Skip to content

fix(caching): keep prompt cache usage on streamed cache hits - #47073

Merged
yuneng-berri merged 2 commits into
mainfrom
litellm_sharp_haibt_a1c5c3
Oct 17, 2026
Merged

yuneng-berri merged 2 commits into
mainfrom
litellm_sharp_haibt_a1c5c3

Conversation

@yuneng-berri

@yuneng-berri yuneng-berri commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Streamed cache hits drop the prompt cache token counts from usage
  • /v1/messages clients see the whole prompt as uncached input on a hit
  • This is what fails the Claude Code prompt caching e2e cell for Opus 4.7 on Bedrock Converse

How it solves it:

  • The replayed usage now keeps prompt_tokens_details and the cache read and creation counts
  • One helper builds it for both the async and the sync replay
  • Token counts are coerced like the live usage, and cached values that fail validation are skipped

User Flow

Before: a developer streaming through a proxy with response caching on gets no cache token counts back on a cache hit

  1. The proxy admin turns on cache: true with Redis
  2. The developer sends POST http://localhost:4093/v1/messages with "stream": true and a cache_control system prompt to a Bedrock Converse Claude model
  3. The proxy serves a repeat of that request from its cache
  4. The message_delta usage says input_tokens: 15780 with no cache fields, and the same repeat on POST /v1/chat/completions shows "prompt_tokens_details": null

After: the same cache hit reports the cache token counts the original response had

  1. The proxy admin turns on cache: true with Redis
  2. The developer sends POST http://localhost:4093/v1/messages with "stream": true and a cache_control system prompt to a Bedrock Converse Claude model
  3. The proxy serves a repeat of that request from its cache
  4. The message_delta usage says input_tokens: 28 and cache_read_input_tokens: 15752, and /v1/chat/completions keeps prompt_tokens_details.cached_tokens: 15752

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/unit/<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
  • Every automated review on my PR's latest commit has finished, and I have addressed or replied to each of its findings before requesting a maintainer review

Delays in PR merge?

If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).

Screenshots / Proof of Fix

Local proxy started with python -m litellm.proxy.proxy_cli --config config.yaml --port 4093, real Bedrock calls, and this config

model_list:
  - model_name: claude-opus-4-7-bedrock-converse
    litellm_params:
      model: bedrock/converse/us.anthropic.claude-opus-4-7
      aws_region_name: us-east-1
litellm_settings:
  cache: true
  cache_params:
    type: redis
    host: 127.0.0.1
    port: 6391
    namespace: litellm.caching
    ttl: 16600

Redis was flushed and the proxy restarted before each side. Every body streams and carries the same ~15.7K token system prompt marked with cache_control

  • messages_1.json and messages_2.json are /v1/messages bodies that differ only in safeguards[0].classifier_context.home_dir, the per-machine field Claude Code sends. Bedrock Converse drops that field, so request 2 misses the /v1/messages cache and is answered by the chat completion cache, which is the replay this PR fixes
  • chat.json is a /v1/chat/completions body with stream_options.include_usage, sent twice unchanged

Before (9f9a02b)

/v1/messages

  1. Send the first request, which goes to Bedrock

    curl -sN http://localhost:4093/v1/messages -H 'Authorization: Bearer $KEY' -H 'content-type: application/json' -H 'anthropic-version: 2023-06-01' -d @messages_1.json | grep message_delta
    event: message_delta
    data: {"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": {"input_tokens": 28, "output_tokens": 6, "cache_read_input_tokens": 15752}}
    
  2. Send the second request, which the proxy serves from its cache

    curl -sN http://localhost:4093/v1/messages -H 'Authorization: Bearer $KEY' -H 'content-type: application/json' -H 'anthropic-version: 2023-06-01' -d @messages_2.json | grep message_delta
    event: message_delta
    data: {"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": {"input_tokens": 15780, "output_tokens": 6}}
    

/v1/chat/completions

  1. Send the first request, which goes to Bedrock

    curl -sN http://localhost:4093/v1/chat/completions -H 'Authorization: Bearer $KEY' -H 'content-type: application/json' -d @chat.json | grep '"usage":{' | sed 's/^data: //' | jq -c '{usage: .usage | {prompt_tokens, completion_tokens, prompt_tokens_details, cache_read_input_tokens, cache_creation_input_tokens}}'
    {"usage":{"prompt_tokens":15780,"completion_tokens":6,"prompt_tokens_details":{"cached_tokens":15752,"text_tokens":28,"cache_write_tokens":0,"cache_creation_tokens":0},"cache_read_input_tokens":15752,"cache_creation_input_tokens":0}}
    
  2. Send the second request, which the proxy serves from its cache

    curl -sN http://localhost:4093/v1/chat/completions -H 'Authorization: Bearer $KEY' -H 'content-type: application/json' -d @chat.json | grep '"usage":{' | sed 's/^data: //' | jq -c '{usage: .usage | {prompt_tokens, completion_tokens, prompt_tokens_details, cache_read_input_tokens, cache_creation_input_tokens}}'
    {"usage":{"prompt_tokens":15780,"completion_tokens":6,"prompt_tokens_details":null,"cache_read_input_tokens":null,"cache_creation_input_tokens":null}}
    

Spend on the cache hits

  1. Read the response_cost the proxy logged for the four calls above, in order

    cache_hit=False response_cost=0.0089826
    cache_hit=True response_cost=0.0
    cache_hit=False response_cost=0.0089826
    cache_hit=True response_cost=0.0
    Bedrock requests sent: 2
    

After (b5b695a)

/v1/messages

  1. Send the first request, which goes to Bedrock

    curl -sN http://localhost:4093/v1/messages -H 'Authorization: Bearer $KEY' -H 'content-type: application/json' -H 'anthropic-version: 2023-06-01' -d @messages_1.json | grep message_delta
    event: message_delta
    data: {"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": {"input_tokens": 28, "output_tokens": 6, "cache_creation_input_tokens": 15752}}
    
  2. Send the second request, which the proxy serves from its cache

    curl -sN http://localhost:4093/v1/messages -H 'Authorization: Bearer $KEY' -H 'content-type: application/json' -H 'anthropic-version: 2023-06-01' -d @messages_2.json | grep message_delta
    event: message_delta
    data: {"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": {"input_tokens": 28, "output_tokens": 6, "cache_creation_input_tokens": 15752}}
    

/v1/chat/completions

  1. Send the first request, which goes to Bedrock

    curl -sN http://localhost:4093/v1/chat/completions -H 'Authorization: Bearer $KEY' -H 'content-type: application/json' -d @chat.json | grep '"usage":{' | sed 's/^data: //' | jq -c '{usage: .usage | {prompt_tokens, completion_tokens, prompt_tokens_details, cache_read_input_tokens, cache_creation_input_tokens}}'
    {"usage":{"prompt_tokens":15780,"completion_tokens":6,"prompt_tokens_details":{"cached_tokens":15752,"text_tokens":28,"cache_write_tokens":0,"cache_creation_tokens":0},"cache_read_input_tokens":15752,"cache_creation_input_tokens":0}}
    
  2. Send the second request, which the proxy serves from its cache

    curl -sN http://localhost:4093/v1/chat/completions -H 'Authorization: Bearer $KEY' -H 'content-type: application/json' -d @chat.json | grep '"usage":{' | sed 's/^data: //' | jq -c '{usage: .usage | {prompt_tokens, completion_tokens, prompt_tokens_details, cache_read_input_tokens, cache_creation_input_tokens}}'
    {"usage":{"prompt_tokens":15780,"completion_tokens":6,"prompt_tokens_details":{"cached_tokens":15752,"text_tokens":28,"cache_write_tokens":0,"cache_creation_tokens":0},"cache_read_input_tokens":15752,"cache_creation_input_tokens":0}}
    

Spend on the cache hits

  1. Read the response_cost the proxy logged for the four calls above, in order

    cache_hit=False response_cost=0.108614
    cache_hit=True response_cost=0.0
    cache_hit=False response_cost=0.0089826
    cache_hit=True response_cost=0.0
    Bedrock requests sent: 2
    

Type

🐛 Bug Fix

Caveats (if any)

Medium

  • Stream cache hits now feed provider cache tokens into downstream accounting
    • The daily rollup's prompt caching savings, Prometheus provider cache counters and the TPM limiter's cached token discount
    • Non-stream cache hits already behave this way, and response_cost on the hit stays $0

Low

  • The hit's usage.cost now prices cached tokens as cache reads, like the live response
  • Streamed x-litellm-response-cost-* headers read 0.0 on live calls too
    • So spend is shown from the cost the proxy logs, not the header
  • A cached usage that is not an object still raises on replay, same as before this PR
  • I did not drive interactive Claude Code for screenshots
    • The curl bodies copy the safeguards field it sends
  • /v1/responses replays through its own iterator and was not checked

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

A stream=true request served from the response cache rebuilt its usage from
the prompt, completion and total counts only, so prompt_tokens_details and the
cache read and creation counts were dropped on the replayed stream. /v1/messages
clients routed to Bedrock Converse saw input_tokens equal to the whole prompt
and no cache tokens on a hit.

Both replays now build the usage through one helper that also restores
prompt_tokens_details and the integer cache read and creation counts, skipping
cached values that do not validate.
@codspeed

codspeed Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

⚠️ 1 benchmark spent significant time in system calls

System calls cannot be consistently instrumented, so they are not included in the measure, which understates the real cost. Please switch to the Walltime instrument to accurately measure system calls.

Measurement and system calls

✅ 32 untouched benchmarks


Comparing litellm_sharp_haibt_a1c5c3 (b5b695a) with main (e960d96)

Open in CodSpeed

@codecov

codecov Bot commented Oct 17, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

The replay accepted only exact ints for the token counts, so an integral float
or numeric string in a cached entry became 0 where the previous replay kept it.
Counts now go through pydantic int coercion and fall back only when they do not
validate.
@yuneng-berri

Copy link
Copy Markdown
Contributor Author

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 b5b695a. Configure here.

@BrickerP BrickerP left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed head b5b695a8. The bug is real: both stream replay paths previously rebuilt Usage from prompt/completion/total (+ completion details) only, so a Redis/response-cache hit on stream=true dropped prompt_tokens_details and the Anthropic-style cache read/creation counts — exactly what breaks Claude Code / Bedrock Converse /v1/messages caching cells.

_replayed_usage + shared helpers for sync/async is the right shape, and the new unit tests cover the important cases (read vs write, details-only cached_tokens, float/string coercion, invalid fields skipped without breaking replay, and the Anthropic message_delta adapter path). CI green on caching/core-utils looks consistent with that.

One semantic caveat worth an explicit follow-up (you already flag the medium risk in the caveats):

  • Cache hits replay cache_creation_input_tokens unchanged. After a cold write is stored, every later stream hit will re-emit the original creation count into anything that consumes usage (daily prompt-cache savings, Prometheus provider cache counters, TPM cached-token discount). response_cost staying $0 on the hit is good, but those side channels can still treat a hit as another write unless they key off cache_hit / cost rather than the usage fields. Non-stream hits already behave this way, so this PR is consistent — just confirming that is the intended contract rather than “on hit, map creation→read or zero creation.”

Also agreed with the low caveat that /v1/responses has its own replay iterator and is still unchecked; a small twin test there would close the gap if that route is cached in production.

Not blocking: the core stream-cache usage restore looks correct and well tested.

@yuneng-berri

Copy link
Copy Markdown
Contributor Author

@litellm-stampbot

@litellm-stampbot

litellm-stampbot Bot commented Oct 17, 2026 •

Copy link
Copy Markdown

litellm-stampbot: risk low

Approved at b5b695a.

Rules (stampbot/risk_rules.yml):

  • low: no rule flagged it

Judge (gpt-6-luna): low, probability of high 0.01 (high at or above 0.75)

  • risk: low (probability of high 0.01)

Pushes do not re-run this check. Comment @litellm-stampbot again to re-check the new head.

@litellm-stampbot litellm-stampbot Bot added the risk:low Small, isolated, low-risk change label Oct 17, 2026

@kerry-berri kerry-berri 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.

Low risk by rule and by judgement at b5b695a

@yuneng-berri
yuneng-berri merged commit d346d76 into main Oct 17, 2026
92 of 93 checks passed
@yuneng-berri
yuneng-berri deleted the litellm_sharp_haibt_a1c5c3 branch October 17, 2026 06:28
yuneng-berri added a commit that referenced this pull request Oct 17, 2026
…in (#47090)

* fix(bedrock)!: block realtime replay after an input-first start and reject malformed Nova Sonic session settings (#46936)

* fix(bedrock): block realtime replay after input starts the session and reject non-string instructions and voice

* test(bedrock): name the malformed realtime setting test for its string cases

* fix(bedrock): replay the opening realtime message until Bedrock accepts the stream and refuse any fallback after commit

Also rejects a malformed modalities, input_sample_rate_hertz or tools setting with invalid_type, dropped under drop_params.

* fix(bedrock): replay a refused opening message on any fallback and reject OpenAI voices and non-string audio formats

* fix(realtime): read the client scope only when the websocket has one and reject any-case OpenAI and empty Bedrock voices

* test(bedrock): cover realtime replay, refusal and committed failure through a real proxy

Fix the scripted Bedrock peer's port import and the nested tool call cell's stale expected events, so the Nova Sonic integration file collects again

(cherry picked from commit 3ef0b35)

* test(integration): write worker configs beside test-supplied configs (#47066)

Under worker isolation the harness rewrote every proxy config into the owned proxy's directory, so modules a test placed next to its own config (custom_auth) no longer resolved and the proxy died at boot. The copy now lands next to a test-supplied config, while configs inside the checkout still go to the worker directory so nothing is written into the repo tree

(cherry picked from commit e754857)

* test(e2e): keep the prompt-caching affinity test on the live provider (#47072)

With E2E_PROVIDER_CACHE=1 the test's Anthropic deployment went through the
shared response cache. Each call's recording expires on its own, so a run
could replay the cache-writing call while a follow-up went live against a
cold provider cache, recording creation instead of a read. That recording
then replayed as a failure for 24 hours. Mark the test provider_live, as
PROVIDER_CACHE.md requires for prompt-caching tests

(cherry picked from commit 6b45a19)

* test(integration): send post-kill requests on a fresh connection in two worker-kill tests (#47080)

kill() returns once the killed worker's main thread is a zombie, but its other threads can
still be exiting and holding its sockets open. A keep-alive connection pooled to that worker
still looks healthy, so the next request goes out on it and the closing socket answers with
a reset. The old reap wait used to hide this. A new connection can only be accepted by a
live worker, so the surviving-worker assertions now run on a fresh client

(cherry picked from commit c32eea6)

* fix(caching): keep prompt cache usage on streamed cache hits (#47073)

* fix(caching): keep prompt cache usage on streamed cache hits

A stream=true request served from the response cache rebuilt its usage from
the prompt, completion and total counts only, so prompt_tokens_details and the
cache read and creation counts were dropped on the replayed stream. /v1/messages
clients routed to Bedrock Converse saw input_tokens equal to the whole prompt
and no cache tokens on a hit.

Both replays now build the usage through one helper that also restores
prompt_tokens_details and the integer cache read and creation counts, skipping
cached values that do not validate.

* fix(caching): coerce replayed token counts the way the live usage does

The replay accepted only exact ints for the token counts, so an integral float
or numeric string in a cached entry became 0 where the previous replay kept it.
Counts now go through pydantic int coercion and fall back only when they do not
validate.

(cherry picked from commit d346d76)

* fix(logging): keep the async request's logging payload when the sync success thread runs late (#47019)

* fix(logging): keep the async request's logging payload when sync callbacks run late

Treat the "cache" success callback as internal when deciding whether to start
the sync success thread for async requests. It has no branch in the sync
handler, so with `cache: true` that thread did nothing except rebuild and
overwrite model_call_details["standard_logging_object"].

When the sync handler does run for an async request (a real sync-only logger
is configured), it now builds its own payload and hands it only to its own
callbacks. The async handler keeps sole ownership of the shared payload, so
edits made by async logging hooks (for example the v3 rate limiter's mirrored
x-ratelimit headers that Prometheus reads) are no longer discarded. Sync
requests keep their existing behavior.

* fix(logging): keep sync cache hits logged and isolate the async-request payload build

The sync completion cache-hit path reused handle_sync_success_callbacks_for_async_calls,
so treating "cache" as internal silently dropped sync callbacks on sync cache hits. It now
submits the sync handler through its own method, as it effectively always did.

For async requests the sync handler builds its payload from a copy of the call details, so
message redaction cannot rewrite the shared standard_logging_object, and when it builds no
payload its callbacks keep the shared one instead of getting None.

* test(caching): lock sync cache-hit logging for completion, embedding and text_completion

* test(logging): keep sync hook edits off a caller-supplied payload for async requests

* fix(logging): give sync hooks a copy of the async payload when the thread builds none

* test(logging): check every legacy sync logger gets the thread's own payload

* test(logging): cover traceloop and supabase sync logging for async requests

(cherry picked from commit a4e0570)

* fix(cost): price exact cost-map names before price-free capability rules, and fix SCIM and MCP integration tests on CircleCI (#47037)

* fix(test-harness): preserve sibling auth modules in isolated worker configs

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(integration): expect servers in MCP connect-flow descriptions

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(integration): expect ptu_hours in daily activity metrics after #43043

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(integration): kill every serving worker once the SCIM push blocks on the row lock

* fix(cost): price exact cost-map names before price-free capability rule matches

* test(streaming): price a priced alias stream at its deployment model and keep the unpriceable case unmapped

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* fix(cost): price an explicit base_model under its own provider after candidate reordering

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* fix(cost): retain priced generalized candidates and skip explicit-pricing lookups

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(cost): assert custom pricing makes no remote model-info requests

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* refactor(cost): keep the per-candidate pricing provider final

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* fix(router): pin a Bedrock application profile prompt for the one-hour ttl its base model sends

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test(integration): assert the Nova Sonic tool-call argument delta carries the full arguments

* fix(cost): sort cost candidates from the static cost map and rules, without provider lookups

* test(integration): bill route-priced Bedrock chat streams and responses, and pin application profiles for an hour on messages and cache hits

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Yuneng Jiang <yuneng@berri.ai>
(cherry picked from commit 4a58784)

* test(e2e): warm the memory test up with two batches before the measured one (#47087)

* test(e2e): warm the memory test up with two batches before the measured one

On a cold worker the second batch of failing requests can still raise the
allocator's high-water mark by about 50 MB while the live Python heap stays
flat, so the 48 MB budget failed about 1 in 10 Buildkite runs without a leak.
The test now runs two warmup batches, measures the third against the same
budget, and records every batch's settled growth per worker as an
rss_batch_growth JUnit property for later calibration

* test(e2e): record each memory batch's growth as soon as it settles

A failure in a later batch no longer drops the growth already measured, and
the worker keys are no longer sorted, which raised on a mix of named and
unnamed hosts

* test(e2e): silence the xunit2 record_property warning on the memory test

(cherry picked from commit 1fd7f81)

* test: import pytest and Final for the backported #47073 test on rc

On main these imports came from an earlier commit that is not on rc/1.107.0, so the
picked test failed collection with NameError

---------

Co-authored-by: Mateo Wang <277851410+mateo-berri@users.noreply.github.com>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk:low Small, isolated, low-risk change

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: streamed response cache stores finish_reason "stop" for truncated streams; replay also drops completion_tokens_details

3 participants