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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
fix(studio): recover from a dead Metal GPU queue instead of failing every later request (#11383)
Long Yixing8d15d04b5f58
diff --git a/studio/backend/core/inference/mlx_inference.py b/studio/backend/core/inference/mlx_inference.pyindex 0762d3a80b6..ef1e5bf1d3a 100644--- a/studio/backend/core/inference/mlx_inference.py+++ b/studio/backend/core/inference/mlx_inference.py@@ -51,6 +51,7 @@ from core.inference.mcp_images import (trim_image_turns,)from utils.models.model_config import is_audio_input_type+from utils.utils import is_metal_queue_deadfrom loggers import get_loggerlogger = get_logger(__name__)@@ -601,7 +602,7 @@ def _mlx_inference_patch(name):def _mlx_optional_fusion(name, model):"""Hold an optional Zoo fusion scope, or yield the model unfused. Guard ENTRY only:an open scope must unwind through the ExitStack as an unguarded `with` would, or an- interrupted generation stops restoring the module tree."""+ interrupted generation stops restoring the module tree. A dead Metal queue is not guarded."""patch = _mlx_inference_patch(name)with ExitStack() as scope:active = model@@ -609,6 +610,8 @@ def _mlx_optional_fusion(name, model):try:entered = scope.enter_context(patch(model))except Exception as error:+ if is_metal_queue_dead(error):+ raise_mlx_fusion_unavailable(name, error)else:if entered is not None:diff --git a/studio/backend/core/inference/orchestrator.py b/studio/backend/core/inference/orchestrator.pyindex 64ae394fe37..bf5366210bc 100644--- a/studio/backend/core/inference/orchestrator.py+++ b/studio/backend/core/inference/orchestrator.py@@ -29,7 +29,7 @@ from core.inference.audio_errors import (AudioGenerationCancelledError,)from utils.hardware import get_device, prepare_gpu_selection-from utils.utils import hf_env_offline+from utils.utils import hf_env_offline, is_metal_queue_dead# Re-exported from the shared helper so GGUF, training and inference share one type. Via PEP 562, not a module-level# import: resolving the name imports unsloth_zoo, hence torch, and routes/inference.py imports this module at startup@@ -175,6 +175,12 @@ def _redact_worker_output(text: str) -> str:return _ABSOLUTE_PATH_RE.sub(_shorten_path, redacted)+class _WorkerMailbox(queue.Queue):+ def __init__(self, worker):+ super().__init__()+ self.worker = worker++class _LoadCancelled(Exception):"""Internal control flow for a caller-cancelled model load."""@@ -991,6 +997,31 @@ class InferenceOrchestrator:def _ensure_subprocess_alive(self) -> bool:return self._proc is not None and self._proc.is_alive()+ def _observe_response(self, resp, worker):+ """Retire ``worker`` if its Metal queue is dead; nothing else reaps it."""+ detail = resp.get("error") or ""+ if worker is None or not is_metal_queue_dead(detail):+ return resp+ with self._subprocess_shutdown_lock:+ if self._proc is not worker:+ return resp+ logger.error("Retiring the inference worker: its GPU queue is dead (%s)", detail)+ if self._shutdown_subprocess_locked(5): # a survivor still holds the model+ self.active_model_name = None+ self.models.clear()+ return resp++ def _observe_off_thread(self, resp, worker) -> None:+ """Off the dispatcher thread because retiring joins it."""+ if worker is None or not is_metal_queue_dead(resp.get("error") or ""):+ return+ threading.Thread(+ target = self._observe_response,+ args = (resp, worker),+ daemon = True,+ name = "inference-retire-worker",+ ).start()+def _subprocess_crash_message(self,context: str,@@ -1053,12 +1084,27 @@ class InferenceOrchestrator:except (OSError, ValueError) as exc:raise RuntimeError(f"Failed to send command to subprocess: {exc}")- def _read_resp(self, timeout: float = 1.0) -> Optional[dict]:- """Read a response from the subprocess (non-blocking with timeout)."""- if self._resp_queue is None:+ def _read_mailbox(+ self,+ mailbox: _WorkerMailbox,+ timeout: Optional[float] = None,+ ):+ resp = mailbox.get_nowait() if timeout is None else mailbox.get(timeout = timeout)+ return self._observe_response(resp, mailbox.worker)++ def _read_resp(+ self,+ timeout: float = 1.0,+ observe: bool = True,+ ) -> Optional[dict]:+ # Handle before queue, else a reload between them blames the replacement.+ worker = self._proc+ resp_queue = self._resp_queue+ if resp_queue is None:return Nonetry:- return self._resp_queue.get(timeout = timeout)+ resp = resp_queue.get(timeout = timeout)+ return self._observe_response(resp, worker) if observe else respexcept queue.Empty:return Noneexcept (EOFError, OSError, ValueError):@@ -1152,22 +1198,23 @@ class InferenceOrchestrator:Returns (read_one, drain, release)."""- mailbox: queue.Queue = queue.Queue()+ mailbox = _WorkerMailbox(self._proc)with self._mailbox_lock:self._direct_mailboxes[request_id] = mailboxdef read_one(timeout: float = 1.0):try:- return mailbox.get_nowait()+ return self._read_mailbox(mailbox)except queue.Empty:passthread = self._dispatcher_threadif thread is not None and thread.is_alive():try:- return mailbox.get(timeout = timeout)+ return self._read_mailbox(mailbox, timeout)except queue.Empty:return None- resp = self._read_resp(timeout = timeout)+ worker = self._proc # handle before queue, as in _read_resp+ resp = self._read_resp(timeout = timeout, observe = False)if resp is None:return Nonerid = resp.get("request_id")@@ -1182,9 +1229,11 @@ class InferenceOrchestrator:else:self._mark_worker_started(owner)other.put(resp)+ # Observe only after hand-over: retiring clears the registry.+ self._observe_response(resp, worker)# Outside the mailbox check on purpose: a released request's late frames go to nobody.return None- return resp+ return self._observe_response(resp, worker)def drain(timeout: float = 5.0) -> bool:deadline = time.monotonic() + timeout@@ -1416,6 +1465,7 @@ class InferenceOrchestrator:if self._resp_queue is None:break+ worker = self._proc # handle before queue, as in _read_resptry:resp = self._resp_queue.get(timeout = _DISPATCH_POLL_INTERVAL)except queue.Empty:@@ -1434,6 +1484,7 @@ class InferenceOrchestrator:continue# Route to mailbox if a matching request_id exists+ delivered = Falseif rid:with self._mailbox_lock:mbox = self._mailboxes.get(rid) or self._direct_mailboxes.get(rid)@@ -1448,13 +1499,16 @@ class InferenceOrchestrator:else:self._mark_worker_started(owner)mbox.put(resp)- continue+ delivered = True- logger.debug(- "Dispatcher: no mailbox for request_id=%s type=%s, dropping",- rid,- rtype,- )+ if not delivered:+ logger.debug(+ "Dispatcher: no mailbox for request_id=%s type=%s, dropping",+ rid,+ rtype,+ )+ # Every response: an abandoned mailbox is never read.+ self._observe_off_thread(resp, worker)except Exception:logger.exception("Inference dispatcher: failed to route a response; continuing")continue@@ -1553,7 +1607,7 @@ class InferenceOrchestrator:video_b64 = video,)- mailbox: queue.Queue = queue.Queue()+ mailbox = _WorkerMailbox(self._proc)with self._mailbox_lock:# _unload_pending alone is not enough: an unload that ran fully since _start_dispatcher clears it in its# finally and stops the dispatcher, so it reads False here though the dispatcher is gone and the model@@ -1613,7 +1667,7 @@ class InferenceOrchestrator:def read_mailbox(timeout):try:- return mailbox.get(timeout = timeout)+ return self._read_mailbox(mailbox, timeout)except queue.Empty:return None@@ -1637,15 +1691,15 @@ class InferenceOrchestrator:def _drain_mailbox(self,- mailbox: queue.Queue,+ mailbox: _WorkerMailbox,timeout: float = 5.0,) -> None:"""Drain a mailbox until gen_done/gen_error, discarding tokens."""deadline = time.monotonic() + timeoutwhile time.monotonic() < deadline:try:- resp = mailbox.get(- timeout = min(_DISPATCH_POLL_INTERVAL, deadline - time.monotonic())+ resp = self._read_mailbox(+ mailbox, min(_DISPATCH_POLL_INTERVAL, deadline - time.monotonic()))except queue.Empty:continuediff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 3a72c08685e..8fbceab5525 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -335,6 +335,7 @@ def _friendly_gen_stream_error(value) -> str:text = str(value)if getattr(value, "public", False):return text+ logger.error("Local generation failed: %s", text)return safe_error_detail(RuntimeError(text), fallback = "An internal error occurred.")diff --git a/studio/backend/tests/test_audio_tts_cancellation.py b/studio/backend/tests/test_audio_tts_cancellation.pyindex ef19f1ec313..25aa74f3205 100644--- a/studio/backend/tests/test_audio_tts_cancellation.py+++ b/studio/backend/tests/test_audio_tts_cancellation.py@@ -86,6 +86,7 @@ def _bare_orchestrator():orchestrator._dispatcher_thread = Noneorchestrator._dispatcher_stop = threading.Event()orchestrator._dispatcher_lifecycle_lock = threading.Lock()+ orchestrator._subprocess_shutdown_lock = threading.Lock()orchestrator._mailbox_lock = threading.Lock()orchestrator._mailboxes = {}orchestrator._direct_mailboxes = {}@@ -234,6 +235,77 @@ def test_audio_response_cancellation_signals_worker_and_drains_terminal_responseassert orchestrator._executing_cancel_events == []+_GPU_TIMEOUT = (+ "[METAL] Command buffer execution failed: Caused GPU Timeout Error "+ "(00000002:kIOGPUCommandBufferCallbackErrorTimeout)"+)+++class _WorkerQueue:+ def __init__(self, sent, *steps):+ self._sent = sent+ self._steps = list(steps)++ def get(self, timeout = None):+ if not self._steps:+ raise queue.Empty+ step = self._steps.pop(0)+ resp = step() if callable(step) else step+ if resp is None:+ raise queue.Empty+ return {**resp, "request_id": self._sent[0]["request_id"]}+++def _watch_teardown(orchestrator, monkeypatch):+ torn_down = []++ def shutdown(timeout):+ torn_down.append(timeout)+ orchestrator._proc = None+ return True++ monkeypatch.setattr(orchestrator, "_shutdown_subprocess_locked", shutdown)+ return torn_down++[email protected]("rtype", ["audio_error", "error"])+def test_a_dead_gpu_queue_during_audio_generation_retires_the_worker(rtype, monkeypatch):+ orchestrator = _bare_orchestrator()+ monkeypatch.setattr(orchestrator, "_ensure_subprocess_alive", lambda: True)+ sent = []+ monkeypatch.setattr(orchestrator, "_send_cmd", lambda cmd: sent.append(cmd))+ torn_down = _watch_teardown(orchestrator, monkeypatch)+ orchestrator._resp_queue = _WorkerQueue(sent, {"type": rtype, "error": _GPU_TIMEOUT})++ with pytest.raises(RuntimeError, match = "GPU Timeout"):+ orchestrator.generate_audio_response("hello")++ assert torn_down, "a dead GPU queue must retire the worker"+ assert orchestrator.active_model_name is None+ assert orchestrator.models == {}+++def test_a_cancelled_audio_request_still_retires_the_poisoned_worker(monkeypatch):+ orchestrator = _bare_orchestrator()+ monkeypatch.setattr(orchestrator, "_ensure_subprocess_alive", lambda: True)+ sent = []+ monkeypatch.setattr(orchestrator, "_send_cmd", lambda cmd: sent.append(cmd))+ torn_down = _watch_teardown(orchestrator, monkeypatch)+ caller_cancel = threading.Event()+ orchestrator._resp_queue = _WorkerQueue(+ sent,+ {"type": "audio_started"},+ caller_cancel.set,+ {"type": "audio_error", "error": _GPU_TIMEOUT},+ )++ with pytest.raises(RuntimeError, match = "cancel"):+ orchestrator.generate_audio_response("hello", cancel_event = caller_cancel)++ assert torn_down+ assert orchestrator.active_model_name is None++def test_audio_response_cancellation_bounds_an_unresponsive_worker(monkeypatch):orchestrator = _bare_orchestrator()monkeypatch.setattr(orchestrator, "_ensure_subprocess_alive", lambda: True)diff --git a/studio/backend/tests/test_inference_dispatcher_resilience.py b/studio/backend/tests/test_inference_dispatcher_resilience.pyindex 5318580f84f..00172e6a0de 100644--- a/studio/backend/tests/test_inference_dispatcher_resilience.py+++ b/studio/backend/tests/test_inference_dispatcher_resilience.py@@ -41,7 +41,9 @@ def _dispatcher():o._dispatcher_stop = threading.Event()o._mailbox_lock = threading.Lock()o._mailboxes = {}+ o._direct_mailboxes = {}o._request_cancel_events = {}+ o._proc = None # no worker, so no routed response retires anythingreturn o@@ -134,6 +136,7 @@ def _direct_reader_host():o._active_cancel_events = []o._executing_cancel_events = []o._dispatcher_thread = None+ o._proc = None # no worker, so no read retires anythingreturn o@@ -184,7 +187,7 @@ def test_rerouting_a_foreign_gen_done_retires_that_request():def _direct_reader_calls(o, request_id):"""_direct_reader wired to a scripted _read_resp (o._scripted, popped in order)."""- o._read_resp = lambda timeout = 1.0: o._scripted.pop(0) if o._scripted else None+ o._read_resp = lambda timeout = 1.0, observe = True: (o._scripted.pop(0) if o._scripted else None)return o._direct_reader(request_id)diff --git a/studio/backend/tests/test_local_generation_error_is_logged.py b/studio/backend/tests/test_local_generation_error_is_logged.pynew file mode 100644index 00000000000..2051c4ba1db--- /dev/null+++ b/studio/backend/tests/test_local_generation_error_is_logged.py@@ -0,0 +1,46 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++from __future__ import annotations++import sys+from pathlib import Path+from types import SimpleNamespace++import pytest++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++from core.inference.orchestrator import GenStreamErrorRaised # noqa: E402+from routes.inference import _friendly_gen_stream_error # noqa: E402+++def logged(monkeypatch):+ lines = []+ monkeypatch.setattr(+ "routes.inference.logger",+ SimpleNamespace(error = lambda fmt, *args: lines.append(fmt % args)),+ )+ return lines+++def test_a_flattened_failure_leaves_the_cause_behind(logged):+ cause = "Error: [METAL] Command buffer execution failed: Caused GPU Timeout Error."+ assert _friendly_gen_stream_error(GenStreamErrorRaised(cause)) == (+ "The GPU stopped responding. Reload the model to recover."+ )+ assert logged == [f"Local generation failed: {cause}"]+++def test_an_unrecognised_failure_is_logged_even_though_the_client_learns_nothing(logged):+ error = GenStreamErrorRaised("Error: /srv/weights blew up")+ assert _friendly_gen_stream_error(error) == "An internal error occurred."+ assert logged == ["Local generation failed: Error: /srv/weights blew up"]+++def test_a_public_message_is_returned_as_written(logged):+ error = GenStreamErrorRaised("Error: audio generation is in progress", public = True)+ assert _friendly_gen_stream_error(error) == "Error: audio generation is in progress"diff --git a/studio/backend/tests/test_mlx_inference_backend.py b/studio/backend/tests/test_mlx_inference_backend.pyindex 01af1e2c831..21e0b91e1c2 100644--- a/studio/backend/tests/test_mlx_inference_backend.py+++ b/studio/backend/tests/test_mlx_inference_backend.py@@ -9,6 +9,7 @@ import jsonimport subprocessimport sysimport types+from collections import Counterfrom contextlib import contextmanagerfrom pathlib import Pathfrom types import SimpleNamespace@@ -106,6 +107,76 @@ def test_mlx_fusion_that_cannot_be_entered_keeps_native(assert active is model+ "feature", ["moe_gate_up", "decode_conv_silu", "residual_norm", "moe_router"]+)+ "message",+ [+ "[METAL] Command buffer execution failed: Caused GPU Timeout Error "+ "(0000000b:kIOGPUCommandBufferCallbackErrorTimeout)",+ "[METAL] Command buffer execution failed: Ignored (for causing prior/excessive GPU "+ "errors) (0000000e:kIOGPUCommandBufferCallbackErrorSubmissionsIgnored)",+ ],+ ids = ["watchdog", "ignored"],+)+def test_mlx_dead_gpu_queue_is_not_reported_as_a_working_fallback(+ monkeypatch, mlx_inference_patches, feature, message+):+ from core.inference import mlx_inference++ @contextmanager+ def fault(_model):+ raise RuntimeError(message)+ yield # pragma: no cover++ monkeypatch.setattr(mlx_inference_patches, f"fused_{feature}", fault)+ monkeypatch.setattr(mlx_inference, "_MLX_FUSION_UNAVAILABLE", set())+ with pytest.raises(RuntimeError, match = "METAL"):+ with getattr(mlx_inference, f"_mlx_fused_{feature}")(object()):+ pass # pragma: no cover+ assert mlx_inference._MLX_FUSION_UNAVAILABLE == set()+++ "feature", ["moe_gate_up", "decode_conv_silu", "residual_norm", "moe_router"]+)+def test_mlx_packing_that_runs_out_of_memory_still_keeps_native(+ monkeypatch, mlx_inference_patches, feature+):+ from core.inference import mlx_inference++ @contextmanager+ def refuse(_model):+ raise RuntimeError("[METAL] Command buffer execution failed: Insufficient Memory.")+ yield # pragma: no cover++ monkeypatch.setattr(mlx_inference_patches, f"fused_{feature}", refuse)+ monkeypatch.setattr(mlx_inference, "_MLX_FUSION_UNAVAILABLE", set())+ model = object()+ with getattr(mlx_inference, f"_mlx_fused_{feature}")(model) as active:+ assert active is model+++def test_mlx_dead_gpu_queue_at_load_fails_the_load(monkeypatch, mlx_moe):+ from core.inference import mlx_inference++ backend = _install_fake_text_stack(monkeypatch, {"p": [1, 2], "generated": [7, 8]}, [])+ _install_fake_fast_mlx(monkeypatch, [])+ sys.modules["mlx.core"].clear_cache = lambda: None++ @contextmanager+ def fault(_model):+ raise RuntimeError("[METAL] Command buffer execution failed: Caused GPU Timeout Error.")+ yield # pragma: no cover++ monkeypatch.setattr(mlx_moe, "fused_moe_gate_up", fault)+ monkeypatch.setattr(mlx_inference, "_MLX_FUSION_UNAVAILABLE", set())+ config = SimpleNamespace(identifier = "fake/text", is_vision = False, is_lora = False)+ with pytest.raises(RuntimeError, match = "METAL"):+ backend.load_model(config)++def test_mlx_fusion_failure_at_load_still_loads_the_model(monkeypatch, mlx_moe):"""The base-model scope is entered inside load_model, so a fusion that refuses theremust not turn a good load into a failed one."""@@ -129,6 +200,138 @@ def test_mlx_fusion_failure_at_load_still_loads_the_model(monkeypatch, mlx_moe):assert backend.unload_model("fake/text")+def test_mlx_fusion_that_refuses_everywhere_still_generates(monkeypatch, mlx_moe):+ from core.inference import mlx_inference++ backend = _install_fake_text_stack(monkeypatch, {"p": [1, 2], "generated": [7, 8]}, [])+ tokenizer = backend._tokenizer+ _install_fake_fast_mlx(monkeypatch, [])+ sys.modules["mlx.core"].clear_cache = lambda: None+ refused = []++ def _refusing(name):+ @contextmanager+ def refuse(_model):+ refused.append(name)+ raise RuntimeError("no headroom to pack")+ yield # pragma: no cover++ return refuse++ for name in ("moe_gate_up", "decode_conv_silu", "residual_norm", "moe_router"):+ monkeypatch.setattr(mlx_moe, f"fused_{name}", _refusing(name))+ monkeypatch.setattr(mlx_inference, "_MLX_FUSION_UNAVAILABLE", set())+ config = SimpleNamespace(identifier = "fake/text", is_vision = False, is_lora = False)+ assert backend.load_model(config) is True+ backend._tokenizer = tokenizer++ stream = backend.generate_chat_response(messages = [{"role": "user", "content": "p"}])+ assert next(stream) == "7"+ stream.close()+ assert Counter(refused) == Counter(+ moe_gate_up = 2, decode_conv_silu = 1, residual_norm = 1, moe_router = 1+ )+++def _all_fusions_refuse(monkeypatch, patches):+ from core.inference import mlx_inference++ refused = []++ def _refusing(name):+ @contextmanager+ def refuse(_model):+ refused.append(name)+ raise RuntimeError("no headroom to pack")+ yield # pragma: no cover++ return refuse++ for name in ("moe_gate_up", "decode_conv_silu", "residual_norm", "moe_router"):+ monkeypatch.setattr(patches, f"fused_{name}", _refusing(name))+ monkeypatch.setattr(mlx_inference, "_MLX_FUSION_UNAVAILABLE", set())+ return refused+++def test_mlx_vlm_generation_survives_every_fusion_refusing(monkeypatch, mlx_inference_patches):+ from core.inference import mlx_inference+ from core.inference.mlx_inference import MLXInferenceBackend++ mlx_vlm = types.ModuleType("mlx_vlm")+ mlx_vlm.prompt_utils = SimpleNamespace(+ MODEL_CONFIG = {}, apply_chat_template = lambda *_a, **_k: "<image> prompt"+ )+ mlx_vlm.stream_generate = lambda *_a, **_k: iter(+ [SimpleNamespace(text = "ok", prompt_tokens = 1, generation_tokens = 1)]+ )+ monkeypatch.setitem(sys.modules, "mlx_vlm", mlx_vlm)+ monkeypatch.setattr(+ "core.inference.chat_template_helpers.apply_chat_template_for_generation",+ lambda *_a, **_k: "<image> prompt",+ )+ monkeypatch.setattr(+ mlx_inference, "_temporary_mlx_adapter_state", lambda *_a, **_k: contextlib.nullcontext()+ )+ refused = _all_fusions_refuse(monkeypatch, mlx_inference_patches)++ backend = MLXInferenceBackend()+ backend._model = SimpleNamespace(config = {"model_type": "generic_vlm"})+ backend._processor = SimpleNamespace(chat_template = "template")+ args = (+ [{"role": "user", "content": [{"type": "image"}]}],+ [object()],+ 0.7,+ 0.9,+ 40,+ 0.01,+ 4,+ 1.0,+ None,+ )+ assert list(backend._generate_vlm(*args)) == ["ok"]+ assert Counter(refused) == Counter(+ moe_gate_up = 1, decode_conv_silu = 1, residual_norm = 1, moe_router = 1+ )+++def test_mlx_audio_input_generation_survives_every_fusion_refusing(+ monkeypatch, mlx_inference_patches+):+ from core.inference import mlx_inference+ from core.inference.mlx_inference import MLXInferenceBackend++ stats = dict(prompt_tokens = 3, prompt_tps = 1.0, generation_tokens = 3, generation_tps = 1.0)+ fake_vlm = types.ModuleType("mlx_vlm")+ fake_vlm.stream_generate = lambda *_a, **_k: (+ SimpleNamespace(text = text, **stats) for text in ("H", "e", "l")+ )+ monkeypatch.setitem(sys.modules, "mlx_vlm", fake_vlm)+ monkeypatch.setattr(+ mlx_inference,+ "_render_registered_vlm_prompt",+ lambda *_a, **_k: "P<audio>",+ )+ refused = _all_fusions_refuse(monkeypatch, mlx_inference_patches)++ backend = MLXInferenceBackend.__new__(MLXInferenceBackend)+ backend._generation_lock = __import__("threading").Lock()+ backend._model, backend._processor = _audio_model(), _audio_processor()+ backend.active_model_name = "m"+ backend.last_generation_stats = None+ backend.models = {"m": {"audio_type": "audio_vlm"}}+ assert list(+ backend.generate_audio_input_response(+ messages = [{"role": "user", "content": "what is said?"}],+ system_prompt = "",+ audio_array = [0.0, 0.1, -0.1],+ max_new_tokens = 64,+ )+ ) == ["H", "e", "l"]+ assert Counter(refused) == Counter(+ moe_gate_up = 1, decode_conv_silu = 1, residual_norm = 1, moe_router = 1+ )++@pytest.mark.parametrize("feature", ["moe_gate_up", "decode_conv_silu", "residual_norm", "moe_router"])diff --git a/studio/backend/tests/test_orchestrator_unload_cancel.py b/studio/backend/tests/test_orchestrator_unload_cancel.pyindex 8a6eb98cf0b..9e8f63f227f 100644--- a/studio/backend/tests/test_orchestrator_unload_cancel.py+++ b/studio/backend/tests/test_orchestrator_unload_cancel.py@@ -6,6 +6,7 @@ hanging the UI. ``unload_model`` now cancels first (the mp.Event the worker checeach token) and takes ``_gen_lock`` before the unload round-trip."""+import queueimport threadingimport time@@ -43,6 +44,10 @@ def _bare_orchestrator():o._dispatcher_thread = Noneo._dispatcher_stop = threading.Event()o._dispatcher_lifecycle_lock = threading.Lock()+ o._mailbox_lock = threading.Lock()+ o._mailboxes = {}+ o._direct_mailboxes = {}+ o._request_cancel_events = {}o._unload_pending = Falseo._exclusive_tts_pending = Falseo.active_model_name = "m"@@ -246,6 +251,310 @@ def test_consume_token_stream_bails_when_subprocess_swapped(monkeypatch):next(gen)+_GPU_TIMEOUT = (+ "[METAL] Command buffer execution failed: Caused GPU Timeout Error "+ "(00000002:kIOGPUCommandBufferCallbackErrorTimeout)"+)+++def _watch_teardown(+ o,+ monkeypatch,+ *,+ dead = True,+):+ torn_down = []++ def shutdown(timeout):+ torn_down.append(timeout)+ if dead:+ o._proc = None+ return dead++ monkeypatch.setattr(o, "_shutdown_subprocess_locked", shutdown)+ return torn_down+++def _queue_of(*responses):+ filled = queue.Queue()+ for resp in responses:+ filled.put(resp)+ return filled+++def _mailbox_for(worker, *responses):+ filled = orch_mod._WorkerMailbox(worker)+ for resp in responses:+ filled.put(resp)+ return filled+++class _LiveDispatcher:+ def is_alive(self):+ return True+++def test_a_foreign_fault_reaches_its_mailbox_before_the_worker_is_retired(monkeypatch):+ o = _bare_orchestrator()+ torn_down = []++ def shutdown(timeout):+ torn_down.append(timeout)+ o._proc = None+ o._reset_worker_scoped_state() # as the real teardown does+ return True++ monkeypatch.setattr(o, "_shutdown_subprocess_locked", shutdown)+ theirs = threading.Event()+ o._request_cancel_events = {"theirs": theirs}+ o._claim_worker(theirs)+ compare_mailbox = queue.Queue()+ o._mailboxes = {"theirs": compare_mailbox}+ fault = {"type": "gen_error", "request_id": "theirs", "error": _GPU_TIMEOUT}+ o._resp_queue = _queue_of(fault)++ read_one, _drain, release = o._direct_reader("mine")+ try:+ assert read_one(timeout = 0.5) is None, "a foreign response is routed, not returned"+ finally:+ release()++ assert compare_mailbox.get_nowait() == fault, "the request it belongs to must see the fault"+ assert torn_down, "and the dead worker must still be retired"+ assert o.active_model_name is None+++ "already_waiting, fault",+ [+ (True, {"type": "gen_error", "request_id": "r1", "error": _GPU_TIMEOUT}),+ (False, {"type": "audio_error", "request_id": "r1", "error": "SubmissionsIgnored"}),+ ],+ ids = ["already waiting", "routed a moment later"],+)+def test_a_direct_request_reading_past_a_live_dispatcher_still_retires(+ already_waiting, fault, monkeypatch+):+ o = _bare_orchestrator()+ torn_down = _watch_teardown(o, monkeypatch)+ o._dispatcher_thread = _LiveDispatcher()+ read_one, _drain, release = o._direct_reader("r1")+ mailbox = o._direct_mailboxes["r1"]+ if already_waiting:+ mailbox.put(fault)+ else:+ threading.Timer(0.05, mailbox.put, [fault]).start()++ try:+ assert read_one(timeout = 2.0) == fault+ finally:+ release()++ assert torn_down+ assert o.active_model_name is None+++def test_a_dispatched_stream_retires_on_the_fault_the_dispatcher_routed(monkeypatch):+ o = _bare_orchestrator()+ monkeypatch.setattr(o, "_ensure_subprocess_alive", lambda: True)+ torn_down = _watch_teardown(o, monkeypatch)+ o._resp_queue = queue.Queue()+ monkeypatch.setattr(+ o,+ "_send_cmd",+ lambda cmd: o._resp_queue.put(+ {"type": "gen_error", "request_id": cmd["request_id"], "error": _GPU_TIMEOUT}+ ),+ )++ try:+ streamed = list(o._generate_dispatched(messages = [{"role": "user", "content": "hi"}]))+ finally:+ o._stop_dispatcher()++ assert torn_down, "a dispatched request must retire the worker its fault killed"+ assert o.active_model_name is None+ assert any("GPU Timeout" in str(item) for item in streamed)+++ "leaves_a_mailbox", [False, True], ids = ["no mailbox left", "a mailbox nobody reads"]+)+def test_a_routed_fault_retires_the_worker_without_waiting_on_a_consumer(+ leaves_a_mailbox, monkeypatch+):+ o = _bare_orchestrator()+ if leaves_a_mailbox:+ o._mailboxes = {"gone": orch_mod._WorkerMailbox(o._proc)}+ torn_down = _watch_teardown(o, monkeypatch)+ observers = []+ observe = o._observe_response+ monkeypatch.setattr(+ o,+ "_observe_response",+ lambda resp, worker: (observers.append(threading.current_thread()), observe(resp, worker))[+ 1+ ],+ )+ o._resp_queue = queue.Queue()+ o._resp_queue.put({"type": "gen_error", "request_id": "gone", "error": _GPU_TIMEOUT})+ o._dispatcher_stop = threading.Event()+ dispatcher = threading.Thread(target = o._dispatcher_loop, daemon = True)+ dispatcher.start()+ try:+ deadline = time.monotonic() + 5.0+ while not torn_down and time.monotonic() < deadline:+ time.sleep(0.01)+ finally:+ o._dispatcher_stop.set()+ dispatcher.join(timeout = 5.0)++ assert torn_down, "no consumer will read it, so routing is the last chance"+ assert o.active_model_name is None+ assert observers and dispatcher not in observers+++def test_a_cancelled_generation_still_retires_the_worker_it_poisoned(monkeypatch):+ direct = _bare_orchestrator()+ monkeypatch.setattr(direct, "_ensure_subprocess_alive", lambda: True)+ direct_torn_down = _watch_teardown(direct, monkeypatch)+ direct._resp_queue = _queue_of(+ {"type": "token", "token": "a"}, {"type": "gen_error", "error": _GPU_TIMEOUT}+ )+ direct._drain_until_gen_done(timeout = 1.0)++ dispatched = _bare_orchestrator()+ dispatched_torn_down = _watch_teardown(dispatched, monkeypatch)+ dispatched._drain_mailbox(+ _mailbox_for(+ dispatched._proc,+ {"type": "token", "token": "a"},+ {"type": "gen_error", "error": _GPU_TIMEOUT},+ ),+ timeout = 1.0,+ )++ assert direct_torn_down and dispatched_torn_down+ assert direct.active_model_name is None and dispatched.active_model_name is None+++def test_an_ordinary_generation_error_leaves_the_worker_alone(monkeypatch):+ o = _bare_orchestrator()+ torn_down = _watch_teardown(o, monkeypatch)+ o._resp_queue = _queue_of(+ {"type": "gen_error", "request_id": "r1", "error": "context too long"}+ )++ assert o._read_resp(timeout = 0.01)["error"] == "context too long"+ assert not torn_down+ assert o.active_model_name == "m"+++def test_a_worker_that_outlives_the_kill_keeps_the_model_it_is_still_holding(monkeypatch):+ o = _bare_orchestrator()+ torn_down = _watch_teardown(o, monkeypatch, dead = False)+ o._resp_queue = _queue_of({"type": "gen_error", "error": _GPU_TIMEOUT})++ o._read_resp(timeout = 0.01)++ assert torn_down+ assert o.active_model_name == "m"+ assert o.models == {"m": {}}+++class _SwappedDuringRead(queue.Queue):+ def __init__(self, orchestrator, replacement, resp):+ super().__init__()+ self._orchestrator = orchestrator+ self._replacement = replacement+ self._resp = resp++ def get(self, timeout = None):+ self._orchestrator._proc = self._replacement+ return self._resp+++def test_a_fault_read_across_a_replacement_leaves_the_replacement_alone(monkeypatch):+ o = _bare_orchestrator()+ torn_down = _watch_teardown(o, monkeypatch)+ replacement = object()+ o._resp_queue = _SwappedDuringRead(o, replacement, {"type": "gen_error", "error": _GPU_TIMEOUT})++ assert o._read_resp(timeout = 0.01)["error"] == _GPU_TIMEOUT++ assert not torn_down, "the fault predates the replacement"+ assert o._proc is replacement+ assert o.active_model_name == "m"+++def test_the_direct_read_takes_the_handle_before_the_queue(monkeypatch):+ o = _bare_orchestrator()+ torn_down = _watch_teardown(o, monkeypatch)+ replacement = object()+ abandoned = _queue_of({"type": "gen_error", "error": _GPU_TIMEOUT})++ def reload_as_the_queue_is_taken(_self):+ o._proc = replacement+ return abandoned++ monkeypatch.setattr(+ type(o), "_resp_queue", property(reload_as_the_queue_is_taken), raising = False+ )++ o._read_resp(timeout = 0.01)++ assert not torn_down, "the fault came off the queue the predecessor left behind"+ assert o.active_model_name == "m"+++def test_a_fault_in_a_mailbox_that_outlived_its_worker_leaves_the_replacement_alone(monkeypatch):+ o = _bare_orchestrator()+ torn_down = _watch_teardown(o, monkeypatch)+ mailbox = _mailbox_for(o._proc, {"type": "gen_error", "error": _GPU_TIMEOUT})+ replacement = object()+ o._proc = replacement # a reload between reads++ assert o._read_mailbox(mailbox, 0.01)["error"] == _GPU_TIMEOUT++ assert not torn_down, "the fault was the old worker's; the replacement never produced it"+ assert o._proc is replacement+ assert o.active_model_name == "m"+ assert o.models == {"m": {}}+++def test_a_fault_from_a_replaced_worker_leaves_the_replacement_alone(monkeypatch):+ o = _bare_orchestrator()+ torn_down = _watch_teardown(o, monkeypatch)+ replacement = object()++ def reload():+ o._proc = replacement+ o._subprocess_shutdown_lock.release()++ o._subprocess_shutdown_lock.acquire()+ threading.Timer(0.05, reload).start()++ o._observe_response({"type": "gen_error", "error": _GPU_TIMEOUT}, o._proc)++ assert not torn_down, "the fault belonged to a worker that is already gone"+ assert o._proc is replacement+ assert o.active_model_name == "m"+ assert o.models == {"m": {}}+++def test_a_fault_with_no_worker_behind_it_clears_nothing(monkeypatch):+ """``None is not None`` is False, so the check alone would let an absent worker through."""+ o = _bare_orchestrator()+ torn_down = _watch_teardown(o, monkeypatch)+ o._proc = None++ o._read_mailbox(_mailbox_for(None, {"type": "gen_error", "error": _GPU_TIMEOUT}), 0.01)++ assert not torn_down+ assert o.active_model_name == "m"+ assert o.models == {"m": {}}++def test_unload_pending_clears_after_unload(monkeypatch):o = _bare_orchestrator()monkeypatch.setattr(o, "_ensure_subprocess_alive", lambda: True)@@ -2440,10 +2749,6 @@ def test_a_dispatcher_started_mid_stream_still_reaches_the_direct_reader():# that chat's tokens and its gen_done as unaddressed, hanging it.o = _bare_orchestrator()- o._mailbox_lock = threading.Lock()- o._mailboxes = {}- o._direct_mailboxes = {}- o._request_cancel_events = {}read_one, _drain, release = o._direct_reader("direct-1")try:diff --git a/studio/backend/tests/test_utils.py b/studio/backend/tests/test_utils.pyindex 8d4c8bee619..732716225e0 100644--- a/studio/backend/tests/test_utils.py+++ b/studio/backend/tests/test_utils.py@@ -711,6 +711,49 @@ class TestFormatErrorMessage:assert msg == "Something completely unexpected"+class TestSafeErrorDetailNamesAMetalFailure:+ @pytest.mark.parametrize(+ "message",+ [+ "[METAL] Command buffer execution failed: Caused GPU Timeout Error "+ "(0000000b:kIOGPUCommandBufferCallbackErrorTimeout)",+ "[METAL] Command buffer execution failed: Ignored (for causing prior/excessive "+ "GPU errors) (0000000e:kIOGPUCommandBufferCallbackErrorSubmissionsIgnored)",+ ],+ ids = ["watchdog", "ignored"],+ )+ def test_a_dead_queue_says_the_gpu_stopped(self, message):+ from utils.utils import is_metal_queue_dead, safe_error_detail+ assert is_metal_queue_dead(Exception(message))+ assert safe_error_detail(Exception(message)) == (+ "The GPU stopped responding. Reload the model to recover."+ )++ @pytest.mark.parametrize(+ "message",+ [+ "[malloc] Unable to allocate 42949672960 bytes.",+ "[METAL] Command buffer execution failed: Insufficient Memory.",+ ],+ ids = ["malloc", "command-buffer"],+ )+ def test_an_allocation_failure_says_memory_and_leaves_the_queue_alive(self, message):+ """mlx wraps this like a watchdog kill, but recovers from it."""+ from utils.utils import is_metal_queue_dead, safe_error_detail++ assert not is_metal_queue_dead(Exception(message))+ assert safe_error_detail(Exception(message)) == (+ "Ran out of memory. Try a smaller model or shorter input."+ )++ def test_an_ordinary_timeout_still_reads_as_upstream(self):+ from utils.utils import is_metal_queue_dead, safe_error_detail++ error = TimeoutError("read timed out")+ assert not is_metal_queue_dead(error)+ assert safe_error_detail(error) == "Could not reach an upstream service. Please try again."++class TestAuthSafeRedirectHandler:"""A Hub token must not leave the origin the operator configured.diff --git a/studio/backend/utils/utils.py b/studio/backend/utils/utils.pyindex fb9872b63e5..12394295620 100644--- a/studio/backend/utils/utils.py+++ b/studio/backend/utils/utils.py@@ -11,7 +11,7 @@ import timefrom loggers import get_loggerfrom contextlib import contextmanagerfrom pathlib import Path-from typing import Optional+from typing import Optional, Unionimport shutilimport tempfilefrom utils.paths.path_utils import is_appledouble_metadata@@ -756,6 +756,16 @@ def snapshot_is_loadable(snapshot, model_name: str) -> bool:# ── Client-safe error helpers ───────────────────────────────────+_METAL_QUEUE_DEAD_MARKERS = ("gpu timeout", "submissionsignored")+++def is_metal_queue_dead(error: Union[Exception, str]) -> bool:+ """Watchdog kill or the refusal after it; not mlx's ``Command buffer execution failed:``+ wrapper, which also carries a recoverable ``Insufficient Memory``."""+ text = str(error).lower()+ return any(marker in text for marker in _METAL_QUEUE_DEAD_MARKERS)++# Never return raw exception text to clients; log server-side, return generic.def safe_error_detail(error: Exception, fallback: str = "An internal error occurred") -> str:"""Map an exception to a generic, client-safe message (never raw ``str(error)``, which can leak paths). Log the real exception server-side."""@@ -767,6 +777,16 @@ def safe_error_detail(error: Exception, fallback: str = "An internal error occurexcept Exception: # noqa: BLE001 -- fall through to the generic mapping belowpasstext = str(error).lower()+ # Before the connection test, which "GPU Timeout Error" would match.+ if is_metal_queue_dead(error):+ return "The GPU stopped responding. Reload the model to recover."+ if (+ "out of memory" in text+ or "cuda error" in text+ or "unable to allocate" in text+ or "insufficient memory" in text+ ):+ return "Ran out of memory. Try a smaller model or shorter input."if (isinstance(error, (ConnectionError, TimeoutError))or "connection" in text@@ -774,8 +794,6 @@ def safe_error_detail(error: Exception, fallback: str = "An internal error occuror "timeout" in text):return "Could not reach an upstream service. Please try again."- if "out of memory" in text or "cuda error" in text:- return "Ran out of memory. Try a smaller model or shorter input."return fallback