@devries-cameron20 / t3code-1 / commits / 38b8c204a6
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(usage): reconcile Codex request and cumulative counters (#21863)

Julius Marminge committed Oct 19, 2026 at 21:19 UTC 38b8c204a6a5d9e4707806c0cd8bc8c36373fe7a
6 files changed +503 -63
apps/server/src/provider/Drivers/codexUsage.test.ts
+179 -7
@@ -1,6 +1,6 @@
1 import { describe, expect, it } from "@effect/vitest";
2
3 -import { initialCodexScanState, parseCodexLine } from "./codexUsage.ts";
3 +import { codexUsageFormat, initialCodexScanState, parseCodexLine } from "./codexUsage.ts";
4
5 describe("parseCodexLine", () => {
6 const sessionMeta = JSON.stringify({
@@ -30,6 +30,23 @@ describe("parseCodexLine", () => {
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();
@@ -60,11 +77,158 @@ describe("parseCodexLine", () => {
77 expect(parseCodexLine(tokenCount(100, 0, 10, 0), state)).toBeNull();
78 });
79
63 - it("does not let a pre-model event poison the duplicate signature", () => {
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", () => {
@@ -139,24 +303,32 @@ describe("parseCodexLine", () => {
303 parseCodexLine(stamped(forkInstant, turnContext), state);
304
305 expect(
142 - parseCodexLine(stamped("2026-08-01T05:00:00.001Z", tokenCount(100, 0, 10, 0)), state),
306 + parseCodexLine(
307 + stamped("2026-08-01T05:00:00.001Z", counted(counters(100, 10), counters(100, 10))),
308 + state,
309 + ),
310 ).toBeNull();
311 expect(
145 - parseCodexLine(stamped("2026-08-01T05:00:00.002Z", tokenCount(200, 0, 20, 0)), state),
312 + parseCodexLine(
313 + stamped("2026-08-01T05:00:00.002Z", counted(counters(200, 20), counters(300, 30))),
314 + state,
315 + ),
316 ).toBeNull();
317
318 const real = parseCodexLine(
149 - stamped("2026-08-01T05:00:06.000Z", tokenCount(300, 0, 30, 0)),
319 + stamped("2026-08-01T05:00:06.000Z", counted(counters(200, 20), counters(500, 50))),
320 state,
321 );
322 expect(real).not.toBeNull();
153 - expect(real?.totals.outputTokens).toBe(30);
323 + expect(real?.sessionId).toBe("child");
324 + expect(real?.totals.outputTokens).toBe(20);
325
326 const next = parseCodexLine(
156 - stamped("2026-08-01T05:00:06.100Z", tokenCount(400, 0, 40, 0)),
327 + stamped("2026-08-01T05:00:06.100Z", counted(counters(400, 40), counters(900, 90))),
328 state,
329 );
330 expect(next).not.toBeNull();
331 + expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0);
332 });
333
334 it("recognizes subagent spawns without forked_from_id", () => {
apps/server/src/provider/Drivers/codexUsage.ts
+127 -25
@@ -5,7 +5,6 @@ import * as Schema from "effect/Schema";
5
6 import {
7 parseTimestampMs,
8 - tokenCount,
8 totalTokens,
9 type ProviderUsageReader,
10 type TranscriptUsageFormat,
@@ -16,6 +15,51 @@ import type { UsageTokenTotals } from "@t3tools/contracts";
15
16 import { resolveCodexHomeLayout } from "./CodexHomeLayout.ts";
17
18 +const TokenCount = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));
19 +const CodexTokenUsage = Schema.Struct({
20 + input_tokens: TokenCount,
21 + cached_input_tokens: TokenCount,
22 + cache_write_input_tokens: TokenCount,
23 + output_tokens: TokenCount,
24 + reasoning_output_tokens: TokenCount,
25 + total_tokens: TokenCount,
26 +}).check(
27 + Schema.makeFilter(
28 + (usage) =>
29 + usage.cached_input_tokens + usage.cache_write_input_tokens <= usage.input_tokens &&
30 + usage.reasoning_output_tokens <= usage.output_tokens &&
31 + usage.total_tokens >= usage.input_tokens + usage.output_tokens,
32 + ),
33 +);
34 +type CodexTokenUsage = typeof CodexTokenUsage.Type;
35 +const isCodexTokenUsage = Schema.is(CodexTokenUsage);
36 +const CODEX_USAGE_FIELDS = Object.keys(CodexTokenUsage.fields) as (keyof CodexTokenUsage)[];
37 +
38 +function readCodexTokenUsage(value: unknown): CodexTokenUsage | null {
39 + if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
40 + const raw = value as Record<string, unknown>;
41 + const input = raw["input_tokens"];
42 + const output = raw["output_tokens"];
43 + if (typeof input !== "number" || typeof output !== "number") return null;
44 + const usage = {
45 + input_tokens: input,
46 + cached_input_tokens: raw["cached_input_tokens"] === undefined ? 0 : raw["cached_input_tokens"],
47 + cache_write_input_tokens:
48 + raw["cache_write_input_tokens"] === undefined ? 0 : raw["cache_write_input_tokens"],
49 + output_tokens: output,
50 + reasoning_output_tokens:
51 + raw["reasoning_output_tokens"] === undefined ? 0 : raw["reasoning_output_tokens"],
52 + total_tokens: raw["total_tokens"] === undefined ? input + output : raw["total_tokens"],
53 + };
54 + return isCodexTokenUsage(usage) ? usage : null;
55 +}
56 +
57 +function advanceCodexUsage(previous: CodexTokenUsage | null, last: CodexTokenUsage) {
58 + return readCodexTokenUsage(
59 + Object.fromEntries(CODEX_USAGE_FIELDS.map((key) => [key, (previous?.[key] ?? 0) + last[key]])),
60 + );
61 +}
62 +
63 /**
64 * Codex `token_count` events carry no model or service tier, so both are carried forward: the model
65 * from the most recent `turn_context`, the tier from the most recent `thread_settings_applied`.
@@ -25,6 +69,8 @@ export const CodexScanState = Schema.Struct({
69 speed: Schema.mutableKey(Schema.Literals(["standard", "fast", "ultrafast"])),
70 sessionId: Schema.mutableKey(Schema.String),
71 lastUsageSignature: Schema.mutableKey(Schema.NullOr(Schema.String)),
72 + lastCumulativeUsage: Schema.mutableKey(Schema.NullOr(CodexTokenUsage)),
73 + malformedRecords: Schema.mutableKey(TokenCount),
74 sawSessionMeta: Schema.mutableKey(Schema.Boolean),
75 suppressingForkCopies: Schema.mutableKey(Schema.Boolean),
76 forkCopyAnchorMs: Schema.mutableKey(Schema.Finite),
@@ -37,6 +83,8 @@ export function initialCodexScanState(): CodexScanState {
83 speed: "standard",
84 sessionId: "",
85 lastUsageSignature: null,
86 + lastCumulativeUsage: null,
87 + malformedRecords: 0,
88 sawSessionMeta: false,
89 suppressingForkCopies: false,
90 forkCopyAnchorMs: 0,
@@ -63,8 +111,8 @@ function isForkedSessionMeta(payload: Record<string, unknown>): boolean {
111 }
112
113 /**
66 - * Deltas come from `last_token_usage`. Summing those across a session reconciles with the session's
67 - * final `total_token_usage`, provided consecutive duplicate events are dropped, which this does.
114 + * Cumulative counters validate request deltas. Older events without cumulative counters use
115 + * normalized consecutive-request deduplication.
116 */
117 export function parseCodexLine(line: string, state: CodexScanState): UsageRecord | null {
118 let parsed: unknown;
@@ -118,45 +166,98 @@ function parseCodexRecord(parsed: unknown, state: CodexScanState): UsageRecord |
166
167 const info = payloadRecord["info"];
168 if (typeof info !== "object" || info === null) return null;
121 - const last = (info as Record<string, unknown>)["last_token_usage"];
122 - if (typeof last !== "object" || last === null) return null;
123 - const lastRecord = last as Record<string, unknown>;
124 -
125 - // Only an event that is otherwise eligible may consume the duplicate
126 - // signature. A token_count arriving before its turn_context (no model yet)
127 - // must not poison it, or the re-emitted copy after the model is known would
128 - // be skipped as a duplicate and those tokens never counted.
169 + const infoRecord = info as Record<string, unknown>;
170 +
171 + // Codex may re-emit these counters after the model or timestamp becomes available.
172 const timestampMs = parseTimestampMs(record["timestamp"]);
130 - if (timestampMs === null) return null;
131 - if (state.model.length === 0) return null;
173 + if (timestampMs === null || state.model.length === 0) return null;
174
133 - // Codex re-emits an unchanged token_count on some stream boundaries. Summing
134 - // those would double count, so identical consecutive payloads are skipped.
135 - const signature = JSON.stringify(lastRecord);
136 - if (signature === state.lastUsageSignature) return null;
137 - state.lastUsageSignature = signature;
175 + const last = readCodexTokenUsage(infoRecord["last_token_usage"]);
176 + const rawCumulative = infoRecord["total_token_usage"];
177 + const hasCumulative = rawCumulative !== undefined && rawCumulative !== null;
178 + const cumulative = hasCumulative ? readCodexTokenUsage(rawCumulative) : null;
179
180 if (state.suppressingForkCopies) {
181 if (timestampMs - state.forkCopyAnchorMs < FORK_COPY_MAX_GAP_MS) {
182 state.forkCopyAnchorMs = timestampMs;
183 + // Copied history is already billed in the parent, but establishes the child's baseline.
184 + const signature = last === null ? null : JSON.stringify(last);
185 + if (cumulative !== null) state.lastCumulativeUsage = cumulative;
186 + else if (!hasCumulative && last !== null && signature !== state.lastUsageSignature) {
187 + state.lastCumulativeUsage = advanceCodexUsage(state.lastCumulativeUsage, last);
188 + }
189 + state.lastUsageSignature = signature;
190 return null;
191 }
192 state.suppressingForkCopies = false;
193 + state.lastUsageSignature = null;
194 + }
195 +
196 + const previous = state.lastCumulativeUsage;
197 + // A valid snapshot remains the next baseline even when its paired request is malformed.
198 + if (cumulative !== null) state.lastCumulativeUsage = cumulative;
199 + if (last === null || (hasCumulative && cumulative === null)) {
200 + state.malformedRecords += 1;
201 + return null;
202 + }
203 +
204 + // fill_to_context_window uses zero components and synthetic totals, then offsets future totals.
205 + if (
206 + cumulative !== null &&
207 + last.input_tokens + last.output_tokens === 0 &&
208 + cumulative.input_tokens + cumulative.output_tokens === 0 &&
209 + cumulative.total_tokens === infoRecord["model_context_window"]
210 + ) {
211 + state.lastUsageSignature = null;
212 + return null;
213 }
214
147 - const inputTokens = tokenCount(lastRecord["input_tokens"]);
148 - const cachedInputTokens = tokenCount(lastRecord["cached_input_tokens"]);
149 - const cacheCreationTokens = tokenCount(lastRecord["cache_write_input_tokens"]);
150 - const outputTokens = tokenCount(lastRecord["output_tokens"]);
215 + if (
216 + cumulative !== null &&
217 + previous !== null &&
218 + CODEX_USAGE_FIELDS.every((key) => cumulative[key] === previous[key])
219 + ) {
220 + return null;
221 + }
222 +
223 + if (last.total_tokens !== last.input_tokens + last.output_tokens) {
224 + state.malformedRecords += 1;
225 + return null;
226 + }
227 +
228 + const signature = JSON.stringify(last);
229 + if (cumulative !== null) {
230 + if (
231 + !CODEX_USAGE_FIELDS.every((key) => cumulative[key] - (previous?.[key] ?? 0) === last[key])
232 + ) {
233 + state.malformedRecords += 1;
234 + return null;
235 + }
236 + } else {
237 + if (signature === state.lastUsageSignature) return null;
238 + // Advance expected totals for billed legacy requests so a cumulative re-emission is stale.
239 + const advanced = advanceCodexUsage(previous, last);
240 + if (advanced === null) {
241 + state.malformedRecords += 1;
242 + return null;
243 + }
244 + state.lastCumulativeUsage = advanced;
245 + }
246 + state.lastUsageSignature = signature;
247 +
248 + const inputTokens = last.input_tokens;
249 + const cachedInputTokens = last.cached_input_tokens;
250 + const cacheCreationTokens = last.cache_write_input_tokens;
251 + const outputTokens = last.output_tokens;
252
253 const totals: UsageTokenTotals = {
254 // Codex reports `input_tokens` inclusive of the cached portion.
154 - uncachedInputTokens: Math.max(0, inputTokens - cachedInputTokens - cacheCreationTokens),
255 + uncachedInputTokens: inputTokens - cachedInputTokens - cacheCreationTokens,
256 cachedInputTokens,
257 cacheCreationTokens,
258 outputTokens,
259 // Reported inside output_tokens, surfaced separately for the token mix.
159 - reasoningTokens: Math.min(outputTokens, tokenCount(lastRecord["reasoning_output_tokens"])),
260 + reasoningTokens: last.reasoning_output_tokens,
261 };
262
263 if (totalTokens(totals) === 0) return null;
@@ -198,7 +299,7 @@ export const codexUsageFormat: TranscriptUsageFormat<CodexScanState> = {
299 thread_settings: { service_tier: true },
300 forked_from_id: true,
301 source: { subagent: { thread_spawn: { parent_thread_id: true } } },
201 - info: { last_token_usage: true },
302 + info: { last_token_usage: true, total_token_usage: true, model_context_window: true },
303 },
304 },
305 // `turn_context`, `thread_settings_applied` and `session_meta` lines hold no
@@ -207,6 +308,7 @@ export const codexUsageFormat: TranscriptUsageFormat<CodexScanState> = {
308 parseLine: (line, state) => orEmpty(parseCodexLine(line, state)),
309 parseProjected: (projected, state) => orEmpty(parseCodexRecord(projected, state)),
310 state: { initial: initialCodexScanState, schema: CodexScanState },
311 + readMalformedRecords: (state) => state.malformedRecords,
312 // A rollout that moved after it was read leaves a copy in both places.
313 sharedSessionsAcrossFiles: true,
314 };
apps/server/src/usage/UsageService.test.ts
+158 -16
@@ -7,6 +7,7 @@ import * as NodePath from "node:path";
7 import * as NodeSqlite from "node:sqlite";
8
9 import { assert, describe, it } from "@effect/vitest";
10 +import { vi } from "vite-plus/test";
11 import * as NodeServices from "@effect/platform-node/NodeServices";
12 import * as HostProcess from "@t3tools/shared/HostProcess";
13 import { mergeUsage } from "@t3tools/shared/usageMerge";
@@ -16,6 +17,7 @@ import {
17 ProviderInstanceId,
18 UsageDay,
19 type UsageSource,
20 + type UsageSummary,
21 type UsageSummaryInput,
22 } from "@t3tools/contracts";
23 import * as Duration from "effect/Duration";
@@ -43,7 +45,9 @@ import * as AntigravityUsage from "../provider/Drivers/AntigravityUsage.ts";
45 import * as ProviderHostLive from "../provider/ProviderHostLive.ts";
46 import { totalTokens, type UsageRecord } from "@t3tools/provider-core/server/usage";
47 import * as UsageService from "./UsageService.ts";
46 -import { encodeScanCache } from "./usageScanCache.ts";
48 +import { encodeScanCache, SCAN_CACHE_FILE_NAME } from "./usageScanCache.ts";
49 +
50 +vi.mock("node:fs/promises", { spy: true });
51
52 const encodeUnknownJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
53 const encodeUnknownJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
@@ -1528,6 +1532,129 @@ describe("UsageService", () => {
1532 }).pipe(Effect.scoped),
1533 );
1534
1535 + it.live(
1536 + "retains Codex reconciliation and partial coverage through persisted restart, append and repair",
1537 + () =>
1538 + Effect.gen(function* () {
1539 + const { home, settings } = yield* setup;
1540 + const dir = NodePath.join(home, "codex", "sessions");
1541 + const transcript = NodePath.join(dir, "rollout.jsonl");
1542 + const usage = (input: number, output: number) => ({
1543 + input_tokens: input,
1544 + output_tokens: output,
1545 + total_tokens: input + output,
1546 + });
1547 + const counted = (input: number, output: number, totalInput: number, totalOutput: number) =>
1548 + encodeUnknownJsonString({
1549 + type: "event_msg",
1550 + timestamp: "2026-08-01T10:00:00Z",
1551 + payload: {
1552 + type: "token_count",
1553 + info: {
1554 + last_token_usage: usage(input, output),
1555 + total_token_usage: usage(totalInput, totalOutput),
1556 + },
1557 + },
1558 + });
1559 + const tier = (service_tier: string) =>
1560 + encodeUnknownJsonString({
1561 + type: "event_msg",
1562 + payload: { type: "thread_settings_applied", thread_settings: { service_tier } },
1563 + });
1564 + const bad = counted(10, 2, 130, 28);
1565 + // Cross the reader's projection threshold so cumulative fields must survive selection.
1566 + const stale = counted(20, 5, 100, 20).replace(
1567 + '"payload":',
1568 + '"padding":' + encodeUnknownJsonString("x".repeat(9 * 1024 * 1024)) + ',"payload":',
1569 + );
1570 + let content = [
1571 + encodeUnknownJsonString({ type: "turn_context", payload: { model: "gpt-6-astra" } }),
1572 + counted(100, 20, 100, 20),
1573 + stale,
1574 + tier("priority"),
1575 + bad,
1576 + ].join("\n");
1577 + yield* Effect.promise(async () => {
1578 + await NodeFSP.mkdir(dir, { recursive: true });
1579 + await NodeFSP.writeFile(transcript, content);
1580 + });
1581 + yield* Effect.gen(function* () {
1582 + const verify = (
1583 + summary: UsageSummary,
1584 + output: number,
1585 + cost: number,
1586 + malformed: number,
1587 + ) => {
1588 + assert.strictEqual(totalOutputTokens(summary), output);
1589 + assert.strictEqual(
1590 + summary.buckets.reduce((sum, bucket) => sum + bucket.costUsd, 0),
1591 + cost,
1592 + );
1593 + const source = summary.sources.find(
1594 + (source) => source.fingerprint.provider === "codex",
1595 + );
1596 + assert.strictEqual(source?.status, malformed === 0 ? "ok" : "partial");
1597 + assert.strictEqual(source?.malformedRecords, malformed);
1598 + if (malformed > 0) assert.match(source?.message ?? "", /1 malformed or inconsistent/);
1599 + else assert.notMatch(source?.message ?? "", /malformed|inconsistent/);
1600 + };
1601 + const open = vi.spyOn(NodeFSP, "open");
1602 + open.mockClear();
1603 + yield* Effect.addFinalizer(() => Effect.sync(() => open.mockRestore()));
1604 + const first = yield* UsageService.make;
1605 + const cold = yield* first.readSummary(WINDOW);
1606 + assert.isTrue(open.mock.calls.some(([path]) => path === transcript));
1607 + verify(cold, 20, 20, 1);
1608 + yield* first.awaitPersisted;
1609 + const restarted = yield* UsageService.make;
1610 + open.mockClear();
1611 + verify(yield* first.readSummary(WINDOW), 20, 20, 1);
1612 + verify(yield* restarted.readSummary(WINDOW), 20, 20, 1);
1613 + assert.isFalse(open.mock.calls.some(([path]) => path === transcript));
1614 + open.mockRestore();
1615 +
1616 + const append = "\n" + counted(10, 2, 140, 30) + "\n";
1617 + content += append;
1618 + yield* Effect.promise(() => NodeFSP.appendFile(transcript, append));
1619 + verify(yield* restarted.readSummary(WINDOW), 22, 24, 1);
1620 + yield* restarted.awaitPersisted;
1621 + const resumed = yield* UsageService.make;
1622 + verify(yield* resumed.readSummary(WINDOW), 22, 24, 1);
1623 + const next = tier("ultrafast") + "\n" + counted(10, 2, 150, 32) + "\n";
1624 + content += next;
1625 + yield* Effect.promise(() => NodeFSP.appendFile(transcript, next));
1626 + verify(yield* resumed.readSummary(WINDOW), 24, 36, 1);
1627 +
1628 + const repaired = content.replace(bad, counted(30, 8, 130, 28));
1629 + assert.strictEqual(Buffer.byteLength(repaired), Buffer.byteLength(content));
1630 + yield* Effect.promise(async () => {
1631 + const stat = await NodeFSP.stat(transcript);
1632 + await NodeFSP.writeFile(transcript, repaired);
1633 + await NodeFSP.utimes(transcript, stat.atime, stat.mtimeMs / 1000 + 1);
1634 + });
1635 + verify(yield* resumed.readSummary(WINDOW), 32, 52, 0);
1636 + }).pipe(
1637 + Effect.provide(
1638 + layerService({
1639 + prefix: "usage-codex-reconciliation",
1640 + home,
1641 + settings,
1642 + ratesDocument: {
1643 + "gpt-6-astra": {
1644 + input_cost_per_token: 0,
1645 + output_cost_per_token: 1,
1646 + input_cost_per_token_priority: 0,
1647 + output_cost_per_token_priority: 2,
1648 + input_cost_per_token_ultrafast: 0,
1649 + output_cost_per_token_ultrafast: 6,
1650 + },
1651 + },
1652 + }),
1653 + ),
1654 + );
1655 + }).pipe(Effect.scoped),
1656 + );
1657 +
1658 it.live(
1659 "keeps large-record totals and costs exact through append, dedupe, restart and cleanup",
1660 () =>
@@ -1583,9 +1710,9 @@ describe("UsageService", () => {
1710 }).pipe(Effect.scoped),
1711 );
1712
1586 - it.live(
1587 - "upgrades a v4 cache: reprices live Codex tiers, keeps deleted rollouts, leaves v4 intact",
1588 - () =>
1713 + it.live.each([4, 5])(
1714 + "upgrades a v%s cache: reparses live Codex usage, keeps deleted rollouts and the old file",
1715 + (version) =>
1716 Effect.gen(function* () {
1717 const { home, settings } = yield* setup;
1718 const sessions = NodePath.join(home, "codex", "sessions");
@@ -1621,33 +1748,46 @@ describe("UsageService", () => {
1748
1749 yield* Effect.gen(function* () {
1750 const { stateDir } = yield* ServerConfig.ServerConfig;
1624 - const cachePath = NodePath.join(stateDir, "usage-scan-cache-v5.json");
1625 - const legacyPath = NodePath.join(stateDir, "usage-scan-cache.json");
1751 + const cachePath = NodePath.join(stateDir, SCAN_CACHE_FILE_NAME);
1752 + const legacyPath = NodePath.join(
1753 + stateDir,
1754 + version === 4 ? "usage-scan-cache.json" : "usage-scan-cache-v5.json",
1755 + );
1756 const first = yield* UsageService.make;
1757 yield* first.readSummary(WINDOW);
1758 yield* first.awaitPersisted;
1759
1760 const legacy = yield* Effect.promise(async () => {
1761 const document = decodeUnknownJsonString(await NodeFSP.readFile(cachePath, "utf8")) as {
1632 - files: Record<string, { r: unknown[][]; cs: { speed?: unknown } }>;
1762 + files: Record<string, { r: unknown[][]; cs: Record<string, unknown> }>;
1763 };
1634 - for (const file of Object.values(document.files)) {
1635 - file.r = file.r.map((row) => [...row.slice(0, 10), 0]);
1636 - delete file.cs.speed;
1764 + for (const [path, file] of Object.entries(document.files)) {
1765 + file.r = file.r.map((row) => [
1766 + ...row.slice(0, 6),
1767 + path === live ? 99 : row[6],
1768 + ...row.slice(7, 10),
1769 + version === 4 ? 0 : 1,
1770 + ]);
1771 + if (version === 4) delete file.cs.speed;
1772 + delete file.cs.lastCumulativeUsage;
1773 + delete file.cs.malformedRecords;
1774 }
1638 - const text = encodeUnknownJsonString({ ...document, version: 4 });
1639 - await NodeFSP.writeFile(legacyPath, text);
1775 + const text = encodeUnknownJsonString({ ...document, version });
1776 await NodeFSP.rm(cachePath);
1777 + await NodeFSP.writeFile(legacyPath, text);
1778 await NodeFSP.rm(deleted);
1779 return text;
1780 });
1781
1645 - const summary = yield* (yield* UsageService.make).readSummary(WINDOW);
1782 + const upgraded = yield* UsageService.make;
1783 + const summary = yield* upgraded.readSummary(WINDOW);
1784 assert.strictEqual(totalOutputTokens(summary), 30);
1785 assert.strictEqual(
1786 summary.buckets.reduce((sum, bucket) => sum + bucket.costUsd, 0),
1649 - 80,
1787 + 60 + 20 * (version === 4 ? 1 : 2),
1788 );
1789 + yield* upgraded.awaitPersisted;
1790 + assert.strictEqual(SCAN_CACHE_FILE_NAME, "usage-scan-cache-v6.json");
1791 assert.strictEqual(
1792 yield* Effect.promise(() => NodeFSP.readFile(legacyPath, "utf8")),
1793 legacy,
@@ -1655,13 +1795,15 @@ describe("UsageService", () => {
1795 }).pipe(
1796 Effect.provide(
1797 layerService({
1658 - prefix: "usage-service-v4-upgrade-test",
1798 + prefix: "usage-service-cache-upgrade-test",
1799 home,
1800 settings,
1801 ratesDocument: {
1802 "gpt-6-astra": {
1803 input_cost_per_token: 0,
1804 output_cost_per_token: 1,
1805 + input_cost_per_token_priority: 0,
1806 + output_cost_per_token_priority: 2,
1807 input_cost_per_token_ultrafast: 0,
1808 output_cost_per_token_ultrafast: 6,
1809 },
@@ -1911,7 +2053,7 @@ describe("UsageService", () => {
2053 yield* Effect.promise(async () => {
2054 await NodeFSP.mkdir(stateDir, { recursive: true });
2055 await NodeFSP.writeFile(
1914 - NodePath.join(stateDir, "usage-scan-cache-v5.json"),
2056 + NodePath.join(stateDir, SCAN_CACHE_FILE_NAME),
2057 encodeUnknownJsonString(cache),
2058 );
2059 });
apps/server/src/usage/UsageService.ts
+4 -4
@@ -50,7 +50,7 @@ import {
50 import {
51 decodeScanCache,
52 dedupeWithinFile,
53 - LEGACY_SCAN_CACHE_FILE_NAME,
53 + LEGACY_SCAN_CACHE_FILE_NAMES,
54 makeScanCacheWriter,
55 pruneScanCache,
56 SCAN_CACHE_FILE_NAME,
@@ -204,7 +204,6 @@ export const make = Effect.gen(function* () {
204
205 const ratesCachePath = path.join(config.stateDir, "usage-model-rates.json");
206 const scanCachePath = path.join(config.stateDir, SCAN_CACHE_FILE_NAME);
207 - const legacyScanCachePath = path.join(config.stateDir, LEGACY_SCAN_CACHE_FILE_NAME);
207 const writeCacheFile = (filePath: string, contents: string) =>
208 writeFileStringAtomically({ filePath, contents }).pipe(
209 Effect.provideService(FileSystem.FileSystem, fileSystem),
@@ -392,8 +391,9 @@ export const make = Effect.gen(function* () {
391 Effect.catchCause(() => Effect.succeed(null)),
392 );
393 let document = yield* readDocument(scanCachePath);
395 - if (document === null) {
396 - document = yield* readDocument(legacyScanCachePath);
394 + for (const fileName of LEGACY_SCAN_CACHE_FILE_NAMES) {
395 + if (document !== null) break;
396 + document = yield* readDocument(path.join(config.stateDir, fileName));
397 cacheDirty = document !== null;
398 }
399 if (document === null) return;
apps/server/src/usage/usageScanCache.test.ts
+27 -4
@@ -12,6 +12,7 @@ import {
12 import type { UsageRecord } from "@t3tools/provider-core/server/usage";
13
14 import { TEST_FORMAT_MAP } from "./usageTestFormats.ts";
15 +import { initialCodexScanState } from "../provider/Drivers/codexUsage.ts";
16
17 function record(overrides: Partial<UsageRecord> = {}): UsageRecord {
18 return {
@@ -108,13 +109,12 @@ describe("scan cache round trip", () => {
109 tailRecords: [],
110 position: position({
111 state: {
112 + ...initialCodexScanState(),
113 model: "gpt-6-astra",
114 speed: "ultrafast",
115 sessionId: "session-c",
116 lastUsageSignature: '{"input_tokens":1}',
117 sawSessionMeta: true,
116 - suppressingForkCopies: false,
117 - forkCopyAnchorMs: 0,
118 },
119 }),
120 });
@@ -142,14 +142,31 @@ describe("scan cache round trip", () => {
142 expect(restored).toEqual(original);
143 });
144
145 - it("defaults missing v5 diagnostic counts to zero without losing cached records", () => {
145 + it("retains v5 history and stateless positions but invalidates obsolete Codex state", () => {
146 const original = cacheWith([["/gone.jsonl", 100, [record({ speed: "fast" })]]]);
147 + original.set("/gone-codex.jsonl", {
148 + ...original.get("/gone.jsonl")!,
149 + provider: "codex",
150 + records: [record({ provider: "codex", speed: "fast", dedupeKey: null })],
151 + position: position({
152 + state: {
153 + model: "gpt-6-astra",
154 + speed: "fast",
155 + sessionId: "session-a",
156 + lastUsageSignature: null,
157 + sawSessionMeta: true,
158 + suppressingForkCopies: false,
159 + forkCopyAnchorMs: 0,
160 + },
161 + }),
162 + });
163 const encoded = encodeScanCache(original);
164 const entry = encoded.files["/gone.jsonl"]!;
165 const legacy = {
166 ...encoded,
167 version: 5,
168 files: {
169 + ...encoded.files,
170 "/gone.jsonl": {
171 s: entry.s,
172 m: entry.m,
@@ -164,7 +181,13 @@ describe("scan cache round trip", () => {
181 },
182 };
183
167 - expect(decodeScanCache(JSON.parse(JSON.stringify(legacy)), TEST_FORMAT_MAP)).toEqual(original);
184 + const restored = decodeScanCache(JSON.parse(JSON.stringify(legacy)), TEST_FORMAT_MAP);
185 + expect(restored.get("/gone.jsonl")).toEqual(original.get("/gone.jsonl"));
186 + expect(restored.get("/gone-codex.jsonl")).toEqual({
187 + ...original.get("/gone-codex.jsonl"),
188 + size: -1,
189 + position: { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null },
190 + });
191 });
192
193 it("drops an entry whose persisted parse state is corrupt", () => {
apps/server/src/usage/usageScanCache.ts
+8 -7
@@ -9,7 +9,7 @@ import * as Schema from "effect/Schema";
9 import { CLAUDE_SYNTHETIC_MODEL } from "../provider/Drivers/claudeUsage.ts";
10 import { GUARD_LENGTH, type TranscriptParsePosition } from "./usageTranscriptReader.ts";
11
12 -const USAGE_SCAN_CACHE_VERSION = 5 as const;
12 +const USAGE_SCAN_CACHE_VERSION = 6 as const;
13 const SPEED_COMPATIBLE_SINCE_VERSION = 4;
14
15 /**
@@ -17,8 +17,11 @@ const SPEED_COMPATIBLE_SINCE_VERSION = 4;
17 * replace it, dropping saved usage for deleted transcripts. Separate files keep
18 * both.
19 */
20 -export const SCAN_CACHE_FILE_NAME = "usage-scan-cache-v5.json";
21 -export const LEGACY_SCAN_CACHE_FILE_NAME = "usage-scan-cache.json";
20 +export const SCAN_CACHE_FILE_NAME = "usage-scan-cache-v6.json";
21 +export const LEGACY_SCAN_CACHE_FILE_NAMES = [
22 + "usage-scan-cache-v5.json",
23 + "usage-scan-cache.json",
24 +] as const;
25
26 const SPEEDS: readonly UsageSpeed[] = ["standard", "fast", "ultrafast"];
27
@@ -295,10 +298,8 @@ export function decodeScanCache(
298 ) {
299 continue;
300 }
298 - // v4 records of stateful formats (Codex) predate service tiers, so they
299 - // all priced as standard. Keep them, because the rollout may be gone, but
300 - // make a live rollout re-parse whole: no file has size -1, and a zero
301 - // position cannot resume.
301 + // Older stateful reducers have different semantics. Keep their history for deleted rollouts,
302 + // but force live files to re-parse: no file has size -1 and a zero position cannot resume.
303 const legacy = format.state !== undefined && version < USAGE_SCAN_CACHE_VERSION;
304 // A corrupt state disqualifies the entry: resuming with it would attach
305 // appended usage to the wrong model or replay fork-copied history.