diff --git a/apps/server/integration/transferBudgetV2.integration.test.ts b/apps/server/integration/transferBudgetV2.integration.test.ts index 4aaac3b9e30e9..be505224587af 100644 --- a/apps/server/integration/transferBudgetV2.integration.test.ts +++ b/apps/server/integration/transferBudgetV2.integration.test.ts @@ -436,7 +436,7 @@ it.live("reports V2 thread HTTP and WebSocket transfer budgets", () => const reconnectThread = { ...resumedThread.recorder.totals(), mode: threadMode }; const reconnectShell = { ...resumedShell.recorder.totals(), mode: shellMode }; const reconnectSqlStatements = counter.count() - reconnectSqlStart; - assert.equal(threadMode, "snapshot"); + assert.equal(threadMode, "replay"); const get = (path: string) => measureHttpGet({ diff --git a/apps/server/src/orchestration-v2/ThreadStream.test.ts b/apps/server/src/orchestration-v2/ThreadStream.test.ts index 5c9fd310e93ae..b6f30e96d1ff4 100644 --- a/apps/server/src/orchestration-v2/ThreadStream.test.ts +++ b/apps/server/src/orchestration-v2/ThreadStream.test.ts @@ -1,7 +1,6 @@ import { ContextHandoffId, ContextTransferId, - EventId, OrchestrationV2ThreadStreamItem, ProviderThreadId, RunId, @@ -17,22 +16,10 @@ import * as DateTime from "effect/DateTime"; import * as Schema from "effect/Schema"; import { boundedSnapshotProjection } from "@t3tools/shared/orchestrationV2BoundedSnapshot"; -import { - buildBoundedThreadStreamSnapshot, - decideThreadResume, - isThreadReplayRawPayloadSafe, - threadReplayEncodedBytes, - THREAD_RESUME_MAX_RAW_PAYLOAD_BYTES, - THREAD_RESUME_MAX_REPLAY_ENCODED_BYTES, - THREAD_RESUME_MAX_REPLAY_EVENTS, -} from "./ThreadStream.ts"; -import { projectDomainEventForWire } from "./WireProjection.ts"; +import { buildBoundedThreadStreamSnapshot } from "./ThreadStream.ts"; const NOW = DateTime.makeUnsafe("2026-09-08T00:00:00.000Z"); const THREAD_ID = ThreadId.make("thread-stream-test"); -const LARGE_PROJECTABLE_OUTPUT_BYTES = 10 * 1_048_576; -const LARGE_PROJECTABLE_RAW_PAYLOAD_BYTES = 10_486_214; -const MAX_PROJECTED_DYNAMIC_REPLAY_BYTES = 2_048; function timelineProjection(itemCount: number): OrchestrationV2ThreadProjection { const visibleTurnItems: OrchestrationV2ProjectedTurnItem[] = Array.from( @@ -115,44 +102,7 @@ function timelineProjection(itemCount: number): OrchestrationV2ThreadProjection } as unknown as OrchestrationV2ThreadProjection; } -describe("decideThreadResume", () => { - it("replays when the event count is within the bound", () => { - expect( - decideThreadResume({ - afterSequence: 10, - highWater: 20_000, - replayEventCount: THREAD_RESUME_MAX_REPLAY_EVENTS, - replayEncodedBytes: THREAD_RESUME_MAX_REPLAY_ENCODED_BYTES, - }), - ).toEqual({ - mode: "replay", - afterSequence: 10, - throughSequence: 20_000, - }); - }); - - it("falls back to a snapshot when encoded replay bytes exceed the bound", () => { - expect( - decideThreadResume({ - afterSequence: 10, - highWater: 11, - replayEventCount: 1, - replayEncodedBytes: THREAD_RESUME_MAX_REPLAY_ENCODED_BYTES + 1, - }), - ).toEqual({ mode: "snapshot" }); - }); - - it("falls back to a snapshot when the client cursor is ahead of the store", () => { - expect( - decideThreadResume({ - afterSequence: 50, - highWater: 40, - replayEventCount: 0, - replayEncodedBytes: 0, - }), - ).toEqual({ mode: "snapshot" }); - }); - +describe("buildBoundedThreadStreamSnapshot", () => { it("builds socket fallback snapshots with a bounded timeline and history cursor", () => { const projection = timelineProjection(80); // A delivered side chat digest stays "ready", which bounded snapshots keep. @@ -187,62 +137,6 @@ describe("decideThreadResume", () => { expect(snapshot.hasMoreHistory).toBe(true); expect(snapshot.latestLocalTurnOrdinal).toBe(80); }); - - it("rejects a 10 MiB raw replay even when its projected form fits the wire budget", () => { - const item = { - id: TurnItemId.make("large-dynamic-tool"), - type: "dynamic_tool", - threadId: THREAD_ID, - runId: null, - nodeId: null, - providerThreadId: null, - providerTurnId: null, - nativeItemRef: null, - parentItemId: null, - ordinal: 1, - status: "completed", - title: "Large result", - toolName: "mcp__test__large_result", - input: { query: "small" }, - output: { text: "x".repeat(LARGE_PROJECTABLE_OUTPUT_BYTES) }, - startedAt: NOW, - completedAt: NOW, - updatedAt: NOW, - } satisfies OrchestrationV2TurnItem; - const event = { - id: EventId.make("large-dynamic-tool-event"), - type: "turn-item.updated" as const, - threadId: THREAD_ID, - occurredAt: NOW, - payload: item, - }; - const rawReplay = [{ kind: "event" as const, sequence: 10, event }]; - const projectedReplay = [ - { - kind: "event" as const, - sequence: 10, - event: projectDomainEventForWire(event), - }, - ]; - - const rawPayloadBytes = Buffer.byteLength(JSON.stringify(event.payload), "utf8"); - expect(rawPayloadBytes).toBe(LARGE_PROJECTABLE_RAW_PAYLOAD_BYTES); - expect(rawPayloadBytes).toBeGreaterThan(THREAD_RESUME_MAX_RAW_PAYLOAD_BYTES); - expect(isThreadReplayRawPayloadSafe(rawPayloadBytes)).toBe(false); - expect(threadReplayEncodedBytes(rawReplay)).toBeGreaterThan( - THREAD_RESUME_MAX_REPLAY_ENCODED_BYTES, - ); - const projectedBytes = threadReplayEncodedBytes(projectedReplay); - expect(projectedBytes).toBeLessThanOrEqual(MAX_PROJECTED_DYNAMIC_REPLAY_BYTES); - expect( - decideThreadResume({ - afterSequence: 9, - highWater: 10, - replayEventCount: projectedReplay.length, - replayEncodedBytes: projectedBytes, - }), - ).toEqual({ mode: "replay", afterSequence: 9, throughSequence: 10 }); - }); }); describe("compact bounded snapshots", () => { diff --git a/apps/server/src/orchestration-v2/ThreadStream.ts b/apps/server/src/orchestration-v2/ThreadStream.ts index c16a1b9e095aa..2bb4bd5396731 100644 --- a/apps/server/src/orchestration-v2/ThreadStream.ts +++ b/apps/server/src/orchestration-v2/ThreadStream.ts @@ -17,14 +17,7 @@ import { export const THREAD_RESUME_MAX_REPLAY_EVENTS = 128; -export const THREAD_RESUME_MAX_REPLAY_ENCODED_BYTES = 1_048_576; - -/** Decoded objects and temporary strings exceed stored JSON size, even before wire slimming. */ -export const THREAD_RESUME_MAX_RAW_PAYLOAD_BYTES = 1_048_576; - -export function isThreadReplayRawPayloadSafe(rawPayloadBytes: number): boolean { - return rawPayloadBytes <= THREAD_RESUME_MAX_RAW_PAYLOAD_BYTES; -} +const THREAD_RESUME_MAX_REPLAY_ENCODED_BYTES = 1_048_576; export function threadReplayEncodedBytes( items: ReadonlyArray, @@ -87,32 +80,3 @@ export function buildBoundedThreadStreamSnapshot(input: { }), }; } - -export type ThreadResumePlan = - | { - readonly mode: "replay"; - readonly afterSequence: number; - readonly throughSequence: number; - } - | { readonly mode: "snapshot" }; - -/** Bound event count and encoded bytes; replace excessive replay with one current snapshot. */ -export function decideThreadResume(input: { - readonly afterSequence: number; - readonly highWater: number; - readonly replayEventCount: number; - readonly replayEncodedBytes: number; -}): ThreadResumePlan { - if ( - input.afterSequence > input.highWater || - input.replayEventCount > THREAD_RESUME_MAX_REPLAY_EVENTS || - input.replayEncodedBytes > THREAD_RESUME_MAX_REPLAY_ENCODED_BYTES - ) { - return { mode: "snapshot" }; - } - return { - mode: "replay", - afterSequence: input.afterSequence, - throughSequence: input.highWater, - }; -} diff --git a/apps/server/src/persistence/OrchestrationEventStore.sequence.test.ts b/apps/server/src/persistence/OrchestrationEventStore.sequence.test.ts index c317ab845738b..ae5d2532ce13a 100644 --- a/apps/server/src/persistence/OrchestrationEventStore.sequence.test.ts +++ b/apps/server/src/persistence/OrchestrationEventStore.sequence.test.ts @@ -69,6 +69,72 @@ const seedEvents = Effect.fn("test.seedSequenceEvents")(function* ( `; }); +it.effect("checks creation ranges without restoring or decoding payloads", () => + Effect.gen(function* () { + const store = yield* OrchestrationEventStore.OrchestrationEventStore; + const threadId = ThreadId.make("creation-existence"); + const inserted = yield* seedEvents([ + { ...eventRow(1, "thread", 2, threadId), event_type: "thread.created", payload_json: "{" }, + eventRow(2, "thread", 2, threadId), + { ...eventRow(3, "thread", 2, "other"), event_type: "thread.created", payload_json: "{" }, + { ...eventRow(4, "thread", 1, threadId), event_type: "thread.created", payload_json: "{" }, + ]); + const range = { + threadId, + afterSequence: 0, + throughSequence: inserted[3]!.sequence, + eventType: "thread.created" as const, + }; + assert.isTrue(yield* store.hasAgentEvent(range)); + assert.isFalse(yield* store.hasAgentEvent({ ...range, afterSequence: inserted[0]!.sequence })); + assert.isFalse(yield* store.hasAgentEvent({ ...range, throughSequence: 0 })); + assert.isTrue(yield* store.hasAgentEvent({ ...range, throughSequence: inserted[0]!.sequence })); + }).pipe(Effect.provide(layerEventStore)), +); + +it.effect("fetches the next byte-bounded replay page after delivering the previous page", () => + Effect.gen(function* () { + const store = yield* OrchestrationEventStore.OrchestrationEventStore; + const sql = yield* SqlClient.SqlClient; + const threadId = ThreadId.make("byte-paged-replay"); + const rows = Arr.map([1, 2] as const, (ordinal) => ({ + ...eventRow(ordinal, "thread", 2, threadId), + payload_json: encodeJson({ + providerSessionId: `session:${ordinal}:${"x".repeat(180_000)}`, + detachedAt: occurredAt, + }), + })); + const inserted = yield* seedEvents(rows); + const updatedPayload = { + providerSessionId: ProviderSessionId.make("session:updated"), + detachedAt: occurredAt, + }; + const items = yield* store + .readAgentEvents({ + threadId, + throughSequence: inserted[1]!.sequence, + maxPageBytes: 256 * 1024, + }) + .pipe( + Stream.tap((item) => + item.sequence === inserted[0]!.sequence + ? sql`UPDATE orchestration_events SET payload_json = ${encodeJson(updatedPayload)} + WHERE sequence = ${inserted[1]!.sequence}` + : Effect.void, + ), + Stream.runCollect, + ); + assert.deepEqual( + items.map((item) => item.sequence), + inserted.map((item) => item.sequence), + ); + assert.deepEqual(items[1]!.event.payload, { + ...updatedPayload, + detachedAt: DateTime.makeUnsafe(occurredAt), + }); + }).pipe(Effect.provide(layerEventStore)), +); + it.effect("keeps application and scoped agent high-water marks separate from legacy history", () => Effect.gen(function* () { const store = yield* OrchestrationEventStore.OrchestrationEventStore; diff --git a/apps/server/src/persistence/OrchestrationEventStore.test.ts b/apps/server/src/persistence/OrchestrationEventStore.test.ts index df6382a8b4f85..8edc939e25877 100644 --- a/apps/server/src/persistence/OrchestrationEventStore.test.ts +++ b/apps/server/src/persistence/OrchestrationEventStore.test.ts @@ -111,7 +111,7 @@ layer("OrchestrationEventStore", (it) => { const id = NodeId.make("node:subagent-prompt"); const driver = ProviderDriverKind.make("claudeAgent"); const providerInstanceId = ProviderInstanceId.make("claudeAgent"); - const prompt = "Audit the repository. ".repeat(200); + const prompt = 'Audit "repo"\n漢字 '.repeat(9_000); const subagent = (index: number, progress: string, nextPrompt = prompt) => ({ id: EventId.make(`event:subagent-prompt:subagent:${index}`), @@ -183,14 +183,14 @@ layer("OrchestrationEventStore", (it) => { subagent(3, "Retrying", "Audit again."), item(3, "Retrying", "Audit again."), ]; - yield* store.appendAgentEvents({ events }); + const appended = yield* store.appendAgentEvents({ events }); const stored = yield* sql<{ readonly payload_json: string }>` SELECT payload_json FROM orchestration_events WHERE stream_id = ${threadId} ORDER BY sequence ASC `; assert.deepEqual( - stored.map((row) => row.payload_json.includes(prompt)), + stored.map((row) => row.payload_json.includes(JSON.stringify(prompt).slice(1, -1))), [true, true, false, false, false, false, false, false], ); const replayed = yield* store @@ -200,18 +200,33 @@ layer("OrchestrationEventStore", (it) => { replayed.map((entry) => entry.event), events, ); - const stats = yield* store.getAgentReplayStats({ - threadId, - afterSequence, - throughSequence: yield* store.latestApplicationSequence, - maxEvents: events.length, - }); - assert.isAbove(stats.rawPayloadBytes, prompt.length * 6); const applicationStats = yield* store.getReplayStats({ afterSequence, throughSequence: yield* store.latestApplicationSequence, }); assert.isAbove(applicationStats.rawPayloadBytes, prompt.length * 6); + const paged = yield* store + .readAgentEvents({ threadId, afterSequence, maxPageBytes: 256 * 1024 }) + .pipe(Stream.runCollect); + assert.deepEqual( + paged.map((entry) => entry.event), + events, + ); + // The first two updates here reference prompts in earlier anchor rows. + // Sizing must stop before touching a later page's malformed payload. + yield* sql`UPDATE orchestration_events SET payload_json = '{' WHERE sequence = ${appended[4]!.sequence}`; + const firstPage = yield* store + .readAgentEvents({ + threadId, + afterSequence: appended[1]!.sequence, + throughSequence: appended[4]!.sequence, + maxPageBytes: 256 * 1024, + }) + .pipe(Stream.take(1), Stream.runCollect); + assert.deepEqual( + firstPage.map((entry) => entry.event), + [events[2]!], + ); }), ); @@ -392,7 +407,7 @@ layer("OrchestrationEventStore", (it) => { ); }), ); - it.effect("measures only a bounded thread replay before decoding its payloads", () => + it.effect("measures replay payloads before decoding them", () => Effect.gen(function* () { const store = yield* OrchestrationEventStore.OrchestrationEventStore; const sql = yield* SqlClient.SqlClient; @@ -420,7 +435,7 @@ layer("OrchestrationEventStore", (it) => { `; return rows[0]!.sequence; }); - const first = yield* insert({ + yield* insert({ id: "measured-replay-1", payload: unicodePayload, type: "thread.created", @@ -432,28 +447,6 @@ layer("OrchestrationEventStore", (it) => { }); yield* insert({ id: "measured-legacy", payload: oversizedPayload, version: 1 }); const head = yield* insert({ id: "measured-replay-02", payload: oversizedPayload }); - const later = yield* insert({ id: "measured-replay-003", payload: "{}" }); - const range = { threadId, afterSequence: baseline, throughSequence: head, maxEvents: 128 }; - assert.deepEqual(yield* store.getAgentReplayStats(range), { - eventCount: 2, - rawPayloadBytes: Buffer.byteLength(unicodePayload) + Buffer.byteLength(oversizedPayload), - hasCreateEvent: true, - }); - assert.deepEqual(yield* store.getAgentReplayStats({ ...range, afterSequence: first }), { - eventCount: 1, - rawPayloadBytes: Buffer.byteLength(oversizedPayload), - hasCreateEvent: false, - }); - assert.equal( - (yield* store.getAgentReplayStats({ ...range, throughSequence: later, maxEvents: 1 })) - .eventCount, - 2, - ); - assert.deepEqual(yield* store.getAgentReplayStats({ ...range, afterSequence: later }), { - eventCount: 0, - rawPayloadBytes: 0, - hasCreateEvent: false, - }); assert.deepEqual( yield* store.getReplayStats({ afterSequence: baseline, throughSequence: head }), { diff --git a/apps/server/src/persistence/OrchestrationEventStore.ts b/apps/server/src/persistence/OrchestrationEventStore.ts index e55d82713871b..788530fd2cba4 100644 --- a/apps/server/src/persistence/OrchestrationEventStore.ts +++ b/apps/server/src/persistence/OrchestrationEventStore.ts @@ -64,21 +64,17 @@ export class OrchestrationEventStore extends Context.Service< readonly eventType?: OrchestrationV2DomainEvent["type"]; readonly limit?: number; readonly skipUnknownEventTypes?: boolean; + /** Bound fetched JSON per page, always allowing one indivisible event. */ + readonly maxPageBytes?: number; }) => Stream.Stream; - readonly getAgentReplayStats: (input: { + /** Check a scoped replay range without reading or restoring event payloads. */ + readonly hasAgentEvent: (input: { readonly threadId: ThreadId; readonly afterSequence: number; readonly throughSequence: number; - readonly maxEvents: number; - }) => Effect.Effect< - { - readonly eventCount: number; - readonly rawPayloadBytes: number; - readonly hasCreateEvent: boolean; - }, - OrchestrationEventStoreError - >; + readonly eventType: OrchestrationV2DomainEvent["type"]; + }) => Effect.Effect; readonly getReplayStats: (input: { readonly afterSequence: number; @@ -399,9 +395,9 @@ const makeEventStore = Effect.gen(function* () { readonly eventType?: OrchestrationV2DomainEvent["type"]; readonly onlyAgentEvents?: boolean; readonly limit: number; - }) => - sql` - SELECT + readonly maxPageBytes?: number; + }) => { + const columns = sql` sequence, event_id, command_id, @@ -414,6 +410,8 @@ const makeEventStore = Effect.gen(function* () { application_event_version, causation_event_id, correlation_id + `; + const from = sql` FROM orchestration_events ${ // Otherwise the sequence index wins and command lookups scan every V2 event. @@ -438,9 +436,41 @@ const makeEventStore = Effect.gen(function* () { ...(input.commandId === undefined ? [] : [sql`command_id = ${input.commandId}`]), ...(input.eventType === undefined ? [] : [sql`event_type = ${input.eventType}`]), ])} - ORDER BY sequence ASC - LIMIT ${input.limit} + `; + if (input.maxPageBytes === undefined) { + return sql` + SELECT ${columns} ${from} ORDER BY sequence ASC LIMIT ${input.limit} + `.pipe(NodeSqliteClient.readOnly); + } + // Materialize only candidate ids. Walk their restored sizes until the page + // fills (at most one overflow row), rather than restoring all 500 bodies. + // Prompt references must be sized after restoration, including JSON escaping. + return sql` + WITH RECURSIVE candidates AS MATERIALIZED ( + SELECT sequence, ROW_NUMBER() OVER (ORDER BY sequence) AS ordinal + ${from} ORDER BY sequence ASC LIMIT ${input.limit} + ), replay_page(cursor, replay_bytes, row_count) AS ( + SELECT orchestration_events.sequence, + octet_length(${restoredPayloadJson}) + octet_length(metadata_json), 1 + FROM orchestration_events + JOIN candidates ON candidates.sequence = orchestration_events.sequence + WHERE candidates.ordinal = 1 + UNION ALL + SELECT orchestration_events.sequence, + page.replay_bytes + octet_length(${restoredPayloadJson}) + octet_length(metadata_json), + page.row_count + 1 + FROM replay_page AS page + JOIN candidates ON candidates.ordinal = page.row_count + 1 + JOIN orchestration_events ON orchestration_events.sequence = candidates.sequence + WHERE page.replay_bytes < ${input.maxPageBytes} + ) + SELECT ${columns} + FROM orchestration_events + JOIN replay_page ON replay_page.cursor = orchestration_events.sequence + WHERE replay_page.row_count = 1 OR replay_page.replay_bytes <= ${input.maxPageBytes} + ORDER BY sequence `.pipe(NodeSqliteClient.readOnly); + }; const appendAgentEvents: OrchestrationEventStore["Service"]["appendAgentEvents"] = (input) => Effect.forEach( @@ -563,6 +593,7 @@ const makeEventStore = Effect.gen(function* () { ...(input?.eventType === undefined ? {} : { eventType: input.eventType }), onlyAgentEvents: true, limit: pageLimit, + ...(input?.maxPageBytes === undefined ? {} : { maxPageBytes: input.maxPageBytes }), }).pipe( Effect.mapError(toPersistenceSqlError("OrchestrationEventStore.readAgentEvents:query")), Effect.map((rows) => { @@ -571,7 +602,7 @@ const makeEventStore = Effect.gen(function* () { return [ rows, last === undefined || - rows.length < pageLimit || + (input?.maxPageBytes === undefined && rows.length < pageLimit) || nextRemaining <= 0 || (input?.throughSequence !== undefined && last.sequence >= input.throughSequence) ? Option.none() @@ -592,35 +623,21 @@ const makeEventStore = Effect.gen(function* () { ); }; - const getAgentReplayStats: OrchestrationEventStore["Service"]["getAgentReplayStats"] = (input) => - sql<{ - readonly eventCount: number; - readonly rawPayloadBytes: number; - readonly hasCreateEvent: number; - }>` - SELECT - COUNT(*) AS "eventCount", - COALESCE(SUM(octet_length(payload_json)), 0) AS "rawPayloadBytes", - COALESCE(MAX(event_type = 'thread.created'), 0) AS "hasCreateEvent" - FROM ( - SELECT ${restoredPayloadJson} AS payload_json, event_type - FROM orchestration_events + const hasAgentEvent: OrchestrationEventStore["Service"]["hasAgentEvent"] = (input) => + sql<{ readonly found: number }>` + SELECT EXISTS ( + SELECT 1 FROM orchestration_events WHERE aggregate_kind = 'thread' AND stream_id = ${input.threadId} AND application_event_version = 2 AND sequence > ${input.afterSequence} AND sequence <= ${input.throughSequence} - ORDER BY sequence ASC - LIMIT ${Math.max(0, Math.floor(input.maxEvents)) + 1} - ) + AND event_type = ${input.eventType} + ) AS found `.pipe( NodeSqliteClient.readOnly, - Effect.mapError(toPersistenceSqlError("OrchestrationEventStore.getAgentReplayStats:query")), - Effect.map((rows) => ({ - eventCount: rows[0]?.eventCount ?? 0, - rawPayloadBytes: rows[0]?.rawPayloadBytes ?? 0, - hasCreateEvent: (rows[0]?.hasCreateEvent ?? 0) !== 0, - })), + Effect.mapError(toPersistenceSqlError("OrchestrationEventStore.hasAgentEvent:query")), + Effect.map((rows) => rows[0]?.found === 1), ); const getReplayStats: OrchestrationEventStore["Service"]["getReplayStats"] = (input) => @@ -760,7 +777,7 @@ const makeEventStore = Effect.gen(function* () { appendProjectEvent, appendAgentEvents, readAgentEvents, - getAgentReplayStats, + hasAgentEvent, getReplayStats, latestAgentSequence, latestApplicationSequence, diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index 660548c1dd68b..7b459ccd17857 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -36,6 +36,7 @@ import { import * as Deferred from "effect/Deferred"; import type { ProviderInstance } from "@t3tools/provider-core/server/driver"; import * as DateTime from "effect/DateTime"; +import * as Arr from "effect/Array"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Cause from "effect/Cause"; @@ -54,6 +55,7 @@ import * as SqlClient from "effect/sql/SqlClient"; import * as Statement from "effect/sql/Statement"; import { vi } from "vite-plus/test"; +import { threadReplayEncodedBytes } from "./orchestration-v2/ThreadStream.ts"; import * as AssetSigner from "./assets/AssetSigner.ts"; import * as PreviewAutomationBroker from "./mcp/PreviewAutomationBroker.ts"; import * as ServerBrowser from "./preview/ServerBrowser.ts"; @@ -394,6 +396,74 @@ it.live("shell resume skips unknown types, synchronizes, and receives the live t resumeSkipsUnknownTypes("shell"), ); +it.effect.each([ + { count: 260, padding: 0, unknownPrefix: 0 }, + { count: 40, padding: 2_000, unknownPrefix: 0 }, + { count: 3, padding: 600_000, unknownPrefix: 0 }, + { count: 3, padding: 0, unknownPrefix: 140 }, +])( + "resumes catch-up of $count events ($padding bytes, $unknownPrefix unknown rows) after interruption", + ({ count, padding, unknownPrefix }) => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const threadId = ThreadId.make("thread:incremental-replay"); + const now = "2026-10-28T00:00:00.000Z"; + const rows = Array.from({ length: count + unknownPrefix }, (_, version) => ({ + event_id: `incremental-replay:${version}`, + aggregate_kind: "thread", + stream_id: threadId, + stream_version: version, + event_type: version < unknownPrefix ? "future.event" : "provider-session.detached", + occurred_at: now, + actor_kind: "server", + payload_json: JSON.stringify({ + providerSessionId: `session:${version}:${"x".repeat(padding)}`, + detachedAt: now, + }), + metadata_json: "{}", + application_event_version: 2, + })); + assert(Arr.isArrayNonEmpty(rows)); + const inserted = yield* sql<{ sequence: number }>` + INSERT INTO orchestration_events ${sql.insert(rows)} RETURNING sequence + `; + const subscribe = (afterSequence: number) => + subscribeOrchestrationV2Thread({ + threadId, + afterSequence, + requestCompletionMarker: true, + }).pipe( + Effect.provideService(ThreadManagement.ThreadManagementService, { + ensureLegacyTranscript: () => Effect.void, + getThreadSnapshot: () => + Effect.die("Ordinary catch-up must not restart with a snapshot"), + streamStoredEventsFrom: () => Stream.empty, + } as unknown as ThreadManagement.ThreadManagementService["Service"]), + ); + const first = yield* subscribe(0).pipe( + Effect.flatMap((stream) => + stream.pipe(Stream.take(Math.min(10, count - 1)), Stream.runCollect), + ), + ); + const last = first.at(-1); + assert.equal(first.length, Math.min(10, count - 1)); + assert.equal(last?.kind, "event"); + if (last?.kind !== "event") return; + const frames = yield* subscribe(last.sequence).pipe( + Effect.flatMap((stream) => stream.pipe(Stream.chunks, Stream.runCollect)), + ); + // Each chunk is one RPC frame; only its last event may cross the page budget. + for (const frame of frames) { + assert.isBelow(threadReplayEncodedBytes(frame.slice(0, -1)), 32 * 1024); + } + const resumed = frames.flat(); + assert.deepEqual( + [...first, ...resumed].map((item) => (item.kind === "event" ? item.sequence : item.kind)), + [...inserted.slice(unknownPrefix).map((row) => row.sequence), "synchronized"], + ); + }).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)), +); + it.effect("coalesces streaming replay before synchronization and the live tail", () => Effect.gen(function* () { const store = yield* OrchestrationEventStore.OrchestrationEventStore; @@ -2056,7 +2126,11 @@ it.effect.each(["thread", "shell"] as const)( const gateReplayRead: Statement.Transformer = (statement) => { const [query] = statement.compile(); // The paged replay read (readApplicationRows), not the stats or high-water queries. - if (!gated && /^\s*SELECT\s+sequence,\s+event_id,/.test(query)) { + if ( + !gated && + (/^\s*SELECT\s+sequence,\s+event_id,/.test(query) || + /^\s*WITH RECURSIVE candidates AS MATERIALIZED/.test(query)) + ) { gated = true; return Deferred.succeed(readStarted, undefined).pipe( Effect.andThen(Deferred.await(releaseRead)), @@ -2066,15 +2140,20 @@ it.effect.each(["thread", "shell"] as const)( return Effect.succeed(statement); }; const subscription = Effect.gen(function* () { - const stream = - scope === "thread" - ? yield* subscribeOrchestrationV2Thread({ threadId, afterSequence: first!.sequence }) - : yield* subscribeOrchestrationV2Shell({ afterSequence: first!.sequence }); - return stream; + if (scope === "thread") { + return yield* subscribeOrchestrationV2Thread({ + threadId, + afterSequence: first!.sequence, + }).pipe(Effect.flatMap(Stream.runDrain)); + } + return yield* subscribeOrchestrationV2Shell({ afterSequence: first!.sequence }).pipe( + Effect.flatMap(Stream.runDrain), + ); }).pipe( Effect.provideService(Statement.CurrentTransformer, gateReplayRead), Effect.provideService(ThreadManagement.ThreadManagementService, { ensureLegacyTranscript: () => Effect.void, + streamStoredEventsFrom: () => Stream.empty, getThreadSnapshot: () => Effect.die("snapshot"), listActiveShellIndex: () => Effect.die("snapshot"), readShellSnapshot: () => Effect.die("snapshot"), diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 16a8d856ab7e9..a20216f8edc56 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -151,8 +151,6 @@ import { } from "./orchestration-v2/ThreadLiveEventCoalescer.ts"; import { buildBoundedThreadStreamSnapshot, - decideThreadResume, - isThreadReplayRawPayloadSafe, threadReplayEncodedBytes, THREAD_RESUME_MAX_REPLAY_EVENTS, } from "./orchestration-v2/ThreadStream.ts"; @@ -705,6 +703,9 @@ function projectFileFailureContext( } const PROVIDER_STATUS_DEBOUNCE_MS = 200; +// A replay page goes out as one RPC frame, and a client keeps only frames it +// fully received, so small pages keep progress across a dropping connection. +const THREAD_REPLAY_PAGE_BYTES = 32 * 1024; // Middleware added later wraps middleware added earlier, so instrumentation wraps authorization. const ServerWsRpcGroup = WsRpcGroup.middleware(RpcInstrumentation); @@ -943,13 +944,14 @@ export const subscribeOrchestrationV2Thread = Effect.fn("ws.orchestrationV2.subs ), ); - const loadReplayThrough = (afterSequence: number, throughSequence: number) => - applicationEvents + const loadReplayThrough = (afterSequence: number, throughSequence: number) => { + let encodedBytes = 0; + const replay = applicationEvents .readAgentEvents({ threadId: input.threadId, afterSequence, throughSequence, - limit: THREAD_RESUME_MAX_REPLAY_EVENTS + 1, + maxPageBytes: THREAD_REPLAY_PAGE_BYTES, // Downgrades can leave unknown rows; skip them and resume live from highWater so later events survive. skipUnknownEventTypes: true, }) @@ -959,17 +961,27 @@ export const subscribeOrchestrationV2Thread = Effect.fn("ws.orchestrationV2.subs sequence: stored.sequence, event: projectDomainEventForWire(stored.event), })), - Stream.runCollect, - Effect.map((items) => Array.from(items)), - Effect.mapError( - (cause) => - new OrchestrationV2GetThreadProjectionError({ - threadId: input.threadId, - message: `Failed while replaying orchestration V2 thread ${input.threadId}`, - cause, - }), - ), ); + return replay.pipe( + // Count delivered events rather than stored rows: a page of + // unknown future event types must not truncate the catch-up. + Stream.take(THREAD_RESUME_MAX_REPLAY_EVENTS), + Stream.takeUntil((item) => { + encodedBytes += threadReplayEncodedBytes([item]); + return encodedBytes >= THREAD_REPLAY_PAGE_BYTES; + }), + Stream.runCollect, + Effect.map((items) => Array.from(items)), + Effect.mapError( + (cause) => + new OrchestrationV2GetThreadProjectionError({ + threadId: input.threadId, + message: `Failed while replaying orchestration V2 thread ${input.threadId}`, + cause, + }), + ), + ); + }; const completionMarker = input.requestCompletionMarker === true @@ -1015,7 +1027,6 @@ export const subscribeOrchestrationV2Thread = Effect.fn("ws.orchestrationV2.subs return rpcInitialItems([snapshotItem]).pipe( Stream.concat(completionMarker), Stream.concat(eventStreamFrom(snapshotSequence)), - withLiveDedupe, ); }); @@ -1046,33 +1057,26 @@ export const subscribeOrchestrationV2Thread = Effect.fn("ws.orchestrationV2.subs input.afterSequence > highWater || (input.afterSequence < highWater && input.afterSequence < prunedThrough) ) { - return yield* snapshotThenLive(); + return withLiveDedupe(yield* snapshotThenLive()); } - const stats = yield* applicationEvents - .getAgentReplayStats({ + const hasCreateEvent = yield* applicationEvents + .hasAgentEvent({ threadId: input.threadId, afterSequence: input.afterSequence, throughSequence: highWater, - maxEvents: THREAD_RESUME_MAX_REPLAY_EVENTS, + eventType: "thread.created", }) .pipe( Effect.mapError( (cause) => new OrchestrationV2GetThreadProjectionError({ threadId: input.threadId, - message: `Failed to measure orchestration V2 thread ${input.threadId} replay`, + message: `Failed to check orchestration V2 thread ${input.threadId} creation`, cause, }), ), ); - // Bound stored and projected payload bytes separately; neither bounds process memory. - if ( - stats.eventCount > THREAD_RESUME_MAX_REPLAY_EVENTS || - !isThreadReplayRawPayloadSafe(stats.rawPayloadBytes) - ) { - return yield* snapshotThenLive(); - } - if (stats.hasCreateEvent) { + if (hasCreateEvent) { const shell = yield* threadManagement.getThreadShell(input.threadId).pipe( Effect.mapError( (cause) => @@ -1083,15 +1087,14 @@ export const subscribeOrchestrationV2Thread = Effect.fn("ws.orchestrationV2.subs }), ), ); - // Retained creation events may describe deleted threads; replace replay only if a snapshot exists. - if (shell !== null) return yield* snapshotThenLive(); + if (shell !== null) return withLiveDedupe(yield* snapshotThenLive()); } - const replayed = yield* loadReplayThrough(input.afterSequence, highWater); - // Pruning publishes its boundary before deleting, so a pass during the read shows up here. - if ( - input.afterSequence < highWater && - input.afterSequence < - (yield* applicationEvents.prunedThroughSequence.pipe( + // Fetch the next page only after the transport consumes this one. + const replay = Stream.paginate(input.afterSequence, (cursor) => + Effect.gen(function* () { + const items = yield* loadReplayThrough(cursor, highWater); + // Pruning publishes its boundary before deleting, so a pass during the read shows up here. + const prunedThrough = yield* applicationEvents.prunedThroughSequence.pipe( Effect.mapError( (cause) => new OrchestrationV2GetThreadProjectionError({ @@ -1100,28 +1103,28 @@ export const subscribeOrchestrationV2Thread = Effect.fn("ws.orchestrationV2.subs cause, }), ), - )) - ) { - return yield* snapshotThenLive(); - } - const replay = coalesceLiveUpdatedEvents(replayed); - const plan = decideThreadResume({ - afterSequence: input.afterSequence, - highWater, - replayEventCount: replay.length, - replayEncodedBytes: threadReplayEncodedBytes(replay), - }); - if (plan.mode === "snapshot") { - return yield* snapshotThenLive(); - } - return rpcInitialItems(replay).pipe( + ); + if (cursor < highWater && cursor < prunedThrough) { + return [[yield* snapshotThenLive()], Option.none()] as const; + } + const last = items.at(-1); + return [ + [rpcInitialItems(coalesceLiveUpdatedEvents(items))], + last === undefined || last.sequence >= highWater + ? Option.none() + : Option.some(last.sequence), + ] as const; + }), + ); + return replay.pipe( + Stream.flatMap((page) => page), Stream.concat(completionMarker), Stream.concat(eventStreamFrom(highWater)), withLiveDedupe, ); } - return yield* snapshotThenLive(); + return withLiveDedupe(yield* snapshotThenLive()); }, );