Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ProjectionMaintenance.ts

620 lines28.1 KB

1import type { ThreadId } from "@t3tools/contracts";
2import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
3import * as Context from "effect/Context";
4import * as DateTime from "effect/DateTime";
5import * as Duration from "effect/Duration";
6import * as Effect from "effect/Effect";
7import * as Layer from "effect/Layer";
8import * as Schema from "effect/Schema";
9import * as SqlClient from "effect/sql/SqlClient";
10import type * as SqlError from "effect/sql/SqlError";
11​
12import {
13 EVENT_LOG_PRUNE_MARK,
14 EVENT_LOG_PRUNED_THROUGH,
15} from "../persistence/OrchestrationEventStore.ts";
16import * as ProjectionStore from "./ProjectionStore.ts";
17​
18export class ProjectionMaintenanceError extends Schema.TaggedError<ProjectionMaintenanceError>()(
19 "ProjectionMaintenanceError",
20 {
21 operation: Schema.String,
22 cause: Schema.optional(Schema.Defect()),
23 },
24) {}
25​
26export interface ProjectionMaintenanceV2Shape {
27 /**
28 * Deletes events the projections already cover once they are older than the retained history,
29 * then purges any deleted thread that still holds conversation content.
30 */
31 readonly pruneEventStore: (betweenPages?: Effect.Effect<void>) => Effect.Effect<
32 {
33 readonly deletedEventCount: number;
34 readonly deletedReceiptCount: number;
35 readonly purgedRowCount: number;
36 readonly reclaimableBytes: number;
37 },
38 ProjectionMaintenanceError
39 >;
40 /**
41 * Removes a deleted thread's conversation, and that of deleted run-fork sources it alone kept.
42 * Returns the number of rows removed.
43 */
44 readonly purgeDeletedThread: (
45 threadId: ThreadId,
46 ) => Effect.Effect<number, ProjectionMaintenanceError>;
48​
49export class ProjectionMaintenanceV2 extends Context.Service<
50 ProjectionMaintenanceV2,
51 ProjectionMaintenanceV2Shape
52>()("t3/orchestration-v2/ProjectionMaintenance/ProjectionMaintenanceV2") {}
53​
54// Reconnect replay and command-id retries read this tail; older cursors resync from a snapshot.
55const RETAINED_EVENT_HISTORY = Duration.days(1);
56// Small pages bound work on the reader worker and synchronous fallback.
57const PAGE_SIZE = 50;
58const REFERENCE_SCAN_WINDOW = 1000;
59// Bounds how long one purge statement holds the writer: on a real database a 500-row batch of
60// turn items took about 400 ms, index and count-trigger work included.
61const PURGE_BATCH_SIZE = 50;
62// Only the v2 migration made legacy receipts, so every later receipt has a higher rowid. This
63// holds the newest legacy thread receipt a pass left, and later passes read no further.
64const LEGACY_RECEIPTS_THROUGH = "legacy-receipts-through";
65// Titles default to the first message, so a tombstone cannot keep the real one.
66export const DELETED_THREAD_TITLE = "Deleted thread";
67​
68// Every thread_id table that holds conversation text. The thread row stays as the tombstone, and
69// the metadata that storage cleanup and usage history still read (checkpoints, provider sessions,
70// provider turns, run attempts, context transfers) stays with it.
71export const DELETED_THREAD_CONTENT_TABLES = [
72 "orchestration_v2_turn_item_positions",
73 "orchestration_v2_projection_turn_items",
74 "orchestration_v2_projection_messages",
75 "orchestration_v2_projection_nodes",
76 "orchestration_v2_projection_runs",
77 "orchestration_v2_projection_subagents",
78 "orchestration_v2_projection_context_handoffs",
79 "orchestration_v2_projection_runtime_requests",
80 "orchestration_v2_projection_plans",
81 "mcp_app_model_context",
82 // A legacy thread's transcript source; deleting it means the importer has nothing to restore.
83 "projection_thread_messages",
84] as const;
85​
86type MetadataRow = {
87 readonly projection_name: string;
88 readonly last_sequence: number;
89 readonly updated_at: string;
90};
91​
92export const layer: Layer.Layer<ProjectionMaintenanceV2, never, SqlClient.SqlClient> = Layer.effect(
93 ProjectionMaintenanceV2,
94 Effect.gen(function* () {
95 const sql = yield* SqlClient.SqlClient;
96​
97 const writeMetadata = (name: string, sequence: number, at: DateTime.Utc) => sql`
98 INSERT INTO orchestration_v2_projection_metadata (
99 projection_name, schema_version, last_sequence, updated_at
100 )
101 VALUES (
102 ${name},
103 ${ProjectionStore.ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION},
104 ${sequence},
105 ${DateTime.formatIso(at)}
106 )
107 ON CONFLICT(projection_name) DO UPDATE SET
108 last_sequence = excluded.last_sequence,
109 updated_at = excluded.updated_at
110 `;
111​
112 // Collects anchors whose prompt later rows borrow through promptSequence.
113 const readPromptReferences = Effect.fnUntraced(function* (
114 afterSequence: number,
115 throughSequence: number,
116 betweenPages: Effect.Effect<void>,
117 ) {
118 const referenced = new Set<number>();
119 for (let cursor = afterSequence; cursor < throughSequence;) {
120 const windowEnd = Math.min(cursor + REFERENCE_SCAN_WINDOW, throughSequence);
121 const rows = yield* sql<{ readonly prompt_sequence: number }>`
122 SELECT json_extract(payload_json, '$.promptSequence') AS prompt_sequence
123 FROM orchestration_events
124 WHERE sequence > ${cursor}
125 AND sequence <= ${windowEnd}
126 AND event_type IN ('subagent.updated', 'turn-item.updated')
127 AND json_type(payload_json, '$.promptSequence') = 'integer'
128 `.pipe(NodeSqliteClient.readOnly);
129 for (const row of rows) referenced.add(row.prompt_sequence);
130 cursor = windowEnd;
131 yield* betweenPages;
132 }
133 return referenced;
134 });
135​
136 const pruneEvents = Effect.fnUntraced(function* (
137 throughSequence: number,
138 head: number,
139 betweenPages: Effect.Effect<void>,
140 ) {
141 const referenced = yield* readPromptReferences(throughSequence, head, betweenPages);
142 // Stream heads at or below the boundary are kept, so the anchors they borrow must stay too.
143 const keptHeadReferences = yield* sql<{ readonly prompt_sequence: number }>`
144 SELECT json_extract(event.payload_json, '$.promptSequence') AS prompt_sequence
145 FROM (
146 SELECT MAX(sequence) AS sequence FROM orchestration_events
147 GROUP BY aggregate_kind, stream_id
148 ) AS heads
149 JOIN orchestration_events AS event ON event.sequence = heads.sequence
150 WHERE heads.sequence <= ${throughSequence}
151 AND event.event_type IN ('subagent.updated', 'turn-item.updated')
152 AND json_type(event.payload_json, '$.promptSequence') = 'integer'
153 `.pipe(NodeSqliteClient.readOnly);
154 for (const row of keptHeadReferences) referenced.add(row.prompt_sequence);
155 yield* betweenPages;
156 let referencesThrough = head;
157 let deleted = 0;
158 let cursor = 0;
159 while (cursor < throughSequence) {
160 const rows = yield* sql<{ readonly sequence: number; readonly prunable: number }>`
161 SELECT
162 event.sequence,
163 CASE
164 WHEN event.application_event_version = 1 THEN 0
165 -- The legacy importer treats a thread without thread.created as not yet imported.
166 WHEN event.event_type = 'thread.created' THEN 0
167 -- Codex usage history reads the selection a run attempt started with.
168 WHEN event.event_type = 'run.updated'
169 AND json_extract(event.payload_json, '$.status') = 'running' THEN 0
170 -- The newest row keeps each stream's high water, stream_version, and snapshot sequence.
171 WHEN event.sequence = (
172 SELECT MAX(newer.sequence) FROM orchestration_events AS newer
173 WHERE newer.aggregate_kind = event.aggregate_kind
174 AND newer.stream_id = event.stream_id
175 ) THEN 0
176 ELSE 1
177 END AS prunable
178 FROM orchestration_events AS event
179 WHERE event.sequence > ${cursor}
180 AND event.sequence <= ${throughSequence}
181 ORDER BY event.sequence ASC
182 LIMIT ${PAGE_SIZE}
183 `.pipe(NodeSqliteClient.readOnly);
184 const candidates = rows.filter((row) => row.prunable === 1).map((row) => row.sequence);
185 // Never hold a transaction or the reader lock across a yield or a rest.
186 yield* Effect.yieldNow;
187 if (candidates.length > 0) {
188 deleted += yield* sql.withTransaction(
189 Effect.gen(function* () {
190 // Rows appended since the reference scan may borrow a prompt from a candidate.
191 const appended = yield* sql<{
192 readonly sequence: number;
193 readonly prompt_sequence: number | null;
194 }>`
195 SELECT
196 sequence,
197 CASE
198 WHEN event_type IN ('subagent.updated', 'turn-item.updated')
199 AND json_type(payload_json, '$.promptSequence') = 'integer'
200 THEN json_extract(payload_json, '$.promptSequence')
201 END AS prompt_sequence
202 FROM orchestration_events
203 WHERE sequence > ${referencesThrough}
204 `;
205 for (const row of appended) {
206 if (row.prompt_sequence !== null) referenced.add(row.prompt_sequence);
207 referencesThrough = Math.max(referencesThrough, row.sequence);
208 }
209 const obsolete = candidates.filter((sequence) => !referenced.has(sequence));
210 if (obsolete.length === 0) return 0;
211 yield* sql`DELETE FROM orchestration_events WHERE sequence IN ${sql.in(obsolete)}`;
212 return obsolete.length;
213 }),
214 );
215 yield* Effect.yieldNow;
216 }
217 // Rest after every page, including the last, so the next loop starts a fresh slice.
218 yield* betweenPages;
219 if (rows.length < PAGE_SIZE) break;
220 cursor = rows.at(-1)?.sequence ?? throughSequence;
221 }
222 return deleted;
223 });
224​
225 // Imported legacy threads are served from v2 rows; their v1 events and receipts have no reader.
226 const pruneImportedLegacyHistory = Effect.fnUntraced(function* (
227 throughSequence: number,
228 throughReceiptRowId: number,
229 betweenPages: Effect.Effect<void>,
230 ) {
231 let deletedEventCount = 0;
232 let deletedReceiptCount = 0;
233 let legacyReceiptsThrough = 0;
234 for (let cursor = 0; ;) {
235 const rows = yield* sql<{ readonly sequence: number; readonly imported: number }>`
236 SELECT
237 event.sequence,
238 event.aggregate_kind = 'thread' AND EXISTS (
239 SELECT 1 FROM orchestration_v2_legacy_imports AS legacy_import
240 WHERE legacy_import.thread_id = event.stream_id
241 AND legacy_import.transcript_imported_at IS NOT NULL
242 ) AS imported
243 FROM orchestration_events AS event
244 INDEXED BY idx_orchestration_events_application_sequence
245 WHERE event.application_event_version = 1
246 AND event.sequence > ${cursor}
247 AND event.sequence <= ${throughSequence}
248 ORDER BY event.sequence ASC
249 LIMIT ${PAGE_SIZE}
250 `.pipe(NodeSqliteClient.readOnly);
251 const obsolete = rows.filter((row) => row.imported === 1).map((row) => row.sequence);
252 yield* Effect.yieldNow;
253 if (obsolete.length > 0) {
254 yield* sql`DELETE FROM orchestration_events WHERE sequence IN ${sql.in(obsolete)}`;
255 deletedEventCount += obsolete.length;
256 yield* Effect.yieldNow;
257 }
258 yield* betweenPages;
259 if (rows.length < PAGE_SIZE) break;
260 cursor = rows.at(-1)?.sequence ?? cursor;
261 }
262 for (let cursor = 0; ;) {
263 const rows = yield* sql<{
264 readonly row_id: number;
265 readonly command_id: string;
266 readonly legacy: number;
267 readonly imported: number;
268 }>`
269 SELECT
270 receipt.rowid AS row_id,
271 receipt.command_id,
272 receipt.command_type = 'legacy' AND receipt.aggregate_kind = 'thread' AS legacy,
273 receipt.command_type = 'legacy' AND receipt.aggregate_kind = 'thread' AND EXISTS (
274 SELECT 1 FROM orchestration_v2_legacy_imports AS legacy_import
275 WHERE legacy_import.thread_id = receipt.aggregate_id
276 AND legacy_import.transcript_imported_at IS NOT NULL
277 ) AS imported
278 FROM orchestration_command_receipts AS receipt
279 WHERE receipt.rowid > ${cursor} AND receipt.rowid <= ${throughReceiptRowId}
280 ORDER BY receipt.rowid ASC
281 LIMIT ${PAGE_SIZE}
282 `.pipe(NodeSqliteClient.readOnly);
283 const obsolete = rows.filter((row) => row.imported === 1).map((row) => row.command_id);
284 for (const row of rows) {
285 if (row.legacy === 1 && row.imported === 0) legacyReceiptsThrough = row.row_id;
286 }
287 yield* Effect.yieldNow;
288 if (obsolete.length > 0) {
289 yield* sql`DELETE FROM orchestration_command_receipts WHERE command_id IN ${sql.in(obsolete)}`;
290 deletedReceiptCount += obsolete.length;
291 yield* Effect.yieldNow;
292 }
293 yield* betweenPages;
294 if (rows.length < PAGE_SIZE) break;
295 cursor = rows.at(-1)?.row_id ?? cursor;
296 }
297 return { deletedEventCount, deletedReceiptCount, legacyReceiptsThrough };
298 });
299​
300 // A run fork shows its source's history without copying it, through any chain of forks, and a
301 // pending merge-back still reads its source. Such a deleted thread keeps its content until
302 // every live thread that shows it is deleted too.
303 const purgeableThreads = (deletedThreadId: ThreadId | undefined) =>
304 sql<{
305 readonly thread_id: string;
306 }>`
307 WITH RECURSIVE shown(thread_id) AS (
308 SELECT thread_id FROM orchestration_v2_projection_threads WHERE deleted_at IS NULL
309 UNION
310 SELECT transfer.source_thread_id
311 FROM orchestration_v2_projection_context_transfers AS transfer
312 JOIN orchestration_v2_projection_threads AS target
313 ON target.thread_id = transfer.target_thread_id
314 WHERE transfer.type = 'merge_back' AND transfer.status = 'pending'
315 AND target.deleted_at IS NULL
316 UNION
317 SELECT json_extract(fork.payload_json, '$.forkedFrom.threadId')
318 FROM shown
319 JOIN orchestration_v2_projection_threads AS fork ON fork.thread_id = shown.thread_id
320 WHERE json_extract(fork.payload_json, '$.forkedFrom.type') = 'run'
321 ),
322 candidate(thread_id) AS (${
323 deletedThreadId === undefined
324 ? sql`SELECT thread_id FROM orchestration_v2_projection_threads WHERE deleted_at IS NOT NULL`
325 : // Deleting a fork can release the deleted sources it was the last to show.
326 sql`
327 SELECT ${deletedThreadId}
328 UNION
329 SELECT json_extract(fork.payload_json, '$.forkedFrom.threadId')
330 FROM candidate
331 JOIN orchestration_v2_projection_threads AS fork
332 ON fork.thread_id = candidate.thread_id
333 WHERE json_extract(fork.payload_json, '$.forkedFrom.type') = 'run'
334 `
335 })
336 SELECT thread.thread_id
337 FROM candidate
338 JOIN orchestration_v2_projection_threads AS thread ON thread.thread_id = candidate.thread_id
339 WHERE thread.deleted_at IS NOT NULL
340 AND thread.thread_id NOT IN (SELECT thread_id FROM shown WHERE thread_id IS NOT NULL)
341 -- Earlier effects still read the thread; a later purge or sweep takes it.
342 AND NOT EXISTS (
343 SELECT 1 FROM orchestration_v2_effect_outbox AS effect
344 WHERE effect.thread_id = thread.thread_id
345 AND effect.status IN ('pending', 'running')
346 -- Title generation has its own lane and needs nothing the purge removes.
347 AND effect.effect_type NOT IN ('thread-content.purge', 'thread-title.generate')
348 )
349 -- A live parent settles its delegated task from this child's runs.
350 AND NOT EXISTS (
351 SELECT 1 FROM orchestration_v2_projection_subagents AS task
352 JOIN orchestration_v2_projection_threads AS parent ON parent.thread_id = task.thread_id
353 WHERE task.child_thread_id = thread.thread_id
354 AND task.status IN ('idle', 'pending', 'running', 'waiting')
355 AND parent.deleted_at IS NULL
356 )
357 -- The delete's own purge always runs; the sweep only takes threads with something left.
358 AND ${
359 deletedThreadId !== undefined
360 ? sql`1 = 1`
361 : sql.or([
362 sql`thread.title <> ${DELETED_THREAD_TITLE}`,
363 // A thread renamed to the placeholder still has its first title in thread.created.
364 sql`EXISTS (
365 SELECT 1 FROM orchestration_events
366 INDEXED BY idx_orchestration_events_agent_stream_sequence
367 WHERE application_event_version = 2
368 AND aggregate_kind = 'thread'
369 AND stream_id = thread.thread_id
370 AND event_type IN ('thread.created', 'thread.deleted')
371 AND json_extract(payload_json, '$.title') IS NOT ${DELETED_THREAD_TITLE}
372 )`,
373 sql`json_type(thread.payload_json, '$.guestShare') IS NOT NULL`,
374 // An interrupted pass leaves events the purge does not keep.
375 sql`EXISTS (
376 SELECT 1 FROM orchestration_events
377 INDEXED BY idx_orchestration_events_agent_stream_sequence
378 WHERE application_event_version = 2
379 AND aggregate_kind = 'thread'
380 AND stream_id = thread.thread_id
381 AND event_type NOT IN ('thread.created', 'thread.deleted')
382 AND NOT (
383 event_type = 'run.updated'
384 AND json_extract(payload_json, '$.status') = 'running'
385 )
386 )`,
387 // The purge deletes settled requests and clears a failed one's error.
388 sql`EXISTS (
389 SELECT 1 FROM orchestration_v2_effect_outbox AS effect
390 WHERE effect.thread_id = thread.thread_id
391 AND effect.effect_type <> 'thread-content.purge'
392 AND (
393 effect.status IN ('succeeded', 'cancelled')
394 OR (effect.status = 'failed' AND effect.last_error IS NOT NULL)
395 )
396 )`,
397 ...DELETED_THREAD_CONTENT_TABLES.map(
398 (table) =>
399 sql`EXISTS (SELECT 1 FROM ${sql(table)} WHERE thread_id = thread.thread_id)`,
400 ),
401 ])
402 }
403 `.pipe(NodeSqliteClient.readOnly);
404​
405 const purgeThreads = Effect.fnUntraced(function* (
406 deletedThreadId: ThreadId | undefined,
407 betweenPages: Effect.Effect<void>,
408 ) {
409 const threads = yield* purgeableThreads(deletedThreadId);
410 const now = DateTime.formatIso(yield* DateTime.now);
411 let purged = 0;
412 // Each statement commits on its own, so a huge thread never holds the writer for long.
413 const drain = Effect.fnUntraced(function* (
414 deleteBatch: Effect.Effect<ReadonlyArray<unknown>, SqlError.SqlError>,
415 ) {
416 for (;;) {
417 const rows = yield* deleteBatch;
418 purged += rows.length;
419 yield* Effect.yieldNow;
420 yield* betweenPages;
421 if (rows.length < PURGE_BATCH_SIZE) return;
422 }
423 });
424 for (const { thread_id: threadId } of threads) {
425 // A re-import restores a deleted thread in one transaction, and each statement here
426 // commits on its own, so each checks again that the thread is still deleted.
427 const stillDeleted = sql`EXISTS (
428 SELECT 1 FROM orchestration_v2_projection_threads
429 WHERE thread_id = ${threadId} AND deleted_at IS NOT NULL
430 )`;
431 const tombstone = sql`(
432 SELECT json_remove(json_set(payload_json, '$.title', ${DELETED_THREAD_TITLE}), '$.guestShare')
433 FROM orchestration_v2_projection_threads WHERE thread_id = ${threadId}
434 )`;
435 yield* sql`
436 UPDATE orchestration_events
437 SET payload_json = json_remove(
438 json_set(payload_json, '$.title', ${DELETED_THREAD_TITLE}),
439 '$.guestShare'
440 )
441 WHERE application_event_version = 2
442 AND aggregate_kind = 'thread'
443 AND stream_id = ${threadId}
444 AND event_type IN ('thread.created', 'thread.deleted')
445 AND ${stillDeleted}
446 `;
447 // The head row only holds the stream's position, so any other head becomes the tombstone.
448 // First, so the head never borrows a prompt from an anchor already deleted below.
449 yield* sql`
450 UPDATE orchestration_events
451 SET event_type = 'thread.deleted', payload_json = ${tombstone}, metadata_json = '{}'
452 WHERE sequence = (
453 SELECT MAX(sequence) FROM orchestration_events
454 WHERE application_event_version = 2
455 AND aggregate_kind = 'thread'
456 AND stream_id = ${threadId}
457 )
458 AND event_type NOT IN ('thread.created', 'thread.deleted')
459 AND NOT (
460 event_type = 'run.updated' AND json_extract(payload_json, '$.status') = 'running'
461 )
462 AND ${stillDeleted}
463 `;
464 for (const table of DELETED_THREAD_CONTENT_TABLES) {
465 yield* drain(sql`
466 DELETE FROM ${sql(table)}
467 WHERE rowid IN (
468 SELECT rowid FROM ${sql(table)} WHERE thread_id = ${threadId} LIMIT ${PURGE_BATCH_SIZE}
469 )
470 AND ${stillDeleted}
471 RETURNING 1 AS purged
472 `);
473 }
474 // Keep only what the pruner keeps for any stream: replay still delivers the deletion.
475 yield* drain(sql`
476 DELETE FROM orchestration_events
477 WHERE sequence IN (
478 SELECT sequence FROM orchestration_events
479 INDEXED BY idx_orchestration_events_agent_stream_sequence
480 WHERE application_event_version = 2
481 AND aggregate_kind = 'thread'
482 AND stream_id = ${threadId}
483 AND event_type NOT IN ('thread.created', 'thread.deleted')
484 AND NOT (
485 event_type = 'run.updated' AND json_extract(payload_json, '$.status') = 'running'
486 )
487 AND sequence < (
488 SELECT MAX(sequence) FROM orchestration_events
489 WHERE application_event_version = 2
490 AND aggregate_kind = 'thread'
491 AND stream_id = ${threadId}
492 )
493 -- Newest first: a row borrowing its prompt goes before the anchor it borrows from.
494 ORDER BY sequence DESC
495 LIMIT ${PURGE_BATCH_SIZE}
496 )
497 AND ${stillDeleted}
498 RETURNING 1 AS purged
499 `);
500 // Settled requests can hold answers, feedback, and titles. A failed one stays as the
501 // marker that keeps a deleted thread's worktree, so only its text goes.
502 yield* sql`
503 DELETE FROM orchestration_v2_effect_outbox
504 WHERE thread_id = ${threadId} AND status IN ('succeeded', 'cancelled')
505 AND ${stillDeleted}
506 `;
507 yield* sql`
508 UPDATE orchestration_v2_effect_outbox
509 SET payload_json = CASE
510 WHEN json_type(payload_json, '$.title') = 'text'
511 THEN json_set(payload_json, '$.title', ${DELETED_THREAD_TITLE})
512 ELSE json_remove(payload_json, '$.feedback', '$.answers')
513 END,
514 last_error = NULL
515 WHERE thread_id = ${threadId} AND status = 'failed' AND ${stillDeleted}
516 `;
517 // Its v1 events then go with the imported-history prune, and no import refills it.
518 yield* sql`
519 UPDATE orchestration_v2_legacy_imports
520 SET transcript_imported_at = ${now}
521 WHERE thread_id = ${threadId} AND transcript_imported_at IS NULL AND ${stillDeleted}
522 `;
523 // Last, because the new title is what marks the purge as done.
524 yield* sql`
525 UPDATE projection_threads SET title = ${DELETED_THREAD_TITLE}
526 WHERE thread_id = ${threadId} AND ${stillDeleted}
527 `;
528 yield* sql`
529 UPDATE orchestration_v2_projection_threads
530 SET title = ${DELETED_THREAD_TITLE}, payload_json = ${tombstone}
531 WHERE thread_id = ${threadId} AND deleted_at IS NOT NULL
532 `;
533 }
534 return purged;
535 });
536​
537 const purgeDeletedThread: ProjectionMaintenanceV2Shape["purgeDeletedThread"] = (threadId) =>
538 purgeThreads(threadId, Effect.void).pipe(
539 Effect.withSpan("ProjectionMaintenance.purgeDeletedThread"),
540 Effect.mapError(
541 (cause) => new ProjectionMaintenanceError({ operation: "purge deleted thread", cause }),
542 ),
543 );
544​
545 // A pass prunes through the mark the previous pass left once that mark is a day old, so
546 // at least RETAINED_EVENT_HISTORY of events always remains. Receipts stay for idempotency.
547 const pruneEventStore = Effect.fn("ProjectionMaintenance.pruneEventStore")(
548 function* (betweenPages: Effect.Effect<void> = Effect.void) {
549 const now = yield* DateTime.now;
550 const metadata = yield* sql<MetadataRow>`
551 SELECT projection_name, last_sequence, updated_at
552 FROM orchestration_v2_projection_metadata
553 WHERE projection_name IN (
554 'thread-projections', ${EVENT_LOG_PRUNE_MARK}, ${EVENT_LOG_PRUNED_THROUGH},
555 ${LEGACY_RECEIPTS_THROUGH}
556 )
557 `.pipe(NodeSqliteClient.readOnly);
558 const read = (name: string) => metadata.find((row) => row.projection_name === name);
559 const projected = read("thread-projections")?.last_sequence ?? 0;
560 const mark = read(EVENT_LOG_PRUNE_MARK);
561 const prunedThrough = read(EVENT_LOG_PRUNED_THROUGH)?.last_sequence ?? 0;
562 // Fixed bounds: foreground commits during the pass wait for the next one.
563 const bounds = yield* sql<{ readonly sequence: number; readonly receipt_row_id: number }>`
564 SELECT
565 COALESCE((SELECT MAX(sequence) FROM orchestration_events), 0) AS sequence,
566 COALESCE((SELECT MAX(rowid) FROM orchestration_command_receipts), 0) AS receipt_row_id
567 `.pipe(NodeSqliteClient.readOnly);
568 const head = bounds[0]?.sequence ?? 0;
569​
570 let deletedEventCount = 0;
571 const markIsDue =
572 mark !== undefined &&
573 DateTime.toEpochMillis(now) - Date.parse(mark.updated_at) >=
574 Duration.toMillis(RETAINED_EVENT_HISTORY);
575 if (mark !== undefined && markIsDue) {
576 const throughSequence = Math.max(Math.min(mark.last_sequence, projected), prunedThrough);
577 if (throughSequence > prunedThrough) {
578 // Publish the boundary first so resuming clients take a snapshot, never a partial replay.
579 yield* writeMetadata(EVENT_LOG_PRUNED_THROUGH, throughSequence, now);
580 }
581 deletedEventCount += yield* pruneEvents(throughSequence, head, betweenPages);
582 }
583 if (mark === undefined || markIsDue) yield* writeMetadata(EVENT_LOG_PRUNE_MARK, head, now);
584​
585 // Catches threads deleted before purging existed, and any purge a crash interrupted.
586 // It runs first so the legacy prune below takes the v1 events of threads it marks.
587 const purgedRowCount = yield* purgeThreads(undefined, betweenPages);
588​
589 const receiptRowId = bounds[0]?.receipt_row_id ?? 0;
590 const legacyReceiptsThrough = read(LEGACY_RECEIPTS_THROUGH)?.last_sequence;
591 const legacy = yield* pruneImportedLegacyHistory(
592 head,
593 Math.min(receiptRowId, legacyReceiptsThrough ?? receiptRowId),
594 betweenPages,
595 );
596 deletedEventCount += legacy.deletedEventCount;
597 if (legacy.legacyReceiptsThrough !== legacyReceiptsThrough) {
598 yield* writeMetadata(LEGACY_RECEIPTS_THROUGH, legacy.legacyReceiptsThrough, now);
599 }
600​
601 const freelistRows = yield* sql<{ readonly freelist_count: number }>`PRAGMA freelist_count`;
602 const pageSizeRows = yield* sql<{ readonly page_size: number }>`PRAGMA page_size`;
603 const reclaimableBytes =
604 (freelistRows[0]?.freelist_count ?? 0) * (pageSizeRows[0]?.page_size ?? 0);
605​
606 return {
607 deletedEventCount,
608 deletedReceiptCount: legacy.deletedReceiptCount,
609 purgedRowCount,
610 reclaimableBytes,
611 };
612 },
613 Effect.mapError(
614 (cause) => new ProjectionMaintenanceError({ operation: "prune event store", cause }),
615 ),
616 );
617​
618 return ProjectionMaintenanceV2.of({ pruneEventStore, purgeDeletedThread });
619 }),
620);