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
Studio: keep SSM kernel installs alive and reap the worker on load timeout (#9419)
Indrajit swain5205a38f70c5
diff --git a/studio/backend/core/inference/orchestrator.py b/studio/backend/core/inference/orchestrator.pyindex c1251b5d101..ac02b12d10c 100644--- a/studio/backend/core/inference/orchestrator.py+++ b/studio/backend/core/inference/orchestrator.py@@ -221,6 +221,7 @@ class InferenceOrchestrator:self._proc: Optional[mp.Process] = Noneself._cmd_queue: Any = Noneself._resp_queue: Any = None+ self._subprocess_shutdown_lock = threading.Lock()self._cancel_event: Any = None # mp.Event — set to cancel generation# Set for the whole unload; the worker never clears it (unlike _cancel_event),# so a generate queued behind the cancelled one is skipped, not run.@@ -458,6 +459,10 @@ class InferenceOrchestrator:return proc is not None and proc.is_alive()def _shutdown_subprocess(self, timeout: float = 10.0) -> bool:+ with self._subprocess_shutdown_lock:+ return self._shutdown_subprocess_locked(timeout)++ def _shutdown_subprocess_locked(self, timeout: float) -> bool:"""Gracefully shut down the inference subprocess.Returns True only once the worker is confirmed dead. If it survives@@ -493,17 +498,25 @@ class InferenceOrchestrator:if self._proc is not None and self._proc.is_alive():logger.warning("Inference subprocess did not exit gracefully, terminating")try:- self._proc.terminate()+ from utils.process_lifetime import terminate_pid+ terminate_pid(self._proc.pid, timeout = 5)self._proc.join(timeout = 5)except Exception:passif self._proc is not None and self._proc.is_alive():- logger.warning("Subprocess still alive after terminate, killing")+ logger.warning("Process-tree shutdown failed, terminating the worker directly")try:- self._proc.kill()- self._proc.join(timeout = 3)+ self._proc.terminate()+ self._proc.join(timeout = 5)except Exception:pass+ if self._proc is not None and self._proc.is_alive():+ logger.warning("Subprocess still alive after terminate, killing")+ try:+ self._proc.kill()+ self._proc.join(timeout = 3)+ except Exception:+ passif self._proc is not None and self._proc.is_alive():# Survived SIGKILL (uninterruptible syscall): keep the handle so callers@@ -1541,7 +1554,6 @@ class InferenceOrchestrator:else:# Worker reports failures (consent gate included) under "message".error = resp.get("message") or resp.get("error") or "Failed to load model"- self.loading_models.discard(model_name)self.active_model_name = Noneself.models.clear()raise Exception(error)@@ -1557,6 +1569,12 @@ class InferenceOrchestrator:raiseself.active_model_name = Noneself.models.clear()+ # Reap workers after any failed load, including inactivity timeouts+ # that leave installs and GPU memory alive (#9398).+ try:+ self._shutdown_subprocess(timeout = 5)+ except Exception as teardown_exc:+ logger.warning("Could not shut the failed load's worker down: %s", teardown_exc)raisedef cancel_load(self, model_name: str) -> bool:diff --git a/studio/backend/tests/test_orchestrator_unload_cancel.py b/studio/backend/tests/test_orchestrator_unload_cancel.pyindex 22e35a87d4e..94895e2d546 100644--- a/studio/backend/tests/test_orchestrator_unload_cancel.py+++ b/studio/backend/tests/test_orchestrator_unload_cancel.py@@ -20,6 +20,7 @@ def _bare_orchestrator():o = InferenceOrchestrator.__new__(InferenceOrchestrator)o._gen_lock = threading.Lock()o._send_order_lock = threading.Lock()+ o._subprocess_shutdown_lock = threading.Lock()o._active_cancel_lock = threading.Lock()o._active_cancel_events = []o._executing_cancel_events = []@@ -1322,6 +1323,180 @@ def test_load_model_proceeds_when_not_cancelled(monkeypatch):assert o.active_model_name == "m"+def test_load_model_reaps_worker_after_inactivity_timeout(monkeypatch):+ # A quiet install can trip the inactivity timeout; the failure path must+ # still tear its worker down (#9398).+ import types++ from utils import transformers_version as tv++ o = _bare_orchestrator()+ o.active_model_name = None+ o.models = {}+ o.loading_models = set()+ o._proc = None+ shutdowns = []+ monkeypatch.setattr(tv, "needs_transformers_5", lambda name: False)+ monkeypatch.setattr(orch_mod, "prepare_gpu_selection", lambda *a, **k: ([0], "sel"))+ monkeypatch.setattr(o, "_ensure_subprocess_alive", lambda: False)+ monkeypatch.setattr(o, "_spawn_subprocess", lambda cfg: None)+ monkeypatch.setattr(+ o,+ "_shutdown_subprocess",+ lambda timeout = 5: shutdowns.append(timeout) or True,+ )+ monkeypatch.setattr(+ o,+ "_wait_response",+ lambda t, timeout = 300.0: (_ for _ in ()).throw(+ RuntimeError("Timeout waiting for 'loaded' response (no activity for 300.0s)")+ ),+ )++ with pytest.raises(RuntimeError, match = "Timeout waiting for 'loaded'"):+ o.load_model(types.SimpleNamespace(identifier = "m", gguf_variant = None))++ assert shutdowns, "failed load must reap the worker after the inactivity timeout"+ assert o.active_model_name is None+ assert o.models == {}+ assert "m" not in o.loading_models+++def test_worker_reported_load_failure_reaps_worker(monkeypatch):+ import types++ from utils import transformers_version as tv++ o = _bare_orchestrator()+ o.active_model_name = None+ o.models = {}+ o.loading_models = set()+ o._proc = None+ shutdowns = []+ monkeypatch.setattr(tv, "needs_transformers_5", lambda name: False)+ monkeypatch.setattr(orch_mod, "prepare_gpu_selection", lambda *a, **k: ([0], "sel"))+ monkeypatch.setattr(o, "_ensure_subprocess_alive", lambda: False)+ monkeypatch.setattr(o, "_spawn_subprocess", lambda cfg: None)+ monkeypatch.setattr(+ o,+ "_shutdown_subprocess",+ lambda timeout = 5: shutdowns.append(timeout) or True,+ )+ monkeypatch.setattr(+ o,+ "_wait_response",+ lambda t, timeout = 300.0: {"success": False, "message": "real worker load failure"},+ )++ with pytest.raises(Exception, match = "real worker load failure"):+ o.load_model(types.SimpleNamespace(identifier = "m", gguf_variant = None))++ assert shutdowns == [5]+ assert "m" not in o.loading_models+++def test_failed_load_keeps_timeout_after_cancel_teardown(monkeypatch):+ # Both paths may request teardown; the serialized second call is harmless.+ import types++ from utils import transformers_version as tv++ o = _bare_orchestrator()+ o.active_model_name = None+ o.models = {}+ o.loading_models = set()+ o._proc = None++ monkeypatch.setattr(tv, "needs_transformers_5", lambda name: False)+ monkeypatch.setattr(orch_mod, "prepare_gpu_selection", lambda *a, **k: ([0], "sel"))+ monkeypatch.setattr(o, "_ensure_subprocess_alive", lambda: False)+ monkeypatch.setattr(o, "_spawn_subprocess", lambda cfg: None)++ parked = threading.Event()+ release_timeout = threading.Event()+ load_done = threading.Event()+ shutdowns = []++ def blocking_wait_response(expected, timeout = 300.0):+ parked.set()+ assert release_timeout.wait(timeout = 5)+ raise RuntimeError("Timeout waiting for 'loaded' response (no activity for 300.0s)")++ def record_shutdown(timeout = 5):+ shutdowns.append(timeout)+ o._cmd_queue = None++ monkeypatch.setattr(o, "_wait_response", blocking_wait_response)+ monkeypatch.setattr(o, "_shutdown_subprocess", record_shutdown)++ load_result: dict = {}++ def run_load():+ try:+ load_result["ok"] = o.load_model(+ types.SimpleNamespace(identifier = "m", gguf_variant = None)+ )+ except Exception as exc: # noqa: BLE001+ load_result["exc"] = exc+ finally:+ load_done.set()++ loader = threading.Thread(target = run_load)+ loader.start()+ assert parked.wait(timeout = 5), "load_model must reach _wait_response"++ assert o.cancel_load("m") is True+ release_timeout.set()+ loader.join(timeout = 5)+ assert load_done.is_set()++ assert isinstance(load_result.get("exc"), RuntimeError), load_result+ assert "Timeout waiting for 'loaded'" in str(load_result["exc"])+ assert shutdowns == [0.5, 5]+ assert o.active_model_name is None+ assert o.models == {}+ assert "m" not in o.loading_models+++def test_failed_load_keeps_the_timeout_when_teardown_raises(monkeypatch):+ # A teardown failure must stay a warning, not replace the load error.+ import types++ from utils import transformers_version as tv++ o = _bare_orchestrator()+ o.active_model_name = None+ o.models = {}+ o.loading_models = set()+ o._proc = None++ monkeypatch.setattr(tv, "needs_transformers_5", lambda name: False)+ monkeypatch.setattr(orch_mod, "prepare_gpu_selection", lambda *a, **k: ([0], "sel"))+ monkeypatch.setattr(o, "_ensure_subprocess_alive", lambda: False)+ monkeypatch.setattr(o, "_spawn_subprocess", lambda cfg: None)+ monkeypatch.setattr(+ o,+ "_shutdown_subprocess",+ lambda timeout = 5: (_ for _ in ()).throw(+ AttributeError("'NoneType' object has no attribute 'put'")+ ),+ )+ monkeypatch.setattr(+ o,+ "_wait_response",+ lambda t, timeout = 300.0: (_ for _ in ()).throw(+ RuntimeError("Timeout waiting for 'loaded' response (no activity for 300.0s)")+ ),+ )++ with pytest.raises(RuntimeError, match = "Timeout waiting for 'loaded'"):+ o.load_model(types.SimpleNamespace(identifier = "m", gguf_variant = None))++ assert o.active_model_name is None+ assert o.models == {}+ assert "m" not in o.loading_models++def test_load_model_aborts_when_cancelled_during_spawn(monkeypatch):# Stop-loading can land AFTER the pre-spawn marker recheck but while# _spawn_subprocess is still creating the queues/process, so cancel_load'sdiff --git a/studio/backend/tests/test_shutdown_preserves_live_worker.py b/studio/backend/tests/test_shutdown_preserves_live_worker.pyindex 15ef93c0025..8e0182793c4 100644--- a/studio/backend/tests/test_shutdown_preserves_live_worker.py+++ b/studio/backend/tests/test_shutdown_preserves_live_worker.py@@ -23,6 +23,7 @@ class _FakeProc:def __init__(self, dies_on = None):self._alive = Trueself._dies_on = dies_on # None | "join" | "terminate" | "kill"+ self.pid = 424242def is_alive(self):return self._alive@@ -42,6 +43,7 @@ class _FakeProc:def _bare_inference():o = InferenceOrchestrator.__new__(InferenceOrchestrator)+ o._subprocess_shutdown_lock = threading.Lock()o._stop_dispatcher = lambda: Noneo._cancel_generation = lambda: Noneo._drain_queue = lambda: []@@ -108,6 +110,61 @@ class TestInferenceShutdownReturn:assert o._shutdown_subprocess(timeout = 0.01) is Trueassert o._proc is None+ def test_forced_shutdown_reaps_worker_tree(self, monkeypatch):+ from utils import process_lifetime++ o = _bare_inference()+ o._proc = _FakeProc(dies_on = "terminate")+ reaped = []+ monkeypatch.setattr(+ process_lifetime,+ "terminate_pid",+ lambda pid, timeout: reaped.append((pid, timeout)),+ )++ assert o._shutdown_subprocess(timeout = 0.01) is True+ assert reaped == [(424242, 5)]++ def test_concurrent_shutdowns_share_one_teardown(self):+ o = _bare_inference()+ o._proc = _FakeProc(dies_on = "join")+ first_put = threading.Event()+ second_put = threading.Event()+ release = threading.Event()+ puts = []++ class _BlockingQueue:+ def put(self, message):+ puts.append(message)+ if len(puts) == 1:+ first_put.set()+ assert release.wait(timeout = 5)+ else:+ second_put.set()++ o._cmd_queue = _BlockingQueue()+ errors = []++ def shutdown():+ try:+ o._shutdown_subprocess(timeout = 0.01)+ except Exception as exc: # noqa: BLE001+ errors.append(exc)++ first = threading.Thread(target = shutdown)+ second = threading.Thread(target = shutdown)+ first.start()+ assert first_put.wait(timeout = 5)+ second.start()+ assert not second_put.wait(timeout = 0.1)+ release.set()+ first.join(timeout = 5)+ second.join(timeout = 5)++ assert not first.is_alive() and not second.is_alive()+ assert errors == []+ assert len(puts) == 1+class TestExportShutdownReturn:def test_worker_that_dies_returns_true_and_clears_handle(self):diff --git a/studio/backend/tests/test_ssm_runtime.py b/studio/backend/tests/test_ssm_runtime.pyindex 71ec92ef346..14b705e2bfe 100644--- a/studio/backend/tests/test_ssm_runtime.py+++ b/studio/backend/tests/test_ssm_runtime.py@@ -275,6 +275,132 @@ def test_install_kernel_uses_prebuilt_wheel(monkeypatch):assert ran == [] # wheel succeeded; no PyPI source build+def test_install_kernel_heartbeats_during_prebuilt_wheel(monkeypatch):+ # Keep the parent alive during a quiet wheel install (#9398).+ import threading+ import time++ monkeypatch.setattr(ssm_runtime, "_HEARTBEAT_SECONDS", 0.05)+ monkeypatch.setattr(ssm_runtime, "_is_importable", lambda name: False)+ monkeypatch.setattr(ssm_runtime, "probe_torch_wheel_env", lambda timeout = 30: {})+ monkeypatch.setattr(+ ssm_runtime,+ "direct_wheel_url",+ lambda **k: "https://example/causal_conv1d-1.6.1.whl",+ )+ monkeypatch.setattr(ssm_runtime, "url_exists", lambda u: True)++ statuses = []+ released = threading.Event()++ def slow_install_wheel(url, **k):+ # Hold long enough for at least one heartbeat tick.+ assert released.wait(1.0)+ return [("uv", _Result(returncode = 1, stdout = "nope"))]++ monkeypatch.setattr(ssm_runtime, "install_wheel", slow_install_wheel)+ # Force the source-build fallback to no-op after the wheel attempt.+ monkeypatch.setattr(ssm_runtime.shutil, "which", lambda name: None)++ def run_fail(cmd, **k):+ return _Result(returncode = 1)++ thread = threading.Thread(+ target = lambda: ssm_runtime._install_kernel(+ import_name = "causal_conv1d",+ display_name = "causal-conv1d",+ pypi_name = "causal-conv1d",+ package_version = "1.6.1",+ release_tag = "v1.6.1.post4",+ release_base_url = "x",+ status_cb = statuses.append,+ run = run_fail,+ ),+ daemon = True,+ )+ thread.start()+ deadline = time.monotonic() + 2.0+ while time.monotonic() < deadline:+ if any("Still installing causal-conv1d (prebuilt kernel)" in s for s in statuses):+ break+ time.sleep(0.02)+ released.set()+ thread.join(timeout = 2.0)+ assert any("Still installing causal-conv1d (prebuilt kernel)" in s for s in statuses), statuses+ assert any("Installing causal-conv1d (prebuilt kernel)" in s for s in statuses)+++def test_install_kernel_heartbeats_through_the_import_check(monkeypatch):+ # The first torch import can be quiet long enough to trip the inactivity+ # deadline, so keep heartbeats running through it.+ import threading+ import time++ monkeypatch.setattr(ssm_runtime, "_HEARTBEAT_SECONDS", 0.05)+ monkeypatch.setattr(ssm_runtime, "probe_torch_wheel_env", lambda timeout = 30: {})+ monkeypatch.setattr(+ ssm_runtime,+ "direct_wheel_url",+ lambda **k: "https://example/causal_conv1d-1.6.1.whl",+ )+ monkeypatch.setattr(ssm_runtime, "url_exists", lambda u: True)+ monkeypatch.setattr(+ ssm_runtime, "install_wheel", lambda url, **k: [("uv", _Result(returncode = 0))]+ )++ import_started = threading.Event()+ import_released = threading.Event()+ seen = {"n": 0}++ def slow_importable(name):+ seen["n"] += 1+ if seen["n"] == 1:+ return False+ import_started.set()+ assert import_released.wait(1.0)+ return True++ monkeypatch.setattr(ssm_runtime, "_is_importable", slow_importable)++ statuses = []+ thread = threading.Thread(+ target = lambda: ssm_runtime._install_kernel(+ import_name = "causal_conv1d",+ display_name = "causal-conv1d",+ pypi_name = "causal-conv1d",+ package_version = "1.6.1",+ release_tag = "v1.6.1.post4",+ release_base_url = "x",+ status_cb = statuses.append,+ run = lambda *a, **k: _Result(returncode = 1),+ ),+ daemon = True,+ )+ thread.start()+ assert import_started.wait(timeout = 2.0), "must reach the post-wheel import check"+ deadline = time.monotonic() + 2.0+ while time.monotonic() < deadline:+ if any("Still installing causal-conv1d (prebuilt kernel)" in s for s in statuses):+ break+ time.sleep(0.02)+ import_released.set()+ thread.join(timeout = 2.0)+ assert any("Still installing causal-conv1d (prebuilt kernel)" in s for s in statuses), statuses+++def test_heartbeat_does_not_emit_after_the_block(monkeypatch):+ # No in-flight tick may emit after the block exits.+ import time++ monkeypatch.setattr(ssm_runtime, "_HEARTBEAT_SECONDS", 0.05)+ statuses = []+ with ssm_runtime._heartbeat(statuses.append, "still going"):+ time.sleep(0.12)+ n = len(statuses)+ time.sleep(0.15)+ assert len(statuses) == n, statuses++def test_install_kernel_falls_back_to_source(monkeypatch):# no wheel -> source build -> importable after installstates = iter([False, True]) # before install, after installdiff --git a/studio/backend/utils/ssm_runtime.py b/studio/backend/utils/ssm_runtime.pyindex 5de02ddc7bd..5f8558f6324 100644--- a/studio/backend/utils/ssm_runtime.py+++ b/studio/backend/utils/ssm_runtime.py@@ -20,8 +20,9 @@ import shutilimport subprocessimport sysimport threading+from contextlib import contextmanagerfrom pathlib import Path-from typing import Any, Callable, Optional+from typing import Any, Callable, Iterator, Optionalfrom loggers import get_loggerfrom utils.child_stdio import utf8_child_env@@ -245,20 +246,43 @@ def _hipcc_gcc_install_dir() -> Optional[str]:return None-def _run_with_heartbeat(run, cmd, status_cb, display_name, **kwargs):- """Run *cmd* via *run*, emitting a status every 60s so the parent's inactivity- timeout isn't tripped by a long (e.g. ROCm) source build."""+# Keep quiet downloads and builds inside the orchestrator's inactivity deadline.+_HEARTBEAT_SECONDS = 60.0+++@contextmanager+def _heartbeat(status_cb: StatusCb, message: str) -> Iterator[None]:+ """Emit *message* on a timer while the wrapped work runs.++ The inference orchestrator treats silence as a dead load: status messages+ reset its inactivity deadline. Prebuilt wheel installs and source builds+ can both stay quiet for minutes on aarch64 / slow links, so both paths use+ this.+ """done = threading.Event()- def _beat():- while not done.wait(60):- _emit(status_cb, f"Still building {display_name} (this can take several minutes)...")+ def _beat() -> None:+ while not done.wait(_HEARTBEAT_SECONDS):+ _emit(status_cb, message)- threading.Thread(target = _beat, daemon = True).start()+ thread = threading.Thread(target = _beat, daemon = True, name = "ssm-install-heartbeat")+ thread.start()try:- return run(cmd, **kwargs)+ yieldfinally:done.set()+ # Wait out a tick that already left done.wait().+ thread.join(timeout = 1)+++def _run_with_heartbeat(run, cmd, status_cb, display_name, **kwargs):+ """Run *cmd* via *run*, emitting a status every 60s so the parent's inactivity+ timeout isn't tripped by a long (e.g. ROCm) source build."""+ with _heartbeat(+ status_cb,+ f"Still building {display_name} (this can take several minutes)...",+ ):+ return run(cmd, **kwargs)def _install_kernel(@@ -294,28 +318,35 @@ def _install_kernel()if wheel_url and url_exists(wheel_url):_emit(status_cb, f"Installing {display_name} (prebuilt kernel) for this model...")- for installer, result in install_wheel(- wheel_url,- python_executable = sys.executable,- use_uv = bool(shutil.which("uv")),- run = run,+ # Keep quiet downloads and unpacks within the inactivity deadline (#9398).+ with _heartbeat(+ status_cb,+ f"Still installing {display_name} (prebuilt kernel)...",):- if getattr(result, "returncode", 1) == 0:- # A wheel can install yet fail to import (CUDA/ABI mismatch); verify before- # trusting it, else source-build to match the local ABI.- if _is_importable(import_name):- logger.info("Installed prebuilt %s wheel", display_name)- return True+ # A cold first import can also stay quiet for tens of seconds.+ for installer, result in install_wheel(+ wheel_url,+ python_executable = sys.executable,+ use_uv = bool(shutil.which("uv")),+ run = run,+ ):+ if getattr(result, "returncode", 1) == 0:+ # A wheel can install yet fail to import (CUDA/ABI mismatch); verify before+ # trusting it, else source-build to match the local ABI.+ if _is_importable(import_name):+ logger.info("Installed prebuilt %s wheel", display_name)+ return True+ logger.warning(+ "%s wheel installed but not importable; building from source",+ display_name,+ )+ breaklogger.warning(- "%s wheel installed but not importable; building from source", display_name+ "%s could not install %s wheel:\n%s",+ installer,+ display_name,+ getattr(result, "stdout", ""),)- break- logger.warning(- "%s could not install %s wheel:\n%s",- installer,- display_name,- getattr(result, "stdout", ""),- )else:logger.info("No prebuilt %s wheel for this environment (%s); building from source",