Skip to content

fix(streaming): let a later usage event zero out stale cache counts (#40736) - #42330

Merged
shreshth-berri merged 4 commits into
mainfrom
litellm_stream_usage_explicit_zero_cache
Sep 22, 2026
Merged

shreshth-berri merged 4 commits into
mainfrom
litellm_stream_usage_explicit_zero_cache

Conversation

@devin-ai-integration

@devin-ai-integration devin-ai-integration Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

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 mine

TLDR

Problem this solves:

  • A streamed cache write count survives after a later usage event reports it as 0
  • The merged usage then counts a 58k write and a 58k read together
  • Uncached input derived from it goes negative and the write is billed twice

How it solves it:

  • A usage event that reports any prompt-side count now sets both cache fields
  • Explicit zeros in that event replace the earlier values
  • An output-only event still leaves the earlier cache counts alone

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

  1. They send POST https://litellm-domain/v1/chat/completions with "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 Bedrock
  2. Their app reads the SSE stream to its end, through the final usage chunk and data: [DONE]
  3. That usage chunk carries prompt_tokens: 58354, cache_read_input_tokens: 58352, and cache_creation_input_tokens: 58352, even though the provider's final count for this request said the cache was read, not written (the cache_creation_token_details in the same block already reads 0 and 0)
  4. Their app computes uncached input as prompt_tokens - cache_read_input_tokens - cache_creation_input_tokens, stores -58350, and their usage dashboard shows negative input tokens for that user

After: the same stream's usage block keeps the provider's final counts, so the derived uncached input is 2

  1. They send POST https://litellm-domain/v1/chat/completions with "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 Bedrock
  2. Their app reads the SSE stream to its end, through the final usage chunk and data: [DONE]
  3. That usage chunk carries prompt_tokens: 58354, cache_read_input_tokens: 58352, and cache_creation_input_tokens: 0, matching the provider's final count
  4. Their app computes 58354 - 58352 - 0 = 2 and the dashboard shows 2 uncached input tokens for that user

Relevant 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

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. 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
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have received a Greptile Confidence Score of at least 4/5 before requesting a maintainer review (Greptile reviews automatically once the PR is opened; only comment @greptileai to 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 in us-east-1, real spend. Each of the three unified endpoints got the same streamed request twice with a fresh 800-clause system block marked cache_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 as prompt_tokens - cache_read_input_tokens - cache_creation_input_tokens

Config, lit7585_config.yaml:

model_list:
  - model_name: bedrock-opus
    litellm_params:
      model: bedrock/invoke/us.anthropic.claude-opus-5
      aws_access_key_id: os.environ/AWS_ACCESS_KEY_ID
      aws_secret_access_key: os.environ/AWS_SECRET_ACCESS_KEY
      aws_region_name: us-east-1

general_settings:
  master_key: sk-lit7585-local

Boot: python litellm/proxy/proxy_cli.py --config lit7585_config.yaml --port $PORT --num_workers 2

Filler, 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.json below 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 usage SSE chunk, for responses the response.completed event's usage, and for messages the usage of the message_start and message_delta events

The reporter's symptom needs one stream whose message_start reports a cache write and whose message_delta then reports a cache read with cache_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 Caveats

Before (3597d61)

/v1/chat/completions

  1. Cache write: 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}
    derived uncached input = 35217 - 0 - 35203 = 14
  2. Cache read, same command and body:
    {"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}
    derived uncached input = 35217 - 35203 - 0 = 14

/v1/responses

  1. Cache write: 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}
  2. Cache read, same command and body:
    {"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

  1. Cache write: curl -sS -N http://localhost:59448/v1/messages -H 'Authorization: Bearer sk-lit7585-local' -H 'Content-Type: application/json' -d @body.json
    message_start usage: {"input_tokens": 14, "cache_creation_input_tokens": 35203, "cache_read_input_tokens": 0, "cache_creation": {"ephemeral_5m_input_tokens": 35203, "ephemeral_1h_input_tokens": 0}, "output_tokens": 1, "service_tier": "standard"}
    message_delta usage: {"input_tokens": 14, "cache_creation_input_tokens": 35203, "cache_read_input_tokens": 0, "output_tokens": 4, "output_tokens_details": {"thinking_tokens": 0}, "cache_creation": {"ephemeral_5m_input_tokens": 35203, "ephemeral_1h_input_tokens": 0}}
    
  2. Cache read, same command and body:
    message_start usage: {"input_tokens": 14, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 35203, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 0}, "output_tokens": 1, "service_tier": "standard"}
    message_delta usage: {"input_tokens": 14, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 35203, "output_tokens": 4, "output_tokens_details": {"thinking_tokens": 0}, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 0}}
    

After (9a4b19a)

/v1/chat/completions

  1. Cache write: 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}
    derived uncached input = 35217 - 0 - 35203 = 14
  2. Cache read, same command and body:
    {"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}
    derived uncached input = 35217 - 35203 - 0 = 14

/v1/responses

  1. Cache write: 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}
  2. Cache read, same command and body:
    {"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

  1. Cache write: curl -sS -N http://localhost:26333/v1/messages -H 'Authorization: Bearer sk-lit7585-local' -H 'Content-Type: application/json' -d @body.json
    message_start usage: {"input_tokens": 14, "cache_creation_input_tokens": 35203, "cache_read_input_tokens": 0, "cache_creation": {"ephemeral_5m_input_tokens": 35203, "ephemeral_1h_input_tokens": 0}, "output_tokens": 1, "service_tier": "standard"}
    message_delta usage: {"input_tokens": 14, "cache_creation_input_tokens": 35203, "cache_read_input_tokens": 0, "output_tokens": 1, "cache_creation": {"ephemeral_5m_input_tokens": 35203, "ephemeral_1h_input_tokens": 0}}
    
  2. Cache read, same command and body:
    message_start usage: {"input_tokens": 14, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 35203, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 0}, "output_tokens": 4, "service_tier": "standard"}
    message_delta usage: {"input_tokens": 14, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 35203, "output_tokens": 4, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 0}}
    

Observed alongside, none caused or changed by this PR:

  • Chat and responses input counts include cached tokens; messages input_tokens excludes them
  • Responses usage carries cache_write_tokens only, no cache_creation_input_tokens key
  • Messages output_tokens in message_start already equals the final count
  • Neither event pair in the messages stream ever disagreed on cache counts

Type

Bug Fix
Test

Caveats (if any)

Medium

  • Live QA never reached the trigger, so before and after read the same on every endpoint
    • The write-then-read flip inside one stream never occurred in 46 streams across Bedrock and Anthropic direct
    • The reporter's exact event sequence is pinned by 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 here

Low

Final 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

muhammadwaqar12 and others added 3 commits September 13, 2026 00:53
…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
@devin-ai-integration

devin-ai-integration Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor Author

I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".

  • Disable automatic comment, CI, and merge conflict monitoring

@codspeed

codspeed Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_stream_usage_explicit_zero_cache (8b4e7ce) with main (ded69f8)1

Open in CodSpeed

Footnotes

  1. No successful run was found on main (2ea4321) during the generation of this report, so ded69f8 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

@greptile-apps

greptile-apps Bot commented Sep 21, 2026

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

The PR appears safe to merge because prompt-side cache corrections are applied without allowing output-only events to erase earlier usage

Summary

This PR updates streamed usage aggregation so a later prompt-side usage event can replace stale cache counts with explicit zero values while output-only events preserve earlier prompt accounting

  • Adds a shared predicate for identifying prompt-side usage events
  • Applies authoritative prompt-side cache values independently when each cache field is present
  • Adds Anthropic regression coverage for restated cache counts, output-only deltas, and input/output deltas

Reviews (1) · Last reviewed commit: "test(streaming): cover an input-only mes..."

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

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

✅ 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

codecov Bot commented Sep 22, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@shreshth-berri
shreshth-berri merged commit ee3f5a8 into main Sep 22, 2026
95 of 96 checks passed
@shreshth-berri
shreshth-berri deleted the litellm_stream_usage_explicit_zero_cache branch September 22, 2026 18:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Streaming usage merger retains stale cache-write tokens after explicit zero update

3 participants