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
177 changes: 125 additions & 52 deletions scripts/ci-budget.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, Sample[]> };

const LEDGER = /<!-- ci-budget-ledger\n([\s\S]*?)\n-->/;

/** 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 `<!-- ci-budget-ledger\n${JSON.stringify(ledger)}\n-->`;
}

/**
* 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<string, Sample> {
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<string, number>();
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<string, Sample>();
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 = {
/**
Expand All @@ -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<string, Sample[]>();
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<string, number>();
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);
Expand All @@ -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<Ledger>((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);
Expand Down
Loading
Loading