Skip to content

Commit 41f339d

Browse files
only21milclaude
andcommitted
perf(contracts): filter unknown timeline members at read boundaries
Forward-compatible turn item arrays decoded each element through ForwardCompatibleUnion, dropped unknown members, then decoded to Schema.Array(Schema.toType(...)), which validated and rebuilt every known item a second time. Thread projections, detail snapshots and history pages paid it on every open and page. The decoded types now keep UnknownUnionMember (Received* types), so each known item is validated once. The exported projection, detail snapshot and history page types still hold only known items, and clients drop unknown ones where they read: socket and bounded snapshots, the full HTTP snapshot, history pages, the thread cache and getThreadProjection. Malformed known items still fail to decode. Refs #18856, #9661 Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 07d38b8 commit 41f339d

16 files changed

Lines changed: 211 additions & 89 deletions

‎apps/mobile/scripts/measure-renders.mts‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,9 @@ import {
1515
ProviderInstanceId,
1616
ThreadId,
1717
WsRpcGroup,
18+
knownThreadProjection,
1819
type OrchestrationV2ThreadProjection,
20+
type ReceivedOrchestrationV2ThreadProjection,
1921
} from "@t3tools/contracts";
2022
import * as Console from "effect/Console";
2123
import * as Crypto from "effect/Crypto";
@@ -228,10 +230,14 @@ const measureStreamReply = Effect.fn("measure.streamReply")(function* (
228230
yield* evaluate(
229231
`__t3RenderCounterOpen(${encodeJson(`${options.scheme}://threads/${environmentId}/${threadId}`)})`,
230232
);
231-
const projectionOf = (item: { kind: string; projection?: OrchestrationV2ThreadProjection }) =>
232-
item.kind === "snapshot" && item.projection
233+
const projectionOf = (item: {
234+
kind: string;
235+
projection?: ReceivedOrchestrationV2ThreadProjection;
236+
}) =>
237+
(item.kind === "snapshot" && item.projection
233238
? Effect.succeed(item.projection)
234-
: client["orchestration.getThreadProjection"]({ threadId });
239+
: client["orchestration.getThreadProjection"]({ threadId })
240+
).pipe(Effect.map(knownThreadProjection));
235241
const streaming = yield* client["orchestration.subscribeThread"]({ threadId }).pipe(
236242
Stream.mapEffect(projectionOf),
237243
Stream.filter((projection) => streamingItem(projection) !== undefined),
@@ -249,7 +255,9 @@ const measureStreamReply = Effect.fn("measure.streamReply")(function* (
249255
return yield* new MeasureError({
250256
message: `Run ${run}: no React commits in the window. Check the device for a red box.`,
251257
});
252-
const after = yield* client["orchestration.getThreadProjection"]({ threadId });
258+
const after = knownThreadProjection(
259+
yield* client["orchestration.getThreadProjection"]({ threadId }),
260+
);
253261
return { report, stillStreaming: streamingItem(after) !== undefined };
254262
}, Effect.scoped);
255263

‎apps/server/scripts/verify-background-live.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import {
1818
ORCHESTRATION_PROTOCOL_VERSION,
1919
ORCHESTRATION_PROTOCOL_HEADER,
2020
CommandId,
21+
knownThreadProjection,
2122
ProjectId,
2223
ProviderInstanceId,
2324
ThreadId,
@@ -374,10 +375,11 @@ try {
374375
NodePath.join(evidence, "events.ndjson"),
375376
JSON.stringify(item) + "\n",
376377
);
377-
const projection =
378+
const projection = knownThreadProjection(
378379
item.kind === "snapshot"
379380
? item.projection
380-
: yield* client["orchestration.getThreadProjection"]({ threadId });
381+
: yield* client["orchestration.getThreadProjection"]({ threadId }),
382+
);
381383
const childThreadId = projection.subagents[0]?.childThreadId;
382384
if (values.scenario === "nested" && childThreadId && !watchingChild) {
383385
watchingChild = true;

‎apps/server/src/orchestration-v2/ThreadStream.ts‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,10 +34,11 @@ export function threadReplayEncodedBytes(items: ReadonlyArray<unknown>): number
3434
return total;
3535
}
3636

37-
type ThreadSnapshotStreamItem = Extract<
38-
OrchestrationV2ThreadStreamItem,
39-
{ readonly kind: "snapshot" }
40-
>;
37+
// Built from this server's own projection, so it holds only turn items it knows.
38+
type ThreadSnapshotStreamItem = Omit<
39+
Extract<OrchestrationV2ThreadStreamItem, { readonly kind: "snapshot" }>,
40+
"projection"
41+
> & { readonly projection: OrchestrationV2ThreadProjection };
4142

4243
export function boundedSnapshotResponseFields(input: {
4344
readonly bounded: BoundedProjectionResult;

‎apps/server/src/orchestration-v2/boundedSnapshotTransport.test.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import {
1919
RunId,
2020
ThreadId,
2121
TurnItemId,
22+
knownThreadProjection,
2223
type OrchestrationV2DomainEvent,
2324
type OrchestrationV2ThreadProjection,
2425
type OrchestrationV2TurnItem,
@@ -320,7 +321,7 @@ it.layer(TestLayer)("compact bounded snapshot transport", (it) => {
320321
"local",
321322
]);
322323
} else {
323-
const ids = itemIds(legacy.projection);
324+
const ids = itemIds(knownThreadProjection(legacy.projection));
324325
assert.isTrue(legacy.hasMoreHistory);
325326
assert.strictEqual(ids.at(-1), `turn-item:${LONG}:request`);
326327
assert.isFalse(

‎packages/client-runtime/src/operations/commands.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {
44
CommandId,
55
CheckpointId,
66
CheckpointScopeId,
7+
knownThreadProjection,
78
ORCHESTRATION_V2_WS_METHODS,
89
OrchestrationV2CheckpointUnavailableError,
910
WS_METHODS,
@@ -263,7 +264,9 @@ const dispatch = (command: OrchestrationV2Command) =>
263264
request(ORCHESTRATION_V2_WS_METHODS.dispatchCommand, command);
264265

265266
const getProjection = (threadId: ThreadId) =>
266-
request(ORCHESTRATION_V2_WS_METHODS.getThreadProjection, { threadId });
267+
request(ORCHESTRATION_V2_WS_METHODS.getThreadProjection, { threadId }).pipe(
268+
Effect.map(knownThreadProjection),
269+
);
267270

268271
const supportsServerResolvedCommandContext = Effect.fn(
269272
"EnvironmentCommands.supportsServerResolvedCommandContext",

‎packages/client-runtime/src/platform/orchestrationCache.test.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {
44
EnvironmentId,
55
MessageId,
66
EventId,
7+
knownThreadProjection,
78
TurnItemId,
89
RuntimeRequestId,
910
type OrchestrationV2ShellSnapshot,
@@ -108,7 +109,9 @@ describe("orchestration cache envelopes", () => {
108109
threadId: v2ThreadId,
109110
snapshot: { snapshotSequence: 5, projection },
110111
});
111-
const decoded = decodeStoredThreadSnapshotJson(encoded).snapshot.projection;
112+
const decoded = knownThreadProjection(
113+
decodeStoredThreadSnapshotJson(encoded).snapshot.projection,
114+
);
112115
expect(decoded.turnItems.find((entry) => entry.id === item.id)).toEqual(item);
113116
expect(decoded.visibleTurnItems.find((entry) => entry.item.id === item.id)?.item).toEqual(item);
114117
});

‎packages/client-runtime/src/platform/persistence.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import {
22
type EnvironmentId,
33
type OrchestrationV2ShellSnapshot,
44
type OrchestrationV2ThreadDetailSnapshot,
5+
type ReceivedOrchestrationV2ThreadDetailSnapshot,
56
type ServerConfig,
67
type ThreadId,
78
type VcsListRefsResult,
@@ -91,7 +92,7 @@ export class EnvironmentCacheStore extends Context.Service<
9192
environmentId: EnvironmentId,
9293
threadId: ThreadId,
9394
) => Effect.Effect<
94-
Option.Option<OrchestrationV2ThreadDetailSnapshot>,
95+
Option.Option<ReceivedOrchestrationV2ThreadDetailSnapshot>,
9596
ConnectionPersistenceError
9697
>;
9798
readonly saveThread: (

‎packages/client-runtime/src/state/threadHistoryHttp.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import type { ThreadId } from "@t3tools/contracts";
1+
import { knownThreadHistoryPage, type ThreadId } from "@t3tools/contracts";
22
import * as Effect from "effect/Effect";
33
import * as Option from "effect/Option";
44

@@ -40,5 +40,5 @@ export const fetchEnvironmentThreadHistoryPage = Effect.fn(
4040
timeoutMs: input.timeoutMs ?? DEFAULT_THREAD_HISTORY_TIMEOUT_MS,
4141
request: ({ client, headers }) =>
4242
client.threadHistoryPage({ ...endpoint, headers: withOrchestrationProtocolHeader(headers) }),
43-
});
43+
}).pipe(Effect.map(knownThreadHistoryPage));
4444
});

‎packages/client-runtime/src/state/threadSnapshotHttp.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
1-
import type { OrchestrationV2ThreadDetailSnapshot, ThreadId } from "@t3tools/contracts";
1+
import {
2+
knownThreadDetailSnapshot,
3+
type OrchestrationV2ThreadDetailSnapshot,
4+
type ThreadId,
5+
} from "@t3tools/contracts";
26
import * as Context from "effect/Context";
37
import * as Effect from "effect/Effect";
48
import * as Option from "effect/Option";
@@ -55,7 +59,7 @@ export const fetchEnvironmentThreadSnapshot = Effect.fn(
5559
params: { threadId: input.threadId },
5660
headers: withOrchestrationProtocolHeader(headers),
5761
}),
58-
});
62+
}).pipe(Effect.map(knownThreadDetailSnapshot));
5963
});
6064

6165
export type FetchEnvironmentThreadSnapshotError = RemoteEnvironmentRequestError;

‎packages/client-runtime/src/state/threads.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import {
2+
knownThreadDetailSnapshot,
23
ORCHESTRATION_V2_WS_METHODS,
34
type EnvironmentId as EnvironmentIdType,
45
type OrchestrationV2ThreadDetailSnapshot,
@@ -184,6 +185,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
184185
const cached =
185186
retained === undefined
186187
? yield* cache.loadThread(environmentId, threadId).pipe(
188+
Effect.map(Option.map(knownThreadDetailSnapshot)),
187189
Effect.catch((error) =>
188190
Effect.logWarning("Could not load cached thread.").pipe(
189191
Effect.annotateLogs({

0 commit comments

Comments
 (0)