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

No flaky tests: ten green runs to join the gate, a nightly flake hunt in random order, mechanical quarantine #1268

Closed opened this in answer to
Closed without merging

scout/forge:scout/1243-no-flaky-tests-ten-green-runs-to-join-th → main 2 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
7 files changed +675 −3
.forgejo/workflows/flake-hunt.yml added +61
@@ -0,0 +1,61 @@
1 name: flake-hunt
2 # Nightly: the whole gate five times in random order, a fresh seed each, on
3 # the runner's own load. A test red in some runs and green in others is
4 # flaky: the hunt files an issue with the failure text, the seed and this
5 # run, moves the file from GATE to EXCLUDED, and proposes that as a pull.
6 # Nobody hand-edits the list. See scripts/flake.ts.
7 on:
8 schedule:
9 - cron: "17 2 * * *"
10 workflow_dispatch: {}
11
12 jobs:
13 hunt:
14 runs-on: isolated
15 timeout-minutes: 120
16 env:
17 REGISTRY: forgejo-http.forgejo.svc.cluster.local:3000
18 steps:
19 - name: clone main
20 env:
21 TOKEN: ${{ github.token }}
22 run: |
23 set -eu
24 git clone "http://x-access-token:$TOKEN@$REGISTRY/$GITHUB_REPOSITORY.git" src
25 cd src
26 bun install --frozen-lockfile
27
28 - name: hunt
29 id: hunt
30 working-directory: src
31 env:
32 FORGE_API: http://${{ env.REGISTRY }}/api/v1
33 FORGE_REPO: ${{ github.repository }}
34 FORGE_TOKEN: ${{ github.token }}
35 FORGE_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
36 run: |
37 set +e
38 bun scripts/flake-hunt.ts hunt --quarantine
39 echo "code=$?" >> "$GITHUB_OUTPUT"
40
41 - name: propose the quarantine
42 if: steps.hunt.outputs.code == '1'
43 working-directory: src
44 env:
45 TOKEN: ${{ github.token }}
46 run: |
47 set -eu
48 git diff --quiet scripts/gate.ts && exit 0
49 branch="flake/$(date -u +%Y-%m-%d)"
50 git config user.name "flake-hunt"
51 git config user.email "[email protected]"
52 git checkout -q -b "$branch"
53 git commit -qam "Quarantine flaky tests found by the nightly hunt"
54 git push -q origin "$branch"
55 curl -fsS -X POST -H "Authorization: token $TOKEN" -H "Content-Type: application/json" \
56 "http://$REGISTRY/api/v1/repos/$GITHUB_REPOSITORY/pulls" \
57 -d "{\"title\":\"Quarantine flaky tests ($branch)\",\"head\":\"$branch\",\"base\":\"main\",\"body\":\"Moved by the hunt, not by hand; each file's issue carries the failure, seed and run.\"}"
58
59 - name: fail when the hunt broke
60 if: steps.hunt.outputs.code == '2'
61 run: exit 1
CLAUDE.md +6
@@ -86,6 +86,12 @@ 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 - **A flaky test is a red that teaches nothing.** A file joins `GATE` only
90 with ten green random-order runs under load in the pull
91 (`bun scripts/flake-hunt.ts admit test/x.test.ts`); the nightly hunt moves
92 flaky files to `EXCLUDED` itself, so never hand-edit that move. Never add
93 `retry` — fix the cause: a shared port, a real clock, order dependence, a
94 leaked server, a timeout near the real duration.
8995 - **Every non-trivial change ships with a test.** Prefer protocol-level tests
9096 that boot a real app (`createApp` + `serve`) over unit mocks. Adversarial
9197 tests (can this be bypassed?) are worth more than happy-path ones.
README.md +24 −2
@@ -439,8 +439,30 @@ Every `test/*.test.ts` is either in `GATE` or in `EXCLUDED` with a one-line
439439 reason and the issue that owns admitting it; `test/check-list.test.ts` goes
440440 red on a file in neither, in both, or named without existing, so a new test
441441 file never sits outside the gate silently. A file joins the gate by moving
442 from `EXCLUDED` to `GATE` in a pull whose check is green — that pull is the
443 proof it passes.
442 from `EXCLUDED` to `GATE` in a pull whose check is green and whose description
443 carries the record of ten green runs in random order under load:
444 `bun scripts/flake-hunt.ts admit test/x.test.ts` runs the file ten times with
445 `--randomize` and a fresh seed each, beside one busy loop per core, prints the
446 record and exits non-zero unless all ten are green.
447
448 **No flaky tests.** Nightly, `.forgejo/workflows/flake-hunt.yml` runs the whole
449 gate five times with `--randomize` and a fresh seed each
450 (`bun scripts/flake-hunt.ts hunt --quarantine`). A test red in some runs and
451 green in others is flaky: the hunt files an issue carrying the failure text,
452 the seed and the run, names the usual root causes (a shared port, a real clock,
453 order dependence, a leaked server, a timeout set near the real duration), moves
454 the file from `GATE` to `EXCLUDED` under that issue and proposes it as a pull.
455 Nobody hand-edits the list. A test red in every run is broken, not flaky, and
456 the check already says so. The fix is the shape of the test, never a retry:
457 `test/flake.test.ts` fails on `--retry`, a bunfig `retry`, or a `{ retry: N }`
458 anywhere in the gate.
459
460 Bun's own flags are used where they fit: `--randomize --seed=N` for every hunt
461 and admission run, and `--shard` for slicing (our `--shard N/M` is passed
462 through the same way). Not adopted: `--rerun-each` (one seed for every rerun,
463 so ten reruns explore one order, where admission needs ten seeds) and
464 `--parallel` (implies `--isolate` and would change the load the gate is judged
465 under); `scripts/shards.ts` keeps balancing by recorded duration.
444466
445467 The gate also refuses hollow work. `test/hollow.test.ts` runs
446468 `scripts/hollow.ts`, which names an exported function in `src/actions/` that
scripts/flake-hunt.ts added +172
@@ -0,0 +1,172 @@
1 /**
2 * Flake hunting and admission, by machine.
3 *
4 * bun scripts/flake-hunt.ts hunt [--runs 5] [--quarantine]
5 * The gate's files HUNT_RUNS times, `--randomize`, a fresh seed each.
6 * A test red in some runs and green in others is flaky: with
7 * `--quarantine` each flaky file gets an issue (FORGE_API, FORGE_REPO,
8 * FORGE_TOKEN) and moves from GATE to EXCLUDED under that issue.
9 * bun scripts/flake-hunt.ts admit test/x.test.ts [--runs 10]
10 * The file ADMISSION_RUNS times in random order, under load; prints the
11 * record the admitting pull carries. Exits non-zero unless all green.
12 *
13 * The load is the gate's own: `scripts/test-shards.ts --gate` on the same box.
14 * `admit` adds as many busy loops as there are cores beside the test.
15 */
16
17 import { availableParallelism } from "node:os";
18 import { readFileSync, writeFileSync } from "node:fs";
19 import {
20 admissionRecord,
21 admitted,
22 ADMISSION_RUNS,
23 findBroken,
24 findFlakes,
25 HUNT_RUNS,
26 issueFor,
27 parseRun,
28 quarantine,
29 type Run,
30 } from "./flake.ts";
31
32 const GATE_FILE = new URL("./gate.ts", import.meta.url).pathname;
33 const [mode, ...rest] = process.argv.slice(2);
34
35 function takeNumber(flag: string, fallback: number): number {
36 const at = rest.indexOf(flag);
37 if (at === -1) return fallback;
38 const n = Number(rest[at + 1]);
39 if (!Number.isInteger(n) || n < 1 || n > 100) {
40 console.error(`${flag} needs a whole number from 1 to 100`);
41 process.exit(2);
42 }
43 return n;
44 }
45
46 const freshSeed = (): number => crypto.getRandomValues(new Uint32Array(1))[0]!;
47
48 async function bunTest(
49 args: string[],
50 ): Promise<{ code: number; output: string }> {
51 const child = Bun.spawn(["bun", ...args], {
52 stdout: "pipe",
53 stderr: "pipe",
54 env: { ...process.env, FORGE_CHECK_SHARDS: "1" },
55 });
56 const [out, err, code] = await Promise.all([
57 new Response(child.stdout).text(),
58 new Response(child.stderr).text(),
59 child.exited,
60 ]);
61 return { code, output: `${out}\n${err}` };
62 }
63
64 /** Busy children, one per core, for as long as `fn` runs. */
65 async function underLoad<T>(fn: () => Promise<T>): Promise<T> {
66 const burners = Array.from({ length: availableParallelism() }, () =>
67 Bun.spawn(["bun", "-e", "for(;;){}"], {
68 stdout: "ignore",
69 stderr: "ignore",
70 }),
71 );
72 try {
73 return await fn();
74 } finally {
75 for (const b of burners) b.kill();
76 }
77 }
78
79 async function hunt(): Promise<number> {
80 const n = takeNumber("--runs", HUNT_RUNS);
81 const url = process.env.FORGE_RUN_URL ?? "";
82 const runs: Run[] = [];
83 for (let i = 0; i < n; i++) {
84 const seed = freshSeed();
85 console.log(`hunt run ${i + 1}/${n}: seed ${seed}`);
86 const { output } = await bunTest([
87 "scripts/test-shards.ts",
88 "--timeout",
89 "60000",
90 "--gate",
91 "--randomize",
92 `--seed=${seed}`,
93 ]);
94 runs.push(parseRun(output, seed, url));
95 }
96 const flakes = findFlakes(runs);
97 for (const name of findBroken(runs)) console.log(`red in every run: ${name}`);
98 if (flakes.length === 0) {
99 console.log(`no flaky test in ${n} runs`);
100 return 0;
101 }
102 const byFile = new Map<string, typeof flakes>();
103 for (const f of flakes)
104 byFile.set(f.file, [...(byFile.get(f.file) ?? []), f]);
105 for (const [file, list] of byFile) {
106 console.log(`FLAKY ${file}: ${list.map((f) => f.name).join("; ")}`);
107 if (!rest.includes("--quarantine")) continue;
108 const api = process.env.FORGE_API;
109 const repo = process.env.FORGE_REPO;
110 const token = process.env.FORGE_TOKEN;
111 if (!api || !repo || !token) {
112 console.error("--quarantine needs FORGE_API, FORGE_REPO and FORGE_TOKEN");
113 return 2;
114 }
115 const res = await fetch(`${api}/repos/${repo}/issues`, {
116 method: "POST",
117 headers: {
118 authorization: `token ${token}`,
119 "content-type": "application/json",
120 },
121 body: JSON.stringify(issueFor(file, list)),
122 });
123 const made = (await res.json()) as { number?: number };
124 if (!res.ok || !Number.isInteger(made.number)) {
125 console.error(`could not file the issue for ${file}: ${res.status}`);
126 return 2;
127 }
128 writeFileSync(
129 GATE_FILE,
130 quarantine(readFileSync(GATE_FILE, "utf8"), file, made.number!),
131 );
132 console.log(`quarantined ${file} under #${made.number}`);
133 }
134 return 1;
135 }
136
137 async function admit(): Promise<number> {
138 const file = rest.find((a) => /^test\/[\w./-]+\.test\.ts$/.test(a));
139 if (!file) {
140 console.error(
141 "admit needs a file: bun scripts/flake-hunt.ts admit test/x.test.ts",
142 );
143 return 2;
144 }
145 const n = takeNumber("--runs", ADMISSION_RUNS);
146 const results: { seed: number; green: boolean }[] = [];
147 await underLoad(async () => {
148 for (let i = 0; i < n; i++) {
149 const seed = freshSeed();
150 const { code } = await bunTest([
151 "test",
152 "--timeout",
153 "60000",
154 "--randomize",
155 `--seed=${seed}`,
156 file,
157 ]);
158 results.push({ seed, green: code === 0 });
159 }
160 });
161 console.log(admissionRecord(file, results));
162 return admitted(results) ? 0 : 1;
163 }
164
165 if (mode === "hunt") process.exit(await hunt());
166 else if (mode === "admit") process.exit(await admit());
167 else {
168 console.error(
169 "usage: flake-hunt.ts hunt [--runs N] [--quarantine] | admit test/x.test.ts [--runs N]",
170 );
171 process.exit(2);
172 }
scripts/flake.ts added +236
@@ -0,0 +1,236 @@
1 /**
2 * What a flake is, and what is done about one — plain data in, plain data out.
3 *
4 * A test that fails in one run and passes in another, over the same code, is
5 * flaky. `scripts/flake-hunt.ts` runs the gate several times in random order
6 * and hands each run's output here; this module names the flaky tests, writes
7 * the issue that carries the evidence, and moves the file from `GATE` to
8 * `EXCLUDED` in `scripts/gate.ts` — so nobody hand-edits the list.
9 */
10
11 /** Green runs, in random order under the gate's own load, to join the gate. */
12 export const ADMISSION_RUNS = 10;
13 /** Whole-suite runs of the nightly hunt, each with a fresh seed. */
14 export const HUNT_RUNS = 5;
15
16 /** The causes a flake has; the fix is the shape, never a retry. */
17 export const ROOT_CAUSES: readonly { name: string; fix: string }[] = [
18 {
19 name: "a shared port",
20 fix: "listen on port 0 and read the port back; never a number two files can both want",
21 },
22 {
23 name: "a real clock",
24 fix: "inject the clock the code already takes; never sleep until something is due",
25 },
26 {
27 name: "order dependence",
28 fix: "each test makes its own state; none reads what an earlier one left",
29 },
30 {
31 name: "a leaked server",
32 fix: "close every server, socket and child in afterEach/afterAll, even on failure",
33 },
34 {
35 name: "a timeout set near the real duration",
36 fix: "make the work fast, or wait on the event itself; never raise the number to fit a loaded box",
37 },
38 ];
39
40 export type Outcome = {
41 file: string;
42 name: string;
43 pass: boolean;
44 text: string;
45 };
46 export type Run = { seed: number; url: string; outcomes: Outcome[] };
47
48 const FILE_LINE = /^(test\/[\w./-]+\.test\.ts):\s*$/;
49 const RESULT_LINE = /^\((pass|fail)\) (.+?)(?: \[[\d.]+m?s\])?\s*$/;
50
51 /** The per-test outcomes in one `bun test` output; failure text rides along. */
52 export function parseRun(output: string, seed: number, url = ""): Run {
53 const outcomes: Outcome[] = [];
54 let file = "";
55 let pending: string[] = [];
56 for (const line of output.split("\n")) {
57 const header = FILE_LINE.exec(line);
58 if (header) {
59 file = header[1]!;
60 pending = [];
61 continue;
62 }
63 const result = RESULT_LINE.exec(line);
64 if (result) {
65 const pass = result[1] === "pass";
66 outcomes.push({
67 file,
68 name: result[2]!,
69 pass,
70 text: pass ? "" : pending.join("\n").trim(),
71 });
72 pending = [];
73 continue;
74 }
75 pending.push(line);
76 if (pending.length > 60) pending.shift();
77 }
78 return { seed, url, outcomes };
79 }
80
81 export type Flake = {
82 file: string;
83 name: string;
84 failed: number;
85 passed: number;
86 /** The first failing run's seed, link and failure text. */
87 seed: number;
88 url: string;
89 text: string;
90 };
91
92 /** A test that failed in some runs and passed in others. */
93 export function findFlakes(runs: readonly Run[]): Flake[] {
94 const seen = new Map<string, Flake>();
95 for (const run of runs)
96 for (const o of run.outcomes) {
97 const key = `${o.file}\0${o.name}`;
98 const flake = seen.get(key) ?? {
99 file: o.file,
100 name: o.name,
101 failed: 0,
102 passed: 0,
103 seed: run.seed,
104 url: run.url,
105 text: "",
106 };
107 if (o.pass) flake.passed++;
108 else {
109 if (flake.failed === 0) {
110 flake.seed = run.seed;
111 flake.url = run.url;
112 flake.text = o.text;
113 }
114 flake.failed++;
115 }
116 seen.set(key, flake);
117 }
118 return [...seen.values()].filter((f) => f.failed > 0 && f.passed > 0);
119 }
120
121 /** Tests red in every run: broken, not flaky — the check already says so. */
122 export function findBroken(runs: readonly Run[]): string[] {
123 const flaky = new Set(findFlakes(runs).map((f) => `${f.file} > ${f.name}`));
124 const red = new Set<string>();
125 for (const run of runs)
126 for (const o of run.outcomes)
127 if (!o.pass && !flaky.has(`${o.file} > ${o.name}`))
128 red.add(`${o.file} > ${o.name}`);
129 return [...red].sort();
130 }
131
132 /** The issue the hunt files for one file's flakes. */
133 export function issueFor(
134 file: string,
135 flakes: readonly Flake[],
136 ): {
137 title: string;
138 body: string;
139 } {
140 const first = flakes[0]!;
141 const fence = "```";
142 const lines = [
143 `The nightly flake hunt ran the suite ${first.failed + first.passed} times in random order and \`${file}\` failed in some runs and passed in others. It is out of the gate (\`EXCLUDED\`) until it is fixed.`,
144 "",
145 ];
146 for (const f of flakes) {
147 lines.push(
148 `### ${f.name}`,
149 "",
150 `- failed ${f.failed} of ${f.failed + f.passed} runs`,
151 `- seed: \`${f.seed}\` (\`bun test --randomize --seed=${f.seed} ${file}\`)`,
152 `- run that failed: ${f.url || "(local run)"}`,
153 "",
154 fence,
155 f.text.slice(-3000) || "(no failure text captured)",
156 fence,
157 "",
158 );
159 }
160 lines.push(
161 "## Name the root cause",
162 "",
163 "Tick the one that holds, and fix the shape. A retry is not a fix: `retry` is refused anywhere in the gate.",
164 "",
165 ...ROOT_CAUSES.map((c) => `- [ ] ${c.name} — ${c.fix}`),
166 "",
167 `To rejoin the gate: fix it, then \`bun scripts/flake-hunt.ts admit ${file}\` and paste its ${ADMISSION_RUNS}-run record into the pull that moves the file back to \`GATE\`.`,
168 );
169 return { title: `Flaky: ${file}`, body: lines.join("\n") };
170 }
171
172 const entryFor = (file: string, reason: string, issue: number): string =>
173 [
174 " {",
175 ` file: ${JSON.stringify(file)},`,
176 ` reason: ${JSON.stringify(reason)},`,
177 ` issue: ${issue},`,
178 " },",
179 "",
180 ].join("\n");
181
182 /** `scripts/gate.ts` with `file` moved from GATE to EXCLUDED under `issue`. */
183 export function quarantine(
184 source: string,
185 file: string,
186 issue: number,
187 reason = "flaky: failed in one run and passed in another (nightly hunt)",
188 ): string {
189 const line = ` ${JSON.stringify(file)},\n`;
190 const at = source.indexOf(line);
191 const gateEnd = source.indexOf("\n];", source.indexOf("export const GATE"));
192 if (at === -1 || at > gateEnd) return source;
193 const without = source.slice(0, at) + source.slice(at + line.length);
194 const marker = without.indexOf(
195 "\n];",
196 without.indexOf("export const EXCLUDED"),
197 );
198 return (
199 without.slice(0, marker + 1) +
200 entryFor(file, reason, issue) +
201 without.slice(marker + 1)
202 );
203 }
204
205 /** A retry anywhere in what the gate runs: the lines that carry one. */
206 export function retries(name: string, source: string): string[] {
207 const found: string[] = [];
208 source.split("\n").forEach((line, i) => {
209 if (
210 /--retry\b/.test(line) ||
211 /^\s*retry\s*=/.test(line) ||
212 /\{[^}"'`]*\bretry\s*:\s*\d/.test(line) ||
213 /\bbun:test\b.*\bretry\b/.test(line)
214 )
215 found.push(`${name}:${i + 1}: ${line.trim()}`);
216 });
217 return found;
218 }
219
220 /** The record an admitting pull carries. */
221 export function admissionRecord(
222 file: string,
223 runs: readonly { seed: number; green: boolean }[],
224 ): string {
225 const green = runs.filter((r) => r.green).length;
226 return [
227 `admission: ${file} — ${green}/${runs.length} green, random order, under gate load`,
228 ...runs.map(
229 (r, i) => ` run ${i + 1}: seed ${r.seed} ${r.green ? "green" : "RED"}`,
230 ),
231 ].join("\n");
232 }
233
234 /** Admitted only when every one of the required runs is green. */
235 export const admitted = (runs: readonly { green: boolean }[]): boolean =>
236 runs.length >= ADMISSION_RUNS && runs.every((r) => r.green);
scripts/gate.ts +5 −1
@@ -9,7 +9,10 @@
99 * cannot sit outside the gate silently.
1010 *
1111 * A file joins the gate by moving from `EXCLUDED` to `GATE` in a pull whose
12 * check is green.
12 * check is green AND whose description carries the record of ten green runs
13 * in random order under load (`bun scripts/flake-hunt.ts admit <file>`). A file
14 * leaves it only through `scripts/flake-hunt.ts`, never by hand: the nightly
15 * hunt (`.forgejo/workflows/flake-hunt.yml`) quarantines what flakes.
1316 */
1417
1518 export type Exclusion = {
@@ -216,6 +219,7 @@ export const GATE: readonly string[] = [
216219 "test/counts.test.ts",
217220 "test/crew-loop.test.ts",
218221 "test/crew-totals.test.ts",
222 "test/flake.test.ts",
219223 ];
220224
221225 export const EXCLUDED: readonly Exclusion[] = [
test/flake.test.ts added +171
@@ -0,0 +1,171 @@
1 /**
2 * The flake machinery (`scripts/flake.ts`): what is flaky, what the issue
3 * carries, how quarantine edits the list, and that nothing in the gate retries.
4 */
5
6 import { describe, expect, test } from "bun:test";
7 import { readdirSync, readFileSync } from "node:fs";
8 import { auditGate, GATE } from "../scripts/gate.ts";
9 import {
10 admissionRecord,
11 admitted,
12 ADMISSION_RUNS,
13 findBroken,
14 findFlakes,
15 HUNT_RUNS,
16 issueFor,
17 parseRun,
18 quarantine,
19 retries,
20 ROOT_CAUSES,
21 } from "../scripts/flake.ts";
22
23 const root = new URL("..", import.meta.url).pathname;
24 const read = (path: string): string => readFileSync(`${root}${path}`, "utf8");
25
26 const output = (second: "pass" | "fail") =>
27 [
28 "test/a.test.ts:",
29 "(pass) steady [3.00ms]",
30 `(${second}) wobbly [4.00ms]`,
31 "test/b.test.ts:",
32 "error: expected 1, got 2",
33 "(fail) always red [1.00ms]",
34 ].join("\n");
35
36 describe("finding flakes", () => {
37 const runs = [
38 parseRun(output("pass"), 11, "http://run/1"),
39 parseRun(output("fail"), 22, "http://run/2"),
40 ];
41
42 test("a test red in one run and green in another is flaky", () => {
43 const flakes = findFlakes(runs);
44 expect(flakes.map((f) => `${f.file} > ${f.name}`)).toEqual([
45 "test/a.test.ts > wobbly",
46 ]);
47 expect(flakes[0]).toMatchObject({
48 failed: 1,
49 passed: 1,
50 seed: 22,
51 url: "http://run/2",
52 });
53 });
54
55 test("a test red every time is broken, not flaky", () => {
56 expect(findBroken(runs)).toEqual(["test/b.test.ts > always red"]);
57 });
58
59 test("the failure text rides with the outcome", () => {
60 expect(runs[0]!.outcomes.at(-1)!.text).toBe("error: expected 1, got 2");
61 });
62
63 test("all green is not flaky", () => {
64 expect(
65 findFlakes([parseRun(output("pass"), 1), parseRun(output("pass"), 2)]),
66 ).toEqual([]);
67 });
68 });
69
70 describe("the issue", () => {
71 test("carries the failure, the seed, the run and every root cause", () => {
72 const failing = ["test/a.test.ts:", "boom here", "(fail) wobbly [1ms]"];
73 const flake = findFlakes([
74 parseRun(output("pass"), 1),
75 parseRun(failing.join("\n"), 99, "http://run/9"),
76 ])[0]!;
77 const { title, body } = issueFor("test/a.test.ts", [flake]);
78 expect(title).toBe("Flaky: test/a.test.ts");
79 expect(body).toContain("boom here");
80 expect(body).toContain("--seed=99");
81 expect(body).toContain("http://run/9");
82 for (const cause of ROOT_CAUSES) expect(body).toContain(cause.name);
83 expect(ROOT_CAUSES.map((c) => c.name)).toEqual([
84 "a shared port",
85 "a real clock",
86 "order dependence",
87 "a leaked server",
88 "a timeout set near the real duration",
89 ]);
90 });
91 });
92
93 describe("quarantine", () => {
94 const source = read("scripts/gate.ts");
95
96 test("moves the file from GATE to EXCLUDED under the issue", async () => {
97 const moved = quarantine(source, "test/apps-idle.test.ts", 4242);
98 expect(moved.split(' "test/apps-idle.test.ts",\n')).toHaveLength(1);
99 expect(moved).toContain("export function auditGate");
100 const dir = `${process.env.TMPDIR ?? "/tmp"}/flake-${crypto.randomUUID()}`;
101 await Bun.write(`${dir}/gate.ts`, moved);
102 const mod = (await import(`${dir}/gate.ts`)) as {
103 GATE: string[];
104 EXCLUDED: { file: string; reason: string; issue: number }[];
105 };
106 const present = readdirSync(`${root}test`)
107 .filter((n) => n.endsWith(".test.ts"))
108 .map((n) => `test/${n}`);
109 expect(auditGate(present, mod.GATE, mod.EXCLUDED)).toEqual([]);
110 expect(mod.GATE).not.toContain("test/apps-idle.test.ts");
111 expect(mod.EXCLUDED.at(-1)).toMatchObject({
112 file: "test/apps-idle.test.ts",
113 issue: 4242,
114 });
115 });
116
117 test("a file not in GATE is left alone", () => {
118 expect(quarantine(source, "test/apps-ws.test.ts", 1)).toBe(source);
119 expect(quarantine(source, "test/nope.test.ts", 1)).toBe(source);
120 });
121 });
122
123 describe("admission", () => {
124 test("needs ten runs, all green", () => {
125 expect(ADMISSION_RUNS).toBe(10);
126 expect(HUNT_RUNS).toBe(5);
127 const green = Array.from({ length: 10 }, () => ({
128 seed: 1,
129 green: true,
130 }));
131 expect(admitted(green)).toBe(true);
132 expect(admitted(green.slice(1))).toBe(false);
133 expect(admitted([...green.slice(1), { seed: 2, green: false }])).toBe(
134 false,
135 );
136 });
137
138 test("the record names every seed", () => {
139 const record = admissionRecord("test/x.test.ts", [
140 { seed: 5, green: true },
141 { seed: 6, green: false },
142 ]);
143 expect(record).toContain("1/2 green");
144 expect(record).toContain("run 2: seed 6 RED");
145 });
146 });
147
148 describe("no retry in the gate", () => {
149 test("the detector sees a retry", () => {
150 expect(retries("x", "bun test --retry=3")).toHaveLength(1);
151 expect(retries("x", "retry = 2")).toHaveLength(1);
152 expect(retries("x", 'test("a", () => {}, { retry: 2 });')).toHaveLength(1);
153 expect(retries("x", 'expect(text).toContain("retry: 1000");')).toEqual([]);
154 });
155
156 test("nothing the gate runs or is run by retries", () => {
157 const named = [
158 "forge.json",
159 "bunfig.toml",
160 "package.json",
161 "scripts/test-shards.ts",
162 "scripts/check.ts",
163 ...readdirSync(`${root}.forgejo/workflows`).map(
164 (n) => `.forgejo/workflows/${n}`,
165 ),
166 // This file holds the detector's own examples.
167 ...GATE.filter((f) => f !== "test/flake.test.ts"),
168 ];
169 expect(named.flatMap((path) => retries(path, read(path)))).toEqual([]);
170 });
171 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs