From db486064efcb62814cf66438fab2fefb711c5c56 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 15 Nov 2026 13:37:25 +0000 Subject: [PATCH] chore(ci): archive and report red-main incidents, flakes, cancellations and merges during red The hourly collector reads the red-main record's history from the shared coordination ref, and the coordinator's cancellation lines for the hours main was red, into normalized archive files. The report gains a red-main section: each incident's lifecycle and time to green, flake verdicts with their escalation to real, PR proof cancelled or refused by the gate with consumed and estimated saved runner minutes (unknowns counted separately), and non-fix merges during red with their PR. The probe path now prints the same cancellation line as a main run. Refs #2953 Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci-timings.yml | 2 +- docs/process/ci-throughput.md | 40 ++- docs/process/ci-timings.md | 14 +- scripts/check-ci-workflows.ts | 2 +- scripts/ci-red-main.ts | 379 ++++++++++++++++++++++++++++ scripts/ci-timing-seed.ts | 10 +- scripts/ci-timings.ts | 45 +++- scripts/red-main-coordinator.ts | 4 +- tests/ci-red-main.test.ts | 247 ++++++++++++++++++ tests/ci-timings-collection.test.ts | 11 +- tests/ci-timings.test.ts | 4 +- tests/red-main.test.ts | 12 +- 12 files changed, 747 insertions(+), 23 deletions(-) create mode 100644 scripts/ci-red-main.ts create mode 100644 tests/ci-red-main.test.ts diff --git a/.github/workflows/ci-timings.yml b/.github/workflows/ci-timings.yml index f5fc6f7d46..42b62919a4 100644 --- a/.github/workflows/ci-timings.yml +++ b/.github/workflows/ci-timings.yml @@ -38,7 +38,7 @@ jobs: TIMING_DEFAULT_BRANCH: ${{ github.event.repository.default_branch }} run: | since=$(date -u -d '2 days ago' +%Y-%m-%dT%H:%M:%SZ) - bun scripts/ci-timings.ts collect --repo "$TIMING_REPO" --since "$since" --seed "$TIMING_DEFAULT_BRANCH" --request-budget 200 --reserve 500 --reservations + bun scripts/ci-timings.ts collect --repo "$TIMING_REPO" --since "$since" --seed "$TIMING_DEFAULT_BRANCH" --request-budget 200 --reserve 500 --reservations --red-main - name: Retain normalized timing archive if: always() uses: actions/upload-artifact@v7 diff --git a/docs/process/ci-throughput.md b/docs/process/ci-throughput.md index 706881a527..7b13589f2f 100644 --- a/docs/process/ci-throughput.md +++ b/docs/process/ci-throughput.md @@ -27,7 +27,8 @@ its append-only history without changing it. Actor IDs and revocation prose are omitted. Protocol expiry establishes authorized lease time, not actual worker activity or caller waiting. -Hourly incremental collection includes PR lifecycle and reservation history, +Hourly incremental collection includes PR lifecycle, reservation and +[red-main](#red-main-incidents-flakes-and-proof-stopped-while-red) history, within the [shared API budget](ci-timings.md#api-cost-and-expected-coverage-gaps). Explicit `--since`/`--until` choose the half-open throughput analysis interval. Without them, collection manifests supply a bounding interval whose gaps need review. @@ -143,6 +144,43 @@ 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. +## Red-main incidents, flakes and proof stopped while red + +`--red-main --since ...` reads the [red-main record](../decisions/ci-utility.md#red-main-record-and-coordinator) +from the same public coordination ref, walking only the commits that changed +`red-main.json`, back to the last green state before the window. It writes +`red-main.json` with one observation per record, keyed by its opening run, and +one per suspected flake. During `collect`, it also reads the coordinator's +`BRAIN_RED_MAIN` lines from the `red-main` workflow runs created while main was +red, as `coordinator--attempt-.json`. A window in which main stayed green +costs no API request. Each archived attempt is seeded forward and never fetched +twice. + +`summary.json` carries a `redMain` section; `summary.md` renders it. + +| Field | Definition and boundary | +| --- | --- | +| `incidents` | Each record's opening run, first bad SHA and its bisect refinements, failing tests and categories with their estimator reasons, incident issue, declared and expedited fixes, and when it was cleared. | +| `timeToGreenSeconds` | Record opened to record cleared, on GitHub server time. An open record has none; `openIncidents` counts them. | +| `flakes` | Per test: suspicions, triage probe outcomes, flake issues, and `escalations` where a second suspicion within the window, or a reproducing probe, made it real. | +| `cancellations` | PR runs the coordinator cancelled, with observed runner seconds consumed and an estimated saving. | +| `refusals` | PR attempts the hosted gate refused (the failed gate step in `changeset`), with the same accounting. | +| `savingReference` | The median observed runner time of successful PR CI attempts in the archive. Saving is that reference minus the time consumed. It is an estimate, not a measured counterfactual. | +| `mergesDuringRed` | Non-fix squashes the coordinator reported landing while red, with their PR from the exact squash identity. | +| `acquisition` | History scopes and their errors, scopes whose red hours lack coordinator logs, and coordinator attempts whose cancellations are unknown. | + +Unknowns never read as zero. A cancelled or refused run without a complete +timing snapshot has unknown consumption and saving. With no reference attempt, +saving is unknown. Each is counted separately (`unknownConsumed`, +`unknownSaved`). A run that finished before its cancellation took effect saved +nothing. A coordinator attempt that failed before printing its line has +unknown cancellations. Probe-triggered cancellations print the same line from +the change that added this collector. Earlier probe attempts that succeeded +without it read as none. A squash without an exact PR identity is counted in +`unknownPR`. No `red-main.json` makes the whole section `null`: unknown, not a +quiet main. Overlapping archives join per record; contradicting opening times, +clearings or incident numbers are refused. + ## Scenario estimates and formal proof Use `report --scenario `. The default assumptions are: diff --git a/docs/process/ci-timings.md b/docs/process/ci-timings.md index 037a518456..939e9266e8 100644 --- a/docs/process/ci-timings.md +++ b/docs/process/ci-timings.md @@ -58,7 +58,8 @@ separate from the hourly artifact collection described here; this guide does not imply that durable compaction or scheduled report delivery is enabled. `.github/workflows/ci-timings.yml` collects an overlapping two-day creation -window hourly, with job/step timings, PR lifecycle and reservation history, +window hourly, with job/step timings, PR lifecycle, reservation history and +[red-main evidence](ci-throughput.md#red-main-incidents-flakes-and-proof-stopped-while-red), and supports manual dispatch. Each invocation seeds from the preceding default-branch `ci-timings` artifact, then fetches only new or incomplete attempts. Completed attempts and unchanged/merged lifecycle observations are @@ -101,7 +102,10 @@ older rerun attempts also need an attempt-identity call. One shared PR index costs one call per 100 recently updated PRs. A changed PR normally costs two calls (detail and one timeline page), or three when its immutable squash is read. Unattributed main heads add an exact-SHA lookup. No resource-job log -calls occur on the schedule. +calls occur on the schedule. Red-main history is read through Git, not the API. +Only while main was red does each new coordinator attempt cost two calls (jobs +and its log), plus one discovery call per 100 coordinator runs in each red +interval. For example, a warm run with two discovery pages, one PR-index page, 20 new attempts, and five changed merged PRs costs **42 calls**: `1 + 3 + 2 + 1 + 20 + @@ -129,7 +133,11 @@ Reservation-history failures are isolated: `reservations.json` records an continues. The report keeps that error in its reservation scopes and sets `reservationAcquisition.complete` to false. Any failed reservation scope leaves total occupancy unknown; successful lease observations remain available in -`reservationAcquisition.leases` for inspection. +`reservationAcquisition.leases` for inspection. Red-main history failures are +isolated the same way in `red-main.json`. A failed coordinator discovery, or a +budget stop before it, marks that scope `partial` in its `coordinatorScope`. +The report then lists it under `redMain.acquisition`, rather than reporting no +cancellations. Download archives before they expire, using their measurement workflow run IDs: diff --git a/scripts/check-ci-workflows.ts b/scripts/check-ci-workflows.ts index d8ba1a0082..3b50cbb7cb 100644 --- a/scripts/check-ci-workflows.ts +++ b/scripts/check-ci-workflows.ts @@ -206,7 +206,7 @@ export function timingWorkflowProblems(text: string): string[] { checkouts[0]?.with?.["persist-credentials"] !== false || checkouts[0]?.with?.repository !== undefined) fail("collector must check out trusted default-branch code without credentials"); if (JSON.stringify(workflow.on?.schedule) !== JSON.stringify([{ cron: "43 * * * *" }])) fail("timing collection must remain hourly and incremental"); const collection = steps.find(s => s.run?.includes("bun scripts/ci-timings.ts collect")); - if (!collection?.run?.includes('bun scripts/ci-timings.ts collect --repo "$TIMING_REPO" --since "$since" --seed "$TIMING_DEFAULT_BRANCH" --request-budget 200 --reserve 500 --reservations') || + if (!collection?.run?.includes('bun scripts/ci-timings.ts collect --repo "$TIMING_REPO" --since "$since" --seed "$TIMING_DEFAULT_BRANCH" --request-budget 200 --reserve 500 --reservations --red-main') || /--resources\b/.test(collection.run) || collection.env?.TIMING_DEFAULT_BRANCH !== "${{ github.event.repository.default_branch }}") fail("timing collection requires seeded acquisition, a hard budget/reserve and no scheduled resource logs"); for (const step of steps) if ((step.run ?? "").includes("${{") || /bun install/.test(step.run ?? "")) fail("collector scripts must not interpolate events or install candidate dependencies"); if (!steps.some(s => s.uses === "actions/upload-artifact@v7" && s.if === "always()" && s.with?.["retention-days"] === 90 && s.with?.path === "tmp/ci-timings/")) fail("bounded always-upload timing archive missing"); diff --git a/scripts/ci-red-main.ts b/scripts/ci-red-main.ts new file mode 100644 index 0000000000..436832faaa --- /dev/null +++ b/scripts/ci-red-main.ts @@ -0,0 +1,379 @@ +/** + * Read-only red-main evidence (#2953): each red-main record's lifecycle, flake + * verdicts and triage probes, PR proof the coordinator cancelled or the hosted + * gate refused, and squashes that landed while red. Measurement only: nothing + * here is an input to proof, selection or merging, and absent evidence stays + * unknown rather than zero. + */ +import { stats } from "./ci-timing-stats"; +import type { PullObservation } from "./ci-throughput"; +import { RESERVATION_REF } from "./integration-reservation"; +import { CATEGORIES, failureKey, parseRedMain, RED_MAIN_FILE, type Category, type RedFailure, type RedMainRecord } from "./red-main"; + +export const RED_MAIN_ARCHIVE = "red-main.json"; +/** The hosted gate's step in ci.yml's metadata job (#2942). */ +export const GATE_STEP = "Refuse doomed proof while main is red"; +/** The coordinator prints this line with the PR runs it cancelled. */ +export const COORDINATOR_MARKER = "BRAIN_RED_MAIN "; +export const COORDINATOR_WORKFLOW = "red-main.yml"; +/** The coordinator that opens a record starts before the record's server timestamp. */ +const COORDINATOR_LEAD_MS = 30 * 60_000; +/** Bounds one history walk; a longer walk is an acquisition error, never a silent truncation. */ +const MAX_HISTORY = 20_000; +const SHA = /^[a-f0-9]{40}$/; +const PROBES = ["pending", "passed", "failed", "unavailable"] as const; +type Probe = typeof PROBES[number]; +type Escalation = "repeated-suspected-flake" | "probe-reproduced"; + +export interface IncidentFailure { + test: string | null; category: Category; reasons: string[]; run: number; sha: string; + /** Why a failure the estimator once suspected was declared real; null for a first-sight real failure. */ + escalated: Escalation | null; priorSuspectRun: number | null; +} +export interface IncidentObservation { + /** The record's opening run, which also keys its incident issue marker. */ + run: number; opened: number; firstBad: string; firstBadHistory: { sha: string; at: number }[]; + failures: IncidentFailure[]; incident: number | null; fixes: number[]; + expedited: { pr: number; squash: string; at: number }[]; + /** Non-fix squashes the coordinator reported as landing while red. */ + reported: string[]; + cleared: { at: number; run: number | null } | null; sources: string[]; +} +export interface FlakeObservation { + test: string; category: Category; run: number; sha: string; at: number; probe: Probe; issue: number | null; sources: string[]; +} +export interface RedMainArchive { + version: 1; repository: string; collectedAt: string; sourceRef: string; sourceHead: string | null; since: string; + incidents: IncidentObservation[]; flakes: FlakeObservation[]; error?: string; + /** Which red hours had their coordinator logs read; absent when no collection requested them. */ + coordinatorScope?: { intervals: { since: string; until: string }[]; status: "completed" | "partial"; error: string | null }; +} +/** One coordinator attempt: the PR runs it cancelled, or null when its log cannot say. */ +export interface CoordinatorObservation { + version: 1; repository: string; collectedAt: string; run: number; attempt: number; createdAt: string; + conclusion: string | null; cancelled: number[] | null; problem: string | null; +} + +const positive = (value: unknown): value is number => Number.isSafeInteger(value) && Number(value) > 0; +const time = (value: unknown): value is number => Number.isSafeInteger(value) && Number(value) >= 0; +const testKey = (value: unknown) => typeof value === "string" && value.length <= 300 && /^[A-Za-z0-9_./@:-]+$/.test(value); +const category = (value: unknown): value is Category => CATEGORIES.includes(value as Category); +const stamp = (value: unknown): value is string => typeof value === "string" && Number.isFinite(Date.parse(value)); + +function escalation(reasons: string[]): Pick { + if (reasons.includes("repeated-suspected-flake")) { + const prior = reasons.map(reason => /^prior-suspect-run-([1-9]\d*)$/.exec(reason)?.[1]).find(Boolean); + return { escalated: "repeated-suspected-flake", priorSuspectRun: prior ? Number(prior) : null }; + } + return { escalated: reasons.includes("probe-reproduced") ? "probe-reproduced" : null, priorSuspectRun: null }; +} +const failure = (f: RedFailure): IncidentFailure => ({ test: f.test, category: f.category, reasons: [...f.reasons], run: f.run, sha: f.sha, ...escalation(f.reasons) }); +const union = (values: T[]) => [...new Set(values)]; + +/** Folds record states, oldest first, into one observation per incident and suspect. */ +export function observeRedMain(rows: { source: string; record: RedMainRecord }[]): Pick { + const incidents = new Map(), flakes = new Map(); + let current: number | null = null; + for (const { source, record } of rows) { + if (!SHA.test(source)) throw new Error("Invalid red-main source"); + const open = record.open; + if (open) { + let seen = incidents.get(open.run); + if (!seen) incidents.set(open.run, seen = { run: open.run, opened: open.opened, firstBad: open.firstBad, firstBadHistory: [], + failures: [], incident: null, fixes: [], expedited: [], reported: [], cleared: null, sources: [] }); + else if (seen.opened !== open.opened) throw new Error("Conflicting red-main history"); + if (seen.firstBadHistory.at(-1)?.sha !== open.firstBad) seen.firstBadHistory.push({ sha: open.firstBad, at: record.updated }); + seen.firstBad = open.firstBad; + for (const f of open.failures) if (!seen.failures.some(known => failureKey(known) === failureKey(f))) seen.failures.push(failure(f)); + seen.incident = open.incident ?? seen.incident; + seen.fixes = union([...seen.fixes, ...open.fixes]); + for (const e of open.expedited ?? []) if (!seen.expedited.some(known => known.squash === e.squash)) seen.expedited.push({ pr: e.pr, squash: e.squash, at: e.at }); + seen.reported = union([...seen.reported, ...open.reported]); + seen.sources.push(source); + current = open.run; + } else if (current !== null) { + // Only a green main run that included the open set clears a record. + const seen = incidents.get(current)!; + if (record.last?.action === "clear") seen.cleared = { at: record.last.at, run: record.last.run }; + seen.sources.push(source); + current = null; + } + for (const s of record.suspects) { + const key = `${s.test}\n${s.run}`, old = flakes.get(key); + flakes.set(key, { test: s.test, category: s.category, run: s.run, sha: s.sha, at: old?.at ?? s.at, + probe: s.probe, issue: s.issue ?? old?.issue ?? null, sources: union([...old?.sources ?? [], source]) }); + } + } + return { incidents: [...incidents.values()], flakes: [...flakes.values()] }; +} + +/** Reads the shared coordination ref's red-main history through the local Git remote. */ +export function collectRedMainHistory(repository: string, since: string, cwd = process.cwd()): RedMainArchive { + if (!stamp(since)) throw new Error("Invalid red-main history window"); + const run = (args: string[]) => { + const p = Bun.spawnSync(["git", ...args], { cwd, stdout: "pipe", stderr: "pipe", timeout: 60000 }); + if (p.exitCode !== 0) throw new Error(`Red-main history unavailable: ${new TextDecoder().decode(p.stderr).trim()}`); + return new TextDecoder().decode(p.stdout).trim(); + }; + const remote = run(["ls-remote", "--refs", "origin", RESERVATION_REF]).split(/\s+/)[0]; + if (!remote || !SHA.test(remote)) throw new Error("Coordination ref unavailable"); + run(["fetch", "--no-tags", "origin", remote]); + // Only commits that changed the record; reservation writes copy it unchanged. + const commits = run(["rev-list", "--first-parent", remote, "--", RED_MAIN_FILE]).split("\n").filter(Boolean); + const rows: { source: string; record: RedMainRecord }[] = []; + for (const source of commits) { + if (rows.length >= MAX_HISTORY) throw new Error("Red-main history exceeds the collection bound; collect a narrower window"); + const record = parseRedMain(run(["show", `${source}:${RED_MAIN_FILE}`])); + rows.push({ source, record }); + // A green state before the window bounds the walk: every incident open in the window opened after it. + if (record.updated < Date.parse(since) && record.open === null) break; + } + return { version: 1, repository, collectedAt: new Date().toISOString(), sourceRef: RESERVATION_REF, sourceHead: remote, since, + ...observeRedMain(rows.reverse()) }; +} + +/** The union of PR runs every coordinator line names; null when the attempt failed before printing one. */ +export function coordinatorCancellations(log: string, conclusion: string | null): number[] | null { + const lines = log.split("\n").filter(line => line.includes(COORDINATOR_MARKER)); + const cancelled: number[] = []; + for (const line of lines) { + let value: { cancelled?: unknown }; + try { value = JSON.parse(line.slice(line.indexOf(COORDINATOR_MARKER) + COORDINATOR_MARKER.length)); } + catch { throw new Error("Invalid coordinator cancellation line"); } + if (!Array.isArray(value?.cancelled) || !value.cancelled.every(positive)) throw new Error("Invalid coordinator cancellation line"); + cancelled.push(...value.cancelled as number[]); + } + // A successful attempt that printed nothing reached no cancellation; a failed one may have cancelled unseen. + return lines.length || conclusion === "success" ? union(cancelled).sort((a, b) => a - b) : null; +} + +/** Red intervals in the window, widened by the opening coordinator's lead and clamped to the window. */ +export function redIntervals(archive: Pick, since: string, until: string): { since: string; until: string }[] { + const lower = Date.parse(since), upper = Date.parse(until); + const spans = archive.incidents.map(i => [Math.max(lower, i.opened - COORDINATOR_LEAD_MS), Math.min(upper, i.cleared?.at ?? upper)] as const) + .filter(([a, b]) => a < b).sort((a, b) => a[0] - b[0]); + const merged: [number, number][] = []; + for (const [a, b] of spans) { + const last = merged.at(-1); + if (last && a <= last[1]) last[1] = Math.max(last[1], b); else merged.push([a, b]); + } + return merged.map(([a, b]) => ({ since: new Date(a).toISOString(), until: new Date(b).toISOString() })); +} + +interface CoordinatorAPI { json(path: string): Promise; log(job: number): Promise; } +/** + * Reads coordinator attempts created while main was red. Zero requests when + * main stayed green; an archived attempt is never fetched twice. + */ +export async function collectCoordinatorRuns(api: CoordinatorAPI, repository: string, intervals: { since: string; until: string }[], + known: (run: number, attempt: number) => Promise, now = () => new Date().toISOString()): Promise { + const out: CoordinatorObservation[] = []; + for (const interval of intervals) { + const query = `actions/workflows/${COORDINATOR_WORKFLOW}/runs?per_page=100&created=${encodeURIComponent(`${interval.since}..${interval.until}`)}`; + const runs: any[] = []; + for (let page = 1; ; page++) { + const result = await api.json(`${query}&page=${page}`); + if (!Number.isSafeInteger(result?.total_count) || !Array.isArray(result.workflow_runs)) throw new Error("Invalid coordinator run inventory"); + if (result.total_count >= 1000) throw new Error("Coordinator run search cap reached; collect a narrower window"); + runs.push(...result.workflow_runs); + if (runs.length >= result.total_count) break; + if (!result.workflow_runs.length) throw new Error("Incomplete coordinator run pagination"); + } + for (const run of runs) { + if (!positive(run?.id) || !positive(run.run_attempt) || !stamp(run.created_at) || run.path !== `.github/workflows/${COORDINATOR_WORKFLOW}`) throw new Error("Invalid coordinator run identity"); + if (run.status !== "completed") continue; + for (let attempt = 1; attempt <= run.run_attempt; attempt++) { + const previous = await known(run.id, attempt); + if (previous && previous.problem === null) continue; + const row: CoordinatorObservation = { version: 1, repository, collectedAt: now(), run: run.id, attempt, createdAt: run.created_at, + conclusion: null, cancelled: null, problem: null }; + try { + const jobs = (await api.json(`actions/runs/${run.id}/attempts/${attempt}/jobs?per_page=100`)).jobs; + const job = Array.isArray(jobs) ? jobs.find((j: any) => j?.name === "coordinate") : undefined; + if (!job || !positive(job.id)) throw new Error("Coordinator job unavailable"); + row.conclusion = typeof job.conclusion === "string" ? job.conclusion : null; + // A skipped coordinator handled no main run or probe. + row.cancelled = row.conclusion === "skipped" ? [] : coordinatorCancellations(await api.log(job.id), row.conclusion); + } catch (error) { + if (String(error).includes("TimingBudgetStop")) throw error; + row.problem = String(error); + } + out.push(row); + } + } + } + return out; +} + +function validIncident(i: IncidentObservation): boolean { + return !!i && positive(i.run) && time(i.opened) && SHA.test(i.firstBad) && Array.isArray(i.firstBadHistory) && i.firstBadHistory.length > 0 && + i.firstBadHistory.every(h => SHA.test(h?.sha) && time(h.at)) && Array.isArray(i.failures) && i.failures.every(f => !!f && + (f.test === null || testKey(f.test)) && category(f.category) && Array.isArray(f.reasons) && f.reasons.every(r => typeof r === "string") && + positive(f.run) && SHA.test(f.sha) && [null, "repeated-suspected-flake", "probe-reproduced"].includes(f.escalated) && + (f.priorSuspectRun === null || positive(f.priorSuspectRun))) && + (i.incident === null || positive(i.incident)) && Array.isArray(i.fixes) && i.fixes.every(positive) && + Array.isArray(i.expedited) && i.expedited.every(e => positive(e?.pr) && SHA.test(e.squash) && time(e.at)) && + Array.isArray(i.reported) && i.reported.every(sha => SHA.test(sha)) && + (i.cleared === null || !!i.cleared && time(i.cleared.at) && i.cleared.at >= i.opened && (i.cleared.run === null || positive(i.cleared.run))) && + Array.isArray(i.sources) && i.sources.every(s => SHA.test(s)); +} +function validFlake(f: FlakeObservation): boolean { + return !!f && testKey(f.test) && category(f.category) && positive(f.run) && SHA.test(f.sha) && time(f.at) && PROBES.includes(f.probe) && + (f.issue === null || positive(f.issue)) && Array.isArray(f.sources) && f.sources.every(s => SHA.test(s)); +} + +/** Joins overlapping archives: later states enrich one incident; contradictions are refused. */ +export function mergeRedMainArchives(input: RedMainArchive[]) { + const archives = [...new Map(input.map(a => [JSON.stringify(a), a])).values()].sort((a, b) => Date.parse(a.collectedAt) - Date.parse(b.collectedAt)); + const incidents = new Map(), flakes = new Map(); + for (const archive of archives) { + if (archive?.version !== 1 || !stamp(archive.collectedAt) || !stamp(archive.since) || archive.sourceRef !== RESERVATION_REF || + !Array.isArray(archive.incidents) || !Array.isArray(archive.flakes) || + (archive.error === undefined ? !SHA.test(archive.sourceHead ?? "") : + typeof archive.error !== "string" || archive.sourceHead !== null || archive.incidents.length || archive.flakes.length) || + !archive.incidents.every(validIncident) || !archive.flakes.every(validFlake) || + archive.coordinatorScope !== undefined && (!Array.isArray(archive.coordinatorScope?.intervals) || + !archive.coordinatorScope.intervals.every(i => stamp(i?.since) && stamp(i.until)) || !["completed", "partial"].includes(archive.coordinatorScope.status) || + (archive.coordinatorScope.status === "completed") !== (archive.coordinatorScope.error === null))) throw new Error("Invalid red-main archive"); + for (const row of archive.incidents) { + const old = incidents.get(row.run); + if (!old) { incidents.set(row.run, structuredClone(row)); continue; } + if (old.opened !== row.opened || old.cleared && row.cleared && JSON.stringify(old.cleared) !== JSON.stringify(row.cleared) || + old.incident !== null && row.incident !== null && old.incident !== row.incident) throw new Error("Conflicting red-main history"); + const history = new Map([...old.firstBadHistory, ...row.firstBadHistory].map(h => [`${h.at}/${h.sha}`, h])); + old.firstBadHistory = [...history.values()].sort((a, b) => a.at - b.at); + old.firstBad = old.firstBadHistory.at(-1)!.sha; + for (const f of row.failures) if (!old.failures.some(known => failureKey(known) === failureKey(f))) old.failures.push(structuredClone(f)); + old.incident ??= row.incident; old.cleared ??= row.cleared; + old.fixes = union([...old.fixes, ...row.fixes]); + for (const e of row.expedited) if (!old.expedited.some(known => known.squash === e.squash)) old.expedited.push(e); + old.reported = union([...old.reported, ...row.reported]); + old.sources = union([...old.sources, ...row.sources]); + } + for (const row of archive.flakes) { + const key = `${row.test}\n${row.run}`, old = flakes.get(key); + if (!old) { flakes.set(key, structuredClone(row)); continue; } + if (old.sha !== row.sha || old.category !== row.category || old.probe !== "pending" && row.probe !== "pending" && old.probe !== row.probe || + old.issue !== null && row.issue !== null && old.issue !== row.issue) throw new Error("Conflicting flake history"); + if (old.probe === "pending") old.probe = row.probe; + old.issue ??= row.issue; old.at = Math.min(old.at, row.at); + old.sources = union([...old.sources, ...row.sources]); + } + } + return { archives, incidents: [...incidents.values()].sort((a, b) => a.opened - b.opened || a.run - b.run), + flakes: [...flakes.values()].sort((a, b) => a.at - b.at || a.test.localeCompare(b.test)) }; +} + +/** The structural subset of a timing snapshot this report reads. */ +interface Attempt { + run: { id: number; attempt: number; path: string; event: string; head: string; status: string; conclusion: string | null; prs: number[]; attribution: string }; + jobs: { category: string; seconds: number | null; steps: { name: string; conclusion: string | null }[] }[]; + problems: string[]; +} +const CI_PATH = ".github/workflows/ci.yml"; +const consumed = (s: Attempt) => s.jobs.reduce((sum, job) => sum + (job.seconds ?? 0), 0); +export const gateRefused = (s: Attempt) => s.run.path === CI_PATH && s.run.event === "pull_request" && + s.jobs.some(j => j.category === "changeset" && j.steps.some(step => step.name === GATE_STEP && step.conclusion === "failure")); + +function stopped(rows: { run: number; attempt: Attempt | null; stopped: boolean }[], reference: number | null) { + const out = rows.map(({ run, attempt, stopped }) => { + const known = !!attempt && attempt.run.status === "completed" && !attempt.problems.length; + const spent = known ? consumed(attempt!) : null; + // Proof that finished anyway saved nothing; an unmeasured run or reference is unknown, never zero. + const saved = spent === null ? null : !stopped ? 0 : reference === null ? null : Math.max(0, reference - spent); + return { run, attempt: attempt?.run.attempt ?? null, prs: attempt?.run.prs ?? [], conclusion: attempt?.run.conclusion ?? null, + consumedRunnerSeconds: spent, estimatedSavedRunnerSeconds: saved }; + }); + return { runs: out, count: out.length, + consumedRunnerSeconds: out.reduce((sum, r) => sum + (r.consumedRunnerSeconds ?? 0), 0), + estimatedSavedRunnerSeconds: out.reduce((sum, r) => sum + (r.estimatedSavedRunnerSeconds ?? 0), 0), + unknownConsumed: out.filter(r => r.consumedRunnerSeconds === null).length, + unknownSaved: out.filter(r => r.estimatedSavedRunnerSeconds === null).length }; +} + +export interface RedMainInputs { + archives: RedMainArchive[]; coordinator: CoordinatorObservation[]; snapshots: Attempt[]; pulls: Pick[]; +} +export function summarizeRedMain({ archives, coordinator, snapshots, pulls }: RedMainInputs) { + if (!archives.length) return null; + const { archives: scopes, incidents, flakes } = mergeRedMainArchives(archives); + for (const c of coordinator) if (c?.version !== 1 || !positive(c.run) || !positive(c.attempt) || !stamp(c.createdAt) || + !(c.cancelled === null || Array.isArray(c.cancelled) && c.cancelled.every(positive)) || !(c.problem === null || typeof c.problem === "string")) throw new Error("Invalid coordinator observation"); + const attempts = [...new Map(coordinator.map(c => [`${c.run}/${c.attempt}`, c])).values()]; + const ci = snapshots.filter(s => s.run.path === CI_PATH); + // The cancelled attempt when there is one: a later rerun of the same run is not the proof that was stopped. + const stoppedAttempt = (run: number) => ci.filter(s => s.run.id === run) + .sort((a, b) => Number(b.run.conclusion === "cancelled") - Number(a.run.conclusion === "cancelled") || b.run.attempt - a.run.attempt)[0] ?? null; + // Estimate reference: what a PR CI attempt costs when it is left to finish green. + const samples = ci.filter(s => s.run.event === "pull_request" && s.run.status === "completed" && s.run.conclusion === "success" && !s.problems.length).map(consumed); + const reference = stats(samples).median; + const cancelledRuns = union(attempts.flatMap(c => c.cancelled ?? [])).sort((a, b) => a - b); + const cancellations = stopped(cancelledRuns.map(run => { const a = stoppedAttempt(run); return { run, attempt: a, stopped: a?.run.conclusion === "cancelled" }; }), reference); + const refusedAttempts = ci.filter(gateRefused).sort((a, b) => a.run.id - b.run.id || a.run.attempt - b.run.attempt); + const refusals = stopped(refusedAttempts.map(a => ({ run: a.run.id, attempt: a, stopped: true })), reference); + const prFor = (sha: string) => { + const exact = ci.filter(s => s.run.event === "push" && s.run.head === sha && s.run.attribution === "exact merged squash SHA").flatMap(s => s.run.prs); + const numbers = union([...exact, ...pulls.filter(p => p.merge === sha).map(p => p.number)]); + return numbers.length === 1 ? numbers[0]! : null; + }; + const merges = incidents.flatMap(i => i.reported.map(sha => ({ incidentRun: i.run, incident: i.incident, sha, pr: prFor(sha) }))); + const rows = incidents.map(i => ({ ...i, openedAt: new Date(i.opened).toISOString(), clearedAt: i.cleared ? new Date(i.cleared.at).toISOString() : null, + timeToGreenSeconds: i.cleared ? (i.cleared.at - i.opened) / 1000 : null, categories: union(i.failures.map(f => f.category)).sort() })); + const tests = union(flakes.map(f => f.test)); + const escalations = incidents.flatMap(i => i.failures.filter(f => f.escalated).map(f => ({ test: failureKey(f), incidentRun: i.run, run: f.run, reason: f.escalated!, priorSuspectRun: f.priorSuspectRun }))); + const flakeRows = union([...tests, ...escalations.map(e => e.test)]).map(test => { + const suspects = flakes.filter(f => f.test === test), raised = escalations.filter(e => e.test === test); + return { test, category: suspects[0]?.category ?? incidents.flatMap(i => i.failures).find(f => failureKey(f) === test)!.category, + suspects: suspects.length, runs: suspects.map(s => s.run), + probes: Object.fromEntries(PROBES.map(p => [p, suspects.filter(s => s.probe === p).length])) as Record, + issues: union(suspects.flatMap(s => s.issue === null ? [] : [s.issue])), verdict: raised.length ? "real" as const : "suspected-flake" as const, escalations: raised }; + }); + const unknownLogs = attempts.filter(c => c.cancelled === null); + // Red hours whose coordinator logs were never read leave cancellations unknown, not zero. + const unread = incidents.length ? scopes.filter(a => a.error === undefined && a.coordinatorScope?.status !== "completed") : []; + return { + acquisition: { complete: scopes.every(a => a.error === undefined) && !unknownLogs.length && !unread.length, + scopes: scopes.map(({ repository, collectedAt, since, sourceRef, sourceHead, error, coordinatorScope }) => + ({ repository, collectedAt, since, sourceRef, sourceHead, error, coordinatorScope: coordinatorScope ?? null })), + coordinatorScopesUnread: unread.length, + coordinatorAttempts: attempts.length, + coordinatorUnknown: unknownLogs.map(c => ({ run: c.run, attempt: c.attempt, problem: c.problem })) }, + incidents: rows, openIncidents: rows.filter(r => !r.cleared).length, + timeToGreenSeconds: stats(rows.flatMap(r => r.timeToGreenSeconds === null ? [] : [r.timeToGreenSeconds])), + flakes: flakeRows, + cancellations, refusals, + savingReference: { label: "Median observed runner time of successful PR CI attempts in this archive; an estimate, not measured savings", + samples: samples.length, runnerSeconds: reference }, + mergesDuringRed: { count: merges.length, unknownPR: merges.filter(m => m.pr === null).length, rows: merges }, + }; +} + +export function redMainMarkdown(report: ReturnType): string { + if (!report) return "\n## Red-main incidents\n\nRed-main evidence is unknown: no red-main history archive was collected.\n"; + const minutes = (n: number | null) => n === null ? "unknown" : (n / 60).toFixed(2); + const iso = (n: string | null) => n ?? "open"; + const cell = (s: string) => s.replaceAll("|", "\\|"); + const gaps = report.acquisition.scopes.filter(s => s.error !== undefined).length; + const stop = (label: string, s: typeof report.cancellations) => `${label}: ${s.count} runs; consumed runner minutes ${minutes(s.consumedRunnerSeconds)}` + + ` (unknown for ${s.unknownConsumed}); estimated saved runner minutes ${minutes(s.estimatedSavedRunnerSeconds)} (unknown for ${s.unknownSaved}).`; + return ["", "## Red-main incidents", "", + `History scopes: ${report.acquisition.scopes.length}; acquisition gaps: ${gaps}; scopes without coordinator logs: ${report.acquisition.coordinatorScopesUnread}; coordinator attempts read: ${report.acquisition.coordinatorAttempts}; with unknown cancellations: ${report.acquisition.coordinatorUnknown.length}.`, "", + ...(report.incidents.length ? ["| Opening run | First bad | Opened | Cleared | Time to green min | Incident | Failing tests and categories | Fixes |", + "| ---: | --- | --- | --- | ---: | --- | --- | --- |", + ...report.incidents.map(i => `| ${i.run} | \`${i.firstBad.slice(0, 12)}\` | ${i.openedAt} | ${iso(i.clearedAt)} | ${minutes(i.timeToGreenSeconds)} | ${i.incident === null ? "pending" : `#${i.incident}`} | ${cell(i.failures.map(f => `${f.test ?? f.category} (${f.category}${f.escalated ? `, escalated: ${f.escalated}` : ""})`).join("; "))} | ${i.fixes.map(n => `#${n}`).join(", ") || "none"} |`), ""] + : ["No red-main incident in the collected history.", ""]), + `Time to green: median ${minutes(report.timeToGreenSeconds.median)} min, p90 ${minutes(report.timeToGreenSeconds.p90)} min over ${report.timeToGreenSeconds.n} cleared incidents; still open: ${report.openIncidents}.`, "", + "### Flake verdicts", "", + ...(report.flakes.length ? ["| Test | Suspected | Probes passed / failed / pending / unavailable | Verdict | Escalation |", "| --- | ---: | --- | --- | --- |", + ...report.flakes.map(f => `| ${cell(f.test)} | ${f.suspects} | ${f.probes.passed} / ${f.probes.failed} / ${f.probes.pending} / ${f.probes.unavailable} | ${f.verdict} | ${f.escalations.map(e => `${e.reason} in run ${e.run}${e.priorSuspectRun ? ` after suspect run ${e.priorSuspectRun}` : ""}`).join("; ") || "none"} |`), ""] + : ["No suspected flake in the collected history.", ""]), + "### Proof stopped while red", "", + stop("Cancelled by the coordinator", report.cancellations), + stop("Refused by the hosted gate", report.refusals), + `${report.savingReference.label}: ${minutes(report.savingReference.runnerSeconds)} min from ${report.savingReference.samples} attempts.`, "", + "### Merges during red", "", + ...(report.mergesDuringRed.rows.length ? ["| Squash | PR | Incident run |", "| --- | --- | ---: |", + ...report.mergesDuringRed.rows.map(m => `| \`${m.sha.slice(0, 12)}\` | ${m.pr === null ? "unknown" : `#${m.pr}`} | ${m.incidentRun} |`), ""] + : ["No non-fix squash was reported landing while red.", ""]), + ].join("\n"); +} diff --git a/scripts/ci-timing-seed.ts b/scripts/ci-timing-seed.ts index b69b0186b4..0493d95530 100644 --- a/scripts/ci-timing-seed.ts +++ b/scripts/ci-timing-seed.ts @@ -5,7 +5,7 @@ import { join } from "node:path"; import type { TimingClient } from "./ci-timing-api"; export async function seedTimings(api: TimingClient, repository: string, branch: string, since: string, until: string, dir: string) { - const seed = { run: null as number | null, artifact: null as number | null, snapshots: 0, pulls: 0, error: null as string | null }; + const seed = { run: null as number | null, artifact: null as number | null, snapshots: 0, pulls: 0, coordinator: 0, error: null as string | null }; let temp: string | undefined; try { const runs = await api.json(`actions/workflows/ci-timings.yml/runs?branch=${encodeURIComponent(branch)}&status=completed&per_page=5`); @@ -28,7 +28,7 @@ export async function seedTimings(api: TimingClient, repository: string, branch: return out; }; const names = (await command(["-Z1", zip])).trim().split("\n") - .filter(name => /^(?:run-\d+-attempt-\d+|pull-\d+)\.json$/.test(name)); + .filter(name => /^(?:run-\d+-attempt-\d+|pull-\d+|coordinator-\d+-attempt-\d+)\.json$/.test(name)); if (!names.length || names.length > 20000 || new Set(names).size !== names.length) throw new Error("Empty or invalid normalized seed inventory"); // Only exact, flat normalized filenames are extracted. No archive path, // executable, symlink or other metadata can become collector tooling. @@ -43,6 +43,12 @@ export async function seedTimings(api: TimingClient, repository: string, branch: !Array.isArray(value.problems) || !Number.isFinite(Date.parse(value.run.createdAt))) throw new Error("Invalid seed attempt identity"); if (Date.parse(value.run.createdAt) < Date.parse(since) || Date.parse(value.run.createdAt) > Date.parse(until)) continue; seed.snapshots++; + } else if (name.startsWith("coordinator-")) { + // Red-main coordinator observations (#2953): an archived log is never fetched twice. + if (name !== `coordinator-${value.run}-attempt-${value.attempt}.json` || !Number.isFinite(Date.parse(value.createdAt)) || + !(value.cancelled === null || Array.isArray(value.cancelled))) throw new Error("Invalid seed coordinator identity"); + if (Date.parse(value.createdAt) < Date.parse(since) || Date.parse(value.createdAt) > Date.parse(until)) continue; + seed.coordinator++; } else { if (name !== `pull-${value.number}.json` || !Array.isArray(value.problems)) throw new Error("Invalid seed PR identity"); if (value.closedAt && Date.parse(value.closedAt) < Date.parse(since)) continue; diff --git a/scripts/ci-timings.ts b/scripts/ci-timings.ts index c9305b0420..5e8d58e1c7 100644 --- a/scripts/ci-timings.ts +++ b/scripts/ci-timings.ts @@ -9,6 +9,8 @@ import { collectReservationHistory, mergeLeaseObservations, type ReservationArch import { TimingClient, TimingBudgetStop } from "./ci-timing-api"; import { seedTimings } from "./ci-timing-seed"; import { gitEpochSource } from "./ci-epochs"; +import { collectCoordinatorRuns, collectRedMainHistory, RED_MAIN_ARCHIVE, redIntervals, redMainMarkdown, summarizeRedMain, + type CoordinatorObservation, type RedMainArchive } from "./ci-red-main"; export interface TimingAPI { json(path: string): Promise; log(job: number): Promise; } interface RawRun { @@ -370,28 +372,33 @@ interface LifecycleAcquisition { errors: { pr: number; problem: string }[]; } async function readOperationalData(dir: string): Promise<{ pulls: PullObservation[]; events: WorkEvent[]; - acquisitions: LifecycleAcquisition[]; reservations: ReservationArchive[] }> { + acquisitions: LifecycleAcquisition[]; reservations: ReservationArchive[]; redMain: RedMainArchive[]; coordinator: CoordinatorObservation[] }> { const pulls: PullObservation[] = [], events: WorkEvent[] = []; const acquisitions: LifecycleAcquisition[] = [], reservations: ReservationArchive[] = []; + const redMain: RedMainArchive[] = [], coordinator: CoordinatorObservation[] = []; for (const entry of await readdir(dir, { withFileTypes: true })) { const path = join(dir, entry.name); if (entry.isDirectory()) { const children = await readOperationalData(path); pulls.push(...children.pulls); events.push(...children.events); acquisitions.push(...children.acquisitions); reservations.push(...children.reservations); + redMain.push(...children.redMain); coordinator.push(...children.coordinator); } else if (/^pull-\d+\.json$/.test(entry.name)) pulls.push(await Bun.file(path).json()); else if (/^event-[\w-]+\.json$/.test(entry.name)) events.push(validateWorkEvent(await Bun.file(path).json())); else if (entry.name === "enrichment.json") acquisitions.push(await Bun.file(path).json()); else if (entry.name === "reservations.json") reservations.push(await Bun.file(path).json()); + else if (entry.name === RED_MAIN_ARCHIVE) redMain.push(await Bun.file(path).json()); + else if (COORDINATOR_FILE.test(entry.name)) coordinator.push(await Bun.file(path).json()); } const unique = new Map(); for (const p of pulls) { const key = `${p.repository}/${p.number}`, old = unique.get(key); if (!old || p.collectedAt > old.collectedAt) unique.set(key, p); } - return { pulls: [...unique.values()], events, acquisitions, reservations }; + return { pulls: [...unique.values()], events, acquisitions, reservations, redMain, coordinator }; } +const COORDINATOR_FILE = /^coordinator-\d+-attempt-\d+\.json$/; function lifecycleCoverage(input: LifecycleAcquisition[], pulls: PullObservation[]) { if (!input.length) return null; @@ -439,7 +446,7 @@ async function writeReport(dir: string, history: string, scenario?: Scenario) { } const basic = summarize(snapshots), operational = await readOperationalData(dir); if (new Set([...snapshots, ...collections, ...operational.pulls, ...operational.events, - ...operational.acquisitions, ...operational.reservations].map(s => s.repository)).size > 1) throw new Error("Report one repository at a time"); + ...operational.acquisitions, ...operational.reservations, ...operational.redMain, ...operational.coordinator].map(s => s.repository)).size > 1) throw new Error("Report one repository at a time"); const analysisPath = join(dir, "analysis-window.json"), scenarioPath = join(dir, "scenario.json"); const intervals = collections.filter(c => stampForWindow(c.since) && stampForWindow(c.until)); const window = await Bun.file(analysisPath).exists() ? await Bun.file(analysisPath).json() : intervals.length ? { @@ -447,7 +454,8 @@ async function writeReport(dir: string, history: string, scenario?: Scenario) { scenario ??= await Bun.file(scenarioPath).exists() ? await Bun.file(scenarioPath).json() : { failedPRFraction: .3, additionalPushes: 2, failedRunCostFraction: 1 }; const lifecycleAcquisition = lifecycleCoverage(operational.acquisitions, operational.pulls); const reservationAcquisition = reservationCoverage(operational.reservations); - const report = { ...basic, lifecycleAcquisition, reservationAcquisition, throughput: window && operational.pulls.length ? summarizeThroughput(deduplicate(snapshots), operational.pulls, operational.events, window, + const redMain = summarizeRedMain({ archives: operational.redMain, coordinator: operational.coordinator, snapshots: deduplicate(snapshots), pulls: operational.pulls }); + const report = { ...basic, lifecycleAcquisition, reservationAcquisition, redMain, throughput: window && operational.pulls.length ? summarizeThroughput(deduplicate(snapshots), operational.pulls, operational.events, window, { runnerSeconds: basic.baseline.runnerSeconds.median, elapsedSeconds: basic.baseline.elapsedSeconds.median, samples: basic.baseline.samples.length }, scenario!, reservationAcquisition?.complete ? reservationAcquisition.leases : undefined, gitEpochSource(process.cwd(), history)) : null, collectionCoverage: { missingAttempts: [...missing], scopes: collections.map(c => ({ repository: c.repository, since: c.since, until: c.until, requestedRun: c.requestedRun, @@ -460,7 +468,7 @@ async function writeReport(dir: string, history: string, scenario?: Scenario) { (report.throughput ? "" : "\nPR lifecycle throughput is unknown until enrichment and an analysis window are available.\n") + `\nPartial collection scopes: ${collections.filter(c => c.status !== "completed").length}; budget stops: ${collections.filter(c => c.requestBudget?.stopped).length}; seed gaps: ${collections.filter(c => c.seed?.error).length}.\n` + `Reservation acquisition gaps: ${reservationAcquisition?.scopes.filter(s => s.error !== undefined).length ?? "unknown"}.\n` + - `\nMissing discovered attempts: ${missing.size}. See summary.json for collection windows and acquisition errors.\n`); + `\nMissing discovered attempts: ${missing.size}. See summary.json for collection windows and acquisition errors.\n` + redMainMarkdown(redMain)); return report; } const stampForWindow = (s: unknown): s is string => typeof s === "string" && Number.isFinite(Date.parse(s)); @@ -510,11 +518,12 @@ if (import.meta.main) { try { const args = process.argv.slice(2), mode = args.shift(); const options = new Map(); - let resources = false, reservations = false; + let resources = false, reservations = false, redMain = false; while (args.length) { const flag = args.shift()!; if (flag === "--resources") { resources = true; continue; } if (flag === "--reservations") { reservations = true; continue; } + if (flag === "--red-main") { redMain = true; continue; } if (!["--repo", "--since", "--until", "--run", "--out", "--event", "--scenario", "--seed", "--request-budget", "--reserve", "--history"].includes(flag) || !args.length || options.has(flag)) throw new Error("Invalid timing option"); options.set(flag, args.shift()!); } @@ -533,6 +542,14 @@ if (import.meta.main) { sourceRef: "refs/heads/brain-integration-reservation", sourceHead: null, leases: [], error: String(error) }; } await Bun.write(join(dir, "reservations.json"), JSON.stringify(archive, null, 2) + "\n"); } + let redHistory: RedMainArchive | null = null; + if (redMain) { + if (!options.has("--since")) throw new Error("Red-main history requires --since"); + try { redHistory = collectRedMainHistory(repository, options.get("--since")!); } + catch (error) { redHistory = { version: 1, repository, collectedAt: new Date().toISOString(), sourceRef: "refs/heads/brain-integration-reservation", + sourceHead: null, since: options.get("--since")!, incidents: [], flakes: [], error: String(error) }; } + await Bun.write(join(dir, RED_MAIN_ARCHIVE), JSON.stringify(redHistory, null, 2) + "\n"); + } if (options.has("--scenario")) await Bun.write(join(dir, "scenario.json"), JSON.stringify(await Bun.file(options.get("--scenario")!).json(), null, 2)); if (options.has("--since") && options.has("--until")) await Bun.write(join(dir, "analysis-window.json"), JSON.stringify({ since: options.get("--since"), until: options.get("--until"), source: "explicit analysis interval" })); if (mode === "record") { @@ -627,6 +644,20 @@ if (import.meta.main) { s.run.prs = numbers!; s.run.attribution = numbers!.length ? "exact merged squash SHA" : "unresolved exact squash lookup"; await Bun.write(join(dir, `run-${s.run.id}-attempt-${s.run.attempt}.json`), JSON.stringify(s, null, 2) + "\n"); } + // Coordinator logs only for the hours main was red; a gap stays a red-main coverage gap, never zero cancellations. + if (redHistory && !redHistory.error) { + const intervals = redIntervals(redHistory, since ?? redHistory.since, cutoff); + redHistory.coordinatorScope = { intervals, status: "completed", error: null }; + try { + const known = async (run: number, attempt: number) => { + const file = Bun.file(join(dir, `coordinator-${run}-attempt-${attempt}.json`)); + return await file.exists() ? await file.json() as CoordinatorObservation : null; + }; + for (const row of await collectCoordinatorRuns(api, repository, intervals, known)) + await Bun.write(join(dir, `coordinator-${row.run}-attempt-${row.attempt}.json`), JSON.stringify(row, null, 2) + "\n"); + } catch (error) { redHistory.coordinatorScope = { intervals, status: "partial", error: String(error) }; } + await Bun.write(join(dir, RED_MAIN_ARCHIVE), JSON.stringify(redHistory, null, 2) + "\n"); + } const enrichmentErrors = await enrich(dir, api, repository, false, pulls); if (api.budget.stopped) errors.push({ run: 0, attempt: 0, error: String(new TimingBudgetStop(api.budget.stopped)) }); const incomplete = (await readSnapshots(dir)).some(s => s.problems.length || s.run.status !== "completed"); @@ -638,6 +669,6 @@ if (import.meta.main) { if (errors.some(e => !budgetProblem(e.error)) || enrichmentErrors.some(e => !budgetProblem(e.problem)) || (await readSnapshots(dir)).some(s => s.problems.some(p => !budgetProblem(p))) || !api.budget.stopped && report.collectionCoverage.missingAttempts.length) process.exitCode = 1; - } else throw new Error("usage: bun scripts/ci-timings.ts collect|enrich|report|record [--since ISO --until ISO] [--run ID] [--resources] [--seed DEFAULT_BRANCH] [--request-budget N --reserve N] [--event JSON] [--scenario JSON] [--history REF] [--repo owner/repo] [--out DIR]"); + } else throw new Error("usage: bun scripts/ci-timings.ts collect|enrich|report|record [--since ISO --until ISO] [--run ID] [--resources] [--seed DEFAULT_BRANCH] [--request-budget N --reserve N] [--reservations] [--red-main] [--event JSON] [--scenario JSON] [--history REF] [--repo owner/repo] [--out DIR]"); } catch (error) { console.error(error); process.exitCode = 1; } } diff --git a/scripts/red-main-coordinator.ts b/scripts/red-main-coordinator.ts index 0bd36eadae..9276a7ee97 100644 --- a/scripts/red-main-coordinator.ts +++ b/scripts/red-main-coordinator.ts @@ -304,7 +304,9 @@ async function handleProbe(io: CoordinatorIO, run: WorkflowRun) { } 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)); + const withIncident = await ensureIncident(io, after), cancelled = await cancelDoomed(io, withIncident); + // The same line as a main run's, so the evidence collector (#2953) sees every cancellation. + io.print(`BRAIN_RED_MAIN ${JSON.stringify({ firstBad: withIncident.open?.firstBad, incident: withIncident.open?.incident, cancelled })}`); } export async function coordinate(io: CoordinatorIO, run: WorkflowRun) { diff --git a/tests/ci-red-main.test.ts b/tests/ci-red-main.test.ts new file mode 100644 index 0000000000..ec0db68c4c --- /dev/null +++ b/tests/ci-red-main.test.ts @@ -0,0 +1,247 @@ +import { expect, test } from "bun:test"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { collectCoordinatorRuns, collectRedMainHistory, coordinatorCancellations, GATE_STEP, mergeRedMainArchives, observeRedMain, redIntervals, + redMainMarkdown, summarizeRedMain, type CoordinatorObservation, type RedMainArchive } from "../scripts/ci-red-main"; +import { normalizeJob, type TimingSnapshot } from "../scripts/ci-timings"; +import { emptyReservation, GitReservationStore, reservationTransition } from "../scripts/integration-reservation"; +import { addSuspect, attachIncident, classifyFailure, clearRed, declareFix, emptyRedMain, openRed, refineFirstBad, reportLanded, settleSuspect, + type RedFailure, type RedMainRecord } from "../scripts/red-main"; + +const repo = "odysseus/chronicle"; +const A = "a".repeat(40), B = "b".repeat(40), C = "c".repeat(40), D = "d".repeat(40); +const T0 = Date.parse("2026-07-12T10:00:00Z"), minute = 60_000; +const iso = (offset: number) => new Date(T0 + offset * minute).toISOString(); +const raft = "packages/core/tests/raft.test.ts"; +const real = (test: string | null, reasons = ["in-affected-closure"], run = 100, sha = B): RedFailure => ({ test, category: "unit", verdict: "real", reasons, run, sha }); +const covering = (record: RedMainRecord) => ({ id: 400, conclusion: "success", included: { run: record.open!.run, firstBad: record.open!.firstBad, failures: record.open!.failures } }); + +/** Applies each step to the previous record, in order, as the coordinator publishes them. */ +function lifecycle(steps: ((r: RedMainRecord) => RedMainRecord)[], start = emptyRedMain()): RedMainRecord[] { + const out: RedMainRecord[] = []; + let record = start; + for (const step of steps) out.push(record = step(record)); + return out; +} +const sources = (records: RedMainRecord[]) => records.map((record, i) => ({ source: String(i + 1).padStart(40, "0"), record })); +function archive(records: RedMainRecord[], collectedAt = iso(200)): RedMainArchive { + return { version: 1, repository: repo, collectedAt, sourceRef: "refs/heads/brain-integration-reservation", sourceHead: D, since: iso(-60), + coordinatorScope: { intervals: [], status: "completed", error: null }, ...observeRedMain(sources(records)) }; +} +function attempt(id: number, conclusion: string, seconds: number, event = "pull_request", extra: Partial = {}, steps: { name: string; conclusion: string }[] = []): TimingSnapshot { + const job = normalizeJob({ id: id * 10, run_id: id, name: "changeset", status: "completed", conclusion, started_at: iso(0), completed_at: new Date(T0 + seconds * 1000).toISOString(), + steps: [{ name: "Set up job", number: 1, status: "completed", conclusion: "success", started_at: iso(0), completed_at: iso(0) }, + ...steps.map((step, i) => ({ ...step, number: i + 2, status: "completed", started_at: iso(0), completed_at: iso(0) }))] }); + return { version: 1, repository: repo, collectedAt: iso(200), problems: [], jobs: [job], + run: { id, attempt: 1, workflow: "CI", path: ".github/workflows/ci.yml", event, head: A, createdAt: iso(0), startedAt: iso(0), + status: "completed", conclusion, prs: [42], attribution: "run payload", ...extra } }; +} + +/** The ruled lifecycle: opened, refined, incident filed, fix declared, a non-fix landing, cleared 90 minutes later. */ +const incidentLifecycle = (start = emptyRedMain()) => lifecycle([ + r => openRed(r, { firstBad: C, run: 100, failures: [real(raft)] }, T0), + r => refineFirstBad(r, B, 101, T0 + minute), + r => attachIncident(r, 500, T0 + 2 * minute), + r => declareFix(r, 8, T0 + 3 * minute), + r => reportLanded(r, C, T0 + 4 * minute), + r => openRed(r, { firstBad: B, run: 100, failures: [real(null, ["closure-unknown"]), real(raft)] }, T0 + 5 * minute), + r => clearRed(r, covering(r), T0 + 90 * minute), +], start); + +test("a fixture red-main lifecycle produces one incident record with its time to green", () => { + const records = incidentLifecycle(); + // Overlapping hourly archives each see part of the same lifecycle. + const early = archive(records.slice(0, 4), iso(30)), late = archive(records, iso(200)); + const report = summarizeRedMain({ archives: [early, late, late], coordinator: [], snapshots: [], pulls: [] })!; + expect(report.incidents, "ONE_INCIDENT_PER_RECORD").toHaveLength(1); + const [incident] = report.incidents; + expect(incident!.timeToGreenSeconds, "TIME_TO_GREEN_FROM_OPEN_TO_CLEAR").toBe(90 * 60); + expect(incident).toMatchObject({ run: 100, firstBad: B, incident: 500, fixes: [8], reported: [C], cleared: { at: T0 + 90 * minute, run: 400 }, + openedAt: iso(0), clearedAt: iso(90), categories: ["unit"] }); + expect(incident!.firstBadHistory).toEqual([{ sha: C, at: T0 }, { sha: B, at: T0 + minute }]); + expect(incident!.failures.map(f => f.test)).toEqual([raft, null]); + expect(report.timeToGreenSeconds).toMatchObject({ n: 1, median: 5400 }); + expect(report.openIncidents).toBe(0); + // An archive that saw only the open record keeps the incident open, not green. + const open = summarizeRedMain({ archives: [early], coordinator: [], snapshots: [], pulls: [] })!; + expect(open.incidents[0]!.timeToGreenSeconds, "OPEN_INCIDENT_HAS_NO_TIME_TO_GREEN").toBeNull(); + expect(open.openIncidents).toBe(1); + expect(redMainMarkdown(report)).toContain("| 100 | `bbbbbbbbbbbb` | 2026-07-12T10:00:00.000Z | 2026-07-12T11:30:00.000Z | 90.00 | #500 |"); +}); + +test("a suspected flake followed by a second suspected flake on the same test shows the escalation to real", () => { + const first = { test: raft, category: "unit" as const, signature: "timeout" as const, inClosure: false }; + const records = lifecycle([ + r => addSuspect(r, { test: raft, category: "unit", run: 100, sha: A, at: T0 }, T0), + r => settleSuspect(r, { test: raft, run: 100 }, { issue: 600 }, T0 + minute), + r => settleSuspect(r, { test: raft, run: 100 }, { probe: "passed" }, T0 + 20 * minute), + ]); + expect(classifyFailure(first, emptyRedMain(), T0).verdict).toBe("suspected-flake"); + // The same timeout outside the closure a day later: the estimator escalates it. + const second = classifyFailure(first, records.at(-1)!, T0 + 24 * 60 * minute); + expect(second.verdict).toBe("real"); + records.push(openRed(records.at(-1)!, { firstBad: B, run: 200, failures: [real(raft, second.reasons, 200, B)] }, T0 + 24 * 60 * minute)); + const report = summarizeRedMain({ archives: [archive(records)], coordinator: [], snapshots: [], pulls: [] })!; + expect(report.flakes).toHaveLength(1); + expect(report.flakes[0], "ESCALATED_TO_REAL").toMatchObject({ test: raft, suspects: 1, runs: [100], issues: [600], + probes: { passed: 1, failed: 0, pending: 0, unavailable: 0 }, verdict: "real", + escalations: [{ incidentRun: 200, run: 200, reason: "repeated-suspected-flake", priorSuspectRun: 100 }] }); + expect(report.incidents[0]!.failures[0]).toMatchObject({ escalated: "repeated-suspected-flake", priorSuspectRun: 100 }); + expect(redMainMarkdown(report)).toContain("| real | repeated-suspected-flake in run 200 after suspect run 100 |"); + // Without the second failure the verdict stays a suspicion. + const single = summarizeRedMain({ archives: [archive(records.slice(0, 3))], coordinator: [], snapshots: [], pulls: [] })!; + expect(single.flakes[0]!.verdict, "ONE_SUSPICION_IS_NOT_REAL").toBe("suspected-flake"); +}); + +test("runner minutes saved by cancellation and refusal are reported with unknowns counted separately", () => { + const records = incidentLifecycle(); + const coordinator: CoordinatorObservation[] = [ + { version: 1, repository: repo, collectedAt: iso(200), run: 900, attempt: 1, createdAt: iso(0), conclusion: "success", cancelled: [300, 301, 302], problem: null }, + { version: 1, repository: repo, collectedAt: iso(200), run: 901, attempt: 1, createdAt: iso(10), conclusion: "failure", cancelled: null, problem: null }, + ]; + const snapshots = [ + attempt(300, "cancelled", 120), + // A later rerun of the cancelled run is not the attempt that was stopped. + attempt(300, "success", 750, "pull_request", { attempt: 2 }), + // The cancel arrived after this run finished: nothing was saved. + attempt(302, "failure", 400), + attempt(310, "failure", 30, "pull_request", {}, [{ name: GATE_STEP, conclusion: "failure" }]), + attempt(320, "success", 600), attempt(321, "success", 900), + ]; + const report = summarizeRedMain({ archives: [archive(records)], coordinator, snapshots, pulls: [] })!; + expect(report.savingReference).toMatchObject({ samples: 3, runnerSeconds: 750 }); + expect(report.cancellations, "CANCELLED_SAVINGS_AND_UNKNOWNS").toMatchObject({ count: 3, consumedRunnerSeconds: 520, estimatedSavedRunnerSeconds: 630, + unknownConsumed: 1, unknownSaved: 1 }); + expect(report.cancellations.runs.map(r => [r.run, r.estimatedSavedRunnerSeconds])).toEqual([[300, 630], [301, null], [302, 0]]); + expect(report.refusals, "REFUSED_BY_GATE").toMatchObject({ count: 1, consumedRunnerSeconds: 30, estimatedSavedRunnerSeconds: 720, unknownSaved: 0 }); + expect(report.acquisition.coordinatorUnknown, "FAILED_COORDINATOR_LOG_IS_UNKNOWN").toEqual([{ run: 901, attempt: 1, problem: null }]); + expect(report.acquisition.complete).toBe(false); + const md = redMainMarkdown(report); + expect(md).toContain("Cancelled by the coordinator: 3 runs; consumed runner minutes 8.67 (unknown for 1); estimated saved runner minutes 10.50 (unknown for 1)."); + expect(md).toContain("Refused by the hosted gate: 1 runs;"); + // Without a successful reference attempt, saving is unknown rather than zero. + const unreferenced = summarizeRedMain({ archives: [archive(records)], coordinator, snapshots: snapshots.filter(s => s.run.conclusion !== "success"), pulls: [] })!; + expect(unreferenced.cancellations.unknownSaved, "NO_REFERENCE_IS_UNKNOWN").toBe(2); + expect(unreferenced.refusals.estimatedSavedRunnerSeconds).toBe(0); + expect(unreferenced.refusals.unknownSaved).toBe(1); +}); + +test("a merge during red appears in the report with its PR number", () => { + const records = incidentLifecycle(); + const squash = attempt(410, "success", 60, "push", { head: C, prs: [7], attribution: "exact merged squash SHA" }); + const report = summarizeRedMain({ archives: [archive(records)], coordinator: [], snapshots: [squash], pulls: [] })!; + expect(report.mergesDuringRed, "MERGE_DURING_RED_HAS_PR").toEqual({ count: 1, unknownPR: 0, rows: [{ incidentRun: 100, incident: 500, sha: C, pr: 7 }] }); + expect(redMainMarkdown(report)).toContain("| `cccccccccccc` | #7 | 100 |"); + // A PR observation's exact squash identifies it too; nothing at all leaves it unknown. + expect(summarizeRedMain({ archives: [archive(records)], coordinator: [], snapshots: [], pulls: [{ number: 9, merge: C }] })!.mergesDuringRed.rows[0]!.pr).toBe(9); + expect(summarizeRedMain({ archives: [archive(records)], coordinator: [], snapshots: [], pulls: [] })!.mergesDuringRed.unknownPR).toBe(1); +}); + +test("absent or failed red-main acquisition reads as unknown, never as a quiet main", () => { + expect(summarizeRedMain({ archives: [], coordinator: [], snapshots: [], pulls: [] })).toBeNull(); + expect(redMainMarkdown(null)).toContain("Red-main evidence is unknown"); + const failed: RedMainArchive = { version: 1, repository: repo, collectedAt: iso(0), sourceRef: "refs/heads/brain-integration-reservation", + sourceHead: null, since: iso(-60), incidents: [], flakes: [], error: "Coordination ref unavailable" }; + expect(summarizeRedMain({ archives: [failed], coordinator: [], snapshots: [], pulls: [] })!.acquisition.complete).toBe(false); + // History read but the red hours' coordinator logs not: cancellations stay unknown. + const unread = { ...archive(incidentLifecycle()), coordinatorScope: { intervals: [], status: "partial" as const, error: "TimingBudgetStop: request limit" } }; + expect(summarizeRedMain({ archives: [unread], coordinator: [], snapshots: [], pulls: [] })!.acquisition, "UNREAD_COORDINATOR_LOGS_ARE_A_GAP").toMatchObject({ complete: false, coordinatorScopesUnread: 1 }); + const conflicting = archive(incidentLifecycle()); + conflicting.incidents[0]!.opened += 1; + expect(() => mergeRedMainArchives([archive(incidentLifecycle()), conflicting])).toThrow("Conflicting red-main history"); + expect(() => mergeRedMainArchives([{ ...failed, incidents: archive(incidentLifecycle()).incidents }])).toThrow("Invalid red-main archive"); +}); + +test("coordinator lines name cancellations; a failed attempt without one is unknown", () => { + expect(coordinatorCancellations("x BRAIN_RED_MAIN {\"firstBad\":\"b\",\"incident\":5,\"cancelled\":[3,1]}\ny BRAIN_RED_MAIN {\"cancelled\":[3]}", "success")).toEqual([1, 3]); + expect(coordinatorCancellations("BRAIN_RED_MAIN_INCLUDED {}\nnothing", "success"), "QUIET_SUCCESS_CANCELLED_NOTHING").toEqual([]); + expect(coordinatorCancellations("nothing", "failure"), "FAILED_BEFORE_PRINTING_IS_UNKNOWN").toBeNull(); + expect(() => coordinatorCancellations("BRAIN_RED_MAIN {\"cancelled\":[\"x\"]}", "success")).toThrow("Invalid coordinator cancellation line"); +}); + +test("coordinator logs are read only for red hours and never twice", async () => { + const calls: string[] = []; + const api = { + async json(path: string) { + calls.push(path); + if (path.includes("red-main.yml/runs")) return { total_count: 2, workflow_runs: [ + { id: 900, run_attempt: 1, created_at: iso(5), status: "completed", path: ".github/workflows/red-main.yml" }, + { id: 901, run_attempt: 1, created_at: iso(6), status: "completed", path: ".github/workflows/red-main.yml" }] }; + const jobs = /runs\/(\d+)\/attempts/.exec(path); + if (jobs) return { jobs: [{ id: Number(jobs[1]) * 10, name: "coordinate", conclusion: "success" }] }; + throw new Error(`Unexpected offline API ${path}`); + }, + async log(job: number) { calls.push(`log ${job}`); return `BRAIN_RED_MAIN {"cancelled":[${job + 1}]}`; }, + }; + const history = archive(incidentLifecycle()); + // Main stayed green outside the incident: no request at all. + expect(await collectCoordinatorRuns(api, repo, redIntervals(history, iso(100), iso(200)), async () => null), "GREEN_HOURS_COST_NOTHING").toEqual([]); + expect(calls).toEqual([]); + const intervals = redIntervals(history, iso(-60), iso(200)); + expect(intervals).toEqual([{ since: iso(-30), until: iso(90) }]); + const known = async (run: number) => run === 900 ? { problem: null } as CoordinatorObservation : null; + const rows = await collectCoordinatorRuns(api, repo, intervals, known, () => iso(200)); + expect(rows, "ARCHIVED_ATTEMPT_NOT_REFETCHED").toEqual([{ version: 1, repository: repo, collectedAt: iso(200), run: 901, attempt: 1, createdAt: iso(6), + conclusion: "success", cancelled: [9011], problem: null }]); + expect(calls.filter(c => c.startsWith("log"))).toEqual(["log 9010"]); + const stop = { ...api, async log(): Promise { throw Object.assign(new Error("request limit"), { name: "TimingBudgetStop" }); } }; + await expect(collectCoordinatorRuns(stop, repo, intervals, async () => null), "BUDGET_STOP_IS_NOT_A_PER_RUN_PROBLEM").rejects.toThrow("request limit"); +}); + +test("native history collection walks the shared coordination ref from an offline local remote", () => { + const dir = mkdtempSync(join(tmpdir(), "ci-red-main-")); + const git = (args: string[], cwd = dir) => { const p = Bun.spawnSync(["git", ...args], { cwd, stdout: "pipe", stderr: "pipe" }); expect(p.exitCode).toBe(0); }; + try { + git(["init", "--bare", "remote.git"]); git(["init", "work"]); + const work = join(dir, "work"); + git(["remote", "add", "origin", join(dir, "remote.git")], work); + const store = new GitReservationStore(work); + const lease = reservationTransition(emptyReservation(), { kind: "acquire", id: "2".repeat(32), + candidate: { repository: `https://github.com/${repo}`, pr: 42, head: A, base: B } }, 1, T0 - 300 * minute); + expect(store.publish({ oid: null, state: emptyReservation() }, lease)).toBe(true); + // An earlier incident, cleared before the window, bounds the walk. + const earlier = openRed(emptyRedMain(), { firstBad: A, run: 50, failures: [real(raft, ["in-affected-closure"], 50, A)] }, T0 - 200 * minute); + expect(store.publishRedMain(store.read(), earlier)).toBe(true); + expect(store.publishRedMain(store.read(), clearRed(earlier, { ...covering(earlier), id: 60 }, T0 - 150 * minute))).toBe(true); + for (const [step, next] of incidentLifecycle(store.read().redMain).entries()) { + expect(store.publishRedMain(store.read(), next)).toBe(true); + // A reservation write between record writes copies the record unchanged. + if (step === 2) expect(store.publish(store.read(), reservationTransition(store.read().state, { kind: "release", id: "2".repeat(32) }, 1, T0 + 2 * minute + 1))).toBe(true); + } + const history = collectRedMainHistory(repo, iso(-60), work); + expect(history.error).toBeUndefined(); + expect(history.incidents.map(i => i.run), "EARLIER_INCIDENT_OUTSIDE_WINDOW").toEqual([100]); + expect(history.incidents[0]).toMatchObject({ opened: T0, firstBad: B, incident: 500, fixes: [8], reported: [C], cleared: { at: T0 + 90 * minute, run: 400 } }); + // One source per record write, not per reservation write. + expect(history.incidents[0]!.sources).toHaveLength(7); + const wide = collectRedMainHistory(repo, iso(-400), work); + expect(wide.incidents.map(i => i.run)).toEqual([50, 100]); + expect(wide.incidents[0]!.cleared).toEqual({ at: T0 - 150 * minute, run: 60 }); + } finally { rmSync(dir, { recursive: true, force: true }); } +}); + +test("native report writes the red-main section from downloaded archives", () => { + const dir = mkdtempSync(join(tmpdir(), "ci-red-main-report-")); + try { + writeFileSync(join(dir, "red-main.json"), JSON.stringify(archive(incidentLifecycle()))); + writeFileSync(join(dir, "coordinator-900-attempt-1.json"), JSON.stringify({ version: 1, repository: repo, collectedAt: iso(200), run: 900, attempt: 1, + createdAt: iso(0), conclusion: "success", cancelled: [300], problem: null })); + writeFileSync(join(dir, "run-300-attempt-1.json"), JSON.stringify(attempt(300, "cancelled", 120))); + writeFileSync(join(dir, "run-320-attempt-1.json"), JSON.stringify(attempt(320, "success", 600))); + writeFileSync(join(dir, "run-410-attempt-1.json"), JSON.stringify(attempt(410, "success", 60, "push", { head: C, prs: [7], attribution: "exact merged squash SHA" }))); + const child = Bun.spawnSync([process.execPath, "scripts/ci-timings.ts", "report", "--out", dir], { stdout: "pipe", stderr: "pipe" }); + expect(new TextDecoder().decode(child.stderr)).toBe(""); + expect(child.exitCode).toBe(0); + const report = JSON.parse(readFileSync(join(dir, "summary.json"), "utf8")); + expect(report.redMain.incidents[0].timeToGreenSeconds).toBe(5400); + expect(report.redMain.cancellations).toMatchObject({ count: 1, estimatedSavedRunnerSeconds: 480 }); + expect(report.redMain.mergesDuringRed.rows[0].pr).toBe(7); + const md = readFileSync(join(dir, "summary.md"), "utf8"); + expect(md).toContain("## Red-main incidents"); + expect(md).toContain("| `cccccccccccc` | #7 | 100 |"); + rmSync(join(dir, "red-main.json")); + expect(Bun.spawnSync([process.execPath, "scripts/ci-timings.ts", "report", "--out", dir]).exitCode).toBe(0); + expect(JSON.parse(readFileSync(join(dir, "summary.json"), "utf8")).redMain, "NO_ARCHIVE_IS_UNKNOWN").toBeNull(); + } finally { rmSync(dir, { recursive: true, force: true }); } +}); diff --git a/tests/ci-timings-collection.test.ts b/tests/ci-timings-collection.test.ts index 1b7d4aa8b2..502cee7bc0 100644 --- a/tests/ci-timings-collection.test.ts +++ b/tests/ci-timings-collection.test.ts @@ -104,10 +104,13 @@ test("scheduled seeded collection fetches only new, incomplete and rerun attempt try { f.seed({ "run-12-attempt-1.json": seededSnapshot(12), "run-13-attempt-1.json": incomplete, "run-15-attempt-1.json": old, + // A red-main coordinator observation (#2953) is carried forward so its log is never fetched twice. + "coordinator-900-attempt-1.json": { version: 1, repository, collectedAt: "2026-07-12T11:00:00Z", run: 900, attempt: 1, + createdAt: "2026-07-12T10:05:00Z", conclusion: "success", cancelled: [12], problem: null }, "pull-42.json": { version: 1, repository, number: 42, collectedAt: "2026-07-12T11:00:00Z", head: "a".repeat(40), merge: "b".repeat(40), createdAt: "2026-07-12T10:00:00Z", mergedAt: "2026-07-12T10:01:00Z", closedAt: "2026-07-12T10:01:00Z", baseBranch: "main", changedFiles: 1, additions: 1, deletions: 0, problems: [], timeline: [] } }); - const child = f.invoke(["--seed", "main", "--request-budget", "200", "--reserve", "500", "--reservations"]); + const child = f.invoke(["--seed", "main", "--request-budget", "200", "--reserve", "500", "--reservations", "--red-main"]); expect(new TextDecoder().decode(child.stderr)).toBe(""); expect(child.exitCode).toBe(0); expect(f.calls().filter(p => p.includes("/jobs?")).sort()).toEqual([ @@ -117,7 +120,11 @@ test("scheduled seeded collection fetches only new, incomplete and rerun attempt expect(f.calls().filter(p => p.includes("pulls?state="))).toHaveLength(1); expect(f.calls().some(p => p.endsWith("pulls/42"))).toBe(false); expect(f.calls()).toHaveLength(10); - expect(f.json("collection.json").seed).toEqual({ run: 99, artifact: 77, snapshots: 2, pulls: 1, error: null }); + expect(f.json("collection.json").seed, "COORDINATOR_OBSERVATION_SEEDED").toEqual({ run: 99, artifact: 77, snapshots: 2, pulls: 1, coordinator: 1, error: null }); + expect(f.json("coordinator-900-attempt-1.json").cancelled).toEqual([12]); + // The coordination ref is unreachable here: red-main evidence is an explicit gap, not a quiet main. + expect(f.json("red-main.json").error).toContain("Reservation ref unavailable"); + expect(f.json("summary.json").redMain.acquisition.complete, "RED_MAIN_GAP_REPORTED").toBe(false); expect(f.json("summary.json").coverage.runAttempts).toBe(4); expect(f.json("summary.json").coverage.incompleteAttempts).toBe(0); expect(f.json("summary.json").throughput.reservation).toBeNull(); diff --git a/tests/ci-timings.test.ts b/tests/ci-timings.test.ts index daadfc0708..003d51d96c 100644 --- a/tests/ci-timings.test.ts +++ b/tests/ci-timings.test.ts @@ -129,7 +129,9 @@ test("collection workflow reads trusted code with a read-only token and no candi expect(timingWorkflowProblems(workflow.replace(" schedule:", " workflow_run:\n schedule:"))).toContain("ci-timings.yml: measurement must use scheduled/manual trusted execution only"); for (const unsafe of [workflow.replace("--request-budget 200", "--request-budget 1000"), workflow.replace("--reserve 500", "--reserve 0"), workflow.replace('--seed "$TIMING_DEFAULT_BRANCH" ', ""), - workflow.replace("--reservations", "--resources --reservations")]) { + workflow.replace("--reservations", "--resources --reservations"), + // Red-main evidence (#2953) is part of every scheduled collection. + workflow.replace(" --red-main", "")]) { expect(timingWorkflowProblems(unsafe)).toContain("ci-timings.yml: timing collection requires seeded acquisition, a hard budget/reserve and no scheduled resource logs"); } expect(timingWorkflowProblems(workflow.replace('"43 * * * *"', '"43 6 * * *"'))) diff --git a/tests/red-main.test.ts b/tests/red-main.test.ts index 530bfa93f8..05542e5ccc 100644 --- a/tests/red-main.test.ts +++ b/tests/red-main.test.ts @@ -6,6 +6,7 @@ import type { CheckPlan } from "../scripts/ci-plan"; import { GitReservationStore } from "../scripts/integration-reservation"; import { addSuspect, classifyFailure, clearRed, declareFix, emptyRedMain, FLAKE_WINDOW_MS, gateDecision, includeRedSet, junitFailures, recordExpedited, openRed, parseRedMain, POST_MERGE_CATEGORIES, postMergeOnly, type RedFailure, type RedMainRecord } from "../scripts/red-main"; +import { coordinatorCancellations } from "../scripts/ci-red-main"; import { coordinate, detectLanded, includedRedSet, incidentMarker, type CoordinatorIO, type Job, type Snapshot, type WorkflowRun } from "../scripts/red-main-coordinator"; const ROOT = resolve(import.meta.dir, ".."); @@ -175,7 +176,7 @@ describe("hosted gate", () => { function fakeGitHub(options: { jobs: Job[]; junit?: string; artifact?: Record; 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 comments: { issue: number; body: string }[] = [], cancelled: number[] = [], dispatched: unknown[] = [], events: unknown[] = [], printed: string[] = []; const io: CoordinatorIO = { repository: "odysseus/brain-kit", async json(path) { @@ -217,9 +218,9 @@ function fakeGitHub(options: { jobs: Job[]; junit?: string; artifact?: Record a === b || (a === A && b !== A) || (a === B && b === C), commitTime: () => NOW, async recordEvent(event) { events.push(event); }, - print() {}, + print(line) { printed.push(line); }, }; - return { io, issues, comments, cancelled, dispatched, events, record: () => snapshot.redMain, set: (record: RedMainRecord) => { snapshot = { oid: String(++version), redMain: record }; } }; + return { io, issues, comments, cancelled, dispatched, events, printed, 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" }); @@ -268,7 +269,7 @@ describe("coordinator", () => { }); 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, + const gh = fakeGitHub({ jobs: [{ id: 2, name: "unit (2)", conclusion: "failure", steps: [] }], closure: false, prRuns: [prRun(320, 9, C)], junit: junit.replace("expect(received).toBe(expected)", "") }); await coordinate(gh.io, mainRun(B, "failure")); expect(gh.record().open).toBeNull(); @@ -279,6 +280,9 @@ describe("coordinator", () => { 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); + // The probe path prints the main-run cancellation line too, so the evidence collector (#2953) sees it. + expect(gh.cancelled).toEqual([320]); + expect(coordinatorCancellations(gh.printed.join("\n"), "failure"), "PROBE_CANCELLATIONS_PRINTED").toEqual([320]); }); test("first bad is the first commit after the last green run, and a squash landed while red is reported", async () => {