Skip to content

fix(router): read the first stream chunk before returning so a failure before any token runs through the retry and fallback budget - #46493

Merged
klu-berri merged 7 commits into
mainfrom
litellm_stream_first_chunk_priming
Oct 14, 2026
Merged

klu-berri merged 7 commits into
mainfrom
litellm_stream_first_chunk_priming

Conversation

@klu-berri

@klu-berri klu-berri commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

How it solves it:

  • Router._acompletion and Router._completion now read the first chunk of a CustomStreamWrapper before returning it (_aread_first_chunk / _read_first_chunk). A failure before any token therefore raises inside _acompletion / _completion, where async_function_with_retries and async_function_with_fallbacks still hold the request, so the existing retry budget, retry policy, cooldowns and fallback walk handle it with no new retry loop
  • The chunk that was read is handed to _acompletion_streaming_iterator / _completion_streaming_iterator as first_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 before
  • A failure after content has streamed is unchanged: the provider's error re-raises, the stream is never restarted

Supersedes #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 Caveats

# litellm/router.py, inside _acompletion after fetch_stream
first_chunk: Final = await _aread_first_chunk(response) if isinstance(response, CustomStreamWrapper) else None
...
return await self._acompletion_streaming_iterator(..., first_chunk=first_chunk)

async def _aread_first_chunk(stream: CustomStreamWrapper) -> _FirstChunk:
    try:
        return _FirstChunk(chunk=await stream.__anext__())
    except StopAsyncIteration:
        return _FirstChunk(chunk=None)
    except MidStreamFallbackError as e:
        raise _mid_stream_retry_trigger(e) from e   # the provider's own error, for the retry policy

User Flow

Before: a developer streaming a tool call through Router with num_retries=2 sees the request fail the moment the provider closes the stream before the first chunk

  1. They call router.acompletion(model="primary", messages=..., tools=[...], stream=True) on a Router built with num_retries=2 and no fallbacks
  2. The provider answers the stream with an error frame (or drops the connection) before any delta
  3. The call raises APIConnectionError after exactly one upstream request, the configured retries never run
  4. With fallbacks=[{"primary": ["backup"]}] the same failure jumps to backup after a single request to primary

After: the same request is retried within its own group before anything else happens

  1. They call router.acompletion(model="primary", messages=..., tools=[...], stream=True) on the same Router
  2. The provider answers the first stream with an error frame (or drops the connection) before any delta
  3. acompletion itself retries primary (the stream failure raised before acompletion returned), the next attempt opens a stream and the tool-call deltas plus finish_reason: "tool_calls" reach the caller once, with x-litellm-attempted-retries on the response
  4. With fallbacks=[{"primary": ["backup"]}], backup is only asked after primary's budget is spent, and when every stream fails before content the request ends after num_retries + 1 requests per group

Linear ticket

Resolves LIT-9585

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
  • Every automated review on my PR's latest commit has finished, and I have addressed or replied to each of its findings before requesting a maintainer review

Screenshots / Proof of Fix

Tests: tests/integration/sdk/test_router_tool_call_stream_fallback_budget_wire.py (new, same file as #46358: a real Router against the scripted local peer from tests/integration/_support/wire.py, every upstream request counted, sync and async, tool-calling stream) and tests/integration/sdk/test_router_sync_stream_fallback_wire.py (expectations updated, see Caveats). Run with PYTHONPATH=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 -q

Before (main, 4f34856, same two test files)

FAILED test_router_tool_call_stream_fallback_budget_wire.py::test_primary_dies_before_the_tool_call_opens_is_retried_within_the_group[sync]
FAILED test_router_tool_call_stream_fallback_budget_wire.py::test_primary_dies_before_the_tool_call_opens_is_retried_within_the_group[async]
FAILED test_router_tool_call_stream_fallback_budget_wire.py::test_request_num_retries_overrides_the_router_budget[sync]
FAILED test_router_tool_call_stream_fallback_budget_wire.py::test_request_num_retries_overrides_the_router_budget[async]
FAILED test_router_tool_call_stream_fallback_budget_wire.py::test_every_stream_dies_before_content_spends_exactly_the_budget[error-frame-sync]
FAILED test_router_tool_call_stream_fallback_budget_wire.py::test_every_stream_dies_before_content_spends_exactly_the_budget[error-frame-async]
FAILED test_router_tool_call_stream_fallback_budget_wire.py::test_every_stream_dies_before_content_spends_exactly_the_budget[dropped-sync]
FAILED test_router_tool_call_stream_fallback_budget_wire.py::test_every_stream_dies_before_content_spends_exactly_the_budget[dropped-async]
FAILED test_router_sync_stream_fallback_wire.py::test_walks_every_configured_fallback[sync]
FAILED test_router_sync_stream_fallback_wire.py::test_walks_every_configured_fallback[async]
FAILED test_router_sync_stream_fallback_wire.py::test_router_retries_configured[sync]
FAILED test_router_sync_stream_fallback_wire.py::test_router_retries_configured[async]
FAILED test_router_sync_stream_fallback_wire.py::test_max_fallbacks_walks_the_list_like_a_non_streaming_request[sync]
FAILED test_router_sync_stream_fallback_wire.py::test_max_fallbacks_walks_the_list_like_a_non_streaming_request[async]
14 failed, 27 passed, 16 warnings in 19.33s

The first 8 and test_router_retries_configured are the ticket (budget never spent). The other 4 are the two Caveats behavior changes

After (7136faf)

41 passed, 16 warnings in 65.13s (0:01:05)

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 the router.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_bytes feeds the Router an invoke stream whose body decodes to no events, so router.completion(stream=True) now raises BadGatewayError from the call (it used to return a wrapper the test never iterated); the test expects that and keeps its iter_bytes(chunk_size=...) assertion, with num_retries=0 so the mock is called once. tests/unit/llms/chat/test_converse_handler.py::test_router_deployment_stream_chunk_size_reaches_iter_bytes is the converse twin and got the same change. tests/unit/test_router/test_router.py::test_arouter_responses_api_bridge mocked litellm.responses with a bare AsyncMock() on a stream: True deployment and never iterated it; reading the first chunk of a stream of mocks never ends (is_chunk_non_empty on a MagicMock), so the mock now returns iter([]), an empty stream, and the test keeps its call_count == 1 assertion. tests/code_coverage_tests/router_code_coverage.py: untested_perc: 0.0

Stream parity with non-streaming requests (probe, not committed)

Same chain, primary and fb1 fail, fb2 answers, fallbacks=[{"primary": ["fb1", "fb2"]}]:

main   stream=False settings={}:                  OK header=1 hits=('primary', 'fb1', 'fb2')
main   stream=True  settings={}:                  OK header=2 hits=('primary', 'fb1', 'fb2')
main   stream=False settings={'max_fallbacks': 1}: OK header=2 hits=('primary', 'fb1', 'fb2')
main   stream=True  settings={'max_fallbacks': 1}: RAISED APIConnectionError hits=('primary', 'fb1')
tip    stream=False settings={}:                  OK header=1 hits=('primary', 'fb1', 'fb2')
tip    stream=True  settings={}:                  OK header=1 hits=('primary', 'fb1', 'fb2')
tip    stream=False settings={'max_fallbacks': 1}: OK header=2 hits=('primary', 'fb1', 'fb2')
tip    stream=True  settings={'max_fallbacks': 1}: OK header=2 hits=('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.6 tool-calling stream through Router (tool_choice="required", num_retries=2)

main  sync : returned_after=2243ms first_chunk_after=2948ms chunks=8 tools=['get_weather'] finish=['tool_calls']
main  async: returned_after=895ms  first_chunk_after=1926ms chunks=8 tools=['get_weather'] finish=['tool_calls']
tip   sync : returned_after=3215ms first_chunk_after=3215ms chunks=8 tools=['get_weather'] finish=['tool_calls']
tip   async: returned_after=2180ms first_chunk_after=2180ms chunks=8 tools=['get_weather'] finish=['tool_calls']

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 leg

Gates

ruff check clean on litellm/router.py and the new test file (the pre-existing I001 in test_router_sync_stream_fallback_wire.py is on main too and left alone), scripts/check_type_discipline.py litellm/router.py 383 findings on both main and tip, basedpyright on litellm/router.py 4160 diagnostics on both main and tip with no per-rule movement, ruff-strict.toml C901 16 on both

Caveats

  1. Stream timing changes for every Router stream, 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 a 200 whose 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 PR
  2. Fallback semantics for a stream that fails before content now follow the regular request walk instead of the mid-stream hop: x-litellm-attempted-fallbacks reports what the equivalent non-streaming request reports (1 where the mid-stream path said 2 in the probe above), and max_fallbacks no longer caps the first-level walk of the fallback list for streams (it never did for non-streaming requests, the depth check in run_async_fallback is at entry only). test_walks_every_configured_fallback and test_max_fallbacks_caps_the_walk (renamed test_max_fallbacks_walks_the_list_like_a_non_streaming_request) in test_router_sync_stream_fallback_wire.py were rewritten to the regular-walk values
  3. Three existing unit tests now expect the pre-content error from the call rather than from the first iteration (listed above). Any caller that today wraps only the iteration in a try/except and lets acompletion(stream=True) run unguarded will see pre-token failures escape from the call instead
  4. A stream that fails after content has streamed is unchanged (re-raise, no restart), same as fix(router): retry a chat completions stream that fails before its first chunk within the retry budget #46358 and main
  5. The in-iterator retry design that keeps the old timing and the old mid-stream fallback semantics is in the closed fix(router): retry a chat completions stream that fails before its first chunk within the retry budget #46358 (_retry_chat_stream_before_content, _adopt_retried_chat_stream) if it is ever wanted

Link 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

…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>
@devin-ai-integration

Copy link
Copy Markdown
Contributor

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

@CLAassistant

CLAassistant commented Oct 14, 2026 •

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

… pre-content stream tests

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@codecov

codecov Bot commented Oct 14, 2026 •

Copy link
Copy Markdown

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

codspeed Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

⚠️ 1 benchmark spent significant time in system calls

System calls cannot be consistently instrumented, so they are not included in the measure, which understates the real cost. Please switch to the Walltime instrument to accurately measure system calls.

Measurement and system calls

✅ 31 untouched benchmarks


Comparing litellm_stream_first_chunk_priming (7136faf) with main (47c4058)

Open in CodSpeed

…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>
@devin-ai-integration
devin-ai-integration Bot force-pushed the litellm_stream_first_chunk_priming branch from 2dbf200 to a1c3985 Compare October 14, 2026 20:32

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

@klu-berri
klu-berri merged commit 83980c9 into main Oct 14, 2026
140 of 143 checks passed
@klu-berri
klu-berri deleted the litellm_stream_first_chunk_priming branch October 14, 2026 21:19
devin-ai-integration Bot added a commit that referenced this pull request Oct 14, 2026
…eams that fail before content

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
yuneng-berri added a commit that referenced this pull request Oct 15, 2026
…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
mateo-berri added a commit that referenced this pull request Oct 15, 2026
…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>
yuneng-berri added a commit that referenced this pull request Oct 17, 2026
…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
yuneng-berri added a commit that referenced this pull request Oct 17, 2026
* 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>
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.

3 participants