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

transferBudgetV2.integration.test.ts

469 lines21.0 KB

1// @effect-diagnostics nodeBuiltinImport:off - Measures real local HTTP/WebSocket sockets.
2import * as NodeHttp from "node:http";
3import * as NodeUtil from "node:util";
4import { assert, it } from "@effect/vitest";
5import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
6import * as NodeHttpPlatform from "@effect/platform-node/NodeHttpPlatform";
7import * as NodeServices from "@effect/platform-node/NodeServices";
8import {
9 ORCHESTRATION_PROTOCOL_HEADER,
10 ORCHESTRATION_PROTOCOL_VERSION,
11 AuthSessionId,
12 AuthOrchestrationReadScope,
13 EnvironmentHttpApi,
14 EnvironmentId,
15 EnvironmentAuthenticatedAuth,
16 EnvironmentAuthenticatedPrincipal,
17 ORCHESTRATION_V2_WS_METHODS,
18 OrchestrationV2RpcSchemas,
19 OrchestrationV2ThreadBoundedSnapshot,
20 OrchestrationV2ThreadDetailSnapshot,
21 OrchestrationV2ThreadHistoryPage,
22 OrchestrationV2ShellSnapshot,
23 OrchestrationV2GetThreadProjectionError,
24 OrchestrationV2GetShellSnapshotError,
25 ProviderDriverKind,
26 type OrchestrationV2ThreadStreamItem,
27 type OrchestrationV2ShellStreamItem,
28} from "@t3tools/contracts";
29import * as Context from "effect/Context";
30import * as Config from "effect/Config";
31import * as Effect from "effect/Effect";
32import * as FileSystem from "effect/FileSystem";
33import * as Layer from "effect/Layer";
34import * as PubSub from "effect/PubSub";
35import * as Queue from "effect/Queue";
36import * as Schema from "effect/Schema";
37import * as Scope from "effect/Scope";
38import * as Stream from "effect/Stream";
39import * as HttpApi from "effect/http-api/HttpApi";
40import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
41import { HttpRouter, HttpServer } from "effect/http";
42import { Rpc, RpcGroup, RpcServer, RpcSerialization } from "effect/rpc";
43import * as ServerEnvironment from "../src/environment/ServerEnvironment.ts";
44import * as SqlitePersistence from "../src/persistence/Sqlite.ts";
45import * as OrchestrationEventStore from "../src/persistence/OrchestrationEventStore.ts";
46import * as EventStore from "../src/orchestration-v2/EventStore.ts";
47import * as EventSink from "../src/orchestration-v2/EventSink.ts";
48import * as ProjectionStore from "../src/orchestration-v2/ProjectionStore.ts";
49import * as ThreadManagementService from "../src/orchestration-v2/ThreadManagementService.ts";
50import * as ProjectStore from "../src/orchestration-v2/ProjectStore.ts";
51import * as ProjectService from "../src/project/ProjectService.ts";
52import * as ProjectEnrichmentService from "../src/project/ProjectEnrichmentService.ts";
53import * as OrchestrationHttp from "../src/orchestration-v2/http.ts";
54import * as ServerHttp from "../src/http.ts";
55import { subscribeOrchestrationV2Thread, subscribeOrchestrationV2Shell } from "../src/ws.ts";
56import {
57 measureHttpGet,
58 openMeasuredWsClient,
59 type HttpTransferMeasurement,
60 type MeasuredWsClient,
61} from "./NetworkTransferMeasurement.integration.ts";
62import { makeSqlStatementCounter } from "./SqlStatementCounter.integration.ts";
63import {
64 formatTransferBudgetReport,
65 formatTransferBudgetResult,
66 transferBudgetViolations,
67 type TransferBudgetRun,
68} from "./TransferBudgetReport.integration.ts";
69import { TRANSFER_HISTORY_TURN_COUNT } from "./fixtures/transferBudget.ts";
70import {
71 LONG_TURN_THREAD_ID,
72 longTurnThreadBatches,
73 SHELL_IDLE_SUBAGENTS,
74 SHELL_SETTLED_THREADS,
75 shellFleetEvents,
76 THREAD_ID,
77 threadCreated,
78 turnEvents,
79} from "./TransferBudgetV2Fixture.integration.ts";
80​
81// The opt-ins current web and mobile clients send; keep in sync with client-runtime's
82// boundedThreadSnapshotHttp.ts, threadHistoryHttp.ts, shellSnapshotHttp.ts, threads.ts and shell.ts.
83const CLIENT_BOUNDED_QUERY = "compactTurnItems=1&dedupeBodies=1&compactIds=1";
84const CLIENT_HISTORY_QUERY = "compactIds=1";
85const CLIENT_SHELL_QUERY = "omitIdleSubagents=1&omitOlderSettled=1";
86​
87const decodeThreadSnapshot = Schema.decodeUnknownEffect(
88 Schema.fromJsonString(Schema.toCodecJson(OrchestrationV2ThreadDetailSnapshot)),
89);
90const decodeBoundedSnapshot = Schema.decodeUnknownEffect(
91 Schema.fromJsonString(Schema.toCodecJson(OrchestrationV2ThreadBoundedSnapshot)),
92);
93const decodeHistoryPage = Schema.decodeUnknownEffect(
94 Schema.fromJsonString(Schema.toCodecJson(OrchestrationV2ThreadHistoryPage)),
95);
96const decodeShellSnapshot = Schema.decodeUnknownEffect(
97 Schema.fromJsonString(Schema.toCodecJson(OrchestrationV2ShellSnapshot)),
98);
99​
100const layerPersistence = EventSink.layer.pipe(
101 Layer.provideMerge(EventStore.layerFromOrchestrationEventStore),
102 Layer.provideMerge(ProjectionStore.layer),
103 Layer.provideMerge(OrchestrationEventStore.layer),
104 Layer.provideMerge(SqlitePersistence.layerMemory),
105);
106const layerManagement = Layer.unwrap(
107 Effect.gen(function* () {
108 const projections = yield* ProjectionStore.ProjectionStoreV2;
109 const sink = yield* EventSink.EventSinkV2;
110 return Layer.mock(ThreadManagementService.ThreadManagementService)({
111 ensureLegacyTranscript: () => Effect.void,
112 getThreadSnapshot: (id) => projections.getThreadSnapshot(id).pipe(Effect.orDie),
113 getThreadSnapshotWindow: (id, options) =>
114 projections.getThreadSnapshotWindow(id, options).pipe(Effect.orDie),
115 getThreadHistoryPage: (id, cursor, throughEntryId, conversationOnly) =>
116 projections
117 .getThreadHistoryPage(id, cursor, throughEntryId, conversationOnly)
118 .pipe(Effect.orDie),
119 getThreadShell: (id) => projections.getThreadShell(id).pipe(Effect.orDie),
120 getShellSnapshot: (options) => projections.getShellSnapshot(options).pipe(Effect.orDie),
121 listActiveShellIndex: () => projections.listActiveShellIndex().pipe(Effect.orDie),
122 listActiveSubagentThreadIds: () =>
123 projections.listActiveSubagentThreadIds().pipe(Effect.orDie),
124 readShellSnapshot: (options) =>
125 projections.readShellSnapshot(options).pipe(Effect.map(Effect.orDie), Effect.orDie),
126 streamStoredEventsFrom: (input) =>
127 sink.stream({ ...input, bounded: true }).pipe(Stream.orDie),
128 });
129 }),
130);
131const layerEnrichment = Layer.unwrap(
132 Effect.gen(function* () {
133 const changes = yield* PubSub.unbounded<never>();
134 return Layer.mock(ProjectEnrichmentService.ProjectEnrichmentService)({
135 getAvailable: () =>
136 Effect.succeed({
137 repositoryIdentity: null,
138 faviconPath: null,
139 repositoryIdentityResolved: true,
140 }),
141 subscribeChanges: PubSub.subscribe(changes),
142 });
143 }),
144);
145const layerServices = layerManagement.pipe(
146 Layer.provideMerge(
147 Layer.succeed(ServerEnvironment.ServerEnvironmentIdentity, {
148 getEnvironmentId: Effect.succeed(EnvironmentId.make("transfer-test")),
149 }),
150 ),
151 Layer.provideMerge(ProjectStore.layer),
152 Layer.provideMerge(Layer.mock(ProjectService.ProjectService)({})),
153 Layer.provideMerge(layerEnrichment),
154 Layer.provideMerge(layerPersistence),
155);
156class TransferApi extends HttpApi.make("environment").add(
157 EnvironmentHttpApi.groups.orchestration,
158) {}
159const layerAuth = Layer.succeed(EnvironmentAuthenticatedAuth, (effect) =>
160 effect.pipe(
161 Effect.provideService(EnvironmentAuthenticatedPrincipal, {
162 sessionId: AuthSessionId.make("transfer-session"),
163 subject: "transfer-test",
164 method: "browser-session-cookie",
165 scopes: new Set([AuthOrchestrationReadScope]),
166 }),
167 ),
168);
169const group = RpcGroup.make(
170 Rpc.make(ORCHESTRATION_V2_WS_METHODS.subscribeThread, {
171 payload: OrchestrationV2RpcSchemas.subscribeThread.input,
172 success: OrchestrationV2RpcSchemas.subscribeThread.output,
173 error: OrchestrationV2GetThreadProjectionError,
174 stream: true,
175 }),
176 Rpc.make(ORCHESTRATION_V2_WS_METHODS.subscribeShell, {
177 payload: OrchestrationV2RpcSchemas.subscribeShell.input,
178 success: OrchestrationV2RpcSchemas.subscribeShell.output,
179 error: OrchestrationV2GetShellSnapshotError,
180 stream: true,
181 }),
182);
183const layerHandlers = group.toLayer({
184 [ORCHESTRATION_V2_WS_METHODS.subscribeThread]: (input) =>
185 Stream.unwrap(subscribeOrchestrationV2Thread(input)),
186 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: (input) =>
187 Stream.unwrap(subscribeOrchestrationV2Shell(input)),
188});
189const layerRoutes = Layer.mergeAll(
190 HttpApiBuilder.layer(TransferApi).pipe(
191 Layer.provide(OrchestrationHttp.layer),
192 Layer.provide(layerAuth),
193 ),
194 RpcServer.layerHttp({ group, path: "/ws", protocol: "websocket" }).pipe(
195 Layer.provide(layerHandlers),
196 Layer.provide(RpcSerialization.layerJson),
197 ),
198).pipe(Layer.provide(ServerHttp.layerHttpCompression), Layer.provide(NodeHttpPlatform.layer));
199​
200function difference(
201 after: { wireBytes: number; decodedBytes: number; messages: number },
202 before: typeof after,
203) {
204 return {
205 wireBytes: after.wireBytes - before.wireBytes,
206 decodedBytes: after.decodedBytes - before.decodedBytes,
207 messages: after.messages - before.messages,
208 };
210type StreamItem = OrchestrationV2ThreadStreamItem | OrchestrationV2ShellStreamItem;
211const collectUntil = Effect.fn("transfer.collectUntil")(function* <T extends StreamItem>(
212 queue: Queue.Queue<T>,
213 done: (item: T) => boolean,
214) {
215 const items: T[] = [];
216 while (true) {
217 const item = yield* Queue.take(queue);
218 items.push(item);
219 if (done(item)) return items;
220 }
221});
222const subscribe = Effect.fn("transfer.subscribe")(function* (
223 client: MeasuredWsClient,
224 kind: "thread" | "shell",
225 afterSequence: number,
226) {
227 const queue = yield* Queue.unbounded<StreamItem>();
228 const stream: Stream.Stream<StreamItem, unknown> =
229 kind === "thread"
230 ? client.client[ORCHESTRATION_V2_WS_METHODS.subscribeThread]({
231 threadId: THREAD_ID,
232 afterSequence,
233 requestCompletionMarker: true,
234 acceptBoundedSnapshot: true,
235 acceptCompactTurnItems: true,
236 acceptCompactIds: true,
237 acceptDedupedBodies: true,
238 })
239 : client.client[ORCHESTRATION_V2_WS_METHODS.subscribeShell]({
240 afterSequence,
241 requestCompletionMarker: true,
242 omitIdleSubagents: true,
243 omitOlderSettled: true,
244 });
245 yield* stream.pipe(
246 Stream.runForEach((item) => Queue.offer(queue, item)),
247 Scope.provide(client.scope),
248 Effect.forkIn(client.scope),
249 );
250 return queue;
251});
252const synchronized = (queue: Queue.Queue<StreamItem>) =>
253 collectUntil(queue, (item) => item.kind === "synchronized").pipe(
254 Effect.map((items) =>
255 items.some((item) => item.kind === "snapshot") ? ("snapshot" as const) : ("replay" as const),
256 ),
257 );
258​
259it.live("reports V2 thread HTTP and WebSocket transfer budgets", () =>
260 Effect.gen(function* () {
261 const runs: TransferBudgetRun[] = [];
262 for (const provider of [
263 ProviderDriverKind.make("codex"),
264 ProviderDriverKind.make("claudeAgent"),
265 ]) {
266 const counter = makeSqlStatementCounter();
267 const run = yield* Effect.scoped(
268 Effect.gen(function* () {
269 const sink = yield* EventSink.EventSinkV2;
270 const projection = yield* ProjectionStore.ProjectionStoreV2;
271 yield* sink.write({ events: [threadCreated(provider)] });
272 for (let index = 0; index < TRANSFER_HISTORY_TURN_COUNT; index++)
273 yield* sink.write({ events: turnEvents(provider, index, false) });
274 const context = yield* Effect.context<Layer.Success<typeof layerServices>>();
275 const server = yield* Layer.build(
276 HttpRouter.serve(layerRoutes, { disableListenLog: true }).pipe(
277 Layer.provide(Layer.succeedContext(context)),
278 Layer.provideMerge(
279 NodeHttpServer.layer(NodeHttp.createServer, {
280 host: "127.0.0.1",
281 port: 0,
282 websocket: { perMessageDeflate: true },
283 }),
284 ),
285 ),
286 );
287 const address = Context.get(server, HttpServer.HttpServer).address;
288 if (!("port" in address)) return yield* Effect.die("Expected TCP server");
289 const base = `http://127.0.0.1:${address.port}`;
290 const threadSnapshot = yield* measureHttpGet({
291 url: `${base}/api/orchestration/threads/${THREAD_ID}`,
292 headers: { [ORCHESTRATION_PROTOCOL_HEADER]: String(ORCHESTRATION_PROTOCOL_VERSION) },
293 });
294 assert.equal(
295 threadSnapshot.status,
296 200,
297 Buffer.from(threadSnapshot.decodedBody).toString(),
298 );
299 assert.equal(threadSnapshot.contentEncoding, "gzip");
300 const decodedThread = yield* decodeThreadSnapshot(
301 Buffer.from(threadSnapshot.decodedBody).toString(),
302 );
303 assert.equal(decodedThread.projection.messages.length, TRANSFER_HISTORY_TURN_COUNT * 2);
304 assert.equal(decodedThread.projection.turnItems.length, TRANSFER_HISTORY_TURN_COUNT * 6);
305 assert.notInclude(Buffer.from(threadSnapshot.decodedBody).toString(), "digest=");
306 const shellSnapshot = yield* measureHttpGet({
307 url: `${base}/api/orchestration/shell`,
308 headers: { [ORCHESTRATION_PROTOCOL_HEADER]: String(ORCHESTRATION_PROTOCOL_VERSION) },
309 });
310 assert.equal(shellSnapshot.status, 200);
311 const decodedShell = yield* decodeShellSnapshot(
312 Buffer.from(shellSnapshot.decodedBody).toString(),
313 );
314 assert.equal(decodedShell.threads.length, 1);
315 const sequence = decodedThread.snapshotSequence;
316 assert.equal(decodedShell.snapshotSequence, sequence);
317 const url = `${base.replace("http:", "ws:")}/ws`;
318 const thread = yield* openMeasuredWsClient({ url, cookie: "" });
319 const shell = yield* openMeasuredWsClient({ url, cookie: "" });
320 const second = yield* openMeasuredWsClient({ url, cookie: "" });
321 assert.include(thread.recorder.negotiatedExtensions(), "permessage-deflate");
322 const tq = yield* subscribe(thread, "thread", sequence);
323 const sq = yield* subscribe(shell, "shell", sequence);
324 const ttq = yield* subscribe(second, "thread", sequence);
325 const ssq = yield* subscribe(second, "shell", sequence);
326 for (const queue of [tq, sq, ttq, ssq])
327 assert.equal(yield* synchronized(queue), "replay");
328 const threadBefore = thread.recorder.totals();
329 const shellBefore = shell.recorder.totals();
330 const secondBefore = second.recorder.totals();
331 const sqlBefore = counter.count();
332 const events = turnEvents(provider, TRANSFER_HISTORY_TURN_COUNT, true);
333 const stored = yield* sink.write({ events });
334 const last = stored.at(-1)!;
335 const threadTerminal = (item: StreamItem) =>
336 "sequence" in item && item.sequence >= last.sequence;
337 // Shell items carry the shell read when their batch is projected, and unchanged
338 // shells are skipped, so a turn split across batches may never yield an item at
339 // the last sequence. Wait for the final shell instead.
340 const finalShell = yield* projection.getThreadShell(THREAD_ID);
341 const shellTerminal = (item: StreamItem) =>
342 item.kind === "thread.updated" && NodeUtil.isDeepStrictEqual(item.thread, finalShell);
343 const liveTurn = yield* collectUntil(tq, threadTerminal);
344 yield* collectUntil(ttq, threadTerminal);
345 // A direct check, so live dedupe stays guarded however small the turn gets.
346 const liveAnswer = liveTurn.flatMap((item) =>
347 item.kind === "event" &&
348 item.event.type === "turn-item.updated" &&
349 item.event.payload.type === "assistant_message"
350 ? [item.event.payload]
351 : [],
352 );
353 assert.equal(liveAnswer.length, 1);
354 assert.equal(liveAnswer[0]!.textOmitted, true);
355 for (const queue of [sq, ssq]) yield* collectUntil(queue, shellTerminal);
356 const measuredTurnWebSocket = difference(thread.recorder.totals(), threadBefore);
357 const measuredTurnShellWebSocket = difference(shell.recorder.totals(), shellBefore);
358 const measuredTurnSecondClientWebSocket = difference(
359 second.recorder.totals(),
360 secondBefore,
361 );
362 const measuredTurnSqlStatements = counter.count() - sqlBefore;
363 const durable = yield* projection.getThreadProjection(THREAD_ID);
364 assert.isTrue(
365 durable.turnItems.some(
366 (item) =>
367 item.type === "dynamic_tool" && JSON.stringify(item.output).length > 1_000_000,
368 ),
369 );
370 yield* second.close;
371 const reconnectSqlStart = counter.count();
372 const resumedThread = yield* openMeasuredWsClient({ url, cookie: "" });
373 const resumedShell = yield* openMeasuredWsClient({ url, cookie: "" });
374 const rq = yield* subscribe(resumedThread, "thread", sequence);
375 const rsq = yield* subscribe(resumedShell, "shell", sequence);
376 const threadMode = yield* synchronized(rq);
377 const shellMode = yield* synchronized(rsq);
378 const reconnectThread = { ...resumedThread.recorder.totals(), mode: threadMode };
379 const reconnectShell = { ...resumedShell.recorder.totals(), mode: shellMode };
380 const reconnectSqlStatements = counter.count() - reconnectSqlStart;
381 assert.equal(threadMode, "snapshot");
382​
383 for (const events of longTurnThreadBatches(provider)) yield* sink.write({ events });
384 const get = (path: string) =>
385 measureHttpGet({
386 url: `${base}${path}`,
387 headers: { [ORCHESTRATION_PROTOCOL_HEADER]: String(ORCHESTRATION_PROTOCOL_VERSION) },
388 }).pipe(Effect.tap((http) => Effect.sync(() => assert.equal(http.status, 200))));
389 const decoded = (http: HttpTransferMeasurement) =>
390 Buffer.from(http.decodedBody).toString();
391 const longTurnPath = `/api/orchestration/threads/${LONG_TURN_THREAD_ID}`;
392 const readColdOpen = (query: string) =>
393 Effect.gen(function* () {
394 const http = yield* get(`${longTurnPath}/bounded?${query}`);
395 const snapshot = yield* decodeBoundedSnapshot(decoded(http));
396 const rows = snapshot.projection.visibleTurnItems.length;
397 return { http, rows, cursor: snapshot.historyCursor };
398 });
399 const readHistoryPage = (cursor: string, query: string) =>
400 Effect.gen(function* () {
401 const http = yield* get(
402 `${longTurnPath}/history?cursor=${encodeURIComponent(cursor)}&${query}`,
403 );
404 const page = yield* decodeHistoryPage(decoded(http));
405 assert.isTrue(page.hasMoreHistory);
406 return { http, rows: page.items.length };
407 });
408 const readShell = (query: string) =>
409 Effect.gen(function* () {
410 const http = yield* get(`/api/orchestration/shell?${query}`);
411 return { http, rows: (yield* decodeShellSnapshot(decoded(http))).threads.length };
412 });
413​
414 const { cursor: _, ...longTurnColdOpenLegacy } =
415 yield* readColdOpen("compactTurnItems=1");
416 const { cursor, ...longTurnColdOpen } = yield* readColdOpen(CLIENT_BOUNDED_QUERY);
417 if (cursor === null) return yield* Effect.die("Expected older long-turn history");
418 const longTurnHistoryPageLegacy = yield* readHistoryPage(cursor, "");
419 const longTurnHistoryPage = yield* readHistoryPage(cursor, CLIENT_HISTORY_QUERY);
420​
421 // The transfer thread plus the long-turn thread.
422 const earlierThreads = decodedShell.threads.length + 1;
423 yield* sink.write({ events: shellFleetEvents(provider) });
424 const fleetShellLegacy = yield* readShell("");
425 const fleetShell = yield* readShell(CLIENT_SHELL_QUERY);
426 assert.equal(
427 fleetShellLegacy.rows,
428 earlierThreads + SHELL_SETTLED_THREADS + SHELL_IDLE_SUBAGENTS,
429 );
430 return {
431 provider,
432 threadSnapshot,
433 shellSnapshot,
434 measuredTurnWebSocket,
435 measuredTurnShellWebSocket,
436 measuredTurnSecondClientWebSocket,
437 measuredTurnSqlStatements,
438 reconnectThread,
439 reconnectShell,
440 reconnectSqlStatements,
441 longTurnColdOpenLegacy,
442 longTurnColdOpen,
443 longTurnHistoryPageLegacy,
444 longTurnHistoryPage,
445 fleetShellLegacy,
446 fleetShell,
447 } satisfies TransferBudgetRun;
448 }).pipe(
449 Effect.provide(Layer.fresh(layerServices).pipe(Layer.provideMerge(NodeServices.layer))),
450 Effect.withTracer(counter.tracer),
451 ),
452 );
453 runs.push(run);
454 }
455 const fs = yield* FileSystem.FileSystem;
456 const report = formatTransferBudgetReport(runs);
457 const outputPaths = yield* Config.all({
458 report: Config.String("T3CODE_TRANSFER_BUDGET_REPORT_PATH").pipe(Config.withDefault("")),
459 result: Config.String("T3CODE_TRANSFER_BUDGET_RESULT_PATH").pipe(Config.withDefault("")),
460 });
461 for (const [path, contents] of [
462 [outputPaths.report, report],
463 [outputPaths.result, formatTransferBudgetResult(runs)],
464 ])
465 if (path && contents) yield* fs.writeFileString(path, contents);
466 yield* Effect.log(report);
467 assert.deepEqual(transferBudgetViolations(runs), []);
468 }).pipe(Effect.provide(NodeServices.layer)),
469);