Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
234 changes: 234 additions & 0 deletions apps/server/src/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5975,6 +5975,240 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest), TestClock.withLive),
);

it.effect("subscribeThread bounds replay to the captured server head gap", () =>
Effect.gen(function* () {
const thread = makeDefaultOrchestrationReadModel().threads[0]!;
let readEventsCalls = 0;
let replayAfterSequence: number | undefined;
let replayLimit: number | undefined;

yield* buildAppUnderTest({
layers: {
orchestrationEngine: {
latestSequence: Effect.succeed(50),
readEvents: (afterSequence, limit) => {
readEventsCalls += 1;
replayAfterSequence = afterSequence;
replayLimit = limit;
return Stream.empty;
},
},
projectionSnapshotQuery: {
getThreadDetailSnapshot: () =>
Effect.succeed(Option.some({ snapshotSequence: 1, thread })),
},
},
});

const wsUrl = yield* getWsServerUrl("/ws");
const first = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[ORCHESTRATION_WS_METHODS.subscribeThread]({
threadId: defaultThreadId,
afterSequence: 7,
requestCompletionMarker: true,
}).pipe(Stream.runHead),
),
);

// The replay is bounded to the captured head gap (50 - 7 = 43), never
// Number.MAX_SAFE_INTEGER, and the empty-replay marker carries the head.
assert.equal(readEventsCalls, 1);
assert.equal(replayAfterSequence, 7);
assert.equal(replayLimit, 43);
assert.deepEqual(Option.getOrThrow(first), { kind: "synchronized", sequence: 50 });
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);

it.effect("subscribeThread replays only this thread's events from the bounded global range", () =>
Effect.gen(function* () {
const thread = makeDefaultOrchestrationReadModel().threads[0]!;
const otherThreadId = ThreadId.make("thread-other");
const now = "2026-01-01T00:00:00.000Z";
let scanned = 0;
let replayLimit: number | undefined;

const messageEvent = (sequence: number, threadId: ThreadId): OrchestrationEvent =>
({
sequence,
eventId: EventId.make(`event-${sequence}`),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: null,
causationEventId: null,
correlationId: null,
metadata: {},
type: "thread.message-sent",
payload: {
threadId,
messageId: MessageId.make(`message-${sequence}`),
role: "user",
text: `message ${sequence}`,
turnId: null,
streaming: false,
createdAt: now,
updatedAt: now,
},
}) satisfies OrchestrationEvent;

yield* buildAppUnderTest({
layers: {
orchestrationEngine: {
latestSequence: Effect.succeed(10),
readEvents: (_afterSequence, limit) => {
replayLimit = limit;
return Stream.fromIterable([
messageEvent(8, otherThreadId),
messageEvent(9, defaultThreadId),
messageEvent(10, otherThreadId),
]).pipe(Stream.tap(() => Effect.sync(() => (scanned += 1))));
},
},
projectionSnapshotQuery: {
getThreadDetailSnapshot: () =>
Effect.succeed(Option.some({ snapshotSequence: 1, thread })),
},
},
});

const wsUrl = yield* getWsServerUrl("/ws");
const items = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[ORCHESTRATION_WS_METHODS.subscribeThread]({
threadId: defaultThreadId,
afterSequence: 7,
requestCompletionMarker: true,
}).pipe(Stream.take(2), Stream.runCollect),
),
);

// The global store scans all 3 events in the bounded range, but only the
// matching thread's event is emitted before the synchronized marker.
assert.equal(scanned, 3);
assert.equal(replayLimit, 3);
assert.equal(items[0]?.kind, "event");
assert.equal(items[0]?.kind === "event" ? items[0].event.sequence : null, 9);
assert.deepEqual(items[1], { kind: "synchronized", sequence: 10 });
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);

it.effect("subscribeThread marks an empty catch-up replay as synchronized with the head", () =>
Effect.gen(function* () {
const thread = makeDefaultOrchestrationReadModel().threads[0]!;

yield* buildAppUnderTest({
layers: {
orchestrationEngine: {
latestSequence: Effect.succeed(12),
readEvents: () => Stream.empty,
},
projectionSnapshotQuery: {
getThreadDetailSnapshot: () =>
Effect.succeed(Option.some({ snapshotSequence: 1, thread })),
},
},
});

const wsUrl = yield* getWsServerUrl("/ws");
const first = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[ORCHESTRATION_WS_METHODS.subscribeThread]({
threadId: defaultThreadId,
afterSequence: 12,
requestCompletionMarker: true,
}).pipe(Stream.runHead),
),
);

// Empty replay (cursor already at the head) still emits the marker, and
// the marker carries the captured head so a quiet thread can advance.
assert.deepEqual(Option.getOrThrow(first), { kind: "synchronized", sequence: 12 });
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);

it.effect("subscribeThread sends a fresh snapshot instead of replaying a large gap", () =>
Effect.gen(function* () {
const thread = makeDefaultOrchestrationReadModel().threads[0]!;
let readEventsCalls = 0;

yield* buildAppUnderTest({
layers: {
orchestrationEngine: {
latestSequence: Effect.succeed(100_000),
readEvents: () =>
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),
),
);

// Large gap => fresh thread snapshot, and the unbounded replay is never
// started. The marker still carries the captured head.
assert.equal(items[0]?.kind, "snapshot");
assert.deepEqual(items[1], { kind: "synchronized", sequence: 100_000 });
assert.equal(readEventsCalls, 0);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);

it.effect("subscribeThread replaces a cursor ahead of the authoritative head", () =>
Effect.gen(function* () {
const thread = makeDefaultOrchestrationReadModel().threads[0]!;
let readEventsCalls = 0;

yield* buildAppUnderTest({
layers: {
orchestrationEngine: {
latestSequence: Effect.succeed(5),
readEvents: () =>
Stream.sync(() => {
readEventsCalls += 1;
return {} as OrchestrationEvent;
}),
},
projectionSnapshotQuery: {
getThreadDetailSnapshot: () =>
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: 10,
requestCompletionMarker: true,
}).pipe(Stream.take(2), Stream.runCollect),
),
);

// Cursor ahead of the head is invalid; reset with a fresh snapshot and
// never start the replay.
assert.equal(items[0]?.kind, "snapshot");
assert.deepEqual(items[1], { kind: "synchronized", sequence: 5 });
assert.equal(readEventsCalls, 0);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);

it.effect("subscribeShell sends a fresh snapshot instead of replaying a large gap", () =>
Effect.gen(function* () {
let readEventsCalls = 0;
Expand Down
104 changes: 84 additions & 20 deletions apps/server/src/ws.ts
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,15 @@ 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 as SHELL_RESUME_MAX_GAP, applied to per-thread resume replay. A
// resuming mobile client passes its last applied sequence; the global event
// store pages and decodes every event in the range before the per-thread filter
// runs, so an unbounded replay (the old Number.MAX_SAFE_INTEGER) re-scans the
// whole store on every foreground resubscribe. Bounding to the captured head
// gap keeps quiet threads from re-reading the same suffix forever, and a gap
// past this bound falls back to a single thread-detail snapshot.
const THREAD_RESUME_MAX_GAP = 1_000;

function toAuthAccessStreamEvent(
change: PairingGrantStore.BootstrapCredentialChange | SessionStore.SessionCredentialChange,
revision: number,
Expand Down Expand Up @@ -1263,33 +1272,88 @@ const makeWsRpcLayer = (
// catch-up followed by the buffered/ongoing live events. Overlapping
// events are deduped by sequence on the client.
//
// Read the full range after the cursor (not the store's default
// page-bounded limit): the range is normally tiny (a fresh HTTP
// snapshot sequence) and the per-thread filter runs after reading,
// so a global cap could otherwise omit this thread's events.
// Capture the authoritative server head *before* replay and bound
// the read to that head gap. The global store pages and decodes
// every event in the range before the per-thread filter runs, so an
// unbounded replay would re-scan the whole store on every
// resubscribe; the bound also keeps a moving event-store head from
// growing the live buffer indefinitely while waiting for an empty
// page. The captured head travels on the completion marker so a
// quiet thread (catch-up emits no thread events) can still advance
// its cursor and avoid re-reading the same suffix next time.
if (input.afterSequence !== undefined) {
const afterSequence = input.afterSequence;
const catchUpStream = orchestrationEngine
.readEvents(afterSequence, Number.MAX_SAFE_INTEGER)
.pipe(
Stream.filter(isThisThreadDetailEvent),
Stream.map((event) => ({
kind: "event" as const,
event: projectActivityEvent(event),
})),
Stream.mapError(
(cause) =>
new OrchestrationGetSnapshotError({
message: `Failed to replay thread ${input.threadId} events`,
cause,
}),
),
const headSequence = yield* orchestrationEngine.latestSequence;
const replayGap = headSequence - afterSequence;

// Cursor ahead of the authoritative head, or gap too large to
// replay per-event: send a fresh thread detail snapshot (the
// same path as no-afterSequence) followed by the buffered live
// tail. The snapshot's snapshotSequence becomes the new cursor;
// the marker still carries the captured head for uniformity.
if (replayGap < 0 || replayGap > THREAD_RESUME_MAX_GAP) {
const snapshot = yield* projectionSnapshotQuery
.getThreadDetailSnapshot(input.threadId)
.pipe(
Effect.mapError(
(cause) =>
new OrchestrationGetSnapshotError({
message: `Failed to load thread ${input.threadId}`,
cause,
}),
),
);

if (Option.isNone(snapshot)) {
return yield* new OrchestrationGetSnapshotError({
message: `Thread ${input.threadId} was not found`,
cause: input.threadId,
});
}

const afterSnapshot =
input.requestCompletionMarker === true
? Stream.concat(
Stream.fromEffect(
Queue.offer(liveBuffer, {
kind: "synchronized" as const,
sequence: headSequence,
}),
).pipe(Stream.drain),
bufferedLiveStream,
)
: bufferedLiveStream;
return Stream.concat(
Stream.make({
kind: "snapshot" as const,
snapshot: projectThreadDetailSnapshot(snapshot.value),
}),
afterSnapshot,
);
}

const catchUpStream = orchestrationEngine.readEvents(afterSequence, replayGap).pipe(
Stream.filter(isThisThreadDetailEvent),
Stream.map((event) => ({
kind: "event" as const,
event: projectActivityEvent(event),
})),
Stream.mapError(
(cause) =>
new OrchestrationGetSnapshotError({
message: `Failed to replay thread ${input.threadId} events`,
cause,
}),
),
);
const afterCatchUp =
input.requestCompletionMarker === true
? Stream.concat(
Stream.fromEffect(
Queue.offer(liveBuffer, { kind: "synchronized" as const }),
Queue.offer(liveBuffer, {
kind: "synchronized" as const,
sequence: headSequence,
}),
).pipe(Stream.drain),
bufferedLiveStream,
)
Expand Down
Loading
Loading