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

transferBudgetV2.integration.test.ts

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