Skip to content

fix(usage): price Codex long context per request, not per aggregate - #22360

Merged
Jinwoo-H merged 2 commits into
mainfrom
codex-usage-per-request-long-context
Sep 23, 2026
Merged

Jinwoo-H merged 2 commits into
mainfrom
codex-usage-per-request-long-context

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 7 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​523 $\color{#cf222e}{\Huge{\mathbf{−}}}$​63 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​460
Prod 9 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​130 $\color{#cf222e}{\Huge{\mathbf{−}}}$​104 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​26

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):

Window Old estimate New estimate
7 days ~$1,069 ~$590
30 days ~$88.5K ~$45.8K

Only 2 requests were over 272K, because Codex compacts the conversation before reaching it.

How it works:

  • Parser (codex-usage-record-parser.ts): each rollout token_count record is one model response. When a record's input_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.
  • Pricing (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 in codex-model-pricing.ts become a longContext rate set, with the same values.
  • Saved cache: CODEX_USAGE_SCHEMA_VERSION goes 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:

  • One record is one response. In the Codex source, each completed response sets last_token_usage to that response's usage alone and emits one token_count (codex-rs/protocol/src/protocol.rs append_last_usage).
  • Cached tokens count toward the prompt size. Cached tokens are a subset of input_tokens (non_cached_input).
  • The threshold. The GPT-5.6 and GPT-6 model pages say "Prompts with more than 272K input tokens are priced at 2x input and cache rates and 1.5x output for the full request". So the check is strictly more than 272,000.
  • "Request" vs "session". The GPT-5.4 and GPT-5.5 pages say "for the full session" instead. Orca only sees per-response usage, so it prices per request; that reading is an assumption, stated in the code.

Known limits:

  • Old logs without per-request usage. A record with no 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 lack last_token_usage.
  • Saved automation run costs. Automation run records keep the dollar figure saved when they ran, so runs recorded before this fix still show the old, higher cost.
  • Claude. Claude's usage pricing applies its 200K tier to totals in the same way, but that only affects the older Sonnet 4 and 4.5 models. It is left for a follow-up.

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: vitest over src/main/codex-usage, src/main/usage, src/main/automations and src/renderer/src/components/stats passed 354/354. pnpm tc, oxlint, oxfmt --check and check:code-quality:changed also 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

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • Remote/wire: the new counters stay in the main process and are only used by local IPC handlers. src/shared and mobile are untouched, and paired clients still receive the same dollar fields.
  • SSH: Codex logs are only scanned from local Codex home folders, so SSH workspaces behave as before.
  • Performance: the one-time rescan after upgrading is a single re-read in the scan worker. The per-folder worktree lookup cache from perf(usage): resolve each cwd's worktree once per scan #21130 is already on main, so it avoids the slow worktree-matching cost behind STA-7724.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ 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_count record long-context when its input_tokens > 272,000 and records that request's input/cached/output as three new counters.
  • Cost split — estimateCostUsd now takes a token object and bills the long subset at the new longContext rates and the remainder at base rates; the old tier arrays become longContext rate 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_VERSION goes 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.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@coderabbitai

coderabbitai Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

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 configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 039fd78d-1e7d-4f6a-9bef-ba463a78015d

📥 Commits

Reviewing files that changed from the base of the PR and between cfa2295 and ee48d21.

📒 Files selected for processing (2)
  • src/main/codex-usage/codex-usage-long-context-billing.test.ts
  • src/main/codex-usage/codex-usage-record-parser.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/main/codex-usage/codex-usage-record-parser.ts
  • src/main/codex-usage/codex-usage-long-context-billing.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review.


📝 Walkthrough

Walkthrough

Codex 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 ee48d

No actionable merge-blocking risk was established for the current change.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 14.29% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 14 functions across 16 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning 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 al… Add a valid issue reference in the Linked Issue section, such as Fixes #22350``. Confirm manual testing and the tested platforms, and either report results for pnpm lint, `pnpm typecheck`, `pnpm test`, and `pnpm build`, or state that CI w…
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly identifies the primary change: Codex long-context pricing now applies per request instead of per aggregate.
Full details: Description check

Explanation

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 Fixes #22350``. Confirm manual testing and the tested platforms, and either report results for pnpm lint, `pnpm typecheck`, `pnpm test`, and `pnpm build`, or state that CI will cover them.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: bd2ed970-05f1-4f97-905e-9214b08899f6

📥 Commits

Reviewing files that changed from the base of the PR and between 0e6862c and cfa2295.

📒 Files selected for processing (16)
  • src/main/codex-usage/codex-automation-run-attribution.ts
  • src/main/codex-usage/codex-model-pricing.ts
  • src/main/codex-usage/codex-usage-aggregation.ts
  • src/main/codex-usage/codex-usage-cost-estimate.test.ts
  • src/main/codex-usage/codex-usage-cost-estimate.ts
  • src/main/codex-usage/codex-usage-long-context-billing.test.ts
  • src/main/codex-usage/codex-usage-provider.ts
  • src/main/codex-usage/codex-usage-record-parser.ts
  • src/main/codex-usage/codex-usage-rollup-projections.ts
  • src/main/codex-usage/scanner.test.ts
  • src/main/codex-usage/store-model-pricing.test.ts
  • src/main/codex-usage/store-orca-scope.test.ts
  • src/main/codex-usage/store-persistence.test.ts
  • src/main/codex-usage/store-snapshot.benchmark.test.ts
  • src/main/codex-usage/store-test-harness.ts
  • src/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]>

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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. When last_token_usage is present, resolveCodexUsageDelta returns 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.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@Jinwoo-H
Jinwoo-H merged commit 2155673 into main Sep 23, 2026
30 checks passed
Jinwoo-H added a commit that referenced this pull request Sep 27, 2026
#18759's test fixture predates #22360 adding required long-context token
fields to Codex session and location breakdowns, so main's typecheck fails.
Jinwoo-H added a commit that referenced this pull request Oct 18, 2026
… 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.
Jinwoo-H added a commit that referenced this pull request Oct 18, 2026
… 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant