Repository navigation
fix(proxy): log mid-stream /v1/messages failures as failures with partial usage - #39589
Conversation
…tial usage A provider read timeout after the 200 was already committed on a streamed /v1/messages request used to run the success logging path, so the failure callbacks never fired and the failure metrics stayed flat. The pass-through stream handler and the Bedrock relay iterator now dispatch the failure handlers instead, with the usage and cost of the chunks already delivered stashed on the logging object so the failure row still bills them.
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
Greptile SummaryThis PR records mid-stream provider and pass-through failures as failures while retaining usage already consumed.
Confidence Score: 5/5The PR appears safe to merge. No blocking failure remains.
|
| Filename | Overview |
|---|---|
| litellm/litellm_core_utils/litellm_logging.py | Adds storage for partial failure usage and a detached-stream failure callback without an accepted blocking issue. |
| litellm/llms/anthropic/experimental_pass_through/messages/streaming_iterator.py | Routes upstream stream exceptions through failure logging while preserving separate client-disconnect handling. |
| litellm/proxy/common_request_processing.py | Arms detached failure reporting for native Anthropic message streams. |
| litellm/proxy/hooks/parallel_request_limiter_v3.py | Reconciles failed stream reservations against recovered usage. |
| litellm/proxy/pass_through_endpoints/llm_provider_handlers/anthropic_passthrough_logging_handler.py | Reuses existing Anthropic stream assembly to retain partial usage on failures. |
| litellm/proxy/pass_through_endpoints/pass_through_endpoints.py | Reports pass-through relay failures through the proxy failure-hook lifecycle. |
| litellm/proxy/pass_through_endpoints/streaming_handler.py | Schedules failure rather than success logging when an upstream stream raises. |
Reviews (8): Last reviewed commit: "fix(anthropic): bill an uncostable parti..." | Re-trigger Greptile
PR overviewAll previously flagged issues have been addressed. No open security concerns remain on this pull request. Security reviewNo open security issues remain on this pull request. Fixed/addressed: 2 · PR risk: 0/10 |
…ging branch Keeps staging's response-id keying next to the pass-through failure-path helpers and types the read-only raw_bytes parameters as Sequence[bytes] so the merged tree stays inside the lint budgets
|
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 f15bdfb. Configure here.
…/litellm into litellm_fix_v1_messages_midstream_timeout_failure_logging
…/litellm into litellm_fix_v1_messages_midstream_timeout_failure_logging # Conflicts: # litellm/litellm_core_utils/litellm_logging.py
|
bugbot run |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.
Autofix Details
Bugbot Autofix prepared a fix for the issue found in the latest run.
- ✅ Fixed: Cost error drops recovered stream usage
- When _compute_response_cost raises, we now still call record_partial_usage_for_failure with response_cost=0.0 so the recovered usage is stashed and the TPM reservation settles, matching the non-Anthropic path.
Or push these changes by commenting:
@cursor push adca647929
Preview (adca647929)
diff --git a/litellm/proxy/pass_through_endpoints/llm_provider_handlers/anthropic_passthrough_logging_handler.py b/litellm/proxy/pass_through_endpoints/llm_provider_handlers/anthropic_passthrough_logging_handler.py
--- a/litellm/proxy/pass_through_endpoints/llm_provider_handlers/anthropic_passthrough_logging_handler.py
+++ b/litellm/proxy/pass_through_endpoints/llm_provider_handlers/anthropic_passthrough_logging_handler.py
@@ -246,10 +246,11 @@
model=AnthropicPassthroughLoggingHandler._resolve_costing_model(model, litellm_logging_obj),
logging_obj=litellm_logging_obj,
)
- except Exception as e: # noqa: BLE001 # an uncostable partial stream must still log as a failure
+ except Exception as e: # noqa: BLE001 # an uncostable partial stream must still log its recovered usage so TPM settles correctly
verbose_proxy_logger.warning(
"Anthropic passthrough: could not cost the partial usage of a failed stream (model=%s): %s", model, e
)
+ litellm_logging_obj.record_partial_usage_for_failure(usage=usage, response_cost=0.0)
return
litellm_logging_obj.record_partial_usage_for_failure(usage=usage, response_cost=response_cost)
diff --git a/tests/test_litellm/proxy/pass_through_endpoints/llm_provider_handlers/test_anthropic_passthrough_logging_handler.py b/tests/test_litellm/proxy/pass_through_endpoints/llm_provider_handlers/test_anthropic_passthrough_logging_handler.py
--- a/tests/test_litellm/proxy/pass_through_endpoints/llm_provider_handlers/test_anthropic_passthrough_logging_handler.py
+++ b/tests/test_litellm/proxy/pass_through_endpoints/llm_provider_handlers/test_anthropic_passthrough_logging_handler.py
@@ -2516,3 +2516,24 @@
assert "combined_usage_object" not in logging_obj.model_call_details
assert "response_cost" not in logging_obj.model_call_details
+
+ def test_stashes_partial_usage_with_zero_cost_when_costing_raises(self):
+ """If completion_cost blows up (unknown model, missing price map, custom
+ pricing lookup error), we must still stash the recovered usage so the
+ TPM reservation settles and the spend row keeps the provider-billed
+ tokens; only the response_cost falls back to 0."""
+ logging_obj = self._make_logging_obj()
+
+ with patch(
+ "litellm.proxy.pass_through_endpoints.llm_provider_handlers.anthropic_passthrough_logging_handler.litellm.completion_cost",
+ side_effect=RuntimeError("no price map for this model"),
+ ):
+ AnthropicPassthroughLoggingHandler.record_partial_usage_for_failure(
+ litellm_logging_obj=logging_obj,
+ request_body={"model": "claude-sonnet-5", "stream": True},
+ all_chunks=self._interrupted_chunks(),
+ )
+
+ usage = logging_obj.model_call_details["combined_usage_object"]
+ assert usage.prompt_tokens == 52
+ assert logging_obj.model_call_details["response_cost"] == 0.0You can send follow-ups to the cloud agent here.
…o cost instead of dropping its usage
|
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 6c27754. Configure here.
44b1cc7
into
litellm_internal_staging

TLDR
Problem this solves:
/v1/messageswas logged as a success/anthropic/*, custom pass-through) logged a dropped stream as success too/v1/chat/completionsalready logged the same timeout as a failureHow it solves it:
User Flow
Before: an operator fronting Claude Code with the gateway sees provider timeouts mid-stream counted as successes, so their timeout alerts and failure dashboards undercount
ANTHROPIC_BASE_URL=https://litellm-domainand sends a promptPOST https://litellm-domain/v1/messageswith"stream": trueand gets a 200 with the first SSE eventsstream_timeoutthe stream ends withdata: {"error": {"message": "Timeout on reading data from socket", ...}}, Claude Code shows the API error and retriesstatus: "success", and no failure eventGET https://litellm-domain/spend/logs?request_id=<x-litellm-call-id>shows the request withstatus: "success"GET https://litellm-domain/metricsshowslitellm_deployment_success_responses_totalup by one for that request whilelitellm_deployment_failure_responses_totalandlitellm_llm_api_failed_requests_metric_totaldo not moveAfter: the same timeout is recorded as a failure everywhere the operator looks
ANTHROPIC_BASE_URL=https://litellm-domainand sends a promptPOST https://litellm-domain/v1/messageswith"stream": trueand gets a 200 with the first SSE eventsstream_timeoutthe stream ends withdata: {"error": {"message": "Timeout on reading data from socket", ...}}, Claude Code shows the API error and retriesstatus: "failure", the error textTimeout on reading data from socket, exception classReadTimeout, and the usage and cost of the chunks that were delivered, and no success eventGET https://litellm-domain/spend/logs?request_id=<x-litellm-call-id>shows the request withstatus: "failure"and the partial spendGET https://litellm-domain/metricsshowslitellm_deployment_failure_responses_total{exception_class="ReadTimeout"}andlitellm_llm_api_failed_requests_metric_totalup by one for that request and no success counter movesRelevant issues
Fixes #29602
Linear ticket
Resolves LIT-3798
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
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@greptileaito 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 for both sides
max_tokens < 1500pass through untouched, so Claude Code's small helper calls succeed and only its main answer stallsstream_timeout: 5, so on model routes the proxy's own read timeout fires before the relay drops. Pass-through routes have no stream timeout, so there the relay's drop is what the proxy sees/anthropic/*pass-through leg addressesapi.anthropic.comthrough the relay acting as an HTTP forward proxy (ANTHROPIC_API_BASE=http://api.anthropic.com HTTP_PROXY=http://127.0.0.1:37432), so the upstream URL the proxy classifies is Anthropic's own. The Claude Code legs address the relay directly as the model'sapi_base. The/gemini/*pass-through leg setsGEMINI_API_BASE=http://127.0.0.1:37432on the proxy and the relay forwards togenerativelanguage.googleapis.com--num_workers 2), Postgres-backed, a coordination Redis shared by every proxy process so rate-limit counters live outside any one process,prometheusplus a custom logger callback that appends one JSON line perasync_log_success_event,async_log_failure_event, andasync_post_call_failure_hookit receives. Before boots the merge base 4990f06, After boots 6c27754; each case names the port it hit. Real provider calls, real costclaude -pConfig
Before (4990f06)
Claude Code, mid-stream timeout on /v1/messages
env -u ANTHROPIC_API_KEY ANTHROPIC_BASE_URL=http://127.0.0.1:47120 ANTHROPIC_AUTH_TOKEN=sk-lit3798 ANTHROPIC_MODEL=claude-sonnet-5 ANTHROPIC_SMALL_FAST_MODEL=claude-sonnet-5 ANTHROPIC_DEFAULT_HAIKU_MODEL=claude-sonnet-5 ANTHROPIC_DEFAULT_SONNET_MODEL=claude-sonnet-5 claude --model claude-sonnet-5, then the promptWrite 150 words about the sea.Bedrock invoke, mid-stream timeout on /v1/messages
curl -sN --max-time 60 http://127.0.0.1:47120/v1/messages -H 'Authorization: Bearer sk-lit3798' -H 'content-type: application/json' -d '{"model":"bedrock-claude","max_tokens":2000,"stream":true,"messages":[{"role":"user","content":"Write 300 words about the sea."}]}' | tail -c 300x-litellm-call-id: f9742a6d-dd20-401f-844c-4cdce17af86a)curl -s "http://127.0.0.1:47120/spend/logs?request_id=f9742a6d-dd20-401f-844c-4cdce17af86a" -H 'Authorization: Bearer sk-lit3798'Anthropic pass-through, mid-stream drop on /anthropic/v1/messages
curl -sN --max-time 60 -H anthropic-version: 2023-06-01 http://127.0.0.1:47120/anthropic/v1/messages -H 'Authorization: Bearer sk-lit3798' -H 'content-type: application/json' -d '{"model":"claude-sonnet-5","max_tokens":2000,"stream":true,"messages":[{"role":"user","content":"Write 300 words about the sea."}]}' | tail -c 300x-litellm-call-id: 8a8eebbc-5408-44b3-a73a-e0f094f068e6)curl -s "http://127.0.0.1:47120/spend/logs?request_id=8a8eebbc-5408-44b3-a73a-e0f094f068e6" -H 'Authorization: Bearer sk-lit3798'Custom pass-through endpoint, mid-stream drop on /relay-chat
curl -sN --max-time 60 http://127.0.0.1:47120/relay-chat -H 'Authorization: Bearer sk-lit3798' -H 'content-type: application/json' -d '{"model":"gpt-5.6","max_completion_tokens":2000,"stream":true,"messages":[{"role":"user","content":"Write 300 words about the sea."}]}' | tail -c 300x-litellm-call-id: 29ea36a1-26ff-4601-b0bb-43182290ec35)curl -s "http://127.0.0.1:47120/spend/logs?request_id=29ea36a1-26ff-4601-b0bb-43182290ec35" -H 'Authorization: Bearer sk-lit3798'Client disconnect on /v1/messages (must stay a partial success)
curl -sN --max-time 60 --max-time 2 http://127.0.0.1:47120/v1/messages -H 'Authorization: Bearer sk-lit3798' -H 'content-type: application/json' -d '{"model":"claude-sonnet-5","max_tokens":1200,"stream":true,"messages":[{"role":"user","content":"Write 300 words about the sea."}]}' | tail -c 300x-litellm-call-id: 70759125-9481-4ab1-a51d-8242e67171a4)curl -s "http://127.0.0.1:47120/spend/logs?request_id=70759125-9481-4ab1-a51d-8242e67171a4" -H 'Authorization: Bearer sk-lit3798'Completed stream on /v1/messages (must stay a success)
curl -sN --max-time 60 http://127.0.0.1:47120/v1/messages -H 'Authorization: Bearer sk-lit3798' -H 'content-type: application/json' -d '{"model":"claude-sonnet-5","max_tokens":100,"stream":true,"messages":[{"role":"user","content":"Say hi in five words."}]}' | tail -c 300x-litellm-call-id: 487b7626-da7a-48bc-a9e1-08d8cf82030c)curl -s "http://127.0.0.1:47120/spend/logs?request_id=487b7626-da7a-48bc-a9e1-08d8cf82030c" -H 'Authorization: Bearer sk-lit3798'/v1/chat/completions, mid-stream timeout (already a failure)
curl -sN --max-time 60 http://127.0.0.1:47120/v1/chat/completions -H 'Authorization: Bearer sk-lit3798' -H 'content-type: application/json' -d '{"model":"gpt-5.6","max_completion_tokens":2000,"stream":true,"messages":[{"role":"user","content":"Write 300 words about the sea."}]}' | tail -c 300x-litellm-call-id: d1becc6b-b180-4fc5-bae4-f6e1d77a8ea9)curl -s "http://127.0.0.1:47120/spend/logs?request_id=d1becc6b-b180-4fc5-bae4-f6e1d77a8ea9" -H 'Authorization: Bearer sk-lit3798'/v1/responses, mid-stream drop (already a failure)
curl -sN --max-time 60 http://127.0.0.1:47120/v1/responses -H 'Authorization: Bearer sk-lit3798' -H 'content-type: application/json' -d '{"model":"gpt-5.6","max_output_tokens":2000,"stream":true,"input":"Write 300 words about the sea."}' | tail -c 300x-litellm-call-id: e76f0bde-39d6-4e7d-80aa-f794d193423b)curl -s "http://127.0.0.1:47120/spend/logs?request_id=e76f0bde-39d6-4e7d-80aa-f794d193423b" -H 'Authorization: Bearer sk-lit3798'Bedrock invoke, non-streaming success on /v1/messages (must stay a success)
curl -sN --max-time 60 http://127.0.0.1:47120/v1/messages -H 'Authorization: Bearer sk-lit3798' -H 'content-type: application/json' -d '{"model":"bedrock-claude","max_tokens":100,"messages":[{"role":"user","content":"Say hi in five words."}]}' | tail -c 300x-litellm-call-id: 60223f24-5dff-4b62-a7fd-645953fa9818)curl -s "http://127.0.0.1:47120/spend/logs?request_id=60223f24-5dff-4b62-a7fd-645953fa9818" -H 'Authorization: Bearer sk-lit3798'curl -s "http://127.0.0.1:47120/spend/logs?request_id=chatcmpl-00c456c1-cae7-44e1-aae7-f51cda861f26" -H 'Authorization: Bearer sk-lit3798'Gemini pass-through, mid-stream drop on /gemini/v1beta/models/gemini-3.8-flash:streamGenerateContent
curl -sN --max-time 60 -H x-goog-api-key: sk-lit3798 http://127.0.0.1:23449/gemini/v1beta/models/gemini-3.8-flash:streamGenerateContent?alt=sse -H 'Authorization: Bearer sk-lit3798' -H 'content-type: application/json' -d '{"contents":[{"role":"user","parts":[{"text":"Write 300 words about the sea."}]}],"generationConfig":{"maxOutputTokens":2000}}' | tail -c 300x-litellm-call-id: 0b53241b-11bc-46b1-b115-2ca136965ceb)curl -s "http://127.0.0.1:23449/spend/logs?request_id=0b53241b-11bc-46b1-b115-2ca136965ceb" -H 'Authorization: Bearer sk-lit3798'OpenAI pass-through, mid-stream drop on /openai/v1/chat/completions
curl -sN --max-time 60 http://127.0.0.1:28266/openai/v1/chat/completions -H 'Authorization: Bearer sk-lit3798' -H 'content-type: application/json' -d '{"model":"gpt-5.6","max_completion_tokens":2000,"stream":true,"messages":[{"role":"user","content":"Write 300 words about the sea."}]}' | tail -c 300x-litellm-call-id: cc277e62-3aba-4559-82b9-ce358b36d5c3)curl -s "http://127.0.0.1:28266/spend/logs?request_id=cc277e62-3aba-4559-82b9-ce358b36d5c3" -H 'Authorization: Bearer sk-lit3798'curl -s "http://127.0.0.1:28266/spend/logs?request_id=chatcmpl-EKAhKZ4Vl57fQ9Q8v7l7Bx5N2ZXSd" -H 'Authorization: Bearer sk-lit3798'Client gives up during a hang on /v1/messages (must stay a partial success: the proxy closes the upstream with the client)
curl -sN --max-time 60 --max-time 2 http://127.0.0.1:54694/v1/messages -H 'Authorization: Bearer sk-lit3798' -H 'content-type: application/json' -d '{"model":"claude-sonnet-5","max_tokens":2000,"stream":true,"messages":[{"role":"user","content":"Write 300 words about the sea."}]}' | tail -c 300x-litellm-call-id: aa5fd29d-4072-4e8f-8dc8-b886c320e359)curl -s "http://127.0.0.1:54694/spend/logs?request_id=aa5fd29d-4072-4e8f-8dc8-b886c320e359" -H 'Authorization: Bearer sk-lit3798'A key with a TPM limit, mid-stream timeout on /v1/messages (two proxy processes sharing Postgres and Redis)
KEY=$(curl -s http://127.0.0.1:47120/key/generate -H 'Authorization: Bearer sk-lit3798' -H 'content-type: application/json' -d '{"tpm_limit": 100000}' | python3 -c 'import json,sys; print(json.load(sys.stdin)["key"])')curl -s -D - http://127.0.0.1:47120/v1/chat/completions -H "Authorization: Bearer $KEY" -H 'content-type: application/json' -d '{"model":"claude-sonnet-5","max_tokens":20,"messages":[{"role":"user","content":"Say hi."}]}' | grep -iE '^x-ratelimit-.*tokens|"usage"'curl -sN --max-time 60 http://127.0.0.1:47120/v1/messages -H "Authorization: Bearer $KEY" -H 'content-type: application/json' -d '{"model":"claude-sonnet-5","max_tokens":2000,"stream":true,"messages":[{"role":"user","content":"Write 300 words about the sea."}]}' | tail -c 300curl -s "http://127.0.0.1:47120/spend/logs?request_id=f80e9275-4815-47bd-8d39-c8259a335500" -H 'Authorization: Bearer sk-lit3798'3. the same small request again, on proxy process B (http://127.0.0.1:38863)
curl -s -D - http://127.0.0.1:38863/v1/chat/completions -H "Authorization: Bearer $KEY" -H 'content-type: application/json' -d '{"model":"claude-sonnet-5","max_tokens":20,"messages":[{"role":"user","content":"Say hi."}]}' | grep -iE '^x-ratelimit-.*tokens|"usage"'request 1 itself used 28 tokens (its usage block); the dropped stream's spend row shows 14 tokens
After (6c27754)
Claude Code, mid-stream timeout on /v1/messages
env -u ANTHROPIC_API_KEY ANTHROPIC_BASE_URL=http://127.0.0.1:38435 ANTHROPIC_AUTH_TOKEN=sk-lit3798 ANTHROPIC_MODEL=claude-sonnet-5 ANTHROPIC_SMALL_FAST_MODEL=claude-sonnet-5 ANTHROPIC_DEFAULT_HAIKU_MODEL=claude-sonnet-5 ANTHROPIC_DEFAULT_SONNET_MODEL=claude-sonnet-5 claude --model claude-sonnet-5, then the promptWrite 150 words about the sea.Bedrock invoke, mid-stream timeout on /v1/messages
curl -sN --max-time 60 http://127.0.0.1:38435/v1/messages -H 'Authorization: Bearer sk-lit3798' -H 'content-type: application/json' -d '{"model":"bedrock-claude","max_tokens":2000,"stream":true,"messages":[{"role":"user","content":"Write 300 words about the sea."}]}' | tail -c 300x-litellm-call-id: 9f939ce7-2b43-4a82-8909-c90b976f9228)curl -s "http://127.0.0.1:38435/spend/logs?request_id=9f939ce7-2b43-4a82-8909-c90b976f9228" -H 'Authorization: Bearer sk-lit3798'Anthropic pass-through, mid-stream drop on /anthropic/v1/messages
curl -sN --max-time 60 -H anthropic-version: 2023-06-01 http://127.0.0.1:38435/anthropic/v1/messages -H 'Authorization: Bearer sk-lit3798' -H 'content-type: application/json' -d '{"model":"claude-sonnet-5","max_tokens":2000,"stream":true,"messages":[{"role":"user","content":"Write 300 words about the sea."}]}' | tail -c 300x-litellm-call-id: 28ea64a3-4d3b-4e22-8833-72d58f86ce7c)curl -s "http://127.0.0.1:38435/spend/logs?request_id=28ea64a3-4d3b-4e22-8833-72d58f86ce7c" -H 'Authorization: Bearer sk-lit3798'Custom pass-through endpoint, mid-stream drop on /relay-chat
curl -sN --max-time 60 http://127.0.0.1:38435/relay-chat -H 'Authorization: Bearer sk-lit3798' -H 'content-type: application/json' -d '{"model":"gpt-5.6","max_completion_tokens":2000,"stream":true,"messages":[{"role":"user","content":"Write 300 words about the sea."}]}' | tail -c 300x-litellm-call-id: 54e55f1b-3d2e-48b9-91c7-c3e98c39e413)curl -s "http://127.0.0.1:38435/spend/logs?request_id=54e55f1b-3d2e-48b9-91c7-c3e98c39e413" -H 'Authorization: Bearer sk-lit3798'Client disconnect on /v1/messages (must stay a partial success)
curl -sN --max-time 60 --max-time 2 http://127.0.0.1:38435/v1/messages -H 'Authorization: Bearer sk-lit3798' -H 'content-type: application/json' -d '{"model":"claude-sonnet-5","max_tokens":1200,"stream":true,"messages":[{"role":"user","content":"Write 300 words about the sea."}]}' | tail -c 300x-litellm-call-id: 43048e6c-3283-41d9-8725-8b347c43174d)curl -s "http://127.0.0.1:38435/spend/logs?request_id=43048e6c-3283-41d9-8725-8b347c43174d" -H 'Authorization: Bearer sk-lit3798'curl -s "http://127.0.0.1:38435/spend/logs?request_id=msg_011CeiiWqywL3GJAqfatQcYv" -H 'Authorization: Bearer sk-lit3798'Completed stream on /v1/messages (must stay a success)
curl -sN --max-time 60 http://127.0.0.1:38435/v1/messages -H 'Authorization: Bearer sk-lit3798' -H 'content-type: application/json' -d '{"model":"claude-sonnet-5","max_tokens":100,"stream":true,"messages":[{"role":"user","content":"Say hi in five words."}]}' | tail -c 300x-litellm-call-id: f48d29a1-7f27-4e36-a5b3-8db5eee58319)curl -s "http://127.0.0.1:38435/spend/logs?request_id=f48d29a1-7f27-4e36-a5b3-8db5eee58319" -H 'Authorization: Bearer sk-lit3798'curl -s "http://127.0.0.1:38435/spend/logs?request_id=msg_011CeiiY2Q31qjAtrLvrbpjB" -H 'Authorization: Bearer sk-lit3798'/v1/chat/completions, mid-stream timeout (already a failure)
curl -sN --max-time 60 http://127.0.0.1:38435/v1/chat/completions -H 'Authorization: Bearer sk-lit3798' -H 'content-type: application/json' -d '{"model":"gpt-5.6","max_completion_tokens":2000,"stream":true,"messages":[{"role":"user","content":"Write 300 words about the sea."}]}' | tail -c 300x-litellm-call-id: 8157897c-42d1-4865-b53f-29798a79f542)curl -s "http://127.0.0.1:38435/spend/logs?request_id=8157897c-42d1-4865-b53f-29798a79f542" -H 'Authorization: Bearer sk-lit3798'/v1/responses, mid-stream drop (already a failure)
curl -sN --max-time 60 http://127.0.0.1:38435/v1/responses -H 'Authorization: Bearer sk-lit3798' -H 'content-type: application/json' -d '{"model":"gpt-5.6","max_output_tokens":2000,"stream":true,"input":"Write 300 words about the sea."}' | tail -c 300x-litellm-call-id: 577bec2a-865c-4574-bb5b-62122436d768)curl -s "http://127.0.0.1:38435/spend/logs?request_id=577bec2a-865c-4574-bb5b-62122436d768" -H 'Authorization: Bearer sk-lit3798'Bedrock invoke, non-streaming success on /v1/messages (must stay a success)
curl -sN --max-time 60 http://127.0.0.1:38435/v1/messages -H 'Authorization: Bearer sk-lit3798' -H 'content-type: application/json' -d '{"model":"bedrock-claude","max_tokens":100,"messages":[{"role":"user","content":"Say hi in five words."}]}' | tail -c 300x-litellm-call-id: 6b8472e0-09de-49ea-9c69-7ece914166fb)curl -s "http://127.0.0.1:38435/spend/logs?request_id=6b8472e0-09de-49ea-9c69-7ece914166fb" -H 'Authorization: Bearer sk-lit3798'curl -s "http://127.0.0.1:38435/spend/logs?request_id=msg_bdrk_cifdot5t5osgxuntkdvz4hwzbebhghilypwjzf6hg2c5xvanawva" -H 'Authorization: Bearer sk-lit3798'Gemini pass-through, mid-stream drop on /gemini/v1beta/models/gemini-3.8-flash:streamGenerateContent
curl -sN --max-time 60 -H x-goog-api-key: sk-lit3798 http://127.0.0.1:38435/gemini/v1beta/models/gemini-3.8-flash:streamGenerateContent?alt=sse -H 'Authorization: Bearer sk-lit3798' -H 'content-type: application/json' -d '{"contents":[{"role":"user","parts":[{"text":"Write 300 words about the sea."}]}],"generationConfig":{"maxOutputTokens":2000}}' | tail -c 300x-litellm-call-id: 6d0360f0-4c79-4d9c-8406-41d4d3de8f42)curl -s "http://127.0.0.1:38435/spend/logs?request_id=6d0360f0-4c79-4d9c-8406-41d4d3de8f42" -H 'Authorization: Bearer sk-lit3798'Client gives up during a hang on /v1/messages (must stay a partial success: the proxy closes the upstream with the client)
curl -sN --max-time 60 --max-time 2 http://127.0.0.1:38435/v1/messages -H 'Authorization: Bearer sk-lit3798' -H 'content-type: application/json' -d '{"model":"claude-sonnet-5","max_tokens":2000,"stream":true,"messages":[{"role":"user","content":"Write 300 words about the sea."}]}' | tail -c 300curl -s "http://127.0.0.1:38435/spend/logs?request_id=msg_011CeiigR8yrEqUVC7U5Hh1b" -H 'Authorization: Bearer sk-lit3798'OpenAI pass-through, mid-stream drop on /openai/v1/chat/completions
curl -sN --max-time 60 http://127.0.0.1:43911/openai/v1/chat/completions -H 'Authorization: Bearer sk-lit3798' -H 'content-type: application/json' -d '{"model":"gpt-5.6","max_completion_tokens":2000,"stream":true,"messages":[{"role":"user","content":"Write 300 words about the sea."}]}' | tail -c 300x-litellm-call-id: 7cef2b6d-30f1-48d9-b14a-b2817b9fc9df)curl -s "http://127.0.0.1:43911/spend/logs?request_id=7cef2b6d-30f1-48d9-b14a-b2817b9fc9df" -H 'Authorization: Bearer sk-lit3798'A key with a TPM limit, mid-stream timeout on /v1/messages (two proxy processes sharing Postgres and Redis)
KEY=$(curl -s http://127.0.0.1:38435/key/generate -H 'Authorization: Bearer sk-lit3798' -H 'content-type: application/json' -d '{"tpm_limit": 100000}' | python3 -c 'import json,sys; print(json.load(sys.stdin)["key"])')curl -s -D - http://127.0.0.1:38435/v1/chat/completions -H "Authorization: Bearer $KEY" -H 'content-type: application/json' -d '{"model":"claude-sonnet-5","max_tokens":20,"messages":[{"role":"user","content":"Say hi."}]}' | grep -iE '^x-ratelimit-.*tokens|"usage"'curl -sN --max-time 60 http://127.0.0.1:38435/v1/messages -H "Authorization: Bearer $KEY" -H 'content-type: application/json' -d '{"model":"claude-sonnet-5","max_tokens":2000,"stream":true,"messages":[{"role":"user","content":"Write 300 words about the sea."}]}' | tail -c 300curl -s "http://127.0.0.1:38435/spend/logs?request_id=a82a3143-f5cb-418b-b5fe-2235545e7483" -H 'Authorization: Bearer sk-lit3798'3. the same small request again, on proxy process B (http://127.0.0.1:54576)
curl -s -D - http://127.0.0.1:54576/v1/chat/completions -H "Authorization: Bearer $KEY" -H 'content-type: application/json' -d '{"model":"claude-sonnet-5","max_tokens":20,"messages":[{"role":"user","content":"Say hi."}]}' | grep -iE '^x-ratelimit-.*tokens|"usage"'request 1 itself used 28 tokens (its usage block); the dropped stream's spend row shows 18 tokens
Merge-ref check:
litellm_internal_stagingmoved three times since the branch point. This branch carries the first two merges (f15bdfb, then 2f3d1ca after #39659 and #39678 landed; the only conflicts were the Anthropic pass-through logging handler's response-id keying, kept from staging next to the failure-path helpers, and an import line inlitellm_logging.py). Staging has since moved on to 2e73400, 41 commits that touch none of the files this PR changes, so the top scenarios were re-run on a throwaway merge of the tip into that head (91abf072a0, a clean merge): the Gemini pass-through drop logged a failure row with 751 completion tokens and $0.0028245 of spend, and the two-process TPM case logged the dropped/v1/messagesstream as a failure row with 31 completion tokens ($0.000344) and charged the key across both processes (remaining 99979 -> 99903), matching the After leg aboveThe last commit (6c27754) adds
_cost_partial_stream_or_zero, a private helper with a single caller. Its only contract change is that a cost lookup that raises for an unpriced model no longer escapesschedule_stream_failure_logging, which on the Anthropic pass-through path used to skip the failure dispatch entirely; the helper now logs a warning and bills the recovered usage at zero cost, the way the non-Anthropic pass-through path already didObservations from the run
/v1/responsesstreams never hitstream_timeout; pre-existing, leaves alone (LIT-6871)requested_modelonly,litellm_model_nameempty; pre-existingchatcmpl-id; pre-existing, leaves alone/v1/messagesgets a partial-success row both sides, because the proxy closes the upstream read when the client goes, so the upstream never gets to time out afterwards. The detached-stream failure hook this PR adds (a failure that arrives after the client already left) is a defensive path the disconnect curl cannot reach on this transport; it is covered by the unit tests intest_streaming_iterator.pyandtest_common_request_processing.pyType
🐛 Bug Fix
Caveats (if any)
Medium
/v1/messagesserved by an OpenAI Responses model still never times out mid-stream (LIT-6871)async_post_call_failure_hookimplementers (alerting, custom loggers, the rate limiter's reservation settlement) that saw nothing for them beforeLow
/v1/messagesprices only the first output token; pre-existing (LIT-6872)get_endpoint_typealready classifies by URL (api.anthropic.com,openai.com, the Vertex and Gemini generateContent paths); any other upstream host isGENERICand logs the failure at zero usageDependency check
What changed and who depends on it, with how each dependent was checked
PassThroughStreamingHandler.chunk_processornow schedules failure logging instead of success on an upstream exception, and_record_partial_usage_for_failurerecovers the partial usage the dropped stream already carried, picked by endpoint type through aPassThroughStreamContext/v1/messagesstreaming: verified live (Claude Code case) and unit-tested; its iterator calls the same scheduler without a stream context, so nothing changes for it beyond the shared entry point/anthropic/*: partial usage recovered from the collectedmessage_startandmessage_deltaevents; verified live, unit-tested/gemini/*and/vertex_ai/*: both classifiedVERTEX_AIby URL, so the Vertex handler rebuilds the partial response and prices it;/gemini/*verified live,/vertex_ai/*unit-tested against the same handler/openai/*: the OpenAI handler rebuilds the partial response throughstream_chunk_builder; verified live (OpenAI pass-through case)GENERIC, which carries no usage, so the failure logs at $0; verified livepass_through_requestnow wraps both SSE relays so an upstream exception runspost_call_failure_hookbefore re-raisingasync_post_call_failure_hookimplementers inlitellm/andenterprise/(spend row, alerting, limiter refunds, custom loggers) were read; each already handles transport exceptions from the model routes, and the custom logger in the rig received the call liveget_async_streaming_response_iterator) routes an upstream error to failure loggingbedrock/invoke/*: verified live;bedrock/mantle/*shares the iterator, unit-tested, not verified liveAnthropicPassthroughLoggingHandlersuccess path refactored into shared helpers plusrecord_partial_usage_for_failureLogging.record_partial_usage_for_failurestashescombined_usage_objectandresponse_cost, which the failure standard-logging payload and the spend-row lift already read_PROXY_MaxParallelRequestsHandler_v3failure hooks now settle a failed stream's reserved tokens at its recovered partial usage instead of refunding the whole reservationcombined_usage_objecton the failure path, read from the code:record_partial_usage_for_failure(this PR) carries output tokens, so the reservation settles at that usage; the pass-through and upstream-usage-header producers carry total tokens only, so their failures still refund in full as before; completed streams settle at billed usage as beforex-ratelimit-api_key-*headers and the 429 decision behind them, verified live across two proxy processes sharing one Redis (TPM case above); the v1 limiter behindLEGACY_MULTI_INSTANCE_RATE_LIMITING=trueis untouchedlitellm_router_unit_testingfailstest_no_linear_scans_in_routeron theconfig_deploymentsandheuristic_v2_router_limit_violationscans that feat(router): limit heuristic_v2 auto-routers to one without the auto_router license feature #39468 added torouter.py, a file this PR never touches; it has been red on every staging scheduled pipeline since 89058 (2026-09-03 21:09 UTC), the same test fails on a plain merge of staging 2e73400 with this tip, and it is tracked as LIT-6911.proxy_store_model_in_db_testsfailstest_missing_model_parameter_curl[chat], which expectslitellm.BadRequestErrorin the error message of a/chat/completionscall sent withoutmodeland now gets the plainInvalid model name passed in model=Nonetext; a rerun of that job at the tip (workflow 9a89f9d0) fails identically, and so has every staging scheduled pipeline since 89084 (2026-09-04 03:09 UTC, the first run after feat(caching): add semantic_cache_scope to isolate semantic cache hits per end user #39590 landed), on a path this PR does not touch (tracked as LIT-6949). The GitHub Actions matrix reds (proxy-infra / Run tests (Python 3.10)andresponses-caching-types / Run testson 3.10 and 3.11) fail the same two tests as staging's own Unit Tests run 33894712689 at 2e73400 (test_qualifiers_and_optionality_are_unwrappedandtest_event_loop_stall_timeout_burst_keeps_breaker_closed, tracked as LIT-6947); none of the matrix legs is a required check, and every one of the 33 required checks is green at the tipFinal 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
6c27754 passes /live-pr-risk