Skip to content

fix(proxy): propagate Invoke cache-token counts to usage - #34498

Draft
yryzhan-vitech wants to merge 1 commit into
BerriAI:mainfrom
yryzhan-vitech:bugfix/bedrock-invoke-cache-token-usage
Draft

yryzhan-vitech wants to merge 1 commit into
BerriAI:mainfrom
yryzhan-vitech:bugfix/bedrock-invoke-cache-token-usage

Conversation

@yryzhan-vitech

@yryzhan-vitech yryzhan-vitech commented Jul 24, 2026 •

Copy link
Copy Markdown

TLDR

Problem this solves:

  • Bedrock Invoke streaming drops cacheRead/cacheWrite token counts from usage → cache-heavy Claude traffic billed as fresh input (4–7× over-report)
  • The usage-only recovery fallback also drops cache-write tokens on large/agentic streams

How it solves it:

  • Map the two cache fields in the Invoke decoder, and read cache_creation from message_delta in the fallback — only when reported, no double-count

Relevant issues

Fixes #34497

Pre-Submission checklist

  • I have added meaningful tests
  • My PR passes all CI/CD checks (e.g., lint, format, unit tests)
  • 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

Screenshots / Proof of Fix

Reproduction: route an Anthropic Claude model over the Bedrock Invoke streaming path (bedrock/invoke/…) with a large cache-eligible prompt + cache_control. Pre-fix the returned usage has input_tokens/output_tokens but no cache_read_input_tokens/cache_creation_input_tokens, even though Bedrock reported cacheReadInputTokenCount/cacheWriteInputTokenCount in amazon-bedrock-invocationMetrics — so the cost calculator bills every request as fresh input.

$ pytest tests/test_litellm/llms/bedrock/messages/invoke_transformations/test_anthropic_claude3_transformation.py \
         tests/test_litellm/proxy/pass_through_endpoints/llm_provider_handlers/test_anthropic_passthrough_logging_handler.py \
         -k "chunk_parser_maps_cache or chunk_parser_omits_cache or recovers_cache_creation_from_message_delta"
6 passed

The fallback test is a negative control: it asserts cache_creation_input_tokens == 120; reverting only the handler change fails it at assert 0 == 120, confirming the fix is load-bearing.

Live proof on a running proxy to be added.

image

Type

🐛 Bug Fix

Changes

For Anthropic Claude models on the Bedrock Invoke streaming path, the final chunk reports token usage in amazon-bedrock-invocationMetrics. The decoder mapped only inputTokenCount/outputTokenCount and dropped cacheReadInputTokenCount/cacheWriteInputTokenCount, so prompt-cache usage never reached cache_read_input_tokens/cache_creation_input_tokens and cache-heavy traffic was billed as fresh input.

  • AmazonAnthropicClaudeMessagesStreamDecoder._chunk_parser (litellm/llms/bedrock/messages/invoke_transformations/anthropic_claude3_transformation.py) now maps cacheReadInputTokenCount → cache_read_input_tokens and cacheWriteInputTokenCount → cache_creation_input_tokens when present.
  • _build_usage_only_response_from_chunks (litellm/proxy/pass_through_endpoints/llm_provider_handlers/anthropic_passthrough_logging_handler.py) read cache_read_input_tokens from message_delta but read cache_creation_input_tokens only from message_start; the message_delta branch now reads cache_creation_input_tokens too.

Notes for review:

  • Distinct from _promote_message_stop_usage: that runs one stage later on fields already in snake_case on message_start/message_stop. On the Invoke path the cache counts exist only in the camelCase invocationMetrics block, so they were dropped before that step could see them — the two are complementary, not redundant.
  • No double-count: the promote step is last-wins (assignment, not addition), and inputTokenCount is exclusive of cached tokens (a real chunk shows inputTokenCount: 1 alongside cacheReadInputTokenCount: 421714), so input_tokens does not overlap the cache counts downstream.
  • The fallback gap matters because the decoder lands cache usage on the final delta; on large/agentic streams that stream_chunk_builder cannot reassemble, cache-write tokens were silently priced at zero. Regression test covers exactly that recovery path.

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

@yryzhan-vitech yryzhan-vitech changed the title fix(bedrock): propagate Invoke cache-token counts to usage fix(proxy): propagate Invoke cache-token counts to usage Jul 24, 2026
@codecov

codecov Bot commented Jul 24, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@yryzhan-vitech
yryzhan-vitech marked this pull request as ready for review July 24, 2026 12:52
@greptile-apps

greptile-apps Bot commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

Propagates Bedrock Invoke prompt-cache token counts through streaming usage and fallback cost accounting

  • Maps Bedrock cache-read and cache-write invocation metrics to Anthropic-compatible usage fields
  • Recovers cache-creation tokens from final message_delta events when full stream reconstruction fails
  • Adds focused regression coverage for present, absent, independent, and zero-valued cache metrics

Confidence Score: 5/5

The PR appears safe to merge, with no concrete correctness or security failures identified in the changed paths

The new mappings preserve optional and zero-valued provider metrics, and the fallback forwards final cache-creation usage through the existing Anthropic usage calculation without introducing additive double-counting

Important Files Changed

Filename Overview
litellm/llms/bedrock/messages/invoke_transformations/anthropic_claude3_transformation.py Maps independently reported Bedrock Invoke cache metrics into the established Anthropic usage fields without changing absent-field behavior
litellm/proxy/pass_through_endpoints/llm_provider_handlers/anthropic_passthrough_logging_handler.py Extends usage-only stream recovery to retain cache-creation counts reported in final message deltas
tests/test_litellm/llms/bedrock/messages/invoke_transformations/test_anthropic_claude3_transformation.py Adds regression coverage for combined, absent, independent, and zero-valued cache metrics
tests/test_litellm/proxy/pass_through_endpoints/llm_provider_handlers/test_anthropic_passthrough_logging_handler.py Verifies fallback usage reconstruction includes delta-reported cache-creation tokens in prompt totals

Reviews (1): Last reviewed commit: "fix(bedrock): propagate Invoke cache-tok..." | Re-trigger Greptile

@codspeed

codspeed Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing yryzhan-vitech:bugfix/bedrock-invoke-cache-token-usage (4467abc) with litellm_internal_staging (09889e1)

Open in CodSpeed

@yryzhan-vitech
yryzhan-vitech marked this pull request as draft July 24, 2026 13:33
AmazonAnthropicClaudeMessagesStreamDecoder._chunk_parser mapped only
inputTokenCount/outputTokenCount from Bedrock Invoke's
amazon-bedrock-invocationMetrics block, dropping cacheReadInputTokenCount
and cacheWriteInputTokenCount. Cache-heavy Anthropic Claude traffic over
the Invoke streaming path then had no cache_read_input_tokens /
cache_creation_input_tokens in usage, so the cost calculator billed every
request as fresh input.

Map the two cache fields onto the synthesized Anthropic-style usage when
present.

Also fix the usage-only recovery fallback
(_build_usage_only_response_from_chunks): its message_delta branch read
cache_read_input_tokens but not cache_creation_input_tokens (only
message_start supplied the latter). Since the Invoke decoder lands cache
usage on the final delta, cache-write tokens were silently dropped and
billed at zero on large/agentic streams that stream_chunk_builder cannot
reassemble. Read cache_creation_input_tokens from message_delta too.

Add unit tests: the decoder mapping (present/absent/independent branches)
and the fallback recovering cache_creation from message_delta.
@yryzhan-vitech
yryzhan-vitech force-pushed the bugfix/bedrock-invoke-cache-token-usage branch from 4be947c to 4467abc Compare August 13, 2026 09:01
@yuneng-berri
yuneng-berri deleted the branch BerriAI:main September 13, 2026 04:34
@yuneng-berri yuneng-berri reopened this Sep 13, 2026
@devin-ai-integration
devin-ai-integration Bot changed the base branch from litellm_internal_staging to main September 23, 2026 15:32

This branch has not been deployed

No deployments
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] Bedrock Invoke streaming drops cacheRead/cacheWrite token counts → cache-heavy traffic billed as fresh input

2 participants