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

The daily proof also runs once after each release goes live, so a release is proven within minutes, not at the next 24 h tick #15945

Merged opened this

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

Merged

torque/forge:torque/15937-the-daily-proof-also-runs-once-after-eac → main 0 commits fork

  • Merged. torque/15937-the-daily-proof-also-runs-once-after-eac was merged into main as 2bf5039.

Review

Sign in to review this change.
8 files changed +196 −21
docs/features/daily-proof.md +8 −2
@@ -8,6 +8,12 @@ A maintenance duty, `daily-proof` (#15625), runs the v1.0.0 checklist of `script
88 against the forge's own public origin (`FORGE_URL`). The checks are one module, `src/release/v1_checks.ts`, which
99 the script and the duty share. Without `FORGE_URL` it skips and says so.
1010
11 It also runs once after each release goes live (#15937). Each run records the release it proved: the running commit,
12 or the stamped version where no commit is known. When the running release is one no run has recorded, the proof runs
13 three minutes after boot, so the process is serving. It is keyed on the release, not on boots: a crash loop proves
14 its release once. The daily tick still runs a day after the last run. Its budget is 24 runs a day: one on the clock
15 and one per release, and a run spends no money.
16
1117 - **Read-only and token-free.** The same requests as the script: GETs, and one MCP `initialize` and `releases` call.
1218 All of them go to the origin. No token is ever sent. The whole run has 60 s; once that is spent, the read in flight
1319 ends and every later line says `no answer: the probe's budget ran out`.
@@ -20,8 +26,8 @@ the script and the duty share. Without `FORGE_URL` it skips and says so.
2026 - **Where it reads.** `/status` (`src/web/pages/status.ts`) has a `daily proof` row once a run exists
2127 (`9 of 9 pass, 6 h ago`). The terminal's Status screen (`src/tui/screens/status.ts`) shows the same row, and
2228 `/status` asked for JSON carries `proof`. `GET /api/v1/proof/daily` answers anyone, with no token, with the
23 newest run's lines: `item`, `verdict`, `url` and `evidence`. Evidence is one plain line, nothing credential-shaped,
24 at most 240 characters. Each run is also a `maintenance_run` row (`GET /api/v1/maintenance/runs`).
29 newest run's `release` (null where the forge knew none) and its lines: `item`, `verdict`, `url` and `evidence`.
30 Evidence is one plain line, nothing credential-shaped, at most 240 characters. Each run is also a `maintenance_run` row (`GET /api/v1/maintenance/runs`).
2531
2632 The weekly `v1-proven` duty ([v1-proven.md](v1-proven.md)) is the older proof list. It files a defect issue; this
2733 one asks the owner.
src/core/migration-pins/20261123120000-daily-proof-release.pin added +1
@@ -0,0 +1,1 @@
1 8ce2d714f74ca9d71cd5f182ce52312c01c36f91f9c4f957806d52ca8cf88c31
src/core/migrations/20261123120000-daily-proof-release.ts added +7
@@ -0,0 +1,7 @@
1 // The release each daily proof run proved (#15937, release/daily_proof.ts): the running commit,
2 // or the stamped version where no commit is known. A run differing from the release that is
3 // running now is what makes the proof run again once after a release goes live. Null for a run
4 // before this, and for a forge that knows neither.
5 export default `
6 ALTER TABLE daily_proof_run ADD COLUMN release TEXT;
7 `;
src/maintain/duties/daily_proof.ts +45 −6
@@ -4,25 +4,63 @@
44 * A line that asks the owner is a finding too, so the run's row says what the ask says.
55 * With no fetcher given, the forge's own origin is read through its own router in process
66 * (`../../release/own_fetch.ts`, #15936): the egress gate refuses the forge's own host.
7 *
8 * It also runs once after each release goes live (#15937): when the running release is one no run
9 * has recorded, `SETTLE_MS` after this process booted, so a broken sign-up or price is seen within
10 * minutes rather than at the next daily tick. Keyed on the release id, never on boots, and tried
11 * at most once per release in this process, so neither a crash loop nor a run that cannot record
12 * repeats it.
713 */
814
915 import { ownRepoPath } from "../../kernel/own_repo.ts";
1016 import { publicOrigin } from "../../core/public_origin.ts";
11 import { BUDGET_MS, proveDaily, recordRun } from "../../release/daily_proof.ts";
17 import { shortOf } from "../../kernel/version.ts";
18 import { BUDGET_MS, lastRelease, proveDaily, recordRun, releaseDue, releaseId } from "../../release/daily_proof.ts";
1219 import { IN_PROCESS, ownFetcher } from "../../release/own_fetch.ts";
1320 import type { Fetcher, Line } from "../../release/v1_checks.ts";
1421 import type { Duty, Finding } from "../duty.ts";
1522
16 export function dailyProof(fetcher?: Fetcher, budget: () => AbortSignal = () => AbortSignal.timeout(BUDGET_MS)): Duty {
23 export interface ProofClock {
24 /** The release this process runs (`releaseId`); null proves on the daily tick only. */
25 readonly release?: string | null;
26 /**
27 * When this process booted, ms since the epoch: the release's proof waits `SETTLE_MS` past it.
28 */
29 readonly bootedAt?: number;
30 }
31
32 /** A release as a row says it: a commit by its short id, a version as it is. */
33 const named = (release: string): string => (/^[0-9a-f]{40,64}$/.test(release) ? shortOf(release) : release);
34
35 export function dailyProof(
36 fetcher?: Fetcher,
37 budget: () => AbortSignal = () => AbortSignal.timeout(BUDGET_MS),
38 clock: ProofClock = {},
39 ): Duty {
40 const release = clock.release === undefined ? releaseId() : clock.release;
41 const bootedAt = clock.bootedAt ?? Date.now();
42 // The release this process has started a proof of; a second is never due early.
43 let tried: string | null = null;
44 const knowsOrigin = (url: string | undefined): url is string => url !== undefined && url !== "";
1745 return {
1846 name: "daily-proof",
1947 intervalMs: 86_400_000,
2048 // The checks stop themselves at their budget; the runner waits a little past it for the lines.
2149 timeoutMs: BUDGET_MS + 5_000,
22 budget: { runsPerDay: 2, dollarsPerDay: 1, reason: "daily is one a day; the second is room for a restart, and it spends no money" },
50 budget: {
51 runsPerDay: 24,
52 dollarsPerDay: 1,
53 reason: "one a day on the clock, and one per release that goes live (#15937), each release once; 24 is room for a busy day of releases and restarts, and a run spends no money, only one minute of reads of the forge's own public pages",
54 },
55 dueNow({ db, now, app }) {
56 if (release === null || tried === release || !knowsOrigin(app?.config.url)) return false;
57 return releaseDue(db, release, bootedAt, now.getTime());
58 },
2359 async run({ db, now, app }) {
2460 const url = app?.config.url;
25 if (url === undefined || url === "") return { findings: [], actions: ["skipped: this forge does not know its public origin (FORGE_URL)"] };
61 if (!knowsOrigin(url)) return { findings: [], actions: ["skipped: this forge does not know its public origin (FORGE_URL)"] };
62 tried = release;
63 const fresh = release !== null && lastRelease(db) !== release;
2664 const base = publicOrigin(url, "");
2765 const repo = app?.config.forgeRepo || ownRepoPath();
2866 let lines: Line[];
@@ -37,12 +75,13 @@ export function dailyProof(fetcher?: Fetcher, budget: () => AbortSignal = () =>
3775 own.close();
3876 }
3977 }
40 const done = recordRun(db, lines, now);
78 const done = recordRun(db, lines, now, release);
4179 const findings: Finding[] = done.raised.map((l) => ({
4280 summary: `daily proof: ${l.item} is ${l.verdict}`,
4381 probe: { kind: "measurement", what: `${l.url}: ${l.verdict === "FAIL" ? "1 is a failure" : "1 is unknown where it passed the day before"}`, number: 1, at: now.toISOString() },
4482 }));
45 return { findings, actions: done.said };
83 const proved = release === null ? [] : [fresh ? `proved release ${named(release)}, new since the run before` : `proved release ${named(release)}`];
84 return { findings, actions: [...proved, ...done.said] };
4685 },
4786 };
4887 }
src/maintain/duty.ts +6
@@ -53,6 +53,12 @@ export interface Duty {
5353 */
5454 readonly timeoutMs?: number;
5555 readonly budget: DutyBudget;
56 /**
57 * Whether the duty is due before its interval has passed, asked on every tick the interval has
58 * not (#15937: the daily proof, once a release goes live). The budget, the pause and the
59 * one-at-a-time rule still hold. Never due early when unset.
60 */
61 readonly dueNow?: (ctx: DutyContext) => boolean;
5662 readonly run: (ctx: DutyContext) => DutyResult | Promise<DutyResult>;
5763 }
5864
src/maintain/runner.ts +14 −2
@@ -1,6 +1,7 @@
11 /**
22 * The duty runner (#11204): on the clock, each duty whose interval has passed since it last
3 * started runs once, never twice at the same time, and leaves a `maintenance_run` row. A
3 * started (or that says it is due sooner, `dueNow`) runs once, never twice at the same time, and
4 * leaves a `maintenance_run` row. A
45 * finding without a probe is refused: the run's outcome says so and no finding is kept.
56 */
67
@@ -84,11 +85,22 @@ export function startMaintain(app: App, options: { duties?: readonly Duty[]; eve
8485 }
8586 }
8687
88 /** A duty's own word that it is due before its interval; a throw is a no. */
89 function dueEarly(duty: Duty, now: Date): boolean {
90 if (duty.dueNow === undefined) return false;
91 try {
92 return duty.dueNow({ db: app.db, bus: app.bus, now, app }) === true;
93 } catch (error) {
94 app.log.error("maintenance duty's due check failed", { duty: duty.name, error: String(error) });
95 return false;
96 }
97 }
98
8799 async function tick(now = new Date()): Promise<void> {
88100 for (const duty of list) {
89101 const last = lastStarted(app.db, duty.name);
90 if (last !== undefined && now.getTime() - last < duty.intervalMs) continue;
91102 if (running.has(duty.name) || isPaused(app.db, duty.name)) continue;
103 if (last !== undefined && now.getTime() - last < duty.intervalMs && !dueEarly(duty, now)) continue;
92104 const stop = overBudget(app.db, duty, now);
93105 if (stop !== undefined) {
94106 // Said once a day per budget: the row names which one the duty stopped at.
src/release/daily_proof.ts +44 −8
@@ -12,12 +12,18 @@
1212 * whose `since` is the newest raise: the notifier tells the owner once per `since`, so a second
1313 * line failing is a new ask and a line that stays failed is not.
1414 *
15 * Besides the daily tick, it runs once after each release goes live (#15937): each run records
16 * the release it proved (`releaseId`: the running commit, or the stamped version where no commit
17 * is known), and a release no run has recorded is due (`releaseDue`) once the process has served
18 * for `SETTLE_MS`. Keyed on the release, not on boots: a crash loop of one release proves it once.
19 *
1520 * `/status`, its terminal screen and `GET /api/v1/proof/daily` read the newest run; what they
1621 * show passes through `plainEvidence`, so no credential-shaped text or control character leaves.
1722 */
1823
1924 import type { Database } from "bun:sqlite";
2025 import { redactSecrets } from "../kernel/log.ts";
26 import { running, UNSTAMPED, type Running } from "../kernel/version.ts";
2127 import { probe, type Fetcher, type Line, type Verdict } from "./v1_checks.ts";
2228
2329 /** The whole run's budget: every read the checks make, together. */
@@ -25,10 +31,14 @@ export const BUDGET_MS = 60_000;
2531 /** Runs kept: a month of days. */
2632 export const KEEP_RUNS = 30;
2733 const EVIDENCE_MAX = 240;
34 /** How long a process serves before the proof of its new release runs: past the boot's own work. */
35 export const SETTLE_MS = 180_000;
2836 const VERDICTS: ReadonlySet<string> = new Set<Verdict>(["PASS", "FAIL", "UNKNOWN"]);
2937
3038 export interface ProofRun {
3139 readonly at: string;
40 /** The release the run proved, or null when the forge knew none (and for runs before #15937). */
41 readonly release: string | null;
3242 readonly lines: readonly Line[];
3343 }
3444
@@ -73,6 +83,30 @@ export function proveDaily(
7383 return probe(base, repo, fetcher, now, undefined, undefined, budget);
7484 }
7585
86 /**
87 * The release that is running, as a run records it: the commit in full, else the stamped version,
88 * else null (a forge run from source, `dev`, has no release to prove).
89 */
90 export function releaseId(r: Running = running()): string | null {
91 if (r.commit !== null) return r.commit;
92 return r.version !== UNSTAMPED ? r.version : null;
93 }
94
95 /** The release the newest run recorded; undefined before the first run, null where it knew none. */
96 export function lastRelease(db: Database): string | null | undefined {
97 const row = db.query<{ release: string | null }, []>("SELECT release FROM daily_proof_run ORDER BY id DESC LIMIT 1").get();
98 return row === null ? undefined : row.release;
99 }
100
101 /**
102 * Whether a release is due its own proof now: one is running, no run has recorded it yet, and the
103 * process has served `SETTLE_MS` since `bootedAt`.
104 */
105 export function releaseDue(db: Database, release: string | null, bootedAt: number, now: number): boolean {
106 if (release === null || now - bootedAt < SETTLE_MS) return false;
107 return lastRelease(db) !== release;
108 }
109
76110 const isLine = (v: unknown): v is Line => {
77111 const l = v as Partial<Line> | null;
78112 return typeof l?.item === "string" && typeof l.url === "string" && typeof l.evidence === "string" && VERDICTS.has(String(l.verdict));
@@ -80,7 +114,7 @@ const isLine = (v: unknown): v is Line => {
80114
81115 /** The newest run, or undefined before the first. */
82116 export function lastRun(db: Database): ProofRun | undefined {
83 const row = db.query<{ at: string; lines: string }, []>("SELECT at, lines FROM daily_proof_run ORDER BY id DESC LIMIT 1").get();
117 const row = db.query<{ at: string; lines: string; release: string | null }, []>("SELECT at, lines, release FROM daily_proof_run ORDER BY id DESC LIMIT 1").get();
84118 if (row === null) return undefined;
85119 let parsed: unknown;
86120 try {
@@ -88,7 +122,7 @@ export function lastRun(db: Database): ProofRun | undefined {
88122 } catch {
89123 parsed = [];
90124 }
91 return { at: row.at, lines: Array.isArray(parsed) ? parsed.filter(isLine) : [] };
125 return { at: row.at, release: row.release, lines: Array.isArray(parsed) ? parsed.filter(isLine) : [] };
92126 }
93127
94128 /** The lines asking the owner now, oldest raise first. */
@@ -106,9 +140,10 @@ export const asks = (line: Line, before: Verdict | undefined): boolean =>
106140 line.verdict === "FAIL" || (line.verdict === "UNKNOWN" && before === "PASS");
107141
108142 /**
109 * Keeps one run's lines and moves the asks: raises the new, keeps the standing, clears the passing.
143 * Keeps one run's lines and the release it proved, and moves the asks: raises the new, keeps the
144 * standing, clears the passing.
110145 */
111 export function recordRun(db: Database, lines: readonly Line[], at: Date): Recorded {
146 export function recordRun(db: Database, lines: readonly Line[], at: Date, release: string | null = null): Recorded {
112147 const iso = at.toISOString();
113148 const before = new Map((lastRun(db)?.lines ?? []).map((l) => [l.item, l.verdict] as const));
114149 const open = new Set(openAsks(db).map((a) => a.item));
@@ -116,7 +151,7 @@ export function recordRun(db: Database, lines: readonly Line[], at: Date): Recor
116151 const raised: Line[] = [];
117152 const cleared: string[] = [];
118153 db.transaction(() => {
119 db.run("INSERT INTO daily_proof_run (at, lines) VALUES (?1, ?2)", [iso, JSON.stringify(lines)]);
154 db.run("INSERT INTO daily_proof_run (at, lines, release) VALUES (?1, ?2, ?3)", [iso, JSON.stringify(lines), release]);
120155 db.run("DELETE FROM daily_proof_run WHERE id <= (SELECT id FROM daily_proof_run ORDER BY id DESC LIMIT 1 OFFSET ?1)", [KEEP_RUNS]);
121156 for (const l of lines) {
122157 if (l.verdict === "PASS") {
@@ -180,17 +215,18 @@ export function proofAlarm(db: Database): { fired: boolean; since?: string; says
180215 }
181216
182217 /**
183 * The public answer: the newest run's counts and its lines, named fields only, evidence plain.
184 * `{at: null}` before the first run.
218 * The public answer: the newest run's counts, the release it proved (null where it knew none) and
219 * its lines, named fields only, evidence plain. `{at: null}` before the first run.
185220 */
186221 export function proofAnswer(db: Database):
187222 | { at: null }
188 | { at: string; pass: number; total: number; lines: { item: string; verdict: Verdict; url: string; evidence: string }[] } {
223 | { at: string; release: string | null; pass: number; total: number; lines: { item: string; verdict: Verdict; url: string; evidence: string }[] } {
189224 const run = lastRun(db);
190225 if (run === undefined) return { at: null };
191226 const t = tally(run);
192227 return {
193228 at: t.at,
229 release: run.release,
194230 pass: t.pass,
195231 total: t.total,
196232 lines: run.lines.map((l) => ({ item: l.item, verdict: l.verdict, url: l.url, evidence: plainEvidence(l.evidence) })),
test/daily-proof.test.ts +71 −3
@@ -4,7 +4,8 @@
44 * (one `daily_proof` flow alarm, one `since`) however many days it stays failed; a day of all PASS
55 * clears it in one line; an UNKNOWN asks only where it passed the day before; the whole run stops
66 * at its budget and still returns its lines. The last run reads on /status, its JSON, the terminal
7 * and `GET /api/v1/proof/daily` without a token.
7 * and `GET /api/v1/proof/daily` without a token, naming the release it proved. A release no run
8 * has recorded runs the proof once, a few minutes after boot, besides the daily tick (#15937).
89 */
910 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
1011 import { mkdtemp, rm } from "node:fs/promises";
@@ -14,8 +15,9 @@ import { createApp, type App } from "../src/app.ts";
1415 import { firedAlarms, FORGE_BROKEN } from "../src/flow/alarms.ts";
1516 import { serve, type Servers } from "../src/http/server.ts";
1617 import { dailyProof } from "../src/maintain/duties/daily_proof.ts";
18 import { startMaintain } from "../src/maintain/runner.ts";
1719 import type { DutyResult } from "../src/maintain/duty.ts";
18 import { lastRun, openAsks, plainEvidence, proofAlarm, recordRun, tallyWords } from "../src/release/daily_proof.ts";
20 import { lastRun, openAsks, plainEvidence, proofAlarm, proofAnswer, recordRun, SETTLE_MS, tallyWords } from "../src/release/daily_proof.ts";
1921 import { IN_PROCESS, ownFetcher } from "../src/release/own_fetch.ts";
2022 import { OUT_OF_BUDGET, type Line } from "../src/release/v1_checks.ts";
2123 import { Session } from "../src/tui/forge.ts";
@@ -93,7 +95,7 @@ const runDay = async (day: number, w: World = {}): Promise<DutyResult> => {
9395 world = w;
9496 now = T0 + day * DAY;
9597 const budget = new AbortController();
96 const duty = dailyProof(stubForge(() => world, () => now, calls, budget), () => budget.signal);
98 const duty = dailyProof(stubForge(() => world, () => now, calls, budget), () => budget.signal, { release: null });
9799 return duty.run({ db: app.db, bus: app.bus, now: new Date(now), app: fakeApp() });
98100 };
99101 const verdicts = () => Object.fromEntries((lastRun(app.db)?.lines ?? []).map((l) => [l.item, l.verdict]));
@@ -195,6 +197,72 @@ describe("the daily proof", () => {
195197 const body = (await res.json()) as { pass: number; total: number; lines: Record<string, unknown>[] };
196198 expect(body).toMatchObject({ pass: total, total });
197199 expect(Object.keys(body.lines[0]!).sort()).toEqual(["evidence", "item", "url", "verdict"]);
200 expect(body).toMatchObject({ release: null }); // a forge that knows no release says so
201 });
202
203 test("the public answer names the release the newest run proved", async () => {
204 const release = "d".repeat(40);
205 const budget = new AbortController();
206 const duty = dailyProof(stubForge(() => ({}), () => now, [], budget), () => budget.signal, { release, bootedAt: now });
207 const r = await duty.run({ db: app.db, bus: app.bus, now: new Date(now), app: fakeApp() });
208 expect(r.actions[0]).toBe("proved release ddddddd, new since the run before");
209 expect(lastRun(app.db)!.release).toBe(release);
210 const body = (await (await fetch(`${servers.url}/api/v1/proof/daily`)).json()) as { release: string };
211 expect(body.release).toBe(release);
212 });
213 });
214
215 describe("once after each release goes live (#15937)", () => {
216 const A = "a".repeat(40);
217 const B = "b".repeat(40);
218 const MIN = 60_000;
219
220 test("a new release id runs the proof exactly once after it settles; an unchanged one none", async () => {
221 const sub = createApp({ dataDir: join(dir, "release-app"), port: 0, url: `${BASE}/`, forgeRepo: "o/forge" });
222 let clock = T0;
223 const runs = () => (sub.db.query("SELECT COUNT(*) AS n FROM daily_proof_run").get() as { n: number }).n;
224 const boot = (release: string, bootedAt: number) => {
225 const budget = new AbortController();
226 const duty = dailyProof(stubForge(() => ({}), () => clock, [], budget), () => budget.signal, { release, bootedAt });
227 const m = startMaintain(sub, { duties: [duty], everyMs: 1e9 });
228 m.stop(); // ticked by hand below
229 return (at: number) => m.tick(new Date((clock = at)));
230 };
231
232 // Release A boots; its first proof runs on the first tick (nothing ran before).
233 let tick = boot(A, T0);
234 await tick(T0 + 4 * MIN);
235 expect(runs()).toBe(1);
236 expect(lastRun(sub.db)!.release).toBe(A);
237 // Unchanged release, minutes and hours later: nothing until the daily tick.
238 await tick(T0 + 10 * MIN);
239 await tick(T0 + 6 * 3_600_000);
240 expect(runs()).toBe(1);
241
242 // Release B goes live: not before it has served SETTLE_MS, then exactly once.
243 const bootB = T0 + 8 * 3_600_000;
244 tick = boot(B, bootB);
245 await tick(bootB + 60_000);
246 expect(runs()).toBe(1);
247 await tick(bootB + SETTLE_MS);
248 expect(runs()).toBe(2);
249 expect(proofAnswer(sub.db)).toMatchObject({ release: B });
250 await tick(bootB + SETTLE_MS + MIN);
251 await tick(bootB + SETTLE_MS + 2 * MIN);
252 expect(runs()).toBe(2);
253
254 // B restarts (a crash loop): the proof is keyed on the release, not the boot, so none.
255 for (let i = 1; i <= 3; i++) {
256 const again = bootB + i * 10 * MIN;
257 tick = boot(B, again);
258 await tick(again + SETTLE_MS + MIN);
259 }
260 expect(runs()).toBe(2);
261
262 // And the daily tick still runs, a day after the last run.
263 await tick(bootB + SETTLE_MS + 86_400_000);
264 expect(runs()).toBe(3);
265 sub.close();
198266 });
199267 });
200268

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs