Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2
3import { codexUsageFormat, initialCodexScanState, parseCodexLine } from "./codexUsage.ts";
4
5describe("parseCodexLine", () => {
6 const sessionMeta = JSON.stringify({
7 type: "session_meta",
8 timestamp: "2026-08-01T05:17:41.289Z",
9 payload: { type: "session_meta", id: "019fbbc1-b12c-7360-a685-28c181f0025f" },
10 });
11 const turnContext = JSON.stringify({
12 type: "turn_context",
13 timestamp: "2026-08-01T05:17:42.694Z",
14 payload: { type: "turn_context", model: "gpt-5.6-sol" },
15 });
16 const tokenCount = (inputTokens: number, cached: number, output: number, reasoning: number) =>
17 JSON.stringify({
18 type: "event_msg",
19 timestamp: "2026-08-01T05:17:49.919Z",
20 payload: {
21 type: "token_count",
22 info: {
23 last_token_usage: {
24 input_tokens: inputTokens,
25 cached_input_tokens: cached,
26 cache_write_input_tokens: 0,
27 output_tokens: output,
28 reasoning_output_tokens: reasoning,
29 },
30 },
31 },
32 });
33 const counters = (input: number, output: number) => ({
34 input_tokens: input,
35 cached_input_tokens: 0,
36 cache_write_input_tokens: 0,
37 output_tokens: output,
38 reasoning_output_tokens: 0,
39 total_tokens: input + output,
40 });
41 const counted = (last: unknown, total?: unknown, extra = {}) =>
42 JSON.stringify({
43 type: "event_msg",
44 timestamp: "2026-08-01T05:17:49.919Z",
45 payload: {
46 type: "token_count",
47 info: { last_token_usage: last, total_token_usage: total, ...extra },
48 },
49 });
50
51 it("attributes usage to the model from the preceding turn context", () => {
52 const state = initialCodexScanState();
53 parseCodexLine(sessionMeta, state);
54 parseCodexLine(turnContext, state);
55 const record = parseCodexLine(tokenCount(19239, 11008, 299, 116), state);
56
57 expect(record?.provider).toBe("codex");
58 expect(record?.model).toBe("gpt-5.6-sol");
59 expect(record?.sessionId).toBe("019fbbc1-b12c-7360-a685-28c181f0025f");
60 expect(record?.totals.uncachedInputTokens).toBe(19239 - 11008);
61 expect(record?.totals.cachedInputTokens).toBe(11008);
62 expect(record?.totals.reasoningTokens).toBe(116);
63 });
64
65 it("skips a repeated token_count so deltas are not double counted", () => {
66 const state = initialCodexScanState();
67 parseCodexLine(turnContext, state);
68 const first = parseCodexLine(tokenCount(100, 0, 10, 0), state);
69 const repeat = parseCodexLine(tokenCount(100, 0, 10, 0), state);
70
71 expect(first).not.toBeNull();
72 expect(repeat).toBeNull();
73 });
74
75 it("does not consume counters before the model and timestamp are valid", () => {
76 const state = initialCodexScanState();
77 expect(parseCodexLine(tokenCount(100, 0, 10, 0), state)).toBeNull();
78 parseCodexLine(turnContext, state);
79 expect(parseCodexLine(tokenCount(100, 0, 10, 0), state)).not.toBeNull();
80
81 const cumulativeState = initialCodexScanState();
82 const line = counted(counters(100, 20), counters(100, 20));
83 expect(parseCodexLine(line, cumulativeState)).toBeNull();
84 parseCodexLine(turnContext, cumulativeState);
85 expect(
86 parseCodexLine(line.replace("2026-08-01T05:17:49.919Z", "invalid"), cumulativeState),
87 ).toBeNull();
88 expect(parseCodexLine(line, cumulativeState)?.totals.outputTokens).toBe(20);
89 expect(codexUsageFormat.readMalformedRecords?.(cumulativeState)).toBe(0);
90 });
91
92 it("ignores stale changed requests but counts equal requests when totals advance across contexts", () => {
93 const state = initialCodexScanState();
94 parseCodexLine(turnContext, state);
95 const request = counters(100, 20);
96 expect(parseCodexLine(counted(request, request), state)?.totals.outputTokens).toBe(20);
97 expect(parseCodexLine(counted(counters(20, 5), request), state)).toBeNull();
98 expect(
99 parseCodexLine(
100 counted({ ...counters(0, 0), total_tokens: 20330 }, request, {
101 model_context_window: 258400,
102 }),
103 state,
104 ),
105 ).toBeNull();
106 expect(parseCodexLine(counted(request, counters(200, 40)), state)?.totals.outputTokens).toBe(
107 20,
108 );
109
110 for (const [index, tier] of ["priority", "ultrafast"].entries()) {
111 parseCodexLine(
112 JSON.stringify({ type: "turn_context", payload: { model: "gpt-6-astra" } }),
113 state,
114 );
115 parseCodexLine(
116 JSON.stringify({
117 type: "event_msg",
118 payload: { type: "thread_settings_applied", thread_settings: { service_tier: tier } },
119 }),
120 state,
121 );
122 const record = parseCodexLine(
123 counted(request, counters(100 * (index + 3), 20 * (index + 3))),
124 state,
125 );
126 expect(record).toMatchObject({
127 model: "gpt-6-astra",
128 speed: tier === "priority" ? "fast" : "ultrafast",
129 totals: { uncachedInputTokens: 100, outputTokens: 20 },
130 });
131 }
132 expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0);
133 });
134
135 it.each([false, true])(
136 "does not rebill legacy requests or drop the next cumulative delta (initial cumulative=%s)",
137 (initialCumulative) => {
138 const state = initialCodexScanState();
139 parseCodexLine(turnContext, state);
140 const first = counters(100, 20);
141 expect(
142 parseCodexLine(counted(first, initialCumulative ? first : undefined), state)?.totals
143 .outputTokens,
144 ).toBe(20);
145 expect(parseCodexLine(counted(first), state)).toBeNull();
146 expect(parseCodexLine(counted(counters(20, 5)), state)?.totals.outputTokens).toBe(5);
147 expect(parseCodexLine(counted(counters(20, 5), counters(120, 25)), state)).toBeNull();
148 expect(
149 parseCodexLine(counted(counters(10, 2), counters(130, 27)), state)?.totals.outputTokens,
150 ).toBe(2);
151 expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0);
152 },
153 );
154
155 it("checks every cumulative component and recovers using an inconsistent pair's valid baseline", () => {
156 const request = {
157 ...counters(100, 20),
158 cached_input_tokens: 30,
159 cache_write_input_tokens: 10,
160 reasoning_output_tokens: 5,
161 };
162 const fields = Object.keys(request) as (keyof typeof request)[];
163 for (const field of fields) {
164 const state = initialCodexScanState();
165 parseCodexLine(turnContext, state);
166 expect(parseCodexLine(counted(request, request), state)?.totals).toEqual({
167 uncachedInputTokens: 60,
168 cachedInputTokens: 30,
169 cacheCreationTokens: 10,
170 outputTokens: 20,
171 reasoningTokens: 5,
172 });
173 const total = { ...request };
174 for (const key of fields) total[key] *= 2;
175 total[field] += 1;
176 if (field === "input_tokens" || field === "output_tokens") total.total_tokens += 1;
177 expect(parseCodexLine(counted(request, total), state), field).toBeNull();
178 expect(codexUsageFormat.readMalformedRecords?.(state), field).toBe(1);
179 for (const key of fields) total[key] += request[key];
180 expect(parseCodexLine(counted(request, total), state)?.totals.outputTokens, field).toBe(20);
181 expect(codexUsageFormat.readMalformedRecords?.(state), field).toBe(1);
182 }
183 });
184
185 it.each(["continuation", "fork", "subagent"])(
186 "bills only the latest request when a %s has no initial counter baseline",
187 (source) => {
188 const state = initialCodexScanState();
189 parseCodexLine(
190 JSON.stringify({
191 type: "session_meta",
192 timestamp: "2026-08-01T05:17:41.000Z",
193 payload: {
194 id: "child",
195 model_provider: "openai",
196 ...(source === "fork" ? { forked_from_id: "parent" } : {}),
197 ...(source === "subagent"
198 ? { source: { subagent: { thread_spawn: { parent_thread_id: "parent" } } } }
199 : { source: "vscode" }),
200 },
201 }),
202 state,
203 );
204 parseCodexLine(turnContext, state);
205 const request = {
206 ...counters(100, 20),
207 cached_input_tokens: 30,
208 cache_write_input_tokens: 10,
209 reasoning_output_tokens: 5,
210 };
211 const cumulative = {
212 ...counters(500, 60),
213 cached_input_tokens: 200,
214 cache_write_input_tokens: 20,
215 reasoning_output_tokens: 15,
216 };
217 const first = counted(request, cumulative);
218 expect(parseCodexLine(first, state)).toMatchObject({
219 sessionId: "child",
220 totals: {
221 uncachedInputTokens: 60,
222 cachedInputTokens: 30,
223 cacheCreationTokens: 10,
224 outputTokens: 20,
225 reasoningTokens: 5,
226 },
227 });
228 expect(parseCodexLine(first, state)).toBeNull();
229 expect(parseCodexLine(counted(counters(10, 2), cumulative), state)).toBeNull();
230 expect(
231 parseCodexLine(
232 counted(counters(10, 2), {
233 ...cumulative,
234 input_tokens: 510,
235 output_tokens: 62,
236 total_tokens: 572,
237 }),
238 state,
239 )?.totals.outputTokens,
240 ).toBe(2);
241 expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0);
242 },
243 );
244
245 it.each([
246 {
247 ...counters(90, 40),
248 cached_input_tokens: 60,
249 cache_write_input_tokens: 20,
250 reasoning_output_tokens: 10,
251 },
252 {
253 ...counters(200, 10),
254 cached_input_tokens: 60,
255 cache_write_input_tokens: 20,
256 reasoning_output_tokens: 5,
257 },
258 {
259 ...counters(200, 40),
260 cached_input_tokens: 20,
261 cache_write_input_tokens: 20,
262 reasoning_output_tokens: 10,
263 },
264 {
265 ...counters(200, 40),
266 cached_input_tokens: 60,
267 cache_write_input_tokens: 5,
268 reasoning_output_tokens: 10,
269 },
270 {
271 ...counters(200, 40),
272 cached_input_tokens: 60,
273 cache_write_input_tokens: 20,
274 reasoning_output_tokens: 3,
275 },
276 {
277 ...counters(110, 40),
278 cached_input_tokens: 60,
279 cache_write_input_tokens: 20,
280 reasoning_output_tokens: 10,
281 },
282 {
283 ...counters(200, 30),
284 cached_input_tokens: 60,
285 cache_write_input_tokens: 20,
286 reasoning_output_tokens: 20,
287 },
288 ])("rejects an initial snapshot with an impossible inherited baseline: %j", (cumulative) => {
289 const state = initialCodexScanState();
290 parseCodexLine(turnContext, state);
291 const request = {
292 ...counters(100, 20),
293 cached_input_tokens: 30,
294 cache_write_input_tokens: 10,
295 reasoning_output_tokens: 5,
296 };
297 expect(parseCodexLine(counted(request, cumulative), state)).toBeNull();
298 expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(1);
299 expect(state.lastCumulativeUsage).toEqual(cumulative);
300 });
301
302 it.each(["request", "cumulative"])("skips malformed %s counters and recovers", (malformed) => {
303 const state = initialCodexScanState();
304 parseCodexLine(turnContext, state);
305 const request = counters(100, 20);
306 parseCodexLine(counted(request, request), state);
307 expect(
308 parseCodexLine(
309 counted(
310 malformed === "request" ? { ...request, cached_input_tokens: -1 } : request,
311 malformed === "cumulative"
312 ? { ...counters(200, 40), output_tokens: "40" }
313 : counters(200, 40),
314 ),
315 state,
316 ),
317 ).toBeNull();
318 expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(1);
319 expect(
320 parseCodexLine(
321 counted(request, malformed === "request" ? counters(300, 60) : counters(200, 40)),
322 state,
323 )?.totals.outputTokens,
324 ).toBe(20);
325 expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(1);
326 });
327
328 it("does not bill a context-window estimate or lose the following real request", () => {
329 const state = initialCodexScanState();
330 parseCodexLine(turnContext, state);
331 parseCodexLine(counted(counters(100, 20), counters(100, 20)), state);
332 const estimate = { ...counters(0, 0), total_tokens: 1000 };
333 expect(
334 parseCodexLine(
335 counted({ ...estimate, total_tokens: 880 }, estimate, { model_context_window: 1000 }),
336 state,
337 ),
338 ).toBeNull();
339 expect(
340 parseCodexLine(counted(counters(10, 2), { ...counters(10, 2), total_tokens: 1012 }), state)
341 ?.totals.outputTokens,
342 ).toBe(2);
343 expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0);
344 });
345
346 it.each([false, true])(
347 "accepts the post-compaction context marker without a malformed record (prior request: %s)",
348 (priorRequest) => {
349 const state = initialCodexScanState();
350 parseCodexLine(turnContext, state);
351 if (priorRequest) parseCodexLine(counted(counters(100, 20), counters(100, 20)), state);
352 const marker = counted({ ...counters(0, 0), total_tokens: 26387 }, counters(0, 0), {
353 model_context_window: 475000,
354 });
355 expect(parseCodexLine(marker, state)).toBeNull();
356 expect(
357 parseCodexLine(counted(counters(30, 5), counters(30, 5)), state)?.totals.outputTokens,
358 ).toBe(5);
359 expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0);
360 },
361 );
362
363 it("bills the first request after a resume restarts the cumulative counters", () => {
364 const state = initialCodexScanState();
365 parseCodexLine(turnContext, state);
366 parseCodexLine(counted(counters(100, 20), counters(100, 20)), state);
367 expect(
368 parseCodexLine(counted(counters(30, 5), counters(30, 5)), state)?.totals.outputTokens,
369 ).toBe(5);
370 expect(
371 parseCodexLine(counted(counters(10, 2), counters(40, 7)), state)?.totals.outputTokens,
372 ).toBe(2);
373 expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0);
374 });
375
376 it("retains initial tier evidence only for the own OpenAI session and exact context until native settings arrive", () => {
377 const meta = (id: string, model_provider?: string) =>
378 JSON.stringify({ type: "session_meta", payload: { id, model_provider } });
379 const context = (turn_id?: string, model?: string) =>
380 JSON.stringify({ type: "turn_context", payload: { turn_id, model } });
381 for (const provider of ["openai", "t3", "custom", undefined]) {
382 const state = initialCodexScanState();
383 parseCodexLine(meta("own-session", provider), state);
384 parseCodexLine(meta("ancestor", provider === "openai" ? "custom" : "openai"), state);
385 parseCodexLine(context("first-turn", "gpt-6-astra"), state);
386 const first = parseCodexLine(tokenCount(100, 0, 1, 0), state);
387 expect(first).toMatchObject({
388 sessionId: "own-session",
389 model: "gpt-6-astra",
390 speed: "standard",
391 });
392 if (provider === "openai") {
393 expect(first).toHaveProperty("unresolvedServiceTierTurnId", "first-turn");
394 } else {
395 expect(first).not.toHaveProperty("unresolvedServiceTierTurnId");
396 }
397
398 parseCodexLine(context(undefined, "gpt-6-astra"), state);
399 expect(parseCodexLine(tokenCount(100, 0, 2, 0), state)).not.toHaveProperty(
400 "unresolvedServiceTierTurnId",
401 );
402 parseCodexLine(context("missing-model"), state);
403 expect(parseCodexLine(tokenCount(100, 0, 3, 0), state)).not.toHaveProperty(
404 "unresolvedServiceTierTurnId",
405 );
406 parseCodexLine(context("next-turn", "gpt-6-astra"), state);
407 const next = parseCodexLine(tokenCount(100, 0, 4, 0), state);
408 if (provider === "openai") {
409 expect(next).toHaveProperty("unresolvedServiceTierTurnId", "next-turn");
410 } else {
411 expect(next).not.toHaveProperty("unresolvedServiceTierTurnId");
412 }
413 }
414
415 for (const service_tier of ["standard", "", undefined, "priority", "ultrafast"]) {
416 const state = initialCodexScanState();
417 parseCodexLine(meta("own-session", "openai"), state);
418 parseCodexLine(context("first-turn", "gpt-6-astra"), state);
419 expect(parseCodexLine(tokenCount(100, 0, 1, 0), state)).toHaveProperty(
420 "unresolvedServiceTierTurnId",
421 "first-turn",
422 );
423 parseCodexLine(
424 JSON.stringify({
425 type: "event_msg",
426 payload: { type: "thread_settings_applied", thread_settings: { service_tier } },
427 }),
428 state,
429 );
430 for (const output of [2, 3]) {
431 parseCodexLine(context(`native-turn-${output}`, "gpt-6-astra"), state);
432 const record = parseCodexLine(tokenCount(100, 0, output, 0), state);
433 expect(record?.speed).toBe(
434 service_tier === "priority"
435 ? "fast"
436 : service_tier === "ultrafast"
437 ? "ultrafast"
438 : "standard",
439 );
440 expect(record).not.toHaveProperty("unresolvedServiceTierTurnId");
441 }
442 }
443 });
444
445 // A forked/subagent rollout opens with the parent's history copied in and
446 // every line re-stamped to the fork instant, then the ancestors' session
447 // metas. Counting those again multiplied usage ~1.85x on real data (#5758).
448 describe("forked rollouts", () => {
449 const meta = (overrides: {
450 id: string;
451 timestamp: string;
452 forkedFromId?: string;
453 spawnParentId?: string;
454 }) =>
455 JSON.stringify({
456 type: "session_meta",
457 timestamp: overrides.timestamp,
458 payload: {
459 type: "session_meta",
460 id: overrides.id,
461 ...(overrides.forkedFromId === undefined
462 ? {}
463 : { forked_from_id: overrides.forkedFromId }),
464 ...(overrides.spawnParentId === undefined
465 ? {}
466 : {
467 source: {
468 subagent: { thread_spawn: { parent_thread_id: overrides.spawnParentId } },
469 },
470 }),
471 },
472 });
473 const stamped = (timestamp: string, line: string) => {
474 const parsed = JSON.parse(line) as { timestamp: string };
475 parsed.timestamp = timestamp;
476 return JSON.stringify(parsed);
477 };
478
479 it("drops the re-stamped copied burst and keeps the first real event", () => {
480 const state = initialCodexScanState();
481 const forkInstant = "2026-08-01T05:00:00.000Z";
482 parseCodexLine(meta({ id: "child", timestamp: forkInstant, forkedFromId: "parent" }), state);
483 parseCodexLine(meta({ id: "parent", timestamp: forkInstant }), state);
484 parseCodexLine(stamped(forkInstant, turnContext), state);
485
486 expect(
487 parseCodexLine(
488 stamped("2026-08-01T05:00:00.001Z", counted(counters(100, 10), counters(100, 10))),
489 state,
490 ),
491 ).toBeNull();
492 expect(
493 parseCodexLine(
494 stamped("2026-08-01T05:00:00.002Z", counted(counters(200, 20), counters(300, 30))),
495 state,
496 ),
497 ).toBeNull();
498
499 const real = parseCodexLine(
500 stamped("2026-08-01T05:00:06.000Z", counted(counters(200, 20), counters(500, 50))),
501 state,
502 );
503 expect(real).not.toBeNull();
504 expect(real?.sessionId).toBe("child");
505 expect(real?.totals.outputTokens).toBe(20);
506
507 const next = parseCodexLine(
508 stamped("2026-08-01T05:00:06.100Z", counted(counters(400, 40), counters(900, 90))),
509 state,
510 );
511 expect(next).not.toBeNull();
512 expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0);
513 });
514
515 it("recognizes subagent spawns without forked_from_id", () => {
516 const state = initialCodexScanState();
517 const spawnInstant = "2026-08-01T05:00:00.000Z";
518 parseCodexLine(
519 meta({ id: "child", timestamp: spawnInstant, spawnParentId: "parent" }),
520 state,
521 );
522 parseCodexLine(stamped(spawnInstant, turnContext), state);
523 expect(
524 parseCodexLine(stamped("2026-08-01T05:00:00.001Z", tokenCount(100, 0, 10, 0)), state),
525 ).toBeNull();
526 });
527
528 it("does not suppress anything in a rollout that is not a fork", () => {
529 const state = initialCodexScanState();
530 parseCodexLine(meta({ id: "root", timestamp: "2026-08-01T05:00:00.000Z" }), state);
531 parseCodexLine(stamped("2026-08-01T05:00:00.100Z", turnContext), state);
532 const record = parseCodexLine(
533 stamped("2026-08-01T05:00:00.200Z", tokenCount(100, 0, 10, 0)),
534 state,
535 );
536 expect(record).not.toBeNull();
537 });
538 });
539});