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(["request", "cumulative"])("skips malformed %s counters and recovers", (malformed) => {
186 const state = initialCodexScanState();
187 parseCodexLine(turnContext, state);
188 const request = counters(100, 20);
189 parseCodexLine(counted(request, request), state);
190 expect(
191 parseCodexLine(
192 counted(
193 malformed === "request" ? { ...request, cached_input_tokens: -1 } : request,
194 malformed === "cumulative"
195 ? { ...counters(200, 40), output_tokens: "40" }
196 : counters(200, 40),
197 ),
198 state,
199 ),
200 ).toBeNull();
201 expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(1);
202 expect(
203 parseCodexLine(
204 counted(request, malformed === "request" ? counters(300, 60) : counters(200, 40)),
205 state,
206 )?.totals.outputTokens,
207 ).toBe(20);
208 expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(1);
209 });
210
211 it("does not bill a context-window estimate or lose the following real request", () => {
212 const state = initialCodexScanState();
213 parseCodexLine(turnContext, state);
214 parseCodexLine(counted(counters(100, 20), counters(100, 20)), state);
215 const estimate = { ...counters(0, 0), total_tokens: 1000 };
216 expect(
217 parseCodexLine(
218 counted({ ...estimate, total_tokens: 880 }, estimate, { model_context_window: 1000 }),
219 state,
220 ),
221 ).toBeNull();
222 expect(
223 parseCodexLine(counted(counters(10, 2), { ...counters(10, 2), total_tokens: 1012 }), state)
224 ?.totals.outputTokens,
225 ).toBe(2);
226 expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0);
227 });
228
229 it.each([false, true])(
230 "accepts the post-compaction context marker without a malformed record (prior request: %s)",
231 (priorRequest) => {
232 const state = initialCodexScanState();
233 parseCodexLine(turnContext, state);
234 if (priorRequest) parseCodexLine(counted(counters(100, 20), counters(100, 20)), state);
235 const marker = counted({ ...counters(0, 0), total_tokens: 26387 }, counters(0, 0), {
236 model_context_window: 475000,
237 });
238 expect(parseCodexLine(marker, state)).toBeNull();
239 expect(
240 parseCodexLine(counted(counters(30, 5), counters(30, 5)), state)?.totals.outputTokens,
241 ).toBe(5);
242 expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0);
243 },
244 );
245
246 it("bills the first request after a resume restarts the cumulative counters", () => {
247 const state = initialCodexScanState();
248 parseCodexLine(turnContext, state);
249 parseCodexLine(counted(counters(100, 20), counters(100, 20)), state);
250 expect(
251 parseCodexLine(counted(counters(30, 5), counters(30, 5)), state)?.totals.outputTokens,
252 ).toBe(5);
253 expect(
254 parseCodexLine(counted(counters(10, 2), counters(40, 7)), state)?.totals.outputTokens,
255 ).toBe(2);
256 expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0);
257 });
258
259 it("retains initial tier evidence only for the own OpenAI session and exact context until native settings arrive", () => {
260 const meta = (id: string, model_provider?: string) =>
261 JSON.stringify({ type: "session_meta", payload: { id, model_provider } });
262 const context = (turn_id?: string, model?: string) =>
263 JSON.stringify({ type: "turn_context", payload: { turn_id, model } });
264 for (const provider of ["openai", "t3", "custom", undefined]) {
265 const state = initialCodexScanState();
266 parseCodexLine(meta("own-session", provider), state);
267 parseCodexLine(meta("ancestor", provider === "openai" ? "custom" : "openai"), state);
268 parseCodexLine(context("first-turn", "gpt-6-astra"), state);
269 const first = parseCodexLine(tokenCount(100, 0, 1, 0), state);
270 expect(first).toMatchObject({
271 sessionId: "own-session",
272 model: "gpt-6-astra",
273 speed: "standard",
274 });
275 if (provider === "openai") {
276 expect(first).toHaveProperty("unresolvedServiceTierTurnId", "first-turn");
277 } else {
278 expect(first).not.toHaveProperty("unresolvedServiceTierTurnId");
279 }
280
281 parseCodexLine(context(undefined, "gpt-6-astra"), state);
282 expect(parseCodexLine(tokenCount(100, 0, 2, 0), state)).not.toHaveProperty(
283 "unresolvedServiceTierTurnId",
284 );
285 parseCodexLine(context("missing-model"), state);
286 expect(parseCodexLine(tokenCount(100, 0, 3, 0), state)).not.toHaveProperty(
287 "unresolvedServiceTierTurnId",
288 );
289 parseCodexLine(context("next-turn", "gpt-6-astra"), state);
290 const next = parseCodexLine(tokenCount(100, 0, 4, 0), state);
291 if (provider === "openai") {
292 expect(next).toHaveProperty("unresolvedServiceTierTurnId", "next-turn");
293 } else {
294 expect(next).not.toHaveProperty("unresolvedServiceTierTurnId");
295 }
296 }
297
298 for (const service_tier of ["standard", "", undefined, "priority", "ultrafast"]) {
299 const state = initialCodexScanState();
300 parseCodexLine(meta("own-session", "openai"), state);
301 parseCodexLine(context("first-turn", "gpt-6-astra"), state);
302 expect(parseCodexLine(tokenCount(100, 0, 1, 0), state)).toHaveProperty(
303 "unresolvedServiceTierTurnId",
304 "first-turn",
305 );
306 parseCodexLine(
307 JSON.stringify({
308 type: "event_msg",
309 payload: { type: "thread_settings_applied", thread_settings: { service_tier } },
310 }),
311 state,
312 );
313 for (const output of [2, 3]) {
314 parseCodexLine(context(`native-turn-${output}`, "gpt-6-astra"), state);
315 const record = parseCodexLine(tokenCount(100, 0, output, 0), state);
316 expect(record?.speed).toBe(
317 service_tier === "priority"
318 ? "fast"
319 : service_tier === "ultrafast"
320 ? "ultrafast"
321 : "standard",
322 );
323 expect(record).not.toHaveProperty("unresolvedServiceTierTurnId");
324 }
325 }
326 });
327
328 // A forked/subagent rollout opens with the parent's history copied in and
329 // every line re-stamped to the fork instant, then the ancestors' session
330 // metas. Counting those again multiplied usage ~1.85x on real data (#5758).
331 describe("forked rollouts", () => {
332 const meta = (overrides: {
333 id: string;
334 timestamp: string;
335 forkedFromId?: string;
336 spawnParentId?: string;
337 }) =>
338 JSON.stringify({
339 type: "session_meta",
340 timestamp: overrides.timestamp,
341 payload: {
342 type: "session_meta",
343 id: overrides.id,
344 ...(overrides.forkedFromId === undefined
345 ? {}
346 : { forked_from_id: overrides.forkedFromId }),
347 ...(overrides.spawnParentId === undefined
348 ? {}
349 : {
350 source: {
351 subagent: { thread_spawn: { parent_thread_id: overrides.spawnParentId } },
352 },
353 }),
354 },
355 });
356 const stamped = (timestamp: string, line: string) => {
357 const parsed = JSON.parse(line) as { timestamp: string };
358 parsed.timestamp = timestamp;
359 return JSON.stringify(parsed);
360 };
361
362 it("drops the re-stamped copied burst and keeps the first real event", () => {
363 const state = initialCodexScanState();
364 const forkInstant = "2026-08-01T05:00:00.000Z";
365 parseCodexLine(meta({ id: "child", timestamp: forkInstant, forkedFromId: "parent" }), state);
366 parseCodexLine(meta({ id: "parent", timestamp: forkInstant }), state);
367 parseCodexLine(stamped(forkInstant, turnContext), state);
368
369 expect(
370 parseCodexLine(
371 stamped("2026-08-01T05:00:00.001Z", counted(counters(100, 10), counters(100, 10))),
372 state,
373 ),
374 ).toBeNull();
375 expect(
376 parseCodexLine(
377 stamped("2026-08-01T05:00:00.002Z", counted(counters(200, 20), counters(300, 30))),
378 state,
379 ),
380 ).toBeNull();
381
382 const real = parseCodexLine(
383 stamped("2026-08-01T05:00:06.000Z", counted(counters(200, 20), counters(500, 50))),
384 state,
385 );
386 expect(real).not.toBeNull();
387 expect(real?.sessionId).toBe("child");
388 expect(real?.totals.outputTokens).toBe(20);
389
390 const next = parseCodexLine(
391 stamped("2026-08-01T05:00:06.100Z", counted(counters(400, 40), counters(900, 90))),
392 state,
393 );
394 expect(next).not.toBeNull();
395 expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0);
396 });
397
398 it("recognizes subagent spawns without forked_from_id", () => {
399 const state = initialCodexScanState();
400 const spawnInstant = "2026-08-01T05:00:00.000Z";
401 parseCodexLine(
402 meta({ id: "child", timestamp: spawnInstant, spawnParentId: "parent" }),
403 state,
404 );
405 parseCodexLine(stamped(spawnInstant, turnContext), state);
406 expect(
407 parseCodexLine(stamped("2026-08-01T05:00:00.001Z", tokenCount(100, 0, 10, 0)), state),
408 ).toBeNull();
409 });
410
411 it("does not suppress anything in a rollout that is not a fork", () => {
412 const state = initialCodexScanState();
413 parseCodexLine(meta({ id: "root", timestamp: "2026-08-01T05:00:00.000Z" }), state);
414 parseCodexLine(stamped("2026-08-01T05:00:00.100Z", turnContext), state);
415 const record = parseCodexLine(
416 stamped("2026-08-01T05:00:00.200Z", tokenCount(100, 0, 10, 0)),
417 state,
418 );
419 expect(record).not.toBeNull();
420 });
421 });
422});