Skip to content

fix(streaming): preserve 5m/1h cache creation split in combined usage - #30088

Closed
Cyberfilo wants to merge 1 commit into
BerriAI:mainfrom
Cyberfilo:fix/29432-stream-1h-cache-split
Closed

Cyberfilo wants to merge 1 commit into
BerriAI:mainfrom
Cyberfilo:fix/29432-stream-1h-cache-split

Conversation

@Cyberfilo

Copy link
Copy Markdown
Contributor

Relevant issues

Fixes #29432

Linear ticket

N/A

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • My PR passes all unit tests on make test-unit
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have requested a Greptile review by commenting @greptileai and received a Confidence Score of at least 4/5 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).

CI (LiteLLM team)

CI status guideline:

  • 50-55 passing tests: main is stable with minor issues.
  • 45-49 passing tests: acceptable but needs attention
  • <= 40 passing tests: unstable; be careful with your merges and assess the risk.
  • Branch creation CI run
    Link:

  • CI run for the last commit
    Link:

  • Merge / cherry-pick CI run
    Links:

Screenshots / Proof of Fix

The combine step is deterministic, so the regression is visible by replaying the exact usage chunks from the issue's Bedrock invocation log through stream_chunk_builder: a message_start usage carrying cache_creation_token_details (ephemeral_5m_input_tokens=288, ephemeral_1h_input_tokens=74) followed by a message_delta usage carrying only totals, priced against bedrock/global.anthropic.claude-opus-4-8 (cache_creation_input_token_cost=6.25e-6, cache_creation_input_token_cost_above_1hr=1.0e-5)

# before (litellm_internal_staging @ e15b37a18e)
"prompt_tokens_details": {
  "cached_tokens": 31034,
  "cache_creation_tokens": 362
}
completion_cost: 0.0242545

# after (this branch)
"prompt_tokens_details": {
  "cached_tokens": 31034,
  "cache_creation_tokens": 362,
  "cache_creation_token_details": {
    "ephemeral_5m_input_tokens": 288,
    "ephemeral_1h_input_tokens": 74
  }
}
completion_cost: 0.024532

The 0.0002775 difference is exactly 74 tokens x (10.00 - 6.25) per million, the undercount computed in the issue. To see it end to end, run the proxy as a Bedrock passthrough and POST /bedrock/model/<inference-profile>/invoke-with-response-stream with cache_control: {"type": "ephemeral", "ttl": "1h"} on a cacheable block; SpendLog cost_breakdown.cache_creation_cost now bills the 1h portion at cache_creation_input_token_cost_above_1hr instead of the 5m rate

Type

🐛 Bug Fix

Changes

ChunkProcessor._calculate_usage_per_chunk in litellm/litellm_core_utils/streaming_chunk_builder_utils.py overwrote prompt_tokens_details with every successive usage chunk. Anthropic-style streams only send the 5m/1h cache creation split in the message_start usage; the closing message_delta repeats the totals without it, so the split was clobbered by the last chunk while the aggregate cache_creation_input_tokens survived through its own keep-the-meaningful-chunk tracking. Downstream, calculate_cache_writing_cost in litellm/litellm_core_utils/llm_cost_calc/utils.py then had no usage.prompt_tokens_details.cache_creation_token_details to read and billed the whole cache write at the 5m rate

The fix tracks cache_creation_token_details across usage chunks the same way the aggregate already is (keep the chunk that has it), adds the field to the UsagePerChunk TypedDict in litellm/types/litellm_core_utils/streaming_chunk_builder_utils.py, and reattaches it to the final usage's prompt_tokens_details in calculate_usage

Regression test test_calculate_usage_retains_cache_creation_token_details in tests/test_litellm/litellm_core_utils/test_streaming_chunk_builder_utils.py fails on the base branch and passes with the fix. tests/test_litellm/litellm_core_utils/ is green apart from test_bedrock_converse_messages_pt_document_various_formats, which also fails on the base branch; tests/test_litellm/test_bedrock_anthropic_1hr_cache_pricing.py, test_cost_calculator.py, test_stream_chunk_builder_annotations.py and the anthropic passthrough logging handler tests all pass

Anthropic-style streams only carry the cache creation TTL split
(usage.cache_creation.ephemeral_5m_input_tokens / ephemeral_1h_input_tokens)
in the message_start usage chunk; the closing message_delta chunk repeats
the totals without it. ChunkProcessor._calculate_usage_per_chunk overwrote
prompt_tokens_details with every successive usage chunk, so the split was
clobbered by the last chunk while the aggregate cache_creation_input_tokens
survived through its own keep-the-meaningful-chunk tracking

With the split gone, generic_cost_per_token had nothing to read from
usage.prompt_tokens_details.cache_creation_token_details and billed the
whole cache write at cache_creation_input_token_cost, the 5m rate. 1h-TTL
writes (for example Bedrock passthrough streaming with cache_control ttl
1h) were undercharged by the cache_creation_input_token_cost_above_1hr
delta

Track cache_creation_token_details across usage chunks the same way the
aggregate already is, expose it on UsagePerChunk, and reattach it to the
final usage's prompt_tokens_details in calculate_usage

Fixes BerriAI#29432.
@greptile-apps

greptile-apps Bot commented Jun 10, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes a cost-calculation bug where Anthropic's cache_creation_token_details (the 5m/1h split) was dropped during streaming chunk combination, causing all cache writes to be billed at the cheaper 5m rate regardless of TTL.

  • Root cause fix: _calculate_usage_per_chunk now tracks cache_creation_token_details independently — using the same "keep the first non-None value" logic already applied to cache_creation_input_tokens — so the closing message_delta chunk (which omits the split) cannot clobber it.
  • Re-attachment in calculate_usage: after prompt_tokens_details is set from the last chunk, the separately-preserved cache_creation_token_details is written back onto prompt_tokens_details, mirroring the existing pattern for web_search_requests.
  • Regression test: test_calculate_usage_retains_cache_creation_token_details replays the exact two-chunk scenario and verifies both ephemeral_5m_input_tokens and ephemeral_1h_input_tokens survive on the final Usage object; no network calls are made.

Confidence Score: 5/5

The change is narrowly scoped to the chunk-combination path, follows the existing keep-first-non-None tracking pattern already used for other fields, and is verified by a targeted regression test that fails on the base branch and passes with the fix.

All three changed files are clean: the core logic correctly separates cache_creation_token_details tracking from the broader prompt_tokens_details assignment, re-attaches it in the right order in calculate_usage, the TypedDict is updated consistently, and the test covers the exact failure scenario from the linked issue without network calls.

No files require special attention.

Important Files Changed

Filename Overview
litellm/litellm_core_utils/streaming_chunk_builder_utils.py Adds independent tracking of cache_creation_token_details in _calculate_usage_per_chunk (keep-first-non-None logic) and re-attaches it to prompt_tokens_details in calculate_usage after the last chunk's prompt_tokens_details overwrites the field.
litellm/types/litellm_core_utils/streaming_chunk_builder_utils.py Adds cache_creation_token_details: Optional[CacheCreationTokenDetails] to the UsagePerChunk TypedDict to carry the new field through the pipeline.
tests/test_litellm/litellm_core_utils/test_streaming_chunk_builder_utils.py New regression test test_calculate_usage_retains_cache_creation_token_details replays the exact two-chunk scenario (message_start with 5m/1h split, message_delta without it) and asserts both split fields survive on the combined usage; no real network calls.

Reviews (1): Last reviewed commit: "fix(streaming): preserve 5m/1h cache cre..." | Re-trigger Greptile

@codecov

codecov Bot commented Jun 10, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.00000% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...itellm_core_utils/streaming_chunk_builder_utils.py 87.50% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Sep 9, 2026

Copy link
Copy Markdown
Contributor

This pull request has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs.

@github-actions github-actions Bot added the stale label Sep 9, 2026
@yuneng-berri
yuneng-berri deleted the branch BerriAI:main September 13, 2026 04:24
@yuneng-berri yuneng-berri reopened this Sep 13, 2026
@github-actions github-actions Bot removed the stale label Sep 14, 2026
@devin-ai-integration
devin-ai-integration Bot changed the base branch from litellm_internal_staging to main September 23, 2026 16:05
@devin-ai-integration
devin-ai-integration Bot requested a review from a team September 23, 2026 16:05
@rpreite

rpreite commented Oct 28, 2026

Copy link
Copy Markdown

Any update about this PR?

@mateo-berri

Copy link
Copy Markdown
Contributor

Main keeps the 5m and 1h cache write split in combined streaming usage since #32073, so closing this. Reopen if something is missing

@mateo-berri mateo-berri closed this Nov 9, 2026
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 passthrough bills 1-hour cache writes at the 5-minute rate (cache_creation.ephemeral_1h_input_tokens not propagated)

4 participants