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

transferBudgetV2.integration.test.ts

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