TypeScript
perf(client-runtime): merge shell deltas once per received batch (#18416)
Alex Southwell1915569b1957
diff --git a/packages/client-runtime/src/state/shell-sync.test.ts b/packages/client-runtime/src/state/shell-sync.test.tsindex 9d1df33d1f7..7f24f61c53b 100644--- a/packages/client-runtime/src/state/shell-sync.test.ts+++ b/packages/client-runtime/src/state/shell-sync.test.ts@@ -123,6 +123,190 @@ const makePersistenceHarness = Effect.fn("test.makeShellPersistenceHarness")(fun});describe("environment shell synchronization", () => {+ it.effect.each([+ { bufferSize: Infinity, expectedSequences: [51], existingRows: false },+ { bufferSize: Infinity, expectedSequences: [51], existingRows: true },+ // RpcClient defaults to a 16-event buffer, which splits larger server chunks.+ { bufferSize: 16, expectedSequences: [17, 33, 49, 51], existingRows: false },+ { bufferSize: 16, expectedSequences: [17, 33, 49, 51], existingRows: true },+ ])("batches $bufferSize events (existing: $existingRows)", (input) =>+ Effect.gen(function* () {+ const { bufferSize, expectedSequences, existingRows } = input;+ const events = yield* Queue.bounded<OrchestrationV2ShellStreamItem>(bufferSize);+ let rowVisits = 0;+ const rows = Array.from({ length: 50 }, (_, index) => ({+ ...v2ThreadShell,+ get id() {+ rowVisits += 1;+ return ThreadId.make(`thread-${index}`);+ },+ }));+ const batchSnapshot = { ...LIVE_SHELL_SNAPSHOT, threads: existingRows ? rows : [] };+ const client = {+ [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),+ } as unknown as WsRpcProtocolClient;+ const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);+ const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(+ Option.some(session(client)),+ );+ const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({+ target: TARGET,+ state: supervisorState,+ session: activeSession,+ prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),+ connect: Effect.void,+ disconnect: Effect.void,+ retryNow: Effect.void,+ } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);+ const cache = Persistence.EnvironmentCacheStore.of({+ loadShell: () => Effect.succeedNone,+ saveShell: () => Effect.void,+ loadThread: () => Effect.succeedNone,+ saveThread: () => Effect.void,+ removeThread: () => Effect.void,+ loadServerConfig: () => Effect.succeedNone,+ saveServerConfig: () => Effect.void,+ loadVcsRefs: () => Effect.succeedNone,+ saveVcsRefs: () => Effect.void,+ removeVcsRefs: () => Effect.void,+ clearVcsRefs: () => Effect.void,+ clear: () => Effect.void,+ });+ const shellState = yield* makeEnvironmentShellState().pipe(+ Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),+ Effect.provideService(Persistence.EnvironmentCacheStore, cache),+ Effect.provideService(+ ShellSnapshotLoader.ShellSnapshotLoader,+ ShellSnapshotLoader.ShellSnapshotLoader.of({+ load: () => Effect.succeedNone,+ }),+ ),+ );+ yield* SubscriptionRef.set(supervisorState, {+ desired: true,+ network: "online",+ phase: "connected",+ stage: null,+ attempt: 1,+ generation: 1,+ lastFailure: null,+ retryAt: null,+ });+ yield* Queue.offer(events, { kind: "snapshot", snapshot: batchSnapshot });+ yield* Queue.offer(events, { kind: "synchronized" });+ yield* SubscriptionRef.changes(shellState).pipe(+ Stream.filter((state) => state.status === "live"),+ Stream.runHead,+ );++ // Observe before publishing so no batch can arrive before the subscription.+ const observed = yield* SubscriptionRef.changes(shellState).pipe(+ Stream.drop(1),+ Stream.takeUntil(+ (state) => Option.isSome(state.snapshot) && state.snapshot.value.snapshotSequence === 51,+ ),+ Stream.runCollect,+ Effect.forkScoped({ startImmediately: true }),+ );+ rowVisits = 0;+ yield* Queue.offerAll(+ events,+ Array.from({ length: 50 }, (_, index) => ({+ kind: "thread.updated" as const,+ sequence: 2 + index,+ location: "active" as const,+ thread: {+ ...v2ThreadShell,+ get id() {+ rowVisits += 1;+ return ThreadId.make(`thread-${index}`);+ },+ title: "Updated",+ },+ })),+ );+ const states = yield* Fiber.join(observed);+ if (existingRows) {+ // Index each received batch once; distinct updates must not rescan every row.+ expect(rowVisits).toBeLessThanOrEqual(50 * (expectedSequences.length + 10));+ }+ const snapshots = states.map((state) => Option.getOrThrow(state.snapshot));+ expect(snapshots.map((snapshot) => snapshot.snapshotSequence)).toEqual(expectedSequences);+ expect(snapshots.at(-1)!.threads.map((thread) => thread.id)).toEqual(+ Array.from({ length: 50 }, (_, index) => `thread-${index}`),+ );++ const removedObserved = yield* SubscriptionRef.changes(shellState).pipe(+ Stream.filter(+ (state) => Option.isSome(state.snapshot) && state.snapshot.value.snapshotSequence === 52,+ ),+ Stream.runHead,+ Effect.forkScoped({ startImmediately: true }),+ );+ yield* Queue.offerAll(events, [+ { kind: "future.event", sequence: 99 } as never,+ {+ kind: "thread.removed",+ sequence: 52,+ location: "active",+ threadId: ThreadId.make("thread-0"),+ },+ {+ kind: "thread.removed",+ sequence: 51,+ location: "active",+ threadId: ThreadId.make("thread-1"),+ },+ ]);+ const removedState = Option.getOrThrow(yield* Fiber.join(removedObserved));+ expect(removedState.generation).toBe(states.at(-1)!.generation);+ expect([...removedState.removedAt]).toEqual([[ThreadId.make("thread-0"), 52]]);++ // An authoritative snapshot resets even a higher live cursor in the same batch.+ const resetRow = { ...v2ThreadShell, id: ThreadId.make("reset-row") };+ const resetObserved = yield* SubscriptionRef.changes(shellState).pipe(+ Stream.filter(+ (state) => Option.isSome(state.snapshot) && state.snapshot.value.snapshotSequence === 4,+ ),+ Stream.runHead,+ Effect.forkScoped({ startImmediately: true }),+ );+ yield* Queue.offerAll(events, [+ {+ kind: "thread.removed",+ sequence: 52,+ location: "active",+ threadId: ThreadId.make("thread-0"),+ },+ {+ kind: "snapshot",+ snapshot: { ...LIVE_SHELL_SNAPSHOT, snapshotSequence: 2, threads: [resetRow] },+ },+ { kind: "thread.removed", sequence: 2, location: "active", threadId: resetRow.id },+ {+ kind: "thread.updated",+ sequence: 3,+ location: "active",+ thread: { ...resetRow, title: "After reset" },+ },+ { kind: "synchronized" },+ {+ kind: "thread.updated",+ sequence: 4,+ location: "active",+ thread: { ...resetRow, title: "After completion" },+ },+ ]);+ const resetState = Option.getOrThrow(yield* Fiber.join(resetObserved));+ expect(resetState.status).toBe("live");+ expect(resetState.generation).toBeGreaterThan(removedState.generation);+ expect(resetState.removedAt.size).toBe(0);+ expect(Option.getOrThrow(resetState.snapshot).threads).toEqual([+ { ...resetRow, title: "After completion" },+ ]);+ }).pipe(Effect.scoped),+ );+it.effect("skips unchanged shell writes, persists resets and flushes changed rows", () =>Effect.gen(function* () {const saved = yield* SubscriptionRef.make<ReadonlyArray<OrchestrationV2ShellSnapshot>>([]);diff --git a/packages/client-runtime/src/state/shell.ts b/packages/client-runtime/src/state/shell.tsindex bce13d315b4..442e99b6f29 100644--- a/packages/client-runtime/src/state/shell.ts+++ b/packages/client-runtime/src/state/shell.ts@@ -31,7 +31,8 @@ import type { RpcSession } from "../rpc/session.ts";import * as ShellSnapshotLoader from "./shellSnapshotHttp.ts";import type { DeferredShellSnapshot } from "./shellPullRequests.ts";import {- applyShellStreamEvent,+ applyShellStreamEvents,+ type ShellStreamEvent,mergeShellSnapshotProjects,reuseUnchangedThreadShells,sameThreadPullRequests,@@ -211,10 +212,46 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")) {const initial = yield* SubscriptionRef.get(state);let waiting = yield* Ref.get(awaitingCompletion);- /* oxlint-disable oxc/no-accumulating-spread -- This copies a fixed-shape state record, not a growing collection. */let next = initial;let receivedSnapshot = false;+ let deltas: Array<ShellStreamEvent> = [];+ const flushDeltas = () => {+ if (deltas.length > 0 && Option.isSome(next.snapshot)) {+ let sequence = next.snapshot.value.snapshotSequence;+ let removedAt: Map<ThreadId, number> | undefined;+ for (const delta of deltas) {+ if (delta.sequence <= sequence) continue;+ switch (delta.kind) {+ case "thread.removed":+ removedAt ??= new Map(next.removedAt);+ removedAt.set(delta.threadId, delta.sequence);+ break;+ case "thread.updated":+ case "project.updated":+ case "project.removed":+ break;+ default:+ continue;+ }+ sequence = delta.sequence;+ }+ next = {+ ...next,+ removedAt: removedAt ?? next.removedAt,+ snapshot: Option.some(applyShellStreamEvents(next.snapshot.value, deltas)),+ status: waiting ? "synchronizing" : "live",+ error: Option.none(),+ };+ }+ deltas = [];+ };for (const item of items) {+ if (item.kind !== "snapshot" && item.kind !== "synchronized") {+ deltas.push(item);+ continue;+ }+ // Snapshots can reset the cursor; completion markers change the sync status.+ flushDeltas();if (item.kind === "synchronized") {waiting = false;if (Option.isSome(next.snapshot)) {@@ -222,46 +259,24 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")}continue;}- const authoritative =- item.kind === "snapshot" && item.resolvedRepositoryIdentityRoots === undefined;- const nextSnapshot =- item.kind === "snapshot"- ? mergeShellSnapshotProjects(- Option.getOrNull(next.snapshot),- item.snapshot,- item.resolvedRepositoryIdentityRoots === undefined- ? undefined- : {- resolvedRepositoryIdentityRoots: item.resolvedRepositoryIdentityRoots,- },- )- : Option.match(next.snapshot, {- onNone: () => null,- onSome: (snapshot) =>- item.sequence > snapshot.snapshotSequence- ? applyShellStreamEvent(snapshot, item)- : snapshot,- });- if (nextSnapshot === null) continue;- receivedSnapshot ||= item.kind === "snapshot";- const removal =- item.kind === "thread.removed" &&- Option.exists(next.snapshot, (snapshot) => item.sequence > snapshot.snapshotSequence)- ? item- : null;+ const authoritative = item.resolvedRepositoryIdentityRoots === undefined;+ const nextSnapshot = mergeShellSnapshotProjects(+ Option.getOrNull(next.snapshot),+ item.snapshot,+ item.resolvedRepositoryIdentityRoots === undefined+ ? undefined+ : { resolvedRepositoryIdentityRoots: item.resolvedRepositoryIdentityRoots },+ );+ receivedSnapshot = true;next = {snapshot: Option.some(nextSnapshot),status: waiting ? "synchronizing" : "live",error: Option.none(),generation: authoritative ? ++lastShellGeneration : next.generation,- removedAt: authoritative- ? EMPTY_REMOVALS- : removal === null- ? next.removedAt- : new Map(next.removedAt).set(removal.threadId, removal.sequence),+ removedAt: authoritative ? EMPTY_REMOVALS : next.removedAt,};}- /* oxlint-enable oxc/no-accumulating-spread */+ flushDeltas();yield* Ref.set(awaitingCompletion, waiting);if (next === initial) return;if (pendingLinkIds !== undefined && Option.isSome(next.snapshot)) {diff --git a/packages/client-runtime/src/state/shellReducer.test.ts b/packages/client-runtime/src/state/shellReducer.test.tsindex 8be1ffd8e7a..3fbd9b1b8d3 100644--- a/packages/client-runtime/src/state/shellReducer.test.ts+++ b/packages/client-runtime/src/state/shellReducer.test.ts@@ -4,6 +4,8 @@ import { describe, expect, it } from "vite-plus/test";import { v2Project, v2ShellSnapshot, v2ThreadShell } from "./orchestrationV2TestFixtures.ts";import {applyShellStreamEvent,+ applyShellStreamEvents,+ type ShellStreamEvent,mergeShellSnapshotProjects,reuseUnchangedThreadShells,} from "./shellReducer.ts";@@ -327,3 +329,95 @@ describe("reuseUnchangedThreadShells", () => {expect(next.threads[0]?.pullRequests).toEqual([]);});});++describe("applyShellStreamEvents", () => {+ const row = (id: string) => ({ ...v2ThreadShell, id: ThreadId.make(id) });+ const a = row("a");+ const b = row("b");+ const unchanged = row("unchanged");+ const archived = row("archived");+ const oldArchive = row("old-archive");+ const added = row("new");+ const update = (+ sequence: number,+ thread: typeof v2ThreadShell,+ location: "active" | "archive" = "active",+ ): ShellStreamEvent => ({ kind: "thread.updated", sequence, location, thread });+ const remove = (sequence: number, thread: typeof v2ThreadShell): ShellStreamEvent => ({+ kind: "thread.removed",+ sequence,+ location: "active",+ threadId: thread.id,+ });++ it("matches sequential mixed deltas, including remove/reinsert order and stale events", () => {+ const otherProject = { ...v2Project, id: ProjectId.make("other-project") };+ const seed = {+ ...v2ShellSnapshot,+ snapshotSequence: 4,+ projects: [{ ...v2Project, repositoryIdentity }, otherProject],+ threads: [a, b, unchanged],+ archivedThreads: [archived, oldArchive],+ };+ const events: Array<ShellStreamEvent> = [+ update(5, { ...b, title: "Renamed" }),+ remove(5, a),+ remove(6, a),+ update(7, a),+ update(8, b, "archive"),+ update(9, archived),+ update(10, oldArchive, "archive"),+ update(11, added),+ remove(12, { ...a, id: ThreadId.make("missing") }),+ remove(11, added),+ remove(13, added),+ update(14, added),+ update(15, { ...archived }),+ { kind: "project.updated", sequence: 16, project: { ...v2Project, title: "Updated" } },+ { kind: "project.updated", sequence: 17, project: { ...v2Project, workspaceRoot: "/moved" } },+ { kind: "project.removed", sequence: 18, projectId: v2Project.id },+ { kind: "project.updated", sequence: 19, project: v2Project },+ ];+ const sequential = events.reduce(applyShellStreamEvent, seed);+ const next = applyShellStreamEvents(seed, events);+ expect(next).toEqual(sequential);+ expect(next.threads.map((row) => row.id)).toEqual([unchanged.id, a.id, archived.id, added.id]);+ expect(next.threads[0]).toBe(unchanged);+ expect(next.threads[2]).toBe(archived);+ expect(next.projects[0]).toBe(otherProject);+ expect(next.archivedThreads).toEqual([]);+ expect(seed.threads).toEqual([a, b, unchanged]);+ expect(seed.archivedThreads).toEqual([archived, oldArchive]);+ // Identity retention must use the latest project in this batch.+ expect(applyShellStreamEvents(seed, events.slice(0, 14)).projects[0]?.repositoryIdentity).toBe(+ repositoryIdentity,+ );+ expect(+ applyShellStreamEvents(seed, events.slice(0, 15)).projects[0]?.repositoryIdentity,+ ).toBeNull();+ });++ it("keeps collection identities for equal rows and rejects stale deltas without indexing", () => {+ const seed = { ...v2ShellSnapshot, threads: [a, b], snapshotSequence: 4 };+ const next = applyShellStreamEvents(seed, [update(5, { ...a }), update(6, { ...b })]);+ expect(next).toEqual(+ [update(5, { ...a }), update(6, { ...b })].reduce(applyShellStreamEvent, seed),+ );+ expect(next.threads).toBe(seed.threads);+ expect(next.projects).toBe(seed.projects);+ expect(next.archivedThreads).toBe(seed.archivedThreads);+ expect(next.snapshotSequence).toBe(6);+ expect(applyShellStreamEvents(seed, [remove(3, a), update(4, b)])).toBe(seed);+ expect(applyShellStreamEvents(seed, [])).toBe(seed);+ });++ it("does not advance the cursor for an unknown future event", () => {+ const events = [+ { kind: "future.event", sequence: 99 } as never,+ update(1, { ...a, title: "Changed" }),+ ];+ expect(applyShellStreamEvents(v2ShellSnapshot, events)).toEqual(+ events.reduce(applyShellStreamEvent, v2ShellSnapshot),+ );+ });+});diff --git a/packages/client-runtime/src/state/shellReducer.ts b/packages/client-runtime/src/state/shellReducer.tsindex 2d9647e85fc..bf8f7141b31 100644--- a/packages/client-runtime/src/state/shellReducer.ts+++ b/packages/client-runtime/src/state/shellReducer.ts@@ -191,3 +191,84 @@ export function applyShellStreamEvent(return snapshot;}}++/** Index a collection lazily and materialize it only if a delta changes its rows. */+function batchRows<T extends { readonly id: unknown }>(rows: ReadonlyArray<T>) {+ let byId: Map<T["id"], T> | undefined;+ let changed = false;+ const index = () => {+ if (byId === undefined) {+ byId = new Map();+ for (const row of rows) byId.set(row.id, row);+ }+ return byId;+ };+ return {+ get: (id: T["id"]) => index().get(id),+ set: (row: T) => {+ index().set(row.id, row);+ changed = true;+ },+ remove: (id: T["id"]) => {+ if (index().delete(id)) changed = true;+ },+ finish: () => (changed ? Array.from(index().values()) : rows),+ };+}++export type ShellStreamEvent = Exclude<+ OrchestrationV2ShellStreamItem,+ { readonly kind: "snapshot" } | { readonly kind: "synchronized" }+>;++/** Apply ordered deltas with one index and at most one new array per collection. */+export function applyShellStreamEvents(+ snapshot: OrchestrationV2ShellSnapshot,+ events: ReadonlyArray<ShellStreamEvent>,+): OrchestrationV2ShellSnapshot {+ // Avoid indexing the whole shell for the common single-event delivery.+ if (events.length === 1) return applyShellStreamEvent(snapshot, events[0]!);+ const projects = batchRows(snapshot.projects);+ const threads = batchRows(snapshot.threads);+ const archivedThreads = batchRows(snapshot.archivedThreads);+ let sequence = snapshot.snapshotSequence;+ for (const event of events) {+ if (event.sequence <= sequence) continue;+ switch (event.kind) {+ case "project.updated":+ projects.set(retainRepositoryIdentity(projects.get(event.project.id), event.project));+ break;+ case "project.removed":+ projects.remove(event.projectId);+ break;+ case "thread.updated": {+ const id = event.thread.id;+ if (event.location === "active") {+ const previous = threads.get(id);+ if (previous !== undefined && sameThreadShell(previous, event.thread)) break;+ threads.set(event.thread);+ } else {+ threads.remove(id);+ }+ // Legacy archive deltas remove rows from the shell; the archive is queried separately.+ archivedThreads.remove(id);+ break;+ }+ case "thread.removed":+ threads.remove(event.threadId);+ archivedThreads.remove(event.threadId);+ break;+ default:+ continue;+ }+ sequence = event.sequence;+ }+ if (sequence === snapshot.snapshotSequence) return snapshot;+ return {+ ...snapshot,+ snapshotSequence: sequence,+ projects: projects.finish(),+ threads: threads.finish(),+ archivedThreads: archivedThreads.finish(),+ };+}