diff --git a/.claude/skills/slowest-tests/SKILL.md b/.claude/skills/slowest-tests/SKILL.md index 5ba26c6837ed..97ef1c401030 100644 --- a/.claude/skills/slowest-tests/SKILL.md +++ b/.claude/skills/slowest-tests/SKILL.md @@ -9,7 +9,7 @@ Args: `[N] [#channel]` — both optional. `N` defaults to 500. If `#channel` is ## 1. Gather the data -Run the script. With no build number it auto-picks the most recent finished build from a merged PR. +Run the script. With no build number it walks the 10 newest PRs merged into `main` and takes the first build that is finished, not canceled, and has every `test-bun` job started. That build often reports `state=failed` because of flaky tests. That is fine, the timing data is still valid. ```bash bun run ci:slowest # top 500 from a recent merged-PR build → TSV on stdout @@ -19,14 +19,20 @@ bun run ci:slowest --json > /tmp/slow.json The script (`scripts/ci-slowest-tests.ts`) does the heavy lifting: -- Lists `test-bun` jobs from `bk build view `, skipping `retried: true`. +- Lists the `test-bun` jobs of the build, skipping `retried: true` and jobs that never started (no `started_at`: their log is empty). - Fetches each job's `raw_log_url` directly with `Authorization: Bearer $BUILDKITE_TOKEN`. **Do not use `bk job log` — it hangs indefinitely on some Windows/alpine jobs.** - Caches logs to `$TMPDIR/bun-ci-logs-/` so re-runs are instant. - Parses `_bk;t= ... --- [N/TOTAL] ` group headers, normalising backslashes to `/` and stripping `[attempt #N]` retries. - Aggregates each file's duration as the **max across all platforms** (a file appears once per platform; shards within a platform are disjoint). - Drops `package.json` / non-JS entries — those are setup steps, not tests. -If the script can't find a build automatically (rare — it walks the last 10 merged PRs), pick one yourself: `gh pr list --state merged --limit 10 --json number,headRefName`, then `bk build list --branch ` and pass the first build with a `finished_at`. Merged-PR builds usually report `state: failed` because of flaky tests — that's fine, the timing data is still valid. +If the script finds no build, it exits 1 with nothing on stdout. Do not walk the PRs by hand: the script already did that, and its stderr says what to do next. + +1. `failed to list the builds of ...` lines: `bk build list` failed for those PRs, and each line carries the error. Run the same command again. +2. A `note:` that names a build: no recent build ran every `test-bun` job, and that build has the most timings. Pass its number. +3. Neither: no recent merged-PR build has test timings. Stop and report the stderr. + +With a build number, a `warning:` line on stderr names the platforms whose jobs never started. The table has no timings from them, so repeat that warning wherever you post the table. A build with no test timings at all gives `error: build #N has no test timings` and exit 1. ## 2. Post to Slack (only if a channel was given) diff --git a/scripts/ci-slowest-tests.ts b/scripts/ci-slowest-tests.ts index 188b70cdad80..12c5a52da910 100644 --- a/scripts/ci-slowest-tests.ts +++ b/scripts/ci-slowest-tests.ts @@ -1,10 +1,11 @@ #!/usr/bin/env bun // Find the slowest test files in a CI build. // -// Downloads every test-bun job log from a BuildKite build, parses per-file -// wall-clock from the `_bk;t=` timestamps that prefix each +// Downloads the log of every test-bun job that started in a BuildKite build, +// parses per-file wall-clock from the `_bk;t=` timestamps that prefix each // `[N/TOTAL] ` header, aggregates as MAX across all platforms, and -// prints the top N. +// prints the top N. Exits 1 with nothing on stdout when the build has no test +// timings. // // Usage: // bun scripts/ci-slowest-tests.ts # auto-pick a recent merged-PR build, top 500 @@ -20,6 +21,66 @@ import { tmpdir } from "os"; import { join } from "path"; import { isPhaseGroupHeader } from "./ci-log-phase.mjs"; +// As `bk build view` and `bk build list` print them. `bk` leaves `started_at` +// out for a job that never started. +type BkJob = { id: string; name?: string; raw_log_url?: string; retried?: boolean; started_at?: string | null }; +type BkBuild = { number: number; state: string; finished_at?: string | null; jobs?: BkJob[] }; +type TestJob = BkJob & { name: string; raw_log_url: string }; + +// A job that never started (its platform's build failed, no agent took it) +// still has a raw_log_url, which answers 200 with an empty body. The test is +// `started_at`, not `finished_at` or `state`: a job killed mid-run keeps its +// partial log, and parseLog reads it on purpose. +export function jobCoverage(jobs: BkJob[]) { + const timed: TestJob[] = []; + // One entry per distinct job name, for example `:debian: 13 x64 - test-bun`. + const platforms = new Map(); + let total = 0; + for (const job of jobs) { + if (!job.name || !job.name.includes("test-bun") || job.retried) continue; + total++; + let platform = platforms.get(job.name); + if (!platform) platforms.set(job.name, (platform = { name: job.name, started: 0, total: 0 })); + platform.total++; + // A job with no log to ask for has no timings either. + if (!job.started_at || !job.raw_log_url) continue; + platform.started++; + timed.push(job as TestJob); + } + // `total > 0`: a build with no test-bun job (`[skip tests]`) is not complete. + return { timed, total, platforms: [...platforms.values()], complete: total > 0 && timed.length === total }; +} +export type JobCoverage = ReturnType; + +// The auto-pick. A build with a job that never started is passed over: the +// report is the MAX across platforms, so the hole would not show. `bk build +// list` returns each build with its jobs, so judging a build costs no request. +export async function findBuild( + prs: PR[], + listBuilds: (branch: string) => Promise, +) { + const skipped: { pr: PR; build: BkBuild; coverage: JobCoverage }[] = []; + const failedLists: { pr: PR; error: unknown }[] = []; + for (const pr of prs) { + let builds: BkBuild[]; + try { + builds = await listBuilds(pr.headRefName); + } catch (error) { + // A list that fails does not end the walk. The caller reports it. + failedLists.push({ pr, error }); + continue; + } + for (const build of builds) { + // `failed` is fine: flaky tests fail most merged-PR builds, and the timings are still valid. + if (!build.finished_at || build.state === "canceled" || build.state === "running") continue; + const coverage = jobCoverage(build.jobs ?? []); + if (coverage.complete) return { picked: { pr, build, coverage }, skipped, failedLists }; + skipped.push({ pr, build, coverage }); + } + } + return { picked: undefined, skipped, failedLists }; +} + // Per-file cost is the gap between the APC timestamps Buildkite injects into // consecutive `[N/M] ` headers (ESC `_bk;t=` BEL). See // scripts/ci-log-phase.mjs for the header shapes runner.node.ts emits and why @@ -91,28 +152,50 @@ if (import.meta.main) { process.exit(1); } - // Auto-pick a build: most-recent merged PR whose branch has a finished build. - // Merged-PR builds usually report state=failed (flaky tests) — that's fine, - // we only need the timing data. + // The auto-pick sets this from the jobs of `bk build list`. Only a build number needs `bk build view`. + let coverage: JobCoverage | undefined; if (!BUILD) { console.error("no build given, finding a recent merged-PR build..."); - const prs = await $`gh pr list --state merged --limit 10 --json number,headRefName`.json(); - for (const pr of prs) { - const builds = await $`bk build list --branch ${pr.headRefName}` - .quiet() - .json() - .catch(() => []); - const done = builds.find((b: any) => b.finished_at && b.state !== "canceled" && b.state !== "running"); - if (done) { - BUILD = String(done.number); - console.error(` using build #${BUILD} (PR #${pr.number}, ${pr.headRefName}, state=${done.state})`); - break; - } + // `--base main`: a PR that merged into the branch of another PR is merged too, and its tree is not main's. + // `--repo`: `bk` reads the bun pipeline from .bk.yaml, so `gh` must not read the PRs of a fork. + const prs: { number: number; headRefName: string }[] = + await $`gh pr list --repo oven-sh/bun --state merged --base main --limit 10 --json number,headRefName`.json(); + const { picked, skipped, failedLists } = await findBuild(prs, branch => + $`bk build list --branch ${branch}`.quiet().json(), + ); + for (const { pr, build, coverage: ran } of skipped) { + console.error( + ` skipped build #${build.number} (PR #${pr.number}, ${pr.headRefName}, state=${build.state}): ` + + `${ran.timed.length} of ${ran.total} test-bun jobs started`, + ); } - if (!BUILD) { - console.error("error: no finished build found among the last 10 merged PRs"); + for (const { pr, error } of failedLists) { + // `$` rejects with the stderr of `bk`, or with a SyntaxError when the output is not JSON. + const why = (error as any)?.stderr?.toString().trim() || (error as any)?.message || String(error); + console.error(` failed to list the builds of ${pr.headRefName} (PR #${pr.number}): ${why}`); + } + if (!picked) { + console.error( + failedLists.length && failedLists.length === prs.length + ? `error: \`bk build list\` failed for each of the last ${prs.length} PRs merged into main, so no build was examined` + : `error: no finished build in which every test-bun job started among the last ${prs.length} PRs merged into main`, + ); + // The skipped build with the most timings, the first one listed on a tie. + let best: (typeof skipped)[number] | undefined; + for (const s of skipped) if (s.coverage.timed.length > (best?.coverage.timed.length ?? 0)) best = s; + if (best) { + console.error( + `note: build #${best.build.number} has timings from ${best.coverage.timed.length} of ` + + `${best.coverage.total} test-bun jobs. Pass its number to report on it.`, + ); + } process.exit(1); } + BUILD = String(picked.build.number); + coverage = picked.coverage; + console.error( + ` using build #${BUILD} (PR #${picked.pr.number}, ${picked.pr.headRefName}, state=${picked.build.state})`, + ); } const CACHE = join(tmpdir(), `bun-ci-logs-${BUILD}`); @@ -120,15 +203,25 @@ if (import.meta.main) { type Job = { id: string; name: string; raw_log_url: string; retried?: boolean }; - const buildJson = JSON.parse( - await new Response(spawn({ cmd: ["bk", "build", "view", BUILD], stdout: "pipe" }).stdout).text(), - ); - const jobs: Job[] = buildJson.jobs.filter( - (j: any) => j.name && j.raw_log_url && j.name.includes("test-bun") && !j.retried, - ); + if (!coverage) { + const buildJson = JSON.parse( + await new Response(spawn({ cmd: ["bk", "build", "view", BUILD], stdout: "pipe" }).stdout).text(), + ); + coverage = jobCoverage(buildJson.jobs ?? []); + } + const jobs: Job[] = coverage.timed; console.error( - `build #${BUILD}: ${jobs.length} test-bun jobs across ${new Set(jobs.map(j => j.name)).size} platforms`, + `build #${BUILD}: ${jobs.length} of ${coverage.total} test-bun jobs started, ` + + `on ${coverage.platforms.filter(p => p.started).length} of ${coverage.platforms.length} platforms`, ); + if (jobs.length === 0) { + console.error( + `error: build #${BUILD} has no test timings: ` + + (coverage.total ? `none of its ${coverage.total} test-bun jobs started` : "it has no test-bun jobs") + + "\nnote: pass another build number, or none to pick a recent merged-PR build", + ); + process.exit(1); + } const platOf = (name: string) => name @@ -182,15 +275,33 @@ if (import.meta.main) { // `package.json` / `test/package.json` are setup steps, not tests. const isTest = (f: string) => /\.(m|c)?(j|t)sx?$/.test(f); - const sorted = [...agg.entries()] + const testFiles = [...agg.entries()] .filter(([file]) => isTest(file)) .map(([file, a]) => ({ file, maxMs: a.maxMs, maxPlat: a.maxPlat })) - .sort((a, b) => b.maxMs - a.maxMs) - .slice(0, TOP_N); + .sort((a, b) => b.maxMs - a.maxMs); + const sorted = testFiles.slice(0, TOP_N); console.error(`${agg.size} unique entries, ${sorted.length} test files after filtering`); console.error(`logs cached at ${CACHE}`); + // Started jobs can still leave no timings: they ended before their first test, or no log came down. + if (testFiles.length === 0) { + console.error( + `error: build #${BUILD} has no test timings: ` + + `no test file in the logs of its ${jobs.length} started test-bun jobs\n` + + "note: a `failed ` line above is a log that could not be downloaded", + ); + process.exit(1); + } + const holes = coverage.platforms.filter(p => p.started < p.total); + if (holes.length) { + console.error( + `warning: build #${BUILD}: ${coverage.total - jobs.length} of ${coverage.total} test-bun jobs never started, ` + + `so the report lacks their timings: ` + + holes.map(p => `${platOf(p.name)} (${p.started} of ${p.total} started)`).join(", "), + ); + } + if (json) { console.log(JSON.stringify({ build: BUILD, count: agg.size, top: sorted }, null, 2)); } else { diff --git a/test/internal/ci-slowest-tests.test.ts b/test/internal/ci-slowest-tests.test.ts index b4315f1886ce..9c998e995044 100644 --- a/test/internal/ci-slowest-tests.test.ts +++ b/test/internal/ci-slowest-tests.test.ts @@ -1,8 +1,9 @@ import { describe, expect, test } from "bun:test"; -import { readFileSync } from "node:fs"; +import { bunEnv, bunExe, isASAN, isWindows, tempDir } from "harness"; +import { chmodSync, readFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { isPhaseGroupHeader } from "../../scripts/ci-log-phase.mjs"; -import { parseLog } from "../../scripts/ci-slowest-tests"; +import { findBuild, jobCoverage, parseLog } from "../../scripts/ci-slowest-tests"; import { entryOfProgram, parseLog as parseDurations } from "../../scripts/update-test-durations.mjs"; // Buildkite prefixes each line with an APC timestamp: ESC `_bk;t=` BEL. @@ -146,6 +147,616 @@ describe("scripts/ci-slowest-tests.ts parseLog", () => { }); }); +// Jobs as `bk build view` and `bk build list` print them. `bk` leaves +// `started_at` out for a job that never started. +const DEBIAN = ":debian: 13 x64 - test-bun"; +const DARWIN = ":darwin: any x64 - test-bun"; +const WINDOWS = ":windows: 2019 x64 - test-bun"; +const bkJob = (id: string, name: string, state: string, fields: object = {}) => ({ + id, + name, + state, + raw_log_url: `https://api.buildkite.com/v2/organizations/bun/pipelines/bun/builds/1/jobs/${id}/log.txt`, + retried: false, + ...fields, +}); +const started = (id: string, name: string, state = "passed") => + bkJob(id, name, state, { started_at: "2026-10-17T02:20:00.000Z", finished_at: "2026-10-17T02:45:00.000Z" }); +const neverStarted = (id: string, name: string, state = "waiting_failed") => bkJob(id, name, state); +// No agent took the job: it has a `finished_at` and still no `started_at`. +const expired = (id: string, name: string) => bkJob(id, name, "expired", { finished_at: "2026-10-17T05:05:25.587Z" }); + +describe("scripts/ci-slowest-tests.ts jobCoverage", () => { + test("a test-bun job has timings only if an agent started it", () => { + const ranToTheEnd = started("a", DEBIAN); + // parseLog reads the partial log of a job that was killed while it ran. + const killedMidRun = started("b", DEBIAN, "canceled"); + const buildJob = started("h", ":linux: x64 - build-bun"); + const retried = { ...started("i", DEBIAN), retried: true }; + const blockStep = { id: "j", type: "manual", state: "broken" }; + const noLogUrl = { id: "k", name: DEBIAN, started_at: "2026-10-17T02:20:00.000Z" }; + const { name, ...unlabeledStep } = started("l", DEBIAN); + + expect( + jobCoverage([ + ranToTheEnd, + killedMidRun, + // Never started. In build 127137 the build-bun jobs were canceled, so + // every test-bun job ended as `waiting_failed`. + neverStarted("c", WINDOWS, "waiting_failed"), + neverStarted("d", WINDOWS, "canceled"), + // In build 127153 no agent took one of the two darwin x64 shards. + expired("e", DARWIN), + neverStarted("f", DARWIN, "scheduled"), + bkJob("g", DARWIN, "waiting", { started_at: null }), + // Started, but there is no log to ask for. + noLogUrl, + // Not a test-bun job of the build. + buildJob, + retried, + blockStep, + unlabeledStep, + ]), + ).toEqual({ + timed: [ranToTheEnd, killedMidRun], + total: 8, + platforms: [ + { name: DEBIAN, started: 2, total: 3 }, + { name: WINDOWS, started: 0, total: 2 }, + { name: DARWIN, started: 0, total: 3 }, + ], + complete: false, + }); + }); + + test("a build is complete when it has test-bun jobs and every one of them started", () => { + expect(jobCoverage([started("a", DEBIAN), started("b", WINDOWS, "failed")]).complete).toBe(true); + expect(jobCoverage([started("a", DEBIAN), expired("b", DARWIN)]).complete).toBe(false); + // A test-bun job with no log URL leaves a hole, started or not. + expect(jobCoverage([started("a", DEBIAN), { id: "b", name: DEBIAN }]).complete).toBe(false); + // `[skip tests]` in the commit subject: the build has no test-bun job. + expect(jobCoverage([started("a", ":linux: x64 - build-bun")])).toEqual({ + timed: [], + total: 0, + platforms: [], + complete: false, + }); + }); +}); + +type MergedPR = { number: number; headRefName: string }; +type Build = { number: number; state: string; finished_at?: string; jobs: ReturnType[] }; +const finishedBuild = (number: number, state: string, jobs: Build["jobs"]): Build => ({ + number, + state, + finished_at: "2026-10-17T07:53:30.239Z", + jobs, +}); +// Three test-bun jobs on two platforms stand in for the 160 on 11 of a real build. +const everyJobStarted = (build: number) => [ + started(`${build}-a`, DEBIAN), + started(`${build}-b`, DEBIAN, "failed"), + started(`${build}-c`, WINDOWS), +]; +const noJobStarted = (build: number) => [ + neverStarted(`${build}-a`, DEBIAN), + neverStarted(`${build}-b`, DEBIAN), + neverStarted(`${build}-c`, WINDOWS), +]; +const oneShardNeverStarted = (build: number) => [ + started(`${build}-a`, DEBIAN), + started(`${build}-b`, DARWIN), + expired(`${build}-c`, DARWIN), +]; + +describe("scripts/ci-slowest-tests.ts findBuild", () => { + // Stands in for `bk build list --branch ` and records the branches asked for. + function lister(byBranch: Record) { + const calls: string[] = []; + const list = async (branch: string) => { + calls.push(branch); + const builds = byBranch[branch]; + if (builds instanceof Error) throw builds; + return builds; + }; + return { calls, list }; + } + + // What findBuild decided, in PR and build numbers. + const decided = ({ picked, skipped, failedLists }: Awaited>>) => ({ + picked: picked && { + pr: picked.pr.number, + build: picked.build.number, + download: picked.coverage.timed.map(job => job.id), + }, + skipped: skipped.map( + ({ pr, build, coverage }) => + `PR ${pr.number} build ${build.number}: ${coverage.timed.length} of ${coverage.total} started`, + ), + failedLists: failedLists.map(({ pr, error }) => `PR ${pr.number}: ${error}`), + }); + + test("passes over a build in which no test-bun job started and takes the next merged PR's build", async () => { + // 2026-10-17: PR #45639 was merged while its last build, 127153, still + // ran. Its only finished build, 127137, failed after 22 s: every build-bun + // job was canceled and none of the 160 test-bun jobs started. + const prs = [ + { number: 45639, headRefName: "hot-loop-no-inline" }, + { number: 45600, headRefName: "merged-earlier" }, + { number: 45599, headRefName: "never-listed" }, + ]; + const { calls, list } = lister({ + "hot-loop-no-inline": [ + { number: 127153, state: "running", jobs: everyJobStarted(127153) }, + finishedBuild(127137, "failed", noJobStarted(127137)), + ], + "merged-earlier": [finishedBuild(126925, "passed", everyJobStarted(126925))], + }); + + expect(decided(await findBuild(prs, list))).toEqual({ + picked: { pr: 45600, build: 126925, download: ["126925-a", "126925-b", "126925-c"] }, + skipped: ["PR 45639 build 127137: 0 of 3 started"], + failedLists: [], + }); + // One `bk build list` for each PR up to the pick, and none after it. + expect(calls).toEqual(["hot-loop-no-inline", "merged-earlier"]); + }); + + test("goes on to an older build of the same branch, past builds that did not finish or were canceled", async () => { + const prs = [ + { number: 1, headRefName: "a" }, + { number: 2, headRefName: "b" }, + ]; + const { calls, list } = lister({ + a: [ + { number: 106, state: "failing", jobs: everyJobStarted(106) }, + // The state decides, with or without a `finished_at`. + finishedBuild(105, "running", everyJobStarted(105)), + finishedBuild(104, "canceled", everyJobStarted(104)), + finishedBuild(103, "failed", noJobStarted(103)), + // Flaky tests failed the build. Its timings are as good as any. + finishedBuild(102, "failed", everyJobStarted(102)), + finishedBuild(101, "passed", everyJobStarted(101)), + ], + b: [finishedBuild(201, "passed", everyJobStarted(201))], + }); + + expect(decided(await findBuild(prs, list))).toEqual({ + picked: { pr: 1, build: 102, download: ["102-a", "102-b", "102-c"] }, + skipped: ["PR 1 build 103: 0 of 3 started"], + failedLists: [], + }); + expect(calls).toEqual(["a"]); + }); + + test("passes over a build with a job that never started, and picks nothing when no build is complete", async () => { + const prs = [ + { number: 1, headRefName: "a" }, + { number: 2, headRefName: "b" }, + ]; + const { calls, list } = lister({ + a: [finishedBuild(101, "failed", oneShardNeverStarted(101))], + b: [ + // The Windows build failed, so that platform has no timings at all. + finishedBuild(202, "failed", [ + started("202-a", DEBIAN), + neverStarted("202-b", WINDOWS), + neverStarted("202-c", WINDOWS), + ]), + // `[skip tests]`: no test-bun job. + finishedBuild(201, "passed", [started("201-a", ":linux: x64 - build-bun")]), + ], + }); + + expect(decided(await findBuild(prs, list))).toEqual({ + picked: undefined, + skipped: ["PR 1 build 101: 2 of 3 started", "PR 2 build 202: 1 of 3 started", "PR 2 build 201: 0 of 0 started"], + failedLists: [], + }); + expect(calls).toEqual(["a", "b"]); + }); + + test("a `bk build list` that fails skips that PR, and its error is kept", async () => { + const prs = [ + { number: 1, headRefName: "a" }, + { number: 2, headRefName: "b" }, + ]; + const { calls, list } = lister({ + a: new Error("429 Too Many Requests"), + b: [finishedBuild(201, "passed", everyJobStarted(201))], + }); + + expect(decided(await findBuild(prs, list))).toEqual({ + picked: { pr: 2, build: 201, download: ["201-a", "201-b", "201-c"] }, + skipped: [], + failedLists: ["PR 1: Error: 429 Too Many Requests"], + }); + expect(calls).toEqual(["a", "b"]); + }); +}); + +// The script asks `gh` for the merged PRs and `bk` for the builds. Here both +// are shell scripts on PATH that record their arguments and print canned +// JSON, and a local server stands in for the Buildkite log URLs. Shell scripts +// do not resolve as executables on Windows, hence the skip. +describe.skipIf(isWindows)("scripts/ci-slowest-tests.ts with a canned `gh` and `bk`", () => { + const script = join(import.meta.dir, "..", "..", "scripts", "ci-slowest-tests.ts"); + const fakeGh = [ + "#!/bin/sh", + 'echo "gh $*" >> "$FAKE/calls"', + 'case " $* " in', + ' *" --base main "*) cat "$FAKE/merged-into-main.json" ;;', + ' *) cat "$FAKE/merged.json" ;;', + "esac", + "", + ].join("\n"); + const fakeBk = [ + "#!/bin/sh", + 'echo "bk $*" >> "$FAKE/calls"', + 'case "$1 $2" in', + ' "build list") canned="$FAKE/list-$4.json" ;;', + ' "build view") canned="$FAKE/view-$3.json" ;;', + "esac", + 'if [ ! -f "$canned" ]; then', + ' echo "Error: 429 Too Many Requests" >&2', + " exit 1", + "fi", + 'cat "$canned"', + "", + ].join("\n"); + + interface Canned { + /** `gh pr list --state merged`. A PR with no `baseRefName` merged into main. */ + merged?: (MergedPR & { baseRefName?: string })[]; + /** `bk build list --branch `. For a branch that is not here, `bk` fails. */ + lists?: Record; + /** `bk build view ` */ + views?: Build[]; + /** What the log URL of each job id answers. A job that is not here has an empty log. */ + logs?: Record Response)>; + } + + async function runSlowest(args: string[], { merged = [], lists = {}, views = [], logs = {} }: Canned) { + const requested: string[] = []; + await using server = Bun.serve({ + port: 0, + fetch(req) { + const id = new URL(req.url).pathname.slice(1); + requested.push(id); + const log = logs[id] ?? ""; + return typeof log === "string" ? new Response(log) : log(); + }, + }); + const served = (build: Build) => ({ + ...build, + jobs: build.jobs.map(job => ({ ...job, raw_log_url: `${server.url}${job.id}` })), + }); + using dir = tempDir("ci-slowest", { + "bin/gh": fakeGh, + "bin/bk": fakeBk, + "calls": "", + "merged.json": JSON.stringify(merged), + "merged-into-main.json": JSON.stringify(merged.filter(pr => (pr.baseRefName ?? "main") === "main")), + ...Object.fromEntries( + Object.entries(lists).map(([branch, builds]) => [`list-${branch}.json`, JSON.stringify(builds.map(served))]), + ), + ...Object.fromEntries(views.map(build => [`view-${build.number}.json`, JSON.stringify(served(build))])), + }); + const bin = join(String(dir), "bin"); + chmodSync(join(bin, "gh"), 0o755); + chmodSync(join(bin, "bk"), 0o755); + + await using proc = Bun.spawn({ + cmd: [bunExe(), script, ...args], + env: { + ...bunEnv, + PATH: `${bin}:${bunEnv.PATH}`, + FAKE: String(dir), + // The script caches logs in $TMPDIR/bun-ci-logs-. + TMPDIR: join(String(dir), "tmp"), + BUILDKITE_TOKEN: "token", + }, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + return { + stdout, + stderr: stderr + .replaceAll(String(dir), "") + .replaceAll(server.url.href, "/") + .split("\n") + // The `N/M logs` progress lines. + .filter(line => !/^ \d+\/\d+ logs/.test(line)), + exitCode, + calls: readFileSync(join(String(dir), "calls"), "utf8") + .split("\n") + .filter(Boolean), + requested: requested.sort(), + }; + } + + const log = (...lines: [ms: number, header: string][]) => + [...lines.map(([ms, header]) => bk(ms, `--- ${header}`)), ""].join("\r\r\n"); + + // An ASAN build starts too slowly to run all of these at the same time within the default timeout. + const scenario = test.concurrentIf(!isASAN); + + scenario("a build number whose test-bun jobs never started: exit 1 and no log request", async () => { + const result = await runSlowest(["127137", "--json"], { + views: [finishedBuild(127137, "failed", noJobStarted(127137))], + }); + expect(result).toEqual({ + stdout: "", + stderr: [ + "build #127137: 0 of 3 test-bun jobs started, on 0 of 2 platforms", + "error: build #127137 has no test timings: none of its 3 test-bun jobs started", + "note: pass another build number, or none to pick a recent merged-PR build", + "", + ], + exitCode: 1, + calls: ["bk build view 127137"], + requested: [], + }); + }); + + scenario("a build number whose jobs started and ran no test: exit 1 and no table", async () => { + const result = await runSlowest(["7"], { + views: [finishedBuild(7, "failed", [started("7-a", DEBIAN, "failed")])], + // The shard ended in its setup step. + logs: { "7-a": log([0, "[1/50] test/package.json"], [900, "End"]) }, + }); + expect(result).toEqual({ + stdout: "", + stderr: [ + "build #7: 1 of 1 test-bun jobs started, on 1 of 1 platforms", + "1 unique entries, 0 test files after filtering", + "logs cached at /tmp/bun-ci-logs-7", + "error: build #7 has no test timings: no test file in the logs of its 1 started test-bun jobs", + "note: a `failed ` line above is a log that could not be downloaded", + "", + ], + exitCode: 1, + calls: ["bk build view 7"], + requested: ["7-a"], + }); + }); + + scenario("no build number: takes the first complete build of a PR that merged into main", async () => { + const untested = finishedBuild(127137, "failed", noJobStarted(127137)); + const complete = finishedBuild(126925, "passed", everyJobStarted(126925)); + const result = await runSlowest(["--json"], { + merged: [ + // 2026-11-07: merged into the branch of another PR, so build 138376 is not a build of main's tree. + { number: 48112, headRefName: "one-walk-fixes-2", baseRefName: "one-walk-fixes" }, + { number: 45639, headRefName: "hot-loop-no-inline" }, + { number: 45620, headRefName: "list-fails" }, + { number: 45600, headRefName: "merged-earlier" }, + { number: 45599, headRefName: "never-listed" }, + ], + lists: { + "one-walk-fixes-2": [finishedBuild(138376, "passed", everyJobStarted(138376))], + "hot-loop-no-inline": [ + { number: 127153, state: "running", jobs: everyJobStarted(127153) }, + untested, + finishedBuild(127100, "failed", oneShardNeverStarted(127100)), + ], + "merged-earlier": [complete], + }, + // `bk build view` can answer for both builds. The script must not need it. + views: [untested, complete], + logs: { + "138376-a": log([0, "[1/1] test/not-on-main.test.ts"], [9000, "End"]), + "126925-a": log([0, "[1/3] test/a.test.ts"], [3000, "[2/3] test/b.test.ts"], [4000, "End"]), + "126925-b": log([0, "[3/3] test/c.test.ts"], [2000, "End"]), + "126925-c": log([0, "[1/1] test/a.test.ts"], [5000, "End"]), + }, + }); + const { build, count, top } = JSON.parse(result.stdout); + expect({ ...result, stdout: { build, count, top } }).toEqual({ + stdout: { + build: "126925", + count: 3, + top: [ + { file: "test/a.test.ts", maxMs: 5000, maxPlat: "windows 2019 x64" }, + { file: "test/c.test.ts", maxMs: 2000, maxPlat: "debian 13 x64" }, + { file: "test/b.test.ts", maxMs: 1000, maxPlat: "debian 13 x64" }, + ], + }, + stderr: [ + "no build given, finding a recent merged-PR build...", + " skipped build #127137 (PR #45639, hot-loop-no-inline, state=failed): 0 of 3 test-bun jobs started", + " skipped build #127100 (PR #45639, hot-loop-no-inline, state=failed): 2 of 3 test-bun jobs started", + " failed to list the builds of list-fails (PR #45620): Error: 429 Too Many Requests", + " using build #126925 (PR #45600, merged-earlier, state=passed)", + "build #126925: 3 of 3 test-bun jobs started, on 2 of 2 platforms", + "3 unique entries, 3 test files after filtering", + "logs cached at /tmp/bun-ci-logs-126925", + "", + ], + exitCode: 0, + // The jobs come with the build list, so there is no `bk build view`. + calls: [ + "gh pr list --repo oven-sh/bun --state merged --base main --limit 10 --json number,headRefName", + "bk build list --branch hot-loop-no-inline", + "bk build list --branch list-fails", + "bk build list --branch merged-earlier", + ], + requested: ["126925-a", "126925-b", "126925-c"], + }); + }); + + scenario( + "no build number and no complete build: exit 1, and the note names the build with the most timings", + async () => { + const result = await runSlowest(["--json"], { + merged: [ + { number: 3, headRefName: "untested" }, + { number: 2, headRefName: "list-fails" }, + { number: 1, headRefName: "partial" }, + ], + lists: { + untested: [finishedBuild(301, "failed", noJobStarted(301))], + partial: [ + finishedBuild(103, "failed", [ + started("103-a", DEBIAN), + neverStarted("103-b", WINDOWS), + neverStarted("103-c", WINDOWS), + ]), + finishedBuild(102, "failed", oneShardNeverStarted(102)), + finishedBuild(101, "failed", oneShardNeverStarted(101)), + ], + }, + }); + expect(result).toEqual({ + stdout: "", + stderr: [ + "no build given, finding a recent merged-PR build...", + " skipped build #301 (PR #3, untested, state=failed): 0 of 3 test-bun jobs started", + " skipped build #103 (PR #1, partial, state=failed): 1 of 3 test-bun jobs started", + " skipped build #102 (PR #1, partial, state=failed): 2 of 3 test-bun jobs started", + " skipped build #101 (PR #1, partial, state=failed): 2 of 3 test-bun jobs started", + " failed to list the builds of list-fails (PR #2): Error: 429 Too Many Requests", + "error: no finished build in which every test-bun job started among the last 3 PRs merged into main", + "note: build #102 has timings from 2 of 3 test-bun jobs. Pass its number to report on it.", + "", + ], + exitCode: 1, + calls: [ + "gh pr list --repo oven-sh/bun --state merged --base main --limit 10 --json number,headRefName", + "bk build list --branch untested", + "bk build list --branch list-fails", + "bk build list --branch partial", + ], + requested: [], + }); + }, + ); + + scenario("no build number and every `bk build list` fails: exit 1 with the reason of each", async () => { + const result = await runSlowest([], { + merged: [ + { number: 2, headRefName: "a" }, + { number: 1, headRefName: "b" }, + ], + }); + expect(result).toEqual({ + stdout: "", + stderr: [ + "no build given, finding a recent merged-PR build...", + " failed to list the builds of a (PR #2): Error: 429 Too Many Requests", + " failed to list the builds of b (PR #1): Error: 429 Too Many Requests", + "error: `bk build list` failed for each of the last 2 PRs merged into main, so no build was examined", + "", + ], + exitCode: 1, + calls: [ + "gh pr list --repo oven-sh/bun --state merged --base main --limit 10 --json number,headRefName", + "bk build list --branch a", + "bk build list --branch b", + ], + requested: [], + }); + }); + + scenario( + "no build number and no log of the picked build can be downloaded: exit 1, and no other build is tried", + async () => { + const result = await runSlowest(["--json"], { + merged: [ + { number: 2, headRefName: "picked" }, + { number: 1, headRefName: "never-listed" }, + ], + lists: { + picked: [finishedBuild(201, "passed", [started("201-a", DEBIAN)])], + "never-listed": [finishedBuild(101, "passed", everyJobStarted(101))], + }, + logs: { "201-a": () => new Response("", { status: 404 }) }, + }); + expect(result).toEqual({ + stdout: "", + stderr: [ + "no build given, finding a recent merged-PR build...", + " using build #201 (PR #2, picked, state=passed)", + "build #201: 1 of 1 test-bun jobs started, on 1 of 1 platforms", + " failed 201-a: 404 /201-a", + "0 unique entries, 0 test files after filtering", + "logs cached at /tmp/bun-ci-logs-201", + "error: build #201 has no test timings: no test file in the logs of its 1 started test-bun jobs", + "note: a `failed ` line above is a log that could not be downloaded", + "", + ], + exitCode: 1, + calls: [ + "gh pr list --repo oven-sh/bun --state merged --base main --limit 10 --json number,headRefName", + "bk build list --branch picked", + ], + requested: ["201-a"], + }); + }, + ); + + // Build 127153 in small: one of the two darwin shards expired, and here the + // Windows build also failed. + const partial: Canned = { + views: [ + finishedBuild(127153, "failed", [ + started("debian-1", DEBIAN), + started("darwin-1", DARWIN), + expired("darwin-2", DARWIN), + neverStarted("windows-1", WINDOWS), + neverStarted("windows-2", WINDOWS), + ]), + ], + logs: { + "debian-1": log([0, "[1/2] test/a.test.ts"], [3000, "[2/2] test/b.test.ts"], [4000, "End"]), + "darwin-1": log([0, "[1/1] test/a.test.ts"], [2000, "End"]), + }, + }; + const partialStderr = [ + "build #127153: 2 of 5 test-bun jobs started, on 2 of 3 platforms", + "2 unique entries, 2 test files after filtering", + "logs cached at /tmp/bun-ci-logs-127153", + "warning: build #127153: 3 of 5 test-bun jobs never started, so the report lacks their timings: " + + "darwin any x64 (1 of 2 started), windows 2019 x64 (0 of 2 started)", + "", + ]; + + scenario("a build number with jobs that never started: reports the rest and names the platforms", async () => { + expect(await runSlowest(["127153"], partial)).toEqual({ + stdout: [ + "rank\tseconds\tfile\tslowest_platform", + "1\t3.00\ttest/a.test.ts\tdebian 13 x64", + "2\t1.00\ttest/b.test.ts\tdebian 13 x64", + "", + ].join("\n"), + stderr: partialStderr, + exitCode: 0, + calls: ["bk build view 127153"], + requested: ["darwin-1", "debian-1"], + }); + }); + + scenario("the same with --json: the warning stays on stderr", async () => { + const result = await runSlowest(["127153", "--json"], partial); + const { build, count, top } = JSON.parse(result.stdout); + expect({ ...result, stdout: { build, count, top } }).toEqual({ + stdout: { + build: "127153", + count: 2, + top: [ + { file: "test/a.test.ts", maxMs: 3000, maxPlat: "debian 13 x64" }, + { file: "test/b.test.ts", maxMs: 1000, maxPlat: "debian 13 x64" }, + ], + }, + stderr: partialStderr, + exitCode: 0, + calls: ["bk build view 127153"], + requested: ["darwin-1", "debian-1"], + }); + }); +}); + describe("phase-header boundary", () => { // Both log parsers share this allowlist (scripts/ci-log-phase.mjs); if // runner.node.ts grows a new phase between the serial tests and the next