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

ProjectionMaintenance.test.ts

663 lines25.7 KB

1import { assert, it } from "@effect/vitest";
2import {
3 EventId,
4 MessageId,
5 NodeId,
6 PlanId,
7 type OrchestrationV2AppThread,
8 type OrchestrationV2DomainEvent,
9 type OrchestrationV2TurnItem,
10 ProjectId,
11 ProviderDriverKind,
12 ProviderInstanceId,
13 RunId,
14 ThreadId,
15 TurnItemId,
16} from "@t3tools/contracts";
17import * as DateTime from "effect/DateTime";
18import * as Deferred from "effect/Deferred";
19import * as Effect from "effect/Effect";
20import * as Fiber from "effect/Fiber";
21import * as Layer from "effect/Layer";
22import * as Stream from "effect/Stream";
23import * as TestClock from "effect/testing/TestClock";
24import * as SqlClient from "effect/sql/SqlClient";
25import * as Statement from "effect/sql/Statement";
26​
27import * as SqlitePersistence from "../persistence/Sqlite.ts";
28import * as EventSink from "./EventSink.ts";
29import * as EventStore from "./EventStore.ts";
30import * as ProjectionMaintenance from "./ProjectionMaintenance.ts";
31import * as ProjectionStore from "./ProjectionStore.ts";
32import * as OrchestrationEventStore from "../persistence/OrchestrationEventStore.ts";
33​
34const database = SqlitePersistence.layerMemory;
35const eventStoreProvided = EventStore.layer.pipe(Layer.provideMerge(database));
36const projectionStoreProvided = ProjectionStore.layer.pipe(Layer.provideMerge(database));
37const stores = Layer.mergeAll(database, eventStoreProvided, projectionStoreProvided);
38const layerTest = Layer.mergeAll(
39 stores,
40 OrchestrationEventStore.layer.pipe(Layer.provide(database)),
41 EventSink.layer.pipe(Layer.provide(stores)),
42 ProjectionMaintenance.layer.pipe(Layer.provide(stores)),
43);
44​
45const providerInstanceId = ProviderInstanceId.make("codex");
46const providerDriver = ProviderDriverKind.make("codex");
47const modelSelection = { instanceId: providerInstanceId, model: "gpt-5.4" };
48​
49function makeThread(threadId: ThreadId, now: DateTime.Utc): OrchestrationV2AppThread {
50 return {
51 id: threadId,
52 projectId: ProjectId.make(`project:${threadId}`),
53 title: "Turn item compaction",
54 providerInstanceId,
55 modelSelection,
56 runtimeMode: "full-access",
57 interactionMode: "default",
58 branch: null,
59 worktreePath: null,
60 activeProviderThreadId: null,
61 lineage: { rootThreadId: threadId, parentThreadId: null, relationshipToParent: null },
62 forkedFrom: null,
63 createdBy: "user",
64 creationSource: "web",
65 createdAt: now,
66 updatedAt: now,
67 archivedAt: null,
68 settledOverride: null,
69 settledAt: null,
70 lastVisitedAt: null,
71 deletedAt: null,
72 };
74​
75function threadCreated(thread: OrchestrationV2AppThread, now: DateTime.Utc) {
76 return {
77 id: EventId.make("event:turn-item-compaction:thread"),
78 type: "thread.created",
79 threadId: thread.id,
80 providerInstanceId,
81 occurredAt: now,
82 payload: thread,
83 } satisfies OrchestrationV2DomainEvent;
85​
86const itemSpecs = [
87 { key: "command", type: "command_execution", ordinal: 10 },
88 { key: "reasoning", type: "reasoning", ordinal: 20 },
89 { key: "todo", type: "todo_list", ordinal: 30 },
90 { key: "commanded", type: "command_execution", ordinal: 40 },
91] as const;
92​
93function itemEvent(
94 threadId: ThreadId,
95 now: DateTime.Utc,
96 spec: (typeof itemSpecs)[number],
97 revision: number,
98 eventId = `event:turn-item-compaction:${spec.key}:${revision}`,
99): OrchestrationV2DomainEvent {
100 const id = TurnItemId.make(`turn-item:compaction:${spec.key}`);
101 const growing = `${spec.key}:${revision}:` + "x".repeat((revision + 1) * 192);
102 const completed = revision === 69;
103 const base = {
104 id,
105 threadId,
106 runId: null,
107 nodeId: null,
108 providerThreadId: null,
109 providerTurnId: null,
110 nativeItemRef: null,
111 parentItemId: null,
112 ordinal: spec.ordinal,
113 status: completed ? ("completed" as const) : ("running" as const),
114 title: spec.key,
115 startedAt: now,
116 completedAt: completed ? now : null,
117 updatedAt: now,
118 };
119 let payload: OrchestrationV2TurnItem;
120 switch (spec.type) {
121 case "command_execution":
122 payload = {
123 ...base,
124 type: "command_execution",
125 input: `run ${spec.key}`,
126 output: growing,
127 };
128 break;
129 case "reasoning":
130 payload = { ...base, type: "reasoning", text: growing, streaming: !completed };
131 break;
132 case "todo_list":
133 payload = {
134 ...base,
135 type: "todo_list",
136 planId: PlanId.make("plan:turn-item-compaction"),
137 steps: [{ id: "step", text: growing, status: completed ? "completed" : "running" }],
138 explanation: growing,
139 };
140 break;
141 }
142 return {
143 id: EventId.make(eventId),
144 type: "turn-item.updated",
145 threadId,
146 occurredAt: now,
147 payload,
148 };
150​
151function subagentEvents(
152 threadId: ThreadId,
153 now: DateTime.Utc,
154 revision: number,
155 eventSuffix = String(revision),
156): ReadonlyArray<OrchestrationV2DomainEvent> {
157 const id = NodeId.make("subagent:turn-item-compaction");
158 const prompt = revision === 0 ? "Review prompt A. ".repeat(40) : "Review prompt B. ".repeat(40);
159 const progress = `Review progress ${revision}`;
160 return [
161 {
162 id: EventId.make(`event:turn-item-compaction:subagent:${eventSuffix}`),
163 type: "subagent.updated",
164 threadId,
165 occurredAt: now,
166 payload: {
167 id,
168 threadId,
169 runId: null,
170 parentNodeId: NodeId.make("node:turn-item-compaction-parent"),
171 origin: "provider_native",
172 createdBy: "agent",
173 driver: providerDriver,
174 providerInstanceId,
175 providerThreadId: null,
176 childThreadId: null,
177 nativeTaskRef: {
178 driver: providerDriver,
179 nativeId: "compaction-review",
180 strength: "strong",
181 },
182 prompt,
183 progress,
184 title: "Review",
185 model: null,
186 status: "running",
187 result: null,
188 startedAt: now,
189 completedAt: null,
190 updatedAt: now,
191 },
192 },
193 {
194 id: EventId.make(`event:turn-item-compaction:subagent-item:${eventSuffix}`),
195 type: "turn-item.updated",
196 threadId,
197 occurredAt: now,
198 payload: {
199 id: TurnItemId.make("turn-item:compaction:subagent"),
200 threadId,
201 runId: null,
202 nodeId: null,
203 providerThreadId: null,
204 providerTurnId: null,
205 nativeItemRef: null,
206 parentItemId: null,
207 ordinal: 50,
208 status: "running",
209 title: "Review",
210 startedAt: now,
211 completedAt: null,
212 updatedAt: now,
213 type: "subagent",
214 subagentId: id,
215 origin: "provider_native",
216 driver: providerDriver,
217 providerInstanceId,
218 childThreadId: null,
219 prompt,
220 progress,
221 result: null,
222 },
223 },
224 ] satisfies ReadonlyArray<OrchestrationV2DomainEvent>;
226​
227const insertRunningRunUpdate = (threadId: ThreadId) =>
228 Effect.flatMap(
229 SqlClient.SqlClient,
230 (sql) => sql<{ readonly sequence: number }>`
231 INSERT INTO orchestration_events (
232 event_id, aggregate_kind, stream_id, stream_version, event_type,
233 occurred_at, actor_kind, payload_json, metadata_json, application_event_version
234 ) VALUES (
235 'event:prune:run-running', 'thread', ${threadId},
236 (SELECT MAX(stream_version) + 1 FROM orchestration_events WHERE stream_id = ${threadId}),
237 'run.updated', '2026-11-01T00:00:00.000Z', 'server', '{"status":"running"}', '{}', 2
238 ) RETURNING sequence
239 `,
240 );
241​
242const remainingEventIds = (threadId: ThreadId) =>
243 Effect.flatMap(
244 SqlClient.SqlClient,
245 (sql) => sql<{ readonly event_id: string }>`
246 SELECT event_id FROM orchestration_events WHERE stream_id = ${threadId} ORDER BY sequence
247 `,
248 ).pipe(Effect.map((rows) => rows.map((row) => row.event_id)));
249​
250it.effect("prunes events the projections cover once the retained day has passed", () =>
251 Effect.gen(function* () {
252 const sink = yield* EventSink.EventSinkV2;
253 const eventStore = yield* EventStore.EventStoreV2;
254 const events = yield* OrchestrationEventStore.OrchestrationEventStore;
255 const projections = yield* ProjectionStore.ProjectionStoreV2;
256 const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
257 const now = yield* DateTime.now;
258 const threadId = ThreadId.make("thread:prune");
259 yield* sink.write({ events: [threadCreated(makeThread(threadId, now), now)] });
260 for (const revision of [0, 1, 2]) {
261 yield* sink.write({ events: [itemEvent(threadId, now, itemSpecs[0], revision)] });
262 }
263 yield* sink.write({ events: subagentEvents(threadId, now, 0) });
264 yield* insertRunningRunUpdate(threadId);
265 yield* sink.write({ events: [itemEvent(threadId, now, itemSpecs[1], 0)] });
266​
267 // The first pass only marks the head; nothing is a day old yet.
268 assert.equal((yield* maintenance.pruneEventStore()).deletedEventCount, 0);
269 const markedThrough = yield* eventStore.latestSequence();
270​
271 // Repeating prompt A borrows it from the anchors written before the mark.
272 yield* sink.write({ events: subagentEvents(threadId, now, 0, "repeat") });
273 yield* sink.write({ events: [itemEvent(threadId, now, itemSpecs[0], 3)] });
274 const highWater = yield* eventStore.latestSequence();
275 const projection = yield* projections.getThreadProjection(threadId);
276​
277 yield* TestClock.adjust("23 hours");
278 assert.equal((yield* maintenance.pruneEventStore()).deletedEventCount, 0);
279 yield* TestClock.adjust("1 hour");
280 assert.equal((yield* maintenance.pruneEventStore()).deletedEventCount, 4);
281​
282 assert.deepEqual(yield* remainingEventIds(threadId), [
283 "event:turn-item-compaction:thread",
284 "event:turn-item-compaction:subagent:0",
285 "event:turn-item-compaction:subagent-item:0",
286 "event:prune:run-running",
287 "event:turn-item-compaction:subagent:repeat",
288 "event:turn-item-compaction:subagent-item:repeat",
289 "event:turn-item-compaction:command:3",
290 ]);
291 assert.equal(yield* events.prunedThroughSequence, markedThrough);
292 assert.equal(yield* eventStore.latestSequence(), highWater);
293 assert.equal(yield* eventStore.latestSequence({ threadId }), highWater);
294 assert.deepEqual(yield* projections.getThreadProjection(threadId), projection);
295 const repeated = yield* eventStore
296 .read({ threadId, eventType: "subagent.updated", afterSequence: markedThrough })
297 .pipe(Stream.runCollect);
298 assert.deepEqual(
299 Array.from(repeated, (stored) =>
300 stored.event.type === "subagent.updated" ? stored.event.payload.prompt : null,
301 ),
302 ["Review prompt A. ".repeat(40)],
303 );
304 }).pipe(Effect.provide(layerTest)),
305);
306​
307it.effect("keeps the anchor a retained stream head borrows from", () =>
308 Effect.gen(function* () {
309 const sink = yield* EventSink.EventSinkV2;
310 const eventStore = yield* EventStore.EventStoreV2;
311 const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
312 const now = yield* DateTime.now;
313 const threadId = ThreadId.make("thread:prune-head");
314 yield* sink.write({ events: [threadCreated(makeThread(threadId, now), now)] });
315 yield* sink.write({ events: subagentEvents(threadId, now, 0) });
316 // The stream's newest row borrows prompt A, so it is kept below the boundary.
317 yield* sink.write({ events: subagentEvents(threadId, now, 0, "repeat") });
318 yield* maintenance.pruneEventStore();
319 yield* TestClock.adjust("1 day");
320 assert.isAbove((yield* maintenance.pruneEventStore()).deletedEventCount, 0);
321​
322 assert.include(
323 yield* remainingEventIds(threadId),
324 "event:turn-item-compaction:subagent-item:0",
325 );
326 const stored = yield* eventStore.read({ threadId }).pipe(Stream.runCollect);
327 const head = Array.from(stored).at(-1)?.event;
328 assert.deepEqual(
329 head?.type === "turn-item.updated" && head.payload.type === "subagent"
330 ? head.payload.prompt
331 : null,
332 "Review prompt A. ".repeat(40),
333 );
334 }).pipe(Effect.provide(layerTest)),
335);
336​
337it.effect("keeps an anchor that a row appended during the pass borrows from", () =>
338 Effect.scoped(
339 Effect.gen(function* () {
340 const sink = yield* EventSink.EventSinkV2;
341 const eventStore = yield* EventStore.EventStoreV2;
342 const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
343 const now = yield* DateTime.now;
344 const threadId = ThreadId.make("thread:prune-race");
345 yield* sink.write({ events: [threadCreated(makeThread(threadId, now), now)] });
346 yield* sink.write({ events: subagentEvents(threadId, now, 0) });
347 yield* maintenance.pruneEventStore();
348 yield* sink.write({ events: [itemEvent(threadId, now, itemSpecs[0], 0)] });
349 yield* TestClock.adjust("1 day");
350​
351 const scanStarted = yield* Deferred.make<void>();
352 const releaseScan = yield* Deferred.make<void>();
353 let blocked = false;
354 const blockFirstScanPage: Statement.Transformer = (statement) => {
355 const [query] = statement.compile();
356 if (!blocked && query.includes("END AS prunable")) {
357 blocked = true;
358 return Deferred.succeed(scanStarted, undefined).pipe(
359 Effect.andThen(Deferred.await(releaseScan)),
360 Effect.as(statement),
361 );
362 }
363 return Effect.succeed(statement);
364 };
365 const pass = yield* maintenance
366 .pruneEventStore()
367 .pipe(
368 Effect.provideService(Statement.CurrentTransformer, blockFirstScanPage),
369 Effect.forkScoped,
370 );
371 yield* Deferred.await(scanStarted);
372 yield* sink.write({ events: subagentEvents(threadId, now, 0, "late") });
373 yield* Deferred.succeed(releaseScan, undefined);
374 assert.equal((yield* Fiber.join(pass)).deletedEventCount, 0);
375​
376 const late = yield* eventStore
377 .read({ threadId, eventType: "subagent.updated" })
378 .pipe(Stream.runCollect);
379 assert.deepEqual(
380 Array.from(late, (stored) =>
381 stored.event.type === "subagent.updated" ? stored.event.payload.prompt : null,
382 ),
383 ["Review prompt A. ".repeat(40), "Review prompt A. ".repeat(40)],
384 );
385 }),
386 ).pipe(Effect.provide(layerTest)),
387);
388​
389function messageUpdated(threadId: ThreadId, now: DateTime.Utc, text: string) {
390 return {
391 id: EventId.make(`event:purge:${threadId}:message`),
392 type: "message.updated",
393 threadId,
394 occurredAt: now,
395 payload: {
396 createdBy: "user",
397 creationSource: "web",
398 id: MessageId.make(`message:${threadId}`),
399 threadId,
400 runId: null,
401 nodeId: null,
402 role: "user",
403 text,
404 attachments: [],
405 streaming: false,
406 createdAt: now,
407 updatedAt: now,
408 },
409 } satisfies OrchestrationV2DomainEvent;
411​
412const writeThread = (thread: OrchestrationV2AppThread, now: DateTime.Utc) =>
413 Effect.flatMap(EventSink.EventSinkV2, (sink) =>
414 Effect.gen(function* () {
415 yield* sink.write({
416 events: [{ ...threadCreated(thread, now), id: EventId.make(`event:purge:${thread.id}`) }],
417 });
418 yield* sink.write({ events: [messageUpdated(thread.id, now, `secret in ${thread.id}`)] });
419 yield* sink.write({
420 events: [itemEvent(thread.id, now, itemSpecs[0], 0, `event:purge:${thread.id}:item`)],
421 });
422 }),
423 );
424​
425const deleteThread = (thread: OrchestrationV2AppThread, now: DateTime.Utc) =>
426 Effect.flatMap(EventSink.EventSinkV2, (sink) =>
427 sink.write({
428 events: [
429 {
430 id: EventId.make(`event:purge:${thread.id}:deleted`),
431 type: "thread.deleted",
432 threadId: thread.id,
433 providerInstanceId,
434 occurredAt: now,
435 payload: { ...thread, deletedAt: now, updatedAt: now },
436 },
437 ],
438 }),
439 );
440​
441const contentRowCount = (threadId: ThreadId) =>
442 Effect.flatMap(SqlClient.SqlClient, (sql) =>
443 Effect.forEach(ProjectionMaintenance.DELETED_THREAD_CONTENT_TABLES, (table) =>
444 sql<{ readonly count: number }>`
445 SELECT COUNT(*) AS count FROM ${sql(table)} WHERE thread_id = ${threadId}
446 `.pipe(Effect.map((rows) => rows[0]?.count ?? 0)),
447 ),
448 ).pipe(Effect.map((counts) => counts.reduce((sum, count) => sum + count, 0)));
449​
450const searchMatches = (text: string) =>
451 Effect.flatMap(
452 SqlClient.SqlClient,
453 (sql) => sql<{ readonly count: number }>`
454 SELECT COUNT(*) AS count FROM orchestration_v2_message_search
455 WHERE orchestration_v2_message_search MATCH ${`"${text}"`}
456 `,
457 ).pipe(Effect.map((rows) => rows[0]?.count ?? 0));
458​
459it.effect("a deleted thread keeps only its tombstone", () =>
460 Effect.gen(function* () {
461 const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
462 const projections = yield* ProjectionStore.ProjectionStoreV2;
463 const now = yield* DateTime.now;
464 const deleted = makeThread(ThreadId.make("thread:purge-deleted"), now);
465 const live = makeThread(ThreadId.make("thread:purge-live"), now);
466 yield* writeThread(deleted, now);
467 yield* writeThread(live, now);
468 const liveProjection = yield* projections.getThreadProjection(live.id);
469 assert.equal(yield* searchMatches("secret in thread:purge-deleted"), 1);
470​
471 yield* deleteThread(deleted, now);
472 assert.isAbove(yield* maintenance.purgeDeletedThread(deleted.id), 0);
473​
474 assert.equal(yield* contentRowCount(deleted.id), 0);
475 assert.equal(yield* searchMatches("secret in thread:purge-deleted"), 0);
476 assert.deepEqual(yield* remainingEventIds(deleted.id), [
477 "event:purge:thread:purge-deleted",
478 "event:purge:thread:purge-deleted:deleted",
479 ]);
480 const tombstone = yield* Effect.flatMap(
481 SqlClient.SqlClient,
482 (sql) => sql<{ readonly deleted_at: string | null; readonly title: string }>`
483 SELECT deleted_at, title FROM orchestration_v2_projection_threads
484 WHERE thread_id = ${deleted.id}
485 `,
486 );
487 assert.isNotNull(tombstone[0]?.deleted_at ?? null);
488 assert.equal(tombstone[0]?.title, ProjectionMaintenance.DELETED_THREAD_TITLE);
489 const leaked = yield* Effect.flatMap(
490 SqlClient.SqlClient,
491 (sql) => sql<{ readonly count: number }>`
492 SELECT
493 (SELECT COUNT(*) FROM orchestration_events
494 WHERE stream_id = ${deleted.id} AND payload_json LIKE ${`%${deleted.title}%`})
495 + (SELECT COUNT(*) FROM orchestration_v2_projection_threads
496 WHERE thread_id = ${deleted.id} AND payload_json LIKE ${`%${deleted.title}%`})
497 AS count
498 `,
499 );
500 assert.equal(leaked[0]?.count, 0);
501 assert.deepEqual(yield* projections.getThreadProjection(live.id), liveProjection);
502 assert.equal(yield* maintenance.purgeDeletedThread(deleted.id), 0);
503 }).pipe(Effect.provide(layerTest)),
504);
505​
506it.effect("a deleted run-fork source stays until its last live fork is deleted", () =>
507 Effect.gen(function* () {
508 const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
509 const now = yield* DateTime.now;
510 const source = makeThread(ThreadId.make("thread:purge-source"), now);
511 const fork: OrchestrationV2AppThread = {
512 ...makeThread(ThreadId.make("thread:purge-fork"), now),
513 forkedFrom: { type: "run", threadId: source.id, runId: RunId.make("run:purge-source") },
514 };
515 yield* writeThread(source, now);
516 yield* writeThread(fork, now);
517​
518 yield* deleteThread(source, now);
519 assert.equal(yield* maintenance.purgeDeletedThread(source.id), 0);
520 assert.isAbove(yield* contentRowCount(source.id), 0);
521​
522 yield* deleteThread(fork, now);
523 yield* maintenance.purgeDeletedThread(fork.id);
524 assert.equal(yield* contentRowCount(source.id), 0);
525 assert.equal(yield* contentRowCount(fork.id), 0);
526 }).pipe(Effect.provide(layerTest)),
527);
528​
529it.effect("the maintenance pass purges threads deleted before purging existed", () =>
530 Effect.gen(function* () {
531 const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
532 const now = yield* DateTime.now;
533 const deleted = makeThread(ThreadId.make("thread:purge-backfill"), now);
534 // Renamed to the placeholder before deletion; its first title is still on record.
535 const renamed = makeThread(ThreadId.make("thread:purge-renamed"), now);
536 yield* Effect.flatMap(EventSink.EventSinkV2, (sink) =>
537 sink.write({
538 events: [{ ...threadCreated(renamed, now), id: EventId.make("event:purge:renamed") }],
539 }),
540 );
541 yield* deleteThread({ ...renamed, title: ProjectionMaintenance.DELETED_THREAD_TITLE }, now);
542 yield* writeThread(deleted, now);
543 yield* deleteThread(deleted, now);
544 // A late transcript import leaves a content event as the stream head.
545 const sink = yield* EventSink.EventSinkV2;
546 yield* sink.write({
547 events: [itemEvent(deleted.id, now, itemSpecs[1], 0, "event:purge:late-item")],
548 });
549 const sql = yield* SqlClient.SqlClient;
550 yield* sql`
551 INSERT INTO orchestration_v2_effect_outbox (
552 effect_id, command_id, thread_id, effect_type, payload_json, status,
553 available_at, created_at, updated_at
554 ) VALUES (
555 'effect:purge-backfill', 'command:purge-backfill', ${deleted.id}, 'terminal.cleanup',
556 '{"type":"terminal.cleanup"}', 'pending', '2026-11-01T00:00:00.000Z',
557 '2026-11-01T00:00:00.000Z', '2026-11-01T00:00:00.000Z'
558 )
559 `;
560​
561 // An earlier effect still reads the thread, so the pass waits for it.
562 yield* maintenance.pruneEventStore();
563 assert.isAbove(yield* contentRowCount(deleted.id), 0);
564 yield* sql`UPDATE orchestration_v2_effect_outbox SET status = 'succeeded'`;
565​
566 assert.isAbove((yield* maintenance.pruneEventStore()).purgedRowCount, 0);
567 assert.equal(yield* contentRowCount(deleted.id), 0);
568 assert.deepEqual(yield* sql`SELECT effect_id FROM orchestration_v2_effect_outbox`, []);
569 const stream = yield* EventStore.EventStoreV2.pipe(
570 Effect.flatMap((store) => store.read({ threadId: deleted.id }).pipe(Stream.runCollect)),
571 );
572 assert.deepEqual(
573 Array.from(stream, (stored) => stored.event.type),
574 ["thread.created", "thread.deleted", "thread.deleted"],
575 );
576 const leaked = yield* sql<{ readonly count: number }>`
577 SELECT COUNT(*) AS count FROM orchestration_events
578 WHERE stream_id = ${deleted.id}
579 AND (payload_json LIKE '%reasoning:0%' OR payload_json LIKE ${`%${deleted.title}%`})
580 `;
581 assert.equal(leaked[0]?.count, 0);
582 const renamedLeaks = yield* sql<{ readonly count: number }>`
583 SELECT COUNT(*) AS count FROM orchestration_events
584 WHERE stream_id = ${renamed.id} AND payload_json LIKE ${`%${renamed.title}%`}
585 `;
586 assert.equal(renamedLeaks[0]?.count, 0);
587 assert.equal((yield* maintenance.pruneEventStore()).purgedRowCount, 0);
588 }).pipe(Effect.provide(layerTest)),
589);
590​
591it.effect("a deleted thread's leftover settled request is purged", () =>
592 Effect.gen(function* () {
593 const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
594 const sql = yield* SqlClient.SqlClient;
595 const now = yield* DateTime.now;
596 const thread = {
597 ...makeThread(ThreadId.make("thread:purge-placeholder"), now),
598 title: ProjectionMaintenance.DELETED_THREAD_TITLE,
599 };
600 yield* Effect.flatMap(EventSink.EventSinkV2, (sink) =>
601 sink.write({
602 events: [{ ...threadCreated(thread, now), id: EventId.make("event:purge:placeholder") }],
603 }),
604 );
605 // A rename in between left its private title in a settled request.
606 yield* sql`
607 INSERT INTO orchestration_v2_effect_outbox (
608 effect_id, command_id, thread_id, effect_type, payload_json, status,
609 available_at, created_at, updated_at
610 ) VALUES (
611 'effect:purge-placeholder', 'command:purge-placeholder', ${thread.id},
612 'provider-session.apply-thread-title',
613 '{"type":"provider-session.apply-thread-title","title":"private rename"}', 'succeeded',
614 '2026-11-01T00:00:00.000Z', '2026-11-01T00:00:00.000Z', '2026-11-01T00:00:00.000Z'
615 )
616 `;
617 yield* deleteThread(thread, now);
618​
619 // The sweep alone finds the leftover request too.
620 yield* maintenance.pruneEventStore();
621 assert.deepEqual(yield* sql`SELECT effect_id FROM orchestration_v2_effect_outbox`, []);
622​
623 // A pass interrupted after the content rows went still leaves a content event.
624 yield* Effect.flatMap(EventSink.EventSinkV2, (sink) =>
625 sink.write({ events: [itemEvent(thread.id, now, itemSpecs[0], 0, "event:purge:stray")] }),
626 );
627 yield* sql`DELETE FROM orchestration_v2_projection_turn_items WHERE thread_id = ${thread.id}`;
628 yield* sql`DELETE FROM orchestration_v2_turn_item_positions WHERE thread_id = ${thread.id}`;
629 yield* maintenance.pruneEventStore();
630 // It is the stream head, so its row stays as the tombstone.
631 assert.deepEqual(
632 yield* sql`SELECT event_type FROM orchestration_events WHERE event_id = 'event:purge:stray'`,
633 [{ event_type: "thread.deleted" }],
634 );
635 }).pipe(Effect.provide(layerTest)),
636);
637​
638it.effect("an interrupted purge leaves a stream that still decodes", () =>
639 Effect.gen(function* () {
640 const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
641 const eventStore = yield* EventStore.EventStoreV2;
642 const sink = yield* EventSink.EventSinkV2;
643 const now = yield* DateTime.now;
644 const thread = makeThread(ThreadId.make("thread:purge-interrupted"), now);
645 yield* sink.write({ events: [{ ...threadCreated(thread, now), id: EventId.make("event:i") }] });
646 yield* sink.write({ events: subagentEvents(thread.id, now, 0, "anchor") });
647 yield* deleteThread(thread, now);
648 // A late update borrows the anchor's prompt and becomes the stream head.
649 yield* sink.write({ events: subagentEvents(thread.id, now, 0, "borrower") });
650​
651 const failAfterEvents: Statement.Transformer = (statement) =>
652 statement.compile()[0].includes("DELETE FROM orchestration_v2_effect_outbox")
653 ? Effect.die("interrupted")
654 : Effect.succeed(statement);
655 const exit = yield* maintenance
656 .purgeDeletedThread(thread.id)
657 .pipe(Effect.provideService(Statement.CurrentTransformer, failAfterEvents), Effect.exit);
658 assert.isTrue(exit._tag === "Failure");
659​
660 const stream = yield* eventStore.read({ threadId: thread.id }).pipe(Stream.runCollect);
661 assert.equal(Array.from(stream).at(-1)?.event.type, "thread.deleted");
662 }).pipe(Effect.provide(layerTest)),
663);