Skip to content

fix(streaming): don't clobber prompt_tokens_details when a later usage chunk lacks it - #32130

Closed
abcgco wants to merge 4 commits into
BerriAI:mainfrom
abcgco:fix-streaming-prompt-tokens-details-clobber
Closed

abcgco wants to merge 4 commits into
BerriAI:mainfrom
abcgco:fix-streaming-prompt-tokens-details-clobber

Conversation

@abcgco

@abcgco abcgco commented Jul 4, 2026

Copy link
Copy Markdown

Relevant issues

Found while auditing the usage accumulation in stream_chunk_builder; no existing issue

Linear ticket

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 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 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?

Screenshots / Proof of Fix

_calculate_usage_per_chunk overwrites the accumulated prompt_tokens_details on every usage-bearing chunk. When a later usage chunk carries no breakdown (a shape real providers produce when usage arrives on more than one chunk), the accumulated cached_tokens split is reset to None and lost from the combined response, so cache-read discounts disappear from cost tracking and from the OpenAI-compatible usage.prompt_tokens_details customers read. Every neighboring accumulator in that loop already guards against this (completion_tokens_details replaces only on non-None, cache_read_input_tokens keeps the last nonzero, and the 5m/1h cache-creation split even has a dedicated rescue added in #30088 because, as its comment says, "prompt_tokens_details is last-wins"); this PR applies the same non-None guard to prompt_tokens_details itself

The repro is the public stream_chunk_builder entrypoint, exactly what an end user runs; no provider call is needed because the bug is in how already-received chunks are combined:

import litellm

base = {"id": "chatcmpl-123", "object": "chat.completion.chunk", "created": 1751600000, "model": "gpt-4o"}
chunks = [
    {**base, "choices": [{"index": 0, "delta": {"role": "assistant", "content": "Hello"}, "finish_reason": None}],
     "usage": {"prompt_tokens": 100, "completion_tokens": 0, "total_tokens": 100,
               "prompt_tokens_details": {"cached_tokens": 80}}},
    {**base, "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}],
     "usage": {"prompt_tokens": 100, "completion_tokens": 5, "total_tokens": 105}},
]
print(litellm.stream_chunk_builder(chunks=chunks).usage.prompt_tokens_details)

Before the fix:

None

After the fix:

PromptTokensDetailsWrapper(audio_tokens=None, cached_tokens=80, text_tokens=None, image_tokens=None, video_tokens=None)

Regression test added to the mapped test file (tests/test_litellm/litellm_core_utils/test_streaming_chunk_builder_utils.py); it fails before the fix and passes after. ruff format --check and ruff check are clean on the touched source file

Type

🐛 Bug Fix

…e chunk lacks it

_calculate_usage_per_chunk overwrote the accumulated prompt_tokens_details on
every usage-bearing chunk, so a final usage chunk without the breakdown reset
it to None and the cached_tokens split was lost from the combined response.
The neighboring completion_tokens_details accumulator already replaces only on
non-None; this applies the same guard. The cache-creation TTL rescue keeps
working since a non-None later wrapper still replaces the accumulated one
@CLAassistant

CLAassistant commented Jul 4, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@abcgco

abcgco commented Jul 4, 2026

Copy link
Copy Markdown
Author

@greptileai

@greptile-apps

greptile-apps Bot commented Jul 4, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes a silent data-loss bug in _calculate_usage_per_chunk where prompt_tokens_details was unconditionally overwritten on every usage chunk, causing an earlier chunk's cached_tokens breakdown to be lost whenever a later chunk omitted the field.

  • Introduces _capture_prompt_tokens_details, a static helper that keeps the accumulated value when the incoming chunk carries None, matching the identical guard already applied to completion_tokens_details and cache_creation_token_details.
  • Adds a focused, mock-only regression test in tests/test_litellm/litellm_core_utils/ that directly reproduces the two-chunk scenario and verifies cached_tokens is preserved.

Confidence Score: 5/5

Safe to merge — the change is a targeted, additive fix that aligns prompt_tokens_details accumulation with the identical non-None guard already applied to every neighbouring field.

The fix is minimal and consistent with the surrounding code pattern. The new helper is stateless, the logic is trivially correct, and the regression test exercises the exact failing scenario end-to-end without touching any network or shared state.

Files Needing Attention: No files require special attention.

Important Files Changed

Filename Overview
litellm/litellm_core_utils/streaming_chunk_builder_utils.py Adds _capture_prompt_tokens_details helper that keeps the accumulated value when an incoming chunk carries no prompt_tokens_details, matching the existing non-None guard pattern used by completion_tokens_details and cache_creation_token_details.
tests/test_litellm/litellm_core_utils/test_streaming_chunk_builder_utils.py New mock-only test test_stream_chunk_builder_preserves_prompt_tokens_details_from_earlier_chunk directly reproduces the reported bug; no network calls, consistent with test folder conventions.

Reviews (3): Last reviewed commit: "style(streaming): use PEP 604 optionals ..." | Re-trigger Greptile

@greptile-apps

greptile-apps Bot commented Jul 4, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes a "last-wins" bug in _calculate_usage_per_chunk where an unconditional assignment to prompt_tokens_details would reset an already-accumulated non-None value to None whenever a later streaming chunk carried no prompt token breakdown. The fix wraps the assignment in a non-None guard, matching the identical pattern already used for completion_tokens_details elsewhere in the same loop.

  • streaming_chunk_builder_utils.py: Replaces prompt_tokens_details = cast(Optional[...], ...) with if ... is not None: prompt_tokens_details = cast(PromptTokensDetailsWrapper, ...), ensuring the first chunk that carries a breakdown is never overwritten by a later chunk that omits one.
  • test_streaming_chunk_builder_utils.py: Adds a mock-only regression test that reproduces the exact before/after behaviour described in the PR description.

Confidence Score: 5/5

Safe to merge — the change is a one-statement guard that aligns prompt_tokens_details with the identical pattern already used by neighbouring accumulators in the same loop.

The fix is minimal and mechanically correct: it adds a is not None check before overwriting prompt_tokens_details, exactly mirroring the guard already present for completion_tokens_details on the line directly above it. The regression test reproduces the documented failure, makes no network calls, and verifies both the preserved field and the correct final completion_tokens value. No other logic in the file is touched.

No files require special attention.

Important Files Changed

Filename Overview
litellm/litellm_core_utils/streaming_chunk_builder_utils.py Adds a non-None guard around the prompt_tokens_details assignment in _calculate_usage_per_chunk, matching the existing pattern used for completion_tokens_details. The fix prevents a later chunk with no breakdown from clobbering an earlier accumulated prompt_tokens_details value.
tests/test_litellm/litellm_core_utils/test_streaming_chunk_builder_utils.py Adds test_stream_chunk_builder_preserves_prompt_tokens_details_from_earlier_chunk — a focused regression test using only pre-built dicts (no network calls) that reproduces the exact failure scenario described in the PR and verifies the fix end-to-end.

Reviews (2): Last reviewed commit: "fix(streaming): don't clobber prompt_tok..." | Re-trigger Greptile

@codecov

codecov Bot commented Jul 4, 2026 •

Copy link
Copy Markdown

Codecov Report

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

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

📢 Thoughts on this report? Let us know!

abcgco added 3 commits July 5, 2026 01:20
…budget

The inline is-not-None guard raised _calculate_usage_per_chunk's cyclomatic
complexity from 15 to 16 and tripped scripts/ruff_strict_gate.py (total 317
over limit 316). Move the guard into a _capture_prompt_tokens_details helper
mirroring _capture_cache_creation_token_details, restoring the function to
its base complexity
… fix-streaming-prompt-tokens-details-clobber

# Conflicts:
#	tests/test_litellm/litellm_core_utils/test_streaming_chunk_builder_utils.py
…guard

Keeps the UP045 strict-rule ratchet flat after merging litellm_internal_staging
@abcgco

abcgco commented Jul 26, 2026

Copy link
Copy Markdown
Author

@greptileai

@codspeed

codspeed Bot commented Jul 26, 2026

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing abcgco:fix-streaming-prompt-tokens-details-clobber (8e64e56) with litellm_internal_staging (2412326)

Open in CodSpeed

@yuneng-berri
yuneng-berri deleted the branch BerriAI:main September 13, 2026 04:28
@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:51
@devin-ai-integration
devin-ai-integration Bot requested a review from a team September 23, 2026 15:51
@mateo-berri

Copy link
Copy Markdown
Contributor

This got fixed on main by #34812, which keeps prompt_tokens_details when a later usage chunk lacks it. 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.

4 participants