Codex cost inflated 2.7–4.6× since #1768: cached input tokens are double-billed
Summary
Codex cost calculation is significantly inflated (≈2.7×–4.6× depending on workload) for any usage that includes cached input tokens. The regression was introduced by #1768 ("Fix Codex archived usage undercount", commit 537fd8ff) and is present on main today. It is not in any shipped release — the latest release v0.37.2 (Jun 22, 2026) predates the merge of #1768 (Jun 28, 2026), so only source builds from main are affected.
The archived-usage dedupe portion of #1768 (seenSessionIds → contributingSessionIds) is correct and should be kept. The damage is limited to the pricing math in codexCostUSD.
Root cause
Sources/CodexBarCore/Vendored/CostUsage/CostUsagePricing.swift, the private codexCostUSD(pricing:inputTokens:cachedInputTokens:outputTokens:).
OpenAI/Codex reports input_tokens as the total prompt size, with cached_input_tokens being a subset of it. #1768 changed the function to treat them as additive:
- let nonCached = max(0, inputTokens - cached)
+ let nonCached = max(0, inputTokens)
- let usesLongContextRates = pricing.thresholdTokens.map { max(0, inputTokens) > $0 } ?? false
+ let usesLongContextRates = pricing.thresholdTokens.map { (nonCached + cached) > $0 } ?? false
This creates two compounding defects:
- Cached tokens are double-billed. The full
input_tokenscount is charged at the input rate, and the cached subset is then charged again at the cache-read rate. Cached reads end up payinginputRate + cacheRateinstead of justcacheRate. - Long-context threshold triggers too early. The 272K threshold is now evaluated against
input + cached(which double-counts cached) instead ofinputalone, so workloads tip into the doubled long-context rates far earlier than they should. Example: a 200K-token prompt with 100K cached has a real context size of 200K (< 272K), but200K + 100K = 300Kwrongly activates the 2× tier.
Evidence
1. Direct execution of the current main function
Running the verbatim codexCostUSD body from main against the fixed (pre-#1768) version, using real gpt-5.4 rates (base input 2.5e-6, cache-read 2.5e-7, output 1.5e-5; threshold 272K with 2× above-threshold rates):
| input / cached / output | main |
correct | inflation |
|---|---|---|---|
| 1K / 900 / 10 | $0.0029 | $0.0006 | 4.60× |
| 200K / 100K / 5K | $1.1625 | $0.3500 | 3.32× |
| 260K / 150K / 10K | $1.6000 | $0.4625 | 3.46× |
| 5M / 4M / 200K | $31.50 | $11.50 | 2.74× |
2. Full build of main (clean worktree at the current tip)
A test asserting the correct value for gpt-5-codex (input 1000 / cached 900 / output 10; rates input 1.25e-6, cache-read 1.25e-7, output 1e-5) fails against a full compile of main:
✘ "codex cost does not double bill cached input tokens" failed
Expectation failed: (cost → 0.0014625) == (expected → 0.0003375)
Expected (100 × 1.25e-6) + (900 × 1.25e-7) + (10 × 1e-5) = 0.0003375; main returns 0.0014625 (the full 1000 billed at the input rate plus the 900 cached billed again) — a 4.33× overcharge.
3. Observed in practice
Identical token usage renders correct totals on the released v0.37.2 build but inflated totals (~6×, amplified by the threshold defect on large daily aggregates) on a make start build from main.
Suggested fix
Restore the pre-#1768 semantics in codexCostUSD:
let cached = min(max(0, cachedInputTokens), max(0, inputTokens))
let nonCached = max(0, inputTokens - cached)
...
let usesLongContextRates = pricing.thresholdTokens.map { max(0, inputTokens) > $0 } ?? false
i.e. clamp cached to inputTokens, bill only the remainder at the input rate, and evaluate the long-context threshold against inputTokens (which already includes cached). The contributingSessionIds change from #1768 is unaffected and should remain.
The test expectations updated in #1768 (CostUsagePricingTests, CostUsageScannerPriorityTests, CostUsageScannerBreakdownTests) were edited to assert the inflated numbers and need to be reverted to the pre-#1768 values as part of the fix.
Reproduction
git worktree add /tmp/cbar-main origin/main
cd /tmp/cbar-main
# add a test: CostUsagePricing.codexCostUSD(model: "gpt-5-codex",
# inputTokens: 1000, cachedInputTokens: 900, outputTokens: 10)
# observe it returns 0.0014625 rather than the correct 0.0003375
Affected versions
main(since #1768, merged 2026-06-28): affected.v0.37.2and earlier releases: not affected.
Codex review: keeping this open for maintainer follow-up; there is still a little grit to resolve. Reviewed June 30, 2026, 4:49 PM ET / 20:49 UTC.
Summary
Keep open: current main still bills Codex cached input additively in codexCostUSD, and the regression appears limited to unreleased source builds after the merged archived-usage repair.
Reproducibility: yes. source-reproducible: current codexCostUSD charges inputTokens and cachedInputTokens separately even though cached input is a subset, and the bundled rates make the issue's focused example compute to the inflated value. I did not run tests because this review is read-only.
Root-cause cluster
Relationship: canonical
Canonical: https://github.com/steipete/codexbar/issues/1796
Summary: This issue is the canonical active tracker for the current-main cached-input overbilling regression; the earlier archived-usage report is closed and the merged repair introduced the pricing change under review.
Members:
partial_overlap: https://github.com/steipete/codexbar/pull/1768 - The merged archived-usage repair changed the pricing helper and tests while solving a separate undercount, but it is closed and not an active fix candidate for the overbilling regression.adjacent_distinct: https://github.com/steipete/codexbar/issues/1767 - The original Overview/CLI undercount issue was closed by the archived-usage PR; this issue reports the opposite cost inflation in the shared pricing area.adjacent_distinct: https://github.com/steipete/codexbar/issues/1062 - The earlier closed overcount report concerned repeated token_count rows, not additive cached-input billing.
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.
Next step Queue a narrow fix PR because the broken helper, expected semantics, likely tests, and validation path are clear and no product decision is needed.
Review details
Best possible solution:
Restore codexCostUSD so cached input is treated as a subset of input, update the affected pricing/scanner expectations, and keep the archived-session dedupe from https://github.com/steipete/CodexBar/pull/1768 intact.
Do we have a high-confidence way to reproduce the issue?
Yes, source-reproducible: current codexCostUSD charges inputTokens and cachedInputTokens separately even though cached input is a subset, and the bundled rates make the issue's focused example compute to the inflated value. I did not run tests because this review is read-only.
Is this the best way to solve the issue?
Yes: the narrow fix is to restore subset-cached pricing and threshold semantics in the helper, then adjust the affected tests. Reverting the whole archived-usage repair would be broader and would reintroduce the undercount bug it fixed.
AGENTS.md: found and applied where relevant.
Remaining risk / open question:
- I did not execute Swift tests because this review had to keep the checkout read-only; the reproduction is source-level plus issue-provided local test output.
- A fix should preserve the row-level active/archive dedupe from https://github.com/steipete/CodexBar/pull/1768 and the later Pi-session cache-read correction instead of reverting the whole merged repair.
Codex review notes: model internal, reasoning high; reviewed against f5340ad62732.
Label changes
Label changes:
- add
P2: This is a clear Codex spend-reporting regression with material cost inflation, but it appears limited to unreleased main builds and does not affect app availability. - add
impact:other: The issue affects user-visible cost accuracy, which is maintainer-visible but outside the specific data-loss, security, message, session, auth, and crash labels. - add
issue-rating: 🦞 diamond lobster: Current issue advisory state selects this label. - add
clawsweeper:source-repro: Current issue advisory state selects this label. - add
clawsweeper:queueable-fix: Current issue advisory state selects this label. - add
clawsweeper:fix-shape-clear: Current issue advisory state selects this label.
Label justifications:
P2: This is a clear Codex spend-reporting regression with material cost inflation, but it appears limited to unreleased main builds and does not affect app availability.impact:other: The issue affects user-visible cost accuracy, which is maintainer-visible but outside the specific data-loss, security, message, session, auth, and crash labels.
Evidence reviewed
Acceptance criteria:
- swift test --filter CostUsagePricingTests
- swift test --filter CostUsageScannerPriorityTests
- swift test --filter CostUsageScannerBreakdownTests
- swift test --filter PiSessionCostScannerTests
- make check
What I checked:
- Repository policy read: AGENTS.md was read fully; its guidance supports a small Swift/XCTest parser-pricing repair and avoiding live provider or Keychain validation for this path. (
AGENTS.md:1, f5340ad62732) - Vision fit: VISION.md says clear, bounded bug fixes are merge-by-default work, which fits this pricing regression. (
VISION.md:5, f5340ad62732) - Current source double-bills cached input: Current main sets
nonCached = max(0, inputTokens), keepscached = max(0, cachedInputTokens), usesnonCached + cachedfor the threshold, and returns both input and cached charges. (Sources/CodexBarCore/Vendored/CostUsage/CostUsagePricing.swift:512, f5340ad62732) - Focused reproduction rates are present: The bundled
gpt-5-codexrates match the issue's focused example, so the current formula yields 0.0014625 for input 1000, cached 900, output 10 instead of the subset-cached expectation 0.0003375. (Sources/CodexBarCore/Vendored/CostUsage/CostUsagePricing.swift:74, f5340ad62732) - Current tests assert additive cached pricing: The current pricing tests expect full input plus cached input for the long-context and cache-heavy cases, matching the reported incorrect behavior rather than guarding against it. (
Tests/CodexBarTests/CostUsagePricingTests.swift:105, f5340ad62732) - Blame provenance:
git blameties the exactnonCached,cached, and threshold changes incodexCostUSDto commit 537fd8ff4f6df55a5fce30f54b1b56469c7b4918. (Sources/CodexBarCore/Vendored/CostUsage/CostUsagePricing.swift:512, 537fd8ff4f6d)
Likely related people:
- kiranmagic7: Blame and diff history tie the exact additive cached-input pricing change and matching test expectations to the archived-usage repair commits. (role: introduced behavior; confidence: high; commits: 537fd8ff4f6d, 0065ca42e6ab; files:
Sources/CodexBarCore/Vendored/CostUsage/CostUsagePricing.swift,Tests/CodexBarTests/CostUsagePricingTests.swift) - steipete: Recent PR discussion and commits show follow-up work on the same Codex scanner/pricing area, including a separate Pi Codex cache-read double-pricing fix. (role: recent area contributor and PR follow-up owner; confidence: high; commits: 004422130c02, 7cece2360ef1, f380287041b8; files:
Sources/CodexBarCore/PiSessionCostScanner.swift,Sources/CodexBarCore/Vendored/CostUsage/CostUsagePricing.swift,Tests/CodexBarTests/PiSessionCostScannerTests.swift) - iam-brain: PR metadata and local history show the Codex tiered and priority pricing surface was introduced through the earlier Codex pricing work that this helper belongs to. (role: feature introducer; confidence: medium; commits: 91522d332d2b, 2f6a31c23e2c; files:
Sources/CodexBarCore/Vendored/CostUsage/CostUsagePricing.swift,Tests/CodexBarTests/CostUsagePricingTests.swift,Tests/CodexBarTests/CostUsageScannerPriorityTests.swift)
How this review workflow works
- ClawSweeper keeps one durable marker-backed review comment per issue or PR.
- Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
- A fresh review can be triggered by eligible
@clawsweeper re-reviewcomments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch. - PR/issue authors and users with repository write access can comment
@clawsweeper re-reviewor@clawsweeper re-runon an open PR or issue to request a fresh review only. - Maintainers can also comment
@clawsweeper reviewto request a fresh review only. - Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
- Maintainer-only repair and merge flows require explicit commands such as
@clawsweeper autofix,@clawsweeper automerge,@clawsweeper fix ci, or@clawsweeper address review. - Maintainers can comment
@clawsweeper explainto ask for more context, or@clawsweeper stopto stop active automation.
Fixed by #1797 and landed in 306cf96787f007cfeec038739f423a0c23923d6e.
Exact-head CI, focused cache-repricing regressions, full local checks/tests, clean bundled autoreview, and redacted real-log CLI proof all passed. The CLI proof confirmed cached-read subset invariants and row/aggregate token and cost reconciliation without publishing private values.