Repository navigation
fix(router)!: bound fake-streamed calls by the request timeout, not stream_timeout - #47162
Conversation
…ream_timeout A stream=True call that the provider serves as one non-streaming request (Bedrock Converse for json_schema on models without native structured output, tools on some Llama models, ai21) gets no byte until generation ends, so stream_timeout acted as a total-duration cap. The Router now passes timeout and stream_timeout separately to chat completion calls, and completion() applies stream_timeout only when it reads a live stream.
…er's timeout split
… stream_timeout under prompt management
…on_stream_timeout # Conflicts: # tests/unit/llms/bedrock/chat/test_bedrock_converse_handler.py
…lit timeouts on every surface A faked stream now takes the longer of timeout and stream_timeout, so a caller who raised stream_timeout to cover a slow fake stream keeps that headroom. Azure o-series dispatch is mirrored when deciding whether a stream is faked. text_completion, /v1/messages and /v1/responses through the Router now get timeout and stream_timeout separately, like chat calls.
…ms, and cover M365 and Rust messages
…on_stream_timeout
Native /v1/messages and /v1/responses now record the timeout they applied, so x-litellm-timeout and the cooldown guard read the real limit instead of the raw request value. A prompt-managed model also passes on only the caller's or its own timeout, so the target deployment's timeout still wins.
…ndoff and report the applied stream limit
…accept text timeouts on responses
…one piece the longer limit
|
@litellm-stampbot |
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
|
@litellm-stampbot |
litellm-stampbot: risk lowApproved at Rules (
Cursor Bugbot: Low Risk at Pushes do not re-run this check. Comment |
|
bugbot run |
kerry-berri
left a comment
There was a problem hiding this comment.
Low risk by rule and by judgement at 2c3d4c7
…imeout' into litellm_fake_stream_request_timeout
|
@litereview code-review |
Merging this PR will not alter performance
|
|
|
@litereview code-review |
[High impact] The PR appears safe to merge, with no new actionable findings SummaryThe PR gives fake streams the longer of
Reviews (2) · Last reviewed commit: "Merge remote-tracking branch 'origin/lit..." · Reviewed by Greptile |
|
bugbot run |
|
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 6e5bddf. Configure here.
…erriAI#47419) Backport of BerriAI#47419 to stable/1.106.x. Cherry-picked from 3124797 (main). Adapted to the line without BerriAI#41523. Registered rates are tracked per cost-map key in litellm.utils (_registered_pricing_fields, reset when litellm.model_cost is replaced, so a request-scoped registration does not outlive its catalog) instead of AliasedCostEntry.registered_fields. AliasedCostEntry and get_model_cost_map.py are untouched. The register_model replay now merges successive registrations as on main. An inference-profile ARN model_id is reduced to its profile id inside _invoked_model_id_for_cost rather than backporting the get_model_info ARN handling from BerriAI#46128. Only BerriAI#47419's lines are taken in completion_cost; base_model_pricing_provider (BerriAI#46318) and configured search cost (BerriAI#46571) are not. Tests: CONVERSE_ANSWER added to the slow_upstream helper (it came with BerriAI#47162, which is not backported), the isolated_pricing_registry fixture and custom-pricing helpers come from main's test file, and the ignore_stamped_cost assertion uses the line's response_cost_calculator signature.
TLDR
Problem this solves:
stream=Truecalls without streaming, so no byte arrives until the answer is donestream_timeoutthen caps the whole call and cuts slow answersHow it solves it:
stream_timeout, and a faked stream gets the longer of the twoReplaces #46908
Breaking change: outside the Router,
stream_timeouton a direct SDK call or in the proxy'sx-litellm-stream-timeoutheader now cuts live streams, where it was ignored. Remove it or set it equal totimeoutto keep the old behaviorUser Flow
Before: a Python app streams a long structured answer from Bedrock through the SDK Router and times out at 15s
Router(model_list=[<a Bedrock model>], timeout=120, stream_timeout=15)json_schemaanswer withrouter.completion(..., stream=True)orrouter.acompletionlitellm.Timeout: Connection timed out after Timeout(timeout=15.0) secondsAfter: the same call is bounded by the 120s
timeoutand returns the whole answerRouter(model_list=[<a Bedrock model>], timeout=120, stream_timeout=15)json_schemaanswer withrouter.completion(..., stream=True)orrouter.acompletionAffected release
Router.acompletionregressed in v1.106.0-rc.1, andRouter.completionhad it in earlier releasesDecisions
A faked stream gets the longer of
timeoutandstream_timeout, since no byte arrives until the answer is writtenWhy the longer limit, where it is picked, which streams count as faked, and what keeps its current handling
The longer value is compared limit by limit when either is an
httpx.Timeout. Usingtimeoutalone was rejected because a caller who raisedstream_timeoutfor a slow faked stream would fail sooner. Callingstream_timeouta total-time cap was rejected because a short one meant for stalled live streams kills every slow structured answerThe Router hands
completion()both values andcompletion()picks one, because onlycompletion()knows whether the provider streams for real once it has mapped the request (ajson_schemarequest on a model without native structured output is only faked after that step). The alternative was to have the Router ask the provider up front, which cannot see that case, or to passstream_timeoutinto every provider handlerA stream counts as faked when any site that dispatches it fakes it: the request's
fake_streamflag, the provider config the handler uses, the Responses API bridge for models without native streaming, Vertex Gemma, Bedrock invokeai21, and Microsoft 365 Copilot. Vertex legacy code models also fake the stream, but their handler gets no timeout at all, so neither value reaches them. For Azure that is the o-series handler's own check on the deployment name, used only whenbase_modelor the deployment name is an o-series model, which is how the call is dispatchedA direct
litellm.completion(stream=True, stream_timeout=X)orlitellm.responses(...)call now appliesXto a live stream, where before only the Router's single value reached it. The alternative was to pass the Router's value under a private key so direct callers keep havingstream_timeoutignored, but a caller who sets it means itOn a stream request the Router's
timeoutis already the longer of the two values, so a stream that a deployment hook (web search, code interpreter, headroom) or an MCP loop answers with one non-streaming call never fails sooner than it did before, or sooner than the same call withstream=False. The alternative was to mark those calls as faked where each hook converts them, which misses the MCP loops. A text timeout, which is what anos.environ/value in the config resolves to, is read as a number before the two are comparedA prompt-managed model that hands off to another model group passes on only the caller's or its own
timeoutandstream_timeout, so the target deployment's own values still win over the Router'sThe Router splits the two values on chat,
text_completion, adapter completion,/v1/messagesand/v1/responses. The bridged routes reachcompletion(), which picks as above. The native/v1/responsesroute picks the same way from its own fake-stream check, and the native/v1/messagesroute, Python or Rust, treats every stream as live. Other Router calls (embeddings, images, audio) keep the single value they got beforeEach route records the timeout it applied on the call's logging object, and the timeout error's
timeoutattribute (the proxy'sx-litellm-timeoutheader) and the cooldown check for caller timeouts read that value. The alternative was to work the value out again in the wrapper from the logged params, which on native/v1/messagesand/v1/responsesheld the raw request timeout.mock_timeouton a stream waits forstream_timeout, since the mock answers before the call knows whether its stream is fakedPre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
uv run pytest tests/unit/<your_test_file>.py -v. Leave the suites (make test-unit-*,make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or moreDelays in PR merge?
If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).
Screenshots / Proof of Fix
Last updated: 6e5bddf. QA and /live-pr-risk ran on e7b051e, the last commit with a product diff, merged in whole from #46908
Before ran at 9aab6ec and after at e7b051e against real Bedrock. Model rows use the customer's
Router(timeout=120, stream_timeout=15), and route rows curl a 2-worker proxystream_timeout/v1/chat/completions/v1/completions/v1/messages/v1/responses/v1/messages/v1/responses/v1/messages, 2s limitHaiku 5.5 faked stream, sync
Before (9aab6ec)
After (e7b051e)
Client script, fake_stream_router.py
Arguments are
sync|asyncandfake|real.fakeadds thejson_schemaresponse format, and env vars pick the model and limitsHaiku 5.5 faked stream, async
Before (9aab6ec)
After (e7b051e)
Llama 3.3 70B faked stream, sync
Before (9aab6ec)
After (e7b051e)
Llama 3.3 70B faked stream, async
Before (9aab6ec)
After (e7b051e)
Llama 3.3 70B faked stream with `timeout=3` and `stream_timeout=120`, async
Before (9aab6ec)
After (e7b051e)
Sonnet 4.6 live stream, 46s long, sync
Before (9aab6ec)
After (e7b051e)
Sonnet 4.6 live stream, 0.5s stream_timeout, async
Before (9aab6ec)
After (e7b051e)
Proxy cases, /v1/chat/completions, /v1/completions, /v1/messages, /v1/responses
Each tree boots with
QA_TREE=<tree> python nodb_proxy.py --config qa_proxy.yaml --port $PORT --num_workers 2. The wrapper dropsDATABASE_URLfrom the tree's.envand calls the CLI'srun_serverProxy config. The base leg's chat and live cases ran before the
bedrock-llamaentry was added, with the other entries the sameFaked,
/v1/chat/completions, withcountries_chat.json{"model": "bedrock-haiku", "stream": true, "messages": [{"role": "user", "content": "Name 25 countries and give each a detailed three-sentence history."}], "response_format": {"type": "json_schema", "json_schema": {"name": "countries", "schema": {"type": "object", "properties": {"countries": {"type": "array", "items": {"type": "object", "properties": {"name": {"type": "string"}, "history": {"type": "string"}}, "required": ["name", "history"]}}}, "required": ["countries"]}}}}Before (9aab6ec)
After (e7b051e). 3
data:events, thenHTTP 200 in 22.066431s. The full output is in the gistFaked,
/v1/completions, withcompletions_fake.json{"model": "bedrock-llama", "stream": true, "prompt": "Name 25 countries and give each a detailed three-sentence history.", "max_tokens": 2000, "response_format": {"type": "json_schema", "json_schema": {"name": "countries", "schema": {"type": "object", "properties": {"countries": {"type": "array", "items": {"type": "object", "properties": {"name": {"type": "string"}, "history": {"type": "string"}}, "required": ["name", "history"]}}}, "required": ["countries"]}}}}Before (9aab6ec)
After (e7b051e). 3
data:events, thenHTTP 200 in 7.283290s. The full output is in the gistFaked,
/v1/messages, withmessages_fake.json{"model": "bedrock-llama", "stream": true, "max_tokens": 2000, "tools": [{"name": "save_essay", "description": "Save a finished essay", "input_schema": {"type": "object", "properties": {"title": {"type": "string"}, "essay": {"type": "string"}}, "required": ["title", "essay"]}}], "messages": [{"role": "user", "content": "Use the save_essay tool to save a 900-word essay on the history of the printing press. Put the whole essay in the essay field."}]}Before (9aab6ec)
After (e7b051e). 6
data:events, thenHTTP 200 in 6.782183s. The full output is in the gistFaked,
/v1/responses, withresponses_fake.json{"model": "bedrock-llama", "stream": true, "input": "Name 25 countries and give each a detailed three-sentence history.", "max_output_tokens": 2000, "text": {"format": {"type": "json_schema", "name": "countries", "schema": {"type": "object", "properties": {"countries": {"type": "array", "items": {"type": "object", "properties": {"name": {"type": "string"}, "history": {"type": "string"}}, "required": ["name", "history"]}}}, "required": ["countries"]}}}}Before (9aab6ec)
After (e7b051e). 10
data:events, thenHTTP 200 in 10.162689s. The full output is in the gistLive,
/v1/messages, withmessages_stream.json{"model": "bedrock-sonnet", "stream": true, "max_tokens": 1500, "messages": [{"role": "user", "content": "Write a 600-word history of the printing press."}]}Live,
/v1/responses, withresponses_stream.json{"model": "bedrock-sonnet", "stream": true, "input": "Write a 600-word history of the printing press."}Live stall with the
x-litellm-stream-timeoutheader, withsonnet_chat_stream.json. Thex-litellm-timeoutresponse header reports the limit that cut the stream{"model": "bedrock-sonnet", "stream": true, "max_tokens": 1500, "messages": [{"role": "user", "content": "Write a 600-word history of the printing press."}]}Before (9aab6ec)
After (e7b051e)
Faked /v1/responses on a deployment with timeout 3 and stream_timeout 1
The same proxy also serves
bedrock-llama-short, the Llama 3.3 deployment with its owntimeout: 3andstream_timeout: 1. The faked stream should run to 3s, and thex-litellm-timeoutresponse header should report 3.0Before (9aab6ec)
After (e7b051e)
Direct SDK calls without a Router
litellm.acompletionandlitellm.aresponsescalled straight from an app, withtimeout=120and thestream_timeoutnamed in each row. The faked row should succeed on both sides. The live rows show the breaking change in the TLDR, where the base ignoredstream_timeoutDirect chat, Llama faked
Direct chat, Sonnet live, 0.5s
Direct responses, Sonnet live, 0.5s
Rust /v1/messages live stream, 0.3s and 30s stream_timeout
The SDK Router's
aanthropic_messages(stream=True)against Anthropic Haiku 5.5 on the Rust path (LITELLM_RUST=1), withRouter(timeout=120, stream_timeout=X, num_retries=0). The Rust path still usesstream_timeoutas the whole call's limit on both sides, and the 30s row shows the 0.3s limit is what cuts itBefore (9aab6ec)
After (e7b051e)
Web search on a /v1/messages stream, deployment timeout 2 and stream_timeout 120
A stream that web search answers with one non-streaming call. Config
haiku-websearchis Bedrock Haiku 5.5 withtimeout: 2,stream_timeout: 120, thewebsearch_interceptioncallback and a Tavily search tool. It should finish with the search result and a summary on both sides. The previous tip answered 408 after 2.6s here, which the last commit fixed. Full streams are in the gistBefore (9aab6ec)
After (e7b051e)
/audit at 062a17b: PASS, 54 cells on base and twice on head, 43 controls
Base leg at merge base 9aab6ec, head and controls legs at 062a17b, each with its own Postgres, Redis, scripted upstream and 4-worker run, head twice with the same seed and order seed. The matrix has every row and the evidence. The /live-pr-risk report lists every dependent of the change and how each was checked
stream_timeout, chat, messages, responses, completionsstream_timeout, chat, messages, responsesThe web search cells answer 408 at the 1.0s
timeouton the mid-PR commit 67aab01, so they catch that regression. One existing cell,test_s7_a_negative_timeout_has_already_expired_for_streams_and_non_streams_alike, answered 200 in the second head run. It flakes at the same rate on base, and the cause is the aiohttp transport, which this PR does not touch (Low caveat)New cells:
tests/integration/providers/test_bedrock_stream_timeout_wire.py::test_f1_to_f4_a_faked_stream_slower_than_its_stream_timeout_is_answered_within_the_deployment_timeout,::test_f5_a_faked_stream_slower_than_both_limits_times_out_at_the_deployment_timeout,::test_c11_to_c13_a_live_stream_slower_than_its_stream_timeout_still_fails_at_the_stream_timeout, andtests/integration/streaming/test_interception_converted_stream_options.py::test_a_converted_stream_slower_than_the_deployment_timeout_is_answered_within_its_stream_timeoutSurprises, none caused or changed by this PR
Deployment Info: timeout: Nonedespite set timeouts/v1/completionsreports the base leg's timeout as HTTP 500tool_choiceon/v1/messagesType
🐛 Bug Fix
Caveats (if any)
High
stream_timeoutnow cuts live streams, the declared breaking change. A stall after the first chunk raisesMidStreamFallbackErrorMedium
json_schemastream live, its 15sstream_timeoutapplies againLow
ai21, and Microsoft 365 Copilot detection is unit-tested only, for lack of deploymentsmock_timeout, a test-only flag, waits forstream_timeouton a faked streamstream=Falseat the basestream_timeout, since it fakes the stream latertimeout=-1integration cell flakes on base and head because of the aiohttp transportFinal Attestation
Bugbot summary