TypeScript
perf(orchestration): thread snapshots send each long ID once (#24643)
Theo Browne80455376f01f
diff --git a/apps/server/src/orchestration-v2/ThreadStream.ts b/apps/server/src/orchestration-v2/ThreadStream.tsindex 8e8323bcff7..3c4baab80ef 100644--- a/apps/server/src/orchestration-v2/ThreadStream.ts+++ b/apps/server/src/orchestration-v2/ThreadStream.ts@@ -41,6 +41,7 @@ export function boundedSnapshotResponseFields(input: {readonly bounded: BoundedProjectionResult;readonly compactTurnItems: boolean;readonly dedupeBodies: boolean;+ readonly compactIds: boolean;}) {const { bounded } = input;// Dedupe keeps shared items one object, which the compaction's identity check needs.@@ -54,6 +55,7 @@ export function boundedSnapshotResponseFields(input: {hasMoreHistory: bounded.hasMoreHistory,latestLocalTurnOrdinal: bounded.latestLocalTurnOrdinal,...(compactProjection === null ? {} : { turnItemsOmitLocalVisible: true as const }),+ ...(input.compactIds ? { idTable: true as const } : {}),};}@@ -62,6 +64,7 @@ export function buildBoundedThreadStreamSnapshot(input: {readonly projection: OrchestrationV2ThreadProjection;readonly compactTurnItems?: boolean;readonly dedupeBodies?: boolean;+ readonly compactIds?: boolean;}): ThreadSnapshotStreamItem {const bounded = buildBoundedThreadProjection({snapshotSequence: input.snapshotSequence,@@ -74,6 +77,7 @@ export function buildBoundedThreadStreamSnapshot(input: {bounded,compactTurnItems: input.compactTurnItems === true,dedupeBodies: input.dedupeBodies === true,+ compactIds: input.compactIds === true,}),};}diff --git a/apps/server/src/orchestration-v2/boundedSnapshotTransport.test.ts b/apps/server/src/orchestration-v2/boundedSnapshotTransport.test.tsindex ec22a06a193..220e707b6c7 100644--- a/apps/server/src/orchestration-v2/boundedSnapshotTransport.test.ts+++ b/apps/server/src/orchestration-v2/boundedSnapshotTransport.test.ts@@ -15,6 +15,7 @@ import {ORCHESTRATION_PROTOCOL_HEADER,ORCHESTRATION_PROTOCOL_VERSION,OrchestrationV2ThreadBoundedSnapshot,+ OrchestrationV2ThreadHistoryPage,OrchestrationV2ThreadStreamItem,ProjectId,ProviderDriverKind,@@ -53,6 +54,9 @@ import * as ThreadManagementService from "./ThreadManagementService.ts";const decodeBounded = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.toCodecJson(OrchestrationV2ThreadBoundedSnapshot)),);+const decodeHistoryPage = Schema.decodeUnknownSync(+ Schema.fromJsonString(Schema.toCodecJson(OrchestrationV2ThreadHistoryPage)),+);const decodeStreamItem = Schema.decodeUnknownSync(Schema.toCodecJson(OrchestrationV2ThreadStreamItem),);@@ -81,6 +85,10 @@ const management = Layer.unwrap(getThreadSnapshot: (id) => projections.getThreadSnapshot(id).pipe(Effect.orDie),getThreadSnapshotWindow: (id, options) =>projections.getThreadSnapshotWindow(id, options).pipe(Effect.orDie),+ getThreadHistoryPage: (id, cursor, throughEntryId, conversationOnly) =>+ projections+ .getThreadHistoryPage(id, cursor, throughEntryId, conversationOnly)+ .pipe(Effect.orDie),streamStoredEventsFrom: (input) =>input?.threadId === BODIES ? Stream.fromIterable(bodiesLiveTail()) : Stream.empty,});@@ -492,6 +500,46 @@ it.layer(TestLayer)("compact bounded snapshot transport", (it) => {),);+ it.effect("HTTP: the ID table is opt-in and decodes to the same snapshot", () =>+ withHttp(async (get) => {+ const base = `/api/orchestration/threads/${encodeURIComponent(threadId)}/bounded?compactTurnItems=1`;+ const plainBody = await (await get(base)).text();+ const tableBody = await (await get(`${base}&compactIds=1`)).text();+ const wire = JSON.parse(tableBody);++ assert.notProperty(JSON.parse(plainBody), "ids");+ assert.isArray(wire.ids);+ assert.isNumber(wire.projection.visibleTurnItems[0].item.id);+ assert.isNumber(wire.projection.thread.id);+ assert.isBelow(tableBody.length, plainBody.length);+ const decoded = decodeBounded(tableBody);+ assert.deepStrictEqual(decoded, decodeBounded(plainBody));++ // Only the long thread has older history to page.+ if (threadId !== LONG) return;+ assert.isNotNull(decoded.historyCursor);+ const history = `/api/orchestration/threads/${encodeURIComponent(threadId)}/history?cursor=${encodeURIComponent(decoded.historyCursor ?? "")}`;+ const plainPage = await (await get(history)).text();+ const tablePage = await (await get(`${history}&compactIds=1`)).text();+ assert.isArray(JSON.parse(tablePage).ids);+ const page = decodeHistoryPage(tablePage);+ assert.isAbove(page.items.length, 0);+ assert.deepStrictEqual(page, decodeHistoryPage(plainPage));+ }),+ );++ it.effect("WS: the ID table is opt-in and decodes to the same snapshot", () =>+ Effect.gen(function* () {+ const input = { threadId, acceptBoundedSnapshot: true, acceptCompactTurnItems: true };+ const plain = yield* firstSnapshot(input);+ const table = yield* firstSnapshot({ ...input, acceptCompactIds: true });++ assert.notProperty(encodeStreamItem(plain.raw), "ids");+ assert.property(encodeStreamItem(table.raw), "ids");+ assert.deepStrictEqual(table.decoded, plain.decoded);+ }),+ );+it.effect("WS: bounded snapshots stay unchanged unless the client opts in", () =>Effect.gen(function* () {const legacy = yield* firstSnapshot({ threadId, acceptBoundedSnapshot: true });@@ -546,6 +594,15 @@ it.layer(TestLayer)("compact bounded snapshot transport", (it) => {boundedSnapshotProjection(decodeBounded(dedupedBody)),boundedSnapshotProjection(decodeBounded(compactBody)),);+ // The client sends both opt-ins: bodies restore after the ID table resolves.+ const tabledBody = await (+ await get(`${base}?compactTurnItems=1&dedupeBodies=1&compactIds=1`)+ ).text();+ assert.property(JSON.parse(tabledBody), "ids");+ assert.deepStrictEqual(+ boundedSnapshotProjection(decodeBounded(tabledBody)),+ boundedSnapshotProjection(decodeBounded(compactBody)),+ );}),);diff --git a/apps/server/src/orchestration-v2/http.ts b/apps/server/src/orchestration-v2/http.tsindex 818698af746..772fa1710b9 100644--- a/apps/server/src/orchestration-v2/http.ts+++ b/apps/server/src/orchestration-v2/http.ts@@ -228,6 +228,7 @@ export const layer = HttpApiBuilder.group(bounded,compactTurnItems: args.query.compactTurnItems === "1",dedupeBodies: args.query.dedupeBodies === "1",+ compactIds: args.query.compactIds === "1",}),};}),@@ -252,6 +253,9 @@ export const layer = HttpApiBuilder.group(args.query.view === "conversation",).pipe(+ Effect.map((page) =>+ args.query.compactIds === "1" ? { ...page, idTable: true as const } : page,+ ),traceLocalHandlerWork,Effect.catch(Effect.fnUntraced(function* (cause) {diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.tsindex 6eb6febbe9e..69204e9cf79 100644--- a/apps/server/src/ws.ts+++ b/apps/server/src/ws.ts@@ -787,6 +787,7 @@ export const subscribeOrchestrationV2Thread = Effect.fn("ws.orchestrationV2.subsreadonly acceptBoundedSnapshot?: boolean;readonly acceptCompactTurnItems?: boolean;readonly acceptDedupedBodies?: boolean;+ readonly acceptCompactIds?: boolean;}) {const threadManagement = yield* ThreadManagementService.ThreadManagementService;const dedupeBodies = input.acceptDedupedBodies === true;@@ -890,6 +891,7 @@ export const subscribeOrchestrationV2Thread = Effect.fn("ws.orchestrationV2.subs...snapshot,compactTurnItems: input.acceptCompactTurnItems === true,dedupeBodies,+ compactIds: input.acceptCompactIds === true,}): (() => {const projection = projectThreadProjectionForWire(snapshot.projection);diff --git a/packages/client-runtime/src/state/boundedThreadSnapshotHttp.test.ts b/packages/client-runtime/src/state/boundedThreadSnapshotHttp.test.tsindex 52ce11411af..c4b52fd8d3e 100644--- a/packages/client-runtime/src/state/boundedThreadSnapshotHttp.test.ts+++ b/packages/client-runtime/src/state/boundedThreadSnapshotHttp.test.ts@@ -1,7 +1,8 @@-import { ThreadId } from "@t3tools/contracts";+import { OrchestrationV2ThreadBoundedSnapshot, ThreadId } from "@t3tools/contracts";import { describe, expect, it } from "@effect/vitest";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";+import * as Schema from "effect/Schema";import { PrimaryConnectionTarget, type PreparedConnection } from "../connection/model.ts";import * as RpcHttp from "../rpc/http.ts";@@ -117,22 +118,29 @@ const boundedBody = (compact: boolean) => ({latestLocalTurnOrdinal: 2,...(compact ? { turnItemsOmitLocalVisible: true } : {}),});+const BoundedJson = Schema.toCodecJson(OrchestrationV2ThreadBoundedSnapshot);+const idTableBody = () => {+ const snapshot = Schema.decodeUnknownSync(BoundedJson)(boundedBody(true));+ return Schema.encodeSync(BoundedJson)({ ...snapshot, idTable: true });+};describe("boundedThreadSnapshotLoader", () => {it.effect.each([- ["an older server that ignores the opt-in", false],- ["a server that sends compact turnItems", true],- ] as const)("requests compact turnItems and loads %s", ([, compact]) => {+ ["an older server that ignores the opt-in", () => boundedBody(false)],+ ["a server that sends compact turnItems", () => boundedBody(true)],+ ["a server that also sends an ID table", idTableBody],+ ] as const)("requests compact turnItems and loads %s", ([, body]) => {const urls: string[] = [];const fetchFn = ((input: RequestInfo | URL) => {urls.push(String(input));- return Promise.resolve(Response.json(boundedBody(compact)));+ return Promise.resolve(Response.json(body()));}) satisfies typeof fetch;return Effect.gen(function* () {const loader = yield* ThreadSnapshotLoader.ThreadSnapshotLoader;const result = yield* loader.load(PREPARED, THREAD_ID);expect(new URL(urls[0]!).searchParams.get("compactTurnItems")).toBe("1");+ expect(new URL(urls[0]!).searchParams.get("compactIds")).toBe("1");expect(result._tag).toBe("present");if (result._tag !== "present") return;expect(result.snapshot.projection.turnItems.map((item) => String(item.id))).toEqual([diff --git a/packages/client-runtime/src/state/boundedThreadSnapshotHttp.ts b/packages/client-runtime/src/state/boundedThreadSnapshotHttp.tsindex 5c57eec1faf..1d6e4af118d 100644--- a/packages/client-runtime/src/state/boundedThreadSnapshotHttp.ts+++ b/packages/client-runtime/src/state/boundedThreadSnapshotHttp.ts@@ -30,7 +30,7 @@ export const fetchEnvironmentBoundedThreadSnapshot = Effect.fn(}) {const endpoint = {params: { threadId: input.threadId },- query: { compactTurnItems: "1", dedupeBodies: "1" },+ query: { compactTurnItems: "1", dedupeBodies: "1", compactIds: "1" },};return yield* executeAuthenticatedEnvironmentHttpRequest({...input,diff --git a/packages/client-runtime/src/state/threadHistoryHttp.ts b/packages/client-runtime/src/state/threadHistoryHttp.tsindex 2d99d7dbf0e..a9714172e44 100644--- a/packages/client-runtime/src/state/threadHistoryHttp.ts+++ b/packages/client-runtime/src/state/threadHistoryHttp.ts@@ -28,6 +28,7 @@ export const fetchEnvironmentThreadHistoryPage = Effect.fn(params: { threadId: input.threadId },query: {cursor: input.cursor,+ compactIds: "1",...(input.view === undefined ? {} : { view: input.view }),...(input.throughEntryId === undefined ? {} : { throughEntryId: input.throughEntryId }),},diff --git a/packages/client-runtime/src/state/threads.ts b/packages/client-runtime/src/state/threads.tsindex ef2393c0255..3bfa1ffbb40 100644--- a/packages/client-runtime/src/state/threads.ts+++ b/packages/client-runtime/src/state/threads.ts@@ -961,7 +961,11 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make...(canResume ? { afterSequence: sequence } : {}),...(supportsCompletionMarker ? { requestCompletionMarker: true as const } : {}),...(acceptBoundedSnapshot- ? { acceptBoundedSnapshot: true as const, acceptCompactTurnItems: true as const }+ ? {+ acceptBoundedSnapshot: true as const,+ acceptCompactTurnItems: true as const,+ acceptCompactIds: true as const,+ }: {}),acceptDedupedBodies: true as const,};diff --git a/packages/contracts/src/baseSchemas.ts b/packages/contracts/src/baseSchemas.tsindex 79723716194..f96c5a380b2 100644--- a/packages/contracts/src/baseSchemas.ts+++ b/packages/contracts/src/baseSchemas.ts@@ -4,12 +4,19 @@ import * as Schema from "effect/Schema";import * as SchemaGetter from "effect/SchemaGetter";import * as SchemaTransformation from "effect/SchemaTransformation";+// Hermes copies the string on every `trim()`, even when nothing changes.+// Returning the original keeps repeated IDs shared after decode.+const trim = (value: string) => {+ const trimmed = value.trim();+ return trimmed.length === value.length ? value : trimmed;+};+export const TrimmedString = Schema.String.pipe(Schema.decodeTo(Schema.String,SchemaTransformation.transformEffect({- decode: (value) => Effect.succeed(value.trim()),- encode: (value) => Effect.succeed(value.trim()),+ decode: (value) => Effect.succeed(trim(value)),+ encode: (value) => Effect.succeed(trim(value)),}),),);diff --git a/packages/contracts/src/environmentHttp.ts b/packages/contracts/src/environmentHttp.tsindex 508d063c021..51634d78eef 100644--- a/packages/contracts/src/environmentHttp.ts+++ b/packages/contracts/src/environmentHttp.ts@@ -674,12 +674,14 @@ const EnvironmentOrchestrationShellSnapshotQuery = Schema.Struct({const EnvironmentOrchestrationThreadBoundedSnapshotQuery = Schema.Struct({compactTurnItems: Schema.optionalKey(Schema.String),dedupeBodies: Schema.optionalKey(Schema.String),+ compactIds: Schema.optionalKey(Schema.String),});const EnvironmentOrchestrationThreadHistoryQuery = Schema.Struct({cursor: TrimmedNonEmptyString,throughEntryId: Schema.optional(TrimmedNonEmptyString),view: Schema.optional(Schema.Literals(["conversation", "activity"])),+ compactIds: Schema.optionalKey(Schema.String),});const EnvironmentOrchestrationThreadHistoryErrors = [diff --git a/packages/contracts/src/orchestrationV2.test.ts b/packages/contracts/src/orchestrationV2.test.tsindex c193ccd943e..2414d3cd019 100644--- a/packages/contracts/src/orchestrationV2.test.ts+++ b/packages/contracts/src/orchestrationV2.test.ts@@ -175,6 +175,24 @@ describe("orchestration V2 contracts", () => {if (snapshot?.kind !== "snapshot") throw new Error("expected a snapshot");expect(snapshot.projection.turnItems.map((turnItem) => turnItem.id)).toEqual(["item-known"]);expect(snapshot.projection.visibleTurnItems.map((row) => row.item.id)).toEqual(["item-known"]);+ // The same snapshot with an ID table: refs resolve before unknown items are skipped.+ const tabled = (turnItem: { readonly id: string }, ref: number) => ({ ...turnItem, id: ref });+ const [tabledSnapshot] = decodeWireItems([+ {+ kind: "snapshot",+ snapshotSequence: 1,+ projection: {+ ...projection,+ turnItems: [tabled(future, 0), tabled(known, 1)],+ visibleTurnItems: [+ { ...projected(0, future), sourceItemId: 0, item: tabled(future, 0) },+ { ...projected(1, known), sourceItemId: 1, item: tabled(known, 1) },+ ],+ },+ ids: ["item-future", "item-known"],+ },+ ]);+ expect(tabledSnapshot).toEqual(snapshot);expect(futureEvent).toEqual({kind: "unknown-event",sequence: 2,diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.tsindex f909de7fabd..6aa4ea7bbe6 100644--- a/packages/contracts/src/orchestrationV2.ts+++ b/packages/contracts/src/orchestrationV2.ts@@ -1,4 +1,5 @@import { OrchestrationMessageContext } from "./composerContext.ts";+import { withRecordIdTable } from "./orchestrationV2IdTable.ts";import * as Effect from "effect/Effect";import * as Schema from "effect/Schema";import * as SchemaAST from "effect/SchemaAST";@@ -3399,9 +3400,16 @@ export const OrchestrationV2SubscribeThreadInput = Schema.Struct({acceptCompactTurnItems: Schema.optionalKey(Schema.Boolean),/** The client restores `*Omitted` bodies from records it already holds. */acceptDedupedBodies: Schema.optionalKey(Schema.Boolean),+ acceptCompactIds: Schema.optionalKey(Schema.Boolean),});export type OrchestrationV2SubscribeThreadInput = typeof OrchestrationV2SubscribeThreadInput.Type;+/**+ * Server-side only: set it on a response for a client that opted in, and the+ * `withRecordIdTable` codec sends that response with an ID table.+ */+const IdTableMarker = Schema.optionalKey(Schema.Literal(true));+export const OrchestrationV2ThreadDetailSnapshot = Schema.Struct({snapshotSequence: NonNegativeInt,projection: OrchestrationV2ThreadProjection,@@ -3413,33 +3421,41 @@ export const OrchestrationV2ThreadDetailSnapshot = Schema.Struct({export type OrchestrationV2ThreadDetailSnapshot = typeof OrchestrationV2ThreadDetailSnapshot.Type;/** Keep historyCursor opaque; resume events with afterSequence = snapshotSequence. */-export const OrchestrationV2ThreadBoundedSnapshot = Schema.Struct({- snapshotSequence: NonNegativeInt,- projection: OrchestrationV2ThreadProjection,- historyCursor: Schema.NullOr(TrimmedNonEmptyString),- hasMoreHistory: Schema.Boolean,- latestLocalTurnOrdinal: Schema.NullOr(NonNegativeInt),- /**- * Set only for clients that opted in: `projection.turnItems` omits the items- * of local visible rows, which lead the full list. Clients must restore them- * with `boundedSnapshotProjection` before using the projection.- */- turnItemsOmitLocalVisible: Schema.optionalKey(Schema.Literal(true)),-});+export const OrchestrationV2ThreadBoundedSnapshot = withRecordIdTable(+ Schema.Struct({+ snapshotSequence: NonNegativeInt,+ projection: OrchestrationV2ThreadProjection,+ historyCursor: Schema.NullOr(TrimmedNonEmptyString),+ hasMoreHistory: Schema.Boolean,+ latestLocalTurnOrdinal: Schema.NullOr(NonNegativeInt),+ /**+ * Set only for clients that opted in: `projection.turnItems` omits the items+ * of local visible rows, which lead the full list. Clients must restore them+ * with `boundedSnapshotProjection` before using the projection.+ */+ turnItemsOmitLocalVisible: Schema.optionalKey(Schema.Literal(true)),+ idTable: IdTableMarker,+ }),+ () => "projection",+);export type OrchestrationV2ThreadBoundedSnapshot = typeof OrchestrationV2ThreadBoundedSnapshot.Type;-export const OrchestrationV2ThreadHistoryPage = Schema.Struct({- snapshotSequence: NonNegativeInt,- items: projectedTurnItemArray(- OrchestrationV2ProjectedTurnItem,- OrchestrationV2ProjectedTurnItem.mapFields((fields) => ({- ...fields,- item: ForwardCompatibleUnion(OrchestrationV2TurnItem.members, "type"),- })),- ),- nextCursor: Schema.NullOr(TrimmedNonEmptyString),- hasMoreHistory: Schema.Boolean,-});+export const OrchestrationV2ThreadHistoryPage = withRecordIdTable(+ Schema.Struct({+ snapshotSequence: NonNegativeInt,+ items: projectedTurnItemArray(+ OrchestrationV2ProjectedTurnItem,+ OrchestrationV2ProjectedTurnItem.mapFields((fields) => ({+ ...fields,+ item: ForwardCompatibleUnion(OrchestrationV2TurnItem.members, "type"),+ })),+ ),+ nextCursor: Schema.NullOr(TrimmedNonEmptyString),+ hasMoreHistory: Schema.Boolean,+ idTable: IdTableMarker,+ }),+ () => null,+);export type OrchestrationV2ThreadHistoryPage = typeof OrchestrationV2ThreadHistoryPage.Type;const knownDomainEventTypes: ReadonlySet<string> = new Set(@@ -3486,26 +3502,30 @@ const OrchestrationV2UnknownThreadStreamEvent = Schema.Struct({),);-export const OrchestrationV2ThreadStreamItem = Schema.Union([- Schema.Struct({- kind: Schema.Literal("synchronized"),- }),- Schema.Struct({- kind: Schema.Literal("snapshot"),- snapshotSequence: NonNegativeInt,- projection: OrchestrationV2ThreadProjection,- historyCursor: Schema.optionalKey(Schema.NullOr(TrimmedNonEmptyString)),- hasMoreHistory: Schema.optionalKey(Schema.Boolean),- latestLocalTurnOrdinal: Schema.optionalKey(Schema.NullOr(NonNegativeInt)),- turnItemsOmitLocalVisible: Schema.optionalKey(Schema.Literal(true)),- }),- Schema.Struct({- kind: Schema.Literal("event"),- sequence: NonNegativeInt,- event: OrchestrationV2DomainEvent,- }),- OrchestrationV2UnknownThreadStreamEvent,-]);+export const OrchestrationV2ThreadStreamItem = withRecordIdTable(+ Schema.Union([+ Schema.Struct({+ kind: Schema.Literal("synchronized"),+ }),+ Schema.Struct({+ kind: Schema.Literal("snapshot"),+ snapshotSequence: NonNegativeInt,+ projection: OrchestrationV2ThreadProjection,+ historyCursor: Schema.optionalKey(Schema.NullOr(TrimmedNonEmptyString)),+ hasMoreHistory: Schema.optionalKey(Schema.Boolean),+ latestLocalTurnOrdinal: Schema.optionalKey(Schema.NullOr(NonNegativeInt)),+ turnItemsOmitLocalVisible: Schema.optionalKey(Schema.Literal(true)),+ idTable: IdTableMarker,+ }),+ Schema.Struct({+ kind: Schema.Literal("event"),+ sequence: NonNegativeInt,+ event: OrchestrationV2DomainEvent,+ }),+ OrchestrationV2UnknownThreadStreamEvent,+ ]),+ (item) => (item.kind === "snapshot" ? "projection" : undefined),+);export type OrchestrationV2ThreadStreamItem = typeof OrchestrationV2ThreadStreamItem.Type;export class OrchestrationV2DispatchCommandError extends Schema.TaggedError<OrchestrationV2DispatchCommandError>()(diff --git a/packages/contracts/src/orchestrationV2IdTable.test.ts b/packages/contracts/src/orchestrationV2IdTable.test.tsnew file mode 100644index 00000000000..6bd2b625ce5--- /dev/null+++ b/packages/contracts/src/orchestrationV2IdTable.test.ts@@ -0,0 +1,63 @@+import { describe, expect, it } from "@effect/vitest";+import * as Schema from "effect/Schema";++import { withRecordIdTable } from "./orchestrationV2IdTable.ts";++const Page = withRecordIdTable(+ Schema.Struct({+ rows: Schema.Array(+ Schema.Struct({+ id: Schema.String,+ count: Schema.Number,+ parentIds: Schema.Array(Schema.String),+ mergedId: Schema.optional(Schema.String),+ item: Schema.Struct({ ownerId: Schema.NullOr(Schema.String), legacyId: Schema.Number }),+ }),+ ),+ idTable: Schema.optionalKey(Schema.Literal(true)),+ }),+ () => null,+);+const encode = Schema.encodeSync(Schema.toCodecJson(Page));+const decode = Schema.decodeUnknownSync(Schema.toCodecJson(Page));++describe("record ID table", () => {+ it("interns record ID slots and restores them exactly, numbers included", () => {+ const value = {+ rows: [+ { id: "row:a", count: 7, parentIds: ["row:b"], item: { ownerId: "row:b", legacyId: 3 } },+ { id: "row:b", count: 3, parentIds: [], item: { ownerId: null, legacyId: 0 } },+ ],+ };+ const wire = JSON.parse(JSON.stringify(encode({ ...value, idTable: true })));++ expect(wire).toEqual({+ rows: [+ { id: 0, count: 7, parentIds: [1], item: { ownerId: 1, legacyId: 2 } },+ { id: 1, count: 3, parentIds: [], item: { ownerId: null, legacyId: 3 } },+ ],+ ids: ["row:a", "row:b", 3, 0],+ });+ expect(decode(wire)).toEqual(value);+ // The table is consumed, so a second decode of the same object cannot remap numbers.+ expect(decode(wire)).toEqual(value);+ });++ it("rejects an index outside the table, even in an optional slot", () => {+ const wire = {+ rows: [{ id: 0, count: 1, parentIds: [], mergedId: 5, item: { ownerId: null, legacyId: 0 } }],+ ids: ["row:a"],+ };++ expect(() => decode(wire)).toThrow(/mergedId/);+ });++ it("sends and reads the plain form without the marker", () => {+ const value = {+ rows: [{ id: "row:a", count: 1, parentIds: [], item: { ownerId: null, legacyId: 1 } }],+ };++ expect(encode(value)).toEqual(value);+ expect(decode(value)).toEqual(value);+ });+});diff --git a/packages/contracts/src/orchestrationV2IdTable.ts b/packages/contracts/src/orchestrationV2IdTable.tsnew file mode 100644index 00000000000..3d4205be76a--- /dev/null+++ b/packages/contracts/src/orchestrationV2IdTable.ts@@ -0,0 +1,125 @@+import * as Schema from "effect/Schema";+import * as SchemaGetter from "effect/SchemaGetter";++/**+ * Opt-in wire form: on each record (top-level array element, top-level object, or `item`), values+ * under `id`, `*Id`, and `*Ids` index the response's `ids` table. Both peers must apply this exact+ * rule; changing it needs a new opt-in (`compactIds=2`, or a new `accept*` key over WS).+ */+type JsonObject = { [key: string]: unknown };++const isObject = (value: unknown): value is JsonObject =>+ typeof value === "object" && value !== null && !Array.isArray(value);+const isIdKey = (key: string) => key === "id" || key.endsWith("Id");+const isIdListKey = (key: string) => key.endsWith("Ids");++function internRecordIds(container: JsonObject, ids: Array<string | number>): JsonObject {+ const index = new Map<string | number, number>();+ const ref = (value: unknown) => {+ if (typeof value !== "string" && typeof value !== "number") return value;+ let position = index.get(value);+ if (position === undefined) {+ position = ids.length;+ ids.push(value);+ index.set(value, position);+ }+ return position;+ };+ // Copies each record: unknown members can pass through encoding by reference.+ const internRecord = (record: JsonObject): JsonObject => {+ const out: JsonObject = {};+ for (const key in record) {+ const value = record[key];+ out[key] = isIdKey(key)+ ? ref(value)+ : isIdListKey(key) && Array.isArray(value)+ ? value.map(ref)+ : key === "item" && isObject(value)+ ? internRecord(value)+ : value;+ }+ return out;+ };+ const out: JsonObject = {};+ for (const key in container) {+ const value = container[key];+ out[key] = Array.isArray(value)+ ? value.map((record) => (isObject(record) ? internRecord(record) : record))+ : isObject(value)+ ? internRecord(value)+ : value;+ }+ return out;+}++// Mutates freshly parsed JSON in place; the client owns it and this avoids a copy.+function expandRecordIds(container: JsonObject, ids: ReadonlyArray<unknown>): void {+ const expandRecord = (record: JsonObject) => {+ for (const key in record) {+ const value = record[key];+ if (typeof value === "number") {+ if (isIdKey(key)) record[key] = ids[value];+ } else if (Array.isArray(value)) {+ if (isIdListKey(key)) {+ for (let i = 0; i < value.length; i++) {+ const entry = value[i];+ if (typeof entry === "number") value[i] = ids[entry];+ }+ }+ } else if (key === "item" && isObject(value)) {+ expandRecord(value);+ }+ }+ };+ for (const key in container) {+ const value = container[key];+ if (Array.isArray(value)) {+ for (const record of value) if (isObject(record)) expandRecord(record);+ } else if (isObject(value)) {+ expandRecord(value);+ }+ }+}++// `toCodecJson` turns `Schema.Unknown` into a recursive JSON check of the whole+// tree. The input is parsed JSON and the inner codec validates it anyway.+const ParsedJson = Schema.declare((_: unknown): _ is unknown => true, {+ toCodecJson: () => undefined,+});++/**+ * Adds the optional ID table to a snapshot-shaped schema. `container` returns the+ * key whose value holds the records, `null` when records sit at the top level, or+ * `undefined` when the value has no records (other stream item kinds).+ */+export const withRecordIdTable = <S extends Schema.Top>(+ schema: S,+ container: (value: JsonObject) => string | null | undefined,+) => {+ const codec = Schema.toCodecJson(schema);+ type Encoded = typeof codec.Encoded;+ return ParsedJson.pipe(+ Schema.decodeTo(codec, {+ decode: SchemaGetter.transform((raw: unknown): Encoded => {+ if (!isObject(raw) || !Array.isArray(raw.ids)) return raw as Encoded;+ // Consumed on the parsed object itself, so decoding it again is a no-op.+ const ids: ReadonlyArray<unknown> = raw.ids;+ delete raw.ids;+ const key = container(raw);+ const target = key === null ? raw : key === undefined ? undefined : raw[key];+ if (isObject(target)) expandRecordIds(target, ids);+ return raw as Encoded;+ }),+ encode: SchemaGetter.transform((encoded: Encoded): unknown => {+ if (!isObject(encoded) || encoded.idTable !== true) return encoded;+ const { idTable: _idTable, ...rest } = encoded;+ const key = container(rest);+ const ids: Array<string | number> = [];+ if (key === null) return { ...internRecordIds(rest, ids), ids };+ const target = key === undefined ? undefined : rest[key];+ if (key === undefined || !isObject(target)) return rest;+ return { ...rest, [key]: internRecordIds(target, ids), ids };+ }),+ }),+ );+};