diff --git a/.agents/skills/work-issue/references/ci-and-merge.md b/.agents/skills/work-issue/references/ci-and-merge.md index 3d880351cd..c7f53df0ad 100644 --- a/.agents/skills/work-issue/references/ci-and-merge.md +++ b/.agents/skills/work-issue/references/ci-and-merge.md @@ -132,7 +132,8 @@ Drafts run cheap gates only, and tests-only changes may intentionally skip packaging while complete affected tests run. One job is the exception: when a PR adds or modifies a Bun test file, `determinism` repeats those files under CPU load at every cadence, drafts included, and `draft gates` and `proof` -require it. A failing repetition is fixed in the test, never rerun +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 and logs for the current head, never an old Depot receipt or latest-main run. GitHub checks/statuses may include additional gates. No rows, diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b3fad4f056..8ca9af90a4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,7 +21,8 @@ concurrency: # Drafts run cheap gates; synchronize gives fast feedback. Open/ready/reopen # requests final affected confirmation. The proof gate refuses intermediate feedback. # One job is selected at every pull-request cadence, drafts included: `determinism` -# repeats the Bun test files a change adds or modifies under CPU load (#4109). +# repeats the Bun test files a change adds or modifies under CPU load (#4109), +# in as many partitions as the planner publishes (#4117). # Independent jobs start together; each PR owns its cancellation group (#1326). jobs: changeset: @@ -40,6 +41,7 @@ jobs: verify: ${{ steps.plan.outputs.verify }} pack: ${{ steps.plan.outputs.pack }} determinism: ${{ steps.plan.outputs.determinism }} + determinism_shards: ${{ steps.plan.outputs.determinism_shards }} red_main_oid: ${{ steps.plan.outputs.red_main_oid }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 @@ -649,6 +651,12 @@ jobs: runs-on: ubuntu-24.04 # 12 minutes setup + 40 minutes proof + 3 minutes for other steps. timeout-minutes: 55 + # One partition while the selection fits one job's capacity; an oversized + # selection is split by reviewed weight (#4117, scripts/proof-shards.ts). + strategy: + fail-fast: false + matrix: + shard: ${{ fromJSON(needs.changeset.outputs.determinism_shards) }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: @@ -674,7 +682,9 @@ jobs: - name: Repeat changed Bun test files under CPU load id: runtime_proof timeout-minutes: 40 - run: bun scripts/ci-proof.ts determinism + env: + DETERMINISM_SHARDS: ${{ strategy.job-total }} + run: bun scripts/ci-proof.ts determinism --shard=${{ matrix.shard }}/"$DETERMINISM_SHARDS" - name: Environment setup and proof outcomes if: always() env: @@ -687,7 +697,7 @@ jobs: if: always() uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: - name: determinism-proof + name: determinism-proof-${{ matrix.shard }} path: | tmp/determinism-report.json tmp/determinism-junit.xml diff --git a/.github/workflows/heavy-feedback.yml b/.github/workflows/heavy-feedback.yml index 9d43b82ffb..6cb7bf5ed7 100644 --- a/.github/workflows/heavy-feedback.yml +++ b/.github/workflows/heavy-feedback.yml @@ -51,6 +51,7 @@ jobs: verify: "${{ steps.plan.outputs.verify }}" pack: "${{ steps.plan.outputs.pack }}" determinism: "${{ steps.plan.outputs.determinism }}" + determinism_shards: "${{ steps.plan.outputs.determinism_shards }}" red_main_oid: "${{ steps.plan.outputs.red_main_oid }}" base_sha: "${{ steps.admit.outputs.base_sha }}" steps: @@ -444,6 +445,10 @@ jobs: if: "${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && needs.changeset.outputs.determinism == 'true' }}" runs-on: ubuntu-24.04 timeout-minutes: 55 + strategy: + fail-fast: false + matrix: + shard: "${{ fromJSON(needs.changeset.outputs.determinism_shards) }}" steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: @@ -467,7 +472,9 @@ jobs: - name: Repeat changed Bun test files under CPU load id: runtime_proof timeout-minutes: 40 - run: bun scripts/ci-proof.ts determinism + env: + DETERMINISM_SHARDS: "${{ strategy.job-total }}" + run: "bun scripts/ci-proof.ts determinism --shard=${{ matrix.shard }}/\"$DETERMINISM_SHARDS\"" - name: Environment setup and proof outcomes if: always() env: @@ -478,7 +485,7 @@ jobs: if: always() uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: - name: determinism-proof + name: "determinism-proof-${{ matrix.shard }}" path: "tmp/determinism-report.json\ntmp/determinism-junit.xml\ntmp/proof-checkout.json\ntmp/proof-resources.json\ntmp/runner-disk.json\n" include-hidden-files: true if-no-files-found: warn diff --git a/docs/decisions/ci-utility.md b/docs/decisions/ci-utility.md index 47d75c7cfd..b97944aebe 100644 --- a/docs/decisions/ci-utility.md +++ b/docs/decisions/ci-utility.md @@ -1699,7 +1699,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:434-446`) applies + `proofSelections` (`scripts/ci-plan.ts:445-457`) 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. @@ -1764,16 +1764,16 @@ 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:395-397`) and publishes the partition numbers as + `scripts/ci-plan.ts:406-408`) 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:125-126`). + (`unitPartitionLimit("confirmation")`, `scripts/integration-proof.ts:127-128`). `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:97-105`). The weight refresh takes its job + `scripts/check-ci-workflows.ts:100-108`). The weight refresh takes its job count from the same table. - **Fewer files than partitions.** A selected inventory smaller than the cap gets one partition per file. No partition is empty and no file runs twice @@ -1936,27 +1936,25 @@ test more than once before it merged. - **What runs.** `bun scripts/test-determinism.ts --base ` selects the Bun test files under `packages/` and `tests/` that the change adds or modifies against its merge base (`determinismTests`, - `scripts/ci-plan.ts:323-328`). It runs them in one invocation of the offline + `scripts/ci-plan.ts:318-323`). It runs them in one invocation of the offline wrapper with Bun's `--rerun-each= --bail=1` (`repetitionArgv`, - `scripts/test-determinism.ts:93-96`), so the offline preload applies and + `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 is killed by PID on every exit path, and exits by itself if its parent dies - (`startBurners`, `scripts/test-determinism.ts:145-160`). The first failing + (`startBurners`, `scripts/test-determinism.ts:105-120`). The first failing repetition fails the command, which names the file, the repetition and the case. A passing run must also show every repetition in Bun's test report. -- **Bounded.** Five repetitions by default, within a budget of 600 seconds of +- **Bounded.** Five repetitions by default, within a budget of 300 seconds of the reviewed weights in `scripts/test-shard-costs.json`. When five do not fit, every file gets the same reduced count, down to a floor of two - (`planRepetitions`, `scripts/test-determinism.ts:71-90`). A selection too - heavy for the floor still runs every file twice and is reported over budget. - No selected file is skipped; the report lists each one with the repetitions - it got. Over 150 merges before the gate, 142 selections fit five - repetitions. A selection too heavy for the job's step limit is - [#4117](https://github.com/schlessera/brain-kit/issues/4117). + (`planRepetitions`, `scripts/determinism-plan.ts:45-65`). No selected file + is skipped; the report lists each one with the repetitions it got. The + budget is one job's capacity, so a selection too heavy for the floor is + [split across partitions](#an-oversized-selection-is-split-by-reviewed-weight). - **Two repetitions at ready confirmation.** The maintainer ruled on 2026-11-17 ([#4137](https://github.com/schlessera/brain-kit/issues/4137)) that ready confirmation runs the floor of two, and every other cadence keeps - five (`repetitionsFor`, `scripts/test-determinism.ts:41-43`). The merge lease + five (`repetitionsFor`, `scripts/determinism-plan.ts:22-24`). The merge lease is held while confirmation runs. In run 44017250694 the job took 1,236 seconds at five repetitions, against 979 for the slowest of eight `unit` partitions, and the lease was held about 25 minutes. The draft head has @@ -1968,7 +1966,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:441-453`). This amends "drafts + too (`proofSelections`, `scripts/ci-plan.ts:445-457`). 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 @@ -1994,8 +1992,111 @@ GitHub Actions Bun prints each run's header as a `::group::` annotation, which the failure parser did not read, so the failure was reported without its file and repetition. The parser reads both forms now. That run took 552 seconds for about 174 weighted seconds, a ratio of about 3.2 under four burners on -four CPUs, so a selection at the 600-second budget needs about 32 minutes of -the 40-minute step limit. +four CPUs. One run was not a calibration: +[the later runs](#an-oversized-selection-is-split-by-reviewed-weight) measured +up to 6.84, and the budget was lowered from 600 to 300 seconds. + +### An oversized selection is split by reviewed weight + +The maintainer ruled on 2026-11-17 +([#4117](https://github.com/schlessera/brain-kit/issues/4117)) that a +selection too heavy for one job is sharded by reviewed weight, as `unit` is. +Running workers inside one job and an exception path for large migrations +were declined: the first shares the job's CPUs with the burners, the second +weakens a gate that is otherwise the same for every pull request. + +**Why.** The job ran the whole selection in one invocation under a 40-minute +step limit. Over the 150 merges before the gate, four selections weighed more +than 600 seconds per pass. The largest was a 388-file fixture migration of +about 1,327 seconds per pass, 2,654 at the floor of two. Such a selection +could only fail by timeout, and the pull request had no way through the gate +except splitting the change. + +- **One owner.** The table (`DETERMINISM_PARTITIONS`, `scripts/proof-shards.ts:44`) holds + one job's capacity (300 weighted seconds at the selection's repetition + count), the maximum of ten partitions, the 40-minute step limit and the + measured load ratio. The repetition budget is that capacity + (`BUDGET_SECONDS`, `scripts/determinism-plan.ts:29`). +- **Count first, then partitions.** The count is decided over the whole + 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`). + 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. +- **A file cannot be split.** A file whose two repetitions alone exceed the + capacity runs in a partition by itself. +- **Beyond the maximum.** A selection that needs more than ten partitions is + refused by the planner, in the metadata job, before any partition starts. + 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`). + 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 + 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 + matrix, a literal divisor, a shared artifact name or a step limit other + than the owner's. + +**Calibration.** The job's own reports give elapsed seconds under load against +estimated weighted seconds. Between its first run and this ruling, 35 hosted +jobs produced a report, all on 2026-11-17, all with four burners on four +CPUs: 32 passed and 3 failed. Five passing jobs repeated at least 90 weighted +seconds, enough for the weights to dominate the result: + +| Run | Pull request | Cadence | Files | Count | Estimated (s) | Elapsed (s) | Ratio | +| --- | --- | --- | --- | --- | --- | --- | --- | +| 43989701310 | #4134 | draft | 8 | 5 | 174.2 | 624.8 | 3.59 | +| 43991629934 | #4134 | draft | 16 | 5 | 194.0 | 1,048.2 | 5.40 | +| 44017250694 | #4134 | confirmation | 14 | 5 | 193.0 | 1,142.1 | 5.92 | +| 44020374567 | #4132 | confirmation | 7 | 5 | 221.3 | 888.7 | 4.02 | +| 44039499653 | #4145 | draft | 2 | 5 | 94.4 | 645.9 | 6.84 | + +The first run, 43986946575, failed in its last file after 552 seconds for the +same 174.2 estimated seconds (3.17). The first confirmation at two +repetitions, run 44036241499 on #4143, took 20.8 seconds for 11.4 estimated +(1.82). The other 26 passing jobs estimated 7.1 seconds or less; there a new +file without a reviewed weight decides the time. Seven runs of #4002 +estimated 2.0 to 3.1 seconds and took 226 to 400, because each new file cost +22 to 34 seconds per pass and weighs the 0.1-second default. + +Per file the ratio is not constant. Across these reports a file with a +reviewed weight of at least one second ran between 1.1 times its weight (a +test that mostly waits) and 6.9 times (`tests/integration-command.test.ts`, +18.8 weighted seconds, 129 seconds per pass under load). + +**The numbers.** The largest whole-job ratio, 6.84, sets the capacity: 300 +weighted seconds take 2,052 seconds at that ratio, 34 of the 40 minutes, and +27 minutes at the median of 5.40. The earlier 600-second budget needed 68 +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. + +**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, +111 select a file: 100 run five repetitions, 3 run three or four, and 8 run +two. Of those eight, six are split (five into two or three partitions, the +migration into nine) and two are a single file. An oversized selection costs +up to ten runners for its two repetitions. + +**Known limit.** All eight contain a real-browser runtime test whose two +repetitions alone exceed the capacity; the heaviest weighs 349.7 seconds per +pass. Sharding cannot help a single file. It runs alone, at the floor, and no +hosted run has yet measured whether it finishes inside the step limit +([#4156](https://github.com/schlessera/brain-kit/issues/4156)). The five +calibration runs are all tooling and backend tests; a refreshed weight table +or a different mix of tests changes the ratio, and the capacity is to be +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 diff --git a/docs/decisions/test-health.md b/docs/decisions/test-health.md index 7a71d4e58a..82d20dc110 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:366-367`): any path + number of files (`const packageCode`, `scripts/ci-plan.ts:367-368`): 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/testing.md b/docs/process/testing.md index 279073a559..57c0059ae9 100644 --- a/docs/process/testing.md +++ b/docs/process/testing.md @@ -318,11 +318,20 @@ bun scripts/test-determinism.ts --base origin/main --json # the report on stdo fails as it does in any test. One busy loop per CPU runs until the command exits; each is stopped by PID and exits by itself if the command is killed. - **The bound.** Five repetitions, reduced uniformly to no fewer than two when - the reviewed weights in `scripts/test-shard-costs.json` exceed 600 seconds. + the reviewed weights in `scripts/test-shard-costs.json` exceed 300 seconds. Ready confirmation runs two, because the merge lease is held while it runs ([ruling](../decisions/ci-utility.md#changed-tests-repeat-under-load-before-merge)). The report lists every selected file with the repetitions it got, and says when the selection is over budget at the floor. +- **Partitions.** A selection too heavy for one job at two repetitions is + split by reviewed weight into `determinism (1)` to at most + `determinism (10)`, each within 300 weighted seconds. Every file runs twice + in exactly one partition. A selection that needs more than ten fails in the + metadata job before anything runs, naming its weight and the limit: split + the change. `DETERMINISM_PARTITIONS` in `scripts/proof-shards.ts` owns the + numbers + ([basis](../decisions/ci-utility.md#an-oversized-selection-is-split-by-reviewed-weight)). + A local `--base` run repeats the whole selection in one invocation. - **A failure** names the file, the repetition and the case. Repetitions of a file share one process, so state left on `globalThis`, in the environment or on disk reaches the next run. Fix the test; do not raise its deadline. diff --git a/scripts/candidate-proof.ts b/scripts/candidate-proof.ts index 81828b6d97..56d63ac0c4 100644 --- a/scripts/candidate-proof.ts +++ b/scripts/candidate-proof.ts @@ -1,5 +1,5 @@ /** Exact merge-candidate validation; feedback never authorizes merging. */ -import { planFromEnvironment, proofCadence, proofSelections, redMainSnapshot, unitShards } from "./ci-plan"; +import { 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"; @@ -66,6 +66,8 @@ export function validateSelections(root: string, event: any, env: NodeJS.Process } // The matrix ran the partitions the metadata job published; they must be the planned set (#4108). 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"); } 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 98ce4dfc5e..ce379668de 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 { PROOF_SHARDS, shardNumbers, type ShardedDomain } from "./proof-shards"; +import { 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"; @@ -81,7 +81,7 @@ export function workflowProblems(text: string, file: string): string[] { fail("verify: always summary must separate raw install, planning and proof outcomes and receipts"); // Network prerequisites cannot spend proof capacity; measured basis: docs/decisions/ci-utility.md (#2658). // Repeated changed tests need the unit job's prerequisites: they may drive real Chrome (#4109). - for (const [name, proofMinutes] of [["unit", 30], ["runtime", 15], ["runtime_host", 15], ["determinism", 40]] as const) { + for (const [name, proofMinutes] of [["unit", 30], ["runtime", 15], ["runtime_host", 15], ["determinism", DETERMINISM_PARTITIONS.stepMinutes]] as const) { const job = workflow.jobs?.[name]; const setup = job?.steps?.find(step => step.run === `bash scripts/ci-runtime-setup.sh${name === "unit" || name === "determinism" ? "" : " --native"}`); const command = `bun scripts/ci-proof.ts ${name}`; @@ -106,6 +106,16 @@ export function workflowProblems(text: string, file: string): string[] { JSON.stringify(unit?.strategy?.matrix) !== JSON.stringify({ shard: "${{ fromJSON(needs.changeset.outputs.unit_shards) }}" }) || unitProof?.run !== 'bun scripts/ci-proof.ts unit --shard=${{ matrix.shard }}/"$UNIT_SHARDS"' || unitProof?.env?.UNIT_SHARDS !== "${{ strategy.job-total }}") fail("unit: matrix and shard divisor must come from the planner's unit_shards output"); + // The determinism partition set has one owner too, DETERMINISM_PARTITIONS, read by the planner (#4117). + // A literal matrix or divisor would run a partition of some split the planner did not make. + const determinism = workflow.jobs?.determinism as any; + const determinismProof = determinism?.steps?.find((step: Step) => step.run?.startsWith("bun scripts/ci-proof.ts determinism")); + if (changeset?.outputs?.determinism_shards !== "${{ steps.plan.outputs.determinism_shards }}" || + JSON.stringify(determinism?.strategy?.matrix) !== JSON.stringify({ shard: "${{ fromJSON(needs.changeset.outputs.determinism_shards) }}" }) || + determinismProof?.run !== 'bun scripts/ci-proof.ts determinism --shard=${{ matrix.shard }}/"$DETERMINISM_SHARDS"' || + 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"); 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"); diff --git a/scripts/ci-plan.ts b/scripts/ci-plan.ts index d170699c9a..6eec1bd8c3 100644 --- a/scripts/ci-plan.ts +++ b/scripts/ci-plan.ts @@ -7,6 +7,7 @@ import { addUnitImportConsumers, type UnitImportGraph } from "./unit-test-consum 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"; export interface Workspace { dir: string; @@ -406,6 +407,16 @@ export function unitShards(plan: CheckPlan): number[] { return unitPartitions(plan.cadence, plan.unitTests?.length); } +/** Partition numbers the `determinism` matrix runs (#4117): one while the + * selection fits one job's capacity at its repetition count, more when it is + * split by reviewed weight. Throws for a selection beyond the maximum, so the + * metadata job fails before any partition starts. An unselected plan publishes + * one number: its job is skipped, and the matrix expression is never empty. */ +export function determinismShards(plan: CheckPlan): number[] { + if (!proofSelections(plan).determinism) return [1]; + return planPartitions(plan.determinism!, { 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. */ @@ -509,7 +520,7 @@ if (import.meta.main) { const draft = process.env.PR_DRAFT === "true"; const selections = proofSelections(plan, draft); if (process.env.GITHUB_OUTPUT) appendFileSync(process.env.GITHUB_OUTPUT, - `unit_shards=${JSON.stringify(unitShards(plan))}\n` + + `unit_shards=${JSON.stringify(unitShards(plan))}\n` + `determinism_shards=${JSON.stringify(determinismShards(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 bfffeb3c97..9ce22b5cd2 100644 --- a/scripts/ci-proof.ts +++ b/scripts/ci-proof.ts @@ -7,7 +7,7 @@ import { localChecks, requireRuntimeTools } from "./check-pr"; import { runCommands, type Command } from "./ci-runner"; import type { CheckPlan } from "./ci-plan"; import { balanceTests, discoverTests } from "./test-shards"; -import { repetitionsFor } from "./test-determinism"; +import { planPartitions, repetitionsFor, selectPartition, type DeterminismPartition, type PartitionPlan } from "./determinism-plan"; import { resolveBrowserPin } from "./captures/provenance"; import { startUnitMemorySampler } from "./unit-memory"; import { diskSampler, floorProblem } from "./ci-disk"; @@ -16,10 +16,18 @@ export const PROOF_JOBS = ["verify", "pack", "unit", "browser", "layout", "captu export type ProofCategory = "unit" | "browser" | "layout" | "captures" | "runtime" | "runtime_host" | "endurance" | "determinism"; export const DETERMINISM_REPORT = "tmp/determinism-report.json"; -/** The planner's added or modified Bun test files; an empty selection is never a job (#4109). */ -export function determinismFiles(plan: CheckPlan): string[] { +/** 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 + * not the planned partition count is refused: a partition of some other split proves nothing. */ +export function determinismPartition(plan: CheckPlan, shard = "1/1"): { selection: PartitionPlan; partition: DeterminismPartition } { if (!plan.determinism?.length) throw new Error("Repeated-run proof was not selected"); - return [...plan.determinism]; + const selection = planPartitions(plan.determinism, { cadence: plan.cadence }); + return { selection, partition: selectPartition(selection, shard) }; +} + +/** The files partition `shard` repeats: every selected file is in exactly one planned partition. */ +export function determinismFiles(plan: CheckPlan, shard?: string): string[] { + return [...determinismPartition(plan, shard).partition.files]; } /** Aggregate requires passed selected jobs; missing/false-looking output is not proof. @@ -60,10 +68,16 @@ export function categoryCommands(category: ProofCategory, plan: CheckPlan, root: "--reporter=junit", "--reporter-outfile=tmp/unit-report.xml", "--timings=tmp/unit-timings.json", "--update-timings"], env: { BRAIN_REQUIRE_CHROME: "1" } }]; // The unit job's serial form, repeated: changed files may drive real Chrome too. - if (category === "determinism") return [{ name: "changed Bun test files repeated under CPU load", - argv: [process.execPath, join(root, "scripts/test-determinism.ts"), `--report=${DETERMINISM_REPORT}`, - ...(repetitionsFor(plan.cadence) === undefined ? [] : [`--repetitions=${repetitionsFor(plan.cadence)}`]), ...determinismFiles(plan)], - env: { BRAIN_REQUIRE_CHROME: "1" } }]; + if (category === "determinism") { + const { selection, partition } = determinismPartition(plan, shard); + // An unsplit selection keeps its command. A partition of a split one names the selection's + // count: the runner would otherwise plan its lighter subset for more repetitions (#4117). + const repetitions = selection.partitions.length > 1 ? selection.repetitions : repetitionsFor(plan.cadence); + return [{ name: "changed Bun test files repeated under CPU load", + argv: [process.execPath, join(root, "scripts/test-determinism.ts"), `--report=${DETERMINISM_REPORT}`, + ...(repetitions === undefined ? [] : [`--repetitions=${repetitions}`]), ...partition.files], + env: { BRAIN_REQUIRE_CHROME: "1" } }]; + } const names: Record, string[]> = { browser: ["workspace build for real browser checks", "complete pinned visual/accessibility/pointer suite"], layout: ["workspace build for real browser checks", "complete pinned layout/offline suite"], @@ -96,7 +110,7 @@ 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 })}`); + 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("All selected hosted proof passed; remaining skips are planner-intended."); } else { const root = resolve(import.meta.dir, ".."); @@ -114,7 +128,7 @@ 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) : undefined }, null, 2)); + checkout: { sha, tree, parents }, plan, files: category === "unit" ? unitFiles(plan, root, shard) : category === "determinism" ? determinismFiles(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 } }); @@ -125,11 +139,18 @@ 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) : []).includes("tests/workspace-lease.test.ts")) { + 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"); const { image } = await resolveBrowserPin(root); commands.unshift({ name: "pinned offline workspace lease container prerequisite", argv: ["docker", "pull", image], env: {} }); } + if (category === "determinism") { + const { selection, partition } = determinismPartition(plan, shard); + if (selection.partitions.length > 1) console.log(`Partition ${shard} of a selection split by reviewed weight: ${selection.files.length} file(s), ` + + `${selection.weightSeconds.toFixed(1)} weighted s per pass, ${selection.repetitions} repetition(s) each (${selection.requested} requested); ` + + `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)" : ""}.`); + } 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 new file mode 100644 index 0000000000..1f0fd20ab6 --- /dev/null +++ b/scripts/determinism-plan.ts @@ -0,0 +1,109 @@ +/** + * Repetition and partition planning for the hosted `determinism` job (#4109, #4117). + * + * Pure: the planner (scripts/ci-plan.ts), each partition's command + * (scripts/ci-proof.ts) and the runner (scripts/test-determinism.ts) read these + * functions, so they cannot disagree about the repetition count or about which + * partition runs a file. The count is decided first, over the whole selection; + * the selection is then partitioned for that count. + * Policy: docs/decisions/ci-utility.md, "Changed tests repeat under load before merge". + */ +import { DETERMINISM_PARTITIONS } from "./proof-shards"; +import { balanceTests, FILE_COST_SECONDS } from "./test-shards"; + +export const DEFAULT_REPETITIONS = 5; +export const FLOOR_REPETITIONS = 2; +/** + * Ready confirmation runs the floor (#4137, maintainer ruling 2026-11-17). The + * merge lease is held while it runs, and the draft head already ran the full + * count; the floor re-checks the tree that merges without making this job the + * confirmation's longest. Undefined keeps the command's default. + */ +export function repetitionsFor(cadence: string | undefined): number | undefined { + return cadence === "confirmation" ? FLOOR_REPETITIONS : undefined; +} +/** + * Reviewed-weight seconds the repetitions may cost before they are reduced: + * one partition's capacity (#4117), so a selection is split only at the floor. + */ +export const BUDGET_SECONDS: number = DETERMINISM_PARTITIONS.capacitySeconds; +/** A file without a reviewed weight costs the small-file default (scripts/test-shards.ts). */ +const UNWEIGHTED_SECONDS = 0.1; + +export interface FileRepetitions { file: string; weightSeconds: number; weighted: boolean; repetitions: number; observed?: number; } +export interface RepetitionPlan { + requested: number; floor: number; repetitions: number; reduced: boolean; + budgetSeconds: number; weightSeconds: number; estimatedSeconds: number; overBudget: boolean; + files: FileRepetitions[]; +} + +/** + * The same count for every file: the most repetitions that fit the budget, + * never more than requested and never fewer than the floor. A selection too + * heavy for the floor still runs at the floor and is reported over budget. + */ +export function planRepetitions(files: readonly string[], options: { repetitions?: number; floor?: number; budgetSeconds?: number; + costs?: Readonly> } = {}): RepetitionPlan { + const requested = options.repetitions ?? DEFAULT_REPETITIONS, floor = options.floor ?? FLOOR_REPETITIONS; + const budgetSeconds = options.budgetSeconds ?? BUDGET_SECONDS, costs = options.costs ?? FILE_COST_SECONDS; + if (!Number.isSafeInteger(floor) || floor < 2) throw new Error("The repetition floor is at least two: one run proves nothing about the next"); + if (!Number.isSafeInteger(requested) || requested < floor) throw new Error(`Repetitions must be an integer of at least ${floor}`); + if (!Number.isFinite(budgetSeconds) || budgetSeconds <= 0) throw new Error("The time budget must be positive seconds"); + if (new Set(files).size !== files.length) throw new Error("A test file was selected twice"); + const weights = files.map(file => { + const weighted = Object.hasOwn(costs, file), weightSeconds = weighted ? costs[file]! : UNWEIGHTED_SECONDS; + if (!Number.isFinite(weightSeconds) || weightSeconds <= 0) throw new Error(`Test file costs must be positive finite seconds: ${file}`); + return { file, weightSeconds, weighted }; + }); + const weightSeconds = weights.reduce((sum, entry) => sum + entry.weightSeconds, 0); + const fit = weightSeconds > 0 ? Math.floor(budgetSeconds / weightSeconds) : requested; + const repetitions = Math.max(floor, Math.min(requested, fit)); + const estimatedSeconds = weightSeconds * repetitions; + return { requested, floor, repetitions, reduced: repetitions < requested, budgetSeconds, weightSeconds, estimatedSeconds, + overBudget: estimatedSeconds > budgetSeconds, files: weights.map(entry => ({ ...entry, repetitions })) }; +} + +export interface DeterminismPartition { files: string[]; weightSeconds: number; estimatedSeconds: number; } +export interface PartitionPlan extends RepetitionPlan { capacitySeconds: number; maxPartitions: number; partitions: DeterminismPartition[]; } + +/** + * One job while the selection fits one job's capacity at its count; otherwise + * the fewest partitions, balanced longest file first, in which every partition + * fits (#4117). A file cannot be split, so one whose repetitions alone exceed + * the capacity runs in a partition by itself. Every file is in exactly one + * partition, at the count decided over the whole selection. A selection that + * needs more partitions than the maximum is refused: it is never skipped and + * never reduced below the floor. + */ +export function planPartitions(files: readonly string[], options: { cadence?: string; repetitions?: number; + costs?: Readonly>; capacitySeconds?: number; maxPartitions?: number } = {}): PartitionPlan { + const capacitySeconds = options.capacitySeconds ?? DETERMINISM_PARTITIONS.capacitySeconds; + const maxPartitions = options.maxPartitions ?? DETERMINISM_PARTITIONS.max; + 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"); + const plan = planRepetitions([...files].sort(), { repetitions: options.repetitions ?? repetitionsFor(options.cadence), + budgetSeconds: capacitySeconds, costs: options.costs }); + 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++) { + const partitions = balanceTests(names, count, weights).map(partition => { + const weightSeconds = partition.reduce((sum, file) => sum + weights[file]!, 0); + return { files: partition, weightSeconds, estimatedSeconds: weightSeconds * plan.repetitions }; + }); + 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, ` + + `${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.`); +} + +/** 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 selectPartition(plan: PartitionPlan, shard: string): DeterminismPartition { + const match = /^([1-9]\d*)\/([1-9]\d*)$/.exec(shard); + if (!match) throw new Error("Expected proof --shard=M/N"); + const index = Number(match[1]), total = Number(match[2]); + if (!Number.isSafeInteger(index) || !Number.isSafeInteger(total) || index > total) throw new Error("Invalid proof shard"); + if (total !== plan.partitions.length) throw new Error(`Repeated-run partition ${shard} is not in the planned set of ${plan.partitions.length}`); + return plan.partitions[index - 1]!; +} diff --git a/scripts/integration-proof.ts b/scripts/integration-proof.ts index 279781a533..e546a12b3c 100644 --- a/scripts/integration-proof.ts +++ b/scripts/integration-proof.ts @@ -4,7 +4,7 @@ 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 { MAX_UNIT_PARTITIONS, shardNumbers, unitPartitionLimit } from "./proof-shards"; +import { DETERMINISM_PARTITIONS, MAX_UNIT_PARTITIONS, shardNumbers, unitPartitionLimit } from "./proof-shards"; import { coveredCategories } from "./check-receipt"; import type { Category } from "./red-main"; @@ -58,7 +58,8 @@ function inventoryDiagnostic(inventory: any, run: any, head: string): string { const choice = (value: unknown, choices: readonly string[]) => typeof value === "string" && choices.includes(value) ? value : "unrecognized"; 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: MAX_UNIT_PARTITIONS }, (_, index) => `unit (${index + 1})`), + ...Array.from({ length: DETERMINISM_PARTITIONS.max }, (_, index) => `determinism (${index + 1})`)]; const fields = metadataObject(inventory) ? inventory : {}; const jobs = fields.jobs; const predicates: string[] = []; @@ -110,7 +111,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; + selections: Record; results: Record; retained?: unknown; unitShards: string | null; determinismShards?: 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"); @@ -125,6 +126,11 @@ 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 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 dc56dad93f..f8d664f19e 100644 --- a/scripts/proof-shards.ts +++ b/scripts/proof-shards.ts @@ -30,3 +30,15 @@ export function unitPartitions(cadence: string | undefined, files?: number): num if (files !== undefined && !(Number.isSafeInteger(files) && files >= 1)) throw new Error("Empty selected unit inventory"); return Array.from({ length: Math.min(limit, files ?? limit) }, (_, index) => index + 1); } + +/** `determinism` partitions (#4117): the one owner of one job's capacity, the + * most partitions a selection may use and the proof step's limit. Capacity is + * in reviewed-weight seconds at the selection's repetition count, and it is + * also the budget that reduces the count (`BUDGET_SECONDS`, + * scripts/determinism-plan.ts). `loadRatio` is the largest elapsed seconds per + * weighted second measured in a complete hosted run of at least 90 weighted + * seconds; capacity times that ratio must fit the step limit. The planner's + * `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 tests repeat under load before merge". */ +export const DETERMINISM_PARTITIONS = { capacitySeconds: 300, max: 10, stepMinutes: 40, loadRatio: 6.84 } as const; diff --git a/scripts/test-determinism.ts b/scripts/test-determinism.ts index 4c72af7039..c7603988f6 100644 --- a/scripts/test-determinism.ts +++ b/scripts/test-determinism.ts @@ -21,6 +21,10 @@ * Bounded: five repetitions by default, reduced uniformly to a floor of two * when the reviewed weights (scripts/test-shard-costs.json) exceed the budget. * No selected file is dropped; the report lists each with its repetitions. + * The count and the hosted partitions are planned in scripts/determinism-plan.ts: + * hosted CI splits a selection too heavy for one job across partitions (#4117), + * and each partition runs this command with its own files. A local `--base` + * run repeats the whole selection in one invocation. * Policy: docs/decisions/ci-utility.md, "Changed tests repeat under load before merge". */ import { appendFileSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; @@ -28,34 +32,16 @@ import { availableParallelism, constants } from "node:os"; import { dirname, join, resolve } from "node:path"; import { changedFiles, determinismTests } from "./ci-plan"; import { ensureHostAdmission } from "./host-admission.mjs"; -import { discoverTests, FILE_COST_SECONDS } from "./test-shards"; +import { planRepetitions, type RepetitionPlan } from "./determinism-plan"; +import { discoverTests } from "./test-shards"; + +export { BUDGET_SECONDS, DEFAULT_REPETITIONS, FLOOR_REPETITIONS, planRepetitions, repetitionsFor, type FileRepetitions, type RepetitionPlan } from "./determinism-plan"; -export const DEFAULT_REPETITIONS = 5; -export const FLOOR_REPETITIONS = 2; -/** - * Ready confirmation runs the floor (#4137, maintainer ruling 2026-11-17). The - * merge lease is held while it runs, and the draft head already ran the full - * count; the floor re-checks the tree that merges without making this job the - * confirmation's longest. Undefined keeps the command's default. - */ -export function repetitionsFor(cadence: string | undefined): number | undefined { - return cadence === "confirmation" ? FLOOR_REPETITIONS : undefined; -} -/** Total reviewed-weight seconds the repetitions may cost before they are reduced. */ -export const BUDGET_SECONDS = 600; -/** A file without a reviewed weight costs the small-file default (scripts/test-shards.ts). */ -const UNWEIGHTED_SECONDS = 0.1; /** A burner outlives its parent by one slice at most, and never this long. */ const BURNER_LIFETIME_MS = 2 * 60 * 60_000, BURNER_SLICE_MS = 200; export const REPORT_KIND = "brain-test-determinism"; const JUNIT_PATH = "tmp/determinism-junit.xml"; -export interface FileRepetitions { file: string; weightSeconds: number; weighted: boolean; repetitions: number; observed?: number; } -export interface RepetitionPlan { - requested: number; floor: number; repetitions: number; reduced: boolean; - budgetSeconds: number; weightSeconds: number; estimatedSeconds: number; overBudget: boolean; - files: FileRepetitions[]; -} export interface Failure { file: string | null; repetition: number | null; test: string | null; reason: string; } export interface Report extends RepetitionPlan { kind: typeof REPORT_KIND; version: 1; base: string | null; @@ -63,32 +49,6 @@ export interface Report extends RepetitionPlan { failure: Failure | null; load: { burners: number; cpus: number }; elapsedSeconds: number; exitCode: number; } -/** - * The same count for every file: the most repetitions that fit the budget, - * never more than requested and never fewer than the floor. A selection too - * heavy for the floor still runs at the floor and is reported over budget. - */ -export function planRepetitions(files: readonly string[], options: { repetitions?: number; floor?: number; budgetSeconds?: number; - costs?: Readonly> } = {}): RepetitionPlan { - const requested = options.repetitions ?? DEFAULT_REPETITIONS, floor = options.floor ?? FLOOR_REPETITIONS; - const budgetSeconds = options.budgetSeconds ?? BUDGET_SECONDS, costs = options.costs ?? FILE_COST_SECONDS; - if (!Number.isSafeInteger(floor) || floor < 2) throw new Error("The repetition floor is at least two: one run proves nothing about the next"); - if (!Number.isSafeInteger(requested) || requested < floor) throw new Error(`Repetitions must be an integer of at least ${floor}`); - if (!Number.isFinite(budgetSeconds) || budgetSeconds <= 0) throw new Error("The time budget must be positive seconds"); - if (new Set(files).size !== files.length) throw new Error("A test file was selected twice"); - const weights = files.map(file => { - const weighted = Object.hasOwn(costs, file), weightSeconds = weighted ? costs[file]! : UNWEIGHTED_SECONDS; - if (!Number.isFinite(weightSeconds) || weightSeconds <= 0) throw new Error(`Test file costs must be positive finite seconds: ${file}`); - return { file, weightSeconds, weighted }; - }); - const weightSeconds = weights.reduce((sum, entry) => sum + entry.weightSeconds, 0); - const fit = weightSeconds > 0 ? Math.floor(budgetSeconds / weightSeconds) : requested; - const repetitions = Math.max(floor, Math.min(requested, fit)); - const estimatedSeconds = weightSeconds * repetitions; - return { requested, floor, repetitions, reduced: repetitions < requested, budgetSeconds, weightSeconds, estimatedSeconds, - overBudget: estimatedSeconds > budgetSeconds, files: weights.map(entry => ({ ...entry, repetitions })) }; -} - /** The wrapper's argv: one invocation, so preparation builds once for every repetition. */ export function repetitionArgv(files: readonly string[], repetitions: number): string[] { return [process.execPath, "run", "test", `--rerun-each=${repetitions}`, "--bail=1", diff --git a/tests/autonomous-runtime.test.ts b/tests/autonomous-runtime.test.ts index af62622857..f5d1376406 100644 --- a/tests/autonomous-runtime.test.ts +++ b/tests/autonomous-runtime.test.ts @@ -129,3 +129,5 @@ for (const backend of ["claude", "pi"]) describe(`${backend} real autonomous run expect(r.histories[0].length).toBeGreaterThan(0); }); }); + +// Throwaway edit: selects this file for the split-selection qualification of #4117. Not for merge. diff --git a/tests/ci-plan.test.ts b/tests/ci-plan.test.ts index 4209af8fe3..89fc74e776 100644 --- a/tests/ci-plan.test.ts +++ b/tests/ci-plan.test.ts @@ -1,8 +1,11 @@ import { afterEach, describe, expect, test } from "bun:test"; -import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync, chmodSync, symlinkSync } from "node:fs"; +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, selectBrowserClosures, proofCadence } from "../scripts/ci-plan"; +import { changedFiles, FAST_TESTS, FILE_INPUT_TESTS, planChecks, planUnitChecks, planFromEnvironment, workspaces, proofSelections, rootConsumers, ROOT_CONSUMERS, unitShards, determinismShards, selectBrowserClosures, proofCadence } from "../scripts/ci-plan"; + +import { planPartitions } from "../scripts/determinism-plan"; +import { FILE_COST_SECONDS } from "../scripts/test-shards"; const documentGuards = ["tests/docs-paths.test.ts", "tests/decision-citations.test.ts", "tests/public-docs.test.ts"]; @@ -34,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"]) 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"]) 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; @@ -237,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]"}\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]\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); @@ -555,7 +558,8 @@ 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", ...Object.fromEntries(Object.entries(proofSelections(plan)).map(([name, on]) => [name, String(on)])) } as Record }; + return { env, event, outputs: { cadence: "draft", determinism_shards: JSON.stringify(determinismShards(plan)), + ...Object.fromEntries(Object.entries(proofSelections(plan)).map(([name, on]) => [name, String(on)])) } as Record }; }; const selected = outputsFor(withTest, base); expect(selected.outputs.determinism, "DRAFT_SELECTS_REPETITION").toBe("true"); @@ -570,6 +574,50 @@ describe("changed Bun test files repeat under load before merge (#4109)", () => .toThrow("determinism: required candidate selection differs from actual inputs"); }); + test("the executable publishes the planned partitions, and the aggregate refuses any other set (#4117)", async () => { + const { validateSelections } = await import("../scripts/candidate-proof"); + const f = plannerFixture(), base = f.git("rev-parse", "HEAD"); + // Unweighted files at 0.1 s each: 160 weighted s per pass, 320 at the floor of two, one more than one job holds. + // Each exports something, so the planner's leaf-test scan (one read of every tracked file per leaf) stops at the first. + for (let index = 0; index < 1600; index++) f.write(`tests/fleet/ship-${String(index).padStart(4, "0")}.test.ts`, `export {};\n${passing}`); + f.git("add", "."); f.git("commit", "-qm", "a fleet of tests"); const head = f.git("rev-parse", "HEAD"); + const run = async (event: object, extra: Record) => { + const output = join(f.dir, "outputs-fleet"), eventPath = join(f.dir, "event-fleet.json"); + rmSync(output, { force: true }); 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-fleet.json"), ...extra } }); + const [code, err] = await Promise.all([child.exited, new Response(child.stderr).text()]); + return { code, err, outputs: existsSync(output) ? Object.fromEntries(readFileSync(output, "utf8").trim().split("\n").map(line => line.split("="))) as Record : {} }; + }; + const pull = (draft: boolean) => ({ action: draft ? "synchronize" : "ready_for_review", pull_request: { draft, base: { sha: base }, head: { sha: head } } }); + for (const draft of [true, false]) { + const planned = await run(pull(draft), {}); + expect(planned.code, planned.err).toBe(0); + expect([planned.outputs.determinism, planned.outputs.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, pull(draft), env, planned.outputs), "PLANNED_SET_ACCEPTED").not.toThrow(); + const { determinism_shards: _dropped, ...missing } = planned.outputs; + for (const [label, outputs] of [["DROPPED_PARTITION", { ...planned.outputs, determinism_shards: "[1]" }], ["EXTRA_PARTITION", { ...planned.outputs, determinism_shards: "[1,2,3]" }], + ["REORDERED", { ...planned.outputs, determinism_shards: "[2,1]" }], ["MISSING_OUTPUT", missing]] as const) { + expect(() => validateSelections(f.dir, pull(draft), env, outputs), `${label}:draft=${draft}`).toThrow("determinism: published partition set differs from the planned one"); + } + } + // Past the maximum: the heaviest reviewed files, as many as it takes for today's table to refuse them. + const heaviest = Object.entries(FILE_COST_SECONDS).sort((a, b) => b[1] - a[1]).map(([file]) => file); + const refuses = (count: number) => { try { planPartitions(heaviest.slice(0, count), { cadence: "draft" }); return false; } catch { return true; } }; + let count = 1; while (!refuses(count)) count++; + for (const file of heaviest.slice(0, count)) f.write(file, `export {};\n${passing}`); + f.git("add", "."); f.git("commit", "-qm", "the heaviest tests"); const heavy = f.git("rev-parse", "HEAD"); + const refused = await run({ action: "synchronize", pull_request: { draft: true, base: { sha: head }, head: { sha: heavy } } }, { BASE_SHA: head, HEAD_SHA: heavy }); + expect(refused.code, "METADATA_JOB_FAILS_BEFORE_ANY_PARTITION").toBe(1); + expect(refused.err).toContain(`Repeated-run proof refused before it ran: ${count} changed Bun test file(s) weigh `); + expect(refused.err).toContain("That needs more than the limit of 10 partitions of 300 weighted s each"); + expect(refused.outputs, "NOTHING_PUBLISHED").toEqual({}); + // One file fewer is planned, at the maximum or under it. + expect(planPartitions(heaviest.slice(0, count - 1), { cadence: "draft" }).partitions.length).toBeLessThanOrEqual(10); + }); + test("a change that touches no Bun test file never selects it, and a main push never repeats", () => { const f = fixture(); f.write("packages/core/tests/held.test.ts", passing); f.git("add", "."); f.git("commit", "-qm", "an existing test"); const base = f.git("rev-parse", "HEAD"); diff --git a/tests/ci-workflows.test.ts b/tests/ci-workflows.test.ts index 36b1528682..991ed39ad7 100644 --- a/tests/ci-workflows.test.ts +++ b/tests/ci-workflows.test.ts @@ -5,6 +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"; const ROOT = resolve(import.meta.dir, ".."); type Json = null | boolean | number | string | Json[] | { [key: string]: Json }; type Obj = { [key: string]: Json }; @@ -133,7 +134,7 @@ describe("the authoritative jobs retain their important phases", () => { 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"]); // 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", "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", "cadence", "unit_shards", "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"); @@ -586,26 +587,58 @@ test("all unit partitions upload incremental memory diagnostics even after proof test("the determinism job has the unit job's prerequisites and both aggregates observe it (#4109)", () => { const original = read("ci.yml"); const job = ci.jobs.determinism!, unit = ci.jobs.unit!; + const REPEAT = 'bun scripts/ci-proof.ts determinism --shard=${{ matrix.shard }}/"$DETERMINISM_SHARDS"'; const runs = (steps: typeof job.steps) => steps.filter(step => step.run).map(step => step.run); // Changed files may drive real Chrome: the same install, plan and runtime setup as unit. for (const command of ["bun install --frozen-lockfile --backend=copyfile", "bun scripts/ci-plan.ts", "bash scripts/ci-runtime-setup.sh"]) { expect(runs(unit.steps), command).toContain(command); expect(runs(job.steps), `UNIT_PREREQUISITE:${command}`).toContain(command); } - expect(runs(job.steps).indexOf("bash scripts/ci-runtime-setup.sh"), "SETUP_BEFORE_REPETITION").toBeLessThan(runs(job.steps).indexOf("bun scripts/ci-proof.ts determinism")); + expect(runs(job.steps).indexOf("bash scripts/ci-runtime-setup.sh"), "SETUP_BEFORE_REPETITION").toBeLessThan(runs(job.steps).indexOf(REPEAT)); + expect(runs(job.steps), "THE_PARTITION_COMMAND").toContain(REPEAT); expect(job.if).toBe("${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && needs.changeset.outputs.determinism == 'true' }}"); expect((ci.jobs.changeset!.outputs as Obj).determinism).toBe("${{ steps.plan.outputs.determinism }}"); const feedback = Bun.YAML.parse(read("heavy-feedback.yml")) as Workflow; - expect(runs(feedback.jobs.determinism!.steps), "DRAFT_HEAVY_FEEDBACK_REPEATS_TOO").toContain("bun scripts/ci-proof.ts determinism"); + expect(runs(feedback.jobs.determinism!.steps), "DRAFT_HEAVY_FEEDBACK_REPEATS_TOO").toContain(REPEAT); + 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("run: bun scripts/ci-proof.ts determinism\n", "run: echo omitted\n"), "ci.yml")).toContain("ci.yml: determinism: complete proof command is missing"); + 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"); expect(workflowProblems(withoutSetup, "ci.yml"), "UNIT_SETUP_REQUIRED").toContain("ci.yml: determinism: environment setup must have its separate 12-minute limit"); }); +test("the determinism matrix, divisor and step limit come from the planner and its one owner (#4117)", () => { + const text = read("ci.yml"), job = ci.jobs.determinism!; + expect(job.strategy).toEqual({ "fail-fast": false, matrix: { shard: "${{ fromJSON(needs.changeset.outputs.determinism_shards) }}" } }); + const step = job.steps.find(s => s.name === "Repeat changed Bun test files under CPU load")!; + expect(step.env?.DETERMINISM_SHARDS).toBe("${{ strategy.job-total }}"); + expect(step.run).toBe('bun scripts/ci-proof.ts determinism --shard=${{ matrix.shard }}/"$DETERMINISM_SHARDS"'); + expect(step["timeout-minutes"], "STEP_LIMIT_HAS_ONE_OWNER").toBe(DETERMINISM_PARTITIONS.stepMinutes); + expect(job.steps.find(s => s.uses === pinned("actions/upload-artifact@v7"))!.with!.name, "ONE_ARTIFACT_PER_PARTITION").toBe("determinism-proof-${{ matrix.shard }}"); + expect(workflowProblems(text, "ci.yml")).toEqual([]); + const problem = "determinism: matrix and shard divisor must come from the planner's determinism_shards output"; + const matrix = " shard: ${{ fromJSON(needs.changeset.outputs.determinism_shards) }}\n"; + for (const [label, from, to, refusal] of [ + ["LITERAL_ONE_MATRIX", matrix, " shard: [1]\n", problem], + ["LITERAL_MAXIMUM_MATRIX", matrix, " shard: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n", problem], + ["UNIT_PARTITIONS_AS_MATRIX", matrix, " shard: ${{ fromJSON(needs.changeset.outputs.unit_shards) }}\n", problem], + ["SECOND_MATRIX_DIMENSION", matrix, matrix + " worker: [1, 2]\n", problem], + ["NO_MATRIX", " strategy:\n fail-fast: false\n matrix:\n" + matrix, "", problem], + ["UNPARTITIONED_COMMAND", 'determinism --shard=${{ matrix.shard }}/"$DETERMINISM_SHARDS"', "determinism", problem], + ["LITERAL_DIVISOR", 'determinism --shard=${{ matrix.shard }}/"$DETERMINISM_SHARDS"', "determinism --shard=${{ matrix.shard }}/2", problem], + ["LITERAL_DIVISOR_VALUE", "DETERMINISM_SHARDS: ${{ strategy.job-total }}", "DETERMINISM_SHARDS: 2", problem], + ["OUTPUT_NOT_FROM_PLANNER", "determinism_shards: ${{ steps.plan.outputs.determinism_shards }}", 'determinism_shards: "[1]"', problem], + ["SHARED_ARTIFACT_NAME", "name: determinism-proof-${{ matrix.shard }}", "name: determinism-proof", "determinism: each partition must upload its own receipts"], + ["STEP_LIMIT_NOT_THE_OWNERS", " timeout-minutes: 40\n env:\n DETERMINISM_SHARDS:", " timeout-minutes: 60\n env:\n DETERMINISM_SHARDS:", "determinism: proof must retain its 40-minute limit"], + ] 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("runtime categories have distinct complete commands and strict aggregate dependencies", () => { const original = read("ci.yml"); expect(workflowProblems(original.replace("run: bun scripts/ci-proof.ts runtime\n", "run: bun scripts/ci-proof.ts runtime_host\n"), "ci.yml")).toContain("ci.yml: runtime: complete proof command is missing"); diff --git a/tests/egress-first-party-paths.test.ts b/tests/egress-first-party-paths.test.ts index 2664615ac2..149d61b5b9 100644 --- a/tests/egress-first-party-paths.test.ts +++ b/tests/egress-first-party-paths.test.ts @@ -102,3 +102,5 @@ describe("first-party egress paths through the turn proxy", () => { expect(Object.keys(walk.reachable).filter(path => walk.reachable[path] === true), "EGRESS_SOCKET_WALK_NO_REACHABLE_HOST_SOCKET").toEqual([]); }, 300_000); }); + +// Throwaway edit: selects this file for the split-selection qualification of #4117. Not for merge. diff --git a/tests/hosted-proof.test.ts b/tests/hosted-proof.test.ts index c1b430ff58..33e23b51cc 100644 --- a/tests/hosted-proof.test.ts +++ b/tests/hosted-proof.test.ts @@ -3,8 +3,9 @@ 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 { planChecks, proofSelections, unitShards, workspaces, type ProofCadence, type Workspace } from "../scripts/ci-plan"; +import { 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 { planRepetitions } from "../scripts/test-determinism"; import { localChecks } from "../scripts/check-pr"; @@ -59,6 +60,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]" }); 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()]); @@ -70,7 +73,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: null, + results: Object.fromEntries(PROOF_JOBS.map(name => [name, "success"])), retained: [], unitShards: "[1,2,3]", determinismShards: "[1,2]", }); } } @@ -238,11 +241,15 @@ test("the aggregate requires repeated-run proof when selected and an intentional }); test("the hosted repetition command runs the planner's files through the command with real Chrome required (#4109)", () => { - const plan = { ...planChecks(["docs/voyage.md"], workspaces(ROOT)), determinism: ["tests/ci-plan.test.ts", "packages/core/tests/briefing.test.ts"] }; - expect(determinismFiles(plan)).toEqual(["tests/ci-plan.test.ts", "packages/core/tests/briefing.test.ts"]); + // The planner publishes the selection sorted (`determinismTests`), and the runner sorts what it is given. + const plan = { ...planChecks(["docs/voyage.md"], workspaces(ROOT)), determinism: ["packages/core/tests/briefing.test.ts", "tests/ci-plan.test.ts"] }; + expect(determinismFiles(plan)).toEqual(["packages/core/tests/briefing.test.ts", "tests/ci-plan.test.ts"]); const [command, ...rest] = categoryCommands("determinism", plan, ROOT); expect(rest).toEqual([]); - expect(command!.argv.slice(1)).toEqual([join(ROOT, "scripts/test-determinism.ts"), `--report=${DETERMINISM_REPORT}`, "tests/ci-plan.test.ts", "packages/core/tests/briefing.test.ts"]); + expect(command!.argv.slice(1)).toEqual([join(ROOT, "scripts/test-determinism.ts"), `--report=${DETERMINISM_REPORT}`, "packages/core/tests/briefing.test.ts", "tests/ci-plan.test.ts"]); + // One partition is the unsplit job: the workflow's `--shard=1/1` runs the same command (#4117). + expect(categoryCommands("determinism", plan, ROOT, "1/1"), "ONE_PARTITION_KEEPS_THE_COMMAND").toEqual([command!]); + expect(() => categoryCommands("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"); expect(command!.env, "CHANGED_FILES_MAY_DRIVE_REAL_CHROME").toEqual({ BRAIN_REQUIRE_CHROME: "1" }); for (const unselected of [{ ...plan, determinism: [] }, { ...plan, determinism: undefined }]) { expect(() => categoryCommands("determinism", unselected, ROOT), "EMPTY_SELECTION_IS_NEVER_A_JOB").toThrow("Repeated-run proof was not selected"); @@ -288,12 +295,42 @@ 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, + results: Object.fromEntries(PROOF_JOBS.map(name => [name, "success"])), retained: [], unitShards: null, determinismShards: null, }); } } }); +test("an oversized selection runs as planned partitions: every file in exactly one, at the selection's count (#4117)", () => { + const { capacitySeconds, max } = DETERMINISM_PARTITIONS; + // Unweighted names, so the reviewed table cannot move this: 0.1 s each, 160 s per pass, 320 at the floor of two. + const fleet = Array.from({ length: 1600 }, (_, index) => `tests/fleet/ship-${String(index).padStart(4, "0")}.test.ts`); + const selected = { ...planChecks(["docs/voyage.md"], workspaces(ROOT)), determinism: fleet }; + for (const cadence of ["draft", "confirmation", "feedback-heavy"] as const) { + const plan = { ...selected, cadence }; + expect(determinismShards(plan), `PUBLISHED_SET:${cadence}`).toEqual([1, 2]); + const partitions = determinismShards(plan).map(shard => categoryCommands("determinism", plan, ROOT, `${shard}/2`)); + const files = partitions.map(([command]) => command!.argv.slice(command!.argv.indexOf("--repetitions=2") + 1)); + for (const [index, [command, ...rest]] of partitions.entries()) { + expect(rest).toEqual([]); + // 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/test-determinism.ts"), `--report=${DETERMINISM_REPORT}`, "--repetitions=2"]); + expect(files[index]!.length * 0.1 * 2, "WITHIN_CAPACITY").toBeLessThanOrEqual(capacitySeconds); + expect(determinismFiles(plan, `${index + 1}/2`), "RECEIPT_NAMES_THE_PARTITION_FILES").toEqual(files[index]!); + } + expect(files.flat().sort(), `EVERY_FILE_EXACTLY_ONCE:${cadence}`).toEqual(fleet); + for (const shard of [undefined, "1/1", "1/3", "3/3"]) expect(() => categoryCommands("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 armada = { ...selected, cadence: "confirmation" as const, determinism: Array.from({ length: (max * capacitySeconds / 2 + 1) * 10 }, (_, index) => `tests/armada/ship-${index}.test.ts`) }; + const refusal = `weigh ${(armada.determinism.length * 0.1).toFixed(1)} weighted s per pass, ${(armada.determinism.length * 0.2).toFixed(1)} s at the floor of 2 repetitions. That needs more than the limit of ${max} partitions of ${capacitySeconds} weighted s each`; + expect(() => determinismShards(armada), "PLANNER_REFUSES").toThrow(refusal); + expect(() => categoryCommands("determinism", armada, ROOT, "1/10"), "PARTITION_REFUSES").toThrow(refusal); + // Unselected, and on main where repetition never runs, the matrix expression still has one value. + expect(determinismShards({ ...selected, determinism: undefined, cadence: "confirmation" })).toEqual([1]); + expect(determinismShards({ ...armada, cadence: "integrated" }), "MAIN_NEVER_REPEATS").toEqual([1]); +}); + test("ready confirmation repeats changed tests at the floor; every other cadence keeps the full count (#4137)", () => { const selected = { ...planChecks(["docs/voyage.md"], workspaces(ROOT)), determinism: ["tests/ci-plan.test.ts"] }; const argv = (cadence: ProofCadence) => categoryCommands("determinism", { ...selected, cadence }, ROOT)[0]!.argv; diff --git a/tests/integration-proof.test.ts b/tests/integration-proof.test.ts index db893760ea..cb879ff7cf 100644 --- a/tests/integration-proof.test.ts +++ b/tests/integration-proof.test.ts @@ -3,6 +3,7 @@ import { PROOF_JOBS } from "../scripts/ci-proof"; import { 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"; 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 }; @@ -127,17 +128,21 @@ 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[]): Promise { +async function confirmationOutcome(published: unknown, ran: readonly number[], + repeated?: { published?: unknown; ran: readonly (number | string)[]; conclusion?: string }): Promise { // Every hosted proof job, so a category added later (determinism, #4109) is part of the inventory. const categories: readonly string[] = PROOF_JOBS; - const fast = (name: string) => ["verify", "pack", "unit"].includes(name); + // `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); + 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: typeof published === "string" || published === null ? published : JSON.stringify(published) }; + unitShards: encoded(published), ...(repeated && "published" in repeated ? { determinismShards: encoded(repeated.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)) : [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` + @@ -174,7 +179,36 @@ 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 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"; + const outcome = (published: unknown, ran: readonly (number | string)[]) => confirmationOutcome(eight, eight, { published, ran }); + // An unsplit selection is one partition; the largest observed selection plans nine. + expect(await outcome([1], [1]), "ONE_PLANNED_ONE_RAN").toBe(accepted); + expect(await outcome(nine, nine), "NINE_PLANNED_NINE_RAN").toBe(accepted); + expect(await outcome(nine, nine.slice(0, 8)), "DROPPED_LAST_PARTITION").toBe(differs); + expect(await outcome(nine, [1, 2, 3, 5, 6, 7, 8, 9]), "DROPPED_MIDDLE_PARTITION").toBe(differs); + expect(await outcome(nine, [...nine, 9]), "DUPLICATE_PARTITION").toBe(differs); + expect(await outcome([1, 2], [1, 2, 3]), "RAN_MORE_THAN_PLANNED").toBe(differs); + // The job as it was before the matrix: its one name is no planned partition. + expect(await outcome([1], ["determinism"]), "UNPARTITIONED_JOB_NAME").toBe(differs); + const limit = Array.from({ length: 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([2, 3], [2, 3]), "PLAN_WITHOUT_FIRST").toBe(identity); + expect(await outcome([], []), "EMPTY_PLAN").toBe(identity); + expect(await outcome(null, [1]), "NULL_PLAN").toBe(identity); + expect(await confirmationOutcome(eight, eight, { ran: [1] }), "RECEIPT_WITHOUT_THE_SET").toBe(identity); + // A failed partition never reaches the partition check: the inventory itself is refused. + expect(await confirmationOutcome(eight, eight, { published: [1, 2], ran: [1, 2], conclusion: "failure" }), "FAILED_PARTITION").toContain("Incomplete or failed selected job inventory"); + // Unselected, the job is one intentional skip and no partition set is read. + expect(await confirmationOutcome(eight, eight), "UNSELECTED_SKIPS_ONCE").toBe(accepted); +}); + test("refusal diagnostics name every partition a confirmation can plan", async () => { + const repeated = await refusal({ total_count: 2, jobs: [job, { ...job, id: 21, name: `determinism (${DETERMINISM_PARTITIONS.max})`, status: "queued" }] }); + expect(JSON.parse(repeated.split("inventory: ")[1]!).offending[0].job.name).toBe(`determinism (${DETERMINISM_PARTITIONS.max})`); const message = await refusal({ total_count: 2, jobs: [job, { ...job, id: 20, name: "unit (8)", status: "queued" }] }); expect(JSON.parse(message.split("inventory: ")[1]!).offending[0].job.name).toBe("unit (8)"); }); diff --git a/tests/pi-worker-runtime.test.ts b/tests/pi-worker-runtime.test.ts index ad91cb5a1f..72d3f43aba 100644 --- a/tests/pi-worker-runtime.test.ts +++ b/tests/pi-worker-runtime.test.ts @@ -257,3 +257,5 @@ describe("ordinary pi isolated worker", () => { }); }); + +// Throwaway edit: selects this file for the split-selection qualification of #4117. Not for merge. diff --git a/tests/policy-write-boundary.test.ts b/tests/policy-write-boundary.test.ts index 823eeef471..a734b4d856 100644 --- a/tests/policy-write-boundary.test.ts +++ b/tests/policy-write-boundary.test.ts @@ -339,3 +339,5 @@ test("governed Pi writes through an internal symlink using the canonical server expect(r.after.target).toBe("Odysseus writes through the harbor alias.\n"); expect(r.after.policy).toBe(POLICY); }, TIMEOUT); + +// Throwaway edit: selects this file for the split-selection qualification of #4117. Not for merge. diff --git a/tests/test-determinism.test.ts b/tests/test-determinism.test.ts index 76c351c4de..3c84ce7221 100644 --- a/tests/test-determinism.test.ts +++ b/tests/test-determinism.test.ts @@ -9,12 +9,14 @@ import { BUDGET_SECONDS, burnerSource, DEFAULT_REPETITIONS, firstFailure, FLOOR_REPETITIONS, observedRepetitions, parseArguments, planRepetitions, repetitionArgv, REPORT_KIND, startBurners, summaryMarkdown, type Report, } from "../scripts/test-determinism"; +import { planPartitions, selectPartition } from "../scripts/determinism-plan"; +import { DETERMINISM_PARTITIONS } from "../scripts/proof-shards"; const ROOT = join(import.meta.dir, ".."); // The wrapper, its preload and what they import, as tests/experiment-tier.test.ts copies them. const SCRIPTS = ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs", - "test-determinism.ts"]; + "test-determinism.ts", "determinism-plan.ts", "proof-shards.ts"]; const scratch: string[] = []; afterEach(() => { for (const dir of scratch.splice(0)) rmSync(dir, { recursive: true, force: true }); }); @@ -30,7 +32,8 @@ describe("repetition budget", () => { test("a selection inside the budget gets the default five repetitions for every file", () => { const plan = planRepetitions(Object.keys(costs), { costs, budgetSeconds: 250 }); - expect([DEFAULT_REPETITIONS, FLOOR_REPETITIONS, BUDGET_SECONDS]).toEqual([5, 2, 600]); + // The budget is one partition's capacity, so a selection is split only at the floor (#4117). + expect([DEFAULT_REPETITIONS, FLOOR_REPETITIONS, BUDGET_SECONDS]).toEqual([5, 2, DETERMINISM_PARTITIONS.capacitySeconds]); expect(plan).toMatchObject({ requested: 5, repetitions: 5, reduced: false, overBudget: false, weightSeconds: 50, estimatedSeconds: 250 }); expect(plan.files).toEqual([ { file: "tests/argo.test.ts", weightSeconds: 20, weighted: true, repetitions: 5 }, @@ -71,6 +74,93 @@ describe("repetition budget", () => { }); }); +describe("hosted partitions by reviewed weight (#4117)", () => { + const { capacitySeconds, max } = DETERMINISM_PARTITIONS; + /** A fleet of `count` files 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) => + [`tests/fleet/ship-${String(index).padStart(3, "0")}.test.ts`, Number((passSeconds / count * (index % 2 ? 1.5 : 0.5)).toFixed(3))])); + const sum = (values: readonly number[]) => values.reduce((total, value) => total + value, 0); + + test("the calibrated numbers have one owner, and its capacity fits the step limit at the measured load ratio", () => { + expect(DETERMINISM_PARTITIONS).toEqual({ capacitySeconds: 300, max: 10, stepMinutes: 40, loadRatio: 6.84 }); + expect(capacitySeconds * DETERMINISM_PARTITIONS.loadRatio, "CAPACITY_FITS_THE_STEP_LIMIT").toBeLessThanOrEqual(DETERMINISM_PARTITIONS.stepMinutes * 60); + }); + + test("a selection the size of the largest observed plans several partitions, each within capacity, covering every file once", () => { + // The 388-file fixture migration: about 1,327 weighted seconds per pass, 2,654 at the floor of two. + const costs = fleet(388, 1327), files = Object.keys(costs); + for (const cadence of ["draft", "confirmation", "feedback-heavy"]) { + const plan = planPartitions(files, { cadence, costs }); + expect(plan, cadence).toMatchObject({ repetitions: 2, floor: 2, capacitySeconds, maxPartitions: max, overBudget: true }); + expect(plan.estimatedSeconds, "THE_OBSERVED_SIZE").toBeCloseTo(2654, 0); + expect(plan.partitions.length, `SEVERAL_PARTITIONS:${cadence}`).toBe(9); + for (const partition of plan.partitions) { + expect(partition.estimatedSeconds, "EACH_WITHIN_CAPACITY").toBeLessThanOrEqual(capacitySeconds); + expect(partition.estimatedSeconds, "AT_THE_SELECTION_COUNT").toBeCloseTo(sum(partition.files.map(file => costs[file]!)) * 2, 6); + expect(partition.files.length).toBeGreaterThan(0); + } + expect(plan.partitions.flatMap(partition => partition.files).sort(), "EVERY_FILE_EXACTLY_ONCE").toEqual([...files].sort()); + expect(plan.files.map(entry => entry.repetitions), "NO_FILE_BELOW_THE_FLOOR").toEqual(files.map(() => 2)); + } + }); + + test("a selection within one job's capacity stays one partition holding every file", () => { + const costs = { "tests/argo.test.ts": 20, "tests/ithaca.test.ts": 30 }, files = ["tests/ithaca.test.ts", "tests/argo.test.ts"]; + const five = planPartitions(files, { cadence: "draft", costs }); + expect(five.partitions, "FIVE_REPETITIONS_ONE_JOB").toEqual([{ files: ["tests/argo.test.ts", "tests/ithaca.test.ts"], weightSeconds: 50, estimatedSeconds: 250 }]); + expect(five).toMatchObject({ repetitions: 5, reduced: false, overBudget: false }); + // Exactly at capacity is still one job; one weighted second more is two. + expect(planPartitions(files, { cadence: "draft", costs: { ...costs, "tests/ithaca.test.ts": 130 } }), "AT_CAPACITY").toMatchObject({ repetitions: 2, estimatedSeconds: 300, partitions: [{ estimatedSeconds: 300 }] }); + expect(planPartitions(files, { cadence: "draft", costs: { ...costs, "tests/ithaca.test.ts": 131 } }).partitions.map(partition => partition.files), "OVER_CAPACITY_SPLITS") + .toEqual([["tests/ithaca.test.ts"], ["tests/argo.test.ts"]]); + }); + + test("the count is decided first, over the whole selection, and the partitions are made for that count", () => { + const costs = fleet(40, 100), files = Object.keys(costs); + // 100 weighted s per pass: three repetitions fit one job on a draft, and ready confirmation asks for two (#4137). + expect(planPartitions(files, { cadence: "draft", costs })).toMatchObject({ requested: 5, repetitions: 3, partitions: [{ estimatedSeconds: 300 }] }); + expect(planPartitions(files, { cadence: "confirmation", costs })).toMatchObject({ requested: 2, repetitions: 2, partitions: [{ estimatedSeconds: 200 }] }); + // 200 per pass cannot fit even two: both cadences split at the floor, never at a count a lighter partition could afford. + const heavy = fleet(40, 200); + for (const cadence of ["draft", "confirmation"]) { + const plan = planPartitions(Object.keys(heavy), { cadence, costs: heavy }); + expect(plan.repetitions, cadence).toBe(2); + expect(plan.partitions.map(partition => Math.round(partition.estimatedSeconds)), cadence).toEqual([200, 200]); + } + }); + + test("a file whose repetitions alone exceed the capacity runs in a partition by itself", () => { + const costs = { "tests/cyclops.test.ts": 340, "tests/argo.test.ts": 100, "tests/ithaca.test.ts": 40 }; + const plan = planPartitions(Object.keys(costs), { costs }); + expect(plan.partitions.map(partition => [partition.files, partition.estimatedSeconds]), "UNSPLITTABLE_FILE_ALONE") + .toEqual([[["tests/cyclops.test.ts"], 680], [["tests/argo.test.ts", "tests/ithaca.test.ts"], 280]]); + expect(planPartitions(["tests/cyclops.test.ts"], { costs }).partitions).toEqual([{ files: ["tests/cyclops.test.ts"], weightSeconds: 340, estimatedSeconds: 680 }]); + }); + + test("a selection beyond the maximum partition count is refused, naming its weight and the limit", () => { + const costs = fleet(400, 1600), files = Object.keys(costs); + expect(planPartitions(files, { costs, maxPartitions: 11 }).partitions.length, "ELEVEN_WOULD_HOLD_IT").toBe(11); + expect(() => planPartitions(files, { costs })).toThrow( + "Repeated-run proof refused before it ran: 400 changed Bun test file(s) weigh 1600.0 weighted s per pass, 3200.0 s at the floor of 2 repetitions. " + + "That needs more than the limit of 10 partitions of 300 weighted s each (DETERMINISM_PARTITIONS, scripts/proof-shards.ts). " + + "No file is skipped and the count stays at the floor: split the change."); + // More files than the maximum, each unsplittable: still refused, never run short. + const giants = Object.fromEntries(Array.from({ length: 11 }, (_, index) => [`tests/giant-${index}.test.ts`, 200])); + expect(() => planPartitions(Object.keys(giants), { costs: giants })).toThrow("needs more than the limit of 10 partitions"); + expect(() => planPartitions([], { costs })).toThrow("Repeated-run proof was not selected"); + expect(() => planPartitions(files, { costs, maxPartitions: 0 })).toThrow("positive integer"); + }); + + test("a partition is read only with the planned count as its divisor", () => { + const costs = fleet(40, 200), plan = planPartitions(Object.keys(costs), { costs }); + expect(selectPartition(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(() => selectPartition(plan, shard), shard).toThrow(refusal); + } + }); +}); + describe("reading the wrapper's output", () => { const files = ["tests/argo.test.ts", "packages/core/tests/ithaca.test.ts"]; diff --git a/tests/test-invocation.test.ts b/tests/test-invocation.test.ts index bbf52fde31..165e68c9d8 100644 --- a/tests/test-invocation.test.ts +++ b/tests/test-invocation.test.ts @@ -200,3 +200,5 @@ test("replacing a checkout at the same pathname revokes the live build receipt", write("probe.ts", consumerProbe + `expect(invocationBuild(root,["ithaca"])).toBeDefined();renameSync(root,root+".previous");cpSync(root+".previous",root,{recursive:true});source(2);await hook();expect(consume(),"REPLACED_CHECKOUT_REBUILDS_CONSUMER").toBe(2);`); const result = await run(root); expect(result.code, result.output).toBe(0); expect(receipts(root)).toHaveLength(2); }); + +// Throwaway edit: selects this file for the split-selection qualification of #4117. Not for merge. diff --git a/tests/unit-test-consumers.test.ts b/tests/unit-test-consumers.test.ts index 4046ebe5b1..069b30b5ee 100644 --- a/tests/unit-test-consumers.test.ts +++ b/tests/unit-test-consumers.test.ts @@ -320,3 +320,5 @@ test("the whole cross-workspace source class retains every independently discove for (const record of conformance) expect(record.unitOwners, "SPAWNED_CONFORMANCE_IS_UNIT_OWNED").toContain("packages/core/tests/paid-provider-qualification.test.ts"); }); + +// Throwaway edit: selects this file for the split-selection qualification of #4117. Not for merge.