Skip to content
TypeScript

fix(server): coalesce queued shell updates for slow clients (#14859)

maria94827737ea01
diff --git a/apps/server/src/orchestration-v2/LiveStreamBudget.test.ts b/apps/server/src/orchestration-v2/LiveStreamBudget.test.ts
index 6e8c9770d31..ba19ed3227b 100644
--- a/apps/server/src/orchestration-v2/LiveStreamBudget.test.ts
+++ b/apps/server/src/orchestration-v2/LiveStreamBudget.test.ts
@@ -9,6 +9,7 @@ import { describe, expect } from "vite-plus/test";
import {
bufferLiveStream,
+ bufferLatestLiveStream,
makeLiveStreamBudget,
replayAndBufferLiveEvents,
type RetainedLiveItem,
@@ -75,6 +76,39 @@ it.effect("stops draining a slow subscriber when its unacknowledged tail fills",
type Event = { readonly sequence: number; readonly text: string; readonly threadId?: string };
+describe("bufferLatestLiveStream", () => {
+ it.effect.each(["items", "bytes"] as const)(
+ "counts an unacknowledged state against the %s limit when its replacement arrives",
+ (limit) =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const releaseUpdate = yield* Deferred.make<void>();
+ const closed = yield* Deferred.make<void>();
+ const first = { sequence: 1, text: "é".repeat(20) };
+ const next = { ...first, sequence: 2 };
+ const pull = yield* Stream.toPull(
+ bufferLatestLiveStream(
+ Stream.concat(
+ Stream.succeed(first),
+ Stream.fromEffect(Deferred.await(releaseUpdate)).pipe(Stream.map(() => next)),
+ ).pipe(Stream.ensuring(Deferred.succeed(closed, undefined))),
+ () => "same-thread",
+ limit === "items"
+ ? { maxItems: 1 }
+ : { maxSerializedBytes: Buffer.byteLength(JSON.stringify(first)) },
+ ),
+ );
+ expect(yield* pull).toEqual([first]);
+ yield* Deferred.succeed(releaseUpdate, undefined);
+ yield* Deferred.await(closed);
+ const result = yield* pull.pipe(Effect.result);
+ expect(result._tag).toBe("Failure");
+ if (result._tag === "Failure") expect(result.failure._tag).toBe("LiveStreamBufferError");
+ }),
+ ),
+ );
+});
+
describe("replayAndBufferLiveEvents", () => {
it.effect.each(["high-water", "replay"] as const)(
"unsubscribes and cancels a blocked %s read on live overflow",
diff --git a/apps/server/src/orchestration-v2/LiveStreamBudget.ts b/apps/server/src/orchestration-v2/LiveStreamBudget.ts
index d7048383998..3960d9982bf 100644
--- a/apps/server/src/orchestration-v2/LiveStreamBudget.ts
+++ b/apps/server/src/orchestration-v2/LiveStreamBudget.ts
@@ -7,6 +7,7 @@ import * as Exit from "effect/Exit";
import * as Queue from "effect/Queue";
import * as PubSub from "effect/PubSub";
import * as Scope from "effect/Scope";
+import * as Semaphore from "effect/Semaphore";
import * as Stream from "effect/Stream";
export class LiveStreamBufferError extends Schema.TaggedError<LiveStreamBufferError>()(
@@ -254,6 +255,83 @@ export const bufferLiveStream = <A extends object, E, R>(
}),
);
+/** Coalesce queued full states; delivered states stay charged until the next pull ACKs them. */
+export const bufferLatestLiveStream = <A extends { readonly sequence: number }, E, R>(
+ source: Stream.Stream<A, E, R>,
+ key: (value: A) => string,
+ limits?: LiveStreamLimits,
+) =>
+ Stream.unwrap(
+ Effect.gen(function* () {
+ const budget = yield* makeLiveStreamBudget(limits);
+ const ready = yield* Queue.bounded<void, E | LiveStreamBufferError | Cause.Done>(1);
+ const mutex = yield* Semaphore.make(1);
+ const pending = new Map<string, RetainedLiveItem<A>>();
+ let closed = false;
+ const close = (error?: LiveStreamBufferError) =>
+ mutex.withPermit(
+ Effect.gen(function* () {
+ if (closed) return;
+ closed = true;
+ budget.release(pending.values());
+ pending.clear();
+ if (error) yield* Queue.fail(ready, error);
+ yield* Queue.shutdown(ready);
+ }),
+ );
+ yield* Effect.addFinalizer(() => close());
+ yield* budget.failed.pipe(
+ Effect.catchTags({ LiveStreamBufferError: close }),
+ Effect.forkScoped,
+ );
+ yield* source.pipe(
+ Stream.runForEach((value) =>
+ mutex.withPermit(
+ Effect.gen(function* () {
+ yield* budget.check;
+ if (closed) return;
+ const identity = key(value);
+ const previous = pending.get(identity);
+ if (previous && previous.value.sequence >= value.sequence) return;
+ const wasEmpty = pending.size === 0;
+ const [item] = yield* budget.replace(previous ? [previous] : [], [value]);
+ pending.set(identity, item!);
+ // Only the empty-to-nonempty transition needs a wakeup; replacements
+ // must not leave another token after this batch has drained.
+ if (wasEmpty) yield* Queue.offer(ready, undefined);
+ }).pipe(Effect.uninterruptible),
+ ),
+ ),
+ Effect.raceFirst(budget.failed),
+ Effect.exit,
+ Effect.flatMap((exit) =>
+ Exit.isFailure(exit) ? Queue.failCause(ready, exit.cause) : Queue.end(ready),
+ ),
+ Effect.forkScoped({ startImmediately: true }),
+ );
+ return budget.deliver(
+ Stream.fromPull(
+ Effect.succeed(
+ Queue.take(ready).pipe(
+ Effect.andThen(
+ mutex.withPermit(
+ Effect.sync(() => {
+ const items = Array.from(pending.values()).sort(
+ (left, right) => left.value.sequence - right.value.sequence,
+ );
+ pending.clear();
+ // Moving to delivery preserves the budget charge until ACK.
+ return items as Arr.NonEmptyArray<RetainedLiveItem<A>>;
+ }),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ }),
+ );
+
/**
* Subscribe and start draining before reading the high-water mark. A blocked
* catch-up query or an unacknowledged replay batch must not strand an unbounded
diff --git a/apps/server/src/orchestration-v2/ShellStream.test.ts b/apps/server/src/orchestration-v2/ShellStream.test.ts
index c86a641d296..240bd8d3e2f 100644
--- a/apps/server/src/orchestration-v2/ShellStream.test.ts
+++ b/apps/server/src/orchestration-v2/ShellStream.test.ts
@@ -8,10 +8,14 @@ import type {
} from "@t3tools/contracts";
import { ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
+import type * as Cause from "effect/Cause";
import * as DateTime from "effect/DateTime";
+import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
+import * as PubSub from "effect/PubSub";
+import * as Queue from "effect/Queue";
import * as SqlClient from "effect/sql/SqlClient";
import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
@@ -19,6 +23,7 @@ import * as TestClock from "effect/testing/TestClock";
import {
archivedShellStreamItemFromThreadShell,
buildActiveShellSnapshot,
+ bufferShellLiveStream,
coalesceShellApplicationEvents,
coalesceStoredThreadEvents,
composeShellStreamWithEnrichment,
@@ -54,6 +59,64 @@ const emptyShellSnapshot = {
archivedThreads: [],
} as OrchestrationV2ShellSnapshot;
+it.effect("coalesces a slow shell subscriber by identity and location in sequence order", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const input = yield* Queue.unbounded<
+ Extract<OrchestrationV2ShellStreamItem, { readonly sequence: number }>,
+ Cause.Done
+ >();
+ const drained = yield* Deferred.make<void>();
+ const shell = shellFixture({ id: ThreadId.make("same"), title: "Before" });
+ const project = {
+ id: ProjectId.make("same"),
+ title: "Before",
+ workspaceRoot: "/workspace/same",
+ repositoryIdentity: null,
+ defaultModelSelection: null,
+ scripts: [],
+ createdAt: "2026-09-01T00:00:00Z",
+ updatedAt: "2026-09-01T00:00:00Z",
+ };
+ const initial = {
+ kind: "thread.updated" as const,
+ sequence: 1,
+ location: "active" as const,
+ thread: shell,
+ };
+ const updates = [
+ { kind: "project.updated", sequence: 2, project },
+ { ...initial, sequence: 3 },
+ { ...initial, sequence: 4, location: "archive" },
+ { ...initial, sequence: 5, thread: { ...shell, id: ThreadId.make("other") } },
+ {
+ kind: "project.updated",
+ sequence: 6,
+ project: { ...project, id: ProjectId.make("other") },
+ },
+ { kind: "project.removed", sequence: 7, projectId: project.id },
+ { kind: "thread.removed", sequence: 8, location: "active", threadId: shell.id },
+ { kind: "project.updated", sequence: 9, project: { ...project, title: "Recreated" } },
+ { ...initial, sequence: 10, thread: { ...shell, title: "Recreated" } },
+ { kind: "thread.removed", sequence: 11, location: "archive", threadId: shell.id },
+ ] satisfies Array<Extract<OrchestrationV2ShellStreamItem, { readonly sequence: number }>>;
+ const pull = yield* Stream.toPull(
+ bufferShellLiveStream(
+ Stream.fromQueue(input).pipe(Stream.ensuring(Deferred.succeed(drained, undefined))),
+ { maxItems: 6, maxSerializedBytes: 1_500 },
+ ),
+ );
+ yield* Queue.offer(input, initial);
+ expect(yield* pull).toEqual([initial]);
+ yield* Queue.offerAll(input, updates);
+ yield* Queue.end(input);
+ // Finish producing the burst while the first batch is still awaiting its ACK.
+ yield* Deferred.await(drained);
+ expect(yield* pull).toEqual([updates[3], updates[4], updates[7], updates[8], updates[9]]);
+ }),
+ ),
+);
+
describe("buildActiveShellSnapshot", () => {
it("never duplicates archived rows into the regular shell", () => {
const active = shellFixture({ archivedAt: null });
@@ -356,6 +419,104 @@ describe("shellStreamItemsFromResumeSnapshot", () => {
});
describe("composeShellStreamWithEnrichment", () => {
+ it.effect("preserves pending repository resolutions while an enrichment ACK is withheld", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ // Match ProjectEnrichmentService's sliding notifications and the WS batching path.
+ const changes = yield* Effect.acquireRelease(
+ PubSub.sliding<{ readonly workspaceRoot: string }>(256),
+ PubSub.shutdown,
+ );
+ const subscription = yield* PubSub.subscribe(changes);
+ const pull = yield* Stream.toPull(
+ composeShellStreamWithEnrichment({
+ initial: Stream.empty,
+ tail: Stream.empty,
+ enrichment: Stream.fromSubscription(subscription).pipe(
+ Stream.groupedWithin(64, Duration.millis(25)),
+ Stream.map((changes) =>
+ shellStreamItemFromEnrichmentRefresh({
+ snapshot: emptyShellSnapshot,
+ changes,
+ }),
+ ),
+ ),
+ }),
+ );
+
+ const firstRoots = Array.from({ length: 64 }, (_, index) => `/workspace/first-${index}`);
+ yield* PubSub.publishAll(
+ changes,
+ firstRoots.map((workspaceRoot) => ({ workspaceRoot })),
+ );
+ expect(yield* pull).toMatchObject([{ resolvedRepositoryIdentityRoots: firstRoots }]);
+
+ // The next completion can be batched before the client acknowledges the first.
+ yield* PubSub.publish(changes, { workspaceRoot: "/workspace/pending" });
+ yield* Effect.yieldNow;
+ yield* TestClock.adjust(Duration.millis(25));
+ const laterRoots = Array.from({ length: 256 }, (_, index) => `/workspace/later-${index}`);
+ yield* PubSub.publishAll(
+ changes,
+ laterRoots.map((workspaceRoot) => ({ workspaceRoot })),
+ );
+
+ const resumed = yield* Stream.fromPull(Effect.succeed(pull)).pipe(
+ Stream.takeUntil(
+ (item) =>
+ item.resolvedRepositoryIdentityRoots?.includes("/workspace/later-255") ?? false,
+ ),
+ Stream.runCollect,
+ );
+ expect(resumed.flatMap((item) => item.resolvedRepositoryIdentityRoots ?? [])).toEqual([
+ "/workspace/pending",
+ ...laterRoots,
+ ]);
+ }),
+ ),
+ );
+
+ it.effect("keeps a merged shell batch charged while the client withholds its ACK", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const update = yield* Deferred.make<void>();
+ const closed = yield* Deferred.make<void>();
+ const initial = {
+ kind: "thread.removed" as const,
+ sequence: 1,
+ location: "active" as const,
+ threadId: ThreadId.make("thread-a"),
+ };
+ const pull = yield* Stream.toPull(
+ composeShellStreamWithEnrichment({
+ initial: Stream.empty,
+ tail: bufferShellLiveStream(
+ Stream.concat(
+ Stream.succeed(initial),
+ Stream.fromEffect(Deferred.await(update)).pipe(
+ Stream.map(() => ({ ...initial, sequence: 2 })),
+ ),
+ ).pipe(Stream.ensuring(Deferred.succeed(closed, undefined))),
+ { maxItems: 1 },
+ ),
+ enrichment: Stream.empty,
+ }),
+ );
+ expect(yield* pull).toEqual([initial]);
+ // Let the merge producer run while the client still withholds its ACK.
+ yield* Effect.yieldNow;
+ yield* Deferred.succeed(update, undefined);
+ yield* Deferred.await(closed);
+ const result = yield* Stream.fromPull(Effect.succeed(pull)).pipe(
+ Stream.runDrain,
+ Effect.result,
+ );
+ expect(result._tag).toBe("Failure");
+ if (result._tag === "Failure") expect(result.failure._tag).toBe("LiveStreamBufferError");
+ }),
+ ),
+ );
+
it.effect(
"emits every initial item before enrichment even when enrichment is already ready",
() =>
diff --git a/apps/server/src/orchestration-v2/ShellStream.ts b/apps/server/src/orchestration-v2/ShellStream.ts
index be8020ac425..057fd77d809 100644
--- a/apps/server/src/orchestration-v2/ShellStream.ts
+++ b/apps/server/src/orchestration-v2/ShellStream.ts
@@ -13,12 +13,43 @@ import {
OrchestrationV2ThreadShell as ThreadShellSchema,
} from "@t3tools/contracts";
import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
+import type * as Arr from "effect/Array";
+import type * as Cause from "effect/Cause";
import * as Clock from "effect/Clock";
+import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
+import * as Exit from "effect/Exit";
+import * as Queue from "effect/Queue";
import * as Schema from "effect/Schema";
import type * as SqlClient from "effect/sql/SqlClient";
import * as Stream from "effect/Stream";
+import { bufferLatestLiveStream } from "./LiveStreamBudget.ts";
+
+type ShellDelta = Extract<OrchestrationV2ShellStreamItem, { readonly sequence: number }>;
+
+/** Snapshots, synchronization, and enrichment markers must bypass full-state coalescing. */
+export const bufferShellLiveStream = <E, R>(
+ source: Stream.Stream<ShellDelta, E, R>,
+ limits?: { readonly maxItems?: number; readonly maxSerializedBytes?: number },
+) =>
+ bufferLatestLiveStream(
+ source,
+ (item) => {
+ switch (item.kind) {
+ case "project.updated":
+ return `project:${item.project.id}`;
+ case "project.removed":
+ return `project:${item.projectId}`;
+ case "thread.updated":
+ return `thread:${item.location}:${item.thread.id}`;
+ case "thread.removed":
+ return `thread:${item.location}:${item.threadId}`;
+ }
+ },
+ limits,
+ );
+
export function buildActiveShellSnapshot(input: {
readonly projects: ReadonlyArray<OrchestrationProjectShell>;
readonly threads: OrchestrationV2ThreadShellSnapshot;
@@ -112,7 +143,58 @@ export function composeShellStreamWithEnrichment<A, E, R, A2, E2, R2, A3, E3, R3
readonly tail: Stream.Stream<A2, E2, R2>;
readonly enrichment: Stream.Stream<A3, E3, R3>;
}): Stream.Stream<A | A2 | A3, E | E2 | E3, R | R2 | R3> {
- return Stream.concat(input.initial, Stream.merge(input.tail, input.enrichment));
+ const merged = Stream.fromPull(
+ Effect.gen(function* () {
+ const output = yield* Queue.bounded<
+ {
+ readonly items: Arr.NonEmptyReadonlyArray<A2 | A3>;
+ readonly acknowledged?: Deferred.Deferred<void>;
+ },
+ E2 | E3 | Cause.Done
+ >(0);
+ yield* Effect.addFinalizer(() => Queue.shutdown(output));
+ let remaining = 2;
+ const drain = (effect: Effect.Effect<void, E2 | E3, R2 | R3>) =>
+ effect.pipe(
+ Effect.exit,
+ Effect.flatMap((exit) =>
+ Exit.isFailure(exit)
+ ? Queue.failCause(output, exit.cause)
+ : --remaining === 0
+ ? Queue.end(output)
+ : Effect.void,
+ ),
+ Effect.forkScoped,
+ );
+ yield* drain(
+ input.tail.pipe(
+ Stream.runForEachArray((items) =>
+ Effect.gen(function* () {
+ const acknowledged = yield* Deferred.make<void>();
+ yield* Queue.offer(output, { items, acknowledged });
+ yield* Deferred.await(acknowledged);
+ }),
+ ),
+ ),
+ );
+ // Keep draining the sliding enrichment subscription after each handoff,
+ // as Stream.merge does, while only the budgeted tail waits for an ACK.
+ yield* drain(
+ input.enrichment.pipe(Stream.runForEachArray((items) => Queue.offer(output, { items }))),
+ );
+ let previous: Deferred.Deferred<void> | undefined;
+ // Stream.merge pulls ahead after handing off each batch. Wait for the next
+ // downstream pull so shell delivery keeps that batch charged until its RPC ACK.
+ // @effect-diagnostics-next-line returnEffectInGen:off - Stream.fromPull needs the pull effect as its result.
+ return Effect.gen(function* () {
+ if (previous) yield* Deferred.succeed(previous, undefined);
+ const next = yield* Queue.take(output);
+ previous = next.acknowledged;
+ return next.items;
+ });
+ }),
+ ).pipe(Stream.scoped);
+ return Stream.concat(input.initial, merged);
}
const sameProjects = Schema.toEquivalence(Schema.Array(ProjectShellSchema));
@@ -275,7 +357,10 @@ export function coalesceStoredThreadEvents(
export function shellStreamItemFromThreadShell(input: {
readonly stored: Extract<ShellApplicationEvent, { readonly event: unknown }>;
readonly shell: OrchestrationV2ThreadShell | null;
-}): Exclude<OrchestrationV2ShellStreamItem, { readonly kind: "snapshot" }> {
+}): Extract<
+ OrchestrationV2ShellStreamItem,
+ { readonly kind: "thread.updated" | "thread.removed" }
+> {
if (input.shell !== null) {
if (input.shell.archivedAt !== null) {
return {
diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts
index 7dc60532204..8eaa4bfad35 100644
--- a/apps/server/src/ws.ts
+++ b/apps/server/src/ws.ts
@@ -121,6 +121,7 @@ import * as SecretRequests from "./secrets/SecretRequests.ts";
import {
archivedShellStreamItemFromThreadShell,
buildActiveShellSnapshot,
+ bufferShellLiveStream,
coalesceShellApplicationEvents,
coalesceStoredThreadEvents,
composeShellStreamWithEnrichment,
@@ -1019,7 +1020,7 @@ export const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subsc
);
const liveFrom = (afterSequence: number) =>
- bufferLiveStream(
+ bufferShellLiveStream(
toShellStream(
applicationEvents.streamProjectedApplicationEvents({
afterSequence,