Public: anyone can read this; the crew can change it.

Every test fast: a budget per test and per file enforced by the gate, the full suite under five minutes #1269

Closed opened this in answer to
Closed without merging

torque/forge:torque/1242-every-test-fast-a-budget-per-test-and-pe → main 6 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
15 files changed +3171 −124
CLAUDE.md +10
@@ -86,6 +86,16 @@ bun run src/main.ts # boots on :3000, data in ./data
8686 It runs the files in `GATE` (`scripts/gate.ts`), not the whole suite; every
8787 other test file is in `EXCLUDED` with its reason and owning issue. Add a new
8888 test file to `GATE`, or the check goes red.
89 - **Every test is fast: 1 s a test, 10 s a file, or the gate is red**
90 (`scripts/budget.ts`, #1242). One forge and one server per file in
91 `beforeAll`, a fake clock instead of `Bun.sleep`, in-memory SQLite unless
92 the disk is the point, fixtures built once per file. `SLOW` in
93 `scripts/gate.ts` lets a file off only with an issue that owns it and a
94 reason (what it measured);
95 slow-by-nature files go in `NIGHTLY`. `scripts/test-times.json` says
96 where the time goes, per file and per test. Short files share one
97 `bun test --isolate` a few at a time, so a test file must not depend on
98 being alone in its process.
8999 - **Every non-trivial change ships with a test.** Prefer protocol-level tests
90100 that boot a real app (`createApp` + `serve`) over unit mocks. Adversarial
91101 tests (can this be bypassed?) are worth more than happy-path ones.
README.md +43
@@ -421,6 +421,49 @@ bun run check:record # the gate's own command, with test-shards.ts --record
421421 once as the gate runs shards. It rewrites the table only when every file
422422 is green. Files it did not run keep their old times.
423423
424 **Every test is fast, and the gate holds it to that** (#1242). Under
425 `--gate` each long file is its own `bun test`, timed from spawn to exit.
426 Files the table expects under 5 s share a process instead, at most 8 files
427 and 20 expected seconds to a group (`groupFiles` in `scripts/shards.ts`).
428 On the gate box most of a short file's time was the bun start, and a group
429 pays that once. The group runs as `bun test --isolate`, so each file gets
430 fresh globals and leaked handles, and nothing one file sets is seen by the
431 next. A preload (`scripts/file-clock.ts`) notes when each file starts, so
432 each grouped file is still timed, module load and hooks included. Each
433 process's peak RSS is on its log line. Eight short files in one process
434 peaked at about what the largest one took alone, so a group stays within
435 one suite's memory, which the Actions runner needs. A JUnit report (bun's
436 own, to a temporary file) times each test. No test
437 may take more than **1 s** and no file more than **10 s**
438 (`scripts/budget.ts`). A file or test over budget turns the run red like a
439 failing assertion. The red log names every one at once and ends with a
440 `SLOW` entry ready to paste. `SLOW` in `scripts/gate.ts` is the short list
441 of gate files let off the budget today, each with the issue that rewrites
442 it; it only shrinks, and a run that finds a `SLOW` file under budget says
443 so. Files slow by nature (a browser, a restore drill, a push storm) go in
444 `NIGHTLY` instead, which `bun scripts/test-shards.ts --nightly` runs and
445 the gate does not.
446
447 Every gate run whose tests all pass rewrites `scripts/test-times.json`:
448 `total` (the run's wall clock, the number the suite's target is held to),
449 `files` (seconds per file) and `tests` (`file > describe > test` to
450 seconds). The log's last lines name the five slowest tests and each one's
451 share of the run, and a passed check's summary repeats them:
452 `check passed in 290s; slowest: crew › boots a forge 0.9s 0%; …`.
453
454 The fast tier (`--tier fast`) is a slice of the gate and is held to the
455 same budget. Its files' times go into the table too, but only a whole,
456 unsliced full gate sets `total` (`budgetFor` in `scripts/budget.ts`).
457
458 Bun's own test flags were checked against the Bun this forge runs (1.3.14,
459 `bun test --help`). `--parallel` and `--shard` exist there, but
460 `--timings` / `--update-timings` do not, so shards are still weighed from
461 our own `scripts/test-times.json`. The gate runs one `bun test` per long
462 file and one per group of short ones, one after another, rather than
463 `--parallel` workers: the gate lane has one slot, and the Actions runner
464 ran out of memory holding more than one suite at a time. The nightly flake hunt (`--randomize --seed`, `--rerun-each`) is
465 #1243, and the per-file coverage impact map is #1279.
466
424467 Every file is independent (its own forge, its own database, port 0), so a test that fails only beside another is a bug
425468 in that test. Two things it will not do:
426469
scripts/budget.ts added +319
@@ -0,0 +1,319 @@
1 /**
2 * The gate's time budget: how long one test and one test file may take,
3 * and what a run says when one took longer.
4 *
5 * Plain data in, plain data out. `scripts/test-shards.ts --gate` times every
6 * long file as its own `bun test` (spawn to exit), every short file in its
7 * group from `scripts/file-clock.ts`'s lines, and every test from the
8 * process's JUnit report; this module reads both, compares them
9 * against the budget, and writes the lines the log ends with. A file named
10 * in `SLOW` (`scripts/gate.ts`) is let off both budgets, with the issue
11 * that owns bringing it under; anything else over budget is red, the same
12 * as a failing assertion.
13 */
14
15 /** No single test longer than this, in seconds, on the gate box (#1242). */
16 export const TEST_BUDGET = 1;
17
18 /** No test file longer than this, in seconds, spawn to exit (#1242). */
19 export const FILE_BUDGET = 10;
20
21 /** What a run of `scripts/test-shards.ts` was asked to do. */
22 export interface RunMode {
23 /** `--gate`: the files `scripts/gate.ts` admits. */
24 readonly gate: boolean;
25 /** `--tier`: `fast` is the slice of the gate a diff touches (#1198). */
26 readonly tier: "fast" | "full";
27 /** `--shard N/M` or its env: one slice of the list, not all of it. */
28 readonly sliced: boolean;
29 }
30
31 /**
32 * Whether a run is held to the budget, and whether its wall clock is the
33 * suite's total in `scripts/test-times.json`. The fast tier is a slice of
34 * the gate, so it keeps the gate's budget and records its files' times;
35 * only a whole full gate is the suite, so only it sets the total.
36 */
37 export function budgetFor(mode: RunMode): {
38 budgeted: boolean;
39 setsTotal: boolean;
40 } {
41 const budgeted = mode.gate || mode.tier === "fast";
42 return {
43 budgeted,
44 setsTotal: mode.gate && mode.tier === "full" && !mode.sliced,
45 };
46 }
47
48 /** One test as its file's JUnit report names it: `describe > test`. */
49 export interface TestTime {
50 readonly file: string;
51 readonly name: string;
52 readonly seconds: number;
53 }
54
55 // Tag by tag, attribute by attribute, never "up to the next `>`": a test
56 // may be named `a > b`, and bun leaves `>` unescaped inside a quoted value.
57 const TAG = /<(\/?)(testsuite|testcase)((?:\s+[a-z]+="[^"]*")*)\s*(\/?)>/g;
58 const ATTR = /\s([a-z]+)="([^"]*)"/g;
59 const ENTITY = /&(lt|gt|quot|apos|amp|#(\d{1,7})|#x([0-9a-f]{1,6}));/gi;
60 const NAMED: Record<string, string> = {
61 lt: "<",
62 gt: ">",
63 quot: '"',
64 apos: "'",
65 amp: "&",
66 };
67
68 function unescapeXml(text: string): string {
69 return text.replace(
70 ENTITY,
71 (_, name: string, dec?: string, hex?: string) =>
72 dec !== undefined
73 ? String.fromCodePoint(Math.min(Number(dec), 0x10ffff))
74 : hex !== undefined
75 ? String.fromCodePoint(Math.min(parseInt(hex, 16), 0x10ffff))
76 : (NAMED[name.toLowerCase()] ?? ""),
77 );
78 }
79
80 function attributes(text: string): Map<string, string> {
81 const attrs = new Map<string, string>();
82 for (const attr of text.matchAll(ATTR))
83 attrs.set(attr[1]!, unescapeXml(attr[2]!));
84 return attrs;
85 }
86
87 /**
88 * Every `<testcase>` in a `bun test --reporter=junit` report, as `file`'s
89 * tests. The name is every enclosing `describe` (a nested `<testsuite>`
90 * below the file's own) and the test's own, joined by ` > ` the way bun's
91 * console names them. A time that is not a finite, non-negative number is
92 * read as zero, so a garbled report can only under-count, never invent a
93 * slow test.
94 */
95 export function parseJunit(xml: string, file: string): TestTime[] {
96 return parseJunitFiles(xml, [file]);
97 }
98
99 /**
100 * {@link parseJunit} over a report of several files run in one process:
101 * each outermost `<testsuite>` is a file, named as `bun test` was given it
102 * (`./test/a.test.ts` is `test/a.test.ts`), and its tests are that file's.
103 * A suite naming none of `files` is skipped; with one file, every test is
104 * that file's whatever the suite is named.
105 */
106 export function parseJunitFiles(
107 xml: string,
108 files: readonly string[],
109 ): TestTime[] {
110 const bare = (name: string): string =>
111 name.startsWith("./") ? name.slice(2) : name;
112 const known = new Map(files.map((file) => [bare(file), file]));
113 const fileOf = (suite: string): string | undefined =>
114 files.length === 1 ? files[0] : known.get(bare(suite));
115 const tests: TestTime[] = [];
116 const suites: string[] = [];
117 for (const match of xml.matchAll(TAG)) {
118 const [, closing, tag, attrText, selfClosing] = match;
119 if (tag === "testsuite") {
120 if (closing === "/") suites.pop();
121 else if (selfClosing !== "/")
122 suites.push(attributes(attrText!).get("name") ?? "");
123 continue;
124 }
125 if (closing === "/") continue;
126 const attrs = attributes(attrText!);
127 // The outer `<testsuites>` is not matched; the first `<testsuite>` is
128 // the file itself, the rest are its describes.
129 const file = fileOf(suites[0] ?? "");
130 if (file === undefined) continue;
131 const path = [...suites.slice(1), attrs.get("name") ?? ""];
132 const seconds = Number(attrs.get("time"));
133 tests.push({
134 file,
135 name: path.join(" > "),
136 seconds: Number.isFinite(seconds) && seconds >= 0 ? seconds : 0,
137 });
138 }
139 return tests;
140 }
141
142 const CLOCK = /^start (\d{1,15}) (.+)$/;
143
144 /**
145 * Each file's time in a group, from `scripts/file-clock.ts`'s lines
146 * (`start <epoch ms> <absolute path>`, one per file as `bun test --isolate`
147 * begins it): from its start to the next file's, the last one's to `exitMs`
148 * when the process ended. A JUnit report cannot say this: it times each
149 * test's body, never the file's module load or hooks, and every file's
150 * own `<testsuite>` time is 0. `root` turns `files` into the absolute paths
151 * the lines name; a line naming none of them is ignored, and a file named
152 * twice keeps its first start. The process's own start is no file's: the
153 * group pays it once.
154 */
155 export function fileClock(
156 text: string,
157 files: readonly string[],
158 root: string,
159 exitMs: number,
160 ): Map<string, number> {
161 const absolute = new Map(
162 files.map((file) => [
163 file.startsWith("/")
164 ? file
165 : `${root.replace(/\/+$/, "")}/${file.replace(/^\.\//, "")}`,
166 file,
167 ]),
168 );
169 const starts: { file: string; at: number }[] = [];
170 const seen = new Set<string>();
171 for (const line of text.split("\n")) {
172 const match = CLOCK.exec(line);
173 const file = match ? absolute.get(match[2]!) : undefined;
174 if (file === undefined || seen.has(file)) continue;
175 seen.add(file);
176 starts.push({ file, at: Number(match![1]) });
177 }
178 starts.sort((a, b) => a.at - b.at);
179 const times = new Map<string, number>();
180 starts.forEach(({ file, at }, i) => {
181 const end = starts[i + 1]?.at ?? exitMs;
182 times.set(file, Math.max(0, end - at) / 1000);
183 });
184 return times;
185 }
186
187 /** What one gate run measured: each file spawn to exit, each test alone. */
188 export interface Measured {
189 readonly files: ReadonlyMap<string, number>;
190 readonly tests: readonly TestTime[];
191 }
192
193 /**
194 * One line per file or test over budget, none when the run kept to it.
195 * `slow` is the files `SLOW` lets off; a file in it is never named.
196 */
197 export function overBudget(
198 measured: Measured,
199 slow: ReadonlySet<string>,
200 ): string[] {
201 const lines: string[] = [];
202 for (const [file, seconds] of measured.files)
203 if (!slow.has(file) && seconds > FILE_BUDGET)
204 lines.push(
205 `over budget: ${file} took ${seconds.toFixed(1)}s (a file may take ${FILE_BUDGET}s)`,
206 );
207 for (const test of measured.tests)
208 if (!slow.has(test.file) && test.seconds > TEST_BUDGET)
209 lines.push(
210 `over budget: ${test.file} > ${test.name} took ${test.seconds.toFixed(2)}s (a test may take ${TEST_BUDGET}s)`,
211 );
212 return lines;
213 }
214
215 /** The distinct files `overBudget` named, in the order it named them. */
216 export function filesOverBudget(
217 measured: Measured,
218 slow: ReadonlySet<string>,
219 ): string[] {
220 const files = new Set<string>();
221 for (const [file, seconds] of measured.files)
222 if (!slow.has(file) && seconds > FILE_BUDGET) files.add(file);
223 for (const test of measured.tests)
224 if (!slow.has(test.file) && test.seconds > TEST_BUDGET) files.add(test.file);
225 return [...files];
226 }
227
228 /**
229 * `SLOW` entries this run found under budget: the file and every test in
230 * it kept to the budget, so its entry can go. Said, not red — one fast
231 * run is a hint, and the entry's issue is closed by a person.
232 */
233 export function slowNoLonger(
234 measured: Measured,
235 slow: ReadonlySet<string>,
236 ): string[] {
237 const over = new Set<string>();
238 for (const test of measured.tests)
239 if (test.seconds > TEST_BUDGET) over.add(test.file);
240 return [...slow].filter((file) => {
241 const seconds = measured.files.get(file);
242 return seconds !== undefined && seconds <= FILE_BUDGET && !over.has(file);
243 });
244 }
245
246 /** `test/crew-loop.test.ts` is `crew-loop` on a one-line summary. */
247 function shortFile(file: string): string {
248 return file.replace(/^(\.\/)?test\//, "").replace(/\.test\.[cm]?[jt]sx?$/, "");
249 }
250
251 /** How much of a test's name a one-line summary keeps. */
252 const NAME_MAX = 24;
253
254 /**
255 * The five slowest tests and each one's share of the run's wall clock, as
256 * one line — `Slowest tests: crew › boots a forge 12.3s 4%; …` — or
257 * undefined when the run timed none. Ties break on file then name, so the
258 * same times always give the same line.
259 */
260 export function slowestLine(
261 tests: readonly TestTime[],
262 runSeconds: number,
263 count = 5,
264 ): string | undefined {
265 const top = [...tests]
266 .sort(
267 (a, b) =>
268 b.seconds - a.seconds ||
269 (a.file < b.file ? -1 : a.file > b.file ? 1 : 0) ||
270 (a.name < b.name ? -1 : a.name > b.name ? 1 : 0),
271 )
272 .slice(0, count);
273 if (top.length === 0) return undefined;
274 const parts = top.map((test) => {
275 const name =
276 test.name.length > NAME_MAX
277 ? `${test.name.slice(0, NAME_MAX - 1)}…`
278 : test.name;
279 const share =
280 runSeconds > 0 ? Math.round((test.seconds / runSeconds) * 100) : 0;
281 return `${shortFile(test.file)} › ${name} ${test.seconds.toFixed(1)}s ${share}%`;
282 });
283 return `Slowest tests: ${parts.join("; ")}`;
284 }
285
286 /**
287 * The gate's verdict on a green run's times: exit 1 and what to do when a
288 * file or test outside `slow` went over budget, every one named so one
289 * red run is the whole list; exit 0 otherwise. Either way, a `SLOW` file
290 * that kept to the budget is said, so its entry can go. The last line is
291 * the one a red check's summary shows.
292 */
293 export function judge(
294 measured: Measured,
295 slow: ReadonlySet<string>,
296 ): { code: 0 | 1; lines: string[] } {
297 const lines = slowNoLonger(measured, slow).map(
298 (file) => `test-shards: ${file} kept to the budget this run; its SLOW entry can go`,
299 );
300 const over = overBudget(measured, slow);
301 if (over.length === 0) return { code: 0, lines };
302 const named = filesOverBudget(measured, slow);
303 return {
304 code: 1,
305 lines: [
306 ...lines,
307 "",
308 ...over,
309 "",
310 "Make each one fast, or (with an issue that owns it) let its file off in SLOW in scripts/gate.ts:",
311 ...named.map(
312 (file) =>
313 ` { file: ${JSON.stringify(file)}, issue: 0, reason: "what it measured" },`,
314 ),
315 "",
316 `${named.length} test file${named.length === 1 ? "" : "s"} over the time budget (${TEST_BUDGET}s a test, ${FILE_BUDGET}s a file); the gate is red.`,
317 ],
318 };
319 }
scripts/file-clock.ts added +13
@@ -0,0 +1,13 @@
1 /**
2 * Preloaded into a group of test files run as one `bun test --isolate`
3 * (`scripts/test-shards.ts`): `--isolate` evaluates the preload again for
4 * each file, before the file's own modules load, so one line per file —
5 * `start <epoch ms> <absolute path>` — appended to `FORGE_TEST_CLOCK` says
6 * when each began. `fileClock` in `scripts/budget.ts` turns the lines into
7 * each file's time. Without `FORGE_TEST_CLOCK` it does nothing.
8 */
9
10 import { appendFileSync } from "node:fs";
11
12 const out = process.env["FORGE_TEST_CLOCK"];
13 if (out) appendFileSync(out, `start ${Date.now()} ${Bun.main}\n`);
scripts/gate.ts +277 −13
@@ -10,6 +10,12 @@
1010 *
1111 * A file joins the gate by moving from `EXCLUDED` to `GATE` in a pull whose
1212 * check is green.
13 *
14 * The gate also holds every file to a time budget (`scripts/budget.ts`: a
15 * test 1 s, a file 10 s, on the gate box). `SLOW` names the gate files let
16 * off it, each with the issue that owns bringing it under; `NIGHTLY` is
17 * the files slow by nature (a restore drill, a browser, a push storm),
18 * run by the nightly lane and not by the gate.
1319 */
1420
1521 export type Exclusion = {
@@ -21,8 +27,19 @@ export type Exclusion = {
2127 issue: number;
2228 };
2329
30 /** A gate file let off the time budget, and the issue that owns it. */
31 export type Slow = {
32 /** Repository-relative path, `test/….test.ts`; must be in `GATE`. */
33 file: string;
34 /** The issue that owns bringing it under the budget. */
35 issue: number;
36 /** One line: what it measured, or why it is slow. */
37 reason: string;
38 };
39
2440 export const GATE: readonly string[] = [
2541 "test/accounts.test.ts",
42 "test/budget.test.ts",
2643 "test/agents.test.ts",
2744 "test/app-domains.test.ts",
2845 "test/app.test.ts",
@@ -125,6 +142,7 @@ export const GATE: readonly string[] = [
125142 "test/asks-rank.test.ts",
126143 "test/plan-pillars.test.ts",
127144 "test/planner-declined.test.ts",
145 "test/plan-route.test.ts",
128146 "test/feed.test.ts",
129147 "test/feed-page.test.ts",
130148 "test/offline.test.ts",
@@ -233,6 +251,227 @@ export const GATE: readonly string[] = [
233251 "test/web-origins.test.ts",
234252 ];
235253
254 /**
255 * Over the budget today, each with the issue that rewrites it (#1242) and
256 * what it measured: alone, spawn to exit, on the gate box (the fast check
257 * run 01m4v94pk641ne5hzw5cntvwr1) where that run reached it, else the last
258 * recording. Short, and shrinking: an entry goes in the pull that brings
259 * its file under, and a new one needs its own issue.
260 */
261 export const SLOW: readonly Slow[] = [
262 {
263 file: "test/studio.test.ts",
264 issue: 1286,
265 reason: "70.6 s on the gate box; 5 tests over 1 s, the slowest 2.0 s",
266 },
267 {
268 file: "test/apps.test.ts",
269 issue: 1287,
270 reason: "91.1 s on the gate box; 15 tests over 1 s, the slowest 18.2 s",
271 },
272 {
273 file: "test/apps-adversarial.test.ts",
274 issue: 1247,
275 reason: "43.9 s on the gate box; 10 tests over 1 s, the slowest 8.6 s",
276 },
277 {
278 file: "test/crew.test.ts",
279 issue: 1288,
280 reason: "66.4 s on the gate box; 8 tests over 1 s, the slowest 14.5 s",
281 },
282 {
283 file: "test/fork-flow.test.ts",
284 issue: 1289,
285 reason: "25.7 s on the gate box; 3 tests over 1 s, the slowest 1.9 s",
286 },
287 {
288 file: "test/apps-busy.test.ts",
289 issue: 1252,
290 reason: "18.2 s on the gate box; 4 tests over 1 s, the slowest 5.1 s",
291 },
292 {
293 file: "test/checks.test.ts",
294 issue: 1253,
295 reason: "14.2 s on the gate box; 3 tests over 1 s, the slowest 4.2 s",
296 },
297 {
298 file: "test/crew-wrapup.test.ts",
299 issue: 1254,
300 reason: "17.9 s on the gate box; 3 tests over 1 s, the slowest 6.4 s",
301 },
302 {
303 file: "test/apps-token.test.ts",
304 issue: 1255,
305 reason: "12.9 s on the gate box; 2 tests over 1 s, the slowest 1.3 s",
306 },
307 {
308 file: "test/web-apps.test.ts",
309 issue: 1256,
310 reason: "6.4 s on the gate box; 1 test over 1 s, the slowest 1.6 s",
311 },
312 {
313 file: "test/usage.test.ts",
314 issue: 1258,
315 reason: "12.1 s on the gate box; 1 test over 1 s, the slowest 10.2 s",
316 },
317 {
318 file: "test/steer.test.ts",
319 issue: 1261,
320 reason: "10.0 s on the gate box; 1 test over 1 s, the slowest 8.9 s",
321 },
322 {
323 file: "test/web.test.ts",
324 issue: 1262,
325 reason: "12.3 s on the gate box; 1 test over 1 s, the slowest 1.4 s",
326 },
327 {
328 file: "test/pulls.test.ts",
329 issue: 1263,
330 reason: "4.8 s on the gate box; 1 test over 1 s, the slowest 1.2 s",
331 },
332 {
333 file: "test/cross-repo-pull.test.ts",
334 issue: 1264,
335 reason: "7.5 s on the gate box; 1 test over 1 s, the slowest 1.4 s",
336 },
337 {
338 file: "test/spawn.test.ts",
339 issue: 1266,
340 reason: "11.1 s in the last recording",
341 },
342 {
343 file: "test/agents.test.ts",
344 issue: 1324,
345 reason: "27.4 s on the gate box; 2 tests over 1 s, the slowest 10.2 s",
346 },
347 {
348 file: "test/crew-direction.test.ts",
349 issue: 1325,
350 reason: "21.6 s on the gate box; 3 tests over 1 s, the slowest 9.5 s",
351 },
352 {
353 file: "test/capacity.test.ts",
354 issue: 1326,
355 reason: "15.9 s on the gate box; 2 tests over 1 s, the slowest 7.8 s",
356 },
357 {
358 file: "test/following.test.ts",
359 issue: 1327,
360 reason: "14.9 s on the gate box; 6 tests over 1 s, the slowest 1.4 s",
361 },
362 {
363 file: "test/fork-pull-approval.test.ts",
364 issue: 1328,
365 reason: "14.6 s on the gate box; 5 tests over 1 s, the slowest 1.7 s",
366 },
367 {
368 file: "test/crew-parks.test.ts",
369 issue: 1329,
370 reason: "14.2 s on the gate box; 1 test over 1 s, the slowest 5.5 s",
371 },
372 {
373 file: "test/body-limits.test.ts",
374 issue: 1330,
375 reason: "14.1 s on the gate box; 4 tests over 1 s, the slowest 4.0 s",
376 },
377 {
378 file: "test/crew-brief-audience.test.ts",
379 issue: 1331,
380 reason: "13.9 s on the gate box",
381 },
382 {
383 file: "test/crew-remotes.test.ts",
384 issue: 1332,
385 reason: "12.6 s on the gate box; 1 test over 1 s, the slowest 11.0 s",
386 },
387 {
388 file: "test/accounts.test.ts",
389 issue: 1333,
390 reason: "9.9 s on the gate box; 2 tests over 1 s, the slowest 1.7 s",
391 },
392 {
393 file: "test/diff-edge-cases.test.ts",
394 issue: 1334,
395 reason: "9.6 s on the gate box; 2 tests over 1 s, the slowest 1.4 s",
396 },
397 {
398 file: "test/credentials.test.ts",
399 issue: 1335,
400 reason: "7.2 s on the gate box; 1 test over 1 s, the slowest 5.6 s",
401 },
402 {
403 file: "test/apps-idle.test.ts",
404 issue: 1336,
405 reason: "7.0 s on the gate box; 2 tests over 1 s, the slowest 2.9 s",
406 },
407 {
408 file: "test/verify-email.test.ts",
409 issue: 1337,
410 reason: "6.8 s on the gate box; 1 test over 1 s, the slowest 1.2 s",
411 },
412 {
413 file: "test/surfaces-adversarial.test.ts",
414 issue: 1338,
415 reason: "6.2 s on the gate box; 2 tests over 1 s, the slowest 1.1 s",
416 },
417 {
418 file: "test/landing.test.ts",
419 issue: 1339,
420 reason: "6.1 s on the gate box; 1 test over 1 s, the slowest 6.0 s",
421 },
422 {
423 file: "test/asks-rank.test.ts",
424 issue: 1340,
425 reason: "5.5 s on the gate box; 1 test over 1 s, the slowest 1.3 s",
426 },
427 {
428 file: "test/orgs.test.ts",
429 issue: 1341,
430 reason: "5.2 s on the gate box; 2 tests over 1 s, the slowest 1.3 s",
431 },
432 {
433 file: "test/client-list.test.ts",
434 issue: 1342,
435 reason: "4.3 s on the gate box; 1 test over 1 s, the slowest 1.6 s",
436 },
437 {
438 file: "test/meter.test.ts",
439 issue: 1343,
440 reason: "3.9 s on the gate box; 1 test over 1 s, the slowest 1.4 s",
441 },
442 {
443 file: "test/highlight.test.ts",
444 issue: 1344,
445 reason: "3.5 s on the gate box; 1 test over 1 s, the slowest 2.1 s",
446 },
447 {
448 file: "test/shards.test.ts",
449 issue: 1345,
450 reason: "1.8 s on the gate box; 1 test over 1 s, the slowest 1.7 s",
451 },
452 {
453 file: "test/edits-security.test.ts",
454 issue: 1346,
455 reason: "a test 1.5 s (the comparison cap)",
456 },
457 {
458 file: "test/plan-route.test.ts",
459 issue: 1438,
460 reason: "5.6 s alone; 1 test over 1 s, a whole crew run, 4.9 s",
461 },
462 {
463 file: "test/chaos.test.ts",
464 issue: 1439,
465 reason: "4.3 s alone; 1 test over 1 s, the slowest 1.7 s",
466 },
467 ];
468
469 /**
470 * Slow by nature, so run nightly (`bun scripts/test-shards.ts --nightly`)
471 * and never by the gate: each with why it cannot be fast and its issue.
472 */
473 export const NIGHTLY: readonly Exclusion[] = [];
474
236475 export const EXCLUDED: readonly Exclusion[] = [
237476 { file: "test/api-errors.test.ts", reason: "not yet admitted", issue: 261 },
238477 { file: "test/apps-api.test.ts", reason: "not yet admitted", issue: 261 },
@@ -343,12 +582,16 @@ export const EXCLUDED: readonly Exclusion[] = [
343582
344583 /**
345584 * Everything wrong with a gate list, against the test files that exist:
346 * one line per problem, none when every file is accounted for exactly once.
585 * one line per problem, none when every file is accounted for exactly once
586 * (in `GATE`, `NIGHTLY` or `EXCLUDED`) and every `SLOW` entry names a gate
587 * file and an issue.
347588 */
348589 export function auditGate(
349590 present: readonly string[],
350591 gate: readonly string[],
351592 excluded: readonly Exclusion[],
593 nightly: readonly Exclusion[] = [],
594 slow: readonly Slow[] = [],
352595 ): string[] {
353596 const problems: string[] = [];
354597 const exists = new Set(present);
@@ -359,20 +602,41 @@ export function auditGate(
359602 if (!exists.has(file))
360603 problems.push(`${file} is in GATE but does not exist`);
361604 }
362 const out = new Set<string>();
363 for (const { file, reason, issue } of excluded) {
364 if (out.has(file)) problems.push(`${file} is in EXCLUDED twice`);
365 out.add(file);
366 if (!exists.has(file))
367 problems.push(`${file} is in EXCLUDED but does not exist`);
368 if (gated.has(file)) problems.push(`${file} is in both GATE and EXCLUDED`);
369 if (typeof reason !== "string" || reason.trim() === "")
370 problems.push(`${file} is excluded with no reason`);
605 const placed = new Set(gated);
606 const lists: [string, readonly Exclusion[], string][] = [
607 ["NIGHTLY", nightly, "in the nightly lane"],
608 ["EXCLUDED", excluded, "excluded"],
609 ];
610 for (const [list, entries, verb] of lists) {
611 const seen = new Set<string>();
612 for (const { file, reason, issue } of entries) {
613 if (seen.has(file)) problems.push(`${file} is in ${list} twice`);
614 seen.add(file);
615 if (!exists.has(file))
616 problems.push(`${file} is in ${list} but does not exist`);
617 if (gated.has(file))
618 problems.push(`${file} is in both GATE and ${list}`);
619 else if (placed.has(file))
620 problems.push(`${file} is in both NIGHTLY and EXCLUDED`);
621 placed.add(file);
622 if (typeof reason !== "string" || reason.trim() === "")
623 problems.push(`${file} is ${verb} with no reason`);
624 if (!Number.isInteger(issue) || issue <= 0)
625 problems.push(`${file} is ${verb} with no issue number`);
626 }
627 }
628 const slowSeen = new Set<string>();
629 for (const { file, issue, reason } of slow) {
630 if (slowSeen.has(file)) problems.push(`${file} is in SLOW twice`);
631 slowSeen.add(file);
632 if (!gated.has(file)) problems.push(`${file} is in SLOW but not in GATE`);
371633 if (!Number.isInteger(issue) || issue <= 0)
372 problems.push(`${file} is excluded with no issue number`);
634 problems.push(`${file} is in SLOW with no issue number`);
635 if (typeof reason !== "string" || reason.trim() === "")
636 problems.push(`${file} is in SLOW with no reason`);
373637 }
374638 for (const file of present)
375 if (!gated.has(file) && !out.has(file))
376 problems.push(`${file} is in neither GATE nor EXCLUDED`);
639 if (!placed.has(file))
640 problems.push(`${file} is in none of GATE, NIGHTLY and EXCLUDED`);
377641 return problems;
378642 }
scripts/shards.ts +138 −22
@@ -76,6 +76,62 @@ export function splitFiles(
7676 );
7777 }
7878
79 /**
80 * A file expected to take less than this many seconds shares a `bun test`
81 * process with its neighbours (#1242). On the gate box most such files are
82 * the process start and module load, not tests: of the first 88 files of a
83 * fast check run one per process, 55 finished under 5 s.
84 */
85 export const GROUP_UNDER = 5;
86
87 /**
88 * At most this many files share one process. Measured with `--isolate`:
89 * 8 to 12 short files peaked at 170–220 MB, about what the largest short
90 * file takes alone (175 MB); all 72 in one process peaked at 943 MB. The
91 * Actions runner OOMed holding more than one suite (#386/#388), so a group
92 * stays the size of one.
93 */
94 export const GROUP_FILES = 8;
95
96 /** At most this many expected seconds share one process, so a red group
97 * stops the run (fail-fast) about as soon as a lone file would. */
98 export const GROUP_SECONDS = 20;
99
100 /**
101 * The gate's processes: each file expected to take {@link GROUP_UNDER}
102 * seconds or more (or named in `alone`, the `SLOW` files) is its own; the
103 * short files are packed in the list's order, a long file between them
104 * not breaking a group, into groups of at most {@link GROUP_FILES} files
105 * and {@link GROUP_SECONDS} expected seconds. Every file is in exactly one
106 * slice; the same input always gives the same slices.
107 */
108 export function groupFiles(
109 files: readonly string[],
110 weight: (file: string) => number,
111 alone: ReadonlySet<string> = new Set(),
112 ): string[][] {
113 const slices: string[][] = [];
114 let group: string[] = [];
115 let load = 0;
116 const close = (): void => {
117 if (group.length > 0) slices.push(group);
118 group = [];
119 load = 0;
120 };
121 for (const file of files) {
122 const seconds = weight(file);
123 if (alone.has(normalise(file)) || !(seconds < GROUP_UNDER)) {
124 slices.push([file]);
125 continue;
126 }
127 if (group.length >= GROUP_FILES || load + seconds > GROUP_SECONDS) close();
128 group.push(file);
129 load += seconds;
130 }
131 close();
132 return slices;
133 }
134
79135 /** How a test file is named: the same rule `scripts/test-shards.ts` uses. */
80136 export const TEST_FILE = /\.test\.[cm]?[jt]sx?$/;
81137
@@ -121,11 +177,14 @@ const TIME_MAX = 86_400;
121177 export const SECONDS_PER_BYTE_DEFAULT = 1 / 2_000;
122178
123179 /**
124 * Reads `scripts/test-times.json`: one object, test file path to the
125 * seconds it took alone, e.g. `{ "test/crew.test.ts": 50.1 }`. Anything
126 * else — not JSON, not an object, a key that is not a test file, a value
127 * that is not a finite number from 0 to a day — refuses the whole table,
128 * so a half-trusted table never steers the split.
180 * Reads `scripts/test-times.json`'s file times: seconds per test file,
181 * spawn to exit. The table is `{ "files": { "test/crew.test.ts": 50.1 },
182 * "tests": { "test/crew.test.ts > a test": 0.4 }, "total": 290.2 }`;
183 * the flat shape it had before per-test times (`{ "test/crew.test.ts":
184 * 50.1 }`) is still read. Anything else — not JSON, not an object, a key
185 * that is not a test file, a value that is not a finite number from 0 to
186 * a day — refuses the whole table, so a half-trusted table never steers
187 * the split.
129188 */
130189 export function parseTimes(
131190 text: string,
@@ -138,16 +197,34 @@ export function parseTimes(
138197 }
139198 if (typeof data !== "object" || data === null || Array.isArray(data))
140199 return { ok: false, error: "not an object of file to seconds" };
200 const table = data as Record<string, unknown>;
201 if ("files" in table) {
202 const files = table["files"];
203 const tests = table["tests"] ?? {};
204 const total = table["total"] ?? 0;
205 if (typeof files !== "object" || files === null || Array.isArray(files))
206 return { ok: false, error: "files is not an object of file to seconds" };
207 if (typeof tests !== "object" || tests === null || Array.isArray(tests))
208 return { ok: false, error: "tests is not an object of test to seconds" };
209 if (!isSeconds(total))
210 return { ok: false, error: `total: ${JSON.stringify(total)} is not seconds` };
211 for (const [key, seconds] of Object.entries(tests)) {
212 const file = key.split(" > ", 1)[0]!;
213 if (!TEST_FILE.test(file) || key.length > 2048)
214 return { ok: false, error: `${JSON.stringify(key)} is not a test` };
215 if (!isSeconds(seconds))
216 return {
217 ok: false,
218 error: `${key}: ${JSON.stringify(seconds)} is not seconds from 0 to ${TIME_MAX}`,
219 };
220 }
221 data = files;
222 }
141223 const times = new Map<string, number>();
142 for (const [file, seconds] of Object.entries(data)) {
224 for (const [file, seconds] of Object.entries(data as object)) {
143225 if (!TEST_FILE.test(file) || file.length > 512)
144226 return { ok: false, error: `${JSON.stringify(file)} is not a test file` };
145 if (
146 typeof seconds !== "number" ||
147 !Number.isFinite(seconds) ||
148 seconds < 0 ||
149 seconds > TIME_MAX
150 )
227 if (!isSeconds(seconds))
151228 return {
152229 ok: false,
153230 error: `${file}: ${JSON.stringify(seconds)} is not seconds from 0 to ${TIME_MAX}`,
@@ -157,6 +234,15 @@ export function parseTimes(
157234 return { ok: true, value: times };
158235 }
159236
237 function isSeconds(value: unknown): value is number {
238 return (
239 typeof value === "number" &&
240 Number.isFinite(value) &&
241 value >= 0 &&
242 value <= TIME_MAX
243 );
244 }
245
160246 /** `./test/a.test.ts` and `test/a.test.ts` are the same file. */
161247 function normalise(file: string): string {
162248 return file.startsWith("./") ? file.slice(2) : file;
@@ -192,18 +278,48 @@ export function weigher(
192278 }
193279
194280 /**
195 * The table as it is checked in: keys sorted, seconds to one decimal, one
196 * file per line, so a refresh reads as a small diff.
281 * The table as it is checked in: keys sorted, files to a tenth of a
282 * second and tests to a hundredth, one entry per line, so a refresh reads
283 * as a small diff. `tests` keys are `file > describe > test`; `total` is
284 * the whole run's wall clock, the number the suite's target is held to.
197285 */
198 export function formatTimes(times: ReadonlyMap<string, number>): string {
199 const entries = [...times]
200 .map(([file, seconds]) => [normalise(file), seconds] as const)
201 .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
202 const lines = entries.map(
203 ([file, seconds]) =>
204 ` ${JSON.stringify(file)}: ${Math.round(seconds * 10) / 10}`,
286 export function formatTimes(
287 files: ReadonlyMap<string, number>,
288 tests: ReadonlyMap<string, number> = new Map(),
289 total = 0,
290 ): string {
291 const block = (
292 entries: ReadonlyMap<string, number>,
293 places: number,
294 ): string => {
295 const lines = [...entries]
296 .map(([key, seconds]) => [normalise(key), seconds] as const)
297 .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
298 .map(
299 ([key, seconds]) =>
300 ` ${JSON.stringify(key)}: ${Math.round(seconds * 10 ** places) / 10 ** places}`,
301 );
302 return lines.length === 0 ? "{}" : `{\n${lines.join(",\n")}\n }`;
303 };
304 return (
305 `{\n "total": ${Math.round(total * 10) / 10},\n` +
306 ` "files": ${block(files, 1)},\n` +
307 ` "tests": ${block(tests, 2)}\n}\n`
205308 );
206 return lines.length === 0 ? "{}\n" : `{\n${lines.join(",\n")}\n}\n`;
309 }
310
311 /**
312 * The table's per-test times, `file > describe > test` to seconds, or an
313 * empty map when it has none (the flat shape, or a refused table): what a
314 * partial run keeps for the files it did not run.
315 */
316 export function parseTestTimes(text: string): Map<string, number> {
317 const tests = new Map<string, number>();
318 if (!parseTimes(text).ok) return tests;
319 const data = JSON.parse(text) as { tests?: Record<string, number> };
320 for (const [key, seconds] of Object.entries(data.tests ?? {}))
321 tests.set(normalise(key), seconds);
322 return tests;
207323 }
208324
209325 /** One shard, finished: what it ran, how it exited, everything it printed. */
scripts/test-shards.ts +194 −31
@@ -6,11 +6,22 @@
66 * bun scripts/test-shards.ts [bun test flags…] test/a.test.ts test/b.test.ts …
77 * bun scripts/test-shards.ts [bun test flags…] --tier fast --diff <base>..<head>
88 * bun scripts/test-shards.ts --record [bun test flags…] test/a.test.ts …
9 * bun scripts/test-shards.ts [bun test flags…] --nightly
910 * bun scripts/test-shards.ts [bun test flags…] -- a b … (test/a.test.ts …)
1011 *
1112 * `--gate` runs the files `scripts/gate.ts` admits, which is how
12 * `forge.json`'s `check.run` names them; files on the command line are for
13 * running a slice by hand. `--shard N/M` (or `FORGE_CHECK_SHARD_INDEX` +
13 * `forge.json`'s `check.run` names them; `--nightly` runs its `NIGHTLY`
14 * list; files on the command line are for running a slice by hand.
15 *
16 * `--gate` also holds the run to the time budget (`scripts/budget.ts`):
17 * each long file is its own `bun test`, timed spawn to exit; files expected
18 * under 5 s share one `bun test --isolate` a few at a time, so they pay
19 * one bun start between them, each timed by `scripts/file-clock.ts`; a
20 * JUnit report times each test. A file or test over budget and not in
21 * `SLOW` turns the run red after every file has run, so the log names
22 * them all at once. When no test failed, `scripts/test-times.json` is
23 * rewritten from the run (per file, per test, and the run's wall clock),
24 * and the log names the five slowest tests and their share of the run. `--shard N/M` (or `FORGE_CHECK_SHARD_INDEX` +
1425 * `FORGE_CHECK_SHARD_TOTAL`) keeps only the Nth contiguous slice of that
1526 * list so Actions can matrix the gate across jobs without parallel bun
1627 * inside one container. Each shard is its own `bun test`
@@ -32,10 +43,20 @@
3243 */
3344
3445 import { availableParallelism } from "node:os";
35 import { readFileSync, statSync, writeFileSync } from "node:fs";
46 import {
47 mkdtempSync,
48 readFileSync,
49 rmSync,
50 statSync,
51 writeFileSync,
52 } from "node:fs";
53 import { tmpdir } from "node:os";
54 import { join } from "node:path";
3655 import {
3756 formatTimes,
57 groupFiles,
3858 parseShardSpec,
59 parseTestTimes,
3960 parseTimes,
4061 shardCount,
4162 sliceFiles,
@@ -45,14 +66,24 @@ import {
4566 weigher,
4667 type ShardResult,
4768 } from "./shards.ts";
48 import { GATE } from "./gate.ts";
69 import {
70 budgetFor,
71 fileClock,
72 judge,
73 parseJunitFiles,
74 slowestLine,
75 type TestTime,
76 } from "./budget.ts";
77 import { GATE, NIGHTLY, SLOW } from "./gate.ts";
4978 import { fastSet, importsOf, duration } from "../src/checks/tiers.ts";
5079
5180 const TIMES = new URL("./test-times.json", import.meta.url).pathname;
81 const CLOCK = new URL("./file-clock.ts", import.meta.url).pathname;
5282
5383 const argv = process.argv.slice(2);
5484 const record = argv.includes("--record");
5585 const gate = argv.includes("--gate");
86 const nightly = argv.includes("--nightly");
5687
5788 /** Pull `--shard N/M` or `--shard=N/M` out of argv so it never reaches bun test. */
5889 function takeShardArg(raw: string[]): {
@@ -112,7 +143,9 @@ function takeValue(
112143 }
113144
114145 const tierArg = takeValue(
115 argv.filter((arg) => arg !== "--record" && arg !== "--gate"),
146 argv.filter(
147 (arg) => arg !== "--record" && arg !== "--gate" && arg !== "--nightly",
148 ),
116149 "--tier",
117150 );
118151 const diffArg = takeValue(tierArg.rest, "--diff");
@@ -164,13 +197,23 @@ if (!shardSpec.ok) {
164197 process.exit(2);
165198 }
166199
200 const { budgeted, setsTotal } = budgetFor({
201 gate,
202 tier: tier === "fast" ? "fast" : "full",
203 sliced: !("none" in shardSpec),
204 });
205
167206 const split = splitArgs(args);
168207 if (!split.ok) {
169208 console.error(`test-shards: ${split.error}`);
170209 process.exit(2);
171210 }
172211 const flags = split.flags;
173 let files = [...(gate || tier === "fast" ? GATE : []), ...split.files];
212 let files = [
213 ...(gate || tier === "fast" ? GATE : []),
214 ...(nightly ? NIGHTLY.map((entry) => entry.file) : []),
215 ...split.files,
216 ];
174217 if (tier === "fast") {
175218 const diff = Bun.spawnSync(
176219 ["git", "diff", "--name-only", "--no-renames", diffArg.value!],
@@ -221,6 +264,10 @@ if (tier === "fast") {
221264 files = plan.files;
222265 }
223266
267 if (files.length === 0 && nightly) {
268 console.log("test-shards: NIGHTLY is empty; nothing to run");
269 process.exit(0);
270 }
224271 if (files.length === 0) {
225272 console.error("test-shards: name the test files to run, or --gate");
226273 process.exit(2);
@@ -278,6 +325,7 @@ delete process.env["FORGE_CHECK_SHARD_TOTAL"];
278325 // where it does not. A missing or refused table is said out loud and the
279326 // gate still runs, on bytes alone.
280327 let times = new Map<string, number>();
328 let testTimes = new Map<string, number>();
281329 let table = "";
282330 try {
283331 table = readFileSync(TIMES, "utf8");
@@ -286,8 +334,10 @@ try {
286334 }
287335 if (table !== "") {
288336 const parsed = parseTimes(table);
289 if (parsed.ok) times = parsed.value;
290 else
337 if (parsed.ok) {
338 times = parsed.value;
339 testTimes = parseTestTimes(table);
340 } else
291341 console.log(
292342 `test-shards: scripts/test-times.json refused (${parsed.error}); weighing by bytes`,
293343 );
@@ -296,17 +346,39 @@ const weight = weigher(files, size, times);
296346 // Recording runs one file per process, so every file is its own slice.
297347 // FORGE_CHECK_SHARDS=1 on the isolated Actions runner still OOMed when one
298348 // bun test held the whole gate (#386/#388, exit 137 ~15–17m). Same count
299 // with one-file-per-process, serial, keeps peak RSS to a single suite.
349 // with one suite's worth per process, serial, keeps peak RSS to one suite.
350 // The gate does the same at any width: a long file's time is its
351 // process's, spawn to exit, so the file budget measures what it costs.
352 // Short files would each pay a bun start for a second of tests, so the
353 // gate runs them a few to a process (`groupFiles`), `--isolate` keeping
354 // each in its own globals and `scripts/file-clock.ts` timing each one;
355 // a group is held to about one suite's peak RSS. `--record` still times
356 // every file alone.
300357 const serialFiles = !record && count.value === 1;
301 const slices =
302 record || serialFiles
303 ? files.map((file) => [file])
358 const eachAlone = record || budgeted || serialFiles;
359 const slowFiles = new Set(SLOW.map((entry) => entry.file));
360 const slices = record
361 ? files.map((file) => [file])
362 : eachAlone
363 ? groupFiles(files, weight, slowFiles)
304364 : splitFiles(files, count.value, weight);
365 // Each process's JUnit report, for its per-test times, and a group's
366 // clock lines. Somewhere the check's own cell may write, and gone when
367 // the run ends.
368 const junitDir = eachAlone ? mkdtempSync(join(tmpdir(), "test-junit-")) : "";
369 const junitPath = (index: number): string =>
370 join(junitDir, `${index + 1}.xml`);
371 const clockPath = (index: number): string =>
372 join(junitDir, `${index + 1}.clock`);
373 const grouped = slices.filter((slice) => slice.length > 1).length;
305374
306375 const banner = record
307376 ? `test-shards: recording ${files.length} files, ${count.value} at a time`
308 : serialFiles
309 ? `test-shards: ${files.length} files serial (one bun test each; FORGE_CHECK_SHARDS=1), ` +
377 : budgeted && !serialFiles
378 ? `test-shards: ${files.length} files in ${slices.length} bun tests (${grouped} grouped), ${count.value} at a time`
379 : serialFiles
380 ? `test-shards: ${files.length} files serial in ${slices.length} bun tests ` +
381 `(long files alone, short ones ${grouped === 0 ? "none grouped" : `in ${grouped} groups`}; FORGE_CHECK_SHARDS=1), ` +
310382 `expected ${files.reduce((sum, file) => sum + weight(file), 0).toFixed(0)}s`
311383 : `test-shards: ${files.length} files in ${slices.length} shard${slices.length === 1 ? "" : "s"}, ` +
312384 `expected ${slices.map((slice) => slice.reduce((sum, file) => sum + weight(file), 0).toFixed(0) + "s").join(" ")}`;
@@ -336,7 +408,20 @@ async function drain(
336408 take(decoder.decode());
337409 }
338410
339 type Timed = ShardResult & { seconds: number };
411 /** A file's text, or nothing when the file was never written. */
412 function readOr(path: string): string {
413 try {
414 return readFileSync(path, "utf8");
415 } catch {
416 return "";
417 }
418 }
419
420 type Timed = ShardResult & {
421 seconds: number;
422 /** Each file's seconds: a lone file's spawn to exit, a group's clocked. */
423 fileSeconds: Map<string, number>;
424 };
340425
341426 /**
342427 * One shard. `live` (shards running one at a time) writes the shard's
@@ -368,14 +453,23 @@ async function runShard(
368453 // to bun test shards — a leftover max-old-space-size races the check
369454 // cell's memory cgroup and the kernel SIGKILLs the gate (exit 137).
370455 delete childEnv["NODE_OPTIONS"];
371 const child = Bun.spawn(["bun", "test", ...flags, ...paths], {
456 const junit = eachAlone
457 ? ["--reporter=junit", `--reporter-outfile=${junitPath(index)}`]
458 : [];
459 const group = eachAlone && slice.length > 1;
460 if (group) childEnv["FORGE_TEST_CLOCK"] = clockPath(index);
461 const clock = group ? ["--isolate", `--preload=${CLOCK}`] : [];
462 const child = Bun.spawn(
463 ["bun", "test", ...flags, ...clock, ...junit, ...paths],
464 {
372465 stdin: "ignore",
373466 stdout: "pipe",
374467 stderr: "pipe",
375468 // Bun keeps shell-inherited vars after `delete process.env.X`; pass a
376469 // cleaned env so capacityDefault does not see the gate's shard count.
377470 env: childEnv,
378 });
471 },
472 );
379473 children.add(child);
380474 // One buffer, in arrival order: `bun test` splits its report across
381475 // stdout and stderr.
@@ -390,19 +484,33 @@ async function runShard(
390484 drain(child.stderr, output, through),
391485 ]);
392486 const code = await child.exited;
487 const exitMs = Date.now();
393488 children.delete(child);
394489 const text = output.join("");
395490 const seconds = ((performance.now() - started) / 1000).toFixed(1);
491 // Peak RSS in MB (Linux reports maxRSS in KB): what keeps a group to
492 // one suite's memory is measured, not assumed.
493 const maxRss = child.resourceUsage()?.maxRSS;
494 const rss = maxRss === undefined ? "" : `, ${Math.round(maxRss / 1024)} MB`;
396495 process.stdout.write(
397496 live
398 ? `${text.endsWith("\n") || text === "" ? "" : "\n"}── shard ${where} done (exit ${code}, ${seconds}s)\n`
399 : `\n── shard ${where} (exit ${code}, ${seconds}s): ${slice.join(" ")}\n${text}${text.endsWith("\n") ? "" : "\n"}`,
497 ? `${text.endsWith("\n") || text === "" ? "" : "\n"}── shard ${where} done (exit ${code}, ${seconds}s${rss})\n`
498 : `\n── shard ${where} (exit ${code}, ${seconds}s${rss}): ${slice.join(" ")}\n${text}${text.endsWith("\n") ? "" : "\n"}`,
400499 );
500 const fileSeconds = group
501 ? fileClock(readOr(clockPath(index)), slice, process.cwd(), exitMs)
502 : new Map([[slice[0]!, (performance.now() - started) / 1000]]);
503 // A grouped file's own time, one line each, as a lone file's shows on
504 // its shard's line.
505 if (group)
506 for (const [file, took] of fileSeconds)
507 process.stdout.write(` ${file} ${took.toFixed(1)}s\n`);
401508 return {
402509 files: slice,
403510 code,
404511 output: text,
405512 seconds: (performance.now() - started) / 1000,
513 fileSeconds,
406514 };
407515 }
408516
@@ -431,38 +539,93 @@ async function pool(width: number): Promise<Timed[]> {
431539 }
432540
433541 const started = performance.now();
434 // Serial one-file processes when SHARDS=1; record keeps its worker width;
435 // multi-shard still runs every slice side by side.
542 // Serial one-file processes when SHARDS=1; record and the gate keep the
543 // worker width; multi-shard still runs every slice side by side.
436544 const results = await pool(
437 serialFiles ? 1 : record ? count.value : slices.length,
545 serialFiles ? 1 : eachAlone ? count.value : slices.length,
438546 );
547 const runSeconds = (performance.now() - started) / 1000;
439548 if (results.length < slices.length) {
440549 const skipped = slices.length - results.length;
441550 console.log(
442551 `test-shards: fail-fast — skipped ${skipped} remaining shard${skipped === 1 ? "" : "s"} after a red exit`,
443552 );
444553 }
445 const ending = tally(results, (performance.now() - started) / 1000);
554 const ending = tally(results, runSeconds);
446555 const spread = results.map((result) => result.seconds);
447556 console.log(`\n${ending.lines.join("\n")}`);
448557 if (!record && results.length > 1)
449558 console.log(
450559 `Slowest shard ${Math.max(...spread).toFixed(1)}s, fastest ${Math.min(...spread).toFixed(1)}s.`,
451560 );
452 if (record) {
453 if (ending.code !== 0) {
561 // What this run measured: a lone file spawn to exit, a grouped one by
562 // its clock lines, every test from its process's report. A report a
563 // process never wrote (it crashed before the end) times no tests.
564 const measuredFiles = new Map<string, number>();
565 const measuredTests: TestTime[] = [];
566 if (eachAlone)
567 results.forEach((result, index) => {
568 for (const [file, seconds] of result.fileSeconds)
569 measuredFiles.set(file, seconds);
570 measuredTests.push(
571 ...parseJunitFiles(readOr(junitPath(index)), result.files),
572 );
573 });
574 // A grouped file its clock never named is a file the budget cannot see:
575 // said, so a gate that quietly judges less than it ran is not quiet.
576 if (eachAlone && ending.code === 0)
577 for (const result of results)
578 for (const file of result.files)
579 if (!measuredFiles.has(file))
580 console.log(`test-shards: ${file} was not timed (no clock line)`);
581 if (junitDir !== "") rmSync(junitDir, { recursive: true, force: true });
582 const measured = { files: measuredFiles, tests: measuredTests };
583 const everyFileRan = results.length === slices.length;
584 let code = ending.code;
585
586 const slowest = slowestLine(measuredTests, runSeconds);
587 if (slowest !== undefined) console.log(slowest);
588
589 // The table is rewritten from a run whose tests all passed, on every gate
590 // run and every --record: a red file's time is not its time. Files and
591 // tests this run did not name keep their old times, and the total is the
592 // wall clock of a whole, unsliced full gate, the number the suite's
593 // target is held to.
594 if ((record || budgeted) && eachAlone) {
595 if (ending.code !== 0 || !everyFileRan) {
454596 console.log(
455597 "test-shards: not recording: a file is red, so its time is not its time",
456598 );
457599 } else {
458 // Files this run did not name keep their old times: a partial run
459 // refreshes what it ran and forgets nothing else.
460600 const fresh = new Map(times);
461 for (const result of results) fresh.set(result.files[0]!, result.seconds);
462 writeFileSync(TIMES, formatTimes(fresh));
601 for (const [file, seconds] of measuredFiles) fresh.set(file, seconds);
602 const freshTests = new Map(
603 [...testTimes].filter(
604 ([key]) => !measuredFiles.has(key.split(" > ", 1)[0]!),
605 ),
606 );
607 for (const test of measuredTests)
608 freshTests.set(`${test.file} > ${test.name}`, test.seconds);
609 let total = 0;
610 if (setsTotal) total = runSeconds;
611 else
612 try {
613 total = (JSON.parse(table) as { total?: number }).total ?? 0;
614 } catch {
615 total = 0;
616 }
617 writeFileSync(TIMES, formatTimes(fresh, freshTests, total));
463618 console.log(
464 `test-shards: wrote ${results.length} times to scripts/test-times.json`,
619 `test-shards: wrote ${measuredFiles.size} files and ${measuredTests.length} tests to scripts/test-times.json`,
465620 );
466621 }
467622 }
468 process.exit(ending.code);
623
624 // The budget is judged on a run whose tests all passed: a red run already
625 // says what is wrong, and a fail-fast run did not time every file.
626 if (budgeted && ending.code === 0) {
627 const verdict = judge(measured, slowFiles);
628 if (verdict.lines.length > 0) console.log(verdict.lines.join("\n"));
629 code = verdict.code;
630 }
631 process.exit(code);
scripts/test-times.json +1607 −41

Diff not shown — 206,528 bytes of diff (limit 100,000). +1607 −41

View file
src/checks/service.ts +5 −5
@@ -62,7 +62,7 @@ import {
6262 STEP_HOSTS,
6363 type CellSpec,
6464 } from "../apps/contain.ts";
65 import { summariseCheckFailure } from "./summary.ts";
65 import { summariseCheckFailure, summariseCheckPass } from "./summary.ts";
6666 import type { CheckDetail } from "../core/runs.ts";
6767
6868 const log = createLog("checks");
@@ -370,7 +370,7 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
370370 const done = finishRun(app.db, run.id, {
371371 state: outcome.ok ? "ok" : "failed",
372372 summary: outcome.ok
373 ? `check passed in ${seconds}s`
373 ? summariseCheckPass(outcome.lines, seconds)
374374 : `check failed: ${outcome.error}`,
375375 ...(outcome.ok || outcome.detail === undefined
376376 ? {}
@@ -389,7 +389,7 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
389389 write: (line: string) => void,
390390 signal: AbortSignal,
391391 ): Promise<
392 | { ok: true }
392 | { ok: true; lines: readonly string[] }
393393 | { ok: false; error: string; detail?: CheckDetail | undefined }
394394 > {
395395 const bare = await runDir(app.db, app.reposRoot, repo, run.issueId);
@@ -430,7 +430,7 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
430430 async function runTier(
431431 x: Execution,
432432 ): Promise<
433 | { ok: true }
433 | { ok: true; lines: readonly string[] }
434434 | { ok: false; error: string; detail?: CheckDetail | undefined }
435435 > {
436436 const { bare, repo, write, signal } = x;
@@ -608,7 +608,7 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
608608 );
609609 return { ok: false, error: summary, detail };
610610 }
611 return { ok: true };
611 return { ok: true, lines: checkLines };
612612 } finally {
613613 if (existsSync(dir)) rmSync(dir, { recursive: true, force: true });
614614 rmSync(home, { recursive: true, force: true });
src/checks/summary.ts +21
@@ -53,3 +53,24 @@ export function summariseCheckFailure(
5353 }
5454 return { summary: fallback, detail: undefined };
5555 }
56
57 /** The line `scripts/test-shards.ts` ends a timed run with (#1242). */
58 const SLOWEST = /^Slowest tests: (.+)$/;
59
60 /**
61 * What a passed check's summary says: how long it took and, when the
62 * check step's output named them, the five slowest tests and their share
63 * of the run — the last such line, so a check that runs the gate twice
64 * reports the run that finished. Bounded like a failure's.
65 */
66 export function summariseCheckPass(
67 lines: readonly string[],
68 seconds: number,
69 ): string {
70 const passed = `check passed in ${seconds}s`;
71 for (let i = lines.length - 1; i >= 0; i--) {
72 const slowest = SLOWEST.exec(lines[i]!.trim());
73 if (slowest) return truncate(`${passed}; slowest: ${slowest[1]}`);
74 }
75 return passed;
76 }
test/budget.test.ts added +298
@@ -0,0 +1,298 @@
1 /**
2 * The gate's time budget (`scripts/budget.ts`, #1242): a test over 1 s or
3 * a file over 10 s, not let off in `SLOW`, turns a green run red; the
4 * JUnit report bun writes is read into names a person can find; and the
5 * log's slowest-five line is the same for the same times.
6 */
7
8 import { describe, expect, test } from "bun:test";
9 import {
10 FILE_BUDGET,
11 TEST_BUDGET,
12 budgetFor,
13 fileClock,
14 judge,
15 overBudget,
16 parseJunit,
17 parseJunitFiles,
18 slowNoLonger,
19 slowestLine,
20 type Measured,
21 } from "../scripts/budget.ts";
22 import { GATE, SLOW } from "../scripts/gate.ts";
23
24 // What `bun test --reporter=junit` 1.3 writes for a nested describe, an
25 // escaped name, a `>` inside a name, and a skipped test (its classname is
26 // escaped twice, which is why the path comes from the suites instead).
27 const REPORT = `<?xml version="1.0" encoding="UTF-8"?>
28 <testsuites name="bun test" tests="3" assertions="0" failures="0" skipped="1" time="1.5">
29 <testsuite name="test/a.test.ts" file="test/a.test.ts" tests="3" time="0">
30 <testcase name="top level" classname="" time="0.25" file="test/a.test.ts" line="2" assertions="1" />
31 <testsuite name="outer &amp; &lt;x&gt;" file="test/a.test.ts" line="3" tests="2" time="0">
32 <testsuite name="inner" file="test/a.test.ts" line="4" tests="2" time="0">
33 <testcase name="a &gt; b &quot;q&quot;" classname="inner" time="1.25" file="test/a.test.ts" line="5" assertions="0" />
34 <testcase name="skipped" classname="inner" time="0" file="test/a.test.ts" line="6" assertions="0">
35 <skipped />
36 </testcase>
37 </testsuite>
38 </testsuite>
39 <testcase name="after > the describes" classname="" time="nope" file="test/a.test.ts" line="8" assertions="0" />
40 </testsuite>
41 </testsuites>
42 `;
43
44 describe("parseJunit", () => {
45 test("names every test by its describes, unescaped, with its seconds", () => {
46 expect(parseJunit(REPORT, "test/a.test.ts")).toEqual([
47 { file: "test/a.test.ts", name: "top level", seconds: 0.25 },
48 {
49 file: "test/a.test.ts",
50 name: 'outer & <x> > inner > a > b "q"',
51 seconds: 1.25,
52 },
53 {
54 file: "test/a.test.ts",
55 name: "outer & <x> > inner > skipped",
56 seconds: 0,
57 },
58 // A time that is not a number is no time: never an invented slow test.
59 { file: "test/a.test.ts", name: "after > the describes", seconds: 0 },
60 ]);
61 });
62
63 test("a report that is not one times nothing", () => {
64 expect(parseJunit("", "test/a.test.ts")).toEqual([]);
65 expect(parseJunit("<html>", "test/a.test.ts")).toEqual([]);
66 });
67 });
68
69 // Three files in one `bun test --isolate`: each outermost suite is a
70 // file, named as bun was given it.
71 const GROUP_REPORT = `<testsuites name="bun test" tests="3" time="2">
72 <testsuite name="test/a.test.ts" file="test/a.test.ts" tests="1" time="0">
73 <testcase name="one" classname="" time="0.5" file="test/a.test.ts" line="2" />
74 </testsuite>
75 <testsuite name="test/b.test.ts" file="test/b.test.ts" tests="1" time="0">
76 <testsuite name="d" file="test/b.test.ts" line="2" tests="1" time="0">
77 <testcase name="two" classname="d" time="1.5" file="test/b.test.ts" line="3" />
78 </testsuite>
79 </testsuite>
80 <testsuite name="test/stray.test.ts" file="test/stray.test.ts" tests="1" time="0">
81 <testcase name="three" classname="" time="9" file="test/stray.test.ts" line="2" />
82 </testsuite>
83 </testsuites>`;
84
85 describe("parseJunitFiles", () => {
86 test("a group's report gives each test to its own file", () => {
87 expect(
88 parseJunitFiles(GROUP_REPORT, ["./test/a.test.ts", "test/b.test.ts"]),
89 ).toEqual([
90 { file: "./test/a.test.ts", name: "one", seconds: 0.5 },
91 { file: "test/b.test.ts", name: "d > two", seconds: 1.5 },
92 // A suite naming no file of the group is no file's.
93 ]);
94 });
95
96 test("one file takes every test, whatever its suite is named", () => {
97 expect(parseJunitFiles(GROUP_REPORT, ["x.test.ts"]).length).toBe(3);
98 });
99 });
100
101 describe("fileClock", () => {
102 const root = "/work/forge";
103 const files = ["test/a.test.ts", "./test/b.test.ts", "test/c.test.ts"];
104
105 test("a file runs from its start to the next one's, the last to the exit", () => {
106 // Out of order and with noise: the lines are sorted by time.
107 const text = [
108 "start 1000700 /work/forge/test/b.test.ts",
109 "start 1000000 /work/forge/test/a.test.ts",
110 "garbage",
111 "start 1000900 /elsewhere/test/c.test.ts",
112 "start 1001200 /work/forge/test/c.test.ts",
113 "start 1009999 /work/forge/test/a.test.ts",
114 ].join("\n");
115 // 0.7 s, 0.5 s, then 2.3 s to the exit at 1 003 500 ms.
116 expect([...fileClock(text, files, root, 1_003_500)]).toEqual([
117 ["test/a.test.ts", 0.7],
118 ["./test/b.test.ts", 0.5],
119 ["test/c.test.ts", 2.3],
120 ]);
121 });
122
123 test("a file the clock never named has no time, and no lines time nothing", () => {
124 const one = fileClock(
125 "start 5000 /work/forge/test/a.test.ts\n",
126 files,
127 `${root}/`,
128 6250,
129 );
130 expect([...one]).toEqual([["test/a.test.ts", 1.25]]);
131 expect(fileClock("", files, root, 1).size).toBe(0);
132 });
133
134 test("an absolute path is matched as it is", () => {
135 const clocked = fileClock("start 0 /abs/x.test.ts", ["/abs/x.test.ts"], root, 2000);
136 expect(clocked.get("/abs/x.test.ts")).toBe(2);
137 });
138 });
139
140 function run(
141 files: Record<string, number>,
142 tests: [string, string, number][] = [],
143 ): Measured {
144 return {
145 files: new Map(Object.entries(files)),
146 tests: tests.map(([file, name, seconds]) => ({ file, name, seconds })),
147 };
148 }
149
150 describe("the budget", () => {
151 test("is a second a test and ten a file", () => {
152 expect(TEST_BUDGET).toBe(1);
153 expect(FILE_BUDGET).toBe(10);
154 });
155
156 test("a file over ten seconds and a test over one are each named", () => {
157 const measured = run({ "test/a.test.ts": 10.05, "test/b.test.ts": 3 }, [
158 ["test/b.test.ts", "boots > a server", 1.01],
159 ["test/b.test.ts", "reads", 0.2],
160 ]);
161 expect(overBudget(measured, new Set())).toEqual([
162 "over budget: test/a.test.ts took 10.1s (a file may take 10s)",
163 "over budget: test/b.test.ts > boots > a server took 1.01s (a test may take 1s)",
164 ]);
165 });
166
167 test("exactly on the budget is within it", () => {
168 const measured = run({ "test/a.test.ts": 10 }, [
169 ["test/a.test.ts", "t", 1],
170 ]);
171 expect(overBudget(measured, new Set())).toEqual([]);
172 });
173
174 test("a file in SLOW is let off both budgets, and no other file is", () => {
175 const measured = run({ "test/a.test.ts": 60, "test/b.test.ts": 11 }, [
176 ["test/a.test.ts", "slow", 30],
177 ]);
178 expect(overBudget(measured, new Set(["test/a.test.ts"]))).toEqual([
179 "over budget: test/b.test.ts took 11.0s (a file may take 10s)",
180 ]);
181 });
182 });
183
184 describe("judge", () => {
185 test("over budget is red, names every file once, and ends with the verdict", () => {
186 const measured = run(
187 { "test/a.test.ts": 12, "test/b.test.ts": 2, "test/c.test.ts": 1 },
188 [
189 ["test/a.test.ts", "one", 2],
190 ["test/b.test.ts", "two", 1.5],
191 ["test/b.test.ts", "three", 1.2],
192 ],
193 );
194 const verdict = judge(measured, new Set());
195 expect(verdict.code).toBe(1);
196 expect(verdict.lines).toContain(
197 ' { file: "test/a.test.ts", issue: 0, reason: "what it measured" },',
198 );
199 expect(verdict.lines).toContain(
200 ' { file: "test/b.test.ts", issue: 0, reason: "what it measured" },',
201 );
202 expect(
203 verdict.lines.filter((line) => line.includes('"test/b.test.ts"')),
204 ).toHaveLength(1);
205 expect(verdict.lines.join("\n")).not.toContain("test/c.test.ts");
206 expect(verdict.lines.at(-1)).toBe(
207 "2 test files over the time budget (1s a test, 10s a file); the gate is red.",
208 );
209 });
210
211 test("within budget is green, and a SLOW file that kept to it is said", () => {
212 const measured = run({ "test/a.test.ts": 4, "test/b.test.ts": 20 }, [
213 ["test/a.test.ts", "quick", 0.5],
214 ]);
215 const slow = new Set(["test/a.test.ts", "test/b.test.ts"]);
216 expect(slowNoLonger(measured, slow)).toEqual(["test/a.test.ts"]);
217 expect(judge(measured, slow)).toEqual({
218 code: 0,
219 lines: [
220 "test-shards: test/a.test.ts kept to the budget this run; its SLOW entry can go",
221 ],
222 });
223 });
224
225 test("a SLOW file with one test still over is not said to be fast", () => {
226 const measured = run({ "test/a.test.ts": 4 }, [
227 ["test/a.test.ts", "slow", 1.5],
228 ]);
229 expect(slowNoLonger(measured, new Set(["test/a.test.ts"]))).toEqual([]);
230 });
231 });
232
233 describe("slowestLine", () => {
234 test("the five slowest, slowest first, with each one's share of the run", () => {
235 const tests: [string, string, number][] = [
236 ["test/a.test.ts", "one", 1],
237 ["test/b.test.ts", "two", 6],
238 ["test/a.test.ts", "three", 3],
239 ["test/c.test.ts", "four", 0.5],
240 ["test/c.test.ts", "five", 2],
241 ["test/c.test.ts", "six", 4],
242 ];
243 expect(slowestLine(run({}, tests).tests, 20)).toBe(
244 "Slowest tests: b › two 6.0s 30%; c › six 4.0s 20%; a › three 3.0s 15%; c › five 2.0s 10%; a › one 1.0s 5%",
245 );
246 });
247
248 test("a long name is cut, ties break on file then name, none is no line", () => {
249 const line = slowestLine(
250 run({}, [
251 ["test/b.test.ts", "x", 1],
252 ["test/a.test.ts", "a name far longer than a summary keeps", 1],
253 ]).tests,
254 0,
255 );
256 expect(line).toBe(
257 "Slowest tests: a › a name far longer than … 1.0s 0%; b › x 1.0s 0%",
258 );
259 expect(slowestLine([], 10)).toBeUndefined();
260 });
261 });
262
263 describe("SLOW", () => {
264 test("is short: no more than the files over budget when it was written", () => {
265 // 23 files were over budget in the table the budget came in with,
266 // recorded on another box over 41 files; the gate box's first fast
267 // check (run 01m4v94pk641ne5hzw5cntvwr1, 110 files) put 18 more over
268 // and 5 under (#1242). The list only shrinks from here; a file added
269 // to it needs a pull that says why.
270 expect(SLOW.length).toBeLessThanOrEqual(41);
271 for (const entry of SLOW) expect(GATE).toContain(entry.file);
272 });
273 });
274
275 describe("budgetFor", () => {
276 test("the gate and the fast tier are budgeted; a hand run is not", () => {
277 expect(budgetFor({ gate: true, tier: "full", sliced: false })).toEqual({
278 budgeted: true,
279 setsTotal: true,
280 });
281 // The fast tier is a slice of the gate: the same budget, not the total.
282 expect(budgetFor({ gate: false, tier: "fast", sliced: false })).toEqual({
283 budgeted: true,
284 setsTotal: false,
285 });
286 expect(budgetFor({ gate: false, tier: "full", sliced: false })).toEqual({
287 budgeted: false,
288 setsTotal: false,
289 });
290 });
291
292 test("one matrix slice of the gate is budgeted but is not the suite's total", () => {
293 expect(budgetFor({ gate: true, tier: "full", sliced: true })).toEqual({
294 budgeted: true,
295 setsTotal: false,
296 });
297 });
298 });
test/check-list.test.ts +48 −3
@@ -7,7 +7,7 @@
77
88 import { describe, expect, test } from "bun:test";
99 import { readdirSync } from "node:fs";
10 import { auditGate, EXCLUDED, GATE } from "../scripts/gate.ts";
10 import { auditGate, EXCLUDED, GATE, NIGHTLY, SLOW } from "../scripts/gate.ts";
1111
1212 const root = new URL("..", import.meta.url).pathname;
1313 const present = readdirSync(`${root}test`)
@@ -17,7 +17,7 @@ const present = readdirSync(`${root}test`)
1717
1818 describe("the gate's list", () => {
1919 test("every test/*.test.ts is in exactly one list, and every entry exists", () => {
20 expect(auditGate(present, GATE, EXCLUDED)).toEqual([]);
20 expect(auditGate(present, GATE, EXCLUDED, NIGHTLY, SLOW)).toEqual([]);
2121 });
2222
2323 test("this guard is itself in the gate", () => {
@@ -39,7 +39,7 @@ describe("auditGate", () => {
3939
4040 test("a file in neither list is named", () => {
4141 expect(auditGate(files, ["test/a.test.ts"], [])).toEqual([
42 "test/b.test.ts is in neither GATE nor EXCLUDED",
42 "test/b.test.ts is in none of GATE, NIGHTLY and EXCLUDED",
4343 ]);
4444 });
4545
@@ -85,4 +85,49 @@ describe("auditGate", () => {
8585 "test/a.test.ts is in GATE twice",
8686 ]);
8787 });
88
89 test("a nightly file counts as placed, and is held to the same rules", () => {
90 expect(
91 auditGate(files, ["test/a.test.ts"], [], [
92 { file: "test/b.test.ts", reason: "a browser", issue: 9 },
93 ]),
94 ).toEqual([]);
95 expect(
96 auditGate(
97 files,
98 ["test/a.test.ts"],
99 [{ file: "test/b.test.ts", reason: "slow", issue: 1 }],
100 [
101 { file: "test/a.test.ts", reason: "", issue: 0 },
102 { file: "test/b.test.ts", reason: "a browser", issue: 9 },
103 ],
104 ),
105 ).toEqual([
106 "test/a.test.ts is in both GATE and NIGHTLY",
107 "test/a.test.ts is in the nightly lane with no reason",
108 "test/a.test.ts is in the nightly lane with no issue number",
109 "test/b.test.ts is in both NIGHTLY and EXCLUDED",
110 ]);
111 });
112
113 test("a SLOW entry names a gate file, once, with an issue and a reason", () => {
114 expect(
115 auditGate(
116 files,
117 ["test/a.test.ts"],
118 [{ file: "test/b.test.ts", reason: "slow", issue: 1 }],
119 [],
120 [
121 { file: "test/a.test.ts", issue: 5, reason: "12 s" },
122 { file: "test/a.test.ts", issue: 0, reason: " " },
123 { file: "test/b.test.ts", issue: 6, reason: "12 s" },
124 ],
125 ),
126 ).toEqual([
127 "test/a.test.ts is in SLOW twice",
128 "test/a.test.ts is in SLOW with no issue number",
129 "test/a.test.ts is in SLOW with no reason",
130 "test/b.test.ts is in SLOW but not in GATE",
131 ]);
132 });
88133 });
test/checks.test.ts +47 −1
@@ -12,7 +12,10 @@ import { createApp, type App } from "../src/app.ts";
1212 import { openPull, submitReview } from "../src/actions/pulls.ts";
1313 import { commitToBranch, createRepo, forkRepo } from "../src/actions/repos.ts";
1414 import { parseBunTestFailure } from "../src/checks/bun-test.ts";
15 import { summariseCheckFailure } from "../src/checks/summary.ts";
15 import {
16 summariseCheckFailure,
17 summariseCheckPass,
18 } from "../src/checks/summary.ts";
1619 import {
1720 pickNext,
1821 requeueAbandonedChecks,
@@ -112,6 +115,31 @@ describe("parseBunTestFailure: a convenience over one known runner, not a genera
112115 });
113116 });
114117
118 describe("summariseCheckPass: a passed check names its slowest tests (#1242)", () => {
119 test("the last slowest-tests line the check printed follows the time", () => {
120 expect(
121 summariseCheckPass(
122 [
123 "Slowest tests: old › run 9.0s 90%",
124 "Ran 3 tests across 2 files in 2.0s (1 shard).",
125 "Slowest tests: crew › boots 1.2s 40%; web › reads 0.3s 10%",
126 "test-shards: wrote 2 files and 3 tests to scripts/test-times.json",
127 ],
128 3,
129 ),
130 ).toBe(
131 "check passed in 3s; slowest: crew › boots 1.2s 40%; web › reads 0.3s 10%",
132 );
133 });
134
135 test("a check that printed none says only the time, and a long one is bounded", () => {
136 expect(summariseCheckPass(["ok"], 12)).toBe("check passed in 12s");
137 const long = summariseCheckPass([`Slowest tests: ${"x".repeat(400)}`], 1);
138 expect(long.length).toBe(200);
139 expect(long.endsWith("…")).toBe(true);
140 });
141 });
142
115143 describe("summariseCheckFailure: what a failed check's summary says first", () => {
116144 test("real bun test output with one failure yields the name and the counts", () => {
117145 const lines = [
@@ -255,6 +283,24 @@ describe("checks", () => {
255283 expect(log).toContain("$ test -f OK.md");
256284 });
257285
286 test("a passed check's summary carries the slowest tests its output named", async () => {
287 const declared = await commitToBranch(app, alice, repo, {
288 message: "A check that times its tests",
289 files: [
290 {
291 path: "forge.json",
292 content: checkJson("echo 'Slowest tests: a › one 0.5s 50%'"),
293 },
294 ],
295 });
296 if (!declared.ok) throw new Error(JSON.stringify(declared.error));
297 const run = await settled((r) => r.commitOid === declared.value.commitOid);
298 expect(run.state).toBe("ok");
299 expect(run.summary).toMatch(
300 /^check passed in \d+s; slowest: a › one 0\.5s 50%$/,
301 );
302 });
303
258304 test("a check's children hold no cells of their own: the check's cell is the boundary", async () => {
259305 // A forge the tests boot inside a check cell must not wrap its apps in
260306 // nested cells (they never answer in time); it is told so in its env.
test/plan-route.test.ts +3 −1
@@ -51,6 +51,8 @@ describe("POST …/plan", () => {
5151 `#!/bin/sh
5252 if [ "$1" = "--version" ]; then echo "2.1.0 (fake)"; exit 0; fi
5353 IFS= read -r first; printf '%s\\n' "$first" > "${dataDir}/prompt"
54 # The planner's brief is the system prompt, passed as an argument.
55 printf '%s\\n' "$@" >> "${dataDir}/prompt"
5456 echo '{"type":"system","subtype":"init","session_id":"p1","model":"fake"}'
5557 if grep -q "this run is a planning run" "${dataDir}/prompt"; then
5658 path=$(grep -o 'api/v1/repos/[^"\\\\ ]*/plan' "${dataDir}/prompt" | head -1)
@@ -137,7 +139,7 @@ echo '{"type":"result","subtype":"success","is_error":false,"result":"Planned.",
137139 const served = second.opened[0].number;
138140 expect(
139141 app.db
140 .query("SELECT 1 FROM issue_dependency WHERE issue_id = ?1 AND blocker_id = (SELECT id FROM issue WHERE repo_id = ?2 AND number = ?3)")
142 .query("SELECT 1 FROM issue_dependency WHERE issue_id = ?1 AND blocked_by_id = (SELECT id FROM issue WHERE repo_id = ?2 AND number = ?3)")
141143 .get(trust.umbrella.id, repo.id, served),
142144 ).not.toBeNull();
143145 }, 40_000);
test/shards.test.ts +148 −7
@@ -9,8 +9,13 @@ import { tmpdir } from "node:os";
99 import { join } from "node:path";
1010 import {
1111 SECONDS_PER_BYTE_DEFAULT,
12 GROUP_FILES,
13 GROUP_SECONDS,
14 GROUP_UNDER,
1215 SHARDS_MAX,
1316 formatTimes,
17 groupFiles,
18 parseTestTimes,
1419 parseTimes,
1520 parseShardSpec,
1621 shardCount,
@@ -177,18 +182,51 @@ describe("parseTimes", () => {
177182 ]);
178183 });
179184
180 test("formatTimes writes what parseTimes reads, sorted, to a tenth", () => {
185 test("formatTimes writes what parseTimes reads: files to a tenth, tests to a hundredth, the total", () => {
181186 const text = formatTimes(
182187 new Map([
183188 ["./test/b.test.ts", 1.26],
184189 ["test/a.test.ts", 50.04],
185190 ]),
191 new Map([
192 ["test/b.test.ts > d > t", 0.123],
193 ["test/a.test.ts > x", 2],
194 ]),
195 291.06,
186196 );
187197 expect(text).toBe(
188 '{\n "test/a.test.ts": 50,\n "test/b.test.ts": 1.3\n}\n',
198 '{\n "total": 291.1,\n' +
199 ' "files": {\n "test/a.test.ts": 50,\n "test/b.test.ts": 1.3\n },\n' +
200 ' "tests": {\n "test/a.test.ts > x": 2,\n "test/b.test.ts > d > t": 0.12\n }\n}\n',
189201 );
190 expect(parseTimes(text).ok).toBe(true);
191 expect(formatTimes(new Map())).toBe("{}\n");
202 expect(parseTimes(text)).toEqual({
203 ok: true,
204 value: new Map([
205 ["test/a.test.ts", 50],
206 ["test/b.test.ts", 1.3],
207 ]),
208 });
209 expect(parseTestTimes(text)).toEqual(
210 new Map([
211 ["test/a.test.ts > x", 2],
212 ["test/b.test.ts > d > t", 0.12],
213 ]),
214 );
215 expect(formatTimes(new Map())).toBe(
216 '{\n "total": 0,\n "files": {},\n "tests": {}\n}\n',
217 );
218 });
219
220 test("a table with a bad test time or total is refused whole", () => {
221 for (const bad of [
222 '{ "files": [] }',
223 '{ "files": {}, "tests": { "src/a.ts > t": 1 } }',
224 '{ "files": {}, "tests": { "test/a.test.ts > t": -1 } }',
225 '{ "files": {}, "total": "long" }',
226 '{ "files": { "test/a.test.ts": 1e9 } }',
227 ])
228 expect(parseTimes(bad).ok).toBe(false);
229 expect(parseTestTimes('{ "test/a.test.ts": 1 }')).toEqual(new Map());
192230 });
193231
194232 test("the checked-in table is accepted and names only files that exist", () => {
@@ -351,6 +389,56 @@ describe("parseShardSpec", () => {
351389 });
352390 });
353391
392 describe("groupFiles", () => {
393 const weights = (table: Record<string, number>) => (file: string) =>
394 table[file] ?? 0;
395
396 test("short files share a process, long and SLOW files are alone, every file once", () => {
397 const weight = weights({
398 "test/long.test.ts": GROUP_UNDER,
399 "test/slow.test.ts": 1,
400 });
401 const list = [
402 "test/a.test.ts",
403 "test/long.test.ts",
404 "test/b.test.ts",
405 "test/slow.test.ts",
406 "test/c.test.ts",
407 ];
408 const slices = groupFiles(list, weight, new Set(["test/slow.test.ts"]));
409 expect(slices).toEqual([
410 ["test/long.test.ts"],
411 ["test/slow.test.ts"],
412 // A long file between short ones does not break their group.
413 ["test/a.test.ts", "test/b.test.ts", "test/c.test.ts"],
414 ]);
415 expect(slices.flat().sort()).toEqual([...list].sort());
416 });
417
418 test("a group holds at most GROUP_FILES files", () => {
419 const list = Array.from({ length: GROUP_FILES * 2 + 1 }, (_, i) => `test/s${i}.test.ts`);
420 const slices = groupFiles(list, () => 0.1);
421 expect(slices.map((slice) => slice.length)).toEqual([GROUP_FILES, GROUP_FILES, 1]);
422 expect(slices.flat()).toEqual(list);
423 });
424
425 test("a group holds at most GROUP_SECONDS expected seconds", () => {
426 // 4.9 s each: four fit under 20 s (19.6 s), a fifth would not (24.5 s).
427 const each = GROUP_UNDER - 0.1;
428 const fit = Math.floor(GROUP_SECONDS / each);
429 const list = Array.from({ length: fit + 1 }, (_, i) => `test/s${i}.test.ts`);
430 const slices = groupFiles(list, () => each);
431 expect(slices.map((slice) => slice.length)).toEqual([fit, 1]);
432 });
433
434 test("a weight that is not a number never joins a group", () => {
435 expect(groupFiles(["test/n.test.ts", "test/m.test.ts"], () => NaN)).toEqual([
436 ["test/n.test.ts"],
437 ["test/m.test.ts"],
438 ]);
439 });
440 });
441
354442 describe("sliceFiles", () => {
355443 test("three slices of 174 are contiguous, disjoint, covering", () => {
356444 const files = Array.from({ length: 174 }, (_, i) => `test/f${i}.test.ts`);
@@ -395,7 +483,7 @@ describe("the shard's output", () => {
395483 `import { test } from "bun:test";
396484 test("says two things, a pause apart", async () => {
397485 console.log("tick-one");
398 await Bun.sleep(1500);
486 await Bun.sleep(250);
399487 console.log("tick-two");
400488 });
401489 `,
@@ -426,9 +514,62 @@ test("says two things, a pause apart", async () => {
426514 expect(code).toBe(0);
427515 expect(firstAt).toBeGreaterThan(0);
428516 // The first line reached us while the test was still asleep.
429 expect(ended - firstAt).toBeGreaterThan(1000);
517 expect(ended - firstAt).toBeGreaterThan(200);
430518 expect(text).toContain("tick-two");
519 // A lone file is timed test by test, from its own JUnit report.
520 expect(text).toMatch(
521 /^Slowest tests: live › says two things, a paus… 0\.[2-9]s \d+%$/m,
522 );
431523 expect(text).toContain("── shard 1/1: live.test.ts");
432 expect(text).toMatch(/── shard 1\/1 done \(exit 0, [\d.]+s\)/);
524 expect(text).toMatch(/── shard 1\/1 done \(exit 0, [\d.]+s, \d+ MB\)/);
525 }, 30_000);
526
527 // Short files each paid a bun start for a second of tests (#1242): the
528 // runner groups them into one `bun test --isolate`, and still times
529 // each file — its module load and hooks too, which JUnit never sees.
530 test("short files share one process, each in its own globals, each timed", async () => {
531 const dir = mkdtempSync(join(tmpdir(), "shards-group-"));
532 writeFileSync(
533 join(dir, "first.test.ts"),
534 `import { expect, test } from "bun:test";
535 (globalThis as Record<string, unknown>)["leaked"] = true;
536 await Bun.sleep(400);
537 test("loads slowly", () => expect(1).toBe(1));
538 `,
539 );
540 writeFileSync(
541 join(dir, "second.test.ts"),
542 `import { expect, test } from "bun:test";
543 test("sees nothing the first file left", () => {
544 expect((globalThis as Record<string, unknown>)["leaked"]).toBeUndefined();
545 });
546 `,
547 );
548 const script = new URL("../scripts/test-shards.ts", import.meta.url)
549 .pathname;
550 const child = Bun.spawn(
551 ["bun", script, "first.test.ts", "second.test.ts"],
552 {
553 cwd: dir,
554 env: { ...process.env, FORGE_CHECK_SHARDS: "1" },
555 stdin: "ignore",
556 stdout: "pipe",
557 stderr: "pipe",
558 },
559 );
560 const text = await new Response(child.stdout).text();
561 const code = await child.exited;
562 rmSync(dir, { recursive: true, force: true });
563 expect(text).toContain("2 files serial in 1 bun tests");
564 expect(text).toContain("── shard 1/1: first.test.ts second.test.ts");
565 expect(text).toContain("Ran 2 tests across 2 files");
566 expect(code).toBe(0);
567 // The first file's time is its module load's 0.4 s sleep; the second
568 // file's is its own, with no bun start in front of it.
569 const took = (file: string): number =>
570 Number(new RegExp(`^ ${file} ([\\d.]+)s$`, "m").exec(text)?.[1]);
571 expect(took("first.test.ts")).toBeGreaterThanOrEqual(0.4);
572 expect(took("first.test.ts")).toBeLessThan(5);
573 expect(took("second.test.ts")).toBeLessThan(0.4);
433574 }, 30_000);
434575 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs