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 * 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 OrchestrationV2ShellHttpSnapshot,
23 OrchestrationV2ShellResumable,
24 OrchestrationV2GetThreadProjectionError,
25 OrchestrationV2GetShellSnapshotError,
26 ProviderDriverKind,
27 type EnvironmentOrchestrationShellSnapshotQuery,
28 type EnvironmentOrchestrationThreadBoundedSnapshotQuery,
29 type EnvironmentOrchestrationThreadHistoryQuery,
30 type OrchestrationV2SubscribeShellInput,
31 type OrchestrationV2SubscribeThreadInput,
32 type OrchestrationV2ThreadStreamItem,
33 type OrchestrationV2ShellStreamItem,
34 type ThreadId,
35} from "@t3tools/contracts";
36import * as Context from "effect/Context";
37import * as Config from "effect/Config";
38import * as Effect from "effect/Effect";
39import * as FileSystem from "effect/FileSystem";
40import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
41import * as Layer from "effect/Layer";
42import * as PubSub from "effect/PubSub";
43import * as Queue from "effect/Queue";
44import * as Schema from "effect/Schema";
45import * as Scope from "effect/Scope";
46import * as Stream from "effect/Stream";
47import * as HttpApi from "effect/http-api/HttpApi";
48import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
49import { HttpRouter, HttpServer } from "effect/http";
50import { Rpc, RpcGroup, RpcServer, RpcSerialization } from "effect/rpc";
51import * as ServerEnvironment from "../src/environment/ServerEnvironment.ts";
52import * as SqlitePersistence from "../src/persistence/Sqlite.ts";
53import * as OrchestrationEventStore from "../src/persistence/OrchestrationEventStore.ts";
54import * as EventStore from "../src/orchestration-v2/EventStore.ts";
55import * as EventSink from "../src/orchestration-v2/EventSink.ts";
56import * as ProjectionStore from "../src/orchestration-v2/ProjectionStore.ts";
57import * as ThreadManagementService from "../src/orchestration-v2/ThreadManagementService.ts";
58import * as ProjectStore from "../src/orchestration-v2/ProjectStore.ts";
59import * as ProjectService from "../src/project/ProjectService.ts";
60import * as ProjectEnrichmentService from "../src/project/ProjectEnrichmentService.ts";
61import * as OrchestrationHttp from "../src/orchestration-v2/http.ts";
62import * as ServerHttp from "../src/http.ts";
63import { subscribeOrchestrationV2Thread, subscribeOrchestrationV2Shell } from "../src/ws.ts";
64import {
65 measureHttpGet,
66 openMeasuredWsClient,
67 type HttpTransferMeasurement,
68 type MeasuredWsClient,
69} from "./NetworkTransferMeasurement.integration.ts";
70import { makeSqlStatementCounter } from "./SqlStatementCounter.integration.ts";
71import {
72 formatTransferBudgetReport,
73 formatTransferBudgetResult,
74 formatTransferBudgetScenarios,
75 transferBudgetViolations,
76 type TransferBudgetRun,
77} from "./TransferBudgetReport.integration.ts";
78import { TRANSFER_HISTORY_TURN_COUNT } from "./fixtures/transferBudget.ts";
79import {
80 FLEET_PROJECT_IDENTITY,
81 fleetProjectCreated,
82 LONG_TURN_THREAD_ID,
83 longTurnThreadBatches,
84 SHELL_IDLE_SUBAGENTS,
85 SHELL_SETTLED_THREADS,
86 shellFleetEvents,
87 STALE_TODO_LAST_FINISHED_CHECKPOINT_ID,
88 STALE_TODO_LIVE_RUN_ID,
89 STALE_TODO_SUBAGENTS_PER_RUN,
90 STALE_TODO_THREAD_ID,
91 staleTodoListThreadBatches,
92 THREAD_ID,
93 threadCreated,
94 turnEvents,
95} from "./TransferBudgetV2Fixture.integration.ts";
96
97// The opt-ins current web and mobile clients send, as client-runtime's boundedThreadSnapshotHttp.ts,
98// threadHistoryHttp.ts, shellSnapshotHttp.ts, threads.ts and shell.ts send them. Each is `Required`,
99// so an opt-in added to a contract fails typecheck here until this test sends it. An omitted field
100// differs per request (a cursor, or what the client holds), so each scenario sends its own.
101const CLIENT_BOUNDED_OPT_INS = {
102 compactTurnItems: "1",
103 dedupeBodies: "1",
104 compactIds: "1",
105 deferWork: "1",
106} satisfies Required<typeof EnvironmentOrchestrationThreadBoundedSnapshotQuery.Type>;
107const CLIENT_HISTORY_OPT_INS = { compactIds: "1", deferWork: "1" } satisfies Required<
108 Omit<
109 typeof EnvironmentOrchestrationThreadHistoryQuery.Type,
110 "cursor" | "throughEntryId" | "view" | "detach"
111 >
112>;
113const CLIENT_SHELL_OPT_INS = {
114 omitIdleSubagents: "1",
115 omitOlderSettled: "1",
116} satisfies Required<Omit<typeof EnvironmentOrchestrationShellSnapshotQuery.Type, "resumeFrom">>;
117const CLIENT_THREAD_SUBSCRIPTION = {
118 requestCompletionMarker: true,
119 acceptBoundedSnapshot: true,
120 acceptDeferredWork: true,
121 acceptCompactTurnItems: true,
122 acceptCompactIds: true,
123 acceptDedupedBodies: true,
124} satisfies Required<Omit<OrchestrationV2SubscribeThreadInput, "threadId" | "afterSequence">>;
125type ShellResumeField = "afterSequence" | "httpSnapshotFallback" | "knownProjectIdentities";
126const CLIENT_SHELL_SUBSCRIPTION = {
127 requestCompletionMarker: true,
128 omitIdleSubagents: true,
129 omitOlderSettled: true,
130} satisfies Required<Omit<OrchestrationV2SubscribeShellInput, ShellResumeField>>;
131const query = (optIns: Readonly<Record<string, string>>) => new URLSearchParams(optIns).toString();
132const CLIENT_BOUNDED_QUERY = query(CLIENT_BOUNDED_OPT_INS);
133const CLIENT_HISTORY_QUERY = query(CLIENT_HISTORY_OPT_INS);
134const CLIENT_SHELL_QUERY = query(CLIENT_SHELL_OPT_INS);
135// A client that holds shell rows names their cursor in the same request.
136const clientShellResumeQuery = (resumeFrom: number) =>
137 query({
138 ...CLIENT_SHELL_OPT_INS,
139 resumeFrom: String(resumeFrom),
140 } satisfies Required<typeof EnvironmentOrchestrationShellSnapshotQuery.Type>);
141
142const decodeThreadSnapshot = Schema.decodeUnknownEffect(
143 Schema.fromJsonString(Schema.toCodecJson(OrchestrationV2ThreadDetailSnapshot)),
144);
145const decodeBoundedSnapshot = Schema.decodeUnknownEffect(
146 Schema.fromJsonString(Schema.toCodecJson(OrchestrationV2ThreadBoundedSnapshot)),
147);
148const decodeHistoryPage = Schema.decodeUnknownEffect(
149 Schema.fromJsonString(Schema.toCodecJson(OrchestrationV2ThreadHistoryPage)),
150);
151const decodeShellSnapshot = Schema.decodeUnknownEffect(
152 Schema.fromJsonString(Schema.toCodecJson(OrchestrationV2ShellHttpSnapshot)),
153);
154const decodeShellResumable = Schema.decodeUnknownEffect(
155 Schema.fromJsonString(Schema.toCodecJson(OrchestrationV2ShellResumable)),
156);
157
158const layerPersistence = EventSink.layer.pipe(
159 Layer.provideMerge(EventStore.layerFromOrchestrationEventStore),
160 Layer.provideMerge(ProjectionStore.layer.pipe(Layer.provide(NodeCrypto.layerDigest))),
161 Layer.provideMerge(OrchestrationEventStore.layer),
162 Layer.provideMerge(SqlitePersistence.layerMemory),
163);
164const layerManagement = Layer.unwrap(
165 Effect.gen(function* () {
166 const projections = yield* ProjectionStore.ProjectionStoreV2;
167 const sink = yield* EventSink.EventSinkV2;
168 return Layer.mock(ThreadManagementService.ThreadManagementService)({
169 ensureLegacyTranscript: () => Effect.void,
170 getThreadSnapshot: (id) => projections.getThreadSnapshot(id).pipe(Effect.orDie),
171 getThreadSnapshotWindow: (id, options) =>
172 projections.getThreadSnapshotWindow(id, options).pipe(Effect.orDie),
173 getThreadHistoryPage: (id, cursor, throughEntryId, conversationOnly, workMode) =>
174 projections
175 .getThreadHistoryPage(id, cursor, throughEntryId, conversationOnly, workMode)
176 .pipe(Effect.orDie),
177 getThreadShell: (id) => projections.getThreadShell(id).pipe(Effect.orDie),
178 getShellSnapshot: (options) => projections.getShellSnapshot(options).pipe(Effect.orDie),
179 listActiveShellIndex: () => projections.listActiveShellIndex().pipe(Effect.orDie),
180 listActiveSubagentThreadIds: () =>
181 projections.listActiveSubagentThreadIds().pipe(Effect.orDie),
182 readShellSnapshot: (options) =>
183 projections.readShellSnapshot(options).pipe(Effect.map(Effect.orDie), Effect.orDie),
184 streamStoredEventsFrom: (input) =>
185 sink.stream({ ...input, bounded: true }).pipe(Stream.orDie),
186 });
187 }),
188);
189const layerEnrichment = Layer.unwrap(
190 Effect.gen(function* () {
191 const changes = yield* PubSub.unbounded<never>();
192 return Layer.mock(ProjectEnrichmentService.ProjectEnrichmentService)({
193 getAvailable: () =>
194 Effect.succeed({
195 repositoryIdentity: FLEET_PROJECT_IDENTITY,
196 faviconPath: null,
197 repositoryIdentityResolved: true,
198 }),
199 subscribeChanges: PubSub.subscribe(changes),
200 });
201 }),
202);
203const layerServices = layerManagement.pipe(
204 Layer.provideMerge(
205 Layer.succeed(ServerEnvironment.ServerEnvironmentIdentity, {
206 getEnvironmentId: Effect.succeed(EnvironmentId.make("transfer-test")),
207 }),
208 ),
209 Layer.provideMerge(ProjectStore.layer),
210 Layer.provideMerge(Layer.mock(ProjectService.ProjectService)({})),
211 Layer.provideMerge(layerEnrichment),
212 Layer.provideMerge(layerPersistence),
213);
214class TransferApi extends HttpApi.make("environment").add(
215 EnvironmentHttpApi.groups.orchestration,
216) {}
217const layerAuth = Layer.succeed(EnvironmentAuthenticatedAuth, (effect) =>
218 effect.pipe(
219 Effect.provideService(EnvironmentAuthenticatedPrincipal, {
220 sessionId: AuthSessionId.make("transfer-session"),
221 subject: "transfer-test",
222 method: "browser-session-cookie",
223 scopes: new Set([AuthOrchestrationReadScope]),
224 }),
225 ),
226);
227const group = RpcGroup.make(
228 Rpc.make(ORCHESTRATION_V2_WS_METHODS.subscribeThread, {
229 payload: OrchestrationV2RpcSchemas.subscribeThread.input,
230 success: OrchestrationV2RpcSchemas.subscribeThread.output,
231 error: OrchestrationV2GetThreadProjectionError,
232 stream: true,
233 }),
234 Rpc.make(ORCHESTRATION_V2_WS_METHODS.subscribeShell, {
235 payload: OrchestrationV2RpcSchemas.subscribeShell.input,
236 success: OrchestrationV2RpcSchemas.subscribeShell.output,
237 error: OrchestrationV2GetShellSnapshotError,
238 stream: true,
239 }),
240);
241const layerHandlers = group.toLayer({
242 [ORCHESTRATION_V2_WS_METHODS.subscribeThread]: (input) =>
243 Stream.unwrap(subscribeOrchestrationV2Thread(input)),
244 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: (input) =>
245 Stream.unwrap(subscribeOrchestrationV2Shell(input)),
246});
247const layerRoutes = Layer.mergeAll(
248 HttpApiBuilder.layer(TransferApi).pipe(
249 Layer.provide(OrchestrationHttp.layer),
250 Layer.provide(layerAuth),
251 ),
252 RpcServer.layerHttp({ group, path: "/ws", protocol: "websocket" }).pipe(
253 Layer.provide(layerHandlers),
254 Layer.provide(RpcSerialization.layerJson),
255 ),
256).pipe(Layer.provide(ServerHttp.layerHttpCompression), Layer.provide(NodeHttpPlatform.layer));
257
258function difference(
259 after: { wireBytes: number; decodedBytes: number; messages: number },
260 before: typeof after,
261) {
262 return {
263 wireBytes: after.wireBytes - before.wireBytes,
264 decodedBytes: after.decodedBytes - before.decodedBytes,
265 messages: after.messages - before.messages,
266 };
267}
268type StreamItem = OrchestrationV2ThreadStreamItem | OrchestrationV2ShellStreamItem;
269const collectUntil = Effect.fn("transfer.collectUntil")(function* <T extends StreamItem>(
270 queue: Queue.Queue<T>,
271 done: (item: T) => boolean,
272) {
273 const items: T[] = [];
274 while (true) {
275 const item = yield* Queue.take(queue);
276 items.push(item);
277 if (done(item)) return items;
278 }
279});
280type Subscription =
281 | ({ readonly thread: ThreadId } & Pick<OrchestrationV2SubscribeThreadInput, "afterSequence">)
282 | ({ readonly shell: true } & Pick<OrchestrationV2SubscribeShellInput, ShellResumeField>);
283function subscriptionStream(
284 client: MeasuredWsClient,
285 subscription: Subscription,
286): Stream.Stream<StreamItem, unknown> {
287 if ("thread" in subscription) {
288 const { thread, ...resume } = subscription;
289 return client.client[ORCHESTRATION_V2_WS_METHODS.subscribeThread]({
290 ...CLIENT_THREAD_SUBSCRIPTION,
291 ...resume,
292 threadId: thread,
293 });
294 }
295 const { shell: _, ...resume } = subscription;
296 return client.client[ORCHESTRATION_V2_WS_METHODS.subscribeShell]({
297 ...CLIENT_SHELL_SUBSCRIPTION,
298 ...resume,
299 });
300}
301const subscribe = Effect.fn("transfer.subscribe")(function* (
302 client: MeasuredWsClient,
303 subscription: Subscription,
304) {
305 const queue = yield* Queue.unbounded<StreamItem>();
306 yield* subscriptionStream(client, subscription).pipe(
307 Stream.runForEach((item) => Queue.offer(queue, item)),
308 Scope.provide(client.scope),
309 Effect.forkIn(client.scope),
310 );
311 return queue;
312});
313const synchronized = (queue: Queue.Queue<StreamItem>) =>
314 collectUntil(queue, (item) => item.kind === "synchronized").pipe(
315 Effect.map((items) =>
316 items.some((item) => item.kind === "snapshot") ? ("snapshot" as const) : ("replay" as const),
317 ),
318 );
319
320it.live("reports V2 thread HTTP and WebSocket transfer budgets", () =>
321 Effect.gen(function* () {
322 const runs: TransferBudgetRun[] = [];
323 for (const provider of [
324 ProviderDriverKind.make("codex"),
325 ProviderDriverKind.make("claudeAgent"),
326 ]) {
327 const counter = makeSqlStatementCounter();
328 const run = yield* Effect.scoped(
329 Effect.gen(function* () {
330 const sink = yield* EventSink.EventSinkV2;
331 const projection = yield* ProjectionStore.ProjectionStoreV2;
332 yield* sink.write({ events: [threadCreated(provider)] });
333 for (let index = 0; index < TRANSFER_HISTORY_TURN_COUNT; index++)
334 yield* sink.write({ events: turnEvents(provider, index, false) });
335 const context = yield* Effect.context<Layer.Success<typeof layerServices>>();
336 const server = yield* Layer.build(
337 HttpRouter.serve(layerRoutes, { disableListenLog: true }).pipe(
338 Layer.provide(Layer.succeedContext(context)),
339 Layer.provideMerge(
340 NodeHttpServer.layer(NodeHttp.createServer, {
341 host: "127.0.0.1",
342 port: 0,
343 websocket: { perMessageDeflate: true },
344 }),
345 ),
346 ),
347 );
348 const address = Context.get(server, HttpServer.HttpServer).address;
349 if (!("port" in address)) return yield* Effect.die("Expected TCP server");
350 const base = `http://127.0.0.1:${address.port}`;
351 const threadSnapshot = yield* measureHttpGet({
352 url: `${base}/api/orchestration/threads/${THREAD_ID}`,
353 headers: { [ORCHESTRATION_PROTOCOL_HEADER]: String(ORCHESTRATION_PROTOCOL_VERSION) },
354 });
355 assert.equal(
356 threadSnapshot.status,
357 200,
358 Buffer.from(threadSnapshot.decodedBody).toString(),
359 );
360 assert.equal(threadSnapshot.contentEncoding, "gzip");
361 const decodedThread = yield* decodeThreadSnapshot(
362 Buffer.from(threadSnapshot.decodedBody).toString(),
363 );
364 assert.equal(decodedThread.projection.messages.length, TRANSFER_HISTORY_TURN_COUNT * 2);
365 assert.equal(decodedThread.projection.turnItems.length, TRANSFER_HISTORY_TURN_COUNT * 6);
366 assert.notInclude(Buffer.from(threadSnapshot.decodedBody).toString(), "digest=");
367 const shellSnapshot = yield* measureHttpGet({
368 url: `${base}/api/orchestration/shell`,
369 headers: { [ORCHESTRATION_PROTOCOL_HEADER]: String(ORCHESTRATION_PROTOCOL_VERSION) },
370 });
371 assert.equal(shellSnapshot.status, 200);
372 const decodedShell = yield* decodeShellSnapshot(
373 Buffer.from(shellSnapshot.decodedBody).toString(),
374 );
375 assert.equal(decodedShell.threads.length, 1);
376 const sequence = decodedThread.snapshotSequence;
377 assert.equal(decodedShell.snapshotSequence, sequence);
378 const url = `${base.replace("http:", "ws:")}/ws`;
379 const thread = yield* openMeasuredWsClient({ url, cookie: "" });
380 const shell = yield* openMeasuredWsClient({ url, cookie: "" });
381 const second = yield* openMeasuredWsClient({ url, cookie: "" });
382 assert.include(thread.recorder.negotiatedExtensions(), "permessage-deflate");
383 const fromSnapshot = { afterSequence: sequence };
384 const tq = yield* subscribe(thread, { thread: THREAD_ID, ...fromSnapshot });
385 const sq = yield* subscribe(shell, { shell: true, ...fromSnapshot });
386 const ttq = yield* subscribe(second, { thread: THREAD_ID, ...fromSnapshot });
387 const ssq = yield* subscribe(second, { shell: true, ...fromSnapshot });
388 for (const queue of [tq, sq, ttq, ssq])
389 assert.equal(yield* synchronized(queue), "replay");
390 const threadBefore = thread.recorder.totals();
391 const shellBefore = shell.recorder.totals();
392 const secondBefore = second.recorder.totals();
393 const sqlBefore = counter.count();
394 const events = turnEvents(provider, TRANSFER_HISTORY_TURN_COUNT, true);
395 const stored = yield* sink.write({ events });
396 const last = stored.at(-1)!;
397 const threadTerminal = (item: StreamItem) =>
398 "sequence" in item && item.sequence >= last.sequence;
399 // Shell items carry the shell read when their batch is projected, and unchanged
400 // shells are skipped, so a turn split across batches may never yield an item at
401 // the last sequence. Wait for the final shell instead.
402 const finalShell = yield* projection.getThreadShell(THREAD_ID);
403 const shellTerminal = (item: StreamItem) =>
404 item.kind === "thread.updated" && NodeUtil.isDeepStrictEqual(item.thread, finalShell);
405 const liveTurn = yield* collectUntil(tq, threadTerminal);
406 yield* collectUntil(ttq, threadTerminal);
407 // A direct check, so live dedupe stays guarded however small the turn gets.
408 const liveAnswer = liveTurn.flatMap((item) =>
409 item.kind === "event" &&
410 item.event.type === "turn-item.updated" &&
411 item.event.payload.type === "assistant_message"
412 ? [item.event.payload]
413 : [],
414 );
415 assert.equal(liveAnswer.length, 1);
416 assert.equal(liveAnswer[0]!.textOmitted, true);
417 for (const queue of [sq, ssq]) yield* collectUntil(queue, shellTerminal);
418 const measuredTurnWebSocket = difference(thread.recorder.totals(), threadBefore);
419 const measuredTurnShellWebSocket = difference(shell.recorder.totals(), shellBefore);
420 const measuredTurnSecondClientWebSocket = difference(
421 second.recorder.totals(),
422 secondBefore,
423 );
424 const measuredTurnSqlStatements = counter.count() - sqlBefore;
425 const durable = yield* projection.getThreadProjection(THREAD_ID);
426 assert.isTrue(
427 durable.turnItems.some(
428 (item) =>
429 item.type === "dynamic_tool" && JSON.stringify(item.output).length > 1_000_000,
430 ),
431 );
432 yield* second.close;
433 const reconnectSqlStart = counter.count();
434 const resumedThread = yield* openMeasuredWsClient({ url, cookie: "" });
435 const resumedShell = yield* openMeasuredWsClient({ url, cookie: "" });
436 const rq = yield* subscribe(resumedThread, { thread: THREAD_ID, ...fromSnapshot });
437 const rsq = yield* subscribe(resumedShell, { shell: true, ...fromSnapshot });
438 const threadMode = yield* synchronized(rq);
439 const shellMode = yield* synchronized(rsq);
440 const reconnectThread = { ...resumedThread.recorder.totals(), mode: threadMode };
441 const reconnectShell = { ...resumedShell.recorder.totals(), mode: shellMode };
442 const reconnectSqlStatements = counter.count() - reconnectSqlStart;
443 assert.equal(threadMode, "snapshot");
444
445 const get = (path: string) =>
446 measureHttpGet({
447 url: `${base}${path}`,
448 headers: { [ORCHESTRATION_PROTOCOL_HEADER]: String(ORCHESTRATION_PROTOCOL_VERSION) },
449 }).pipe(Effect.tap((http) => Effect.sync(() => assert.equal(http.status, 200))));
450 const decoded = (http: HttpTransferMeasurement) =>
451 Buffer.from(http.decodedBody).toString();
452 const longTurnPath = `/api/orchestration/threads/${LONG_TURN_THREAD_ID}`;
453 const readColdOpen = (query: string) =>
454 Effect.gen(function* () {
455 const http = yield* get(`${longTurnPath}/bounded?${query}`);
456 const snapshot = yield* decodeBoundedSnapshot(decoded(http));
457 const rows = snapshot.projection.visibleTurnItems;
458 const workAnchor = rows.find((row) => row.item.deferredWork !== undefined);
459 return { http, rows: rows.length, cursor: snapshot.historyCursor, workAnchor };
460 });
461 const readHistoryPage = (cursor: string, query: string) =>
462 Effect.gen(function* () {
463 const http = yield* get(
464 `${longTurnPath}/history?cursor=${encodeURIComponent(cursor)}&${query}`,
465 );
466 const page = yield* decodeHistoryPage(decoded(http));
467 assert.isTrue(page.hasMoreHistory);
468 return { http, rows: page.items.length };
469 });
470 const readShell = (query: string) =>
471 Effect.gen(function* () {
472 const http = yield* get(`/api/orchestration/shell?${query}`);
473 const { threads, snapshotSequence, projectIdentities } = yield* decodeShellSnapshot(
474 decoded(http),
475 );
476 return { http, rows: threads.length, snapshotSequence, projectIdentities };
477 });
478 // A new socket, read until the subscription caught up or the server ended it.
479 const open = (subscription: Subscription) =>
480 Effect.gen(function* () {
481 const socket = yield* openMeasuredWsClient({ url, cookie: "" });
482 const items = yield* subscriptionStream(socket, subscription).pipe(
483 Stream.takeUntil((item) => item.kind === "synchronized"),
484 Stream.runCollect,
485 Scope.provide(socket.scope),
486 Effect.orDie,
487 );
488 const totals = socket.recorder.totals();
489 yield* socket.close;
490 return { kinds: items.map((item) => item.kind), items, totals };
491 });
492
493 // A phone that comes back after one ordinary turn replays it, without tool bodies.
494 const shortTurn = yield* sink.write({
495 events: turnEvents(provider, TRANSFER_HISTORY_TURN_COUNT + 1, false),
496 });
497 const shortTurnResume = yield* open({ thread: THREAD_ID, afterSequence: last.sequence });
498 assert.notInclude(shortTurnResume.kinds, "snapshot");
499 // The byte cap below also passes when the resume skips the turn.
500 assert.isTrue(
501 shortTurnResume.items.some(
502 (item) => "sequence" in item && item.sequence === shortTurn.at(-1)!.sequence,
503 ),
504 );
505
506 // A turn that is still running cannot defer its work, so it loads in row-budget windows.
507 const [finishLongTurn, ...longTurnHistory] = longTurnThreadBatches(provider).toReversed();
508 for (const events of longTurnHistory.toReversed()) yield* sink.write({ events });
509 const longTurnRunningColdOpenLegacy = yield* readColdOpen("compactTurnItems=1");
510 const longTurnRunningColdOpen = yield* readColdOpen(CLIENT_BOUNDED_QUERY);
511 const { cursor } = longTurnRunningColdOpen;
512 if (cursor === null) return yield* Effect.die("Expected older long-turn history");
513 const longTurnRunningHistoryPageLegacy = yield* readHistoryPage(cursor, "");
514 const longTurnRunningHistoryPage = yield* readHistoryPage(cursor, CLIENT_HISTORY_QUERY);
515
516 // Once it finishes, its work stays on the server until a group is expanded.
517 yield* sink.write({ events: finishLongTurn! });
518 const longTurnColdOpen = yield* readColdOpen(CLIENT_BOUNDED_QUERY);
519 const { workAnchor } = longTurnColdOpen;
520 if (workAnchor?.item.deferredWork === undefined)
521 return yield* Effect.die("Expected the finished long turn to defer its work");
522 const longTurnWorkPage = yield* readHistoryPage(
523 workAnchor.item.deferredWork.cursor,
524 `view=work&throughEntryId=${encodeURIComponent(workAnchor.sourceItemId)}&compactIds=1`,
525 );
526 // Mobile opens a thread over the socket alone.
527 const socketOpen = yield* open({ thread: LONG_TURN_THREAD_ID });
528 const socketSnapshot = socketOpen.items.find(
529 (item) => item.kind === "snapshot" && "projection" in item,
530 );
531 if (socketSnapshot?.kind !== "snapshot" || !("projection" in socketSnapshot))
532 return yield* Effect.die("Expected a bounded socket snapshot");
533 const longTurnSocketColdOpen = {
534 ...socketOpen,
535 rows: socketSnapshot.projection.visibleTurnItems.length,
536 };
537 // The row cap below also passes when the socket ignores the deferral and sends a window.
538 assert.equal(longTurnSocketColdOpen.rows, longTurnColdOpen.rows);
539 const idleThreadResume = yield* open({
540 thread: LONG_TURN_THREAD_ID,
541 afterSequence: socketSnapshot.snapshotSequence,
542 });
543 assert.deepEqual(idleThreadResume.kinds, ["synchronized"]);
544
545 // The transfer thread plus the long-turn thread.
546 const earlierThreads = decodedShell.threads.length + 1;
547 // The fleet's project is in a repository. Earlier phases have no project, as on `main`.
548 yield* (yield* ProjectStore.ProjectStoreV2).apply(fleetProjectCreated);
549 yield* sink.write({ events: shellFleetEvents(provider) });
550 const fleetShellLegacy = yield* readShell("");
551 const fleetShell = yield* readShell(CLIENT_SHELL_QUERY);
552 assert.equal(
553 fleetShellLegacy.rows,
554 earlierThreads + SHELL_SETTLED_THREADS + SHELL_IDLE_SUBAGENTS,
555 );
556 const { projectIdentities } = fleetShell;
557 if (projectIdentities === undefined)
558 return yield* Effect.die("Expected the shell snapshot to name its project identities");
559 // A cold connect subscribes from the snapshot it just loaded and names its identities.
560 // Without them the resume sends the project again, in a marked snapshot.
561 const fleetShellSubscribe = yield* open({
562 shell: true,
563 afterSequence: fleetShell.snapshotSequence,
564 knownProjectIdentities: projectIdentities,
565 });
566 assert.notInclude(fleetShellSubscribe.kinds, "snapshot");
567 // A client that holds those rows asks the route whether they still resume, and keeps them.
568 const fleetShellResumeHttp = yield* get(
569 `/api/orchestration/shell?${clientShellResumeQuery(fleetShell.snapshotSequence)}`,
570 );
571 yield* decodeShellResumable(decoded(fleetShellResumeHttp));
572 const fleetShellResume = { http: fleetShellResumeHttp, rows: 0 };
573 // A cursor too old to replay gets the snapshot in the same answer.
574 const staleShellReload = yield* readShell(clientShellResumeQuery(sequence));
575 assert.equal(staleShellReload.rows, fleetShell.rows);
576 // When that request fails, the socket tells the client to reload, with no snapshot.
577 const staleShellResume = yield* open({
578 shell: true,
579 afterSequence: sequence,
580 httpSnapshotFallback: true,
581 });
582 assert.deepEqual(staleShellResume.kinds, ["snapshot-required"]);
583
584 for (const events of staleTodoListThreadBatches(provider)) yield* sink.write({ events });
585 const staleTodoHttp = yield* get(
586 `/api/orchestration/threads/${STALE_TODO_THREAD_ID}/bounded?${CLIENT_BOUNDED_QUERY}`,
587 );
588 const staleTodo = (yield* decodeBoundedSnapshot(decoded(staleTodoHttp))).projection;
589 // Clients show the diff of the last finished turn from this record.
590 assert.include(
591 staleTodo.checkpoints.map((checkpoint) => checkpoint.id),
592 STALE_TODO_LAST_FINISHED_CHECKPOINT_ID,
593 );
594 // The caps below also pass when the running turn loses its own tasks.
595 assert.lengthOf(
596 staleTodo.subagents.filter((subagent) => subagent.runId === STALE_TODO_LIVE_RUN_ID),
597 STALE_TODO_SUBAGENTS_PER_RUN,
598 );
599 // The byte cap below also passes when the window loses the handoff.
600 assert.lengthOf(staleTodo.contextHandoffs, 1);
601 const staleTodoColdOpen = {
602 http: staleTodoHttp,
603 rows: staleTodo.visibleTurnItems.length,
604 records: {
605 nodes: staleTodo.nodes.length,
606 subagents: staleTodo.subagents.length,
607 plans: staleTodo.plans.length,
608 providerTurns: staleTodo.providerTurns.length,
609 checkpoints: staleTodo.checkpoints.length,
610 },
611 };
612 return {
613 provider,
614 threadSnapshot,
615 shellSnapshot,
616 measuredTurnWebSocket,
617 measuredTurnShellWebSocket,
618 measuredTurnSecondClientWebSocket,
619 measuredTurnSqlStatements,
620 reconnectThread,
621 reconnectShell,
622 reconnectSqlStatements,
623 shortTurnResume,
624 longTurnRunningColdOpenLegacy,
625 longTurnRunningColdOpen,
626 longTurnRunningHistoryPageLegacy,
627 longTurnRunningHistoryPage,
628 longTurnColdOpen,
629 longTurnWorkPage,
630 longTurnSocketColdOpen,
631 idleThreadResume,
632 fleetShellLegacy,
633 fleetShell,
634 fleetShellSubscribe,
635 fleetShellResume,
636 staleShellReload,
637 staleShellResume,
638 staleTodoColdOpen,
639 } satisfies TransferBudgetRun;
640 }).pipe(
641 Effect.provide(Layer.fresh(layerServices).pipe(Layer.provideMerge(NodeServices.layer))),
642 Effect.withTracer(counter.tracer),
643 ),
644 );
645 runs.push(run);
646 }
647 const fs = yield* FileSystem.FileSystem;
648 const report = formatTransferBudgetReport(runs);
649 const outputPaths = yield* Config.all({
650 report: Config.String("T3CODE_TRANSFER_BUDGET_REPORT_PATH").pipe(Config.withDefault("")),
651 result: Config.String("T3CODE_TRANSFER_BUDGET_RESULT_PATH").pipe(Config.withDefault("")),
652 scenarios: Config.String("T3CODE_TRANSFER_BUDGET_SCENARIOS_PATH").pipe(
653 Config.withDefault(""),
654 ),
655 });
656 for (const [path, contents] of [
657 [outputPaths.report, report],
658 [outputPaths.result, formatTransferBudgetResult(runs)],
659 [outputPaths.scenarios, formatTransferBudgetScenarios(runs)],
660 ])
661 if (path && contents) yield* fs.writeFileString(path, contents);
662 yield* Effect.log(report);
663 assert.deepEqual(transferBudgetViolations(runs), []);
664 }).pipe(Effect.provide(NodeServices.layer)),
665);