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 re-emits an unchanged token_count on stream boundaries; the copy
192 // lands after the resume point and must still be dropped.
193 await NodeFSP.appendFile(path, codexUsageLine(9, 5) + codexUsageLine(21, 8));
194 const second = await readTranscriptRecords(path, TEST_FORMATS.codex, first.position);
195 assert.isNotNull(second);
196 assert.isTrue(second.resumed);
197 assert.deepStrictEqual(
198 second.records.map((record) => record.totals.outputTokens),
199 [21],
200 );
201 });
202
203 it("defers an unterminated trailing line to tailRecords, then consumes it once terminated", async () => {
204 const path = NodePath.join(dir, "claude.jsonl");
205 const unterminated = claudeLine(2, 7).trimEnd();
206 await NodeFSP.writeFile(path, claudeLine(1, 5) + unterminated);
207 const first = await readTranscriptRecords(path, TEST_FORMATS.claude);
208 assert.isNotNull(first);
209 assert.strictEqual(first.records.length, 1);
210 assert.strictEqual(first.tailRecords.length, 1);
211 assert.strictEqual(first.tailRecords[0]?.totals.outputTokens, 7);
212
213 await NodeFSP.appendFile(path, `\n${claudeLine(3, 11)}`);
214 const second = await readTranscriptRecords(path, TEST_FORMATS.claude, first.position);
215 assert.isNotNull(second);
216 assert.isTrue(second.resumed);
217 assert.deepStrictEqual(
218 second.records.map((record) => record.totals.outputTokens),
219 [7, 11],
220 );
221 assert.strictEqual(second.tailRecords.length, 0);
222 });
223
224 it("re-parses from the start when the guard bytes no longer match", async () => {
225 const path = NodePath.join(dir, "claude.jsonl");
226 await NodeFSP.writeFile(path, claudeLine(1, 5));
227 const first = await readTranscriptRecords(path, TEST_FORMATS.claude);
228 assert.isNotNull(first);
229
230 await NodeFSP.writeFile(path, claudeLine(4, 13) + claudeLine(5, 17));
231 const second = await readTranscriptRecords(path, TEST_FORMATS.claude, first.position);
232 assert.isNotNull(second);
233 assert.isFalse(second.resumed);
234 assert.deepStrictEqual(
235 second.records.map((record) => record.totals.outputTokens),
236 [13, 17],
237 );
238 });
239
240 it("re-parses from the start when the file shrank below the resume point", async () => {
241 const path = NodePath.join(dir, "claude.jsonl");
242 await NodeFSP.writeFile(path, claudeLine(1, 5) + claudeLine(2, 7));
243 const first = await readTranscriptRecords(path, TEST_FORMATS.claude);
244 assert.isNotNull(first);
245
246 await NodeFSP.writeFile(path, claudeLine(3, 11));
247 const second = await readTranscriptRecords(path, TEST_FORMATS.claude, first.position);
248 assert.isNotNull(second);
249 assert.isFalse(second.resumed);
250 assert.deepStrictEqual(
251 second.records.map((record) => record.totals.outputTokens),
252 [11],
253 );
254 });
255
256 it("parses a line larger than one stream chunk", async () => {
257 const path = NodePath.join(dir, "claude.jsonl");
258 const bigLine = `${JSON.stringify({
259 type: "assistant",
260 timestamp: "2026-08-01T10:00:00Z",
261 requestId: "req_big",
262 sessionId: "session-1",
263 padding: "x".repeat(512 * 1024),
264 message: {
265 id: "msg_big",
266 model: "claude-fable-5",
267 usage: { input_tokens: 10, output_tokens: 42 },
268 },
269 })}\n`;
270 await NodeFSP.writeFile(path, bigLine + claudeLine(2, 7));
271
272 const parsed = await readTranscriptRecords(path, TEST_FORMATS.claude);
273 assert.isNotNull(parsed);
274 assert.deepStrictEqual(
275 parsed.records.map((record) => record.totals.outputTokens),
276 [42, 7],
277 );
278 });
279
280 it("keeps a CRLF Codex reducer line whose marker straddles a stream chunk", async () => {
281 const path = NodePath.join(dir, "rollout.jsonl");
282 const crlf = (line: string) => line.replace("\n", "\r\n");
283 const modelLine = crlf(codexModelLine("gpt-5.2-codex"));
284 const head = crlf(codexMetaLine());
285 const fillerBytes =
286 256 * 1024 - Buffer.byteLength(head) - modelLine.indexOf("turn_context") - 4;
287 const fillerEnvelope = crlf(`${JSON.stringify({ type: "response_item", output: "" })}\n`);
288 const padding = "é".repeat((fillerBytes - Buffer.byteLength(fillerEnvelope)) / 2);
289 const filler = crlf(`${JSON.stringify({ type: "response_item", output: padding })}\n`);
290 const content = head + filler + modelLine + crlf(codexUsageLine(40, 2));
291 await NodeFSP.writeFile(path, content);
292
293 const result = await readTranscriptRecords(path, TEST_FORMATS.codex);
294 assert.isNotNull(result);
295 assert.strictEqual(result.records.length, 1);
296 assert.strictEqual(result.records[0]?.model, "gpt-5.2-codex");
297 assert.strictEqual(result.records[0]?.sessionId, "codex-session-1");
298 assert.strictEqual(result.position.resumeOffset, Buffer.byteLength(content));
299 });
300
301 it("returns null for an unreadable file", async () => {
302 assert.isNull(
303 await readTranscriptRecords(NodePath.join(dir, "missing.jsonl"), TEST_FORMATS.claude),
304 );
305 });
306});
307
308describe("transcriptLineGate", () => {
309 const gates = {
310 one: transcriptLineGate(['"usage"']),
311 several: transcriptLineGate(['"token_count"', '"session_meta"', '"a.b(c)"']),
312 };
313 const markers = { one: ['"usage"'], several: ['"token_count"', '"session_meta"', '"a.b(c)"'] };
314
315 it("passes only lines containing one of its markers", () => {
316 for (const kind of ["one", "several"] as const) {
317 for (const marker of markers[kind]) {
318 assert.isTrue(gates[kind](Buffer.from(`{"payload":{${marker}:1}}`)));
319 assert.isFalse(gates[kind](Buffer.from(`{"text":"see ${marker.slice(1, -1)} here"}`)));
320 assert.isFalse(gates[kind](Buffer.from(`{${marker.replace(/[._]|usage/, "x")}:1}`)));
321 }
322 assert.isFalse(gates[kind](Buffer.alloc(0)));
323 }
324 });
325
326 it("matches markers beside multi-byte and malformed UTF-8", () => {
327 const invalid = Buffer.from([0xff, 0xc3]);
328 for (const kind of ["one", "several"] as const) {
329 for (const marker of markers[kind]) {
330 assert.isTrue(gates[kind](Buffer.from(`{"text":"日本語 é",${marker}:1}`)));
331 assert.isTrue(gates[kind](Buffer.concat([invalid, Buffer.from(marker), invalid])));
332 assert.isFalse(gates[kind](Buffer.from(`{"text":"日本語 é ${marker.slice(1, -1)}"}`)));
333 }
334 }
335 });
336});