Skip to content

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

Open
nuernber wants to merge 2 commits into
BerriAI:mainfrom
nuernber:litellm_chat_completions_disconnect_full_spend
Open

nuernber wants to merge 2 commits into
BerriAI:mainfrom
nuernber:litellm_chat_completions_disconnect_full_spend

Conversation

@nuernber

@nuernber nuernber commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Interrupted /v1/chat/completions streams log far fewer tokens than Bedrock 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:

User Flow

Before: a team streaming long chat completions through the proxy sees spend that undercounts their AWS Bedrock 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. Bedrock keeps generating the full answer and bills every output token
  4. GET http://localhost:4000/spend/logs?request_id= shows completion_tokens in the tens, priced from the few chunks the app received

After: the same interrupted request is logged with the output tokens Bedrock actually 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. Bedrock keeps generating the full answer and bills every output token
  4. Once Bedrock finishes, GET http://localhost:4000/spend/logs?request_id= shows completion_tokens in the thousands, in line with an uninterrupted run of the same prompt

Relevant issues

Fixes #46499

Related: #33736 (added partial billing on disconnect), #34147, #35958, #36008 (full billing for /v1/messages)

Linear ticket

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/test_litellm/<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
  • 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)

The new tests are in 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. Three mutations were checked against them:

  • Reading the provider stream directly again, without the shielded read, fails the direct, router and post-disconnect error cases
  • Letting the router close the original attempt on teardown again fails the router case
  • Ignoring the drain cap fails the cap=1 case

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

Run against a local proxy calling live AWS Bedrock (us.anthropic.claude-sonnet-5, us-west-2), with Postgres for spend logs. Every request below hit the real Bedrock API and was billed by AWS

Proxy start command, the same for both runs:

uv run python litellm/proxy/proxy_cli.py --config config.yaml --port 4000 --detailed_debug 2>&1 | tee litellm.log

config.yaml deployment:

model_list:
- model_name: us.anthropic.claude-sonnet-5
  litellm_params:
    model: us.anthropic.claude-sonnet-5
    aws_profile_name: <profile>
    aws_region_name: us-west-2

Shared shell setup:

export MASTER_KEY=sk-<redacted> MODEL=us.anthropic.claude-sonnet-5
BODY='{"model":"'$MODEL'","stream":true,"max_tokens":8000,
  "messages":[{"role":"user","content":"Write a 3000 word story about a lighthouse keeper. Do not stop early."}]}'
KEY=$(curl -s -X POST http://localhost:4000/key/generate -H "Authorization: Bearer $MASTER_KEY" \
  -H "Content-Type: application/json" -d '{}' | jq -r .key)

Before (d8f162e)

Client disconnects after 2000 bytes

  1. Stream and disconnect early
curl -sN -D /tmp/h1.txt -X POST http://localhost:4000/v1/chat/completions \
  -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" -d "$BODY" | head -c 2000; echo
CALL1=$(grep -i '^x-litellm-call-id' /tmp/h1.txt | awk '{print $2}' | tr -d '\r')
  1. Read the spend log row
curl -s "http://localhost:4000/spend/logs?request_id=$CALL1" -H "Authorization: Bearer $MASTER_KEY" \
  | jq -c '.[0] | {request_id, prompt_tokens, completion_tokens, spend}'

Client reads the whole stream (control)

  1. Stream to the end
curl -sN -D /tmp/h2.txt -X POST http://localhost:4000/v1/chat/completions \
  -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" -d "$BODY" > /dev/null
CALL2=$(grep -i '^x-litellm-call-id' /tmp/h2.txt | awk '{print $2}' | tr -d '\r')
  1. Read the spend log row
curl -s "http://localhost:4000/spend/logs?request_id=$CALL2" -H "Authorization: Bearer $MASTER_KEY" \
  | jq -c '.[0] | {request_id, prompt_tokens, completion_tokens, spend}'

After (73ea3b9)

Client disconnects after 2000 bytes

  1. Stream and disconnect early
curl -sN -D /tmp/h1.txt -X POST http://localhost:4000/v1/chat/completions \
  -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" -d "$BODY" | head -c 2000; echo
CALL1=$(grep -i '^x-litellm-call-id' /tmp/h1.txt | awk '{print $2}' | tr -d '\r')
  1. Read the spend log row once Bedrock has finished generating (about a minute or two later)
curl -s "http://localhost:4000/spend/logs?request_id=$CALL1" -H "Authorization: Bearer $MASTER_KEY" \
  | jq -c '.[0] | {request_id, prompt_tokens, completion_tokens, spend}'

Client reads the whole stream (control)

  1. Stream to the end
curl -sN -D /tmp/h2.txt -X POST http://localhost:4000/v1/chat/completions \
  -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" -d "$BODY" > /dev/null
CALL2=$(grep -i '^x-litellm-call-id' /tmp/h2.txt | awk '{print $2}' | tr -d '\r')
  1. Read the spend log row
curl -s "http://localhost:4000/spend/logs?request_id=$CALL2" -H "Authorization: Bearer $MASTER_KEY" \
  | jq -c '.[0] | {request_id, prompt_tokens, completion_tokens, spend}'

Type

🐛 Bug Fix

Caveats (if any)

Medium

  • Other streams that wrap a chat stream still bill partially on disconnect
    • /v1/messages through the chat adapter
    • /v1/responses bridged to chat completions
    • streams after a mid-stream fallback took over
  • A drain keeps the provider connection open until generation ends
    • It also holds the deployment's parallel-request slot for that time
    • Capped at 100 concurrent drains, after which the old partial billing applies
  • A provider error during the drain now logs a failure row with partial usage
    • Previously the disconnect logged a success row with partial usage

Low

  • Armed streams read each chunk through its own task: small per-chunk cost on the proxy path only
  • The router now leaves the attempt open until the proxy closes the stream
    • Assumed: every proxy path that arms the drain always closes the response, which async_data_generator does in its cleanup
  • New env var CHAT_COMPLETIONS_MAX_DETACHED_STREAM_DRAINS is excluded from the env-key docs test, like the /v1/messages drain settings

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

… streams

A client disconnect cancelled the in-flight provider read and the router closed
the attempt, so spend logs only held an estimate from the chunks the client got.
Armed streams now read through a shielded task and a bounded detached drain reads
them to the terminal usage chunk, matching what BerriAI#36008 did for /v1/messages.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@veria-ai

veria-ai Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

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

Security review

No open security issues remain on this pull request.

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

The drain cap only bounded how many drains run, so a stalled provider could hold
a drain slot, its buffered chunks and the request's concurrency slot forever.
Each drain now stops at CHAT_COMPLETIONS_DETACHED_STREAM_DRAIN_TIMEOUT_SECONDS
(default 600), bills the chunks read so far and closes the provider stream.
@CLAassistant

CLAassistant commented Nov 5, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

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

2 participants