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 OrchestrationV2ThreadDetailSnapshot,
20 OrchestrationV2ShellSnapshot,
21 OrchestrationV2GetThreadProjectionError,
22 OrchestrationV2GetShellSnapshotError,
23 ProviderDriverKind,
24 type OrchestrationV2ThreadStreamItem,
25 type OrchestrationV2ShellStreamItem,
26} from "@t3tools/contracts";
27import * as Context from "effect/Context";
28import * as Effect from "effect/Effect";
29import * as FileSystem from "effect/FileSystem";
30import * as Layer from "effect/Layer";
31import * as PubSub from "effect/PubSub";
32import * as Queue from "effect/Queue";
33import * as Schema from "effect/Schema";
34import * as Scope from "effect/Scope";
35import * as Stream from "effect/Stream";
36import * as HttpApi from "effect/http-api/HttpApi";
37import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
38import { HttpRouter, HttpServer } from "effect/http";
39import { Rpc, RpcGroup, RpcServer, RpcSerialization } from "effect/rpc";
40import * as ServerEnvironment from "../src/environment/ServerEnvironment.ts";
41import * as SqlitePersistence from "../src/persistence/Sqlite.ts";
42import * as OrchestrationEventStore from "../src/persistence/OrchestrationEventStore.ts";
43import * as EventStore from "../src/orchestration-v2/EventStore.ts";
44import * as EventSink from "../src/orchestration-v2/EventSink.ts";
45import * as ProjectionStore from "../src/orchestration-v2/ProjectionStore.ts";
46import * as ThreadManagementService from "../src/orchestration-v2/ThreadManagementService.ts";
47import * as ProjectStore from "../src/orchestration-v2/ProjectStore.ts";
48import * as ProjectService from "../src/project/ProjectService.ts";
49import * as ProjectEnrichmentService from "../src/project/ProjectEnrichmentService.ts";
50import * as OrchestrationHttp from "../src/orchestration-v2/http.ts";
51import * as ServerHttp from "../src/http.ts";
52import { subscribeOrchestrationV2Thread, subscribeOrchestrationV2Shell } from "../src/ws.ts";
53import {
54 measureHttpGet,
55 openMeasuredWsClient,
56 type MeasuredWsClient,
57} from "./NetworkTransferMeasurement.integration.ts";
58import { makeSqlStatementCounter } from "./SqlStatementCounter.integration.ts";
59import {
60 formatTransferBudgetReport,
61 formatTransferBudgetResult,
62 transferBudgetViolations,
63 type TransferBudgetRun,
64} from "./TransferBudgetReport.integration.ts";
65import { TRANSFER_HISTORY_TURN_COUNT } from "./fixtures/transferBudget.ts";
66import { THREAD_ID, threadCreated, turnEvents } from "./TransferBudgetV2Fixture.integration.ts";
67
68const decodeThreadSnapshot = Schema.decodeUnknownEffect(
69 Schema.fromJsonString(Schema.toCodecJson(OrchestrationV2ThreadDetailSnapshot)),
70);
71const decodeShellSnapshot = Schema.decodeUnknownEffect(
72 Schema.fromJsonString(Schema.toCodecJson(OrchestrationV2ShellSnapshot)),
73);
74
75const layerPersistence = EventSink.layer.pipe(
76 Layer.provideMerge(EventStore.layerFromOrchestrationEventStore),
77 Layer.provideMerge(ProjectionStore.layer),
78 Layer.provideMerge(OrchestrationEventStore.layer),
79 Layer.provideMerge(SqlitePersistence.layerMemory),
80);
81const layerManagement = Layer.unwrap(
82 Effect.gen(function* () {
83 const projections = yield* ProjectionStore.ProjectionStoreV2;
84 const sink = yield* EventSink.EventSinkV2;
85 return Layer.mock(ThreadManagementService.ThreadManagementService)({
86 ensureLegacyTranscript: () => Effect.void,
87 getThreadSnapshot: (id) => projections.getThreadSnapshot(id).pipe(Effect.orDie),
88 getThreadSnapshotWindow: (id, options) =>
89 projections.getThreadSnapshotWindow(id, options).pipe(Effect.orDie),
90 getThreadShell: (id) => projections.getThreadShell(id).pipe(Effect.orDie),
91 getShellSnapshot: (options) => projections.getShellSnapshot(options).pipe(Effect.orDie),
92 listActiveSubagentThreadIds: () =>
93 projections.listActiveSubagentThreadIds().pipe(Effect.orDie),
94 readShellSnapshot: (options) =>
95 projections.readShellSnapshot(options).pipe(Effect.map(Effect.orDie), Effect.orDie),
96 streamStoredEventsFrom: (input) =>
97 sink.stream({ ...input, bounded: true }).pipe(Stream.orDie),
98 });
99 }),
100);
101const layerEnrichment = Layer.unwrap(
102 Effect.gen(function* () {
103 const changes = yield* PubSub.unbounded<never>();
104 return Layer.mock(ProjectEnrichmentService.ProjectEnrichmentService)({
105 getAvailable: () =>
106 Effect.succeed({
107 repositoryIdentity: null,
108 faviconPath: null,
109 repositoryIdentityResolved: true,
110 }),
111 subscribeChanges: PubSub.subscribe(changes),
112 });
113 }),
114);
115const layerServices = layerManagement.pipe(
116 Layer.provideMerge(
117 Layer.succeed(ServerEnvironment.ServerEnvironmentIdentity, {
118 getEnvironmentId: Effect.succeed(EnvironmentId.make("transfer-test")),
119 }),
120 ),
121 Layer.provideMerge(ProjectStore.layer),
122 Layer.provideMerge(Layer.mock(ProjectService.ProjectService)({})),
123 Layer.provideMerge(layerEnrichment),
124 Layer.provideMerge(layerPersistence),
125);
126class TransferApi extends HttpApi.make("environment").add(
127 EnvironmentHttpApi.groups.orchestration,
128) {}
129const layerAuth = Layer.succeed(EnvironmentAuthenticatedAuth, (effect) =>
130 effect.pipe(
131 Effect.provideService(EnvironmentAuthenticatedPrincipal, {
132 sessionId: AuthSessionId.make("transfer-session"),
133 subject: "transfer-test",
134 method: "browser-session-cookie",
135 scopes: new Set([AuthOrchestrationReadScope]),
136 }),
137 ),
138);
139const group = RpcGroup.make(
140 Rpc.make(ORCHESTRATION_V2_WS_METHODS.subscribeThread, {
141 payload: OrchestrationV2RpcSchemas.subscribeThread.input,
142 success: OrchestrationV2RpcSchemas.subscribeThread.output,
143 error: OrchestrationV2GetThreadProjectionError,
144 stream: true,
145 }),
146 Rpc.make(ORCHESTRATION_V2_WS_METHODS.subscribeShell, {
147 payload: OrchestrationV2RpcSchemas.subscribeShell.input,
148 success: OrchestrationV2RpcSchemas.subscribeShell.output,
149 error: OrchestrationV2GetShellSnapshotError,
150 stream: true,
151 }),
152);
153const layerHandlers = group.toLayer({
154 [ORCHESTRATION_V2_WS_METHODS.subscribeThread]: (input) =>
155 Stream.unwrap(subscribeOrchestrationV2Thread(input)),
156 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: (input) =>
157 Stream.unwrap(subscribeOrchestrationV2Shell(input)),
158});
159const layerRoutes = Layer.mergeAll(
160 HttpApiBuilder.layer(TransferApi).pipe(
161 Layer.provide(OrchestrationHttp.layer),
162 Layer.provide(layerAuth),
163 ),
164 RpcServer.layerHttp({ group, path: "/ws", protocol: "websocket" }).pipe(
165 Layer.provide(layerHandlers),
166 Layer.provide(RpcSerialization.layerJson),
167 ),
168).pipe(Layer.provide(ServerHttp.layerHttpCompression), Layer.provide(NodeHttpPlatform.layer));
169
170function difference(
171 after: { wireBytes: number; decodedBytes: number; messages: number },
172 before: typeof after,
173) {
174 return {
175 wireBytes: after.wireBytes - before.wireBytes,
176 decodedBytes: after.decodedBytes - before.decodedBytes,
177 messages: after.messages - before.messages,
178 };
179}
180type StreamItem = OrchestrationV2ThreadStreamItem | OrchestrationV2ShellStreamItem;
181const collectUntil = Effect.fn("transfer.collectUntil")(function* <T extends StreamItem>(
182 queue: Queue.Queue<T>,
183 done: (item: T) => boolean,
184) {
185 const items: T[] = [];
186 while (true) {
187 const item = yield* Queue.take(queue);
188 items.push(item);
189 if (done(item)) return items;
190 }
191});
192const subscribe = Effect.fn("transfer.subscribe")(function* (
193 client: MeasuredWsClient,
194 kind: "thread" | "shell",
195 afterSequence: number,
196) {
197 const queue = yield* Queue.unbounded<StreamItem>();
198 const stream: Stream.Stream<StreamItem, unknown> =
199 kind === "thread"
200 ? client.client[ORCHESTRATION_V2_WS_METHODS.subscribeThread]({
201 threadId: THREAD_ID,
202 afterSequence,
203 requestCompletionMarker: true,
204 acceptBoundedSnapshot: true,
205 })
206 : client.client[ORCHESTRATION_V2_WS_METHODS.subscribeShell]({
207 afterSequence,
208 requestCompletionMarker: true,
209 });
210 yield* stream.pipe(
211 Stream.runForEach((item) => Queue.offer(queue, item)),
212 Scope.provide(client.scope),
213 Effect.forkIn(client.scope),
214 );
215 return queue;
216});
217const synchronized = (queue: Queue.Queue<StreamItem>) =>
218 collectUntil(queue, (item) => item.kind === "synchronized").pipe(
219 Effect.map((items) =>
220 items.some((item) => item.kind === "snapshot") ? ("snapshot" as const) : ("replay" as const),
221 ),
222 );
223
224it.live("reports V2 thread HTTP and WebSocket transfer budgets", () =>
225 Effect.gen(function* () {
226 const runs: TransferBudgetRun[] = [];
227 for (const provider of [
228 ProviderDriverKind.make("codex"),
229 ProviderDriverKind.make("claudeAgent"),
230 ]) {
231 const counter = makeSqlStatementCounter();
232 const run = yield* Effect.scoped(
233 Effect.gen(function* () {
234 const sink = yield* EventSink.EventSinkV2;
235 const projection = yield* ProjectionStore.ProjectionStoreV2;
236 yield* sink.write({ events: [threadCreated(provider)] });
237 for (let index = 0; index < TRANSFER_HISTORY_TURN_COUNT; index++)
238 yield* sink.write({ events: turnEvents(provider, index, false) });
239 const context = yield* Effect.context<Layer.Success<typeof layerServices>>();
240 const server = yield* Layer.build(
241 HttpRouter.serve(layerRoutes, { disableListenLog: true }).pipe(
242 Layer.provide(Layer.succeedContext(context)),
243 Layer.provideMerge(
244 NodeHttpServer.layer(NodeHttp.createServer, {
245 host: "127.0.0.1",
246 port: 0,
247 websocket: { perMessageDeflate: true },
248 }),
249 ),
250 ),
251 );
252 const address = Context.get(server, HttpServer.HttpServer).address;
253 if (!("port" in address)) return yield* Effect.die("Expected TCP server");
254 const base = `http://127.0.0.1:${address.port}`;
255 const threadSnapshot = yield* measureHttpGet({
256 url: `${base}/api/orchestration/threads/${THREAD_ID}`,
257 headers: { [ORCHESTRATION_PROTOCOL_HEADER]: String(ORCHESTRATION_PROTOCOL_VERSION) },
258 });
259 assert.equal(
260 threadSnapshot.status,
261 200,
262 Buffer.from(threadSnapshot.decodedBody).toString(),
263 );
264 assert.equal(threadSnapshot.contentEncoding, "gzip");
265 const decodedThread = yield* decodeThreadSnapshot(
266 Buffer.from(threadSnapshot.decodedBody).toString(),
267 );
268 assert.equal(decodedThread.projection.messages.length, TRANSFER_HISTORY_TURN_COUNT * 2);
269 assert.equal(decodedThread.projection.turnItems.length, TRANSFER_HISTORY_TURN_COUNT * 6);
270 assert.notInclude(Buffer.from(threadSnapshot.decodedBody).toString(), "digest=");
271 const shellSnapshot = yield* measureHttpGet({
272 url: `${base}/api/orchestration/shell`,
273 headers: { [ORCHESTRATION_PROTOCOL_HEADER]: String(ORCHESTRATION_PROTOCOL_VERSION) },
274 });
275 assert.equal(shellSnapshot.status, 200);
276 const decodedShell = yield* decodeShellSnapshot(
277 Buffer.from(shellSnapshot.decodedBody).toString(),
278 );
279 assert.equal(decodedShell.threads.length, 1);
280 const sequence = decodedThread.snapshotSequence;
281 assert.equal(decodedShell.snapshotSequence, sequence);
282 const url = `${base.replace("http:", "ws:")}/ws`;
283 const thread = yield* openMeasuredWsClient({ url, cookie: "" });
284 const shell = yield* openMeasuredWsClient({ url, cookie: "" });
285 const second = yield* openMeasuredWsClient({ url, cookie: "" });
286 assert.include(thread.recorder.negotiatedExtensions(), "permessage-deflate");
287 const tq = yield* subscribe(thread, "thread", sequence);
288 const sq = yield* subscribe(shell, "shell", sequence);
289 const ttq = yield* subscribe(second, "thread", sequence);
290 const ssq = yield* subscribe(second, "shell", sequence);
291 for (const queue of [tq, sq, ttq, ssq])
292 assert.equal(yield* synchronized(queue), "replay");
293 const threadBefore = thread.recorder.totals();
294 const shellBefore = shell.recorder.totals();
295 const secondBefore = second.recorder.totals();
296 const sqlBefore = counter.count();
297 const events = turnEvents(provider, TRANSFER_HISTORY_TURN_COUNT, true);
298 const stored = yield* sink.write({ events });
299 const last = stored.at(-1)!;
300 const threadTerminal = (item: StreamItem) =>
301 "sequence" in item && item.sequence >= last.sequence;
302 // Shell items carry the shell read when their batch is projected, and unchanged
303 // shells are skipped, so a turn split across batches may never yield an item at
304 // the last sequence. Wait for the final shell instead.
305 const finalShell = yield* projection.getThreadShell(THREAD_ID);
306 const shellTerminal = (item: StreamItem) =>
307 item.kind === "thread.updated" && NodeUtil.isDeepStrictEqual(item.thread, finalShell);
308 for (const queue of [tq, ttq]) yield* collectUntil(queue, threadTerminal);
309 for (const queue of [sq, ssq]) yield* collectUntil(queue, shellTerminal);
310 const measuredTurnWebSocket = difference(thread.recorder.totals(), threadBefore);
311 const measuredTurnShellWebSocket = difference(shell.recorder.totals(), shellBefore);
312 const measuredTurnSecondClientWebSocket = difference(
313 second.recorder.totals(),
314 secondBefore,
315 );
316 const measuredTurnSqlStatements = counter.count() - sqlBefore;
317 const durable = yield* projection.getThreadProjection(THREAD_ID);
318 assert.isTrue(
319 durable.turnItems.some(
320 (item) =>
321 item.type === "dynamic_tool" && JSON.stringify(item.output).length > 1_000_000,
322 ),
323 );
324 yield* second.close;
325 const reconnectSqlStart = counter.count();
326 const resumedThread = yield* openMeasuredWsClient({ url, cookie: "" });
327 const resumedShell = yield* openMeasuredWsClient({ url, cookie: "" });
328 const rq = yield* subscribe(resumedThread, "thread", sequence);
329 const rsq = yield* subscribe(resumedShell, "shell", sequence);
330 const threadMode = yield* synchronized(rq);
331 const shellMode = yield* synchronized(rsq);
332 const reconnectThread = { ...resumedThread.recorder.totals(), mode: threadMode };
333 const reconnectShell = { ...resumedShell.recorder.totals(), mode: shellMode };
334 assert.equal(threadMode, "snapshot");
335 return {
336 provider,
337 threadSnapshot,
338 shellSnapshot,
339 measuredTurnWebSocket,
340 measuredTurnShellWebSocket,
341 measuredTurnSecondClientWebSocket,
342 measuredTurnSqlStatements,
343 reconnectThread,
344 reconnectShell,
345 reconnectSqlStatements: counter.count() - reconnectSqlStart,
346 } satisfies TransferBudgetRun;
347 }).pipe(
348 Effect.provide(Layer.fresh(layerServices).pipe(Layer.provideMerge(NodeServices.layer))),
349 Effect.withTracer(counter.tracer),
350 ),
351 );
352 runs.push(run);
353 }
354 const fs = yield* FileSystem.FileSystem;
355 const report = formatTransferBudgetReport(runs);
356 for (const [path, contents] of [
357 [process.env.T3CODE_TRANSFER_BUDGET_REPORT_PATH, report],
358 [process.env.T3CODE_TRANSFER_BUDGET_RESULT_PATH, formatTransferBudgetResult(runs)],
359 ])
360 if (path && contents) yield* fs.writeFileString(path, contents);
361 yield* Effect.log(report);
362 assert.deepEqual(transferBudgetViolations(runs), []);
363 }).pipe(Effect.provide(NodeServices.layer)),
364);