@devries-cameron20 / t3code Mirror · read-only / commits / 5752253818
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 23, 09:15 UTC

fix(server): compact superseded history in the background (#19435)

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>

Julius Marminge committed Oct 15, 2026 at 17:03 UTC 57522538182fe9ffac2b96c4f35f45a10cc70440
9 files changed +376 -16
apps/server/src/mcp/ThreadMetadataMcpService.ts
+14 -3
@@ -111,7 +111,10 @@ function resultFromThread(input: {
111 readonly action: ThreadMetadataMcpAction;
112 readonly commandId: CommandId;
113 readonly sequence: number;
114 - readonly thread: OrchestrationV2AppThread;
114 + readonly thread: Pick<
115 + OrchestrationV2AppThread,
116 + "id" | "title" | "titleRegeneration" | "linkedPullRequest" | "updatedAt"
117 + >;
118 }): ThreadMetadataMcpUpdateResult {
119 return {
120 threadId: input.thread.id,
@@ -199,7 +202,15 @@ const make = Effect.gen(function* () {
202 const metadataEvent = dispatched.storedEvents.find(
203 (stored) => stored.event.type === "thread.metadata-updated",
204 );
202 - if (metadataEvent === undefined || metadataEvent.event.type !== "thread.metadata-updated") {
205 + // A retried commandId replays the stored events of the first dispatch;
206 + // compaction may have deleted them by then, so answer from the projection.
207 + const thread =
208 + metadataEvent?.event.type === "thread.metadata-updated"
209 + ? metadataEvent.event.payload
210 + : yield* threadManagement
211 + .getThreadShell(threadId)
212 + .pipe(Effect.mapError((error) => failure("orchestration_error", errorMessage(error))));
213 + if (thread === null) {
214 return yield* failure(
215 "orchestration_error",
216 `Thread ${threadId} metadata update completed without a resultant state.`,
@@ -209,7 +220,7 @@ const make = Effect.gen(function* () {
220 action: input.action,
221 commandId: updateCommandId,
222 sequence: dispatched.sequence,
212 - thread: metadataEvent.event.payload,
223 + thread,
224 });
225 });
226
apps/server/src/orchestration-v2/FoundationPersistence.test.ts
+7 -2
@@ -967,8 +967,10 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => {
967 `;
968
969 const summary = yield* maintenance.compactEventStore;
970 - // Superseded state spans several discovery pages. Both turn-item updates stay.
971 - assert.isAtLeast(summary.deletedEventCount, 507);
970 + // Superseded state spans several discovery pages. Both turn-item updates
971 + // stay, and so do the first message and node events (replay order). The
972 + // rename stays too: visits are read state and only supersede each other.
973 + assert.isAtLeast(summary.deletedEventCount, 504);
974 assert.isAtLeast(summary.deletedReceiptCount, 1);
975
976 const remaining = yield* sql<{ readonly event_id: string }>`
@@ -982,6 +984,9 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => {
984 remaining.map((row) => row.event_id),
985 [
986 "event:foundation-compact:create",
987 + "event:foundation-compact:meta",
988 + "event:foundation-compact:message-1",
989 + "event:foundation-compact:node-1",
990 "event:foundation-compact:item-1",
991 "event:foundation-compact:visit-2",
992 "event:foundation-compact:message-2",
apps/server/src/orchestration-v2/ProjectionMaintenance.ts
+52 -10
@@ -205,11 +205,11 @@ export const layer: Layer.Layer<
205 // Thread-state events whose payload is the complete thread: only the
206 // newest per thread can influence a replay or an afterSequence catch-up.
207 // thread.created stays out — verify derives the expected thread set from
208 - // it, and it anchors replay ordering.
208 + // it, and it anchors replay ordering. thread.deleted stays out too: clients
209 + // and waitForThread switch on the event type, not just the payload.
210 const SUPERSEDABLE_THREAD_EVENT_TYPES = [
211 "thread.archived",
212 "thread.unarchived",
212 - "thread.deleted",
213 "thread.settled",
214 "thread.unsettled",
215 "thread.snoozed",
@@ -225,16 +225,26 @@ export const layer: Layer.Layer<
225 "thread.interaction-mode-updated",
226 "thread.model-selection-updated",
227 "thread.provider-switched",
228 - "thread.visited",
229 - "thread.marked-unread",
228 ];
229 + // Read-state events carry the whole thread too, but client reducers apply
230 + // them without bumping updatedAt. They supersede only each other: a newer
231 + // visit must not delete the rename that carries the activity timestamp,
232 + // while any newer activity-bearing event supersedes both groups.
233 + const READ_STATE_THREAD_EVENT_TYPES = ["thread.visited", "thread.marked-unread"];
234
235 const supersedableThreadEventTypes = new Set(SUPERSEDABLE_THREAD_EVENT_TYPES);
236 + const readStateThreadEventTypes = new Set(READ_STATE_THREAD_EVENT_TYPES);
237 // Keep subagent.updated and turn-item.updated rows: slimmed payloads reference their prompts.
234 - const COMPACTION_PAGE_SIZE = 500;
238 + // Discovery runs on the shared synchronous connection; json_extract over
239 + // large payloads made 500-row pages block the event loop for ~90ms.
240 + const COMPACTION_PAGE_SIZE = 50;
241
242 /**
237 - * Scan newest first to retain the newest state for each entity.
243 + * Scan newest first to retain the newest state for each entity. Keyed
244 + * entities (messages, nodes, PR links) also keep their oldest event: client
245 + * reducers append an entity where they first see it, so a replay from any
246 + * cursor must either carry that first event or find the entity already
247 + * present. Only the events in between are deleted.
248 * Page every event, including non-candidates: filtering before LIMIT could
249 * still scan the entire history when superseded events are sparse.
250 * turn-item.updated stays intact because replay assigns positions on first write.
@@ -251,7 +261,10 @@ export const layer: Layer.Layer<
261 let throughSequence = bounds[0]?.event_sequence ?? 0;
262 let throughReceiptRowId = bounds[0]?.receipt_row_id ?? 0;
263 const retainedThreadIds = new Set<string>();
254 - const retainedEntityKeys = new Set<string>();
264 + const retainedReadStateThreadIds = new Set<string>();
265 + // Per key: the lowest sequence seen so far after the newest. It is
266 + // deleted once an even older event turns up and kept otherwise.
267 + const oldestCandidateByEntityKey = new Map<string, number | null>();
268 let deletedEventCount = 0;
269 let deletedReceiptCount = 0;
270
@@ -275,6 +288,11 @@ export const layer: Layer.Layer<
288 WHEN event.application_event_version = 2
289 AND event.event_type IN ('message.updated', 'node.updated')
290 THEN json_extract(event.payload_json, '$.id')
291 + WHEN event.application_event_version = 2
292 + AND event.event_type = 'thread.pull-request-link-updated'
293 + THEN json_array(json_extract(event.payload_json, '$.host'),
294 + json_extract(event.payload_json, '$.repository'),
295 + json_extract(event.payload_json, '$.number'))
296 ELSE NULL
297 END AS entity_id,
298 CASE
@@ -302,10 +320,34 @@ export const layer: Layer.Layer<
320 ) {
321 if (retainedThreadIds.has(row.stream_id)) obsolete.push(row.sequence);
322 else retainedThreadIds.add(row.stream_id);
305 - } else if (row.event_type === "message.updated" || row.event_type === "node.updated") {
323 + } else if (
324 + row.aggregate_kind === "thread" &&
325 + readStateThreadEventTypes.has(row.event_type)
326 + ) {
327 + if (
328 + retainedThreadIds.has(row.stream_id) ||
329 + retainedReadStateThreadIds.has(row.stream_id)
330 + ) {
331 + obsolete.push(row.sequence);
332 + } else retainedReadStateThreadIds.add(row.stream_id);
333 + } else if (
334 + row.event_type === "thread.pull-request-link-updated" &&
335 + retainedThreadIds.has(row.stream_id)
336 + ) {
337 + // A newer whole-thread payload already carries this link's state.
338 + obsolete.push(row.sequence);
339 + } else if (
340 + row.event_type === "thread.pull-request-link-updated" ||
341 + row.event_type === "message.updated" ||
342 + row.event_type === "node.updated"
343 + ) {
344 const key = encodeEntityKey([row.event_type, row.stream_id, row.entity_id]);
307 - if (retainedEntityKeys.has(key)) obsolete.push(row.sequence);
308 - else retainedEntityKeys.add(key);
345 + const candidate = oldestCandidateByEntityKey.get(key);
346 + if (candidate === undefined) oldestCandidateByEntityKey.set(key, null);
347 + else {
348 + if (candidate !== null) obsolete.push(candidate);
349 + oldestCandidateByEntityKey.set(key, row.sequence);
350 + }
351 }
352 }
353 }
apps/server/src/orchestration-v2/runtimeLayer.test.ts
+78 -1
@@ -4950,11 +4950,88 @@ it.layer(Layer.fresh(layerSharedApplicationDataPlaneTest))("compact PR events",
4950 (yield* orchestrator.getThreadShell(threadId))?.pullRequests,
4951 after?.pullRequests,
4952 );
4953 + // Later syncs of the same link supersede the ones between the first
4954 + // (kept for replay order) and the newest.
4955 + for (const [commandId, title] of [
4956 + ["compact-pr-sync-again", "Still open PR"],
4957 + ["compact-pr-sync-merged", "Merged PR"],
4958 + ] as const) {
4959 + yield* orchestrator.dispatch({
4960 + type: "thread.pull-request-link.sync",
4961 + commandId: CommandId.make(commandId),
4962 + threadId,
4963 + ...key,
4964 + number: 2,
4965 + snapshot: {
4966 + state: title === "Merged PR" ? "merged" : "open",
4967 + title,
4968 + headBranch: "feature/pr",
4969 + baseBranch: "main",
4970 + isDraft: false,
4971 + updatedAt: null,
4972 + syncedAt: "2026-10-13T13:00:00.000Z",
4973 + },
4974 + stack: null,
4975 + });
4976 + }
4977 + const latest = yield* orchestrator.getThreadShell(threadId);
4978 yield* maintenance.compactEventStore;
4979 + const linkEvents = yield* sql<{ command_id: string }>`
4980 + SELECT command_id FROM orchestration_events
4981 + WHERE stream_id = ${threadId} AND event_type = 'thread.pull-request-link-updated'
4982 + ORDER BY sequence
4983 + `;
4984 + assert.deepEqual(
4985 + linkEvents.map((row) => row.command_id),
4986 + ["compact-pr-sync", "compact-pr-sync-merged"],
4987 + );
4988 assert.isTrue((yield* maintenance.rebuild).valid);
4989 assert.deepEqual(
4990 (yield* orchestrator.getThreadShell(threadId))?.pullRequests,
4957 - after?.pullRequests,
4991 + latest?.pullRequests,
4992 + );
4993 +
4994 + // A later visit is read state only: clients keep updatedAt from the
4995 + // rename, so compaction must keep the rename. Two visits supersede each
4996 + // other, and a later rename supersedes a visit.
4997 + const threadEvents = () => sql<{ event_type: string }>`
4998 + SELECT event_type FROM orchestration_events
4999 + WHERE stream_id = ${threadId}
5000 + AND event_type IN ('thread.metadata-updated', 'thread.visited')
5001 + ORDER BY sequence
5002 + `;
5003 + yield* orchestrator.dispatch({
5004 + type: "thread.metadata.update",
5005 + commandId: CommandId.make("compact-pr-rename"),
5006 + threadId,
5007 + title: "Renamed before visit",
5008 + });
5009 + for (const [commandId, visitedAt] of [
5010 + ["compact-pr-visit", "2026-10-13T14:00:00.000Z"],
5011 + ["compact-pr-visit-again", "2026-10-13T15:00:00.000Z"],
5012 + ] as const) {
5013 + yield* orchestrator.dispatch({
5014 + type: "thread.visit",
5015 + commandId: CommandId.make(commandId),
5016 + threadId,
5017 + visitedAt,
5018 + });
5019 + }
5020 + yield* maintenance.compactEventStore;
5021 + assert.deepEqual(
5022 + (yield* threadEvents()).map((row) => row.event_type),
5023 + ["thread.metadata-updated", "thread.visited"],
5024 + );
5025 + yield* orchestrator.dispatch({
5026 + type: "thread.metadata.update",
5027 + commandId: CommandId.make("compact-pr-rename-again"),
5028 + threadId,
5029 + title: "Renamed after visit",
5030 + });
5031 + yield* maintenance.compactEventStore;
5032 + assert.deepEqual(
5033 + (yield* threadEvents()).map((row) => row.event_type),
5034 + ["thread.metadata-updated"],
5035 );
5036 }),
5037 );
apps/server/src/persistence/DatabaseStorage.test.ts new
+43
@@ -0,0 +1,43 @@
1 +import { assert, it } from "@effect/vitest";
2 +import * as Effect from "effect/Effect";
3 +import * as Layer from "effect/Layer";
4 +import * as SqlClient from "effect/sql/SqlClient";
5 +
6 +import * as EventStore from "../orchestration-v2/EventStore.ts";
7 +import * as ProjectionMaintenance from "../orchestration-v2/ProjectionMaintenance.ts";
8 +import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
9 +import * as DatabaseStorage from "./DatabaseStorage.ts";
10 +import * as Sqlite from "./Sqlite.ts";
11 +
12 +const freePages = Effect.map(
13 + Effect.flatMap(
14 + SqlClient.SqlClient,
15 + (sql) => sql<{ readonly freelist_count: number }>`PRAGMA freelist_count`,
16 + ),
17 + (rows) => rows[0]?.freelist_count ?? 0,
18 +);
19 +
20 +it.effect("a new database returns freed pages online without losing data", () =>
21 + Effect.gen(function* () {
22 + const sql = yield* SqlClient.SqlClient;
23 + const storage = yield* DatabaseStorage.DatabaseStorage;
24 + assert.deepEqual(yield* sql`PRAGMA auto_vacuum`, [{ auto_vacuum: 2 }]);
25 + yield* sql`CREATE TABLE retained (value TEXT)`;
26 + yield* sql`INSERT INTO retained VALUES ('keep')`;
27 + yield* sql`CREATE TABLE discarded (value BLOB)`;
28 + yield* sql`INSERT INTO discarded VALUES (zeroblob(1048576))`;
29 + yield* sql`DROP TABLE discarded`;
30 + assert.isAbove(yield* freePages, 0);
31 + yield* storage.reclaim;
32 + assert.equal(yield* freePages, 0);
33 + assert.deepEqual(yield* sql`SELECT value FROM retained`, [{ value: "keep" }]);
34 + }).pipe(
35 + Effect.provide(
36 + DatabaseStorage.layer.pipe(
37 + Layer.provide(ProjectionMaintenance.layer),
38 + Layer.provide(Layer.merge(EventStore.layer, ProjectionStore.layer)),
39 + Layer.provideMerge(Sqlite.layerMemory),
40 + ),
41 + ),
42 + ),
43 +);
apps/server/src/persistence/DatabaseStorage.ts new
+72
@@ -0,0 +1,72 @@
1 +import * as Context from "effect/Context";
2 +import * as Effect from "effect/Effect";
3 +import * as Layer from "effect/Layer";
4 +import * as Schedule from "effect/Schedule";
5 +import * as SqlClient from "effect/sql/SqlClient";
6 +
7 +import * as ProjectionMaintenance from "../orchestration-v2/ProjectionMaintenance.ts";
8 +import { forkParked } from "../serverActivation.ts";
9 +
10 +/** Pages returned per reclaim pass; one minute of churn, not a backlog. */
11 +const RECLAIM_PAGES_PER_PASS = 1024;
12 +
13 +export class DatabaseStorage extends Context.Service<
14 + DatabaseStorage,
15 + {
16 + /** Return free pages to the filesystem on databases with incremental auto_vacuum. */
17 + readonly reclaim: Effect.Effect<void>;
18 + }
19 +>()("t3/persistence/DatabaseStorage") {}
20 +
21 +/**
22 + * Deletes superseded history every few hours and hands freed pages back to
23 + * the filesystem every minute. Deleted events are always superseded by a
24 + * retained event with a higher sequence, so a client replaying from an older
25 + * cursor still reaches the same state; no replay boundary is published.
26 + */
27 +const make = Effect.gen(function* () {
28 + const sql = yield* SqlClient.SqlClient;
29 + const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
30 +
31 + const reclaim = Effect.gen(function* () {
32 + const mode = yield* sql<{ readonly auto_vacuum: number }>`PRAGMA auto_vacuum`;
33 + if (mode[0]?.auto_vacuum !== 2) return;
34 + // The driver steps a statement without result columns once, and each
35 + // step of incremental_vacuum frees one page. Yield between pages so
36 + // client requests can run.
37 + for (let page = 0; page < RECLAIM_PAGES_PER_PASS; page++) {
38 + const free = yield* sql<{ readonly freelist_count: number }>`PRAGMA freelist_count`;
39 + if ((free[0]?.freelist_count ?? 0) === 0) break;
40 + yield* sql`PRAGMA incremental_vacuum(1)`;
41 + yield* Effect.yieldNow;
42 + }
43 + }).pipe(
44 + Effect.catch((cause) => Effect.logWarning("Database space reclamation failed", { cause })),
45 + );
46 +
47 + const compact = maintenance.compactEventStore.pipe(
48 + Effect.tap((result) =>
49 + result.deletedEventCount > 0 || result.deletedReceiptCount > 0
50 + ? Effect.logInfo("Compacted orchestration history", result)
51 + : Effect.void,
52 + ),
53 + Effect.catch((cause) =>
54 + Effect.logWarning("Orchestration history compaction failed", { cause }),
55 + ),
56 + );
57 +
58 + yield* forkParked(
59 + Effect.sleep("1 minute").pipe(
60 + Effect.andThen(compact.pipe(Effect.repeat(Schedule.spaced("6 hours")))),
61 + ),
62 + );
63 + yield* forkParked(
64 + Effect.sleep("1 minute").pipe(
65 + Effect.andThen(reclaim.pipe(Effect.repeat(Schedule.spaced("1 minute")))),
66 + ),
67 + );
68 +
69 + return DatabaseStorage.of({ reclaim });
70 +});
71 +
72 +export const layer = Layer.effect(DatabaseStorage, make);
apps/server/src/persistence/Sqlite.ts
+6
@@ -18,6 +18,12 @@ const layerSetup = Layer.effectDiscard(
18 // CLI and server write from separate processes; wait rather than fail with SQLITE_BUSY.
19 yield* sql`PRAGMA busy_timeout = 5000;`;
20 yield* sql`PRAGMA foreign_keys = ON;`;
21 + // Only an empty file can switch modes here; an existing database needs the
22 + // offline VACUUM that `t3 doctor` runs, which rebuilds it with pointer maps.
23 + const tables = yield* sql<{
24 + readonly count: number;
25 + }>`SELECT COUNT(*) AS count FROM sqlite_schema WHERE type = 'table'`;
26 + if (tables[0]?.count === 0) yield* sql`PRAGMA auto_vacuum = INCREMENTAL;`;
27 yield* sql`PRAGMA journal_mode = WAL;`;
28 // FULL fsyncs the WAL on every commit, on the main thread. Every provider
29 // event is its own commit, so a slow or busy disk stalls the event loop
apps/server/src/server.ts
+9
@@ -3,6 +3,7 @@ import type { RelayManagedEndpointRuntimeConfig } from "@t3tools/contracts/relay
3 import * as Clock from "effect/Clock";
4 import * as Random from "effect/Random";
5 import * as Semaphore from "effect/Semaphore";
6 +import * as DatabaseStorage from "./persistence/DatabaseStorage.ts";
7 import * as StorageCleanup from "./storageCleanup.ts";
8 import * as PullRequestSyncReactor from "./orchestration-v2/PullRequestSyncReactor.ts";
9 import * as PullRequestWatchReactor from "./orchestration-v2/PullRequestWatchReactor.ts";
@@ -171,6 +172,8 @@ import * as ResourceCleanupService from "./orchestration-v2/ResourceCleanupServi
172 import * as ThreadSettlementService from "./orchestration-v2/ThreadSettlementService.ts";
173 import * as ThreadPullRequestService from "./orchestration-v2/ThreadPullRequestService.ts";
174 import * as RunFinalizationService from "./orchestration-v2/RunFinalizationService.ts";
175 +import * as EventStoreV2 from "./orchestration-v2/EventStore.ts";
176 +import * as ProjectionMaintenance from "./orchestration-v2/ProjectionMaintenance.ts";
177 import * as ProjectionStoreV2 from "./orchestration-v2/ProjectionStore.ts";
178 import { makePersistedServerRuntimeState } from "./serverRuntimeState.ts";
179 import * as OrchestrationHttp from "./orchestration-v2/http.ts";
@@ -551,6 +554,12 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll(
554 HeldHooksWaker.layer,
555 layerThreadSettlementWorker,
556 StorageCleanup.layer.pipe(Layer.provide(ProjectionStoreV2.layer)),
557 + DatabaseStorage.layer.pipe(
558 + Layer.provide(ProjectionMaintenance.layer),
559 + Layer.provide(
560 + Layer.merge(EventStoreV2.layerFromOrchestrationEventStore, ProjectionStoreV2.layer),
561 + ),
562 + ),
563 layerThreadPullRequestWorker,
564 Layer.effectDiscard(
565 Effect.gen(function* () {
apps/server/src/ws.test.ts
+95
@@ -24,6 +24,9 @@ import * as TestClock from "effect/testing/TestClock";
24 import { ChildProcessSpawner } from "effect/process";
25 import * as SqlClient from "effect/sql/SqlClient";
26
27 +import * as EventStore from "./orchestration-v2/EventStore.ts";
28 +import * as ProjectionMaintenance from "./orchestration-v2/ProjectionMaintenance.ts";
29 +import * as ProjectionStore from "./orchestration-v2/ProjectionStore.ts";
30 import * as ThreadManagement from "./orchestration-v2/ThreadManagementService.ts";
31 import * as ProjectStore from "./orchestration-v2/ProjectStore.ts";
32 import * as OrchestrationEventStore from "./persistence/OrchestrationEventStore.ts";
@@ -364,3 +367,95 @@ it.live.each(["thread", "shell"] as const)(
367 );
368 }).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)),
369 );
370 +
371 +// Compaction keeps the oldest and newest event per message, so a cursor older
372 +// than the deleted rows still replays each message where the client would
373 +// first have seen it (reducers append on first sight) and reaches the same
374 +// final state. No snapshot fallback is needed.
375 +it.effect("thread resume across compacted history keeps message order and final state", () =>
376 + Effect.gen(function* () {
377 + const sql = yield* SqlClient.SqlClient;
378 + const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
379 + const now = "2026-10-13T00:00:00.000Z";
380 + const threadId = ThreadId.make("thread:compacted");
381 + const insertMessage = (version: number, id: string, text: string) => sql<{
382 + sequence: number;
383 + }>`
384 + INSERT INTO orchestration_events (
385 + event_id, aggregate_kind, stream_id, stream_version, event_type,
386 + occurred_at, actor_kind, payload_json, metadata_json, application_event_version
387 + ) VALUES (
388 + ${`compacted:${version}`}, 'thread', ${threadId}, ${version}, 'message.updated',
389 + ${now}, 'server', ${JSON.stringify({
390 + createdBy: "user",
391 + creationSource: "web",
392 + id,
393 + threadId,
394 + runId: null,
395 + nodeId: null,
396 + role: "user",
397 + text,
398 + attachments: [],
399 + streaming: false,
400 + createdAt: now,
401 + updatedAt: now,
402 + })}, '{}', 2
403 + ) RETURNING sequence
404 + `;
405 + const [first] = yield* insertMessage(0, "message:a", "a created");
406 + const [second] = yield* insertMessage(1, "message:b", "b created");
407 + yield* insertMessage(2, "message:a", "a superseded");
408 + const [head] = yield* insertMessage(3, "message:a", "a final");
409 + // thread.deleted is never superseded: clients switch on the event type.
410 + for (const version of [0, 1]) {
411 + yield* sql`
412 + INSERT INTO orchestration_events (
413 + event_id, aggregate_kind, stream_id, stream_version, event_type,
414 + occurred_at, actor_kind, payload_json, metadata_json, application_event_version
415 + ) VALUES (
416 + ${`deleted:${version}`}, 'thread', 'thread:deleted-twice', ${version}, 'thread.deleted',
417 + ${now}, 'server', '{}', '{}', 2
418 + )
419 + `;
420 + }
421 + // Only the event between a's first and newest is deleted.
422 + assert.equal((yield* maintenance.compactEventStore).deletedEventCount, 1);
423 +
424 + const items = yield* subscribeOrchestrationV2Thread({
425 + threadId,
426 + afterSequence: first!.sequence - 1,
427 + requestCompletionMarker: true,
428 + }).pipe(
429 + Effect.flatMap((stream) =>
430 + stream.pipe(
431 + Stream.takeUntil((item) => item.kind === "synchronized"),
432 + Stream.runCollect,
433 + ),
434 + ),
435 + Effect.provideService(ThreadManagement.ThreadManagementService, {
436 + ensureLegacyTranscript: () => Effect.void,
437 + streamStoredEventsFrom: () => Stream.never,
438 + } as unknown as ThreadManagement.ThreadManagementService["Service"]),
439 + );
440 + assert.deepEqual(
441 + Array.from(items, (item) =>
442 + item.kind === "event"
443 + ? [item.sequence, item.event.type === "message.updated" ? item.event.payload.text : null]
444 + : [item.kind],
445 + ),
446 + [
447 + [first!.sequence, "a created"],
448 + [second!.sequence, "b created"],
449 + [head!.sequence, "a final"],
450 + ["synchronized"],
451 + ],
452 + );
453 + }).pipe(
454 + Effect.provide(
455 + ProjectionMaintenance.layer.pipe(
456 + Layer.provide(Layer.merge(EventStore.layer, ProjectionStore.layer)),
457 + Layer.provideMerge(ReplayTestLayer),
458 + ),
459 + ),
460 + ),
461 +);