|
| 1 | +#!/usr/bin/env -S node --import tsx |
| 2 | +import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; |
| 3 | +import path from "node:path"; |
| 4 | +import { setTimeout } from "node:timers/promises"; |
| 5 | +import { fileURLToPath } from "node:url"; |
| 6 | +import { parseArgs } from "node:util"; |
| 7 | +import { z } from "zod"; |
| 8 | +import { isRetryableGhJsonErrorMessage } from "./ci-run-timings.mjs"; |
| 9 | +import { refitTestTimings, type CiTimingRun } from "./lib/ci-test-timings-refit.mts"; |
| 10 | +import { ciTestTimingsSchema } from "./lib/ci-test-timings-schema.mts"; |
| 11 | +import { parsePositiveInt } from "./lib/numeric-options.mjs"; |
| 12 | +import { execPlainGh } from "./lib/plain-gh.mjs"; |
| 13 | + |
| 14 | +const jobPageSchema = z.object({ |
| 15 | + total_count: z.number().int().nonnegative(), |
| 16 | + jobs: z.array( |
| 17 | + z.object({ |
| 18 | + id: z.number().int().positive(), |
| 19 | + name: z.string(), |
| 20 | + conclusion: z.string().nullable(), |
| 21 | + }), |
| 22 | + ), |
| 23 | +}); |
| 24 | + |
| 25 | +async function readGh(args: string[]): Promise<string> { |
| 26 | + const retryDelays = [1000, 3000, 6000]; |
| 27 | + for (let attempt = 0; ; attempt += 1) { |
| 28 | + try { |
| 29 | + return execPlainGh(args, { |
| 30 | + encoding: "utf8", |
| 31 | + timeout: 120_000, |
| 32 | + stdio: ["ignore", "pipe", "pipe"], |
| 33 | + }); |
| 34 | + } catch (error) { |
| 35 | + if ( |
| 36 | + attempt === retryDelays.length || |
| 37 | + !isRetryableGhJsonErrorMessage(error instanceof Error ? error.message : String(error)) |
| 38 | + ) { |
| 39 | + throw error; |
| 40 | + } |
| 41 | + await setTimeout(retryDelays[attempt]); |
| 42 | + } |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +async function main() { |
| 47 | + const { values } = parseArgs({ |
| 48 | + args: process.argv.slice(2).filter((arg) => arg !== "--"), |
| 49 | + options: { |
| 50 | + runs: { type: "string", default: "5" }, |
| 51 | + repo: { type: "string", default: "openclaw/openclaw" }, |
| 52 | + "dry-run": { type: "boolean", default: false }, |
| 53 | + out: { |
| 54 | + type: "string", |
| 55 | + default: fileURLToPath(new URL("../config/ci-test-timings.json", import.meta.url)), |
| 56 | + }, |
| 57 | + }, |
| 58 | + }); |
| 59 | + const count = parsePositiveInt(values.runs, "--runs"); |
| 60 | + const repo = z |
| 61 | + .string() |
| 62 | + .regex(/^[\w.-]+\/[\w.-]+$/u) |
| 63 | + .parse(values.repo); |
| 64 | + const runPageSchema = z.array( |
| 65 | + z.object({ |
| 66 | + id: z.number().int().positive(), |
| 67 | + created_at: z.iso.datetime(), |
| 68 | + status: z.literal("completed"), |
| 69 | + conclusion: z.literal("success"), |
| 70 | + }), |
| 71 | + ); |
| 72 | + const listed: z.infer<typeof runPageSchema> = []; |
| 73 | + const pageSize = Math.min(count, 100); |
| 74 | + for (let page = 1; listed.length < count; page += 1) { |
| 75 | + if (page > 25) { |
| 76 | + throw new Error("Run pagination limit exceeded; reduce --runs"); |
| 77 | + } |
| 78 | + const runs = runPageSchema.parse( |
| 79 | + JSON.parse( |
| 80 | + await readGh([ |
| 81 | + "api", |
| 82 | + `repos/${repo}/actions/workflows/ci.yml/runs?branch=main&status=success&per_page=${pageSize}&page=${page}`, |
| 83 | + "--jq", |
| 84 | + "[.workflow_runs[] | {id, created_at, status, conclusion}]", |
| 85 | + ]), |
| 86 | + ), |
| 87 | + ); |
| 88 | + listed.push(...runs); |
| 89 | + if (runs.length < pageSize) { |
| 90 | + break; |
| 91 | + } |
| 92 | + } |
| 93 | + if (listed.length === 0) { |
| 94 | + throw new Error("No successful main CI runs found"); |
| 95 | + } |
| 96 | + // New gh versions reject reporter ANSI unless opted in; logs are parsed, never printed. |
| 97 | + const logFlags = (await readGh(["api", "--help"])).includes("--allow-escape-sequences") |
| 98 | + ? ["--allow-escape-sequences"] |
| 99 | + : []; |
| 100 | + const runs: CiTimingRun[] = []; |
| 101 | + for (const run of listed.slice(0, count)) { |
| 102 | + const logs: CiTimingRun["logs"] = []; |
| 103 | + let seenJobs = 0; |
| 104 | + for (let page = 1; page <= 25; page += 1) { |
| 105 | + const payload = jobPageSchema.parse( |
| 106 | + JSON.parse( |
| 107 | + await readGh([ |
| 108 | + "api", |
| 109 | + `repos/${repo}/actions/runs/${run.id}/jobs?filter=latest&per_page=100&page=${page}`, |
| 110 | + "--jq", |
| 111 | + "{total_count, jobs: [.jobs[] | {id, name, conclusion}]}", |
| 112 | + ]), |
| 113 | + ), |
| 114 | + ); |
| 115 | + for (const job of payload.jobs) { |
| 116 | + if (job.conclusion !== "success") { |
| 117 | + continue; |
| 118 | + } |
| 119 | + const kind = job.name.startsWith("checks-ui-e2e (") |
| 120 | + ? "uiE2e" |
| 121 | + : job.name.startsWith("checks-node-compact-") |
| 122 | + ? "compact" |
| 123 | + : undefined; |
| 124 | + if (kind) { |
| 125 | + console.error(`[ci-timings] ${run.id}: ${job.name}`); |
| 126 | + logs.push({ |
| 127 | + kind, |
| 128 | + text: await readGh(["api", `repos/${repo}/actions/jobs/${job.id}/logs`, ...logFlags]), |
| 129 | + }); |
| 130 | + } |
| 131 | + } |
| 132 | + seenJobs += payload.jobs.length; |
| 133 | + if (seenJobs >= payload.total_count) { |
| 134 | + break; |
| 135 | + } |
| 136 | + if (payload.jobs.length === 0 || page === 25) { |
| 137 | + throw new Error(`Job pagination incomplete for CI run ${run.id}`); |
| 138 | + } |
| 139 | + } |
| 140 | + runs.push({ id: run.id, createdAt: run.created_at, logs }); |
| 141 | + } |
| 142 | + let previous; |
| 143 | + try { |
| 144 | + previous = ciTestTimingsSchema.parse(JSON.parse(readFileSync(values.out, "utf8"))); |
| 145 | + } catch { |
| 146 | + // A missing or invalid baseline has no measurements worth preserving. |
| 147 | + } |
| 148 | + const { timings, changes, runIds } = refitTestTimings(runs, previous); |
| 149 | + if ( |
| 150 | + Object.keys(timings.uiE2e.fileSeconds).length + |
| 151 | + Object.keys(timings.compactGroupSeconds.blacksmith).length + |
| 152 | + Object.keys(timings.compactGroupSeconds.github).length === |
| 153 | + 0 |
| 154 | + ) { |
| 155 | + throw new Error("No test timings have at least two successful run samples"); |
| 156 | + } |
| 157 | + ciTestTimingsSchema.parse(timings); |
| 158 | + console.log(`Sampled successful main CI runs: ${runIds.join(", ")}\n`); |
| 159 | + console.log("| Key | Old seconds | New seconds | Delta |\n| --- | ---: | ---: | ---: |"); |
| 160 | + for (const change of changes) { |
| 161 | + const delta = |
| 162 | + change.old === undefined || change.old === 0 |
| 163 | + ? "new" |
| 164 | + : `${(((change.next - change.old) / change.old) * 100).toFixed(1)}%`; |
| 165 | + console.log(`| ${change.key} | ${change.old ?? "—"} | ${change.next} | ${delta} |`); |
| 166 | + } |
| 167 | + if (changes.length === 0) { |
| 168 | + console.log("\nNo timing changes exceed the 15% write threshold."); |
| 169 | + } else if (!values["dry-run"]) { |
| 170 | + mkdirSync(path.dirname(values.out), { recursive: true }); |
| 171 | + writeFileSync(values.out, `${JSON.stringify(timings, null, 2)}\n`); |
| 172 | + } |
| 173 | +} |
| 174 | + |
| 175 | +try { |
| 176 | + await main(); |
| 177 | +} catch (error) { |
| 178 | + console.error(error instanceof Error ? error.message : String(error)); |
| 179 | + console.error("[ci-timings] FAILED (exit 1)"); |
| 180 | + process.exitCode = 1; |
| 181 | +} |
0 commit comments