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.
This commit is contained in:
Resham Joshi 2026-11-06 05:53:53 -08:00
parent deb6b3b297
commit 591cecc6f4
2 changed files with 24 additions and 3 deletions

View file

@ -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<string>, 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<string>, capture?: {
forkedFromId,
...(forkReplayState ? { forkReplayState: { ...forkReplayState } } : {}),
prevCumulativeTotal,
restartEpoch,
prevInfoIdentity,
hasTokenUsageRecord,
serviceTier,
@ -1622,7 +1627,7 @@ function createParser(source: SessionSource, seenKeys: Set<string>, 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<string>, 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, {

View file

@ -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' }),