diff --git a/scripts/ci-budget.ts b/scripts/ci-budget.ts index 68a160794a..adcdc90c86 100644 --- a/scripts/ci-budget.ts +++ b/scripts/ci-budget.ts @@ -648,7 +648,104 @@ export function median(values: number[]): number { : ((sorted[middle - 1] as number) + (sorted[middle] as number)) / 2; } -export type Sample = { run: Run; minutes: number }; +/** One run's time for a job: the run, its minutes, where it ran, and when it started. */ +export type Sample = { + run: number; + minutes: number; + where: "merge queue" | "main"; + at: string; +}; + +/** + * The recent times of every job of one workflow, newest first, at most WINDOW each: what each job's + * median is taken over. CI watch keeps it in the body of the workflow's `CI budget record` issue and + * adds the run it watches, so it reads one run's jobs, not the last runs' every time (the Actions + * token has 1,000 API requests an hour for the whole repository). + */ +export type Ledger = { jobs: Record }; + +const LEDGER = //; + +/** The ledger in a record issue's body, or an empty one. */ +export function readLedger(body: string | null | undefined): Ledger { + const found = LEDGER.exec(body ?? "")?.[1]; + if (!found) return { jobs: {} }; + try { + const parsed = JSON.parse(found) as Ledger; + return parsed && typeof parsed.jobs === "object" ? parsed : { jobs: {} }; + } catch { + return { jobs: {} }; + } +} + +export function writeLedger(ledger: Ledger): string { + return ``; +} + +/** + * One steady run's samples: each job's slowest shard, the one the run waited for, from the attempt + * that passed; and the whole run, from a first attempt that passed (a re-run's span counts the wait + * between attempts). + */ +export function samplesOf(run: Run, jobs: Job[]): Map { + const where = run.event === "merge_group" ? "merge queue" : "main"; + const sample = (took: number): Sample => ({ + run: run.id, + minutes: Math.round(took * 100) / 100, + where, + at: run.created_at, + }); + const slowest = new Map(); + for (const job of jobs) { + if (job.conclusion !== "success") continue; + const took = minutes(job.started_at, job.completed_at); + if (took === undefined) continue; + const key = jobKey(job.name); + slowest.set(key, Math.max(slowest.get(key) ?? 0, took)); + } + const samples = new Map(); + for (const [key, took] of slowest) samples.set(key, sample(took)); + if (run.conclusion === "success" && run.run_attempt === 1) { + const ran = jobs.filter( + (j) => j.run_attempt === 1 && j.conclusion !== "skipped", + ); + const starts = ran.map((j) => j.started_at).filter(Boolean) as string[]; + const ends = ran.map((j) => j.completed_at).filter(Boolean) as string[]; + if (starts.length && ends.length) { + const took = minutes( + starts.reduce((a, b) => (a < b ? a : b)), + ends.reduce((a, b) => (a > b ? a : b)), + ); + // Main's runs and the merge queue's run different jobs (main's only build what the queue + // did not), so each is a run of its own shape, with its own median. + if (took !== undefined) + samples.set( + run.event === "merge_group" + ? "(whole run in the merge queue)" + : "(whole run on main)", + sample(took), + ); + } + } + return samples; +} + +/** + * The ledger with one more steady run in it: its samples first (by when the run started, so a run + * watched late still sits in its place), the same run's earlier attempt replaced, WINDOW kept. + */ +export function fold(ledger: Ledger, run: Run, jobs: Job[]): Ledger { + const next: Ledger = { jobs: { ...ledger.jobs } }; + for (const [key, sample] of samplesOf(run, jobs)) { + next.jobs[key] = [ + sample, + ...(next.jobs[key] ?? []).filter((s) => s.run !== run.id), + ] + .sort((a, b) => b.at.localeCompare(a.at)) + .slice(0, WINDOW); + } + return next; +} export type Measured = { /** @@ -661,63 +758,16 @@ export type Measured = { samples: Sample[]; }; -/** - * Each budgeted job's time across the most recent steady runs, newest first: in each run, its - * slowest shard, the one the run waited for, from the attempt that passed; and the whole run, from - * a first attempt that passed (a re-run's span counts the wait between attempts). Only budgets with - * at least FEWEST runs are measured. - */ -export function measure( +/** Each budgeted job's median over its samples in the ledger, once it has at least FEWEST. */ +export function measureLedger( workflow: string, - recorded: Recorded[], + ledger: Ledger, budgets: Budgets, ): Measured[] { const budget = budgets[workflow]; if (!budget) return []; - const runs = recorded - .filter(({ run }) => run.name === workflow && steady(run)) - .sort((a, b) => b.run.created_at.localeCompare(a.run.created_at)); - const samples = new Map(); - const add = (key: string, sample: Sample) => { - const list = samples.get(key) ?? []; - if (list.length < WINDOW) list.push(sample); - samples.set(key, list); - }; - for (const { run, jobs } of runs) { - const slowest = new Map(); - for (const job of jobs) { - if (job.conclusion !== "success") continue; - const took = minutes(job.started_at, job.completed_at); - if (took === undefined) continue; - const key = jobKey(job.name); - slowest.set(key, Math.max(slowest.get(key) ?? 0, took)); - } - for (const [key, took] of slowest) add(key, { run, minutes: took }); - if (run.conclusion === "success" && run.run_attempt === 1) { - const ran = jobs.filter( - (j) => j.run_attempt === 1 && j.conclusion !== "skipped", - ); - const starts = ran.map((j) => j.started_at).filter(Boolean) as string[]; - const ends = ran.map((j) => j.completed_at).filter(Boolean) as string[]; - if (starts.length && ends.length) { - const took = minutes( - starts.reduce((a, b) => (a < b ? a : b)), - ends.reduce((a, b) => (a > b ? a : b)), - ); - // Main's runs and the merge queue's run different jobs (main's only build what the queue - // did not), so each is a run of its own shape, with its own median. - if (took !== undefined) - add( - run.event === "merge_group" - ? "(whole run in the merge queue)" - : "(whole run on main)", - { run, minutes: took }, - ); - } - } - } const measured: Measured[] = []; - for (const [job, list] of samples) { + for (const [job, list] of Object.entries(ledger.jobs)) { const allowed = job.startsWith("(whole run") ? budget.run : budgetFor(budget.jobs, job); @@ -732,6 +782,29 @@ export function measure( return measured; } +/** The workflow's steady runs among these, folded into a ledger oldest first, then measured. */ +export function measure( + workflow: string, + recorded: Recorded[], + budgets: Budgets, +): Measured[] { + const ledger = recorded + .filter(({ run }) => run.name === workflow && steady(run)) + .sort((a, b) => a.run.created_at.localeCompare(b.run.created_at)) + .reduce((so, { run, jobs }) => fold(so, run, jobs), { jobs: {} }); + return measureLedger(workflow, ledger, budgets); +} + +/** + * Whether the ledger has had enough runs for a job missing from it to be one that does not run where + * times are held at all (a pull request's own jobs), not one that has not come round yet. + */ +export function warm(ledger: Ledger): boolean { + return Object.entries(ledger.jobs).some( + ([key, list]) => key.startsWith("(whole run") && list.length >= FEWEST, + ); +} + /** The jobs whose median over their recent steady runs is over budget. */ export function overBudget(measured: Measured[]): Measured[] { return measured.filter((m) => m.median > m.budget); diff --git a/scripts/ci-watch-requests.test.ts b/scripts/ci-watch-requests.test.ts new file mode 100644 index 0000000000..bbf239a0c1 --- /dev/null +++ b/scripts/ci-watch-requests.test.ts @@ -0,0 +1,203 @@ +import { afterAll, describe, expect, test } from "bun:test"; +import { + chmodSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fold, type Ledger, type Recorded, writeLedger } from "./ci-budget"; + +/** + * CI watch runs after every run of CI, and the Actions token it uses has 1,000 API requests an + * hour for the whole repository, shared with every other workflow. So each run of it makes a few + * requests, whatever the history: it reads the run it watches, and keeps the last runs' times in + * the record issue rather than reading those runs again. And when GitHub refuses (a rate limit), it + * warns and stops green rather than failing for GitHub's sake. + * + * scripts/ci-watch.ts runs here as it runs in CI, against a stand-in for `gh api` + * (ci-watch.fixtures/fake-gh.ts) that answers from real runs of this repository's CI and counts + * every request. + */ + +const ROOT = join(import.meta.dir, ".."); +const REPOSITORY = "CopilotKit/OpenBot"; +const runs = (file: string) => + JSON.parse( + readFileSync(join(import.meta.dir, "ci-budget.fixtures", file), "utf8"), + ) as Recorded[]; +const mergeQueue = runs("merge-queue-runs.json"); +const pullRequests = runs("pull-request-runs.json"); + +const dir = mkdtempSync(join(tmpdir(), "ci-watch-requests-")); +afterAll(() => rmSync(dir, { recursive: true, force: true })); +writeFileSync( + join(dir, "gh"), + `#!/bin/sh\nexec bun "${join(import.meta.dir, "ci-watch.fixtures", "fake-gh.ts")}" "$@"\n`, +); +chmodSync(join(dir, "gh"), 0o755); + +type Issue = { + number: number; + title: string; + state: string; + body?: string; + labels: string[]; +}; + +/** Runs CI watch on one run, as the workflow_run event hands it over; its requests and its exit. */ +function watch( + watched: Recorded, + world: { issues?: Issue[]; fail?: boolean; earlier?: Recorded[] } = {}, +) { + const name = `${watched.run.id}-${Math.random().toString(36).slice(2)}`; + const worldFile = join(dir, `${name}.world.json`); + const log = join(dir, `${name}.log`); + const event = join(dir, `${name}.event.json`); + writeFileSync( + worldFile, + JSON.stringify({ + runs: [watched, ...(world.earlier ?? [])], + issues: world.issues ?? [], + fail: world.fail, + }), + ); + writeFileSync(log, ""); + writeFileSync(event, JSON.stringify({ workflow_run: watched.run })); + const result = Bun.spawnSync(["bun", "scripts/ci-watch.ts"], { + cwd: ROOT, + env: { + ...process.env, + PATH: `${dir}:${process.env.PATH}`, + GITHUB_REPOSITORY: REPOSITORY, + GITHUB_EVENT_PATH: event, + GITHUB_STEP_SUMMARY: "", + FAKE_GH_WORLD: worldFile, + FAKE_GH_LOG: log, + }, + stdout: "pipe", + stderr: "pipe", + }); + const requests = readFileSync(log, "utf8") + .split("\n") + .filter(Boolean) + .map((line) => JSON.parse(line) as string[]); + return { + exit: result.exitCode, + out: result.stdout.toString(), + err: result.stderr.toString(), + requests, + }; +} + +const [newest, ...older] = mergeQueue as [Recorded, ...Recorded[]]; +const ledger: Ledger = [...older] + .reverse() + .reduce((so, { run, jobs }) => fold(so, run, jobs), { jobs: {} }); +const record: Issue = { + number: 3001, + title: "CI budget record: CI", + state: "open", + body: `The record.\n\n${writeLedger(ledger)}`, + labels: ["ci-budget"], +}; +const webkit: Issue = { + number: 2790, + title: "CI over budget: CI / app (real browser, WebKit) (shard N of N)", + state: "open", + labels: ["ci-budget"], +}; +const setupWindow: Issue = { + number: 2643, + title: "CI over budget: CI / app (real browser, desktop setup window)", + state: "open", + labels: ["ci-budget"], +}; + +/** The issues of the jobs these runs have over budget, already open. */ +const overIssues: Issue[] = [ + webkit, + setupWindow, + { + number: 3002, + title: "CI over budget: CI / (whole run in the merge queue)", + state: "open", + labels: ["ci-budget"], + }, +]; + +describe("a run in the merge queue", () => { + test("is measured from the record, in four requests, however many runs the medians span", () => { + // Every earlier run is there to be read, as on GitHub; CI watch must not need to. + const { exit, requests, out, err } = watch(newest, { + issues: [record, ...overIssues], + earlier: older, + }); + // The run's jobs, an earlier failed run of its commit (for flakes), the open ci-budget issues, + // and the record's update. No other run's jobs. + expect(requests).toHaveLength(4); + expect(err).not.toContain("gh:"); + expect( + requests.filter((r) => r.some((a) => /\/runs\/\d+\/jobs/.test(a))), + ).toHaveLength(1); + const update = requests.find((r) => + r.includes(`repos/${REPOSITORY}/issues/3001`), + ); + const body = update?.find((a) => a.startsWith("body=")) ?? ""; + // The record now holds this run's time first. + expect(body).toContain(`"run":${newest.run.id}`); + // Over budget, its issues already open: CI watch is red, and says so without a request more. + expect(out).toContain("still over, #2790"); + expect(exit).toBe(1); + }); + + test("with no record yet, starts one, and closes nothing it has not measured", () => { + const { requests } = watch(newest, { issues: [webkit] }); + expect(requests).toHaveLength(4); + const created = requests.find((r) => + r.includes("title=CI budget record: CI"), + ); + expect(created).toBeDefined(); + expect(requests.some((r) => r.includes("state=closed"))).toBe(false); + }); + + test("closes at most five stale issues in one run", () => { + const stale = Array.from({ length: 12 }, (_, i) => ({ + number: 4000 + i, + title: `CI over budget: CI / a pull request's own job ${i}`, + state: "open", + labels: ["ci-budget"], + })); + const { requests } = watch(newest, { + issues: [record, ...overIssues, ...stale], + }); + const closed = requests.filter((r) => r.includes("state=closed")); + expect(closed).toHaveLength(5); + // Four, then a comment and a close for each of the five: 14, never two per stale issue. + expect(requests).toHaveLength(4 + 2 * 5); + }); + + test("a job newly over budget costs three requests, once: its issue is opened", () => { + const { requests } = watch(newest, { issues: [record] }); + // Three jobs newly over: for each, the ci-budget issues (to reopen one closed), the new issue, + // and the check for one opened at the same moment. + expect(requests).toHaveLength(4 + 3 * 3); + }); +}); + +test("a pull request's run reads its own jobs and nothing more", () => { + const [run] = pullRequests as [Recorded]; + const { exit, requests } = watch(run); + expect(requests.length).toBeLessThanOrEqual(2); + expect(exit).toBe(0); +}); + +test("when GitHub refuses (a rate limit), CI watch warns and stops green", () => { + const { exit, out, requests } = watch(newest, { fail: true }); + expect(exit).toBe(0); + expect(out).toContain("::warning title=CI watch stopped::"); + expect(out).toContain("rate limit"); + expect(requests).toHaveLength(1); +}); diff --git a/scripts/ci-watch.fixtures/fake-gh.ts b/scripts/ci-watch.fixtures/fake-gh.ts new file mode 100644 index 0000000000..00daabd074 --- /dev/null +++ b/scripts/ci-watch.fixtures/fake-gh.ts @@ -0,0 +1,81 @@ +/** + * `gh api` for scripts/ci-watch-requests.test.ts: answers each request CI watch makes the way + * GitHub's REST API does, from recorded runs and the issues the test gives it, and writes every + * request to a log so the test can count them. With `fail` set it answers every request as a rate + * limit does: a message on stderr and exit code 1. + * + * Env: FAKE_GH_WORLD (a JSON file: { runs: Recorded[], issues: Issue-with-labels[], fail?: true }) + * and FAKE_GH_LOG (the file each request is appended to, one JSON array of arguments per line). + */ +import { appendFileSync, readFileSync } from "node:fs"; + +type World = { + runs: { run: { id: number }; jobs: unknown[] }[]; + issues: { number: number; title: string; state: string; labels: string[] }[]; + fail?: boolean; +}; + +const args = process.argv.slice(3); // bun, this file, "api", then gh api's own arguments +appendFileSync(process.env.FAKE_GH_LOG ?? "", `${JSON.stringify(args)}\n`); +const world = JSON.parse( + readFileSync(process.env.FAKE_GH_WORLD ?? "", "utf8"), +) as World; +if (world.fail) { + console.error( + "gh: API rate limit exceeded for installation ID 1. (HTTP 403)", + ); + process.exit(1); +} + +const path = args.find((a) => a.startsWith("repos/")) ?? ""; +const methodAt = args.indexOf("--method"); +const method = methodAt >= 0 ? args[methodAt + 1] : "GET"; +const url = new URL(`https://api.github.com/${path}`); +const answer = (value: unknown) => { + console.log(JSON.stringify(value)); + process.exit(0); +}; + +if (method === "GET") { + const run = /\/actions\/runs\/(\d+)(\/jobs)?$/.exec(url.pathname); + if (run) { + const found = world.runs.find((r) => r.run.id === Number(run[1])); + if (!found) { + console.error("gh: Not Found (HTTP 404)"); + process.exit(1); + } + if (!run[2]) answer(found.run); + const page = Number(url.searchParams.get("page") ?? "1"); + answer({ jobs: page === 1 ? found.jobs : [] }); + } + if (/\/actions\/workflows\/\d+\/runs$/.test(url.pathname)) { + const sha = url.searchParams.get("head_sha"); + const status = url.searchParams.get("status"); + const listed = world.runs + .map((r) => r.run as { head_sha?: string; conclusion?: string }) + .filter((r) => !sha || r.head_sha === sha) + .filter( + (r) => !status || status === "completed" || r.conclusion === status, + ); + answer({ total_count: listed.length, workflow_runs: listed }); + } + if (url.pathname.endsWith("/issues")) { + const label = url.searchParams.get("labels"); + const state = url.searchParams.get("state") ?? "open"; + const issues = world.issues + .filter((i) => !label || i.labels.includes(label)) + .filter((i) => state === "all" || i.state === state) + .map(({ labels, ...issue }) => ({ + ...issue, + labels: labels.map((name) => ({ name })), + })); + // --paginate --slurp: one array per page. + answer(args.includes("--slurp") ? [issues] : issues); + } +} else if (method === "POST" && url.pathname.endsWith("/issues")) { + answer({ number: 90_000, title: "", state: "open" }); +} else { + answer({}); +} +console.error(`gh: no route for ${method} ${path} (HTTP 404)`); +process.exit(1); diff --git a/scripts/ci-watch.ts b/scripts/ci-watch.ts index bedafcadac..de13e01211 100644 --- a/scripts/ci-watch.ts +++ b/scripts/ci-watch.ts @@ -14,9 +14,11 @@ * .github/ci-budgets.json, well under its `timeout-minutes` (which fails the job), and every * workflow has one for the whole run. After a run on main or in the merge queue, where timings are * steady, each job's median over its last five such runs is held to its budget: one slow run moves - * that median by nothing, a job that has crept moves it over. A job or a run over budget opens a - * `ci-budget` issue (or keeps the open one current) and fails this job, until it is back under, - * when its issue is closed. After a run on a pull request, the jobs it started are held to the most + * that median by nothing, a job that has crept moves it over. The last runs' times live in the + * workflow's `CI budget record` issue, which each run adds its own to, so a run reads only its own + * jobs (the Actions token has 1,000 API requests an hour for the whole repository). A job or a run + * over budget opens a `ci-budget` issue and fails this job, until it is back under, when its issue + * is closed. Should GitHub's API fail or refuse (a rate limit), this warns and stops, green. After a run on a pull request, the jobs it started are held to the most * its workflow files say a pull request can start, which a matrix known only at run time could * outgrow. scripts/ci-budgets.test.ts holds every job to having a budget. * @@ -30,20 +32,26 @@ import { appendFileSync, existsSync, readFileSync } from "node:fs"; import { join } from "node:path"; import { + type Budgets, + budgetFor, + fold, type Job, jobKey, + type Ledger, type Measured, - measure, + measureLedger, overBudget, pullRequestJobs, - type Recorded, type Run, readBudgets, + readLedger, started, steady, total, WINDOW, + warm, watchedBudgets, + writeLedger, } from "./ci-budget"; export { @@ -172,6 +180,12 @@ export function quiet(text: string, max = 200): string { // --------------------------------------------------------------------------------------------- +/** + * GitHub's API refused or failed a request: a rate limit, an outage. CI watch reports on CI; it is + * not CI, so it says so in a warning and stops, green, rather than turning red for GitHub's sake. + */ +export class ApiError extends Error {} + function gh(args: string[], input?: string): string { const result = Bun.spawnSync(["gh", "api", ...args], { stdin: input === undefined ? "ignore" : new TextEncoder().encode(input), @@ -179,8 +193,8 @@ function gh(args: string[], input?: string): string { stderr: "pipe", }); if (result.exitCode !== 0) { - throw new Error( - `gh api ${args.join(" ")}: ${result.stderr.toString().trim()}`, + throw new ApiError( + `gh api ${args.find((a) => a.startsWith("repos/")) ?? args[0]}: ${result.stderr.toString().trim()}`, ); } return result.stdout.toString(); @@ -206,7 +220,7 @@ async function jobLog(repository: string, jobId: number): Promise { }, ); if (!response.ok) { - throw new Error(`The log of job ${jobId}: HTTP ${response.status}`); + throw new ApiError(`The log of job ${jobId}: HTTP ${response.status}`); } return response.text(); } @@ -222,7 +236,12 @@ function jobsOf(repository: string, runId: number): Job[] { } } -export type Issue = { number: number; title: string; state: string }; +export type Issue = { + number: number; + title: string; + state: string; + body?: string | null; +}; /** * Of the issues with this title, the one every run writes to: the oldest. Two runs that each found @@ -234,12 +253,16 @@ export function keeperOf(issues: Issue[], title: string): Issue | undefined { .sort((a, b) => a.number - b.number)[0]; } -/** Every issue with this label, open or closed, every page of them. */ -function labelled(repository: string, label: string): Issue[] { +/** Every issue with this label, open or closed (or only the open ones), every page of them. */ +function labelled( + repository: string, + label: string, + state: "all" | "open" = "all", +): Issue[] { return json([ "--paginate", "--slurp", - `repos/${repository}/issues?labels=${label}&state=all&per_page=100`, + `repos/${repository}/issues?labels=${label}&state=${state}&per_page=100`, ]).flat(); } @@ -328,40 +351,39 @@ const COUNT_BODY = "A push to a pull request started more jobs than its workflow files allow (.github/ci-budgets.json, `pull request jobs` and `matrix legs`): a matrix known only once the run starts gave it more legs than its cap. Each comment below is one run that did. Start fewer, or raise the cap in a pull request that says why."; /** A measured job's median and the runs it was taken over, newest first. */ -export function measuredText(m: Measured): string { +export function measuredText(m: Measured, repository: string): string { const rows = m.samples.map( (s) => - `- [run ${s.run.id}](${s.run.html_url}), ${s.run.event === "merge_group" ? "merge queue" : s.run.head_branch}, ${s.run.created_at.slice(0, 16).replace("T", " ")}: ${s.minutes.toFixed(1)} minutes`, + `- [run ${s.run}](https://github.com/${repository}/actions/runs/${s.run}), ${s.where}, ${s.at.slice(0, 16).replace("T", " ")}: ${s.minutes.toFixed(1)} minutes`, ); return `Median **${m.median.toFixed(1)} minutes** over its last ${m.samples.length} runs, against a budget of ${m.budget}:\n\n${rows.join("\n")}`; } -/** - * Over budget: an open issue has its body kept current, so a job over budget for days does not - * comment on every run; one that is closed or missing is reopened or opened, with the comment. - */ -function budgetIssue( - repository: string, - issues: Issue[], - title: string, - body: string, - comment: string, - dryRun: boolean, +const RECORD_BODY = + "Every job's recent times on main and in the merge queue, kept by CI watch (scripts/ci-watch.ts) after each run there, newest first: the median of each job's last runs is what .github/ci-budgets.json holds it to. A job over its budget has an issue of its own. Leave this open: CI watch reads its times from here rather than reading every run again."; + +/** The record issue's body: a table a person reads, and the ledger CI watch reads back. */ +export function recordBody( + ledger: Ledger, + measured: Measured[], + budgets: Budgets[string] | undefined, ): string { - const found = keeperOf(issues, title); - if (found?.state !== "open") - return upsertIssue(repository, "ci-budget", title, body, comment, dryRun); - if (dryRun) return `would update #${found.number}: ${title}`; - gh([ - `repos/${repository}/issues/${found.number}`, - "--method", - "PATCH", - "-f", - `body=${body}`, - ]); - return `updated #${found.number}: ${title}`; + const medians = new Map(measured.map((m) => [m.job, m])); + const rows = Object.entries(ledger.jobs) + .sort(([a], [b]) => a.localeCompare(b)) + .map(([job, list]) => { + const m = medians.get(job); + const budget = job.startsWith("(whole run") + ? budgets?.run + : budgetFor(budgets?.jobs ?? {}, job); + return `| ${quiet(job, 120)} | ${m ? m.median.toFixed(1) : "–"} | ${budget ?? "–"} | ${list.map((s) => s.minutes.toFixed(1)).join(", ")} |`; + }); + return `${RECORD_BODY}\n\n| Job | Median | Budget | Last runs, newest first |\n|---|---|---|---|\n${rows.join("\n")}\n\n${writeLedger(ledger)}`; } +/** At most this many stale issues closed in one run, two requests each. */ +const CLOSES_PER_RUN = 5; + function closeIssue( repository: string, issue: Issue, @@ -388,7 +410,7 @@ function closeIssue( return `closed #${issue.number}: ${issue.title}`; } -if (import.meta.main) { +async function main() { const dryRun = process.argv.includes("--dry-run"); const repository = process.env.GITHUB_REPOSITORY ?? ""; if (!repository) { @@ -475,49 +497,79 @@ if (import.meta.main) { const file = readBudgets(ROOT); const budgets = watchedBudgets(file); - // Times, on a run whose times are steady: each job's median over its recent steady runs. + // Times, on a run whose times are steady: each job's median over its recent steady runs, from + // the workflow's record issue with this run added. Requests: the open ci-budget issues, the + // record's update, and only when something changes, an issue opened or a few closed. if (steady(run) && budgets[run.name]) { - const listed = json<{ workflow_runs: Run[] }>([ - `repos/${repository}/actions/workflows/${run.workflow_id}/runs?status=completed&per_page=50`, - ]).workflow_runs.filter((r) => steady(r) && r.id !== run.id); - // Enough runs for every job to have its window, when not every steady run runs every job: - // main's own runs build images; the merge queue's run the rest. - const recorded: Recorded[] = [{ run, jobs }]; - for (const r of listed.slice(0, WINDOW * 3)) - recorded.push({ run: r, jobs: jobsOf(repository, r.id) }); - const measured = measure(run.name, recorded, budgets); + const open = labelled(repository, "ci-budget", "open"); + const recordTitle = `CI budget record: ${run.name}`; + const record = keeperOf(open, recordTitle); + const ledger: Ledger = fold(readLedger(record?.body), run, jobs); + const measured = measureLedger(run.name, ledger, budgets); + const body = recordBody(ledger, measured, budgets[run.name]); + if (dryRun) say(`would update the record: ${recordTitle}`); + else if (record) + gh([ + `repos/${repository}/issues/${record.number}`, + "--method", + "PATCH", + "-f", + `body=${body}`, + ]); + else + gh([ + `repos/${repository}/issues`, + "--method", + "POST", + "-f", + `title=${recordTitle}`, + "-f", + `body=${body}`, + "-f", + "labels[]=ci-budget", + ]); + const recordLink = record + ? ` Every job's recent times: #${record.number}.` + : ""; + const over = overBudget(measured); - const issues = labelled(repository, "ci-budget"); const prefix = `CI over budget: ${run.name} / `; for (const m of over) { - const filed = budgetIssue( - repository, - issues, - `${prefix}${m.job}`, - `${BUDGET_BODY}\n\n${measuredText(m)}`, - `Over budget: median ${m.median.toFixed(1)} minutes over its last ${m.samples.length} runs, against ${m.budget}. Latest: ${where}.`, - dryRun, - ); + const title = `${prefix}${m.job}`; + // Over and already open: nothing to say on every run; the record keeps its times current. + const already = keeperOf(open, title); + const filed = already + ? `still over, #${already.number}: ${title}` + : upsertIssue( + repository, + "ci-budget", + title, + `${BUDGET_BODY}${recordLink}\n\n${measuredText(m, repository)}`, + `Over budget: median ${m.median.toFixed(1)} minutes over its last ${m.samples.length} runs, against ${m.budget}. Latest: ${where}.`, + dryRun, + ); say( `${filed} (median ${m.median.toFixed(1)} minutes over ${m.samples.length} runs, budget ${m.budget})`, ); failed = true; } - // Every other open issue of this workflow's: its job is back under budget, or does not run - // where times are held to budget any more. + // Every other open issue of this workflow's: its job is back under budget, or, once the + // record has seen enough runs, never runs where times are held (a pull request's own job). const overTitles = new Set(over.map((m) => `${prefix}${m.job}`)); const measuredUnder = new Map( measured .filter((m) => !overTitles.has(`${prefix}${m.job}`)) .map((m) => [`${prefix}${m.job}`, m]), ); - for (const issue of issues) { - if ( - issue.state !== "open" || - !issue.title.startsWith(prefix) || - overTitles.has(issue.title) - ) - continue; + const stale = open.filter((issue) => { + if (!issue.title.startsWith(prefix) || overTitles.has(issue.title)) + return false; + if (measuredUnder.has(issue.title)) return true; + return ( + warm(ledger) && !(issue.title.slice(prefix.length) in ledger.jobs) + ); + }); + for (const issue of stale.slice(0, CLOSES_PER_RUN)) { const under = measuredUnder.get(issue.title); say( closeIssue( @@ -525,7 +577,7 @@ if (import.meta.main) { issue, under ? `Back under budget: median ${under.median.toFixed(1)} minutes over its last ${under.samples.length} runs, against ${under.budget}. Latest: ${where}.` - : `Not over budget on main or in the merge queue: budgets are held to the median of a job's last ${WINDOW} runs there, not to one run. Latest: ${where}.`, + : `Not over budget on main or in the merge queue: this job does not run there, and budgets are held to the median of a job's last ${WINDOW} runs there, not to one run. Latest: ${where}.`, dryRun, ), ); @@ -579,3 +631,15 @@ if (import.meta.main) { process.exit(1); } } + +if (import.meta.main) { + try { + await main(); + } catch (error) { + if (!(error instanceof ApiError)) throw error; + console.log( + `::warning title=CI watch stopped::GitHub's API did not answer, so this run checked nothing more: ${quiet(error.message, 300)}`, + ); + process.exit(0); + } +}