Repository navigation
fix(responses): keep the provider code and message on top-level stream error events - #46438
Conversation
…m error events Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
@litereview code-review |
|
bugbot run |
✅ code-review5/5 · Ready for human reviewScope: full · Full PR review. No correctness findings. The PR description no longer claims the router cooldown fix. It now lists the mid-stream 429 cooldown race as a pre-existing issue that is tracked separately, so the earlier finding is fixed. Checks and execution details
Coverage: Fixture provenance: The installed OpenAI SDK's generated Results (local, at head):
Constructors: The in-repo Compatibility: View review · Reviewed |
Merging this PR will not alter performance
|
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
CustomStreamWrapper now waits for failure logging before it raises the error the router falls back on, so the cooldown lands on the deployment that failed instead of the fallback that replaced it. Also keeps numeric error codes and the top-level message on the WebSocket and ChatGPT paths.
…ls back to another deployment The router cools a deployment down from a sync failure callback that reads the request's model_info. A failed stream submitted that callback to the logging executor without waiting, so it often ran after the router's fallback had overwritten model_info and cooled down the healthy fallback deployment instead, leaving the model group with no deployments
…dge_error_event_message # Conflicts: # litellm/litellm_core_utils/streaming_handler.py
|
@litereview code-review |
1 similar comment
|
@litereview code-review |
Review already requestedcode-review is already reviewing |
| async def test_worker_sigkill_mid_burst_leaves_the_sibling_answering_the_bridged_streams(rig: _Rig) -> None: | ||
| calls: Final = _calls(20, _CHAT_KINDS) | ||
| @pytest.mark.parametrize("kinds", [_CHAT_KINDS, _TOP_LEVEL_CHAT_KINDS], ids=["nested", "top_level"]) | ||
| async def test_worker_sigkill_mid_burst_leaves_the_sibling_answering_the_bridged_streams( |
There was a problem hiding this comment.
Medium · Parametrized SIGKILL chaos test fails because the earlier variant leaves a third worker PID in the shared proxy log
- The
rigfixture is module-scoped. Both parameters oftest_worker_sigkill_mid_burst_leaves_the_sibling_answering_the_bridged_streamsshare one 2-worker proxy and one log file. - The first variant (
[nested]) SIGKILLs a worker, and uvicorn logsStarted server process [...]again for the replacement. - The second variant (
[top_level], added in this PR) calls_worker_pids(rig.proxy.log, 2). That helper counts everyStarted server processline in the whole log. - It now sees 3 PIDs, never reaches 2, and fails after 30s with
State did not converge: (pid1, pid2, pid3). This happens before any top-level error behavior gets exercised.
Whichever variant runs second hits this. I reproduced it locally in two separate runs. The [top_level] variant passes when it runs alone, so the product code is fine.
Smallest fix: read the live worker PIDs from the process tree (rig.proxy.worker_pids()), or give each parameter its own proxy instead of scanning the cumulative log.
Evidence
Run 1, five changed integration files via tests/integration/run.py providers ... against local Postgres/Redis: 1 failed, 53 passed. The failure was test_worker_sigkill_mid_burst_..._bridged_streams[top_level] → tests/integration/streaming/test_responses_bridge_stream_chaos.py:309 _worker_pids ... AssertionError: State did not converge: (17816, 17815, 18115)
Run 2, the test function only (both params): [nested] PASSED, [top_level] FAILED, State did not converge: (18815, 18816, 19008)
The owned proxy log from run 2 has Started server process [18815], [18816], Child process [18815] died, then Started server process [19008]
Run 3, [top_level] alone: 1 passed in 52.16s
_worker_pids uses _STARTED_WORKER.finditer(log.read_text()) with the predicate len(pids) == count, so killed workers stay in the count
Latest summary by code-review · View this review · Reviewed 3b2709aa5217
There was a problem hiding this comment.
Fixed in 67b2752, the chaos test now reads live worker pids from the proxy, so the second SIGKILL variant sees exactly two workers
There was a problem hiding this comment.
Finding withdrawn
The reply is right. The failure came from _worker_pids scanning the shared proxy log with a regex. A worker killed by the [nested] variant stayed in that log, so the [top_level] variant saw three PIDs and never reached two.
At head, _worker_pids polls OwnedProxy.worker_pids(). That method lists the live, serving child processes of the supervisor. By the time the first variant exits replacing_worker, the killed worker has been reaped and its replacement is serving. The second variant therefore sees exactly two PIDs. The module-scoped rig can stay shared because the stale log lines no longer affect the count.
I verified this by reading the code and did not rerun the integration test.
Evidence
tests/integration/streaming/test_responses_bridge_stream_chaos.py:307-308: def _worker_pids(proxy: OwnedProxy, count: int) -> frozenset[int]: return eventually(proxy.worker_pids, lambda pids: len(pids) == count, seconds=30)
tests/integration/streaming/test_responses_bridge_stream_chaos.py:360: workers: Final = _worker_pids(rig.proxy, 2)
tests/integration/_support/process.py:192-197: worker_pids returns frozenset(child.pid for child in psutil.Process(self.process.pid).children() if _is_serving_worker(child))
tests/integration/_support/process.py:259-264: replacing_worker asserts the kill fired, then calls _await_replacement(before). WorkerKill.__call__ waits through _wait_until_gone and _wait_until_reaped.
The _STARTED_WORKER.finditer(log.read_text()) log scan cited in the original finding no longer appears in _worker_pids.
GitHub does not allow this App to resolve this thread. A repository maintainer must do it manually.
Reviewed d8552da4c8f4 · View follow-up
|
@litereview code-review |
Waiting for sync failure callbacks before a failed stream raises fixed the router cooldown race, but it slowed healthy calls under many failing streams with a slow callback, since the wait shares a thread pool with every call's start. The race is pre-existing on main and is tracked separately, so this PR goes back to main's logging timing and keeps only the top-level error event changes
|
@litereview code-review |
1 similar comment
|
@litereview code-review |
|
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 d8552da. Configure here.
|
@litellm-stampbot |
litellm-stampbot: risk highNot approved at Rules (
Judge (gpt-6-luna): high, default behavior change, request hot path, complex diff
Pushes do not re-run this check. Comment |
|
@litellm-stampbot |
|
@litereview full |
✅ fullScope: full · Full PR review. Completed · Some checks not run. Verdict: no actionable defects foundThis PR teaches the Responses stream error paths to read OpenAI's documented top-level What changed
Who depends on it
Caveat on scopeI verified with unit-level drives and the PR's own tests. I did not build the live base-vs-head proxy rig with real provider credentials, so the HTTP 429-vs-500 change on the proxy is reasoned from the mapping code and the unit runs, not observed on a proxy. Checks and execution details
View review · Reviewed |
TLDR
Problem this solves:
errorevents with top-levelcodeandmessageerrorobject, so those fields were droppedHow it solves it:
ErrorEventaccepts the documented top-levelcode,messageandparamerrorexists, the WebSocket path keeps numeric codes, and the ChatGPT path keeps the top-level messageThis is hardening for a documented shape. Every live OpenAI stream failure we could trigger (an unreachable MCP server) sent the nested
errorobject, which main already reads, so the top-level cases run against a local server that replays OpenAI's documented eventsThe ticket's
finish_reason="stop"symptom is a stream closing without a terminal event. #43133 fixed that in v1.105.0, so this PR resolves the ticket together with it, and the customer, now on v1.104.2, needs v1.105.0 or laterUser Flow
Before: a developer streaming OpenAI through the Responses bridge loses OpenAI's reason when the stream ends in a top-level
erroreventlitellm.completion(model="openai/responses/gpt-5.5", stream=True),Router.acompletion(...), orPOST https://litellm-domain/v1/chat/completionswith"stream": trueerrorevent withcodeandmessageat the top levelrate_limit_exceededalso comes back as a 500After: the same failure carries OpenAI's own code and message
erroreventrate_limit_exceededraises a 429RateLimitError(HTTP 429 on the proxy)Linear ticket
Resolves LIT-9574
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
Each leg runs a 2-worker proxy with no DB from its own worktree. OpenAI cannot send a top-level
errorevent on demand, so those cases use a local server replaying OpenAI's documented events. The MCP failure and healthy cases call OpenAI for realcompletion(), error eventRouter, rate limit eventRateLimitErrorresponses(), error eventresponse.failed, generic messageresponse.failed, OpenAI's messageevent: error, generic messageevent: error, OpenAI's messagestop, real usageReplay server, SDK script and proxy config, to rerun the legs
The
server_errorreplay sendsresponse.created, one text delta, then{"type": "error", "code": "server_error", "message": "An error occurred while processing your request. ..."}. Therate_limitreplay sendsresponse.created, then the same event withrate_limit_exceeded. On each commit, run the replay server, a proxy with this config, the SDK script, and the curls under each legreplay_upstream.pyproxy_config.yamlsdk_cases.pyBefore (493ed61)
SDK completion(), stream ending in an error event
litellm.completion(model="openai/responses/gpt-5.5", api_base=<replay>/server_error/v1, stream=True)'The sky looks blue because the', thenMidStreamFallbackError500Response API in-stream errorSDK Router.acompletion(), stream opening with a rate limit event
Steps and output
Router(...).acompletion(model="gpt", stream=True)on<replay>/rate_limit/v1InternalServerError500Response API in-stream errorSDK responses(), stream ending in an error event
Steps and output
litellm.responses(model="openai/gpt-5.5", api_base=<replay>/server_error/v1, stream=True)MidStreamFallbackError500Response API in-stream errorPOST /v1/chat/completions, stream ending in an error event
Steps and output
curl -sN $PROXY/v1/chat/completions -d '{"model":"gpt-replay-server-error","stream":true,...}'Response API in-stream errorPOST /v1/chat/completions, stream opening with a rate limit event
Steps and output
curl -sN $PROXY/v1/chat/completions -d '{"model":"gpt-replay-rate-limit","stream":true,...}'internal_server_error,Response API in-stream errorPOST /v1/responses, stream ending in an error event
Steps and output
curl -sN $PROXY/v1/responses -d '{"model":"responses-replay-server-error","stream":true,...}'response.failedwithResponse API in-stream errorPOST /v1/messages, stream ending in an error event
Steps and output
curl -sN $PROXY/v1/messages -d '{"model":"gpt-replay-server-error","stream":true,...}'event: errorwithapi_errorandResponse API in-stream errorReal OpenAI gpt-5.5 stream failing on an unreachable MCP server
Steps and output
litellm.completion(..., tools=[<MCP tool at a dead URL>], stream=True), then viaRouterand the proxyError retrieving tool list from MCP server ... 424Healthy real OpenAI gpt-5.5 stream
Steps and output
litellm.completion(..., stream=True, stream_options={"include_usage": True}), then via the proxy'the bridge is healthy',finish_reasonstop, real usageRaw output, SDK cases
Raw output, proxy cases
After (d8552da)
SDK completion(), stream ending in an error event
'The sky looks blue because the', thenMidStreamFallbackError500 OpenAI'sAn error occurred ...SDK Router.acompletion(), stream opening with a rate limit event
Steps and output
RateLimitError429Rate limit reached for gpt-5.5 ...SDK responses(), stream ending in an error event
Steps and output
MidStreamFallbackError500 OpenAI'sAn error occurred ...POST /v1/chat/completions, stream ending in an error event
Steps and output
An error occurred ...POST /v1/chat/completions, stream opening with a rate limit event
Steps and output
throttling_error,Rate limit reached for gpt-5.5 ...POST /v1/responses, stream ending in an error event
Steps and output
response.failedwith OpenAI'sAn error occurred ...POST /v1/messages, stream ending in an error event
Steps and output
event: errorwithapi_errorand OpenAI'sAn error occurred ...Real OpenAI gpt-5.5 stream failing on an unreachable MCP server
Steps and output
Healthy real OpenAI gpt-5.5 stream
Steps and output
Raw output, SDK cases
Raw output, proxy cases
Seen on both legs and unchanged by this PR:
completion()raises the wrapper error,Routerthe inner one/v1/responsesturns OpenAI'serrorevent intoresponse.failedResponseAPIUsageserializer warning prints on healthy streams/live-pr-risk at d8552da
Verdict: no dependent path broke on the routes we ran live at the tip and the merge base 493ed61. The changes a client or operator can see are listed below as backward incompatible, each one intended by this PR
Breaking
None observed. Every scenario above ran on both sides, and the only differences are the ones this PR names
Backward incompatible
errorevent carries a top-levelcodenow raises that code's status (429RateLimitErrorforrate_limit_exceeded) with OpenAI's message, where it raised a 500 "Response API in-stream error". Clients and the router now retry, fall back, and cool down on it like any 429. Intended, it is the ticket's askErrorEvent.erroris now optional, since a top-level error event has no nested object. SDK code that readsevent.error.messageon such an event has to handleNone. Events with the nested shape still fill it.model_dump()of anyErrorEventnow also carriescode,messageandparam,Noneon the nested shape, which the proxy drops withexclude_noneinvalid_promptnow raisesBadRequestError400, so the Router no longer falls back on it. At 493ed61 it raised a generic 500 and the fallback answered. Intended, the nested shape already gets the 400 on main, andtest_bridged_invalid_prompt_answers_a_bad_request_without_trying_the_fallbackchecks both shapesRegression risk
rate_limit_exceedednow cools its deployment down. On main, a mid-stream 429 that falls back sometimes cools down the healthy fallback deployment too (3 of 24 requests on/v1/responseswith the nested shape at 493ed61). This PR leaves that race as it is, and it is tracked separatelychatgpt/provider's non-stream path reads only the message of an error event, never itscode, for both shapes. A top-level error that does not say "rate limit" keeps the HTTP status, as a nested one does on mainDependency graph
/v1/responsesstream/v1/chat/completionsstream/v1/messagesstreamRouter.acompletionErrorEventconstructorschatgpt/providerNot verified
errorevent. The live API nests it in every failure we could trigger, so that shape ran against a replay upstreamchatgpt/provider and Responses WebSocket mode against the real services. Both ran against local wire servers onlyAudit round 4 of 3 (past the cap: the round-3 tip's logging wait was reverted)
Head d8552da against base 493ed61 on rig lit9574au, with seed 46438 and order seed 9574. Head lanes are head-run1/run2-{providers,sdk,chaos}-r4d, and controls are ctl-{providers,sdk}-r4d. Base lanes are base-providers-r3 and base-sdk-r3, plus base-chaos-r4 for X1 and X2, which ran after the chaos fix in 67b2752. The base leg's test files match d8552da's
error: nullC11, C19, C20n and S5 are parity rows, so they are green on both legs by design. The chaos lanes ran X1 and X2 with both variants in one session, with the second SIGKILL after the first. Rounds 1 and 2 at 08e7650 found C13, G2 and W1 red on both head runs, and 6380fbf fixed them. Round 3 at 3b2709a was all green. Round 4 at f4b446b was stopped when the logging wait was reverted
Type
🐛 Bug Fix
Caveats (if any)
Medium
invalid_promptnow answers 400 and skips the Router fallback, where main fell back and answered. The nested shape already does this on mainLow
errorevent on demand, so that shape ran against a replay of its documented events. The replay server and SDK script are in the proof sectionfinish_reason="stop"fix is fix(responses): fall back on pre-output stream drops, fail truncated streams, honor request_timeout #43133 in v1.105.0, so the customer needs that version too"code":"429"or"500", the HTTP status, not OpenAI's string code, the same as every other proxy errorErrorEventaccepts a top-levelparam, but nothing reads it downstream, the same as with the nested shapeErrorEvent.erroris now optional, so typed SDK code that readsevent.error.messageon a top-level event has to handleNone, and SDK dumps of anyErrorEventnow carrynullforcode,messageandparamchatgpt/non-stream path still maps errors by message text and HTTP status, never bycode, for both shapesFinal Attestation
Link to Devin session: https://app.devin.ai/sessions/f9e767de340e4d9e91d35e0b3a56a9f3
Open in Devin Desktop: https://app.devin.ai/desktop/session/f9e767de340e4d9e91d35e0b3a56a9f3?variant=devin
Note
Medium Risk
Changes mid-stream error parsing and HTTP status mapping across Responses streaming, bridges, WebSocket, and Router fallback/cooldown paths; behavior shifts (e.g. 429 vs 500) are intentional but affect production retry and routing semantics.
Overview
OpenAI Responses streams can emit
errorevents with top-levelcodeandmessage(not only a nestederrorobject). This PR teaches LiteLLM to read that shape end-to-end so mid-stream failures keep the provider’s code and text instead of collapsing to a generic 500 “Response API in-stream error”.ErrorEventnow allows an optional nestederrorand optional top-levelcode,message, andparam. Shared helpers in the Responses stream iterator build an error object from nested fields when present, otherwise from top-levelmessage/code(including numeric codes). That path is used for HTTP streaming, the Responses WebSocket bridge, and ChatGPT SSE aggregation when no nested error exists.Downstream behavior changes are intentional: e.g.
rate_limit_exceededsurfaces as 429 /RateLimitErrorwith the upstream message across chat bridge,/v1/responses,/v1/messages, Router streaming, and fallbacks where eligible. Integration and unit tests cover nested vs top-level shapes, malformed fields, cache behavior, and ChatGPT non-stream errors.Reviewed by Cursor Bugbot for commit d8552da. Bugbot is set up for automated code reviews on this repo. Configure here.