diff --git a/.agents/skills/work-issue/references/ci-and-merge.md b/.agents/skills/work-issue/references/ci-and-merge.md index 2dd6fbe090..0870b82db2 100644 --- a/.agents/skills/work-issue/references/ci-and-merge.md +++ b/.agents/skills/work-issue/references/ci-and-merge.md @@ -128,7 +128,11 @@ Forks use ordinary `pull_request` with a read-only token (`contents: read`, plus `actions: read` / `checks: read` for bounded proof lookup), no secrets and nonpersisted checkout credentials; an approval-held run has not passed. Drafts run cheap gates only, and tests-only changes may intentionally skip -packaging while complete affected tests run. Read actual GitHub checks +packaging while complete affected tests run. One job is the exception: when a +PR adds or modifies a Bun test file, `determinism` repeats those files under +CPU load at every cadence, drafts included, and `draft gates` and `proof` +require it. A failing repetition is fixed in the test, never rerun +([the gate](../../../../docs/process/testing.md#changed-tests-repeat-under-load)). Read actual GitHub checks and logs for the current head, never an old Depot receipt or latest-main run. GitHub checks/statuses may include additional gates. No rows, queued/running checks or cancelled runs are not green. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b17e0d5f53..355ffa093a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,6 +21,8 @@ concurrency: # Drafts run cheap gates; synchronize gives fast feedback. Open/ready/reopen # requests final affected confirmation. The proof gate refuses intermediate feedback. +# One job is selected at every pull-request cadence, drafts included: `determinism` +# repeats the Bun test files a change adds or modifies under CPU load (#4109). # Independent jobs start together; each PR owns its cancellation group (#1326). jobs: changeset: @@ -38,6 +40,7 @@ jobs: unit_shards: ${{ steps.plan.outputs.unit_shards }} verify: ${{ steps.plan.outputs.verify }} pack: ${{ steps.plan.outputs.pack }} + determinism: ${{ steps.plan.outputs.determinism }} run_browser: ${{ steps.reuse.outputs.run_browser }} run_layout: ${{ steps.reuse.outputs.run_layout }} reuse: ${{ steps.reuse.outputs.reuse }} @@ -651,10 +654,66 @@ jobs: if-no-files-found: warn retention-days: 7 + determinism: + # A changed test that passes once can still fail on someone else's merge (#4109). + needs: changeset + if: ${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && needs.changeset.outputs.determinism == 'true' }} + runs-on: ubuntu-24.04 + # 12 minutes setup + 40 minutes proof + 3 minutes for other steps. + timeout-minutes: 55 + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + fetch-depth: 0 + - uses: oven-sh/setup-bun@v2 + with: + bun-version: "1.4.2" + # Native source freezes require dependency inodes owned by this checkout. + - run: bun install --frozen-lockfile --backend=copyfile + - name: Recompute affected proof on the actual checkout + env: + BASE_SHA: ${{ github.event.pull_request.base.sha }} + BEFORE_SHA: ${{ github.event.before }} + HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + RED_MAIN_OID: ${{ needs.changeset.outputs.red_main_oid }} + run: bun scripts/ci-plan.ts + # The unit job's prerequisites: a changed file may drive real Chrome or the offline namespaces. + - name: Real Chrome and offline Linux namespace prerequisites + id: runtime_setup + timeout-minutes: 12 + run: bash scripts/ci-runtime-setup.sh + - name: Repeat changed Bun test files under CPU load + id: runtime_proof + timeout-minutes: 40 + run: bun scripts/ci-proof.ts determinism + - name: Environment setup and proof outcomes + if: always() + env: + SETUP_OUTCOME: ${{ steps.runtime_setup.outcome }} + PROOF_OUTCOME: ${{ steps.runtime_proof.outcome }} + run: | + printf 'Environment setup (infrastructure prerequisite, 12-minute limit): %s\nProof (40-minute limit): %s\n' \ + "$SETUP_OUTCOME" "$PROOF_OUTCOME" >> "$GITHUB_STEP_SUMMARY" + - name: Proof receipts and failure diagnostics + if: always() + uses: actions/upload-artifact@v7 + with: + name: determinism-proof + path: | + tmp/determinism-report.json + tmp/determinism-junit.xml + tmp/proof-checkout.json + tmp/proof-resources.json + tmp/runner-disk.json + include-hidden-files: true + if-no-files-found: warn + retention-days: 7 + proof: name: ${{ github.event_name != 'pull_request' && 'integrated or exhaustive proof' || github.event.pull_request.draft && 'draft gates' || 'proof' }} # Evaluate even after failures or skips; never interpret missing selected proof as green. - needs: [changeset, verify, pack, unit, runtime, runtime_host, browser, layout, captures, endurance] + needs: [changeset, verify, pack, unit, runtime, runtime_host, browser, layout, captures, endurance, determinism] if: ${{ always() && !cancelled() }} runs-on: ubuntu-24.04 timeout-minutes: 3 diff --git a/.github/workflows/heavy-feedback.yml b/.github/workflows/heavy-feedback.yml index 5322a51276..c5ee363e34 100644 --- a/.github/workflows/heavy-feedback.yml +++ b/.github/workflows/heavy-feedback.yml @@ -51,6 +51,7 @@ jobs: unit_shards: "${{ steps.plan.outputs.unit_shards }}" verify: "${{ steps.plan.outputs.verify }}" pack: "${{ steps.plan.outputs.pack }}" + determinism: "${{ steps.plan.outputs.determinism }}" run_browser: "${{ steps.reuse.outputs.run_browser }}" run_layout: "${{ steps.reuse.outputs.run_layout }}" red_main_oid: "${{ steps.plan.outputs.red_main_oid }}" @@ -444,6 +445,50 @@ jobs: include-hidden-files: true if-no-files-found: warn retention-days: 7 + determinism: + needs: changeset + if: "${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && needs.changeset.outputs.determinism == 'true' }}" + runs-on: ubuntu-24.04 + timeout-minutes: 55 + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + fetch-depth: 0 + ref: "${{ inputs.head_sha }}" + - uses: oven-sh/setup-bun@v2 + with: + bun-version: 1.4.2 + - run: bun install --frozen-lockfile --backend=copyfile + - name: Recompute affected proof on the actual checkout + env: + BASE_SHA: "${{ needs.changeset.outputs.base_sha }}" + HEAD_SHA: "${{ inputs.head_sha }}" + FEEDBACK_PR: "${{ inputs.pr }}" + run: bun scripts/ci-plan.ts + - name: Real Chrome and offline Linux namespace prerequisites + id: runtime_setup + timeout-minutes: 12 + run: bash scripts/ci-runtime-setup.sh + - name: Repeat changed Bun test files under CPU load + id: runtime_proof + timeout-minutes: 40 + run: bun scripts/ci-proof.ts determinism + - name: Environment setup and proof outcomes + if: always() + env: + SETUP_OUTCOME: "${{ steps.runtime_setup.outcome }}" + PROOF_OUTCOME: "${{ steps.runtime_proof.outcome }}" + run: "printf 'Environment setup (infrastructure prerequisite, 12-minute limit): %s\\nProof (40-minute limit): %s\\n' \\\n \"$SETUP_OUTCOME\" \"$PROOF_OUTCOME\" >> \"$GITHUB_STEP_SUMMARY\"\n" + - name: Proof receipts and failure diagnostics + if: always() + uses: actions/upload-artifact@v7 + with: + name: determinism-proof + path: "tmp/determinism-report.json\ntmp/determinism-junit.xml\ntmp/proof-checkout.json\ntmp/proof-resources.json\ntmp/runner-disk.json\n" + include-hidden-files: true + if-no-files-found: warn + retention-days: 7 aggregate: name: draft heavy feedback needs: @@ -457,6 +502,7 @@ jobs: - layout - captures - endurance + - determinism if: "${{ always() && !cancelled() && github.event_name == 'workflow_dispatch' }}" runs-on: ubuntu-24.04 timeout-minutes: 3 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ca628ae45f..4df162dff7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -223,7 +223,9 @@ real Chrome and required namespaces may not silently skip. The final `proof` check requires every selected category to pass. Scheduled/manual exhaustive runs supplement affected PR proof; they do not replace it. -Drafts stay on cheap gates. Opening/reopening a ready PR or marking it ready +Drafts stay on cheap gates, plus one job: a PR that adds or modifies a Bun +test file has those files repeated under CPU load +([why](docs/process/testing.md#changed-tests-repeat-under-load)). Opening/reopening a ready PR or marking it ready requests affected candidate confirmation of the fast categories (types, packaging, unit/integration); heavy runtime, browser, layout, capture and endurance proof runs on the squash's own main run diff --git a/docs/decisions/ci-utility.md b/docs/decisions/ci-utility.md index 530166972e..67f1e48340 100644 --- a/docs/decisions/ci-utility.md +++ b/docs/decisions/ci-utility.md @@ -1815,7 +1815,7 @@ stay pre-merge; heavy categories move to the squash's own main run. `unit` (complete affected unit/integration discovery, unchanged). It no longer runs `runtime`, `runtime_host`, `browser`, `layout`, `captures` or `endurance`. The exclusion lives in one place: - `proofSelections` (`scripts/ci-plan.ts:424-433`) applies + `proofSelections` (`scripts/ci-plan.ts:441-453`) applies `POST_MERGE_CATEGORIES` (`scripts/red-main.ts:20-25`). Candidate admission, the aggregate and the merge path validate that same selection, so none of them can require a post-merge category. @@ -1907,6 +1907,79 @@ lease, red-main refusal, main's complete affected proof and releases from a green main all still apply. A fast-lane merge is not a successful delivery until its main run is green. +## Changed tests repeat under load before merge + +The maintainer ruled on 2026-11-16 +([#4109](https://github.com/schlessera/brain-kit/issues/4109)) that a Bun test +file a pull request adds or modifies must pass repeated runs under CPU load +before it merges. + +**Why.** Main went red 25 times between 2026-11-02 and 2026-11-16. About 18 of +those incidents were cleared by changing only a test: a wait, a pinned clock, +a readiness signal, a deadline a loaded shard could meet. About six were +product defects. The first-main failure rate was about the same for PRs under +100 lines (19%) as for PRs over 2,000 lines (22%). These are tests that pass +once and fail later on someone else's merge, and nothing ran a new or changed +test more than once before it merged. + +- **What runs.** `bun scripts/test-determinism.ts --base ` selects the + Bun test files under `packages/` and `tests/` that the change adds or + modifies against its merge base (`determinismTests`, + `scripts/ci-plan.ts:323-328`). It runs them in one invocation of the offline + wrapper with Bun's `--rerun-each= --bail=1` (`repetitionArgv`, + `scripts/test-determinism.ts:84-87`), 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:136-151`). 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 600 seconds of + the reviewed weights in `scripts/test-shard-costs.json`. When five do not + fit, every file gets the same reduced count, down to a floor of two + (`planRepetitions`, `scripts/test-determinism.ts:62-81`). A selection too + heavy for the floor still runs every file twice and is reported over budget. + No selected file is skipped; the report lists each one with the repetitions + it got. Over 150 merges before the gate, 142 selections fit five + repetitions. A selection too heavy for the job's step limit is + [#4117](https://github.com/schlessera/brain-kit/issues/4117). +- **Where it is required.** The hosted `determinism` job is selected whenever + the plan lists such a file, at every pull-request cadence: draft, ready + `synchronize` feedback and ready confirmation. Draft heavy feedback runs it + too (`proofSelections`, `scripts/ci-plan.ts:441-453`). This amends "drafts + run cheap gates only" for this one job, so the + [fast lane](#fast-lane-outside-the-core-packages)'s newest run includes it. + `draft gates`, `proof` and the merge path require it when selected and + require its intentional skip otherwise. It is a fast category under the + [hybrid split](#hybrid-post-merge-heavy-proof): it is not in + `POST_MERGE_CATEGORIES`. The job has the `unit` job's runtime prerequisites, + because a changed file may drive real Chrome. +- **Not on main.** A main push never selects it. The squash's files were + repeated before they merged, and the main run already runs each of them once + in `unit`. +- **Not local.** `check:pr` never runs it, because it occupies every CPU of a + shared host. `check:pr --plan` names the command when the change selects it. + 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. + +**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 +GitHub Actions Bun prints each run's header as a `::group::` annotation, which +the failure parser did not read, so the failure was reported without its file +and repetition. The parser reads both forms now. That run took 552 seconds +for about 174 weighted seconds, a ratio of about 3.2 under four burners on +four CPUs, so a selection at the 600-second budget needs about 32 minutes of +the 40-minute step limit. + +**Known limits.** Repetitions of one file share a process. Bun 1.4.2 evaluates +the module again for each run, but `globalThis` and process state persist, so a +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)). + ## Historical measurement and upstream guidance The following guidance records the paid-provider investigation which motivated diff --git a/docs/decisions/test-health.md b/docs/decisions/test-health.md index 16267cfc63..a361ce3a70 100644 --- a/docs/decisions/test-health.md +++ b/docs/decisions/test-health.md @@ -39,7 +39,7 @@ follows is in [ci-utility.md](ci-utility.md) and enumerated fields. - **A batch stays inside one group and lands as one pull request.** Hosted proof for a test edit is priced by the workspaces it touches, not by the - number of files (`const packageCode`, `scripts/ci-plan.ts:355-356`): any path + number of files (`const packageCode`, `scripts/ci-plan.ts:372-373`): any path under a package's `tests/` selects that package and its reverse dependants. One changed test in a package costs the same confirmation as thirty, so small pull requests are the most expensive way to land this work. A large diff --git a/docs/process/test-authoring.md b/docs/process/test-authoring.md index d114bbd174..20715031e9 100644 --- a/docs/process/test-authoring.md +++ b/docs/process/test-authoring.md @@ -151,6 +151,15 @@ test("the date field shows the parsed date and refuses an unparseable one", asyn discovers. Prevents `skipped`, `conditional-skip`, `retry`, `only` and `undiscovered`. +A Bun test file that a pull request adds or modifies is checked against these +rules before it merges: the hosted `determinism` job runs it five times in a +row under CPU load and fails on the first failing repetition +([the gate](testing.md#changed-tests-repeat-under-load)). A test that waits for +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. + ## Cost - **C1. Know the budget of the tier.** Most unit files finish in under a diff --git a/docs/process/testing.md b/docs/process/testing.md index bf7d70c538..773b0483a8 100644 --- a/docs/process/testing.md +++ b/docs/process/testing.md @@ -297,6 +297,41 @@ Await it and assert on the result, or use `expectRejection` (`packages/ui-server/tests/helpers/expect-rejection.ts`) ([why](../decisions/sqlite-write-worker.md#testing-note)). +## Changed tests repeat under load + +A Bun test file that a pull request adds or modifies runs several times under +CPU load before it merges +([the 2026-11-16 ruling](../decisions/ci-utility.md#changed-tests-repeat-under-load-before-merge)). +Most red-main incidents in the two weeks before it were cleared by changing +only a test that had passed once. + +```sh +bun scripts/test-determinism.ts --base origin/main # what the hosted job runs +bun scripts/test-determinism.ts --base origin/main --json # the report on stdout +``` + +- **Selection.** Files that `bun test` discovers under `packages/` and + `tests/`, added or modified against the merge base. Deleted files, the + experiment tier and Vitest specs are not selected. +- **The run.** One invocation of `bun run test` with `--rerun-each` and + `--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. +- **The bound.** Five repetitions, reduced uniformly to no fewer than two when + the reviewed weights in `scripts/test-shard-costs.json` exceed 600 seconds. + The report lists every selected file with the repetitions it got, and says + when the selection is over budget at the floor. +- **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. +- **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 + occupies every CPU, and the host is shared. `check:pr --plan` prints the + command when it applies. A local run waits for + [host admission](#host-admission-for-heavy-local-commands); + `--burners ` lowers the load for a diagnosis. + ## Tests that cannot fail A green test is evidence only if it could have been red. Each of these shapes @@ -636,7 +671,10 @@ in the [CI and merge reference](../../.agents/skills/work-issue/references/ci-an release preparation runs instead of PR proof. Scheduled exhaustive CI is additional coverage, not a replacement for selected pre-merge proof. -- Drafts run cheap gates. Ready `opened`, `reopened` and `ready_for_review` +- Drafts run cheap gates, plus the `determinism` job when the change adds or + modifies a Bun test file + ([changed tests repeat under load](#changed-tests-repeat-under-load)). + Ready `opened`, `reopened` and `ready_for_review` events request full affected confirmation. Ready `synchronize` runs affected fast invariants and types only; `proof` remains nonpassing until the author converts to draft and marks ready after the final push. A push invalidates @@ -713,13 +751,15 @@ action/runtime versions, pinned offline browser image and diagnostic artifacts. Independent selected categories run after metadata; the final proof aggregate rejects failures, cancellations, missing outputs and unexpected skips. Tests-only changes may intentionally skip packaging while complete -affected tests run. Drafts run cheap gates only. Forks use ordinary +affected tests run. Drafts run cheap gates only, with one exception: the +`determinism` job repeats a change's added or modified Bun test files under +CPU load at every pull-request cadence. Forks use ordinary `pull_request`, a read-only token (`contents: read`, plus `actions: read` / `checks: read` for bounded proof lookup), no secrets and nonpersisted checkout credentials. A fork run awaiting maintainer approval has not passed. Environment setup via `scripts/ci-runtime-setup.sh` has its own 12-minute -step limit in `unit`, `runtime` and `runtime_host`. Proof retains a separate +step limit in `unit`, `runtime`, `runtime_host` and `determinism`. Proof retains a separate 30-minute unit allowance or 15-minute runtime allowance. The job caps are 45 and 30 minutes respectively, including three minutes for the remaining steps. The [timeout basis](../decisions/ci-utility.md#separate-environment-setup-and-proof-budgets) diff --git a/scripts/check-ci-workflows.ts b/scripts/check-ci-workflows.ts index 3b50cbb7cb..033d2ff29d 100644 --- a/scripts/check-ci-workflows.ts +++ b/scripts/check-ci-workflows.ts @@ -32,7 +32,7 @@ export function workflowProblems(text: string, file: string): string[] { if (JSON.stringify(workflow.permissions) !== JSON.stringify(permissions)) fail("workflow permissions must be the specified read-only contents/actions scope"); const expectedTriggers = file === "ci.yml" ? ["pull_request", "push", "schedule", "workflow_dispatch"] : ["pull_request"]; if (JSON.stringify(Object.keys(workflow.on ?? {}).sort()) !== JSON.stringify(expectedTriggers)) fail("unexpected contribution triggers"); - const expectedJobs = file === "ci.yml" ? ["browser", "captures", "changeset", "endurance", "layout", "pack", "proof", "runtime", "runtime_host", "unit", "verify"] : ["contract"]; + const expectedJobs = file === "ci.yml" ? ["browser", "captures", "changeset", "determinism", "endurance", "layout", "pack", "proof", "runtime", "runtime_host", "unit", "verify"] : ["contract"]; if (JSON.stringify(Object.keys(workflow.jobs ?? {}).sort()) !== JSON.stringify(expectedJobs)) fail("missing or unexpected CI jobs"); for (const [name, job] of Object.entries(workflow.jobs ?? {})) { if (job["runs-on"] !== "ubuntu-24.04") fail(`${name}: unmapped GitHub-hosted runner`); @@ -52,7 +52,7 @@ export function workflowProblems(text: string, file: string): string[] { } } if (file === "ci.yml") { - const names = ["verify", "pack", "unit", "runtime", "runtime_host", "browser", "layout", "captures", "endurance"]; + const names = ["verify", "pack", "unit", "runtime", "runtime_host", "browser", "layout", "captures", "endurance", "determinism"]; for (const name of names) { const job = workflow.jobs?.[name]; if (job?.needs !== "changeset") fail(`${name}: independent proof must depend only on metadata`); @@ -78,9 +78,10 @@ export function workflowProblems(text: string, file: string): string[] { verifySteps.indexOf(summary) <= verifySteps.findIndex(s => s.id === "verify_proof")) fail("verify: always summary must separate raw install, planning and proof outcomes and receipts"); // Network prerequisites cannot spend proof capacity; measured basis: docs/decisions/ci-utility.md (#2658). - for (const [name, proofMinutes] of [["unit", 30], ["runtime", 15], ["runtime_host", 15]] as const) { + // Repeated changed tests need the unit job's prerequisites: they may drive real Chrome (#4109). + for (const [name, proofMinutes] of [["unit", 30], ["runtime", 15], ["runtime_host", 15], ["determinism", 40]] as const) { const job = workflow.jobs?.[name]; - const setup = job?.steps?.find(step => step.run === `bash scripts/ci-runtime-setup.sh${name === "unit" ? "" : " --native"}`); + const setup = job?.steps?.find(step => step.run === `bash scripts/ci-runtime-setup.sh${name === "unit" || name === "determinism" ? "" : " --native"}`); const command = `bun scripts/ci-proof.ts ${name}`; const proof = job?.steps?.find(step => step.run === command || step.run?.startsWith(`${command} `)); if (setup?.["timeout-minutes"] !== 12) fail(`${name}: environment setup must have its separate 12-minute limit`); @@ -98,7 +99,7 @@ export function workflowProblems(text: string, file: string): string[] { if (proof?.name !== "${{ github.event_name != 'pull_request' && 'integrated or exhaustive proof' || github.event.pull_request.draft && 'draft gates' || 'proof' }}") fail("proof: draft, manual or main runs must not impersonate candidate confirmation"); if (JSON.stringify(proof?.needs) !== JSON.stringify(["changeset", ...names])) fail("proof: aggregate must observe every selected category"); if (proof?.if !== "${{ always() && !cancelled() }}") fail("proof: aggregate must observe failures/skips and reject cancellation"); - for (const category of ["unit", "runtime", "runtime_host", "browser", "layout", "captures", "endurance"]) { + for (const category of ["unit", "runtime", "runtime_host", "browser", "layout", "captures", "endurance", "determinism"]) { if (!workflow.jobs?.[category]?.steps?.some(step => step.run === `bun scripts/ci-proof.ts ${category}` || step.run?.startsWith(`bun scripts/ci-proof.ts ${category} `))) fail(`${category}: complete proof command is missing`); } if (!proof?.steps?.some(step => step.run === "bun scripts/ci-proof.ts aggregate")) fail("proof: executable aggregate is missing"); diff --git a/scripts/check-pr.ts b/scripts/check-pr.ts index 12685959ba..3d98b97d69 100644 --- a/scripts/check-pr.ts +++ b/scripts/check-pr.ts @@ -68,6 +68,15 @@ export function localChecks(plan: CheckPlan, full = false, mergeBase?: string, i return checks; } +/** + * The repeated-run command for a plan that changes Bun test files (#4109). + * `check:pr` names it and never runs it: it occupies every CPU of a shared + * host, so the hosted `determinism` job is where it runs. + */ +export function determinismCommand(plan: CheckPlan, base: string): string | undefined { + return plan.determinism?.length ? `bun scripts/test-determinism.ts --base ${base}` : undefined; +} + class SandboxSetupTimeout extends Error {} /** The fastest of three sandbox setup probes must take less than this. */ @@ -266,7 +275,9 @@ if (import.meta.main) { const importGraphFeedback = full ? "skipped: --full/--all retain their existing suites" : importGraph ? "enabled with --import-graph" : "skipped by default; enable with --import-graph"; console.log(JSON.stringify({ ...plan, commands: plannedCommands.map(command => command.name), commandDetails: plannedCommands, - importGraphFeedback, packedConsumerChecks: full && plan.pack, hostedProofRequired: plan.local }, null, 2)); + importGraphFeedback, packedConsumerChecks: full && plan.pack, hostedProofRequired: plan.local, + ...(determinismCommand(plan, base) ? { determinismCommand: determinismCommand(plan, base), + determinismNote: "not run locally: it occupies every CPU; the hosted determinism job repeats these files under load" } : {}) }, null, 2)); if (print) process.exit(0); const chromeStep: Command = { name: "first real Chrome launch and render", argv: [] }; const steps: PreflightStep[] = [...commands.slice(0, 3).map(command => [command]), [contributionChangeset], 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/ci-proof.ts b/scripts/ci-proof.ts index 9d354e1447..af42734ede 100644 --- a/scripts/ci-proof.ts +++ b/scripts/ci-proof.ts @@ -16,8 +16,15 @@ import { diskSampler, floorProblem } from "./ci-disk"; import { browserInventory, checkout, git, proofInputs, runnerIdentity, type Reusable, type Inputs } from "./proof-inputs"; import { contextFromEvent, GitHubProofAPI, RECEIPT_MARKER, retainedCategories } from "./proof-reuse"; -export const PROOF_JOBS = ["verify", "pack", "unit", "browser", "layout", "captures", "runtime", "runtime_host", "endurance"] as const; -export type ProofCategory = "unit" | "browser" | "layout" | "captures" | "runtime" | "runtime_host" | "endurance"; +export const PROOF_JOBS = ["verify", "pack", "unit", "browser", "layout", "captures", "runtime", "runtime_host", "endurance", "determinism"] as const; +export type ProofCategory = "unit" | "browser" | "layout" | "captures" | "runtime" | "runtime_host" | "endurance" | "determinism"; +export const DETERMINISM_REPORT = "tmp/determinism-report.json"; + +/** The planner's added or modified Bun test files; an empty selection is never a job (#4109). */ +export function determinismFiles(plan: CheckPlan): string[] { + if (!plan.determinism?.length) throw new Error("Repeated-run proof was not selected"); + return [...plan.determinism]; +} /** Aggregate requires passed selected jobs; missing/false-looking output is not proof. */ export function proofProblems(needs: Record }>, retained: ReadonlySet = new Set()): string[] { @@ -56,7 +63,11 @@ export function categoryCommands(category: ProofCategory, plan: CheckPlan, root: : [process.execPath, "run", "test", ...unitFiles(plan, root, shard).map(file => join(root, file)), "--reporter=junit", "--reporter-outfile=tmp/unit-report.xml", "--timings=tmp/unit-timings.json", "--update-timings"], env: { BRAIN_REQUIRE_CHROME: "1" } }]; - const names: Record, string[]> = { + // The unit job's serial form, repeated: changed files may drive real Chrome too. + if (category === "determinism") return [{ name: "changed Bun test files repeated under CPU load", + argv: [process.execPath, join(root, "scripts/test-determinism.ts"), `--report=${DETERMINISM_REPORT}`, ...determinismFiles(plan)], + env: { BRAIN_REQUIRE_CHROME: "1" } }]; + const names: Record, string[]> = { browser: ["workspace build for real browser checks", "complete pinned visual/accessibility/pointer suite"], layout: ["workspace build for real browser checks", "complete pinned layout/offline suite"], endurance: ["workspace build for real browser checks", "complete pinned endurance suite"], @@ -97,7 +108,7 @@ if (import.meta.main) { } else { const root = resolve(import.meta.dir, ".."); const category = process.argv[2] as ProofCategory; - if (!["unit", "browser", "layout", "captures", "runtime", "runtime_host", "endurance"].includes(category)) throw new Error("Unknown proof category"); + if (!["unit", "browser", "layout", "captures", "runtime", "runtime_host", "endurance", "determinism"].includes(category)) throw new Error("Unknown proof category"); const args = process.argv.slice(3); const shardArg = args.find(arg => arg.startsWith("--shard=")); const workersArg = args.find(arg => arg.startsWith("--workers=")); @@ -117,18 +128,18 @@ if (import.meta.main) { if (identity.exitCode !== 0) throw new Error("Cannot record actual proof checkout"); const [sha, tree, ...parents] = new TextDecoder().decode(identity.stdout).trim().split(" "); await Bun.write(join(root, "tmp/proof-checkout.json"), JSON.stringify({ category, shard, - checkout: { sha, tree, parents }, plan, inputs, files: category === "unit" ? unitFiles(plan, root, shard) : undefined }, null, 2)); - const native = category === "unit" || category === "runtime" || category === "runtime_host"; + checkout: { sha, tree, parents }, plan, inputs, files: category === "unit" ? unitFiles(plan, root, shard) : category === "determinism" ? determinismFiles(plan) : undefined }, null, 2)); + const native = category === "unit" || category === "runtime" || category === "runtime_host" || category === "determinism"; const chrome = requireRuntimeTools({ ...plan, local: { ...plan.local, fullTests: native, browser: !native, layout: !native, captures: !native } }); - if (chrome && category === "unit") await runCommands([{ name: "first real Chrome launch and render", + if (chrome && (category === "unit" || category === "determinism")) await runCommands([{ name: "first real Chrome launch and render", argv: [process.execPath, "packages/ui-render-puppeteer/tests/cold-start.ts", chrome] }], root); const commands = categoryCommands(category, plan, root, shard, unitWorkers).map(command => ({ ...command, env: { ...(chrome ? { PUPPETEER_EXECUTABLE_PATH: chrome } : {}), ...command.env, ...(inputs?.nativeDiagram?{BRAIN_PROOF_NATIVE_DIAGRAM_INPUTS:JSON.stringify(inputs.nativeDiagram)}:{}) } })); // The host/container lease regression deliberately uses --pull=never // under the offline test harness. Prepare its actual pinned image once, // only on the partition that discovers that test, before entering tests. - if (category === "unit" && unitFiles(plan, root, shard).includes("tests/workspace-lease.test.ts")) { + if ((category === "unit" ? unitFiles(plan, root, shard) : category === "determinism" ? determinismFiles(plan) : []).includes("tests/workspace-lease.test.ts")) { if (!Bun.which("docker")) throw new Error("The native workspace lease test requires Docker"); const { image } = await resolveBrowserPin(root); commands.unshift({ name: "pinned offline workspace lease container prerequisite", argv: ["docker", "pull", image], env: {} }); diff --git a/scripts/heavy-feedback-workflow.ts b/scripts/heavy-feedback-workflow.ts index c5d32b331c..e54e2d0922 100644 --- a/scripts/heavy-feedback-workflow.ts +++ b/scripts/heavy-feedback-workflow.ts @@ -12,7 +12,7 @@ import { readFileSync, writeFileSync } from "node:fs"; import { join, resolve } from "node:path"; import { FEEDBACK_AGGREGATE } from "./heavy-feedback"; -export const CATEGORY_JOBS = ["verify", "pack", "unit", "runtime", "runtime_host", "browser", "layout", "captures", "endurance"] as const; +export const CATEGORY_JOBS = ["verify", "pack", "unit", "runtime", "runtime_host", "browser", "layout", "captures", "endurance", "determinism"] as const; export const FEEDBACK_GROUP = "heavy-feedback-${{ github.event.pull_request.number || inputs.pr }}"; const HEAD = "${{ inputs.head_sha }}"; const DISPATCH = "github.event_name == 'workflow_dispatch'"; diff --git a/scripts/test-determinism.ts b/scripts/test-determinism.ts new file mode 100644 index 0000000000..e5837c144a --- /dev/null +++ b/scripts/test-determinism.ts @@ -0,0 +1,312 @@ +/** + * 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. Under GitHub Actions the same + * header opens a log group, `::group::: (run #k)`. 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)`, as a `::group::` annotation under GitHub Actions, and + * reports the case as `(fail) [