diff --git a/docs/process/ci-throughput.md b/docs/process/ci-throughput.md index d479cf0af1..f128577d2e 100644 --- a/docs/process/ci-throughput.md +++ b/docs/process/ci-throughput.md @@ -67,6 +67,7 @@ execution. It is not complete lifetime cost without complete lifetime coverage. | Merge → same-commit green | Time to observed green main proof on that exact squash. Recovery via a later repair commit needs an explicit related record. | | Pre-green/main-nongreen | A green aggregate at the final head followed by non-green first main proof. Discordance, not a diagnosed escaped defect. | | Same-source recovery | Failed/cancelled first main attempt followed by green at the same SHA. Not, by itself, a diagnosed flaky test. | +| Runner-slot wait | Job creation → observed execution start, in seconds. Overall and workflow/category/event cohorts report known sample count, median, nearest-rank p90, max, unknown count and jobs waiting strictly over 300 seconds / known jobs (with percentage). | | Dependency → job start | Metadata completion → selected job start, including dispatch/queue delay. Does not isolate capacity pressure. | | CI concurrency | Time-weighted executed-job overlap, peak and means while active/across the interval. Adjacent end-exclusive intervals do not invent overlap. | | PR verification concurrency | Distinct PRs with verification intervals, merging overlapping attempts of one PR. Includes queueing; not active agent count. | @@ -213,3 +214,32 @@ agent-concurrency settings, work/queue/lease events, complete proof, main result and follow-up incident records. Compare green deliveries/day, tail latency, runner cost and recovery work together. A faster merge with unfinished main verification does not meet this objective. + +## Runner-slot wait + +New `run` snapshots use schema v2 and retain each job's API `created_at` as +`jobs[].createdAt`. Readers accept v1 and v2 and refuse unknown versions; +legacy v1 archives are preserved without inventing creation timestamps. +`summary.json` is v2 and exposes `runnerSlotWait.overall`, `byWorkflow` +(workflow path), `byCategory` and `byEvent`. `summary.md` renders those cohorts. +Each cohort carries `n`, `mean`, `median`, `p90`, `max`, `unknown` and +`overFiveMinutes: { numerator, denominator, percent }`. Durations are seconds; +Markdown displays minutes. The percentage denominator is known intervals only, +and an empty denominator has an unknown percentage. + +PR event cohorts are `pull_request_draft` and `pull_request_ready` when retained +planner context establishes draft or feedback/confirmation cadence. Without +that evidence they are `pull_request_unknown`; current PR draft state is never +projected onto a historical run. Optional `--resources` enrichment reads this +context; the hourly collector does not fetch logs just to classify PRs. +Main pushes use `push_main` when the retained branch is `main`; dispatch uses +`workflow_dispatch`, and other events retain their API event name. + +Missing, invalid or reversed timestamps and jobs without observed executed +steps count as unknown and stay outside percentiles and the five-minute share. +A real zero remains a known sample. For example, creation at 10:00:00 and start +at 10:03:30 yields 210 seconds. Queue cancellations with synthetic-looking +start timestamps cannot establish a start. This is creation-to-start latency, +including dependency/dispatch delay; it does not isolate runner capacity, +reservation admission or draft-feedback starvation. It remains separate from +the first-attempt run-level initial queue estimate and metadata-to-job delay. diff --git a/docs/process/ci-timings.md b/docs/process/ci-timings.md index 92d32b505b..a77c375939 100644 --- a/docs/process/ci-timings.md +++ b/docs/process/ci-timings.md @@ -197,6 +197,9 @@ The report distinguishes three quantities: Initial queue is separately request-to-first-observed-job for first attempts. A rerun's original `created_at` is not its request time. Dependent-job queue eligibility, reservations, human review and ready-to-merge time are unknown. +- **Runner-slot wait:** job creation to observed execution start, with explicit + unknown counts and a known-job denominator for waits over five minutes. See + [cohorts and schema versions](ci-throughput.md#runner-slot-wait). - **Check duration:** mean, median, nearest-rank p90 and sample count per event/category, named step and successful resource-command phase. Job/step samples include observed failed and cancelled execution. Means across diff --git a/scripts/ci-timing-seed.ts b/scripts/ci-timing-seed.ts index 0493d95530..657bedadab 100644 --- a/scripts/ci-timing-seed.ts +++ b/scripts/ci-timing-seed.ts @@ -37,7 +37,7 @@ export async function seedTimings(api: TimingClient, repository: string, branch: const path = join(extracted, name); if (!(await lstat(path)).isFile()) throw new Error("Seed contains a non-file observation"); const value = await Bun.file(path).json(); - if (value.version !== 1 || value.repository !== repository) throw new Error("Seed repository/version mismatch"); + if (!(name.startsWith("run-") ? [1, 2].includes(value.version) : value.version === 1) || value.repository !== repository) throw new Error("Seed repository/version mismatch"); if (name.startsWith("run-")) { if (name !== `run-${value.run?.id}-attempt-${value.run?.attempt}.json` || !Array.isArray(value.jobs) || !Array.isArray(value.problems) || !Number.isFinite(Date.parse(value.run.createdAt))) throw new Error("Invalid seed attempt identity"); diff --git a/scripts/ci-timings.ts b/scripts/ci-timings.ts index 5e8d58e1c7..c0af36a5c3 100644 --- a/scripts/ci-timings.ts +++ b/scripts/ci-timings.ts @@ -1,7 +1,7 @@ /** Read-only CI timing archive. Logs are data; no candidate code is executed. */ import { mkdir, readdir, writeFile } from "node:fs/promises"; import { join, resolve } from "node:path"; -import { seconds, stats } from "./ci-timing-stats"; +import { percentage, seconds, stats } from "./ci-timing-stats"; export { seconds, stats } from "./ci-timing-stats"; import { collectPullObservation, summarizeThroughput, throughputMarkdown, validateWorkEvent, type PullObservation, type WorkEvent, type Scenario } from "./ci-throughput"; @@ -22,12 +22,12 @@ interface RawRun { interface RawStep { name: string; number: number; status: string; conclusion: string | null; started_at?: string; completed_at?: string; } interface RawJob { id: number; run_id: number; run_attempt?: number; name: string; status: string; - conclusion: string | null; started_at?: string; completed_at?: string; labels?: string[]; steps?: RawStep[]; + conclusion: string | null; created_at?: string; started_at?: string; completed_at?: string; labels?: string[]; steps?: RawStep[]; } export interface TimingJob { id: number; name: string; category: string; conclusion: string | null; labels: string[]; execution: "observed" | "excluded" | "retained" | "unobserved"; - startedAt: string | null; completedAt: string | null; seconds: number | null; + createdAt?: string | null; startedAt: string | null; completedAt: string | null; seconds: number | null; steps: { number: number; name: string; conclusion: string | null; seconds: number | null }[]; resource: Resource | null; resourceProblem: string | null; } @@ -37,7 +37,7 @@ interface Resource { machine: { logicalCpus: number; totalBytes: number; activeCpuSeconds: number; sampledPeakUsedBytes: number }; } export interface TimingSnapshot { - version: 1; repository: string; collectedAt: string; + version: 1 | 2; repository: string; collectedAt: string; run: { id: number; attempt: number; workflow: string; path: string; event: string; head: string; branch?: string; headRepository?: string; createdAt: string; startedAt: string | null; status: string; conclusion: string | null; @@ -63,7 +63,7 @@ export function normalizeJob(job: RawJob): TimingJob { step.conclusion !== "skipped" && Number.isFinite(Date.parse(step.started_at ?? ""))); const execution = job.conclusion === "skipped" ? "excluded" : observed ? "observed" : "unobserved"; return { id: job.id, name: job.name, category: category(job.name), conclusion: job.conclusion, - labels: job.labels ?? [], execution, startedAt: job.started_at ?? null, completedAt: job.completed_at ?? null, + labels: job.labels ?? [], execution, createdAt: job.created_at ?? null, startedAt: job.started_at ?? null, completedAt: job.completed_at ?? null, seconds: execution === "observed" ? seconds(job.started_at, job.completed_at) : null, steps: (job.steps ?? []).map(step => ({ number: step.number, name: step.name, conclusion: step.conclusion, seconds: step.conclusion === "skipped" ? null : seconds(step.started_at, step.completed_at) })), @@ -119,7 +119,7 @@ export async function collectAttempt(api: TimingAPI, repository: string, raw: Ra const run: RawRun = attempt === raw.run_attempt ? raw : await api.json(`actions/runs/${raw.id}/attempts/${attempt}`); if (run.id !== raw.id || run.run_attempt !== attempt || !SHA.test(run.head_sha) || !WORKFLOWS.some(w => run.path === `.github/workflows/${w}`)) throw new Error("Run attempt identity mismatch"); - const snapshot: TimingSnapshot = { version: 1, repository, collectedAt: now, + const snapshot: TimingSnapshot = { version: 2, repository, collectedAt: now, run: { id: run.id, attempt, workflow: run.name, path: run.path, event: run.event, head: run.head_sha, branch: run.head_branch, headRepository: run.head_repository?.full_name, createdAt: run.created_at, startedAt: run.run_started_at ?? null, status: run.status, conclusion: run.conclusion, @@ -201,7 +201,7 @@ function end(snapshot: TimingSnapshot): string | null { export function deduplicate(snapshots: TimingSnapshot[]): TimingSnapshot[] { const result = new Map(); for (const snapshot of snapshots) { - if (snapshot.version !== 1 || !/^[\w.-]+\/[\w.-]+$/.test(snapshot.repository) || !Number.isSafeInteger(snapshot.run?.id) || !Number.isSafeInteger(snapshot.run.attempt) || !Array.isArray(snapshot.jobs) || !Array.isArray(snapshot.problems)) throw new Error("Invalid timing snapshot"); + if (![1, 2].includes(snapshot.version) || !/^[\w.-]+\/[\w.-]+$/.test(snapshot.repository) || !Number.isSafeInteger(snapshot.run?.id) || !Number.isSafeInteger(snapshot.run.attempt) || !Array.isArray(snapshot.jobs) || !Array.isArray(snapshot.problems)) throw new Error("Invalid timing snapshot"); const key = `${snapshot.repository}/${snapshot.run.id}/${snapshot.run.attempt}`; const old = result.get(key); if (!old) { result.set(key, structuredClone(snapshot)); continue; } @@ -217,6 +217,7 @@ export function deduplicate(snapshots: TimingSnapshot[]): TimingSnapshot[] { if (!merged.candidate && older.candidate) merged.candidate = older.candidate; for (const job of merged.jobs) { const previous = older.jobs.find(j => j.id === job.id); + if (!job.createdAt && previous?.createdAt) { job.createdAt = previous.createdAt; merged.version = 2; } if (!job.resource && previous?.resource) { job.resource = previous.resource; job.resourceProblem = null; } if (job.execution === "excluded" && merged.selection?.retained.includes(job.category)) job.execution = "retained"; } @@ -225,6 +226,25 @@ export function deduplicate(snapshots: TimingSnapshot[]): TimingSnapshot[] { return [...result.values()].sort((a, b) => a.run.id - b.run.id || a.run.attempt - b.run.attempt); } +/** Creation-to-start is an observation, not a diagnosis of capacity pressure. */ +function runnerSlotWait(snapshots: TimingSnapshot[]) { + const rows = snapshots.flatMap(s => s.jobs.map(j => ({ + workflow: s.run.path, category: j.category, + event: s.run.event === "pull_request" ? s.context?.cadence === "draft" ? "pull_request_draft" : + ["feedback", "confirmation"].includes(s.context?.cadence ?? "") ? "pull_request_ready" : "pull_request_unknown" : + s.run.event === "push" && s.run.branch === "main" ? "push_main" : s.run.event, + wait: j.execution === "observed" ? seconds(j.createdAt, j.startedAt) : null, + }))); + const aggregate = (items: typeof rows) => { + const values = items.flatMap(r => r.wait === null ? [] : [r.wait]); + return { ...stats(values), max: values.length ? values.reduce((max, n) => Math.max(max, n), 0) : null, + unknown: items.length - values.length, overFiveMinutes: percentage(values.filter(n => n > 300).length, values.length) }; + }; + const group = (key: "workflow" | "category" | "event") => Object.fromEntries( + [...new Set(rows.map(r => r[key]))].sort().map(value => [value, aggregate(rows.filter(r => r[key] === value))])); + return { overall: aggregate(rows), byWorkflow: group("workflow"), byCategory: group("category"), byEvent: group("event") }; +} + export function summarize(input: TimingSnapshot[]) { const snapshots = deduplicate(input), ci = snapshots.filter(s => s.run.path === ".github/workflows/ci.yml"); if (new Set(snapshots.map(s => s.repository)).size > 1) throw new Error("Report one repository at a time"); @@ -256,7 +276,7 @@ export function summarize(input: TimingSnapshot[]) { const baselineStats = stats(baseline.map(executionSeconds)); const baselineElapsed = stats(baseline.flatMap(s => { const n = seconds(s.run.startedAt, end(s)); return n === null ? [] : [n]; })); const paired = prs.filter(pr => pr.pairedInWindow); - return { version: 1, coverage: { runAttempts: snapshots.length, runs: new Set(snapshots.map(s => `${s.repository}/${s.run.id}`)).size, + return { version: 2, runnerSlotWait: runnerSlotWait(snapshots), coverage: { runAttempts: snapshots.length, runs: new Set(snapshots.map(s => `${s.repository}/${s.run.id}`)).size, prs: prs.length, pairedPRs: paired.length, incompleteAttempts: snapshots.filter(s => s.problems.length || s.run.status !== "completed").length, jobs: snapshots.reduce((n, s) => n + s.jobs.length, 0), unobservedJobs: snapshots.flatMap(s => s.jobs).filter(j => j.execution === "unobserved").length, @@ -311,6 +331,14 @@ export function markdown(report: ReturnType): string { `Observed runner minutes: ${minutes(report.observedRunnerSeconds)}; cancelled attempts: ${minutes(report.cancelledAttemptRunnerSeconds)}; failed attempts: ${minutes(report.failedAttemptRunnerSeconds)}.`, "", "| Event / category | Jobs | Mean min | Median min | p90 min |", "| --- | ---: | ---: | ---: | ---: |", ...Object.entries(report.categories).map(([key, value]) => `| ${key.replaceAll("|", "\\|")} | ${value.n} | ${minutes(value.mean)} | ${minutes(value.median)} | ${minutes(value.p90)} |`), "", + "## Runner-slot wait", "", "Creation to observed execution start; absent, invalid and unexecuted intervals are unknown. Shares use known jobs only.", "", + "| Cohort | Known jobs | Unknown jobs | Median min | p90 min | Max min | >5 min / known | Share % |", + "| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |", + ...[["overall", report.runnerSlotWait.overall] as const, + ...Object.entries(report.runnerSlotWait.byWorkflow).map(([k, v]) => [`workflow/${k}`, v] as const), + ...Object.entries(report.runnerSlotWait.byCategory).map(([k, v]) => [`category/${k}`, v] as const), + ...Object.entries(report.runnerSlotWait.byEvent).map(([k, v]) => [`event/${k}`, v] as const)].map(([key, v]) => + `| ${key.replaceAll("|", "\\|")} | ${v.n} | ${v.unknown} | ${minutes(v.median)} | ${minutes(v.p90)} | ${minutes(v.max)} | ${v.overFiveMinutes.numerator}/${v.overFiveMinutes.denominator} | ${v.overFiveMinutes.percent ?? "unknown"} |`), "", "## Approximate full-proof comparison", "", report.baseline.label + ".", "The two-run reference assumes a clean first pass; every-attempt costing is the opposite extreme. Use the explicit throughput scenario for a failure/rework assumption.", `Successful exhaustive samples: ${report.baseline.samples.length}; median runner minutes per full run: ${minutes(report.baseline.runnerSeconds.median)}.`, diff --git a/tests/ci-timings-collection.test.ts b/tests/ci-timings-collection.test.ts index 502cee7bc0..f23bce0db9 100644 --- a/tests/ci-timings-collection.test.ts +++ b/tests/ci-timings-collection.test.ts @@ -99,10 +99,11 @@ function seededSnapshot(id: number): TimingSnapshot { test("scheduled seeded collection fetches only new, incomplete and rerun attempts and reuses merged lifecycle data", () => { const f = fixture({ count: 3, rerun: true, pullCount: 1, headerlessDownloads: true }); + const complete = seededSnapshot(12); complete.version = 2; complete.jobs[0]!.createdAt = complete.jobs[0]!.startedAt; const incomplete = seededSnapshot(13); incomplete.jobs = []; incomplete.problems = ["jobs unavailable"]; const old = seededSnapshot(15); old.run.createdAt = "2026-07-04T10:00:00Z"; try { - f.seed({ "run-12-attempt-1.json": seededSnapshot(12), "run-13-attempt-1.json": incomplete, + f.seed({ "run-12-attempt-1.json": complete, "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, diff --git a/tests/ci-timings.test.ts b/tests/ci-timings.test.ts index 003d51d96c..8a2a255212 100644 --- a/tests/ci-timings.test.ts +++ b/tests/ci-timings.test.ts @@ -243,3 +243,61 @@ test("native report joins overlapping downloaded reservation and acquisition arc expect(new TextDecoder().decode(conflict.stderr)).toContain("Conflicting lease history"); } finally { rmSync(dir, { recursive: true, force: true }); } }); + +test("runner-slot wait preserves creation time and legacy unknowns", async () => { + const created = "2026-07-12T10:00:00Z", started = "2026-07-12T10:03:30Z"; + const api: TimingAPI = { json: async () => ({ total_count: 1, jobs: [{ ...job(), created_at: created, started_at: started }] }), log: async () => "" }; + const fresh = await collectAttempt(api, "odysseus/chronicle", rawRun, 1, false); + expect(fresh.version).toBe(2); + expect(fresh.jobs[0]!.createdAt).toBe(created); + fresh.context = { cadence: "draft", global: false, head: sha }; + const legacy = snapshot(13); legacy.jobs[0]!.id = 2; + delete legacy.jobs[0]!.createdAt; + const report = summarize([fresh, legacy]); + expect(report.runnerSlotWait.overall).toEqual({ n: 1, mean: 210, median: 210, p90: 210, max: 210, + unknown: 1, overFiveMinutes: { numerator: 0, denominator: 1, percent: 0 } }); + expect(report.runnerSlotWait.byWorkflow[rawRun.path]!.unknown).toBe(1); + expect(report.runnerSlotWait.byCategory.unit!.median).toBe(210); + expect(report.runnerSlotWait.byEvent.pull_request_draft!.n).toBe(1); + expect(report.runnerSlotWait.byEvent.pull_request_unknown!.unknown).toBe(1); + expect(markdown(report)).toContain("Runner-slot wait"); + expect(markdown(report)).toContain("unknown"); +}); + +test("runner-slot wait cohorts keep strict threshold, real zero and unexecuted unknowns", () => { + const inputs = [0, 300, 301, 900].map((wait, i) => { + const s = snapshot(20 + i); s.version = 2; s.jobs[0]!.id = 20 + i; + s.jobs[0]!.createdAt = start; s.jobs[0]!.startedAt = new Date(Date.parse(start) + wait * 1000).toISOString(); + s.run.event = ["pull_request", "push", "workflow_dispatch", "pull_request"][i]!; + s.run.branch = "main"; s.context = { cadence: "confirmation", global: false, head: sha }; return s; + }); + const queued = snapshot(30); queued.jobs = [normalizeJob({ ...job(30), created_at: start, steps: [], conclusion: "cancelled" })]; + const r = summarize([...inputs, queued]).runnerSlotWait; + expect(r.overall).toEqual({ n: 4, mean: 375.25, median: 300.5, p90: 900, max: 900, unknown: 1, + overFiveMinutes: { numerator: 2, denominator: 4, percent: 50 } }); + expect(r.byEvent.pull_request_ready!.n).toBe(2); + expect(r.byEvent.push_main!.median).toBe(300); + expect(r.byEvent.workflow_dispatch!.median).toBe(301); +}); + +test("native report reads v2 slot waits with legacy archives and rejects unknown versions", () => { + const dir = mkdtempSync(join(tmpdir(), "slot-wait-")); + try { + const s = snapshot(); s.version = 2; s.jobs[0]!.createdAt = start; + s.jobs[0]!.startedAt = "2026-07-12T10:03:30Z"; + writeFileSync(join(dir, "run-12-attempt-1.json"), JSON.stringify(s)); + const legacy = snapshot(13); legacy.jobs[0]!.id = 2; delete legacy.jobs[0]!.createdAt; + writeFileSync(join(dir, "run-13-attempt-1.json"), JSON.stringify(legacy)); + const child = Bun.spawnSync([process.execPath, "scripts/ci-timings.ts", "report", "--out", dir], { stdout: "pipe", stderr: "pipe" }); + expect(child.exitCode).toBe(0); + const r = JSON.parse(readFileSync(join(dir, "summary.json"), "utf8")); + expect(r.version).toBe(2); expect(r.runnerSlotWait.overall.median).toBe(210); + expect(r.runnerSlotWait.overall.unknown).toBe(1); + expect(readFileSync(join(dir, "summary.md"), "utf8")).toContain("3.50"); + expect(() => deduplicate([{ ...s, version: 3 } as unknown as TimingSnapshot])).toThrow("Invalid timing snapshot"); + const older = structuredClone(s); older.collectedAt = start; + const newer = structuredClone(s); newer.version = 1; delete newer.jobs[0]!.createdAt; + expect(deduplicate([older, newer])[0]!.jobs[0]!.createdAt).toBe(start); + expect(deduplicate([older, newer])[0]!.version).toBe(2); + } finally { rmSync(dir, { recursive: true, force: true }); } +});