From 591cecc6f49c49652067e2eac6ababaf57d3a41e Mon Sep 17 00:00:00 2001 From: Resham Joshi <65915470+iamtoruk@users.noreply.github.com> Date: Fri, 6 Nov 2026 05:53:53 -0800 Subject: [PATCH] fix(codex): key cumulative calls by restart epoch After a counter restart the running totals can climb back to a state seen before it (100/10 -> restart 50/5 -> 100/10), and the third record reused the first record's dedup key and was dropped. Count restarts per rollout, carry the count across append resumes, and add it to the cumulative key once a restart has happened. --- src/providers/codex.ts | 12 +++++++++--- tests/providers/codex.test.ts | 15 +++++++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/src/providers/codex.ts b/src/providers/codex.ts index 0d83f338..884c7dfe 100644 --- a/src/providers/codex.ts +++ b/src/providers/codex.ts @@ -738,6 +738,8 @@ type CodexResumeState = { forkedFromId: string forkReplayState?: CodexForkReplayState prevCumulativeTotal: number | null + /// Counter restarts seen so far; keys a repeated cumulative state after one. + restartEpoch?: number /// Byte-identity of the last token_count info payload (#257 re-emission /// collapse). Optional so resume states written before it still decode. prevInfoIdentity?: string | null @@ -816,6 +818,7 @@ function isResumeState(value: unknown): value is CodexResumeState { && typeof v['forkedFromId'] === 'string' && (v['forkReplayState'] === undefined || isCodexForkReplayState(v['forkReplayState'])) && (v['prevCumulativeTotal'] === null || typeof v['prevCumulativeTotal'] === 'number') + && (v['restartEpoch'] === undefined || typeof v['restartEpoch'] === 'number') && (v['prevInfoIdentity'] === undefined || v['prevInfoIdentity'] === null || typeof v['prevInfoIdentity'] === 'string') && (v['hasTokenUsageRecord'] === undefined || typeof v['hasTokenUsageRecord'] === 'boolean') && (v['serviceTier'] === undefined || typeof v['serviceTier'] === 'string') @@ -913,6 +916,7 @@ function createParser(source: SessionSource, seenKeys: Set, capture?: { // total and dedup on equality regardless of whether it is zero. let prevCumulativeTotal: number | null = resume?.state.prevCumulativeTotal ?? null let prevInfoIdentity: string | null = resume?.state.prevInfoIdentity ?? null + let restartEpoch = resume?.state.restartEpoch ?? 0 let hasTokenUsageRecord = resume?.state.hasTokenUsageRecord ?? false // #1616: the service tier `thread_settings_applied` last set. Everything // the loop reads from a PRIOR line must ride CodexResumeState, and this @@ -1288,6 +1292,7 @@ function createParser(source: SessionSource, seenKeys: Set, capture?: { forkedFromId, ...(forkReplayState ? { forkReplayState: { ...forkReplayState } } : {}), prevCumulativeTotal, + restartEpoch, prevInfoIdentity, hasTokenUsageRecord, serviceTier, @@ -1622,7 +1627,7 @@ function createParser(source: SessionSource, seenKeys: Set, capture?: { const restart = prevTotal !== null ? cumulativeTotal < prevTotal : present.length > 0 && present.every(([now, prev]) => now < prev) - if (restart) { prevInput = 0; prevCached = 0; prevCacheWrite = 0; prevOutput = 0; prevReasoning = 0 } + if (restart) { restartEpoch++; prevInput = 0; prevCached = 0; prevCacheWrite = 0; prevOutput = 0; prevReasoning = 0 } const since = (now: number | undefined, prev: number) => now === undefined ? 0 : Math.max(0, now - prev) inputTokens = since(total.input_tokens, prevInput) cachedInputTokens = since(total.cached_input_tokens, prevCached) @@ -1673,9 +1678,10 @@ function createParser(source: SessionSource, seenKeys: Set, capture?: { // burst (accepted trade-off: the alternative collapsed // distinct requests wholesale). // Two rollouts of one thread at identical cumulative totals are the - // same calls replayed (resume), so sharing this key is intended. + // same calls replayed (resume), so sharing this key is intended. After + // a counter restart the same totals are new calls: the epoch tells. const dedupKey = reportsCumulative - ? `codex:${forkedFromId || threadId}:${cumulativeTotal}:${total?.input_tokens ?? 0}:${total?.cached_input_tokens ?? 0}:${total?.output_tokens ?? 0}:${total?.reasoning_output_tokens ?? 0}` + ? `codex:${forkedFromId || threadId}:${cumulativeTotal}:${total?.input_tokens ?? 0}:${total?.cached_input_tokens ?? 0}:${total?.output_tokens ?? 0}:${total?.reasoning_output_tokens ?? 0}${restartEpoch ? `:r${restartEpoch}` : ''}` : `codex:record:${JSON.stringify([source.path, tracker.lastCompleteLineOffset])}` accountUsage(entry, { diff --git a/tests/providers/codex.test.ts b/tests/providers/codex.test.ts index f549bc82..5c5b9f98 100644 --- a/tests/providers/codex.test.ts +++ b/tests/providers/codex.test.ts @@ -857,6 +857,21 @@ describe('codex provider - JSONL parsing', () => { expect(calls.map(c => [c.inputTokens, c.outputTokens])).toEqual([[8_000, 800], [3_000, 300], [3_000, 300]]) }) + it('counts a cumulative state repeated after a restart as a new call', async () => { + const filePath = await writeSession(tmpDir, '2026-04-14', 'rollout-cumulative-restart-repeat.jsonl', [ + sessionMeta({ session_id: 'sess-restart-repeat', model: 'gpt-5.5' }), + tokenCount({ timestamp: '2026-04-14T10:00:10Z', total: { input: 100, output: 10 } }), + tokenCount({ timestamp: '2026-04-14T10:00:20Z', total: { input: 50, output: 5 } }), + tokenCount({ timestamp: '2026-04-14T10:00:30Z', total: { input: 100, output: 10 } }), + ]) + + 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([[100, 10], [50, 5], [50, 5]]) + }) + it('restarts every counter on a restart, including one the restart record omits', async () => { const filePath = await writeSession(tmpDir, '2026-04-14', 'rollout-cumulative-restart-omitted.jsonl', [ sessionMeta({ session_id: 'sess-restart-omitted', model: 'gpt-5.5' }),