Repository navigation
fix(streaming): let a later usage event zero out stale cache counts (#40736) - #42330
Conversation
…40736) The usage merger only replaced cache_creation_input_tokens and cache_read_input_tokens with a positive value, so when Anthropic's message_delta restated the cache block with a 0 write, the 58k write from message_start survived next to the 58k read. prompt_tokens minus both cache counts then went negative and the write was billed twice A usage event that reports any prompt-side count is now authoritative for both cache fields, zeros included. An event with no prompt-side counts, such as an output-only message_delta, still leaves the earlier values alone
…cached input in the cache count merger test
|
I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".
|
|
|
bugbot run |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit 9a4b19a. Configure here.
…explicit_zero_cache # Conflicts: # tests/test_litellm/litellm_core_utils/test_streaming_chunk_builder_utils.py
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
Replaces #40845 (head 9a4b19a) on a
litellm_branch so the CircleCI suites can run on it; the commits and their authorship are unchanged, so the fix is @muhammadwaqar12's and the regression tests and the merge of main are mineTLDR
Problem this solves:
How it solves it:
User Flow
Before: a developer whose app streams a cached Claude prompt through the proxy gets a usage block that still counts a cache write the provider took back, so the app's derived uncached input goes negative
POST https://litellm-domain/v1/chat/completionswith"stream": true,"stream_options": {"include_usage": true}, and a system block of about 58k tokens marked"cache_control": {"type": "ephemeral"}, routed to Claude Opus on Bedrockusagechunk anddata: [DONE]prompt_tokens: 58354,cache_read_input_tokens: 58352, andcache_creation_input_tokens: 58352, even though the provider's final count for this request said the cache was read, not written (thecache_creation_token_detailsin the same block already reads0and0)prompt_tokens - cache_read_input_tokens - cache_creation_input_tokens, stores-58350, and their usage dashboard shows negative input tokens for that userAfter: the same stream's usage block keeps the provider's final counts, so the derived uncached input is
2POST https://litellm-domain/v1/chat/completionswith"stream": true,"stream_options": {"include_usage": true}, and a system block of about 58k tokens marked"cache_control": {"type": "ephemeral"}, routed to Claude Opus on Bedrockusagechunk anddata: [DONE]prompt_tokens: 58354,cache_read_input_tokens: 58352, andcache_creation_input_tokens: 0, matching the provider's final count58354 - 58352 - 0 = 2and the dashboard shows 2 uncached input tokens for that userRelevant issues
Fixes #40736
Affected release
Linear ticket
Resolves LIT-7585
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
uv run pytest tests/test_litellm/<your_test_file>.py -v. Leave the suites (make test-unit-*,make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or more@greptileaito re-request a review after pushing changes)Screenshots / Proof of Fix
Both legs ran a LiteLLM proxy booted with
--num_workers 2(two server processes behind one random port) in front of Claude Opus 5 on Bedrock through the Invoke route inus-east-1, real spend. Each of the three unified endpoints got the same streamed request twice with a fresh 800-clause system block markedcache_control(first request: cache write expected, second request: cache read expected). What is shown is the usage the client receives, plus, for chat, the uncached input the reporter's app derives asprompt_tokens - cache_read_input_tokens - cache_creation_input_tokensConfig,
lit7585_config.yaml:Boot:
python litellm/proxy/proxy_cli.py --config lit7585_config.yaml --port $PORT --num_workers 2Filler, unique per run so the first request is always a cache write:
FILLER=$(python3 -c "print(' '.join(f'clause {i} of the reference manual for run $RUN_ID states that widget {i % 97} must be inspected before shipment' for i in range(800)))")Request bodies (
body.jsonbelow is one of these, sent twice unchanged):{"model": "bedrock-opus", "stream": true, "stream_options": {"include_usage": true}, "max_tokens": 40, "messages": [{"role": "system", "content": [{"type": "text", "text": "$FILLER", "cache_control": {"type": "ephemeral"}}]}, {"role": "user", "content": "Reply with the single word OK."}]}{"model": "bedrock-opus", "stream": true, "max_output_tokens": 40, "input": [{"role": "system", "content": [{"type": "input_text", "text": "$FILLER", "cache_control": {"type": "ephemeral"}}]}, {"role": "user", "content": "Reply with the single word OK."}]}{"model": "bedrock-opus", "stream": true, "max_tokens": 40, "system": [{"type": "text", "text": "$FILLER", "cache_control": {"type": "ephemeral"}}], "messages": [{"role": "user", "content": "Reply with the single word OK."}]}The output shown for chat is the final
usageSSE chunk, for responses theresponse.completedevent'susage, and for messages theusageof themessage_startandmessage_deltaeventsThe reporter's symptom needs one stream whose
message_startreports a cache write and whosemessage_deltathen reports a cache read withcache_creation_input_tokens: 0. That sequence never occurred live during this QA: 20 Bedrock Invoke streams (12 plain, 8 started 400 ms apart on one identical cached prompt) and 8 Anthropic-direct streams sent straight to the providers all reported the same cache counts in both events, and so did the 18 proxy streams of the two legs. So the legs below show that the plain write and read shapes read the same before and after on every endpoint, and the reporter's exact event sequence is covered by the regression tests named under CaveatsBefore (3597d61)
/v1/chat/completions
curl -sS -N http://localhost:59448/v1/chat/completions -H 'Authorization: Bearer sk-lit7585-local' -H 'Content-Type: application/json' -d @body.json{"completion_tokens": 1, "prompt_tokens": 35217, "total_tokens": 35218, "completion_tokens_details": {"reasoning_tokens": 0, "text_tokens": 1}, "prompt_tokens_details": {"cached_tokens": 0, "text_tokens": 14, "cache_write_tokens": 35203, "cache_creation_tokens": 35203, "cache_creation_token_details": {"ephemeral_5m_input_tokens": 35203, "ephemeral_1h_input_tokens": 0}}, "cost": 0.24212512500000002, "cache_creation_input_tokens": 35203, "cache_read_input_tokens": 0}{"completion_tokens": 1, "prompt_tokens": 35217, "total_tokens": 35218, "completion_tokens_details": {"reasoning_tokens": 0, "text_tokens": 1}, "prompt_tokens_details": {"cached_tokens": 35203, "text_tokens": 14, "cache_write_tokens": 0, "cache_creation_tokens": 0, "cache_creation_token_details": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 0}}, "cost": 0.01946615, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 35203}/v1/responses
curl -sS -N http://localhost:59448/v1/responses -H 'Authorization: Bearer sk-lit7585-local' -H 'Content-Type: application/json' -d @body.json{"input_tokens": 35217, "input_tokens_details": {"cached_tokens": 0, "text_tokens": 14, "cache_write_tokens": 35203}, "output_tokens": 4, "output_tokens_details": {"reasoning_tokens": 0, "text_tokens": 4}, "total_tokens": 35221, "cost": 0.242207625}{"input_tokens": 35217, "input_tokens_details": {"cached_tokens": 35203, "text_tokens": 14, "cache_write_tokens": 0}, "output_tokens": 4, "output_tokens_details": {"reasoning_tokens": 0, "text_tokens": 4}, "total_tokens": 35221, "cost": 0.01954865}/v1/messages
curl -sS -N http://localhost:59448/v1/messages -H 'Authorization: Bearer sk-lit7585-local' -H 'Content-Type: application/json' -d @body.jsonAfter (9a4b19a)
/v1/chat/completions
curl -sS -N http://localhost:26333/v1/chat/completions -H 'Authorization: Bearer sk-lit7585-local' -H 'Content-Type: application/json' -d @body.json{"completion_tokens": 1, "prompt_tokens": 35217, "total_tokens": 35218, "completion_tokens_details": {"reasoning_tokens": 0, "text_tokens": 1}, "prompt_tokens_details": {"cached_tokens": 0, "text_tokens": 14, "cache_write_tokens": 35203, "cache_creation_tokens": 35203, "cache_creation_token_details": {"ephemeral_5m_input_tokens": 35203, "ephemeral_1h_input_tokens": 0}}, "cost": 0.24212512500000002, "cache_creation_input_tokens": 35203, "cache_read_input_tokens": 0}{"completion_tokens": 1, "prompt_tokens": 35217, "total_tokens": 35218, "completion_tokens_details": {"reasoning_tokens": 0, "text_tokens": 1}, "prompt_tokens_details": {"cached_tokens": 35203, "text_tokens": 14, "cache_write_tokens": 0, "cache_creation_tokens": 0, "cache_creation_token_details": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 0}}, "cost": 0.01946615, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 35203}/v1/responses
curl -sS -N http://localhost:26333/v1/responses -H 'Authorization: Bearer sk-lit7585-local' -H 'Content-Type: application/json' -d @body.json{"input_tokens": 35217, "input_tokens_details": {"cached_tokens": 0, "text_tokens": 14, "cache_write_tokens": 35203}, "output_tokens": 1, "output_tokens_details": {"reasoning_tokens": 0, "text_tokens": 1}, "total_tokens": 35218, "cost": 0.24212512500000002}{"input_tokens": 35217, "input_tokens_details": {"cached_tokens": 35203, "text_tokens": 14, "cache_write_tokens": 0}, "output_tokens": 1, "output_tokens_details": {"reasoning_tokens": 0, "text_tokens": 1}, "total_tokens": 35218, "cost": 0.01946615}/v1/messages
curl -sS -N http://localhost:26333/v1/messages -H 'Authorization: Bearer sk-lit7585-local' -H 'Content-Type: application/json' -d @body.jsonObserved alongside, none caused or changed by this PR:
inputcounts include cached tokens; messagesinput_tokensexcludes themcache_write_tokensonly, nocache_creation_input_tokenskeyoutput_tokensinmessage_startalready equals the final countType
Bug Fix
Test
Caveats (if any)
Medium
tests/test_litellm/litellm_core_utils/test_streaming_chunk_builder_utils.py::test_anthropic_stream_usage_takes_cache_counts_from_last_event_that_reports_them, three cases through the real Anthropic stream parser and the merger, all failing on the merge base and passing hereLow
message_deltawithout cache fields inherits themessage_startcounts; thedelta_reports_input_and_output_onlycase pins that, so the earlier worry that such an event would clear both counts does not apply at this headtests/local_testingandtests/llm_translationdo not run on a fork head, sotests/local_testing/test_anthropic_prompt_caching.pywas run locally at this tip against the real Anthropic API: 7 passed (the streaming case included), 2 skipped, 4 failedtest_anthropic_vertex_ai_prompt_cachingnames a Vertex model that is no longer in the cost map, andtest_litellm_anthropic_prompt_caching_systemandtest_litellm_anthropic_prompt_caching_toolsassert a mockedpostcall without thelogging_objkwarg the handler now passes; none of them reach the usage mergertest_jev_classifiercases that fail on everylitellm_branch since the JEV launch commits (83ec5d6 and siblings) landed on main before the merge base, and on main's own pipeline 89979 at cc1a315get_model_infocases), test_bad_database_url, and proxy_logging_guardrails_model_info_tests (7tests/otel_tests/test_e2e_budgeting.pycases expecting a 429 and getting a 422) fail identically on that same main pipeline 89979, whose commit cc1a315 is an ancestor of the merge basetest_fal_h3_video_create_uses_canonical_body_and_status_pathcame in with feat(fal_ai): add MiniMax H3 text-to-video and reference-to-video #42286 before the merge base and fix(fal_ai): surface fal errors in video status and content instead of completed and generic 500 #42306 changed it on main afterwardstest_case_bills_expected_cost[gpt-5.6-responses_previous_response_id]came in with test(integration): embeddings, rerank, completions and moderations cost cases #42020 before the merge base, sends a non-streaming/v1/responsesrequest the proxy rejects with a 403 at Responses id authorization before any usage merging, and fails the same way on #42323's branch at the same merge base; it failed here twice (the first run and a from-failed rerun), and main's next scheduled pipeline has not run on that commit yetupload-coveragedid not run because the jobs above feed itFinal Attestation
The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR
9a4b19a passes /live-pr-risk