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