Skip to content

Studio: follow up #9201 across non-streaming sibling paths - #9312

Merged
oobabooga merged 2 commits into
unslothai:mainfrom
oobabooga:fix/studio-nonstreaming-liveness-followups
Aug 19, 2026
Merged

oobabooga merged 2 commits into
unslothai:mainfrom
oobabooga:fix/studio-nonstreaming-liveness-followups

Conversation

@oobabooga

Copy link
Copy Markdown
Member

Follow-up to #9201.

Problem

#9201 moves non-streaming Anthropic generation off the event loop, fixing the watchdog failure in #8916. Two related blocking paths remain:

  • The Anthropic server-tool path collects events in a worker but reduces them on the event loop. Its cumulative tool-call sanitization becomes quadratic on long responses.
  • OpenAI safetensors and MLX generation, its tool-nudge retry, and audio-input generation still drain synchronous generators on the event loop.

Both can block health checks, disconnect handling, and unrelated API work during a long non-streaming request.

Fix

  • Run Anthropic collection and reduction as one worker unit.
  • Drain the OpenAI and audio-input generators in workers.
  • On cancellation, wait for the real worker before releasing generation tracking or llama admission.
  • Use a daemon worker for Anthropic server tools so a cancellation-resistant tool cannot extend process shutdown.
  • Rename the shared cleanup helper to _drain_pending_worker.

Streaming behavior is unchanged. Response content, error mapping, usage, nudge fallback, monitor state, and tool behavior are preserved.

Validation

  • python3 -m pytest -q studio/backend/tests/test_anthropic_messages.py studio/backend/tests/test_openai_tool_passthrough.py studio/backend/tests/test_tool_stream_generator_drain.py (409 passed)
  • python3 -m ruff check studio/backend/routes/inference.py studio/backend/tests/test_anthropic_messages.py studio/backend/tests/test_openai_tool_passthrough.py studio/backend/tests/test_tool_stream_generator_drain.py
  • python3 -m py_compile studio/backend/routes/inference.py studio/backend/tests/test_anthropic_messages.py studio/backend/tests/test_openai_tool_passthrough.py studio/backend/tests/test_tool_stream_generator_drain.py

@oobabooga

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 581c26c046

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@oobabooga
oobabooga merged commit 9a45830 into unslothai:main Aug 19, 2026
37 of 40 checks passed
Lyxot added a commit to Lyxot/unsloth that referenced this pull request Aug 20, 2026
Two conflicts, both from main's non-blocking generation work.

`routes/inference.py`: unslothai#9312 moved the non-streaming safetensors drain onto `_run_blocking_generation` so health checks stay responsive, while this branch had replaced the same drain with a per-choice `_one_choice` for `n > 1`. `_one_choice` is now async and drives main's `_drain_generate` through `_run_blocking_generation`, once per choice and once more for a nudge retry, so each sampled answer keeps its own seed and stats without holding the event loop.

`core/inference/llama_cpp.py`: main hoisted the streaming payload's `_reasoning_kwargs` call above the rolling-context preflight; the branch's `logit_bias` addition sits beside where it used to be. Kept main's hoist and dropped the duplicate assignment.
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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant