Repository navigation
Report what the model server actually said when a stream fails - #9390
Conversation
A mid-stream error from llama-server reached the user with its cause stripped
out, on both paths that read that stream.
Deep Research raised RuntimeError("Local model stream failed") for any chunk
carrying an "error" key. Observed live against a model loaded at a 2048 token
context, the server had said:
request (2358 tokens) exceeds the available context size (2048 tokens),
try increasing it
which names both counts and the remedy. All of it was discarded and the user
was shown a generic failure with nothing to act on.
The chat loops in llama_cpp.py were worse: they only ever read finish_reason
out of choices, and an error chunk carries no choices, so the error was
skipped entirely. The reply was emitted with whatever text had accumulated and
no finish_reason, which means no incomplete stamp, no continue bar and no
auto-continue. To the user the model simply stopped mid-sentence for no stated
reason.
Adds core/inference/stream_errors.py, used by both paths so one failure reads
the same in each, and separates the two errors that share the word "context"
because they need opposite advice:
- KV starvation ("Context size has been exceeded") is explained rather than
repeated. With --parallel N --kv-unified, llama.cpp allocates one cache of
n_ctx but reports n_ctx_slot = n_ctx to every slot, so concurrent
generations can each be admitted believing they own the whole window; when
their combined length crosses it the decode fails and every task involved is
killed. Nothing about either request was too long, so the server's own
wording sends the user off to shorten a conversation that was never the
problem. Two chats at once is enough to trigger it.
- An oversize refusal already states both token counts, so it is kept verbatim
and only gains a pointer to the Context Length setting.
- Anything else is passed through unchanged. Replacing the server's text with
a fixed string is what made these undiagnosable.
The three chat stream loops now fail the stream on an error chunk instead of
ignoring it, so the failure is surfaced rather than read as a silent stop.
Tests: 15 unit tests over classification and rendering, plus integration tests
built from both real error strings and a guard that no input can produce the
old fixed string. The existing in-band error test asserted that fixed string
and now asserts the cause survives.
The message was raised correctly and then rewritten one layer up, so a chat user still learned nothing. routes/inference.py::_friendly_error ends with `return "An internal error occurred"` for anything it does not recognise. The KV starvation text matches neither the token-count regex nor the lost-connection check, so it fell straight through that catch-all. The backend unit tests passed because they exercised the helper, not the route. Worse, _classify_llama_generation_error flags a context overflow by finding "context" beside "window". The explanation says "they share one context window" while making the point that the window is SHARED, so starvation was being labelled context_length_exceeded, which sets the client compacting a conversation that was never too long. Adds a typed LlamaStreamError carrying friendly, kv_starvation and context_oversize. str(exc) stays the server's own text, so the existing token-count regex still matches an oversize refusal and rewrites it into the established "Message too long" wording rather than a longer duplicate. _friendly_error returns exc.friendly after that regex and before the catch-all; _classify_llama_generation_error decides from the flag before the substring test. Subclassing RuntimeError keeps every existing `except RuntimeError` around these streams working. Verified through the route layer rather than the helper: - starvation -> the concurrency explanation, classify False - request (2358 tokens) exceeds the available context size (2048 tokens) -> "Message too long: 2358 tokens exceeds the 2048-token context window", classify True - anything else -> verbatim, classify False Tests: a TestSurvivesTheRouteLayer class covering all three plus the RuntimeError subclassing, since testing the helper alone is what let this through. The two research tests now assert on .friendly, because str() is deliberately the server's text.
|
Codex Review: Didn't find any major issues. Hooray! 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". |
…acity failures Two follow-ups from review, the first of which broke the case this PR exists for. _safe_error in core/research_runs.py reads str(exc), and str() on a stream error is deliberately the server's own text so the token-count regex in routes/inference.py still matches it. Deep Research has no such regex, so it showed the raw "Context size has been exceeded." and an oversize refusal lost the Model settings hint: the friendly rendering only ever reached the routes path. _safe_error now prefers .friendly when it is present and falls back to str() otherwise, so a plain exception is unchanged. _classify_llama_generation_error returned False for every typed stream failure that was not an oversize refusal. False is read as an upstream 4xx and emits a 400, which tells the client its own request was at fault. KV starvation is server capacity exhaustion and a retry is the right response, so a 400 discourages the one thing that would work, and an in-band "tokenizer failed" carries no 4xx evidence at all. Only context_oversize returns True now; everything else returns None and stays a 500. The message is unaffected either way, since _friendly_error reads .friendly independently of the classification.
With stream=false the same exception routes through safe_error_detail, which returns a fixed fallback for anything it does not recognise, so a KV starvation or other in-band failure reached the client as "An internal error occurred" while streaming clients got the cause. That is the defect this PR fixes, one layer further out. safe_error_detail exists to stop raw str(error) leaking paths. A curated friendly message is written to be shown, so it is exempt; everything else still goes through the generic mapping, and an ordinary exception is still reduced to the fallback. The import is local because utils is low level and must not depend on core.inference at import time. Tests assert the starvation explanation and both token counts reach a non-streaming client, and that an exception carrying a path is still generalised.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ee7a23ea0c
ℹ️ 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".
| elif message: | ||
| body = message |
There was a problem hiding this comment.
Sanitize unknown server error text before returning it
When llama-server emits any error outside the two recognized context cases, this branch treats its arbitrary message as client-safe and returns it verbatim through _friendly_error, Deep Research, and the new safe_error_detail exemption. Server-side exceptions can contain filesystem paths or other implementation details—the information that safe_error_detail explicitly prevents leaking—so an inference API caller can receive internal data whenever such an exception reaches an in-band error chunk. Preserve the actionable known messages, but redact or generalize unrecognized server text rather than automatically marking every stream error as public.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. I went and read what llama-server can actually put in an in-band error chunk on a chat path, in tools/server/server-context.cpp on master, and it is a closed set of fixed English diagnostics plus integers:
- :3643 the KV-starvation broadcast, "Context size has been exceeded.", sent to every processing slot
- :3115 / :3126 / :3137 the three token-count refusals, string_format over n_tokens and n_ctx
- :2846 / :2858 context shift disabled or unusable, :3108 logits, :3430 failed to process mtmd chunk, :3630 invalid input batch, :3635 compute error
The only two path-bearing messages in the whole server are "Unable to restore slot: " (:2572) and the model load and download errors. Neither is a chat completion task, so neither reaches the three loops this PR touches, and all three insertion points read self.base_url, meaning local llama-server only.
The bigger reason is that verbatim is already the deliberate policy here, not something this PR introduces. _openai_passthrough_error at routes/inference.py:310 returns f"llama-server error: {text}" and says so in its docstring, and _friendly_gen_stream_error at :285 exempts GenStreamError from safe_error_detail through the same public flag. What safe_error_detail is actually guarding is str(error) on a Python exception raised inside Studio, something like a FileNotFoundError carrying a local path. LlamaStreamError.friendly is never that.
And redacting the unrecognized branch would undo the point. That branch is the whole reason the PR exists: an unrecognized message is the only information there is, and replacing it with a fixed string is exactly what made these failures undiagnosable, which is also what your other item on this PR was about. Happy to reconsider if you can name a specific chat-path message that carries an internal detail.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: edfb5cd87e
ℹ️ 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".
| "chats or research runs generate at the same time, because they share one context " | ||
| "window. Try again with fewer running at once, or raise the Context Length in Model " |
There was a problem hiding this comment.
Avoid classifying KV starvation as a context-limit error
When this starvation message reaches the Studio chat client, its "context window" substring matches isContextLimitError() in chat-adapter.ts, which then displays the “Context limit reached” toast claiming that the conversation filled the window. This defeats the new backend-side distinction and gives contradictory advice precisely when concurrent generations exhaust the shared KV cache; use wording that does not trigger the existing context-limit heuristic, or update that client predicate to distinguish this typed starvation failure.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed, and it is a real one: the user is shown confident, specific, wrong advice.
KV_STARVATION_MESSAGE said "because they share one context window", and chat-adapter.ts::isContextLimitError matches on substrings, one of which is literally "context window":
m.includes("context size") || m.includes("context shift") ||
m.includes("exceeds the available context") || m.includes("message too long") ||
m.includes("context window") || (m.includes("n_ctx") && (...))
So the client re-labels it "Context limit reached" and, in the no-truncation case that starvation always is, tells the user the conversation has filled the window and to shorten it or start a new chat. Starting a new chat is the worst available move: nothing about the conversation was too long, and a new chat fails identically for as long as the other generation is running. That is this PR's own defect reintroduced one layer out.
The code cannot rescue it either. _classify_llama_generation_error correctly returns None for starvation, so the chunk carries no code, and chat-api.ts rethrows an in-band error as new Error(parsed.error.message). The text is all the client sees.
Fix is to reword rather than to loosen the client predicate, which is doing its job for the cases it was written for: "because they all draw on one shared pool of context". Context Length is kept, since it names the actual setting and is not one of the markers. Verified the new text hits none of them.
I also corrected the LlamaStreamError docstring, which cited the old "context window" phrasing as the reason kv_starvation opts out of the backend classifier. The opt-out is still needed, since that heuristic matches "context" beside "length", but the rationale no longer described the text.
The regression test mirrors the client's marker list and also asserts the raw llama-server wording WOULD have matched, so it cannot pass vacuously if the list is ever emptied. 193 passed.
Merged already, so it is in #9417.
A mid-stream error from llama-server reached the user with its cause stripped out, on both paths that read that stream.
Deep Research
core/research_runs.pyraisedRuntimeError("Local model stream failed")for any chunk carrying anerrorkey. Observed live against a model loaded at a 2048 token context, the server had said:That names both counts and the remedy. All of it was discarded, and the user was shown a generic failure with nothing to act on.
Chat
The three stream loops in
core/inference/llama_cpp.pyonly ever readfinish_reasonout ofchoices. An error chunk carries nochoices, so the error was skipped entirely: the reply was emitted with whatever text had accumulated and nofinish_reason, which means no incomplete stamp, no continue bar and no auto-continue. To the user, the model stopped mid-sentence for no stated reason.This was reproduced live. Two chats generating at once starved the shared KV cache, llama.cpp killed both tasks, and all four assistant messages in the affected thread were persisted mid-code with an empty metadata
customblock.Change
Adds
core/inference/stream_errors.py, used by both paths so one failure reads the same in each. It separates the two errors that share the word "context", because they need opposite advice.KV starvation (
Context size has been exceeded) is explained rather than repeated. With--parallel N --kv-unified, llama.cpp allocates one cache ofn_ctxbut reportsn_ctx_slot = n_ctxto every slot, so concurrent generations can each be admitted believing they own the whole window. When their combined length crosses it, the decode fails and every task involved is killed:565 + 1485 = 2050 against a 2048 cache,
truncated = 0on both. Neither request was too long on its own, so the server's own wording sends the user off to shorten a conversation that was never the problem. Two chats at once is enough.An oversize refusal already states both token counts, so it is kept verbatim and only gains a pointer to the Context Length setting.
Anything else is passed through unchanged. Replacing the server's text with a fixed string is what made these undiagnosable in the first place.
The three chat stream loops now fail the stream on an error chunk instead of ignoring it, so the failure surfaces through the existing error handling rather than reading as a silent stop.
Scope
This reports the failure honestly, it does not prevent it. The underlying overcommit is that
core/inference/llama_admission.pygates concurrency on slot count alone, with no accounting of the shared KV budget, so N generations are admitted against a cache that can hold fewer. That fix touches every request path and follows separately.Tests
tests/test_stream_errors.py, 15 new tests over chunk parsing, classification and rendering, including a guard that no input can produce the old fixed string.tests/test_research_runs_hardening.pygains two integration tests built from the real error strings above. The existing in-band error test asserted the old fixed string and now asserts the cause survives; its failure before the update wasExpected regex: 'Local model stream failed'againstActual message: 'generation failed'.checkpointkeyword happens to match, and they fail identically on an untouched tree.