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: avoid repeated llama-server capability probe timeouts (#8317) (#8334)

Ben Younes578f7322b742
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 2cd8a35646d..2ceb0672809 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -3168,6 +3168,13 @@ class LlamaCppBackend:
# llama.cpp" hint in the UI. "binary_no_mtp" / "binary_outdated" ->
# a newer prebuilt would help; "runtime_error" -> it may not.
self._spec_fallback_reason: Optional[str] = None
+ # Whether THIS load ran against a probe that did not answer, rather than one
+ # that answered "no". An inconclusive probe reports every capability absent, so it
+ # silently degrades speculative decoding, the DSpark sidecar and the --kv-unified
+ # slot clamp alike. Separate from _spec_fallback_reason, whose UI banner stays
+ # suppressed for an unresolved probe, so a reload can still be judged worth
+ # retrying (#8317).
+ self._capability_probe_inconclusive: bool = False
self._spec_drafter_kind: Optional[str] = None
self._dspark_sidecar_absent: bool = False
# Set after an auto-Vulkan crash recovers with all devices disabled.
@@ -3981,6 +3988,21 @@ class LlamaCppBackend:
and not spec_owned_by_extra_args
):
return False
+ # Retry a runtime the probe degraded, once the probe starts answering (#8317).
+ # The retry window is worth nothing if Apply keeps deduping against the degraded
+ # runtime, since nothing would re-probe. The slot clamp is the trap:
+ # _requested_n_parallel stores the ASK, so a clamped runtime compares equal and
+ # would never be revisited. One reload, not a loop -- it records the conclusive
+ # probe and clears this flag, so a build that really lacks the capability
+ # re-derives the same runtime and dedupes after. The probe is cached, so it is
+ # free on the only path that reaches it.
+ if (
+ self._capability_probe_inconclusive
+ and not self._is_diffusion
+ and not self.probe_server_capabilities().get("mtp_probe_inconclusive")
+ ):
+ return False
+
compared_draft_n_max = self._spec_draft_n_max
if self._spec_fallback_reason == "runtime_error" and self._last_load_intent is not None:
# The MTP-free recovery clears the runtime value but retains the
@@ -4268,7 +4290,10 @@ class LlamaCppBackend:
return bool(match) and int(match.group(1)) in cls._BROKEN_DSPARK_BUILDS
# Cached on (path, mtime); `unsloth studio update` bumps mtime.
+ _CAPABILITY_PROBE_RETRY_SECONDS = 30.0
_capability_cache: dict[tuple[str, int], dict[str, object]] = {}
+ _capability_retry_after: dict[tuple[str, int], float] = {}
+ _capability_cache_lock = threading.Lock()
@classmethod
def probe_server_capabilities(cls, binary: Optional[str] = None) -> dict[str, object]:
@@ -4316,9 +4341,16 @@ class LlamaCppBackend:
except OSError:
mtime = 0
cache_key = (bin_path, mtime)
- cached = cls._capability_cache.get(cache_key)
- if cached is not None:
- return cached
+ with cls._capability_cache_lock:
+ cached = cls._capability_cache.get(cache_key)
+ if cached is not None:
+ if not cached.get("mtp_probe_inconclusive"):
+ return cached
+ retry_after = cls._capability_retry_after.get(cache_key)
+ if retry_after is not None and time.monotonic() < retry_after:
+ return cached
+ cls._capability_cache.pop(cache_key, None)
+ cls._capability_retry_after.pop(cache_key, None)
mtp_token: Optional[str] = None
supports_dspark = False
@@ -4340,6 +4372,18 @@ class LlamaCppBackend:
help_text = ""
try:
probe_env = cls._llama_server_env_for_binary(bin_path)
+ # Capability detection describes the binary, independently of the
+ # user's launch defaults. In particular, a device selected through
+ # LLAMA_ARG_* becomes invalid when the macOS probe disables Metal.
+ for name in tuple(probe_env):
+ if name.startswith("LLAMA_ARG_"):
+ probe_env.pop(name, None)
+ if sys.platform == "darwin":
+ # Building --help asks llama_supports_rpc(), which otherwise
+ # initializes Metal and compiles its embedded shaders. A cold
+ # compile exceeds this probe's timeout; no device is needed to
+ # enumerate the command-line flags.
+ probe_env["GGML_METAL_DEVICES"] = "0"
result = subprocess.run(
[bin_path, "--help"],
capture_output = True,
@@ -4515,8 +4559,26 @@ class LlamaCppBackend:
"supports_load_mode": supports_load_mode,
"spec_draft_ngl_flag": spec_draft_ngl_flag,
}
- cls._capability_cache[cache_key] = info
- return info
+ with cls._capability_cache_lock:
+ published = cls._capability_cache.get(cache_key)
+ if published is not None and (
+ not published.get("mtp_probe_inconclusive") or mtp_probe_inconclusive
+ ):
+ # Concurrent callers may finish out of order. Never replace a
+ # conclusive result with a timeout, or a newer retry result with
+ # another result of the same confidence.
+ return published
+ cls._capability_cache[cache_key] = info
+ if mtp_probe_inconclusive:
+ # Bound both failure modes: do not pin a transient failure for
+ # the process lifetime, and do not make every caller repeat a
+ # 10-second timeout while a persistent failure remains (#8317).
+ cls._capability_retry_after[cache_key] = (
+ time.monotonic() + cls._CAPABILITY_PROBE_RETRY_SECONDS
+ )
+ else:
+ cls._capability_retry_after.pop(cache_key, None)
+ return info
@staticmethod
def _mtp_token_from_spec_help(spec_help: str) -> Optional[str]:
@@ -7976,6 +8038,7 @@ class LlamaCppBackend:
hf_token: Optional[str] = None,
near_path: Optional[str] = None,
binary: Optional[str] = None,
+ caps_probe: Optional[Callable[[Optional[str]], dict]] = None,
) -> Optional[str]:
"""Download the published DSpark sidecar, preferring its Q8_0 copy.
@@ -7983,7 +8046,13 @@ class LlamaCppBackend:
``draft-dspark`` (every prebuilt in the known-broken window included) falls
back, so the download would never be opened. A raised probe still fetches,
since launch re-probes and may yet engage.
+
+ ``caps_probe`` is the caller's accumulator: this gate shapes the launch, and a
+ guess here has to latch like any other, or a load that skipped the sidecar on an
+ inconclusive probe looks conclusive once the retry window lapses mid-download.
"""
+ if caps_probe is None:
+ caps_probe = self.probe_server_capabilities
def _pick_dspark(candidates: list[str]) -> Optional[str]:
from utils.models.model_config import dspark_preference_key
@@ -8000,7 +8069,7 @@ class LlamaCppBackend:
cache_dir = _hub_cache_dir_for_snapshot_path(near_path),
)
try:
- if not self.probe_server_capabilities(binary).get("supports_dspark"):
+ if not caps_probe(binary).get("supports_dspark"):
logger.warning(
"Skipping the DSpark sidecar download: llama-server has no usable "
"--spec-type draft-dspark, so this load falls back to no speculative "
@@ -9425,6 +9494,20 @@ class LlamaCppBackend:
# Resolve llama-server now but defer a not-found error: a block-diffusion
# GGUF uses the diffusion runner, and its arch is only known after the header.
binary = self._find_llama_server_binary()
+
+ # Every capability answer shaping this launch, latching whether any was a
+ # guess. Accumulated, not sampled: the decisions straddle the whole load (slot
+ # clamp before an HF download, command build after), and with a 30s window a
+ # later success would otherwise erase an earlier one that already degraded it.
+ _launch_probe_inconclusive = False
+
+ def _launch_caps(bin_path):
+ nonlocal _launch_probe_inconclusive
+ caps = self.probe_server_capabilities(bin_path)
+ if caps.get("mtp_probe_inconclusive"):
+ _launch_probe_inconclusive = True
+ return caps
+
is_vulkan_backend = self._is_vulkan_backend(binary)
_vulkan_ordinal_pin = (
is_vulkan_backend and bool(gpu_ids) and gpu_ids_are_vulkan_ordinals is not False
@@ -9437,11 +9520,7 @@ class LlamaCppBackend:
# build lacking the flag the default of 4 would quarter every context window for a
# feature it cannot serve: fall back to one slot. Ahead of the KV estimates so the
# fit matches what launches.
- if (
- n_parallel > 1
- and binary
- and not self.probe_server_capabilities(binary).get("supports_kv_unified")
- ):
+ if n_parallel > 1 and binary and not _launch_caps(binary).get("supports_kv_unified"):
logger.warning(
"llama-server at %s has no --kv-unified, so %d parallel slots would "
"split the context window %d ways. Using 1 slot instead; update "
@@ -9610,6 +9689,7 @@ class LlamaCppBackend:
hf_token = hf_token,
near_path = model_path,
binary = binary,
+ caps_probe = _launch_caps,
)
elif gguf_path:
if not Path(gguf_path).is_file():
@@ -9633,7 +9713,7 @@ class LlamaCppBackend:
and not _extra_args_set_spec_type(extra_args)
):
try:
- if self.probe_server_capabilities(binary).get("supports_dspark"):
+ if _launch_caps(binary).get("supports_dspark"):
_spec_canon = "dspark"
logger.info("Auto: DSpark sidecar available, using draft-dspark.")
except Exception as exc:
@@ -9703,7 +9783,7 @@ class LlamaCppBackend:
# same message remote validation already shows.
raise LlamaServerNotFoundError(LLAMA_SERVER_NOT_FOUND_DETAIL)
- server_caps = self.probe_server_capabilities(binary)
+ server_caps = _launch_caps(binary)
# Outside ``self._lock`` so /unload, /cancel, /status aren't
# blocked. ``unload_model`` also records the kill, so the
@@ -10114,7 +10194,7 @@ class LlamaCppBackend:
_mtp_probe_raised = False
if not _user_mtp_via_extras:
try:
- _fit_caps = self.probe_server_capabilities(binary) or {}
+ _fit_caps = _launch_caps(binary) or {}
_mtp_binary_ok = bool(
_fit_caps.get("supports_dspark")
if _mtp_effective == "dspark"
@@ -11035,7 +11115,7 @@ class LlamaCppBackend:
if n_ubatch is not None:
cmd.extend(["--ubatch-size", str(n_ubatch)])
- server_caps = self.probe_server_capabilities(binary)
+ server_caps = _launch_caps(binary)
# Report a clean public model id (matching GET /v1/models) rather
# than the raw -m path in llama-server's own /v1/models and the
@@ -12589,6 +12669,11 @@ class LlamaCppBackend:
self._requested_n_ctx = int(n_ctx)
# Local n_parallel may have been reduced above; the snapshot has the ask.
self._requested_n_parallel = max(1, int(intent.n_parallel))
+ # Commit with the rest of the known-good state: only a launch that got
+ # this far replaced the runtime, so a rejected preflight leaves the old
+ # marker intact, and the diffusion runner returns well before it without
+ # consuming, or paying for, any llama-server capability.
+ self._capability_probe_inconclusive = _launch_probe_inconclusive
self._requested_n_batch = intent.n_batch
self._requested_n_ubatch = intent.n_ubatch
# Commit the known-good snapshot + whether MTP+tensor is live, then
@@ -13235,6 +13320,7 @@ class LlamaCppBackend:
self._mtp_draft_path = None
self._mtp_draft_suppressed_path = None
self._spec_fallback_reason = None
+ self._capability_probe_inconclusive = False
self._spec_drafter_kind = None
self._dspark_sidecar_absent = False
self._cpu_fallback_reason = None
diff --git a/studio/backend/tests/test_llama_cpp_mtp_detection.py b/studio/backend/tests/test_llama_cpp_mtp_detection.py
index 9b23441c391..958588b2f33 100644
--- a/studio/backend/tests/test_llama_cpp_mtp_detection.py
+++ b/studio/backend/tests/test_llama_cpp_mtp_detection.py
@@ -777,7 +777,9 @@ _NEEDS_BASH = pytest.mark.skipif(
def _clear_caps_cache():
- LlamaCppBackend._capability_cache.clear()
+ with LlamaCppBackend._capability_cache_lock:
+ LlamaCppBackend._capability_cache.clear()
+ LlamaCppBackend._capability_retry_after.clear()
@_NEEDS_BASH
@@ -842,8 +844,13 @@ def test_probe_server_capabilities_uses_binary_library_env(tmp_path, monkeypatch
monkeypatch.setattr(
"core.inference.llama_cpp.child_env_without_native_path_secret",
- lambda: {"LD_LIBRARY_PATH": "/already-there"},
+ lambda: {
+ "LD_LIBRARY_PATH": "/already-there",
+ "LLAMA_ARG_DEVICE": "MTL0",
+ "LLAMA_ARG_OVERRIDE_TENSOR": ".*=MTL0",
+ },
)
+ monkeypatch.setattr("core.inference.llama_cpp.sys.platform", "darwin")
def fake_run(cmd, **kwargs):
captured["cmd"] = cmd
@@ -861,11 +868,36 @@ def test_probe_server_capabilities_uses_binary_library_env(tmp_path, monkeypatch
assert caps["supports_mtp"] is True
assert captured["cmd"] == [str(fake), "--help"]
assert captured["env"] is not None
+ assert captured["env"]["GGML_METAL_DEVICES"] == "0"
+ assert not any(name.startswith("LLAMA_ARG_") for name in captured["env"])
ld_dirs = captured["env"]["LD_LIBRARY_PATH"].split(os.pathsep)
assert str(fake.parent) in ld_dirs
assert "/already-there" in ld_dirs
+@_NEEDS_BASH
+def test_probe_server_capabilities_does_not_disable_devices_off_macos(tmp_path, monkeypatch):
+ fake = _make_fake_llama_server(
+ tmp_path / "llama-server",
+ "--spec-type none,mtp,ngram-simple\n",
+ )
+ captured = {}
+ monkeypatch.setattr("core.inference.llama_cpp.child_env_without_native_path_secret", dict)
+ monkeypatch.setattr("core.inference.llama_cpp.sys.platform", "linux")
+
+ def fake_run(_cmd, **kwargs):
+ captured["env"] = kwargs.get("env")
+ return _types.SimpleNamespace(
+ stdout = "--spec-type none,mtp,ngram-simple\n", stderr = "", returncode = 0
+ )
+
+ monkeypatch.setattr("core.inference.llama_cpp.subprocess.run", fake_run)
+ _clear_caps_cache()
+ LlamaCppBackend.probe_server_capabilities(str(fake))
+
+ assert "GGML_METAL_DEVICES" not in captured["env"]
+
+
@_NEEDS_BASH
def test_probe_server_capabilities_detects_renamed_mtp(tmp_path):
# Renamed upstream: draft-mtp -> mtp.
@@ -2599,3 +2631,655 @@ def test_probe_reports_no_draft_ngl_flag_when_the_build_has_neither(tmp_path):
neither = _make_fake_llama_server(tmp_path / "neither", "usage: llama-server\n\n--parallel N\n")
_clear_caps_cache()
assert LlamaCppBackend.probe_server_capabilities(str(neither))["spec_draft_ngl_flag"] is None
+
+
+@_NEEDS_BASH
+def test_inconclusive_probe_retries_after_a_bounded_cache_window(tmp_path, monkeypatch):
+ """A transient timeout may not be pinned for the whole process, while a
+ persistent failure may not make every capability caller wait again (#8317)."""
+ import subprocess as _subprocess
+
+ fake = _make_fake_llama_server(
+ tmp_path / "llama-server",
+ "--spec-type none,draft-mtp,ngram-mod",
+ )
+ _clear_caps_cache()
+ now = [100.0]
+ calls = []
+
+ def _run(cmd, **kwargs):
+ calls.append(cmd)
+ if len(calls) <= 2:
+ raise _subprocess.TimeoutExpired(cmd, kwargs.get("timeout", 10))
+ return _types.SimpleNamespace(
+ stdout = "--spec-type none,draft-mtp,ngram-mod\n",
+ stderr = "",
+ returncode = 0,
+ )
+
+ monkeypatch.setattr("core.inference.llama_cpp.subprocess.run", _run)
+ monkeypatch.setattr("core.inference.llama_cpp.time.monotonic", lambda: now[0])
+ first = LlamaCppBackend.probe_server_capabilities(str(fake))
+ assert first["mtp_probe_inconclusive"] is True
+ assert first["supports_mtp"] is False
+
+ # Immediate callers reuse the inconclusive answer instead of each paying
+ # the subprocess timeout again.
+ second = LlamaCppBackend.probe_server_capabilities(str(fake))
+ assert second is first
+ assert len(calls) == 1
+
+ # Every failed retry receives a fresh bounded window; persistent failures
+ # still do not make every caller pay the subprocess timeout.
+ now[0] += LlamaCppBackend._CAPABILITY_PROBE_RETRY_SECONDS + 1
+ retried = LlamaCppBackend.probe_server_capabilities(str(fake))
+ assert retried["mtp_probe_inconclusive"] is True
+ assert len(calls) == 2
+ assert LlamaCppBackend.probe_server_capabilities(str(fake)) is retried
+ assert len(calls) == 2
+
+ # Once a later retry succeeds, the result returns to the normal long-lived
+ # cache.
+ now[0] += LlamaCppBackend._CAPABILITY_PROBE_RETRY_SECONDS + 1
+ recovered = LlamaCppBackend.probe_server_capabilities(str(fake))
+ assert recovered["mtp_probe_inconclusive"] is False
+ assert recovered["supports_mtp"] is True
+ assert len(calls) == 3
+ assert LlamaCppBackend.probe_server_capabilities(str(fake)) is recovered
+ assert len(calls) == 3
+
+
+@_NEEDS_BASH
+def test_concurrent_timeout_cannot_overwrite_a_successful_probe(tmp_path, monkeypatch):
+ """A late, lower-confidence result may not replace a conclusive result."""
+ import subprocess as _subprocess
+ import threading as _threading
+
+ fake = _make_fake_llama_server(
+ tmp_path / "llama-server",
+ "--spec-type none,draft-mtp,ngram-mod",
+ )
+ _clear_caps_cache()
+ barrier = _threading.Barrier(2)
+ assignment_lock = _threading.Lock()
+ success_published = _threading.Event()
+ call_ids = []
+ results = []
+
+ def _run(cmd, **kwargs):
+ with assignment_lock:
+ call_id = len(call_ids)
+ call_ids.append(call_id)
+ barrier.wait(timeout = 2)
+ if call_id == 0:
+ return _types.SimpleNamespace(
+ stdout = "--spec-type none,draft-mtp,ngram-mod\n",
+ stderr = "",
+ returncode = 0,
+ )
+ assert success_published.wait(timeout = 2)
+ raise _subprocess.TimeoutExpired(cmd, kwargs.get("timeout", 10))
+
+ def _probe():
+ result = LlamaCppBackend.probe_server_capabilities(str(fake))
+ results.append(result)
+ if not result["mtp_probe_inconclusive"]:
+ success_published.set()
+
+ monkeypatch.setattr("core.inference.llama_cpp.subprocess.run", _run)
+ threads = [_threading.Thread(target = _probe) for _ in range(2)]
+ for thread in threads:
+ thread.start()
+ for thread in threads:
+ thread.join(timeout = 3)
+
+ assert not any(thread.is_alive() for thread in threads)
+ assert len(call_ids) == 2
+ assert len(results) == 2
+ assert all(result["supports_mtp"] for result in results)
+ cached = LlamaCppBackend.probe_server_capabilities(str(fake))
+ assert cached["supports_mtp"] is True
+ assert cached["mtp_probe_inconclusive"] is False
+
+
+@_NEEDS_BASH
+def test_a_conclusive_probe_is_never_expired_by_the_retry_window(tmp_path, monkeypatch):
+ """Only the inconclusive answer is time-bounded. A conclusive one describes the
+ binary, which cannot change while its mtime holds, so applying the retry window to it
+ too would re-run --help forever on a perfectly healthy install (#8317)."""
+ fake = _make_fake_llama_server(
+ tmp_path / "llama-server",
+ "--spec-type none,draft-mtp,ngram-mod",
+ )
+ _clear_caps_cache()
+ now = [100.0]
+ calls = []
+
+ def _run(cmd, **kwargs):
+ calls.append(cmd)
+ return _types.SimpleNamespace(
+ stdout = "--spec-type none,draft-mtp,ngram-mod\n",
+ stderr = "",
+ returncode = 0,
+ )
+
+ monkeypatch.setattr("core.inference.llama_cpp.subprocess.run", _run)
+ monkeypatch.setattr("core.inference.llama_cpp.time.monotonic", lambda: now[0])
+
+ first = LlamaCppBackend.probe_server_capabilities(str(fake))
+ assert first["supports_mtp"] is True
+ assert len(calls) == 1
+
+ now[0] += LlamaCppBackend._CAPABILITY_PROBE_RETRY_SECONDS * 100
+ again = LlamaCppBackend.probe_server_capabilities(str(fake))
+ assert again is first
+ assert len(calls) == 1, "a conclusive probe must not be re-run once cached"
+
+
+@_NEEDS_BASH
+def test_a_hanging_binary_is_probed_once_per_model_load(tmp_path, monkeypatch):
+ """The cost half of #8317, stated as the caller sees it. One model load makes seven
+ capability calls; a binary that hangs for a permanent reason must pay the --help
+ timeout once across all of them, not once each."""
+ import subprocess as _subprocess
+
+ fake = _make_fake_llama_server(tmp_path / "llama-server", "--spec-type none,draft-mtp")
+ _clear_caps_cache()
+ now = [100.0]
+ calls = []
+
+ def _run(cmd, **kwargs):
+ calls.append(cmd)
+ raise _subprocess.TimeoutExpired(cmd, kwargs.get("timeout", 10))
+
+ monkeypatch.setattr("core.inference.llama_cpp.subprocess.run", _run)
+ monkeypatch.setattr("core.inference.llama_cpp.time.monotonic", lambda: now[0])
+
+ # probe_server_capabilities call sites reached by a single load:
+ # llama_cpp.py 8003, 9443, 9636, 9706, 10117, 11038, 12786.
+ for _ in range(7):
+ LlamaCppBackend.probe_server_capabilities(str(fake))
+ assert len(calls) == 1, f"expected one --help per load, got {len(calls)}"
+
+
+@_NEEDS_BASH
+def test_a_missing_binary_is_not_cached_so_it_is_seen_as_soon_as_it_lands(tmp_path):
+ """The found:False early return sits above the cache and costs a stat rather than a
+ subprocess, so it must stay uncached: an install finishing mid-session has to be
+ picked up without a Studio restart."""
+ binary = tmp_path / "llama-server"
+ _clear_caps_cache()
+
+ absent = LlamaCppBackend.probe_server_capabilities(str(binary))
+ assert absent["found"] is False
+ assert LlamaCppBackend._capability_cache == {}
+
+ _make_fake_llama_server(binary, "--spec-type none,draft-mtp,ngram-mod")
+ present = LlamaCppBackend.probe_server_capabilities(str(binary))
+ assert present["found"] is True
+ assert present["supports_mtp"] is True
+
+
+def _inconclusive_fallback_backend():
+ """A backend that asked for MTP, got an inconclusive probe, and launched without
+ speculative decoding. _spec_fallback_reason stays None so the UI banner is suppressed."""
+ return _mtp_backend(
+ _speculative_type = "default",
+ _spec_fallback_reason = None,
+ _capability_probe_inconclusive = True,
+ _gguf_path = None,
+ )
+
+
+def _same_settings_apply():
+ """Apply pressed again with the settings the fallback load already used. The identifier
+ has to be the fixture's own, or the reuse check refuses on identity and every assertion
+ below passes without ever reaching the speculative branch."""
+ return dict(
+ model_identifier = "unsloth/Qwen3.6-27B-MTP-GGUF",
+ hf_variant = "Q4_K_M",
+ n_ctx = 8192,
+ cache_type_kv = None,
+ speculative_type = "auto",
+ chat_template_override = None,
+ extra_args = None,
+ is_vision = False,
+ gguf_path = None,
+ )
+
+
+def _stub_caps(monkeypatch, **caps):
+ monkeypatch.setattr(
+ LlamaCppBackend,
+ "probe_server_capabilities",
+ classmethod(lambda cls, binary = None: caps),
+ )
+
+
+def test_apply_reloads_once_an_inconclusive_probe_starts_answering(monkeypatch):
+ # The retry window is worth nothing if Apply dedupes against the fallback: nothing
+ # re-probes, so MTP stays off for the life of the process, which is the symptom the
+ # window exists to end (#8317).
+ _stub_caps(
+ monkeypatch,
+ found = True,
+ mtp_token = "draft-mtp",
+ supports_mtp = True,
+ mtp_probe_inconclusive = False,
+ )
+ assert _matches(_inconclusive_fallback_backend(), **_same_settings_apply()) is False
+
+
+def test_apply_still_dedupes_while_the_probe_keeps_hanging(monkeypatch):
+ # A binary that hangs for a permanent reason must not relaunch an identical server on
+ # every Apply. Only a probe that has actually turned conclusive earns the reload.
+ _stub_caps(
+ monkeypatch,
+ found = True,
+ mtp_token = None,
+ supports_mtp = False,
+ mtp_probe_inconclusive = True,
+ )
+ assert _matches(_inconclusive_fallback_backend(), **_same_settings_apply()) is True
+
+
+def test_apply_reloads_once_even_when_the_build_turns_out_to_have_no_mtp(monkeypatch):
+ # Conclusive-and-negative still earns exactly one reload: the degradation has to be
+ # re-derived from a real answer rather than from a probe that never returned. That
+ # reload records the conclusive probe, clearing the flag, so it does not loop.
+ _stub_caps(
+ monkeypatch,
+ found = True,
+ mtp_token = None,
+ supports_mtp = False,
+ mtp_probe_inconclusive = False,
+ )
+ assert _matches(_inconclusive_fallback_backend(), **_same_settings_apply()) is False
+ # Cleared flag (what the reload leaves behind) dedupes from then on.
+ settled = _mtp_backend(_speculative_type = "default", _gguf_path = None)
+ assert settled._capability_probe_inconclusive is False
+ assert _matches(settled, **_same_settings_apply()) is True
+
+
+def test_a_slot_clamp_from_an_inconclusive_probe_is_also_retried(monkeypatch):
+ # An inconclusive probe reports --kv-unified absent too, so n_parallel is clamped to
+ # 1 while _requested_n_parallel keeps the ASK. The two then compare equal and Apply
+ # would never restore the slots once the probe recovers. No speculative decoding is
+ # involved, so the spec-only version of this guard missed it entirely.
+ _stub_caps(
+ monkeypatch,
+ found = True,
+ mtp_token = "draft-mtp",
+ supports_mtp = True,
+ supports_kv_unified = True,
+ mtp_probe_inconclusive = False,
+ )
+ clamped = _mtp_backend(
+ _speculative_type = "default",
+ _capability_probe_inconclusive = True,
+ _requested_n_parallel = 4,
+ _gguf_path = None,
+ )
+ assert _matches(clamped, n_parallel = 4, **_same_settings_apply()) is False
+
+
+def test_the_probe_marker_is_committed_only_once_the_runtime_is_replaced():
+ """The marker describes the RUNNING runtime, so load_model must not write it before
+ the launch is committed.
+
+ Two early exits sit between the probe and the commit and both leave the old server
+ up: the Vulkan-ordinal preflight rejects an invalid GPU selection, and a diffusion
+ load returns through _start_diffusion_server without using any llama-server
+ capability. Writing the marker early would clear it for a runtime that is still
+ degraded, or set it on a diffusion runner that would then be torn down and reloaded
+ for no reason. Checked structurally because load_model is not unit-callable.
+ """
+ import ast
+ import inspect
+
+ from core.inference import llama_cpp as mod
+
+ source = inspect.getsource(mod)
+ tree = ast.parse(source)
+ load_model = next(
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, ast.FunctionDef) and node.name == "load_model"
+ )
+
+ writes = [
+ node.lineno
+ for node in ast.walk(load_model)
+ for target in getattr(node, "targets", [])
+ if isinstance(node, ast.Assign)
+ and isinstance(target, ast.Attribute)
+ and target.attr == "_capability_probe_inconclusive"
+ ]
+ assert len(writes) == 1, f"expected one commit-point write, found {len(writes)}"
+
+ diffusion_returns = [
+ node.lineno
+ for node in ast.walk(load_model)
+ if isinstance(node, ast.Return)
+ and isinstance(node.value, ast.Call)
+ and isinstance(node.value.func, ast.Attribute)
+ and node.value.func.attr == "_start_diffusion_server"
+ ]
+ assert diffusion_returns, "the diffusion early return moved; re-pin this test"
+ assert writes[0] > max(diffusion_returns), (
+ "the marker is written before the diffusion early return, so a diffusion runner "
+ "would carry it and be reloaded once the probe recovers"
+ )
+
+
+def test_a_diffusion_runtime_is_never_reloaded_by_the_capability_recovery(monkeypatch):
+ # A diffusion runner consumes no llama-server capability, so it cannot be degraded by
+ # one. A marker left over from an earlier llama-server load must not make every
+ # otherwise identical diffusion Apply tear it down and start it again.
+ _stub_caps(
+ monkeypatch,
+ found = True,
+ mtp_token = "draft-mtp",
+ supports_mtp = True,
+ mtp_probe_inconclusive = False,
+ )
+ diffusion = _mtp_backend(
+ _speculative_type = "default",
+ _capability_probe_inconclusive = True,
+ _is_diffusion = True,
+ _gguf_path = None,
+ )
+ assert _matches(diffusion, **_same_settings_apply()) is True
+ # The same stale marker on a llama-server runtime still earns its reload.
+ assert _matches(_inconclusive_fallback_backend(), **_same_settings_apply()) is False
+
+
+def test_unload_clears_the_capability_marker():
+ # Otherwise it outlives the runtime it describes and follows the next load in.
+ backend = _mtp_backend(_capability_probe_inconclusive = True)
+ backend._process = None
+ backend.unload_model()
+ assert backend._capability_probe_inconclusive is False
+
+
+def test_a_diffusion_load_never_pays_for_the_capability_probe():
+ # The probe is read at the snapshot commit, which a diffusion load returns long
+ # before. Reading it beside the capability gates instead made an independent
+ # diffusion launch wait out the full --help timeout this change exists to bound.
+ import ast
+ import inspect
+
+ from core.inference import llama_cpp as mod
+
+ load_model = next(
+ node
+ for node in ast.walk(ast.parse(inspect.getsource(mod)))
+ if isinstance(node, ast.FunctionDef) and node.name == "load_model"
+ )
+ # In-load probes go through the accumulating _launch_caps helper, so count both it
+ # and any direct call.
+ probe_calls = [
+ node.lineno
+ for node in ast.walk(load_model)
+ if isinstance(node, ast.Call)
+ and (
+ (isinstance(node.func, ast.Attribute) and node.func.attr == "probe_server_capabilities")
+ or (isinstance(node.func, ast.Name) and node.func.id == "_launch_caps")
+ )
+ ]
+ diffusion_return = max(
+ node.lineno
+ for node in ast.walk(load_model)
+ if isinstance(node, ast.Return)
+ and isinstance(node.value, ast.Call)
+ and isinstance(node.value.func, ast.Attribute)
+ and node.value.func.attr == "_start_diffusion_server"
+ )
+ # The probes that legitimately sit above the diffusion return are the pre-existing
+ # ones, and every one of them is guarded by the feature that needs it (the
+ # --kv-unified clamp behind n_parallel > 1, the DSpark lookup behind its own request),
+ # so a diffusion load short-circuits past them. An unconditional probe added up there
+ # would make an independent diffusion launch wait out the full --help timeout.
+ guarded = {
+ node.lineno
+ for branch in ast.walk(load_model)
+ if isinstance(branch, ast.If)
+ for node in ast.walk(branch)
+ if isinstance(node, ast.Call)
+ and (
+ (isinstance(node.func, ast.Attribute) and node.func.attr == "probe_server_capabilities")
+ or (isinstance(node.func, ast.Name) and node.func.id == "_launch_caps")
+ )
+ }
+ helper_body = {
+ node.lineno
+ for fn in ast.walk(load_model)
+ if isinstance(fn, ast.FunctionDef) and fn.name == "_launch_caps"
+ for node in ast.walk(fn)
+ if isinstance(node, ast.Call)
+ }
+ unconditional = [
+ ln
+ for ln in probe_calls
+ if ln < diffusion_return and ln not in guarded and ln not in helper_body
+ ]
+ assert unconditional == [], (
+ f"unguarded probe calls above the diffusion return: {unconditional}; a diffusion "
+ "load must not pay for a capability it never consumes"
+ )
+
+
+def test_the_marker_comes_from_the_launch_snapshot_not_a_probe_after_startup():
+ """The marker must describe the probe that BUILT the command, not one taken after the
+ server is up.
+
+ _wait_for_health allows up to 600s, and the retry window is 30s, so a large model's
+ startup expires the inconclusive entry many times over. Re-probing at the commit point
+ would then record False for a server that was launched without speculative decoding or
+ unified KV slots, and every identical Apply would dedupe against that degraded runtime
+ for good -- the original bug, reintroduced. Checked structurally because load_model is
+ not unit-callable.
+ """
+ import ast
+ import inspect
+
+ from core.inference import llama_cpp as mod
+
+ load_model = next(
+ node
+ for node in ast.walk(ast.parse(inspect.getsource(mod)))
+ if isinstance(node, ast.FunctionDef) and node.name == "load_model"
+ )
+
+ commit = next(
+ node
+ for node in ast.walk(load_model)
+ if isinstance(node, ast.Assign)
+ and any(
+ isinstance(t, ast.Attribute) and t.attr == "_capability_probe_inconclusive"
+ for t in node.targets
+ )
+ )
+ # The committed value must be a plain name pinned earlier, never a live probe call.
+ assert isinstance(commit.value, ast.Name), (
+ "the marker is computed at the commit point; it must be pinned from the snapshot "
+ "that built the launch command instead"
+ )
+
+ health_waits = [
+ node.lineno
+ for node in ast.walk(load_model)
+ if isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Attribute)
+ and node.func.attr == "_wait_for_health"
+ ]
+ pins = [
+ node.lineno
+ for node in ast.walk(load_model)
+ if isinstance(node, ast.Assign)
+ and any(isinstance(t, ast.Name) and t.id == commit.value.id for t in node.targets)
+ ]
+ assert pins, "the pinned local vanished; re-pin this test"
+ assert health_waits, "the startup health wait moved; re-pin this test"
+ assert min(pins) < min(health_waits), (
+ "the capability snapshot is pinned after the startup wait, so a slow load can "
+ "still record a probe that is not the one the server was launched with"
+ )
+
+
+def test_a_later_successful_probe_cannot_erase_an_earlier_degrading_one():
+ """The launch's capability decisions are spread across the whole load, and the retry
+ window is 30s. The slot clamp runs before an HF download; the command is built after
+ it. Sampling one probe lets a later success erase the fact that an earlier one already
+ clamped the slots, so the marker has to accumulate.
+
+ Exercised on the accumulator itself: driving load_model would need a real download.
+ """
+ import ast
+ import inspect
+
+ from core.inference import llama_cpp as mod
+
+ load_model = next(
+ node
+ for node in ast.walk(ast.parse(inspect.getsource(mod)))
+ if isinstance(node, ast.FunctionDef) and node.name == "load_model"
+ )
+ helper = next(
+ (
+ node
+ for node in ast.walk(load_model)
+ if isinstance(node, ast.FunctionDef) and node.name == "_launch_caps"
+ ),
+ None,
+ )
+ assert helper is not None, "the accumulating probe helper vanished; re-pin this test"
+
+ # It must only ever latch True, never assign the raw probe result.
+ assigns = [
+ node
+ for node in ast.walk(helper)
+ if isinstance(node, ast.Assign)
+ and any(
+ isinstance(t, ast.Name) and t.id == "_launch_probe_inconclusive" for t in node.targets
+ )
+ ]
+ assert assigns, "the helper no longer records the probe state"
+ for node in assigns:
+ assert isinstance(node.value, ast.Constant) and node.value.value is True, (
+ "the helper assigns the probe result directly; a later conclusive probe would "
+ "then erase an earlier degrading one"
+ )
+
+ # And nothing outside it may overwrite the accumulator mid-load.
+ outside = [
+ node.lineno
+ for node in ast.walk(load_model)
+ if isinstance(node, ast.Assign)
+ and any(
+ isinstance(t, ast.Name) and t.id == "_launch_probe_inconclusive" for t in node.targets
+ )
+ and not (helper.lineno <= node.lineno <= (helper.end_lineno or helper.lineno))
+ ]
+ assert (
+ len(outside) == 1
+ ), f"expected only the initialisation outside the helper, found {outside}"
+
+
+def test_the_accumulator_latches_across_probes():
+ """Behavioural check of the same property, on a stand-in with the helper's shape."""
+ state = {"inconclusive": False}
+
+ def launch_caps(caps):
+ if caps.get("mtp_probe_inconclusive"):
+ state["inconclusive"] = True
+ return caps
+
+ launch_caps({"mtp_probe_inconclusive": True}) # slot clamp, probe timed out
+ launch_caps({"mtp_probe_inconclusive": False}) # command build, probe recovered
+ assert state["inconclusive"] is True, "a later success must not erase the earlier guess"
+
+
+def test_the_dspark_pre_download_gate_latches_into_the_launch_accumulator():
+ """The sidecar gate shapes the launch as much as the slot clamp does: an inconclusive
+ probe there skips an ~11 GB drafter, so that load ran degraded. It sits before a
+ download that can outlast the 30s retry window, so if it probes on its own the later
+ launch probe can come back conclusive and the load is remembered as a good one --
+ every identical Apply after it then dedupes against a server with no drafter.
+ """
+ import ast
+ import inspect
+
+ from core.inference import llama_cpp as mod
+
+ tree = ast.parse(inspect.getsource(mod))
+ download = next(
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, ast.FunctionDef) and node.name == "_download_dspark"
+ )
+ direct = [
+ node.lineno
+ for node in ast.walk(download)
+ if isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Attribute)
+ and node.func.attr == "probe_server_capabilities"
+ ]
+ assert direct == [], (
+ f"_download_dspark probes directly at {direct}; route it through the caller's "
+ "accumulator so a guess there is not forgotten"
+ )
+
+ load_model = next(
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, ast.FunctionDef) and node.name == "load_model"
+ )
+ call = next(
+ node
+ for node in ast.walk(load_model)
+ if isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Attribute)
+ and node.func.attr == "_download_dspark"
+ )
+ passed = {
+ kw.value.id
+ for kw in call.keywords
+ if kw.arg == "caps_probe" and isinstance(kw.value, ast.Name)
+ }
+ assert passed == {
+ "_launch_caps"
+ }, "load_model must hand _download_dspark the accumulating probe helper"
+
+
+def test_the_dspark_gate_uses_the_probe_it_is_given():
+ """Behavioural half: the injected probe is the one consulted, and its verdict still
+ drives the skip. A default is kept so the direct callers in the tests and the CLI
+ keep working unchanged.
+ """
+ import inspect
+
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ signature = inspect.signature(LlamaCppBackend._download_dspark)
+ default = signature.parameters["caps_probe"].default
+ assert default is None, "caps_probe must stay optional for the standalone callers"
+
+ seen = []
+
+ def probe(binary):
+ seen.append(binary)
+ return {"supports_dspark": False, "mtp_probe_inconclusive": True}
+
+ server = LlamaCppBackend.__new__(LlamaCppBackend)
+ result = LlamaCppBackend._download_dspark(
+ server,
+ hf_repo = "unsloth/does-not-matter",
+ near_path = None,
+ binary = "/nonexistent/llama-server",
+ caps_probe = probe,
+ )
+ assert seen == ["/nonexistent/llama-server"], "the injected probe was not consulted"
+ # No sidecar on disk and an incapable binary: the fetch is skipped, which is exactly
+ # the degraded launch the accumulator has to remember.
+ assert result is None