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

TransferBudgetReport.integration.ts

367 lines14.3 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} from "./TransferBudgetV2Fixture.integration.ts";
19​
20export interface WebSocketCatchUpMeasurement extends WebSocketTransferTotals {
21 readonly mode: "replay" | "snapshot";
23​
24export interface TimelineHttpMeasurement {
25 readonly http: HttpTransferMeasurement;
26 readonly rows: number;
28​
29export interface TransferBudgetRun {
30 readonly provider: ProviderDriverKind;
31 readonly threadSnapshot: HttpTransferMeasurement;
32 readonly measuredTurnWebSocket: WebSocketTransferTotals;
33 readonly shellSnapshot: HttpTransferMeasurement;
34 readonly measuredTurnShellWebSocket: WebSocketTransferTotals;
35 readonly measuredTurnSecondClientWebSocket: WebSocketTransferTotals;
36 readonly reconnectThread: WebSocketCatchUpMeasurement;
37 readonly reconnectShell: WebSocketCatchUpMeasurement;
38 readonly measuredTurnSqlStatements: number;
39 readonly reconnectSqlStatements: number;
40 /** The compact bounded snapshot web and mobile load when the long-turn thread opens. */
41 readonly longTurnColdOpen: TimelineHttpMeasurement;
42 readonly longTurnHistoryPage: TimelineHttpMeasurement;
43 /** The same reads as an older client that only sends `compactTurnItems`, to show the savings. */
44 readonly longTurnColdOpenLegacy: TimelineHttpMeasurement;
45 readonly longTurnHistoryPageLegacy: TimelineHttpMeasurement;
46 /** The cold-connect shell snapshot after the settled-thread fleet is written. */
47 readonly fleetShell: TimelineHttpMeasurement;
48 readonly fleetShellLegacy: TimelineHttpMeasurement;
50​
51interface ProviderTransferBudget {
52 readonly totalWireBytes: number;
53 readonly threadSnapshotWireBytes: number;
54 readonly measuredTurnWebSocketWireBytes: number;
55 readonly measuredTurnWebSocketDecodedBytes: number;
56 readonly measuredTurnWebSocketMessages: number;
58​
59// The measured turn decodes to about 22 KB; without live body dedupe its repeated answer makes it 26 KB.
60const TRANSFER_BUDGET = {
61 totalWireBytes: 7_000,
62 threadSnapshotWireBytes: 5_000,
63 measuredTurnWebSocketWireBytes: 2_000,
64 measuredTurnWebSocketDecodedBytes: 25_000,
65 measuredTurnWebSocketMessages: 8,
66} satisfies ProviderTransferBudget;
67​
68const TRANSFER_BUDGETS: Readonly<Record<string, ProviderTransferBudget>> = {
69 codex: TRANSFER_BUDGET,
70 claudeAgent: TRANSFER_BUDGET,
71};
72​
73// Decoded bytes, not wire bytes: phones parse and keep the decoded JSON. About 7% above the
74// observed 103 KB, so a cold open without body dedupe (117 KB), the ID table, or row budgets
75// (all 920 rows) fails. Kept apart from TRANSFER_BUDGET because the PR comment validates its keys.
76const LONG_TURN_BUDGET = {
77 decodedBytes: 110_000,
78 rows: 75,
79};
80​
81// About 30% above the observed 42 KB. Without the shell opt-ins it carries all 142 rows (217 KB).
82const FLEET_SHELL_BUDGET = {
83 decodedBytes: 55_000,
84 rows: 27,
85};
86​
87function totalWireBytes(run: TransferBudgetRun): number {
88 return run.threadSnapshot.wireBytes + run.measuredTurnWebSocket.wireBytes;
90​
91function serverEgressWireBytes(run: TransferBudgetRun): number {
92 return (
93 run.measuredTurnWebSocket.wireBytes +
94 run.measuredTurnShellWebSocket.wireBytes +
95 run.measuredTurnSecondClientWebSocket.wireBytes
96 );
98​
99function observedTransfer(run: TransferBudgetRun) {
100 return {
101 totalWireBytes: totalWireBytes(run),
102 threadSnapshotWireBytes: run.threadSnapshot.wireBytes,
103 threadSnapshotDecodedBytes: run.threadSnapshot.decodedBodyBytes,
104 measuredTurnWebSocketWireBytes: run.measuredTurnWebSocket.wireBytes,
105 measuredTurnWebSocketDecodedBytes: run.measuredTurnWebSocket.decodedBytes,
106 measuredTurnWebSocketMessages: run.measuredTurnWebSocket.messages,
107 };
109​
110export function formatTransferBudgetResult(runs: ReadonlyArray<TransferBudgetRun>): string {
111 const providers = Object.fromEntries(
112 runs.flatMap((run) => {
113 const ceiling = TRANSFER_BUDGETS[run.provider];
114 return ceiling ? [[run.provider, { observed: observedTransfer(run), ceiling }]] : [];
115 }),
116 );
117​
118 return `${JSON.stringify(
119 {
120 schemaVersion: 1,
121 scenario: {
122 id: "thread-transfer-v2",
123 historyTurns: TRANSFER_HISTORY_TURN_COUNT,
124 historyCommandToolsPerTurn: TRANSFER_HISTORY_TOOLS_PER_TURN,
125 historyMcpResultBytes: TRANSFER_HISTORY_MCP_RESULT_BYTES,
126 measuredCommandTools: TRANSFER_MEASURED_TOOLS,
127 measuredMcpResultBytes: TRANSFER_MEASURED_MCP_RESULT_BYTES,
128 },
129 providers,
130 },
131 null,
132 2,
133 )}\n`;
135​
136function formatBytes(bytes: number): string {
137 if (bytes < 1_024) return `${bytes} B`;
138 if (bytes >= 1_024 * 1_024) {
139 return `${(bytes / 1_024 / 1_024).toFixed(2)} MiB (${bytes.toLocaleString("en-US")} B)`;
140 }
141 return `${(bytes / 1_024).toFixed(1)} KiB (${bytes.toLocaleString("en-US")} B)`;
143​
144function row(
145 provider: ProviderDriverKind,
146 phase: string,
147 metric: string,
148 observed: number,
149 maximum: number,
150 format: (value: number) => string = formatBytes,
151): string {
152 const status = observed <= maximum ? "PASS" : "FAIL";
153 return `| ${provider} | ${phase} | ${metric} | ${format(observed)} | ${format(maximum)} | ${status} |`;
155​
156// The 50 ms shell batching makes transfer, reconnect and SQL figures timing-dependent.
157function infoRow(
158 provider: ProviderDriverKind,
159 phase: string,
160 metric: string,
161 observed: number,
162 format: (value: number) => string = formatBytes,
163): string {
164 return `| ${provider} | ${phase} | ${metric} | ${format(observed)} | none | INFO |`;
166​
167function webSocketRows(
168 provider: ProviderDriverKind,
169 phase: string,
170 totals: WebSocketTransferTotals,
171): string[] {
172 return [
173 infoRow(provider, phase, "WebSocket wire", totals.wireBytes),
174 infoRow(provider, phase, "WebSocket decoded", totals.decodedBytes),
175 infoRow(provider, phase, "WebSocket messages", totals.messages, String),
176 ];
178​
179function timelineRows(
180 provider: ProviderDriverKind,
181 phase: string,
182 measured: TimelineHttpMeasurement,
183 budget: { readonly decodedBytes: number; readonly rows: number },
184): string[] {
185 return [
186 infoRow(provider, phase, "HTTP wire", measured.http.wireBytes),
187 row(provider, phase, "HTTP decoded", measured.http.decodedBodyBytes, budget.decodedBytes),
188 row(provider, phase, "rows", measured.rows, budget.rows, String),
189 ];
191​
192function legacyRows(
193 provider: ProviderDriverKind,
194 phase: string,
195 measured: TimelineHttpMeasurement,
196): string[] {
197 return [
198 infoRow(provider, `${phase}, older client`, "HTTP wire", measured.http.wireBytes),
199 infoRow(provider, `${phase}, older client`, "HTTP decoded", measured.http.decodedBodyBytes),
200 infoRow(provider, `${phase}, older client`, "rows", measured.rows, String),
201 ];
203​
204export function transferBudgetViolations(runs: ReadonlyArray<TransferBudgetRun>): string[] {
205 const violations: string[] = [];
206 for (const run of runs) {
207 const budget = TRANSFER_BUDGETS[run.provider];
208 if (!budget) {
209 violations.push(`${run.provider}: no transfer budget is configured`);
210 continue;
211 }
212 const checks = [
213 ["total thread wire bytes", totalWireBytes(run), budget.totalWireBytes],
214 ["thread snapshot wire bytes", run.threadSnapshot.wireBytes, budget.threadSnapshotWireBytes],
215 [
216 "measured-turn WebSocket wire bytes",
217 run.measuredTurnWebSocket.wireBytes,
218 budget.measuredTurnWebSocketWireBytes,
219 ],
220 [
221 "measured-turn WebSocket decoded bytes",
222 run.measuredTurnWebSocket.decodedBytes,
223 budget.measuredTurnWebSocketDecodedBytes,
224 ],
225 [
226 "measured-turn WebSocket messages",
227 run.measuredTurnWebSocket.messages,
228 budget.measuredTurnWebSocketMessages,
229 ],
230 [
231 "long-turn cold open decoded bytes",
232 run.longTurnColdOpen.http.decodedBodyBytes,
233 LONG_TURN_BUDGET.decodedBytes,
234 ],
235 ["long-turn cold open rows", run.longTurnColdOpen.rows, LONG_TURN_BUDGET.rows],
236 [
237 "long-turn history page decoded bytes",
238 run.longTurnHistoryPage.http.decodedBodyBytes,
239 LONG_TURN_BUDGET.decodedBytes,
240 ],
241 ["long-turn history page rows", run.longTurnHistoryPage.rows, LONG_TURN_BUDGET.rows],
242 [
243 "fleet shell snapshot decoded bytes",
244 run.fleetShell.http.decodedBodyBytes,
245 FLEET_SHELL_BUDGET.decodedBytes,
246 ],
247 ["fleet shell snapshot rows", run.fleetShell.rows, FLEET_SHELL_BUDGET.rows],
248 ] as const;
249 for (const [metric, observed, maximum] of checks) {
250 if (observed > maximum) {
251 violations.push(`${run.provider}: ${metric} was ${observed}, maximum ${maximum}`);
252 }
253 }
254 }
255 return violations;
257​
258export function formatTransferBudgetReport(runs: ReadonlyArray<TransferBudgetRun>): string {
259 const lines = [
260 "# T3 Code thread transfer budget",
261 "",
262 "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.",
263 "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.",
264 `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.`,
265 `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.`,
266 `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.`,
267 "",
268 "| Provider | Total thread wire | Budget | Result |",
269 "| --- | ---: | ---: | --- |",
270 ...runs.flatMap((run) => {
271 const budget = TRANSFER_BUDGETS[run.provider];
272 if (!budget) return [];
273 const observed = observedTransfer(run).totalWireBytes;
274 return [
275 `| ${run.provider} | ${formatBytes(observed)} | ${formatBytes(budget.totalWireBytes)} | ${observed <= budget.totalWireBytes ? "PASS" : "FAIL"} |`,
276 ];
277 }),
278 "",
279 "## Detailed measurements",
280 "",
281 "| Provider | Phase | Metric | Observed | Budget | Result |",
282 "| --- | --- | --- | ---: | ---: | --- |",
283 ];
284​
285 for (const run of runs) {
286 const budget = TRANSFER_BUDGETS[run.provider];
287 if (!budget) continue;
288 lines.push(
289 row(
290 run.provider,
291 "thread snapshot",
292 "HTTP wire",
293 run.threadSnapshot.wireBytes,
294 budget.threadSnapshotWireBytes,
295 ),
296 row(
297 run.provider,
298 "measured turn",
299 "WebSocket wire",
300 run.measuredTurnWebSocket.wireBytes,
301 budget.measuredTurnWebSocketWireBytes,
302 ),
303 row(
304 run.provider,
305 "measured turn",
306 "WebSocket decoded",
307 run.measuredTurnWebSocket.decodedBytes,
308 budget.measuredTurnWebSocketDecodedBytes,
309 ),
310 row(
311 run.provider,
312 "measured turn",
313 "WebSocket messages",
314 run.measuredTurnWebSocket.messages,
315 budget.measuredTurnWebSocketMessages,
316 String,
317 ),
318 infoRow(run.provider, "shell snapshot", "HTTP wire", run.shellSnapshot.wireBytes),
319 ...webSocketRows(run.provider, "measured turn, shell", run.measuredTurnShellWebSocket),
320 ...webSocketRows(
321 run.provider,
322 "measured turn, second client",
323 run.measuredTurnSecondClientWebSocket,
324 ),
325 infoRow(run.provider, "measured turn", "server egress wire", serverEgressWireBytes(run)),
326 infoRow(
327 run.provider,
328 "measured turn",
329 "SQL statements",
330 run.measuredTurnSqlStatements,
331 String,
332 ),
333 ...webSocketRows(
334 run.provider,
335 `reconnect, thread (${run.reconnectThread.mode})`,
336 run.reconnectThread,
337 ),
338 ...webSocketRows(
339 run.provider,
340 `reconnect, shell (${run.reconnectShell.mode})`,
341 run.reconnectShell,
342 ),
343 infoRow(run.provider, "reconnect", "SQL statements", run.reconnectSqlStatements, String),
344 ...timelineRows(run.provider, "long-turn cold open", run.longTurnColdOpen, LONG_TURN_BUDGET),
345 ...legacyRows(run.provider, "long-turn cold open", run.longTurnColdOpenLegacy),
346 ...timelineRows(
347 run.provider,
348 "long-turn history page",
349 run.longTurnHistoryPage,
350 LONG_TURN_BUDGET,
351 ),
352 ...legacyRows(run.provider, "long-turn history page", run.longTurnHistoryPageLegacy),
353 ...timelineRows(run.provider, "fleet shell snapshot", run.fleetShell, FLEET_SHELL_BUDGET),
354 ...legacyRows(run.provider, "fleet shell snapshot", run.fleetShellLegacy),
355 );
356 }
357​
358 lines.push("", "## Compression diagnostics", "");
359 for (const run of runs) {
360 lines.push(
361 `- ${run.provider}: thread snapshot ${formatBytes(run.threadSnapshot.decodedBodyBytes)} decoded to ${formatBytes(run.threadSnapshot.encodedBodyBytes)} gzip.`,
362 `- ${run.provider}: shell snapshot ${formatBytes(run.shellSnapshot.decodedBodyBytes)} decoded to ${formatBytes(run.shellSnapshot.encodedBodyBytes)} gzip.`,
363 );
364 }
365​
366 return `${lines.join("\n")}\n`;