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: honor a cancelled load inside the llama-server health wait
Nilay5be8f37dcf3f
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 623f3f624b5..274b01a2136 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -462,12 +462,41 @@ class LlamaServerNotFoundError(RuntimeError):__slots__ = ()+class GgufDownloadCancelled(RuntimeError):+ """Expected signal from a cancelled GGUF download."""++ __slots__ = ()++class _LlamaStreamCancelled(Exception):"""Internal signal for an expected client/request cancellation."""__slots__ = ()+class _CombinedCancelEvent:+ __slots__ = ("_events",)++ def __init__(self, *events: threading.Event):+ self._events = events++ def is_set(self) -> bool:+ return any(event.is_set() for event in self._events)++ def wait(self, timeout: Optional[float] = None) -> bool:+ if self.is_set():+ return True+ deadline = None if timeout is None else time.monotonic() + max(0.0, timeout)+ while True:+ remaining = None if deadline is None else deadline - time.monotonic()+ if remaining is not None and remaining <= 0:+ return self.is_set()+ pause = 0.05 if remaining is None else min(0.05, remaining)+ self._events[0].wait(pause)+ if self.is_set():+ return True++# Deliberately NOT ``slots=True``: it drops ``__dict__``, so ``vars(intent)`` raises and# every GGUF load breaks. Reflection over this dataclass is part of how it is used.@dataclass(frozen = True)@@ -12549,6 +12578,7 @@ class LlamaCppBackend:gpu_ids: Optional[List[int]] = None,gpu_memory_mode: Literal["auto", "manual"] = "auto",gpu_layers: int = -1,+ cancelled: Optional[Callable[[], bool]] = None,) -> bool:"""Launch the OpenAI-compat diffusion shim (which drives the on-devicevisual decoder) and wait for health. Presents the same /v1 + /health@@ -12782,7 +12812,7 @@ class LlamaCppBackend:self._effective_context_length = maxtok or self._context_lengthself._max_context_length = self._context_length or maxtok or None- healthy = self._wait_for_health(timeout = 600.0)+ healthy = self._wait_for_health(timeout = 600.0, cancelled = cancelled)if healthy:self._healthy = Trueself._gpu_offload_active = not holds_no_gpu@@ -12807,9 +12837,21 @@ class LlamaCppBackend:self._effective_context_length = chosenself._max_context_length = chosenself._requested_n_ctx = int(n_ctx)+ if cancelled is not None and cancelled():+ logger.info("DiffusionGemma start cancelled after it became healthy")+ self._healthy = False+ self._kill_process()+ return Falseelse:self._healthy = False- logger.error("DiffusionGemma runner failed to become healthy")+ if getattr(self, "_health_wait_cancelled", False):+ # An automatic switch cancels without unloading, so nothing else reaps+ # the shim and the visual server: they would keep loading and holding+ # memory until some later teardown.+ logger.info("DiffusionGemma start cancelled; stopping the runner")+ self._kill_process()+ else:+ logger.error("DiffusionGemma runner failed to become healthy")return healthy# ── HF download (no lock held) ───────────────────────────────@@ -12836,6 +12878,8 @@ class LlamaCppBackend:touching the shared one; defaults to the shared event."""cancel_event = cancel_event if cancel_event is not None else self._cancel_event+ if cancel_event.is_set():+ raise GgufDownloadCancelled("Cancelled")from utils.hf_cache_settings import get_hf_cache_pathsdownload_cache_dir = str(get_hf_cache_paths().hub_cache)@@ -13000,7 +13044,7 @@ class LlamaCppBackend:logger.info(f"Resolving GGUF: {gguf_label}")try:if cancel_event.is_set():- raise RuntimeError("Cancelled")+ raise GgufDownloadCancelled("Cancelled")dl_start = time.monotonic()# Xet primary, HTTP fallback on stall; per-file so finished shards stay cached.local_path = hf_hub_download_with_xet_fallback(@@ -13014,7 +13058,7 @@ class LlamaCppBackend:)for shard in gguf_extra_shards:if cancel_event.is_set():- raise RuntimeError("Cancelled")+ raise GgufDownloadCancelled("Cancelled")logger.info(f"Resolving GGUF shard: {shard}")hf_hub_download_with_xet_fallback(hf_repo,@@ -13025,8 +13069,10 @@ class LlamaCppBackend:cache_dir = download_cache_dir,)except Exception as e:- if isinstance(e, RuntimeError) and "Cancelled" in str(e):+ if isinstance(e, GgufDownloadCancelled):raise+ if isinstance(e, RuntimeError) and "Cancelled" in str(e):+ raise GgufDownloadCancelled(str(e)) from eraise RuntimeError(f"Failed to download GGUF file '{gguf_filename}' from {hf_repo}: {e}")@@ -13322,6 +13368,7 @@ class LlamaCppBackend:*,hf_repo: str,hf_token: Optional[str] = None,+ cancel_event: Optional[threading.Event] = None,near_path: Optional[str] = None,) -> Optional[str]:"""Download the separate MTP drafter (speculative head) from a GGUF repo.@@ -13334,6 +13381,10 @@ class LlamaCppBackend:are intentionally skipped. Returns the local path, or None."""+ cancel_event = cancel_event if cancel_event is not None else self._cancel_event+ if cancel_event.is_set():+ return None+if near_path:cached = _companion_snapshot_sibling(near_path, _pick_mtp)if cached:@@ -13358,6 +13409,7 @@ class LlamaCppBackend:hf_token = hf_token,pick = _pick_mtp,label = "MTP drafter",+ cancel_event = cancel_event,near_path = near_path,)@@ -13400,6 +13452,7 @@ class LlamaCppBackend:*,hf_repo: str,hf_token: Optional[str] = None,+ cancel_event: Optional[threading.Event] = None,near_path: Optional[str] = None,binary: Optional[str] = None,caps_probe: Optional[Callable[[Optional[str]], dict]] = None,@@ -13415,6 +13468,13 @@ class LlamaCppBackend:guess here has to latch like any other, or a load that skipped the sidecar on aninconclusive probe looks conclusive once the retry window lapses mid-download."""+ cancel_event = (+ cancel_event+ if cancel_event is not None+ else getattr(self, "_cancel_event", threading.Event())+ )+ if cancel_event.is_set():+ return Noneif caps_probe is None:caps_probe = self.probe_server_capabilities@@ -13448,6 +13508,7 @@ class LlamaCppBackend:hf_token = hf_token,pick = _pick_dspark,label = "DSpark drafter",+ cancel_event = cancel_event,near_path = near_path,outcome = outcome,)@@ -13542,6 +13603,7 @@ class LlamaCppBackend:*,hf_repo: str,hf_token: Optional[str] = None,+ cancel_event: Optional[threading.Event] = None,near_path: Optional[str] = None,binary: Optional[str] = None,) -> Optional[str]:@@ -13556,6 +13618,9 @@ class LlamaCppBackend:engage."""+ cancel_event = cancel_event if cancel_event is not None else self._cancel_event+ if cancel_event.is_set():+ return Noneweight_name = Path(near_path).name if near_path else None# Whatever a previous load concluded, this one is asking again.self._dflash_retry_needed = False@@ -13645,7 +13710,7 @@ class LlamaCppBackend:# it too, so a scan that ignores the pool cannot spin here.cached: Optional[str] = Noneseen_siblings: set[str] = set()- while near_path:+ while near_path and not cancel_event.is_set():sibling = _companion_snapshot_sibling(near_path, _pick_dflash)if sibling is None or sibling in seen_siblings:break@@ -13694,6 +13759,7 @@ class LlamaCppBackend:hf_token = hf_token,pick = _pick_dflash,label = "DFlash drafter",+ cancel_event = cancel_event,near_path = near_path,outcome = outcome,# Not a header rejection: that candidate is settled and the loop moves@@ -16654,6 +16720,12 @@ class LlamaCppBackend:load_cancel_event is not None and load_cancel_event.is_set())+ download_cancel_event = (+ _CombinedCancelEvent(self._cancel_event, load_cancel_event)+ if load_cancel_event is not None+ else self._cancel_event+ )+gguf_path = intent.gguf_pathmmproj_path = intent.mmproj_pathmtp_draft_path = intent.mtp_draft_path@@ -16845,6 +16917,9 @@ class LlamaCppBackend:# Placement is undecided until the spawn site narrows it: a needless# reload prompt beats sizing a child against a replaced budget.self._cancel_event.clear()+ # Belongs to this attempt only; a guard that runs before this load's first+ # health wait would otherwise read the previous request's cancellation.+ self._health_wait_cancelled = Falseif _load_cancelled():logger.info("Load cancelled before GGUF resolution")return False@@ -16961,6 +17036,7 @@ class LlamaCppBackend:hf_repo = hf_repo,hf_variant = hf_variant,hf_token = hf_token,+ cancel_event = download_cancel_event,)_preflight_is_diffusion = self._gguf_path_is_diffusion(_preflight_model_path, model_identifier@@ -17125,6 +17201,7 @@ class LlamaCppBackend:hf_repo = hf_repo,hf_variant = hf_variant,hf_token = hf_token,+ cancel_event = download_cancel_event,)# Auto-download mmproj for vision models unless opted out. Vision# switched off does NOT opt out: remote discovery calls any mmproj@@ -17137,6 +17214,7 @@ class LlamaCppBackend:mmproj_path = self._download_mmproj(hf_repo = hf_repo,hf_token = hf_token,+ cancel_event = download_cancel_event,near_path = model_path,)# Auto-download the separate MTP drafter (e.g. Gemma) when@@ -17154,6 +17232,7 @@ class LlamaCppBackend:mtp_draft_path = self._download_mtp(hf_repo = hf_repo,hf_token = hf_token,+ cancel_event = download_cancel_event,near_path = model_path,)# "auto" is included: DSpark is the default whenever the repo@@ -17167,6 +17246,7 @@ class LlamaCppBackend:dspark_draft_path = self._download_dspark(hf_repo = hf_repo,hf_token = hf_token,+ cancel_event = download_cancel_event,near_path = model_path,binary = binary,caps_probe = _launch_caps,@@ -17201,6 +17281,7 @@ class LlamaCppBackend:dflash_draft_path = self._download_dflash(hf_repo = hf_repo,hf_token = hf_token,+ cancel_event = download_cancel_event,near_path = model_path,binary = binary,)@@ -17316,6 +17397,7 @@ class LlamaCppBackend:gpu_ids = gpu_ids,gpu_memory_mode = gpu_memory_mode,gpu_layers = gpu_layers,+ cancelled = _load_cancelled,)if not binary:@@ -21834,12 +21916,14 @@ class LlamaCppBackend:target = self._drain_stdout, daemon = True, name = "llama-stdout")self._stdout_thread.start()- if self._wait_for_health(timeout = 600.0):+ if self._wait_for_health(timeout = 600.0, cancelled = _load_cancelled):if _did_rocm_retry:# Proved on this host: every later child skips the# prepend instead of crashing into it first.self._remember_bundle_only_rocm(binary)return True+ if getattr(self, "_health_wait_cancelled", False):+ return False_startup_crashed = (self._process.poll() is not None and self._process.returncode != 0)@@ -22043,6 +22127,19 @@ class LlamaCppBackend:self._vram_fraction_pending = Noneraise RuntimeError(detail)+ def _cleanup_cancelled_load(message: str) -> None:+ logger.info(message)+ self._cleanup_failed_cpu_fallback()+ self._unload_audio_codec()+ self._healthy = False+ self._vram_fraction_pending = None++ def _finish_cancelled_health_wait(message: str) -> bool:+ if not getattr(self, "_health_wait_cancelled", False):+ return False+ _cleanup_cancelled_load(message)+ return True+def _try_auto_vulkan_cpu_fallback(failed_cmd: list[str],failed_rc: Optional[int],@@ -22083,7 +22180,7 @@ class LlamaCppBackend:# Staging copies a whole runtime, so an /unload can land after# the gate above with no runtime yet for unload_model() to# remove; take it back here.- self._cleanup_cpu_fallback_runtime()+ _cleanup_cancelled_load("Load cancelled while staging the CPU fallback")return Falsereplay, _spawn_cwd, _cpu_pageable_note = prepared# The rewrite mutates the SHARED env in place, so it happens once@@ -22101,6 +22198,10 @@ class LlamaCppBackend:"startup; retrying once with llama.cpp devices disabled.")if not _spawn_and_wait(replay, label = "-cpu"):+ if _finish_cancelled_health_wait(+ "Load cancelled during the staged CPU replay health wait"+ ):+ return Falseif not terminal:# This argv's drafter may be why it cannot start at all,# which the GPU crash says nothing about. Reap the child@@ -22242,6 +22343,11 @@ class LlamaCppBackend:avail_mib = _preflight_avail_mib,)if prepared is None:+ if _load_cancelled():+ _cleanup_cancelled_load(+ "Load cancelled while reconstructing the CPU fallback"+ )+ return False_raise_terminal_load_failure("The prior Vulkan CPU fallback could not be reconstructed; run ""`unsloth studio update` to repair the managed llama.cpp runtime."@@ -22308,6 +22414,10 @@ class LlamaCppBackend:healthy = _spawn_and_wait(cmd)finally:self._memory_launch_pending = False+ if not healthy and _finish_cancelled_health_wait(+ "Load cancelled during the llama-server health wait"+ ):+ return False# #6415 split-mode tensor warmup abort. Latch it on THIS first spawn:# the flash-attn-off retry below can't run tensor (needs flash_attn),# so its output drops the marker and recording later would miss it,@@ -22348,7 +22458,7 @@ class LlamaCppBackend:# narrowed set. Auto selection only; an explicit pick keeps its error.if (not healthy- and not self._cancel_event.is_set()+ and not _load_cancelled()and not gpu_idsand not is_vulkan_backendand gpu_indices@@ -22852,6 +22962,13 @@ class LlamaCppBackend:# Read the crash code before _kill_process() clears _process._crash_rc = self._process.poll() if self._process is not None else Noneself._kill_process()+ # Only when the WAIT itself was cancelled. A cancel that lands later,+ # while a crashed launch is staging its CPU fallback, must still run+ # that recovery, so _load_cancelled() alone is the wrong test here.+ if _finish_cancelled_health_wait(+ "Load cancelled during the llama-server health wait"+ ):+ return False# The #6415 split-axis abort is latched earlier (first spawn).# Skip if a cancel/unload is pending (mirrors the MTP guard)._projector_msg = self._is_projector_incompatibility(out)@@ -22916,7 +23033,14 @@ class LlamaCppBackend:self._process.poll() if self._process is not None else None)self._kill_process()+ if _finish_cancelled_health_wait(+ "Load cancelled during the CPU-projector health wait"+ ):+ return Falseif _load_cancelled():+ _cleanup_cancelled_load(+ "Load cancelled after the CPU-projector health wait"+ )return Falseif self._is_projector_incompatibility(_cpu_projector_out):_projector_msg = True@@ -22976,7 +23100,7 @@ class LlamaCppBackend:self._is_vision = Falseself._mmproj_has_audio = Falseself._start_llama_process(cmd, env)- if self._wait_for_health(timeout = 600.0):+ if self._wait_for_health(timeout = 600.0, cancelled = _load_cancelled):healthy = True# The child that serves this session never read the# CPU-pinned projector, so the host-memory advisory the@@ -23000,6 +23124,10 @@ class LlamaCppBackend:self._process.poll() if self._process is not None else None)self._kill_process()+ if _finish_cancelled_health_wait(+ "Load cancelled during the text-only retry health wait"+ ):+ return False# A text-only signal crash is independent evidence of a GPU# startup fault. Keep a confirmed bad projector out of the# replay; a guessed one still gets a CPU try with vision.@@ -23017,6 +23145,10 @@ class LlamaCppBackend:if not _projector_msg:self._mmproj_fallback_reason = Noneelse:+ if _finish_cancelled_health_wait(+ "Load cancelled during the CPU replay health wait"+ ):+ return False_raise_terminal_load_failure(self._gpu_init_crash_message(binary))@@ -23031,6 +23163,10 @@ class LlamaCppBackend:(self._api_key,),self._extra_args,)+ if _finish_cancelled_health_wait(+ "Load cancelled during the text-only recovery"+ ):+ return False_raise_terminal_load_failure(self._mmproj_retry_failure_message(projector_confirmed = _projector_msg,@@ -23057,6 +23193,10 @@ class LlamaCppBackend:if _replayed:healthy = Trueelse:+ if _finish_cancelled_health_wait(+ "Load cancelled during the CPU replay health wait"+ ):+ return False_raise_terminal_load_failure(self._classify_llama_start_failure(out,@@ -23273,6 +23413,13 @@ class LlamaCppBackend:if not self._healthy:return False+ if _load_cancelled():+ # Cancelled during the post-health setup or the audio probe. Publishing+ # now leaves the child resident while the cancel route sees is_loaded.+ _cleanup_cancelled_load(+ "Load cancelled after llama-server became healthy; unwinding"+ )+ return False# Snapshot the files the server actually loaded. If a GGUF shard or a# LoRA/control-vector sidecar is swapped on disk afterwards while the# old weights stay mapped, save_slots_for_resume() compares against@@ -24128,14 +24275,7 @@ class LlamaCppBackend:except Exception:passself._chat_template_file = None- # Free audio codec GPU memory.- if LlamaCppBackend._codec_mgr is not None:- LlamaCppBackend._codec_mgr.unload()- LlamaCppBackend._codec_mgr = None- import torch-- if torch.cuda.is_available():- torch.cuda.empty_cache()+ self._unload_audio_codec()return True@staticmethod@@ -25603,15 +25743,17 @@ class LlamaCppBackend:# load_model) so a newer load isn't clobbered by this stale replay.requested_mode = snapshot.speculative_typewith self._serial_load_lock:- if self._cancel_event.is_set():- logger.info("MTP-crash reload skipped: load was cancelled/unloaded.")- return- if self._process is not proc:- logger.info("MTP-crash reload skipped: a newer load is already active.")- return- if self._last_load_intent != snapshot:- logger.info("MTP-crash reload skipped: load settings changed.")- return+ with self._lock:+ if self._cancel_event.is_set():+ logger.info("MTP-crash reload skipped: load was cancelled/unloaded.")+ return+ if self._process is not proc:+ logger.info("MTP-crash reload skipped: a newer load is already active.")+ return+ if self._last_load_intent != snapshot:+ logger.info("MTP-crash reload skipped: load settings changed.")+ return+ unload_epoch = self._unload_epoch# Appending --spec-default cannot drop MTP: llama.cpp appends spec# types rather than replacing, so the extras have to lose theirs.# Once they do, Unsloth owns the block and the launch scrubs the@@ -25634,21 +25776,35 @@ class LlamaCppBackend:speculative_type = "off",extra_args = fallback_extra_args,)- self.load_model(fallback)- # Same reason the mode is restored below: the replay launched a- # stripped list but the caller keeps sending the original, so a- # comparator seeing only the stripped one would reload the very MTP- # configuration that just crashed.- if fallback_extra_args is not snapshot.extra_args:- self._requested_extra_args = (- self._strip_device_extra_args(_ea)- if snapshot.gpu_ids is not None- else list(_ea)+ started = bool(self.load_model(fallback))+ if not started:+ logger.info("MTP-crash reload stopped before the replacement was ready.")+ return+ undo_reload = False+ with self._lock:+ if self._cancel_event.is_set() or self._unload_epoch != unload_epoch:+ undo_reload = True+ else:+ # Same reason the mode is restored below: the replay launched a+ # stripped list but the caller keeps sending the original, so a+ # comparator seeing only the stripped one would reload the very MTP+ # configuration that just crashed.+ if fallback_extra_args is not snapshot.extra_args:+ self._requested_extra_args = (+ self._strip_device_extra_args(_ea)+ if snapshot.gpu_ids is not None+ else list(_ea)+ )+ # Restore the requested mode + reason load_model("off") cleared,+ # so /status shows the user's mode + note (like the startup fallback).+ self._requested_spec_mode = _canonicalize_spec_mode(requested_mode)+ self._spec_fallback_reason = "runtime_error"+ if undo_reload:+ logger.info(+ "MTP-crash reload undone: the model was unloaded during reload.")- # Restore the requested mode + reason load_model("off") cleared,- # so /status shows the user's mode + note (like the startup fallback).- self._requested_spec_mode = _canonicalize_spec_mode(requested_mode)- self._spec_fallback_reason = "runtime_error"+ self.unload_model()+ returnlogger.info("Reloaded without MTP after the tensor-parallel crash.")except Exception as e:logger.error(f"Reload without MTP failed: {e}")@@ -25707,6 +25863,7 @@ class LlamaCppBackend:self,timeout: float = 120.0,interval: float = 0.5,+ cancelled: Optional[Callable[[], bool]] = None,) -> bool:"""Poll llama-server's /health until 200; also detect early exit/crash."""deadline = time.monotonic() + timeout@@ -25715,7 +25872,22 @@ class LlamaCppBackend:if health_probe_event is None: # Backward-compatible with lightweight test doubles.health_probe_event = self._health_probe_event = threading.Event()+ if cancelled is None:+ # A scoped /load carries its own cancel event, so load_model passes its own+ # predicate; fall back to the unload flag for callers that have none.+ cancel_event = getattr(self, "_cancel_event", None)+ cancelled = cancel_event.is_set if cancel_event is not None else None++ # Why this wait ended, for callers that must tell a cancel apart from a crash:+ # a cancel landing during CPU-fallback staging is not a cancelled wait.+ self._health_wait_cancelled = False+while time.monotonic() < deadline:+ # unload_model() blocks on self._lock, which the load holds across this wait.+ if cancelled is not None and cancelled():+ logger.info("llama-server startup cancelled before it became healthy")+ self._health_wait_cancelled = True+ return False# Cleared before probing so output during the request stays latched for# the fallback wait below.health_probe_event.clear()@@ -25744,6 +25916,12 @@ class LlamaCppBackend:# for 127.0.0.1 loops the probe until timeout and hangs load.resp = httpx.get(url, timeout = 2.0, trust_env = False)if resp.status_code == 200:+ # The probe blocks for up to 2s; a cancel landing inside that window+ # would otherwise publish the model the user just asked us to drop.+ if cancelled is not None and cancelled():+ logger.info("llama-server became healthy after the load was cancelled")+ self._health_wait_cancelled = True+ return Falsereturn Trueexcept (httpx.ConnectError,@@ -25758,6 +25936,11 @@ class LlamaCppBackend:health_probe_event.wait(interval)+ if cancelled is not None and cancelled():+ logger.info("llama-server startup cancelled at the health-check deadline")+ self._health_wait_cancelled = True+ return False+# Leave a marker so _classify_llama_start_failure tells a live but# never-healthy load (too large, or a proxy hijacking the loopback# probe) apart from a bad GGUF (#5740).@@ -30831,6 +31014,17 @@ class LlamaCppBackend:_codec_mgr = None # Shared AudioCodecManager instance+ @staticmethod+ def _unload_audio_codec() -> None:+ if LlamaCppBackend._codec_mgr is None:+ return+ LlamaCppBackend._codec_mgr.unload()+ LlamaCppBackend._codec_mgr = None+ import torch++ if torch.cuda.is_available():+ torch.cuda.empty_cache()+def init_audio_codec(self, audio_type: str) -> None:"""Load the audio codec at model load time (mirrors the non-GGUF path)."""import torchdiff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex f4a2f03abd7..9d610dc1650 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -1425,6 +1425,7 @@ if str(backend_path) not in sys.path:try:from core.inference import get_inference_backendfrom core.inference.llama_cpp import (+ GgufDownloadCancelled,GgufLoadIntent,LlamaCppBackend,_DEFAULT_FIRST_TOKEN_TIMEOUT_S,@@ -1481,6 +1482,7 @@ except ImportError:sys.path.insert(0, str(parent_backend))from core.inference import get_inference_backendfrom core.inference.llama_cpp import (+ GgufDownloadCancelled,GgufLoadIntent,LlamaCppBackend,_DEFAULT_FIRST_TOKEN_TIMEOUT_S,@@ -12407,6 +12409,23 @@ def _restore_alias_if_failed_load_left_the_prior_model(backend._openai_advertised_id = prior_alias+def _gguf_load_cancelled(llama_backend, load_cancel_event: Optional[threading.Event]) -> bool:+ return llama_backend.load_cancelled() or bool(+ load_cancel_event is not None and load_cancel_event.is_set()+ )+++async def _run_gguf_load_attempt(llama_backend, intent, load_cancel_event) -> bool:+ try:+ return await asyncio.to_thread(+ llama_backend.load_model,+ intent = intent,+ load_cancel_event = load_cancel_event,+ )+ except GgufDownloadCancelled:+ return False++async def _load_model_impl(request: LoadRequest,fastapi_request: Request,@@ -12997,10 +13016,10 @@ async def _load_model_impl(and not _effective_tensor_parallel(attempt_extra_args, tensor_parallel)),)- return await asyncio.to_thread(- llama_backend.load_model,- intent = attempt,- load_cancel_event = load_cancel_event,+ return await _run_gguf_load_attempt(+ llama_backend,+ attempt,+ load_cancel_event,)# Tensor parallelism is arch-gated in llama.cpp and crashes some loads@@ -13014,10 +13033,7 @@ async def _load_model_impl(requested_tensor = request.tensor_parallel,extra_args = extra_llama_args,label = config.identifier,- cancelled = lambda: (- llama_backend.load_cancelled()- or bool(load_cancel_event and load_cancel_event.is_set())- ),+ cancelled = lambda: _gguf_load_cancelled(llama_backend, load_cancel_event),)except Exception:# A GGUF load can raise before tearing down the old llama-server (e.g. an@@ -13029,6 +13045,11 @@ async def _load_model_impl(if not success:_restore_marker_if_prior_preview_still_resident()+ # A cancelled load is not a failed one. An automatic switch cancels+ # through its own event without unloading, and the 500 built here+ # would land before the caller reaches _raise_if_generation_cancelled.+ if _gguf_load_cancelled(llama_backend, load_cancel_event):+ raise HTTPException(status_code = 409, detail = "Model load cancelled")raise HTTPException(status_code = 500,detail = f"Failed to load GGUF model: {model_log_label if native_grant_backed else config.display_name}",diff --git a/studio/backend/tests/test_cuda_sm_gate.py b/studio/backend/tests/test_cuda_sm_gate.pyindex 47ba316192e..ae586feafe8 100644--- a/studio/backend/tests/test_cuda_sm_gate.py+++ b/studio/backend/tests/test_cuda_sm_gate.py@@ -235,7 +235,7 @@ def _gated_backend(backend._prepare_cpu_fallback_launch = lambda *_a, **_kw: Nonebackend._detect_audio_type_strict = lambda: Nonebackend._apply_detected_audio = lambda _detected: True- backend._wait_for_health = lambda timeout: True+ backend._wait_for_health = lambda timeout, **_kw: Truebackend._llama_server_env_for_binary = lambda _binary: {"PATH": os.environ.get("PATH", "")}return backend, ggufdiff --git a/studio/backend/tests/test_gpu_arch_gate_consumers_7624.py b/studio/backend/tests/test_gpu_arch_gate_consumers_7624.pyindex 3ed1476aaa2..a29da8cfcc5 100644--- a/studio/backend/tests/test_gpu_arch_gate_consumers_7624.py+++ b/studio/backend/tests/test_gpu_arch_gate_consumers_7624.py@@ -146,7 +146,7 @@ def _backend(backend._amd_apu_wants_unified_memory = lambda *args, **kwargs: Falsebackend._find_llama_server_binary = lambda include_denied = False: "/fake/llama-server"backend._is_vulkan_backend = lambda _binary = None: False- backend._wait_for_health = lambda timeout: True+ backend._wait_for_health = lambda timeout, **_kw: Truebackend._detect_audio_type_strict = lambda: Nonebackend._apply_detected_audio = lambda _detected: Truereturn backend, _write_gguf(tmp_path / "model.gguf")diff --git a/studio/backend/tests/test_gpu_arch_gate_os_matrix_7624.py b/studio/backend/tests/test_gpu_arch_gate_os_matrix_7624.pyindex 00eaa7fd1b9..5c1f6ed21f0 100644--- a/studio/backend/tests/test_gpu_arch_gate_os_matrix_7624.py+++ b/studio/backend/tests/test_gpu_arch_gate_os_matrix_7624.py@@ -861,7 +861,7 @@ def _run_auto_load(launches.append((list(cmd), dict(kwargs["env"])))return _Process(returncode)- def _wait_for_health(timeout):+ def _wait_for_health(timeout, **_kw):backend._stdout_lines = [output]return returncode is Nonediff --git a/studio/backend/tests/test_gpu_init_crash_message.py b/studio/backend/tests/test_gpu_init_crash_message.pyindex f734136ef8e..929d5251837 100644--- a/studio/backend/tests/test_gpu_init_crash_message.py+++ b/studio/backend/tests/test_gpu_init_crash_message.py@@ -184,7 +184,7 @@ def _run_cpu_fallback_load(launches.append((list(cmd), dict(kwargs["env"])))return _Process(returncodes[index])- def _wait_for_health(timeout):+ def _wait_for_health(timeout, **_kw):if len(launches) == 1 and first_output:backend._stdout_lines = [first_output]if cancel_after is not None and len(launches) >= cancel_after:@@ -1228,7 +1228,7 @@ def test_terminal_signal_with_explicit_child_placement_does_not_replay(backend._is_vulkan_backend = lambda _binary = None: Truebackend._vulkan_prebuilt_was_auto_selected = lambda _binary: Truebackend.probe_server_capabilities = lambda _binary: {"found": True}- backend._wait_for_health = lambda timeout: False+ backend._wait_for_health = lambda timeout, **_kw: Falsebackend._record_server_pid = lambda _pid: Nonebackend._clear_server_pid = lambda: Nonebackend._llama_server_env_for_binary = lambda _binary: {@@ -1612,7 +1612,7 @@ def _run_full_offload_spawns(monkeypatch, tmp_path, *, outputs, returncodes):code = returncodes[idx] if idx < len(returncodes) else 1return _Process(code)- def _wait_for_health(timeout = 600.0):+ def _wait_for_health(timeout = 600.0, **_kw):idx = len(launches) - 1if 0 <= idx < len(outputs):backend._stdout_lines = [outputs[idx]]diff --git a/studio/backend/tests/test_llama_cpp_placement.py b/studio/backend/tests/test_llama_cpp_placement.pyindex 02ce12736fe..9dd3fa491fa 100644--- a/studio/backend/tests/test_llama_cpp_placement.py+++ b/studio/backend/tests/test_llama_cpp_placement.py@@ -102,7 +102,7 @@ def _backend(tmp_path: Path, *, vulkan: bool, memory):backend._amd_apu_wants_unified_memory = lambda *args, **kwargs: Falsebackend._find_llama_server_binary = lambda include_denied = False: "/fake/llama-server"backend._is_vulkan_backend = lambda _binary = None: vulkan- backend._wait_for_health = lambda timeout: True+ backend._wait_for_health = lambda timeout, **_kw: Truebackend._detect_audio_type_strict = lambda: Nonebackend._apply_detected_audio = lambda _detected: Truereturn backend, gguf@@ -3001,7 +3001,7 @@ def _launch_with_text_only_fallback(backend, gguf, **load_kwargs):},)()- def fake_health(timeout = None):+ def fake_health(timeout = None, **_kw):launched = captured["cmds"][-1] if captured["cmds"] else []if "--mmproj" in launched:backend._stdout_lines = _PROJECTOR_ABORT_OUT.splitlines()@@ -3229,7 +3229,7 @@ def _launch_with_vulkan_cpu_replay(},)()- def fake_health(timeout = None):+ def fake_health(timeout = None, **_kw):if crash and not _is_cpu_replay(captured["cmds"][-1] if captured["cmds"] else []):backend._stdout_lines = ["ggml_vulkan: Device memory allocation failed"]return Falsediff --git a/studio/backend/tests/test_llama_cpp_remote_non_chat_gguf_preflight.py b/studio/backend/tests/test_llama_cpp_remote_non_chat_gguf_preflight.pyindex e08756c14f1..e35370481c3 100644--- a/studio/backend/tests/test_llama_cpp_remote_non_chat_gguf_preflight.py+++ b/studio/backend/tests/test_llama_cpp_remote_non_chat_gguf_preflight.py@@ -976,7 +976,7 @@ def _launchable_backend(monkeypatch) -> LlamaCppBackend:backend._record_server_pid = lambda _pid: Nonebackend._clear_server_pid = lambda: Nonebackend._llama_server_env_for_binary = lambda _binary: {}- backend._wait_for_health = lambda timeout: True+ backend._wait_for_health = lambda timeout, **_kw: Truebackend.probe_server_capabilities = lambda _binary: {"found": True}monkeypatch.setattr(LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda _binary = None: False)diff --git a/studio/backend/tests/test_llama_cpp_wait_for_health.py b/studio/backend/tests/test_llama_cpp_wait_for_health.pyindex 508d371a555..6d49c51b25e 100644--- a/studio/backend/tests/test_llama_cpp_wait_for_health.py+++ b/studio/backend/tests/test_llama_cpp_wait_for_health.py@@ -76,6 +76,77 @@ class TestWaitForHealthResilience:assert b._wait_for_health(timeout = 0.02, interval = 0.01) is Falseassert any("health check timed out" in ln for ln in b._stdout_lines)+ def test_cancel_stops_the_wait_without_a_timeout_marker(self, monkeypatch):+ b = _make_backend()+ b._process.poll.return_value = None+ b._cancel_event = threading.Event()+ b._cancel_event.set()+ monkeypatch.setattr(httpx, "get", lambda *a, **kw: mock.Mock(status_code = 503))+ started = time.monotonic()+ assert b._wait_for_health(timeout = 30.0, interval = 0.01) is False+ assert time.monotonic() - started < 1.0+ assert not any("health check timed out" in ln for ln in b._stdout_lines)++ def test_cancel_midway_stops_a_wait_already_in_progress(self, monkeypatch):+ b = _make_backend()+ b._process.poll.return_value = None+ b._cancel_event = threading.Event()+ probes = []++ def probe(*a, **kw):+ probes.append(1)+ if len(probes) == 3:+ b._cancel_event.set()+ return mock.Mock(status_code = 503)++ monkeypatch.setattr(httpx, "get", probe)+ assert b._wait_for_health(timeout = 30.0, interval = 0.01) is False+ assert len(probes) == 3++ def test_cancel_at_the_deadline_is_not_reported_as_a_timeout(self, monkeypatch):+ b = _make_backend()+ b._process.poll.return_value = None+ b._cancel_event = threading.Event()+ b._health_probe_event = mock.Mock()+ b._health_probe_event.wait.side_effect = lambda _interval: b._cancel_event.set()+ ticks = iter((0.0, 0.0, 1.0))+ monkeypatch.setattr(time, "monotonic", lambda: next(ticks))+ monkeypatch.setattr(httpx, "get", lambda *a, **kw: mock.Mock(status_code = 503))++ assert b._wait_for_health(timeout = 0.5, interval = 0.5) is False+ assert b._health_wait_cancelled is True+ assert not any("health check timed out" in ln for ln in b._stdout_lines)++ def test_a_scoped_load_cancel_stops_the_wait(self, monkeypatch):+ """An auto-switch or a /load carrying load_request_id cancels through its own+ event and never calls unload_model, so _cancel_event stays clear. The wait has+ to honor the predicate load_model passes down or it polls the full timeout."""+ b = _make_backend()+ b._process.poll.return_value = None+ b._cancel_event = threading.Event() # no unload was issued+ scoped = threading.Event()+ scoped.set()+ monkeypatch.setattr(httpx, "get", lambda *a, **kw: mock.Mock(status_code = 503))+ started = time.monotonic()+ assert b._wait_for_health(timeout = 30.0, interval = 0.01, cancelled = scoped.is_set) is False+ assert time.monotonic() - started < 1.0+ assert not any("health check timed out" in ln for ln in b._stdout_lines)++ def test_a_cancel_during_the_probe_does_not_publish_the_model(self, monkeypatch):+ """The probe blocks for up to 2s. A cancel landing inside that window used to be+ ignored because the 200 returned first, so the unwanted model went live."""+ b = _make_backend()+ b._process.poll.return_value = None+ b._cancel_event = threading.Event()+ scoped = threading.Event()++ def probe(*a, **kw):+ scoped.set() # the user cancels while this request is in flight+ return mock.Mock(status_code = 200)++ monkeypatch.setattr(httpx, "get", probe)+ assert b._wait_for_health(timeout = 30.0, interval = 0.01, cancelled = scoped.is_set) is False+def test_read_error_loops_to_subprocess_poll(self, monkeypatch):"""WinError 10054 (httpx.ReadError) must be swallowed; the next iteration sees the dead subprocess and returns False with a structured exit-code log."""b = _make_backend()@@ -299,3 +370,349 @@ class TestFitOffRetryEligible:def test_fit_tuning_flags_do_not_block_retry(self, tuning_args):cmd = ["llama-server", "-m", "x.gguf", *tuning_args]assert LlamaCppBackend._fit_off_retry_eligible(cmd, use_fit = False) is True+++class TestCancelledWaitEndsTheLoad:+ """An auto-switch cancels through its own event and never unloads, so the child is+ still alive and poll() reports no exit code. Classifying that as a start failure+ raises a 500 at the caller before it can run its own cancellation handling."""++ def test_a_cancelled_health_wait_returns_false_instead_of_raising(self, tmp_path):+ from core.inference.llama_cpp import GgufLoadIntent++ gguf = tmp_path / "model.gguf"+ gguf.write_bytes(b"GGUF" + b"\0" * 4096)++ b = LlamaCppBackend()+ b._find_llama_server_binary = lambda *a, **kw: "/usr/bin/true"+ # The header refusals read a real GGUF; this fixture stands in for a chat model.+ b._non_chat_gguf_refusal_for_path = lambda *a, **kw: None+ b._non_chat_gguf_refusal = lambda *a, **kw: None+ b._kill_process = lambda *a, **kw: None++ def _start(cmd, env, **kw):+ proc = mock.Mock()+ proc.poll.return_value = None # alive: the cancel kills it, not a crash+ proc.pid = 424242+ b._process = proc+ b._stdout_lines = ["build: 6543", "main: loading model"]+ return proc++ b._start_llama_process = _start+ scoped = threading.Event()+ real_wait = b._wait_for_health++ def _wait(+ timeout = 600.0,+ interval = 0.5,+ cancelled = None,+ ):+ scoped.set()+ return real_wait(timeout = 2.0, interval = 0.05, cancelled = cancelled)++ b._wait_for_health = _wait++ assert (+ b.load_model(+ GgufLoadIntent(+ model_identifier = "owner/model",+ gguf_path = str(gguf),+ n_ctx = 4096,+ ),+ load_cancel_event = scoped,+ )+ is False+ )+++def test_a_cancelled_diffusion_start_reaps_the_runner():+ """An automatic switch cancels without unloading, so nothing else reaps the shim+ and the visual server; they would keep loading and holding memory."""+ import subprocess++ b = LlamaCppBackend()+ kills = []+ b._kill_process = lambda *a, **kw: kills.append(1)+ b._find_diffusion_assets = lambda *a, **kw: (["/bin/true"], "/bin/true", None)+ b._find_free_port = lambda *a, **kw: 45999++ def _wait(+ timeout = 600.0,+ interval = 0.5,+ cancelled = None,+ ):+ b._health_wait_cancelled = True+ return False++ b._wait_for_health = _wait+ proc = mock.Mock()+ proc.poll.return_value = None+ proc.pid = 999+ with mock.patch.object(subprocess, "Popen", return_value = proc):+ assert (+ b._start_diffusion_server(+ model_path = "/m/x.gguf",+ gguf_path = "/m/x.gguf",+ hf_repo = None,+ hf_variant = None,+ model_identifier = "o/m",+ n_ctx = 4096,+ extra_args = None,+ cancelled = lambda: True,+ )+ is False+ )+ # One teardown before the launch, one for the cancelled runner.+ assert len(kills) == 2, f"the cancelled runner was left running (kills={len(kills)})"+++def test_a_diffusion_cancel_after_health_reaps_the_runner():+ import subprocess++ b = LlamaCppBackend()+ kills = []+ b._kill_process = lambda *a, **kw: kills.append(1)+ b._find_diffusion_assets = lambda *a, **kw: (["/bin/true"], "/bin/true", None)+ b._find_free_port = lambda *a, **kw: 45999+ scoped = threading.Event()++ def _wait(+ timeout = 600.0,+ interval = 0.5,+ cancelled = None,+ ):+ scoped.set()+ return True++ b._wait_for_health = _wait+ proc = mock.Mock()+ proc.poll.return_value = None+ proc.pid = 999+ with mock.patch.object(subprocess, "Popen", return_value = proc):+ assert (+ b._start_diffusion_server(+ model_path = "/m/x.gguf",+ gguf_path = "/m/x.gguf",+ hf_repo = None,+ hf_variant = None,+ model_identifier = "o/m",+ n_ctx = 4096,+ extra_args = None,+ cancelled = scoped.is_set,+ )+ is False+ )+ assert b._healthy is False+ assert len(kills) == 2, f"the cancelled runner was left running (kills={len(kills)})"+++def _cancel_scaffold(tmp_path, kills):+ """A backend wired far enough to run load_model without weights or a server."""+ b = LlamaCppBackend()+ b._find_llama_server_binary = lambda *a, **kw: "/usr/bin/true"+ b._non_chat_gguf_refusal_for_path = lambda *a, **kw: None+ b._non_chat_gguf_refusal = lambda *a, **kw: None+ b._kill_process = lambda *a, **kw: kills.append(1)++ def _start(cmd, env, **kw):+ proc = mock.Mock()+ proc.poll.return_value = None+ proc.pid = 424242+ b._process = proc+ b._stdout_lines = ["build: 6543", "main: loading model"]+ return proc++ b._start_llama_process = _start+ gguf = tmp_path / "model.gguf"+ gguf.write_bytes(b"GGUF" + b"\0" * 4096)+ return b, gguf+++def test_combined_download_cancel_wait_observes_the_scoped_event():+ from core.inference.llama_cpp import _CombinedCancelEvent++ shared = threading.Event()+ scoped = threading.Event()+ timer = threading.Timer(0.01, scoped.set)+ timer.start()+ try:+ assert _CombinedCancelEvent(shared, scoped).wait(0.5)+ finally:+ timer.cancel()++[email protected]("cancel_source", ["shared", "scoped"])+def test_remote_download_observes_both_load_cancel_sources(tmp_path, cancel_source):+ from core.inference.llama_cpp import GgufLoadIntent++ kills = []+ b, gguf = _cancel_scaffold(tmp_path, kills)+ b._remote_non_chat_gguf_refusal = lambda **_kw: None+ scoped = threading.Event()+ seen = []++ def _download(**kwargs):+ cancel_event = kwargs["cancel_event"]+ seen.append(cancel_event)+ (b._cancel_event if cancel_source == "shared" else scoped).set()+ assert cancel_event.is_set()+ return str(gguf)++ b._download_gguf = _download+ assert (+ b.load_model(+ GgufLoadIntent(+ model_identifier = "owner/model",+ hf_repo = "owner/model-GGUF",+ speculative_type = "none",+ n_ctx = 4096,+ ),+ load_cancel_event = scoped,+ )+ is False+ )+ assert len(seen) == 1+++def test_a_stale_cancel_marker_does_not_abort_the_next_load(tmp_path):+ """The marker belongs to one attempt. Left set, a guard that runs before this+ load's first health wait reads the previous request's cancellation and swallows+ a genuine start failure."""+ from core.inference.llama_cpp import GgufLoadIntent++ kills = []+ b, gguf = _cancel_scaffold(tmp_path, kills)+ b._health_wait_cancelled = True # left over from an earlier cancelled load+ # A genuine failure: the wait fails and does NOT mark the load cancelled.+ b._wait_for_health = lambda timeout = 600.0, interval = 0.5, cancelled = None: False++ with pytest.raises(RuntimeError):+ b.load_model(+ GgufLoadIntent(+ model_identifier = "owner/model",+ gguf_path = str(gguf),+ n_ctx = 4096,+ )+ )+++def test_cancelled_health_wait_removes_the_staged_cpu_runtime(tmp_path):+ from core.inference.llama_cpp import GgufLoadIntent++ kills = []+ cleaned = []+ waits = []+ b, gguf = _cancel_scaffold(tmp_path, kills)+ scoped = threading.Event()++ def _wait(+ timeout = 600.0,+ interval = 0.5,+ cancelled = None,+ ):+ waits.append(1)+ b._process = mock.Mock(returncode = -9)+ b._process.poll.return_value = -9+ b._cpu_fallback_runtime = _types.SimpleNamespace(+ tempdir = _types.SimpleNamespace(cleanup = lambda: cleaned.append(1))+ )+ scoped.set()+ b._health_wait_cancelled = True+ return False++ b._wait_for_health = _wait+ assert (+ b.load_model(+ GgufLoadIntent(+ model_identifier = "owner/model",+ gguf_path = str(gguf),+ n_ctx = 4096,+ ),+ load_cancel_event = scoped,+ )+ is False+ )+ assert waits == [1]+ assert b._cpu_fallback_runtime is None+ assert cleaned == [1]+++def test_a_cancel_after_the_server_is_healthy_does_not_publish_it(tmp_path):+ """Cancelling during the post-health setup used to leave the child resident while+ the cancel route saw is_loaded and skipped teardown."""+ from core.inference.llama_cpp import GgufLoadIntent++ kills = []+ cleaned = []+ b, gguf = _cancel_scaffold(tmp_path, kills)++ def _wait(+ timeout = 600.0,+ interval = 0.5,+ cancelled = None,+ ):+ b._cpu_fallback_runtime = _types.SimpleNamespace(+ tempdir = _types.SimpleNamespace(cleanup = lambda: cleaned.append(1))+ )+ b._cancel_event.set() # the user cancels while the load finishes publishing+ return True++ b._wait_for_health = _wait+ assert (+ b.load_model(+ GgufLoadIntent(+ model_identifier = "owner/model",+ gguf_path = str(gguf),+ n_ctx = 4096,+ )+ )+ is False+ )+ assert kills, "the healthy-but-cancelled child was left resident"+ assert b._cpu_fallback_runtime is None+ assert cleaned == [1]+++def test_a_cancel_after_audio_setup_unloads_the_codec(tmp_path, monkeypatch):+ from core.inference.llama_cpp import GgufLoadIntent++ kills = []+ emptied = []+ b, gguf = _cancel_scaffold(tmp_path, kills)+ scoped = threading.Event()+ codec = mock.Mock()+ monkeypatch.setattr(LlamaCppBackend, "_codec_mgr", None)+ monkeypatch.setitem(+ sys.modules,+ "torch",+ _types.SimpleNamespace(+ cuda = _types.SimpleNamespace(+ is_available = lambda: True,+ empty_cache = lambda: emptied.append(1),+ )+ ),+ )++ def _apply_audio(_detected):+ LlamaCppBackend._codec_mgr = codec+ scoped.set()+ return True++ b._wait_for_health = lambda **_kwargs: True+ b._detect_audio_type_strict = lambda: "snac"+ b._apply_detected_audio = _apply_audio++ assert (+ b.load_model(+ GgufLoadIntent(+ model_identifier = "owner/model",+ gguf_path = str(gguf),+ n_ctx = 4096,+ ),+ load_cancel_event = scoped,+ )+ is False+ )+ codec.unload.assert_called_once_with()+ assert LlamaCppBackend._codec_mgr is None+ assert emptied == [1]diff --git a/studio/backend/tests/test_metal_explicit_context_guard.py b/studio/backend/tests/test_metal_explicit_context_guard.pyindex cbe88f5b1ed..d10dc94cbfd 100644--- a/studio/backend/tests/test_metal_explicit_context_guard.py+++ b/studio/backend/tests/test_metal_explicit_context_guard.py@@ -173,7 +173,7 @@ def _launch(backend._amd_apu_wants_unified_memory = lambda *a, **k: Falsebackend._find_llama_server_binary = lambda include_denied = False: "/fake/llama-server"backend._is_vulkan_backend = lambda _binary = None: False- backend._wait_for_health = lambda timeout: True+ backend._wait_for_health = lambda timeout, **_kw: Truebackend._detect_audio_type_strict = lambda: Nonebackend._apply_detected_audio = lambda _detected: Truebackend._context_length = nativediff --git a/studio/backend/tests/test_metal_never_starts_at_native_context.py b/studio/backend/tests/test_metal_never_starts_at_native_context.pyindex 894df5b0b7b..282ddde9279 100644--- a/studio/backend/tests/test_metal_never_starts_at_native_context.py+++ b/studio/backend/tests/test_metal_never_starts_at_native_context.py@@ -117,7 +117,7 @@ def _launch(backend._amd_apu_wants_unified_memory = lambda *a, **k: Falsebackend._find_llama_server_binary = lambda include_denied = False: "/fake/llama-server"backend._is_vulkan_backend = lambda _binary = None: False- backend._wait_for_health = lambda timeout: True+ backend._wait_for_health = lambda timeout, **_kw: Truebackend._detect_audio_type_strict = lambda: Nonebackend._apply_detected_audio = lambda _detected: Truebackend._context_length = ctx_metadatadiff --git a/studio/backend/tests/test_mmproj_placement_policy.py b/studio/backend/tests/test_mmproj_placement_policy.pyindex 2d12b66cbc4..51295f4ac55 100644--- a/studio/backend/tests/test_mmproj_placement_policy.py+++ b/studio/backend/tests/test_mmproj_placement_policy.py@@ -105,7 +105,7 @@ def _backend(backend._amd_apu_wants_unified_memory = lambda *_a, **_kw: Falsebackend._find_llama_server_binary = lambda include_denied = False: "/fake/llama-server"backend._is_vulkan_backend = lambda _binary = None: False- backend._wait_for_health = lambda timeout: True+ backend._wait_for_health = lambda timeout, **_kw: Truebackend._detect_audio_type_strict = lambda: Nonebackend._apply_detected_audio = lambda _detected: Truebackend.probe_server_capabilities = lambda _binary = None: {diff --git a/studio/backend/tests/test_mtp_drafter_companion.py b/studio/backend/tests/test_mtp_drafter_companion.pyindex ae670bec574..355a0ff7fa2 100644--- a/studio/backend/tests/test_mtp_drafter_companion.py+++ b/studio/backend/tests/test_mtp_drafter_companion.py@@ -12,6 +12,7 @@ quant's main files), and local drafter detection / self-pairing rejection.from __future__ import annotationsimport sys+import threadingfrom pathlib import Pathfrom types import SimpleNamespace@@ -680,6 +681,41 @@ def test_download_mtp_prefers_root_over_new_scheme_copies(monkeypatch):assert captured["pick"](repo_files) == "mtp-gemma-4-E4B-it.gguf"+def test_companion_downloads_forward_the_load_cancel_event(monkeypatch):+ import core.inference.llama_cpp as llama_cpp_module+ from core.inference.llama_cpp import LlamaCppBackend++ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)+ monkeypatch.setattr(+ llama_cpp_module, "_companion_snapshot_sibling", lambda near_path, pick: None+ )+ event = threading.Event()+ seen = []+ b = LlamaCppBackend()+ b.probe_server_capabilities = lambda binary = None: {+ "supports_dspark": True,+ "supports_dflash": True,+ }++ def _fake_companion(**kwargs):+ seen.append((kwargs["label"], kwargs["cancel_event"]))+ return None++ b._download_companion_gguf = _fake_companion+ b._download_mmproj(hf_repo = "org/repo", cancel_event = event)+ b._download_mtp(hf_repo = "org/repo", cancel_event = event)+ b._download_dspark(hf_repo = "org/repo", cancel_event = event)+ b._download_dflash(hf_repo = "org/repo", cancel_event = event)++ assert {label for label, _ in seen} == {+ "mmproj",+ "MTP drafter",+ "DSpark drafter",+ "DFlash drafter",+ }+ assert all(forwarded is event for _, forwarded in seen)++# ── Reuse an on-disk drafter offline; fetch fresh online ─────────────diff --git a/studio/backend/tests/test_orchestrator_unload_cancel.py b/studio/backend/tests/test_orchestrator_unload_cancel.pyindex 94895e2d546..966b5e06a94 100644--- a/studio/backend/tests/test_orchestrator_unload_cancel.py+++ b/studio/backend/tests/test_orchestrator_unload_cancel.py@@ -1079,6 +1079,94 @@ def test_standard_load_honors_scoped_cancel_before_worker_start():assert orchestrator.loading_models == set()+def test_gguf_load_cancellation_includes_the_backend_unload_event():+ import asyncio++ import routes.inference as inference_route+ from core.inference.llama_cpp import GgufDownloadCancelled++ class _Llama:+ def load_cancelled(self):+ return True++ assert inference_route._gguf_load_cancelled(_Llama(), threading.Event()) is True++ scoped = threading.Event()++ class _CancellingLlama:+ def load_cancelled(self):+ return False++ def load_model(self, *, intent, load_cancel_event):+ load_cancel_event.set()+ raise GgufDownloadCancelled("Cancelled")++ assert (+ asyncio.run(+ inference_route._run_gguf_load_attempt(+ _CancellingLlama(),+ object(),+ scoped,+ )+ )+ is False+ )+++def test_cancelled_gguf_download_uses_the_typed_signal():+ from core.inference.llama_cpp import GgufDownloadCancelled, LlamaCppBackend++ cancelled = threading.Event()+ cancelled.set()+ with pytest.raises(GgufDownloadCancelled):+ LlamaCppBackend()._download_gguf(+ hf_repo = "owner/model-GGUF",+ cancel_event = cancelled,+ )+++def test_gguf_load_attempt_does_not_hide_a_real_resolver_failure():+ import asyncio++ import routes.inference as inference_route++ class _Llama:+ def load_cancelled(self):+ return True++ def load_model(self, *, intent, load_cancel_event):+ raise RuntimeError("resolver failed")++ with pytest.raises(RuntimeError, match = "resolver failed"):+ asyncio.run(+ inference_route._run_gguf_load_attempt(+ _Llama(),+ object(),+ threading.Event(),+ )+ )+++def test_stale_unload_does_not_hide_an_update_refusal():+ import asyncio++ import routes.inference as inference_route+ from core.inference.llama_cpp import GgufLoadIntent, LlamaCppBackend++ llama = LlamaCppBackend()+ llama._cancel_event.set()+ llama._llama_update_in_progress = True++ with pytest.raises(RuntimeError, match = "llama.cpp is updating"):+ asyncio.run(+ inference_route._run_gguf_load_attempt(+ llama,+ GgufLoadIntent(model_identifier = "owner/model"),+ threading.Event(),+ )+ )++# ----------------------------------------------------------------------------# A dispatched (compare-mode) request that races an unload must not orphan its# mailbox after _wait_dispatcher_idle stops the dispatcher.diff --git a/studio/backend/tests/test_tensor_parallel.py b/studio/backend/tests/test_tensor_parallel.pyindex 9f63fb72946..ae765bfce6e 100644--- a/studio/backend/tests/test_tensor_parallel.py+++ b/studio/backend/tests/test_tensor_parallel.py@@ -512,6 +512,102 @@ def test_runtime_recovery_restores_requested_mode(monkeypatch):assert b._spec_fallback_reason == "runtime_error"+def test_runtime_recovery_does_not_publish_state_when_reload_is_cancelled(monkeypatch):+ b = _recovery_backend()+ b._requested_spec_mode = "auto"+ b._spec_fallback_reason = "existing"+ done = threading.Event()++ def _cancelled_load(intent):+ done.set()+ return False++ monkeypatch.setattr(b, "load_model", _cancelled_load)+ assert b._maybe_recover_from_mtp_crash(RuntimeError()) is True+ assert done.wait(timeout = 5)+ deadline = time.monotonic() + 2+ while b._mtp_runtime_fallback_in_progress and time.monotonic() < deadline:+ time.sleep(0.02)+ assert b._requested_spec_mode == "auto"+ assert b._spec_fallback_reason == "existing"+++def test_runtime_recovery_undoes_an_unload_during_reload(monkeypatch):+ b = _recovery_backend()+ b._requested_spec_mode = "auto"+ b._spec_fallback_reason = "existing"+ done = threading.Event()+ unloads = []++ def _racing_load(intent):+ b._unload_epoch += 1+ done.set()+ return True++ monkeypatch.setattr(b, "load_model", _racing_load)+ monkeypatch.setattr(b, "unload_model", lambda: unloads.append(1) or True)+ assert b._maybe_recover_from_mtp_crash(RuntimeError()) is True+ assert done.wait(timeout = 5)+ deadline = time.monotonic() + 2+ while b._mtp_runtime_fallback_in_progress and time.monotonic() < deadline:+ time.sleep(0.02)+ assert unloads == [1]+ assert b._requested_spec_mode == "auto"+ assert b._spec_fallback_reason == "existing"+++def test_runtime_recovery_publishes_state_atomically_with_unload(monkeypatch):+ b = _recovery_backend()+ b._last_load_intent = replace(+ b._last_load_intent,+ extra_args = ("--spec-type", "draft-mtp"),+ gpu_ids = (0,),+ )+ b._requested_extra_args = ["old"]+ b._requested_spec_mode = "auto"+ b._spec_fallback_reason = "existing"+ load_finished = threading.Event()+ unload_entered = threading.Event()+ unload_done = threading.Event()+ unload_threads = []++ def _fake_load(intent):+ load_finished.set()+ return True++ def _unload_state():+ unload_entered.set()+ b._cancel_event.set()+ with b._lock:+ b._unload_epoch += 1+ b._requested_extra_args = None+ b._requested_spec_mode = None+ b._spec_fallback_reason = None+ unload_done.set()++ def _race_after_epoch_check(extra_args):+ thread = threading.Thread(target = _unload_state)+ unload_threads.append(thread)+ thread.start()+ assert unload_entered.wait(timeout = 2)+ unload_done.wait(timeout = 0.2)+ return list(extra_args)++ monkeypatch.setattr(b, "load_model", _fake_load)+ monkeypatch.setattr(b, "_strip_device_extra_args", _race_after_epoch_check)+ assert b._maybe_recover_from_mtp_crash(RuntimeError()) is True+ assert load_finished.wait(timeout = 5)+ assert unload_done.wait(timeout = 5)+ for thread in unload_threads:+ thread.join(timeout = 2)+ deadline = time.monotonic() + 2+ while b._mtp_runtime_fallback_in_progress and time.monotonic() < deadline:+ time.sleep(0.02)+ assert b._requested_extra_args is None+ assert b._requested_spec_mode is None+ assert b._spec_fallback_reason is None++def test_runtime_recovery_skips_when_process_replaced(monkeypatch):# A newer user load that replaces the process during the death-confirm poll# must not be clobbered by the stale recovery replay.@@ -911,13 +1007,20 @@ def test_socket_probe_is_false_without_a_port():assert b._server_socket_is_open() is False-def test_runtime_recovery_rechecks_cancel_before_reload():- # recover() must re-check the cancel flag after the death poll (load_model- # clears it), so a reload scheduled just before /unload can't resurrect it.- src = inspect.getsource(LlamaCppBackend._maybe_recover_from_mtp_crash)- cancel = src.rfind("self._cancel_event.is_set()")- load = src.find("self.load_model(")- assert 0 <= cancel < load, "recovery must re-check cancel before reloading"+def test_runtime_recovery_rechecks_cancel_after_the_death_poll(monkeypatch):+ b = _recovery_backend()+ process = _BlockingDeadProc()+ b._process = process+ loads = []+ monkeypatch.setattr(b, "load_model", lambda intent: loads.append(intent) or True)++ assert b._maybe_recover_from_mtp_crash(RuntimeError()) is True+ b._cancel_event.set()+ process.release()+ deadline = time.monotonic() + 2+ while b._mtp_runtime_fallback_in_progress and time.monotonic() < deadline:+ time.sleep(0.02)+ assert loads == []def test_probe_mtp_decode_uses_api_key_auth(monkeypatch):@@ -1778,7 +1881,7 @@ class TestLegacyBuildQuantizedKvInTensorMode:},)()- backend._wait_for_health = lambda timeout: not self._doomed(spawns[-1])+ backend._wait_for_health = lambda timeout, **_kw: not self._doomed(spawns[-1])error: list[BaseException] = []with patch.object(subprocess, "Popen", side_effect = fake_popen):try: