From cb4128588f23adc529cd6b20ee6ccb9b0ed97b02 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 00:17:27 +0000 Subject: [PATCH 1/6] chore(ci): repeat changed Bun test files under CPU load (#4109) Add bun scripts/test-determinism.ts. It selects the Bun test files a change adds or modifies against its merge base and runs them through the offline test wrapper with --rerun-each and --bail=1 while one busy loop per CPU runs. Five repetitions by default, reduced uniformly to a floor of two when the reviewed weights exceed the 600-second budget; no selected file is skipped and the report lists each with its repetitions. Burners are killed by PID on every exit path and exit by themselves when their parent dies. The planner records the selection for pull requests and selects determinism at every pull-request cadence, drafts included, and never on main. Co-Authored-By: Claude Fable 5.2 --- scripts/ci-plan.ts | 26 ++- scripts/test-determinism.ts | 310 +++++++++++++++++++++++++++++++++ tests/candidate-proof.test.ts | 10 +- tests/ci-plan.test.ts | 46 ++++- tests/test-determinism.test.ts | 299 +++++++++++++++++++++++++++++++ 5 files changed, 683 insertions(+), 8 deletions(-) create mode 100644 scripts/test-determinism.ts create mode 100644 tests/test-determinism.test.ts diff --git a/scripts/ci-plan.ts b/scripts/ci-plan.ts index d199e2c85b..f5313502b5 100644 --- a/scripts/ci-plan.ts +++ b/scripts/ci-plan.ts @@ -149,6 +149,8 @@ export interface CheckPlan { local: { fullTests: boolean; browser: boolean; layout: boolean; captures: boolean; runtime: boolean; endurance: boolean }; /** Main pushes also prove the open red-main record's failures (#2942). */ redMain?: IncludedRedSet; + /** Bun test files a pull request adds or modifies; each repeats under CPU load before merge (#4109). */ + determinism?: string[]; } export function workspaces(root: string): Workspace[] { @@ -307,7 +309,22 @@ export function planChecks(changed: readonly string[], packages: readonly Worksp // Explicit roots identify a real harness; two-argument synthetic workspace diagnostics stay conservative. const explicitRoot = arguments.length >= 3; const plan = planBeforeBrowserClosures(changed, packages, root, enableConsumerSelection, explicitRoot); - return explicitRoot && !plan.global ? selectBrowserClosures(plan, discoverBrowserClosures(root)) : plan; + const selected = explicitRoot && !plan.global ? selectBrowserClosures(plan, discoverBrowserClosures(root)) : plan; + // Main pushes and their red-main replans pass enableConsumerSelection=false: repetition is pre-merge proof. + const determinism = explicitRoot && enableConsumerSelection ? determinismTests(root, changed) : []; + return determinism.length ? { ...selected, determinism } : selected; +} + +/** + * The Bun test files among `changed` that exist in this checkout: what a + * change adds or modifies, never what it deletes (#4109). Same roots, name + * suffixes and directory exclusions as `discoverTests` (scripts/test-shards.ts). + */ +export function determinismTests(root: string, changed: readonly string[]): string[] { + return [...new Set(changed)].filter(path => /^(?:packages|tests)\//.test(path) && + /(?:\.test|\.spec|_test|_spec)\.(?:[cm]?[jt]s|[jt]sx)$/i.test(basename(path)) && + !path.split("/").slice(0, -1).some(part => part.startsWith(".") || part.toLowerCase() === "node_modules") && + lstatSync(join(root, path), { throwIfNoEntry: false })?.isFile() === true).sort(); } /** @@ -425,11 +442,14 @@ export function proofSelections(plan: CheckPlan, draft = false): Record 0; + return { ...Object.fromEntries(Object.entries({ verify: plan.typecheck || ((feedback || !plan.local.fullTests) && plan.tests.length > 0), pack: !feedback && plan.pack, unit: !feedback && plan.local.fullTests, browser: !feedback && plan.local.browser, layout: !feedback && plan.local.layout, captures: !feedback && plan.local.captures, runtime: !feedback && plan.local.runtime, runtime_host: !feedback && plan.local.runtime, endurance: !feedback && plan.local.endurance, - }).map(([name, selected]) => [name, !draft && !(confirmation && isPostMerge(name as Category)) && selected])); + }).map(([name, selected]) => [name, !draft && !(confirmation && isPostMerge(name as Category)) && selected])), determinism }; } function git(root: string, args: string[]): string { diff --git a/scripts/test-determinism.ts b/scripts/test-determinism.ts new file mode 100644 index 0000000000..abc82d3ad3 --- /dev/null +++ b/scripts/test-determinism.ts @@ -0,0 +1,310 @@ +/** + * Repeats a change's added or modified Bun test files under CPU load (#4109). + * + * Most red-main incidents were cleared by changing only a test: a racy wait, an + * unpinned clock, a deadline a loaded shard missed. Such a test passes once and + * fails later on someone else's merge. This command runs each changed file + * several times before it merges, while busy loops occupy the CPUs. + * + * bun scripts/test-determinism.ts --base origin/main [--json] + * bun scripts/test-determinism.ts tests/a.test.ts ... # an explicit selection (hosted job) + * + * The files run in one invocation of the offline wrapper (`bun run test`, + * scripts/test.ts), so its preload, lease and single preparation build apply, + * with Bun's `--rerun-each= --bail=1`. Verified against Bun 1.4.2: each file + * runs n times in a row in one process, its module is evaluated again for each + * run, `globalThis` and process state persist between runs, and a run with + * output is headed `: (run #k)` on stderr. A file that leaks state into + * its next run therefore fails here too. + * + * Bounded: five repetitions by default, reduced uniformly to a floor of two + * when the reviewed weights (scripts/test-shard-costs.json) exceed the budget. + * No selected file is dropped; the report lists each with its repetitions. + * Policy: docs/decisions/ci-utility.md, "Changed tests repeat under load before merge". + */ +import { appendFileSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { availableParallelism, constants } from "node:os"; +import { dirname, join, resolve } from "node:path"; +import { changedFiles, determinismTests } from "./ci-plan"; +import { ensureHostAdmission } from "./host-admission.mjs"; +import { discoverTests, FILE_COST_SECONDS } from "./test-shards"; + +export const DEFAULT_REPETITIONS = 5; +export const FLOOR_REPETITIONS = 2; +/** Total reviewed-weight seconds the repetitions may cost before they are reduced. */ +export const BUDGET_SECONDS = 600; +/** A file without a reviewed weight costs the small-file default (scripts/test-shards.ts). */ +const UNWEIGHTED_SECONDS = 0.1; +/** A burner outlives its parent by one slice at most, and never this long. */ +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"; + +export interface FileRepetitions { file: string; weightSeconds: number; weighted: boolean; repetitions: number; observed?: number; } +export interface RepetitionPlan { + requested: number; floor: number; repetitions: number; reduced: boolean; + budgetSeconds: number; weightSeconds: number; estimatedSeconds: number; overBudget: boolean; + files: FileRepetitions[]; +} +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; +} + +/** + * The same count for every file: the most repetitions that fit the budget, + * never more than requested and never fewer than the floor. A selection too + * heavy for the floor still runs at the floor and is reported over budget. + */ +export function planRepetitions(files: readonly string[], options: { repetitions?: number; floor?: number; budgetSeconds?: number; + costs?: Readonly> } = {}): RepetitionPlan { + const requested = options.repetitions ?? DEFAULT_REPETITIONS, floor = options.floor ?? FLOOR_REPETITIONS; + const budgetSeconds = options.budgetSeconds ?? BUDGET_SECONDS, costs = options.costs ?? FILE_COST_SECONDS; + if (!Number.isSafeInteger(floor) || floor < 2) throw new Error("The repetition floor is at least two: one run proves nothing about the next"); + if (!Number.isSafeInteger(requested) || requested < floor) throw new Error(`Repetitions must be an integer of at least ${floor}`); + if (!Number.isFinite(budgetSeconds) || budgetSeconds <= 0) throw new Error("The time budget must be positive seconds"); + if (new Set(files).size !== files.length) throw new Error("A test file was selected twice"); + const weights = files.map(file => { + const weighted = Object.hasOwn(costs, file), weightSeconds = weighted ? costs[file]! : UNWEIGHTED_SECONDS; + if (!Number.isFinite(weightSeconds) || weightSeconds <= 0) throw new Error(`Test file costs must be positive finite seconds: ${file}`); + return { file, weightSeconds, weighted }; + }); + const weightSeconds = weights.reduce((sum, entry) => sum + entry.weightSeconds, 0); + const fit = weightSeconds > 0 ? Math.floor(budgetSeconds / weightSeconds) : requested; + const repetitions = Math.max(floor, Math.min(requested, fit)); + const estimatedSeconds = weightSeconds * repetitions; + return { requested, floor, repetitions, reduced: repetitions < requested, budgetSeconds, weightSeconds, estimatedSeconds, + overBudget: estimatedSeconds > budgetSeconds, files: weights.map(entry => ({ ...entry, repetitions })) }; +} + +/** The wrapper's argv: one invocation, so preparation builds once for every repetition. */ +export function repetitionArgv(files: readonly string[], repetitions: number): string[] { + return [process.execPath, "run", "test", `--rerun-each=${repetitions}`, "--bail=1", + "--reporter=junit", `--reporter-outfile=${JUNIT_PATH}`, ...files.map(file => `./${file}`)]; +} + +const plain = (text: string) => text.replace(/\x1b\[[0-9;]*m/g, ""); + +/** + * The first failure in the wrapper's stderr: Bun heads a run's output with + * `: (run #k)` and reports the case as `(fail) [