Public: anyone can read this; the crew can change it.

A red domain drill, or a drillable domain with none in eight days, is one need in vitals #2013

Parked opened this
Closed without merging

scout/forge:scout/1854-a-red-domain-drill-or-a-drillable-domain → main 13 commits fork 2 threads · 2 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
13 files changed +357 −9
README.md +1 −1

Diff not shown — a line 3,133 characters wide (limit 2,000). +1 −1

View file
scripts/gate.ts +2
@@ -188,6 +188,8 @@ export const GATE: readonly string[] = [
188188 "test/snapshot-drill.test.ts",
189189 "test/drill-verdict.test.ts",
190190 "test/drill-board-line.test.ts",
191 "test/domain-drill-need.test.ts",
192 "test/domain-drill-door.test.ts",
191193 "test/snapshot-drill-page.test.ts",
192194 "test/snapshot-store.test.ts",
193195 "test/migrate.test.ts",
src/core/domain_drills.ts +15 −1
@@ -1,8 +1,9 @@
11 /** Every domain drill's result, kept with its verdict (`kernel/domain_drill.ts`). */
22
33 import type { Database } from "bun:sqlite";
4 import { DOMAINS } from "../kernel/domains.ts";
45 import { id } from "../kernel/id.ts";
5 import type { Observed, Verdict } from "../kernel/domain_drill.ts";
6 import type { LastDrill, Observed, Verdict } from "../kernel/domain_drill.ts";
67
78 export interface DrillRecord extends Verdict {
89 readonly id: string;
@@ -25,3 +26,16 @@ export function recordDrill(
2526 ).run(row, domain, by, seen.health, seen.board, backSeconds, verdict.green ? 1 : 0, verdict.why);
2627 return { id: row, domain, backSeconds, ...verdict };
2728 }
29
30 /** Each domain's newest drill, by domain key; the later row wins a shared second. */
31 export function lastDrills(db: Database): Map<string, LastDrill> {
32 const newest = db.query<{ green: number; why: string; at: string }, [string]>(
33 `SELECT green, why, at FROM domain_drill WHERE domain = ?1 ORDER BY at DESC, rowid DESC LIMIT 1`,
34 );
35 const out = new Map<string, LastDrill>();
36 for (const { key } of DOMAINS) {
37 const r = newest.get(key);
38 if (r) out.set(key, { domain: key, green: r.green === 1, why: r.why, at: r.at });
39 }
40 return out;
41 }
src/http/api.ts +14 −2
@@ -13,8 +13,8 @@ import { parentForgeFor } from "../core/parent_releases.ts";
1313 import { readFlow } from "../flow/read.ts";
1414 import { deleteBoard, listAllBoards, showBoard, writeBoard, type BoardError } from "../actions/boards.ts";
1515 import { runQuery } from "../boards/query.ts";
16 import { recordDrill } from "../core/domain_drills.ts";
17 import { drillVerdict } from "../kernel/domain_drill.ts";
16 import { lastDrills, recordDrill } from "../core/domain_drills.ts";
17 import { drillableDomains, drillVerdict } from "../kernel/domain_drill.ts";
1818 import { DOMAINS } from "../kernel/domains.ts";
1919 import { SOURCES } from "../boards/sources.ts";
2020 import { bodyCapFor, readBounded } from "./limits.ts";
@@ -1316,6 +1316,18 @@ export function apiRoutes(router: Router<Handler>): void {
13161316 return json(recordDrill(ctx.app.db, ctx.auth.user!.id, domain.key, observed, back, verdict), 201);
13171317 });
13181318
1319 router.add("GET", "/api/v1/drills", (ctx) => {
1320 const denied = boardsAdmin(ctx) ?? requireAccount(ctx, { adminToken: true });
1321 if (denied) return denied;
1322 const last = lastDrills(ctx.app.db);
1323 return json({
1324 drills: drillableDomains(DOMAINS).map((d) => ({
1325 domain: d.key,
1326 last: last.get(d.key) ?? null,
1327 })),
1328 });
1329 });
1330
13191331 router.add("POST", "/api/v1/boards/query", async (ctx) => {
13201332 const denied = boardsAdmin(ctx) ?? requireAccount(ctx, { adminToken: true });
13211333 if (denied) return denied;
src/kernel/domain_drill.ts +56
@@ -37,3 +37,59 @@ export function drillVerdict(
3737 }
3838 return { green: true, why: `every phrase seen; back in ${backSeconds}s of ${limit}s` };
3939 }
40
41 /** A domain with no drill in this long, or whose last drill is red, is one need. */
42 export const DOMAIN_DRILL_STALE_MS = 8 * 24 * 3_600_000;
43
44 export interface LastDrill {
45 readonly domain: string;
46 readonly green: boolean;
47 readonly why: string;
48 readonly at: string;
49 }
50
51 export interface DomainDrillNeed {
52 readonly domain: Domain;
53 readonly sentence: string;
54 readonly since: string | undefined;
55 }
56
57 /** The domains a drill can be kept for: all but the undrillable and the snapshot store (the restore drill's). */
58 export function drillableDomains(domains: readonly Domain[]): Domain[] {
59 return domains.filter((d) => d.drill.name !== null && d.key !== "snapshots");
60 }
61
62 /**
63 * The needs the domain drills owe the board: one per drillable domain whose
64 * last drill is red (naming the failing phrase), or with none in eight days.
outdated

Low (clean): this file now has two doc comments in a row. The domainDrillNeeds docblock above ends up attached to drillableDomains, and domainDrillNeeds has no doc of its own. Fix: move the long docblock down so it sits directly above export function domainDrillNeeds.

65 * The snapshot store is left to the restore drill's own line. A domain never
66 * drilled owes nothing: no page or terminal can run a domain drill yet
67 * (#1195), so a need for one could never be cleared by the owner.
68 */
69 export function domainDrillNeeds(
70 domains: readonly Domain[],
71 last: ReadonlyMap<string, LastDrill>,
72 now: number,
73 ): DomainDrillNeed[] {
74 const out: DomainDrillNeed[] = [];
75 for (const domain of drillableDomains(domains)) {
76 const d = last.get(domain.key);
77 if (d !== undefined && !d.green) {
78 out.push({
79 domain,
80 sentence: `The ${domain.key} drill failed: ${d.why}.`,
81 since: d.at,
82 });
83 continue;
84 }
85 if (d === undefined) continue;
86 const began = Date.parse(d.at);
87 if (!(now - began > DOMAIN_DRILL_STALE_MS)) continue;
88 out.push({
89 domain,
90 sentence: `The ${domain.key} drill has not run in ${DOMAIN_DRILL_STALE_MS / 86_400_000} days; the last one passed on ${d.at.slice(0, 10)}.`,
91 since: new Date(began + DOMAIN_DRILL_STALE_MS).toISOString(),
92 });
93 }
94 return out;
95 }
src/kernel/vitals.ts +13
@@ -22,6 +22,9 @@ import {
2222 import { STALE_AFTER_MS } from "../runs/lease.ts";
2323 import { BUDGETS } from "./budgets.ts";
2424 import { drillNeed, firstSeen as drillFirstSeen, lastVerdict } from "../snapshot/verdict.ts";
25 import { DOMAINS, type Domain } from "./domains.ts";
26 import { domainDrillNeeds } from "./domain_drill.ts";
27 import { lastDrills } from "../core/domain_drills.ts";
2528 import { heldChecks, redSentence } from "../checks/red_main.ts";
2629
2730 /** Free disk under this share of the volume is something to say. */
@@ -94,6 +97,8 @@ export interface VitalsInput {
9497 /** Every environment the runtime holds, when one is up. */
9598 readonly envs?: readonly EnvCount[];
9699 readonly now?: number;
100 /** The failure domains whose drills are owed; `DOMAINS` unless a test says. */
101 readonly domains?: readonly Domain[];
97102 /** The free-disk share below which the disk is a need; `DISK_FREE_MIN` unless a test says. */
98103 readonly diskFreeMin?: number;
99104 /** One forge's own signals (`App.signals`). */
@@ -318,6 +323,14 @@ export function vitals(input: VitalsInput): Vitals {
318323 if (owed !== undefined)
319324 need("drill", owed.sentence, owed.since, "/settings/backups");
320325
326 // A red domain drill, or none in eight days, is a card per domain until one passes.
327 for (const owed of domainDrillNeeds(
328 input.domains ?? DOMAINS,
329 lastDrills(input.db),
330 now,
331 ))
332 need(`drill:${owed.domain.key}`, owed.sentence, owed.since, `/settings/backups#drill-${owed.domain.key}`);
outdated

Low (tap-through): the need links to /settings/backups. When there are snapshots, the Domain drills section comes after the whole snapshot list. Fix: link to /settings/backups#drill-${owed.domain.key} (or #domain-drills) so the tap lands on the row it is about.

333
321334 const apps = { serving: 0, asleep: 0, previews: 0 };
322335 for (const e of input.envs ?? []) {
323336 if (e.env !== "production") apps.previews++;
src/tui/forge.ts +9
@@ -38,6 +38,7 @@ import { pullScreen } from "./screens/pull.ts";
3838 import { blobScreen } from "./screens/repo.ts";
3939 import { dashboardScreen } from "./screens/dashboard.ts";
4040 import { accessScreen } from "./screens/access.ts";
41 import { domainDrillLines, domainDrillsScreen } from "./screens/domain_drills.ts";
4142 import { flowLines, flowScreen } from "./screens/flow.ts";
4243 import { stalledScreen } from "./screens/stalled.ts";
4344 import { issuesScreen, newIssueScreen } from "./screens/issues.ts";
@@ -223,6 +224,14 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] {
223224 hint: "the pipeline's bottleneck and throughput",
224225 run: () => ctx.push(flowScreen(ctx, flowLines(session.db))),
225226 });
227 // The newest kept drill of each failure domain, as Settings → Backups says it: a site admin's (#1854).
228 if (session.user?.isAdmin === true)
229 commands.push({
230 id: "domain-drills",
231 title: "Domain drills",
232 hint: "each failure domain's last drill and its verdict",
233 run: () => ctx.push(domainDrillsScreen(ctx, domainDrillLines(session.db))),
234 });
226235 // Stalled flow steps the viewer can unblock, as the home's cards show them (#1807).
227236 if (session.signedIn)
228237 commands.push({
src/tui/screens/domain_drills.ts added +53
@@ -0,0 +1,53 @@
1 /**
2 * The domain drills in the terminal, a forge admin's: each drillable
3 * domain's newest kept drill and its verdict, the list Settings → Backups
4 * shows and the board's drill need points at. Read-only; Enter, Esc or q
5 * closes it.
6 */
7
8 import type { Database } from "bun:sqlite";
9 import { lastDrills } from "../../core/domain_drills.ts";
10 import { drillableDomains } from "../../kernel/domain_drill.ts";
11 import { DOMAINS } from "../../kernel/domains.ts";
12 import type { Ctx, Screen } from "../app/app.ts";
13 import { binding } from "../app/keys.ts";
14 import { wrap } from "../term/width.ts";
15 import { dialog } from "../ui/widgets.ts";
16
17 const WIDTH = 72;
18
19 /** One wrapped entry per drillable domain: green, red with its why, or never drilled. */
20 export function domainDrillLines(db: Database): string[] {
21 const last = lastDrills(db);
22 return drillableDomains(DOMAINS).flatMap((d) => {
23 const l = last.get(d.key);
24 const says =
25 l === undefined
26 ? "never drilled"
27 : l.green
28 ? `green, ${l.at.slice(0, 10)}`
29 : `red, ${l.at.slice(0, 10)}: ${l.why}`;
30 return wrap(`${d.key}: ${says}`, WIDTH - 6);
31 });
32 }
33
34 export function domainDrillsScreen(ctx: Ctx, lines: readonly string[]): Screen {
35 return {
36 title: "Domain drills",
37 keys: [binding(["enter", "esc", "q"], "close")],
38 render(area, s) {
39 const buttons = dialog(s, area, ctx.theme.c, {
40 title: "Domain drills",
41 body: lines,
42 actions: [{ label: "Close" }],
43 selected: 0,
44 width: WIDTH,
45 });
46 buttons.forEach((rect) => ctx.hit(rect, () => ctx.pop()));
47 },
48 key(e) {
49 if (e.key === "enter" || e.key === "esc" || e.key === "q") ctx.pop();
50 return true;
51 },
52 };
53 }
src/web/pages/backups.ts +25 −2
@@ -16,6 +16,9 @@ import {
1616 } from "../../actions/destination.ts";
1717 import { resolveDestination, sealedSet } from "../../snapshot/destination.ts";
1818 import { keyOf } from "../../snapshot/snapshot.ts";
19 import { lastDrills } from "../../core/domain_drills.ts";
20 import { drillableDomains } from "../../kernel/domain_drill.ts";
21 import { DOMAINS } from "../../kernel/domains.ts";
1922 import { lastDrill } from "../../snapshot/drills.ts";
2023 import { snapshotsOf } from "../../snapshot/service.ts";
2124 import type { Ctx } from "../../http/context.ts";
@@ -111,6 +114,26 @@ function drillLine(ctx: Ctx): Html {
111114 </form>`;
112115 }
113116
117 /** The last drill of each drillable domain and its verdict: where a drill need on the board lands. */
118 function domainDrills(ctx: Ctx): Html {
119 const last = lastDrills(ctx.app.db);
120 const rows = drillableDomains(DOMAINS).map((d) => {
121 const l = last.get(d.key);
122 const verdict =
123 l === undefined
124 ? html`never drilled`
125 : l.green
126 ? html`${icon("check")} green ${time(l.at)}`
127 : html`${icon("alert")} red ${time(l.at)}: ${l.why}`;
128 return html`<li id="drill-${d.key}"><strong>${d.name}</strong>: ${verdict}</li>`;
129 });
130 return html`<section class="backups-domains" id="domain-drills">
131 <h2>Domain drills</h2>
132 <ul>${rows}</ul>
133 <p>A drill is kept by an admin with <code>POST /api/v1/drills</code>; <code>GET /api/v1/drills</code> reads the same list.</p>
134 </section>`;
135 }
136
114137 export async function backupsPage(ctx: Ctx): Promise<Response> {
115138 const denied = requireAdmin(ctx);
116139 if (denied) return denied;
@@ -123,7 +146,7 @@ export async function backupsPage(ctx: Ctx): Promise<Response> {
123146 icon: "download",
124147 title: "No snapshots are taken",
125148 note: "This forge was given nowhere to put them. On the platform an app's bucket (S3_*) is the place; on a machine, FORGE_SNAPSHOT_DIR names a directory. Seal a bucket below, or restart with one set, and a snapshot is taken every night at 08:00 UTC.",
126 })}${form}`,
149 })}${form}${domainDrills(ctx)}`,
127150 );
128151 // The store is somewhere else; a listing that fails is a sentence on the
129152 // page, never a page that fails.
@@ -231,7 +254,7 @@ bun run src/snapshot/restore.ts ${snapshots[0].name} /path/to/empty/data</pre>`
231254 },
232255 )
233256 }
234 ${form}`,
257 ${domainDrills(ctx)}${form}`,
235258 svc.progress() !== undefined,
236259 );
237260 }
test/domain-drill-door.test.ts added +100
@@ -0,0 +1,100 @@
1 /** The domain drills are readable: the newest per domain wins a shared second; the Backups page and GET /api/v1/drills list them. */
2 import { afterAll, beforeAll, beforeEach, describe, expect, test } from "bun:test";
3 import { mkdtempSync } from "node:fs";
4 import { rm } from "node:fs/promises";
5 import { tmpdir } from "node:os";
6 import { join } from "node:path";
7 import { createApp, type App } from "../src/app.ts";
8 import { lastDrills } from "../src/core/domain_drills.ts";
9 import { createUser } from "../src/core/users.ts";
10 import { serve, type Servers } from "../src/http/server.ts";
11 import { drillableDomains } from "../src/kernel/domain_drill.ts";
12 import { DOMAINS } from "../src/kernel/domains.ts";
13 import { domainDrillLines } from "../src/tui/screens/domain_drills.ts";
14 import { quietLogs } from "./helpers/globals.ts";
15
16 quietLogs();
17
18 describe("reading domain drills", () => {
19 let root: string;
20 let app: App;
21 let servers: Servers;
22 let cookie = "";
23 const at = "2026-10-01T00:00:00.000Z";
24 const insert = (id: string, domain: string, green: boolean, why: string) =>
25 app.db
26 .query(
27 `INSERT INTO domain_drill (id, domain, run_by, health, board, back_seconds, green, why, at)
28 VALUES (?1, ?2, 'u', '', '', 1, ?3, ?4, ?5)`,
29 )
30 .run(id, domain, green ? 1 : 0, why, at);
31
32 beforeAll(async () => {
33 root = mkdtempSync(join(tmpdir(), "forge-drill-door-"));
34 app = createApp({ dataDir: root, port: 0 });
35 const u = 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 (!u.ok) throw new Error(u.error);
43 servers = await serve(app);
44 const r = await fetch(`${servers.url}/signin`, {
45 method: "POST",
46 headers: { origin: servers.url },
47 body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }),
48 redirect: "manual",
49 });
50 cookie = (r.headers.get("set-cookie") ?? "").split(";")[0]!;
51 });
52 beforeEach(() => {
53 app.db.query("DELETE FROM domain_drill").run();
54 insert("a", "compute", false, "red first");
55 insert("b", "compute", true, "green second");
56 insert("c", "compute", false, "red third");
57 });
58 afterAll(async () => {
59 await servers.stop?.();
60 await rm(root, { recursive: true, force: true });
61 });
62
63 test("two drills in one second: the later kept one is the verdict", () => {
64 expect(lastDrills(app.db).get("compute")?.why).toBe("red third");
65 app.db.query("DELETE FROM domain_drill WHERE id = 'c'").run();
66 expect(lastDrills(app.db).get("compute")?.green).toBe(true);
67 });
68
69 test("the Backups page lists each drillable domain's last verdict", async () => {
70 const r = await fetch(`${servers.url}/settings/backups`, { headers: { cookie } });
71 const body = await r.text();
72 expect(body).toContain('id="drill-compute"');
73 expect(body).toContain("red third");
74 expect(body).toContain("never drilled");
75 });
76
77 test("the terminal lists the same verdicts", () => {
78 const lines = domainDrillLines(app.db).join("\n");
79 expect(lines).toContain("compute: red");
80 expect(lines).toContain("red third");
81 expect(lines).toContain("never drilled");
82 expect(lines).not.toContain("snapshots:");
83 });
84
85 test("one predicate says which domains are drillable", () => {
86 const keys = drillableDomains(DOMAINS).map((d) => d.key);
87 expect(keys).toContain("compute");
88 expect(keys).not.toContain("snapshots");
89 expect(keys).not.toContain("state");
90 });
91
92 test("GET /api/v1/drills reads the same list for an admin only", async () => {
93 const anon = await fetch(`${servers.url}/api/v1/drills`);
94 expect(anon.status).toBeGreaterThanOrEqual(400);
95 const r = await fetch(`${servers.url}/api/v1/drills`, { headers: { cookie } });
96 expect(r.status).toBe(200);
97 const j = (await r.json()) as { drills: { domain: string; last: { why: string } | null }[] };
98 expect(j.drills.find((d) => d.domain === "compute")?.last?.why).toBe("red third");
99 });
100 });
test/domain-drill-need.test.ts added +66
@@ -0,0 +1,66 @@
1 /** A red domain drill, or none in eight days, is one need per domain, on a fixed clock. */
2 import { afterAll, beforeAll, beforeEach, describe, expect, test } from "bun:test";
3 import { mkdtempSync } from "node:fs";
4 import { rm } from "node:fs/promises";
5 import { tmpdir } from "node:os";
6 import { join } from "node:path";
7 import { createApp, type App } from "../src/app.ts";
8 import { vitals } from "../src/kernel/vitals.ts";
9 import { DOMAINS } from "../src/kernel/domains.ts";
10 import { domainDrillNeeds } from "../src/kernel/domain_drill.ts";
11
12 const DAY = 86_400_000;
13 const T0 = Date.parse("2026-10-01T00:00:00Z");
14
15 describe("the domain drill's need", () => {
16 let root: string;
17 let app: App;
18 const insert = (domain: string, at: number, green: boolean, why: string) =>
19 app.db
20 .query(
21 `INSERT INTO domain_drill (id, domain, run_by, health, board, back_seconds, green, why, at)
22 VALUES (?1, ?2, 'u', '', '', 1, ?3, ?4, ?5)`,
23 )
24 .run(`${domain}-${at}`, domain, green ? 1 : 0, why, new Date(at).toISOString());
25 const lines = (now: number, domains = DOMAINS) =>
26 vitals({ db: app.db, dataDir: root, signals: app.signals, now, domains }).degraded.filter((d) =>
27 d.cause.startsWith("drill:"),
28 );
29
30 beforeAll(() => {
31 root = mkdtempSync(join(tmpdir(), "forge-domain-drill-"));
32 app = createApp({ dataDir: root, port: 0 });
33 });
34 beforeEach(() => {
35 app.db.query("DELETE FROM domain_drill").run();
36 });
37 afterAll(async () => {
38 await rm(root, { recursive: true, force: true });
39 });
40
41 test("a domain never drilled raises nothing: no door can run one yet", () => {
42 expect(lines(T0 + 30 * DAY)).toEqual([]);
43 });
44
45 test("red names the domain and phrase; the next green clears it", () => {
46 insert("compute", T0 - DAY, false, 'the forge never said "wait"');
47 const red = lines(T0).find((d) => d.cause === "drill:compute");
48 expect(red?.sentence).toContain("compute");
49 expect(red?.sentence).toContain('the forge never said "wait"');
50 expect(red?.sentence).not.toContain("POST");
51 insert("compute", T0 - 1000, true, "ok");
52 expect(lines(T0).map((d) => d.cause)).not.toContain("drill:compute");
53 });
54
55 test("a drilled domain goes stale after eight days, in plain words", () => {
56 insert("compute", T0 - 1000, true, "ok");
57 expect(lines(T0 + 7 * DAY).map((d) => d.cause)).not.toContain("drill:compute");
58 const stale = lines(T0 + 8 * DAY).find((d) => d.cause === "drill:compute");
59 expect(stale?.sentence).toBe("The compute drill has not run in 8 days; the last one passed on 2026-09-30.");
60 expect(lines(T0 + 8 * DAY).map((d) => d.cause)).not.toContain("drill:runner");
61 });
62
63 test("a forge with no drillable domain raises nothing", () => {
64 expect(lines(T0 + 30 * DAY, DOMAINS.filter((d) => d.drill.name === null))).toEqual([]);
65 });
66 });
test/tui-tell.test.ts +1 −1
@@ -74,7 +74,7 @@ afterAll(async () => {
7474
7575 describe("tell the crew in the terminal", () => {
7676 test("the owner's palette has the row", async () => {
77 expect(await palette(alice, [":"])).toContain("alice/lobby — Tell the crew");
77 expect(await palette(alice, [":", "tell"])).toContain("alice/lobby — Tell the crew");
7878 });
7979
8080 test("a reader who may not direct the crew sees no row", async () => {
test/vitals.test.ts +2 −2
@@ -153,8 +153,8 @@ test("the number of queries does not grow with runs", () => {
153153 if (i % 2) app.db.query("UPDATE run SET state='running' WHERE id=?1").run(r.id);
154154 }
155155 expect(count()).toBe(before);
156 // The queue, the running runs, the runs killed twice for their budget, the lane's depth and finished checks, and the red mains holding pulls' checks.
157 expect(before).toBe(6);
156 // The queue, the running runs, the runs killed twice for their budget, the lane's depth and finished checks, the red mains holding pulls' checks, and the newest drill of each domain.
157 expect(before).toBe(7);
158158 });
159159
160160 test("errors are counted, bounded, redacted, and a burst is said", async () => {

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs