Fix Anthropic usage double-counting cache in input - #617
Open
elrensmin wants to merge 1 commit into
Open
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
Anthropic's message_start/message_delta stored input_tokens verbatim, but Anthropic's input_tokens already includes cache reads+writes. total_tokens was then recomputed as input+output+cache_read+cache_write, double-counting cache (e.g. input=100, cache_read=40, cache_write=25 → total=172). Every OpenAI-family path (openai_compatible, openai_codex) instead stores fresh input = max(0, input - cache_read - cache_write). Downstream consumers (session_stats.py:83, session_usage.py, context_window.py:183, _response_cost) all assume the fresh convention, so Anthropic silently over-reported stats and overcharged cost.
Fix
store fresh input in both _usage_from_message_start and _apply_message_delta_usage, matching the OpenAI convention; total_tokens computed from fresh input.
Tests
test_tau_ai.py updated to the corrected numbers (input 100→35, total 172→107); test_session_stats.py already encodes the correct convention, unchanged.
Validation
uv run pytest tests/test_tau_ai.py tests/test_session_stats.py (89 passed).