TypeScript
perf(client): avoid full ordering scans for streamed replacements (#24264)
Julius Marminge7de9535a6c7b
diff --git a/packages/client-runtime/src/state/orchestrationV2Projection.test.ts b/packages/client-runtime/src/state/orchestrationV2Projection.test.tsindex 9d96d800143..e1274a36770 100644--- a/packages/client-runtime/src/state/orchestrationV2Projection.test.ts+++ b/packages/client-runtime/src/state/orchestrationV2Projection.test.ts@@ -555,3 +555,86 @@ it("does not scan every row against every run for a streaming item update", () =expect(next?.visibleTurnItems[0]).toBe(projection.visibleTurnItems[0]);expect(runReads).toBeLessThanOrEqual(100);});++it("does not scan ordering or positions for a streamed replacement", () => {+ const size = 100;+ let ordinalReads = 0;+ let positionReads = 0;+ const items = Array.from({ length: size }, (_, index) => ({+ ...commandItem(`item-${index}`, "before", index),+ get ordinal() {+ ordinalReads++;+ return index;+ },+ }));+ const rows = items.map((item, index) => ({+ item,+ get position() {+ positionReads++;+ return index;+ },+ visibility: "local" as const,+ sourceThreadId: threadId,+ sourceItemId: item.id,+ }));+ const payload = commandItem(`item-${size - 1}`, "after", size - 1);+ const next = applyOrchestrationV2ProjectionEvent(+ { ...emptyProjection, runs: [run], turnItems: items, visibleTurnItems: rows },+ {+ id: "stable-replacement",+ type: "turn-item.updated",+ threadId,+ occurredAt: now,+ payload,+ } as OrchestrationV2DomainEvent,+ );++ expect(ordinalReads).toBeLessThanOrEqual(2);+ expect(positionReads).toBeLessThanOrEqual(2);+ expect(next?.visibleTurnItems.at(-1)).toMatchObject({ item: payload, position: size - 1 });+ expect(next?.visibleTurnItems[0]).toBe(rows[0]);+ expect(items.at(-1)).toMatchObject({ output: "before" });+ expect(rows.at(-1)?.item).toBe(items.at(-1));+});++it("rechecks visibility when an existing item changes runs without changing ordinal", () => {+ const first = commandItem("item-first", "first", 1);+ const second = commandItem("item-second", "second", 2);+ const rolledBackRun = { ...run, id: RunId.make("rolled-back"), status: "rolled_back" as const };+ const projection = {+ ...emptyProjection,+ runs: [run, rolledBackRun],+ turnItems: [first, second],+ visibleTurnItems: [first, second].map((item, position) => ({+ item,+ position,+ visibility: "local" as const,+ sourceThreadId: threadId,+ sourceItemId: item.id,+ })),+ };+ const update = (payload: OrchestrationV2TurnItem) =>+ ({+ id: "visibility-update",+ type: "turn-item.updated",+ threadId,+ occurredAt: now,+ payload,+ }) as OrchestrationV2DomainEvent;+ const hidden = applyOrchestrationV2ProjectionEvent(+ projection,+ update({+ ...first,+ runId: rolledBackRun.id,+ }),+ );+ expect(hidden?.visibleTurnItems.map((row) => [row.item.id, row.position])).toEqual([+ [second.id, 0],+ ]);+ const restored = applyOrchestrationV2ProjectionEvent(hidden, update(first));+ expect(restored?.visibleTurnItems.map((row) => [row.item.id, row.position])).toEqual([+ [first.id, 0],+ [second.id, 1],+ ]);+ expect(projection.visibleTurnItems[0]?.item).toBe(first);+});diff --git a/packages/client-runtime/src/state/orchestrationV2Projection.ts b/packages/client-runtime/src/state/orchestrationV2Projection.tsindex d954e8a1eda..491d158700f 100644--- a/packages/client-runtime/src/state/orchestrationV2Projection.ts+++ b/packages/client-runtime/src/state/orchestrationV2Projection.ts@@ -15,6 +15,36 @@ export type ApplyOrchestrationV2ProjectionEventOptions = {readonly latestLocalTurnOrdinal?: number | null;};+// Only this exact pair differs at one index. Both keys are weak so hints+// neither retain streaming history nor apply to replacement snapshots.+const arrayReplacements = new WeakMap<+ ReadonlyArray<unknown>,+ WeakMap<ReadonlyArray<unknown>, number>+>();++export function getProjectionArrayReplacementIndex(+ previous: ReadonlyArray<unknown>,+ next: ReadonlyArray<unknown>,+): number | undefined {+ return arrayReplacements.get(previous)?.get(next);+}++function replaceProjectionArrayItem<T>(+ items: ReadonlyArray<T>,+ index: number,+ item: T,+): ReadonlyArray<T> {+ const next = items.slice();+ next[index] = item;+ let replacements = arrayReplacements.get(items);+ if (replacements === undefined) {+ replacements = new WeakMap();+ arrayReplacements.set(items, replacements);+ }+ replacements.set(next, index);+ return next;+}+function upsertEntity<T extends { readonly id: unknown }>(items: ReadonlyArray<T>,item: T,@@ -167,11 +197,12 @@ function upsertVisibleTurnItem(if (previous !== undefined &&previous.visibility === next.visibility &&- previous.sourceThreadId === next.sourceThreadId &&- previous.sourceItemId === next.sourceItemId &&- previous.item === item+ previous.sourceThreadId === next.sourceThreadId) {- return rows;+ if (previous.item === item) return rows;+ if (previous.item.ordinal === item.ordinal) {+ return replaceProjectionArrayItem(rows, index, { ...next, position: previous.position });+ }}if (index === -1 &&@@ -181,8 +212,8 @@ function upsertVisibleTurnItem(return rows;}// The item goes before the first later local row, as if its old row were- // removed first. One pass builds and renumbers the result: this runs for- // every streamed chunk of a thread that can hold thousands of rows.+ // removed first. Inserts, reorders, and inherited-to-local changes need+ // this ordering pass; replacements above preserve every other row.let insertion = rows.length;for (let candidate = 0; candidate < rows.length; candidate += 1) {const row = rows[candidate]!;@@ -326,9 +357,10 @@ export function applyOrchestrationV2ProjectionEvent() {return projection;}- const turnItems = [...projection.turnItems];- if (itemIndex === -1) turnItems.push(event.payload);- else turnItems[itemIndex] = event.payload;+ const turnItems =+ itemIndex === -1+ ? [...projection.turnItems, event.payload]+ : replaceProjectionArrayItem(projection.turnItems, itemIndex, event.payload);const next = { ...base, turnItems };// Only interrupt requests can change another item's visibility. Streaming// text/tool updates must not recheck every row against every run.diff --git a/packages/client-runtime/src/state/threadDetail.test.ts b/packages/client-runtime/src/state/threadDetail.test.tsindex 68998403056..8fc01839183 100644--- a/packages/client-runtime/src/state/threadDetail.test.ts+++ b/packages/client-runtime/src/state/threadDetail.test.ts@@ -1,5 +1,6 @@import {EnvironmentId,+ EventId,MessageId,RunId,TurnItemId,@@ -12,7 +13,9 @@ import * as Option from "effect/Option";import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";import { v2Now, v2Projection, v2ThreadId } from "./orchestrationV2TestFixtures.ts";+import { applyOrchestrationV2ProjectionEvent } from "./orchestrationV2Projection.ts";import { createEnvironmentThreadDetailAtoms, sameThreadStructure } from "./threadDetail.ts";+import { mergeOlderHistoryIntoProjection } from "./threadHistoryMerge.ts";import { EMPTY_ENVIRONMENT_THREAD_STATE } from "./threadState.ts";const later = DateTime.makeUnsafe("2026-06-20T00:00:01.000Z");@@ -132,10 +135,14 @@ describe("quietThreadAtom", () => {registry.mount(quietAtom);return {read: () => registry.get(quietAtom),- push: (projection: OrchestrationV2ThreadProjection) =>+ [Symbol.dispose]: () => registry.dispose(),+ push: (projection: OrchestrationV2ThreadProjection | null) =>registry.set(stateAtom,- AsyncResult.success({ ...EMPTY_ENVIRONMENT_THREAD_STATE, data: Option.some(projection) }),+ AsyncResult.success({+ ...EMPTY_ENVIRONMENT_THREAD_STATE,+ data: Option.fromNullishOr(projection),+ }),),};}@@ -158,6 +165,22 @@ describe("quietThreadAtom", () => {expect(next?.projection.turnItems[0]).toMatchObject({ status: "completed", streaming: false });});+ it("discards structure held before the thread resets", () => {+ const initial = withItem(assistant);+ using thread = setup(initial);+ const first = thread.read();+ thread.push(replaceItem(initial, { ...assistant, text: "Hello" }));+ expect(thread.read()).toBe(first);+ thread.push(null);+ expect(thread.read()).toBeNull();+ const reset = withItem({ ...assistant, title: "Restored", text: "New snapshot" });+ thread.push(reset);+ expect(thread.read()).not.toBe(first);+ expect(thread.read()?.projection.turnItems[0]).toMatchObject({ title: "Restored" });+ thread.push(replaceItem(reset, { ...assistant, title: "Restored", text: "More text" }));+ expect(thread.read()?.projection.turnItems[0]).toMatchObject({ title: "Restored" });+ });+it("leaves out the fields that streaming moves", () => {const thread = setup(withItem(assistant));const projection = thread.read()?.projection;@@ -173,3 +196,120 @@ describe("quietThreadAtom", () => {});});});++it("only compares replaced entries in a streamed reducer delta", () => {+ const size = 100;+ let slotReads = 0;+ const countReads = <T>(items: ReadonlyArray<T>): ReadonlyArray<T> =>+ new Proxy(items, {+ get(target, key, receiver) {+ if (typeof key === "string" && /^\d+$/.test(key)) slotReads++;+ return Reflect.get(target, key, receiver);+ },+ });+ const items = Array.from({ length: size }, (_, index) => ({+ ...assistant,+ id: TurnItemId.make(`item-${index}`),+ ordinal: index,+ }));+ const before = {+ ...v2Projection,+ turnItems: countReads(items),+ visibleTurnItems: countReads(+ items.map((item, position) => ({+ item,+ position,+ visibility: "local" as const,+ sourceThreadId: v2ThreadId,+ sourceItemId: item.id,+ })),+ ),+ };+ const next = applyOrchestrationV2ProjectionEvent(before, {+ id: EventId.make("text-delta"),+ type: "turn-item.updated",+ threadId: v2ThreadId,+ occurredAt: later,+ payload: { ...items.at(-1)!, text: "Hello", updatedAt: later },+ });+ slotReads = 0;++ expect(sameThreadStructure(before, next!)).toBe(true);+ expect(slotReads).toBeLessThanOrEqual(2);+});++function replaceItem(projection: OrchestrationV2ThreadProjection, item: OrchestrationV2TurnItem) {+ return applyOrchestrationV2ProjectionEvent(projection, {+ id: EventId.make(`event-${item.id}`),+ type: "turn-item.updated",+ threadId: v2ThreadId,+ occurredAt: item.updatedAt,+ payload: item,+ })!;+}++it("matches full structure comparisons across streamed, batched, and reordered updates", () => {+ const message = { ...assistant, ordinal: 2 };+ const reasoning = {+ ...assistant,+ id: TurnItemId.make("reasoning"),+ type: "reasoning" as const,+ ordinal: 1,+ };+ const initial = mergeOlderHistoryIntoProjection(withItem(message), [+ withItem(reasoning).visibleTurnItems[0]!,+ ]);+ const updates = [+ { ...message, text: "Hello", updatedAt: later },+ { ...reasoning, text: "Thinking", updatedAt: later },+ { ...reasoning, text: "Done", status: "completed" as const, streaming: false },+ { ...message, text: "Hello there", updatedAt: later },+ { ...message, text: "Hello there", ordinal: 0 },+ { ...message, text: "More text", ordinal: 0 },+ { ...message, text: "More text", ordinal: 2 },+ { ...message, text: "More text", runId: RunId.make("another-run") },+ ];+ const projections = [initial];+ const withoutHints = (projection: OrchestrationV2ThreadProjection) => ({+ ...projection,+ turnItems: projection.turnItems.slice(),+ visibleTurnItems: projection.visibleTurnItems.slice(),+ });+ const consecutive: boolean[] = [];+ for (const item of updates) {+ const previous = projections.at(-1)!;+ const next = replaceItem(previous, item);+ consecutive.push(sameThreadStructure(previous, next));+ // All earlier snapshots include readers that skip one or several updates in a batch.+ for (const before of projections) {+ expect(sameThreadStructure(before, next)).toBe(+ sameThreadStructure(withoutHints(before), withoutHints(next)),+ );+ }+ projections.push(next);+ }++ // A resumed snapshot can reuse item ids while changing a different row.+ const snapshot = withoutHints(projections[1]!);+ const resumed = replaceItem(snapshot, { ...reasoning, title: "Restored reasoning" });+ const sibling = replaceItem(initial, { ...message, text: "Another stream" });+ const reconnected = replaceItem(resumed, { ...message, text: "Resumed stream" });+ for (const before of [initial, sibling, projections[1]!, resumed]) {+ expect(sameThreadStructure(before, reconnected)).toBe(+ sameThreadStructure(withoutHints(before), withoutHints(reconnected)),+ );+ }+ expect(sameThreadStructure(sibling, reconnected)).toBe(false);+ expect(sameThreadStructure(resumed, reconnected)).toBe(true);++ expect(consecutive).toEqual([true, true, false, true, false, true, false, false]);+ expect(sameThreadStructure(initial, projections[4]!)).toBe(false);+ expect(projections[5]!.visibleTurnItems.map((row) => [row.item.id, row.position])).toEqual([+ [assistant.id, 0],+ [reasoning.id, 1],+ ]);+ expect(projections[7]!.visibleTurnItems.map((row) => [row.item.id, row.position])).toEqual([+ [reasoning.id, 0],+ [assistant.id, 1],+ ]);+});diff --git a/packages/client-runtime/src/state/threadDetail.ts b/packages/client-runtime/src/state/threadDetail.tsindex 57bdd36027a..a53494ebc59 100644--- a/packages/client-runtime/src/state/threadDetail.ts+++ b/packages/client-runtime/src/state/threadDetail.ts@@ -33,6 +33,7 @@ import {type PendingThreadRequests,} from "./threadRequests.ts";import { arrayElementsEqual, parseThreadKey, threadKey } from "./entities.ts";+import { getProjectionArrayReplacementIndex } from "./orchestrationV2Projection.ts";const EMPTY_VISIBLE_TURN_ITEMS: OrchestrationV2ThreadProjection["visibleTurnItems"] = Object.freeze([],@@ -123,6 +124,29 @@ function sameTurnItemStructure(previous: TurnItem, next: TurnItem): boolean {return sameApartFromStripped(sameTurnItem, previous, structure, next);}+function sameProjectionArray<T>(+ previous: ReadonlyArray<T>,+ next: ReadonlyArray<T>,+ same: (previous: T, next: T) => boolean,+): boolean {+ if (previous === next) return true;+ if (previous.length !== next.length) return false;+ const replacedIndex = getProjectionArrayReplacementIndex(previous, next);+ if (replacedIndex !== undefined) return same(previous[replacedIndex]!, next[replacedIndex]!);+ return previous.every((item, index) => same(item, next[index]!));+}++function sameVisibleTurnItemStructure(before: VisibleTurnItem, after: VisibleTurnItem): boolean {+ return (+ before === after ||+ (before.position === after.position &&+ before.visibility === after.visibility &&+ before.sourceThreadId === after.sourceThreadId &&+ before.sourceItemId === after.sourceItemId &&+ sameTurnItemStructure(before.item, after.item))+ );+}+/*** Whether `previous` and `next` have the same ThreadStructure: they differ* only by text streamed into existing assistant and reasoning items or by a@@ -156,32 +180,14 @@ export function sameThreadStructure() {return false;}- if (- previous.turnItems.length !== next.turnItems.length ||- previous.visibleTurnItems.length !== next.visibleTurnItems.length- ) {- return false;- }- for (let index = 0; index < next.turnItems.length; index += 1) {- if (!sameTurnItemStructure(previous.turnItems[index]!, next.turnItems[index]!)) {- return false;- }- }- for (let index = 0; index < next.visibleTurnItems.length; index += 1) {- const before = previous.visibleTurnItems[index]!;- const after = next.visibleTurnItems[index]!;- if (before === after) continue;- if (- before.position !== after.position ||- before.visibility !== after.visibility ||- before.sourceThreadId !== after.sourceThreadId ||- before.sourceItemId !== after.sourceItemId ||- !sameTurnItemStructure(before.item, after.item)- ) {- return false;- }- }- return true;+ return (+ sameProjectionArray(previous.turnItems, next.turnItems, sameTurnItemStructure) &&+ sameProjectionArray(+ previous.visibleTurnItems,+ next.visibleTurnItems,+ sameVisibleTurnItemStructure,+ )+ );}export function createEnvironmentThreadDetailAtoms<E>(@@ -233,7 +239,7 @@ export function createEnvironmentThreadDetailAtoms<E>(projection: toThreadStructure(next.projection),};}- // Compared against the latest projection, a delta only compares the item it replaced.+ // Comparing the latest projection lets consecutive replacements bypass history scans.previousProjection = next?.projection ?? null;return previous;}).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-quiet-thread:${key}`));