Repository navigation
fix(router): send /v1/messages message_start live during thinking when retries are on - #54319
Conversation
…y can take over With the router's default retries and no fallback, message_start and content_block_start were held until the first content delta, so a long thinking pass showed the client nothing but the proxy's keepalive ping. They now go out as soon as the provider sends them, and a retry before content drops its repeat of the frames already sent. A fallback or a refusal fallback keeps the hold.
…an take over With default num_retries, every lifecycle frame waited for the first content delta, so a long thinking pass showed the client nothing but the 15 s keepalive ping. Now message_start, plus any ping or SSE comment in front of it, goes out as soon as the provider sends it whenever only a same-group retry can take over Block starts and every other pre-content frame stay held, because a retry's first block can differ from the first attempt's (adaptive thinking can open text where the first attempt opened thinking, and redacted_thinking carries new data each time). A retry or a context-window fallback drops its own message_start and then sends its frames unchanged, so the client sees one message_start and a valid frame sequence. A fallback, refusal fallback, order level, or weighted failover left keeps the full hold, and so does a stream whose first frame is not recognized
…am_lifecycle_live_on_retry # Conflicts: # litellm/router_rust/invoke/streaming.py
… a cut retry on /v1/messages streams
… follows a live message_start
[Medium impact] The reviewed changes appear safe to merge.
|
A request with a message thread keeps the old hold, so the client sees the message id of the attempt that answers and its next continue finds the thread. Also types two test literals and the guardrail initializer lookup so the basedpyright count stops flipping between runs.
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
…an answer the stream A context_window_fallbacks list for the stream's group can take over after a retry fails, so the stream policy now reports it and message_start waits for content as before. streaming.py also reuses the shared SSE frame terminators.
…ping next to message_start stays held
|
bugbot run |
… message_start retry
|
bugbot run |
… stream logs the client's message id
|
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 02a828c. Configure here.
Handwritten 1-3 sentence description
Streaming /v1/messages requests with thinking used to get only keepalive pings until the model started writing, so hard prompts sat for minutes with no message_start. The gateway now passes message_start through right away and still retries a stream dropped before any content, with one message_start
Details
TLDR
Problem this solves:
How it solves it:
threadIntentional product change: a retry rejected after message_start ends as 200 plus
event: errorUser Flow
Before: Claude Code gets no first byte until the model starts writing, minutes on a hard prompt
claude --model claude-sonnet-5-5 --effort max --debug-file debug.logwithANTHROPIC_BASE_URL=http://localhost:4000and default router settingsdebug.logshowsfirst byte afterthe whole thinking timeAfter: the first byte comes right away, like a direct provider call
debug.logshowsfirst byte aftera couple of secondsRelevant issues
Fixes #38689 from v1.106.0 on, since its v1.98.0 report predates this hold
Affected release
Regression in v1.106.0 (#44276)
Linear ticket
Resolves LIT-10251
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 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: 02a828c. QA ran on 72e09a6 and its merge base 4f61996, and the two id cases ran again on 02a828c. Changes since QA: SDK callbacks log the client's id. Proof stands because no frame changed. Verification: id integration tests pass
Each leg ran 2-worker proxies from its tree and Claude Code v2.1.299 in its TUI. Claude Code rows show first bytes, other rows show message_start. Only mock rows skip a real provider
RoutercallbackShared setup (proxy start, config, client scripts)
Env vars:
LITELLM_MASTER_KEY,ANTHROPIC_API_KEY,OPENAI_API_KEY,AWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEY,AWS_SESSION_TOKEN. The client exportsLITELLM_KEYas the master keyThe thread proxy's config has only
claude-sonnet-5-5-flakyplusgeneral_settings.coordination_redis: {host: 127.0.0.1, port: <redis port>}, since thread owners live in each worker's memory without Redis.$QAis the QA scratch directoryThe fallback proxy's config has
mock-claudeand amock-claude-backupcopy of it, plusrouter_settings: {fallbacks: [{mock-claude: [mock-claude-backup]}]}. The context-window proxy's config is the same withcontext_window_fallbacksin place offallbacksThe spend case's proxy runs the main config with
DATABASE_URLset to a Postgres database of its ownstamp.pyprints the time of each event line the client receivesdrop_relay.py <port> https://api.anthropic.comforwards to Anthropic. AfterGET /arm?times=N&fail=M, it cuts the next N streams right before their firstcontent_block_delta, so each of those attempts dies after message_start, and then answers the next M requests with a 529overloaded_errorwithout calling Anthropic. A bareGET /armcuts one streamsdk_stream.py <base url> <model> [prompt]runs a Claude Agent SDK query (claude-agent-sdk 0.2.188) with adaptive thinking at effort max and prints each stream event's timemock_anthropic.py <port> thinksendsmessage_start, a thinkingcontent_block_startand apingat once, waits 20s, then the deltas andmessage_stopBefore (4f61996)
Claude Code, hard thinking prompt on Bedrock
ANTHROPIC_BASE_URL=http://127.0.0.1:<port> ANTHROPIC_AUTH_TOKEN=$LITELLM_KEY ANTHROPIC_DEFAULT_HAIKU_MODEL=claude-haiku-5-5 CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1 claude --model claude-sonnet-5-5 --effort max --debug-file $QA/out_base/cc_hard.debug.logWithout using any tools, count the integers between 1 and 3000 that are prime and whose digits sum to a prime. Verify your count carefully, then answer with just the number.Claude Code, dropped once
Steps and output
ANTHROPIC_BASE_URL=http://127.0.0.1:<port> ANTHROPIC_AUTH_TOKEN=$LITELLM_KEY ANTHROPIC_DEFAULT_HAIKU_MODEL=claude-haiku-5-5 CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1 claude --model claude-sonnet-5-5-flaky --effort max --debug-file $QA/out_base/cc_drop.debug.logcurl -s http://127.0.0.1:<relay port>/arm, so the relay cuts the next stream aftercontent_block_startand before any deltaAnswer in one short sentence: why is the sky blue?Thread create then continue, dropped once
Output
Other cases
curl and Agent SDK cases
Anthropic, hard thinking, curl
Bedrock, hard thinking, curl
Bedrock, Agent SDK
Anthropic, dropped once, curl
Anthropic, dropped once, Agent SDK
Anthropic, Agent SDK
gpt-5.6 bridged, curl
Anthropic, every attempt dropped, curl
Anthropic, dropped then 529, curl
Fallback, mock, curl
Fallback, mock, Agent SDK
Context-window fallback, mock, curl
Mock, 20s thinking, curl
Anthropic, dropped once, spend row, curl
The whole output is in a gist. Its last line:
SDK
Router, dropped once, callback idWhole output
After (72e09a6)
Claude Code, hard thinking prompt on Bedrock
Claude Code, dropped once
Steps and output
Thread create then continue, dropped once
Output
Other cases
curl and Agent SDK cases
Anthropic, hard thinking, curl
Bedrock, hard thinking, curl
Bedrock, Agent SDK
Anthropic, dropped once, curl
Anthropic, dropped once, Agent SDK
Anthropic, Agent SDK
gpt-5.6 bridged, curl
Anthropic, every attempt dropped, curl
Anthropic, dropped then 529, curl
Fallback, mock, curl
Fallback, mock, Agent SDK
Context-window fallback, mock, curl
Mock, 20s thinking, curl
Anthropic, dropped once, spend row, curl
The whole output is in a gist. Its last line:
After (02a828c)
Two id cases
Anthropic, dropped once, spend row, curl
The whole output is in a gist. Its last line:
SDK
Router, dropped once, callback idsdk_router_ids.pystreams through alitellm.Routerwithnum_retries=1and a success callback, against the relay that cuts attempt 1 before contentQA observations
Type
🐛 Bug Fix
Caveats (if any)
Medium
message_startends as 200 plusevent: error, so the Anthropic SDK skips its own retrymessage_startand headers, sox-litellm-attempted-retriesreads 0message_start, tracked in a follow-upLITELLM_RUST_FIRSTon, the Rust gateway still holdsmessage_start, tracked in a follow-upLow
message_startran liveDecisions
What goes out early. Frames wait for the first content delta while a retry or fallback could take over. Pings go out live as on base, and a ping that shares a read with a held block start stays held with it, as on base.
message_startgoes out live when only a retry can take over and the request has nothreadThreads. A request with
threadkeeps the old hold. Anthropic stores only the message of the attempt that answers, and the nextcontinuenames the id the client saw, so a livemessage_startfrom a cut attempt would make thatcontinueanswer 404. Rejected: mapping the cut id to the retry's id inMessageThreadOwnership, which only works with that hook on and a store shared by every replicaBlock starts.
content_block_startstill waits for the first delta. A retry can open a different block (text where attempt 1 opened thinking, or a new tool id), so a live block start could leave the client with two starts at one indexStatus. Once
message_startgoes out the status is 200, so a retry that then fails ends as 200 plusevent: error, the way Anthropic answers once its ownmessage_startis out. The Anthropic SDK retries on a status, never on that frame, so it no longer retries the request itself. Before, a retry that also dropped already ended that way, and only one rejected with an error status kept it. A group whose only retry setting is amodel_group_retry_policythat does not cover a dropped stream also goes live, so a drop there ends as 200 plusevent: errorwhere base answered 500, the same asnum_retries: 0on both. Rejected: holdingmessage_startfor the first 15s, which keeps the status a little longer but leaves the bug, and going live only when the policy names a drop's error class, which keeps the thinking delay in those groups to keep a 500 thatnum_retries: 0never sendsForced by the ask. The internal ticket asks for
message_startas soon as the provider sends it, with a later drop still retried and only onemessage_start. Once that frame is out the status, the headers and themessage_startfields can no longer change, so the 200 status, attempt 1's id, model and usage, and retry headers that read no retry follow from the askRejected. Capping the hold adds a fixed delay. Any fallback setting keeps
message_startheld,context_window_fallbacksfor the group,orderlevels and weighted failover inside one model group included, since the ticket covers the default settings and a fallback can answer from another modelAfter a retry. The client keeps attempt 1's
message_start, so its id, model and usage come from the cut attempt, and with prompt caching that usage shows a cache write where the retry read the cache. Headers go out with that first frame, before any retry, so they match a stream with no retry,x-litellm-attempted-retriesreading 0, nox-litellm-max-retries, andx-litellm-response-duration-msstopping atmessage_start. The spend row and success callbacks take the id the client saw, on the proxy and the SDKRouteralike, so/spend/logs?request_id=with that id finds it, while its usage stays the retry's likemessage_delta. When the retry lands on another deployment of the group,x-litellm-model-idnames the cut one and the spend row the one that answered. A later request that sends attempt 1's id asdiagnostics.previous_message_idgets Anthropic's 200 with aprevious_message_not_foundnote. Rejected: droppingx-litellm-attempted-retriesor addingx-litellm-max-retrieson live streams, since both change what a stream with no retry sends and neither can report a retry that has not happened yetWhole frames. Only a stream whose
message_startcan go out live is read as whole SSE frames, kept together per upstream read withmessage_starton its own, so a splitmessage_startnever goes out half and a ping keeps base's place next to the block start it came with. Rejected: one frame at a time, which sent that ping ahead of the held block start. Held streams keep base's raw reads, so a ping that shares a read withmessage_startstays held with it and the status waits as on base. Content detection reads the held bytes plus the current read, so acontent_block_deltasplit across reads still sends the stream on at onceFinal Attestation
Bugbot summary