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