Repository navigation
fix(responses): bill the provider-reported input on a cut bridged stream - #53394
Merged
mateo-berri merged 14 commits intoNov 23, 2026
Merged
mateo-berri merged 14 commits into
mateo-berri merged 14 commits into
Conversation
A /v1/responses stream that runs through the chat bridge and is cut mid-answer now bills the input and cache counts the provider sent before the cut, and the spend row carries the 499 ClientDisconnected marker that /v1/responses reads from litellm_metadata
Contributor
Contributor
Contributor
[High impact] The PR appears safe to merge, with no new actionable issues found.
|
…d the partial off the event loop
…stream The cut partial took its usage from the rebuild over every kept chunk but kept the response_cost the first build stamped from the estimate, and the logger uses a stamped cost before it prices the usage. The partial now carries the rebuild's cost along with its usage.
Contributor
Merged
5 of 7 tasks
…thropic's parser reads Anthropic's stream parser marks its message_start chunk, and the placeholder reset reads that mark instead of a provider list plus a Claude model name. Bedrock application inference profile ARNs and OpenCode Go's non-Claude models stream Anthropic's events too, and kept the 1-token output placeholder on a cut stream before.
…_stream_bills_provider_input # Conflicts: # litellm/llms/anthropic/chat/handler.py
A client that drops a bridged /v1/responses stream after the provider's first usage event but before any text logged no spend row, since the partial response was built only from relayed chunks. The partial now falls back to the chunks the stream wrapper kept, so the row bills the provider's input and cache counts with no output text
A cancelled background response whose stream teardown had already billed the cut also logged a second, failed 499 row. The background task now skips its own failure log once the teardown billed. A client cut after a mid-stream fallback billed both deployments' tokens at the fallback's price with no cache split, and now sums both partials' tokens, cache counts and cost the way MCP rounds are billed
…tream Each deployment's partial price already includes the fixed fee from cost_margin_config, so adding the first deployment's price to the fallback's charged that fee twice. The sum now takes off one fee, and the logged cost breakdown matches the billed total
Contributor
Contributor
Contributor
|
bugbot run |
A client cut after a mid-stream fallback now prices the first deployment's partial when the fallback starts, before the fallback changes the shared logging object's model, so its tokens keep their own price. An unpriced deployment bills nothing and keeps the other side's cost breakdown. The fixed fee is charged once at the final round's amount, and a fallback that fails after the cut leaves no breakdown from the first deployment's partial.
Contributor
Contributor
|
bugbot run |
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
…_stream_bills_provider_input
… cuts while the fallback connects
…_stream_bills_provider_input # Conflicts: # litellm/llms/anthropic/chat/handler.py
Contributor
Contributor
Contributor
|
bugbot run |
Contributor
Contributor
|
bugbot run |
Contributor
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 4972504. Configure here.
3 of 5 tasks
3 of 6 tasks
narmstrong-berri
added a commit
that referenced
this pull request
Nov 24, 2026
…our (#54223) Main's rust-wheel job fails 10 tests in tests/test_litellm_rust/messages, each pinned to behaviour a later PR changed on purpose. The stub check failed first until #53922, so the pytest step never reported them. Credential failures on Bedrock invoke and Mantle now answer a 401 AuthenticationError with the botocore error as its context (#53362). A 200 Bedrock stream whose body is JSON answers BedrockError 502 (#53482). A cut Bedrock stream drops the message_start output placeholder and re-counts the streamed text (#53394). Logging copies the resolved provider into litellm_params before callbacks run (#52709)
3 of 6 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Handwritten 1-3 sentence description
When a client drops a streaming /v1/responses call on Claude (Anthropic, Vertex AI, Azure AI or Bedrock invoke), or cancels a background response, the spend log now bills and prices the input and cache tokens the provider reported instead of LiteLLM's prompt estimate. The cut row is also marked as a client disconnect, like chat completions already do
Details
TLDR
Problem this solves:
How it solves it:
User Flow
Before: a cut /v1/responses call on Claude bills a guess at the prompt, with any prompt cache ignored
"stream": true(or"background": true) to ClaudeAfter: the same cut call bills the provider's input and cache counts and is marked as cut
Decisions
message_startchunk the stream wrapper keeps but never yields. Options were (a) make the wrapper yield usage-only chunks, which changes every chat stream consumer, (b) read usage off the logging object, which is only filled once the stream finishes, or (c) run the chunk builder over every chunk the wrapper kept and take only its usage. Chose (c). The response text still comes from the relayed chunks. The billed output is the provider's own output count when the stream carried one before the cut, and otherwise a count of the text the wrapper read. Gemini's running count includes the thinking tokens it bills as output, so a cut Gemini row now bills more output than before. Counting only the relayed text would drop output Gemini billed. If that second build fails, the bill built from the relayed chunks stands, so a cut call is never left unbilled. A cut before the bridge relayed any chunk (aftermessage_start, before the first text) now bills from the kept chunks with no output text, where it used to log no rowlitellm_metadataonly when that dict is already non-empty. The spend log readslitellm_metadatawhenever it is non-empty, so writing into an empty one would make it win overmetadataand drop the key's tags. Copying the marker across in the spend-metadata merge instead would touch every routemetadatavalue is now skipped instead of raising. Before, the recorder assumed a dict and would throw on anything else during stream teardownlitellm_metadatanow marks a cut stream, /v1/messages included, the same way the chat route already did. The alternative was to mark only /v1/responses, which would leave a cut /v1/messages row looking like a finished call. The row's status stays success, as on the chat route, since marking it failed would count a billed, partly answered call as a failed requestmessage_start, which the chunk builder replaces with a count of the text. Anthropic's stream parser now marks that chunk and the reset reads the mark, so it covers every stream that parser reads whatever the provider or model name, including Vertex AI, Azure AI, Bedrock invoke and its ARNs, Bedrock Mantle, Snowflake and OpenCode Go. A provider list plus a Claude model name missed the ARNs and OpenCode Go's other models. A lone usage event from any other parser keeps its countasyncio.to_thread, since rebuilding a long stream on the event loop would hold up every other request on that workerbilled_for_every_round, the helper MCP rounds already bill with, and the summed price is also written as the row's usage cost. Before, the fallback wrapper summed only the token counts at the fallback's price and dropped the cache split. A deployment the cost map cannot price bills 0 and keeps the other side's cost breakdown. Each partial's price already holds the fixed fee fromcost_margin_config, so the sum takes the first deployment's fee back off. A retry after a mid-stream break takes the same path and bills both attempts, since the provider charged for both. A fallback that runs to the end keeps the old sum, which is tracked separately. The row stays under the fallback's model, provider, deployment id and api_base, as a finished fallback does. That includes a cut while the fallback is still connecting, which bills only the first deployment's partial, at its own price. Moving the first deployment's labels back would mean writing the shared logging object from the disconnect thread while the router changes itPre-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 moreDelays 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
Before ran on main at
d1e9e7f034and After at4af80781bb0, with three fallback cells again at the tip4972504cf82. Both used one config, 2 workers, their own Postgres and Redis, and real provider APIs. Each case cuts the client, asks the provider for its count, and reads the key's /spend/logs row. Full output, config and case script are in this gistShared setup (config, env, proxy start, per-case variables)
Env var names:
ANTHROPIC_API_KEY,GEMINI_API_KEY,MISTRAL_API_KEY,OPENAI_API_KEY,VERTEXAI_PROJECT,GOOGLE_APPLICATION_CREDENTIALS,AZURE_FOUNDRY_API_BASE,AZURE_FOUNDRY_API_KEY,AWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEY,AWS_SESSION_TOKEN,LITELLM_MASTER_KEY,DATABASE_URL,REDIS_HOST,REDIS_PORTcutstream-haiku-stallgoes throughstall_relay.pyfrom the gist on port 23471. It forwards each call to api.anthropic.com, logs every event it relays, and holds the stream for 10 seconds aftermessage_start, so a client that gives up after 4 seconds is cut before any textcutstream-haiku-dropgoes throughdrop_relay.pyfrom the gist on port 21873. It forwards each call to api.anthropic.com and closes the connection 1 second aftermessage_start, so the router falls back tocutstream-haiku-stall, or tocutstream-haikuforcutstream-haiku-drop-direct, and to OpenAI'scutstream-openaiforcutstream-haiku-drop-openai. After ran with thecost_margin_configabove. Before ran without it, except the fallback and fee rows, which charged the global $0.001 on every provider. The full config.yaml in the gist adds the custom-price and free deployments its extra rows useCells are the cut row's billed prompt tokens out of the provider's count, on /v1/responses unless the row names another route
Fallback and fixed fee rows
Reading the rows
After spend is the billed tokens at the cost map's price plus the fixed fee. The cached turns split into 21637 cache-write and then 21637 cache-read tokens, matching Anthropic's
message_start. On the cut Vertex AI and Bedrock chat streams, Before billed Anthropic's 2-token placeholder and After billed 12 and 58, a count of the text each read. After bills 0 output tokens on the cut before any text. The fallback row adds the dropped first deployment's 25 input tokens to the fallback's 25 and prices both. On the fixed fee rows the fee is charged once, and both the cost breakdown's total and the row's usage cost match the spend. The OpenAI fallback row bills Claude's 25 input tokens plus OpenAI's 18, and OpenAI's $0.0005 fee once. A cut while the fallback is still connecting bills the first deployment's 25 input tokens at its own $0.00002 price plus the $0.001 fee, where Before wrote no rowBefore (d1e9e7f)
Responses stream, Anthropic
Responses stream cut before any text
Background cancel, Anthropic
Cache write and cache read turns
Responses stream, Vertex AI Claude
Responses stream, Azure AI Claude
Responses stream, Bedrock invoke
Responses stream, Bedrock converse
Responses stream, Gemini
Responses stream, Mistral
Chat stream, Anthropic
Chat stream, Vertex AI Claude
Chat stream, Bedrock invoke
Messages stream, Anthropic
Interactions stream, Gemini
Background cancel before any text
Background cancel after some text
Fallback, then cut before any text
Fixed fee, fallback, then cut after some text
Fixed fee, Claude falls back to OpenAI, then cut after some text
Fixed fee, cut after some text
Cut while the fallback is still connecting, on the /live-pr-risk rig at fd0ee2c
After (4af8078)
Carry from 4af8078 to the tip 4972504
The tip
4972504cf82changes one thing after4af80781bb0. When a fallback has connected, the summed price is also written as the row's usage cost. The three fallback cells below that connect a fallback ran again at that tip and now also read the row's usage cost, which matches the spend. A background cancel after a fallback ran on both sides too, and its cells are in the gist. The other cells carry from4af80781bb0because none of them reaches the fallback merge that commit changed. Focused checks at the tip were the 20 affected test files (2519 passed) andmake checkResponses stream, Anthropic
Responses stream cut before any text
Background cancel, Anthropic
Cache write and cache read turns
Responses stream, Vertex AI Claude
Responses stream, Azure AI Claude
Responses stream, Bedrock invoke
Responses stream, Bedrock converse
Responses stream, Gemini
Responses stream, Mistral
Chat stream, Anthropic
Chat stream, Vertex AI Claude
Chat stream, Bedrock invoke
Messages stream, Anthropic
Interactions stream, Gemini
Background cancel before any text
Background cancel after some text
Fallback, then cut before any text
Fixed fee, fallback, then cut after some text
Fixed fee, Claude falls back to OpenAI, then cut after some text
Fixed fee, cut after some text
Cut while the fallback is still connecting, on the /live-pr-risk rig at 4af8078
Type
🐛 Bug Fix
Caveats (if any)
Medium
litellm_metadataroutesLow
record_client_disconnectis_str_keyed_dictis reused from the guardrail cost module. Moving it is a separate refactorFinal Attestation
Bugbot summary