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

The test budget is CPU time: a test starved on a loaded box is not red, one that spends its seconds is #17310

opened this

Merged 39h 56m ago, live in production

checks/cpu-budget → main 0 commits 1 thread · 1 unresolved

  • Merged. checks/cpu-budget was merged into main as 3814902.

Review

Sign in to review this change.
6 files changed +164 −27
scripts/test-budget.ts +49 −13
@@ -1,7 +1,11 @@
11 /**
22 * The test budget (#1242): no gated file over {@link FILE_BUDGET_SECONDS},
33 * no single test over {@link TEST_BUDGET_SECONDS}, unless the file is named
4 * in `SLOW` in `scripts/gate.ts` with the issue that owns it.
4 * in `SLOW` in `scripts/gate.ts` with the issue that owns it. Both are CPU
5 * seconds where the run measured them (`scripts/test-cpu.ts`, the child's
6 * own usage): on a loaded machine wall time measures the machine, so a test
7 * starved of CPU is not red, and one that spends it is. Wall time stays a
8 * backstop for a hang, at {@link HANG_FACTOR} times the budget.
59 *
610 * Plain data in, lines out. `scripts/test-shards.ts` times each file and
711 * hands in each test's time, read from the JUnit report `bun test` writes
@@ -21,8 +25,34 @@ export const SLOWEST_TESTS = 5;
2125 * One case of a report. `skipped` when bun did not run it; `lines` then holds its source line and
2226 * those of the `describe` blocks around it, innermost first, where a conditional skip is declared.
2327 */
24 export type TestTime = { file: string; test: string; seconds: number; skipped?: true; lines?: readonly number[] };
25 export type FileTime = { file: string; seconds: number };
28 export type TestTime = { file: string; test: string; seconds: number; skipped?: true; lines?: readonly number[]; wall?: number };
29 /** `seconds` is CPU time where `wall` is given (the run measured both), else wall time. */
30 export type FileTime = { file: string; seconds: number; wall?: number };
31
32 /** Wall time past this many budgets is a breach whatever the CPU said: a hang, not a slow test. */
33 export const HANG_FACTOR = 5;
34
35 /** The CPU seconds `scripts/test-cpu.ts` wrote for the tests process `pid` ran, in the order they ran. */
36 export function readCpu(text: string, pid: number): number[] {
37 const out: number[] = [];
38 for (const line of text.split("\n")) {
39 const [who, seconds] = line.split(" ");
40 const n = Number(seconds);
41 if (Number(who) === pid && seconds !== undefined && Number.isFinite(n) && n >= 0) out.push(n);
42 }
43 return out;
44 }
45
46 /**
47 * Each test's CPU seconds in place of its wall seconds (kept as `wall`): the report lists the cases
48 * in the order they ran, so the ones that ran (not skipped) take `cpu` in turn. When the counts
49 * differ (a test retried, a report cut short), nothing is matched and the wall seconds stand.
50 */
51 export function withCpu(tests: readonly TestTime[], cpu: readonly number[]): TestTime[] {
52 if (cpu.length !== tests.filter((t) => t.skipped !== true).length) return [...tests];
53 let i = 0;
54 return tests.map((t) => (t.skipped === true ? t : { ...t, seconds: cpu[i++]!, wall: t.seconds }));
55 }
2656
2757 export type Budgets = { file: number; test: number };
2858
@@ -40,7 +70,7 @@ export function budgetsFrom(value: string | undefined): Budgets {
4070 }
4171
4272 /** One thing over its budget: a whole file, or one test in it. */
43 export type Breach = { file: string; test?: string; seconds: number; budget: number; aloneRed?: true };
73 export type Breach = { file: string; test?: string; seconds: number; budget: number; aloneRed?: true; wall?: number; hang?: true };
4474
4575 const ENTITIES: Record<string, string> = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
4676
@@ -124,13 +154,17 @@ export function breaches(
124154 slow: ReadonlySet<string>,
125155 budgets: Budgets = { file: FILE_BUDGET_SECONDS, test: TEST_BUDGET_SECONDS },
126156 ): Breach[] {
157 // Over on CPU (or on wall, where only wall was measured), or past the hang backstop on wall.
158 const isOver = (t: { seconds: number; wall?: number }, budget: number) => t.seconds > budget || (t.wall ?? 0) > budget * HANG_FACTOR;
159 const times = (t: { seconds: number; wall?: number }, budget: number) => ({
160 seconds: t.seconds,
161 budget,
162 ...(t.wall === undefined ? {} : { wall: t.wall }),
163 ...(t.seconds <= budget ? { hang: true as const } : {}),
164 });
127165 const over: Breach[] = [
128 ...files
129 .filter((f) => !slow.has(f.file) && f.seconds > budgets.file)
130 .map((f) => ({ file: f.file, seconds: f.seconds, budget: budgets.file })),
131 ...tests
132 .filter((t) => !slow.has(t.file) && t.seconds > budgets.test)
133 .map((t) => ({ file: t.file, test: t.test, seconds: t.seconds, budget: budgets.test })),
166 ...files.filter((f) => !slow.has(f.file) && isOver(f, budgets.file)).map((f) => ({ file: f.file, ...times(f, budgets.file) })),
167 ...tests.filter((t) => !slow.has(t.file) && isOver(t, budgets.test)).map((t) => ({ file: t.file, test: t.test, ...times(t, budgets.test) })),
134168 ];
135169 return over.sort((a, b) => b.seconds - a.seconds);
136170 }
@@ -153,9 +187,11 @@ export function breachReport(over: readonly Breach[]): string {
153187 lines.push(`${file}:`);
154188 for (const b of list)
155189 lines.push(
156 b.test === undefined
157 ? `(fail) the whole file took ${b.seconds.toFixed(1)} s, over the ${b.budget} s file budget${ALONE_RED(b)}: ${FIX}`
158 : `(fail) ${b.test} took ${b.seconds.toFixed(2)} s, over the ${b.budget} s test budget${ALONE_RED(b)}: ${FIX}`,
190 b.hang === true
191 ? `(fail) ${b.test ?? "the whole file"} ran ${b.wall!.toFixed(1)} s, past the ${b.budget * HANG_FACTOR} s backstop for a hang (${b.seconds.toFixed(2)} s of CPU)${ALONE_RED(b)}: ${FIX}`
192 : b.test === undefined
193 ? `(fail) the whole file took ${b.seconds.toFixed(1)} s${b.wall === undefined ? "" : " of CPU"}, over the ${b.budget} s file budget${ALONE_RED(b)}: ${FIX}`
194 : `(fail) ${b.test} took ${b.seconds.toFixed(2)} s${b.wall === undefined ? "" : " of CPU"}, over the ${b.budget} s test budget${ALONE_RED(b)}: ${FIX}`,
159195 );
160196 }
161197 return lines.length === 0 ? "" : `${lines.join("\n")}\n`;
scripts/test-cpu.ts added +23
@@ -0,0 +1,23 @@
1 /**
2 * Preloaded into each `bun test` that `scripts/test-shards.ts` starts: each test's CPU seconds
3 * (this process's user + system time, from just before it to just after it), one line per test in
4 * the order they ran, `<pid> <seconds>`, appended to `FORGE_TEST_CPU_OUT`. The pid keeps out a
5 * `bun test` a test itself starts, which inherits the variable. Without it, nothing is recorded.
6 * Wall time on a loaded machine measures the machine; CPU time measures the test (`test-budget.ts`).
7 */
8
9 import { afterEach, beforeEach } from "bun:test";
10 import { appendFileSync } from "node:fs";
11
12 const out = process.env["FORGE_TEST_CPU_OUT"];
13 if (out !== undefined && out !== "") {
14 let at = process.cpuUsage();
15 beforeEach(() => {
16 at = process.cpuUsage();
17 });
18 afterEach(() => {
19 // process.cpuUsage is process-wide: `test.concurrent` tests share the CPU time spent meanwhile.
20 const spent = process.cpuUsage(at);
21 appendFileSync(out, `${process.pid} ${(spent.user + spent.system) / 1e6}\n`);
22 });
23 }
scripts/test-honesty-allow.json +1 −1
@@ -421,7 +421,7 @@
421421 "test/template-page.test.ts": {"timeout":1},
422422 "test/template-scripts.test.ts": {"timeout":1},
423423 "test/templates-boot.test.ts": {"wait":1},
424 "test/test-budget-run.test.ts": {"wait":1},
424 "test/test-budget-run.test.ts": {"wait":2},
425425 "test/toolbar-keyboard.test.ts": {"wait":1},
426426 "test/toolbar-move.test.ts": {"wait":1},
427427 "test/tree-read.test.ts": {"wait":5},
scripts/test-shards.ts +35 −13
@@ -115,7 +115,7 @@ import {
115115 import { gateFiles, gateRefusal, looksTests, presentTests, SLOW, slowRefusal } from "./gate.ts";
116116 import { findChromium } from "../src/looks/capture.ts";
117117 import { chromiumRuns } from "../test/helpers/chrome.ts";
118 import { breaches, breachReport, budgetsFrom, retimeVerdict, breachClosing, breachWarnings, formatTestTimes, loadVerdict, retimeFiles, RETIME_SECONDS, slowSecondsLines, slowUnderLines, parseJunit, slowestTestLines, underLoadLines, unverifiedLines, type AloneRun, type Breach, type TestTime, type UnderLoad, type Unverified } from "./test-budget.ts";
118 import { breaches, breachReport, budgetsFrom, readCpu, retimeVerdict, withCpu, breachClosing, breachWarnings, formatTestTimes, loadVerdict, retimeFiles, RETIME_SECONDS, slowSecondsLines, slowUnderLines, parseJunit, slowestTestLines, underLoadLines, unverifiedLines, type AloneRun, type Breach, type FileTime, type TestTime, type UnderLoad, type Unverified } from "./test-budget.ts";
119119 import { cgroupMemory, summaryLines } from "./gate-summary.ts";
120120 import { GATE_STEP_FILE, readGateStep, type Step } from "./step-times.ts";
121121 import { GATE_FILE, LOADS_ONLY, coverOf, executedFiles, formatImpact, gateListAdds, handedImpact, mergeImpact, packImpact, usedFiles, type Cover } from "../src/checks/impact.ts";
@@ -643,6 +643,20 @@ const SLOW_FILES = new Set(SLOW.map((entry) => entry.file));
643643 // The looks lane has no per-test budget: a real browser's time is its own.
644644 const BUDGET_EXEMPT = new Set([...SLOW_FILES, ...LOOKS_SET]);
645645 const BUDGETS = budgetsFrom(process.env["FORGE_TEST_BUDGET_SECONDS"]);
646 // Each test's CPU seconds, recorded by a preload beside the suite's own (`scripts/test-cpu.ts`).
647 const CPU_PRELOAD = ["--preload", join(import.meta.dir, "test-cpu.ts")];
648 /** A finished child's CPU seconds, user and system, its reaped children's included. */
649 const cpuSeconds = (child: Bun.Subprocess): number | undefined => {
650 const used = child.resourceUsage();
651 return used === undefined ? undefined : Number(used.cpuTime.total) / 1e6;
652 };
653 const cpuOf = (path: string, pid: number): number[] => {
654 try {
655 return readCpu(readFileSync(path, "utf8"), pid);
656 } catch {
657 return [];
658 }
659 };
646660 const budgetBinds = (file: string): boolean =>
647661 (tier === "full" && (gate || tierArg.value === "full")) ||
648662 (tier === "fast" && changed.includes(file.replace(/^\.\//, "")));
@@ -706,14 +720,19 @@ async function runShardIn(
706720 : [];
707721 const junit = join(home, "junit.xml");
708722 const report = junitAsked ? [] : ["--reporter=junit", `--reporter-outfile=${junit}`];
723 // Each test's CPU seconds (`scripts/test-cpu.ts`), what the budget holds a test to.
724 const cpuOut = join(home, "cpu.txt");
725 childEnv["FORGE_TEST_CPU_OUT"] = cpuOut;
726 let lastPid = 0;
709727 const run = async (
710728 targets: string[],
711729 extra: string[],
712730 through?: (text: string) => void,
713 ): Promise<{ code: number; output: string[]; seconds: number }> => {
731 ): Promise<{ code: number; output: string[]; seconds: number; cpu: number | undefined }> => {
714732 rmSync(junit, { force: true });
733 rmSync(cpuOut, { force: true });
715734 const began = performance.now();
716 const child = Bun.spawn(["bun", "test", ...flags, ...report, ...extra, ...targets], {
735 const child = Bun.spawn(["bun", "test", ...flags, ...report, ...CPU_PRELOAD, ...extra, ...targets], {
717736 stdin: "ignore",
718737 stdout: "pipe",
719738 stderr: "pipe",
@@ -732,11 +751,12 @@ async function runShardIn(
732751 output.push(line);
733752 through?.(line);
734753 }
735 return { code, output, seconds: (performance.now() - began) / 1000 };
754 lastPid = child.pid;
755 return { code, output, seconds: (performance.now() - began) / 1000, cpu: cpuSeconds(child) };
736756 };
737757 const testsOfLastRun = (): TestTime[] => {
738758 try {
739 return parseJunit(readFileSync(junit, "utf8"));
759 return withCpu(parseJunit(readFileSync(junit, "utf8")), cpuOf(cpuOut, lastPid));
740760 } catch {
741761 return [];
742762 }
@@ -780,7 +800,7 @@ async function runShardIn(
780800 let retried = crashed;
781801 let code = first.code;
782802 let output = quoted === "" ? first.output : [quoted, ...first.output];
783 let lastSeconds = first.seconds;
803 let last: FileTime = { file: "", seconds: first.cpu ?? first.seconds, ...(first.cpu === undefined ? {} : { wall: first.seconds }) };
784804 let tests = testsOfLastRun();
785805 // Kept going, a file red on its own is run once more alone: green then,
786806 // it was a flake, and its first output (the `(fail)` lines) is set aside.
@@ -792,7 +812,7 @@ async function runShardIn(
792812 }
793813 retried = true;
794814 const again = await run(paths, cover, through);
795 lastSeconds = again.seconds;
815 last = { file: "", seconds: again.cpu ?? again.seconds, ...(again.cpu === undefined ? {} : { wall: again.seconds }) };
796816 tests = testsOfLastRun();
797817 if (again.code === 0) {
798818 code = 0;
@@ -832,7 +852,7 @@ async function runShardIn(
832852 let slowRan: string[] = [];
833853 let slowOver: Breach[] = [];
834854 if (code === 0) {
835 const fileTimes = slice.length === 1 ? [{ file: slice[0]!.replace(/^\.\//, ""), seconds: lastSeconds }] : [];
855 const fileTimes = slice.length === 1 ? [{ ...last, file: slice[0]!.replace(/^\.\//, "") }] : [];
836856 slowRan = slice.map((file) => file.replace(/^\.\//, "")).filter((file) => SLOW_FILES.has(file));
837857 if (slowRan.length > 0)
838858 slowOver = breaches(fileTimes, tests, new Set(), BUDGETS).filter((b) => SLOW_FILES.has(b.file));
@@ -850,7 +870,7 @@ async function runShardIn(
850870 const judged = retimeVerdict(
851871 binding,
852872 again.code === 0
853 ? breaches(retimed.length === 1 && slice.length === 1 ? [{ file: retimed[0]!, seconds: again.seconds }] : [], againTests, BUDGET_EXEMPT, BUDGETS)
873 ? breaches(retimed.length === 1 && slice.length === 1 ? [{ file: retimed[0]!, seconds: again.cpu ?? again.seconds, ...(again.cpu === undefined ? {} : { wall: again.seconds }) }] : [], againTests, BUDGET_EXEMPT, BUDGETS)
854874 : undefined,
855875 );
856876 still = judged.still;
@@ -928,7 +948,8 @@ async function runShardIn(
928948 */
929949 async function timeAlone(file: string): Promise<AloneRun> {
930950 const home = shardHome(process.env, tmpdir());
931 const env: Record<string, string | undefined> = { ...process.env, TMPDIR: join(home, "tmp"), FORGE_APP_DATA: join(home, "data") };
951 const cpuOut = join(home, "cpu.txt");
952 const env: Record<string, string | undefined> = { ...process.env, TMPDIR: join(home, "tmp"), FORGE_APP_DATA: join(home, "data"), FORGE_TEST_CPU_OUT: cpuOut };
932953 for (const name of ["FORGE_CHECK_SHARDS", "FORGE_CHECK_SHARD_INDEX", "FORGE_CHECK_SHARD_TOTAL", "NODE_OPTIONS"]) delete env[name];
933954 const junit = join(home, "junit.xml");
934955 try {
@@ -936,7 +957,7 @@ async function timeAlone(file: string): Promise<AloneRun> {
936957 mkdirSync(join(home, "data"), { recursive: true });
937958 const report = junitAsked ? [] : ["--reporter=junit", `--reporter-outfile=${junit}`];
938959 const began = performance.now();
939 const child = Bun.spawn(["bun", "test", ...flags, ...report, `./${file.replace(/^\.\//, "")}`], {
960 const child = Bun.spawn(["bun", "test", ...flags, ...report, ...CPU_PRELOAD, `./${file.replace(/^\.\//, "")}`], {
940961 stdin: "ignore",
941962 stdout: "ignore",
942963 stderr: "ignore",
@@ -945,11 +966,12 @@ async function timeAlone(file: string): Promise<AloneRun> {
945966 children.add(child);
946967 const code = await child.exited;
947968 children.delete(child);
948 const seconds = (performance.now() - began) / 1000;
969 // CPU seconds where the child's usage is known, as the shard's own run is judged.
970 const seconds = cpuSeconds(child) ?? (performance.now() - began) / 1000;
949971 let tests: TestTime[] = [];
950972 let wrote = false;
951973 try {
952 tests = parseJunit(readFileSync(junit, "utf8"));
974 tests = withCpu(parseJunit(readFileSync(junit, "utf8")), cpuOf(cpuOut, child.pid));
953975 wrote = true;
954976 } catch {
955977 // no report: its test breaches are named unverified under load, with why
test/test-budget-run.test.ts +16
@@ -90,11 +90,27 @@ describe("the budget in the runner", () => {
9090 test("a run that names the full tier is red on it, without --gate (#12088)", async () => {
9191 const got = await runner(["--tier", "full", "test/zz-budget.test.ts"]);
9292 expect(got.out).toContain("test/zz-budget.test.ts:\n(fail) spins past the budget took ");
93 // Held to CPU time: spinning spends it.
94 expect(got.out).toMatch(/\(fail\) spins past the budget took [\d.]+ s of CPU, over the 0\.02 s test budget/);
9395 expect(got.out).toContain("over the 0.02 s test budget: make it faster, or name its file in SLOW in scripts/gate.ts");
9496 expect(got.out).not.toContain("over budget (not enforced here)");
9597 expect(got.code).toBe(1);
9698 }, 20_000);
9799
100 test("a test that waits, not spins, is under the budget: CPU time is judged, wall time only past the hang backstop", async () => {
101 // 150 ms of wall clock and next to no CPU, against a 0.1 s test budget: its backstop, 0.5 s,
102 // leaves a starved box room.
103 writeFileSync(join(dir, "test/zz-sleep.test.ts"), `import { expect, test } from "bun:test";\ntest("waits", async () => {\n await Bun.sleep(150);\n expect(true).toBe(true);\n});\n`); // real-timer: the fixture is a test that waits (long wall, no CPU) by design
outdated

Flaky under load: the first run's wall time must stay under the 0.25 s backstop (0.05 x 5) while the sleep is 150 ms, which leaves only ~100 ms of slack. On a starved box this goes red as a 'hang'. Widen the margin, e.g. a 0.1 s budget (0.5 s backstop) for the green run, keeping the sleep at 150 ms so it still exceeds the budget on wall time.

104 const got = await runner(["--tier", "full", "test/zz-sleep.test.ts"], { FORGE_TEST_BUDGET_SECONDS: ",0.1" });
105 expect(got.out).not.toContain("(fail) waits");
106 expect(got.code).toBe(0);
107 // Past the backstop, the wait is a hang: red on wall time.
108 const hung = await runner(["--tier", "full", "test/zz-sleep.test.ts"], { FORGE_TEST_BUDGET_SECONDS: ",0.02" });
109 expect(hung.out).toMatch(/\(fail\) waits ran [\d.]+ s, past the 0\.1 s backstop for a hang/);
110 expect(hung.code).toBe(1);
111 rmSync(join(dir, "test/zz-sleep.test.ts"));
112 }, 30_000);
113
98114 test("a file's hooks count against the file budget, not any one test's (#12485)", async () => {
99115 // The walking sits in beforeAll; the test itself is instant (under the
100116 // 2 s test budget), so only the file's own wall time, hooks and all, can
test/test-budget.test.ts +40
@@ -16,6 +16,7 @@ import {
1616 formatTestTimes,
1717 loadVerdict,
1818 parseJunit,
19 readCpu,
1920 RETIME_SECONDS,
2021 retimeFiles,
2122 retimeVerdict,
@@ -25,6 +26,8 @@ import {
2526 TEST_BUDGET_SECONDS,
2627 underLoadLines,
2728 unverifiedLines,
29 withCpu,
30 type TestTime,
2831 } from "../scripts/test-budget.ts";
2932
3033 const junit = `<?xml version="1.0" encoding="UTF-8"?>
@@ -86,6 +89,43 @@ describe("breaches", () => {
8689 });
8790 });
8891
92 describe("CPU time, not wall time", () => {
93 const budgets = { file: 20, test: 2 };
94 test("each test that ran takes its CPU seconds in turn; a skipped one keeps none; the wall seconds are kept", () => {
95 const tests: TestTime[] = [
96 { file: "test/a.test.ts", test: "waits", seconds: 3 },
97 { file: "test/a.test.ts", test: "skipped", seconds: 0, skipped: true },
98 { file: "test/a.test.ts", test: "spins", seconds: 2.6 },
99 ];
100 const cpu = readCpu("41 0.01\n99 7\n41 2.5\nnot a line\n", 41);
101 expect(cpu).toEqual([0.01, 2.5]);
102 const timed = withCpu(tests, cpu);
103 expect(timed.map((t) => [t.test, t.seconds, t.wall])).toEqual([["waits", 0.01, 3], ["skipped", 0, undefined], ["spins", 2.5, 2.6]]);
104 // A count that does not match (a retry, a report cut short) leaves the wall seconds.
105 expect(withCpu(tests, [0.01])).toEqual(tests);
106 });
107
108 test("a test that waits is no breach; one that spins past the CPU budget is; past five budgets of wall, a hang is", () => {
109 const over = breaches(
110 [{ file: "test/a.test.ts", seconds: 1, wall: 30 }],
111 [
112 { file: "test/a.test.ts", test: "waits", seconds: 0.01, wall: 3 },
113 { file: "test/a.test.ts", test: "spins", seconds: 2.5, wall: 2.6 },
114 { file: "test/a.test.ts", test: "hangs", seconds: 0.1, wall: 11 },
115 ],
116 new Set(),
117 budgets,
118 );
119 expect(over.map((b) => [b.test, b.hang === true])).toEqual([["spins", false], ["hangs", true]]);
120 const report = breachReport(over);
121 expect(report).toContain("(fail) spins took 2.50 s of CPU, over the 2 s test budget");
122 expect(report).toContain("(fail) hangs ran 11.0 s, past the 10 s backstop for a hang (0.10 s of CPU)");
123 // A starved file (1 s of CPU in 30 s of wall) is under both its budget and its backstop.
124 expect(over.some((b) => b.test === undefined)).toBe(false);
125 expect(breaches([{ file: "test/b.test.ts", seconds: 1, wall: 120 }], [], new Set(), budgets)[0]).toMatchObject({ hang: true, wall: 120 });
126 });
127 });
128
89129 describe("budgetsFrom", () => {
90130 test("only ever tightens the constants", () => {
91131 expect(budgetsFrom(undefined)).toEqual({ file: FILE_BUDGET_SECONDS, test: TEST_BUDGET_SECONDS });

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

Keyboard shortcuts

Docs