From dd94a2c2c5d7e059c7c51a0b1ce0347cd4ead6ba Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 20:00:31 +0000 Subject: [PATCH] chore(ci): scale browser repetition watchdog deadlines --- docs/decisions/ci-utility.md | 73 ++++++++++++++++--- docs/process/testing.md | 31 +++++++- .../tests/visual/deadline-scaling.visual.tsx | 41 +++++++++++ scripts/browser-determinism-inside.d.mts | 5 +- scripts/browser-determinism-inside.mjs | 22 +++++- scripts/browser-determinism.ts | 22 ++++-- scripts/proof-shards.ts | 6 +- scripts/test-deadlines.ts | 11 ++- tests/browser-determinism-container.test.ts | 21 +++++- tests/browser-determinism.test.ts | 40 ++++++++-- .../deadline-explicit-hook.repeat.js | 5 ++ .../browser-deadlines/deadline-hang.repeat.js | 6 ++ .../browser-deadlines/deadline-hook.repeat.js | 9 +++ .../browser-deadlines/deadline-work.repeat.js | 11 +++ .../browser-deadlines/vitest.config.mjs | 17 +++++ 15 files changed, 281 insertions(+), 39 deletions(-) create mode 100644 packages/ui-kit/tests/visual/deadline-scaling.visual.tsx create mode 100644 tests/fixtures/browser-deadlines/deadline-explicit-hook.repeat.js create mode 100644 tests/fixtures/browser-deadlines/deadline-hang.repeat.js create mode 100644 tests/fixtures/browser-deadlines/deadline-hook.repeat.js create mode 100644 tests/fixtures/browser-deadlines/deadline-work.repeat.js create mode 100644 tests/fixtures/browser-deadlines/vitest.config.mjs diff --git a/docs/decisions/ci-utility.md b/docs/decisions/ci-utility.md index 41124f4a7a..95eaef0854 100644 --- a/docs/decisions/ci-utility.md +++ b/docs/decisions/ci-utility.md @@ -2184,7 +2184,7 @@ and 9 of 16 with burners inside it. A further pass cost the spec's own time, suite's. Inside, `scripts/browser-determinism-inside.mjs` starts Vitest once through `vitest/node` and calls `runTestSpecifications` with exactly the selected pairs for every pass (`runPasses`, - `scripts/browser-determinism-inside.mjs:109-143`). Vitest 4.1.11 then opens a new + `scripts/browser-determinism-inside.mjs:110-146`). Vitest 4.1.11 then opens a new tester iframe for each file: a new document, the module evaluated again, `beforeAll` rerun. What carries over between passes is the browser process, its context and orchestrator page, cookies, `localStorage`, `sessionStorage` @@ -2226,7 +2226,7 @@ and 9 of 16 with burners inside it. A further pass cost the spec's own time, refreshed table (7.9 seconds) and below its mean (12.1). Every spec a change adds is unweighted until the next refresh. - **Partitions.** One owner (`BROWSER_DETERMINISM_PARTITIONS`, - `scripts/proof-shards.ts:58`) holds one job's capacity of 300 weighted seconds, + `scripts/proof-shards.ts:68`) holds one job's capacity of 300 weighted seconds, the maximum of 15 partitions, the 20-minute step limit, the load ratio and the unweighted default. Counting and partitioning are the Bun gate's functions applied to pairs @@ -2263,7 +2263,8 @@ and 9 of 16 with burners inside it. A further pass cost the spec's own time, slot through the launcher, and `--cpu-list` confines the container's work and its burners to a few CPUs of a shared host. -**What does not change.** No spec, deadline or baseline changes. No failure is +**What does not change.** No spec or baseline changes. Default watchdogs scale under deliberate load +([the watchdog ruling](#test-watchdogs-are-a-worst-case-catch-all)). No failure is retried into a pass: the first failing repetition fails the job, which names the spec, the project, the repetition and the case. Unchanged specs are not repeated. @@ -2366,8 +2367,8 @@ fit under it. 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. +(`DETERMINISM_PARTITIONS`, `scripts/proof-shards.ts:52`). The browser repetition job applies its own factor, described below. Other +jobs retain their written durations. - **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`), @@ -2377,10 +2378,10 @@ anything. - **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`; + (`scaledTestModule`, `scripts/test-deadlines.ts:110-119`; `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 + (`watchdogMs`, `scripts/test-deadlines.ts:48-51`), 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`). @@ -2436,14 +2437,62 @@ ratio with its margin. 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 +- Other ordinary jobs: `unit`, runtime and ordinary 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). +- Explicit Vitest test/suite timeout options and hook timeout arguments. In + Vitest 4.1.11 these take precedence over `testTimeout`/`hookTimeout`; raising + the project defaults does not multiply them. `expect.poll` defaults to its + own 1,000 ms or `expect.poll.timeout` configuration, and `vi.waitFor` to its + own 1,000 ms. Their explicit timeout options are also independent. A watchdog + in any of these can opt in with `watchdogMs(n)`. Poll intervals stay unchanged. +- Ordinary Vitest runs: only the browser repetition command scales defaults, + wherever it runs. `--deadline-factor 1` disables scaling for diagnosis. + +### The browser repetition job scales its own defaults + +The same 2026-11-17 ruling covers `browser_determinism` +([#4192](https://github.com/schlessera/brain-kit/issues/4192)). Its factor is +**3**, owned by `BROWSER_DETERMINISM_PARTITIONS.deadlineFactor` in +`scripts/proof-shards.ts`: the smallest integer at least 15% above its own +measured load ratio, 1.8. It does not inherit the Bun job's factor of 8. +The basis is the [#4116 hosted measurement](https://github.com/schlessera/brain-kit/issues/4116#issuecomment-6943920511), +runs [44049769708](https://github.com/schlessera/brain-kit/actions/runs/44049769708) +and [44051630821](https://github.com/schlessera/brain-kit/actions/runs/44051630821). +Inside-container burners slowed the four measured specs 1.27 to 1.79 times, +rounded up to 1.8 by the partition owner. The later local mixed selection +measured about 1.3, as recorded above; it is not substituted for hosted evidence. + +After `createVitest` resolves projects and before `standalone` opens browser +servers, the repetition runner multiplies each project's resolved +`testTimeout` and `hookTimeout`. Vitest 4.1.11 browser defaults are 15,000 ms +and 30,000 ms, so the loaded defaults are 45,000 ms and 90,000 ms. A project's +custom values scale from those values; a disabled timeout (zero) stays disabled. +No other Vitest configuration is changed. Each project receives +`BRAIN_TEST_DEADLINE_FACTOR` through `test.env`; Vitest exposes it as +`import.meta.env` in browser specs. `watchdogMs` reads it without requiring +Node globals, so the helper has the same contract in Bun and a real browser. +The runner logs each project's factor and resulting caps, and the host report +and job summary also name the factor. + +Verified against the installed, lockfile-pinned Vitest **4.1.11**: the runner's +collection chooses an explicit timeout before the configured default, and its +hook registration, `expect.poll` and `vi.waitFor` likewise keep their own +explicit limits. The browser fixture exercises the injected factor, both +scaled defaults, explicit test options and product timing on a controlled +clock. Separate fixture projects exercise fixed CPU work and a truly unresolved +promise through the actual repetition command in the pinned container. + +The unchanged 20-minute step still bounds the job. Full capacity at the +measured ratio is 300 × 1.8 = 540 seconds; one hang at the larger default +(a hook) adds 90 and the measured setup/start-up adds 135, for 765 seconds +inside 1,200. A test +asserts this bound and the factor's margin from the owner's numbers. The first +failing pass ends the command. Several hangs in the same file or a very large +explicit timeout can instead reach the outer step limit, which remains the +worst-case catch-all. Product timings and all the independent waits listed +above remain unscaled. ### The proof-system check follows the direction diff --git a/docs/process/testing.md b/docs/process/testing.md index e9e6830b93..82cc55dbf1 100644 --- a/docs/process/testing.md +++ b/docs/process/testing.md @@ -317,6 +317,15 @@ bun scripts/test-determinism.ts --base origin/main --json # the report on stdo `--bail=1`, so the offline preload is active and a non-loopback connection fails as it does in any test. One busy loop per CPU runs until the command exits; each is stopped by PID and exits by itself if the command is killed. +- **Watchdogs under load.** The job multiplies each Vitest project's + `testTimeout` and `hookTimeout` by three (45 s and 90 s for the browser + defaults), and sets `BRAIN_TEST_DEADLINE_FACTOR` for browser-side + `watchdogMs(n)`. `BROWSER_DETERMINISM_PARTITIONS.deadlineFactor` owns the + number. `--deadline-factor 1` disables it for a comparison. Explicit test, + suite and hook timeout options, `expect.poll` and `vi.waitFor` timeouts and + polling intervals keep their own values; a hang-catching bound there can + opt in with `watchdogMs(n)`. Product timing assertions use controlled clocks + and never scale. The 20-minute step limit is unchanged. - **The bound.** Five repetitions, reduced uniformly to no fewer than two when the reviewed weights in `scripts/test-shard-costs.json` exceed 300 seconds. Ready confirmation runs two, because the merge lease is held while it runs @@ -385,6 +394,15 @@ packages' built output. Node-side state of browser commands and the Vite server are kept, as they are between two files of an ordinary run. One busy loop per CPU runs inside the container until the command exits. +- **Watchdogs under load.** The job multiplies each Vitest project's + `testTimeout` and `hookTimeout` by three (45 s and 90 s for the browser + defaults), and sets `BRAIN_TEST_DEADLINE_FACTOR` for browser-side + `watchdogMs(n)`. `BROWSER_DETERMINISM_PARTITIONS.deadlineFactor` owns the + number. `--deadline-factor 1` disables it for a comparison. Explicit test, + suite and hook timeout options, `expect.poll` and `vi.waitFor` timeouts and + polling intervals keep their own values; a hang-catching bound there can + opt in with `watchdogMs(n)`. Product timing assertions use controlled clocks + and never scale. The 20-minute step limit is unchanged. - **The bound.** Five repetitions, reduced uniformly to no fewer than two when the reviewed weights in `scripts/browser-shard-costs.json` exceed 300 seconds. Ready confirmation runs two. A pair with no reviewed weight, which @@ -400,8 +418,9 @@ packages' built output. Failure screenshots are written under `__screenshots__/` beside the spec, as in any browser run, and the hosted job uploads them. Fix the spec: wait for the state it asserts ([test waits](test-waits.md)), and do not leave state - in storage that its next pass will read. A longer deadline or a retry is not - a fix. + in storage that its next pass will read. If only a hang-catching deadline + tripped under load, raise it or use `watchdogMs`; see [the watchdog rule](#watchdogs-and-product-timings). + Never retry a failing repetition into a pass. - **Where it runs.** The hosted `browser_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. Never on main. @@ -439,10 +458,14 @@ import { watchdogMs } from "../scripts/test-deadlines"; const watchdog = setTimeout(stopChildren, watchdogMs(27_000)); ``` -`watchdogMs` multiplies by `BRAIN_TEST_DEADLINE_FACTOR`, which +`watchdogMs` works in Bun and Vitest browser specs. It 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 +tests it repeats. The browser repetition runner sets its own factor of three +(`BROWSER_DETERMINISM_PARTITIONS.deadlineFactor`) in each project's `test.env`, +which Vitest exposes as `import.meta.env` in a spec. In ordinary runs 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. diff --git a/packages/ui-kit/tests/visual/deadline-scaling.visual.tsx b/packages/ui-kit/tests/visual/deadline-scaling.visual.tsx new file mode 100644 index 0000000000..4e3725d7c4 --- /dev/null +++ b/packages/ui-kit/tests/visual/deadline-scaling.visual.tsx @@ -0,0 +1,41 @@ +// Hosted selection witness for #4192: this changed spec is repeated by the PR's +// own browser_determinism job. Ordinary browser proof keeps factor one. Timing +// assertions use controlled clocks; only hang-catching defaults are scaled. +import { expect, test, vi } from "vitest"; +import { deadlineFactor, watchdogMs } from "../../../../scripts/test-deadlines"; + +test("the crew's watchdog follows the loaded run in every pass", ({ task }) => { + expect(task.timeout, "BROWSER_TEST_DEFAULT_SCALES").toBe(15_000 * deadlineFactor()); + expect(watchdogMs(37), "BROWSER_WATCHDOG_READS_FACTOR").toBe(37 * deadlineFactor()); +}); + +test("an explicit per-test timeout keeps its written value", { timeout: 2_000 }, ({ task }) => { + expect(task.timeout, "EXPLICIT_TIMEOUT_IS_UNSCALED").toBe(2_000); +}); + +test("product timings stay on controlled time", () => { + vi.useFakeTimers(); + try { + let ready = false; + setTimeout(() => { ready = true; }, 600); + vi.advanceTimersByTime(599); + expect(ready).toBe(false); + vi.advanceTimersByTime(1); + expect(ready).toBe(true); + } finally { vi.useRealTimers(); } +}); + +for (const wait of ["poll", "waitFor"] as const) { + test(`${wait} keeps its explicit timeout independently of project defaults`, async () => { + let ready = false; + const timer = setTimeout(() => { ready = true; }, 200); + try { + // If the 80 ms wait were multiplied by three, readiness at 200 ms would + // make it pass; rejection proves it kept its own limit. + const result = wait === "poll" + ? expect.poll(() => ready, { timeout: 80, interval: 10 }).toBe(true) + : vi.waitFor(() => { expect(ready).toBe(true); }, { timeout: 80, interval: 10 }); + await expect(result).rejects.toThrow(); + } finally { clearTimeout(timer); } + }); +} diff --git a/scripts/browser-determinism-inside.d.mts b/scripts/browser-determinism-inside.d.mts index 08442f1911..f509f3246d 100644 --- a/scripts/browser-determinism-inside.d.mts +++ b/scripts/browser-determinism-inside.d.mts @@ -1,6 +1,6 @@ export const RESULT_KIND: "brain-browser-determinism-passes"; export interface PassPair { project: string; file: string; } -export interface PassPlan { root: string; result: string; pairs: PassPair[]; repetitions: number; burners: number | null; cpuList: string | null; } +export interface PassPlan { root: string; result: string; pairs: PassPair[]; repetitions: number; deadlineFactor: number; burners: number | null; cpuList: string | null; } export interface PassFailure { project: string | null; file: string | null; repetition: number | null; test: string | null; reason: string; } export interface PassOutcome { passes: { repetition: number; elapsedSeconds: number; ok: boolean }[]; failure: PassFailure | null; alsoFailed: PassPair[]; } /** The part of a Vitest test module the runner reads. */ @@ -21,3 +21,6 @@ export function readPassPlan(value: unknown): PassPlan; export function passCollector(): PassCollector; export function runPasses(options: { vitest: PassRunner; collector: PassCollector; pairs: readonly PassPair[]; repetitions: number; repo?: string; log?: (line: string) => void; now?: () => number }): Promise; + +export function scaleVitestDeadlines(vitest: { projects: { name: string; config: { testTimeout: number; hookTimeout: number; env?: Record } }[] }, + factor: number, log?: (line: string) => void): void; diff --git a/scripts/browser-determinism-inside.mjs b/scripts/browser-determinism-inside.mjs index c0c23e5107..78513da39a 100644 --- a/scripts/browser-determinism-inside.mjs +++ b/scripts/browser-determinism-inside.mjs @@ -71,7 +71,7 @@ const repositoryPath = value => typeof value === "string" && PATH.test(value) && /** The host's plan for this container, validated: nothing here is trusted because a script wrote it. */ export function readPassPlan(value) { if (!value || typeof value !== "object" || value.kind !== RESULT_KIND || value.version !== 1) throw new Error("Not a browser repetition plan"); - const { root, pairs, repetitions, burners, cpuList, result } = value; + const { root, pairs, repetitions, burners, cpuList, result, deadlineFactor } = value; if (!repositoryPath(root) || !repositoryPath(result) || !result.startsWith("tmp/")) throw new Error("The plan's configuration root and result path must be repository paths"); if (!Array.isArray(pairs) || !pairs.length || pairs.some(pair => !pair || !PROJECT.test(pair.project ?? "") || !repositoryPath(pair.file))) throw new Error("The plan must name at least one project/file pair"); const keys = pairs.map(pair => `${pair.project}::${pair.file}`); @@ -79,7 +79,8 @@ export function readPassPlan(value) { if (!Number.isSafeInteger(repetitions) || repetitions < 2 || repetitions > 100) throw new Error("Repetitions must be an integer of at least two: one run proves nothing about the next"); if (burners !== null && (!Number.isSafeInteger(burners) || burners < 0 || burners > 1024)) throw new Error("Burners must be null (one per CPU) or a non-negative integer"); if (cpuList !== null && (typeof cpuList !== "string" || !/^\d+(?:-\d+)?(?:,\d+(?:-\d+)?)*$/.test(cpuList))) throw new Error("The CPU list must look like 0-3 or 0,2,4"); - return { root, result, pairs: pairs.map(pair => ({ project: pair.project, file: pair.file })), repetitions, burners, cpuList }; + if (!Number.isSafeInteger(deadlineFactor) || deadlineFactor < 1 || deadlineFactor > 100) throw new Error("The deadline factor must be a whole number from 1 to 100"); + return { root, result, deadlineFactor, pairs: pairs.map(pair => ({ project: pair.project, file: pair.file })), repetitions, burners, cpuList }; } /** Collects the modules Vitest reports as ended, so a repetition is judged on what ran in it and never on an earlier result. */ @@ -142,6 +143,22 @@ export async function runPasses({ vitest, collector, pairs, repetitions, repo = return { passes, failure: null, alsoFailed: [] }; } +/** + * Apply once after createVitest resolves projects and before standalone opens + * browser servers. Use each resolved project's own defaults, including overrides. + * Vitest 4.1.11 serializes these values afresh for every pass; test.env is also + * exposed as import.meta.env to browser specs. Explicit per-test/hook options, + * expect.poll and vi.waitFor own their deadlines and are intentionally untouched. + */ +export function scaleVitestDeadlines(vitest, factor, log = () => {}) { + for (const project of vitest.projects) { + project.config.testTimeout *= factor; + project.config.hookTimeout *= factor; + project.config.env = { ...project.config.env, BRAIN_TEST_DEADLINE_FACTOR: String(factor) }; + log(`Deadline factor ${factor}: ${project.name}; testTimeout=${project.config.testTimeout} ms, hookTimeout=${project.config.hookTimeout} ms; BRAIN_TEST_DEADLINE_FACTOR=${factor}.`); + } +} + async function main(argv) { if (argv.length !== 1) throw new Error("usage: node scripts/browser-determinism-inside.mjs "); const plan = readPassPlan(JSON.parse(readFileSync(resolve(REPO, argv[0]), "utf8"))); @@ -169,6 +186,7 @@ async function main(argv) { const collector = passCollector(); vitest = await createVitest("test", { watch: false, project: [...new Set(plan.pairs.map(pair => pair.project))], browser: { fileParallelism: false }, reporters: ["default", collector.reporter] }); + scaleVitestDeadlines(vitest, plan.deadlineFactor, log); await vitest.standalone(); outcome = await runPasses({ vitest, collector, pairs: plan.pairs, repetitions: plan.repetitions, log }); } catch (error) { diff --git a/scripts/browser-determinism.ts b/scripts/browser-determinism.ts index 8eed1a66eb..a3f63b2039 100644 --- a/scripts/browser-determinism.ts +++ b/scripts/browser-determinism.ts @@ -35,6 +35,8 @@ import { constants } from "node:os"; import { dirname, join, resolve } from "node:path"; import { listBrowserSpecs } from "./browser-input-closure"; import { expandSpecs, pairKey, parsePairKey, planBrowserRepetitions, type BrowserRepetitionPlan, type PlanOptions, type SpecPair } from "./browser-determinism-plan"; +import { BROWSER_DETERMINISM_PARTITIONS } from "./proof-shards"; +import { parseDeadlineFactor } from "./test-deadlines"; import { RESULT_KIND as PASSES_KIND } from "./browser-determinism-inside.mjs"; import { browserDeterminismSpecs, changedFiles } from "./ci-plan"; @@ -46,16 +48,17 @@ const PLAN_PATH = "tmp/browser-determinism/plan.json", PASSES_PATH = "tmp/browse export interface Failure { file: string | null; project: string | null; repetition: number | null; test: string | null; reason: string; } export interface Pass { repetition: number; elapsedSeconds: number; ok: boolean; } export interface Report extends BrowserRepetitionPlan { - kind: typeof REPORT_KIND; version: 1; base: string | null; configRoot: string; + kind: typeof REPORT_KIND; version: 1; base: string | null; configRoot: string; deadlineFactor: number; outcome: "passed" | "failed" | "none-selected"; failure: Failure | null; alsoFailed: SpecPair[]; passes: Pass[]; load: { burners: number; cpus: number | null; inside: "pinned container" }; elapsedSeconds: number; exitCode: number; } /** What the container side runs: exactly these pairs, this many passes, this load. */ -export function passPlan(plan: BrowserRepetitionPlan, options: { configRoot?: string; burners?: number; cpuList?: string } = {}) { +export function passPlan(plan: BrowserRepetitionPlan, options: { configRoot?: string; burners?: number; cpuList?: string; deadlineFactor?: number } = {}) { return { kind: PASSES_KIND, version: 1, root: options.configRoot ?? CONFIG_ROOT, result: PASSES_PATH, pairs: plan.pairs.map(({ project, file }) => ({ project, file })), repetitions: plan.repetitions, + deadlineFactor: parseDeadlineFactor(options.deadlineFactor ?? BROWSER_DETERMINISM_PARTITIONS.deadlineFactor), burners: options.burners ?? null, cpuList: options.cpuList ?? null }; } @@ -96,7 +99,7 @@ export function judge(plan: BrowserRepetitionPlan, result: PassesResult | undefi } export interface RunOptions extends PlanOptions { - root: string; pairs: readonly SpecPair[]; base?: string | null; configRoot?: string; burners?: number; cpuList?: string; + root: string; pairs: readonly SpecPair[]; base?: string | null; configRoot?: string; burners?: number; cpuList?: string; deadlineFactor?: number; env?: Record; log?: (line: string) => void; /** Starts the launcher and resolves with its exit code; the default inherits this process's output. */ launch?: (argv: string[], cwd: string, env: Record) => Promise; @@ -129,12 +132,14 @@ async function launchInherited(argv: string[], cwd: string, env: Record { const { root } = options, log = options.log ?? (line => console.error(line)); const configRoot = options.configRoot ?? CONFIG_ROOT; + const deadlineFactor = parseDeadlineFactor(options.deadlineFactor ?? BROWSER_DETERMINISM_PARTITIONS.deadlineFactor); const plan = planBrowserRepetitions(options.pairs, options); - const base = { kind: REPORT_KIND as typeof REPORT_KIND, version: 1 as const, base: options.base ?? null, configRoot, ...plan }; + const base = { kind: REPORT_KIND as typeof REPORT_KIND, version: 1 as const, base: options.base ?? null, configRoot, deadlineFactor, ...plan }; if (!plan.pairs.length) { log("No added or modified browser, layout or story spec: nothing to repeat."); return { ...base, outcome: "none-selected", failure: null, alsoFailed: [], passes: [], load: { burners: 0, cpus: null, inside: "pinned container" }, elapsedSeconds: 0, exitCode: 0 }; } + log(`Test and hook default deadlines and watchdogMs scale by ${deadlineFactor} under deliberate load.`); for (const line of describePlan(plan, options.burners)) log(line); mkdirSync(dirname(join(root, PLAN_PATH)), { recursive: true }); rmSync(join(root, PASSES_PATH), { force: true }); @@ -162,7 +167,7 @@ export function summaryMarkdown(report: Report): string { if (report.outcome === "none-selected") return lines.concat("No added or modified browser, layout or story spec.", "").join("\n"); lines.push(`${report.repetitions} of ${report.requested} requested repetitions per project/file pair, ${report.load.burners} burner(s) on ${report.load.cpus ?? "unknown"} CPU(s) inside the pinned container; ` + `${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.`, ""); + `${report.elapsedSeconds.toFixed(1)} s elapsed; deadline factor ${report.deadlineFactor}.`, ""); const { failure } = report; if (failure) lines.push(`**Failed:** \`${failure.file ?? "unknown spec"}\` in project \`${failure.project ?? "unknown"}\`, repetition ${failure.repetition ?? "unknown"}` + `${failure.test ? `, case \`${failure.test.replaceAll("`", "'")}\`` : ""} (${failure.reason.replaceAll("`", "'")}).`, ""); @@ -172,9 +177,9 @@ export function summaryMarkdown(report: Report): string { return lines.concat("").join("\n"); } -const USAGE = "usage: bun scripts/browser-determinism.ts (--base | ::...) [--json] [--report ] [--repetitions ] [--budget-seconds ] [--burners ] [--cpu-list ] [--config-root ]"; +const USAGE = "usage: bun scripts/browser-determinism.ts (--base | ::...) [--json] [--report ] [--repetitions ] [--budget-seconds ] [--burners ] [--cpu-list ] [--config-root ] [--deadline-factor ]"; -export interface Arguments { base?: string; pairs: SpecPair[]; json: boolean; report?: string; repetitions?: number; budgetSeconds?: number; burners?: number; cpuList?: string; configRoot?: string; } +export interface Arguments { base?: string; pairs: SpecPair[]; json: boolean; report?: string; repetitions?: number; budgetSeconds?: number; burners?: number; cpuList?: string; configRoot?: string; deadlineFactor?: number; } export function parseArguments(args: readonly string[]): Arguments { const parsed: Arguments = { pairs: [], json: false }; @@ -190,6 +195,7 @@ export function parseArguments(args: readonly string[]): Arguments { else if (flag === "--report") { parsed.report = value(); if (!parsed.report) throw new Error(`--report needs a path\n${USAGE}`); } else if (flag === "--repetitions") parsed.repetitions = integer(flag, value(), 2); else if (flag === "--budget-seconds") parsed.budgetSeconds = integer(flag, value(), 1); + else if (flag === "--deadline-factor") parsed.deadlineFactor = parseDeadlineFactor(value()); // Zero burners is a diagnosis: the same passes without load. else if (flag === "--burners") parsed.burners = integer(flag, value(), 0); else if (flag === "--cpu-list") { parsed.cpuList = value(); if (!parsed.cpuList || !/^\d+(?:-\d+)?(?:,\d+(?:-\d+)?)*$/.test(parsed.cpuList)) throw new Error(`--cpu-list needs CPUs such as 0-3\n${USAGE}`); } @@ -212,7 +218,7 @@ if (import.meta.main) { } // The launcher takes the host admission slot and the workspace lease, as every browser run does. const report = await runBrowserDeterminism({ root, pairs, base: args.base ?? null, repetitions: args.repetitions, budgetSeconds: args.budgetSeconds, - burners: args.burners, cpuList: args.cpuList, configRoot: args.configRoot, + burners: args.burners, cpuList: args.cpuList, configRoot: args.configRoot, deadlineFactor: args.deadlineFactor, ...(args.json ? { launch: async (argv, cwd, env) => { const child = Bun.spawn(argv, { cwd, env, stdin: "ignore", stdout: 2, stderr: "inherit" }); return await child.exited; } } : {}) }); if (args.report) { mkdirSync(dirname(resolve(root, args.report)), { recursive: true }); diff --git a/scripts/proof-shards.ts b/scripts/proof-shards.ts index 5f3a32c2bf..05331ec473 100644 --- a/scripts/proof-shards.ts +++ b/scripts/proof-shards.ts @@ -62,5 +62,7 @@ export const DETERMINISM_PARTITIONS = { capacitySeconds: 300, max: 10, stepMinut * `browser_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 browser specs repeat under - * load before merge". */ -export const BROWSER_DETERMINISM_PARTITIONS = { capacitySeconds: 300, max: 15, stepMinutes: 20, loadRatio: 1.8, unweightedSeconds: 10 } as const; + * load before merge". `deadlineFactor` is the smallest integer at least 15% + * above the measured ratio: Vitest defaults and in-spec watchdogs scale by + * it only inside this deliberately loaded job (#4192). */ +export const BROWSER_DETERMINISM_PARTITIONS = { capacitySeconds: 300, max: 15, stepMinutes: 20, loadRatio: 1.8, unweightedSeconds: 10, deadlineFactor: 3 } as const; diff --git a/scripts/test-deadlines.ts b/scripts/test-deadlines.ts index 2a58cbd354..4cb8729a62 100644 --- a/scripts/test-deadlines.ts +++ b/scripts/test-deadlines.ts @@ -31,14 +31,21 @@ export function parseDeadlineFactor(value: unknown): number { return factor; } +// Vitest injects test.env into import.meta.env in the browser. Bun exposes +// import.meta.env too; plain Node falls back to process.env. No browser shim +// or Node built-in is required by a spec importing this helper. +const runEnvironment = (): Readonly> => + // Keep import.meta.env contiguous: Vitest recognizes it before TS casts are erased. + import.meta.env ?? (typeof process === "undefined" ? {} : process.env); + /** The factor of this process's run: one unless a loaded run set it. */ -export function deadlineFactor(env: Readonly> = process.env): number { +export function deadlineFactor(env: Readonly> = runEnvironment()): 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 { +export function watchdogMs(milliseconds: number, env: Readonly> = runEnvironment()): number { if (!Number.isFinite(milliseconds) || milliseconds <= 0) throw new Error("A watchdog is a positive, finite number of milliseconds"); return milliseconds * deadlineFactor(env); } diff --git a/tests/browser-determinism-container.test.ts b/tests/browser-determinism-container.test.ts index 9ba4ee1fd4..8a416dacf0 100644 --- a/tests/browser-determinism-container.test.ts +++ b/tests/browser-determinism-container.test.ts @@ -24,12 +24,12 @@ const owned: string[] = []; afterEach(() => { for (const dir of owned.splice(0)) rmSync(dir, { recursive: true, force: true }); }); /** Runs the container side on `pairs` and returns what it wrote, said and exited with. */ -async function repeatInContainer(pairs: { project: string; file: string }[], repetitions: number) { +async function repeatInContainer(pairs: { project: string; file: string }[], repetitions: number, configRoot = FIXTURES) { const scratch = mkdtempSync(join(tmpdir(), "browser-determinism-container-")); owned.push(scratch); // The result is read from the checkout's ignored tmp/, where the container writes it through its one mount. const run = `tmp/browser-determinism-container/${process.pid}-${owned.length}`; mkdirSync(join(ROOT, run), { recursive: true }); owned.push(join(ROOT, run)); - writeFileSync(join(ROOT, run, "plan.json"), JSON.stringify({ kind: RESULT_KIND, version: 1, root: FIXTURES, result: `${run}/passes.json`, pairs, repetitions, burners: 1, cpuList: null })); + writeFileSync(join(ROOT, run, "plan.json"), JSON.stringify({ kind: RESULT_KIND, version: 1, root: configRoot, result: `${run}/passes.json`, pairs, repetitions, deadlineFactor: 3, burners: 1, cpuList: null })); // Rootless Docker maps the container's user to a subordinate one: it needs the plan readable, these two // directories open, and an open umask inside so this process can remove what the container wrote. Rootful // Docker runs as this user and needs none of it. @@ -65,3 +65,20 @@ test("the same spec made deterministic passes every repetition in both of its pr expect([code, result.pairs, result.repetitions]).toEqual([0, pairs, 5]); expect(out).toContain("[browser-determinism] Passed: 2 project/file pair(s), 5 repetition(s) each."); }); + +test("real Vitest defaults scale for hooks and still stop hangs, while explicit hook arguments stay unscaled", async () => { + const hook = await repeatInContainer([{ project: "harbour", file: "tests/fixtures/browser-deadlines/deadline-hook.repeat.js" }], 2, "tests/fixtures/browser-deadlines"); + expect(hook.result.failure, hook.out).toBeNull(); + expect(hook.code).toBe(0); + expect(hook.out).toContain("testTimeout=3000 ms, hookTimeout=2100 ms; BRAIN_TEST_DEADLINE_FACTOR=3"); + + const hang = await repeatInContainer([{ project: "harbour", file: "tests/fixtures/browser-deadlines/deadline-hang.repeat.js" }], 2, "tests/fixtures/browser-deadlines"); + expect(hang.code).toBe(1); + expect(hang.result.failure).toMatchObject({ repetition: 1, test: "the missing crew never arrives" }); + expect(hang.result.failure.reason, "HANG_FAILS_AT_SCALED_CAP").toContain("Test timed out in 3000ms"); + expect(hang.result.passes.map((pass: { ok: boolean }) => pass.ok)).toEqual([false]); + + const explicit = await repeatInContainer([{ project: "harbour", file: "tests/fixtures/browser-deadlines/deadline-explicit-hook.repeat.js" }], 2, "tests/fixtures/browser-deadlines"); + expect(explicit.code).toBe(1); + expect(explicit.result.failure.reason, "EXPLICIT_HOOK_TIMEOUT_IS_UNSCALED").toContain("Hook timed out in 80ms"); +}, 60_000); diff --git a/tests/browser-determinism.test.ts b/tests/browser-determinism.test.ts index c73a673d99..f322586361 100644 --- a/tests/browser-determinism.test.ts +++ b/tests/browser-determinism.test.ts @@ -11,7 +11,7 @@ import { pairKey, parsePairKey, planBrowserPartitions, planBrowserRepetitions, selectBrowserPartition, type SpecPair, } from "../scripts/browser-determinism-plan"; import { CONFIG_ROOT, REPORT_KIND, judge, launcherArgv, parseArguments, passPlan, runBrowserDeterminism, summaryMarkdown } from "../scripts/browser-determinism"; -import { RESULT_KIND, burnerSource, passCollector, readPassPlan, runPasses, startBurners } from "../scripts/browser-determinism-inside.mjs"; +import { RESULT_KIND, burnerSource, passCollector, readPassPlan, runPasses, scaleVitestDeadlines, startBurners } from "../scripts/browser-determinism-inside.mjs"; import { readBrowserCosts } from "../scripts/browser-shards"; import { BROWSER_DETERMINISM_PARTITIONS } from "../scripts/proof-shards"; @@ -78,8 +78,13 @@ describe("repetition count and budget", () => { const costs = Object.fromEntries(oars.map((spec, index) => [pairKey(spec), 10 + index * 10])); test("the numbers have one owner: five repetitions, a floor of two, 300 weighted seconds, and capacity fits the step limit at the measured load ratio", () => { - expect(BROWSER_DETERMINISM_PARTITIONS).toEqual({ capacitySeconds: 300, max: 15, stepMinutes: 20, loadRatio: 1.8, unweightedSeconds: 10 }); + expect(BROWSER_DETERMINISM_PARTITIONS).toEqual({ capacitySeconds: 300, max: 15, stepMinutes: 20, loadRatio: 1.8, unweightedSeconds: 10, deadlineFactor: 3 }); expect([DEFAULT_REPETITIONS, FLOOR_REPETITIONS, BROWSER_BUDGET_SECONDS, UNWEIGHTED_PAIR_SECONDS]).toEqual([5, 2, 300, 10]); + const { deadlineFactor, loadRatio, capacitySeconds, stepMinutes } = BROWSER_DETERMINISM_PARTITIONS; + expect(Number(deadlineFactor), "BROWSER_DEADLINE_COVERS_LOAD_WITH_MARGIN").toBe(Math.ceil(loadRatio * 1.15)); + // Vitest 4.1.11: 15 s browser tests and 30 s browser hooks. One default hang after a full capacity, + // plus the measured setup/start-up, still fits the unchanged step limit. + expect(capacitySeconds * loadRatio + 30 * deadlineFactor + 135, "BROWSER_HANG_FITS_STEP_LIMIT").toBeLessThan(stepMinutes * 60); // Passes at the measured ratio, plus the measured 2 min 15 s of build, image pull and start-up, inside the proof step. expect(BROWSER_DETERMINISM_PARTITIONS.capacitySeconds * BROWSER_DETERMINISM_PARTITIONS.loadRatio + 135, "CAPACITY_FITS_THE_STEP_LIMIT").toBeLessThanOrEqual(BROWSER_DETERMINISM_PARTITIONS.stepMinutes * 60); }); @@ -285,13 +290,14 @@ describe("further passes in one Vitest process", () => { }); test("the container's plan is validated: a kind, repository paths, at least two repetitions and a bounded load", () => { - const plan = { kind: RESULT_KIND, version: 1, root: "packages/ui-kit", result: "tmp/browser-determinism/passes.json", pairs: [harbour], repetitions: 2, burners: null, cpuList: null }; - expect(readPassPlan(plan)).toEqual({ root: "packages/ui-kit", result: "tmp/browser-determinism/passes.json", pairs: [harbour], repetitions: 2, burners: null, cpuList: null }); + const plan = { kind: RESULT_KIND, version: 1, root: "packages/ui-kit", result: "tmp/browser-determinism/passes.json", pairs: [harbour], repetitions: 2, deadlineFactor: 3, burners: null, cpuList: null }; + expect(readPassPlan(plan)).toEqual({ root: "packages/ui-kit", result: "tmp/browser-determinism/passes.json", pairs: [harbour], repetitions: 2, deadlineFactor: 3, burners: null, cpuList: null }); expect(readPassPlan({ ...plan, burners: 0, cpuList: "12-15" })).toMatchObject({ burners: 0, cpuList: "12-15" }); for (const [label, change, refusal] of [ ["ONE_PASS_PROVES_NOTHING", { repetitions: 1 }, "at least two"], ["NO_PAIR", { pairs: [] }, "at least one project/file pair"], ["DUPLICATE_PAIR", { pairs: [harbour, harbour] }, "selected twice"], ["ESCAPING_SPEC", { pairs: [pair("harbour", "../etc/passwd")] }, "at least one project/file pair"], ["ESCAPING_ROOT", { root: "../elsewhere" }, "repository paths"], ["RESULT_OUTSIDE_TMP", { result: "packages/passes.json" }, "repository paths"], + ["BAD_FACTOR", { deadlineFactor: 0 }, "whole number from 1 to 100"], ["MISSING_FACTOR", { deadlineFactor: undefined }, "whole number from 1 to 100"], ["NEGATIVE_LOAD", { burners: -1 }, "non-negative integer"], ["NOT_A_CPU_LIST", { cpuList: "12-15; rm" }, "CPU list"], ["ANOTHER_KIND", { kind: "brain-test-determinism" }, "Not a browser repetition plan"], ] as const) expect(() => readPassPlan({ ...plan, ...change }), label).toThrow(refusal); }); @@ -359,11 +365,11 @@ describe("the command", () => { const seen: { argv?: string[]; plan?: ReturnType } = {}, lines: string[] = []; const report = await runBrowserDeterminism({ root: checkout(), pairs: selection, costs, configRoot: "tests/fixtures/browser-determinism", cpuList: "12-15", launch: container(green, 0, seen), log: line => lines.push(line) }); expect(seen.argv, "THE_BROWSER_SUITES_LAUNCHER").toEqual(["node", "scripts/visual.mjs", "--project=harbour", "--project=strait", "--repeat-plan=tmp/browser-determinism/plan.json"]); - expect(seen.plan).toEqual({ kind: RESULT_KIND, version: 1, root: "tests/fixtures/browser-determinism", result: "tmp/browser-determinism/passes.json", pairs: selection, repetitions: 5, burners: null, cpuList: "12-15" }); + expect(seen.plan).toEqual({ kind: RESULT_KIND, version: 1, root: "tests/fixtures/browser-determinism", result: "tmp/browser-determinism/passes.json", pairs: selection, repetitions: 5, deadlineFactor: 3, burners: null, cpuList: "12-15" }); expect(report).toMatchObject({ kind: REPORT_KIND, version: 1, outcome: "passed", failure: null, exitCode: 0, repetitions: 5, requested: 5, weightSeconds: 14, load: { burners: 4, cpus: 4, inside: "pinned container" } }); expect(report.pairs.map(entry => [entry.project, entry.weighted, entry.weightSeconds]), "UNWEIGHTED_PAIR_NAMED_IN_THE_REPORT").toEqual([["harbour", true, 4], ["strait", false, 10]]); expect(lines.find(line => line.includes("strait")), "AND_IN_THE_LOG").toContain("no reviewed weight: costed at the 10s default"); - expect(passPlan(report), "THE_GATES_OWN_CONFIGURATION_BY_DEFAULT").toMatchObject({ root: CONFIG_ROOT, burners: null, cpuList: null }); + expect(passPlan(report), "THE_GATES_OWN_CONFIGURATION_BY_DEFAULT").toMatchObject({ root: CONFIG_ROOT, deadlineFactor: 3, burners: null, cpuList: null }); expect(launcherArgv([pair("rail-fine", `${browser}/a.pointer.tsx`), pair("rail-fine", `${browser}/b.pointer.tsx`), pair("ui-react-layout", `${browser}/c.layout.tsx`)]).slice(2, 4), "ONE_FLAG_PER_PROJECT").toEqual(["--project=rail-fine", "--project=ui-react-layout"]); }); @@ -422,3 +428,25 @@ describe("the command", () => { } }); }); + +test("resolved Vitest projects scale their own default caps and expose the factor to browser watchdogs", () => { + const projects: { name: string; config: { testTimeout: number; hookTimeout: number; env: Record } }[] = [ + { name: "harbour", config: { testTimeout: 15000, hookTimeout: 10000, env: { TIDE: "high" } } }, + { name: "strait", config: { testTimeout: 1700, hookTimeout: 900, env: {} } }, + { name: "unbounded", config: { testTimeout: 0, hookTimeout: 0, env: {} } }, + ]; + scaleVitestDeadlines({ projects }, 3); + expect(projects.map(project => project.config), "PROJECT_DEFAULTS_AND_BROWSER_ENV_SCALE").toEqual([ + { testTimeout: 45000, hookTimeout: 30000, env: { TIDE: "high", BRAIN_TEST_DEADLINE_FACTOR: "3" } }, + { testTimeout: 5100, hookTimeout: 2700, env: { BRAIN_TEST_DEADLINE_FACTOR: "3" } }, + { testTimeout: 0, hookTimeout: 0, env: { BRAIN_TEST_DEADLINE_FACTOR: "3" } }, + ]); +}); + + +test("a diagnostic deadline factor is validated, reported and handed unchanged to the container", async () => { + expect(parseArguments(["--deadline-factor", "1", "harbour::tests/fixtures/browser-deadlines/deadline-work.repeat.js"]).deadlineFactor).toBe(1); + for (const value of ["0", "101", "3.5", "", "three"]) + expect(() => parseArguments(["--deadline-factor", value, "harbour::tests/fixtures/browser-deadlines/deadline-work.repeat.js"])).toThrow("whole number from 1 to 100"); + expect(passPlan(planBrowserRepetitions([pair("harbour", "tests/fixtures/browser-deadlines/deadline-work.repeat.js")], { costs: {} }), { deadlineFactor: 1 }).deadlineFactor).toBe(1); +}); diff --git a/tests/fixtures/browser-deadlines/deadline-explicit-hook.repeat.js b/tests/fixtures/browser-deadlines/deadline-explicit-hook.repeat.js new file mode 100644 index 0000000000..54c3cc6f9a --- /dev/null +++ b/tests/fixtures/browser-deadlines/deadline-explicit-hook.repeat.js @@ -0,0 +1,5 @@ +// An explicit hook timeout takes precedence over the scaled project default. +import { beforeAll, test } from "vitest"; + +beforeAll(async () => { await new Promise(() => {}); }, 80); +test("the missing crew prevents departure", () => {}); diff --git a/tests/fixtures/browser-deadlines/deadline-hang.repeat.js b/tests/fixtures/browser-deadlines/deadline-hang.repeat.js new file mode 100644 index 0000000000..41e8c286b0 --- /dev/null +++ b/tests/fixtures/browser-deadlines/deadline-hang.repeat.js @@ -0,0 +1,6 @@ +// Selected only by the harness's negative receipt: a real unresolved promise. +import { test } from "vitest"; + +test("the missing crew never arrives", async () => { + await new Promise(() => {}); +}); diff --git a/tests/fixtures/browser-deadlines/deadline-hook.repeat.js b/tests/fixtures/browser-deadlines/deadline-hook.repeat.js new file mode 100644 index 0000000000..348959a0a1 --- /dev/null +++ b/tests/fixtures/browser-deadlines/deadline-hook.repeat.js @@ -0,0 +1,9 @@ +// A default hook cap of 700 ms becomes 2,100 ms inside the loaded command. +import { beforeAll, expect, test } from "vitest"; + +let aboard = false; +beforeAll(async () => { + await new Promise(done => setTimeout(done, 1000)); + aboard = true; +}); +test("the crew is aboard after the hook", () => { expect(aboard).toBe(true); }); diff --git a/tests/fixtures/browser-deadlines/deadline-work.repeat.js b/tests/fixtures/browser-deadlines/deadline-work.repeat.js new file mode 100644 index 0000000000..ba8d271948 --- /dev/null +++ b/tests/fixtures/browser-deadlines/deadline-work.repeat.js @@ -0,0 +1,11 @@ +// A fixed amount of CPU work, about half the fixture project's unloaded 1 s +// timeout. Under deliberate CPU contention it needs the repetition factor. +import { expect, test } from "vitest"; + +test("the crew counts the oars under load", () => { + const start = performance.now(); + let count = 1; + for (let index = 0; index < 500_000_000; index++) count = Math.imul(count ^ index, 1_664_525); + console.log(`Oar count took ${(performance.now() - start).toFixed(0)} ms`); + expect(count).toBe(793779201); +}); diff --git a/tests/fixtures/browser-deadlines/vitest.config.mjs b/tests/fixtures/browser-deadlines/vitest.config.mjs new file mode 100644 index 0000000000..434dd7bcdd --- /dev/null +++ b/tests/fixtures/browser-deadlines/vitest.config.mjs @@ -0,0 +1,17 @@ +// Isolated watchdog fixtures: no ordinary project includes these specs. +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { playwright } from "@vitest/browser-playwright"; +import { defineConfig } from "vitest/config"; + +export default defineConfig({ + cacheDir: join(tmpdir(), "brain-kit-browser-deadline-fixture"), + test: { + name: "harbour", + include: ["*.repeat.js"], + testTimeout: 1000, + hookTimeout: 700, + browser: { enabled: true, headless: true, screenshotFailures: false, + provider: playwright({}), instances: [{ browser: "chromium" }] }, + }, +});