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

The fast tier runs its files in one bun test --parallel --no-isolate, longest first, in place of N slices #17509

opened this

Merged 26h 52m ago, live in production

shards-parallel → main 0 commits 1 thread · 1 unresolved

  • Merged. shards-parallel was merged into main as 641629b.

Review

Sign in to review this change.
5 files changed +202 −9
forge.json +1 −1
@@ -49,7 +49,7 @@
4949 }
5050 },
5151 "check": {
52 "fast": "bun scripts/gate.ts && bun scripts/design-drift.ts && mkdir -p .forge-cache && GOMEMLIMIT=6GiB ./node_modules/typescript/bin/tsc --noEmit --incremental --tsBuildInfoFile .forge-cache/tsc.tsbuildinfo && bun scripts/test-shards.ts --timeout 60000 --tier fast --diff $FORGE_CHECK_BASE..HEAD --learned \"$FORGE_CHECK_LEARNED\"",
52 "fast": "bun scripts/gate.ts && bun scripts/design-drift.ts && mkdir -p .forge-cache && GOMEMLIMIT=6GiB ./node_modules/typescript/bin/tsc --noEmit --incremental --tsBuildInfoFile .forge-cache/tsc.tsbuildinfo && bun scripts/test-shards.ts --parallel --timeout 60000 --tier fast --diff $FORGE_CHECK_BASE..HEAD --learned \"$FORGE_CHECK_LEARNED\"",
5353 "run": "bun scripts/gate.ts && bun scripts/design-drift.ts && mkdir -p .forge-cache && GOMEMLIMIT=6GiB ./node_modules/typescript/bin/tsc --noEmit --incremental --tsBuildInfoFile .forge-cache/tsc.tsbuildinfo",
5454 "full": "bun scripts/gate.ts && bun scripts/design-drift.ts && mkdir -p .forge-cache && GOMEMLIMIT=6GiB ./node_modules/typescript/bin/tsc --noEmit --incremental --tsBuildInfoFile .forge-cache/tsc.tsbuildinfo && bun test test/client-size.test.ts",
5555 "verify": "{ bun scripts/reach.ts || true; } && bun scripts/gate.ts && bun scripts/test-shards.ts --timeout 60000 --gate --impact --keep-going --nice",
scripts/shards.ts +18
@@ -185,6 +185,24 @@ export function rulesFirst(files: readonly string[], rules: ReadonlySet<string>)
185185 return { first: files.filter(isRule), rest: files.filter((file) => !isRule(file)) };
186186 }
187187
188 /**
189 * The weights of `files` in the shape `bun test --timings` reads,
190 * `{ version: 1, files: { path: ms } }`, under each path both as given and without its leading
191 * `./`, so Bun finds it however it names it.
192 */
193 export function timingsFile(
194 files: readonly string[],
195 weight: (file: string) => number,
196 ): { version: 1; files: Record<string, number> } {
197 const out: Record<string, number> = {};
198 for (const file of files) {
199 const ms = Math.max(1, Math.round(weight(file) * 1000));
200 out[file] = ms;
201 out[file.replace(/^\.\//, "")] = ms;
202 }
203 return { version: 1, files: out };
204 }
205
188206 /**
189207 * {@link splitFiles}, with no slice over `max` files: enough slices that
190208 * every one fits, balanced by weight, and any still over (many light files
scripts/test-shards.ts +52 −8
@@ -9,6 +9,7 @@
99 * bun scripts/test-shards.ts [bun test flags…] -- a b … (test/a.test.ts …)
1010 * bun scripts/test-shards.ts [bun test flags…] --gate --impact --keep-going --nice
1111 * bun scripts/test-shards.ts --ceiling 60 [bun test flags…] test/a.test.ts …
12 * bun scripts/test-shards.ts --parallel [bun test flags…] --tier fast --diff <base>..<head>
1213 *
1314 * `--gate` runs the files `scripts/gate.ts` admits (every test file not
1415 * excluded), which is how
@@ -34,6 +35,16 @@
3435 * behind ` │ `. At most `CRASH_RERUNS` shards are re-run so. Exits
3536 * non-zero if any shard does.
3637 *
38 * `--parallel` (#16876, forge.json's check commands carry it) runs what would have been N slices as

Only the fast command in forge.json carries --parallel; verify does not. Reword to 'the fast check carries it'.

39 * one `bun test --parallel=N --no-isolate`: N warm workers take the files from one queue, longest
40 * first by the same weights (`--timings`), so no worker waits on a slice it was statically handed
41 * and no file pays a process start. Measured on a runner, 80 files 4-way: 17.6 s to 13.0 s of wall
42 * at the same CPU and the same results. Everything that reads a shard reads it as one shard of many
43 * files: its failing files are run alone ("red only beside others"), its JUnit report times each
44 * test, a breach is timed again alone and judged by CPU there, and a crash re-runs it once. Each
45 * worker gets its own TMPDIR and FORGE_APP_DATA (`test-worker-dirs.ts`). Recording, measuring,
46 * one-file-per-process runs and a run without the flag take the slices, as before.
47 *
3748 * `--keep-going` is the verification after landing (#7786): no shard stops
3849 * the rest, a file red on its own is run once more alone (green then, it
3950 * is named flaky and does not fail the run), and a measuring run writes
@@ -98,6 +109,7 @@ import {
98109 sliceFiles,
99110 splitArgs,
100111 splitCapped,
112 timingsFile,
101113 tally,
102114 weigher,
103115 besideOthers,
@@ -159,6 +171,7 @@ const gate = argv.includes("--gate");
159171 const measure = argv.includes("--impact");
160172 const keepGoing = argv.includes("--keep-going");
161173 const nice = argv.includes("--nice");
174 const parallelAsked = argv.includes("--parallel");
162175 // Every `bun test` this spawns inherits it.
163176 if (nice)
164177 try {
@@ -266,7 +279,7 @@ function takeValue(
266279 }
267280
268281 const tierArg = takeValue(
269 argv.filter((arg) => !["--record", "--gate", "--impact", "--keep-going", "--nice"].includes(arg)),
282 argv.filter((arg) => !["--record", "--gate", "--impact", "--keep-going", "--nice", "--parallel"].includes(arg)),
270283 "--tier",
271284 );
272285 const diffArg = takeValue(tierArg.rest, "--diff");
@@ -559,6 +572,10 @@ const serialFiles = !record && count.value === 1;
559572 // refreshes the time of every file it ran (#1797).
560573 const timed = !record && !serialFiles && gate && tier === "full" && "none" in shardSpec;
561574 const perFile = record || measure || serialFiles || timed;
575 // One `bun test --parallel` in place of the slices, where slices would have run (`--parallel`).
576 const parallel = parallelAsked && !perFile && count.value > 1;
577 /** A parallel shard's workers: the shard count. */
578 const workers = count.value;
562579 // The map as it was handed over; a measuring run refreshes it.
563580 const oldImpact: Map<string, string[]> = measure
564581 ? (readImpact(IMPACT, IMPACT_NAME, (line) =>
@@ -577,7 +594,9 @@ const slicesOf = (list: string[]): string[][] =>
577594 ? []
578595 : perFile
579596 ? inOrder(list).map((file) => [file])
580 : splitCapped(list, count.value, weight);
597 : parallel
598 ? [inOrder(list)]
599 : splitCapped(list, count.value, weight);
581600 // The rule and scan tests run first, on their own: a run that does not keep going stops on
582601 // their red before a behaviour test starts. Recording, measuring and a run kept going (the
583602 // verification) run every file as before.
@@ -599,6 +618,9 @@ const banner = record
599618 : timed
600619 ? `test-shards: ${files.length} files, one bun test each, ${count.value} at a time, ` +
601620 `expected ${(work / count.value).toFixed(0)}s (${work.toFixed(0)}s of work)`
621 : parallel
622 ? `test-shards: ${files.length} files in one bun test --parallel=${count.value} --no-isolate, longest first, ` +
623 `expected ${(work / count.value).toFixed(0)}s (${work.toFixed(0)}s of work)`
602624 : `test-shards: ${files.length} files in ${slices.length} shard${slices.length === 1 ? "" : "s"}, ` +
603625 `expected ${slices.map((slice) => slice.reduce((sum, file) => sum + weight(file), 0).toFixed(0) + "s").join(" ")}`;
604626 console.log(banner);
@@ -673,6 +695,19 @@ const budgetBinds = (file: string): boolean =>
673695 // A run that already asks for a report keeps it; the budget then reads no tests.
674696 const junitAsked = flags.some((flag) => flag === "--reporter" || flag.startsWith("--reporter=") || flag === "--dots");
675697
698 /** The worker preload: its own TMPDIR and FORGE_APP_DATA for each `--parallel` worker. */
699 const WORKER_DIRS = join(import.meta.dir, "test-worker-dirs.ts");
700
701 /**
702 * What a parallel shard adds to `bun test`: N workers sharing one module registry, the files'
703 * weights as a timings file (Bun starts the slowest first), and the worker preload.
704 */
705 function parallelArgs(slice: readonly string[], home: string): string[] {
706 const timings = join(home, "timings.json");
707 writeFileSync(timings, JSON.stringify(timingsFile(slice, weight)));
708 return [`--parallel=${workers}`, "--no-isolate", `--timings=${timings}`, "--preload", WORKER_DIRS];
709 }
710
676711 /**
677712 * One shard. `live` (shards running one at a time) writes the shard's
678713 * output as it arrives, between a header and a footer line; otherwise the
@@ -733,6 +768,15 @@ async function runShardIn(
733768 // Each test's CPU seconds (`scripts/test-cpu.ts`), what the budget holds a test to.
734769 const cpuOut = join(home, "cpu.txt");
735770 childEnv["FORGE_TEST_CPU_OUT"] = cpuOut;
771 // A parallel shard: N warm workers over the slice, longest first, each in directories of its own.
772 // Its alone runs (a failing file, a breach timed again) are plain `bun test`s, as a slice's are.
773 const wide = parallel && slice.length > 1 ? parallelArgs(slice, home) : [];
774 // What a parallel shard stands in for: the slices it replaces. Its ceiling is a slice's for each
775 // slice a worker would have run in turn, and it runs alone as many failing files as they would
776 // have between them.
777 const replaced = wide.length > 0 ? splitCapped(slice, workers, weight).length : 1;
778 const shardCeiling = ceilingMs * Math.max(1, Math.ceil(replaced / workers));
779 const retryCap = RETRY_CAP * replaced;
736780 let lastPid = 0;
737781 const run = async (
738782 targets: string[],
@@ -754,11 +798,11 @@ async function runShardIn(
754798 // One buffer, in arrival order: `bun test` splits its report across
755799 // stdout and stderr.
756800 const output: string[] = [];
757 const { code, cut, hung } = await childOutput(child, output, through, DRAIN_GRACE_MS, ceilingMs);
801 const { code, cut, hung } = await childOutput(child, output, through, DRAIN_GRACE_MS, shardCeiling);
758802 children.delete(child);
759803 const what = targets.length === 1 ? targets[0]!.replace(/^\.\//, "") : `a shard of ${targets.length} files`;
760804 // Killed at the ceiling: the files it ran are named, and the shard is red (#17441).
761 for (const line of [...(hung ? [hungLine(what, ceilingMs)] : []), ...(cut ? [cutLine(what)] : [])]) {
805 for (const line of [...(hung ? [hungLine(what, shardCeiling)] : []), ...(cut ? [cutLine(what)] : [])]) {
762806 output.push(line);
763807 through?.(line);
764808 }
@@ -790,7 +834,7 @@ async function runShardIn(
790834 else through(text);
791835 }
792836 : through;
793 let first = await run(paths, cover, firstThrough);
837 let first = await run(paths, [...cover, ...wide], firstThrough);
794838 // A crash outside any test re-runs the shard once, whole (#7788): the
795839 // leaked-timer class ("Cannot use a closed database" between tests) is
796840 // not this shard's tests failing. The re-run is the verdict, and its
@@ -805,7 +849,7 @@ async function runShardIn(
805849 if (live) process.stdout.write(quoted);
806850 process.stderr.write(`test-shards: re-run ${where} after a crash (exit ${first.code})\n`);
807851 started = performance.now();
808 first = await run(paths, cover, through);
852 first = await run(paths, [...cover, ...wide], through);
809853 // Green the second time: the crash is a flake, named for the check to record.
810854 if (first.code === 0) process.stderr.write(`${crashFlakeLine(where, quoted)}\n`);
811855 }
@@ -842,11 +886,11 @@ async function runShardIn(
842886 // A file that errored (not a failed test) keeps the whole shard red.
843887 const red = onlyTestFailures(report) ? failingFiles(report) : [];
844888 const alone = new Map<string, boolean>();
845 for (const file of red.slice(0, RETRY_CAP)) {
889 for (const file of red.slice(0, retryCap)) {
846890 const again = await run([file.startsWith("/") || file.startsWith("./") ? file : `./${file}`], []);
847891 alone.set(file, again.code === 0);
848892 }
849 const verdict = besideOthers(red, alone, RETRY_CAP);
893 const verdict = besideOthers(red, alone, retryCap);
850894 if (verdict.line !== null) {
851895 retried = true;
852896 const note = `${output.join("").endsWith("\n") ? "" : "\n"}test-shards: ${verdict.line}\n`;
scripts/test-worker-dirs.ts added +19
@@ -0,0 +1,19 @@
1 /**
2 * Preloaded into each worker of a `bun test --parallel` that `scripts/test-shards.ts` starts: the
3 * worker's own temp and data directories, beneath the shard's, so two workers never share a path a
4 * test writes to (a slice had a home of its own; a worker now does). Bun numbers its workers in
5 * `BUN_TEST_WORKER_ID`; outside a worker this does nothing.
6 */
7
8 import { mkdirSync } from "node:fs";
9 import { join } from "node:path";
10
11 const worker = process.env["BUN_TEST_WORKER_ID"];
12 if (worker !== undefined && /^\d+$/.test(worker))
13 for (const key of ["TMPDIR", "FORGE_APP_DATA"] as const) {
14 const base = process.env[key];
15 if (base === undefined || base === "") continue;
16 const own = join(base, `worker-${worker}`);
17 mkdirSync(own, { recursive: true });
18 process.env[key] = own;
19 }
test/shards-parallel.test.ts added +112
@@ -0,0 +1,112 @@
1 /**
2 * `scripts/test-shards.ts --parallel` (#16876): one `bun test --parallel=N --no-isolate` in place
3 * of the N slices, read as one shard of many files by everything that reads a shard. Each test here
4 * spawns the runner, which spawns `bun test`.
5 *
6 * @not-a-tree-scan: it lists only the repository's test names, to make an audit-clean fixture,
7 * and reads nothing else of the tree.
8 */
9 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
10 import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
11 import { tmpdir } from "node:os";
12 import { join } from "node:path";
13 import { presentTests } from "../scripts/gate.ts";
14 import { timingsFile } from "../scripts/shards.ts";
15
16 const script = new URL("../scripts/test-shards.ts", import.meta.url).pathname;
17 let dir = "";
18
19 const runner = async (args: string[], env: Record<string, string> = {}): Promise<{ code: number; out: string }> => {
20 const child = Bun.spawn(["bun", script, ...args], {
21 cwd: dir,
22 env: { ...process.env, FORGE_CHECK_SHARDS: "2", FORGE_CHECK_SCRATCH: join(dir, "scratch"), ...env },
23 stdin: "ignore",
24 stdout: "pipe",
25 stderr: "pipe",
26 });
27 const [out, err] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text()]);
28 return { code: await child.exited, out: out + err };
29 };
30
31 const fixture = (name: string, body: string): string => {
32 writeFileSync(join(dir, "test", name), `import { expect, test } from "bun:test";\n${body}\n`);
33 return `test/${name}`;
34 };
35
36 beforeAll(() => {
37 dir = mkdtempSync(join(tmpdir(), "forge-shards-parallel-"));
38 mkdirSync(join(dir, "test"));
39 for (const file of presentTests()) writeFileSync(join(dir, file), "");
40 });
41 afterAll(() => rmSync(dir, { recursive: true, force: true }));
42
43 describe("one bun test --parallel in place of the slices", () => {
44 test("the banner says so, every file runs, and each worker writes under a directory of its own", async () => {
45 const files = [
46 fixture("zz-a.test.ts", `test("a", () => { console.log("TMP=" + process.env.TMPDIR); expect(1).toBe(1); });`),
47 fixture("zz-b.test.ts", `test("b", () => expect(2).toBe(2));`),
48 fixture("zz-c.test.ts", `test("c", () => expect(3).toBe(3));`),
49 ];
50 const got = await runner(["--parallel", ...files]);
51 expect(got.out).toContain("test-shards: 3 files in one bun test --parallel=2 --no-isolate, longest first");
52 expect(got.out).toMatch(/TMP=\S*\/worker-\d+/);
53 expect(got.out).toMatch(/3 pass/);
54 expect(got.code).toBe(0);
55 }, 30_000);
56
57 test("without the flag the same files run in slices, as before", async () => {
58 const files = [
59 fixture("zz-a.test.ts", `test("a", () => expect(1).toBe(1));`),
60 fixture("zz-b.test.ts", `test("b", () => expect(2).toBe(2));`),
61 ];
62 const got = await runner(files);
63 expect(got.out).toContain("test-shards: 2 files in ");
64 expect(got.out).not.toContain("--parallel=");
65 expect(got.code).toBe(0);
66 }, 30_000);
67
68 test("a file red only in a worker is run alone, passes, and is named as failing only beside others", async () => {
69 const files = [
70 fixture("zz-worker.test.ts", `test("red in a worker", () => expect(process.env.BUN_TEST_WORKER_ID).toBeUndefined());`),
71 fixture("zz-b.test.ts", `test("b", () => expect(2).toBe(2));`),
72 ];
73 const got = await runner(["--parallel", ...files]);
74 expect(got.out).toContain("fails only beside others: test/zz-worker.test.ts");
75 expect(got.code).toBe(0);
76 }, 30_000);
77
78 test("a file red alone too stays red, and the tally names its test", async () => {
79 const files = [
80 fixture("zz-red.test.ts", `test("always red", () => expect(1).toBe(2));`),
81 fixture("zz-b.test.ts", `test("b", () => expect(2).toBe(2));`),
82 ];
83 const got = await runner(["--parallel", ...files]);
84 expect(got.out).toContain("(fail) always red");
85 expect(got.out).not.toContain("fails only beside others");
86 expect(got.code).toBe(1);
87 }, 30_000);
88
89 test("the budget still binds: a test spinning past it is timed again alone, by CPU, and stays red", async () => {
90 const files = [
91 fixture(
92 "zz-spin.test.ts",
93 `test("spins past the budget", () => { const end = performance.now() + 60; while (performance.now() < end) {} expect(true).toBe(true); });`,
94 ),
95 fixture("zz-b.test.ts", `test("b", () => expect(2).toBe(2));`),
96 ];
97 const got = await runner(["--parallel", "--tier", "full", ...files], { FORGE_TEST_BUDGET_SECONDS: ",0.02" });
98 expect(got.out).toContain("over the 0.02 s test budget");
99 expect(got.code).toBe(1);
100 }, 30_000);
101 });
102
103 test("the timings Bun reads: each file's weight in milliseconds, under its path with and without ./", () => {
104 const weights = new Map([
105 ["./test/a.test.ts", 2.5],
106 ["test/b.test.ts", 0.0001],
107 ]);
108 expect(timingsFile(["./test/a.test.ts", "test/b.test.ts"], (f) => weights.get(f) ?? 0)).toEqual({
109 version: 1,
110 files: { "./test/a.test.ts": 2500, "test/a.test.ts": 2500, "test/b.test.ts": 1 },
111 });
112 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs