Repository navigation
Fix expected non-streaming cancellation handling - #9616
Conversation
ee215d9 to
7a7262e
Compare
7a7262e to
36bf89a
Compare
|
Confirmed this hits the path in studio/backend/routes/inference.py where an expected non-streaming cancel is still turned into asyncio.CancelledError and surfaces as an ASGI error instead of a 499. Will get this reviewed. |
# Conflicts: # studio/backend/tests/test_openai_tool_passthrough.py
|
Review record for #9616, carried over from the mirror it was reviewed on: danielhanchen/unsloth-staging-review#394. Findings are quoted as posted and attributed to the account that posted them. The reactions shown are the triage recorded on the mirror; none were re-applied here. Commits are named as the mirror's, with this PR's equivalent where one was found. Round 1: reviewed mirror
|
…ver recovers on every API route (unslothai#15138) Every Studio route that proxies to llama-server built its own URL, auth header, per-request client, cancel watcher and crash-respawn retry: eight copies across `/v1/chat/completions`, `/v1/messages`, `/v1/responses`, `/v1/completions` and `/v1/embeddings`, holding 20 hand-built llama-server URLs and headers in `routes/inference.py`. Fixes landed one copy at a time: - unslothai#8999 gave `/v1/chat/completions` the respawn `/v1/messages` already had, and stopped there. - unslothai#13011 found `/v1/completions`, `/v1/embeddings`, the Responses stream and `/v1/messages` still sending no per-launch key. - The disconnect handling was copied path by path in unslothai#10096, unslothai#9312, unslothai#11961 and unslothai#9616. So when llama-server was killed and relaunched on a new port, only chat recovered fully. `/v1/messages` recovered from a refused connection but not from a connection dropped before upstream response headers, and every other route failed each request until something else reloaded the model. ## Changes - `_LlamaUpstream` owns a request's calls to llama-server: - the URL and per-launch key, which move together after a relaunch; - one respawn per request, on a lost connection and never on a timeout; - a per-request client that a Stop or a disconnect closes; - a recovery wait that continues streaming keepalives and lets cancelled requests release their resources while the backend reload finishes independently; - the rule that tells a cancel from a transport error. - `_monitored_llama_call` replaces the swap-gate and API-monitor shell that `/v1/completions` and `/v1/embeddings` each spelled out. - `_llama_stream_client` replaces four streaming client constructions that disagreed on keep-alive. - Every llama-server request in `routes/inference.py` goes through `_LlamaUpstream`. The source scan that counted call sites for the key now checks that instead. - The non-streaming OpenAI passthrough's pooled-client branch is gone. Production always passes a request, so only tests reached it; they now patch the per-request client. ## Crash recovery - **Streaming `/v1/responses` (Codex) now respawns.** It had no retry, so after a crash every Codex request failed with "Lost connection to the model server" until a chat request or a manual reload. - **`/v1/completions` and `/v1/embeddings` now respawn.** Non-streaming, they previously surfaced the raw `ConnectError` as a 500. - **`/v1/messages` now retries lost connections** (`RemoteProtocolError`, `ReadError`), not only a refused connection, which is the rule chat already used. Streaming recovery applies only before upstream response headers arrive; a server can send those headers before prefill finishes. A failure after headers is not replayed. Its non-streaming nudge retry shares the request's one respawn. - **Responses, completions and embeddings now hand an MTP crash to its recovery (unslothai#13316)** before respawning; they never called it. - **A Stop that lands between two POSTs of one request now reports 499 instead of a server error.** This covers an embeddings `/tokenize` call or a `/v1/messages` nudge retry sent after the Stop closed the client. - **Streaming chat errors after recovery keepalives use the SSE response.** If recovery outlasts the pre-header status window, the response can already be HTTP 200; a later failure is delivered as an error event. Recovery failures completed within that window still return 502. Reloads still run in the shared thread pool and are serialized by the backend. Burst-load behavior during a reload is unmeasured. ## Validation - **Teardown and tokenization:** 1,096 selected backend tests passed; 1 skipped. Six new cases cover cancellation during watcher cleanup on all four non-streaming paths and embedding truncation after another request restarts the server, including a restart between the two tokenization calls. - **Recovery-wait follow-up:** 80 recovery tests and 1,317 other selected backend tests passed; 1 skipped. These cover delayed reload keepalives, Stop/disconnect and task cancellation, admission and registration cleanup, retry limits, refreshed URL/key pairs, and cancellation at reload completion. The broad-suite and live socket checks below preceded this follow-up; no live model reload was repeated. - **Initial Linux, Python 3.13, CPU run:** I ran the 344 backend test files that import `routes/inference.py` (CI's serial-only and live-server exclusions applied). 23,011 passed and 386 skipped. - **Existing failures, not from this change:** 261 failures and errors in torch-backed diffusion, audio and GPU tests also fail on `main` with this sandbox's broken torch. None fails only on this branch. - **Count-the-call-sites guards:** three source scans counted copies (the auth-header scan, the five-client `trust_env` scan and the direct-counter placement scan). They now check the one owner instead. - `test_llama_upstream_single_owner.py` exercises refused connections and connections dropped before upstream headers, along with blocked reloads that verify keepalives and prompt Stop/disconnect cleanup without a retry after cancellation. - Formatted with `scripts/run_ruff_format.py` (ruff 0.6.9); `ruff check` (0.16.10) is clean. Initial live crash check: a real stand-in llama-server process on a real port, either SIGKILLed or exiting mid-request, then relaunched by `_respawn_if_dead` on a new port with a new key. Each route was driven over real sockets. | Case | Before | After | |---|---|---| | `/v1/responses` stream (Codex), server killed | `response.failed`: "Lost connection to the model server" | Answers from the relaunched server | | `/v1/completions`, server killed | 500 Internal Server Error (`ConnectError`) | Answers | | `/v1/completions` stream, server killed | Error chunk: "Lost connection…" | Answers | | `/v1/embeddings`, server killed | 500 Internal Server Error (`ConnectError`) | Answers | | `/v1/messages`, server dies mid-prefill | 500 Internal Server Error (`RemoteProtocolError`) | Answers | | `/v1/messages` stream, connection drops before upstream headers | `error` event: "Lost connection…" | Answers | | `/v1/chat/completions`, stream and non-stream, both crashes | Answers | Answers | --------- Co-authored-by: Daniel Han <[email protected]>
Summary
asyncio.CancelledErrorto UvicornMotivation
Cancelable non-streaming requests use a dedicated HTTP client. Closing that client intentionally interrupts a blocked llama-server request, but the resulting
httpx.ReadErrorwas converted toasyncio.CancelledError. Because task cancellation bypasses normal FastAPI exception handling, Uvicorn logged an expected client stop asERROR: Exception in ASGI application.The new private exception is only an internal request-level signal. Real
asyncio.CancelledErrorstill propagates unchanged.Validation
maingit diff --checkpassedcancelled, and produced no ASGI,ReadError, orCancelledErrortracebackFollow-up commits
mainand resolved the test conflicts intest_openai_tool_passthrough.pyonto main's shared helpers./v1/embeddingshad the same pattern (a disconnected client raisedasyncio.CancelledError); it now returns 499 too, with the permit and monitor cleanup unchanged.End to end on a real Studio install with llama-server (Qwen3.5-0.8B GGUF), merge base vs head:
/v1/chat/completionswith tools, cancelled bycancel_idInternal Server Error, ASGI traceback in the logRequest cancelled./v1/completions, client hangs up