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

usageTranscriptStreaming.test.ts

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