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

usageTranscriptStreaming.test.ts

327 lines11.6 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​
14// Exercise the same transition with compact fixtures. UsageService tests and
15// external 65/517 MiB fixtures also exercise the production threshold.
16const readTranscriptRecords = (
17 path: string,
18 provider: "claude" | "codex" | "grok",
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" } },
56 { type: "turn_context", timestamp, payload: { model: "gpt-5.6-sol" } },
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: "claude" | "codex" | "grok",
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("keeps usage after large Claude tool input, including fast-mode cost and dedupe metadata", async () => {
114 const result = await scan([claude()], "claude");
115 expect(result.records).toEqual([
116 {
117 provider: "claude",
118 timestampMs: Date.parse(timestamp),
119 sessionId: "s1",
120 model: "claude-fable-5",
121 totals: {
122 uncachedInputTokens: 100,
123 outputTokens: 99,
124 cachedInputTokens: 20,
125 cacheCreationTokens: 5,
126 reasoningTokens: 0,
127 },
128 reportedCostUsd: 0.25,
129 speed: "fast",
130 dedupeKey: "m1:r-m1",
131 },
132 ]);
133 });
134​
135 it.each(["claude", "codex", "grok"] as const)(
136 "matches ordinary %s records with large irrelevant fields in either order",
137 async (provider) => {
138 const small =
139 provider === "codex"
140 ? codex
141 : provider === "grok"
142 ? [grok]
143 : [{ ...claude(), message: { ...claude().message, content: [] } }];
144 const expected = await scan(small, provider, "small");
145 for (const first of [true, false]) {
146 const large = small.map((record) =>
147 first ? { padding: content, ...record } : { ...record, padding: content },
148 );
149 const actual = await scan(large, provider);
150 expect(actual.records).toEqual(expected.records);
151 expect(actual.position.state).toEqual(expected.position.state);
152 }
153 },
154 );
155​
156 it("preserves Grok model allocation, precise timestamp and prompt identity", async () => {
157 const result = await scan([{ padding: content, ...grok }], "grok");
158 expect(result.records[0]).toMatchObject({
159 timestampMs: 1785578400123,
160 model: "grok-4.5-build",
161 sessionId: "s1",
162 totals: {
163 uncachedInputTokens: 75,
164 cachedInputTokens: 20,
165 cacheCreationTokens: 5,
166 outputTokens: 99,
167 reasoningTokens: 10,
168 },
169 dedupeKey: "s1:p1:grok-4.5-build",
170 reportedCostUsd: 0.25,
171 });
172 });
173​
174 it("does not count usage-looking text or nested objects inside tool output", async () => {
175 const result = await scan(
176 [
177 { type: "user", padding: content, toolOutput: claude() },
178 { padding: content, message: { content: JSON.stringify(claude()) } },
179 { type: "assistant", timestamp, message: { model: "claude-fable-5", content: [claude()] } },
180 ],
181 "claude",
182 );
183 expect(result.records).toEqual([]);
184 });
185​
186 it("replays partial UTF-8 and JSON tails, commits exact CRLF offsets, and replaces the tail once", async () => {
187 const path = NodePath.join(dir, "tail.jsonl");
188 const first = JSON.stringify(claude("first", 5)) + "\r\n";
189 const second = Buffer.from(JSON.stringify(claude("second", 7)));
190 const split = second.lastIndexOf(Buffer.from("工具")) + 1;
191 await NodeFSP.writeFile(path, Buffer.concat([Buffer.from(first), second.subarray(0, split)]));
192 const partial = await readTranscriptRecords(path, "claude");
193 expect(partial?.records.map((r) => r.totals.outputTokens)).toEqual([5]);
194 expect(partial?.tailRecords).toEqual([]);
195 expect(partial?.position.resumeOffset).toBe(Buffer.byteLength(first));
196 await NodeFSP.appendFile(path, second.subarray(split));
197 const complete = await readTranscriptRecords(path, "claude", partial!.position);
198 expect(complete?.resumed).toBe(true);
199 expect(complete?.records).toEqual([]);
200 expect(complete?.tailRecords.map((r) => r.totals.outputTokens)).toEqual([7]);
201 expect(complete?.position.resumeOffset).toBe(Buffer.byteLength(first));
202 await NodeFSP.appendFile(path, "\r\n" + JSON.stringify(claude("third", 11)) + "\n");
203 const appended = await readTranscriptRecords(path, "claude", complete!.position);
204 expect(appended?.records.map((r) => r.totals.outputTokens)).toEqual([7, 11]);
205 expect(appended?.tailRecords).toEqual([]);
206 expect(appended?.position.resumeOffset).toBe((await NodeFSP.stat(path)).size);
207 const full = await readTranscriptRecords(path, "claude");
208 expect([...partial!.records, ...appended!.records]).toEqual(full?.records);
209 });
210​
211 it("preserves Codex model switches and duplicate suppression across streaming resumes", async () => {
212 const path = NodePath.join(dir, "history.jsonl");
213 const first = await scan(
214 codex.map((record) => ({ padding: content, ...record })),
215 "codex",
216 );
217 await NodeFSP.appendFile(
218 path,
219 [
220 { padding: content, ...codex[2] },
221 { type: "turn_context", payload: { padding: content, model: "gpt-6" } },
222 {
223 type: "event_msg",
224 timestamp,
225 payload: {
226 type: "token_count",
227 padding: content,
228 info: { last_token_usage: { input_tokens: 200, output_tokens: 101 } },
229 },
230 },
231 ]
232 .map((line) => JSON.stringify(line))
233 .join("\n") + "\n",
234 );
235 const result = await readTranscriptRecords(path, "codex", first.position);
236 expect(result?.resumed).toBe(true);
237 expect(result?.records).toHaveLength(1);
238 expect(result?.records[0]).toMatchObject({
239 model: "gpt-6",
240 sessionId: "s1",
241 totals: { outputTokens: 101 },
242 });
243 const full = await readTranscriptRecords(path, "codex");
244 expect([...first.records, ...result!.records]).toEqual(full?.records);
245 });
246​
247 it.each(["forked_from_id", "source"])(
248 "preserves Codex fork-copy suppression from %s",
249 async (field) => {
250 const fork =
251 field === "source"
252 ? { source: { subagent: { thread_spawn: { parent_thread_id: "parent" } } } }
253 : { forked_from_id: "parent" };
254 const lines = [
255 { type: "session_meta", timestamp, payload: { padding: content, id: "child", ...fork } },
256 codex[1],
257 codex[2],
258 {
259 ...codex[2],
260 timestamp: "2026-08-01T10:00:05Z",
261 payload: {
262 type: "token_count",
263 info: { last_token_usage: { input_tokens: 100, output_tokens: 101 } },
264 },
265 },
266 ];
267 const result = await scan(lines, "codex");
268 expect(result.records).toHaveLength(1);
269 expect(result.records[0]).toMatchObject({
270 sessionId: "child",
271 totals: { outputTokens: 101 },
272 });
273 },
274 );
275​
276 it("rejects malformed large lines without accepting partial usage or losing following lines", async () => {
277 const valid = JSON.stringify(claude());
278 const path = NodePath.join(dir, "broken.jsonl");
279 await NodeFSP.writeFile(
280 path,
281 [valid + " junk", valid.slice(0, -1), valid + valid, JSON.stringify(claude("good", 7))].join(
282 "\n",
283 ) + "\n",
284 );
285 const result = await readTranscriptRecords(path, "claude");
286 expect(result?.records.map((r) => r.totals.outputTokens)).toEqual([7]);
287 });
288​
289 it("matches JSON.parse for reordered and escaped keys, duplicate fields, arrays and unknown key names", async () => {
290 const path = NodePath.join(dir, "odd.jsonl");
291 const small = JSON.stringify({ ...claude(), message: { ...claude().message, content: [] } });
292 const variants = [
293 small.replace('"message":', '"mess\\u0061ge":'),
294 small.replace('"costUSD":0.25', '"costUSD":5,"costUSD":0.25'),
295 small.replace('"type":"assistant"', '"type":"user","type":"assistant"'),
296 small.replace('"message":', '"__proto__":{"type":"user"},"message":'),
297 small.replace('"message":', '"message.usage":{"output_tokens":1234},"message":'),
298 ];
299 for (const line of variants) {
300 await NodeFSP.writeFile(path, line + "\n");
301 const expected = await readTranscriptRecords(path, "claude");
302 await NodeFSP.writeFile(
303 path,
304 '{"padding":' + JSON.stringify(content) + "," + line.slice(1) + "\n",
305 );
306 const actual = await readTranscriptRecords(path, "claude");
307 expect(actual?.records).toEqual(expected?.records);
308 }
309 });
310 it("reads usage after deeply nested discarded tool content", async () => {
311 const path = NodePath.join(dir, "deep.jsonl");
312 const record = JSON.stringify(claude());
313 const nested = "[".repeat(300) + "0" + "]".repeat(300);
314 await NodeFSP.writeFile(path, '{"toolOutput":' + nested + "," + record.slice(1) + "\n");
315 const result = await readTranscriptRecords(path, "claude");
316 expect(result?.records[0]?.totals.outputTokens).toBe(99);
317 });
318​
319 it("keeps JSON number semantics for non-finite values without serializing them into null", async () => {
320 const path = NodePath.join(dir, "numbers.jsonl");
321 const record = JSON.stringify(claude()).replace('"costUSD":0.25', '"costUSD":1e400');
322 await NodeFSP.writeFile(path, record + "\n");
323 const result = await readTranscriptRecords(path, "claude");
324 expect(result?.records[0]?.reportedCostUsd).toBeNull();
325 expect(result?.records[0]?.totals.outputTokens).toBe(99);
326 });
327});