Repository navigation
Studio: reload without MTP when llama-server dies mid-generation on any MTP launch - #13316
Conversation
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@codex review |
|
@codex security review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4acff76ece
ℹ️ 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".
| t.join() | ||
| time.sleep(1.0) | ||
| # The control proves the hazard is real on this host. | ||
| assert procs["direct"].poll() is not None |
There was a problem hiding this comment.
Skip the control when PDEATHSIG is unavailable
On Linux hosts where PR_SET_PDEATHSIG is blocked by seccomp or prctl is otherwise unavailable, child_popen_kwargs() deliberately degrades without raising, so the directly spawned child remains alive and this assertion always fails. The skip condition currently checks only sys.platform; gate the test on _pdeathsig_available() or skip when the direct control remains alive so the suite remains runnable in restricted Linux containers.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 4d58739: gated on process_lifetime._pdeathsig_available(), as test_data_recipe_worker_lifetime.py does.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. You're on a roll. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
…drop tests that pass without the fix
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Delightful! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
… after recovering extras-owned MTP
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep it up! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
…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]>
Fixes #13253
Problem
Gemma 4 GGUFs turn on the MTP drafter in Auto. When llama-server passes
/healthwith the drafter attached and then dies on a decode (the report: Gemma 4 E2B on an 8 GB M2, every chat request returns 500), Studio respawns the exact same MTP launch, so every following request crashes again. The only way out was turning speculative decoding off by hand.Studio already has a fallback for this: when llama-server dies mid-generation it reloads once without speculative decoding, records
runtime_erroras the fallback reason, and keeps the requested mode so the UI shows why. That fallback was armed only for tensor-parallel launches, so a single-device Mac never got it.Changes
--split-mode tensor. The load-time decode probe stays tensor-only, so normal MTP loads get no extra work.spawn_on_lifetime_thread. On LinuxPR_SET_PDEATHSIGfires when the forking thread exits, and the MTP-free reload runs on a short-lived thread, so the replacement server was sent SIGTERM about 100 ms after it came up. The next request then respawned it once more and theruntime_errornotice was lost. macOS and Windows spawn exactly as before.--spec-typeextras, the requested mode is restored asNone, which is what the duplicate-load match expects. Before, an identical Apply looked like a new request and relaunched the crashing MTP.Trade-off: recovery keys on the process exiting, not on why. A llama-server killed from outside Studio (for example the OOM killer) on an MTP launch now comes back without speculative decoding until the next load, where before it was respawned with MTP. Deliberate unloads, model switches and Studio's own kills stop the watchdog first, so they are unaffected.
Evidence
Studio's real
LlamaCppBackendwith a real llama-server (b11541 CPU build),unsloth/gemma-4-E2B-it-GGUFUD-Q4_K_XL plusmtp-gemma-4-E2B-it.gguf, Auto mode. A SIGABRT is sent to a healthy draft-mtp server once it starts a task, matching "loads fine, dies on the first decode":exited (code -6); respawning, same MTP launch, crashes againauto+runtime_errorNew tests in
studio/backend/tests/test_mtp_runtime_fallback_any_launch.py: 5 pass on this branch; on main the two that pin the fix fail.Apple Silicon (staging CI,
macos-15andmacos-26, Apple M1 Virtual, 7 GB)Same backend comparison on macOS (Studio pins GGUF to the CPU there because the runner's Metal device is paravirtual), main vs this PR, same model, drafter and llama.cpp b11541:
runtime_error, modeautoThe new test file there: 4 passed, 1 skipped (the Linux-only PDEATHSIG test).
Raw llama-server with Gemma 4 E2B + MTP (
draft-mtpn=2 andngram-mod,draft-mtpn=3) on the b11160 and b11541 macOS builds served every request on these runners, but they show no layer offload, so they ran on the CPU and do not reproduce the reporter's M2 Metal crash. That crash itself is not reproduced here; this PR makes Studio recover from it instead of failing every request.