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.

Studio: keep inference status probes off the event loop (#7944)

oobabooga47df5b851c91
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index ad62c59c134..5c6dac917dd 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -24,6 +24,7 @@ from loggers import get_logger
import asyncio
import threading
import weakref
+from concurrent.futures import ThreadPoolExecutor
from contextlib import ExitStack, contextmanager
from dataclasses import replace
@@ -148,6 +149,11 @@ def _install_httpcore_asyncgen_silencer() -> None:
_install_httpcore_asyncgen_silencer()
+# Status polls can start a cold subprocess probe or wait on a release lookup. Keep
+# that bounded work out of the default executor, which drives local token streaming.
+_STATUS_PROBE_EXECUTOR = ThreadPoolExecutor(max_workers = 2, thread_name_prefix = "inference-status")
+
+
def _loaded_chat_template() -> Optional[str]:
"""Chat template of the currently loaded GGUF model, if any."""
try:
@@ -8317,6 +8323,30 @@ async def generate_stream(
return _sse_streaming_response(stream())
+def _probe_llama_cpp_status(llama_backend) -> tuple[bool, dict]:
+ """Read llama.cpp capabilities and release freshness without raising."""
+ try:
+ binary = type(llama_backend)._find_llama_server_binary()
+ capabilities = type(llama_backend).probe_server_capabilities(binary)
+ # Treat a discovered but inconclusive binary as MTP-compatible.
+ supports_mtp = bool(
+ capabilities.get("supports_mtp", False)
+ or (
+ capabilities.get("found", False)
+ and capabilities.get("mtp_probe_inconclusive", False)
+ )
+ )
+ except Exception:
+ binary = None
+ supports_mtp = False # no usable binary: MTP genuinely unavailable
+ try:
+ from utils.llama_cpp_freshness import check_prebuilt_freshness
+ freshness = check_prebuilt_freshness(binary)
+ except Exception:
+ freshness = {}
+ return supports_mtp, freshness
+
+
@router.get("/status", response_model = InferenceStatusResponse)
async def get_status(current_subject: str = Depends(get_current_subject)):
"""
@@ -8326,24 +8356,11 @@ async def get_status(current_subject: str = Depends(get_current_subject)):
try:
llama_backend = get_llama_cpp_backend()
- # MTP probe + freshness check (both cached); drive the UI banner.
- try:
- _bin = type(llama_backend)._find_llama_server_binary()
- _caps = type(llama_backend).probe_server_capabilities(_bin)
- # Fail open on inconclusive probes: False means a definitive
- # "binary lacks MTP" to API consumers.
- _supports_mtp = bool(
- _caps.get("supports_mtp", False)
- or (_caps.get("found", False) and _caps.get("mtp_probe_inconclusive", False))
- )
- except Exception:
- _bin = None
- _supports_mtp = False # no usable binary: MTP genuinely unavailable
- try:
- from utils.llama_cpp_freshness import check_prebuilt_freshness
- _freshness = check_prebuilt_freshness(_bin)
- except Exception:
- _freshness = {}
+ # The cold subprocess and GitHub probes must not block the event loop or
+ # consume the default executor used by local token streaming.
+ _supports_mtp, _freshness = await asyncio.get_running_loop().run_in_executor(
+ _STATUS_PROBE_EXECUTOR, _probe_llama_cpp_status, llama_backend
+ )
_stale = bool(_freshness.get("stale"))
_installed_tag = _freshness.get("installed_tag")
_latest_tag = _freshness.get("latest_tag")
diff --git a/studio/backend/tests/test_inference_status_route.py b/studio/backend/tests/test_inference_status_route.py
new file mode 100644
index 00000000000..90eb75d9b3b
--- /dev/null
+++ b/studio/backend/tests/test_inference_status_route.py
@@ -0,0 +1,158 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Verify that slow inference status probes run off the event loop."""
+
+from __future__ import annotations
+
+import asyncio
+import sys
+import threading
+from concurrent.futures import ThreadPoolExecutor
+from pathlib import Path
+
+_BACKEND = Path(__file__).resolve().parents[1]
+if str(_BACKEND) not in sys.path:
+ sys.path.insert(0, str(_BACKEND))
+
+import routes.inference as inference_route # noqa: E402
+
+# Multiple turns make scheduler progress unambiguous.
+_CONTROL_TURNS = 5
+# Prevent a regression from hanging the suite.
+_GUARD_SECONDS = 10.0
+
+
+class _FakeLlamaBackend:
+ is_loaded = False
+
+
+class _FakeInferenceBackend:
+ active_model_name = None
+ models: dict = {}
+ loading_models: set = set()
+
+
+def _patch_status_dependencies(monkeypatch):
+ """Stub everything the route touches other than the two slow probes."""
+ monkeypatch.setattr(inference_route, "get_llama_cpp_backend", _FakeLlamaBackend)
+ monkeypatch.setattr(inference_route, "get_inference_backend", _FakeInferenceBackend)
+ monkeypatch.setattr(
+ inference_route,
+ "_detect_safetensors_features",
+ lambda *_args: {
+ "supports_reasoning": False,
+ "reasoning_style": "enable_thinking",
+ "reasoning_effort_levels": [],
+ "reasoning_always_on": False,
+ "supports_preserve_thinking": False,
+ "supports_tools": False,
+ },
+ )
+
+
+def _patch_slow_probes(monkeypatch, *, entered, release):
+ """Block the capability probe and stub the GitHub request."""
+ from utils import llama_cpp_freshness
+
+ def _find_binary(_cls):
+ return "/nonexistent/llama-server"
+
+ def _probe_capabilities(_cls, _binary):
+ entered.set()
+ release.wait(timeout = _GUARD_SECONDS)
+ return {"found": True, "supports_mtp": True}
+
+ def _check_freshness(_binary):
+ return {"stale": True, "installed_tag": "b1", "latest_tag": "b2"}
+
+ monkeypatch.setattr(
+ _FakeLlamaBackend,
+ "_find_llama_server_binary",
+ classmethod(_find_binary),
+ raising = False,
+ )
+ monkeypatch.setattr(
+ _FakeLlamaBackend,
+ "probe_server_capabilities",
+ classmethod(_probe_capabilities),
+ raising = False,
+ )
+ monkeypatch.setattr(llama_cpp_freshness, "check_prebuilt_freshness", _check_freshness)
+
+
+def test_status_probe_runs_off_the_event_loop(monkeypatch):
+ """The blocked probe must not stall the shared streaming loop."""
+ _patch_status_dependencies(monkeypatch)
+ entered = threading.Event()
+ release = threading.Event()
+ _patch_slow_probes(monkeypatch, entered = entered, release = release)
+
+ async def _run():
+ turns = 0
+
+ async def _control():
+ nonlocal turns
+ for _ in range(_CONTROL_TURNS):
+ await asyncio.sleep(0)
+ turns += 1
+
+ status = asyncio.create_task(inference_route.get_status(current_subject = "test"))
+ control = asyncio.create_task(_control())
+ # Wait without blocking the event loop.
+ started = await asyncio.to_thread(entered.wait, _GUARD_SECONDS)
+ await control
+ # The control task finished while the probe remained blocked.
+ probe_in_flight = not status.done()
+ release.set()
+ response = await asyncio.wait_for(status, timeout = _GUARD_SECONDS)
+ return response, started, turns, probe_in_flight
+
+ response, started, turns, probe_in_flight = asyncio.run(_run())
+
+ assert started, "the probe never ran"
+ assert turns == _CONTROL_TURNS
+ assert probe_in_flight, "the status request finished its probe on the event loop"
+ assert response.llama_cpp_supports_mtp is True
+ assert response.llama_cpp_prebuilt_stale is True
+ assert response.llama_cpp_installed_tag == "b1"
+ assert response.llama_cpp_latest_tag == "b2"
+
+
+def test_overlapping_status_probes_leave_default_executor_for_streaming(monkeypatch):
+ """Slow polls cannot starve the workers that advance local token streams."""
+ _patch_status_dependencies(monkeypatch)
+ entered = threading.Event()
+ release = threading.Event()
+ _patch_slow_probes(monkeypatch, entered = entered, release = release)
+
+ async def _wait_for_probe():
+ deadline = asyncio.get_running_loop().time() + _GUARD_SECONDS
+ while not entered.is_set() and asyncio.get_running_loop().time() < deadline:
+ await asyncio.sleep(0.001)
+ return entered.is_set()
+
+ async def _run():
+ loop = asyncio.get_running_loop()
+ # One worker makes default-executor starvation deterministic. The status
+ # executor remains separate, so two overlapping polls still leave it free.
+ loop.set_default_executor(ThreadPoolExecutor(max_workers = 1))
+ statuses = [
+ asyncio.create_task(inference_route.get_status(current_subject = "test"))
+ for _ in range(2)
+ ]
+ try:
+ started = await _wait_for_probe()
+ token = await asyncio.wait_for(
+ asyncio.to_thread(lambda: "token"), timeout = _GUARD_SECONDS
+ )
+ finally:
+ release.set()
+ responses = await asyncio.gather(*statuses)
+ return started, token, responses
+
+ started, token, responses = asyncio.run(_run())
+
+ assert started, "the status probe never ran"
+ assert token == "token"
+ assert len(responses) == 2
diff --git a/studio/backend/tests/test_llama_cpp_freshness.py b/studio/backend/tests/test_llama_cpp_freshness.py
index 08e1334ac97..0624d6e9e5b 100644
--- a/studio/backend/tests/test_llama_cpp_freshness.py
+++ b/studio/backend/tests/test_llama_cpp_freshness.py
@@ -185,8 +185,70 @@ def test_latest_published_release_uses_disk_cache(monkeypatch):
def test_latest_published_release_returns_none_on_network_failure(monkeypatch):
- monkeypatch.setattr(fr, "_fetch_latest_release_tag", lambda repo, timeout = 5.0: None)
+ calls = []
+
+ def _failed_fetch(repo, timeout = 5.0):
+ calls.append(repo)
+ return None
+
+ monkeypatch.setattr(fr, "_fetch_latest_release_tag", _failed_fetch)
+ assert fr.latest_published_release("unslothai/llama.cpp") is None
assert fr.latest_published_release("unslothai/llama.cpp") is None
+ assert calls == ["unslothai/llama.cpp"]
+
+
+def test_latest_published_release_retries_after_failure_ttl(monkeypatch):
+ wall_now = [1000.0]
+ monotonic_now = [100.0]
+ calls = []
+
+ monkeypatch.setattr(fr._flow.time, "time", lambda: wall_now[0])
+ monkeypatch.setattr(fr._flow.time, "monotonic", lambda: monotonic_now[0])
+
+ def _fetch(repo, timeout = 5.0):
+ calls.append(repo)
+ return None if len(calls) == 1 else "b9999"
+
+ monkeypatch.setattr(fr, "_fetch_latest_release_tag", _fetch)
+ assert fr.latest_published_release("unslothai/llama.cpp") is None
+ assert fr.latest_published_release("unslothai/llama.cpp") is None
+
+ # A wall-clock rollback must not extend this in-process failure TTL.
+ wall_now[0] -= 500
+ monotonic_now[0] += fr._flow.RELEASE_FAILURE_CACHE_TTL_SECONDS + 1
+ assert fr.latest_published_release("unslothai/llama.cpp") == "b9999"
+ assert calls == ["unslothai/llama.cpp", "unslothai/llama.cpp"]
+
+
+def test_latest_published_release_force_refresh_bypasses_failure_ttl(monkeypatch):
+ calls = []
+
+ def _fetch(repo, timeout = 5.0):
+ calls.append(repo)
+ return None if len(calls) == 1 else "b9999"
+
+ monkeypatch.setattr(fr, "_fetch_latest_release_tag", _fetch)
+ assert fr.latest_published_release("unslothai/llama.cpp") is None
+ assert fr.latest_published_release("unslothai/llama.cpp", force_refresh = True) == "b9999"
+ assert fr.latest_published_release("unslothai/llama.cpp") == "b9999"
+ assert calls == ["unslothai/llama.cpp", "unslothai/llama.cpp"]
+
+
+def test_reset_caches_clears_release_failure_memo(monkeypatch):
+ calls = []
+
+ def _failed_fetch(repo, timeout = 5.0):
+ calls.append(repo)
+ return None
+
+ monkeypatch.setattr(fr, "_fetch_latest_release_tag", _failed_fetch)
+ assert fr.latest_published_release("unslothai/llama.cpp") is None
+ assert fr.latest_published_release("unslothai/llama.cpp") is None
+
+ fr.reset_caches()
+
+ assert fr.latest_published_release("unslothai/llama.cpp") is None
+ assert calls == ["unslothai/llama.cpp", "unslothai/llama.cpp"]
def test_latest_published_release_keeps_old_cache_on_transient_failure(monkeypatch, tmp_path):
@@ -196,8 +258,16 @@ def test_latest_published_release_keeps_old_cache_on_transient_failure(monkeypat
cache_file = cache_dir / "unslothai__llama.cpp.json"
yesterday = time.time() - 25 * 60 * 60 # > 24h
cache_file.write_text(json.dumps({"fetched_at": yesterday, "latest_tag": "b9000"}))
- monkeypatch.setattr(fr, "_fetch_latest_release_tag", lambda repo, timeout = 5.0: None)
+ calls = []
+
+ def _failed_fetch(repo, timeout = 5.0):
+ calls.append(repo)
+ return None
+
+ monkeypatch.setattr(fr, "_fetch_latest_release_tag", _failed_fetch)
+ assert fr.latest_published_release("unslothai/llama.cpp") == "b9000"
assert fr.latest_published_release("unslothai/llama.cpp") == "b9000"
+ assert calls == ["unslothai/llama.cpp"]
# check_prebuilt_freshness end-to-end.
diff --git a/studio/backend/utils/llama_cpp_freshness.py b/studio/backend/utils/llama_cpp_freshness.py
index a184fdb3e97..5211b0ced88 100644
--- a/studio/backend/utils/llama_cpp_freshness.py
+++ b/studio/backend/utils/llama_cpp_freshness.py
@@ -33,6 +33,7 @@ _INSTALL_MARKER_NAME = "UNSLOTH_PREBUILT_INFO.json"
_marker_cache: dict[str, Optional[dict]] = {}
_release_memo: dict[str, tuple[float, Optional[str]]] = {}
+_release_failed_at: dict[str, float] = {}
# Newest-release asset sizes (name -> bytes), memoized like the tag (24h TTL).
_assets_memo: dict[str, tuple[float, dict[str, int]]] = {}
@@ -74,12 +75,12 @@ def _fetch_latest_release_tag(repo: str, timeout: float = 5.0) -> Optional[str]:
def latest_published_release(repo: str, *, force_refresh: bool = False) -> Optional[str]:
- """Latest release tag for `repo`. Memo + disk-cached (24h TTL).
- None when offline and never previously cached."""
+ """Latest release tag with 24h success and 60s failure caches."""
return _flow.latest_published_release(
repo,
force_refresh = force_refresh,
memo = _release_memo,
+ failed_at = _release_failed_at,
cache_dir = lambda: _cache_dir(),
fetch = lambda r: _fetch_latest_release_tag(r),
save = lambda r, tag: _save_disk_cache(r, tag),
@@ -232,7 +233,7 @@ def reset_caches(*, drop_disk: bool = False) -> None:
cache makes latest read as None in that offline case, so the banner fails
open (off) instead of pointing at the just-replaced build."""
_flow.reset_caches(
- (_marker_cache, _release_memo, _assets_memo),
+ (_marker_cache, _release_memo, _release_failed_at, _assets_memo),
drop_disk = drop_disk,
cache_dir = lambda: _cache_dir(),
)
diff --git a/studio/backend/utils/prebuilt/freshness_flow.py b/studio/backend/utils/prebuilt/freshness_flow.py
index b90ebf776ce..d441df9653f 100644
--- a/studio/backend/utils/prebuilt/freshness_flow.py
+++ b/studio/backend/utils/prebuilt/freshness_flow.py
@@ -24,6 +24,9 @@ logger = structlog.get_logger(__name__)
# 24h TTL keeps the GitHub call off the hot path and within rate limits.
RELEASE_CACHE_TTL_SECONDS = 24 * 60 * 60
+# Briefly memoize failed lookups so recurring status reads do not retry an
+# unreachable GitHub endpoint on every request.
+RELEASE_FAILURE_CACHE_TTL_SECONDS = 60
def read_install_marker(
@@ -178,29 +181,50 @@ def latest_published_release(
cache_dir: Callable[[], Path],
fetch: Callable[[str], Optional[str]],
save: Callable[[str, Optional[str]], None],
+ failed_at: Optional[dict[str, float]] = None,
) -> Optional[str]:
- """Latest release tag for `repo`. Memo + disk-cached (24h TTL).
- None when offline and never previously cached."""
+ """Latest release tag with optional short-lived failure caching.
+
+ Successes use the 24h memory and disk cache. Supplying ``failed_at`` also
+ caches failures for ``RELEASE_FAILURE_CACHE_TTL_SECONDS``; omitting it keeps
+ retry-on-every-call behavior.
+ """
if not repo:
return None
- now = time.time()
+ # Success timestamps persist to disk and need wall time. Failure timestamps
+ # are process-local and use monotonic time so clock changes cannot extend them.
+ wall_now = time.time()
if not force_refresh:
+ last_failure = failed_at.get(repo) if failed_at is not None else None
+ if (
+ last_failure is not None
+ and time.monotonic() - last_failure < RELEASE_FAILURE_CACHE_TTL_SECONDS
+ ):
+ cached = memo.get(repo)
+ if cached:
+ return cached[1]
+ disk = load_disk_cache(repo, cache_dir())
+ return disk[1] if disk else None
cached = memo.get(repo)
- if cached and now - cached[0] < RELEASE_CACHE_TTL_SECONDS:
+ if cached and wall_now - cached[0] < RELEASE_CACHE_TTL_SECONDS:
return cached[1]
disk = load_disk_cache(repo, cache_dir())
- if disk and now - disk[0] < RELEASE_CACHE_TTL_SECONDS:
+ if disk and wall_now - disk[0] < RELEASE_CACHE_TTL_SECONDS:
memo[repo] = disk
return disk[1]
latest = fetch(repo)
if latest is None:
+ if failed_at is not None:
+ failed_at[repo] = time.monotonic()
# Keep the last-good disk value rather than poison it with None.
disk = load_disk_cache(repo, cache_dir())
if disk:
memo[repo] = disk
return disk[1]
return None
- memo[repo] = (now, latest)
+ if failed_at is not None:
+ failed_at.pop(repo, None)
+ memo[repo] = (wall_now, latest)
save(repo, latest)
return latest