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

usageTranscriptStreaming.test.ts

497 lines17.5 KB

1// @effect-diagnostics nodeBuiltinImport:off - exercise the real byte reader.
2import * as NodeFSP from "node:fs/promises";
3import * as NodeOS from "node:os";
4import * as NodePath from "node:path";
5import * as NodeZlib from "node:zlib";
6​
7import { afterEach, beforeEach, describe, expect, it } from "@effect/vitest";
8import { vi } from "vite-plus/test";
9​
10import { TEST_FORMATS } from "./usageTestFormats.ts";
11import {
12 readTranscriptRecords as readWithDefaultThreshold,
13 type TranscriptParsePosition,
14} from "./usageTranscriptReader.ts";
15​
16const readTranscriptRecords = (
17 path: string,
18 provider: keyof typeof TEST_FORMATS,
19 position?: TranscriptParsePosition,
20) =>
21 readWithDefaultThreshold(path, TEST_FORMATS[provider], position, {
22 streamingThresholdBytes: 256 * 1024,
23 });
24​
25let dir: string;
26beforeEach(async () => {
27 dir = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "usage-stream-"));
28});
29afterEach(async () => {
30 await NodeFSP.rm(dir, { recursive: true, force: true });
31});
32​
33const timestamp = "2026-08-01T10:00:00Z";
34const content = '工具 output \\" usage token_count '.repeat(40_000);
35const claude = (id = "m1", output = 99) => ({
36 type: "assistant",
37 timestamp,
38 sessionId: "s1",
39 requestId: `r-${id}`,
40 costUSD: 0.25,
41 message: {
42 content: [{ type: "tool_use", input: { text: content } }],
43 id,
44 model: "claude-fable-5",
45 usage: {
46 input_tokens: 100,
47 output_tokens: output,
48 cache_read_input_tokens: 20,
49 cache_creation_input_tokens: 5,
50 speed: "fast",
51 },
52 },
53});
54const codex = [
55 { type: "session_meta", timestamp, payload: { id: "s1", model_provider: "openai" } },
56 { type: "turn_context", timestamp, payload: { model: "gpt-5.6-sol", turn_id: "initial-turn" } },
57 {
58 type: "event_msg",
59 timestamp,
60 payload: {
61 type: "token_count",
62 info: {
63 last_token_usage: {
64 input_tokens: 100,
65 output_tokens: 99,
66 cached_input_tokens: 20,
67 cache_write_input_tokens: 5,
68 reasoning_output_tokens: 10,
69 },
70 },
71 },
72 },
73];
74const grok = {
75 timestamp: 1785578400,
76 params: {
77 sessionId: "s1",
78 _meta: { agentTimestampMs: 1785578400123 },
79 update: {
80 sessionUpdate: "turn_completed",
81 prompt_id: "p1",
82 usage: {
83 inputTokens: 100,
84 outputTokens: 99,
85 costUsdTicks: 2500000000,
86 modelUsage: {
87 "grok-4.5-build": {
88 inputTokens: 100,
89 outputTokens: 99,
90 cachedReadTokens: 20,
91 cacheCreationTokens: 5,
92 reasoningTokens: 10,
93 },
94 },
95 },
96 },
97 },
98};
99​
100async function scan(
101 lines: readonly unknown[],
102 provider: keyof typeof TEST_FORMATS,
103 name = "history",
104) {
105 const path = NodePath.join(dir, `${name}.jsonl`);
106 await NodeFSP.writeFile(path, lines.map((line) => JSON.stringify(line)).join("\n") + "\n");
107 const result = await readTranscriptRecords(path, provider);
108 expect(result).not.toBeNull();
109 return result!;
111​
112describe("large usage records", () => {
113 it("skips JSON projection for oversized lines without usage markers", async () => {
114 const path = NodePath.join(dir, "unrelated.jsonl");
115 await NodeFSP.writeFile(
116 path,
117 JSON.stringify({ type: "response_item", payload: { content } }) +
118 "\n" +
119 codex.map((line) => JSON.stringify(line)).join("\n") +
120 "\n",
121 );
122 const parseProjected = vi.fn(TEST_FORMATS.codex.parseProjected);
123 const result = await readWithDefaultThreshold(
124 path,
125 { ...TEST_FORMATS.codex, parseProjected },
126 undefined,
127 { streamingThresholdBytes: 256 * 1024 },
128 );
129 expect(result?.records.map((record) => record.totals)).toEqual([
130 {
131 uncachedInputTokens: 75,
132 cachedInputTokens: 20,
133 cacheCreationTokens: 5,
134 outputTokens: 99,
135 reasoningTokens: 10,
136 },
137 ]);
138 expect(parseProjected).not.toHaveBeenCalled();
139 });
140​
141 it("replays an oversized usage line whose marker spans a read boundary", async () => {
142 const path = NodePath.join(dir, "split-marker.jsonl");
143 const head = codex
144 .slice(0, 2)
145 .map((line) => JSON.stringify(line) + "\n")
146 .join("");
147 const usageLine = (pad: number) =>
148 JSON.stringify({ pad: "x".repeat(pad), ...codex[2], tail: "y".repeat(16 * 1024) }) + "\n";
149 const markerOffset = Buffer.from(usageLine(0)).indexOf('"token_count"');
150 const readBoundary = 256 * 1024;
151 const pad = readBoundary - 6 - Buffer.byteLength(head) - markerOffset;
152 await NodeFSP.writeFile(path, head + usageLine(pad));
153 const parseProjected = vi.fn(TEST_FORMATS.codex.parseProjected);
154 const result = await readWithDefaultThreshold(
155 path,
156 { ...TEST_FORMATS.codex, parseProjected },
157 undefined,
158 { streamingThresholdBytes: readBoundary },
159 );
160 expect(result?.records.map((record) => record.totals)).toEqual([
161 {
162 uncachedInputTokens: 75,
163 cachedInputTokens: 20,
164 cacheCreationTokens: 5,
165 outputTokens: 99,
166 reasoningTokens: 10,
167 },
168 ]);
169 expect(parseProjected).toHaveBeenCalledTimes(1);
170 });
171​
172 it("projects oversized usage lines in compressed transcripts", async () => {
173 const path = NodePath.join(dir, "archived.jsonl.zst");
174 await NodeFSP.writeFile(path, NodeZlib.zstdCompressSync(JSON.stringify(claude()) + "\n"));
175 const result = await readTranscriptRecords(path, "claude");
176 expect(result?.records.map((record) => record.totals)).toEqual([
177 {
178 uncachedInputTokens: 100,
179 cachedInputTokens: 20,
180 cacheCreationTokens: 5,
181 outputTokens: 99,
182 reasoningTokens: 0,
183 },
184 ]);
185 });
186​
187 it("streams Muse completion envelopes and resumes a partial appended event", async () => {
188 const entry = {
189 schema_version: 1,
190 record_type: "event",
191 payload_type: "runtime.session",
192 payload_schema_version: 3,
193 id: "envelope-1",
194 recorded_at: 1_785_578_400_123_456,
195 stream: { kind: "session", id: "parent" },
196 payload: {
197 source_run_record_id: "inference-1",
198 event: {
199 kind: "automated_review_completed",
200 model: { model_id: "review-model" },
201 usage: {
202 input_tokens: 100,
203 cached_input_tokens: 60,
204 output_tokens: 20,
205 reasoning_tokens: 8,
206 },
207 },
208 },
209 };
210 const small = await scan([entry], "muse", "small-muse");
211 expect(small.records[0]?.totals).toMatchObject({
212 uncachedInputTokens: 40,
213 cachedInputTokens: 60,
214 });
215 const path = NodePath.join(dir, "large-muse.jsonl");
216 await NodeFSP.writeFile(path, JSON.stringify({ ...entry, discarded: { content } }) + "\n");
217 const large = await readTranscriptRecords(path, "muse");
218 expect(large?.records).toEqual(small.records);
219 const appended = JSON.stringify({
220 ...entry,
221 id: "envelope-2",
222 payload: { ...entry.payload, source_run_record_id: "inference-2" },
223 });
224 await NodeFSP.appendFile(path, appended.slice(0, -7));
225 const partial = await readTranscriptRecords(path, "muse", large!.position);
226 expect(partial?.records).toEqual([]);
227 await NodeFSP.appendFile(path, appended.slice(-7) + "\n");
228 const completed = await readTranscriptRecords(path, "muse", partial!.position);
229 expect(completed?.records).toHaveLength(1);
230 expect(completed?.records[0]?.dedupeKey).not.toBe(large?.records[0]?.dedupeKey);
231 expect(completed?.records[0]?.totals).toEqual(small.records[0]?.totals);
232 });
233​
234 it("keeps Pi model, cost, and fork identity after large assistant content", async () => {
235 const entry = {
236 type: "message",
237 id: "a123abcd",
238 timestamp,
239 message: {
240 role: "assistant",
241 provider: "anthropic",
242 model: "requested",
243 responseModel: "actual",
244 content: [{ type: "text", text: content }],
245 usage: {
246 input: 100,
247 output: 99,
248 cacheRead: 20,
249 cacheWrite: 5,
250 reasoning: 10,
251 cost: { total: 0.25 },
252 },
253 },
254 };
255 const result = await scan([{ type: "session", id: "pi-session" }, entry], "pi");
256 expect(result.records).toEqual([
257 {
258 provider: "pi",
259 model: "anthropic/actual",
260 rateModel: "actual",
261 sessionId: "pi-session",
262 timestampMs: Date.parse(timestamp),
263 totals: {
264 uncachedInputTokens: 100,
265 outputTokens: 99,
266 cachedInputTokens: 20,
267 cacheCreationTokens: 5,
268 reasoningTokens: 10,
269 },
270 reportedCostUsd: 0.25,
271 speed: "standard",
272 dedupeKey: JSON.stringify(["pi", entry.id, timestamp, "anthropic/actual"]),
273 },
274 ]);
275 });
276​
277 it("keeps usage after large Claude tool input, including fast-mode cost and dedupe metadata", async () => {
278 const result = await scan([claude()], "claude");
279 expect(result.records).toEqual([
280 {
281 provider: "claude",
282 timestampMs: Date.parse(timestamp),
283 sessionId: "s1",
284 model: "claude-fable-5",
285 totals: {
286 uncachedInputTokens: 100,
287 outputTokens: 99,
288 cachedInputTokens: 20,
289 cacheCreationTokens: 5,
290 reasoningTokens: 0,
291 },
292 reportedCostUsd: 0.25,
293 speed: "fast",
294 dedupeKey: "m1:r-m1",
295 },
296 ]);
297 });
298​
299 it.each(["claude", "codex", "grok"] as const)(
300 "matches ordinary %s records with large irrelevant fields in either order",
301 async (provider) => {
302 const small =
303 provider === "codex"
304 ? codex
305 : provider === "grok"
306 ? [grok]
307 : [{ ...claude(), message: { ...claude().message, content: [] } }];
308 const expected = await scan(small, provider, "small");
309 for (const first of [true, false]) {
310 const large = small.map((record) =>
311 first ? { padding: content, ...record } : { ...record, padding: content },
312 );
313 const actual = await scan(large, provider);
314 expect(actual.records).toEqual(expected.records);
315 expect(actual.position.state).toEqual(expected.position.state);
316 }
317 },
318 );
319​
320 it("preserves Grok model allocation, precise timestamp and prompt identity", async () => {
321 const result = await scan([{ padding: content, ...grok }], "grok");
322 expect(result.records[0]).toMatchObject({
323 timestampMs: 1785578400123,
324 model: "grok-4.5-build",
325 sessionId: "s1",
326 totals: {
327 uncachedInputTokens: 75,
328 cachedInputTokens: 20,
329 cacheCreationTokens: 5,
330 outputTokens: 99,
331 reasoningTokens: 10,
332 },
333 dedupeKey: "s1:p1:1785578400123:grok-4.5-build",
334 reportedCostUsd: 0.25,
335 });
336 });
337​
338 it("does not count usage-looking text or nested objects inside tool output", async () => {
339 const result = await scan(
340 [
341 { type: "user", padding: content, toolOutput: claude() },
342 { padding: content, message: { content: JSON.stringify(claude()) } },
343 { type: "assistant", timestamp, message: { model: "claude-fable-5", content: [claude()] } },
344 ],
345 "claude",
346 );
347 expect(result.records).toEqual([]);
348 });
349​
350 it("replays partial UTF-8 and JSON tails, commits exact CRLF offsets, and replaces the tail once", async () => {
351 const path = NodePath.join(dir, "tail.jsonl");
352 const first = JSON.stringify(claude("first", 5)) + "\r\n";
353 const second = Buffer.from(JSON.stringify(claude("second", 7)));
354 const split = second.lastIndexOf(Buffer.from("工具")) + 1;
355 await NodeFSP.writeFile(path, Buffer.concat([Buffer.from(first), second.subarray(0, split)]));
356 const partial = await readTranscriptRecords(path, "claude");
357 expect(partial?.records.map((r) => r.totals.outputTokens)).toEqual([5]);
358 expect(partial?.tailRecords).toEqual([]);
359 expect(partial?.position.resumeOffset).toBe(Buffer.byteLength(first));
360 await NodeFSP.appendFile(path, second.subarray(split));
361 const complete = await readTranscriptRecords(path, "claude", partial!.position);
362 expect(complete?.resumed).toBe(true);
363 expect(complete?.records).toEqual([]);
364 expect(complete?.tailRecords.map((r) => r.totals.outputTokens)).toEqual([7]);
365 expect(complete?.position.resumeOffset).toBe(Buffer.byteLength(first));
366 await NodeFSP.appendFile(path, "\r\n" + JSON.stringify(claude("third", 11)) + "\n");
367 const appended = await readTranscriptRecords(path, "claude", complete!.position);
368 expect(appended?.records.map((r) => r.totals.outputTokens)).toEqual([7, 11]);
369 expect(appended?.tailRecords).toEqual([]);
370 expect(appended?.position.resumeOffset).toBe((await NodeFSP.stat(path)).size);
371 const full = await readTranscriptRecords(path, "claude");
372 expect([...partial!.records, ...appended!.records]).toEqual(full?.records);
373 });
374​
375 it("preserves Codex model switches and duplicate suppression across streaming resumes", async () => {
376 const path = NodePath.join(dir, "history.jsonl");
377 const first = await scan(
378 codex.map((record) => ({ padding: "x".repeat(9 * 1024 * 1024), ...record })),
379 "codex",
380 );
381 expect(first.records[0]).toMatchObject({
382 sessionId: "s1",
383 model: "gpt-5.6-sol",
384 unresolvedServiceTierTurnId: "initial-turn",
385 });
386 await NodeFSP.appendFile(
387 path,
388 [
389 { padding: content, ...codex[2] },
390 { type: "turn_context", payload: { padding: content, model: "gpt-6" } },
391 {
392 type: "event_msg",
393 timestamp,
394 payload: {
395 type: "token_count",
396 padding: content,
397 info: { last_token_usage: { input_tokens: 200, output_tokens: 101 } },
398 },
399 },
400 ]
401 .map((line) => JSON.stringify(line))
402 .join("\n") + "\n",
403 );
404 const result = await readTranscriptRecords(path, "codex", first.position);
405 expect(result?.resumed).toBe(true);
406 expect(result?.records).toHaveLength(1);
407 expect(result?.records[0]).toMatchObject({
408 model: "gpt-6",
409 sessionId: "s1",
410 totals: { outputTokens: 101 },
411 });
412 expect(result?.records[0]).not.toHaveProperty("unresolvedServiceTierTurnId");
413 const full = await readTranscriptRecords(path, "codex");
414 expect([...first.records, ...result!.records]).toEqual(full?.records);
415 });
416​
417 it.each(["forked_from_id", "source"])(
418 "preserves Codex fork-copy suppression from %s",
419 async (field) => {
420 const fork =
421 field === "source"
422 ? { source: { subagent: { thread_spawn: { parent_thread_id: "parent" } } } }
423 : { forked_from_id: "parent" };
424 const lines = [
425 { type: "session_meta", timestamp, payload: { padding: content, id: "child", ...fork } },
426 codex[1],
427 codex[2],
428 {
429 ...codex[2],
430 timestamp: "2026-08-01T10:00:05Z",
431 payload: {
432 type: "token_count",
433 info: { last_token_usage: { input_tokens: 100, output_tokens: 101 } },
434 },
435 },
436 ];
437 const result = await scan(lines, "codex");
438 expect(result.records).toHaveLength(1);
439 expect(result.records[0]).toMatchObject({
440 sessionId: "child",
441 totals: { outputTokens: 101 },
442 });
443 },
444 );
445​
446 it("rejects malformed large lines without accepting partial usage or losing following lines", async () => {
447 const valid = JSON.stringify(claude());
448 const path = NodePath.join(dir, "broken.jsonl");
449 await NodeFSP.writeFile(
450 path,
451 [valid + " junk", valid.slice(0, -1), valid + valid, JSON.stringify(claude("good", 7))].join(
452 "\n",
453 ) + "\n",
454 );
455 const result = await readTranscriptRecords(path, "claude");
456 expect(result?.records.map((r) => r.totals.outputTokens)).toEqual([7]);
457 });
458​
459 it("matches JSON.parse for reordered and escaped keys, duplicate fields, arrays and unknown key names", async () => {
460 const path = NodePath.join(dir, "odd.jsonl");
461 const small = JSON.stringify({ ...claude(), message: { ...claude().message, content: [] } });
462 const variants = [
463 small.replace('"message":', '"mess\\u0061ge":'),
464 small.replace('"costUSD":0.25', '"costUSD":5,"costUSD":0.25'),
465 small.replace('"type":"assistant"', '"type":"user","type":"assistant"'),
466 small.replace('"message":', '"__proto__":{"type":"user"},"message":'),
467 small.replace('"message":', '"message.usage":{"output_tokens":1234},"message":'),
468 ];
469 for (const line of variants) {
470 await NodeFSP.writeFile(path, line + "\n");
471 const expected = await readTranscriptRecords(path, "claude");
472 await NodeFSP.writeFile(
473 path,
474 '{"padding":' + JSON.stringify(content) + "," + line.slice(1) + "\n",
475 );
476 const actual = await readTranscriptRecords(path, "claude");
477 expect(actual?.records).toEqual(expected?.records);
478 }
479 });
480 it("reads usage after deeply nested discarded tool content", async () => {
481 const path = NodePath.join(dir, "deep.jsonl");
482 const record = JSON.stringify(claude());
483 const nested = "[".repeat(300) + "0" + "]".repeat(300);
484 await NodeFSP.writeFile(path, '{"toolOutput":' + nested + "," + record.slice(1) + "\n");
485 const result = await readTranscriptRecords(path, "claude");
486 expect(result?.records[0]?.totals.outputTokens).toBe(99);
487 });
488​
489 it("keeps JSON number semantics for non-finite values without serializing them into null", async () => {
490 const path = NodePath.join(dir, "numbers.jsonl");
491 const record = JSON.stringify(claude()).replace('"costUSD":0.25', '"costUSD":1e400');
492 await NodeFSP.writeFile(path, record + "\n");
493 const result = await readTranscriptRecords(path, "claude");
494 expect(result?.records[0]?.reportedCostUsd).toBeNull();
495 expect(result?.records[0]?.totals.outputTokens).toBe(99);
496 });
497});