diff --git a/docs/rollouts/2026-12-03-collector-sweep-followups.md b/docs/rollouts/2026-12-03-collector-sweep-followups.md new file mode 100644 index 00000000..919368d3 --- /dev/null +++ b/docs/rollouts/2026-12-03-collector-sweep-followups.md @@ -0,0 +1,113 @@ +# Two ways the receipt sweep could get it wrong + +**Date:** 2026-12-03 **Seat:** ZC **Session:** `sess_6ab61beb-b36e-4e27-b44f-5bf2948f67d3` +**Files:** `scripts/lib/collector-sentry-bridge.mjs`, `scripts/prune-collector-sentry-outboxes.mjs`, +`scripts/minimax-runtime-usage-collector.mjs`, `scripts/test-collector-sentry-outboxes.mjs` +**Rows:** UM-1684 (follow-up) +**Found by:** Jet (peer review of #2124) and by running the sweep on the host + +## What was wrong + +The receipt sweep finds a producer's checkpoint by the producer's name, and it checks +that the checkpoint file records that same producer.  That is the right rule, because a +watermark authorizes the deletion of receipts and must belong to the collector whose +receipts it would allow to go. + +One collector does not use the same name for both.  The minimax collector checkpoints +under its state key, `minimax-runtime`, while its outbox belongs to the producer +`minimax-code`, so the two names never match.  The sweep reported that outbox as +`no-checkpoint` and left it alone, which is the safe answer and the wrong one: the +receipts in that outbox were never pruned, and it is the largest of the six on this +host.  Its checkpoint was written moments before the sweep ran, so the watermark was +there the whole time. + +Every other collector uses one name for both, which is why the sweep found four of the +six outboxes and skipped only this one and the botfleet outbox, which has no checkpoint +because no botfleet collector runs here. + +## The fix + +The collector is the only side that knows both names, so the collector records the key it +checkpoints under, in the identity row the outbox already carries.  The sweep reads that +key and looks the checkpoint up by it, checking that the file records the key it is named +after.  Without the recorded key the sweep still falls back to the producer's own name, +and an outbox whose checkpoint cannot be found is still skipped. + +The fallback matters: a checkpoint from another collector must never authorize the +deletion of these receipts, so the match stays exact. + +## Verification + +`scripts/test-collector-sentry-outboxes.mjs` passes 25 assertions.  The two new ones +cover the outbox whose checkpoint is filed under the collector's state key, which is now +pruned, and the same outbox without the recorded key, which is still skipped and keeps +its receipts.  The first of the two fails against the code before this change. + +The key is recorded on both paths the collector takes.  The pass that finds nothing to +send knows the key because it writes the checkpoint, and the pass that finds events to +send now carries it as well, because that pass is the one that writes the outbox's +identity row.  An identity recorded without a key keeps the key that was already +recorded, so neither pass can reset the other. + +## The second way: a collector could write into the outbox as it was removed + +Jet raised this on the first review of #2124, and it is right: the sweep counted an +outbox's receipts, and if the count was zero it removed the directory.  A collector +writing into that outbox at that moment would lose the row it was writing, because the +count and the removal were not one step.  The count closes the database handle before the +removal, and the enqueue path shares no guard with the sweep. + +The fix is the lock the collector's own writes already take.  The reclaim opens the +outbox, takes the write lock, counts under it, and removes the directory while it still +holds it.  A collector that was already writing either holds the lock itself - so the +removal waits for it and then sees the row - or waits for the lock, and its write fails +loudly rather than disappearing into a directory that is being removed.  A collector +that writes after the removal recreates the directory, which is the directory it wanted. + +A regression test reproduces the window Jet named: the sweep has counted the outbox +empty, and a collector writes into it at that moment.  Without the lock the outbox is +removed and the row goes with it; with it the outbox is left in place and the sweep +reports why. + +## What the review found on top of that + +The review of this pull request left four findings open, and all four were real. + +The checkpoint key was carried only by the pass that finds nothing to send, so a +collector whose passes always find events never recorded it at all, and the sweep kept +reporting its outbox as `no-checkpoint`.  The key now travels with the identity on the +path that writes the outbox, and an identity recorded without a key keeps the one that +was already recorded. + +The checkpoint file was read without being validated, even though a watermark +authorizes the deletion of receipts and the file is untrusted input.  It is now checked +against a schema before any of its fields are read. + +The reclaim took the write lock with a bare `BEGIN IMMEDIATE`, whose wait is capped by +the connection's short busy timeout, so a collector write that ran longer than that +failed the outbox rather than being waited for.  The reclaim now retries a busy +database, and the outbox's schema is checked with reads before it is changed, so a +maintenance job no longer needs the write lock merely to open an outbox.  The busy check +lives in the bridge, where the collector and the maintenance job can both reach it. + +## What the review found on the reclaim as well + +The review of the merged pull request found a third way the reclaim could get it wrong, +and it is the same window Jet named, one step further on. + +A collector that had already opened the outbox when the reclaim removed it is waiting for +the lock, and two things can then happen to its write. It can fail with an I/O error, +because the write-ahead log it needs went with the directory, or it can succeed, because +a connection that already holds that log open writes into it happily. In the second case +the receipt lands in a file no path points at, and the collector is told it stored a +receipt that is gone. + +The write now compares the file the path points at before and after the write, by device +and inode, and writes the receipt again when the path no longer holds what was written +into it. A write that failed with the I/O error is retried once, because the outbox is +simply gone and a new one is the answer. + +The test file passes 30 assertions.  The four new ones cover an identity that keeps +its recorded key, a checkpoint file of the wrong shape, the reclaim waiting for a +collector's write instead of failing the outbox, and a receipt written into an outbox +that was reclaimed being written again. diff --git a/scripts/lib/collector-sentry-bridge.mjs b/scripts/lib/collector-sentry-bridge.mjs index 59321c32..659ab1ea 100644 --- a/scripts/lib/collector-sentry-bridge.mjs +++ b/scripts/lib/collector-sentry-bridge.mjs @@ -1,5 +1,5 @@ import { createHash, randomUUID } from "node:crypto"; -import { mkdir, chmod, readFile, stat } from "node:fs/promises"; +import { mkdir, chmod, readFile, rm, stat } from "node:fs/promises"; import { DatabaseSync } from "node:sqlite"; import { execFile } from "node:child_process"; import { promisify } from "node:util"; @@ -120,6 +120,26 @@ async function processBirth(pid) { } } +/** + * Make sure the outbox holds the schema the collectors use. + * + * The statements need the write lock, and a collector writing at this moment + * holds it, so a job that only reads an outbox would fail whenever a + * collector happened to be writing. The schema is therefore read first, and + * changed only when it really is missing something. + */ +function ensureOutboxSchema(db) { + const tables = db.prepare("SELECT name FROM sqlite_master WHERE type='table'").all().map((row) => row.name); + if (!tables.includes("events")) { + db.exec("CREATE TABLE IF NOT EXISTS events (id TEXT PRIMARY KEY, payload TEXT NOT NULL, state TEXT NOT NULL DEFAULT 'pending', owner TEXT, pid INTEGER, birth TEXT, sent_at INTEGER)"); + } + const columns = db.prepare("PRAGMA table_info(events)").all().map((column) => column.name); + if (!columns.includes("birth")) db.exec("ALTER TABLE events ADD COLUMN birth TEXT"); + if (!columns.includes("sent_at")) db.exec("ALTER TABLE events ADD COLUMN sent_at INTEGER"); + if (!columns.includes("retry_batch_size")) db.exec("ALTER TABLE events ADD COLUMN retry_batch_size INTEGER NOT NULL DEFAULT 100"); + if (!tables.includes("metadata")) db.exec("CREATE TABLE IF NOT EXISTS metadata (key TEXT PRIMARY KEY, value TEXT NOT NULL)"); +} + async function openOutbox(root, { create = true } = {}) { const path = join(root, "outbox.sqlite"); if (create) await mkdir(root, { recursive: true, mode: 0o700 }); @@ -128,21 +148,17 @@ async function openOutbox(root, { create = true } = {}) { try { await chmod(path, 0o600); db.exec("PRAGMA busy_timeout=1000; PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;"); - db.exec("CREATE TABLE IF NOT EXISTS events (id TEXT PRIMARY KEY, payload TEXT NOT NULL, state TEXT NOT NULL DEFAULT 'pending', owner TEXT, pid INTEGER, birth TEXT, sent_at INTEGER)"); - if (!db.prepare("PRAGMA table_info(events)").all().some((column) => column.name === "birth")) db.exec("ALTER TABLE events ADD COLUMN birth TEXT"); - if (!db.prepare("PRAGMA table_info(events)").all().some((column) => column.name === "sent_at")) db.exec("ALTER TABLE events ADD COLUMN sent_at INTEGER"); - if (!db.prepare("PRAGMA table_info(events)").all().some((column) => column.name === "retry_batch_size")) db.exec("ALTER TABLE events ADD COLUMN retry_batch_size INTEGER NOT NULL DEFAULT 100"); - db.exec("CREATE TABLE IF NOT EXISTS metadata (key TEXT PRIMARY KEY, value TEXT NOT NULL)"); + ensureOutboxSchema(db); } catch (error) { db.close(); throw error; } return db; } -export async function flushCollectorSentry({ producerId, producerInstanceId, dryRun, log = console.log }) { +export async function flushCollectorSentry({ producerId, producerInstanceId, checkpointKey, dryRun, log = console.log }) { if (dryRun) return; try { const config = collectorSentryConfig(process.env, producerId); if (!config) return; - const root = await enqueueCollectorSentry([], { producerId, producerInstanceId: producerInstanceId || process.env.USAGE_MACHINE_ID?.trim() || hostname() }, config); + const root = await enqueueCollectorSentry([], { producerId, producerInstanceId: producerInstanceId || process.env.USAGE_MACHINE_ID?.trim() || hostname(), checkpointKey }, config); const result = await drainCollectorSentry(root, config); if (result.pending) log("WARNING: collector Sentry delivery pending in durable outbox"); if (result.quarantined) log(`WARNING: ${result.quarantined} collector Sentry event(s) quarantined in durable outbox`); @@ -165,14 +181,7 @@ export async function enqueueCollectorSentryTelemetry(events, identity, config) async function persistCollectorSentry(events, identity, config) { const root = join(config.stateRoot, hash(JSON.stringify([identity.producerId, identity.producerInstanceId || hostname(), config.destination || "sentry", config.endpoint]))); - const db = await openOutbox(root); - try { - db.exec("BEGIN IMMEDIATE"); - const insert = db.prepare("INSERT OR IGNORE INTO events (id, payload) VALUES (?, ?)"); - for (const event of events) insert.run(event.eventId, JSON.stringify(event)); - db.exec("COMMIT"); - } catch (error) { if (db.isTransaction) db.exec("ROLLBACK"); throw error; } - finally { db.close(); } + await writeCollectorSentryReceipts(root, events); // Record which producer this outbox belongs to. The outbox directory is // named by a HASH of the identity, so without this row a maintenance job // cannot tell which producer's checkpoint applies to it and has to skip it. @@ -184,6 +193,80 @@ async function persistCollectorSentry(events, identity, config) { return root; } +/** + * Write the receipts into the outbox at the path. + * + * A reclaim removes an empty outbox while holding the lock the collector's + * writes take, so a collector that had already opened the outbox is waiting + * for that lock when the directory goes. Two things can then happen, and both + * lose the receipt. The write can fail with an I/O error, because the + * write-ahead log it needs went with the directory; or it can succeed, because + * a connection that already holds that log open writes into it happily, and + * the receipt lands in a file no path points at. + * + * So the path is checked after the write: the file the path points at has to + * be the file the receipt was written into, and the receipt is written again + * when it is not. The write is also retried once, because the outbox is + * simply gone and a new one is the answer. + */ +export async function writeCollectorSentryReceipts(root, events, { onOpen } = {}) { + let lastError = null; + for (let attempt = 0; attempt < 2; attempt += 1) { + const db = await openOutbox(root); + try { + // The file this connection holds, so the path can be compared with it + // after the write. + const opened = await outboxFileIdentity(root); + // The hook lets a test act between the open and the write, which is + // where the reclaim removes the outbox from under the collector. + if (onOpen) await onOpen(db); + db.exec("BEGIN IMMEDIATE"); + const insert = db.prepare("INSERT OR IGNORE INTO events (id, payload) VALUES (?, ?)"); + for (const event of events) insert.run(event.eventId, JSON.stringify(event)); + db.exec("COMMIT"); + const current = await outboxFileIdentity(root); + if (opened && current && opened.dev === current.dev && opened.ino === current.ino) return; + lastError = new Error("The collector outbox was reclaimed while the receipt was written"); + } catch (error) { + if (db.isTransaction) { + try { db.exec("ROLLBACK"); } catch { /* the file is gone; the lock goes with the handle */ } + } + if (!isOutboxRemovedError(error)) throw error; + lastError = error; + } finally { + db.close(); + } + } + throw lastError ?? new Error("The collector receipt could not be stored"); +} + +/** + * Which file the outbox path points at, or null when it points at none. + * + * The device and inode together say whether the path still holds the file + * that was written to, which is what a removal under the writer changes. + */ +async function outboxFileIdentity(root) { + try { + const info = await stat(join(root, "outbox.sqlite")); + return { dev: info.dev, ino: info.ino }; + } catch { + return null; + } +} + +/** + * Whether the error says the outbox's directory went away under the write. + * + * SQLite reports it as an I/O error, because the write-ahead log it needs was + * removed with the directory. A disk that is genuinely failing reports the + * same thing, and that write fails again on the retry and is reported. + */ +function isOutboxRemovedError(error) { + const message = error instanceof Error ? error.message : String(error ?? ""); + return error?.errcode === 1802 || /disk I\/O error|unable to open database file/i.test(message); +} + /** * Record which producer an outbox belongs to. * @@ -196,10 +279,26 @@ async function persistCollectorSentry(events, identity, config) { export async function recordCollectorSentryIdentity(root, identity) { const db = await openOutbox(root); try { + // A pass that sends events does not know the checkpoint key, while the + // pass that finds nothing to send does. The key that was already + // recorded is therefore kept when this call does not carry one, so the + // event path cannot reset it and leave the outbox unprunable. + const recorded = db.prepare("SELECT value FROM metadata WHERE key='identity'").get(); + let previous = null; + if (recorded) { + try { previous = JSON.parse(recorded.value); } catch { previous = null; } + } + const known = typeof previous?.checkpointKey === "string" && previous.checkpointKey ? previous.checkpointKey : null; db.prepare("INSERT INTO metadata (key,value) VALUES ('identity',?) ON CONFLICT(key) DO UPDATE SET value=excluded.value").run( JSON.stringify({ producerId: identity.producerId, producerInstanceId: identity.producerInstanceId || hostname(), + // The collector's checkpoint is named after its STATE KEY, which is not + // always the producer id: the minimax collector checkpoints under + // "minimax-runtime" while its outbox belongs to "minimax-code". A + // maintenance job needs to know which checkpoint governs this outbox, + // and the collector is the only side that knows both. + checkpointKey: identity.checkpointKey || known || null, }), ); } finally { @@ -237,6 +336,7 @@ const OutboxIdentity = z .object({ producerId: z.string().min(1), producerInstanceId: z.string().min(1).nullish(), + checkpointKey: z.string().min(1).nullish(), }) .passthrough(); @@ -263,6 +363,7 @@ export async function readCollectorSentryIdentity(root) { return { producerId: parsed.data.producerId, producerInstanceId: parsed.data.producerInstanceId ?? null, + checkpointKey: parsed.data.checkpointKey ?? null, }; } catch { return null; @@ -305,6 +406,90 @@ export async function readCollectorSentryProducerFromReceipts(root) { } } +/** + * Remove an outbox that holds no receipts, while holding its write lock. + * + * The lock is the one the collector's own writes take, so a collector that is + * writing at that moment either already holds it - and the removal waits for + * it and then sees the row - or waits for it, and its write fails loudly + * instead of landing in a directory that is being removed. Removing the + * directory while the lock is held is what closes the window between counting + * the receipts and removing them. + * + * The result says whether the outbox was removed, and how many receipts it + * held when the lock was taken. + */ +export async function reclaimEmptyCollectorSentryOutbox(root) { + const db = await openOutboxForReclaim(root); + try { + const row = db.prepare("SELECT COUNT(*) AS n FROM events").get(); + const receipts = typeof row?.n === "number" ? row.n : 0; + if (receipts !== 0) { + db.exec("ROLLBACK"); + return { reclaimed: false, receipts }; + } + // The database file is unlinked while the lock is held. The connection + // keeps working on the unlinked file, so the rollback below still ends the + // transaction cleanly, and a collector that writes afterwards recreates the + // directory rather than writing into a removed one. + await rm(root, { recursive: true, force: true }); + db.exec("ROLLBACK"); + return { reclaimed: true, receipts: 0 }; + } catch (error) { + if (db.isTransaction) { + try { db.exec("ROLLBACK"); } catch { /* the file is gone; the lock is released with the handle */ } + } + throw error; + } finally { + db.close(); + } +} + +/** + * Open an outbox and take its write lock, waiting for a collector that holds + * it. + * + * The collector's own write takes this lock, so a busy database is worth + * another try: the reclaim is the step that removes an empty outbox, and a + * collector that happens to be writing at that moment should not leave the + * outbox behind for the next sweep. The wait covers opening the outbox as + * well, because a schema that has to be changed needs the same lock. + */ +async function openOutboxForReclaim(root) { + for (let attempt = 0; ; attempt += 1) { + let db = null; + try { + db = await openOutbox(root, { create: false }); + db.exec("BEGIN IMMEDIATE"); + return db; + } catch (error) { + if (db) { + try { if (db.isTransaction) db.exec("ROLLBACK"); } catch { /* the lock was never taken */ } + db.close(); + } + if (!isBusyDatabase(error) || attempt >= LOCK_ATTEMPTS - 1) throw error; + await new Promise((resolve) => setTimeout(resolve, LOCK_BACKOFF_MS * (attempt + 1))); + } + } +} + +/** + * Whether an error is SQLite reporting that another process holds the lock. + * + * The collector and this maintenance job share the outbox, so a busy database + * is a normal state rather than a failure, and both sides need to recognise + * it the same way. + */ +export function isBusyDatabase(error) { + const code = error?.code ?? ""; + const message = error instanceof Error ? error.message : String(error ?? ""); + return code === "SQLITE_BUSY" || /database is locked|database table is locked/i.test(message); +} + +/** How many times a busy lock is waited for, and how long between the tries. */ +const LOCK_ATTEMPTS = 3; +const LOCK_BACKOFF_MS = 250; + /** * How many receipts an outbox still holds, in any state, or null when that * cannot be read. diff --git a/scripts/lib/session-token-collectors.mjs b/scripts/lib/session-token-collectors.mjs index 2b495509..468c8a0b 100644 --- a/scripts/lib/session-token-collectors.mjs +++ b/scripts/lib/session-token-collectors.mjs @@ -1097,6 +1097,7 @@ export async function postUsageBatches({ ingestToken, producerId, producerInstanceId, + checkpointKey, dryRun = false, log = console.log, }) { @@ -1116,7 +1117,11 @@ export async function postUsageBatches({ let spoolError; try { sentryConfig = collectorSentryConfig(process.env, producerId); - if (sentryConfig) sentryRoot = await enqueueCollectorSentry(events, { producerId, producerInstanceId: bodyFor([]).producerInstanceId }, sentryConfig); + // The checkpoint key travels with the identity, because the outbox's + // identity row is written on this path: a collector whose passes always + // find events would otherwise never record which checkpoint governs its + // outbox, and the sweep could not prune it. + if (sentryConfig) sentryRoot = await enqueueCollectorSentry(events, { producerId, producerInstanceId: bodyFor([]).producerInstanceId, checkpointKey }, sentryConfig); } catch { spoolError = true; log("WARNING: collector Sentry outbox unavailable; Usage Monitor delivery continues"); diff --git a/scripts/minimax-runtime-usage-collector.mjs b/scripts/minimax-runtime-usage-collector.mjs index 344f8828..bac12892 100644 --- a/scripts/minimax-runtime-usage-collector.mjs +++ b/scripts/minimax-runtime-usage-collector.mjs @@ -233,7 +233,10 @@ async function main() { log(`models: ${[...models].join(", ") || "(none)"}`); } if (events.length === 0) { - await flushCollectorSentry({ producerId: MINIMAX_RUNTIME_PRODUCER_ID, dryRun: DRY || args.dryRun, log }); + // The checkpoint is written under the state key, so the outbox records + // that key: a maintenance job that prunes the outbox needs to know which + // checkpoint governs it, and the two names are not the same. + await flushCollectorSentry({ producerId: MINIMAX_RUNTIME_PRODUCER_ID, checkpointKey: MINIMAX_RUNTIME_STATE_KEY, dryRun: DRY || args.dryRun, log }); log("nothing to send"); const scanComplete = events.truncated !== true; if (!DRY && canAdvanceCollectorCheckpoint(args, { scanComplete })) { @@ -254,6 +257,11 @@ async function main() { ingestUrl, ingestToken: token, producerId: MINIMAX_RUNTIME_PRODUCER_ID, + // The checkpoint is written under the state key, so the outbox records + // that key on this path too: a maintenance job that prunes the outbox + // needs to know which checkpoint governs it, and the two names are not + // the same. + checkpointKey: MINIMAX_RUNTIME_STATE_KEY, dryRun: DRY || args.dryRun, log, }); diff --git a/scripts/prune-collector-sentry-outboxes.mjs b/scripts/prune-collector-sentry-outboxes.mjs index 8c226133..4e81454e 100644 --- a/scripts/prune-collector-sentry-outboxes.mjs +++ b/scripts/prune-collector-sentry-outboxes.mjs @@ -33,13 +33,16 @@ * [--dry-run] */ -import { readdir, readFile, rm, stat } from "node:fs/promises"; +import { readdir, readFile, stat } from "node:fs/promises"; import { homedir } from "node:os"; import { join } from "node:path"; +import { z } from "zod"; import { countCollectorSentryReceipts, + isBusyDatabase, pruneCollectorSentryReceipts, + reclaimEmptyCollectorSentryOutbox, readCollectorSentryIdentity, readCollectorSentryLastDelivery, readCollectorSentryProducerFromReceipts, @@ -58,6 +61,19 @@ const PRUNE_BATCH_LIMIT = 1000; const PRUNE_ATTEMPTS = 3; const PRUNE_BACKOFF_MS = 250; +/** + * The shape of a collector checkpoint file. + * + * The file is written by the collector and read by this job, so it is untrusted + * input, and a watermark authorizes the deletion of receipts: its fields are + * read only after the file has been validated against this schema. + */ +const CheckpointSchema = z.object({ + version: z.literal(1), + producerId: z.string().min(1), + successfulThrough: z.string().min(1), +}); + /** * The producer's recorded watermark, or null when there is no usable one. * @@ -72,7 +88,16 @@ const PRUNE_BACKOFF_MS = 250; * producer id must match, and a watermark dated in the future is a skewed * clock rather than a watermark. */ -export async function readCollectorCheckpoint(producerId, checkpointRoot, now = Date.now()) { +export async function readCollectorCheckpoint(producerId, checkpointRoot, now = Date.now(), checkpointKey = null) { + // The collector records the key of the checkpoint that governs its outbox + // when the two names differ, and the checkpoint file is the one named after + // that key. The file has to agree with the key it is named after, because a + // watermark authorizes the deletion of receipts. + if (checkpointKey) { + const parsed = await readCheckpointFile(join(checkpointRoot, `${sanitizeCheckpointKey(checkpointKey)}.json`)); + if (!parsed || parsed.version !== 1 || parsed.producerId !== checkpointKey) return null; + return usableWatermark(parsed, now); + } let names; try { names = await readdir(checkpointRoot); @@ -81,22 +106,43 @@ export async function readCollectorCheckpoint(producerId, checkpointRoot, now = } for (const name of names) { if (!name.endsWith(".json")) continue; - let parsed; - try { - parsed = JSON.parse(await readFile(join(checkpointRoot, name), "utf8")); - } catch { - continue; - } - if (parsed?.version !== 1 || parsed?.producerId !== producerId) continue; - const successfulThrough = parsed.successfulThrough; - if (typeof successfulThrough !== "string" || !successfulThrough) continue; - const when = new Date(successfulThrough).getTime(); - if (!Number.isFinite(when) || when > now) continue; - return successfulThrough; + const parsed = await readCheckpointFile(join(checkpointRoot, name)); + if (!parsed || parsed.version !== 1 || parsed.producerId !== producerId) continue; + const watermark = usableWatermark(parsed, now); + if (watermark) return watermark; } return null; } +/** The checkpoint key as a file name, the way the collector names its state. */ +function sanitizeCheckpointKey(key) { + return String(key).replace(/[^a-zA-Z0-9._-]/g, "_"); +} + +/** One checkpoint file, or null when it cannot be read or parsed. */ +async function readCheckpointFile(path) { + let raw; + try { + raw = JSON.parse(await readFile(path, "utf8")); + } catch { + return null; + } + // The file is untrusted input, and the watermark it holds decides which + // receipts may be removed, so its shape is checked before any field of it is + // read. + const parsed = CheckpointSchema.safeParse(raw); + return parsed.success ? parsed.data : null; +} + +/** The watermark of a checkpoint, when it is one this job may act on. */ +function usableWatermark(parsed, now) { + const successfulThrough = parsed?.successfulThrough; + if (typeof successfulThrough !== "string" || !successfulThrough) return null; + const when = new Date(successfulThrough).getTime(); + if (!Number.isFinite(when) || when > now) return null; + return successfulThrough; +} + /** * How long an outbox has gone unwritten, or null when it cannot be measured. * @@ -221,7 +267,12 @@ async function sweepOutbox(name, summary, options) { summary.skipped.push({ outbox: name, reason: "producer-unknown" }); return; } - const successfulThrough = await readCollectorCheckpoint(producerId, checkpointRoot, now); + const successfulThrough = await readCollectorCheckpoint( + producerId, + checkpointRoot, + now, + identity?.checkpointKey ?? null, + ); if (!successfulThrough) { // A missing checkpoint means no receipt may be deleted. It does not mean // the outbox can never be reclaimed: an empty outbox whose instance is gone @@ -297,7 +348,19 @@ async function reclaimIfIdle(root, name, producerId, fileIdleMs, summary, option summary.reclaimed.push({ outbox: name, producerId, idleDays }); return; } - await rm(root, { recursive: true, force: true }); + // The removal happens under the outbox's write lock, which is the lock the + // collector's own writes take, so a collector writing at that moment cannot + // lose the row it is writing into a directory that is being removed. + const result = await reclaimEmptyCollectorSentryOutbox(root); + if (!result.reclaimed) { + // A receipt arrived between the count above and the lock. The outbox is + // left in place and reported. + summary.orphaned.push({ outbox: name, producerId, idleDays, receipts: result.receipts }); + log( + `orphaned ${producerId} outbox ${name}: ${result.receipts} receipt(s) arrived before it could be reclaimed`, + ); + return; + } summary.reclaimed.push({ outbox: name, producerId, idleDays }); log(`reclaimed the empty ${producerId} outbox ${name} (idle ${idleDays} day(s))`); } @@ -325,12 +388,14 @@ async function pruneWithRetry(root, options) { throw lastError; } -/** Whether an error is SQLite reporting that another process holds the lock. */ -export function isBusyDatabase(error) { - const code = error?.code ?? ""; - const message = error instanceof Error ? error.message : String(error ?? ""); - return code === "SQLITE_BUSY" || /database is locked|database table is locked/i.test(message); -} +/** + * Whether an error is SQLite reporting that another process holds the lock. + * + * The check lives in the bridge, because the collector and this job share the + * outbox and have to recognise a busy database the same way; it is re-exported + * here for the callers that have always read it from this script. + */ +export { isBusyDatabase }; if (import.meta.url === `file://${process.argv[1]}`) { const args = process.argv.slice(2); diff --git a/scripts/test-collector-sentry-outboxes.mjs b/scripts/test-collector-sentry-outboxes.mjs index ba81ce2a..dfc710b8 100644 --- a/scripts/test-collector-sentry-outboxes.mjs +++ b/scripts/test-collector-sentry-outboxes.mjs @@ -15,6 +15,8 @@ import { DatabaseSync } from "node:sqlite"; import { recordCollectorSentryIdentity, readCollectorSentryIdentity, + reclaimEmptyCollectorSentryOutbox, + writeCollectorSentryReceipts, } from "./lib/collector-sentry-bridge.mjs"; import { pruneCollectorSentryOutboxes, @@ -517,5 +519,178 @@ await test("an orphan threshold that does not make sense stops the sweep", async } }); +await test("a checkpoint named by the collector's state key governs its outbox", async () => { + const { base, stateRoot, checkpointRoot } = scratch(); + try { + // The minimax collector checkpoints under "minimax-runtime" while its + // outbox belongs to the producer "minimax-code", so the outbox records the + // key it checkpoints under and the sweep finds the checkpoint by that key. + const root = writeOutbox(stateRoot, "producer-state-key", { sent: 6, daysAgo: 400 }); + await recordCollectorSentryIdentity(root, { + producerId: "minimax-code", + checkpointKey: "minimax-runtime", + }); + writeCheckpoint(checkpointRoot, "minimax-runtime"); + const summary = await pruneCollectorSentryOutboxes({ stateRoot, checkpointRoot, log: () => {} }); + assert.equal(summary.skipped.length, 0, "the outbox is not skipped for want of a checkpoint"); + assert.equal(summary.outboxes, 1, "it is swept"); + assert.equal(summary.pruned, 6, "and its receipts are pruned against that checkpoint"); + } finally { + rmSync(base, { recursive: true, force: true }); + } +}); + +await test("an outbox whose checkpoint cannot be found is still skipped", async () => { + const { base, stateRoot, checkpointRoot } = scratch(); + try { + // Without the recorded key there is no way to tell which checkpoint + // governs the outbox, and a watermark from another collector must never + // authorize the deletion of these receipts. + const root = writeOutbox(stateRoot, "producer-unknown-key", { sent: 6, daysAgo: 400 }); + await recordCollectorSentryIdentity(root, { producerId: "minimax-code" }); + writeCheckpoint(checkpointRoot, "minimax-runtime"); + const summary = await pruneCollectorSentryOutboxes({ stateRoot, checkpointRoot, log: () => {} }); + assert.equal(summary.skipped.length, 1, "the outbox is skipped"); + assert.equal(summary.skipped[0].reason, "no-checkpoint"); + assert.equal(countEvents(root), 6, "and its receipts are left alone"); + } finally { + rmSync(base, { recursive: true, force: true }); + } +}); + +await test("a collector that writes after the prune keeps its outbox from being reclaimed", async () => { + const { base, stateRoot, checkpointRoot } = scratch(); + try { + // The window Jet named: the sweep has counted the outbox empty, and a + // collector writes into it at that moment. The reclaim takes the outbox's + // write lock, which is the lock the collector's own writes take, so the + // collector's row cannot land in a directory that is being removed. + const root = writeOutbox(stateRoot, "producer-writing", { daysAgo: 400 }); + await recordCollectorSentryIdentity(root, { producerId: "claude-code" }); + writeCheckpoint(checkpointRoot, "claude-code"); + ageOutbox(root, 30); + const writer = new DatabaseSync(join(root, "outbox.sqlite")); + let armed = false; + const summary = await pruneCollectorSentryOutboxes({ + stateRoot, + checkpointRoot, + log: (line) => { + if (!armed && line.startsWith("pruned")) { + armed = true; + writer.exec("BEGIN IMMEDIATE"); + writer.prepare("INSERT INTO events (id,payload,state,sent_at) VALUES (?,?,?,?)").run( + "arriving-row", + JSON.stringify({ ts: new Date().toISOString() }), + "sent", + Date.now(), + ); + } + }, + }); + assert.equal(summary.reclaimed.length, 0, "an outbox a collector is writing into is not reclaimed"); + assert.equal(existsSync(root), true, "and its directory is left in place"); + try { writer.exec("COMMIT"); } catch { /* the directory is gone: the row went with it */ } + assert.equal(countEvents(root), 1, "with the row the collector added still in it"); + writer.close(); + } finally { + rmSync(base, { recursive: true, force: true }); + } +}); + +await test("an identity recorded without a checkpoint key keeps the one already recorded", async () => { + // The pass that sends events does not know the checkpoint key, while the pass + // that finds nothing to send does. The key that was already recorded is what + // tells a maintenance job which checkpoint governs the outbox, so the event + // path must not reset it. + const { base, stateRoot } = scratch(); + try { + const root = writeOutbox(stateRoot, "producer-keyed", { daysAgo: 400 }); + await recordCollectorSentryIdentity(root, { producerId: "minimax-code", checkpointKey: "minimax-runtime" }); + await recordCollectorSentryIdentity(root, { producerId: "minimax-code" }); + const identity = await readCollectorSentryIdentity(root); + assert.equal(identity.checkpointKey, "minimax-runtime", "the recorded key survives a pass that does not carry one"); + } finally { + rmSync(base, { recursive: true, force: true }); + } +}); + +await test("a checkpoint file is checked against its schema before its fields are read", async () => { + // The checkpoint file is untrusted input, and the watermark it holds decides + // which receipts may be removed, so a file that is not the shape of a + // checkpoint proves nothing. + const { base, checkpointRoot } = scratch(); + try { + writeFileSync( + join(checkpointRoot, "claude-code.json"), + JSON.stringify({ version: 1, producerId: "claude-code", successfulThrough: 1767225600000 }), + ); + assert.equal(await readCollectorCheckpoint("claude-code", checkpointRoot), null, "a watermark that is not a date proves nothing"); + writeFileSync( + join(checkpointRoot, "claude-code.json"), + JSON.stringify({ version: 1, producerId: "claude-code", successfulThrough: new Date().toISOString() }), + ); + assert.ok(await readCollectorCheckpoint("claude-code", checkpointRoot), "a checkpoint of the right shape is a watermark"); + } finally { + rmSync(base, { recursive: true, force: true }); + } +}); + +await test("the reclaim waits for a collector's write instead of failing", async () => { + // The reclaim takes the same write lock the collector's own writes take, so + // a collector that is writing at that moment holds the lock for longer than + // the reclaim's first attempt waits. The reclaim waits for it rather than + // failing the outbox for a lock that lasts a moment. + const { base, stateRoot } = scratch(); + try { + const root = writeOutbox(stateRoot, "producer-locked", { daysAgo: 400 }); + const writer = new DatabaseSync(join(root, "outbox.sqlite")); + writer.exec("PRAGMA busy_timeout=1000;"); + writer.exec("BEGIN IMMEDIATE"); + writer.prepare("INSERT INTO events (id,payload,state,sent_at) VALUES (?,?,?,?)").run( + "held-row", + JSON.stringify({ ts: new Date().toISOString() }), + "sent", + Date.now(), + ); + // The write holds the lock for longer than the reclaim's busy timeout, so + // the reclaim has to try again to get it. + const release = setTimeout(() => { + try { writer.exec("COMMIT"); } catch { /* the reclaim took the lock first */ } + }, 1400); + const result = await reclaimEmptyCollectorSentryOutbox(root); + clearTimeout(release); + assert.equal(result.reclaimed, false, "an outbox that holds a receipt is not reclaimed"); + assert.equal(result.receipts, 1, "and the collector's row is counted once the lock is held"); + try { writer.exec("ROLLBACK"); } catch { /* the write was committed */ } + writer.close(); + } finally { + rmSync(base, { recursive: true, force: true }); + } +}); + +await test("a receipt written into an outbox that was reclaimed is written again", async () => { + // The window the review named: a collector has already opened the outbox + // when the reclaim removes it, so the collector's write fails, because the + // database's write-ahead log went with the directory. The receipt is + // written again into a new outbox, so the collector keeps the receipt it + // was told it had stored. + const { base, stateRoot } = scratch(); + try { + const root = writeOutbox(stateRoot, "producer-reclaimed", { sent: 0 }); + let reclaimed = null; + await writeCollectorSentryReceipts(root, [{ eventId: "held-row" }], { + onOpen: async () => { + // The reclaim runs between the open and the write, once. + if (reclaimed) return; + reclaimed = await reclaimEmptyCollectorSentryOutbox(root); + }, + }); + assert.equal(reclaimed?.reclaimed, true, "the empty outbox was reclaimed under the waiting writer"); + assert.equal(countEvents(root), 1, "the receipt is in the outbox at the path again"); + } finally { + rmSync(base, { recursive: true, force: true }); + } +}); + console.log(`${passes} passed, ${failures} failed`); if (failures) process.exit(1);