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

usageTranscripts.test.ts

598 lines20.1 KB

1import { describe, expect, it } from "@effect/vitest";
2​
3import {
4 GROK_COST_USD_TICKS_PER_DOLLAR,
5 initialCodexScanState,
6 parseClaudeLine,
7 parseCodexLine,
8 parseGrokLine,
9 totalTokens,
10} from "./usageTranscripts.ts";
11​
12/** Shaped after a real Claude Code assistant record. */
13function claudeLine(overrides: {
14 messageId: string;
15 contentType: string;
16 model?: string;
17 outputTokens?: number;
18 speed?: string;
19}): string {
20 return JSON.stringify({
21 type: "assistant",
22 timestamp: "2026-08-07T04:05:13.944Z",
23 sessionId: "5a128faa-8253-489e-b935-6c08e8e670c0",
24 cwd: "/home/theo/project",
25 message: {
26 id: overrides.messageId,
27 role: "assistant",
28 model: overrides.model ?? "claude-fable-5",
29 content: [{ type: overrides.contentType }],
30 usage: {
31 input_tokens: 2,
32 cache_creation_input_tokens: 66818,
33 cache_read_input_tokens: 1000,
34 output_tokens: overrides.outputTokens ?? 286,
35 ...(overrides.speed === undefined ? {} : { speed: overrides.speed }),
36 },
37 },
38 });
40​
41describe("parseClaudeLine", () => {
42 it("extracts token totals and a dedupe key", () => {
43 const record = parseClaudeLine(claudeLine({ messageId: "msg_1", contentType: "text" }));
44​
45 expect(record).not.toBeNull();
46 expect(record?.provider).toBe("claude");
47 expect(record?.model).toBe("claude-fable-5");
48 expect(record?.totals).toEqual({
49 uncachedInputTokens: 2,
50 cachedInputTokens: 1000,
51 cacheCreationTokens: 66818,
52 outputTokens: 286,
53 reasoningTokens: 0,
54 });
55 expect(record?.dedupeKey).toBe("msg_1:");
56 expect(record?.speed).toBe("standard");
57 });
58​
59 it("marks fast-mode requests", () => {
60 const line = (speed: string) =>
61 parseClaudeLine(claudeLine({ messageId: "msg_1", contentType: "text", speed }));
62​
63 expect(line("fast")?.speed).toBe("fast");
64 expect(line("standard")?.speed).toBe("standard");
65 });
66​
67 it("gives every content block of one message the same dedupe key", () => {
68 // T3 Code writes one record per content block, each repeating the parent
69 // message's full usage. Summing them would overcount ~2.4x on real data.
70 const text = parseClaudeLine(claudeLine({ messageId: "msg_2", contentType: "text" }));
71 const toolUse = parseClaudeLine(claudeLine({ messageId: "msg_2", contentType: "tool_use" }));
72​
73 expect(text?.dedupeKey).toBe(toolUse?.dedupeKey);
74 expect(text?.totals).toEqual(toolUse?.totals);
75 });
76​
77 it("ignores records that are not assistant messages", () => {
78 expect(parseClaudeLine(JSON.stringify({ type: "user", message: {} }))).toBeNull();
79 expect(parseClaudeLine("not json")).toBeNull();
80 });
81});
82​
83describe("parseCodexLine", () => {
84 const sessionMeta = JSON.stringify({
85 type: "session_meta",
86 timestamp: "2026-08-01T05:17:41.289Z",
87 payload: { type: "session_meta", id: "019fbbc1-b12c-7360-a685-28c181f0025f" },
88 });
89 const turnContext = JSON.stringify({
90 type: "turn_context",
91 timestamp: "2026-08-01T05:17:42.694Z",
92 payload: { type: "turn_context", model: "gpt-5.6-sol" },
93 });
94 const tokenCount = (inputTokens: number, cached: number, output: number, reasoning: number) =>
95 JSON.stringify({
96 type: "event_msg",
97 timestamp: "2026-08-01T05:17:49.919Z",
98 payload: {
99 type: "token_count",
100 info: {
101 last_token_usage: {
102 input_tokens: inputTokens,
103 cached_input_tokens: cached,
104 cache_write_input_tokens: 0,
105 output_tokens: output,
106 reasoning_output_tokens: reasoning,
107 },
108 },
109 },
110 });
111​
112 it("attributes usage to the model from the preceding turn context", () => {
113 const state = initialCodexScanState();
114 parseCodexLine(sessionMeta, state);
115 parseCodexLine(turnContext, state);
116 const record = parseCodexLine(tokenCount(19239, 11008, 299, 116), state);
117​
118 expect(record?.provider).toBe("codex");
119 expect(record?.model).toBe("gpt-5.6-sol");
120 expect(record?.sessionId).toBe("019fbbc1-b12c-7360-a685-28c181f0025f");
121 // Codex reports input_tokens inclusive of the cached portion.
122 expect(record?.totals.uncachedInputTokens).toBe(19239 - 11008);
123 expect(record?.totals.cachedInputTokens).toBe(11008);
124 expect(record?.totals.reasoningTokens).toBe(116);
125 });
126​
127 it("skips a repeated token_count so deltas are not double counted", () => {
128 const state = initialCodexScanState();
129 parseCodexLine(turnContext, state);
130 const first = parseCodexLine(tokenCount(100, 0, 10, 0), state);
131 const repeat = parseCodexLine(tokenCount(100, 0, 10, 0), state);
132​
133 expect(first).not.toBeNull();
134 expect(repeat).toBeNull();
135 });
136​
137 it("drops usage that arrives before any model is known", () => {
138 const state = initialCodexScanState();
139 expect(parseCodexLine(tokenCount(100, 0, 10, 0), state)).toBeNull();
140 });
141​
142 it("does not let a pre-model event poison the duplicate signature", () => {
143 // A token_count before its turn_context is dropped; the identical event
144 // re-emitted once the model is known must still be counted.
145 const state = initialCodexScanState();
146 expect(parseCodexLine(tokenCount(100, 0, 10, 0), state)).toBeNull();
147 parseCodexLine(turnContext, state);
148 expect(parseCodexLine(tokenCount(100, 0, 10, 0), state)).not.toBeNull();
149 });
150​
151 it("carries the service tier from the latest thread settings", () => {
152 const settings = (thread_settings: Record<string, unknown>) =>
153 JSON.stringify({
154 type: "event_msg",
155 timestamp: "2026-08-01T05:17:42.000Z",
156 payload: { type: "thread_settings_applied", thread_settings },
157 });
158 const state = initialCodexScanState();
159 parseCodexLine(turnContext, state);
160 const speedAfter = (line: string, output: number) => {
161 parseCodexLine(line, state);
162 return parseCodexLine(tokenCount(100, 0, output, 0), state)?.speed;
163 };
164​
165 expect(parseCodexLine(tokenCount(100, 0, 1, 0), state)?.speed).toBe("standard");
166 expect(speedAfter(settings({ service_tier: "ultrafast" }), 2)).toBe("ultrafast");
167 expect(speedAfter(settings({ service_tier: "priority" }), 3)).toBe("fast");
168 // Codex omits the field when no tier was requested.
169 expect(speedAfter(settings({ model: "gpt-6-astra" }), 4)).toBe("standard");
170 });
171​
172 // A forked/subagent rollout opens with the parent's history copied in and
173 // every line re-stamped to the fork instant, then the ancestors' session
174 // metas. Counting those again multiplied usage ~1.85x on real data (#5758).
175 describe("forked rollouts", () => {
176 const meta = (overrides: {
177 id: string;
178 timestamp: string;
179 forkedFromId?: string;
180 spawnParentId?: string;
181 }) =>
182 JSON.stringify({
183 type: "session_meta",
184 timestamp: overrides.timestamp,
185 payload: {
186 type: "session_meta",
187 id: overrides.id,
188 ...(overrides.forkedFromId === undefined
189 ? {}
190 : { forked_from_id: overrides.forkedFromId }),
191 ...(overrides.spawnParentId === undefined
192 ? {}
193 : {
194 source: {
195 subagent: { thread_spawn: { parent_thread_id: overrides.spawnParentId } },
196 },
197 }),
198 },
199 });
200 const stamped = (timestamp: string, line: string) => {
201 const parsed = JSON.parse(line) as { timestamp: string };
202 parsed.timestamp = timestamp;
203 return JSON.stringify(parsed);
204 };
205​
206 it("keeps the child session id over copied ancestor metas", () => {
207 const state = initialCodexScanState();
208 parseCodexLine(meta({ id: "child", timestamp: "2026-08-01T05:00:00.000Z" }), state);
209 parseCodexLine(meta({ id: "parent", timestamp: "2026-08-01T05:00:00.000Z" }), state);
210 parseCodexLine(turnContext, state);
211 const record = parseCodexLine(tokenCount(100, 0, 10, 0), state);
212​
213 expect(record?.sessionId).toBe("child");
214 });
215​
216 it("drops the re-stamped copied burst and keeps the first real event", () => {
217 const state = initialCodexScanState();
218 const forkInstant = "2026-08-01T05:00:00.000Z";
219 parseCodexLine(meta({ id: "child", timestamp: forkInstant, forkedFromId: "parent" }), state);
220 parseCodexLine(meta({ id: "parent", timestamp: forkInstant }), state);
221 parseCodexLine(stamped(forkInstant, turnContext), state);
222​
223 // Copied history: written in one burst at the fork instant.
224 expect(
225 parseCodexLine(stamped("2026-08-01T05:00:00.001Z", tokenCount(100, 0, 10, 0)), state),
226 ).toBeNull();
227 expect(
228 parseCodexLine(stamped("2026-08-01T05:00:00.002Z", tokenCount(200, 0, 20, 0)), state),
229 ).toBeNull();
230​
231 // The child's first genuine turn lands seconds later and must count.
232 const real = parseCodexLine(
233 stamped("2026-08-01T05:00:06.000Z", tokenCount(300, 0, 30, 0)),
234 state,
235 );
236 expect(real).not.toBeNull();
237 expect(real?.totals.outputTokens).toBe(30);
238​
239 // Suppression never restarts, even for closely spaced later events.
240 const next = parseCodexLine(
241 stamped("2026-08-01T05:00:06.100Z", tokenCount(400, 0, 40, 0)),
242 state,
243 );
244 expect(next).not.toBeNull();
245 });
246​
247 it("recognizes subagent spawns without forked_from_id", () => {
248 const state = initialCodexScanState();
249 const spawnInstant = "2026-08-01T05:00:00.000Z";
250 parseCodexLine(
251 meta({ id: "child", timestamp: spawnInstant, spawnParentId: "parent" }),
252 state,
253 );
254 parseCodexLine(stamped(spawnInstant, turnContext), state);
255 expect(
256 parseCodexLine(stamped("2026-08-01T05:00:00.001Z", tokenCount(100, 0, 10, 0)), state),
257 ).toBeNull();
258 });
259​
260 it("does not suppress anything in a rollout that is not a fork", () => {
261 const state = initialCodexScanState();
262 parseCodexLine(meta({ id: "root", timestamp: "2026-08-01T05:00:00.000Z" }), state);
263 parseCodexLine(stamped("2026-08-01T05:00:00.100Z", turnContext), state);
264 const record = parseCodexLine(
265 stamped("2026-08-01T05:00:00.200Z", tokenCount(100, 0, 10, 0)),
266 state,
267 );
268 expect(record).not.toBeNull();
269 });
270 });
271});
272​
273describe("totalTokens", () => {
274 it("does not add reasoning on top of output", () => {
275 expect(
276 totalTokens({
277 uncachedInputTokens: 10,
278 cachedInputTokens: 20,
279 cacheCreationTokens: 30,
280 outputTokens: 40,
281 reasoningTokens: 25,
282 }),
283 ).toBe(100);
284 });
285});
286​
287describe("parseGrokLine", () => {
288 /** Shaped after a real Grok Build `turn_completed` session update. */
289 function turnCompleted(overrides?: {
290 sessionId?: string;
291 promptId?: string;
292 timestamp?: number;
293 agentTimestampMs?: number;
294 usage?: Record<string, unknown>;
295 modelUsage?: Record<string, Record<string, unknown>> | null;
296 }): string {
297 const modelUsage =
298 overrides && "modelUsage" in overrides
299 ? overrides.modelUsage
300 : {
301 "grok-4.5-build": {
302 inputTokens: 20_272,
303 outputTokens: 272,
304 totalTokens: 20_544,
305 cachedReadTokens: 11_264,
306 cacheCreationTokens: 0,
307 reasoningTokens: 180,
308 costUsdTicks: 230_272_000,
309 },
310 };
311​
312 return JSON.stringify({
313 timestamp: overrides?.timestamp ?? 1_786_372_566,
314 method: "_x.ai/session/update",
315 params: {
316 sessionId: overrides?.sessionId ?? "019fec1a-12f7-72f2-9b1f-7778a00aea3c",
317 update: {
318 sessionUpdate: "turn_completed",
319 prompt_id: overrides?.promptId ?? "prompt-1",
320 stop_reason: "end_turn",
321 usage: {
322 inputTokens: 20_272,
323 outputTokens: 272,
324 totalTokens: 20_544,
325 cachedReadTokens: 11_264,
326 cacheCreationTokens: 0,
327 reasoningTokens: 180,
328 costUsdTicks: 230_272_000,
329 ...(modelUsage === null ? {} : { modelUsage }),
330 ...overrides?.usage,
331 },
332 },
333 _meta: {
334 eventId: "event-1",
335 agentTimestampMs: overrides?.agentTimestampMs ?? 1_786_372_566_485,
336 },
337 },
338 });
339 }
340​
341 it("extracts per-model totals and provider-reported cost ticks", () => {
342 const records = parseGrokLine(turnCompleted());
343​
344 expect(records).toHaveLength(1);
345 const [record] = records;
346 expect(record?.provider).toBe("grok");
347 expect(record?.model).toBe("grok-4.5-build");
348 expect(record?.sessionId).toBe("019fec1a-12f7-72f2-9b1f-7778a00aea3c");
349 expect(record?.timestampMs).toBe(1_786_372_566_485);
350 expect(record?.totals).toEqual({
351 uncachedInputTokens: 20_272 - 11_264,
352 cachedInputTokens: 11_264,
353 cacheCreationTokens: 0,
354 outputTokens: 272,
355 reasoningTokens: 180,
356 });
357 expect(record?.reportedCostUsd).toBeCloseTo(230_272_000 / GROK_COST_USD_TICKS_PER_DOLLAR, 12);
358 expect(record?.dedupeKey).toBe("019fec1a-12f7-72f2-9b1f-7778a00aea3c:prompt-1:grok-4.5-build");
359 });
360​
361 it("emits one record per model when modelUsage has several entries", () => {
362 const records = parseGrokLine(
363 turnCompleted({
364 modelUsage: {
365 "grok-4.5": {
366 inputTokens: 1000,
367 outputTokens: 50,
368 cachedReadTokens: 400,
369 reasoningTokens: 20,
370 costUsdTicks: 50_000_000,
371 },
372 "grok-composer-2.5-fast": {
373 inputTokens: 200,
374 outputTokens: 30,
375 cachedReadTokens: 100,
376 reasoningTokens: 0,
377 costUsdTicks: 10_000_000,
378 },
379 },
380 }),
381 );
382​
383 expect(records.map((record) => record.model).toSorted()).toEqual([
384 "grok-4.5",
385 "grok-composer-2.5-fast",
386 ]);
387 expect(records.every((record) => record.provider === "grok")).toBe(true);
388 expect(records.find((record) => record.model === "grok-4.5")?.reportedCostUsd).toBeCloseTo(
389 0.005,
390 12,
391 );
392 });
393​
394 it("inherits top-level cost ticks for a single model without its own ticks", () => {
395 const records = parseGrokLine(
396 turnCompleted({
397 modelUsage: {
398 "grok-4.5-build": {
399 inputTokens: 1000,
400 outputTokens: 10,
401 cachedReadTokens: 0,
402 reasoningTokens: 0,
403 },
404 },
405 usage: { costUsdTicks: GROK_COST_USD_TICKS_PER_DOLLAR },
406 }),
407 );
408​
409 expect(records).toHaveLength(1);
410 expect(records[0]?.reportedCostUsd).toBe(1);
411 });
412​
413 it("falls back to a generic grok model when modelUsage is absent", () => {
414 const records = parseGrokLine(turnCompleted({ modelUsage: null }));
415​
416 expect(records).toHaveLength(1);
417 const [record] = records;
418 expect(record?.provider).toBe("grok");
419 expect(record?.model).toBe("grok");
420 expect(record?.totals).toEqual({
421 uncachedInputTokens: 20_272 - 11_264,
422 cachedInputTokens: 11_264,
423 cacheCreationTokens: 0,
424 outputTokens: 272,
425 reasoningTokens: 180,
426 });
427 expect(record?.reportedCostUsd).toBeCloseTo(230_272_000 / GROK_COST_USD_TICKS_PER_DOLLAR, 12);
428 expect(record?.dedupeKey).toBe("019fec1a-12f7-72f2-9b1f-7778a00aea3c:prompt-1:grok");
429 });
430​
431 it("pro-rates top-level cost ticks across multi-model turns without per-model ticks", () => {
432 const records = parseGrokLine(
433 turnCompleted({
434 modelUsage: {
435 "grok-4.5": {
436 inputTokens: 300,
437 outputTokens: 0,
438 cachedReadTokens: 0,
439 reasoningTokens: 0,
440 },
441 "grok-composer-2.5-fast": {
442 inputTokens: 100,
443 outputTokens: 0,
444 cachedReadTokens: 0,
445 reasoningTokens: 0,
446 },
447 },
448 usage: { costUsdTicks: GROK_COST_USD_TICKS_PER_DOLLAR },
449 }),
450 );
451​
452 expect(records).toHaveLength(2);
453 const byModel = Object.fromEntries(records.map((record) => [record.model, record]));
454 expect(byModel["grok-4.5"]?.reportedCostUsd).toBeCloseTo(0.75, 12);
455 expect(byModel["grok-composer-2.5-fast"]?.reportedCostUsd).toBeCloseTo(0.25, 12);
456 const sum =
457 (byModel["grok-4.5"]?.reportedCostUsd ?? 0) +
458 (byModel["grok-composer-2.5-fast"]?.reportedCostUsd ?? 0);
459 expect(sum).toBeCloseTo(1, 12);
460 });
461​
462 it("pro-rates aggregate cost when a zero-token sibling carries costUsdTicks: 0", () => {
463 const records = parseGrokLine(
464 turnCompleted({
465 modelUsage: {
466 "grok-4.5": {
467 inputTokens: 300,
468 outputTokens: 0,
469 cachedReadTokens: 0,
470 reasoningTokens: 0,
471 },
472 "grok-composer-2.5-fast": {
473 inputTokens: 100,
474 outputTokens: 0,
475 cachedReadTokens: 0,
476 reasoningTokens: 0,
477 },
478 "empty-sibling": {
479 inputTokens: 0,
480 outputTokens: 0,
481 cachedReadTokens: 0,
482 reasoningTokens: 0,
483 costUsdTicks: 0,
484 },
485 },
486 usage: { costUsdTicks: GROK_COST_USD_TICKS_PER_DOLLAR },
487 }),
488 );
489​
490 expect(records).toHaveLength(2);
491 expect(records.every((record) => record.model !== "empty-sibling")).toBe(true);
492 const byModel = Object.fromEntries(records.map((record) => [record.model, record]));
493 expect(byModel["grok-4.5"]?.reportedCostUsd).toBeCloseTo(0.75, 12);
494 expect(byModel["grok-composer-2.5-fast"]?.reportedCostUsd).toBeCloseTo(0.25, 12);
495 const sum =
496 (byModel["grok-4.5"]?.reportedCostUsd ?? 0) +
497 (byModel["grok-composer-2.5-fast"]?.reportedCostUsd ?? 0);
498 expect(sum).toBeCloseTo(1, 12);
499 });
500​
501 it("allocates leftover aggregate ticks to models that omit per-model ticks", () => {
502 const records = parseGrokLine(
503 turnCompleted({
504 modelUsage: {
505 "grok-4.5": {
506 inputTokens: 300,
507 outputTokens: 0,
508 cachedReadTokens: 0,
509 reasoningTokens: 0,
510 costUsdTicks: 0.4 * GROK_COST_USD_TICKS_PER_DOLLAR,
511 },
512 "grok-composer-2.5-fast": {
513 inputTokens: 100,
514 outputTokens: 0,
515 cachedReadTokens: 0,
516 reasoningTokens: 0,
517 },
518 },
519 usage: { costUsdTicks: GROK_COST_USD_TICKS_PER_DOLLAR },
520 }),
521 );
522​
523 expect(records).toHaveLength(2);
524 const byModel = Object.fromEntries(records.map((record) => [record.model, record]));
525 expect(byModel["grok-4.5"]?.reportedCostUsd).toBeCloseTo(0.4, 12);
526 expect(byModel["grok-composer-2.5-fast"]?.reportedCostUsd).toBeCloseTo(0.6, 12);
527 const sum =
528 (byModel["grok-4.5"]?.reportedCostUsd ?? 0) +
529 (byModel["grok-composer-2.5-fast"]?.reportedCostUsd ?? 0);
530 expect(sum).toBeCloseTo(1, 12);
531 });
532​
533 it("does not invent a colliding dedupe key when prompt_id is missing", () => {
534 const line = JSON.stringify({
535 timestamp: 1_786_372_566,
536 method: "_x.ai/session/update",
537 params: {
538 sessionId: "s1",
539 update: {
540 sessionUpdate: "turn_completed",
541 usage: {
542 inputTokens: 10,
543 outputTokens: 2,
544 modelUsage: {
545 "grok-4.5": { inputTokens: 10, outputTokens: 2 },
546 },
547 },
548 },
549 },
550 });
551​
552 expect(parseGrokLine(line)[0]?.dedupeKey).toBeNull();
553 });
554​
555 it("ignores non-turn lines and empty usage", () => {
556 expect(parseGrokLine(JSON.stringify({ method: "session/update", params: {} }))).toEqual([]);
557 expect(parseGrokLine("not json")).toEqual([]);
558 expect(
559 parseGrokLine(
560 turnCompleted({
561 modelUsage: {
562 "grok-4.5-build": {
563 inputTokens: 0,
564 outputTokens: 0,
565 cachedReadTokens: 0,
566 reasoningTokens: 0,
567 costUsdTicks: 0,
568 },
569 },
570 }),
571 ),
572 ).toEqual([]);
573 });
574​
575 it("falls back to the outer unix-seconds timestamp when agent meta is missing", () => {
576 const line = JSON.stringify({
577 timestamp: 1_786_372_566,
578 method: "_x.ai/session/update",
579 params: {
580 sessionId: "s1",
581 update: {
582 sessionUpdate: "turn_completed",
583 prompt_id: "p1",
584 usage: {
585 inputTokens: 10,
586 outputTokens: 2,
587 modelUsage: {
588 "grok-4.5": { inputTokens: 10, outputTokens: 2 },
589 },
590 },
591 },
592 },
593 });
594​
595 const records = parseGrokLine(line);
596 expect(records[0]?.timestampMs).toBe(1_786_372_566_000);
597 });
598});