Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - resume coverage writes, appends
2// to, and truncates real transcript files byte-exactly, mirroring the reader's
3// own deliberate node:fs usage.
4import * as NodeFSP from "node:fs/promises";
5import * as NodeOS from "node:os";
6import * as NodePath from "node:path";
7
8import { afterEach, assert, beforeEach, describe, it } from "@effect/vitest";
9import type { TranscriptUsageFormat } from "@t3tools/provider-core/server/usage";
10import * as Schema from "effect/Schema";
11
12import { TEST_FORMATS } from "./usageTestFormats.ts";
13import { readTranscriptRecords, transcriptLineGate } from "./usageTranscriptReader.ts";
14
15let dir: string;
16
17beforeEach(async () => {
18 dir = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "usage-reader-test-"));
19});
20
21afterEach(async () => {
22 await NodeFSP.rm(dir, { recursive: true, force: true });
23});
24
25function claudeLine(id: number, outputTokens: number): string {
26 return `${JSON.stringify({
27 type: "assistant",
28 timestamp: "2026-08-01T10:00:00Z",
29 requestId: `req_${id}`,
30 sessionId: "session-1",
31 message: {
32 id: `msg_${id}`,
33 model: "claude-fable-5",
34 usage: { input_tokens: 10, output_tokens: outputTokens },
35 },
36 })}\n`;
37}
38
39function codexMetaLine(): string {
40 return `${JSON.stringify({
41 type: "session_meta",
42 timestamp: "2026-08-01T10:00:00Z",
43 payload: { type: "session_meta", id: "codex-session-1" },
44 })}\n`;
45}
46
47function codexModelLine(model: string): string {
48 return `${JSON.stringify({
49 type: "turn_context",
50 timestamp: "2026-08-01T10:00:01Z",
51 payload: { type: "turn_context", model },
52 })}\n`;
53}
54
55function codexTierLine(serviceTier: string): string {
56 return `${JSON.stringify({
57 type: "event_msg",
58 timestamp: "2026-08-01T10:00:01Z",
59 payload: { type: "thread_settings_applied", thread_settings: { service_tier: serviceTier } },
60 })}\n`;
61}
62
63function codexUsageLine(outputTokens: number, secondsOffset: number): string {
64 return `${JSON.stringify({
65 type: "event_msg",
66 timestamp: `2026-08-01T10:00:${String(secondsOffset).padStart(2, "0")}Z`,
67 payload: {
68 type: "token_count",
69 info: { last_token_usage: { input_tokens: 100, output_tokens: outputTokens } },
70 },
71 })}\n`;
72}
73
74describe("readTranscriptRecords resume", () => {
75 it.each([
76 { mode: "buffered", streamingThresholdBytes: Infinity },
77 { mode: "streaming", streamingThresholdBytes: 0 },
78 ])("counts malformed tails once across $mode reads and resume", async (options) => {
79 const format: TranscriptUsageFormat<{ errors: number }> = {
80 ...TEST_FORMATS.claude,
81 selectFields: { ...TEST_FORMATS.claude.selectFields, usage: true },
82 state: {
83 initial: () => ({ errors: 0 }),
84 schema: Schema.Struct({ errors: Schema.Number }),
85 },
86 parseLine(line, state) {
87 return this.parseProjected(JSON.parse(line), state);
88 },
89 parseProjected(value, state) {
90 if (
91 typeof value === "object" &&
92 value !== null &&
93 "usage" in value &&
94 value.usage === "malformed"
95 ) {
96 state.errors += 1;
97 return [];
98 }
99 return TEST_FORMATS.claude.parseProjected(value, undefined);
100 },
101 readMalformedRecords: (state: { errors: number }) => state.errors,
102 };
103 const path = NodePath.join(dir, "diagnostics.jsonl");
104 const malformed = JSON.stringify({ usage: "malformed" });
105 // Completed lines enter the projected parser only when they cross a stream chunk.
106 const committed = `${JSON.stringify({ usage: "malformed", padding: "x".repeat(256 * 1024) })}\n${claudeLine(1, 5)}`;
107 await NodeFSP.writeFile(path, committed + malformed);
108
109 const first = await readTranscriptRecords(path, format, undefined, options);
110 assert.isNotNull(first);
111 assert.deepStrictEqual(
112 first.records.map((record) => record.totals.outputTokens),
113 [5],
114 );
115 assert.deepStrictEqual(first.tailRecords, []);
116 assert.strictEqual(first.position.resumeOffset, Buffer.byteLength(committed));
117 assert.deepStrictEqual(first.position.state, { errors: 1 });
118 assert.strictEqual(first.malformedRecords, 2);
119
120 const savedPosition = JSON.parse(JSON.stringify(first.position));
121 await NodeFSP.appendFile(path, `\n${claudeLine(2, 7)}${malformed}\n`);
122 const resumed = await readTranscriptRecords(path, format, savedPosition, options);
123 assert.isNotNull(resumed);
124 assert.isTrue(resumed.resumed);
125 assert.deepStrictEqual(
126 resumed.records.map((record) => record.totals.outputTokens),
127 [7],
128 );
129 assert.deepStrictEqual(resumed.position.state, { errors: 3 });
130 assert.strictEqual(resumed.malformedRecords, 3);
131
132 const full = await readTranscriptRecords(path, format, undefined, options);
133 assert.isNotNull(full);
134 assert.deepStrictEqual([...first.records, ...resumed.records], full.records);
135 assert.deepStrictEqual(resumed.tailRecords, full.tailRecords);
136 assert.deepStrictEqual(resumed.position, full.position);
137 assert.strictEqual(resumed.malformedRecords, full.malformedRecords);
138 });
139
140 it("parses only appended lines when resuming a grown file", async () => {
141 const path = NodePath.join(dir, "claude.jsonl");
142 await NodeFSP.writeFile(path, claudeLine(1, 5) + claudeLine(2, 7));
143 const first = await readTranscriptRecords(path, TEST_FORMATS.claude);
144 assert.isNotNull(first);
145 assert.strictEqual(first.records.length, 2);
146 assert.isFalse(first.resumed);
147 assert.strictEqual(first.malformedRecords, 0);
148
149 await NodeFSP.appendFile(path, claudeLine(3, 11));
150 const second = await readTranscriptRecords(path, TEST_FORMATS.claude, first.position);
151 assert.isNotNull(second);
152 assert.isTrue(second.resumed);
153 assert.strictEqual(second.records.length, 1);
154 assert.strictEqual(second.records[0]?.totals.outputTokens, 11);
155
156 const full = await readTranscriptRecords(path, TEST_FORMATS.claude);
157 assert.isNotNull(full);
158 assert.deepStrictEqual([...first.records, ...second.records], [...full.records]);
159 });
160
161 it("carries the Codex reducer state across the resume boundary", async () => {
162 const path = NodePath.join(dir, "rollout.jsonl");
163 await NodeFSP.writeFile(
164 path,
165 codexMetaLine() + codexModelLine("gpt-5.2-codex") + codexTierLine("ultrafast"),
166 );
167 const first = await readTranscriptRecords(path, TEST_FORMATS.codex);
168 assert.isNotNull(first);
169 assert.strictEqual(first.records.length, 0);
170
171 await NodeFSP.appendFile(path, codexUsageLine(9, 5));
172 const second = await readTranscriptRecords(path, TEST_FORMATS.codex, first.position);
173 assert.isNotNull(second);
174 assert.isTrue(second.resumed);
175 assert.strictEqual(second.records.length, 1);
176 assert.strictEqual(second.records[0]?.model, "gpt-5.2-codex");
177 assert.strictEqual(second.records[0]?.speed, "ultrafast");
178 assert.strictEqual(second.records[0]?.sessionId, "codex-session-1");
179 });
180
181 it("suppresses a Codex duplicate usage event that straddles the boundary", async () => {
182 const path = NodePath.join(dir, "rollout.jsonl");
183 await NodeFSP.writeFile(
184 path,
185 codexMetaLine() + codexModelLine("gpt-5.2-codex") + codexUsageLine(9, 5),
186 );
187 const first = await readTranscriptRecords(path, TEST_FORMATS.codex);
188 assert.isNotNull(first);
189 assert.strictEqual(first.records.length, 1);
190
191 // Codex duplicates token_count at stream boundaries, including after resume points.
192 await NodeFSP.appendFile(path, codexUsageLine(9, 5) + codexUsageLine(21, 8));
193 const second = await readTranscriptRecords(path, TEST_FORMATS.codex, first.position);
194 assert.isNotNull(second);
195 assert.isTrue(second.resumed);
196 assert.deepStrictEqual(
197 second.records.map((record) => record.totals.outputTokens),
198 [21],
199 );
200 });
201
202 it("defers an unterminated trailing line to tailRecords, then consumes it once terminated", async () => {
203 const path = NodePath.join(dir, "claude.jsonl");
204 const unterminated = claudeLine(2, 7).trimEnd();
205 await NodeFSP.writeFile(path, claudeLine(1, 5) + unterminated);
206 const first = await readTranscriptRecords(path, TEST_FORMATS.claude);
207 assert.isNotNull(first);
208 assert.strictEqual(first.records.length, 1);
209 assert.strictEqual(first.tailRecords.length, 1);
210 assert.strictEqual(first.tailRecords[0]?.totals.outputTokens, 7);
211
212 await NodeFSP.appendFile(path, `\n${claudeLine(3, 11)}`);
213 const second = await readTranscriptRecords(path, TEST_FORMATS.claude, first.position);
214 assert.isNotNull(second);
215 assert.isTrue(second.resumed);
216 assert.deepStrictEqual(
217 second.records.map((record) => record.totals.outputTokens),
218 [7, 11],
219 );
220 assert.strictEqual(second.tailRecords.length, 0);
221 });
222
223 it.each([
224 { mode: "buffered", streamingThresholdBytes: Infinity },
225 { mode: "streaming", streamingThresholdBytes: 0 },
226 ])(
227 "resumes an initial Codex carried-total tail without rebilling it ($mode)",
228 async (options) => {
229 const path = NodePath.join(dir, "continuation.jsonl");
230 const usage = (input: number, output: number) => ({
231 input_tokens: input,
232 output_tokens: output,
233 });
234 const event = (last: unknown, cumulative: unknown) =>
235 JSON.stringify({
236 type: "event_msg",
237 timestamp: "2026-08-01T10:00:05Z",
238 payload: {
239 type: "token_count",
240 info: { last_token_usage: last, total_token_usage: cumulative },
241 },
242 });
243 const firstLine = event(usage(100, 20), usage(500, 60));
244 await NodeFSP.writeFile(
245 path,
246 codexMetaLine() + codexModelLine("gpt-6-astra") + codexTierLine("ultrafast") + firstLine,
247 );
248 const first = await readTranscriptRecords(path, TEST_FORMATS.codex, undefined, options);
249 assert.isNotNull(first);
250 assert.strictEqual(first.records.length, 0);
251 assert.deepStrictEqual(
252 first.tailRecords.map((r) => [r.totals.outputTokens, r.speed]),
253 [[20, "ultrafast"]],
254 );
255 assert.strictEqual(first.malformedRecords, 0);
256
257 await NodeFSP.appendFile(path, `\n${firstLine}\n${event(usage(10, 2), usage(510, 62))}\n`);
258 const resumed = await readTranscriptRecords(
259 path,
260 TEST_FORMATS.codex,
261 JSON.parse(JSON.stringify(first.position)),
262 options,
263 );
264 const full = await readTranscriptRecords(path, TEST_FORMATS.codex, undefined, options);
265 assert.isNotNull(resumed);
266 assert.isNotNull(full);
267 assert.isTrue(resumed.resumed);
268 assert.deepStrictEqual(resumed.records, full.records);
269 assert.deepStrictEqual(
270 resumed.records.map((r) => [r.totals.outputTokens, r.speed]),
271 [
272 [20, "ultrafast"],
273 [2, "ultrafast"],
274 ],
275 );
276 assert.deepStrictEqual(resumed.tailRecords, []);
277 assert.strictEqual(resumed.malformedRecords, 0);
278 assert.deepStrictEqual(resumed.position, full.position);
279 },
280 );
281
282 it("re-parses from the start when the guard bytes no longer match", async () => {
283 const path = NodePath.join(dir, "claude.jsonl");
284 await NodeFSP.writeFile(path, claudeLine(1, 5));
285 const first = await readTranscriptRecords(path, TEST_FORMATS.claude);
286 assert.isNotNull(first);
287
288 await NodeFSP.writeFile(path, claudeLine(4, 13) + claudeLine(5, 17));
289 const second = await readTranscriptRecords(path, TEST_FORMATS.claude, first.position);
290 assert.isNotNull(second);
291 assert.isFalse(second.resumed);
292 assert.deepStrictEqual(
293 second.records.map((record) => record.totals.outputTokens),
294 [13, 17],
295 );
296 });
297
298 it("re-parses from the start when the file shrank below the resume point", async () => {
299 const path = NodePath.join(dir, "claude.jsonl");
300 await NodeFSP.writeFile(path, claudeLine(1, 5) + claudeLine(2, 7));
301 const first = await readTranscriptRecords(path, TEST_FORMATS.claude);
302 assert.isNotNull(first);
303
304 await NodeFSP.writeFile(path, claudeLine(3, 11));
305 const second = await readTranscriptRecords(path, TEST_FORMATS.claude, first.position);
306 assert.isNotNull(second);
307 assert.isFalse(second.resumed);
308 assert.deepStrictEqual(
309 second.records.map((record) => record.totals.outputTokens),
310 [11],
311 );
312 });
313
314 it("parses a line larger than one stream chunk", async () => {
315 const path = NodePath.join(dir, "claude.jsonl");
316 const bigLine = `${JSON.stringify({
317 type: "assistant",
318 timestamp: "2026-08-01T10:00:00Z",
319 requestId: "req_big",
320 sessionId: "session-1",
321 padding: "x".repeat(512 * 1024),
322 message: {
323 id: "msg_big",
324 model: "claude-fable-5",
325 usage: { input_tokens: 10, output_tokens: 42 },
326 },
327 })}\n`;
328 await NodeFSP.writeFile(path, bigLine + claudeLine(2, 7));
329
330 const parsed = await readTranscriptRecords(path, TEST_FORMATS.claude);
331 assert.isNotNull(parsed);
332 assert.deepStrictEqual(
333 parsed.records.map((record) => record.totals.outputTokens),
334 [42, 7],
335 );
336 });
337
338 it("keeps a CRLF Codex reducer line whose marker straddles a stream chunk", async () => {
339 const path = NodePath.join(dir, "rollout.jsonl");
340 const crlf = (line: string) => line.replace("\n", "\r\n");
341 const modelLine = crlf(codexModelLine("gpt-5.2-codex"));
342 const head = crlf(codexMetaLine());
343 const fillerBytes =
344 256 * 1024 - Buffer.byteLength(head) - modelLine.indexOf("turn_context") - 4;
345 const fillerEnvelope = crlf(`${JSON.stringify({ type: "response_item", output: "" })}\n`);
346 const padding = "é".repeat((fillerBytes - Buffer.byteLength(fillerEnvelope)) / 2);
347 const filler = crlf(`${JSON.stringify({ type: "response_item", output: padding })}\n`);
348 const content = head + filler + modelLine + crlf(codexUsageLine(40, 2));
349 await NodeFSP.writeFile(path, content);
350
351 const result = await readTranscriptRecords(path, TEST_FORMATS.codex);
352 assert.isNotNull(result);
353 assert.strictEqual(result.records.length, 1);
354 assert.strictEqual(result.records[0]?.model, "gpt-5.2-codex");
355 assert.strictEqual(result.records[0]?.sessionId, "codex-session-1");
356 assert.strictEqual(result.position.resumeOffset, Buffer.byteLength(content));
357 });
358});
359
360describe("transcriptLineGate", () => {
361 const gates = {
362 one: transcriptLineGate(['"usage"']),
363 several: transcriptLineGate(['"token_count"', '"session_meta"', '"a.b(c)"']),
364 };
365 const markers = { one: ['"usage"'], several: ['"token_count"', '"session_meta"', '"a.b(c)"'] };
366
367 it("matches markers beside multi-byte and malformed UTF-8", () => {
368 const invalid = Buffer.from([0xff, 0xc3]);
369 for (const kind of ["one", "several"] as const) {
370 for (const marker of markers[kind]) {
371 assert.isTrue(gates[kind](Buffer.from(`{"text":"日本語 é",${marker}:1}`)));
372 assert.isTrue(gates[kind](Buffer.concat([invalid, Buffer.from(marker), invalid])));
373 assert.isFalse(gates[kind](Buffer.from(`{"text":"日本語 é ${marker.slice(1, -1)}"}`)));
374 }
375 }
376 });
377});