Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 61 additions & 12 deletions docs/decisions/ci-utility.md
Original file line number Diff line number Diff line change
Expand Up @@ -2187,7 +2187,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`
Expand Down Expand Up @@ -2229,7 +2229,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
Expand Down Expand Up @@ -2266,7 +2266,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.
Expand Down Expand Up @@ -2369,8 +2370,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`),
Expand All @@ -2380,10 +2381,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`).
Expand Down Expand Up @@ -2439,14 +2440,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

Expand Down
31 changes: 27 additions & 4 deletions docs/process/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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.
Expand Down Expand Up @@ -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.

Expand Down
41 changes: 41 additions & 0 deletions packages/ui-kit/tests/visual/deadline-scaling.visual.tsx
Original file line number Diff line number Diff line change
@@ -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); }
});
}
5 changes: 4 additions & 1 deletion scripts/browser-determinism-inside.d.mts
Original file line number Diff line number Diff line change
@@ -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. */
Expand All @@ -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<PassOutcome>;

export function scaleVitestDeadlines(vitest: { projects: { name: string; config: { testTimeout: number; hookTimeout: number; env?: Record<string, string> } }[] },
factor: number, log?: (line: string) => void): void;
22 changes: 20 additions & 2 deletions scripts/browser-determinism-inside.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -71,15 +71,16 @@ 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}`);
if (new Set(keys).size !== keys.length) throw new Error("A project/file pair was selected twice");
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. */
Expand Down Expand Up @@ -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 <plan.json under the repository>");
const plan = readPassPlan(JSON.parse(readFileSync(resolve(REPO, argv[0]), "utf8")));
Expand Down Expand Up @@ -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) {
Expand Down
Loading
Loading