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

transferBudgetV2.integration.test.ts

360 lines15.7 KB

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