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

Every gate run times each test and names those over the budget (20 s a file, 2 s a test); a breach is red on the fast tier for files the pull changed #12110

Parked opened this
Closed without merging

scout/forge:scout/12087-every-gate-run-times-each-test-and-names → main 2 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
4 files changed +281 −3
scripts/gate.ts +7
@@ -37,6 +37,13 @@ export type Exclusion = {
3737
3838 export const EXCLUDED: readonly Exclusion[] = [];
3939
40 /**
41 * Test files known to be over the time budget (`scripts/test-budget.ts`:
42 * 20 s a file, 2 s a test), each with the issue that owns making it fast:
43 * their breaches are reported and set aside, never red (#12087).
44 */
45 export const SLOW: Readonly<Record<string, { issue: number; reason: string }>> = {};
46
4047 /**
4148 * Everything wrong with the quarantine, against the test files that exist:
4249 * one line per problem, none when every exclusion is sound.
scripts/test-budget.ts added +117
@@ -0,0 +1,117 @@
1 /**
2 * The gate's time budget (#12087, the first step of #1242): a test file
3 * should run in 20 s and a single test in 2 s. Plain data in, plain data
4 * out: `scripts/test-shards.ts` hands it the per-file times it measured and
5 * the per-test times Bun's JUnit report gave, and prints what comes back.
6 *
7 * A file named in `SLOW` (`scripts/gate.ts`) is set aside, with the issue
8 * that owns making it fast. A breach is red only on the fast tier and only
9 * for a test file the pull changed (`budgetBinds`); elsewhere it is said.
10 */
11
12 export const FILE_BUDGET_SECONDS = 20;
13 export const TEST_BUDGET_SECONDS = 2;
14
15 export type FileTime = { file: string; seconds: number };
16 export type TestTime = { file: string; test: string; seconds: number };
17 export type Slow = Readonly<Record<string, { issue: number; reason: string }>>;
18
19 export type Breaches = {
20 /** Files over the file budget, slowest first. */
21 files: FileTime[];
22 /** Tests over the test budget, slowest first. */
23 tests: TestTime[];
24 /** Breaches in a `SLOW` file: reported, never counted. */
25 aside: (FileTime | TestTime)[];
26 /** The five slowest tests of the run. */
27 slowest: TestTime[];
28 /** Their share of all the tests' time, 0 to 1. */
29 share: number;
30 };
31
32 const plain = (file: string): string => file.replace(/^\.\//, "");
33 const slowestFirst = <T extends { seconds: number }>(a: T, b: T): number => b.seconds - a.seconds;
34
35 export function breaches(
36 run: { files: readonly FileTime[]; tests: readonly TestTime[] },
37 slow: Slow,
38 ): Breaches {
39 const isSlow = (file: string): boolean => Object.hasOwn(slow, plain(file));
40 const overFiles = run.files.filter((f) => f.seconds > FILE_BUDGET_SECONDS).sort(slowestFirst);
41 const overTests = run.tests.filter((t) => t.seconds > TEST_BUDGET_SECONDS).sort(slowestFirst);
42 const tests = [...run.tests].sort(slowestFirst);
43 const total = tests.reduce((sum, t) => sum + t.seconds, 0);
44 const slowest = tests.slice(0, 5);
45 const top = slowest.reduce((sum, t) => sum + t.seconds, 0);
46 return {
47 files: overFiles.filter((f) => !isSlow(f.file)),
48 tests: overTests.filter((t) => !isSlow(t.file)),
49 aside: [...overFiles, ...overTests].filter((b) => isSlow(b.file)),
50 slowest,
51 share: total > 0 ? top / total : 0,
52 };
53 }
54
55 /** Whether a breach in `file` turns the check red. */
56 export function budgetBinds(tier: "fast" | "full", changed: readonly string[], file: string): boolean {
57 return tier === "fast" && changed.map(plain).includes(plain(file));
58 }
59
60 const name = (b: FileTime | TestTime): string =>
61 "test" in b ? `${plain(b.file)} > ${b.test} (${b.seconds.toFixed(2)}s)` : `${plain(b.file)} (${b.seconds.toFixed(2)}s)`;
62
63 /** The summary's closing lines: the five slowest, then each breach by name. */
64 export function budgetLines(found: Breaches, binds: (file: string) => boolean): string[] {
65 const lines: string[] = [];
66 if (found.slowest.length > 0) {
67 lines.push(`Slowest tests (${(found.share * 100).toFixed(0)}% of the tests' time):`);
68 for (const t of found.slowest) lines.push(` ${name(t)}`);
69 }
70 const over = [...found.files, ...found.tests];
71 lines.push(`over the budget: ${over.length}, SLOW aside: ${found.aside.length}`);
72 for (const b of over)
73 lines.push(` ${binds(b.file) ? "red" : "said"}: ${name(b)} over ${"test" in b ? TEST_BUDGET_SECONDS : FILE_BUDGET_SECONDS}s`);
74 for (const b of found.aside) lines.push(` SLOW: ${name(b)}`);
75 return lines;
76 }
77
78 const unescape = (text: string): string =>
79 text
80 .replace(/&lt;/g, "<")
81 .replace(/&gt;/g, ">")
82 .replace(/&quot;/g, '"')
83 .replace(/&apos;/g, "'")
84 .replace(/&#(\d+);/g, (_, n: string) => String.fromCodePoint(Number(n)))
85 .replace(/&amp;/g, "&");
86
87 const attr = (tag: string, key: string): string | undefined =>
88 new RegExp(`\\s${key}="([^"]*)"`).exec(tag)?.[1];
89
90 /**
91 * Each test case of a Bun JUnit report: its file, its name as the console
92 * prints it (`describe > test`), and its seconds. Bun escapes `classname`
93 * twice, so it is unescaped twice.
94 */
95 export function parseJunit(xml: string): TestTime[] {
96 const out: TestTime[] = [];
97 for (const match of xml.matchAll(/<testcase\b[^>]*>/g)) {
98 const tag = match[0];
99 const file = attr(tag, "file");
100 const test = attr(tag, "name");
101 const seconds = Number(attr(tag, "time"));
102 if (file === undefined || test === undefined || !Number.isFinite(seconds)) continue;
103 const group = unescape(unescape(attr(tag, "classname") ?? ""));
104 out.push({
105 file: plain(unescape(file)),
106 test: group === "" ? unescape(test) : `${group} > ${unescape(test)}`,
107 seconds,
108 });
109 }
110 return out;
111 }
112
113 /** The per-test times a green run keeps, one line each, slowest first. */
114 export function formatTestTimes(tests: readonly TestTime[]): string {
115 const rows = [...tests].sort(slowestFirst).map((t) => ({ ...t, seconds: Math.round(t.seconds * 1000) / 1000 }));
116 return `${JSON.stringify(rows, null, 0).replace(/\},\{/g, "},\n{")}\n`;
117 }
scripts/test-shards.ts +53 −3
@@ -82,7 +82,8 @@ import {
8282 CRASH_RERUNS,
8383 type ShardResult,
8484 } from "./shards.ts";
85 import { gateFiles, gateRefusal, presentTests } from "./gate.ts";
85 import { gateFiles, gateRefusal, presentTests, SLOW } from "./gate.ts";
86 import { breaches, budgetBinds, budgetLines, formatTestTimes, parseJunit, type TestTime } from "./test-budget.ts";
8687 import { cgroupMemory, summaryLines } from "./gate-summary.ts";
8788 import { GATE_FILE, executedFiles, formatImpact, gateListAdds, handedImpact, mergeImpact, parseImpact } from "../src/checks/impact.ts";
8889 import { importsReader, readImpact, scansIn } from "./tier-input.ts";
@@ -104,6 +105,8 @@ const IMPACT_NAME = handed ?? "scripts/test-impact.json";
104105 // What the forge keeps between checks (`src/checks/cache.ts`): the full
105106 // gate's own per-file times, fresher than the committed table.
106107 const CACHED_TIMES = `${CHECK_CACHE}/test-times.json`;
108 // Each test's own time from the last green run, from Bun's JUnit report (#12087).
109 const CACHED_TEST_TIMES = `${CHECK_CACHE}/test-times-tests.json`;
107110
108111 const argv = process.argv.slice(2);
109112 const record = argv.includes("--record");
@@ -477,7 +480,11 @@ let crashReruns = 0;
477480 /** What a live first run shows once it has gone red: held until its end. */
478481 const RED_SIGN = /^(\(fail\)|# Unhandled error|error:)/m;
479482
480 type Timed = ShardResult & { seconds: number };
483 type Timed = ShardResult & { seconds: number; tests: TestTime[] };
484
485 // Bun's JUnit report beside the console one, for each test's time; never
486 // when the caller chose a reporter of their own.
487 const junit = !flags.some((flag) => flag.startsWith("--reporter"));
481488
482489 /**
483490 * One shard. `live` (shards running one at a time) writes the shard's
@@ -534,12 +541,16 @@ async function runShardIn(
534541 const cover = covDir
535542 ? ["--coverage", "--coverage-reporter=lcov", `--coverage-dir=${covDir}`]
536543 : [];
544 let runs = 0;
545 const tests = new Map<string, TestTime>();
537546 const run = async (
538547 targets: string[],
539548 extra: string[],
540549 through?: (text: string) => void,
541550 ): Promise<{ code: number; output: string[] }> => {
542 const child = Bun.spawn(["bun", "test", ...flags, ...extra, ...targets], {
551 const report = join(home, `junit-${runs++}.xml`);
552 const junitFlags = junit ? ["--reporter=junit", `--reporter-outfile=${report}`] : [];
553 const child = Bun.spawn(["bun", "test", ...flags, ...junitFlags, ...extra, ...targets], {
543554 stdin: "ignore",
544555 stdout: "pipe",
545556 stderr: "pipe",
@@ -557,6 +568,9 @@ async function runShardIn(
557568 ]);
558569 const code = await child.exited;
559570 children.delete(child);
571 // Last run of a test wins: a re-run's time is the test's time.
572 if (junit && existsSync(report))
573 for (const test of parseJunit(readFileSync(report, "utf8"))) tests.set(`${test.file}\0${test.test}`, test);
560574 return { code, output };
561575 };
562576 const through = live
@@ -664,6 +678,7 @@ async function runShardIn(
664678 code,
665679 output: text,
666680 seconds: (performance.now() - started) / 1000,
681 tests: [...tests.values()],
667682 };
668683 }
669684
@@ -836,6 +851,37 @@ async function runOnBase(asked: readonly string[], base: string): Promise<Map<st
836851 return did;
837852 }
838853
854 // The time budget (#12087): the five slowest tests and each file over 20 s
855 // or test over 2 s, by name. A file run alone is timed by its process; a
856 // file in a shard of many, by the sum of its tests.
857 const allTests = results.flatMap((result) => result.tests);
858 const fileTimes = results.flatMap((result) =>
859 result.files.length === 1
860 ? [{ file: result.files[0]!.replace(/^\.\//, ""), seconds: result.seconds }]
861 : result.files.map((file) => {
862 const name = file.replace(/^\.\//, "");
863 return { file: name, seconds: allTests.filter((t) => t.file === name).reduce((sum, t) => sum + t.seconds, 0) };
864 }),
865 );
866 const budget = breaches({ files: fileTimes, tests: allTests }, SLOW);
867 const binds = (file: string): boolean => budgetBinds(tier === "fast" ? "fast" : "full", changed, file);
868 if (junit) console.log(`\n${budgetLines(budget, binds).join("\n")}`);
869 const budgetRed = junit && [...budget.files, ...budget.tests].some((breach) => binds(breach.file));
870 if (junit && ending.code === 0 && !record && allTests.length > 0) {
871 // Files this run did not name keep their tests' old times.
872 let kept: TestTime[] = [];
873 try {
874 const parsed: unknown = JSON.parse(readFileSync(CACHED_TEST_TIMES, "utf8"));
875 if (Array.isArray(parsed)) kept = parsed.filter((row): row is TestTime =>
876 typeof row?.file === "string" && typeof row?.test === "string" && typeof row?.seconds === "number");
877 } catch {}
878 const ran = new Set(allTests.map((t) => t.file));
879 const merged = [...kept.filter((t) => !ran.has(t.file) && existsSync(t.file)), ...allTests];
880 mkdirSync(CHECK_CACHE, { recursive: true });
881 writeFileSync(CACHED_TEST_TIMES, formatTestTimes(merged));
882 console.log(`test-shards: wrote ${allTests.length} test times to ${CACHED_TEST_TIMES}`);
883 }
884
839885 // A fast tier red only on tests main's own tree fails too is main's red,
840886 // not this pull's (#10304): said, and not counted against it.
841887 let code = ending.code;
@@ -849,4 +895,8 @@ if (code !== 0 && tier === "fast" && range !== undefined && only === undefined)
849895 if (verdict.cleared) code = 0;
850896 }
851897 }
898 if (budgetRed) {
899 console.log("test-shards: red: a test file this pull changed is over the time budget (scripts/test-budget.ts)");
900 code = code === 0 ? 1 : code;
901 }
852902 process.exit(code);
test/test-budget-run.test.ts added +104
@@ -0,0 +1,104 @@
1 import { describe, expect, test } from "bun:test";
2 import {
3 breaches,
4 budgetBinds,
5 budgetLines,
6 formatTestTimes,
7 parseJunit,
8 } from "../scripts/test-budget.ts";
9 import { SLOW } from "../scripts/gate.ts";
10
11 const quick = {
12 files: [{ file: "test/a.test.ts", seconds: 3 }],
13 tests: [
14 { file: "test/a.test.ts", test: "one", seconds: 0.5 },
15 { file: "test/a.test.ts", test: "two", seconds: 1.9 },
16 ],
17 };
18
19 describe("the time budget", () => {
20 test("a run under budget has nothing over", () => {
21 const found = breaches(quick, {});
22 expect(found.files).toEqual([]);
23 expect(found.tests).toEqual([]);
24 expect(found.aside).toEqual([]);
25 expect(budgetLines(found, () => true)).toContain("over the budget: 0, SLOW aside: 0");
26 });
27
28 test("a file over 20 s and a test over 2 s are named", () => {
29 const found = breaches(
30 {
31 files: [...quick.files, { file: "test/b.test.ts", seconds: 21 }],
32 tests: [...quick.tests, { file: "test/a.test.ts", test: "grp > three", seconds: 2.5 }],
33 },
34 {},
35 );
36 expect(found.files).toEqual([{ file: "test/b.test.ts", seconds: 21 }]);
37 expect(found.tests).toEqual([{ file: "test/a.test.ts", test: "grp > three", seconds: 2.5 }]);
38 const lines = budgetLines(found, () => false);
39 expect(lines).toContain("over the budget: 2, SLOW aside: 0");
40 expect(lines).toContain(" said: test/b.test.ts (21.00s) over 20s");
41 expect(lines).toContain(" said: test/a.test.ts > grp > three (2.50s) over 2s");
42 });
43
44 test("a SLOW file is set aside, not counted", () => {
45 const found = breaches(
46 {
47 files: [{ file: "./test/slow.test.ts", seconds: 40 }],
48 tests: [{ file: "test/slow.test.ts", test: "long", seconds: 9 }],
49 },
50 { "test/slow.test.ts": { issue: 1242, reason: "boots a server per test" } },
51 );
52 expect(found.files).toEqual([]);
53 expect(found.tests).toEqual([]);
54 expect(found.aside.length).toBe(2);
55 expect(budgetLines(found, () => true)).toContain("over the budget: 0, SLOW aside: 2");
56 });
57
58 test("the five slowest tests and their share of the run", () => {
59 const tests = [1, 2, 3, 4, 5, 6].map((n) => ({ file: "test/a.test.ts", test: `t${n}`, seconds: n }));
60 const found = breaches({ files: [], tests }, {});
61 expect(found.slowest.map((t) => t.test)).toEqual(["t6", "t5", "t4", "t3", "t2"]);
62 expect(found.share).toBeCloseTo(20 / 21);
63 });
64
65 test("a breach binds only on the fast tier, only for a file the pull changed", () => {
66 expect(budgetBinds("fast", ["test/a.test.ts"], "./test/a.test.ts")).toBe(true);
67 expect(budgetBinds("fast", ["test/other.test.ts"], "test/a.test.ts")).toBe(false);
68 expect(budgetBinds("full", ["test/a.test.ts"], "test/a.test.ts")).toBe(false);
69 });
70
71 test("SLOW names only test files that exist, each with an issue and a reason", () => {
72 for (const [file, why] of Object.entries(SLOW)) {
73 expect(file).toMatch(/^test\/.+\.test\.ts$/);
74 expect(Bun.file(file).size).toBeGreaterThan(0);
75 expect(why.issue).toBeGreaterThan(0);
76 expect(why.reason.trim()).not.toBe("");
77 }
78 });
79 });
80
81 describe("Bun's JUnit report", () => {
82 test("each test case with its file, console name and seconds", () => {
83 const xml = `<?xml version="1.0" encoding="UTF-8"?>
84 <testsuites name="bun test" tests="2">
85 <testsuite name="y.test.ts" file="test/y.test.ts">
86 <testcase name="plain" classname="" time="0.030759" file="test/y.test.ts" line="2" assertions="0" />
87 <testsuite name="grp &lt;x&gt;" file="test/y.test.ts">
88 <testcase name="bad &amp; &quot;q&quot;" classname="grp &amp;lt;x&amp;gt;" time="2.5" file="test/y.test.ts" line="3" assertions="1">
89 <failure type="AssertionError" />
90 </testcase>
91 </testsuite>
92 </testsuite>
93 </testsuites>`;
94 expect(parseJunit(xml)).toEqual([
95 { file: "test/y.test.ts", test: "plain", seconds: 0.030759 },
96 { file: "test/y.test.ts", test: 'grp <x> > bad & "q"', seconds: 2.5 },
97 ]);
98 });
99
100 test("the kept times read back, slowest first", () => {
101 const text = formatTestTimes(quick.tests);
102 expect(JSON.parse(text).map((t: { test: string }) => t.test)).toEqual(["two", "one"]);
103 });
104 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs