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

ProjectionMaintenance.test.ts

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