From 22b5fe4fe29520352a888ffce12a060d1ef99e75 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 15:50:33 +0000 Subject: [PATCH 1/3] chore(ci): stop flagging a raised test timeout as a proof-system change (#4191) A watchdog is a catch-all for the worst case, so raising one cannot make a passing test fail. The timeout check now reads the direction of a value rewritten in place: the same or a larger number, or the same expression with no number made smaller, is not reported. A lowered, removed or added value is still a proof-system change, and so is one whose direction cannot be read or that moved between hunks. A duration inside watchdogMs() is read as that duration, so adopting the scaling helper is not a change and leaving it is a lowering. Co-Authored-By: Claude Fable 5.2 --- scripts/proof-system.ts | 96 +++++++++++++++++++++++++++-------- tests/proof-system.test.ts | 100 +++++++++++++++++++++++++++++++++---- 2 files changed, 165 insertions(+), 31 deletions(-) diff --git a/scripts/proof-system.ts b/scripts/proof-system.ts index 9ac9129f82..17669fea89 100644 --- a/scripts/proof-system.ts +++ b/scripts/proof-system.ts @@ -1,9 +1,14 @@ /** Classifies a diff as a proof-system change: one that touches a path in the - * ruled path set (`scripts/proof-system-paths.json`) or changes a test timeout or - * deadline constant. The serialized lane, the proof-policy epochs and off-main - * qualification all read this classification (docs/decisions/ci-utility.md, + * ruled path set (`scripts/proof-system-paths.json`) or lowers, removes or adds + * a test timeout or deadline. The serialized lane, the proof-policy epochs and + * off-main qualification all read this classification (docs/decisions/ci-utility.md, * "Proof-system lane", answer 5). * + * A timeout or deadline that is only raised is not a proof-system change + * (#4191): a watchdog is a catch-all for the worst case, and raising one cannot + * make a passing test fail (docs/decisions/ci-utility.md, "Test watchdogs are a + * worst-case catch-all"). + * * bun scripts/proof-system.ts classify --base --head [--json] * * A diff that cannot be computed throws; the command then exits nonzero and @@ -58,9 +63,46 @@ export function matchProofSystemPath(path: string, set: PathSet = loadPathSet()) // Numeric expressions such as `5000`, `30_000`, `2.5` or `5 * 60 * 1000`. const NUM = String.raw`\d[\d_]*(?:\.\d+)?(?:\s*[*+]\s*\d[\d_]*(?:\.\d+)?)*`; const IDENT = String.raw`[A-Za-z_$][\w$]*`; +// A duration as a test writes it: the number, or the number inside the scaling +// helper (`watchdogMs`, scripts/test-deadlines.ts). +const DURATION = String.raw`(?:watchdogMs\(\s*${NUM}\s*\)|${NUM})`; const TIMING = /timeout|deadline/i; const norm = (value: string) => value.replace(/[\s_]/g, ""); +/** A signal's normalized value split into what a direction can be read from. */ +interface Magnitude { scaled: boolean; shape: string; numbers: number[]; total: number | null } + +/** + * Reads a normalized value as a sum of products of numbers and opaque operands + * (`30000`, `5*60*1000`, `Date.now()+5000`), optionally inside `watchdogMs(...)`. + * Anything else (a conditional, a call with arguments, a subtraction) has no + * readable magnitude. + */ +function magnitude(value: string): Magnitude | null { + const helper = /^watchdogMs\((.*)\)$/.exec(value); + const inner = helper ? helper[1]! : value; + const operand = String.raw`(?:\d+(?:\.\d+)?|${IDENT}(?:\.${IDENT})*(?:\(\))?)`; + if (!new RegExp(`^${operand}(?:[*+]${operand})*$`).test(inner)) return null; + const numbers: number[] = []; + const shape = inner.replace(/(? { numbers.push(Number(digits)); return "#"; }); + const total = /^[#*+]+$/.test(shape) + ? inner.split("+").reduce((sum, term) => sum + term.split("*").reduce((product, factor) => product * Number(factor), 1), 0) : null; + return { scaled: Boolean(helper), shape, numbers, total }; +} + +/** + * Whether `to` is certainly no shorter than `from`: the same or a larger + * number, or the same expression with no number made smaller, and still read + * through the scaling helper if it was. A direction that cannot be read is not + * a raise. + */ +export function raisedOrEqual(from: string, to: string): boolean { + const before = magnitude(from), after = magnitude(to); + if (!before || !after || (before.scaled && !after.scaled)) return false; + if (before.total !== null && after.total !== null) return after.total >= before.total; + return before.shape === after.shape && after.numbers.every((number, index) => number >= before.numbers[index]!); +} + /** The timeout and deadline values one source line declares, read syntactically. */ export function timeoutSignals(line: string): Signal[] { const signals: Signal[] = []; @@ -69,29 +111,30 @@ export function timeoutSignals(line: string): Signal[] { if (TIMING.test(m[1]!)) signals.push({ kind: "constant", name: m[1]!, value: norm(m[2]!) }); } // `{ timeout: 5000 }`, `deadlineMs: 2_000`. - for (const m of line.matchAll(new RegExp(String.raw`\b(${IDENT})\s*:\s*(${NUM})(?![\w.])`, "g"))) { + for (const m of line.matchAll(new RegExp(String.raw`\b(${IDENT})\s*:\s*(${DURATION})(?![\w.])`, "g"))) { if (TIMING.test(m[1]!)) signals.push({ kind: "option", name: m[1]!, value: norm(m[2]!) }); } // `setDefaultTimeout(5000)`, `jest.setTimeout(5000)`, `this.timeout(5000)`. - for (const m of line.matchAll(new RegExp(String.raw`\b((?:${IDENT}\.)*(?:setDefaultTimeout|setTimeout|timeout))\s*\(\s*(${NUM})\s*\)`, "g"))) { + for (const m of line.matchAll(new RegExp(String.raw`\b((?:${IDENT}\.)*(?:setDefaultTimeout|setTimeout|timeout))\s*\(\s*(${DURATION})\s*\)`, "g"))) { signals.push({ kind: "call", name: m[1]!, value: norm(m[2]!) }); } // Bun test third-argument timeouts: `test("x", fn, 5000);` or the closing `}, 5000);`. - const single = line.match(new RegExp(String.raw`(?:^|[^\w$.])((?:test|it|describe)(?:\.${IDENT})*)\s*\(.*,\s*(${NUM})\s*\)\s*;?\s*$`)); - const closing = single ? null : line.match(new RegExp(String.raw`^\s*\}\s*\)?\s*,\s*(${NUM})\s*\)\s*;?\s*$`)); + const single = line.match(new RegExp(String.raw`(?:^|[^\w$.])((?:test|it|describe)(?:\.${IDENT})*)\s*\(.*,\s*(${DURATION})\s*\)\s*;?\s*$`)); + const closing = single ? null : line.match(new RegExp(String.raw`^\s*\}\s*\)?\s*,\s*(${DURATION})\s*\)\s*;?\s*$`)); if (single) signals.push({ kind: "test-argument", name: "test", value: norm(single[2]!) }); else if (closing) signals.push({ kind: "test-argument", name: "test", value: norm(closing[1]!) }); return signals; } -interface DiffLine { side: "head" | "base"; line: number; text: string; edit: boolean } +interface DiffLine { side: "head" | "base"; line: number; text: string; edit: boolean; hunk: number } /** Added and removed lines of a `git diff --unified=0` patch for one file. * `edit` marks a line whose hunk both removes and adds lines, i.e. rewrites - * existing lines rather than only inserting or deleting them. */ + * existing lines rather than only inserting or deleting them. `hunk` numbers + * the hunk a line belongs to. */ export function changedLines(patch: string): DiffLine[] { const lines: DiffLine[] = []; - let base = 0, head = 0, hunk: DiffLine[] | null = null; + let base = 0, head = 0, hunk: DiffLine[] | null = null, hunks = 0; const flush = () => { if (!hunk) return; const edit = hunk.some(l => l.side === "base") && hunk.some(l => l.side === "head"); @@ -99,20 +142,26 @@ export function changedLines(patch: string): DiffLine[] { }; for (const text of patch.split("\n")) { const header = text.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/); - if (header) { flush(); base = Number(header[1]); head = Number(header[2]); hunk = []; continue; } + if (header) { flush(); base = Number(header[1]); head = Number(header[2]); hunk = []; hunks++; continue; } if (!hunk) continue; - if (text.startsWith("-")) hunk.push({ side: "base", line: base++, text: text.slice(1), edit: false }); - else if (text.startsWith("+")) hunk.push({ side: "head", line: head++, text: text.slice(1), edit: false }); + if (text.startsWith("-")) hunk.push({ side: "base", line: base++, text: text.slice(1), edit: false, hunk: hunks }); + else if (text.startsWith("+")) hunk.push({ side: "head", line: head++, text: text.slice(1), edit: false, hunk: hunks }); } flush(); return lines; } -type Located = Signal & { line: number; edit: boolean }; +type Located = Signal & { line: number; edit: boolean; hunk: number }; -/** Timeout or deadline signals that differ between the removed and added lines - * of one file. A signal moved unchanged within the file is not a change; a - * changed value is reported once, at its head line, with both values. +/** Timeout or deadline signals that are lowered, removed or added between the + * removed and added lines of one file. A signal moved unchanged within the + * file is not a change; a changed value is reported once, at its head line, + * with both values. + * + * A value rewritten in place to one that is certainly no shorter is a raised + * watchdog and is not reported (#4191, `raisedOrEqual`). In place means the + * same hunk: a value that disappears from one test while a larger one appears + * in another is a removal and an addition, never a raise. * * Only existing budgets count: an unmatched signal is a change when its hunk * rewrites existing lines, or when it is a file-wide default call @@ -123,7 +172,7 @@ export function timeoutChanges(patch: string, path: { base: string; head: string const removed: Located[] = [], added: Located[] = []; for (const line of changedLines(patch)) { for (const signal of timeoutSignals(line.text)) { - (line.side === "base" ? removed : added).push({ ...signal, line: line.line, edit: line.edit }); + (line.side === "base" ? removed : added).push({ ...signal, line: line.line, edit: line.edit, hunk: line.hunk }); } } const key = (s: Signal) => `${s.kind}\0${s.name}\0${s.value}`; @@ -134,11 +183,14 @@ export function timeoutChanges(patch: string, path: { base: string; head: string return false; }); const counts = (signal: Located) => signal.edit || (existing && signal.kind === "call"); - const reasons: Reason[] = unmatchedAdded.filter(counts).map(signal => { - const index = removed.findIndex(other => counts(other) && other.kind === signal.kind && other.name === signal.name); + const reasons: Reason[] = unmatchedAdded.filter(counts).flatMap((signal): Reason[] => { + const partner = (sameHunk: boolean) => removed.findIndex(other => counts(other) && other.kind === signal.kind && other.name === signal.name && + (!sameHunk || other.hunk === signal.hunk)); + const inPlace = partner(true), index = inPlace < 0 ? partner(false) : inPlace; const previous = index < 0 ? null : removed.splice(index, 1)[0]!.value; - return { kind: "timeout-change", path: path.head, line: signal.line, side: "head", - signal: signal.kind, name: signal.name, from: previous, to: signal.value }; + if (inPlace >= 0 && raisedOrEqual(previous!, signal.value)) return []; + return [{ kind: "timeout-change", path: path.head, line: signal.line, side: "head", + signal: signal.kind, name: signal.name, from: previous, to: signal.value }]; }); for (const signal of removed.filter(counts)) { reasons.push({ kind: "timeout-change", path: path.base, line: signal.line, side: "base", diff --git a/tests/proof-system.test.ts b/tests/proof-system.test.ts index 894b4aa668..02f5658a87 100644 --- a/tests/proof-system.test.ts +++ b/tests/proof-system.test.ts @@ -117,30 +117,110 @@ describe("path set", () => { }); describe("timeout-change check", () => { - test("changing a Bun test third-argument timeout is a proof-system change naming file and line", () => { + test("lowering a Bun test third-argument timeout is a proof-system change naming file and line", () => { const repo = fixture(BASE_FILES); - const head = repo.commit({ "packages/core/tests/raft.test.ts": TEST_FILE.replace("}, 5000);", "}, 10000);") }, "slower"); + const head = repo.commit({ "packages/core/tests/raft.test.ts": TEST_FILE.replace("}, 5000);", "}, 2000);") }, "tighter"); const result = classify(repo.base, head, { cwd: repo.dir }); expect(result.proofSystem).toBe(true); expect(result.reasons).toEqual([{ kind: "timeout-change", path: "packages/core/tests/raft.test.ts", line: 7, side: "head", - signal: "test-argument", name: "test", from: "5000", to: "10000" }]); + signal: "test-argument", name: "test", from: "5000", to: "2000" }]); }); - test("changing a single-line test(\"x\", fn, 5000) timeout is flagged", () => { + test("lowering a single-line test(\"x\", fn, 5000) timeout is flagged", () => { const repo = fixture(BASE_FILES); const head = repo.commit({ "packages/core/tests/raft.test.ts": - TEST_FILE.replace("expect(true).toBe(true), 5000);", "expect(true).toBe(true), 10000);") }, "slower"); + TEST_FILE.replace("expect(true).toBe(true), 5000);", "expect(true).toBe(true), 2000);") }, "tighter"); const result = classify(repo.base, head, { cwd: repo.dir }); - expect(result.reasons).toMatchObject([{ kind: "timeout-change", path: "packages/core/tests/raft.test.ts", line: 9, from: "5000", to: "10000" }]); + expect(result.reasons).toMatchObject([{ kind: "timeout-change", path: "packages/core/tests/raft.test.ts", line: 9, from: "5000", to: "2000" }]); }); - test("changing a RESTART_DEADLINE_MS constant is flagged", () => { + test("lowering a RESTART_DEADLINE_MS constant is flagged", () => { const repo = fixture(BASE_FILES); - const head = repo.commit({ "packages/core/tests/raft.test.ts": TEST_FILE.replace("30_000", "60_000") }, "longer deadline"); + const head = repo.commit({ "packages/core/tests/raft.test.ts": TEST_FILE.replace("30_000", "10_000") }, "shorter deadline"); const result = classify(repo.base, head, { cwd: repo.dir }); expect(result.proofSystem).toBe(true); expect(result.reasons).toEqual([{ kind: "timeout-change", path: "packages/core/tests/raft.test.ts", line: 3, side: "head", - signal: "constant", name: "RESTART_DEADLINE_MS", from: "30000", to: "60000" }]); + signal: "constant", name: "RESTART_DEADLINE_MS", from: "30000", to: "10000" }]); + }); + + // A watchdog is a catch-all for the worst case, so raising one is not a proof-system change (#4191). + test.each([ + ["a multi-line third-argument timeout", [["}, 5000);", "}, 10000);"]]], + ["a single-line third-argument timeout", [["expect(true).toBe(true), 5000);", "expect(true).toBe(true), 120_000);"]]], + ["a deadline constant", [["30_000", "60_000"]]], + ["a deadline constant written as a product", [["30_000", "5 * 60 * 1000"]]], + ["every timeout in the file at once", [["}, 5000);", "}, 10000);"], ["expect(true).toBe(true), 5000);", "expect(true).toBe(true), 6000);"], ["30_000", "240_000"]]], + ] as const)("a diff that only raises %s is not a proof-system change", (_name, edits) => { + const repo = fixture(BASE_FILES); + const head = repo.commit({ "packages/core/tests/raft.test.ts": edits.reduce((text, [from, to]) => text.replace(from, to), TEST_FILE) }, "a longer watchdog"); + const result = classify(repo.base, head, { cwd: repo.dir }); + expect(result.reasons, "RAISED_WATCHDOG_IS_NOT_FLAGGED").toEqual([]); + expect(result.proofSystem).toBe(false); + }); + + test("the command reports a raise as not a proof-system change, and a lowering or a removal as one", () => { + const repo = fixture(BASE_FILES); + const raised = repo.commit({ "packages/core/tests/raft.test.ts": TEST_FILE.replace("}, 5000);", "}, 60_000);") }, "raise"); + const up = main(["classify", "--base", repo.base, "--head", raised, "--json"], repo.dir); + expect(JSON.parse(up.stdout), "RAISE_ONLY_DIFF").toMatchObject({ proofSystem: false, reasons: [] }); + expect(main(["classify", "--base", repo.base, "--head", raised], repo.dir).stdout).toStartWith("not a proof-system change"); + const lowered = repo.commit({ "packages/core/tests/raft.test.ts": TEST_FILE.replace("}, 5000);", "}, 4999);") }, "lower"); + const down = main(["classify", "--base", repo.base, "--head", lowered, "--json"], repo.dir); + expect(JSON.parse(down.stdout), "LOWERED_STAYS_FLAGGED").toMatchObject({ proofSystem: true, + reasons: [{ kind: "timeout-change", line: 7, signal: "test-argument", from: "5000", to: "4999" }] }); + // Back from the raised value to the original is a lowering too: the direction is read, not the size. + expect(JSON.parse(main(["classify", "--base", raised, "--head", lowered, "--json"], repo.dir).stdout).reasons) + .toMatchObject([{ kind: "timeout-change", from: "60000", to: "4999" }]); + const removed = repo.commit({ "packages/core/tests/raft.test.ts": TEST_FILE.replace("}, 5000);", "});") }, "remove"); + const gone = main(["classify", "--base", repo.base, "--head", removed, "--json"], repo.dir); + expect(JSON.parse(gone.stdout), "REMOVED_STAYS_FLAGGED").toMatchObject({ proofSystem: true, + reasons: [{ kind: "timeout-change", line: 7, side: "base", from: "5000", to: null }] }); + expect(main(["classify", "--base", repo.base, "--head", removed], repo.dir).stdout).toStartWith("proof-system change"); + }); + + test("a raise beside a lowering reports only the lowering", () => { + const repo = fixture(BASE_FILES); + const head = repo.commit({ "packages/core/tests/raft.test.ts": TEST_FILE.replace("}, 5000);", "}, 10000);").replace("30_000", "20_000") }, "mixed"); + expect(classify(repo.base, head, { cwd: repo.dir }).reasons).toEqual([{ kind: "timeout-change", path: "packages/core/tests/raft.test.ts", line: 3, side: "head", + signal: "constant", name: "RESTART_DEADLINE_MS", from: "30000", to: "20000" }]); + }); + + test("a watchdog that starts reading the scaling helper is not flagged; one that stops, or shrinks inside it, is", () => { + const repo = fixture(BASE_FILES); + const wrapped = TEST_FILE.replace("}, 5000);", "}, watchdogMs(5000));").replace("= 30_000;", "= watchdogMs(30_000);"); + const head = repo.commit({ "packages/core/tests/raft.test.ts": wrapped }, "scale under load"); + expect(classify(repo.base, head, { cwd: repo.dir }).reasons, "ADOPTING_THE_HELPER_IS_A_RAISE").toEqual([]); + const longer = repo.commit({ "packages/core/tests/raft.test.ts": wrapped.replace("watchdogMs(5000)", "watchdogMs(9000)") }, "longer"); + expect(classify(head, longer, { cwd: repo.dir }).reasons).toEqual([]); + const shorter = repo.commit({ "packages/core/tests/raft.test.ts": wrapped.replace("watchdogMs(5000)", "watchdogMs(4000)") }, "shorter"); + expect(classify(head, shorter, { cwd: repo.dir }).reasons).toMatchObject([{ line: 7, from: "watchdogMs(5000)", to: "watchdogMs(4000)" }]); + const unwrapped = repo.commit({ "packages/core/tests/raft.test.ts": wrapped.replace("watchdogMs(5000)", "9000") }, "unscaled again"); + expect(classify(head, unwrapped, { cwd: repo.dir }).reasons, "LEAVING_THE_HELPER_IS_A_LOWERING_UNDER_LOAD") + .toMatchObject([{ line: 7, from: "watchdogMs(5000)", to: "9000" }]); + }); + + test("a change whose direction cannot be read stays flagged", () => { + const file = TEST_FILE.replace("const RESTART_DEADLINE_MS = 30_000;", "const RESTART_DEADLINE_MS = slow ? 60_000 : 30_000; const landingDeadline = Date.now() + 5_000;"); + const repo = fixture({ ...BASE_FILES, "packages/core/tests/raft.test.ts": file }); + const sum = repo.commit({ "packages/core/tests/raft.test.ts": file.replace("Date.now() + 5_000", "Date.now() + 9_000") }, "later"); + expect(classify(repo.base, sum, { cwd: repo.dir }).reasons, "SAME_SHAPE_LARGER_NUMBER_IS_A_RAISE").toEqual([]); + const earlier = repo.commit({ "packages/core/tests/raft.test.ts": file.replace("Date.now() + 5_000", "Date.now() + 1_000") }, "earlier"); + expect(classify(repo.base, earlier, { cwd: repo.dir }).reasons).toMatchObject([{ name: "landingDeadline", from: "Date.now()+5000", to: "Date.now()+1000" }]); + const ternary = repo.commit({ "packages/core/tests/raft.test.ts": file.replace("slow ? 60_000 : 30_000", "slow ? 90_000 : 30_000") }, "conditional"); + expect(classify(repo.base, ternary, { cwd: repo.dir }).reasons, "UNREADABLE_DIRECTION_FAILS_CLOSED").toMatchObject([{ name: "RESTART_DEADLINE_MS", from: "slow?60000:30000", to: "slow?90000:30000" }]); + const reshaped = repo.commit({ "packages/core/tests/raft.test.ts": file.replace("Date.now() + 5_000", "start + 50_000") }, "another clock"); + expect(classify(repo.base, reshaped, { cwd: repo.dir }).reasons).toMatchObject([{ name: "landingDeadline", from: "Date.now()+5000", to: "start+50000" }]); + }); + + test("a timeout that leaves one test while a larger one appears on another is flagged: only a rewrite in place is a raise", () => { + const file = TEST_FILE.replace("expect(true).toBe(true), 5000);", "expect(true).toBe(true));"); + const repo = fixture({ ...BASE_FILES, "packages/core/tests/raft.test.ts": file }); + // Line 7 loses its 5000 and line 9 gains 60000. Paired across hunks they would read as one raised timeout. + const head = repo.commit({ "packages/core/tests/raft.test.ts": file.replace("}, 5000);", "});").replace("expect(true).toBe(true));", "expect(true).toBe(true), 60_000);") }, "moved"); + const result = classify(repo.base, head, { cwd: repo.dir }); + expect(result.proofSystem, "MOVED_TIMEOUT_IS_NOT_A_RAISE").toBe(true); + expect(result.reasons).toEqual([{ kind: "timeout-change", path: "packages/core/tests/raft.test.ts", line: 9, side: "head", + signal: "test-argument", name: "test", from: "5000", to: "60000" }]); }); test("a test-file diff that changes no timeout is not a proof-system change", () => { @@ -207,6 +287,8 @@ describe("timeout-change check", () => { expect(timeoutSignals("setDefaultTimeout(30 * 1000);")).toEqual([{ kind: "call", name: "setDefaultTimeout", value: "30*1000" }]); expect(timeoutSignals("const deadlineMs = 2.5;")).toEqual([{ kind: "constant", name: "deadlineMs", value: "2.5" }]); expect(timeoutSignals("setTimeout(resolve, 100);")).toEqual([]); + expect(timeoutSignals("}, watchdogMs(27_000));")).toEqual([{ kind: "test-argument", name: "test", value: "watchdogMs(27000)" }]); + expect(timeoutSignals('test("x", fn, { timeout: watchdogMs(5 * 1000) });')).toEqual([{ kind: "option", name: "timeout", value: "watchdogMs(5*1000)" }]); expect(timeoutSignals('test("x", fn);')).toEqual([]); }); }); From 5731601dbb50371653b25cab63c1424794b4f5bc Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 15:50:33 +0000 Subject: [PATCH 2/3] chore(ci): scale test watchdogs under the determinism gate (#4191) The gate applies CPU load on purpose, and a timeout that exists to stop a hang is a catch-all for the worst case. The repetition command now multiplies test deadlines by one factor, owned by DETERMINISM_PARTITIONS.deadlineFactor: Bun's per-test cap through a later --timeout, explicit test and hook timeouts through a preload that replaces bun:test with a scaling copy, and in-test watchdogs that read watchdogMs() through the environment. The 27-second watchdog in tests/integration-command.test.ts reads the helper. Co-Authored-By: Claude Fable 5.2 --- scripts/proof-shards.ts | 12 +- scripts/test-deadline-preload.ts | 35 ++++++ scripts/test-deadlines.ts | 112 +++++++++++++++++ scripts/test-determinism.ts | 64 ++++++++-- tests/integration-command.test.ts | 13 +- tests/test-deadlines.test.ts | 197 ++++++++++++++++++++++++++++++ tests/test-determinism.test.ts | 177 +++++++++++++++++++++++++-- 7 files changed, 585 insertions(+), 25 deletions(-) create mode 100644 scripts/test-deadline-preload.ts create mode 100644 scripts/test-deadlines.ts create mode 100644 tests/test-deadlines.test.ts diff --git a/scripts/proof-shards.ts b/scripts/proof-shards.ts index f8d664f19e..67170a4ff5 100644 --- a/scripts/proof-shards.ts +++ b/scripts/proof-shards.ts @@ -40,5 +40,13 @@ export function unitPartitions(cadence: string | undefined, files?: number): num * seconds; capacity times that ratio must fit the step limit. The planner's * `determinism_shards` output, each partition's command, both aggregates, the * merge path and the workflow guard read this table. Measured basis: - * docs/decisions/ci-utility.md, "Changed tests repeat under load before merge". */ -export const DETERMINISM_PARTITIONS = { capacitySeconds: 300, max: 10, stepMinutes: 40, loadRatio: 6.84 } as const; + * docs/decisions/ci-utility.md, "Changed tests repeat under load before merge". + * + * `deadlineFactor` multiplies test deadlines inside the job (#4191): Bun's + * per-test cap, explicit test and hook timeouts and `watchdogMs` watchdogs + * (scripts/test-deadlines.ts). It is the smallest whole number at least 15% + * above `loadRatio`, the largest slowdown measured under the job's own load, + * so a watchdog trips on a hang and not on the load. One hung test waiting out + * its scaled cap after a full capacity must still fit the step limit. Basis: + * docs/decisions/ci-utility.md, "Test watchdogs are a worst-case catch-all". */ +export const DETERMINISM_PARTITIONS = { capacitySeconds: 300, max: 10, stepMinutes: 40, loadRatio: 6.84, deadlineFactor: 8 } as const; diff --git a/scripts/test-deadline-preload.ts b/scripts/test-deadline-preload.ts new file mode 100644 index 0000000000..b3f5cde8fc --- /dev/null +++ b/scripts/test-deadline-preload.ts @@ -0,0 +1,35 @@ +/** + * Preload for a run that applies CPU load on purpose (#4191): multiplies every + * explicit test and hook timeout by the run's factor. + * + * Bun 1.4.2 has no flag for this. `--timeout` and `setDefaultTimeout` set only + * the default: a test that names its own timeout (`test(name, body, 5000)`, + * `{ timeout: 5000 }`) keeps it whatever the invocation says. The repetition + * command (scripts/test-determinism.ts) therefore adds this preload after the + * offline one and sets the factor in the environment. No other command loads + * it, and with a factor of one it does nothing. + * + * It replaces `bun:test` for the invocation with a copy whose registrars scale + * (`scaledTestModule`, scripts/test-deadlines.ts), through Bun's own + * `mock.module`. Verified against Bun 1.4.2: the replacement reaches every + * later import and the runner's globals, in every file and every repetition, + * whether or not an earlier preload already imported `bun:test`; and + * `mock.restore()` in a test does not undo it. Assigning to the object + * `require("bun:test")` returns does not work once anything has imported the + * module, which the offline preload has. + */ +import * as real from "bun:test"; +import { mock } from "bun:test"; +import { deadlineFactor, scaledTestModule } from "./test-deadlines"; + +const factor = deadlineFactor(); +if (factor > 1) { + const scaled = scaledTestModule(real, factor); + mock.module("bun:test", () => scaled); + // An unknown never becomes scaled: if a later Bun stops handing the + // replacement to importers, the run stops here instead of repeating its + // files under unscaled timeouts. + const seen = await import("bun:test") as unknown as Record; + if (seen.test !== scaled.test || seen.beforeEach !== scaled.beforeEach) + throw new Error("bun:test was not replaced for this invocation: explicit test timeouts would stay unscaled under load (scripts/test-deadline-preload.ts)"); +} diff --git a/scripts/test-deadlines.ts b/scripts/test-deadlines.ts new file mode 100644 index 0000000000..2a58cbd354 --- /dev/null +++ b/scripts/test-deadlines.ts @@ -0,0 +1,112 @@ +/** + * Test watchdogs scale under known load (#4191). + * + * A watchdog is a timeout that exists to stop a hang and clean up. It is a + * catch-all for the worst case, so a run that applies CPU load on purpose + * multiplies it by that run's factor instead of letting an honest slow test + * trip it. The `determinism` gate is such a run: it sets the factor in the + * environment of the tests it repeats (scripts/test-determinism.ts), and the + * owner of the number is `DETERMINISM_PARTITIONS.deadlineFactor` + * (scripts/proof-shards.ts). Everywhere else the factor is one and nothing + * here changes a duration. + * + * import { watchdogMs } from "../scripts/test-deadlines"; + * const watchdog = setTimeout(stopEverything, watchdogMs(27_000)); + * + * A product timing (a hold the product promises, a readiness limit) is not a + * watchdog and never goes through this module: it is asserted on measured or + * controlled time. Policy: docs/decisions/ci-utility.md, "Test watchdogs are a + * worst-case catch-all". + */ + +/** Set by a run that applies load on purpose; a whole number from 1 to 100. */ +export const DEADLINE_FACTOR_ENV = "BRAIN_TEST_DEADLINE_FACTOR"; +export const MAX_DEADLINE_FACTOR = 100; + +/** A factor as the owner, the command line or the environment gives it. Anything else is refused, never read as one. */ +export function parseDeadlineFactor(value: unknown): number { + const factor = typeof value === "number" ? value : typeof value === "string" && /^[1-9]\d{0,2}$/.test(value) ? Number(value) : NaN; + if (!Number.isSafeInteger(factor) || factor < 1 || factor > MAX_DEADLINE_FACTOR) + throw new Error(`The test deadline factor is a whole number from 1 to ${MAX_DEADLINE_FACTOR}: ${JSON.stringify(value)}`); + return factor; +} + +/** The factor of this process's run: one unless a loaded run set it. */ +export function deadlineFactor(env: Readonly> = process.env): number { + const raw = env[DEADLINE_FACTOR_ENV]; + return raw === undefined || raw === "" ? 1 : parseDeadlineFactor(raw); +} + +/** A watchdog's duration for this run: the written milliseconds times the run's factor. */ +export function watchdogMs(milliseconds: number, env: Readonly> = process.env): number { + if (!Number.isFinite(milliseconds) || milliseconds <= 0) throw new Error("A watchdog is a positive, finite number of milliseconds"); + return milliseconds * deadlineFactor(env); +} + +type Registrar = (...args: unknown[]) => unknown; + +const scaledOption = (value: unknown, factor: number): unknown => { + if (typeof value === "number") return Number.isFinite(value) ? value * factor : value; + if (value !== null && typeof value === "object" && typeof (value as { timeout?: unknown }).timeout === "number") { + const timeout = (value as { timeout: number }).timeout; + return { ...value, timeout: Number.isFinite(timeout) ? timeout * factor : timeout }; + } + return value; +}; + +/** + * A `bun:test` registrar (`test`, `it`, a hook) whose explicit timeout is + * multiplied by `factor`. The timeout is the number, or the `timeout` of the + * options object, beside the body: `test(name, body, 5000)`, + * `test(name, { timeout: 5000 }, body)`, `beforeAll(body, 5000)`. `bodyFrom` + * is the first position a body may take, one for a test (the name is first) + * and zero for a hook. A call with no body there (`test.each(table)`, + * `test.if(condition)`) is passed through and what it returns is wrapped, as + * is every function-valued property (`test.only`, `test.skip.each`). + */ +export function scaledRegistrar(target: T, factor: number, bodyFrom: number): T { + const targets = new WeakMap(), proxies = new WeakMap(); + const wrap = (registrar: object): object => { + const known = proxies.get(registrar); + if (known) return known; + const proxy = new Proxy(registrar, { + apply(fn, self, args: unknown[]) { + const body = args.findIndex((arg, index) => index >= bodyFrom && typeof arg === "function"); + const scaled = body < 0 ? args : args.map((arg, index) => index >= bodyFrom && index !== body ? scaledOption(arg, factor) : arg); + // Bun checks the receiver's class, so a chained call needs the registrar itself, not its proxy. + const result = Reflect.apply(fn as Registrar, (self !== null && typeof self === "object" || typeof self === "function") ? targets.get(self) ?? self : self, scaled); + return typeof result === "function" ? wrap(result) : result; + }, + get(fn, key) { + const value = Reflect.get(fn, key, fn); + if (typeof value !== "function") return value; + // A proxy must report a frozen data property unchanged. + const own = Reflect.getOwnPropertyDescriptor(fn, key); + return own && "value" in own && !own.configurable && !own.writable ? value : wrap(value); + }, + }); + targets.set(proxy, registrar); proxies.set(registrar, proxy); + return proxy; + }; + return wrap(target) as T; +} + +const TESTS = ["test", "it"] as const, HOOKS = ["beforeAll", "beforeEach", "afterAll", "afterEach"] as const; + +/** + * A copy of a `bun:test` module whose registrars multiply explicit timeouts by + * `factor`, and whose `setDefaultTimeout` does the same for a file-wide + * default. Everything else is the module's own. The originals are read here, + * before the copy replaces the module: afterwards the module's own bindings + * are the scaled ones, and a wrapper that looked itself up would never return. + */ +export function scaledTestModule(real: Readonly>, factor: number): Record { + parseDeadlineFactor(factor); + const scaled: Record = { ...real }; + for (const name of TESTS) scaled[name] = scaledRegistrar(real[name] as object, factor, 1); + for (const name of HOOKS) scaled[name] = scaledRegistrar(real[name] as object, factor, 0); + const setDefault = real.setDefaultTimeout as (milliseconds: number) => void; + scaled.setDefaultTimeout = (milliseconds: number) => setDefault(Number.isFinite(milliseconds) ? milliseconds * factor : milliseconds); + if ("default" in real) scaled.default = scaled; + return scaled; +} diff --git a/scripts/test-determinism.ts b/scripts/test-determinism.ts index c7603988f6..17e236142a 100644 --- a/scripts/test-determinism.ts +++ b/scripts/test-determinism.ts @@ -25,7 +25,19 @@ * hosted CI splits a selection too heavy for one job across partitions (#4117), * and each partition runs this command with its own files. A local `--base` * run repeats the whole selection in one invocation. - * Policy: docs/decisions/ci-utility.md, "Changed tests repeat under load before merge". + * + * Watchdogs scale with the load (#4191). The burners slow every test, and a + * timeout that exists to stop a hang is a catch-all for the worst case, so the + * run multiplies test deadlines by one factor + * (`DETERMINISM_PARTITIONS.deadlineFactor`, scripts/proof-shards.ts): Bun's + * per-test cap through a later `--timeout`, explicit test and hook timeouts + * through a second preload (scripts/test-deadline-preload.ts), and in-test + * watchdogs that read `watchdogMs` (scripts/test-deadlines.ts) through the + * environment. Verified against Bun 1.4.2: the last `--timeout` on the command + * line wins, and neither it nor `setDefaultTimeout` changes a timeout a test + * names itself. A wait a test bounds any other way is not scaled. + * Policy: docs/decisions/ci-utility.md, "Changed tests repeat under load before merge" + * and "Test watchdogs are a worst-case catch-all". */ import { appendFileSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { availableParallelism, constants } from "node:os"; @@ -33,6 +45,8 @@ import { dirname, join, resolve } from "node:path"; import { changedFiles, determinismTests } from "./ci-plan"; import { ensureHostAdmission } from "./host-admission.mjs"; import { planRepetitions, type RepetitionPlan } from "./determinism-plan"; +import { DETERMINISM_PARTITIONS } from "./proof-shards"; +import { DEADLINE_FACTOR_ENV, parseDeadlineFactor } from "./test-deadlines"; import { discoverTests } from "./test-shards"; export { BUDGET_SECONDS, DEFAULT_REPETITIONS, FLOOR_REPETITIONS, planRepetitions, repetitionsFor, type FileRepetitions, type RepetitionPlan } from "./determinism-plan"; @@ -41,18 +55,38 @@ export { BUDGET_SECONDS, DEFAULT_REPETITIONS, FLOOR_REPETITIONS, planRepetitions const BURNER_LIFETIME_MS = 2 * 60 * 60_000, BURNER_SLICE_MS = 200; export const REPORT_KIND = "brain-test-determinism"; const JUNIT_PATH = "tmp/determinism-junit.xml"; +const DEADLINE_PRELOAD = "scripts/test-deadline-preload.ts"; export interface Failure { file: string | null; repetition: number | null; test: string | null; reason: string; } export interface Report extends RepetitionPlan { kind: typeof REPORT_KIND; version: 1; base: string | null; outcome: "passed" | "failed" | "none-selected"; - failure: Failure | null; load: { burners: number; cpus: number }; elapsedSeconds: number; exitCode: number; + failure: Failure | null; load: { burners: number; cpus: number }; + /** The factor test deadlines were multiplied by, and Bun's per-test cap after it. */ + deadlines: { factor: number; testCapMs: number }; + elapsedSeconds: number; exitCode: number; } -/** The wrapper's argv: one invocation, so preparation builds once for every repetition. */ -export function repetitionArgv(files: readonly string[], repetitions: number): string[] { +/** + * Bun's per-test cap for `bun run test`, read from the root script that owns + * it. A script that names none is refused: an unknown cap cannot be scaled. + */ +export function testCapMs(root: string): number { + const script: unknown = JSON.parse(readFileSync(join(root, "package.json"), "utf8"))?.scripts?.test; + const cap = typeof script === "string" ? /(?:^|\s)--timeout[=\s](\d+)(?=\s|$)/.exec(script)?.[1] : undefined; + if (!cap || Number(cap) <= 0) throw new Error("The root test script names no --timeout, so the per-test cap cannot be scaled under load"); + return Number(cap); +} + +/** + * The wrapper's argv: one invocation, so preparation builds once for every + * repetition. `deadlines` adds the scaled per-test cap after the script's own + * `--timeout`, and the preload that scales explicit timeouts. + */ +export function repetitionArgv(files: readonly string[], repetitions: number, deadlines?: { capMs: number; preload: string }): string[] { return [process.execPath, "run", "test", `--rerun-each=${repetitions}`, "--bail=1", - "--reporter=junit", `--reporter-outfile=${JUNIT_PATH}`, ...files.map(file => `./${file}`)]; + "--reporter=junit", `--reporter-outfile=${JUNIT_PATH}`, + ...(deadlines ? [`--timeout=${deadlines.capMs}`, `--preload=${deadlines.preload}`] : []), ...files.map(file => `./${file}`)]; } const plain = (text: string) => text.replace(/\x1b\[[0-9;]*m/g, ""); @@ -121,6 +155,8 @@ export function startBurners(count: number, lifetimeMs = BURNER_LIFETIME_MS): Bu export interface RunOptions { root: string; files: readonly string[]; base?: string | null; repetitions?: number; budgetSeconds?: number; burners?: number; + /** Multiplies test deadlines for the run; the gate's own factor unless named. One leaves every deadline as written. */ + deadlineFactor?: number; costs?: Readonly>; env?: Record; log?: (line: string) => void; /** Receives the wrapper's output as it arrives. */ relay?: (chunk: Uint8Array, channel: "stdout" | "stderr") => void; @@ -148,12 +184,15 @@ export async function runDeterminism(options: RunOptions): Promise { const unknown = options.files.filter(file => !discovered.has(file)); if (unknown.length) throw new Error(`Not a Bun test file under packages/ or tests/: ${unknown.join(", ")}`); const plan = planRepetitions([...options.files].sort(), options); - const base = { kind: REPORT_KIND as typeof REPORT_KIND, version: 1 as const, base: options.base ?? null, ...plan, load: { burners: burnerCount, cpus } }; + const factor = parseDeadlineFactor(options.deadlineFactor ?? DETERMINISM_PARTITIONS.deadlineFactor); + const deadlines = { factor, testCapMs: testCapMs(root) * factor }; + const base = { kind: REPORT_KIND as typeof REPORT_KIND, version: 1 as const, base: options.base ?? null, ...plan, load: { burners: burnerCount, cpus }, deadlines }; if (!plan.files.length) { log("No added or modified Bun test file: nothing to repeat."); return { ...base, load: { burners: 0, cpus }, outcome: "none-selected", failure: null, elapsedSeconds: 0, exitCode: 0 }; } for (const line of describePlan(plan, burnerCount)) log(line); + if (factor > 1) log(`Test deadlines scaled by ${factor} under load: Bun's per-test cap is ${deadlines.testCapMs} ms, and explicit test and hook timeouts and watchdogMs() watchdogs are multiplied the same way.`); const files = plan.files.map(entry => entry.file), started = performance.now(); mkdirSync(dirname(join(root, JUNIT_PATH)), { recursive: true }); rmSync(join(root, JUNIT_PATH), { force: true }); @@ -169,8 +208,9 @@ export async function runDeterminism(options: RunOptions): Promise { burners = startBurners(burnerCount); log(`CPU burners started (PIDs ${burners.pids.join(", ")}).`); if (!cancelled) { - child = Bun.spawn(repetitionArgv(files, plan.repetitions), { cwd: root, stdin: "ignore", stdout: "pipe", stderr: "pipe", - env: { ...process.env, ...options.env } }); + // The factor is always named, so a run asked for one never inherits another run's. + child = Bun.spawn(repetitionArgv(files, plan.repetitions, factor > 1 ? { capMs: deadlines.testCapMs, preload: join(root, DEADLINE_PRELOAD) } : undefined), + { cwd: root, stdin: "ignore", stdout: "pipe", stderr: "pipe", env: { ...process.env, ...options.env, [DEADLINE_FACTOR_ENV]: String(factor) } }); const decoder = new TextDecoder(); const read = async (stream: ReadableStream, channel: "stdout" | "stderr") => { for await (const chunk of stream) { @@ -221,6 +261,7 @@ export function summaryMarkdown(report: Report): string { lines.push(`${report.repetitions} of ${report.requested} requested repetitions per file, ${report.load.burners} burner(s) on ${report.load.cpus} CPU(s); ` + `${report.estimatedSeconds.toFixed(1)} weighted s estimated against a ${report.budgetSeconds} s budget${report.overBudget ? " (over budget at the floor)" : ""}; ` + `${report.elapsedSeconds.toFixed(1)} s elapsed.`, ""); + if (report.deadlines.factor > 1) lines.push(`Test deadlines scaled by ${report.deadlines.factor} (per-test cap ${report.deadlines.testCapMs / 1000} s).`, ""); if (report.failure) lines.push(`**Failed:** \`${report.failure.file ?? "unknown file"}\`, repetition ${report.failure.repetition ?? "unknown"}` + `${report.failure.test ? `, case \`${report.failure.test.replaceAll("`", "'")}\`` : ""} (${report.failure.reason}).`, ""); lines.push("| File | Reviewed weight (s) | Repetitions |", "| --- | --- | --- |"); @@ -228,9 +269,9 @@ export function summaryMarkdown(report: Report): string { return lines.concat("").join("\n"); } -const USAGE = "usage: bun scripts/test-determinism.ts (--base | ...) [--json] [--report ] [--repetitions ] [--budget-seconds ] [--burners ]"; +const USAGE = "usage: bun scripts/test-determinism.ts (--base | ...) [--json] [--report ] [--repetitions ] [--budget-seconds ] [--burners ] [--deadline-factor ]"; -export interface Arguments { base?: string; files: string[]; json: boolean; report?: string; repetitions?: number; budgetSeconds?: number; burners?: number; } +export interface Arguments { base?: string; files: string[]; json: boolean; report?: string; repetitions?: number; budgetSeconds?: number; burners?: number; deadlineFactor?: number; } export function parseArguments(args: readonly string[]): Arguments { const parsed: Arguments = { files: [], json: false }; @@ -247,6 +288,7 @@ export function parseArguments(args: readonly string[]): Arguments { else if (flag === "--repetitions") parsed.repetitions = positive(flag, value()); else if (flag === "--budget-seconds") parsed.budgetSeconds = positive(flag, value()); else if (flag === "--burners") parsed.burners = positive(flag, value()); + else if (flag === "--deadline-factor") parsed.deadlineFactor = parseDeadlineFactor(positive(flag, value())); else if (flag.startsWith("-")) throw new Error(`Unknown option ${flag}\n${USAGE}`); else parsed.files.push(flag.replace(/^\.\//, "")); } @@ -265,7 +307,7 @@ if (import.meta.main) { if (admitted !== undefined) process.exit(admitted); } const report = await runDeterminism({ root, files, base: args.base ?? null, repetitions: args.repetitions, - budgetSeconds: args.budgetSeconds, burners: args.burners, + budgetSeconds: args.budgetSeconds, burners: args.burners, deadlineFactor: args.deadlineFactor, relay: (chunk, channel) => { process[args.json ? "stderr" : channel].write(chunk); } }); if (args.report) { mkdirSync(dirname(resolve(root, args.report)), { recursive: true }); diff --git a/tests/integration-command.test.ts b/tests/integration-command.test.ts index 9b38715056..e45ddb7752 100644 --- a/tests/integration-command.test.ts +++ b/tests/integration-command.test.ts @@ -7,6 +7,7 @@ import { declareFix, emptyRedMain, openRed } from "../scripts/red-main"; import { receiptBlock, type CheckReceipt } from "../scripts/check-receipt"; import { reviewComment, type ReviewFinding } from "../scripts/review-receipt"; import { invocationChild } from "../scripts/test-invocation-child"; +import { watchdogMs } from "../scripts/test-deadlines"; import { processIdentity } from "../scripts/workspace-lease.mjs"; const dirs: string[] = []; @@ -17,13 +18,15 @@ const scenarios = new Set(); let deadline: ReturnType, overdue = false, deadlineCleanup: Promise | undefined; beforeEach(() => { overdue = false; deadlineCleanup = undefined; - // Bun kills dangling children before afterEach on timeout. Reserve three - // seconds inside its unchanged 30-second cap for the owned group/output join. + // Bun kills dangling children before afterEach on timeout. Reserve a tenth + // of its per-test cap, three of 30 seconds, for the owned group/output join. + // This is a watchdog for a hung child, not a budget for the work: a run that + // applies load on purpose scales it with the cap (#4191). deadline = setTimeout(() => { overdue = true; deadlineCleanup = stopScenarios(); void deadlineCleanup.catch(() => {}); // afterEach observes cleanup errors. - }, 27_000); + }, watchdogMs(27_000)); }); async function stopScenarios() { const active = [...scenarios]; @@ -54,7 +57,7 @@ function startScenario(mode: string, beforeRead?: () => Promise) { } function scenario(mode: string) { return startScenario(mode).work; } async function runScenario(mode: string, owner: Scenario): Promise { - if (overdue) throw new Error("Integration fixture work deadline exceeded; owned cleanup joined inside the 30-second test cap"); + if (overdue) throw new Error("Integration fixture work deadline exceeded; owned cleanup joined inside the per-test cap"); const dir = mkdtempSync(join(tmpdir(), "odysseus-integration-command-")); dirs.push(dir); owner.dir = dir; const root = join(dir, "client"), remote = join(dir, "remote.git"), bin = join(dir, "bin"); @@ -276,7 +279,7 @@ fi`); await child.ready; const [code, out, err] = await output; await child.finish(); - if (overdue) throw new Error("Integration fixture work deadline exceeded; owned cleanup joined inside the 30-second test cap"); + if (overdue) throw new Error("Integration fixture work deadline exceeded; owned cleanup joined inside the per-test cap"); await owner.beforeRead?.(); const eventDir = join(root, "tmp/ci-timings"); const events = existsSync(eventDir) ? readdirSync(eventDir).filter(name => name.startsWith("event-")).map(name => JSON.parse(readFileSync(join(eventDir, name), "utf8"))) : []; diff --git a/tests/test-deadlines.test.ts b/tests/test-deadlines.test.ts new file mode 100644 index 0000000000..0a5fb645c9 --- /dev/null +++ b/tests/test-deadlines.test.ts @@ -0,0 +1,197 @@ +// Test watchdogs scale under known load (#4191). The pure parts are tested +// directly; the last receipt runs real `bun test` with the scaling preload. +import { afterEach, describe, expect, test } from "bun:test"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { DEADLINE_FACTOR_ENV, deadlineFactor, parseDeadlineFactor, scaledRegistrar, scaledTestModule, watchdogMs } from "../scripts/test-deadlines"; + +const ROOT = join(import.meta.dir, ".."); +const scratch: string[] = []; +afterEach(() => { for (const dir of scratch.splice(0)) rmSync(dir, { recursive: true, force: true }); }); + +describe("the factor", () => { + test("is one unless a loaded run set it, so a watchdog keeps its written duration", () => { + expect(deadlineFactor({})).toBe(1); + expect(deadlineFactor({ [DEADLINE_FACTOR_ENV]: "" })).toBe(1); + expect(watchdogMs(27_000, {}), "UNLOADED_WATCHDOG_IS_UNCHANGED").toBe(27_000); + }); + + test("multiplies a watchdog under a loaded run", () => { + expect(deadlineFactor({ [DEADLINE_FACTOR_ENV]: "8" })).toBe(8); + expect(watchdogMs(27_000, { [DEADLINE_FACTOR_ENV]: "8" }), "WATCHDOG_SCALES_WITH_THE_RUN").toBe(216_000); + expect(watchdogMs(0.5, { [DEADLINE_FACTOR_ENV]: "100" })).toBe(50); + }); + + test("a malformed factor is refused, never read as one", () => { + for (const raw of ["0", "-2", "1.5", "8x", " 8", "0x8", "101", "1000", "NaN"]) { + expect(() => deadlineFactor({ [DEADLINE_FACTOR_ENV]: raw }), raw).toThrow("whole number from 1 to 100"); + expect(() => watchdogMs(1000, { [DEADLINE_FACTOR_ENV]: raw }), raw).toThrow("whole number from 1 to 100"); + } + for (const value of [0, 1.5, 101, NaN, Infinity, null, undefined, {}]) expect(() => parseDeadlineFactor(value), String(value)).toThrow("whole number from 1 to 100"); + expect([parseDeadlineFactor(1), parseDeadlineFactor("100"), parseDeadlineFactor(8)]).toEqual([1, 100, 8]); + }); + + test("a watchdog is a positive, finite duration", () => { + for (const value of [0, -1, NaN, Infinity]) expect(() => watchdogMs(value, {}), String(value)).toThrow("positive, finite number of milliseconds"); + }); +}); + +/** A stand-in registrar that records what reaches it, with the chained forms `bun:test` has. */ +function registrar() { + const calls: { via: string; self: unknown; args: unknown[] }[] = []; + const base = function (this: unknown, ...args: unknown[]) { calls.push({ via: "test", self: this, args }); } as ((...args: unknown[]) => void) & Record; + base.only = function (this: unknown, ...args: unknown[]) { calls.push({ via: "only", self: this, args }); }; + base.each = function (this: unknown, ...table: unknown[]) { + calls.push({ via: "each", self: this, args: table }); + return (...args: unknown[]) => { calls.push({ via: "each-row", self: undefined, args }); }; + }; + base.label = "the registrar"; + Object.defineProperty(base, "frozen", { value: () => "frozen", writable: false, configurable: false }); + return { base, calls }; +} + +describe("a scaled registrar", () => { + const body = () => {}, FACTOR = 8; + + test("multiplies the number or the options timeout beside a test body, and nothing else", () => { + const { base, calls } = registrar(), scaled = scaledRegistrar(base, FACTOR, 1); + scaled("the bow is strung", body, 5000); + scaled("the bow is strung", body, { timeout: 5000, retry: 2 }); + scaled("the bow is strung", { timeout: 5000 }, body); + scaled("the bow is strung", body); + scaled("twelve axes", body, { retry: 2 }); + expect(calls.map(call => call.args)).toEqual([ + ["the bow is strung", body, 40_000], + ["the bow is strung", body, { timeout: 40_000, retry: 2 }], + ["the bow is strung", { timeout: 40_000 }, body], + ["the bow is strung", body], + ["twelve axes", body, { retry: 2 }], + ]); + }); + + test("leaves the caller's options object alone, and a timeout that is not finite", () => { + const { base, calls } = registrar(), scaled = scaledRegistrar(base, FACTOR, 1); + const options = { timeout: 250 }; + scaled("the suitors wait", body, options); + scaled("the loom is unpicked", body, Infinity); + expect(options, "CALLER_OPTIONS_NOT_MUTATED").toEqual({ timeout: 250 }); + expect(calls.map(call => call.args[2])).toEqual([{ timeout: 2000 }, Infinity]); + }); + + test("a hook's timeout follows its body in first position", () => { + const { base, calls } = registrar(), scaled = scaledRegistrar(base, FACTOR, 0); + scaled(body, 300); + scaled(body, { timeout: 300 }); + scaled(body); + expect(calls.map(call => call.args)).toEqual([[body, 2400], [body, { timeout: 2400 }], [body]]); + }); + + test("chained forms scale too: a property, and the registrar a table returns", () => { + const { base, calls } = registrar(), scaled = scaledRegistrar(base, FACTOR, 1) as typeof base & { only: (...args: unknown[]) => void; each: (...table: unknown[]) => (...args: unknown[]) => void }; + scaled.only("the scar is recognised", body, 100); + // The table is not a test: a number in it is data, not a timeout. + scaled.each([1, 2], 7)("ship %d", body, 100); + expect(calls.map(call => [call.via, call.args])).toEqual([ + ["only", ["the scar is recognised", body, 800]], + ["each", [[1, 2], 7]], + ["each-row", ["ship %d", body, 800]], + ]); + }); + + test("a chained call reaches the registrar itself as its receiver, as Bun requires", () => { + const { base, calls } = registrar(), scaled = scaledRegistrar(base, FACTOR, 1) as typeof base & { only: (...args: unknown[]) => void }; + scaled.only("the scar is recognised", body); + expect(calls[0]!.self, "RECEIVER_IS_THE_REAL_REGISTRAR").toBe(base); + expect(scaled.only).toBe(scaled.only); + }); + + test("other properties pass through unchanged, a frozen one included", () => { + const { base } = registrar(), scaled = scaledRegistrar(base, FACTOR, 1) as typeof base & { frozen: () => string }; + expect(scaled.label).toBe("the registrar"); + expect(scaled.frozen()).toBe("frozen"); + }); +}); + +describe("a scaled bun:test module", () => { + test("scales tests, hooks and the file-wide default, and keeps everything else", () => { + const seen: Record = {}; + const record = (name: string) => (...args: unknown[]) => { (seen[name] ??= []).push(args); }; + const expectStandIn = () => "expect"; + const real: Record = { describe: record("describe"), expect: expectStandIn, default: {} }; + for (const name of ["test", "it", "beforeAll", "beforeEach", "afterAll", "afterEach", "setDefaultTimeout"]) real[name] = record(name); + const scaled = scaledTestModule(real, 4) as Record void>; + const body = () => {}; + scaled.test!("the raft holds", body, 100); scaled.it!("the raft holds", body, { timeout: 100 }); + for (const hook of ["beforeAll", "beforeEach", "afterAll", "afterEach"]) scaled[hook]!(body, 100); + scaled.setDefaultTimeout!(100); scaled.describe!("the voyage", body, 100); + expect(seen).toEqual({ test: [["the raft holds", body, 400]], it: [["the raft holds", body, { timeout: 400 }]], + beforeAll: [[body, 400]], beforeEach: [[body, 400]], afterAll: [[body, 400]], afterEach: [[body, 400]], + setDefaultTimeout: [[400]], describe: [["the voyage", body, 100]] }); + expect(scaled.expect as unknown, "EVERYTHING_ELSE_IS_THE_MODULE'S_OWN").toBe(expectStandIn); + expect(scaled.default as unknown, "DEFAULT_EXPORT_IS_THE_SCALED_MODULE").toBe(scaled); + expect(real.test, "THE_REAL_MODULE_IS_NOT_MUTATED").not.toBe(scaled.test); + expect(() => scaledTestModule(real, 0)).toThrow("whole number from 1 to 100"); + }); +}); + +// Timeouts of 100 ms around work of 300 ms: certain to trip unscaled, and far inside +// twenty times the timeout however loaded this host is. +const FLEET = `import { beforeAll, describe, expect, it, mock, test } from "bun:test"; +const row = async () => { await Bun.sleep(300); }; +test("a number beside the body", row, 100); +test("an options object", row, { timeout: 100 }); +it("the it alias", row, 100); +test.each([1, 2])("a table row %d", async ship => { await row(); expect(ship).toBeGreaterThan(0); }, 100); +describe("in a group", () => { + beforeAll(row, 100); + test("after a slow hook", () => { mock.restore(); expect(1).toBe(1); }); + test("after a test restored its mocks", row, 100); +}); +`; +// The runner's globals, with no import at all. +const GLOBALS = `test("a global registrar", async () => { await Bun.sleep(300); }, 100);\n`; + +describe("the scaling preload, under real bun test", () => { + function fleet() { + const dir = mkdtempSync(join(tmpdir(), "odysseus-test-deadlines-")); scratch.push(dir); + writeFileSync(join(dir, "fleet.test.ts"), FLEET); writeFileSync(join(dir, "globals.test.ts"), GLOBALS); + // An earlier preload that already imported bun:test, as the offline preload has. + writeFileSync(join(dir, "earlier.ts"), 'import { afterEach } from "bun:test";\nafterEach(() => {});\n'); + return dir; + } + async function run(dir: string, factor: string | undefined, ...flags: string[]) { + const env: Record = { ...process.env, [DEADLINE_FACTOR_ENV]: factor }; + for (const name of ["CLAUDECODE", "AGENT", "REPL_ID", "CI", "GITHUB_ACTIONS"]) delete env[name]; + const proc = Bun.spawn([process.execPath, "test", "--preload", "./earlier.ts", "--preload", join(ROOT, "scripts/test-deadline-preload.ts"), + "--timeout", "30000", ...flags, "./fleet.test.ts", "./globals.test.ts"], { cwd: dir, stdout: "pipe", stderr: "pipe", env }); + const [out, err, code] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]); + return { code, output: (out + err).replace(/\x1b\[[0-9;]*m/g, "") }; + } + + test("every explicit timeout form is multiplied, in each file and each repetition", async () => { + const result = await run(fleet(), "20", "--rerun-each=2"); + expect(result.output, "EXPLICIT_TIMEOUTS_SCALED").toContain(" 0 fail"); + expect(result.code, result.output).toBe(0); + // Seven tests in the fleet and one global, twice. + expect(result.output, "EVERY_FORM_RAN_TWICE").toContain(" 16 pass"); + }, 60_000); + + test.each([["unset", undefined], ["one", "1"]] as const)("with the factor %s the preload does nothing, and the same tests trip their timeouts", async (_name, factor) => { + const result = await run(fleet(), factor); + expect(result.code, result.output).toBe(1); + for (const name of ["a number beside the body", "an options object", "the it alias", "a table row 1", "a table row 2", "a global registrar"]) + expect(result.output, "UNSCALED_TIMEOUT_TRIPS").toContain(`(fail) ${name} [`); + expect(result.output).toContain("this test timed out after 100ms"); + // The group never gets past its slow hook. + expect(result.output, "UNSCALED_HOOK_TIMEOUT_TRIPS").toContain("(fail) in a group >"); + expect(result.output).toContain("hook timed out"); + }, 60_000); + + test("a malformed factor stops the run instead of repeating it unscaled", async () => { + const result = await run(fleet(), "eight"); + expect(result.code).not.toBe(0); + expect(result.output).toContain("The test deadline factor is a whole number from 1 to 100"); + expect(result.output).not.toContain(" 0 fail"); + }, 60_000); +}); diff --git a/tests/test-determinism.test.ts b/tests/test-determinism.test.ts index 3c84ce7221..0dc01b9d0b 100644 --- a/tests/test-determinism.test.ts +++ b/tests/test-determinism.test.ts @@ -7,7 +7,7 @@ import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { BUDGET_SECONDS, burnerSource, DEFAULT_REPETITIONS, firstFailure, FLOOR_REPETITIONS, observedRepetitions, parseArguments, - planRepetitions, repetitionArgv, REPORT_KIND, startBurners, summaryMarkdown, type Report, + planRepetitions, repetitionArgv, REPORT_KIND, startBurners, summaryMarkdown, testCapMs, type Report, } from "../scripts/test-determinism"; import { planPartitions, selectPartition } from "../scripts/determinism-plan"; import { DETERMINISM_PARTITIONS } from "../scripts/proof-shards"; @@ -16,7 +16,7 @@ const ROOT = join(import.meta.dir, ".."); // The wrapper, its preload and what they import, as tests/experiment-tier.test.ts copies them. const SCRIPTS = ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs", - "test-determinism.ts", "determinism-plan.ts", "proof-shards.ts"]; + "test-determinism.ts", "determinism-plan.ts", "proof-shards.ts", "test-deadlines.ts", "test-deadline-preload.ts"]; const scratch: string[] = []; afterEach(() => { for (const dir of scratch.splice(0)) rmSync(dir, { recursive: true, force: true }); }); @@ -72,6 +72,22 @@ describe("repetition budget", () => { expect(argv.slice(1)).toEqual(["run", "test", "--rerun-each=4", "--bail=1", "--reporter=junit", "--reporter-outfile=tmp/determinism-junit.xml", "./tests/argo.test.ts", "./packages/core/tests/ithaca.test.ts"]); }); + + // Bun 1.4.2 takes the last --timeout, so the scaled cap follows the root script's own (#4191). + test("a scaled invocation names the scaled cap and the scaling preload after the wrapper's own flags", () => { + const argv = repetitionArgv(["tests/argo.test.ts"], 2, { capMs: 240_000, preload: "/odyssey/scripts/test-deadline-preload.ts" }); + expect(argv.slice(1)).toEqual(["run", "test", "--rerun-each=2", "--bail=1", "--reporter=junit", "--reporter-outfile=tmp/determinism-junit.xml", + "--timeout=240000", "--preload=/odyssey/scripts/test-deadline-preload.ts", "./tests/argo.test.ts"]); + }); + + test("the cap that is scaled is the root test script's own, and a script without one is refused", () => { + expect(testCapMs(ROOT), "ONE_OWNER_FOR_THE_CAP").toBe(30_000); + const dir = mkdtempSync(join(tmpdir(), "test-determinism-cap-")); scratch.push(dir); + writeFileSync(join(dir, "package.json"), JSON.stringify({ scripts: { test: "bun scripts/test.ts --timeout=1500 --bail" } })); + expect(testCapMs(dir)).toBe(1500); + writeFileSync(join(dir, "package.json"), JSON.stringify({ scripts: { test: "bun scripts/test.ts" } })); + expect(() => testCapMs(dir)).toThrow("names no --timeout"); + }); }); describe("hosted partitions by reviewed weight (#4117)", () => { @@ -82,10 +98,18 @@ describe("hosted partitions by reviewed weight (#4117)", () => { const sum = (values: readonly number[]) => values.reduce((total, value) => total + value, 0); test("the calibrated numbers have one owner, and its capacity fits the step limit at the measured load ratio", () => { - expect(DETERMINISM_PARTITIONS).toEqual({ capacitySeconds: 300, max: 10, stepMinutes: 40, loadRatio: 6.84 }); + expect(DETERMINISM_PARTITIONS).toEqual({ capacitySeconds: 300, max: 10, stepMinutes: 40, loadRatio: 6.84, deadlineFactor: 8 }); expect(capacitySeconds * DETERMINISM_PARTITIONS.loadRatio, "CAPACITY_FITS_THE_STEP_LIMIT").toBeLessThanOrEqual(DETERMINISM_PARTITIONS.stepMinutes * 60); }); + test("the deadline factor covers the measured slowdown with margin, and one hung test still fits the step limit", () => { + const { deadlineFactor, loadRatio, stepMinutes } = DETERMINISM_PARTITIONS; + expect(Number.isSafeInteger(deadlineFactor)).toBe(true); + expect(deadlineFactor, "FACTOR_COVERS_THE_MEASURED_SLOWDOWN_WITH_MARGIN").toBeGreaterThanOrEqual(loadRatio * 1.15); + // --bail=1 ends the run at the first failure, so at most one test waits out its scaled cap. + expect(capacitySeconds * loadRatio + testCapMs(ROOT) * deadlineFactor / 1000, "STEP_LIMIT_STILL_BOUNDS_A_SCALED_RUN").toBeLessThanOrEqual(stepMinutes * 60); + }); + test("a selection the size of the largest observed plans several partitions, each within capacity, covering every file once", () => { // The 388-file fixture migration: about 1,327 weighted seconds per pass, 2,654 at the floor of two. const costs = fleet(388, 1327), files = Object.keys(costs); @@ -220,8 +244,9 @@ describe("reading the wrapper's output", () => { test("the job summary lists each file with the repetitions it got", () => { const report: Report = { kind: REPORT_KIND, version: 1, base: null, ...planRepetitions(["tests/argo.test.ts"], { costs: { "tests/argo.test.ts": 400 } }), outcome: "failed", failure: { file: "tests/argo.test.ts", repetition: 2, test: "rows `past` the sirens", reason: "a test case failed" }, - load: { burners: 4, cpus: 4 }, elapsedSeconds: 12.5, exitCode: 1 }; + load: { burners: 4, cpus: 4 }, deadlines: { factor: 8, testCapMs: 240_000 }, elapsedSeconds: 12.5, exitCode: 1 }; const summary = summaryMarkdown(report); + expect(summary, "SUMMARY_NAMES_THE_SCALING").toContain("Test deadlines scaled by 8 (per-test cap 240 s)"); expect(summary).toContain("2 of 5 requested repetitions per file"); expect(summary).toContain("(over budget at the floor)"); expect(summary).toContain("| `tests/argo.test.ts` | 400 | 2 |"); @@ -293,7 +318,7 @@ function sh(dir: string, ...argv: string[]): string { } /** A committed scratch checkout carrying the real command, wrapper and preload; returns its base commit. */ -function checkout(weights: Record = {}) { +function checkout(weights: Record = {}, capMs = 30_000) { const dir = mkdtempSync(join(tmpdir(), "test-determinism-")); scratch.push(dir); const write = (path: string, text: string) => { mkdirSync(dirname(join(dir, path)), { recursive: true }); writeFileSync(join(dir, path), text); }; for (const script of SCRIPTS) cpSync(join(ROOT, "scripts", script), join(dir, "scripts", script)); @@ -301,9 +326,9 @@ function checkout(weights: Record = {}) { write("scripts/ci-plan.ts", `export * from ${JSON.stringify(join(ROOT, "scripts/ci-plan.ts"))};\n`); write("scripts/test-shard-costs.json", JSON.stringify(weights)); cpSync(join(ROOT, "packages/core/tests/cli-harness.ts"), join(dir, "packages/core/tests/cli-harness.ts"), { recursive: true }); - write("package.json", JSON.stringify({ name: "odysseus-determinism", private: true, scripts: { test: "bun scripts/test.ts --timeout 30000" } })); + write("package.json", JSON.stringify({ name: "odysseus-determinism", private: true, scripts: { test: `bun scripts/test.ts --timeout ${capMs}` } })); write("bun.lock", "{ \"lockfileVersion\": 1 }\n"); - write(".gitignore", "tmp/\nnode_modules/\n*.count\nprobe-runtime\nstep-summary.md\n"); + write(".gitignore", "tmp/\nnode_modules/\n*.count\n*.pid\nprobe-runtime\nstep-summary.md\n"); write("tests/harbour.test.ts", PASSING("the harbour is calm")); write("tests/retired.test.ts", PASSING("the old route")); const commit = (message: string) => { sh(dir, "git", "add", "-A"); sh(dir, "git", "-c", "commit.gpgsign=false", "commit", "-q", "-m", message); return sh(dir, "git", "rev-parse", "HEAD"); }; @@ -437,3 +462,141 @@ describe("the command, through the real offline wrapper", () => { expect(unknown.stderr.toString()).toContain("Not a Bun test file under packages/ or tests/: docs/voyage.md"); }, 60_000); }); + +// Watchdogs are a catch-all for the worst case (#4191). Each fixture's work is +// half its 500 ms watchdog in calm water. `ODYSSEUS_HEADWIND` multiplies the +// work the way the gate's CPU load does, so the receipts do not depend on how +// slow this host happens to be: three times the work overruns the unscaled +// watchdog and fits the scaled one. Sleeping, not computing, keeps the +// overrun certain and the scaled run far inside its watchdog under real load. +const HEADWIND = `const headwind = Number(process.env.ODYSSEUS_HEADWIND ?? 1);\n`; +const WATCHDOG_FIXTURES = { + // No timeout of its own: the root script's cap is its watchdog. + "tests/cap.test.ts": `import { expect, test } from "bun:test";\n${HEADWIND}test("the crew rows home inside the runner's cap", async () => { + await Bun.sleep(250 * headwind); + expect(headwind).toBeGreaterThan(0); +}); +`, + "tests/explicit.test.ts": `import { expect, test } from "bun:test";\n${HEADWIND}test("the crew rows home inside the test's own timeout", async () => { + await Bun.sleep(250 * headwind); + expect(headwind).toBeGreaterThan(0); +}, 500); +`, + // The shape of tests/integration-command.test.ts: a timer in the test stops the work before the runner would. + "tests/watchdog.test.ts": `import { afterEach, beforeEach, expect, test } from "bun:test"; +import { watchdogMs } from "../scripts/test-deadlines"; +${HEADWIND}let watchdog: ReturnType, overdue = false; +beforeEach(() => { overdue = false; watchdog = setTimeout(() => { overdue = true; }, watchdogMs(500)); }); +afterEach(() => clearTimeout(watchdog)); +test("the crew rows home before the lookout gives up", async () => { + await Bun.sleep(250 * headwind); + expect(overdue, "IN_TEST_WATCHDOG_TRIPPED").toBe(false); +}, 60_000); +`, +} as const; +// A child that outlives any watchdog; the test records its PID and waits for it. +const HANGING_CHILD = `const child = Bun.spawn(["sleep", "300"], { stdio: ["ignore", "ignore", "ignore"] }); + writeFileSync(join(import.meta.dir, "lotus.pid"), String(child.pid));`; +const HUNG_UNDER_THE_CAP = `import { expect, test } from "bun:test"; +import { writeFileSync } from "node:fs"; +import { join } from "node:path"; +test("the lotus-eaters never let the crew leave", async () => { + ${HANGING_CHILD} + await child.exited; + expect.unreachable(); +}); +`; +const HUNG_UNDER_ITS_OWN_WATCHDOG = `import { afterEach, beforeEach, expect, test } from "bun:test"; +import { writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { watchdogMs } from "../scripts/test-deadlines"; +let watchdog: ReturnType, stop = () => {}, overdue = false; +beforeEach(() => { overdue = false; watchdog = setTimeout(() => { overdue = true; stop(); }, watchdogMs(200)); }); +afterEach(() => clearTimeout(watchdog)); +test("the lotus-eaters never let the crew leave", async () => { + ${HANGING_CHILD} + stop = () => child.kill("SIGKILL"); + await child.exited; + expect(overdue, "IN_TEST_WATCHDOG_STOPPED_THE_HANG").toBe(false); +}, 60_000); +`; + +describe("watchdogs scale under the gate (#4191)", () => { + const { deadlineFactor } = DETERMINISM_PARTITIONS; + const headwind = (dir: string) => ({ ...scratchEnv(dir), ODYSSEUS_HEADWIND: "3" }); + function slowFleet() { + const f = checkout({}, 500); + for (const [path, source] of Object.entries(WATCHDOG_FIXTURES)) f.write(path, source); + f.commit("three watchdogs, each twice the work in calm water"); + return f; + } + + test("tests that take half their watchdog in calm water pass under the gate's factor, with every watchdog kind scaled", async () => { + const f = slowFleet(); + const run = await determinismUnder(headwind(f.dir), f.dir, "--base", f.base, "--repetitions", "2"); + expect(run.report.failure, run.output).toBeNull(); + expect(run.code, "SLOW_TESTS_PASS_UNDER_THE_SCALED_WATCHDOGS").toBe(0); + expect(run.report.deadlines, "REPORT_NAMES_THE_FACTOR_AND_THE_SCALED_CAP").toEqual({ factor: deadlineFactor, testCapMs: 500 * deadlineFactor }); + expect(run.report.files.map(entry => [entry.file, entry.observed]), "EVERY_KIND_RAN_EVERY_REPETITION") + .toEqual([["tests/cap.test.ts", 2], ["tests/explicit.test.ts", 2], ["tests/watchdog.test.ts", 2]]); + expect(run.output).toContain(`Test deadlines scaled by ${deadlineFactor}`); + }, 90_000); + + test.each([ + ["tests/cap.test.ts", "the crew rows home inside the runner's cap", "this test timed out after 500ms"], + ["tests/explicit.test.ts", "the crew rows home inside the test's own timeout", "this test timed out after 500ms"], + ["tests/watchdog.test.ts", "the crew rows home before the lookout gives up", "IN_TEST_WATCHDOG_TRIPPED"], + ] as const)("without the scaling the same slow test in %s trips its watchdog", async (file, name, evidence) => { + const f = slowFleet(); + const run = await determinismUnder(headwind(f.dir), f.dir, "--deadline-factor", "1", "--repetitions", "2", file); + expect(run.code, run.output).toBe(1); + expect(run.report.failure, "UNSCALED_WATCHDOG_TRIPS").toEqual({ file, repetition: 1, test: name, reason: "a test case failed" }); + expect(run.output, "TRIPPED_BY_ITS_OWN_WATCHDOG").toContain(evidence); + expect(run.report.deadlines).toEqual({ factor: 1, testCapMs: 500 }); + }, 60_000); + + async function hung(source: string) { + const f = checkout({}, 250); f.write("tests/lotus.test.ts", source); f.commit("a test that never returns"); + const started = performance.now(); + const run = await determinism(f.dir, "--base", f.base); + const child = Number(readFileSync(join(f.dir, "tests/lotus.pid"), "utf8")); + return { run, child, elapsedMs: performance.now() - started }; + } + + test("a test that truly hangs still fails at the scaled cap, and its child is gone", async () => { + const { run, child, elapsedMs } = await hung(HUNG_UNDER_THE_CAP); + try { + expect(run.code, run.output).toBe(1); + expect(run.report.failure, "HANG_STILL_FAILS").toEqual({ file: "tests/lotus.test.ts", repetition: 1, + test: "the lotus-eaters never let the crew leave", reason: "a test case failed" }); + expect(run.output, "AT_THE_SCALED_CAP").toContain(`this test timed out after ${250 * deadlineFactor}ms`); + expect(elapsedMs, "WITHIN_THE_SCALED_WATCHDOG").toBeLessThan(45_000); + expect(Number.isSafeInteger(child) && child > 1, "CHILD_PID_RECORDED").toBe(true); + expect(await gone(child, 5000), "HUNG_CHILD_CLEANED_UP").toBe(true); + } finally { if (alive(child)) process.kill(child, "SIGKILL"); } + }, 90_000); + + test("a hang under an in-test watchdog is stopped by that watchdog at its scaled duration, and its child is gone", async () => { + const { run, child } = await hung(HUNG_UNDER_ITS_OWN_WATCHDOG); + try { + expect(run.code, run.output).toBe(1); + expect(run.report.failure).toMatchObject({ file: "tests/lotus.test.ts", repetition: 1, test: "the lotus-eaters never let the crew leave" }); + expect(run.output, "STOPPED_BY_THE_IN_TEST_WATCHDOG").toContain("IN_TEST_WATCHDOG_STOPPED_THE_HANG"); + // Bun reports the case's own duration: it waited out the scaled watchdog, not the written 200 ms. + const reported = /\(fail\) the lotus-eaters never let the crew leave \[([\d.]+)(ms|s)\]/.exec(run.output.replace(/\x1b\[[0-9;]*m/g, "")); + const waitedMs = reported ? Number(reported[1]) * (reported[2] === "s" ? 1000 : 1) : NaN; + expect(waitedMs, "WAITED_THE_SCALED_WATCHDOG").toBeGreaterThanOrEqual(200 * deadlineFactor); + expect(waitedMs, "NOT_THE_TEST_TIMEOUT").toBeLessThan(45_000); + expect(await gone(child, 5000), "HUNG_CHILD_CLEANED_UP").toBe(true); + } finally { if (alive(child)) process.kill(child, "SIGKILL"); } + }, 90_000); + + test("a factor outside the range is refused before anything runs", async () => { + const f = checkout(); + const refused = Bun.spawnSync([unguardedRuntime(f.dir), join(f.dir, "scripts/test-determinism.ts"), "--burners", "1", "--deadline-factor", "101", "tests/harbour.test.ts"], + { cwd: f.dir, stdout: "pipe", stderr: "pipe", env: scratchEnv(f.dir) }); + expect(refused.exitCode).toBe(1); + expect(refused.stderr.toString()).toContain("The test deadline factor is a whole number from 1 to 100"); + expect(refused.stderr.toString()).not.toContain("CPU burners started"); + }, 30_000); +}); From 93fcb661490d4d500dbd42dffdf5621a20396878 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 15:56:00 +0000 Subject: [PATCH 3/3] docs: test watchdogs are a worst-case catch-all (#4191) Records the 2026-11-17 ruling and what it supersedes: the practice of treating every test deadline as proof that must not move. The decision record states the two kinds of number, the gate's factor of eight with the hosted runs behind it, what stays unscaled, and what the proof-system check still flags. The process docs say how to size a watchdog and what to do when one trips. Co-Authored-By: Claude Fable 5.2 --- .agents/skills/test-health/SKILL.md | 9 +- AGENTS.md | 6 + docs/decisions/ci-utility.md | 197 ++++++++++++++++++++++++++-- docs/process/test-authoring.md | 25 +++- docs/process/test-waits.md | 2 +- docs/process/testing.md | 69 +++++++++- 6 files changed, 288 insertions(+), 20 deletions(-) diff --git a/.agents/skills/test-health/SKILL.md b/.agents/skills/test-health/SKILL.md index 87432d5351..83d8d827e0 100644 --- a/.agents/skills/test-health/SKILL.md +++ b/.agents/skills/test-health/SKILL.md @@ -170,7 +170,11 @@ rewriting a test; rewriting beats removing it. - **Test code only.** A product defect is filed as a `type: fix` issue and the finding is `filed`. The batch gate refuses any other path. - **Never hide a test.** No `skip`, `todo`, `only`, `retry` or conditional - skip, and no raised or added timeout or deadline. The gate refuses each. + skip, and no added, lowered or removed timeout or deadline. The gate refuses + each, and a budget raised to a minute or more. A watchdog that only detects + a hang may be raised when it trips on a slow run; a product timing is never + loosened + ([the difference](../../../docs/process/testing.md#watchdogs-and-product-timings)). - **Never weaken an assertion to get green**, and never delete a test because it fails. - **Take assertions away only with an obligation map**: every assertion of the @@ -188,7 +192,8 @@ rewriting a test; rewriting beats removing it. `git status --short` before each commit and commit only test files. - **Stay inside your cluster.** Member files only. A helper shared with other tests is changed only when every user of it is a member. -- **Never rerun a failed CI job**, and never raise a deadline to absorb load. +- **Never rerun a failed CI job**, and never loosen a product timing to + absorb load. - **Fixtures use the Odysseus world** and the pinned date `2026-07-12`; no real names anywhere. diff --git a/AGENTS.md b/AGENTS.md index a963495746..226f84bdaf 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -162,6 +162,12 @@ write one, and which kind of test proves which claim: mutation: break the guard, watch the named test fail on the expected assertion, restore, and record both in the PR. A failing-first receipt must fail for the reason claimed — a module-load error is not one. +- A test watchdog (a timeout that stops a hang and cleans up) is a catch-all + for the worst case: size it well above normal duration, write an in-test one + as `watchdogMs(n)`, and raise it when it trips on a slow run. A product + timing (a time the product promises) is proof: assert it on measured or + controlled time and never loosen it to get green + ([how to tell them apart](docs/process/testing.md#watchdogs-and-product-timings)). - A review finding is one instance of a bug class: grep the diff and its file for every other instance before calling it closed. - Before opening or marking a PR ready, run `bun run check:pr --base diff --git a/docs/decisions/ci-utility.md b/docs/decisions/ci-utility.md index d6fc315bdf..bea527dabd 100644 --- a/docs/decisions/ci-utility.md +++ b/docs/decisions/ci-utility.md @@ -1326,6 +1326,12 @@ and [for the window and bundling](https://github.com/schlessera/brain-kit/issues 11. **Phase B gate of #2934.** Seven consecutive days within one proof-policy epoch, first-main green at or above 80%, and every red incident attributed. +Answers 3 and 5 are amended by +[the 2026-11-17 watchdog ruling](#test-watchdogs-are-a-worst-case-catch-all): +raising a test timeout or deadline is neither a proof-system change nor a +test optimization that needs off-main qualification. Lowering, removing or +adding one still is. + Answers 6, 8 and 10 restate the [2026-10-25 red-main and coordination decisions](https://github.com/schlessera/brain-kit/issues/2934#issuecomment-6402400614). That decision also covers strict flake handling, cooperative merge blocking with @@ -1341,10 +1347,12 @@ Each implementation task is tracked separately: The globs live only in `scripts/proof-system-paths.json`; `bun scripts/proof-system.ts classify --base --head [--json]` and its exported `classify` report the decision with its reasons. The - timeout check flags a changed, added or removed timeout or deadline value + timeout check flags a lowered, added or removed timeout or deadline value where a hunk rewrites existing test lines, and a `setDefaultTimeout` added to - or removed from an existing test file. A new test or test file that sets its - own timeout changes no existing budget and is not flagged; + or removed from an existing test file. A value raised in place is not + flagged ([#4191](#the-proof-system-check-follows-the-direction)). A new test + or test file that sets its own timeout changes no existing budget and is not + flagged; - lane and stability window: [#3269](https://github.com/schlessera/brain-kit/issues/3269); - automatic epochs: [#3270](https://github.com/schlessera/brain-kit/issues/3270). `scripts/ci-epochs.ts` classifies each first-parent squash of main against @@ -1947,10 +1955,10 @@ test more than once before it merged. modifies against its merge base (`determinismTests`, `scripts/ci-plan.ts:318-323`). It runs them in one invocation of the offline wrapper with Bun's `--rerun-each= --bail=1` (`repetitionArgv`, - `scripts/test-determinism.ts:53-56`), so the offline preload applies and + `scripts/test-determinism.ts:86-90`), so the offline preload applies and preparation builds once. One busy loop per CPU runs for the duration. Each is killed by PID on every exit path, and exits by itself if its parent dies - (`startBurners`, `scripts/test-determinism.ts:105-120`). The first failing + (`startBurners`, `scripts/test-determinism.ts:139-154`). The first failing repetition fails the command, which names the file, the repetition and the case. A passing run must also show every repetition in Bun's test report. - **Bounded.** Five repetitions by default, within a budget of 300 seconds of @@ -1991,9 +1999,12 @@ test more than once before it merged. A deliberate local run takes a [host admission](../process/testing.md#host-admission-for-heavy-local-commands) slot. -**What does not change.** No test deadline changes. No failure is retried -into a pass: a failing repetition is a failed job, and the remedy is fixing -the test or what it exposes. Unchanged tests are not repeated. +**What does not change.** No failure is retried into a pass: a failing +repetition is a failed job, and the remedy is fixing the test or what it +exposes. Unchanged tests are not repeated. As ruled, no test deadline changed +either; since [#4191](#test-watchdogs-are-a-worst-case-catch-all) the job +multiplies watchdogs by a fixed factor, and a watchdog that trips on a slow +run is raised rather than treated as a failed proof. **First hosted run.** The job's first run, on the PR that added it, repeated seven changed files five times and then failed in the gate's own test: under @@ -2021,7 +2032,7 @@ about 1,327 seconds per pass, 2,654 at the floor of two. Such a selection could only fail by timeout, and the pull request had no way through the gate except splitting the change. -- **One owner.** The table (`DETERMINISM_PARTITIONS`, `scripts/proof-shards.ts:44`) holds +- **One owner.** The table (`DETERMINISM_PARTITIONS`, `scripts/proof-shards.ts:52`) holds one job's capacity (300 weighted seconds at the selection's repetition count), the maximum of ten partitions, the 40-minute step limit and the measured load ratio. The repetition budget is that capacity @@ -2113,6 +2124,174 @@ file that leaks state into its next run fails too. Vitest browser, layout, endurance and story specs run in the pinned container and are not covered ([#4116](https://github.com/schlessera/brain-kit/issues/4116)). +## Test watchdogs are a worst-case catch-all + +The maintainer ruled on 2026-11-17 +([#4191](https://github.com/schlessera/brain-kit/issues/4191)) that a watchdog +is a catch-all for the worst case, and not friction or flakiness in the +average case. Two things follow. The `determinism` job, which applies CPU load +on purpose, multiplies test deadlines by a fixed factor. And a deadline that +only detects a hang may be raised freely: only a deadline that asserts a +product timing counts as proof. + +**What this supersedes.** The practice of treating every test deadline as +proof that must not move. Three statements carried it and are amended here: +"No test deadline changes" in +[the repeated-run ruling](#changed-tests-repeat-under-load-before-merge), +answers 3 and 5 of the [proof-system lane](#proof-system-lane) where they +count any changed timeout as a proof-system change, and rule C4 of +[the authoring guide](../process/test-authoring.md#cost), "never raise a time +budget to make a test pass". What those protected is kept by the second kind +of number below. + +**Why.** `tests/integration-command.test.ts` stops its child processes 27 +seconds into each test: Bun's 30-second per-test cap minus three seconds for +the join. It exists to catch a hung child. In run 44104941268 one of its +tests took 26.9 seconds in one repetition and 27.2 in the next under the +gate's load, and failed. The same test takes 8.3 seconds in the `unit` job. +Nothing was wrong except that the watchdog sat a few seconds above the work. +Such numbers stayed tight for three reasons. One 30-second cap covered every +Bun test, from a one-millisecond unit test to one that starts twelve +processes. The gate slows a test several times over, so a test that normally +used more than about a fifth of its deadline could not pass it. And moving +the number was a proof-system change with its own lane and off-main +qualification, so squeezing the work under it was cheaper than moving it. + +### Two kinds of number + +| | A watchdog | A product timing | +| --- | --- | --- | +| What it is | A timeout that exists to stop a hang and clean up | A time the product promises | +| Examples | Bun's per-test cap, a test's own timeout argument, a timer that stops a test's child processes, the upper bound of a polling loop | The composer microphone's 0.6-second hold, a one-second guard, a five-second readiness limit | +| What a pass says about it | Nothing: a passing test never reached it | That the product kept the promise | +| How it is asserted | It is not asserted. It ends the test when something hangs | On measured or controlled time: a clock the test advances, or a measured duration compared with the promised one | +| When it trips on a slow run | It was too tight. Raise it, or let the loaded run scale it | The product was too slow. That is a finding | +| Changing it | Raise it freely. No lane, no off-main qualification | A change to what the product promises, reviewed as one | + +To tell which kind a number is, ask what a user would notice if it doubled. +Nothing, for a watchdog: the test only takes longer to give up on a hang. A +different product, for a product timing. A test timeout is never the right +place for a product timing, because a slow host fails it and a fast host +proves nothing beyond "under the cap". A number that serves as both is split: +the promise is asserted on measured or controlled time, and the watchdog +above it is sized for the worst case. + +**Sizing a watchdog.** Well above the test's normal duration, so that only a +real hang trips it: about ten times is a reasonable start, and the per-test +cap is enough for almost every test. A tripped watchdog on a slow run is +raised or scaled. It is not a failed proof, and the work is not squeezed to +fit under it. + +### The gate scales deadlines by a fixed factor + +Under the `determinism` job every test deadline the job can reach is +multiplied by one factor, **8**, owned beside the job's other numbers +(`DETERMINISM_PARTITIONS`, `scripts/proof-shards.ts:52`). No other job scales +anything. + +- **Bun's per-test cap.** The command reads the cap from the root `test` + script, which owns it (`testCapMs`, `scripts/test-determinism.ts:74-79`), + and passes the scaled value as a later `--timeout` + (`repetitionArgv`, `scripts/test-determinism.ts:86-90`): 240 seconds for + the script's 30. Hooks follow the same cap. +- **Explicit test and hook timeouts.** A second preload, loaded only by this + command, replaces `bun:test` for the invocation with a copy whose `test`, + `it`, hooks and `setDefaultTimeout` multiply the timeout they are given + (`scaledTestModule`, `scripts/test-deadlines.ts:103-112`; + `scripts/test-deadline-preload.ts`). No test is edited. +- **In-test watchdogs.** A test's own timer reads the helper + (`watchdogMs`, `scripts/test-deadlines.ts:41-44`), which multiplies by the + factor the command sets in `BRAIN_TEST_DEADLINE_FACTOR` and by one + everywhere else. The 27-second watchdog is the first to read it + (`watchdogMs(27_000)`, `tests/integration-command.test.ts:29`). + +Verified against Bun 1.4.2, the version CI pins. The last `--timeout` on the +command line wins, so the scaled cap follows the script's own. Neither +`--timeout` nor `setDefaultTimeout` changes a timeout a test names itself, +and Bun has no flag that does, so scaling those needs the replacement. Bun's +own `mock.module` makes it: the copy reaches every later import and the +runner's globals, in every file and every repetition, although the offline +preload has already imported `bun:test`, and a test's `mock.restore()` does +not undo it. Assigning to the object `require("bun:test")` returns does not +work once anything has imported the module. The preload checks that the +replacement took and stops the run if it did not, so a later Bun cannot leave +the timeouts silently unscaled. + +**The factor and the runs behind it.** The largest slowdown measured under +the job's own load is 6.84 elapsed seconds per weighted second, in run +44039499653, the highest of the five calibration runs in +[the partition ruling](#an-oversized-selection-is-split-by-reviewed-weight) +(43989701310, 43991629934, 44017250694, 44020374567 and 44039499653, between +3.59 and 6.84). The factor is the smallest whole number at least 15% above +it. Per test the slowdown is smaller. The `determinism` jobs of 33 hosted +runs on 2026-11-17 ran 140 test cases that take at least one second in the +`unit` job of main run 44107659969, 1,137 times in all: the median case took +1.94 times its `unit` duration, the 99th percentile 3.40 times and the +slowest 3.83 times. The whole-job ratio is higher because it also carries stale +weights and per-file start-up, so the factor leaves about twice the largest +per-test slowdown. The test that prompted the ruling ran 3.3 times slower in +the failing run, and 2.3 to 2.8 times slower in runs 44064090479 and +44104948265, where it passed at 19.3 to 23.4 seconds. + +**The step limit still bounds the job.** Scaling changes how long a hang +takes to be reported, not how long a passing test runs. `--bail=1` ends the +run at the first failure, so at most one test waits out its cap. A full +capacity at the measured ratio takes 2,052 seconds, one hung test under the +scaled cap adds 240, and 2,292 fits the 40-minute step. A test asserts that +sum against the owner's numbers, and that the factor covers the measured +ratio with its margin. + +**What stays unscaled.** + +- A wait a test bounds any other way: a polling loop's `Date.now() + n`, a + helper's own `timeout` option, an `AbortSignal.timeout`. It scales once it + reads `watchdogMs`. The test files that carry an explicit timeout or + deadline, 372 when this was ruled, change that way: when one trips, or when + its file is next edited. Nothing is raised in bulk. +- Timeouts inside the product, and inside a child process a test starts. A + child `bun test` that a test runs does not load the scaling preload; it + inherits the environment, so `watchdogMs` scales there too. +- Product timings, by the rule above. +- A test whose explicit timeout is already minutes long. Multiplied by eight + it can exceed what is left of the step, and then the step limit, not Bun, + ends a hang in it. +- The job's 12-minute setup limit and 40-minute step limit. +- Every other job: `unit`, the runtime and browser domains and local runs + keep the written durations. `bun scripts/test-determinism.ts` scales + wherever it runs, and `--deadline-factor 1` turns the scaling off for a + comparison. +- Vitest specs. The browser repetition job + ([#4163](https://github.com/schlessera/brain-kit/issues/4163)) is not on + main; scaling Vitest's test and hook timeouts inside it is + [#4192](https://github.com/schlessera/brain-kit/issues/4192). + +### The proof-system check follows the direction + +The timeout check reads which way a value moved +(`raisedOrEqual`, `scripts/proof-system.ts:99-104`). A timeout or deadline +rewritten in place to the same or a larger number, or to the same expression +with no number made smaller, is a raised watchdog and is not a proof-system +change. A duration inside `watchdogMs(...)` is read as that duration, so +adopting the helper is not a change either. + +Still a proof-system change: + +- a lowered timeout or deadline, and one that stops reading `watchdogMs`; +- a removed one; +- an added one on an existing test, and a `setDefaultTimeout` added to an + existing file: the check does not know which default applied before, so it + cannot tell a raise from a lowering; +- a change whose direction it cannot read, such as a conditional or a call + with arguments; +- a value that leaves one hunk while a larger one appears in another. Only a + rewrite in place is read as a raise + (`timeoutChanges`, `scripts/proof-system.ts:171-202`). + +The check is syntactic and reads names, not intent: it cannot tell a watchdog +from a product timing kept in a constant called `...Deadline`. Loosening a +product timing was never something it could see when the number sat in an +assertion, and it stays a review question either way. + ## Historical measurement and upstream guidance The following guidance records the paid-provider investigation which motivated diff --git a/docs/process/test-authoring.md b/docs/process/test-authoring.md index fdc37b6a4c..327b59d6c2 100644 --- a/docs/process/test-authoring.md +++ b/docs/process/test-authoring.md @@ -159,7 +159,10 @@ first failing repetition a while, reads the wall clock or keeps state from its previous run fails there, not on someone else's merge. Reproduce a failure with `bun scripts/test-determinism.ts --base origin/main`, and fix the test under -the rule it broke. A longer deadline or a retry is not a fix. +the rule it broke. A retry is not a fix. A longer watchdog is the fix only +when the watchdog is what tripped (C4): the gate already multiplies watchdogs +by eight, so a test that still times out there is usually waiting for a while +or racing something. ## Cost @@ -175,10 +178,22 @@ the rule it broke. A longer deadline or a retry is not a fix. - **C3. A real-time wait of a second or more needs its justification.** State the failure mode controlled time cannot reproduce and the basis for the window ([test-waits.md](test-waits.md)). Prevents `real-time-wait`. -- **C4. Never raise a time budget to make a test pass.** A changed timeout or - deadline is a proof-system change with its own lane - ([the CI decision](../decisions/ci-utility.md#proof-system-lane)). A test that - needs a minute is telling you about its tier or its setup. Prevents +- **C4. A watchdog is sized for the worst case; a product timing is asserted + on a clock.** They are two kinds of number + ([the ruling](../decisions/ci-utility.md#test-watchdogs-are-a-worst-case-catch-all)). + A *watchdog* stops a hang and cleans up: Bun's per-test cap, a test's own + timeout, a timer that stops its child processes. Set it well above the + test's normal duration, about ten times, so that only a real hang trips it, + and write an in-test one as `watchdogMs(n)` (`scripts/test-deadlines.ts`) so + a run under deliberate load scales it. When one trips on a slow run, raise + it or let the run scale it: that is not a failed proof, and the work is not + squeezed to fit. Raising one needs no proof-system lane. A *product timing* + is a time the product promises: a 0.6-second hold, a one-second guard, a + five-second readiness limit. Never loosen it to make a test pass, and never + assert it through a test timeout: advance a controlled clock, or compare a + measured duration with the promise (D1, D2). To tell them apart, ask what a + user would notice if the number doubled. A test that needs a minute of real + work is still telling you about its tier or its setup (C1, C2). Prevents `long-timeout`. ## Proving a test can fail diff --git a/docs/process/test-waits.md b/docs/process/test-waits.md index 2b71e5babf..2a5bebac5d 100644 --- a/docs/process/test-waits.md +++ b/docs/process/test-waits.md @@ -16,7 +16,7 @@ policy and changes how tests advance it. | Animation/media progress | The browser has actually produced the frame/chunk/commit that the assertion observes | Animation lifecycle and decoded/persisted media events. JavaScript fake time does not advance audio capture or browser compositor/process time. | | Negative observation | An asynchronous forbidden action had a real opportunity to occur and did not | Advance every relevant timer or await a causal completion barrier. Immediate absence, intermediate DOM state, or a held promise alone is insufficient. | | Condition polling | A named event or state appeared | Exit on the condition; record actual iterations and elapsed time. The polling interval is latency granularity, not the whole test cost. | -| Failure maximum | An operation did not hang forever | Preserve the failure deadline. A losing timeout branch contributes no awaited deadline duration; clear it on completion. | +| Failure maximum | An operation did not hang forever | Keep a failure deadline, sized for the worst case: it is a [watchdog](testing.md#watchdogs-and-product-timings), raised when it trips on a slow run. A losing timeout branch contributes no awaited deadline duration; clear it on completion. | | Fixture hold | A native worker remains alive until released/cancelled | Count actual hold time and termination, not the advertised sleep. Retain process-boundary cancellation and cleanup. | Keep real IO and event processing between clock advances. A fake clock must not diff --git a/docs/process/testing.md b/docs/process/testing.md index 57c0059ae9..5ce005526f 100644 --- a/docs/process/testing.md +++ b/docs/process/testing.md @@ -332,9 +332,18 @@ bun scripts/test-determinism.ts --base origin/main --json # the report on stdo numbers ([basis](../decisions/ci-utility.md#an-oversized-selection-is-split-by-reviewed-weight)). A local `--base` run repeats the whole selection in one invocation. +- **Deadlines are scaled.** The burners slow every test, so the run multiplies + watchdogs by eight: Bun's per-test cap (240 seconds for the script's 30), + every explicit test and hook timeout, and in-test watchdogs written as + `watchdogMs(n)`. A wait bounded any other way is not scaled. The report and + the job summary name the factor; `--deadline-factor 1` turns it off for a + comparison ([watchdogs and product timings](#watchdogs-and-product-timings)). - **A failure** names the file, the repetition and the case. Repetitions of a file share one process, so state left on `globalThis`, in the environment or - on disk reaches the next run. Fix the test; do not raise its deadline. + on disk reaches the next run. Fix the test. If what tripped was a watchdog + the run could not scale, a polling loop's own deadline for example, raise it + or make it read `watchdogMs`: that is a too-tight watchdog, not a failed + proof. - **Where it runs.** The hosted `determinism` job, at every pull-request cadence including draft, and in draft heavy feedback. `draft gates` and `proof` require it when the change selects it. `check:pr` never runs it: it @@ -343,6 +352,59 @@ bun scripts/test-determinism.ts --base origin/main --json # the report on stdo [host admission](#host-admission-for-heavy-local-commands); `--burners ` lowers the load for a diagnosis. +## Watchdogs and product timings + +A test carries two kinds of time limit, and they are handled in opposite ways +([the 2026-11-17 ruling](../decisions/ci-utility.md#test-watchdogs-are-a-worst-case-catch-all)). + +- **A watchdog** stops a hang and cleans up: Bun's per-test cap, the timeout a + test names as its third argument, a timer that stops a test's child + processes, the upper bound of a polling loop. A passing test never reaches + it, so it proves nothing and may be raised freely. +- **A product timing** is a time the product promises: the composer + microphone's 0.6-second hold, a one-second guard, a five-second readiness + limit. It is proof, and it is asserted on measured or controlled time + ([the clock rules](test-waits.md)), never through a test timeout. + +To decide which one a number is, ask what a user would notice if it doubled. +For a watchdog, nothing. For a product timing, a different product. + +**Sizing a watchdog.** Put it well above the test's normal duration, so that +only a real hang trips it. About ten times is a reasonable start, and the +30-second cap `bun run test` supplies is enough for almost every test. A +watchdog a few seconds above the work is a flake waiting for a loaded host. +An in-test watchdog reads the helper, so a run under deliberate load scales +it with everything else: + +```ts +import { watchdogMs } from "../scripts/test-deadlines"; +const watchdog = setTimeout(stopChildren, watchdogMs(27_000)); +``` + +`watchdogMs` multiplies by `BRAIN_TEST_DEADLINE_FACTOR`, which +`scripts/test-determinism.ts` sets to the gate's factor of eight +(`DETERMINISM_PARTITIONS.deadlineFactor`, `scripts/proof-shards.ts`) for the +tests it repeats. Everywhere else the variable is unset and the duration is +the one written. A malformed value fails the test instead of being read as +one. Never pass a product timing through the helper. + +**When a watchdog trips.** First find out whether the test hung or was only +slow: the failure names the case and its duration. + +- *It hung.* That is what the watchdog is for. Fix the hang. +- *It was slow, on a loaded run.* Raise the watchdog, or make it read + `watchdogMs`. This is not a failed proof and needs no proof-system lane: + `bun scripts/proof-system.ts classify` does not flag a timeout or deadline + that is only raised. Do not shrink the work to fit the number, and do not + rerun. +- *It is slow everywhere.* The watchdog is fine and the test is too expensive + for its tier ([cost rules](test-authoring.md#cost)). + +Lowering or removing a timeout, adding one to an existing test, and a change +whose direction the check cannot read are still proof-system changes. So is +loosening a product timing, whatever the classifier says: it changes what +the product promises, and review decides it. + ## Tests that cannot fail A green test is evidence only if it could have been red. Each of these shapes @@ -519,8 +581,9 @@ Local long suites are for debugging a specific failure only (#2939); they run through a host-wide admission ledger, `scripts/host-admission.mjs` (#2943). Separate worktrees on one machine share its slots, so a heavy command that would exceed the limit waits, printing the holders and its queue position, -instead of starting and timing out. Test deadlines are never raised to absorb -contention. +instead of starting and timing out. Admission, not a longer deadline, is how +local contention is absorbed; a watchdog that still trips on a slow run is +[raised](#watchdogs-and-product-timings). Heavy commands are the integrated default `bun run test` suite, runtime-host and native test selections, any selected file whose measured cost in