Skip to content

Commit e45265e

Browse files
ci(cli-tests): balance the CLI's Test Core slices by declared file weight, not equal file counts (#37073)
<!-- claude-projects-attribution: {"github_login":"huangyiirene"} --> _Requested by **Irene** · [project thread](https://claude.ai/code/project/chan_01TJXtQ1tVD26ecLDZxFS67x?thread=cmsg_01TJXtQ1tVD26ecLDZxFS67x8Be2AAcUBhodBsvnWLd3Xs)_ Part of #36646 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户无感:只改合并队列里核心测试分片如何切分命令行工具的测试文件,产品行为不变。 - 属于合并队列提速:队列最慢的一成里,拖尾的总是同一个测试分片,本改动把它承担的那份测试切得更均匀。 - 出错只会让某个分片多跑或少跑一点时间,每个测试文件仍恰好跑一次(新测试钉住这一点);可直接撤回。 - 要你做的:无(另有一张已全绿的自动生成的分片耗时数据刷新拉取请求待席位合入,详见下方说明)。 ## What changes `@objectstack/cli` is the one package Test Core cuts below package granularity (3 file-level slices, `OS_TEST_SHARD=k/3`). Its vitest sequencer cut vitest's sha1 order into **equal file counts**. This PR cuts it by **weight** instead: `planSlices()` (new `packages/cli/vitest-slices.ts`) seeds the declaration readers into slice 1/n as before, then places every other file heaviest first into the lightest slice, a file weighing the `// test-budget:` its header already declares (seconds / 1.25), or 1.6 s when it declares none. **Why the producer is in `packages/cli`, not `scripts/ci/**`.** The card's expected landing was Test Core's shard planning. The measurements below put the tail inside one shard's CLI slice leg, and which files a CLI slice holds is decided by the CLI's own vitest config (`DeclarationReaderSequencer` in `packages/cli/vitest.config.ts`), not by the planner: the planner only places "cli k/3" as an item at the package's weight / 3. So the fix is at that producer. Files: `packages/cli/vitest-slices.ts` (new, pure), `packages/cli/vitest.config.ts` (the sequencer calls it), `packages/cli/test/vitest-slices.test.ts` (new pin), `packages/cli/tsconfig.test.json` (the new root module named in the test program). No workflow, budget file, partitioner constant or shard count is touched. What does not change: the readers stay in slice 1/n (the partitioner's self-test reads `DECLARATION_READER_SLICE` and the sequencer back, green); the partitioner still weighs each slice at whole / 3; the shard-timings generator decodes slices from the sha256 of `OS_TEST_SHARD`, never from membership. ## The measured tail (before) All readings: `objectstack-ai/objectstack`, green `merge_group` runs of `ci.yml` created 2026-11-21T00:00Z .. 2026-11-24T15:20Z (620 runs; run wall p50 21.6 min, p90 35.1 min). - The 63 slowest (the top decile): the last matrix job to end was **`Test Core (9/10)`** on **47 of 63**; `Test UI` shards 11 (all in runs created 2026-11-22 05:47-05:49Z, where Test UI started 18-23 min into the run), `Test Core (10/10)` 3, `Test Core (3/10)` 1, `Test Core (6/10)` 1. - `Test Core (9/10)` job median: **32.6 min** on the slow decile (n=52), 18.6 min on an evenly spaced 40-run sample of the rest (n=18). It starts ~2.5 min into the run (median start offset of the last-ending job, 2.6 min). - Its two legs, serial, on three slow-decile logs (runs 45342138743, 45213635210, 45032942394): whole-package leg 13m56s / 13m22s / 13m22s, then the **CLI slice 2/3 leg 17m59s / 17m20s / 17m18s**. - The CLI's three slices are equal in files and not in seconds. Per-file vitest durations from the three slice shards of five slow-decile runs, summed per slice: 1171/2347/2164, 1748/2270/1638, 1786/2275/2115, 1589/2253/1418, 1373/2178/1692 s (runs 45342138743, 45213635210, 45032942394, 45116811975, 45383396882). Slice 2 is the heaviest on all five. ## After - **Planner replay (a prediction from measured per-file readings, not a queue reading):** `planSlices()` itself, run over those five runs' per-file readings with this tree's budget lines, puts the heaviest slice at 2014, 2076, 2203, 1928, 1912 s against 2347, 2270, 2275, 2253, 2178 s: **-14.2%, -8.5%, -3.2%, -14.4%, -12.2%**, lower on every run. An even split of the same seconds would be 1894/1885/2059/1753/1748 s; the budgets are ceilings, so the split recovers part of that. - **Queue reading after: NOT MEASURED** — it exists only once queue runs carry this head. The before figure to compare against is the `Test Core (9/10)` median above (32.6 min on the slow decile, 18.6 min on the rest), and the slice leg 17.3-18.0 min. - This PR alone is not shown to bring the p90 under 32 min, hence `Part of`. ## Acceptance notes - **The larger lever is the shard-timings dataset, and it is already a green PR.** `scripts/test-shard-timings.json` was measured 2026-11-02; the weekly refreshes of 11-09 and 11-16 were closed unmerged and the 11-23 one (#36637, generated, 25 checks green, 24 skipped, non-governed) is open. Every slow-decile `Test Core (9/10)` log read carries the planner's own DRIFT warning (2.10x, 2.00x, 2.01x measured vs predicted) naming the refresh as the remedy. Planner prediction, not a reading: replaying the full package list, the slowest shard's modelled tests step (whole / 2.9 + slice) is 1293 s with today's placement and 1127 s with #36637's placement, both on #36637's weights. Landing it is a seat act; this PR does not carry or duplicate its bytes, and the two are independent (this one changes which files a slice holds, that one which packages sit beside it). - Measured candidates that need a decision, reported on the card rather than built here: running the CLI slice leg beside the whole leg instead of after it (a workflow change); a fourth CLI slice (refused by the partitioner's slice-count pin under its ruling); the spec shard (`Test Core (3/10)`, 22.3 min slow-decile median) as the next floor. - The ablation's first attempt stayed green: the first balance pins used heavy files that sort first by path, where path-order greedy also balances. A pin with the heavy file last in path order was added and the second attempt went red as expected. ## Verification Read first: `packages/cli/vitest-slices.ts` (`planSlices`: every file in exactly one slice is the risk), then the `DeclarationReaderSequencer` hunk of `packages/cli/vitest.config.ts`. Two-minute check: `pnpm --filter @objectstack/cli exec vitest run --project unit --maxWorkers=2 test/vitest-slices.test.ts` → 17 tests pass, including the live-population partition at three slices. <details><summary>Tests (head 96c83ea; unit layer at 9b0861a, the only later commit adds one pin to the new test file)</summary> - `pnpm --filter @objectstack/cli exec vitest run --project unit --maxWorkers=2`: Test Files 444 passed (444), Tests 6342 passed (6342), lock VERDICT command-exit 0. The `integration` layer is declared to CI (no spawn entry or integration file in the diff). - `test/vitest-slices.test.ts` at 96c83ea: 17 passed. - `pnpm --filter @objectstack/cli typecheck` (tsc + check:test-typecheck): exit 0 at 96c83ea. - End to end through vitest itself: the unit project run as `OS_TEST_SHARD=1/3`, `2/3`, `3/3` with a test-name filter matching nothing reported 141 / 151 / 152 files, union 444, all distinct, the 5 declaration readers all in slice 1. (Suites failed to import there only because that run had no built dependencies; membership is what was read.) </details> <details><summary>Ablation (committed fix first, restore by HEAD blob)</summary> `node scripts/ablation-replace.mjs` on `packages/cli/vitest-slices.ts`, replacing the heaviest-first sort with path order: mutation landed (anchor 1 → 0, blob 8b98292 → 2f80d72879d2). Attempt 1 (before the new pin): 16/16 green, recorded above as a pin gap. Attempt 2 at 96c83ea: `× places the heaviest file first even when it comes last in path order`, `expected [ 9, 3 ] to deeply equal [ 6, 6 ]`, exit 1. Restore: `git diff HEAD` empty, `git hash-object` equals the HEAD blob, 17/17 green after. </details> <details><summary>Gates</summary> - `node scripts/pm/dispatch-gates.mjs --commands` at 9b0861a: 53 families, all run, each `:: exit 0` (`check:dual-build-cjs-loads` exited 3 on the first pass while the closure rebuild was fresh, 0 on the re-run, recorded as 0); `--ran` reconciliation: "53 derived famil(ies) accounted for — 53 run, 0 NOT-MEASURED (a DERIVED zero)". - Re-run at 96c83ea for the test-file change: check:cross-package-test-inputs, check:test-source-alias, check:tier-file-adoption, check:cli-test-child-env, check:nul-bytes, check:doc-authoring, check:issue-citations, all exit 0. - `node scripts/partition-test-shards.mjs --self-test`: OK (reads the CLI config's reader slice and sequencer back). - No changeset: `packages/cli` publishes `dist`, README and CHANGELOG; built `dist` has zero hits for `planSlices` with a positive control (`SCAFFOLD_PNPM_RANGE` hits `dist/commands/create.d.ts`). </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01J8VVAjMMU8pcMXmiLEMMG4)_ --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: objectstack-fleet[bot] <332303061+objectstack-fleet[bot]@users.noreply.github.com>
1 parent b90dcf4 commit e45265e

4 files changed

Lines changed: 340 additions & 36 deletions

File tree

Lines changed: 176 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,176 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* Pins `planSlices()` and the weight it balances on (`../vitest-slices.ts`),
5+
* which `vitest.config.ts`'s `DeclarationReaderSequencer` uses to cut this
6+
* package's suite into Test Core's file-level slices.
7+
*
8+
* What a wrong slicer costs is silent: a file in no slice never runs and a
9+
* file in two runs twice, and every slice still goes green. So the first
10+
* battery holds the partition itself -- every file in exactly one slice, the
11+
* declaration readers in the reader slice -- on fixtures and on this
12+
* package's live test population; the balance and the weight read come after.
13+
*/
14+
15+
import { readFileSync } from 'node:fs';
16+
import { dirname, resolve } from 'node:path';
17+
import { fileURLToPath } from 'node:url';
18+
import { describe, expect, it } from 'vitest';
19+
import {
20+
BUDGET_HEADROOM,
21+
UNDECLARED_FILE_WEIGHT_SECONDS,
22+
declaredBudgetSeconds,
23+
fileWeight,
24+
planSlices,
25+
type SliceEntry,
26+
} from '../vitest-slices.js';
27+
import { integrationTestFiles, unitTestFiles } from '../vitest-tiers.js';
28+
29+
const PKG = resolve(dirname(fileURLToPath(import.meta.url)), '..');
30+
31+
// The reader list as the config declares it, read from its text: importing
32+
// the config itself would run its load-time checks inside this suite.
33+
const DECLARATION_READER_FILES: readonly string[] = (() => {
34+
const text = readFileSync(resolve(PKG, 'vitest.config.ts'), 'utf8');
35+
const m = /export const DECLARATION_READER_FILES = Object\.freeze\(\[([^\]]*)\]\)/.exec(text);
36+
if (!m) throw new Error('vitest.config.ts: no `export const DECLARATION_READER_FILES = Object.freeze([...])` to read');
37+
return [...m[1].matchAll(/'([^']+)'/g)].map((x) => x[1]);
38+
})();
39+
40+
const entry = (path: string, weight: number, reader = false): SliceEntry => ({ path, weight, reader });
41+
42+
/** Each slice's members, by path, from a plan. */
43+
function members(entries: readonly SliceEntry[], slices: readonly number[], count: number): string[][] {
44+
const out = Array.from({ length: count }, () => [] as string[]);
45+
slices.forEach((s, i) => out[s - 1].push(entries[i].path));
46+
return out;
47+
}
48+
49+
const totals = (entries: readonly SliceEntry[], slices: readonly number[], count: number): number[] => {
50+
const out = new Array<number>(count).fill(0);
51+
slices.forEach((s, i) => (out[s - 1] += entries[i].weight));
52+
return out;
53+
};
54+
55+
describe('planSlices: every file in exactly one slice', () => {
56+
const fixture: SliceEntry[] = [
57+
...Array.from({ length: 40 }, (_, i) => entry(`test/f${String(i).padStart(2, '0')}.test.ts`, (i * 7919) % 97)),
58+
entry('test/reader-a.test.ts', 30, true),
59+
entry('test/reader-b.test.ts', 2, true),
60+
];
61+
62+
for (const count of [1, 2, 3, 4, 7]) {
63+
it(`at ${count} slice(s) the slices are disjoint and their union is the whole set`, () => {
64+
const slices = planSlices(fixture, count, 1);
65+
expect(slices).toHaveLength(fixture.length);
66+
for (const s of slices) expect(s >= 1 && s <= count).toBe(true);
67+
const all = members(fixture, slices, count).flat().sort();
68+
expect(all).toEqual(fixture.map((e) => e.path).sort());
69+
expect(new Set(all).size).toBe(fixture.length);
70+
});
71+
}
72+
73+
it('puts every declaration reader in the reader slice, at any reader slice', () => {
74+
for (const readerSlice of [1, 2, 3]) {
75+
const slices = planSlices(fixture, 3, readerSlice);
76+
fixture.forEach((e, i) => {
77+
if (e.reader) expect(slices[i]).toBe(readerSlice);
78+
});
79+
}
80+
});
81+
82+
it('answers the same plan whatever order the files arrive in, so every slice process agrees', () => {
83+
const plan = (list: readonly SliceEntry[]) => {
84+
const slices = planSlices(list, 3, 1);
85+
return new Map(list.map((e, i) => [e.path, slices[i]]));
86+
};
87+
const forward = plan(fixture);
88+
expect(plan([...fixture].reverse())).toEqual(forward);
89+
expect(plan([...fixture].sort((a, b) => (a.path < b.path ? 1 : -1)))).toEqual(forward);
90+
});
91+
92+
it("holds on this package's live queue population at the configured three slices", () => {
93+
const integration = integrationTestFiles(PKG);
94+
const files = [...unitTestFiles(PKG, integration), ...integration];
95+
const readers = new Set<string>(DECLARATION_READER_FILES);
96+
const live = files.map((f) => entry(f, fileWeight(readFileSync(resolve(PKG, f), 'utf8')), readers.has(f)));
97+
expect(live.length).toBeGreaterThan(100);
98+
expect(live.filter((e) => e.reader)).toHaveLength(DECLARATION_READER_FILES.length);
99+
const slices = planSlices(live, 3, 1);
100+
const sets = members(live, slices, 3);
101+
expect(sets.flat().sort()).toEqual(files.slice().sort());
102+
for (const set of sets) expect(set.length).toBeGreaterThan(0);
103+
for (const r of DECLARATION_READER_FILES) expect(sets[0]).toContain(r);
104+
});
105+
106+
it('refuses a slice count, reader slice or weight it cannot plan with', () => {
107+
expect(() => planSlices(fixture, 0, 1)).toThrow(/slice count 0/);
108+
expect(() => planSlices(fixture, 3, 4)).toThrow(/reader slice 4/);
109+
expect(() => planSlices([entry('test/x.test.ts', Number.NaN)], 2, 1)).toThrow(/test\/x\.test\.ts weighs NaN/);
110+
});
111+
});
112+
113+
describe('planSlices: balance by weight, not by file count', () => {
114+
it('spreads the heavy files that an equal-count cut would put in one slice', () => {
115+
// Six heavy files first in path order, then sixty light ones: cut into
116+
// three equal counts, the first slice would hold all six.
117+
const heavy = Array.from({ length: 6 }, (_, i) => entry(`test/a${i}.test.ts`, 300));
118+
const light = Array.from({ length: 60 }, (_, i) => entry(`test/z${String(i).padStart(2, '0')}.test.ts`, 2));
119+
const list = [...heavy, ...light];
120+
const slices = planSlices(list, 3, 1);
121+
const t = totals(list, slices, 3);
122+
expect(Math.max(...t) - Math.min(...t)).toBeLessThanOrEqual(2);
123+
for (let s = 1; s <= 3; s++) expect(heavy.filter((_, i) => slices[i] === s)).toHaveLength(2);
124+
});
125+
126+
it('places the heaviest file first even when it comes last in path order', () => {
127+
// Placed in path order, six 1 s files would split 3/3 and the 6 s file
128+
// would land on top of one half (9 against 3); placed heaviest first, it
129+
// takes a slice and the six fill the other (6 against 6).
130+
const list = [...Array.from({ length: 6 }, (_, i) => entry(`test/a${i}.test.ts`, 1)), entry('test/z.test.ts', 6)];
131+
const slices = planSlices(list, 2, 1);
132+
expect(totals(list, slices, 2)).toEqual([6, 6]);
133+
});
134+
135+
it('keeps every slice within one file of the mean when no single file dominates (LPT bound)', () => {
136+
const list = Array.from({ length: 200 }, (_, i) => entry(`test/f${i}.test.ts`, 1 + ((i * 31) % 50)));
137+
const slices = planSlices(list, 3, 1);
138+
const t = totals(list, slices, 3);
139+
const mean = t.reduce((a, b) => a + b, 0) / 3;
140+
const heaviest = Math.max(...list.map((e) => e.weight));
141+
expect(Math.max(...t)).toBeLessThanOrEqual(mean + heaviest);
142+
});
143+
144+
it("counts the readers' weight against the reader slice before placing the rest", () => {
145+
const list = [entry('test/r.test.ts', 100, true), entry('test/a.test.ts', 60), entry('test/b.test.ts', 60)];
146+
expect(planSlices(list, 2, 1)).toEqual([1, 2, 2]);
147+
});
148+
});
149+
150+
describe("fileWeight: the budget a file's header declares", () => {
151+
const budget = '// test-budget: 450 — spawns the real producer once per single-cause fixture: one spawn per case';
152+
153+
it('weighs a declared file at its budget over the headroom it was rounded up with', () => {
154+
const text = `// Copyright (c) 2026 ObjectStack.\n\n${budget}\n\nimport { it } from 'vitest';\n`;
155+
expect(declaredBudgetSeconds(text)).toBe(450);
156+
expect(fileWeight(text)).toBe(450 / BUDGET_HEADROOM);
157+
});
158+
159+
it('reads the header through block comments and a shebang', () => {
160+
expect(declaredBudgetSeconds(`#!/usr/bin/env node\n/**\n * header\n */\n${budget}\nconst x = 1;\n`)).toBe(450);
161+
});
162+
163+
it('weighs a file with no declaration, or one below the header, as undeclared', () => {
164+
expect(fileWeight("import { it } from 'vitest';\n")).toBe(UNDECLARED_FILE_WEIGHT_SECONDS);
165+
expect(declaredBudgetSeconds(`// header\nimport { it } from 'vitest';\n${budget}\n`)).toBeNull();
166+
expect(declaredBudgetSeconds('// test-budget: abc — x: y\n')).toBeNull();
167+
});
168+
169+
it('reads a real declaration from this package as the generator would', () => {
170+
const file = 'src/commands/migrate/data-commands.absent-database.integration.test.ts';
171+
const text = readFileSync(resolve(PKG, file), 'utf8');
172+
const seconds = declaredBudgetSeconds(text);
173+
expect(seconds).not.toBeNull();
174+
expect(text).toContain(`// test-budget: ${seconds} — `);
175+
});
176+
});

‎packages/cli/tsconfig.test.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,7 @@
179179
"include": [
180180
"test/**/*",
181181
"vitest.config.ts",
182+
"vitest-slices.ts",
182183
"vitest-tiers.ts",
183184
"vitest-tiers.fixtures.ts"
184185
],

‎packages/cli/vitest-slices.ts‎

Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* Which of this package's test files run in which file-level slice, when
5+
* Test Core cuts the suite into `OS_TEST_SHARD=k/n` slices
6+
* (`FILE_SHARDED_PACKAGES` in `scripts/partition-test-shards.mjs`).
7+
*
8+
* `vitest.config.ts`'s `DeclarationReaderSequencer` calls `planSlices()` from
9+
* its `shard()`; `test/vitest-slices.test.ts` pins it. Pure, so the pin needs
10+
* no vitest context.
11+
*
12+
* ## Why the slices are balanced by weight, not cut into equal file counts
13+
*
14+
* The sequencer used to cut vitest's own sha1 order into equal-COUNT ranges.
15+
* A slice runs as its shard's serial leg after the whole-package leg, so the
16+
* heaviest slice sets that shard's wall, and on full merge_group runs that
17+
* shard is the job that ends the queue entry: `Test Core (9/10)`, the shard
18+
* carrying slice 2/3, ended last on 47 of the 63 slowest-decile green
19+
* merge_group runs of 2026-11-21..24, its job at a 32.6-minute median there,
20+
* 13.4-13.9 min whole leg plus 17.3-18.0 min of CLI slice on the three logs
21+
* read. Equal counts are not equal seconds: on five such runs' per-file
22+
* readings (45342138743, 45213635210, 45032942394, 45116811975, 45383396882)
23+
* the three slices summed 1171/2347/2164, 1748/2270/1638, 1786/2275/2115,
24+
* 1589/2253/1418 and 1373/2178/1692 seconds of file time -- the same files,
25+
* slice 2 the heaviest on all five, because a handful of files carry most of
26+
* the suite (one reads 532 s, the top 25 about half of it) and sha1 put more
27+
* of them into slice 2.
28+
*
29+
* ## The weight: the budget a heavy file already declares
30+
*
31+
* Every test file over the 10 s line declares its own budget in its header
32+
* (`// test-budget: SECONDS — CLASS: REASON`, ruling records 6181973363 and
33+
* 6212133431; `readTestBudget()` in `scripts/measure-test-shard-timings.mjs`
34+
* owns the grammar and refuses a malformed one). SECONDS is the measured CI
35+
* reading x 1.25, rounded up, so a file weighs SECONDS / BUDGET_HEADROOM, and
36+
* a file that declares none weighs UNDECLARED_FILE_WEIGHT_SECONDS. Over the
37+
* five runs, 103 files declared a budget and carried 4812 of 5683 seconds on
38+
* the first; the files without one averaged 1.53-1.74 s (median 0.11-0.12 s).
39+
*
40+
* Replayed on those five runs' readings, placing the files heaviest first into
41+
* the lightest slice (readers seeded into theirs first) moves the heaviest
42+
* slice's file time 2347 -> 2014, 2270 -> 2076, 2275 -> 2203, 2253 -> 1928 and
43+
* 2178 -> 1912 seconds: lower on every run, by 3.2-14.4%. A perfect split of the
44+
* same seconds would read 1894, 1885, 2059, 1753 and 1748 -- the budgets are
45+
* ceilings, not readings, so the split recovers part of that, never all.
46+
*
47+
* No table and no second artefact: the weight is read from the file the
48+
* slice runs, so nothing here can go stale apart from the files themselves.
49+
* This module reads only the number, leniently: a header line it cannot read
50+
* weighs as undeclared, which can cost balance and never decides WHETHER a file
51+
* runs. Every file lands in exactly one slice whatever the weights say.
52+
*
53+
* ## What does not change
54+
*
55+
* - The declaration readers (`DECLARATION_READER_FILES`) all run in the
56+
* reader slice, and only there (#25870): they are seeded into it before
57+
* anything is placed, so ci.yml keeps declarations for that slice alone.
58+
* - The split is deterministic. Every slice's own vitest process computes
59+
* the whole plan from the same file set and the same file text, and keeps
60+
* its own part; ties go to the lower path, then to the lower slice.
61+
* - The partitioner still places each slice at the package's plain weight
62+
* / n, and the shard-timings generator still decodes a slice from the
63+
* sha256 of its `OS_TEST_SHARD` value: neither reads which files a slice
64+
* holds.
65+
*/
66+
67+
/** A declared budget is the measured CI reading x this, rounded up (`CEILING_HEADROOM`). */
68+
export const BUDGET_HEADROOM = 1.25;
69+
70+
/**
71+
* What a file that declares no budget weighs: the mean file time of the
72+
* files without one, 1.53, 1.58 and 1.74 s on merge_group runs 45342138743,
73+
* 45213635210 and 45032942394.
74+
*/
75+
export const UNDECLARED_FILE_WEIGHT_SECONDS = 1.6;
76+
77+
const BUDGET_SECONDS = /^\/\/ test-budget: ([1-9]\d*) — /u;
78+
79+
/**
80+
* The declared budget's SECONDS, read from the file's header -- its leading
81+
* run of blank lines, `//` lines and block comments, up to the first line of
82+
* code -- or null when the header declares none this can read.
83+
*/
84+
export function declaredBudgetSeconds(text: string): number | null {
85+
let inBlock = false;
86+
const lines = text.split(/\r?\n/);
87+
for (let i = 0; i < lines.length; i++) {
88+
const t = lines[i].trim();
89+
if (inBlock) {
90+
inBlock = !t.includes('*/');
91+
continue;
92+
}
93+
if (t.startsWith('/*')) {
94+
inBlock = !t.slice(2).includes('*/');
95+
continue;
96+
}
97+
if (t === '' || (i === 0 && t.startsWith('#!'))) continue;
98+
if (!t.startsWith('//')) return null;
99+
const m = BUDGET_SECONDS.exec(lines[i]);
100+
if (m) return Number(m[1]);
101+
}
102+
return null;
103+
}
104+
105+
/** What one test file weighs when the slices are balanced. */
106+
export function fileWeight(text: string): number {
107+
const seconds = declaredBudgetSeconds(text);
108+
return seconds === null ? UNDECLARED_FILE_WEIGHT_SECONDS : seconds / BUDGET_HEADROOM;
109+
}
110+
111+
export interface SliceEntry {
112+
/** The file's path below the package root, `/`-separated: the tie-break. */
113+
readonly path: string;
114+
readonly weight: number;
115+
/** A declaration reader: placed in the reader slice, whatever it weighs. */
116+
readonly reader: boolean;
117+
}
118+
119+
/**
120+
* The slice (1-based) of every entry, in input order, for `count` slices.
121+
* Readers go into `readerSlice` first; every other entry is then placed
122+
* heaviest first into the slice with the least weight so far.
123+
*/
124+
export function planSlices(entries: readonly SliceEntry[], count: number, readerSlice: number): number[] {
125+
if (!Number.isInteger(count) || count < 1) throw new Error(`planSlices: slice count ${count} is not a positive integer`);
126+
if (!Number.isInteger(readerSlice) || readerSlice < 1 || readerSlice > count) {
127+
throw new Error(`planSlices: reader slice ${readerSlice} is not one of the ${count} slice(s)`);
128+
}
129+
for (const e of entries) {
130+
if (!Number.isFinite(e.weight) || e.weight < 0) throw new Error(`planSlices: ${e.path} weighs ${e.weight}`);
131+
}
132+
const totals = new Array<number>(count).fill(0);
133+
const slices = new Array<number>(entries.length).fill(0);
134+
const byPath = (a: number, b: number) => (entries[a].path < entries[b].path ? -1 : entries[a].path > entries[b].path ? 1 : a - b);
135+
const order = entries.map((_, i) => i);
136+
for (const i of order.filter((i) => entries[i].reader).sort(byPath)) {
137+
slices[i] = readerSlice;
138+
totals[readerSlice - 1] += entries[i].weight;
139+
}
140+
const rest = order.filter((i) => !entries[i].reader).sort((a, b) => entries[b].weight - entries[a].weight || byPath(a, b));
141+
for (const i of rest) {
142+
let lightest = 0;
143+
for (let s = 1; s < count; s++) if (totals[s] < totals[lightest]) lightest = s;
144+
slices[i] = lightest + 1;
145+
totals[lightest] += entries[i].weight;
146+
}
147+
return slices;
148+
}

0 commit comments

Comments
 (0)