Skip to content

Studio: stop generating when the client disconnects on a non-streaming request - #11961

Merged
danielhanchen merged 2 commits into
unslothai:mainfrom
NilayYadav:gguf-nonstream-disconnect
Sep 27, 2026
Merged

danielhanchen merged 2 commits into
unslothai:mainfrom
NilayYadav:gguf-nonstream-disconnect

Conversation

@NilayYadav

@NilayYadav NilayYadav commented Sep 25, 2026 •

Copy link
Copy Markdown
Collaborator

On GGUF, a non-streaming /v1/chat/completions request keeps generating after the client disconnects. The model stays busy until the full answer is done, so the next request has to wait, and the API page shows the abandoned request as completed. With a large max_tokens this wait was 20 to 30 seconds.

This watches for the disconnect while the answer is being generated, the same way /v1/messages already does. On disconnect it stops generation, frees the model for the next request, and marks the request as cancelled on the API page. This covers both the plain path and the tool calling path, and requests with n greater than 1. Streaming requests are unchanged.

Before / after: API monitor

A non-streaming /v1/chat/completions request (Qwen3-0.6B GGUF, max_tokens 12000) whose client disconnects after 1 second, then a short follow-up request. Before: the abandoned request is still running, the server reports Serving requests with 1/4 slots busy. After: it is recorded as cancelled (amber) after 1.0s and the server is back to Ready with 0/4 slots busy.

API monitor before and after a client disconnect

@NilayYadav

Copy link
Copy Markdown
Collaborator Author

Review + UI evidence

Pinned head: 31cddbd42f. No blocking findings.

Codex: reviewed on an exact mirror, NilayYadav/unsloth-staging#173. The mirror is based on fresh upstream main, and its diff has this PR's 3 files only. Round 1 returned "Codex Review: Didn't find any major issues" on 94adb27757, which is this PR's head 31cddbd42f merged onto main. That is converged, so no further rounds were requested.

API monitor page. Real Studio in Chromium (1500×1000) on an L4 with Qwen3-1.7B-UD-Q4_K_XL. Before is the merge base 4cfeec94d and after is this PR. The frontend is unchanged, so one install serves both sides, with separate homes, caches and ports.

Each side ran two requests:

  • A control non-streaming POST /v1/chat/completions that is allowed to finish.
  • A 400-token non-streaming request whose socket is reset 0.4 s in, so the server sees a real client disconnect.

Values come from /api/inference/monitor on the same Studio that was photographed.

Abandoned request Before After
Monitor status completed (green) cancelled (amber)
Completion tokens 400 of 400, stop reason length none, no stop reason
Duration 2.8 s 422 ms
Model held after the client left 2.59 s 0.27 s
Control request 200, completed 200, completed

PR 11961 before/after

Fixed during review (31cddbd42f): a non-streaming /v1/responses request goes through the same chat path, so after this PR it also stops on disconnect. Its outer monitor row still said completed for the partial answer, so it now records cancelled when the client has left. This comes with a regression test, which fails without the fix ('completed' == 'cancelled') and passes with it.

Checked, not a bug:

  • A request that finishes normally can't be marked cancelled. The watcher is stopped before the response is built, the same way /v1/messages already works.
  • After a cancel, the admission lease and the tracker are still released, including when the route is cancelled while the watcher is being stopped.
  • Durable chat runs always stream, so the new watchers never fire for them.

Tests:

  • The new test_non_streaming_gguf_disconnect_stops_generation passes 3/3 on head (plain, n=3, tools). On the merge base all 3 fail with "generation ran to completion after the client left", the right negative.
  • test_openai_tool_passthrough.py: 446 passed.
  • The /v1/responses, passthrough, API monitor and disconnect-watcher suites: 908 passed.
  • 21 dependent suites: 2230 passed. The one failure was a missing transformers in the test container, in a file this PR doesn't touch.

CI: upstream 3 pass, 41 still running, 0 failures. Staged on fresh main: NilayYadav/unsloth-staging#173 (17 runs queued).

@danielhanchen

Copy link
Copy Markdown
Member

Review record for #11961, carried over from the mirror it was reviewed on: danielhanchen/unsloth-staging-review#155.

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 3b5d593d64 (this PR's 31cddbd42)

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

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: 3b5d593d64

No triage reaction was recorded on the mirror

Verdict

The round converged at mirror 3b5d593d64 (this PR's 31cddbd42).

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

danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 27, 2026
@danielhanchen
danielhanchen merged commit b3f8ffe into unslothai:main Sep 27, 2026
50 of 57 checks passed
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…g request (unslothai#11961)

* Studio: stop non-streaming GGUF chat completions when the client disconnects

* Studio: record a disconnected non-streaming /v1/responses request as cancelled
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.

2 participants