TypeScript
perf(server): replay only the selected thread (#9726)
Theo Browne50bfca43d76c
diff --git a/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts b/apps/server/src/orchestration/Layers/OrchestrationEngine.test.tsindex 820002737f4..866e56ac037 100644--- a/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts+++ b/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts@@ -325,6 +325,8 @@ describe("OrchestrationEngine", () => {}),),hasEventAfter: () => Effect.succeed(false),+ readAggregateRange: () => Stream.die("unused aggregate replay"),+ getAggregateReplayStats: () => Effect.die("unused aggregate replay stats"),};const projectionSnapshot = {@@ -1235,6 +1237,8 @@ describe("OrchestrationEngine", () => {return Stream.fromIterable(events);},hasEventAfter: () => Effect.succeed(false),+ readAggregateRange: () => Stream.die("unused aggregate replay"),+ getAggregateReplayStats: () => Effect.die("unused aggregate replay stats"),};const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {@@ -1473,6 +1477,8 @@ describe("OrchestrationEngine", () => {return Stream.fromIterable(events);},hasEventAfter: () => Effect.succeed(false),+ readAggregateRange: () => Stream.die("unused aggregate replay"),+ getAggregateReplayStats: () => Effect.die("unused aggregate replay stats"),};let shouldFailProjection = true;diff --git a/apps/server/src/orchestration/Layers/OrchestrationEngine.ts b/apps/server/src/orchestration/Layers/OrchestrationEngine.tsindex 792dd0da390..8512007ae8d 100644--- a/apps/server/src/orchestration/Layers/OrchestrationEngine.ts+++ b/apps/server/src/orchestration/Layers/OrchestrationEngine.ts@@ -381,6 +381,19 @@ const makeOrchestrationEngine = Effect.gen(function* () {const readEvents: OrchestrationEngineShape["readEvents"] = (fromSequenceExclusive, limit) =>eventStore.readFromSequence(fromSequenceExclusive, limit);+ const readThreadEvents: OrchestrationEngineShape["readThreadEvents"] = ({ threadId, ...range }) =>+ eventStore.readAggregateRange({ ...range, aggregateKind: "thread", aggregateId: threadId });++ const getThreadReplayStats: OrchestrationEngineShape["getThreadReplayStats"] = ({+ threadId,+ ...range+ }) =>+ eventStore.getAggregateReplayStats({+ ...range,+ aggregateKind: "thread",+ aggregateId: threadId,+ });+const dispatch: OrchestrationEngineShape["dispatch"] = (command, options) =>Effect.gen(function* () {const result = yield* Deferred.make<{ sequence: number }, OrchestrationDispatchError>();@@ -395,6 +408,8 @@ const makeOrchestrationEngine = Effect.gen(function* () {return {readEvents,+ readThreadEvents,+ getThreadReplayStats,dispatch,subscribeDomainEvents: PubSub.subscribe(eventPubSub).pipe(Effect.map(Stream.fromSubscription)),// Each access creates a fresh PubSub subscription so that multiplediff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.tsindex 1c5e834ec2d..b9478b1b5f5 100644--- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts+++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts@@ -418,6 +418,8 @@ describe("ProviderCommandReactor", () => {const engine = yield* OrchestrationEngineService;return {readEvents: engine.readEvents,+ readThreadEvents: engine.readThreadEvents,+ getThreadReplayStats: engine.getThreadReplayStats,dispatch: (command) => {if (command.type === "thread.title.regeneration.complete") {titleRegenerationCompletionDispatchAttempts += 1;diff --git a/apps/server/src/orchestration/Services/OrchestrationEngine.ts b/apps/server/src/orchestration/Services/OrchestrationEngine.tsindex 08f63c47642..cf2ef2a4035 100644--- a/apps/server/src/orchestration/Services/OrchestrationEngine.ts+++ b/apps/server/src/orchestration/Services/OrchestrationEngine.ts@@ -14,6 +14,7 @@ import type {OrchestrationClientOrigin,OrchestrationCommand,OrchestrationEvent,+ ThreadId,} from "@t3tools/contracts";import * as Context from "effect/Context";import type * as Effect from "effect/Effect";@@ -22,6 +23,13 @@ import type * as Stream from "effect/Stream";import type { OrchestrationDispatchError } from "../Errors.ts";import type { OrchestrationEventStoreError } from "../../persistence/Errors.ts";+import type { OrchestrationAggregateReplayStats } from "../../persistence/Services/OrchestrationEventStore.ts";++export interface OrchestrationThreadReplayRange {+ readonly threadId: ThreadId;+ readonly fromSequenceExclusive: number;+ readonly toSequenceInclusive: number;+}/*** OrchestrationEngineShape - Service API for orchestration command and event flow.@@ -33,8 +41,7 @@ export interface OrchestrationEngineShape {* @param fromSequenceExclusive - Sequence cursor (exclusive).* @param limit - Maximum number of events to read. Defaults to the event* store's page-bounded default; pass a higher value when the caller must- * read every event after the cursor (e.g. per-thread catch-up that filters- * a small subset out of a potentially larger global range).+ * read a wider global range. Thread subscriptions use readThreadEvents.* @returns Stream containing ordered events.*/readonly readEvents: (@@ -42,6 +49,16 @@ export interface OrchestrationEngineShape {limit?: number,) => Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError, never>;+ /** Read only this thread's events through a captured authoritative head. */+ readonly readThreadEvents: (+ input: OrchestrationThreadReplayRange & { readonly limit?: number },+ ) => Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError>;++ /** Measure a bounded thread replay without decoding its event bodies. */+ readonly getThreadReplayStats: (+ input: OrchestrationThreadReplayRange & { readonly maxEvents: number },+ ) => Effect.Effect<OrchestrationAggregateReplayStats, OrchestrationEventStoreError>;+/*** Dispatch a validated orchestration command.*diff --git a/apps/server/src/persistence/Layers/OrchestrationEventStore.test.ts b/apps/server/src/persistence/Layers/OrchestrationEventStore.test.tsindex 1e21501e409..e7e6b659008 100644--- a/apps/server/src/persistence/Layers/OrchestrationEventStore.test.ts+++ b/apps/server/src/persistence/Layers/OrchestrationEventStore.test.ts@@ -1,4 +1,11 @@-import { CommandId, EventId, ProjectId } from "@t3tools/contracts";+import {+ CommandId,+ EventId,+ MessageId,+ ProjectId,+ ThreadId,+ type OrchestrationEvent,+} from "@t3tools/contracts";import { assert, it } from "@effect/vitest";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";@@ -12,6 +19,31 @@ import { OrchestrationEventStoreLive } from "./OrchestrationEventStore.ts";import { SqlitePersistenceMemory } from "./Sqlite.ts";const isPersistenceDecodeError = Schema.is(PersistenceDecodeError);+function messageEvent(threadId: ThreadId, id: string): Omit<OrchestrationEvent, "sequence"> {+ const now = "2026-01-01T00:00:00.000Z";+ return {+ type: "thread.message-sent",+ eventId: EventId.make(id),+ aggregateKind: "thread",+ aggregateId: threadId,+ occurredAt: now,+ commandId: null,+ causationEventId: null,+ correlationId: null,+ metadata: {},+ payload: {+ threadId,+ messageId: MessageId.make(id),+ role: "assistant",+ text: id,+ turnId: null,+ streaming: false,+ createdAt: now,+ updatedAt: now,+ },+ };+}+const layer = it.layer(OrchestrationEventStoreLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)),);@@ -79,7 +111,7 @@ layer("OrchestrationEventStore", (it) => {const sql = yield* SqlClient.SqlClient;const now = "2026-01-01T00:00:00.000Z";- yield* sql`+ const invalidRows = yield* sql<{ readonly sequence: number }>`INSERT INTO orchestration_events (event_id,aggregate_kind,@@ -108,6 +140,7 @@ layer("OrchestrationEventStore", (it) => {${"{"},${"{}"})+ RETURNING sequence`;const replayResult = yield* Effect.result(@@ -122,6 +155,154 @@ layer("OrchestrationEventStore", (it) => {),);}+ const scopedResult = yield* eventStore+ .readAggregateRange({+ aggregateKind: "project",+ aggregateId: "project-invalid-json",+ fromSequenceExclusive: 0,+ toSequenceInclusive: invalidRows[0]!.sequence,+ })+ .pipe(Stream.runCollect, Effect.result);+ assert.equal(scopedResult._tag, "Failure");+ if (scopedResult._tag === "Failure") {+ assert.ok(isPersistenceDecodeError(scopedResult.failure));+ assert.ok(+ scopedResult.failure.operation.includes(+ "OrchestrationEventStore.readAggregateRange:decodeRows",+ ),+ );+ }+ }),+ );++ it.effect("reads one aggregate through the captured head across pruned global gaps", () =>+ Effect.gen(function* () {+ const store = yield* OrchestrationEventStore;+ const sql = yield* SqlClient.SqlClient;+ const threadId = ThreadId.make("shared-stream-id");+ const first = yield* store.append(messageEvent(threadId, "scoped-first"));+ const pruned = yield* store.append(+ messageEvent(ThreadId.make("pruned-thread"), "pruned-event"),+ );+ const second = yield* store.append(messageEvent(threadId, "scoped-second"));+ // The same stream ID in a different aggregate is not part of this thread.+ // Its invalid JSON must never reach the event decoder.+ yield* sql`+ INSERT INTO orchestration_events (+ event_id, aggregate_kind, stream_id, stream_version, event_type, occurred_at,+ actor_kind, payload_json, metadata_json+ ) VALUES (+ 'same-id-project', 'project', ${threadId}, 0, 'project.created',+ '2026-01-01T00:00:00.000Z', 'server', '{', '{'+ ), (+ 'unrelated-invalid', 'thread', 'unrelated-invalid-thread', 0, 'thread.activity-appended',+ '2026-01-01T00:00:00.000Z', 'server', '{', '{'+ )+ `;+ const last = yield* store.append(messageEvent(threadId, "scoped-last"));+ yield* sql`DELETE FROM orchestration_events WHERE sequence = ${pruned.sequence}`;+ yield* store.append(messageEvent(threadId, "after-captured-head"));++ const events = yield* store+ .readAggregateRange({+ aggregateKind: "thread",+ aggregateId: threadId,+ fromSequenceExclusive: first.sequence,+ toSequenceInclusive: last.sequence,+ limit: 100,+ })+ .pipe(Stream.runCollect);+ assert.deepEqual(+ events.map((event) => event.sequence),+ [second.sequence, last.sequence],+ );+ }),+ );++ it.effect("bounds thread replay metadata and counts UTF-8 bytes without decoding payloads", () =>+ Effect.gen(function* () {+ const store = yield* OrchestrationEventStore;+ const sql = yield* SqlClient.SqlClient;+ const rows = yield* sql<{ readonly sequence: number }>`+ INSERT INTO orchestration_events (+ event_id, aggregate_kind, stream_id, stream_version, event_type, occurred_at,+ actor_kind, payload_json, metadata_json+ ) VALUES+ ('stats-1', 'thread', 'stats-thread', 0, 'thread.message-sent',+ '2026-01-01T00:00:00.000Z', 'provider', '{"output":"😀"}', '{}'),+ ('stats-unrelated', 'thread', 'another-thread', 0, 'thread.created',+ '2026-01-01T00:00:00.000Z', 'provider', printf('%.*c', 10000, 'x'), '{}'),+ ('stats-2', 'thread', 'stats-thread', 1, 'thread.activity-appended',+ '2026-01-01T00:00:00.000Z', 'provider', '{', '{}'),+ ('stats-other-kind', 'project', 'stats-thread', 0, 'project.deleted',+ '2026-01-01T00:00:00.000Z', 'provider', printf('%.*c', 20000, 'x'), '{}'),+ ('stats-3', 'thread', 'stats-thread', 2, 'thread.deleted',+ '2026-01-01T00:00:00.000Z', 'provider', '{"output":"é"}', '{}'),+ ('stats-4', 'thread', 'stats-thread', 3, 'thread.created',+ '2026-01-01T00:00:00.000Z', 'provider', printf('%.*c', 2000, 'x'), '{}')+ RETURNING sequence+ `;+ const range = {+ aggregateKind: "thread" as const,+ aggregateId: "stats-thread",+ fromSequenceExclusive: 0,+ toSequenceInclusive: rows.at(-1)!.sequence,+ };+ assert.deepEqual(yield* store.getAggregateReplayStats({ ...range, maxEvents: 2 }), {+ eventCount: 3,+ payloadBytes: 33,+ hasCreateEvent: false,+ });+ assert.deepEqual(yield* store.getAggregateReplayStats({ ...range, maxEvents: 10 }), {+ eventCount: 4,+ payloadBytes: 2033,+ hasCreateEvent: true,+ });+ assert.deepEqual(+ yield* store.getAggregateReplayStats({+ ...range,+ toSequenceInclusive: rows[2]!.sequence,+ maxEvents: 10,+ }),+ {+ eventCount: 2,+ payloadBytes: 18,+ hasCreateEvent: false,+ },+ );+ }),+ );++ it.effect("keeps later pages below the captured head when new events are appended", () =>+ Effect.gen(function* () {+ const store = yield* OrchestrationEventStore;+ const threadId = ThreadId.make("paged-thread");+ const persisted = yield* Effect.forEach(+ Array.from({ length: 502 }, (_, index) => index),+ (index) => store.append(messageEvent(threadId, `paged-${index}`)),+ );+ const head = persisted.at(-1)!.sequence;+ let appendedDuringReplay = false;+ const replayed = yield* store+ .readAggregateRange({+ aggregateKind: "thread",+ aggregateId: threadId,+ fromSequenceExclusive: 0,+ toSequenceInclusive: head,+ limit: 1_000,+ })+ .pipe(+ Stream.tap(() => {+ if (appendedDuringReplay) return Effect.void;+ appendedDuringReplay = true;+ return store.append(messageEvent(threadId, "appended-during-replay"));+ }),+ Stream.runCollect,+ );+ assert.deepEqual(+ replayed.map((event) => event.sequence),+ persisted.map((event) => event.sequence),+ );}),);});diff --git a/apps/server/src/persistence/Layers/OrchestrationEventStore.ts b/apps/server/src/persistence/Layers/OrchestrationEventStore.tsindex e801c34af58..1f97f514e43 100644--- a/apps/server/src/persistence/Layers/OrchestrationEventStore.ts+++ b/apps/server/src/persistence/Layers/OrchestrationEventStore.ts@@ -72,6 +72,18 @@ const ReadFromSequenceRequestSchema = Schema.Struct({sequenceExclusive: NonNegativeInt,limit: Schema.Number,});+const AggregateReplayRequestSchema = Schema.Struct({+ aggregateKind: OrchestrationAggregateKind,+ aggregateId: Schema.String,+ fromSequenceExclusive: NonNegativeInt,+ toSequenceInclusive: NonNegativeInt,+ limit: Schema.Number,+});+const AggregateReplayStatsRowSchema = Schema.Struct({+ eventCount: Schema.Number,+ payloadBytes: Schema.Number,+ hasCreateEvent: Schema.Number,+});const DEFAULT_READ_FROM_SEQUENCE_LIMIT = 1_000;const READ_PAGE_SIZE = 500;@@ -189,6 +201,57 @@ const makeEventStore = Effect.gen(function* () {`,});+ const readAggregateEventRows = SqlSchema.findAll({+ Request: AggregateReplayRequestSchema,+ Result: OrchestrationEventPersistedRowSchema,+ execute: (request) =>+ sql`+ SELECT+ sequence,+ event_id AS "eventId",+ event_type AS "type",+ aggregate_kind AS "aggregateKind",+ stream_id AS "aggregateId",+ occurred_at AS "occurredAt",+ command_id AS "commandId",+ causation_event_id AS "causationEventId",+ correlation_id AS "correlationId",+ payload_json AS "payload",+ metadata_json AS "metadata"+ FROM orchestration_events+ WHERE aggregate_kind = ${request.aggregateKind}+ AND stream_id = ${request.aggregateId}+ AND sequence > ${request.fromSequenceExclusive}+ AND sequence <= ${request.toSequenceInclusive}+ ORDER BY sequence ASC+ LIMIT ${request.limit}+ `,+ });++ const readAggregateReplayStats = SqlSchema.findOne({+ Request: AggregateReplayRequestSchema,+ Result: AggregateReplayStatsRowSchema,+ execute: (request) =>+ sql`+ SELECT+ COUNT(*) AS "eventCount",+ COALESCE(SUM(octet_length(payload_json)), 0) AS "payloadBytes",+ COALESCE(MAX(event_type IN (+ 'thread.created', 'project.created'+ )), 0) AS "hasCreateEvent"+ FROM (+ SELECT payload_json, event_type+ FROM orchestration_events+ WHERE aggregate_kind = ${request.aggregateKind}+ AND stream_id = ${request.aggregateId}+ AND sequence > ${request.fromSequenceExclusive}+ AND sequence <= ${request.toSequenceInclusive}+ ORDER BY sequence ASC+ LIMIT ${request.limit}+ )+ `,+ });+const append: OrchestrationEventStoreShape["append"] = (event) =>appendEventRow({eventId: event.eventId,@@ -295,9 +358,78 @@ const makeEventStore = Effect.gen(function* () {),);+ const readAggregateRange: OrchestrationEventStoreShape["readAggregateRange"] = (input) => {+ const limit = Math.max(0, Math.floor(input.limit ?? DEFAULT_READ_FROM_SEQUENCE_LIMIT));+ if (limit === 0 || input.fromSequenceExclusive >= input.toSequenceInclusive) {+ return Stream.empty;+ }+ const readPage = (+ cursor: number,+ remaining: number,+ ): Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError> =>+ Stream.fromEffect(+ readAggregateEventRows({+ ...input,+ fromSequenceExclusive: cursor,+ limit: Math.min(remaining, READ_PAGE_SIZE),+ }).pipe(+ Effect.mapError(+ toPersistenceSqlOrDecodeError(+ "OrchestrationEventStore.readAggregateRange:query",+ "OrchestrationEventStore.readAggregateRange:decodeRows",+ ),+ ),+ Effect.flatMap((rows) =>+ Effect.forEach(rows, (row) =>+ decodeEvent(row).pipe(+ Effect.mapError(+ toPersistenceDecodeError("OrchestrationEventStore.readAggregateRange:rowToEvent"),+ ),+ ),+ ),+ ),+ ),+ ).pipe(+ Stream.flatMap((events) => {+ const last = events.at(-1);+ if (last === undefined) {+ return Stream.empty;+ }+ const nextRemaining = remaining - events.length;+ if (+ events.length < READ_PAGE_SIZE ||+ nextRemaining === 0 ||+ last.sequence >= input.toSequenceInclusive+ ) {+ return Stream.fromIterable(events);+ }+ return Stream.concat(Stream.fromIterable(events), readPage(last.sequence, nextRemaining));+ }),+ );+ return readPage(input.fromSequenceExclusive, limit);+ };++ const getAggregateReplayStats: OrchestrationEventStoreShape["getAggregateReplayStats"] = (+ input,+ ) =>+ readAggregateReplayStats({+ ...input,+ limit: Math.max(0, Math.floor(input.maxEvents)) + 1,+ }).pipe(+ Effect.mapError(+ toPersistenceSqlOrDecodeError(+ "OrchestrationEventStore.getAggregateReplayStats:query",+ "OrchestrationEventStore.getAggregateReplayStats:decodeRow",+ ),+ ),+ Effect.map((row) => ({ ...row, hasCreateEvent: row.hasCreateEvent !== 0 })),+ );+return {append,readFromSequence,+ readAggregateRange,+ getAggregateReplayStats,readAll: () => readFromSequence(0, Number.MAX_SAFE_INTEGER),hasEventAfter,} satisfies OrchestrationEventStoreShape;diff --git a/apps/server/src/persistence/Services/OrchestrationEventStore.ts b/apps/server/src/persistence/Services/OrchestrationEventStore.tsindex b865957c06b..3e131b068b0 100644--- a/apps/server/src/persistence/Services/OrchestrationEventStore.ts+++ b/apps/server/src/persistence/Services/OrchestrationEventStore.ts@@ -16,6 +16,20 @@ import type * as Stream from "effect/Stream";import type { OrchestrationEventStoreError } from "../Errors.ts";+export interface OrchestrationAggregateReplayRange {+ readonly aggregateKind: OrchestrationEvent["aggregateKind"];+ readonly aggregateId: string;+ readonly fromSequenceExclusive: number;+ readonly toSequenceInclusive: number;+}++export interface OrchestrationAggregateReplayStats {+ readonly eventCount: number;+ readonly payloadBytes: number;+ /** A creation in this range does not prove that the aggregate still exists. */+ readonly hasCreateEvent: boolean;+}+/*** OrchestrationEventStoreShape - Service API for orchestration event persistence.*/@@ -46,6 +60,19 @@ export interface OrchestrationEventStoreShape {limit?: number,) => Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError>;+ /** Read one aggregate through a captured global head, without decoding other streams. */+ readonly readAggregateRange: (+ input: OrchestrationAggregateReplayRange & { readonly limit?: number },+ ) => Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError>;++ /**+ * Measure at most maxEvents + 1 rows without decoding payloads. The extra+ * row tells the caller to use a snapshot instead of a truncated replay.+ */+ readonly getAggregateReplayStats: (+ input: OrchestrationAggregateReplayRange & { readonly maxEvents: number },+ ) => Effect.Effect<OrchestrationAggregateReplayStats, OrchestrationEventStoreError>;+/*** Read all events from the beginning of the stream.*diff --git a/apps/server/src/relay/AgentAwarenessRelay.test.ts b/apps/server/src/relay/AgentAwarenessRelay.test.tsindex b38861c9877..5c79a543fb4 100644--- a/apps/server/src/relay/AgentAwarenessRelay.test.ts+++ b/apps/server/src/relay/AgentAwarenessRelay.test.ts@@ -459,6 +459,8 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {const orchestrationEngine = {readEvents: () => Stream.empty,+ readThreadEvents: () => Stream.empty,+ getThreadReplayStats: () => Effect.die("unused thread replay stats"),dispatch: () => Effect.succeed({ sequence: 1 }),streamDomainEvents: Stream.fromQueue(events),subscribeDomainEvents: Effect.succeed(Stream.fromQueue(events)),@@ -653,6 +655,8 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {}),Layer.succeed(OrchestrationEngineService, {readEvents: () => Stream.empty,+ readThreadEvents: () => Stream.empty,+ getThreadReplayStats: () => Effect.die("unused thread replay stats"),dispatch: () => Effect.succeed({ sequence: 1 }),streamDomainEvents: Stream.fromQueue(events),subscribeDomainEvents: Effect.succeed(Stream.fromQueue(events)),diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.tsindex ce11f516b65..c98bc07fcd2 100644--- a/apps/server/src/server.test.ts+++ b/apps/server/src/server.test.ts@@ -115,6 +115,8 @@ import {import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";import { ThreadDeletionReactor } from "./orchestration/Services/ThreadDeletionReactor.ts";import { SqlitePersistenceMemory } from "./persistence/Layers/Sqlite.ts";+import { OrchestrationEventStoreLive } from "./persistence/Layers/OrchestrationEventStore.ts";+import { OrchestrationEventStore } from "./persistence/Services/OrchestrationEventStore.ts";import { PersistenceSqlError } from "./persistence/Errors.ts";import * as ProviderRegistry from "./provider/Services/ProviderRegistry.ts";import * as ProviderService from "./provider/Services/ProviderService.ts";@@ -918,6 +920,13 @@ const buildAppUnderTest = (options?: {Layer.mergeAll(Layer.mock(OrchestrationEngine.OrchestrationEngineService)({readEvents: () => Stream.empty,+ readThreadEvents: () => Stream.empty,+ getThreadReplayStats: () =>+ Effect.succeed({+ eventCount: 0,+ payloadBytes: 0,+ hasCreateEvent: false,+ }),dispatch: () => Effect.succeed({ sequence: 0 }),streamDomainEvents: Stream.empty,latestSequence: Effect.succeed(0),@@ -8047,50 +8056,57 @@ it.layer(NodeServices.layer)("server router seam", (it) => {}).pipe(Effect.provide(NodeHttpServer.layerTest), TestClock.withLive),);- it.effect("subscribeThread sends a fresh snapshot instead of replaying a large gap", () =>- Effect.gen(function* () {- let readEventsCalls = 0;- const thread = makeDefaultOrchestrationReadModel().threads[0]!;+ it.effect(+ "subscribeThread sends a fresh snapshot when its event count exceeds the replay limit",+ () =>+ Effect.gen(function* () {+ let readEventsCalls = 0;+ const thread = makeDefaultOrchestrationReadModel().threads[0]!;- yield* buildAppUnderTest({- layers: {- orchestrationEngine: {- // Head is far ahead of the client's afterSequence (gap > 1000).- latestSequence: Effect.succeed(100_000),- readEvents: () =>- Stream.sync(() => {- readEventsCalls += 1;- return {} as OrchestrationEvent;- }),- },- projectionSnapshotQuery: {- getThreadDetailSnapshot: () =>- Effect.succeed(Option.some({ snapshotSequence: 100_000, thread })),+ yield* buildAppUnderTest({+ layers: {+ orchestrationEngine: {+ latestSequence: Effect.succeed(100_000),+ getThreadReplayStats: () =>+ Effect.succeed({+ eventCount: 1_001,+ payloadBytes: 1_000,+ hasCreateEvent: false,+ }),+ readThreadEvents: () =>+ Stream.sync(() => {+ readEventsCalls += 1;+ return {} as OrchestrationEvent;+ }),+ },+ projectionSnapshotQuery: {+ getThreadDetailSnapshot: () =>+ Effect.succeed(Option.some({ snapshotSequence: 100_000, thread })),+ },},- },- });+ });- const wsUrl = yield* getWsServerUrl("/ws");- const items = yield* Effect.scoped(- withWsRpcClient(wsUrl, (client) =>- client[ORCHESTRATION_WS_METHODS.subscribeThread]({- threadId: defaultThreadId,- afterSequence: 5,- requestCompletionMarker: true,- }).pipe(Stream.take(2), Stream.runCollect),- ),- );+ const wsUrl = yield* getWsServerUrl("/ws");+ const items = yield* Effect.scoped(+ withWsRpcClient(wsUrl, (client) =>+ client[ORCHESTRATION_WS_METHODS.subscribeThread]({+ threadId: defaultThreadId,+ afterSequence: 5,+ requestCompletionMarker: true,+ }).pipe(Stream.take(2), Stream.runCollect),+ ),+ );- const [first, second] = Array.from(items);- // Large gap => fresh thread snapshot, and the global replay never starts.- assert.equal(first?.kind, "snapshot");- if (first?.kind === "snapshot") {- assert.equal(first.snapshot.thread.id, defaultThreadId);- assert.equal(first.snapshot.snapshotSequence, 100_000);- }- assert.equal(second?.kind, "synchronized");- assert.equal(readEventsCalls, 0);- }).pipe(Effect.provide(NodeHttpServer.layerTest)),+ const [first, second] = Array.from(items);+ // Never truncate a thread's replay at the event limit.+ assert.equal(first?.kind, "snapshot");+ if (first?.kind === "snapshot") {+ assert.equal(first.snapshot.thread.id, defaultThreadId);+ assert.equal(first.snapshot.snapshotSequence, 100_000);+ }+ assert.equal(second?.kind, "synchronized");+ assert.equal(readEventsCalls, 0);+ }).pipe(Effect.provide(NodeHttpServer.layerTest)),);it.effect(@@ -8104,7 +8120,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {const releaseAck = yield* Deferred.make<void>();const firstApplied = yield* Deferred.make<void>();const replayStarted = yield* Deferred.make<void>();- const replayCalls: Array<{ afterSequence: number; limit: number | undefined }> = [];+ const replayCalls: Array<{ afterSequence: number; headSequence: number }> = [];let headSequence = 0;let snapshotCalls = 0;const message = (sequence: number, text: string) =>@@ -8148,24 +8164,21 @@ it.layer(NodeServices.layer)("server router seam", (it) => {return Stream.fromSubscription(subscription);}),).pipe(Stream.ensuring(Deferred.succeed(detached, undefined))),- readEvents: (afterSequence, limit) => {- replayCalls.push({ afterSequence, limit });+ readThreadEvents: ({ fromSequenceExclusive, toSequenceInclusive }) => {+ replayCalls.push({+ afterSequence: fromSequenceExclusive,+ headSequence: toSequenceInclusive,+ });const range = events.filter(- (event) => event.sequence > afterSequence && event.sequence <= headSequence,+ (event) =>+ event.sequence > fromSequenceExclusive && event.sequence <= toSequenceInclusive,);return Stream.concat(Stream.fromEffect(Deferred.succeed(replayStarted, undefined)).pipe(Stream.drain),Stream.fromIterable(range),);},- },- projectionSnapshotQuery: {- getThreadDetailSnapshot: () =>- Effect.sync(() => {- snapshotCalls += 1;- return Option.none();- }),- getEventReplayStats: ({ fromSequenceExclusive, toSequenceInclusive }) => {+ getThreadReplayStats: ({ fromSequenceExclusive, toSequenceInclusive }) => {const range = events.filter((event) =>event.sequence > fromSequenceExclusive && event.sequence <= toSequenceInclusive,@@ -8176,9 +8189,17 @@ it.layer(NodeServices.layer)("server router seam", (it) => {(bytes, event) => bytes + Buffer.byteLength(jsonRequestBody(event.payload)),0,),+ hasCreateEvent: false,});},},+ projectionSnapshotQuery: {+ getThreadDetailSnapshot: () =>+ Effect.sync(() => {+ snapshotCalls += 1;+ return Option.none();+ }),+ },},});@@ -8242,8 +8263,8 @@ it.layer(NodeServices.layer)("server router seam", (it) => {);assert.equal(completed.event.payload.activity.kind, "tool.completed");assert.deepEqual(replayCalls, [- { afterSequence: 0, limit: 0 },- { afterSequence: 1, limit: 3 },+ { afterSequence: 0, headSequence: 0 },+ { afterSequence: 1, headSequence: 4 },]);assert.equal(snapshotCalls, 0);}),@@ -8369,7 +8390,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => {layers: {orchestrationEngine: {latestSequence: Effect.succeed(5),- readEvents: () =>+ getThreadReplayStats: () =>+ Effect.die("An invalid cursor must not start a replay query"),+ readThreadEvents: () =>Stream.sync(() => {readEventsCalls += 1;return {} as OrchestrationEvent;@@ -8397,9 +8420,225 @@ it.layer(NodeServices.layer)("server router seam", (it) => {}).pipe(Effect.provide(NodeHttpServer.layerTest)),);+ it.effect("subscribeThread replays a small thread range across a large global gap", () =>+ Effect.gen(function* () {+ const event = makeLiveToolActivityEvent(99_999, "tool.completed");+ yield* buildAppUnderTest({+ layers: {+ orchestrationEngine: {+ latestSequence: Effect.succeed(100_000),+ getThreadReplayStats: () =>+ Effect.succeed({+ eventCount: 1,+ payloadBytes: Buffer.byteLength(jsonRequestBody(event.payload)),+ hasCreateEvent: false,+ }),+ readThreadEvents: () => Stream.make(event),+ readEvents: () => Stream.die("Thread replay must not read the global log"),+ },+ projectionSnapshotQuery: {+ getEventReplayStats: () => Effect.die("Thread replay must not measure the global log"),+ getThreadDetailSnapshot: () =>+ Effect.die("Unrelated activity must not force a snapshot"),+ },+ },+ });+ const wsUrl = yield* getWsServerUrl("/ws");+ const items = yield* Effect.scoped(+ withWsRpcClient(wsUrl, (client) =>+ client[ORCHESTRATION_WS_METHODS.subscribeThread]({+ threadId: defaultThreadId,+ afterSequence: 5,+ requestCompletionMarker: true,+ }).pipe(+ Stream.takeUntil((item) => item.kind === "synchronized"),+ Stream.runCollect,+ ),+ ),+ );+ assert.deepEqual(+ items.map((item) => (item.kind === "event" ? item.event.sequence : item.kind)),+ [99_999, "synchronized"],+ );+ const first = items[0];+ assertTrue(first?.kind === "event" && first.event.type === "thread.activity-appended");+ assert.equal(first.event.payload.activity.kind, "tool.completed");+ }).pipe(Effect.provide(NodeHttpServer.layerTest)),+ );++ it.effect("subscribeThread resets cached history when its ID is created again", () =>+ Effect.gen(function* () {+ const thread = {+ ...makeDefaultOrchestrationReadModel().threads[0]!,+ title: "Recreated thread",+ };+ let requestedTurnLimit: number | undefined;+ yield* buildAppUnderTest({+ layers: {+ orchestrationEngine: {+ latestSequence: Effect.succeed(5),+ getThreadReplayStats: () =>+ Effect.succeed({+ eventCount: 3,+ payloadBytes: 1_000,+ hasCreateEvent: true,+ }),+ readThreadEvents: () => Stream.die("A recreated thread must not reuse cached history"),+ },+ projectionSnapshotQuery: {+ getThreadDetailSnapshot: (_threadId, options) => {+ requestedTurnLimit = options?.turnLimit;+ return Effect.succeed(Option.some({ snapshotSequence: 5, thread }));+ },+ },+ },+ });+ const wsUrl = yield* getWsServerUrl("/ws");+ const items = yield* Effect.scoped(+ withWsRpcClient(wsUrl, (client) =>+ client[ORCHESTRATION_WS_METHODS.subscribeThread]({+ threadId: defaultThreadId,+ afterSequence: 2,+ turnLimit: 1,+ requestCompletionMarker: true,+ }).pipe(+ Stream.takeUntil((item) => item.kind === "synchronized"),+ Stream.runCollect,+ ),+ ),+ );+ const first = items[0];+ assertTrue(first?.kind === "snapshot");+ assert.equal(first.snapshot.thread.title, "Recreated thread");+ assert.equal(first.snapshot.snapshotSequence, 5);+ assert.equal(requestedTurnLimit, 1);+ assert.deepEqual(items[1], { kind: "synchronized" });+ }).pipe(Effect.provide(NodeHttpServer.layerTest)),+ );++ for (const { createBeforeDelete, oversized } of [+ { createBeforeDelete: false, oversized: false },+ { createBeforeDelete: true, oversized: false },+ { createBeforeDelete: true, oversized: true },+ ]) {+ it.effect(+ oversized+ ? "keeps the missing-snapshot error when an absent thread exceeds the replay limit"+ : `synchronizes an absent thread and removes its shell after ${createBeforeDelete ? "creation and deletion" : "deletion"}`,+ () =>+ Effect.gen(function* () {+ const store = yield* OrchestrationEventStore;+ const base = makeLiveToolActivityEvent(0, "tool.completed");+ if (createBeforeDelete) {+ const thread = makeDefaultOrchestrationReadModel().threads[0]!;+ yield* store.append({+ ...base,+ eventId: EventId.make(`create-before-final-delete-${oversized}`),+ type: "thread.created",+ payload: {+ threadId: defaultThreadId,+ projectId: thread.projectId,+ title: thread.title,+ modelSelection: thread.modelSelection,+ runtimeMode: thread.runtimeMode,+ interactionMode: thread.interactionMode,+ branch: thread.branch,+ worktreePath: thread.worktreePath,+ createdAt: thread.createdAt,+ updatedAt: thread.updatedAt,+ },+ });+ }+ if (oversized) {+ yield* Effect.forEach(+ Array.from({ length: 1_000 }, (_, index) => index + 1),+ (sequence) => store.append(makeLiveToolActivityEvent(sequence, "tool.completed")),+ { discard: true },+ );+ }+ const deleted = yield* store.append({+ ...base,+ eventId: EventId.make(`deleted-replay-${createBeforeDelete}-${oversized}`),+ type: "thread.deleted",+ payload: { threadId: defaultThreadId, deletedAt: base.occurredAt },+ });+ yield* buildAppUnderTest({+ layers: {+ orchestrationEngine: {+ latestSequence: Effect.succeed(deleted.sequence),+ getThreadReplayStats: ({ threadId, ...range }) =>+ store.getAggregateReplayStats({+ ...range,+ aggregateKind: "thread",+ aggregateId: threadId,+ }),+ readThreadEvents: ({ threadId, ...range }) =>+ store.readAggregateRange({+ ...range,+ aggregateKind: "thread",+ aggregateId: threadId,+ }),+ readEvents: store.readFromSequence,+ },+ projectionSnapshotQuery: {+ getThreadDetailSnapshot: () => Effect.succeed(Option.none()),+ },+ },+ });+ const wsUrl = yield* getWsServerUrl("/ws");+ yield* Effect.scoped(+ withWsRpcClient(wsUrl, (client) =>+ Effect.gen(function* () {+ const threadResult = yield* client[ORCHESTRATION_WS_METHODS.subscribeThread]({+ threadId: defaultThreadId,+ afterSequence: 0,+ requestCompletionMarker: true,+ }).pipe(+ Stream.takeUntil((item) => item.kind === "synchronized"),+ Stream.runCollect,+ Effect.result,+ );+ if (oversized) {+ assertTrue(threadResult._tag === "Failure");+ assert.equal(threadResult.failure._tag, "OrchestrationGetSnapshotError");+ assert.equal(+ threadResult.failure.message,+ `Thread ${defaultThreadId} was not found`,+ );+ return;+ }+ assertTrue(threadResult._tag === "Success");+ assert.deepEqual(threadResult.success, [{ kind: "synchronized" }]);+ const shellItems = yield* client[ORCHESTRATION_WS_METHODS.subscribeShell]({+ afterSequence: 0,+ requestCompletionMarker: true,+ }).pipe(+ Stream.takeUntil((item) => item.kind === "synchronized"),+ Stream.runCollect,+ );+ assert.deepEqual(shellItems, [+ { kind: "thread-removed", sequence: deleted.sequence, threadId: defaultThreadId },+ { kind: "synchronized" },+ ]);+ }),+ ),+ );+ }).pipe(+ Effect.provide(+ Layer.mergeAll(+ OrchestrationEventStoreLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)),+ NodeHttpServer.layerTest,+ ),+ ),+ ),+ );+ }+it.effect("subscribeThread bounds catch-up replay to the captured head", () =>Effect.gen(function* () {- let replayLimit: number | undefined;+ let replayHead: number | undefined;+ let headSequence = 50;+ const liveEvents = yield* PubSub.unbounded<OrchestrationEvent>();const now = "2026-01-01T00:00:00.000Z";const messageEvent = {sequence: 3,@@ -8427,10 +8666,26 @@ it.layer(NodeServices.layer)("server router seam", (it) => {yield* buildAppUnderTest({layers: {orchestrationEngine: {- latestSequence: Effect.succeed(50),- readEvents: (_afterSequence, limit) => {- replayLimit = limit;- return Stream.make(messageEvent);+ latestSequence: Effect.sync(() => headSequence),+ streamDomainEvents: Stream.fromPubSub(liveEvents),+ getThreadReplayStats: () =>+ Effect.sync(() => {+ headSequence = 100;+ return { eventCount: 1, payloadBytes: 100, hasCreateEvent: false };+ }),+ readThreadEvents: ({ toSequenceInclusive }) => {+ replayHead = toSequenceInclusive;+ return Stream.fromEffect(+ PubSub.publish(liveEvents, {+ ...messageEvent,+ sequence: 51,+ eventId: EventId.make("event-live-after-head"),+ payload: {+ ...messageEvent.payload,+ messageId: MessageId.make("message-live-after-head"),+ },+ }),+ ).pipe(Stream.flatMap(() => Stream.make(messageEvent)));},},},@@ -8443,17 +8698,18 @@ it.layer(NodeServices.layer)("server router seam", (it) => {threadId: defaultThreadId,afterSequence: 0,requestCompletionMarker: true,- }).pipe(Stream.take(2), Stream.runCollect),+ }).pipe(+ Stream.takeUntil((item) => item.kind === "synchronized"),+ Stream.runCollect,+ ),),);- const [first, second] = Array.from(items);- assert.equal(first?.kind, "event");- assert.equal(first?.kind === "event" ? first.event.sequence : null, 3);- assert.equal(second?.kind, "synchronized");- // The replay is bounded to the head captured before the read, not- // Number.MAX_SAFE_INTEGER.- assert.equal(replayLimit, 50);+ assert.deepEqual(+ items.map((item) => (item.kind === "event" ? item.event.sequence : item.kind)),+ [3, 51, "synchronized"],+ );+ assert.equal(replayHead, 50);}).pipe(Effect.provide(NodeHttpServer.layerTest)),);@@ -8530,6 +8786,19 @@ it.layer(NodeServices.layer)("server router seam", (it) => {layers: {orchestrationEngine: {latestSequence: Effect.succeed(5),+ getThreadReplayStats: () =>+ Effect.sync(() => {+ replayStatsCalls += 1;+ return {+ eventCount: 5,+ payloadBytes: 8 * 1024 * 1024 + 1,+ hasCreateEvent: false,+ };+ }),+ readThreadEvents: () => {+ readEventsCalls += 1;+ return Stream.empty;+ },readEvents: () =>Stream.sync(() => {readEventsCalls += 1;diff --git a/apps/server/src/serverRuntimeStartup.reconcile.test.ts b/apps/server/src/serverRuntimeStartup.reconcile.test.tsindex 9374560c4e9..39c284330d4 100644--- a/apps/server/src/serverRuntimeStartup.reconcile.test.ts+++ b/apps/server/src/serverRuntimeStartup.reconcile.test.ts@@ -90,6 +90,8 @@ const runReconciliation = (input: {Effect.provideService(ProviderSessionDirectory.ProviderSessionDirectory, input.directory),Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {readEvents: () => Stream.empty,+ readThreadEvents: () => Stream.empty,+ getThreadReplayStats: () => Effect.die("unused thread replay stats"),dispatch: input.dispatch,streamDomainEvents: Stream.empty,subscribeDomainEvents: Effect.succeed(Stream.empty),@@ -653,6 +655,8 @@ it.effect("does not fail startup when the live provider session inventory cannot}),Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {readEvents: () => Stream.empty,+ readThreadEvents: () => Stream.empty,+ getThreadReplayStats: () => Effect.die("unused thread replay stats"),dispatch: () => Effect.die("unused"),streamDomainEvents: Stream.empty,subscribeDomainEvents: Effect.succeed(Stream.empty),diff --git a/apps/server/src/serverRuntimeStartup.test.ts b/apps/server/src/serverRuntimeStartup.test.tsindex a2b57c0fde2..b53e1843c22 100644--- a/apps/server/src/serverRuntimeStartup.test.ts+++ b/apps/server/src/serverRuntimeStartup.test.ts@@ -220,6 +220,8 @@ it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and threa}),Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {readEvents: () => Stream.empty,+ readThreadEvents: () => Stream.empty,+ getThreadReplayStats: () => Effect.die("unused thread replay stats"),dispatch: (command) =>Ref.update(dispatchCalls, (calls) => [...calls, command.type]).pipe(Effect.as({ sequence: 1 }),@@ -275,6 +277,8 @@ it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread when}),Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {readEvents: () => Stream.empty,+ readThreadEvents: () => Stream.empty,+ getThreadReplayStats: () => Effect.die("unused thread replay stats"),dispatch: (command) =>Ref.update(dispatchCalls, (calls) => [...calls, command]).pipe(Effect.as({ sequence: 1 }),@@ -339,6 +343,8 @@ it.effect("resolveAutoBootstrapWelcomeTargets preserves typed UUID generation fa}),Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {readEvents: () => Stream.empty,+ readThreadEvents: () => Stream.empty,+ getThreadReplayStats: () => Effect.die("unused thread replay stats"),dispatch: (command) =>Ref.update(dispatchCalls, (calls) => [...calls, command.type]).pipe(Effect.as({ sequence: 1 }),diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.tsindex 3beb4daf7ff..e1aff4a678c 100644--- a/apps/server/src/ws.ts+++ b/apps/server/src/ws.ts@@ -333,12 +333,9 @@ const PROVIDER_STATUS_DEBOUNCE_MS = 200;// Matches the event store's default page size (DEFAULT_READ_FROM_SEQUENCE_LIMIT).const SHELL_RESUME_MAX_GAP = 1_000;-// Same bound for thread resume. The replay reads the *global* event range and-// filters per-thread afterwards, so a stale cursor far behind the head would-// otherwise decode every intervening event's payload — reconnects with cursors-// hundreds of thousands of events behind have OOM-killed servers on large-// databases. Past this gap the client is reset with a fresh thread snapshot.-const THREAD_RESUME_MAX_GAP = 1_000;+// Thread replay counts only this thread's rows. Busy or pruned unrelated+// streams must not force a full thread snapshot.+const THREAD_RESUME_MAX_EVENTS = 1_000;// Row count alone does not bound replay memory: a few events with large tool// payloads can decode to gigabytes. Before replaying, sum the serialized// payload bytes of the range in SQL and reset with a snapshot past this budget.@@ -1594,6 +1591,7 @@ const makeWsRpcLayer = ({ startImmediately: true },);const bufferedLiveStream = liveBuffer.stream;+ let replayOnMissingSnapshot: typeof bufferedLiveStream | undefined;// When the client already loaded the snapshot over HTTP it passes// that snapshot's sequence, and we resume the live subscription by@@ -1608,24 +1606,41 @@ const makeWsRpcLayer = (// catch-up followed by the buffered/ongoing live events. Overlapping// events are deduped by sequence on the client.//- // The replay is bounded to the projection head captured below. The- // catch-up range is normally tiny (a fresh HTTP snapshot sequence),- // but a stale cached cursor can sit hundreds of thousands of global- // events behind — replaying that decodes every intervening event- // (including every other thread's tool payloads) only to discard- // almost all of them, which has OOM-killed servers on large- // databases. A truncated replay would silently drop this thread's- // events, so past the gap cap we reset the client with a fresh- // thread snapshot instead, exactly like subscribeShell above.+ // Measure only this thread's rows. Global sequence gaps can+ // contain unrelated or pruned streams. Keep an explicit upper+ // bound so events after the captured head stay in the live tail.if (input.afterSequence !== undefined) {const afterSequence = input.afterSequence;const headSequence = yield* orchestrationEngine.latestSequence;- const replayGap = headSequence - afterSequence;+ const range = {+ threadId: input.threadId,+ fromSequenceExclusive: afterSequence,+ toSequenceInclusive: headSequence,+ };+ const replayStats =+ afterSequence > headSequence+ ? null+ : yield* orchestrationEngine+ .getThreadReplayStats({+ ...range,+ maxEvents: THREAD_RESUME_MAX_EVENTS,+ })+ .pipe(+ Effect.mapError(+ (cause) =>+ new OrchestrationGetSnapshotError({+ message: `Failed to measure thread ${input.threadId} replay range`,+ cause,+ }),+ ),+ );if (- yield* canReplayPersistedRange(afterSequence, headSequence, THREAD_RESUME_MAX_GAP)+ replayStats !== null &&+ replayStats.eventCount <= THREAD_RESUME_MAX_EVENTS &&+ replayStats.payloadBytes <= ORCHESTRATION_REPLAY_PAYLOAD_BUDGET_BYTES) {const catchUpStream = orchestrationEngine- .readEvents(afterSequence, replayGap)+ .readThreadEvents({ ...range, limit: THREAD_RESUME_MAX_EVENTS }).pipe(Stream.filter(isThisThreadDetailEvent),Stream.map((event) => ({@@ -1648,11 +1663,14 @@ const makeWsRpcLayer = (.pipe(Effect.as(bufferedLiveStream)),): bufferedLiveStream;- return Stream.concat(catchUpStream, afterCatchUp);+ const replay = Stream.concat(catchUpStream, afterCatchUp);+ if (!replayStats.hasCreateEvent) {+ return replay;+ }+ replayOnMissingSnapshot = replay;}- // Gap too large (or cursor ahead of authoritative state): fall- // through to the snapshot path so the client converges from a- // fresh thread detail instead of an unbounded replay.+ // A recreated thread needs a fresh snapshot if it still exists.+ // Oversized replays and invalid cursors also use the snapshot path.}const snapshot = yield* projectionSnapshotQuery@@ -1675,6 +1693,12 @@ const makeWsRpcLayer = ();if (Option.isNone(snapshot)) {+ // The recreated thread can already be deleted. Preserve the+ // bounded replay and shell removal instead of retrying a+ // snapshot that cannot exist. Oversized ranges still fail.+ if (replayOnMissingSnapshot !== undefined) {+ return replayOnMissingSnapshot;+ }return yield* new OrchestrationGetSnapshotError({message: `Thread ${input.threadId} was not found`,cause: input.threadId,