TypeScript
fix(server): compact superseded history in the background (#19435)
Julius Marminge57522538182f
diff --git a/apps/server/src/mcp/ThreadMetadataMcpService.ts b/apps/server/src/mcp/ThreadMetadataMcpService.tsindex a997e2ede47..74176ec90c7 100644--- a/apps/server/src/mcp/ThreadMetadataMcpService.ts+++ b/apps/server/src/mcp/ThreadMetadataMcpService.ts@@ -111,7 +111,10 @@ function resultFromThread(input: {readonly action: ThreadMetadataMcpAction;readonly commandId: CommandId;readonly sequence: number;- readonly thread: OrchestrationV2AppThread;+ readonly thread: Pick<+ OrchestrationV2AppThread,+ "id" | "title" | "titleRegeneration" | "linkedPullRequest" | "updatedAt"+ >;}): ThreadMetadataMcpUpdateResult {return {threadId: input.thread.id,@@ -199,7 +202,15 @@ const make = Effect.gen(function* () {const metadataEvent = dispatched.storedEvents.find((stored) => stored.event.type === "thread.metadata-updated",);- if (metadataEvent === undefined || metadataEvent.event.type !== "thread.metadata-updated") {+ // A retried commandId replays the stored events of the first dispatch;+ // compaction may have deleted them by then, so answer from the projection.+ const thread =+ metadataEvent?.event.type === "thread.metadata-updated"+ ? metadataEvent.event.payload+ : yield* threadManagement+ .getThreadShell(threadId)+ .pipe(Effect.mapError((error) => failure("orchestration_error", errorMessage(error))));+ if (thread === null) {return yield* failure("orchestration_error",`Thread ${threadId} metadata update completed without a resultant state.`,@@ -209,7 +220,7 @@ const make = Effect.gen(function* () {action: input.action,commandId: updateCommandId,sequence: dispatched.sequence,- thread: metadataEvent.event.payload,+ thread,});});diff --git a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts b/apps/server/src/orchestration-v2/FoundationPersistence.test.tsindex e3082f5382d..06ac0ec190b 100644--- a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts+++ b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts@@ -967,8 +967,10 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => {`;const summary = yield* maintenance.compactEventStore;- // Superseded state spans several discovery pages. Both turn-item updates stay.- assert.isAtLeast(summary.deletedEventCount, 507);+ // Superseded state spans several discovery pages. Both turn-item updates+ // stay, and so do the first message and node events (replay order). The+ // rename stays too: visits are read state and only supersede each other.+ assert.isAtLeast(summary.deletedEventCount, 504);assert.isAtLeast(summary.deletedReceiptCount, 1);const remaining = yield* sql<{ readonly event_id: string }>`@@ -982,6 +984,9 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => {remaining.map((row) => row.event_id),["event:foundation-compact:create",+ "event:foundation-compact:meta",+ "event:foundation-compact:message-1",+ "event:foundation-compact:node-1","event:foundation-compact:item-1","event:foundation-compact:visit-2","event:foundation-compact:message-2",diff --git a/apps/server/src/orchestration-v2/ProjectionMaintenance.ts b/apps/server/src/orchestration-v2/ProjectionMaintenance.tsindex ccd7e383593..e5eda0df06a 100644--- a/apps/server/src/orchestration-v2/ProjectionMaintenance.ts+++ b/apps/server/src/orchestration-v2/ProjectionMaintenance.ts@@ -205,11 +205,11 @@ export const layer: Layer.Layer<// Thread-state events whose payload is the complete thread: only the// newest per thread can influence a replay or an afterSequence catch-up.// thread.created stays out — verify derives the expected thread set from- // it, and it anchors replay ordering.+ // it, and it anchors replay ordering. thread.deleted stays out too: clients+ // and waitForThread switch on the event type, not just the payload.const SUPERSEDABLE_THREAD_EVENT_TYPES = ["thread.archived","thread.unarchived",- "thread.deleted","thread.settled","thread.unsettled","thread.snoozed",@@ -225,16 +225,26 @@ export const layer: Layer.Layer<"thread.interaction-mode-updated","thread.model-selection-updated","thread.provider-switched",- "thread.visited",- "thread.marked-unread",];+ // Read-state events carry the whole thread too, but client reducers apply+ // them without bumping updatedAt. They supersede only each other: a newer+ // visit must not delete the rename that carries the activity timestamp,+ // while any newer activity-bearing event supersedes both groups.+ const READ_STATE_THREAD_EVENT_TYPES = ["thread.visited", "thread.marked-unread"];const supersedableThreadEventTypes = new Set(SUPERSEDABLE_THREAD_EVENT_TYPES);+ const readStateThreadEventTypes = new Set(READ_STATE_THREAD_EVENT_TYPES);// Keep subagent.updated and turn-item.updated rows: slimmed payloads reference their prompts.- const COMPACTION_PAGE_SIZE = 500;+ // Discovery runs on the shared synchronous connection; json_extract over+ // large payloads made 500-row pages block the event loop for ~90ms.+ const COMPACTION_PAGE_SIZE = 50;/**- * Scan newest first to retain the newest state for each entity.+ * Scan newest first to retain the newest state for each entity. Keyed+ * entities (messages, nodes, PR links) also keep their oldest event: client+ * reducers append an entity where they first see it, so a replay from any+ * cursor must either carry that first event or find the entity already+ * present. Only the events in between are deleted.* Page every event, including non-candidates: filtering before LIMIT could* still scan the entire history when superseded events are sparse.* turn-item.updated stays intact because replay assigns positions on first write.@@ -251,7 +261,10 @@ export const layer: Layer.Layer<let throughSequence = bounds[0]?.event_sequence ?? 0;let throughReceiptRowId = bounds[0]?.receipt_row_id ?? 0;const retainedThreadIds = new Set<string>();- const retainedEntityKeys = new Set<string>();+ const retainedReadStateThreadIds = new Set<string>();+ // Per key: the lowest sequence seen so far after the newest. It is+ // deleted once an even older event turns up and kept otherwise.+ const oldestCandidateByEntityKey = new Map<string, number | null>();let deletedEventCount = 0;let deletedReceiptCount = 0;@@ -275,6 +288,11 @@ export const layer: Layer.Layer<WHEN event.application_event_version = 2AND event.event_type IN ('message.updated', 'node.updated')THEN json_extract(event.payload_json, '$.id')+ WHEN event.application_event_version = 2+ AND event.event_type = 'thread.pull-request-link-updated'+ THEN json_array(json_extract(event.payload_json, '$.host'),+ json_extract(event.payload_json, '$.repository'),+ json_extract(event.payload_json, '$.number'))ELSE NULLEND AS entity_id,CASE@@ -302,10 +320,34 @@ export const layer: Layer.Layer<) {if (retainedThreadIds.has(row.stream_id)) obsolete.push(row.sequence);else retainedThreadIds.add(row.stream_id);- } else if (row.event_type === "message.updated" || row.event_type === "node.updated") {+ } else if (+ row.aggregate_kind === "thread" &&+ readStateThreadEventTypes.has(row.event_type)+ ) {+ if (+ retainedThreadIds.has(row.stream_id) ||+ retainedReadStateThreadIds.has(row.stream_id)+ ) {+ obsolete.push(row.sequence);+ } else retainedReadStateThreadIds.add(row.stream_id);+ } else if (+ row.event_type === "thread.pull-request-link-updated" &&+ retainedThreadIds.has(row.stream_id)+ ) {+ // A newer whole-thread payload already carries this link's state.+ obsolete.push(row.sequence);+ } else if (+ row.event_type === "thread.pull-request-link-updated" ||+ row.event_type === "message.updated" ||+ row.event_type === "node.updated"+ ) {const key = encodeEntityKey([row.event_type, row.stream_id, row.entity_id]);- if (retainedEntityKeys.has(key)) obsolete.push(row.sequence);- else retainedEntityKeys.add(key);+ const candidate = oldestCandidateByEntityKey.get(key);+ if (candidate === undefined) oldestCandidateByEntityKey.set(key, null);+ else {+ if (candidate !== null) obsolete.push(candidate);+ oldestCandidateByEntityKey.set(key, row.sequence);+ }}}}diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.tsindex d86a042e173..d8ec9305c0f 100644--- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts+++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts@@ -4950,11 +4950,88 @@ it.layer(Layer.fresh(layerSharedApplicationDataPlaneTest))("compact PR events",(yield* orchestrator.getThreadShell(threadId))?.pullRequests,after?.pullRequests,);+ // Later syncs of the same link supersede the ones between the first+ // (kept for replay order) and the newest.+ for (const [commandId, title] of [+ ["compact-pr-sync-again", "Still open PR"],+ ["compact-pr-sync-merged", "Merged PR"],+ ] as const) {+ yield* orchestrator.dispatch({+ type: "thread.pull-request-link.sync",+ commandId: CommandId.make(commandId),+ threadId,+ ...key,+ number: 2,+ snapshot: {+ state: title === "Merged PR" ? "merged" : "open",+ title,+ headBranch: "feature/pr",+ baseBranch: "main",+ isDraft: false,+ updatedAt: null,+ syncedAt: "2026-10-13T13:00:00.000Z",+ },+ stack: null,+ });+ }+ const latest = yield* orchestrator.getThreadShell(threadId);yield* maintenance.compactEventStore;+ const linkEvents = yield* sql<{ command_id: string }>`+ SELECT command_id FROM orchestration_events+ WHERE stream_id = ${threadId} AND event_type = 'thread.pull-request-link-updated'+ ORDER BY sequence+ `;+ assert.deepEqual(+ linkEvents.map((row) => row.command_id),+ ["compact-pr-sync", "compact-pr-sync-merged"],+ );assert.isTrue((yield* maintenance.rebuild).valid);assert.deepEqual((yield* orchestrator.getThreadShell(threadId))?.pullRequests,- after?.pullRequests,+ latest?.pullRequests,+ );++ // A later visit is read state only: clients keep updatedAt from the+ // rename, so compaction must keep the rename. Two visits supersede each+ // other, and a later rename supersedes a visit.+ const threadEvents = () => sql<{ event_type: string }>`+ SELECT event_type FROM orchestration_events+ WHERE stream_id = ${threadId}+ AND event_type IN ('thread.metadata-updated', 'thread.visited')+ ORDER BY sequence+ `;+ yield* orchestrator.dispatch({+ type: "thread.metadata.update",+ commandId: CommandId.make("compact-pr-rename"),+ threadId,+ title: "Renamed before visit",+ });+ for (const [commandId, visitedAt] of [+ ["compact-pr-visit", "2026-10-13T14:00:00.000Z"],+ ["compact-pr-visit-again", "2026-10-13T15:00:00.000Z"],+ ] as const) {+ yield* orchestrator.dispatch({+ type: "thread.visit",+ commandId: CommandId.make(commandId),+ threadId,+ visitedAt,+ });+ }+ yield* maintenance.compactEventStore;+ assert.deepEqual(+ (yield* threadEvents()).map((row) => row.event_type),+ ["thread.metadata-updated", "thread.visited"],+ );+ yield* orchestrator.dispatch({+ type: "thread.metadata.update",+ commandId: CommandId.make("compact-pr-rename-again"),+ threadId,+ title: "Renamed after visit",+ });+ yield* maintenance.compactEventStore;+ assert.deepEqual(+ (yield* threadEvents()).map((row) => row.event_type),+ ["thread.metadata-updated"],);}),);diff --git a/apps/server/src/persistence/DatabaseStorage.test.ts b/apps/server/src/persistence/DatabaseStorage.test.tsnew file mode 100644index 00000000000..59f9bf8b530--- /dev/null+++ b/apps/server/src/persistence/DatabaseStorage.test.ts@@ -0,0 +1,43 @@+import { assert, it } from "@effect/vitest";+import * as Effect from "effect/Effect";+import * as Layer from "effect/Layer";+import * as SqlClient from "effect/sql/SqlClient";++import * as EventStore from "../orchestration-v2/EventStore.ts";+import * as ProjectionMaintenance from "../orchestration-v2/ProjectionMaintenance.ts";+import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";+import * as DatabaseStorage from "./DatabaseStorage.ts";+import * as Sqlite from "./Sqlite.ts";++const freePages = Effect.map(+ Effect.flatMap(+ SqlClient.SqlClient,+ (sql) => sql<{ readonly freelist_count: number }>`PRAGMA freelist_count`,+ ),+ (rows) => rows[0]?.freelist_count ?? 0,+);++it.effect("a new database returns freed pages online without losing data", () =>+ Effect.gen(function* () {+ const sql = yield* SqlClient.SqlClient;+ const storage = yield* DatabaseStorage.DatabaseStorage;+ assert.deepEqual(yield* sql`PRAGMA auto_vacuum`, [{ auto_vacuum: 2 }]);+ yield* sql`CREATE TABLE retained (value TEXT)`;+ yield* sql`INSERT INTO retained VALUES ('keep')`;+ yield* sql`CREATE TABLE discarded (value BLOB)`;+ yield* sql`INSERT INTO discarded VALUES (zeroblob(1048576))`;+ yield* sql`DROP TABLE discarded`;+ assert.isAbove(yield* freePages, 0);+ yield* storage.reclaim;+ assert.equal(yield* freePages, 0);+ assert.deepEqual(yield* sql`SELECT value FROM retained`, [{ value: "keep" }]);+ }).pipe(+ Effect.provide(+ DatabaseStorage.layer.pipe(+ Layer.provide(ProjectionMaintenance.layer),+ Layer.provide(Layer.merge(EventStore.layer, ProjectionStore.layer)),+ Layer.provideMerge(Sqlite.layerMemory),+ ),+ ),+ ),+);diff --git a/apps/server/src/persistence/DatabaseStorage.ts b/apps/server/src/persistence/DatabaseStorage.tsnew file mode 100644index 00000000000..914ca51fa45--- /dev/null+++ b/apps/server/src/persistence/DatabaseStorage.ts@@ -0,0 +1,72 @@+import * as Context from "effect/Context";+import * as Effect from "effect/Effect";+import * as Layer from "effect/Layer";+import * as Schedule from "effect/Schedule";+import * as SqlClient from "effect/sql/SqlClient";++import * as ProjectionMaintenance from "../orchestration-v2/ProjectionMaintenance.ts";+import { forkParked } from "../serverActivation.ts";++/** Pages returned per reclaim pass; one minute of churn, not a backlog. */+const RECLAIM_PAGES_PER_PASS = 1024;++export class DatabaseStorage extends Context.Service<+ DatabaseStorage,+ {+ /** Return free pages to the filesystem on databases with incremental auto_vacuum. */+ readonly reclaim: Effect.Effect<void>;+ }+>()("t3/persistence/DatabaseStorage") {}++/**+ * Deletes superseded history every few hours and hands freed pages back to+ * the filesystem every minute. Deleted events are always superseded by a+ * retained event with a higher sequence, so a client replaying from an older+ * cursor still reaches the same state; no replay boundary is published.+ */+const make = Effect.gen(function* () {+ const sql = yield* SqlClient.SqlClient;+ const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;++ const reclaim = Effect.gen(function* () {+ const mode = yield* sql<{ readonly auto_vacuum: number }>`PRAGMA auto_vacuum`;+ if (mode[0]?.auto_vacuum !== 2) return;+ // The driver steps a statement without result columns once, and each+ // step of incremental_vacuum frees one page. Yield between pages so+ // client requests can run.+ for (let page = 0; page < RECLAIM_PAGES_PER_PASS; page++) {+ const free = yield* sql<{ readonly freelist_count: number }>`PRAGMA freelist_count`;+ if ((free[0]?.freelist_count ?? 0) === 0) break;+ yield* sql`PRAGMA incremental_vacuum(1)`;+ yield* Effect.yieldNow;+ }+ }).pipe(+ Effect.catch((cause) => Effect.logWarning("Database space reclamation failed", { cause })),+ );++ const compact = maintenance.compactEventStore.pipe(+ Effect.tap((result) =>+ result.deletedEventCount > 0 || result.deletedReceiptCount > 0+ ? Effect.logInfo("Compacted orchestration history", result)+ : Effect.void,+ ),+ Effect.catch((cause) =>+ Effect.logWarning("Orchestration history compaction failed", { cause }),+ ),+ );++ yield* forkParked(+ Effect.sleep("1 minute").pipe(+ Effect.andThen(compact.pipe(Effect.repeat(Schedule.spaced("6 hours")))),+ ),+ );+ yield* forkParked(+ Effect.sleep("1 minute").pipe(+ Effect.andThen(reclaim.pipe(Effect.repeat(Schedule.spaced("1 minute")))),+ ),+ );++ return DatabaseStorage.of({ reclaim });+});++export const layer = Layer.effect(DatabaseStorage, make);diff --git a/apps/server/src/persistence/Sqlite.ts b/apps/server/src/persistence/Sqlite.tsindex 1c49b578a0b..e89130414db 100644--- a/apps/server/src/persistence/Sqlite.ts+++ b/apps/server/src/persistence/Sqlite.ts@@ -18,6 +18,12 @@ const layerSetup = Layer.effectDiscard(// CLI and server write from separate processes; wait rather than fail with SQLITE_BUSY.yield* sql`PRAGMA busy_timeout = 5000;`;yield* sql`PRAGMA foreign_keys = ON;`;+ // Only an empty file can switch modes here; an existing database needs the+ // offline VACUUM that `t3 doctor` runs, which rebuilds it with pointer maps.+ const tables = yield* sql<{+ readonly count: number;+ }>`SELECT COUNT(*) AS count FROM sqlite_schema WHERE type = 'table'`;+ if (tables[0]?.count === 0) yield* sql`PRAGMA auto_vacuum = INCREMENTAL;`;yield* sql`PRAGMA journal_mode = WAL;`;// FULL fsyncs the WAL on every commit, on the main thread. Every provider// event is its own commit, so a slow or busy disk stalls the event loopdiff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex 23981a932e0..cd3cfafec6e 100644--- a/apps/server/src/server.ts+++ b/apps/server/src/server.ts@@ -3,6 +3,7 @@ import type { RelayManagedEndpointRuntimeConfig } from "@t3tools/contracts/relayimport * as Clock from "effect/Clock";import * as Random from "effect/Random";import * as Semaphore from "effect/Semaphore";+import * as DatabaseStorage from "./persistence/DatabaseStorage.ts";import * as StorageCleanup from "./storageCleanup.ts";import * as PullRequestSyncReactor from "./orchestration-v2/PullRequestSyncReactor.ts";import * as PullRequestWatchReactor from "./orchestration-v2/PullRequestWatchReactor.ts";@@ -171,6 +172,8 @@ import * as ResourceCleanupService from "./orchestration-v2/ResourceCleanupServiimport * as ThreadSettlementService from "./orchestration-v2/ThreadSettlementService.ts";import * as ThreadPullRequestService from "./orchestration-v2/ThreadPullRequestService.ts";import * as RunFinalizationService from "./orchestration-v2/RunFinalizationService.ts";+import * as EventStoreV2 from "./orchestration-v2/EventStore.ts";+import * as ProjectionMaintenance from "./orchestration-v2/ProjectionMaintenance.ts";import * as ProjectionStoreV2 from "./orchestration-v2/ProjectionStore.ts";import { makePersistedServerRuntimeState } from "./serverRuntimeState.ts";import * as OrchestrationHttp from "./orchestration-v2/http.ts";@@ -551,6 +554,12 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll(HeldHooksWaker.layer,layerThreadSettlementWorker,StorageCleanup.layer.pipe(Layer.provide(ProjectionStoreV2.layer)),+ DatabaseStorage.layer.pipe(+ Layer.provide(ProjectionMaintenance.layer),+ Layer.provide(+ Layer.merge(EventStoreV2.layerFromOrchestrationEventStore, ProjectionStoreV2.layer),+ ),+ ),layerThreadPullRequestWorker,Layer.effectDiscard(Effect.gen(function* () {diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.tsindex 476224cb2cd..6cbeb16e2a2 100644--- a/apps/server/src/ws.test.ts+++ b/apps/server/src/ws.test.ts@@ -24,6 +24,9 @@ import * as TestClock from "effect/testing/TestClock";import { ChildProcessSpawner } from "effect/process";import * as SqlClient from "effect/sql/SqlClient";+import * as EventStore from "./orchestration-v2/EventStore.ts";+import * as ProjectionMaintenance from "./orchestration-v2/ProjectionMaintenance.ts";+import * as ProjectionStore from "./orchestration-v2/ProjectionStore.ts";import * as ThreadManagement from "./orchestration-v2/ThreadManagementService.ts";import * as ProjectStore from "./orchestration-v2/ProjectStore.ts";import * as OrchestrationEventStore from "./persistence/OrchestrationEventStore.ts";@@ -364,3 +367,95 @@ it.live.each(["thread", "shell"] as const)();}).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)),);++// Compaction keeps the oldest and newest event per message, so a cursor older+// than the deleted rows still replays each message where the client would+// first have seen it (reducers append on first sight) and reaches the same+// final state. No snapshot fallback is needed.+it.effect("thread resume across compacted history keeps message order and final state", () =>+ Effect.gen(function* () {+ const sql = yield* SqlClient.SqlClient;+ const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;+ const now = "2026-10-13T00:00:00.000Z";+ const threadId = ThreadId.make("thread:compacted");+ const insertMessage = (version: number, id: string, text: string) => sql<{+ sequence: number;+ }>`+ INSERT INTO orchestration_events (+ event_id, aggregate_kind, stream_id, stream_version, event_type,+ occurred_at, actor_kind, payload_json, metadata_json, application_event_version+ ) VALUES (+ ${`compacted:${version}`}, 'thread', ${threadId}, ${version}, 'message.updated',+ ${now}, 'server', ${JSON.stringify({+ createdBy: "user",+ creationSource: "web",+ id,+ threadId,+ runId: null,+ nodeId: null,+ role: "user",+ text,+ attachments: [],+ streaming: false,+ createdAt: now,+ updatedAt: now,+ })}, '{}', 2+ ) RETURNING sequence+ `;+ const [first] = yield* insertMessage(0, "message:a", "a created");+ const [second] = yield* insertMessage(1, "message:b", "b created");+ yield* insertMessage(2, "message:a", "a superseded");+ const [head] = yield* insertMessage(3, "message:a", "a final");+ // thread.deleted is never superseded: clients switch on the event type.+ for (const version of [0, 1]) {+ yield* sql`+ INSERT INTO orchestration_events (+ event_id, aggregate_kind, stream_id, stream_version, event_type,+ occurred_at, actor_kind, payload_json, metadata_json, application_event_version+ ) VALUES (+ ${`deleted:${version}`}, 'thread', 'thread:deleted-twice', ${version}, 'thread.deleted',+ ${now}, 'server', '{}', '{}', 2+ )+ `;+ }+ // Only the event between a's first and newest is deleted.+ assert.equal((yield* maintenance.compactEventStore).deletedEventCount, 1);++ const items = yield* subscribeOrchestrationV2Thread({+ threadId,+ afterSequence: first!.sequence - 1,+ requestCompletionMarker: true,+ }).pipe(+ Effect.flatMap((stream) =>+ stream.pipe(+ Stream.takeUntil((item) => item.kind === "synchronized"),+ Stream.runCollect,+ ),+ ),+ Effect.provideService(ThreadManagement.ThreadManagementService, {+ ensureLegacyTranscript: () => Effect.void,+ streamStoredEventsFrom: () => Stream.never,+ } as unknown as ThreadManagement.ThreadManagementService["Service"]),+ );+ assert.deepEqual(+ Array.from(items, (item) =>+ item.kind === "event"+ ? [item.sequence, item.event.type === "message.updated" ? item.event.payload.text : null]+ : [item.kind],+ ),+ [+ [first!.sequence, "a created"],+ [second!.sequence, "b created"],+ [head!.sequence, "a final"],+ ["synchronized"],+ ],+ );+ }).pipe(+ Effect.provide(+ ProjectionMaintenance.layer.pipe(+ Layer.provide(Layer.merge(EventStore.layer, ProjectionStore.layer)),+ Layer.provideMerge(ReplayTestLayer),+ ),+ ),+ ),+);