Skip to content

fix(proxy): log mid-stream /v1/messages failures as failures with partial usage - #39589

Merged
mateo-berri merged 10 commits into
litellm_internal_stagingfrom
litellm_fix_v1_messages_midstream_timeout_failure_logging
Sep 4, 2026
Merged

mateo-berri merged 10 commits into
litellm_internal_stagingfrom
litellm_fix_v1_messages_midstream_timeout_failure_logging

Conversation

@mateo-berri

@mateo-berri mateo-berri commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • A provider timeout mid-stream on /v1/messages was logged as a success
  • Failure callbacks never fired for it and the failure metrics stayed flat
  • Pass-through routes (/anthropic/*, custom pass-through) logged a dropped stream as success too
  • /v1/chat/completions already logged the same timeout as a failure

How it solves it:

  • The pass-through stream handler runs the failure handlers on an upstream exception
  • The Bedrock relay iterator does the same instead of routing to success logging
  • Pass-through routes also run the proxy failure hook, so the spend row says failure
  • The failure row keeps the usage and cost of the chunks already delivered
  • Vertex and Gemini pass-through streams keep their partial usage and cost on a drop too
  • The rate limiter settles a failed stream's reserved tokens at that partial usage instead of refunding them all
  • Client disconnects keep their partial-success billing, unchanged

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

  1. A developer runs Claude Code with ANTHROPIC_BASE_URL=https://litellm-domain and sends a prompt
  2. Claude Code sends POST https://litellm-domain/v1/messages with "stream": true and gets a 200 with the first SSE events
  3. The provider stalls mid-response; after the configured stream_timeout the stream ends with data: {"error": {"message": "Timeout on reading data from socket", ...}}, Claude Code shows the API error and retries
  4. The operator's logging callbacks (custom logger, Langfuse, Datadog, ...) receive a success event for that request with status: "success", and no failure event
  5. GET https://litellm-domain/spend/logs?request_id=<x-litellm-call-id> shows the request with status: "success"
  6. GET https://litellm-domain/metrics shows litellm_deployment_success_responses_total up by one for that request while litellm_deployment_failure_responses_total and litellm_llm_api_failed_requests_metric_total do not move

After: the same timeout is recorded as a failure everywhere the operator looks

  1. A developer runs Claude Code with ANTHROPIC_BASE_URL=https://litellm-domain and sends a prompt
  2. Claude Code sends POST https://litellm-domain/v1/messages with "stream": true and gets a 200 with the first SSE events
  3. The provider stalls mid-response; after the configured stream_timeout the stream ends with data: {"error": {"message": "Timeout on reading data from socket", ...}}, Claude Code shows the API error and retries
  4. The operator's logging callbacks receive a failure event for that request with status: "failure", the error text Timeout on reading data from socket, exception class ReadTimeout, and the usage and cost of the chunks that were delivered, and no success event
  5. GET https://litellm-domain/spend/logs?request_id=<x-litellm-call-id> shows the request with status: "failure" and the partial spend
  6. GET https://litellm-domain/metrics shows litellm_deployment_failure_responses_total{exception_class="ReadTimeout"} and litellm_llm_api_failed_requests_metric_total up by one for that request and no success counter moves

Relevant issues

Fixes #29602

Linear ticket

Resolves LIT-3798

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)

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

  • A local relay sits in front of the real Anthropic, OpenAI, Google (Gemini API), and Bedrock APIs. It forwards each streamed response for 3 chunks, then stalls for 12s and drops the connection mid-body. Non-streaming calls and streams with max_tokens < 1500 pass through untouched, so Claude Code's small helper calls succeed and only its main answer stalls
  • Every model in the config carries stream_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
  • The /anthropic/* pass-through leg addresses api.anthropic.com through 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's api_base. The /gemini/* pass-through leg sets GEMINI_API_BASE=http://127.0.0.1:37432 on the proxy and the relay forwards to generativelanguage.googleapis.com
  • Both sides run from the same config: 2 uvicorn workers (--num_workers 2), Postgres-backed, a coordination Redis shared by every proxy process so rate-limit counters live outside any one process, prometheus plus a custom logger callback that appends one JSON line per async_log_success_event, async_log_failure_event, and async_post_call_failure_hook it receives. Before boots the merge base 4990f06, After boots 6c27754; each case names the port it hit. Real provider calls, real cost
  • The rate-limit case runs across two proxy processes: process A serves the first two requests and is stopped, then process B is booted from the same tree against the same Postgres and Redis and serves the third, so the counter it reports was written by A
  • Claude Code v2.1.259 is driven interactively in a tmux pane, never claude -p
  • Case names and order are the same on both sides; the only difference is which commit the proxy was booted from

Config

model_list:
  - model_name: claude-sonnet-5
    litellm_params:
      model: anthropic/claude-sonnet-5
      api_key: os.environ/ANTHROPIC_API_KEY
      api_base: http://127.0.0.1:37432
      stream_timeout: 5
  - model_name: claude-*
    litellm_params:
      model: anthropic/claude-*
      api_key: os.environ/ANTHROPIC_API_KEY
      api_base: http://127.0.0.1:37432
      stream_timeout: 5
  - model_name: gpt-5.6
    litellm_params:
      model: openai/gpt-5.6
      api_key: os.environ/OPENAI_API_KEY
      api_base: http://127.0.0.1:37432/v1
      stream_timeout: 5
  - model_name: bedrock-claude
    litellm_params:
      model: bedrock/invoke/us.anthropic.claude-sonnet-5
      aws_region_name: us-east-1
      api_base: http://127.0.0.1:37432
      stream_timeout: 5

litellm_settings:
  callbacks: ["lit3798_callbacks.qa_logger", "prometheus"]
  num_retries: 0

router_settings:
  num_retries: 0

general_settings:
  master_key: sk-lit3798
  coordination_redis:
    host: 127.0.0.1
    port: 6379
  pass_through_endpoints:
    - path: "/relay-chat"
      target: "http://127.0.0.1:37432/v1/chat/completions"
      auth: true
      headers:
        Authorization: "Bearer os.environ/OPENAI_API_KEY"
        content-type: application/json

Before (4990f06)

Claude Code, mid-stream timeout on /v1/messages

  1. 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 prompt Write 150 words about the sea.
  2. What the pane showed:
    ⏺ Streaming response ended before any complete data was received. Retrying without streaming. If this keeps happening, check any
      proxy or gateway between Claude Code and your model provider.
    ⏺ The sea stretches beyond every horizon, restless and ancient, holding more of this planet's surface than all its continents combined. It
    ✻ Sautéed for 25s · done 1:02 PM
    
  3. Logging callback events fired during that turn:
    {"event": "async_post_call_failure_hook", "model": "claude-sonnet-5", "exception": "ReadTimeout", "call_id": "925de5d6-efb5-41cc-9293-be7433feb126"}
    {"event": "async_log_success_event", "call_type": "anthropic_messages", "model": "claude-sonnet-5", "slp_status": "success", "cost": 0.002348, "completion_tokens": 1}
    {"event": "async_post_call_failure_hook", "model": "claude-sonnet-5", "exception": "ReadTimeout", "call_id": "1af64373-2adc-4442-9fd6-6aaff361c826"}
    {"event": "async_log_success_event", "call_type": "anthropic_messages", "model": "claude-sonnet-5", "slp_status": "success", "cost": 0.13701400000000002, "completion_tokens": 2}
    {"event": "async_log_success_event", "call_type": "anthropic_messages", "model": "claude-sonnet-5", "slp_status": "success", "cost": 0.002508, "completion_tokens": 17}
    {"event": "async_log_success_event", "call_type": "anthropic_messages", "model": "claude-sonnet-5", "slp_status": "success", "cost": 0.021434, "completion_tokens": 1047}
    
  4. Prometheus counters that moved during the turn:
    litellm_deployment_success_responses_total{litellm_model_name="claude-sonnet-5"} 4.0
    litellm_deployment_total_requests_total{litellm_model_name="claude-sonnet-5"} 4.0
    litellm_proxy_failed_requests_metric_total{exception_class="ReadTimeout",exception_status="None"} 2.0
    

Bedrock invoke, mid-stream timeout on /v1/messages

  1. 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 300
    {"error":{"message":"Timeout on reading data from socket","type":"None","param":"None","code":"500"}}
    
    (x-litellm-call-id: f9742a6d-dd20-401f-844c-4cdce17af86a)
  2. Logging callback events fired:
    {"event": "async_post_call_failure_hook", "model": "bedrock-claude", "exception": "ReadTimeout", "call_id": "f9742a6d-dd20-401f-844c-4cdce17af86a"}
    
  3. Prometheus counters that moved:
    litellm_proxy_failed_requests_metric_total{exception_class="ReadTimeout",exception_status="None",requested_model="bedrock-claude"} 1.0
    
  4. curl -s "http://127.0.0.1:47120/spend/logs?request_id=f9742a6d-dd20-401f-844c-4cdce17af86a" -H 'Authorization: Bearer sk-lit3798'
    {'status': 'failure', 'model': 'bedrock-claude', 'spend': 0.0, 'prompt_tokens': 15, 'completion_tokens': 0}
    

Anthropic pass-through, mid-stream drop on /anthropic/v1/messages

  1. 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 300
    ,"text":"#"}    }
    event: content_block_delta
    data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":" The Sea\n\nThe sea has captivated humanity since the dawn of civilization, serving as both a source of sustenance and a symbol of the unknown. Covering more"}         }
    
    (x-litellm-call-id: 8a8eebbc-5408-44b3-a73a-e0f094f068e6)
  2. Logging callback events fired:
    {"event": "async_log_success_event", "call_type": "pass_through_endpoint", "model": "claude-sonnet-5", "slp_status": "success", "cost": 4.4e-05, "completion_tokens": 35, "id": "8a8eebbc-5408-44b3-a73a-e0f094f068e6"}
    
  3. Prometheus counters that moved:
    litellm_deployment_success_responses_total{litellm_model_name="claude-sonnet-5",requested_model=""} 1.0
    litellm_deployment_total_requests_total{litellm_model_name="claude-sonnet-5",requested_model=""} 1.0
    
  4. curl -s "http://127.0.0.1:47120/spend/logs?request_id=8a8eebbc-5408-44b3-a73a-e0f094f068e6" -H 'Authorization: Bearer sk-lit3798'
    {'status': 'success', 'model': 'claude-sonnet-5', 'spend': 4.4e-05, 'prompt_tokens': 17, 'completion_tokens': 35}
    

Custom pass-through endpoint, mid-stream drop on /relay-chat

  1. 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 300
    n":"v6OCebF23Yr"}
    data: {"id":"chatcmpl-EK7t50yUxUMuHPescLooCuUiWZZOJ","object":"chat.completion.chunk","created":1788465587,"model":"gpt-5.6-sol","service_tier":"default","system_fingerprint":null,"choices":[{"index":0,"delta":{"content":" sea"},"finish_reason":null}],"obfuscation":"ewzfeQS5Fh"}
    
    (x-litellm-call-id: 29ea36a1-26ff-4601-b0bb-43182290ec35)
  2. Logging callback events fired:
    {"event": "async_log_success_event", "call_type": "pass_through_endpoint", "model": "gpt-5.6", "slp_status": "success", "cost": 0.0, "completion_tokens": 0, "id": "29ea36a1-26ff-4601-b0bb-43182290ec35"}
    
  3. Prometheus counters that moved:
    litellm_deployment_success_responses_total{litellm_model_name="gpt-5.6",requested_model=""} 1.0
    litellm_deployment_total_requests_total{litellm_model_name="gpt-5.6",requested_model=""} 1.0
    
  4. curl -s "http://127.0.0.1:47120/spend/logs?request_id=29ea36a1-26ff-4601-b0bb-43182290ec35" -H 'Authorization: Bearer sk-lit3798'
    {'status': 'success', 'model': 'gpt-5.6', 'spend': 0.0, 'prompt_tokens': 0, 'completion_tokens': 0}
    

Client disconnect on /v1/messages (must stay a partial success)

  1. 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 300
    :{"type":"text_delta","text":"#"}   }
    event: content_block_delta
    data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":" The Sea\n\nThe sea has captivated humanity since the dawn of civilization, serving as both a source of sustenance and a canvas for our de"}        }
    
    (x-litellm-call-id: 70759125-9481-4ab1-a51d-8242e67171a4)
  2. Logging callback events fired:
    {"event": "async_log_success_event", "call_type": "anthropic_messages", "model": "claude-sonnet-5", "slp_status": "success", "slp_error": "Client disconnected the request", "cost": 4.4e-05, "completion_tokens": 31, "id": "70759125-9481-4ab1-a51d-8242e67171a4"}
    
  3. Prometheus counters that moved:
    litellm_deployment_success_responses_total{litellm_model_name="claude-sonnet-5",requested_model="claude-sonnet-5"} 1.0
    litellm_deployment_total_requests_total{litellm_model_name="claude-sonnet-5",requested_model="claude-sonnet-5"} 1.0
    
  4. curl -s "http://127.0.0.1:47120/spend/logs?request_id=70759125-9481-4ab1-a51d-8242e67171a4" -H 'Authorization: Bearer sk-lit3798'
    {'status': 'success', 'model': 'anthropic/claude-sonnet-5', 'spend': 4.4e-05, 'prompt_tokens': 17, 'completion_tokens': 31}
    

Completed stream on /v1/messages (must stay a success)

  1. 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 300
    ta","delta":{"stop_reason":"end_turn","stop_sequence":null,"stop_details":null},"usage":{"input_tokens":14,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"output_tokens":11,"output_tokens_details":{"thinking_tokens":0}}       }
    event: message_stop
    data: {"type":"message_stop"       }
    
    (x-litellm-call-id: 487b7626-da7a-48bc-a9e1-08d8cf82030c)
  2. Logging callback events fired:
    {"event": "async_log_success_event", "call_type": "anthropic_messages", "model": "claude-sonnet-5", "slp_status": "success", "cost": 0.000138, "completion_tokens": 11, "id": "487b7626-da7a-48bc-a9e1-08d8cf82030c"}
    
  3. Prometheus counters that moved:
    litellm_deployment_success_responses_total{litellm_model_name="claude-sonnet-5",requested_model="claude-sonnet-5"} 2.0
    litellm_deployment_total_requests_total{litellm_model_name="claude-sonnet-5",requested_model="claude-sonnet-5"} 2.0
    
  4. curl -s "http://127.0.0.1:47120/spend/logs?request_id=487b7626-da7a-48bc-a9e1-08d8cf82030c" -H 'Authorization: Bearer sk-lit3798'
    {'status': 'success', 'model': 'anthropic/claude-sonnet-5', 'spend': 0.000138, 'prompt_tokens': 14, 'completion_tokens': 11}
    

/v1/chat/completions, mid-stream timeout (already a failure)

  1. 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 300
    {"error":{"message":"litellm.Timeout: APITimeoutError - Request timed out. Error_str: Request timed out.\n\nDeployment Info: request_timeout: None\ntimeout: None. Received Model Group=gpt-5.6\nAvailable Model Group Fallbacks=None","type":null,"param":null,"code":"408"}}
    
    (x-litellm-call-id: d1becc6b-b180-4fc5-bae4-f6e1d77a8ea9)
  2. Logging callback events fired:
    {"event": "async_log_failure_event", "call_type": "acompletion", "model": "gpt-5.6", "slp_status": "failure", "slp_error": "litellm.Timeout: APITimeoutError - Request timed out. Error_str: Request timed o", "cost": 0.0, "completion_tokens": 0, "id": "d1becc6b-b180-4fc5-bae4-f6e1d77a8ea9", "exception": "Timeout"}
    {"event": "async_post_call_failure_hook", "model": "gpt-5.6", "exception": "Timeout", "call_id": "d1becc6b-b180-4fc5-bae4-f6e1d77a8ea9"}
    
  3. Prometheus counters that moved:
    litellm_deployment_failure_responses_total{exception_class="Openai.Timeout",exception_status="408",litellm_model_name="gpt-5.6",requested_model="gpt-5.6"} 1.0
    litellm_deployment_total_requests_total{litellm_model_name="gpt-5.6",requested_model="gpt-5.6"} 1.0
    litellm_llm_api_failed_requests_metric_total{model="gpt-5.6"} 1.0
    litellm_proxy_failed_requests_metric_total{exception_class="Openai.Timeout",exception_status="408",requested_model="gpt-5.6"} 1.0
    
  4. curl -s "http://127.0.0.1:47120/spend/logs?request_id=d1becc6b-b180-4fc5-bae4-f6e1d77a8ea9" -H 'Authorization: Bearer sk-lit3798'
    {'status': 'failure', 'model': 'openai/gpt-5.6', 'spend': 0.0, 'prompt_tokens': 15, 'completion_tokens': 0}
    

/v1/responses, mid-stream drop (already a failure)

  1. 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 300
    },"web_search":{"num_requests":0}},"top_logprobs":0},"sequence_number":1,"model":"gpt-5.6"}
    data: {"error": {"message": "Response payload is not completed: <TransferEncodingError: 400, message='Not enough data to satisfy transfer length header.'>", "type": "None", "param": "None", "code": "500"}}
    
    (x-litellm-call-id: e76f0bde-39d6-4e7d-80aa-f794d193423b)
  2. Logging callback events fired:
    {"event": "async_log_failure_event", "call_type": "aresponses", "model": "gpt-5.6", "slp_status": "failure", "slp_error": "Response payload is not completed: <TransferEncodingError: 400, message='Not eno", "cost": 0.0, "completion_tokens": 0, "id": "e76f0bde-39d6-4e7d-80aa-f794d193423b", "exception": "ReadError"}
    {"event": "async_post_call_failure_hook", "model": "gpt-5.6", "exception": "ReadError", "call_id": "e76f0bde-39d6-4e7d-80aa-f794d193423b"}
    
  3. Prometheus counters that moved:
    litellm_deployment_failure_responses_total{exception_class="ReadError",exception_status="None",litellm_model_name="gpt-5.6",requested_model="gpt-5.6"} 1.0
    litellm_deployment_total_requests_total{litellm_model_name="gpt-5.6",requested_model="gpt-5.6"} 1.0
    litellm_llm_api_failed_requests_metric_total{model="gpt-5.6"} 2.0
    litellm_proxy_failed_requests_metric_total{exception_class="ReadError",exception_status="None",requested_model="gpt-5.6"} 1.0
    
  4. curl -s "http://127.0.0.1:47120/spend/logs?request_id=e76f0bde-39d6-4e7d-80aa-f794d193423b" -H 'Authorization: Bearer sk-lit3798'
    {'status': 'failure', 'model': 'openai/gpt-5.6', 'spend': 0.0, 'prompt_tokens': 15, 'completion_tokens': 0}
    

Bedrock invoke, non-streaming success on /v1/messages (must stay a success)

  1. 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 300
    ,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":14,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0},"output_tokens":11,"output_tokens_details":{"thinking_tokens":0},"service_tier":"standard"}}
    
    (x-litellm-call-id: 60223f24-5dff-4b62-a7fd-645953fa9818)
  2. Logging callback events fired:
    {"event": "async_log_success_event", "call_type": "anthropic_messages", "model": "invoke/us.anthropic.claude-sonnet-5", "slp_status": "success", "cost": 0.0001518, "completion_tokens": 11, "id": "chatcmpl-00c456c1-cae7-44e1-aae7-f51cda861f26"}
    
  3. Prometheus counters that moved:
    litellm_deployment_success_responses_total{litellm_model_name="invoke/us.anthropic.claude-sonnet-5",requested_model="bedrock-claude"} 1.0
    litellm_deployment_total_requests_total{litellm_model_name="invoke/us.anthropic.claude-sonnet-5",requested_model="bedrock-claude"} 1.0
    
  4. curl -s "http://127.0.0.1:47120/spend/logs?request_id=60223f24-5dff-4b62-a7fd-645953fa9818" -H 'Authorization: Bearer sk-lit3798'
    (no spend row)
    
  5. curl -s "http://127.0.0.1:47120/spend/logs?request_id=chatcmpl-00c456c1-cae7-44e1-aae7-f51cda861f26" -H 'Authorization: Bearer sk-lit3798'
    {'status': 'success', 'model': 'bedrock/invoke/us.anthropic.claude-sonnet-5', 'spend': 0.0001518, 'prompt_tokens': 14, 'completion_tokens': 11}
    

Gemini pass-through, mid-stream drop on /gemini/v1beta/models/gemini-3.8-flash:streamGenerateContent

  1. 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 300
    index": 0}],"usageMetadata": {"promptTokenCount": 11,"candidatesTokenCount": 74,"totalTokenCount": 2005,"promptTokensDetails": [{"modality": "TEXT","tokenCount": 11}],"thoughtsTokenCount": 1920,"serviceTier": "standard"},"modelVersion": "gemini-3.8-flash","responseId": "tdyZatCmOp2c_uMPmrqKmQE"}
    
    (x-litellm-call-id: 0b53241b-11bc-46b1-b115-2ca136965ceb)
  2. Logging callback events fired:
    {"event": "async_log_success_event", "call_type": "pass_through_endpoint", "model": "gemini-3.8-flash", "slp_status": "success", "cost": 0.008234325, "completion_tokens": 1994, "id": "0b53241b-11bc-46b1-b115-2ca136965ceb"}
    
  3. Prometheus counters that moved:
    litellm_deployment_success_responses_total{litellm_model_name="gemini-3.8-flash",requested_model=""} 1.0
    litellm_deployment_total_requests_total{litellm_model_name="gemini-3.8-flash",requested_model=""} 1.0
    
  4. curl -s "http://127.0.0.1:23449/spend/logs?request_id=0b53241b-11bc-46b1-b115-2ca136965ceb" -H 'Authorization: Bearer sk-lit3798'
    {'status': 'success', 'model': 'gemini-3.8-flash', 'spend': 0.008234325, 'prompt_tokens': 11, 'completion_tokens': 1994}
    

OpenAI pass-through, mid-stream drop on /openai/v1/chat/completions

  1. 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 300
    n":"6R8CYRSoAqO"}
    data: {"id":"chatcmpl-EKAhKZ4Vl57fQ9Q8v7l7Bx5N2ZXSd","object":"chat.completion.chunk","created":1788476390,"model":"gpt-5.6-sol","service_tier":"default","system_fingerprint":null,"choices":[{"index":0,"delta":{"content":" both"},"finish_reason":null}],"obfuscation":"57A5Dx8Ah"}
    
    (x-litellm-call-id: cc277e62-3aba-4559-82b9-ce358b36d5c3)
  2. Logging callback events fired:
    {"event": "async_log_success_event", "call_type": "pass_through_endpoint", "model": "gpt-5.6", "slp_status": "success", "cost": 8e-05, "completion_tokens": 4, "id": "chatcmpl-EKAhKZ4Vl57fQ9Q8v7l7Bx5N2ZXSd"}
    
  3. Prometheus counters that moved:
    litellm_deployment_success_responses_total{litellm_model_name="gpt-5.6",requested_model=""} 1.0
    litellm_deployment_total_requests_total{litellm_model_name="gpt-5.6",requested_model=""} 1.0
    
  4. curl -s "http://127.0.0.1:28266/spend/logs?request_id=cc277e62-3aba-4559-82b9-ce358b36d5c3" -H 'Authorization: Bearer sk-lit3798'
    (no spend row)
    
  5. curl -s "http://127.0.0.1:28266/spend/logs?request_id=chatcmpl-EKAhKZ4Vl57fQ9Q8v7l7Bx5N2ZXSd" -H 'Authorization: Bearer sk-lit3798'
    {'status': 'success', 'model': 'gpt-5.6', 'spend': 8e-05, 'prompt_tokens': 0, 'completion_tokens': 4}
    

Client gives up during a hang on /v1/messages (must stay a partial success: the proxy closes the upstream with the client)

  1. 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 300
    delta","text":"#"}    }
    event: content_block_delta
    data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":" The Sea\n\nThe sea has captivated humanity since the dawn of civilization, serving as both a source of sustenance and a symbol of the unknown. Covering more"}   }
    
    (x-litellm-call-id: aa5fd29d-4072-4e8f-8dc8-b886c320e359)
  2. Logging callback events fired:
    {"event": "async_log_success_event", "call_type": "anthropic_messages", "model": "claude-sonnet-5", "slp_status": "success", "slp_error": "Client disconnected the request", "cost": 4.4e-05, "completion_tokens": 35, "id": "aa5fd29d-4072-4e8f-8dc8-b886c320e359"}
    
  3. Prometheus counters that moved:
    litellm_deployment_success_responses_total{litellm_model_name="claude-sonnet-5",requested_model="claude-sonnet-5"} 1.0
    litellm_deployment_total_requests_total{litellm_model_name="claude-sonnet-5",requested_model="claude-sonnet-5"} 1.0
    
  4. curl -s "http://127.0.0.1:54694/spend/logs?request_id=aa5fd29d-4072-4e8f-8dc8-b886c320e359" -H 'Authorization: Bearer sk-lit3798'
    {'status': 'success', 'model': 'anthropic/claude-sonnet-5', 'spend': 4.4e-05, 'prompt_tokens': 17, 'completion_tokens': 35}
    

A key with a TPM limit, mid-stream timeout on /v1/messages (two proxy processes sharing Postgres and Redis)

  1. 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"])')
    1. small request on the fresh key (a chat completion, whose response carries the key's rate-limit headers)
  2. 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"'
    x-ratelimit-limit-tokens: 12000000
    x-ratelimit-remaining-tokens: 12000000
    x-ratelimit-api_key-remaining-tokens: 99979
    x-ratelimit-api_key-limit-tokens: 100000
    "usage": {"completion_tokens": 17, "prompt_tokens": 11, "total_tokens": 28, "completion_tokens_details": {"reasoning_tokens": 0, "text_tokens": 17}, "prompt_tokens_details": {"cached_tokens": 0, "text_tokens": 11, "cache_write_tokens": 0, "cache_creation_tokens": 0, "cache_creation_token_details": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 0}}, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "inference_geo": "global", "service_tier": "standard"}
    
    1. streaming request whose upstream stalls after 3 chunks and then drops
  3. 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 300
    manity since the dawn of civilization, serving as both a source of sustenance and a symbol of the unknown. Covering more than seventy percent of our planet's surface, the "}       }
    data: {"error": {"message": "Timeout on reading data from socket", "type": "None", "param": "None", "code": "500"}}
    (curl exit 0; response header x-litellm-call-id: f80e9275-4815-47bd-8d39-c8259a335500)
    
    logging callback events fired (new lines in callbacks-before2.jsonl) ---
  4. curl -s "http://127.0.0.1:47120/spend/logs?request_id=f80e9275-4815-47bd-8d39-c8259a335500" -H 'Authorization: Bearer sk-lit3798'
    {'status': 'failure', 'model': 'claude-sonnet-5', 'spend': 0.0, 'prompt_tokens': 14, 'completion_tokens': 0}
    
    (proxy process A stopped here; process B booted from the same tree, sharing the same Postgres and Redis)
    3. the same small request again, on proxy process B (http://127.0.0.1:38863)
  5. 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"'
    x-ratelimit-limit-tokens: 12000000
    x-ratelimit-remaining-tokens: 12000000
    x-ratelimit-api_key-remaining-tokens: 99979
    x-ratelimit-api_key-limit-tokens: 100000
    "usage": {"completion_tokens": 17, "prompt_tokens": 11, "total_tokens": 28, "completion_tokens_details": {"reasoning_tokens": 0, "text_tokens": 17}, "prompt_tokens_details": {"cached_tokens": 0, "text_tokens": 11, "cache_write_tokens": 0, "cache_creation_tokens": 0, "cache_creation_token_details": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 0}}, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "inference_geo": "global", "service_tier": "standard"}
    
    remaining tokens on the key (limit 100000): reported by request 1 = 99979, reported by request 3 = 99979; between the two the key was charged 0 tokens, with request 3 itself counted at the moment it was checked
    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

  1. 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 prompt Write 150 words about the sea.
  2. What the pane showed:
    ⏺ Streaming response ended before any complete data was received. Retrying without streaming. If this keeps happening, check any
      proxy or gateway between Claude Code and your model provider.
    ⏺ The sea covers most of Earth and shapes climate, weather, and life everywhere.
    ✻ Churned for 31s · done 9:32 AM
    
  3. Logging callback events fired during that turn:
    {"event": "async_post_call_failure_hook", "model": "claude-sonnet-5", "exception": "ReadTimeout", "call_id": "2c95a3c8-ff97-43ae-bbaf-2bd3cc11a608"}
    {"event": "async_log_failure_event", "call_type": "anthropic_messages", "model": "claude-sonnet-5", "slp_status": "failure", "slp_error": "Timeout on reading data from socket", "cost": 0.13717400000000002, "completion_tokens": 1, "exception": "ReadTimeout"}
    {"event": "async_post_call_failure_hook", "model": "claude-sonnet-5", "exception": "ReadTimeout", "call_id": "5a052bc7-826b-4196-a434-0e36c35c57df"}
    {"event": "async_log_failure_event", "call_type": "anthropic_messages", "model": "claude-sonnet-5", "slp_status": "failure", "slp_error": "Timeout on reading data from socket", "cost": 0.002368, "completion_tokens": 3, "exception": "ReadTimeout"}
    {"event": "async_log_success_event", "call_type": "anthropic_messages", "model": "claude-sonnet-5", "slp_status": "success", "cost": 0.0024479999999999997, "completion_tokens": 11}
    {"event": "async_post_call_failure_hook", "model": "claude-sonnet-5", "exception": "ReadTimeout", "call_id": "9a671e04-0e6d-4cd3-a425-245d35729541"}
    {"event": "async_log_failure_event", "call_type": "anthropic_messages", "model": "claude-sonnet-5", "slp_status": "failure", "slp_error": "Timeout on reading data from socket", "cost": 0.0109968, "completion_tokens": 2, "exception": "ReadTimeout"}
    {"event": "async_post_call_failure_hook", "model": "claude-sonnet-5", "exception": "ReadTimeout", "call_id": "b603a82a-d100-4c64-bd73-16deb5875bae"}
    {"event": "async_log_failure_event", "call_type": "anthropic_messages", "model": "claude-sonnet-5", "slp_status": "failure", "slp_error": "Timeout on reading data from socket", "cost": 0.0109868, "completion_tokens": 1, "exception": "ReadTimeout"}
    {"event": "async_post_call_failure_hook", "model": "claude-sonnet-5", "exception": "ReadTimeout", "call_id": "6394afd4-a457-4a06-af7b-b893c24b6608"}
    {"event": "async_log_failure_event", "call_type": "anthropic_messages", "model": "claude-sonnet-5", "slp_status": "failure", "slp_error": "Timeout on reading data from socket", "cost": 0.0111768, "completion_tokens": 20, "exception": "ReadTimeout"}
    {"event": "async_log_success_event", "call_type": "anthropic_messages", "model": "claude-sonnet-5", "slp_status": "success", "cost": 0.0112668, "completion_tokens": 29}
    
  4. Prometheus counters that moved during the turn:
    litellm_deployment_failure_responses_total{exception_class="ReadTimeout",exception_status="None",litellm_model_name="claude-sonnet-5"} 5.0
    litellm_deployment_success_responses_total{litellm_model_name="claude-sonnet-5"} 2.0
    litellm_deployment_total_requests_total{litellm_model_name="claude-sonnet-5"} 2.0
    litellm_deployment_total_requests_total{litellm_model_name="claude-sonnet-5"} 5.0
    litellm_llm_api_failed_requests_metric_total{model="claude-sonnet-5"} 5.0
    litellm_proxy_failed_requests_metric_total{exception_class="ReadTimeout",exception_status="None"} 5.0
    

Bedrock invoke, mid-stream timeout on /v1/messages

  1. 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 300
    {"error":{"message":"Timeout on reading data from socket","type":"internal_server_error","param":null,"code":"500"}}
    
    (x-litellm-call-id: 9f939ce7-2b43-4a82-8909-c90b976f9228)
  2. Logging callback events fired:
    {"event": "async_post_call_failure_hook", "model": "bedrock-claude", "exception": "ReadTimeout", "call_id": "9f939ce7-2b43-4a82-8909-c90b976f9228"}
    {"event": "async_log_failure_event", "call_type": "anthropic_messages", "model": "invoke/us.anthropic.claude-sonnet-5", "slp_status": "failure", "slp_error": "Timeout on reading data from socket", "cost": 4.84e-05, "completion_tokens": 1, "id": "9f939ce7-2b43-4a82-8909-c90b976f9228", "exception": "ReadTimeout"}
    
  3. Prometheus counters that moved:
    litellm_deployment_failure_responses_total{exception_class="ReadTimeout",exception_status="None",litellm_model_name="invoke/us.anthropic.claude-sonnet-5",requested_model="bedrock-claude"} 1.0
    litellm_deployment_total_requests_total{litellm_model_name="invoke/us.anthropic.claude-sonnet-5",requested_model="bedrock-claude"} 1.0
    litellm_llm_api_failed_requests_metric_total{model="invoke/us.anthropic.claude-sonnet-5"} 1.0
    litellm_proxy_failed_requests_metric_total{exception_class="ReadTimeout",exception_status="None",requested_model="bedrock-claude"} 1.0
    
  4. curl -s "http://127.0.0.1:38435/spend/logs?request_id=9f939ce7-2b43-4a82-8909-c90b976f9228" -H 'Authorization: Bearer sk-lit3798'
    {'status': 'failure', 'model': 'bedrock-claude', 'spend': 4.84e-05, 'prompt_tokens': 17, 'completion_tokens': 1}
    

Anthropic pass-through, mid-stream drop on /anthropic/v1/messages

  1. 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 300
    meral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0},"output_tokens":1,"service_tier":"standard","inference_geo":"global"}}         }
    event: content_block_start
    data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}         }
    event: ping
    data: {"type": "ping"}
    
    (x-litellm-call-id: 28ea64a3-4d3b-4e22-8833-72d58f86ce7c)
  2. Logging callback events fired:
    {"event": "async_post_call_failure_hook", "model": "claude-sonnet-5", "exception": "ReadError", "call_id": "28ea64a3-4d3b-4e22-8833-72d58f86ce7c"}
    {"event": "async_log_failure_event", "call_type": "pass_through_endpoint", "model": "claude-sonnet-5", "slp_status": "failure", "slp_error": "Response payload is not completed: <TransferEncodingError: 400, message='Not eno", "cost": 4.4e-05, "completion_tokens": 1, "id": "28ea64a3-4d3b-4e22-8833-72d58f86ce7c", "exception": "ReadError"}
    
  3. Prometheus counters that moved:
    litellm_deployment_failure_responses_total{exception_class="ReadError",exception_status="None",litellm_model_name="",requested_model="claude-sonnet-5"} 1.0
    litellm_deployment_total_requests_total{litellm_model_name="",requested_model="claude-sonnet-5"} 1.0
    litellm_llm_api_failed_requests_metric_total{model="claude-sonnet-5"} 1.0
    litellm_proxy_failed_requests_metric_total{exception_class="ReadError",exception_status="None",requested_model="claude-sonnet-5"} 1.0
    
  4. curl -s "http://127.0.0.1:38435/spend/logs?request_id=28ea64a3-4d3b-4e22-8833-72d58f86ce7c" -H 'Authorization: Bearer sk-lit3798'
    {'status': 'failure', 'model': 'claude-sonnet-5', 'spend': 4.4e-05, 'prompt_tokens': 17, 'completion_tokens': 1}
    

Custom pass-through endpoint, mid-stream drop on /relay-chat

  1. 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 300
    on":"BgEyK9wKz4"}
    data: {"id":"chatcmpl-EKR4k6ZWTCkzY4w5Hq4VEwki0aunO","object":"chat.completion.chunk","created":1788539346,"model":"gpt-5.6-sol","service_tier":"default","system_fingerprint":null,"choices":[{"index":0,"delta":{"content":" always"},"finish_reason":null}],"obfuscation":"pq2oUdM"}
    
    (x-litellm-call-id: 54e55f1b-3d2e-48b9-91c7-c3e98c39e413)
  2. Logging callback events fired:
    {"event": "async_post_call_failure_hook", "model": "gpt-5.6", "exception": "ReadError", "call_id": "54e55f1b-3d2e-48b9-91c7-c3e98c39e413"}
    {"event": "async_log_failure_event", "call_type": "pass_through_endpoint", "model": "gpt-5.6", "slp_status": "failure", "slp_error": "Response payload is not completed: <TransferEncodingError: 400, message='Not eno", "cost": 0.0, "completion_tokens": 0, "id": "54e55f1b-3d2e-48b9-91c7-c3e98c39e413", "exception": "ReadError"}
    
  3. Prometheus counters that moved:
    litellm_deployment_failure_responses_total{exception_class="ReadError",exception_status="None",litellm_model_name="",requested_model="gpt-5.6"} 1.0
    litellm_deployment_total_requests_total{litellm_model_name="",requested_model="gpt-5.6"} 1.0
    litellm_llm_api_failed_requests_metric_total{model="gpt-5.6"} 1.0
    litellm_proxy_failed_requests_metric_total{exception_class="ReadError",exception_status="None",requested_model="gpt-5.6"} 1.0
    
  4. curl -s "http://127.0.0.1:38435/spend/logs?request_id=54e55f1b-3d2e-48b9-91c7-c3e98c39e413" -H 'Authorization: Bearer sk-lit3798'
    {'status': 'failure', 'model': 'gpt-5.6', 'spend': 0.0, 'prompt_tokens': 0, 'completion_tokens': 0}
    

Client disconnect on /v1/messages (must stay a partial success)

  1. 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 300
    lta","text":"#"}     }
    event: content_block_delta
    data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":" The Sea\n\nThe sea has captivated humanity since the dawn of civilization, serving as both a source of sustenance and a symbol of the unknown. Covering more"}    }
    
    (x-litellm-call-id: 43048e6c-3283-41d9-8725-8b347c43174d)
  2. Logging callback events fired:
    {"event": "async_log_success_event", "call_type": "anthropic_messages", "model": "claude-sonnet-5", "slp_status": "success", "slp_error": "Client disconnected the request", "cost": 4.4e-05, "completion_tokens": 35, "id": "msg_011CeiiWqywL3GJAqfatQcYv"}
    
  3. Prometheus counters that moved:
    litellm_deployment_success_responses_total{litellm_model_name="claude-sonnet-5",requested_model="claude-sonnet-5"} 1.0
    litellm_deployment_total_requests_total{litellm_model_name="claude-sonnet-5",requested_model="claude-sonnet-5"} 1.0
    
  4. curl -s "http://127.0.0.1:38435/spend/logs?request_id=43048e6c-3283-41d9-8725-8b347c43174d" -H 'Authorization: Bearer sk-lit3798'
    (no spend row)
    
  5. curl -s "http://127.0.0.1:38435/spend/logs?request_id=msg_011CeiiWqywL3GJAqfatQcYv" -H 'Authorization: Bearer sk-lit3798'
    {'status': 'success', 'model': 'anthropic/claude-sonnet-5', 'spend': 4.4e-05, 'prompt_tokens': 17, 'completion_tokens': 35}
    

Completed stream on /v1/messages (must stay a success)

  1. 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 300
    e_delta","delta":{"stop_reason":"end_turn","stop_sequence":null,"stop_details":null},"usage":{"input_tokens":14,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"output_tokens":11,"output_tokens_details":{"thinking_tokens":0}}}
    event: message_stop
    data: {"type":"message_stop"         }
    
    (x-litellm-call-id: f48d29a1-7f27-4e36-a5b3-8db5eee58319)
  2. Logging callback events fired:
    {"event": "async_log_success_event", "call_type": "anthropic_messages", "model": "claude-sonnet-5", "slp_status": "success", "cost": 0.000138, "completion_tokens": 11, "id": "msg_011CeiiY2Q31qjAtrLvrbpjB"}
    
  3. Prometheus counters that moved:
    litellm_deployment_success_responses_total{litellm_model_name="claude-sonnet-5",requested_model="claude-sonnet-5"} 2.0
    litellm_deployment_total_requests_total{litellm_model_name="claude-sonnet-5",requested_model="claude-sonnet-5"} 2.0
    
  4. curl -s "http://127.0.0.1:38435/spend/logs?request_id=f48d29a1-7f27-4e36-a5b3-8db5eee58319" -H 'Authorization: Bearer sk-lit3798'
    (no spend row)
    
  5. curl -s "http://127.0.0.1:38435/spend/logs?request_id=msg_011CeiiY2Q31qjAtrLvrbpjB" -H 'Authorization: Bearer sk-lit3798'
    {'status': 'success', 'model': 'anthropic/claude-sonnet-5', 'spend': 0.000138, 'prompt_tokens': 14, 'completion_tokens': 11}
    

/v1/chat/completions, mid-stream timeout (already a failure)

  1. 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 300
    {"error":{"message":"litellm.Timeout: APITimeoutError - Request timed out. Error_str: Request timed out.\n\nDeployment Info: request_timeout: None\ntimeout: None. Received Model Group=gpt-5.6\nAvailable Model Group Fallbacks=None","type":"invalid_request_error","param":null,"code":"408"}}
    
    (x-litellm-call-id: 8157897c-42d1-4865-b53f-29798a79f542)
  2. Logging callback events fired:
    {"event": "async_log_failure_event", "call_type": "acompletion", "model": "gpt-5.6", "slp_status": "failure", "slp_error": "litellm.Timeout: APITimeoutError - Request timed out. Error_str: Request timed o", "cost": 0.0, "completion_tokens": 0, "id": "8157897c-42d1-4865-b53f-29798a79f542", "exception": "Timeout"}
    {"event": "async_post_call_failure_hook", "model": "gpt-5.6", "exception": "Timeout", "call_id": "8157897c-42d1-4865-b53f-29798a79f542"}
    
  3. Prometheus counters that moved:
    litellm_deployment_failure_responses_total{exception_class="Openai.Timeout",exception_status="408",litellm_model_name="gpt-5.6",requested_model="gpt-5.6"} 1.0
    litellm_deployment_total_requests_total{litellm_model_name="gpt-5.6",requested_model="gpt-5.6"} 1.0
    litellm_llm_api_failed_requests_metric_total{model="gpt-5.6"} 1.0
    litellm_proxy_failed_requests_metric_total{exception_class="Openai.Timeout",exception_status="408",requested_model="gpt-5.6"} 1.0
    
  4. curl -s "http://127.0.0.1:38435/spend/logs?request_id=8157897c-42d1-4865-b53f-29798a79f542" -H 'Authorization: Bearer sk-lit3798'
    {'status': 'failure', 'model': 'openai/gpt-5.6', 'spend': 0.0, 'prompt_tokens': 15, 'completion_tokens': 0}
    

/v1/responses, mid-stream drop (already a failure)

  1. 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 300
    },"web_search":{"num_requests":0}},"top_logprobs":0},"sequence_number":1,"model":"gpt-5.6"}
    data: {"error": {"message": "Response payload is not completed: <TransferEncodingError: 400, message='Not enough data to satisfy transfer length header.'>", "type": "None", "param": "None", "code": "500"}}
    
    (x-litellm-call-id: 577bec2a-865c-4574-bb5b-62122436d768)
  2. Logging callback events fired:
    {"event": "async_log_failure_event", "call_type": "aresponses", "model": "gpt-5.6", "slp_status": "failure", "slp_error": "Response payload is not completed: <TransferEncodingError: 400, message='Not eno", "cost": 0.0, "completion_tokens": 0, "id": "577bec2a-865c-4574-bb5b-62122436d768", "exception": "ReadError"}
    {"event": "async_post_call_failure_hook", "model": "gpt-5.6", "exception": "ReadError", "call_id": "577bec2a-865c-4574-bb5b-62122436d768"}
    
  3. Prometheus counters that moved:
    litellm_deployment_failure_responses_total{exception_class="ReadError",exception_status="None",litellm_model_name="gpt-5.6",requested_model="gpt-5.6"} 1.0
    litellm_deployment_total_requests_total{litellm_model_name="gpt-5.6",requested_model="gpt-5.6"} 1.0
    litellm_llm_api_failed_requests_metric_total{model="gpt-5.6"} 2.0
    litellm_proxy_failed_requests_metric_total{exception_class="ReadError",exception_status="None",requested_model="gpt-5.6"} 1.0
    
  4. curl -s "http://127.0.0.1:38435/spend/logs?request_id=577bec2a-865c-4574-bb5b-62122436d768" -H 'Authorization: Bearer sk-lit3798'
    {'status': 'failure', 'model': 'openai/gpt-5.6', 'spend': 0.0, 'prompt_tokens': 15, 'completion_tokens': 0}
    

Bedrock invoke, non-streaming success on /v1/messages (must stay a success)

  1. 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 300
    ,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":14,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0},"output_tokens":20,"output_tokens_details":{"thinking_tokens":0},"service_tier":"standard"}}
    
    (x-litellm-call-id: 6b8472e0-09de-49ea-9c69-7ece914166fb)
  2. Logging callback events fired:
    {"event": "async_log_success_event", "call_type": "anthropic_messages", "model": "invoke/us.anthropic.claude-sonnet-5", "slp_status": "success", "cost": 0.00025079999999999997, "completion_tokens": 20, "id": "msg_bdrk_cifdot5t5osgxuntkdvz4hwzbebhghilypwjzf6hg2c5xvanawva"}
    
  3. Prometheus counters that moved:
    litellm_deployment_success_responses_total{litellm_model_name="invoke/us.anthropic.claude-sonnet-5",requested_model="bedrock-claude"} 1.0
    litellm_deployment_total_requests_total{litellm_model_name="invoke/us.anthropic.claude-sonnet-5",requested_model="bedrock-claude"} 1.0
    
  4. curl -s "http://127.0.0.1:38435/spend/logs?request_id=6b8472e0-09de-49ea-9c69-7ece914166fb" -H 'Authorization: Bearer sk-lit3798'
    (no spend row)
    
  5. curl -s "http://127.0.0.1:38435/spend/logs?request_id=msg_bdrk_cifdot5t5osgxuntkdvz4hwzbebhghilypwjzf6hg2c5xvanawva" -H 'Authorization: Bearer sk-lit3798'
    {'status': 'success', 'model': 'bedrock/invoke/us.anthropic.claude-sonnet-5', 'spend': 0.0002508, 'prompt_tokens': 14, 'completion_tokens': 20}
    

Gemini pass-through, mid-stream drop on /gemini/v1beta/models/gemini-3.8-flash:streamGenerateContent

  1. 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 300
    index": 0}],"usageMetadata": {"promptTokenCount": 11,"candidatesTokenCount": 79,"totalTokenCount": 1106,"promptTokensDetails": [{"modality": "TEXT","tokenCount": 11}],"thoughtsTokenCount": 1016,"serviceTier": "standard"},"modelVersion": "gemini-3.8-flash","responseId": "WPKaarCvCdXcjMcP-rvSkAc"}
    
    (x-litellm-call-id: 6d0360f0-4c79-4d9c-8406-41d4d3de8f42)
  2. Logging callback events fired:
    {"event": "async_post_call_failure_hook", "model": "", "exception": "ReadError", "call_id": "6d0360f0-4c79-4d9c-8406-41d4d3de8f42"}
    {"event": "async_log_failure_event", "call_type": "pass_through_endpoint", "model": "gemini-3.8-flash", "slp_status": "failure", "slp_error": "Response payload is not completed: <TransferEncodingError: 400, message='Not eno", "cost": 0.004114499999999999, "completion_tokens": 1095, "id": "6d0360f0-4c79-4d9c-8406-41d4d3de8f42", "exception": "ReadError"}
    
  3. Prometheus counters that moved:
    litellm_deployment_failure_responses_total{exception_class="ReadError",exception_status="None",litellm_model_name="",requested_model="other"} 1.0
    litellm_deployment_total_requests_total{litellm_model_name="",requested_model="other"} 1.0
    litellm_llm_api_failed_requests_metric_total{model="gemini-3.8-flash"} 1.0
    litellm_proxy_failed_requests_metric_total{exception_class="ReadError",exception_status="None",requested_model=""} 1.0
    
  4. curl -s "http://127.0.0.1:38435/spend/logs?request_id=6d0360f0-4c79-4d9c-8406-41d4d3de8f42" -H 'Authorization: Bearer sk-lit3798'
    {'status': 'failure', 'model': '', 'spend': 0.004114499999999999, 'prompt_tokens': 11, 'completion_tokens': 1095}
    

Client gives up during a hang on /v1/messages (must stay a partial success: the proxy closes the upstream with the client)

  1. 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 300
    (nothing)
    
  2. Logging callback events fired:
    {"event": "async_log_success_event", "call_type": "anthropic_messages", "model": "claude-sonnet-5", "slp_status": "success", "slp_error": "Client disconnected the request", "cost": 4.4e-05, "completion_tokens": 1, "id": "msg_011CeiigR8yrEqUVC7U5Hh1b"}
    
  3. Prometheus counters that moved:
    litellm_deployment_success_responses_total{litellm_model_name="claude-sonnet-5",requested_model="claude-sonnet-5"} 3.0
    litellm_deployment_total_requests_total{litellm_model_name="claude-sonnet-5",requested_model="claude-sonnet-5"} 3.0
    
  4. curl -s "http://127.0.0.1:38435/spend/logs?request_id=msg_011CeiigR8yrEqUVC7U5Hh1b" -H 'Authorization: Bearer sk-lit3798'
    {'status': 'success', 'model': 'anthropic/claude-sonnet-5', 'spend': 4.4e-05, 'prompt_tokens': 17, 'completion_tokens': 1}
    

OpenAI pass-through, mid-stream drop on /openai/v1/chat/completions

  1. 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 300
    n":"BY7T1vbsKdI"}
    data: {"id":"chatcmpl-EKRABTrQzvrwOmZqgaH4KrwzL24t8","object":"chat.completion.chunk","created":1788539683,"model":"gpt-5.6-sol","service_tier":"default","system_fingerprint":null,"choices":[{"index":0,"delta":{"content":" both"},"finish_reason":null}],"obfuscation":"3rKL3Spy3"}
    
    (x-litellm-call-id: 7cef2b6d-30f1-48d9-b14a-b2817b9fc9df)
  2. Logging callback events fired:
    {"event": "async_post_call_failure_hook", "model": "gpt-5.6", "exception": "ReadError", "call_id": "7cef2b6d-30f1-48d9-b14a-b2817b9fc9df"}
    {"event": "async_log_failure_event", "call_type": "pass_through_endpoint", "model": "gpt-5.6", "slp_status": "failure", "slp_error": "Response payload is not completed: <TransferEncodingError: 400, message='Not eno", "cost": 8e-05, "completion_tokens": 4, "id": "7cef2b6d-30f1-48d9-b14a-b2817b9fc9df", "exception": "ReadError"}
    
  3. Prometheus counters that moved:
    litellm_deployment_failure_responses_total{exception_class="ReadError",exception_status="None",litellm_model_name="",requested_model="gpt-5.6"} 1.0
    litellm_deployment_total_requests_total{litellm_model_name="",requested_model="gpt-5.6"} 1.0
    litellm_llm_api_failed_requests_metric_total{model="gpt-5.6"} 1.0
    litellm_proxy_failed_requests_metric_total{exception_class="ReadError",exception_status="None",requested_model="gpt-5.6"} 1.0
    
  4. curl -s "http://127.0.0.1:43911/spend/logs?request_id=7cef2b6d-30f1-48d9-b14a-b2817b9fc9df" -H 'Authorization: Bearer sk-lit3798'
    {'status': 'failure', 'model': 'gpt-5.6', 'spend': 8e-05, 'prompt_tokens': 0, 'completion_tokens': 4}
    

A key with a TPM limit, mid-stream timeout on /v1/messages (two proxy processes sharing Postgres and Redis)

  1. 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"])')
    1. small request on the fresh key (a chat completion, whose response carries the key's rate-limit headers)
  2. 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"'
    x-ratelimit-limit-tokens: 12000000
    x-ratelimit-remaining-tokens: 12000000
    x-ratelimit-api_key-remaining-tokens: 99979
    x-ratelimit-api_key-limit-tokens: 100000
    "usage": {"completion_tokens": 17, "prompt_tokens": 11, "total_tokens": 28, "completion_tokens_details": {"reasoning_tokens": 0, "text_tokens": 17}, "prompt_tokens_details": {"cached_tokens": 0, "text_tokens": 11, "cache_write_tokens": 0, "cache_creation_tokens": 0, "cache_creation_token_details": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 0}}, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "inference_geo": "global", "service_tier": "standard"}
    
    1. streaming request whose upstream stalls after 3 chunks and then drops
  3. 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 300
    {"error":{"message":"Timeout on reading data from socket","type":"internal_server_error","param":null,"code":"500"}}
    (curl exit 0; response header x-litellm-call-id: a82a3143-f5cb-418b-b5fe-2235545e7483)
    
    logging callback events fired (new lines in callbacks-after7.jsonl) ---
  4. curl -s "http://127.0.0.1:38435/spend/logs?request_id=a82a3143-f5cb-418b-b5fe-2235545e7483" -H 'Authorization: Bearer sk-lit3798'
    {'status': 'failure', 'model': 'claude-sonnet-5', 'spend': 4.4e-05, 'prompt_tokens': 17, 'completion_tokens': 1}
    
    (proxy process A stopped here; process B booted from the same tree, sharing the same Postgres and Redis)
    3. the same small request again, on proxy process B (http://127.0.0.1:54576)
  5. 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"'
    x-ratelimit-limit-tokens: 12000000
    x-ratelimit-remaining-tokens: 12000000
    x-ratelimit-api_key-remaining-tokens: 99933
    x-ratelimit-api_key-limit-tokens: 100000
    "usage": {"completion_tokens": 17, "prompt_tokens": 11, "total_tokens": 28, "completion_tokens_details": {"reasoning_tokens": 0, "text_tokens": 17}, "prompt_tokens_details": {"cached_tokens": 0, "text_tokens": 11, "cache_write_tokens": 0, "cache_creation_tokens": 0, "cache_creation_token_details": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 0}}, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "inference_geo": "global", "service_tier": "standard"}
    
    remaining tokens on the key (limit 100000): reported by request 1 = 99979, reported by request 3 = 99933; between the two the key was charged 46 tokens, with request 3 itself counted at the moment it was checked
    request 1 itself used 28 tokens (its usage block); the dropped stream's spend row shows 18 tokens

Merge-ref check: litellm_internal_staging moved 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 in litellm_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/messages stream as a failure row with 31 completion tokens ($0.000344) and charged the key across both processes (remaining 99979 -> 99903), matching the After leg above

The 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 escapes schedule_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 did

Observations from the run

  • Claude Code's on-screen timeout message is identical both sides; this PR leaves it alone
  • /v1/responses streams never hit stream_timeout; pre-existing, leaves alone (LIT-6871)
  • Client-disconnect partial billing prices only one output token; pre-existing, leaves alone (LIT-6872)
  • Pass-through failure counters carry requested_model only, litellm_model_name empty; pre-existing
  • Gemini pass-through failure spend rows carry an empty model; pre-existing failure-row behavior, filed as LIT-6922
  • Bedrock non-stream spend row is keyed by the chatcmpl- id; pre-existing, leaves alone
  • Custom pass-through drops log a failure at $0 since generic streams carry no usage; unchanged
  • OpenAI pass-through drops bill the chunk-builder partial usage; same cost both sides
  • A client that gives up during a hang on /v1/messages gets 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 in test_streaming_iterator.py and test_common_request_processing.py

Type

🐛 Bug Fix

Caveats (if any)

Medium

  • /v1/messages served by an OpenAI Responses model still never times out mid-stream (LIT-6871)
  • Pass-through mid-stream drops now reach async_post_call_failure_hook implementers (alerting, custom loggers, the rate limiter's reservation settlement) that saw nothing for them before

Low

  • Client-disconnect partial billing on /v1/messages prices only the first output token; pre-existing (LIT-6872)
  • Partial usage on a dropped pass-through stream is recovered only for the routes get_endpoint_type already classifies by URL (api.anthropic.com, openai.com, the Vertex and Gemini generateContent paths); any other upstream host is GENERIC and logs the failure at zero usage
  • Non-SSE pass-through responses relayed as raw bytes still log success on a partial body; pre-existing, out of scope

Dependency check

What changed and who depends on it, with how each dependent was checked

  • PassThroughStreamingHandler.chunk_processor now schedules failure logging instead of success on an upstream exception, and _record_partial_usage_for_failure recovers the partial usage the dropped stream already carried, picked by endpoint type through a PassThroughStreamContext
    • native Anthropic /v1/messages streaming: 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 collected message_start and message_delta events; verified live, unit-tested
    • /gemini/* and /vertex_ai/*: both classified VERTEX_AI by 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 through stream_chunk_builder; verified live (OpenAI pass-through case)
    • custom pass-through endpoints: classified GENERIC, which carries no usage, so the failure logs at $0; verified live
  • pass_through_request now wraps both SSE relays so an upstream exception runs post_call_failure_hook before re-raising
    • the 10 async_post_call_failure_hook implementers in litellm/ and enterprise/ (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 live
    • non-streaming pass-through and non-SSE byte relays: untouched, verified live (Bedrock non-stream case)
  • Bedrock relay iterator (get_async_streaming_response_iterator) routes an upstream error to failure logging
    • bedrock/invoke/*: verified live; bedrock/mantle/* shares the iterator, unit-tested, not verified live
  • AnthropicPassthroughLoggingHandler success path refactored into shared helpers plus record_partial_usage_for_failure
    • success logging of native and pass-through Anthropic streams: verified live (completed-stream and client-disconnect cases), unit-tested
  • Logging.record_partial_usage_for_failure stashes combined_usage_object and response_cost, which the failure standard-logging payload and the spend-row lift already read
    • verified live through the spend rows above
  • _PROXY_MaxParallelRequestsHandler_v3 failure hooks now settle a failed stream's reserved tokens at its recovered partial usage instead of refunding the whole reservation
    • producers of combined_usage_object on 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 before
    • readers: the x-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 behind LEGACY_MULTI_INSTANCE_RATE_LIMITING=true is untouched
  • CircleCI (workflow ba70ce35 at 6c27754): 40 of 42 jobs green, and both reds fail the same way on staging's own scheduled pipelines without this PR. litellm_router_unit_testing fails test_no_linear_scans_in_router on the config_deployments and heuristic_v2_router_limit_violation scans that feat(router): limit heuristic_v2 auto-routers to one without the auto_router license feature #39468 added to router.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_tests fails test_missing_model_parameter_curl[chat], which expects litellm.BadRequestError in the error message of a /chat/completions call sent without model and now gets the plain Invalid model name passed in model=None text; 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) and responses-caching-types / Run tests on 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_unwrapped and test_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 tip

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

  • 6c27754 passes /live-pr-risk

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

codspeed Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_fix_v1_messages_midstream_timeout_failure_logging (6c27754) with litellm_internal_staging (2e73400)

Open in CodSpeed

@codecov

codecov Bot commented Sep 3, 2026 •

Copy link
Copy Markdown

@mateo-berri mateo-berri added run-ci and removed run-ci labels Sep 3, 2026
@mateo-berri
mateo-berri marked this pull request as ready for review September 3, 2026 19:19
@greptile-apps

greptile-apps Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR records mid-stream provider and pass-through failures as failures while retaining usage already consumed.

  • Adds partial-usage recovery and failure dispatch for Anthropic, Bedrock, Gemini, Vertex, OpenAI, and generic pass-through stream paths.
  • Runs proxy failure hooks when streamed upstream responses fail, including detached Anthropic streams.
  • Settles rate-limit reservations using recovered partial usage and adds focused regression coverage.

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains.

Important Files Changed

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

@veria-ai

veria-ai Bot commented Sep 3, 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: 2 · PR risk: 0/10

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@mateo-berri mateo-berri added run-ci and removed run-ci labels Sep 3, 2026
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

…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
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@mateo-berri mateo-berri added run-ci and removed run-ci labels Sep 3, 2026
@mateo-berri

Copy link
Copy Markdown
Contributor 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 f15bdfb. Configure here.

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@mateo-berri mateo-berri added run-ci and removed run-ci labels Sep 4, 2026
…/litellm into litellm_fix_v1_messages_midstream_timeout_failure_logging

# Conflicts:
#	litellm/litellm_core_utils/litellm_logging.py
@mateo-berri mateo-berri added run-ci and removed run-ci labels Sep 4, 2026
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@mateo-berri

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

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.

Create PR

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

You can send follow-ups to the cloud agent here.

@mateo-berri mateo-berri added run-ci and removed run-ci labels Sep 4, 2026
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor 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 6c27754. Configure here.

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

LGTM

@mateo-berri
mateo-berri merged commit 44b1cc7 into litellm_internal_staging Sep 4, 2026
226 of 233 checks passed
@mateo-berri
mateo-berri deleted the litellm_fix_v1_messages_midstream_timeout_failure_logging branch September 4, 2026 20:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Streaming requests that time out mid-stream are logged as success (not reported as failures)

2 participants