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

codexUsage.test.ts

427 lines16.5 KB

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("drops usage that arrives before any model is known", () => {
76 const state = initialCodexScanState();
77 expect(parseCodexLine(tokenCount(100, 0, 10, 0), state)).toBeNull();
78 });
79​
80 it("does not consume counters before the model and timestamp are valid", () => {
81 const state = initialCodexScanState();
82 expect(parseCodexLine(tokenCount(100, 0, 10, 0), state)).toBeNull();
83 parseCodexLine(turnContext, state);
84 expect(parseCodexLine(tokenCount(100, 0, 10, 0), state)).not.toBeNull();
85​
86 const cumulativeState = initialCodexScanState();
87 const line = counted(counters(100, 20), counters(100, 20));
88 expect(parseCodexLine(line, cumulativeState)).toBeNull();
89 parseCodexLine(turnContext, cumulativeState);
90 expect(
91 parseCodexLine(line.replace("2026-08-01T05:17:49.919Z", "invalid"), cumulativeState),
92 ).toBeNull();
93 expect(parseCodexLine(line, cumulativeState)?.totals.outputTokens).toBe(20);
94 expect(codexUsageFormat.readMalformedRecords?.(cumulativeState)).toBe(0);
95 });
96​
97 it("ignores stale changed requests but counts equal requests when totals advance across contexts", () => {
98 const state = initialCodexScanState();
99 parseCodexLine(turnContext, state);
100 const request = counters(100, 20);
101 expect(parseCodexLine(counted(request, request), state)?.totals.outputTokens).toBe(20);
102 expect(parseCodexLine(counted(counters(20, 5), request), state)).toBeNull();
103 expect(
104 parseCodexLine(
105 counted({ ...counters(0, 0), total_tokens: 20330 }, request, {
106 model_context_window: 258400,
107 }),
108 state,
109 ),
110 ).toBeNull();
111 expect(parseCodexLine(counted(request, counters(200, 40)), state)?.totals.outputTokens).toBe(
112 20,
113 );
114​
115 for (const [index, tier] of ["priority", "ultrafast"].entries()) {
116 parseCodexLine(
117 JSON.stringify({ type: "turn_context", payload: { model: "gpt-6-astra" } }),
118 state,
119 );
120 parseCodexLine(
121 JSON.stringify({
122 type: "event_msg",
123 payload: { type: "thread_settings_applied", thread_settings: { service_tier: tier } },
124 }),
125 state,
126 );
127 const record = parseCodexLine(
128 counted(request, counters(100 * (index + 3), 20 * (index + 3))),
129 state,
130 );
131 expect(record).toMatchObject({
132 model: "gpt-6-astra",
133 speed: tier === "priority" ? "fast" : "ultrafast",
134 totals: { uncachedInputTokens: 100, outputTokens: 20 },
135 });
136 }
137 expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0);
138 });
139​
140 it.each([false, true])(
141 "does not rebill legacy requests or drop the next cumulative delta (initial cumulative=%s)",
142 (initialCumulative) => {
143 const state = initialCodexScanState();
144 parseCodexLine(turnContext, state);
145 const first = counters(100, 20);
146 expect(
147 parseCodexLine(counted(first, initialCumulative ? first : undefined), state)?.totals
148 .outputTokens,
149 ).toBe(20);
150 expect(parseCodexLine(counted(first), state)).toBeNull();
151 expect(parseCodexLine(counted(counters(20, 5)), state)?.totals.outputTokens).toBe(5);
152 expect(parseCodexLine(counted(counters(20, 5), counters(120, 25)), state)).toBeNull();
153 expect(
154 parseCodexLine(counted(counters(10, 2), counters(130, 27)), state)?.totals.outputTokens,
155 ).toBe(2);
156 expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0);
157 },
158 );
159​
160 it("checks every cumulative component and recovers using an inconsistent pair's valid baseline", () => {
161 const request = {
162 ...counters(100, 20),
163 cached_input_tokens: 30,
164 cache_write_input_tokens: 10,
165 reasoning_output_tokens: 5,
166 };
167 const fields = Object.keys(request) as (keyof typeof request)[];
168 for (const field of fields) {
169 const state = initialCodexScanState();
170 parseCodexLine(turnContext, state);
171 expect(parseCodexLine(counted(request, request), state)?.totals).toEqual({
172 uncachedInputTokens: 60,
173 cachedInputTokens: 30,
174 cacheCreationTokens: 10,
175 outputTokens: 20,
176 reasoningTokens: 5,
177 });
178 const total = { ...request };
179 for (const key of fields) total[key] *= 2;
180 total[field] += 1;
181 if (field === "input_tokens" || field === "output_tokens") total.total_tokens += 1;
182 expect(parseCodexLine(counted(request, total), state), field).toBeNull();
183 expect(codexUsageFormat.readMalformedRecords?.(state), field).toBe(1);
184 for (const key of fields) total[key] += request[key];
185 expect(parseCodexLine(counted(request, total), state)?.totals.outputTokens, field).toBe(20);
186 expect(codexUsageFormat.readMalformedRecords?.(state), field).toBe(1);
187 }
188 });
189​
190 it.each(["request", "cumulative"])("skips malformed %s counters and recovers", (malformed) => {
191 const state = initialCodexScanState();
192 parseCodexLine(turnContext, state);
193 const request = counters(100, 20);
194 parseCodexLine(counted(request, request), state);
195 expect(
196 parseCodexLine(
197 counted(
198 malformed === "request" ? { ...request, cached_input_tokens: -1 } : request,
199 malformed === "cumulative"
200 ? { ...counters(200, 40), output_tokens: "40" }
201 : counters(200, 40),
202 ),
203 state,
204 ),
205 ).toBeNull();
206 expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(1);
207 expect(
208 parseCodexLine(
209 counted(request, malformed === "request" ? counters(300, 60) : counters(200, 40)),
210 state,
211 )?.totals.outputTokens,
212 ).toBe(20);
213 expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(1);
214 });
215​
216 it("does not bill a context-window estimate or lose the following real request", () => {
217 const state = initialCodexScanState();
218 parseCodexLine(turnContext, state);
219 parseCodexLine(counted(counters(100, 20), counters(100, 20)), state);
220 const estimate = { ...counters(0, 0), total_tokens: 1000 };
221 expect(
222 parseCodexLine(
223 counted({ ...estimate, total_tokens: 880 }, estimate, { model_context_window: 1000 }),
224 state,
225 ),
226 ).toBeNull();
227 expect(
228 parseCodexLine(counted(counters(10, 2), { ...counters(10, 2), total_tokens: 1012 }), state)
229 ?.totals.outputTokens,
230 ).toBe(2);
231 expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0);
232 });
233​
234 it("carries the service tier from the latest thread settings", () => {
235 const settings = (thread_settings: Record<string, unknown>) =>
236 JSON.stringify({
237 type: "event_msg",
238 timestamp: "2026-08-01T05:17:42.000Z",
239 payload: { type: "thread_settings_applied", thread_settings },
240 });
241 const state = initialCodexScanState();
242 parseCodexLine(turnContext, state);
243 const speedAfter = (line: string, output: number) => {
244 parseCodexLine(line, state);
245 return parseCodexLine(tokenCount(100, 0, output, 0), state)?.speed;
246 };
247​
248 expect(parseCodexLine(tokenCount(100, 0, 1, 0), state)?.speed).toBe("standard");
249 expect(speedAfter(settings({ service_tier: "ultrafast" }), 2)).toBe("ultrafast");
250 expect(speedAfter(settings({ service_tier: "priority" }), 3)).toBe("fast");
251 expect(speedAfter(settings({ model: "gpt-6-astra" }), 4)).toBe("standard");
252 });
253​
254 it("retains initial tier evidence only for the own OpenAI session and exact context until native settings arrive", () => {
255 const meta = (id: string, model_provider?: string) =>
256 JSON.stringify({ type: "session_meta", payload: { id, model_provider } });
257 const context = (turn_id?: string, model?: string) =>
258 JSON.stringify({ type: "turn_context", payload: { turn_id, model } });
259 for (const provider of ["openai", "t3", "custom", undefined]) {
260 const state = initialCodexScanState();
261 parseCodexLine(meta("own-session", provider), state);
262 parseCodexLine(meta("ancestor", provider === "openai" ? "custom" : "openai"), state);
263 parseCodexLine(context("first-turn", "gpt-6-astra"), state);
264 const first = parseCodexLine(tokenCount(100, 0, 1, 0), state);
265 expect(first).toMatchObject({
266 sessionId: "own-session",
267 model: "gpt-6-astra",
268 speed: "standard",
269 });
270 if (provider === "openai") {
271 expect(first).toHaveProperty("unresolvedServiceTierTurnId", "first-turn");
272 } else {
273 expect(first).not.toHaveProperty("unresolvedServiceTierTurnId");
274 }
275​
276 parseCodexLine(context(undefined, "gpt-6-astra"), state);
277 expect(parseCodexLine(tokenCount(100, 0, 2, 0), state)).not.toHaveProperty(
278 "unresolvedServiceTierTurnId",
279 );
280 parseCodexLine(context("missing-model"), state);
281 expect(parseCodexLine(tokenCount(100, 0, 3, 0), state)).not.toHaveProperty(
282 "unresolvedServiceTierTurnId",
283 );
284 parseCodexLine(context("next-turn", "gpt-6-astra"), state);
285 const next = parseCodexLine(tokenCount(100, 0, 4, 0), state);
286 if (provider === "openai") {
287 expect(next).toHaveProperty("unresolvedServiceTierTurnId", "next-turn");
288 } else {
289 expect(next).not.toHaveProperty("unresolvedServiceTierTurnId");
290 }
291 }
292​
293 for (const service_tier of ["standard", "", undefined, "priority", "ultrafast"]) {
294 const state = initialCodexScanState();
295 parseCodexLine(meta("own-session", "openai"), state);
296 parseCodexLine(context("first-turn", "gpt-6-astra"), state);
297 expect(parseCodexLine(tokenCount(100, 0, 1, 0), state)).toHaveProperty(
298 "unresolvedServiceTierTurnId",
299 "first-turn",
300 );
301 parseCodexLine(
302 JSON.stringify({
303 type: "event_msg",
304 payload: { type: "thread_settings_applied", thread_settings: { service_tier } },
305 }),
306 state,
307 );
308 for (const output of [2, 3]) {
309 parseCodexLine(context(`native-turn-${output}`, "gpt-6-astra"), state);
310 const record = parseCodexLine(tokenCount(100, 0, output, 0), state);
311 expect(record?.speed).toBe(
312 service_tier === "priority"
313 ? "fast"
314 : service_tier === "ultrafast"
315 ? "ultrafast"
316 : "standard",
317 );
318 expect(record).not.toHaveProperty("unresolvedServiceTierTurnId");
319 }
320 }
321 });
322​
323 // A forked/subagent rollout opens with the parent's history copied in and
324 // every line re-stamped to the fork instant, then the ancestors' session
325 // metas. Counting those again multiplied usage ~1.85x on real data (#5758).
326 describe("forked rollouts", () => {
327 const meta = (overrides: {
328 id: string;
329 timestamp: string;
330 forkedFromId?: string;
331 spawnParentId?: string;
332 }) =>
333 JSON.stringify({
334 type: "session_meta",
335 timestamp: overrides.timestamp,
336 payload: {
337 type: "session_meta",
338 id: overrides.id,
339 ...(overrides.forkedFromId === undefined
340 ? {}
341 : { forked_from_id: overrides.forkedFromId }),
342 ...(overrides.spawnParentId === undefined
343 ? {}
344 : {
345 source: {
346 subagent: { thread_spawn: { parent_thread_id: overrides.spawnParentId } },
347 },
348 }),
349 },
350 });
351 const stamped = (timestamp: string, line: string) => {
352 const parsed = JSON.parse(line) as { timestamp: string };
353 parsed.timestamp = timestamp;
354 return JSON.stringify(parsed);
355 };
356​
357 it("keeps the child session id over copied ancestor metas", () => {
358 const state = initialCodexScanState();
359 parseCodexLine(meta({ id: "child", timestamp: "2026-08-01T05:00:00.000Z" }), state);
360 parseCodexLine(meta({ id: "parent", timestamp: "2026-08-01T05:00:00.000Z" }), state);
361 parseCodexLine(turnContext, state);
362 const record = parseCodexLine(tokenCount(100, 0, 10, 0), state);
363​
364 expect(record?.sessionId).toBe("child");
365 });
366​
367 it("drops the re-stamped copied burst and keeps the first real event", () => {
368 const state = initialCodexScanState();
369 const forkInstant = "2026-08-01T05:00:00.000Z";
370 parseCodexLine(meta({ id: "child", timestamp: forkInstant, forkedFromId: "parent" }), state);
371 parseCodexLine(meta({ id: "parent", timestamp: forkInstant }), state);
372 parseCodexLine(stamped(forkInstant, turnContext), state);
373​
374 expect(
375 parseCodexLine(
376 stamped("2026-08-01T05:00:00.001Z", counted(counters(100, 10), counters(100, 10))),
377 state,
378 ),
379 ).toBeNull();
380 expect(
381 parseCodexLine(
382 stamped("2026-08-01T05:00:00.002Z", counted(counters(200, 20), counters(300, 30))),
383 state,
384 ),
385 ).toBeNull();
386​
387 const real = parseCodexLine(
388 stamped("2026-08-01T05:00:06.000Z", counted(counters(200, 20), counters(500, 50))),
389 state,
390 );
391 expect(real).not.toBeNull();
392 expect(real?.sessionId).toBe("child");
393 expect(real?.totals.outputTokens).toBe(20);
394​
395 const next = parseCodexLine(
396 stamped("2026-08-01T05:00:06.100Z", counted(counters(400, 40), counters(900, 90))),
397 state,
398 );
399 expect(next).not.toBeNull();
400 expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0);
401 });
402​
403 it("recognizes subagent spawns without forked_from_id", () => {
404 const state = initialCodexScanState();
405 const spawnInstant = "2026-08-01T05:00:00.000Z";
406 parseCodexLine(
407 meta({ id: "child", timestamp: spawnInstant, spawnParentId: "parent" }),
408 state,
409 );
410 parseCodexLine(stamped(spawnInstant, turnContext), state);
411 expect(
412 parseCodexLine(stamped("2026-08-01T05:00:00.001Z", tokenCount(100, 0, 10, 0)), state),
413 ).toBeNull();
414 });
415​
416 it("does not suppress anything in a rollout that is not a fork", () => {
417 const state = initialCodexScanState();
418 parseCodexLine(meta({ id: "root", timestamp: "2026-08-01T05:00:00.000Z" }), state);
419 parseCodexLine(stamped("2026-08-01T05:00:00.100Z", turnContext), state);
420 const record = parseCodexLine(
421 stamped("2026-08-01T05:00:00.200Z", tokenCount(100, 0, 10, 0)),
422 state,
423 );
424 expect(record).not.toBeNull();
425 });
426 });
427});