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

usageTranscriptStreaming.test.ts

374 lines13.0 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";
5​
6import { afterEach, beforeEach, describe, expect, it } from "@effect/vitest";
7​
8import { TEST_FORMATS } from "./usageTestFormats.ts";
9import {
10 readTranscriptRecords as readWithDefaultThreshold,
11 type TranscriptParsePosition,
12} from "./usageTranscriptReader.ts";
13​
14const readTranscriptRecords = (
15 path: string,
16 provider: keyof typeof TEST_FORMATS,
17 position?: TranscriptParsePosition,
18) =>
19 readWithDefaultThreshold(path, TEST_FORMATS[provider], position, {
20 streamingThresholdBytes: 256 * 1024,
21 });
22​
23let dir: string;
24beforeEach(async () => {
25 dir = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "usage-stream-"));
26});
27afterEach(async () => {
28 await NodeFSP.rm(dir, { recursive: true, force: true });
29});
30​
31const timestamp = "2026-08-01T10:00:00Z";
32const content = '工具 output \\" usage token_count '.repeat(40_000);
33const claude = (id = "m1", output = 99) => ({
34 type: "assistant",
35 timestamp,
36 sessionId: "s1",
37 requestId: `r-${id}`,
38 costUSD: 0.25,
39 message: {
40 content: [{ type: "tool_use", input: { text: content } }],
41 id,
42 model: "claude-fable-5",
43 usage: {
44 input_tokens: 100,
45 output_tokens: output,
46 cache_read_input_tokens: 20,
47 cache_creation_input_tokens: 5,
48 speed: "fast",
49 },
50 },
51});
52const codex = [
53 { type: "session_meta", timestamp, payload: { id: "s1", model_provider: "openai" } },
54 { type: "turn_context", timestamp, payload: { model: "gpt-5.6-sol", turn_id: "initial-turn" } },
55 {
56 type: "event_msg",
57 timestamp,
58 payload: {
59 type: "token_count",
60 info: {
61 last_token_usage: {
62 input_tokens: 100,
63 output_tokens: 99,
64 cached_input_tokens: 20,
65 cache_write_input_tokens: 5,
66 reasoning_output_tokens: 10,
67 },
68 },
69 },
70 },
71];
72const grok = {
73 timestamp: 1785578400,
74 params: {
75 sessionId: "s1",
76 _meta: { agentTimestampMs: 1785578400123 },
77 update: {
78 sessionUpdate: "turn_completed",
79 prompt_id: "p1",
80 usage: {
81 inputTokens: 100,
82 outputTokens: 99,
83 costUsdTicks: 2500000000,
84 modelUsage: {
85 "grok-4.5-build": {
86 inputTokens: 100,
87 outputTokens: 99,
88 cachedReadTokens: 20,
89 cacheCreationTokens: 5,
90 reasoningTokens: 10,
91 },
92 },
93 },
94 },
95 },
96};
97​
98async function scan(
99 lines: readonly unknown[],
100 provider: keyof typeof TEST_FORMATS,
101 name = "history",
102) {
103 const path = NodePath.join(dir, `${name}.jsonl`);
104 await NodeFSP.writeFile(path, lines.map((line) => JSON.stringify(line)).join("\n") + "\n");
105 const result = await readTranscriptRecords(path, provider);
106 expect(result).not.toBeNull();
107 return result!;
109​
110describe("large usage records", () => {
111 it("keeps Pi model, cost, and fork identity after large assistant content", async () => {
112 const entry = {
113 type: "message",
114 id: "a123abcd",
115 timestamp,
116 message: {
117 role: "assistant",
118 provider: "anthropic",
119 model: "requested",
120 responseModel: "actual",
121 content: [{ type: "text", text: content }],
122 usage: {
123 input: 100,
124 output: 99,
125 cacheRead: 20,
126 cacheWrite: 5,
127 reasoning: 10,
128 cost: { total: 0.25 },
129 },
130 },
131 };
132 const result = await scan([{ type: "session", id: "pi-session" }, entry], "pi");
133 expect(result.records).toEqual([
134 {
135 provider: "pi",
136 model: "anthropic/actual",
137 rateModel: "actual",
138 sessionId: "pi-session",
139 timestampMs: Date.parse(timestamp),
140 totals: {
141 uncachedInputTokens: 100,
142 outputTokens: 99,
143 cachedInputTokens: 20,
144 cacheCreationTokens: 5,
145 reasoningTokens: 10,
146 },
147 reportedCostUsd: 0.25,
148 speed: "standard",
149 dedupeKey: JSON.stringify(["pi", entry.id, timestamp, "anthropic/actual"]),
150 },
151 ]);
152 });
153​
154 it("keeps usage after large Claude tool input, including fast-mode cost and dedupe metadata", async () => {
155 const result = await scan([claude()], "claude");
156 expect(result.records).toEqual([
157 {
158 provider: "claude",
159 timestampMs: Date.parse(timestamp),
160 sessionId: "s1",
161 model: "claude-fable-5",
162 totals: {
163 uncachedInputTokens: 100,
164 outputTokens: 99,
165 cachedInputTokens: 20,
166 cacheCreationTokens: 5,
167 reasoningTokens: 0,
168 },
169 reportedCostUsd: 0.25,
170 speed: "fast",
171 dedupeKey: "m1:r-m1",
172 },
173 ]);
174 });
175​
176 it.each(["claude", "codex", "grok"] as const)(
177 "matches ordinary %s records with large irrelevant fields in either order",
178 async (provider) => {
179 const small =
180 provider === "codex"
181 ? codex
182 : provider === "grok"
183 ? [grok]
184 : [{ ...claude(), message: { ...claude().message, content: [] } }];
185 const expected = await scan(small, provider, "small");
186 for (const first of [true, false]) {
187 const large = small.map((record) =>
188 first ? { padding: content, ...record } : { ...record, padding: content },
189 );
190 const actual = await scan(large, provider);
191 expect(actual.records).toEqual(expected.records);
192 expect(actual.position.state).toEqual(expected.position.state);
193 }
194 },
195 );
196​
197 it("preserves Grok model allocation, precise timestamp and prompt identity", async () => {
198 const result = await scan([{ padding: content, ...grok }], "grok");
199 expect(result.records[0]).toMatchObject({
200 timestampMs: 1785578400123,
201 model: "grok-4.5-build",
202 sessionId: "s1",
203 totals: {
204 uncachedInputTokens: 75,
205 cachedInputTokens: 20,
206 cacheCreationTokens: 5,
207 outputTokens: 99,
208 reasoningTokens: 10,
209 },
210 dedupeKey: "s1:p1:grok-4.5-build",
211 reportedCostUsd: 0.25,
212 });
213 });
214​
215 it("does not count usage-looking text or nested objects inside tool output", async () => {
216 const result = await scan(
217 [
218 { type: "user", padding: content, toolOutput: claude() },
219 { padding: content, message: { content: JSON.stringify(claude()) } },
220 { type: "assistant", timestamp, message: { model: "claude-fable-5", content: [claude()] } },
221 ],
222 "claude",
223 );
224 expect(result.records).toEqual([]);
225 });
226​
227 it("replays partial UTF-8 and JSON tails, commits exact CRLF offsets, and replaces the tail once", async () => {
228 const path = NodePath.join(dir, "tail.jsonl");
229 const first = JSON.stringify(claude("first", 5)) + "\r\n";
230 const second = Buffer.from(JSON.stringify(claude("second", 7)));
231 const split = second.lastIndexOf(Buffer.from("工具")) + 1;
232 await NodeFSP.writeFile(path, Buffer.concat([Buffer.from(first), second.subarray(0, split)]));
233 const partial = await readTranscriptRecords(path, "claude");
234 expect(partial?.records.map((r) => r.totals.outputTokens)).toEqual([5]);
235 expect(partial?.tailRecords).toEqual([]);
236 expect(partial?.position.resumeOffset).toBe(Buffer.byteLength(first));
237 await NodeFSP.appendFile(path, second.subarray(split));
238 const complete = await readTranscriptRecords(path, "claude", partial!.position);
239 expect(complete?.resumed).toBe(true);
240 expect(complete?.records).toEqual([]);
241 expect(complete?.tailRecords.map((r) => r.totals.outputTokens)).toEqual([7]);
242 expect(complete?.position.resumeOffset).toBe(Buffer.byteLength(first));
243 await NodeFSP.appendFile(path, "\r\n" + JSON.stringify(claude("third", 11)) + "\n");
244 const appended = await readTranscriptRecords(path, "claude", complete!.position);
245 expect(appended?.records.map((r) => r.totals.outputTokens)).toEqual([7, 11]);
246 expect(appended?.tailRecords).toEqual([]);
247 expect(appended?.position.resumeOffset).toBe((await NodeFSP.stat(path)).size);
248 const full = await readTranscriptRecords(path, "claude");
249 expect([...partial!.records, ...appended!.records]).toEqual(full?.records);
250 });
251​
252 it("preserves Codex model switches and duplicate suppression across streaming resumes", async () => {
253 const path = NodePath.join(dir, "history.jsonl");
254 const first = await scan(
255 codex.map((record) => ({ padding: "x".repeat(9 * 1024 * 1024), ...record })),
256 "codex",
257 );
258 expect(first.records[0]).toMatchObject({
259 sessionId: "s1",
260 model: "gpt-5.6-sol",
261 unresolvedServiceTierTurnId: "initial-turn",
262 });
263 await NodeFSP.appendFile(
264 path,
265 [
266 { padding: content, ...codex[2] },
267 { type: "turn_context", payload: { padding: content, model: "gpt-6" } },
268 {
269 type: "event_msg",
270 timestamp,
271 payload: {
272 type: "token_count",
273 padding: content,
274 info: { last_token_usage: { input_tokens: 200, output_tokens: 101 } },
275 },
276 },
277 ]
278 .map((line) => JSON.stringify(line))
279 .join("\n") + "\n",
280 );
281 const result = await readTranscriptRecords(path, "codex", first.position);
282 expect(result?.resumed).toBe(true);
283 expect(result?.records).toHaveLength(1);
284 expect(result?.records[0]).toMatchObject({
285 model: "gpt-6",
286 sessionId: "s1",
287 totals: { outputTokens: 101 },
288 });
289 expect(result?.records[0]).not.toHaveProperty("unresolvedServiceTierTurnId");
290 const full = await readTranscriptRecords(path, "codex");
291 expect([...first.records, ...result!.records]).toEqual(full?.records);
292 });
293​
294 it.each(["forked_from_id", "source"])(
295 "preserves Codex fork-copy suppression from %s",
296 async (field) => {
297 const fork =
298 field === "source"
299 ? { source: { subagent: { thread_spawn: { parent_thread_id: "parent" } } } }
300 : { forked_from_id: "parent" };
301 const lines = [
302 { type: "session_meta", timestamp, payload: { padding: content, id: "child", ...fork } },
303 codex[1],
304 codex[2],
305 {
306 ...codex[2],
307 timestamp: "2026-08-01T10:00:05Z",
308 payload: {
309 type: "token_count",
310 info: { last_token_usage: { input_tokens: 100, output_tokens: 101 } },
311 },
312 },
313 ];
314 const result = await scan(lines, "codex");
315 expect(result.records).toHaveLength(1);
316 expect(result.records[0]).toMatchObject({
317 sessionId: "child",
318 totals: { outputTokens: 101 },
319 });
320 },
321 );
322​
323 it("rejects malformed large lines without accepting partial usage or losing following lines", async () => {
324 const valid = JSON.stringify(claude());
325 const path = NodePath.join(dir, "broken.jsonl");
326 await NodeFSP.writeFile(
327 path,
328 [valid + " junk", valid.slice(0, -1), valid + valid, JSON.stringify(claude("good", 7))].join(
329 "\n",
330 ) + "\n",
331 );
332 const result = await readTranscriptRecords(path, "claude");
333 expect(result?.records.map((r) => r.totals.outputTokens)).toEqual([7]);
334 });
335​
336 it("matches JSON.parse for reordered and escaped keys, duplicate fields, arrays and unknown key names", async () => {
337 const path = NodePath.join(dir, "odd.jsonl");
338 const small = JSON.stringify({ ...claude(), message: { ...claude().message, content: [] } });
339 const variants = [
340 small.replace('"message":', '"mess\\u0061ge":'),
341 small.replace('"costUSD":0.25', '"costUSD":5,"costUSD":0.25'),
342 small.replace('"type":"assistant"', '"type":"user","type":"assistant"'),
343 small.replace('"message":', '"__proto__":{"type":"user"},"message":'),
344 small.replace('"message":', '"message.usage":{"output_tokens":1234},"message":'),
345 ];
346 for (const line of variants) {
347 await NodeFSP.writeFile(path, line + "\n");
348 const expected = await readTranscriptRecords(path, "claude");
349 await NodeFSP.writeFile(
350 path,
351 '{"padding":' + JSON.stringify(content) + "," + line.slice(1) + "\n",
352 );
353 const actual = await readTranscriptRecords(path, "claude");
354 expect(actual?.records).toEqual(expected?.records);
355 }
356 });
357 it("reads usage after deeply nested discarded tool content", async () => {
358 const path = NodePath.join(dir, "deep.jsonl");
359 const record = JSON.stringify(claude());
360 const nested = "[".repeat(300) + "0" + "]".repeat(300);
361 await NodeFSP.writeFile(path, '{"toolOutput":' + nested + "," + record.slice(1) + "\n");
362 const result = await readTranscriptRecords(path, "claude");
363 expect(result?.records[0]?.totals.outputTokens).toBe(99);
364 });
365​
366 it("keeps JSON number semantics for non-finite values without serializing them into null", async () => {
367 const path = NodePath.join(dir, "numbers.jsonl");
368 const record = JSON.stringify(claude()).replace('"costUSD":0.25', '"costUSD":1e400');
369 await NodeFSP.writeFile(path, record + "\n");
370 const result = await readTranscriptRecords(path, "claude");
371 expect(result?.records[0]?.reportedCostUsd).toBeNull();
372 expect(result?.records[0]?.totals.outputTokens).toBe(99);
373 });
374});