diff --git a/.agents/skills/work-issue/references/ci-and-merge.md b/.agents/skills/work-issue/references/ci-and-merge.md index 913228fb9e..3d880351cd 100644 --- a/.agents/skills/work-issue/references/ci-and-merge.md +++ b/.agents/skills/work-issue/references/ci-and-merge.md @@ -322,6 +322,18 @@ Refresh a reviewed branch by merging `origin/main` and pushing. A rebase rewrites the reviewed commits and discards the record's coverage. A refresh that needed a conflict resolution also needs a new review. +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 completed main-push run of its own and the newest completed main run +from that squash on is green: its own green run opens the lane, and after a +failure the next green main run reopens it. They also refuse it 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 fd89186c9e..df7a930c3d 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 18eb17a775..9b38715056 100644 --- a/tests/integration-command.test.ts +++ b/tests/integration-command.test.ts @@ -68,15 +68,31 @@ 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"); // A `review-` candidate also changes a core package, so it needs a recorded independent review (#4110). if (mode.includes("review-")) { mkdirSync(join(root, "packages/core/src"), { recursive: true }); writeFileSync(join(root, "packages/core/src/raft.ts"), "export const raft = 1;\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`); @@ -89,7 +105,7 @@ async function runScenario(mode: string, owner: Scenario): Promise = { + "own-busy": ["busy", "success", "success"], "own-red": ["failure", "busy", undefined], "own-red-recovered": ["failure", "busy", "success"], + recovering: ["success", "failure", "busy"], recovered: ["success", "failure", "success"], cancelled: ["success", "success", "cancelled"], + pending: ["success", "busy", undefined] }; + const shape = Object.entries(windows).filter(([key]) => mode.includes(`lane-${key}`)).sort((a, b) => b[0].length - a[0].length)[0]?.[1] ?? ["success", "success", "success"]; + const mainRuns: Record = {}; + if (lane) for (const [index, sha] of [history.sails!, history.oars!, base].entries()) { + const outcome = shape[index]; + if (outcome) mainRuns[sha] = { id: 81 + index, status: outcome === "busy" ? "in_progress" : "completed", conclusion: outcome === "busy" ? null : outcome }; + } const review = (findings: ReviewFinding[] = []) => reviewComment({ version: 1, kind: "brain-review-receipt", pr: 7, head, base, reviewer: "agent", outcome: findings.length ? "findings" : "no-findings", findings }); const openReview = review([{ summary: "The mast is not lashed." }]); @@ -136,6 +167,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","determinism"]; const selected={selections:Object.fromEntries(categories.map(x=>[x,"false"])),results:Object.fromEntries(categories.map(x=>[x,"skipped"])),retained:[],unitShards:null}; @@ -172,7 +204,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"||(s.mode==="confirm-changed"&&s.requested&&s.now>${NOW})?"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:s.mode.endsWith("contract-absent")?[] // A creation or push-and-edit burst: the newest run was cancelled while pending, an older one passed (#3573). @@ -230,7 +263,7 @@ fi`); const lifecycle = /^(?:legacy-)?(renew|release)-(holder|none|wrong)$/.exec(mode); const presented = (kind: string) => kind === "holder" ? ["--token", TOKEN] : kind === "wrong" ? ["--token", OTHER] : []; if (mode === "renew-push-fail") writeFileSync(failPush, "1"); - const command = mode === "acquire" ? ["acquire", "7"] : mode === "renew-push-fail" ? ["renew", id, "--token", TOKEN] : lifecycle ? [lifecycle[1]!, id, ...presented(lifecycle[2]!)] + const command = mode.startsWith("lane-") && mode.endsWith("-read") ? ["lane", "--json"] : mode === "acquire" ? ["acquire", "7"] : mode === "renew-push-fail" ? ["renew", id, "--token", TOKEN] : lifecycle ? [lifecycle[1]!, id, ...presented(lifecycle[2]!)] : [mode.startsWith("confirm-") ? "confirm" : "merge", "7", ...(mode.startsWith("confirm-") ? [] : ["--lease", mode === "wrong-id" ? "2".repeat(32) : id, ...presented(mode === "no-token" ? "none" : mode === "wrong-token" ? "wrong" : "holder")]), ...(delivered.length ? ["--issues", delivered.join(",")] : []), ...(mode.startsWith("expedite-") ? ["--fixes-main-run", "11"] : [])]; @@ -583,3 +616,71 @@ test("the merge path refuses an undisposed finding, rereads the record at the me expect(expedited.dispatched).toBe(true); expect(expedited.commentReads).toBe(0); }); + +test("a proof-system candidate waits for its predecessor's own main run, then one green run after a failure; a product candidate does not (#3269)", async () => { + for (const [mode, message] of [ + ["lane-own-busy", "has no settled main run of its own yet"], + ["confirm-lane-own-busy", "has no settled main run of its own yet"], + ["lane-own-red", "its own main run is not green"], + ["lane-recovering", "the newest settled main run after it is not green"], + ["confirm-lane-recovering", "the newest settled main run after it is not green"], + ["lane-cancelled", "run 2 after it at"], + ] as const) { + const refused = await scenario(mode); + expect(refused.dispatched, `NO_PROOF_SYSTEM_MERGE_INSIDE_THE_WINDOW:${mode}`).toBe(false); + expect(refused.code, refused.err).toBe(1); + expect(refused.err).toContain("Proof-system candidate refused (scripts/ci-shards.ts)"); + expect(refused.err).toContain("1 more green main run required"); + expect(refused.err).toContain(message); + expect(refused.err).not.toContain("Off-main qualification missing"); + expect(refused.requested, `NO_CANDIDATE_CI_FOR_A_HELD_CANDIDATE:${mode}`).toBe(false); + expect(refused.state.active, `REFUSED_BEFORE_OWNERSHIP_OR_RELEASED:${mode}`).toBeNull(); + } + // The own green run opens the lane without later runs; after a failure, one later green run reopens it. + for (const mode of ["lane-own-red-product", "lane-recovering-product", "lane-open", "lane-pending", "lane-recovered", "lane-own-red-recovered"]) { + const accepted = await scenario(mode); + expect(accepted.code, `LANE_ACCEPTS:${mode}: ${accepted.err}`).toBe(2); + expect(accepted.dispatched).toBe(true); + } +}); + +test("lane --json reports the refusal's decision from the same function (#3269)", async () => { + const read = await scenario("lane-recovering-read"); + expect(read.code, read.err).toBe(0); + const decision = JSON.parse(read.out); + expect(decision).toMatchObject({ schemaVersion: 1, state: "closed", open: false, ownGreen: true, required: 1, next: null, + window: [{ position: 0, green: true, settled: true, run: { id: 81 } }, { position: 2, green: false, settled: false, run: { id: 83 } }, { position: 1, green: false, settled: true, run: { id: 82, conclusion: "failure" } }], + decisive: { position: 1, run: { id: 82 } } }); + 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-pending-read"); + expect(JSON.parse(open.out), open.err).toMatchObject({ state: "open", open: true, required: 0, refusal: null, decisive: { position: 0 } }); +}); + +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'], + ["confirm-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); + expect(refused.err).not.toContain("Proof-system lane"); + } + 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); + const product = await scenario("lane-open-unqualified-product"); + expect(product.code, `PRODUCT_NEEDS_NO_QUALIFICATION: ${product.err}`).toBe(2); +}); + +test("declared red-main fixes are exempt from the stability window and off-main qualification (#3269, #3271)", async () => { + for (const mode of ["expedite-lane-own-red", "red-main-fix-lane-own-red-unqualified"]) { + 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..2c4612b56f --- /dev/null +++ b/tests/proof-system-lane.test.ts @@ -0,0 +1,175 @@ +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, 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, +// 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 })); + + +describe("stability window (#3269, single run as amended in #2938 issuecomment-6580707195)", () => { + 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!], omitted: 0, scanned: 3 }); + expect(lastProofSystemSquash(sha.oars!, { cwd: dir })).toEqual({ squash: sha.sails!, later: [sha.oars!], omitted: 0, scanned: 2 }); + expect(lastProofSystemSquash(sha.sails!, { cwd: dir })).toEqual({ squash: sha.sails!, later: [], omitted: 0, scanned: 1 }); + expect(lastProofSystemSquash(sha.raft!, { cwd: dir })).toEqual({ squash: null, later: [], omitted: 0, scanned: 2 }); + }); + + // Synthetic merge order: p is the proof-system squash, a..k the squashes after it. + const later = "abcdefghijk".split(""); + const history = (count: number, omitted = 0) => ({ squash: "p", later: later.slice(0, count), omitted, scanned: count + omitted + 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)[], omitted = 0) => + decideLane("main", history(rest.length, omitted), new Map([["p", own], ...rest.map((run, index): [string, MainRun | null] => [later[index]!, run])])); + + test("the own green run opens the lane without waiting for later runs", () => { + for (const rest of [[], [busy(2)], [null], [busy(2), null], [ok(2)]]) { + const decision = decide(ok(1), rest); + expect(decision, `OWN_GREEN_OPENS:${JSON.stringify(rest)}`).toMatchObject({ state: "open", open: true, ownGreen: true, required: 0 }); + expect(laneRefusal(decision)).toBeNull(); + } + }); + + test("an own run that has not settled holds the lane, whatever later runs show", () => { + for (const [own, rest] of [[busy(1), []], [null, []], [{ id: 1, status: "queued", conclusion: null }, [ok(2)]], [busy(1), [ok(2), ok(3)]]] as const) { + const decision = decide(own, [...rest]); + expect(decision, `OWN_RUN_NOT_SETTLED:${JSON.stringify(own)}`).toMatchObject({ state: "closed", open: false, required: 1, decisive: null }); + expect(laneRefusal(decision)).toContain("has no settled main run of its own yet"); + expect(laneRefusal(decision)).toContain("1 more green main run required"); + } + }); + + test("a failed, cancelled or timed-out own run holds the lane until the next green main run", () => { + for (const own of [bad(1), bad(1, "cancelled"), bad(1, "timed_out")]) { + const decision = decide(own, [busy(2)]); + expect(decision, `OWN_RUN_NOT_GREEN:${JSON.stringify(own)}`).toMatchObject({ state: "closed", ownGreen: false, required: 1, decisive: { position: 0 } }); + expect(laneRefusal(decision)).toContain("its own main run is not green"); + expect(decide(own, [busy(2), ok(3)]), `NEXT_GREEN_AFTER_A_RED_OWN_RUN:${JSON.stringify(own)}`).toMatchObject({ state: "open", ownGreen: false, decisive: { position: 2 } }); + } + // A squash that never got a run is settled not green once a later squash exists. + expect(decide(null, [busy(2)])).toMatchObject({ state: "closed", ownGreen: false, decisive: { position: 0, settled: true } }); + }); + + test("after a later failure, a single later green run reopens the lane", () => { + const failed = decide(ok(1), [bad(2)]); + expect(failed, "LATER_FAILURE_CLOSES").toMatchObject({ state: "closed", ownGreen: true, required: 1, decisive: { position: 1 } }); + expect(laneRefusal(failed)).toContain("the newest settled main run after it is not green"); + expect(laneRefusal(failed)).toContain("run 1 after it at a: run 2 failure"); + expect(decide(ok(1), [bad(2), busy(3)]), "PENDING_IS_NOT_GREEN").toMatchObject({ state: "closed", required: 1 }); + expect(decide(ok(1), [bad(2), ok(3)]), "ONE_GREEN_REOPENS").toMatchObject({ state: "open", required: 0, decisive: { position: 2 } }); + expect(decide(ok(1), [bad(2), ok(3), busy(4)])).toMatchObject({ state: "open" }); + expect(decide(ok(1), [ok(2), bad(3)]), "GREEN_BEFORE_THE_FAILURE_DOES_NOT_COUNT").toMatchObject({ state: "closed", decisive: { position: 2 } }); + }); + + test("cancelled and missing later runs are not green", () => { + const cancelled = decide(ok(1), [bad(2, "cancelled")]); + expect(cancelled, "CANCELLED_IS_NOT_GREEN").toMatchObject({ state: "closed", required: 1 }); + expect(laneRefusal(cancelled)).toContain("run 2 cancelled"); + expect(decide(ok(1), [bad(2, "cancelled"), ok(3)])).toMatchObject({ state: "open" }); + // A squash with no run before a later squash never gets one. + expect(decide(ok(1), [null, busy(3)]), "MISSING_IS_NOT_GREEN").toMatchObject({ state: "closed", decisive: { position: 1, run: null, settled: true } }); + expect(laneRefusal(decide(ok(1), [null, busy(3)]))).toContain("run 1 after it at a: no main-push CI run)"); + }); + + test("when every later run read is unsettled and older ones were not read, the lane is unknown and refused", () => { + const pending = Array.from({ length: MAX_MAIN_RUNS - 1 }, (_, index) => busy(index + 2)); + const unknown = decide(ok(1), pending, 3); + expect(unknown).toMatchObject({ state: "unknown", open: false, required: null }); + expect(laneRefusal(unknown)).toContain("Proof-system lane unknown"); + expect(decide(ok(1), pending, 0)).toMatchObject({ state: "open" }); + }); + + test("readLane reads the own run, then later runs newest first, stops once decided and agrees with the refusal", async () => { + const asked: string[] = []; + const runs: Record = { [sha.sails!]: ok(1), [sha.oars!]: bad(2), [sha.mast!]: busy(3) }; + const decision = await readLane(sha.mast!, async at => { asked.push(at); return runs[at]!; }, { cwd: dir }); + expect(asked).toEqual([sha.sails!, sha.mast!, sha.oars!]); + expect(decision).toMatchObject({ state: "closed", required: 1, next: null }); + expect(laneRefusal(decision)).toContain("run 2 failure"); + const own: string[] = []; + await readLane(sha.mast!, async at => { own.push(at); return busy(1); }, { cwd: dir }); + expect(own, "NO_LATER_READS_BEFORE_THE_OWN_RUN_SETTLES").toEqual([sha.sails!]); + const newest: string[] = []; + await readLane(sha.mast!, async at => { newest.push(at); return ok(1); }, { cwd: dir }); + expect(newest, "STOPS_AT_THE_NEWEST_SETTLED_RUN").toEqual([sha.sails!, sha.mast!]); + 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 are all still in progress. + 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 at === sha.sails ? ok(1) : busy(asked.length); }, { cwd: dir }); + expect(asked, "BOUNDED_MAIN_RUN_READS").toHaveLength(MAX_MAIN_RUNS); + expect(asked[0]).toBe(sha.sails!); + expect(asked[1]).toBe(tip); + expect(decision).toMatchObject({ state: "unknown", open: false, required: 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") }); + }); +});