Skip to content

fix(proxy): bill full provider usage on interrupted /chat/completions streams - #54542

Open
kenneth-berri wants to merge 5 commits into
mainfrom
litellm_chat_stream_disconnect_full_usage
Open

kenneth-berri wants to merge 5 commits into
mainfrom
litellm_chat_stream_disconnect_full_usage

Conversation

@kenneth-berri

@kenneth-berri kenneth-berri commented Nov 25, 2026 •

Copy link
Copy Markdown
Collaborator

Handwritten 1-3 sentence description

When a client hangs up in the middle of a streamed chat completion, the spend log now shows the tokens the provider actually generated and billed. Before, it only counted the few tokens sent before the hangup.

Details

Link to Devin session: https://app.devin.ai/sessions/5626335e14d7474a89303a290d8780ae
Open in Devin Desktop: https://app.devin.ai/desktop/session/5626335e14d7474a89303a290d8780ae?variant=devin
Requested by: @kenneth-berri

TLDR

Problem this solves:

  • Interrupted /v1/chat/completions streams log far fewer tokens than the provider bills
  • The proxy stops reading the provider stream when the client leaves
  • Spend is estimated from the few chunks the client received

How it solves it:

  • Provider reads survive the client's disconnect instead of being cancelled
  • A detached task reads the stream to its final usage chunk
  • That usage is billed, as fix(anthropic_messages): drain upstream in a detached pump so client … #36008 did for /v1/messages
  • The drained tokens also count on the router's deployment counters
  • Concurrent drains capped by CHAT_COMPLETIONS_MAX_DETACHED_STREAM_DRAINS (default 100, 0 disables)
  • Each drain limited by CHAT_COMPLETIONS_DETACHED_STREAM_DRAIN_TIMEOUT_SECONDS (default 600)

This ports #49715 by @nuernber onto current main, where the router's stream wrapper has since moved, and credits them as co-author.

User Flow

Before: a team streaming long chat completions through the proxy sees spend that undercounts their provider bill whenever a client stops reading early

  1. Their app sends POST http://localhost:4000/v1/chat/completions with "stream": true and a prompt that produces a long answer
  2. The app reads the first 2000 bytes of the SSE stream and closes the connection
  3. The provider keeps generating the full answer and bills every output token
  4. GET http://localhost:4000/spend/logs shows that request with completion_tokens in the tens

After: the same interrupted request is logged with the output tokens the provider billed

  1. Their app sends the same POST http://localhost:4000/v1/chat/completions with "stream": true
  2. The app reads the first 2000 bytes of the SSE stream and closes the connection
  3. The provider keeps generating the full answer and bills every output token
  4. Once the provider finishes, GET http://localhost:4000/spend/logs shows that request with completion_tokens in the thousands, in line with an uninterrupted run

Relevant issues

Fixes #46499

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

The new tests are TestStreamingDisconnectDrainsProviderUsage in tests/unit/proxy/test_common_request_processing.py. A custom provider holds back the end of its stream, including its final usage of 50 prompt and 2000 completion tokens, until after the client has disconnected mid-read. With the shielded read turned off, the direct, router and post-disconnect error cases fail.

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

Both legs ran against live providers with Postgres for spend logs, two workers and one dedicated Redis. --reload was dropped because it serves only one worker. Before is the merge base 333906b, After is the tip 7df517e.

Proxy start command, the same for both legs:

python litellm/proxy/proxy_cli.py --config config.yaml --port 4000 --num_workers 2 --detailed_debug --use_v2_migration_resolver

Env vars: LITELLM_MASTER_KEY, DATABASE_URL, ANTHROPIC_API_KEY, OPENAI_API_KEY, and an AWS profile with Bedrock access.

config.yaml
model_list:
  - model_name: bedrock-claude-sonnet
    litellm_params:
      model: bedrock/us.anthropic.claude-sonnet-4-5-20250929-v1:0
      aws_region_name: us-west-2
      aws_profile_name: <profile>
  - model_name: anthropic-sonnet
    litellm_params:
      model: anthropic/claude-sonnet-5
      api_key: os.environ/ANTHROPIC_API_KEY
  - model_name: openai-chat
    litellm_params:
      model: openai/gpt-5.5
      api_key: os.environ/OPENAI_API_KEY

router_settings:
  redis_host: 127.0.0.1
  redis_port: 6390

general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY
  database_url: os.environ/DATABASE_URL
  coordination_redis:
    host: 127.0.0.1
    port: 6390

Client, run once per model with $TAG naming the case. The control case drops | head -c 2000.

curl -sN -X POST http://localhost:4000/v1/chat/completions \
  -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json" \
  -d '{"model":"'$MODEL'","user":"'$TAG'","stream":true,"max_tokens":8000,
       "messages":[{"role":"user","content":"Write a 3000 word story about a lighthouse keeper. Do not stop early."}]}' \
  | head -c 2000 > /dev/null

Spend rows, read about three minutes later:

psql "$DATABASE_URL" -At -F ' | ' -c "select end_user, model, status, prompt_tokens, completion_tokens, round(spend::numeric,6) from \"LiteLLM_SpendLogs\" where end_user like '$LEG-%' order by end_user"

Before (333906b)

before-anthropic-sonnet-cut | anthropic/claude-sonnet-5 | success | 33 | 7 | 0.000136
before-bedrock-claude-sonnet-cut | bedrock/us.anthropic.claude-sonnet-4-5-20250929-v1:0 | success | 25 | 24 | 0.000479
before-bedrock-claude-sonnet-full | bedrock/us.anthropic.claude-sonnet-4-5-20250929-v1:0 | success | 25 | 3176 | 0.052487
before-openai-chat-cut | openai/gpt-5.5 | success | 24 | 12 | 0.000480

The three interrupted requests log 7, 24 and 12 output tokens. The uninterrupted Bedrock control logs 3176.

After (7df517e)

tip4-anthropic-sonnet-cut | anthropic/claude-sonnet-5 | success | 33 | 6429 | 0.064356
tip4-bedrock-claude-sonnet-cut | bedrock/us.anthropic.claude-sonnet-4-5-20250929-v1:0 | success | 25 | 3704 | 0.061199
tip4-bedrock-claude-sonnet-full | bedrock/us.anthropic.claude-sonnet-4-5-20250929-v1:0 | success | 25 | 3286 | 0.054302
tip4-openai-chat-cut | openai/gpt-5.5 | success | 23 | 7971 | 0.239245

The three interrupted requests now log 6429, 3704 and 7971 output tokens, and each row appears only once the provider has finished. The interrupted Bedrock request lands next to its uninterrupted control (3704 against 3286).

Type

🐛 Bug Fix

Caveats (if any)

Medium

  • A stream that already fell back mid-stream is still billed on partial chunks
  • Drains still running at shutdown are stopped and billed on the chunks read
    • They get at least one second to bill, more when the shutdown budget allows
  • A request with post-call guardrails armed is still billed on partial chunks
  • Provider-side billing was not read from the provider consoles
    • The uninterrupted control run is the yardstick instead
  • A drain holds the key's parallel-request slot until the provider finishes

Low

  • Providers streamed through a sync iterator are not drained
  • /v1/responses streams are 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

Note

Medium Risk
Changes proxy disconnect handling, concurrency slot release, and spend logging for streaming chat completions—billing correctness improves but drains can hold resources until timeout or provider EOF.

Overview
When a client drops a /v1/chat/completions SSE connection mid-stream, the proxy can now keep reading the provider in a detached background task so spend logs reflect the provider’s terminal usage, not just tokens already sent to the client—mirroring the existing /v1/messages disconnect-drain behavior.

CustomStreamWrapper gains arm_disconnect_drain and shielded upstream reads so consumer cancellation does not tear down the provider iterator; common_request_processing spawns capped, timeout-bounded drains on disconnect, settles billing/logging/slot release, and proxy_server arms drains for streaming requests and cancels running drains at shutdown with a minimum billing window. Router _AsyncChatStream forwards drain targets and delays closing the attempt until drainage finishes.

Tuning knobs: CHAT_COMPLETIONS_MAX_DETACHED_STREAM_DRAINS (0 disables) and CHAT_COMPLETIONS_DETACHED_STREAM_DRAIN_TIMEOUT_SECONDS, plus DETACHED_STREAM_DRAIN_SHUTDOWN_BILLING_MIN_SECONDS.

Reviewed by Cursor Bugbot for commit 7df517e. Bugbot is set up for automated code reviews on this repo. Configure here.

… streams

When a client disconnects mid-stream the proxy now keeps reading the provider
stream in a detached task until its final usage chunk and bills that, as
/v1/messages already does. Drains are capped and time-limited.

Ports #49715 onto current main.

Co-authored-by: nuernber <benjamin.nuernberger@jpl.nasa.gov>
@kenneth-berri

Copy link
Copy Markdown
Collaborator Author

@greptile

@kenneth-berri

Copy link
Copy Markdown
Collaborator Author

bugbot run

@veria-ai

veria-ai Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

All previously flagged issues have been addressed. No open security concerns remain on this pull request.

Fixed/addressed: 1 · PR risk: 0/10

Reviews

@greptile-apps

greptile-apps Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5 · The PR appears safe to merge, with no new actionable issues found.RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge, with no new actionable issues found.

Summary

The PR keeps reading interrupted chat streams so spend logs can use the provider's final usage. The latest change reads saved usage when a detached drain reaches the end without returning another chunk.

  • Interrupted async chat streams can be read through to the provider’s final usage.

Reviews (6) · Last reviewed commit: "fix(proxy): read a drained stream's usag..." · Reviewed by Greptile

Comment thread litellm/router_rust/invoke/streaming.py Resolved

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

Stale Bugbot comment from a previous run.

Comment thread litellm/router_rust/invoke/streaming.py Resolved
@codecov

codecov Bot commented Nov 25, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@kenneth-berri

Copy link
Copy Markdown
Collaborator Author

@greptile

@kenneth-berri

Copy link
Copy Markdown
Collaborator 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.

Stale Bugbot comment from a previous run.

@kenneth-berri

Copy link
Copy Markdown
Collaborator Author

@greptile

@kenneth-berri

Copy link
Copy Markdown
Collaborator Author

bugbot run

Comment thread litellm/router_rust/invoke/streaming.py Resolved

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

Stale Bugbot comment from a previous run.

@kenneth-berri

Copy link
Copy Markdown
Collaborator Author

@greptile

Comment thread litellm/router_rust/invoke/streaming.py Resolved
@kenneth-berri

Copy link
Copy Markdown
Collaborator Author

@greptile

@kenneth-berri

Copy link
Copy Markdown
Collaborator 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.

Stale Bugbot comment from a previous run.

@kenneth-berri

Copy link
Copy Markdown
Collaborator Author

@greptile

@kenneth-berri

Copy link
Copy Markdown
Collaborator 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 7df517e. Configure here.

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]: Interrupted streaming /chat/completions logs partial spend instead of full provider-billed usage

1 participant