peppa/packages/core/src/retention.ts

191 lines
10 KiB
TypeScript

// 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";
import { archiveEvents, archiveLogs, expireHistory, expireLogs, historyCursor, type ArchivedLog, type LogKind } from "./history.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;
/**
* PEP-221: `mainDays` — business events of closed stories and of the project stay this long in the
* main database once archived; `journalDays`, `metricsDays`, `logDays` — terms of the archive.
*/
export type RetentionConfig = { workDays: number; stateDays: number; mainDays: number; journalDays: number; metricsDays: number; logDays: number };
export const DEFAULT_RETENTION: RetentionConfig = { workDays: 1, stateDays: 7, mainDays: 7, journalDays: 90, metricsDays: 365, logDays: 7 };
/** The discussion of a story: shown on the page of an accepted story and in the ready digest. */
export const MAIN_KEEP_EVENTS = ["pm_comment", "intake_note", "proposal_approved"] as const;
export async function getRetention(db: Db): Promise<RetentionConfig> {
const saved = (await getSetting<Partial<RetentionConfig>>(db, RETENTION_KEY)) ?? {};
const days = (v: unknown, d: number) => (typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : d);
const k = (key: keyof RetentionConfig) => days(saved[key], DEFAULT_RETENTION[key]);
return { workDays: k("workDays"), stateDays: k("stateDays"), mainDays: k("mainDays"), journalDays: k("journalDays"), metricsDays: k("metricsDays"), logDays: k("logDays") };
}
export const setRetention = (db: Db, c: Partial<RetentionConfig>) => setSetting(db, RETENTION_KEY, c);
export type RetentionResult = { at: number; deleted: Record<string, number>; archived?: Record<string, number>; 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;
}
/** PEP-221: what goes into the log archive of a row about to lose its tail. */
const LOG_ROW: Record<LogKind, { table: string; cols: string; map: (r: Record<string, unknown>) => ArchivedLog }> = {
checks: {
table: "check_runs",
cols: `id, project_id, task_id, sha, "check", state, updated_at, log_tail`,
map: (r) => ({ id: Number(r.id), projectId: Number(r.project_id), taskId: r.task_id == null ? null : Number(r.task_id), sha: r.sha as string, check: r.check as string, state: r.state as string, at: Number(r.updated_at), log: String(r.log_tail) }),
},
releases: {
table: "releases",
cols: "id, project_id, sha, env, status, updated_at, log_tail",
map: (r) => ({ id: Number(r.id), projectId: Number(r.project_id), sha: r.sha as string, env: r.env as string, state: r.status as string, at: Number(r.updated_at), log: String(r.log_tail) }),
},
};
/** Clears a text column of `where` rows in batches; log tails are archived first (PEP-221). */
function blank(db: Db, table: string, column: string, where: string, params: unknown[], archive?: LogKind): number {
const c = raw(db);
let total = 0;
for (let i = 0; i < MAX_BATCHES; i++) {
const pick = `SELECT id FROM ${table} WHERE ${column} IS NOT NULL AND ${where} LIMIT ${BATCH}`;
if (archive) {
const spec = LOG_ROW[archive];
const rows = db.$client.db.prepare(`SELECT ${spec.cols} FROM ${spec.table} WHERE id IN (${pick})`).all(...(params as never[])) as Record<string, unknown>[];
if (rows.length) archiveLogs(archive, rows.map(spec.map));
}
const n = Number(c.prepare(`UPDATE ${table} SET ${column} = NULL WHERE id IN (${pick})`).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<string, number> | 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<RetentionResult> {
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<string, number> = {};
const marks = NOISE_EVENTS.map(() => "?").join(",");
// PEP-221: business history goes to history.db first; only archived rows may leave the main base.
const archived: Record<string, number> = { events: archiveEvents(db, { now: o.now, skipTypes: NOISE_EVENTS }) };
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],
"checks",
);
deleted.check_runs = purge(db, "check_runs", `updated_at < ? AND log_tail IS NULL 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], "releases");
// Archived business events of closed stories and of the project, past `mainDays`. Events of an open
// story stay (reviewer, model escalation, refinement read them), and so does a story's discussion.
const keep = MAIN_KEEP_EVENTS.map(() => "?").join(",");
deleted.history_events = purge(
db,
"events",
`id <= ? AND created_at < ? AND type NOT IN (${keep})
AND (task_id IS NULL OR task_id IN (SELECT id FROM tasks WHERE status = 'done' OR archived_at IS NOT NULL))
AND (session_id IS NULL OR session_id IN (SELECT id FROM sessions WHERE status IN ('done','failed')))`,
[historyCursor(), now - cfg.mainDays * 86_400_000, ...MAIN_KEEP_EVENTS],
);
const exp = expireHistory({ now: o.now, journalDays: cfg.journalDays, metricsDays: cfg.metricsDays });
archived.expired_journal = exp.journal;
archived.expired_metrics = exp.metrics;
archived.expired_log_files = expireLogs({ now: o.now, days: cfg.logDays });
// 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, archived, 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<RetentionResult>(db, RETENTION_LAST_KEY);