Repository navigation
fix(router): retry a /v1/messages stream the provider drops before the first content chunk - #44276
Conversation
…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
|
I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".
|
|
Codecov Report❌ Patch coverage is
📢 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
…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
…loyment num_retries before the stream opens
…t that served it and bound the retry-policy hold
|
bugbot run |
… 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
…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
… 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
| 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") |
There was a problem hiding this comment.
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)
There was a problem hiding this comment.
The same overloaded error already answers 500 on main before the stream opens. Only a failed fallback returned 503, so a flag is unnecessary
There was a problem hiding this comment.
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.
… 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
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
|
bugbot run |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit 5af838e. Configure here.
TLDR
Problem this solves:
/v1/messagesstream dropped before any content ends inevent: errornum_retriesnever runsHow it solves it:
num_retriesnum_retries: 0turns them offnum_retriesis also stamped pre-stream on the generic routesIntentional product change: with retries available,
message_startandcontent_block_startare 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 asmessage_start, so in practice the hold has no keepalive. The client sees the headers a moment later and loses nothingUser 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_retriessetPOST https://litellm-domain/v1/messageswith"model": "glm-5.3","stream": true,"max_tokens": 64through the Anthropic Python SDK (client.messages.stream(...))event: message_startfollowed byevent: error(api_error, "Response payload is not completed")APIStatusError(status 200), the upstream saw exactly one request, and the developer's app has to send the whole call again itselfAfter: the same request comes back complete because the gateway retried the drop before anything reached the client
POST https://litellm-domain/v1/messageswith"model": "glm-5.3","stream": true,"max_tokens": 64through the Anthropic Python SDKnum_retriestimesfinal_message()carriesstop_reason: end_turnand the textx-litellm-attempted-retries: 1andx-litellm-max-retries: 3event: errorafter one attempt, since that content cannot be taken backDecisions
num_retries, then the deployment'slitellm_params.num_retries, then the router's. Alternative rejected: reading the deployment'smax_retries, which is the provider SDK's own knob and defaults to 0 under the routernum_retriesof 2 now applies to every/v1/messagesstream, 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) brokennum_retriestherefore 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: forwardingmessage_startlive 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 madeattempted_retriesandmax_retriesinto the request metadata, so a retry's own stream dropping again continues the same count instead of starting over, and onto the response asx-litellm-attempted-retries/x-litellm-max-retries, the pre-stream retry's headers; a later fallback's headers replace them, as they do pre-streamlitellm._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 itlitellm_params.num_retriesis 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@clientwrapper 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 itnum_retriesas given (so a bodytruecounts as one retry, being anintto Python), a deploymentnum_retriesthe way the config loader leaves it (anintor a digit string, asos.environ/...substitution produces). The pre-stream reader of the deployment knob accepts only anintand falls to the router default for"1", a pre-existing gap this PR leaves to a follow-up rather than widening its scopecontext_window_fallbacksandcontent_policy_fallbacksare consulted the way they are for a failure before the first stream opened. Alternative rejected: handing over the mid-stream envelope, which only the regularfallbackslist matchedevent: errorframe is classed by running anAnthropicErrorcarrying the frame's own body through the pre-stream exception mapping, so the class agrees by construction: an overloaded frame is theInternalServerErrora 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 acrossInternalServerErrorRetriesbefore the stream andServiceUnavailableErrorRetriesafter it, so one request drew on two budgetsmodel_group_retry_policyentry that does not resolve to aRetryPolicy(a non-integer budget, an entry that is not a mapping) governs nothing mid-stream: the stream runs with no policy and the plainnum_retriesbudget, 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 PRevent: errorframe 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 openslitellm_settings.num_retries_per_requestcap governs a mid-stream retry the way it governs a pre-stream one, through the same counterlog_retrykeeps, 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 JSONMax 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_asynccarries 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 retryRelevant issues
Fixes #44238
Linear ticket
Resolves LIT-9180
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
uv run pytest tests/unit/<your_test_file>.py -v. Leave the suites (make test-unit-*,make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or more@greptileaito re-request a review after pushing changes)Delays in PR merge?
If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).
Screenshots / Proof of Fix
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/messagestakes 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 /__hitsis the upstream's request counter,POST /__reset?drop=N&match=pongarms it. Each leg boots its own proxy with--num_workers 2and 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 commitRig 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_startand then an errorCase 2, curl stream, same drop:
message_startthen anevent: errorframe under HTTP 200, one upstream requestCase 3, control with no drop: the stream completes on one upstream request
Case 4, the provider drops before content on every attempt: still one upstream request, so neither
router_settings.num_retries: 3nor the deployment'smax_retries: 1ever fires for a drop after the headersAfter (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
pongin 2.5sCase 2, curl stream, same drop: the full lifecycle through
message_stopunder HTTP 200, two upstream requests (thinking deltas elided)Case 3, control with no drop: the stream completes on one upstream request, nothing is retried
Case 4, the provider drops before content on every attempt: four upstream requests (the first plus
router_settings.num_retries: 3, the deployment'smax_retries: 1is not the budget) over 7.1s, then the sameevent: errorframe as beforeResponse headers the client sees at 5af838e (same boot; cost, timing and model name headers elided,
x-litellm-model-idkept 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 carries0and no max header; every attempt dropped reads3of3and the stream ends inevent: error. At 9cdedf8 all three readx-litellm-attempted-retries: 0with no max headerRetry policy and per-deployment budgets, both legs
Three more boots per leg cover the budget rules: a
retry_policyclass 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 providerevent: errorframe is retried under the class its body maps to. Same rig, same client, real upstreamsRetry policy boot: the router's own
num_retriesis 0 and only the policy grants retries. The dropped stream reaches the router as an Anthropicapi_errorframe, which the pre-stream mapping classes as an internal server errorBefore (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: 0After (5af838e; proxy on :53278 with 2 uvicorn workers, drop proxy on :55465): a single drop is retried and the client gets
pongon two upstream requests; with every attempt dropped the policy's 2 retries run (three upstream requests) and the headers read2of2Two-deployment boot: one model group, deployment A with
num_retries: 3behind one drop proxy and deployment B withnum_retries: 1behind another, routernum_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'supstream hitsline is the two proxies'GET /__hitscounters after the runBefore (9cdedf8; proxy on :55304 with 2 uvicorn workers, drop proxies on :34983 and :37731): six runs, one upstream request each, no retry
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-retriesnames 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 AOverloaded frame boot: a real Anthropic
claude-haiku-4-5deployment, so/v1/messagestakes 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, andmessage_start, then writes anevent: errorframe withoverloaded_errorin 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=pongarms one planned frame per matching request. The router'snum_retriesis 0 and the policy grants internal server errors 2 retries, the class an overloaded body maps to before the stream opensBefore (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
After (5af838e; proxy on :28805 with 2 uvicorn workers, frame injector on :40271): one overloaded frame is retried and the client gets
pongon two upstream requests; with a frame on every attempt the policy's 2 retries run (three upstream requests), the headers read2of2, and the provider's own frame reaches the client unchanged; the control is one requestClaude Code, both legs
Claude Code retries a dropped stream on its own, so its pane reads
pongat 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 promptReply with the single word pong.Before (9cdedf8): the gateway answers
event: error, Claude Code sends the request again and showspong; upstream saw 3 requests (the dropped one, Claude Code's own second attempt, and one unmatched request Claude Code sends in parallel)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)Observations from the legs (what the PR causes, worsens, or leaves alone)
event: erroron HTTP 200 (leaves alone)max_retries: 1ignored, routernum_retries: 3wins (causes)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 0on 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 fromtests/integration/_support,LITELLM_LOCAL_MODEL_COST_MAP=True, routernum_retriesseeded 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@clientwrapper 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 bursttests/integration/messages_endpoint/chat_bridge/test_chat_bridge_pre_content_retry_wire.py(12 cells; base 8 red and 4 green; head green twice)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]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)test_worker_sigkill_mid_burst_leaves_the_sibling_retrying_pre_content_failurestest_outage_on_every_first_attempt_is_absorbed_by_the_deployment_budgettests/integration/messages_endpoint/providers/anthropic/test_anthropic_messages_pre_content_retry_wire.py(35 cells; base 19 red and 16 green; head green twice)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_responsetest_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_retriedtests/integration/routing/test_deployment_num_retries_generic_routes_wire.py(9 cells; base 1 red and 8 green; head green twice)test_fine_tuning_jobs_list_rejected_is_retried_per_the_deployment_budgettest_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)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_budgettest_request_num_retries_zero_turns_a_retry_policy_off,test_request_num_retries_zero_turns_the_router_budget_offType
🐛 Bug Fix
Caveats (if any)
Backward incompatible, per /live-pr-risk (ran at 940e61a against e9bf2cf, top cells again at 5af838e against 9cdedf8)
litellm_settings.num_retries_per_requestcap now reaches a/v1/messagesstream that a non-Anthropic deployment drops before contentevent: errorafter one upstream hit (it never retried); this PR answers HTTP 500 JSONlitellm.APIConnectionError: Max retries per request hit!after the same one hit/v1/messagesand/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)x-litellm-attempted-retries: 1) and two drops answer the 500wrapper_asynccarries no check), and the responses bridge was not drivenInternalServerError, as a 529 answer is), so a retry policy'sInternalServerErrorRetriesgoverns it on both sides of the first byteevent: errorafter one attemptDefaultRetries: 1under routernum_retries: 2): 500 after 2 hits withx-litellm-attempted-retries: 1,x-litellm-max-retries: 1num_retries: 1) the last attempt is live and the shape is 200 plus the error eventnum_retriesattempts1 + num_retriestimes, and an in-band ending still writes no spend or failure rownum_retries: truecounts as one retrynum_retries: "1"counts mid-stream and not pre-stream (pre-existing on the pre-stream side, follow-up ticketed)x-litellm-attempted-retriesread 0 after a mid-stream retryevent: errorframe nothing can take over for reaches the client as the provider sent itMedium
/v1/messagesstream with retries left holdsmessage_startuntil the first content deltanum_retriesis 2, so this is on unlessnum_retries: 0is setmessage_startandcontent_block_starton 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)num_retriesattempts on the group firstlitellm_deployment_total_requests_totalfor the dropping Databricks deployment 2.0 on the merge base and 5.0 here,litellm_llm_api_failed_requests_metric_total2.0 and 4.0, so a failed-requests alert sees up to1 + num_retriesfailures per request on that routelitellm_proxy_total_requests_metric_totalwhere the merge base had no entry (both its legs failed in-band)Low
litellm.InternalServerError: AnthropicException - {...}around the merge base'sMidStreamFallbackErrorline; status anderror.typeare unchangedrequest_too_large, is classed 500 and retried up to the budget before passing through verbatimparse_anthropic_error_eventdefaults 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_large3 hits here against 1)litellm_deployment_statestays 0.0 for it after overloaded frames on both sides; only raised failures feed the cooldownmessage_startusage is billed on a failure row1 + num_retriestimes writes one failure row per attempt (cost 2e-05 each on the rig) where the merge base wrote one row for its single attemptmodel_group_retry_policyentry that does not resolve to aRetryPolicygoverns nothing mid-stream, with a router warningnum_retries_per_requestbefore and after this PRwrapper_asynccarries no check; a pre-stream 503 under a cap of 1 still retries there on both sides (h01)Max retries per request hit!body on the/v1/messageschat bridge before the stream opens carries a Python traceback inerror.message/v1/chat/completionsreturns the bare message; follow-up to filenum_retries: 20stops after about 8 upstream hits on both sidesevent: erroritselfmax_retriesis not a retry budget here;num_retriesisattempted_retries,previous_models) keeps the countevent: errorending still writes no spend or failure row1 + num_retriesattempts too; the in-band ending never wrote one/v1/chat/completionsand/v1/responsesare still not retriednum_retriesunused (h01: a chat drop under any cap answers 500 with the raw error on both sides)/v1/messages, the route [Bug]: /v1/messages streaming: transport drop before first content is never retried (num_retries/max_retries ignored), surfaces as HTTP 500 #44238 reportsevent: errorx-litellm-attempted-retries: 0after 2 upstream hits) or was refused by the per-request cap (i01: 1 of 2 after 2 hits)x-litellm-max-retriesis new on a stream that followed an opened retry0attempted retries next to the budget); a stream that never retried carries none, as beforemax_retriesnames the budget of the last retry madex-litellm-attempted-retries: 0num_retries: "1"(a digit string) counts mid-stream and not pre-streamos.environ/...substitution leaves a digit string, and the pre-stream reader accepts only anint, so it falls to the router default there; pre-existing, left to a follow-upnum_retries: truecounts as one retry on both pathsboolis anintto Python; a string, float or null body value falls to the router default (e03), and-1means no retriesevent: errorframe is not retriednum_retriesnow wins over the router's before the stream opens@clientwrapper does not cover: files, vector stores, containers, skills, video, realtime, OCR, count_tokens, interactions, managed agentsnum_retries: 3event: error, which this PR does not changeFinal 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/messagesstreams 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/messagesstreams that fail before any content reaches the client—connection drops, pre-stream HTTP errors, and retriable SSEevent: errorframes—using the samenum_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;
FallbackAwareAnthropicMessagesStreamnow mirrors attribution from inner retry/fallback streams and stampsx-litellm-*-retriesheaders. Provider error frames are mapped via newanthropic_error_frame_exceptionso overloaded frames align withInternalServerErrorfor policy budgeting.fallback_event_handlersgains request metadata helpers (attempted_retries, committed budget, routed deployment carry-over);resolve_retry_policyis exported for router use.Reviewed by Cursor Bugbot for commit 5af838e. Bugbot is set up for automated code reviews on this repo. Configure here.