Skip to content
TypeScript

fix(server): bound slow-client event buffers (#9715)

Theo Browne108f295cc367
diff --git a/apps/server/src/orchestration/LiveStreamBudget.test.ts b/apps/server/src/orchestration/LiveStreamBudget.test.ts
new file mode 100644
index 00000000000..d163a8317fc
--- /dev/null
+++ b/apps/server/src/orchestration/LiveStreamBudget.test.ts
@@ -0,0 +1,47 @@
+import { it } from "@effect/vitest";
+import * as Deferred from "effect/Deferred";
+import * as Effect from "effect/Effect";
+import * as Queue from "effect/Queue";
+import * as Stream from "effect/Stream";
+import { describe, expect } from "vite-plus/test";
+
+import { makeLiveStreamBudget, type RetainedLiveItem } from "./LiveStreamBudget.ts";
+
+describe("LiveStreamBudget", () => {
+ it.effect("closes the source without releasing a batch still waiting for an ACK", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const budget = yield* makeLiveStreamBudget({ maxItems: 3 });
+ const queue = yield* Queue.unbounded<RetainedLiveItem<{ text: string }>>();
+ const sourceClosed = yield* Deferred.make<void>();
+ const first = yield* budget.retain({ text: "first" });
+ const second = yield* budget.retain({ text: "second" });
+ const third = yield* budget.retain({ text: "third" });
+ yield* Queue.offerAll(queue, [first, second, third]);
+ yield* Effect.scoped(
+ Effect.gen(function* () {
+ const pull = yield* Stream.toPull(
+ budget.deliver(
+ Stream.fromQueue(queue).pipe(
+ Stream.rechunk(1),
+ Stream.ensuring(Deferred.succeed(sourceClosed, undefined)),
+ ),
+ ),
+ );
+ expect(yield* pull).toEqual([{ text: "first" }]);
+ // The other two items are in the source's pull state, not its queue.
+ expect(yield* Queue.size(queue)).toBe(0);
+ expect((yield* budget.usage).retainedItems).toBe(3);
+ const overflow = yield* budget.retain({ text: "fourth" }).pipe(Effect.result);
+ expect(overflow._tag).toBe("Failure");
+ // Do not resume the consumer. Its source scope must close now.
+ yield* Deferred.await(sourceClosed);
+ yield* budget.closed;
+ expect((yield* budget.usage).retainedItems).toBe(1);
+ }),
+ );
+ expect(yield* budget.usage).toEqual({ retainedItems: 0, retainedSerializedBytes: 0 });
+ }),
+ ),
+ );
+});
diff --git a/apps/server/src/orchestration/LiveStreamBudget.ts b/apps/server/src/orchestration/LiveStreamBudget.ts
new file mode 100644
index 00000000000..3e3d3112859
--- /dev/null
+++ b/apps/server/src/orchestration/LiveStreamBudget.ts
@@ -0,0 +1,196 @@
+import { OrchestrationGetSnapshotError } from "@t3tools/contracts";
+import * as Arr from "effect/Array";
+import * as Deferred from "effect/Deferred";
+import * as Effect from "effect/Effect";
+import * as Exit from "effect/Exit";
+import * as Scope from "effect/Scope";
+import * as Stream from "effect/Stream";
+
+export const LIVE_STREAM_MAX_ITEMS = 1_000;
+export const LIVE_STREAM_MAX_SERIALIZED_BYTES = 8 * 1024 * 1024;
+
+export interface RetainedLiveItem<A> {
+ readonly value: A;
+ readonly serializedBytes: number;
+}
+
+// Published events are immutable and shared across subscriptions. Measure each
+// object once without keeping the event or its serialized copy alive.
+const serializedSizes = new WeakMap<object, number>();
+
+function serializedSize(value: object): number {
+ const cached = serializedSizes.get(value);
+ if (cached !== undefined) {
+ return cached;
+ }
+ const bytes = Buffer.byteLength(JSON.stringify(value));
+ serializedSizes.set(value, bytes);
+ return bytes;
+}
+
+/** One budget covers one subscription and its delivery stream, including the batch waiting for an RPC ACK. */
+export const makeLiveStreamBudget = Effect.fn("makeLiveStreamBudget")(function* (limits?: {
+ readonly maxItems?: number;
+ readonly maxSerializedBytes?: number;
+}) {
+ const maxItems = limits?.maxItems ?? LIVE_STREAM_MAX_ITEMS;
+ const maxSerializedBytes = limits?.maxSerializedBytes ?? LIVE_STREAM_MAX_SERIALIZED_BYTES;
+ const failed = yield* Deferred.make<never, OrchestrationGetSnapshotError>();
+ const cleanupComplete = yield* Deferred.make<void>();
+ let failure: OrchestrationGetSnapshotError | undefined;
+ const retained = new Set<RetainedLiveItem<unknown>>();
+ let retainedSerializedBytes = 0;
+
+ const release = (items: Iterable<RetainedLiveItem<unknown>>) => {
+ for (const item of items) {
+ if (!retained.delete(item)) {
+ continue;
+ }
+ retainedSerializedBytes -= item.serializedBytes;
+ }
+ };
+ yield* Effect.addFinalizer(() =>
+ Effect.sync(() => release(retained)).pipe(
+ Effect.andThen(Deferred.succeed(cleanupComplete, undefined)),
+ ),
+ );
+
+ const check = Effect.suspend(() => (failure ? Effect.fail(failure) : Effect.void));
+
+ const overflow = Effect.fn("LiveStreamBudget.overflow")(function* (
+ nextItems: number,
+ nextSerializedBytes: number,
+ ) {
+ failure ??= new OrchestrationGetSnapshotError({
+ message: "The live event buffer is full. Resume from the last received sequence.",
+ });
+ yield* Deferred.fail(failed, failure);
+ yield* Effect.logWarning("orchestration live event buffer is full", {
+ retainedItems: retained.size,
+ retainedSerializedBytes,
+ nextItems,
+ nextSerializedBytes,
+ maxItems,
+ maxSerializedBytes,
+ });
+ return yield* failure;
+ });
+
+ const retain = <A extends object>(value: A, payload: object = value) =>
+ Effect.suspend(() => {
+ if (failure) {
+ return Effect.fail(failure);
+ }
+ const serializedBytes = serializedSize(payload);
+ const nextItems = retained.size + 1;
+ const nextSerializedBytes = retainedSerializedBytes + serializedBytes;
+ if (nextItems > maxItems || nextSerializedBytes > maxSerializedBytes) {
+ return overflow(nextItems, nextSerializedBytes);
+ }
+ const item = { value, serializedBytes };
+ retained.add(item);
+ retainedSerializedBytes = nextSerializedBytes;
+ return Effect.succeed(item);
+ });
+
+ // Replace one coalescing batch atomically. Both raw and projected payloads
+ // count against the same budget, and discarded updates release their charge.
+ const replace = <A extends object>(
+ previous: ReadonlyArray<RetainedLiveItem<unknown>>,
+ values: ReadonlyArray<A>,
+ payload: (value: A) => object = (value) => value,
+ ) =>
+ Effect.suspend(() => {
+ if (failure) {
+ return Effect.fail(failure);
+ }
+ const next = values.map((value) => ({
+ value,
+ serializedBytes: serializedSize(payload(value)),
+ }));
+ let nextItems = retained.size + next.length;
+ let nextSerializedBytes =
+ retainedSerializedBytes + next.reduce((sum, item) => sum + item.serializedBytes, 0);
+ for (const item of previous) {
+ if (retained.has(item)) {
+ nextItems -= 1;
+ nextSerializedBytes -= item.serializedBytes;
+ }
+ }
+ if (nextItems > maxItems || nextSerializedBytes > maxSerializedBytes) {
+ return overflow(nextItems, nextSerializedBytes);
+ }
+ release(previous);
+ for (const item of next) {
+ retained.add(item);
+ }
+ retainedSerializedBytes = nextSerializedBytes;
+ return Effect.succeed(next);
+ });
+
+ const deliver = <A, E, R>(stream: Stream.Stream<RetainedLiveItem<A>, E, R>) =>
+ Stream.fromPull(
+ Effect.gen(function* () {
+ yield* check;
+ const sourceScope = yield* Scope.fork(yield* Effect.scope);
+ const source = {
+ pull: yield* Stream.toPull(stream).pipe(Scope.provide(sourceScope)),
+ };
+ let inFlight: ReadonlyArray<RetainedLiveItem<A>> = [];
+ yield* Effect.addFinalizer(() =>
+ Effect.sync(() => {
+ release(inFlight);
+ inFlight = [];
+ source.pull = Effect.interrupt;
+ }),
+ );
+ yield* Deferred.await(failed).pipe(
+ Effect.catchTags({
+ OrchestrationGetSnapshotError: (error) =>
+ Effect.sync(() => {
+ // A grouped source can retain its own pending chunk. Close it
+ // and release the pull closure without waiting for an RPC ACK.
+ source.pull = Effect.interrupt;
+ }).pipe(
+ Effect.andThen(Scope.close(sourceScope, Exit.fail(error))),
+ Effect.andThen(
+ Effect.sync(() => {
+ const delivered = new Set<RetainedLiveItem<unknown>>(inFlight);
+ for (const item of retained) {
+ if (!delivered.has(item)) {
+ release([item]);
+ }
+ }
+ }),
+ ),
+ Effect.andThen(Deferred.succeed(cleanupComplete, undefined)),
+ ),
+ }),
+ Effect.forkScoped,
+ );
+ // @effect-diagnostics-next-line returnEffectInGen:off - Stream.fromPull needs the pull effect as its result.
+ return Effect.gen(function* () {
+ // RpcServer requests the next batch only after the client ACKs this
+ // one. Removing items from a queue alone does not mean delivery ended.
+ release(inFlight);
+ inFlight = [];
+ yield* check;
+ const items = yield* Effect.raceFirst(source.pull, Deferred.await(failed));
+ inFlight = items;
+ yield* check;
+ return Arr.map(items, (item) => item.value);
+ });
+ }),
+ );
+
+ return {
+ retain,
+ replace,
+ release,
+ deliver,
+ check,
+ failed: Deferred.await(failed),
+ closed: Deferred.await(cleanupComplete),
+ usage: Effect.sync(() => ({ retainedItems: retained.size, retainedSerializedBytes })),
+ };
+});
diff --git a/apps/server/src/orchestration/ThreadLiveEventCoalescer.test.ts b/apps/server/src/orchestration/ThreadLiveEventCoalescer.test.ts
index 0a9915294d0..440356ef933 100644
--- a/apps/server/src/orchestration/ThreadLiveEventCoalescer.test.ts
+++ b/apps/server/src/orchestration/ThreadLiveEventCoalescer.test.ts
@@ -3,12 +3,14 @@ import {
MessageId,
ThreadId,
TurnId,
- type OrchestrationEvent,
+ OrchestrationEvent,
type OrchestrationThreadActivity,
} from "@t3tools/contracts";
import { it } from "@effect/vitest";
import * as Clock from "effect/Clock";
import * as Effect from "effect/Effect";
+import * as Schema from "effect/Schema";
+import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
import { describe, expect } from "vite-plus/test";
@@ -19,6 +21,7 @@ import {
const threadId = ThreadId.make("thread-coalescer-test");
const turnId = TurnId.make("turn-coalescer-test");
+const encodeEvent = Schema.encodeSync(Schema.fromJsonString(OrchestrationEvent));
function makeToolActivity(
sequence: number,
@@ -61,7 +64,7 @@ function makeToolActivity(
};
}
-function makeMessage(sequence: number): OrchestrationEvent {
+function makeMessage(sequence: number, text = "Still working"): OrchestrationEvent {
return {
sequence,
eventId: EventId.make(`event-${sequence}`),
@@ -77,7 +80,7 @@ function makeMessage(sequence: number): OrchestrationEvent {
threadId,
messageId: MessageId.make(`message-${sequence}`),
role: "assistant",
- text: "Still working",
+ text,
turnId,
streaming: false,
createdAt: "2026-01-01T00:00:02.000Z",
@@ -134,15 +137,14 @@ describe("ThreadLiveEventCoalescer", () => {
const startedAt = yield* Clock.currentTimeMillis;
yield* Effect.forEach(
Array.from({ length: 10 }, (_, index) => index + 2),
- (sequence) =>
- coalescer.offerAndWait({ kind: "event", event: makeToolActivity(sequence) }),
+ (sequence) => coalescer.offer({ kind: "event", event: makeToolActivity(sequence) }),
{ discard: true },
);
- yield* coalescer.offerAndWait({ kind: "event", event: makeMessage(12) });
+ yield* coalescer.offer({ kind: "event", event: makeMessage(12) });
expect(yield* Clock.currentTimeMillis).toBe(startedAt);
expect(
- Array.from(yield* coalescer.takeAll).map((item) =>
+ (yield* coalescer.stream.pipe(Stream.take(2), Stream.runCollect)).map((item) =>
item.kind === "event" ? item.event.sequence : item.kind,
),
).toEqual([11, 12]);
@@ -155,17 +157,94 @@ describe("ThreadLiveEventCoalescer", () => {
Effect.gen(function* () {
const coalescer = yield* makeThreadLiveEventCoalescer({ coalesceWindow: "500 millis" });
const startedAt = yield* Clock.currentTimeMillis;
- yield* coalescer.offerAndWait({ kind: "event", event: makeToolActivity(2) });
- yield* coalescer.offerAndWait({ kind: "event", event: makeToolActivity(3) });
- yield* coalescer.offerAndWait({ kind: "synchronized" });
+ yield* coalescer.offer({ kind: "event", event: makeToolActivity(2) });
+ yield* coalescer.offer({ kind: "event", event: makeToolActivity(3) });
+ yield* coalescer.offer({ kind: "synchronized" });
expect(yield* Clock.currentTimeMillis).toBe(startedAt);
expect(
- Array.from(yield* coalescer.takeAll).map((item) =>
+ (yield* coalescer.stream.pipe(Stream.take(2), Stream.runCollect)).map((item) =>
item.kind === "event" ? item.event.sequence : item.kind,
),
).toEqual([3, "synchronized"]);
}),
).pipe(Effect.provide(TestClock.layer())),
);
+
+ it.effect("fails and clears pending updates when their serialized payload fills the budget", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const first = makeToolActivity(1);
+ const coalescer = yield* makeThreadLiveEventCoalescer({
+ coalesceWindow: "500 millis",
+ maxSerializedBytes: Buffer.byteLength(encodeEvent(first)),
+ });
+ yield* coalescer.offer({ kind: "event", event: first });
+ expect(yield* coalescer.usage).toEqual({
+ retainedItems: 1,
+ retainedSerializedBytes: Buffer.byteLength(encodeEvent(first)),
+ });
+
+ const overflow = yield* coalescer
+ .offer({ kind: "event", event: makeToolActivity(2) })
+ .pipe(Effect.result);
+ expect(overflow._tag).toBe("Failure");
+ yield* coalescer.closed;
+ expect(yield* coalescer.usage).toEqual({ retainedItems: 0, retainedSerializedBytes: 0 });
+ const marker = yield* coalescer.offer({ kind: "synchronized" }).pipe(Effect.result);
+ expect(marker._tag).toBe("Failure");
+ const delivered = yield* coalescer.stream.pipe(Stream.runCollect, Effect.result);
+ expect(delivered._tag).toBe("Failure");
+ }),
+ ),
+ );
+
+ it.effect("keeps the flush timer alive when an offer's shorter scope closes", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const coalescer = yield* makeThreadLiveEventCoalescer({ coalesceWindow: "50 millis" });
+ yield* Effect.scoped(coalescer.offer({ kind: "event", event: makeToolActivity(1) }));
+ yield* TestClock.adjust("50 millis");
+ const items = yield* coalescer.stream.pipe(Stream.take(1), Stream.runCollect);
+ expect(
+ items.map((item) => (item.kind === "event" ? item.event.sequence : item.kind)),
+ ).toEqual([1]);
+ }),
+ ),
+ );
+
+ it.effect("keeps an unacknowledged batch charged and clears later events on overflow", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const coalescer = yield* makeThreadLiveEventCoalescer({ maxItems: 3 });
+ const first = makeMessage(1, "é".repeat(1_024));
+ yield* coalescer.offer({ kind: "event", event: first });
+
+ yield* Effect.scoped(
+ Effect.gen(function* () {
+ const pull = yield* Stream.toPull(coalescer.stream);
+ const batch = yield* pull;
+ expect(
+ batch.map((item) => (item.kind === "event" ? item.event.sequence : null)),
+ ).toEqual([1]);
+ yield* coalescer.offer({ kind: "event", event: makeMessage(2) });
+ yield* coalescer.offer({ kind: "event", event: makeToolActivity(3) });
+ expect((yield* coalescer.usage).retainedItems).toBe(3);
+
+ const overflow = yield* coalescer
+ .offer({ kind: "event", event: makeToolActivity(4, { kind: "tool.completed" }) })
+ .pipe(Effect.result);
+ expect(overflow._tag).toBe("Failure");
+ // Do not pull or acknowledge the batch. Cleanup must still finish.
+ yield* coalescer.closed;
+ expect(yield* coalescer.usage).toEqual({
+ retainedItems: 1,
+ retainedSerializedBytes: Buffer.byteLength(encodeEvent(first)),
+ });
+ }),
+ );
+ expect(yield* coalescer.usage).toEqual({ retainedItems: 0, retainedSerializedBytes: 0 });
+ }),
+ ),
+ );
});
diff --git a/apps/server/src/orchestration/ThreadLiveEventCoalescer.ts b/apps/server/src/orchestration/ThreadLiveEventCoalescer.ts
index 8271f6a550f..c7f2155b4b3 100644
--- a/apps/server/src/orchestration/ThreadLiveEventCoalescer.ts
+++ b/apps/server/src/orchestration/ThreadLiveEventCoalescer.ts
@@ -1,4 +1,8 @@
-import type { OrchestrationEvent, OrchestrationThreadStreamItem } from "@t3tools/contracts";
+import type {
+ OrchestrationEvent,
+ OrchestrationGetSnapshotError,
+ OrchestrationThreadStreamItem,
+} from "@t3tools/contracts";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
@@ -9,6 +13,7 @@ import * as Semaphore from "effect/Semaphore";
import * as Stream from "effect/Stream";
import { projectActivityEvent } from "./ActivityPayloadProjection.ts";
+import { makeLiveStreamBudget, type RetainedLiveItem } from "./LiveStreamBudget.ts";
const COALESCE_WINDOW = Duration.millis(50);
const MAX_PENDING_UPDATES = 512;
@@ -89,17 +94,24 @@ export function coalesceLiveToolUpdatedEvents(
}
export const makeThreadLiveEventCoalescer = Effect.fn("makeThreadLiveEventCoalescer")(
- function* (options?: { readonly coalesceWindow?: Duration.Input }) {
- const output = yield* Queue.unbounded<OrchestrationThreadStreamItem>();
- const input = yield* Queue.unbounded<{
- readonly value: ThreadLiveInput;
- readonly processed?: Deferred.Deferred<void>;
- }>();
+ function* (options?: {
+ readonly coalesceWindow?: Duration.Input;
+ readonly maxItems?: number;
+ readonly maxSerializedBytes?: number;
+ }) {
+ const coalescerScope = yield* Effect.scope;
+ const budget = yield* makeLiveStreamBudget(options);
+ const cleanupComplete = yield* Deferred.make<void>();
+ const output = yield* Queue.unbounded<
+ RetainedLiveItem<OrchestrationThreadStreamItem>,
+ OrchestrationGetSnapshotError
+ >();
const mutex = yield* Semaphore.make(1);
const coalesceWindow = options?.coalesceWindow ?? COALESCE_WINDOW;
- let pendingUpdates: Array<OrchestrationEvent> = [];
+ let pendingUpdates: Array<RetainedLiveItem<OrchestrationEvent>> = [];
let windowGeneration = 0;
let windowFiber: Fiber.Fiber<void, never> | null = null;
+ let closed = false;
const cancelWindow = Effect.fn("ThreadLiveEventCoalescer.cancelWindow")(function* () {
const fiber = windowFiber;
@@ -110,22 +122,21 @@ export const makeThreadLiveEventCoalescer = Effect.fn("makeThreadLiveEventCoales
yield* Fiber.interrupt(fiber);
});
- const flushPending = Effect.fn("ThreadLiveEventCoalescer.flushPending")(function* (
- boundary?: OrchestrationEvent,
- ) {
- const events = boundary ? [...pendingUpdates, boundary] : pendingUpdates;
- pendingUpdates = [];
- if (events.length === 0) {
+ const flushPending = Effect.fn("ThreadLiveEventCoalescer.flushPending")(function* () {
+ if (pendingUpdates.length === 0) {
return;
}
- yield* Queue.offerAll(
- output,
- coalesceLiveToolUpdatedEvents(events).map((event) => ({
+ const items = yield* budget.replace(
+ pendingUpdates,
+ coalesceLiveToolUpdatedEvents(pendingUpdates.map((item) => item.value)).map((event) => ({
kind: "event" as const,
event: projectActivityEvent(event),
})),
+ (item) => item.event,
);
- });
+ pendingUpdates = [];
+ yield* Queue.offerAll(output, items);
+ }, Effect.uninterruptible);
const flushWindow = (generation: number) =>
Effect.sleep(coalesceWindow).pipe(
@@ -141,67 +152,89 @@ export const makeThreadLiveEventCoalescer = Effect.fn("makeThreadLiveEventCoales
}
}),
),
+ Effect.catchTags({ OrchestrationGetSnapshotError: () => Effect.void }),
);
- const process = Effect.fn("ThreadLiveEventCoalescer.process")(function* (
- input: ThreadLiveInput,
+ // Keep each source batch together so a synchronization marker cannot pass
+ // events already pulled from PubSub but still being coalesced.
+ const offerAll = Effect.fn("ThreadLiveEventCoalescer.offerAll")(function* (
+ inputs: ReadonlyArray<ThreadLiveInput>,
) {
yield* mutex.withPermits(1)(
- Effect.gen(function* () {
- if (input.kind === "event" && isToolUpdated(input.event)) {
- pendingUpdates.push(input.event);
- if (pendingUpdates.length === 1) {
- const generation = ++windowGeneration;
- windowFiber = yield* Effect.forkScoped(flushWindow(generation));
- }
- if (pendingUpdates.length >= MAX_PENDING_UPDATES) {
+ Effect.forEach(
+ inputs,
+ (input) =>
+ Effect.gen(function* () {
+ yield* budget.check;
+ if (input.kind === "event") {
+ yield* budget.retain(input.event).pipe(
+ Effect.tap((item) => Effect.sync(() => pendingUpdates.push(item))),
+ Effect.uninterruptible,
+ );
+ }
+ if (input.kind === "event" && isToolUpdated(input.event)) {
+ if (pendingUpdates.length === 1) {
+ const generation = ++windowGeneration;
+ windowFiber = yield* Effect.forkIn(flushWindow(generation), coalescerScope);
+ }
+ if (pendingUpdates.length >= MAX_PENDING_UPDATES) {
+ yield* cancelWindow();
+ windowGeneration += 1;
+ yield* flushPending();
+ }
+ return;
+ }
+
yield* cancelWindow();
windowGeneration += 1;
+ // A non-update event closes the run immediately. The coalescer keeps
+ // that boundary after the final update from the run.
yield* flushPending();
- }
+ if (input.kind === "synchronized") {
+ yield* budget.retain({ kind: "synchronized" as const }).pipe(
+ Effect.flatMap((marker) => Queue.offer(output, marker)),
+ Effect.uninterruptible,
+ );
+ }
+ }),
+ { discard: true },
+ ),
+ );
+ });
+
+ const close = (error?: OrchestrationGetSnapshotError) =>
+ mutex.withPermits(1)(
+ Effect.gen(function* () {
+ if (closed) {
return;
}
-
- yield* cancelWindow();
+ closed = true;
windowGeneration += 1;
- // A non-update event closes the run immediately. The coalescer keeps
- // that boundary after the final update from the run.
- if (input.kind === "event") {
- yield* flushPending(input.event);
- } else {
- yield* flushPending();
- yield* Queue.offer(output, { kind: "synchronized" });
+ yield* cancelWindow();
+ budget.release(pendingUpdates);
+ pendingUpdates = [];
+ budget.release(yield* Queue.clear(output).pipe(Effect.orDie));
+ if (error) {
+ yield* Queue.fail(output, error);
}
+ yield* Queue.shutdown(output);
+ yield* Deferred.succeed(cleanupComplete, undefined);
}),
);
- });
- yield* Stream.fromQueue(input).pipe(
- Stream.runForEach(({ value, processed }) =>
- process(value).pipe(
- Effect.andThen(processed ? Deferred.succeed(processed, undefined) : Effect.void),
- ),
- ),
+ yield* Effect.addFinalizer(() => close());
+ yield* budget.failed.pipe(
+ Effect.catchTags({ OrchestrationGetSnapshotError: close }),
Effect.forkScoped,
);
- const offer = (value: ThreadLiveInput) => Queue.offer(input, { value }).pipe(Effect.asVoid);
-
- // Synchronization callers wait for their marker to pass through the same
- // ordered input queue before draining output produced ahead of it.
- const offerAndWait = Effect.fn("ThreadLiveEventCoalescer.offerAndWait")(function* (
- value: ThreadLiveInput,
- ) {
- const processed = yield* Deferred.make<void>();
- yield* Queue.offer(input, { value, processed });
- yield* Deferred.await(processed);
- });
-
return {
- offer,
- offerAndWait,
- stream: Stream.fromQueue(output),
- takeAll: Queue.takeAll(output),
+ offer: (input: ThreadLiveInput) => offerAll([input]),
+ offerAll,
+ stream: budget.deliver(Stream.fromQueue(output)),
+ failed: budget.failed,
+ closed: Deferred.await(cleanupComplete),
+ usage: budget.usage,
} as const;
},
);
diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts
index aeec8329ea3..ce11f516b65 100644
--- a/apps/server/src/server.test.ts
+++ b/apps/server/src/server.test.ts
@@ -1194,6 +1194,32 @@ const withWsRpcClient = <A, E, R>(
onMessage?: (message: string) => void,
) => makeWsRpcClient.pipe(Effect.flatMap(f), Effect.provide(wsRpcProtocolLayer(wsUrl, onMessage)));
+const withFirstWsAckHeld = (
+ wsUrl: string,
+ held: Deferred.Deferred<void>,
+ release: Deferred.Deferred<void>,
+) => {
+ let holdNextAck = true;
+ return Layer.effect(RpcClient.Protocol)(
+ Effect.map(RpcClient.Protocol, (protocol) =>
+ RpcClient.Protocol.of({
+ ...protocol,
+ send: (clientId, request, transferables) => {
+ const send = protocol.send(clientId, request, transferables);
+ if (request._tag !== "Ack" || !holdNextAck) {
+ return send;
+ }
+ holdNextAck = false;
+ return Deferred.succeed(held, undefined).pipe(
+ Effect.andThen(Deferred.await(release)),
+ Effect.andThen(send),
+ );
+ },
+ }),
+ ),
+ ).pipe(Layer.provide(wsRpcProtocolLayer(wsUrl)));
+};
+
const appendSessionCookieToWsUrl = (url: string, sessionCookieHeader: string) => {
const isAbsoluteUrl = /^[a-zA-Z][a-zA-Z\d+.-]*:/.test(url);
const next = new URL(url, "http://localhost");
@@ -8067,6 +8093,273 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
+ it.effect(
+ "stops an overflowing thread producer without an ACK and replays the missing events",
+ () =>
+ Effect.gen(function* () {
+ const liveEvents = yield* PubSub.unbounded<OrchestrationEvent>();
+ const attached = yield* Deferred.make<void>();
+ const detached = yield* Deferred.make<void>();
+ const ackHeld = yield* Deferred.make<void>();
+ 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 }> = [];
+ let headSequence = 0;
+ let snapshotCalls = 0;
+ const message = (sequence: number, text: string) =>
+ ({
+ sequence,
+ eventId: EventId.make(`slow-thread-${sequence}`),
+ aggregateKind: "thread",
+ aggregateId: defaultThreadId,
+ occurredAt: "2026-01-01T00:00:01.000Z",
+ commandId: null,
+ causationEventId: null,
+ correlationId: null,
+ metadata: {},
+ type: "thread.message-sent",
+ payload: {
+ threadId: defaultThreadId,
+ messageId: MessageId.make(`slow-message-${sequence}`),
+ role: "assistant",
+ text,
+ turnId: TurnId.make("turn-edit"),
+ streaming: false,
+ createdAt: "2026-01-01T00:00:01.000Z",
+ updatedAt: "2026-01-01T00:00:01.000Z",
+ },
+ }) satisfies OrchestrationEvent;
+ const events = [
+ message(1, "a".repeat(4 * 1024 * 1024)),
+ message(2, "b".repeat(4 * 1024 * 1024)),
+ makeLiveToolActivityEvent(3, "tool.completed"),
+ message(4, "Finished"),
+ ] as const;
+
+ yield* buildAppUnderTest({
+ layers: {
+ orchestrationEngine: {
+ latestSequence: Effect.sync(() => headSequence),
+ streamDomainEvents: Stream.unwrap(
+ Effect.gen(function* () {
+ const subscription = yield* PubSub.subscribe(liveEvents);
+ yield* Deferred.succeed(attached, undefined);
+ return Stream.fromSubscription(subscription);
+ }),
+ ).pipe(Stream.ensuring(Deferred.succeed(detached, undefined))),
+ readEvents: (afterSequence, limit) => {
+ replayCalls.push({ afterSequence, limit });
+ const range = events.filter(
+ (event) => event.sequence > afterSequence && event.sequence <= headSequence,
+ );
+ 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 }) => {
+ const range = events.filter(
+ (event) =>
+ event.sequence > fromSequenceExclusive && event.sequence <= toSequenceInclusive,
+ );
+ return Effect.succeed({
+ eventCount: range.length,
+ payloadBytes: range.reduce(
+ (bytes, event) => bytes + Buffer.byteLength(jsonRequestBody(event.payload)),
+ 0,
+ ),
+ });
+ },
+ },
+ },
+ });
+
+ const wsUrl = yield* getWsServerUrl("/ws");
+ yield* makeWsRpcClient.pipe(
+ Effect.flatMap((client) =>
+ Effect.gen(function* () {
+ let cursor = 0;
+ const received: number[] = [];
+ const attempt = yield* client[ORCHESTRATION_WS_METHODS.subscribeThread]({
+ threadId: defaultThreadId,
+ afterSequence: cursor,
+ }).pipe(
+ Stream.tap((item) => {
+ if (item.kind !== "event") return Effect.void;
+ cursor = item.event.sequence;
+ received.push(cursor);
+ return Deferred.succeed(firstApplied, undefined);
+ }),
+ Stream.runDrain,
+ Effect.result,
+ Effect.forkScoped,
+ );
+ yield* Deferred.await(attached);
+ yield* Deferred.await(replayStarted);
+ headSequence = 1;
+ yield* PubSub.publish(liveEvents, events[0]!);
+ yield* Deferred.await(ackHeld);
+ yield* Deferred.await(firstApplied);
+ headSequence = 4;
+ yield* PubSub.publishAll(liveEvents, events.slice(1));
+
+ // This must finish while the server is still waiting for the first
+ // batch's ACK. A failed output queue alone would leave PubSub live.
+ yield* Deferred.await(detached);
+ assert.equal(yield* PubSub.size(liveEvents), 0);
+ assert.deepEqual(received, [1]);
+ yield* Deferred.succeed(releaseAck, undefined);
+ const result = yield* Fiber.join(attempt);
+ assertTrue(result._tag === "Failure");
+ assert.equal(result.failure._tag, "OrchestrationGetSnapshotError");
+
+ const recovered = yield* client[ORCHESTRATION_WS_METHODS.subscribeThread]({
+ threadId: defaultThreadId,
+ afterSequence: cursor,
+ requestCompletionMarker: true,
+ }).pipe(
+ Stream.takeUntil((item) => item.kind === "synchronized"),
+ Stream.runCollect,
+ );
+ assert.deepEqual(
+ recovered.map((item) => (item.kind === "event" ? item.event.sequence : item.kind)),
+ [2, 3, 4, "synchronized"],
+ );
+ const first = recovered[0];
+ assertTrue(first?.kind === "event" && first.event.type === "thread.message-sent");
+ assert.equal(first.event.payload.text, events[1]!.payload.text);
+ const completed = recovered[1];
+ assertTrue(
+ completed?.kind === "event" && completed.event.type === "thread.activity-appended",
+ );
+ assert.equal(completed.event.payload.activity.kind, "tool.completed");
+ assert.deepEqual(replayCalls, [
+ { afterSequence: 0, limit: 0 },
+ { afterSequence: 1, limit: 3 },
+ ]);
+ assert.equal(snapshotCalls, 0);
+ }),
+ ),
+ Effect.provide(withFirstWsAckHeld(wsUrl, ackHeld, releaseAck)),
+ );
+ }).pipe(Effect.scoped, Effect.provide(NodeHttpServer.layerTest)),
+ );
+
+ it.effect("stops an overflowing shell producer without an ACK and recovers deleted entries", () =>
+ Effect.gen(function* () {
+ const liveEvents = yield* PubSub.unbounded<OrchestrationEvent>();
+ const detached = yield* Deferred.make<void>();
+ const ackHeld = yield* Deferred.make<void>();
+ const releaseAck = yield* Deferred.make<void>();
+ let headSequence = 1;
+ let snapshotCalls = 0;
+ let replayCalls = 0;
+ const thread = makeDefaultOrchestrationThreadShell();
+ const project = makeDefaultOrchestrationReadModel().projects[0]!;
+ const events: OrchestrationEvent[] = Array.from({ length: 1_001 }, (_, index) =>
+ makeLiveToolActivityEvent(index + 2, "tool.completed"),
+ );
+ events.push(
+ {
+ ...events[0]!,
+ sequence: 1_003,
+ type: "thread.archived",
+ payload: {
+ threadId: defaultThreadId,
+ archivedAt: "2026-01-01T00:00:02.000Z",
+ updatedAt: "2026-01-01T00:00:02.000Z",
+ },
+ },
+ {
+ ...events[0]!,
+ sequence: 1_004,
+ aggregateKind: "project",
+ aggregateId: defaultProjectId,
+ type: "project.deleted",
+ payload: { projectId: defaultProjectId, deletedAt: "2026-01-01T00:00:02.000Z" },
+ },
+ );
+ yield* buildAppUnderTest({
+ layers: {
+ orchestrationEngine: {
+ latestSequence: Effect.sync(() => headSequence),
+ streamDomainEvents: Stream.fromPubSub(liveEvents).pipe(
+ Stream.ensuring(Deferred.succeed(detached, undefined)),
+ ),
+ readEvents: () => {
+ replayCalls += 1;
+ return Stream.empty;
+ },
+ },
+ projectionSnapshotQuery: {
+ getShellSnapshot: () =>
+ Effect.sync(() => {
+ snapshotCalls += 1;
+ return {
+ snapshotSequence: headSequence,
+ projects: headSequence === 1 ? [project] : [],
+ threads: headSequence === 1 ? [thread] : [],
+ updatedAt: "2026-01-01T00:00:02.000Z",
+ };
+ }),
+ },
+ },
+ });
+ const wsUrl = yield* getWsServerUrl("/ws");
+ yield* makeWsRpcClient.pipe(
+ Effect.flatMap((client) =>
+ Effect.gen(function* () {
+ const received: OrchestrationShellStreamItem[] = [];
+ const attempt = yield* client[ORCHESTRATION_WS_METHODS.subscribeShell]({}).pipe(
+ Stream.tap((item) => Effect.sync(() => received.push(item))),
+ Stream.runDrain,
+ Effect.result,
+ Effect.forkScoped,
+ );
+ yield* Deferred.await(ackHeld);
+ headSequence = 1_004;
+ yield* PubSub.publishAll(liveEvents, events);
+ yield* Deferred.await(detached);
+ assert.equal(yield* PubSub.size(liveEvents), 0);
+ yield* Deferred.succeed(releaseAck, undefined);
+ const result = yield* Fiber.join(attempt);
+ assertTrue(result._tag === "Failure");
+ assert.equal(result.failure._tag, "OrchestrationGetSnapshotError");
+ assert.equal(received.length, 1);
+ const initial = received[0];
+ assertTrue(initial?.kind === "snapshot");
+ assert.equal(initial.snapshot.threads.length, 1);
+
+ const recovered = yield* client[ORCHESTRATION_WS_METHODS.subscribeShell]({
+ afterSequence: initial.snapshot.snapshotSequence,
+ requestCompletionMarker: true,
+ }).pipe(
+ Stream.takeUntil((item) => item.kind === "synchronized"),
+ Stream.runCollect,
+ );
+ const snapshot = recovered[0];
+ assertTrue(snapshot?.kind === "snapshot");
+ assert.equal(snapshot.snapshot.snapshotSequence, 1_004);
+ assert.deepEqual(snapshot.snapshot.projects, []);
+ assert.deepEqual(snapshot.snapshot.threads, []);
+ assert.deepEqual(recovered[1], { kind: "synchronized" });
+ assert.equal(snapshotCalls, 2);
+ assert.equal(replayCalls, 0);
+ }),
+ ),
+ Effect.provide(withFirstWsAckHeld(wsUrl, ackHeld, releaseAck)),
+ );
+ }).pipe(Effect.scoped, Effect.provide(NodeHttpServer.layerTest)),
+ );
+
it.effect("subscribeThread replaces a cursor ahead of the authoritative head", () =>
Effect.gen(function* () {
let readEventsCalls = 0;
diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts
index 35f41d58e31..3beb4daf7ff 100644
--- a/apps/server/src/ws.ts
+++ b/apps/server/src/ws.ts
@@ -81,6 +81,7 @@ import {
projectThreadDetailSnapshot,
} from "./orchestration/ActivityPayloadProjection.ts";
import { makeThreadLiveEventCoalescer } from "./orchestration/ThreadLiveEventCoalescer.ts";
+import { makeLiveStreamBudget, type RetainedLiveItem } from "./orchestration/LiveStreamBudget.ts";
import {
cleanupFailedUploadedAttachments,
normalizeDispatchCommand,
@@ -927,15 +928,6 @@ const makeWsRpcLayer = (
return output;
});
- const coalesceShellLiveStream = <E, R>(
- stream: Stream.Stream<ShellLiveInput, E, R>,
- ): Stream.Stream<OrchestrationShellStreamItem, E, R> =>
- stream.pipe(
- Stream.groupedWithin(SHELL_COALESCE_MAX_CHUNK, SHELL_COALESCE_WINDOW),
- Stream.mapEffect(coalesceShellLiveInputs),
- Stream.flatMap((items) => Stream.fromIterable(items)),
- );
-
const dispatchBootstrapTurnStart = (
command: Extract<OrchestrationCommand, { type: "thread.turn.start" }>,
): Effect.Effect<{ readonly sequence: number }, OrchestrationDispatchCommandError> =>
@@ -1416,16 +1408,55 @@ const makeWsRpcLayer = (
// sequence but the live subscription is not attached yet). Every
// path below emits from this same buffered live tail. Overlapping
// events are deduped by sequence on the client.
- const liveBuffer = yield* Queue.unbounded<ShellLiveInput>();
+ const liveBudget = yield* makeLiveStreamBudget();
+ const liveBuffer = yield* Queue.unbounded<
+ RetainedLiveItem<ShellLiveInput>,
+ OrchestrationGetSnapshotError
+ >();
+ let liveBufferClosed = false;
+ const closeLiveBuffer = (error?: OrchestrationGetSnapshotError) =>
+ Effect.gen(function* () {
+ if (liveBufferClosed) {
+ return;
+ }
+ liveBufferClosed = true;
+ liveBudget.release(yield* Queue.clear(liveBuffer).pipe(Effect.orDie));
+ if (error) {
+ yield* Queue.fail(liveBuffer, error);
+ }
+ yield* Queue.shutdown(liveBuffer);
+ });
+ yield* Effect.addFinalizer(() => closeLiveBuffer());
+ yield* liveBudget.failed.pipe(
+ Effect.catchTags({ OrchestrationGetSnapshotError: closeLiveBuffer }),
+ Effect.forkScoped,
+ );
yield* Effect.forkScoped(
orchestrationEngine.streamDomainEvents.pipe(
Stream.runForEach((event) =>
- Queue.offer(liveBuffer, { kind: "event" as const, event }),
+ liveBudget.retain({ kind: "event" as const, event }, event).pipe(
+ Effect.flatMap((item) => Queue.offer(liveBuffer, item)),
+ Effect.uninterruptible,
+ ),
),
+ // Stop the PubSub consumer even if RPC delivery is waiting
+ // for an ACK and never pulls the failed buffer again.
+ Effect.raceFirst(liveBudget.failed),
+ Effect.catchTags({ OrchestrationGetSnapshotError: () => Effect.void }),
),
{ startImmediately: true },
);
- const bufferedLiveStream = coalesceShellLiveStream(Stream.fromQueue(liveBuffer));
+ const coalesceRetainedInputs = (
+ items: ReadonlyArray<RetainedLiveItem<ShellLiveInput>>,
+ ) =>
+ coalesceShellLiveInputs(items.map((item) => item.value)).pipe(
+ Effect.flatMap((output) => liveBudget.replace(items, output)),
+ );
+ const bufferedLiveStream = Stream.fromQueue(liveBuffer).pipe(
+ Stream.groupedWithin(SHELL_COALESCE_MAX_CHUNK, SHELL_COALESCE_WINDOW),
+ Stream.mapEffect(coalesceRetainedInputs),
+ Stream.flatMap((items) => Stream.fromIterable(items)),
+ );
const loadSnapshot = projectionSnapshotQuery.getShellSnapshot().pipe(
Effect.tapError((cause) =>
@@ -1443,18 +1474,21 @@ const makeWsRpcLayer = (
// Offer the completion marker into the same queue as live events.
// Anything buffered while snapshot/replay work was in flight is
// therefore delivered before the client is told it is synchronized.
- const synchronizedThenLive =
+ const synchronizedThenLive = liveBudget.deliver(
input.requestCompletionMarker === true
? Stream.concat(
Stream.fromEffect(
- Queue.offer(liveBuffer, { kind: "synchronized" as const }).pipe(
+ liveBudget.retain({ kind: "synchronized" as const }).pipe(
+ Effect.flatMap((item) => Queue.offer(liveBuffer, item)),
+ Effect.uninterruptible,
Effect.andThen(Queue.takeAll(liveBuffer)),
- Effect.flatMap(coalesceShellLiveInputs),
+ Effect.flatMap(coalesceRetainedInputs),
),
).pipe(Stream.flatMap((items) => Stream.fromIterable(items))),
bufferedLiveStream,
)
- : bufferedLiveStream;
+ : bufferedLiveStream,
+ );
// When the client already holds a shell snapshot (cached, or loaded
// over HTTP) it passes that snapshot's sequence, and we resume by
@@ -1551,9 +1585,14 @@ const makeWsRpcLayer = (
// Attach live delivery before reading either replay or snapshot state.
// Otherwise an event published while the snapshot is loading is lost.
const liveBuffer = yield* makeThreadLiveEventCoalescer();
- yield* Effect.forkScoped(liveStream.pipe(Stream.runForEach(liveBuffer.offer)), {
- startImmediately: true,
- });
+ yield* Effect.forkScoped(
+ liveStream.pipe(
+ Stream.runForEachArray(liveBuffer.offerAll),
+ Effect.raceFirst(liveBuffer.failed),
+ Effect.catchTags({ OrchestrationGetSnapshotError: () => Effect.void }),
+ ),
+ { startImmediately: true },
+ );
const bufferedLiveStream = liveBuffer.stream;
// When the client already loaded the snapshot over HTTP it passes
@@ -1603,13 +1642,10 @@ const makeWsRpcLayer = (
);
const afterCatchUp =
input.requestCompletionMarker === true
- ? Stream.concat(
- Stream.fromEffect(
- liveBuffer
- .offerAndWait({ kind: "synchronized" as const })
- .pipe(Effect.andThen(liveBuffer.takeAll)),
- ).pipe(Stream.flatMap((items) => Stream.fromIterable(items))),
- bufferedLiveStream,
+ ? Stream.unwrap(
+ liveBuffer
+ .offer({ kind: "synchronized" as const })
+ .pipe(Effect.as(bufferedLiveStream)),
)
: bufferedLiveStream;
return Stream.concat(catchUpStream, afterCatchUp);
@@ -1647,13 +1683,10 @@ const makeWsRpcLayer = (
const afterSnapshot =
input.requestCompletionMarker === true
- ? Stream.concat(
- Stream.fromEffect(
- liveBuffer
- .offerAndWait({ kind: "synchronized" as const })
- .pipe(Effect.andThen(liveBuffer.takeAll)),
- ).pipe(Stream.flatMap((items) => Stream.fromIterable(items))),
- bufferedLiveStream,
+ ? Stream.unwrap(
+ liveBuffer
+ .offer({ kind: "synchronized" as const })
+ .pipe(Effect.as(bufferedLiveStream)),
)
: bufferedLiveStream;
return Stream.concat(