From 7c31606deeafb8571c6ef95be70deeb4a74ca7b8 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 10:41:25 +0000 Subject: [PATCH 1/9] feat(ci): record check:pr outcomes, refuse uncovered local skips and add an expedited red-main fix merge check:pr writes a machine-readable receipt of every selected check (passed/failed/skipped/timed-out/preempted), with an optional per-check budget and explicit --skip; the PR template carries it. integrate.ts refuses a missing receipt and any skipped, timed-out or preempted check whose hosted category the exact-head proof did not run. confirm/merge --fixes-main-run merges a declared fix (forward fix or targeted revert) on red-base/green-head fix probes plus exact-head fast invariants, under the reservation, records it on the red-main record and as an expedited-fix event; ci-timings reports each PR's merge path. Refs #2940 Co-Authored-By: Claude Opus 5.5 --- .agents/skills/work-issue/SKILL.md | 4 +- .../work-issue/references/ci-and-merge.md | 16 ++ .github/PULL_REQUEST_TEMPLATE.md | 8 + .github/workflows/red-main-probe.yml | 12 +- docs/decisions/ci-utility.md | 87 ++++++++++- docs/process/ci-throughput.md | 6 +- docs/process/testing.md | 7 +- scripts/check-pr.ts | 146 ++++++++++++++++-- scripts/check-receipt.ts | 126 +++++++++++++++ scripts/ci-runner.ts | 28 +++- scripts/ci-throughput.ts | 15 +- scripts/integrate.ts | 109 ++++++++++++- scripts/integration-proof.ts | 6 +- scripts/red-main-cli.ts | 14 +- scripts/red-main-coordinator.ts | 5 +- scripts/red-main-expedite.ts | 73 +++++++++ scripts/red-main.ts | 16 +- tests/check-receipt.test.ts | 117 ++++++++++++++ tests/ci-throughput.test.ts | 20 ++- tests/integration-command.test.ts | 79 ++++++++-- tests/local-checks.test.ts | 2 +- tests/red-main-expedite.test.ts | 51 ++++++ tests/red-main.test.ts | 25 ++- 23 files changed, 911 insertions(+), 61 deletions(-) create mode 100644 scripts/check-receipt.ts create mode 100644 scripts/red-main-expedite.ts create mode 100644 tests/check-receipt.test.ts create mode 100644 tests/red-main-expedite.test.ts diff --git a/.agents/skills/work-issue/SKILL.md b/.agents/skills/work-issue/SKILL.md index 00a7513d65..926f0a3c15 100644 --- a/.agents/skills/work-issue/SKILL.md +++ b/.agents/skills/work-issue/SKILL.md @@ -282,7 +282,9 @@ nonpassing final gate. Before `confirm`, run `bun scripts/collisions.ts --json - and record its collisions (or none) with the PR head in the PR. For ordinary candidates, acquire the exact-candidate integration reservation with `bun scripts/integrate.ts confirm --issues owner/repo#N,...` before requesting expensive confirmation; it handles the draft-to-ready transition, -minute renewal and shared proof-checked merge. Hold competing confirmation and +minute renewal and shared proof-checked merge. The PR body must carry the +`check:pr` receipt; skipped or timed-out local checks need exact-head hosted +coverage. A declared red-main fix may use `--fixes-main-run `. Hold competing confirmation and main merges while another lease is live. See the CI reference for explicit acquire/renew/release/revoke, expiry, hard cap and unsupported native candidates. After the last push, convert to draft and mark ready under that reservation to diff --git a/.agents/skills/work-issue/references/ci-and-merge.md b/.agents/skills/work-issue/references/ci-and-merge.md index bcb8b7abfa..ab9abe72fe 100644 --- a/.agents/skills/work-issue/references/ci-and-merge.md +++ b/.agents/skills/work-issue/references/ci-and-merge.md @@ -276,6 +276,22 @@ actor/time/reason and immediately removes the old authority without waiving proof. Native candidates need separately qualified prefix integration; this ordinary command rejects them. See the [binding decision](../../../../docs/decisions/ci-utility.md#exact-candidate-integration-reservation). +The merge path also reads the `check:pr` receipt from the PR body. It refuses +a PR with no receipt (`confirm` says so before acquiring), and one whose +skipped, timed-out or preempted checks map to hosted categories the exact-head +proof did not run, naming each. Rerun the check locally and paste the new +receipt, or get the category selected; never edit a receipt by hand +([local check receipts](../../../../docs/decisions/ci-utility.md#local-check-receipts)). + +While main is red, a declared fix for the open record, forward fix or +targeted revert alike, may use `bun scripts/integrate.ts confirm +--fixes-main-run --issues owner/repo#N,...`. It dispatches fix probes +that must show the record's failing test files red on the exact base and green +on the exact head, waits for the exact-head fast invariants and squashes under +the reservation. It refuses category-level failures; use ordinary confirmation +for those. Never merge a red-main fix any other way +([expedited red-main fixes](../../../../docs/decisions/ci-utility.md#expedited-red-main-fixes)). + While main is red, `confirm` and `merge` refuse every PR that is not a declared fix, and hosted proof containing the bad commit is refused or cancelled. Do not retry it; follow [the red-main incident steps](red-main.md) diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 7062195982..19e997ddeb 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -38,6 +38,14 @@ bun run check:pr --base origin/main tested parent/head/checkout and selected proof; see docs/process/github.md#stacked-pull-requests. --> + + + + ## Checklist - [ ] Focused local preflight/behavioral receipts and complete selected hosted proof passed; actual head/base/job checkout evidence is in Proof. diff --git a/.github/workflows/red-main-probe.yml b/.github/workflows/red-main-probe.yml index ecd3b26f85..f2c64b7151 100644 --- a/.github/workflows/red-main-probe.yml +++ b/.github/workflows/red-main-probe.yml @@ -1,6 +1,9 @@ # Triage probe for the red-main coordinator (#2942). Reruns only the named test -# files at one SHA. A probe never counts as proof and never makes anything -# mergeable; the coordinator reads its result to decide whether main is red. +# files at one SHA. A flake or bisect probe never counts as proof and never makes +# anything mergeable; the coordinator reads its result to decide whether main is +# red. A fix probe is the expedited fix evidence `integrate.ts --fixes-main-run` +# reads (#2940): red at the bad base, green at the fix head. The coordinator +# ignores it. name: red-main-probe run-name: red-main probe ${{ inputs.purpose }} ${{ inputs.source_run }} ${{ inputs.sha }} @@ -8,10 +11,10 @@ on: workflow_dispatch: inputs: purpose: - description: flake or bisect + description: flake, bisect, or fix (expedited red/green evidence for integrate.ts, #2940) required: true type: choice - options: [flake, bisect] + options: [flake, bisect, fix] source_run: description: The main CI run whose failure is triaged required: true @@ -63,4 +66,5 @@ jobs: timeout-minutes: 30 env: PROBE_TESTS: ${{ inputs.tests }} + PROBE_PURPOSE: ${{ inputs.purpose }} run: bun tooling/scripts/red-main-cli.ts probe --target target diff --git a/docs/decisions/ci-utility.md b/docs/decisions/ci-utility.md index 643f5a2dd0..27c2a02098 100644 --- a/docs/decisions/ci-utility.md +++ b/docs/decisions/ci-utility.md @@ -1336,7 +1336,13 @@ claimed as completion. Failures exit 1, with best-effort owned cleanup. This is mandatory cooperative procedure, not an atomic GitHub branch lock. Direct API/UI merges under existing permissions can bypass it or race the -final read; actual squash checks still own reconciliation. No protection, +final read; actual squash checks still own reconciliation. The +[#2940 investigation](https://github.com/schlessera/brain-kit/issues/2940#issuecomment-6574325914) +found 157 merges from 2026-10-22 to 2026-10-26 that bypassed it, and every +merge since 2026-10-26T23:44Z under an exact-head lease. So that a bypass is +visible rather than inferred, `scripts/ci-timings.ts` reports each merged PR's +merge path (`recorded`, `expedited`, `unrecorded` or `unknown`) from the +reservation history and the expedited-fix events. No protection, permission, provider or native merge-queue change is introduced. Native stack candidates remain unsupported by this command pending separately qualified prefix integration; do not flatten them into an ordinary receipt or bypass @@ -1499,7 +1505,84 @@ runs, dispatch probes, read logs and artifacts), `issues: write` (incident and flake issues) and `pull-requests: write` (landed-while-red reports). It runs trusted default-branch tooling and parses candidate logs and artifacts as data. `red-main-probe.yml` has `contents: read` only. The incident workflow in the -skills is #2944, and the expedited fix merge is #2940. +skills is #2944, and the expedited fix merge is #2940 +([below](#expedited-red-main-fixes)). The probe's `fix` purpose serves only +that merge; the coordinator ignores fix probes. + +### Expedited red-main fixes + +[#2940](https://github.com/schlessera/brain-kit/issues/2940) implements answer 7 +of the proof-system lane ruling. `bun scripts/integrate.ts confirm +--fixes-main-run --issues owner/repo#N,...` requires an open red-main +record whose opening run is ``, declares the PR a fix and acquires the +ordinary exact-candidate reservation. It then dispatches `red-main-probe.yml` +with purpose `fix` and the record's failing test files twice: at the exact +base, where they must fail, and at the exact head, where they must pass. Each +probe prints one `BRAIN_RED_MAIN_PROBE` line with its SHA, the files it ran and +its exit code; the merge reads that line, not only the run conclusion, so a +probe that failed during setup is not red evidence. The command also requests a +fresh ready run of `ci.yml` at the exact head and waits only for its metadata +gate and `verify` job: the affected fast invariants. It does not wait for the +rest of that run. When all three are in, it squashes under the reservation with +the same live-candidate, lease, milestone, parent and ancestry checks as an +ordinary merge; the expected tree is the exact base merged with the exact head. +`merge --lease --fixes-main-run ` does the same with evidence +that already exists. + +It refuses a run that is not the open record's, any category-level failure +(no test file to show red and green: use ordinary confirmation as a declared +fix), evidence for other SHAs or other files, a base that did not fail, a head +that did not pass, a draft-cadence run and failed fast invariants. A failing +test file may be absent at the head only when the fix deletes it relative to +the base, which is how a targeted revert removes the failing test its reverted +commit added; a revert is otherwise held to the same evidence as a forward fix. +The local check receipt is not required in this mode: the ruling defines the +expedited proof, and the next main run is the backstop. + +After the squash it appends an `expedited` entry to the open record (fix PR, +head, base, squash, both probe runs, the fast-invariant run, the numeric actor +ID and server time) and records an `expedited-fix` event through +`scripts/ci-timings.ts record` under `tmp/ci-timings`. The record stays open: +the next main run includes the red set, and only its green result clears the +record. A new failure there opens a new incident. No controller merges a fix +by itself. + +### Local check receipts + +`check:pr` writes `tmp/check-pr-receipt.json` (`--receipt ` overrides +it) and prints it at the end as a block for the PR body; the PR template holds +its markers. The receipt names the head, the base ref and mode, and every +selected check with the hosted categories that prove it and one outcome: +`passed`, `failed`, `skipped`, `timed-out` or `preempted`. It is rewritten +after every change, and a started check reads `timed-out` until it settles, so +a run killed from outside still leaves an honest receipt. + +- `--check-timeout=` gives each check a budget. A check that exceeds + it is killed with its process group and recorded `timed-out`; the run goes + on. A signal to `check:pr` records the running check `timed-out` and the + rest `skipped`. +- `--skip ` records a deliberate skip instead of an unrecorded one. +- `preempted` is a check that exited with status 75, host admission's + cancellation ([#2943](https://github.com/schlessera/brain-kit/issues/2943)). + It is neither checked nor failed: `check:pr` exits 75 so it is rerun. +- A failure still stops the run and exits 1; later checks read `skipped`. + Timed-out and skipped checks alone exit 0 with a warning, because the merge + path enforces them. + +`integrate.ts merge` maps each skipped, timed-out or preempted check to its +hosted categories and refuses the candidate when none of them ran successfully +in the exact-head selected proof, naming every such check and the categories it +needs. A category retained by validated proof reuse counts as run. The metadata +gate always runs, so lint, leakage and changeset checks are always covered; an +unknown check maps to no category and can never be covered. + +A PR body with no receipt, or only the template's empty markers, is refused. +`confirm` checks this before it acquires the reservation or requests proof, so +an in-flight PR learns it at once, with the command that fixes it, and never +after a full hosted run. Running `check:pr` and pasting its block is the whole +remedy. The receipt's head is recorded but need not equal the candidate's: +skips are a property of the local run, and coverage is judged against the +exact-head proof. #### Incident workflow and recovery diff --git a/docs/process/ci-throughput.md b/docs/process/ci-throughput.md index 0f26045a60..f7f0a6cf59 100644 --- a/docs/process/ci-throughput.md +++ b/docs/process/ci-throughput.md @@ -67,6 +67,7 @@ execution. It is not complete lifetime cost without complete lifetime coverage. | CI concurrency | Time-weighted executed-job overlap, peak and means while active/across the interval. Adjacent end-exclusive intervals do not invent overlap. | | PR verification concurrency | Distinct PRs with verification intervals, merging overlapping attempts of one PR. Includes queueing; not active agent count. | | Reservation occupancy | Authorized lease intervals, including inferred expiry. Time without observed candidate jobs includes queue/admission/verification and missing observations; not proven waste. | +| Merge path | Per merged PR: `recorded` when the reservation history holds an `integrate.ts` lease for the merged head, `expedited` when an `expedited-fix` event names the PR, `unrecorded` when neither (a merge that bypassed `integrate.ts`), `unknown` when no reservation history was collected (`--reservations`). | Means, medians, p90 and sample counts accompany durations. First-main failing job categories and supplied failure classifications help distinguish pipeline @@ -103,7 +104,10 @@ preserve every worker's archive, including unsuccessful/unmerged work. `failure-classified` requires run, attempt, classification (`product`, `test`, `infrastructure`, `stale-candidate`, `intentional-feedback`) and public repository evidence. `incident`/`revert` require affected `pr` and evidence; `relatedPR` can -name a repair/revert. These are supplied annotations, not independently verified +name a repair/revert. `expedited-fix` requires the fix `pr`, the failing main +`run` and evidence (the head fix probe run); `integrate.ts --fixes-main-run` +records it after an expedited squash +([#2940](../decisions/ci-utility.md#expedited-red-main-fixes)). These are supplied annotations, not independently verified diagnoses. No incident surveillance means unknown overall incident rate. Arbitrary fields such as prompts, names, hosts and prose are refused. Keep event files with normalized snapshots under ignored `tmp/`, not in the public tree. diff --git a/docs/process/testing.md b/docs/process/testing.md index 1fc66bf3e1..762ef41e9b 100644 --- a/docs/process/testing.md +++ b/docs/process/testing.md @@ -433,7 +433,12 @@ in the [CI and merge reference](../../.agents/skills/work-issue/references/ci-an metadata gates and complete affected hosted unit/integration/runtime, keyless funnel, pinned browser proof, strict types and packaging on explicit ready-candidate confirmation events. Agents keep focused local behavioral proof. -- Run `bun run check:pr --base origin/main` before opening or marking ready. +- Run `bun run check:pr --base origin/main` before opening or marking ready, + and paste the receipt block it prints into the PR body. Record a check you + cannot finish with `--check-timeout=` or `--skip ` + rather than dropping it: the merge path refuses a missing receipt, and a + skipped, timed-out or preempted check whose hosted category the exact-head + proof did not run ([local check receipts](../decisions/ci-utility.md#local-check-receipts)). For an upper stack layer, substitute its verified immediate parent ref; see [stack rules](github.md#stacked-pull-requests). Each included PR needs its own selected proof and actual base/head/checkout evidence. diff --git a/scripts/check-pr.ts b/scripts/check-pr.ts index 5b5c31dc30..7f990512af 100644 --- a/scripts/check-pr.ts +++ b/scripts/check-pr.ts @@ -1,9 +1,10 @@ /** Focused local preflight; repeatable full proof is authoritative in hosted CI. */ import { dirname, resolve } from "node:path"; -import { accessSync, constants, readFileSync, statSync } from "node:fs"; +import { accessSync, constants, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs"; import { changedFiles, planChecks, workspaces, type CheckPlan } from "./ci-plan"; -import { runCommands, type Command } from "./ci-runner"; +import { runCommands, type Command, type Settled } from "./ci-runner"; import { checkPackages } from "./check-packages"; +import { checkCategories, PREEMPTED_EXIT, RECEIPT_KIND, receiptBlock, UNPROVEN, type CheckReceipt, type Outcome, type ReceiptCheck } from "./check-receipt"; export function localChecks(plan: CheckPlan, full = false, mergeBase?: string, importGraph = false, importGraphWorkers?: number): Command[] { const bun = process.execPath; @@ -118,11 +119,98 @@ export function requireRuntimeTools(plan: CheckPlan): string | undefined { return chrome; } +/** One preflight step: commands run together, or an in-process task. */ +export type PreflightStep = Command[] | { name: string; task: () => Promise }; +const stepNames = (step: PreflightStep) => Array.isArray(step) ? step.map(command => command.name) : [step.name]; + +export function newReceipt(steps: PreflightStep[], head: string, base: string, mode: CheckReceipt["mode"], now = new Date()): CheckReceipt { + return { version: 1, kind: RECEIPT_KIND, head, base, mode, startedAt: now.toISOString(), finishedAt: null, + checks: steps.flatMap(stepNames).map(name => ({ name, categories: checkCategories(name), outcome: "skipped" as const, reason: "not started" })) }; +} + +/** A check that was started but never settled reads as timed out if check:pr itself is killed. */ +const RUNNING = "started; check:pr ended before it finished"; + +export function settledOutcome(result: Settled, timeoutMs: number | undefined): Pick { + if (result.timedOut) return { outcome: "timed-out", reason: `exceeded the ${timeoutMs} ms check budget` }; + if (result.stopped) return { outcome: "skipped", reason: "stopped by the runner before it finished" }; + if (result.exitCode === PREEMPTED_EXIT && !result.signal) return { outcome: "preempted", reason: "cancelled by host admission; rerun it" }; + if (result.exitCode === 0 && !result.signal) return { outcome: "passed" }; + return { outcome: "failed", reason: `exit ${result.signal ?? result.exitCode}` }; +} + +/** + * Runs the steps in order and records every check's outcome in the receipt, + * saving it after each change. A failure skips the remaining steps; a timed-out, + * preempted or explicitly skipped check is recorded and the run continues. + */ +export async function runPreflight(steps: PreflightStep[], receipt: CheckReceipt, options: { root: string; skip?: ReadonlySet; + timeoutMs?: number; save: (receipt: CheckReceipt) => void; run?: typeof runCommands }): Promise { + const run = options.run ?? runCommands, skip = options.skip ?? new Set(); + const set = (name: string, change: Partial & { outcome: Outcome }) => { + const check = receipt.checks.find(entry => entry.name === name); + if (!check) throw new Error(`Receipt has no check named ${name}`); + delete check.reason; delete check.elapsedMs; Object.assign(check, change); options.save(receipt); + }; + let stop: string | undefined; + try { + for (const step of steps) { + if (stop) { for (const name of stepNames(step)) set(name, { outcome: "skipped", reason: stop }); continue; } + if (!Array.isArray(step)) { + if (skip.has(step.name)) { set(step.name, { outcome: "skipped", reason: "skipped with --skip" }); continue; } + set(step.name, { outcome: "timed-out", reason: RUNNING }); + const started = performance.now(); + try { await step.task(); set(step.name, { outcome: "passed", elapsedMs: performance.now() - started }); } + catch (error) { set(step.name, { outcome: "failed", reason: String(error).slice(0, 300), elapsedMs: performance.now() - started }); stop = `not run after ${step.name} failed`; throw error; } + continue; + } + for (const command of step.filter(command => skip.has(command.name))) set(command.name, { outcome: "skipped", reason: "skipped with --skip" }); + const commands = step.filter(command => !skip.has(command.name)).map(command => ({ ...command, + ...(options.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs }), + started: () => set(command.name, { outcome: "timed-out", reason: RUNNING }), + settled: (result: Settled) => set(command.name, { ...settledOutcome(result, options.timeoutMs), elapsedMs: result.elapsedMs }) })); + if (!commands.length) continue; + try { await run(commands, options.root); } + catch (error) { + if (String(error).includes("Checks interrupted")) { + for (const command of commands) { + const check = receipt.checks.find(entry => entry.name === command.name)!; + if (check.outcome === "skipped" && check.reason === "stopped by the runner before it finished" || check.reason === RUNNING) set(command.name, { outcome: "timed-out", reason: "check:pr was interrupted by a signal while it ran" }); + } + stop = "not run: check:pr was interrupted"; + throw error; + } + const failed = commands.filter(command => receipt.checks.find(entry => entry.name === command.name)!.outcome === "failed"); + if (failed.length || commands.some(command => receipt.checks.find(entry => entry.name === command.name)!.reason === "not started")) { + stop = `not run after ${failed.map(command => command.name).join(", ") || "an earlier check"} failed`; + throw error; + } + } + } + } finally { + if (stop) for (const check of receipt.checks) if (check.reason === "not started") Object.assign(check, { reason: stop }); + receipt.finishedAt = new Date().toISOString(); options.save(receipt); + } + return receipt; +} + +export function writeReceipt(path: string, receipt: CheckReceipt): void { + mkdirSync(dirname(path), { recursive: true }); + // Replace atomically so a killed run never leaves a truncated receipt. + writeFileSync(`${path}.tmp`, JSON.stringify(receipt, null, 2) + "\n"); renameSync(`${path}.tmp`, path); +} + +export const RECEIPT_PATH = "tmp/check-pr-receipt.json"; + if (import.meta.main) { try { const args = process.argv.slice(2); let base = "origin/main"; let all = false; let full = false; let print = false; let importGraph = false; let importGraphWorkers: number | undefined; + let receiptPath = RECEIPT_PATH, timeoutMs: number | undefined; const skip = new Set(); for (let i = 0; i < args.length; i++) { if (args[i] === "--base" && args[i + 1]) base = args[++i]!; + else if (args[i] === "--receipt" && args[i + 1]) receiptPath = args[++i]!; + else if (args[i] === "--skip" && args[i + 1]) skip.add(args[++i]!); + else if (/^--check-timeout=[1-9]\d*$/.test(args[i]!)) timeoutMs = Number(args[i]!.slice("--check-timeout=".length)) * 1000; else if (args[i] === "--all") { all = true; full = true; } else if (args[i] === "--full") full = true; else if (args[i] === "--import-graph") importGraph = true; @@ -131,7 +219,7 @@ if (import.meta.main) { importGraphWorkers = Number(args[i]!.slice("--import-graph-workers=".length)); if (!Number.isSafeInteger(importGraphWorkers)) throw new Error("Import-graph workers must be a positive integer"); } - else throw new Error("usage: bun run check:pr [--base ] [--full|--all] [--import-graph] [--plan] [--import-graph-workers=N]"); + else throw new Error("usage: bun run check:pr [--base ] [--full|--all] [--import-graph] [--plan] [--import-graph-workers=N] [--check-timeout=] [--skip ]... [--receipt ]"); } const root = resolve(import.meta.dir, ".."); const changed = all ? ["package.json"] : changedFiles(root, base, "HEAD", true, true); @@ -150,23 +238,47 @@ if (import.meta.main) { console.log(JSON.stringify({ ...plan, commands: plannedCommands.map(command => command.name), commandDetails: plannedCommands, importGraphFeedback, packedConsumerChecks: full && plan.pack, hostedProofRequired: plan.local }, null, 2)); if (print) process.exit(0); - requireLocalSandbox(); - const chrome = full ? requireRuntimeTools(plan) : undefined; // Setup/metadata are ordered. Full Bun tests and strict types are the only // independent memory-bounded pair; browser jobs stay sequential to retain // the measured scheduling/isolation behavior and diagnostic artifacts. - const env: Record = chrome ? { PUPPETEER_EXECUTABLE_PATH: chrome } : {}; - const withEnv = (command: Command) => ({ ...command, env: { ...env, ...command.env } }); const parallel = commands.filter(command => command.name === "strict typecheck" || command.name === "complete unit and integration suite"); - for (const command of commands.slice(0, 3)) await runCommands([withEnv(command)], root); - await runCommands([contributionChangeset], root); - if (full && plan.local.captures) await runCommands([{ name: "pinned capture fonts and original notices", - argv: [process.execPath, "run", "capture:fonts"] }], root); - if (chrome) await runCommands([{ name: "first real Chrome launch and render", - argv: [process.execPath, "packages/ui-render-puppeteer/tests/cold-start.ts", chrome], env }], root); - await runCommands(parallel.map(withEnv), root); - for (const command of commands.slice(3).filter(command => !parallel.includes(command))) await runCommands([withEnv(command)], root); - if (full && plan.pack) await checkPackages(root); - console.log("Local preflight passed. Record focused receipts; selected hosted proof must pass before merge."); + const chromeStep: Command = { name: "first real Chrome launch and render", argv: [] }; + const steps: PreflightStep[] = [...commands.slice(0, 3).map(command => [command]), [contributionChangeset], + ...(full && plan.local.captures ? [[{ name: "pinned capture fonts and original notices", argv: [process.execPath, "run", "capture:fonts"] }]] : []), + ...(full && plan.local.fullTests ? [[chromeStep]] : []), + ...(parallel.length ? [parallel] : []), + ...commands.slice(3).filter(command => !parallel.includes(command)).map(command => [command]), + ...(full && plan.pack ? [{ name: "packed consumer checks", task: () => checkPackages(root) }] : [])]; + for (const name of skip) if (!steps.flatMap(stepNames).includes(name)) throw new Error(`--skip names no selected check: ${name}`); + const head = new TextDecoder().decode(Bun.spawnSync(["git", "rev-parse", "HEAD"], { cwd: root, stdout: "pipe" }).stdout).trim(); + const receipt = newReceipt(steps, head, base, all ? "all" : full ? "full" : "focused"); + const save = (value: CheckReceipt) => writeReceipt(resolve(root, receiptPath), value); + save(receipt); + try { + requireLocalSandbox(); + const chrome = full ? requireRuntimeTools(plan) : undefined; + if (chrome) { + chromeStep.argv.push(process.execPath, "packages/ui-render-puppeteer/tests/cold-start.ts", chrome); + for (const step of steps) if (Array.isArray(step)) for (const command of step) command.env = { PUPPETEER_EXECUTABLE_PATH: chrome, ...command.env }; + } + } catch (error) { + for (const check of receipt.checks) check.reason = `not run: preflight setup refused (${String(error).slice(0, 200)})`; + receipt.finishedAt = new Date().toISOString(); save(receipt); + throw error; + } + const report = () => { + console.log(`check:pr receipt written to ${receiptPath}. Paste this block into the PR body, replacing any earlier one:\n${receiptBlock(receipt)}`); + }; + try { await runPreflight(steps, receipt, { root, skip, timeoutMs, save }); } + finally { report(); } + const unproven = receipt.checks.filter(check => UNPROVEN.includes(check.outcome)); + if (unproven.some(check => check.outcome === "preempted")) { + console.error(`Local preflight preempted: ${unproven.filter(check => check.outcome === "preempted").map(check => check.name).join(", ")}. Rerun check:pr; a preempted check is neither checked nor failed.`); + process.exit(PREEMPTED_EXIT); + } + if (unproven.length) { + console.warn(`Local preflight incomplete: ${unproven.map(check => `${check.name} (${check.outcome}; hosted ${check.categories.join(" or ") || "none"})`).join("; ")}. ` + + "The receipt records them; integrate.ts refuses the merge unless exact-head hosted proof runs those categories successfully."); + } else console.log("Local preflight passed. Record focused receipts; selected hosted proof must pass before merge."); } catch (error) { console.error(error); process.exit(1); } } diff --git a/scripts/check-receipt.ts b/scripts/check-receipt.ts new file mode 100644 index 0000000000..81d7545166 --- /dev/null +++ b/scripts/check-receipt.ts @@ -0,0 +1,126 @@ +/** + * The machine-readable `check:pr` receipt (#2940). It lists every selected local + * check with its outcome. The PR template carries it, and the merge path in + * `scripts/integrate.ts` refuses a candidate whose skipped, timed-out or + * preempted local checks map to a hosted category that its exact-head hosted + * proof did not run successfully. + */ +import { CATEGORIES, type Category } from "./red-main"; + +export const RECEIPT_KIND = "brain-check-pr-receipt"; +export const RECEIPT_START = ""; +export const RECEIPT_END = ""; +/** + * Exit status of a check cancelled by host admission (#2943): sysexits + * EX_TEMPFAIL. A preempted check must be rerun; it never counts as checked or + * as a failure. + */ +export const PREEMPTED_EXIT = 75; +export const OUTCOMES = ["passed", "failed", "skipped", "timed-out", "preempted"] as const; +export type Outcome = typeof OUTCOMES[number]; +/** Outcomes that leave a check unproven locally; hosted proof must cover them. */ +export const UNPROVEN: readonly Outcome[] = ["skipped", "timed-out", "preempted"]; + +export interface ReceiptCheck { name: string; categories: Category[]; outcome: Outcome; elapsedMs?: number; reason?: string; } +export interface CheckReceipt { + version: 1; kind: typeof RECEIPT_KIND; head: string; base: string; mode: "focused" | "full" | "all"; + startedAt: string; finishedAt: string | null; checks: ReceiptCheck[]; +} + +const RUNTIME = ["measure-claude-runtime", "measure-claude-enforcement", "native delegation, capabilities and measurement isolation", "shared-process Chrome then child cleanup"]; +const RUNTIME_HOST = ["native managed hosted admission", "native separate-UID worker identity", "native reference pool allocation"]; + +/** + * Hosted categories whose exact-head success proves a local check. Any one of + * them suffices. An unknown check maps to none and can never be covered, so a + * new local check cannot silently escape the merge gate. + */ +export function checkCategories(name: string): Category[] { + if (["all lint and leakage gates", "environment documentation", "pending changeset package names", "contribution changeset"].includes(name)) return ["changeset"]; + if (name === "affected fast invariants" || name.startsWith("import-graph affected tests")) return ["verify", "unit"]; + if (name === "strict typecheck") return ["verify"]; + if (name === "complete unit and integration suite" || name === "first real Chrome launch and render") return ["unit"]; + if (name === "workspace build for real browser checks") return ["browser", "layout", "endurance"]; + if (name === "complete pinned visual/accessibility/pointer suite") return ["browser"]; + if (name === "complete pinned layout/offline suite") return ["layout"]; + if (name === "complete pinned endurance suite") return ["endurance"]; + if (name === "editorial provenance and reproducibility" || name === "pinned capture fonts and original notices") return ["captures"]; + if (name === "packed consumer checks") return ["pack"]; + if (RUNTIME.includes(name)) return ["runtime"]; + if (RUNTIME_HOST.includes(name)) return ["runtime_host"]; + return []; +} + +const SHA = /^[a-f0-9]{40}$/; +const stamp = (value: unknown) => typeof value === "string" && Number.isFinite(Date.parse(value)); + +export function parseReceipt(value: unknown): CheckReceipt { + const r = value as CheckReceipt; + if (!r || typeof r !== "object" || r.version !== 1 || r.kind !== RECEIPT_KIND || !SHA.test(r.head ?? "") || + typeof r.base !== "string" || !r.base.length || r.base.length > 200 || !["focused", "full", "all"].includes(r.mode) || + !stamp(r.startedAt) || !(r.finishedAt === null || stamp(r.finishedAt)) || !Array.isArray(r.checks) || !r.checks.length || r.checks.length > 100) throw new Error("Invalid check:pr receipt"); + const names = new Set(); + for (const check of r.checks) { + if (!check || typeof check.name !== "string" || !check.name.length || check.name.length > 200 || names.has(check.name) || + !OUTCOMES.includes(check.outcome) || !Array.isArray(check.categories) || check.categories.some(c => !CATEGORIES.includes(c)) || + (check.elapsedMs !== undefined && !(Number.isFinite(check.elapsedMs) && check.elapsedMs >= 0)) || + (check.reason !== undefined && (typeof check.reason !== "string" || check.reason.length > 300))) throw new Error("Invalid check:pr receipt check"); + names.add(check.name); + } + return r; +} + +/** The block `check:pr` prints for the PR body; the template carries its markers. */ +export function receiptBlock(receipt: CheckReceipt): string { + return [RECEIPT_START, "```json", JSON.stringify(receipt), "```", RECEIPT_END].join("\n"); +} + +/** + * The receipt carried by a PR body: null when the body has none (or only the + * template's empty markers). More than one receipt, or an unreadable one, refuses. + */ +export function receiptFromBody(body: string | null | undefined): CheckReceipt | null { + const text = (body ?? "").replace(/\r\n/g, "\n"); + const blocks: string[] = []; + let at = 0; + for (;;) { + const start = text.indexOf(RECEIPT_START, at); + if (start < 0) break; + const end = text.indexOf(RECEIPT_END, start); + if (end < 0) throw new Error("Unterminated check:pr receipt block in the PR body"); + blocks.push(text.slice(start + RECEIPT_START.length, end)); at = end + RECEIPT_END.length; + } + const filled = blocks.map(block => /```json\s*\n([\s\S]*?)\n\s*```/.exec(block)?.[1]?.trim()).filter((json): json is string => !!json); + if (!filled.length) return null; + if (filled.length > 1) throw new Error("The PR body carries more than one check:pr receipt; keep only the latest"); + let parsed: unknown; + try { parsed = JSON.parse(filled[0]!); } catch { throw new Error("The PR body's check:pr receipt is not JSON"); } + return parseReceipt(parsed); +} + +/** Hosted categories the exact-head selected proof ran successfully (or validly retained). */ +export function coveredCategories(selected: { selections: Record; results: Record; retained: string[] }): Set { + const covered = new Set(["changeset"]); + for (const category of CATEGORIES) { + if (category === "changeset" || selected.selections[category] !== "true") continue; + if (selected.results[category] === "success" || selected.retained.includes(category)) covered.add(category); + } + return covered; +} + +export interface Uncovered { name: string; outcome: Outcome; categories: Category[]; } +/** Local checks the receipt leaves unproven whose hosted categories did not run successfully. */ +export function uncoveredChecks(receipt: CheckReceipt, covered: Set): Uncovered[] { + return receipt.checks.filter(check => UNPROVEN.includes(check.outcome) && !check.categories.some(c => covered.has(c))) + .map(({ name, outcome, categories }) => ({ name, outcome, categories })); +} + +/** The merge decision for an ordinary candidate's receipt; returns the refusal text or null. */ +export function receiptRefusal(body: string | null | undefined, covered: Set): string | null { + const receipt = receiptFromBody(body); + if (!receipt) return "No check:pr receipt in the PR body. Run `bun run check:pr --base origin/main` and paste the block it prints between the receipt markers of the PR template"; + const missing = uncoveredChecks(receipt, covered); + if (!missing.length) return null; + return `Local checks recorded as not run are not covered by exact-head hosted proof: ${missing.map(m => + `${m.name} (${m.outcome}; needs ${m.categories.length ? m.categories.join(" or ") : "no hosted category: rerun it locally"})`).join("; ")}. Rerun them locally and update the receipt, or get the categories selected in hosted proof`; +} diff --git a/scripts/ci-runner.ts b/scripts/ci-runner.ts index 8b544ba199..673f9d766c 100644 --- a/scripts/ci-runner.ts +++ b/scripts/ci-runner.ts @@ -4,7 +4,15 @@ import { dirname, join, resolve } from "node:path"; import type { CheckPlan } from "./ci-plan"; import { balanceTests } from "./test-shards"; -export interface Command { name: string; argv: string[]; env?: Record; compilerRuntime?: boolean; completed?: (elapsedMs: number) => void; } +export interface Settled { exitCode: number | null; signal: string | null; elapsedMs: number; timedOut: boolean; stopped: boolean; } +export interface Command { + name: string; argv: string[]; env?: Record; compilerRuntime?: boolean; completed?: (elapsedMs: number) => void; + /** Kill the check's process group after this many milliseconds and report it as timed out. */ + timeoutMs?: number; + started?: () => void; + /** Every spawned check settles exactly once: finished, failed, timed out or stopped by the runner. */ + settled?: (result: Settled) => void; +} export function verificationCommands(plan: CheckPlan, root: string): Command[] { const commands: Command[] = []; @@ -76,11 +84,25 @@ export async function runCommands(commands: readonly Command[], cwd: string, con } const child = Bun.spawn(command.argv, { cwd, detached: process.platform !== "win32", stdio: ["ignore", "inherit", "inherit"], env }); children.push(child); + command.started?.(); + let timedOut = false, force: ReturnType | undefined; + const budget = command.timeoutMs === undefined ? undefined : setTimeout(() => { + timedOut = true; + const kill = (signal: "SIGTERM" | "SIGKILL") => { + try { if (process.platform === "win32") child.kill(signal); else process.kill(-child.pid, signal); } + catch (error) { if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error; } + }; + kill("SIGTERM"); force = setTimeout(() => kill("SIGKILL"), cleanupGraceMs); + }, command.timeoutMs); const code = await child.exited; + clearTimeout(budget); clearTimeout(force); const elapsedMs = performance.now() - started; - receipt({ event: interrupted || stopped.has(child) ? "interrupted" : "finish", id, name: command.name, - elapsedMs, exitCode: code, signal: child.signalCode ?? null }); + const wasStopped = interrupted || stopped.has(child); + receipt({ event: timedOut || wasStopped ? "interrupted" : "finish", id, name: command.name, + elapsedMs, exitCode: code, signal: child.signalCode ?? null, ...(timedOut ? { timedOut } : {}) }); command.completed?.(elapsedMs); + command.settled?.({ exitCode: code, signal: child.signalCode ?? null, elapsedMs, timedOut, stopped: wasStopped && !timedOut }); + if (timedOut) throw new Error(`${command.name} timed out after ${command.timeoutMs} ms`); if (code !== 0 || child.signalCode) throw new Error(`${command.name} failed (${child.signalCode ?? code})`); } catch (error) { failed = true; throw error; } } diff --git a/scripts/ci-throughput.ts b/scripts/ci-throughput.ts index b442493ab1..f5d6ac6626 100644 --- a/scripts/ci-throughput.ts +++ b/scripts/ci-throughput.ts @@ -11,7 +11,7 @@ export interface PullObservation { mergeObject?: { sha: string; tree: string; parents: string[] }; } export interface WorkEvent { - version: 1; id: string; repository: string; kind: "work-started" | "work-finished" | "wait-started" | "wait-finished" | "failure-classified" | "incident" | "revert"; + version: 1; id: string; repository: string; kind: "work-started" | "work-finished" | "wait-started" | "wait-finished" | "failure-classified" | "incident" | "revert" | "expedited-fix"; at: string; worker?: string; task?: string; reason?: "reservation" | "ci" | "review" | "conflict" | "other"; pr?: number; run?: number; attempt?: number; job?: number; relatedPR?: number; classification?: "product" | "test" | "infrastructure" | "stale-candidate" | "intentional-feedback"; @@ -40,7 +40,7 @@ export function validateWorkEvent(value: unknown): WorkEvent { const allowed = new Set(["version", "id", "repository", "kind", "at", "worker", "task", "reason", "pr", "run", "attempt", "job", "relatedPR", "classification", "evidence"]); if (!e || typeof e !== "object" || Object.keys(e).some(k => !allowed.has(k)) || e.version !== 1 || typeof e.id !== "string" || !/^[a-zA-Z0-9_-]{1,100}$/.test(e.id) || !/^[\w.-]+\/[\w.-]+$/.test(e.repository) || !stamp(e.at) || - !["work-started", "work-finished", "wait-started", "wait-finished", "failure-classified", "incident", "revert"].includes(e.kind)) throw new Error("Invalid coordination event"); + !["work-started", "work-finished", "wait-started", "wait-finished", "failure-classified", "incident", "revert", "expedited-fix"].includes(e.kind)) throw new Error("Invalid coordination event"); for (const field of ["pr", "run", "attempt", "job", "relatedPR"] as const) if (e[field] !== undefined && !number(e[field])) throw new Error(`Invalid event ${field}`); if (/^(work|wait)-/.test(e.kind)) { if (![e.worker, e.task].every(x => typeof x === "string" && /^[a-zA-Z0-9_-]{1,100}$/.test(x))) throw new Error("Opaque worker/task IDs required"); @@ -51,6 +51,7 @@ export function validateWorkEvent(value: unknown): WorkEvent { if (e.kind === "failure-classified" && (!number(e.run) || !number(e.attempt) || !["product", "test", "infrastructure", "stale-candidate", "intentional-feedback"].includes(e.classification ?? ""))) throw new Error("Run/attempt and failure classification required"); if (["incident", "revert"].includes(e.kind) && !number(e.pr)) throw new Error("Affected PR required"); + if (e.kind === "expedited-fix" && (!number(e.pr) || !number(e.run))) throw new Error("Fix PR and failing main run required"); } return Object.fromEntries([...allowed].filter(k => (e as unknown as Record)[k] !== undefined) .map(k => [k, (e as unknown as Record)[k]])) as unknown as WorkEvent; @@ -128,6 +129,10 @@ export function summarizeThroughput(snapshots: TimingSnapshot[], pulls: PullObse events = [...seenEvents.values()].sort((a, b) => Date.parse(a.at) - Date.parse(b.at)); const delivered = pulls.filter(p => p.mergedAt && inWindow(Date.parse(p.mergedAt)) && p.baseBranch === "main"); const ordered = (values: TimingSnapshot[]) => [...values].sort((a, b) => Date.parse(a.run.createdAt) - Date.parse(b.run.createdAt) || a.run.id - b.run.id || a.run.attempt - b.run.attempt); + // The recorded merge path (#2940): an integrate.ts lease for the merged head, an expedited fix, or neither. + const mergePath = (p: PullObservation, mergeAt: number): "expedited" | "recorded" | "unrecorded" | "unknown" => + events.some(e => e.kind === "expedited-fix" && e.pr === p.number) ? "expedited" : !leases ? "unknown" : + leases.some(l => l.pr === p.number && l.head === p.head && l.acquired <= mergeAt) ? "recorded" : "unrecorded"; const prRows = delivered.map(p => { const mergeAt = Date.parse(p.mergedAt!), pre = rows.filter(s => s.run.event === "pull_request" && s.run.prs.length === 1 && s.run.prs[0] === p.number && Date.parse(s.run.createdAt) <= mergeAt); const main = ordered(rows.filter(s => s.run.event === "push" && s.run.head === p.merge)); @@ -151,7 +156,8 @@ export function summarizeThroughput(snapshots: TimingSnapshot[], pulls: PullObse mergeToGreenSeconds: postGreen ? seconds(p.mergedAt, new Date(completed(postGreen)!).toISOString()) : null, createToGreenSeconds: postGreen ? seconds(p.createdAt, new Date(completed(postGreen)!).toISOString()) : null, observedRunnerSeconds: [...pre, ...main].reduce((n, s) => n + execution(s), 0), - equivalence, incidents: events.filter(e => ["incident", "revert"].includes(e.kind) && e.pr === p.number).map(e => e.id) }; + equivalence, incidents: events.filter(e => ["incident", "revert"].includes(e.kind) && e.pr === p.number).map(e => e.id), + mergePath: mergePath(p, mergeAt) }; }); const firstKnown = prRows.filter(p => p.firstMainOutcome !== "unknown"), firstGreen = prRows.filter(p => p.firstMainOutcome === "success"); const eventual = prRows.filter(p => p.mergeToGreenSeconds !== null), paired = prRows.filter(p => p.preAttempts && p.postAttempts); @@ -219,6 +225,8 @@ export function summarizeThroughput(snapshots: TimingSnapshot[], pulls: PullObse classifiedFailedAttempts: percentage(failed.filter(s => classified.has(`${s.run.id}/${s.run.attempt}`)).length, failed.length), classificationRecords: events.filter(e => e.kind === "failure-classified").map(e => ({ id: e.id, run: e.run, attempt: e.attempt, job: e.job, classification: e.classification, evidence: e.evidence })), explicitIncidentOrRevertRecords: events.filter(e => ["incident", "revert"].includes(e.kind)).length, + mergePaths: Object.fromEntries((["recorded", "expedited", "unrecorded", "unknown"] as const).map(k => [k, prRows.filter(p => p.mergePath === k).length])), + expeditedFixRecords: events.filter(e => e.kind === "expedited-fix").map(e => ({ id: e.id, pr: e.pr, run: e.run, at: e.at, evidence: e.evidence })), incidentRate: null, note: "No incident records does not establish no incidents. Green-main discordance is not a diagnosed escaped defect; same-source recovery is not a diagnosed flaky test." }, parallelism: { ciJobs: concurrency(jobIntervals, window), distinctPRVerification: concurrency([...byPR.values()].flatMap(mergeIntervals), window), recordedWorkers: workByWorker.size ? concurrency([...workByWorker.values()].flatMap(mergeIntervals), window) : null, @@ -263,6 +271,7 @@ export function throughputMarkdown(r: ReturnType): s return `| ${k} | ${d.n} | ${format(d.mean === null ? null : d.mean / 60)} | ${format(d.median === null ? null : d.median / 60)} | ${format(d.p90 === null ? null : d.p90 / 60)} |`; }), "", `Peak observed CI jobs: ${r.parallelism.ciJobs.peak}; peak distinct PR verification intervals: ${r.parallelism.distinctPRVerification.peak}. Worker concurrency: ${r.parallelism.recordedWorkers ? r.parallelism.recordedWorkers.peak : "unknown (no complete worker records)"}.`, `Reservation occupied wall-seconds: ${r.reservation ? format(r.reservation.activeWallSeconds) : "unknown"}; caller reservation wait remains unknown without wait records.`, + `Merge paths: ${JSON.stringify(r.reliability.mergePaths)}; expedited red-main fixes: ${r.reliability.expeditedFixRecords.length}. Unrecorded merges bypassed integrate.ts; unknown means no reservation history was collected.`, `Final candidate receipt / immutable squash comparisons: ${JSON.stringify(r.evidence.squashComparedToRecordedReceipt)}. Differences require contextual review; unknown is not equivalent.`, `Scenario: ${JSON.stringify(r.scenario.assumptions)}; equivalent full runs/PR ${format(r.scenario.equivalentFullRunsPerPR)}; estimated compute saving ${format(r.scenario.estimatedSavingPercent)}%; full reference samples: ${r.scenario.baselineSamples}.`, "Causal wall-time and reliability improvements remain unknown. Guarantee satisfaction requires the existing independent proof/merge validation; these rates do not replace it.", ""].join("\n"); diff --git a/scripts/integrate.ts b/scripts/integrate.ts index 1cc7130806..af00c70d3f 100644 --- a/scripts/integrate.ts +++ b/scripts/integrate.ts @@ -4,8 +4,10 @@ import { scanText } from "./check-leakage"; import { GitReservationStore, assertLease, liveLease, reservationServerTime, reservationTransition, RENEW_MS, sameCandidate, type Candidate, type Operation, type Lease } from "./integration-reservation"; import { latestIntegrationRun, verifyIntegrationProof } from "./integration-proof"; -import { declareFix, gateDecision, type RedMainRecord } from "./red-main"; +import { declareFix, gateDecision, recordExpedited, type RedMainRecord } from "./red-main"; import { isAncestor } from "./red-main-cli"; +import { expeditedProblems, expeditedTests, fixProbeTitle, probeReceipt, type FeedbackEvidence, type ProbeEvidence } from "./red-main-expedite"; +import { receiptFromBody, receiptRefusal } from "./check-receipt"; import type { API } from "./proof-reuse"; async function gh(...args: string[]): Promise { @@ -74,6 +76,18 @@ if (import.meta.main) { } throw new Error("Concurrent coordination update; bounded retries exhausted"); } + /** Durable record of an expedited fix: the red-main record (coordination ref history) and a ci-timings event. */ + async function recordExpeditedFix(desired: Candidate, fixesRun: number, squash: string, evidence: Awaited>) { + try { + await changeRedMain((record, now) => recordExpedited(record, { pr: desired.pr, head: desired.head, base: desired.base, squash, + baseProbe: evidence.baseProbe!.run, headProbe: evidence.headProbe!.run, feedbackRun: evidence.feedback!.run, actor, at: now }, now)); + const dir = `${store!.root}/tmp/ci-timings`, file = `${store!.root}/tmp/expedited-fix-${desired.pr}.json`; + await Bun.write(file, JSON.stringify({ kind: "expedited-fix", pr: desired.pr, run: fixesRun, + evidence: `https://github.com/${repository}/actions/runs/${evidence.headProbe!.run}` })); + const child = Bun.spawnSync([process.execPath, `${import.meta.dir}/ci-timings.ts`, "record", "--repo", repository, "--event", file, "--out", dir], { stdout: "pipe", stderr: "pipe" }); + if (child.exitCode !== 0) throw new Error(new TextDecoder().decode(child.stderr).trim()); + } catch (error) { console.error(`Expedited fix merged but its record is incomplete; record it by hand: ${String(error)}`); } + } function heartbeat() { timer = setInterval(() => { pending = pending.then(async () => { if (!lost) try { await renew(); } catch (error) { lost = error; } }); return pending; }, RENEW_MS); } @@ -92,11 +106,54 @@ if (import.meta.main) { if (issue.milestone?.title !== live.milestone.title) throw new Error(`Release milestone mismatch: ${ref}`); } } - async function merge(issueRefs: string[]) { + async function probeRuns(): Promise { + return (await api.json(`actions/workflows/red-main-probe.yml/runs?event=workflow_dispatch&per_page=50`)).workflow_runs ?? []; + } + async function fixProbe(source: number, sha: string, after = 0): Promise { + const run = (await probeRuns()).filter(r => r.display_title === fixProbeTitle(source, sha) && r.id > after).sort((a, b) => b.id - a.id)[0]; + if (!run) return null; + if (run.status !== "completed") return { run: run.id, status: run.status, conclusion: null, receipt: null }; + const jobs = (await api.json(`actions/runs/${run.id}/attempts/${run.run_attempt}/jobs?per_page=100`)).jobs ?? []; + const job = jobs.find((entry: { name: string }) => entry.name === "probe"); + return { run: run.id, status: "completed", conclusion: run.conclusion, receipt: job ? probeReceipt(await api.log(job.id)) : null }; + } + async function feedbackEvidence(desired: Candidate): Promise { + const run = await latestIntegrationRun(api, "ci.yml", desired); + if (!run) return null; + const jobs = (await api.json(`actions/runs/${run.id}/attempts/${run.run_attempt}/jobs?per_page=100`)).jobs ?? []; + const find = (name: string) => jobs.find((job: { name: string }) => job.name === name); + const done = (job: any) => job?.status === "completed" ? job.conclusion as string : null; + const changeset = find("changeset"); + const cadence = done(changeset) ? /"cadence":\s*"(\w+)"/.exec(await api.log(changeset.id))?.[1] ?? null : null; + return { run: run.id, cadence, changeset: done(changeset), verify: done(find("verify")) }; + } + /** Expedited fix evidence for the exact candidate; throws the ruling's refusals. */ + async function expeditedEvidence(desired: Candidate, fixesRun: number, after = { probe: 0, run: 0 }) { + const tests = expeditedTests(store!.read().redMain, fixesRun); + for (const sha of [desired.head, desired.base]) if (Bun.spawnSync(["git", "cat-file", "-e", `${sha}^{commit}`], { cwd: store!.root }).exitCode !== 0) store!.git(["fetch", "origin", sha]); + const deleted = store!.git(["diff", "--name-only", "--no-renames", "--diff-filter=D", `${desired.base}...${desired.head}`]).split("\n").filter(Boolean); + const run = await feedbackEvidence(desired), feedback = run && run.run > after.run ? run : null; + const [baseProbe, headProbe] = [await fixProbe(fixesRun, desired.base, after.probe), await fixProbe(fixesRun, desired.head, after.probe)]; + return { tests, baseProbe, headProbe, feedback, problems: expeditedProblems({ tests, base: desired.base, head: desired.head, deleted, baseProbe, headProbe, feedback }) }; + } + async function merge(issueRefs: string[], fixesRun?: number, after?: { probe: number; run: number }) { if (!own) throw new Error("Explicit owned reservation required"); heartbeat(); const desired = own.candidate; - const proof = await verifyIntegrationProof(store!.root, repository, desired, api, sha => { store!.git(["fetch", "origin", sha]); }); + let tree: string, candidateRun: number, expedited: Awaited> | undefined; + if (fixesRun === undefined) { + const proof = await verifyIntegrationProof(store!.root, repository, desired, api, sha => { store!.git(["fetch", "origin", sha]); }); + const refusal = receiptRefusal((await api.json(`pulls/${desired.pr}`)).body, proof.covered); + if (refusal) throw new Error(refusal); + tree = proof.checkout.tree; candidateRun = proof.run; + } else { + expedited = await expeditedEvidence(desired, fixesRun, after); + if (expedited.problems.length) throw new Error(`Expedited fix proof refused: ${expedited.problems.join("; ")}`); + // The squash must equal the exact base merged with the exact probed head. + const merged = Bun.spawnSync(["git", "merge-tree", "--write-tree", desired.base, desired.head], { cwd: store!.root, stdout: "pipe", stderr: "pipe" }); + if (merged.exitCode !== 0) throw new Error("The fix head does not merge cleanly onto the exact base"); + tree = new TextDecoder().decode(merged.stdout).split("\n")[0]!.trim(); candidateRun = expedited.feedback!.run; + } await milestones(desired.pr, issueRefs); await stopHeartbeat(); if (lost) throw lost; @@ -107,24 +164,30 @@ if (import.meta.main) { const merged = await api.json(`pulls/${desired.pr}`); if (!merged.merged || !merged.merge_commit_sha) throw new Error("Merge not complete; no delivery claim"); const commit = await api.json(`git/commits/${merged.merge_commit_sha}`); - if (commit.parents?.length !== 1 || commit.parents[0]?.sha !== desired.base || commit.tree?.sha !== proof.checkout.tree) throw new Error("Actual squash parent/tree differ; reconcile actual main before claiming completion"); + if (commit.parents?.length !== 1 || commit.parents[0]?.sha !== desired.base || commit.tree?.sha !== tree) throw new Error("Actual squash parent/tree differ; reconcile actual main before claiming completion"); store!.git(["fetch", "origin", "main"]); store!.git(["merge-base", "--is-ancestor", merged.merge_commit_sha, "origin/main"]); await milestones(desired.pr, issueRefs); await change({ kind: "release", id: own.id }); own = undefined; + if (expedited) await recordExpeditedFix(desired, fixesRun!, merged.merge_commit_sha, expedited); const main = await api.json(`actions/workflows/ci.yml/runs?event=push&head_sha=${merged.merge_commit_sha}&per_page=10`); const mainProof = "pending; inspect actual main jobs before claiming full completion"; const observedMainConclusion = main.workflow_runs?.[0]?.conclusion ?? null; - console.log(JSON.stringify({ merged: true, sha: merged.merge_commit_sha, candidateRun: proof.run, mainProof, observedMainConclusion })); + console.log(JSON.stringify({ merged: true, sha: merged.merge_commit_sha, candidateRun, mainProof, observedMainConclusion, + ...(expedited ? { expedited: { fixesMainRun: fixesRun, baseProbe: expedited.baseProbe!.run, headProbe: expedited.headProbe!.run, + backstop: "the next main run includes the open red set; only its green result clears the record" } } : {}) })); process.exitCode = 2; // A run summary alone never completes actual main proof reconciliation. } try { const [command, target, ...options] = process.argv.slice(2), values = new Map(); for (let index = 0; index < options.length; index += 2) { const key = options[index]!, value = options[index + 1]; - if (!["--issues", "--lease"].includes(key) || !value || value.startsWith("--") || values.has(key)) throw new Error("Invalid integration options"); + if (!["--issues", "--lease", "--fixes-main-run"].includes(key) || !value || value.startsWith("--") || values.has(key)) throw new Error("Invalid integration options"); values.set(key, value); } const issues = values.has("--issues") ? values.get("--issues")!.split(",") : []; + const fixesRun = values.has("--fixes-main-run") ? Number(values.get("--fixes-main-run")) : undefined; + if (fixesRun !== undefined && (!/^[1-9]\d*$/.test(values.get("--fixes-main-run")!) || !Number.isSafeInteger(fixesRun))) throw new Error("--fixes-main-run needs a main CI run ID"); + if (fixesRun !== undefined && !["confirm", "merge"].includes(command ?? "")) throw new Error("--fixes-main-run applies to confirm and merge only"); if (issues.some(value => !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+#[1-9]\d*$/.test(value)) || issues.length > 100) throw new Error("Invalid delivered issue identities"); repository = await gh("repo", "view", "--json", "nameWithOwner", "--jq", ".nameWithOwner"); const user = JSON.parse(await gh("api", "user")); actor = user.id; @@ -159,6 +222,13 @@ if (import.meta.main) { if (current && current.id === values.get("--lease") && current.actor === actor && current.candidate.pr === Number(target) && current.candidate.repository === `https://github.com/${repository}`) own = current; } const desired = await candidate(Number(target)); + if (fixesRun !== undefined) { + // Refuse a run that is not the open record's, or category-only failures, before any write. + expeditedTests(store.read().redMain, fixesRun); + console.log(JSON.stringify({ declared: (await changeRedMain((record, now) => declareFix(record, desired.pr, now))).open?.fixes })); + } else if (command !== "acquire" && !receiptFromBody((await api.json(`pulls/${desired.pr}`)).body)) { + throw new Error(receiptRefusal("", new Set())!); + } refuseWhileRed(desired); if (command === "merge") { const lease = values.get("--lease"); @@ -166,7 +236,30 @@ if (import.meta.main) { const state = store.read().state; if (state.active?.id === lease && state.active.actor === actor) own = state.active; assertLease(state, lease, actor, desired, await clock()); - await merge(issues); + await merge(issues, fixesRun); + } else if (command === "confirm" && fixesRun !== undefined) { + own = await acquire(desired); + console.log(JSON.stringify({ acquired: own })); + heartbeat(); + const tests = expeditedTests(store.read().redMain, fixesRun); + const after = { probe: Math.max(0, ...(await probeRuns()).map(r => r.id)), run: (await latestIntegrationRun(api, "ci.yml", desired))?.id ?? 0 }; + for (const sha of [desired.base, desired.head]) await gh("api", "--method", "POST", + `repos/${repository}/actions/workflows/red-main-probe.yml/dispatches`, "-f", "ref=main", "-f", "inputs[purpose]=fix", + "-f", `inputs[source_run]=${fixesRun}`, "-f", `inputs[sha]=${sha}`, "-f", `inputs[tests]=${JSON.stringify(tests)}`); + const live = await api.json(`pulls/${desired.pr}`); + if (!sameCandidate(await candidate(desired.pr), desired)) throw new Error("Candidate changed before the expedited request"); + assertLease(store.read().state, own.id, actor, desired, await clock()); + // A fresh ready request runs the exact-head affected fast invariants; the rest of that run is not waited for. + if (!live.draft) await gh("pr", "ready", String(desired.pr), "--repo", repository, "--undo"); + await gh("pr", "ready", String(desired.pr), "--repo", repository); + while (!lost) { + const { baseProbe, headProbe, feedback } = await expeditedEvidence(desired, fixesRun, after); + const pending = [baseProbe, headProbe].some(probe => probe?.status !== "completed") || !feedback || feedback.changeset === null || + (feedback.changeset === "success" && feedback.verify === null); + if (!pending) { await stopHeartbeat(); await merge(issues, fixesRun, after); break; } + await Bun.sleep(RENEW_MS); + } + if (lost) throw lost; } else { own = await acquire(desired); console.log(JSON.stringify({ acquired: own })); @@ -194,7 +287,7 @@ if (import.meta.main) { if (lost) throw lost; } } - } else throw new Error("usage: bun scripts/integrate.ts inspect | main-status [--json] | declare-fix | acquire/confirm/merge [--lease id] [--issues owner/repo#N,...] | renew/release | revoke "); + } else throw new Error("usage: bun scripts/integrate.ts inspect | main-status [--json] | declare-fix | acquire/confirm/merge [--lease id] [--issues owner/repo#N,...] [--fixes-main-run ] | renew/release | revoke "); } catch (error) { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1; } finally { diff --git a/scripts/integration-proof.ts b/scripts/integration-proof.ts index a1b8957abb..ff05ad3949 100644 --- a/scripts/integration-proof.ts +++ b/scripts/integration-proof.ts @@ -5,6 +5,8 @@ import type { Candidate } from "./integration-reservation"; import type { API } from "./proof-reuse"; import { PROOF_JOBS, proofProblems } from "./ci-proof"; import { shardNumbers } from "./proof-shards"; +import { coveredCategories } from "./check-receipt"; +import type { Category } from "./red-main"; export function checkoutFromJob(log: string): string { const lines = log.replace(/\x1b\[[0-9;]*m/g, "").split("\n"); @@ -67,7 +69,7 @@ function inventoryDiagnostic(inventory: any, run: any, head: string): string { } export async function verifyIntegrationProof(root: string, repository: string, candidate: Candidate, api: API, - fetchCheckout: (sha: string) => void): Promise<{ run: number; checkout: Checkout }> { + fetchCheckout: (sha: string) => void): Promise<{ run: number; checkout: Checkout; covered: Set }> { const run = await latestIntegrationRun(api, "ci.yml", candidate); const contract = await latestIntegrationRun(api, "contract.yml", candidate); if (run?.status !== "completed" || run.conclusion !== "success" || contract?.status !== "completed" || contract.conclusion !== "success") throw new Error("Complete current-candidate CI and contract proof required"); @@ -110,5 +112,5 @@ export async function verifyIntegrationProof(root: string, repository: string, c await validateCandidate(root, { action: receipt.event, pull_request: { number: candidate.pr, draft: false, head: { sha: candidate.head }, base: { ref: "main", sha: candidate.base } } }, { GITHUB_EVENT_NAME: "pull_request", GITHUB_SHA: receipt.checkout.sha, GITHUB_REPOSITORY: repository }, api, receipt.checkout); - return { run: run.id, checkout: receipt.checkout }; + return { run: run.id, checkout: receipt.checkout, covered: coveredCategories(selected) }; } diff --git a/scripts/red-main-cli.ts b/scripts/red-main-cli.ts index 09573ad99c..1013b59523 100644 --- a/scripts/red-main-cli.ts +++ b/scripts/red-main-cli.ts @@ -11,6 +11,7 @@ import { changedFiles, planChecks, proofSelections, redMainSnapshot, workspaces import { GitReservationStore, reservationServerTime, type Snapshot as StoreSnapshot } from "./integration-reservation"; import { coordinate, type CoordinatorIO, type WorkflowRun } from "./red-main-coordinator"; import { gateDecision, type Category } from "./red-main"; +import { PROBE_RECEIPT } from "./red-main-expedite"; // Hosted jobs run from the checkout root; fixtures run from their own repository. const root = process.cwd(); @@ -125,11 +126,16 @@ if (import.meta.main) { await coordinate(liveIO(repository), event.workflow_run as WorkflowRun); } else if (command === "probe") { const target = resolve(rest[rest.indexOf("--target") + 1] ?? ""); - const tests = JSON.parse(process.env.PROBE_TESTS ?? "[]") as unknown; + const tests = JSON.parse(process.env.PROBE_TESTS ?? "[]") as unknown, purpose = process.env.PROBE_PURPOSE ?? "flake"; + if (!["flake", "bisect", "fix"].includes(purpose)) throw new Error("Unknown probe purpose"); if (!Array.isArray(tests) || !tests.length || tests.length > 50 || tests.some(test => typeof test !== "string" || - !/^[A-Za-z0-9_./@-]+\.test\.[cm]?[jt]sx?$/.test(test) || test.split("/").includes("..") || !existsSync(join(target, test)))) throw new Error("Probe tests must be existing test files at the probed SHA"); - const child = Bun.spawn([process.execPath, "run", "test", ...tests], { cwd: target, stdout: "inherit", stderr: "inherit" }); - process.exit(await child.exited); + !/^[A-Za-z0-9_./@-]+\.test\.[cm]?[jt]sx?$/.test(test) || test.split("/").includes(".."))) throw new Error("Probe tests must be test file paths"); + const present = (tests as string[]).filter(test => existsSync(join(target, test))), absent = (tests as string[]).filter(test => !present.includes(test)); + // Only an expedited fix probe may find a file absent: a targeted revert can delete the failing test it reverts. + if (absent.length && purpose !== "fix") throw new Error("Probe tests must be existing test files at the probed SHA"); + const exitCode = present.length ? await Bun.spawn([process.execPath, "run", "test", ...present], { cwd: target, stdout: "inherit", stderr: "inherit" }).exited : 0; + console.log(`${PROBE_RECEIPT} ${JSON.stringify({ purpose, sha: must(["git", "rev-parse", "HEAD"], target), tests: present, absent, exitCode })}`); + process.exit(exitCode); } else throw new Error("usage: bun scripts/red-main-cli.ts gate | coordinate [--dry-run --run ] | probe --target "); } catch (error) { console.error(error instanceof Error ? error.message : String(error)); process.exit(1); } } diff --git a/scripts/red-main-coordinator.ts b/scripts/red-main-coordinator.ts index 33d3e26ef9..db7042fd60 100644 --- a/scripts/red-main-coordinator.ts +++ b/scripts/red-main-coordinator.ts @@ -262,7 +262,10 @@ async function handleMainRun(io: CoordinatorIO, run: WorkflowRun) { io.print(`BRAIN_RED_MAIN ${JSON.stringify({ firstBad: withIncident.open?.firstBad, incident: withIncident.open?.incident, cancelled })}`); } -/** Probe run names carry their purpose, source run and SHA; tests come from the record. */ +/** + * Probe run names carry their purpose, source run and SHA; tests come from the record. + * `fix` probes are expedited fix evidence for integrate.ts (#2940) and are ignored here. + */ export function probeIdentity(title: string): { purpose: "flake" | "bisect"; source: number; sha: string } | null { const match = /^red-main probe (flake|bisect) ([1-9]\d*) ([a-f0-9]{40})$/.exec(title); return match ? { purpose: match[1] as "flake" | "bisect", source: Number(match[2]), sha: match[3]! } : null; diff --git a/scripts/red-main-expedite.ts b/scripts/red-main-expedite.ts new file mode 100644 index 0000000000..8555c65a03 --- /dev/null +++ b/scripts/red-main-expedite.ts @@ -0,0 +1,73 @@ +/** + * Expedited red-main fix proof (#2940, ruling 7 of #2938). A declared fix (a + * forward fix or a targeted revert) merges ahead of complete candidate proof + * when the open record's failing test files are shown red on the bad base and + * green on the fix head, and the exact-head affected fast invariants pass. The + * next main run, which includes the red set, is the complete backstop. + */ +import type { RedMainRecord } from "./red-main"; + +export const PROBE_RECEIPT = "BRAIN_RED_MAIN_PROBE"; +export const fixProbeTitle = (source: number, sha: string) => `red-main probe fix ${source} ${sha}`; + +export interface ProbeReceipt { purpose: string; sha: string; tests: string[]; absent: string[]; exitCode: number; } +export interface ProbeEvidence { run: number; status: string; conclusion: string | null; receipt: ProbeReceipt | null; } +export interface FeedbackEvidence { run: number; cadence: string | null; changeset: string | null; verify: string | null; } + +/** The single structured line a probe prints after running its files. */ +export function probeReceipt(log: string): ProbeReceipt | null { + const lines = log.split("\n").filter(line => line.includes(`${PROBE_RECEIPT} `)); + if (lines.length !== 1) return null; + try { + const r = JSON.parse(lines[0]!.slice(lines[0]!.indexOf(`${PROBE_RECEIPT} `) + PROBE_RECEIPT.length + 1).trim()) as ProbeReceipt; + if (!r || typeof r.purpose !== "string" || !/^[a-f0-9]{40}$/.test(r.sha ?? "") || !Array.isArray(r.tests) || !Array.isArray(r.absent) || + ![...r.tests, ...r.absent].every(test => typeof test === "string") || !Number.isSafeInteger(r.exitCode)) return null; + return r; + } catch { return null; } +} + +/** + * The failing test files an expedited fix must show red and green. Refuses a run + * that is not the open record's, and category-level failures with no test file. + */ +export function expeditedTests(record: RedMainRecord, run: number): string[] { + const open = record.open; + if (!open) throw new Error("Main is not red: --fixes-main-run needs an open red-main record"); + if (open.run !== run) throw new Error(`--fixes-main-run ${run} does not match the open red-main record's run ${open.run}`); + const categories = open.failures.filter(failure => failure.test === null).map(failure => failure.category); + if (categories.length) throw new Error(`Category-level red failures (${[...new Set(categories)].join(", ")}) have no failing test file to show red and green; an expedited fix cannot prove them. Use ordinary confirmation as a declared fix`); + return [...new Set(open.failures.map(failure => failure.test!))].sort(); +} + +const same = (a: string[], b: string[]) => JSON.stringify([...a].sort()) === JSON.stringify([...b].sort()); + +/** + * Problems with the expedited evidence; empty means it satisfies the ruling. + * `deleted` lists files the fix head deletes relative to the base: only those may + * be absent at the head, which is how a targeted revert removes a failing test. + */ +export function expeditedProblems(input: { tests: string[]; base: string; head: string; deleted: string[]; + baseProbe: ProbeEvidence | null; headProbe: ProbeEvidence | null; feedback: FeedbackEvidence | null }): string[] { + const problems: string[] = []; + const { tests, base, head, baseProbe, headProbe, feedback } = input; + const label = tests.join(", "); + if (!baseProbe || baseProbe.status !== "completed") problems.push(`no completed fix probe at the bad base ${base}`); + else { + const r = baseProbe.receipt; + if (!r || r.purpose !== "fix" || r.sha !== base) problems.push(`fix probe ${baseProbe.run} has no receipt for the bad base ${base}`); + else if (r.absent.length || !same(r.tests, tests)) problems.push(`fix probe ${baseProbe.run} did not run every failing test file at the bad base (${label})`); + else if (r.exitCode === 0 || baseProbe.conclusion !== "failure") problems.push(`the failing tests were not shown red on the bad base ${base} (probe ${baseProbe.run})`); + } + if (!headProbe || headProbe.status !== "completed") problems.push(`no completed fix probe at the fix head ${head}`); + else { + const r = headProbe.receipt; + if (!r || r.purpose !== "fix" || r.sha !== head) problems.push(`fix probe ${headProbe.run} has no receipt for the fix head ${head}`); + else if (!same([...r.tests, ...r.absent], tests)) problems.push(`fix probe ${headProbe.run} did not cover every failing test file at the fix head (${label})`); + else if (r.absent.some(test => !input.deleted.includes(test))) problems.push(`failing test files absent at the fix head without the fix deleting them: ${r.absent.filter(test => !input.deleted.includes(test)).join(", ")}`); + else if (r.exitCode !== 0 || headProbe.conclusion !== "success") problems.push(`the failing tests were not shown green on the fix head ${head} (probe ${headProbe.run})`); + } + if (!feedback) problems.push(`no hosted CI run at the fix head ${head} for its affected fast invariants`); + else if (!["feedback", "confirmation"].includes(feedback.cadence ?? "")) problems.push(`CI run ${feedback.run} at the fix head is a ${feedback.cadence ?? "unknown"} run, which selects no fast invariants`); + else if (feedback.changeset !== "success" || !["success", "skipped"].includes(feedback.verify ?? "")) problems.push(`affected fast invariants did not pass at the fix head (CI run ${feedback.run}: changeset ${feedback.changeset ?? "pending"}, verify ${feedback.verify ?? "pending"})`); + return problems; +} diff --git a/scripts/red-main.ts b/scripts/red-main.ts index 34a7fd0d18..b2b9e8abeb 100644 --- a/scripts/red-main.ts +++ b/scripts/red-main.ts @@ -16,12 +16,16 @@ export type Signature = "timeout" | "assertion" | "setup" | "unknown"; export type Verdict = "real" | "suspected-flake"; export interface RedFailure { test: string | null; category: Category; verdict: "real"; reasons: string[]; run: number; sha: string; } +/** An expedited fix squash (#2940): its red/green probe evidence, fast-invariant run and numeric actor. */ +export interface ExpeditedFix { pr: number; head: string; base: string; squash: string; baseProbe: number; headProbe: number; feedbackRun: number; actor: number; at: number; } export interface RedIncident { /** First red after the last run where the failing set actually ran green. */ firstBad: string; run: number; opened: number; failures: RedFailure[]; incident: number | null; fixes: number[]; reported: string[]; /** The one fix claim (#2944). Absent in records written before claims existed. */ claim?: FixClaim | null; + /** Optional and additive: absent until an expedited fix lands. */ + expedited?: ExpeditedFix[]; } /** Who owns the fix: a worker under an orchestrator, for a renewable term. */ export interface FixClaim { @@ -35,7 +39,7 @@ export interface RedMainRecord { version: 1; updated: number; open: RedIncident | null; suspects: Suspect[]; last: { action: Action; at: number; run: number | null } | null; } -const ACTIONS = ["open", "update", "refine", "incident", "declare-fix", "report", "clear", "suspect", "probe", "claim", "takeover", "renew-claim", "release-claim"] as const; +const ACTIONS = ["open", "update", "refine", "incident", "declare-fix", "report", "clear", "suspect", "probe", "claim", "takeover", "renew-claim", "release-claim", "expedite"] as const; type Action = typeof ACTIONS[number]; /** A claim lasts this long from its last renewal; after that any orchestrator may take it over. */ export const CLAIM_TERM_MS = 60 * 60_000; @@ -60,7 +64,9 @@ export function parseRedMain(text: string): RedMainRecord { !Array.isArray(o.fixes) || o.fixes.length > MAX_FIXES || !o.fixes.every(positive) || !Array.isArray(o.reported) || o.reported.length > MAX_REPORTED || !o.reported.every(sha => SHA.test(sha)) || o.failures.some(f => !f || !(f.test === null || testPath(f.test)) || !category(f.category) || f.verdict !== "real" || - !Array.isArray(f.reasons) || !f.reasons.length || f.reasons.some(x => typeof x !== "string" || !/^[a-z0-9-]{1,60}$/.test(x)) || !positive(f.run) || !SHA.test(f.sha)))) throw new Error("Invalid red-main incident"); + !Array.isArray(f.reasons) || !f.reasons.length || f.reasons.some(x => typeof x !== "string" || !/^[a-z0-9-]{1,60}$/.test(x)) || !positive(f.run) || !SHA.test(f.sha)) || + (o.expedited !== undefined && (!Array.isArray(o.expedited) || o.expedited.length > MAX_FIXES || o.expedited.some(e => !e || + ![e.pr, e.baseProbe, e.headProbe, e.feedbackRun, e.actor].every(positive) || ![e.head, e.base, e.squash].every(sha => SHA.test(sha)) || !Number.isSafeInteger(e.at)))))) throw new Error("Invalid red-main incident"); if (o && Object.hasOwn(o, "claim") && !validClaim(o.claim, o, r.updated)) throw new Error("Invalid red-main fix claim"); if (r.last !== null && (!r.last || r.last.at !== r.updated || !(r.last.run === null || positive(r.last.run)) || !ACTIONS.includes(r.last.action))) throw new Error("Invalid red-main audit"); @@ -152,6 +158,12 @@ export function releaseFixClaim(record: RedMainRecord, who: Claimant, now: numbe const open = claimable(record, who), held = open.claim ?? null; if (!held || !sameClaimant(held, who)) throw new Error("This worker does not hold the fix claim"); return next(record, now, "release-claim", open.run, { open: { ...open, claim: null } }); +/** Records an expedited fix squash on the open record; the next green main run that includes the red set still clears it. */ +export function recordExpedited(record: RedMainRecord, fix: ExpeditedFix, now: number): RedMainRecord { + if (!record.open) throw new Error("No open red-main record to record an expedited fix on"); + if (!record.open.fixes.includes(fix.pr)) throw new Error("Only a declared fix can be recorded as expedited"); + if (record.open.expedited?.some(e => e.squash === fix.squash)) return record; + return next(record, now, "expedite", record.open.run, { open: { ...record.open, expedited: [...record.open.expedited ?? [], fix].slice(-MAX_FIXES) } }); } export function reportLanded(record: RedMainRecord, sha: string, now: number): RedMainRecord { diff --git a/tests/check-receipt.test.ts b/tests/check-receipt.test.ts new file mode 100644 index 0000000000..a0533bc366 --- /dev/null +++ b/tests/check-receipt.test.ts @@ -0,0 +1,117 @@ +import { afterEach, expect, test } from "bun:test"; +import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { localChecks, newReceipt, runPreflight, settledOutcome, type PreflightStep } from "../scripts/check-pr"; +import { checkCategories, coveredCategories, parseReceipt, receiptBlock, receiptFromBody, receiptRefusal, RECEIPT_END, RECEIPT_START, + uncoveredChecks, type CheckReceipt } from "../scripts/check-receipt"; +import { planChecks, workspaces } from "../scripts/ci-plan"; +import type { Command } from "../scripts/ci-runner"; + +const dirs: string[] = []; +afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); }); +const head = "a".repeat(40); +const command = (name: string, script: string): Command => ({ name, argv: [process.execPath, "-e", script] }); + +test("a check forced past its budget is recorded timed-out and the run continues (#2940)", async () => { + const dir = mkdtempSync(join(tmpdir(), "odysseus-receipt-")); dirs.push(dir); + const steps: PreflightStep[] = [[command("all lint and leakage gates", "await Bun.sleep(30000)")], [command("affected fast invariants", "process.exit(0)")]]; + const saved: string[] = []; + const receipt = await runPreflight(steps, newReceipt(steps, head, "origin/main", "focused"), { root: dir, timeoutMs: 300, save: r => saved.push(JSON.stringify(r)) }); + expect(receipt.checks.map(c => [c.name, c.outcome])).toEqual([["all lint and leakage gates", "timed-out"], ["affected fast invariants", "passed"]]); + expect(receipt.checks[0]!.reason).toContain("300 ms check budget"); + expect(receipt.finishedAt).not.toBeNull(); + // Saved while running: a killed check:pr leaves the started check reading as timed out. + expect(saved.some(text => text.includes("started; check:pr ended before it finished"))).toBe(true); +}); + +test("outcomes: preempted is neither passed nor failed, a failure skips the rest, --skip is recorded", async () => { + expect(settledOutcome({ exitCode: 75, signal: null, elapsedMs: 1, timedOut: false, stopped: false }, undefined).outcome).toBe("preempted"); + expect(settledOutcome({ exitCode: 0, signal: null, elapsedMs: 1, timedOut: false, stopped: false }, undefined).outcome).toBe("passed"); + expect(settledOutcome({ exitCode: null, signal: "SIGTERM", elapsedMs: 1, timedOut: false, stopped: true }, undefined).outcome).toBe("skipped"); + expect(settledOutcome({ exitCode: 1, signal: null, elapsedMs: 1, timedOut: false, stopped: false }, undefined).outcome).toBe("failed"); + const dir = mkdtempSync(join(tmpdir(), "odysseus-receipt-")); dirs.push(dir); + const steps: PreflightStep[] = [[command("environment documentation", "process.exit(75)")], [command("strict typecheck", "process.exit(0)")], + [command("contribution changeset", "process.exit(3)")], [command("affected fast invariants", "process.exit(0)")]]; + const receipt = newReceipt(steps, head, "origin/main", "focused"); + await expect(runPreflight(steps, receipt, { root: dir, skip: new Set(["strict typecheck"]), save: () => {} })).rejects.toThrow("contribution changeset failed"); + expect(receipt.checks.map(c => c.outcome)).toEqual(["preempted", "skipped", "failed", "skipped"]); + expect(receipt.checks[1]!.reason).toBe("skipped with --skip"); + expect(receipt.checks[3]!.reason).toBe("not run after contribution changeset failed"); + expect(parseReceipt(JSON.parse(JSON.stringify(receipt)))).toEqual(receipt); +}); + +test("every selected local check maps to a hosted category", () => { + const root = resolve(import.meta.dir, ".."); + const plan = planChecks(["package.json"], workspaces(root), root); + const names = [...localChecks(plan, true), ...localChecks(plan, false, "b".repeat(40), true)].map(c => c.name) + .concat(["contribution changeset", "first real Chrome launch and render", "pinned capture fonts and original notices", "packed consumer checks", + "complete pinned visual/accessibility/pointer suite", "complete pinned layout/offline suite", "complete pinned endurance suite", "editorial provenance and reproducibility"]); + for (const name of names) expect(checkCategories(name).length, name).toBeGreaterThan(0); + expect(checkCategories("an unknown future check")).toEqual([]); +}); + +function receipt(checks: CheckReceipt["checks"]): CheckReceipt { + return { version: 1, kind: "brain-check-pr-receipt", head, base: "origin/main", mode: "focused", startedAt: "2026-07-12T00:00:00.000Z", finishedAt: "2026-07-12T00:05:00.000Z", checks }; +} + +test("the PR body carries one receipt; missing, empty markers and duplicates are explicit", () => { + const r = receipt([{ name: "strict typecheck", categories: ["verify"], outcome: "passed" }]); + const body = `## Proof\n\n${receiptBlock(r)}\n`; + expect(receiptFromBody(body)).toEqual(r); + expect(receiptFromBody(body.replace(/\n/g, "\r\n"))).toEqual(r); + expect(receiptFromBody(null)).toBeNull(); + expect(receiptFromBody(`${RECEIPT_START}\n${RECEIPT_END}`)).toBeNull(); + expect(() => receiptFromBody(body + body)).toThrow("more than one"); + expect(() => receiptFromBody(`${RECEIPT_START}\n\`\`\`json\n{"version":2}\n\`\`\`\n${RECEIPT_END}`)).toThrow("Invalid check:pr receipt"); + expect(receiptRefusal("no receipt here", new Set())).toContain("No check:pr receipt"); +}); + +test("merge refusal names skipped, timed-out and preempted checks whose hosted category did not run", () => { + const selected = { selections: { verify: "true", browser: "true", layout: "true", unit: "false" }, results: { verify: "success", browser: "skipped", layout: "skipped" }, retained: ["layout"] }; + const covered = coveredCategories(selected); + expect([...covered].sort()).toEqual(["changeset", "layout", "verify"]); + const r = receipt([ + { name: "strict typecheck", categories: ["verify"], outcome: "timed-out" }, + { name: "complete pinned visual/accessibility/pointer suite", categories: ["browser"], outcome: "skipped" }, + { name: "complete unit and integration suite", categories: ["unit"], outcome: "preempted" }, + { name: "complete pinned layout/offline suite", categories: ["layout"], outcome: "skipped" }, + { name: "environment documentation", categories: ["changeset"], outcome: "failed" }, + ]); + expect(uncoveredChecks(r, covered).map(c => c.name)).toEqual(["complete pinned visual/accessibility/pointer suite", "complete unit and integration suite"]); + const refusal = receiptRefusal(receiptBlock(r), covered)!; + expect(refusal).toContain("complete pinned visual/accessibility/pointer suite (skipped; needs browser)"); + expect(refusal).toContain("complete unit and integration suite (preempted; needs unit)"); + expect(receiptRefusal(receiptBlock(receipt([{ name: "strict typecheck", categories: ["verify"], outcome: "skipped" }])), covered)).toBeNull(); +}); + +test("check:pr CLI writes a receipt recording a forced timeout and prints the PR block", async () => { + const dir = mkdtempSync(join(tmpdir(), "odysseus-check-pr-cli-")); dirs.push(dir); + const owner = resolve(import.meta.dir, ".."), entry = join(dir, "scripts/check-pr.ts"); + mkdirSync(join(dir, "scripts")); mkdirSync(join(dir, "packages/ithaca"), { recursive: true }); + cpSync(join(owner, "scripts/check-pr.ts"), entry); + for (const helper of ["ci-plan", "ci-runner", "check-packages", "check-receipt"]) writeFileSync(join(dir, `scripts/${helper}.ts`), `export * from ${JSON.stringify(join(owner, `scripts/${helper}.ts`))};\n`); + writeFileSync(join(dir, "package.json"), JSON.stringify({ private: true, workspaces: ["packages/*"] })); + writeFileSync(join(dir, "packages/ithaca/package.json"), JSON.stringify({ name: "@odysseus/ithaca" })); + writeFileSync(join(dir, ".gitignore"), "tmp/\n"); + // Only the checks' own commands are replaced: the lint gate hangs, everything else passes. + const preload = join(dir, "odysseus-slow-lint.ts"); + writeFileSync(preload, `const sync=Bun.spawnSync, spawn=Bun.spawn; + Bun.spawnSync=((argv,options)=>{const c=Array.isArray(argv)?argv:argv.cmd;if(c[0]==="bwrap")return {exitCode:0,exitedDueToTimeout:false,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)};return sync(argv,options);}); + Bun.spawn=((argv,options)=>spawn(argv.includes("lint")?[process.execPath,"-e","await Bun.sleep(30000)"]:[process.execPath,"-e","process.exit(0)"],options));`); + const git = (...args: string[]) => Bun.spawnSync(["git", "-c", "commit.gpgsign=false", "-c", "user.name=Odysseus", "-c", "user.email=odysseus@example.invalid", ...args], { cwd: dir, stdout: "pipe" }); + git("init", "-q"); git("add", "."); git("commit", "-qm", "fixture"); + const base = new TextDecoder().decode(git("rev-parse", "HEAD").stdout).trim(); + writeFileSync(join(dir, "packages/ithaca/README.md"), "The return to Ithaca.\n"); + const child = Bun.spawn([process.execPath, "--preload", preload, entry, "--base", base, "--check-timeout=1"], { cwd: dir, stdout: "pipe", stderr: "pipe" }); + const [code, out, err] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); + const path = join(dir, "tmp/check-pr-receipt.json"); + expect(existsSync(path), `CHECK_PR_WRITES_RECEIPT: ${err}`).toBe(true); + const written = parseReceipt(JSON.parse(readFileSync(path, "utf8"))); + expect(written.head).toBe(base); + expect(written.checks.find(c => c.name === "all lint and leakage gates")?.outcome, "FORCED_TIMEOUT_RECORDED").toBe("timed-out"); + expect(written.checks.filter(c => c.name !== "all lint and leakage gates").every(c => c.outcome === "passed")).toBe(true); + expect(code, err).toBe(0); + expect(err).toContain("Local preflight incomplete"); + expect(receiptFromBody(out)).toEqual(written); +}); diff --git a/tests/ci-throughput.test.ts b/tests/ci-throughput.test.ts index a847ba6223..8225dda9cb 100644 --- a/tests/ci-throughput.test.ts +++ b/tests/ci-throughput.test.ts @@ -2,7 +2,7 @@ import { expect, test } from "bun:test"; import { mkdtempSync, rmSync, writeFileSync, readFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { collectPullObservation, concurrency, summarizeThroughput, validateWorkEvent, type PullObservation, type WorkEvent } from "../scripts/ci-throughput"; +import { collectPullObservation, concurrency, summarizeThroughput, throughputMarkdown, validateWorkEvent, type PullObservation, type WorkEvent } from "../scripts/ci-throughput"; import { attachTimingEvidence, type TimingSnapshot } from "../scripts/ci-timings"; import { declareFix, emptyRedMain, openRed } from "../scripts/red-main"; import { collectReservationHistory, mergeLeaseObservations, reservationObservations, type LeaseObservation } from "../scripts/ci-coordination"; @@ -178,3 +178,21 @@ test("native event recording is append-only and refuses arbitrary personal field expect(() => validateWorkEvent({ ...event, kind: "failure-classified", run: 1, attempt: 1, classification: "product" })).toThrow("evidence"); } finally { rmSync(dir, { recursive: true, force: true }); } }); + +test("the merge path is recorded per PR and expedited fixes are reported (#2940)", () => { + const lease = (pr: number, leaseHead: string): LeaseObservation => ({ id: "1".repeat(32), pr, head: leaseHead, base, acquired: Date.parse(at(5)), expires: Date.parse(at(10)), + cap: Date.parse(at(65)), endedAt: Date.parse(at(10)), ending: "release", sources: ["e".repeat(40)] }); + const pre = run(1, "pull_request", 4, 8); + expect(summarizeThroughput([pre], [pull()], [], window, reference, scenario, [lease(42, head)]).prs[0]!.mergePath).toBe("recorded"); + const bypass = summarizeThroughput([pre], [pull()], [], window, reference, scenario, [lease(42, "f".repeat(40))]); + expect(bypass.prs[0]!.mergePath, "MERGE_WITHOUT_EXACT_HEAD_LEASE_IS_UNRECORDED").toBe("unrecorded"); + expect(bypass.reliability.mergePaths).toEqual({ recorded: 0, expedited: 0, unrecorded: 1, unknown: 0 }); + expect(summarizeThroughput([pre], [pull()], [], window, reference, scenario).prs[0]!.mergePath).toBe("unknown"); + const event: WorkEvent = { version: 1, id: "expedited-42", repository: repo, kind: "expedited-fix", at: at(10), pr: 42, run: 11, + evidence: `https://github.com/${repo}/actions/runs/302` }; + const expedited = summarizeThroughput([pre], [pull()], [event], window, reference, scenario, [lease(42, head)]); + expect(expedited.prs[0]!.mergePath).toBe("expedited"); + expect(expedited.reliability.expeditedFixRecords).toEqual([{ id: "expedited-42", pr: 42, run: 11, at: at(10), evidence: event.evidence }]); + expect(throughputMarkdown(expedited)).toContain("expedited red-main fixes: 1"); + expect(() => validateWorkEvent({ ...event, run: undefined })).toThrow("Fix PR and failing main run required"); +}); diff --git a/tests/integration-command.test.ts b/tests/integration-command.test.ts index c91c342996..fcc5d84257 100644 --- a/tests/integration-command.test.ts +++ b/tests/integration-command.test.ts @@ -1,14 +1,16 @@ import { afterEach, beforeEach, expect, test } from "bun:test"; -import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { join, resolve } from "node:path"; import { tmpdir } from "node:os"; import { GitReservationStore, emptyReservation, reservationTransition, MAX_MS } from "../scripts/integration-reservation"; import { declareFix, emptyRedMain, openRed } from "../scripts/red-main"; +import { receiptBlock, type CheckReceipt } from "../scripts/check-receipt"; import { invocationChild } from "../scripts/test-invocation-child"; import { processIdentity } from "../scripts/workspace-lease.mjs"; const dirs: string[] = []; -type ScenarioResult = { code: number; out: string; err: string; dispatched: boolean; reads: string[]; state: ReturnType["state"] }; +type ScenarioResult = { code: number; out: string; err: string; dispatched: boolean; reads: string[]; state: ReturnType["state"]; + redMain: ReturnType["redMain"]; events: any[] }; type Scenario = { dir?: string; child?: ReturnType; work?: Promise; settled: boolean; beforeRead?: () => Promise }; const scenarios = new Set(); let deadline: ReturnType, overdue = false, deadlineCleanup: Promise | undefined; @@ -61,10 +63,13 @@ async function runScenario(mode: string, owner: Scenario): Promise ({ name, categories, outcome }); + const receipt: CheckReceipt = { version: 1, kind: "brain-check-pr-receipt", head, base: "origin/main", mode: "focused", startedAt: "2026-07-12T00:00:00.000Z", + finishedAt: "2026-07-12T00:05:00.000Z", checks: [check("all lint and leakage gates", ["changeset"]), check("affected fast invariants", ["verify", "unit"]), + ...(mode === "receipt-uncovered" ? [check("complete pinned visual/accessibility/pointer suite", ["browser"], "timed-out"), check("complete unit and integration suite", ["unit"], "preempted")] : []), + ...(mode === "browser-receipt-skipped" ? [check("complete pinned visual/accessibility/pointer suite", ["browser"], "skipped")] : [])] }; + const body = mode === "receipt-absent" || mode.startsWith("expedite-") ? "Odysseus builds a raft.\n" : `Odysseus builds a raft.\n\n${receiptBlock(receipt)}\n`; + const probeLog = (id: number) => (id === 401 ? { sha: base, tests: ["tests/raft.test.ts"], absent: [], exitCode: mode === "expedite-base-green" ? 0 : 1 } + : mode === "expedite-revert" ? { sha: head, tests: [], absent: ["tests/raft.test.ts"], exitCode: 0 } + : { sha: head, tests: ["tests/raft.test.ts"], absent: [], exitCode: mode === "expedite-head-red" ? 1 : 0 }); writeFileSync(gh, `#!${process.execPath} import {readFileSync,writeFileSync} from "node:fs"; import {GitReservationStore,reservationTransition} from ${JSON.stringify(library)}; const args=process.argv.slice(2), file=${JSON.stringify(apiState)}, s=JSON.parse(readFileSync(file,"utf8")); const candidate=${JSON.stringify(candidate)}, actual=${JSON.stringify(actual)}, root=${JSON.stringify(root)}, remote=${JSON.stringify(remote)}; - const refs=${JSON.stringify(refs)};s.reads??=[]; + const refs=${JSON.stringify(refs)}, body=${JSON.stringify(body)}, probes=${JSON.stringify({ 401: probeLog(401), 402: probeLog(402) })};s.reads??=[]; const repo="odysseus/brain-kit", base=candidate.base, head=candidate.head, squash=${JSON.stringify(squash)}; const categories=["verify","pack","unit","browser","layout","captures","runtime","runtime_host","endurance"]; const selected={selections:Object.fromEntries(categories.map(x=>[x,"false"])),results:Object.fromEntries(categories.map(x=>[x,"skipped"])),retained:[],unitShards:null}; if(s.mode.startsWith("browser-")){selected.selections.browser="true";selected.results.browser="success";} + if(s.mode==="receipt-uncovered"){selected.selections.unit="false";} if(s.mode==="missing-selection")delete selected.selections.endurance; if(s.mode==="unexpected-skip"){selected.selections.endurance="true";selected.results.endurance="success";} const job=(id,name,conclusion="success")=>({id,name,status:"completed",conclusion,run_id:91,head_sha:head}); @@ -126,7 +142,10 @@ fi`); chmodSync(shim, 0o755); } if(args.includes("--include")){console.log("HTTP/2.0 200 OK\\nDate: "+new Date(s.now).toUTCString()+"\\n\\n{}");writeFileSync(file,JSON.stringify(s));process.exit(0);} if(path==="user")value={id:101,login:"odysseus"}; - else if(path.endsWith("/pulls/7"))value={number:7,state:s.merged?"closed":"open",draft:s.draft,merged:s.merged,merge_commit_sha:squash,head:{sha:s.mode==="changed-head"?"e".repeat(40):head,repo:{full_name:repo}},base:{ref:"main",sha:base,repo:{full_name:repo}},milestone:{title:"0.44.0"}}; + else if(path.includes("actions/workflows/red-main-probe.yml/runs"))value={workflow_runs:[[301,base,probes[401]],[302,head,probes[402]]].map(([id,sha,p])=>({id,run_attempt:1,status:"completed",conclusion:p.exitCode?"failure":"success",display_title:"red-main probe fix 11 "+sha}))}; + else if(["/runs/301/attempts/1/jobs","/runs/302/attempts/1/jobs"].some(x=>path.includes(x)))value={jobs:[{id:path.includes("/301/")?401:402,name:"probe",status:"completed"}]}; + else if(path.endsWith("actions/jobs/401/logs")||path.endsWith("actions/jobs/402/logs"))value="2026-07-12T00:00:00Z BRAIN_RED_MAIN_PROBE "+JSON.stringify({purpose:"fix",...probes[path.includes("/401/")?401:402]}); + else if(path.endsWith("/pulls/7"))value={number:7,state:s.merged?"closed":"open",draft:s.draft,merged:s.merged,merge_commit_sha:squash,head:{sha:s.mode==="changed-head"?"e".repeat(40):head,repo:{full_name:repo}},base:{ref:"main",sha:base,repo:{full_name:repo}},milestone:{title:"0.44.0"},body}; else if(path.endsWith("git/ref/heads/main"))value={object:{sha:s.mode==="changed-base"?"d".repeat(40):base}}; else if(path.includes("actions/workflows/ci.yml/runs?event=push"))value={workflow_runs:[]}; else if(path.includes("actions/workflows/ci.yml/runs"))value={workflow_runs:[run(s.mode.startsWith("confirm-")&&!s.requested?90:91,"ci")]}; @@ -149,7 +168,8 @@ fi`); chmodSync(shim, 0o755); globalThis.setInterval=(callback,ms,...args)=>ms===60000?(callbacks.set(++id,callback),id):originalSet(callback,ms,...args); globalThis.clearInterval=timer=>callbacks.has(timer)?callbacks.delete(timer):originalClear(timer); Bun.sleep=async ms=>{if(ms!==60000)return originalSleep(ms);const file=${JSON.stringify(apiState)},state=JSON.parse(readFileSync(file,"utf8"));state.now+=ms;writeFileSync(file,JSON.stringify(state));for(const callback of callbacks.values())await callback();};`); - const child = invocationChild([process.execPath, ...(mode.startsWith("confirm-") ? ["--preload", preload] : []), resolve(import.meta.dir, "../scripts/integrate.ts"), mode.startsWith("confirm-") ? "confirm" : "merge", "7", ...(mode.startsWith("confirm-") ? [] : ["--lease", mode === "wrong-id" ? "2".repeat(32) : id]), "--issues", delivered.join(",")], { + const child = invocationChild([process.execPath, ...(mode.startsWith("confirm-") ? ["--preload", preload] : []), resolve(import.meta.dir, "../scripts/integrate.ts"), mode.startsWith("confirm-") ? "confirm" : "merge", "7", ...(mode.startsWith("confirm-") ? [] : ["--lease", mode === "wrong-id" ? "2".repeat(32) : id]), "--issues", delivered.join(","), + ...(mode.startsWith("expedite-") ? ["--fixes-main-run", "11"] : [])], { cwd: root, env: { ...process.env, PATH: `${bin}:${process.env.PATH ?? ""}` }, }); owner.child = child; @@ -160,7 +180,9 @@ fi`); chmodSync(shim, 0o755); await child.finish(); if (overdue) throw new Error("Integration fixture work deadline exceeded; owned cleanup joined inside the 30-second test cap"); await owner.beforeRead?.(); - return { code, out, err, dispatched: existsSync(sentinel), reads: JSON.parse(readFileSync(apiState, "utf8")).reads ?? [], state: store.read().state }; + const eventDir = join(root, "tmp/ci-timings"); + const events = existsSync(eventDir) ? readdirSync(eventDir).filter(name => name.startsWith("event-")).map(name => JSON.parse(readFileSync(join(eventDir, name), "utf8"))) : []; + return { code, out, err, dispatched: existsSync(sentinel), reads: JSON.parse(readFileSync(apiState, "utf8")).reads ?? [], state: store.read().state, redMain: store.read().redMain, events }; } finally { await child.stop("SIGTERM"); await Promise.allSettled([output]); @@ -282,3 +304,42 @@ test("while main is red a candidate whose merge ref does not contain the bad com expect(unrelated.code, `MERGE_REF_WITHOUT_BAD_COMMIT_MERGES: ${unrelated.err}`).toBe(2); expect(unrelated.dispatched).toBe(true); }); + +test("the merge path refuses uncovered local skips and a missing receipt, and accepts covered ones (#2940)", async () => { + const uncovered = await scenario("receipt-uncovered"); + expect(uncovered.dispatched, "NO_MERGE_WITH_UNCOVERED_LOCAL_SKIPS").toBe(false); + expect(uncovered.code, uncovered.err).toBe(1); + expect(uncovered.err).toContain("complete pinned visual/accessibility/pointer suite (timed-out; needs browser)"); + expect(uncovered.err).toContain("complete unit and integration suite (preempted; needs unit)"); + expect(uncovered.state.active, "REFUSAL_RELEASES_THE_LEASE").toBeNull(); + const missing = await scenario("receipt-absent"); + expect(missing.dispatched).toBe(false); + expect(missing.err).toContain("No check:pr receipt in the PR body"); + const covered = await scenario("browser-receipt-skipped"); + expect(covered.code, `SKIP_COVERED_BY_EXACT_HEAD_HOSTED_BROWSER: ${covered.err}`).toBe(2); + expect(covered.dispatched).toBe(true); +}); + +test("expedited fix merges only with red-on-base and green-on-head evidence, and records it (#2940)", async () => { + for (const [mode, message] of [ + ["expedite-base-green", "not shown red on the bad base"], + ["expedite-head-red", "not shown green on the fix head"], + ["expedite-category", "Category-level red failures (browser)"], + ] as const) { + const refused = await scenario(mode); + expect(refused.dispatched, `NO_EXPEDITED_MERGE:${mode}`).toBe(false); + expect(refused.code, refused.err).toBe(1); + expect(refused.err).toContain(message); + } + for (const mode of ["expedite-valid", "expedite-revert"]) { + const fix = await scenario(mode); + expect(fix.code, `EXPEDITED_FIX_MERGES:${mode}: ${fix.err}`).toBe(2); + expect(fix.dispatched).toBe(true); + expect(fix.out).toContain('"expedited":{"fixesMainRun":11,"baseProbe":301,"headProbe":302'); + expect(fix.state.active).toBeNull(); expect(fix.state.last?.action).toBe("release"); + // The record stays open: only the next green main run that includes the red set clears it. + expect(fix.redMain.open?.fixes).toEqual([7]); + expect(fix.redMain.open?.expedited).toMatchObject([{ pr: 7, baseProbe: 301, headProbe: 302, feedbackRun: 91, actor: 101 }]); + expect(fix.events).toMatchObject([{ kind: "expedited-fix", pr: 7, run: 11, repository: "odysseus/brain-kit", evidence: "https://github.com/odysseus/brain-kit/actions/runs/302" }]); + } +}); diff --git a/tests/local-checks.test.ts b/tests/local-checks.test.ts index 321dda97d1..7d7f8c4d18 100644 --- a/tests/local-checks.test.ts +++ b/tests/local-checks.test.ts @@ -114,7 +114,7 @@ test("focused and full local CLI refuse setup before downstream proof while plan // helpers. Planning must inspect this tiny Git root, never the worker checkout. cpSync(join(owner, "scripts/check-pr.ts"), entry); expect(readFileSync(entry)).toEqual(readFileSync(join(owner, "scripts/check-pr.ts"))); - for (const helper of ["ci-plan", "ci-runner", "check-packages"]) { + for (const helper of ["ci-plan", "ci-runner", "check-packages", "check-receipt"]) { writeFileSync(join(dir, `scripts/${helper}.ts`), `export * from ${JSON.stringify(join(owner, `scripts/${helper}.ts`))};\n`); } writeFileSync(join(dir, "package.json"), JSON.stringify({ private: true, workspaces: ["packages/*"] })); diff --git a/tests/red-main-expedite.test.ts b/tests/red-main-expedite.test.ts new file mode 100644 index 0000000000..af31e0f175 --- /dev/null +++ b/tests/red-main-expedite.test.ts @@ -0,0 +1,51 @@ +import { expect, test } from "bun:test"; +import { emptyRedMain, openRed, type RedFailure } from "../scripts/red-main"; +import { expeditedProblems, expeditedTests, fixProbeTitle, probeReceipt, PROBE_RECEIPT, type ProbeEvidence } from "../scripts/red-main-expedite"; + +const NOW = Date.parse("2026-07-12T00:00:00Z"), BASE = "b".repeat(40), HEAD = "c".repeat(40); +const failure = (test: string | null, category: RedFailure["category"] = "unit"): RedFailure => + ({ test, category, verdict: "real", reasons: ["in-affected-closure"], run: 11, sha: BASE }); +const TESTS = ["tests/raft.test.ts"]; +const probe = (run: number, sha: string, exitCode: number, tests = TESTS, absent: string[] = []): ProbeEvidence => + ({ run, status: "completed", conclusion: exitCode ? "failure" : "success", receipt: { purpose: "fix", sha, tests, absent, exitCode } }); +const feedback = { run: 91, cadence: "confirmation", changeset: "success", verify: "success" }; +const valid = { tests: TESTS, base: BASE, head: HEAD, deleted: [], baseProbe: probe(301, BASE, 1), headProbe: probe(302, HEAD, 0), feedback }; + +test("expedited proof requires the failing tests red on the bad base and green on the fix head", () => { + expect(expeditedProblems(valid)).toEqual([]); + expect(expeditedProblems({ ...valid, baseProbe: probe(301, BASE, 0) }).join(), "BASE_NOT_SHOWN_RED_REFUSED").toContain("not shown red on the bad base"); + expect(expeditedProblems({ ...valid, headProbe: probe(302, HEAD, 1) }).join(), "HEAD_NOT_SHOWN_GREEN_REFUSED").toContain("not shown green on the fix head"); + expect(expeditedProblems({ ...valid, baseProbe: probe(301, HEAD, 1) }).join()).toContain("no receipt for the bad base"); + expect(expeditedProblems({ ...valid, baseProbe: probe(301, BASE, 1, ["tests/other.test.ts"]) }).join()).toContain("did not run every failing test file"); + expect(expeditedProblems({ ...valid, baseProbe: null, headProbe: { run: 302, status: "in_progress", conclusion: null, receipt: null } })).toHaveLength(2); +}); + +test("a targeted revert may delete the failing test file it reverts; any other absence refuses", () => { + const revert = { ...valid, headProbe: probe(302, HEAD, 0, [], TESTS) }; + expect(expeditedProblems({ ...revert, deleted: TESTS }), "REVERT_ACCEPTED_AS_DECLARED_FIX").toEqual([]); + expect(expeditedProblems(revert).join()).toContain("absent at the fix head without the fix deleting them"); +}); + +test("affected fast invariants must pass on a non-draft exact-head run", () => { + expect(expeditedProblems({ ...valid, feedback: { ...feedback, verify: "skipped" } })).toEqual([]); + expect(expeditedProblems({ ...valid, feedback: { ...feedback, verify: "failure" } }).join()).toContain("fast invariants did not pass"); + expect(expeditedProblems({ ...valid, feedback: { ...feedback, cadence: "draft" } }).join()).toContain("selects no fast invariants"); + expect(expeditedProblems({ ...valid, feedback: null }).join()).toContain("no hosted CI run at the fix head"); +}); + +test("only the open record's run, with test-file failures, can be expedited", () => { + const red = openRed(emptyRedMain(), { firstBad: BASE, run: 11, failures: [failure("tests/raft.test.ts"), failure("tests/raft.test.ts")] }, NOW); + expect(expeditedTests(red, 11)).toEqual(TESTS); + expect(() => expeditedTests(red, 12)).toThrow("does not match the open red-main record's run 11"); + expect(() => expeditedTests(emptyRedMain(), 11)).toThrow("Main is not red"); + const category = openRed(emptyRedMain(), { firstBad: BASE, run: 11, failures: [failure("tests/raft.test.ts"), failure(null, "browser")] }, NOW); + expect(() => expeditedTests(category, 11), "CATEGORY_LEVEL_FAILURE_REFUSED").toThrow("Category-level red failures (browser)"); +}); + +test("probe receipts are single, structured lines", () => { + const line = `${PROBE_RECEIPT} ${JSON.stringify({ purpose: "fix", sha: BASE, tests: TESTS, absent: [], exitCode: 1 })}`; + expect(probeReceipt(`2026-07-12T00:00:00Z ${line}\n`)).toEqual({ purpose: "fix", sha: BASE, tests: TESTS, absent: [], exitCode: 1 }); + expect(probeReceipt(`${line}\n${line}`)).toBeNull(); + expect(probeReceipt("no receipt")).toBeNull(); + expect(fixProbeTitle(11, BASE)).toBe(`red-main probe fix 11 ${BASE}`); +}); diff --git a/tests/red-main.test.ts b/tests/red-main.test.ts index fa8daf4073..f1a8db103f 100644 --- a/tests/red-main.test.ts +++ b/tests/red-main.test.ts @@ -4,7 +4,7 @@ import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import type { CheckPlan } from "../scripts/ci-plan"; import { GitReservationStore } from "../scripts/integration-reservation"; -import { addSuspect, classifyFailure, clearRed, declareFix, emptyRedMain, FLAKE_WINDOW_MS, gateDecision, includeRedSet, junitFailures, +import { addSuspect, classifyFailure, clearRed, declareFix, emptyRedMain, FLAKE_WINDOW_MS, gateDecision, includeRedSet, junitFailures, recordExpedited, openRed, parseRedMain, type RedFailure, type RedMainRecord } from "../scripts/red-main"; import { coordinate, includedRedSet, incidentMarker, type CoordinatorIO, type Job, type Snapshot, type WorkflowRun } from "../scripts/red-main-coordinator"; @@ -311,3 +311,26 @@ describe("coordinator", () => { expect(existsSync(ROOT)).toBe(true); }); }); + +describe("expedited fixes (#2940)", () => { + test("an expedited fix is recorded on the open record only for a declared fix, and parses back", () => { + const red = openRed(emptyRedMain(), { firstBad: B, run: 11, failures: [failure("tests/raft.test.ts")] }, NOW); + const fix = { pr: 8, head: C, base: B, squash: A, baseProbe: 301, headProbe: 302, feedbackRun: 91, actor: 101, at: NOW + 2 }; + expect(() => recordExpedited(red, fix, NOW + 2)).toThrow("declared fix"); + const recorded = recordExpedited(declareFix(red, 8, NOW + 1), fix, NOW + 2); + expect(recorded.open?.expedited).toEqual([fix]); + expect(recorded.last).toEqual({ action: "expedite", at: NOW + 2, run: 11 }); + expect(parseRedMain(JSON.stringify(recorded))).toEqual(recorded); + expect(recordExpedited(recorded, fix, NOW + 3)).toBe(recorded); + expect(() => parseRedMain(JSON.stringify({ ...recorded, open: { ...recorded.open, expedited: [{ ...fix, actor: "odysseus" }] } }))).toThrow("Invalid red-main incident"); + }); + + test("the coordinator ignores expedited fix probes", async () => { + const gh = fakeGitHub({ jobs: [] }); + gh.set(openRed(emptyRedMain(), { firstBad: B, run: 100, failures: [failure("tests/raft.test.ts")] }, NOW)); + const before = gh.record(); + await coordinate(gh.io, { ...mainRun(B, "failure", 200), name: "red-main-probe", event: "workflow_dispatch", display_title: `red-main probe fix 100 ${B}` }); + expect(gh.record(), "FIX_PROBE_NEVER_CHANGES_THE_RECORD").toBe(before); + expect(gh.issues).toHaveLength(0); expect(gh.comments).toHaveLength(0); expect(gh.dispatched).toHaveLength(0); + }); +}); From f8257826d0369dbdd49f02f84379a1505c040c10 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 09:33:43 +0000 Subject: [PATCH 2/9] feat(ci): admit heavy local test commands through a host-wide ledger Separate worktrees on one host now share a limited number of slots for heavy local commands (the integrated suite, runtime-host, native and long test files, check:pr --full/--all and browser proof). A command over the limit waits, printing holders and queue position, and records the wait as a wait-started/wait-finished pair through scripts/ci-timings.ts record. The ledger records holder process identity, worker, orchestrator and priority class; dead holders are reclaimed after their orphaned group is killed. A declared red-main fix is admitted ahead of ordinary waiters. preempt cancels a holder in the caller's own orchestrator subtree, only to admit a waiting red-main fix, lets cleanup run within a grace period and records the run as preempted (#2938). Refs #2943 Co-Authored-By: Claude Opus 5.5 --- scripts/check-pr.ts | 6 + scripts/host-admission.d.mts | 46 +++ scripts/host-admission.mjs | 411 +++++++++++++++++++++++ scripts/test-network-preload.ts | 11 +- scripts/test.ts | 38 ++- scripts/visual.mjs | 11 + tests/experiment-tier.test.ts | 2 +- tests/helpers/test-invocation-fixture.ts | 2 +- tests/host-admission.test.ts | 208 ++++++++++++ tests/local-checks.test.ts | 3 +- tests/test-script.test.ts | 26 +- tests/test-shards.test.ts | 2 +- tests/visual-runner.test.ts | 2 + tests/workspace-lease.test.ts | 2 +- 14 files changed, 762 insertions(+), 8 deletions(-) create mode 100644 scripts/host-admission.d.mts create mode 100644 scripts/host-admission.mjs create mode 100644 tests/host-admission.test.ts diff --git a/scripts/check-pr.ts b/scripts/check-pr.ts index 7f990512af..abebae5933 100644 --- a/scripts/check-pr.ts +++ b/scripts/check-pr.ts @@ -5,6 +5,7 @@ import { changedFiles, planChecks, workspaces, type CheckPlan } from "./ci-plan" import { runCommands, type Command, type Settled } from "./ci-runner"; import { checkPackages } from "./check-packages"; import { checkCategories, PREEMPTED_EXIT, RECEIPT_KIND, receiptBlock, UNPROVEN, type CheckReceipt, type Outcome, type ReceiptCheck } from "./check-receipt"; +import { ensureHostAdmission } from "./host-admission.mjs"; export function localChecks(plan: CheckPlan, full = false, mergeBase?: string, importGraph = false, importGraphWorkers?: number): Command[] { const bun = process.execPath; @@ -222,6 +223,11 @@ if (import.meta.main) { else throw new Error("usage: bun run check:pr [--base ] [--full|--all] [--import-graph] [--plan] [--import-graph-workers=N] [--check-timeout=] [--skip ]... [--receipt ]"); } const root = resolve(import.meta.dir, ".."); + if (full && !print) { + // Full local suites are for debugging only and run through host admission (#2939, #2943). + const admitted = await ensureHostAdmission(all ? "check:pr --all" : "check:pr --full"); + if (admitted !== undefined) process.exit(admitted); + } const changed = all ? ["package.json"] : changedFiles(root, base, "HEAD", true, true); const plan = planChecks(changed, workspaces(root), root); let mergeBase: string | undefined; diff --git a/scripts/host-admission.d.mts b/scripts/host-admission.d.mts new file mode 100644 index 0000000000..53960b42b0 --- /dev/null +++ b/scripts/host-admission.d.mts @@ -0,0 +1,46 @@ +export const MARKER: "BRAIN_HOST_ADMISSION"; +export const PREEMPTED_EXIT: 75; +export const RED_MAIN_FIX: "red-main-fix"; +export const DEFAULT_GRACE_MS: number; +export function ledgerDir(env?: Record): string; +export function admissionLimit(env?: Record, cpus?: number): number; +export interface AdmissionEntry { + id: string; + state: "queued" | "holding"; + pid: number; + start: string; + worker: string; + orchestrator: string | null; + priority: "red-main-fix" | "ordinary"; + fixPR: number | null; + label: string; + seq: number; + queuedAt: string; + admittedAt?: string; + child?: { pid: number; start: string }; + preempt?: { reason: string; by: string; at: string; graceMs: number }; +} +export interface AdmissionState { version: 1; seq: number; entries: AdmissionEntry[] } +export function admissionOrder(entries: readonly AdmissionEntry[]): AdmissionEntry[]; +export function readHistory(dir: string): Record[]; +export function withLedger(dir: string, transaction: (state: AdmissionState) => T): Promise; +export interface AdmissionOptions { + env?: Record; + dir?: string; + limit?: number; + worker?: string; + orchestrator?: string; + redMainFix?: string | number; + label?: string; + pollMs?: number; + root?: string; + timingsOut?: string; +} +export function runAdmitted(command: readonly string[], options?: AdmissionOptions): Promise; +export function preempt(slot: string, options?: { env?: Record; dir?: string; orchestrator?: string; reason?: string; graceMs?: number }): + Promise<{ slot: string; reason: string; preempted: true; forced: boolean }>; +export class RefusedError extends Error {} +export function status(options?: { env?: Record; dir?: string }): + Promise<{ ledger: string; limit: number; holders: AdmissionEntry[]; queue: AdmissionEntry[] }>; +export function inheritedAdmission(env?: Record): boolean; +export function ensureHostAdmission(label: string): Promise; diff --git a/scripts/host-admission.mjs b/scripts/host-admission.mjs new file mode 100644 index 0000000000..2c5d113280 --- /dev/null +++ b/scripts/host-admission.mjs @@ -0,0 +1,411 @@ +/** + * Host-wide admission for heavy local test commands (#2943). + * + * Separate worktrees on one machine share nothing through the workspace lease + * (`scripts/workspace-lease.mjs`), so five checkouts could start five native + * suites at once and time out together. This ledger admits at most a limited + * number of heavy commands per host; the rest wait in a priority queue instead + * of starting. Its state is durable and only ever changed under a short ledger + * lock by these commands, so a crashed orchestrator or worker leaves nothing an + * ordinary later caller cannot reconcile: dead holders and waiters are pruned + * by process identity on every pass. + * + * node scripts/host-admission.mjs run [--red-main-fix ] [--label ] -- + * node scripts/host-admission.mjs preempt --reason red-main-fix [--grace-ms ] + * node scripts/host-admission.mjs status + * + * Preemption follows the #2938 ruling: only within the caller's own + * orchestrator subtree, and only to admit a waiting red-main fix. A preempted + * run is recorded as `preempted`, which is neither a pass nor a failure. + */ +import { appendFileSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { randomBytes } from "node:crypto"; +import { availableParallelism, constants, tmpdir } from "node:os"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { liveAncestor, processIdentity } from "./workspace-lease.mjs"; + +/** Inherited by an admitted command, so its nested heavy commands do not queue behind themselves. */ +export const MARKER = "BRAIN_HOST_ADMISSION"; +/** Distinct from a pass (0) and an ordinary failure: EX_TEMPFAIL. */ +export const PREEMPTED_EXIT = 75; +export const RED_MAIN_FIX = "red-main-fix"; +export const DEFAULT_GRACE_MS = 10_000; +const OPAQUE = /^[A-Za-z0-9_-]{1,100}$/; +const script = fileURLToPath(import.meta.url); +const repoRoot = resolve(dirname(script), ".."); +const sleep = ms => new Promise(done => setTimeout(done, ms)); +const now = () => new Date().toISOString(); + +/** One ledger per host user; worktrees and clones on the machine share it. */ +export function ledgerDir(env = process.env) { + const user = typeof process.getuid === "function" ? process.getuid() : "user"; + return resolve(env.BRAIN_HOST_ADMISSION_DIR || join(tmpdir(), `brain-host-admission-${user}`)); +} + +/** Heavy suites each use many cores; by default admit one per four CPUs. */ +export function admissionLimit(env = process.env, cpus = availableParallelism()) { + const raw = env.BRAIN_HOST_ADMISSION_LIMIT; + if (raw === undefined || raw === "") return Math.max(1, Math.floor(cpus / 4)); + if (!/^[1-9]\d*$/.test(raw.trim())) throw new Error("BRAIN_HOST_ADMISSION_LIMIT must be a positive integer"); + return Number(raw.trim()); +} + +function opaque(value, name) { + if (value === undefined || value === "") return null; + if (!OPAQUE.test(value)) throw new Error(`${name} must be an opaque ID of letters, digits, '-' or '_'`); + return value; +} + +/** Linux compares process lifetimes, so a reused PID never keeps a slot. */ +function alive(pid, start) { + if (process.platform === "linux") return processIdentity(pid)?.start === start; + try { process.kill(pid, 0); return true; } catch (error) { return error.code === "EPERM"; } +} + +function groupAlive(pgid) { + try { process.kill(-pgid, 0); return true; } catch (error) { return error.code === "EPERM"; } +} + +function signalGroup(pgid, signal) { + try { process.kill(-pgid, signal); } catch (error) { if (error.code !== "ESRCH") throw error; } +} + +const identity = () => processIdentity(process.pid)?.start ?? ""; + +function lockOwnerStale(lock) { + let owner; + try { owner = readFileSync(join(lock, "owner"), "utf8"); } + catch { + // The owner writes its identity right after mkdir; give that gap time. + try { return Date.now() - statSync(lock).mtimeMs > 2_000; } catch { return false; } + } + const [pid, start] = owner.split(" "); + return !alive(Number(pid), start ?? ""); +} + +/** Only one caller removes a dead owner's lock; the guard serializes stealers. */ +function stealStaleLock(lock) { + const guard = `${lock}.steal`; + try { mkdirSync(guard); } + catch (error) { + if (error.code !== "EEXIST") throw error; + try { if (Date.now() - statSync(guard).mtimeMs > 5_000) rmSync(guard, { recursive: true, force: true }); } catch { /* raced */ } + return; + } + try { if (lockOwnerStale(lock)) rmSync(lock, { recursive: true, force: true }); } + finally { rmSync(guard, { recursive: true, force: true }); } +} + +function readState(dir) { + try { + const state = JSON.parse(readFileSync(join(dir, "state.json"), "utf8")); + if (state?.version === 1 && Number.isSafeInteger(state.seq) && Array.isArray(state.entries)) return state; + } catch (error) { if (error.code !== "ENOENT" && !(error instanceof SyntaxError)) throw error; } + return { version: 1, seq: 0, entries: [] }; +} + +function writeState(dir, state) { + const path = join(dir, "state.json"), staged = `${path}.${process.pid}.${randomBytes(4).toString("hex")}`; + writeFileSync(staged, JSON.stringify(state, null, 2) + "\n", { mode: 0o600 }); + renameSync(staged, path); +} + +export function history(dir, event) { + appendFileSync(join(dir, "history.jsonl"), JSON.stringify({ at: now(), ...event }) + "\n", { mode: 0o600 }); +} + +export function readHistory(dir) { + try { return readFileSync(join(dir, "history.jsonl"), "utf8").split("\n").filter(Boolean).map(line => JSON.parse(line)); } + catch (error) { if (error.code === "ENOENT") return []; throw error; } +} + +/** Run a synchronous ledger transaction under the host-wide lock. */ +export async function withLedger(dir, transaction) { + mkdirSync(dir, { recursive: true, mode: 0o700 }); + const lock = join(dir, "ledger.lock"), me = `${process.pid} ${identity()}`; + for (let attempt = 0; ; attempt++) { + try { mkdirSync(lock); writeFileSync(join(lock, "owner"), me); break; } + catch (error) { if (error.code !== "EEXIST") throw error; } + if (lockOwnerStale(lock)) stealStaleLock(lock); + if (attempt > 6_000) throw new Error("The host admission ledger lock stayed unavailable"); + await sleep(5 + Math.floor(Math.random() * 10)); + } + try { + const state = readState(dir); + const result = transaction(state); + writeState(dir, state); + return result; + } finally { rmSync(lock, { recursive: true, force: true }); } +} + +/** + * Forget dead waiters and reclaim dead holders. A holder whose wrapper died + * while its detached command group still runs keeps the slot until that group + * has been killed and is gone, so the slot is never handed out twice. + */ +export function prune(state, dir) { + state.entries = state.entries.filter(entry => { + if (alive(entry.pid, entry.start)) return true; + if (entry.state === "holding" && entry.child && groupAlive(entry.child.pid)) { + signalGroup(entry.child.pid, "SIGKILL"); + if (groupAlive(entry.child.pid)) return true; + } + history(dir, { kind: entry.state === "holding" ? (entry.preempt ? "preempted" : "reclaimed") : "abandoned", + slot: entry.id, worker: entry.worker, orchestrator: entry.orchestrator, priority: entry.priority }); + return false; + }); +} + +const rank = entry => entry.priority === RED_MAIN_FIX ? 0 : 1; + +/** Red-main fixes go ahead of every ordinary waiter; otherwise arrival order. */ +export function admissionOrder(entries) { + return entries.filter(entry => entry.state === "queued").sort((a, b) => rank(a) - rank(b) || a.seq - b.seq); +} + +function tryAdmit(state, dir, id, limit) { + prune(state, dir); + const entry = state.entries.find(candidate => candidate.id === id); + if (!entry) return { lost: true }; + const holders = state.entries.filter(candidate => candidate.state === "holding"); + const order = admissionOrder(state.entries), position = order.indexOf(entry); + if (position < limit - holders.length) { + entry.state = "holding"; entry.admittedAt = now(); + history(dir, { kind: "admitted", slot: id, worker: entry.worker, orchestrator: entry.orchestrator, priority: entry.priority }); + return { admitted: true }; + } + return { admitted: false, position: position + 1, queued: order.length, limit, + holders: holders.map(holder => `${holder.id} (${holder.label}, worker ${holder.worker}, ${holder.priority})`) }; +} + +/** Record a wait boundary through the shared coordination recorder. */ +async function recordWait(kind, { worker, task, timingsOut, root, ledger }) { + const { spawn } = await import("node:child_process"); + const dir = join(ledger, "events"); + try { + mkdirSync(dir, { recursive: true }); + const file = join(dir, `${task}-${kind}.json`); + writeFileSync(file, JSON.stringify({ kind, worker, task, reason: "other" })); + const bun = process.versions.bun ? process.execPath : "bun"; + const code = await new Promise(done => { + const child = spawn(bun, [join(root, "scripts/ci-timings.ts"), "record", "--event", file, "--out", timingsOut], + { stdio: ["ignore", "ignore", "inherit"] }); + child.once("error", () => done(1)); + child.once("exit", status => done(status ?? 1)); + }); + rmSync(file, { force: true }); + if (code !== 0) console.error(`Host admission could not record ${kind}; the wait itself is unaffected.`); + } catch (error) { console.error(`Host admission could not record ${kind}: ${error.message}`); } +} + +function exitCode(code, signal) { + return signal ? 128 + (constants.signals[signal] ?? 0) : code ?? 1; +} + +/** Wait for a slot, run the command in its own process group, then release. */ +export async function runAdmitted(command, options = {}) { + if (!command.length) throw new Error("Host admission needs a command after --"); + const env = options.env ?? process.env; + const dir = options.dir ?? ledgerDir(env), limit = options.limit ?? admissionLimit(env); + const worker = opaque(options.worker ?? env.BRAIN_WORKER_ID, "Worker ID") ?? `host-${process.pid}`; + const orchestrator = opaque(options.orchestrator ?? env.BRAIN_ORCHESTRATOR_ID, "Orchestrator ID"); + const fix = options.redMainFix ?? env.BRAIN_RED_MAIN_FIX; + if (fix !== undefined && fix !== "" && !/^[1-9]\d*$/.test(String(fix))) throw new Error("A red-main fix is declared by its PR number"); + const fixPR = fix ? Number(fix) : null, priority = fixPR ? RED_MAIN_FIX : "ordinary"; + const label = String(options.label ?? command.join(" ")).slice(0, 120); + const pollMs = options.pollMs ?? 500, root = options.root ?? repoRoot; + const timingsOut = resolve(options.timingsOut ?? join(root, "tmp", "ci-timings")); + const start = identity(); + let id, child, cancelled; + await withLedger(dir, state => { + state.seq += 1; + id = `h${state.seq}-${randomBytes(4).toString("hex")}`; + state.entries.push({ id, state: "queued", pid: process.pid, start, worker, orchestrator, priority, fixPR, label, seq: state.seq, queuedAt: now() }); + history(dir, { kind: "queued", slot: id, worker, orchestrator, priority, fixPR }); + }); + const release = async kind => withLedger(dir, state => { + const entry = state.entries.find(candidate => candidate.id === id); + state.entries = state.entries.filter(candidate => candidate !== entry); + const preempted = Boolean(entry?.preempt); + history(dir, { kind: preempted ? "preempted" : kind, slot: id, worker, orchestrator, priority, + ...(preempted ? { reason: entry.preempt.reason, by: entry.preempt.by } : {}) }); + return preempted; + }); + const signals = ["SIGINT", "SIGTERM", "SIGHUP"]; + const listeners = signals.map(signal => () => { + if (child?.pid) signalGroup(child.pid, signal); + else cancelled = signal; + }); + signals.forEach((signal, index) => process.on(signal, listeners[index])); + const task = `admission-${id}`; + try { + let waited = false, last = ""; + for (;;) { + if (cancelled) { await release("cancelled"); return exitCode(null, cancelled); } + const result = await withLedger(dir, state => { + const attempt = tryAdmit(state, dir, id, limit); + if (attempt.lost) state.entries.push({ id, state: "queued", pid: process.pid, start, worker, orchestrator, priority, fixPR, label, seq: ++state.seq, queuedAt: now() }); + return attempt; + }); + if (result.admitted) break; + if (result.lost) continue; + if (!waited) { waited = true; await recordWait("wait-started", { worker, task, timingsOut, root, ledger: dir }); } + const line = `Waiting for a host admission slot (${result.limit} on this host): position ${result.position} of ${result.queued}; holders: ${result.holders.join(", ") || "none"}.`; + if (line !== last) { console.error(line); last = line; } + await sleep(pollMs); + } + if (waited) await recordWait("wait-finished", { worker, task, timingsOut, root, ledger: dir }); + if (cancelled) { await release("cancelled"); return exitCode(null, cancelled); } + const { spawn } = await import("node:child_process"); + child = spawn(command[0], command.slice(1), { stdio: "inherit", detached: process.platform !== "win32", + env: { ...env, [MARKER]: JSON.stringify({ slot: id, pid: process.pid, start, dir }) } }); + const exited = new Promise(done => { + child.once("error", () => done(127)); + child.once("exit", (code, signal) => done(exitCode(code, signal))); + }); + if (child.pid) { + const pending = await withLedger(dir, state => { + const entry = state.entries.find(candidate => candidate.id === id); + if (entry) entry.child = { pid: child.pid, start: processIdentity(child.pid)?.start ?? "" }; + return entry?.preempt; + }); + // A preemption requested before the group existed is delivered now. + if (pending) signalGroup(child.pid, "SIGTERM"); + } + const code = await exited; + if (child.pid) { + const preempt = await withLedger(dir, state => state.entries.find(candidate => candidate.id === id)?.preempt); + if (preempt) { + // Let the group's cleanup finish within the preemption's grace period. + const deadline = Date.parse(preempt.at) + preempt.graceMs; + while (groupAlive(child.pid) && Date.now() < deadline) await sleep(25); + } + signalGroup(child.pid, "SIGKILL"); + while (groupAlive(child.pid)) await sleep(10); + } + if (await release("released")) { + console.error(`Host admission slot ${id} was preempted to admit a red-main fix; this run neither passed nor failed.`); + return PREEMPTED_EXIT; + } + return code; + } finally { + signals.forEach((signal, index) => process.off(signal, listeners[index])); + } +} + +/** + * Cancel a holder in the caller's own orchestrator subtree so a waiting + * red-main fix can start. Its group gets SIGTERM, then SIGKILL after the grace + * period; the slot is released only after the group has gone. + */ +export async function preempt(slot, options = {}) { + const env = options.env ?? process.env, dir = options.dir ?? ledgerDir(env); + const orchestrator = opaque(options.orchestrator ?? env.BRAIN_ORCHESTRATOR_ID, "Orchestrator ID"); + const graceMs = options.graceMs ?? DEFAULT_GRACE_MS, reason = options.reason; + if (reason !== RED_MAIN_FIX) throw new RefusedError(`Preemption is only permitted to admit a red-main fix (--reason ${RED_MAIN_FIX})`); + if (!orchestrator) throw new RefusedError("Preemption requires the caller's orchestrator ID (BRAIN_ORCHESTRATOR_ID or --orchestrator)"); + if (!Number.isSafeInteger(graceMs) || graceMs < 0) throw new Error("Grace period must be a non-negative integer of milliseconds"); + const outcome = await withLedger(dir, state => { + prune(state, dir); + const entry = state.entries.find(candidate => candidate.id === slot && candidate.state === "holding"); + if (!entry) return { refused: `Slot ${slot} is not held` }; + if (entry.orchestrator !== orchestrator) return { refused: `Slot ${slot} is outside the caller's orchestrator subtree; it yields only through queue priority or the maintainer` }; + if (!state.entries.some(candidate => candidate.state === "queued" && candidate.priority === RED_MAIN_FIX)) return { refused: "No red-main fix is waiting for admission" }; + if (!entry.preempt) { + entry.preempt = { reason, by: orchestrator, at: now(), graceMs }; + history(dir, { kind: "preempt-requested", slot, orchestrator, reason, graceMs }); + } + return { child: entry.child }; + }); + if (outcome.refused) throw new RefusedError(outcome.refused); + if (outcome.child) signalGroup(outcome.child.pid, "SIGTERM"); + const deadline = Date.now() + graceMs; + let forced = false; + for (;;) { + const entry = await withLedger(dir, state => { prune(state, dir); return state.entries.find(candidate => candidate.id === slot); }); + if (!entry) return { slot, reason, preempted: true, forced }; + if (Date.now() >= deadline && entry.child && groupAlive(entry.child.pid)) { signalGroup(entry.child.pid, "SIGKILL"); forced = true; } + if (Date.now() >= deadline + 30_000) throw new Error(`Slot ${slot} was signalled but its holder has not released it`); + await sleep(25); + } +} + +export class RefusedError extends Error {} + +export async function status(options = {}) { + const dir = options.dir ?? ledgerDir(options.env); + return withLedger(dir, state => { + prune(state, dir); + return { ledger: dir, limit: admissionLimit(options.env), holders: state.entries.filter(entry => entry.state === "holding"), + queue: admissionOrder(state.entries) }; + }); +} + +/** True when an ancestor already holds a slot for this command tree. */ +export function inheritedAdmission(env = process.env) { + try { + const held = JSON.parse(env[MARKER] ?? "null"); + if (!held || !Number.isSafeInteger(held.pid) || typeof held.start !== "string") return false; + if (process.platform === "linux") return liveAncestor(held.pid, held.start); + return alive(held.pid, held.start); + } catch { return false; } +} + +/** + * Re-enter this heavy command through `run`, unless an ancestor holds a slot. + * Returns the admitted command's exit code, or undefined to continue inline. + */ +export async function ensureHostAdmission(label) { + if (inheritedAdmission()) return; + const { spawn } = await import("node:child_process"); + let child, pending; + const signals = ["SIGINT", "SIGTERM", "SIGHUP"]; + const listeners = signals.map(signal => () => { if (child) child.kill(signal); else pending = signal; }); + signals.forEach((signal, index) => process.on(signal, listeners[index])); + try { + child = spawn(process.execPath, [script, "run", "--label", label, "--", process.execPath, ...process.execArgv, ...process.argv.slice(1)], + { stdio: "inherit" }); + if (pending) child.kill(pending); + return await new Promise((done, reject) => { + child.once("error", reject); + child.once("exit", (code, signal) => done(exitCode(code, signal))); + }); + } finally { signals.forEach((signal, index) => process.off(signal, listeners[index])); } +} + +function parse(args) { + const options = {}, rest = []; + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + if (arg === "--") { options.command = args.slice(i + 1); break; } + const value = () => { if (i + 1 >= args.length) throw new Error(`${arg} needs a value`); return args[++i]; }; + if (arg === "--label") options.label = value(); + else if (arg === "--red-main-fix") options.redMainFix = value(); + else if (arg === "--worker") options.worker = value(); + else if (arg === "--orchestrator") options.orchestrator = value(); + else if (arg === "--reason") options.reason = value(); + else if (arg === "--grace-ms") options.graceMs = Number(value()); + else if (arg === "--poll-ms") options.pollMs = Number(value()); + else if (arg === "--timings-out") options.timingsOut = value(); + else if (arg.startsWith("-")) throw new Error(`Unknown option ${arg}`); + else rest.push(arg); + } + return { options, rest }; +} + +const usage = "usage: host-admission.mjs run [--red-main-fix ] [--label ] -- | preempt --reason red-main-fix [--grace-ms ] | status"; + +if (process.argv[1] && pathToFileURL(resolve(process.argv[1])).href === import.meta.url) { + try { + const [mode, ...args] = process.argv.slice(2); + const { options, rest } = parse(args); + if (mode === "run" && !rest.length) process.exit(await runAdmitted(options.command ?? [], options)); + else if (mode === "preempt" && rest.length === 1 && !options.command) console.log(JSON.stringify(await preempt(rest[0], options))); + else if (mode === "status" && !rest.length && !options.command) console.log(JSON.stringify(await status(), null, 2)); + else throw new Error(usage); + } catch (error) { + console.error(error instanceof Error ? error.message : String(error)); + process.exit(error instanceof RefusedError ? 2 : 1); + } +} diff --git a/scripts/test-network-preload.ts b/scripts/test-network-preload.ts index e797298f60..68e11727ab 100644 --- a/scripts/test-network-preload.ts +++ b/scripts/test-network-preload.ts @@ -1,12 +1,20 @@ import { afterAll, afterEach } from "bun:test"; import { cleanupCliUtilities } from "../packages/core/tests/cli-harness"; import { installNetworkGuard } from "./test-network-guard"; -import { resolve } from "node:path"; +import { join, resolve } from "node:path"; +import { rmSync } from "node:fs"; +import { tmpdir } from "node:os"; import { ensureWorkspaceLease, workspaceTestAccess } from "./workspace-lease.mjs"; const guard = installNetworkGuard(); const coordinated = await ensureWorkspaceLease(resolve(import.meta.dir, ".."), workspaceTestAccess(), "test"); if (coordinated !== undefined) process.exit(coordinated); +// Commands a test spawns queue in a ledger private to this test process, never +// behind the host's real heavy commands (#2943). A test that exercises the host +// ledger names its own directory; an admitted caller's descendants inherit its slot. +const privateAdmission = process.env.BRAIN_HOST_ADMISSION_DIR ? undefined : + join(tmpdir(), "brain-host-admission-tests", String(process.pid)); +if (privateAdmission) process.env.BRAIN_HOST_ADMISSION_DIR = privateAdmission; afterEach(() => guard.assertNoEscapes()); // A preload hook runs after all files; a hook in the cached helper would run // after its first importing file. Bun test does not run the ordinary exit hook. @@ -15,5 +23,6 @@ afterAll(() => { guard.assertNoEscapes(); } finally { cleanupCliUtilities(); + if (privateAdmission) rmSync(privateAdmission, { recursive: true, force: true }); } }); diff --git a/scripts/test.ts b/scripts/test.ts index 46e160dfe8..e0d22f756b 100644 --- a/scripts/test.ts +++ b/scripts/test.ts @@ -17,12 +17,14 @@ */ import { constants } from "node:os"; -import { join, resolve } from "node:path"; +import { isAbsolute, join, resolve } from "node:path"; import { realpathSync } from "node:fs"; import { invocationChild } from "./test-invocation-child"; import { runtimeBuildSelection } from "./runtime-test-builds"; import { acceptsSpeechDelegation, clearInvocation, prepareCopiedInvocation, prepareInvocation, takePreparedTree } from "./test-invocation"; import { ensureWorkspaceLease, workspaceTestAccess } from "./workspace-lease.mjs"; +import { ensureHostAdmission } from "./host-admission.mjs"; +import { FILE_COST_SECONDS } from "./test-shards"; /** What runs when the caller names no path. */ export const DEFAULT_ROOTS: readonly string[] = ["packages", "tests"]; @@ -125,6 +127,33 @@ export function testArgv(args: readonly string[]): string[] { return testPaths(args).length ? [...args] : [...DEFAULT_PATH_ARGS, ...args]; } +/** A measured file at or over this many seconds is a heavy local command on its own (#2943). */ +export const HEAVY_TEST_FILE_SECONDS = 30; + +/** + * Why a selection needs host admission, or undefined for a focused run: the + * integrated default suite, runtime-host and native suites, and any selected + * file whose measured cost reaches HEAVY_TEST_FILE_SECONDS. Paths match the + * way runtimeBuildSelection matches them. + */ +export function heavyTestReason(root: string, cwd: string, args: readonly string[], + costs: Readonly> = FILE_COST_SECONDS): string | undefined { + const paths = testPaths(args); + if (!paths.length) return "integrated suite"; + if (runtimeBuildSelection(root, cwd, paths).length) return "runtime-host tests"; + if (paths.some(path => /(?:^|\/)native-proof(?:\/|$)|\.native\./.test(path))) return "native tests"; + const selects = (file: string) => paths.some(path => { + const absolute = join(root, file); + if (isAbsolute(path) || path.startsWith(".")) { + const target = resolve(cwd, path); + return absolute === target || absolute.startsWith(`${target}/`); + } + return absolute.includes(path); + }); + const long = Object.entries(costs).find(([file, seconds]) => seconds >= HEAVY_TEST_FILE_SECONDS && selects(file)); + return long ? `long test file ${long[0]}` : undefined; +} + if (import.meta.main) { const coordinated = await ensureWorkspaceLease(resolve(import.meta.dir, ".."), workspaceTestAccess()); if (coordinated !== undefined) process.exit(coordinated); @@ -159,6 +188,13 @@ if (import.meta.main) { } args = forwarded; argv = testArgv(args); + const heavy = help ? undefined : heavyTestReason(resolve(import.meta.dir, ".."), process.cwd(), args); + // Inside the workspace lease: a queued command never holds a host slot + // while it waits for its own checkout's output. + if (heavy) { + const admitted = await ensureHostAdmission(`bun run test (${heavy})`); + if (admitted !== undefined) process.exit(admitted); + } if (balanced.length) { if (balanced.length !== 1 || argv.length === args.length || args.some((arg) => arg.startsWith("--shard") || arg.startsWith("--cwd"))) { diff --git a/scripts/visual.mjs b/scripts/visual.mjs index d7a60e902c..4a93fdb774 100644 --- a/scripts/visual.mjs +++ b/scripts/visual.mjs @@ -119,6 +119,17 @@ if (inside) { const uid = typeof process.getuid === "function" ? process.getuid() : 0; const gid = typeof process.getgid === "function" ? process.getgid() : 0; +// Browser proof is a heavy local command: separate worktrees share the host's +// admission slots (#2943). The container cannot see the host ledger, so the +// host side holds the slot for the whole container run. +// Loaded here, not statically: the container never imports it, so it is not +// part of the pinned native diagram source. +{ + const { ensureHostAdmission } = await import("./host-admission.mjs"); + const admitted = await ensureHostAdmission(`browser proof (${projects.join(", ")})`); + if (admitted !== undefined) process.exit(admitted); +} + // Execution bootstrap owns acquisition. Metadata lookup and the network-disabled // native producer never pull; both consumers launch this exact manifest digest. const inspectImage = () => spawnSync("docker", ["image", "inspect", IMAGE, "--format", "{{json .RepoDigests}}"], { encoding: "utf8" }); diff --git a/tests/experiment-tier.test.ts b/tests/experiment-tier.test.ts index 59a279ab57..2fad53a575 100644 --- a/tests/experiment-tier.test.ts +++ b/tests/experiment-tier.test.ts @@ -17,7 +17,7 @@ import { const ROOT = join(import.meta.dir, ".."); const SCRIPTS = ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-experiments.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", - "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs"]; + "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]; const passing = (name: string) => `import { expect, test } from "bun:test";\ntest(${JSON.stringify(name)}, () => expect(1).toBe(1));\n`; diff --git a/tests/helpers/test-invocation-fixture.ts b/tests/helpers/test-invocation-fixture.ts index ac63308c7c..d1dc673fb2 100644 --- a/tests/helpers/test-invocation-fixture.ts +++ b/tests/helpers/test-invocation-fixture.ts @@ -10,7 +10,7 @@ export function invocationFixture(parent = tmpdir()) { write("bun.lock", "{}\n"); write(".gitignore", "node_modules/\npackages/*/dist/\ntmp/\n"); write("tsconfig.json", JSON.stringify({ compilerOptions: { target: "ES2019", module: "ESNext", moduleResolution: "Bundler", types: [], skipLibCheck: true } })); - for (const file of ["build.ts", "clean.ts", "build-execution.ts", "build-receipt.ts", "build-repeat-observation.ts", "bin-modes.ts", "publishable-packages.ts", "workspace-lease.mjs", "test.ts", "test-invocation.ts", "test-invocation-child.ts", "runtime-test-builds.ts", "test-network-preload.ts", "test-network-guard.ts", "test-network-child-preload.ts", "unit-worker-entry.sh"]) { + for (const file of ["build.ts", "clean.ts", "build-execution.ts", "build-receipt.ts", "build-repeat-observation.ts", "bin-modes.ts", "publishable-packages.ts", "workspace-lease.mjs", "host-admission.mjs", "test.ts", "test-shards.ts", "test-shard-costs.json", "test-invocation.ts", "test-invocation-child.ts", "runtime-test-builds.ts", "test-network-preload.ts", "test-network-guard.ts", "test-network-child-preload.ts", "unit-worker-entry.sh"]) { write(`scripts/${file}`, readFileSync(join(source, "scripts", file), "utf8")); } for (const file of ["packages/core/tests/cli-harness.ts", "packages/ui-react/tests/fixtures/runtime-package-build.ts", "packages/ui-react/tests/fixtures/runtime-hook-phases.ts"]) write(file, readFileSync(join(source, file), "utf8")); diff --git a/tests/host-admission.test.ts b/tests/host-admission.test.ts new file mode 100644 index 0000000000..789db3af37 --- /dev/null +++ b/tests/host-admission.test.ts @@ -0,0 +1,208 @@ +// Host-wide admission for heavy local commands (#2943): separate worktrees on +// one machine share a limited number of slots instead of timing out together. +import { afterEach, describe, expect, test } from "bun:test"; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { admissionLimit, admissionOrder, PREEMPTED_EXIT, readHistory, type AdmissionEntry } from "../scripts/host-admission.mjs"; +import { heavyTestReason, HEAVY_TEST_FILE_SECONDS } from "../scripts/test"; + +const ROOT = resolve(import.meta.dir, ".."); +const SCRIPT = join(ROOT, "scripts/host-admission.mjs"); +const scratch: string[] = []; +const children: Bun.Subprocess[] = []; + +afterEach(() => { + for (const child of children.splice(0)) { try { child.kill("SIGKILL"); } catch { /* gone */ } } + // A killed wrapper leaves its detached command group for the next ledger + // pass to reclaim; a failed test must not leave that group running. + for (const dir of scratch) for (const entry of entries(join(dir, "ledger"))) { + if (entry.child) { try { process.kill(-entry.child.pid, "SIGKILL"); } catch { /* gone */ } } + } + for (const dir of scratch.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); + +function fixture() { + const dir = mkdtempSync(join(tmpdir(), "odysseus-host-admission-")); + scratch.push(dir); + const ledger = join(dir, "ledger"), timings = join(dir, "timings"); + // Two separate checkouts of Ithaca's harbour plan share one host. + for (const name of ["ithaca", "ogygia"]) mkdirSync(join(dir, name)); + return { dir, ledger, timings }; +} + +/** Never inherit the caller's slot, worker or orchestrator identity. */ +function env(ledger: string, extra: Record = {}) { + return { PATH: process.env.PATH!, HOME: process.env.HOME ?? tmpdir(), BRAIN_HOST_ADMISSION_DIR: ledger, BRAIN_HOST_ADMISSION_LIMIT: "1", ...extra }; +} + +function admit(cwd: string, ledger: string, timings: string, command: string, extra: Record = {}, flags: string[] = []) { + const child = Bun.spawn([process.execPath, SCRIPT, "run", "--poll-ms", "20", "--timings-out", timings, ...flags, "--", "sh", "-c", command], + { cwd, env: env(ledger, extra), stdout: "pipe", stderr: "pipe" }); + children.push(child); + const output = Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text()]).then(([out, err]) => out + err); + return { child, output }; +} + +function entries(ledger: string): AdmissionEntry[] { + try { return JSON.parse(readFileSync(join(ledger, "state.json"), "utf8")).entries; } catch { return []; } +} + +async function until(condition: () => boolean, what: string, ms = 10_000) { + const deadline = Date.now() + ms; + while (!condition()) { + if (Date.now() > deadline) throw new Error(`Timed out waiting for ${what}`); + await Bun.sleep(10); + } +} + +const holding = (ledger: string) => entries(ledger).filter(entry => entry.state === "holding" && entry.child); +const queued = (ledger: string) => entries(ledger).filter(entry => entry.state === "queued"); + +function alive(pid: number) { + try { process.kill(pid, 0); return true; } catch { return false; } +} + +describe("host admission ledger", () => { + test("with the limit at 1, heavy commands from two worktrees run one after the other and neither times out", async () => { + const { dir, ledger, timings } = fixture(); + const log = join(dir, "log"); + // Each command fails if another is running, and has its own deadline. + const heavy = (name: string) => `if ! mkdir ${dir}/running 2>/dev/null; then echo OVERLAP-${name} >> ${log}; exit 9; fi; ` + + `echo start-${name} >> ${log}; sleep 0.4; echo end-${name} >> ${log}; rmdir ${dir}/running`; + const first = admit(join(dir, "ithaca"), ledger, timings, heavy("ithaca")); + await until(() => holding(ledger).length === 1, "the first holder"); + const second = admit(join(dir, "ogygia"), ledger, timings, heavy("ogygia")); + const deadline = Bun.sleep(8_000).then(() => "timed out"); + expect(await Promise.race([Promise.all([first.child.exited, second.child.exited]), deadline])).toEqual([0, 0]); + expect(readFileSync(log, "utf8").trim().split("\n")).toEqual(["start-ithaca", "end-ithaca", "start-ogygia", "end-ogygia"]); + const waiting = await second.output; + expect(waiting).toContain("Waiting for a host admission slot (1 on this host): position 1 of 1; holders: h1-"); + expect(waiting).toContain("worker host-"); + + // The wait is recorded as one wait-started/wait-finished pair. + const events = readdirSync(timings).filter(name => name.startsWith("event-")) + .map(name => JSON.parse(readFileSync(join(timings, name), "utf8"))) + .sort((a, b) => Date.parse(a.at) - Date.parse(b.at)); + expect(events.map(event => event.kind)).toEqual(["wait-started", "wait-finished"]); + expect(new Set(events.map(event => `${event.worker}/${event.task}/${event.reason}`)).size).toBe(1); + expect(events[0].reason).toBe("other"); + expect(events[0].task).toMatch(/^admission-h2-/); + expect(entries(ledger)).toEqual([]); + }); + + test("with no orchestrator, the host slots still limit concurrent heavy commands", async () => { + const { dir, ledger, timings } = fixture(); + const marks = join(dir, "marks"); + mkdirSync(marks); + const runs = ["a", "b", "c"].map(name => admit(join(dir, "ithaca"), ledger, timings, + `touch ${marks}/${name}; n=$(ls ${marks} | wc -l); echo $n > ${dir}/peak-${name}; sleep 0.3; rm ${marks}/${name}`, + { BRAIN_HOST_ADMISSION_LIMIT: "2" })); + expect(await Promise.all(runs.map(run => run.child.exited))).toEqual([0, 0, 0]); + const peaks = ["a", "b", "c"].map(name => Number(readFileSync(join(dir, `peak-${name}`), "utf8"))); + expect(Math.max(...peaks)).toBeLessThanOrEqual(2); + expect(readHistory(ledger).filter(event => event.kind === "admitted").every(event => event.orchestrator === null)).toBe(true); + }); + + test("a crashed holder's slot is reclaimed, including its orphaned command group", async () => { + const { dir, ledger, timings } = fixture(); + const holder = admit(join(dir, "ithaca"), ledger, timings, `echo $$ > ${dir}/orphan; exec sleep 30`); + await until(() => holding(ledger).length === 1 && existsSync(join(dir, "orphan")), "the holder"); + const orphan = Number(readFileSync(join(dir, "orphan"), "utf8")); + holder.child.kill("SIGKILL"); + await holder.child.exited; + expect(alive(orphan), "the detached command survives its killed wrapper").toBe(true); + const next = admit(join(dir, "ogygia"), ledger, timings, "echo PENELOPE_ADMITTED"); + expect(await Promise.race([next.child.exited, Bun.sleep(8_000).then(() => "blocked")])).toBe(0); + expect(await next.output).toContain("PENELOPE_ADMITTED"); + expect(alive(orphan), "reclaiming the slot stops the orphaned group").toBe(false); + expect(readHistory(ledger).map(event => event.kind)).toContain("reclaimed"); + }); + + test("a red-main fix queued later is admitted ahead of an ordinary waiter", async () => { + const { dir, ledger, timings } = fixture(); + const log = join(dir, "log"); + const holder = admit(join(dir, "ithaca"), ledger, timings, `while [ ! -e ${dir}/release ]; do sleep 0.02; done; echo holder >> ${log}`); + await until(() => holding(ledger).length === 1, "the holder"); + const ordinary = admit(join(dir, "ithaca"), ledger, timings, `echo ordinary >> ${log}`); + await until(() => queued(ledger).length === 1, "the ordinary waiter"); + const fix = admit(join(dir, "ogygia"), ledger, timings, `echo fix >> ${log}`, { BRAIN_RED_MAIN_FIX: "42" }); + await until(() => queued(ledger).length === 2, "the fix waiter"); + expect(admissionOrder(entries(ledger)).map(entry => entry.priority)).toEqual(["red-main-fix", "ordinary"]); + // The running holder is not preempted by priority alone. + expect(holding(ledger)).toHaveLength(1); + Bun.write(join(dir, "release"), ""); + expect(await Promise.all([holder.child.exited, ordinary.child.exited, fix.child.exited])).toEqual([0, 0, 0]); + expect(readFileSync(log, "utf8").trim().split("\n")).toEqual(["holder", "fix", "ordinary"]); + expect(readHistory(ledger).find(event => event.kind === "queued" && event.priority === "red-main-fix")?.fixPR).toBe(42); + }); + + test("preemption lets the holder's cleanup finish before the slot is reassigned, and records preempted", async () => { + const { dir, ledger, timings } = fixture(); + const crew = { BRAIN_ORCHESTRATOR_ID: "odysseus", BRAIN_WORKER_ID: "eurylochus" }; + // The holder's cleanup (a stand-in for unmounting and removing a tmpfs) + // takes a while and writes a marker when it is done. + const holder = admit(join(dir, "ithaca"), ledger, timings, + // The command exits at once and leaves the cleanup to another group member. + `trap '(sleep 0.3; echo cleaned > ${dir}/cleanup) & exit 143' TERM; while true; do sleep 0.02; done`, crew); + await until(() => holding(ledger).length === 1, "the holder"); + const slot = holding(ledger)[0]!.id; + const fix = admit(join(dir, "ogygia"), ledger, timings, `test -e ${dir}/cleanup && echo FIX_AFTER_CLEANUP`, { BRAIN_RED_MAIN_FIX: "7" }); + await until(() => queued(ledger).length === 1, "the fix waiter"); + const preempt = Bun.spawnSync([process.execPath, SCRIPT, "preempt", slot, "--reason", "red-main-fix", "--grace-ms", "5000"], + { env: env(ledger, { BRAIN_ORCHESTRATOR_ID: "odysseus" }), stdout: "pipe", stderr: "pipe" }); + expect(preempt.exitCode, preempt.stderr.toString()).toBe(0); + expect(JSON.parse(preempt.stdout.toString())).toEqual({ slot, reason: "red-main-fix", preempted: true, forced: false }); + expect(await holder.child.exited).toBe(PREEMPTED_EXIT); + expect(await holder.output).toContain("neither passed nor failed"); + expect(readFileSync(join(dir, "cleanup"), "utf8")).toBe("cleaned\n"); + expect(await fix.child.exited).toBe(0); + expect(await fix.output).toContain("FIX_AFTER_CLEANUP"); + const kinds = readHistory(ledger).filter(event => event.slot === slot).map(event => event.kind); + expect(kinds).toEqual(["queued", "admitted", "preempt-requested", "preempted"]); + const admittedFix = readHistory(ledger).find(event => event.kind === "admitted" && event.priority === "red-main-fix")!; + expect(Date.parse(admittedFix.at as string)).toBeGreaterThanOrEqual(statSync(join(dir, "cleanup")).mtimeMs - 5); + }); + + test("preempt refuses a slot held under a different orchestrator, and any reason but a red-main fix", async () => { + const { dir, ledger, timings } = fixture(); + const holder = admit(join(dir, "ithaca"), ledger, timings, `while [ ! -e ${dir}/release ]; do sleep 0.02; done`, + { BRAIN_ORCHESTRATOR_ID: "circe" }); + await until(() => holding(ledger).length === 1, "the holder"); + const slot = holding(ledger)[0]!.id; + const fix = admit(join(dir, "ogygia"), ledger, timings, "true", { BRAIN_RED_MAIN_FIX: "7", BRAIN_ORCHESTRATOR_ID: "odysseus" }); + await until(() => queued(ledger).length === 1, "the fix waiter"); + const attempt = (orchestrator: string, reason: string) => Bun.spawnSync([process.execPath, SCRIPT, "preempt", slot, "--reason", reason], + { env: env(ledger, { BRAIN_ORCHESTRATOR_ID: orchestrator }), stdout: "pipe", stderr: "pipe" }); + const foreign = attempt("odysseus", "red-main-fix"); + expect(foreign.exitCode).toBe(2); + expect(foreign.stderr.toString()).toContain("outside the caller's orchestrator subtree"); + const unruled = attempt("circe", "faster-feedback"); + expect(unruled.exitCode).toBe(2); + expect(unruled.stderr.toString()).toContain("only permitted to admit a red-main fix"); + expect(holding(ledger)[0]?.preempt).toBeUndefined(); + expect(readHistory(ledger).some(event => event.kind === "preempt-requested")).toBe(false); + Bun.write(join(dir, "release"), ""); + expect(await Promise.all([holder.child.exited, fix.child.exited])).toEqual([0, 0]); + }); + + test("the limit defaults from the CPU count and is overridden by BRAIN_HOST_ADMISSION_LIMIT", () => { + expect(admissionLimit({}, 16)).toBe(4); + expect(admissionLimit({}, 2)).toBe(1); + expect(admissionLimit({ BRAIN_HOST_ADMISSION_LIMIT: "3" }, 16)).toBe(3); + expect(() => admissionLimit({ BRAIN_HOST_ADMISSION_LIMIT: "0" }, 16)).toThrow("positive integer"); + }); +}); + +describe("which test runs are heavy", () => { + const costs = { "tests/raft.test.ts": HEAVY_TEST_FILE_SECONDS, "tests/oar.test.ts": 1 }; + test("the integrated suite, runtime-host, native and long files need admission; a focused file does not", () => { + expect(heavyTestReason(ROOT, ROOT, [], costs)).toBe("integrated suite"); + expect(heavyTestReason(ROOT, ROOT, ["--timeout", "30000"], costs)).toBe("integrated suite"); + expect(heavyTestReason(ROOT, ROOT, ["packages/ui-react/tests/draft-runtime.test.ts"], costs)).toBe("runtime-host tests"); + expect(heavyTestReason(ROOT, ROOT, ["scripts/native-proof/reference-pool.native.ts"], costs)).toBe("native tests"); + expect(heavyTestReason(ROOT, ROOT, ["./tests/raft.test.ts"], costs)).toBe("long test file tests/raft.test.ts"); + expect(heavyTestReason(ROOT, ROOT, ["./tests"], costs)).toBe("long test file tests/raft.test.ts"); + expect(heavyTestReason(ROOT, ROOT, ["./tests/oar.test.ts"], costs)).toBeUndefined(); + }); +}); diff --git a/tests/local-checks.test.ts b/tests/local-checks.test.ts index 7d7f8c4d18..2cb84e042a 100644 --- a/tests/local-checks.test.ts +++ b/tests/local-checks.test.ts @@ -117,6 +117,7 @@ test("focused and full local CLI refuse setup before downstream proof while plan for (const helper of ["ci-plan", "ci-runner", "check-packages", "check-receipt"]) { writeFileSync(join(dir, `scripts/${helper}.ts`), `export * from ${JSON.stringify(join(owner, `scripts/${helper}.ts`))};\n`); } + writeFileSync(join(dir, "scripts/host-admission.mjs"), `export * from ${JSON.stringify(join(owner, "scripts/host-admission.mjs"))};\n`); writeFileSync(join(dir, "package.json"), JSON.stringify({ private: true, workspaces: ["packages/*"] })); writeFileSync(join(dir, "packages/ithaca/package.json"), JSON.stringify({ name: "@odysseus/ithaca" })); writeFileSync(join(dir, ".gitignore"), "tmp/\n"); @@ -347,7 +348,7 @@ function importFixture() { const dir = fixture(); const root = join(import.meta.dir, ".."); mkdirSync(join(dir, "scripts")); - for (const helper of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs"]) { + for (const helper of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { cpSync(join(root, "scripts", helper), join(dir, "scripts", helper)); } mkdirSync(join(dir, "packages/core/tests"), { recursive: true }); diff --git a/tests/test-script.test.ts b/tests/test-script.test.ts index fe5a182067..c8749b7fa8 100644 --- a/tests/test-script.test.ts +++ b/tests/test-script.test.ts @@ -33,7 +33,7 @@ async function run(args: string[], env: Record = {}) { if (existsSync(script)) { mkdirSync(join(dir, "scripts")); cpSync(script, join(dir, "scripts/test.ts")); - for (const helper of ["runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs"]) { + for (const helper of ["runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { cpSync(join(ROOT, "scripts", helper), join(dir, "scripts", helper)); } // The actual preload also owns cleanup for the shared CLI harness. @@ -118,6 +118,30 @@ describe("root test script, run for real", () => { expect(await ran(["--test-name-pattern", "--balanced-shard=1/3", "other"])).toEqual(["other"]); }); + test("the integrated suite waits for a host admission slot; a focused path does not (#2943)", async () => { + const ledger = mkdtempSync(join(tmpdir(), "odysseus-test-admission-")); + try { + // The caller's own slot, if any, must not admit these runs. + const env = { BRAIN_HOST_ADMISSION_DIR: ledger, BRAIN_HOST_ADMISSION_LIMIT: "1", BRAIN_HOST_ADMISSION: "" }; + const holder = Bun.spawn([process.execPath, join(ROOT, "scripts/host-admission.mjs"), "run", "--poll-ms", "20", "--", "sh", "-c", `while [ ! -e ${ledger}/release ]; do sleep 0.02; done`], + { env: { ...process.env, ...env }, stdout: "ignore", stderr: "ignore" }); + while (!(existsSync(join(ledger, "state.json")) && readFileSync(join(ledger, "state.json"), "utf8").includes('"holding"'))) await Bun.sleep(10); + const focused = await run(["other"], env); + expect(focused.ran).toEqual(["other"]); + expect(focused.output).not.toContain("Waiting for a host admission slot"); + const pending = run([], env); + while (!readFileSync(join(ledger, "state.json"), "utf8").includes('"queued"')) await Bun.sleep(10); + writeFileSync(join(ledger, "release"), ""); + const integrated = await pending; + expect(integrated.code).toBe(0); + expect(integrated.ran).toEqual(DEFAULT_SET); + expect(integrated.output).toContain("Waiting for a host admission slot (1 on this host): position 1 of 1"); + expect(await holder.exited).toBe(0); + } finally { + rmSync(ledger, { recursive: true, force: true }); + } + }); + test("a failing test fails the command", async () => { const result = await run(["other"], { FAIL_OTHER: "1" }); expect(result.ran).toEqual(["other"]); diff --git a/tests/test-shards.test.ts b/tests/test-shards.test.ts index 02ab31ca6d..fd415d32bd 100644 --- a/tests/test-shards.test.ts +++ b/tests/test-shards.test.ts @@ -59,7 +59,7 @@ describe("balanced shards run the root command for real", () => { mkdirSync(join(dir, "scripts")); const manifest = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")); writeFileSync(join(dir, "package.json"), JSON.stringify({ name: "fixture", scripts: { test: manifest.scripts.test } })); - for (const script of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs"]) { + for (const script of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { cpSync(join(ROOT, "scripts", script), join(dir, "scripts", script)); } mkdirSync(join(dir, "packages/core/tests"), { recursive: true }); diff --git a/tests/visual-runner.test.ts b/tests/visual-runner.test.ts index bf71256395..9eb3c01672 100644 --- a/tests/visual-runner.test.ts +++ b/tests/visual-runner.test.ts @@ -27,6 +27,8 @@ async function invoke(args: string[], exit = 0, imageState: "warm"|"cold"|"drift await mkdir(dirname(resolve(root, file)), { recursive: true }); await copyFile(resolve(import.meta.dir, "..", file), resolve(root, file)); } + // The host side of the wrapper admits itself through the host ledger (#2943). + await copyFile(resolve(import.meta.dir, "../scripts/host-admission.mjs"), resolve(root, "scripts/host-admission.mjs")); for (const domain of diagramSourceDomains) { const manifest = JSON.parse(await readFile(resolve(root, `packages/${domain}/package.json`), "utf8")); const alias = resolve(root, "node_modules", manifest.name);await mkdir(dirname(alias), {recursive:true});await symlink(resolve(root, "packages", domain), alias); diff --git a/tests/workspace-lease.test.ts b/tests/workspace-lease.test.ts index 0c84faeb64..bccaaa810b 100644 --- a/tests/workspace-lease.test.ts +++ b/tests/workspace-lease.test.ts @@ -251,7 +251,7 @@ const spawn = (...args) => { test("the real pinned container wrapper waits for host ownership of its mounted checkout", async () => { const root = fixture(helper, false, false, join(project, "tmp", "workspace-lease-container")); for (const path of ["scripts", "packages/ui-kit", "node_modules/vitest"]) mkdirSync(join(root, path), { recursive: true }); - for (const name of ["visual.mjs", "workspace-lease.mjs", "prepare-diagram-export-source.mjs", "diagram-export-source.mjs", "diagram-export-installation.mjs", "diagram-export-producer.mjs"]) copyFileSync(join(project, "scripts", name), join(root, "scripts", name)); + for (const name of ["visual.mjs", "workspace-lease.mjs", "host-admission.mjs", "prepare-diagram-export-source.mjs", "diagram-export-source.mjs", "diagram-export-installation.mjs", "diagram-export-producer.mjs"]) copyFileSync(join(project, "scripts", name), join(root, "scripts", name)); writeFileSync(join(root, "node_modules/vitest/vitest.mjs"), 'import {writeFileSync} from "node:fs";writeFileSync(new URL("../../vitest-entered",import.meta.url),"native container acquired ownership\\n");\n'); const owner = start(root, "write", "hold", "host"); await entered(root, "host"); From 2a4699cc3758efb908be7958d2081f5aadab9ef3 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 09:33:43 +0000 Subject: [PATCH 3/9] docs(process): document host admission and its environment Refs #2943 Co-Authored-By: Claude Opus 5.5 --- docs/process/ci-throughput.md | 2 ++ docs/process/testing.md | 44 +++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/docs/process/ci-throughput.md b/docs/process/ci-throughput.md index f7f0a6cf59..eb4d5c8551 100644 --- a/docs/process/ci-throughput.md +++ b/docs/process/ci-throughput.md @@ -95,6 +95,8 @@ ID/time permit attributed historical observations. IDs cannot be overwritten with different content. Pairs are `work-started`/`work-finished` and `wait-started`/`wait-finished`; waits require `reason` set to `reservation`, `ci`, `review`, `conflict` or `other`. Each pair shares worker/task/reason. +Host admission records each wait for a heavy local slot as a pair with reason +`other` and task `admission-` ([host admission](testing.md#host-admission-for-heavy-local-commands)). Unmatched records remain unknown; overlapping tasks on one worker do not create two workers. Complete task intervals measure task lifetime, not CPU busy time or token cost. No records means unknown worker concurrency. This endpoint does diff --git a/docs/process/testing.md b/docs/process/testing.md index 762ef41e9b..e85c27fdf9 100644 --- a/docs/process/testing.md +++ b/docs/process/testing.md @@ -424,6 +424,50 @@ permits setup failures and does not belong in proof. A PATH change on the host does not upgrade a fixed `/usr/bin/bwrap` inside a container; qualify that runtime separately before changing its supplied binary. Hosted CI images stay unchanged. +## Host admission for heavy local commands + +Local long suites are for debugging a specific failure only (#2939); they run +through a host-wide admission ledger, `scripts/host-admission.mjs` (#2943). +Separate worktrees on one machine share its slots, so a heavy command that +would exceed the limit waits, printing the holders and its queue position, +instead of starting and timing out. Test deadlines are never raised to absorb +contention. + +Heavy commands are the integrated default `bun run test` suite, runtime-host +and native test selections, any selected file whose measured cost in +`scripts/test-shard-costs.json` reaches 30 seconds, `check:pr --full`/`--all` +and `bun run test:browser` (held on the host for the whole container run). +Focused tests and default `check:pr` are not admitted. Nested heavy commands +inherit their caller's slot. A wait is recorded as a `wait-started`/`wait-finished` +pair with reason `other` through `scripts/ci-timings.ts record` +([coordination events](ci-throughput.md#record-coordination-and-incidents)). + +| Variable | Meaning | +| --- | --- | +| `BRAIN_HOST_ADMISSION_LIMIT` | Concurrent heavy commands admitted on this host. Defaults to one per four CPUs, at least 1; anything but a positive integer is refused. | +| `BRAIN_HOST_ADMISSION_DIR` | Ledger directory. Defaults to `brain-host-admission-` under the system temporary directory. The test preload gives each test process a private ledger unless a test names one. | +| `BRAIN_WORKER_ID`, `BRAIN_ORCHESTRATOR_ID` | Opaque worker and orchestrator IDs recorded with each slot. Without them a worker is `host-` and has no orchestrator; it still gets the admission limit. | +| `BRAIN_RED_MAIN_FIX` | The PR number of a declared red-main fix. Its commands are admitted ahead of every queued ordinary command; they do not preempt running ones. Equivalent to `run --red-main-fix `. | +| `BRAIN_HOST_ADMISSION` | Internal: the slot an admitted command's descendants inherit. Never set it by hand. | + +```sh +node scripts/host-admission.mjs status +node scripts/host-admission.mjs run [--red-main-fix ] -- +node scripts/host-admission.mjs preempt --reason red-main-fix [--grace-ms 10000] +``` + +The ledger records each slot's holder process identity, worker, orchestrator +and priority class. A holder whose process has died is reclaimed on the next +pass, after its orphaned command group has been killed. `preempt` follows the +[#2938 ruling](https://github.com/schlessera/brain-kit/issues/2938): it refuses +a slot outside the caller's orchestrator subtree, any reason but +`red-main-fix`, and a call while no red-main fix is waiting. It sends SIGTERM to +the holder's process group, lets cleanup run for the grace period, then kills +it; the slot is released only after the group has gone. The preempted run exits +`75` and is recorded as `preempted` in the ledger history, which is neither a +pass nor a failure. Another orchestrator's holder yields only through queue +priority or the maintainer. + ## Required proof for a PR The policy is [the CI decision](../decisions/ci-utility.md); the commands are From 0f0f3eccc38e2a036b51eb92b6b7f45049107ed3 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 09:34:53 +0000 Subject: [PATCH 4/9] fix(ci): admit check:pr --full only after its prerequisite refusals Refs #2943 Co-Authored-By: Claude Opus 5.5 --- scripts/check-pr.ts | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/scripts/check-pr.ts b/scripts/check-pr.ts index abebae5933..7bdcd5e64e 100644 --- a/scripts/check-pr.ts +++ b/scripts/check-pr.ts @@ -223,11 +223,6 @@ if (import.meta.main) { else throw new Error("usage: bun run check:pr [--base ] [--full|--all] [--import-graph] [--plan] [--import-graph-workers=N] [--check-timeout=] [--skip ]... [--receipt ]"); } const root = resolve(import.meta.dir, ".."); - if (full && !print) { - // Full local suites are for debugging only and run through host admission (#2939, #2943). - const admitted = await ensureHostAdmission(all ? "check:pr --all" : "check:pr --full"); - if (admitted !== undefined) process.exit(admitted); - } const changed = all ? ["package.json"] : changedFiles(root, base, "HEAD", true, true); const plan = planChecks(changed, workspaces(root), root); let mergeBase: string | undefined; @@ -272,6 +267,16 @@ if (import.meta.main) { receipt.finishedAt = new Date().toISOString(); save(receipt); throw error; } + if (full) { + // Full local suites are for debugging only and run through host admission + // (#2939, #2943), after the cheap prerequisite refusals above. + const admitted = await ensureHostAdmission(all ? "check:pr --all" : "check:pr --full"); + if (admitted !== undefined) { + for (const check of receipt.checks) check.reason = "not run: host admission did not admit this run"; + receipt.finishedAt = new Date().toISOString(); save(receipt); + process.exit(admitted); + } + } const report = () => { console.log(`check:pr receipt written to ${receiptPath}. Paste this block into the PR body, replacing any earlier one:\n${receiptBlock(receipt)}`); }; From 33e3945e1fd729308bcad57eaa16e96dc1d8b82c Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 11:08:44 +0000 Subject: [PATCH 5/9] fix(ci): keep host admission inherited across replaced environments and namespaces Hosted unit proof timed out: the parallel unit-worker queue's workers queued behind each other; descendants whose caller replaced their environment lost the inherited slot and queued behind their own ancestor; and admitted commands lost the workspace lease descriptor, so a re-executed test wrapper in a nested user namespace waited on its own ancestor's workspace lock. The unit-worker queue now holds one slot for all its workers. Admission is also inherited when the ledger shows a live ancestor holding a slot, test processes register a private ledger their descendants find by ancestry, and both admission hops forward the workspace lease descriptor. Refs #2943 Co-Authored-By: Claude Opus 5.5 --- docs/decisions/ci-utility.md | 2 +- docs/process/testing.md | 13 +++--- scripts/host-admission.d.mts | 1 + scripts/host-admission.mjs | 67 ++++++++++++++++++++++------ scripts/test-network-preload.ts | 19 ++++---- scripts/unit-workers.ts | 5 +++ tests/helpers/unit-worker-fixture.ts | 2 +- tests/host-admission.test.ts | 43 +++++++++++++++++- 8 files changed, 121 insertions(+), 31 deletions(-) diff --git a/docs/decisions/ci-utility.md b/docs/decisions/ci-utility.md index 27c2a02098..d739f60377 100644 --- a/docs/decisions/ci-utility.md +++ b/docs/decisions/ci-utility.md @@ -169,7 +169,7 @@ Local import-graph feedback uses eight workers on the measured 32-CPU, 47-GiB host. The default is `max(1, min(floor(cores / 4), floor(RAM * 0.7 / 2 GiB)))`, with `--import-graph-workers=N` as the override (`localUnitWorkerCount`, -`scripts/unit-workers.ts:15-17`). Changed-mode workers use one fresh prepared +`scripts/unit-workers.ts:16-18`). Changed-mode workers use one fresh prepared build and private overlay views; `unit-workers --private-tree` retains the ordinary private-build comparison. Hosted explicit-file partitions retain `balanceTests`, their private builds and N=2. diff --git a/docs/process/testing.md b/docs/process/testing.md index e85c27fdf9..e1b33229e0 100644 --- a/docs/process/testing.md +++ b/docs/process/testing.md @@ -435,17 +435,20 @@ contention. Heavy commands are the integrated default `bun run test` suite, runtime-host and native test selections, any selected file whose measured cost in -`scripts/test-shard-costs.json` reaches 30 seconds, `check:pr --full`/`--all` -and `bun run test:browser` (held on the host for the whole container run). -Focused tests and default `check:pr` are not admitted. Nested heavy commands -inherit their caller's slot. A wait is recorded as a `wait-started`/`wait-finished` +`scripts/test-shard-costs.json` reaches 30 seconds, `check:pr --full`/`--all`, +the parallel unit-worker queue (one slot for all its workers) and +`bun run test:browser` (held on the host for the whole container run). Focused +tests and default `check:pr` are not admitted. Nested heavy commands inherit +their caller's slot, also when a caller replaced their environment: the +ledger itself shows a live ancestor holding a slot. The admitted command +receives the workspace lease's descriptor, as a nested user namespace needs. A wait is recorded as a `wait-started`/`wait-finished` pair with reason `other` through `scripts/ci-timings.ts record` ([coordination events](ci-throughput.md#record-coordination-and-incidents)). | Variable | Meaning | | --- | --- | | `BRAIN_HOST_ADMISSION_LIMIT` | Concurrent heavy commands admitted on this host. Defaults to one per four CPUs, at least 1; anything but a positive integer is refused. | -| `BRAIN_HOST_ADMISSION_DIR` | Ledger directory. Defaults to `brain-host-admission-` under the system temporary directory. The test preload gives each test process a private ledger unless a test names one. | +| `BRAIN_HOST_ADMISSION_DIR` | Ledger directory. Defaults to `brain-host-admission-` under the system temporary directory. The test preload gives each test process a private ledger, which its descendants also find through their ancestry; a test exercising the host ledger names its own. | | `BRAIN_WORKER_ID`, `BRAIN_ORCHESTRATOR_ID` | Opaque worker and orchestrator IDs recorded with each slot. Without them a worker is `host-` and has no orchestrator; it still gets the admission limit. | | `BRAIN_RED_MAIN_FIX` | The PR number of a declared red-main fix. Its commands are admitted ahead of every queued ordinary command; they do not preempt running ones. Equivalent to `run --red-main-fix `. | | `BRAIN_HOST_ADMISSION` | Internal: the slot an admitted command's descendants inherit. Never set it by hand. | diff --git a/scripts/host-admission.d.mts b/scripts/host-admission.d.mts index 53960b42b0..97efcf69b2 100644 --- a/scripts/host-admission.d.mts +++ b/scripts/host-admission.d.mts @@ -2,6 +2,7 @@ export const MARKER: "BRAIN_HOST_ADMISSION"; export const PREEMPTED_EXIT: 75; export const RED_MAIN_FIX: "red-main-fix"; export const DEFAULT_GRACE_MS: number; +export function testLedgerFor(pid: number, start: string): string; export function ledgerDir(env?: Record): string; export function admissionLimit(env?: Record, cpus?: number): number; export interface AdmissionEntry { diff --git a/scripts/host-admission.mjs b/scripts/host-admission.mjs index 2c5d113280..98265cc473 100644 --- a/scripts/host-admission.mjs +++ b/scripts/host-admission.mjs @@ -18,12 +18,12 @@ * orchestrator subtree, and only to admit a waiting red-main fix. A preempted * run is recorded as `preempted`, which is neither a pass nor a failure. */ -import { appendFileSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs"; import { randomBytes } from "node:crypto"; import { availableParallelism, constants, tmpdir } from "node:os"; import { dirname, join, resolve } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; -import { liveAncestor, processIdentity } from "./workspace-lease.mjs"; +import { inheritWorkspaceLease, liveAncestor, processIdentity } from "./workspace-lease.mjs"; /** Inherited by an admitted command, so its nested heavy commands do not queue behind themselves. */ export const MARKER = "BRAIN_HOST_ADMISSION"; @@ -37,10 +37,42 @@ const repoRoot = resolve(dirname(script), ".."); const sleep = ms => new Promise(done => setTimeout(done, ms)); const now = () => new Date().toISOString(); -/** One ledger per host user; worktrees and clones on the machine share it. */ +const user = () => typeof process.getuid === "function" ? process.getuid() : "user"; + +/** + * A test process's private ledger. The test preload creates it with the same + * convention, so a descendant whose environment was replaced still finds it + * through its ancestry and never queues behind the host's real heavy commands. + */ +export function testLedgerFor(pid, start) { + return join(tmpdir(), `brain-host-admission-tests-${user()}`, `${pid}-${start}`); +} + +/** This process's ancestors, nearest first (Linux only). */ +function ancestors() { + const found = []; + if (process.platform !== "linux") return found; + let pid = processIdentity(process.pid)?.parent; + for (let depth = 0; pid > 0 && depth < 128; depth++) { + const identity = processIdentity(pid); + if (!identity) break; + found.push({ pid, start: identity.start }); + pid = identity.parent; + } + return found; +} + +/** + * One ledger per host user; worktrees and clones on the machine share it. + * An explicit directory wins, then the nearest ancestor test process's ledger. + */ export function ledgerDir(env = process.env) { - const user = typeof process.getuid === "function" ? process.getuid() : "user"; - return resolve(env.BRAIN_HOST_ADMISSION_DIR || join(tmpdir(), `brain-host-admission-${user}`)); + if (env.BRAIN_HOST_ADMISSION_DIR) return resolve(env.BRAIN_HOST_ADMISSION_DIR); + for (const ancestor of ancestors()) { + const dir = testLedgerFor(ancestor.pid, ancestor.start); + if (existsSync(dir)) return dir; + } + return join(tmpdir(), `brain-host-admission-${user()}`); } /** Heavy suites each use many cores; by default admit one per four CPUs. */ @@ -258,8 +290,10 @@ export async function runAdmitted(command, options = {}) { if (waited) await recordWait("wait-finished", { worker, task, timingsOut, root, ledger: dir }); if (cancelled) { await release("cancelled"); return exitCode(null, cancelled); } const { spawn } = await import("node:child_process"); - child = spawn(command[0], command.slice(1), { stdio: "inherit", detached: process.platform !== "win32", - env: { ...env, [MARKER]: JSON.stringify({ slot: id, pid: process.pid, start, dir }) } }); + // Pass the workspace lease's descriptor on: a command in a nested user + // namespace cannot prove its inherited lease through /proc. + child = spawn(command[0], command.slice(1), inheritWorkspaceLease({ stdio: ["inherit", "inherit", "inherit"], + detached: process.platform !== "win32", env: { ...env, [MARKER]: JSON.stringify({ slot: id, pid: process.pid, start, dir }) } }, "inherit")); const exited = new Promise(done => { child.once("error", () => done(127)); child.once("exit", (code, signal) => done(exitCode(code, signal))); @@ -342,14 +376,19 @@ export async function status(options = {}) { }); } -/** True when an ancestor already holds a slot for this command tree. */ +/** + * True when an ancestor already holds a slot for this command tree: through + * the inherited marker, or, for a descendant whose environment was replaced, + * through a holder in the ledger that is one of its live ancestors. + */ export function inheritedAdmission(env = process.env) { try { - const held = JSON.parse(env[MARKER] ?? "null"); - if (!held || !Number.isSafeInteger(held.pid) || typeof held.start !== "string") return false; - if (process.platform === "linux") return liveAncestor(held.pid, held.start); - return alive(held.pid, held.start); - } catch { return false; } + const held = JSON.parse(env[MARKER] || "null"); + if (held && Number.isSafeInteger(held.pid) && typeof held.start === "string" && + (process.platform === "linux" ? liveAncestor(held.pid, held.start) : alive(held.pid, held.start))) return true; + } catch { /* A malformed marker grants nothing; the ledger may still. */ } + if (process.platform !== "linux") return false; + return readState(ledgerDir(env)).entries.some(entry => entry.state === "holding" && liveAncestor(entry.pid, entry.start)); } /** @@ -365,7 +404,7 @@ export async function ensureHostAdmission(label) { signals.forEach((signal, index) => process.on(signal, listeners[index])); try { child = spawn(process.execPath, [script, "run", "--label", label, "--", process.execPath, ...process.execArgv, ...process.argv.slice(1)], - { stdio: "inherit" }); + inheritWorkspaceLease({ stdio: ["inherit", "inherit", "inherit"] }, "inherit")); if (pending) child.kill(pending); return await new Promise((done, reject) => { child.once("error", reject); diff --git a/scripts/test-network-preload.ts b/scripts/test-network-preload.ts index 68e11727ab..bb85a12738 100644 --- a/scripts/test-network-preload.ts +++ b/scripts/test-network-preload.ts @@ -2,19 +2,22 @@ import { afterAll, afterEach } from "bun:test"; import { cleanupCliUtilities } from "../packages/core/tests/cli-harness"; import { installNetworkGuard } from "./test-network-guard"; import { join, resolve } from "node:path"; -import { rmSync } from "node:fs"; +import { mkdirSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; -import { ensureWorkspaceLease, workspaceTestAccess } from "./workspace-lease.mjs"; +import { ensureWorkspaceLease, processIdentity, workspaceTestAccess } from "./workspace-lease.mjs"; const guard = installNetworkGuard(); const coordinated = await ensureWorkspaceLease(resolve(import.meta.dir, ".."), workspaceTestAccess(), "test"); if (coordinated !== undefined) process.exit(coordinated); // Commands a test spawns queue in a ledger private to this test process, never -// behind the host's real heavy commands (#2943). A test that exercises the host -// ledger names its own directory; an admitted caller's descendants inherit its slot. -const privateAdmission = process.env.BRAIN_HOST_ADMISSION_DIR ? undefined : - join(tmpdir(), "brain-host-admission-tests", String(process.pid)); -if (privateAdmission) process.env.BRAIN_HOST_ADMISSION_DIR = privateAdmission; +// behind the host's real heavy commands (#2943). The path is testLedgerFor's +// convention in scripts/host-admission.mjs, so a descendant whose environment +// was replaced finds it through its ancestry. A test exercising the host ledger +// names its own directory; an admitted caller's descendants inherit its slot. +const privateAdmission = join(tmpdir(), `brain-host-admission-tests-${process.getuid?.() ?? "user"}`, + `${process.pid}-${processIdentity(process.pid)?.start ?? "0"}`); +mkdirSync(privateAdmission, { recursive: true, mode: 0o700 }); +process.env.BRAIN_HOST_ADMISSION_DIR = privateAdmission; afterEach(() => guard.assertNoEscapes()); // A preload hook runs after all files; a hook in the cached helper would run // after its first importing file. Bun test does not run the ordinary exit hook. @@ -23,6 +26,6 @@ afterAll(() => { guard.assertNoEscapes(); } finally { cleanupCliUtilities(); - if (privateAdmission) rmSync(privateAdmission, { recursive: true, force: true }); + rmSync(privateAdmission, { recursive: true, force: true }); } }); diff --git a/scripts/unit-workers.ts b/scripts/unit-workers.ts index faf960a393..a417d3a1ab 100644 --- a/scripts/unit-workers.ts +++ b/scripts/unit-workers.ts @@ -4,6 +4,7 @@ import { createHash, randomUUID } from "node:crypto"; import { availableParallelism, tmpdir, totalmem } from "node:os"; import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path"; import { runCommands } from "./ci-runner"; +import { ensureHostAdmission } from "./host-admission.mjs"; import { balanceTests, FILE_COST_SECONDS } from "./test-shards"; import { validateChangedUnitReports, validateUnitReports } from "./unit-proof-report"; import { captureUnitInputs } from "./unit-worker-inputs"; @@ -430,6 +431,10 @@ async function bootstrapPreparedTree(root: string, files: readonly string[], chr } if (import.meta.main) { + // The queue is one heavy command: it holds a single host slot (#2943) that + // its parallel workers inherit, rather than queueing them behind each other. + const admitted = await ensureHostAdmission("unit worker queue"); + if (admitted !== undefined) process.exit(admitted); try { const root = resolve(import.meta.dir, ".."); const options: UnitWorkerOptions = {}, files: string[] = []; diff --git a/tests/helpers/unit-worker-fixture.ts b/tests/helpers/unit-worker-fixture.ts index e2b73ffd28..82031daf4d 100644 --- a/tests/helpers/unit-worker-fixture.ts +++ b/tests/helpers/unit-worker-fixture.ts @@ -66,7 +66,7 @@ const stop=Date.now()+5000;while((!existsSync(join(shared,"built-1"))||!existsSy ${options.failBuild ? "process.exit(7);" : ""} mkdirSync("dist",{recursive:true});writeFileSync("dist/lease.json",JSON.stringify({lease:JSON.parse(process.env.BRAIN_WORKSPACE_LEASE),nonce:process.env.BRAIN_TEST_INVOCATION_NONCE}));writeFileSync("dist/ready.txt","Odysseus builds the raft.");receipt.packageEnd("raft",true);receipt.finish(0);\n`); for (const file of ["scripts/test.ts", "scripts/runtime-test-builds.ts", "scripts/test-invocation.ts", "scripts/test-invocation-child.ts", "scripts/publishable-packages.ts", - "scripts/workspace-lease.mjs", "scripts/test-network-preload.ts", "scripts/test-network-child-preload.ts", "scripts/test-network-guard.ts", "packages/core/tests/cli-harness.ts"]) { + "scripts/workspace-lease.mjs", "scripts/host-admission.mjs", "scripts/test-shards.ts", "scripts/test-shard-costs.json", "scripts/test-network-preload.ts", "scripts/test-network-child-preload.ts", "scripts/test-network-guard.ts", "packages/core/tests/cli-harness.ts"]) { write(file, readFileSync(join(source, file), "utf8")); } const files = ["odysseus", "penelope"].map(name => `tests/${name}.test.ts`); diff --git a/tests/host-admission.test.ts b/tests/host-admission.test.ts index 789db3af37..d70bd35d12 100644 --- a/tests/host-admission.test.ts +++ b/tests/host-admission.test.ts @@ -1,10 +1,11 @@ // Host-wide admission for heavy local commands (#2943): separate worktrees on // one machine share a limited number of slots instead of timing out together. import { afterEach, describe, expect, test } from "bun:test"; -import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, statSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; -import { admissionLimit, admissionOrder, PREEMPTED_EXIT, readHistory, type AdmissionEntry } from "../scripts/host-admission.mjs"; +import { admissionLimit, admissionOrder, PREEMPTED_EXIT, readHistory, testLedgerFor, type AdmissionEntry } from "../scripts/host-admission.mjs"; +import { processIdentity } from "../scripts/workspace-lease.mjs"; import { heavyTestReason, HEAVY_TEST_FILE_SECONDS } from "../scripts/test"; const ROOT = resolve(import.meta.dir, ".."); @@ -186,6 +187,44 @@ describe("host admission ledger", () => { expect(await Promise.all([holder.child.exited, fix.child.exited])).toEqual([0, 0]); }); + test("a descendant whose environment lost the slot marker still inherits its ancestor's slot", async () => { + const { dir, ledger, timings } = fixture(); + // The nested heavy command's caller replaced its environment (as test + // fixtures and sandbox wrappers do), dropping BRAIN_HOST_ADMISSION. + const nested = `env -u BRAIN_HOST_ADMISSION ${process.execPath} -e 'const m = await import("${SCRIPT}"); ` + + `const code = await m.ensureHostAdmission("nested"); console.log(code === undefined ? "NESTED_INHERITED" : "NESTED_QUEUED"); process.exit(code ?? 0)'`; + const holder = admit(join(dir, "ithaca"), ledger, timings, nested); + expect(await Promise.race([holder.child.exited, Bun.sleep(8_000).then(() => "deadlocked")])).toBe(0); + expect(await holder.output).toContain("NESTED_INHERITED"); + }); + + test("a descendant without a ledger directory finds its test process's private ledger", () => { + const own = testLedgerFor(process.pid, processIdentity(process.pid)!.start); + expect(existsSync(own), "the test preload creates this process's private ledger").toBe(true); + const child = Bun.spawnSync([process.execPath, "-e", `console.log((await import(${JSON.stringify(SCRIPT)})).ledgerDir({}))`], + { env: { PATH: process.env.PATH! }, stdout: "pipe", stderr: "pipe" }); + expect(child.stdout.toString().trim(), child.stderr.toString()).toBe(own); + }); + + test("the admitted command receives the workspace lease descriptor, not only its marker", async () => { + // This test runs under the real workspace lease; a command in a nested + // user namespace can prove that inheritance only through the descriptor. + const { dir, ledger, timings } = fixture(); + // Node, unlike Bun, gets no offline-harness child preload, which would + // itself forward the lease and hide a wrapper that dropped it. + const node = Bun.which("node"); + if (!node) throw new Error("Lease forwarding proof requires node, as the browser wrapper does"); + const child = Bun.spawn([node, SCRIPT, "run", "--poll-ms", "20", "--timings-out", timings, "--", "sh", "-c", + 'echo "LEASE=$BRAIN_WORKSPACE_LEASE"; for f in /proc/$$/fd/*; do echo "FD $(basename $f) $(readlink $f)"; done'], + { cwd: dir, env: { ...process.env, ...env(ledger) }, stdout: "pipe", stderr: "pipe" }); + children.push(child); + const [out, err] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text()]); + expect(await child.exited, err).toBe(0); + const lease = JSON.parse(out.match(/^LEASE=(.*)$/m)![1]!); + const lock = realpathSync(join(ROOT, "tmp/workspace-operation/output.lock")); + expect(out, "LEASE_DESCRIPTOR_REACHES_THE_ADMITTED_COMMAND").toContain(`FD ${lease.fd} ${lock}`); + }); + test("the limit defaults from the CPU count and is overridden by BRAIN_HOST_ADMISSION_LIMIT", () => { expect(admissionLimit({}, 16)).toBe(4); expect(admissionLimit({}, 2)).toBe(1); From 86e0354968815566ddd80a9ff38fde181931ef47 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 11:31:20 +0000 Subject: [PATCH 6/9] fix(ci): leave no shared directory behind for a test process's private ledger Refs #2943 Co-Authored-By: Claude Opus 5.5 --- scripts/host-admission.mjs | 2 +- scripts/test-network-preload.ts | 8 +++++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/scripts/host-admission.mjs b/scripts/host-admission.mjs index 98265cc473..29c1636007 100644 --- a/scripts/host-admission.mjs +++ b/scripts/host-admission.mjs @@ -45,7 +45,7 @@ const user = () => typeof process.getuid === "function" ? process.getuid() : "us * through its ancestry and never queues behind the host's real heavy commands. */ export function testLedgerFor(pid, start) { - return join(tmpdir(), `brain-host-admission-tests-${user()}`, `${pid}-${start}`); + return join(tmpdir(), `brain-host-admission-test-${user()}-${pid}-${start}`); } /** This process's ancestors, nearest first (Linux only). */ diff --git a/scripts/test-network-preload.ts b/scripts/test-network-preload.ts index bb85a12738..afa60694a5 100644 --- a/scripts/test-network-preload.ts +++ b/scripts/test-network-preload.ts @@ -14,9 +14,11 @@ if (coordinated !== undefined) process.exit(coordinated); // convention in scripts/host-admission.mjs, so a descendant whose environment // was replaced finds it through its ancestry. A test exercising the host ledger // names its own directory; an admitted caller's descendants inherit its slot. -const privateAdmission = join(tmpdir(), `brain-host-admission-tests-${process.getuid?.() ?? "user"}`, - `${process.pid}-${processIdentity(process.pid)?.start ?? "0"}`); -mkdirSync(privateAdmission, { recursive: true, mode: 0o700 }); +// One flat entry, removed in afterAll, so a test asserting an empty TMPDIR +// after its child exits sees nothing left behind. +const privateAdmission = join(tmpdir(), + `brain-host-admission-test-${process.getuid?.() ?? "user"}-${process.pid}-${processIdentity(process.pid)?.start ?? "0"}`); +mkdirSync(privateAdmission, { mode: 0o700 }); process.env.BRAIN_HOST_ADMISSION_DIR = privateAdmission; afterEach(() => guard.assertNoEscapes()); // A preload hook runs after all files; a hook in the cached helper would run From 0c15ffdf4c5a31ea35524c1d27712bee29525cea Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 15:19:19 +0000 Subject: [PATCH 7/9] test(ci): give the receipt CLI fixture the host-admission module check:pr now imports Co-Authored-By: Claude Opus 5.5 --- tests/check-receipt.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/check-receipt.test.ts b/tests/check-receipt.test.ts index a0533bc366..a8fef05016 100644 --- a/tests/check-receipt.test.ts +++ b/tests/check-receipt.test.ts @@ -91,6 +91,7 @@ test("check:pr CLI writes a receipt recording a forced timeout and prints the PR mkdirSync(join(dir, "scripts")); mkdirSync(join(dir, "packages/ithaca"), { recursive: true }); cpSync(join(owner, "scripts/check-pr.ts"), entry); for (const helper of ["ci-plan", "ci-runner", "check-packages", "check-receipt"]) writeFileSync(join(dir, `scripts/${helper}.ts`), `export * from ${JSON.stringify(join(owner, `scripts/${helper}.ts`))};\n`); + writeFileSync(join(dir, "scripts/host-admission.mjs"), `export * from ${JSON.stringify(join(owner, "scripts/host-admission.mjs"))};\n`); writeFileSync(join(dir, "package.json"), JSON.stringify({ private: true, workspaces: ["packages/*"] })); writeFileSync(join(dir, "packages/ithaca/package.json"), JSON.stringify({ name: "@odysseus/ithaca" })); writeFileSync(join(dir, ".gitignore"), "tmp/\n"); From f5af3222eded67c92cd8b7cb744f2f0514be0fd7 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 20:29:34 +0000 Subject: [PATCH 8/9] fix(ci): close releaseFixClaim after merging the claim and expedited-fix records Co-Authored-By: Claude Opus 5.5 --- scripts/red-main.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/scripts/red-main.ts b/scripts/red-main.ts index b2b9e8abeb..9f912950fc 100644 --- a/scripts/red-main.ts +++ b/scripts/red-main.ts @@ -158,6 +158,8 @@ export function releaseFixClaim(record: RedMainRecord, who: Claimant, now: numbe const open = claimable(record, who), held = open.claim ?? null; if (!held || !sameClaimant(held, who)) throw new Error("This worker does not hold the fix claim"); return next(record, now, "release-claim", open.run, { open: { ...open, claim: null } }); +} + /** Records an expedited fix squash on the open record; the next green main run that includes the red set still clears it. */ export function recordExpedited(record: RedMainRecord, fix: ExpeditedFix, now: number): RedMainRecord { if (!record.open) throw new Error("No open red-main record to record an expedited fix on"); From 62c9fda193bf80ab453d171588de94f2da8f404d Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 23:36:56 +0000 Subject: [PATCH 9/9] docs(ci): follow gateDecision and refuseWhileRed to their bundled lines Co-Authored-By: Claude Opus 5.5 --- docs/decisions/ci-utility.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/decisions/ci-utility.md b/docs/decisions/ci-utility.md index d739f60377..3ee6378279 100644 --- a/docs/decisions/ci-utility.md +++ b/docs/decisions/ci-utility.md @@ -1484,7 +1484,7 @@ main run that printed the same open record as included. The first step of a non-draft PR run refuses with `main red at , incident #` when its merge ref contains the bad commit and the PR is not a declared fix. Draft runs keep their cheap gates. One ancestry rule decides every refusal and cancellation -(`gateDecision`, `scripts/red-main.ts:209-216`): proof is doomed only when the +(`gateDecision`, `scripts/red-main.ts:223-230`): proof is doomed only when the tree it tests contains the bad commit and its PR is not a declared fix ([#3321](https://github.com/schlessera/brain-kit/issues/3321)). The coordinator cancels a queued or running PR proof run only when its PR's base or head, as @@ -1494,7 +1494,7 @@ GitHub did not record, or whose ancestry cannot be determined, is left alone. So proof for a PR against an integration or release branch forked before the bad commit keeps running. `integrate.ts` applies the same rule to the candidate's base and head before confirming or merging, and refuses when -ancestry is unknown (`refuseWhileRed`, `scripts/integrate.ts:62-66`). A non-fix squash +ancestry is unknown (`refuseWhileRed`, `scripts/integrate.ts:64-68`). A non-fix squash that lands while red is reported once on its PR and on the incident, and recorded as an `incident` event through `scripts/ci-timings.ts record` in the coordinator's `red-main-events` artifact.