From fa8c008f71a661ad16f4a36fbd1fdc56e9649bed Mon Sep 17 00:00:00 2001 From: iamtoruk Date: Fri, 21 Aug 2026 15:37:57 -0700 Subject: [PATCH] revert(codex): retract the BUG-2 partial-dedup timing fix Re-instrumenting this exact head over the full corpus traced the original 12.5%/46% figures to a replication gap: the earlier prevCumulativeTotal guard (codex.ts) already discards any token_count event whose running total exactly repeats the previous kept one, so a drop at the seenKeys dedup site is always a byte-identical replay of already-counted tokens -- never a real loss. The condition BUG-2's fix guarded against does not occur in real Codex output. Removes taskDedupedTokens, its increment at the dedup site, the active-time scaling at task_complete, and the now-unexercisable unit test (its fixture forces a dedup collision that is not also a cumulative-total repeat, a state the real writer never produces). The dedup site keeps a short comment recording why no rescaling is needed, so the next investigator doesn't retrace this. Keeps: the reasoning double-count fix, the harness-startup exclusion (BUG-1, confirmed to the decimal), the shared mergeToolIntervals helper and permissive duration parsing (BUG-8), and the legend rename. The real-corpus table is unchanged -- BUG-2 measured zero effect on it before this revert too. --- CHANGELOG.md | 2 +- src/providers/codex.ts | 27 ++++++--------------------- tests/providers/codex.test.ts | 29 ----------------------------- 3 files changed, 7 insertions(+), 51 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 553f1148..e27dced3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,7 +40,7 @@ ### Fixed - **Mixed-version installs no longer thrash the Codex / Cursor / Antigravity result caches.** Daily and session caches already own a version-suffixed file so an old desktop binary and a newer CLI cannot clobber each other. The three per-provider result caches still used one unsuffixed filename with an internal version field, so a v10 and a v11 binary rewrote the same `codex-results.json` (and the Cursor / Antigravity siblings) on every run and each re-parsed its whole corpus. They now write `*-results.v.json` the same way the daily cache does. The unsuffixed file is left for older binaries; a matching-version copy is adopted once and never overwritten. (#1082) - **Codex spend no longer counts reasoning tokens twice, and cache writes are priced only where OpenAI actually charges for them.** OpenAI bills reasoning tokens as *part of* `output_tokens`, not on top of it — on a 1,396-rollout corpus all 134,316 events carrying a total satisfy `input + output == total` — but CodeBurn added `reasoning_output_tokens` to output when pricing a Codex call and again in the models, audit and per-model displays. Every Codex number was therefore too high: on that corpus **cost by $166.03 (3.5%)** and **displayed Output tokens by 34.6%** ($4,713.12 -> $4,547.09; 22.6M -> 16.8M output tokens). The raw `reasoningTokens` figure is unchanged and still reported on its own; only the double-count is gone. Both places that price a Codex call — the parser and the cache-rehydration re-price — now go through one shared `billableOutputTokens` helper, so a cold run and a warm run can never disagree. Separately, Codex's `cache_write_input_tokens` (new in codex PR #33454) was never read and cache-creation tokens were hardcoded to 0; they are now carved out of the uncached-input bucket and clamped so they can never exceed it. That carve-out happens **only on models whose pricing source publishes a real cache-write rate** — gpt-5.6 and its terra/sol/luna variants charge 1.25x input for a cache write, everything before it charges nothing extra — because CodeBurn fabricates a 1.25x rate when a source omits one, and charging that would have invented a surcharge on gpt-5.5, gpt-5.4, gpt-5.3-codex and gpt-5. On models without an explicit rate the tokens stay in the plain input bucket and the price is unchanged to the cent. The field is new enough that today's impact is $0 on that corpus. Codex sessions re-parse once and the daily cache re-derives once off the warm session cache (a global re-derivation of every day and every provider, since it has no per-provider invalidation); no other provider's numbers move. Days whose Codex transcripts have since aged out are held by the same never-lose guard #1040 relies on: a re-derivation that finds fewer calls than the settled baseline keeps the older, pre-fix (double-counted) total rather than truncating it, so those days do not pick up the repricing until their sources are re-derived with equal or greater evidence. Long-context pricing tiers from the same report are tracked separately in #1076 and the missing `gpt-5.6-codex` snapshot rows in #1077. Thanks @chr-evensen. (#1075) -- **Codex Tok/s no longer counts reasoning tokens twice, credits harness startup as model time, or lets a partially fork-deduped task shrink only its numerator.** Three separate distortions in the same metric, found and fixed together because they share the same cache-invalidation and test surface. (1) #1075 fixed the reasoning-token double-count for cost, but `activeGeneratedTokens`/`taskGeneratedTokens` in the Codex parser and `generatedTokens` in the `codex-tps` live-throughput reader still summed `outputTokens + reasoningTokens`; both now go through the same `billableOutputTokens('codex', …)` helper #1075 introduced, so the numerator can never drift from the billed one. (2) Codex fires `task_started` before it assembles the request, so the gap up to the first request-context event (`turn_context`, `world_state`, `event_msg/user_message`, or a `response_item/message`) was pure CLI/harness startup counted as active model time — the active window now starts at that first event instead, which matters most for one-shot `codex exec` sessions that pay the gap on every task (GPT-5.6 Luna's active window shrank 8s->less on this corpus). (3) A `token_count` event dropped by fork-replay dedup (`seenKeys`) lost its tokens from the numerator while the task's real wall-clock duration still spanned it in the denominator, understating Tok/s for any task with SOME but not all events deduped (a fully-replayed task was already excluded by the existing `taskGeneratedTokens === 0` guard); the active window is now scaled down by the dropped tokens' proportional share instead. The duplicated tool-interval clip/merge/cap logic in `providers/codex.ts` and `codex-throughput.ts` is now one function (`mergeToolIntervals`, exported from `codex-throughput.ts`), which also closes a live trap where `task_complete`'s duration only parsed a plain number and silently dropped the `{secs,nanos}`/string forms `mcp_tool_call_end` already tolerated. Display only, no cost or token-count impact — verified byte-identical on the same real corpus. Combined effect on a real Codex corpus (original bug -> all fixes): GPT-5.5 37.8 -> 28.2 tok/s (-25.5%), Codex Auto Review 23.3 -> 20.0 (-14.2%), GPT-5.6 Sol 43.2 -> 33.9 (-21.4%), GPT-5.6 Luna 53.5 -> 49.0 (-8.5%), GPT-5.4 68.0 -> 43.6 (-35.9%), GPT-5.4 Mini 54.9 -> 55.6 (**+1.1%**, the harness-startup correction outweighing the reasoning-count correction for this model on this corpus). The partial-dedup fix is real and unit-tested but measured zero effect on this corpus — only 29 of thousands of session files are forks. `activeGeneratedTokens`/`activeDurationMs`/`toolWaitMs` are stored verbatim in both the Codex result cache and the session cache rather than re-derived on read, so none of this self-heals: Codex sessions re-parse once (one cache-version bump covers all three fixes, since they touch the same fields). The dashboard's per-model column stays labelled `Tok/s` — a wider label had zero room at the standard three-column layout, verified by breaking a real width-budget test — but the legend beneath it now reads "Effective Tok/s: generated tokens ÷ time the agent spent waiting on the model, tool execution excluded. Includes prefill, request assembly and reasoning. Not comparable to vendor decode-speed figures." (#1079, #1088) +- **Codex Tok/s no longer counts reasoning tokens twice or credits harness startup as model time.** Two distortions in the same metric, found and fixed together because they share the same cache-invalidation and test surface. (1) #1075 fixed the reasoning-token double-count for cost, but `activeGeneratedTokens`/`taskGeneratedTokens` in the Codex parser and `generatedTokens` in the `codex-tps` live-throughput reader still summed `outputTokens + reasoningTokens`; both now go through the same `billableOutputTokens('codex', …)` helper #1075 introduced, so the numerator can never drift from the billed one. (2) Codex fires `task_started` before it assembles the request, so the gap up to the first request-context event (`turn_context`, `world_state`, `event_msg/user_message`, or a `response_item/message`) was pure CLI/harness startup counted as active model time — the active window now starts at that first event instead, which matters most for one-shot `codex exec` sessions that pay the gap on every task. The duplicated tool-interval clip/merge/cap logic in `providers/codex.ts` and `codex-throughput.ts` is now one function (`mergeToolIntervals`, exported from `codex-throughput.ts`), which also closes a live trap where `task_complete`'s duration only parsed a plain number and silently dropped the `{secs,nanos}`/string forms `mcp_tool_call_end` already tolerated. (A third suspected distortion — fork-replay dedup dropping a token_count event's tokens from the numerator without shrinking the window to match — was investigated and retracted: the earlier `prevCumulativeTotal` guard already discards a repeated running total before dedup is ever reached, so a real Codex writer never produces a partial drop; the dedup site now carries a comment recording this so the trip isn't repeated.) Display only, no cost or token-count impact — verified byte-identical on the same real corpus. Combined effect on a real Codex corpus (original bug -> all fixes): GPT-5.5 37.8 -> 28.2 tok/s (-25.5%), Codex Auto Review 23.3 -> 20.0 (-14.2%), GPT-5.6 Sol 43.2 -> 33.9 (-21.4%), GPT-5.6 Luna 53.5 -> 49.0 (-8.5%), GPT-5.4 68.0 -> 43.6 (-35.9%), GPT-5.4 Mini 54.9 -> 55.6 (**+1.1%**, the harness-startup correction outweighing the reasoning-count correction for this model on this corpus). `activeGeneratedTokens`/`activeDurationMs`/`toolWaitMs` are stored verbatim in both the Codex result cache and the session cache rather than re-derived on read, so none of this self-heals: Codex sessions re-parse once (one cache-version bump covers both fixes, since they touch the same fields). The dashboard's per-model column stays labelled `Tok/s` — a wider label had zero room at the standard three-column layout, verified by breaking a real width-budget test — but the legend beneath it now reads "Effective Tok/s: generated tokens ÷ time the agent spent waiting on the model, tool execution excluded. Includes prefill, request assembly and reasoning. Not comparable to vendor decode-speed figures." (#1079, #1088) - **Codex calls attributed from session metadata no longer carry a stale model.** The Buffer fast path scanned `session_meta` for the first `"model"` string anywhere in the payload, so a nested `base_instructions.provenance.model` was read as if it were `payload.model` — and since the model is last-writer-wins state, that wrong value was credited to every call before the rollout's first `turn_context` and to every call after any mid-file `session_meta` (29 of 1380 rollouts on one real corpus carry a late `session_meta`, and 57 record usage before any `turn_context`). Direct payload fields are now read depth-aware, which is what the non-fast `JSON.parse` path always did. Codex sessions re-parse once (~9s on a 4 GB rollout corpus) and the daily cache re-derives once off the warm session cache, a global re-derivation of every day and every provider since it has no per-provider invalidation; it moves per-model attribution, and clears any rollup an earlier parse change had left stale. Days whose transcripts have partly aged out are held by the never-lose guard: on a real 110-day cache no day lost value and none disappeared — 100 days came back identical and 9 grok days rose by $19.80 in total. Thanks @timdp. (#1040) - **Codex `session_meta` cwd / session id / originator follow the same depth-1 window as `model`.** #1040 fixed nested `provenance.model`; the compact Buffer path still took the first `cwd`, `session_id`, `originator`, `name`, `forked_from_id` or `model_provider` anywhere in the payload, so a `dynamic_tools[].name` (or any same-named nested key) could steal the top-level field. Those strings now use the existing payload-depth-1 scan. Function-call `name` on other event types is unchanged. Codex sessions re-parse once. (#1045) - **Plan rows for sticker-price presets read as a budget instead of live provider quota.** There is no Grok quota endpoint, so a SuperGrok row was parsed API-equivalent spend divided by the plan's sticker price on a monthly reset — but the TUI labelled that math "plan" and "reset", which next to a client showing xAI's real weekly window read as CodeBurn being wrong. The bars and the arithmetic are unchanged; the words are not. Both the dashboard and the desktop app now say the number is an API-equivalent monthly budget and not a live provider window, in the same wording on both surfaces, and for every preset rather than as a SuperGrok special case. The window is anniversary-based (`plan.resetDay`, settable with `codeburn plan set --reset-day`), so it is called a budget reset rather than a calendar one. The row was also shortened to fit 80 columns: at that width the percentage and the projected month were being truncated away, including on custom plans, whose label carries the provider. diff --git a/src/providers/codex.ts b/src/providers/codex.ts index 8eebb4af..e6aafe85 100644 --- a/src/providers/codex.ts +++ b/src/providers/codex.ts @@ -725,10 +725,6 @@ function createParser(source: SessionSource, seenKeys: Set, capture?: { // Bounded by one task's calls; flushed at the next task_started and at EOF. let pendingTaskCalls: ParsedProviderCall[] = [] let taskGeneratedTokens = 0 - // #1088 BUG-2: tokens from token_count events dropped by fork-replay - // dedup within the current (not-yet-completed) task. See the dedup site - // below for why this must offset the active-time window at task_complete. - let taskDedupedTokens = 0 let taskToolIntervals: Array<[number, number]> = [] let taskStartedAt: number | undefined = resume?.state.taskStartedAt let taskActiveStartedAt: number | undefined = resume?.state.taskActiveStartedAt @@ -814,7 +810,6 @@ function createParser(source: SessionSource, seenKeys: Set, capture?: { results.push(...pendingTaskCalls) pendingTaskCalls = [] taskGeneratedTokens = 0 - taskDedupedTokens = 0 taskToolIntervals = [] const startedAt = entry.timestamp ? Date.parse(entry.timestamp) : NaN taskStartedAt = Number.isFinite(startedAt) ? startedAt : undefined @@ -911,13 +906,7 @@ function createParser(source: SessionSource, seenKeys: Set, capture?: { // #1088 BUG-8: shared with codex-throughput.ts's live estimate // instead of a second inline copy of the same clip/merge/cap. const toolWaitMs = mergeToolIntervals(taskToolIntervals, effectiveDurationMs, activeWindowStart, Number.isFinite(completedAt) ? completedAt : undefined) - // #1088 BUG-2: a partially fork-deduped task's active window still - // spans the dropped events' real time even though their tokens - // never reached taskGeneratedTokens (see the dedup site above). - // Shrink the window by the dropped fraction so surviving calls - // aren't credited with time that covers discarded work. - const totalTaskTokens = taskGeneratedTokens + taskDedupedTokens - const activeMs = (effectiveDurationMs - toolWaitMs) * (taskGeneratedTokens / totalTaskTokens) + const activeMs = effectiveDurationMs - toolWaitMs if (activeMs <= 0) continue for (const call of pendingTaskCalls) { // Reasoning is already inside output_tokens (#1075/#1078); the @@ -1143,15 +1132,11 @@ function createParser(source: SessionSource, seenKeys: Set, capture?: { // key would spuriously diverge on a replay and double-count it. const dedupKey = `codex:${forkedFromId || sessionId}:${cumulativeTotal}:${total?.input_tokens ?? 0}:${total?.cached_input_tokens ?? 0}:${total?.output_tokens ?? 0}:${total?.reasoning_output_tokens ?? 0}` - if (seenKeys.has(dedupKey)) { - // #1088 BUG-2: this event's tokens are dropped from the numerator, - // but task_complete's duration_ms is real wall-clock time that - // still spans them -- track what was dropped so the active window - // can be scaled down to match, instead of crediting the surviving - // calls with time that covers work whose tokens were discarded. - taskDedupedTokens += billableOutputTokens('codex', outputTokens, reasoningTokens) - continue - } + // A drop here can only be a byte-identical replay: the + // prevCumulativeTotal guard above already discards a repeated + // running total, so nothing reaching this point ever loses real + // tokens -- no active-time rescaling needed (#1088 investigation). + if (seenKeys.has(dedupKey)) continue seenKeys.add(dedupKey) // Reasoning tokens are already inside output_tokens, so they are NOT diff --git a/tests/providers/codex.test.ts b/tests/providers/codex.test.ts index cfd01c50..198eb411 100644 --- a/tests/providers/codex.test.ts +++ b/tests/providers/codex.test.ts @@ -752,35 +752,6 @@ describe('codex provider - JSONL parsing', () => { expect(calls[0]).toMatchObject({ activeGeneratedTokens: 100, activeDurationMs: 13_000, toolWaitMs: 0 }) }) - it('REGRESSION (#1088 BUG-2): a partially fork-deduped task rate matches the undeduped rate', async () => { - // Two checkpoints generate 50 tokens each over a 10s task with no tool - // calls; the first is pre-marked as already-seen (as a fork replay would - // collide it) so only the second reaches pendingTaskCalls. The task's - // real active time (10s) still spans both checkpoints' work, so the - // survivor must be credited with only its proportional share (5s), not - // the full 10s -- giving 50 tokens / 5s = 10 tok/s, the same rate as if - // neither checkpoint had been deduped (100 tokens / 10s). If this ever - // reverts to crediting the full window, it reads 50 tokens / 10s = 5 tok/s. - const dedupedKey = 'codex:sess-dedup:50:0:0:50:0' - const filePath = await writeSession(tmpDir, '2026-04-14', 'rollout-partial-dedup.jsonl', [ - sessionMeta({ session_id: 'sess-dedup', model: 'gpt-5.5' }), - JSON.stringify({ type: 'event_msg', timestamp: '2026-04-14T10:00:00Z', payload: { type: 'task_started' } }), - userMessage('run the tool', '2026-04-14T10:00:00Z'), - tokenCount({ timestamp: '2026-04-14T10:00:04Z', last: { output: 50 }, total: { output: 50, total: 50 } }), - tokenCount({ timestamp: '2026-04-14T10:00:08Z', last: { output: 50 }, total: { output: 100, total: 100 } }), - JSON.stringify({ type: 'event_msg', timestamp: '2026-04-14T10:00:10Z', payload: { type: 'task_complete', duration_ms: 10_000 } }), - ]) - - const provider = createCodexProvider(tmpDir) - const source = { path: filePath, project: 'test', provider: 'codex' } - const seenKeys = new Set([dedupedKey]) - const calls: ParsedProviderCall[] = [] - for await (const call of provider.createSessionParser(source, seenKeys).parse()) calls.push(call) - - expect(calls).toHaveLength(1) - expect(calls[0]).toMatchObject({ outputTokens: 50, activeGeneratedTokens: 50, activeDurationMs: 5_000 }) - }) - it('#1088 BUG-8: reads a task_complete duration reported as {secs,nanos}, not only a plain number', async () => { // mcp_tool_call_end already tolerates {secs,nanos} and string durations // (durationValueMs); task_complete only read the plain-number duration_ms