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

A pull's new breach of a rule main already breaks is the pull's red: rule and scan reds are compared by failure text, not name #17218

opened this

Merged 35h 21m ago, live in production

fix/rule-red-texts → main 0 commits

  • Merged. fix/rule-red-texts was merged into main as c26e527.

Review

Sign in to review this change.
4 files changed +162 −9
scripts/base-run.ts +4
@@ -7,6 +7,7 @@ import { mkdirSync, rmSync } from "node:fs";
77 import { join } from "node:path";
88 import { childOutput, cutLine } from "./shard-output.ts";
99 import { failingTests, onlyTestFailures } from "./shards.ts";
10 import { failureTexts } from "../src/checks/base_red.ts";
1011
1112 export interface BaseRun {
1213 /** The shard home the scratch goes under. */
@@ -20,6 +21,8 @@ export interface BaseRun {
2021 readonly env: Readonly<Record<string, string | undefined>>;
2122 /** Children still running, for the script's own exit to stop. */
2223 readonly children: Set<Bun.Subprocess>;
24 /** Where a red run leaves its failing tests' texts (`failureTexts`), the last red's kept. */
25 readonly texts?: Map<string, ReadonlyMap<string, readonly string[]>>;
2326 }
2427
2528 /** Run `file` once as run `run`: "green", or the tests that failed (none named when it crashed). */
@@ -50,6 +53,7 @@ export async function baseRun(input: BaseRun, run: number, stop: AbortSignal): P
5053 rmSync(scratch.data, { recursive: true, force: true });
5154 }
5255 const report = output.join("");
56 input.texts?.set(input.file, failureTexts(report).get(input.file) ?? new Map());
5357 // A crash or load error names no test: nothing to compare the pull's red with.
5458 return onlyTestFailures(report) ? [...failingTests(report).values()].flat() : [];
5559 }
scripts/test-shards.ts +13 −4
@@ -131,7 +131,7 @@ import { FLAKY_ALONE, onlyFiles } from "../src/checks/verify.ts";
131131 import { crashFlakeLine } from "../src/checks/flake.ts";
132132 import { DROPPED_FILE, dropDisagreed, droppedLine, finalCode, formatKept, keptLine, mergeKept, parseKept, type KeptEntry } from "../src/checks/kept.ts";
133133 import { answerKept, freshKept } from "./kept-input.ts";
134 import { askBase, baseVerdict, untilRed, type OnBase } from "../src/checks/base_red.ts";
134 import { askBase, baseVerdict, failureTexts, untilRed, type OnBase } from "../src/checks/base_red.ts";
135135 import { baseRun } from "./base-run.ts";
136136
137137 const TIMES = new URL("./test-times.json", import.meta.url).pathname;
@@ -1083,6 +1083,8 @@ const busy: Busy[] = [];
10831083 // Never more side by side than the count: capped slices outnumber it.
10841084 const width = (n: number): number => (serialFiles ? 1 : Math.max(1, Math.min(count.value, n)));
10851085 const ruleResults = await pool(width(ruleSlices.length), 0, ruleSlices.length, busy);
1086 /** The rule and scan files, as the red names them. */
1087 const ruleSet = new Set(ruleFiles.map((file) => file.replace(/^\.\//, "")));
10861088 /** What each file did on main, once asked (`mainsRed`): the rule stage's answers are not asked again. */
10871089 const askedOfMain = new Map<string, OnBase>();
10881090 const ruleRed = ruleResults.some((result) => result.code !== 0);
@@ -1292,7 +1294,11 @@ async function mainsRed(results: readonly Timed[], stage: "rule" | "all"): Promi
12921294 console.log(`\ntest-shards: asking main at ${range[0]} about ${fresh.join(", ")}${stage === "rule" ? " (the rule and scan red)" : ""}`);
12931295 for (const [file, did] of await runOnBase(fresh, range[0]!)) askedOfMain.set(file, did);
12941296 }
1295 const verdict = baseVerdict(red, askedOfMain, range[0]!);
1297 // A rule or scan file's red is compared by its failure text, not its name (`baseVerdict`).
1298 const texts = new Map<string, ReadonlyMap<string, readonly string[]>>();
1299 for (const result of results)
1300 if (result.code !== 0) for (const [file, tests] of failureTexts(result.output)) texts.set(file, tests);
1301 const verdict = baseVerdict(red, askedOfMain, range[0]!, { files: ruleSet, texts });
12961302 // The cleared line (the last, when cleared) is the run's verdict, said once at the end: the rule
12971303 // stage's would read as a green check (`clearedIn`) before the behaviour files have run.
12981304 const said = stage === "rule" && verdict.cleared ? verdict.lines.slice(0, -1) : verdict.lines;
@@ -1326,8 +1332,11 @@ async function runOnBase(asked: readonly string[], base: string): Promise<Map<st
13261332 // BASE_RUNS runs at once (`untilRed`), each with its own scratch, ended at the first red of
13271333 // any, which one run alone then confirms: a flaky test on main is main's too, a collision of
13281334 // two runs is not.
1329 const input = { home, tree, file, flags, env: parentEnv, children };
1330 did.set(file, await untilRed((run, stop) => baseRun(input, run, stop)));
1335 const texts = new Map<string, ReadonlyMap<string, readonly string[]>>();
1336 const input = { home, tree, file, flags, env: parentEnv, children, texts };
1337 const onBase = await untilRed((run, stop) => baseRun(input, run, stop));
1338 // The lone run that confirmed a red was the last: its texts are the ones kept.
1339 did.set(file, onBase.did === "red" ? { ...onBase, texts: texts.get(file) ?? new Map() } : onBase);
13311340 }
13321341 } finally {
13331342 git(["worktree", "remove", "--force", tree]);
src/checks/base_red.ts +80 −4
@@ -27,7 +27,13 @@
2727 * there to run.
2828 */
2929 export type OnBase =
30 | { readonly did: "red"; readonly failing: readonly string[]; readonly runs?: number }
30 | {
31 readonly did: "red";
32 readonly failing: readonly string[];
33 readonly runs?: number;
34 /** Each failing test's failure text on the base (`failureTexts`), compared for a rule file. */
35 readonly texts?: ReadonlyMap<string, readonly string[]>;
36 }
3137 | { readonly did: "green"; readonly runs?: number }
3238 | { readonly did: "absent" };
3339
@@ -80,6 +86,57 @@ export async function untilRed(
8086 /** Each red file of the pull's run, with the tests in it that failed. */
8187 export type RedTests = ReadonlyMap<string, readonly string[]>;
8288
89 /** Failure texts by file, then by test name (`failureTexts`). */
90 export type FailureTexts = ReadonlyMap<string, ReadonlyMap<string, readonly string[]>>;
91
92 const ANSI = /\x1b\[[0-9;]*m/g;
93 const FILE_HEADER = /^(?:\.\/)?(\S+\.(?:test|spec)\.[cm]?[jt]sx?):$/;
94 const FAIL_LINE = /^\(fail\) (.+?)(?: \[[\d.]+m?s\])?$/;
95
96 /**
97 * Each failing test's block of a `bun test` report (the code frame, the error, what was expected
98 * and received, the stack), by file and test name. Paths up to the tree's own directories and
99 * times are dropped, so the same failure reads the same on the pull's checkout and main's.
100 */
101 export function failureTexts(report: string): Map<string, Map<string, string[]>> {
102 const out = new Map<string, Map<string, string[]>>();
103 let file: string | undefined;
104 let block: string[] = [];
105 for (const raw of report.replace(ANSI, "").split("\n")) {
106 const line = raw.trimEnd();
107 const header = FILE_HEADER.exec(line);
108 if (header !== null) {
109 file = header[1]!;
110 block = [];
111 continue;
112 }
113 if (/^\((?:pass|skip|todo)\) /.test(line)) {
114 block = [];
115 continue;
116 }
117 const failed = FAIL_LINE.exec(line);
118 if (failed !== null) {
119 if (file !== undefined) {
120 const tests = out.get(file) ?? new Map<string, string[]>();
121 tests.set(failed[1]!, block);
122 out.set(file, tests);
123 }
124 block = [];
125 continue;
126 }
127 const plain = line
128 .replace(/[^\s()'"`]*\/(?=(?:test|src|scripts|docs)\/)/g, "")
129 .replace(/\[[\d.]+m?s\]/g, "")
130 .trim();
131 if (plain !== "") block.push(plain);
132 }
133 return out;
134 }
135
136 /** Whether every line of the pull's failure is a line of main's: the same failure, or less of it. */
137 const within = (pull: readonly string[] | undefined, main: readonly string[] | undefined): boolean =>
138 pull !== undefined && main !== undefined && pull.length > 0 && pull.every((line) => main.includes(line));
139
83140 export interface BaseInput {
84141 /** The pull's red files and their failing tests; `undefined` when some red names no file or no test. */
85142 readonly red: RedTests | undefined;
@@ -116,7 +173,17 @@ const some = (names: readonly string[]): string =>
116173 * on the base too: red on the base is not the same red, and a second break
117174 * in a file main already has red is the pull's.
118175 */
119 export function baseVerdict(red: RedTests, onBase: ReadonlyMap<string, OnBase>, base: string): BaseVerdict {
176 export function baseVerdict(
177 red: RedTests,
178 onBase: ReadonlyMap<string, OnBase>,
179 base: string,
180 /**
181 * A rule or scan test fails as one test for every breach of its rule, so its name says nothing
182 * of which breach: for these files a failure is main's only when its text is within main's, and a
183 * pull that adds a breach to a rule main already breaks is red (`texts`: the pull's own).
184 */
185 rules?: { readonly files: ReadonlySet<string>; readonly texts: FailureTexts },
186 ): BaseVerdict {
120187 const at = `main at ${short(base)}`;
121188 const mains: string[] = [];
122189 const lines: string[] = [];
@@ -128,7 +195,9 @@ export function baseVerdict(red: RedTests, onBase: ReadonlyMap<string, OnBase>,
128195 theirs.push(`${file} is green on ${at}${(there.runs ?? 1) > 1 ? ` in ${there.runs} runs` : ""}: this pull's red`);
129196 else if (there.did === "absent") theirs.push(`${file} is not on ${at}: this pull's red`);
130197 else {
131 const own = failing.filter((name) => !there.failing.includes(name));
198 const byText = rules?.files.has(file) === true;
199 const differs = (name: string) => byText && !within(rules!.texts.get(file)?.get(name), there.texts?.get(name));
200 const own = failing.filter((name) => !there.failing.includes(name) || differs(name));
132201 if (failing.length > 0 && own.length === 0) {
133202 mains.push(file);
134203 const runs = there.runs ?? 1;
@@ -139,7 +208,14 @@ export function baseVerdict(red: RedTests, onBase: ReadonlyMap<string, OnBase>,
139208 );
140209 } else if (there.failing.length === 0)
141210 theirs.push(`${file} is red on ${at}, but names no failing test there to compare: this pull's red`);
142 else theirs.push(`${file} is red on ${at} too, but ${some(own)} pass${own.length === 1 ? "es" : ""} there: this pull's red`);
211 else {
212 const passing = own.filter((name) => !there.failing.includes(name));
213 theirs.push(
214 passing.length > 0
215 ? `${file} is red on ${at} too, but ${some(passing)} pass${passing.length === 1 ? "es" : ""} there: this pull's red`
216 : `${file} is red on ${at} too, but ${some(own)} fail${own.length === 1 ? "s" : ""} differently there (a breach main does not have): this pull's red`,
217 );
218 }
143219 }
144220 }
145221 lines.push(...theirs);
test/red-on-main.test.ts +65 −1
@@ -3,13 +3,15 @@
33 * red on the pull's base too, with the same tests, the check says so and is
44 * green; any other red is the pull's. Once end to end through
55 * `scripts/test-shards.ts`, in a scratch repository of trivial tests.
6 *
7 * @not-a-tree-scan: the scans it writes list only their own scratch repository's src.
68 */
79 import { describe, expect, test } from "bun:test";
810 import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
911 import { tmpdir } from "node:os";
1012 import { join } from "node:path";
1113 import { EXCLUDED, SLOW } from "../scripts/gate.ts";
12 import { askBase, BASE_RUNS, baseVerdict, clearedIn, untilRed, type OnBase } from "../src/checks/base_red.ts";
14 import { askBase, BASE_RUNS, baseVerdict, clearedIn, failureTexts, untilRed, type OnBase } from "../src/checks/base_red.ts";
1315
1416 const BASE = "0123456789abcdef0123456789abcdef01234567";
1517 const red = (...failing: string[]) => ({ did: "red" as const, failing });
@@ -143,6 +145,41 @@ describe("whose red it is", () => {
143145 expect(ended.toSorted()).toEqual(Array.from({ length: BASE_RUNS }, (_, i) => i + 1).filter((r) => r !== 2));
144146 });
145147
148 test("a bun report's failing tests are read as text by file and name, paths and times dropped", () => {
149 const report = [
150 "test/r.test.ts:",
151 "(pass) fine [0.20ms]",
152 "1 | test(\"rule\", () => {",
153 "error: expect(received).toEqual(expected)",
154 "+ \"src/b.ts\",",
155 " at <anonymous> (/tmp/x/tree/test/r.test.ts:2:31)",
156 "(fail) grp > rule [3.10ms]",
157 ].join("\n");
158 expect(failureTexts(report).get("test/r.test.ts")?.get("grp > rule")).toEqual([
159 '1 | test("rule", () => {',
160 "error: expect(received).toEqual(expected)",
161 '+ "src/b.ts",',
162 "at <anonymous> (test/r.test.ts:2:31)",
163 ]);
164 });
165
166 test("a rule file's red is main's only when its failure text is within main's", () => {
167 const red = new Map([["test/r.test.ts", ["rule"]]]);
168 const mainSays = new Map([["rule", ["error: x", '+ "src/a.ts",']]]);
169 const onBase = new Map<string, OnBase>([["test/r.test.ts", { did: "red", failing: ["rule"], texts: mainSays }]]);
170 const rules = (lines: string[]) => ({ files: new Set(["test/r.test.ts"]), texts: new Map([["test/r.test.ts", new Map([["rule", lines]])]]) });
171 expect(baseVerdict(red, onBase, BASE, rules(["error: x", '+ "src/a.ts",'])).cleared).toBe(true);
172 const more = baseVerdict(red, onBase, BASE, rules(["error: x", '+ "src/a.ts",', '+ "src/b.ts",']));
173 expect(more.cleared).toBe(false);
174 expect(more.lines).toEqual([
175 `test/r.test.ts is red on main at 0123456 too, but "rule" fails differently there (a breach main does not have): this pull's red`,
176 ]);
177 // No text on the pull's side to compare: the pull's, never assumed main's.
178 expect(baseVerdict(red, onBase, BASE, { files: new Set(["test/r.test.ts"]), texts: new Map() }).cleared).toBe(false);
179 // A behaviour file is still compared by name.
180 expect(baseVerdict(red, onBase, BASE, { files: new Set(), texts: new Map() }).cleared).toBe(true);
181 });
182
146183 test("a second break in a file main already has red is the pull's", () => {
147184 const got = baseVerdict(
148185 new Map([["test/a.test.ts", ["x", "new break"]]]),
@@ -285,6 +322,33 @@ describe("the fast tier asks main", () => {
285322 expect(got.code).not.toBe(0);
286323 }, 60_000);
287324
325 test("a pull that adds a second breach to a rule main already breaks is red: the rule's failure text is not main's", async () => {
326 // RED is a rule test: every src file holding BAD is a breach, all named in one failure. Main
327 // breaks it in src/a.ts; the pull adds src/b.ts. Same test name, a different failure.
328 const scan =
329 `import { expect, test } from "bun:test";\nimport { readdirSync, readFileSync } from "node:fs";\n` +
330 `test("no file holds BAD", () => {\n` +
331 ` const bad = readdirSync("src").filter((f) => readFileSync("src/" + f, "utf8").includes("BAD")).sort();\n` +
332 ` expect(bad).toEqual([]);\n});\n`;
333 const got = await check(scan, { "src/b.ts": "export const b = 'BAD';\n" }, { "src/a.ts": "export const a = 'BAD';\n" });
334 expect(got.out).toContain(`${RED} is red on main at HEAD~1 too, but "no file holds BAD" fails differently there`);
335 expect(got.out).not.toContain("green: every red test is red on main");
336 expect(got.out).toContain("behaviour files were not run");
337 expect(got.code).not.toBe(0);
338 }, 60_000);
339
340 test("the same breach of a rule on the pull and on main is main's, compared by its text", async () => {
341 const scan =
342 `import { expect, test } from "bun:test";\nimport { readdirSync, readFileSync } from "node:fs";\n` +
343 `test("no file holds BAD", () => {\n` +
344 ` const bad = readdirSync("src").filter((f) => readFileSync("src/" + f, "utf8").includes("BAD")).sort();\n` +
345 ` expect(bad).toEqual([]);\n});\n`;
346 const got = await check(scan, { "README.md": "# scratch, changed\n" }, { "src/a.ts": "export const a = 'BAD';\n" });
347 expect(got.out).toContain(`${RED} is red on main at HEAD~1 too, the same tests: not counted against this pull`);
348 expect(clearedIn(got.out.split("\n"))).toBe(`red on main at HEAD~1, not this pull's: ${RED}`);
349 expect(got.code).toBe(0);
350 }, 60_000);
351
288352 test("main's red in a rule test, with the pull's behaviour files green, passes once they have run", async () => {
289353 const two = `import { expect, test } from "bun:test";\nimport { two } from "../src/two.ts";\ntest("two", () => { expect(two).toBeGreaterThan(1); });\n`;
290354 const got = await check(fail, { "src/two.ts": "export const two = 3;\n" }, { "src/two.ts": "export const two = 2;\n", "test/two.test.ts": two });

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

Keyboard shortcuts

Docs