Public: anyone can read this; the crew can change it.
Runners show what an SLA rests on: queue wait, speed, availability and completion, measured #16845
Conflicts with main in 6 files
scripts/gate.ts · src/checks/runner_jobs.ts · src/http/api/runners.ts · and 3 more
sold/runner-metrics → main 1 commit 1 thread · 1 unresolved
This pull asks for more cpus. Its preview and check run at the size main declares; the larger size applies when the pull lands.
19 files
changed +1102
−12
- docs/features/runners.md
- docs/features/settings-runners.md
- scripts/gate.ts
- src/checks/runner_bench.ts
- src/checks/runner_bench_worker.ts
- src/checks/runner_jobs.ts
- src/checks/runner_metrics.ts
- src/contract/openapi/routes/getApiV1AdminRunners.ts
- src/contract/openapi/routes/index.ts
- src/contract/openapi/routes/postApiV1RunnerBench.ts
- src/core/migration-pins/20261201000000-runner-metrics.pin
- src/core/migrations/20261201000000-runner-metrics.ts
- src/http/api/runners.ts
- src/runner/main.ts
- src/tui/screens/runners.ts
- src/web/pages/runners.ts
- test/runner-bench-full.test.ts
- test/runner-bench-idle.test.ts
- test/runner-metrics.test.ts
docs/features/runners.md +6
| @@ -44,6 +44,12 @@ a remove for a hand-made one: [settings-runners.md](settings-runners.md). | ||
| 44 | 44 | |
| 45 | 45 | Not yet: a job that survives a restart, caches by hash (#14201's follow-ups). |
| 46 | 46 | |
| 47 | Each runner is measured: how long checks wait for it, its speed on a fixed reference benchmark it | |
| 48 | runs once a day, after a minute idle and never before its first claim or while it holds a job, in a worker it ends when a job comes (`POST /api/v1/runner/bench`, kept only with the work's | |
| 49 | digest), how often it is connected and how many of its jobs it finishes. The numbers are on | |
| 50 | Settings → Runners, in the terminal and in `GET /api/v1/admin/runners`: | |
| 51 | [](settings-runners.md). | |
| 52 | ||
| 47 | 53 | ## Start one, in two lines |
| 48 | 54 | |
| 49 | 55 | An admin enrols it (admin scope; the token is shown this once): |
docs/features/settings-runners.md +24
| @@ -12,6 +12,30 @@ asked**, when it last asked, how many jobs it runs at once (what its claim says, | ||
| 12 | 12 | and when it was enrolled. The rows are |
| 13 | 13 | the ones `GET /api/v1/admin/runners` answers with. |
| 14 | 14 | |
| 15 | **Metrics** (#16840, R1), the base for SLAs, on each row and for the forge as a whole above | |
| 16 | them, in plain words ("Checks wait 4 s for a runner (p95, last day); half wait 1.2 s or less"): | |
| 17 | ||
| 18 | - **Queue wait**: a job on the desk, from when it became claimable to when a runner claimed it, | |
| 19 | p50 and p95 over the last day (exact) and the last 30 days (from daily buckets, read at each | |
| 20 | bucket's upper bound so it errs long), for the forge and for each runner that claimed. | |
| 21 | - **Speed**: the reference benchmark (`src/checks/runner_bench.ts`) a runner runs once a day, | |
| 22 | only after a minute idle (never before its first claim, never while it holds a job), in a | |
| 23 | worker it ends the moment a job comes: a fixed sha256 chain and sort, half a second on a laptop | |
| 24 | core and about five seconds on a check runner. Shown in seconds and as a score against the forge's own `local-1` | |
| 25 | (2× is twice as fast). A report whose digest is not the work's is not kept. | |
| 26 | - **Availability**: the share of the last 7 days (or of its life, if younger) the runner asked for | |
| 27 | work, counted by the minute. | |
| 28 | - **Completion**: jobs finished out of jobs ended over 30 days. A job lost (its lease ran out, or | |
| 29 | its runner was removed while holding it), handed back, or ended by a step's timeout counts | |
| 30 | against it, and the latest says its reason. A job still held is not counted yet. | |
| 31 | ||
| 32 | Too little history says so instead of a number: fewer than 5 claims for a wait, fewer than 3 | |
| 33 | ended jobs for completion, under an hour for availability, and "not benchmarked yet". The facts | |
| 34 | are rows in SQLite (`runner_event`, `runner_wait_day`, `runner_presence`, `runner_bench`), kept 31 | |
| 35 | days (presence 8), and read on request: no timer and no polling. The same numbers are in | |
| 36 | `GET /api/v1/admin/runners` (`metrics` on each item and for the forge) and the terminal. | |
| 37 | Code: `src/checks/runner_metrics.ts`. | |
| 38 | ||
| 15 | 39 | **Remove** on a hand-made runner stops its token at once and queues again any job it held: the |
| 16 | 40 | same `remove` as `DELETE /api/v1/admin/runners/<id>`, and the same `runner.removed` event. A |
| 17 | 41 | `local-N` runner is the forge's own, started again at each boot, so it has no button and is |
scripts/gate.ts +1
| @@ -58,6 +58,7 @@ export const SLOW: readonly Exclusion[] = [ | ||
| 58 | 58 | { file: "test/apps-toolbar.test.ts", reason: "its opt-out test deploys a real scaffolded app twice; 2.35 s under full-suite load, 2.8 s alone here", issue: 13773 }, |
| 59 | 59 | { file: "test/following-incoming.test.ts", reason: "makes 52 real commits to pass the 50-line cap of the incoming list; 2.4 s under full-suite load, 0.5 s alone", issue: 13144 }, |
| 60 | 60 | { file: "test/release-sweep-safety-14784.test.ts", reason: "boots the real src/main.ts twice at once (proof and live control) to prove the outbox untouched; 4.1 s a test under full-suite load", issue: 14784 }, |
| 61 | { file: "test/runner-bench-full.test.ts", reason: "runs the runner's whole reference benchmark to prove its pinned digest; 0.5 s on a laptop core, 5.4 s on a check runner", issue: 16840 }, | |
| 61 | 62 | { file: "test/spawn-cell-looks.test.ts", reason: "boots a real child forge in a cell (~30 s) and waits for its own looks job to take a picture", issue: 10620 }, |
| 62 | 63 | // From the breach list closing this pull's check log at e2a5c15 (#12088): |
| 63 | 64 | // every test over the 2 s budget, its file named once with its slowest time. |
src/checks/runner_bench.ts added +49
| @@ -0,0 +1,49 @@ | ||
| 1 | /** | |
| 2 | * The runner's reference benchmark (#16840, R1): a small, fixed piece of work every runner does at | |
| 3 | * once a day when it sits idle, so a runner's speed is a number the forge can compare, not a | |
| 4 | * claim. It is deterministic: the same work gives the same digest on every machine, so the forge | |
| 5 | * can tell a runner that did the work from one that only said so (`BENCH_DIGEST`). It is about | |
| 6 | * half a second on a laptop core (0.5 s on an M-series Mac) and well under ten seconds on anything | |
| 7 | * that can run a check: a sha256 chain (hashing, the core of git and of installs) and a sort of pseudo-random | |
| 8 | * integers (the core of everything else), one thread, no disk, no network. | |
| 9 | */ | |
| 10 | ||
| 11 | /** The work's version: a change to `benchWork` is a new version, and old measurements stop comparing. */ | |
| 12 | export const BENCH_VERSION = 1; | |
| 13 | ||
| 14 | /** The digest `benchWork` gives, on any machine. A report with another is not counted. */ | |
| 15 | export const BENCH_DIGEST = "e778951785645ccb38209eefbd5c19b59d76973ab375ff01823410667b23c3e6"; | |
| 16 | ||
| 17 | /** The work's size: a sha256 chain this long, then a sort of this many integers. */ | |
| 18 | export const BENCH_SIZE = { chain: 3_000_000, sorted: 3_000_000 } as const; | |
| 19 | ||
| 20 | /** | |
| 21 | * The fixed work: its digest is the same everywhere. `size` is the benchmark's own unless a test | |
| 22 | * asks for a small run of the same work (with its own pinned digest). | |
| 23 | */ | |
| 24 | export function benchWork(size: BenchSize = BENCH_SIZE): string { | |
| 25 | const hasher = () => new Bun.CryptoHasher("sha256"); | |
| 26 | let block: Uint8Array = new Uint8Array(32); | |
| 27 | for (let i = 0; i < size.chain; i++) block = hasher().update(block).digest() as Uint8Array; | |
| 28 | // A linear congruential sequence, sorted as numbers, folded into the chain's last block. | |
| 29 | const numbers = new Uint32Array(size.sorted); | |
| 30 | let x = 0x9e3779b9; | |
| 31 | for (let i = 0; i < size.sorted; i++) { | |
| 32 | x = (Math.imul(x, 1664525) + 1013904223) >>> 0; | |
| 33 | numbers[i] = x; | |
| 34 | } | |
| 35 | numbers.sort(); | |
| 36 | const fold = hasher().update(block); | |
| 37 | for (let i = 0; i < size.sorted; i += 997) fold.update(numbers.subarray(i, i + 1)); | |
| 38 | return fold.digest("hex"); | |
| 39 | } | |
| 40 | ||
| 41 | /** The work's size, `BENCH_SIZE` or a test's smaller run of it. */ | |
| 42 | export type BenchSize = { readonly chain: number; readonly sorted: number }; | |
| 43 | ||
| 44 | /** Run the benchmark once: how long it took, in milliseconds, and its digest. */ | |
| 45 | export function runBench(size: BenchSize = BENCH_SIZE, now: () => number = () => performance.now()): { ms: number; digest: string; version: number } { | |
| 46 | const started = now(); | |
| 47 | const digest = benchWork(size); | |
| 48 | return { ms: Math.max(1, Math.round(now() - started)), digest, version: BENCH_VERSION }; | |
| 49 | } |
src/checks/runner_bench_worker.ts added +14
| @@ -0,0 +1,14 @@ | ||
| 1 | /** | |
| 2 | * The worker side of the runner's reference benchmark (`runner_bench.ts`): the work runs here, off | |
| 3 | * the runner's own thread, so a claim answered meanwhile is read at once and the runner can end the | |
| 4 | * benchmark the moment a job comes. | |
| 5 | */ | |
| 6 | ||
| 7 | import { runBench, type BenchSize } from "./runner_bench.ts"; | |
| 8 | ||
| 9 | declare const self: Worker; | |
| 10 | ||
| 11 | /** Asked with nothing, the benchmark's own size; a test asks a small run of the same work. */ | |
| 12 | self.onmessage = (e: MessageEvent<BenchSize | null>) => { | |
| 13 | postMessage(runBench(e.data ?? undefined)); | |
| 14 | }; |
src/checks/runner_jobs.ts +25
| @@ -22,6 +22,7 @@ import type { App } from "../app.ts"; | ||
| 22 | 22 | import { sha256 } from "../kernel/hash.ts"; |
| 23 | 23 | import { id, secret } from "../kernel/id.ts"; |
| 24 | 24 | import { during } from "../perf/jobs.ts"; |
| 25 | import { noteClaimed, noteEnded, noteGone, noteLost, notePresent, noteQueued, timedOut } from "./runner_metrics.ts"; | |
| 25 | 26 | |
| 26 | 27 | export const RUNNER_TOKEN_PREFIX = "forge_runner_"; |
| 27 | 28 | export const JOB_TOKEN_PREFIX = "forge_job_"; |
| @@ -166,6 +167,13 @@ export function listRunners(db: Database): Enrolled[] { | ||
| 166 | 167 | */ |
| 167 | 168 | export function removeRunner(db: Database, runnerId: string): boolean { |
| 168 | 169 | return db.transaction(() => { |
| 170 | // What it held is lost against it (runner_metrics.ts), and claimable again from now. | |
| 171 | noteLost( | |
| 172 | db, | |
| 173 | db.query<{ id: string; runner_id: string | null }, [string]>("SELECT id, runner_id FROM check_job WHERE runner_id = ?1 AND state = 'claimed'").all(runnerId), | |
| 174 | "its runner was removed while holding it", | |
| 175 | Date.now(), | |
| 176 | ); | |
| 169 | 177 | const gone = |
| 170 | 178 | db.query("DELETE FROM check_runner WHERE id = ?1").run(runnerId).changes > |
| 171 | 179 | 0; |
| @@ -198,6 +206,7 @@ export function runnerByToken( | ||
| 198 | 206 | row.id, |
| 199 | 207 | now, |
| 200 | 208 | ); |
| 209 | notePresent(db, row.id, now); | |
| 201 | 210 | return toEnrolled({ ...row, seen_at: now }); |
| 202 | 211 | } |
| 203 | 212 | |
| @@ -248,6 +257,7 @@ export function offerJob( | ||
| 248 | 257 | JSON.stringify(job), |
| 249 | 258 | job.cell === "required" ? 1 : 0, |
| 250 | 259 | ); |
| 260 | noteQueued(db, job.id, Date.now()); | |
| 251 | 261 | return job; |
| 252 | 262 | } |
| 253 | 263 | |
| @@ -285,6 +295,7 @@ export function claimJob( | ||
| 285 | 295 | ) |
| 286 | 296 | .run(row.id, runner.id, sha256(token), now + leaseMs).changes > 0; |
| 287 | 297 | if (taken) { |
| 298 | noteClaimed(db, row.id, runner.id, now); | |
| 288 | 299 | const spec = db |
| 289 | 300 | .query<{ spec: string }, [string]>("SELECT spec FROM check_job WHERE id = ?1") |
| 290 | 301 | .get(row.id)!.spec; |
| @@ -390,6 +401,11 @@ export function settleJob( | ||
| 390 | 401 | ); |
| 391 | 402 | // A job done is one more the runner has run (#15252); a returned one is not. |
| 392 | 403 | if (done && settled?.runner_id) db.query("UPDATE check_runner SET ran = ran + 1 WHERE id = ?1").run(settled.runner_id); |
| 404 | // Its outcome, for the runner's completion (runner_metrics.ts): a step's timeout counts against it. | |
| 405 | if (settled?.runner_id) { | |
| 406 | const late = done ? timedOut(end.done.steps) : undefined; | |
| 407 | noteEnded(db, jobId, settled.runner_id, !done ? "returned" : late !== undefined ? "timeout" : "done", !done ? end.returned : (late ?? ""), Date.now()); | |
| 408 | } | |
| 393 | 409 | return settled !== null; |
| 394 | 410 | })(); |
| 395 | 411 | } |
| @@ -399,6 +415,13 @@ export function settleJob( | ||
| 399 | 415 | * check each serves is still running under the forge's own lease: nothing is counted as a try. |
| 400 | 416 | */ |
| 401 | 417 | export function lapseJobs(db: Database, now: number): string[] { |
| 418 | // Each lapsing claim is lost against its runner (runner_metrics.ts), and claimable again from now. | |
| 419 | noteLost( | |
| 420 | db, | |
| 421 | db.query<{ id: string; runner_id: string | null }, [number]>("SELECT id, runner_id FROM check_job WHERE state = 'claimed' AND lease_until <= ?1").all(now), | |
| 422 | "its runner went silent and the lease ran out", | |
| 423 | now, | |
| 424 | ); | |
| 402 | 425 | return db |
| 403 | 426 | .query<{ id: string }, [number]>( |
| 404 | 427 | `UPDATE check_job SET state = 'queued', runner_id = NULL, token_hash = NULL, lease_until = 0 |
| @@ -410,6 +433,7 @@ export function lapseJobs(db: Database, now: number): string[] { | ||
| 410 | 433 | |
| 411 | 434 | /** Take a job nobody claimed back off the desk; false when a runner got there first. */ |
| 412 | 435 | export function withdrawJob(db: Database, jobId: string): boolean { |
| 436 | noteGone(db, jobId); | |
| 413 | 437 | return ( |
| 414 | 438 | db |
| 415 | 439 | .query("DELETE FROM check_job WHERE id = ?1 AND state = 'queued'") |
| @@ -419,6 +443,7 @@ export function withdrawJob(db: Database, jobId: string): boolean { | ||
| 419 | 443 | |
| 420 | 444 | /** The check that offered the job has ended: the row goes, and with it any claim. */ |
| 421 | 445 | export function dropJob(db: Database, jobId: string): void { |
| 446 | noteGone(db, jobId); | |
| 422 | 447 | db.query("DELETE FROM check_job WHERE id = ?1").run(jobId); |
| 423 | 448 | } |
| 424 | 449 |
src/checks/runner_metrics.ts added +378
| @@ -0,0 +1,378 @@ | ||
| 1 | /** | |
| 2 | * Runner metrics (#16840, R1): what an SLA for a runner, or for the forge's checks as a whole, | |
| 3 | * rests on. Four measures, each from facts the desk already sees (`runner_jobs.ts` calls the | |
| 4 | * `note*` functions where they happen), never from what a runner says of itself: | |
| 5 | * | |
| 6 | * - **Queue wait**: a job on the desk, from when it became claimable to when a runner claimed it, | |
| 7 | * p50 and p95 over the last day (from the raw claims) and the last 30 days (from a daily rollup | |
| 8 | * of fixed buckets, so a month is a few hundred rows however busy the forge is). | |
| 9 | * - **Speed**: the reference benchmark (`runner_bench.ts`) each runner runs once a day when idle, | |
| 10 | * in seconds and as a score against the forge's own `local-1` (2 is twice as fast). | |
| 11 | * A report whose digest is not the work's is not counted. | |
| 12 | * - **Availability**: the share of the last 7 days the runner was connected, counted in minutes it | |
| 13 | * asked for work (`runner_presence`). | |
| 14 | * - **Completion**: jobs finished out of jobs settled. A job lost (its lease ran out, or its runner | |
| 15 | * was removed holding it), handed back, or ended by a step's timeout counts against it, each | |
| 16 | * with its reason; a job still held is not counted yet. | |
| 17 | * | |
| 18 | * Little history is said, never dressed as a number: under `MIN_WAITS` claims, `MIN_SETTLED` ended | |
| 19 | * jobs or `MIN_AVAILABILITY_MINUTES` of a runner's life, the words say so. Everything is read on | |
| 20 | * request from compact rows; no timer, no polling. Raw facts are kept 31 days, presence 8. | |
| 21 | */ | |
| 22 | ||
| 23 | import type { Database } from "bun:sqlite"; | |
| 24 | import { BENCH_DIGEST, BENCH_VERSION } from "./runner_bench.ts"; | |
| 25 | ||
| 26 | const MINUTE_MS = 60_000; | |
| 27 | const DAY_MS = 86_400_000; | |
| 28 | /** The upper bound of each queue-wait bucket, in milliseconds; the last holds everything longer. */ | |
| 29 | export const WAIT_BUCKETS_MS: readonly number[] = [ | |
| 30 | 100, | |
| 31 | 250, | |
| 32 | 500, | |
| 33 | 1_000, | |
| 34 | 2_000, | |
| 35 | 3_000, | |
| 36 | 5_000, | |
| 37 | 7_500, | |
| 38 | 10_000, | |
| 39 | 15_000, | |
| 40 | 20_000, | |
| 41 | 30_000, | |
| 42 | 45_000, | |
| 43 | 60_000, | |
| 44 | 90_000, | |
| 45 | 120_000, | |
| 46 | 180_000, | |
| 47 | 300_000, | |
| 48 | 600_000, | |
| 49 | Infinity, | |
| 50 | ]; | |
| 51 | /** Fewer claims than this in a window: too few to say a percentile. */ | |
| 52 | export const MIN_WAITS = 5; | |
| 53 | /** Fewer ended jobs than this: too few to say a share. */ | |
| 54 | export const MIN_SETTLED = 3; | |
| 55 | /** A runner younger than this (or a window shorter): too little to say how often it is there. */ | |
| 56 | export const MIN_AVAILABILITY_MINUTES = 60; | |
| 57 | /** The forge's own first runner, the speed every score is against. */ | |
| 58 | export const REFERENCE_RUNNER = "local-1"; | |
| 59 | ||
| 60 | export type Outcome = "done" | "timeout" | "returned" | "lost"; | |
| 61 | const AGAINST: readonly Outcome[] = ["timeout", "returned", "lost"]; | |
| 62 | ||
| 63 | /** A percentile of values already sorted ascending, by nearest rank; 0 for none. */ | |
| 64 | export function percentile(sorted: readonly number[], p: number): number { | |
| 65 | if (sorted.length === 0) return 0; | |
| 66 | const rank = Math.min(sorted.length, Math.max(1, Math.ceil((p / 100) * sorted.length))); | |
| 67 | return sorted[rank - 1]!; | |
| 68 | } | |
| 69 | ||
| 70 | /** The bucket a wait falls in. */ | |
| 71 | export const bucketOf = (ms: number): number => WAIT_BUCKETS_MS.findIndex((upper) => ms <= upper); | |
| 72 | ||
| 73 | /** | |
| 74 | * A percentile from bucket counts (`counts[i]` waits in `WAIT_BUCKETS_MS[i]`): the upper bound of | |
| 75 | * the bucket the rank falls in, so it errs long, never short. The open last bucket reads as its | |
| 76 | * lower bound. | |
| 77 | */ | |
| 78 | export function bucketPercentile(counts: readonly number[], p: number): number { | |
| 79 | const n = counts.reduce((s, c) => s + c, 0); | |
| 80 | if (n === 0) return 0; | |
| 81 | const rank = Math.min(n, Math.max(1, Math.ceil((p / 100) * n))); | |
| 82 | let seen = 0; | |
| 83 | for (let i = 0; i < counts.length; i++) { | |
| 84 | seen += counts[i] ?? 0; | |
| 85 | if (seen >= rank) return Number.isFinite(WAIT_BUCKETS_MS[i]) ? WAIT_BUCKETS_MS[i]! : WAIT_BUCKETS_MS[i - 1]!; | |
| 86 | } | |
| 87 | return WAIT_BUCKETS_MS[WAIT_BUCKETS_MS.length - 2]!; | |
| 88 | } | |
| 89 | ||
| 90 | /** Whether a finished job's steps ended on a timeout, from `runStep`'s own words. */ | |
| 91 | export const timedOut = (steps: readonly { ok: boolean; error?: string }[]): string | undefined => | |
| 92 | steps.find((s) => !s.ok && s.error !== undefined && /took longer than|used its .*(second|minute|hour)/.test(s.error))?.error; | |
| 93 | ||
| 94 | // ---- the facts, noted where the desk sees them ---- | |
| 95 | ||
| 96 | const pruned = new WeakMap<Database, number>(); | |
| 97 | /** Drop what no window reads any more, at most once an hour. */ | |
| 98 | function prune(db: Database, now: number): void { | |
| 99 | if (now - (pruned.get(db) ?? 0) < 3_600_000) return; | |
| 100 | pruned.set(db, now); | |
| 101 | db.query("DELETE FROM runner_event WHERE at < ?1").run(now - 31 * DAY_MS); | |
| 102 | db.query("DELETE FROM runner_wait_day WHERE day < ?1").run(Math.floor(now / DAY_MS) - 31); | |
| 103 | db.query("DELETE FROM runner_presence WHERE minute < ?1").run(Math.floor(now / MINUTE_MS) - 8 * 1440); | |
| 104 | db.query("DELETE FROM runner_bench WHERE at < ?1 AND id NOT IN (SELECT MAX(id) FROM runner_bench GROUP BY runner_id)").run( | |
| 105 | now - 31 * DAY_MS, | |
| 106 | ); | |
| 107 | // A job whose check ended without the desk saying so (a forge that died) leaves its row behind. | |
| 108 | db.query("DELETE FROM runner_job_queued WHERE job_id NOT IN (SELECT id FROM check_job)").run(); | |
| 109 | } | |
| 110 | ||
| 111 | /** A job became claimable: offered, or back on the desk after a lost claim. */ | |
| 112 | export function noteQueued(db: Database, jobId: string, now: number): void { | |
| 113 | db.query("INSERT INTO runner_job_queued (job_id, at) VALUES (?1, ?2) ON CONFLICT(job_id) DO UPDATE SET at = excluded.at").run(jobId, now); | |
| 114 | } | |
| 115 | ||
| 116 | /** A runner claimed a job: its wait is the time since it became claimable. */ | |
| 117 | export function noteClaimed(db: Database, jobId: string, runnerId: string, now: number): void { | |
| 118 | const queued = db.query<{ at: number }, [string]>("SELECT at FROM runner_job_queued WHERE job_id = ?1").get(jobId); | |
| 119 | const ms = queued === null ? 0 : Math.max(0, now - queued.at); | |
| 120 | db.query("INSERT INTO runner_event (at, runner_id, job_id, kind, ms) VALUES (?1, ?2, ?3, 'claimed', ?4)").run(now, runnerId, jobId, ms); | |
| 121 | db.query( | |
| 122 | `INSERT INTO runner_wait_day (day, runner_id, bucket, n) VALUES (?1, ?2, ?3, 1) | |
| 123 | ON CONFLICT(day, runner_id, bucket) DO UPDATE SET n = n + 1`, | |
| 124 | ).run(Math.floor(now / DAY_MS), runnerId, bucketOf(ms)); | |
| 125 | prune(db, now); | |
| 126 | } | |
| 127 | ||
| 128 | /** A held job ended: finished, timed out, handed back, or lost, with the reason in words. */ | |
| 129 | export function noteEnded(db: Database, jobId: string, runnerId: string, outcome: Outcome, reason: string, now: number): void { | |
| 130 | db.query("INSERT INTO runner_event (at, runner_id, job_id, kind, reason) VALUES (?1, ?2, ?3, ?4, ?5)").run( | |
| 131 | now, | |
| 132 | runnerId, | |
| 133 | jobId, | |
| 134 | outcome, | |
| 135 | reason.slice(0, 200), | |
| 136 | ); | |
| 137 | if (outcome !== "lost") db.query("DELETE FROM runner_job_queued WHERE job_id = ?1").run(jobId); | |
| 138 | } | |
| 139 | ||
| 140 | /** | |
| 141 | * Claims about to be taken back (their leases ran out, or their runner was removed): each is a | |
| 142 | * lost job against the runner that held it, and is claimable again from now. | |
| 143 | */ | |
| 144 | export function noteLost(db: Database, held: readonly { id: string; runner_id: string | null }[], reason: string, now: number): void { | |
| 145 | for (const job of held) { | |
| 146 | if (job.runner_id !== null) noteEnded(db, job.id, job.runner_id, "lost", reason, now); | |
| 147 | noteQueued(db, job.id, now); | |
| 148 | } | |
| 149 | } | |
| 150 | ||
| 151 | /** A job left the desk unclaimed or ended with its check: nothing more to measure of it. */ | |
| 152 | export function noteGone(db: Database, jobId: string): void { | |
| 153 | db.query("DELETE FROM runner_job_queued WHERE job_id = ?1").run(jobId); | |
| 154 | } | |
| 155 | ||
| 156 | /** A runner asked for work: this minute it was there. */ | |
| 157 | export function notePresent(db: Database, runnerId: string, now: number): void { | |
| 158 | db.query("INSERT OR IGNORE INTO runner_presence (runner_id, minute) VALUES (?1, ?2)").run(runnerId, Math.floor(now / MINUTE_MS)); | |
| 159 | } | |
| 160 | ||
| 161 | /** Keep a runner's benchmark, if it is the work's: the version and digest match, the time is sane. */ | |
| 162 | export function noteBench( | |
| 163 | db: Database, | |
| 164 | runnerId: string, | |
| 165 | raw: { ms?: unknown; digest?: unknown; version?: unknown }, | |
| 166 | now: number, | |
| 167 | ): boolean { | |
| 168 | const ms = Number(raw.ms); | |
| 169 | if (raw.version !== BENCH_VERSION || raw.digest !== BENCH_DIGEST || !Number.isFinite(ms) || ms < 1 || ms > 600_000) return false; | |
| 170 | db.query("INSERT INTO runner_bench (runner_id, at, ms, version) VALUES (?1, ?2, ?3, ?4)").run( | |
| 171 | runnerId, | |
| 172 | now, | |
| 173 | Math.round(ms), | |
| 174 | BENCH_VERSION, | |
| 175 | ); | |
| 176 | return true; | |
| 177 | } | |
| 178 | ||
| 179 | // ---- the read ---- | |
| 180 | ||
| 181 | /** Queue waits in a window: how many, and the median and 95th percentile in milliseconds. */ | |
| 182 | export interface Waits { | |
| 183 | readonly n: number; | |
| 184 | readonly p50: number; | |
| 185 | readonly p95: number; | |
| 186 | } | |
| 187 | ||
| 188 | export interface Speed { | |
| 189 | readonly ms: number; | |
| 190 | readonly at: number; | |
| 191 | /** Against `local-1`'s latest (its time over this one's): 2 is twice as fast; null with no reference. */ | |
| 192 | readonly score: number | null; | |
| 193 | } | |
| 194 | ||
| 195 | export interface Completion { | |
| 196 | readonly done: number; | |
| 197 | readonly timeout: number; | |
| 198 | readonly returned: number; | |
| 199 | readonly lost: number; | |
| 200 | /** Finished over ended, 0 to 1; null under `MIN_SETTLED`. */ | |
| 201 | readonly share: number | null; | |
| 202 | /** The latest jobs counted against it, newest first, each with its reason. */ | |
| 203 | readonly against: readonly { readonly outcome: Outcome; readonly reason: string; readonly at: number }[]; | |
| 204 | } | |
| 205 | ||
| 206 | export interface Measured { | |
| 207 | readonly waitDay: Waits; | |
| 208 | readonly waitMonth: Waits; | |
| 209 | /** Share of the window it was connected, 0 to 1; null when the window is under `MIN_AVAILABILITY_MINUTES`. */ | |
| 210 | readonly availability: number | null; | |
| 211 | readonly completion: Completion; | |
| 212 | } | |
| 213 | ||
| 214 | export interface RunnerMetrics extends Measured { | |
| 215 | readonly speed: Speed | null; | |
| 216 | } | |
| 217 | ||
| 218 | export interface ForgeMetrics extends Measured { | |
| 219 | /** `local-1`'s latest benchmark, the reference every score is against; null before it ran. */ | |
| 220 | readonly referenceMs: number | null; | |
| 221 | } | |
| 222 | ||
| 223 | const waitsOf = (values: number[]): Waits => { | |
| 224 | const sorted = values.sort((a, b) => a - b); | |
| 225 | return { n: sorted.length, p50: percentile(sorted, 50), p95: percentile(sorted, 95) }; | |
| 226 | }; | |
| 227 | const bucketWaits = (counts: number[]): Waits => ({ | |
| 228 | n: counts.reduce((s, c) => s + c, 0), | |
| 229 | p50: bucketPercentile(counts, 50), | |
| 230 | p95: bucketPercentile(counts, 95), | |
| 231 | }); | |
| 232 | ||
| 233 | /** | |
| 234 | * Every runner's metrics and the forge's, read at `now`: seven queries, none of them a scan of | |
| 235 | * more than a month of facts. | |
| 236 | */ | |
| 237 | export function readMetrics( | |
| 238 | db: Database, | |
| 239 | runners: readonly { readonly id: string; readonly name: string; readonly createdAt: string }[], | |
| 240 | now: number, | |
| 241 | ): { forge: ForgeMetrics; byRunner: Map<string, RunnerMetrics> } { | |
| 242 | const dayAgo = now - DAY_MS; | |
| 243 | const monthAgo = now - 30 * DAY_MS; | |
| 244 | const nowMinute = Math.floor(now / MINUTE_MS); | |
| 245 | const weekMinutes = 7 * 1440; | |
| 246 | const claims = db | |
| 247 | .query<{ runner_id: string; ms: number }, [number]>("SELECT runner_id, ms FROM runner_event WHERE kind = 'claimed' AND at > ?1") | |
| 248 | .all(dayAgo); | |
| 249 | const buckets = db | |
| 250 | .query< | |
| 251 | { runner_id: string; bucket: number; n: number }, | |
| 252 | [number] | |
| 253 | >("SELECT runner_id, bucket, SUM(n) AS n FROM runner_wait_day WHERE day > ?1 GROUP BY runner_id, bucket") | |
| 254 | .all(Math.floor(now / DAY_MS) - 30); | |
| 255 | const ends = db | |
| 256 | .query< | |
| 257 | { runner_id: string; kind: Outcome; n: number }, | |
| 258 | [number] | |
| 259 | >("SELECT runner_id, kind, COUNT(*) AS n FROM runner_event WHERE kind IN ('done', 'timeout', 'returned', 'lost') AND at > ?1 GROUP BY runner_id, kind") | |
| 260 | .all(monthAgo); | |
| 261 | const against = db | |
| 262 | .query< | |
| 263 | { runner_id: string; kind: Outcome; reason: string; at: number }, | |
| 264 | [number] | |
| 265 | >("SELECT runner_id, kind, reason, at FROM runner_event WHERE kind IN ('timeout', 'returned', 'lost') AND at > ?1 ORDER BY at DESC LIMIT 60") | |
| 266 | .all(monthAgo); | |
| 267 | const present = db | |
| 268 | .query< | |
| 269 | { runner_id: string; n: number }, | |
| 270 | [number] | |
| 271 | >("SELECT runner_id, COUNT(*) AS n FROM runner_presence WHERE minute > ?1 GROUP BY runner_id") | |
| 272 | .all(nowMinute - weekMinutes); | |
| 273 | const anyPresent = | |
| 274 | db | |
| 275 | .query<{ n: number }, [number]>("SELECT COUNT(DISTINCT minute) AS n FROM runner_presence WHERE minute > ?1") | |
| 276 | .get(nowMinute - weekMinutes)?.n ?? 0; | |
| 277 | const benches = db | |
| 278 | .query< | |
| 279 | { runner_id: string; ms: number; at: number }, | |
| 280 | [number] | |
| 281 | >("SELECT runner_id, ms, MAX(at) AS at FROM runner_bench WHERE version = ?1 GROUP BY runner_id") | |
| 282 | .all(BENCH_VERSION); | |
| 283 | ||
| 284 | const counts = (rows: readonly { runner_id: string; bucket: number; n: number }[]): number[] => { | |
| 285 | const out = WAIT_BUCKETS_MS.map(() => 0); | |
| 286 | for (const r of rows) out[r.bucket] = (out[r.bucket] ?? 0) + r.n; | |
| 287 | return out; | |
| 288 | }; | |
| 289 | const completionOf = (rows: readonly { kind: Outcome; n: number }[], latest: typeof against): Completion => { | |
| 290 | const by = (k: Outcome) => rows.filter((r) => r.kind === k).reduce((s, r) => s + r.n, 0); | |
| 291 | const done = by("done"); | |
| 292 | const ended = done + AGAINST.reduce((s, k) => s + by(k), 0); | |
| 293 | return { | |
| 294 | done, | |
| 295 | timeout: by("timeout"), | |
| 296 | returned: by("returned"), | |
| 297 | lost: by("lost"), | |
| 298 | share: ended < MIN_SETTLED ? null : done / ended, | |
| 299 | against: latest.slice(0, 3).map((r) => ({ outcome: r.kind, reason: r.reason, at: r.at })), | |
| 300 | }; | |
| 301 | }; | |
| 302 | /** The share of a window, from `since` (capped at a week) to now, that `minutes` cover. */ | |
| 303 | const share = (minutes: number, since: number): number | null => { | |
| 304 | const window = Math.min(weekMinutes, Math.floor((now - since) / MINUTE_MS)); | |
| 305 | return window < MIN_AVAILABILITY_MINUTES ? null : Math.min(1, minutes / window); | |
| 306 | }; | |
| 307 | const reference = benches.find((b) => runners.some((r) => r.id === b.runner_id && r.name === REFERENCE_RUNNER)); | |
| 308 | ||
| 309 | const byRunner = new Map<string, RunnerMetrics>(); | |
| 310 | for (const r of runners) { | |
| 311 | const bench = benches.find((b) => b.runner_id === r.id); | |
| 312 | byRunner.set(r.id, { | |
| 313 | waitDay: waitsOf(claims.filter((c) => c.runner_id === r.id).map((c) => c.ms)), | |
| 314 | waitMonth: bucketWaits(counts(buckets.filter((b) => b.runner_id === r.id))), | |
| 315 | availability: share(present.find((p) => p.runner_id === r.id)?.n ?? 0, Date.parse(r.createdAt) || now), | |
| 316 | completion: completionOf( | |
| 317 | ends.filter((e) => e.runner_id === r.id), | |
| 318 | against.filter((a) => a.runner_id === r.id), | |
| 319 | ), | |
| 320 | speed: | |
| 321 | bench === undefined | |
| 322 | ? null | |
| 323 | : { ms: bench.ms, at: bench.at, score: reference === undefined ? null : Math.round((reference.ms / bench.ms) * 100) / 100 }, | |
| 324 | }); | |
| 325 | } | |
| 326 | const firstEnrolled = Math.min(now, ...runners.map((r) => Date.parse(r.createdAt) || now)); | |
| 327 | return { | |
| 328 | forge: { | |
| 329 | waitDay: waitsOf(claims.map((c) => c.ms)), | |
| 330 | waitMonth: bucketWaits(counts(buckets)), | |
| 331 | availability: runners.length === 0 ? null : share(anyPresent, firstEnrolled), | |
| 332 | completion: completionOf(ends, against), | |
| 333 | referenceMs: reference?.ms ?? null, | |
| 334 | }, | |
| 335 | byRunner, | |
| 336 | }; | |
| 337 | } | |
| 338 | ||
| 339 | // ---- the words every door says ---- | |
| 340 | ||
| 341 | /** A duration as people say it: "under 1 s", "4.2 s", "38 s", "3 min". */ | |
| 342 | export function seconds(ms: number): string { | |
| 343 | if (ms < 1_000) return "under 1 s"; | |
| 344 | if (ms < 10_000) return `${(Math.round(ms / 100) / 10).toString()} s`; | |
| 345 | if (ms < 120_000) return `${Math.round(ms / 1_000)} s`; | |
| 346 | return `${Math.round(ms / 60_000)} min`; | |
| 347 | } | |
| 348 | ||
| 349 | const PERIOD = { day: "last day", month: "last 30 days" } as const; | |
| 350 | ||
| 351 | /** "Checks wait 4 s for a runner (p95, last day); half wait 1.2 s or less", or that there is too little to say. */ | |
| 352 | export function waitWords(w: Waits, period: keyof typeof PERIOD, who = "Checks"): string { | |
| 353 | if (w.n < MIN_WAITS) | |
| 354 | return `${who === "Checks" ? "Too few checks" : "Too few claims"} in the ${PERIOD[period]} to say a wait (${w.n} so far)`; | |
| 355 | return `${who} wait ${seconds(w.p95)} for a runner (p95, ${PERIOD[period]}); half wait ${w.p50 < 1_000 ? "under 1 s" : `${seconds(w.p50)} or less`}`; | |
| 356 | } | |
| 357 | ||
| 358 | /** "Benchmark 0.5 s, 1.8× local-1's speed (Mon 30 Nov)", or that it has not run. */ | |
| 359 | export function speedWords(s: Speed | null): string { | |
| 360 | if (s === null) return "Not benchmarked yet: it runs the reference work once a day, when it has sat idle a minute"; | |
| 361 | const score = s.score === null ? `; ${REFERENCE_RUNNER} has not run it yet, so no score` : `, ${s.score}× ${REFERENCE_RUNNER}'s speed`; | |
| 362 | return `Benchmark ${seconds(s.ms)}${score}`; | |
| 363 | } | |
| 364 | ||
| 365 | /** "Connected 96% of the last 7 days", or that it is too new to say. */ | |
| 366 | export function availabilityWords(share: number | null): string { | |
| 367 | return share === null | |
| 368 | ? "Too new to say how often it is connected (under an hour)" | |
| 369 | : `Connected ${Math.round(share * 100)}% of the last 7 days`; | |
| 370 | } | |
| 371 | ||
| 372 | /** "Finished 97% of the jobs it took (34 of 35); the last against it: lost, the runner went silent". */ | |
| 373 | export function completionWords(c: Completion): string { | |
| 374 | const ended = c.done + c.timeout + c.returned + c.lost; | |
| 375 | if (c.share === null) return `Too few jobs ended in the last 30 days to say (${ended} so far)`; | |
| 376 | const last = c.against[0]; | |
| 377 | return `Finished ${Math.round(c.share * 100)}% of the jobs it took (${c.done} of ${ended}, last 30 days)${last === undefined ? "" : `; the last against it: ${last.outcome === "returned" ? "handed back" : last.outcome === "timeout" ? "timed out" : "lost"}, ${last.reason}`}`; | |
| 378 | } |
src/contract/openapi/routes/getApiV1AdminRunners.ts +1 −1
| @@ -6,7 +6,7 @@ export const route: Route = { | ||
| 6 | 6 | summary: |
| 7 | 7 | "The enrolled runners, each with when it last asked for work", |
| 8 | 8 | detail: |
| 9 | "The enrolled runners, each with when it last asked for work (seenAt, milliseconds; 0 for never); answers { items, next_cursor }", | |
| 9 | "The enrolled runners, each with when it last asked for work (seenAt, milliseconds; 0 for never) and its metrics (queue wait p50/p95 over the last day and 30 days, benchmark speed against local-1, share of the last 7 days connected, jobs finished of those ended with what counted against it), and the forge's metrics as a whole; answers { items, metrics, next_cursor }", | |
| 10 | 10 | auth: true, |
| 11 | 11 | role: "admin", |
| 12 | 12 | refuses: [404], |
src/contract/openapi/routes/index.ts +1
| @@ -451,6 +451,7 @@ export { route as postApiV1ReposOwnerNameSpend } from "./postApiV1ReposOwnerName | ||
| 451 | 451 | export { route as postApiV1ReposOwnerNameSync } from "./postApiV1ReposOwnerNameSync.ts"; |
| 452 | 452 | export { route as postApiV1ReposOwnerNameTransfer } from "./postApiV1ReposOwnerNameTransfer.ts"; |
| 453 | 453 | export { route as postApiV1ReposOwnerNameUpstreamCheck } from "./postApiV1ReposOwnerNameUpstreamCheck.ts"; |
| 454 | export { route as postApiV1RunnerBench } from "./postApiV1RunnerBench.ts"; | |
| 454 | 455 | export { route as postApiV1RunnerClaim } from "./postApiV1RunnerClaim.ts"; |
| 455 | 456 | export { route as postApiV1RunnerJobsId } from "./postApiV1RunnerJobsId.ts"; |
| 456 | 457 | export { route as postApiV1RunnerJobsIdGitGitUploadPack } from "./postApiV1RunnerJobsIdGitGitUploadPack.ts"; |
src/contract/openapi/routes/postApiV1RunnerBench.ts added +18
| @@ -0,0 +1,18 @@ | ||
| 1 | import type { Route } from "../shared.ts"; | |
| 2 | ||
| 3 | export const route: Route = { | |
| 4 | method: "post", | |
| 5 | path: "/api/v1/runner/bench", | |
| 6 | summary: "A runner reports its reference benchmark. Takes a runner token as the bearer", | |
| 7 | detail: | |
| 8 | "A runner reports the reference benchmark it ran (src/checks/runner_bench.ts) once a day, when it has sat idle: ms, the digest the work gives and the work's version. Kept for its speed on Settings → Runners and GET /api/v1/admin/runners only when the digest and version are the work's; answers 204", | |
| 9 | auth: false, | |
| 10 | role: "anonymous", | |
| 11 | body: { ms: "integer", digest: "string", version: "integer" }, | |
| 12 | alsoStatus: [204], | |
| 13 | refusals: { | |
| 14 | unauthorized: "401: not a runner token this forge enrolled", | |
| 15 | invalid_bench: "422: the digest or version is not the work's, or the time is not a number of milliseconds", | |
| 16 | }, | |
| 17 | errorStatus: { 401: "`unauthorized`: not a runner token this forge enrolled", 422: "`invalid_bench`: not the work's digest or version" }, | |
| 18 | }; |
src/core/migration-pins/20261201000000-runner-metrics.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | 670a596fdd95f94ebd30ad609ae25f0dda6b27d7ea198ffcf5eae66376d71a29 |
src/core/migrations/20261201000000-runner-metrics.ts added +47
| @@ -0,0 +1,47 @@ | ||
| 1 | // Runner metrics (#16840, R1), the base for SLAs: what each runner and the forge as a whole are | |
| 2 | // measured by. `runner_event` is one fact a row (a claim with its queue wait, an end with its | |
| 3 | // outcome and reason), kept 31 days; `runner_job_queued` is when a job on the desk last became | |
| 4 | // claimable, so a claim knows how long it waited; `runner_wait_day` is the queue waits rolled up by | |
| 5 | // day and runner into fixed buckets, so 30 days of percentiles read a few hundred rows; | |
| 6 | // `runner_presence` is each minute a runner asked for work, kept 8 days, which availability | |
| 7 | // counts; `runner_bench` is each reference benchmark a runner ran. Times are milliseconds since | |
| 8 | // the epoch, days and minutes whole periods since it. | |
| 9 | // Additive: five tables and their indexes. | |
| 10 | export default ` | |
| 11 | CREATE TABLE runner_event ( | |
| 12 | id INTEGER PRIMARY KEY, | |
| 13 | at INTEGER NOT NULL, | |
| 14 | runner_id TEXT, | |
| 15 | job_id TEXT NOT NULL, | |
| 16 | kind TEXT NOT NULL, | |
| 17 | ms INTEGER NOT NULL DEFAULT 0, | |
| 18 | reason TEXT NOT NULL DEFAULT '' | |
| 19 | ); | |
| 20 | CREATE INDEX runner_event_kind_at ON runner_event (kind, at); | |
| 21 | CREATE INDEX runner_event_runner_at ON runner_event (runner_id, at); | |
| 22 | CREATE TABLE runner_job_queued ( | |
| 23 | job_id TEXT PRIMARY KEY, | |
| 24 | at INTEGER NOT NULL | |
| 25 | ) WITHOUT ROWID; | |
| 26 | CREATE TABLE runner_wait_day ( | |
| 27 | day INTEGER NOT NULL, | |
| 28 | runner_id TEXT NOT NULL, | |
| 29 | bucket INTEGER NOT NULL, | |
| 30 | n INTEGER NOT NULL, | |
| 31 | PRIMARY KEY (day, runner_id, bucket) | |
| 32 | ) WITHOUT ROWID; | |
| 33 | CREATE TABLE runner_presence ( | |
| 34 | runner_id TEXT NOT NULL, | |
| 35 | minute INTEGER NOT NULL, | |
| 36 | PRIMARY KEY (runner_id, minute) | |
| 37 | ) WITHOUT ROWID; | |
| 38 | CREATE INDEX runner_presence_minute ON runner_presence (minute); | |
| 39 | CREATE TABLE runner_bench ( | |
| 40 | id INTEGER PRIMARY KEY, | |
| 41 | runner_id TEXT NOT NULL, | |
| 42 | at INTEGER NOT NULL, | |
| 43 | ms INTEGER NOT NULL, | |
| 44 | version INTEGER NOT NULL | |
| 45 | ); | |
| 46 | CREATE INDEX runner_bench_runner_at ON runner_bench (runner_id, at); | |
| 47 | `; |
src/http/api/runners.ts +17 −3
| @@ -25,6 +25,7 @@ import { | ||
| 25 | 25 | settleJob, |
| 26 | 26 | type RunnerResult, |
| 27 | 27 | } from "../../checks/runner_jobs.ts"; |
| 28 | import { noteBench, readMetrics } from "../../checks/runner_metrics.ts"; | |
| 28 | 29 | import { notePhase, takeSessionTime } from "../../core/route_timing.ts"; |
| 29 | 30 | import { inFlight } from "../../perf/live.ts"; |
| 30 | 31 | import { advertiseRefs, serviceRpc } from "../../git/smart-http.ts"; |
| @@ -101,9 +102,10 @@ export function runnerRoutes(router: Router<Handler>): void { | ||
| 101 | 102 | const denied = accountAdmin(ctx, "ro"); |
| 102 | 103 | if (denied) return denied; |
| 103 | 104 | const seen = list(ctx.app, ctx.auth.user); |
| 104 | return seen.ok | |
| 105 | ? json({ items: seen.value, next_cursor: null }) | |
| 106 | : notFound(); | |
| 105 | if (!seen.ok) return notFound(); | |
| 106 | // Each runner's metrics beside it, and the forge's as a whole (#16840, R1). | |
| 107 | const measured = readMetrics(ctx.app.db, seen.value, Date.now()); | |
| 108 | return json({ items: seen.value.map((r) => ({ ...r, metrics: measured.byRunner.get(r.id) })), metrics: measured.forge, next_cursor: null }); | |
| 107 | 109 | }); |
| 108 | 110 | |
| 109 | 111 | router.add("DELETE", "/api/v1/admin/runners/:id", (ctx) => { |
| @@ -148,6 +150,18 @@ export function runnerRoutes(router: Router<Handler>): void { | ||
| 148 | 150 | } |
| 149 | 151 | }); |
| 150 | 152 | |
| 153 | // A runner's reference benchmark (`checks/runner_bench.ts`): its time, kept when the digest is | |
| 154 | // the work's. Run once a day, when the runner sits idle. | |
| 155 | router.add("POST", "/api/v1/runner/bench", async (ctx) => { | |
| 156 | const runner = runnerByToken(ctx.app.db, bearer(ctx.request), Date.now()); | |
| 157 | if (runner === undefined) return unauthorized(); | |
| 158 | const input = await boundedBody(ctx.request, STRANGER_MAX); | |
| 159 | if (input === "too_large") return apiError("too_large", 413, `at most ${STRANGER_MAX} bytes`); | |
| 160 | return noteBench(ctx.app.db, runner.id, input, Date.now()) | |
| 161 | ? new Response(null, { status: 204 }) | |
| 162 | : apiError("invalid_bench", 422, "bench takes { ms, digest, version } from the work in checks/runner_bench.ts, unchanged"); | |
| 163 | }); | |
| 164 | ||
| 151 | 165 | /** The job this request's token holds, with the check waiting on it here; else nothing. */ |
| 152 | 166 | const held = (ctx: Ctx) => { |
| 153 | 167 | const job = jobByToken( |
src/runner/main.ts +68 −4
| @@ -43,6 +43,7 @@ import type { | ||
| 43 | 43 | import { runGit } from "../git/env.ts"; |
| 44 | 44 | import { isSafeOid } from "../git/guard.ts"; |
| 45 | 45 | import { during } from "../perf/jobs.ts"; |
| 46 | import type { BenchSize } from "../checks/runner_bench.ts"; | |
| 46 | 47 | |
| 47 | 48 | /** How often a job's lines go to the forge; each report renews the lease. */ |
| 48 | 49 | const REPORT_MS = 1_000; |
| @@ -66,8 +67,17 @@ export interface RunnerOptions { | ||
| 66 | 67 | /** Stops it: no new claim, and a job in flight is handed back. */ |
| 67 | 68 | readonly signal?: AbortSignal | undefined; |
| 68 | 69 | readonly say?: ((line: string) => void) | undefined; |
| 70 | /** How long it must sit idle, holding nothing and offered nothing, before it benchmarks; default a minute. */ | |
| 71 | readonly benchIdleMs?: number | undefined; | |
| 72 | /** A test's small run of the benchmark's work (its digest is not the work's, so the forge refuses it). */ | |
| 73 | readonly benchSize?: BenchSize | undefined; | |
| 69 | 74 | } |
| 70 | 75 | |
| 76 | /** How often a runner runs the reference benchmark: once its first idle minute comes, then once a day. */ | |
| 77 | const BENCH_EVERY_MS = 86_400_000; | |
| 78 | /** How long a runner sits idle, holding nothing and offered nothing, before it benchmarks. */ | |
| 79 | const BENCH_IDLE_MS = 60_000; | |
| 80 | ||
| 71 | 81 | const pause = (ms: number, signal: AbortSignal): Promise<void> => |
| 72 | 82 | new Promise((resolve) => { |
| 73 | 83 | if (signal.aborted) return resolve(); |
| @@ -414,6 +424,48 @@ export async function runRunner(options: RunnerOptions): Promise<void> { | ||
| 414 | 424 | } |
| 415 | 425 | } |
| 416 | 426 | |
| 427 | /** | |
| 428 | * The reference benchmark (`checks/runner_bench.ts`, #16840), once a day, never in the way of | |
| 429 | * work: only after the runner has sat idle for `benchIdleMs` (no job held, its last claims | |
| 430 | * offered nothing), so a fresh runner claims at once; in a worker, so a claim's answer is read | |
| 431 | * meanwhile; and ended the moment a job comes, to be tried at the next idle stretch. The forge | |
| 432 | * keeps its time only when its digest is the work's. | |
| 433 | */ | |
| 434 | const benchIdleMs = options.benchIdleMs ?? BENCH_IDLE_MS; | |
| 435 | let benchedAt = 0; | |
| 436 | let benching: Worker | undefined; | |
| 437 | let held = 0; | |
| 438 | let busyAt = Date.now(); | |
| 439 | let askedIdle = false; | |
| 440 | const endBench = (): void => { | |
| 441 | benching?.terminate(); | |
| 442 | benching = undefined; | |
| 443 | }; | |
| 444 | stopping.addEventListener("abort", endBench, { once: true }); | |
| 445 | function maybeBench(): void { | |
| 446 | if (options.once === true || benching !== undefined || held > 0 || !askedIdle) return; | |
| 447 | if (Date.now() - busyAt < benchIdleMs || Date.now() - benchedAt < BENCH_EVERY_MS) return; | |
| 448 | const worker = new Worker(new URL("../checks/runner_bench_worker.ts", import.meta.url).href); | |
| 449 | benching = worker; | |
| 450 | worker.onmessage = (e: MessageEvent<{ ms: number; digest: string; version: number }>) => { | |
| 451 | if (benching !== worker) return; | |
| 452 | endBench(); | |
| 453 | benchedAt = Date.now(); | |
| 454 | const done = e.data; | |
| 455 | post("/api/v1/runner/bench", options.token, done, stopping) | |
| 456 | .then(async (res) => { | |
| 457 | await res.body?.cancel().catch(() => {}); | |
| 458 | say(`benchmark: ${(done.ms / 1000).toFixed(2)}s${res.ok ? "" : ` (the forge answered ${res.status})`}`); | |
| 459 | }) | |
| 460 | // The forge unreachable: tried again at the next day's turn, or the next start. | |
| 461 | .catch(() => {}); | |
| 462 | }; | |
| 463 | worker.onerror = () => { | |
| 464 | if (benching === worker) endBench(); | |
| 465 | }; | |
| 466 | worker.postMessage(options.benchSize ?? null); | |
| 467 | } | |
| 468 | ||
| 417 | 469 | async function loop(): Promise<void> { |
| 418 | 470 | while (!stopping.aborted) { |
| 419 | 471 | let res: Response; |
| @@ -433,11 +485,23 @@ export async function runRunner(options: RunnerOptions): Promise<void> { | ||
| 433 | 485 | throw new Error( |
| 434 | 486 | "the forge does not know this runner token (removed, or mistyped)", |
| 435 | 487 | ); |
| 436 | if (res.status === 200) | |
| 437 | await work((await res.json()) as Pick<Claim, "job" | "token">); | |
| 438 | else { | |
| 488 | if (res.status === 200) { | |
| 489 | // A job ends any benchmark under way: work first, the measure at the next idle stretch. | |
| 490 | endBench(); | |
| 491 | held += 1; | |
| 492 | busyAt = Date.now(); | |
| 493 | try { | |
| 494 | await work((await res.json()) as Pick<Claim, "job" | "token">); | |
| 495 | } finally { | |
| 496 | held -= 1; | |
| 497 | busyAt = Date.now(); | |
| 498 | } | |
| 499 | } else { | |
| 439 | 500 | await res.body?.cancel().catch(() => {}); |
| 440 | if (res.status !== 204) await pause(RETRY_MS, stopping); | |
| 501 | if (res.status === 204) { | |
| 502 | askedIdle = true; | |
| 503 | maybeBench(); | |
| 504 | } else await pause(RETRY_MS, stopping); | |
| 441 | 505 | } |
| 442 | 506 | if (options.once === true) return; |
| 443 | 507 | } |
src/tui/screens/runners.ts +8 −1
| @@ -9,6 +9,7 @@ | ||
| 9 | 9 | import { isLocal, list, removeHandMade, runnerState } from "../../actions/runners.ts"; |
| 10 | 10 | import { yieldNote, yieldState } from "../../checks/lent_yield.ts"; |
| 11 | 11 | import { heldByRunner, workByRunner } from "../../checks/runner_jobs.ts"; |
| 12 | import { availabilityWords, completionWords, readMetrics, speedWords, waitWords } from "../../checks/runner_metrics.ts"; | |
| 12 | 13 | import type { Ctx, Screen } from "../app/app.ts"; |
| 13 | 14 | import { binding } from "../app/keys.ts"; |
| 14 | 15 | import { style } from "../term/style.ts"; |
| @@ -33,13 +34,19 @@ export function runnersScreen(f: Session, ctx: Ctx): Screen { | ||
| 33 | 34 | const now = Date.now(); |
| 34 | 35 | const held = heldByRunner(f.db); |
| 35 | 36 | const work = workByRunner(f.db); |
| 37 | const measured = readMetrics(f.db, entries(), now); | |
| 36 | 38 | return entries().map((r) => { |
| 39 | const m = measured.byRunner.get(r.id); | |
| 37 | 40 | const n = held.get(r.id) ?? 0; |
| 38 | 41 | const w = work.get(r.id) ?? { jobs: 1, ran: 0 }; |
| 39 | 42 | const asked = r.seenAt === 0 ? "has not asked for work" : `last asked ${new Date(r.seenAt).toISOString().slice(0, 16).replace("T", " ")}`; |
| 40 | 43 | return { |
| 41 | 44 | title: `${r.name} ${STATE_WORDS[runnerState(r.seenAt, now)]}${isLocal(r) ? " (the forge's own)" : ""}`, |
| 42 | 45 | meta: `${asked} · runs ${w.jobs} at once · holding ${n} · ${w.ran} job${w.ran === 1 ? "" : "s"} run`, |
| 46 | // Its metrics (#16840, R1), in the words Settings → Runners says. | |
| 47 | ...(m === undefined | |
| 48 | ? {} | |
| 49 | : { below: [`${waitWords(m.waitDay, "day", "Its claims")}.`, `${speedWords(m.speed)}. ${availabilityWords(m.availability)}.`, `${completionWords(m.completion)}.`] }), | |
| 43 | 50 | }; |
| 44 | 51 | }); |
| 45 | 52 | }; |
| @@ -54,7 +61,7 @@ export function runnersScreen(f: Session, ctx: Ctx): Screen { | ||
| 54 | 61 | ? "Only a forge admin sees the runners." |
| 55 | 62 | : entries().length === 0 |
| 56 | 63 | ? "No runner is enrolled; checks run on the forge's own machine." |
| 57 | : "The machines that take this forge's checks; x removes a hand-made one."; | |
| 64 | : `${waitWords(readMetrics(f.db, entries(), Date.now()).forge.waitDay, "day")}; x removes a hand-made one.`; | |
| 58 | 65 | const waiting = mayRunners(f) ? yieldNote(yieldState(process.env["FORGE_LEND_YIELD_LOAD"])) : ""; |
| 59 | 66 | s.text(head!.x, head!.y, truncate(waiting === "" ? text : waiting, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w); |
| 60 | 67 | drawList(s, body!, c, state, rows()); |
src/web/pages/runners.ts +25 −3
| @@ -11,7 +11,8 @@ | ||
| 11 | 11 | import { isLocal, list, removeHandMade, runnerState } from "../../actions/runners.ts"; |
| 12 | 12 | import { yieldNote, yieldState } from "../../checks/lent_yield.ts"; |
| 13 | 13 | import { heldByRunner, workByRunner, type Enrolled, type RunnerWork } from "../../checks/runner_jobs.ts"; |
| 14 | import { notePhase, takeSessionTime } from "../../core/route_timing.ts"; | |
| 14 | import { REFERENCE_RUNNER, availabilityWords, completionWords, readMetrics, seconds, speedWords, waitWords, type ForgeMetrics, type RunnerMetrics } from "../../checks/runner_metrics.ts"; | |
| 15 | import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts"; | |
| 15 | 16 | import type { Ctx } from "../../http/context.ts"; |
| 16 | 17 | import { sshOn } from "../../settings/ssh.ts"; |
| 17 | 18 | import { notFoundPage, pageHead, settingsLayout, signInFirst } from "../chrome.ts"; |
| @@ -29,7 +30,25 @@ function admin(ctx: Ctx): Response | undefined { | ||
| 29 | 30 | return ctx.auth.user.isAdmin && ctx.auth.user.kind === "user" ? undefined : notFoundPage(ctx); |
| 30 | 31 | } |
| 31 | 32 | |
| 32 | function runnerRow(r: Enrolled, held: number, work: RunnerWork, now: number) { | |
| 33 | /** A runner's metrics (#16840, R1) as row facts, in the words every door says. */ | |
| 34 | const metricFacts = (m: RunnerMetrics | undefined) => | |
| 35 | m === undefined | |
| 36 | ? [] | |
| 37 | : [ | |
| 38 | { label: "Queue wait", value: `${waitWords(m.waitDay, "day", "Its claims")}. ${waitWords(m.waitMonth, "month", "Its claims")}.` }, | |
| 39 | { label: "Speed", value: speedWords(m.speed) }, | |
| 40 | { label: "Availability", value: availabilityWords(m.availability) }, | |
| 41 | { label: "Completion", value: completionWords(m.completion) }, | |
| 42 | ]; | |
| 43 | ||
| 44 | /** The forge's checks as a whole: how long they wait for a runner, and how often one is there. */ | |
| 45 | const forgeLines = (f: ForgeMetrics) => | |
| 46 | html`<div class="status-rows" id="runner-metrics"> | |
| 47 | <p>${waitWords(f.waitDay, "day")}.</p> | |
| 48 | <p class="muted small">${waitWords(f.waitMonth, "month")}. ${f.availability === null ? "" : `A runner was connected ${Math.round(f.availability * 100)}% of the last 7 days. `}${completionWords(f.completion)}.${f.referenceMs === null ? "" : ` Speed scores are against ${REFERENCE_RUNNER}'s benchmark, ${seconds(f.referenceMs)}.`}</p> | |
| 49 | </div>`; | |
| 50 | ||
| 51 | function runnerRow(r: Enrolled, held: number, work: RunnerWork, now: number, m?: RunnerMetrics) { | |
| 33 | 52 | const state = runnerState(r.seenAt, now); |
| 34 | 53 | return row({ |
| 35 | 54 | lead: icon("activity"), |
| @@ -42,6 +61,7 @@ function runnerRow(r: Enrolled, held: number, work: RunnerWork, now: number) { | ||
| 42 | 61 | : badge("Never asked", { variant: "outline", icon: "ban" })}`, |
| 43 | 62 | meta: html`${r.seenAt === 0 ? "Has not asked for work" : html`Last asked for work ${time(new Date(r.seenAt).toISOString())}`} |
| 44 | 63 | · runs ${work.jobs} at once · holding ${held} now · ${work.ran} job${work.ran === 1 ? "" : "s"} run · enrolled ${time(r.createdAt, { date: true })}`, |
| 64 | facts: metricFacts(m), | |
| 45 | 65 | trail: isLocal(r) |
| 46 | 66 | ? html`<span class="muted small">The forge's own: started again at each boot, so not removed here.</span>` |
| 47 | 67 | : html`<form class="row-fields" method="post" action="${HERE}/${r.id}/remove"> |
| @@ -62,13 +82,15 @@ export function runnersPage(ctx: Ctx): Response { | ||
| 62 | 82 | const held = heldByRunner(ctx.app.db); |
| 63 | 83 | const work = workByRunner(ctx.app.db); |
| 64 | 84 | const waiting = yieldNote(yieldState(process.env["FORGE_LEND_YIELD_LOAD"])); |
| 85 | const measured = timePhase(ctx.request, "metrics", () => readMetrics(ctx.app.db, seen.value, now)); | |
| 65 | 86 | const body = html`<section class="settings-block"> |
| 66 | 87 | ${waiting === "" ? "" : html`<p class="muted small" id="lent-waiting">${waiting}</p>`} |
| 88 | ${seen.value.length === 0 ? "" : forgeLines(measured.forge)} | |
| 67 | 89 | <p class="muted small">Enrol one with <code>POST /api/v1/admin/runners</code>.</p> |
| 68 | 90 | ${seen.value.length === 0 |
| 69 | 91 | ? emptyList("runners") |
| 70 | 92 | : html`<ul class="list setting-list" id="runner-list"> |
| 71 | ${seen.value.map((r) => runnerRow(r, held.get(r.id) ?? 0, work.get(r.id) ?? { jobs: 1, ran: 0 }, now))} | |
| 93 | ${seen.value.map((r) => runnerRow(r, held.get(r.id) ?? 0, work.get(r.id) ?? { jobs: 1, ran: 0 }, now, measured.byRunner.get(r.id)))} | |
| 72 | 94 | </ul>`} |
| 73 | 95 | </section>`; |
| 74 | 96 | notePhase(ctx.request, "render", performance.now() - rendering); |
test/runner-bench-full.test.ts added +14
| @@ -0,0 +1,14 @@ | ||
| 1 | /** | |
| 2 | * The whole reference benchmark (#16840): its digest is the one the forge pins (`BENCH_DIGEST`), so | |
| 3 | * a runner's report counts, and it ends well under ten seconds. SLOW-listed: 0.5 s on a laptop | |
| 4 | * core, 5 s on a check runner; the default path tests a small run of the same work | |
| 5 | * (test/runner-metrics.test.ts). | |
| 6 | */ | |
| 7 | import { expect, test } from "bun:test"; | |
| 8 | import { BENCH_DIGEST, BENCH_VERSION, runBench } from "../src/checks/runner_bench.ts"; | |
| 9 | ||
| 10 | test("the whole work gives the pinned digest, in under ten seconds", () => { | |
| 11 | const run = runBench(); | |
| 12 | expect(run).toMatchObject({ digest: BENCH_DIGEST, version: BENCH_VERSION }); | |
| 13 | expect(run.ms).toBeLessThan(10_000); | |
| 14 | }, 20_000); |
test/runner-bench-idle.test.ts added +111
| @@ -0,0 +1,111 @@ | ||
| 1 | /** | |
| 2 | * A runner benchmarks only when idle (#16840): a fresh runner's first request is a claim, sent at | |
| 3 | * once, never held behind the benchmark; the benchmark starts only after its claims came back empty | |
| 4 | * for `benchIdleMs`, runs in a worker while the runner keeps claiming, and is reported with the | |
| 5 | * work's digest. A stand-in forge answers every claim with nothing. | |
| 6 | */ | |
| 7 | import { afterEach, expect, test } from "bun:test"; | |
| 8 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 9 | import { tmpdir } from "node:os"; | |
| 10 | import { join } from "node:path"; | |
| 11 | import { benchWork } from "../src/checks/runner_bench.ts"; | |
| 12 | import { runRunner } from "../src/runner/main.ts"; | |
| 13 | ||
| 14 | const SMALL = { chain: 2_000, sorted: 5_000 }; | |
| 15 | ||
| 16 | type Seen = { path: string; at: number; body: Record<string, unknown> }; | |
| 17 | const cleanups: (() => Promise<void>)[] = []; | |
| 18 | afterEach(async () => { | |
| 19 | for (const c of cleanups.splice(0)) await c(); | |
| 20 | }); | |
| 21 | ||
| 22 | /** A forge that offers nothing: each claim answers 204 after `holdMs`, as a long poll would. */ | |
| 23 | async function standIn(holdMs: number) { | |
| 24 | const seen: Seen[] = []; | |
| 25 | const server = Bun.serve({ | |
| 26 | port: 0, | |
| 27 | hostname: "127.0.0.1", | |
| 28 | async fetch(req) { | |
| 29 | const path = new URL(req.url).pathname; | |
| 30 | seen.push({ path, at: Date.now(), body: (await req.json().catch(() => ({}))) as Record<string, unknown> }); | |
| 31 | for (const w of waiters.splice(0)) w(); | |
| 32 | if (path === "/api/v1/runner/claim") { | |
| 33 | await new Promise((r) => setTimeout(r, holdMs)); // real-timer: the stand-in holds a claim open, as the forge\'s long poll does | |
| 34 | return new Response(null, { status: 204 }); | |
| 35 | } | |
| 36 | return new Response(null, { status: 204 }); | |
| 37 | }, | |
| 38 | }); | |
| 39 | const root = await mkdtemp(join(tmpdir(), "forge-runner-bench-")); | |
| 40 | const stop = new AbortController(); | |
| 41 | cleanups.push(async () => { | |
| 42 | stop.abort(); | |
| 43 | server.stop(true); | |
| 44 | await rm(root, { recursive: true, force: true }); | |
| 45 | }); | |
| 46 | return { seen, url: `http://127.0.0.1:${String(server.port)}`, root, stop }; | |
| 47 | } | |
| 48 | ||
| 49 | /** Woken on every request the stand-in sees. */ | |
| 50 | const waiters: (() => void)[] = []; | |
| 51 | ||
| 52 | /** The first request in `seen` that `ok` accepts, waking on each new one; undefined past `ms`. */ | |
| 53 | async function until(seen: Seen[], ok: (s: Seen) => boolean, ms: number): Promise<Seen | undefined> { | |
| 54 | const end = Date.now() + ms; | |
| 55 | for (;;) { | |
| 56 | const hit = seen.find(ok); | |
| 57 | if (hit !== undefined || Date.now() >= end) return hit; | |
| 58 | await new Promise<void>((wake) => { | |
| 59 | const deadline = setTimeout(wake, end - Date.now()); // real-timer: a deadline only; a request wakes it first | |
| 60 | waiters.push(() => { | |
| 61 | clearTimeout(deadline); | |
| 62 | wake(); | |
| 63 | }); | |
| 64 | }); | |
| 65 | } | |
| 66 | } | |
| 67 | ||
| 68 | test("a fresh runner's first request is a claim, at once; no benchmark before it is idle", async () => { | |
| 69 | const forge = await standIn(50); | |
| 70 | const started = Date.now(); | |
| 71 | const running = runRunner({ | |
| 72 | forgeUrl: forge.url, | |
| 73 | token: "forge_runner_test", | |
| 74 | root: forge.root, | |
| 75 | signal: forge.stop.signal, | |
| 76 | say: () => {}, | |
| 77 | }); | |
| 78 | const first = await until(forge.seen, () => true, 5_000); | |
| 79 | expect(first?.path).toBe("/api/v1/runner/claim"); | |
| 80 | // The cell probe aside, nothing stands between the start and the first claim. | |
| 81 | expect(first!.at - started).toBeLessThan(3_000); | |
| 82 | // Several empty claims later, still no benchmark: a minute of idle has not passed. | |
| 83 | await until(forge.seen, () => forge.seen.filter((s) => s.path === "/api/v1/runner/claim").length >= 4, 5_000); | |
| 84 | expect(forge.seen.some((s) => s.path === "/api/v1/runner/bench")).toBe(false); | |
| 85 | forge.stop.abort(); | |
| 86 | await running; | |
| 87 | }); | |
| 88 | ||
| 89 | test("once idle, it benchmarks in a worker while it keeps claiming, and reports the work's digest", async () => { | |
| 90 | const forge = await standIn(20); | |
| 91 | const running = runRunner({ | |
| 92 | forgeUrl: forge.url, | |
| 93 | token: "forge_runner_test", | |
| 94 | root: forge.root, | |
| 95 | signal: forge.stop.signal, | |
| 96 | say: () => {}, | |
| 97 | benchIdleMs: 0, | |
| 98 | benchSize: SMALL, | |
| 99 | }); | |
| 100 | const bench = await until(forge.seen, (s) => s.path === "/api/v1/runner/bench", 5_000); | |
| 101 | expect(bench?.body).toMatchObject({ digest: benchWork(SMALL), version: 1 }); | |
| 102 | // It came after a claim had come back empty, never first. | |
| 103 | expect(forge.seen.findIndex((s) => s.path === "/api/v1/runner/bench")).toBeGreaterThan(0); | |
| 104 | expect(forge.seen[0]!.path).toBe("/api/v1/runner/claim"); | |
| 105 | // Once a day: the next empty claims start no second one. | |
| 106 | const claimsThen = forge.seen.filter((s) => s.path === "/api/v1/runner/claim").length; | |
| 107 | await until(forge.seen, () => forge.seen.filter((s) => s.path === "/api/v1/runner/claim").length >= claimsThen + 3, 5_000); | |
| 108 | expect(forge.seen.filter((s) => s.path === "/api/v1/runner/bench")).toHaveLength(1); | |
| 109 | forge.stop.abort(); | |
| 110 | await running; | |
| 111 | }); |
test/runner-metrics.test.ts added +294
| @@ -0,0 +1,294 @@ | ||
| 1 | /** | |
| 2 | * Runner metrics (#16840, R1): queue wait percentiles (exact over a day, bucketed over 30 days), | |
| 3 | * the reference benchmark and its score against local-1, availability from the minutes a runner | |
| 4 | * asked for work, and completion: finished out of ended, with each lost, handed-back and timed-out | |
| 5 | * job counted against the runner that held it, by its reason. Too little history says so. | |
| 6 | */ | |
| 7 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 8 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 9 | import { tmpdir } from "node:os"; | |
| 10 | import { join } from "node:path"; | |
| 11 | import { createApp, type App } from "../src/app.ts"; | |
| 12 | import { BENCH_DIGEST, BENCH_VERSION, benchWork, runBench } from "../src/checks/runner_bench.ts"; | |
| 13 | import { claimJob, enrolRunner, lapseJobs, offerJob, removeRunner, settleJob, type RunnerJob } from "../src/checks/runner_jobs.ts"; | |
| 14 | import { | |
| 15 | MIN_WAITS, | |
| 16 | WAIT_BUCKETS_MS, | |
| 17 | availabilityWords, | |
| 18 | bucketOf, | |
| 19 | bucketPercentile, | |
| 20 | completionWords, | |
| 21 | noteBench, | |
| 22 | notePresent, | |
| 23 | noteQueued, | |
| 24 | percentile, | |
| 25 | readMetrics, | |
| 26 | seconds, | |
| 27 | speedWords, | |
| 28 | waitWords, | |
| 29 | } from "../src/checks/runner_metrics.ts"; | |
| 30 | import { listRunners } from "../src/checks/runner_jobs.ts"; | |
| 31 | import { createSession } from "../src/core/sessions.ts"; | |
| 32 | import { serve } from "../src/http/server.ts"; | |
| 33 | import { seedAdmin } from "./helpers/admin.ts"; | |
| 34 | import { getUserById, type User } from "../src/core/users.ts"; | |
| 35 | import { createForgeApp } from "../src/tui/forge.ts"; | |
| 36 | import { runnersScreen } from "../src/tui/screens/runners.ts"; | |
| 37 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; | |
| 38 | import { settleApp } from "./helpers/tui.ts"; | |
| 39 | import { setLoadSource } from "../src/checks/lent_yield.ts"; | |
| 40 | import { quietLogs } from "./helpers/globals.ts"; | |
| 41 | ||
| 42 | quietLogs(); | |
| 43 | ||
| 44 | const MIN = 60_000; | |
| 45 | const DAY = 86_400_000; | |
| 46 | const job: Omit<RunnerJob, "id"> = { | |
| 47 | run: "run-1", | |
| 48 | repo: "alice/lib", | |
| 49 | commit: "a".repeat(40), | |
| 50 | base: "b".repeat(40), | |
| 51 | depth: 1, | |
| 52 | steps: [{ name: "check", command: "bun test" }], | |
| 53 | env: {}, | |
| 54 | limits: { cpus: 1, memoryMiB: 512 }, | |
| 55 | timeoutS: 60, | |
| 56 | egress: [], | |
| 57 | egressMode: "enforce", | |
| 58 | cell: "preferred", | |
| 59 | cache: { repo: "repo-1", tree: "c".repeat(40), base: "b".repeat(40) }, | |
| 60 | }; | |
| 61 | const green = { steps: [{ name: "check", ok: true, ms: 1 }], contained: true, note: "" }; | |
| 62 | ||
| 63 | describe("percentiles", () => { | |
| 64 | test("nearest rank over sorted values", () => { | |
| 65 | const v = [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000]; | |
| 66 | expect(percentile(v, 50)).toBe(500); | |
| 67 | expect(percentile(v, 95)).toBe(1000); | |
| 68 | expect(percentile(v, 90)).toBe(900); | |
| 69 | expect(percentile([42], 95)).toBe(42); | |
| 70 | expect(percentile([], 50)).toBe(0); | |
| 71 | }); | |
| 72 | ||
| 73 | test("from bucket counts, the bucket's upper bound: it errs long, never short", () => { | |
| 74 | expect(bucketOf(0)).toBe(0); | |
| 75 | expect(bucketOf(100)).toBe(0); | |
| 76 | expect(bucketOf(101)).toBe(1); | |
| 77 | expect(bucketOf(4_000)).toBe(WAIT_BUCKETS_MS.indexOf(5_000)); | |
| 78 | expect(bucketOf(10 * 3_600_000)).toBe(WAIT_BUCKETS_MS.length - 1); | |
| 79 | const counts = WAIT_BUCKETS_MS.map(() => 0); | |
| 80 | counts[bucketOf(400)] = 18; // 18 waits under half a second | |
| 81 | counts[bucketOf(4_000)] = 2; // two of up to 5 s | |
| 82 | expect(bucketPercentile(counts, 50)).toBe(500); | |
| 83 | expect(bucketPercentile(counts, 95)).toBe(5_000); | |
| 84 | const forever = WAIT_BUCKETS_MS.map(() => 0); | |
| 85 | forever[WAIT_BUCKETS_MS.length - 1] = 3; | |
| 86 | expect(bucketPercentile(forever, 95)).toBe(600_000); | |
| 87 | expect( | |
| 88 | bucketPercentile( | |
| 89 | WAIT_BUCKETS_MS.map(() => 0), | |
| 90 | 50, | |
| 91 | ), | |
| 92 | ).toBe(0); | |
| 93 | }); | |
| 94 | ||
| 95 | test("the words: a wait in seconds, and too little history said plainly", () => { | |
| 96 | expect(seconds(400)).toBe("under 1 s"); | |
| 97 | expect(seconds(4_200)).toBe("4.2 s"); | |
| 98 | expect(seconds(38_400)).toBe("38 s"); | |
| 99 | expect(seconds(185_000)).toBe("3 min"); | |
| 100 | expect(waitWords({ n: 40, p50: 1_200, p95: 4_000 }, "day")).toBe( | |
| 101 | "Checks wait 4 s for a runner (p95, last day); half wait 1.2 s or less", | |
| 102 | ); | |
| 103 | expect(waitWords({ n: MIN_WAITS - 1, p50: 1, p95: 1 }, "month")).toBe( | |
| 104 | `Too few checks in the last 30 days to say a wait (${MIN_WAITS - 1} so far)`, | |
| 105 | ); | |
| 106 | expect(availabilityWords(null)).toBe("Too new to say how often it is connected (under an hour)"); | |
| 107 | expect(availabilityWords(0.964)).toBe("Connected 96% of the last 7 days"); | |
| 108 | expect(speedWords(null)).toStartWith("Not benchmarked yet"); | |
| 109 | }); | |
| 110 | }); | |
| 111 | ||
| 112 | describe("the reference benchmark", () => { | |
| 113 | // A small run of the same work, with its own pinned digest: the whole work's digest and time are | |
| 114 | // test/runner-bench-full.test.ts's (SLOW: 0.5 s on a laptop, 5 s on a check runner). | |
| 115 | const SMALL = { chain: 2_000, sorted: 5_000 }; | |
| 116 | const SMALL_DIGEST = "fc9320fda5280895ea87212b93268e5ca5f652cd868481f1c8a2bba9817efbda"; | |
| 117 | test("is deterministic: the same work gives the pinned digest, every run", () => { | |
| 118 | expect(benchWork(SMALL)).toBe(SMALL_DIGEST); | |
| 119 | const run = runBench(SMALL); | |
| 120 | expect(run).toMatchObject({ digest: SMALL_DIGEST, version: BENCH_VERSION }); | |
| 121 | expect(run.ms).toBeGreaterThanOrEqual(1); | |
| 122 | expect(benchWork({ ...SMALL, chain: SMALL.chain + 1 })).not.toBe(SMALL_DIGEST); | |
| 123 | }); | |
| 124 | }); | |
| 125 | ||
| 126 | describe("on a forge", () => { | |
| 127 | let dataDir = ""; | |
| 128 | let app: App; | |
| 129 | let adminId = ""; | |
| 130 | ||
| 131 | beforeAll(async () => { | |
| 132 | dataDir = await mkdtemp(join(tmpdir(), "forge-runner-metrics-")); | |
| 133 | app = createApp({ dataDir, port: 0 }); | |
| 134 | const a = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "correct-horse-battery" }); | |
| 135 | if (!a.ok) throw new Error(a.error); | |
| 136 | adminId = a.value.id; | |
| 137 | }); | |
| 138 | afterAll(async () => { | |
| 139 | app.close(); | |
| 140 | await rm(dataDir, { recursive: true, force: true }); | |
| 141 | }); | |
| 142 | ||
| 143 | /** Offer a job that became claimable `waited` ms before `at`, and claim it then. */ | |
| 144 | const claimed = (runnerId: string, at: number, waited: number) => { | |
| 145 | const offered = offerJob(app.db, { runId: "run-1", repoId: "repo-1", dir: "/nowhere", job }); | |
| 146 | noteQueued(app.db, offered.id, at - waited); | |
| 147 | const claim = claimJob(app.db, { id: runnerId, cells: true }, at); | |
| 148 | if (claim === undefined || claim.job.id !== offered.id) throw new Error("no claim"); | |
| 149 | return { id: offered.id, token: claim.token }; | |
| 150 | }; | |
| 151 | ||
| 152 | test("queue waits: exact over the day, per runner and for the forge", () => { | |
| 153 | const fast = enrolRunner(app.db, "local-1", adminId).runner; | |
| 154 | const slow = enrolRunner(app.db, "mac", adminId).runner; | |
| 155 | const now = Date.now(); | |
| 156 | for (const w of [200, 300, 400, 500, 600, 700, 800, 900, 1_000, 4_000]) | |
| 157 | { | |
| 158 | const c = claimed(fast.id, now, w); | |
| 159 | settleJob(app.db, c.id, c.token, { done: green }); | |
| 160 | } | |
| 161 | for (const w of [9_000, 12_000, 30_000]) { | |
| 162 | const c = claimed(slow.id, now, w); | |
| 163 | settleJob(app.db, c.id, c.token, { done: green }); | |
| 164 | } | |
| 165 | const m = readMetrics(app.db, listRunners(app.db), now + 1); | |
| 166 | expect(m.byRunner.get(fast.id)!.waitDay).toEqual({ n: 10, p50: 600, p95: 4_000 }); | |
| 167 | expect(m.byRunner.get(slow.id)!.waitDay.n).toBe(3); | |
| 168 | expect(waitWords(m.byRunner.get(slow.id)!.waitDay, "day", "Its claims")).toBe( | |
| 169 | "Too few claims in the last day to say a wait (3 so far)", | |
| 170 | ); | |
| 171 | expect(m.forge.waitDay).toEqual({ n: 13, p50: 800, p95: 30_000 }); | |
| 172 | // The month reads the daily buckets: the same claims, at their buckets' upper bounds. | |
| 173 | expect(m.byRunner.get(fast.id)!.waitMonth).toEqual({ n: 10, p50: 1_000, p95: 5_000 }); | |
| 174 | expect(m.forge.waitMonth.n).toBe(13); | |
| 175 | }); | |
| 176 | ||
| 177 | test("completion: finished of ended, and lost, handed back and timed out count against it with their reasons", () => { | |
| 178 | const r = enrolRunner(app.db, "flaky", adminId).runner; | |
| 179 | const now = Date.now(); | |
| 180 | for (let i = 0; i < 3; i++) { | |
| 181 | const c = claimed(r.id, now, 100); | |
| 182 | expect(settleJob(app.db, c.id, c.token, { done: green })).toBe(true); | |
| 183 | } | |
| 184 | const back = claimed(r.id, now, 100); | |
| 185 | expect(settleJob(app.db, back.id, back.token, { returned: "no cells here, and the job needs one" })).toBe(true); | |
| 186 | const late = claimed(r.id, now, 100); | |
| 187 | expect( | |
| 188 | settleJob(app.db, late.id, late.token, { | |
| 189 | done: { ...green, steps: [{ name: "check", ok: false, error: "check took longer than 600s", ms: 600_000 }] }, | |
| 190 | }), | |
| 191 | ).toBe(true); | |
| 192 | // A lease that runs out: lost, and claimable again. | |
| 193 | claimed(r.id, now, 100); | |
| 194 | expect(lapseJobs(app.db, now + 60_000)).toHaveLength(1); | |
| 195 | const m = readMetrics(app.db, listRunners(app.db), now + 60_001); | |
| 196 | const c = m.byRunner.get(r.id)!.completion; | |
| 197 | expect(c).toMatchObject({ done: 3, timeout: 1, returned: 1, lost: 1, share: 0.5 }); | |
| 198 | expect(c.against.map((a) => [a.outcome, a.reason])).toContainEqual(["lost", "its runner went silent and the lease ran out"]); | |
| 199 | expect(c.against.map((a) => [a.outcome, a.reason])).toContainEqual(["returned", "no cells here, and the job needs one"]); | |
| 200 | expect(c.against.map((a) => [a.outcome, a.reason])).toContainEqual(["timeout", "check took longer than 600s"]); | |
| 201 | expect(completionWords(c)).toStartWith("Finished 50% of the jobs it took (3 of 6, last 30 days); the last against it:"); | |
| 202 | // The lost job went back on the desk: another runner's claim of it waits from the lapse. | |
| 203 | const other = enrolRunner(app.db, "steady", adminId).runner; | |
| 204 | const again = claimJob(app.db, { id: other.id, cells: true }, now + 61_000); | |
| 205 | expect(again).toBeDefined(); | |
| 206 | const steady = readMetrics(app.db, listRunners(app.db), now + 61_001).byRunner.get(other.id)!; | |
| 207 | expect(steady.waitDay).toEqual({ n: 1, p50: 1_000, p95: 1_000 }); | |
| 208 | }); | |
| 209 | ||
| 210 | test("a runner removed while it holds a job loses it, by that reason; too few ended jobs say so", () => { | |
| 211 | const r = enrolRunner(app.db, "gone", adminId).runner; | |
| 212 | const now = Date.now(); | |
| 213 | claimed(r.id, now, 50); | |
| 214 | const before = readMetrics(app.db, listRunners(app.db), now).byRunner.get(r.id)!; | |
| 215 | expect(completionWords(before.completion)).toBe("Too few jobs ended in the last 30 days to say (0 so far)"); | |
| 216 | expect(removeRunner(app.db, r.id)).toBe(true); | |
| 217 | // Read with the row's id still known, as the API does for a moment after. | |
| 218 | const after = readMetrics(app.db, [{ id: r.id, name: "gone", createdAt: new Date(now).toISOString() }], now + 1).byRunner.get(r.id)!; | |
| 219 | expect(after.completion).toMatchObject({ lost: 1, share: null }); | |
| 220 | expect(after.completion.against[0]).toMatchObject({ outcome: "lost", reason: "its runner was removed while holding it" }); | |
| 221 | }); | |
| 222 | ||
| 223 | test("availability: the minutes it asked for work over its last week, and too new to say under an hour", () => { | |
| 224 | const r = enrolRunner(app.db, "weekend", adminId).runner; | |
| 225 | const now = Date.now(); | |
| 226 | expect(readMetrics(app.db, listRunners(app.db), now).byRunner.get(r.id)!.availability).toBeNull(); | |
| 227 | // Enrolled two days ago, there for one of them. | |
| 228 | app.db.query("UPDATE check_runner SET created_at = ?2 WHERE id = ?1").run(r.id, new Date(now - 2 * DAY).toISOString()); | |
| 229 | for (let i = 0; i < 1440; i++) notePresent(app.db, r.id, now - i * MIN); | |
| 230 | notePresent(app.db, r.id, now - 30_000); // twice in one minute counts once | |
| 231 | const m = readMetrics(app.db, listRunners(app.db), now).byRunner.get(r.id)!; | |
| 232 | expect(m.availability!).toBeCloseTo(0.5, 2); | |
| 233 | // Older than a week counts from a week ago, not from the enrolment. | |
| 234 | app.db.query("UPDATE check_runner SET created_at = ?2 WHERE id = ?1").run(r.id, new Date(now - 30 * DAY).toISOString()); | |
| 235 | expect(readMetrics(app.db, listRunners(app.db), now).byRunner.get(r.id)!.availability!).toBeCloseTo(1440 / (7 * 1440), 3); | |
| 236 | }); | |
| 237 | ||
| 238 | test("speed: a benchmark is kept only with the work's digest, and scored against local-1", () => { | |
| 239 | const runners = listRunners(app.db); | |
| 240 | const local = runners.find((r) => r.name === "local-1")!; | |
| 241 | const mac = runners.find((r) => r.name === "mac")!; | |
| 242 | const now = Date.now(); | |
| 243 | expect(noteBench(app.db, mac.id, { ms: 250, digest: "made-up", version: BENCH_VERSION }, now)).toBe(false); | |
| 244 | expect(noteBench(app.db, mac.id, { ms: 250, digest: BENCH_DIGEST, version: BENCH_VERSION + 1 }, now)).toBe(false); | |
| 245 | expect(noteBench(app.db, mac.id, { ms: 250, digest: BENCH_DIGEST, version: BENCH_VERSION }, now)).toBe(true); | |
| 246 | let m = readMetrics(app.db, listRunners(app.db), now); | |
| 247 | expect(m.byRunner.get(mac.id)!.speed).toMatchObject({ ms: 250, score: null }); | |
| 248 | expect(speedWords(m.byRunner.get(mac.id)!.speed)).toBe("Benchmark under 1 s; local-1 has not run it yet, so no score"); | |
| 249 | expect(noteBench(app.db, local.id, { ms: 500, digest: BENCH_DIGEST, version: BENCH_VERSION }, now)).toBe(true); | |
| 250 | m = readMetrics(app.db, listRunners(app.db), now); | |
| 251 | expect(m.byRunner.get(mac.id)!.speed!.score).toBe(2); | |
| 252 | expect(m.byRunner.get(local.id)!.speed!.score).toBe(1); | |
| 253 | expect(m.forge.referenceMs).toBe(500); | |
| 254 | }); | |
| 255 | ||
| 256 | test("the doors: Settings → Runners and GET /api/v1/admin/runners say the same numbers", async () => { | |
| 257 | const servers = await serve(app); | |
| 258 | try { | |
| 259 | const cookie = `forge_session=${createSession(app.db, adminId).token}`; | |
| 260 | const page = await (await fetch(`${servers.url}/settings/runners`, { headers: { cookie } })).text(); | |
| 261 | expect(page).toContain('id="runner-metrics"'); | |
| 262 | expect(page).toContain("for a runner (p95, last day)"); | |
| 263 | expect(page).toContain("Benchmark under 1 s, 2× local-1's speed"); | |
| 264 | expect(page).toContain("Finished 50% of the jobs it took"); | |
| 265 | const api = (await (await fetch(`${servers.url}/api/v1/admin/runners`, { headers: { cookie } })).json()) as { | |
| 266 | items: { name: string; metrics: { speed: { score: number } | null } }[]; | |
| 267 | metrics: { waitDay: { n: number } }; | |
| 268 | }; | |
| 269 | expect(api.items.find((i) => i.name === "mac")!.metrics.speed!.score).toBe(2); | |
| 270 | expect(api.metrics.waitDay.n).toBeGreaterThan(10); | |
| 271 | } finally { | |
| 272 | servers.stop(); | |
| 273 | } | |
| 274 | }); | |
| 275 | ||
| 276 | test("the terminal's Runners says the forge's wait and each runner's numbers", async () => { | |
| 277 | const admin = getUserById(app.db, adminId) as User; | |
| 278 | const { app: tui, session } = createForgeApp(app, { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: admin }, { terminal: headlessTerminal(200, 60), exitHooks: false }); | |
| 279 | tui.start(); | |
| 280 | // An idle machine: on a busy one the header says lent runners wait instead (lent_yield.ts). | |
| 281 | setLoadSource(() => 0); | |
| 282 | let text = ""; | |
| 283 | try { | |
| 284 | tui.ctx.push(runnersScreen(session, tui.ctx)); | |
| 285 | await settleApp(tui); | |
| 286 | text = tui.screen.toText(); | |
| 287 | } finally { | |
| 288 | setLoadSource(); | |
| 289 | } | |
| 290 | expect(text).toMatch(/Checks wait \S+ s for a runner \(p95, last day\); half wait [^;]+; x removes a hand-made one\./); | |
| 291 | expect(text).toContain("Benchmark under 1 s, 2× local-1's speed."); | |
| 292 | tui.stop?.(); | |
| 293 | }); | |
| 294 | }); |
new above
offline
Findings 1 and 2: the digest is a public constant so it proves nothing about speed, and every valid report inserts a new row with no per-runner limit. Upsert one row a runner and say the time is as reported.