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

transferBudgetV2.integration.test.ts

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