TypeScript
fix(server): bound orchestration replay payloads (#8992)
Ross Cawston7e460f429b74
diff --git a/apps/server/src/checkpointing/CheckpointDiffQuery.test.ts b/apps/server/src/checkpointing/CheckpointDiffQuery.test.tsindex fe093c451e2..55b6dd97349 100644--- a/apps/server/src/checkpointing/CheckpointDiffQuery.test.ts+++ b/apps/server/src/checkpointing/CheckpointDiffQuery.test.ts@@ -85,6 +85,7 @@ describe("CheckpointDiffQuery.layer", () => {Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),+ getEventReplayStats: () => Effect.die("unused"),getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),getProjectShellById: () => Effect.succeed(Option.none()),getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),@@ -194,6 +195,7 @@ describe("CheckpointDiffQuery.layer", () => {Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),+ getEventReplayStats: () => Effect.die("unused"),getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),getProjectShellById: () => Effect.succeed(Option.none()),getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),@@ -278,6 +280,7 @@ describe("CheckpointDiffQuery.layer", () => {Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),+ getEventReplayStats: () => Effect.die("unused"),getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),getProjectShellById: () => Effect.succeed(Option.none()),getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),@@ -347,6 +350,7 @@ describe("CheckpointDiffQuery.layer", () => {Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),+ getEventReplayStats: () => Effect.die("unused"),getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),getProjectShellById: () => Effect.succeed(Option.none()),getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),@@ -401,6 +405,7 @@ describe("CheckpointDiffQuery.layer", () => {Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),+ getEventReplayStats: () => Effect.die("unused"),getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),getProjectShellById: () => Effect.succeed(Option.none()),getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),diff --git a/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts b/apps/server/src/orchestration/Layers/OrchestrationEngine.test.tsindex 3952cf34bdd..b0aa2c57d81 100644--- a/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts+++ b/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts@@ -206,6 +206,7 @@ describe("OrchestrationEngine", () => {getSnapshotSequence: () =>Effect.succeed({ snapshotSequence: projectionSnapshot.snapshotSequence }),getCounts: () => Effect.succeed({ projectCount: 1, threadCount: 1 }),+ getEventReplayStats: () => Effect.die("unused"),getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),getProjectShellById: () => Effect.succeed(Option.none()),getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.tsindex fd8b601b13e..e4f1d9d1b95 100644--- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts+++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts@@ -922,6 +922,52 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {}),);+ it.effect("measures replay payload bytes without decoding event bodies", () =>+ Effect.gen(function* () {+ const snapshotQuery = yield* ProjectionSnapshotQuery;+ const sql = yield* SqlClient.SqlClient;++ yield* sql`DELETE FROM orchestration_events`;+ yield* sql`+ INSERT INTO orchestration_events (+ event_id, aggregate_kind, stream_id, stream_version, event_type, occurred_at,+ command_id, causation_event_id, correlation_id, actor_kind, payload_json, metadata_json+ )+ VALUES+ (+ 'replay-event-1', 'thread', 'thread-replay', 1, 'thread.activity-appended',+ '2026-03-01T00:00:00.000Z', NULL, NULL, NULL, 'provider',+ json_object('output', printf('%.*c', 1000, 'x')), '{}'+ ),+ (+ 'replay-event-2', 'thread', 'thread-replay', 2, 'thread.activity-appended',+ '2026-03-01T00:00:01.000Z', NULL, NULL, NULL, 'provider',+ json_object('output', printf('%.*c', 2000, 'x')), '{}'+ ),+ (+ 'replay-event-3', 'thread', 'thread-replay', 3, 'thread.activity-appended',+ '2026-03-01T00:00:02.000Z', NULL, NULL, NULL, 'provider',+ json_object('output', printf('%.*c', 3000, 'x')), '{}'+ ),+ (+ 'replay-event-4', 'thread', 'thread-replay', 4, 'thread.activity-appended',+ '2026-03-01T00:00:03.000Z', NULL, NULL, NULL, 'provider',+ json_object('output', 'π'), '{}'+ )+ `;++ // Bytes, not code points: the 4-byte emoji row is {"output":"π"}, 17 bytes.+ const stats = yield* snapshotQuery.getEventReplayStats({+ fromSequenceExclusive: 1,+ toSequenceInclusive: 4,+ });+ assert.deepStrictEqual(stats, {+ eventCount: 3,+ payloadBytes: 5043,+ });+ }),+ );+it.effect("reads single-thread checkpoint context without hydrating unrelated threads", () =>Effect.gen(function* () {const snapshotQuery = yield* ProjectionSnapshotQuery;diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.tsindex ea808f18d3a..02cbefe9691 100644--- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts+++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts@@ -62,6 +62,7 @@ import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityResimport { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts";import {ProjectionSnapshotQuery,+ type ProjectionEventReplayStats,type ProjectionFullThreadDiffContext,type ProjectionSnapshotCounts,type ProjectionThreadCheckpointContext,@@ -129,6 +130,14 @@ const ProjectionCountsRowSchema = Schema.Struct({projectCount: Schema.Number,threadCount: Schema.Number,});+const EventReplayStatsInput = Schema.Struct({+ fromSequenceExclusive: NonNegativeInt,+ toSequenceInclusive: NonNegativeInt,+});+const EventReplayStatsRowSchema = Schema.Struct({+ eventCount: Schema.Number,+ payloadBytes: Schema.Number,+});const ProjectionThreadSearchRequest = Schema.Struct({pattern: Schema.String,limit: Schema.Int,@@ -812,6 +821,20 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {`,});+ const readEventReplayStats = SqlSchema.findOne({+ Request: EventReplayStatsInput,+ Result: EventReplayStatsRowSchema,+ execute: ({ fromSequenceExclusive, toSequenceInclusive }) =>+ sql`+ SELECT+ COUNT(*) AS "eventCount",+ COALESCE(SUM(octet_length(payload_json)), 0) AS "payloadBytes"+ FROM orchestration_events+ WHERE sequence > ${fromSequenceExclusive}+ AND sequence <= ${toSequenceInclusive}+ `,+ });+const searchActiveThreadRows = SqlSchema.findAll({Request: ProjectionThreadSearchRequest,Result: ProjectionThreadSearchRow,@@ -2448,6 +2471,22 @@ pending_approval_requests AS (),);+ const getEventReplayStats: ProjectionSnapshotQueryShape["getEventReplayStats"] = (input) =>+ readEventReplayStats(input).pipe(+ Effect.mapError(+ toPersistenceSqlOrDecodeError(+ "ProjectionSnapshotQuery.getEventReplayStats:query",+ "ProjectionSnapshotQuery.getEventReplayStats:decodeRow",+ ),+ ),+ Effect.map(+ (row): ProjectionEventReplayStats => ({+ eventCount: row.eventCount,+ payloadBytes: row.payloadBytes,+ }),+ ),+ );+const searchThreads: ProjectionSnapshotQueryShape["searchThreads"] = Effect.fn("ProjectionSnapshotQuery.searchThreads",)(function* (input) {@@ -3109,6 +3148,7 @@ pending_approval_requests AS (searchThreads,getSnapshotSequence,getCounts,+ getEventReplayStats,getActiveProjectByWorkspaceRoot,getProjectShellById,getFirstActiveThreadIdByProjectId,diff --git a/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.tsindex 9428e84747c..5ad9ceef1d2 100644--- a/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts+++ b/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts@@ -37,6 +37,11 @@ export interface ProjectionSnapshotSequence {readonly snapshotSequence: number;}+export interface ProjectionEventReplayStats {+ readonly eventCount: number;+ readonly payloadBytes: number;+}+export interface ProjectionThreadCheckpointContext {readonly threadId: ThreadId;readonly projectId: ProjectId;@@ -128,6 +133,14 @@ export interface ProjectionSnapshotQueryShape {*/readonly getCounts: () => Effect.Effect<ProjectionSnapshotCounts, ProjectionRepositoryError>;+ /**+ * Measure a persisted event range without decoding its payload bodies.+ */+ readonly getEventReplayStats: (input: {+ readonly fromSequenceExclusive: number;+ readonly toSequenceInclusive: number;+ }) => Effect.Effect<ProjectionEventReplayStats, ProjectionRepositoryError>;+/*** Read the active project for an exact workspace root match.*/diff --git a/apps/server/src/project/ProjectSetupScriptRunner.test.ts b/apps/server/src/project/ProjectSetupScriptRunner.test.tsindex 5c5da4666b0..b0679a94cc2 100644--- a/apps/server/src/project/ProjectSetupScriptRunner.test.ts+++ b/apps/server/src/project/ProjectSetupScriptRunner.test.ts@@ -32,6 +32,7 @@ const makeProjectionSnapshotQueryLayer = (project: OrchestrationProject) =>getArchivedShellSnapshot: () => Effect.die("unused"),getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 1 }),getCounts: () => Effect.die("unused"),+ getEventReplayStats: () => Effect.die("unused"),getActiveProjectByWorkspaceRoot: (workspaceRoot) =>Effect.succeed(workspaceRoot === project.workspaceRoot ? Option.some(project) : Option.none(),diff --git a/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts b/apps/server/src/provider/Layers/ProviderSessionReaper.test.tsindex 0b1bc9e149f..692181531aa 100644--- a/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts+++ b/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts@@ -210,6 +210,7 @@ describe("ProviderSessionReaper", () => {getSnapshotSequence: () =>Effect.succeed({ snapshotSequence: input.readModel.snapshotSequence }),getCounts: () => Effect.die("unused"),+ getEventReplayStats: () => Effect.die("unused"),getActiveProjectByWorkspaceRoot: () => Effect.die("unused"),getProjectShellById: () => Effect.die("unused"),getFirstActiveThreadIdByProjectId: () => Effect.die("unused"),diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.tsindex 8170901a21f..10cf74240ae 100644--- a/apps/server/src/server.test.ts+++ b/apps/server/src/server.test.ts@@ -888,6 +888,11 @@ const buildAppUnderTest = (options?: {getThreadDetailById: () => Effect.succeed(Option.none()),getThreadDetailSnapshot: () => Effect.succeed(Option.none()),getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),+ getEventReplayStats: ({ fromSequenceExclusive, toSequenceInclusive }) =>+ Effect.succeed({+ eventCount: Math.max(0, toSequenceInclusive - fromSequenceExclusive),+ payloadBytes: 0,+ }),getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),getThreadCheckpointContext: () => Effect.succeed(Option.none()),@@ -7366,6 +7371,70 @@ it.layer(NodeServices.layer)("server router seam", (it) => {}).pipe(Effect.provide(NodeHttpServer.layerTest)),);+ it.effect("subscriptions snapshot instead of decoding an oversized replay range", () =>+ Effect.gen(function* () {+ let readEventsCalls = 0;+ let replayStatsCalls = 0;+ const thread = makeDefaultOrchestrationReadModel().threads[0]!;+ const shell = makeDefaultOrchestrationThreadShell({ id: thread.id });++ yield* buildAppUnderTest({+ layers: {+ orchestrationEngine: {+ latestSequence: Effect.succeed(5),+ readEvents: () =>+ Stream.sync(() => {+ readEventsCalls += 1;+ return {} as OrchestrationEvent;+ }),+ },+ projectionSnapshotQuery: {+ getEventReplayStats: () =>+ Effect.sync(() => {+ replayStatsCalls += 1;+ return { eventCount: 5, payloadBytes: 8 * 1024 * 1024 + 1 };+ }),+ getThreadDetailSnapshot: () =>+ Effect.succeed(Option.some({ snapshotSequence: 5, thread })),+ getShellSnapshot: () =>+ Effect.succeed({+ snapshotSequence: 5,+ projects: [],+ threads: [shell],+ updatedAt: "2026-01-01T00:00:00.000Z",+ }),+ },+ },+ });++ const wsUrl = yield* getWsServerUrl("/ws");+ const threadItems = yield* Effect.scoped(+ withWsRpcClient(wsUrl, (client) =>+ client[ORCHESTRATION_WS_METHODS.subscribeThread]({+ threadId: thread.id,+ afterSequence: 0,+ requestCompletionMarker: true,+ }).pipe(Stream.take(2), Stream.runCollect),+ ),+ );+ const shellItems = yield* Effect.scoped(+ withWsRpcClient(wsUrl, (client) =>+ client[ORCHESTRATION_WS_METHODS.subscribeShell]({+ afterSequence: 0,+ requestCompletionMarker: true,+ }).pipe(Stream.take(2), Stream.runCollect),+ ),+ );++ assert.equal(threadItems[0]?.kind, "snapshot");+ assert.equal(threadItems[1]?.kind, "synchronized");+ assert.equal(shellItems[0]?.kind, "snapshot");+ assert.equal(shellItems[1]?.kind, "synchronized");+ assert.equal(replayStatsCalls, 2);+ assert.equal(readEventsCalls, 0);+ }).pipe(Effect.provide(NodeHttpServer.layerTest)),+ );+it.effect("subscribeShell replaces a cursor ahead of the authoritative head", () =>Effect.gen(function* () {let readEventsCalls = 0;diff --git a/apps/server/src/serverRuntimeStartup.test.ts b/apps/server/src/serverRuntimeStartup.test.tsindex fc5b2c9e545..83642a956ae 100644--- a/apps/server/src/serverRuntimeStartup.test.ts+++ b/apps/server/src/serverRuntimeStartup.test.ts@@ -83,6 +83,7 @@ it.effect("launchStartupHeartbeat does not block the caller while counts are loagetShellSnapshot: () => Effect.die("unused"),getArchivedShellSnapshot: () => Effect.die("unused"),getSnapshotSequence: () => Effect.die("unused"),+ getEventReplayStats: () => Effect.die("unused"),getCounts: () =>Deferred.succeed(countsStarted, undefined).pipe(Effect.andThen(Deferred.await(releaseCounts)),@@ -150,6 +151,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and threagetArchivedShellSnapshot: () => Effect.die("unused"),getSnapshotSequence: () => Effect.die("unused"),getCounts: () => Effect.die("unused"),+ getEventReplayStats: () => Effect.die("unused"),getActiveProjectByWorkspaceRoot: () =>Effect.succeed(Option.some({@@ -207,6 +209,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread whengetArchivedShellSnapshot: () => Effect.die("unused"),getSnapshotSequence: () => Effect.die("unused"),getCounts: () => Effect.die("unused"),+ getEventReplayStats: () => Effect.die("unused"),getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),getProjectShellById: () => Effect.die("unused"),getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),@@ -258,6 +261,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets preserves typed UUID generation fagetArchivedShellSnapshot: () => Effect.die("unused"),getSnapshotSequence: () => Effect.die("unused"),getCounts: () => Effect.die("unused"),+ getEventReplayStats: () => Effect.die("unused"),getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),getProjectShellById: () => Effect.die("unused"),getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.tsindex db3b74b7e4b..53f1b6734e8 100644--- a/apps/server/src/ws.ts+++ b/apps/server/src/ws.ts@@ -335,6 +335,10 @@ const SHELL_RESUME_MAX_GAP = 1_000;// 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;+// 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.+const ORCHESTRATION_REPLAY_PAYLOAD_BUDGET_BYTES = 8 * 1024 * 1024;function toAuthAccessStreamEvent(change: PairingGrantStore.BootstrapCredentialChange | SessionStore.SessionCredentialChange,@@ -514,6 +518,42 @@ const makeWsRpcLayer = (const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup;const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;+ const canReplayPersistedRange = Effect.fnUntraced(function* (+ afterSequence: number,+ headSequence: number,+ maxGap: number,+ ) {+ const replayGap = headSequence - afterSequence;+ if (replayGap < 0 || replayGap > maxGap) {+ return false;+ }+ const stats = yield* projectionSnapshotQuery+ .getEventReplayStats({+ fromSequenceExclusive: afterSequence,+ toSequenceInclusive: headSequence,+ })+ .pipe(+ Effect.mapError(+ (cause) =>+ new OrchestrationGetSnapshotError({+ message: "Failed to measure orchestration replay range",+ cause,+ }),+ ),+ );+ if (stats.payloadBytes > ORCHESTRATION_REPLAY_PAYLOAD_BUDGET_BYTES) {+ yield* Effect.logDebug("orchestration replay replaced by snapshot", {+ afterSequence,+ headSequence,+ replayGap,+ eventCount: stats.eventCount,+ payloadBytes: stats.payloadBytes,+ payloadBudgetBytes: ORCHESTRATION_REPLAY_PAYLOAD_BUDGET_BYTES,+ });+ return false;+ }+ return true;+ });const projectSetupScriptRunner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;@@ -1419,7 +1459,13 @@ const makeWsRpcLayer = (// is also invalid, so reset it with a snapshot. Send the snapshot// followed by the buffered live tail, exactly as the// no-afterSequence path does.- if (replayGap < 0 || replayGap > SHELL_RESUME_MAX_GAP) {+ if (+ !(yield* canReplayPersistedRange(+ afterSequence,+ headSequence,+ SHELL_RESUME_MAX_GAP,+ ))+ ) {const snapshot = yield* loadSnapshot;return Stream.concat(Stream.make({ kind: "snapshot" as const, snapshot }),@@ -1521,7 +1567,9 @@ const makeWsRpcLayer = (const afterSequence = input.afterSequence;const headSequence = yield* orchestrationEngine.latestSequence;const replayGap = headSequence - afterSequence;- if (replayGap >= 0 && replayGap <= THREAD_RESUME_MAX_GAP) {+ if (+ yield* canReplayPersistedRange(afterSequence, headSequence, THREAD_RESUME_MAX_GAP)+ ) {const catchUpStream = orchestrationEngine.readEvents(afterSequence, replayGap).pipe(