Repository navigation
Studio: run llama-server with a per-launch API key by default - #13011
Conversation
llama-server answers with permissive CORS, so any web page the user has open could drive the loopback server and read /slots, /props and completions. Every launch now writes a random key to a 0600 file under the auth directory and passes --api-key-file; /health stays public. Every Studio request to llama-server already sent the backend's Bearer header except /v1/completions (stream and non-stream), /v1/embeddings, the Responses stream, the Anthropic passthrough (stream and non-stream) and the /metrics stats scrape. Those now send it too. UNSLOTH_LLAMA_SERVER_API_KEY=0 opts out (UNSLOTH_DIRECT_STREAM=1 still forces the key on). The key file is one per backend, rewritten on a relaunch and removed on unload, and the tool sandbox refuses the new suffixed name.
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 |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a891b2e1db
ℹ️ 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".
| def _llama_server_api_key_enabled() -> bool: | ||
| """Launch llama-server with a per-launch API key; UNSLOTH_LLAMA_SERVER_API_KEY=0 opts out unless direct streaming | ||
| (UNSLOTH_DIRECT_STREAM=1) needs the key.""" | ||
| return ( | ||
| os.getenv("UNSLOTH_DIRECT_STREAM", "0") == "1" | ||
| or os.getenv("UNSLOTH_LLAMA_SERVER_API_KEY", "1") != "0" |
There was a problem hiding this comment.
Protect the RAG embedding llama-server too
Apply this default-key policy to core/rag/embed_llama_server.py as well. Whenever the resolved RAG backend is llama-server, _build_cmd() still launches a dedicated server without --api-key-file and _post_active() sends no authorization header, so a web page can probe its loopback port and access endpoints such as /slots while document chunks are being embedded—the same exposure this change closes for chat and MTMD servers.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in ed20342: the RAG embed llama-server gets its own per-spawn key (file removed once healthy) and sends it on embeddings and /props. Real check with bge-small: embeddings work, keyless /slots and /v1/embeddings return 401, no key file left. Test added.
| if _llama_server_api_key_enabled(): | ||
| self._api_key = _secrets.token_urlsafe(32) | ||
| # Through a file, not argv: a command line is readable by every process of this Unix user, and the auth directory is not. | ||
| cmd.extend(["--api-key-file", str(_write_direct_stream_key(self._api_key))]) | ||
| logger.info("llama-server started with --api-key-file for direct streaming") | ||
| self._api_key_file = _write_direct_stream_key(self._api_key, self._api_key_file) | ||
| cmd.extend(["--api-key-file", str(self._api_key_file)]) |
There was a problem hiding this comment.
Probe custom binaries before requiring api-key-file
Gate this flag through the existing llama-server --help capability probe. Studio explicitly supports arbitrary binaries through LLAMA_SERVER_PATH, UNSLOTH_LLAMA_CPP_PATH, custom settings, and PATH, and the surrounding launcher already notes that an unknown option makes such a server exit immediately; because the key is now enabled by default, any otherwise-compatible custom build that predates --api-key-file can no longer load any GGUF model unless the operator discovers and sets the opt-out environment variable.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in ed20342: the --help capability probe now reports supports_api_key_file (fail open like --jinja), and a build whose help positively lacks it starts without a key and logs a warning. The RAG server uses the same check.
| # Path form only: the bare name is an ordinary identifier. auth.db is absent for the same reason, | ||
| # and Studio's copy is covered by the auth-directory patterns below. | ||
| + r"|[/\\]llama_api_key" | ||
| + r"|[/\\]llama_api_key(?:_\w+)?" |
There was a problem hiding this comment.
Reject basename searches for randomized key files
When server tools are enabled, this pattern still allows discovery commands such as find / -name 'llama_api_key_*' -exec cat {} +: the new regex requires a slash immediately before the basename, while the separate bare-basename check only triggers when the command also names the Studio root. Because the main server's live key file remains on disk until unload and tool subprocesses run as the same OS user, a tool can recover and expose the bearer key without triggering the credential guard; basename/glob searches for this prefix need to be classified as credential access too.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in ed20342: the credential guard matches the per-launch name bare and as a glob (find / -name 'llama_api_key_*'), not only after a slash. The unsuffixed name stays an ordinary identifier. Test added.
| with urllib.request.urlopen( | ||
| urllib.request.Request(self._url, headers = self._headers), timeout = 3 | ||
| ) as r: |
There was a problem hiding this comment.
Bypass ambient proxies for authenticated metrics scrapes
Use a proxy-disabled opener for this loopback request. urllib.request.urlopen() honors HTTP_PROXY, so when that variable is set and NO_PROXY does not include 127.0.0.1, every scrape forwards the newly added Authorization: Bearer … header to the ambient proxy instead of directly to llama-server; the other loopback clients in this repository explicitly use trust_env=False for this reason. Building an opener with ProxyHandler({}) (or using a proxy-disabled HTTP client) avoids disclosing the per-launch key.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in ed20342: the metrics scrape uses an opener with an empty ProxyHandler, so the bearer only goes to the loopback server. Test checks the opener.
…i-key-file, proxy-free metrics scrape, refuse key-file searches
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ed20342eb7
ℹ️ 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".
| ) | ||
|
|
||
| api_key = key_file = None | ||
| if _llama_server_api_key_enabled(): |
There was a problem hiding this comment.
Probe the MTMD binary before adding api-key-file
Gate the MTMD key flag with LlamaCppBackend.probe_server_capabilities() as the chat and RAG launchers do. find_llama_server_binary() uses the same resolver that accepts LLAMA_SERVER_PATH, UNSLOTH_LLAMA_CPP_PATH, and other custom binaries, but this new path unconditionally adds --api-key-file; an otherwise MTMD-capable custom build without that option exits immediately, making dictation unavailable unless the operator discovers the global key opt-out. Although the earlier custom-binary issue was fixed for the chat and RAG servers, this newly added MTMD launch remains ungated.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 9f1a3ff: the MTMD sidecar checks the same supports_api_key_file capability (fail open on a failed probe) and starts a build without the flag keyless, as before. Test added.
|
@codex review |
|
Codex Review: Didn't find any major issues. 🚀 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". |
|
@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". |
…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]>
Studio's llama-server children listen on a random 127.0.0.1 port and answer with permissive CORS. Without an API key, a web page the user has open can find the port and read
/slots(the prompts and replies of the current conversation),/props,/metricsand/tokenize, or run its own generations. Requests that need no CORS preflight reach it directly. The key existed only behindUNSLOTH_DIRECT_STREAM=1.Every load now starts llama-server with a random per-launch key, and every Studio request to it sends that key.
--api-key-file, never the command line. The file is0600in Studio's auth directory, one per backend, rewritten in place on a relaunch and removed on unload.UNSLOTH_LLAMA_SERVER_API_KEY=0turns the key off;UNSLOTH_DIRECT_STREAM=1still forces it on./v1/completions(stream and non-stream),/v1/embeddings, the Responses stream, and the/v1/messagespassthrough (stream, retry and non-stream) now share one header helper./metricsstats scrape now receives the key as well./props,/slotsand template calls already sent it through_auth_headers.--helpcapability probe now reports--api-key-file. A customLLAMA_SERVER_PATHbuild whose help lacks it starts without a key, as before, and logs a warning instead of failing to load. A failed probe still sends the flag, the same way--jinjais handled./props. The key file is deleted once the server is healthy.HTTP_PROXY.stt_mtmd_sidecar.pygets its own per-launch key. Its file is deleted once the server is ready, because llama-server reads the key only at startup.find / -name 'llama_api_key_*').Testing:
tests/test_llama_server_api_key_default.py:routes/inference.pysends the key.--api-key-file, the file is gone once the server is ready, and the transcription request sends the bearer.llama_extra_argslaunch-command tests now mask the per-launch key path, as they already mask the port. 117 passed together with the new tests./slots,/props,/tokenize,/metrics,/v1/chat/completionswithout the key (also withOrigin: https://evil.example)/health/v1/completions,/v1/embeddings,/v1/responses,/v1/messages(with tools), count_tokens,/props/v1/completions, Responses stream and/v1/messagestool passthrough fail withInvalid API Key(the header fixes above)/slotsand/v1/embeddingsreturn 401, and no key file is left on disk./healthturns 200 still answers 401 without the key and 200 with it.Performance: the key costs nothing measurable. Six alternating launches per arm, 20 requests each, same GPU and model, through Studio's
/v1/chat/completions: