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

A maintenance finding shows its age and who last touched it, and the oldest one leads #16079

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

mason/forge:mason/16048-a-maintenance-finding-shows-its-age-and → main 0 commits fork 4 threads · 4 unresolved

  • Merged. mason/16048-a-maintenance-finding-shows-its-age-and was merged into main as 1f151b2.

Review

Sign in to review this change.
7 files changed +116 −39
docs/features/maintenance-findings.md +11 −8
@@ -7,16 +7,19 @@ row: Findings on the maintenance board
77 `/maintenance` (admin) lists what the forge saw degrade, one row per cause however many days it
88 held (#14577), so a cause that lasted a month is one line, not thirty.
99
10 - **A row.** The cause, its latest reading (the newest span's sentence) and "seen N days", the
11 distinct UTC days a span of that cause opened on. "; still open" ends the row while the newest
12 span is open. The fold opens when any row is open.
13 - **Bounded.** At most 20 rows, newest first, then "And N more". One grouped read of
14 `degraded_span` (`src/maintenance/findings.ts`), whose closed spans are pruned, so the first paint
15 costs one statement.
10 - **A row.** The cause, its latest reading (the newest span's sentence) and its age, "opened 3 d
11 ago" (m, h or d; "opened just now" under a minute), counted from the first span of that cause
12 still kept: a cause that cleared and opened again keeps the age of its first kept span, beside
13 "; still open", which ends the row while the newest span is open. The fold opens when any row
outdated

Line runs past the wrap used in the rest of the file; rewrap.

14 is open.
15 - **Bounded.** The 20 newest causes, listed oldest first so the longest-standing leads, then "And
16 N more". One grouped read of `degraded_span` (`src/maintenance/findings.ts`), whose closed spans
17 are pruned, so the first paint costs one statement.
1618 - **In the terminal.** The Maintenance screen (`src/tui/screens/maintenance.ts`, admins) ends with
17 the same rows, from `findingLines`.
19 the same rows, in the same order and words, from `findingLines`.
outdated

Same: rewrap this long line.

1820 - **As JSON, for an agent.** `GET /maintenance.json`, or `/maintenance` with
19 `Accept: application/json`, answers the same rows as `{duty, severity, cause, action}` objects.
21 `Accept: application/json`, answers the same rows as `{duty, severity, cause, action, openedAt}`
22 objects, `openedAt` an ISO time.
2023 Admin only, the same rule as the page, so a signed-out caller gets the sign-in redirect (303),
2124 not a 401. At most 20 rows and no "more" count. `Cache-Control: no-store`; `/maintenance`
2225 answers `Vary: accept` so a shared cache never hands JSON to a browser or the reverse.
src/maintenance/findings.ts +37 −17
@@ -1,6 +1,6 @@
11 /**
22 * The degraded findings as the board shows them: one row per cause however many days it held,
3 * with its latest reading and how many days it was seen (#14577). One grouped query over
3 * with its latest reading and its age (#14577, #16048). One grouped query over
44 * `degraded_span`, so the first paint costs the same with one day of history or thirty.
55 */
66
@@ -12,10 +12,13 @@ export interface FindingRow {
1212 readonly cause: string;
1313 /** The newest span's sentence: the latest reading. */
1414 readonly latest: string;
15 /** Distinct UTC days a span of the cause opened on. */
16 readonly days: number;
1715 /** True while the newest span is still open. */
1816 readonly open: boolean;
outdated

Dead: days is no longer read anywhere after seenWords was removed. Drop it and the days computation in the query.

17 /**
18 * Epoch ms the cause was first seen in the history kept: its age starts here, and a cause that
19 * cleared and opened again keeps the age of its first kept span.
20 */
21 readonly openedAt: number;
1922 /** When the tick closed it for want of action (epoch ms), or null while it stands. */
2023 readonly autoClosedAt: number | null;
2124 }
@@ -37,27 +40,40 @@ export interface Findings {
3740 }
3841
3942 /**
40 * Findings newest first, at most `FINDING_ROWS`. `degraded_span` keeps closed spans a bounded time
41 * (`degraded_history.ts` prunes them), so the grouping reads a bounded table.
43 * The newest `FINDING_ROWS` causes, listed oldest first so the longest-standing leads.
44 * `degraded_span` keeps closed spans a bounded time (`degraded_history.ts` prunes them), so the
45 * grouping reads a bounded table.
4246 */
4347 export function findingRows(db: Database, cap = FINDING_ROWS): Findings {
4448 const { got, more } = latestSpans(db, cap);
45 const rows = got.map((r) => ({ cause: r.cause, latest: r.sentence, days: r.days, open: r.closed_at === null, autoClosedAt: r.swept_at }));
49 const rows = oldestFirst(got).map((r) => ({ cause: r.cause, latest: r.sentence, open: r.closed_at === null, openedAt: r.first, autoClosedAt: r.swept_at }));
4650 return { rows, autoClosed: autoClosedCauses(db).length, more };
4751 }
4852
49 interface SpanRow { cause: string; sentence: string; href: string; closed_at: number | null; swept_at: number | null; days: number; total: number }
53 interface SpanRow { cause: string; sentence: string; href: string; closed_at: number | null; swept_at: number | null; first: number; total: number }
54
55 /** Oldest first-seen leads; ties keep the query's order. */
56 const oldestFirst = (rows: SpanRow[]): SpanRow[] => [...rows].sort((a, b) => a.first - b.first);
57
58 /** "opened 3 d ago": the age of a finding against the clock the caller passes in. */
59 export function openedWords(openedAt: number, now: number): string {
60 const ms = Math.max(0, now - openedAt);
61 if (ms < 60_000) return "opened just now";
62 if (ms < 3_600_000) return `opened ${String(Math.floor(ms / 60_000))} m ago`;
63 if (ms < DAY_MS) return `opened ${String(Math.floor(ms / 3_600_000))} h ago`;
64 return `opened ${String(Math.floor(ms / DAY_MS))} d ago`;
65 }
5066
5167 /** The one query behind every reading of the findings: the board, the terminal and the JSON. */
5268 function latestSpans(db: Database, cap: number): { got: SpanRow[]; more: number } {
5369 const got = db
54 .query<SpanRow, [number, number]>(
55 `SELECT s.cause, s.sentence, s.href, s.closed_at, s.swept_at, g.days, COUNT(*) OVER () AS total
70 .query<SpanRow, [number]>(
71 `SELECT s.cause, s.sentence, s.href, s.closed_at, s.swept_at, g.first, COUNT(*) OVER () AS total
5672 FROM degraded_span s
57 JOIN (SELECT cause, MAX(id) AS last, COUNT(DISTINCT opened_at / ?1) AS days FROM degraded_span GROUP BY cause) g ON s.id = g.last
58 ORDER BY s.opened_at DESC, s.id DESC LIMIT ?2`,
73 JOIN (SELECT cause, MAX(id) AS last, MIN(opened_at) AS first FROM degraded_span GROUP BY cause) g ON s.id = g.last
74 ORDER BY s.opened_at DESC, s.id DESC LIMIT ?1`,
5975 )
60 .all(DAY_MS, cap);
76 .all(cap);
6177 return { got, more: Math.max(0, (got[0]?.total ?? 0) - got.length) };
6278 }
6379
@@ -111,31 +127,35 @@ export interface FindingJson {
111127 readonly cause: string;
112128 /** The path that shows it and where to act on it. */
113129 readonly action: string;
130 /** ISO time the cause was first seen. */
131 readonly openedAt: string;
114132 }
115133
116134 /** The same rows as `findingRows`, as the plain data `/maintenance.json` answers. */
117135 export function findingsJson(db: Database): { findings: FindingJson[] } {
118136 return {
119 findings: latestSpans(db, FINDING_ROWS).got.map((r) => ({
137 findings: oldestFirst(latestSpans(db, FINDING_ROWS).got).map((r) => ({
120138 duty: r.cause,
121139 severity: r.closed_at === null && r.swept_at === null ? "degraded" : "cleared",
122140 cause: r.sentence,
123141 action: r.href,
142 openedAt: new Date(r.first).toISOString(),
124143 })),
125144 };
126145 }
127146
128 /** "seen 3 days", the words the row ends on. */
129 export const seenWords = (days: number): string => `seen ${String(days)} ${days === 1 ? "day" : "days"}`;
147 /** The words a row ends on, board and terminal alike: its age, then "still open" while it is. */
148 export const rowWords = (r: FindingRow, now: number): string =>
149 `${openedWords(r.openedAt, now)}${r.autoClosedAt !== null ? `; closed ${closedDate(r.autoClosedAt)}: ${AUTO_CLOSE_NOTE}` : r.open ? "; still open" : ""}`;
130150
131151 /** The same rows as terminal lines, led by a blank line; nothing when none. */
132 export function findingLines(db: Database): string[] {
152 export function findingLines(db: Database, now: number = Date.now()): string[] {
133153 const { rows, more } = findingRows(db);
134154 if (rows.length === 0) return [];
135155 return [
136156 "",
137157 "Findings (what degraded, latest reading):",
138 ...rows.map((r) => `${r.cause}: ${r.latest} (${seenWords(r.days)}${r.autoClosedAt !== null ? `; closed ${closedDate(r.autoClosedAt)}: ${AUTO_CLOSE_NOTE}` : r.open ? "; still open" : ""})`),
158 ...rows.map((r) => `${r.cause}: ${r.latest} (${rowWords(r, now)})`),
139159 ...(more > 0 ? [`And ${String(more)} more, older causes, not listed.`] : []),
140160 ];
141161 }
src/web/pages/maintenance.ts +4 −4
@@ -11,7 +11,7 @@ import { dutyStates, switchDuty } from "../../maintain/pause.ts";
1111 import { DISMISS_DAYS, REASON_MAX, dismiss, dismissals, dismissalWords } from "../../maintain/dismiss.ts";
1212 import { duties, quietLine, splitDuties } from "../../maintenance/duties.ts";
1313 import { LEVELS, LEVEL_WORDS, dutiesLevel, levelOf, returnLevel, stateLevel, type Level } from "../../maintenance/level.ts";
14 import { AUTO_CLOSE_NOTE, closedDate, findingRows, findingsJson, reopenFinding, seenWords } from "../../maintenance/findings.ts";
14 import { findingRows, findingsJson, reopenFinding, rowWords } from "../../maintenance/findings.ts";
1515 import { NOTHING_FILED, filedPieces } from "../../maintenance/filed.ts";
1616 import { stalledStep } from "../../maintenance/stalled.ts";
1717 import { statusWithStandby } from "../../maintenance/standby.ts";
@@ -49,16 +49,16 @@ const fold = (id: string, title: string, count: string, open: boolean, body: Htm
4949 const plural = (n: number, one: string, many: string): string => `${String(n)} ${n === 1 ? one : many}`;
5050
5151 /**
52 * What the forge saw degrade, one row per cause with its latest reading and the days it was seen;
52 * What the forge saw degrade, one row per cause with its latest reading and its age;
5353 * nothing when none. Open when a cause is still open, which each row says once.
5454 */
55 function findingsFold(db: Parameters<typeof findingRows>[0]): Html {
55 export function findingsFold(db: Parameters<typeof findingRows>[0], now: number = Date.now()): Html {
5656 const { rows, more, autoClosed } = findingRows(db);
5757 if (rows.length === 0) return html``;
5858 const count = `${String(rows.length + more)}${autoClosed > 0 ? `, ${String(autoClosed)} auto-closed` : ""}`;
5959 return fold("maintenance-findings", "Findings", count, rows.some((r) => r.open && r.autoClosedAt === null),
6060 html`<dl id="maintenance-findings-rows" class="status-rows">${rows.map(
outdated

Principles 1 and 8: age and days-seen are said twice here, with abbreviated units ("3 d ago"). Merge them into one plain phrase. Also no test renders this row: reverting this line leaves the suite green.

61 (r) => statusRow(r.cause, html`<span data-finding="${r.cause}">${r.latest}</span> <span class="muted">${seenWords(r.days)}${r.autoClosedAt !== null ? html`; closed ${closedDate(r.autoClosedAt)}: ${AUTO_CLOSE_NOTE}` : r.open ? "; still open" : ""}</span>${r.autoClosedAt !== null ? html` <form method="post" action="/maintenance/findings/reopen" class="inline"><input type="hidden" name="cause" value="${r.cause}">${btn("Reopen", { variant: "ghost", size: "sm" })}</form>` : null}`),
61 (r) => statusRow(r.cause, html`<span data-finding="${r.cause}">${r.latest}</span> <span class="muted">${rowWords(r, now)}</span>${r.autoClosedAt !== null ? html` <form method="post" action="/maintenance/findings/reopen" class="inline"><input type="hidden" name="cause" value="${r.cause}">${btn("Reopen", { variant: "ghost", size: "sm" })}</form>` : null}`),
6262 )}${more > 0 ? statusRow(`And ${String(more)} more`, html`<span class="muted">older causes, not listed</span>`) : html``}</dl>`);
6363 }
6464
test/maintenance-finding-age.test.ts added +56
@@ -0,0 +1,56 @@
1 /** A maintenance finding shows its age, and the oldest leads (#16048). Time is injected. */
2 import { expect, test } from "bun:test";
3 import { Database } from "bun:sqlite";
4 import { findingsFold } from "../src/web/pages/maintenance.ts";
5 import { findingLines, findingRows, findingsJson, openedWords } from "../src/maintenance/findings.ts";
6
7 const DAY = 86_400_000;
8 const NOW = Date.parse("2026-11-23T12:00:00.000Z");
9
10 function seed(): Database {
11 const db = new Database(":memory:");
12 db.run("CREATE TABLE degraded_span (id INTEGER PRIMARY KEY AUTOINCREMENT, cause TEXT NOT NULL, sentence TEXT NOT NULL, href TEXT NOT NULL, opened_at INTEGER NOT NULL, closed_at INTEGER, swept_at INTEGER, clock_at INTEGER)");
13 const ins = db.query("INSERT INTO degraded_span (cause, sentence, href, opened_at, closed_at) VALUES (?1, 'x', '/system', ?2, NULL)");
14 ins.run("newer", NOW - 2 * 3_600_000);
15 ins.run("oldest", NOW - 3 * DAY);
16 ins.run("middle", NOW - DAY);
17 return db;
18 }
19
20 test("ages read in minutes, hours and days against the clock given", () => {
21 expect(openedWords(NOW - 5 * 60_000, NOW)).toBe("opened 5 m ago");
22 expect(openedWords(NOW - 2 * 3_600_000, NOW)).toBe("opened 2 h ago");
23 expect(openedWords(NOW - 3 * DAY, NOW)).toBe("opened 3 d ago");
24 expect(openedWords(NOW + 1000, NOW)).toBe("opened just now");
25 });
26
27 test("findings list oldest first, in the rows, the terminal and the JSON", () => {
28 const db = seed();
29 expect(findingRows(db).rows.map((r) => r.cause)).toEqual(["oldest", "middle", "newer"]);
30 expect(findingLines(db, NOW)[2]).toBe("oldest: x (opened 3 d ago; still open)");
31 const json = findingsJson(db).findings;
32 expect(json.map((f) => f.duty)).toEqual(["oldest", "middle", "newer"]);
33 expect(json[0]?.openedAt).toBe(new Date(NOW - 3 * DAY).toISOString());
34 });
35
36 test("the board's Findings fold says the age in each row, oldest first, against the clock given", () => {
37 const out = String(findingsFold(seed(), NOW));
38 expect(out).toContain("opened 3 d ago; still open");
39 expect(out).toContain("opened 1 d ago; still open");
40 expect(out).toContain("opened 2 h ago; still open");
41 expect(out).not.toContain("seen ");
42 expect(out.indexOf('data-finding="oldest"')).toBeLessThan(out.indexOf('data-finding="middle"'));
43 expect(out.indexOf('data-finding="middle"')).toBeLessThan(out.indexOf('data-finding="newer"'));
44 });
45
46 test("a cause that cleared and opened again keeps the age of its first kept span", () => {
47 const db = new Database(":memory:");
48 db.run("CREATE TABLE degraded_span (id INTEGER PRIMARY KEY AUTOINCREMENT, cause TEXT NOT NULL, sentence TEXT NOT NULL, href TEXT NOT NULL, opened_at INTEGER NOT NULL, closed_at INTEGER, swept_at INTEGER, clock_at INTEGER)");
49 const ins = db.query("INSERT INTO degraded_span (cause, sentence, href, opened_at, closed_at) VALUES ('disk', ?1, '/system', ?2, ?3)");
50 ins.run("first", NOW - 5 * DAY, NOW - 4 * DAY);
51 ins.run("again", NOW - 3_600_000, null);
52 const [row] = findingRows(db).rows;
53 expect(row?.openedAt).toBe(NOW - 5 * DAY);
54 expect(findingLines(db, NOW)[2]).toBe("disk: again (opened 5 d ago; still open)");
55 expect(findingsJson(db).findings[0]?.openedAt).toBe(new Date(NOW - 5 * DAY).toISOString());
56 });
test/maintenance-findings.test.ts +4 −6
@@ -1,7 +1,7 @@
11 /** /maintenance shows one row per degraded cause, not one per day (#14577). */
22 import { expect, test } from "bun:test";
33 import { Database } from "bun:sqlite";
4 import { FINDING_ROWS, findingLines, findingRows, seenWords } from "../src/maintenance/findings.ts";
4 import { FINDING_ROWS, findingLines, findingRows } from "../src/maintenance/findings.ts";
55
66 const DAY = 86_400_000;
77 const T0 = Date.parse("2026-11-01T12:00:00.000Z");
@@ -25,10 +25,8 @@ test("three days of one finding are one row with the latest reading; another fin
2525 const { rows } = findingRows(db);
2626 expect(rows.length).toBe(2);
2727 const mem = rows.find((r) => r.cause === "memory-growth")!;
28 expect(mem).toEqual({ cause: "memory-growth", latest: "50 MiB", days: 3, open: true, autoClosedAt: null });
29 expect(rows.find((r) => r.cause === "disk-free")).toEqual({ cause: "disk-free", latest: "5 GiB", days: 1, open: false, autoClosedAt: null });
30 expect(seenWords(3)).toBe("seen 3 days");
31 expect(seenWords(1)).toBe("seen 1 day");
28 expect(mem).toEqual({ cause: "memory-growth", latest: "50 MiB", open: true, openedAt: T0, autoClosedAt: null });
29 expect(rows.find((r) => r.cause === "disk-free")).toEqual({ cause: "disk-free", latest: "5 GiB", open: false, openedAt: T0 + DAY, autoClosedAt: null });
3230 });
3331
3432 test("rows are capped and the rest counted; the terminal says the same", () => {
@@ -44,5 +42,5 @@ test("rows are capped and the rest counted; the terminal says the same", () => {
4442 test("an open cause says so once, in its row", () => {
4543 const db = seed();
4644 add(db, "disk-free", "1 GiB", T0, false);
47 expect(findingLines(db)).toContain("disk-free: 1 GiB (seen 1 day; still open)");
45 expect(findingLines(db, T0)).toContain("disk-free: 1 GiB (opened just now; still open)");
4846 });
test/maintenance-json.test.ts +2 −2
@@ -36,8 +36,8 @@ afterAll(async () => {
3636
3737 test("the JSON carries the findings the page lists, from the same module", async () => {
3838 const want = [
39 { duty: "memory-growth", severity: "cleared", cause: "40 MiB", action: "/resilience" },
40 { duty: "disk-free", severity: "degraded", cause: "5 GiB left", action: "/system" },
39 { duty: "disk-free", severity: "degraded", cause: "5 GiB left", action: "/system", openedAt: new Date(1_000).toISOString() },
40 { duty: "memory-growth", severity: "cleared", cause: "40 MiB", action: "/resilience", openedAt: new Date(2_000).toISOString() },
4141 ];
4242 for (const res of [
4343 await fetch(`${servers.url}/maintenance.json`, { headers: { cookie } }),
test/maintenance-page.test.ts +2 −2
@@ -71,7 +71,7 @@ test("the answer names its phases in Server-Timing and stays under the budget ov
7171 expect(render).toBeLessThan(BUDGET_MS);
7272 });
7373
74 test("the page shows one Findings row per cause, with its latest reading and days seen (#14577)", async () => {
74 test("the page shows one Findings row per cause, with its latest reading and its age (#14577)", async () => {
7575 const ins = app.db.query("INSERT INTO degraded_span (cause, sentence, href, opened_at, closed_at) VALUES ('memory-growth', ?1, '/system', ?2, ?3)");
7676 const t = Date.now() - 3 * 86_400_000;
7777 for (let i = 0; i < 3; i++) ins.run(`reading ${String(i)} MiB`, t + i * 86_400_000, t + i * 86_400_000 + 1000);
@@ -79,7 +79,7 @@ test("the page shows one Findings row per cause, with its latest reading and day
7979 expect(text.match(/data-finding="memory-growth"/g)?.length).toBe(1);
8080 expect(text).toContain("reading 2 MiB");
8181 expect(text).not.toContain("reading 0 MiB");
82 expect(text).toContain("seen 3 days");
82 expect(text).toContain("opened 3 d ago");
8383 expect(text).not.toContain("still open");
8484 app.db.query("DELETE FROM degraded_span").run();
8585 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs