Skip to content

Fix expected non-streaming cancellation handling - #9616

Merged
danielhanchen merged 6 commits into
unslothai:mainfrom
Apoze:fix/studio-nonstream-cancel-disconnect
Oct 5, 2026
Merged

danielhanchen merged 6 commits into
unslothai:mainfrom
Apoze:fix/studio-nonstream-cancel-disconnect

Conversation

@Apoze

@Apoze Apoze commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • distinguish expected non-streaming request cancellation from real task cancellation
  • return HTTP 499 at the OpenAI and Anthropic route boundaries instead of leaking asyncio.CancelledError to Uvicorn
  • preserve upstream cleanup, monitor finalization, respawn retry, and tool-call nudge behavior

Motivation

Cancelable non-streaming requests use a dedicated HTTP client. Closing that client intentionally interrupts a blocked llama-server request, but the resulting httpx.ReadError was converted to asyncio.CancelledError. Because task cancellation bypasses normal FastAPI exception handling, Uvicorn logged an expected client stop as ERROR: Exception in ASGI application.

The new private exception is only an internal request-level signal. Real asyncio.CancelledError still propagates unchanged.

Validation

  • 733 relevant backend tests passed; 2 unrelated fixed-delay streaming tests were deselected after reproducing them unchanged on Windows main
  • Ruff, the repository formatter, Python compilation, and git diff --check passed
  • end-to-end Qwen3.8 27B non-streaming tool passthrough cancellation returned HTTP 499, finalized the monitor as cancelled, and produced no ASGI, ReadError, or CancelledError traceback
  • Hermes and DeepSeek Harness completed real tool-call round trips against the isolated server

Follow-up commits

  • Merged latest main and resolved the test conflicts in test_openai_tool_passthrough.py onto main's shared helpers.
  • The Studio-embedder fallback for /v1/embeddings had the same pattern (a disconnected client raised asyncio.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:

Scenario Base Head
Non-streaming /v1/chat/completions with tools, cancelled by cancel_id 500 Internal Server Error, ASGI traceback in the log 499 Request cancelled.
Non-streaming /v1/completions, client hangs up ASGI traceback in the log 499 logged, no traceback
Normal non-streaming request 200 200

@Apoze
Apoze requested a review from danielhanchen as a code owner August 24, 2026 06:44
@Apoze
Apoze force-pushed the fix/studio-nonstream-cancel-disconnect branch from ee215d9 to 7a7262e Compare August 24, 2026 07:16
@mahiatlinux
mahiatlinux self-requested a review August 24, 2026 07:58
@Apoze
Apoze force-pushed the fix/studio-nonstream-cancel-disconnect branch from 7a7262e to 36bf89a Compare August 24, 2026 10:34
@danielhanchen

Copy link
Copy Markdown
Member

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.

@Apoze
Apoze requested a review from oobabooga as a code owner September 3, 2026 18:03
@unslothai unslothai deleted a comment from mahiatlinux Oct 4, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 4, 2026
@shimmyshimmer

Copy link
Copy Markdown
Member

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 dd8ac3097 (no equivalent commit found on this PR)

chatgpt-codex-connector[bot] (on the mirror)

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: dd8ac30975

No triage reaction was recorded on the mirror

Verdict

The round converged at mirror dd8ac3097 (no equivalent commit found on this PR).

This is the review as it stood at that commit. Anything pushed to this PR afterwards was not part of it.

@danielhanchen
danielhanchen merged commit 27e124c into unslothai:main Oct 5, 2026
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Oct 26, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants