Skip to content

fix(router): retry a /v1/messages stream the provider drops before the first content chunk - #44276

Merged
mateo-berri merged 14 commits into
mainfrom
litellm_messages_stream_retry_pre_first_chunk
Oct 5, 2026
Merged

mateo-berri merged 14 commits into
mainfrom
litellm_messages_stream_retry_pre_first_chunk

Conversation

@devin-ai-integration

@devin-ai-integration devin-ai-integration Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

How it solves it:

  • A pre-content drop is retried within the model group
  • Budget is the request's, then the deployment's, then the router's num_retries
  • Retry policies apply per error class, like a failure before the stream opened
  • Retries run before the fallback chain; num_retries: 0 turns them off
  • A raised 408, 409, 429, or 5xx before content is retried; anything else goes to fallbacks
  • Response headers name the deployment that served the stream and count the retries
  • A deployment's num_retries is also stamped pre-stream on the generic routes
  • A drop after content reached the client keeps today's behavior

Intentional product change: with retries available, message_start and content_block_start are held until the first content delta, the shape fallback-configured groups already had, and a retry policy's hold ends at the largest budget the policy names. A ping goes out live only when it arrives in its own transport chunk; Anthropic's arrives in the same read as message_start, so in practice the hold has no keepalive. The client sees the headers a moment later and loses nothing

User Flow

Before: a developer streaming through the gateway's Anthropic endpoint gets an error event after a single upstream attempt whenever the provider closes the stream before any content, even with num_retries set

  1. They send POST https://litellm-domain/v1/messages with "model": "glm-5.3", "stream": true, "max_tokens": 64 through the Anthropic Python SDK (client.messages.stream(...))
  2. The provider closes the connection before any content, so the response is HTTP 200 with event: message_start followed by event: error (api_error, "Response payload is not completed")
  3. The SDK raises APIStatusError (status 200), the upstream saw exactly one request, and the developer's app has to send the whole call again itself

After: the same request comes back complete because the gateway retried the drop before anything reached the client

  1. They send the same POST https://litellm-domain/v1/messages with "model": "glm-5.3", "stream": true, "max_tokens": 64 through the Anthropic Python SDK
  2. The provider closes the connection before any content; the gateway sends the request again (the upstream now sees two requests), up to num_retries times
  3. The response is HTTP 200 with the full lifecycle, and the SDK's final_message() carries stop_reason: end_turn and the text
  4. The response headers say x-litellm-attempted-retries: 1 and x-litellm-max-retries: 3
  5. A drop after content already streamed still ends in event: error after one attempt, since that content cannot be taken back

Decisions

  • The retry stays within the model group and routes again, like the pre-stream retry does. A one-deployment group retries the same deployment; a multi-deployment group may land on a sibling. Alternative rejected: pinning the failed deployment, which the pre-stream path does not do either
  • Budget precedence: a retry policy that names the error class, then the request's num_retries, then the deployment's litellm_params.num_retries, then the router's. Alternative rejected: reading the deployment's max_retries, which is the provider SDK's own knob and defaults to 0 under the router
  • The router default num_retries of 2 now applies to every /v1/messages stream, so lifecycle frames are held until the first content delta even for groups without fallbacks. Alternative rejected: opt-in retries, which would leave the reported setup (router_settings.num_retries: 3, no fallbacks) broken
  • A retry policy that resolves for the group counts as retries remaining for that hold up to a ceiling, the larger of the plain budget and the largest budget the policy names across error classes, since the class's own budget is only known once the error is; at that ceiling the stream is the last attempt and its frames go out live. A policy granting fewer retries than the router's or the deployment's num_retries therefore still holds its last attempt, and a drop there leaves as the mapped HTTP error (500 JSON) before any byte where the plain path answers 200 with the error in-band. Alternatives rejected: forwarding message_start live and losing the clean restart on the first policy-governed drop; an unbounded hold, under which every policy-governed exhaustion left as a 500; and resolving the class's budget from the first drop, which needs the error before the hold decision is made
  • Each retry's or fallback's stream carries its own mid-stream wrapper, and the outer one, the one the proxy reads headers off, mirrors its source's attribution as items pass through, so a fallback made after the retries ran out names the fallback deployment. Alternative rejected: one wrapper shared across hops, which would have every hop's stream reach into its parent's state
  • An error a retry attempt raises that is not retriable ends the retries and goes to the fallback chain, the way a failure before the first stream opened does; with no fallbacks configured it reaches the client unchanged. Alternative rejected: raising it straight to the client, which would skip a configured fallback the first attempt would have used
  • Mid-stream retries stamp attempted_retries and max_retries into the request metadata, so a retry's own stream dropping again continues the same count instead of starting over, and onto the response as x-litellm-attempted-retries / x-litellm-max-retries, the pre-stream retry's headers; a later fallback's headers replace them, as they do pre-stream
  • An error raised before any content, on the first attempt's stream or a retry's, is judged by the pre-stream retry rule (litellm._should_retry: 408, 409, 429, 5xx retried; anything else ends the retries and goes to the fallback chain). Alternative rejected: the SSE error-frame gate (429 and 5xx only), which left a raised 408 or 409 unretried where the pre-stream path retries it
  • A deployment's litellm_params.num_retries is stamped on a failure raised before the stream opens on every route behind the generic helper, so the mid-stream budget and the pre-stream budget of one request agree. The proxy's @client wrapper already stamps it on /v1/messages, /v1/responses, and chat (identical on both sides live), so the helper's stamp is reached only on generic routes that wrapper does not cover and on failures raised in the helper itself. Batch create, file create, moderation, assistants, vector-store file ops, and containers do not go through that helper and keep ignoring it. Alternative rejected: dropping the deployment tier from the mid-stream budget, which would ignore a documented knob on the one path that reads it
  • Values are read where the pre-stream path reads them: a request num_retries as given (so a body true counts as one retry, being an int to Python), a deployment num_retries the way the config loader leaves it (an int or a digit string, as os.environ/... substitution produces). The pre-stream reader of the deployment knob accepts only an int and falls to the router default for "1", a pre-existing gap this PR leaves to a follow-up rather than widening its scope
  • A retry attempt raising a context window or content policy error hands the fallback chain that error itself, so context_window_fallbacks and content_policy_fallbacks are consulted the way they are for a failure before the first stream opened. Alternative rejected: handing over the mid-stream envelope, which only the regular fallbacks list matched
  • An event: error frame is classed by running an AnthropicError carrying the frame's own body through the pre-stream exception mapping, so the class agrees by construction: an overloaded frame is the InternalServerError a 529 answer maps to on both sides of the first byte, and a failed fallback after one answers 500 JSON like every other litellm path (the merge base answered the frame map's 503). Alternative rejected: a class per frame status, which split one overload across InternalServerErrorRetries before the stream and ServiceUnavailableErrorRetries after it, so one request drew on two budgets
  • A model_group_retry_policy entry that does not resolve to a RetryPolicy (a non-integer budget, an entry that is not a mapping) governs nothing mid-stream: the stream runs with no policy and the plain num_retries budget, with a router warning naming the group. The hold decision resolves the policy before the first byte, so without this a malformed policy failed every healthy stream of the group with a 500 before any attempt. The pre-stream retry loop still raises the validation error when an attempt fails under that policy, as it did before this PR
  • An event: error frame nothing can take over for (its class granted no retry by the policy, no fallback configured) reaches the client exactly as the provider sent it, behind the lifecycle frames held back for a retry that never opened, the way the merge base forwarded every frame and the way the last exhausted attempt still does. Raising it instead turned a provider error frame into an HTTP error only on the first attempt, so a policy that grants a class no retry now changes nothing the client sees. Alternative rejected: a user-controlled flag keeping the pass-through map's 503 for an overloaded frame (Greptile's ask), since that status was never documented, reached a client only when a configured fallback also failed, and disagrees with the 500 the same overloaded body already gets as an HTTP answer before the stream opens
  • The request-wide litellm_settings.num_retries_per_request cap governs a mid-stream retry the way it governs a pre-stream one, through the same counter log_retry keeps, so on the one path that consults the cap (the chat bridge a non-Anthropic deployment runs through, checked in the Rust driver's prologue) a retry the cap refuses ends the request with the cap's existing answer, HTTP 500 JSON Max retries per request hit!, where the merge base, which never retried, answered 200 with the drop as an in-band error event. A cap above 1 lets the retry recover (cap 2, one drop: 200 after the retry; two drops: the 500). The native Anthropic route never consulted the cap before this PR and still does not (wrapper_async carries no check), unchanged here. Alternative rejected: forwarding the drop as an in-band error when the cap refuses a retry, which would make the same route answer two shapes for one operator setting and hand SDK clients a 200 they cannot retry

Relevant issues

Fixes #44238

Linear ticket

Resolves LIT-9180

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/unit/<your_test_file>.py -v. Leave the suites (make test-unit-*, make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or 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

Last updated: 5af838e. QA ran on 5af838e (the merge of main; the PR's own last product commit is be053be) against the merge base 9cdedf8; /live-pr-risk ran on 940e61a against e9bf2cf; its fallback, cap, and guardrail replay cells ran again on 5af838e with the same results

Setup shared by both legs. A real Databricks Foundation Model endpoint (databricks-gpt-oss-120b, since the QA workspace does not serve the reported glm model; a non-Claude model, so /v1/messages takes the same completion bridge, real $$$ on every hit) sits behind a small reverse proxy (drop_once_upstream.py, aiohttp) that, on the first request whose body carries the match string, forwards the upstream's status, headers, and first content-free SSE chunk and then closes the TCP transport mid body, exactly the way the gateway in #44238 does (TransferEncodingError: Not enough data to satisfy transfer length header); every other request passes through untouched. GET /__hits is the upstream's request counter, POST /__reset?drop=N&match=pong arms it. Each leg boots its own proxy with --num_workers 2 and no DB from its own worktree (before at the merge base, after at the PR tip), on its own random ports, from the same script, so the two legs differ only in the commit

model_list:
  - model_name: glm-5.3
    litellm_params:
      model: databricks/databricks-gpt-oss-120b
      api_base: http://127.0.0.1:<drop proxy port>/serving-endpoints
      api_key: os.environ/DATABRICKS_API_KEY
      max_retries: 1
router_settings:
  num_retries: 3
litellm_settings:
  drop_params: true
general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY

Rig sources, moved out of the body for GitHub's 65536-character limit: sdk_stream.py and drop_once_upstream.py (the Anthropic Python SDK 0.84.0 stream client with client retries off, and the fault injector in front of the real upstream that forwards the status, headers and at most one content-free SSE event, then closes the transport)

Before (9cdedf8, the merge base; proxy on :56064 with 2 uvicorn workers, drop proxy on :36328)

Case 1, Anthropic SDK stream, the provider drops before the first content chunk: one upstream request, the client gets message_start and then an error

$ curl -s -X POST 'http://127.0.0.1:36328/__reset?drop=1&match=pong'
{"hits": 0, "matched": 0, "drops": 0, "passes": 0, "drop_first_n": 1, "match": "pong"}
$ python sdk_stream.py
event: message_start
RESULT error APIStatusError status=200 message={'type': 'error', 'error': {'type': 'api_error', 'message': "litellm.MidStreamFallbackError: litellm.APIConnectionError: DatabricksException - Response payload is not completed: <TransferEncodingError: 400, message='Not enough data to satisfy transfer length header.'>"}}
elapsed 1.4s
sdk exit=1
$ curl -s http://127.0.0.1:36328/__hits
{"hits": 1, "matched": 1, "drops": 1, "passes": 0, "drop_first_n": 1, "match": "pong"}

Case 2, curl stream, same drop: message_start then an event: error frame under HTTP 200, one upstream request

$ curl -s -X POST 'http://127.0.0.1:36328/__reset?drop=1&match=pong'
{"hits": 0, "matched": 0, "drops": 0, "passes": 0, "drop_first_n": 1, "match": "pong"}
$ curl -sS -N -w '\nHTTP %{http_code}\n' http://127.0.0.1:56064/v1/messages -H 'x-api-key: $LITELLM_MASTER_KEY' -H 'anthropic-version: 2023-06-01' -H 'content-type: application/json' -d '{"model":"glm-5.3","max_tokens":64,"stream":true,"messages":[{"role":"user","content":"Reply with the single word pong."}]}'
event: message_start
data: {"type":"message_start","message":{"id":"msg_6aac98f2-dabb-407d-94a2-a4312b9b16d3","type":"message","role":"assistant","content":[],"model":"glm-5.3","stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0,"cache_creation_input_tokens":0,"cache_read_input_tokens":0}}}

event: error
data: {"type": "error", "error": {"type": "api_error", "message": "litellm.MidStreamFallbackError: litellm.APIConnectionError: DatabricksException - Response payload is not completed: <TransferEncodingError: 400, message='Not enough data to satisfy transfer length header.'>"}}


HTTP 200
$ curl -s http://127.0.0.1:36328/__hits
{"hits": 1, "matched": 1, "drops": 1, "passes": 0, "drop_first_n": 1, "match": "pong"}

Case 3, control with no drop: the stream completes on one upstream request

$ curl -s -X POST 'http://127.0.0.1:36328/__reset?drop=0'
{"hits": 0, "matched": 0, "drops": 0, "passes": 0, "drop_first_n": 0, "match": ""}
$ python sdk_stream.py
event: message_start
event: content_block_start
event: content_block_stop
event: content_block_start
event: content_block_stop
event: message_stop
RESULT ok stop_reason=end_turn text='pong' usage=40 out tokens
elapsed 1.7s
sdk exit=0
$ curl -s http://127.0.0.1:36328/__hits
{"hits": 1, "matched": 1, "drops": 0, "passes": 1, "drop_first_n": 0, "match": ""}

Case 4, the provider drops before content on every attempt: still one upstream request, so neither router_settings.num_retries: 3 nor the deployment's max_retries: 1 ever fires for a drop after the headers

$ curl -s -X POST 'http://127.0.0.1:36328/__reset?drop=10&match=pong'
{"hits": 0, "matched": 0, "drops": 0, "passes": 0, "drop_first_n": 10, "match": "pong"}
$ python sdk_stream.py
event: message_start
RESULT error APIStatusError status=200 message={'type': 'error', 'error': {'type': 'api_error', 'message': "litellm.MidStreamFallbackError: litellm.APIConnectionError: DatabricksException - Response payload is not completed: <TransferEncodingError: 400, message='Not enough data to satisfy transfer length header.'>"}}
elapsed 0.7s
sdk exit=1
$ curl -s http://127.0.0.1:36328/__hits
{"hits": 1, "matched": 1, "drops": 1, "passes": 0, "drop_first_n": 10, "match": "pong"}

After (5af838e, the PR tip; proxy on :55611 with 2 uvicorn workers, drop proxy on :48085)

Case 1, Anthropic SDK stream, the provider drops before the first content chunk: two upstream requests (the dropped one and the gateway's retry), the client gets the full lifecycle and pong in 2.5s

$ curl -s -X POST 'http://127.0.0.1:48085/__reset?drop=1&match=pong'
{"hits": 0, "matched": 0, "drops": 0, "passes": 0, "drop_first_n": 1, "match": "pong"}
$ python sdk_stream.py
event: message_start
event: content_block_start
event: content_block_stop
event: content_block_start
event: content_block_stop
event: message_stop
RESULT ok stop_reason=end_turn text='pong' usage=36 out tokens
elapsed 2.5s
sdk exit=0
$ curl -s http://127.0.0.1:48085/__hits
{"hits": 2, "matched": 2, "drops": 1, "passes": 1, "drop_first_n": 1, "match": "pong"}

Case 2, curl stream, same drop: the full lifecycle through message_stop under HTTP 200, two upstream requests (thinking deltas elided)

$ curl -s -X POST 'http://127.0.0.1:48085/__reset?drop=1&match=pong'
{"hits": 0, "matched": 0, "drops": 0, "passes": 0, "drop_first_n": 1, "match": "pong"}
$ curl -sS -N -w '\nHTTP %{http_code}\n' http://127.0.0.1:55611/v1/messages -H 'x-api-key: $LITELLM_MASTER_KEY' -H 'anthropic-version: 2023-06-01' -H 'content-type: application/json' -d '{"model":"glm-5.3","max_tokens":64,"stream":true,"messages":[{"role":"user","content":"Reply with the single word pong."}]}'
event: message_start
data: {"type":"message_start","message":{"id":"msg_1ac9c61b-689a-493d-aa01-02d426cb6893","type":"message","role":"assistant","content":[],"model":"glm-5.3","stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0,"cache_creation_input_tokens":0,"cache_read_input_tokens":0}}}

event: content_block_start
data: {"type": "content_block_start", "index": 0, "content_block": {"type": "thinking", "thinking": "User", "signature": ""}}

...

event: content_block_stop
data: {"type": "content_block_stop", "index": 0}

event: content_block_start
data: {"type": "content_block_start", "index": 1, "content_block": {"type": "text", "text": ""}}

event: content_block_delta
data: {"type": "content_block_delta", "index": 1, "delta": {"type": "text_delta", "text": "pong"}}

event: content_block_stop
data: {"type": "content_block_stop", "index": 1}

event: message_delta
data: {"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": {"input_tokens": 108, "output_tokens": 29}}

event: message_stop
data: {"type": "message_stop"}


HTTP 200
$ curl -s http://127.0.0.1:48085/__hits
{"hits": 2, "matched": 2, "drops": 1, "passes": 1, "drop_first_n": 1, "match": "pong"}

Case 3, control with no drop: the stream completes on one upstream request, nothing is retried

$ curl -s -X POST 'http://127.0.0.1:48085/__reset?drop=0'
{"hits": 0, "matched": 0, "drops": 0, "passes": 0, "drop_first_n": 0, "match": ""}
$ python sdk_stream.py
event: message_start
event: content_block_start
event: content_block_stop
event: content_block_start
event: content_block_stop
event: message_stop
RESULT ok stop_reason=end_turn text='pong' usage=25 out tokens
elapsed 1.0s
sdk exit=0
$ curl -s http://127.0.0.1:48085/__hits
{"hits": 1, "matched": 1, "drops": 0, "passes": 1, "drop_first_n": 0, "match": ""}

Case 4, the provider drops before content on every attempt: four upstream requests (the first plus router_settings.num_retries: 3, the deployment's max_retries: 1 is not the budget) over 7.1s, then the same event: error frame as before

$ curl -s -X POST 'http://127.0.0.1:48085/__reset?drop=10&match=pong'
{"hits": 0, "matched": 0, "drops": 0, "passes": 0, "drop_first_n": 10, "match": "pong"}
$ python sdk_stream.py
event: message_start
RESULT error APIStatusError status=200 message={'type': 'error', 'error': {'type': 'api_error', 'message': "litellm.MidStreamFallbackError: litellm.APIConnectionError: DatabricksException - Response payload is not completed: <TransferEncodingError: 400, message='Not enough data to satisfy transfer length header.'>"}}
elapsed 7.1s
sdk exit=1
$ curl -s http://127.0.0.1:48085/__hits
{"hits": 4, "matched": 4, "drops": 4, "passes": 0, "drop_first_n": 10, "match": "pong"}

Response headers the client sees at 5af838e (same boot; cost, timing and model name headers elided, x-litellm-model-id kept since it names the deployment that served). After a drop-once the headers name the retry (x-litellm-attempted-retries: 1, x-litellm-max-retries: 3); the control carries 0 and no max header; every attempt dropped reads 3 of 3 and the stream ends in event: error. At 9cdedf8 all three read x-litellm-attempted-retries: 0 with no max header

$ curl -s -X POST 'http://127.0.0.1:48085/__reset?drop=1&match=pong'
{"hits": 0, "matched": 0, "drops": 0, "passes": 0, "drop_first_n": 1, "match": "pong"}
$ curl -sS -N -D - http://127.0.0.1:55611/v1/messages -H "x-api-key: $LITELLM_MASTER_KEY" -H 'anthropic-version: 2023-06-01' -H 'content-type: application/json' -d '{"model":"glm-5.3","max_tokens":64,"stream":true,"messages":[{"role":"user","content":"Reply with the single word pong."}]}' | tr -d '\r' | grep -i -E '^HTTP|^x-litellm-(model|attempted|max)|^event: (message_start|message_stop|error)|text_delta|^data: {"type": "error"'
HTTP/1.1 200 OK
x-litellm-model-id: b066d84940f610f5d250ba165c36c8edc072eb844f5438381ccb015d9d008073
x-litellm-attempted-retries: 1
x-litellm-attempted-fallbacks: 0
x-litellm-max-retries: 3
event: message_start
data: {"type": "content_block_delta", "index": 1, "delta": {"type": "text_delta", "text": "pong"}}
event: message_stop
$ curl -s http://127.0.0.1:48085/__hits
{"hits": 2, "matched": 2, "drops": 1, "passes": 1, "drop_first_n": 1, "match": "pong"}
$ curl -s -X POST 'http://127.0.0.1:48085/__reset?drop=0'
{"hits": 0, "matched": 0, "drops": 0, "passes": 0, "drop_first_n": 0, "match": ""}
$ curl -sS -N -D - http://127.0.0.1:55611/v1/messages -H "x-api-key: $LITELLM_MASTER_KEY" -H 'anthropic-version: 2023-06-01' -H 'content-type: application/json' -d '{"model":"glm-5.3","max_tokens":64,"stream":true,"messages":[{"role":"user","content":"Reply with the single word pong."}]}' | tr -d '\r' | grep -i -E '^HTTP|^x-litellm-(model|attempted|max)|^event: (message_start|message_stop|error)|text_delta|^data: {"type": "error"'
HTTP/1.1 200 OK
x-litellm-model-id: b066d84940f610f5d250ba165c36c8edc072eb844f5438381ccb015d9d008073
x-litellm-attempted-retries: 0
x-litellm-attempted-fallbacks: 0
event: message_start
data: {"type": "content_block_delta", "index": 1, "delta": {"type": "text_delta", "text": "pong"}}
event: message_stop
$ curl -s http://127.0.0.1:48085/__hits
{"hits": 1, "matched": 1, "drops": 0, "passes": 1, "drop_first_n": 0, "match": ""}
$ curl -s -X POST 'http://127.0.0.1:48085/__reset?drop=10&match=pong'
{"hits": 0, "matched": 0, "drops": 0, "passes": 0, "drop_first_n": 10, "match": "pong"}
$ curl -sS -N -D - http://127.0.0.1:55611/v1/messages -H "x-api-key: $LITELLM_MASTER_KEY" -H 'anthropic-version: 2023-06-01' -H 'content-type: application/json' -d '{"model":"glm-5.3","max_tokens":64,"stream":true,"messages":[{"role":"user","content":"Reply with the single word pong."}]}' | tr -d '\r' | grep -i -E '^HTTP|^x-litellm-(model|attempted|max)|^event: (message_start|message_stop|error)|text_delta|^data: {"type": "error"'
HTTP/1.1 200 OK
x-litellm-model-id: b066d84940f610f5d250ba165c36c8edc072eb844f5438381ccb015d9d008073
x-litellm-attempted-retries: 3
x-litellm-attempted-fallbacks: 0
x-litellm-max-retries: 3
event: message_start
event: error
data: {"type": "error", "error": {"type": "api_error", "message": "litellm.MidStreamFallbackError: litellm.APIConnectionError: DatabricksException - Response payload is not completed: <TransferEncodingError: 400, message='Not enough data to satisfy transfer length header.'>"}}
$ curl -s http://127.0.0.1:48085/__hits
{"hits": 4, "matched": 4, "drops": 4, "passes": 0, "drop_first_n": 10, "match": "pong"}

Retry policy and per-deployment budgets, both legs

Three more boots per leg cover the budget rules: a retry_policy class budget governs a stream that fails before content, the budget picked on the first retry holds for the whole request across sibling deployments, and a provider event: error frame is retried under the class its body maps to. Same rig, same client, real upstreams

Retry policy boot: the router's own num_retries is 0 and only the policy grants retries. The dropped stream reaches the router as an Anthropic api_error frame, which the pre-stream mapping classes as an internal server error

model_list:
  - model_name: glm-5.3
    litellm_params:
      model: databricks/databricks-gpt-oss-120b
      api_base: http://127.0.0.1:<drop proxy port>/serving-endpoints
      api_key: os.environ/DATABRICKS_API_KEY
router_settings:
  num_retries: 0
  retry_policy:
    InternalServerErrorRetries: 2

Before (9cdedf8; proxy on :27684 with 2 uvicorn workers, drop proxy on :34845): one upstream request each time, the client gets the error and x-litellm-attempted-retries: 0

$ curl -s -X POST 'http://127.0.0.1:34845/__reset?drop=1&match=pong'
{"hits": 0, "matched": 0, "drops": 0, "passes": 0, "drop_first_n": 1, "match": "pong"}
$ python sdk_stream.py
event: message_start
RESULT error APIStatusError status=200 message={'type': 'error', 'error': {'type': 'api_error', 'message': "litellm.MidStreamFallbackError: litellm.APIConnectionError: DatabricksException - Response payload is not completed: <TransferEncodingError: 400, message='Not enough data to satisfy transfer length header.'>"}}
elapsed 0.7s
sdk exit=1
$ curl -s http://127.0.0.1:34845/__hits
{"hits": 1, "matched": 1, "drops": 1, "passes": 0, "drop_first_n": 1, "match": "pong"}
$ curl -s -X POST 'http://127.0.0.1:34845/__reset?drop=10&match=pong'
{"hits": 0, "matched": 0, "drops": 0, "passes": 0, "drop_first_n": 10, "match": "pong"}
$ curl -sS -N -D - http://127.0.0.1:27684/v1/messages -H "x-api-key: $LITELLM_MASTER_KEY" -H 'anthropic-version: 2023-06-01' -H 'content-type: application/json' -d '{"model":"glm-5.3","max_tokens":64,"stream":true,"messages":[{"role":"user","content":"Reply with the single word pong."}]}' | tr -d '\r' | grep -i -E '^HTTP|^x-litellm-(attempted-retries|max)|^event: (message_start|message_stop|error)|text_delta|^data: {"type": "error"'
HTTP/1.1 200 OK
x-litellm-attempted-retries: 0
event: message_start
event: error
data: {"type": "error", "error": {"type": "api_error", "message": "litellm.MidStreamFallbackError: litellm.APIConnectionError: DatabricksException - Response payload is not completed: <TransferEncodingError: 400, message='Not enough data to satisfy transfer length header.'>"}}
$ curl -s http://127.0.0.1:34845/__hits
{"hits": 1, "matched": 1, "drops": 1, "passes": 0, "drop_first_n": 10, "match": "pong"}

After (5af838e; proxy on :53278 with 2 uvicorn workers, drop proxy on :55465): a single drop is retried and the client gets pong on two upstream requests; with every attempt dropped the policy's 2 retries run (three upstream requests) and the headers read 2 of 2

$ curl -s -X POST 'http://127.0.0.1:55465/__reset?drop=1&match=pong'
{"hits": 0, "matched": 0, "drops": 0, "passes": 0, "drop_first_n": 1, "match": "pong"}
$ python sdk_stream.py
event: message_start
event: content_block_start
event: content_block_stop
event: content_block_start
event: content_block_stop
event: message_stop
RESULT ok stop_reason=end_turn text='pong' usage=35 out tokens
elapsed 2.6s
sdk exit=0
$ curl -s http://127.0.0.1:55465/__hits
{"hits": 2, "matched": 2, "drops": 1, "passes": 1, "drop_first_n": 1, "match": "pong"}
$ curl -s -X POST 'http://127.0.0.1:55465/__reset?drop=10&match=pong'
{"hits": 0, "matched": 0, "drops": 0, "passes": 0, "drop_first_n": 10, "match": "pong"}
$ curl -sS -N -D - http://127.0.0.1:53278/v1/messages -H "x-api-key: $LITELLM_MASTER_KEY" -H 'anthropic-version: 2023-06-01' -H 'content-type: application/json' -d '{"model":"glm-5.3","max_tokens":64,"stream":true,"messages":[{"role":"user","content":"Reply with the single word pong."}]}' | tr -d '\r' | grep -i -E '^HTTP|^x-litellm-(attempted-retries|max)|^event: (message_start|message_stop|error)|text_delta|^data: {"type": "error"'
HTTP/1.1 200 OK
x-litellm-attempted-retries: 2
x-litellm-max-retries: 2
event: message_start
event: error
data: {"type": "error", "error": {"type": "api_error", "message": "litellm.MidStreamFallbackError: litellm.APIConnectionError: DatabricksException - Response payload is not completed: <TransferEncodingError: 400, message='Not enough data to satisfy transfer length header.'>"}}
$ curl -s http://127.0.0.1:55465/__hits
{"hits": 3, "matched": 3, "drops": 3, "passes": 0, "drop_first_n": 10, "match": "pong"}

Two-deployment boot: one model group, deployment A with num_retries: 3 behind one drop proxy and deployment B with num_retries: 1 behind another, router num_retries: 0, and a policy that names only another class, so the deployment's own budget applies. Both drop proxies drop every attempt, and each run's upstream hits line is the two proxies' GET /__hits counters after the run

model_list:
  - model_name: glm-5.3
    litellm_params:
      model: databricks/databricks-gpt-oss-120b
      api_base: http://127.0.0.1:<drop proxy A port>/serving-endpoints
      api_key: os.environ/DATABRICKS_API_KEY
      num_retries: 3
  - model_name: glm-5.3
    litellm_params:
      model: databricks/databricks-gpt-oss-120b
      api_base: http://127.0.0.1:<drop proxy B port>/serving-endpoints
      api_key: os.environ/DATABRICKS_API_KEY
      num_retries: 1
router_settings:
  num_retries: 0
  retry_policy:
    RateLimitErrorRetries: 2

Before (9cdedf8; proxy on :55304 with 2 uvicorn workers, drop proxies on :34983 and :37731): six runs, one upstream request each, no retry

# run 1
$ curl -sS -N -D - http://127.0.0.1:55304/v1/messages -H "x-api-key: $LITELLM_MASTER_KEY" -H 'anthropic-version: 2023-06-01' -H 'content-type: application/json' -d '{"model":"glm-5.3","max_tokens":64,"stream":true,"messages":[{"role":"user","content":"Reply with the single word pong."}]}' | tr -d '\r' | grep -i -E '^HTTP|^x-litellm-(attempted-retries|max)|^event: (message_start|error)'
HTTP/1.1 200 OK
x-litellm-attempted-retries: 0
event: message_start
event: error
upstream hits: deployment A 0, deployment B 1, total 1
# run 2
HTTP/1.1 200 OK
x-litellm-attempted-retries: 0
event: message_start
event: error
upstream hits: deployment A 0, deployment B 1, total 1
# run 3
HTTP/1.1 200 OK
x-litellm-attempted-retries: 0
event: message_start
event: error
upstream hits: deployment A 0, deployment B 1, total 1
# run 4
HTTP/1.1 200 OK
x-litellm-attempted-retries: 0
event: message_start
event: error
upstream hits: deployment A 1, deployment B 0, total 1
# run 5
HTTP/1.1 200 OK
x-litellm-attempted-retries: 0
event: message_start
event: error
upstream hits: deployment A 1, deployment B 0, total 1
# run 6
HTTP/1.1 200 OK
x-litellm-attempted-retries: 0
event: message_start
event: error
upstream hits: deployment A 0, deployment B 1, total 1

After (5af838e; proxy on :44287 with 2 uvicorn workers, drop proxies on :36373 and :40050): six runs, and in every one the total is 1 plus the budget of the deployment that took the first attempt (x-litellm-max-retries names it), whichever sibling the later attempts land on. Run 2 started on B, so its budget of 1 held even though the retry went to A

# run 1
$ curl -sS -N -D - http://127.0.0.1:44287/v1/messages -H "x-api-key: $LITELLM_MASTER_KEY" -H 'anthropic-version: 2023-06-01' -H 'content-type: application/json' -d '{"model":"glm-5.3","max_tokens":64,"stream":true,"messages":[{"role":"user","content":"Reply with the single word pong."}]}' | tr -d '\r' | grep -i -E '^HTTP|^x-litellm-(attempted-retries|max)|^event: (message_start|error)'
HTTP/1.1 200 OK
x-litellm-attempted-retries: 3
x-litellm-max-retries: 3
event: message_start
event: error
upstream hits: deployment A 2, deployment B 2, total 4
# run 2
HTTP/1.1 200 OK
x-litellm-attempted-retries: 1
x-litellm-max-retries: 1
event: message_start
event: error
upstream hits: deployment A 1, deployment B 1, total 2
# run 3
HTTP/1.1 200 OK
x-litellm-attempted-retries: 3
x-litellm-max-retries: 3
event: message_start
event: error
upstream hits: deployment A 3, deployment B 1, total 4
# run 4
HTTP/1.1 200 OK
x-litellm-attempted-retries: 3
x-litellm-max-retries: 3
event: message_start
event: error
upstream hits: deployment A 3, deployment B 1, total 4
# run 5
HTTP/1.1 200 OK
x-litellm-attempted-retries: 3
x-litellm-max-retries: 3
event: message_start
event: error
upstream hits: deployment A 2, deployment B 2, total 4
# run 6
HTTP/1.1 200 OK
x-litellm-attempted-retries: 3
x-litellm-max-retries: 3
event: message_start
event: error
upstream hits: deployment A 2, deployment B 2, total 4

Overloaded frame boot: a real Anthropic claude-haiku-4-5 deployment, so /v1/messages takes the native pass-through route, behind a frame injector. The injector is fault injection in front of the real API: it sends every request to Anthropic (real $$$ on every hit), forwards the upstream's status, headers, and message_start, then writes an event: error frame with overloaded_error in place of the content and ends the body, the shape Anthropic sends when it overloads after the headers. POST /__reset?plan=err:overloaded_error,...&match=pong arms one planned frame per matching request. The router's num_retries is 0 and the policy grants internal server errors 2 retries, the class an overloaded body maps to before the stream opens

model_list:
  - model_name: claude-haiku-4-5
    litellm_params:
      model: anthropic/claude-haiku-4-5
      api_base: http://127.0.0.1:<frame injector port>
      api_key: os.environ/ANTHROPIC_API_KEY
router_settings:
  num_retries: 0
  retry_policy:
    InternalServerErrorRetries: 2
general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY
litellm_settings:
  drop_params: true

Before (9cdedf8; proxy on :26517 with 2 uvicorn workers, frame injector on :20127): one upstream request each time and the frame reaches the client, whatever the policy grants

$ curl -s -X POST 'http://127.0.0.1:20127/__reset?plan=err:overloaded_error&match=pong'
{"hits": 0, "matched": 0, "drops": 0, "passes": 0, "fails": 0, "errs": 0, "plan": ["err:overloaded_error"], "match": "pong"}
$ MODEL=claude-haiku-4-5 python sdk_stream.py
event: message_start
RESULT error APIStatusError status=200 message={'type': 'error', 'error': {'type': 'overloaded_error', 'message': 'rig frame overloaded_error'}}
elapsed 0.9s
sdk exit=1
$ curl -s http://127.0.0.1:20127/__hits
{"hits": 1, "matched": 1, "drops": 0, "passes": 0, "fails": 0, "errs": 1, "plan": ["err:overloaded_error"], "match": "pong"}
$ curl -s -X POST 'http://127.0.0.1:20127/__reset?plan=err:overloaded_error,err:overloaded_error,err:overloaded_error,err:overloaded_error,err:overloaded_error&match=pong'
{"hits": 0, "matched": 0, "drops": 0, "passes": 0, "fails": 0, "errs": 0, "plan": ["err:overloaded_error", "err:overloaded_error", "err:overloaded_error", "err:overloaded_error", "err:overloaded_error"], "match": "pong"}
$ curl -sS -N -D - http://127.0.0.1:26517/v1/messages -H "x-api-key: $LITELLM_MASTER_KEY" -H 'anthropic-version: 2023-06-01' -H 'content-type: application/json' -d '{"model":"claude-haiku-4-5","max_tokens":64,"stream":true,"messages":[{"role":"user","content":"Reply with the single word pong."}]}' | tr -d '\r' | grep -i -E '^HTTP|^content-type|^x-litellm-(attempted-retries|max)|^event: (message_start|message_stop|error)|text_delta|^data: {"type": "error"|^{"'
HTTP/1.1 200 OK
x-litellm-attempted-retries: 0
content-type: text/event-stream; charset=utf-8
event: message_start
event: error
data: {"type": "error", "error": {"type": "overloaded_error", "message": "rig frame overloaded_error"}}
$ curl -s http://127.0.0.1:20127/__hits
{"hits": 1, "matched": 1, "drops": 0, "passes": 0, "fails": 0, "errs": 1, "plan": ["err:overloaded_error", "err:overloaded_error", "err:overloaded_error", "err:overloaded_error", "err:overloaded_error"], "match": "pong"}
$ curl -s -X POST 'http://127.0.0.1:20127/__reset?plan=&match=pong'
{"hits": 0, "matched": 0, "drops": 0, "passes": 0, "fails": 0, "errs": 0, "plan": [], "match": "pong"}
$ MODEL=claude-haiku-4-5 python sdk_stream.py
event: message_start
event: content_block_start
event: content_block_stop
event: message_stop
RESULT ok stop_reason=end_turn text='pong' usage=5 out tokens
elapsed 0.5s
sdk exit=0
$ curl -s http://127.0.0.1:20127/__hits
{"hits": 1, "matched": 1, "drops": 0, "passes": 1, "fails": 0, "errs": 0, "plan": [], "match": "pong"}

After (5af838e; proxy on :28805 with 2 uvicorn workers, frame injector on :40271): one overloaded frame is retried and the client gets pong on two upstream requests; with a frame on every attempt the policy's 2 retries run (three upstream requests), the headers read 2 of 2, and the provider's own frame reaches the client unchanged; the control is one request

$ curl -s -X POST 'http://127.0.0.1:40271/__reset?plan=err:overloaded_error&match=pong'
{"hits": 0, "matched": 0, "drops": 0, "passes": 0, "fails": 0, "errs": 0, "plan": ["err:overloaded_error"], "match": "pong"}
$ MODEL=claude-haiku-4-5 python sdk_stream.py
event: message_start
event: content_block_start
event: content_block_stop
event: message_stop
RESULT ok stop_reason=end_turn text='pong' usage=5 out tokens
elapsed 2.1s
sdk exit=0
$ curl -s http://127.0.0.1:40271/__hits
{"hits": 2, "matched": 2, "drops": 0, "passes": 1, "fails": 0, "errs": 1, "plan": ["err:overloaded_error"], "match": "pong"}
$ curl -s -X POST 'http://127.0.0.1:40271/__reset?plan=err:overloaded_error,err:overloaded_error,err:overloaded_error,err:overloaded_error,err:overloaded_error&match=pong'
{"hits": 0, "matched": 0, "drops": 0, "passes": 0, "fails": 0, "errs": 0, "plan": ["err:overloaded_error", "err:overloaded_error", "err:overloaded_error", "err:overloaded_error", "err:overloaded_error"], "match": "pong"}
$ curl -sS -N -D - http://127.0.0.1:28805/v1/messages -H "x-api-key: $LITELLM_MASTER_KEY" -H 'anthropic-version: 2023-06-01' -H 'content-type: application/json' -d '{"model":"claude-haiku-4-5","max_tokens":64,"stream":true,"messages":[{"role":"user","content":"Reply with the single word pong."}]}' | tr -d '\r' | grep -i -E '^HTTP|^content-type|^x-litellm-(attempted-retries|max)|^event: (message_start|message_stop|error)|text_delta|^data: {"type": "error"|^{"'
HTTP/1.1 200 OK
x-litellm-attempted-retries: 2
x-litellm-max-retries: 2
content-type: text/event-stream; charset=utf-8
event: message_start
event: error
data: {"type": "error", "error": {"type": "overloaded_error", "message": "rig frame overloaded_error"}}
$ curl -s http://127.0.0.1:40271/__hits
{"hits": 3, "matched": 3, "drops": 0, "passes": 0, "fails": 0, "errs": 3, "plan": ["err:overloaded_error", "err:overloaded_error", "err:overloaded_error", "err:overloaded_error", "err:overloaded_error"], "match": "pong"}
$ curl -s -X POST 'http://127.0.0.1:40271/__reset?plan=&match=pong'
{"hits": 0, "matched": 0, "drops": 0, "passes": 0, "fails": 0, "errs": 0, "plan": [], "match": "pong"}
$ MODEL=claude-haiku-4-5 python sdk_stream.py
event: message_start
event: content_block_start
event: content_block_stop
event: message_stop
RESULT ok stop_reason=end_turn text='pong' usage=5 out tokens
elapsed 0.5s
sdk exit=0
$ curl -s http://127.0.0.1:40271/__hits
{"hits": 1, "matched": 1, "drops": 0, "passes": 1, "fails": 0, "errs": 0, "plan": [], "match": "pong"}

Claude Code, both legs

Claude Code retries a dropped stream on its own, so its pane reads pong at both commits and this case is an observation, not the verdict; the SDK and curl cases above, with client retries off, carry it. Same drop as case 1 (drop=1&match=pong,tools), Claude Code 2.1.289 in tmux pointed at each leg's proxy (ANTHROPIC_BASE_URL=http://127.0.0.1:<proxy port> ANTHROPIC_AUTH_TOKEN=$LITELLM_MASTER_KEY ANTHROPIC_MODEL=glm-5.3 ANTHROPIC_SMALL_FAST_MODEL=glm-5.3 CLAUDE_CODE_MAX_OUTPUT_TOKENS=8192 claude), then the prompt Reply with the single word pong.

Before (9cdedf8): the gateway answers event: error, Claude Code sends the request again and shows pong; upstream saw 3 requests (the dropped one, Claude Code's own second attempt, and one unmatched request Claude Code sends in parallel)

 ▐▛███▛█   Claude Code v2.1.289
▝▜██████▀  glm-5.3 · API Usage Billing
 ▝▝   ▝▝   /private/tmp/claude-501/-Users-mateo-Development-litellm/3fd1a73a-f3b7-473f-b234-b113777029c5/scratchpad/pr44276/qa/cc_bef
▎ Auto mode is now Claude Code's default permission mode.
▎ Auto mode lets Claude handle permission prompts automatically. Claude checks each tool call for risky actions and prompt injection before executing, runs the ones it assesses as lower-risk, and blocks the rest.
▎ https://code.claude.com/docs/en/permission-modes
❯ Reply with the single word pong.
  Thought for 9s
⏺ pong
✻ Worked for 9s · done 2:02 PM
❯
  ⏵⏵ auto mode on (shift+tab to cycle) · ← for agents

$ curl -s http://127.0.0.1:36328/__hits
{"hits": 3, "matched": 2, "drops": 1, "passes": 2, "drop_first_n": 1, "match": "pong,tools"}

Claude Code before

After (5af838e): the gateway's retry answers Claude Code's first request and the pane shows pong; upstream saw 3 requests (the dropped one, the gateway's retry, and the same parallel unmatched request)

 ▐▛███▛█   Claude Code v2.1.289
▝▜██████▀  glm-5.3 · API Usage Billing
 ▝▝   ▝▝   /private/tmp/claude-501/-Users-mateo-Development-litellm/3fd1a73a-f3b7-473f-b234-b113777029c5/scratchpad/pr44276/qa/cc_aft
▎ Auto mode is now Claude Code's default permission mode.
▎ Auto mode lets Claude handle permission prompts automatically. Claude checks each tool call for risky actions and prompt injection before executing, runs the ones it assesses as lower-risk, and blocks the rest.
▎ https://code.claude.com/docs/en/permission-modes
❯ Reply with the single word pong.
  Thought for 9s
⏺ pong
✻ Cooked for 9s · done 2:03 PM
❯
  ⏵⏵ auto mode on (shift+tab to cycle) · ← for agents

$ curl -s http://127.0.0.1:48085/__hits
{"hits": 3, "matched": 2, "drops": 1, "passes": 2, "drop_first_n": 1, "match": "pong,tools"}

Claude Code after

Observations from the legs (what the PR causes, worsens, or leaves alone)

  • Claude Code retries a dropped stream itself (leaves alone)
  • Claude Code sends one unmatched parallel request (leaves alone)
  • Exhausted retries still end in event: error on HTTP 200 (leaves alone)
  • Retried SDK reply took 2.5s against 1.0s undropped (causes)
  • A retry policy class budget now retries dropped streams (causes)
  • First deployment's budget holds across sibling deployments (causes)
  • Deployment max_retries: 1 ignored, router num_retries: 3 wins (causes)
  • Overloaded frame retried under the internal server error budget (causes)
  • Exhausted overloaded frame reaches the client unchanged (leaves alone)

Two branches are not scripted in these legs: an error class the policy grants zero retries (the frame then passes through as the provider sent it, which the live risk rig drives on both commits) and the 408 gate on a raised pre-stream error (a unit test covers it)

/audit, checked-in integration cells on both legs

/audit round 1 of 3 rerun at the merged tip 5af838e: 68 checked-in cells, 0 FAIL; merge base 9cdedf8 (run1) against head 5af838e (run1 and run2, identical sets, as at 66d01a7)

Selection: every test in the five files below (a parametrized test is listed once with its ids in brackets, one cell per id), run as uv run --no-sync python tests/integration/run.py providers <node ids> --seed 4106601 --order-seed 0 on both legs. Head run1 and run2 collected and passed the same 68 cells with no skip, retry or sleep (435.723 s and 424.507 s); the merge base run1 passed 31 and failed 37 (387.02 s). Rig: a licensed proxy with 2 uvicorn workers, real Postgres and Redis, the scripted upstream from tests/integration/_support, LITELLM_LOCAL_MODEL_COST_MAP=True, router num_retries seeded 0 over /config/update; the base leg is the 9cdedf8 tree in its own venv. Each cell asserts what the caller received, what the upstream received (by id and attempt) and the spend row where it names one. A cell red on the base failed the way its inventory row expected (one upstream attempt and then the error, or the base's own status); a cell green on the base is a control whose behavior is unchanged: the pre-stream @client wrapper already stamps the deployment budget on an exception it raises, and a non-retriable, opted-out or after-content case is retried on neither side. The chaos file kills one of the two workers mid burst and fails every first attempt of a 36-call burst

tests/integration/messages_endpoint/chat_bridge/test_chat_bridge_pre_content_retry_wire.py (12 cells; base 8 red and 4 green; head green twice)

  • red on the base: test_anthropic_sdk_async_stream_over_the_bridge_completes_after_a_drop[chat, responses], test_bridge_stream_failing_before_content_is_retried_per_the_deployment_budget[drop_after_headers-chat, drop_after_headers-responses, drop_after_pre_content_frame-chat, drop_after_pre_content_frame-responses], test_bridge_stream_failing_before_content_is_retried_per_the_request_budget[chat, responses]
  • green on both (control): test_bridge_stream_dropping_after_content_is_not_retried[chat, responses], test_bridge_stream_failing_before_content_is_retried_per_the_deployment_budget[http_500-chat, http_500-responses]

tests/integration/messages_endpoint/providers/anthropic/test_anthropic_messages_pre_content_retry_chaos.py (2 cells; base 1 red and 1 green; head green twice)

  • red on the base: test_worker_sigkill_mid_burst_leaves_the_sibling_retrying_pre_content_failures
  • green on both (control): test_outage_on_every_first_attempt_is_absorbed_by_the_deployment_budget

tests/integration/messages_endpoint/providers/anthropic/test_anthropic_messages_pre_content_retry_wire.py (35 cells; base 19 red and 16 green; head green twice)

  • red on the base: test_always_dropping_upstream_is_attempted_once_per_budget_unit_plus_the_first_call, test_anthropic_sdk_async_stream_completes_after_a_drop_following_message_start, test_anthropic_sdk_sync_stream_completes_after_a_drop_following_message_start, test_anthropic_sdk_sync_stream_completes_after_an_overloaded_error_frame, test_retried_stream_is_cached_and_the_identical_request_is_served_without_the_upstream, test_retried_stream_response_headers_name_the_attempt, test_retried_stream_spend_row_records_the_attempt_count, test_retry_rejected_before_it_opens_counts_against_the_same_budget, test_stream_failing_before_content_is_retried_on_the_same_group_and_completes[drop_after_headers-500-deployment, drop_after_headers-500-request, drop_after_message_start-500-deployment, drop_after_message_start-500-request, error_frame-429-deployment, error_frame-429-request, error_frame-529-deployment, error_frame-529-request, error_frame_after_message_start-500-deployment, error_frame_after_message_start-500-request], test_two_drops_stamp_two_attempted_retries_on_the_response
  • green on both (control): test_anthropic_sdk_async_stream_completes_after_a_529_before_the_stream_opens, test_non_stream_messages_rejected_with_500_is_retried_per_the_deployment_budget, test_request_num_retries_zero_turns_the_retry_off_for_a_deployment_with_a_budget, test_stream_dropping_after_content_is_not_retried, test_stream_invalid_request_error_frame_is_not_retried, test_stream_rejected_before_it_opens_is_retried_and_completes[408-deployment, 408-request, 409-deployment, 409-request, 429-deployment, 429-request, 500-deployment, 500-request, 529-deployment, 529-request], test_stream_rejected_with_401_before_it_opens_is_not_retried

tests/integration/routing/test_deployment_num_retries_generic_routes_wire.py (9 cells; base 1 red and 8 green; head green twice)

  • red on the base: test_fine_tuning_jobs_list_rejected_is_retried_per_the_deployment_budget
  • green on both (control): test_chat_completions_control_keeps_retrying_per_the_deployment_budget[non_stream, stream], test_gemini_generate_content_rejected_is_retried_per_the_deployment_budget, test_responses_rejected_before_the_stream_opens_is_retried_per_the_deployment_budget[non_stream, stream], test_responses_request_budget_still_wins_over_a_zero_deployment_budget, test_vllm_passthrough_rejected_before_it_opens_is_retried_per_the_deployment_budget[non_stream, stream]

tests/integration/routing/test_messages_stream_retry_budget_sources_owned_proxy.py (10 cells; base 8 red and 2 green; head green twice)

  • red on the base: test_a_digit_string_deployment_budget_is_honored_as_a_number, test_a_retry_policy_default_retries_sets_the_budget_for_a_pre_content_drop, test_a_retry_raising_a_context_window_error_reaches_the_context_window_fallback, test_a_retry_rejected_with_401_ends_the_retries_and_reaches_the_client_unchanged, test_fallbacks_run_only_after_the_same_group_budget_is_spent, test_lifecycle_frames_are_held_until_content_while_pings_go_out_live, test_overloaded_frames_whose_fallback_fails_answer_the_mapped_internal_server_error, test_router_num_retries_governs_a_group_without_its_own_budget
  • green on both (control): test_request_num_retries_zero_turns_a_retry_policy_off, test_request_num_retries_zero_turns_the_router_budget_off

Type

🐛 Bug Fix

Caveats (if any)

Backward incompatible, per /live-pr-risk (ran at 940e61a against e9bf2cf, top cells again at 5af838e against 9cdedf8)

  • Medium, decided here: the request-wide litellm_settings.num_retries_per_request cap now reaches a /v1/messages stream that a non-Anthropic deployment drops before content
    • with the cap at 1 the merge base answered 200 plus an in-band event: error after one upstream hit (it never retried); this PR answers HTTP 500 JSON litellm.APIConnectionError: Max retries per request hit! after the same one hit
    • that is the cap's existing answer on the same route before the stream opens (a pre-stream 503 under the cap answers the same 500 on both sides, on /v1/messages and /v1/chat/completions), since the check in the Rust driver's prologue refuses a retry once the request's counter reaches the cap, so a cap of N allows N - 1 retries (pre-existing)
    • with the cap at 2 one drop recovers (200 after the retry, x-litellm-attempted-retries: 1) and two drops answer the 500
    • only the chat bridge consults the cap; the native Anthropic route never did and still does not (wrapper_async carries no check), and the responses bridge was not driven
    • with a fallback configured the refused retry goes to the fallback, 200 after 1 + 1 upstream hits on both sides
    • workaround: a cap above the retries the stream needs, or no cap; reasoning in Decisions; ships with the approving review
  • Low, decided here: an overloaded frame whose configured fallback then fails answers HTTP 500 instead of the merge base's 503
    • the frame is classed through the pre-stream mapping (InternalServerError, as a 529 answer is), so a retry policy's InternalServerErrorRetries governs it on both sides of the first byte
    • measured (d10): base 503 JSON after 1 primary hit and 3 fallback hits, this PR 500 JSON after 3 primary hits and 3 fallback hits; the message prefix and the logged class change with it
    • Greptile raised and withdrew this; reasoning in Decisions; ships with the approving review
  • Backward incompatible, decided here: a policy-governed stream that keeps dropping can answer HTTP 500 JSON
    • applies when the policy's grant is below the larger of the plain budget and the policy's largest per-class budget
    • the merge base answered 200 plus an in-band event: error after one attempt
    • measured (c06, DefaultRetries: 1 under router num_retries: 2): 500 after 2 hits with x-litellm-attempted-retries: 1, x-litellm-max-retries: 1
    • with the policy's grant at that ceiling (body num_retries: 1) the last attempt is live and the shape is 200 plus the error event
    • bounded in a626f52, reasoning in Decisions; ships with the approving review
  • Backward incompatible, decided here: retries change timing and counts on a dropping group
    • retries run before the fallback chain, so a fallback-configured group whose primary drops answers later by num_retries attempts
    • lifecycle frames and the HTTP status line wait for the first content delta while a retry or fallback remains
    • a group that keeps dropping or keeps sending retriable frames is tried 1 + num_retries times, and an in-band ending still writes no spend or failure row
    • a body num_retries: true counts as one retry
    • a deployment num_retries: "1" counts mid-stream and not pre-stream (pre-existing on the pre-stream side, follow-up ticketed)
    • reasoning in Decisions; ships with the approving review
  • Fixed in a626f52: a fallback after exhausted retries named the primary deployment, and x-litellm-attempted-retries read 0 after a mid-stream retry
    • the outer stream wrapper now follows its source's attribution, and the retry stamps the pre-stream retry's headers (observed again at 940e61a, c01, c09, c27, c28)
  • Parity with the merge base, changed since 69e7182: an event: error frame nothing can take over for reaches the client as the provider sent it
    • a class the policy grants no retry with no fallback configured, and the last exhausted attempt, answer 200 with the frame verbatim on both sides (e01, d10)
    • 69e7182 answered mapped JSON errors there; be053be restored the pass-through

Medium

  • Every /v1/messages stream with retries left holds message_start until the first content delta
    • the router default num_retries is 2, so this is on unless num_retries: 0 is set
    • the hold ends at the first delta (thinking and tool-input deltas count) or after 200 held frames
    • the HTTP status line and headers wait with the frames, since the proxy sends them with the first forwarded chunk
    • a ping is forwarded live only when it arrives in its own transport chunk, and then it carries the headers out while the lifecycle frames stay held
    • in practice the hold has no keepalive: Anthropic's ping arrived in the same read as message_start and content_block_start on the rig, so it was held with them (first bytes at 7977 ms with the hold against 1362 ms without, on a 7 s first token)
    • the completion bridge for OpenAI-compatible deployments sends no pings at all
  • Retries run before the fallback chain, so a fallback answers later
    • a group with fallbacks whose primary drops spends num_retries attempts on the group first
    • first text at 3.28 s against 1.16 s before, on the rig's drop-every-stream deployment
  • Prometheus counts every upstream attempt on the chat bridge
    • six legs on each side (g01): litellm_deployment_total_requests_total for the dropping Databricks deployment 2.0 on the merge base and 5.0 here, litellm_llm_api_failed_requests_metric_total 2.0 and 4.0, so a failed-requests alert sees up to 1 + num_retries failures per request on that route
    • the recovered request appears as a 200 in litellm_proxy_total_requests_metric_total where the merge base had no entry (both its legs failed in-band)
    • the native Anthropic route's series are identical on both sides across the same legs; retried frame attempts do not register there on either side

Low

  • A stream dropped on every attempt whose fallback also fails answers the same HTTP 500 with a longer message
    • the text reads litellm.InternalServerError: AnthropicException - {...} around the merge base's MidStreamFallbackError line; status and error.type are unchanged
  • A frame type the status map does not know, and request_too_large, is classed 500 and retried up to the budget before passing through verbatim
    • parse_anthropic_error_event defaults an undocumented type to 500 (pre-existing map, not touched here); the merge base forwarded such frames after one attempt (d03: weird_new_error, request_too_large 3 hits here against 1)
  • A deployment that keeps sending retriable frames is not cooled down
    • litellm_deployment_state stays 0.0 for it after overloaded frames on both sides; only raised failures feed the cooldown
  • A dropped retry attempt's message_start usage is billed on a failure row
    • a native stream dropped 1 + num_retries times writes one failure row per attempt (cost 2e-05 each on the rig) where the merge base wrote one row for its single attempt
  • A model_group_retry_policy entry that does not resolve to a RetryPolicy governs nothing mid-stream, with a router warning
    • the pre-stream retry loop still raises the validation error when an attempt fails under it, as before this PR (e02)
  • The native Anthropic route ignores num_retries_per_request before and after this PR
    • wrapper_async carries no check; a pre-stream 503 under a cap of 1 still retries there on both sides (h01)
  • The Max retries per request hit! body on the /v1/messages chat bridge before the stream opens carries a Python traceback in error.message
    • pre-existing on both sides (h01); /v1/chat/completions returns the bare message; follow-up to file
  • A pre-stream 503 with body num_retries: 20 stops after about 8 upstream hits on both sides
    • the deployment cools down before the budget is spent (e03), pre-existing
  • Claude Code retries an in-band event: error itself
    • the Claude Code pane looks the same on both legs; the curl and SDK legs show the retry
  • The deployment's max_retries is not a retry budget here; num_retries is
  • A multi-deployment group may retry on a sibling deployment, as the pre-stream retry does
  • A retry whose own stream drops again continues the same count, and the first retry's budget binds every later attempt whichever deployment it lands on
  • A fallback after exhausted retries replaces the retry headers with its own
    • the pre-stream path does the same; the spend log metadata (attempted_retries, previous_models) keeps the count
  • An in-band event: error ending still writes no spend or failure row
    • true after 1 + num_retries attempts too; the in-band ending never wrote one
  • Pre-content drops on /v1/chat/completions and /v1/responses are still not retried
  • Under a retry policy, a class granted fewer retries holds its last attempt's frames
    • the hold ends at the larger of the plain budget and the largest budget the policy names across error classes
    • with no fallbacks that attempt's pre-content drop answers the mapped HTTP error (500 JSON) instead of 200 plus event: error
  • An error response's retry count can read one short
    • it carries the count stamped at the last retry whose stream opened
    • right when that retry's stream dropped (c06, 1 of 1), one short when the retry failed before its stream opened (drop then 400: x-litellm-attempted-retries: 0 after 2 upstream hits) or was refused by the per-request cap (i01: 1 of 2 after 2 hits)
  • x-litellm-max-retries is new on a stream that followed an opened retry
    • a fallback's response carries it too (0 attempted retries next to the budget); a stream that never retried carries none, as before
  • The spend row's max_retries names the budget of the last retry made
    • the router's or deployment's when no mid-stream retry ran, the policy's grant when one did
  • A lone ping before the drop sends headers out with x-litellm-attempted-retries: 0
    • native Anthropic path only, when the ping arrives in its own transport chunk; the retry that follows is then recorded only in the Logs page and the spend log metadata
    • on the completion bridge, which sends no pings, the retry is always in the headers
  • A deployment num_retries: "1" (a digit string) counts mid-stream and not pre-stream
    • os.environ/... substitution leaves a digit string, and the pre-stream reader accepts only an int, so it falls to the router default there; pre-existing, left to a follow-up
  • A request body num_retries: true counts as one retry on both paths
    • a bool is an int to Python; a string, float or null body value falls to the router default (e03), and -1 means no retries
  • A 408 or 409 arriving as an SSE event: error frame is not retried
    • the frame gate stays 429 and 5xx, while the same status raised is retried; the Anthropic error-frame vocabulary has no such type
  • On generic routes a deployment's num_retries now wins over the router's before the stream opens
    • the routes the proxy's @client wrapper does not cover: files, vector stores, containers, skills, video, realtime, OCR, count_tokens, interactions, managed agents
    • only when the request carries none, as the routing docs already say; the audit drives the fine-tuning jobs list route (C10, deployment 1 wins over router 0 after a 500), the other routes were not driven
  • The issue's own pytest passes its retry assertion on the tip
    • adapted to the AI Gateway route: 4 upstream hits for num_retries: 3
    • its after-content case expects a raised error where the gateway answers event: error, which this PR does not change

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

  • 5af838e passes /live-pr-risk

  • 5af838e passes /audit


Note

Medium Risk
Changes core router streaming, retry budgeting, and client-visible timing/headers for all /v1/messages streams with retries enabled; behavior shifts (frame hold, cap interaction on chat bridge, 500 vs in-band errors in some policy cases) are documented but affect production traffic patterns.

Overview
Adds same-group retries for /v1/messages streams that fail before any content reaches the client—connection drops, pre-stream HTTP errors, and retriable SSE event: error frames—using the same num_retries / retry-policy rules as pre-stream failures, and only then runs the existing fallback chain.

While a retry or fallback might still succeed, the router buffers early lifecycle SSE (instead of forwarding immediately) so a clean restart is possible; FallbackAwareAnthropicMessagesStream now mirrors attribution from inner retry/fallback streams and stamps x-litellm-*-retries headers. Provider error frames are mapped via new anthropic_error_frame_exception so overloaded frames align with InternalServerError for policy budgeting. fallback_event_handlers gains request metadata helpers (attempted_retries, committed budget, routed deployment carry-over); resolve_retry_policy is exported for router use.

Reviewed by Cursor Bugbot for commit 5af838e. Bugbot is set up for automated code reviews on this repo. Configure here.

…e first content chunk

A /v1/messages stream that the upstream closed before any content reached the
client answered an error event after a single attempt, so the router's
num_retries never applied to that drop. The pre-content failure is now retried
within the model group before the fallback chain runs, with the budget resolved
the way a failure raised before the stream opened resolves it: a retry policy
that names the error class, then the request's num_retries, then the
deployment's, then the router's. A drop after content reached the client keeps
surfacing the provider's error after one attempt.

Fixes #44238
@devin-ai-integration

devin-ai-integration Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor Author

I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".

  • Disable automatic comment, CI, and merge conflict monitoring

@greptile-apps

greptile-apps Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[High risk] Adds mid-stream retry logic to the message streaming handler.

The PR appears safe to merge based on the current findings.

Findings

  1. P1 Overload responses change without flag ▶

Summary

The PR retries /v1/messages streams that fail before content, using the configured retry budget before attempting fallbacks. It also buffers pre-content lifecycle frames and carries retry and deployment attribution into response headers.

  • The changes since the previous review are a merge from main; no new actionable issue was established in the PR changes.

Reviews (13) · Last reviewed commit: "chore: merge main into litellm_messages_..."

Comment thread litellm/router.py Resolved
Comment thread litellm/router.py Resolved
Comment thread litellm/router.py Resolved
Comment thread litellm/router.py Resolved
@codspeed

codspeed Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_messages_stream_retry_pre_first_chunk (5af838e) with main (9cdedf8)1

Open in CodSpeed

Footnotes

  1. No successful run was found on main (cad87a9) during the generation of this report, so 9cdedf8 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

@codecov

codecov Bot commented Oct 2, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.03524% with 9 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/router.py 96.53% 6 Missing ⚠️
litellm/llms/anthropic/common_utils.py 85.71% 2 Missing ⚠️
litellm/router_utils/fallback_event_handlers.py 97.36% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

… and type the retry helpers

A retry that failed before its stream opened with an error no retry covers raised straight to the
client, skipping a fallback the first attempt would have used. assert_never now comes from
typing_extensions so the router imports on Python 3.10, and the retry helpers read their kwargs
through typed narrowing instead of Mapping[str, Any]
…ry gate reads

The retry gate passed the router's fallback attributes, declared without element types, to the
typed request override helper, which basedpyright counted as new unknown-argument errors
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

Comment thread litellm/router.py Resolved
…ages stream overflows

A retry attempt raising ContextWindowExceededError reached the fallback chain inside its
mid-stream envelope, so only the regular fallbacks list matched. The fallback attempt now
unwraps it the way it unwraps a content policy error. The new router helpers are covered for
the router code coverage check with two direct-call tests and named covering tests
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

…t that served it and bound the retry-policy hold
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

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.

Stale Bugbot comment from a previous run.

Comment thread litellm/router.py Resolved
Comment thread litellm/router.py Resolved
… class and keep the first drop's committed budget

An `event: error` frame that arrives before the first content delta now raises the exception class the pre-stream mapping gives an HTTP answer with the same status (429 RateLimitError, 500 and 529 InternalServerError, 503 ServiceUnavailableError, 504 Timeout), so a retry policy's per-class budget governs it the way it governs the error before the stream opened. The status the client sees is unchanged

A retry that lands on a sibling deployment keeps the budget the first drop committed to, read back from the request's attempted_retries and max_retries, instead of recomputing it from the new deployment's num_retries, matching the pre-stream retry loop
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

Comment thread litellm/router.py Resolved
Comment thread tests/unit/test_router/test_router.py Resolved
Comment thread litellm/router.py Fixed
…s and type the retry test helper

The status-to-exception mapping an `event: error` frame gets before the retry policy is consulted now lives next to the Anthropic error status map in llms/anthropic/common_utils.py, with its own unit test, and the two-deployment retry test helper takes explicit typed parameters instead of a bare dict and untyped kwargs
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

… mapping

An overloaded `event: error` frame on a /v1/messages stream now raises the InternalServerError a 529 answer maps to, built by exception_type from the frame's own body, so one retry policy class governs the error before and after the first byte; a failed fallback after such a frame answers 500 like every other litellm path instead of the frame map's 503

A model_group_retry_policy that does not parse (a non-integer budget, an entry that is not a mapping) no longer fails every healthy stream of that group before its first attempt: the stream runs with no policy and the plain num_retries budget, with a warning naming the group
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

Comment on lines +85 to +88
frame_body: Final = json.dumps({"type": "error", "error": {"type": error_type, "message": message}})
frame_error: Final = AnthropicError(status_code=status_code, message=frame_body)
try:
exception_type(model=model, original_exception=frame_error, custom_llm_provider="anthropic")

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.

P1 Overload responses change without flag A pre-content overloaded_error now maps from 503 to 500 and switches retry-policy classes. Existing configurations may behave differently, violating the requirement for a user-controlled flag on backward-incompatible changes

Rule Used: What: avoid backwards-incompatible changes without user-controlled flags Why: This breaks current behaviour for users using existing functionality Example of BAD: this PR (#22164) introduced run_post_custom... (source)

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.

The same overloaded error already answers 500 on main before the stream opens. Only a failed fallback returned 503, so a flag is unnecessary

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.

You're right. The direct overloaded_error path already maps to InternalServerError/HTTP 500 before streaming; the 503 behavior on main was specific to the failed-fallback response, not the primary error. This change aligns the SSE frame with the existing pre-stream mapping so retry-policy classification is consistent, rather than introducing a new user-visible status change on the primary path. A user-controlled flag is therefore not necessary, and I’m withdrawing that finding.

…provider sent it

A pre-content error frame whose class the retry policy grants no retry, with no fallback configured, raised an HTTP error only on the first attempt while the same frame after exhausted retries reached the client verbatim. Both now pass through as sent, the way the merge base forwarded every frame.
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

… and budgets

Adds the /audit cells for the pre-content stream retry: the native Anthropic route
(drops and error frames before content, HTTP rejections before the stream opens, SDK
sync and async, after-content and non-retriable controls, budget exhaustion, cache
twin, spend row and headers), the chat and responses bridges, the generic routes
(responses, chat, vllm pass-through, Gemini generateContent, fine-tuning jobs list),
owned two-worker proxies for router-level budgets, retry policies and fallbacks, and
two chaos cells (a worker killed mid burst, an outage on every first attempt). Shared
helpers for scripted Anthropic SSE upstreams and OpenAI-compatible wire replies live
in tests/integration/_support
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

Resolves the one conflict, in tests/unit/llms/anthropic/test_anthropic_common_utils.py, by keeping both
appended test blocks. Adds a reasoned reportPrivateUsage suppression on the stream wrapper's call into
Router._prepare_fallback_hidden_params, since main used up the room that diagnostic had in the budget
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

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 5af838e. Configure here.

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: /v1/messages streaming: transport drop before first content is never retried (num_retries/max_retries ignored), surfaces as HTTP 500

2 participants