Skip to content

fix(claude-usage): bill 1-hour cache writes at 2x base input - #16878

Merged
nwparker merged 3 commits into
mainfrom
nwparker/fix-15993-claude-cost-sonnet5-pricing
Aug 28, 2026
Merged

nwparker merged 3 commits into
mainfrom
nwparker/fix-15993-claude-cost-sonnet5-pricing

Conversation

@nwparker

@nwparker nwparker commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​284 $\color{#cf222e}{\Huge{\mathbf{−}}}$​28 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​256
Prod 7 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​102 $\color{#cf222e}{\Huge{\mathbf{−}}}$​29 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​73

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 — ClaudeModelPricing had one
    flat cacheWrite: number and no per-TTL dimension. Every row's cacheWrite is
    input * 1.25, i.e. the 5-minute rate.
  • src/main/claude-usage/claude-model-pricing.ts:182-221 — estimateCostUsd(...) billed
    the 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 only
    usage.cache_creation_input_tokens. The nested
    usage.cache_creation.{ephemeral_5m,ephemeral_1h}_input_tokens object was not even
    declared on the source-record type, so the split was discarded at parse time and could
    never reach pricing. Real transcripts under ~/.claude/projects/**/*.jsonl do carry it,
    with large non-zero ephemeral_1h_input_tokens values.

Confirmed against the claude-api skill, 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.ts
Extended: src/main/claude-usage/scanner.test.ts

Command: pnpm test src/main/claude-usage/claude-model-pricing.test.ts and
pnpm test src/main/claude-usage/scanner.test.ts

BEFORE (tests written, fix not yet applied)

 FAIL  src/main/claude-usage/claude-model-pricing.test.ts > estimateCostUsd cache-write TTL rates > bills 1-hour cache writes at 2x base input
AssertionError: expected 6.25 to be close to 10, received difference is 3.75, but expected 0.005

 FAIL  src/main/claude-usage/claude-model-pricing.test.ts > estimateCostUsd cache-write TTL rates > splits a mixed write bucket without double-billing the 1-hour share
AssertionError: expected 6.25 to be close to 7.75, received difference is 1.5, but expected 0.005

 FAIL  src/main/claude-usage/claude-model-pricing.test.ts > estimateCostUsd cache-write TTL rates > applies the long-context tier to 1-hour writes
AssertionError: expected 2.25 to be close to 3.6, received difference is 1.35, but expected 0.005

 Test Files  1 failed (1)
      Tests  3 failed | 4 passed (7)
 FAIL  src/main/claude-usage/scanner.test.ts > parseClaudeUsageRecord > extracts token usage from assistant transcript lines
AssertionError: expected { sessionId: 'session-1', ...(8) } to deeply equal { sessionId: 'session-1', ...(9) }

 FAIL  src/main/claude-usage/scanner.test.ts > parseClaudeUsageRecord > splits the cache-write total by TTL when the breakdown is present
AssertionError: expected undefined to be 400 // Object.is equality

 FAIL  src/main/claude-usage/scanner.test.ts > parseClaudeUsageRecord > clamps a 1-hour breakdown that exceeds the reported cache-write total
AssertionError: expected undefined to be 100 // Object.is equality

 FAIL  src/main/claude-usage/scanner.test.ts > parseClaudeUsageRecord > merges duplicate streamed assistant usage by message and request id
AssertionError: expected [ { sessionId: 'session-1', ...(8) } ] to deeply equal [ { sessionId: 'session-1', ...(9) } ]

 Test Files  1 failed (1)
      Tests  4 failed | 2 passed (6)

(Reverting every production hunk at once, keeping only the tests, is redder still:
Tests 9 failed | 29 passed (38) across the whole directory, because
scanner.test.ts > Claude usage aggregation and the new store.test.ts case also
depend on the split.)

AFTER (whole directory, including the two sibling suites and the new store-level case)

$ pnpm test src/main/claude-usage

 RUN  v4.1.5

 Test Files  5 passed (5)
      Tests  40 passed (40)

pnpm run tc:node and pnpm run check:code-quality:changed are clean.

Follow-up commit: shared long-context allowance

Review caught that pricing the 5m and 1h buckets with two independent
calculateTieredCost calls handed each bucket its own 200k below-threshold
allowance. 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:

400k writes on claude-sonnet-4-6, by 1h share:
0 -> $2.25   50k -> $2.175   100k -> $2.10   200k -> $1.95   300k -> $2.775   400k -> $3.60

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:

The $2/$10 per million input/output token pricing for Claude Sonnet 5, announced at launch
as introductory pricing through August 31, 2026, is now the standard price. The previously
scheduled increase to $3/$15 per million input/output tokens on September 1, 2026 will not
occur.

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_PRICING would encode a $3/$15 tier that no token was ever billed at; the correct
minimal fix is the flat rate. claude-model-pricing.ts keeps 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 a
day inside the announced window (2026-08-15) and a day after it (2026-09-15) through
buildSummary(..., '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)

 FAIL  src/main/claude-usage/claude-model-pricing.test.ts > estimateCostUsd Claude Sonnet 5 rates > bills base input at $2/MTok
AssertionError: expected 3 to be close to 2, received difference is 1, but expected 0.005

 FAIL  src/main/claude-usage/claude-model-pricing.test.ts > estimateCostUsd Claude Sonnet 5 rates > bills output at $10/MTok
AssertionError: expected 15 to be close to 10, received difference is 5, but expected 0.005

 FAIL  src/main/claude-usage/claude-model-pricing.test.ts > estimateCostUsd Claude Sonnet 5 rates > bills cache hits at $0.20/MTok
AssertionError: expected 0.3 to be close to 0.2, received difference is 0.09999999999999998, but expected 0.005

 FAIL  src/main/claude-usage/claude-model-pricing.test.ts > estimateCostUsd Claude Sonnet 5 rates > bills 5-minute cache writes at $2.50/MTok and 1-hour writes at $4/MTok
AssertionError: expected 3.75 to be close to 2.5, received difference is 1.25, but expected 0.005

 FAIL  src/main/claude-usage/claude-usage-report-aggregation.test.ts > buildSummary Claude Sonnet 5 pricing over time > prices an introductory-window day and a post-window day at the same $2/$10 rate
AssertionError: expected 18 to be close to 12, received difference is 6, but expected 0.005

 FAIL  src/main/claude-usage/claude-usage-report-aggregation.test.ts > buildSummary Claude Sonnet 5 pricing over time > sums both days in the All range without re-pricing history upward
AssertionError: expected 36 to be close to 24, received difference is 12, but expected 0.005

 Test Files  2 failed (2)
      Tests  6 failed | 10 passed (16)

AFTER

$ npx vitest run --config config/vitest.config.ts src/main/claude-usage

 RUN  v4.1.5

 Test Files  6 passed (6)
      Tests  47 passed (47)
   Duration  815ms
$ npx vitest run --config config/vitest.config.ts \
    src/renderer/src/components/usage-overview-model.test.ts src/main/rate-limits/

 RUN  v4.1.5

 Test Files  45 passed (45)
      Tests  444 passed (444)
   Duration  6.56s

Risk

Low. The change is confined to src/main/claude-usage/; grep finds no consumer of
ClaudeUsagePersistedState, ClaudeUsageDailyAggregate, ClaudeUsageLocationBreakdown,
or ClaudeUsageParsedTurn outside that directory. No shared/IPC type
(src/shared/claude-usage-types.ts) changed, so there is no renderer or remote-wire
surface to negotiate — the 1-hour split is kept main-process-local via a lookup map in
buildBreakdown rather than being added to ClaudeUsageBreakdownRow. Transcripts without
the cache_creation object parse to cacheWrite1hTokens: 0 and price exactly as before,
so the change is a strict superset of current behavior (pinned by a test).

User-facing regressions

  • Estimated Claude cost goes up for anyone with 1-hour cache writes. That is the fix,
    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.
  • One full Claude transcript rescan on first launch after upgrade. SCHEMA_VERSION goes
    5 -> 6 in src/main/claude-usage/store.ts because existing caches never recorded the split
    and would otherwise stay stuck at the 5-minute rate. normalizePersistedState already
    preserves the scanState.enabled opt-in across resets, so tracking stays on; only the
    derived 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.
  • Checked adjacent behavior: token counts shown in the UI are untouched (cacheWriteTokens
    remains the full write total, 5m + 1h), so the Stats charts, share card, session rows, and
    cacheReuseRate render identically. Automation run cost
    (claude-usage-automation-attribution.ts) and the Stats model breakdown were both wired to
    the new bucket so the two never disagree. Codex usage pricing
    (src/main/codex-usage/) has its own estimateCostUsd and is untouched.
  • Estimated Claude cost goes down ~33% for Sonnet 5 usage. The old $3/$15 row over-priced
    every 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).
  • No rescan needed for this commit. The rate lives in MODEL_PRICING and is applied at
    render time from cached token counts, so the corrected number appears immediately.
    SCHEMA_VERSION stays at 6.

Follow-up (not in this PR)

claude-sonnet-4-6 still carries SONNET_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) in 591fbd41ddb.
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 a
post-window day through buildSummary(..., 'all').

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.
@coderabbitai

coderabbitai Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The 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 a7963

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)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning The PR fully addresses the 1-hour cache TTL pricing objective in issue #15993, including parsing, aggregation, pricing, long-context handling, and cache migration. It does not address the issue's sepa… 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 #15993 until both objectives are addressed or explicit…
Docstring Coverage ⚠️ Warning Docstring coverage is 9.09% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 11 functions across 10 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Out of Scope Changes check ✅ Passed 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 unrelate…
Title check ✅ Passed The title clearly and concisely describes the primary change: billing 1-hour Claude cache writes at 2× the base input price.
Description check ✅ Passed 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, …
Full details: Linked Issues check

Explanation

The PR fully addresses the 1-hour cache TTL pricing objective in issue #15993, including parsing, aggregation, pricing, long-context handling, and cache migration. It does not address the issue's separate Sonnet 5 introductory-pricing objective.

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 #15993 until both objectives are addressed or explicitly separated.

Full details: Out of Scope Changes check

Explanation

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 check

Explanation

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.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: e5c1cc36-60a5-4b81-9373-8bb520a1d8c2

📥 Commits

Reviewing files that changed from the base of the PR and between 1485aa4 and a796310.

📒 Files selected for processing (10)
  • src/main/claude-usage/claude-model-pricing.test.ts
  • src/main/claude-usage/claude-model-pricing.ts
  • src/main/claude-usage/claude-usage-automation-attribution.ts
  • src/main/claude-usage/claude-usage-report-aggregation.ts
  • src/main/claude-usage/scanner.test.ts
  • src/main/claude-usage/store.test.ts
  • src/main/claude-usage/store.ts
  • src/main/claude-usage/transcript-record-parser.ts
  • src/main/claude-usage/types.ts
  • src/main/claude-usage/usage-aggregation.ts

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

Comment on lines +239 to +243
calculateTieredCost(
write1hTokens,
pricing.cacheWrite1h,
pricing.cacheWrite1hAboveThreshold,
pricing.thresholdTokens

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.

🎯 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.80 and 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

Comment on lines +111 to +115
// 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
)

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.

🎯 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.

Suggested change
// 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.
@nwparker
nwparker merged commit 3d796b8 into main Aug 28, 2026
93 of 95 checks passed
@nwparker
nwparker deleted the nwparker/fix-15993-claude-cost-sonnet5-pricing branch August 28, 2026 03:13
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 30, 2026
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
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.

[Bug]: Claude cost estimate ignores Sonnet 5 launch pricing and 1-hour cache TTL

1 participant