// PEP-220: how long the work journals live. Classes (the audit table is in the change's design.md): // · work journal — `workDays` (1 day): noise events, sent outbox rows, finished runner commands, // CI/release log tails, expired temporary `settings` rows; // · state — `stateDays` (7 days): CI runs of closed stories; // · business history (`task_updated`, `question_answered`, comments, switches …) is NOT touched here. // Deleting is done in batches of BATCH rows: `BEGIN IMMEDIATE` of a long delete would block the // writes of every other process. import type { Db } from "@peppa/db"; import { getSetting, setSetting } from "./settings.ts"; export const RETENTION_KEY = "platform.retention"; export const RETENTION_LAST_KEY = "retention.last"; export const BATCH = 5000; /** Batches per table per run — a backlog is eaten over several hourly runs, never in one long hold. */ const MAX_BATCHES = 20; /** Events that are journal noise: nobody reads them after the day is over (see the audit table). */ export const NOISE_EVENTS = [ "step", "turn_end", "auto_continue", "claude_session", "claude_session_end", "notification", "input_sent", "capacity_wait", "secrets_issued", "awaiting_review", "awaiting_automerge", "awaiting_checks", "terminal_input", ] as const; /** `settings` keys that live minutes (login flows, link codes, brute-force counters). */ export const TEMP_SETTING_PREFIXES = ["egov.flow:", "google.flow:", "chat.link:", "auth.fail:"] as const; export type RetentionConfig = { workDays: number; stateDays: number }; export const DEFAULT_RETENTION: RetentionConfig = { workDays: 1, stateDays: 7 }; export async function getRetention(db: Db): Promise { const saved = (await getSetting>(db, RETENTION_KEY)) ?? {}; const days = (v: unknown, d: number) => (typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : d); return { workDays: days(saved.workDays, DEFAULT_RETENTION.workDays), stateDays: days(saved.stateDays, DEFAULT_RETENTION.stateDays) }; } export const setRetention = (db: Db, c: Partial) => setSetting(db, RETENTION_KEY, c); export type RetentionResult = { at: number; deleted: Record; total: number; freedBytes: number; dbBytes: number; vacuumed: boolean }; type Raw = { prepare(sql: string): { run(...a: unknown[]): { changes: number | bigint }; get(...a: unknown[]): unknown } }; const raw = (db: Db) => (db as unknown as { $client: Raw }).$client; /** Deletes `where` rows of `table` in batches; returns how many went. */ function purge(db: Db, table: string, where: string, params: unknown[]): number { const c = raw(db); let total = 0; for (let i = 0; i < MAX_BATCHES; i++) { const n = Number(c.prepare(`DELETE FROM ${table} WHERE id IN (SELECT id FROM ${table} WHERE ${where} LIMIT ${BATCH})`).run(...params).changes); total += n; if (n < BATCH) break; } return total; } /** Clears a text column of `where` rows in batches. */ function blank(db: Db, table: string, column: string, where: string, params: unknown[]): number { const c = raw(db); let total = 0; for (let i = 0; i < MAX_BATCHES; i++) { const n = Number(c.prepare(`UPDATE ${table} SET ${column} = NULL WHERE id IN (SELECT id FROM ${table} WHERE ${column} IS NOT NULL AND ${where} LIMIT ${BATCH})`).run(...params).changes); total += n; if (n < BATCH) break; } return total; } const pragma = (db: Db, name: string): number => { const row = raw(db).prepare(`PRAGMA ${name}`).get() as Record | undefined; return row ? Number(Object.values(row)[0] ?? 0) : 0; }; /** One pass of the cleanup. `daily` also optimizes and gives the free pages back. */ export async function runRetention(db: Db, o: { now?: Date; daily?: boolean } = {}): Promise { const now = (o.now ?? new Date()).getTime(); const cfg = await getRetention(db); const work = now - cfg.workDays * 86_400_000; const state = now - cfg.stateDays * 86_400_000; const deleted: Record = {}; const marks = NOISE_EVENTS.map(() => "?").join(","); deleted.events = purge(db, "events", `type IN (${marks}) AND created_at < ?`, [...NOISE_EVENTS, work]); // The last run of every check of a story still open keeps its log; the rest of the tails go. deleted.check_log = blank( db, "check_runs", "log_tail", `updated_at < ? AND NOT (task_id IS NOT NULL AND task_id IN (SELECT id FROM tasks WHERE status NOT IN ('done') AND archived_at IS NULL) AND NOT EXISTS (SELECT 1 FROM check_runs n WHERE n.task_id = check_runs.task_id AND n."check" = check_runs."check" AND n.id > check_runs.id))`, [work], ); deleted.check_runs = purge(db, "check_runs", `updated_at < ? AND (task_id IS NULL OR task_id IN (SELECT id FROM tasks WHERE status = 'done' OR archived_at IS NOT NULL))`, [state]); // The newest release of every environment keeps its log (the first thing to read after a failure). deleted.release_log = blank(db, "releases", "log_tail", `updated_at < ? AND EXISTS (SELECT 1 FROM releases n WHERE n.project_id = releases.project_id AND n.env = releases.env AND n.id > releases.id)`, [work]); // A sent message of an open question stays: the bot matches its repeats against it (PEP-151). deleted.telegram_outbox = purge( db, "telegram_outbox", `status IN ('sent','failed') AND created_at < ? AND chat_message_id IS NULL AND (question_id IS NULL OR question_id NOT IN (SELECT id FROM questions WHERE answered_at IS NULL))`, [work], ); deleted.push_outbox = purge(db, "push_outbox", `status IN ('sent','failed') AND created_at < ?`, [work]); deleted.runner_commands = purge(db, "runner_commands", `status IN ('done','failed','expired') AND created_at < ?`, [work]); const c = raw(db); let tu = 0; for (let i = 0; i < MAX_BATCHES; i++) { const n = Number(c.prepare(`DELETE FROM telegram_updates WHERE update_id IN (SELECT update_id FROM telegram_updates WHERE status != 'dispatching' AND created_at < ? LIMIT ${BATCH})`).run(work).changes); tu += n; if (n < BATCH) break; } deleted.telegram_updates = tu; const like = TEMP_SETTING_PREFIXES.map(() => "key LIKE ?").join(" OR "); deleted.settings = Number(c.prepare(`DELETE FROM settings WHERE (${like}) AND updated_at < ?`).run(...TEMP_SETTING_PREFIXES.map((p) => `${p}%`), work).changes); const total = Object.values(deleted).reduce((a, b) => a + b, 0); let vacuumed = false; let freedBytes = 0; if (o.daily) { const before = pragma(db, "freelist_count"); // No-op unless auto_vacuum is incremental; the freed pages are reused either way. c.prepare("PRAGMA incremental_vacuum(4000)").run(); c.prepare("PRAGMA optimize").run(); freedBytes = Math.max(0, before - pragma(db, "freelist_count")) * pragma(db, "page_size"); vacuumed = true; } const pageSize = pragma(db, "page_size"); // What can be reused by new rows without growing the file. const reusable = pragma(db, "freelist_count") * pageSize; const result: RetentionResult = { at: now, deleted, total, freedBytes: freedBytes || reusable, dbBytes: pragma(db, "page_count") * pageSize, vacuumed }; await setSetting(db, RETENTION_LAST_KEY, result); return result; } export const getLastRetention = (db: Db) => getSetting(db, RETENTION_LAST_KEY);