Skip to content

fix(anthropic): log partial stream spend when a /v1/messages client disconnects mid-stream - #37558

Merged
mateo-berri merged 1 commit into
litellm_internal_stagingfrom
litellm_v1_messages_partial_stream_usage
Aug 20, 2026
Merged

mateo-berri merged 1 commit into
litellm_internal_stagingfrom
litellm_v1_messages_partial_stream_usage

Conversation

@mateo-berri

@mateo-berri mateo-berri commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Canceled Bedrock /v1/messages streams recorded zero spend
  • Partial output tokens Bedrock already billed vanished from budgets

How it solves it:

  • Client disconnects now dispatch the stream's spend logging on teardown
  • Output tokens are recovered from the chunks already streamed

User Flow

Before: a developer streams a Bedrock-backed answer through /v1/messages, their end user cancels mid-answer, and the request never shows up in spend tracking

  1. They send POST https://litellm-domain/v1/messages with "model": "bedrock-claude-opus-5", "stream": true, and "max_tokens": 4000
  2. SSE events start arriving; mid-answer their end user hits stop, so the client closes the connection
  3. They query GET https://litellm-domain/spend/logs?request_id= and get [] back no matter how long they wait
  4. https://litellm-domain/ui/?page=logs has no row for the request, so the tokens Bedrock generated and billed are invisible to budgets and chargeback

After: the same canceled stream lands in spend logs within seconds, with the partial output tokens counted

  1. They send POST https://litellm-domain/v1/messages with "model": "bedrock-claude-opus-5", "stream": true, and "max_tokens": 4000
  2. SSE events start arriving; mid-answer their end user hits stop, so the client closes the connection
  3. GET https://litellm-domain/spend/logs?request_id= returns one success row seconds later, with the prompt tokens plus the output tokens generated before the cancel and their real cost
  4. https://litellm-domain/ui/?page=logs shows the request with that partial spend, and a stream left to finish normally is logged exactly as before

Relevant issues

Linear ticket

Resolves LIT-5839

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

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

Shared setup, both sides identical: proxy from the tree under test with a fresh Postgres DB, real Bedrock calls in us-east-1

model_list:
  - model_name: bedrock-claude-opus-5
    litellm_params:
      model: bedrock/us.anthropic.claude-opus-5
      aws_region_name: us-east-1
python litellm/proxy/proxy_cli.py --config repro_config.yaml --port 44545 --detailed_debug --use_v2_migration_resolver

Before (eecb226)

Control: stream left to complete

  1. curl -s -N -D headers http://127.0.0.1:44545/v1/messages -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "anthropic-version: 2023-06-01" -H "Content-Type: application/json" -d '{"model":"bedrock-claude-opus-5","stream":true,"max_tokens":600,"messages":[{"role":"user","content":"Write about 400 words on how rivers shape landscapes."}]}'
  2. Full SSE stream ends in message_stop with "usage": {"input_tokens": 25, "output_tokens": 600}, x-litellm-call-id: 23eea144-e8c7-4fe1-8a72-f5d28be8d648
  3. curl -s "http://127.0.0.1:44545/spend/logs?request_id=23eea144-e8c7-4fe1-8a72-f5d28be8d648" -H "Authorization: Bearer $LITELLM_MASTER_KEY" returns one row: status success, call_type anthropic_messages, prompt_tokens 25, completion_tokens 600, total_tokens 625, spend 0.0166375

Client disconnect mid-stream

  1. Same POST with "max_tokens": 4000 and a longer prompt, piped through | head -n 150 so curl exits mid-stream after 50 SSE events, x-litellm-call-id: 62b260f4-c72f-4a79-987f-3aea51b6a521
  2. curl -s "http://127.0.0.1:44545/spend/logs?request_id=62b260f4-c72f-4a79-987f-3aea51b6a521" -H "Authorization: Bearer $LITELLM_MASTER_KEY" polled every 3s for 45s returns [] every time: the tokens Bedrock generated and billed are never tracked

After (9209bb6)

Control: stream left to complete

  1. Same POST as Before, x-litellm-call-id: 23c11e3c-09f9-47dd-88fd-94b7a40b9b8c
  2. Full SSE stream ends in message_stop with "usage": {"input_tokens": 25, "output_tokens": 600}
  3. curl -s "http://127.0.0.1:44545/spend/logs?request_id=23c11e3c-09f9-47dd-88fd-94b7a40b9b8c" -H "Authorization: Bearer $LITELLM_MASTER_KEY" returns one row identical in shape to Before: status success, call_type anthropic_messages, prompt_tokens 25, completion_tokens 600, total_tokens 625, spend 0.0166375

Client disconnect mid-stream

  1. Same POST piped through | head -n 150, curl exits after 50 SSE events, x-litellm-call-id: 61a2b61c-13d0-4bcf-b50a-6cc21a69427a
  2. curl -s "http://127.0.0.1:44545/spend/logs?request_id=61a2b61c-13d0-4bcf-b50a-6cc21a69427a" -H "Authorization: Bearer $LITELLM_MASTER_KEY" returns one row at the first 3s poll: status success, call_type anthropic_messages, prompt_tokens 23, completion_tokens 115, total_tokens 138, spend 0.003289

Type

🐛 Bug Fix

Caveats (if any)

  • Upstream provider stream errors still take the failure-logging path, unchanged

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

  • 9209bb6 passes /live-pr-risk

@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@greptile-apps

greptile-apps Bot commented Aug 20, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

The PR ensures partial Anthropic Messages stream spend is dispatched when a client disconnects or consumption is cancelled.

  • Routes streaming success logging through the rooted global logging worker.
  • Logs chunks collected before generator teardown and preserves the original cancellation.
  • Deterministically closes the inner Anthropic SSE wrapper from the Bedrock adapter.
  • Adds focused tests for disconnect, cancellation, pre-first-chunk teardown, and Bedrock wrapper propagation.

Confidence Score: 5/5

The PR appears safe to merge, with the disconnect and cancellation paths covered by focused regression tests and no actionable defects identified.

The changed teardown flow logs collected chunks once, preserves cancellation, leaves normal completion behavior intact, and deterministically reaches partial-spend dispatch from the Bedrock wrapper.

Important Files Changed

Filename Overview
litellm/llms/anthropic/experimental_pass_through/messages/streaming_iterator.py Dispatches normal and partial-stream logging through the global worker and logs collected chunks during generator cancellation or closure.
litellm/llms/bedrock/messages/invoke_transformations/anthropic_claude3_transformation.py Closes the inner SSE generator during Bedrock wrapper teardown so disconnect-driven partial logging runs deterministically.
tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_streaming_iterator.py Adds coverage for partial logging on explicit closure and cancellation, including the zero-chunk case.
tests/test_litellm/llms/bedrock/messages/invoke_transformations/test_anthropic_claude3_transformation.py Verifies closing the outer Bedrock stream reaches the inner logging handler.

Reviews (1): Last reviewed commit: "fix(anthropic): log partial stream spend..." | Re-trigger Greptile

@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 9209bb6. Configure here.

@codecov

codecov Bot commented Aug 20, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@codspeed

codspeed Bot commented Aug 20, 2026

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_v1_messages_partial_stream_usage (9209bb6) with litellm_internal_staging (f22eeb2)1

Open in CodSpeed

Footnotes

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

@mateo-berri
mateo-berri enabled auto-merge (squash) August 20, 2026 01:32
@mateo-berri
mateo-berri merged commit 8922aaa into litellm_internal_staging Aug 20, 2026
72 checks passed
@mateo-berri
mateo-berri deleted the litellm_v1_messages_partial_stream_usage branch August 20, 2026 01:43
@nuernber

Copy link
Copy Markdown
Contributor

While this is an improvement, this does not fix the regression introduced at some point between v1.79.1 and v1.83.14. See #35958 and #36008. Importantly, for AWS Bedrock, partial spend logs is not good enough because AWS CUR records the full spend of the API request, not a partial spend.

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.

3 participants