Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 17 additions & 4 deletions docs/decisions/ci-utility.md
Original file line number Diff line number Diff line change
Expand Up @@ -1477,8 +1477,18 @@ 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 <sha>, incident #<n>` 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
their cheap gates. One ancestry rule decides every refusal and cancellation
(`gateDecision`, `scripts/red-main.ts:209-216`): proof is doomed only when the
tree it tests contains the bad commit and its PR is not a declared fix
([#3321](https://github.com/schlessera/brain-kit/issues/3321)). The coordinator
cancels a queued or running PR proof run only when its PR's base or head, as
recorded when the run was created, descends from the bad commit
(`cancelDoomed`, `scripts/red-main-coordinator.ts:154-179`). A run whose base
GitHub did not record, or whose ancestry cannot be determined, is left alone.
So proof for a PR against an integration or release branch forked before the
bad commit keeps running. `integrate.ts` applies the same rule to the
candidate's base and head before confirming or merging, and refuses when
ancestry is unknown (`refuseWhileRed`, `scripts/integrate.ts:62-66`). A non-fix squash
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.
Expand Down Expand Up @@ -1606,8 +1616,11 @@ branch, so the request always runs main's admission code.
feedback run. The [#2952](https://github.com/schlessera/brain-kit/issues/2952)
runner-slot wait measures whether this is enough.
- **Red main.** The refusal while main is red is the red-main gate from
[#2942](https://github.com/schlessera/brain-kit/issues/2942). Whichever of
#2942 and #3272 lands second adds that gate to the admission job.
[#2942](https://github.com/schlessera/brain-kit/issues/2942). The admission
job runs it on the requested head after admission
(`redMain.name`, `scripts/heavy-feedback-workflow.ts:85`), so feedback is
refused only when that head contains the bad commit and the PR is not a
declared fix ([#3321](https://github.com/schlessera/brain-kit/issues/3321)).

### Conditional concurrency direction

Expand Down
19 changes: 12 additions & 7 deletions scripts/integrate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ 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, gateDecision, type RedMainRecord } from "./red-main";
import { isAncestor } from "./red-main-cli";
import type { API } from "./proof-reuse";

async function gh(...args: string[]): Promise<string> {
Expand Down Expand Up @@ -54,10 +55,14 @@ 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 <pr>)`);
/**
* Cooperative merge blocking while red (#2942): a candidate whose merge ref contains
* the bad commit proceeds only as a declared fix (#3321). Unknown ancestry refuses.
*/
function refuseWhileRed(desired: Candidate) {
const decision = gateDecision({ record: store!.read().redMain, pr: desired.pr,
contains: sha => isAncestor(sha, desired.base, store!.root) || isAncestor(sha, desired.head, store!.root) });
if (decision.refuse) throw new Error(`${decision.message}; only a declared fix may confirm or merge (bun scripts/integrate.ts declare-fix <pr>)`);
}
async function changeRedMain(update: (record: RedMainRecord, now: number) => RedMainRecord) {
for (let attempt = 0; attempt < 3; attempt++) {
Expand Down Expand Up @@ -95,7 +100,7 @@ if (import.meta.main) {
await milestones(desired.pr, issueRefs);
await stopHeartbeat();
if (lost) throw lost;
refuseWhileRed(desired.pr);
refuseWhileRed(desired);
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);
Expand Down Expand Up @@ -154,7 +159,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);
refuseWhileRed(desired);
if (command === "merge") {
const lease = values.get("--lease");
if (!lease) throw new Error("Explicit --lease required");
Expand Down
27 changes: 22 additions & 5 deletions scripts/red-main-coordinator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 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,
import { addSuspect, attachIncident, CATEGORIES, classifyFailure, clearRed, coversRedSet, failureKey, gateDecision, 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";
Expand All @@ -17,7 +17,9 @@ 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 }[];
run_attempt: number; display_title: string; created_at: string;
/** GitHub records each PR's base and head as they stood when the run was created. */
pull_requests?: { number: number; base?: { sha: string }; head?: { sha: string } }[];
}
export interface Job { id: number; name: string; conclusion: string | null; steps?: { name: string; conclusion: string | null }[]; }
export interface Snapshot { oid: string | null; redMain: RedMainRecord; }
Expand Down Expand Up @@ -144,16 +146,31 @@ export async function noteFlake(io: CoordinatorIO, key: string, text: string, ex
return issue.number as number;
}

/** Cancels in-progress PR proof created after the bad commit landed, except declared fixes. */
/**
* Cancels queued and in-progress PR proof whose tested merge ref contains the bad
* commit, except declared fixes (#3321). The merge ref contains it when the PR's
* base or head at run creation descends from it; unknown ancestry leaves the run alone.
*/
export async function cancelDoomed(io: CoordinatorIO, record: RedMainRecord): Promise<number[]> {
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;
const prs = run.pull_requests ?? [];
// A run created before the bad commit landed cannot test a merge ref containing it.
if (!prs.length || Date.parse(run.created_at) < landed) continue;
let doomed: boolean;
try {
// Without the recorded base the merge ref is unknown, so the run is not doomed.
doomed = prs.every(pr => gateDecision({ record, pr: pr.number,
contains: sha => pr.base?.sha !== undefined && (io.isAncestor(sha, pr.base.sha) || io.isAncestor(sha, run.head_sha)) }).refuse);
} catch (error) {
io.print(`left run ${run.id} alone: ancestry of ${short(open.firstBad)} unknown (${error instanceof Error ? error.message : String(error)})`);
continue;
}
if (!doomed) continue;
await io.write("POST", `repos/${io.repository}/actions/runs/${run.id}/cancel`);
cancelled.push(run.id);
}
Expand Down
9 changes: 8 additions & 1 deletion tests/integration-command.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,8 @@ async function runScenario(mode: string, owner: Scenario): Promise<ScenarioResul
expect(store.publish(snapshot, state)).toBe(true);
if (mode.startsWith("red-main")) {
const failure = { test: "tests/raft.test.ts", category: "unit" as const, verdict: "real" as const, reasons: ["in-affected-closure"], run: 11, sha: base };
const red = openRed(emptyRedMain(), { firstBad: base, run: 11, failures: [failure] }, NOW);
// A sibling squash of the base is red on another line: the candidate's merge ref does not contain it.
const red = openRed(emptyRedMain(), { firstBad: mode === "red-main-unrelated" ? squash : base, run: 11, failures: [failure] }, NOW);
expect(store.publishRedMain(store.read(), mode === "red-main-fix" ? declareFix(red, 7, NOW) : red)).toBe(true);
}
const sentinel = join(dir, "merged"), apiState = join(dir, "api.json");
Expand Down Expand Up @@ -275,3 +276,9 @@ 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("while main is red a candidate whose merge ref does not contain the bad commit still merges (#3321)", async () => {
const unrelated = await scenario("red-main-unrelated");
expect(unrelated.code, `MERGE_REF_WITHOUT_BAD_COMMIT_MERGES: ${unrelated.err}`).toBe(2);
expect(unrelated.dispatched).toBe(true);
});
20 changes: 18 additions & 2 deletions tests/red-main.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,9 @@ function fakeGitHub(options: { jobs: Job[]; junit?: string; artifact?: Record<st
}
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" });
/** A running PR proof run whose PR had `base` as its base when the run was created. */
const prRun = (id: number, pr: number, base?: string, head = A): WorkflowRun => ({ ...mainRun(head, "", id), event: "pull_request", head_branch: `pr-${pr}`,
status: "in_progress", conclusion: null, created_at: "2026-07-12T00:00:01Z", pull_requests: [{ number: pr, ...(base ? { base: { sha: base } } : {}), head: { sha: head } }] });
const junit = `<testsuites><testsuite name="packages/core/tests/raft.test.ts" file="packages/core/tests/raft.test.ts" failures="1"><testcase name="t"><failure>expect(received).toBe(expected)</failure></testcase></testsuite></testsuites>`;

describe("coordinator", () => {
Expand All @@ -238,8 +241,7 @@ 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" }] });
prRuns: [prRun(300, 7, C), prRun(301, 8, C)] });
await coordinate(gh.io, mainRun(B, "failure"));
gh.set(declareFix(gh.record(), 8, NOW + 100_000));
await coordinate(gh.io, mainRun(B, "failure"));
Expand All @@ -251,6 +253,20 @@ describe("coordinator", () => {
expect(gh.cancelled, "DOOMED_NON_FIX_RUN_CANCELLED_FIX_KEPT").toEqual([300, 301, 300]);
});

test("only proof whose merge ref contains the bad commit is cancelled, and declared fixes never are (#3321)", async () => {
// First bad is B. Base C descends from it; base A (an integration branch forked earlier) does not.
const gh = fakeGitHub({ jobs: [{ id: 2, name: "unit (2)", conclusion: "failure", steps: [] }], junit,
prRuns: [prRun(310, 7, A), prRun(311, 9, C), prRun(312, 8, C), prRun(313, 10), prRun(314, 11, A, C)] });
gh.set(declareFix(openRed(emptyRedMain(), { firstBad: B, run: 100, failures: [failure("packages/core/tests/raft.test.ts")] }, NOW), 8, NOW));
await coordinate(gh.io, mainRun(B, "failure"));
expect(gh.cancelled.includes(310), "BASE_WITHOUT_BAD_COMMIT_NOT_CANCELLED").toBe(false);
expect(gh.cancelled.includes(311), "BASE_CONTAINING_BAD_COMMIT_CANCELLED").toBe(true);
expect(gh.cancelled.includes(312), "DECLARED_FIX_NOT_CANCELLED").toBe(false);
expect(gh.cancelled.includes(313), "UNKNOWN_BASE_NOT_CANCELLED").toBe(false);
expect(gh.cancelled.includes(314), "HEAD_CONTAINING_BAD_COMMIT_CANCELLED").toBe(true);
expect(gh.cancelled).toEqual([311, 314]);
});

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("<failure>expect(received).toBe(expected)</failure>", "<failure message=\"Timed out after 5000ms\"/>") });
Expand Down
Loading