Repository navigation
fix(router): read the first stream chunk before returning so a failure before any token runs through the retry and fallback budget - #46493
Conversation
…e before any token runs through the retry and fallback budget Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".
|
|
|
… pre-content stream tests Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
…r so the stream iterators keep their complexity Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Merging this PR will not alter performance
|
…ter.completion now that the first chunk is read there Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…r first read neither hangs nor retries Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…ead_first_chunk, _FirstChunk, _chunks_with_first) Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2dbf200 to
a1c3985
Compare
…delResponseStream is imported at runtime
…eams that fail before content Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…6570) Brings integration tests in line with intentional behavior changes from #46331, #46291, #46341, #46355, #46368 and #46493, moves the Databricks non-Claude cases off llama-3 names so they no longer download a Hugging Face tokenizer, drops the unrealistic count_tokens tools=5 case and skips the Mantle region-prefixed v1 base case as unrealistic input
…expectation (#46509) * test(integration): follow #44788 and #46101 in the openrouter translation and cache mark census expectations Expect prompt_cache_breakpoint for opted-in OpenAI and omit assistant tool-call marks from the capped census Match OpenRouter refusal, logprobs, and system fingerprint nulls Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(integration): follow #46341 blank env and guardrail param handling in keepalive and scope expectations Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(router): read the first stream chunk through the stream's iterator so MCP streams keep working Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(integration): follow #46493 retry and fallback semantics for streams that fail before content Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(integration): drop the openrouter expectations #46510 already landed on main Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(integration): restore blank lines lost in the main merge Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…eam to fall back (#47020) #46493 reads the first stream chunk inside the router's retry and fallback chain, so an invalid prompt rejected before any token now falls back to the configured fallback deployment instead of answering 400. The author confirmed this is intended The fallback test now asserts the spare serves the stream. The old 400 without a fallback attempt still holds when fallback_on_unsupported_params is false, so that contract moves to a second proxy with that setting
* fix(proxy): give /team/delete transactions a 30s timeout (#46979) Both interactive transactions in /team/delete used Prisma's 5s default. A lock wait or a short database stall past 5s expired the transaction after the keys were already deleted, so the call returned 503 and left the team row, memberships and team models behind (cherry picked from commit 6530b32) * fix(sso): concurrent first sign-ins land on the winner's account, worker-kill test stops waiting on the reap (#46855) * fix(sso): concurrent first sign-ins land on the account the winner created, worker-kill test pins half its streams to each worker * test(integration): a worker kill returns once the worker is dead, the reap waits at block exit uvicorn can take a full worker healthcheck to reap a worker that died mid-ping, so kill() held the caller that long and peers held on the surviving worker hit their client timeout * fix(sso): a sign-in that loses the first-insert race joins the default teams The losing sign-in could read the winner's row before new_user added the default teams, so its CLI key was minted with no team. The race tests now run the real new_user against a fake user table (cherry picked from commit 29cd11b) * test(e2e): fix MCP tool search hit matching and the retired Bedrock image model (#46998) * test(e2e): compare parsed MCP tool search hit names instead of raw text * test(e2e): move Bedrock image generation off the retired Nova Canvas model (cherry picked from commit e9a8581) * test(integration): fix seven CircleCI integration tests that race or assume a worker spread (#47001) * test(integration): expect the tool search call replayed beside the function call for Anthropic targets * test(integration): wait for the team spend flush before killing a worker * test(integration): poll for the S3 attempt the batch sinks write concurrently * test(integration): queue the terminal object and its sibling into the same s3_v2 flush * test(integration): time the long Bedrock version against an equally long unversioned name * test(integration): pin each half of a burst to one worker instead of hoping the kernel spreads it * test(integration): assert parsed SSE events for live pings instead of transport chunk boundaries (cherry picked from commit 910c303) * test(ui): wait for the logout navigation before checking the session is gone (#47008) (cherry picked from commit 53ef631) * fix(ui): preserve key settings drafts during background refreshes (#41350) * fix(ui): preserve key settings drafts during background refreshes * fix(ui): refresh untouched key settings while preserving edits * fix(ui): keep team-change MCP clears across key refreshes clearMcpGrants now marks the MCP fields dirty, so a background refresh with keepDirtyValues no longer restores the grants a team change just cleared. Also adapts the draft tests to the onSubmit(values, dirtyFields) signature on main and asserts a refresh does not mark untouched fields dirty, since the team admin member-key path rejects saves with non-budget dirty fields. KeyEditView becomes a one-line arrow to stay under the max-lines limit. * fix(ui): keep MCP tool defaults out of a key's edited fields MCPToolPermissions writes non-delete tool defaults for unrestricted servers on mount. Marking that write dirty made a team admin's budget-only save on a member key get rejected for editing mcp_tool_permissions. onChange now says whether a write is a default or a user edit, and the key editor dirties only edits. The edit session is now keyed by token or token_id, matching the form's own fallback, so switching between keys that only carry token_id starts fresh. * fix(ui): keep a new MCP server's default tool limits across refreshes Default tool writes for a server the user just added in this edit session are part of that edit, so they are marked dirty and survive a background refresh. Defaults written for an already saved server stay clean, so a team admin's budget-only save on a member key is still accepted. (cherry picked from commit 37b3a69) * fix(logging): stop the spend metadata merge from walking a dict the logging thread writes to (#46044) (cherry picked from commit aa32e4c) * test(integration): expect a pre-token invalid prompt on a bridged stream to fall back (#47020) #46493 reads the first stream chunk inside the router's retry and fallback chain, so an invalid prompt rejected before any token now falls back to the configured fallback deployment instead of answering 400. The author confirmed this is intended The fallback test now asserts the spare serves the stream. The old 400 without a fallback attempt still holds when fallback_on_unsupported_params is false, so that contract moves to a second proxy with that setting (cherry picked from commit 856a3f6) * test(e2e): repair fallback management test for config-owned fallbacks (#47023) * test(e2e): repair fallback round trip for config-owned fallbacks The e2e stack config sets router_settings.fallbacks, and since #45860 a /fallback write to a key the config file owns is refused with a 400. The round trip now runs on context_window fallbacks, which the stack config leaves to the database, and also deletes the rule and checks it is gone. A second test locks the new contract: a /fallback write to the config-owned fallbacks key returns 400 naming router_settings.fallbacks, and the config rule keeps being served unchanged. * test(e2e): assert the refused fallback rule is never served (cherry picked from commit 59fa785) * test(e2e): assert the Vertex cache-creation billing contract in the prompt caching test (#47027) The cache-creating call now reports cache_creation_input_tokens on top of Vertex's own prompt count and bills the write at the input rate, as Google does. The old assertions assumed neither, so the test went red on every run. Check the cache write, the discounted read, and that a second identical call reuses the cache instead. (cherry picked from commit 81a3802) --------- Co-authored-by: Mateo Wang <277851410+mateo-berri@users.noreply.github.com> Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
TLDR
Problem this solves:
Routerchat completions stream that fails before its first chunk never spendsnum_retries/v1/messagesstreams already retry in-group since PR fix(router): retry a /v1/messages stream the provider drops before the first content chunk #44276, chat completions did notHow it solves it:
Router._acompletionandRouter._completionnow read the first chunk of aCustomStreamWrapperbefore returning it (_aread_first_chunk/_read_first_chunk). A failure before any token therefore raises inside_acompletion/_completion, whereasync_function_with_retriesandasync_function_with_fallbacksstill hold the request, so the existing retry budget, retry policy, cooldowns and fallback walk handle it with no new retry loop_acompletion_streaming_iterator/_completion_streaming_iteratorasfirst_chunk=_FirstChunk(chunk=...)and put back in front of the stream by_achunks_with_first/_chunks_with_first, so the caller sees the same sequence of chunks as beforeSupersedes #46358 (closed), which fixed the same bug with the same tests by adding a retry loop inside the stream iterators (~100 lines of new logic) and kept today's stream timing. This PR is ~70 lines in
router.py(+67/-4) with no new retry loop, at the cost of the two behavior changes under CaveatsUser Flow
Before: a developer streaming a tool call through
Routerwithnum_retries=2sees the request fail the moment the provider closes the stream before the first chunkrouter.acompletion(model="primary", messages=..., tools=[...], stream=True)on aRouterbuilt withnum_retries=2and no fallbacksAPIConnectionErrorafter exactly one upstream request, the configured retries never runfallbacks=[{"primary": ["backup"]}]the same failure jumps tobackupafter a single request toprimaryAfter: the same request is retried within its own group before anything else happens
router.acompletion(model="primary", messages=..., tools=[...], stream=True)on the sameRouteracompletionitself retriesprimary(the stream failure raised beforeacompletionreturned), the next attempt opens a stream and the tool-call deltas plusfinish_reason: "tool_calls"reach the caller once, withx-litellm-attempted-retrieson the responsefallbacks=[{"primary": ["backup"]}],backupis only asked afterprimary's budget is spent, and when every stream fails before content the request ends afternum_retries + 1requests per groupLinear ticket
Resolves LIT-9585
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 moreScreenshots / Proof of Fix
Tests:
tests/integration/sdk/test_router_tool_call_stream_fallback_budget_wire.py(new, same file as #46358: a realRouteragainst the scripted local peer fromtests/integration/_support/wire.py, every upstream request counted, sync and async, tool-calling stream) andtests/integration/sdk/test_router_sync_stream_fallback_wire.py(expectations updated, see Caveats). Run withPYTHONPATH=tests .venv/bin/python -m pytest tests/integration/sdk/test_router_tool_call_stream_fallback_budget_wire.py tests/integration/sdk/test_router_sync_stream_fallback_wire.py -qBefore (main, 4f34856, same two test files)
The first 8 and
test_router_retries_configuredare the ticket (budget never spent). The other 4 are the two Caveats behavior changesAfter (7136faf)
tests/unit/test_router/test_router.py -k "stream or Stream or fallback or first_chunk or chunks_with_first":309 passed, 730 deselected(includes direct-call tests for_read_first_chunk,_aread_first_chunk,_chunks_with_first,_achunks_with_first, which the router coverage gate requires). Three existing tests now expect the error from therouter.acompletion(...)/router.completion(...)call itself (the iteration line is gone, the pre-content error raises before a stream object exists):test_acompletion_mid_stream_fallback_honors_a_per_request_fallbacks_none,test_acompletion_disable_fallbacks_reaches_the_mid_stream_hop,test_completion_disable_fallbacks_reaches_the_mid_stream_hop. Their assertions (error identity, groups called) are unchanged.tests/unit/llms/bedrock/chat/invoke_transformations/test_base_invoke_transformation.py::test_router_deployment_stream_chunk_size_reaches_iter_bytesfeeds the Router an invoke stream whose body decodes to no events, sorouter.completion(stream=True)now raisesBadGatewayErrorfrom the call (it used to return a wrapper the test never iterated); the test expects that and keeps itsiter_bytes(chunk_size=...)assertion, withnum_retries=0so the mock is called once.tests/unit/llms/chat/test_converse_handler.py::test_router_deployment_stream_chunk_size_reaches_iter_bytesis the converse twin and got the same change.tests/unit/test_router/test_router.py::test_arouter_responses_api_bridgemockedlitellm.responseswith a bareAsyncMock()on astream: Truedeployment and never iterated it; reading the first chunk of a stream of mocks never ends (is_chunk_non_emptyon aMagicMock), so the mock now returnsiter([]), an empty stream, and the test keeps itscall_count == 1assertion.tests/code_coverage_tests/router_code_coverage.py:untested_perc: 0.0Stream parity with non-streaming requests (probe, not committed)
Same chain, primary and fb1 fail, fb2 answers,
fallbacks=[{"primary": ["fb1", "fb2"]}]:At the tip a stream behaves exactly like the non-streaming request on main for the same chain
Live OpenAI, real
gpt-5.6tool-calling stream throughRouter(tool_choice="required",num_retries=2)Same chunks and tool call at both,
completion()/acompletion()now return when the first chunk is in hand (Caveat 1). A live provider cannot be made to fail before its first token on demand, so the scripted peer carries that legGates
ruff checkclean onlitellm/router.pyand the new test file (the pre-existingI001intest_router_sync_stream_fallback_wire.pyis onmaintoo and left alone),scripts/check_type_discipline.py litellm/router.py383 findings on bothmainand tip, basedpyright onlitellm/router.py4160 diagnostics on bothmainand tip with no per-rule movement,ruff-strict.tomlC901 16 on bothCaveats
Routerstream, success or failure:completion(stream=True)/acompletion(stream=True)return after the provider's first chunk instead of after its response headers (live numbers above: time-to-return grows by the model's time-to-first-token, time-to-first-chunk is unchanged). Anything timing "how long until the response object comes back" (latency-based routing, callbacks, proxy request timeouts) now includes time-to-first-token. On the proxy, a stream rejected before any token (429, 500, dropped connection) is expected to reach the client as that status instead of a200whose SSE body carries the error, because the failure now happens before the response object exists. That proxy-level consequence is inferred from the code path, not measured in this PRx-litellm-attempted-fallbacksreports what the equivalent non-streaming request reports (1where the mid-stream path said2in the probe above), andmax_fallbacksno longer caps the first-level walk of the fallback list for streams (it never did for non-streaming requests, the depth check inrun_async_fallbackis at entry only).test_walks_every_configured_fallbackandtest_max_fallbacks_caps_the_walk(renamedtest_max_fallbacks_walks_the_list_like_a_non_streaming_request) intest_router_sync_stream_fallback_wire.pywere rewritten to the regular-walk valuesacompletion(stream=True)run unguarded will see pre-token failures escape from the call insteadmain_retry_chat_stream_before_content,_adopt_retried_chat_stream) if it is ever wantedLink to Devin session: https://app.devin.ai/sessions/3584a1354e014b719702a03351d16bea
Open in Devin Desktop: https://app.devin.ai/desktop/session/3584a1354e014b719702a03351d16bea?variant=devin
Requested by: @kerrylu-berri