fix(codex): read a dropping cumulative-only total as a counter restart

Rollouts without last_token_usage are priced from cumulative deltas. When
the running total fell (resume, compaction) the delta went negative and
output and reasoning sums shrank. A counter below its previous value now
counts what it holds as the usage since the restart.
This commit is contained in:
Resham Joshi 2026-11-06 04:47:13 -08:00
parent 4b15470a5f
commit 7ecf573e5e
4 changed files with 28 additions and 7 deletions

View file

@ -75,7 +75,8 @@ import { isWslUncPath } from './wsl.js'
// v25: rollouts that name the thread only as payload.id key their calls on
// that UUID, so fork replays collide with them; v24 entries hold stem-keyed
// calls and double-counted fork replays. Same version: a turn-start
// rate-limit ping (null info, no output yet) is no longer an estimated call.
// rate-limit ping (null info, no output yet) is no longer an estimated call,
// and a cumulative-only total that drops reads as a restart, not negative usage.
export const CODEX_CACHE_VERSION = 25
export const CODEX_LEGACY_CACHE_FILE = 'codex-results.json'
export function codexCacheFileName(version = CODEX_CACHE_VERSION): string {

View file

@ -1606,11 +1606,14 @@ function createParser(source: SessionSource, seenKeys: Set<string>, capture?: {
} else if (cumulativeTotal > 0) {
const total = info.total_token_usage
if (!total) continue
inputTokens = (total.input_tokens ?? 0) - prevInput
cachedInputTokens = (total.cached_input_tokens ?? 0) - prevCached
cacheWriteTokens = (total.cache_write_input_tokens ?? 0) - prevCacheWrite
outputTokens = (total.output_tokens ?? 0) - prevOutput
reasoningTokens = (total.reasoning_output_tokens ?? 0) - prevReasoning
// A running counter below its previous value restarted (resume,
// compaction): what it holds now is the usage since the restart.
const since = (now: number | undefined, prev: number) => (now ?? 0) >= prev ? (now ?? 0) - prev : now ?? 0
inputTokens = since(total.input_tokens, prevInput)
cachedInputTokens = since(total.cached_input_tokens, prevCached)
cacheWriteTokens = since(total.cache_write_input_tokens, prevCacheWrite)
outputTokens = since(total.output_tokens, prevOutput)
reasoningTokens = since(total.reasoning_output_tokens, prevReasoning)
}
// Always advance the prev counters to track the cumulative state.

View file

@ -449,8 +449,10 @@ export const PROVIDER_PARSE_VERSIONS: Record<string, string> = {
// the UUID forks name, so cached double-counted fork replays re-parse.
// rate-limit-ping-v1: a null-info token_count before any output is not a
// call, so cached phantom estimates re-parse away.
// cumulative-restart-v1: a cumulative-only total below the previous one is a
// counter restart, so cached negative token deltas re-parse.
// Compose every suffix so cached sessions receive all accounting fixes.
codex: 'mcp-attribution-v5-est-cost-active-timing-mcp-wait-rich-capture-v1-cross-provider-pr-v1-session-meta-model-v1-session-meta-fields-v1-codex-pricing-v1-codex-tps-v1-codex-mcp-skills-v1-activity-price-v1-fork-replay-burst-v1-codex-token-usage-record-v1-codex-priority-tier-v1-codex-auto-review-date-v1-codex-flex-reserve-v1-codex-fork-mask-v1-native-tool-events-v1-mcp-cli-command-v1-thread-id-key-v1-rate-limit-ping-v1',
codex: 'mcp-attribution-v5-est-cost-active-timing-mcp-wait-rich-capture-v1-cross-provider-pr-v1-session-meta-model-v1-session-meta-fields-v1-codex-pricing-v1-codex-tps-v1-codex-mcp-skills-v1-activity-price-v1-fork-replay-burst-v1-codex-token-usage-record-v1-codex-priority-tier-v1-codex-auto-review-date-v1-codex-flex-reserve-v1-codex-fork-mask-v1-native-tool-events-v1-mcp-cli-command-v1-thread-id-key-v1-rate-limit-ping-v1-cumulative-restart-v1',
// reported-cost-v1: cached Crush calls stored costUSD: undefined and must
// re-parse to keep the recorded session cost.
crush: 'reported-cost-v1',

View file

@ -842,6 +842,21 @@ describe('codex provider - JSONL parsing', () => {
expect(calls[0]!.outputTokens).toBeGreaterThan(0)
})
it('reads a cumulative-only total that drops as a counter restart, never as negative usage', async () => {
const filePath = await writeSession(tmpDir, '2026-04-14', 'rollout-cumulative-reset.jsonl', [
sessionMeta({ session_id: 'sess-reset', model: 'gpt-5.5' }),
tokenCount({ timestamp: '2026-04-14T10:00:10Z', total: { input: 8_000, output: 800 } }),
tokenCount({ timestamp: '2026-04-14T10:10:10Z', total: { input: 3_000, output: 300 } }),
tokenCount({ timestamp: '2026-04-14T10:10:20Z', total: { input: 6_000, output: 600 } }),
])
const provider = createCodexProvider(tmpDir)
const calls: ParsedProviderCall[] = []
for await (const call of provider.createSessionParser({ path: filePath, project: 'test', provider: 'codex' }, new Set()).parse()) calls.push(call)
expect(calls.map(c => [c.inputTokens, c.outputTokens])).toEqual([[8_000, 800], [3_000, 300], [3_000, 300]])
})
it('treats a turn-start rate-limit ping with no usage info as no call and keeps the prompt', async () => {
const filePath = await writeSession(tmpDir, '2026-04-14', 'rollout-rate-limit-ping.jsonl', [
sessionMeta({ session_id: 'sess-ping', model: 'gpt-5.5' }),