Skip to content
TypeScript

fix(usage): Codex compaction and resumed sessions no longer show skipped-usage warnings (#22558)

Theo Browne733a303abf31
diff --git a/apps/server/src/provider/Drivers/codexUsage.test.ts b/apps/server/src/provider/Drivers/codexUsage.test.ts
index 4133a281918..347132f331a 100644
--- a/apps/server/src/provider/Drivers/codexUsage.test.ts
+++ b/apps/server/src/provider/Drivers/codexUsage.test.ts
@@ -226,6 +226,36 @@ describe("parseCodexLine", () => {
expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0);
});
+ it.each([false, true])(
+ "accepts the post-compaction context marker without a malformed record (prior request: %s)",
+ (priorRequest) => {
+ const state = initialCodexScanState();
+ parseCodexLine(turnContext, state);
+ if (priorRequest) parseCodexLine(counted(counters(100, 20), counters(100, 20)), state);
+ const marker = counted({ ...counters(0, 0), total_tokens: 26387 }, counters(0, 0), {
+ model_context_window: 475000,
+ });
+ expect(parseCodexLine(marker, state)).toBeNull();
+ expect(
+ parseCodexLine(counted(counters(30, 5), counters(30, 5)), state)?.totals.outputTokens,
+ ).toBe(5);
+ expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0);
+ },
+ );
+
+ it("bills the first request after a resume restarts the cumulative counters", () => {
+ const state = initialCodexScanState();
+ parseCodexLine(turnContext, state);
+ parseCodexLine(counted(counters(100, 20), counters(100, 20)), state);
+ expect(
+ parseCodexLine(counted(counters(30, 5), counters(30, 5)), state)?.totals.outputTokens,
+ ).toBe(5);
+ expect(
+ parseCodexLine(counted(counters(10, 2), counters(40, 7)), state)?.totals.outputTokens,
+ ).toBe(2);
+ expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0);
+ });
+
it("retains initial tier evidence only for the own OpenAI session and exact context until native settings arrive", () => {
const meta = (id: string, model_provider?: string) =>
JSON.stringify({ type: "session_meta", payload: { id, model_provider } });
diff --git a/apps/server/src/provider/Drivers/codexUsage.ts b/apps/server/src/provider/Drivers/codexUsage.ts
index 20aa59e1411..7a483b9fbe3 100644
--- a/apps/server/src/provider/Drivers/codexUsage.ts
+++ b/apps/server/src/provider/Drivers/codexUsage.ts
@@ -219,13 +219,9 @@ function parseCodexRecord(parsed: unknown, state: CodexScanState): UsageRecord |
return null;
}
- // fill_to_context_window uses zero components and synthetic totals, then offsets future totals.
- if (
- cumulative !== null &&
- last.input_tokens + last.output_tokens === 0 &&
- cumulative.input_tokens + cumulative.output_tokens === 0 &&
- cumulative.total_tokens === infoRecord["model_context_window"]
- ) {
+ // Zero-component counters report context size, not a request: fill_to_context_window, or the
+ // post-compaction marker whose total is the new context size (its cumulative may reset to zero).
+ if (last.input_tokens + last.output_tokens === 0) {
state.lastUsageSignature = null;
return null;
}
@@ -245,7 +241,10 @@ function parseCodexRecord(parsed: unknown, state: CodexScanState): UsageRecord |
const signature = JSON.stringify(last);
if (cumulative !== null) {
+ // A session resumed in a new Codex process restarts its cumulative counters at this request.
+ const restarted = CODEX_USAGE_FIELDS.every((key) => cumulative[key] === last[key]);
if (
+ !restarted &&
!CODEX_USAGE_FIELDS.every((key) => cumulative[key] - (previous?.[key] ?? 0) === last[key])
) {
state.malformedRecords += 1;
@@ -325,7 +324,7 @@ export const codexUsageFormat: TranscriptUsageFormat<CodexScanState> = {
thread_settings: { service_tier: true },
forked_from_id: true,
source: { subagent: { thread_spawn: { parent_thread_id: true } } },
- info: { last_token_usage: true, total_token_usage: true, model_context_window: true },
+ info: { last_token_usage: true, total_token_usage: true },
},
},
// `turn_context`, `thread_settings_applied` and `session_meta` lines hold no
diff --git a/apps/server/src/usage/UsageService.test.ts b/apps/server/src/usage/UsageService.test.ts
index 44a4e938db2..75de5ec25a4 100644
--- a/apps/server/src/usage/UsageService.test.ts
+++ b/apps/server/src/usage/UsageService.test.ts
@@ -1881,7 +1881,7 @@ describe("UsageService", () => {
}).pipe(Effect.scoped),
);
- it.live.each([4, 5, 6])(
+ it.live.each([4, 5, 6, 7])(
"upgrades a v%s cache: reparses live Codex usage, keeps deleted rollouts and the old file",
(version) =>
Effect.gen(function* () {
@@ -1971,7 +1971,7 @@ describe("UsageService", () => {
60 + 20 * (version === 4 ? 1 : 2),
);
yield* upgraded.awaitPersisted;
- assert.strictEqual(SCAN_CACHE_FILE_NAME, "usage-scan-cache-v7.json");
+ assert.strictEqual(SCAN_CACHE_FILE_NAME, "usage-scan-cache-v8.json");
assert.strictEqual(
yield* Effect.promise(() => NodeFSP.readFile(legacyPath, "utf8")),
legacy,
diff --git a/apps/server/src/usage/usageScanCache.test.ts b/apps/server/src/usage/usageScanCache.test.ts
index 78770e1e646..231454d7c17 100644
--- a/apps/server/src/usage/usageScanCache.test.ts
+++ b/apps/server/src/usage/usageScanCache.test.ts
@@ -162,7 +162,7 @@ describe("scan cache round trip", () => {
expect(restored).toEqual(original);
});
- it.each([5, 6])(
+ it.each([5, 6, 7])(
"retains v%s history and compatible positions but invalidates obsolete state",
(version) => {
const original = cacheWith([["/gone.jsonl", 100, [record({ speed: "fast" })]]]);
@@ -172,7 +172,7 @@ describe("scan cache round trip", () => {
records: [record({ provider: "codex", speed: "fast", dedupeKey: null })],
position: position({
state: {
- ...(version === 6 ? initialCodexScanState() : {}),
+ ...(version >= 6 ? initialCodexScanState() : {}),
model: "gpt-6-astra",
speed: "fast",
sessionId: "session-a",
@@ -220,7 +220,7 @@ describe("scan cache round trip", () => {
position: { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null },
});
expect(restored.get("/gone-pi.jsonl")).toEqual(
- version === 6
+ version >= 6
? original.get("/gone-pi.jsonl")
: {
...original.get("/gone-pi.jsonl"),
diff --git a/apps/server/src/usage/usageScanCache.ts b/apps/server/src/usage/usageScanCache.ts
index 8ae4068f2a0..2cffb633deb 100644
--- a/apps/server/src/usage/usageScanCache.ts
+++ b/apps/server/src/usage/usageScanCache.ts
@@ -9,7 +9,7 @@ import * as Schema from "effect/Schema";
import { CLAUDE_SYNTHETIC_MODEL } from "../provider/Drivers/claudeUsage.ts";
import { GUARD_LENGTH, type TranscriptParsePosition } from "./usageTranscriptReader.ts";
-const USAGE_SCAN_CACHE_VERSION = 7 as const;
+const USAGE_SCAN_CACHE_VERSION = 8 as const;
const SPEED_COMPATIBLE_SINCE_VERSION = 4;
/**
@@ -17,8 +17,9 @@ const SPEED_COMPATIBLE_SINCE_VERSION = 4;
* replace it, dropping saved usage for deleted transcripts. Separate files keep
* both.
*/
-export const SCAN_CACHE_FILE_NAME = "usage-scan-cache-v7.json";
+export const SCAN_CACHE_FILE_NAME = "usage-scan-cache-v8.json";
export const LEGACY_SCAN_CACHE_FILE_NAMES = [
+ "usage-scan-cache-v7.json",
"usage-scan-cache-v6.json",
"usage-scan-cache-v5.json",
"usage-scan-cache.json",
@@ -310,9 +311,9 @@ export function decodeScanCache(
continue;
}
// Keep history for deleted rollouts, but re-parse incompatible reducer state.
- // Only Codex requires new provenance state in v7.
+ // Older Codex entries lack provenance state (v7) or misread compaction and resume counters (v8).
const legacy =
- format.state !== undefined && (version < 6 || (entry.p === "codex" && version < 7));
+ format.state !== undefined && (version < 6 || (entry.p === "codex" && version < 8));
// A corrupt state disqualifies the entry: resuming with it would attach
// appended usage to the wrong model or replay fork-copied history.
if (!legacy && !isValidState.get(entry.p)?.(entry.cs)) continue;