Skip to content

Studio: one owner for every request to llama-server, so a crashed server recovers on every API route - #15138

Merged
danielhanchen merged 9 commits into
unslothai:mainfrom
oobabooga:worktree-llama-upstream-one-owner
Oct 26, 2026
Merged

danielhanchen merged 9 commits into
unslothai:mainfrom
oobabooga:worktree-llama-upstream-one-owner

Conversation

@oobabooga

@oobabooga oobabooga commented Oct 24, 2026 •

Copy link
Copy Markdown
Member

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:

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 (Studio: reload without MTP when llama-server dies mid-generation on any MTP launch #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

@oobabooga

Copy link
Copy Markdown
Member Author

Reached Codex review convergence at oobabooga#412.

@danielhanchen

Copy link
Copy Markdown
Member

The Source lint failure here is the import-hoist verifier, and it comes from this PR's change to studio/backend/routes/inference.py:

=== studio/backend/routes/inference.py: BLOCKERS ===
  [BLOCKER] HOISTED-IMPORT-UNUSED 'nonstreaming_client' (['from:core.inference.llama_http:nonstreaming_client'])
            was used before, now unused (references re-pointed)

The non-streaming passthrough no longer calls nonstreaming_client, but the module-level import is still there. Removing the import (or using it again, if dropping the call was a mistake) clears it. The "Would reformat" and codespell output above it in the log is informational and is the same on main.

@danielhanchen

Copy link
Copy Markdown
Member

One more from this PR's latest run, (Python 3.13, g-r): the new tests/test_llama_upstream_single_owner.py::test_streams_emit_keepalives_before_a_slow_reload_finishes[chat-stream] fails (assert not True from drain, line 329, called from _chat_stream). The file is new in this PR and isn't on main, so it is either a real gap in the chat-stream keepalive path or a timing assumption in the test's slow-reload stand-in. It is worth running in a loop under -n 4 alongside the rest of the shard.

@danielhanchen

Copy link
Copy Markdown
Member

The latest (Python 3.13, a-f) run here has two failures that come from this branch: studio/backend/tests/test_active_generations.py::test_completions_proxy_non_stream_is_visible_to_the_swap_gate and ::test_embeddings_proxy_is_visible_to_the_swap_gate both stop at

AttributeError: <module 'routes.inference' ...> has no attribute 'nonstreaming_client'

They monkeypatch routes.inference.nonstreaming_client (lines 1254 and 1325), which this PR removes from that module. They need to patch whatever now hands out the non-streaming client for the completions and embeddings proxies, so the swap-gate assertions still run against the new single owner. The other reds on this run (the Run settings footer test and test_single_row_cached_attention on the Core legs) are from main and are fixed by #15181 and #15182.

@danielhanchen danielhanchen self-assigned this Oct 26, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-26T11:31:48.640593Z
We couldn’t complete this review. Comment @codex review to try again.
714f458 Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Something went wrong. Try again later by commenting “@codex review”.

An unknown error occurred
ℹ️ 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".

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Something went wrong. Try again later by commenting “@codex review”.

An unknown error occurred
ℹ️ 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".

@danielhanchen
danielhanchen merged commit c74438a into unslothai:main Oct 26, 2026
6 of 53 checks passed
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.

2 participants