Public: anyone can read this; the crew can change it.
Fail fast, fail loud: every queue and run has a budget, past it is a failure said in one sentence with its cause, and the owner is paged once #1273
mason/forge:mason/1270-fail-fast-fail-loud-every-queue-and-run → main 3 commits fork
13 files
changed +528
−59
CLAUDE.md +6 −2
| @@ -112,7 +112,9 @@ src/ | ||
| 112 | 112 | app.ts composition root — one data dir = one forge (dataDir is resolved |
| 113 | 113 | absolute here; the hook socket depends on it) |
| 114 | 114 | kernel/ zero-dep primitives: result, error, id (monotonic ULID), log, |
| 115 | db (sqlite/WAL), hash | |
| 115 | db (sqlite/WAL), hash, budgets (how long every queue and run | |
| 116 | may take, and the one sentence past it), vitals (the forge's | |
| 117 | standing: one `degraded` sentence per cause) | |
| 116 | 118 | git/ env (runGit*), read (cat-file batch readers), diff, merge (bare |
| 117 | 119 | plumbing, no work tree), write (commit via plumbing, deletes as |
| 118 | 120 | index-info mode 0, a `land` hook so an origin answers first), |
| @@ -192,7 +194,9 @@ src/ | ||
| 192 | 194 | may reach and read), workdir (where clones live), runner (one |
| 193 | 195 | run: token, clone, branch, Claude, push, open/update the pull, |
| 194 | 196 | report, reap leftovers), dispatch (outbox consumer + sweep + |
| 195 | worker tick), running (in-flight runs, for cancel) | |
| 197 | worker tick), running (in-flight runs, for cancel), notify | |
| 198 | (what newly asks a person, to their phone), forge_page (a | |
| 199 | degraded forge pages its admins once per cause) | |
| 196 | 200 | design/ themes, and activity (what an event is called, for both |
| 197 | 201 | surfaces) |
| 198 | 202 |
scripts/gate.ts +1
| @@ -108,6 +108,7 @@ export const GATE: readonly string[] = [ | ||
| 108 | 108 | "test/schema-additive.test.ts", |
| 109 | 109 | "test/schema-migrations.test.ts", |
| 110 | 110 | "test/vitals.test.ts", |
| 111 | "test/budgets.test.ts", | |
| 111 | 112 | "test/version.test.ts", |
| 112 | 113 | "test/watches.test.ts", |
| 113 | 114 | "test/guard.test.ts", |
src/crew/forge_page.ts added +136
| @@ -0,0 +1,136 @@ | ||
| 1 | /** | |
| 2 | * A degraded forge reaches its admins where they are. Every minute the | |
| 3 | * forge reads its own vitals (`kernel/vitals.ts`); each cause that newly | |
| 4 | * degrades it is posted once, as its one sentence, to every site admin who | |
| 5 | * set a phone URL (`crew/notify.ts`). A cause is paged once while it lasts, | |
| 6 | * and once paged it is quiet for an hour after — a lane that clears and | |
| 7 | * clogs again in that hour does not page twice. Nothing is paged per poll | |
| 8 | * or per viewer; a line that cannot be sent is dropped, never queued. | |
| 9 | * | |
| 10 | * What is remembered is in memory: a forge that restarts degraded pages | |
| 11 | * once more, which is news in itself. | |
| 12 | */ | |
| 13 | ||
| 14 | import type { App } from "../app.ts"; | |
| 15 | import { vitals, type Degraded } from "../kernel/vitals.ts"; | |
| 16 | import { notifyUrlOf, oneLine, post, type Sender } from "./notify.ts"; | |
| 17 | ||
| 18 | /** How long a paged cause stays quiet, open or cleared. */ | |
| 19 | export const QUIET_MS = 3_600_000; | |
| 20 | /** How often the forge reads its vitals for something to page. */ | |
| 21 | const TICK_MS = 60_000; | |
| 22 | /** At most this many causes are paged from one look; the board has the rest. */ | |
| 23 | const PER_LOOK = 3; | |
| 24 | ||
| 25 | /** | |
| 26 | * Which of `degraded` to page now: a cause not open at the last look and | |
| 27 | * not paged within the quiet hour, at most `PER_LOOK` of them; the rest | |
| 28 | * are paged on the looks after. `open` and `paged` are updated in place. | |
| 29 | */ | |
| 30 | export function causesToPage( | |
| 31 | degraded: readonly Degraded[], | |
| 32 | open: Set<string>, | |
| 33 | paged: Map<string, number>, | |
| 34 | now: number, | |
| 35 | ): Degraded[] { | |
| 36 | const out: Degraded[] = []; | |
| 37 | const current = new Set(degraded.map((d) => d.cause)); | |
| 38 | // Past PER_LOOK a new cause waits for the next look, so it stays un-open. | |
| 39 | const deferred = new Set<string>(); | |
| 40 | for (const d of degraded) { | |
| 41 | if (open.has(d.cause)) continue; | |
| 42 | const last = paged.get(d.cause); | |
| 43 | if (last !== undefined && now - last < QUIET_MS) continue; | |
| 44 | if (out.length >= PER_LOOK) { | |
| 45 | deferred.add(d.cause); | |
| 46 | continue; | |
| 47 | } | |
| 48 | paged.set(d.cause, now); | |
| 49 | out.push(d); | |
| 50 | } | |
| 51 | open.clear(); | |
| 52 | for (const cause of current) if (!deferred.has(cause)) open.add(cause); | |
| 53 | for (const [cause, at] of paged) | |
| 54 | if (now - at >= QUIET_MS && !current.has(cause)) paged.delete(cause); | |
| 55 | return out; | |
| 56 | } | |
| 57 | ||
| 58 | export interface ForgePager { | |
| 59 | /** Read the vitals and page what is new; resolves when sent. */ | |
| 60 | tick(): Promise<void>; | |
| 61 | stop(): void; | |
| 62 | } | |
| 63 | ||
| 64 | export interface ForgePagerOptions { | |
| 65 | /** The forge's public address; a page links to where the cause is. */ | |
| 66 | forgeUrl: string; | |
| 67 | send?: Sender; | |
| 68 | now?: () => number; | |
| 69 | /** @default 60 s; 0 starts no timer (tests call `tick`). */ | |
| 70 | tickMs?: number; | |
| 71 | } | |
| 72 | ||
| 73 | export function startForgePager( | |
| 74 | app: App, | |
| 75 | options: ForgePagerOptions, | |
| 76 | ): ForgePager { | |
| 77 | const send = options.send ?? post; | |
| 78 | const now = options.now ?? Date.now; | |
| 79 | const open = new Set<string>(); | |
| 80 | const paged = new Map<string, number>(); | |
| 81 | let running: Promise<void> = Promise.resolve(); | |
| 82 | ||
| 83 | const admins = (): string[] => | |
| 84 | app.db | |
| 85 | .query<{ user_id: string }, []>( | |
| 86 | `SELECT user_setting.user_id FROM user_setting | |
| 87 | JOIN user ON user.id = user_setting.user_id | |
| 88 | WHERE user_setting.key = 'notify_url' AND user_setting.value <> '' | |
| 89 | AND user.is_admin = 1`, | |
| 90 | ) | |
| 91 | .all() | |
| 92 | .map((r) => r.user_id); | |
| 93 | ||
| 94 | async function look(): Promise<void> { | |
| 95 | const t = now(); | |
| 96 | const fresh = causesToPage( | |
| 97 | vitals({ db: app.db, dataDir: app.config.dataDir, now: t }).degraded, | |
| 98 | open, | |
| 99 | paged, | |
| 100 | t, | |
| 101 | ); | |
| 102 | if (fresh.length === 0) return; | |
| 103 | for (const id of admins()) { | |
| 104 | const url = notifyUrlOf(app.db, id); | |
| 105 | if (url === undefined) continue; | |
| 106 | for (const d of fresh) { | |
| 107 | const to = new URL(d.href ?? "/board", options.forgeUrl).toString(); | |
| 108 | try { | |
| 109 | await send(url, `forge degraded: ${oneLine(d.sentence)}\n${to}`, { | |
| 110 | click: to, | |
| 111 | title: "forge degraded", | |
| 112 | priority: "high", | |
| 113 | }); | |
| 114 | } catch { | |
| 115 | // Dropped: the board and the home still say it. | |
| 116 | } | |
| 117 | } | |
| 118 | } | |
| 119 | } | |
| 120 | ||
| 121 | const tick = (): Promise<void> => { | |
| 122 | running = running.then(look).catch((error) => | |
| 123 | app.log.error("forge page failed", { error: String(error) }), | |
| 124 | ); | |
| 125 | return running; | |
| 126 | }; | |
| 127 | const every = options.tickMs ?? TICK_MS; | |
| 128 | const timer = every > 0 ? setInterval(() => void tick(), every) : undefined; | |
| 129 | timer?.unref(); | |
| 130 | return { | |
| 131 | tick, | |
| 132 | stop() { | |
| 133 | if (timer !== undefined) clearInterval(timer); | |
| 134 | }, | |
| 135 | }; | |
| 136 | } |
src/crew/notify.ts +2 −2
| @@ -133,7 +133,7 @@ export type Sender = ( | ||
| 133 | 133 | ) => Promise<boolean>; |
| 134 | 134 | |
| 135 | 135 | /** The real sender: the name is resolved and judged first, no redirect is followed. */ |
| 136 | const post: Sender = async (url, body, headers) => { | |
| 136 | export const post: Sender = async (url, body, headers) => { | |
| 137 | 137 | const host = new URL(url).hostname; |
| 138 | 138 | const found = await lookup(host, { all: true }); |
| 139 | 139 | if (found.length === 0 || found.some((a) => isPrivateHost(a.address))) |
| @@ -161,7 +161,7 @@ export interface NotifyOptions { | ||
| 161 | 161 | now?: () => number; |
| 162 | 162 | } |
| 163 | 163 | |
| 164 | const oneLine = (s: string): string => | |
| 164 | export const oneLine = (s: string): string => | |
| 165 | 165 | // eslint-disable-next-line no-control-regex |
| 166 | 166 | s.replace(/[\u0000-\u001f\u007f]+/g, " ").slice(0, 160); |
| 167 | 167 |
src/kernel/budgets.ts added +45
| @@ -0,0 +1,45 @@ | ||
| 1 | /** | |
| 2 | * How long each queue and run may take, written in one place. A budget is | |
| 3 | * not patience: past it is a failure, and it is said in one sentence — | |
| 4 | * `budget: <what> took <n> min, limit <m>` — by whoever finds it | |
| 5 | * (`kernel/vitals.ts` for the forge's standing, the lease sweep for a run | |
| 6 | * whose process went quiet). Plain data, no I/O. | |
| 7 | */ | |
| 8 | ||
| 9 | export const MINUTE_MS = 60_000; | |
| 10 | ||
| 11 | export interface Budget { | |
| 12 | /** What is measured, as the sentence names it. */ | |
| 13 | readonly what: string; | |
| 14 | readonly limitMs: number; | |
| 15 | } | |
| 16 | ||
| 17 | export const BUDGETS = { | |
| 18 | /** A check from start to verdict: the whole gate. */ | |
| 19 | gate: { what: "a full gate", limitMs: 15 * MINUTE_MS }, | |
| 20 | /** An agent run sent to review a pull. */ | |
| 21 | review: { what: "a review run", limitMs: 10 * MINUTE_MS }, | |
| 22 | /** The oldest check queued and not yet started. */ | |
| 23 | lane: { what: "a check waiting in the lane", limitMs: 10 * MINUTE_MS }, | |
| 24 | /** A run whose process has stopped renewing its lease (`runs/lease.ts`). */ | |
| 25 | heartbeat: { what: "a run with no heartbeat", limitMs: 3 * MINUTE_MS }, | |
| 26 | /** Any queue of runs waiting to start that is not the check lane. */ | |
| 27 | queue: { what: "a queued run", limitMs: 30 * MINUTE_MS }, | |
| 28 | /** Any run still running, however well it breathes. */ | |
| 29 | run: { what: "a run", limitMs: 6 * 60 * MINUTE_MS }, | |
| 30 | } as const satisfies Record<string, Budget>; | |
| 31 | ||
| 32 | export type BudgetName = keyof typeof BUDGETS; | |
| 33 | ||
| 34 | /** Whole minutes, never rounded up into a lie: 9.9 min is 9. */ | |
| 35 | export const minutes = (ms: number): number => Math.floor(ms / MINUTE_MS); | |
| 36 | ||
| 37 | /** Whether `tookMs` is past the named budget. */ | |
| 38 | export const pastBudget = (name: BudgetName, tookMs: number): boolean => | |
| 39 | tookMs > BUDGETS[name].limitMs; | |
| 40 | ||
| 41 | /** The one sentence a budget overrun is said in. */ | |
| 42 | export function budgetLine(name: BudgetName, tookMs: number): string { | |
| 43 | const b = BUDGETS[name]; | |
| 44 | return `budget: ${b.what} took ${minutes(tookMs)} min, limit ${minutes(b.limitMs)}`; | |
| 45 | } |
src/kernel/vitals.ts +110 −33
| @@ -4,8 +4,10 @@ | ||
| 4 | 4 | * own page (`web/pages/capacity.ts`), never here. Plain data in, |
| 5 | 5 | * plain data out — the disk under `FORGE_DATA`, this process's memory, the |
| 6 | 6 | * queue, runs that stopped making progress, and how many apps are serving, |
| 7 | * asleep or previewed. A fixed handful of queries however many runs and | |
| 8 | * apps there are; nothing is cached, nothing shelled out. | |
| 7 | * asleep or previewed. What is wrong is `degraded`: one sentence per | |
| 8 | * cause, measured against the budgets in `kernel/budgets.ts`. A fixed | |
| 9 | * handful of queries however many runs and apps there are; nothing is | |
| 10 | * cached, nothing shelled out. | |
| 9 | 11 | */ |
| 10 | 12 | |
| 11 | 13 | import type { Database } from "bun:sqlite"; |
| @@ -14,15 +16,29 @@ import { freemem, totalmem } from "node:os"; | ||
| 14 | 16 | import { recentErrors, type ErrorLine } from "./log.ts"; |
| 15 | 17 | import { leaseLapsed, listRunning, queueDepth } from "../core/runs.ts"; |
| 16 | 18 | import { STALE_AFTER_MS } from "../runs/lease.ts"; |
| 19 | import { | |
| 20 | BUDGETS, | |
| 21 | budgetLine, | |
| 22 | minutes, | |
| 23 | pastBudget, | |
| 24 | type BudgetName, | |
| 25 | } from "./budgets.ts"; | |
| 17 | 26 | |
| 18 | 27 | /** Free disk under this share of the volume is something to say. */ |
| 19 | 28 | export const DISK_FREE_MIN = 0.1; |
| 20 | 29 | /** This many error lines in an hour is a burst worth saying. */ |
| 21 | 30 | export const ERROR_BURST = 20; |
| 22 | /** A run still running this long after it started is stuck even if it breathes. */ | |
| 23 | export const NO_PROGRESS_MS = 6 * 3_600_000; | |
| 24 | /** A run that has waited this long to start is a queue that is not moving. */ | |
| 25 | export const QUEUE_WAIT_MAX_MS = 30 * 60_000; | |
| 31 | ||
| 32 | /** | |
| 33 | * One thing that is wrong, said once: `cause` is stable while it lasts (the | |
| 34 | * key a page is sent once for), `sentence` names the stuck thing and why | |
| 35 | * from the forge's own rows, and `href` is where it can be acted on. | |
| 36 | */ | |
| 37 | export interface Degraded { | |
| 38 | readonly cause: string; | |
| 39 | readonly sentence: string; | |
| 40 | readonly href?: string; | |
| 41 | } | |
| 26 | 42 | |
| 27 | 43 | export interface EnvCount { |
| 28 | 44 | readonly env: string; |
| @@ -31,7 +47,9 @@ export interface EnvCount { | ||
| 31 | 47 | |
| 32 | 48 | export interface Vitals { |
| 33 | 49 | readonly ok: boolean; |
| 50 | /** Each degraded sentence, in order: what the board and the home say. */ | |
| 34 | 51 | readonly needs: string[]; |
| 52 | readonly degraded: Degraded[]; | |
| 35 | 53 | readonly disk: { freeBytes: number; totalBytes: number }; |
| 36 | 54 | readonly memory: { |
| 37 | 55 | rssBytes: number; |
| @@ -59,9 +77,14 @@ export interface VitalsInput { | ||
| 59 | 77 | readonly now?: number; |
| 60 | 78 | } |
| 61 | 79 | |
| 80 | const plural = (n: number, one: string, many: string): string => | |
| 81 | n === 1 ? one : many; | |
| 82 | /** The minute of a timestamp, as a clock reads it. */ | |
| 83 | const clock = (iso: string): string => `${iso.slice(11, 16)} UTC`; | |
| 84 | ||
| 62 | 85 | export function vitals(input: VitalsInput): Vitals { |
| 63 | 86 | const now = input.now ?? Date.now(); |
| 64 | const needs: string[] = []; | |
| 87 | const degraded: Degraded[] = []; | |
| 65 | 88 | |
| 66 | 89 | const fs = statfsSync(input.dataDir); |
| 67 | 90 | const disk = { |
| @@ -69,34 +92,86 @@ export function vitals(input: VitalsInput): Vitals { | ||
| 69 | 92 | totalBytes: Number(fs.blocks) * Number(fs.bsize), |
| 70 | 93 | }; |
| 71 | 94 | if (disk.totalBytes > 0 && disk.freeBytes / disk.totalBytes < DISK_FREE_MIN) |
| 72 | needs.push( | |
| 73 | `Disk is nearly full: ${Math.round((disk.freeBytes / disk.totalBytes) * 100)}% free.`, | |
| 74 | ); | |
| 95 | degraded.push({ | |
| 96 | cause: "disk", | |
| 97 | sentence: `Disk is nearly full: ${Math.round((disk.freeBytes / disk.totalBytes) * 100)}% free.`, | |
| 98 | }); | |
| 75 | 99 | |
| 100 | const running = listRunning(input.db); | |
| 101 | const label = (r: (typeof running)[number]): string => | |
| 102 | r.issue === null ? `${r.repo} ${r.run.env || r.run.kind}` : `${r.repo}#${r.issue}`; | |
| 103 | const runHref = (r: (typeof running)[number]): string => | |
| 104 | `/${r.repo}/runs/${r.run.id}`; | |
| 105 | const startedAt = (r: (typeof running)[number]): string => | |
| 106 | r.run.startedAt ?? r.run.createdAt; | |
| 107 | const lanes = running.filter((r) => r.run.kind === "check"); | |
| 108 | ||
| 109 | // The check lane: what waits, since when, and what holds the lane — the | |
| 110 | // cause, never only the symptom. | |
| 76 | 111 | const queue: Record<string, number> = {}; |
| 112 | let laneSaid = false; | |
| 77 | 113 | for (const row of queueDepth(input.db, now)) { |
| 78 | 114 | queue[row.kind] = row.queued; |
| 79 | if (now - new Date(row.oldest).getTime() > QUEUE_WAIT_MAX_MS) | |
| 80 | needs.push( | |
| 81 | `The ${row.kind} queue has waited over ${QUEUE_WAIT_MAX_MS / 60_000} minutes.`, | |
| 115 | const waited = now - new Date(row.oldest).getTime(); | |
| 116 | if (row.kind === "check" && pastBudget("lane", waited)) { | |
| 117 | laneSaid = true; | |
| 118 | const limit = minutes(BUDGETS.gate.limitMs); | |
| 119 | const held = lanes.map( | |
| 120 | (r) => | |
| 121 | `${label(r)} for ${minutes(now - Date.parse(startedAt(r)))} min`, | |
| 82 | 122 | ); |
| 83 | } | |
| 84 | ||
| 85 | const stuck: Vitals["stuck"] = []; | |
| 86 | for (const { run, repo, issue } of listRunning(input.db)) { | |
| 87 | const started = new Date(run.startedAt ?? run.createdAt).getTime(); | |
| 88 | if (leaseLapsed(run, STALE_AFTER_MS, now) || now - started > NO_PROGRESS_MS) | |
| 89 | stuck.push({ | |
| 90 | runId: run.id, | |
| 91 | repo, | |
| 92 | issue, | |
| 93 | since: run.heartbeatAt ?? run.startedAt ?? run.createdAt, | |
| 123 | const cause = | |
| 124 | lanes.length === 0 | |
| 125 | ? "nothing runs in the lane" | |
| 126 | : `the ${plural(lanes.length, "lane runs", "lanes run")} ${held.join(", ")} (limit ${limit})`; | |
| 127 | const behind = | |
| 128 | lanes.length === 0 | |
| 129 | ? "an empty lane" | |
| 130 | : lanes.length === 1 | |
| 131 | ? "one lane" | |
| 132 | : `${lanes.length} lanes`; | |
| 133 | degraded.push({ | |
| 134 | cause: "lane", | |
| 135 | sentence: `${row.queued} ${plural(row.queued, "check waits", "checks wait")} behind ${behind}; the oldest since ${clock(row.oldest)}; ${cause}`, | |
| 136 | ...(lanes[0] === undefined ? {} : { href: runHref(lanes[0]) }), | |
| 137 | }); | |
| 138 | } else if (row.kind !== "check" && pastBudget("queue", waited)) | |
| 139 | degraded.push({ | |
| 140 | cause: `queue:${row.kind}`, | |
| 141 | sentence: `${budgetLine("queue", waited)} — the ${row.kind} queue holds ${row.queued}, the oldest since ${clock(row.oldest)}`, | |
| 94 | 142 | }); |
| 95 | 143 | } |
| 96 | if (stuck.length > 0) | |
| 97 | needs.push( | |
| 98 | `${stuck.length} run${stuck.length === 1 ? " is" : "s are"} stuck.`, | |
| 99 | ); | |
| 144 | ||
| 145 | // A run past its budget, or one whose process went quiet past the | |
| 146 | // heartbeat budget: the lease sweep should have ended it, and has not. | |
| 147 | const stuck: Vitals["stuck"] = []; | |
| 148 | for (const r of running) { | |
| 149 | const { run } = r; | |
| 150 | const took = now - Date.parse(startedAt(r)); | |
| 151 | if (leaseLapsed(run, STALE_AFTER_MS, now) || pastBudget("run", took)) | |
| 152 | stuck.push({ | |
| 153 | runId: run.id, | |
| 154 | repo: r.repo, | |
| 155 | issue: r.issue, | |
| 156 | since: run.heartbeatAt ?? startedAt(r), | |
| 157 | }); | |
| 158 | const silent = now - Date.parse(run.heartbeatAt ?? startedAt(r)); | |
| 159 | const over: BudgetName | undefined = pastBudget("heartbeat", silent) | |
| 160 | ? "heartbeat" | |
| 161 | : run.kind === "check" && !laneSaid && pastBudget("gate", took) | |
| 162 | ? "gate" | |
| 163 | : run.kind === "agent" && run.reason === "review" && pastBudget("review", took) | |
| 164 | ? "review" | |
| 165 | : pastBudget("run", took) | |
| 166 | ? "run" | |
| 167 | : undefined; | |
| 168 | if (over === undefined) continue; | |
| 169 | degraded.push({ | |
| 170 | cause: `${over}:${run.id}`, | |
| 171 | sentence: `${budgetLine(over, over === "heartbeat" ? silent : took)} — ${label(r)}${over === "heartbeat" ? "; the lease sweep has not ended it" : ""}`, | |
| 172 | href: runHref(r), | |
| 173 | }); | |
| 174 | } | |
| 100 | 175 | |
| 101 | 176 | const apps = { serving: 0, asleep: 0, previews: 0 }; |
| 102 | 177 | for (const e of input.envs ?? []) { |
| @@ -107,13 +182,15 @@ export function vitals(input: VitalsInput): Vitals { | ||
| 107 | 182 | |
| 108 | 183 | const seen = recentErrors(5, now); |
| 109 | 184 | if (seen.lastHour >= ERROR_BURST) |
| 110 | needs.push( | |
| 111 | `${seen.lastHour} errors in the last hour (${ERROR_BURST} or more is a burst).`, | |
| 112 | ); | |
| 185 | degraded.push({ | |
| 186 | cause: "errors", | |
| 187 | sentence: `${seen.lastHour} errors in the last hour (${ERROR_BURST} or more is a burst).`, | |
| 188 | }); | |
| 113 | 189 | |
| 114 | 190 | return { |
| 115 | ok: needs.length === 0, | |
| 116 | needs, | |
| 191 | ok: degraded.length === 0, | |
| 192 | needs: degraded.map((d) => d.sentence), | |
| 193 | degraded, | |
| 117 | 194 | disk, |
| 118 | 195 | memory: { |
| 119 | 196 | rssBytes: process.memoryUsage().rss, |
src/main.ts +4
| @@ -33,6 +33,7 @@ import { typeSafeDecider } from "./crew/decide.ts"; | ||
| 33 | 33 | import { graphInstagram } from "./crew/instagram.ts"; |
| 34 | 34 | import { peopleOnCrews } from "./core/agents.ts"; |
| 35 | 35 | import { startNotifier } from "./crew/notify.ts"; |
| 36 | import { startForgePager } from "./crew/forge_page.ts"; | |
| 36 | 37 | import { sweepStaleAsks } from "./crew/stale_asks.ts"; |
| 37 | 38 | import { recordAskLedger } from "./web/studio/asks.ts"; |
| 38 | 39 | import { startPromptRoutine } from "./crew/prompts.ts"; |
| @@ -285,6 +286,8 @@ await firstBoot(app); | ||
| 285 | 286 | const prompts = startPromptRoutine(app, { client: graphInstagram() }); |
| 286 | 287 | // What newly asks a person reaches the phone they chose (docs/APPS.md). |
| 287 | 288 | const notifier = startNotifier(app, { forgeUrl }); |
| 289 | // A degraded forge pages its admins once per cause (crew/forge_page.ts). | |
| 290 | const pager = startForgePager(app, { forgeUrl }); | |
| 288 | 291 | |
| 289 | 292 | // The webhook delivery worker: poll the outbox for due deliveries. The event |
| 290 | 293 | // row is the source of truth, so a missed tick only delays delivery, never |
| @@ -407,6 +410,7 @@ function shutdown(): void { | ||
| 407 | 410 | Promise.all([ |
| 408 | 411 | prompts.stop(), |
| 409 | 412 | notifier.stop(), |
| 413 | pager.stop(), | |
| 410 | 414 | crew?.stop({ drain: true }), |
| 411 | 415 | apps?.stop(), |
| 412 | 416 | checks?.stop(), |
src/runs/lease.ts +8 −2
| @@ -12,11 +12,17 @@ | ||
| 12 | 12 | |
| 13 | 13 | import type { Database } from "bun:sqlite"; |
| 14 | 14 | import { heartbeatRuns } from "../core/runs.ts"; |
| 15 | import { BUDGETS } from "../kernel/budgets.ts"; | |
| 15 | 16 | |
| 16 | 17 | /** How often a held lease is renewed. */ |
| 17 | 18 | export const HEARTBEAT_MS = 15_000; |
| 18 | /** How long without a renewal before a running run counts as abandoned. */ | |
| 19 | export const STALE_AFTER_MS = 90_000; | |
| 19 | /** | |
| 20 | * How long without a renewal before a running run counts as abandoned: | |
| 21 | * half the heartbeat budget (`kernel/budgets.ts`), so the sweep ends a | |
| 22 | * silent run well inside it, and a run still silent past the budget is the | |
| 23 | * sweep itself failing — which the forge's vitals say. | |
| 24 | */ | |
| 25 | export const STALE_AFTER_MS = BUDGETS.heartbeat.limitMs / 2; | |
| 20 | 26 | |
| 21 | 27 | const held = new Map<Database, Set<string>>(); |
| 22 | 28 | let timer: ReturnType<typeof setInterval> | undefined; |
src/web/pages/board.ts +6 −14
| @@ -38,7 +38,7 @@ import { readSpend } from "../../actions/spend.ts"; | ||
| 38 | 38 | import { spendView } from "./spend.ts"; |
| 39 | 39 | import { listApps } from "../../core/apps.ts"; |
| 40 | 40 | import { forgeHealth, rolloutLine } from "../../kernel/guard.ts"; |
| 41 | import { vitals, type Vitals } from "../../kernel/vitals.ts"; | |
| 41 | import { vitals } from "../../kernel/vitals.ts"; | |
| 42 | 42 | import { getIssue, getIssuesByIds, type Issue } from "../../core/issues.ts"; |
| 43 | 43 | import { looksForApps } from "../../core/looks.ts"; |
| 44 | 44 | import { |
| @@ -303,13 +303,6 @@ export function bigRedirect(ctx: Ctx): Response { | ||
| 303 | 303 | |
| 304 | 304 | // ---- the forge ---- |
| 305 | 305 | |
| 306 | /** Where a need can be acted on, when it can: a stuck run's page. */ | |
| 307 | function needHref(need: string, v: Vitals): string | undefined { | |
| 308 | if (/ stuck\.$/.test(need) && v.stuck[0] !== undefined) | |
| 309 | return `/${v.stuck[0].repo}/runs/${v.stuck[0].runId}`; | |
| 310 | return undefined; | |
| 311 | } | |
| 312 | ||
| 313 | 306 | /** |
| 314 | 307 | * The forge's health as one line, for a site admin only: *All fine*, or |
| 315 | 308 | * each thing that needs them. A live region of its own; nobody else gets |
| @@ -345,12 +338,11 @@ function forgeStrip(ctx: Ctx): Html | null { | ||
| 345 | 338 | ${ |
| 346 | 339 | ok |
| 347 | 340 | ? html`<span class="board-forge-ok">All fine</span>` |
| 348 | : v.needs.map((need) => { | |
| 349 | const href = needHref(need, v); | |
| 350 | return href === undefined | |
| 351 | ? html`<span class="board-forge-need">${need}</span>` | |
| 352 | : html`<a class="board-forge-need" href="${href}">${need}</a>`; | |
| 353 | }) | |
| 341 | : v.degraded.map(({ sentence, href }) => | |
| 342 | href === undefined | |
| 343 | ? html`<span class="board-forge-need">${sentence}</span>` | |
| 344 | : html`<a class="board-forge-need" href="${href}">${sentence}</a>`, | |
| 345 | ) | |
| 354 | 346 | } |
| 355 | 347 | </div>`; |
| 356 | 348 | } |
test/asks.test.ts +4 −2
| @@ -158,11 +158,13 @@ describe("the asks page", () => { | ||
| 158 | 158 | .query("UPDATE run SET created_at = ?1 WHERE state = 'queued'") |
| 159 | 159 | .run(new Date(Date.now() - 3 * 3_600_000).toISOString()); |
| 160 | 160 | const admin = await get(alice, "/"); |
| 161 | expect(admin).toContain("queue has waited over"); | |
| 161 | expect(admin).toContain( | |
| 162 | "1 check waits behind an empty lane; the oldest since", | |
| 163 | ); | |
| 162 | 164 | expect(sentence(admin)).toBe("2 things need you"); |
| 163 | 165 | expect(headerCount(admin)).toBe(2); |
| 164 | 166 | const other = await get(bob, "/"); |
| 165 | expect(other).not.toContain("queue has waited"); | |
| 167 | expect(other).not.toContain("behind an empty lane"); | |
| 166 | 168 | expect(sentence(other)).toBe("All fine"); |
| 167 | 169 | }); |
| 168 | 170 |
test/board.test.ts +4 −2
| @@ -447,13 +447,15 @@ describe("the board's forge strip", () => { | ||
| 447 | 447 | .run("2020-01-01T00:00:00.000Z", run.id); |
| 448 | 448 | const stuck = await board("root"); |
| 449 | 449 | expect(stuck).not.toContain("All fine"); |
| 450 | expect(stuck).toContain("1 run is stuck."); | |
| 450 | expect(stuck).toMatch( | |
| 451 | /budget: a run with no heartbeat took \d+ min, limit 3 — root\/stuck agent; the lease sweep has not ended it/, | |
| 452 | ); | |
| 451 | 453 | expect(stuck).toContain(`href="/root/stuck/runs/${run.id}"`); |
| 452 | 454 | |
| 453 | 455 | const other = await board("bob"); |
| 454 | 456 | expect(other).not.toContain('id="forge"'); |
| 455 | 457 | expect(other).not.toContain("All fine"); |
| 456 | expect(other).not.toContain("stuck."); | |
| 458 | expect(other).not.toContain("budget:"); | |
| 457 | 459 | }); |
| 458 | 460 | |
| 459 | 461 | test("a setting that is not the default is no incident: the strip stays fine and the cards render", async () => { |
test/budgets.test.ts added +195
| @@ -0,0 +1,195 @@ | ||
| 1 | /** | |
| 2 | * Budgets, not patience: a lane older than its budget turns the forge | |
| 3 | * degraded with the sentence that names its cause, a run past its heartbeat | |
| 4 | * budget is said and swept, and a degraded cause pages the phone once. | |
| 5 | */ | |
| 6 | ||
| 7 | import { afterAll, beforeAll, 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 { createRun, failAbandonedRuns, getRun } from "../src/core/runs.ts"; | |
| 13 | import { createUser, type User } from "../src/core/users.ts"; | |
| 14 | import { setNotifyUrl } from "../src/crew/notify.ts"; | |
| 15 | import { | |
| 16 | causesToPage, | |
| 17 | QUIET_MS, | |
| 18 | startForgePager, | |
| 19 | } from "../src/crew/forge_page.ts"; | |
| 20 | import { BUDGETS, budgetLine, MINUTE_MS } from "../src/kernel/budgets.ts"; | |
| 21 | import { vitals } from "../src/kernel/vitals.ts"; | |
| 22 | import { STALE_AFTER_MS } from "../src/runs/lease.ts"; | |
| 23 | ||
| 24 | let dataDir: string; | |
| 25 | let app: App; | |
| 26 | let admin: User; | |
| 27 | let repoId = ""; | |
| 28 | ||
| 29 | const at = (ms: number): string => new Date(ms).toISOString(); | |
| 30 | const clear = () => app.db.query("DELETE FROM run").run(); | |
| 31 | ||
| 32 | beforeAll(async () => { | |
| 33 | dataDir = await mkdtemp(join(tmpdir(), "forge-budgets-")); | |
| 34 | app = createApp({ dataDir, port: 0 }); | |
| 35 | const made = await createUser(app.db, { | |
| 36 | trusted: true, | |
| 37 | username: "alice", | |
| 38 | email: "[email protected]", | |
| 39 | password: "a-good-passphrase", | |
| 40 | adminIfFirst: true, | |
| 41 | }); | |
| 42 | if (!made.ok) throw new Error(made.error); | |
| 43 | admin = made.value; | |
| 44 | repoId = "repo-budgets"; | |
| 45 | app.db | |
| 46 | .query("INSERT INTO repo (id, owner_id, name) VALUES (?1, ?2, 'r')") | |
| 47 | .run(repoId, admin.id); | |
| 48 | }); | |
| 49 | ||
| 50 | afterAll(async () => { | |
| 51 | app.close(); | |
| 52 | await rm(dataDir, { recursive: true, force: true }); | |
| 53 | }); | |
| 54 | ||
| 55 | test("a budget overrun is one sentence", () => { | |
| 56 | expect(budgetLine("gate", 31 * MINUTE_MS + 59_000)).toBe( | |
| 57 | "budget: a full gate took 31 min, limit 15", | |
| 58 | ); | |
| 59 | expect(STALE_AFTER_MS).toBeLessThan(BUDGETS.heartbeat.limitMs); | |
| 60 | }); | |
| 61 | ||
| 62 | test("a lane older than its budget turns the forge degraded, naming what holds it", () => { | |
| 63 | clear(); | |
| 64 | const now = Date.parse("2026-10-13T05:00:00.000Z"); | |
| 65 | const lane = createRun(app.db, { repoId, kind: "check", env: "pull-1212" }); | |
| 66 | app.db | |
| 67 | .query( | |
| 68 | "UPDATE run SET state='running', created_at=?2, started_at=?2, heartbeat_at=?3 WHERE id=?1", | |
| 69 | ) | |
| 70 | .run(lane.id, at(now - 31 * MINUTE_MS), at(now - 5_000)); | |
| 71 | for (const [i, minutesAgo] of [47, 20, 2].entries()) { | |
| 72 | const r = createRun(app.db, { repoId, kind: "check", env: `pull-${i}` }); | |
| 73 | app.db | |
| 74 | .query("UPDATE run SET created_at=?2 WHERE id=?1") | |
| 75 | .run(r.id, at(now - minutesAgo * MINUTE_MS)); | |
| 76 | } | |
| 77 | const v = vitals({ db: app.db, dataDir, now }); | |
| 78 | expect(v.ok).toBe(false); | |
| 79 | expect(v.degraded).toEqual([ | |
| 80 | { | |
| 81 | cause: "lane", | |
| 82 | sentence: | |
| 83 | "3 checks wait behind one lane; the oldest since 04:13 UTC; the lane runs alice/r pull-1212 for 31 min (limit 15)", | |
| 84 | href: `/alice/r/runs/${lane.id}`, | |
| 85 | }, | |
| 86 | ]); | |
| 87 | expect(v.needs).toEqual([v.degraded[0]!.sentence]); | |
| 88 | ||
| 89 | // Inside its budget, a lane is fine — however long the gate has run. | |
| 90 | const early = vitals({ db: app.db, dataDir, now: now - 40 * MINUTE_MS }); | |
| 91 | expect(early.degraded.map((d) => d.cause)).toEqual([]); | |
| 92 | }); | |
| 93 | ||
| 94 | test("a lane nobody works says so, rather than how long it waited", () => { | |
| 95 | clear(); | |
| 96 | const now = Date.parse("2026-10-13T15:46:00.000Z"); | |
| 97 | const r = createRun(app.db, { repoId, kind: "check", env: "pull-1269" }); | |
| 98 | app.db | |
| 99 | .query("UPDATE run SET created_at=?2 WHERE id=?1") | |
| 100 | .run(r.id, at(now - 3 * 60 * MINUTE_MS)); | |
| 101 | expect(vitals({ db: app.db, dataDir, now }).needs).toEqual([ | |
| 102 | "1 check waits behind an empty lane; the oldest since 12:46 UTC; nothing runs in the lane", | |
| 103 | ]); | |
| 104 | }); | |
| 105 | ||
| 106 | test("a gate past its budget with nothing waiting is still said", () => { | |
| 107 | clear(); | |
| 108 | const now = Date.now(); | |
| 109 | const r = createRun(app.db, { repoId, kind: "check", env: "main" }); | |
| 110 | app.db | |
| 111 | .query( | |
| 112 | "UPDATE run SET state='running', started_at=?2, heartbeat_at=?3 WHERE id=?1", | |
| 113 | ) | |
| 114 | .run(r.id, at(now - 45 * MINUTE_MS), at(now)); | |
| 115 | expect(vitals({ db: app.db, dataDir, now }).degraded).toEqual([ | |
| 116 | { | |
| 117 | cause: `gate:${r.id}`, | |
| 118 | sentence: "budget: a full gate took 45 min, limit 15 — alice/r main", | |
| 119 | href: `/alice/r/runs/${r.id}`, | |
| 120 | }, | |
| 121 | ]); | |
| 122 | }); | |
| 123 | ||
| 124 | test("a run past its heartbeat budget is said, and the sweep ends it", () => { | |
| 125 | clear(); | |
| 126 | const now = Date.now(); | |
| 127 | const r = createRun(app.db, { repoId, kind: "deploy", env: "production" }); | |
| 128 | app.db | |
| 129 | .query( | |
| 130 | "UPDATE run SET state='running', started_at=?2, heartbeat_at=?2 WHERE id=?1", | |
| 131 | ) | |
| 132 | .run(r.id, at(now - 4 * MINUTE_MS)); | |
| 133 | expect(vitals({ db: app.db, dataDir, now }).needs).toEqual([ | |
| 134 | "budget: a run with no heartbeat took 4 min, limit 3 — alice/r production; the lease sweep has not ended it", | |
| 135 | ]); | |
| 136 | expect(failAbandonedRuns(app.db, STALE_AFTER_MS, ["deploy"])).toBe(1); | |
| 137 | expect(getRun(app.db, r.id)!.state).toBe("failed"); | |
| 138 | expect(vitals({ db: app.db, dataDir, now }).ok).toBe(true); | |
| 139 | }); | |
| 140 | ||
| 141 | test("a cause pages once, and stays quiet for an hour after it clears", () => { | |
| 142 | const open = new Set<string>(); | |
| 143 | const paged = new Map<string, number>(); | |
| 144 | const lane = { cause: "lane", sentence: "lane" }; | |
| 145 | expect(causesToPage([lane], open, paged, 0)).toEqual([lane]); | |
| 146 | expect(causesToPage([lane], open, paged, 60_000)).toEqual([]); | |
| 147 | expect(causesToPage([], open, paged, 120_000)).toEqual([]); | |
| 148 | // Back within the quiet hour: still quiet. | |
| 149 | expect(causesToPage([lane], open, paged, 30 * MINUTE_MS)).toEqual([]); | |
| 150 | expect(causesToPage([], open, paged, 40 * MINUTE_MS)).toEqual([]); | |
| 151 | // Back after it: news again. | |
| 152 | expect(causesToPage([lane], open, paged, QUIET_MS + 1)).toEqual([lane]); | |
| 153 | }); | |
| 154 | ||
| 155 | test("causes past one look's share are paged on the next look", () => { | |
| 156 | const open = new Set<string>(); | |
| 157 | const paged = new Map<string, number>(); | |
| 158 | const causes = ["a", "b", "c", "d"].map((c) => ({ cause: c, sentence: c })); | |
| 159 | expect(causesToPage(causes, open, paged, 0)).toEqual(causes.slice(0, 3)); | |
| 160 | expect(causesToPage(causes, open, paged, 60_000)).toEqual([causes[3]!]); | |
| 161 | expect(causesToPage(causes, open, paged, 120_000)).toEqual([]); | |
| 162 | }); | |
| 163 | ||
| 164 | test("a degraded forge pages its admin's phone once per cause", async () => { | |
| 165 | clear(); | |
| 166 | const set = setNotifyUrl(app.db, admin.id, "https://ntfy.example.test/topic"); | |
| 167 | expect(set.ok).toBe(true); | |
| 168 | const posts: { url: string; body: string }[] = []; | |
| 169 | let clock = Date.now(); | |
| 170 | const pager = startForgePager(app, { | |
| 171 | forgeUrl: "https://forge.example.test", | |
| 172 | send: async (url, body) => (posts.push({ url, body }), true), | |
| 173 | now: () => clock, | |
| 174 | tickMs: 0, | |
| 175 | }); | |
| 176 | try { | |
| 177 | await pager.tick(); | |
| 178 | expect(posts).toEqual([]); | |
| 179 | const r = createRun(app.db, { repoId, kind: "check", env: "pull-9" }); | |
| 180 | app.db | |
| 181 | .query("UPDATE run SET created_at=?2 WHERE id=?1") | |
| 182 | .run(r.id, at(clock - 20 * MINUTE_MS)); | |
| 183 | await pager.tick(); | |
| 184 | clock += 60_000; | |
| 185 | await pager.tick(); | |
| 186 | expect(posts.length).toBe(1); | |
| 187 | expect(posts[0]!.url).toBe("https://ntfy.example.test/topic"); | |
| 188 | expect(posts[0]!.body).toContain( | |
| 189 | "forge degraded: 1 check waits behind an empty lane;", | |
| 190 | ); | |
| 191 | expect(posts[0]!.body).toContain("https://forge.example.test/board"); | |
| 192 | } finally { | |
| 193 | pager.stop(); | |
| 194 | } | |
| 195 | }); |
test/vitals.test.ts +7 −2
| @@ -80,7 +80,7 @@ test("a site admin with a read-only token gets the shape; others get the short o | ||
| 80 | 80 | const v = (await res.json()) as Record<string, any>; |
| 81 | 81 | expect(Object.keys(v).sort()).toEqual( |
| 82 | 82 | [ |
| 83 | "apps", "at", "checkedAt", "commit", "disk", "draining", "errors", | |
| 83 | "apps", "at", "checkedAt", "commit", "degraded", "disk", "draining", "errors", | |
| 84 | 84 | "incidents", "memory", "needs", "ok", "queue", "rollout", "stale", "stuck", |
| 85 | 85 | "version", |
| 86 | 86 | ].sort(), |
| @@ -121,7 +121,12 @@ test("a running run with a lapsed lease is stuck, and needs says so", async () = | ||
| 121 | 121 | expect(v.stuck.map((s) => s.runId)).toEqual([run.id]); |
| 122 | 122 | expect(v.stuck[0]!.repo).toBe("alice/r"); |
| 123 | 123 | expect(v.ok).toBe(false); |
| 124 | expect(v.needs.some((n) => n.includes("stuck"))).toBe(true); | |
| 124 | expect(v.needs).toContain( | |
| 125 | "budget: a run with no heartbeat took 10 min, limit 3 — alice/r production; the lease sweep has not ended it", | |
| 126 | ); | |
| 127 | expect(v.degraded.find((d) => d.cause === `heartbeat:${run.id}`)?.href).toBe( | |
| 128 | `/alice/r/runs/${run.id}`, | |
| 129 | ); | |
| 125 | 130 | // A fresh heartbeat clears it. |
| 126 | 131 | app.db |
| 127 | 132 | .query("UPDATE run SET heartbeat_at=?2 WHERE id=?1") |
new above
offline