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