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

Telemetry retention: probes and preview findings keep 30 days (#16572) #16573

Merged opened this

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

Merged

fix/retention-probe → main 0 commits 2 threads · 2 unresolved

  • Merged. fix/retention-probe was merged into main as 4b96635.

Review

Sign in to review this change.
4 files changed +235 −2
src/system/retention.ts +23 −2
@@ -1,7 +1,7 @@
11 /**
22 * What has left its window goes, in small slices on a pace (#12052, part of #11973).
33 *
4 * Five jobs, each a slice of bounded rows and so of bounded time, none holding a
4 * Six jobs, each a slice of bounded rows and so of bounded time, none holding a
55 * transaction open past it, each named to the perf job watch (`perf/jobs.ts`) so a
66 * stall is blamed on it:
77 *
@@ -12,7 +12,9 @@
1212 * - `landed-backfill`: `deploy_landed` from the rows of the old ledger, 60 pulls a slice, then
1313 * an hourly pass for the deploys an older release recorded meanwhile;
1414 * - `retention-deploys`: the old ledger's rows past the window (`system/retention_deploys.ts`),
15 * 250 rows a slice, and only once `landed-backfill` has had a full pass.
15 * 250 rows a slice, and only once `landed-backfill` has had a full pass;
16 * - `retention-telemetry`: app probes and preview findings past 30 days
17 * (`system/retention_telemetry.ts`), 200 rows a table a slice.
1618 *
1719 * The pace is the cost of the slice: after a slice of `t` ms with more behind it, the next
1820 * waits `t * (1 / DUTY - 1)` (at least `MIN_GAP_MS`), so a job takes at most `DUTY` of the thread
@@ -46,6 +48,7 @@ import {
4648 TICK_ROWS,
4749 } from "./retention_events.ts";
4850 import { pruneSamples, ROW_CAP } from "./retention_samples.ts";
51 import { pruneTelemetry, type Cursor } from "./retention_telemetry.ts";
4952
5053 /** The share of the thread one job may take while it has work behind it. */
5154 export const DUTY = 0.05;
@@ -98,6 +101,7 @@ export interface Retention {
98101 readonly samples: Job;
99102 readonly backfill: Job;
100103 readonly deploys: Job;
104 readonly telemetry: Job;
101105 /** Whether `deploy_landed` has had a full pass from the old ledger. */
102106 landedReady(): boolean;
103107 }
@@ -106,6 +110,7 @@ export function retentionJobs(app: App): Retention {
106110 const db = app.db;
107111 let filled = false;
108112 let cursor: { at: string; id: string } | undefined;
113 const walked: Cursor = { probe: 0, finding: 0 };
109114 const trimDeploys = deployRetention(
110115 db,
111116 undefined,
@@ -168,6 +173,14 @@ export function retentionJobs(app: App): Retention {
168173 : { did: r.deleted, more: r.more };
169174 },
170175 },
176 telemetry: {
177 // A pass that reached the window rests: what it would find next is a day younger at most.
178 idleMs: BACKFILL_EVERY_MS,
179 slice(now) {
180 const r = quietly(db, () => withoutWaiting(db, () => pruneTelemetry(db, now, walked)));
181 return r === undefined ? { did: 0, more: false } : { did: r.deleted, more: r.more };
182 },
183 },
171184 };
172185 }
173186
@@ -243,10 +256,18 @@ export function startRetention(app: App, which: { local: boolean; engine: boolea
243256 backfill(0);
244257 events(3_000);
245258 }
259 const telemetry = (delay: number): void => {
260 pending[5] = setTimeout(() => {
261 if (stopped) return;
262 if (held(telemetry)) return;
263 during("retention-telemetry", () => telemetry(work(jobs.telemetry, "probe and finding prune")), undefined, app);
264 }, delay);
265 };
246266 if (which.local) {
247267 live(1_000);
248268 samples(5_000);
249269 deploys(7_000);
270 telemetry(9_000);
250271 }
251272 return () => {
252273 stopped = true;
src/system/retention_telemetry.ts added +104
@@ -0,0 +1,104 @@
1 /**
2 * How long two kinds of telemetry are kept (#16572): `probe` (what a running app said when the
3 * forge knocked on its doors) and `preview_finding` (what `webspec()` found on a preview once it
4 * was live). Each grew without end: 56 and 76 MiB of production's live data on 2026-11-27.
5 *
6 * Every reader, and what it reaches:
7 * - `contract/probes.ts`: an app's newest probe (`latestProbes`) and its newest 30 (`listProbes`).
8 * - `core/preview_findings.ts`: the findings of one deploy run, shown beside a pull's check.
9 *
10 * So a row older than `KEEP_DAYS` goes, except an app's newest probe (its last word stays
11 * however long ago it was said) and the findings of the newest deploy of an environment that is
12 * still live: production, or the preview of a pull still open (`pull-<n>`). A pull that closed or
13 * landed, and any other environment, keeps nothing past the window: each pull is an environment of
14 * its own, so keeping every environment's newest would grow the table by a row a pull for ever.
15 * The newest deploy is the one created last (run ids are ULIDs, so they sort by creation time
16 * too, and break a tie of the same millisecond).
17 *
18 * The walk goes in `rowid` order from a cursor, a bounded slice at a time, and stops at the first
19 * row inside the window, so a slice never scans the table. Rows are inserted as they happen, so
20 * `rowid` order is age order only approximately: a VACUUM may renumber the rows of these
21 * TEXT-keyed tables, and then a pass may skip or revisit some until its cursor starts over, which
22 * the next pass does from the beginning.
23 */
24 import type { Database } from "bun:sqlite";
25
26 /** Days kept. */
27 export const KEEP_DAYS = 30;
28 /** Rows one slice walks at most. */
29 export const SLICE_ROWS = 200;
30
31 export interface Cursor {
32 probe: number;
33 finding: number;
34 }
35
36 /** One slice over both tables from `cursor` (moved in place); what it deleted and whether more is behind. */
37 export function pruneTelemetry(db: Database, now: number, cursor: Cursor, rows = SLICE_ROWS, keepMs = KEEP_DAYS * 86_400_000): { deleted: number; more: boolean } {
38 const cut = new Date(now - keepMs).toISOString();
39 const probes = walk(
40 db,
41 "SELECT rowid AS rid, created_at AS at, app_id AS owner FROM probe WHERE rowid > ?1 ORDER BY rowid LIMIT ?2",
42 (row) => db.query<{ n: number }, [string, number]>("SELECT 1 AS n FROM probe WHERE app_id = ?1 AND rowid <> ?2 AND (created_at, rowid) > (SELECT created_at, rowid FROM probe WHERE rowid = ?2) LIMIT 1").get(row.owner, row.rid) !== null,
outdated

This keeps the newest deploy of every env forever, including envs of closed pulls. Restrict the exemption to live environments, with a test for a closed pull's old findings.

43 "DELETE FROM probe WHERE rowid IN (SELECT value FROM json_each(?1))",
44 cursor.probe,
45 cut,
46 rows,
47 );
48 cursor.probe = probes.next;
49 const findings = walk(
50 db,
51 "SELECT rowid AS rid, at, run_id AS owner FROM preview_finding WHERE rowid > ?1 ORDER BY rowid LIMIT ?2",
52 // Kept only while it is what a page shows: the newest deploy of a live environment.
53 (row) =>
54 db
55 .query<{ n: number }, [string]>(
56 `SELECT 1 AS n FROM run r
57 WHERE r.id = ?1
58 AND (r.env = 'production'
59 OR (r.env GLOB 'pull-[0-9]*' AND EXISTS (
60 SELECT 1 FROM issue i WHERE i.repo_id = r.repo_id AND i.kind = 'pull' AND i.state = 'open'
61 AND i.number = CAST(substr(r.env, 6) AS INTEGER))))
62 AND NOT EXISTS (
63 SELECT 1 FROM run newer WHERE newer.repo_id = r.repo_id AND newer.env = r.env AND newer.kind = 'deploy'
64 AND (newer.created_at > r.created_at OR (newer.created_at = r.created_at AND newer.id > r.id)))`,
65 )
66 .get(row.owner) === null,
67 "DELETE FROM preview_finding WHERE rowid IN (SELECT value FROM json_each(?1))",
68 cursor.finding,
69 cut,
70 rows,
71 );
72 cursor.finding = findings.next;
73 return { deleted: probes.deleted + findings.deleted, more: probes.more || findings.more };
74 }
75
76 /**
77 * Walks up to `rows` rows after `from`: each older than `cut` and `stale` goes; the first inside
78 * the window ends the pass (the cursor goes back to the start for the next one).
79 */
80 function walk(
81 db: Database,
82 select: string,
83 stale: (row: { rid: number; owner: string }) => boolean,
84 remove: string,
85 from: number,
86 cut: string,
87 rows: number,
88 ): { deleted: number; more: boolean; next: number } {
89 const got = db.query<{ rid: number; at: string; owner: string }, [number, number]>(select).all(from, rows);
90 const gone: number[] = [];
91 let next = from;
92 for (const row of got) {
93 if (row.at >= cut) return { deleted: drop(db, remove, gone), more: false, next: 0 };
94 if (stale(row)) gone.push(row.rid);
95 next = row.rid;
96 }
97 const deleted = drop(db, remove, gone);
98 // A full slice of old rows: more may be behind it. A short one reached the end of the table.
99 return got.length === rows ? { deleted, more: true, next } : { deleted, more: false, next: 0 };
100 }
101
102 function drop(db: Database, remove: string, rowids: readonly number[]): number {
103 return rowids.length === 0 ? 0 : db.query<unknown, [string]>(remove).run(JSON.stringify(rowids)).changes;
104 }
test/job-slices.test.ts +1
@@ -253,6 +253,7 @@ function jobs(): Record<string, () => unknown> {
253253 "retention-samples": () => retention.samples.slice(Date.now()),
254254 "landed-backfill": () => retention.backfill.slice(Date.now()),
255255 "retention-deploys": () => retention.deploys.slice(Date.now()),
256 "retention-telemetry": () => retention.telemetry.slice(Date.now() + 40 * 86_400_000),
256257 };
257258 }
258259
test/retention-telemetry.test.ts added +107
@@ -0,0 +1,107 @@
1 /**
2 * Probes and preview findings past 30 days go (#16572), a bounded slice at a time, on the forge's
3 * own migrated schema: an app's newest probe stays, and so do the findings of the newest deploy of
4 * an environment still live (production, an open pull's preview); a closed pull's go.
5 */
6 import { afterAll, beforeAll, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createRepo } from "../src/actions/repos.ts";
11 import { createApp, type App } from "../src/app.ts";
12 import { recordProbe } from "../src/contract/probes.ts";
13 import { createApp as createAppRecord } from "../src/core/apps.ts";
14 import { createIssue } from "../src/core/issues.ts";
15 import { getRepoById } from "../src/core/repos.ts";
outdated

Hand-written schema: use the real migrations so a column change fails here, not silently in production.

16 import { createRun } from "../src/core/runs.ts";
17 import { createUser } from "../src/core/users.ts";
18 import { pruneTelemetry, type Cursor } from "../src/system/retention_telemetry.ts";
19
20 const DAY = 86_400_000;
21 const NOW = Date.parse("2026-11-27T12:00:00.000Z");
22 const ago = (days: number) => new Date(NOW - days * DAY).toISOString();
23
24 let dir: string;
25 let app: App;
26 let repoId = "";
27 let appId = "";
28 let other = "";
29
30 beforeAll(async () => {
31 dir = await mkdtemp(join(tmpdir(), "forge-retention-telemetry-"));
32 app = createApp({ dataDir: dir, port: 0 });
33 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
34 if (!made.ok) throw new Error(made.error);
35 const repo = await createRepo(app, made.value, { name: "shop", visibility: "public" });
36 if (!repo.ok) throw new Error(String(repo.error));
37 repoId = repo.value.id;
38 const record = createAppRecord(app.db, { repoId, slug: "shop", access: "public" });
39 if (!record.ok) throw new Error(String(record.error));
40 appId = record.value.id;
41 // A second app, probed once long ago and never since.
42 const second = await createRepo(app, made.value, { name: "cart", visibility: "public" });
43 if (!second.ok) throw new Error(String(second.error));
44 const cart = createAppRecord(app.db, { repoId: second.value.id, slug: "cart", access: "public" });
45 if (!cart.ok) throw new Error(String(cart.error));
46 other = cart.value.id;
47 // Pulls 1 (open) and 2 (closed), for their previews' environments.
48 for (const [title, state] of [["open one", "open"], ["closed one", "closed"]] as const) {
49 const pull = createIssue(app.db, { repoId, authorId: made.value.id, title, kind: "pull" });
50 if (!pull.ok) throw new Error(String(pull.error));
51 if (state === "closed") app.db.query("UPDATE issue SET state = 'closed' WHERE id = ?1").run(pull.value.id);
52 }
53 });
54
55 afterAll(async () => {
56 app.close();
57 await rm(dir, { recursive: true, force: true });
58 });
59
60 const probe = (appOf: string, days: number) => {
61 const repo = getRepoById(app.db, repoId)!;
62 const row = recordProbe(app.db, appOf, { repo, commitOid: "abc1234", at: ago(days), verdict: "ok", said: [], knocks: [] });
63 app.db.query("UPDATE probe SET created_at = ?2 WHERE id = ?1").run(row.id, ago(days));
64 return row.id;
65 };
66 const deploy = (env: string, days: number) => {
67 const run = createRun(app.db, { repoId, kind: "deploy", env });
68 app.db.query("UPDATE run SET created_at = ?2 WHERE id = ?1").run(run.id, ago(days));
69 app.db.query("INSERT INTO preview_finding (run_id, at, findings) VALUES (?1, ?2, '[]')").run(run.id, ago(days));
70 return run.id;
71 };
72 const sweep = () => {
73 const cursor: Cursor = { probe: 0, finding: 0 };
74 let r = pruneTelemetry(app.db, NOW, cursor, 3);
75 while (r.more) r = pruneTelemetry(app.db, NOW, cursor, 3);
76 return cursor;
77 };
78 const left = (sql: string) => app.db.query<{ id: string }, []>(sql).all().map((r) => r.id);
79
80 test("old probes go, and an app's newest stays however old", () => {
81 const gone = [probe(appId, 60), probe(appId, 50)];
82 const kept = [probe(other, 95), probe(appId, 2)];
83 expect(sweep()).toEqual({ probe: 0, finding: 0 });
84 const ids = left("SELECT id FROM probe");
85 for (const id of kept) expect(ids).toContain(id);
86 for (const id of gone) expect(ids).not.toContain(id);
87 });
88
89 test("findings stay only for the newest deploy of a live environment; a closed pull's go however new its deploy", () => {
90 const oldProduction = deploy("production", 70);
91 const production = deploy("production", 40);
92 const openPull = deploy("pull-1", 60);
93 const closedPull = deploy("pull-2", 60);
94 const elsewhere = deploy("b1234567", 45);
95 sweep();
96 const ids = left("SELECT run_id AS id FROM preview_finding");
97 expect(ids.sort()).toEqual([openPull, production].sort());
98 for (const id of [oldProduction, closedPull, elsewhere]) expect(ids).not.toContain(id);
99 });
100
101 test("rows inside the window stop the walk without a delete", () => {
102 const fresh = deploy("pull-2", 1);
103 const before = left("SELECT run_id AS id FROM preview_finding").length;
104 sweep();
105 expect(left("SELECT run_id AS id FROM preview_finding")).toContain(fresh);
106 expect(left("SELECT run_id AS id FROM preview_finding").length).toBe(before);
107 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs