fix(server): bound orchestration replay payloads (#8992)

WebSocket reconnect catch-up only checked the number of missing events, then loaded and decoded the whole replay range before sending it. A handful of events with large tool payloads could allocate gigabytes and OOM the server.

Before replaying, run a SQL preflight that counts the events in the range and sums their serialized payload bytes with octet_length(). If the range is over the existing row limit or an 8 MiB byte budget, fall back to the fresh snapshot path. Applies to both thread and shell subscriptions.

Authored by @rcawston. Review, octet_length fix, and merge by Claude Fable 5.1 in Claude Code on behalf of @t3dotgg.
This commit is contained in:
Ross Cawston authored and GitHub committed 2026-09-01 18:07:56 -07:00
1 parent c2283ce146
commit 7e460f429b
10 files changed
+230 -2

No files matched your search

@@ -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()),
@@ -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()),
@@ -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;
@@ -62,6 +62,7 @@ import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityRes
import { 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,
@@ -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.
*/
@@ -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(),
@@ -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"),
+69
View File
@@ -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;
@@ -83,6 +83,7 @@ it.effect("launchStartupHeartbeat does not block the caller while counts are loa
getShellSnapshot: () => 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 threa
getArchivedShellSnapshot: () => 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 when
getArchivedShellSnapshot: () => 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 fa
getArchivedShellSnapshot: () => 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()),
+50 -2
View File
@@ -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(