Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

threadSnapshotBody.test.ts

379 lines13.1 KB

1import { assert, it } from "@effect/vitest";
2import {
3 EnvironmentHttpApi,
4 EventId,
5 MessageId,
6 NodeId,
7 type OrchestrationV2ThreadDetailSnapshot,
8 ProjectId,
9 ProviderDriverKind,
10 ProviderInstanceId,
11 RunId,
12 RuntimeRequestId,
13 ThreadId,
14 TurnItemId,
15 type OrchestrationV2DomainEvent,
16 type OrchestrationV2TurnItem,
17} from "@t3tools/contracts";
18import * as DateTime from "effect/DateTime";
19import * as Effect from "effect/Effect";
20import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
21import * as Layer from "effect/Layer";
22import * as Schema from "effect/Schema";
23import * as Stream from "effect/Stream";
24​
25import * as SqlitePersistence from "../persistence/Sqlite.ts";
26import * as ProjectionStore from "./ProjectionStore.ts";
27import { encodeThreadSnapshotBody } from "./threadSnapshotBody.ts";
28import { projectThreadProjectionForWire } from "./WireProjection.ts";
29​
30const provider = ProviderInstanceId.make("codex");
31const modelSelection = { instanceId: provider, model: "gpt-5.4" };
32const PARENT = ThreadId.make("thread:snapshot-body:parent");
33const FORK = ThreadId.make("thread:snapshot-body:fork");
34const parentRun = RunId.make("run:snapshot-body:parent");
35const ITEMS = 1_200;
36// Escapes, a lone surrogate, astral and two-byte text: every JSON.stringify string rule.
37const TEXT = 'quote " slash \\ tab \t nl \n nul \u0000 lone \ud800 astral π„ž η•Œ';
38​
39// What HttpApiBuilder sends: JSON.stringify of the endpoint's own success codec (toCodecJson).
40const encodeAsEndpoint = Schema.encodeUnknownSync(
41 [...EnvironmentHttpApi.groups.orchestration.endpoints.threadSnapshot.success][0] as Schema.Codec<
42 unknown,
43 unknown
44 >,
45);
46const referenceBody = (snapshot: OrchestrationV2ThreadDetailSnapshot) =>
47 Buffer.from(JSON.stringify(encodeAsEndpoint(snapshot)), "utf8");
48​
49const streamedBody = (snapshot: OrchestrationV2ThreadDetailSnapshot) =>
50 encodeThreadSnapshotBody(snapshot).pipe(
51 Effect.flatMap(Stream.runCollect),
52 Effect.map((chunks) => ({
53 chunks: chunks.length,
54 largestChunk: Math.max(...chunks.map((chunk) => chunk.byteLength)),
55 bytes: Buffer.concat([...chunks]),
56 })),
57 );
58​
59const threadCreated = (
60 id: ThreadId,
61 at: DateTime.Utc,
62 forkOf?: RunId,
63): OrchestrationV2DomainEvent => ({
64 id: EventId.make(`event:${id}:created`),
65 type: "thread.created",
66 threadId: id,
67 occurredAt: at,
68 payload: {
69 createdBy: "user",
70 creationSource: "web",
71 id,
72 projectId: ProjectId.make("project:snapshot-body"),
73 title: `${id} ${TEXT}`,
74 providerInstanceId: provider,
75 modelSelection,
76 runtimeMode: "full-access",
77 interactionMode: "default",
78 branch: null,
79 worktreePath: null,
80 activeProviderThreadId: null,
81 lineage:
82 forkOf === undefined
83 ? { parentThreadId: null, relationshipToParent: null, rootThreadId: id }
84 : { parentThreadId: PARENT, relationshipToParent: "fork", rootThreadId: PARENT },
85 forkedFrom: forkOf === undefined ? null : { type: "run", threadId: PARENT, runId: forkOf },
86 createdAt: at,
87 updatedAt: at,
88 archivedAt: null,
89 settledOverride: null,
90 settledAt: null,
91 lastVisitedAt: null,
92 deletedAt: null,
93 },
94});
95​
96const runCreated = (threadId: ThreadId, runId: RunId, at: DateTime.Utc) => {
97 const rootNodeId = NodeId.make(`node:${runId}`);
98 return {
99 id: EventId.make(`event:${runId}:created`),
100 type: "run.created",
101 threadId,
102 runId,
103 nodeId: rootNodeId,
104 driver: ProviderDriverKind.make("codex"),
105 occurredAt: at,
106 payload: {
107 id: runId,
108 threadId,
109 ordinal: 1,
110 providerInstanceId: provider,
111 modelSelection,
112 providerThreadId: null,
113 userMessageId: MessageId.make(`message:${runId}`),
114 rootNodeId,
115 activeAttemptId: null,
116 status: "completed",
117 requestedAt: at,
118 startedAt: at,
119 completedAt: at,
120 checkpointId: null,
121 contextHandoffId: null,
122 },
123 } satisfies OrchestrationV2DomainEvent;
124};
125​
126// One item of each wire-projected shape: omitted output, truncated input, a failed diff.
127const item = (
128 threadId: ThreadId,
129 runId: RunId | null,
130 ordinal: number,
131 at: DateTime.Utc,
132): OrchestrationV2DomainEvent => {
133 const base = {
134 id: TurnItemId.make(`turn-item:${threadId}:${ordinal}`),
135 threadId,
136 runId,
137 nodeId: null,
138 providerThreadId: null,
139 providerTurnId: null,
140 nativeItemRef: null,
141 parentItemId: null,
142 ordinal,
143 status: "completed" as const,
144 title: `${ordinal} ${TEXT}`,
145 startedAt: at,
146 completedAt: at,
147 updatedAt: at,
148 };
149 const payloads: ReadonlyArray<OrchestrationV2TurnItem> = [
150 {
151 ...base,
152 type: "command_execution",
153 input: `echo ${ordinal} ${TEXT}`,
154 output: `${TEXT}\n`.repeat(40),
155 exitCode: ordinal % 7 === 0 ? 1 : 0,
156 },
157 {
158 ...base,
159 type: "dynamic_tool",
160 toolName: "search",
161 input: { query: TEXT, pages: Array.from({ length: 900 }, (_, page) => page) },
162 output: [{ type: "text", text: TEXT }],
163 },
164 {
165 ...base,
166 status: "failed",
167 type: "file_change",
168 fileName: `src/${ordinal}.ts`,
169 diffStr: `@@ ${TEXT}\n`.repeat(20),
170 },
171 {
172 ...base,
173 type: "assistant_message",
174 messageId: MessageId.make(`message:${threadId}:${ordinal}`),
175 text: TEXT.repeat(3),
176 streaming: false,
177 },
178 // No progress: the wire projection sets it to undefined, which the endpoint sends as null.
179 {
180 ...base,
181 type: "subagent",
182 subagentId: NodeId.make(`node:${threadId}:task:${ordinal}`),
183 origin: "app_owned",
184 driver: ProviderDriverKind.make("codex"),
185 providerInstanceId: provider,
186 childThreadId: null,
187 prompt: `Look into ${TEXT}`,
188 result: ordinal % 2 === 0 ? null : TEXT,
189 },
190 ];
191 return {
192 id: EventId.make(`event:${threadId}:item:${ordinal}`),
193 type: "turn-item.updated",
194 threadId,
195 ...(runId === null ? {} : { runId }),
196 occurredAt: at,
197 payload: payloads[ordinal % payloads.length]!,
198 };
199};
200​
201const seed = Effect.gen(function* () {
202 const projections = yield* ProjectionStore.ProjectionStoreV2;
203 const at = DateTime.makeUnsafe("2026-10-01T00:00:00.000Z");
204 const events: ReadonlyArray<OrchestrationV2DomainEvent> = [
205 threadCreated(PARENT, at),
206 runCreated(PARENT, parentRun, at),
207 ...Array.from({ length: ITEMS }, (_, index) => item(PARENT, parentRun, index + 1, at)),
208 // Larger than a chunk, astral throughout, at both offsets: chunks split inside one member.
209 ...["", "x"].map((prefix, index) => {
210 const event = item(PARENT, parentRun, 1_000 * ITEMS + index * 5, at) as Extract<
211 OrchestrationV2DomainEvent,
212 { type: "turn-item.updated" }
213 >;
214 return { ...event, payload: { ...event.payload, input: prefix + "π„ž".repeat(600_000) } };
215 }),
216 threadCreated(FORK, at, parentRun),
217 ...Array.from({ length: 40 }, (_, index) => item(FORK, null, index + 1, at)),
218 ];
219 for (const event of events) yield* projections.apply(event);
220});
221​
222const seededStore = <E>(events: Effect.Effect<void, E, ProjectionStore.ProjectionStoreV2>) =>
223 Layer.effectDiscard(events).pipe(
224 Layer.provideMerge(ProjectionStore.layer.pipe(Layer.provide(NodeCrypto.layerDigest))),
225 Layer.provideMerge(SqlitePersistence.layerMemory),
226 );
227​
228const TestLayer = seededStore(seed);
229​
230const cycle: Record<string, unknown> = {};
231cycle.self = cycle;
232const sparse: Array<number> = [];
233sparse[2] = 3;
234// Values JSON cannot carry, for a field the schema leaves unknown.
235const NOT_JSON_VALUES: ReadonlyArray<unknown> = [
236 undefined,
237 Number.NaN,
238 DateTime.toDateUtc(DateTime.makeUnsafe(0)),
239 () => 1,
240 1n,
241 cycle,
242 Object("boxed"),
243 sparse,
244];
245​
246const runtimeRequests = (answerSets: ReadonlyArray<Readonly<Record<string, unknown>>>) => {
247 const at = DateTime.makeUnsafe("2026-10-01T00:00:00.000Z");
248 return answerSets.map((answers, index) => ({
249 id: RuntimeRequestId.make(`runtime-request:snapshot-body:${index}`),
250 nodeId: NodeId.make(`node:${parentRun}`),
251 providerTurnId: null,
252 nativeRequestRef: null,
253 kind: "user_input" as const,
254 status: "resolved" as const,
255 responseCapability: { type: "message" as const },
256 createdAt: at,
257 resolvedAt: at,
258 answers,
259 }));
260};
261​
262it.layer(TestLayer)("thread snapshot body", (it) => {
263 it.effect("streams a long thread and its fork as the endpoint encodes them", () =>
264 Effect.gen(function* () {
265 const projections = yield* ProjectionStore.ProjectionStoreV2;
266 for (const threadId of [PARENT, FORK]) {
267 const { snapshotSequence, projection } = yield* projections.getThreadSnapshot(threadId);
268 const snapshot = {
269 snapshotSequence,
270 projection: projectThreadProjectionForWire(projection),
271 };
272 const streamed = yield* streamedBody(snapshot);
273 assert.isTrue(streamed.bytes.equals(referenceBody(snapshot)));
274 if (threadId === PARENT) {
275 assert.strictEqual(snapshot.projection.turnItems.length, ITEMS + 2);
276 assert.isTrue(
277 snapshot.projection.turnItems.some(
278 (item) =>
279 item.type === "subagent" && "progress" in item && item.progress === undefined,
280 ),
281 );
282 assert.isAtMost(streamed.largestChunk, 1024 * 1024);
283 } else {
284 // Inherited rows hold parent items that are not in this thread's turn items.
285 assert.isTrue(
286 snapshot.projection.visibleTurnItems.some((row) => row.visibility === "inherited"),
287 );
288 }
289 }
290 }),
291 );
292​
293 it.effect("fails before the body when the schema rejects the snapshot, as encoding did", () =>
294 Effect.gen(function* () {
295 const projections = yield* ProjectionStore.ProjectionStoreV2;
296 const { snapshotSequence, projection } = yield* projections.getThreadSnapshot(PARENT);
297 const wire = projectThreadProjectionForWire(projection);
298 const [first, ...rest] = wire.turnItems;
299 const invalid = {
300 snapshotSequence,
301 projection: {
302 ...wire,
303 turnItems: [
304 { ...first!, status: "unknown" } as unknown as OrchestrationV2TurnItem,
305 ...rest,
306 ],
307 },
308 };
309 const notJson = NOT_JSON_VALUES.map((value) => ({ value })).map((answers) => ({
310 snapshotSequence,
311 projection: { ...wire, runtimeRequests: runtimeRequests([answers]) },
312 }));
313 for (const snapshot of [invalid, ...notJson]) {
314 assert.throws(() => referenceBody(snapshot));
315 const error = yield* encodeThreadSnapshotBody(snapshot).pipe(Effect.flip);
316 assert.isTrue(Schema.isSchemaError(error));
317 }
318 }),
319 );
320​
321 it.effect("keeps chunks bounded for large and deeply nested answers", () =>
322 Effect.gen(function* () {
323 const projections = yield* ProjectionStore.ProjectionStoreV2;
324 const { snapshotSequence, projection } = yield* projections.getThreadSnapshot(FORK);
325 // Deeper than a recursive writer, or one JSON.stringify call, can go: with and without bulk.
326 const nest = (leaf: unknown) => {
327 let deep = leaf;
328 for (let depth = 0; depth < 3_000; depth++) deep = depth % 2 === 0 ? [deep] : { deep };
329 return deep;
330 };
331 const snapshot = {
332 snapshotSequence,
333 projection: {
334 ...projectThreadProjectionForWire(projection),
335 // Each answer set is large or deep in its own way.
336 runtimeRequests: runtimeRequests([
337 { reply: { toJSON: null, text: `${TEXT}\n`.repeat(40_000) } },
338 { [TEXT.repeat(40_000)]: 0 },
339 // Under a chunk before escaping, six times that after: each NUL is written as \u0000.
340 { nul: "\u0000".repeat(200_000) },
341 { many: Array.from({ length: 200_000 }, (_, index) => ({ index, text: "x" })) },
342 { deep: nest(TEXT.repeat(40_000)) },
343 { deep: nest(TEXT) },
344 ]),
345 },
346 };
347 const streamed = yield* streamedBody(snapshot);
348 assert.isTrue(streamed.bytes.equals(referenceBody(snapshot)));
349 assert.isAtMost(streamed.largestChunk, 1024 * 1024);
350 }),
351 );
352​
353 it.effect("writes an answer too deep for JSON.stringify here, without failing mid-body", () =>
354 Effect.gen(function* () {
355 const projections = yield* ProjectionStore.ProjectionStoreV2;
356 const { snapshotSequence, projection } = yield* projections.getThreadSnapshot(FORK);
357 const snapshot = (deep: unknown) => ({
358 snapshotSequence,
359 projection: {
360 ...projectThreadProjectionForWire(projection),
361 runtimeRequests: runtimeRequests([{ deep }]),
362 },
363 });
364 // A two-byte string puts JSON.stringify on its recursive path, which this depth overflows.
365 let deep: unknown = "π„ž".repeat(10);
366 let deepJson = JSON.stringify(deep);
367 for (let depth = 0; depth < 20_000; depth++) {
368 deep = depth % 2 === 0 ? [deep] : { deep };
369 deepJson = depth % 2 === 0 ? `[${deepJson}]` : `{"deep":${deepJson}}`;
370 }
371 assert.throws(() => JSON.stringify(deep), RangeError);
372 const expected = referenceBody(snapshot("placeholder"))
373 .toString("utf8")
374 .replace('"deep":"placeholder"', () => `"deep":${deepJson}`);
375 const streamed = yield* streamedBody(snapshot(deep));
376 assert.strictEqual(streamed.bytes.toString("utf8"), expected);
377 }),
378 );
379});