diff --git a/.agents/skills/work-issue/references/ci-and-merge.md b/.agents/skills/work-issue/references/ci-and-merge.md index 8c439acc91..fd6a904242 100644 --- a/.agents/skills/work-issue/references/ci-and-merge.md +++ b/.agents/skills/work-issue/references/ci-and-merge.md @@ -134,7 +134,12 @@ 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. The job is `determinism (1)`; a selection too heavy for one job runs as several numbered partitions, and all of them must pass. 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 +([the gate](../../../../docs/process/testing.md#changed-tests-repeat-under-load)). +`browser_determinism` is the same rule for Vitest specs: when a PR adds or +modifies a browser, layout or story spec, it repeats those specs under CPU +load in the pinned container, as `browser_determinism (1)` or several +numbered partitions +([the gate](../../../../docs/process/testing.md#changed-browser-specs-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 8ca9af90a4..35cf8d405d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -20,9 +20,11 @@ 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), -# in as many partitions as the planner publishes (#4117). +# Two jobs are selected at every pull-request cadence, drafts included: `determinism` +# repeats the Bun test files a change adds or modifies under CPU load (#4109), and +# `browser_determinism` repeats its Vitest browser, layout and story specs in the +# pinned container (#4163). Each runs in as many partitions as the planner +# publishes (#4117). # Independent jobs start together; each PR owns its cancellation group (#1326). jobs: changeset: @@ -42,6 +44,8 @@ jobs: pack: ${{ steps.plan.outputs.pack }} determinism: ${{ steps.plan.outputs.determinism }} determinism_shards: ${{ steps.plan.outputs.determinism_shards }} + browser_determinism: ${{ steps.plan.outputs.browser_determinism }} + browser_determinism_shards: ${{ steps.plan.outputs.browser_determinism_shards }} red_main_oid: ${{ steps.plan.outputs.red_main_oid }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 @@ -708,10 +712,68 @@ jobs: if-no-files-found: warn retention-days: 7 + browser_determinism: + # A changed browser, layout or story spec that passes once can still fail on someone else's merge (#4163). + needs: changeset + if: ${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && needs.changeset.outputs.browser_determinism == 'true' }} + runs-on: ubuntu-24.04 + # 20 minutes proof (build, image and repeated passes) + 5 minutes for other steps. + timeout-minutes: 25 + # One partition while the selection fits one job's capacity; an oversized + # selection is split by reviewed weight (scripts/proof-shards.ts). + strategy: + fail-fast: false + matrix: + shard: ${{ fromJSON(needs.changeset.outputs.browser_determinism_shards) }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + persist-credentials: false + fetch-depth: 0 + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 + with: + bun-version: "1.4.2" + - run: bun install --frozen-lockfile + - 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 + - name: Repeat changed browser, layout and story specs under CPU load + timeout-minutes: 20 + env: + BROWSER_REPEAT_SHARDS: ${{ strategy.job-total }} + run: bun scripts/ci-proof.ts browser_determinism --shard=${{ matrix.shard }}/"$BROWSER_REPEAT_SHARDS" + - name: Proof receipts and failure diagnostics + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: browser-determinism-proof-${{ matrix.shard }} + path: | + tmp/browser-determinism-report.json + tmp/browser-determinism/ + tmp/proof-checkout.json + tmp/proof-resources.json + packages/ui-kit/.vitest-attachments/ + packages/ui-react/.vitest-attachments/ + .vitest-attachments/ + tmp/hygiene-proof/ + tmp/cold-capture/ + tmp/share-review/ + packages/ui-kit/**/__screenshots__/**/*-[0-9]*.png + packages/ui-react/**/__screenshots__/**/*-[0-9]*.png + !packages/ui-kit/**/__screenshots__/**/*-linux.png + !packages/ui-react/**/__screenshots__/**/*-linux.png + 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, determinism] + needs: [changeset, verify, pack, unit, runtime, runtime_host, browser, layout, captures, endurance, determinism, browser_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 6cb7bf5ed7..d33831c016 100644 --- a/.github/workflows/heavy-feedback.yml +++ b/.github/workflows/heavy-feedback.yml @@ -52,6 +52,8 @@ jobs: pack: "${{ steps.plan.outputs.pack }}" determinism: "${{ steps.plan.outputs.determinism }}" determinism_shards: "${{ steps.plan.outputs.determinism_shards }}" + browser_determinism: "${{ steps.plan.outputs.browser_determinism }}" + browser_determinism_shards: "${{ steps.plan.outputs.browser_determinism_shards }}" red_main_oid: "${{ steps.plan.outputs.red_main_oid }}" base_sha: "${{ steps.admit.outputs.base_sha }}" steps: @@ -490,6 +492,45 @@ jobs: include-hidden-files: true if-no-files-found: warn retention-days: 7 + browser_determinism: + needs: changeset + if: "${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && needs.changeset.outputs.browser_determinism == 'true' }}" + runs-on: ubuntu-24.04 + timeout-minutes: 25 + strategy: + fail-fast: false + matrix: + shard: "${{ fromJSON(needs.changeset.outputs.browser_determinism_shards) }}" + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + persist-credentials: false + fetch-depth: 0 + ref: "${{ inputs.head_sha }}" + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 + with: + bun-version: 1.4.2 + - run: bun install --frozen-lockfile + - 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: "Repeat changed browser, layout and story specs under CPU load" + timeout-minutes: 20 + env: + BROWSER_REPEAT_SHARDS: "${{ strategy.job-total }}" + run: "bun scripts/ci-proof.ts browser_determinism --shard=${{ matrix.shard }}/\"$BROWSER_REPEAT_SHARDS\"" + - name: Proof receipts and failure diagnostics + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: "browser-determinism-proof-${{ matrix.shard }}" + path: "tmp/browser-determinism-report.json\ntmp/browser-determinism/\ntmp/proof-checkout.json\ntmp/proof-resources.json\npackages/ui-kit/.vitest-attachments/\npackages/ui-react/.vitest-attachments/\n.vitest-attachments/\ntmp/hygiene-proof/\ntmp/cold-capture/\ntmp/share-review/\npackages/ui-kit/**/__screenshots__/**/*-[0-9]*.png\npackages/ui-react/**/__screenshots__/**/*-[0-9]*.png\n!packages/ui-kit/**/__screenshots__/**/*-linux.png\n!packages/ui-react/**/__screenshots__/**/*-linux.png\n" + include-hidden-files: true + if-no-files-found: warn + retention-days: 7 aggregate: name: draft heavy feedback needs: @@ -504,6 +545,7 @@ jobs: - captures - endurance - determinism + - browser_determinism if: "${{ always() && !cancelled() && github.event_name == 'workflow_dispatch' }}" runs-on: ubuntu-24.04 timeout-minutes: 3 diff --git a/docs/decisions/ci-utility.md b/docs/decisions/ci-utility.md index d6fc315bdf..692bb6b944 100644 --- a/docs/decisions/ci-utility.md +++ b/docs/decisions/ci-utility.md @@ -1708,7 +1708,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:445-457`) applies + `proofSelections` (`scripts/ci-plan.ts:490-505`) 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. @@ -1738,6 +1738,18 @@ proof covered every real regression in the October cohort. The red main that remains is mostly latent timing, browser and runtime failures, which pre-merge proof rarely prevents and which made heavy confirmation the slowest step. +**Amended 2026-11-17: one pre-merge browser job.** The maintainer ruled on +[#4163](https://github.com/schlessera/brain-kit/issues/4163) that the browser, +layout and story specs a pull request adds or modifies repeat under CPU load +in the pinned container before it merges +([the gate](#changed-browser-specs-repeat-under-load-before-merge)). The new +`browser_determinism` job is a fast category: ready confirmation, draft and +ready feedback run it when the plan selects it. It runs only the changed +specs. The complete `browser`, `layout`, `captures` and `endurance` suites +stay post-merge, so the reason for the split is unchanged: a suite's latent +timing failure is still found by main, and a changed spec's own race is now +looked for before it gets there. + **What does not change.** No test, assertion, offline boundary, pinned image or category is removed. Main proves every selected category on the combined tree, and a faster merge with unfinished main proof is still not a successful @@ -1773,13 +1785,13 @@ Proof content does not change. run needs no more runners than before. - **One owner.** One table holds both caps (`UNIT_PARTITIONS`, `scripts/proof-shards.ts:17`). The planner reads it by cadence (`unitShards`, - `scripts/ci-plan.ts:406-408`) and publishes the partition numbers as + `scripts/ci-plan.ts:443-445`) and publishes the partition numbers as `unit_shards`. The `unit` matrix is that output, and each partition's divisor is the matrix size. The hosted aggregate plans again and refuses a published set that differs from the plan (`selections.unit`, `scripts/candidate-proof.ts:68`). The merge path accepts only a job inventory that matches the confirmed set, bounded by the confirmation cap - (`unitPartitionLimit("confirmation")`, `scripts/integration-proof.ts:127-128`). + (`unitPartitionLimit("confirmation")`, `scripts/integration-proof.ts:142-143`). `bun run lint` refuses a literal matrix, a second matrix dimension or a literal divisor (`The unit partition count has one owner`, `scripts/check-ci-workflows.ts:100-108`). The weight refresh takes its job @@ -1945,7 +1957,7 @@ 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:318-323`). It runs them in one invocation of the offline + `scripts/ci-plan.ts:355-360`). It runs them in one invocation of the offline wrapper with Bun's `--rerun-each= --bail=1` (`repetitionArgv`, `scripts/test-determinism.ts:53-56`), so the offline preload applies and preparation builds once. One busy loop per CPU runs for the duration. Each @@ -1975,7 +1987,7 @@ test more than once before it merged. - **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:445-457`). This amends "drafts + too (`proofSelections`, `scripts/ci-plan.ts:490-505`). 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 @@ -2030,7 +2042,7 @@ except splitting the change. selection, as before. A selection that fits one job at that count stays one job, and its command and report are unchanged. Otherwise the planner takes the fewest partitions, balanced longest file first, in which every partition - fits the capacity (`planPartitions`, `scripts/determinism-plan.ts:78-99`). + fits the capacity (`planPartitions`, `scripts/determinism-plan.ts:83-105`). Because the budget is the capacity, a selection is only ever split at the floor of two, and each partition is told that count. Every file is in exactly one partition. @@ -2041,16 +2053,16 @@ except splitting the change. The message names the selection's weight and the limit. Nothing is skipped and the count is never reduced below the floor: the change has to be split. - **Wiring.** The planner publishes the partition numbers as - `determinism_shards` (`determinismShards`, `scripts/ci-plan.ts:415-418`). + `determinism_shards` (`determinismShards`, `scripts/ci-plan.ts:452-455`). The `determinism` matrix is that output, and each partition's divisor is the matrix's own job total, so neither is written in the workflow. Each partition's command reads its files from the same plan and refuses a divisor that is not the planned count (`determinismPartition`, - `scripts/ci-proof.ts:22-26`). The hosted aggregate refuses a published set + `scripts/ci-proof.ts:27-31`). The hosted aggregate refuses a published set that differs from the planned one (`validateSelections`, `scripts/candidate-proof.ts:54-71`). The merge path requires one successful `determinism (n)` job for every published number and no other - (`name === "determinism"`, `scripts/integration-proof.ts:129-134`). `bun run lint` refuses a literal + (`name in PLANNED_MATRICES`, `scripts/integration-proof.ts:144-149`). `bun run lint` refuses a literal matrix, a literal divisor, a shared artifact name or a step limit other than the owner's. @@ -2088,8 +2100,9 @@ minutes at 6.84 and 54 at the median, so it never fitted its own step limit; the step limit stays at 40 minutes and the budget drops to the capacity. A test asserts that capacity times the recorded ratio fits the step limit. Ten partitions hold 3,000 weighted seconds at the floor. The largest observed -selection plans nine, and ten keeps a confirmation's job inventory inside the -merge path's bound of 30. +selection plans nine. The merge path bounds a run's job inventory by every +proof job at its widest matrix (`MAX_RUN_JOBS`, `scripts/integration-proof.ts:22`), +so the maximum here and that bound cannot drift apart. **Accepted cost.** Five repetitions now fit only while one pass weighs at most 60 seconds, down from 120. Replaying the same 150 merges with today's weights, @@ -2109,9 +2122,175 @@ recalibrated from the reports then. **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)). +file that leaks state into its next run fails too. Vitest browser, layout and +story specs run in the pinned container and have +[their own gate](#changed-browser-specs-repeat-under-load-before-merge); the +one endurance spec is not repeated. + +## Changed browser specs repeat under load before merge + +The maintainer ruled on 2026-11-17 +([#4163](https://github.com/schlessera/brain-kit/issues/4163)) that a Vitest +browser, layout or story spec a pull request adds or modifies must pass +repeated passes under CPU load, in the pinned container, before it merges. The +ruling follows the +[#4116 measurement spike](https://github.com/schlessera/brain-kit/issues/4116#issuecomment-6943920511) +with one change: a selection too heavy for one job is split across runners by +reviewed weight, as the Bun gate's is. It is not skipped. + +**Why.** Seven of the 14 red-main incidents opened between 2026-11-09 and +2026-11-17 were in `browser` or `layout`, and six of those were cleared by +changing only a test. Under the [hybrid split](#hybrid-post-merge-heavy-proof) +such a spec first ran on a runner after it merged. The spike repeated a spec +with a known race (#3953, its fix reverted in a copy) on a hosted runner: 0 of +8 passes failed without load, 2 of 8 with CPU burners outside the container +and 9 of 16 with burners inside it. A further pass cost the spec's own time, +1.6 to 10.8 seconds, after about 2 minutes 15 seconds of job start-up. + +- **What is selected.** Spec files the change adds or modifies against its + merge base: `*.visual.tsx` under `packages/ui-kit/tests/visual/`, + `*.stories.tsx` under `packages/ui-kit/stories/`, and `*.pointer.tsx`, + `*.layout.tsx` and `*.offline.tsx` under `packages/ui-react/tests/browser/` + (`SPEC_PATTERNS`, `scripts/browser-determinism-plan.ts:32-36`). The one + `*.endurance.tsx` spec stays out: it is real-time media proof with its own + job. A changed helper selects nothing. In the spike's window 21 merges + changed a helper under the spec directories; selecting specs through their + imports would have added none in 15 of them and at most five in the rest, + while one change to the most imported helper would select 27 specs. +- **Pairs, not files.** Vitest runs a file once in every project that includes + it, so each selected file expands to the project/file pairs Vitest's own + file listing reports: three `rail-*` projects for a pointer spec, both + themes for a story, Chromium and WebKit for a diagram spec (`expandSpecs`, + `scripts/browser-determinism-plan.ts:45-54`). The planner reads that listing once + per plan and shares it with category selection (`listBrowserSpecs`, + `scripts/browser-input-closure.ts:242-260`). A changed spec that no project lists, + or a listing that cannot be read, fails the plan: it never becomes an empty + selection. +- **Mechanism: further passes in one Vitest process.** + `bun scripts/browser-determinism.ts` enters the container through + `scripts/visual.mjs`, so the image, mounts and network are the browser + 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 + 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` + and IndexedDB, the Node-side state of browser commands and the Vite server. + That is what two consecutive files of an ordinary run already share. A spec + that leaves state in storage therefore meets it on its next pass, as a Bun + test meets its own `globalThis`. + - **Not `repeats`.** Vitest's `repeats` option reruns a single test inside + one page with every piece of state kept, and the file never reruns as a + unit. A spec that is not idempotent in its own document would fail for a + reason that is not a race. + - **Not a loop of `vitest run`.** Separate invocations give a new browser + each time, at 5 to 6.5 seconds more per repetition by the spike's + derivation, which was never timed. The catch rate and the false-failure + sample were both measured with in-process passes, and only in-process + passes can run exactly the selected pairs: a command line names projects + and files and runs their cross product. +- **One project at a time.** Within a pass the selected projects run one after + another. The spike measured one project per invocation. This gate's first + run of a mixed selection started six projects at once beside four burners, + and a green visual spec failed its first pass with "Could not capture a + stable screenshot within 5000ms". The same selection, one project at a time, + passed five of five passes. One browser beside the burners is the measured + load; every project at once is a heavier one that nothing has measured. +- **Load.** One busy loop per CPU, started inside the container before Vitest + and stopped by PID on every exit path; each exits by itself if its parent + dies (`startBurners`, `scripts/browser-determinism-inside.mjs:47-66`). Inside, not + beside: on a hosted runner the job's processes and the container are two + sibling cgroups of equal weight, so the kernel leaves the container half the + CPUs however many burners run outside it. Burners outside slowed the spike's + four specs 1.25 to 1.37 times and reproduced the #3953 race in 2 of 8 + passes; burners inside slowed them 1.27 to 1.79 times and reproduced it in 9 + of 16. +- **Bounded.** Five repetitions, and two at ready confirmation while the merge + lease is held: the Bun gate's counts. The count is reduced uniformly to no + fewer than two inside a budget of 300 seconds of the reviewed weights in + `scripts/browser-shard-costs.json`. A pair without a weight costs 10 seconds + and the report says so; it is never free. Ten is above three quarters of the + 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, + 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 + ([the pattern](#an-oversized-selection-is-split-by-reviewed-weight)): the + count is decided over the whole selection, a selection over capacity at two + repetitions takes the fewest partitions in which every partition fits, each + pair is in exactly one partition, and a pair that cannot fit runs alone. A + selection that needs more than 15 is refused by the planner in the metadata + job, naming its weight and the limit. Fifteen holds 2,250 weighted seconds + per pass. Of the 38 spec-changing merges in the spike's window, five were + over one job's capacity at two repetitions by the spike's estimate: 178, + 390, 444 and 450 weighted seconds per pass plan two or three partitions, and + the largest, an 89-file change estimated at 1,993, plans 14. +- **Wiring.** The planner publishes `browser_determinism` and + `browser_determinism_shards`. The job's matrix is that output and each + partition's divisor is the matrix's own job total. Each partition's command + reads its pairs from the same plan (`browserDeterminismPartition`, + `scripts/ci-proof.ts:41-45`), the hosted aggregate refuses a published set that + differs from the planned one (`validateSelections`, + `scripts/candidate-proof.ts:54-73`), and the merge path requires one successful + `browser_determinism (n)` job for every published number and no other. + `bun run lint` refuses a literal matrix, a literal divisor, a shared + artifact name or a step limit other than the owner's. +- **Where it is required.** At every pull-request cadence that selects it + (draft, ready `synchronize` feedback and ready confirmation) and in draft + heavy feedback. `draft gates`, `proof` and the merge path require it when + selected and require its intentional skip otherwise. It is a fast category: + it is not in `POST_MERGE_CATEGORIES`. +- **Not on main.** A main push never selects it. The squash's specs were + repeated before they merged, and the main run runs each of them once in + `browser` or `layout`. +- **Not local.** `check:pr` never runs it; `check:pr --plan` names the command + when the change selects it. A deliberate local run takes a host admission + 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 +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. + +**Expected cost.** At the spike's load ratio of 1.8, 300 weighted seconds are +about 9 minutes of passes and about 12 minutes for the job, with its measured +start-up: install 16 seconds, workspace build 94, image pull 17. The median +selection weighed 13 seconds per pass. In three ready confirmations the +slowest job was a `unit` partition at 879 to 981 seconds, so a job capped near +12 minutes should not set the merge lease. The 20-minute step limit leaves +room for a pass that runs slower than its weight. + +**False failures: what was measured.** A gate that fails green specs is worse +than none, so this is the number that matters most and the one known least. + +- The spike repeated 31 project/file pairs from the fourteen most recent + spec-changing merges, two passes each and four more once, under four burners + inside the container: 66 passes on one shared development host, none failed. +- This gate's own local runs, on the same kind of host with the container + pinned to four CPUs, repeated seven pairs (a visual spec, a pointer spec in + three projects, a layout spec and a story in two themes) five times: 35 + passes, none failed. Further passes took 66 to 69 seconds for 52.9 weighted + seconds, a ratio of about 1.3; the first took 103 seconds. +- The one false failure seen is the concurrent-projects run described above, + and it changed the design. + +**Unknown.** + +- The false-failure rate across all specs and on a hosted runner. The two + samples above are about a tenth of the specs, on one kind of host. +- Whether repetition would have caught the other five incidents in the + spike's window. Only #3953 was tried. +- The load ratio on a hosted runner with the refreshed weights. The 1.8 is + the spike's largest ratio for a further pass of one spec; a first pass + carries Vite's cold transforms and ran at 1.9 locally. +- WebKit and the `diagrams-*` projects: no diagram spec was repeated, and + their native artifact preparation adds start-up that was not timed. +- Peak memory, run-to-run variance and whether the runner's cgroup layout is + stable: each was read once or not at all. ## Historical measurement and upstream guidance diff --git a/docs/decisions/feature-captures.md b/docs/decisions/feature-captures.md index cf73bde1f0..271f362bc2 100644 --- a/docs/decisions/feature-captures.md +++ b/docs/decisions/feature-captures.md @@ -42,7 +42,7 @@ content on scrolling screens; that exclusion constrains their alt text. ## Readiness includes the environment that produced the pixels -Use the shared pin (`const IMAGE =`, `scripts/visual.mjs:53`) +Use the shared pin (`const IMAGE =`, `scripts/visual.mjs:54`) and its matching installed dependency. D10's measured rendering differences make a host browser an inadequate replacement for the declared environment. The paper renderer (`async function looksRightOnPaper(`, `packages/ui-kit/tests/visual/subjects.visual.tsx:179-184`) diff --git a/docs/decisions/test-health.md b/docs/decisions/test-health.md index 82d20dc110..baf898fb05 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:367-368`): any path + number of files (`const packageCode`, `scripts/ci-plan.ts:404-405`): 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 fdc37b6a4c..d0e3b465ee 100644 --- a/docs/process/test-authoring.md +++ b/docs/process/test-authoring.md @@ -161,6 +161,17 @@ 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. +A story, a visual baseline, or a pointer, layout or offline spec is checked +the same way: the hosted `browser_determinism` job repeats each added or +modified spec in the pinned container under CPU load, in every Vitest project +that includes it, five times on a draft and twice at ready confirmation +([the gate](testing.md#changed-browser-specs-repeat-under-load)). A spec that +reads a status once instead of waiting for it, or that leaves something in +`localStorage` for its own next pass, fails there. Reproduce a failure with +`bun scripts/browser-determinism.ts --base origin/main`. Changing a helper +repeats nothing, so a wait added to a shared helper is proved by the specs +that are changed with it. + ## 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 57c0059ae9..e63546c2fc 100644 --- a/docs/process/testing.md +++ b/docs/process/testing.md @@ -343,6 +343,64 @@ bun scripts/test-determinism.ts --base origin/main --json # the report on stdo [host admission](#host-admission-for-heavy-local-commands); `--burners ` lowers the load for a diagnosis. +## Changed browser specs repeat under load + +A Vitest browser, layout or story spec that a pull request adds or modifies +runs several times under CPU load, in the pinned container, before it merges +([the 2026-11-17 ruling](../decisions/ci-utility.md#changed-browser-specs-repeat-under-load-before-merge)). +Without this gate such a spec first ran on a runner after it merged. + +```sh +bun scripts/browser-determinism.ts --base origin/main # what the hosted job runs +bun scripts/browser-determinism.ts --base origin/main --cpu-list 0-3 # on a shared host: four CPUs only +bun scripts/browser-determinism.ts --base origin/main --burners 0 # the same passes without load +bun scripts/browser-determinism.ts rail-fine::packages/ui-react/tests/browser/.pointer.tsx # one project/file pair +``` + +Run `bun run build` first, as for any browser run: the container resolves the +packages' built output. + +- **Selection.** `*.visual.tsx` under `packages/ui-kit/tests/visual/`, + `*.stories.tsx` under `packages/ui-kit/stories/`, and `*.pointer.tsx`, + `*.layout.tsx` and `*.offline.tsx` under `packages/ui-react/tests/browser/`, + added or modified against the merge base. Deleted specs, the endurance spec + and helpers are not selected: changing a helper repeats nothing. +- **Pairs.** A spec runs once in every Vitest project that includes it, so it + is repeated as project/file pairs from Vitest's own file listing: a pointer + spec in three `rail-*` projects, a story in both themes. A changed spec that + no project lists fails the plan, because nothing would ever run it. +- **The run.** Vitest starts once in the container and runs exactly the + selected pairs, pass after pass, one project at a time. Each pass opens a + new page for the file and evaluates its module again. The browser, its + storage (cookies, `localStorage`, `sessionStorage`, IndexedDB), the + 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. +- **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 + every added spec is, costs 10 seconds and the report names it. +- **Partitions.** A selection too heavy for one job at two repetitions is + split by reviewed weight into `browser_determinism (1)` to at most + `browser_determinism (15)`, each within 300 weighted seconds. Every pair + runs twice in exactly one partition. A selection that needs more than + fifteen fails in the metadata job before anything runs, naming its weight + and the limit: split the change. `BROWSER_DETERMINISM_PARTITIONS` in + `scripts/proof-shards.ts` owns the numbers. +- **A failure** names the spec, the project, the repetition and the case. + 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. +- **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. + `check:pr` never runs it; `check:pr --plan` prints the command when it + applies. A local run waits for + [host admission](#host-admission-for-heavy-local-commands) like any browser + run. + ## Tests that cannot fail A green test is evidence only if it could have been red. Each of these shapes @@ -695,7 +753,10 @@ in the [CI and merge reference](../../.agents/skills/work-issue/references/ci-an pre-merge proof. - 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)). + ([changed tests repeat under load](#changed-tests-repeat-under-load)) and the + `browser_determinism` job when it adds or modifies a browser, layout or + story spec + ([changed browser specs repeat under load](#changed-browser-specs-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 @@ -770,9 +831,11 @@ 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, 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 +affected tests run. Drafts run cheap gates only, with two exceptions that run +at every pull-request cadence: the `determinism` job repeats a change's added +or modified Bun test files under CPU load, and the `browser_determinism` job +repeats its added or modified browser, layout and story specs in the pinned +container. 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. diff --git a/scripts/browser-determinism-inside.d.mts b/scripts/browser-determinism-inside.d.mts new file mode 100644 index 0000000000..08442f1911 --- /dev/null +++ b/scripts/browser-determinism-inside.d.mts @@ -0,0 +1,23 @@ +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 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. */ +export interface EndedModule { + project: { name: string }; moduleId: string; + ok(): boolean; errors(): { message?: string }[]; + children: { allTests(state?: string): Iterable<{ fullName: string; result(): { errors?: { message?: string }[] } }> }; +} +export interface PassCollector { reporter: { onTestModuleEnd(module: EndedModule): void }; take(): EndedModule[]; } +/** The part of a Vitest instance the runner drives. */ +export interface PassRunner { + globTestSpecifications(): Promise<{ project: { name: string }; moduleId: string }[]>; + runTestSpecifications(specifications: any[], allTestsRun: boolean): Promise<{ unhandledErrors: unknown[] }>; +} +export function burnerSource(parent: number, lifetimeMs?: number): string; +export function startBurners(count: number, lifetimeMs?: number): { pids: number[]; stop(): void }; +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; diff --git a/scripts/browser-determinism-inside.mjs b/scripts/browser-determinism-inside.mjs new file mode 100644 index 0000000000..c0c23e5107 --- /dev/null +++ b/scripts/browser-determinism-inside.mjs @@ -0,0 +1,194 @@ +#!/usr/bin/env node +/** + * The container side of `scripts/browser-determinism.ts` (#4163): repeats the + * selected project/file pairs as further passes in ONE Vitest process, one + * project at a time, while one busy loop per CPU runs beside the browser. + * + * `scripts/visual.mjs --inside --repeat-plan=` starts this file in the + * pinned image in place of `vitest run`, so the container, its mounts and its + * network are exactly the browser suite's. Plain Node ESM for the same reason + * as that launcher: the image supplies Node, not Bun. + * + * Why further passes in one process, and not Vitest's `repeats` option: + * `repeats` reruns a single test inside one page with every piece of state + * kept, so a spec that is not idempotent in its own document fails for a + * reason that is not a race. A further pass reruns the file: Vitest opens a + * new tester iframe, evaluates the module again and reruns `beforeAll`. The + * browser process, its context and storage (cookies, `localStorage`, + * `sessionStorage`, IndexedDB), the Node-side state of browser commands and + * the Vite server carry over, which is what two consecutive files of an + * ordinary run already share. Measured with Vitest 4.1.11 in the #4116 spike; + * policy and evidence: docs/decisions/ci-utility.md, "Changed browser specs + * repeat under load before merge". + * + * Why the burners run here: on a hosted runner the container is its own + * cgroup beside the job's processes, so the kernel halves the CPUs between + * the two groups however many burners run outside. Inside, each burner + * competes with the browser thread for thread. + */ +import { spawn, spawnSync } from "node:child_process"; +import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { availableParallelism } from "node:os"; +import { dirname, relative, resolve } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; + +const REPO = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +export const RESULT_KIND = "brain-browser-determinism-passes"; +/** 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; +const PINNED = "BRAIN_BROWSER_DETERMINISM_PINNED"; + +/** A busy loop that exits by itself once its parent is gone or its lifetime ends. */ +export function burnerSource(parent, lifetimeMs = BURNER_LIFETIME_MS) { + return `const parent=${parent},end=Date.now()+${lifetimeMs};for(;;){const slice=Date.now()+${BURNER_SLICE_MS};while(Date.now()end)process.exit(0);}`; +} + +/** One busy loop per requested CPU. `stop` kills exactly the PIDs started here that are still running. */ +export function startBurners(count, lifetimeMs = BURNER_LIFETIME_MS) { + if (!Number.isSafeInteger(count) || count < 0 || count > 1024) throw new Error("Burners must be a non-negative integer"); + const children = []; + const stop = () => { + for (const child of children.splice(0)) { + // An exited child's PID may already belong to another process. + if (child.exitCode !== null || child.signalCode !== null) continue; + try { process.kill(child.pid, "SIGKILL"); } catch (error) { if (error?.code !== "ESRCH") throw error; } + } + }; + try { + for (let index = 0; index < count; index++) { + const child = spawn(process.execPath, ["-e", burnerSource(process.pid, lifetimeMs)], { stdio: "ignore" }); + if (!Number.isSafeInteger(child.pid)) throw new Error("A CPU burner did not start"); + child.on("error", () => {}); + children.push(child); + } + } catch (error) { stop(); throw error; } + return { pids: children.map(child => child.pid), stop }; +} + +const PROJECT = /^[A-Za-z0-9][A-Za-z0-9-]*$/, PATH = /^[A-Za-z0-9_@.-]+(?:\/[A-Za-z0-9_@.-]+)*$/; +const repositoryPath = value => typeof value === "string" && PATH.test(value) && !value.split("/").some(part => part === ".." || part === "."); + +/** 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; + 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 }; +} + +/** Collects the modules Vitest reports as ended, so a repetition is judged on what ran in it and never on an earlier result. */ +export function passCollector() { + let ended = []; + return { reporter: { onTestModuleEnd(module) { ended.push(module); } }, take() { const modules = ended; ended = []; return modules; } }; +} + +const projectName = name => String(name).replace(/ \((?:chromium|webkit|firefox)\)$/, ""); +const brief = value => String(value ?? "").replace(/\x1b\[[0-9;]*m/g, "").replace(/\s+/g, " ").trim().slice(0, 300); + +function moduleFailure(module) { + for (const test of module.children.allTests("failed")) return { test: test.fullName, detail: brief(test.result().errors?.[0]?.message) }; + return { test: null, detail: brief(module.errors()[0]?.message) || "the file failed outside a test" }; +} + +/** + * Runs every selected pair `repetitions` times, pass after pass, and stops at + * the first failing pass. Within a pass the projects run one after another: + * each browser then competes with the burners alone, which is the load the + * #4116 spike measured. Every selected project at once is a heavier and + * unmeasured load; six of them beside four burners made a green visual spec + * miss its 5 s screenshot deadline on this gate's first mixed run. A pass is + * green only when Vitest reported each selected pair exactly once in that pass + * and every one of them passed. + */ +export async function runPasses({ vitest, collector, pairs, repetitions, repo = REPO, log = console.log, now = () => performance.now() }) { + const key = pair => `${pair.project}::${pair.file}`; + const identify = (project, moduleId) => `${projectName(project.name)}::${relative(repo, moduleId).replaceAll("\\", "/")}`; + const listed = new Map((await vitest.globTestSpecifications()).map(specification => [identify(specification.project, specification.moduleId), specification])); + const unlisted = pairs.filter(pair => !listed.has(key(pair))); + if (unlisted.length) { + return { passes: [], failure: { ...unlisted[0], repetition: null, test: null, reason: "Vitest's own listing has no such project/file pair, so nothing would run" }, alsoFailed: unlisted.slice(1) }; + } + const projects = [...new Set(pairs.map(pair => pair.project))].map(project => pairs.filter(pair => pair.project === project)); + const passes = []; + for (let repetition = 1; repetition <= repetitions; repetition++) { + const started = now(), failed = []; + for (const group of projects) { + collector.take(); + const { unhandledErrors } = await vitest.runTestSpecifications(group.map(pair => listed.get(key(pair))), true); + const ended = collector.take(); + for (const pair of group) { + const modules = ended.filter(module => identify(module.project, module.moduleId) === key(pair)); + if (modules.length !== 1) failed.push({ ...pair, test: null, reason: `Vitest reported ${modules.length} results for this pair in the repetition; a repetition counts only when each pair is reported once` }); + else if (!modules[0].ok()) { const { test, detail } = moduleFailure(modules[0]); failed.push({ ...pair, test, reason: test ? `a test case failed: ${detail}` : detail }); } + } + if (!failed.length && unhandledErrors.length) failed.push({ project: null, file: null, test: null, reason: `${unhandledErrors.length} unhandled error(s) outside a test: ${brief(unhandledErrors[0]?.message ?? unhandledErrors[0])}` }); + // The first failing project ends the repetition: what it leaves behind must not decide the next project's result. + if (failed.length) break; + } + const elapsedSeconds = (now() - started) / 1000; + passes.push({ repetition, elapsedSeconds, ok: !failed.length }); + log(`Repetition ${repetition} of ${repetitions}: ${failed.length ? "FAILED" : "passed"} in ${elapsedSeconds.toFixed(1)} s (${pairs.length} project/file pair(s) in ${projects.length} project(s), one project at a time).`); + if (failed.length) { + const [first, ...rest] = failed; + return { passes, failure: { ...first, repetition }, alsoFailed: rest.map(({ project, file }) => ({ project, file })) }; + } + } + return { passes, failure: null, alsoFailed: [] }; +} + +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"))); + // A shared host confines the browser, Vitest and the burners to the same CPUs, so the load matches a runner of that size. + if (plan.cpuList && process.env[PINNED] !== plan.cpuList) { + const pinned = spawnSync("taskset", ["-c", plan.cpuList, process.execPath, ...process.argv.slice(1)], { stdio: "inherit", env: { ...process.env, [PINNED]: plan.cpuList } }); + if (pinned.error) throw pinned.error; + process.exit(pinned.status ?? 1); + } + // The Storybook plugin registers its stories only under the flag the Vitest CLI sets. + process.env.VITEST ??= "true"; + process.chdir(resolve(REPO, plan.root)); + const log = line => console.log(`[browser-determinism] ${line}`); + const cpus = availableParallelism(), started = performance.now(); + let burners, vitest, exiting = false; + const stopBurners = () => burners?.stop(); + process.on("exit", stopBurners); + for (const [signal, code] of [["SIGINT", 130], ["SIGTERM", 143], ["SIGHUP", 129]]) process.on(signal, () => { stopBurners(); if (!exiting) { exiting = true; process.exit(code); } }); + let outcome; + try { + // Started first: Vitest, Vite and the browser launch under the same load as every pass. + burners = startBurners(plan.burners ?? cpus); + log(`${burners.pids.length} CPU burner(s) on ${cpus} CPU(s)${burners.pids.length ? ` (PIDs ${burners.pids.join(", ")})` : ""}; ${plan.pairs.length} project/file pair(s), ${plan.repetitions} repetition(s) each.`); + const { createVitest } = await import(pathToFileURL(resolve(REPO, "node_modules/vitest/dist/node.js")).href); + 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] }); + await vitest.standalone(); + outcome = await runPasses({ vitest, collector, pairs: plan.pairs, repetitions: plan.repetitions, log }); + } catch (error) { + console.error(error); + outcome = { passes: [], failure: { project: null, file: null, repetition: null, test: null, reason: `the runner stopped before a repetition completed: ${brief(error?.message ?? error)}` }, alsoFailed: [] }; + } finally { + const load = { burners: burners?.pids.length ?? 0, cpus }; + stopBurners(); + const result = { kind: RESULT_KIND, version: 1, pairs: plan.pairs, repetitions: plan.repetitions, load, elapsedSeconds: (performance.now() - started) / 1000, ...outcome }; + mkdirSync(dirname(resolve(REPO, plan.result)), { recursive: true }); + writeFileSync(resolve(REPO, plan.result), JSON.stringify(result, null, 2) + "\n"); + } + const { failure } = outcome; + if (failure) log(`FAILED: ${failure.file ?? "unknown spec"} in project ${failure.project ?? "unknown"}, repetition ${failure.repetition ?? "unknown"} of ${plan.repetitions}${failure.test ? `: ${JSON.stringify(failure.test)}` : ""} (${failure.reason}).`); + else log(`Passed: ${plan.pairs.length} project/file pair(s), ${plan.repetitions} repetition(s) each.`); + // A browser that will not close must not turn a judged result into a hung job. + await Promise.race([vitest?.close().catch(() => {}), new Promise(done => setTimeout(done, 15_000).unref())]); + process.exit(failure ? 1 : 0); +} + +if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + main(process.argv.slice(2)).catch(error => { console.error(error instanceof Error ? error.message : String(error)); process.exit(1); }); +} diff --git a/scripts/browser-determinism-plan.ts b/scripts/browser-determinism-plan.ts new file mode 100644 index 0000000000..4782eed451 --- /dev/null +++ b/scripts/browser-determinism-plan.ts @@ -0,0 +1,121 @@ +/** + * Selection, repetition and partition planning for the hosted `browser_determinism` job (#4163). + * + * Pure: the planner (scripts/ci-plan.ts), each partition's command + * (scripts/ci-proof.ts) and the runner (scripts/browser-determinism.ts) read + * these functions, so they cannot disagree about which specs count, which + * project/file pairs a spec expands to, the repetition count or the partition + * that runs a pair. Counting and partitioning are the Bun gate's + * (scripts/determinism-plan.ts), applied to pairs and browser weights. + * Policy: docs/decisions/ci-utility.md, "Changed browser specs repeat under load before merge". + */ +import { readBrowserCosts } from "./browser-shards"; +import { planPartitions, planRepetitions, repetitionsFor, selectPartition, type PartitionSubject } from "./determinism-plan"; +import { BROWSER_DETERMINISM_PARTITIONS } from "./proof-shards"; + +/** One run of a spec: Vitest runs a file once in every project that includes it. */ +export interface SpecPair { project: string; file: string; } +/** The key `scripts/browser-shard-costs.json` records a pair's weight under. */ +export const pairKey = (pair: SpecPair): string => `${pair.project}::${pair.file}`; +export function parsePairKey(key: string): SpecPair { + const match = /^([A-Za-z0-9][A-Za-z0-9-]*)::([A-Za-z0-9_@.-]+(?:\/[A-Za-z0-9_@.-]+)+)$/.exec(key); + if (!match || match[2]!.split("/").some(part => part === ".." || part === ".")) throw new Error(`Expected ::, received ${JSON.stringify(key)}`); + return { project: match[1]!, file: match[2]! }; +} +const comparePairs = (a: SpecPair, b: SpecPair) => pairKey(a) < pairKey(b) ? -1 : pairKey(a) > pairKey(b) ? 1 : 0; + +/** + * The specs the Vitest projects in `packages/ui-kit/vitest.config.ts` include, + * without the one endurance spec: real-time media proof has its own job. A + * helper beside a spec matches none of these and selects nothing. + */ +const SPEC_PATTERNS: readonly RegExp[] = [ + /^packages\/ui-kit\/tests\/visual\/(?:[^/]+\/)*[^/]+\.visual\.tsx$/, + /^packages\/ui-kit\/stories\/(?:[^/]+\/)*[^/]+\.stories\.tsx$/, + /^packages\/ui-react\/tests\/browser\/(?:[^/]+\/)*[^/]+\.(?:pointer|layout|offline)\.tsx$/, +]; +export const isRepeatedSpec = (path: string): boolean => SPEC_PATTERNS.some(pattern => pattern.test(path)); + +/** + * Each spec as the project/file pairs Vitest's own file listing reports for + * it: three `rail-*` projects for a pointer spec, both themes for a story. A + * spec that no project lists never runs, so repeating it would prove nothing: + * it is refused here, before any runner starts. + */ +export function expandSpecs(files: readonly string[], listing: readonly SpecPair[]): SpecPair[] { + const pairs: SpecPair[] = []; + for (const file of [...new Set(files)].sort()) { + if (!isRepeatedSpec(file)) throw new Error(`Not a browser, layout or story spec the gate repeats: ${file}`); + const listed = listing.filter(spec => spec.file === file); + if (!listed.length) throw new Error(`${file} is a changed spec that no Vitest project lists, so nothing runs it: add it to a project's include in packages/ui-kit/vitest.config.ts`); + pairs.push(...listed.map(spec => ({ project: spec.project, file: spec.file }))); + } + return pairs.sort(comparePairs); +} + +export const DEFAULT_REPETITIONS = 5; +export const FLOOR_REPETITIONS = 2; +/** Five repetitions, and the floor of two at ready confirmation while the merge lease is held: the Bun gate's counts (#4137). */ +export const browserRepetitionsFor = repetitionsFor; +/** Weighted seconds the repetitions may cost before they are reduced: one partition's capacity. */ +export const BROWSER_BUDGET_SECONDS: number = BROWSER_DETERMINISM_PARTITIONS.capacitySeconds; +/** A pair without a reviewed weight is never free: an added spec has none until the table is refreshed. */ +export const UNWEIGHTED_PAIR_SECONDS: number = BROWSER_DETERMINISM_PARTITIONS.unweightedSeconds; +const SUBJECT: PartitionSubject = { proof: "Repeated browser proof", units: "changed project/file pair(s)", unit: "pair", owner: "BROWSER_DETERMINISM_PARTITIONS" }; + +export interface PairRepetitions extends SpecPair { weightSeconds: number; weighted: boolean; repetitions: number; observed?: number; } +export interface BrowserRepetitionPlan { + requested: number; floor: number; repetitions: number; reduced: boolean; + budgetSeconds: number; weightSeconds: number; estimatedSeconds: number; overBudget: boolean; + unweightedSeconds: number; pairs: PairRepetitions[]; +} +export interface PlanOptions { repetitions?: number; budgetSeconds?: number; costs?: Readonly>; unweightedSeconds?: number; } + +let recorded: Readonly> | undefined; +const reviewedCosts = () => recorded ??= readBrowserCosts().seconds; + +function keysOf(pairs: readonly SpecPair[]): string[] { + const keys = pairs.map(pair => pairKey(parsePairKey(pairKey(pair)))); + if (new Set(keys).size !== keys.length) throw new Error("A project/file pair was selected twice"); + return keys.sort(); +} + +/** + * The same count for every pair: 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 planBrowserRepetitions(pairs: readonly SpecPair[], options: PlanOptions = {}): BrowserRepetitionPlan { + const unweightedSeconds = options.unweightedSeconds ?? UNWEIGHTED_PAIR_SECONDS; + const { files, ...plan } = planRepetitions(keysOf(pairs), { repetitions: options.repetitions, budgetSeconds: options.budgetSeconds ?? BROWSER_BUDGET_SECONDS, + costs: options.costs ?? reviewedCosts(), unweightedSeconds }); + return { ...plan, unweightedSeconds, pairs: files.map(({ file, ...entry }) => ({ ...parsePairKey(file), ...entry })) }; +} + +export interface BrowserPartition { pairs: SpecPair[]; weightSeconds: number; estimatedSeconds: number; } +export interface BrowserPartitionPlan extends BrowserRepetitionPlan { capacitySeconds: number; maxPartitions: number; partitions: BrowserPartition[]; } + +/** + * One job while the selection fits one job's capacity at its count; otherwise + * the fewest partitions, balanced heaviest pair first, in which every + * partition fits. Every pair is in exactly one partition, at the count decided + * over the whole selection. A pair cannot be split, so one whose repetitions + * alone exceed the capacity runs in a partition by itself. A selection that + * needs more partitions than the maximum is refused: it is never skipped and + * never reduced below the floor. + */ +export function planBrowserPartitions(pairs: readonly SpecPair[], options: Omit & { cadence?: string; capacitySeconds?: number; maxPartitions?: number } = {}): BrowserPartitionPlan { + const unweightedSeconds = options.unweightedSeconds ?? UNWEIGHTED_PAIR_SECONDS; + const { files, partitions, ...plan } = planPartitions(keysOf(pairs), { cadence: options.cadence, repetitions: options.repetitions, + costs: options.costs ?? reviewedCosts(), unweightedSeconds, subject: SUBJECT, + capacitySeconds: options.capacitySeconds ?? BROWSER_DETERMINISM_PARTITIONS.capacitySeconds, maxPartitions: options.maxPartitions ?? BROWSER_DETERMINISM_PARTITIONS.max }); + return { ...plan, unweightedSeconds, pairs: files.map(({ file, ...entry }) => ({ ...parsePairKey(file), ...entry })), + partitions: partitions.map(partition => ({ pairs: partition.files.map(parsePairKey), weightSeconds: partition.weightSeconds, estimatedSeconds: partition.estimatedSeconds })) }; +} + +/** Partition `M/N` of the plan. `N` must be the planned count, so a matrix or a command that disagrees with the planner runs nothing. */ +export function selectBrowserPartition(plan: BrowserPartitionPlan, shard: string): BrowserPartition { + // The Bun gate's reader validates `M/N` against the planned count; the partition at `M` is this plan's. + const keyed = plan.partitions.map(partition => ({ files: partition.pairs.map(pairKey), weightSeconds: partition.weightSeconds, estimatedSeconds: partition.estimatedSeconds })); + return plan.partitions[keyed.indexOf(selectPartition({ ...plan, files: [], partitions: keyed }, shard))]!; +} diff --git a/scripts/browser-determinism.ts b/scripts/browser-determinism.ts new file mode 100644 index 0000000000..8eed1a66eb --- /dev/null +++ b/scripts/browser-determinism.ts @@ -0,0 +1,228 @@ +/** + * Repeats a change's added or modified Vitest browser, layout and story specs + * under CPU load in the pinned container (#4163). + * + * The Bun gate (scripts/test-determinism.ts, #4109) repeats changed Bun test + * files. These specs run in the pinned Playwright image instead, once, after + * merge; a racy wait in one passes there and fails later on someone else's + * merge. This command runs each changed spec several times before it merges, + * in every project that includes it, while busy loops occupy the container's + * CPUs. + * + * bun scripts/browser-determinism.ts --base origin/main [--json] + * bun scripts/browser-determinism.ts rail-fine::packages/ui-react/tests/browser/a.pointer.tsx ... # explicit pairs (hosted job) + * + * It enters the container through `scripts/visual.mjs`, so the image, mounts + * and network are the browser suite's, and hands it a plan that + * `scripts/browser-determinism-inside.mjs` runs: further passes of exactly the + * selected project/file pairs in one Vitest process, with one burner per CPU + * started inside the container. That file says what a further pass reruns and + * what carries over, and why the burners run inside. + * + * Bounded: five repetitions by default, reduced uniformly to a floor of two + * when the reviewed weights (scripts/browser-shard-costs.json) exceed the + * budget. No selected pair is dropped; a pair without a weight is costed at a + * stated default and the report says so. The count and the hosted partitions + * are planned in scripts/browser-determinism-plan.ts: hosted CI splits a + * selection too heavy for one job across partitions, and each partition runs + * this command with its own pairs. A local `--base` run repeats the whole + * selection in one invocation; `--cpu-list` confines the container's work and + * its burners to a few CPUs of a shared host. + * Policy: docs/decisions/ci-utility.md, "Changed browser specs repeat under load before merge". + */ +import { appendFileSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +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 { RESULT_KIND as PASSES_KIND } from "./browser-determinism-inside.mjs"; +import { browserDeterminismSpecs, changedFiles } from "./ci-plan"; + +export const REPORT_KIND = "brain-browser-determinism"; +/** The gate's own Vitest configuration; `--config-root` names another only for the gate's fixtures. */ +export const CONFIG_ROOT = "packages/ui-kit"; +const PLAN_PATH = "tmp/browser-determinism/plan.json", PASSES_PATH = "tmp/browser-determinism/passes.json"; + +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; + 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 } = {}) { + 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, + burners: options.burners ?? null, cpuList: options.cpuList ?? null }; +} + +/** The launcher's argv: the selected projects decide the container's network and native preparation, as for any browser run. */ +export function launcherArgv(pairs: readonly SpecPair[]): string[] { + return ["node", "scripts/visual.mjs", ...[...new Set(pairs.map(pair => pair.project))].sort().map(project => `--project=${project}`), `--repeat-plan=${PLAN_PATH}`]; +} + +interface PassesResult { kind?: unknown; version?: unknown; pairs?: unknown; repetitions?: unknown; passes?: unknown; failure?: unknown; alsoFailed?: unknown; load?: { burners?: unknown; cpus?: unknown } } + +/** + * The container's verdict, judged again on the host. A green run is evidence + * only if the result names this plan's pairs and shows every repetition + * passing; a missing, foreign or short result is a failure whatever the exit code. + */ +export function judge(plan: BrowserRepetitionPlan, result: PassesResult | undefined, exitCode: number): { failure: Failure | null; alsoFailed: SpecPair[]; passes: Pass[]; load: { burners: number; cpus: number | null } } { + const none = { alsoFailed: [], passes: [], load: { burners: 0, cpus: null } }; + const anonymous = (reason: string): Failure => ({ file: null, project: null, repetition: null, test: null, reason }); + if (!result || result.kind !== PASSES_KIND || result.version !== 1 || !Array.isArray(result.passes) || !Array.isArray(result.pairs)) { + return { ...none, failure: anonymous(`the pinned container exited ${exitCode} without a readable repetition result`) }; + } + const passes = (result.passes as Pass[]).map(pass => ({ repetition: Number(pass.repetition), elapsedSeconds: Number(pass.elapsedSeconds), ok: pass.ok === true })); + const load = { burners: Number(result.load?.burners ?? 0), cpus: Number.isSafeInteger(result.load?.cpus) ? Number(result.load!.cpus) : null }; + const alsoFailed = Array.isArray(result.alsoFailed) ? (result.alsoFailed as SpecPair[]).filter(pair => pair?.project && pair?.file).map(({ project, file }) => ({ project, file })) : []; + const ran = JSON.stringify((result.pairs as SpecPair[]).map(pairKey).sort()), planned = JSON.stringify(plan.pairs.map(pairKey).sort()); + if (ran !== planned || result.repetitions !== plan.repetitions) return { passes, load, alsoFailed, failure: anonymous("the container's result names another selection or repetition count than this plan") }; + const reported = result.failure as Partial | null | undefined; + if (reported) { + return { passes, load, alsoFailed, failure: { file: reported.file ?? null, project: reported.project ?? null, + repetition: Number.isSafeInteger(reported.repetition) ? reported.repetition! : null, test: reported.test ?? null, reason: String(reported.reason ?? "a repetition failed") } }; + } + const green = passes.filter(pass => pass.ok).length; + if (passes.length !== plan.repetitions || green !== plan.repetitions || passes.some((pass, index) => pass.repetition !== index + 1)) { + return { passes, load, alsoFailed, failure: anonymous(`ran ${green} of ${plan.repetitions} repetitions according to the container's result; a passing run must show every repetition`) }; + } + if (exitCode !== 0) return { passes, load, alsoFailed, failure: anonymous(`the pinned container exited ${exitCode} after reporting every repetition green`) }; + return { passes, load, alsoFailed, failure: null }; +} + +export interface RunOptions extends PlanOptions { + root: string; pairs: readonly SpecPair[]; base?: string | null; configRoot?: string; burners?: number; cpuList?: string; + 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; +} + +function describePlan(plan: BrowserRepetitionPlan, burners: number | undefined): string[] { + const lines = [`Repeating ${plan.pairs.length} changed project/file pair(s) ${plan.repetitions} time(s) each in the pinned container under ` + + `${burners === undefined ? "one CPU burner per CPU" : `${burners} CPU burner(s)`}: ${plan.weightSeconds.toFixed(1)} weighted s per pass, ` + + `${plan.estimatedSeconds.toFixed(1)} s estimated, budget ${plan.budgetSeconds} s.`]; + if (plan.reduced) lines.push(`Reduced from ${plan.requested} to ${plan.repetitions} repetitions: ${plan.requested} would cost ` + + `${(plan.weightSeconds * plan.requested).toFixed(1)} weighted s against the ${plan.budgetSeconds} s budget.`); + if (plan.overBudget) lines.push(`Over budget at the floor of ${plan.floor}: every pair still runs ${plan.repetitions} times.`); + for (const entry of plan.pairs) lines.push(` ${entry.repetitions}x ${entry.project} ${entry.file} (${entry.weighted ? `weight ${entry.weightSeconds}s` : `no reviewed weight: costed at the ${plan.unweightedSeconds}s default`})`); + return lines; +} + +async function launchInherited(argv: string[], cwd: string, env: Record): Promise { + const child = Bun.spawn(argv, { cwd, env, stdin: "ignore", stdout: "inherit", stderr: "inherit" }); + const signals = ["SIGINT", "SIGTERM", "SIGHUP"] as const; + // The launcher forwards a signal to its container run; this process then reports the interruption. + const listeners = signals.map(signal => () => { child.kill(signal); }); + signals.forEach((signal, index) => process.on(signal, listeners[index]!)); + try { + const code = await child.exited; + return child.signalCode ? 128 + (constants.signals[child.signalCode] ?? 0) : code; + } finally { signals.forEach((signal, index) => process.off(signal, listeners[index]!)); } +} + +/** Plans the selection, runs it in the pinned container and returns its report. */ +export async function runBrowserDeterminism(options: RunOptions): Promise { + const { root } = options, log = options.log ?? (line => console.error(line)); + const configRoot = options.configRoot ?? CONFIG_ROOT; + 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 }; + 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 }; + } + 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 }); + writeFileSync(join(root, PLAN_PATH), JSON.stringify(passPlan(plan, options), null, 2) + "\n"); + const started = performance.now(); + const exitCode = await (options.launch ?? launchInherited)(launcherArgv(plan.pairs), root, { ...process.env, ...options.env }); + const elapsedSeconds = (performance.now() - started) / 1000; + let result: PassesResult | undefined; + try { result = JSON.parse(readFileSync(join(root, PASSES_PATH), "utf8")); } catch {} + const verdict = judge(plan, result, exitCode); + const report: Report = { ...base, outcome: verdict.failure ? "failed" : "passed", failure: verdict.failure, alsoFailed: verdict.alsoFailed, passes: verdict.passes, + load: { ...verdict.load, inside: "pinned container" }, elapsedSeconds, exitCode: verdict.failure ? (exitCode || 1) : 0 }; + const { failure } = report; + if (failure) { + log(`FAILED: ${failure.file ?? "unknown spec"} in project ${failure.project ?? "unknown"}, repetition ${failure.repetition ?? "unknown"} of ${plan.repetitions}` + + `${failure.test ? `: ${JSON.stringify(failure.test)}` : ""} (${failure.reason}).`); + log("A changed spec must pass every repetition. Fix the spec or what it exposes; a rerun is not a fix."); + } else log(`Passed: ${plan.pairs.length} project/file pair(s), ${plan.repetitions} repetition(s) each, ${elapsedSeconds.toFixed(1)} s including the container start.`); + return report; +} + +/** A Markdown table for the hosted job summary: each pair with the repetitions it got. */ +export function summaryMarkdown(report: Report): string { + const lines = [`### Changed browser specs under CPU load: ${report.outcome}`, ""]; + 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.`, ""); + 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("`", "'")}).`, ""); + lines.push("| Project | Spec | Reviewed weight (s) | Repetitions |", "| --- | --- | --- | --- |"); + for (const entry of report.pairs) lines.push(`| \`${entry.project}\` | \`${entry.file}\` | ${entry.weighted ? entry.weightSeconds : `none (${report.unweightedSeconds} default)`} | ${entry.repetitions} |`); + if (report.passes.length) lines.push("", `Pass seconds: ${report.passes.map(pass => `${pass.elapsedSeconds.toFixed(1)}${pass.ok ? "" : " (failed)"}`).join(", ")}.`); + return lines.concat("").join("\n"); +} + +const USAGE = "usage: bun scripts/browser-determinism.ts (--base | ::...) [--json] [--report ] [--repetitions ] [--budget-seconds ] [--burners ] [--cpu-list ] [--config-root ]"; + +export interface Arguments { base?: string; pairs: SpecPair[]; json: boolean; report?: string; repetitions?: number; budgetSeconds?: number; burners?: number; cpuList?: string; configRoot?: string; } + +export function parseArguments(args: readonly string[]): Arguments { + const parsed: Arguments = { pairs: [], json: false }; + const integer = (name: string, value: string | undefined, least: number) => { + if (!value || !/^(?:0|[1-9]\d{0,6})$/.test(value) || Number(value) < least) throw new Error(`${name} needs an integer of at least ${least}\n${USAGE}`); + return Number(value); + }; + for (let index = 0; index < args.length; index++) { + const [flag, inline] = args[index]!.startsWith("--") ? args[index]!.split(/=(.*)/s, 2) as [string, string | undefined] : [args[index]!, undefined]; + const value = () => inline ?? args[++index]; + if (flag === "--json" && inline === undefined) parsed.json = true; + else if (flag === "--base") { parsed.base = value(); if (!parsed.base) throw new Error(`--base needs a ref\n${USAGE}`); } + 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); + // 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}`); } + else if (flag === "--config-root") { parsed.configRoot = value(); if (!parsed.configRoot || !/^[A-Za-z0-9_@.-]+(?:\/[A-Za-z0-9_@.-]+)*$/.test(parsed.configRoot) || parsed.configRoot.split("/").includes("..")) throw new Error(`--config-root needs a repository directory\n${USAGE}`); } + else if (flag.startsWith("-")) throw new Error(`Unknown option ${flag}\n${USAGE}`); + else { try { parsed.pairs.push(parsePairKey(flag)); } catch (error) { throw new Error(`${(error as Error).message}\n${USAGE}`); } } + } + if ((parsed.base === undefined) === (parsed.pairs.length === 0)) throw new Error(`Name either --base or the project/file pairs to repeat\n${USAGE}`); + return parsed; +} + +if (import.meta.main) { + try { + const root = resolve(import.meta.dir, ".."); + const args = parseArguments(process.argv.slice(2)); + let pairs = args.pairs; + if (args.base !== undefined) { + const specs = browserDeterminismSpecs(root, changedFiles(root, args.base, "HEAD", true, true)); + pairs = specs.length ? expandSpecs(specs, listBrowserSpecs(root)) : []; + } + // 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, + ...(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 }); + writeFileSync(resolve(root, args.report), JSON.stringify(report, null, 2) + "\n"); + } + if (process.env.GITHUB_STEP_SUMMARY) appendFileSync(process.env.GITHUB_STEP_SUMMARY, summaryMarkdown(report)); + if (args.json) console.log(JSON.stringify(report)); + process.exit(report.exitCode); + } catch (error) { + console.error(error instanceof Error ? error.message : String(error)); + process.exit(1); + } +} diff --git a/scripts/browser-input-closure.ts b/scripts/browser-input-closure.ts index d608c05503..857456dabb 100644 --- a/scripts/browser-input-closure.ts +++ b/scripts/browser-input-closure.ts @@ -232,8 +232,34 @@ export function closureSelects(changed: readonly string[], closure: InputClosure } export type BrowserClosures = Record; +const LISTING_FAILURES = ["Installed Vitest discovery failed", "Unknown browser project selection", "Incomplete browser project discovery"]; +/** + * The installed runner's own file listing as project/file pairs, complete over + * every project `scripts/visual.mjs` runs. Throws when it cannot be + * established: category selection then stays broad, and a planner that needs + * the pairs (scripts/ci-plan.ts, #4163) fails instead of guessing them. + */ +export function listBrowserSpecs(root: string): Spec[] { + const output = join(root, "tmp", `browser-selection-${process.pid}.json`); + mkdirSync(dirname(output), { recursive: true }); + rmSync(output, { force: true }); + try { + // File discovery must not retain the child for unawaited Storybook telemetry retries. + const command = Bun.spawnSync(["node", "../../node_modules/vitest/vitest.mjs", "list", "--filesOnly", `--json=${output}`], { + cwd: join(root, "packages/ui-kit"), env: { ...process.env, CI: "true", STORYBOOK_DISABLE_TELEMETRY: "1" }, stdout: "pipe", stderr: "pipe", timeout: 15000, + }); + if (command.exitCode !== 0) throw new Error(LISTING_FAILURES[0]); + const specs = normalizeInventory(JSON.parse(readFileSync(output, "utf8")), root); + const declaration = /const projects = projectArgs\.length \?[^\n]+ : (\[[^\n]+\]);/.exec(readFileSync(join(root, "scripts/visual.mjs"), "utf8")); + if (!declaration) throw new Error(LISTING_FAILURES[1]); + const expected = [...JSON.parse(declaration[1]!), "ui-react-layout", "ui-react-endurance"].sort(); + const actual = [...new Set(specs.map(spec => spec.project))].sort(); + if (new Set(expected).size !== expected.length || JSON.stringify(actual) !== JSON.stringify(expected)) throw new Error(LISTING_FAILURES[2]); + return specs; + } finally { rmSync(output, { force: true }); } +} /** Use the installed runner's actual file discovery; a failure leaves every category broad. */ -export function discoverBrowserClosures(root: string): BrowserClosures { +export function discoverBrowserClosures(root: string, list: (root: string) => Spec[] = listBrowserSpecs): BrowserClosures { const declarations = (file: string): InputDeclaration[] => { const data = JSON.parse(readFileSync(join(root, file), "utf8")); if (!Array.isArray(data)) throw new Error("Invalid indirect-input declarations"); @@ -244,26 +270,11 @@ export function discoverBrowserClosures(root: string): BrowserClosures { let captures: InputClosure; try { captures = discoverInputClosure(root, ["scripts/capture.ts", "scripts/captures", "docs/process/feature-captures.md", ...cssConfig], [...declarations("scripts/captures/proof-inputs.json"), ...cssDeclarations()]); } catch { captures = { files: [], unresolved: ["Cannot establish capture input ownership"] }; } - const output = join(root, "tmp", `browser-selection-${process.pid}.json`); - mkdirSync(dirname(output), { recursive: true }); - rmSync(output, { force: true }); const failed = (message: string): BrowserClosures => Object.fromEntries( ["browser", "layout", "endurance", "captures"].map(category => [category, category === "captures" ? captures : { files: [], unresolved: [message] }])) as unknown as BrowserClosures; let specs: Spec[]; - try { - // File discovery must not retain the child for unawaited Storybook telemetry retries. - const command = Bun.spawnSync(["node", "../../node_modules/vitest/vitest.mjs", "list", "--filesOnly", `--json=${output}`], { - cwd: join(root, "packages/ui-kit"), env: { ...process.env, CI: "true", STORYBOOK_DISABLE_TELEMETRY: "1" }, stdout: "pipe", stderr: "pipe", timeout: 15000, - }); - if (command.exitCode !== 0) return failed("Installed Vitest discovery failed"); - specs = normalizeInventory(JSON.parse(readFileSync(output, "utf8")), root); - const declaration = /const projects = projectArgs\.length \?[^\n]+ : (\[[^\n]+\]);/.exec(readFileSync(join(root, "scripts/visual.mjs"), "utf8")); - if (!declaration) return failed("Unknown browser project selection"); - const expected = [...JSON.parse(declaration[1]!), "ui-react-layout", "ui-react-endurance"].sort(); - const actual = [...new Set(specs.map(spec => spec.project))].sort(); - if (new Set(expected).size !== expected.length || JSON.stringify(actual) !== JSON.stringify(expected)) return failed("Incomplete browser project discovery"); - } catch { return failed("Installed Vitest discovery unavailable"); } - finally { rmSync(output, { force: true }); } + try { specs = list(root); } + catch (error) { return failed(error instanceof Error && LISTING_FAILURES.includes(error.message) ? error.message : "Installed Vitest discovery unavailable"); } try { const visualDeclarations = [...declarations("packages/ui-kit/tests/proof-inputs.json"), ...cssDeclarations()]; const config = [...cssConfig, "packages/ui-kit/tests/proof-inputs.json", "packages/ui-kit/vitest.config.ts", "packages/ui-kit/vite.config.ts", "packages/ui-kit/.storybook/main.ts", "packages/ui-kit/.storybook/preview.ts"]; diff --git a/scripts/candidate-proof.ts b/scripts/candidate-proof.ts index 56d63ac0c4..ecd003477b 100644 --- a/scripts/candidate-proof.ts +++ b/scripts/candidate-proof.ts @@ -1,5 +1,5 @@ /** Exact merge-candidate validation; feedback never authorizes merging. */ -import { determinismShards, planFromEnvironment, proofCadence, proofSelections, redMainSnapshot, unitShards } from "./ci-plan"; +import { browserDeterminismShards, determinismShards, planFromEnvironment, proofCadence, proofSelections, redMainSnapshot, unitShards } from "./ci-plan"; import type { RedMainRecord } from "./red-main"; import { checkout, type Checkout } from "./proof-inputs"; import { GitHubProofAPI, type API } from "./proof-api"; @@ -68,6 +68,8 @@ export function validateSelections(root: string, event: any, env: NodeJS.Process if (selections.unit && outputs?.unit_shards !== JSON.stringify(unitShards(plan))) throw new Error("unit: published partition set differs from the planned one"); // A dropped or added partition would leave a selected file unrepeated, or repeat one the plan put elsewhere (#4117). if (selections.determinism && outputs?.determinism_shards !== JSON.stringify(determinismShards(plan))) throw new Error("determinism: published partition set differs from the planned one"); + // The same for changed browser specs: every pair runs in exactly one published partition (#4163). + if (selections.browser_determinism && outputs?.browser_determinism_shards !== JSON.stringify(browserDeterminismShards(plan))) throw new Error("browser_determinism: published partition set differs from the planned one"); } export async function requireCandidate(root: string, event: any, env: NodeJS.ProcessEnv): Promise { diff --git a/scripts/check-ci-workflows.ts b/scripts/check-ci-workflows.ts index ce379668de..d93d3f36ed 100644 --- a/scripts/check-ci-workflows.ts +++ b/scripts/check-ci-workflows.ts @@ -1,7 +1,7 @@ /** GitHub is the sole CI provider; contributions share read-only workflows. */ import { existsSync, readFileSync, readdirSync } from "node:fs"; import { join, resolve } from "node:path"; -import { DETERMINISM_PARTITIONS, PROOF_SHARDS, shardNumbers, type ShardedDomain } from "./proof-shards"; +import { BROWSER_DETERMINISM_PARTITIONS, DETERMINISM_PARTITIONS, PROOF_SHARDS, shardNumbers, type ShardedDomain } from "./proof-shards"; import { FEEDBACK_AGGREGATE } from "./heavy-feedback"; import { CATEGORY_JOBS, FEEDBACK_GROUP, renderHeavyFeedbackWorkflow, sameWorkflow } from "./heavy-feedback-workflow"; import { actionPinProblems, pinned } from "./action-pins"; @@ -33,7 +33,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", "determinism", "endurance", "layout", "pack", "proof", "runtime", "runtime_host", "unit", "verify"] : ["contract"]; + const expectedJobs = file === "ci.yml" ? ["browser", "browser_determinism", "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`); @@ -53,7 +53,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", "determinism"]; + const names = ["verify", "pack", "unit", "runtime", "runtime_host", "browser", "layout", "captures", "endurance", "determinism", "browser_determinism"]; for (const name of names) { const job = workflow.jobs?.[name]; if (job?.needs !== "changeset") fail(`${name}: independent proof must depend only on metadata`); @@ -116,11 +116,23 @@ export function workflowProblems(text: string, file: string): string[] { determinismProof?.env?.DETERMINISM_SHARDS !== "${{ strategy.job-total }}") fail("determinism: matrix and shard divisor must come from the planner's determinism_shards output"); // One artifact name per partition: a shared name fails every upload after the first. if (!determinism?.steps?.some((step: Step) => step.uses?.startsWith("actions/upload-artifact@") && step.with?.name === "determinism-proof-${{ matrix.shard }}")) fail("determinism: each partition must upload its own receipts"); + // Changed browser specs repeat in planned partitions too, under the same one-owner rule (#4163): + // the matrix is the planner's output, the divisor is the matrix's own job total, and the step limit is the table's. + const repeat = workflow.jobs?.browser_determinism as any; + const repeatProof = repeat?.steps?.find((step: Step) => step.run?.startsWith("bun scripts/ci-proof.ts browser_determinism")); + if (changeset?.outputs?.browser_determinism_shards !== "${{ steps.plan.outputs.browser_determinism_shards }}" || + JSON.stringify(repeat?.strategy?.matrix) !== JSON.stringify({ shard: "${{ fromJSON(needs.changeset.outputs.browser_determinism_shards) }}" }) || + repeatProof?.run !== 'bun scripts/ci-proof.ts browser_determinism --shard=${{ matrix.shard }}/"$BROWSER_REPEAT_SHARDS"' || + repeatProof?.env?.BROWSER_REPEAT_SHARDS !== "${{ strategy.job-total }}") fail("browser_determinism: matrix and shard divisor must come from the planner's browser_determinism_shards output"); + if (repeatProof?.["timeout-minutes"] !== BROWSER_DETERMINISM_PARTITIONS.stepMinutes) fail(`browser_determinism: proof must retain its ${BROWSER_DETERMINISM_PARTITIONS.stepMinutes}-minute limit`); + const repeatLimit = repeat?.["timeout-minutes"]; + if (typeof repeatLimit !== "number" || !Number.isInteger(repeatLimit) || repeatLimit < BROWSER_DETERMINISM_PARTITIONS.stepMinutes + 5) fail("browser_determinism: job limit must cover proof and 5 minutes of other steps"); + if (!repeat?.steps?.some((step: Step) => step.uses?.startsWith("actions/upload-artifact@") && step.with?.name === "browser-determinism-proof-${{ matrix.shard }}")) fail("browser_determinism: each partition must upload its own receipts"); const proof = workflow.jobs?.proof; 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", "determinism"]) { + for (const category of ["unit", "runtime", "runtime_host", "browser", "layout", "captures", "endurance", "determinism", "browser_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 3d98b97d69..7c2f2555e1 100644 --- a/scripts/check-pr.ts +++ b/scripts/check-pr.ts @@ -77,6 +77,15 @@ export function determinismCommand(plan: CheckPlan, base: string): string | unde return plan.determinism?.length ? `bun scripts/test-determinism.ts --base ${base}` : undefined; } +/** + * The same for a plan that changes Vitest browser, layout or story specs + * (#4163): the hosted `browser_determinism` job repeats them in the pinned + * container, with every CPU of that container occupied. + */ +export function browserDeterminismCommand(plan: CheckPlan, base: string): string | undefined { + return plan.browserDeterminism?.length ? `bun scripts/browser-determinism.ts --base ${base}` : undefined; +} + class SandboxSetupTimeout extends Error {} /** The fastest of three sandbox setup probes must take less than this. */ @@ -277,7 +286,9 @@ if (import.meta.main) { console.log(JSON.stringify({ ...plan, commands: plannedCommands.map(command => command.name), commandDetails: plannedCommands, 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)); + determinismNote: "not run locally: it occupies every CPU; the hosted determinism job repeats these files under load" } : {}), + ...(browserDeterminismCommand(plan, base) ? { browserDeterminismCommand: browserDeterminismCommand(plan, base), + browserDeterminismNote: "not run locally: it occupies every CPU of the pinned container; the hosted browser_determinism job repeats these specs 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 6eec1bd8c3..98acfbfa52 100644 --- a/scripts/ci-plan.ts +++ b/scripts/ci-plan.ts @@ -2,12 +2,13 @@ import { appendFileSync, existsSync, readFileSync, readdirSync, readlinkSync, lstatSync, realpathSync } from "node:fs"; import { basename, dirname, join, relative, resolve } from "node:path"; import ts from "typescript"; -import { closureSelects, discoverBrowserClosures, type BrowserClosures } from "./browser-input-closure"; +import { closureSelects, discoverBrowserClosures, listBrowserSpecs, type BrowserClosures } from "./browser-input-closure"; import { addUnitImportConsumers, type UnitImportGraph } from "./unit-test-consumers"; import { coordinationFiles, RESERVATION_REF } from "./integration-reservation"; import { includeRedSet, isPostMerge, type Category, type IncludedRedSet, type RedMainRecord } from "./red-main"; import { unitPartitions } from "./proof-shards"; import { planPartitions } from "./determinism-plan"; +import { expandSpecs, isRepeatedSpec, planBrowserPartitions, type SpecPair } from "./browser-determinism-plan"; export interface Workspace { dir: string; @@ -146,6 +147,11 @@ export interface CheckPlan { redMain?: IncludedRedSet; /** Bun test files a pull request adds or modifies; each repeats under CPU load before merge (#4109). */ determinism?: string[]; + /** + * The project/file pairs of the Vitest browser, layout and story specs a pull request adds or + * modifies; each repeats under CPU load in the pinned container before merge (#4163). + */ + browserDeterminism?: SpecPair[]; } export function workspaces(root: string): Workspace[] { @@ -300,14 +306,45 @@ export function independentTests(root: string, changed: readonly string[]): stri } catch { return undefined; } } -export function planChecks(changed: readonly string[], packages: readonly Workspace[], root = resolve(import.meta.dir, ".."), enableConsumerSelection = true): CheckPlan { +export function planChecks(changed: readonly string[], packages: readonly Workspace[], root = resolve(import.meta.dir, ".."), enableConsumerSelection = true, + listSpecs: (root: string) => SpecPair[] = listBrowserSpecs): CheckPlan { // 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); - const selected = explicitRoot && !plan.global ? selectBrowserClosures(plan, discoverBrowserClosures(root)) : plan; + // Category selection and spec repetition read one listing: Vitest lists its files once per plan. + let listing: SpecPair[] | undefined, unavailable: unknown; + const list = (from: string) => { + if (!listing && unavailable === undefined) { try { listing = listSpecs(from); } catch (error) { unavailable = error ?? new Error("Vitest file listing failed"); } } + if (!listing) throw unavailable; + return listing; + }; + const selected = explicitRoot && !plan.global ? selectBrowserClosures(plan, discoverBrowserClosures(root, list)) : 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; + const specs = explicitRoot && enableConsumerSelection ? browserDeterminismSpecs(root, changed) : []; + return { ...selected, ...(determinism.length ? { determinism } : {}), ...(specs.length ? { browserDeterminism: browserDeterminismPairs(specs, () => list(root)) } : {}) }; +} + +/** + * The Vitest browser, layout and story specs among `changed` that exist in + * this checkout: what a change adds or modifies, never what it deletes + * (#4163). `isRepeatedSpec` (scripts/browser-determinism-plan.ts) owns the + * patterns; a changed helper matches none of them. + */ +export function browserDeterminismSpecs(root: string, changed: readonly string[]): string[] { + return [...new Set(changed)].filter(path => isRepeatedSpec(path) && lstatSync(join(root, path), { throwIfNoEntry: false })?.isFile() === true).sort(); +} + +/** + * Each changed spec as the project/file pairs Vitest's own listing reports + * for it. A listing that cannot be established is an error, never an empty + * selection: a changed spec must not skip its repetitions silently. + */ +export function browserDeterminismPairs(specs: readonly string[], list: () => SpecPair[]): SpecPair[] { + let listing: SpecPair[]; + try { listing = list(); } + catch (error) { throw new Error(`Cannot expand ${specs.length} changed browser spec(s) to project/file pairs: ${error instanceof Error ? error.message : String(error)}`); } + return expandSpecs(specs, listing); } /** @@ -417,6 +454,14 @@ export function determinismShards(plan: CheckPlan): number[] { return planPartitions(plan.determinism!, { cadence: plan.cadence }).partitions.map((_, index) => index + 1); } +/** Partition numbers the `browser_determinism` matrix runs (#4163), by the same rule as + * `determinismShards`: the planned partitions of a selected plan, and one number for an + * unselected one. A selection beyond the maximum throws here, in the metadata job. */ +export function browserDeterminismShards(plan: CheckPlan): number[] { + if (!proofSelections(plan).browser_determinism) return [1]; + return planBrowserPartitions(plan.browserDeterminism!, { cadence: plan.cadence }).partitions.map((_, index) => index + 1); +} + export type ProofCadence = "draft" | "feedback" | "feedback-heavy" | "confirmation" | "integrated" | "exhaustive"; /** A draft heavy feedback dispatch names its PR and head; ci.yml's bare dispatch declares no inputs. */ @@ -448,12 +493,15 @@ export function proofSelections(plan: CheckPlan, draft = false): Record 0; + const premerge = !["integrated", "exhaustive"].includes(plan.cadence ?? ""); + const determinism = premerge && (plan.determinism?.length ?? 0) > 0; + // Changed Vitest specs repeat in the pinned container at the same cadences (2026-11-17 ruling, #4163). + const browser_determinism = premerge && (plan.browserDeterminism?.length ?? 0) > 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])), determinism }; + }).map(([name, selected]) => [name, !draft && !(confirmation && isPostMerge(name as Category)) && selected])), determinism, browser_determinism }; } function git(root: string, args: string[]): string { @@ -521,6 +569,7 @@ if (import.meta.main) { const selections = proofSelections(plan, draft); if (process.env.GITHUB_OUTPUT) appendFileSync(process.env.GITHUB_OUTPUT, `unit_shards=${JSON.stringify(unitShards(plan))}\n` + `determinism_shards=${JSON.stringify(determinismShards(plan))}\n` + + `browser_determinism_shards=${JSON.stringify(browserDeterminismShards(plan))}\n` + `cadence=${plan.cadence ?? "diagnostic"}\n` + `red_main_oid=${red?.oid ?? ""}\n` + Object.entries(selections).map(([name, selected]) => `${name}=${selected}\n`).join("")); console.log(JSON.stringify({ ...plan, draft, event: event && { name: process.env.GITHUB_EVENT_NAME, action: event.action, diff --git a/scripts/ci-proof.ts b/scripts/ci-proof.ts index 9ce22b5cd2..5a6fdfbce8 100644 --- a/scripts/ci-proof.ts +++ b/scripts/ci-proof.ts @@ -8,13 +8,18 @@ import { runCommands, type Command } from "./ci-runner"; import type { CheckPlan } from "./ci-plan"; import { balanceTests, discoverTests } from "./test-shards"; import { planPartitions, repetitionsFor, selectPartition, type DeterminismPartition, type PartitionPlan } from "./determinism-plan"; +import { browserRepetitionsFor, pairKey, planBrowserPartitions, selectBrowserPartition, type BrowserPartition, type BrowserPartitionPlan } from "./browser-determinism-plan"; import { resolveBrowserPin } from "./captures/provenance"; import { startUnitMemorySampler } from "./unit-memory"; import { diskSampler, floorProblem } from "./ci-disk"; -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 PROOF_JOBS = ["verify", "pack", "unit", "browser", "layout", "captures", "runtime", "runtime_host", "endurance", "determinism", "browser_determinism"] as const; +export const PROOF_CATEGORIES = ["unit", "browser", "layout", "captures", "runtime", "runtime_host", "endurance", "determinism", "browser_determinism"] as const; +export type ProofCategory = typeof PROOF_CATEGORIES[number]; export const DETERMINISM_REPORT = "tmp/determinism-report.json"; +export const BROWSER_DETERMINISM_REPORT = "tmp/browser-determinism-report.json"; +/** Bun tests that start the pinned image with `--pull=never`: a partition holding one pulls the image first. */ +export const PINNED_IMAGE_TESTS = ["tests/workspace-lease.test.ts", "tests/browser-determinism-container.test.ts"] as const; /** One partition of the planner's added or modified Bun test files, at the count decided over the * whole selection (#4117). An empty selection is never a job (#4109), and a shard divisor that is @@ -30,6 +35,20 @@ export function determinismFiles(plan: CheckPlan, shard?: string): string[] { return [...determinismPartition(plan, shard).partition.files]; } +/** One partition of the planner's changed browser, layout and story spec pairs, at the count decided + * over the whole selection (#4163). The Bun gate's rules: an empty selection is never a job, and a + * shard divisor that is not the planned partition count is refused. */ +export function browserDeterminismPartition(plan: CheckPlan, shard = "1/1"): { selection: BrowserPartitionPlan; partition: BrowserPartition } { + if (!plan.browserDeterminism?.length) throw new Error("Repeated browser proof was not selected"); + const selection = planBrowserPartitions(plan.browserDeterminism, { cadence: plan.cadence }); + return { selection, partition: selectBrowserPartition(selection, shard) }; +} + +/** The `project::file` pairs partition `shard` repeats: every selected pair is in exactly one planned partition. */ +export function browserDeterminismPairs(plan: CheckPlan, shard?: string): string[] { + return browserDeterminismPartition(plan, shard).partition.pairs.map(pairKey); +} + /** Aggregate requires passed selected jobs; missing/false-looking output is not proof. * Every selected category runs fresh: a skipped selected job never passes (#4107). */ export function proofProblems(needs: Record }>): string[] { @@ -78,7 +97,17 @@ export function categoryCommands(category: ProofCategory, plan: CheckPlan, root: ...(repetitions === undefined ? [] : [`--repetitions=${repetitions}`]), ...partition.files], env: { BRAIN_REQUIRE_CHROME: "1" } }]; } - const names: Record, string[]> = { + // The pinned container, entered as `browser` and `layout` enter it. As for the Bun gate, an unsplit + // selection keeps its command and a partition of a split one names the selection's count. + if (category === "browser_determinism") { + const { selection, partition } = browserDeterminismPartition(plan, shard); + const repetitions = selection.partitions.length > 1 ? selection.repetitions : browserRepetitionsFor(plan.cadence); + return [{ name: "workspace build for real browser checks", argv: [process.execPath, "run", "build", "--jobs=2"] }, + { name: "changed Vitest specs repeated under CPU load in the pinned container", + argv: [process.execPath, join(root, "scripts/browser-determinism.ts"), `--report=${BROWSER_DETERMINISM_REPORT}`, + ...(repetitions === undefined ? [] : [`--repetitions=${repetitions}`]), ...partition.pairs.map(pairKey)] }]; + } + 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"], @@ -110,12 +139,12 @@ if (import.meta.main) { // `retained` is always empty since proof retention was retired (#4107). The field stays so // a checkout that predates the retirement, and the timing collector reading older runs, // still parse this receipt. - console.log(`BRAIN_SELECTED_PROOF_RECEIPT ${JSON.stringify({ selections: Object.fromEntries(PROOF_JOBS.map(name => [name, needs.changeset.outputs[name]])), results: Object.fromEntries(PROOF_JOBS.map(name => [name, needs[name]?.result])), retained: [], unitShards: needs.changeset.outputs.unit_shards ?? null, determinismShards: needs.changeset.outputs.determinism_shards ?? null })}`); + console.log(`BRAIN_SELECTED_PROOF_RECEIPT ${JSON.stringify({ selections: Object.fromEntries(PROOF_JOBS.map(name => [name, needs.changeset.outputs[name]])), results: Object.fromEntries(PROOF_JOBS.map(name => [name, needs[name]?.result])), retained: [], unitShards: needs.changeset.outputs.unit_shards ?? null, determinismShards: needs.changeset.outputs.determinism_shards ?? null, browserDeterminismShards: needs.changeset.outputs.browser_determinism_shards ?? null })}`); console.log("All selected hosted proof passed; remaining skips are planner-intended."); } else { const root = resolve(import.meta.dir, ".."); const category = process.argv[2] as ProofCategory; - if (!["unit", "browser", "layout", "captures", "runtime", "runtime_host", "endurance", "determinism"].includes(category)) throw new Error("Unknown proof category"); + if (!PROOF_CATEGORIES.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=")); @@ -128,7 +157,8 @@ 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, files: category === "unit" ? unitFiles(plan, root, shard) : category === "determinism" ? determinismFiles(plan, shard) : undefined }, null, 2)); + checkout: { sha, tree, parents }, plan, files: category === "unit" ? unitFiles(plan, root, shard) : category === "determinism" ? determinismFiles(plan, shard) : + category === "browser_determinism" ? browserDeterminismPairs(plan, shard) : 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 } }); @@ -139,8 +169,10 @@ if (import.meta.main) { // 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) : category === "determinism" ? determinismFiles(plan, shard) : []).includes("tests/workspace-lease.test.ts")) { - if (!Bun.which("docker")) throw new Error("The native workspace lease test requires Docker"); + // The browser repetition gate's own container test starts the same image the same way (#4163). + const selectedFiles = category === "unit" ? unitFiles(plan, root, shard) : category === "determinism" ? determinismFiles(plan, shard) : []; + if (PINNED_IMAGE_TESTS.some(file => selectedFiles.includes(file))) { + if (!Bun.which("docker")) throw new Error("The pinned-container tests require Docker"); const { image } = await resolveBrowserPin(root); commands.unshift({ name: "pinned offline workspace lease container prerequisite", argv: ["docker", "pull", image], env: {} }); } @@ -151,6 +183,13 @@ if (import.meta.main) { `this partition repeats ${partition.files.length} file(s), ${partition.estimatedSeconds.toFixed(1)} s estimated against a capacity of ${selection.capacitySeconds} s` + `${partition.estimatedSeconds > selection.capacitySeconds ? " (one file that cannot be split)" : ""}.`); } + if (category === "browser_determinism") { + const { selection, partition } = browserDeterminismPartition(plan, shard); + if (selection.partitions.length > 1) console.log(`Partition ${shard} of a selection split by reviewed weight: ${selection.pairs.length} project/file pair(s), ` + + `${selection.weightSeconds.toFixed(1)} weighted s per pass, ${selection.repetitions} repetition(s) each (${selection.requested} requested); ` + + `this partition repeats ${partition.pairs.length} pair(s), ${partition.estimatedSeconds.toFixed(1)} s estimated against a capacity of ${selection.capacitySeconds} s` + + `${partition.estimatedSeconds > selection.capacitySeconds ? " (one pair that cannot be split)" : ""}.`); + } const started = performance.now(); const cpu = () => cpus().reduce((sum, core) => sum + core.times.user + core.times.nice + core.times.sys + core.times.irq, 0) / 1000; const cpuStart = cpu(); diff --git a/scripts/determinism-plan.ts b/scripts/determinism-plan.ts index 1f0fd20ab6..ba3c133e67 100644 --- a/scripts/determinism-plan.ts +++ b/scripts/determinism-plan.ts @@ -43,15 +43,16 @@ export interface RepetitionPlan { * 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 { + costs?: Readonly>; unweightedSeconds?: number } = {}): RepetitionPlan { const requested = options.repetitions ?? DEFAULT_REPETITIONS, floor = options.floor ?? FLOOR_REPETITIONS; const budgetSeconds = options.budgetSeconds ?? BUDGET_SECONDS, costs = options.costs ?? FILE_COST_SECONDS; + const unweightedSeconds = options.unweightedSeconds ?? UNWEIGHTED_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; + const weighted = Object.hasOwn(costs, file), weightSeconds = weighted ? costs[file]! : unweightedSeconds; if (!Number.isFinite(weightSeconds) || weightSeconds <= 0) throw new Error(`Test file costs must be positive finite seconds: ${file}`); return { file, weightSeconds, weighted }; }); @@ -63,6 +64,10 @@ export function planRepetitions(files: readonly string[], options: { repetitions overBudget: estimatedSeconds > budgetSeconds, files: weights.map(entry => ({ ...entry, repetitions })) }; } +/** What a planner repeats, for its refusals: the Bun gate's files, or another gate's units (#4163). */ +export interface PartitionSubject { proof: string; units: string; unit: string; owner: string; } +const BUN_FILES: PartitionSubject = { proof: "Repeated-run proof", units: "changed Bun test file(s)", unit: "file", owner: "DETERMINISM_PARTITIONS" }; + export interface DeterminismPartition { files: string[]; weightSeconds: number; estimatedSeconds: number; } export interface PartitionPlan extends RepetitionPlan { capacitySeconds: number; maxPartitions: number; partitions: DeterminismPartition[]; } @@ -76,13 +81,14 @@ export interface PartitionPlan extends RepetitionPlan { capacitySeconds: number; * never reduced below the floor. */ export function planPartitions(files: readonly string[], options: { cadence?: string; repetitions?: number; - costs?: Readonly>; capacitySeconds?: number; maxPartitions?: number } = {}): PartitionPlan { + costs?: Readonly>; capacitySeconds?: number; maxPartitions?: number; unweightedSeconds?: number; + subject?: PartitionSubject } = {}): PartitionPlan { const capacitySeconds = options.capacitySeconds ?? DETERMINISM_PARTITIONS.capacitySeconds; - const maxPartitions = options.maxPartitions ?? DETERMINISM_PARTITIONS.max; + const maxPartitions = options.maxPartitions ?? DETERMINISM_PARTITIONS.max, subject = options.subject ?? BUN_FILES; if (!Number.isSafeInteger(maxPartitions) || maxPartitions < 1) throw new Error("The maximum partition count is a positive integer"); - if (!files.length) throw new Error("Repeated-run proof was not selected"); + if (!files.length) throw new Error(`${subject.proof} was not selected`); const plan = planRepetitions([...files].sort(), { repetitions: options.repetitions ?? repetitionsFor(options.cadence), - budgetSeconds: capacitySeconds, costs: options.costs }); + budgetSeconds: capacitySeconds, costs: options.costs, unweightedSeconds: options.unweightedSeconds }); const weights = Object.fromEntries(plan.files.map(entry => [entry.file, entry.weightSeconds])); const names = plan.files.map(entry => entry.file); for (let count = 1; count <= Math.min(maxPartitions, names.length); count++) { @@ -93,9 +99,9 @@ export function planPartitions(files: readonly string[], options: { cadence?: st if (partitions.every(partition => partition.estimatedSeconds <= capacitySeconds || partition.files.length === 1)) return { ...plan, capacitySeconds, maxPartitions, partitions }; } - throw new Error(`Repeated-run proof refused before it ran: ${names.length} changed Bun test file(s) weigh ${plan.weightSeconds.toFixed(1)} weighted s per pass, ` + + throw new Error(`${subject.proof} refused before it ran: ${names.length} ${subject.units} weigh ${plan.weightSeconds.toFixed(1)} weighted s per pass, ` + `${plan.estimatedSeconds.toFixed(1)} s at the floor of ${plan.repetitions} repetitions. That needs more than the limit of ${maxPartitions} partitions ` + - `of ${capacitySeconds} weighted s each (DETERMINISM_PARTITIONS, scripts/proof-shards.ts). No file is skipped and the count stays at the floor: split the change.`); + `of ${capacitySeconds} weighted s each (${subject.owner}, scripts/proof-shards.ts). No ${subject.unit} is skipped and the count stays at the floor: split the change.`); } /** Partition `M/N` of the plan. `N` must be the planned count, so a matrix or a command that disagrees with the planner runs nothing. */ diff --git a/scripts/heavy-feedback-workflow.ts b/scripts/heavy-feedback-workflow.ts index c120616c39..575120a2bd 100644 --- a/scripts/heavy-feedback-workflow.ts +++ b/scripts/heavy-feedback-workflow.ts @@ -13,7 +13,7 @@ import { annotateActionPins } from "./action-pins"; 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", "determinism"] as const; +export const CATEGORY_JOBS = ["verify", "pack", "unit", "runtime", "runtime_host", "browser", "layout", "captures", "endurance", "determinism", "browser_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/integration-proof.ts b/scripts/integration-proof.ts index e546a12b3c..89952d15a2 100644 --- a/scripts/integration-proof.ts +++ b/scripts/integration-proof.ts @@ -4,10 +4,25 @@ import { checkout, type Checkout } from "./proof-inputs"; import type { Candidate } from "./integration-reservation"; import type { API } from "./proof-api"; import { PROOF_JOBS, proofProblems } from "./ci-proof"; -import { DETERMINISM_PARTITIONS, MAX_UNIT_PARTITIONS, shardNumbers, unitPartitionLimit } from "./proof-shards"; +import { BROWSER_DETERMINISM_PARTITIONS, DETERMINISM_PARTITIONS, MAX_UNIT_PARTITIONS, PROOF_SHARDS, shardNumbers, unitPartitionLimit } from "./proof-shards"; import { coveredCategories } from "./check-receipt"; import type { Category } from "./red-main"; +/** Proof jobs whose matrix the planner publishes, with the receipt field that carries the published set and its largest size. */ +const PLANNED_MATRICES = { + determinism: { field: "determinismShards", max: DETERMINISM_PARTITIONS.max }, + browser_determinism: { field: "browserDeterminismShards", max: BROWSER_DETERMINISM_PARTITIONS.max }, +} as const; +/** + * The most jobs one run can list: metadata, the aggregate and every proof job + * at its widest matrix. The inventory is bounded by this rather than by a + * literal, so a new matrix or a wider one cannot make a complete run look + * malformed (#4163). + */ +export const MAX_RUN_JOBS = 2 + PROOF_JOBS.reduce((jobs, name) => jobs + (name === "unit" ? MAX_UNIT_PARTITIONS : + name in PLANNED_MATRICES ? PLANNED_MATRICES[name as keyof typeof PLANNED_MATRICES].max : + name in PROOF_SHARDS ? PROOF_SHARDS[name as keyof typeof PROOF_SHARDS] : 1), 0); + export function checkoutFromJob(log: string): string { const lines = log.replace(/\x1b\[[0-9;]*m/g, "").split("\n"); const index = lines.findIndex(line => line.includes("git log -1 --format=%H")); @@ -59,7 +74,7 @@ function inventoryDiagnostic(inventory: any, run: any, head: string): string { const names = ["changeset", "proof", ...PROOF_JOBS, ...["browser", "layout"].flatMap(name => shardNumbers(name as "browser" | "layout").map(shard => `${name} (${shard})`)), ...Array.from({ length: MAX_UNIT_PARTITIONS }, (_, index) => `unit (${index + 1})`), - ...Array.from({ length: DETERMINISM_PARTITIONS.max }, (_, index) => `determinism (${index + 1})`)]; + ...Object.entries(PLANNED_MATRICES).flatMap(([name, matrix]) => Array.from({ length: matrix.max }, (_, index) => `${name} (${index + 1})`))]; const fields = metadataObject(inventory) ? inventory : {}; const jobs = fields.jobs; const predicates: string[] = []; @@ -69,7 +84,7 @@ function inventoryDiagnostic(inventory: any, run: any, head: string): string { else { if (fields.total_count !== jobs.length) predicates.push("total_count differs from jobs.length"); if (!jobs.length) predicates.push("jobs.length is zero"); - if (jobs.length > 30) predicates.push("jobs.length exceeds 30"); + if (jobs.length > MAX_RUN_JOBS) predicates.push(`jobs.length exceeds ${MAX_RUN_JOBS}`); // The endpoint requests at most 100 jobs. Bound diagnostics even for a malformed response. for (const [index, value] of jobs.slice(0, 100).entries()) { const job = metadataObject(value) ? value : {}; @@ -101,7 +116,7 @@ export async function verifyIntegrationProof(root: string, repository: string, c const inventory = await api.json(`actions/runs/${run.id}/attempts/${run.run_attempt}/jobs?per_page=100`); if (!metadataObject(inventory)) throw new Error(`Incomplete or failed selected job inventory: ${inventoryDiagnostic(inventory, run, candidate.head)}`); const jobs: Array<{ id: number; name: string; status: string; conclusion: string; run_id: number; head_sha: string }> = inventory.jobs; - if (!Array.isArray(jobs) || inventory.total_count !== jobs.length || !jobs.length || jobs.length > 30 || + if (!Array.isArray(jobs) || inventory.total_count !== jobs.length || !jobs.length || jobs.length > MAX_RUN_JOBS || jobs.some(job => !metadataObject(job) || !Number.isSafeInteger(job.id) || job.run_id !== run.id || job.head_sha !== candidate.head || job.status !== "completed" || !["success", "skipped"].includes(job.conclusion))) throw new Error(`Incomplete or failed selected job inventory: ${inventoryDiagnostic(inventory, run, candidate.head)}`); const proofs = jobs.filter(job => job.name === "proof" && job.conclusion === "success"); if (proofs.length !== 1) throw new Error("Missing complete candidate aggregate"); @@ -111,7 +126,7 @@ export async function verifyIntegrationProof(root: string, repository: string, c const selectedLines = proofLog.split("\n").filter(line => line.includes("BRAIN_SELECTED_PROOF_RECEIPT ")); if (selectedLines.length !== 1) throw new Error("Fresh structured selected-proof receipt required"); const selected = JSON.parse(selectedLines[0]!.split("BRAIN_SELECTED_PROOF_RECEIPT ")[1]!) as { - selections: Record; results: Record; retained?: unknown; unitShards: string | null; determinismShards?: string | null; + selections: Record; results: Record; retained?: unknown; unitShards: string | null; determinismShards?: string | null; browserDeterminismShards?: string | null; }; // Retention is retired (#4107): a receipt naming a retained category is not fresh proof. if (selected.retained !== undefined && (!Array.isArray(selected.retained) || selected.retained.length)) throw new Error("Retained proof is retired: every selected category must run fresh"); @@ -126,11 +141,12 @@ export async function verifyIntegrationProof(root: string, repository: string, c // Only a ready confirmation reaches the merge path, so its cap bounds the planned set (#4108). if (!Array.isArray(shards) || !shards.length || shards.length > unitPartitionLimit("confirmation") || shards.some((value, index) => value !== index + 1)) throw new Error("Missing actual unit partition identity"); expected.push(...shards.map(index => `unit (${index}):success`)); - } else if (fresh && name === "determinism") { - // The aggregate validated this published set against the plan; every one of its partitions must have run (#4117). - const shards: unknown = JSON.parse(selected.determinismShards ?? "null"); - if (!Array.isArray(shards) || !shards.length || shards.length > DETERMINISM_PARTITIONS.max || shards.some((value, index) => value !== index + 1)) throw new Error("Missing actual determinism partition identity"); - expected.push(...shards.map(index => `determinism (${index}):success`)); + } else if (fresh && name in PLANNED_MATRICES) { + // The aggregate validated this published set against the plan; every one of its partitions must have run (#4117, #4163). + const matrix = PLANNED_MATRICES[name as keyof typeof PLANNED_MATRICES]; + const shards: unknown = JSON.parse(selected[matrix.field] ?? "null"); + if (!Array.isArray(shards) || !shards.length || shards.length > matrix.max || shards.some((value, index) => value !== index + 1)) throw new Error(`Missing actual ${name} partition identity`); + expected.push(...shards.map(index => `${name} (${index}):success`)); } else expected.push(`${name}:${fresh ? "success" : "skipped"}`); } if (JSON.stringify(jobs.map(job => `${job.name}:${job.conclusion}`).sort()) !== JSON.stringify(expected.sort())) throw new Error("Actual selected job inventory differs from the validated selection"); diff --git a/scripts/proof-shards.ts b/scripts/proof-shards.ts index f8d664f19e..f80b049696 100644 --- a/scripts/proof-shards.ts +++ b/scripts/proof-shards.ts @@ -42,3 +42,17 @@ export function unitPartitions(cadence: string | undefined, files?: number): num * merge path and the workflow guard read this table. Measured basis: * docs/decisions/ci-utility.md, "Changed tests repeat under load before merge". */ export const DETERMINISM_PARTITIONS = { capacitySeconds: 300, max: 10, stepMinutes: 40, loadRatio: 6.84 } as const; + +/** `browser_determinism` partitions (#4163): the one owner of one job's + * capacity, the most partitions a selection may use, the proof step's limit + * and the cost of a project/file pair that has no reviewed weight. Capacity is + * in seconds of `scripts/browser-shard-costs.json` at the selection's + * repetition count, and it is also the budget that reduces the count + * (`BROWSER_BUDGET_SECONDS`, scripts/browser-determinism-plan.ts). `loadRatio` + * is the largest elapsed seconds per weighted second the #4116 spike measured + * for a pass under burners inside the container. The planner's + * `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; diff --git a/scripts/visual.mjs b/scripts/visual.mjs index 31683504ef..6b747e6867 100644 --- a/scripts/visual.mjs +++ b/scripts/visual.mjs @@ -36,6 +36,7 @@ * node scripts/visual.mjs --update # rewrite the baselines * node scripts/visual.mjs --shard=1/2 # half the files of every project (CI) * node scripts/visual.mjs --inside … # already in the image (CI) + * node scripts/visual.mjs --project=… --repeat-plan=tmp/…json # repeated passes under load; written by scripts/browser-determinism.ts * node scripts/visual.mjs --browser.fileParallelism=true # diagnostic override */ import { execFileSync, spawnSync } from "node:child_process"; @@ -71,6 +72,17 @@ if (schedulingArgs.length > 1 || schedulingArgs.some((a) => !/^--browser\.filePa process.exit(1); } const schedulingArg = schedulingArgs[0] ?? "--browser.fileParallelism=false"; +// Changed specs repeated under CPU load (#4163): the same container, mounts and +// network as any run of the selected projects, entered by a different inner +// command. The plan names the exact project/file pairs, so nothing else that +// chooses files applies. +const repeatPlans = argv.filter((a) => a.startsWith("--repeat-plan=")); +const repeatPlan = repeatPlans[0]?.slice("--repeat-plan=".length); +if (repeatPlans.length > 1 || (repeatPlan !== undefined && (!/^tmp\/[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)*\.json$/.test(repeatPlan) || repeatPlan.split("/").includes("..") || + !projectArgs.length || update || shardArg || filters.length || schedulingArgs.length || argv.includes("--proof-report")))) { + console.error("use --repeat-plan=tmp/.json once, with --project and no --update, --shard, --filter, --proof-report or scheduling override"); + process.exit(1); +} const gitCheckout = () => { const [sha, tree, ...parents] = execFileSync("git", ["show", "-s", "--format=%H %T %P", "HEAD"], { cwd: REPO, encoding: "utf8" }).trim().split(" "); return JSON.stringify({ sha, tree, parents }); @@ -93,6 +105,8 @@ if (inside) { // separate locks. Exclusive access also preserves project scheduling/captures. const coordinated = await ensureWorkspaceLease(REPO, "write"); if (coordinated !== undefined) process.exit(coordinated); + // Repeated passes run Vitest in-process, with their CPU burners beside it in this container. + if (repeatPlan) process.exit(run(process.execPath, [resolve(REPO, "scripts/browser-determinism-inside.mjs"), repeatPlan], { cwd: resolve(REPO, KIT) })); // Already in the image. Vitest is invoked through its own entry rather than // through a package script, because a package script would need bun. // diff --git a/tests/browser-determinism-container.test.ts b/tests/browser-determinism-container.test.ts new file mode 100644 index 0000000000..9ba4ee1fd4 --- /dev/null +++ b/tests/browser-determinism-container.test.ts @@ -0,0 +1,67 @@ +// The seam of the browser repetition gate, once (#4163): the real container +// side (scripts/browser-determinism-inside.mjs), the installed Vitest and a real +// Chromium, in the pinned image, against fixture specs no ordinary browser, +// layout or story project includes: their two projects are declared in +// tests/fixtures/browser-determinism/vitest.config.mjs. tests/browser-determinism.test.ts +// enumerates every case against a stand-in; this proves that further passes in +// one Vitest process really rerun a file, that the first failing repetition +// stops the run with its spec and project named, and that burners start and +// stop beside the browser. +// +// The container has no network and is started with --pull=never, as +// tests/workspace-lease.test.ts starts it: hosted proof pulls the pinned image +// before the partition that holds this file (scripts/ci-proof.ts). +import { afterEach, expect, test } from "bun:test"; +import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { RESULT_KIND } from "../scripts/browser-determinism-inside.mjs"; +import { resolveBrowserPin } from "../scripts/captures/provenance"; + +const ROOT = join(import.meta.dir, ".."), FIXTURES = "tests/fixtures/browser-determinism"; +const racy = `${FIXTURES}/landing-racy.repeat.js`, steady = `${FIXTURES}/landing-steady.repeat.js`; +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) { + 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 })); + // 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. + chmodSync(join(ROOT, run, "plan.json"), 0o644); + for (const dir of [scratch, join(ROOT, run)]) chmodSync(dir, 0o777); + const child = Bun.spawn(["docker", "run", "--rm", "--pull=never", "--network=none", "--ipc=host", "--user", `${process.getuid!()}:${process.getgid!()}`, + "-v", `${ROOT}:/repo`, "-v", `${scratch}:${scratch}`, "-e", `TMPDIR=${scratch}`, "-e", "HOME=/tmp", "-w", "/repo", + (await resolveBrowserPin(ROOT)).image, "sh", "-c", 'umask 000 && exec node scripts/browser-determinism-inside.mjs "$1"', "sh", `${run}/plan.json`], { stdin: "ignore", stdout: "pipe", stderr: "pipe" }); + const [code, out, err] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); + let result: any; + try { result = JSON.parse(readFileSync(join(ROOT, run, "passes.json"), "utf8")); } catch { throw new Error(`The container wrote no result (exit ${code}):\n${out}\n${err}`); } + return { code, out, result }; +} + +test("the racy fixture fails the real runner at its third repetition in the pinned container, with spec, project and repetition named", async () => { + const { code, out, result } = await repeatInContainer([{ project: "harbour", file: racy }], 5); + expect(result.failure, "SPEC_PROJECT_AND_REPETITION_NAMED").toEqual({ project: "harbour", file: racy, repetition: 3, test: "the crew is aboard before the tide turns", + reason: "a test case failed: expected 'tide' to be 'crew' // Object.is equality" }); + // Two green passes before the failing one: a single pass would have let the race through. + expect(result.passes.map((pass: { repetition: number; ok: boolean }) => [pass.repetition, pass.ok]), "FURTHER_PASSES_RERUN_THE_FILE").toEqual([[1, true], [2, true], [3, false]]); + expect(code).toBe(1); + expect(out).toContain(`[browser-determinism] FAILED: ${racy} in project harbour, repetition 3 of 5: "the crew is aboard before the tide turns"`); + // Exactly the selected pair ran: the same file in the fixture's other project did not. + expect(out).not.toContain("strait"); + expect(result.load.burners, "BURNER_STARTED_INSIDE_THE_CONTAINER").toBe(1); +}); + +test("the same spec made deterministic passes every repetition in both of its projects", async () => { + const pairs = [{ project: "harbour", file: steady }, { project: "strait", file: steady }]; + const { code, out, result } = await repeatInContainer(pairs, 5); + expect(result.failure, out).toBeNull(); + expect(result.passes.map((pass: { repetition: number; ok: boolean }) => [pass.repetition, pass.ok])).toEqual([[1, true], [2, true], [3, true], [4, true], [5, true]]); + 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."); +}); diff --git a/tests/browser-determinism.test.ts b/tests/browser-determinism.test.ts new file mode 100644 index 0000000000..c73a673d99 --- /dev/null +++ b/tests/browser-determinism.test.ts @@ -0,0 +1,424 @@ +// Changed Vitest browser, layout and story specs repeat under CPU load in the +// pinned container before merge (#4163). Every case is enumerated here against +// the pure planner and a stand-in Vitest; tests/browser-determinism-container.test.ts +// proves the seam once, with the real runner, browser and image. +import { afterEach, describe, expect, test } from "bun:test"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { + BROWSER_BUDGET_SECONDS, DEFAULT_REPETITIONS, FLOOR_REPETITIONS, UNWEIGHTED_PAIR_SECONDS, browserRepetitionsFor, expandSpecs, isRepeatedSpec, + 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 { readBrowserCosts } from "../scripts/browser-shards"; +import { BROWSER_DETERMINISM_PARTITIONS } from "../scripts/proof-shards"; + +const scratch: string[] = []; +afterEach(() => { for (const dir of scratch.splice(0)) rmSync(dir, { recursive: true, force: true }); }); + +const stories = "packages/ui-kit/stories", browser = "packages/ui-react/tests/browser", visual = "packages/ui-kit/tests/visual"; +const pair = (project: string, file: string): SpecPair => ({ project, file }); +const sum = (values: readonly number[]) => values.reduce((total, value) => total + value, 0); + +describe("which specs the gate repeats", () => { + test("visual, story, pointer, layout and offline specs count; the endurance spec, a helper and anything elsewhere do not", () => { + const repeated = [`${visual}/sails.visual.tsx`, `${visual}/harbour/quay.visual.tsx`, `${stories}/Sail.stories.tsx`, `${stories}/ship/Mast.stories.tsx`, + `${browser}/oars.pointer.tsx`, `${browser}/deck.layout.tsx`, `${browser}/offline/fog.offline.tsx`]; + expect(repeated.filter(path => !isRepeatedSpec(path)), "EVERY_SPEC_KIND_COUNTS").toEqual([]); + const ignored = [`${browser}/watch.endurance.tsx`, `${browser}/offline/fault-network.ts`, `${browser}/conversation-server-command.ts`, `${visual}/request-log.ts`, + `${stories}/Sail.tsx`, "packages/ui-react/tests/session-demux.test.ts", "packages/ui-react/src/deck.layout.tsx", "packages/core/tests/sails.layout.tsx", + "packages/ui-kit/tests/sails.visual.tsx", `${browser}/oars.pointer.ts`, "tests/fixtures/browser-determinism/landing-racy.repeat.js"]; + expect(ignored.filter(isRepeatedSpec), "NOTHING_ELSE_COUNTS").toEqual([]); + }); + + test("a spec expands to every project/file pair the listing reports for it, and to nothing else", () => { + const listing = [pair("visual", `${visual}/sails.visual.tsx`), pair("storybook", `${stories}/Sail.stories.tsx`), pair("storybook-light", `${stories}/Sail.stories.tsx`), + ...["rail-mixed", "rail-fine", "rail-coarse"].map(project => pair(project, `${browser}/oars.pointer.tsx`)), pair("keyboard-hints-live", `${browser}/keys.pointer.tsx`), + pair("ui-react-layout", `${browser}/deck.layout.tsx`), pair("diagrams-chromium", `${browser}/diagrams-axis.layout.tsx`), pair("diagrams-webkit", `${browser}/diagrams-axis.layout.tsx`)]; + expect(expandSpecs([`${browser}/oars.pointer.tsx`], listing), "A_POINTER_SPEC_IS_THREE_PAIRS").toEqual(["rail-coarse", "rail-fine", "rail-mixed"].map(project => pair(project, `${browser}/oars.pointer.tsx`))); + expect(expandSpecs([`${stories}/Sail.stories.tsx`, `${stories}/Sail.stories.tsx`], listing), "A_STORY_IS_BOTH_THEMES_ONCE").toEqual([pair("storybook-light", `${stories}/Sail.stories.tsx`), pair("storybook", `${stories}/Sail.stories.tsx`)]); + expect(expandSpecs([`${browser}/diagrams-axis.layout.tsx`, `${browser}/deck.layout.tsx`], listing).map(pairKey)).toEqual([ + `diagrams-chromium::${browser}/diagrams-axis.layout.tsx`, `diagrams-webkit::${browser}/diagrams-axis.layout.tsx`, `ui-react-layout::${browser}/deck.layout.tsx`]); + expect(expandSpecs([], listing)).toEqual([]); + expect(() => expandSpecs([`${browser}/stray.pointer.tsx`], listing), "A_SPEC_NOTHING_RUNS").toThrow("is a changed spec that no Vitest project lists, so nothing runs it"); + expect(() => expandSpecs([`${browser}/offline/fault-network.ts`], listing), "A_HELPER_IS_NOT_A_SPEC").toThrow("Not a browser, layout or story spec the gate repeats"); + }); + + // The reviewed weight table records one row per project/file pair of a complete hosted run: the + // installed runner's listing at the last refresh, read here without starting Vitest. + test("every project/file pair of the last complete browser and layout run is a spec the gate repeats, in the projects that ran it", () => { + const recorded = Object.keys(readBrowserCosts().seconds).map(parsePairKey); + // A control against an empty or partial table, not a pin on its size: the table had 387 rows + // before the 2026-11-17 refresh and 514 after it, and that refresh has been reverted once. + expect(recorded.length, "A_COMPLETE_RUN").toBeGreaterThan(300); + expect(recorded.filter(spec => !isRepeatedSpec(spec.file)).map(pairKey), "PATTERNS_COVER_EVERY_PROJECT").toEqual([]); + const projects = (file: string) => expandSpecs([file], recorded).map(spec => spec.project); + expect(projects(`${browser}/dictation-notice.pointer.tsx`)).toEqual(["rail-coarse", "rail-fine", "rail-mixed"]); + expect(projects(`${stories}/evidence/SearchResultCard.stories.tsx`)).toEqual(["storybook-light", "storybook"]); + expect(projects(`${browser}/diagrams-axis.layout.tsx`)).toEqual(["diagrams-chromium", "diagrams-webkit"]); + expect(projects(`${browser}/handoff-sheet.layout.tsx`)).toEqual(["ui-react-layout"]); + expect(projects(`${visual}/contact-card-fact-keys.visual.tsx`)).toEqual(["visual"]); + // The endurance project has no row and its one spec no pattern: real-time media proof keeps its own job. + expect(recorded.filter(spec => spec.project === "ui-react-endurance")).toEqual([]); + }); + + test("a pair key is a project and a repository path, and nothing that escapes the repository", () => { + expect(parsePairKey(`rail-fine::${browser}/oars.pointer.tsx`)).toEqual(pair("rail-fine", `${browser}/oars.pointer.tsx`)); + expect(pairKey(pair("harbour", "tests/fixtures/browser-determinism/landing-racy.repeat.js"))).toBe("harbour::tests/fixtures/browser-determinism/landing-racy.repeat.js"); + for (const key of ["oars.pointer.tsx", `::${browser}/oars.pointer.tsx`, "rail-fine::../oars.pointer.tsx", "rail-fine::packages/../../etc/passwd", "rail fine::packages/a.tsx", "rail-fine::/abs/a.tsx"]) { + expect(() => parsePairKey(key), key).toThrow("Expected ::"); + } + }); +}); + +describe("repetition count and budget", () => { + const oars = ["rail-coarse", "rail-fine", "rail-mixed"].map(project => pair(project, `${browser}/oars.pointer.tsx`)); + 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([DEFAULT_REPETITIONS, FLOOR_REPETITIONS, BROWSER_BUDGET_SECONDS, UNWEIGHTED_PAIR_SECONDS]).toEqual([5, 2, 300, 10]); + // 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); + }); + + test("ready confirmation asks for two repetitions and every other cadence for five", () => { + expect(browserRepetitionsFor("confirmation"), "CONFIRMATION_ASKS_FOR_THE_FLOOR").toBe(2); + for (const cadence of ["draft", "feedback", "feedback-heavy", undefined]) expect(browserRepetitionsFor(cadence), `DEFAULT_COUNT:${cadence}`).toBeUndefined(); + // 60 weighted s per pass: five repetitions fit the budget exactly. + const counts = Object.fromEntries(["draft", "feedback", "feedback-heavy", "confirmation"].map(cadence => { + const plan = planBrowserPartitions(oars, { cadence, costs }); + return [cadence, [plan.requested, plan.repetitions, plan.pairs.map(entry => entry.repetitions)]]; + })); + expect(counts).toEqual({ draft: [5, 5, [5, 5, 5]], feedback: [5, 5, [5, 5, 5]], "feedback-heavy": [5, 5, [5, 5, 5]], confirmation: [2, 2, [2, 2, 2]] }); + }); + + test("a selection inside the budget gets five repetitions for every pair", () => { + const plan = planBrowserRepetitions(oars, { costs }); + expect(plan).toMatchObject({ requested: 5, floor: 2, repetitions: 5, reduced: false, overBudget: false, budgetSeconds: 300, weightSeconds: 60, estimatedSeconds: 300, unweightedSeconds: 10 }); + expect(plan.pairs).toEqual(oars.map((spec, index) => ({ ...spec, weightSeconds: 10 + index * 10, weighted: true, repetitions: 5 }))); + }); + + test("five that do not fit drop uniformly to what fits, never below two, and no pair is dropped", () => { + const reduced = planBrowserRepetitions(oars, { costs, budgetSeconds: 299 }); + expect(reduced, "REDUCED_TO_WHAT_FITS").toMatchObject({ repetitions: 4, reduced: true, overBudget: false, estimatedSeconds: 240 }); + expect(reduced.pairs.map(entry => entry.repetitions), "UNIFORM_REDUCTION").toEqual([4, 4, 4]); + const floor = planBrowserRepetitions(oars, { costs, budgetSeconds: 100 }); + expect(floor, "FLOOR_OF_TWO_HOLDS").toMatchObject({ repetitions: 2, reduced: true, overBudget: true, estimatedSeconds: 120 }); + expect(floor.pairs.map(entry => [entry.project, entry.repetitions]), "NO_PAIR_DROPPED").toEqual([["rail-coarse", 2], ["rail-fine", 2], ["rail-mixed", 2]]); + }); + + test("a pair without a reviewed weight costs the stated default, is named as unweighted and is never free", () => { + const added = [pair("storybook", `${stories}/Mast.stories.tsx`), pair("storybook-light", `${stories}/Mast.stories.tsx`)]; + const plan = planBrowserRepetitions([...added, oars[0]!], { costs }); + expect(plan.pairs.map(entry => [entry.project, entry.weightSeconds, entry.weighted])).toEqual([["rail-coarse", 10, true], ["storybook-light", 10, false], ["storybook", 10, false]]); + expect(plan.weightSeconds, "THE_DEFAULT_COUNTS_TOWARDS_THE_BUDGET").toBe(30); + // Enough unweighted pairs reduce the count like any other weight: 7 pairs are 70 s per pass, and four passes fit. + const many = Array.from({ length: 7 }, (_, index) => pair("visual", `${visual}/new-${index}.visual.tsx`)); + expect(planBrowserRepetitions(many, { costs: {} }), "UNWEIGHTED_PAIRS_REDUCE_THE_COUNT").toMatchObject({ weightSeconds: 70, repetitions: 4, reduced: true }); + expect(planBrowserRepetitions(many, { costs: {}, unweightedSeconds: 1 }).repetitions).toBe(5); + }); + + test("the reviewed table weighs real pairs, and one run, a duplicate pair and a non-positive budget are refused", () => { + const [key, seconds] = Object.entries(readBrowserCosts().seconds)[0]!; + expect(planBrowserRepetitions([parsePairKey(key)]).pairs, "DEFAULT_COSTS_ARE_THE_REVIEWED_TABLE").toEqual([{ ...parsePairKey(key), weightSeconds: seconds, weighted: true, repetitions: Math.max(2, Math.min(5, Math.floor(300 / seconds))) }]); + expect(() => planBrowserRepetitions(oars, { costs, repetitions: 1 })).toThrow("at least 2"); + expect(() => planBrowserRepetitions([oars[0]!, oars[0]!], { costs })).toThrow("A project/file pair was selected twice"); + expect(() => planBrowserRepetitions(oars, { costs, budgetSeconds: 0 })).toThrow("budget must be positive"); + expect(planBrowserRepetitions([], { costs })).toMatchObject({ pairs: [], repetitions: 5, weightSeconds: 0 }); + }); +}); + +describe("hosted partitions by reviewed weight", () => { + const { capacitySeconds, max } = BROWSER_DETERMINISM_PARTITIONS; + /** `count` pairs whose pass weighs `passSeconds` in all, none heavy enough to need a partition alone. */ + const fleet = (count: number, passSeconds: number) => Object.fromEntries(Array.from({ length: count }, (_, index) => + [`ui-react-layout::${browser}/fleet/ship-${String(index).padStart(3, "0")}.layout.tsx`, Number((passSeconds / count * (index % 2 ? 1.5 : 0.5)).toFixed(3))])); + const pairsOf = (costs: Record) => Object.keys(costs).map(parsePairKey); + + test("a selection over capacity at two repetitions plans several partitions that cover every pair exactly once", () => { + // 450 weighted s per pass, as two of the selections in the spike's window: 900 at the floor of two. + const costs = fleet(60, 450), pairs = pairsOf(costs); + for (const cadence of ["draft", "confirmation", "feedback-heavy"]) { + const plan = planBrowserPartitions(pairs, { cadence, costs }); + expect(plan, cadence).toMatchObject({ repetitions: 2, floor: 2, capacitySeconds, maxPartitions: max, overBudget: true }); + expect(plan.partitions.length, `SEVERAL_PARTITIONS:${cadence}`).toBe(3); + for (const partition of plan.partitions) { + expect(partition.estimatedSeconds, "EACH_WITHIN_CAPACITY").toBeLessThanOrEqual(capacitySeconds); + expect(partition.estimatedSeconds, "AT_THE_SELECTION_COUNT").toBeCloseTo(sum(partition.pairs.map(spec => costs[pairKey(spec)]!)) * 2, 6); + expect(partition.pairs.length).toBeGreaterThan(0); + } + expect(plan.partitions.flatMap(partition => partition.pairs.map(pairKey)).sort(), "EVERY_PAIR_EXACTLY_ONCE").toEqual(Object.keys(costs).sort()); + expect(plan.pairs.map(entry => entry.repetitions), "NO_PAIR_BELOW_THE_FLOOR").toEqual(pairs.map(() => 2)); + } + }); + + test("a selection within one job's capacity stays one partition, and one weighted second more splits it", () => { + const pairs = [pair("rail-fine", `${browser}/oars.pointer.tsx`), pair("ui-react-layout", `${browser}/deck.layout.tsx`)]; + const costs = { [pairKey(pairs[0]!)]: 20, [pairKey(pairs[1]!)]: 30 }; + const five = planBrowserPartitions(pairs, { cadence: "draft", costs }); + expect(five.partitions, "FIVE_REPETITIONS_ONE_JOB").toEqual([{ pairs, weightSeconds: 50, estimatedSeconds: 250 }]); + expect(planBrowserPartitions(pairs, { cadence: "draft", costs: { ...costs, [pairKey(pairs[1]!)]: 130 } }), "AT_CAPACITY").toMatchObject({ repetitions: 2, estimatedSeconds: 300, partitions: [{ estimatedSeconds: 300 }] }); + expect(planBrowserPartitions(pairs, { cadence: "draft", costs: { ...costs, [pairKey(pairs[1]!)]: 131 } }).partitions.map(partition => partition.pairs), "OVER_CAPACITY_SPLITS").toEqual([[pairs[1]!], [pairs[0]!]]); + }); + + test("a pair whose repetitions alone exceed the capacity runs in a partition by itself", () => { + const heavy = pair("rail-mixed", `${browser}/cyclops.pointer.tsx`), light = [pair("rail-fine", `${browser}/oars.pointer.tsx`), pair("visual", `${visual}/sails.visual.tsx`)]; + const costs = { [pairKey(heavy)]: 183, [pairKey(light[0]!)]: 100, [pairKey(light[1]!)]: 40 }; + expect(planBrowserPartitions([heavy, ...light], { costs }).partitions.map(partition => [partition.pairs, partition.estimatedSeconds]), "UNSPLITTABLE_PAIR_ALONE").toEqual([[[heavy], 366], [light, 280]]); + }); + + test("a selection beyond the maximum partition count is refused, naming its weight and the limit", () => { + const costs = fleet(400, 2400), pairs = pairsOf(costs); + expect(planBrowserPartitions(pairs, { costs, maxPartitions: 16 }).partitions.length, "SIXTEEN_WOULD_HOLD_IT").toBe(16); + expect(() => planBrowserPartitions(pairs, { costs })).toThrow( + "Repeated browser proof refused before it ran: 400 changed project/file pair(s) weigh 2400.0 weighted s per pass, 4800.0 s at the floor of 2 repetitions. " + + "That needs more than the limit of 15 partitions of 300 weighted s each (BROWSER_DETERMINISM_PARTITIONS, scripts/proof-shards.ts). " + + "No pair is skipped and the count stays at the floor: split the change."); + expect(() => planBrowserPartitions([], { costs })).toThrow("Repeated browser proof was not selected"); + }); + + test("a partition is read only with the planned count as its divisor", () => { + const costs = fleet(40, 200), plan = planBrowserPartitions(pairsOf(costs), { costs }); + expect(plan.partitions).toHaveLength(2); + expect(selectBrowserPartition(plan, "1/2")).toBe(plan.partitions[0]!); + expect(selectBrowserPartition(plan, "2/2")).toBe(plan.partitions[1]!); + for (const [shard, refusal] of [["1/1", "Repeated-run partition 1/1 is not in the planned set of 2"], ["1/3", "Repeated-run partition 1/3 is not in the planned set of 2"], + ["3/2", "Invalid proof shard"], ["0/2", "Expected proof --shard=M/N"], ["2", "Expected proof --shard=M/N"]] as const) { + expect(() => selectBrowserPartition(plan, shard), shard).toThrow(refusal); + } + }); +}); + +// A stand-in for the Vitest instance the container side drives: it reports each module through the +// reporter hook, as Vitest does, and fails where its schedule says. +const REPO = "/odyssey", racy = "tests/fixtures/browser-determinism/landing-racy.repeat.js", steady = "tests/fixtures/browser-determinism/landing-steady.repeat.js"; +interface Schedule { fails?: (repetition: number, key: string) => string | null | undefined; silent?: (repetition: number, key: string) => boolean; twice?: (repetition: number, key: string) => boolean; unhandled?: (repetition: number) => string | undefined; } +function standIn(listed: readonly SpecPair[], schedule: Schedule = {}) { + const collector = passCollector(), runs: string[][] = []; + const specification = (spec: SpecPair) => ({ project: { name: `${spec.project} (chromium)` }, moduleId: `${REPO}/${spec.file}` }); + const vitest = { + async globTestSpecifications() { return listed.map(specification); }, + async runTestSpecifications(specifications: ReturnType[], all: boolean) { + expect(all).toBe(true); + const keys = specifications.map(entry => `${entry.project.name.replace(" (chromium)", "")}::${entry.moduleId.slice(REPO.length + 1)}`); + runs.push(keys); + // A pair's repetition is how often it has been run: a pass makes one call per project. + const repetition = runs.filter(run => run.includes(keys[0]!)).length; + for (const [index, entry] of specifications.entries()) { + const key = keys[index]!; + const failed = schedule.fails?.(repetition, key); + const module = { project: entry.project, moduleId: entry.moduleId, ok: () => failed === undefined || failed === null && false, + errors: () => failed === null ? [{ message: "No test suite found in file" }] : [], + children: { *allTests(state?: string) { if (failed && state === "failed") yield { fullName: "the crew is aboard before the tide turns", result: () => ({ errors: [{ message: failed }] }) }; } } }; + if (schedule.silent?.(repetition, key)) continue; + collector.reporter.onTestModuleEnd(module); + if (schedule.twice?.(repetition, key)) collector.reporter.onTestModuleEnd(module); + } + const unhandled = schedule.unhandled?.(repetition); + return { testModules: [], unhandledErrors: unhandled ? [{ message: unhandled }] : [] }; + }, + }; + return { vitest, collector, runs }; +} +const harbour = pair("harbour", racy), strait = pair("strait", racy); +const passes = (schedule: Schedule, pairs = [harbour, strait], repetitions = 5, listed: readonly SpecPair[] = [harbour, strait, pair("harbour", steady)]) => { + const { vitest, collector, runs } = standIn(listed, schedule), lines: string[] = []; + let clock = 0; + return runPasses({ vitest, collector, pairs, repetitions, repo: REPO, log: line => lines.push(line), now: () => (clock += 500) }).then(outcome => ({ outcome, runs, lines })); +}; + +describe("further passes in one Vitest process", () => { + test("every selected pair runs every repetition, and only the selected pairs", async () => { + const { outcome, runs, lines } = await passes({}, [harbour]); + expect(outcome).toEqual({ failure: null, alsoFailed: [], passes: [1, 2, 3, 4, 5].map(repetition => ({ repetition, elapsedSeconds: 0.5, ok: true })) }); + // Exactly the pair, never the project's other files nor the file's other project. + expect(runs, "EXACT_PAIRS_EVERY_PASS").toEqual(Array.from({ length: 5 }, () => [`harbour::${racy}`])); + expect(lines).toEqual([1, 2, 3, 4, 5].map(repetition => `Repetition ${repetition} of 5: passed in 0.5 s (1 project/file pair(s) in 1 project(s), one project at a time).`)); + }); + + test("within a pass the projects run one after another, each with exactly its own pairs", async () => { + const pairs = [harbour, pair("harbour", steady), strait]; + const { outcome, runs } = await passes({}, pairs, 2); + expect(outcome.failure).toBeNull(); + // One browser at a time beside the burners: the load the spike measured, never every project at once. + expect(runs, "ONE_PROJECT_AT_A_TIME").toEqual([[`harbour::${racy}`, `harbour::${steady}`], [`strait::${racy}`], [`harbour::${racy}`, `harbour::${steady}`], [`strait::${racy}`]]); + }); + + test("a spec that passes twice and fails on its third pass fails the run at repetition three, with spec, project and case named", async () => { + const tide = "expected 'tide' to be 'crew' // Object.is equality"; + const { outcome, runs } = await passes({ fails: (repetition, key) => repetition % 3 === 0 && key === `strait::${racy}` ? tide : undefined }); + expect(outcome.failure, "SPEC_PROJECT_AND_REPETITION_NAMED").toEqual({ project: "strait", file: racy, repetition: 3, test: "the crew is aboard before the tide turns", reason: `a test case failed: ${tide}` }); + expect(outcome.passes.map(pass => pass.ok), "ONE_PASS_WOULD_HAVE_BEEN_GREEN").toEqual([true, true, false]); + expect(runs, "STOPS_AT_THE_FIRST_FAILING_REPETITION").toEqual([[`harbour::${racy}`], [`strait::${racy}`], [`harbour::${racy}`], [`strait::${racy}`], [`harbour::${racy}`], [`strait::${racy}`]]); + }); + + test("the first failing pair is named, its project's other failures are listed, and no later project runs in that repetition", async () => { + const { outcome, runs } = await passes({ fails: repetition => repetition === 2 ? "the tide won" : undefined }, [harbour, pair("harbour", steady), strait]); + expect(outcome.failure).toMatchObject({ project: "harbour", file: racy, repetition: 2 }); + expect(outcome.alsoFailed).toEqual([pair("harbour", steady)]); + expect(runs.slice(2), "THE_REPETITION_ENDS_AT_ITS_FIRST_FAILING_PROJECT").toEqual([[`harbour::${racy}`, `harbour::${steady}`]]); + }); + + test("a repetition counts only when Vitest reported each selected pair once in it", async () => { + // A pair with no result in the second pass must not pass on the strength of its first. + const silent = await passes({ silent: (repetition, key) => repetition === 2 && key === `strait::${racy}` }); + expect(silent.outcome.failure, "AN_EARLIER_RESULT_NEVER_STANDS_IN").toEqual({ project: "strait", file: racy, repetition: 2, test: null, + reason: "Vitest reported 0 results for this pair in the repetition; a repetition counts only when each pair is reported once" }); + const twice = await passes({ twice: (repetition, key) => repetition === 1 && key === `harbour::${racy}` }); + expect(twice.outcome.failure).toMatchObject({ project: "harbour", repetition: 1, reason: expect.stringContaining("Vitest reported 2 results") }); + }); + + test("a file that fails outside a test, and an error outside any file, fail the repetition", async () => { + const collection = await passes({ fails: (repetition, key) => repetition === 4 && key === `harbour::${racy}` ? null : undefined }); + expect(collection.outcome.failure).toEqual({ project: "harbour", file: racy, repetition: 4, test: null, reason: "No test suite found in file" }); + const unhandled = await passes({ unhandled: repetition => repetition === 2 ? "Browser connection was closed" : undefined }); + expect(unhandled.outcome.failure).toEqual({ project: null, file: null, repetition: 2, test: null, reason: "1 unhandled error(s) outside a test: Browser connection was closed" }); + }); + + test("a pair Vitest does not list runs nothing and fails before the first pass", async () => { + const { outcome, runs } = await passes({}, [harbour, pair("strait", steady)]); + expect(outcome.failure).toEqual({ project: "strait", file: steady, repetition: null, test: null, reason: "Vitest's own listing has no such project/file pair, so nothing would run" }); + expect(runs).toEqual([]); + }); + + 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 }); + 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"], + ["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); + }); +}); + +const alive = (pid: number) => { try { process.kill(pid, 0); return true; } catch { return false; } }; +async function gone(pid: number, withinMs: number): Promise { + for (const deadline = Date.now() + withinMs; Date.now() < deadline; await Bun.sleep(20)) if (!alive(pid)) return true; + return !alive(pid); +} + +describe("CPU burners inside the container", () => { + test("stop kills exactly the started PIDs, a second stop is harmless, and zero burners is a diagnosis", async () => { + const burners = startBurners(2, 5000); + try { + expect(burners.pids).toHaveLength(2); + for (const pid of burners.pids) expect(alive(pid), "BURNER_RUNNING").toBe(true); + } finally { burners.stop(); } + for (const pid of burners.pids) expect(await gone(pid, 2000), "BURNER_KILLED_BY_PID").toBe(true); + expect(() => burners.stop()).not.toThrow(); + expect(startBurners(0).pids).toEqual([]); + expect(() => startBurners(-1)).toThrow("non-negative integer"); + }); + + test("a burner whose parent is killed exits by itself within its slice", async () => { + // The parent is SIGKILLed, so no cleanup of its own can run. + const parent = Bun.spawn([process.execPath, "-e", + `const child = Bun.spawn([process.execPath, "-e", ${JSON.stringify(burnerSource(0, 5000))}.replace("parent=0", "parent=" + process.pid)], { stdio: ["ignore", "ignore", "ignore"] }); console.log(child.pid); await Bun.sleep(5000);`], + { stdout: "pipe", stderr: "inherit" }); + const reader = parent.stdout.getReader(); + const burner = Number(new TextDecoder().decode((await reader.read()).value).trim()); + try { + expect(Number.isSafeInteger(burner) && burner > 1, "BURNER_PID_REPORTED").toBe(true); + expect(alive(burner)).toBe(true); + parent.kill("SIGKILL"); await parent.exited; + expect(await gone(burner, 3000), "ORPHANED_BURNER_EXITS").toBe(true); + } finally { if (alive(burner)) process.kill(burner, "SIGKILL"); parent.kill("SIGKILL"); } + }); + + test("a burner never outlives its lifetime even with its parent alive", async () => { + const burners = startBurners(1, 300); + try { expect(await gone(burners.pids[0]!, 3000), "BURNER_LIFETIME_ENDS").toBe(true); } finally { burners.stop(); } + }); +}); + +describe("the command", () => { + const selection = [harbour, strait]; + const costs = { [pairKey(harbour)]: 4 }; + function checkout() { + const dir = mkdtempSync(join(tmpdir(), "browser-determinism-")); scratch.push(dir); + return dir; + } + /** A launcher that behaves as the container would: reads the plan the command wrote and writes a result beside it. */ + const container = (result: (plan: ReturnType) => object | undefined, exitCode: number, seen: { argv?: string[]; plan?: ReturnType } = {}) => + async (argv: string[], cwd: string) => { + seen.argv = argv; seen.plan = JSON.parse(readFileSync(join(cwd, "tmp/browser-determinism/plan.json"), "utf8")); + const written = result(seen.plan!); + if (written) { mkdirSync(dirname(join(cwd, seen.plan!.result)), { recursive: true }); writeFileSync(join(cwd, seen.plan!.result), JSON.stringify(written)); } + return exitCode; + }; + const green = (plan: ReturnType) => ({ kind: RESULT_KIND, version: 1, pairs: plan.pairs, repetitions: plan.repetitions, load: { burners: 4, cpus: 4 }, + passes: Array.from({ length: plan.repetitions }, (_, index) => ({ repetition: index + 1, elapsedSeconds: 1.5, ok: true })), failure: null, alsoFailed: [] }); + + test("it hands the container exactly its pairs, count and load, through the launcher with the pairs' projects", async () => { + 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(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(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"]); + }); + + test("the container's first failing repetition fails the command and names the spec, the project and the repetition", async () => { + const lines: string[] = []; + const failed = (plan: ReturnType) => ({ ...green(plan), passes: [{ repetition: 1, elapsedSeconds: 1, ok: true }, { repetition: 2, elapsedSeconds: 1, ok: true }, { repetition: 3, elapsedSeconds: 1, ok: false }], + failure: { project: "strait", file: racy, repetition: 3, test: "the crew is aboard before the tide turns", reason: "a test case failed: expected 'tide' to be 'crew'" }, alsoFailed: [harbour] }); + const report = await runBrowserDeterminism({ root: checkout(), pairs: selection, costs, launch: container(failed, 1), log: line => lines.push(line) }); + expect(report).toMatchObject({ outcome: "failed", exitCode: 1, alsoFailed: [harbour], + failure: { file: racy, project: "strait", repetition: 3, test: "the crew is aboard before the tide turns", reason: "a test case failed: expected 'tide' to be 'crew'" } }); + expect(lines).toContain(`FAILED: ${racy} in project strait, repetition 3 of 5: "the crew is aboard before the tide turns" (a test case failed: expected 'tide' to be 'crew').`); + expect(lines.at(-1)).toBe("A changed spec must pass every repetition. Fix the spec or what it exposes; a rerun is not a fix."); + const summary = summaryMarkdown(report); + expect(summary).toContain("### Changed browser specs under CPU load: failed"); + expect(summary).toContain(`**Failed:** \`${racy}\` in project \`strait\`, repetition 3, case \`the crew is aboard before the tide turns\``); + expect(summary).toContain(`| \`strait\` | \`${racy}\` | none (10 default) | 5 |`); + expect(summary).toContain("Pass seconds: 1.0, 1.0, 1.0 (failed)."); + }); + + test("a green exit is not a pass without a result that shows this plan's pairs and every repetition", async () => { + const run = (result: (plan: ReturnType) => object | undefined, exitCode = 0) => + runBrowserDeterminism({ root: checkout(), pairs: selection, costs, launch: container(result, exitCode), log: () => {} }).then(report => [report.outcome, report.exitCode, report.failure?.reason]); + expect(await run(green)).toEqual(["passed", 0, undefined]); + expect(await run(() => undefined), "NO_RESULT").toEqual(["failed", 1, "the pinned container exited 0 without a readable repetition result"]); + expect(await run(() => undefined, 137), "KILLED_CONTAINER").toEqual(["failed", 137, "the pinned container exited 137 without a readable repetition result"]); + // One pass only: the result a runner that skipped its further passes would write. + expect(await run(plan => ({ ...green(plan), passes: green(plan).passes.slice(0, 1) })), "ONE_PASS_IS_NOT_FIVE").toEqual(["failed", 1, + "ran 1 of 5 repetitions according to the container's result; a passing run must show every repetition"]); + expect(await run(plan => ({ ...green(plan), pairs: plan.pairs.slice(0, 1) })), "A_DROPPED_PAIR").toEqual(["failed", 1, "the container's result names another selection or repetition count than this plan"]); + expect(await run(plan => ({ ...green(plan), repetitions: 2 })), "ANOTHER_COUNT").toEqual(["failed", 1, "the container's result names another selection or repetition count than this plan"]); + expect(await run(plan => ({ ...green(plan), kind: "brain-test-determinism" })), "ANOTHER_KIND").toEqual(["failed", 1, "the pinned container exited 0 without a readable repetition result"]); + expect(await run(green, 1), "RED_EXIT_AFTER_GREEN_PASSES").toEqual(["failed", 1, "the pinned container exited 1 after reporting every repetition green"]); + expect(judge(planBrowserRepetitions(selection, { costs }), undefined, 0).failure?.repetition).toBeNull(); + }); + + test("no changed spec is no container run, and a stale result never survives into the next run", async () => { + let launched = 0; + const none = await runBrowserDeterminism({ root: checkout(), pairs: [], launch: async () => { launched++; return 0; }, log: () => {} }); + expect([none.outcome, none.exitCode, launched]).toEqual(["none-selected", 0, 0]); + expect(summaryMarkdown(none)).toContain("No added or modified browser, layout or story spec."); + const root = checkout(); + const first = await runBrowserDeterminism({ root, pairs: selection, costs, launch: container(green, 0), log: () => {} }); + expect(first.outcome).toBe("passed"); + // The second container writes nothing: the first run's green result must not be read again. + const second = await runBrowserDeterminism({ root, pairs: selection, costs, launch: container(() => undefined, 0), log: () => {} }); + expect(second.outcome, "STALE_RESULT_REMOVED").toBe("failed"); + }); + + test("arguments name either a base or explicit project/file pairs, never both or neither", () => { + expect(parseArguments(["--base", "origin/main", "--json"])).toEqual({ base: "origin/main", pairs: [], json: true }); + expect(parseArguments(["--report=tmp/r.json", "--burners", "0", "--repetitions=3", "--budget-seconds", "90", "--cpu-list=12-15", "--config-root", "tests/fixtures/browser-determinism", `harbour::${racy}`])) + .toEqual({ pairs: [harbour], json: false, report: "tmp/r.json", burners: 0, repetitions: 3, budgetSeconds: 90, cpuList: "12-15", configRoot: "tests/fixtures/browser-determinism" }); + for (const args of [[], ["--json"], ["--base", "origin/main", `harbour::${racy}`], ["--repetitions", "1", `harbour::${racy}`], ["--base"], ["--unknown", `harbour::${racy}`], + [racy], ["--cpu-list", "all", `harbour::${racy}`], ["--config-root", "../elsewhere", `harbour::${racy}`], ["--burners", "-1", `harbour::${racy}`]]) { + expect(() => parseArguments(args), args.join(" ")).toThrow("usage:"); + } + }); +}); diff --git a/tests/candidate-proof.test.ts b/tests/candidate-proof.test.ts index dcf3dc3248..f97818878c 100644 --- a/tests/candidate-proof.test.ts +++ b/tests/candidate-proof.test.ts @@ -26,12 +26,12 @@ test("events distinguish cheap drafts, fast pushes, explicit final requests and expect(() => proofCadence({ GITHUB_EVENT_NAME: "unknown" }, {})).toThrow("Unknown proof event"); const plan = planChecks(["package.json"], [{ dir: "ui-react", name: "@fixture/ui-react", dependencies: [], files: ["src"] }]); plan.cadence = "feedback"; - expect(proofSelections(plan)).toEqual({ verify: true, pack: false, unit: false, browser: false, layout: false, captures: false, runtime: false, runtime_host: false, endurance: false, determinism: false }); + expect(proofSelections(plan)).toEqual({ verify: true, pack: false, unit: false, browser: false, layout: false, captures: false, runtime: false, runtime_host: false, endurance: false, determinism: false, browser_determinism: false }); plan.cadence = "confirmation"; // Hybrid ruling: ready confirmation runs the fast categories; heavy categories run on main. - expect(proofSelections(plan), "CONFIRMATION_RUNS_FAST_CATEGORIES_ONLY").toEqual({ verify: true, pack: true, unit: true, browser: false, layout: false, captures: false, runtime: false, runtime_host: false, endurance: false, determinism: false }); + expect(proofSelections(plan), "CONFIRMATION_RUNS_FAST_CATEGORIES_ONLY").toEqual({ verify: true, pack: true, unit: true, browser: false, layout: false, captures: false, runtime: false, runtime_host: false, endurance: false, determinism: false, browser_determinism: false }); // Repeating changed tests is pre-merge proof; main and exhaustive runs never select it (#4109). - const exceptRepetition = () => { const { determinism, ...rest } = proofSelections(plan); expect(determinism, "NO_REPETITION_AFTER_MERGE").toBe(false); return Object.values(rest); }; + const exceptRepetition = () => { const { determinism, browser_determinism, ...rest } = proofSelections(plan); expect([determinism, browser_determinism], "NO_REPETITION_AFTER_MERGE").toEqual([false, false]); return Object.values(rest); }; plan.cadence = "integrated"; expect(exceptRepetition().every(Boolean), "MAIN_RUNS_EVERY_SELECTED_CATEGORY").toBe(true); plan.cadence = "exhaustive"; diff --git a/tests/ci-plan.test.ts b/tests/ci-plan.test.ts index 89fc74e776..446f8b96cc 100644 --- a/tests/ci-plan.test.ts +++ b/tests/ci-plan.test.ts @@ -2,7 +2,7 @@ import { afterEach, describe, expect, test } from "bun:test"; import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync, chmodSync, symlinkSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; -import { changedFiles, FAST_TESTS, FILE_INPUT_TESTS, planChecks, planUnitChecks, planFromEnvironment, workspaces, proofSelections, rootConsumers, ROOT_CONSUMERS, unitShards, determinismShards, selectBrowserClosures, proofCadence } from "../scripts/ci-plan"; +import { changedFiles, FAST_TESTS, FILE_INPUT_TESTS, planChecks, planUnitChecks, planFromEnvironment, workspaces, proofSelections, rootConsumers, ROOT_CONSUMERS, unitShards, determinismShards, browserDeterminismShards, selectBrowserClosures, proofCadence } from "../scripts/ci-plan"; import { planPartitions } from "../scripts/determinism-plan"; import { FILE_COST_SECONDS } from "../scripts/test-shards"; @@ -37,7 +37,7 @@ function fixture() { /** The real planner executable inside a fixture repository whose HEAD changes one core source file. */ function plannerFixture() { const f = fixture(); f.write("scripts/ci-plan.ts", readFileSync(join(import.meta.dir, "../scripts/ci-plan.ts"), "utf8").replace('"typescript"', JSON.stringify(import.meta.resolve("typescript")))); - for (const name of ["browser-input-closure", "unit-test-consumers", "integration-reservation", "red-main", "proof-shards", "determinism-plan"]) f.write(`scripts/${name}.ts`, `export * from ${JSON.stringify(resolve(import.meta.dir, `../scripts/${name}.ts`))};\n`); + for (const name of ["browser-input-closure", "unit-test-consumers", "integration-reservation", "red-main", "proof-shards", "determinism-plan", "browser-determinism-plan"]) f.write(`scripts/${name}.ts`, `export * from ${JSON.stringify(resolve(import.meta.dir, `../scripts/${name}.ts`))};\n`); f.write("packages/core/src/note.ts", "export const note = 2;\n"); f.git("add", "."); f.git("commit", "-qm", "planner fixture"); return f; @@ -240,7 +240,7 @@ describe("affected CI checks", () => { const [code, err] = await Promise.all([child.exited, new Response(child.stderr).text()]); expect(code, err).toBe(0); const expected = proofSelections(JSON.parse(readFileSync(plan, "utf8")), draft === "true"); - expect(readFileSync(output, "utf8")).toBe(`unit_shards=${draft === "true" ? "[1,2,3,4]" : "[1,2,3,4,5,6,7,8]"}\ndeterminism_shards=[1]\ncadence=${draft === "true" ? "draft" : "confirmation"}\nred_main_oid=\n` + Object.entries(expected).map(([name, value]) => `${name}=${value}\n`).join("")); + expect(readFileSync(output, "utf8")).toBe(`unit_shards=${draft === "true" ? "[1,2,3,4]" : "[1,2,3,4,5,6,7,8]"}\ndeterminism_shards=[1]\nbrowser_determinism_shards=[1]\ncadence=${draft === "true" ? "draft" : "confirmation"}\nred_main_oid=\n` + Object.entries(expected).map(([name, value]) => `${name}=${value}\n`).join("")); expect(expected.unit).toBe(draft === "false"); // Ready confirmation leaves heavy runtime proof to the squash's main run (hybrid ruling). expect(expected.runtime, "CONFIRMATION_DEFERS_RUNTIME").toBe(false); @@ -378,8 +378,8 @@ describe("file-reading invariant inputs", () => { expect(plan.global, path).toBe(true); expect(plan.unitTests, path).toBeUndefined(); expect(plan.affected).toEqual(packages.map(pkg => pkg.dir).sort()); expect(Object.values(plan.local).every(Boolean), path).toBe(true); - const { determinism, ...selections } = proofSelections(plan); - expect(determinism, path).toBe(false); + const { determinism, browser_determinism, ...selections } = proofSelections(plan); + expect([determinism, browser_determinism], path).toEqual([false, false]); expect(Object.values(selections).every(Boolean), path).toBe(true); expect(plan.pack).toBe(true); expect(plan.typecheck).toBe(true); } @@ -558,7 +558,7 @@ describe("changed Bun test files repeat under load before merge (#4109)", () => const env = { GITHUB_EVENT_NAME: "pull_request", GITHUB_SHA: head }; const event = { action: "synchronize", pull_request: { draft: true, base: { sha: before }, head: { sha: head } } }; const plan = planFromEnvironment(f.dir, { ...env, BASE_SHA: before, HEAD_SHA: head }); plan.cadence = "draft"; - return { env, event, outputs: { cadence: "draft", determinism_shards: JSON.stringify(determinismShards(plan)), + return { env, event, outputs: { cadence: "draft", determinism_shards: JSON.stringify(determinismShards(plan)), browser_determinism_shards: "[1]", ...Object.fromEntries(Object.entries(proofSelections(plan)).map(([name, on]) => [name, String(on)])) } as Record }; }; const selected = outputsFor(withTest, base); @@ -635,6 +635,139 @@ describe("changed Bun test files repeat under load before merge (#4109)", () => }); }); +describe("changed browser specs repeat under load before merge (#4163)", () => { + const cadences = ["draft", "feedback", "confirmation", "feedback-heavy", "integrated", "exhaustive"] as const; + const stories = "packages/ui-kit/stories", browser = "packages/ui-react/tests/browser"; + const fleet = Array.from({ length: 114 }, (_, index) => `${stories}/Fleet${String(index).padStart(3, "0")}.stories.tsx`); + /** What the installed runner lists for the fixture's specs: a spec once per project that includes it. */ + const listing: [string, string][] = [ + ["visual", "packages/ui-kit/tests/visual/sails.visual.tsx"], + ...[`${stories}/Sail.stories.tsx`, ...fleet].flatMap(file => [["storybook", file], ["storybook-light", file]] as [string, string][]), + ...["rail-coarse", "rail-fine", "rail-mixed"].map(project => [project, `${browser}/oars.pointer.tsx`] as [string, string]), + ["ui-react-layout", `${browser}/deck.layout.tsx`], ["ui-react-layout", `${browser}/offline/fog.offline.tsx`], + ["ui-react-endurance", `${browser}/watch.endurance.tsx`], + ]; + const pair = (project: string, file: string) => ({ project, file }); + /** The planner executable in a repository whose Vitest is a stand-in that prints `listing`, as `vitest list --filesOnly --json` would. */ + function specFixture(lists = true) { + const f = plannerFixture(); + f.write("scripts/visual.mjs", 'const projects = projectArgs.length ? [] : ["visual", "storybook", "storybook-light", "rail-coarse", "rail-fine", "rail-mixed"];\n'); + f.write("node_modules/vitest/vitest.mjs", lists ? `import { writeFileSync } from "node:fs";\nimport { resolve } from "node:path";\n` + + `const output = process.argv.find(argument => argument.startsWith("--json=")).slice("--json=".length);\n` + + `writeFileSync(output, JSON.stringify(${JSON.stringify(listing)}.map(([project, file]) => ({ projectName: project + " (chromium)", file: resolve(process.cwd(), "../..", file) }))));\n` + : "process.exit(1);\n"); + for (const file of ["packages/ui-kit/tests/visual/sails.visual.tsx", `${stories}/Sail.stories.tsx`, `${browser}/oars.pointer.tsx`, `${browser}/deck.layout.tsx`, + `${browser}/offline/fog.offline.tsx`, `${browser}/watch.endurance.tsx`, `${browser}/offline/fault-network.ts`]) f.write(file, "export {};\n"); + f.git("add", "-f", "."); f.git("commit", "-qm", "specs and their listing"); + return { ...f, base: f.git("rev-parse", "HEAD") }; + } + const commit = (f: ReturnType, message: string) => { f.git("add", "-f", "."); f.git("commit", "-qm", message); return f.git("rev-parse", "HEAD"); }; + async function execute(f: ReturnType, base: string, head: string, draft: boolean) { + const output = join(f.dir, "outputs-specs"), eventPath = join(f.dir, "event-specs.json"); + rmSync(output, { force: true }); + const event = { action: draft ? "synchronize" : "ready_for_review", pull_request: { draft, base: { sha: base }, head: { sha: head } } }; + writeFileSync(eventPath, JSON.stringify(event)); + const child = Bun.spawn([process.execPath, join(f.dir, "scripts/ci-plan.ts")], { cwd: f.dir, stdout: "pipe", stderr: "pipe", + env: { ...process.env, BEFORE_SHA: "", FEEDBACK_PR: "", RED_MAIN_OID: "", PR_DRAFT: "", GITHUB_EVENT_NAME: "pull_request", BASE_SHA: base, HEAD_SHA: head, + GITHUB_EVENT_PATH: eventPath, GITHUB_OUTPUT: output, CI_PLAN_PATH: join(f.dir, "plan-specs.json") } }); + const [code, err] = await Promise.all([child.exited, new Response(child.stderr).text()]); + return { code, err, event, outputs: existsSync(output) ? Object.fromEntries(readFileSync(output, "utf8").trim().split("\n").map(line => line.split("="))) as Record : {} }; + } + + test("a pull request selects the specs it adds or modifies, as the project/file pairs Vitest lists, and never on main", () => { + const f = specFixture(); + f.write(`${browser}/oars.pointer.tsx`, "export {}; // changed\n"); f.write(`${stories}/Sail.stories.tsx`, "export {}; // changed\n"); + f.write(`${browser}/offline/fog.offline.tsx`, "export {}; // changed\n"); f.write(fleet[0]!, "export {};\n"); + // Not selected: the endurance spec, a helper beside the specs, and a spec the change deletes. + f.write(`${browser}/watch.endurance.tsx`, "export {}; // changed\n"); f.write(`${browser}/offline/fault-network.ts`, "export {}; // changed\n"); + f.git("rm", "-q", `${browser}/deck.layout.tsx`); commit(f, "change specs"); + const plan = planFromEnvironment(f.dir, { GITHUB_EVENT_NAME: "pull_request", BASE_SHA: f.base, HEAD_SHA: "HEAD" }); + expect(plan.changed, "DELETION_AND_HELPER_ARE_IN_THE_DIFF").toEqual(expect.arrayContaining([`${browser}/deck.layout.tsx`, `${browser}/offline/fault-network.ts`, `${browser}/watch.endurance.tsx`])); + expect(plan.browserDeterminism, "ADDED_AND_MODIFIED_SPECS_AS_LISTED_PAIRS").toEqual([ + pair("rail-coarse", `${browser}/oars.pointer.tsx`), pair("rail-fine", `${browser}/oars.pointer.tsx`), pair("rail-mixed", `${browser}/oars.pointer.tsx`), + pair("storybook-light", fleet[0]!), pair("storybook-light", `${stories}/Sail.stories.tsx`), + pair("storybook", fleet[0]!), pair("storybook", `${stories}/Sail.stories.tsx`), + pair("ui-react-layout", `${browser}/offline/fog.offline.tsx`), + ]); + const selected = Object.fromEntries(cadences.map(cadence => [cadence, proofSelections({ ...plan, cadence }).browser_determinism])); + expect(selected, "EVERY_PULL_REQUEST_CADENCE").toEqual({ draft: true, feedback: true, confirmation: true, "feedback-heavy": true, integrated: false, exhaustive: false }); + // A draft keeps every other category off: with no Bun test changed, this job is the only one. + expect(Object.entries(proofSelections({ ...plan, cadence: "draft" })).filter(([, on]) => on).map(([name]) => name), "DRAFT_RUNS_ONLY_REPETITION").toEqual(["browser_determinism"]); + expect(proofSelections(plan, true).browser_determinism, "PR_DRAFT_FLAG_KEEPS_REPETITION").toBe(true); + const heavy = planFromEnvironment(f.dir, { GITHUB_EVENT_NAME: "workflow_dispatch", BASE_SHA: f.base, HEAD_SHA: "HEAD", FEEDBACK_PR: "7" }); + expect(heavy.browserDeterminism, "DRAFT_HEAVY_FEEDBACK_SELECTS_THE_SAME").toEqual(plan.browserDeterminism!); + // The squash's specs were repeated before they merged; its main run runs each of them once. + const main = planFromEnvironment(f.dir, { GITHUB_EVENT_NAME: "push", BEFORE_SHA: f.base, HEAD_SHA: "HEAD" }); + expect(main.browserDeterminism, "MAIN_NEVER_REPEATS").toBeUndefined(); + expect(browserDeterminismShards({ ...main, cadence: "integrated" })).toEqual([1]); + }); + + test("a pull request that changes no spec does not select the job, and the aggregate requires its skip", async () => { + const { validateSelections } = await import("../scripts/candidate-proof"); + const f = specFixture(); + f.write("docs/voyage.md", "Ithaca lies west.\n"); f.write(`${browser}/offline/fault-network.ts`, "export {}; // changed\n"); + f.write(`${browser}/watch.endurance.tsx`, "export {}; // changed\n"); const withoutSpec = commit(f, "a helper, the endurance spec and prose"); + const plan = planFromEnvironment(f.dir, { GITHUB_EVENT_NAME: "pull_request", BASE_SHA: f.base, HEAD_SHA: withoutSpec }); + expect(plan.browserDeterminism, "A_HELPER_SELECTS_NOTHING").toBeUndefined(); + for (const cadence of cadences) expect(proofSelections({ ...plan, cadence }).browser_determinism, cadence).toBe(false); + const env = { GITHUB_EVENT_NAME: "pull_request", GITHUB_SHA: withoutSpec }; + const unselected = await execute(f, f.base, withoutSpec, true); + expect(unselected.code, unselected.err).toBe(0); + expect([unselected.outputs.browser_determinism, unselected.outputs.browser_determinism_shards], "NOT_SELECTED").toEqual(["false", "[1]"]); + expect(() => validateSelections(f.dir, unselected.event, env, unselected.outputs), "THE_SKIP_IS_ACCEPTED").not.toThrow(); + expect(() => validateSelections(f.dir, unselected.event, env, { ...unselected.outputs, browser_determinism: "true" }), "ADDED_SELECTION_REFUSED") + .toThrow("browser_determinism: required candidate selection differs from actual inputs"); + // The reverse: a head that changes a spec cannot publish the job as unselected. + f.write(`${browser}/oars.pointer.tsx`, "export {}; // changed\n"); const withSpec = commit(f, "a pointer spec"); + const selected = await execute(f, withoutSpec, withSpec, true); + expect([selected.code, selected.outputs.browser_determinism, selected.outputs.browser_determinism_shards], selected.err).toEqual([0, "true", "[1]"]); + expect(() => validateSelections(f.dir, selected.event, { ...env, GITHUB_SHA: withSpec }, { ...selected.outputs, browser_determinism: "false" }), "DROPPED_SELECTION_REFUSED") + .toThrow("browser_determinism: required candidate selection differs from actual inputs"); + }); + + test("the executable publishes the planned partitions, the aggregate refuses any other set, and a selection past the maximum fails before any runner starts", async () => { + const { validateSelections } = await import("../scripts/candidate-proof"); + const f = specFixture(); + // Eight new stories in two themes: sixteen unweighted pairs at the 10 s default, 160 weighted s per pass, 320 at the floor of two. + for (const file of fleet.slice(0, 8)) f.write(file, "export {};\n"); + const head = commit(f, "a fleet of stories"); + for (const draft of [true, false]) { + const planned = await execute(f, f.base, head, draft); + expect(planned.code, planned.err).toBe(0); + expect([planned.outputs.browser_determinism, planned.outputs.browser_determinism_shards], `SPLIT_BY_WEIGHT:draft=${draft}`).toEqual(["true", "[1,2]"]); + const env = { GITHUB_EVENT_NAME: "pull_request", GITHUB_SHA: head }; + expect(() => validateSelections(f.dir, planned.event, env, planned.outputs), "PLANNED_SET_ACCEPTED").not.toThrow(); + const { browser_determinism_shards: _dropped, ...missing } = planned.outputs; + for (const [label, outputs] of [["DROPPED_PARTITION", { ...planned.outputs, browser_determinism_shards: "[1]" }], ["EXTRA_PARTITION", { ...planned.outputs, browser_determinism_shards: "[1,2,3]" }], + ["REORDERED", { ...planned.outputs, browser_determinism_shards: "[2,1]" }], ["MISSING_OUTPUT", missing]] as const) { + expect(() => validateSelections(f.dir, planned.event, env, outputs), `${label}:draft=${draft}`).toThrow("browser_determinism: published partition set differs from the planned one"); + } + } + // 113 stories are 226 pairs: 2,260 weighted s per pass, 4,520 at the floor, one pair more than fifteen partitions hold. + for (const file of fleet.slice(8, 113)) f.write(file, "export {};\n"); + const armada = commit(f, "an armada of stories"); + const refused = await execute(f, f.base, armada, true); + expect(refused.code, "METADATA_JOB_FAILS_BEFORE_ANY_PARTITION").toBe(1); + expect(refused.err).toContain("Repeated browser proof refused before it ran: 226 changed project/file pair(s) weigh 2260.0 weighted s per pass, 4520.0 s at the floor of 2 repetitions. " + + "That needs more than the limit of 15 partitions of 300 weighted s each (BROWSER_DETERMINISM_PARTITIONS, scripts/proof-shards.ts). No pair is skipped and the count stays at the floor: split the change."); + expect(refused.outputs, "NOTHING_PUBLISHED").toEqual({}); + }); + + test("a changed spec that no project lists, or a listing that cannot be read, fails the plan instead of skipping the repetition", () => { + const f = specFixture(); + f.write(`${browser}/stray.pointer.tsx`, "export {};\n"); const stray = commit(f, "a pointer spec no rail project includes"); + expect(() => planFromEnvironment(f.dir, { GITHUB_EVENT_NAME: "pull_request", BASE_SHA: f.base, HEAD_SHA: stray }), "UNLISTED_SPEC_REFUSED") + .toThrow(`${browser}/stray.pointer.tsx is a changed spec that no Vitest project lists, so nothing runs it`); + const blind = specFixture(false); + blind.write(`${browser}/oars.pointer.tsx`, "export {}; // changed\n"); const changed = commit(blind, "a pointer spec"); + expect(() => planFromEnvironment(blind.dir, { GITHUB_EVENT_NAME: "pull_request", BASE_SHA: blind.base, HEAD_SHA: changed }), "NO_LISTING_NO_SILENT_SKIP") + .toThrow("Cannot expand 1 changed browser spec(s) to project/file pairs: Installed Vitest discovery failed"); + // Without a changed spec the same unreadable listing only leaves category selection broad. + blind.write("docs/voyage.md", "Ithaca lies west.\n"); const prose = commit(blind, "prose"); + expect(planFromEnvironment(blind.dir, { GITHUB_EVENT_NAME: "pull_request", BASE_SHA: changed, HEAD_SHA: prose }).browserDeterminism).toBeUndefined(); + }); +}); + describe("main aggregate re-plans with the metadata job's red-main set (#3541)", () => { test("a push whose open incident widens the selection validates only with that snapshot", async () => { const { validateSelections } = await import("../scripts/candidate-proof"); diff --git a/tests/ci-workflows.test.ts b/tests/ci-workflows.test.ts index 991ed39ad7..301915c4b1 100644 --- a/tests/ci-workflows.test.ts +++ b/tests/ci-workflows.test.ts @@ -5,7 +5,7 @@ import { tmpdir } from "node:os"; import { dirname, join, resolve } from "node:path"; import { CI_WORKFLOWS, checkCIWorkflows, publicationWorkflowProblems, workflowProblems } from "../scripts/check-ci-workflows.ts"; import { ACTION_PINS, actionPinProblems, annotateActionPins, pinned } from "../scripts/action-pins.ts"; -import { DETERMINISM_PARTITIONS } from "../scripts/proof-shards.ts"; +import { BROWSER_DETERMINISM_PARTITIONS, DETERMINISM_PARTITIONS } from "../scripts/proof-shards.ts"; const ROOT = resolve(import.meta.dir, ".."); type Json = null | boolean | number | string | Json[] | { [key: string]: Json }; type Obj = { [key: string]: Json }; @@ -30,7 +30,7 @@ const pullRequest = (headRepo: string | null, extra: Obj = {}): Obj => ({ }); function runs(workflow: Workflow, job: Job, context: Obj): boolean { return String(context.event_name) in workflow.on && (job.if === undefined || evaluate(job.if, { - github: context, needs: { changeset: { result: "success", outputs: { verify: "true", pack: "true", unit: "true", runtime: "true", runtime_host: "true", browser: "true", layout: "true", captures: "true", endurance: "true", determinism: "true" } }, pack: { result: "success" } }, + github: context, needs: { changeset: { result: "success", outputs: { verify: "true", pack: "true", unit: "true", runtime: "true", runtime_host: "true", browser: "true", layout: "true", captures: "true", endurance: "true", determinism: "true", browser_determinism: "true" } }, pack: { result: "success" } }, }) === true); } function evaluate(expression: string, context: Obj): Json { @@ -132,9 +132,9 @@ describe("the authoritative jobs retain their important phases", () => { expect(ci.name).toBe("CI"); expect(ci.on.push).toEqual({ branches: ["main"] }); expect(ci.on.pull_request).toEqual({ types: ["opened", "synchronize", "reopened", "ready_for_review", "converted_to_draft"] }); - expect(Object.keys(ci.jobs)).toEqual(["changeset", "verify", "pack", "unit", "runtime", "runtime_host", "browser", "layout", "captures", "endurance", "determinism", "proof"]); + expect(Object.keys(ci.jobs)).toEqual(["changeset", "verify", "pack", "unit", "runtime", "runtime_host", "browser", "layout", "captures", "endurance", "determinism", "browser_determinism", "proof"]); // The planner step is the only source of a metadata output: no later step can deselect a category (#4107). - expect(ci.jobs.changeset!.outputs).toEqual(Object.fromEntries(["verify", "pack", "unit", "browser", "layout", "captures", "runtime", "runtime_host", "endurance", "determinism", "cadence", "unit_shards", "determinism_shards", "red_main_oid"].map(name => [name, `\${{ steps.plan.outputs.${name} }}`]))); + expect(ci.jobs.changeset!.outputs).toEqual(Object.fromEntries(["verify", "pack", "unit", "browser", "layout", "captures", "runtime", "runtime_host", "endurance", "determinism", "browser_determinism", "cadence", "unit_shards", "determinism_shards", "browser_determinism_shards", "red_main_oid"].map(name => [name, `\${{ steps.plan.outputs.${name} }}`]))); const metadata = ci.jobs.changeset!.steps.filter(s => s.run).map(s => s.run); expect(metadata).toContain("bun scripts/ci-plan.ts"); expect(metadata).toContain("bun run lint"); expect(metadata).toContain("bun scripts/env-docs.ts --check"); expect(metadata).toContain("bun scripts/check-changeset-packages.ts"); @@ -252,16 +252,16 @@ describe("CI concurrency configuration (live scheduler proof remains separate)", }); describe("independent hosted proof after cheap gates", () => { - const context = (selected = "true", result = "success") => ({ needs: { changeset: { result, outputs: { verify: selected, pack: selected, unit: selected, runtime: selected, runtime_host: selected, browser: selected, layout: selected, captures: selected, endurance: selected, determinism: selected } } } }); + const context = (selected = "true", result = "success") => ({ needs: { changeset: { result, outputs: { verify: selected, pack: selected, unit: selected, runtime: selected, runtime_host: selected, browser: selected, layout: selected, captures: selected, endurance: selected, determinism: selected, browser_determinism: selected } } } }); test("all independent categories depend only on metadata", () => { - for (const name of ["verify", "pack", "unit", "runtime", "runtime_host", "browser", "layout", "captures", "endurance", "determinism"]) { + for (const name of ["verify", "pack", "unit", "runtime", "runtime_host", "browser", "layout", "captures", "endurance", "determinism", "browser_determinism"]) { expect(ci.jobs[name]!.needs).toBe("changeset"); expect(evaluate(ci.jobs[name]!.if!, context())).toBe(true); expect(evaluate(ci.jobs[name]!.if!, context("false"))).toBe(false); } }); test("the aggregate observes every category even after an intentional skip or failed prerequisite", () => { - expect(ci.jobs.proof!.needs).toEqual(["changeset", "verify", "pack", "unit", "runtime", "runtime_host", "browser", "layout", "captures", "endurance", "determinism"]); + expect(ci.jobs.proof!.needs).toEqual(["changeset", "verify", "pack", "unit", "runtime", "runtime_host", "browser", "layout", "captures", "endurance", "determinism", "browser_determinism"]); expect(ci.jobs.proof!.if).toContain("always()"); expect(evaluate(ci.jobs.proof!.if!, { cancelled: false })).toBe(true); expect(evaluate(ci.jobs.proof!.if!, { cancelled: true })).toBe(false); @@ -270,11 +270,11 @@ describe("independent hosted proof after cheap gates", () => { for (const repo of [REPO, "odysseus/brain-kit"]) { const c = { github: pullRequest(repo), ...context("false") }; expect(ci.jobs.changeset!.if).toBeUndefined(); - for (const name of ["verify", "pack", "unit", "runtime", "runtime_host", "browser", "layout", "captures", "endurance", "determinism"]) expect(evaluate(ci.jobs[name]!.if!, c)).toBe(false); + for (const name of ["verify", "pack", "unit", "runtime", "runtime_host", "browser", "layout", "captures", "endurance", "determinism", "browser_determinism"]) expect(evaluate(ci.jobs[name]!.if!, c)).toBe(false); } }); test("a selected category runs on the planner's selection alone; no other output can skip it (#4107)", () => { - for (const name of ["verify", "pack", "unit", "runtime", "runtime_host", "browser", "layout", "captures", "endurance", "determinism"]) { + for (const name of ["verify", "pack", "unit", "runtime", "runtime_host", "browser", "layout", "captures", "endurance", "determinism", "browser_determinism"]) { expect(ci.jobs[name]!.if, `SELECTION_ALONE:${name}`).toBe(`\${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && needs.changeset.outputs.${name} == 'true' }}`); // The outputs retention used to set are gone; their absence must not skip a selected job. const selected = context(); @@ -603,7 +603,7 @@ test("the determinism job has the unit job's prerequisites and both aggregates o expect(feedback.jobs.determinism!.strategy, "DRAFT_HEAVY_FEEDBACK_SPLITS_TOO").toEqual(job.strategy); expect(feedback.jobs.aggregate!.needs).toContain("determinism"); expect(workflowProblems(original, "ci.yml")).toEqual([]); - expect(workflowProblems(original.replace("captures, endurance, determinism]", "captures, endurance]"), "ci.yml"), "PROOF_MUST_OBSERVE_IT").toContain("ci.yml: proof: aggregate must observe every selected category"); + expect(workflowProblems(original.replace("captures, endurance, determinism, browser_determinism]", "captures, endurance, browser_determinism]"), "ci.yml"), "PROOF_MUST_OBSERVE_IT").toContain("ci.yml: proof: aggregate must observe every selected category"); expect(workflowProblems(original.replace(`run: ${REPEAT}\n`, "run: echo omitted\n"), "ci.yml")).toContain("ci.yml: determinism: complete proof command is missing"); expect(workflowProblems(original.replace("needs.changeset.outputs.determinism == 'true' }}", "needs.changeset.outputs.unit == 'true' }}"), "ci.yml")).toContain("ci.yml: determinism: proof must run on its explicit planner selection alone"); const withoutSetup = original.slice(0, original.indexOf(" determinism:\n")) + original.slice(original.indexOf(" determinism:\n")).replace("run: bash scripts/ci-runtime-setup.sh\n", "run: bash scripts/ci-runtime-setup.sh --native\n"); @@ -743,9 +743,66 @@ test("verify successful step requires final marker and zero unsignalled finishes } finally { rmSync(dir, { recursive: true, force: true }); } }); +test("the browser repetition job enters the pinned container as the browser jobs do, and both aggregates observe it (#4163)", () => { + const original = read("ci.yml"); + const job = ci.jobs.browser_determinism!, layout = ci.jobs.layout!; + const REPEAT = 'bun scripts/ci-proof.ts browser_determinism --shard=${{ matrix.shard }}/"$BROWSER_REPEAT_SHARDS"'; + const runs = (steps: typeof job.steps) => steps.filter(step => step.run).map(step => step.run); + // A container job: the layout job's install and plan, and no native runtime setup. + for (const command of ["bun install --frozen-lockfile", "bun scripts/ci-plan.ts"]) { + expect(runs(layout.steps), command).toContain(command); + expect(runs(job.steps), `CONTAINER_PREREQUISITE:${command}`).toContain(command); + } + expect(runs(job.steps)).toEqual(["bun install --frozen-lockfile", "bun scripts/ci-plan.ts", REPEAT]); + expect(job.if).toBe("${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && needs.changeset.outputs.browser_determinism == 'true' }}"); + expect((ci.jobs.changeset!.outputs as Obj).browser_determinism).toBe("${{ steps.plan.outputs.browser_determinism }}"); + const feedback = Bun.YAML.parse(read("heavy-feedback.yml")) as Workflow; + expect(runs(feedback.jobs.browser_determinism!.steps), "DRAFT_HEAVY_FEEDBACK_REPEATS_TOO").toContain(REPEAT); + expect(feedback.jobs.browser_determinism!.strategy, "DRAFT_HEAVY_FEEDBACK_SPLITS_TOO").toEqual(job.strategy); + expect(feedback.jobs.aggregate!.needs).toContain("browser_determinism"); + expect(ci.jobs.proof!.needs).toContain("browser_determinism"); + expect(workflowProblems(original.replace("endurance, determinism, browser_determinism]", "endurance, determinism]"), "ci.yml"), "PROOF_MUST_OBSERVE_IT").toContain("ci.yml: proof: aggregate must observe every selected category"); + expect(workflowProblems(original.replace(`run: ${REPEAT}\n`, "run: echo omitted\n"), "ci.yml")).toContain("ci.yml: browser_determinism: complete proof command is missing"); + expect(workflowProblems(original.replace("needs.changeset.outputs.browser_determinism == 'true' }}", "needs.changeset.outputs.browser == 'true' }}"), "ci.yml")).toContain("ci.yml: browser_determinism: proof must run on its explicit planner selection alone"); + const withoutJob = original.slice(0, original.indexOf(" browser_determinism:\n # A changed")) + original.slice(original.indexOf(" proof:\n")); + expect(workflowProblems(withoutJob, "ci.yml"), "THE_JOB_IS_REQUIRED").toContain("ci.yml: missing or unexpected CI jobs"); +}); + +test("the browser repetition matrix, divisor and step limit come from the planner and its one owner (#4163)", () => { + const text = read("ci.yml"), job = ci.jobs.browser_determinism!; + expect(job.strategy).toEqual({ "fail-fast": false, matrix: { shard: "${{ fromJSON(needs.changeset.outputs.browser_determinism_shards) }}" } }); + const step = job.steps.find(s => s.name === "Repeat changed browser, layout and story specs under CPU load")!; + expect(step.env?.BROWSER_REPEAT_SHARDS).toBe("${{ strategy.job-total }}"); + expect(step.run).toBe('bun scripts/ci-proof.ts browser_determinism --shard=${{ matrix.shard }}/"$BROWSER_REPEAT_SHARDS"'); + expect(step["timeout-minutes"], "STEP_LIMIT_HAS_ONE_OWNER").toBe(BROWSER_DETERMINISM_PARTITIONS.stepMinutes); + expect(job["timeout-minutes"], "JOB_COVERS_THE_STEP").toBe(BROWSER_DETERMINISM_PARTITIONS.stepMinutes + 5); + expect(job.steps.find(s => s.uses === pinned("actions/upload-artifact@v7"))!.with!.name, "ONE_ARTIFACT_PER_PARTITION").toBe("browser-determinism-proof-${{ matrix.shard }}"); + expect(workflowProblems(text, "ci.yml")).toEqual([]); + const problem = "browser_determinism: matrix and shard divisor must come from the planner's browser_determinism_shards output"; + const matrix = " shard: ${{ fromJSON(needs.changeset.outputs.browser_determinism_shards) }}\n"; + const command = 'browser_determinism --shard=${{ matrix.shard }}/"$BROWSER_REPEAT_SHARDS"'; + for (const [label, from, to, refusal] of [ + ["LITERAL_ONE_MATRIX", matrix, " shard: [1]\n", problem], + ["LITERAL_MAXIMUM_MATRIX", matrix, ` shard: [${Array.from({ length: BROWSER_DETERMINISM_PARTITIONS.max }, (_, index) => index + 1).join(", ")}]\n`, problem], + ["THE_BUN_GATES_PARTITIONS_AS_MATRIX", matrix, " shard: ${{ fromJSON(needs.changeset.outputs.determinism_shards) }}\n", problem], + ["SECOND_MATRIX_DIMENSION", matrix, matrix + " project: [visual, storybook]\n", problem], + ["NO_MATRIX", " strategy:\n fail-fast: false\n matrix:\n" + matrix, "", problem], + ["UNPARTITIONED_COMMAND", command, "browser_determinism", problem], + ["LITERAL_DIVISOR", command, "browser_determinism --shard=${{ matrix.shard }}/2", problem], + ["LITERAL_DIVISOR_VALUE", "BROWSER_REPEAT_SHARDS: ${{ strategy.job-total }}", "BROWSER_REPEAT_SHARDS: 2", problem], + ["OUTPUT_NOT_FROM_PLANNER", "browser_determinism_shards: ${{ steps.plan.outputs.browser_determinism_shards }}", 'browser_determinism_shards: "[1]"', problem], + ["SHARED_ARTIFACT_NAME", "name: browser-determinism-proof-${{ matrix.shard }}", "name: browser-determinism-proof", "browser_determinism: each partition must upload its own receipts"], + ["STEP_LIMIT_NOT_THE_OWNERS", " timeout-minutes: 20\n env:\n BROWSER_REPEAT_SHARDS:", " timeout-minutes: 45\n env:\n BROWSER_REPEAT_SHARDS:", "browser_determinism: proof must retain its 20-minute limit"], + ["JOB_LIMIT_BELOW_THE_STEP", " # 20 minutes proof (build, image and repeated passes) + 5 minutes for other steps.\n timeout-minutes: 25\n", " timeout-minutes: 20\n", "browser_determinism: job limit must cover proof and 5 minutes of other steps"], + ] as const) { + expect(text.split(from), `ONE_SITE: ${label}`).toHaveLength(2); + expect(workflowProblems(text.replace(from, to), "ci.yml"), label).toContain(`ci.yml: ${refusal}`); + } +}); + test("a main push whose metadata job fails still runs its selected proof (#2942)", () => { const ci = Bun.YAML.parse(readFileSync(join(ROOT, ".github/workflows/ci.yml"), "utf8")) as { jobs: Record }; - for (const name of ["verify", "pack", "unit", "runtime", "runtime_host", "browser", "layout", "captures", "endurance", "determinism"]) { + for (const name of ["verify", "pack", "unit", "runtime", "runtime_host", "browser", "layout", "captures", "endurance", "determinism", "browser_determinism"]) { const condition = ci.jobs[name]!.if ?? ""; // No implicit success(): a status function plus an explicit push alternative. expect(condition, `PUSH_PROOF_SURVIVES_METADATA_FAILURE:${name}`).toContain("!cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push')"); diff --git a/tests/fixtures/browser-determinism/landing-racy.repeat.js b/tests/fixtures/browser-determinism/landing-racy.repeat.js new file mode 100644 index 0000000000..0beb96fc84 --- /dev/null +++ b/tests/fixtures/browser-determinism/landing-racy.repeat.js @@ -0,0 +1,18 @@ +// A real-time race with a fixed schedule: on every third landing the crew is +// slow and the tide's timer wins. One pass is green; the third repetition +// fails. The landing count lives in the page's storage, which a further pass +// in the same Vitest process keeps and a new container does not. +import { expect, test } from "vitest"; + +const landing = () => { + const next = Number(localStorage.getItem("landings-racy") ?? 0) + 1; + localStorage.setItem("landings-racy", String(next)); + return next; +}; +const after = (milliseconds, who) => new Promise(resolve => setTimeout(() => resolve(who), milliseconds)); + +test("the crew is aboard before the tide turns", async () => { + const tide = after(150, "tide"); + const crew = after(landing() % 3 === 0 ? 600 : 1, "crew"); + expect(await Promise.race([tide, crew])).toBe("crew"); +}); diff --git a/tests/fixtures/browser-determinism/landing-steady.repeat.js b/tests/fixtures/browser-determinism/landing-steady.repeat.js new file mode 100644 index 0000000000..fe583cb9e3 --- /dev/null +++ b/tests/fixtures/browser-determinism/landing-steady.repeat.js @@ -0,0 +1,15 @@ +// The racy landing made deterministic: the tide waits for the crew, not for a +// clock. The crew is still slow on every third landing, and every pass is green. +import { expect, test } from "vitest"; + +const landing = () => { + const next = Number(localStorage.getItem("landings-steady") ?? 0) + 1; + localStorage.setItem("landings-steady", String(next)); + return next; +}; +const after = (milliseconds, who) => new Promise(resolve => setTimeout(() => resolve(who), milliseconds)); + +test("the crew is aboard before the tide turns", async () => { + const crew = after(landing() % 3 === 0 ? 60 : 1, "crew"); + expect(await crew).toBe("crew"); +}); diff --git a/tests/fixtures/browser-determinism/vitest.config.mjs b/tests/fixtures/browser-determinism/vitest.config.mjs new file mode 100644 index 0000000000..286de20a65 --- /dev/null +++ b/tests/fixtures/browser-determinism/vitest.config.mjs @@ -0,0 +1,25 @@ +// Fixture projects for the browser repetition gate's own tests (#4163, +// scripts/browser-determinism.ts). Deliberately outside `packages/`: no +// browser, layout or story project of `packages/ui-kit/vitest.config.ts` +// includes these specs, so the ordinary suites never run a fixture that is +// meant to fail. Two projects list every spec, so one file expands to two +// project/file pairs as a story does for its two themes. +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { playwright } from "@vitest/browser-playwright"; +import { defineConfig } from "vitest/config"; + +const project = name => ({ + extends: true, + test: { + name, + include: ["*.repeat.js"], + browser: { enabled: true, headless: true, screenshotFailures: false, provider: playwright({}), instances: [{ browser: "chromium" }] }, + }, +}); + +export default defineConfig({ + // The checkout stays clean: Vite's dependency cache goes to the run's temporary directory. + cacheDir: join(tmpdir(), "brain-kit-browser-determinism-fixture"), + test: { projects: [project("harbour"), project("strait")] }, +}); diff --git a/tests/heavy-feedback.test.ts b/tests/heavy-feedback.test.ts index d433f42c77..891f038a9e 100644 --- a/tests/heavy-feedback.test.ts +++ b/tests/heavy-feedback.test.ts @@ -98,12 +98,15 @@ test("the request script reads the live head, dispatches it from the default bra }); test("the feedback aggregate requires its own cadence and every selected category", () => { - const outputs = { cadence: "feedback-heavy", verify: "true", pack: "false", unit: "true", browser: "false", layout: "false", captures: "false", runtime: "false", runtime_host: "false", endurance: "false", determinism: "true" }; + const outputs = { cadence: "feedback-heavy", verify: "true", pack: "false", unit: "true", browser: "false", layout: "false", captures: "false", runtime: "false", runtime_host: "false", endurance: "false", determinism: "true", browser_determinism: "true" }; const needs: Record }> = { changeset: { result: "success", outputs }, - verify: { result: "success" }, unit: { result: "success" }, determinism: { result: "success" }, ...Object.fromEntries(["pack", "browser", "layout", "captures", "runtime", "runtime_host", "endurance"].map(name => [name, { result: "skipped" }])) }; + verify: { result: "success" }, unit: { result: "success" }, determinism: { result: "success" }, browser_determinism: { result: "success" }, ...Object.fromEntries(["pack", "browser", "layout", "captures", "runtime", "runtime_host", "endurance"].map(name => [name, { result: "skipped" }])) }; expect(feedbackProblems(needs)).toEqual([]); // Draft heavy feedback repeats the changed Bun tests too (#4109). expect(feedbackProblems({ ...needs, determinism: { result: "skipped" } }), "FEEDBACK_REQUIRES_SELECTED_DETERMINISM").toEqual(["determinism: selected proof did not pass (skipped)"]); + // And its changed browser, layout and story specs, in the pinned container (#4163). + expect(feedbackProblems({ ...needs, browser_determinism: { result: "skipped" } }), "FEEDBACK_REQUIRES_SELECTED_BROWSER_REPETITION").toEqual(["browser_determinism: selected proof did not pass (skipped)"]); + expect(feedbackProblems({ ...needs, browser_determinism: { result: "failure" } })).toEqual(["browser_determinism: selected proof did not pass (failure)"]); expect(feedbackProblems({ ...needs, unit: { result: "failure" } })).toEqual(["unit: selected proof did not pass (failure)"]); expect(feedbackProblems({ ...needs, changeset: { result: "success", outputs: { ...outputs, cadence: "confirmation" } } })).toEqual(["admission did not plan a feedback-heavy selection"]); }); diff --git a/tests/hosted-proof.test.ts b/tests/hosted-proof.test.ts index 33e23b51cc..03254322b8 100644 --- a/tests/hosted-proof.test.ts +++ b/tests/hosted-proof.test.ts @@ -2,12 +2,13 @@ import { afterEach, expect, test } from "bun:test"; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; -import { categoryCommands, DETERMINISM_REPORT, determinismFiles, proofProblems, PROOF_JOBS, unitFiles } from "../scripts/ci-proof"; -import { determinismShards, planChecks, proofSelections, unitShards, workspaces, type ProofCadence, type Workspace } from "../scripts/ci-plan"; +import { BROWSER_DETERMINISM_REPORT, browserDeterminismPairs, categoryCommands, DETERMINISM_REPORT, determinismFiles, proofProblems, PROOF_JOBS, unitFiles } from "../scripts/ci-proof"; +import { browserDeterminismShards, determinismShards, planChecks, proofSelections, unitShards, workspaces, type ProofCadence, type Workspace } from "../scripts/ci-plan"; import { discoverTests } from "../scripts/test-shards"; -import { DETERMINISM_PARTITIONS } from "../scripts/proof-shards"; +import { BROWSER_DETERMINISM_PARTITIONS, DETERMINISM_PARTITIONS } from "../scripts/proof-shards"; import { planRepetitions } from "../scripts/test-determinism"; import { localChecks } from "../scripts/check-pr"; +import { POST_MERGE_CATEGORIES } from "../scripts/red-main"; const ROOT = resolve(import.meta.dir, ".."); const directories: string[] = []; @@ -31,7 +32,7 @@ function receipt(selected = true): { changeset: { result: string; outputs: Recor } test("aggregate accepts actual selected passes and intentional exclusions only", () => { - expect(PROOF_JOBS.length).toBe(10); + expect(PROOF_JOBS.length).toBe(11); expect(proofProblems(receipt())).toEqual([]); expect(proofProblems(receipt(false))).toEqual([]); for (const name of PROOF_JOBS) for (const result of ["failure", "cancelled", "skipped", "queued", ""]) { @@ -60,8 +61,8 @@ test("aggregate accepts actual selected passes and intentional exclusions only", test("emitted aggregate executable fails a cancelled or skipped selected job and accepts its corrected receipt", async () => { for (const result of ["cancelled", "skipped", "success"]) { const needs = receipt(); needs.layout.result = result; - // The metadata job's published partition sets reach the merge path through the receipt (#4108, #4117). - Object.assign(needs.changeset.outputs, { unit_shards: "[1,2,3]", determinism_shards: "[1,2]" }); + // The metadata job's published partition sets reach the merge path through the receipt (#4108, #4117, #4163). + Object.assign(needs.changeset.outputs, { unit_shards: "[1,2,3]", determinism_shards: "[1,2]", browser_determinism_shards: "[1,2,3,4]" }); const child = Bun.spawn([process.execPath, "scripts/ci-proof.ts", "aggregate"], { cwd: ROOT, env: { ...process.env, GITHUB_ACTIONS: "false", GITHUB_EVENT_PATH: "", PROOF_NEEDS: JSON.stringify(needs) }, stdout: "pipe", stderr: "pipe" }); const [code, out, err] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); @@ -73,7 +74,7 @@ test("emitted aggregate executable fails a cancelled or skipped selected job and expect(line, "MERGE_CONSUMER_RECEIVES_VALIDATED_SELECTED_INVENTORY").toBeDefined(); expect(JSON.parse(line!.slice("BRAIN_SELECTED_PROOF_RECEIPT ".length))).toEqual({ selections: Object.fromEntries(PROOF_JOBS.map(name => [name, "true"])), - results: Object.fromEntries(PROOF_JOBS.map(name => [name, "success"])), retained: [], unitShards: "[1,2,3]", determinismShards: "[1,2]", + results: Object.fromEntries(PROOF_JOBS.map(name => [name, "success"])), retained: [], unitShards: "[1,2,3]", determinismShards: "[1,2]", browserDeterminismShards: "[1,2,3,4]", }); } } @@ -145,9 +146,10 @@ test("eight confirmation partitions run the files four main partitions run, each test("hosted global commands retain the full local inventory and real offline namespaces", () => { const plan = planChecks(["package.json"], workspaces(ROOT)); - // A global change touches no Bun test file, so nothing is repeated under load (#4109). - const { determinism, ...selections } = proofSelections(plan); + // A global change touches no Bun test file and no browser spec, so nothing is repeated under load (#4109, #4163). + const { determinism, browser_determinism, ...selections } = proofSelections(plan); expect(determinism, "NO_CHANGED_TEST_NO_REPETITION").toBe(false); + expect(browser_determinism, "NO_CHANGED_SPEC_NO_REPETITION").toBe(false); expect(Object.values(selections).every(Boolean)).toBe(true); expect(Object.values(proofSelections(plan, true)).every(value => !value)).toBe(true); const cmds = ["unit", "runtime", "runtime_host", "browser", "layout", "captures", "endurance"].flatMap(category => categoryCommands(category as "unit", plan, ROOT)); @@ -295,7 +297,7 @@ test("emitted aggregate refuses skipped or missing selected native host job", as expect(line, "MERGE_CONSUMER_RECEIVES_VALIDATED_SELECTED_INVENTORY").toBeDefined(); expect(JSON.parse(line!.slice("BRAIN_SELECTED_PROOF_RECEIPT ".length))).toEqual({ selections: Object.fromEntries(PROOF_JOBS.map(name => [name, "true"])), - results: Object.fromEntries(PROOF_JOBS.map(name => [name, "success"])), retained: [], unitShards: null, determinismShards: null, + results: Object.fromEntries(PROOF_JOBS.map(name => [name, "success"])), retained: [], unitShards: null, determinismShards: null, browserDeterminismShards: null, }); } } @@ -343,3 +345,80 @@ test("ready confirmation repeats changed tests at the floor; every other cadence expect(planRepetitions(["tests/ci-plan.test.ts"], { repetitions: 2 }).repetitions).toBe(2); expect(() => planRepetitions(["tests/ci-plan.test.ts"], { repetitions: 1 })).toThrow("at least 2"); }); + +// Names the reviewed table does not hold, so a weight refresh cannot move these: each pair costs the stated default. +const story = (name: string) => [{ project: "storybook", file: `packages/ui-kit/stories/${name}.stories.tsx` }, { project: "storybook-light", file: `packages/ui-kit/stories/${name}.stories.tsx` }]; +const keys = (pairs: readonly { project: string; file: string }[]) => pairs.map(pair => `${pair.project}::${pair.file}`).sort(); + +test("a plan with changed browser specs repeats exactly its project/file pairs in the pinned container (#4163)", () => { + const pairs = story("Argo"), plan = { ...planChecks(["docs/voyage.md"], workspaces(ROOT)), browserDeterminism: pairs }; + expect(browserDeterminismPairs(plan)).toEqual(["storybook-light::packages/ui-kit/stories/Argo.stories.tsx", "storybook::packages/ui-kit/stories/Argo.stories.tsx"]); + const [build, repeat, ...rest] = categoryCommands("browser_determinism", plan, ROOT); + expect(rest).toEqual([]); + // The container resolves the packages' built output, as the browser and layout jobs do. + expect([build!.name, build!.argv.slice(1)]).toEqual(["workspace build for real browser checks", ["run", "build", "--jobs=2"]]); + expect(repeat!.argv.slice(1), "EXACT_PAIRS_NO_FILTER").toEqual([join(ROOT, "scripts/browser-determinism.ts"), `--report=${BROWSER_DETERMINISM_REPORT}`, ...keys(pairs)]); + expect(categoryCommands("browser_determinism", plan, ROOT, "1/1"), "ONE_PARTITION_KEEPS_THE_COMMAND").toEqual([build!, repeat!]); + expect(() => categoryCommands("browser_determinism", plan, ROOT, "1/2"), "DIVISOR_MUST_BE_THE_PLANNED_COUNT").toThrow("Repeated-run partition 1/2 is not in the planned set of 1"); + for (const unselected of [{ ...plan, browserDeterminism: [] }, { ...plan, browserDeterminism: undefined }]) { + expect(() => categoryCommands("browser_determinism", unselected, ROOT), "EMPTY_SELECTION_IS_NEVER_A_JOB").toThrow("Repeated browser proof was not selected"); + } + // The aggregate requires the job exactly when the plan selects it. + const selected = receipt(false); selected.changeset.outputs.browser_determinism = "true"; + for (const state of ["skipped", "failure", "cancelled", undefined]) { + if (state === undefined) delete selected.browser_determinism; else selected.browser_determinism = { result: state }; + expect(proofProblems(selected), "SELECTED_REPETITION_MUST_PASS").toEqual([`browser_determinism: selected proof did not pass (${state ?? "missing"})`]); + } + selected.browser_determinism = { result: "success" }; + expect(proofProblems(selected)).toEqual([]); + const unselected = receipt(false); unselected.browser_determinism = { result: "success" }; + expect(proofProblems(unselected)).toEqual(["browser_determinism: unselected job must be intentionally skipped (success)"]); +}); + +test("ready confirmation repeats changed browser specs twice; every other pull-request cadence asks for five (#4163)", () => { + const selected = { ...planChecks(["docs/voyage.md"], workspaces(ROOT)), browserDeterminism: story("Argo") }; + const argv = (cadence: ProofCadence) => categoryCommands("browser_determinism", { ...selected, cadence }, ROOT)[1]!.argv; + expect(argv("confirmation"), "CONFIRMATION_RUNS_THE_FLOOR").toContain("--repetitions=2"); + for (const cadence of ["draft", "feedback", "feedback-heavy"] as const) { + // No count on the command is the command's default of five. + expect(argv(cadence).filter(arg => arg.startsWith("--repetitions")), `FULL_COUNT:${cadence}`).toEqual([]); + expect(proofSelections({ ...selected, cadence }).browser_determinism, `SELECTED:${cadence}`).toBe(true); + } + for (const cadence of ["integrated", "exhaustive"] as const) expect(proofSelections({ ...selected, cadence }).browser_determinism, `NEVER_ON_MAIN:${cadence}`).toBe(false); + // A fast category under the hybrid split: confirmation selects it, where it leaves the complete browser suites to main. + expect(POST_MERGE_CATEGORIES, "NOT_A_POST_MERGE_CATEGORY").toEqual(["runtime", "runtime_host", "browser", "layout", "captures", "endurance"]); + expect([proofSelections({ ...selected, cadence: "confirmation" }).browser_determinism, proofSelections({ ...selected, cadence: "confirmation", local: { ...selected.local, browser: true } }).browser]) + .toEqual([true, false]); +}); + +test("an oversized browser selection runs as planned partitions: every pair in exactly one, at the selection's count (#4163)", () => { + const { capacitySeconds, max, unweightedSeconds } = BROWSER_DETERMINISM_PARTITIONS; + // Sixteen unweighted pairs: 160 weighted s per pass, 320 at the floor of two, one more than one job holds. + const fleet = Array.from({ length: 8 }, (_, index) => story(`Fleet${index}`)).flat(); + const selected = { ...planChecks(["docs/voyage.md"], workspaces(ROOT)), browserDeterminism: fleet }; + for (const cadence of ["draft", "confirmation", "feedback-heavy"] as const) { + const plan = { ...selected, cadence }; + expect(browserDeterminismShards(plan), `PUBLISHED_SET:${cadence}`).toEqual([1, 2]); + const partitions = browserDeterminismShards(plan).map(shard => categoryCommands("browser_determinism", plan, ROOT, `${shard}/2`)[1]!); + const ran = partitions.map(command => command.argv.slice(command.argv.indexOf("--repetitions=2") + 1)); + for (const [index, command] of partitions.entries()) { + // A draft asks for five; the count for the whole selection is the floor, and each partition is told so. + expect(command.argv.slice(1, 4), `COUNT_DECIDED_OVER_THE_SELECTION:${cadence}`).toEqual([join(ROOT, "scripts/browser-determinism.ts"), `--report=${BROWSER_DETERMINISM_REPORT}`, "--repetitions=2"]); + expect(ran[index]!.length * unweightedSeconds * 2, "WITHIN_CAPACITY").toBeLessThanOrEqual(capacitySeconds); + expect(browserDeterminismPairs(plan, `${index + 1}/2`), "RECEIPT_NAMES_THE_PARTITION_PAIRS").toEqual(ran[index]!); + } + expect(ran.flat().sort(), `EVERY_PAIR_EXACTLY_ONCE:${cadence}`).toEqual(keys(fleet)); + for (const shard of [undefined, "1/1", "1/3", "3/3"]) expect(() => categoryCommands("browser_determinism", plan, ROOT, shard), `NOT_THE_PLANNED_SPLIT:${shard}`).toThrow("is not in the planned set of 2"); + } + // Past the maximum nothing is planned, published or run: the metadata job and every partition refuse. + const count = max * capacitySeconds / (2 * unweightedSeconds) + 1; + const armada = { ...selected, cadence: "confirmation" as const, browserDeterminism: Array.from({ length: count }, (_, index) => ({ project: "visual", file: `packages/ui-kit/tests/visual/armada-${index}.visual.tsx` })) }; + const refusal = `Repeated browser proof refused before it ran: ${count} changed project/file pair(s) weigh ${(count * unweightedSeconds).toFixed(1)} weighted s per pass, ` + + `${(count * unweightedSeconds * 2).toFixed(1)} s at the floor of 2 repetitions. That needs more than the limit of ${max} partitions of ${capacitySeconds} weighted s each (BROWSER_DETERMINISM_PARTITIONS, scripts/proof-shards.ts)`; + expect(() => browserDeterminismShards(armada), "PLANNER_REFUSES").toThrow(refusal); + expect(() => categoryCommands("browser_determinism", armada, ROOT, `1/${max}`), "PARTITION_REFUSES").toThrow(refusal); + expect(browserDeterminismShards({ ...armada, browserDeterminism: armada.browserDeterminism.slice(1) }), "ONE_PAIR_FEWER_IS_THE_MAXIMUM").toHaveLength(max); + // Unselected, and on main where repetition never runs, the matrix expression still has one value. + expect(browserDeterminismShards({ ...selected, browserDeterminism: undefined, cadence: "confirmation" })).toEqual([1]); + expect(browserDeterminismShards({ ...armada, cadence: "integrated" }), "MAIN_NEVER_REPEATS").toEqual([1]); +}); diff --git a/tests/integration-command.test.ts b/tests/integration-command.test.ts index 9b38715056..8c3521e4ad 100644 --- a/tests/integration-command.test.ts +++ b/tests/integration-command.test.ts @@ -169,7 +169,7 @@ fi`); chmodSync(shim, 0o755); const refs=${JSON.stringify(refs)}, body=${JSON.stringify(body)}, probes=${JSON.stringify({ 401: probeLog(401), 402: probeLog(402) })};s.reads??=[]; const mainRuns=${JSON.stringify(mainRuns)}, qualificationRuns=${JSON.stringify(qualificationRuns)}; const repo="odysseus/brain-kit", base=candidate.base, head=candidate.head, squash=${JSON.stringify(squash)}; - const categories=["verify","pack","unit","browser","layout","captures","runtime","runtime_host","endurance","determinism"]; + const categories=["verify","pack","unit","browser","layout","captures","runtime","runtime_host","endurance","determinism","browser_determinism"]; const selected={selections:Object.fromEntries(categories.map(x=>[x,"false"])),results:Object.fromEntries(categories.map(x=>[x,"skipped"])),retained:[],unitShards:null}; if(s.mode.startsWith("browser-")){selected.selections.browser="true";selected.results.browser="success";} if(s.mode==="receipt-uncovered"){selected.selections.unit="false";} @@ -617,32 +617,36 @@ test("the merge path refuses an undisposed finding, rereads the record at the me expect(expedited.commentReads).toBe(0); }); -test("a proof-system candidate waits for its predecessor's own main run, then one green run after a failure; a product candidate does not (#3269)", async () => { - for (const [mode, message] of [ - ["lane-own-busy", "has no settled main run of its own yet"], - ["confirm-lane-own-busy", "has no settled main run of its own yet"], - ["lane-own-red", "its own main run is not green"], - ["lane-recovering", "the newest settled main run after it is not green"], - ["confirm-lane-recovering", "the newest settled main run after it is not green"], - ["lane-cancelled", "run 2 after it at"], - ] as const) { - const refused = await scenario(mode); - expect(refused.dispatched, `NO_PROOF_SYSTEM_MERGE_INSIDE_THE_WINDOW:${mode}`).toBe(false); - expect(refused.code, refused.err).toBe(1); - expect(refused.err).toContain("Proof-system candidate refused (scripts/ci-shards.ts)"); - expect(refused.err).toContain("1 more green main run required"); - expect(refused.err).toContain(message); - expect(refused.err).not.toContain("Off-main qualification missing"); - expect(refused.requested, `NO_CANDIDATE_CI_FOR_A_HELD_CANDIDATE:${mode}`).toBe(false); - expect(refused.state.active, `REFUSED_BEFORE_OWNERSHIP_OR_RELEASED:${mode}`).toBeNull(); - } - // The own green run opens the lane without later runs; after a failure, one later green run reopens it. - for (const mode of ["lane-own-red-product", "lane-recovering-product", "lane-open", "lane-pending", "lane-recovered", "lane-own-red-recovered"]) { +// One scenario per test: each starts its own child process, and twelve of them under one +// 27-second work deadline overran it on a loaded runner (run 44104941268, 27.2 s). +for (const [mode, message] of [ + ["lane-own-busy", "has no settled main run of its own yet"], + ["confirm-lane-own-busy", "has no settled main run of its own yet"], + ["lane-own-red", "its own main run is not green"], + ["lane-recovering", "the newest settled main run after it is not green"], + ["confirm-lane-recovering", "the newest settled main run after it is not green"], + ["lane-cancelled", "run 2 after it at"], +] as const) test(`a proof-system candidate waits for its predecessor's own main run, then one green run after a failure: ${mode} (#3269)`, async () => { + const refused = await scenario(mode); + expect(refused.dispatched, `NO_PROOF_SYSTEM_MERGE_INSIDE_THE_WINDOW:${mode}`).toBe(false); + expect(refused.code, refused.err).toBe(1); + expect(refused.err).toContain("Proof-system candidate refused (scripts/ci-shards.ts)"); + expect(refused.err).toContain("1 more green main run required"); + expect(refused.err).toContain(message); + expect(refused.err).not.toContain("Off-main qualification missing"); + expect(refused.requested, `NO_CANDIDATE_CI_FOR_A_HELD_CANDIDATE:${mode}`).toBe(false); + expect(refused.state.active, `REFUSED_BEFORE_OWNERSHIP_OR_RELEASED:${mode}`).toBeNull(); +}); + +// The own green run opens the lane without later runs; after a failure, one later green run reopens it. +// A product candidate does not wait at all. +for (const mode of ["lane-own-red-product", "lane-recovering-product", "lane-open", "lane-pending", "lane-recovered", "lane-own-red-recovered"]) { + test(`the lane admits a candidate it no longer holds: ${mode} (#3269)`, async () => { const accepted = await scenario(mode); expect(accepted.code, `LANE_ACCEPTS:${mode}: ${accepted.err}`).toBe(2); expect(accepted.dispatched).toBe(true); - } -}); + }); +} test("lane --json reports the refusal's decision from the same function (#3269)", async () => { const read = await scenario("lane-recovering-read"); diff --git a/tests/integration-proof.test.ts b/tests/integration-proof.test.ts index cb879ff7cf..c8ed239726 100644 --- a/tests/integration-proof.test.ts +++ b/tests/integration-proof.test.ts @@ -1,9 +1,9 @@ import { expect, test } from "bun:test"; import { PROOF_JOBS } from "../scripts/ci-proof"; -import { verifyIntegrationProof } from "../scripts/integration-proof"; +import { MAX_RUN_JOBS, verifyIntegrationProof } from "../scripts/integration-proof"; import { scanText } from "../scripts/check-leakage"; import type { API } from "../scripts/proof-api"; -import { DETERMINISM_PARTITIONS } from "../scripts/proof-shards"; +import { BROWSER_DETERMINISM_PARTITIONS, DETERMINISM_PARTITIONS, MAX_UNIT_PARTITIONS } from "../scripts/proof-shards"; const candidate = { repository: "https://github.com/odysseus/brain-kit", pr: 7, head: "a".repeat(40), base: "b".repeat(40) }; const job = { id: 19, name: "changeset", status: "completed", conclusion: "success", run_id: 17, head_sha: candidate.head }; @@ -33,7 +33,8 @@ for (const [predicate, inventory] of [ ["jobs is not an array", { total_count: 1 }], ["total_count differs from jobs.length", { total_count: 2, jobs: [job] }], ["jobs.length is zero", { total_count: 0, jobs: [] }], - ["jobs.length exceeds 30", { total_count: 31, jobs: Array.from({ length: 31 }, () => ({ ...job })) }], + // The bound is every proof job at its widest matrix, never a literal a new matrix would outgrow (#4163). + [`jobs.length exceeds ${MAX_RUN_JOBS}`, { total_count: MAX_RUN_JOBS + 1, jobs: Array.from({ length: MAX_RUN_JOBS + 1 }, () => ({ ...job })) }], ] as const) test(`inventory refuses ${predicate} with count context`, async () => { const message = await refusal(inventory); expect(message).toContain("Incomplete or failed selected job inventory"); @@ -128,21 +129,24 @@ for (const [label, malformed] of [ }); /** A ready confirmation as the merge path reads it: the aggregate's receipts plus the run's actual job inventory. */ -async function confirmationOutcome(published: unknown, ran: readonly number[], - repeated?: { published?: unknown; ran: readonly (number | string)[]; conclusion?: string }): Promise { +type Repeated = { published?: unknown; ran: readonly (number | string)[]; conclusion?: string }; +async function confirmationOutcome(published: unknown, ran: readonly number[], repeated?: Repeated, browser?: Repeated): Promise { // Every hosted proof job, so a category added later (determinism, #4109) is part of the inventory. const categories: readonly string[] = PROOF_JOBS; - // `repeated` selects the determinism job: its published partition set and the partitions that really ran (#4117). - const fast = (name: string) => ["verify", "pack", "unit"].includes(name) || (name === "determinism" && repeated !== undefined); + // `repeated` selects the determinism job and `browser` the browser repetition job: each with its + // published partition set and the partitions that really ran (#4117, #4163). + const matrices: Record = { determinism: repeated, browser_determinism: browser }; + const fast = (name: string) => ["verify", "pack", "unit"].includes(name) || matrices[name] !== undefined; const encoded = (value: unknown) => typeof value === "string" || value === null ? value : JSON.stringify(value); const checkout = { sha: "d".repeat(40), tree: "e".repeat(40), parents: [candidate.base, candidate.head] }; const selected = { selections: Object.fromEntries(categories.map(name => [name, String(fast(name))])), results: Object.fromEntries(categories.map(name => [name, fast(name) ? "success" : "skipped"])), retained: [], - unitShards: encoded(published), ...(repeated && "published" in repeated ? { determinismShards: encoded(repeated.published) } : {}) }; + unitShards: encoded(published), ...(repeated && "published" in repeated ? { determinismShards: encoded(repeated.published) } : {}), + ...(browser && "published" in browser ? { browserDeterminismShards: encoded(browser.published) } : {}) }; let id = 100; const entry = (name: string, conclusion = "success") => ({ ...job, id: id++, name, conclusion }); const jobs = [entry("changeset"), entry("proof"), ...categories.flatMap(name => name === "unit" ? ran.map(shard => entry(`unit (${shard})`)) - : name === "determinism" && repeated ? repeated.ran.map(shard => entry(typeof shard === "number" ? `determinism (${shard})` : shard, repeated.conclusion)) + : matrices[name] ? matrices[name]!.ran.map(shard => entry(typeof shard === "number" ? `${name} (${shard})` : shard, matrices[name]!.conclusion)) : [entry(name, fast(name) ? "success" : "skipped")])]; const actual = `[command]/usr/bin/git log -1 --format=%H\n2026-07-12T00:00:00Z ${checkout.sha}\n`; const proofLog = actual + `BRAIN_CANDIDATE_RECEIPT ${JSON.stringify({ event: "ready_for_review", head: candidate.head, base: candidate.base, checkout })}\n` + @@ -179,6 +183,33 @@ test("the merge path accepts a confirmation only with exactly its planned unit p expect(await confirmationOutcome(null, eight), "MISSING_PLAN").toBe(identity); }); +test("the merge path accepts a confirmation only with exactly its planned browser repetition partitions (#4163)", async () => { + const eight = [1, 2, 3, 4, 5, 6, 7, 8], three = [1, 2, 3], accepted = `ACCEPTED_INVENTORY ${"d".repeat(40)}`; + const differs = "Actual selected job inventory differs from the validated selection", identity = "Missing actual browser_determinism partition identity"; + const outcome = (published: unknown, ran: readonly (number | string)[]) => confirmationOutcome(eight, eight, undefined, { published, ran }); + expect(await outcome([1], [1]), "ONE_PLANNED_ONE_RAN").toBe(accepted); + expect(await outcome(three, three), "THREE_PLANNED_THREE_RAN").toBe(accepted); + expect(await outcome(three, [1, 2]), "DROPPED_LAST_PARTITION").toBe(differs); + expect(await outcome(three, [1, 3]), "DROPPED_MIDDLE_PARTITION").toBe(differs); + expect(await outcome(three, [...three, 3]), "DUPLICATE_PARTITION").toBe(differs); + expect(await outcome([1, 2], three), "RAN_MORE_THAN_PLANNED").toBe(differs); + // An unpartitioned job, or the Bun gate's partitions under this job's selection, is no planned partition. + expect(await outcome([1], ["browser_determinism"]), "UNPARTITIONED_JOB_NAME").toBe(differs); + expect(await outcome([1], ["determinism (1)"]), "ANOTHER_JOBS_PARTITION").toBe(differs); + const limit = Array.from({ length: BROWSER_DETERMINISM_PARTITIONS.max }, (_, index) => index + 1); + expect(await outcome(limit, limit), "THE_MAXIMUM_IS_ACCEPTED").toBe(accepted); + expect(await outcome([...limit, limit.length + 1], [...limit, limit.length + 1]), "ABOVE_THE_MAXIMUM").toBe(identity); + expect(await outcome([2, 1], [1, 2]), "REORDERED_PLAN").toBe(identity); + expect(await outcome([], []), "EMPTY_PLAN").toBe(identity); + expect(await outcome(null, [1]), "NULL_PLAN").toBe(identity); + expect(await confirmationOutcome(eight, eight, undefined, { ran: [1] }), "RECEIPT_WITHOUT_THE_SET").toBe(identity); + expect(await confirmationOutcome(eight, eight, undefined, { published: [1, 2], ran: [1, 2], conclusion: "failure" }), "FAILED_PARTITION").toContain("Incomplete or failed selected job inventory"); + // Both repetition jobs at their widest, beside eight unit partitions: a complete run, inside the inventory bound. + const widest = Array.from({ length: DETERMINISM_PARTITIONS.max }, (_, index) => index + 1); + expect(MAX_UNIT_PARTITIONS + widest.length + limit.length + 2, "THE_WIDEST_CONFIRMATION_FITS").toBeLessThanOrEqual(MAX_RUN_JOBS); + expect(await confirmationOutcome(eight, eight, { published: widest, ran: widest }, { published: limit, ran: limit }), "WIDEST_CONFIRMATION_ACCEPTED").toBe(accepted); +}); + test("the merge path accepts a confirmation only with exactly its planned determinism partitions (#4117)", async () => { const eight = [1, 2, 3, 4, 5, 6, 7, 8], nine = [...eight, 9], accepted = `ACCEPTED_INVENTORY ${"d".repeat(40)}`; const differs = "Actual selected job inventory differs from the validated selection", identity = "Missing actual determinism partition identity"; diff --git a/tests/local-checks.test.ts b/tests/local-checks.test.ts index 8fdd380786..bb8face6db 100644 --- a/tests/local-checks.test.ts +++ b/tests/local-checks.test.ts @@ -3,7 +3,7 @@ import { chmodSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rm import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { checkPackages } from "../scripts/check-packages"; -import { determinismCommand, localChecks, localStages, localUnitInventory, newReceipt, requireLocalSandbox, requireRuntimeTools, runPreflight, type PreflightStep } from "../scripts/check-pr"; +import { browserDeterminismCommand, determinismCommand, localChecks, localStages, localUnitInventory, newReceipt, requireLocalSandbox, requireRuntimeTools, runPreflight, type PreflightStep } from "../scripts/check-pr"; import { DEFAULT_ROOTS, testArgv } from "../scripts/test"; import { planChecks, workspaces } from "../scripts/ci-plan"; import { discoverTests } from "../scripts/test-shards"; @@ -386,6 +386,17 @@ test("check:pr names the repeated-run command for changed Bun tests and never ru expect(determinismCommand({ ...unchanged, determinism: [] }, "origin/main")).toBeUndefined(); }); +test("check:pr names the repeated-run command for changed browser specs and never runs it locally (#4163)", () => { + const unchanged = planChecks(["package.json"], workspaces(join(import.meta.dir, ".."))); + const plan = { ...unchanged, browserDeterminism: [{ project: "ui-react-layout", file: "packages/ui-react/tests/browser/argo.layout.tsx" }] }; + expect(browserDeterminismCommand(plan, "origin/main"), "PLAN_NAMES_THE_COMMAND").toBe("bun scripts/browser-determinism.ts --base origin/main"); + for (const commands of [localChecks(plan), localChecks(plan, true), localChecks(plan, false, "a".repeat(40), true)]) { + expect(commands.map(command => command.argv.join(" ")).join("\n"), "NO_LOCAL_BURN").not.toContain("scripts/browser-determinism.ts"); + } + expect(browserDeterminismCommand(unchanged, "origin/main"), "NO_CHANGED_SPEC_NO_COMMAND").toBeUndefined(); + expect(browserDeterminismCommand({ ...unchanged, browserDeterminism: [] }, "origin/main")).toBeUndefined(); +}); + test("default local feedback excludes import-graph tests even with a merge-base SHA", () => { const plan = planChecks(["packages/common/src/index.ts"], workspaces(join(import.meta.dir, ".."))); const commands = localChecks(plan, false, "a".repeat(40)); diff --git a/tests/visual-runner.test.ts b/tests/visual-runner.test.ts index d8f0d62e99..bf085b2112 100644 --- a/tests/visual-runner.test.ts +++ b/tests/visual-runner.test.ts @@ -57,6 +57,9 @@ async function invoke(args: string[], exit = 0, imageState: "warm"|"cold"|"drift args: process.argv.slice(2), cwd: process.cwd()}) + "\\n");`; await writeFile(resolve(root, "node_modules/vitest/vitest.mjs"), record.replace("COMMAND", '"vitest"') + "process.exit(Number(process.env.RUNNER_EXIT));"); + // A stand-in for the container side of the browser repetition gate (#4163), recorded like Vitest. + await writeFile(resolve(root, "scripts/browser-determinism-inside.mjs"), + record.replace("COMMAND", '"repeat"') + "process.exit(Number(process.env.RUNNER_EXIT));"); for (const command of ["bun", "docker"]) { const script = resolve(root, "commands", command); const docker = command === "docker" ? ` @@ -178,6 +181,32 @@ test("inside default serializes browser files in every configured project", asyn expect(result.calls[0]!.cwd).toBe(resolve(result.root, "packages/ui-kit")); }); +test("a repeat plan enters the same container and runs the repetition runner there in place of vitest run (#4163)", async () => { + const plan = "--repeat-plan=tmp/browser-determinism/plan.json"; + const inside = await invoke(["--inside", "--project=rail-fine", plan], 7); + // The runner's exit status is the launcher's, and Vitest's CLI is never started: the runner drives Vitest in-process. + expect(inside.code, inside.stderr).toBe(7); + expect(inside.calls).toEqual([{ command: "repeat", args: ["tmp/browser-determinism/plan.json"], cwd: resolve(inside.root, "packages/ui-kit") }]); + const local = await invoke(["--project=ui-react-layout", "--project=visual", plan]); + expect(local.code, local.stderr).toBe(0); + expect(local.calls.map((call) => call.command), "SAME_HOST_PATH_AS_ANY_BROWSER_RUN").toEqual(["bun", "docker", "repeat"]); + const docker = local.calls[1]!.args; + expect(docker.slice(docker.indexOf("--inside"))).toEqual(["--inside", "--project=ui-react-layout", "--project=visual", plan]); + // The selected projects decide the network exactly as for an ordinary run of them. + expect(docker, "LAYOUT_STAYS_OFFLINE").toContain("--network=none"); + expect((await invoke(["--project=visual", plan])).calls[1]!.args).not.toContain("--network=none"); +}); + +test("a repeat plan names its projects and a file under tmp/, and nothing else that chooses files", async () => { + const plan = "--repeat-plan=tmp/browser-determinism/plan.json"; + for (const args of [[plan], ["--project=visual", plan, "--shard=1/2"], ["--project=visual", plan, "--update"], ["--project=visual", plan, "--filter=Composer"], + ["--project=visual", plan, plan], ["--project=visual", "--repeat-plan=packages/plan.json"], ["--project=visual", "--repeat-plan=tmp/../plan.json"]]) { + const refused = await invoke(args); + expect([refused.code, refused.calls], args.join(" ")).toEqual([1, []]); + expect(refused.stderr).toContain("use --repeat-plan=tmp/.json once, with --project and no --update, --shard, --filter, --proof-report or scheduling override"); + } +}); + test("hosted proof adds project-aware case receipts while retaining human output and the runner failure", async () => { const result = await invoke(["--inside", "--project=ui-react-endurance", "--proof-report"], 7); expect(result.code, result.stderr).toBe(7);