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

usageTranscriptStreaming.test.ts

368 lines12.7 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" } },
54 { type: "turn_context", timestamp, payload: { model: "gpt-5.6-sol" } },
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: content, ...record })),
256 "codex",
257 );
258 await NodeFSP.appendFile(
259 path,
260 [
261 { padding: content, ...codex[2] },
262 { type: "turn_context", payload: { padding: content, model: "gpt-6" } },
263 {
264 type: "event_msg",
265 timestamp,
266 payload: {
267 type: "token_count",
268 padding: content,
269 info: { last_token_usage: { input_tokens: 200, output_tokens: 101 } },
270 },
271 },
272 ]
273 .map((line) => JSON.stringify(line))
274 .join("\n") + "\n",
275 );
276 const result = await readTranscriptRecords(path, "codex", first.position);
277 expect(result?.resumed).toBe(true);
278 expect(result?.records).toHaveLength(1);
279 expect(result?.records[0]).toMatchObject({
280 model: "gpt-6",
281 sessionId: "s1",
282 totals: { outputTokens: 101 },
283 });
284 const full = await readTranscriptRecords(path, "codex");
285 expect([...first.records, ...result!.records]).toEqual(full?.records);
286 });
287​
288 it.each(["forked_from_id", "source"])(
289 "preserves Codex fork-copy suppression from %s",
290 async (field) => {
291 const fork =
292 field === "source"
293 ? { source: { subagent: { thread_spawn: { parent_thread_id: "parent" } } } }
294 : { forked_from_id: "parent" };
295 const lines = [
296 { type: "session_meta", timestamp, payload: { padding: content, id: "child", ...fork } },
297 codex[1],
298 codex[2],
299 {
300 ...codex[2],
301 timestamp: "2026-08-01T10:00:05Z",
302 payload: {
303 type: "token_count",
304 info: { last_token_usage: { input_tokens: 100, output_tokens: 101 } },
305 },
306 },
307 ];
308 const result = await scan(lines, "codex");
309 expect(result.records).toHaveLength(1);
310 expect(result.records[0]).toMatchObject({
311 sessionId: "child",
312 totals: { outputTokens: 101 },
313 });
314 },
315 );
316​
317 it("rejects malformed large lines without accepting partial usage or losing following lines", async () => {
318 const valid = JSON.stringify(claude());
319 const path = NodePath.join(dir, "broken.jsonl");
320 await NodeFSP.writeFile(
321 path,
322 [valid + " junk", valid.slice(0, -1), valid + valid, JSON.stringify(claude("good", 7))].join(
323 "\n",
324 ) + "\n",
325 );
326 const result = await readTranscriptRecords(path, "claude");
327 expect(result?.records.map((r) => r.totals.outputTokens)).toEqual([7]);
328 });
329​
330 it("matches JSON.parse for reordered and escaped keys, duplicate fields, arrays and unknown key names", async () => {
331 const path = NodePath.join(dir, "odd.jsonl");
332 const small = JSON.stringify({ ...claude(), message: { ...claude().message, content: [] } });
333 const variants = [
334 small.replace('"message":', '"mess\\u0061ge":'),
335 small.replace('"costUSD":0.25', '"costUSD":5,"costUSD":0.25'),
336 small.replace('"type":"assistant"', '"type":"user","type":"assistant"'),
337 small.replace('"message":', '"__proto__":{"type":"user"},"message":'),
338 small.replace('"message":', '"message.usage":{"output_tokens":1234},"message":'),
339 ];
340 for (const line of variants) {
341 await NodeFSP.writeFile(path, line + "\n");
342 const expected = await readTranscriptRecords(path, "claude");
343 await NodeFSP.writeFile(
344 path,
345 '{"padding":' + JSON.stringify(content) + "," + line.slice(1) + "\n",
346 );
347 const actual = await readTranscriptRecords(path, "claude");
348 expect(actual?.records).toEqual(expected?.records);
349 }
350 });
351 it("reads usage after deeply nested discarded tool content", async () => {
352 const path = NodePath.join(dir, "deep.jsonl");
353 const record = JSON.stringify(claude());
354 const nested = "[".repeat(300) + "0" + "]".repeat(300);
355 await NodeFSP.writeFile(path, '{"toolOutput":' + nested + "," + record.slice(1) + "\n");
356 const result = await readTranscriptRecords(path, "claude");
357 expect(result?.records[0]?.totals.outputTokens).toBe(99);
358 });
359​
360 it("keeps JSON number semantics for non-finite values without serializing them into null", async () => {
361 const path = NodePath.join(dir, "numbers.jsonl");
362 const record = JSON.stringify(claude()).replace('"costUSD":0.25', '"costUSD":1e400');
363 await NodeFSP.writeFile(path, record + "\n");
364 const result = await readTranscriptRecords(path, "claude");
365 expect(result?.records[0]?.reportedCostUsd).toBeNull();
366 expect(result?.records[0]?.totals.outputTokens).toBe(99);
367 });
368});