Repository navigation
fix(claude-usage): bill 1-hour cache writes at 2x base input - #16878
Conversation
Anthropic charges 1.25x base input for a 5-minute cache write and 2x for
a 1-hour one. `MODEL_PRICING` carried a single flat `cacheWrite` rate (the
5m one) and the transcript parser read only the aggregate
`usage.cache_creation_input_tokens`, discarding the
`usage.cache_creation.{ephemeral_5m,ephemeral_1h}_input_tokens` split that
is already on disk. Every 1h cache write was therefore billed at 62.5% of
its real cost.
Parse the TTL split, carry it through session/location/daily aggregates,
and give `estimateCostUsd` a 1h bucket with its own long-context tier.
Bumps the Claude usage cache schema to 6 so existing caches, which never
recorded the split, are rebuilt.
Fixes #15993
…-write TTLs Pricing the 5m and 1h write buckets with two independent tiered calls gave each its own 200k below-threshold allowance, so a Sonnet daily row with a mixed bucket could estimate LESS than the same tokens billed entirely at the 5m rate (400k writes: $2.25 -> $1.95). Split the allowance in proportion to each bucket's share.
📝 WalkthroughWalkthroughThe Claude usage pipeline now tracks one-hour TTL cache-write tokens separately from five-minute TTL cache writes. Transcript parsing reads the cache creation breakdown and clamps the one-hour count to total cache writes. Session, location, and daily aggregates preserve the new count. Cost estimation applies separate rates and threshold pricing. Reports and automation attribution pass the one-hour count into cost calculation. Schema version 6 records the new persisted field. Merge Risk: 🟡 Moderate · up to The PR fixes one-hour cache-write pricing but still underreports those writes for long-context requests over 200K tokens, and malformed negative breakdown values can reduce reported usage; a failed first-run rescan can also temporarily hide cached usage. These bounded correctness and availability issues should be fixed or explicitly accepted before merge. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Linked Issues checkExplanation The PR fully addresses the 1-hour cache TTL pricing objective in issue Resolution Implement date-bounded Sonnet 5 introductory pricing in this PR, or split the work and link this PR to an issue scoped only to the 1-hour cache TTL pricing objective. Do not close issue Full details: Out of Scope Changes checkExplanation The changes are confined to Claude usage parsing, aggregation, pricing, tests, and schema migration. These changes directly support the 1-hour cache TTL pricing objective and do not introduce unrelated functionality. Full details: Description checkExplanation The description is detailed and covers the change, rationale, linked issue, testing results, risks, compatibility, and follow-up scope. It does not reproduce every template heading or checklist item, and it lacks the requested visual-proof format, but the required technical information is substantially present.
✨ 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: 2
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: e5c1cc36-60a5-4b81-9373-8bb520a1d8c2
📒 Files selected for processing (10)
src/main/claude-usage/claude-model-pricing.test.tssrc/main/claude-usage/claude-model-pricing.tssrc/main/claude-usage/claude-usage-automation-attribution.tssrc/main/claude-usage/claude-usage-report-aggregation.tssrc/main/claude-usage/scanner.test.tssrc/main/claude-usage/store.test.tssrc/main/claude-usage/store.tssrc/main/claude-usage/transcript-record-parser.tssrc/main/claude-usage/types.tssrc/main/claude-usage/usage-aggregation.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 1 remains after this review.
| calculateTieredCost( | ||
| write1hTokens, | ||
| pricing.cacheWrite1h, | ||
| pricing.cacheWrite1hAboveThreshold, | ||
| pricing.thresholdTokens |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift
Apply the long-context rate to the full request. The estimator tiers write1hTokens progressively. A 400K-token request must charge all one-hour writes at $12/MTok, or $4.80, not the current $3.60. Anthropic selects premium pricing when total input, including cache writes and reads, exceeds 200K. (docs.anthropic.com)
src/main/claude-usage/claude-model-pricing.ts#L239-L243: preserve per-request tier information, then price all request tokens at the selected tier.src/main/claude-usage/claude-model-pricing.test.ts#L25-L27: expect$4.80and add a mixed 5-minute/one-hour long-context case.
📍 Affects 2 files
src/main/claude-usage/claude-model-pricing.ts#L239-L243(this comment)src/main/claude-usage/claude-model-pricing.test.ts#L25-L27
| // Why: clamp so the implied 5m remainder can never go negative on a partial row. | ||
| const cacheWrite1hTokens = Math.min( | ||
| usage?.cache_creation?.ephemeral_1h_input_tokens ?? 0, | ||
| cacheWriteTokens | ||
| ) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Clamp the lower bound. A negative ephemeral_1h_input_tokens survives Math.min and can offset valid one-hour totals during aggregation. Use Math.max(0, ...).
Proposed fix
- const cacheWrite1hTokens = Math.min(
- usage?.cache_creation?.ephemeral_1h_input_tokens ?? 0,
- cacheWriteTokens
- )
+ const cacheWrite1hTokens = Math.max(
+ 0,
+ Math.min(usage?.cache_creation?.ephemeral_1h_input_tokens ?? 0, cacheWriteTokens)
+ )📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| // Why: clamp so the implied 5m remainder can never go negative on a partial row. | |
| const cacheWrite1hTokens = Math.min( | |
| usage?.cache_creation?.ephemeral_1h_input_tokens ?? 0, | |
| cacheWriteTokens | |
| ) | |
| // Why: clamp so the implied 5m remainder can never go negative on a partial row. | |
| const cacheWrite1hTokens = Math.max( | |
| 0, | |
| Math.min(usage?.cache_creation?.ephemeral_1h_input_tokens ?? 0, cacheWriteTokens) | |
| ) |
Sonnet 5 was billed at $3/$15 (plus derived $0.30 read / $3.75 5m write / $6 1h write). Anthropic's pricing page states the $2/$10 launch price, announced as introductory through 2026-08-31, is now the standard price and the 2026-09-01 increase to $3/$15 will not occur. So no date dimension is needed: one rate covers historical and future days, including the All range that re-prices every past day on each render.
ELI5
Claude charges more to write something into its prompt cache if you ask it to stay
cached for an hour instead of five minutes — 2x the base input price instead of 1.25x.
Orca's usage stats knew only about the cheaper 5-minute rate, so every 1-hour cache
write showed up at 62.5% of what it actually cost. Anyone whose Claude Code sessions
use 1-hour caching (the split is already recorded in the on-disk transcripts) was
seeing an "Estimated cost" that was too low. Now Orca reads the per-TTL breakdown and
prices each share at its real rate.
Separately, Orca charged Sonnet 5 at $3/$15 per million tokens. Sonnet 5 costs $2/$10 —
the launch price, announced as "introductory through 2026-08-31", was made permanent and
the scheduled increase was cancelled. That row is now the published rate, which also fixes
the historical over-estimate the All range recomputes on every render.
Root cause
src/main/claude-usage/claude-model-pricing.ts:1-11—ClaudeModelPricinghad oneflat
cacheWrite: numberand no per-TTL dimension. Every row'scacheWriteisinput * 1.25, i.e. the 5-minute rate.src/main/claude-usage/claude-model-pricing.ts:182-221—estimateCostUsd(...)billedthe entire write bucket through a single
calculateTieredCost(cacheWriteTokens, pricing.cacheWrite, ...)call, so a 1-hour write was charged as if it were a 5-minute one.src/main/claude-usage/transcript-record-parser.ts:103— the parser read onlyusage.cache_creation_input_tokens. The nestedusage.cache_creation.{ephemeral_5m,ephemeral_1h}_input_tokensobject was not evendeclared on the source-record type, so the split was discarded at parse time and could
never reach pricing. Real transcripts under
~/.claude/projects/**/*.jsonldo carry it,with large non-zero
ephemeral_1h_input_tokensvalues.Confirmed against the
claude-apiskill,shared/prompt-caching.md:142: "Cache reads cost~0.1x base input price. Cache writes cost 1.25x for 5-minute TTL, 2x for 1-hour TTL."
Proof
New test file:
src/main/claude-usage/claude-model-pricing.test.tsExtended:
src/main/claude-usage/scanner.test.tsCommand:
pnpm test src/main/claude-usage/claude-model-pricing.test.tsandpnpm test src/main/claude-usage/scanner.test.tsBEFORE (tests written, fix not yet applied)
(Reverting every production hunk at once, keeping only the tests, is redder still:
Tests 9 failed | 29 passed (38)across the whole directory, becausescanner.test.ts > Claude usage aggregationand the newstore.test.tscase alsodepend on the split.)
AFTER (whole directory, including the two sibling suites and the new store-level case)
pnpm run tc:nodeandpnpm run check:code-quality:changedare clean.Follow-up commit: shared long-context allowance
Review caught that pricing the 5m and 1h buckets with two independent
calculateTieredCostcalls handed each bucket its own 200k below-thresholdallowance. For a Sonnet row with a mixed bucket that made the estimate go down
versus billing the same tokens entirely at the 5m rate — the opposite of this PR's
intent — and made cost non-monotonic in the 1h share:
Fixed by splitting the single 200k allowance between the two buckets in proportion
to each one's share of the write total. Pure-5m rows are byte-identical to
main;the all-1h case still prices at $3.60. Two regression tests cover the mixed value
($2.925) and monotonicity; both fail on the previous head of this branch.
Second commit: Sonnet 5 priced at its published rate (defect 1)
Review pushed back on the original punt ("the introductory period ends 2026-08-31, after
which the hardcoded rate is correct") and was right to: the All range re-prices every
historical day on each render, so an over-estimate on tokens spent during the launch window
never expires.
Checking the authoritative source changed the shape of the fix. Anthropic's pricing page
(
platform.claude.com/docs/en/about-claude/pricing) carries this note:So Sonnet 5 never had two rates. The published row is $2 input / $10 output / $0.20 cache
hit / $2.50 5m write / $4 1h write per MTok, for every day past and future. A date dimension
in
MODEL_PRICINGwould encode a $3/$15 tier that no token was ever billed at; the correctminimal fix is the flat rate.
claude-model-pricing.tskeeps its one-rate-per-model shape —no new type fields, no per-row date list, no allocation on the pricing path.
The old row was wrong for all Sonnet 5 usage, not just the window, so this raises spend
accuracy for current days too (the previous row over-estimated Sonnet 5 by 50%).
New test file:
src/main/claude-usage/claude-usage-report-aggregation.test.ts— prices aday inside the announced window (
2026-08-15) and a day after it (2026-09-15) throughbuildSummary(..., 'all'), which is exactly the path the reviewer flagged.Extended:
claude-model-pricing.test.ts(per-rate assertions incl. both cache-write TTLs).Updated:
store.test.ts(two Sonnet 5 expectations rebased onto the published rate:22.05 -> 14.7,6.615 -> 4.41).BEFORE (tests written, rate not yet corrected)
AFTER
Risk
Low. The change is confined to
src/main/claude-usage/;grepfinds no consumer ofClaudeUsagePersistedState,ClaudeUsageDailyAggregate,ClaudeUsageLocationBreakdown,or
ClaudeUsageParsedTurnoutside that directory. No shared/IPC type(
src/shared/claude-usage-types.ts) changed, so there is no renderer or remote-wiresurface to negotiate — the 1-hour split is kept main-process-local via a lookup map in
buildBreakdownrather than being added toClaudeUsageBreakdownRow. Transcripts withoutthe
cache_creationobject parse tocacheWrite1hTokens: 0and price exactly as before,so the change is a strict superset of current behavior (pinned by a test).
User-facing regressions
not a regression — the previous number was under-reported by up to 37.5% of the cache-write
line. Costs for 5-minute-only usage are unchanged to the cent.
SCHEMA_VERSIONgoes5 -> 6 in
src/main/claude-usage/store.tsbecause existing caches never recorded the splitand would otherwise stay stuck at the 5-minute rate.
normalizePersistedStatealreadypreserves the
scanState.enabledopt-in across resets, so tracking stays on; only thederived cache is rebuilt. This is the same mechanism used for the v5 bump. Rolling back to
an older Orca is also safe: it sees the version mismatch and resets the same way.
cacheWriteTokensremains the full write total, 5m + 1h), so the Stats charts, share card, session rows, and
cacheReuseRaterender identically. Automation run cost(
claude-usage-automation-attribution.ts) and the Stats model breakdown were both wired tothe new bucket so the two never disagree. Codex usage pricing
(
src/main/codex-usage/) has its ownestimateCostUsdand is untouched.$3/$15row over-pricedevery Sonnet 5 token, historical and current. Correcting it lowers the Sonnet 5 line by a
third; the two defects push in opposite directions, which is exactly the partial cancellation
the reporter measured (Orca $3,860.48 vs their tool $3,914.30 on the same corpus).
MODEL_PRICINGand is applied atrender time from cached token counts, so the corrected number appears immediately.
SCHEMA_VERSIONstays at 6.Follow-up (not in this PR)
claude-sonnet-4-6still carriesSONNET_LONG_CONTEXT_PRICING(>200k tokens at $6/$22.50),but the pricing page's Long context section now reads: "Claude 4.6 and later models ... include
the full 1M token context window at standard pricing." That looks like a third over-estimate,
independent of this issue — filing separately rather than widening this PR.
Fixes #15993 — both defects are now covered. Defect 2 (1-hour cache writes at 2x base
input) in
a7963108a6a+ec6a2de711c; defect 1 (Sonnet 5 rate) in591fbd41ddb.Defect 1 landed as a flat-rate correction rather than the date dimension the issue proposes,
because the $3/$15 tier the issue expects on 2026-09-01 was cancelled and never took effect —
$2/$10 is the standard price for every day, so there is no second rate to date-bound. The
All-range re-pricing concern is covered by a test that prices a launch-window day and apost-window day through
buildSummary(..., 'all').