Repository navigation
Conversation
The Bedrock invoke /v1/messages reader passed chunk_size=1024 to httpx.Response.aiter_bytes. httpx's ByteChunker is an accumulator, not a cap: below the threshold it returns nothing at all. A message_start frame is roughly 500-700 bytes, so it sat in httpx's buffer until enough further upstream bytes arrived. During a reasoning phase nothing else arrives, so the preamble was released only once the first content block showed up, tens of seconds later, past the client's first-byte watchdog. Dropping chunk_size lets each transport read through as it lands. The event-stream decoder already emits on botocore event boundaries, so framing is unaffected. The /chat/completions invoke path was never affected: it passes stream_chunk_size, which defaults to None.
…onfigured Router._aanthropic_messages_streaming_iterator buffers message_start, content_block_start, and pings until the first content_block_delta arrives, so a mid-stream provider error can retry against a fallback deployment before any lifecycle frame commits the client to the current attempt. That buffering ran unconditionally, with no check for whether the router has any fallback deployment to retry against in the first place. For adaptive-thinking Bedrock models, the first content_block_delta doesn't arrive until the model's entire thinking pass finishes, which can take well over a minute. With no fallback configured, the buffering held message_start and content_block_start hostage for that whole window even though the provider answered in about two seconds, purely because there was nothing to protect against. Add Router._has_any_configured_fallback to check whether any fallback (general, context-window, content-policy, or a catch-all default) could resolve for the requested model group, and skip the buffering entirely when it can't: forward the source stream live instead. When a fallback is configured, behavior is unchanged.
Rewrite _has_any_configured_fallback's loop as a generator expression: basedpyright rejects a Final-annotated variable assigned inside a for-loop body (reportGeneralTypeIssues), and ruff format reflows the result.
Greptile SummaryThis PR forwards Bedrock Anthropic lifecycle frames without HTTP chunk thresholds and bypasses Router buffering when fallback recovery is disabled or unavailable
Confidence Score: 3/5The PR is not yet safe to merge because fallback matching and weighted-failover viability can still preserve unnecessary lifecycle buffering Special fallback entries can arm buffering even when their retry branches cannot resolve them, while weighted failover still arms buffering based on configured deployment count rather than currently usable alternatives Files Needing Attention: litellm/router.py
|
| Filename | Overview |
|---|---|
| litellm/router.py | Adds no-fallback live forwarding and recovery detection, but special-fallback matching diverges from retry resolution and weighted viability remains incomplete |
| litellm/llms/bedrock/messages/invoke_transformations/anthropic_claude3_transformation.py | Removes httpx fixed-size byte chunking so complete Bedrock event frames can be decoded immediately |
| tests/router_unit_tests/test_router_anthropic_messages_fallback.py | Adds focused coverage for configured fallback categories, stripped names, request lists, order levels, and weighted failover |
| tests/test_litellm/llms/bedrock/messages/invoke_transformations/test_anthropic_claude3_transformation.py | Adds a byte-faithful regression test proving message_start arrives before the next upstream event |
| tests/test_litellm/test_router.py | Adds no-fallback forwarding, upstream cleanup, and configured-fallback buffering coverage |
Reviews (4): Last reviewed commit: "fix(router): respect disable_fallbacks a..." | Re-trigger Greptile
PR overviewAll previously flagged issues have been addressed. No open security concerns remain on this pull request. Security reviewNo open security issues remain on this pull request. Fixed/addressed: 1 · PR risk: 0/10 |
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
Close the upstream stream on client disconnect in the no-fallback live-forward path, matching the buffered path's shielded aclose_if_supported cleanup. Fix _has_any_configured_fallback to match what a real retry would resolve: a stripped model-group key and a client-supplied non-standard fallbacks list both arm a retry but were reported as "nothing configured" before this fix.
…he fallback gate _has_any_configured_fallback only checked fallbacks/context_window_fallbacks/ content_policy_fallbacks, missing two retry paths the same dispatcher runs unconditionally: order-based fallback across deployments at different `order` levels, and enable_weighted_failover's intra-group re-pick. Either could still retry a mid-stream error after lifecycle frames were forwarded live, appending a second message_start onto an already-committed stream.
…ability Addresses two PR review comments: 1. When disable_fallbacks=True is set on a streaming Anthropic Messages request, skip the buffer-until-content path even if fallbacks are configured. The request explicitly opted out of recovery, so withholding lifecycle frames provides no benefit and only adds latency. 2. When enable_weighted_failover is enabled, only report a recovery path if the routing strategy is simple-shuffle AND there are multiple deployments available. Weighted failover cannot select an alternative deployment for single-deployment groups or non-simple-shuffle strategies, so the unconditional return was incorrectly triggering buffering with no actual fallback protection. Both issues caused Anthropic lifecycle frames (message_start, content_block_start) to be buffered until visible content arrived, preserving the adaptive-thinking delay this PR is intended to remove.
Context-window and content-policy chains resolve through _get_fallback_model_group_for_lookup_groups at retry time, which matches an exact model-group key only and raises the original exception on a miss. The gate checked all three lists with the permissive generic resolver, so a wildcard or stripped-name special chain armed buffer-until-content for a retry that could never run, paying the lifecycle delay for nothing. Resolve each list the way the dispatcher does, and fix the weighted-failover test's stale single-deployment group now that the gate checks re-pick viability.
…itellm_anthropic_messages_router_fallback_ttfb # Conflicts: # litellm/router.py
…lper The buffering gate copied async_function_with_fallbacks' order-scan, so both call sites reached into litellm.utils._get_deployment_order and the duplicate tripped the LIT006 and reportPrivateUsage ceilings. Put the scan next to the private accessor as get_distinct_deployment_orders and call that from both, which drops 4 private reads where the gate only needed 2 gone. Also validate the fallback list through a TypeAdapter instead of narrowing it with cast, and ratchet the basedpyright limits down by what this clears.
|
Ok, I think this is ready for a maintainer review... @shivamrawat1 @mateo-berri |
TLDR
Problem this solves:
/v1/messagesstreams delaymessage_startuntil the model finishes thinkingHow it solves it:
User Flow
Before: a developer streaming a request through the proxy's
/v1/messagesendpoint sees no bytes at all for as long as the model spends thinking, even though the exact same request straight to Bedrock starts streaming in about two secondsPOST https://<proxy-domain>/v1/messageswithmodelset to a Bedrock adaptive-thinking model (e.g.us.anthropic.claude-sonnet-5),"thinking": {"type": "adaptive"},"output_config": {"effort": "max"}, and"stream": trueevent: pingframe arriving roughly every 15 secondsevent: message_start, does not appear until the model finishes its entire thinking pass, which for a largemax_tokensceiling can be a minute or more laterevent: message_startwithin about two seconds every time, so the developer has no way to tell in advance whether their next call through the proxy will start in two seconds or two minutesAfter: the same developer sees
event: message_startandevent: content_block_startarrive within about two seconds, matching a direct call to Bedrock, and only the model's own thinking time accounts for any further wait before visible contentPOST https://<proxy-domain>/v1/messageswith the same bodyevent: message_startandevent: content_block_startarrive within about two secondsevent: pingkeepalives may still appear while the model keeps thinking, but only after the real lifecycle events already reached the clientevent: content_block_deltamatches the model's own thinking time exactly, the same as calling Bedrock directlyRelevant issues
Fixes #39431
Linear ticket
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
uv run pytest tests/test_litellm/<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
Config the proxy ran with (no fallbacks configured anywhere in the file):
Ran with
AWS_BEARER_TOKEN_BEDROCKset (a short-term Bedrock API key), which rules out AWS credential resolution as a factor. Both runs use the same request body (thinking: {"type": "adaptive"},output_config.effort: "max",max_tokens: 8000) against a live proxy hitting real Bedrock, viapython ttfb_litellm_direct.py --runs 1(MAX_TOKENS=8000)Before (2ffe6a1)
MAX_TOKENS=8000 LITELLM_API_KEY=<REDACTED> python ttfb_litellm_direct.py --runs 1message_startdoes not reach the client until 61.35s, three keepalive-ping cycles later, even though this commit already includes the httpx chunk-size fix on its ownAfter (8f5f42f)
MAX_TOKENS=8000 LITELLM_API_KEY=<REDACTED> python ttfb_litellm_direct.py --runs 1message_startandcontent_block_startboth reach the client within about two seconds.event: pingstill appears afterward while the model keeps thinking, andcontent_block_deltastill doesn't land until 63.52s, but that wait now matches Bedrock's own thinking time (confirmed separately against Bedrock directly, bypassing the proxy) rather than the proxy withholding data it already hasType
🐛 Bug Fix
Caveats (if any)
Medium
chunk_size). Its router-side gate reuses_refusal_fallback_available, which does not checkcontext_window_fallbacks, and forwards lifecycle frames live without marking the stream as having generated content. For a router configured with onlycontext_window_fallbacks, that combination lets a later context-window error still attempt a fallback and append a secondmessage_startonto a stream that already delivered one live, reintroducing the double-lifecycle problem the buffering exists to prevent. This PR's gate (_has_any_configured_fallback) checks all four fallback categories and skips the buffering path entirely rather than partially, so that gap doesn't apply hereLow
chunk_sizeremoval (97da25fc) and the router mid-stream-fallback gate (1b2cbb55,8f5f42fa). Tested in isolation, the router fix alone getsmessage_startout fast but leavescontent_block_startstuck, since httpx's fixed 1024-byte chunking can split a frame across its boundary independent of the router-level issue - both are needed together for every lifecycle frame to forward live/chat/completionsmid-stream-fallback iterator (_acompletion_streaming_iterator) was not audited for the same unconditional-buffering gap; this PR only touches the anthropic_messages pathFinal Attestation