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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions docs/process/ci-throughput.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand Down Expand Up @@ -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.
3 changes: 3 additions & 0 deletions docs/process/ci-timings.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion scripts/ci-timing-seed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
44 changes: 36 additions & 8 deletions scripts/ci-timings.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -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;
}
Expand All @@ -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;
Expand All @@ -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) })),
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -201,7 +201,7 @@ function end(snapshot: TimingSnapshot): string | null {
export function deduplicate(snapshots: TimingSnapshot[]): TimingSnapshot[] {
const result = new Map<string, TimingSnapshot>();
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; }
Expand All @@ -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";
}
Expand All @@ -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");
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -311,6 +331,14 @@ export function markdown(report: ReturnType<typeof summarize>): 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)}.`,
Expand Down
3 changes: 2 additions & 1 deletion tests/ci-timings-collection.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Loading
Loading