Repository navigation
fix(usage): price Codex long context per request, not per aggregate - #22360
Conversation
OpenAI bills a request whose prompt exceeds 272K input tokens at the long-context rates for that whole request. Orca applied 272K as a marginal threshold to daily, per-range and per-session token totals, so ordinary days of short requests were billed mostly at long-context rates and the summary disagreed with the model breakdown. Classify each token_count at parse time and carry long-context token counts through every rollup; the estimate bills that subset at the long-context rates and the rest at base. Bump the cache schema to 6 so existing caches rescan and pick up the split.
There was a problem hiding this comment.
ℹ️ No critical issues. The pricing fix is correct and well-tested; one minor wording/scope question inline.
Reviewed changes
- Per-request long-context classification — the parser marks a
token_countrecord long-context when itsinput_tokens > 272,000and records that request's input/cached/output as three new counters. - Cost split —
estimateCostUsdnow takes a token object and bills the long subset at the newlongContextrates and the remainder at base rates; the old tier arrays becomelongContextrate sets. - Rollups — the new counters fold through sessions, locations, models, location-models, daily aggregates, cache merges and the scan-worker handoff.
- Schema bump —
CODEX_USAGE_SCHEMA_VERSIONgoes 5 → 6, discarding caches that cannot be backfilled and triggering one full rescan. - Tests — exact-value unit and end-to-end tests (threshold boundary, mixed short/long, unbackfillable cache) plus re-pinned existing expectations.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
|
Navigate logical layers of code changes, visualize relationships, and explore their blast radius. No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review. 📝 WalkthroughWalkthroughCodex usage now records long-context input, cached-input, and output tokens per request. Requests above 272,000 input tokens use whole-request long-context rates. Cost estimation accepts complete token objects and supports mixed short- and long-context totals. Usage types, aggregations, projections, fixtures, and persistence handling now include the new fields. The usage schema version increases from 5 to 6, and legacy caches are rescanned. Priority: ➖ Normal Merge Risk: ⚪ Minimal · up to No actionable merge-blocking risk was established for the current change. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description is detailed and covers the change, rationale, testing, limitations, and compatibility considerations. However, it does not provide the required linked issue, and it does not confirm all required validation commands or manual test platforms. Resolution Add a valid issue reference in the Linked Issue section, such as
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: bd2ed970-05f1-4f97-905e-9214b08899f6
📒 Files selected for processing (16)
src/main/codex-usage/codex-automation-run-attribution.tssrc/main/codex-usage/codex-model-pricing.tssrc/main/codex-usage/codex-usage-aggregation.tssrc/main/codex-usage/codex-usage-cost-estimate.test.tssrc/main/codex-usage/codex-usage-cost-estimate.tssrc/main/codex-usage/codex-usage-long-context-billing.test.tssrc/main/codex-usage/codex-usage-provider.tssrc/main/codex-usage/codex-usage-record-parser.tssrc/main/codex-usage/codex-usage-rollup-projections.tssrc/main/codex-usage/scanner.test.tssrc/main/codex-usage/store-model-pricing.test.tssrc/main/codex-usage/store-orca-scope.test.tssrc/main/codex-usage/store-persistence.test.tssrc/main/codex-usage/store-snapshot.benchmark.test.tssrc/main/codex-usage/store-test-harness.tssrc/main/codex-usage/types.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 3 remain after this review.
A token_count with only running totals yields the increase since the previous total, which can span several short requests; classing that aggregate as one >272K request would bill short requests at long-context rates. Only a last_token_usage record is one response. Also note that OpenAI's GPT-5.4/5.5 pages say "full session" where 5.6/6 say "full request"; the per-request reading is the stated assumption. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Total-only deltas are never long context — the parser's long-context classifier is now guarded by
lastUsage !== null, so a running-total subtraction (which can span several requests) is always billed at base rates. Whenlast_token_usageis present,resolveCodexUsageDeltareturns that usage as the delta in every branch, so the guard excludes exactly the total-only case and nothing else. - Rationale comment aligned with the source — the comment now names both the "full request" (GPT-5.6/6) and "full session" (GPT-5.4/5.5) wordings and states the per-request reading as the assumption, closing the prior wording/scope thread.
- Parser test re-pinned — the total-only case now asserts zero long-context input/cached/output tokens instead of treating the aggregate delta as a single long request.
The focused suites pass (vitest over codex-usage-long-context-billing.test.ts and codex-usage-cost-estimate.test.ts = 8/8). The prior pullfrog inline thread on the classifier comment was replied to and resolved.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
… Haiku 5.5 Haiku 5.5 bills a whole request at higher rates once its prompt (input plus cache reads and writes) exceeds 100K tokens. Claude usage was only kept as daily totals, so that could not be priced and Haiku 5.5 stayed unpriced. The existing Sonnet 4.5/4 200K tier had the opposite problem: it was applied as a marginal threshold to each day's totals, so a day of short requests could be surcharged and a single long request was under-charged (the Claude side of STA-8117, fixed for Codex in #22360). Each turn is now classified when it is aggregated, against its own model's threshold, and daily and per-location rows carry the long-context subset as an optional `longContext` field. A streamed turn that grows across the threshold moves its whole share in the resume correction. estimateCostUsd takes one token object and bills that subset at the long-context rates and the rest at base, replacing the per-bucket tiering. Saved per-file projections carry a projection version; files from an older version are reparsed on the next scan, so history picks up the split without touching the signed cache schema.
… Haiku 5.5 (#30427) * fix(usage): price Claude long-context requests per request, and price Haiku 5.5 Haiku 5.5 bills a whole request at higher rates once its prompt (input plus cache reads and writes) exceeds 100K tokens. Claude usage was only kept as daily totals, so that could not be priced and Haiku 5.5 stayed unpriced. The existing Sonnet 4.5/4 200K tier had the opposite problem: it was applied as a marginal threshold to each day's totals, so a day of short requests could be surcharged and a single long request was under-charged (the Claude side of STA-8117, fixed for Codex in #22360). Each turn is now classified when it is aggregated, against its own model's threshold, and daily and per-location rows carry the long-context subset as an optional `longContext` field. A streamed turn that grows across the threshold moves its whole share in the resume correction. estimateCostUsd takes one token object and bills that subset at the long-context rates and the rest at base, replacing the per-bucket tiering. Saved per-file projections carry a projection version; files from an older version are reparsed on the next scan, so history picks up the split without touching the signed cache schema. * fix(usage): keep the projection version out of the integrity hash Hashing it made older inline reports fail validation and show the 'could not be validated' error; the scanner's version check alone decides reparse.

ELI5
OpenAI charges extra for a single request with a very long prompt, meaning more than 272K input tokens. Orca applied that surcharge to totals instead: once a day's (or a whole date range's) combined tokens passed 272K, everything above that was billed at the higher rate. Nearly every active day passes that total, even though almost no individual request does. So Codex cost estimates in Stats & Usage were far too high.
What Changed
Before: a normal day of short Codex requests was billed mostly at long-context rates, 2x on input and 1.5x on output. The summary card added up daily rows while the per-model breakdown priced one row for the whole range, so the two showed different totals. A single very long request was split by token type and billed mostly at normal rates.
After: each request is priced on its own. A request is long-context only when its prompt is over 272K tokens, and then all of its input, cached input and output use the long-context rates. The summary, the model breakdown and the per-automation costs all agree.
On one heavy user's real Codex logs (about 529K requests):
Only 2 requests were over 272K, because Codex compacts the conversation before reaching it.
How it works:
codex-usage-record-parser.ts): each rollouttoken_countrecord is one model response. When a record'sinput_tokens(which includes cached tokens) is over 272,000, its input, cached and output tokens also go into three new long-context counters. The counters are added through every rollup: sessions, location and model breakdowns, daily rows, cache merges and the scan-worker handoff.codex-usage-cost-estimate.ts): the long-context part is billed at the long-context rates and the rest at base rates. The tier arrays incodex-model-pricing.tsbecome alongContextrate set, with the same values.CODEX_USAGE_SCHEMA_VERSIONgoes from 5 to 6. Old cached totals can't be split after the fact, so existing caches are thrown away and the logs are re-read once.Why
The saved data stays as token counts, split by short and long requests, instead of stored dollar amounts. That means a future price change (like #22350) still reprices history without a rescan, and the short/long split doesn't depend on the price table.
Evidence behind the rule:
last_token_usageto that response's usage alone and emits onetoken_count(codex-rs/protocol/src/protocol.rsappend_last_usage).input_tokens(non_cached_input).Known limits:
last_token_usage(older Codex logs) is always billed at base rates, because the difference in running totals can span several short requests. Those logs predate the models that have long-context pricing, and none of the 1.69M token-count records on the test machine lacklast_token_usage.Linked Issue
None. This is a follow-up to the CodeRabbit review on #22350.
Visual Proof
N/A. The layout and interactions are unchanged; only the numbers are corrected (see the before/after table above).
Testing
I manually tested these changes locally
Automated tests added/updated, or explained why not below
New tests: one 300K request is billed entirely at long-context rates; short requests adding up to millions are billed at base rates; exactly 272,000 tokens is short and 272,001 is long. A mixed two-day log gives the same cost for the summary, the model breakdown and automation cost ($26.80; the old code gave $29.32 and $32.31). A cache from the old version is not reused.
Updated expected values: existing tests were re-pinned to base-rate values recomputed by hand. For example, GPT-5.6 Sol went from $34.88 to $24.40 for 1M uncached, 1M cached and 1M output.
Proof the tests catch the bug: 15 tests fail when the old source files are swapped back in.
Results:
vitestoversrc/main/codex-usage,src/main/usage,src/main/automationsandsrc/renderer/src/components/statspassed 354/354.pnpm tc,oxlint,oxfmt --checkandcheck:code-quality:changedalso passed.Real-data check: a throwaway script priced about 2,000 real Codex logs the old way and the new way, and the numbers are in the table above.
AI Disclosure
Written with Claude Opus 5.5 and reviewed by a separate Opus reviewer.
Review
Agent skill upstream boundary
docs/reference/agent-skill-sharing-upstream-boundary.mdand copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.Notes
src/sharedandmobileare untouched, and paired clients still receive the same dollar fields.Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)