From c33390ef15c78bd62043fdf2b516e3ef079c82f1 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 09:43:33 +0000 Subject: [PATCH 1/7] feat(ci): record a red main centrally, gate doomed proof and coordinate incidents Adds the repository-level red-main record to the shared coordination ref (red-main.json beside reservation.json, exact --force-with-lease CAS), a deterministic flake estimator, a coordinator workflow on main CI completion (one incident issue per record, triage and bisect probes, cancellation of doomed PR proof, detection of squashes that land while red, clearing on a green run that included the red set), a hosted gate as the first PR step, integrate.ts main-status/declare-fix and merge refusal while red, and main runs that select the open red set and run proof even when metadata fails. Refs #2942 Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 48 +++-- .github/workflows/red-main-probe.yml | 66 +++++++ .github/workflows/red-main.yml | 52 +++++ scripts/check-ci-workflows.ts | 9 +- scripts/ci-coordination.ts | 2 + scripts/ci-plan.ts | 34 +++- scripts/integrate.ts | 31 ++- scripts/integration-reservation.ts | 39 +++- scripts/red-main-cli.ts | 122 ++++++++++++ scripts/red-main-coordinator.ts | 281 +++++++++++++++++++++++++++ scripts/red-main.ts | 186 ++++++++++++++++++ tests/ci-plan.test.ts | 3 +- tests/ci-throughput.test.ts | 6 + tests/ci-workflows.test.ts | 17 +- tests/integration-command.test.ts | 17 ++ tests/red-main.test.ts | 276 ++++++++++++++++++++++++++ 16 files changed, 1153 insertions(+), 36 deletions(-) create mode 100644 .github/workflows/red-main-probe.yml create mode 100644 .github/workflows/red-main.yml create mode 100644 scripts/red-main-cli.ts create mode 100644 scripts/red-main-coordinator.ts create mode 100644 scripts/red-main.ts create mode 100644 tests/red-main.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 25f3659603..429d9cedaa 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -41,6 +41,7 @@ jobs: run_browser: ${{ steps.reuse.outputs.run_browser }} run_layout: ${{ steps.reuse.outputs.run_layout }} reuse: ${{ steps.reuse.outputs.reuse }} + red_main_oid: ${{ steps.plan.outputs.red_main_oid }} steps: - uses: actions/checkout@v7 with: @@ -50,6 +51,13 @@ jobs: with: bun-version: "1.4.2" - run: bun install --frozen-lockfile + # Fail fast while main is red (#2942): hosted proof whose merge ref contains + # the recorded bad commit is refused, except declared fixes. Drafts run cheap gates only. + - name: Refuse doomed proof while main is red + if: github.event_name == 'pull_request' && !github.event.pull_request.draft + env: + PR_NUMBER: ${{ github.event.pull_request.number }} + run: bun scripts/red-main-cli.ts gate - name: Plan affected fast and local checks id: plan env: @@ -66,6 +74,14 @@ jobs: - name: Discover product scenario and assertion ownership if: steps.plan.outputs.cadence != 'draft' run: bun scripts/proof-inventory.ts + # Plan outputs and retention decisions are set before any metadata gate can + # fail, so a main push still runs its complete selected proof (#2942). + - name: Retain only validated equivalent automatic proof + id: reuse + env: + GH_TOKEN: ${{ github.token }} + PR_DRAFT: ${{ github.event.pull_request.draft }} + run: bun scripts/proof-reuse.ts - name: Lint, leakage and contribution workflow guards run: bun run lint - name: Env documentation matches its descriptors @@ -82,12 +98,6 @@ jobs: elif [ "$GITHUB_EVENT_NAME" = push ]; then bun scripts/check-changeset.ts "$BEFORE_SHA" fi - - name: Retain only validated equivalent automatic proof - id: reuse - env: - GH_TOKEN: ${{ github.token }} - PR_DRAFT: ${{ github.event.pull_request.draft }} - run: bun scripts/proof-reuse.ts - name: Retention ledger and diagnostics if: always() uses: actions/upload-artifact@v7 @@ -102,7 +112,7 @@ jobs: verify: # Packaging and verification are independent after cheap rejection gates. needs: changeset - if: needs.changeset.outputs.verify == 'true' + if: ${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && needs.changeset.outputs.verify == 'true' }} runs-on: ubuntu-24.04 timeout-minutes: 7 steps: @@ -123,6 +133,7 @@ jobs: BASE_SHA: ${{ github.event.pull_request.base.sha }} BEFORE_SHA: ${{ github.event.before }} HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + RED_MAIN_OID: ${{ needs.changeset.outputs.red_main_oid }} run: bun scripts/ci-plan.ts - name: Strict types and curated fast tests concurrently on this runner id: verify_proof @@ -142,7 +153,7 @@ jobs: pack: needs: changeset - if: needs.changeset.outputs.pack == 'true' + if: ${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && needs.changeset.outputs.pack == 'true' }} timeout-minutes: 5 runs-on: ubuntu-24.04 env: @@ -170,7 +181,7 @@ jobs: unit: needs: changeset - if: needs.changeset.outputs.unit == 'true' + if: ${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && needs.changeset.outputs.unit == 'true' }} runs-on: ubuntu-24.04 # Separate network setup from the unchanged proof budget (#2658). # 12 minutes setup + 30 minutes proof + 3 minutes for other steps. @@ -194,6 +205,7 @@ jobs: BASE_SHA: ${{ github.event.pull_request.base.sha }} BEFORE_SHA: ${{ github.event.before }} HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + RED_MAIN_OID: ${{ needs.changeset.outputs.red_main_oid }} run: bun scripts/ci-plan.ts - name: Real Chrome and offline Linux namespace prerequisites id: runtime_setup @@ -250,7 +262,7 @@ jobs: runtime: needs: changeset - if: needs.changeset.outputs.runtime == 'true' + if: ${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && needs.changeset.outputs.runtime == 'true' }} runs-on: ubuntu-24.04 # 12 minutes setup + unchanged 15 minutes proof + 3 minutes for other steps (#2658). timeout-minutes: 30 @@ -268,6 +280,7 @@ jobs: BASE_SHA: ${{ github.event.pull_request.base.sha }} BEFORE_SHA: ${{ github.event.before }} HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + RED_MAIN_OID: ${{ needs.changeset.outputs.red_main_oid }} run: bun scripts/ci-plan.ts - name: Real Chrome and offline Linux namespace prerequisites id: runtime_setup @@ -318,7 +331,7 @@ jobs: runtime_host: needs: changeset - if: needs.changeset.outputs.runtime_host == 'true' + if: ${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && needs.changeset.outputs.runtime_host == 'true' }} runs-on: ubuntu-24.04 # 12 minutes setup + unchanged 15 minutes proof + 3 minutes for other steps (#2658). timeout-minutes: 30 @@ -336,6 +349,7 @@ jobs: BASE_SHA: ${{ github.event.pull_request.base.sha }} BEFORE_SHA: ${{ github.event.before }} HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + RED_MAIN_OID: ${{ needs.changeset.outputs.red_main_oid }} run: bun scripts/ci-plan.ts - name: Real Chrome and offline Linux namespace prerequisites id: runtime_setup @@ -407,7 +421,7 @@ jobs: browser: needs: changeset - if: needs.changeset.outputs.browser == 'true' && needs.changeset.outputs.run_browser == 'true' + if: ${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && needs.changeset.outputs.browser == 'true' && needs.changeset.outputs.run_browser == 'true' }} runs-on: ubuntu-24.04 timeout-minutes: 20 strategy: @@ -428,6 +442,7 @@ jobs: BASE_SHA: ${{ github.event.pull_request.base.sha }} BEFORE_SHA: ${{ github.event.before }} HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + RED_MAIN_OID: ${{ needs.changeset.outputs.red_main_oid }} run: bun scripts/ci-plan.ts - name: Complete browser proof run: bun scripts/ci-proof.ts browser --shard=${{ matrix.shard }}/3 @@ -471,7 +486,7 @@ jobs: layout: needs: changeset - if: needs.changeset.outputs.layout == 'true' && needs.changeset.outputs.run_layout == 'true' + if: ${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && needs.changeset.outputs.layout == 'true' && needs.changeset.outputs.run_layout == 'true' }} runs-on: ubuntu-24.04 timeout-minutes: 25 strategy: @@ -492,6 +507,7 @@ jobs: BASE_SHA: ${{ github.event.pull_request.base.sha }} BEFORE_SHA: ${{ github.event.before }} HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + RED_MAIN_OID: ${{ needs.changeset.outputs.red_main_oid }} run: bun scripts/ci-plan.ts - name: Complete layout proof run: bun scripts/ci-proof.ts layout --shard=${{ matrix.shard }}/2 @@ -529,7 +545,7 @@ jobs: captures: needs: changeset - if: needs.changeset.outputs.captures == 'true' + if: ${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && needs.changeset.outputs.captures == 'true' }} runs-on: ubuntu-24.04 timeout-minutes: 20 steps: @@ -546,6 +562,7 @@ jobs: BASE_SHA: ${{ github.event.pull_request.base.sha }} BEFORE_SHA: ${{ github.event.before }} HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + RED_MAIN_OID: ${{ needs.changeset.outputs.red_main_oid }} run: bun scripts/ci-plan.ts - name: Complete captures proof run: bun scripts/ci-proof.ts captures @@ -581,7 +598,7 @@ jobs: endurance: needs: changeset - if: needs.changeset.outputs.endurance == 'true' + if: ${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && needs.changeset.outputs.endurance == 'true' }} runs-on: ubuntu-24.04 timeout-minutes: 20 steps: @@ -598,6 +615,7 @@ jobs: BASE_SHA: ${{ github.event.pull_request.base.sha }} BEFORE_SHA: ${{ github.event.before }} HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + RED_MAIN_OID: ${{ needs.changeset.outputs.red_main_oid }} run: bun scripts/ci-plan.ts - name: Complete endurance proof run: bun scripts/ci-proof.ts endurance diff --git a/.github/workflows/red-main-probe.yml b/.github/workflows/red-main-probe.yml new file mode 100644 index 0000000000..ecd3b26f85 --- /dev/null +++ b/.github/workflows/red-main-probe.yml @@ -0,0 +1,66 @@ +# 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. +name: red-main-probe +run-name: red-main probe ${{ inputs.purpose }} ${{ inputs.source_run }} ${{ inputs.sha }} + +on: + workflow_dispatch: + inputs: + purpose: + description: flake or bisect + required: true + type: choice + options: [flake, bisect] + source_run: + description: The main CI run whose failure is triaged + required: true + sha: + description: The commit to probe + required: true + tests: + description: JSON array of test files to rerun + required: true + +permissions: + contents: read + +jobs: + probe: + runs-on: ubuntu-24.04 + # 12 minutes setup + 30 minutes proof + 3 minutes for other steps, as unit proof. + timeout-minutes: 45 + steps: + - name: Validate dispatch identities + env: + SOURCE_RUN: ${{ inputs.source_run }} + PROBE_SHA: ${{ inputs.sha }} + run: | + [[ "$SOURCE_RUN" =~ ^[1-9][0-9]*$ ]] && [[ "$PROBE_SHA" =~ ^[a-f0-9]{40}$ ]] + - uses: actions/checkout@v7 + with: + ref: ${{ github.event.repository.default_branch }} + path: tooling + persist-credentials: false + - uses: actions/checkout@v7 + with: + ref: ${{ inputs.sha }} + path: target + persist-credentials: false + fetch-depth: 0 + - uses: oven-sh/setup-bun@v2 + with: + bun-version: "1.4.2" + - run: bun install --frozen-lockfile + working-directory: tooling + - run: bun install --frozen-lockfile --backend=copyfile + working-directory: target + - name: Real Chrome and offline Linux namespace prerequisites + timeout-minutes: 12 + working-directory: target + run: bash scripts/ci-runtime-setup.sh + - name: Rerun only the failing test files + timeout-minutes: 30 + env: + PROBE_TESTS: ${{ inputs.tests }} + run: bun tooling/scripts/red-main-cli.ts probe --target target diff --git a/.github/workflows/red-main.yml b/.github/workflows/red-main.yml new file mode 100644 index 0000000000..a5543048a3 --- /dev/null +++ b/.github/workflows/red-main.yml @@ -0,0 +1,52 @@ +# Red-main coordinator (#2942). Runs trusted default-branch tooling after every +# main CI run and every triage probe; candidate logs and artifacts are parsed as +# data, never executed. Writes only the shared coordination ref, incident and +# flake issues, PR reports, probe dispatches and cancellations of doomed PR proof. +name: red-main + +on: + workflow_run: + workflows: [CI, red-main-probe] + types: [completed] + +permissions: {} + +# One coordinator at a time: records and incident issues are never raced. +concurrency: + group: red-main-coordinator + cancel-in-progress: false + +jobs: + coordinate: + if: >- + (github.event.workflow_run.name == 'CI' && github.event.workflow_run.event == 'push' && + github.event.workflow_run.head_branch == 'main') || + (github.event.workflow_run.name == 'red-main-probe' && github.event.workflow_run.event == 'workflow_dispatch') + runs-on: ubuntu-24.04 + timeout-minutes: 20 + permissions: + contents: write # compare-and-swap push of the shared coordination ref + actions: write # cancel doomed PR runs, dispatch triage probes, read logs and artifacts + issues: write # one incident issue per record; flake issues + pull-requests: write # report squashes that landed while red + steps: + - uses: actions/checkout@v7 + with: + ref: ${{ github.event.repository.default_branch }} + fetch-depth: 0 + - uses: oven-sh/setup-bun@v2 + with: + bun-version: "1.4.2" + - run: bun install --frozen-lockfile + - name: Coordinate the red-main record + env: + GH_TOKEN: ${{ github.token }} + run: bun scripts/red-main-cli.ts coordinate + - name: Retain recorded incident events + if: always() + uses: actions/upload-artifact@v7 + with: + name: red-main-events + path: tmp/red-main-events/ + if-no-files-found: ignore + retention-days: 90 diff --git a/scripts/check-ci-workflows.ts b/scripts/check-ci-workflows.ts index 6cec99915b..d2d16380c6 100644 --- a/scripts/check-ci-workflows.ts +++ b/scripts/check-ci-workflows.ts @@ -55,7 +55,9 @@ export function workflowProblems(text: string, file: string): string[] { const job = workflow.jobs?.[name]; if (job?.needs !== "changeset") fail(`${name}: independent proof must depend only on metadata`); const selection = `needs.changeset.outputs.${name} == 'true'` + (["browser", "layout"].includes(name) ? ` && needs.changeset.outputs.run_${name} == 'true'` : ""); - if (job?.if !== selection) fail(`${name}: proof must use its explicit planner selection and validated retention`); + // Main pushes run selected proof even when the metadata job fails (#2942); + // PR proof still requires a successful metadata job. + if (job?.if !== `\${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && ${selection} }}`) fail(`${name}: proof must use its explicit planner selection and validated retention`); } const verify = workflow.jobs?.verify; const verifySteps = verify?.steps ?? []; @@ -124,10 +126,11 @@ export function checkCIWorkflows(root: string): string[] { const problems: string[] = []; const directory = join(root, ".github/workflows"); const files = existsSync(directory) ? readdirSync(directory).sort() : []; - const expected = ["ci.yml", "contract.yml", "project-sync.yml"]; + // The red-main coordinator and its triage probe are authoritative coordination (#2942). + const expected = ["ci.yml", "contract.yml", "project-sync.yml", "red-main.yml", "red-main-probe.yml"]; if (files.includes("publish-pages.yml")) expected.push("publish-pages.yml"); if (files.includes("ci-timings.yml")) expected.push("ci-timings.yml"); - if (JSON.stringify(files) !== JSON.stringify(expected.sort())) problems.push("GitHub must contain only authoritative CI, contract, project-sync and optional Pages/timing workflows"); + if (JSON.stringify(files) !== JSON.stringify(expected.sort())) problems.push("GitHub must contain only authoritative CI, contract, project-sync, red-main coordination and optional Pages/timing workflows"); const depot = join(root, ".depot/workflows"); if (existsSync(depot) && readdirSync(depot).some(file => /\.ya?ml$/.test(file))) problems.push("Active Depot CI workflow definitions must be removed"); for (const file of CI_WORKFLOWS) { diff --git a/scripts/ci-coordination.ts b/scripts/ci-coordination.ts index d965261006..20fbd2cc66 100644 --- a/scripts/ci-coordination.ts +++ b/scripts/ci-coordination.ts @@ -67,6 +67,8 @@ export function collectReservationHistory(repository: string, since: string): Re const commits = run(["rev-list", "--first-parent", remote]).split("\n"), rows: { source: string; state: any }[] = []; for (const source of commits) { const state = parseReservation(run(["show", `${source}:reservation.json`])); + // Red-main record writes (#2942) share this ref and leave reservation.json unchanged. + if (rows.length && JSON.stringify(rows.at(-1)!.state) === JSON.stringify(state)) { rows[rows.length - 1] = { source, state }; continue; } rows.push({ source, state }); // The protocol caps leases at one hour. Keep the preceding source record. // Server timestamps drive this bound; commit author clocks do not. diff --git a/scripts/ci-plan.ts b/scripts/ci-plan.ts index f8907b640d..dbd8ed911d 100644 --- a/scripts/ci-plan.ts +++ b/scripts/ci-plan.ts @@ -4,6 +4,8 @@ import { basename, dirname, join, relative, resolve } from "node:path"; import ts from "typescript"; import { closureSelects, discoverBrowserClosures, type BrowserClosures } from "./browser-input-closure"; import { addUnitImportConsumers, type UnitImportGraph } from "./unit-test-consumers"; +import { coordinationFiles, RESERVATION_REF } from "./integration-reservation"; +import { includeRedSet, type IncludedRedSet, type RedMainRecord } from "./red-main"; export interface Workspace { dir: string; @@ -144,6 +146,8 @@ export interface CheckPlan { unitTests?: string[]; // Complete proof categories, shared by hosted CI and opt-in full local checks. local: { fullTests: boolean; browser: boolean; layout: boolean; captures: boolean; runtime: boolean; endurance: boolean }; + /** Main pushes also prove the open red-main record's failures (#2942). */ + redMain?: IncludedRedSet; } export function workspaces(root: string): Workspace[] { @@ -436,18 +440,38 @@ export function changedFiles(root: string, base: string, head = "HEAD", mergeBas return [...new Set(paths)].sort(); } -export function planFromEnvironment(root: string, env: NodeJS.ProcessEnv): CheckPlan { +export function planFromEnvironment(root: string, env: NodeJS.ProcessEnv, redMain: RedMainRecord | null = null): CheckPlan { if (["api", "schedule", "workflow_dispatch"].includes(env.GITHUB_EVENT_NAME ?? "")) return planChecks(["package.json"], workspaces(root), root); const pr = env.GITHUB_EVENT_NAME === "pull_request"; const base = pr ? env.BASE_SHA : env.BEFORE_SHA; if (!base || !env.HEAD_SHA) throw new Error("CI requires BASE_SHA/BEFORE_SHA and HEAD_SHA"); - return planChecks(changedFiles(root, base, env.HEAD_SHA, pr), workspaces(root), root, pr); + const packages = workspaces(root), plan = planChecks(changedFiles(root, base, env.HEAD_SHA, pr), packages, root, pr); + return env.GITHUB_EVENT_NAME === "push" ? includeRedSet(plan, redMain, changed => planChecks(changed, packages, root, false)) : plan; +} + +/** + * Every job of one main run reads the same coordination snapshot: the + * metadata job resolves it once and later jobs receive its object ID. + */ +export function redMainSnapshot(root: string, requested: string | undefined): { oid: string; record: RedMainRecord | null } { + const attempt = (args: string[]) => { + for (let index = 0; ; index++) { + try { return git(root, args).trim(); } catch (error) { if (index === 2) throw error; Bun.sleepSync(1000 * 2 ** index); } + } + }; + let oid = requested; + if (!oid) oid = attempt(["ls-remote", "--refs", "origin", RESERVATION_REF]).split(/\s+/)[0] || "none"; + if (oid === "none") return { oid, record: null }; + if (!/^[a-f0-9]{40}$/.test(oid)) throw new Error("Invalid red-main coordination snapshot"); + attempt(["fetch", "--no-tags", "origin", oid]); + return { oid, record: coordinationFiles(git(root, ["ls-tree", oid]), name => git(root, ["show", `${oid}:${name}`])).redMain }; } if (import.meta.main) { try { const root = resolve(import.meta.dir, ".."); - const plan = planFromEnvironment(root, process.env); + const red = process.env.GITHUB_EVENT_NAME === "push" ? redMainSnapshot(root, process.env.RED_MAIN_OID) : null; + const plan = planFromEnvironment(root, process.env, red?.record ?? null); if (process.env.GITHUB_ACTIONS === "true" && !process.env.GITHUB_EVENT_PATH) throw new Error("Hosted proof requires GITHUB_EVENT_PATH"); // Standalone planner diagnostics preserve complete selection; only an actual // event requests hosted confirmation, enforced again by the final gate. @@ -459,12 +483,14 @@ if (import.meta.main) { const selections = proofSelections(plan, draft); if (process.env.GITHUB_OUTPUT) appendFileSync(process.env.GITHUB_OUTPUT, `unit_shards=${JSON.stringify(unitShards(plan))}\n` + - `cadence=${plan.cadence ?? "diagnostic"}\n` + Object.entries(selections).map(([name, selected]) => `${name}=${selected}\n`).join("")); + `cadence=${plan.cadence ?? "diagnostic"}\n` + `red_main_oid=${red?.oid ?? ""}\n` + Object.entries(selections).map(([name, selected]) => `${name}=${selected}\n`).join("")); console.log(JSON.stringify({ ...plan, draft, event: event && { name: process.env.GITHUB_EVENT_NAME, action: event.action, head: event.pull_request?.head?.sha ?? process.env.GITHUB_SHA, base: event.pull_request?.base?.sha ?? event.before, } }, null, 2)); + // The coordinator clears a record only from a green run that printed it here. + if (plan.redMain) console.log(`BRAIN_RED_MAIN_INCLUDED ${JSON.stringify(plan.redMain)}`); if (event) console.log(`BRAIN_TIMING_CONTEXT ${JSON.stringify({ cadence: plan.cadence, global: plan.global, head: event.pull_request?.head?.sha ?? process.env.GITHUB_SHA })}`); } catch (error) { console.error(error); process.exit(1); } diff --git a/scripts/integrate.ts b/scripts/integrate.ts index d84eec0d59..7ce6539951 100644 --- a/scripts/integrate.ts +++ b/scripts/integrate.ts @@ -4,6 +4,7 @@ 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, type RedMainRecord } from "./red-main"; import type { API } from "./proof-reuse"; async function gh(...args: string[]): Promise { @@ -53,6 +54,21 @@ if (import.meta.main) { } throw new Error("Bounded acquisition exhausted"); } + /** Cooperative merge blocking while red (#2942): only a declared fix proceeds. */ + function refuseWhileRed(pr: number) { + const open = store!.read().redMain.open; + if (open && !open.fixes.includes(pr)) throw new Error(`main red at ${open.firstBad}, ${open.incident ? `incident #${open.incident}` : "incident pending"}; only a declared fix may confirm or merge (bun scripts/integrate.ts declare-fix )`); + } + async function changeRedMain(update: (record: RedMainRecord, now: number) => RedMainRecord) { + for (let attempt = 0; attempt < 3; attempt++) { + const snapshot = store!.read(), record = update(snapshot.redMain, await clock()); + if (record === snapshot.redMain) return record; + if (scanText("coordination", JSON.stringify(record)).length) throw new Error("Public coordination state failed the leakage gate"); + if (store!.publishRedMain(snapshot, record)) return record; + await Bun.sleep(100 * 2 ** attempt); + } + throw new Error("Concurrent coordination update; bounded retries exhausted"); + } function heartbeat() { timer = setInterval(() => { pending = pending.then(async () => { if (!lost) try { await renew(); } catch (error) { lost = error; } }); return pending; }, RENEW_MS); } @@ -79,6 +95,7 @@ if (import.meta.main) { await milestones(desired.pr, issueRefs); await stopHeartbeat(); if (lost) throw lost; + refuseWhileRed(desired.pr); if (!sameCandidate(await candidate(desired.pr), desired)) throw new Error("Candidate changed before merge"); assertLease(store!.read().state, own.id, actor, desired, await clock()); await gh("pr", "merge", String(desired.pr), "--repo", repository, "--squash", "--match-head-commit", desired.head); @@ -109,7 +126,16 @@ if (import.meta.main) { store = new GitReservationStore(process.cwd()); const remote = store.git(["remote", "get-url", "origin"]).replace(/^git@github.com:/, "https://github.com/").replace(/\.git$/, ""); if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repository) || remote !== `https://github.com/${repository}`) throw new Error("Authenticated repository and origin differ"); - if (command === "inspect") { + if (command === "main-status") { + if (target !== undefined && target !== "--json") throw new Error("usage: bun scripts/integrate.ts main-status [--json]"); + const snapshot = store.read(); + console.log(JSON.stringify({ red: snapshot.redMain.open !== null, source: snapshot.oid, record: snapshot.redMain })); + } else if (command === "declare-fix") { + if (!/^[1-9]\d*$/.test(target ?? "") || !Number.isSafeInteger(Number(target))) throw new Error("A PR number is required"); + const live = await api.json(`pulls/${target}`); + if (live.state !== "open" || live.base?.ref !== "main" || live.base?.repo?.full_name !== repository) throw new Error("Only an open PR against main can be declared a red-main fix"); + console.log(JSON.stringify(await changeRedMain((record, now) => declareFix(record, Number(target), now)))); + } else if (command === "inspect") { const snapshot = store.read(), now = await clock(); console.log(JSON.stringify({ ...snapshot, live: liveLease(snapshot.state.active, now), serverTime: now })); } else if (command === "revoke") { @@ -128,6 +154,7 @@ 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)); + refuseWhileRed(desired.pr); if (command === "merge") { const lease = values.get("--lease"); if (!lease) throw new Error("Explicit --lease required"); @@ -162,7 +189,7 @@ if (import.meta.main) { if (lost) throw lost; } } - } else throw new Error("usage: bun scripts/integrate.ts inspect | 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,...] | renew/release | revoke "); } catch (error) { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1; } finally { diff --git a/scripts/integration-reservation.ts b/scripts/integration-reservation.ts index d5716406c6..27b05e2338 100644 --- a/scripts/integration-reservation.ts +++ b/scripts/integration-reservation.ts @@ -1,5 +1,6 @@ /** Cooperative integration ownership: remote Git CAS, never a branch lock. */ import { randomBytes } from "node:crypto"; +import { emptyRedMain, parseRedMain, RED_MAIN_FILE, type RedMainRecord } from "./red-main"; export const RESERVATION_REF = "refs/heads/brain-integration-reservation"; export const LEASE_MS = 5 * 60_000, RENEW_MS = 60_000, MAX_MS = 60 * 60_000; @@ -9,7 +10,8 @@ export interface ReservationState { version: 1; updated: number; active: Lease | null; last: { action: "acquire" | "renew" | "release" | "revoke"; actor: number; at: number; previous: Lease | null; reason?: string } | null; } -export interface Snapshot { oid: string | null; state: ReservationState; } +/** One ref commit holds both coordination files; every write preserves the other one. */ +export interface Snapshot { oid: string | null; state: ReservationState; redMain?: RedMainRecord; } export type Operation = { kind: "acquire"; candidate: Candidate; id?: string } | { kind: "renew"; id: string } | { kind: "release"; id: string } | { kind: "revoke"; reason: string; maintainer: boolean }; const hash = (value: unknown): value is string => typeof value === "string" && /^[a-f0-9]{40}$/.test(value); @@ -94,19 +96,25 @@ export class GitReservationStore { if (!hash(oid) || ref !== this.ref || extra.length) throw new Error("Invalid remote reservation ref"); return oid; } - read(): Snapshot { + read(): Snapshot & { redMain: RedMainRecord } { const oid = this.remoteOid(); - if (!oid) return { oid, state: emptyReservation() }; + if (!oid) return { oid, state: emptyReservation(), redMain: emptyRedMain() }; this.git(["fetch", "--no-tags", this.remote, oid]); - const tree = this.git(["ls-tree", oid]); - if (!/^100644 blob [a-f0-9]{40}\treservation\.json$/.test(tree)) throw new Error("Unknown shared coordination tree"); - return { oid, state: parseReservation(this.git(["show", `${oid}:reservation.json`])) }; + return { oid, ...coordinationFiles(this.git(["ls-tree", oid]), name => this.git(["show", `${oid}:${name}`])) }; } publish(snapshot: Snapshot, state: ReservationState): boolean { - const content = JSON.stringify(parseReservation(JSON.stringify(state))) + "\n"; - const blob = this.git(["hash-object", "-w", "--stdin"], content); - const tree = this.git(["mktree"], `100644 blob ${blob}\treservation.json\n`); - const oid = this.git(["commit-tree", tree, ...(snapshot.oid ? ["-p", snapshot.oid] : []), "-m", `integration: ${state.last?.action ?? "state"}`]); + return this.write(snapshot, parseReservation(JSON.stringify(state)), snapshot.redMain ?? emptyRedMain(), `integration: ${state.last?.action ?? "state"}`); + } + publishRedMain(snapshot: Snapshot, record: RedMainRecord): boolean { + return this.write(snapshot, snapshot.state, parseRedMain(JSON.stringify(record)), `red-main: ${record.last?.action ?? "state"}`); + } + private write(snapshot: Snapshot, state: ReservationState, redMain: RedMainRecord, message: string): boolean { + const blob = (value: unknown) => this.git(["hash-object", "-w", "--stdin"], JSON.stringify(value) + "\n"); + const entries = [`100644 blob ${blob(state)}\treservation.json`]; + // An untouched red-main record is not materialized, so reservation-only history keeps its shape. + if (redMain.last !== null) entries.unshift(`100644 blob ${blob(redMain)}\t${RED_MAIN_FILE}`); + const tree = this.git(["mktree"], entries.join("\n") + "\n"); + const oid = this.git(["commit-tree", tree, ...(snapshot.oid ? ["-p", snapshot.oid] : []), "-m", message]); try { this.git(["push", "--porcelain", `--force-with-lease=${this.ref}:${snapshot.oid ?? ""}`, this.remote, `${oid}:${this.ref}`]); return true; @@ -116,3 +124,14 @@ export class GitReservationStore { } } } + +/** Accepts exactly the known coordination files; anything else fails closed. */ +export function coordinationFiles(tree: string, show: (name: string) => string): { state: ReservationState; redMain: RedMainRecord } { + const names = tree.split("\n").filter(Boolean).map(line => { + const match = /^100644 blob [a-f0-9]{40}\t(reservation\.json|red-main\.json)$/.exec(line); + if (!match) throw new Error("Unknown shared coordination tree"); + return match[1]!; + }); + if (!names.includes("reservation.json") || new Set(names).size !== names.length) throw new Error("Unknown shared coordination tree"); + return { state: parseReservation(show("reservation.json")), redMain: names.includes(RED_MAIN_FILE) ? parseRedMain(show(RED_MAIN_FILE)) : emptyRedMain() }; +} diff --git a/scripts/red-main-cli.ts b/scripts/red-main-cli.ts new file mode 100644 index 0000000000..8a855a6715 --- /dev/null +++ b/scripts/red-main-cli.ts @@ -0,0 +1,122 @@ +/** + * Red-main entry points (#2942): + * gate first step of PR proof: refuse doomed hosted proof while main is red + * coordinate workflow_run handler for main CI and triage probes + * probe rerun only the named test files at one SHA (triage, never proof) + */ +import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { changedFiles, planChecks, proofSelections, redMainSnapshot, workspaces } from "./ci-plan"; +import { GitReservationStore, reservationServerTime, type Snapshot as StoreSnapshot } from "./integration-reservation"; +import { coordinate, type CoordinatorIO, type Snapshot, type WorkflowRun } from "./red-main-coordinator"; +import { gateDecision, type Category } from "./red-main"; + +// Hosted jobs run from the checkout root; fixtures run from their own repository. +const root = process.cwd(); + +function run(argv: string[], cwd = root, input?: string): { code: number; out: string; err: string } { + const result = Bun.spawnSync(argv, { cwd, stdout: "pipe", stderr: "pipe", stdin: input === undefined ? "ignore" : new TextEncoder().encode(input) }); + return { code: result.exitCode ?? 1, out: new TextDecoder().decode(result.stdout), err: new TextDecoder().decode(result.stderr) }; +} +function must(argv: string[], cwd = root, input?: string): string { + const result = run(argv, cwd, input); + if (result.code !== 0) throw new Error(`${argv.slice(0, 3).join(" ")} failed: ${result.err.trim()}`); + return result.out.trim(); +} + +/** Ancestry with an on-demand fetch; anything other than a definite answer fails closed. */ +export function isAncestor(ancestor: string, descendant: string, cwd = root): boolean { + for (const sha of [ancestor, descendant]) if (sha !== "HEAD" && run(["git", "cat-file", "-e", `${sha}^{commit}`], cwd).code !== 0) must(["git", "fetch", "--no-tags", "origin", sha], cwd); + const result = run(["git", "merge-base", "--is-ancestor", ancestor, descendant], cwd); + if (result.code === 0 || result.code === 1) return result.code === 0; + throw new Error(`Cannot determine ancestry: ${result.err.trim()}`); +} + +/** Whether a failure belongs to the squash's own affected closure; null when the graph cannot say. */ +export function inClosure(sha: string, failure: { test: string | null; category: Category }): boolean | null { + try { + const parent = must(["git", "rev-parse", `${sha}^`]); + const plan = planChecks(changedFiles(root, parent, sha, false), workspaces(root), root, true); + if (plan.global) return null; + if (failure.test) { + if (plan.unitTests) return plan.unitTests.includes(failure.test); + const dir = /^packages\/([^/]+)\//.exec(failure.test)?.[1]; + return dir ? plan.local.fullTests && plan.affected.includes(dir) : null; + } + if (failure.category === "changeset") return true; + return proofSelections({ ...plan, cadence: "integrated" })[failure.category] ?? null; + } catch { return null; } +} + +async function gh(args: string[], input?: string): Promise { + const child = Bun.spawn(["gh", ...args], { stdout: "pipe", stderr: "pipe", stdin: input === undefined ? "ignore" : new TextEncoder().encode(input) }); + const [code, out, err] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); + if (code !== 0) throw new Error(`gh ${args.slice(0, 2).join(" ")} failed: ${err.trim()}`); + return out; +} + +function liveIO(repository: string): CoordinatorIO { + const store = new GitReservationStore(root); + return { + repository, + async json(path) { return JSON.parse(await gh(["api", path])); }, + async write(method, path, body) { + const out = await gh(["api", "-X", method, path, ...(body === undefined ? [] : ["--input", "-"])], body === undefined ? undefined : JSON.stringify(body)); + return out.trim() ? JSON.parse(out) : {}; + }, + async now() { return reservationServerTime(await gh(["api", "--include", "-H", "Cache-Control: no-cache", `repos/${repository}/git/ref/heads/main?red_main_clock=${crypto.randomUUID()}`])); }, + read() { return store.read(); }, + publish(snapshot, record) { return store.publishRedMain(snapshot as StoreSnapshot, record); }, + async artifactFiles(runId, name, file) { + const listing = JSON.parse(await gh(["api", `repos/${repository}/actions/runs/${runId}/artifacts?per_page=100`])); + if (!(listing.artifacts ?? []).some((artifact: { name: string; expired: boolean }) => artifact.name === name && !artifact.expired)) return []; + const dir = mkdtempSync(join(tmpdir(), "red-main-artifact-")); + try { + await gh(["run", "download", String(runId), "--repo", repository, "--name", name, "--dir", dir]); + const found: string[] = []; + const walk = (path: string) => { for (const entry of readdirSync(path)) { const full = join(path, entry); if (statSync(full).isDirectory()) walk(full); else if (entry === file) found.push(readFileSync(full, "utf8")); } }; + walk(dir); + return found; + } finally { rmSync(dir, { recursive: true, force: true }); } + }, + async log(job) { return gh(["api", "--allow-escape-sequences", `repos/${repository}/actions/jobs/${job}/logs`]); }, + inClosure, + range(since, until) { return must(["git", "rev-list", "--first-parent", "--reverse", `${since}..${until}`]).split("\n").filter(Boolean); }, + isAncestor: (a, b) => isAncestor(a, b), + commitTime(sha) { return Number(must(["git", "show", "-s", "--format=%ct", sha])) * 1000; }, + async recordEvent(event) { + const dir = join(root, "tmp/red-main-events"), file = join(dir, `input-${crypto.randomUUID()}.json`); + await Bun.write(file, JSON.stringify(event)); + must([process.execPath, "scripts/ci-timings.ts", "record", "--repo", repository, "--event", file, "--out", dir]); + rmSync(file); + }, + print(line) { console.log(line); }, + }; +} + +if (import.meta.main) { + try { + const [command, ...rest] = process.argv.slice(2); + if (command === "gate") { + const pr = Number(process.env.PR_NUMBER); + if (!Number.isSafeInteger(pr) || pr <= 0) throw new Error("PR_NUMBER is required"); + const { record } = redMainSnapshot(root, undefined); + const decision = record ? gateDecision({ record, pr, contains: sha => isAncestor(sha, "HEAD") }) : { refuse: false, message: "main green: no coordination record" }; + if (decision.refuse) { console.error(`::error::${decision.message}`); console.error(decision.message); process.exit(1); } + console.log(decision.message); + } else if (command === "coordinate") { + const event = JSON.parse(readFileSync(process.env.GITHUB_EVENT_PATH!, "utf8")); + const repository = process.env.GITHUB_REPOSITORY!; + if (!event.workflow_run || !/^[\w.-]+\/[\w.-]+$/.test(repository ?? "")) throw new Error("A workflow_run event and repository are required"); + 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; + 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); + } else throw new Error("usage: bun scripts/red-main-cli.ts gate | coordinate | 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 new file mode 100644 index 0000000000..10d1f5c620 --- /dev/null +++ b/scripts/red-main-coordinator.ts @@ -0,0 +1,281 @@ +/** + * Red-main coordinator (#2942): runs on every completed main CI run and every + * triage probe. It records a red main in the shared coordination ref, files one + * incident issue, cancels doomed PR proof and reports squashes that land while red. + * A rerun is only a triage probe: it never turns proof green or makes anything mergeable. + */ +import { scanText } from "./check-leakage"; +import { addSuspect, attachIncident, CATEGORIES, classifyFailure, clearRed, coversRedSet, failureKey, junitFailures, openRed, refineFirstBad, + reportLanded, settleSuspect, type Category, type FailureEvidence, type IncludedRedSet, type RedFailure, type RedMainRecord, type Signature } from "./red-main"; + +export const PROBE_WORKFLOW = "red-main-probe.yml"; +/** Bisect only bounded ranges; a wider range keeps the conservative first red. */ +export const MAX_BISECT = 10; +const SETUP_STEP = /prerequisites|environment setup/i; + +export interface WorkflowRun { + id: number; name: string; event: string; head_branch: string; head_sha: string; status: string; conclusion: string | null; + run_attempt: number; display_title: string; created_at: string; pull_requests?: { number: number }[]; +} +export interface Job { id: number; name: string; conclusion: string | null; steps?: { name: string; conclusion: string | null }[]; } +export interface Snapshot { oid: string | null; redMain: RedMainRecord; } +export interface CoordinatorIO { + repository: string; + json(path: string): Promise; + write(method: "POST" | "PATCH", path: string, body?: unknown): Promise; + /** Authoritative GitHub server time. */ + now(): Promise; + read(): Snapshot; + publish(snapshot: Snapshot, record: RedMainRecord): boolean; + /** Text of every named file inside the run's artifacts matching the prefix. */ + artifactFiles(run: number, prefix: string, file: string): Promise; + log(job: number): Promise; + /** Whether a failing test or category belongs to the commit's own affected closure; null when unknown. */ + inClosure(sha: string, failure: { test: string | null; category: Category }): boolean | null; + /** First-parent main commits after `since` (exclusive) up to `until` (inclusive), oldest first. */ + range(since: string, until: string): string[]; + isAncestor(ancestor: string, descendant: string): boolean; + commitTime(sha: string): number; + recordEvent(event: { kind: "incident"; pr: number; run: number; evidence: string }): Promise; + print(line: string): void; +} + +const short = (sha: string) => sha.slice(0, 12); +const issueUrl = (io: CoordinatorIO, number: number) => `https://github.com/${io.repository}/issues/${number}`; +const runUrl = (io: CoordinatorIO, run: number) => `https://github.com/${io.repository}/actions/runs/${run}`; +/** Keyed by the record's opening run: bisect may later move its first bad SHA. */ +export const incidentMarker = (run: number) => ``; +export const flakeMarker = (key: string) => ``; + +/** Retries a compare-and-swap update of the shared record; an unchanged result writes nothing. */ +export async function updateRecord(io: CoordinatorIO, update: (record: RedMainRecord, now: number) => RedMainRecord): Promise<{ before: RedMainRecord; after: RedMainRecord }> { + for (let attempt = 0; attempt < 5; attempt++) { + const snapshot = io.read(), after = update(snapshot.redMain, await io.now()); + if (after === snapshot.redMain) return { before: snapshot.redMain, after }; + if (scanText("coordination", JSON.stringify(after)).length) throw new Error("Public coordination state failed the leakage gate"); + if (io.publish(snapshot, after)) return { before: snapshot.redMain, after }; + await Bun.sleep(200 * 2 ** attempt); + } + throw new Error("Concurrent red-main update; bounded retries exhausted"); +} + +export function jobCategory(name: string): Category | null { + const base = name.split(" ")[0]!; + return CATEGORIES.includes(base as Category) ? base as Category : null; +} + +/** Failures of one completed main run, with their deterministic estimator evidence. */ +export async function runFailures(io: CoordinatorIO, run: WorkflowRun, jobs: Job[]): Promise { + const out: FailureEvidence[] = []; + for (const job of jobs.filter(job => job.conclusion === "failure" || job.conclusion === "timed_out")) { + const category = jobCategory(job.name); + if (!category) continue; + const setup = job.steps?.some(step => SETUP_STEP.test(step.name) && step.conclusion === "failure"); + const fallback: Signature = setup ? "setup" : job.conclusion === "timed_out" ? "timeout" : "unknown"; + if (category === "unit" && !setup) { + const shard = /\((\d+)\)/.exec(job.name)?.[1]; + const reports = shard ? await io.artifactFiles(run.id, `unit-proof-${shard}`, "unit-report.xml") : []; + const tests = reports.flatMap(junitFailures); + if (tests.length) { + for (const { test, signature } of tests) out.push({ test, category, signature, inClosure: io.inClosure(run.head_sha, { test, category }) }); + continue; + } + } + if (!out.some(f => f.test === null && f.category === category)) out.push({ test: null, category, signature: fallback, inClosure: io.inClosure(run.head_sha, { test: null, category }) }); + } + return out; +} + +/** Parses the exact record snapshot a main run printed as included in its selection. */ +export function includedRedSet(log: string): IncludedRedSet | null { + const line = log.split("\n").find(entry => entry.includes("BRAIN_RED_MAIN_INCLUDED ")); + if (!line) return null; + try { return JSON.parse(line.slice(line.indexOf("BRAIN_RED_MAIN_INCLUDED ") + 24)); } catch { return null; } +} + +async function search(io: CoordinatorIO, query: string): Promise<{ number: number; title: string; body?: string }[]> { + const result = await io.json(`search/issues?q=${encodeURIComponent(`repo:${io.repository} is:issue is:open ${query}`)}&per_page=20`); + return result.items ?? []; +} + +/** Exactly one incident issue per record: the record and a body marker both deduplicate. */ +export async function ensureIncident(io: CoordinatorIO, record: RedMainRecord): Promise { + const open = record.open; + if (!open || open.incident !== null) return record; + const marker = incidentMarker(open.run); + let number = (await search(io, `"brain-red-main: run ${open.run}" in:body`)).find(issue => issue.body?.includes(marker))?.number; + if (!number) { + const related = new Set(); + for (const failure of open.failures.filter(f => f.test)) for (const issue of await search(io, `"${failure.test}" in:title,body`)) related.add(issue.number); + const lines = [ + marker, + `Main is red at \`${open.firstBad}\` (first failing main run: ${runUrl(io, open.run)}).`, + "", + "Failing tests and categories:", + ...open.failures.map(f => `- \`${f.test ?? f.category}\` (${f.category}; ${f.reasons.join(", ")}; run ${runUrl(io, f.run)})`), + "", + "Hosted proof whose merge ref contains this commit is refused or cancelled, and `integrate.ts` refuses ordinary confirmation and merges, until a main run that includes this failing set is green. Declare a fix PR with `bun scripts/integrate.ts declare-fix `; the first confirmed fix wins.", + ...(related.size ? ["", `Possibly related open issues: ${[...related].sort((a, b) => a - b).map(n => `#${n}`).join(", ")}.`] : []), + ]; + const issue = await io.write("POST", `repos/${io.repository}/issues`, { + title: `ci: main red at ${short(open.firstBad)}: ${open.failures[0]!.test ?? open.failures[0]!.category}`, + body: lines.join("\n"), labels: ["type: fix", "area: ci"] }); + number = issue.number as number; + } + const { after } = await updateRecord(io, (current, now) => current.open?.run === open.run && current.open.incident === null ? attachIncident(current, number!, now) : current); + return after; +} + +/** Files or updates the issue of a suspected flake, whatever the probe result. */ +export async function noteFlake(io: CoordinatorIO, key: string, text: string, existing: number | null): Promise { + const marker = flakeMarker(key); + const number = existing ?? (await search(io, `"brain-flake: ${key}" in:body`)).find(issue => issue.body?.includes(marker))?.number; + if (number) { await io.write("POST", `repos/${io.repository}/issues/${number}/comments`, { body: text }); return number; } + const issue = await io.write("POST", `repos/${io.repository}/issues`, { + title: `test: suspected flake in ${key}`, labels: ["type: test", "area: ci"], + body: `${marker}\nThe red-main coordinator suspected a flake in \`${key}\`. A rerun is only a triage probe: it never turns proof green. A second suspected flake within the window is treated as a real failure.\n\n${text}` }); + return issue.number as number; +} + +/** Cancels in-progress PR proof created after the bad commit landed, except declared fixes. */ +export async function cancelDoomed(io: CoordinatorIO, record: RedMainRecord): Promise { + const open = record.open; + if (!open) return []; + const landed = io.commitTime(open.firstBad), cancelled: number[] = []; + for (const status of ["queued", "in_progress"]) { + const runs = await io.json(`repos/${io.repository}/actions/workflows/ci.yml/runs?event=pull_request&status=${status}&per_page=100`); + for (const run of (runs.workflow_runs ?? []) as WorkflowRun[]) { + const prs = (run.pull_requests ?? []).map(pr => pr.number); + if (!prs.length || prs.some(pr => open.fixes.includes(pr)) || Date.parse(run.created_at) < landed) continue; + await io.write("POST", `repos/${io.repository}/actions/runs/${run.id}/cancel`); + cancelled.push(run.id); + } + } + return cancelled; +} + +/** Reports a non-fix squash that landed on main while the record was open. */ +export async function detectLanded(io: CoordinatorIO, record: RedMainRecord, run: WorkflowRun): Promise { + const open = record.open, sha = run.head_sha; + if (!open || sha === open.firstBad || open.reported.includes(sha) || !io.isAncestor(open.firstBad, sha)) return false; + const pulls = await io.json(`repos/${io.repository}/commits/${sha}/pulls`); + const pr = (pulls as { number: number; merged_at: string | null }[]).find(p => p.merged_at)?.number; + if (!pr || open.fixes.includes(pr)) return false; + const incident = open.incident ? `incident #${open.incident}` : "the open red-main record"; + await io.write("POST", `repos/${io.repository}/issues/${pr}/comments`, { body: `This PR's squash \`${sha}\` landed on main while main was red at \`${open.firstBad}\` (${incident}) without being a declared fix. Merge blocking while red is cooperative; this report is the detection.` }); + if (open.incident) await io.write("POST", `repos/${io.repository}/issues/${open.incident}/comments`, { body: `Squash \`${sha}\` from #${pr} landed while red without being a declared fix (main run ${runUrl(io, run.id)}).` }); + await io.recordEvent({ kind: "incident", pr, run: run.id, evidence: open.incident ? issueUrl(io, open.incident) : runUrl(io, run.id) }); + await updateRecord(io, (current, now) => reportLanded(current, sha, now)); + return true; +} + +export async function dispatchProbe(io: CoordinatorIO, purpose: "flake" | "bisect", source: number, sha: string, tests: string[]) { + await io.write("POST", `repos/${io.repository}/actions/workflows/${PROBE_WORKFLOW}/dispatches`, { + ref: "main", inputs: { purpose, source_run: String(source), sha, tests: JSON.stringify(tests) } }); +} + +/** Last earlier main run where the failing category's job actually ran green. */ +async function lastGreen(io: CoordinatorIO, run: WorkflowRun, category: Category): Promise { + const runs = await io.json(`repos/${io.repository}/actions/workflows/ci.yml/runs?event=push&branch=main&status=completed&per_page=30`); + for (const earlier of ((runs.workflow_runs ?? []) as WorkflowRun[]).filter(r => r.id !== run.id && r.head_sha !== run.head_sha && io.isAncestor(r.head_sha, run.head_sha))) { + const jobs: Job[] = (await io.json(`repos/${io.repository}/actions/runs/${earlier.id}/attempts/${earlier.run_attempt}/jobs?per_page=100`)).jobs ?? []; + if (jobs.some(job => jobCategory(job.name) === category && job.conclusion === "success") && + !jobs.some(job => jobCategory(job.name) === category && job.conclusion !== "success" && job.conclusion !== "skipped")) return earlier.head_sha; + } + return null; +} + +async function handleMainRun(io: CoordinatorIO, run: WorkflowRun) { + const jobs: Job[] = (await io.json(`repos/${io.repository}/actions/runs/${run.id}/attempts/${run.run_attempt}/jobs?per_page=100`)).jobs ?? []; + const start = io.read().redMain; + // Detection uses the record as it stood before this run's own result. + if (start.open) await detectLanded(io, start, run); + if (run.conclusion === "success") { + const metadata = jobs.find(job => job.name === "changeset"); + const included = metadata ? includedRedSet(await io.log(metadata.id)) : null; + if (start.open && coversRedSet(start, included)) { + const { after } = await updateRecord(io, (current, now) => coversRedSet(current, included) + ? clearRed(current, { id: run.id, conclusion: "success", included }, now) : current); + if (!after.open && start.open.incident) await io.write("POST", `repos/${io.repository}/issues/${start.open.incident}/comments`, { body: `Main is green again: run ${runUrl(io, run.id)} at \`${run.head_sha}\` included the failing set and passed. The red-main record is cleared.` }); + io.print(`cleared red-main record ${start.open.firstBad}`); + } + return; + } + if (run.conclusion !== "failure") return; + const evidence = await runFailures(io, run, jobs), now = await io.now(); + const real: RedFailure[] = [], suspects: FailureEvidence[] = []; + for (const failure of evidence) { + const verdict = classifyFailure(failure, io.read().redMain, now); + io.print(`BRAIN_FLAKE_ESTIMATE ${JSON.stringify({ test: failure.test, category: failure.category, ...verdict })}`); + if (verdict.verdict === "real") real.push({ test: failure.test, category: failure.category, verdict: "real", reasons: verdict.reasons, run: run.id, sha: run.head_sha }); + else suspects.push(failure); + } + for (const suspect of suspects) { + const key = failureKey(suspect); + await updateRecord(io, (current, at) => addSuspect(current, { test: key, category: suspect.category, run: run.id, sha: run.head_sha, at }, at)); + const issue = await noteFlake(io, key, `Suspected flake in main run ${runUrl(io, run.id)} at \`${run.head_sha}\` (${suspect.signature} signature, ${suspect.inClosure === false ? "outside" : "inside"} the commit's affected closure).${suspect.test ? " A triage probe reruns only this test file at that SHA." : " No single-file probe exists for this category; the next suspected flake escalates to real."}`, null); + await updateRecord(io, (current, at) => settleSuspect(current, { test: key, run: run.id }, { issue, ...(suspect.test ? {} : { probe: "unavailable" }) }, at)); + } + const probeTests = suspects.flatMap(s => s.test ? [s.test] : []); + if (probeTests.length) await dispatchProbe(io, "flake", run.id, run.head_sha, probeTests); + if (!real.length) return; + // First bad: the first red after the last run where the failing category actually ran green. + // With several failing categories, the oldest of their last greens bounds the range; + // a category with no green run in the window keeps the conservative current SHA. + let firstBad = run.head_sha, range: string[] = []; + const greens = await Promise.all([...new Set(real.map(f => f.category))].map(category => lastGreen(io, run, category))); + if (greens.length && greens.every(green => green !== null)) { + const oldest = greens.find(green => greens.every(other => other === green || io.isAncestor(green!, other!)))!; + range = oldest ? io.range(oldest, run.head_sha) : []; + if (range.length) firstBad = range[0]!; + } + const { after } = await updateRecord(io, (current, at) => openRed(current, { firstBad, run: run.id, failures: real }, at)); + const withIncident = await ensureIncident(io, after); + const tests = real.flatMap(f => f.test ? [f.test] : []); + // Probe each candidate commit with only the failing test files. + if (range.length > 1 && range.length <= MAX_BISECT && tests.length) for (const sha of range) await dispatchProbe(io, "bisect", run.id, sha, tests); + const cancelled = await cancelDoomed(io, withIncident); + 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. */ +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; +} + +async function handleProbe(io: CoordinatorIO, run: WorkflowRun) { + const identity = probeIdentity(run.display_title); + if (!identity || run.status !== "completed") return; + const failed = run.conclusion === "failure", result = failed ? "failed" : run.conclusion === "success" ? "passed" : "unavailable"; + if (identity.purpose === "bisect") { + // Starts at the earliest candidate after the last green run. A passing probe proves the + // first bad commit is later; a failing probe proves it is no later than the probed SHA. + if (result === "unavailable") return; + const { before, after } = await updateRecord(io, (current, now) => { + const open = current.open; + if (!open || open.run !== identity.source) return current; + if (failed) return io.isAncestor(identity.sha, open.firstBad) && identity.sha !== open.firstBad ? refineFirstBad(current, identity.sha, run.id, now) : current; + if (!io.isAncestor(open.firstBad, identity.sha)) return current; + const later = io.range(identity.sha, open.failures[0]!.sha)[0]; + return later ? refineFirstBad(current, later, run.id, now) : current; + }); + if (after !== before && after.open?.incident) await io.write("POST", `repos/${io.repository}/issues/${after.open.incident}/comments`, { body: `Bisect probe ${runUrl(io, run.id)} ${failed ? "reproduced" : "passed"} at \`${identity.sha}\`; the record's first bad SHA is now \`${after.open.firstBad}\`.` }); + return; + } + const pending = io.read().redMain.suspects.filter(s => s.run === identity.source && s.sha === identity.sha && s.probe === "pending"); + const real: RedFailure[] = []; + for (const suspect of pending) { + await updateRecord(io, (current, now) => settleSuspect(current, { test: suspect.test, run: suspect.run }, { probe: result }, now)); + await noteFlake(io, suspect.test, `Triage probe ${runUrl(io, run.id)} at \`${identity.sha}\`: **${result}**. ${failed ? "The failure reproduced; main is declared red." : "A passing probe does not turn the original run green."}`, suspect.issue); + if (failed) real.push({ test: suspect.test.startsWith("category:") ? null : suspect.test, category: suspect.category, verdict: "real", reasons: ["probe-reproduced"], run: identity.source, sha: identity.sha }); + } + if (!real.length) return; + const { after } = await updateRecord(io, (current, now) => openRed(current, { firstBad: identity.sha, run: identity.source, failures: real }, now)); + await cancelDoomed(io, await ensureIncident(io, after)); +} + +export async function coordinate(io: CoordinatorIO, run: WorkflowRun) { + if (run.name === "CI" && run.event === "push" && run.head_branch === "main" && run.status === "completed") await handleMainRun(io, run); + else if (run.name === "red-main-probe") await handleProbe(io, run); +} diff --git a/scripts/red-main.ts b/scripts/red-main.ts new file mode 100644 index 0000000000..15f54c7209 --- /dev/null +++ b/scripts/red-main.ts @@ -0,0 +1,186 @@ +/** + * Repository-level red-main record (#2942): shared through the coordination ref, + * written by the coordinator workflow, read by CI, `integrate.ts` and orchestrators. + */ +import type { CheckPlan } from "./ci-plan"; + +export const RED_MAIN_FILE = "red-main.json"; +/** Two suspected flakes on one test within this window make the second real. */ +export const FLAKE_WINDOW_MS = 7 * 24 * 60 * 60_000; +const MAX_SUSPECTS = 200, MAX_REPORTED = 200, MAX_FAILURES = 100, MAX_FIXES = 20; +const SHA = /^[a-f0-9]{40}$/; +/** `changeset` is the metadata/lint gate; it always runs and widens no selection. */ +export const CATEGORIES = ["changeset", "verify", "pack", "unit", "runtime", "runtime_host", "browser", "layout", "captures", "endurance"] as const; +export type Category = typeof CATEGORIES[number]; +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; } +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[]; +} +export interface Suspect { test: string; category: Category; run: number; sha: string; at: number; probe: "pending" | "passed" | "failed" | "unavailable"; issue: number | null; } +export interface RedMainRecord { + version: 1; updated: number; open: RedIncident | null; suspects: Suspect[]; + last: { action: "open" | "update" | "refine" | "incident" | "declare-fix" | "report" | "clear" | "suspect" | "probe"; at: number; run: number | null } | null; +} + +export const emptyRedMain = (): RedMainRecord => ({ version: 1, updated: 0, open: null, suspects: [], last: null }); +const positive = (value: unknown) => Number.isSafeInteger(value) && Number(value) > 0; +const testPath = (value: unknown) => typeof value === "string" && value.length <= 300 && /^[A-Za-z0-9_./@-]+$/.test(value) && !value.split("/").includes(".."); +const category = (value: unknown): value is Category => CATEGORIES.includes(value as Category); + +export function parseRedMain(text: string): RedMainRecord { + if (text.length > 64_000) throw new Error("Unbounded red-main record"); + const r = JSON.parse(text) as RedMainRecord; + if (r?.version !== 1 || !Number.isSafeInteger(r.updated) || r.updated < 0 || !Array.isArray(r.suspects) || r.suspects.length > MAX_SUSPECTS || + !Object.hasOwn(r, "open") || !Object.hasOwn(r, "last")) throw new Error("Invalid red-main record"); + for (const s of r.suspects) if (!s || !testPath(s.test) || !category(s.category) || !positive(s.run) || !SHA.test(s.sha) || !Number.isSafeInteger(s.at) || + !["pending", "passed", "failed", "unavailable"].includes(s.probe) || !(s.issue === null || positive(s.issue))) throw new Error("Invalid red-main suspect"); + const o = r.open; + if (o !== null && (!o || !SHA.test(o.firstBad) || !positive(o.run) || !Number.isSafeInteger(o.opened) || !Array.isArray(o.failures) || + !o.failures.length || o.failures.length > MAX_FAILURES || !(o.incident === null || positive(o.incident)) || + !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"); + if (r.last !== null && (!r.last || r.last.at !== r.updated || !(r.last.run === null || positive(r.last.run)) || + !["open", "update", "refine", "incident", "declare-fix", "report", "clear", "suspect", "probe"].includes(r.last.action))) throw new Error("Invalid red-main audit"); + return r; +} + +const key = (f: { test: string | null; category: Category }) => f.test ?? `category:${f.category}`; +function next(record: RedMainRecord, now: number, action: NonNullable["action"], run: number | null, change: Partial): RedMainRecord { + if (!Number.isSafeInteger(now) || now < record.updated) throw new Error("Backwards or unavailable clock"); + return parseRedMain(JSON.stringify({ ...record, ...change, version: 1, updated: now, last: { action, at: now, run } })); +} + +/** Opens the record, or adds new failures to the open one; never changes its first bad SHA. */ +export function openRed(record: RedMainRecord, input: { firstBad: string; run: number; failures: RedFailure[] }, now: number): RedMainRecord { + if (!input.failures.length) throw new Error("A red record needs at least one real failure"); + if (record.open) { + const known = new Set(record.open.failures.map(key)), added = input.failures.filter(f => !known.has(key(f))); + if (!added.length) return record; + return next(record, now, "update", input.run, { open: { ...record.open, failures: [...record.open.failures, ...added].slice(0, MAX_FAILURES) } }); + } + return next(record, now, "open", input.run, { open: { firstBad: input.firstBad, run: input.run, opened: now, failures: input.failures.slice(0, MAX_FAILURES), incident: null, fixes: [], reported: [] } }); +} + +/** Bisect probes narrow the first bad SHA within the recorded range; the caller proves ancestry. */ +export function refineFirstBad(record: RedMainRecord, sha: string, run: number, now: number): RedMainRecord { + if (!record.open || record.open.firstBad === sha) return record; + if (!SHA.test(sha)) throw new Error("Invalid first bad SHA"); + return next(record, now, "refine", run, { open: { ...record.open, firstBad: sha } }); +} + +export function attachIncident(record: RedMainRecord, incident: number, now: number): RedMainRecord { + if (!record.open) throw new Error("No open red-main record"); + if (record.open.incident === incident) return record; + if (record.open.incident !== null) throw new Error(`Red-main record already names incident #${record.open.incident}`); + return next(record, now, "incident", record.open.run, { open: { ...record.open, incident } }); +} + +export function declareFix(record: RedMainRecord, pr: number, now: number): RedMainRecord { + if (!record.open) throw new Error("Main is not red; there is nothing to declare a fix for"); + if (!positive(pr)) throw new Error("Invalid fix PR"); + if (record.open.fixes.includes(pr)) return record; + return next(record, now, "declare-fix", null, { open: { ...record.open, fixes: [...record.open.fixes, pr] } }); +} + +export function reportLanded(record: RedMainRecord, sha: string, now: number): RedMainRecord { + if (!record.open || record.open.reported.includes(sha)) return record; + return next(record, now, "report", null, { open: { ...record.open, reported: [...record.open.reported, sha].slice(-MAX_REPORTED) } }); +} + +export interface IncludedRedSet { run: number; firstBad: string; failures: RedFailure[]; } +/** Whether a main run's printed selection covered every failure of this open record. */ +export function coversRedSet(record: RedMainRecord, included: IncludedRedSet | null): boolean { + if (!record.open || !included || included.run !== record.open.run) return false; + const keys = new Set(included.failures.map(key)); + return record.open.failures.every(f => keys.has(key(f))); +} + +/** Clears only on a green main run whose selection included this exact open record. */ +export function clearRed(record: RedMainRecord, run: { id: number; conclusion: string; included: IncludedRedSet | null }, now: number): RedMainRecord { + if (!record.open) return record; + if (run.conclusion !== "success" || !coversRedSet(record, run.included)) throw new Error("Only a green main run that included the open red set clears it"); + return next(record, now, "clear", run.id, { open: null }); +} + +export function addSuspect(record: RedMainRecord, suspect: Omit & Partial>, now: number): RedMainRecord { + return next(record, now, "suspect", suspect.run, { suspects: [...record.suspects, { probe: "pending" as const, issue: null, ...suspect }].slice(-MAX_SUSPECTS) }); +} + +export function settleSuspect(record: RedMainRecord, match: { test: string; run: number }, update: Partial>, now: number): RedMainRecord { + let found = false; + const suspects = record.suspects.map(s => s.test === match.test && s.run === match.run ? (found = true, { ...s, ...update }) : s); + if (!found) throw new Error("Unknown suspected flake"); + return next(record, now, "probe", match.run, { suspects }); +} + +export interface FailureEvidence { test: string | null; category: Category; signature: Signature; inClosure: boolean | null; } + +/** + * Deterministic flake estimator. A rerun never turns proof green; this only + * decides whether main is declared red now or after a triage probe. + */ +export function classifyFailure(failure: FailureEvidence, record: RedMainRecord, now: number, windowMs = FLAKE_WINDOW_MS): { verdict: Verdict; reasons: string[] } { + const id = key(failure); + const prior = record.suspects.filter(s => s.test === id && now - s.at <= windowMs); + if (prior.length) return { verdict: "real", reasons: ["repeated-suspected-flake", `prior-suspect-run-${prior.at(-1)!.run}`] }; + if (failure.signature === "setup") return { verdict: "suspected-flake", reasons: ["setup-failure"] }; + if (failure.inClosure === null) return { verdict: "real", reasons: ["closure-unknown"] }; + if (failure.inClosure) return { verdict: "real", reasons: ["in-affected-closure", `${failure.signature}-signature`] }; + if (failure.signature === "timeout") return { verdict: "suspected-flake", reasons: ["outside-affected-closure", "timeout-signature"] }; + return { verdict: "real", reasons: ["outside-affected-closure", `${failure.signature}-signature`] }; +} + +export const failureKey = key; + +export interface GateInput { record: RedMainRecord; pr: number; contains: (sha: string) => boolean; } +/** The hosted gate: refuse doomed proof, admit declared fixes and unaffected merge refs. */ +export function gateDecision({ record, pr, contains }: GateInput): { refuse: boolean; message: string } { + const open = record.open; + if (!open) return { refuse: false, message: "main green: no open red-main record" }; + const incident = open.incident ? `incident #${open.incident}` : "incident pending"; + if (open.fixes.includes(pr)) return { refuse: false, message: `main red at ${open.firstBad}, ${incident}; PR #${pr} is a declared fix` }; + if (!contains(open.firstBad)) return { refuse: false, message: `main red at ${open.firstBad}, ${incident}; this merge ref does not contain it` }; + return { refuse: true, message: `main red at ${open.firstBad}, ${incident}` }; +} + +/** Main runs select their affected set plus every test and category in the open red record. */ +export function includeRedSet(plan: CheckPlan, record: RedMainRecord | null, replan: (changed: string[]) => CheckPlan): CheckPlan { + const open = record?.open; + if (!open) return plan; + const tests = open.failures.flatMap(f => f.test ? [f.test] : []); + const widened = tests.length ? replan([...new Set([...plan.changed, ...tests])].sort()) : { ...plan, local: { ...plan.local } }; + const local = { ...widened.local }; + for (const f of open.failures) { + if (f.category === "unit") local.fullTests = true; + else if (f.category === "runtime" || f.category === "runtime_host") local.runtime = true; + else if (f.category === "browser" || f.category === "layout" || f.category === "captures" || f.category === "endurance") local[f.category] = true; + } + const typecheck = widened.typecheck || open.failures.some(f => f.category === "verify"); + const pack = widened.pack || open.failures.some(f => f.category === "pack"); + // The file inventory, when narrowed, must still name each red test. + const unitTests = widened.unitTests && [...new Set([...widened.unitTests, ...tests])].sort(); + return { ...widened, changed: plan.changed, typecheck, pack, local, ...(unitTests ? { unitTests } : {}), redMain: { run: open.run, firstBad: open.firstBad, failures: open.failures } }; +} + +/** Extracts failing test files and their signature from Bun JUnit output. */ +export function junitFailures(xml: string): { test: string; signature: Signature }[] { + const out = new Map(); + const suites = xml.split(/(?=]*>/.exec(suite)?.[0]; + const file = tag && /\sfile="([^"]*)"/.exec(tag)?.[1]; + if (!file || !testPath(file) || out.has(file)) continue; + const failures = [...suite.matchAll(/<(failure|error)\b([^>]*)>([\s\S]*?)<\/\1>|<(failure|error)\b([^>]*)\/>/g)]; + if (!failures.length) continue; + const text = failures.map(m => `${m[2] ?? m[5] ?? ""} ${m[3] ?? ""}`).join("\n"); + out.set(file, /timed? ?out|timeout|deadline exceeded/i.test(text) ? "timeout" : /expect|assert|toBe|toEqual|received|expected/i.test(text) ? "assertion" : "unknown"); + } + return [...out].map(([test, signature]) => ({ test, signature })); +} diff --git a/tests/ci-plan.test.ts b/tests/ci-plan.test.ts index 224317fea5..1c48753844 100644 --- a/tests/ci-plan.test.ts +++ b/tests/ci-plan.test.ts @@ -212,6 +212,7 @@ describe("affected CI checks", () => { const f = fixture(); f.write("scripts/ci-plan.ts", readFileSync(join(import.meta.dir, "../scripts/ci-plan.ts"), "utf8").replace('"typescript"', JSON.stringify(import.meta.resolve("typescript")))); f.write("scripts/browser-input-closure.ts", `export * from ${JSON.stringify(resolve(import.meta.dir, "../scripts/browser-input-closure.ts"))};\n`); f.write("scripts/unit-test-consumers.ts", `export * from ${JSON.stringify(resolve(import.meta.dir, "../scripts/unit-test-consumers.ts"))};\n`); + for (const name of ["integration-reservation", "red-main"]) f.write(`scripts/${name}.ts`, `export * from ${JSON.stringify(resolve(import.meta.dir, `../scripts/${name}.ts`))};\n`); f.write("packages/core/src/note.ts", "export const note = 2;\n"); f.git("add", "."); f.git("commit", "-qm", "planner fixture"); for (const draft of ["true", "false"]) { @@ -224,7 +225,7 @@ describe("affected CI checks", () => { const [code, err] = await Promise.all([child.exited, new Response(child.stderr).text()]); expect(code, err).toBe(0); const expected = proofSelections(JSON.parse(readFileSync(plan, "utf8")), draft === "true"); - expect(readFileSync(output, "utf8")).toBe(`unit_shards=[1,2,3,4]\ncadence=${draft === "true" ? "draft" : "confirmation"}\n` + Object.entries(expected).map(([name, value]) => `${name}=${value}\n`).join("")); + expect(readFileSync(output, "utf8")).toBe(`unit_shards=[1,2,3,4]\ncadence=${draft === "true" ? "draft" : "confirmation"}\nred_main_oid=\n` + Object.entries(expected).map(([name, value]) => `${name}=${value}\n`).join("")); expect(expected.unit).toBe(draft === "false"); expect(expected.runtime).toBe(draft === "false"); expect(JSON.parse(readFileSync(plan, "utf8")).tests.length).toBeGreaterThan(0); diff --git a/tests/ci-throughput.test.ts b/tests/ci-throughput.test.ts index d4b29e1735..a847ba6223 100644 --- a/tests/ci-throughput.test.ts +++ b/tests/ci-throughput.test.ts @@ -4,6 +4,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { collectPullObservation, concurrency, summarizeThroughput, 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"; import { emptyReservation, reservationTransition, GitReservationStore } from "../scripts/integration-reservation"; @@ -139,10 +140,15 @@ test("native reservation collection reads an explicitly local offline Git remote const store = new GitReservationStore(work); const state = reservationTransition(emptyReservation(), { kind: "acquire", candidate: { repository: `https://github.com/${repo}`, pr: 42, head, base }, id: "2".repeat(32) }, 1, Date.parse(at(0))); expect(store.publish({ oid: null, state: emptyReservation() }, state)).toBe(true); + // Red-main record writes share the ref and leave reservation.json unchanged (#2942). + const failure = { test: "tests/raft.test.ts", category: "unit" as const, verdict: "real" as const, reasons: ["in-affected-closure"], run: 7, sha: head }; + expect(store.publishRedMain(store.read(), openRed(emptyRedMain(), { firstBad: head, run: 7, failures: [failure] }, Date.parse(at(0)) + 1))).toBe(true); + expect(store.publishRedMain(store.read(), declareFix(store.read().redMain, 43, Date.parse(at(0)) + 2))).toBe(true); // The production collector uses Git argv against this local remote only. process.chdir(work); const history = collectReservationHistory(repo, at(0)); expect(history.leases.length).toBe(1); expect(history.leases[0]!.pr).toBe(42); + expect(history.leases[0]!.sources, "RED_MAIN_WRITES_ARE_NOT_LEASE_SOURCES").toHaveLength(1); } finally { process.chdir(cwd); rmSync(dir, { recursive: true, force: true }); } }); diff --git a/tests/ci-workflows.test.ts b/tests/ci-workflows.test.ts index e374ec8c43..5cad2fc6e9 100644 --- a/tests/ci-workflows.test.ts +++ b/tests/ci-workflows.test.ts @@ -131,7 +131,7 @@ describe("the authoritative jobs retain their important phases", () => { expect(ci.on.push).toEqual({ branches: ["main"] }); expect(ci.on.pull_request).toEqual({ types: ["opened", "synchronize", "reopened", "ready_for_review", "converted_to_draft"] }); expect(Object.keys(ci.jobs)).toEqual(["changeset", "verify", "pack", "unit", "runtime", "runtime_host", "browser", "layout", "captures", "endurance", "proof"]); - expect(ci.jobs.changeset!.outputs).toEqual({ ...Object.fromEntries(["verify", "pack", "unit", "browser", "layout", "captures", "runtime", "runtime_host", "endurance", "cadence", "unit_shards"].map(name => [name, `\${{ steps.plan.outputs.${name} }}`])), + expect(ci.jobs.changeset!.outputs).toEqual({ ...Object.fromEntries(["verify", "pack", "unit", "browser", "layout", "captures", "runtime", "runtime_host", "endurance", "cadence", "unit_shards", "red_main_oid"].map(name => [name, `\${{ steps.plan.outputs.${name} }}`])), ...Object.fromEntries(["run_browser", "run_layout", "reuse"].map(name => [name, `\${{ steps.reuse.outputs.${name} }}`])) }); const metadata = ci.jobs.changeset!.steps.filter(s => s.run).map(s => s.run); expect(metadata).toContain("bun scripts/ci-plan.ts"); expect(metadata).toContain("bun run lint"); @@ -662,3 +662,18 @@ test("verify successful step requires final marker and zero unsignalled finishes } } finally { rmSync(dir, { recursive: true, force: true }); } }); + +test("a main push whose metadata job fails still runs its selected proof (#2942)", () => { + const ci = Bun.YAML.parse(readFileSync(join(ROOT, ".github/workflows/ci.yml"), "utf8")) as { jobs: Record }; + for (const name of ["verify", "pack", "unit", "runtime", "runtime_host", "browser", "layout", "captures", "endurance"]) { + const condition = ci.jobs[name]!.if ?? ""; + // No implicit success(): a status function plus an explicit push alternative. + expect(condition, `PUSH_PROOF_SURVIVES_METADATA_FAILURE:${name}`).toContain("!cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push')"); + } + const steps = ci.jobs.changeset!.steps!.map(step => step.id ?? step.name ?? ""); + const gate = steps.indexOf("Refuse doomed proof while main is red"), plan = steps.indexOf("plan"), reuse = steps.indexOf("reuse"); + expect(gate, "RED_MAIN_GATE_RUNS_FIRST").toBeGreaterThan(-1); expect(gate).toBeLessThan(plan); + // Every output-producing step precedes every metadata gate that can fail. + for (const gateStep of ["Lint, leakage and contribution workflow guards", "Env documentation matches its descriptors", "Validate all pending changeset package names", "Require a changeset for shipped package changes"]) + expect(steps.indexOf(gateStep), `OUTPUTS_BEFORE_${gateStep}`).toBeGreaterThan(reuse); +}); diff --git a/tests/integration-command.test.ts b/tests/integration-command.test.ts index 9a73095e54..1756f8876b 100644 --- a/tests/integration-command.test.ts +++ b/tests/integration-command.test.ts @@ -3,6 +3,7 @@ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, wr 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 { invocationChild } from "../scripts/test-invocation-child"; import { processIdentity } from "../scripts/workspace-lease.mjs"; @@ -72,6 +73,11 @@ async function runScenario(mode: string, owner: Scenario): Promise { + const refused = await scenario("red-main"); + expect(refused.dispatched, "NO_NON_FIX_MERGE_WHILE_RED").toBe(false); + expect(refused.code, refused.err).toBe(1); + expect(refused.err).toContain("main red at"); + expect(refused.err).toContain("only a declared fix may confirm or merge"); + const fix = await scenario("red-main-fix"); + expect(fix.code, `DECLARED_FIX_MERGES: ${fix.err}`).toBe(2); + expect(fix.dispatched).toBe(true); +}); diff --git a/tests/red-main.test.ts b/tests/red-main.test.ts new file mode 100644 index 0000000000..39996cf2ee --- /dev/null +++ b/tests/red-main.test.ts @@ -0,0 +1,276 @@ +import { afterEach, describe, expect, test } from "bun:test"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { planChecks, workspaces } from "../scripts/ci-plan"; +import { GitReservationStore } from "../scripts/integration-reservation"; +import { addSuspect, classifyFailure, clearRed, declareFix, emptyRedMain, FLAKE_WINDOW_MS, gateDecision, includeRedSet, junitFailures, + 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"; + +const ROOT = resolve(import.meta.dir, ".."); +const scratch: string[] = []; +afterEach(() => { for (const dir of scratch.splice(0)) rmSync(dir, { recursive: true, force: true }); }); +const NOW = Date.parse("2026-07-12T00:00:00Z"); +const A = "a".repeat(40), B = "b".repeat(40), C = "c".repeat(40); +const failure = (test: string | null, category: RedFailure["category"] = "unit"): RedFailure => + ({ test, category, verdict: "real", reasons: ["in-affected-closure"], run: 11, sha: B }); + +function repo() { + const dir = mkdtempSync(join(tmpdir(), "odysseus-red-main-")); scratch.push(dir); + const git = (cwd: string, ...args: string[]) => { + const p = Bun.spawnSync(["git", "-c", "commit.gpgsign=false", ...args], { cwd, stdout: "pipe", stderr: "pipe", env: { ...process.env, + GIT_AUTHOR_NAME: "Odysseus", GIT_AUTHOR_EMAIL: "odysseus@example.invalid", GIT_COMMITTER_NAME: "Odysseus", GIT_COMMITTER_EMAIL: "odysseus@example.invalid", + GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: "/dev/null" } }); + expect(p.exitCode, new TextDecoder().decode(p.stderr)).toBe(0); + return new TextDecoder().decode(p.stdout).trim(); + }; + return { dir, git }; +} + +describe("flake estimator", () => { + test("an out-of-closure timeout is a suspected flake, an in-closure assertion is real, and a second suspicion is real", () => { + const record = emptyRedMain(); + expect(classifyFailure({ test: "tests/raft.test.ts", category: "unit", signature: "timeout", inClosure: false }, record, NOW).verdict, "OUTSIDE_CLOSURE_TIMEOUT_SUSPECTED").toBe("suspected-flake"); + expect(classifyFailure({ test: "tests/raft.test.ts", category: "unit", signature: "assertion", inClosure: true }, record, NOW).verdict, "IN_CLOSURE_ASSERTION_REAL").toBe("real"); + const suspected = addSuspect(record, { test: "tests/raft.test.ts", category: "unit", run: 9, sha: A, at: NOW - 1000 }, NOW - 1000); + const second = classifyFailure({ test: "tests/raft.test.ts", category: "unit", signature: "timeout", inClosure: false }, suspected, NOW); + expect(second.verdict, "SECOND_SUSPECTED_FLAKE_ESCALATES").toBe("real"); + expect(second.reasons).toContain("repeated-suspected-flake"); + // Outside the configured window the earlier suspicion no longer escalates. + expect(classifyFailure({ test: "tests/raft.test.ts", category: "unit", signature: "timeout", inClosure: false }, suspected, NOW + FLAKE_WINDOW_MS).verdict).toBe("suspected-flake"); + // An unknown closure fails closed to real, never to a flake. + expect(classifyFailure({ test: "tests/raft.test.ts", category: "unit", signature: "timeout", inClosure: null }, record, NOW).verdict).toBe("real"); + }); + + test("JUnit failures name each failing file with its signature", () => { + const xml = ` + expect(received).toBe(expected) + `; + expect(junitFailures(xml)).toEqual([{ test: "tests/a.test.ts", signature: "timeout" }, { test: "tests/b.test.ts", signature: "assertion" }]); + }); +}); + +describe("red-main record", () => { + test("records validate, merge new failures, clear only from a green run that included the set", () => { + let record = openRed(emptyRedMain(), { firstBad: B, run: 11, failures: [failure("tests/raft.test.ts")] }, NOW); + record = openRed(record, { firstBad: C, run: 12, failures: [failure("tests/raft.test.ts"), failure(null, "browser")] }, NOW + 1); + expect(record.open?.firstBad).toBe(B); expect(record.open?.failures).toHaveLength(2); + expect(parseRedMain(JSON.stringify(record))).toEqual(record); + expect(() => parseRedMain(JSON.stringify({ ...record, open: { ...record.open, firstBad: "nope" } }))).toThrow("Invalid red-main incident"); + expect(() => clearRed(record, { id: 13, conclusion: "success", included: { run: 11, firstBad: B, failures: [failure("tests/raft.test.ts")] } }, NOW + 2)).toThrow("included the open red set"); + expect(() => clearRed(record, { id: 13, conclusion: "failure", included: { run: 11, firstBad: B, failures: record.open!.failures } }, NOW + 2)).toThrow(); + expect(clearRed(record, { id: 13, conclusion: "success", included: { run: 11, firstBad: B, failures: record.open!.failures } }, NOW + 2).open).toBeNull(); + }); + + test("two concurrent coordinators cannot both write the record through the remote compare-and-swap", async () => { + const { dir, git } = repo(); + const remote = join(dir, "remote.git"); git(dir, "init", "--bare", remote); + for (const name of ["one", "two"]) { mkdirSync(join(dir, name)); git(join(dir, name), "init"); git(join(dir, name), "remote", "add", "origin", remote); } + const script = join(dir, "contender.ts"); + writeFileSync(script, `import { existsSync, writeFileSync } from "node:fs"; + import { GitReservationStore } from ${JSON.stringify(join(ROOT, "scripts/integration-reservation.ts"))}; + import { openRed, emptyRedMain } from ${JSON.stringify(join(ROOT, "scripts/red-main.ts"))}; + const [root, number, barrier] = process.argv.slice(2), store = new GitReservationStore(root), snapshot = store.read(); + writeFileSync(barrier + number, "ready"); while (!existsSync(barrier + "1") || !existsSync(barrier + "2")) await Bun.sleep(5); + if (number === "2") while (!existsSync(barrier + "published")) await Bun.sleep(5); + const record = openRed(emptyRedMain(), { firstBad: "${B}", run: Number(number), failures: [{ test: "tests/raft.test.ts", category: "unit", verdict: "real", reasons: ["in-affected-closure"], run: Number(number), sha: "${B}" }] }, ${NOW}); + const published = store.publishRedMain(snapshot, record); if (number === "1") writeFileSync(barrier + "published", "done"); + console.log(JSON.stringify({ published }));`); + const children = ["1", "2"].map((id, index) => Bun.spawn([process.execPath, script, join(dir, index ? "two" : "one"), id, join(dir, "barrier-")], { stdout: "pipe", stderr: "pipe" })); + const results = await Promise.all(children.map(async child => { + const [code, out, err] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); + expect(code, err).toBe(0); return JSON.parse(out).published as boolean; + })); + expect(results, "ONLY_ONE_RED_MAIN_WRITER_SUCCEEDS").toEqual([true, false]); + const store = new GitReservationStore(join(dir, "two")), snapshot = store.read(); + expect(snapshot.redMain.open?.run).toBe(1); + // The reservation file is preserved beside the record, and clearing writes through the same ref. + expect(snapshot.state.active).toBeNull(); + const cleared = clearRed(snapshot.redMain, { id: 3, conclusion: "success", included: { run: 1, firstBad: B, failures: snapshot.redMain.open!.failures } }, NOW + 1); + expect(store.publishRedMain(snapshot, cleared)).toBe(true); + expect(store.read().redMain.open).toBeNull(); + expect(store.read().redMain.last?.action).toBe("clear"); + }); +}); + +describe("main selection includes the open red set", () => { + test("a later main run that does not touch the red test's closure still runs it", () => { + const packages = workspaces(ROOT), replan = (changed: string[]) => planChecks(changed, packages, ROOT, false); + const plan = replan(["docs/README.md"]); + expect(plan.local.fullTests).toBe(false); expect(plan.local.browser).toBe(false); + const record = openRed(emptyRedMain(), { firstBad: B, run: 11, failures: [failure("packages/core/tests/frontmatter.test.ts"), failure(null, "browser")] }, NOW); + const widened = includeRedSet(plan, record, replan); + expect(widened.local.fullTests, "RED_UNIT_TEST_SELECTED_WITHOUT_CLOSURE_CHANGE").toBe(true); + expect(widened.local.browser, "RED_CATEGORY_SELECTED").toBe(true); + expect(widened.changed).toEqual(["docs/README.md"]); + expect(widened.redMain).toEqual({ run: 11, firstBad: B, failures: record.open!.failures }); + expect(includeRedSet(plan, emptyRedMain(), replan)).toBe(plan); + }); + + test("the planner executable pins one coordination snapshot and prints the included set", () => { + const { dir, git } = repo(); + git(dir, "init", "-q"); git(dir, "remote", "add", "origin", dir); + for (const name of ["core", "ui-sdk"]) { mkdirSync(join(dir, "packages", name, "src"), { recursive: true }); + writeFileSync(join(dir, "packages", name, "package.json"), JSON.stringify({ name: `@fixture/${name}`, files: ["src"] })); writeFileSync(join(dir, "packages", name, "src/index.ts"), "export {};\n"); } + mkdirSync(join(dir, "scripts")); mkdirSync(join(dir, "docs")); + writeFileSync(join(dir, "scripts/ci-plan.ts"), readFileSync(join(ROOT, "scripts/ci-plan.ts"), "utf8").replace('"typescript"', JSON.stringify(import.meta.resolve("typescript")))); + for (const name of ["browser-input-closure", "unit-test-consumers", "integration-reservation", "red-main"]) writeFileSync(join(dir, `scripts/${name}.ts`), `export * from ${JSON.stringify(join(ROOT, `scripts/${name}.ts`))};\n`); + writeFileSync(join(dir, "docs/notes.md"), "Ithaca.\n"); git(dir, "add", "."); git(dir, "commit", "-qm", "base"); + const before = git(dir, "rev-parse", "HEAD"); + writeFileSync(join(dir, "docs/notes.md"), "Ithaca, again.\n"); git(dir, "commit", "-qam", "docs only"); + const store = new GitReservationStore(dir); + expect(store.publishRedMain(store.read(), openRed(emptyRedMain(), { firstBad: before, run: 11, failures: [failure("packages/core/src/index.test.ts")] }, NOW))).toBe(true); + const oid = git(dir, "rev-parse", "refs/heads/brain-integration-reservation"); + const plan = (requested?: string) => { + const output = join(dir, `out-${requested ?? "resolve"}`), event = join(dir, "event.json"); + writeFileSync(event, JSON.stringify({ before })); + const p = Bun.spawnSync([process.execPath, join(dir, "scripts/ci-plan.ts")], { cwd: dir, stdout: "pipe", stderr: "pipe", env: { ...process.env, + GITHUB_EVENT_NAME: "push", GITHUB_EVENT_PATH: event, BEFORE_SHA: before, HEAD_SHA: "HEAD", GITHUB_OUTPUT: output, CI_PLAN_PATH: join(dir, "plan.json"), + ...(requested ? { RED_MAIN_OID: requested } : {}) } }); + expect(p.exitCode, new TextDecoder().decode(p.stderr)).toBe(0); + return { outputs: readFileSync(output, "utf8"), stdout: new TextDecoder().decode(p.stdout) }; + }; + const resolved = plan(); + expect(resolved.outputs).toContain(`red_main_oid=${oid}\n`); + expect(resolved.outputs, "PUSH_RUNS_RED_UNIT_TEST").toContain("unit=true\n"); + expect(includedRedSet(resolved.stdout)?.run).toBe(11); + // A later job receives the same snapshot even after the record changes. + expect(store.publishRedMain(store.read(), clearRed(store.read().redMain, { id: 12, conclusion: "success", included: { run: 11, firstBad: before, failures: store.read().redMain.open!.failures } }, NOW + 1))).toBe(true); + expect(plan(oid).outputs, "PINNED_SNAPSHOT").toContain("unit=true\n"); + expect(plan("none").outputs).toContain("unit=false\n"); + }); +}); + +describe("hosted gate", () => { + test("refuses a non-fix PR whose merge ref contains the bad SHA and admits a declared fix", () => { + const { dir, git } = repo(); + git(dir, "init", "-q"); git(dir, "remote", "add", "origin", dir); + writeFileSync(join(dir, "raft.md"), "1\n"); git(dir, "add", "."); git(dir, "commit", "-qm", "good"); + const good = git(dir, "rev-parse", "HEAD"); + writeFileSync(join(dir, "raft.md"), "2\n"); git(dir, "commit", "-qam", "bad"); + const bad = git(dir, "rev-parse", "HEAD"); + const store = new GitReservationStore(dir); + expect(store.publishRedMain(store.read(), declareFix(openRed(emptyRedMain(), { firstBad: bad, run: 11, failures: [failure("tests/raft.test.ts")] }, NOW), 8, NOW + 1))).toBe(true); + const gate = (pr: number) => { + const p = Bun.spawnSync([process.execPath, join(ROOT, "scripts/red-main-cli.ts"), "gate"], { cwd: dir, stdout: "pipe", stderr: "pipe", env: { ...process.env, PR_NUMBER: String(pr) } }); + return { code: p.exitCode, text: new TextDecoder().decode(p.stdout) + new TextDecoder().decode(p.stderr) }; + }; + const refused = gate(7); + expect(refused.code, "NON_FIX_CONTAINING_BAD_SHA_REFUSED").toBe(1); + expect(refused.text).toContain(`main red at ${bad}, incident pending`); + expect(gate(8).code, "DECLARED_FIX_ADMITTED").toBe(0); + git(dir, "checkout", "-q", good); + expect(gate(7).code, "MERGE_REF_WITHOUT_BAD_SHA_ADMITTED").toBe(0); + expect(gateDecision({ record: emptyRedMain(), pr: 7, contains: () => true }).refuse).toBe(false); + }); +}); + +/** In-memory GitHub plus a real-shape record store for the coordinator. */ +function fakeGitHub(options: { jobs: Job[]; junit?: string; closure?: boolean | null; pulls?: Record; prRuns?: WorkflowRun[]; history?: WorkflowRun[]; historyJobs?: Record }) { + let snapshot: Snapshot = { oid: null, redMain: emptyRedMain() }, version = 0, clock = NOW; + const issues: { number: number; title: string; body: string; labels: string[] }[] = []; + const comments: { issue: number; body: string }[] = [], cancelled: number[] = [], dispatched: unknown[] = [], events: unknown[] = []; + const io: CoordinatorIO = { + repository: "odysseus/brain-kit", + async json(path) { + if (path.startsWith("search/issues")) { + const query = decodeURIComponent(path.split("q=")[1]!.split("&")[0]!); + const phrase = /"([^"]+)"/.exec(query)?.[1] ?? ""; + return { items: issues.filter(issue => issue.body.includes(phrase) || issue.title.includes(phrase)) }; + } + const jobsMatch = /actions\/runs\/(\d+)\/attempts\/\d+\/jobs/.exec(path); + if (jobsMatch) return { jobs: Number(jobsMatch[1]) >= 100 ? options.jobs : options.historyJobs?.[Number(jobsMatch[1])] ?? [] }; + if (path.includes("ci.yml/runs?event=pull_request")) return { workflow_runs: path.includes("in_progress") ? options.prRuns ?? [] : [] }; + if (path.includes("ci.yml/runs?event=push")) return { workflow_runs: options.history ?? [] }; + const pulls = /commits\/([a-f0-9]{40})\/pulls/.exec(path); + if (pulls) return options.pulls?.[pulls[1]!] ? [{ number: options.pulls[pulls[1]!], merged_at: "2026-07-12T00:00:00Z" }] : []; + throw new Error(`Unexpected offline API ${path}`); + }, + async write(method, path, body: any) { + if (path.endsWith("/issues")) { const issue = { number: 500 + issues.length, ...body }; issues.push(issue); return issue; } + const comment = /issues\/(\d+)\/comments$/.exec(path); + if (comment) { comments.push({ issue: Number(comment[1]), body: body.body }); return {}; } + const cancel = /actions\/runs\/(\d+)\/cancel$/.exec(path); + if (cancel) { cancelled.push(Number(cancel[1])); return {}; } + if (path.endsWith("/dispatches")) { dispatched.push(body); return {}; } + throw new Error(`Unexpected offline write ${method} ${path}`); + }, + async now() { return clock += 1000; }, + read() { return { oid: String(version), redMain: snapshot.redMain }; }, + publish(seen, record) { if (seen.oid !== String(version)) return false; version++; snapshot = { oid: String(version), redMain: parseRedMain(JSON.stringify(record)) }; return true; }, + async artifactFiles(_run, name) { return name === "unit-proof-2" && options.junit ? [options.junit] : []; }, + async log() { return ""; }, + inClosure: () => options.closure ?? true, + range: (since, until) => since === A && until === C ? [B, C] : [], + isAncestor: (a, b) => a === b || (a === A && b !== A) || (a === B && b === C), + commitTime: () => NOW, + async recordEvent(event) { events.push(event); }, + print() {}, + }; + return { io, issues, comments, cancelled, dispatched, events, record: () => snapshot.redMain, set: (record: RedMainRecord) => { snapshot = { oid: String(++version), redMain: record }; } }; +} +const mainRun = (sha: string, conclusion: string, id = 100): WorkflowRun => ({ id, name: "CI", event: "push", head_branch: "main", head_sha: sha, status: "completed", conclusion, + run_attempt: 1, display_title: "squash", created_at: "2026-07-12T00:00:00Z" }); +const junit = `expect(received).toBe(expected)`; + +describe("coordinator", () => { + test("two coordinator runs for the same bad SHA and test leave exactly one incident issue and cancel doomed PR proof", async () => { + const gh = fakeGitHub({ jobs: [{ id: 1, name: "changeset", conclusion: "success" }, { id: 2, name: "unit (2)", conclusion: "failure", steps: [] }], junit, + prRuns: [{ ...mainRun(A, "", 300), event: "pull_request", head_branch: "feat", status: "in_progress", pull_requests: [{ number: 7 }], created_at: "2026-07-12T00:00:01Z" }, + { ...mainRun(A, "", 301), event: "pull_request", head_branch: "fix", status: "in_progress", pull_requests: [{ number: 8 }], created_at: "2026-07-12T00:00:01Z" }] }); + await coordinate(gh.io, mainRun(B, "failure")); + gh.set(declareFix(gh.record(), 8, NOW + 100_000)); + await coordinate(gh.io, mainRun(B, "failure")); + expect(gh.issues, "EXACTLY_ONE_INCIDENT_ISSUE").toHaveLength(1); + expect(gh.issues[0]!.body).toContain(incidentMarker(100)); + expect(gh.issues[0]!.title).toContain("packages/core/tests/raft.test.ts"); + expect(gh.record().open).toMatchObject({ firstBad: B, incident: 500, failures: [{ test: "packages/core/tests/raft.test.ts", reasons: ["in-affected-closure", "assertion-signature"] }] }); + // Before PR #8 is declared a fix both runs are doomed; afterwards only the non-fix run is cancelled. + expect(gh.cancelled, "DOOMED_NON_FIX_RUN_CANCELLED_FIX_KEPT").toEqual([300, 301, 300]); + }); + + test("a suspected flake files its test issue and dispatches a probe without declaring main red", async () => { + const gh = fakeGitHub({ jobs: [{ id: 2, name: "unit (2)", conclusion: "failure", steps: [] }], closure: false, + junit: junit.replace("expect(received).toBe(expected)", "") }); + await coordinate(gh.io, mainRun(B, "failure")); + expect(gh.record().open).toBeNull(); + expect(gh.record().suspects).toMatchObject([{ test: "packages/core/tests/raft.test.ts", probe: "pending", issue: 500 }]); + expect(gh.issues[0]!.title).toBe("test: suspected flake in packages/core/tests/raft.test.ts"); + expect(gh.dispatched).toEqual([{ ref: "main", inputs: { purpose: "flake", source_run: "100", sha: B, tests: JSON.stringify(["packages/core/tests/raft.test.ts"]) } }]); + // The failed probe reproduces it: main is declared red and the flake issue is updated. + await coordinate(gh.io, { ...mainRun(B, "failure", 200), name: "red-main-probe", event: "workflow_dispatch", display_title: `red-main probe flake 100 ${B}` }); + expect(gh.record().open?.failures[0]?.reasons).toEqual(["probe-reproduced"]); + expect(gh.comments.some(comment => comment.issue === 500 && comment.body.includes("**failed**"))).toBe(true); + }); + + test("first bad is the first commit after the last green run, and a squash landed while red is reported", async () => { + const history = [mainRun(A, "success", 90)]; + const gh = fakeGitHub({ jobs: [{ id: 2, name: "unit (2)", conclusion: "failure", steps: [] }], junit, history, + historyJobs: { 90: [{ id: 9, name: "unit (1)", conclusion: "success" }] }, pulls: { [C]: 7 } }); + await coordinate(gh.io, mainRun(C, "failure")); + expect(gh.record().open?.firstBad, "FIRST_RED_AFTER_LAST_GREEN").toBe(B); + expect(gh.dispatched.filter((d: any) => d.inputs.purpose === "bisect")).toHaveLength(2); + // The next main run's squash C lands while red without being a declared fix. + await coordinate(gh.io, mainRun(C, "failure", 101)); + expect(gh.comments.filter(comment => comment.issue === 7), "LANDED_WHILE_RED_REPORTED_ON_PR").toHaveLength(1); + expect(gh.comments.some(comment => comment.issue === 500 && comment.body.includes("landed while red"))).toBe(true); + expect(gh.events).toEqual([{ kind: "incident", pr: 7, run: 101, evidence: "https://github.com/odysseus/brain-kit/issues/500" }]); + expect(gh.record().open?.reported).toEqual([C]); + await coordinate(gh.io, mainRun(C, "failure", 102)); + expect(gh.comments.filter(comment => comment.issue === 7), "REPORTED_ONCE").toHaveLength(1); + }); + + test("a green main run clears the record only when it included the open set", async () => { + const gh = fakeGitHub({ jobs: [{ id: 1, name: "changeset", conclusion: "success" }] }); + const record = openRed(emptyRedMain(), { firstBad: B, run: 11, failures: [failure("tests/raft.test.ts")] }, NOW); + gh.set(record); + gh.io.log = async () => ""; + await coordinate(gh.io, mainRun(C, "success")); + expect(gh.record().open, "GREEN_WITHOUT_RED_SET_DOES_NOT_CLEAR").not.toBeNull(); + gh.io.log = async () => `2026-07-12T00:00:00Z BRAIN_RED_MAIN_INCLUDED ${JSON.stringify({ run: 11, firstBad: B, failures: record.open!.failures })}`; + await coordinate(gh.io, mainRun(C, "success", 103)); + expect(gh.record().open).toBeNull(); + expect(existsSync(ROOT)).toBe(true); + }); +}); From 471d33d0a9ca6394a97189ffe5d1224b29a0219e Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 09:43:51 +0000 Subject: [PATCH 2/7] docs(ci): record the red-main controller decisions and permissions Refs #2942 Co-Authored-By: Claude Opus 5.5 --- docs/decisions/ci-utility.md | 63 ++++++++++++++++++++++++++++++++++++ scripts/red-main-cli.ts | 2 +- 2 files changed, 64 insertions(+), 1 deletion(-) diff --git a/docs/decisions/ci-utility.md b/docs/decisions/ci-utility.md index 1d21b87ddb..1e05b13b4a 100644 --- a/docs/decisions/ci-utility.md +++ b/docs/decisions/ci-utility.md @@ -1423,6 +1423,69 @@ Each implementation task is tracked separately: - automatic epochs: [#3270](https://github.com/schlessera/brain-kit/issues/3270); - off-main qualification evidence: [#3271](https://github.com/schlessera/brain-kit/issues/3271). +### Red-main record and coordinator + +The [2026-10-25 red-main and coordination decisions](https://github.com/schlessera/brain-kit/issues/2934#issuecomment-6402400614) +are implemented by [#2942](https://github.com/schlessera/brain-kit/issues/2942): + +- **Strict flake handling.** A rerun is only a triage probe that decides whether + main is declared red. It never turns proof green or makes anything mergeable. + It always files or updates an issue on the test, and a second suspected flake + on one test within seven days is treated as real. "Never rerun a real failure" + stays. +- **A red main stops doomed work.** Hosted proof whose merge ref contains the + bad commit is refused or cancelled, except declared fixes. Each machine keeps + its own resources for a fix it is building. +- **Coordination runs on GitHub.** A coordinator workflow on main CI completion + and the shared reservation ref hold the repository-level record. Orchestrators + read and enforce it and never message each other. +- **Merge blocking while red is cooperative, plus detection.** `integrate.ts` + refuses non-fix confirmation and merges. Any squash that lands anyway is + reported on its PR and on the incident. There is no repository ruleset. +- **Several declared fixes** may exist for one incident; the first whose fix is + confirmed wins. +- **One incident issue per record**, created once by the coordinator. + +The record is `red-main.json`, stored beside `reservation.json` in the same +coordination ref and updated with the same exact `--force-with-lease` +compare-and-swap. A write to either file preserves the other. It holds the +first bad SHA, the failing tests and categories with the estimator's reasons, +the opening run, the incident issue, the declared fix PRs, the squashes already +reported, and a bounded ledger of suspected flakes. +`bun scripts/integrate.ts main-status --json` reads it, and +`declare-fix ` adds a fix. It is leakage-screened like the reservation. + +The estimator is deterministic. It decides from the failing test's membership +in the squash's own affected closure (an unknown closure counts as inside), +the error signature from JUnit (timeout or assertion), environment-setup step +failure, and earlier suspicions within the window. A suspected flake reruns +only its failing test files at that SHA through `red-main-probe.yml`. A real +failure opens the record. The first bad SHA is the first commit after the last +main run where the failing category actually ran green. When that range has +2–10 commits, probes rerun only the failing test files at each candidate and +narrow it; a wider range keeps the conservative first candidate. + +Main runs run their selected proof even when the metadata job fails. Each main +run selects its own affected set plus every test and category in the open +record. All of its jobs read one pinned coordination snapshot, and the +metadata job prints the included set. The record is cleared only by a green +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. The coordinator also cancels queued and running PR proof +created after the bad commit landed, except declared fixes. 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. + +`red-main.yml` declares no workflow-level permissions. Its one job has +`contents: write` (the coordination ref), `actions: write` (cancel doomed PR +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. + ### Hosted heavy feedback on draft heads The [#2939 ruling](https://github.com/schlessera/brain-kit/issues/2939#issuecomment-6403978097) diff --git a/scripts/red-main-cli.ts b/scripts/red-main-cli.ts index 8a855a6715..c2168e7a46 100644 --- a/scripts/red-main-cli.ts +++ b/scripts/red-main-cli.ts @@ -9,7 +9,7 @@ import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { changedFiles, planChecks, proofSelections, redMainSnapshot, workspaces } from "./ci-plan"; import { GitReservationStore, reservationServerTime, type Snapshot as StoreSnapshot } from "./integration-reservation"; -import { coordinate, type CoordinatorIO, type Snapshot, type WorkflowRun } from "./red-main-coordinator"; +import { coordinate, type CoordinatorIO, type WorkflowRun } from "./red-main-coordinator"; import { gateDecision, type Category } from "./red-main"; // Hosted jobs run from the checkout root; fixtures run from their own repository. From 32a0a8245611e6a8a8bf8d906de562a255f26b4a Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 09:46:40 +0000 Subject: [PATCH 3/7] docs: follow the moved CI install citation Refs #2942 Co-Authored-By: Claude Opus 5.5 --- docs/decisions/claude-code-runtime.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/decisions/claude-code-runtime.md b/docs/decisions/claude-code-runtime.md index 5cf4074f1a..30d9115f97 100644 --- a/docs/decisions/claude-code-runtime.md +++ b/docs/decisions/claude-code-runtime.md @@ -318,7 +318,7 @@ name instead of repeating the numbers. Two mechanisms hang off it: fails in both. A path hard-coded to the root `node_modules` could read a different copy from the one the backend loads. CI installs with `--frozen-lockfile` (`bun install --frozen-lockfile`, - `.github/workflows/ci.yml:52`), so the guard compares the lockfile-installed pair. + `.github/workflows/ci.yml:53`), so the guard compares the lockfile-installed pair. This fast version guard remains an affected automatic check under [the current CI policy](ci-utility.md); changing the SDK requires fresh local runtime measurements before updating the constant. It needs no key and no From b75fc0986b653ed08958dc43e18184c2db3b2f2a Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 09:49:38 +0000 Subject: [PATCH 4/7] feat(ci): replay the red-main coordinator read-only against a recorded run Refs #2942 Co-Authored-By: Claude Opus 5.5 --- scripts/red-main-cli.ts | 15 ++++++++++++++- scripts/red-main-coordinator.ts | 2 +- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/scripts/red-main-cli.ts b/scripts/red-main-cli.ts index c2168e7a46..89f3dacbf0 100644 --- a/scripts/red-main-cli.ts +++ b/scripts/red-main-cli.ts @@ -105,6 +105,19 @@ if (import.meta.main) { const decision = record ? gateDecision({ record, pr, contains: sha => isAncestor(sha, "HEAD") }) : { refuse: false, message: "main green: no coordination record" }; if (decision.refuse) { console.error(`::error::${decision.message}`); console.error(decision.message); process.exit(1); } console.log(decision.message); + } else if (command === "coordinate" && rest[0] === "--dry-run") { + // Read-only replay against a recorded run: every write is printed, none is sent. + const id = rest[rest.indexOf("--run") + 1] ?? "", repository = must(["gh", "repo", "view", "--json", "nameWithOwner", "--jq", ".nameWithOwner"]); + if (!/^[1-9]\d*$/.test(id)) throw new Error("usage: coordinate --dry-run --run "); + const io = liveIO(repository), seen = io.read(); + let record = seen.redMain; + const run = await io.json(`repos/${repository}/actions/runs/${id}`) as WorkflowRun; + await coordinate({ ...io, + read: () => ({ ...seen, redMain: record }), + publish(_snapshot, next) { record = next; console.log(`DRY_RUN record ${JSON.stringify(next)}`); return true; }, + async write(method, path, body) { console.log(`DRY_RUN ${method} ${path} ${JSON.stringify(body ?? null)}`); return { number: 999_999 }; }, + async recordEvent(event) { console.log(`DRY_RUN event ${JSON.stringify(event)}`); }, + }, run); } else if (command === "coordinate") { const event = JSON.parse(readFileSync(process.env.GITHUB_EVENT_PATH!, "utf8")); const repository = process.env.GITHUB_REPOSITORY!; @@ -117,6 +130,6 @@ if (import.meta.main) { !/^[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); - } else throw new Error("usage: bun scripts/red-main-cli.ts gate | coordinate | probe --target "); + } 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 10d1f5c620..67b23f45e4 100644 --- a/scripts/red-main-coordinator.ts +++ b/scripts/red-main-coordinator.ts @@ -114,7 +114,7 @@ export async function ensureIncident(io: CoordinatorIO, record: RedMainRecord): "Failing tests and categories:", ...open.failures.map(f => `- \`${f.test ?? f.category}\` (${f.category}; ${f.reasons.join(", ")}; run ${runUrl(io, f.run)})`), "", - "Hosted proof whose merge ref contains this commit is refused or cancelled, and `integrate.ts` refuses ordinary confirmation and merges, until a main run that includes this failing set is green. Declare a fix PR with `bun scripts/integrate.ts declare-fix `; the first confirmed fix wins.", + "Hosted proof whose merge ref contains this commit is refused or cancelled, and `integrate.ts` refuses ordinary confirmation and merges, until a main run that includes this failing set is green. Declare a fix PR with `bun scripts/integrate.ts declare-fix `; the first confirmed fix wins. Only a green main run that includes this failing set clears the record, so a failure that does not reproduce still needs a declared fix to land.", ...(related.size ? ["", `Possibly related open issues: ${[...related].sort((a, b) => a - b).map(n => `#${n}`).join(", ")}.`] : []), ]; const issue = await io.write("POST", `repos/${io.repository}/issues`, { From 07fd0ecc7cb1285e1a4130f2f0f8b5c0d885fb15 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 10:41:25 +0000 Subject: [PATCH 5/7] 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 | 20 ++- 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, 914 insertions(+), 62 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 77d60c37b4..d2439209bc 100644 --- a/.agents/skills/work-issue/SKILL.md +++ b/.agents/skills/work-issue/SKILL.md @@ -277,7 +277,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 5cb6cd8e01..698b2fd75c 100644 --- a/.agents/skills/work-issue/references/ci-and-merge.md +++ b/.agents/skills/work-issue/references/ci-and-merge.md @@ -268,6 +268,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)). + ## Merge and verify Before every merge, assign the PR and each completed/advanced issue a release 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 1e05b13b4a..b5c4fdaf8e 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 @@ -1484,7 +1490,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. ### Hosted heavy feedback on draft heads 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 bbe92e4bbc..dee7c30ebb 100644 --- a/docs/process/testing.md +++ b/docs/process/testing.md @@ -421,7 +421,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 7ce6539951..cd059f74c2 100644 --- a/scripts/integrate.ts +++ b/scripts/integrate.ts @@ -4,7 +4,9 @@ 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, type RedMainRecord } from "./red-main"; +import { declareFix, recordExpedited, type RedMainRecord } from "./red-main"; +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 { @@ -69,6 +71,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); } @@ -87,11 +101,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; @@ -102,24 +159,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; @@ -154,6 +217,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.pr); if (command === "merge") { const lease = values.get("--lease"); @@ -161,7 +231,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 })); @@ -189,7 +282,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 89f3dacbf0..237ade56dd 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 67b23f45e4..d25de6611a 100644 --- a/scripts/red-main-coordinator.ts +++ b/scripts/red-main-coordinator.ts @@ -238,7 +238,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 15f54c7209..ac85d66949 100644 --- a/scripts/red-main.ts +++ b/scripts/red-main.ts @@ -16,15 +16,19 @@ 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[]; + /** Optional and additive: absent until an expedited fix lands. */ + expedited?: ExpeditedFix[]; } export interface Suspect { test: string; category: Category; run: number; sha: string; at: number; probe: "pending" | "passed" | "failed" | "unavailable"; issue: number | null; } export interface RedMainRecord { version: 1; updated: number; open: RedIncident | null; suspects: Suspect[]; - last: { action: "open" | "update" | "refine" | "incident" | "declare-fix" | "report" | "clear" | "suspect" | "probe"; at: number; run: number | null } | null; + last: { action: "open" | "update" | "refine" | "incident" | "declare-fix" | "report" | "clear" | "suspect" | "probe" | "expedite"; at: number; run: number | null } | null; } export const emptyRedMain = (): RedMainRecord => ({ version: 1, updated: 0, open: null, suspects: [], last: null }); @@ -45,9 +49,11 @@ 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 (r.last !== null && (!r.last || r.last.at !== r.updated || !(r.last.run === null || positive(r.last.run)) || - !["open", "update", "refine", "incident", "declare-fix", "report", "clear", "suspect", "probe"].includes(r.last.action))) throw new Error("Invalid red-main audit"); + !["open", "update", "refine", "incident", "declare-fix", "report", "clear", "suspect", "probe", "expedite"].includes(r.last.action))) throw new Error("Invalid red-main audit"); return r; } @@ -89,6 +95,14 @@ export function declareFix(record: RedMainRecord, pr: number, now: number): RedM return next(record, now, "declare-fix", null, { open: { ...record.open, fixes: [...record.open.fixes, pr] } }); } +/** 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 { if (!record.open || record.open.reported.includes(sha)) return record; return next(record, now, "report", null, { open: { ...record.open, reported: [...record.open.reported, sha].slice(-MAX_REPORTED) } }); 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 1756f8876b..25cf67f0d6 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}); @@ -125,7 +141,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")]}; @@ -148,7 +167,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; @@ -159,7 +179,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]); @@ -275,3 +297,42 @@ test("while main is red the shared merge refuses non-fix candidates and still me expect(fix.code, `DECLARED_FIX_MERGES: ${fix.err}`).toBe(2); expect(fix.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 39996cf2ee..78d1b261db 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 { planChecks, workspaces } 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"; @@ -274,3 +274,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 c445ed57fd7e2646ef326be8b4ed975ac442bbe5 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 11:23:48 +0000 Subject: [PATCH 6/7] feat(ci): hold proof-system candidates behind a two-green-main window and off-main qualification integrate.ts confirm and merge classify the candidate (merge base to head) with classify() from scripts/proof-system.ts. A proof-system candidate is refused unless the last proof-system squash on main has a completed, green main-push run at its own squash and at each of the next two (#2938 ruling, answers 1-2), and unless its PR body has an "Off-main qualification" section linking a run of this repository on the exact head or on an ancestor with no proof-system change after it (answer 3). The refusal names the blocking squash, the runs found and the green runs still required, or the missing evidence. `integrate.ts lane --json` reports the same decision from the same function, reading at most three runs. Product candidates are never held; declared red-main fixes (expedited or ordinary) are exempt. Closes #3269 Closes #3271 Co-Authored-By: Claude Opus 5.5 --- .../work-issue/references/ci-and-merge.md | 10 + .github/PULL_REQUEST_TEMPLATE.md | 9 + docs/decisions/ci-utility.md | 31 ++++ scripts/integrate.ts | 46 ++++- scripts/proof-system-lane.ts | 172 ++++++++++++++++++ tests/integration-command.test.ts | 91 ++++++++- tests/proof-system-lane.test.ts | 124 +++++++++++++ 7 files changed, 474 insertions(+), 9 deletions(-) create mode 100644 scripts/proof-system-lane.ts create mode 100644 tests/proof-system-lane.test.ts diff --git a/.agents/skills/work-issue/references/ci-and-merge.md b/.agents/skills/work-issue/references/ci-and-merge.md index 698b2fd75c..58cce4e8f7 100644 --- a/.agents/skills/work-issue/references/ci-and-merge.md +++ b/.agents/skills/work-issue/references/ci-and-merge.md @@ -275,6 +275,16 @@ 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)). +A proof-system candidate (`bun scripts/proof-system.ts classify --base +--head `) waits its turn in the proof-system lane. `confirm` (before +acquiring) and `merge` refuse it until the last proof-system squash on main +has a green main-push run at its own squash and at each of the next two, and +until its PR body has an `## Off-main qualification` section linking a replay +or dispatch run on the exact head, or on an ancestor with no proof-system +change after it. Read the window with `bun scripts/integrate.ts lane --json` +instead of polling runs; product candidates and declared red-main fixes are +never held ([proof-system lane](../../../../docs/decisions/ci-utility.md#lane-and-qualification-gates)). + 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 diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 19e997ddeb..eb9bf97682 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -38,6 +38,15 @@ bun run check:pr --base origin/main tested parent/head/checkout and selected proof; see docs/process/github.md#stacked-pull-requests. --> + +### Off-main qualification + |$)/g, "").split("\n"); + const heading = (line: string) => /^(#{1,6})\s+(.*?)\s*#*\s*$/.exec(line); + const start = lines.findIndex(line => heading(line)?.[2]?.toLowerCase() === QUALIFICATION_HEADING.toLowerCase()); + if (start < 0) return null; + const level = heading(lines[start]!)![1]!.length, section: string[] = []; + for (const line of lines.slice(start + 1)) { + const next = heading(line); + if (next && next[1]!.length <= level) break; + section.push(line); + } + return section.join("\n"); +} + +/** GitHub Actions run IDs linked from `text` for `repository` (owner/name), in order. */ +export function qualificationRunIds(text: string, repository: string): number[] { + const ids: number[] = []; + for (const match of text.matchAll(/https:\/\/github\.com\/([\w.-]+\/[\w.-]+)\/actions\/runs\/([1-9]\d*)/g)) { + const id = Number(match[2]); + if (match[1]!.toLowerCase() === repository.toLowerCase() && Number.isSafeInteger(id) && !ids.includes(id)) ids.push(id); + } + return ids; +} + +export interface QualificationRun { id: number; headSha: string | null; repository: string | null } +export interface QualificationEvidence { run: number; headSha: string; via: "head" | "ancestor" } + +/** Whether a run's head SHA qualifies `head`: it is the head, or an ancestor + * whose diff to the head is not a proof-system change. Returns why not. */ +export function qualifies(run: QualificationRun, repository: string, head: string, options: ClassifyOptions = {}): "head" | "ancestor" | string { + if (run.repository?.toLowerCase() !== repository.toLowerCase()) return `run ${run.id} is not a run in ${repository}`; + if (!run.headSha || !/^[a-f0-9]{40}$/.test(run.headSha)) return `run ${run.id} has no head SHA`; + if (run.headSha === head) return "head"; + const cwd = options.cwd ?? process.cwd(); + const ancestor = Bun.spawnSync(["git", "merge-base", "--is-ancestor", run.headSha, head], { cwd, stdout: "pipe", stderr: "pipe" }); + if (ancestor.exitCode !== 0) return `run ${run.id} ran on ${short(run.headSha)}, which is not an ancestor of the head ${short(head)}`; + const after = classify(run.headSha, head, options); + if (after.proofSystem) return `run ${run.id} ran on ${short(run.headSha)}, and the diff from there to the head is a proof-system change (${after.reasons.map(r => r.path).filter((p, i, all) => all.indexOf(p) === i).join(", ")})`; + return "ancestor"; +} + +/** Off-main qualification for a proof-system candidate: evidence, or the refusal naming what is missing. */ +export async function checkQualification(input: { body: string | null | undefined; repository: string; head: string; + readRun: (id: number) => Promise; ensure?: (sha: string) => void } & ClassifyOptions, +): Promise<{ evidence: QualificationEvidence } | { refusal: string }> { + const how = `Add an "## ${QUALIFICATION_HEADING}" section to the PR body naming the replay or dispatch run URLs (https://github.com/${input.repository}/actions/runs/), the head SHA they ran on and the comparison they establish`; + const section = qualificationSection(input.body); + if (section === null) return { refusal: `Off-main qualification missing: the PR body has no "${QUALIFICATION_HEADING}" section. ${how}` }; + const ids = qualificationRunIds(section, input.repository); + if (!ids.length) return { refusal: `Off-main qualification missing: the "${QUALIFICATION_HEADING}" section links no GitHub Actions run in ${input.repository}. ${how}` }; + const problems: string[] = []; + for (const id of ids.slice(0, MAX_QUALIFICATION_RUNS)) { + const run = await input.readRun(id); + if (!run) { problems.push(`run ${id} was not found`); continue; } + if (run.headSha && run.headSha !== input.head && input.ensure) { + try { input.ensure(run.headSha); } catch { problems.push(`run ${id} ran on ${short(run.headSha)}, which cannot be fetched`); continue; } + } + const verdict = qualifies(run, input.repository, input.head, input); + if (verdict === "head" || verdict === "ancestor") return { evidence: { run: id, headSha: run.headSha!, via: verdict } }; + problems.push(verdict); + } + return { refusal: `Off-main qualification missing: no linked run ran on the head ${short(input.head)} or on an ancestor with no proof-system change after it (${problems.join("; ")}). ${how}` }; +} diff --git a/tests/integration-command.test.ts b/tests/integration-command.test.ts index 25cf67f0d6..c621c3f64f 100644 --- a/tests/integration-command.test.ts +++ b/tests/integration-command.test.ts @@ -65,12 +65,28 @@ async function runScenario(mode: string, owner: Scenario): Promise = {}; + const commitAll = (name: string, parents: string[]) => { setup(root, "add", "."); return setup(root, "commit-tree", setup(root, "write-tree"), ...parents.flatMap(parent => ["-p", parent]), "-m", name); }; + if (lane) { + history.ithaca = commitAll("ithaca", []); + mkdirSync(join(root, ".github/workflows"), { recursive: true }); writeFileSync(join(root, ".github/workflows/ci.yml"), "name: ci\n"); + history.sails = commitAll("sails", [history.ithaca]); + writeFileSync(join(root, "oars.md"), "Oars.\n"); history.oars = commitAll("oars", [history.sails]); + } + const base = commitAll("base", lane ? [history.oars!] : []); setup(root, "update-ref", "HEAD", base); + let headParent = base; + if (lane && !mode.includes("-product")) { + mkdirSync(join(root, "scripts")); writeFileSync(join(root, "scripts/ci-shards.ts"), "export const shards = 3;\n"); + headParent = history.shards = commitAll("shards", [base]); + } writeFileSync(join(root, "raft.md"), "The crossing.\n"); setup(root, "add", "."); // A targeted revert deletes the failing test file its reverted commit added. if (mode === "expedite-revert") setup(root, "rm", "-q", "--cached", "tests/raft.test.ts"); - const tree = setup(root, "write-tree"), head = setup(root, "commit-tree", tree, "-p", base, "-m", "head"); + const tree = setup(root, "write-tree"), head = setup(root, "commit-tree", tree, "-p", headParent, "-m", "head"); const synthetic = setup(root, "commit-tree", tree, "-p", base, "-p", head, "-m", "tested merge"); const squash = setup(root, "commit-tree", tree, "-p", base, "-m", "actual squash"); setup(root, "push", "origin", `${base}:refs/heads/main`, `${synthetic}:refs/heads/proof-fixture`, `${squash}:refs/heads/squash-fixture`); @@ -82,7 +98,7 @@ async function runScenario(mode: string, owner: Scenario): Promise ({ id, status: conclusion ? "completed" : "in_progress", conclusion }); + const mainRuns: Record> = !lane ? {} : { [history.sails!]: window(81, "success"), [history.oars!]: window(82, "success"), + ...(mode.includes("lane-short") ? {} : { [base]: window(83, mode.includes("cancelled") ? "cancelled" : "success") }) }; 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 }); @@ -115,6 +137,7 @@ fi`); chmodSync(shim, 0o755); 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)}, body=${JSON.stringify(body)}, probes=${JSON.stringify({ 401: probeLog(401), 402: probeLog(402) })};s.reads??=[]; + const mainRuns=${JSON.stringify(mainRuns)}, qualificationRuns=${JSON.stringify(qualificationRuns)}; const repo="odysseus/brain-kit", base=candidate.base, head=candidate.head, squash=${JSON.stringify(squash)}; const categories=["verify","pack","unit","browser","layout","captures","runtime","runtime_host","endurance"]; const selected={selections:Object.fromEntries(categories.map(x=>[x,"false"])),results:Object.fromEntries(categories.map(x=>[x,"skipped"])),retained:[],unitShards:null}; @@ -146,7 +169,8 @@ fi`); chmodSync(shim, 0o755); 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?event=push"))value={workflow_runs:Object.entries(mainRuns).filter(([sha])=>path.includes("head_sha="+sha)).map(([sha,run])=>({...run,head_sha:sha}))}; + else if(/actions\\/runs\\/555$/.test(path))value={id:555,head_sha:qualificationRuns[555],repository:{full_name:repo}}; else if(path.includes("actions/workflows/ci.yml/runs"))value={workflow_runs:[run(s.mode.startsWith("confirm-")&&!s.requested?90:91,"ci")]}; else if(path.includes("actions/workflows/contract.yml/runs"))value={workflow_runs:[run(92,"contract")]}; else if(path.includes("/attempts/1/jobs"))value={total_count:jobs.length,jobs}; @@ -167,8 +191,9 @@ 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(","), - ...(mode.startsWith("expedite-") ? ["--fixes-main-run", "11"] : [])], { + const command = mode.endsWith("-read") ? ["lane", "--json"] : [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"] : [])]; + const child = invocationChild([process.execPath, ...(mode.startsWith("confirm-") ? ["--preload", preload] : []), resolve(import.meta.dir, "../scripts/integrate.ts"), ...command], { cwd: root, env: { ...process.env, PATH: `${bin}:${process.env.PATH ?? ""}` }, }); owner.child = child; @@ -336,3 +361,55 @@ test("expedited fix merges only with red-on-base and green-on-head evidence, and 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" }]); } }); + +test("a proof-system candidate waits for the two-green-main stability window; a product candidate does not (#3269)", async () => { + for (const mode of ["lane-short", "lane-cancelled", "confirm-lane-short"]) { + const refused = await scenario(mode); + expect(refused.dispatched, `NO_PROOF_SYSTEM_MERGE_INSIDE_THE_WINDOW:${mode}`).toBe(false); + expect(refused.code, refused.err).toBe(1); + expect(refused.err).toContain("Proof-system candidate refused (scripts/ci-shards.ts)"); + expect(refused.err).toContain("1 more green main run required"); + expect(refused.err).not.toContain("Off-main qualification missing"); + expect(refused.state.active, `REFUSED_BEFORE_OWNERSHIP_OR_RELEASED:${mode}`).toBeNull(); + } + for (const mode of ["lane-short-product", "lane-open"]) { + const accepted = await scenario(mode); + expect(accepted.code, `LANE_ACCEPTS:${mode}: ${accepted.err}`).toBe(2); + expect(accepted.dispatched).toBe(true); + } +}); + +test("lane --json reports the refusal's decision from the same function (#3269)", async () => { + const read = await scenario("lane-short-read"); + expect(read.code, read.err).toBe(0); + const decision = JSON.parse(read.out); + expect(decision).toMatchObject({ schemaVersion: 1, open: false, missing: 1, window: [{ position: 0, green: true, run: { id: 81 } }, { position: 1, green: true, run: { id: 82 } }, { position: 2, green: false, run: null }] }); + expect(decision.refusal).toContain("1 more green main run required"); + expect(decision.refusal).toContain(`the last proof-system squash ${decision.proofSystemSquash}`); + const open = await scenario("lane-open-read"); + expect(JSON.parse(open.out), open.err).toMatchObject({ open: true, missing: 0, refusal: null }); +}); + +test("a proof-system candidate needs off-main qualification on its head or a proof-system-free ancestor (#3271)", async () => { + for (const [mode, message] of [ + ["lane-open-unqualified", 'no "Off-main qualification" section'], + ["lane-open-stale-run", "the diff from there to the head is a proof-system change (scripts/ci-shards.ts)"], + ] as const) { + const refused = await scenario(mode); + expect(refused.dispatched, `NO_UNQUALIFIED_PROOF_SYSTEM_MERGE:${mode}`).toBe(false); + expect(refused.code, refused.err).toBe(1); + expect(refused.err).toContain("Off-main qualification missing"); + expect(refused.err).toContain(message); + } + const ancestor = await scenario("lane-open-ancestor-run"); + expect(ancestor.code, `QUALIFIED_BY_A_PROOF_SYSTEM_FREE_ANCESTOR: ${ancestor.err}`).toBe(2); + expect(ancestor.dispatched).toBe(true); +}); + +test("declared red-main fixes are exempt from the stability window and off-main qualification (#3269, #3271)", async () => { + for (const mode of ["expedite-lane-short", "red-main-fix-lane-short"]) { + const fix = await scenario(mode); + expect(fix.code, `DECLARED_FIX_EXEMPT:${mode}: ${fix.err}`).toBe(2); + expect(fix.dispatched).toBe(true); + } +}); diff --git a/tests/proof-system-lane.test.ts b/tests/proof-system-lane.test.ts new file mode 100644 index 0000000000..6bcdf82446 --- /dev/null +++ b/tests/proof-system-lane.test.ts @@ -0,0 +1,124 @@ +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { tmpdir } from "node:os"; +import { checkQualification, decideLane, isGreen, laneRefusal, lastProofSystemSquash, qualificationRunIds, qualificationSection, readLane, + type MainRun, type QualificationRun } from "../scripts/proof-system-lane"; + +// Odysseus's fleet history on main: a product squash, a proof-system squash, +// then two product squashes. A side branch carries a candidate whose first +// commit changes the proof system and whose second does not. +let dir = ""; +const sha: Record = {}; +function git(...args: string[]) { + const result = Bun.spawnSync(["git", ...args], { cwd: dir, stdout: "pipe", stderr: "pipe", env: { ...process.env, + GIT_AUTHOR_NAME: "Odysseus", GIT_AUTHOR_EMAIL: "odysseus@example.invalid", GIT_COMMITTER_NAME: "Odysseus", GIT_COMMITTER_EMAIL: "odysseus@example.invalid", + GIT_AUTHOR_DATE: "2026-07-12T00:00:00Z", GIT_COMMITTER_DATE: "2026-07-12T00:00:00Z" } }); + expect(result.exitCode, result.stderr.toString()).toBe(0); + return result.stdout.toString().trim(); +} +function commit(name: string, files: Record) { + for (const [path, text] of Object.entries(files)) { mkdirSync(join(dir, dirname(path)), { recursive: true }); writeFileSync(join(dir, path), text); } + git("add", "."); git("commit", "-q", "-m", name); sha[name] = git("rev-parse", "HEAD"); +} +beforeAll(() => { + dir = mkdtempSync(join(tmpdir(), "odysseus-lane-")); + git("init", "-q", "-b", "main"); + commit("ithaca", { "README.md": "Ithaca.\n" }); + commit("raft", { "raft.md": "The raft.\n" }); + commit("sails", { ".github/workflows/ci.yml": "name: ci\n" }); + commit("oars", { "oars.md": "Oars.\n" }); + commit("mast", { "mast.md": "Mast.\n" }); + git("checkout", "-q", "-b", "candidate"); + commit("shards", { "scripts/ci-shards.ts": "export const shards = 3;\n" }); + commit("chart", { "chart.md": "The chart.\n" }); + git("checkout", "-q", "main"); +}); +afterAll(() => rmSync(dir, { recursive: true, force: true })); + +const green = (id: number): MainRun => ({ id, status: "completed", conclusion: "success" }); +const runs = (entries: Record) => new Map(Object.entries(entries).map(([name, run]) => [sha[name]!, run])); + +describe("stability window (#3269)", () => { + test("finds the last proof-system squash and the squashes after it", () => { + expect(lastProofSystemSquash(sha.mast!, { cwd: dir })).toEqual({ squash: sha.sails!, later: [sha.oars!, sha.mast!], scanned: 3 }); + expect(lastProofSystemSquash(sha.oars!, { cwd: dir })).toEqual({ squash: sha.sails!, later: [sha.oars!], scanned: 2 }); + expect(lastProofSystemSquash(sha.raft!, { cwd: dir })).toEqual({ squash: null, later: [], scanned: 2 }); + }); + + test("own run green and only one later green run: 1 more green main run required", () => { + const history = lastProofSystemSquash(sha.mast!, { cwd: dir }); + const decision = decideLane(sha.mast!, history, runs({ sails: green(1), oars: green(2), mast: null })); + expect(decision.open).toBe(false); + expect(decision.missing).toBe(1); + expect(laneRefusal(decision)).toContain("1 more green main run required"); + expect(laneRefusal(decision)).toContain(`the last proof-system squash ${sha.sails}`); + expect(laneRefusal(decision)).toContain("next run 2 at"); + }); + + test("own run and two later green runs open the lane", () => { + const history = lastProofSystemSquash(sha.mast!, { cwd: dir }); + const decision = decideLane(sha.mast!, history, runs({ sails: green(1), oars: green(2), mast: green(3) })); + expect(decision).toMatchObject({ open: true, missing: 0, proofSystemSquash: sha.sails }); + expect(laneRefusal(decision)).toBeNull(); + }); + + test("a missing, in-progress, cancelled or failed window run is not green", () => { + const history = lastProofSystemSquash(sha.mast!, { cwd: dir }); + for (const run of [null, { id: 3, status: "in_progress", conclusion: null }, { id: 3, status: "queued", conclusion: null }, + { id: 3, status: "completed", conclusion: "cancelled" }, { id: 3, status: "completed", conclusion: "failure" }, + { id: 3, status: "completed", conclusion: "skipped" }, { id: 3, status: "completed", conclusion: "timed_out" }]) { + expect(isGreen(run), `NOT_GREEN:${JSON.stringify(run)}`).toBe(false); + const decision = decideLane(sha.mast!, history, runs({ sails: green(1), oars: green(2), mast: run })); + expect(decision.open, `LANE_CLOSED:${JSON.stringify(run)}`).toBe(false); + expect(laneRefusal(decision)).toContain("1 more green main run required"); + } + // A squash with no later main squash yet counts as missing too. + const fresh = decideLane(sha.sails!, lastProofSystemSquash(sha.sails!, { cwd: dir }), runs({ sails: green(1) })); + expect(laneRefusal(fresh)).toContain("2 more green main runs required"); + expect(laneRefusal(fresh)).toContain("next run 1: no main squash yet"); + }); + + test("readLane reads at most the window's runs and agrees with the refusal", async () => { + const asked: string[] = []; + const decision = await readLane(sha.mast!, async at => { asked.push(at); return at === sha.mast ? { id: 3, status: "completed", conclusion: "cancelled" } : green(1); }, { cwd: dir }); + expect(asked).toEqual([sha.sails!, sha.oars!, sha.mast!]); + expect(decision).toMatchObject({ open: false, missing: 1 }); + expect(laneRefusal(decision)).toContain("run 3 cancelled"); + const product = await readLane(sha.raft!, async () => { throw new Error("NO_RUN_READ_WITHOUT_A_PROOF_SYSTEM_SQUASH"); }, { cwd: dir }); + expect(product).toMatchObject({ open: true, proofSystemSquash: null }); + }); +}); + +describe("off-main qualification (#3271)", () => { + const repository = "odysseus/brain-kit"; + const url = (id: number, repo = repository) => `https://github.com/${repo}/actions/runs/${id}`; + const body = (section: string) => `Odysseus re-rigs the shards.\n\n## Off-main qualification\n\n${section}\n\n## Anything left open\n\n${url(999)}\n`; + const check = (text: string | null, runsById: Record) => checkQualification({ body: text, repository, head: sha.chart!, cwd: dir, + async readRun(id): Promise { return runsById[id] ? { id, headSha: runsById[id]!, repository } : null; } }); + + test("reads only the qualification section, without comments, and only this repository's runs", () => { + const text = body(`\nReplay ${url(2)} and ${url(3, "circe/brain-kit")} and ${url(2)}/attempts/1`); + expect(qualificationRunIds(qualificationSection(text)!, repository)).toEqual([2]); + expect(qualificationSection("## Proof\n\nnone")).toBeNull(); + }); + + test("a body without the section is refused, naming the missing evidence", async () => { + const result = await check("Odysseus re-rigs the shards.", {}); + expect(result).toEqual({ refusal: expect.stringContaining('no "Off-main qualification" section') }); + const empty = await check(body("Replayed by hand."), {}); + expect(empty).toEqual({ refusal: expect.stringContaining("links no GitHub Actions run in odysseus/brain-kit") }); + }); + + test("a run on the head, or on an ancestor with no proof-system change after it, qualifies", async () => { + expect(await check(body(`Replay ${url(41)} on the head.`), { 41: sha.chart! })).toEqual({ evidence: { run: 41, headSha: sha.chart!, via: "head" } }); + expect(await check(body(`Dispatch ${url(42)}.`), { 42: sha.shards! })).toEqual({ evidence: { run: 42, headSha: sha.shards!, via: "ancestor" } }); + }); + + test("a run whose head SHA has proof-system changes after it is refused", async () => { + const result = await check(body(`Replay ${url(43)}.`), { 43: sha.mast! }); + expect(result).toEqual({ refusal: expect.stringContaining("is a proof-system change (scripts/ci-shards.ts)") }); + const unrelated = await check(body(`Replay ${url(44)}.`), { 44: sha.raft!.replace(/^./, c => c === "a" ? "b" : "a") }); + expect(unrelated).toEqual({ refusal: expect.stringContaining("not an ancestor of the head") }); + }); +}); From 5224e5ff75e4c66570b563509de706d21c03884b Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 11:32:38 +0000 Subject: [PATCH 7/7] feat(ci): reopen the proof-system lane after two consecutive green main runs Apply the maintainer's clarification of the stability window (#3269, issuecomment-6575963951): the proof-system squash's own main run must be green, then two consecutive later main runs must be completed and green. A failed or cancelled run restarts the count instead of keeping the lane closed until a rerun or revoke. Queued, in-progress or not-yet-created runs are not green yet. The decision reads at most ten main runs in merge order, stops once decided, and reports `unknown` (refused) past that bound. `lane --json` reports state, ownGreen, streak and required. Refs #3269 Co-Authored-By: Claude Opus 5.5 --- .../work-issue/references/ci-and-merge.md | 3 +- docs/decisions/ci-utility.md | 29 +++-- scripts/proof-system-lane.ts | 96 ++++++++++----- tests/integration-command.test.ts | 22 +++- tests/proof-system-lane.test.ts | 113 ++++++++++++------ 5 files changed, 179 insertions(+), 84 deletions(-) diff --git a/.agents/skills/work-issue/references/ci-and-merge.md b/.agents/skills/work-issue/references/ci-and-merge.md index 58cce4e8f7..02fa6aa6b3 100644 --- a/.agents/skills/work-issue/references/ci-and-merge.md +++ b/.agents/skills/work-issue/references/ci-and-merge.md @@ -278,7 +278,8 @@ receipt, or get the category selected; never edit a receipt by hand A proof-system candidate (`bun scripts/proof-system.ts classify --base --head `) waits its turn in the proof-system lane. `confirm` (before acquiring) and `merge` refuse it until the last proof-system squash on main -has a green main-push run at its own squash and at each of the next two, and +has a green main-push run at its own squash followed by two consecutive green +main runs (a failure restarts that count), and until its PR body has an `## Off-main qualification` section linking a replay or dispatch run on the exact head, or on an ancestor with no proof-system change after it. Read the window with `bun scripts/integrate.ts lane --json` diff --git a/docs/decisions/ci-utility.md b/docs/decisions/ci-utility.md index a5aa8f29e7..03cf5a2ce2 100644 --- a/docs/decisions/ci-utility.md +++ b/docs/decisions/ci-utility.md @@ -1438,17 +1438,24 @@ and `lane --json` live in `scripts/proof-system-lane.ts`; neither lists a glob. - **Stability window** ([#3269](https://github.com/schlessera/brain-kit/issues/3269), - answers 1 and 2). The last proof-system squash is the newest first-parent - main commit, within 200, whose diff to its parent classifies as one. The - window is that squash and the next two main squashes. Each needs the newest - main-push `ci.yml` run at that SHA completed with `success`; a missing, - queued, in-progress, cancelled or failed run, or a squash not yet made, is - not green. A failed window run therefore keeps the lane closed until a - rerun at the same squash succeeds or a maintainer revokes. The refusal - names the blocking squash, the run found at each position and how many - green runs are still required. `bun scripts/integrate.ts lane --json` - prints the same decision with that refusal, or `null` when the lane is - open. It reads at most three runs. + answers 1 and 2, with the maintainer's + [clarification of how it reopens](https://github.com/schlessera/brain-kit/issues/3269#issuecomment-6575963951)). + The last proof-system squash is the newest first-parent main commit, within + 200, whose diff to its parent classifies as one. Each squash's run is the + newest main-push `ci.yml` run at that SHA. The squash's own run must be + completed and green. After it, two consecutive later main runs must be + completed and green. A failed or cancelled run restarts that count, so the + lane reopens once two consecutive green runs follow the failure; no rerun + or revoke is needed. A squash with no run restarts the count once a later + squash exists. A queued or in-progress run, or no run yet at the newest + squash, is not green yet, and nothing after it counts. The check reads at + most ten main runs, in merge order, and stops as soon as it has decided. If + ten runs show no two consecutive greens while later squashes exist, the + lane is `unknown` and refused. The refusal names the blocking squash, the + run found at each squash it read and how many green runs are still + required. `bun scripts/integrate.ts lane --json` prints the same decision + (`state`, `ownGreen`, `streak`, `required`, `window`) with that refusal, or + `null` when the lane is open. - **Off-main qualification** ([#3271](https://github.com/schlessera/brain-kit/issues/3271), answer 3). The PR body needs an `Off-main qualification` heading whose section, outside HTML comments, links a GitHub Actions run of this diff --git a/scripts/proof-system-lane.ts b/scripts/proof-system-lane.ts index 30c0e3b484..e091c51def 100644 --- a/scripts/proof-system-lane.ts +++ b/scripts/proof-system-lane.ts @@ -1,5 +1,5 @@ /** The proof-system lane's merge gates (docs/decisions/ci-utility.md, - * "Proof-system lane", answers 1–3): the two-green-main stability window + * "Proof-system lane", answers 1–3): the two-consecutive-green-main stability window * (#3269) and off-main qualification evidence on the PR (#3271). * * `integrate.ts confirm` and `merge` refuse a proof-system candidate with the @@ -8,12 +8,16 @@ * `classify` from `scripts/proof-system.ts`; this file lists no globs. * * Every GitHub read goes through a caller-supplied lookup so the gate stays - * bounded: at most `WINDOW` main-run reads and `MAX_QUALIFICATION_RUNS` run + * bounded: at most `MAX_MAIN_RUNS` main-run reads and `MAX_QUALIFICATION_RUNS` run * reads per decision. */ import { classify, type ClassifyOptions } from "./proof-system"; -/** The proof-system squash's own main run plus the next two (answer 2). */ -export const WINDOW = 3; +/** Consecutive completed-green main runs required after the proof-system + * squash's own green run, and again after any later failure (answer 2, as + * clarified on #3269, issuecomment-6575963951). */ +export const STREAK = 2; +/** Main-push runs one lane decision reads at most: the own run and up to nine later ones. */ +export const MAX_MAIN_RUNS = 10; /** First-parent main squashes examined for the last proof-system change. */ export const SCAN_LIMIT = 200; /** Run URLs read from one PR body's qualification section. */ @@ -21,7 +25,8 @@ export const MAX_QUALIFICATION_RUNS = 5; export const QUALIFICATION_HEADING = "Off-main qualification"; export interface MainRun { id: number; status: string; conclusion: string | null } -export interface WindowEntry { position: number; sha: string | null; run: MainRun | null; green: boolean } +/** One main squash the decision read, in merge order; position 0 is the proof-system squash itself. */ +export interface WindowEntry { position: number; sha: string; run: MainRun | null; green: boolean } export interface LaneDecision { schemaVersion: 1; /** The main squash the history was read from. */ @@ -29,10 +34,17 @@ export interface LaneDecision { /** The most recent proof-system squash within the scan, or null. */ proofSystemSquash: string | null; scanned: number; - window: WindowEntry[]; - /** Window positions without a completed, successful main-push run. */ - missing: number; + /** `unknown`: no two consecutive green runs within `MAX_MAIN_RUNS` while later squashes exist. */ + state: "open" | "closed" | "unknown"; open: boolean; + ownGreen: boolean | null; + /** Consecutive green later runs counted when the decision stopped. */ + streak: number; + /** Green main runs still required, or null when unknown. */ + required: number | null; + window: WindowEntry[]; + /** The squash whose run the decision needs next; null once decided. */ + next: string | null; } function git(cwd: string, args: string[]): string { @@ -47,11 +59,12 @@ export function isGreen(run: MainRun | null): boolean { return run?.status === "completed" && run.conclusion === "success"; } -export interface ProofSystemHistory { squash: string | null; later: string[]; scanned: number } +/** `later` holds at most `MAX_MAIN_RUNS - 1` squashes after the proof-system + * squash, in merge order; `more` says whether main has squashes beyond them. */ +export interface ProofSystemHistory { squash: string | null; later: string[]; more: boolean; scanned: number } /** The most recent first-parent squash at or before `main` whose diff to its - * parent is a proof-system change, and up to `WINDOW - 1` squashes after it in - * merge order. */ + * parent is a proof-system change, and the squashes after it within the bound. */ export function lastProofSystemSquash(main: string, options: ClassifyOptions & { limit?: number } = {}): ProofSystemHistory { const cwd = options.cwd ?? process.cwd(); const lines = git(cwd, ["rev-list", "--first-parent", "--parents", `--max-count=${options.limit ?? SCAN_LIMIT}`, main]).split("\n").filter(Boolean); @@ -60,40 +73,60 @@ export function lastProofSystemSquash(main: string, options: ClassifyOptions & { const [sha, parent] = line.split(" ") as [string, string | undefined]; newestFirst.push(sha); if (parent && classify(parent, sha, options).proofSystem) { - const index = newestFirst.length - 1; - return { squash: sha, later: newestFirst.slice(Math.max(0, index - (WINDOW - 1)), index).reverse(), scanned: newestFirst.length }; + const index = newestFirst.length - 1, from = Math.max(0, index - (MAX_MAIN_RUNS - 1)); + return { squash: sha, later: newestFirst.slice(from, index).reverse(), more: from > 0, scanned: newestFirst.length }; } } - return { squash: null, later: [], scanned: newestFirst.length }; + return { squash: null, later: [], more: false, scanned: newestFirst.length }; } -/** The stability-window decision for a history and the main-push runs found - * at its squashes. Pure: `lane --json` and the refusal both read it. */ +/** The stability-window decision from the runs read so far. Pure: `lane + * --json` and the refusal both read it, and `readLane` reads the run it names + * in `next` until it is null. + * + * The own run must be green. Later runs then count toward `STREAK` + * consecutive greens; a completed run that is not green (failed, cancelled, + * timed out) restarts the count, and so does a squash with no run when a later + * squash exists. A queued or in-progress run, or a missing run at the newest + * squash, is pending: the count stops there, not yet green. */ export function decideLane(main: string, history: ProofSystemHistory, runs: ReadonlyMap): LaneDecision { - if (!history.squash) return { schemaVersion: 1, main, proofSystemSquash: null, scanned: history.scanned, window: [], missing: 0, open: true }; + const base = { schemaVersion: 1 as const, main, proofSystemSquash: history.squash, scanned: history.scanned }; + if (!history.squash) return { ...base, state: "open", open: true, ownGreen: null, streak: 0, required: 0, window: [], next: null }; + const window: WindowEntry[] = []; + const closed = (ownGreen: boolean, streak: number, next: string | null = null): LaneDecision => + ({ ...base, state: "closed", open: false, ownGreen, streak, required: (ownGreen ? 0 : 1) + STREAK - streak, window, next }); const shas = [history.squash, ...history.later]; - const window = Array.from({ length: WINDOW }, (_, position): WindowEntry => { - const sha = shas[position] ?? null, run = sha ? runs.get(sha) ?? null : null; - return { position, sha, run, green: isGreen(run) }; - }); - const missing = window.filter(entry => !entry.green).length; - return { schemaVersion: 1, main, proofSystemSquash: history.squash, scanned: history.scanned, window, missing, open: missing === 0 }; + let streak = 0; + for (const [position, sha] of shas.entries()) { + if (!runs.has(sha)) return closed(position > 0, streak, sha); + const run = runs.get(sha) ?? null, green = isGreen(run); + window.push({ position, sha, run, green }); + const pending = run ? run.status !== "completed" : position === shas.length - 1 && !history.more; + if (position === 0) { if (!green) return closed(false, 0); continue; } + if (green) { if (++streak === STREAK) return { ...base, state: "open", open: true, ownGreen: true, streak, required: 0, window, next: null }; } + else if (pending) return closed(true, streak); + else streak = 0; + } + if (history.more) return { ...base, state: "unknown", open: false, ownGreen: true, streak, required: null, window, next: null }; + return closed(true, streak); } -/** Reads the decision: local first-parent history plus at most `WINDOW` run lookups. */ +/** Reads the decision: local first-parent history plus at most `MAX_MAIN_RUNS` run lookups, in merge order. */ export async function readLane(main: string, runAt: (sha: string) => Promise, options: ClassifyOptions = {}): Promise { const cwd = options.cwd ?? process.cwd(); const resolved = git(cwd, ["rev-parse", "--verify", "--end-of-options", `${main}^{commit}`]); const history = lastProofSystemSquash(resolved, options); const runs = new Map(); - for (const sha of history.squash ? [history.squash, ...history.later] : []) runs.set(sha, await runAt(sha)); - return decideLane(resolved, history, runs); + for (;;) { + const decision = decideLane(resolved, history, runs); + if (!decision.next || runs.size >= MAX_MAIN_RUNS) return decision; + runs.set(decision.next, await runAt(decision.next)); + } } const short = (sha: string) => sha.slice(0, 12); function describe(entry: WindowEntry): string { const label = entry.position === 0 ? "own run" : `next run ${entry.position}`; - if (!entry.sha) return `${label}: no main squash yet`; if (!entry.run) return `${label} at ${short(entry.sha)}: no main-push CI run`; return `${label} at ${short(entry.sha)}: run ${entry.run.id} ${entry.run.status === "completed" ? entry.run.conclusion ?? "no conclusion" : entry.run.status}`; } @@ -101,8 +134,13 @@ function describe(entry: WindowEntry): string { /** The stability-window refusal, or null when the lane is open. */ export function laneRefusal(decision: LaneDecision): string | null { if (decision.open) return null; - return `Proof-system lane closed: the last proof-system squash ${decision.proofSystemSquash} needs its own main run and the next ${WINDOW - 1} main runs green (${decision.window.map(describe).join("; ")}); ` + - `${decision.missing} more green main run${decision.missing === 1 ? "" : "s"} required. A failed or cancelled window run counts only once a rerun at the same squash succeeds`; + const runs = decision.window.length ? decision.window.map(describe).join("; ") : "no main run read"; + const squash = `the last proof-system squash ${decision.proofSystemSquash}`; + if (decision.state === "unknown") return `Proof-system lane unknown: ${squash} has no ${STREAK} consecutive green main runs within the ${MAX_MAIN_RUNS} main runs this check reads (${runs}). Ask a maintainer to inspect main`; + const required = `${decision.required} more green main run${decision.required === 1 ? "" : "s"} required`; + if (!decision.ownGreen) return `Proof-system lane closed: ${squash} needs its own main run green first, then ${STREAK} consecutive green main runs (${runs}); ${required}. Rerun its main run if it failed or was cancelled`; + return `Proof-system lane closed: ${squash} needs ${STREAK} consecutive green main runs after its own green run (${runs}); ${required}. ` + + `A failed or cancelled run restarts the count; a queued or in-progress run is not green yet`; } /** The PR body's "Off-main qualification" section without HTML comments, or diff --git a/tests/integration-command.test.ts b/tests/integration-command.test.ts index c621c3f64f..57d38699bd 100644 --- a/tests/integration-command.test.ts +++ b/tests/integration-command.test.ts @@ -124,9 +124,12 @@ fi`); chmodSync(shim, 0o755); const qualification = lane && !mode.includes("unqualified") && !mode.startsWith("expedite-") ? `## Off-main qualification\n\nReplay https://github.com/odysseus/brain-kit/actions/runs/555 compares three shards with two.\n\n` : ""; const body = mode === "receipt-absent" || mode.startsWith("expedite-") ? "Odysseus builds a raft.\n" : `Odysseus builds a raft.\n\n${qualification}${receiptBlock(receipt)}\n`; const qualificationRuns = { 555: mode.includes("stale-run") ? base : mode.includes("ancestor-run") ? history.shards : head }; - // Main-push CI runs at the window squashes: sails and oars green; base green only once the lane is open. + // Main-push CI runs at sails (own), oars and base: all green once the lane + // is open; "-short" has no run at base yet, "-cancelled" a cancelled one, + // "-own-red" a failed own run and "-recovering" a failure at oars. const window = (id: number, conclusion: string | null) => ({ id, status: conclusion ? "completed" : "in_progress", conclusion }); - const mainRuns: Record> = !lane ? {} : { [history.sails!]: window(81, "success"), [history.oars!]: window(82, "success"), + const mainRuns: Record> = !lane ? {} : { [history.sails!]: window(81, mode.includes("own-red") ? "failure" : "success"), + [history.oars!]: window(82, mode.includes("recovering") ? "failure" : "success"), ...(mode.includes("lane-short") ? {} : { [base]: window(83, mode.includes("cancelled") ? "cancelled" : "success") }) }; 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 } @@ -363,12 +366,18 @@ test("expedited fix merges only with red-on-base and green-on-head evidence, and }); test("a proof-system candidate waits for the two-green-main stability window; a product candidate does not (#3269)", async () => { - for (const mode of ["lane-short", "lane-cancelled", "confirm-lane-short"]) { + for (const [mode, message] of [ + ["lane-short", "1 more green main run required"], + ["confirm-lane-short", "1 more green main run required"], + ["lane-cancelled", "2 more green main runs required"], + ["lane-recovering", "1 more green main run required"], + ["lane-own-red", "needs its own main run green first"], + ] as const) { const refused = await scenario(mode); expect(refused.dispatched, `NO_PROOF_SYSTEM_MERGE_INSIDE_THE_WINDOW:${mode}`).toBe(false); expect(refused.code, refused.err).toBe(1); expect(refused.err).toContain("Proof-system candidate refused (scripts/ci-shards.ts)"); - expect(refused.err).toContain("1 more green main run required"); + expect(refused.err).toContain(message); expect(refused.err).not.toContain("Off-main qualification missing"); expect(refused.state.active, `REFUSED_BEFORE_OWNERSHIP_OR_RELEASED:${mode}`).toBeNull(); } @@ -383,11 +392,12 @@ test("lane --json reports the refusal's decision from the same function (#3269)" const read = await scenario("lane-short-read"); expect(read.code, read.err).toBe(0); const decision = JSON.parse(read.out); - expect(decision).toMatchObject({ schemaVersion: 1, open: false, missing: 1, window: [{ position: 0, green: true, run: { id: 81 } }, { position: 1, green: true, run: { id: 82 } }, { position: 2, green: false, run: null }] }); + expect(decision).toMatchObject({ schemaVersion: 1, state: "closed", open: false, ownGreen: true, streak: 1, required: 1, next: null, + window: [{ position: 0, green: true, run: { id: 81 } }, { position: 1, green: true, run: { id: 82 } }, { position: 2, green: false, run: null }] }); expect(decision.refusal).toContain("1 more green main run required"); expect(decision.refusal).toContain(`the last proof-system squash ${decision.proofSystemSquash}`); const open = await scenario("lane-open-read"); - expect(JSON.parse(open.out), open.err).toMatchObject({ open: true, missing: 0, refusal: null }); + expect(JSON.parse(open.out), open.err).toMatchObject({ state: "open", open: true, required: 0, refusal: null }); }); test("a proof-system candidate needs off-main qualification on its head or a proof-system-free ancestor (#3271)", async () => { diff --git a/tests/proof-system-lane.test.ts b/tests/proof-system-lane.test.ts index 6bcdf82446..457c4aa784 100644 --- a/tests/proof-system-lane.test.ts +++ b/tests/proof-system-lane.test.ts @@ -2,7 +2,7 @@ import { afterAll, beforeAll, describe, expect, test } from "bun:test"; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { tmpdir } from "node:os"; -import { checkQualification, decideLane, isGreen, laneRefusal, lastProofSystemSquash, qualificationRunIds, qualificationSection, readLane, +import { checkQualification, decideLane, laneRefusal, MAX_MAIN_RUNS, lastProofSystemSquash, qualificationRunIds, qualificationSection, readLane, type MainRun, type QualificationRun } from "../scripts/proof-system-lane"; // Odysseus's fleet history on main: a product squash, a proof-system squash, @@ -36,58 +36,97 @@ beforeAll(() => { }); afterAll(() => rmSync(dir, { recursive: true, force: true })); -const green = (id: number): MainRun => ({ id, status: "completed", conclusion: "success" }); -const runs = (entries: Record) => new Map(Object.entries(entries).map(([name, run]) => [sha[name]!, run])); -describe("stability window (#3269)", () => { +describe("stability window (#3269, as clarified in issuecomment-6575963951)", () => { test("finds the last proof-system squash and the squashes after it", () => { - expect(lastProofSystemSquash(sha.mast!, { cwd: dir })).toEqual({ squash: sha.sails!, later: [sha.oars!, sha.mast!], scanned: 3 }); - expect(lastProofSystemSquash(sha.oars!, { cwd: dir })).toEqual({ squash: sha.sails!, later: [sha.oars!], scanned: 2 }); - expect(lastProofSystemSquash(sha.raft!, { cwd: dir })).toEqual({ squash: null, later: [], scanned: 2 }); + expect(lastProofSystemSquash(sha.mast!, { cwd: dir })).toEqual({ squash: sha.sails!, later: [sha.oars!, sha.mast!], more: false, scanned: 3 }); + expect(lastProofSystemSquash(sha.oars!, { cwd: dir })).toEqual({ squash: sha.sails!, later: [sha.oars!], more: false, scanned: 2 }); + expect(lastProofSystemSquash(sha.raft!, { cwd: dir })).toEqual({ squash: null, later: [], more: false, scanned: 2 }); }); - test("own run green and only one later green run: 1 more green main run required", () => { - const history = lastProofSystemSquash(sha.mast!, { cwd: dir }); - const decision = decideLane(sha.mast!, history, runs({ sails: green(1), oars: green(2), mast: null })); - expect(decision.open).toBe(false); - expect(decision.missing).toBe(1); - expect(laneRefusal(decision)).toContain("1 more green main run required"); - expect(laneRefusal(decision)).toContain(`the last proof-system squash ${sha.sails}`); - expect(laneRefusal(decision)).toContain("next run 2 at"); - }); + // Synthetic merge order: p is the proof-system squash, a..k the squashes after it. + const later = "abcdefghijk".split(""); + const history = (count: number, more = false) => ({ squash: "p", later: later.slice(0, count), more, scanned: count + 1 }); + const ok = (id: number): MainRun => ({ id, status: "completed", conclusion: "success" }); + const bad = (id: number, conclusion = "failure"): MainRun => ({ id, status: "completed", conclusion }); + const busy = (id: number): MainRun => ({ id, status: "in_progress", conclusion: null }); + const decide = (own: MainRun | null, rest: (MainRun | null)[], more = false) => + decideLane("main", history(rest.length, more), new Map([["p", own], ...rest.map((run, index): [string, MainRun | null] => [later[index]!, run])])); - test("own run and two later green runs open the lane", () => { - const history = lastProofSystemSquash(sha.mast!, { cwd: dir }); - const decision = decideLane(sha.mast!, history, runs({ sails: green(1), oars: green(2), mast: green(3) })); - expect(decision).toMatchObject({ open: true, missing: 0, proofSystemSquash: sha.sails }); - expect(laneRefusal(decision)).toBeNull(); + test("the own run must be green", () => { + for (const own of [bad(1), bad(1, "cancelled"), busy(1), null]) { + const decision = decide(own, [ok(2), ok(3)]); + expect(decision, `OWN_RUN_NOT_GREEN:${JSON.stringify(own)}`).toMatchObject({ state: "closed", open: false, ownGreen: false, required: 3 }); + expect(laneRefusal(decision)).toContain("needs its own main run green first"); + } }); - test("a missing, in-progress, cancelled or failed window run is not green", () => { - const history = lastProofSystemSquash(sha.mast!, { cwd: dir }); - for (const run of [null, { id: 3, status: "in_progress", conclusion: null }, { id: 3, status: "queued", conclusion: null }, - { id: 3, status: "completed", conclusion: "cancelled" }, { id: 3, status: "completed", conclusion: "failure" }, - { id: 3, status: "completed", conclusion: "skipped" }, { id: 3, status: "completed", conclusion: "timed_out" }]) { - expect(isGreen(run), `NOT_GREEN:${JSON.stringify(run)}`).toBe(false); - const decision = decideLane(sha.mast!, history, runs({ sails: green(1), oars: green(2), mast: run })); - expect(decision.open, `LANE_CLOSED:${JSON.stringify(run)}`).toBe(false); + test("own green and one later green run: 1 more green main run required", () => { + for (const tail of [[], [null], [busy(3)], [{ id: 3, status: "queued", conclusion: null }]]) { + const decision = decide(ok(1), [ok(2), ...tail]); + expect(decision, `ONE_MORE:${JSON.stringify(tail)}`).toMatchObject({ state: "closed", ownGreen: true, streak: 1, required: 1 }); expect(laneRefusal(decision)).toContain("1 more green main run required"); } - // A squash with no later main squash yet counts as missing too. - const fresh = decideLane(sha.sails!, lastProofSystemSquash(sha.sails!, { cwd: dir }), runs({ sails: green(1) })); - expect(laneRefusal(fresh)).toContain("2 more green main runs required"); - expect(laneRefusal(fresh)).toContain("next run 1: no main squash yet"); }); - test("readLane reads at most the window's runs and agrees with the refusal", async () => { + test("own green and the next two green open the lane", () => { + const decision = decide(ok(1), [ok(2), ok(3)]); + expect(decision).toMatchObject({ state: "open", open: true, streak: 2, required: 0 }); + expect(laneRefusal(decision)).toBeNull(); + }); + + test("a later failure restarts the count: one green after it is not enough, two consecutive are", () => { + const one = decide(ok(1), [bad(2), ok(3)]); + expect(one, "FAILURE_RESTARTS_THE_COUNT").toMatchObject({ state: "closed", streak: 1, required: 1 }); + expect(laneRefusal(one)).toContain("1 more green main run required"); + expect(laneRefusal(one)).toContain("next run 1 at a: run 2 failure"); + expect(decide(ok(1), [ok(2), bad(3), ok(4)]), "GREEN_BEFORE_THE_FAILURE_DOES_NOT_COUNT").toMatchObject({ state: "closed", streak: 1, required: 1 }); + expect(decide(ok(1), [bad(2), ok(3), ok(4)])).toMatchObject({ state: "open", required: 0 }); + expect(decide(ok(1), [ok(2), bad(3), ok(4), ok(5)])).toMatchObject({ state: "open", required: 0 }); + }); + + test("cancelled and missing runs are not green; pending runs stop the count", () => { + expect(decide(ok(1), [ok(2), bad(3, "cancelled")]), "CANCELLED_IS_NOT_GREEN").toMatchObject({ state: "closed", streak: 0, required: 2 }); + expect(laneRefusal(decide(ok(1), [ok(2), bad(3, "cancelled")]))).toContain("2 more green main runs required"); + // A squash with no run before a later squash never gets one: it restarts the count. + expect(decide(ok(1), [ok(2), null, ok(4)])).toMatchObject({ state: "closed", streak: 1, required: 1 }); + expect(decide(ok(1), [null, ok(3), ok(4)])).toMatchObject({ state: "open" }); + // An in-progress run may still fail: nothing after it counts yet. + expect(decide(ok(1), [busy(2), ok(3), ok(4)])).toMatchObject({ state: "closed", streak: 0, required: 2 }); + expect(decide(ok(1), [])).toMatchObject({ state: "closed", required: 2 }); + }); + + test("beyond the bound the lane is unknown and refused", () => { + const flapping = Array.from({ length: MAX_MAIN_RUNS - 1 }, (_, index) => index % 2 ? bad(index + 2) : ok(index + 2)); + const unknown = decide(ok(1), flapping, true); + expect(unknown).toMatchObject({ state: "unknown", open: false, required: null }); + expect(laneRefusal(unknown)).toContain("Proof-system lane unknown"); + expect(decide(ok(1), flapping, false)).toMatchObject({ state: "closed", required: 1 }); + }); + + test("readLane reads runs in merge order, stops once decided and agrees with the refusal", async () => { const asked: string[] = []; - const decision = await readLane(sha.mast!, async at => { asked.push(at); return at === sha.mast ? { id: 3, status: "completed", conclusion: "cancelled" } : green(1); }, { cwd: dir }); + const decision = await readLane(sha.mast!, async at => { asked.push(at); return at === sha.oars ? { id: 2, status: "completed", conclusion: "failure" } : ok(1); }, { cwd: dir }); expect(asked).toEqual([sha.sails!, sha.oars!, sha.mast!]); - expect(decision).toMatchObject({ open: false, missing: 1 }); - expect(laneRefusal(decision)).toContain("run 3 cancelled"); + expect(decision).toMatchObject({ state: "closed", streak: 1, required: 1, next: null }); + expect(laneRefusal(decision)).toContain("run 2 failure"); + const own: string[] = []; + await readLane(sha.mast!, async at => { own.push(at); return bad(1); }, { cwd: dir }); + expect(own, "NO_LATER_READS_AFTER_A_RED_OWN_RUN").toEqual([sha.sails!]); const product = await readLane(sha.raft!, async () => { throw new Error("NO_RUN_READ_WITHOUT_A_PROOF_SYSTEM_SQUASH"); }, { cwd: dir }); expect(product).toMatchObject({ open: true, proofSystemSquash: null }); }); + + test("readLane never reads more than the bound", async () => { + // Twelve product squashes after mast whose runs alternate red and green. + let tip = sha.mast!; + for (let index = 0; index < 12; index++) tip = git("commit-tree", `${tip}^{tree}`, "-p", tip, "-m", `wave ${index}`); + const asked: string[] = []; + const decision = await readLane(tip, async at => { asked.push(at); return asked.length % 2 ? ok(asked.length) : bad(asked.length); }, { cwd: dir }); + expect(asked, "BOUNDED_MAIN_RUN_READS").toHaveLength(MAX_MAIN_RUNS); + expect(asked[0]).toBe(sha.sails!); + expect(decision).toMatchObject({ state: "unknown", open: false, required: null }); + }); }); describe("off-main qualification (#3271)", () => {