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