Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Report what the model server actually said when a stream fails (#9390)

Daniel Han8d6728da7725
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 0b18745222c..77d253aec67 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -57,6 +57,7 @@ from core.inference.context_window import (
fit_rolling_context,
messages_have_media,
)
+from core.inference.stream_errors import stream_error_from_chunk
from core.inference.llama_server_args import (
_GPU_LAYER_FLAGS,
_LAYER_OFFLOAD_FLAGS,
@@ -22976,6 +22977,13 @@ class LlamaCppBackend:
_chunk_usage = data.get("usage")
if _chunk_usage:
_metadata_usage = _chunk_usage
+ # An error chunk carries no choices, so without this the loop
+ # ignored it and the reply ended with no finish_reason and no
+ # incomplete stamp: to the user, a mid-sentence stop for no
+ # stated reason. Raise so the failure is surfaced.
+ _stream_error = stream_error_from_chunk(data)
+ if _stream_error is not None:
+ raise _stream_error
choices = data.get("choices", [])
if choices:
delta = choices[0].get("delta", {})
@@ -23807,6 +23815,11 @@ class LlamaCppBackend:
if _cu:
_iter_usage = _cu
+ # See the note on the first stream loop: an error chunk has
+ # no choices, so `continue` below would drop it silently.
+ _stream_error = stream_error_from_chunk(chunk_data)
+ if _stream_error is not None:
+ raise _stream_error
choices = chunk_data.get("choices", [])
if not choices:
continue
@@ -25273,6 +25286,10 @@ class LlamaCppBackend:
_chunk_usage = chunk_data.get("usage")
if _chunk_usage:
_metadata_usage = _chunk_usage
+ # See the note on the first stream loop.
+ _stream_error = stream_error_from_chunk(chunk_data)
+ if _stream_error is not None:
+ raise _stream_error
choices = chunk_data.get("choices", [])
if choices:
delta = choices[0].get("delta", {})
diff --git a/studio/backend/core/inference/stream_errors.py b/studio/backend/core/inference/stream_errors.py
new file mode 100644
index 00000000000..27cf036de29
--- /dev/null
+++ b/studio/backend/core/inference/stream_errors.py
@@ -0,0 +1,163 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Turn a mid-stream llama-server error chunk into something the user can act on.
+
+llama-server can fail a request after the stream has already opened. It sends one
+``{"error": {"message": ...}}`` chunk and closes. Two callers read that stream and both
+handled it badly:
+
+- ``core.research_runs`` raised ``RuntimeError("Local model stream failed")``, discarding
+ whatever the server said. The user saw a generic failure with no cause and no remedy.
+- ``core.inference.llama_cpp``'s chat loops only ever read ``finish_reason`` out of
+ ``choices``. An error chunk carries no ``choices``, so nothing was recorded: the reply
+ was emitted with whatever text had accumulated and no ``incomplete`` stamp, which reads
+ to the user as the model stopping mid-sentence for no reason.
+
+The error worth naming is KV-cache exhaustion. With ``--parallel N --kv-unified``,
+llama.cpp allocates ONE cache of ``n_ctx`` tokens but reports ``n_ctx_slot = n_ctx`` to
+every slot, so N concurrent generations may each be admitted believing they own the whole
+window. When their combined length crosses it, the decode fails and llama.cpp kills every
+task involved, not just the one that tipped it over. Two chats running at once is enough.
+The server's own wording for that is "Context size has been exceeded", which sounds like
+the prompt was too long and sends the user off to shorten a conversation that was never
+the problem.
+"""
+
+from typing import Any, Optional
+
+# Two different failures share the word "context" and need different advice.
+#
+# Starvation: the decode could not find KV space because concurrent generations drew on
+# the same unified cache. Nothing about this request was too big, so telling the user to
+# shorten it is wrong. Matched on a substring because the server appends punctuation and,
+# on some paths, batch details.
+_STARVATION_MARKERS = (
+ "context size has been exceeded",
+ "failed to find free space in the kv cache",
+ "failed to find a memory slot",
+)
+
+# Oversize: the request alone did not fit, and the server says so precisely, including
+# both token counts. That text is kept verbatim; only the remedy is added.
+_OVERSIZE_MARKERS = (
+ "exceeds the available context size",
+ "exceeds the context size",
+)
+
+KV_STARVATION_MESSAGE = (
+ "The model ran out of context space while generating. This happens when several "
+ "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 "
+ "settings."
+)
+
+_OVERSIZE_HINT = "Raise the Context Length in Model settings, or shorten the request."
+
+_GENERIC_MESSAGE = "The model stopped generating early."
+
+
+class LlamaStreamError(RuntimeError):
+ """A mid-stream llama-server failure, carrying a message already fit to show.
+
+ Typed rather than a bare ``RuntimeError`` for two reasons, both in
+ ``routes/inference.py``:
+
+ - ``_friendly_error`` ends with ``return "An internal error occurred"`` for any
+ exception it does not recognise. A bare RuntimeError would have that message
+ swapped out on the chat path, so the cause would still never reach the user
+ even though it now survives the stream loop.
+ - ``_classify_llama_generation_error`` flags an overflow by substring, matching
+ "context" beside "window". The starvation text below says "context window"
+ while explaining that the window is shared, so it would be classified as
+ ``context_length_exceeded`` and set the client compacting a conversation that
+ was never too long. ``kv_starvation`` lets that path opt out explicitly.
+ """
+
+ def __init__(
+ self,
+ friendly: str,
+ *,
+ server_message: Optional[str] = None,
+ kv_starvation: bool = False,
+ context_oversize: bool = False,
+ ):
+ # str(exc) stays the server's own text where there is one, so the existing
+ # token-count regex in _friendly_error still matches an oversize refusal and
+ # rewrites it into the established "Message too long" wording.
+ super().__init__(server_message or friendly)
+ self.friendly = friendly
+ self.server_message = server_message
+ self.kv_starvation = kv_starvation
+ self.context_oversize = context_oversize
+
+
+def stream_error_from_chunk(chunk: Any) -> Optional[LlamaStreamError]:
+ """A raisable error for a streamed chunk, or None when the chunk is not one."""
+ message = error_message_from_chunk(chunk)
+ if message is None:
+ return None
+ starvation = is_kv_starvation(message)
+ return LlamaStreamError(
+ describe_stream_error(message),
+ server_message = message or None,
+ kv_starvation = starvation,
+ context_oversize = is_context_oversize(message),
+ )
+
+
+def error_message_from_chunk(chunk: Any) -> Optional[str]:
+ """The server's own error text from a streamed chunk, or None if it is not an error.
+
+ Accepts the two shapes llama-server emits: ``{"error": {"message": ...}}`` and a bare
+ ``{"error": "..."}``. A chunk carrying an ``error`` key with neither shape is still an
+ error, so it returns the empty string rather than None; only a non-error chunk is None.
+ """
+ if not isinstance(chunk, dict) or "error" not in chunk:
+ return None
+ error = chunk["error"]
+ if isinstance(error, str):
+ return error.strip()
+ if isinstance(error, dict):
+ message = error.get("message")
+ if isinstance(message, str):
+ return message.strip()
+ return ""
+
+
+def is_kv_starvation(message: Optional[str]) -> bool:
+ """Whether the error is the shared-KV starvation case rather than an oversize request."""
+ if not message:
+ return False
+ lowered = message.lower()
+ return any(marker in lowered for marker in _STARVATION_MARKERS)
+
+
+def is_context_oversize(message: Optional[str]) -> bool:
+ """Whether the server refused the request because it alone did not fit."""
+ if not message:
+ return False
+ lowered = message.lower()
+ return any(marker in lowered for marker in _OVERSIZE_MARKERS)
+
+
+def describe_stream_error(message: Optional[str], *, prefix: str = "") -> str:
+ """A user-facing sentence for a mid-stream failure.
+
+ Starvation gets the explanation above, because the server's own wording ("Context size
+ has been exceeded") reads as though the request was too long and sends the user off to
+ shorten a conversation that was never the problem. An oversize refusal already names
+ both token counts, so it is kept verbatim and only gains the remedy. Anything else is
+ passed through unchanged: it is the only information there is, and replacing it with a
+ fixed string is what made these undiagnosable. ``prefix`` names the caller ("Deep
+ Research") where the surrounding UI does not already.
+ """
+ if is_kv_starvation(message):
+ body = KV_STARVATION_MESSAGE
+ elif is_context_oversize(message):
+ body = f"{message.rstrip('. ')}. {_OVERSIZE_HINT}"
+ elif message:
+ body = message
+ else:
+ body = _GENERIC_MESSAGE
+ return f"{prefix}: {body}" if prefix else body
diff --git a/studio/backend/core/research_runs.py b/studio/backend/core/research_runs.py
index 1379fff7049..1952ecc7202 100644
--- a/studio/backend/core/research_runs.py
+++ b/studio/backend/core/research_runs.py
@@ -21,6 +21,7 @@ import httpx
from auth import storage as auth_storage
from core.inference.llama_admission import llama_admission_config_from_env
from core.inference.message_content import message_text_with_pastes
+from core.inference.stream_errors import stream_error_from_chunk
from core.inference.tool_loop_controller import is_tool_error, strip_result_for_model
from core.inference.tools import EMPTY_SEARCH_RESULTS, RAG_SOURCES_SENTINEL, execute_tool
from core.inference.web_access_policy import check_url_access, website_policy_prompt
@@ -231,7 +232,14 @@ def _safe_error(exc: BaseException) -> str:
return "Local model request timed out"
if isinstance(exc, httpx.HTTPStatusError):
return f"Local model request failed with HTTP {exc.response.status_code}"
- text = str(exc).replace("\n", " ").strip()
+ # str() on a stream error is deliberately the server's own text, so that the
+ # token-count regex in routes/inference.py still matches it. Deep Research has no
+ # such regex, so reading str() here showed the raw "Context size has been exceeded."
+ # and dropped the Model settings hint from an oversize refusal: the very case this
+ # exception was introduced to explain.
+ friendly = getattr(exc, "friendly", None)
+ text = friendly if isinstance(friendly, str) and friendly else str(exc)
+ text = text.replace("\n", " ").strip()
return (text or exc.__class__.__name__)[:_MAX_ERROR_CHARS]
@@ -1428,8 +1436,12 @@ class ResearchSupervisor:
continue
try:
chunk = json.loads(data)
- if isinstance(chunk, dict) and "error" in chunk:
- raise RuntimeError("Local model stream failed")
+ _stream_error = stream_error_from_chunk(chunk)
+ if _stream_error is not None:
+ # The server's own text names the cause and, for a context
+ # refusal, both token counts. Flattening it to a fixed
+ # string left the user with nothing to act on.
+ raise _stream_error
normalized_usage = _normalize_completion_usage(
chunk.get("usage") if isinstance(chunk, dict) else None
)
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index f44adf0eabc..345294fa050 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -64,6 +64,7 @@ from core.inference.context_window import (
estimate_messages_tokens as _estimate_messages_tokens,
truncate_oldest_messages as _truncate_oldest_messages,
)
+from core.inference.stream_errors import LlamaStreamError
from core.inference.orchestrator import (
AUDIO_GENERATION_MAX_TOKENS,
GenStreamError,
@@ -271,6 +272,13 @@ def _friendly_error(exc: Exception) -> str:
template_msg = _template_raise_message(msg, _loaded_chat_template())
if template_msg:
return f"An internal error occurred: {template_msg}"
+ # Placed after the token-count regex so an oversize refusal still gets the
+ # established "Message too long" wording, and before the catch-all so a
+ # mid-stream server failure is not flattened into "An internal error
+ # occurred". That flattening is what left these undiagnosable: the cause
+ # survived the stream loop and then died here.
+ if isinstance(exc, LlamaStreamError):
+ return exc.friendly
return "An internal error occurred"
@@ -1288,6 +1296,18 @@ def _classify_llama_generation_error(exc: Exception) -> Optional[bool]:
real client error from a genuine crash by the explicit "llama-server
returned 4xx" marker, not a bare "tokens"/"exceed" substring.
"""
+ # Decided before the substring test, which cannot tell these apart. KV
+ # starvation is a shared-cache capacity failure, not an overflow: the
+ # explanation says "context window" while making the point that the window is
+ # SHARED, so the heuristic below would read it as an overflow and set the
+ # client compacting a conversation that was never too long.
+ if isinstance(exc, LlamaStreamError):
+ # Only an oversize refusal is an overflow. Everything else stays None, which
+ # keeps it a 500: KV starvation is server capacity exhaustion and an in-band
+ # "tokenizer failed" carries no 4xx evidence at all, so returning False would
+ # emit a 400 and tell the client its own request was at fault, discouraging the
+ # retry that is actually the right response.
+ return True if exc.context_oversize else None
msg = str(exc)
msg_l = msg.lower()
if "n_ctx" in msg_l or (
diff --git a/studio/backend/tests/test_research_runs_hardening.py b/studio/backend/tests/test_research_runs_hardening.py
index 07dd9d05cd8..3b65893f3ad 100644
--- a/studio/backend/tests/test_research_runs_hardening.py
+++ b/studio/backend/tests/test_research_runs_hardening.py
@@ -1250,12 +1250,58 @@ def test_stream_completion_rejects_in_band_error_after_partial_report(monkeypatc
sent = _install_fake_client(monkeypatch, [_response(200, body = stream)])
supervisor = _make_supervisor(_noop_check_active)
- with pytest.raises(RuntimeError, match = "Local model stream failed"):
+ # The server's own text is the only account of the cause there is, so it is what the
+ # user must be shown. This used to be replaced with "Local model stream failed".
+ with pytest.raises(RuntimeError, match = "generation failed"):
_run_stream(supervisor)
assert len(sent) == 1
+def test_stream_completion_reports_an_oversize_context_refusal_with_its_counts(monkeypatch):
+ # Observed live: Deep Research sent 2358 tokens into a 2048 token window. The counts
+ # are what tell the user which setting to change and by how much.
+ error = json.dumps(
+ {
+ "error": {
+ "message": (
+ "request (2358 tokens) exceeds the available context size "
+ "(2048 tokens), try increasing it"
+ )
+ }
+ }
+ )
+ stream = f"data: {error}\n\ndata: [DONE]\n\n"
+ _install_fake_client(monkeypatch, [_response(200, body = stream)])
+ supervisor = _make_supervisor(_noop_check_active)
+
+ with pytest.raises(RuntimeError) as excinfo:
+ _run_stream(supervisor)
+
+ # .friendly, not str(): str stays the server's own text so the token-count regex in
+ # routes/inference.py still matches and rewrites it into the "Message too long" wording.
+ message = excinfo.value.friendly
+ assert "2358" in message and "2048" in message
+ assert "Context Length in Model settings" in message
+ assert excinfo.value.context_oversize
+
+
+def test_stream_completion_explains_a_shared_kv_starvation(monkeypatch):
+ # Observed live: two chats generating at once starved one unified KV cache and
+ # llama.cpp killed both. Neither request was too long, so the server's own wording
+ # would have misdirected the user.
+ error = json.dumps({"error": {"message": "Context size has been exceeded."}})
+ stream = f"data: {error}\n\ndata: [DONE]\n\n"
+ _install_fake_client(monkeypatch, [_response(200, body = stream)])
+ supervisor = _make_supervisor(_noop_check_active)
+
+ with pytest.raises(RuntimeError) as excinfo:
+ _run_stream(supervisor)
+
+ assert "at the same time" in excinfo.value.friendly
+ assert excinfo.value.kv_starvation
+
+
def test_stream_completion_timeout_is_absolute_despite_keepalives(monkeypatch):
state = {"iteratorClosed": False, "responseClosed": False}
diff --git a/studio/backend/tests/test_stream_errors.py b/studio/backend/tests/test_stream_errors.py
new file mode 100644
index 00000000000..47f2bccf4ec
--- /dev/null
+++ b/studio/backend/tests/test_stream_errors.py
@@ -0,0 +1,226 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""A mid-stream llama-server error must reach the user with its cause intact.
+
+The two failures these cover were both observed live against a model loaded at a 2048
+token context:
+
+- Two chats generating at once starved the shared unified KV cache. llama.cpp killed both
+ tasks with "Context size has been exceeded". The chat loop ignored the error chunk (it
+ carries no ``choices``) and the reply ended mid-code with no finish_reason, so no
+ continue bar rendered and auto-continue never fired.
+- Deep Research sent a 2358 token request into that 2048 token window. The server said so
+ precisely, naming both counts, and ``research_runs`` replaced it with "Local model
+ stream failed".
+"""
+
+from core.inference.stream_errors import (
+ KV_STARVATION_MESSAGE,
+ LlamaStreamError,
+ describe_stream_error,
+ error_message_from_chunk,
+ is_context_oversize,
+ is_kv_starvation,
+ stream_error_from_chunk,
+)
+
+
+class TestErrorMessageFromChunk:
+ def test_a_chunk_without_an_error_key_is_not_an_error(self):
+ assert error_message_from_chunk({"choices": [{"delta": {"content": "hi"}}]}) is None
+
+ def test_a_non_dict_chunk_is_not_an_error(self):
+ assert error_message_from_chunk("[DONE]") is None
+ assert error_message_from_chunk(None) is None
+
+ def test_the_nested_shape_yields_the_server_message(self):
+ chunk = {"error": {"message": "Context size has been exceeded.", "code": 500}}
+ assert error_message_from_chunk(chunk) == "Context size has been exceeded."
+
+ def test_the_bare_string_shape_yields_the_server_message(self):
+ assert error_message_from_chunk({"error": "boom"}) == "boom"
+
+ def test_an_unrecognised_error_shape_is_still_an_error(self):
+ # Empty string, not None: the caller must still fail the stream. Returning None
+ # here would restore the silent truncation this module exists to remove.
+ assert error_message_from_chunk({"error": {"code": 500}}) == ""
+
+
+class TestClassification:
+ def test_the_starvation_wordings_are_recognised(self):
+ for text in (
+ "Context size has been exceeded.",
+ "srv decode: failed to find free space in the KV cache, retrying",
+ "decode: failed to find a memory slot for batch of size 2",
+ ):
+ assert is_kv_starvation(text), text
+ assert not is_context_oversize(text), text
+
+ def test_an_oversize_refusal_is_not_read_as_starvation(self):
+ text = "request (2358 tokens) exceeds the available context size (2048 tokens), try increasing it"
+ assert is_context_oversize(text)
+ assert not is_kv_starvation(text)
+
+ def test_an_unrelated_error_is_neither(self):
+ assert not is_kv_starvation("tokenizer failed")
+ assert not is_context_oversize("tokenizer failed")
+
+ def test_empty_input_is_neither(self):
+ assert not is_kv_starvation(None) and not is_kv_starvation("")
+ assert not is_context_oversize(None) and not is_context_oversize("")
+
+
+class TestDescribeStreamError:
+ def test_starvation_explains_concurrency_rather_than_repeating_the_server(self):
+ described = describe_stream_error("Context size has been exceeded.")
+ assert described == KV_STARVATION_MESSAGE
+ # The server's own wording sends the user off to shorten a conversation that was
+ # never too long, so it must not be what they read.
+ assert "Context size has been exceeded" not in described
+ assert "at the same time" in described
+
+ def test_an_oversize_refusal_keeps_both_token_counts_and_gains_a_remedy(self):
+ described = describe_stream_error(
+ "request (2358 tokens) exceeds the available context size (2048 tokens), try increasing it"
+ )
+ assert "2358" in described and "2048" in described
+ assert "Context Length in Model settings" in described
+
+ def test_an_unrelated_error_is_passed_through_verbatim(self):
+ assert describe_stream_error("tokenizer failed") == "tokenizer failed"
+
+ def test_an_empty_error_still_says_something(self):
+ described = describe_stream_error("")
+ assert described and "stopped generating early" in described
+
+ def test_the_prefix_names_the_caller(self):
+ described = describe_stream_error("tokenizer failed", prefix = "Deep Research")
+ assert described == "Deep Research: tokenizer failed"
+
+ def test_no_outcome_is_the_old_fixed_string(self):
+ # The regression guard: whatever the input, the user must never be handed a
+ # message that discards the cause.
+ for text in ("Context size has been exceeded.", "tokenizer failed", ""):
+ assert "Local model stream failed" not in describe_stream_error(text)
+
+
+class TestSurvivesTheRouteLayer:
+ """Raising the right message is not enough: `routes/inference.py` rewrites it.
+
+ Both defects here were live. `_friendly_error` ends with a catch-all that
+ replaced any unrecognised exception with "An internal error occurred", so the
+ cause survived the stream loop and then died one layer up. And
+ `_classify_llama_generation_error` flags an overflow by finding "context" beside
+ "window", which the starvation text says while explaining that the window is
+ SHARED, so it was labelled `context_length_exceeded` and set the client
+ compacting a conversation that was never too long.
+ """
+
+ @staticmethod
+ def _routes():
+ import routes.inference as routes_inference
+ return routes_inference
+
+ def _error(self, message):
+ return stream_error_from_chunk({"error": {"message": message}})
+
+ def test_starvation_reaches_the_user_instead_of_an_internal_error(self):
+ routes = self._routes()
+ described = routes._friendly_error(self._error("Context size has been exceeded."))
+ assert described == KV_STARVATION_MESSAGE
+ assert "An internal error occurred" not in described
+
+ def test_starvation_is_not_classified_as_a_context_overflow(self):
+ # True would set the client compacting. False would emit a 400 and tell the
+ # client its own request was at fault, discouraging the retry that is the right
+ # response to server capacity exhaustion. None keeps it a 500.
+ routes = self._routes()
+ assert (
+ routes._classify_llama_generation_error(self._error("Context size has been exceeded."))
+ is None
+ )
+
+ def test_an_unrelated_failure_is_not_downgraded_to_a_client_error(self):
+ routes = self._routes()
+ assert routes._classify_llama_generation_error(self._error("tokenizer failed")) is None
+
+ def test_an_oversize_refusal_keeps_the_established_wording_and_triggers_compaction(self):
+ routes = self._routes()
+ error = self._error(
+ "request (2358 tokens) exceeds the available context size (2048 tokens), try increasing it"
+ )
+ described = routes._friendly_error(error)
+ assert described.startswith("Message too long: 2358 tokens")
+ assert "2048-token context window" in described
+ # An overflow genuinely is one, so the client should compact here.
+ assert routes._classify_llama_generation_error(error) is True
+
+ def test_an_unrelated_error_survives_verbatim(self):
+ routes = self._routes()
+ assert routes._friendly_error(self._error("tokenizer failed")) == "tokenizer failed"
+
+ def test_deep_research_shows_the_friendly_text_not_the_server_text(self):
+ """`_safe_error` reads str(exc), which is deliberately the server's own wording.
+ Reading it here showed the raw "Context size has been exceeded." on the very
+ path this exception was introduced to explain."""
+ from core.research_runs import _safe_error
+
+ assert _safe_error(self._error("Context size has been exceeded.")) == KV_STARVATION_MESSAGE
+ oversize = _safe_error(
+ self._error("request (2358 tokens) exceeds the available context size (2048 tokens)")
+ )
+ assert "2358" in oversize and "Context Length in Model settings" in oversize
+ # A plain exception still reads from str().
+ assert _safe_error(RuntimeError("plain")) == "plain"
+
+ def test_str_of_the_error_stays_the_server_text(self):
+ # What lets the existing token-count regex in _friendly_error still match.
+ error = self._error("request (10 tokens) exceeds the available context size (5 tokens)")
+ assert str(error).startswith("request (10 tokens)")
+
+ def test_the_typed_error_is_a_runtimeerror(self):
+ # Callers that already catch RuntimeError around the stream keep working.
+ assert isinstance(self._error("boom"), RuntimeError)
+ assert isinstance(self._error("boom"), LlamaStreamError)
+
+ def test_a_non_error_chunk_yields_no_exception(self):
+ assert stream_error_from_chunk({"choices": [{"delta": {"content": "hi"}}]}) is None
+
+
+class TestTheNonStreamingPathAlsoReportsTheCause:
+ """`stream=false` routes the same exception through `safe_error_detail`.
+
+ That helper exists to stop raw `str(error)` leaking paths, so it returns a fixed
+ fallback for anything it does not recognise. A curated `friendly` is written to be
+ shown, so it is exempt: without that, streaming clients got the cause and
+ non-streaming clients got "An internal error occurred", which is the same defect
+ this PR fixes, one layer further out.
+ """
+
+ def _error(self, message):
+ return stream_error_from_chunk({"error": {"message": message}})
+
+ def test_starvation_reaches_a_non_streaming_client(self):
+ from utils.utils import safe_error_detail
+ assert (
+ safe_error_detail(self._error("Context size has been exceeded."))
+ == KV_STARVATION_MESSAGE
+ )
+
+ def test_an_oversize_refusal_keeps_both_counts(self):
+ from utils.utils import safe_error_detail
+ detail = safe_error_detail(
+ self._error("request (2358 tokens) exceeds the available context size (2048 tokens)")
+ )
+ assert "2358" in detail and "2048" in detail
+
+ def test_an_ordinary_exception_is_still_generalised(self):
+ """The leak guard must keep working: only the curated message is exempt."""
+ from utils.utils import safe_error_detail
+
+ assert (
+ safe_error_detail(RuntimeError("/srv/secret/path blew up"))
+ == "An internal error occurred"
+ )
+ assert "/srv/secret" not in safe_error_detail(RuntimeError("/srv/secret/path blew up"))
diff --git a/studio/backend/utils/utils.py b/studio/backend/utils/utils.py
index 560a2e08076..feb592c0a42 100644
--- a/studio/backend/utils/utils.py
+++ b/studio/backend/utils/utils.py
@@ -599,6 +599,18 @@ def safe_error_detail(error: Exception, fallback: str = "An internal error occur
"""Map an exception to a generic, client-safe message (never raw
``str(error)``, which can leak paths). Log the real exception server-side.
"""
+ # A mid-stream llama-server failure carries a message that was written to be shown,
+ # so the leak this function guards against does not apply to it. Without this the
+ # non-streaming paths reduced it to the fallback while streaming clients got the
+ # cause, which is the same "reaches the user stripped of its reason" defect one layer
+ # further out. Imported lazily: utils is low level and must not depend on
+ # core.inference at import time.
+ try:
+ from core.inference.stream_errors import LlamaStreamError # noqa: PLC0415
+ if isinstance(error, LlamaStreamError) and error.friendly:
+ return error.friendly
+ except Exception: # noqa: BLE001 -- fall through to the generic mapping below
+ pass
text = str(error).lower()
if (
isinstance(error, (ConnectionError, TimeoutError))