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

Closed opened this in answer to
Closed without merging

mason/forge:mason/1270-fail-fast-fail-loud-every-queue-and-run → main 3 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
13 files changed +528 −59
CLAUDE.md +6 −2
@@ -112,7 +112,9 @@ src/
112112 app.ts composition root — one data dir = one forge (dataDir is resolved
113113 absolute here; the hook socket depends on it)
114114 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)
116118 git/ env (runGit*), read (cat-file batch readers), diff, merge (bare
117119 plumbing, no work tree), write (commit via plumbing, deletes as
118120 index-info mode 0, a `land` hook so an origin answers first),
@@ -192,7 +194,9 @@ src/
192194 may reach and read), workdir (where clones live), runner (one
193195 run: token, clone, branch, Claude, push, open/update the pull,
194196 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)
196200 design/ themes, and activity (what an event is called, for both
197201 surfaces)
198202 ```
scripts/gate.ts +1
@@ -108,6 +108,7 @@ export const GATE: readonly string[] = [
108108 "test/schema-additive.test.ts",
109109 "test/schema-migrations.test.ts",
110110 "test/vitals.test.ts",
111 "test/budgets.test.ts",
111112 "test/version.test.ts",
112113 "test/watches.test.ts",
113114 "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 = (
133133 ) => Promise<boolean>;
134134
135135 /** 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) => {
137137 const host = new URL(url).hostname;
138138 const found = await lookup(host, { all: true });
139139 if (found.length === 0 || found.some((a) => isPrivateHost(a.address)))
@@ -161,7 +161,7 @@ export interface NotifyOptions {
161161 now?: () => number;
162162 }
163163
164 const oneLine = (s: string): string =>
164 export const oneLine = (s: string): string =>
165165 // eslint-disable-next-line no-control-regex
166166 s.replace(/[\u0000-\u001f\u007f]+/g, " ").slice(0, 160);
167167
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 @@
44 * own page (`web/pages/capacity.ts`), never here. Plain data in,
55 * plain data out — the disk under `FORGE_DATA`, this process's memory, the
66 * 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.
911 */
1012
1113 import type { Database } from "bun:sqlite";
@@ -14,15 +16,29 @@ import { freemem, totalmem } from "node:os";
1416 import { recentErrors, type ErrorLine } from "./log.ts";
1517 import { leaseLapsed, listRunning, queueDepth } from "../core/runs.ts";
1618 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";
1726
1827 /** Free disk under this share of the volume is something to say. */
1928 export const DISK_FREE_MIN = 0.1;
2029 /** This many error lines in an hour is a burst worth saying. */
2130 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 }
2642
2743 export interface EnvCount {
2844 readonly env: string;
@@ -31,7 +47,9 @@ export interface EnvCount {
3147
3248 export interface Vitals {
3349 readonly ok: boolean;
50 /** Each degraded sentence, in order: what the board and the home say. */
3451 readonly needs: string[];
52 readonly degraded: Degraded[];
3553 readonly disk: { freeBytes: number; totalBytes: number };
3654 readonly memory: {
3755 rssBytes: number;
@@ -59,9 +77,14 @@ export interface VitalsInput {
5977 readonly now?: number;
6078 }
6179
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
6285 export function vitals(input: VitalsInput): Vitals {
6386 const now = input.now ?? Date.now();
64 const needs: string[] = [];
87 const degraded: Degraded[] = [];
6588
6689 const fs = statfsSync(input.dataDir);
6790 const disk = {
@@ -69,34 +92,86 @@ export function vitals(input: VitalsInput): Vitals {
6992 totalBytes: Number(fs.blocks) * Number(fs.bsize),
7093 };
7194 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 });
7599
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.
76111 const queue: Record<string, number> = {};
112 let laneSaid = false;
77113 for (const row of queueDepth(input.db, now)) {
78114 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`,
82122 );
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)}`,
94142 });
95143 }
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 }
100175
101176 const apps = { serving: 0, asleep: 0, previews: 0 };
102177 for (const e of input.envs ?? []) {
@@ -107,13 +182,15 @@ export function vitals(input: VitalsInput): Vitals {
107182
108183 const seen = recentErrors(5, now);
109184 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 });
113189
114190 return {
115 ok: needs.length === 0,
116 needs,
191 ok: degraded.length === 0,
192 needs: degraded.map((d) => d.sentence),
193 degraded,
117194 disk,
118195 memory: {
119196 rssBytes: process.memoryUsage().rss,
src/main.ts +4
@@ -33,6 +33,7 @@ import { typeSafeDecider } from "./crew/decide.ts";
3333 import { graphInstagram } from "./crew/instagram.ts";
3434 import { peopleOnCrews } from "./core/agents.ts";
3535 import { startNotifier } from "./crew/notify.ts";
36 import { startForgePager } from "./crew/forge_page.ts";
3637 import { sweepStaleAsks } from "./crew/stale_asks.ts";
3738 import { recordAskLedger } from "./web/studio/asks.ts";
3839 import { startPromptRoutine } from "./crew/prompts.ts";
@@ -285,6 +286,8 @@ await firstBoot(app);
285286 const prompts = startPromptRoutine(app, { client: graphInstagram() });
286287 // What newly asks a person reaches the phone they chose (docs/APPS.md).
287288 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 });
288291
289292 // The webhook delivery worker: poll the outbox for due deliveries. The event
290293 // row is the source of truth, so a missed tick only delays delivery, never
@@ -407,6 +410,7 @@ function shutdown(): void {
407410 Promise.all([
408411 prompts.stop(),
409412 notifier.stop(),
413 pager.stop(),
410414 crew?.stop({ drain: true }),
411415 apps?.stop(),
412416 checks?.stop(),
src/runs/lease.ts +8 −2
@@ -12,11 +12,17 @@
1212
1313 import type { Database } from "bun:sqlite";
1414 import { heartbeatRuns } from "../core/runs.ts";
15 import { BUDGETS } from "../kernel/budgets.ts";
1516
1617 /** How often a held lease is renewed. */
1718 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;
2026
2127 const held = new Map<Database, Set<string>>();
2228 let timer: ReturnType<typeof setInterval> | undefined;
src/web/pages/board.ts +6 −14
@@ -38,7 +38,7 @@ import { readSpend } from "../../actions/spend.ts";
3838 import { spendView } from "./spend.ts";
3939 import { listApps } from "../../core/apps.ts";
4040 import { forgeHealth, rolloutLine } from "../../kernel/guard.ts";
41 import { vitals, type Vitals } from "../../kernel/vitals.ts";
41 import { vitals } from "../../kernel/vitals.ts";
4242 import { getIssue, getIssuesByIds, type Issue } from "../../core/issues.ts";
4343 import { looksForApps } from "../../core/looks.ts";
4444 import {
@@ -303,13 +303,6 @@ export function bigRedirect(ctx: Ctx): Response {
303303
304304 // ---- the forge ----
305305
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
313306 /**
314307 * The forge's health as one line, for a site admin only: *All fine*, or
315308 * each thing that needs them. A live region of its own; nobody else gets
@@ -345,12 +338,11 @@ function forgeStrip(ctx: Ctx): Html | null {
345338 ${
346339 ok
347340 ? 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 )
354346 }
355347 </div>`;
356348 }
test/asks.test.ts +4 −2
@@ -158,11 +158,13 @@ describe("the asks page", () => {
158158 .query("UPDATE run SET created_at = ?1 WHERE state = 'queued'")
159159 .run(new Date(Date.now() - 3 * 3_600_000).toISOString());
160160 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 );
162164 expect(sentence(admin)).toBe("2 things need you");
163165 expect(headerCount(admin)).toBe(2);
164166 const other = await get(bob, "/");
165 expect(other).not.toContain("queue has waited");
167 expect(other).not.toContain("behind an empty lane");
166168 expect(sentence(other)).toBe("All fine");
167169 });
168170
test/board.test.ts +4 −2
@@ -447,13 +447,15 @@ describe("the board's forge strip", () => {
447447 .run("2020-01-01T00:00:00.000Z", run.id);
448448 const stuck = await board("root");
449449 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 );
451453 expect(stuck).toContain(`href="/root/stuck/runs/${run.id}"`);
452454
453455 const other = await board("bob");
454456 expect(other).not.toContain('id="forge"');
455457 expect(other).not.toContain("All fine");
456 expect(other).not.toContain("stuck.");
458 expect(other).not.toContain("budget:");
457459 });
458460
459461 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
8080 const v = (await res.json()) as Record<string, any>;
8181 expect(Object.keys(v).sort()).toEqual(
8282 [
83 "apps", "at", "checkedAt", "commit", "disk", "draining", "errors",
83 "apps", "at", "checkedAt", "commit", "degraded", "disk", "draining", "errors",
8484 "incidents", "memory", "needs", "ok", "queue", "rollout", "stale", "stuck",
8585 "version",
8686 ].sort(),
@@ -121,7 +121,12 @@ test("a running run with a lapsed lease is stuck, and needs says so", async () =
121121 expect(v.stuck.map((s) => s.runId)).toEqual([run.id]);
122122 expect(v.stuck[0]!.repo).toBe("alice/r");
123123 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 );
125130 // A fresh heartbeat clears it.
126131 app.db
127132 .query("UPDATE run SET heartbeat_at=?2 WHERE id=?1")

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs