Repository navigation
fix(proxy): bill full provider usage on interrupted /chat/completions streams - #54542
kenneth-berri wants to merge 5 commits into
Conversation
… 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>
|
bugbot run |
[Medium impact] The PR appears safe to merge, with no new actionable issues found.
|
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
…the new test helpers
|
bugbot run |
…ait, always close the provider stream
|
bugbot run |
…tdown billing a minimum wait
|
bugbot run |
…in yields nothing
|
bugbot run |
There was a problem hiding this comment.
✅ 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.
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:
/v1/chat/completionsstreams log far fewer tokens than the provider billsHow it solves it:
/v1/messagesCHAT_COMPLETIONS_MAX_DETACHED_STREAM_DRAINS(default 100, 0 disables)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
"stream": trueand a prompt that produces a long answercompletion_tokensin the tensAfter: the same interrupted request is logged with the output tokens the provider billed
"stream": truecompletion_tokensin the thousands, in line with an uninterrupted runRelevant issues
Fixes #46499
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
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 moreThe new tests are
TestStreamingDisconnectDrainsProviderUsageintests/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.
--reloadwas 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:
Env vars:
LITELLM_MASTER_KEY,DATABASE_URL,ANTHROPIC_API_KEY,OPENAI_API_KEY, and an AWS profile with Bedrock access.config.yaml
Client, run once per model with
$TAGnaming the case. The control case drops| head -c 2000.Spend rows, read about three minutes later:
Before (333906b)
The three interrupted requests log 7, 24 and 12 output tokens. The uninterrupted Bedrock control logs 3176.
After (7df517e)
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
Low
/v1/responsesstreams are unchangedFinal Attestation
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/completionsSSE 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/messagesdisconnect-drain behavior.CustomStreamWrappergainsarm_disconnect_drainand shielded upstream reads so consumer cancellation does not tear down the provider iterator;common_request_processingspawns capped, timeout-bounded drains on disconnect, settles billing/logging/slot release, andproxy_serverarms drains for streaming requests and cancels running drains at shutdown with a minimum billing window. Router_AsyncChatStreamforwards drain targets and delays closing the attempt until drainage finishes.Tuning knobs:
CHAT_COMPLETIONS_MAX_DETACHED_STREAM_DRAINS(0 disables) andCHAT_COMPLETIONS_DETACHED_STREAM_DRAIN_TIMEOUT_SECONDS, plusDETACHED_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.