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

TransferBudgetReport.integration.ts

432 lines16.7 KB

1import type { ProviderDriverKind } from "@t3tools/contracts";
2​
3import type {
4 HttpTransferMeasurement,
5 WebSocketTransferTotals,
6} from "./NetworkTransferMeasurement.integration.ts";
7import {
8 TRANSFER_HISTORY_MCP_RESULT_BYTES,
9 TRANSFER_HISTORY_TOOLS_PER_TURN,
10 TRANSFER_HISTORY_TURN_COUNT,
11 TRANSFER_MEASURED_MCP_RESULT_BYTES,
12 TRANSFER_MEASURED_TOOLS,
13} from "./fixtures/transferBudget.ts";
14import {
15 LONG_TURN_WORK_ROWS,
16 SHELL_IDLE_SUBAGENTS,
17 SHELL_SETTLED_THREADS,
18 STALE_TODO_LIVE_ROWS,
19 STALE_TODO_SETTLED_RUNS,
20 STALE_TODO_SUBAGENTS_PER_RUN,
21} from "./TransferBudgetV2Fixture.integration.ts";
22​
23export interface WebSocketCatchUpMeasurement extends WebSocketTransferTotals {
24 readonly mode: "replay" | "snapshot";
26​
27export interface TimelineHttpMeasurement {
28 readonly http: HttpTransferMeasurement;
29 readonly rows: number;
31​
32const STALE_TODO_RECORD_KINDS = [
33 "nodes",
34 "subagents",
35 "plans",
36 "providerTurns",
37 "checkpoints",
38] as const;
39type StaleTodoRecordCounts = Readonly<Record<(typeof STALE_TODO_RECORD_KINDS)[number], number>>;
40​
41export interface TransferBudgetRun {
42 readonly provider: ProviderDriverKind;
43 readonly threadSnapshot: HttpTransferMeasurement;
44 readonly measuredTurnWebSocket: WebSocketTransferTotals;
45 readonly shellSnapshot: HttpTransferMeasurement;
46 readonly measuredTurnShellWebSocket: WebSocketTransferTotals;
47 readonly measuredTurnSecondClientWebSocket: WebSocketTransferTotals;
48 readonly reconnectThread: WebSocketCatchUpMeasurement;
49 readonly reconnectShell: WebSocketCatchUpMeasurement;
50 readonly measuredTurnSqlStatements: number;
51 readonly reconnectSqlStatements: number;
52 /** The compact bounded snapshot web and mobile load when the long-turn thread opens. */
53 readonly longTurnColdOpen: TimelineHttpMeasurement;
54 readonly longTurnHistoryPage: TimelineHttpMeasurement;
55 /** The same reads as an older client that only sends `compactTurnItems`, to show the savings. */
56 readonly longTurnColdOpenLegacy: TimelineHttpMeasurement;
57 readonly longTurnHistoryPageLegacy: TimelineHttpMeasurement;
58 /** The cold-connect shell snapshot after the settled-thread fleet is written. */
59 readonly fleetShell: TimelineHttpMeasurement;
60 readonly fleetShellLegacy: TimelineHttpMeasurement;
61 /**
62 * The compact bounded snapshot of the long thread whose finished runs left todo lists open,
63 * with the count of each record kind that rides along with its rows.
64 */
65 readonly staleTodoColdOpen: TimelineHttpMeasurement & {
66 readonly records: StaleTodoRecordCounts;
67 };
69​
70interface ProviderTransferBudget {
71 readonly totalWireBytes: number;
72 readonly threadSnapshotWireBytes: number;
73 readonly measuredTurnWebSocketWireBytes: number;
74 readonly measuredTurnWebSocketDecodedBytes: number;
75 readonly measuredTurnWebSocketMessages: number;
77​
78// The measured turn decodes to about 22 KB; without live body dedupe its repeated answer makes it 26 KB.
79const TRANSFER_BUDGET = {
80 totalWireBytes: 7_000,
81 threadSnapshotWireBytes: 5_000,
82 measuredTurnWebSocketWireBytes: 2_000,
83 measuredTurnWebSocketDecodedBytes: 25_000,
84 measuredTurnWebSocketMessages: 8,
85} satisfies ProviderTransferBudget;
86​
87const TRANSFER_BUDGETS: Readonly<Record<string, ProviderTransferBudget>> = {
88 codex: TRANSFER_BUDGET,
89 claudeAgent: TRANSFER_BUDGET,
90};
91​
92// Decoded bytes, not wire bytes: phones parse and keep the decoded JSON. About 7% above the
93// observed 103 KB, so a cold open without body dedupe (117 KB), the ID table, or row budgets
94// (all 920 rows) fails. Kept apart from TRANSFER_BUDGET because the PR comment validates its keys.
95const LONG_TURN_BUDGET = {
96 decodedBytes: 110_000,
97 rows: 75,
98};
99​
100// About 30% above the observed 42 KB. Without the shell opt-ins it carries all 142 rows (217 KB).
101const FLEET_SHELL_BUDGET = {
102 decodedBytes: 55_000,
103 rows: 27,
104};
105​
106// About 14% above the observed 75 KB. The window holds the working run only: 2 nodes, 2 subagents,
107// 1 plan, 1 provider turn and the last finished turn's checkpoint. When finished runs ride along
108// it holds 82 nodes, 82 subagents, 41 plans, 41 provider turns, 40 checkpoints and 740 KB.
109const STALE_TODO_BUDGET = {
110 decodedBytes: 85_000,
111 rows: 75,
112 records: {
113 nodes: 4,
114 subagents: 4,
115 plans: 2,
116 providerTurns: 2,
117 checkpoints: 2,
118 } satisfies StaleTodoRecordCounts,
119};
120​
121function totalWireBytes(run: TransferBudgetRun): number {
122 return run.threadSnapshot.wireBytes + run.measuredTurnWebSocket.wireBytes;
124​
125function serverEgressWireBytes(run: TransferBudgetRun): number {
126 return (
127 run.measuredTurnWebSocket.wireBytes +
128 run.measuredTurnShellWebSocket.wireBytes +
129 run.measuredTurnSecondClientWebSocket.wireBytes
130 );
132​
133function observedTransfer(run: TransferBudgetRun) {
134 return {
135 totalWireBytes: totalWireBytes(run),
136 threadSnapshotWireBytes: run.threadSnapshot.wireBytes,
137 threadSnapshotDecodedBytes: run.threadSnapshot.decodedBodyBytes,
138 measuredTurnWebSocketWireBytes: run.measuredTurnWebSocket.wireBytes,
139 measuredTurnWebSocketDecodedBytes: run.measuredTurnWebSocket.decodedBytes,
140 measuredTurnWebSocketMessages: run.measuredTurnWebSocket.messages,
141 };
143​
144export function formatTransferBudgetResult(runs: ReadonlyArray<TransferBudgetRun>): string {
145 const providers = Object.fromEntries(
146 runs.flatMap((run) => {
147 const ceiling = TRANSFER_BUDGETS[run.provider];
148 return ceiling ? [[run.provider, { observed: observedTransfer(run), ceiling }]] : [];
149 }),
150 );
151​
152 return `${JSON.stringify(
153 {
154 schemaVersion: 1,
155 scenario: {
156 id: "thread-transfer-v2",
157 historyTurns: TRANSFER_HISTORY_TURN_COUNT,
158 historyCommandToolsPerTurn: TRANSFER_HISTORY_TOOLS_PER_TURN,
159 historyMcpResultBytes: TRANSFER_HISTORY_MCP_RESULT_BYTES,
160 measuredCommandTools: TRANSFER_MEASURED_TOOLS,
161 measuredMcpResultBytes: TRANSFER_MEASURED_MCP_RESULT_BYTES,
162 },
163 providers,
164 },
165 null,
166 2,
167 )}\n`;
169​
170function formatBytes(bytes: number): string {
171 if (bytes < 1_024) return `${bytes} B`;
172 if (bytes >= 1_024 * 1_024) {
173 return `${(bytes / 1_024 / 1_024).toFixed(2)} MiB (${bytes.toLocaleString("en-US")} B)`;
174 }
175 return `${(bytes / 1_024).toFixed(1)} KiB (${bytes.toLocaleString("en-US")} B)`;
177​
178function row(
179 provider: ProviderDriverKind,
180 phase: string,
181 metric: string,
182 observed: number,
183 maximum: number,
184 format: (value: number) => string = formatBytes,
185): string {
186 const status = observed <= maximum ? "PASS" : "FAIL";
187 return `| ${provider} | ${phase} | ${metric} | ${format(observed)} | ${format(maximum)} | ${status} |`;
189​
190// The 50 ms shell batching makes transfer, reconnect and SQL figures timing-dependent.
191function infoRow(
192 provider: ProviderDriverKind,
193 phase: string,
194 metric: string,
195 observed: number,
196 format: (value: number) => string = formatBytes,
197): string {
198 return `| ${provider} | ${phase} | ${metric} | ${format(observed)} | none | INFO |`;
200​
201function webSocketRows(
202 provider: ProviderDriverKind,
203 phase: string,
204 totals: WebSocketTransferTotals,
205): string[] {
206 return [
207 infoRow(provider, phase, "WebSocket wire", totals.wireBytes),
208 infoRow(provider, phase, "WebSocket decoded", totals.decodedBytes),
209 infoRow(provider, phase, "WebSocket messages", totals.messages, String),
210 ];
212​
213function timelineRows(
214 provider: ProviderDriverKind,
215 phase: string,
216 measured: TimelineHttpMeasurement,
217 budget: { readonly decodedBytes: number; readonly rows: number },
218): string[] {
219 return [
220 infoRow(provider, phase, "HTTP wire", measured.http.wireBytes),
221 row(provider, phase, "HTTP decoded", measured.http.decodedBodyBytes, budget.decodedBytes),
222 row(provider, phase, "rows", measured.rows, budget.rows, String),
223 ];
225​
226function legacyRows(
227 provider: ProviderDriverKind,
228 phase: string,
229 measured: TimelineHttpMeasurement,
230): string[] {
231 return [
232 infoRow(provider, `${phase}, older client`, "HTTP wire", measured.http.wireBytes),
233 infoRow(provider, `${phase}, older client`, "HTTP decoded", measured.http.decodedBodyBytes),
234 infoRow(provider, `${phase}, older client`, "rows", measured.rows, String),
235 ];
237​
238export function transferBudgetViolations(runs: ReadonlyArray<TransferBudgetRun>): string[] {
239 const violations: string[] = [];
240 for (const run of runs) {
241 const budget = TRANSFER_BUDGETS[run.provider];
242 if (!budget) {
243 violations.push(`${run.provider}: no transfer budget is configured`);
244 continue;
245 }
246 const checks = [
247 ["total thread wire bytes", totalWireBytes(run), budget.totalWireBytes],
248 ["thread snapshot wire bytes", run.threadSnapshot.wireBytes, budget.threadSnapshotWireBytes],
249 [
250 "measured-turn WebSocket wire bytes",
251 run.measuredTurnWebSocket.wireBytes,
252 budget.measuredTurnWebSocketWireBytes,
253 ],
254 [
255 "measured-turn WebSocket decoded bytes",
256 run.measuredTurnWebSocket.decodedBytes,
257 budget.measuredTurnWebSocketDecodedBytes,
258 ],
259 [
260 "measured-turn WebSocket messages",
261 run.measuredTurnWebSocket.messages,
262 budget.measuredTurnWebSocketMessages,
263 ],
264 [
265 "long-turn cold open decoded bytes",
266 run.longTurnColdOpen.http.decodedBodyBytes,
267 LONG_TURN_BUDGET.decodedBytes,
268 ],
269 ["long-turn cold open rows", run.longTurnColdOpen.rows, LONG_TURN_BUDGET.rows],
270 [
271 "long-turn history page decoded bytes",
272 run.longTurnHistoryPage.http.decodedBodyBytes,
273 LONG_TURN_BUDGET.decodedBytes,
274 ],
275 ["long-turn history page rows", run.longTurnHistoryPage.rows, LONG_TURN_BUDGET.rows],
276 [
277 "fleet shell snapshot decoded bytes",
278 run.fleetShell.http.decodedBodyBytes,
279 FLEET_SHELL_BUDGET.decodedBytes,
280 ],
281 ["fleet shell snapshot rows", run.fleetShell.rows, FLEET_SHELL_BUDGET.rows],
282 [
283 "stale todo list cold open decoded bytes",
284 run.staleTodoColdOpen.http.decodedBodyBytes,
285 STALE_TODO_BUDGET.decodedBytes,
286 ],
287 ["stale todo list cold open rows", run.staleTodoColdOpen.rows, STALE_TODO_BUDGET.rows],
288 ...STALE_TODO_RECORD_KINDS.map(
289 (kind) =>
290 [
291 `stale todo list cold open ${kind}`,
292 run.staleTodoColdOpen.records[kind],
293 STALE_TODO_BUDGET.records[kind],
294 ] as const,
295 ),
296 ] as const;
297 for (const [metric, observed, maximum] of checks) {
298 if (observed > maximum) {
299 violations.push(`${run.provider}: ${metric} was ${observed}, maximum ${maximum}`);
300 }
301 }
302 }
303 return violations;
305​
306export function formatTransferBudgetReport(runs: ReadonlyArray<TransferBudgetRun>): string {
307 const lines = [
308 "# T3 Code thread transfer budget",
309 "",
310 "Wire values are thread data bytes read from local HTTP and WebSocket sockets. HTTP includes response headers; WebSocket measurement starts after the resumed thread subscription synchronizes. TCP/IP, TLS framing, and the WebSocket upgrade are excluded. WebSocket permessage-deflate is negotiated.",
311 "The measured turn is observed on three sockets at once: one with only the thread subscription (the capped rows), one with only the shell subscription, and a second client holding both. Server egress is the sum of the three. After the turn the second client disconnects and new sockets resubscribe from the cursor it held before the turn, which is the cursor a backgrounded phone would hold. SQL statements are the SQL client's per-statement spans, counted across V2 persistence and the HTTP/WebSocket handlers.",
312 `Scenario: ${TRANSFER_HISTORY_TURN_COUNT} historical turns with ${TRANSFER_HISTORY_TOOLS_PER_TURN} command tools and one retained ${formatBytes(TRANSFER_HISTORY_MCP_RESULT_BYTES)} MCP result each, followed by one measured turn with ${TRANSFER_MEASURED_TOOLS} command tools and a retained ${formatBytes(TRANSFER_MEASURED_MCP_RESULT_BYTES)} MCP result. Synthetic V2 domain events exercise persistence, wire projection, and production HTTP/subscription handlers; this does not measure provider adapter ingestion. Payloads contain no user data.`,
313 `The long-turn rows open a second thread through the compact bounded snapshot web and mobile use, then load one older page. Its last user turn holds ${LONG_TURN_WORK_ROWS} rows of reasoning, commands, file changes, MCP calls, progress messages, checkpoints, and subagents.`,
314 `The fleet shell rows read the cold-connect shell after ${SHELL_SETTLED_THREADS} settled threads and ${SHELL_IDLE_SUBAGENTS} idle subagent children are added. Budgeted reads send the opt-ins current clients send; "older client" rows show the same read without the opt-ins added since row budgets.`,
315 `The stale todo list rows open a third thread the same way: ${STALE_TODO_SETTLED_RUNS} finished runs, then one run still at work with ${STALE_TODO_LIVE_ROWS} rows. Every run left its todo list open and has ${STALE_TODO_SUBAGENTS_PER_RUN} finished subagents, a provider turn and, once finished, a checkpoint. The record counts must not grow with the number of finished runs.`,
316 "",
317 "| Provider | Total thread wire | Budget | Result |",
318 "| --- | ---: | ---: | --- |",
319 ...runs.flatMap((run) => {
320 const budget = TRANSFER_BUDGETS[run.provider];
321 if (!budget) return [];
322 const observed = observedTransfer(run).totalWireBytes;
323 return [
324 `| ${run.provider} | ${formatBytes(observed)} | ${formatBytes(budget.totalWireBytes)} | ${observed <= budget.totalWireBytes ? "PASS" : "FAIL"} |`,
325 ];
326 }),
327 "",
328 "## Detailed measurements",
329 "",
330 "| Provider | Phase | Metric | Observed | Budget | Result |",
331 "| --- | --- | --- | ---: | ---: | --- |",
332 ];
333​
334 for (const run of runs) {
335 const budget = TRANSFER_BUDGETS[run.provider];
336 if (!budget) continue;
337 lines.push(
338 row(
339 run.provider,
340 "thread snapshot",
341 "HTTP wire",
342 run.threadSnapshot.wireBytes,
343 budget.threadSnapshotWireBytes,
344 ),
345 row(
346 run.provider,
347 "measured turn",
348 "WebSocket wire",
349 run.measuredTurnWebSocket.wireBytes,
350 budget.measuredTurnWebSocketWireBytes,
351 ),
352 row(
353 run.provider,
354 "measured turn",
355 "WebSocket decoded",
356 run.measuredTurnWebSocket.decodedBytes,
357 budget.measuredTurnWebSocketDecodedBytes,
358 ),
359 row(
360 run.provider,
361 "measured turn",
362 "WebSocket messages",
363 run.measuredTurnWebSocket.messages,
364 budget.measuredTurnWebSocketMessages,
365 String,
366 ),
367 infoRow(run.provider, "shell snapshot", "HTTP wire", run.shellSnapshot.wireBytes),
368 ...webSocketRows(run.provider, "measured turn, shell", run.measuredTurnShellWebSocket),
369 ...webSocketRows(
370 run.provider,
371 "measured turn, second client",
372 run.measuredTurnSecondClientWebSocket,
373 ),
374 infoRow(run.provider, "measured turn", "server egress wire", serverEgressWireBytes(run)),
375 infoRow(
376 run.provider,
377 "measured turn",
378 "SQL statements",
379 run.measuredTurnSqlStatements,
380 String,
381 ),
382 ...webSocketRows(
383 run.provider,
384 `reconnect, thread (${run.reconnectThread.mode})`,
385 run.reconnectThread,
386 ),
387 ...webSocketRows(
388 run.provider,
389 `reconnect, shell (${run.reconnectShell.mode})`,
390 run.reconnectShell,
391 ),
392 infoRow(run.provider, "reconnect", "SQL statements", run.reconnectSqlStatements, String),
393 ...timelineRows(run.provider, "long-turn cold open", run.longTurnColdOpen, LONG_TURN_BUDGET),
394 ...legacyRows(run.provider, "long-turn cold open", run.longTurnColdOpenLegacy),
395 ...timelineRows(
396 run.provider,
397 "long-turn history page",
398 run.longTurnHistoryPage,
399 LONG_TURN_BUDGET,
400 ),
401 ...legacyRows(run.provider, "long-turn history page", run.longTurnHistoryPageLegacy),
402 ...timelineRows(run.provider, "fleet shell snapshot", run.fleetShell, FLEET_SHELL_BUDGET),
403 ...legacyRows(run.provider, "fleet shell snapshot", run.fleetShellLegacy),
404 ...timelineRows(
405 run.provider,
406 "stale todo list cold open",
407 run.staleTodoColdOpen,
408 STALE_TODO_BUDGET,
409 ),
410 ...STALE_TODO_RECORD_KINDS.map((kind) =>
411 row(
412 run.provider,
413 "stale todo list cold open",
414 kind,
415 run.staleTodoColdOpen.records[kind],
416 STALE_TODO_BUDGET.records[kind],
417 String,
418 ),
419 ),
420 );
421 }
422​
423 lines.push("", "## Compression diagnostics", "");
424 for (const run of runs) {
425 lines.push(
426 `- ${run.provider}: thread snapshot ${formatBytes(run.threadSnapshot.decodedBodyBytes)} decoded to ${formatBytes(run.threadSnapshot.encodedBodyBytes)} gzip.`,
427 `- ${run.provider}: shell snapshot ${formatBytes(run.shellSnapshot.decodedBodyBytes)} decoded to ${formatBytes(run.shellSnapshot.encodedBodyBytes)} gzip.`,
428 );
429 }
430​
431 return `${lines.join("\n")}\n`;