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: bring the login screen up before the ML stack loads (#7607)
Daniel Han4316454dff5a
diff --git a/studio/backend/core/inference/orchestrator.py b/studio/backend/core/inference/orchestrator.pyindex 4699148a08b..8b6edd66e37 100644--- a/studio/backend/core/inference/orchestrator.py+++ b/studio/backend/core/inference/orchestrator.py@@ -28,10 +28,20 @@ from io import BytesIOfrom pathlib import Pathfrom typing import Any, Generator, Optional, Tuple, Unionfrom utils.hardware import get_device, prepare_gpu_selection+from utils.utils import hf_env_offline++# Re-exported from the shared helper so GGUF, training and inference share one type.+# Via PEP 562, not a module-level import: resolving the name imports unsloth_zoo, hence+# torch, and routes/inference.py imports this module at startup only for GenStream*.+DownloadStallError: type+++def __getattr__(name: str):+ if name == "DownloadStallError":+ from utils.hf_xet_fallback import DownloadStallError as _exc+ return _exc+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")-# Re-exported from the shared helper so GGUF, training, and inference share one-# type; kept importable here for backwards compatibility.-from utils.hf_xet_fallback import DownloadStallErrorlogger = get_logger(__name__)@@ -143,7 +153,16 @@ class InferenceOrchestrator:self.loading_models: set = set()from core.inference.defaults import get_default_models+ # The list depends on detection (chat-only hosts get the GGUF set) and the MLX+ # self-heal re-detects, so unchecked a repaired Mac serves the chat-only list+ # forever. Stamp read BEFORE the list, or a re-detect tags the old list as new.+ import utils.hardware.hardware as _hw_mod++ self._static_models_generation = _hw_mod.DETECTION_GENERATIONself._static_models = get_default_models()+ # Own lock for the stamp/value pair; the construction lock is held across a+ # build that waits on hardware detection.+ self._static_models_lock = threading.Lock()self._top_gguf_cache: Optional[list[str]] = Noneself._top_hub_cache: Optional[list[str]] = Noneself._top_models_ready = threading.Event()@@ -151,14 +170,61 @@ class InferenceOrchestrator:atexit.register(self._cleanup)logger.info("InferenceOrchestrator initialized (subprocess mode)")- threading.Thread(target = self._fetch_top_models, daemon = True, name = "top-models").start()+ # Deliberately NOT started here: construction now runs on the startup warm thread, so+ # fetching from __init__ would call huggingface.co on every boot. First reader starts it.+ self._top_models_started = False# ------------------------------------------------------------------# Default models (top GGUFs fetched dynamically from HF)# ------------------------------------------------------------------+ def _refresh_static_models_if_stale(self) -> None:+ """Recompute the curated defaults if hardware was re-detected since."""+ import utils.hardware.hardware as _hw_mod++ generation = _hw_mod.DETECTION_GENERATION+ if generation == self._static_models_generation:+ return+ from core.inference.defaults import get_default_models++ # Built outside the lock so readers do not queue behind the torch import.+ models = get_default_models()+ with self._static_models_lock:+ # Commit only while still the newest: a slow reader storing its older list+ # under a newer stamp would look current for the life of the process.+ if generation != _hw_mod.DETECTION_GENERATION:+ return+ if generation <= self._static_models_generation:+ return+ self._static_models = models+ self._static_models_generation = generation+ logger.info("hardware was re-detected; curated default models refreshed")++ def _start_top_models_fetch(self) -> None:+ """Kick the remote ranking fetch once, on first read of the model list.++ Guarded by the construction lock, so two concurrent first-readers cannot each put up+ a thread. Skipped when the host asked for no outbound calls: the fetch is a raw+ httpx.get, so HF_HUB_OFFLINE does not reach it on its own. Via hf_env_offline(), not+ a literal "1" test, since HF_HUB_OFFLINE=true/on and TRANSFORMERS_OFFLINE count too.+ """+ if self._top_models_started:+ return+ # Checked before the latch: claiming it while offline would retire the fetch for the+ # process, so an offline boot or a temporary force_hf_offline() could never recover.+ if hf_env_offline():+ logger.info("offline mode requested; skipping the remote top-models ranking")+ return+ with _inference_backend_lock:+ if self._top_models_started:+ return+ self._top_models_started = True+ threading.Thread(target = self._fetch_top_models, daemon = True, name = "top-models").start()+@propertydef default_models(self) -> list[str]:+ self._refresh_static_models_if_stale()+ self._start_top_models_fetch()top_gguf = self._top_gguf_cache or []top_hub = self._top_hub_cache or []# Never wait for the remote Hugging Face ranking during startup. Chat's@@ -396,9 +462,7 @@ class InferenceOrchestrator:" This usually means the system killed it under memory pressure. ""Try a smaller model, lower context length, or close other GPU-heavy apps.")- return (- f"{message}{suffix} " f"Details: pid={pid}, signal={sig_name}, exitcode={exitcode}."- )+ return f"{message}{suffix} Details: pid={pid}, signal={sig_name}, exitcode={exitcode}."return f"{message} Details: pid={pid}, exitcode={exitcode}."@@ -440,6 +504,10 @@ class InferenceOrchestrator:message, so long-running operations (large downloads, slow loads)survive as long as the subprocess keeps reporting progress."""+ # Local: resolving this name runs the shim's lazy unsloth_zoo load, which pulls torch.+ # The shim caches its pick, so this site and load_model()'s `except` see one class.+ from utils.hf_xet_fallback import DownloadStallError+deadline = time.monotonic() + timeoutwhile time.monotonic() < deadline:@@ -480,7 +548,7 @@ class InferenceOrchestrator:)raise RuntimeError(- f"Timeout waiting for '{expected_type}' response " f"(no activity for {timeout}s)"+ f"Timeout waiting for '{expected_type}' response (no activity for {timeout}s)")def _drain_queue(self) -> list:@@ -1118,6 +1186,9 @@ class InferenceOrchestrator:"""from utils.transformers_version import needs_transformers_5+ # Same lazy-shim reason as _wait_response(); see the note there.+ from utils.hf_xet_fallback import DownloadStallError+model_name = config.identifierself.loading_models.add(model_name)@@ -2096,11 +2167,27 @@ class InferenceOrchestrator:# ========== GLOBAL INSTANCE ==========_inference_backend = None+# Guards the lazy construction below. The first build runs hardware detection, seconds cold,+# and first-paint routes call this getter from executor threads. Unlocked, several would see+# None and each build an orchestrator, orphaning all but the last plus any load on them.+_inference_backend_lock = threading.Lock()+++def peek_inference_backend() -> Optional["InferenceOrchestrator"]:+ """The orchestrator if one exists, else None. Never constructs one.++ For callers that only describe what is already loaded: constructing reaches+ get_default_models() -> get_device(), which blocks on the torch import during the warm.+ """+ return _inference_backenddef get_inference_backend() -> InferenceOrchestrator:"""Global inference backend instance (orchestrator)."""global _inference_backend+ # Double-checked: the cheap read keeps the hot path lock-free, the recheck picks a builder.if _inference_backend is None:- _inference_backend = InferenceOrchestrator()+ with _inference_backend_lock:+ if _inference_backend is None:+ _inference_backend = InferenceOrchestrator()return _inference_backenddiff --git a/studio/backend/core/research_runs.py b/studio/backend/core/research_runs.pyindex cdd13ea866f..fd8f3420d93 100644--- a/studio/backend/core/research_runs.py+++ b/studio/backend/core/research_runs.py@@ -625,6 +625,26 @@ def _positive_int_or_none(value: object) -> int | None:return value if isinstance(value, int) and not isinstance(value, bool) and value > 0 else None+def _peek_inference_backend() -> Any:+ """The orchestrator if one already exists, else None. Never constructs one.++ A resumed durable run probes on uvicorn's loop, and constructing reaches+ get_default_models() -> get_device(), so a cold probe would block the loop on the torch+ import just to answer "nothing is loaded". A patched core.inference getter still wins:+ that is the seam these probes are injected through.+ """+ from core.inference import get_inference_backend++ try:+ from core.inference.orchestrator import get_inference_backend as _real+ from core.inference.orchestrator import peek_inference_backend+ except Exception:+ return get_inference_backend()+ return (+ get_inference_backend() if get_inference_backend is not _real else peek_inference_backend()+ )++def _loaded_context_length() -> int | None:"""Best-effort read of the active model's context window in tokens, or None if unknown.@@ -644,9 +664,7 @@ def _loaded_context_length() -> int | None:logger.debug("research.context_probe_llama_failed", exc_info = True)# Native / transformers: the orchestrator the API layer reads (not the subprocess singleton).try:- from core.inference import get_inference_backend-- backend = get_inference_backend()+ backend = _peek_inference_backend()name = getattr(backend, "active_model_name", None)models = getattr(backend, "models", {}) or {}info = models.get(name) if (name and isinstance(models, dict)) else None@@ -688,8 +706,8 @@ def _local_model_ready() -> bool:except Exception:logger.debug("research.model_probe_llama_failed", exc_info = True)try:- from core.inference import get_inference_backend- if getattr(get_inference_backend(), "active_model_name", None):+ # No orchestrator yet is a real answer (nothing is loaded), not a failed probe.+ if getattr(_peek_inference_backend(), "active_model_name", None):return Trueprobed = Trueexcept Exception:diff --git a/studio/backend/hub/services/models/deletion.py b/studio/backend/hub/services/models/deletion.pyindex c7369080585..d48632f29fa 100644--- a/studio/backend/hub/services/models/deletion.py+++ b/studio/backend/hub/services/models/deletion.py@@ -577,11 +577,15 @@ def _llama_cpp_blocks_delete(repo_id: str, variant: Optional[str]) -> bool:def _inference_backend_blocks_delete(repo_id: str) -> bool:"""Whether the subprocess inference backend holds *repo_id*; same fail-open-on-acquire / surface-on-query contract as :func:`_llama_cpp_blocks_delete`."""try:- from core.inference import get_inference_backend- backend = get_inference_backend()+ from core.inference.orchestrator import peek_inference_backend++ # Peek, never construct: building one just to learn nothing is loaded imports torch.+ backend = peek_inference_backend()except Exception as e:logger.debug(f"Inference backend unavailable during delete guard for {repo_id}: {e}")return False+ if backend is None:+ return Falseactive_name = backend.active_model_namereturn bool(active_name) and _loaded_id_matches_repo(active_name, repo_id)@@ -609,10 +613,15 @@ async def delete_cached_model_response(# Guard fails closed: if a live backend's load state can't be read, abort# with 503 rather than risk unlinking weights under a running process.- try:- blocks_delete = _llama_cpp_blocks_delete(repo_id, variant) or (+ # Both guards are sync and the second reaches get_inference_backend(), whose cold+ # build waits on hardware detection. One worker keeps the `or` short-circuit.+ def _load_state_blocks_delete() -> bool:+ return _llama_cpp_blocks_delete(repo_id, variant) or (_inference_backend_blocks_delete(repo_id))++ try:+ blocks_delete = await asyncio.to_thread(_load_state_blocks_delete)except Exception as e:logger.warning(f"Load-state verification failed for {repo_id}; refusing delete: {e}")raise HTTPException(diff --git a/studio/backend/main.py b/studio/backend/main.pyindex c8f903f0d1e..3541704c6ed 100644--- a/studio/backend/main.py+++ b/studio/backend/main.py@@ -334,13 +334,19 @@ from routes.profile_stats import router as profile_stats_routerfrom auth import storagefrom auth.authentication import get_current_subjectfrom utils.hardware import (- detect_hardware,+ start_background_detection,get_device,DeviceType,get_backend_visible_gpu_info,)import utils.hardware.hardware as _hw_module+from utils.torch_warmup import (+ DISABLE_ENV_VAR,+ join_background_warm,+ reset_background_warm,+ start_background_warm,+)from utils.cache_cleanup import clear_unsloth_compiled_cachefrom utils.lifespan_shutdown import run_lifespan_shutdownfrom utils.native_path_leases import native_path_leases_supported@@ -496,6 +502,112 @@ def _warm_rag_embedder() -> None:pass+_post_warm_thread: Optional[threading.Thread] = None+_post_warm_lock = threading.Lock()+# Bumped by every start and stop. A worker captures the value it started with and stops once+# it no longer matches, so one parked in join_background_warm() cannot act after shutdown.+_post_warm_generation = 0+++def _post_warm_current_generation() -> int:+ with _post_warm_lock:+ return _post_warm_generation+++def _start_post_warm_thread() -> bool:+ """Put up a post-warm worker for this lifespan. True iff one was started.++ Starts one even while a previous worker is parked in the warm join. Declining there+ left a restart with no worker at all: the old one was alive so this returned early,+ then read the shutdown and exited. Generations make the overlap safe -- the stale+ worker drops out by itself and a parked thread is free.+ """+ global _post_warm_thread, _post_warm_generation+ with _post_warm_lock:+ _post_warm_generation += 1+ mine = _post_warm_generation+ thread = threading.Thread(+ target = _post_warm_background_work,+ args = (mine,),+ daemon = True,+ name = f"post-warm-{mine}",+ )+ _post_warm_thread = thread+ thread.start()+ return True+++def _stop_post_warm_thread() -> None:+ """Retire whatever worker is current; never wait for it.++ Joining would hold shutdown for the rest of the ML stack import, the stall this path+ exists to avoid. Bumping the generation suffices: the worker re-reads it after its join.+ """+ global _post_warm_generation+ with _post_warm_lock:+ _post_warm_generation += 1+++def _post_warm_retired(generation: Optional[int]) -> bool:+ """True when this post-warm worker's lifespan has ended. Logs once when it has.++ A mismatch means the application that wanted this work has stopped. Everything the+ worker does imports or loads something, and the RAG warm can spawn a llama-server, so+ none of it may start for a stopped lifespan.+ """+ if generation is None or _post_warm_current_generation() == generation:+ return False+ import structlog as _structlog++ _structlog.get_logger(__name__).info(+ "post-warm work %s stood down: its lifespan ended while the ML stack was still loading",+ generation,+ )+ return True+++def _post_warm_background_work(generation: Optional[int] = None) -> None:+ """Stack-dependent startup work, run after the coordinated warm.++ Both import the ML stack, and both used to do it their own way before the socket bound:+ the MLX check inline on the lifespan thread (a healthy Mac waited on mlx.core/mlx_lm/+ mlx_vlm before uvicorn could bind), the RAG embedder early enough to race the warm for+ the GIL and the import locks, outside its hardware-first order and purge-on-failure.++ Joining the warm first means the stack is imported once, in the intended order.+ """+ # No-op when the warm never started, so this is safe under the kill switch.+ join_background_warm()++ # Shutdown routinely lands while parked in the join above, and everything below imports+ # or loads part of the stack. Rechecked before every action, since MLX autorepair and the+ # RAG warm each take their own time. generation is None only for a direct call (tests).+ if _post_warm_retired(generation):+ return++ # Apple Silicon with MLX missing => chat-only; reinstall mlx and re-detect so a dropped+ # mlx self-heals. No-op elsewhere; opt out with UNSLOTH_DISABLE_MLX_AUTOREPAIR=1. After+ # the warm because the availability probe imports the MLX runtime.+ try:+ from utils.mlx_repair import start_mlx_autorepair_if_needed+ if _post_warm_retired(generation):+ return+ start_mlx_autorepair_if_needed()+ except Exception as _mlx_exc:+ import structlog as _structlog+ _structlog.get_logger(__name__).debug("mlx autorepair skipped: %s", _mlx_exc)++ # Only the RAG warm is gated: it pulls sentence-transformers/transformers/torch, which+ # is what this kill switch prevents. MLX autorepair has its own opt-out, and gating it+ # would leave a broken MLX Mac chat-only for good.+ if os.environ.get(DISABLE_ENV_VAR) == "1":+ return++ if _post_warm_retired(generation):+ return+ _warm_rag_embedder()++@asynccontextmanagerasync def lifespan(app: FastAPI):"""Startup: detect hardware, seed default admin if needed. Shutdown: clean up compiled cache."""@@ -513,24 +625,9 @@ async def lifespan(app: FastAPI):if overlay_dir.is_dir():shutil.rmtree(overlay_dir, ignore_errors = True)- # Detect hardware first — sets the DEVICE global used everywhere.- detect_hardware()-- _lifespan_log.info(- "lifespan hardware detection completed in %.1fms",- (_time.perf_counter() - _lifespan_started) * 1000,- )-- # Apple Silicon with MLX missing => Train/Export are greyed out (chat-only).- # Reinstall mlx by name on a background thread (off the critical path) and- # re-detect, so a reinstall/update that dropped mlx self-heals. No-op- # elsewhere; opt out with UNSLOTH_DISABLE_MLX_AUTOREPAIR=1.- try:- from utils.mlx_repair import start_mlx_autorepair_if_needed- start_mlx_autorepair_if_needed()- except Exception as _mlx_exc:- import structlog as _structlog- _structlog.get_logger(__name__).debug("mlx autorepair skipped: %s", _mlx_exc)+ # Hardware detection and MLX autorepair moved out of this lifespan: both import heavy+ # runtimes and uvicorn binds only once this returns, so they held the login screen behind+ # the import. Detection is stage one of the warm below; autorepair runs post-warm.# Reap workers/runs orphaned by a previous crash before new work starts.try:@@ -558,8 +655,9 @@ async def lifespan(app: FastAPI):except Exception as exc:_lifespan_log.warning("reconcile_orphaned_ingestion_jobs failed at startup: %s", exc)+ # The RAG embedder warm moved to _post_warm_background_work: started here it raced+ # the warm for the GIL and the import locks._start_helper_precache_if_enabled()- threading.Thread(target = _warm_rag_embedder, daemon = True, name = "rag-embedder-warm").start()from core.research_runs import ResearchSupervisor@@ -601,12 +699,29 @@ async def lifespan(app: FastAPI):None if _suppress_bootstrap else storage.get_bootstrap_password())+ # Last, so it never contends with the work above for the GIL. The socket binds as soon as+ # this returns, so the login screen is up while torch/transformers/datasets load.+ start_background_warm()+ _start_post_warm_thread()+_lifespan_log.info("lifespan startup completed in %.1fms",(_time.perf_counter() - _lifespan_started) * 1000,)yield+ # Before any shutdown await: a warm finishing during one would still read the lifespan as+ # current and start MLX autorepair or the RAG embedder.+ _stop_post_warm_thread()++ # Same for the coordinated warm: retiring its epoch stops it at the next stage boundary.+ # run_lifespan_shutdown() also invalidates, but only after several awaits, through which+ # the warm keeps importing for a stopped lifespan. Retiring twice is harmless. getattr+ # for parity with the helper: tests stub the hardware module.+ _invalidate_detection = getattr(_hw_module, "invalidate_detection", None)+ if _invalidate_detection is not None:+ _invalidate_detection()+_idle_task = getattr(app.state, "idle_unload_task", None)if _idle_task is not None:_idle_task.cancel()@@ -628,6 +743,9 @@ async def lifespan(app: FastAPI):clear_unsloth_compiled_cache,_hw_module,)+ # Shutdown cleared the state this warm produced, so release the one-per-process latch and+ # let a second lifespan warm again. No-op while the first warm is still running.+ reset_background_warm()app = FastAPI(@@ -1070,6 +1188,76 @@ install_api_error_handlers(app)# ============ Health and System Endpoints ============+# /api/health has a hard deadline: preflight/backend.rs probes it with a 2s timeout right+# after TAURI_PORT is emitted, and a timeout is not retried -- it falls through to+# "desktop_owned_backend_starting", a dead end the user must clear by hand. TAURI_PORT is+# emitted before detection finishes, so health must answer within budget either way.+#+# A target, not a guarantee: the wait polls on the event loop and a C-extension import can+# hold the GIL past it. 1.5s measured a 1.742s worst case, only 0.26s of margin; 1.0s buys+# that back for one extra provisional reply, and the next poll ~0.3s later carries the real+# value. Nothing the launcher reads depends on detection -- only the web UI reads chat_only.+_HEALTH_DETECT_BUDGET_S = 1.0+++async def _await_hardware_detection(budget: float) -> bool:+ """Wait up to ``budget`` seconds for DEVICE to be set. True iff it is.++ Polls on the event loop instead of awaiting ensure_hardware_detected() in a thread:+ asyncio.wait_for cannot cancel a to_thread, so a timed-out call holds the executor slot+ for the rest of the import and a polled endpoint would drain the pool. Detection runs on+ the warm thread, or the one start_background_detection() puts up.++ Returns False without kicking anything when the warm is switched off. Health is probed+ automatically (desktop preflight, the frontend's first fetch), so kicking detection here+ would import torch on every such host and the switch would buy nothing. The provisional+ answer ships instead and the first hardware-dependent operation detects.+ """+ if os.environ.get(DISABLE_ENV_VAR) == "1":+ return _hw_module.DETECTION_COMPLETE.is_set() and _hw_module.DEVICE is not None+ # The event, not DEVICE alone: branches assign DEVICE and keep probing. And DEVICE too,+ # not the event alone: shutdown clears DEVICE then the event, so a racing detector can+ # leave event-set-with-DEVICE-None, serving a torn-down verdict instead of re-detecting.+ if _hw_module.DETECTION_COMPLETE.is_set() and _hw_module.DEVICE is not None:+ return True+ start_background_detection()+ loop = asyncio.get_running_loop()+ deadline = loop.time() + budget+ while not (_hw_module.DETECTION_COMPLETE.is_set() and _hw_module.DEVICE is not None):+ if loop.time() >= deadline:+ return False+ await asyncio.sleep(0.02)+ return True+++def _hardware_snapshot() -> Optional[tuple[bool, Optional[str]]]:+ """``(chat_only, chat_only_reason)`` if detection is settled, else ``None``.++ A seqlock read rather than ``_DETECT_LOCK``: that lock would park the endpoint for the+ whole torch import, the stall this startup path removes. A forced re-detect clears the+ event on the way in and bumps the generation before setting it again, so a read bracketed+ by both lands wholly before or after one pass, never mid-pass where CHAT_ONLY is back to+ True and the reason to None.++ That middle must not be published: config/env.ts caches the first reply carrying+ `device_type` as authoritative, and the sidebar's recovery poll runs only while it reads+ `chat_only_reason == "mlx_unavailable"`, so one such reply hides Train for the session.+ """+ for _ in range(3):+ if not _hw_module.DETECTION_COMPLETE.is_set():+ return None+ generation = _hw_module.DETECTION_GENERATION+ device = _hw_module.DEVICE+ chat_only = bool(_hw_module.CHAT_ONLY)+ reason = getattr(_hw_module, "CHAT_ONLY_REASON", None)+ if (+ device is not None+ and _hw_module.DETECTION_COMPLETE.is_set()+ and _hw_module.DETECTION_GENERATION == generation+ ):+ return chat_only, reason+ return None+@app.get("/api/liveness")async def liveness_check():@@ -1097,11 +1285,19 @@ async def health_check(request: Request):backend and gate UI before a token exists. version / studio_version /device_type require a bearer since they fingerprint the host."""+ # Wait for detection rather than grey out Train/Export on a GPU host for a second, but+ # only up to a budget. Called for the wait, not the answer: _hardware_snapshot() below+ # decides what the reply says, and a True here can be stale by the time it is read.+ await _await_hardware_detection(_HEALTH_DETECT_BUDGET_S)+ # Snapshot, not a bare global read: a forced re-detect can start at any moment.+ snapshot = _hardware_snapshot()base = {"status": "healthy","timestamp": datetime.now().isoformat(),"service": "Unsloth UI Backend",- "chat_only": _hw_module.CHAT_ONLY,+ # Literal True with no snapshot, not a CHAT_ONLY read: a pass in flight sets the flag+ # False before a probe that can still fall back to CPU. hardware-verdict.ts stores as-is.+ "chat_only": snapshot[0] if snapshot is not None else True,"desktop_protocol_version": 1,# Lockstep: see the note in /api/liveness above."desktop_manageability_version": 2,@@ -1112,6 +1308,14 @@ async def health_check(request: Request):"native_path_leases_supported": native_path_leases_supported(),**({"desktop_owner": owner} if (owner := _desktop_owner()) else {}),}+ if snapshot is None:+ # chat_only above is the conservative pre-detection default, not a measurement,+ # so a client caching it should re-read. Additive: older launchers ignore it.+ base["hardware_detecting"] = True+ if os.environ.get(DISABLE_ENV_VAR) == "1":+ # Nothing is detecting until a hardware-dependent operation runs, so a client+ # polling for a measured verdict would wait out its whole budget. Say so instead.+ base["hardware_detection_deferred"] = Trueauth = request.headers.get("authorization", "")if not auth.lower().startswith("bearer "):return base@@ -1129,20 +1333,40 @@ async def health_check(request: Request):if not subject:return base+ # Re-read: the bearer check is an await, so a forced re-detect can land between+ # the snapshot taken for `base` and the authoritative fields below.+ snapshot = _hardware_snapshot()+platform_map = {"darwin": "mac", "win32": "windows", "linux": "linux"}device_type = platform_map.get(sys.platform, sys.platform)- return {+ authed = {**base,- # Why chat_only is set. This fingerprints the host, so keep it authed.- "chat_only_reason": getattr(_hw_module, "CHAT_ONLY_REASON", None),"version": UNSLOTH_VERSION,"studio_version": STUDIO_VERSION,- "device_type": device_type,# API-screen fields (authed-only; they fingerprint how the host is exposed)."cloudflare_url": getattr(request.app.state, "cloudflare_url", None),"server_url": getattr(request.app.state, "server_url", None),"secure": bool(getattr(request.app.state, "secure", False)),}+ if snapshot is not None:+ # Why chat_only is set; fingerprints the host, so keep it authed. All three+ # come from one snapshot, so the reason cannot disagree with the chat_only.+ authed["chat_only"] = snapshot[0]+ authed["chat_only_reason"] = snapshot[1]+ authed["device_type"] = device_type+ # base predates the bearer await, so its marker can describe a snapshot+ # detection has since replaced. Never ship "detecting" beside a measurement.+ authed.pop("hardware_detecting", None)+ # Same for the deferred marker: the client reads it first and would keep the+ # previous reason against a verdict that now has one.+ authed.pop("hardware_detection_deferred", None)+ else:+ # A re-detect started during the bearer await and base carries no chat_only_reason,+ # so a client reading this as measured would store reason null and stop the sidebar's+ # mlx_unavailable recovery poll. Mark provisional and omit device_type: env.ts treats+ # a present device_type as authoritative and would pin a GPU host to chat-only.+ authed["hardware_detecting"] = True+ return authed@app.get("/api/studio/install-source")@@ -1419,7 +1643,8 @@ def get_system_info(current_subject: str = Depends(get_current_subject)):@app.get("/api/system/gpu-visibility")async def get_gpu_visibility(current_subject: str = Depends(get_current_subject)):- return get_backend_visible_gpu_info()+ # Off-loop: get_device() blocks on detection while the warm is still importing torch.+ return await asyncio.to_thread(get_backend_visible_gpu_info)@app.get("/api/system/hardware")diff --git a/studio/backend/mcp_server.py b/studio/backend/mcp_server.pyindex e93490411d9..981ae66aba6 100644--- a/studio/backend/mcp_server.py+++ b/studio/backend/mcp_server.py@@ -11,6 +11,7 @@ start GPU work or write model artifacts.from __future__ import annotationsimport hmac+import asynciofrom typing import Anyfrom fastmcp import FastMCP@@ -111,7 +112,8 @@ def create_studio_mcp() -> FastMCP:"training": _dump(training),"export": _dump(export),"inference": _dump(inference),- "hardware": get_gpu_utilization(),+ # Off-loop: reaches hardware detection, which blocks on the warm's torch import.+ "hardware": await asyncio.to_thread(get_gpu_utilization),}@mcp.tooldiff --git a/studio/backend/routes/export.py b/studio/backend/routes/export.pyindex d44e2ac0211..76252b67d5a 100644--- a/studio/backend/routes/export.py+++ b/studio/backend/routes/export.py@@ -46,7 +46,7 @@ router = APIRouter()logger = get_logger(__name__)-def _ensure_export_supported() -> None:+async def _ensure_export_supported() -> None:"""Reject a mutating export request up front (HTTP 400) when the host can't export.Keeps the backend authoritative even if a client bypasses the UI gate. Read-only endpoints@@ -64,7 +64,8 @@ def _ensure_export_supported() -> None:from utils.hardware import export_capability- cap = export_capability()+ # Off-loop: detection is deferred past bind, so the first call can wait on a cold import.+ cap = await asyncio.to_thread(export_capability)if not cap.get("export_supported", True):raise HTTPException(status_code = 400,@@ -85,7 +86,7 @@ async def load_checkpoint(a clear error instead of tearing down the user's other running workloads."""try:- _ensure_export_supported()+ await _ensure_export_supported()backend = get_export_backend()# Run in a worker thread (spawns and waits on a subprocess, can take# minutes) so the event loop stays free to serve the live log SSE stream.@@ -299,7 +300,7 @@ async def export_merged_model(Wraps ExportBackend.export_merged_model."""try:- _ensure_export_supported()+ await _ensure_export_supported()backend = get_export_backend()success, message, output_path = await asyncio.to_thread(backend.export_merged_model,@@ -344,7 +345,7 @@ async def export_base_model(Wraps ExportBackend.export_base_model."""try:- _ensure_export_supported()+ await _ensure_export_supported()backend = get_export_backend()success, message, output_path = await asyncio.to_thread(backend.export_base_model,@@ -388,7 +389,7 @@ async def export_gguf(Wraps ExportBackend.export_gguf."""try:- _ensure_export_supported()+ await _ensure_export_supported()backend = get_export_backend()# A custom path wins; otherwise the imatrix toggle requests the upstream auto-download.imatrix_file = request.imatrix_path or (True if request.imatrix else None)@@ -434,7 +435,7 @@ async def export_lora_adapter(Wraps ExportBackend.export_lora_adapter."""try:- _ensure_export_supported()+ await _ensure_export_supported()backend = get_export_backend()success, message, output_path = await asyncio.to_thread(backend.export_lora_adapter,diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex df277e55204..17d4ff35675 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -3246,14 +3246,30 @@ def _monitor_anthropic_response(return response+def _peek_inference_backend() -> Any:+ """The orchestrator if one already exists, else None. Never constructs one.++ Constructing reaches get_default_models() -> get_device(), so during the warm a caller+ that only describes what is loaded would block uvicorn on the torch import to answer+ "nothing". A patched module getter still wins: that is this module's injection seam.+ """+ from core.inference import orchestrator as _orch++ if get_inference_backend is not _orch.get_inference_backend:+ return get_inference_backend()+ return _orch.peek_inference_backend()++def _monitor_context_length() -> Optional[int]:llama_backend = get_llama_cpp_backend()if getattr(llama_backend, "is_loaded", False):context_length = _positive_int_or_none(getattr(llama_backend, "context_length", None))if context_length is not None:return context_length- backend = get_inference_backend()- if not backend.active_model_name:+ # Peek, not the constructing getter: called inline from the OpenAI, Responses and+ # Anthropic monitor paths, and no orchestrator already means nothing is loaded.+ backend = _peek_inference_backend()+ if backend is None or not backend.active_model_name:return Nonemodels = getattr(backend, "models", {}) or {}model_info = models.get(backend.active_model_name, {}) if isinstance(models, dict) else {}@@ -3298,7 +3314,11 @@ def _monitor_active_model() -> Optional[str]:if model_id and variant and ":" not in model_id:return f"{model_id}:{variant}"return model_id- backend = get_inference_backend()+ # Peek: the monitor overlay is on by default and polls this read-only, so building+ # the singleton to answer "nothing loaded" would import torch on a warm-disabled host.+ backend = _peek_inference_backend()+ if backend is None:+ return Nonereturn public_model_id(backend.active_model_name) or backend.active_model_name@@ -4066,7 +4086,7 @@ async def _no_model_loaded_error(if named is None or not get_openai_auto_switch_enabled():return status, _no_model_loaded_detail(base)try:- if _loaded_satisfies(named):+ if await asyncio.to_thread(_loaded_satisfies, named):# Resident but on a backend this endpoint can't use, so "not downloaded" is false.return status, _no_model_loaded_detail(base)if await asyncio.to_thread(resolve_local_gguf, named) is not None:@@ -4129,7 +4149,7 @@ async def _maybe_auto_download_model(if not is_downloadable_ref(requested_model):return# An Ollama-style tag (":latest") names no quant, so the resolver misses a servable model.- if _loaded_satisfies(requested_model):+ if await asyncio.to_thread(_loaded_satisfies, requested_model):returntry:refusal = await maybe_auto_download(@@ -4374,11 +4394,11 @@ async def _reject_unservable_model(still_indexing = Falsetry:- if _loaded_satisfies(requested_model):+ if await asyncio.to_thread(_loaded_satisfies, requested_model):returnif not (get_llama_cpp_backend().is_loaded- or getattr(get_inference_backend(), "active_model_name", None)+ or getattr(await asyncio.to_thread(get_inference_backend), "active_model_name", None)):return# Refresh in the background and read the index as-is: scanning here would stall the@@ -4405,9 +4425,11 @@ async def _reject_unservable_model(# so match on the path too. Quants of one repo share a directory, so the path# alone cannot tell them apart: without the variant check an explicit :Q8_0# would be answered by a resident Q4_K_M.+ # Off-loop: reads the Transformers singleton, and the llama.cpp short-circuits above+ # skip the offloaded reads, so on a restart this built the singleton on the loop.if (resolved is not None- and _resolves_to_resident(resolved[0], llama_only = quantified)+ and await asyncio.to_thread(_resolves_to_resident, resolved[0], llama_only = quantified)and (not quantified or _resident_quant_is(variant))):return@@ -4416,7 +4438,7 @@ async def _reject_unservable_model(advertised = _advertised_local_path(base)if (advertised is not None- and _resolves_to_resident(advertised, llama_only = quantified)+ and await asyncio.to_thread(_resolves_to_resident, advertised, llama_only = quantified)and (not quantified or _resident_quant_is(variant))):return@@ -4553,7 +4575,9 @@ async def _maybe_auto_switch_model(if (not lastor get_llama_cpp_backend().is_loaded- or getattr(get_inference_backend(), "active_model_name", None)+ or getattr(+ await asyncio.to_thread(get_inference_backend), "active_model_name", None+ )):returnif len(last) == 3:@@ -5002,11 +5026,20 @@ async def _override_gpu_ids_still_resolve(gpu_ids: List[int]) -> bool:from utils.hardware import DeviceType, get_devicefrom utils.hardware.hardware import resolve_requested_gpu_ids- is_vulkan = LlamaCppBackend._is_vulkan_backend()- if get_device() == DeviceType.XPU and not is_vulkan:+ # One hop for the whole device-dependent block: resolve_requested_gpu_ids() reaches+ # get_device() itself, so both wait on the detection lock during the warm.+ def _device_and_resolution() -> tuple[object, bool, list]:+ is_vulkan = LlamaCppBackend._is_vulkan_backend()+ return (+ get_device(),+ is_vulkan,+ resolve_requested_gpu_ids(gpu_ids, is_vulkan = is_vulkan),+ )++ device, is_vulkan, resolved = await asyncio.to_thread(_device_and_resolution)+ if device == DeviceType.XPU and not is_vulkan:# Rejected outright on XPU.return False- resolved = resolve_requested_gpu_ids(gpu_ids, is_vulkan = is_vulkan)if is_vulkan and resolved:# Vulkan ordinals are their own index space, so presence needs the ggml probe.binary = LlamaCppBackend._find_llama_server_binary()@@ -5066,7 +5099,8 @@ async def _resolve_gguf_gpu_ids_for_request(diffusion_kind = _classify_diffusion_gguf(config)confirmed_diffusion = diffusion_kind is Truedefinitively_non_diffusion = diffusion_kind is False- device = get_device()+ # Off-loop: get_device() waits on the detection lock, i.e. the cold torch import.+ device = await asyncio.to_thread(get_device)lacks_gpu_lib = getattr(llama_backend, "_backend_lacks_gpu_lib", None)# ROCm is deliberately DeviceType.CUDA internally because it uses@@ -5890,7 +5924,7 @@ async def _load_model_impl()# ── Already-loaded check: skip reload if the exact model is active ──- backend = get_inference_backend()+ backend = await asyncio.to_thread(get_inference_backend)llama_backend = get_llama_cpp_backend()# Resolve the slot count once (per-load field, else the server-wide@@ -6057,6 +6091,8 @@ async def _load_model_impl(gguf_variant = request.gguf_variant,)+ # Guard and call go to the worker together: from_identifier can import transformers+ # to build the detection registry, and the guard's probe is a network round trip.config = await asyncio.to_thread(_resolve_config)if not config:@@ -6155,7 +6191,7 @@ async def _load_model_impl(# ── GGUF path: load via llama-server ──────────────────────if config.is_gguf:llama_backend = get_llama_cpp_backend()- unsloth_backend = get_inference_backend()+ unsloth_backend = await asyncio.to_thread(get_inference_backend)if config.gguf_hf_repo:from core.inference.llama_cpp import gguf_load_in_flight@@ -6459,7 +6495,7 @@ async def _load_model_impl()# ── Standard path: load via Unsloth/transformers ──────────- backend = get_inference_backend()+ backend = await asyncio.to_thread(get_inference_backend)# Same sidecar rejection as GGUF: fast path ahead of the drain, rechecked after._raise_if_sidecar_swap_in_progress()@@ -6802,6 +6838,8 @@ async def validate_model(# The frontend validates before it loads, so this needs the same guard as# /load; otherwise the stall just moves here and /load is never reached.+ # Off-loop twice over: the guard is a network round trip, and the first+ # from_identifier builds the detection registry (transformers, or the warm's lock).def _resolve_config():with _hf_offline_if_unreachable_for(model_identifier):return ModelConfig.from_identifier(@@ -7204,7 +7242,7 @@ async def install_latest_transformers_route(# before_swap, only once the staged install succeeded: a failed pip/compat check# must not leave the user with their model gone. GGUF stays loaded (llama-server# never imports transformers).- backend = get_inference_backend()+ backend = await asyncio.to_thread(get_inference_backend)export_backend = get_export_backend()unloaded_chat = {"v": False}@@ -7361,7 +7399,7 @@ async def _unload_model_impl(request: UnloadRequest, current_subject: str):# model promptly, and /load holds the lifecycle gate for the whole load. cancel_load only# tears the loading subprocess down, so it is safe off-gate -- and ahead of the# active-generation refusal below, which it can never need (see there).- backend = get_inference_backend()+ backend = await asyncio.to_thread(get_inference_backend)loading = getattr(backend, "get_loading_model", lambda: None)()if (loading is not None@@ -7404,7 +7442,7 @@ async def _unload_model_impl(request: UnloadRequest, current_subject: str):# anything yet, so neither can interrupt a chat, and refusing them counted a teardown that# cannot happen (unretryably -- the frontend's Cancel sends this unload unforced and drops# the error). Any other name still falls through here.- if _unload_may_evict(request.model_path):+ if await asyncio.to_thread(_unload_may_evict, request.model_path):_raise_or_cancel_active_generations(force = request.force_cancel_active,action = "Unloading the model",@@ -7419,7 +7457,7 @@ async def _unload_model_impl(request: UnloadRequest, current_subject: str):# Rechecked under the gate, like /load: a chat can register while this one queues here (the# middleware takes and releases the same gate). Still refusal only, and re-read rather# than carried down, since a load may have finished meanwhile.- if _unload_may_evict(request.model_path):+ if await asyncio.to_thread(_unload_may_evict, request.model_path):_raise_or_cancel_active_generations(force = request.force_cancel_active,action = "Unloading the model",@@ -7465,7 +7503,7 @@ async def _unload_model_impl(request: UnloadRequest, current_subject: str):# Unload from Unsloth backend off the event loop: unload takes _gen_lock, which# a slow SSE stream paused between tokens still holds, so a sync call would block# the loop that drives the stream's next token and the lock release.- backend = get_inference_backend()+ backend = await asyncio.to_thread(get_inference_backend)if _unload_evicts_standard_backend(backend, request.model_path):# Point of no return for the standard path, same rule as above._raise_or_cancel_active_generations(@@ -7550,7 +7588,11 @@ async def confirm_tool_call(@studio_router.get("/monitor")async def get_api_monitor(current_subject: str = Depends(get_current_subject)):"""Return recent OpenAI-compatible API activity for Unsloth."""- active_model = _monitor_active_model()+ # Off-loop: both helpers reach get_inference_backend(), whose first call waits on+ # hardware detection, and this is polled from first paint.+ active_model, context_length = await asyncio.to_thread(+ lambda: (_monitor_active_model(), _monitor_context_length())+ )active_requests = api_monitor.active_count(subject = current_subject)if active_requests:operating_status = "generating"@@ -7567,7 +7609,7 @@ async def get_api_monitor(current_subject: str = Depends(get_current_subject)):# against this, since the browser's clock need not agree over a tunnel."server_time": time.time(),"active_model": active_model,- "context_length": _monitor_context_length(),+ "context_length": context_length,"active_requests": active_requests,"logging_enabled": api_monitor.enabled,"entries": api_monitor.snapshot(include_details = False, subject = current_subject),@@ -7610,7 +7652,7 @@ async def generate_stream(For vision models, provide image_base64 (base64-encoded image)."""- backend = get_inference_backend()+ backend = await asyncio.to_thread(get_inference_backend)if not backend.active_model_name:raise HTTPException(@@ -7844,8 +7886,16 @@ async def get_status(current_subject: str = Depends(get_current_subject)):llama_cpp_latest_tag = _latest_tag,)- # Otherwise, report Unsloth backend status- backend = get_inference_backend()+ # Otherwise report Unsloth backend status. Peek rather than build: no singleton means+ # nothing is loaded, and the chat UI polls this from first paint.+ backend = _peek_inference_backend()+ if backend is None:+ return InferenceStatusResponse(+ llama_cpp_supports_mtp = _supports_mtp,+ llama_cpp_prebuilt_stale = _stale,+ llama_cpp_installed_tag = _installed_tag,+ llama_cpp_latest_tag = _latest_tag,+ )is_vision = Falseis_audio = False@@ -8021,7 +8071,7 @@ async def generate_audio(cancel_event = _audio_cancel,)else:- backend = get_inference_backend()+ backend = await asyncio.to_thread(get_inference_backend)if not backend.active_model_name:raise HTTPException(status_code = 400, detail = "No model loaded.")model_info = backend.models.get(backend.active_model_name, {})@@ -9689,7 +9739,7 @@ async def openai_chat_completions(context_length = llama_backend.context_length,)else:- backend = get_inference_backend()+ backend = await asyncio.to_thread(get_inference_backend)if not backend.active_model_name:_status, _detail = await _no_model_loaded_error("No model loaded. Call POST /inference/load first.",@@ -12637,7 +12687,9 @@ async def _openai_catalog_objects() -> list[dict]:_created = int(time.time())# Loaded models first (clean ids + context fields), marked loaded.by_id: dict[str, dict] = {}- for entry in _openai_model_objects():+ # Off-loop: _openai_model_objects() is sync and calls get_inference_backend(), whose cold+ # build waits on detection. Inline, an early GET /v1/models held the loop for the import.+ for entry in await asyncio.to_thread(_openai_model_objects):by_id[entry["id"]] = {**entry, "loaded": True}# Locally available (downloaded/cached) models that are not already loaded.@@ -12711,7 +12763,8 @@ async def openai_retrieve_model(model_id: str, current_subject: str = Depends(ge# Loaded models resolve without a catalog scan (the common case); only build# the full catalog -- which may hit the filesystem -- for unloaded ids. Match# case-insensitively, like the catalog loop below and the resolver's index.- _loaded = _openai_model_objects()+ # Off-loop like the catalog helper: the singleton's cold build waits on detection.+ _loaded = await asyncio.to_thread(_openai_model_objects)for entry in _loaded:eid = entry["id"]if isinstance(eid, str) and eid.lower() == model_id.lower():@@ -12731,7 +12784,7 @@ async def openai_retrieve_model(model_id: str, current_subject: str = Depends(ge# path, so public_model_id(path) would miss the advertised entry and 404 a# model that is in fact loaded.llama_backend = get_llama_cpp_backend()- backend = get_inference_backend()+ backend = await asyncio.to_thread(get_inference_backend)raw_to_public: list[tuple[str, Optional[str]]] = []if llama_backend.is_loaded and llama_backend.model_identifier:raw_to_public.append(diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.pyindex d6678e55f31..837b01c3c46 100644--- a/studio/backend/routes/models.py+++ b/studio/backend/routes/models.py@@ -1786,7 +1786,9 @@ def _looks_like_mlx_repo(model_id: str) -> bool:async def list_models(current_subject: str = Depends(get_current_subject)):"""List available models: default plus currently loaded."""try:- inference_backend = get_inference_backend()+ # Off-loop: building the singleton calls get_device(), and the frontend+ # fetches this on load, so inline it would freeze the whole torch import.+ inference_backend = await asyncio.to_thread(get_inference_backend)default_models = inference_backend.default_models@@ -2157,8 +2159,11 @@ async def discard_remote_code_download(except Exception:passtry:- inference_backend = get_inference_backend()- if inference_backend.active_model_name:+ # Peek, not construct: no orchestrator means no active model to protect, and+ # building one here would reach get_device() and wait on the torch import.+ from core.inference.orchestrator import peek_inference_backend+ inference_backend = peek_inference_backend()+ if inference_backend is not None and inference_backend.active_model_name:if _loaded_id_matches_repo(inference_backend.active_model_name, model_name):return {"deleted": False, "reason": "loaded"}except Exception:@@ -2497,25 +2502,29 @@ async def delete_finetuned_model() from etry:- inference_backend = get_inference_backend()- loading_models = getattr(inference_backend, "loading_models", set())- if any(- _loading_model_matches_deleted_path(loading_model, target_path)- for loading_model in loading_models- ):- raise HTTPException(- status_code = 409,- detail = "Cannot delete a model while it is loading",- )- if inference_backend.active_model_name:- if _loaded_model_matches_deleted_path(- inference_backend.active_model_name,- target_path,+ # Peek: no orchestrator means nothing below can block this delete, and building one+ # to learn that reaches get_device() -- a torch import for a metadata-only op.+ from core.inference.orchestrator import peek_inference_backend+ inference_backend = peek_inference_backend()+ if inference_backend is not None:+ loading_models = getattr(inference_backend, "loading_models", set())+ if any(+ _loading_model_matches_deleted_path(loading_model, target_path)+ for loading_model in loading_models):raise HTTPException(- status_code = 400,- detail = "Unload the model before deleting",+ status_code = 409,+ detail = "Cannot delete a model while it is loading",)+ if inference_backend.active_model_name:+ if _loaded_model_matches_deleted_path(+ inference_backend.active_model_name,+ target_path,+ ):+ raise HTTPException(+ status_code = 400,+ detail = "Unload the model before deleting",+ )except HTTPException:raiseexcept Exception as e:@@ -2643,7 +2652,8 @@ async def check_vision_model(# A local path resolves from disk, so it skips the probe.from core.inference.llama_cpp import _hf_offline_if_unreachable_for- # Off the loop: the guard's probes are blocking and stall unrelated requests.+ # Off-loop: the probes block, and is_vision_model()'s lazy sets make the first+ # call import transformers or wait on _DETECTION_SETS_LOCK behind the warm.def _check():with _hf_offline_if_unreachable_for(model_name):return is_vision_model(model_name, hf_token = hf_token)diff --git a/studio/backend/routes/training.py b/studio/backend/routes/training.pyindex 8be4283415f..01f530c87e5 100644--- a/studio/backend/routes/training.py+++ b/studio/backend/routes/training.py@@ -103,7 +103,10 @@ async def get_hardware_utilization(current_subject: str = Depends(get_current_suPolled by the frontend during training."""from utils.hardware import get_gpu_utilization- return get_gpu_utilization()++ # Off-loop like /hardware/visible below; the first call blocks on detection while+ # the warm is importing torch.+ return await asyncio.to_thread(get_gpu_utilization)@router.get("/hardware/visible")@@ -223,6 +226,9 @@ async def start_training(# Validate streaming-mode compatibility before any expensive work.# Streaming is supported only for Hugging Face text datasets.+ from utils.hardware import hardware as _hw+ from utils.hardware import ensure_hardware_detected+if request.dataset_streaming:if not request.hf_dataset:raise HTTPException(@@ -239,8 +245,10 @@ async def start_training(status_code = 400,detail = "dataset_streaming is not supported for embedding training; the embedding loader needs the full dataset.",)- from utils.hardware import hardware as _hw-+ # The warm fills DEVICE shortly after the socket binds, so a start in that window+ # would read None, skip the MLX rejection, and hand a streaming dataset to the MLX+ # loader (which materializes it whole). Detect first, off-loop: it imports torch.+ await asyncio.to_thread(ensure_hardware_detected)if _hw.DEVICE == _hw.DeviceType.MLX:raise HTTPException(status_code = 400,@@ -282,6 +290,10 @@ async def start_training("Streaming is not supported with S3 datasets."),)+ else:+ # The synchronous backend start builds its worker config with get_device().+ # Detect off-loop first so an early start cannot stall login or health.+ await asyncio.to_thread(ensure_hardware_detected)# Convert request to backend kwargs.training_kwargs = {diff --git a/studio/backend/tests/test_async_singleton_access.py b/studio/backend/tests/test_async_singleton_access.pynew file mode 100644index 00000000000..ded8d3d075d--- /dev/null+++ b/studio/backend/tests/test_async_singleton_access.py@@ -0,0 +1,204 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Async handlers must not build the inference singleton on the event loop.++Construction runs get_default_models() -> hw.get_device(), so the first caller waits+for the background warm. Inline, that holds the event-loop thread for the whole torch+import, stalling login, liveness and the deadline-bound desktop health probe.++The offload has to stay at the call site, passing the route module's own+`get_inference_backend` to a thread. A helper in orchestrator.py would resolve that+module's global instead, bypassing callers that patch `routes.inference.get_inference_backend`.+"""++from __future__ import annotations++import ast+import sys+from pathlib import Path++_BACKEND = Path(__file__).resolve().parent.parent+if str(_BACKEND) not in sys.path:+ sys.path.insert(0, str(_BACKEND))++# Every read below pins utf-8: Path.read_text() defaults to the locale encoding (cp1252+# on Windows), which cannot decode routes/inference.py, so these guards would raise+# instead of failing honestly.+_ROUTE_FILES = ("routes/inference.py", "routes/models.py")+++def _async_call_sites(rel: str) -> list[str]:+ """Bare get_inference_backend() invocations inside an async def.+ `asyncio.to_thread(get_inference_backend)` passes the function object, an ast.Name and+ never an ast.Call, so only real on-loop invocations are reported."""+ tree = ast.parse((_BACKEND / rel).read_text(encoding = "utf-8"))+ found = []+ for fn in ast.walk(tree):+ if not isinstance(fn, ast.AsyncFunctionDef):+ continue+ for sub in ast.walk(fn):+ if not (isinstance(sub, ast.Call) and isinstance(sub.func, ast.Name)):+ continue+ if sub.func.id == "get_inference_backend":+ found.append(f"{rel}:{sub.lineno} in async {fn.name}")+ return found+++def test_no_async_handler_builds_the_singleton_inline():+ offenders = [s for rel in _ROUTE_FILES for s in _async_call_sites(rel)]+ assert not offenders, "async handlers building the singleton inline:\n " + "\n ".join(+ offenders+ )+++def test_the_offload_is_actually_present():+ """Guard against the sweep passing because the calls simply vanished. Counted off the+ AST: a literal-string count would report the offload gone the moment a formatter wraps+ one of these calls across lines."""+ total = 0+ for rel in _ROUTE_FILES:+ tree = ast.parse((_BACKEND / rel).read_text(encoding = "utf-8"))+ total += sum(+ 1+ for node in ast.walk(tree)+ if isinstance(node, ast.Call)+ and isinstance(node.func, ast.Attribute)+ and node.func.attr == "to_thread"+ and any(isinstance(a, ast.Name) and a.id == "get_inference_backend" for a in node.args)+ )+ # 13, not 14: the status poll's site became a non-constructing peek, which needs no+ # offload at all. Lower the floor only when a site is removed that way, never when+ # one goes back on the loop.+ assert total >= 13, f"expected the offloaded call sites to survive, found {total}"+++def _sync_helpers_that_build_the_singleton(rel: str) -> set[str]:+ """Sync functions in this module that call get_inference_backend() inline."""+ tree = ast.parse((_BACKEND / rel).read_text(encoding = "utf-8"))+ names = set()+ for fn in ast.walk(tree):+ if not isinstance(fn, ast.FunctionDef): # sync only+ continue+ # The peek helper is the module's injection seam: it invokes the getter only+ # when that global has been patched, which is a test double, and otherwise+ # returns orchestrator.peek_inference_backend(). Reading it as a builder would+ # report every caller that deliberately stopped constructing.+ if fn.name == "_peek_inference_backend":+ continue+ for sub in ast.walk(fn):+ if (+ isinstance(sub, ast.Call)+ and isinstance(sub.func, ast.Name)+ and sub.func.id == "get_inference_backend"+ ):+ names.add(fn.name)+ return names+++def test_no_async_handler_reaches_the_singleton_through_a_sync_helper():+ """The direct sweep is not enough: a sync helper hides the same stall. _loaded_satisfies+ calls get_inference_backend() inline, so an async handler calling it on the loop pays+ the cold build all the same, and walking only ast.AsyncFunctionDef misses that."""+ offenders = []+ for rel in _ROUTE_FILES:+ helpers = _sync_helpers_that_build_the_singleton(rel)+ if not helpers:+ continue+ tree = ast.parse((_BACKEND / rel).read_text(encoding = "utf-8"))+ for fn in ast.walk(tree):+ if not isinstance(fn, ast.AsyncFunctionDef):+ continue+ for sub in ast.walk(fn):+ # A bare Call to the helper runs it on the loop; passing it to+ # to_thread makes it an ast.Name argument, never a Call.+ if (+ isinstance(sub, ast.Call)+ and isinstance(sub.func, ast.Name)+ and sub.func.id in helpers+ ):+ offenders.append(f"{rel}:{sub.lineno} async {fn.name} -> {sub.func.id}()")++ # Empty on purpose. Both monitor helpers used to sit here as a known gap: they+ # reached the singleton through a sync helper and were not individually offloaded,+ # so they blocked during exactly the window this path exists to fix. Both now peek+ # instead. Do not add a name back without an offload or a justification here.+ known: set[str] = set()++ # _resolves_to_resident is offloaded at its two singleton-reading call sites. The+ # third, in _openai_catalog_objects, passes llama_only = True, under which the+ # helper never evaluates the getter. This sweep matches on callee name and cannot+ # see that, so exempt by argument rather than blanket-exempting the helper.+ def _is_llama_only(site: str) -> bool:+ rel, rest = site.split(":", 1)+ lineno = int(rest.split(" ", 1)[0])+ tree = ast.parse((_BACKEND / rel).read_text(encoding = "utf-8"))+ for node in ast.walk(tree):+ if (+ isinstance(node, ast.Call)+ and getattr(node.func, "id", None) == "_resolves_to_resident"+ and node.lineno == lineno+ ):+ return any(+ kw.arg == "llama_only"+ and isinstance(kw.value, ast.Constant)+ and kw.value.value is True+ for kw in node.keywords+ )+ return False++ offenders = [o for o in offenders if not _is_llama_only(o)]+ new = [o for o in offenders if o.rsplit("-> ", 1)[-1].rstrip("()") not in known]+ assert not new, (+ "new async handlers reaching the singleton through a sync helper; "+ "offload at the call site rather than widening the baseline:\n " + "\n ".join(new)+ )+++def test_the_offload_stays_at_the_call_site():+ """No orchestrator-level async helper: it would bypass patched route globals.++ tests/test_orchestrator_unload_cancel.py patches routes.inference.get_inference_backend.+ An accessor defined in orchestrator.py resolves orchestrator's own global, so the patch+ would not take and the test hangs on a load gate that never opens."""+ orch = (_BACKEND / "core/inference/orchestrator.py").read_text(encoding = "utf-8")+ assert "async def get_inference_backend_async" not in orch, (+ "an async accessor in orchestrator.py bypasses callers that patch the "+ "route module's get_inference_backend"+ )+++# The read-only surface: these answer "what is loaded" and must never be the reason a+# host imports torch. Each is polled from first paint or fired by a metadata-only+# action, so building the singleton here defeats UNSLOTH_STUDIO_DISABLE_TORCH_WARM=1+# until a genuinely hardware-dependent operation runs.+_READ_ONLY_SITES = (+ ("routes/inference.py", "_monitor_active_model"),+ ("routes/inference.py", "get_status"),+ ("routes/models.py", "delete_finetuned_model"),+)+++def test_read_only_endpoints_never_construct_the_singleton():+ """Peek, not build. A peek is a plain global read, so it needs no offload either."""+ offenders = []+ for rel, name in _READ_ONLY_SITES:+ tree = ast.parse((_BACKEND / rel).read_text(encoding = "utf-8"))+ fn = next(+ (+ node+ for node in ast.walk(tree)+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == name+ ),+ None,+ )+ assert fn is not None, f"{rel}:{name} moved; update this guard"+ for sub in ast.walk(fn):+ # Both shapes: a bare call on the loop, and the name handed to to_thread,+ # which still constructs and still imports torch.+ if isinstance(sub, ast.Name) and sub.id == "get_inference_backend":+ offenders.append(f"{rel}:{sub.lineno} {name}")+ assert not offenders, (+ "read-only paths construct the inference singleton, so a status poll or a "+ "metadata-only delete imports torch on a warm-disabled host:\n " + "\n ".join(offenders)+ )diff --git a/studio/backend/tests/test_defaults_refresh_after_redetect.py b/studio/backend/tests/test_defaults_refresh_after_redetect.pynew file mode 100644index 00000000000..9e128e0584a--- /dev/null+++ b/studio/backend/tests/test_defaults_refresh_after_redetect.py@@ -0,0 +1,115 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The curated default models must survive a re-detection.++Detection is not once-per-process: on Apple Silicon with a missing MLX stack the first pass+is chat-only, then the autorepair installs MLX, re-detects, and CHAT_ONLY flips.+get_default_models() reads that state and the warm snapshots it before the repair runs, so+without a staleness check the host serves the chat-only list for the rest of the process.+"""++from __future__ import annotations++import sys+from pathlib import Path++_BACKEND = Path(__file__).resolve().parent.parent+if str(_BACKEND) not in sys.path:+ sys.path.insert(0, str(_BACKEND))++import core.inference.defaults as defaults_mod # noqa: E402+import utils.hardware.hardware as hw # noqa: E402+from core.inference.orchestrator import InferenceOrchestrator # noqa: E402+++def _orchestrator(monkeypatch, models):+ monkeypatch.setattr(InferenceOrchestrator, "_fetch_top_models", lambda self: None)+ monkeypatch.setattr(defaults_mod, "get_default_models", lambda: list(models))+ return InferenceOrchestrator()+++def test_defaults_refresh_when_hardware_is_redetected(monkeypatch):+ monkeypatch.setattr(hw, "DETECTION_GENERATION", 1)+ orch = _orchestrator(monkeypatch, ["chat-only-gguf"])+ assert orch.default_models == ["chat-only-gguf"]++ # The MLX repair succeeds and re-detects: CHAT_ONLY flips, the curated list is full.+ monkeypatch.setattr(defaults_mod, "get_default_models", lambda: ["full-a", "full-b"])+ monkeypatch.setattr(hw, "DETECTION_GENERATION", 2)++ assert orch.default_models == [+ "full-a",+ "full-b",+ ], "the orchestrator is still serving the pre-repair chat-only list"+++def test_defaults_are_not_recomputed_without_a_redetect(monkeypatch):+ """The refresh is keyed on the generation, not on every read."""+ monkeypatch.setattr(hw, "DETECTION_GENERATION", 5)+ calls = []++ def _counted():+ calls.append(1)+ return ["a"]++ monkeypatch.setattr(InferenceOrchestrator, "_fetch_top_models", lambda self: None)+ monkeypatch.setattr(defaults_mod, "get_default_models", _counted)+ orch = InferenceOrchestrator()++ orch.default_models+ orch.default_models++ assert len(calls) == 1, f"recomputed {len(calls)}x without a re-detection"+++def test_detection_generation_advances_on_every_settled_detection():+ """The counter is what makes the staleness check possible."""+ before = hw.DETECTION_GENERATION+ hw.ensure_hardware_detected()+ hw.detect_hardware()+ assert hw.DETECTION_GENERATION > before+++def test_a_forced_redetect_unpublishes_while_it_runs(monkeypatch):+ """Health must not read a forced pass's intermediate globals as settled. The pass resets+ CHAT_ONLY and CHAT_ONLY_REASON before re-probing, so with the event left set a health+ request landing mid-repair reports that as authoritative and the sidebar's MLX recovery+ poll stops, the reason no longer being "mlx_unavailable"."""+ seen = []++ def _mid_pass():+ seen.append(hw.DETECTION_COMPLETE.is_set())+ return hw.DeviceType.CPU++ hw.DETECTION_COMPLETE.set()+ monkeypatch.setattr(hw, "_detect_hardware_locked", _mid_pass)++ hw.detect_hardware()++ assert seen == [False], "detection was still published while the forced pass ran"+ assert hw.DETECTION_COMPLETE.is_set(), "the forced pass must republish when it settles"+++def test_a_failed_forced_redetect_does_not_leave_detection_unpublished(monkeypatch):+ """Clearing the event must not be able to strand health forever.++ start_background_detection() declines once DEVICE is set, so nothing would republish and+ health would answer provisionally for the life of the process -- worse than the+ intermediate state the clear protects against. A raising pass restores what it found."""++ def _boom():+ raise RuntimeError("probe exploded mid-pass")++ hw.DETECTION_COMPLETE.set()+ monkeypatch.setattr(hw, "_detect_hardware_locked", _boom)++ try:+ hw.detect_hardware()+ except RuntimeError:+ pass++ assert hw.DETECTION_COMPLETE.is_set(), (+ "a failed forced re-detect left detection unpublished; health would stay "+ "provisional for the rest of the process"+ )diff --git a/studio/backend/tests/test_desktop_auth.py b/studio/backend/tests/test_desktop_auth.pyindex 039bb5e3e63..335caaa9634 100644--- a/studio/backend/tests/test_desktop_auth.py+++ b/studio/backend/tests/test_desktop_auth.py@@ -699,6 +699,9 @@ def test_health_response_reports_desktop_capability_fields(monkeypatch):import studio.backend.main as backend_main+ # DEVICE alongside the two it is set with, since /api/health waits on+ # ensure_hardware_detected(). CPU + "mlx_unavailable" is an MLX-less Apple Silicon.+ monkeypatch.setattr(backend_main._hw_module, "DEVICE", backend_main._hw_module.DeviceType.CPU)monkeypatch.setattr(backend_main._hw_module, "CHAT_ONLY", True)monkeypatch.setattr(backend_main._hw_module, "CHAT_ONLY_REASON", "mlx_unavailable")diff --git a/studio/backend/tests/test_export_capability.py b/studio/backend/tests/test_export_capability.pyindex e04417f9338..d086d48b659 100644--- a/studio/backend/tests/test_export_capability.py+++ b/studio/backend/tests/test_export_capability.py@@ -138,9 +138,9 @@ def test_main_endpoints_expose_export_capability():def test_routes_guard_mutating_endpoints():r = _src("routes/export.py")- assert "def _ensure_export_supported()" in r+ assert "async def _ensure_export_supported()" in r# load + all four export endpoints call the guard.- assert r.count("_ensure_export_supported()") >= 6+ assert r.count("await _ensure_export_supported()") >= 5def test_export_methods_check_runtime():@@ -154,3 +154,34 @@ def test_export_methods_check_runtime():def test_export_capability_reads_no_torch_helper():cap = _func_src("utils/hardware/hardware.py", "export_capability")assert "_has_torch()" in cap and "DeviceType.MLX" in cap and "is_apple_silicon()" in cap+++def test_a_failed_detection_is_reported_as_such(monkeypatch):+ """Do not send the user to fix something that is not wrong. ensure_hardware_detected()+ records CPU + "detection_failed" when the probe raises, so the host looks CPU-only to+ export_capability; reporting no_accelerator (or pytorch_not_installed) there points the+ remediation at hardware or an install that may both be fine."""+ from utils.hardware import hardware as hw++ monkeypatch.setattr(hw, "get_device", lambda: hw.DeviceType.CPU)+ monkeypatch.setattr(hw, "CHAT_ONLY_REASON", "detection_failed")++ cap = hw.export_capability()++ assert cap["export_supported"] is False+ assert cap["export_unsupported_reason"] == "detection_failed"+ assert "detection failed" in cap["export_unsupported_message"].lower()+++def test_a_genuinely_cpu_only_host_still_says_no_accelerator(monkeypatch):+ """The new branch must not swallow the case it sits in front of."""+ from utils.hardware import hardware as hw++ monkeypatch.setattr(hw, "get_device", lambda: hw.DeviceType.CPU)+ monkeypatch.setattr(hw, "CHAT_ONLY_REASON", "no_gpu")+ monkeypatch.setattr(hw, "is_apple_silicon", lambda: False)+ monkeypatch.setattr(hw, "_has_torch", lambda: True)++ cap = hw.export_capability()++ assert cap["export_unsupported_reason"] == "no_accelerator"diff --git a/studio/backend/tests/test_health_answers_within_probe_budget.py b/studio/backend/tests/test_health_answers_within_probe_budget.pynew file mode 100644index 00000000000..5ae24a6efb4--- /dev/null+++ b/studio/backend/tests/test_health_answers_within_probe_budget.py@@ -0,0 +1,349 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Invariant: /api/health answers inside the desktop launcher's probe timeout,+detected hardware or not.++studio/src-tauri/src/preflight/backend.rs probes with a 2s client timeout right after+TAURI_PORT is emitted, and a timeout is not retried: it falls through to+"desktop_owned_backend_starting", a dead end the user has to clear by hand. That was safe+while the lifespan detected inline, since TAURI_PORT came after detection; detection runs on+the warm thread now and TAURI_PORT precedes it, so an unbounded wait inside health puts a+cold `import torch` in front of that deadline. Nothing the launcher reads from health+depends on detection, only chat_only does.++CPU-only, no network, no GPU, no weights: the subprocess tests stub detection.+"""++from __future__ import annotations++import ast+import json+import re+import subprocess+import sys+from pathlib import Path++_BACKEND_DIR = Path(__file__).resolve().parent.parent # studio/backend+_MAIN_SRC = _BACKEND_DIR / "main.py"+_PROBE_RS = _BACKEND_DIR.parent / "src-tauri" / "src" / "preflight" / "backend.rs"+++def _run(snippet: str) -> subprocess.CompletedProcess:+ return subprocess.run(+ [sys.executable, "-c", snippet],+ cwd = str(_BACKEND_DIR),+ capture_output = True,+ text = True,+ timeout = 900,+ )+++def _main_constant(name: str) -> float:+ """Read a module-level float from main.py without importing it."""+ tree = ast.parse(_MAIN_SRC.read_text(encoding = "utf-8"))+ for node in tree.body:+ if isinstance(node, ast.Assign) and any(+ isinstance(t, ast.Name) and t.id == name for t in node.targets+ ):+ return float(ast.literal_eval(node.value))+ raise AssertionError(f"main.py no longer defines {name}")+++def test_the_budget_stays_under_the_desktop_probe_timeout():+ """Cross-language guard: the budget is only correct relative to the Rust one, and+ either side can be changed without the other."""+ assert _PROBE_RS.is_file(), f"{_PROBE_RS} moved; update this guard"+ rust = _PROBE_RS.read_text(encoding = "utf-8")+ probe = rust[rust.index("fn probe_ownerless_spawned_backend") :]+ # Bound to this function; a later one must not be the source of the number.+ end = probe.find("\n}\n")+ if end != -1:+ probe = probe[: end + 3]+ # The builder's .timeout() and the shared loopback_http::client() constructor both+ # take the client timeout as a whole-seconds Duration, and the probe sets exactly+ # one. Matching the Duration rather than either call site keeps this guard working+ # across that refactor while still failing if the unit stops being seconds.+ match = re.search(r"Duration::from_secs\((\d+)\)", probe)+ assert match, (+ "probe_ownerless_spawned_backend no longer sets a whole-seconds client "+ "timeout; re-derive the health budget from whatever replaced it"+ )+ probe_timeout = float(match.group(1))+ budget = _main_constant("_HEALTH_DETECT_BUDGET_S")+ assert budget < probe_timeout, (+ f"/api/health waits up to {budget}s for detection but the desktop probe "+ f"gives up at {probe_timeout}s"+ )+ # Connect, routing and JSON share the same 2s, and the budget overruns whenever a+ # C-extension import holds the GIL past it (0.24s measured at 1.5s). A budget that+ # only just fits is one slow host away from the dead end.+ assert probe_timeout - budget >= 0.9, (+ f"only {probe_timeout - budget}s of headroom between the health budget "+ f"and the {probe_timeout}s probe timeout"+ )+++_SNIPPET = r"""+import asyncio, json, os, sys, threading, time++# UNSLOTH_STUDIO_DISABLE_TORCH_WARM is deliberately NOT set here. It used to be,+# to keep a real warm out of the way, but nothing below runs the lifespan -- the+# app is built by hand with one route -- so no warm ever starts anyway. Setting+# it now would suppress the very kick these tests measure: health does not start+# detection when the switch is on, which is what makes the switch mean anything.+os.environ.pop("UNSLOTH_STUDIO_DISABLE_TORCH_WARM", None)++import main+from fastapi import FastAPI+from fastapi.testclient import TestClient++hw = main._hw_module+DETECT_SECONDS = %(detect_seconds)s++hw.DEVICE = None+hw.CHAT_ONLY = True+hw.CHAT_ONLY_REASON = None+# This stub stands in for ensure_hardware_detected, so it owns the same+# completion protocol. DEVICE alone no longer means "finished": the branches+# assign it partway through and keep probing, so the health wait polls+# DETECTION_COMPLETE instead. Start it clear to model "detection has not run".+hw.DETECTION_COMPLETE.clear()++def slow_detect(*_): # start_background_detection binds the spawn-time epoch+ # Stands in for the torch import the warm thread is running.+ time.sleep(DETECT_SECONDS)+ hw.DEVICE = hw.DeviceType.CUDA+ hw.CHAT_ONLY = False+ hw.CHAT_ONLY_REASON = None+ hw.DETECTION_COMPLETE.set()+ return hw.DEVICE++hw.ensure_hardware_detected = slow_detect++app = FastAPI()+app.add_api_route("/api/health", main.health_check, methods = ["GET"])+client = TestClient(app)++started = time.perf_counter()+response = client.get("/api/health")+elapsed = time.perf_counter() - started+body = response.json()++# Same request with a bearer, which is the one config/env.ts caches on.+# health_check imports get_current_subject inside the function, so patching the+# module attribute is enough and keeps this test off the real JWT/storage path.+import auth.authentication as _authmod++async def _subject(_creds):+ return "tester"++_authmod.get_current_subject = _subject+authed = client.get("/api/health", headers = {"Authorization": "Bearer probe"}).json()++print("RESULT" + json.dumps({+ "status": response.status_code,+ "elapsed": elapsed,+ "chat_only": body.get("chat_only"),+ "hardware_detecting": body.get("hardware_detecting"),+ "authed_has_device_type": "device_type" in authed,+ "authed_has_chat_only_reason": "chat_only_reason" in authed,+ "authed_hardware_detecting": authed.get("hardware_detecting"),+ "authed_has_version": "version" in authed,+}))+"""+++def _probe(detect_seconds: float) -> dict:+ proc = _run(_SNIPPET % {"detect_seconds": detect_seconds})+ assert (+ proc.returncode == 0+ ), f"probe failed\nstdout:\n{proc.stdout}\nstderr:\n{proc.stderr[-4000:]}"+ line = next(ln for ln in proc.stdout.splitlines() if ln.startswith("RESULT"))+ return json.loads(line[len("RESULT") :])+++# A pass that sets CHAT_ONLY False and then degrades, the shape every accelerator+# branch has: the flag is assigned before the device-name probe that can raise, and+# detect_hardware() restores the previous verdict on the way out.+_MID_PASS_SNIPPET = r"""+import json, os, threading, time++os.environ.pop("UNSLOTH_STUDIO_DISABLE_TORCH_WARM", None)++import main+from fastapi import FastAPI+from fastapi.testclient import TestClient++hw = main._hw_module+hw.DEVICE = None+hw.CHAT_ONLY = True+hw.CHAT_ONLY_REASON = None+hw.DETECTION_COMPLETE.clear()++def degrading_detect(*_):+ # The XPU branch verbatim: DEVICE and CHAT_ONLY assigned, then a probe that hangs+ # and would raise. DETECTION_COMPLETE is never set, so the verdict is not settled.+ hw.DEVICE = hw.DeviceType.XPU+ hw.CHAT_ONLY = False+ time.sleep(30.0)+ return hw.DEVICE++hw.ensure_hardware_detected = degrading_detect++app = FastAPI()+app.add_api_route("/api/health", main.health_check, methods = ["GET"])+client = TestClient(app)++# start_background_detection() runs the stub, which flips the global well inside the+# budget; the reply lands while the pass is still in flight.+body = client.get("/api/health").json()++print("RESULT" + json.dumps({+ "chat_only": body.get("chat_only"),+ "hardware_detecting": body.get("hardware_detecting"),+ "global_chat_only": hw.CHAT_ONLY,+ "complete": hw.DETECTION_COMPLETE.is_set(),+}))+"""+++def test_an_unsettled_pass_is_never_published_as_training_capable():+ """chat_only with no snapshot must be the literal True, not the live global.++ Every accelerator branch of _detect_hardware_locked assigns CHAT_ONLY = False and then+ keeps probing (torch.xpu.get_device_name, the MLX stack check), and a raise there+ degrades the host to CPU. DETECTION_COMPLETE stays clear throughout, so the reply is+ marked provisional; with the kill switch on it is also marked deferred, and+ hardware-verdict.ts stores data.chat_only verbatim for those. Reading the global+ therefore flashes Train and Export on a host that ends up chat-only."""+ proc = _run(_MID_PASS_SNIPPET)+ assert (+ proc.returncode == 0+ ), f"probe failed\nstdout:\n{proc.stdout}\nstderr:\n{proc.stderr[-4000:]}"+ line = next(ln for ln in proc.stdout.splitlines() if ln.startswith("RESULT"))+ result = json.loads(line[len("RESULT") :])++ assert not result["complete"], "the stub settled detection; the window is not modelled"+ assert result["global_chat_only"] is False, "the mid-pass flip did not happen"+ assert result["hardware_detecting"] is True, "expected a provisional reply"+ assert result["chat_only"] is True, (+ "health published chat_only=False from a detection pass still in flight; the "+ "frontend enables Train and Export until the real verdict lands"+ )+++def test_health_answers_within_the_budget_while_detection_is_slow():+ """The regression: detection outlasts the probe, health must not. Against an unbounded+ `await asyncio.to_thread(ensure_hardware_detected)` this returns in ~10s and the desktop+ launch dead-ends."""+ budget = _main_constant("_HEALTH_DETECT_BUDGET_S")+ result = _probe(10.0)++ assert result["status"] == 200+ assert result["elapsed"] < budget + 0.5, (+ f"/api/health took {result['elapsed']:.2f}s with detection still "+ f"running; the budget is {budget}s and the desktop probe gives up at 2s"+ )+ assert result["hardware_detecting"] is True, (+ "health returned a provisional chat_only without saying so; a client "+ "cannot tell it apart from a measured one"+ )+ # Conservative direction: never offer Train/Export on a host that may not have it.+ assert result["chat_only"] is True+++def test_health_still_waits_when_detection_finishes_inside_the_budget():+ """The budget is a ceiling, not a floor. The wait exists so a GPU host is not+ published as chat-only for a second; bounding it must not make every early health+ call provisional."""+ result = _probe(0.3)++ assert result["status"] == 200+ assert (+ result["chat_only"] is False+ ), "health published chat_only=True on a host whose detection completed well inside the budget"+ assert "hardware_detecting" not in result or result["hardware_detecting"] is None+++def test_health_does_not_await_detection_unbounded():+ """Static guard: health_check must go through the bounded helper. `await+ asyncio.to_thread(ensure_hardware_detected)` reads like the obvious fix and passes every+ test that pins DEVICE first; it only fails on a cold desktop launch."""+ tree = ast.parse(_MAIN_SRC.read_text(encoding = "utf-8"))+ health = next(+ node+ for node in ast.walk(tree)+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == "health_check"+ )+ called = {+ node.func.id+ for node in ast.walk(health)+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Name)+ }+ assert "_await_hardware_detection" in called, (+ "health_check no longer waits for detection through "+ "_await_hardware_detection; whatever replaced it must still answer "+ "inside the desktop probe timeout"+ )+ assert "ensure_hardware_detected" not in called, (+ "health_check calls ensure_hardware_detected directly again; that wait "+ "is unbounded and the desktop probe gives up at 2s"+ )+++def test_a_provisional_reply_is_not_cacheable_by_the_frontend():+ """The provisional reply must not look authoritative to config/env.ts.++ fetchDeviceType() sets ``fetched = data.device_type !== undefined`` and every later+ non-forced call short-circuits on ``fetched``, so a provisional authed reply carrying+ device_type pins chat_only=true for the rest of the SPA session on a GPU host: Train+ hidden, /studio redirected to /chat. The sidebar's recovery poll runs only for+ chat_only_reason === "mlx_unavailable", so it does not save it either."""+ result = _probe(10.0)++ assert result["authed_hardware_detecting"] is True, "expected a provisional reply"+ assert not result["authed_has_device_type"], (+ "the provisional authed reply carries device_type, so the frontend caches "+ "it as authoritative and never re-reads the measured chat_only"+ )+ assert not result[+ "authed_has_chat_only_reason"+ ], "chat_only_reason is meaningless before detection has run"+ # The launcher-facing fields are unaffected.+ assert result["authed_has_version"]+++def test_a_measured_reply_still_carries_the_authoritative_fields():+ """The omission is scoped to the provisional case."""+ result = _probe(0.3)++ assert not result["hardware_detecting"]+ assert result["authed_has_device_type"]+ assert result["authed_has_chat_only_reason"]+++def test_a_mid_detection_assignment_is_not_treated_as_finished():+ """DEVICE goes non-None before detection has settled. The XPU branch assigns DEVICE and+ CHAT_ONLY=False, then calls torch.xpu.get_device_name(0); if that raises, the host+ degrades to CPU/chat-only. A waiter keyed on "DEVICE is not None" would have published+ the intermediate value, reporting training available on a chat-only host."""+ import importlib+ import threading++ hw = importlib.import_module("utils.hardware.hardware")++ assert hasattr(+ hw, "DETECTION_COMPLETE"+ ), "detection needs a completion signal distinct from the DEVICE assignment"+ assert isinstance(hw.DETECTION_COMPLETE, threading.Event)++ src = _MAIN_SRC.read_text(encoding = "utf-8")+ start = src.index("async def _await_hardware_detection")+ body = src[start : start + 1800]+ assert (+ "DETECTION_COMPLETE" in body+ ), "the health wait must poll the completion signal, not the DEVICE assignment"+ assert (+ "while _hw_module.DEVICE is None" not in body+ ), "the health wait is keyed on the mid-detection assignment again"diff --git a/studio/backend/tests/test_inference_backend_singleton.py b/studio/backend/tests/test_inference_backend_singleton.pynew file mode 100644index 00000000000..0848f41722d--- /dev/null+++ b/studio/backend/tests/test_inference_backend_singleton.py@@ -0,0 +1,181 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Invariant: ``get_inference_backend()`` builds exactly one orchestrator, even+when several threads reach it at once.++The first call is expensive: ``__init__`` runs ``get_default_models()``, which calls+``hw.get_device()`` and so blocks on the torch warm, ~2.9s on a cold GPU host. That is why+the first-paint routes call it through ``asyncio.to_thread``.++Off-loop means genuinely parallel, though, and the getter used to be a plain check-then-set+on a module global. Concurrent first-paint requests all observed ``None`` inside that+window, each built an orchestrator, and the last assignment won. Orchestrator state is+per-instance (subprocess handle, ``loading_models``, ``active_model_name``), so a load+started on a loser became invisible to every later call.++The orchestrator is stubbed here: these exercise the getter's locking, not the constructor.+"""++from __future__ import annotations++import ast+import threading+from pathlib import Path++import pytest++import core.inference.orchestrator as orch++_ORCHESTRATOR_SRC = Path(orch.__file__)++# Wide enough that every thread is inside the window before the first leaves it, small+# enough to stay a unit test. The real window is ~2.9s.+_BUILD_SECONDS = 0.20+_THREADS = 8+++def fresh_singleton(monkeypatch):+ """Reset the module global and restore it afterwards. Set directly, not via+ monkeypatch.setattr, so the getter's ``global`` write is what the test observes."""+ saved = orch._inference_backend+ orch._inference_backend = None+ try:+ yield+ finally:+ orch._inference_backend = saved+++class _StubOrchestrator:+ """Records every construction and holds the window open the way detection does."""++ built: list["_StubOrchestrator"] = []+ _record_lock = threading.Lock()++ def __init__(self):+ with self._record_lock:+ self.__class__.built.append(self)+ # The real constructor spends this time in hw.get_device().+ threading.Event().wait(_BUILD_SECONDS)+++def stub_orchestrator(monkeypatch):+ _StubOrchestrator.built = []+ monkeypatch.setattr(orch, "InferenceOrchestrator", _StubOrchestrator)+ return _StubOrchestrator+++def test_concurrent_first_calls_build_exactly_one_orchestrator(fresh_singleton, stub_orchestrator):+ """The regression: N threads entering a cold getter together. Unlocked, every thread+ observes None inside the construction window and builds its own. Asserts both that one+ is built and that every caller gets that same one: an orphan handed to any caller is+ the bug."""+ handed_out: list[object] = []+ handed_lock = threading.Lock()+ errors: list[BaseException] = []+ gate = threading.Barrier(_THREADS)++ def worker():+ try:+ gate.wait(timeout = 30)+ backend = orch.get_inference_backend()+ with handed_lock:+ handed_out.append(backend)+ except BaseException as exc: # noqa: BLE001 - surfaced by the assert below+ errors.append(exc)++ threads = [threading.Thread(target = worker, name = f"getter-{i}") for i in range(_THREADS)]+ for t in threads:+ t.start()+ for t in threads:+ # Generous, so a deadlock fails here rather than hanging the suite.+ t.join(timeout = 60)+ assert not t.is_alive(), f"{t.name} never returned from get_inference_backend()"++ assert not errors, f"worker threads raised: {errors}"+ assert len(handed_out) == _THREADS++ assert len(stub_orchestrator.built) == 1, (+ f"{len(stub_orchestrator.built)} orchestrators were constructed; "+ "concurrent first calls must share one"+ )++ survivor = orch._inference_backend+ assert survivor is stub_orchestrator.built[0]+ orphans = [b for b in handed_out if b is not survivor]+ assert not orphans, (+ f"{len(orphans)} callers were handed an orchestrator that is not the "+ "module global; a load started on one would be invisible to later calls"+ )+++def test_warm_path_does_not_take_the_lock(fresh_singleton, stub_orchestrator):+ """Once built, the getter must not serialize on the lock. Every request path reaches it,+ so a single ``with`` around the whole body would funnel all of them through one mutex."""+ first = orch.get_inference_backend()+ assert len(stub_orchestrator.built) == 1++ returned: list[object] = []+ with orch._inference_backend_lock:+ # Lock held by this thread: a warm call from another must still return,+ # which it can only do by skipping the lock.+ t = threading.Thread(target = lambda: returned.append(orch.get_inference_backend()))+ t.start()+ t.join(timeout = 10)+ assert not t.is_alive(), "the warm path blocked on the singleton lock"++ assert returned == [first]+ assert len(stub_orchestrator.built) == 1+++def test_getter_constructs_under_a_module_level_lock():+ """Static guard: construction must stay inside a ``with`` on the lock. A refactor back to+ the bare ``if _inference_backend is None: ...`` reads fine and passes every+ single-threaded test, so pin the shape."""+ tree = ast.parse(_ORCHESTRATOR_SRC.read_text(encoding = "utf-8"))++ assigns_lock = [+ node+ for node in tree.body+ if isinstance(node, ast.Assign)+ and any(isinstance(t, ast.Name) and t.id == "_inference_backend_lock" for t in node.targets)+ ]+ assert len(assigns_lock) == 1, "expected one module-level _inference_backend_lock"++ getter = next(+ node+ for node in tree.body+ if isinstance(node, ast.FunctionDef) and node.name == "get_inference_backend"+ )++ constructions = [+ node+ for node in ast.walk(getter)+ if isinstance(node, ast.Call)+ and isinstance(node.func, ast.Name)+ and node.func.id == "InferenceOrchestrator"+ ]+ assert constructions, "get_inference_backend no longer constructs the orchestrator"++ guarded: set[int] = set()+ for with_node in ast.walk(getter):+ if not isinstance(with_node, ast.With):+ continue+ holds_lock = any(+ isinstance(item.context_expr, ast.Name)+ and item.context_expr.id == "_inference_backend_lock"+ for item in with_node.items+ )+ if not holds_lock:+ continue+ for inner in ast.walk(with_node):+ guarded.add(id(inner))++ unguarded = [c for c in constructions if id(c) not in guarded]+ assert not unguarded, (+ "InferenceOrchestrator() is constructed outside "+ "`with _inference_backend_lock:` -- concurrent first callers will each "+ "build their own and orphan all but the last"+ )diff --git a/studio/backend/tests/test_lifespan_restart_rewarms.py b/studio/backend/tests/test_lifespan_restart_rewarms.pynew file mode 100644index 00000000000..886fb8f58b2--- /dev/null+++ b/studio/backend/tests/test_lifespan_restart_rewarms.py@@ -0,0 +1,205 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A second lifespan in one process must re-detect and re-warm, not inherit.++Shutdown clears hardware.DEVICE, so after it the process holds no measured device. Two+pieces of bookkeeping have to be cleared with it or the next lifespan disagrees with+reality:++ * DETECTION_COMPLETE. /api/health takes a set event as "DEVICE is authoritative", so left+ set over a cleared DEVICE it publishes a device that is gone.+ * torch_warmup's one-warm-per-process latch. A finished thread left in place makes the+ second lifespan's start_background_warm() a no-op, so the stack stays cold.++Reachable through repeated ASGI lifespan contexts and an embedded restart, both of+which reuse the app object in one interpreter.+"""++from __future__ import annotations++import asyncio+import sys+import threading+import types+from pathlib import Path++_BACKEND = Path(__file__).resolve().parent.parent+if str(_BACKEND) not in sys.path:+ sys.path.insert(0, str(_BACKEND))++import utils.torch_warmup as warmup # noqa: E402+from utils.lifespan_shutdown import run_lifespan_shutdown # noqa: E402+++def _stub_hardware(*, with_event: bool = True) -> types.SimpleNamespace:+ stub = types.SimpleNamespace(DEVICE = "cuda:0")+ if with_event:+ stub.DETECTION_COMPLETE = threading.Event()+ stub.DETECTION_COMPLETE.set()+ return stub+++def test_shutdown_clears_the_detection_completion_signal():+ hw = _stub_hardware()+ asyncio.run(run_lifespan_shutdown(lambda: None, lambda: None, hw))+ assert hw.DEVICE is None+ assert not hw.DETECTION_COMPLETE.is_set(), (+ "shutdown cleared DEVICE but left DETECTION_COMPLETE set; /api/health "+ "would report the torn-down device as measured instead of re-detecting"+ )+++def test_shutdown_still_clears_device_without_the_event():+ """Negative control: a hardware module with no event must not break shutdown."""+ hw = _stub_hardware(with_event = False)+ asyncio.run(run_lifespan_shutdown(lambda: None, lambda: None, hw))+ assert hw.DEVICE is None+++def test_shutdown_runs_the_later_steps_even_if_clearing_raises():+ """A hardware module that rejects the write must not skip clear_compiled_cache,+ which is what frees the on-disk cache."""++ class Hostile:+ DEVICE = "cuda:0"++ def __setattr__(self, name, value):+ raise RuntimeError("read-only hardware module")++ cleared: list[str] = []+ asyncio.run(+ run_lifespan_shutdown(+ lambda: cleared.append("downloads"),+ lambda: cleared.append("compiled_cache"),+ Hostile(),+ )+ )+ assert cleared == ["downloads", "compiled_cache"]+++def _restore(monkeypatch) -> None:+ """Put the module-level warm bookkeeping back after a test mutates it."""+ monkeypatch.setattr(warmup, "_thread", None, raising = False)+ monkeypatch.setattr(+ warmup,+ "_status",+ {"started": False, "finished": False, "stages": {}},+ raising = False,+ )+++def test_a_second_lifespan_warms_again_however_the_first_ended(monkeypatch):+ """Both restart paths must re-warm, not just the one that got a clean reset.++ reset_background_warm() declines while a warm is alive, the normal case for a shutdown+ landing mid-warm. If that warm then finishes its thread object is left behind, and+ treating it as "already started" would skip the second lifespan's warm entirely, over+ hardware state the same shutdown just cleared."""+ _restore(monkeypatch)+ runs: list[int] = []+ monkeypatch.setattr(warmup, "_warm", lambda *_: runs.append(1))++ assert warmup.start_background_warm() is True+ assert warmup.join_background_warm(30) is True++ # Path one: shutdown reset cleanly, the next lifespan warms.+ assert warmup.reset_background_warm() is True+ assert warmup.start_background_warm() is True+ assert warmup.join_background_warm(30) is True+ assert runs == [1, 1], "the second lifespan did not run the warm again"++ # Path two: no reset ran, because the warm outlived the shutdown that tried.+ # The finished thread must not still hold the latch. Retire the epoch first, as+ # run_lifespan_shutdown does: that is what makes the leftover thread stale.+ from utils.hardware import hardware as hw++ hw.invalidate_detection()+ assert warmup.start_background_warm() is True+ assert warmup.join_background_warm(30) is True+ assert runs == [1, 1, 1], (+ "a finished warm kept the latch, so the restart served with the ML stack "+ "cold until some request kicked detection"+ )+++def test_a_live_warm_still_holds_the_latch(monkeypatch):+ """Negative control: clearing the dead thread must not allow two live warms."""+ _restore(monkeypatch)+ release = threading.Event()+ entered = threading.Event()++ def _slow_warm(*_) -> None:+ entered.set()+ release.wait(30)++ monkeypatch.setattr(warmup, "_warm", _slow_warm)+ try:+ assert warmup.start_background_warm() is True+ assert entered.wait(30)+ assert warmup.start_background_warm() is False, "a second warm ran beside a live one"+ assert warmup.reset_background_warm() is False+ finally:+ release.set()+ warmup.join_background_warm(30)+++def test_reset_clears_the_reported_warm_status(monkeypatch):+ _restore(monkeypatch)+ monkeypatch.setattr(warmup, "_warm", lambda *_: warmup._run_stage("hardware", lambda: None))++ warmup.start_background_warm()+ warmup.join_background_warm(30)+ assert warmup.warm_status()["stages"]["hardware"]["ok"] is True++ warmup.reset_background_warm()+ status = warmup.warm_status()+ assert status["started"] is False+ assert status["finished"] is False+ assert status["stages"] == {}, "a stale stage table outlived the warm it described"+ assert status["seconds"] is None+++def test_reset_declines_while_the_warm_is_still_running(monkeypatch):+ """Two warms on the same imports is worse than a cold second lifespan."""+ _restore(monkeypatch)+ release = threading.Event()+ entered = threading.Event()++ def _slow(*_) -> None:+ entered.set()+ release.wait(30)++ monkeypatch.setattr(warmup, "_warm", _slow)+ assert warmup.start_background_warm() is True+ assert entered.wait(30) is True+ running = warmup._thread++ try:+ assert warmup.reset_background_warm() is False+ assert warmup._thread is running, "the reset dropped a live warm thread"+ finally:+ release.set()+ warmup.join_background_warm(30)+++def test_the_lifespan_resets_the_warm_after_shutdown():+ """Guard the wiring, not just the helper: the reset has to be reachable."""+ import ast++ tree = ast.parse((_BACKEND / "main.py").read_text(encoding = "utf-8"))+ for node in ast.walk(tree):+ if isinstance(node, ast.AsyncFunctionDef) and node.name == "lifespan":+ break+ else:+ raise AssertionError("lifespan not found in main.py")++ called = {+ sub.func.id+ for sub in ast.walk(node)+ if isinstance(sub, ast.Call) and isinstance(sub.func, ast.Name)+ }+ assert "reset_background_warm" in called, (+ "the lifespan never releases the one-warm-per-process latch, so a "+ "second lifespan in this process leaves the ML stack cold"+ )diff --git a/studio/backend/tests/test_openai_tool_passthrough.py b/studio/backend/tests/test_openai_tool_passthrough.pyindex eeb6cee871c..e5a489d6fd7 100644--- a/studio/backend/tests/test_openai_tool_passthrough.py+++ b/studio/backend/tests/test_openai_tool_passthrough.py@@ -6547,6 +6547,10 @@ class TestApiMonitorSafetensorsUsage:# Only the generation hop should cancel; resolution runs before the row opens.if getattr(func, "__name__", "") == "resolve_local_gguf":return None+ # Resolving what is already serving is pre-row work too, offloaded for the+ # same reason: _loaded_satisfies reaches the singleton, whose build detects.+ if func in (inf_mod.get_inference_backend, inf_mod._loaded_satisfies):+ return func(*_args, **_kwargs)raise asyncio.CancelledError()monitor = ApiMonitor(max_entries = 3)diff --git a/studio/backend/tests/test_startup_defers_stack_dependent_work.py b/studio/backend/tests/test_startup_defers_stack_dependent_work.pynew file mode 100644index 00000000000..d23d583bcaf--- /dev/null+++ b/studio/backend/tests/test_startup_defers_stack_dependent_work.py@@ -0,0 +1,190 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Stack-dependent startup work must not run before the socket binds.++Two pieces of work import the ML stack: the MLX availability probe (the MLX runtime) and+the RAG embedder warm (sentence-transformers/transformers/torch). Uvicorn binds only once+the lifespan yields, so doing either on the lifespan thread, or on a thread early enough to+race the warm for the GIL and the import locks, puts that import back in front of the login+screen. Both now run on the post-warm thread, which joins the warm first.+"""++from __future__ import annotations++import ast+import sys+from pathlib import Path++_BACKEND = Path(__file__).resolve().parent.parent+if str(_BACKEND) not in sys.path:+ sys.path.insert(0, str(_BACKEND))++_MAIN = _BACKEND / "main.py"+++def _lifespan_body() -> ast.AsyncFunctionDef:+ tree = ast.parse(_MAIN.read_text(encoding = "utf-8"))+ for node in ast.walk(tree):+ if isinstance(node, ast.AsyncFunctionDef) and node.name == "lifespan":+ return node+ raise AssertionError("lifespan not found in main.py")+++def _post_warm_body() -> ast.FunctionDef:+ tree = ast.parse(_MAIN.read_text(encoding = "utf-8"))+ for node in ast.walk(tree):+ if isinstance(node, ast.FunctionDef) and node.name == "_post_warm_background_work":+ return node+ raise AssertionError("_post_warm_background_work not found in main.py")+++def _names_called(node: ast.AST) -> set[str]:+ """Every bare name and attribute tail invoked or referenced under `node`."""+ found: set[str] = set()+ for sub in ast.walk(node):+ if isinstance(sub, ast.Name):+ found.add(sub.id)+ elif isinstance(sub, ast.Attribute):+ found.add(sub.attr)+ return found+++def test_lifespan_does_not_probe_mlx_before_yielding():+ referenced = _names_called(_lifespan_body())+ assert "start_mlx_autorepair_if_needed" not in referenced, (+ "the MLX autorepair probe is back on the lifespan thread; "+ "mlx_stack_available() imports the MLX runtime and the socket binds "+ "only after this coroutine yields"+ )+++def test_lifespan_does_not_start_the_rag_warm_before_yielding():+ referenced = _names_called(_lifespan_body())+ assert "_warm_rag_embedder" not in referenced, (+ "the RAG embedder warm is started from the lifespan again; it imports "+ "sentence-transformers/transformers/torch and races the coordinated warm"+ )+++def test_post_warm_thread_joins_the_warm_before_doing_stack_work():+ body = _post_warm_body()+ statements = [n for n in body.body if not isinstance(n, ast.Expr) or True]++ # The join has to come first, or these imports race the warm instead of+ # building on it.+ join_line = None+ work_lines = []+ for sub in ast.walk(body):+ if isinstance(sub, ast.Name) and sub.id == "join_background_warm":+ join_line = sub.lineno if join_line is None else min(join_line, sub.lineno)+ if isinstance(sub, ast.Name) and sub.id in {+ "start_mlx_autorepair_if_needed",+ "_warm_rag_embedder",+ }:+ work_lines.append(sub.lineno)++ assert join_line is not None, "_post_warm_background_work must join the warm"+ assert work_lines, "_post_warm_background_work must do the deferred work"+ assert join_line < min(work_lines), (+ "join_background_warm() must precede the stack-dependent work, "+ f"got join at {join_line} and work at {sorted(work_lines)}"+ )+ assert statements, "body must not be empty"+++def test_post_warm_work_honours_the_coordinated_warm_kill_switch():+ """The switch must gate the torch-dependent work, and only that.++ It used to be the first statement, which also skipped MLX autorepair. That one is not+ torch, has its own UNSLOTH_DISABLE_MLX_AUTOREPAIR opt-out, and ran unconditionally+ before the deferral, so skipping it left a broken-MLX Mac chat-only for good. Ordering+ against autorepair is pinned in test_warm_window_review_fixes.py."""+ body = _post_warm_body()+ guards = [+ node+ for node in body.body+ if isinstance(node, ast.If) and "DISABLE_ENV_VAR" in ast.unparse(node.test)+ ]+ assert guards, "the kill-switch guard is gone; the RAG warm would import torch anyway"+ guard = guards[0]+ condition = ast.unparse(guard.test)+ assert "os.environ" in condition+ assert any(isinstance(node, ast.Return) for node in guard.body)++ # Everything after the guard is what the switch actually disables.+ after = body.body[body.body.index(guard) + 1 :]+ protected = {+ sub.func.id+ for stmt in after+ for sub in ast.walk(stmt)+ if isinstance(sub, ast.Call) and isinstance(sub.func, ast.Name)+ }+ assert "_warm_rag_embedder" in protected, (+ "the RAG warm is no longer behind the kill switch, so a --no-torch host "+ "still pulls sentence-transformers and torch at startup"+ )+++def test_post_warm_thread_is_started_by_the_lifespan():+ """The lifespan must still put the thread up, now through a helper. The old inline Thread+ was untracked, so a shutdown landing while it was parked in the warm join could not stop+ it and a second lifespan stacked another. Follow the indirection, not the inline form."""+ referenced = _names_called(_lifespan_body())+ assert "_start_post_warm_thread" in referenced or (+ "_post_warm_background_work" in referenced+ ), (+ "nothing starts the post-warm thread, so the MLX autorepair and the RAG "+ "warm would never run"+ )++ # ...and the helper must target the real work, or a do-nothing thread passes.+ tree = ast.parse(_MAIN.read_text(encoding = "utf-8"))+ starter = next(+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.FunctionDef) and node.name == "_start_post_warm_thread"+ )+ assert "_post_warm_background_work" in _names_called(starter)+++def test_post_warm_actually_runs_both_pieces_of_work(monkeypatch):+ """Deferring must not become dropping. The lexical tests above would still pass if the+ deferred work never ran at all, silently ending MLX self-healing and leaving the RAG+ embedder cold."""+ import main as main_mod+ import utils.mlx_repair as mlx_mod++ order: list[str] = []+ monkeypatch.setattr(main_mod, "join_background_warm", lambda *a, **k: order.append("join"))+ monkeypatch.setattr(+ mlx_mod, "start_mlx_autorepair_if_needed", lambda: order.append("mlx") or False+ )+ monkeypatch.setattr(main_mod, "_warm_rag_embedder", lambda: order.append("rag"))++ main_mod._post_warm_background_work()++ assert order == [+ "join",+ "mlx",+ "rag",+ ], f"post-warm work did not run in the intended order, got {order}"+++def test_a_failing_mlx_probe_does_not_strand_the_rag_warm(monkeypatch):+ """One deferred stage failing must not take the other down with it."""+ import main as main_mod+ import utils.mlx_repair as mlx_mod++ ran: list[str] = []+ monkeypatch.setattr(main_mod, "join_background_warm", lambda *a, **k: None)++ def _boom():+ raise RuntimeError("mlx probe exploded")++ monkeypatch.setattr(mlx_mod, "start_mlx_autorepair_if_needed", _boom)+ monkeypatch.setattr(main_mod, "_warm_rag_embedder", lambda: ran.append("rag"))++ main_mod._post_warm_background_work()++ assert ran == ["rag"], "a failing MLX probe must not skip the RAG warm"diff --git a/studio/backend/tests/test_startup_defers_torch.py b/studio/backend/tests/test_startup_defers_torch.pynew file mode 100644index 00000000000..eeb7ade0c6b--- /dev/null+++ b/studio/backend/tests/test_startup_defers_torch.py@@ -0,0 +1,602 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Invariant: ``import main`` must not import torch, and the warm that replaces+it must be safe.++uvicorn binds the socket only after ``import main`` and the lifespan both finish, so+anything they import is time the login screen does not exist. torch and what it drags+in was about 5s of that on a GPU host. Four eager edges caused it:++ utils/models/model_config.py _build_detection_sets() at module scope+ routes/models.py from core.inference import get_inference_backend+ core/inference/orchestrator.py from utils.hf_xet_fallback import DownloadStallError+ utils/datasets/raw_text.py from datasets import Dataset (annotation only)++All four are lazy now and detection moved onto utils/torch_warmup.py. A fresh interpreter+is used for the import invariant, since importing in-process would measure an already-warm+sys.modules. CPU-only, no network, no GPU, no weights.+"""++from __future__ import annotations++import ast+import importlib.util+import subprocess+import sys+import threading+from pathlib import Path++import pytest++_BACKEND_DIR = Path(__file__).resolve().parent.parent # studio/backend++_HEAVY = ("torch", "transformers", "unsloth_zoo", "scipy", "sklearn", "sympy")++_IMPORT_MAIN_SNIPPET = r"""+import sys++# Never start the warm here: it would import the very modules under test, and+# the assertion below would race it.+import os+os.environ["UNSLOTH_STUDIO_DISABLE_TORCH_WARM"] = "1"++import main # noqa: F401++HEAVY = %(heavy)r+leaked = sorted(+ m for m in sys.modules+ if any(m == h or m.startswith(h + ".") for h in HEAVY)+)+assert not leaked, "import main pulled heavy ML modules: %%s" %% (leaked,)+print("IMPORT_MAIN_CLEAN")+""" % {"heavy": list(_HEAVY)}+++def _run(snippet: str) -> subprocess.CompletedProcess:+ return subprocess.run(+ [sys.executable, "-c", snippet],+ cwd = str(_BACKEND_DIR),+ capture_output = True,+ text = True,+ timeout = 900,+ )+++def test_import_main_does_not_import_torch():+ """`import main` must leave torch and its scientific stack unimported."""+ proc = _run(_IMPORT_MAIN_SNIPPET)+ assert (+ proc.returncode == 0+ ), f"import main was not clean\nstdout:\n{proc.stdout}\nstderr:\n{proc.stderr[-4000:]}"+ assert "IMPORT_MAIN_CLEAN" in proc.stdout+++ "module_path",+ [+ "utils.models.model_config",+ "utils.datasets.raw_text",+ "core.inference.orchestrator",+ "routes.models",+ ],+)+def test_module_import_does_not_pull_torch(module_path: str):+ """Each module that used to force torch must import clean on its own."""+ snippet = (+ "import sys, importlib\n"+ f"importlib.import_module({module_path!r})\n"+ f"HEAVY = {list(_HEAVY)!r}\n"+ "leaked = sorted(m for m in sys.modules"+ " if any(m == h or m.startswith(h + '.') for h in HEAVY))\n"+ "assert not leaked, leaked\n"+ "print('CLEAN')\n"+ )+ proc = _run(snippet)+ assert proc.returncode == 0, f"{module_path}: {proc.stderr[-3000:]}"+ assert "CLEAN" in proc.stdout+++def test_detection_sets_still_resolve_under_their_old_names():+ """The PEP 562 shim must keep `from ... import _VLM_MODEL_TYPES` working."""+ if importlib.util.find_spec("transformers") is None:+ pytest.skip("transformers not installed")+ from utils.models.model_config import (+ _AUDIO_ONLY_MODEL_TYPES,+ _VISION_CHECK_INLINE_HELPERS,+ _VISION_CHECK_SCRIPT,+ _VLM_CLASS_NAMES,+ _VLM_MODEL_TYPES,+ )++ assert "llava" in _VLM_MODEL_TYPES+ assert {"csm", "whisper"} <= _AUDIO_ONLY_MODEL_TYPES+ assert _VLM_CLASS_NAMES+ assert "_VLM_MODEL_TYPES = " in _VISION_CHECK_INLINE_HELPERS+ assert _VISION_CHECK_INLINE_HELPERS in _VISION_CHECK_SCRIPT+++def test_detection_sets_are_built_once_under_concurrency():+ """Two requests racing the warm must not each read the registry."""+ from utils.models import model_config as mc++ calls = []+ original = mc._build_detection_sets+ saved = mc._DETECTION_SETS+ mc._DETECTION_SETS = None+ try:++ def counted():+ calls.append(1)+ return (frozenset({"x"}), frozenset(), frozenset())++ mc._build_detection_sets = counted+ results = []+ barrier = threading.Barrier(8)++ def worker():+ barrier.wait()+ results.append(mc._detection_sets())++ threads = [threading.Thread(target = worker) for _ in range(8)]+ for t in threads:+ t.start()+ for t in threads:+ t.join(30)+ assert len(calls) == 1, f"built {len(calls)} times"+ assert all(r is results[0] for r in results)+ finally:+ mc._build_detection_sets = original+ mc._DETECTION_SETS = saved+++def test_hardware_is_detected_once_under_concurrency():+ """ensure_hardware_detected() collapses the warm thread and any request arriving+ mid-detection into a single run."""+ from utils.hardware import hardware as hw++ calls = []+ saved_device, saved_impl = hw.DEVICE, hw._detect_hardware_locked+ hw.DEVICE = None+ try:++ def counted():+ calls.append(1)+ hw.DEVICE = hw.DeviceType.CPU+ return hw.DEVICE++ hw._detect_hardware_locked = counted+ barrier = threading.Barrier(8)++ def worker():+ barrier.wait()+ hw.ensure_hardware_detected()++ threads = [threading.Thread(target = worker) for _ in range(8)]+ for t in threads:+ t.start()+ for t in threads:+ t.join(30)+ assert len(calls) == 1, f"detected {len(calls)} times"+ finally:+ hw._detect_hardware_locked = saved_impl+ hw.DEVICE = saved_device+++def test_warm_starts_once_and_honours_the_kill_switch(monkeypatch):+ from utils import torch_warmup++ monkeypatch.setattr(torch_warmup, "_thread", None, raising = False)+ monkeypatch.setenv(torch_warmup.DISABLE_ENV_VAR, "1")+ assert torch_warmup.start_background_warm() is False+ assert torch_warmup.warm_status()["started"] is False++ monkeypatch.delenv(torch_warmup.DISABLE_ENV_VAR)+ monkeypatch.setattr(torch_warmup, "_STAGES", (("noop", lambda: None),))+ assert torch_warmup.start_background_warm() is True+ # Second call is a no-op: one warm thread per process.+ assert torch_warmup.start_background_warm() is False+ assert torch_warmup.join_background_warm(60) is True+ status = torch_warmup.warm_status()+ assert status["finished"] is True+ assert status["stages"]["noop"]["ok"] is True+++def test_the_warm_covers_every_package_import_main_used_to_pull():+ """Deferring an import only moves its cost if something still pays it. One stage per+ package `import main` used to leave in sys.modules; dropping one fails no other test,+ it silently moves that import onto the first request."""+ from utils import torch_warmup+ assert [name for name, _ in torch_warmup._STAGES] == [+ "hardware", # torch, via utils.hardware+ # Not a package import: builds the orchestrator singleton, whose constructor+ # waits on the detection a first request would otherwise pay for. Right after+ # hardware so it reuses this thread's.+ "inference_backend",+ "transformers", # via model_config's registry read+ "datasets", # via utils/datasets/raw_text.py+ "unsloth_zoo", # via orchestrator's utils.hf_xet_fallback import+ ]+++def test_the_unsloth_zoo_stage_goes_through_the_shim(monkeypatch):+ """The warm must reproduce the eager import, not just import the package. The edge it+ replaces was orchestrator.py's ``from utils.hf_xet_fallback import DownloadStallError``,+ and the shim retries under UNSLOTH_ZOO_DISABLE_GPU_INIT=1 when unsloth_zoo's GPU init+ raises. A bare ``import unsloth_zoo`` skips that retry and fails where startup+ succeeded."""+ import builtins+ import importlib++ from utils import torch_warmup++ # Through sys.modules: another test re-imports the shim and leaves the package+ # attribute pointing elsewhere. import_module resolves it the way the code does.+ hf_xet_fallback = importlib.import_module("utils.hf_xet_fallback")++ monkeypatch.setattr(torch_warmup, "_torch_installed", lambda: True)+ calls = []+ monkeypatch.setattr(hf_xet_fallback, "_load_shared", lambda: (calls.append(1), True)[1])++ real_import = builtins.__import__++ def no_bare_zoo(name, *args, **kwargs):+ assert name != "unsloth_zoo", (+ "the warm imported unsloth_zoo directly; it must go through "+ "utils.hf_xet_fallback so the UNSLOTH_ZOO_DISABLE_GPU_INIT retry runs"+ )+ return real_import(name, *args, **kwargs)++ monkeypatch.setattr(builtins, "__import__", no_bare_zoo)+ torch_warmup._warm_unsloth_zoo()+ assert calls == [1]++ # A shim that could not load leaves the watchdog degraded; that has to surface as a+ # failed stage rather than a silent success.+ monkeypatch.setattr(hf_xet_fallback, "_load_shared", lambda: False)+ with pytest.raises(RuntimeError, match = "unsloth_zoo unavailable"):+ torch_warmup._warm_unsloth_zoo()+++def test_a_failing_warm_stage_is_reported_not_swallowed(monkeypatch, capsys, caplog):+ """A broken stage must be visible in the log and must not kill the warm."""+ from utils import torch_warmup++ def boom():+ raise RuntimeError("stage exploded")++ monkeypatch.setattr(torch_warmup, "_thread", None, raising = False)+ monkeypatch.delenv(torch_warmup.DISABLE_ENV_VAR, raising = False)+ monkeypatch.setattr(torch_warmup, "_STAGES", (("boom", boom), ("after", lambda: None)))+ assert torch_warmup.start_background_warm() is True+ assert torch_warmup.join_background_warm(60) is True++ status = torch_warmup.warm_status()+ assert status["stages"]["boom"]["ok"] is False+ assert "stage exploded" in status["stages"]["boom"]["error"]+ # The stage after the failure still ran, and the process is still alive.+ assert status["stages"]["after"]["ok"] is True+ assert status["finished"] is True+ # The operator has to be able to grep it. Which sink structlog is bound to depends+ # on what configured logging earlier, so accept stdout or the stdlib records.+ logged = capsys.readouterr().out + "\n".join(r.getMessage() for r in caplog.records)+ assert "stage exploded" in logged+++# ---------------------------------------------------------------------------+# The warm window: routes must not block uvicorn's loop while torch loads+# ---------------------------------------------------------------------------+#+# get_device() used to be free by the time any request arrived. For the length of the+# warm it now blocks on _DETECT_LOCK and the torch import, stalling every other request+# on the loop (1547ms measured on a /api/liveness that touches nothing).+#+# First-paint and polled routes, certain to land inside the warm window. Each must+# reach its blocking helper only through asyncio.to_thread.++_OFFLOAD_REQUIRED = [+ ("main.py", "get_gpu_visibility", "get_backend_visible_gpu_info"),+ ("routes/training.py", "get_hardware_utilization", "get_gpu_utilization"),+ # Not first-paint, but lands in the warm window when a start is submitted early,+ # and its MLX streaming guard forces detection itself.+ ("routes/training.py", "start_training", "ensure_hardware_detected"),+ ("routes/export.py", "_ensure_export_supported", "export_capability"),+ ("routes/models.py", "list_models", "get_inference_backend"),+ # get_status is deliberately absent. It used to offload get_inference_backend; it+ # now peeks, which constructs nothing and so needs no offload at all. The stronger+ # invariant lives in test_async_singleton_access.py::+ # test_read_only_endpoints_never_construct_the_singleton, which fails if it goes+ # back to building. Listing it here would require the offload it no longer needs.+ ("routes/inference.py", "get_api_monitor", "_monitor_active_model"),+ ("routes/inference.py", "get_api_monitor", "_monitor_context_length"),+ # Also not first-paint, but a load or validate carrying gpu_ids lands in the warm+ # window and this probes the device before any teardown.+ ("routes/inference.py", "_resolve_gguf_gpu_ids_for_request", "get_device"),+]+++def _find_function(tree: ast.AST, name: str) -> ast.AST:+ for node in ast.walk(tree):+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == name:+ return node+ raise AssertionError(f"no function {name!r} in the parsed module")+++def _is_to_thread(node: ast.AST) -> bool:+ return (+ isinstance(node, ast.Call)+ and isinstance(node.func, ast.Attribute)+ and node.func.attr == "to_thread"+ )+++def _offloaded_nodes(func: ast.AST) -> set[int]:+ """Every node lexically inside an asyncio.to_thread(...) argument."""+ offloaded: set[int] = set()+ for node in ast.walk(func):+ if not _is_to_thread(node):+ continue+ for arg in list(node.args) + [kw.value for kw in node.keywords]:+ for sub in ast.walk(arg):+ offloaded.add(id(sub))+ return offloaded++[email protected]("rel_path, func_name, callee", _OFFLOAD_REQUIRED)+def test_first_paint_routes_do_not_block_the_event_loop(rel_path, func_name, callee):+ source = (_BACKEND_DIR / rel_path).read_text(encoding = "utf-8")+ func = _find_function(ast.parse(source), func_name)+ assert isinstance(func, ast.AsyncFunctionDef), (+ f"{rel_path}:{func_name} is no longer `async def`; this guard assumes it runs on "+ "the loop (a plain `def` handler is already safe -- drop it from the list)"+ )+ offloaded = _offloaded_nodes(func)++ # The bare-name form: asyncio.to_thread(callee).+ handed_off = any(+ isinstance(n, ast.Name) and n.id == callee and id(n) in offloaded for n in ast.walk(func)+ )+ direct = [+ n+ for n in ast.walk(func)+ if isinstance(n, ast.Call)+ and isinstance(n.func, ast.Name)+ and n.func.id == callee+ and id(n) not in offloaded+ ]+ assert not direct, (+ f"{rel_path}:{func_name} calls {callee}() directly on the event loop at line(s) "+ f"{[n.lineno for n in direct]}; it blocks on hardware detection until the "+ "startup warm has imported torch. Wrap it in await asyncio.to_thread(...)."+ )+ called_inside = any(+ isinstance(n, ast.Call)+ and isinstance(n.func, ast.Name)+ and n.func.id == callee+ and id(n) in offloaded+ for n in ast.walk(func)+ )+ assert (+ handed_off or called_inside+ ), f"{rel_path}:{func_name} no longer references {callee}; update this guard"+++def test_a_failed_detection_degrades_instead_of_raising():+ """A torch that raises must not leave DEVICE unset. The warm swallows stage failures, so a+ raising detection would leave DEVICE None, and then every get_device() retries the same+ broken import while /api/health, which waits on this, answers 500."""+ from utils.hardware import hardware as hw++ saved_device, saved_impl = hw.DEVICE, hw._detect_hardware_locked+ saved_chat, saved_reason = hw.CHAT_ONLY, hw.CHAT_ONLY_REASON+ hw.DEVICE = None+ calls = []+ try:++ def boom():+ calls.append(1)+ raise OSError("libcudart.so.12: cannot open shared object file")++ hw._detect_hardware_locked = boom+ assert hw.ensure_hardware_detected() == hw.DeviceType.CPU+ assert hw.CHAT_ONLY is True+ assert hw.CHAT_ONLY_REASON == "detection_failed"+ # Cached: the second call must not re-enter the failing import.+ assert hw.ensure_hardware_detected() == hw.DeviceType.CPU+ assert len(calls) == 1, f"retried the broken import {len(calls)} times"+ finally:+ hw._detect_hardware_locked = saved_impl+ hw.DEVICE, hw.CHAT_ONLY, hw.CHAT_ONLY_REASON = saved_device, saved_chat, saved_reason+++def test_a_broken_torch_counts_as_no_torch(monkeypatch):+ """_has_torch() must not let a non-ImportError escape into detection."""+ import builtins++ from utils.hardware import hardware as hw++ real_import = builtins.__import__++ def fake_import(name, *args, **kwargs):+ if name == "torch":+ raise OSError("undefined symbol: cudaGetDeviceCount")+ return real_import(name, *args, **kwargs)++ monkeypatch.setattr(builtins, "__import__", fake_import)+ assert hw._has_torch() is False+++def test_purge_partial_import_clears_the_zombie_and_leaves_live_ones():+ """A half-imported package must not survive into the retry."""+ import sys++ from utils.torch_warmup import purge_partial_import++ sys.modules["zzz_fake_pkg.sub"] = object()+ sys.modules["zzz_fake_pkg.sub.deep"] = object()+ try:+ # Parent absent + submodules present: the zombie signature.+ assert sorted(purge_partial_import("zzz_fake_pkg")) == [+ "zzz_fake_pkg.sub",+ "zzz_fake_pkg.sub.deep",+ ]+ assert not [m for m in sys.modules if m.startswith("zzz_fake_pkg")]++ # Parent present: a healthy (or still-importing) package is left alone.+ sys.modules["zzz_fake_pkg"] = object()+ sys.modules["zzz_fake_pkg.sub"] = object()+ assert purge_partial_import("zzz_fake_pkg") == []+ assert "zzz_fake_pkg.sub" in sys.modules+ finally:+ for name in [m for m in list(sys.modules) if m.startswith("zzz_fake_pkg")]:+ sys.modules.pop(name, None)+++def test_purge_declines_when_a_compiled_submodule_is_loaded():+ """Evicting a loaded C extension is worse than the zombie it would fix. Re-importing one+ re-runs its module init, and pybind11 calls std::terminate on a second registration of+ the same type."""+ import sys+ from importlib.machinery import EXTENSION_SUFFIXES+ from types import ModuleType++ from utils.torch_warmup import purge_partial_import++ compiled = ModuleType("zzz_ext_pkg.binding")+ compiled.__file__ = "/nowhere/zzz_ext_pkg/binding" + EXTENSION_SUFFIXES[0]+ sys.modules["zzz_ext_pkg.binding"] = compiled+ sys.modules["zzz_ext_pkg.pure"] = ModuleType("zzz_ext_pkg.pure")+ try:+ assert purge_partial_import("zzz_ext_pkg") == []+ # Both survive: a half-purged package is not a state worth creating.+ assert "zzz_ext_pkg.binding" in sys.modules+ assert "zzz_ext_pkg.pure" in sys.modules+ finally:+ for name in [m for m in list(sys.modules) if m.startswith("zzz_ext_pkg")]:+ sys.modules.pop(name, None)+++def test_a_broken_torch_purges_its_own_zombie(monkeypatch):+ """_has_torch() must clean up after the import it just watched fail. Restores the real+ torch entries exactly: leaving `torch` in sys.modules with its submodules evicted aborts+ the pytest process the next time anything imports one."""+ import builtins+ import sys+ from types import ModuleType++ from utils.hardware import hardware as hw++ real_import = builtins.__import__+ saved = {name: mod for name, mod in sys.modules.items() if name.split(".")[0] == "torch"}++ def fake_import(name, *args, **kwargs):+ if name == "torch":+ # Zombie signature: `torch/__init__` raised after executing a pure-Python+ # submodule, leaving it behind with the parent evicted.+ sys.modules["torch._early"] = ModuleType("torch._early")+ sys.modules.pop("torch", None)+ raise OSError("undefined symbol: cudaGetDeviceCount")+ return real_import(name, *args, **kwargs)++ monkeypatch.setattr(builtins, "__import__", fake_import)+ for name in saved:+ sys.modules.pop(name, None)+ try:+ assert hw._has_torch() is False+ assert "torch._early" not in sys.modules+ finally:+ for name in [m for m in list(sys.modules) if m.split(".")[0] == "torch"]:+ sys.modules.pop(name, None)+ sys.modules.update(saved)+++def test_one_detection_pass_probes_torch_once(monkeypatch):+ """A detection pass must import torch at most once.++ _has_torch() is the expensive part: a broken wheel takes seconds to fail, and the purge+ then declines because a compiled submodule is loaded, so the partial tree stays and a+ second probe re-runs torch/__init__ against those cache hits -- same cost again, with no+ guarantee it fails the same way. The CUDA branch and the XPU fallback share one probe."""+ import builtins+ from types import ModuleType++ from utils.hardware import hardware as hw++ saved = {n: m for n, m in sys.modules.items() if n.split(".")[0] == "torch"}+ saved_device = hw.DEVICE+ saved_chat, saved_reason = hw.CHAT_ONLY, hw.CHAT_ONLY_REASON+ real_import = builtins.__import__+ attempts = []++ def fake_import(name, *args, **kwargs):+ if name == "torch":+ attempts.append(name)+ # A loaded compiled submodule makes the purge decline, so a retry re-runs+ # torch/__init__ in full.+ ext = ModuleType("torch._C")+ ext.__file__ = "/nonexistent/torch/_C.cpython-313-x86_64-linux-gnu.so"+ sys.modules["torch._C"] = ext+ sys.modules.pop("torch", None)+ raise OSError("libcudart.so.12: cannot open shared object file")+ return real_import(name, *args, **kwargs)++ for name in saved:+ sys.modules.pop(name, None)+ monkeypatch.setattr(builtins, "__import__", fake_import)+ try:+ hw.DEVICE = None+ assert hw._detect_hardware_locked() == hw.DeviceType.CPU+ assert len(attempts) == 1, (+ f"detection imported torch {len(attempts)} times in one pass; the "+ "CUDA branch and the XPU fallback must share a single probe"+ )+ finally:+ monkeypatch.undo()+ for name in [m for m in list(sys.modules) if m.split(".")[0] == "torch"]:+ sys.modules.pop(name, None)+ sys.modules.update(saved)+ hw.DEVICE, hw.CHAT_ONLY, hw.CHAT_ONLY_REASON = saved_device, saved_chat, saved_reason+++def test_every_importing_warm_stage_purges_on_failure():+ """A failed stage must not leave a half-imported package behind. An import that dies+ partway leaves its submodules cached under an evicted parent, so the retry returns a+ package that imports but is missing attributes: broken until restart, while+ warm_status() reports nothing worse than a cold stage."""+ from utils import torch_warmup++ importing = {name for name, _ in torch_warmup._STAGES} - {"inference_backend"}+ assert importing <= set(torch_warmup._STAGE_PACKAGE), (+ "a warm stage imports a package with no purge mapping: "+ f"{sorted(importing - set(torch_warmup._STAGE_PACKAGE))}"+ )+++def test_a_failed_stage_actually_purges(monkeypatch):+ purged = []+ from utils import torch_warmup++ monkeypatch.setattr(torch_warmup, "purge_partial_import", lambda pkg: purged.append(pkg))++ def _boom():+ raise RuntimeError("datasets exploded partway")++ torch_warmup._run_stage("datasets", _boom)++ assert purged == ["datasets"], f"expected the datasets purge, got {purged}"+ assert torch_warmup._status["stages"]["datasets"]["ok"] is False+++def test_a_stage_that_imports_nothing_is_not_purged(monkeypatch):+ """inference_backend builds an object; there is no package to clean up."""+ purged = []+ from utils import torch_warmup++ monkeypatch.setattr(torch_warmup, "purge_partial_import", lambda pkg: purged.append(pkg))++ def _boom():+ raise RuntimeError("constructor exploded")++ torch_warmup._run_stage("inference_backend", _boom)++ assert purged == [], f"nothing to purge for a non-importing stage, got {purged}"diff --git a/studio/backend/tests/test_training_streaming_mlx_warm.py b/studio/backend/tests/test_training_streaming_mlx_warm.pynew file mode 100644index 00000000000..3a76ba69098--- /dev/null+++ b/studio/backend/tests/test_training_streaming_mlx_warm.py@@ -0,0 +1,173 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Invariant: /training/start's MLX streaming rejection must survive the warm window.++``hardware.DEVICE`` used to be set before uvicorn bound the socket. The warm thread+fills it in now, so for the first moment of serving it still holds ``None``.++``start_training`` rejects ``dataset_streaming`` on Apple Silicon by comparing ``DEVICE ==+DeviceType.MLX``. Against the default that is False, the rejection is skipped, and the+request runs on to ``_build_training_worker_config``, which detects MLX only after+validation and hands a streaming dataset to a loader that materializes the whole thing. The+guard must force detection first, and off the event loop, since detection imports torch.++The lexical half is in ``test_startup_defers_torch.py``; this file covers the behaviour.+CPU-only, no network, no GPU, no weights.+"""++from __future__ import annotations++import platform+from unittest.mock import MagicMock++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++import routes.training as training_routes+from auth.authentication import authenticated_via_api_key, get_current_subject+from utils.hardware import hardware as hw++# Clears every streaming precondition but the MLX guard, so only that can reject it.+# load_in_4bit is off so the latest-sidecar probe stays offline.+_STREAMING_START = {+ "model_name": "unsloth/Llama-3.2-1B-Instruct",+ "training_type": "LoRA/QLoRA",+ "format_type": "Alpaca",+ "hf_dataset": "yahma/alpaca-cleaned",+ "dataset_streaming": True,+ "max_steps": 60,+ "load_in_4bit": False,+ "eval_steps": 0,+}++_NON_STREAMING_START = {+ **_STREAMING_START,+ "dataset_streaming": False,+ "max_steps": None,+}++_MLX_REJECTION = "dataset_streaming is not yet supported on Apple Silicon (MLX)"+++def hardware_globals():+ """Restore the detection globals -- the route mutates them for real here."""+ saved = (hw.DEVICE, hw.CHAT_ONLY, hw.CHAT_ONLY_REASON, hw.IS_ROCM)+ try:+ yield hw+ finally:+ hw.DEVICE, hw.CHAT_ONLY, hw.CHAT_ONLY_REASON, hw.IS_ROCM = saved+++def spawn_calls(monkeypatch):+ """Stub the backend so a start past validation is observable without a worker."""+ backend = MagicMock()+ backend.is_training_active.return_value = False+ backend.current_job_id = ""+ backend.start_training.return_value = True+ monkeypatch.setattr(training_routes, "get_training_backend", lambda: backend)+ return backend+++def client(spawn_calls):+ app = FastAPI()+ app.include_router(training_routes.router, prefix = "/training")+ app.dependency_overrides[get_current_subject] = lambda: "tester"+ app.dependency_overrides[authenticated_via_api_key] = lambda: False+ return TestClient(app, raise_server_exceptions = False)+++def _pretend_apple_silicon(monkeypatch):+ """Make detection resolve to MLX: arm64 Darwin, no torch, usable MLX stack."""+ monkeypatch.setattr(platform, "system", lambda: "Darwin")+ monkeypatch.setattr(platform, "machine", lambda: "arm64")+ monkeypatch.setattr(hw, "_has_torch", lambda: False)+ monkeypatch.setattr(hw, "_has_usable_mlx_stack", lambda: True)+++def _pretend_cpu_linux(monkeypatch):+ """Make detection resolve to CPU: no torch, not a Mac."""+ monkeypatch.setattr(platform, "system", lambda: "Linux")+ monkeypatch.setattr(platform, "machine", lambda: "x86_64")+ monkeypatch.setattr(hw, "_has_torch", lambda: False)+ monkeypatch.setattr(hw, "_has_usable_mlx_stack", lambda: False)+++def test_streaming_is_rejected_on_mlx_before_detection_has_run(+ monkeypatch, hardware_globals, spawn_calls, client+):+ """The regression: DEVICE is still None when the request lands."""+ _pretend_apple_silicon(monkeypatch)+ hardware_globals.DEVICE = None # warm thread has not finished++ response = client.post("/training/start", json = _STREAMING_START)++ assert response.status_code == 400, (+ "streaming start on an Apple Silicon host was not rejected while DEVICE "+ f"was still unset (got {response.status_code}: {response.text}); the guard "+ "read the pre-detection default instead of detecting"+ )+ assert _MLX_REJECTION in response.json()["detail"]+ spawn_calls.start_training.assert_not_called()+++def test_the_guard_detects_rather_than_reading_the_default(+ monkeypatch, hardware_globals, spawn_calls, client+):+ """The guard forces detection, not some later step: DEVICE goes None -> MLX across+ a request that never reaches the worker config builder."""+ _pretend_apple_silicon(monkeypatch)+ hardware_globals.DEVICE = None++ client.post("/training/start", json = _STREAMING_START)++ assert hardware_globals.DEVICE == hw.DeviceType.MLX+ spawn_calls.start_training.assert_not_called()+++def test_streaming_still_starts_on_a_non_mlx_host_during_the_warm_window(+ monkeypatch, hardware_globals, spawn_calls, client+):+ """Forcing detection must not turn the guard into a blanket rejection."""+ _pretend_cpu_linux(monkeypatch)+ hardware_globals.DEVICE = None++ response = client.post("/training/start", json = _STREAMING_START)++ assert response.status_code == 200, response.text+ assert response.json()["status"] == "queued"+ assert hardware_globals.DEVICE == hw.DeviceType.CPU+ spawn_calls.start_training.assert_called_once()+++def test_rejection_still_fires_once_detection_has_already_run(+ monkeypatch, hardware_globals, spawn_calls, client+):+ """The pre-existing behaviour, unchanged: DEVICE already MLX."""+ _pretend_apple_silicon(monkeypatch)+ hardware_globals.DEVICE = hw.DeviceType.MLX++ response = client.post("/training/start", json = _STREAMING_START)++ assert response.status_code == 400+ assert _MLX_REJECTION in response.json()["detail"]+ spawn_calls.start_training.assert_not_called()+++def test_non_streaming_start_detects_before_entering_the_sync_backend(+ monkeypatch, hardware_globals, spawn_calls, client+):+ """An ordinary start reaches a synchronous worker-config build that reads the+ device, so it must also detect through the route's off-loop handoff."""+ _pretend_cpu_linux(monkeypatch)+ hardware_globals.DEVICE = None++ response = client.post("/training/start", json = _NON_STREAMING_START)++ assert response.status_code == 200, response.text+ assert hardware_globals.DEVICE == hw.DeviceType.CPU+ spawn_calls.start_training.assert_called_once()diff --git a/studio/backend/tests/test_warm_window_review_fixes.py b/studio/backend/tests/test_warm_window_review_fixes.pynew file mode 100644index 00000000000..8d83b0678d9--- /dev/null+++ b/studio/backend/tests/test_warm_window_review_fixes.py@@ -0,0 +1,2732 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The warm window's remaining sharp edges, one test per edge.++Deferring the ML stack opens an interval between the socket binding and the stack being+importable. Separate things went wrong in it: the generation counter advanced on the+cached path, so ordinary get_device() traffic looked like a re-detection; a failed forced+re-detect left half a verdict published; building the orchestrator on the warm thread made+its ranking fetch an unprompted boot-time request; two sync helpers reached the inference+singleton from the loop thread; the kill switch also disabled MLX self-heal; purging a+half-imported package raced a request retrying the same import; the post-warm worker+outlived its lifespan, then starved the next one; and /api/health published a verdict read+mid-re-detect, treating a torn event-set/DEVICE-None state as settled.+"""++from __future__ import annotations++import ast+import builtins+import os+import sys+import types+import threading+from unittest import mock+from pathlib import Path++import pytest++_BACKEND = Path(__file__).resolve().parent.parent+if str(_BACKEND) not in sys.path:+ sys.path.insert(0, str(_BACKEND))++import utils.hardware.hardware as hw # noqa: E402+++class _NeverStarts:+ """Stand-in for threading.Thread that records the call and runs nothing."""++ def start(self) -> None:+ return None+++# ---------------------------------------------------------------- generation+++def test_the_cached_path_does_not_look_like_a_redetect(monkeypatch):+ """get_device() on a warm process must not advance the generation counter:+ _refresh_static_models_if_stale() reads a change as a re-detection, so counting cache+ hits made any GPU or export helper rebuild the curated defaults and log falsely."""+ monkeypatch.setattr(hw, "DEVICE", hw.DeviceType.CPU, raising = False)+ before = hw.DETECTION_GENERATION+ for _ in range(5):+ hw.ensure_hardware_detected()+ assert hw.DETECTION_GENERATION == before, (+ "the cached path advanced DETECTION_GENERATION; every get_device() would "+ "make the next model list rebuild its curated defaults"+ )+++def test_a_real_detection_still_advances_the_generation(monkeypatch):+ """Negative control: the counter must still move when detection runs."""+ monkeypatch.setattr(hw, "DEVICE", None, raising = False)+ calls: list[int] = []++ def _fake_locked():+ calls.append(1)+ hw.DEVICE = hw.DeviceType.CPU+ return hw.DEVICE++ monkeypatch.setattr(hw, "_detect_hardware_locked", _fake_locked)+ before = hw.DETECTION_GENERATION+ hw.ensure_hardware_detected()+ assert calls == [1]+ assert hw.DETECTION_GENERATION == before + 1+++def test_the_completion_event_is_published_on_the_cached_path_too(monkeypatch):+ """The event is not the counter: a late waiter must still find it set."""+ monkeypatch.setattr(hw, "DEVICE", hw.DeviceType.CPU, raising = False)+ hw.DETECTION_COMPLETE.clear()+ try:+ hw.ensure_hardware_detected()+ assert hw.DETECTION_COMPLETE.is_set()+ finally:+ hw.DETECTION_COMPLETE.set()+++# ------------------------------------------------------- failed re-detection+++def test_a_failed_redetect_restores_the_whole_published_verdict(monkeypatch):+ """A raise must not leave a half-written verdict as what health serves.++ The pass resets CHAT_ONLY / CHAT_ONLY_REASON / IS_ROCM on entry and the MLX autorepair+ catches the exception, so without a restore the reason is gone and the sidebar poll+ stops (it continues only while it reads "mlx_unavailable")."""+ monkeypatch.setattr(hw, "DEVICE", hw.DeviceType.CPU, raising = False)+ monkeypatch.setattr(hw, "CHAT_ONLY", True, raising = False)+ monkeypatch.setattr(hw, "CHAT_ONLY_REASON", "mlx_unavailable", raising = False)+ monkeypatch.setattr(hw, "IS_ROCM", True, raising = False)++ def _boom():+ # Exactly what the real body does before it can fail.+ hw.CHAT_ONLY = True+ hw.CHAT_ONLY_REASON = None+ hw.IS_ROCM = False+ hw.DEVICE = hw.DeviceType.MLX+ raise RuntimeError("probe blew up mid-pass")++ monkeypatch.setattr(hw, "_detect_hardware_locked", _boom)+ hw.DETECTION_COMPLETE.set()++ with pytest.raises(RuntimeError):+ hw.detect_hardware()++ assert hw.DEVICE is hw.DeviceType.CPU+ assert hw.CHAT_ONLY is True+ assert hw.CHAT_ONLY_REASON == "mlx_unavailable", (+ "the failed re-detect dropped the chat_only reason; the frontend recovery "+ "poll stops as soon as it reads a reply without it"+ )+ assert hw.IS_ROCM is True+ assert hw.DETECTION_COMPLETE.is_set()+++def test_a_successful_redetect_publishes_the_new_verdict(monkeypatch):+ """Negative control: the restore must not undo a pass that worked."""+ monkeypatch.setattr(hw, "DEVICE", hw.DeviceType.CPU, raising = False)+ monkeypatch.setattr(hw, "CHAT_ONLY", True, raising = False)+ monkeypatch.setattr(hw, "CHAT_ONLY_REASON", "mlx_unavailable", raising = False)++ def _ok():+ hw.CHAT_ONLY = False+ hw.CHAT_ONLY_REASON = None+ hw.DEVICE = hw.DeviceType.MLX+ return hw.DEVICE++ monkeypatch.setattr(hw, "_detect_hardware_locked", _ok)+ before = hw.DETECTION_GENERATION+ assert hw.detect_hardware() is hw.DeviceType.MLX+ assert hw.CHAT_ONLY is False+ assert hw.CHAT_ONLY_REASON is None+ assert hw.DETECTION_GENERATION == before + 1+++# ------------------------------------------------------------- boot silence+++def test_building_the_orchestrator_makes_no_outbound_request():+ """Construction moved onto the warm thread, so it must not fetch anything.++ Starting the ranking fetch from __init__ reached huggingface.co on every boot before+ anyone signed in. Asserted on the source: importing here pulls the whole stack."""+ tree = ast.parse(+ (_BACKEND / "core" / "inference" / "orchestrator.py").read_text(encoding = "utf-8")+ )+ # Scope to the class: the module defines more than one __init__.+ cls = next(+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.ClassDef) and node.name == "InferenceOrchestrator"+ )+ init = next(+ node for node in cls.body if isinstance(node, ast.FunctionDef) and node.name == "__init__"+ )+ offenders = [+ sub+ for sub in ast.walk(init)+ if isinstance(sub, ast.Attribute) and sub.attr == "_fetch_top_models"+ ]+ assert not offenders, (+ "the orchestrator constructor references _fetch_top_models again; building "+ "it on the warm thread then reaches huggingface.co on every boot, before "+ "anyone signs in"+ )+++def test_the_ranking_fetch_is_started_by_the_first_reader():+ """...but it must still be reachable, or the extra choices never load."""+ tree = ast.parse(+ (_BACKEND / "core" / "inference" / "orchestrator.py").read_text(encoding = "utf-8")+ )+ prop = next(+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.FunctionDef) and node.name == "default_models"+ )+ called = {+ sub.func.attr+ for sub in ast.walk(prop)+ if isinstance(sub, ast.Call) and isinstance(sub.func, ast.Attribute)+ }+ assert "_start_top_models_fetch" in called+++ "env",+ [+ {"HF_HUB_OFFLINE": "1"},+ {"HF_HUB_OFFLINE": "true"},+ {"HF_HUB_OFFLINE": "on"},+ {"TRANSFORMERS_OFFLINE": "1"},+ ],+)+def test_the_ranking_fetch_starts_no_thread_when_offline(monkeypatch, env):+ """It is a raw httpx.get, so the offline variables do not reach it by themselves.++ Driven through the real method: every spelling the backend accepts as offline must+ leave the first model list network-silent, not just the one the guard compares."""+ from core.inference import orchestrator as orch++ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)+ monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)+ for key, value in env.items():+ monkeypatch.setenv(key, value)++ started = []+ monkeypatch.setattr(+ orch.threading,+ "Thread",+ lambda *a, **kw: started.append(kw.get("name")) or _NeverStarts(),+ raising = True,+ )++ instance = object.__new__(orch.InferenceOrchestrator)+ instance._top_models_started = False+ orch.InferenceOrchestrator._start_top_models_fetch(instance)++ assert not started, f"{env} still put up the top-models fetch thread"+++def test_the_ranking_fetch_still_runs_when_online(monkeypatch):+ """Negative control: nothing above may have disabled the fetch outright."""+ from core.inference import orchestrator as orch++ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)+ monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)++ started = []+ monkeypatch.setattr(+ orch.threading,+ "Thread",+ lambda *a, **kw: started.append(kw.get("name")) or _NeverStarts(),+ raising = True,+ )++ instance = object.__new__(orch.InferenceOrchestrator)+ instance._top_models_started = False+ orch.InferenceOrchestrator._start_top_models_fetch(instance)++ assert started == ["top-models"], "an online host no longer fetches the ranking"+++# ------------------------------------------------- offloads at the call site+++def _async_offloaded_names(path: Path, function: str) -> set[str]:+ """Names this async function hands to asyncio.to_thread."""+ tree = ast.parse(path.read_text(encoding = "utf-8"))+ fn = next(+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.AsyncFunctionDef) and node.name == function+ )+ out: set[str] = set()+ for sub in ast.walk(fn):+ if not isinstance(sub, ast.Call):+ continue+ target = sub.func+ name = target.attr if isinstance(target, ast.Attribute) else getattr(target, "id", None)+ if name != "to_thread" or not sub.args:+ continue+ first = sub.args[0]+ out.add(getattr(first, "id", None) or getattr(first, "attr", ""))+ return out++[email protected]("function", ["_openai_catalog_objects", "openai_retrieve_model"])+def test_the_openai_model_listing_reaches_the_singleton_off_loop(function):+ """_openai_model_objects() is sync and calls get_inference_backend(). Left inline, an+ early GET /v1/models held the loop for the rest of the torch import, and the offload+ further down could not help: the call had already happened."""+ path = _BACKEND / "routes" / "inference.py"+ tree = ast.parse(path.read_text(encoding = "utf-8"))+ names = {node.name for node in ast.walk(tree) if isinstance(node, ast.AsyncFunctionDef)}+ if function not in names:+ pytest.skip(f"{function} is not an async handler in this tree")+ assert "_openai_model_objects" in _async_offloaded_names(path, function)+++def test_the_model_config_capability_block_runs_off_loop():+ """is_vision_model() reaches _detection_sets(), so it cannot run inline. Pins the+ property, not a helper name: the handler body must not call the probes, and whatever+ the worker runs must."""+ path = _BACKEND / "routes" / "models.py"+ tree = ast.parse(path.read_text(encoding = "utf-8"))+ fn = next(+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.AsyncFunctionDef) and node.name == "get_model_config"+ )+ nested = {+ sub+ for helper in ast.walk(fn)+ if isinstance(helper, ast.FunctionDef)+ for sub in ast.walk(helper)+ }+ inline = [+ sub+ for sub in ast.walk(fn)+ if isinstance(sub, ast.Call)+ and getattr(sub.func, "id", None) in {"is_vision_model", "is_embedding_model"}+ and sub not in nested+ ]+ assert not inline, (+ "the capability detection block is inline again; is_vision_model() can "+ "import transformers on the event-loop thread"+ )+ offloaded = [+ sub+ for sub in ast.walk(fn)+ if isinstance(sub, ast.Call)+ and isinstance(sub.func, ast.Attribute)+ and sub.func.attr == "to_thread"+ ]+ assert offloaded, "nothing in the config handler goes to a worker thread any more"+ reached = {+ call.func.id+ for helper in ast.walk(fn)+ if isinstance(helper, ast.FunctionDef)+ for call in ast.walk(helper)+ if isinstance(call, ast.Call) and isinstance(call.func, ast.Name)+ }+ assert "is_vision_model" in reached, (+ "no offloaded helper reaches is_vision_model; the probe moved somewhere "+ "this test no longer covers"+ )+++# ------------------------------------------------------------- kill switch+++def test_the_torch_kill_switch_leaves_mlx_selfheal_running():+ """The switch is about torch; MLX autorepair has its own opt-out. Gating autorepair on it+ left an Apple Silicon host with a broken MLX stack chat-only for good, where before it+ ran in the lifespan no matter what."""+ tree = ast.parse((_BACKEND / "main.py").read_text(encoding = "utf-8"))+ fn = next(+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.FunctionDef) and node.name == "_post_warm_background_work"+ )+ body = fn.body++ def _index_of(predicate) -> int:+ for i, stmt in enumerate(body):+ if predicate(ast.dump(stmt)):+ return i+ return -1++ mlx_at = _index_of(lambda d: "start_mlx_autorepair_if_needed" in d)+ gate_at = _index_of(lambda d: "DISABLE_ENV_VAR" in d and "Return" in d)+ rag_at = _index_of(lambda d: "_warm_rag_embedder" in d)++ assert mlx_at >= 0 and gate_at >= 0 and rag_at >= 0+ assert mlx_at < gate_at, (+ "the kill-switch return precedes MLX autorepair, so setting "+ "UNSLOTH_STUDIO_DISABLE_TORCH_WARM leaves a broken MLX host chat-only"+ )+ assert gate_at < rag_at, (+ "the RAG warm is no longer gated; it pulls sentence-transformers and "+ "torch, which is what the kill switch exists to prevent"+ )+++def test_the_purge_rechecks_before_touching_sys_modules():+ """A racing retry republishes the parent; do not strip modules under it."""+ src = (_BACKEND / "utils" / "torch_warmup.py").read_text(encoding = "utf-8")+ tree = ast.parse(src)+ fn = next(+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.FunctionDef) and node.name == "purge_partial_import"+ )+ # `package in sys.modules` is a Compare/In, which a dumped-text search misses.+ checks = [+ sub+ for sub in ast.walk(fn)+ if isinstance(sub, ast.Compare)+ and any(isinstance(op, ast.In) for op in sub.ops)+ and any(+ isinstance(c, ast.Attribute)+ and c.attr == "modules"+ and getattr(c.value, "id", None) == "sys"+ for c in sub.comparators+ )+ ]+ assert len(checks) >= 3, (+ f"expected the entry guard plus a re-check before and during the pops, "+ f"found {len(checks)} membership tests"+ )+++def test_the_purge_stops_when_the_parent_reappears(monkeypatch):+ """Behavioural half of the guard above, not just its shape."""+ import utils.torch_warmup as warmup++ popped: list[str] = []+ fake = {"pkg.a": object(), "pkg.b": object(), "pkg.c": object()}++ class _Watcher(dict):+ def pop(+ self,+ key,+ default = None,+ ):+ popped.append(key)+ # A retry publishes the parent right after the first pop.+ if len(popped) == 1:+ self["pkg"] = object()+ return super().pop(key, default)++ watcher = _Watcher(fake)+ monkeypatch.setattr(warmup.sys, "modules", watcher)+ monkeypatch.setattr(warmup, "_is_extension_module", lambda name: False)++ warmup.purge_partial_import("pkg")+ assert len(popped) == 1, f"kept purging after the parent came back: popped {popped}"+++def test_the_purge_still_cleans_an_uncontested_failure(monkeypatch):+ """Negative control: the guards must not disable the purge outright."""+ import utils.torch_warmup as warmup++ fake = {"pkg.a": object(), "pkg.b": object()}+ monkeypatch.setattr(warmup.sys, "modules", fake)+ monkeypatch.setattr(warmup, "_is_extension_module", lambda name: False)++ removed = warmup.purge_partial_import("pkg")+ assert sorted(removed) == ["pkg.a", "pkg.b"]+ assert fake == {}+++def test_threading_import_is_present_for_the_lazy_fetch():+ """The lazy start puts up its own thread; keep the import it needs."""+ src = (_BACKEND / "core" / "inference" / "orchestrator.py").read_text(encoding = "utf-8")+ assert "import threading" in src+ assert isinstance(threading.Lock(), type(threading.Lock()))+++# --------------------------------------------------- post-warm thread lifetime+++def test_shutdown_stands_the_post_warm_thread_down(monkeypatch):+ """Work must not start for an application that has already stopped. The worker is parked+ in join_background_warm(), so a shutdown before the warm finishes reaches it no other+ way: it wakes later and loads the embedder, which can spawn a llama-server."""+ import main as main_mod++ ran: list[str] = []+ released = threading.Event()++ monkeypatch.setattr(main_mod, "join_background_warm", lambda *a, **k: released.wait(30))+ monkeypatch.setattr(main_mod, "_warm_rag_embedder", lambda: ran.append("rag"))+ import utils.mlx_repair as mlx_mod++ monkeypatch.setattr(mlx_mod, "start_mlx_autorepair_if_needed", lambda: ran.append("mlx"))++ assert main_mod._start_post_warm_thread() is True+ worker = main_mod._post_warm_thread+ try:+ # Shutdown while the worker is still inside the join.+ main_mod._stop_post_warm_thread()+ finally:+ released.set()+ worker.join(30)++ assert ran == [], (+ f"post-warm work ran after shutdown: {ran}. The RAG warm can load an "+ f"embedder or start a llama-server for a stopped application."+ )+++def test_the_post_warm_thread_still_works_without_a_shutdown(monkeypatch):+ """Negative control: standing down must not become never running."""+ import main as main_mod+ import utils.mlx_repair as mlx_mod++ ran: list[str] = []+ monkeypatch.setattr(main_mod, "join_background_warm", lambda *a, **k: None)+ monkeypatch.setattr(mlx_mod, "start_mlx_autorepair_if_needed", lambda: ran.append("mlx"))+ monkeypatch.setattr(main_mod, "_warm_rag_embedder", lambda: ran.append("rag"))++ assert main_mod._start_post_warm_thread() is True+ main_mod._post_warm_thread.join(30)+ assert ran == ["mlx", "rag"]+++def test_a_restart_gets_its_own_worker_while_the_old_one_is_parked(monkeypatch):+ """The handoff case: the replacement must do the work, not inherit a refusal. Refusing+ while the previous worker was alive left a restart with nothing: the old worker was+ parked in the join so the start declined, then it read the shutdown and exited."""+ import main as main_mod+ import utils.mlx_repair as mlx_mod++ ran: list[str] = []+ release_old = threading.Event()+ release_new = threading.Event()+ joins: list[int] = []++ def _join(*_a, **_k):+ joins.append(1)+ (release_old if len(joins) == 1 else release_new).wait(30)++ monkeypatch.setattr(main_mod, "join_background_warm", _join)+ monkeypatch.setattr(mlx_mod, "start_mlx_autorepair_if_needed", lambda: ran.append("mlx"))+ monkeypatch.setattr(main_mod, "_warm_rag_embedder", lambda: ran.append("rag"))++ # Lifespan 1 starts a worker, then shuts down while it is still parked.+ assert main_mod._start_post_warm_thread() is True+ old = main_mod._post_warm_thread+ main_mod._stop_post_warm_thread()++ # Lifespan 2 starts immediately, with the old worker still alive.+ assert (+ main_mod._start_post_warm_thread() is True+ ), "the restart was refused a worker because the retired one was still parked"+ new = main_mod._post_warm_thread+ assert new is not old++ release_old.set()+ old.join(30)+ release_new.set()+ new.join(30)++ assert ran == ["mlx", "rag"], f"the restarted lifespan did not get its deferred work: {ran}"+++def test_only_the_current_generation_does_the_work(monkeypatch):+ """Two parked workers, one retired: exactly one must proceed."""+ import main as main_mod+ import utils.mlx_repair as mlx_mod++ ran: list[str] = []+ gate = threading.Event()+ monkeypatch.setattr(main_mod, "join_background_warm", lambda *a, **k: gate.wait(30))+ monkeypatch.setattr(mlx_mod, "start_mlx_autorepair_if_needed", lambda: ran.append("mlx"))+ monkeypatch.setattr(main_mod, "_warm_rag_embedder", lambda: ran.append("rag"))++ main_mod._start_post_warm_thread()+ first = main_mod._post_warm_thread+ main_mod._start_post_warm_thread()+ second = main_mod._post_warm_thread++ gate.set()+ first.join(30)+ second.join(30)++ assert ran == ["mlx", "rag"], f"expected one worker to do the work once, got {ran}"+++def test_shutdown_does_not_wait_for_the_post_warm_thread():+ """Retiring must not join: a join would hold shutdown for the rest of the ML+ stack import, which is the stall this path exists to avoid."""+ tree = ast.parse((_BACKEND / "main.py").read_text(encoding = "utf-8"))+ fn = next(+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.FunctionDef) and node.name == "_stop_post_warm_thread"+ )+ joins = [+ sub+ for sub in ast.walk(fn)+ if isinstance(sub, ast.Call) and getattr(sub.func, "attr", None) == "join"+ ]+ assert not joins, "shutdown joins the post-warm thread; that can block for the import"+++def test_the_lifespan_stops_the_post_warm_thread_on_shutdown():+ """Guard the wiring: the signal has to actually be sent."""+ tree = ast.parse((_BACKEND / "main.py").read_text(encoding = "utf-8"))+ fn = next(+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.AsyncFunctionDef) and node.name == "lifespan"+ )+ called = {+ sub.func.id+ for sub in ast.walk(fn)+ if isinstance(sub, ast.Call) and isinstance(sub.func, ast.Name)+ }+ assert "_stop_post_warm_thread" in called+ assert "_start_post_warm_thread" in called+++# ------------------------------------------------- authoritative health verdict+++def test_health_will_not_publish_a_verdict_mid_redetect(monkeypatch):+ """A forced re-detect must not be reported as a settled answer.++ config/env.ts caches the first reply carrying device_type as authoritative and the+ sidebar poll continues only while it reads chat_only_reason == "mlx_unavailable", so+ one mid-pass chat-only reply with a null reason hides Train for the SPA session."""+ import main as main_mod++ hw_mod = main_mod._hw_module+ monkeypatch.setattr(hw_mod, "DEVICE", hw_mod.DeviceType.CPU, raising = False)+ monkeypatch.setattr(hw_mod, "CHAT_ONLY", True, raising = False)+ monkeypatch.setattr(hw_mod, "CHAT_ONLY_REASON", None, raising = False)+ hw_mod.DETECTION_COMPLETE.clear()+ try:+ assert (+ main_mod._hardware_snapshot() is None+ ), "a cleared completion event still produced a publishable verdict"+ finally:+ hw_mod.DETECTION_COMPLETE.set()+++def test_health_snapshot_rejects_a_torn_read(monkeypatch):+ """Event set but DEVICE gone is the shutdown/detector race, not an answer."""+ import main as main_mod++ hw_mod = main_mod._hw_module+ monkeypatch.setattr(hw_mod, "DEVICE", None, raising = False)+ hw_mod.DETECTION_COMPLETE.set()+ assert main_mod._hardware_snapshot() is None+++def test_health_snapshot_returns_a_settled_verdict(monkeypatch):+ """Negative control: a settled verdict must still be publishable."""+ import main as main_mod++ hw_mod = main_mod._hw_module+ monkeypatch.setattr(hw_mod, "DEVICE", hw_mod.DeviceType.CPU, raising = False)+ monkeypatch.setattr(hw_mod, "CHAT_ONLY", True, raising = False)+ monkeypatch.setattr(hw_mod, "CHAT_ONLY_REASON", "mlx_unavailable", raising = False)+ hw_mod.DETECTION_COMPLETE.set()+ assert main_mod._hardware_snapshot() == (True, "mlx_unavailable")+++def test_health_rereads_the_verdict_after_authentication():+ """The bearer check is an await, so the pre-auth answer must be revalidated."""+ tree = ast.parse((_BACKEND / "main.py").read_text(encoding = "utf-8"))+ fn = next(+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.AsyncFunctionDef) and node.name == "health_check"+ )+ snapshots = [+ sub.lineno+ for sub in ast.walk(fn)+ if isinstance(sub, ast.Call) and getattr(sub.func, "id", None) == "_hardware_snapshot"+ ]+ assert len(snapshots) >= 2, (+ f"health_check takes {len(snapshots)} hardware snapshot(s); the verdict "+ f"published to an authed caller must be re-read after the auth await"+ )+ awaits = [sub.lineno for sub in ast.walk(fn) if isinstance(sub, ast.Await)]+ assert any(+ any(a > snapshots[0] and a < s for a in awaits) for s in snapshots[1:]+ ), "the second snapshot does not come after an await, so it revalidates nothing"+++def test_detection_wait_requires_a_device_not_just_the_event():+ """Event-set-with-DEVICE-None must send the caller to a fresh detection."""+ tree = ast.parse((_BACKEND / "main.py").read_text(encoding = "utf-8"))+ fn = next(+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.AsyncFunctionDef) and node.name == "_await_hardware_detection"+ )+ # Match the executable form: the docstring names DEVICE too, so text search passes on prose.+ device_tests = [+ sub+ for sub in ast.walk(fn)+ if isinstance(sub, ast.Compare)+ and isinstance(sub.left, ast.Attribute)+ and sub.left.attr == "DEVICE"+ and any(isinstance(op, (ast.IsNot, ast.Is)) for op in sub.ops)+ ]+ assert len(device_tests) >= 2, (+ f"found {len(device_tests)} DEVICE comparison(s); both the fast path and "+ f"the poll loop must require a device, or a torn event-set/DEVICE-None "+ f"state is reported as detected and nothing re-detects"+ )+++# ------------------------------------------------- cached-model delete guard+++def test_the_delete_guard_runs_off_the_event_loop():+ """Both load-state guards must go to a worker, in one hop.+ _inference_backend_blocks_delete() is sync and reaches get_inference_backend(), whose+ cold build waits on detection: inline, an authed DELETE held the loop for the import."""+ path = _BACKEND / "hub" / "services" / "models" / "deletion.py"+ tree = ast.parse(path.read_text(encoding = "utf-8"))+ fn = next(+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.AsyncFunctionDef) and node.name == "delete_cached_model_response"+ )++ # The guards belong to the nested helper handed to the worker, not the body.+ nested = {node.name for node in ast.walk(fn) if isinstance(node, ast.FunctionDef)}+ assert "_load_state_blocks_delete" in nested, (+ "the load-state guards are called inline again; get_inference_backend() "+ "then blocks the event loop for the remaining torch import"+ )++ offloaded = set()+ for sub in ast.walk(fn):+ if (+ isinstance(sub, ast.Call)+ and getattr(sub.func, "attr", None) == "to_thread"+ and sub.args+ ):+ offloaded.add(getattr(sub.args[0], "id", None))+ assert "_load_state_blocks_delete" in offloaded+++def test_the_delete_guard_keeps_its_short_circuit_and_fail_closed():+ """The offload must not change what the guard decides. The `or` matters: with a GGUF model+ loaded the first guard answers and the second never runs. And an unreadable load state+ must still raise rather than fall through to unlinking weights under a live process."""+ path = _BACKEND / "hub" / "services" / "models" / "deletion.py"+ tree = ast.parse(path.read_text(encoding = "utf-8"))+ helper = next(+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.FunctionDef) and node.name == "_load_state_blocks_delete"+ )+ bool_ops = [sub for sub in ast.walk(helper) if isinstance(sub, ast.BoolOp)]+ assert bool_ops and isinstance(bool_ops[0].op, ast.Or), (+ "the guard no longer short-circuits; the inference lookup would run even "+ "when llama.cpp has already answered"+ )++ fn = next(+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.AsyncFunctionDef) and node.name == "delete_cached_model_response"+ )++ # Bind to the specific Try, not any Try whose dump mentions to_thread: a decoy elsewhere+ # in the handler would satisfy that with the real fail-closed guard deleted.+ def _offloads_the_delete_guard(node: ast.Try) -> bool:+ return any(+ isinstance(call, ast.Call)+ and isinstance(call.func, ast.Attribute)+ and call.func.attr == "to_thread"+ and any(+ isinstance(a, ast.Name) and a.id == "_load_state_blocks_delete" for a in call.args+ )+ for stmt in node.body+ for call in ast.walk(stmt)+ )++ guarded = [+ sub+ for sub in ast.walk(fn)+ if isinstance(sub, ast.Try) and sub.handlers and _offloads_the_delete_guard(sub)+ ]+ assert guarded, "the offloaded guard is no longer inside a try/except"+ # The raise must be in a handler: in the body it says nothing about an unreadable state.+ raises = [+ sub+ for handler in guarded[0].handlers+ for sub in ast.walk(handler)+ if isinstance(sub, ast.Raise)+ ]+ assert raises, "an unreadable load state no longer raises; delete would proceed"+++# ------------------------------------------------- the kill switch and health+def test_health_does_not_kick_detection_when_the_warm_is_off(monkeypatch):+ """The torch-warm switch has to survive the automatic health probe. The desktop preflight+ and the frontend's first fetch both hit /api/health unasked, so a kick from there+ imports torch on exactly the hosts whose owner set the switch."""+ import asyncio as _asyncio++ import main as main_mod++ kicks = []+ monkeypatch.setattr(+ main_mod, "start_background_detection", lambda: kicks.append(1), raising = True+ )+ monkeypatch.setenv(main_mod.DISABLE_ENV_VAR, "1")++ hw_mod = main_mod._hw_module+ monkeypatch.setattr(hw_mod, "DEVICE", None, raising = False)+ was_complete = hw_mod.DETECTION_COMPLETE.is_set()+ hw_mod.DETECTION_COMPLETE.clear()+ try:+ detected = _asyncio.run(main_mod._await_hardware_detection(0.2))+ finally:+ if was_complete:+ hw_mod.DETECTION_COMPLETE.set()++ assert not kicks, "the health path started a torch import the kill switch forbids"+ assert detected is False, "health claimed a verdict nothing had measured"+++def test_health_still_kicks_detection_when_the_warm_is_on(monkeypatch):+ """Negative control: the switch is what stops the kick, not the fix itself."""+ import asyncio as _asyncio++ import main as main_mod++ kicks = []+ monkeypatch.setattr(+ main_mod, "start_background_detection", lambda: kicks.append(1), raising = True+ )+ monkeypatch.delenv(main_mod.DISABLE_ENV_VAR, raising = False)++ hw_mod = main_mod._hw_module+ monkeypatch.setattr(hw_mod, "DEVICE", None, raising = False)+ was_complete = hw_mod.DETECTION_COMPLETE.is_set()+ hw_mod.DETECTION_COMPLETE.clear()+ try:+ _asyncio.run(main_mod._await_hardware_detection(0.05))+ finally:+ if was_complete:+ hw_mod.DETECTION_COMPLETE.set()++ assert kicks, "nothing filled DEVICE in; health would report detecting forever"+++def test_the_switch_still_reports_a_verdict_it_already_has(monkeypatch):+ """Not kicking is not the same as not answering: once something else has detected+ (the first training or export call), health must stop answering provisionally."""+ import asyncio as _asyncio++ import main as main_mod++ monkeypatch.setenv(main_mod.DISABLE_ENV_VAR, "1")+ hw_mod = main_mod._hw_module+ monkeypatch.setattr(hw_mod, "DEVICE", hw_mod.DeviceType.CPU, raising = False)+ was_complete = hw_mod.DETECTION_COMPLETE.is_set()+ hw_mod.DETECTION_COMPLETE.set()+ try:+ assert _asyncio.run(main_mod._await_hardware_detection(0.05)) is True+ finally:+ if not was_complete:+ hw_mod.DETECTION_COMPLETE.clear()+++# ------------------------------------------------------- the vision probe hop+def test_the_standalone_vision_probe_runs_off_the_event_loop():+ """GET /api/models/check-vision must not build the registry sets inline. The sets behind+ is_vision_model() are lazy now, so the first call either imports transformers or waits+ on _DETECTION_SETS_LOCK while the warm holds it. Both park uvicorn."""+ path = _BACKEND / "routes" / "models.py"+ tree = ast.parse(path.read_text(encoding = "utf-8"))+ fn = next(+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.AsyncFunctionDef) and node.name == "check_vision_model"+ )++ # Nested helpers are the offload, so only the handler's own body counts as inline.+ nested = {+ sub+ for helper in ast.walk(fn)+ if isinstance(helper, ast.FunctionDef)+ for sub in ast.walk(helper)+ }+ direct = [+ sub+ for sub in ast.walk(fn)+ if isinstance(sub, ast.Call)+ and isinstance(sub.func, ast.Name)+ and sub.func.id == "is_vision_model"+ and sub not in nested+ ]+ assert not direct, (+ "is_vision_model() is called inline from the handler again; the lazy "+ "registry build then blocks the event loop"+ )++ offloaded = [+ sub+ for sub in ast.walk(fn)+ if isinstance(sub, ast.Call)+ and isinstance(sub.func, ast.Attribute)+ and sub.func.attr == "to_thread"+ ]+ assert offloaded, "the vision probe is no longer handed to a worker thread"+ reached = {+ call.func.id+ for helper in ast.walk(fn)+ if isinstance(helper, ast.FunctionDef)+ for call in ast.walk(helper)+ if isinstance(call, ast.Call) and isinstance(call.func, ast.Name)+ }+ assert "is_vision_model" in reached, (+ "nothing handed to the worker calls is_vision_model; the probe moved "+ "somewhere this test no longer covers"+ )+++# ------------------------------------------------------ offline is not just 1+def test_the_ranking_fetch_uses_the_shared_offline_check():+ """HF_HUB_OFFLINE=true and TRANSFORMERS_OFFLINE are offline here too. Every other offline+ read goes through hf_env_offline(); a literal "1" comparison leaves a boot that set any+ other accepted spelling making a raw outbound httpx.get to Hugging Face."""+ path = _BACKEND / "core" / "inference" / "orchestrator.py"+ tree = ast.parse(path.read_text(encoding = "utf-8"))+ fn = next(+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.FunctionDef) and node.name == "_start_top_models_fetch"+ )++ calls = [+ sub+ for sub in ast.walk(fn)+ if isinstance(sub, ast.Call)+ and isinstance(sub.func, ast.Name)+ and sub.func.id == "hf_env_offline"+ ]+ assert calls, "the ranking guard no longer asks the shared offline helper"++ literal = [+ sub+ for sub in ast.walk(fn)+ if isinstance(sub, ast.Constant) and sub.value == "HF_HUB_OFFLINE"+ ]+ assert not literal, (+ "the guard reads HF_HUB_OFFLINE directly again; true/yes/on and "+ "TRANSFORMERS_OFFLINE would go back to being treated as online"+ )+++def test_the_shared_offline_check_accepts_the_other_spellings(monkeypatch):+ """The helper the guard now uses has to be the broader one, not a rename."""+ from utils.utils import hf_env_offline++ for var, value in (+ ("HF_HUB_OFFLINE", "true"),+ ("HF_HUB_OFFLINE", "yes"),+ ("HF_HUB_OFFLINE", "on"),+ ("TRANSFORMERS_OFFLINE", "1"),+ ):+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)+ monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)+ monkeypatch.setenv(var, value)+ assert hf_env_offline(), f"{var}={value} was treated as online"++ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)+ monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)+ assert not hf_env_offline(), "a host with neither variable set was called offline"+++# --------------------------------------------- shutdown resets the whole verdict+def test_shutdown_resets_chat_only_with_the_detection_event():+ """Clearing DEVICE without CHAT_ONLY leaves a stale capability published.++ Health falls back to a bare CHAT_ONLY read while the event is clear, so a second+ lifespan after a GPU run would answer chat_only: false before anything re-measured it.+ config/env.ts stores that even with no device_type, showing Train and Export."""+ import asyncio as _asyncio++ from utils import lifespan_shutdown as shutdown_mod++ hw_mod = _FakeHardwareModule()+ hw_mod.DEVICE = "cuda"+ hw_mod.CHAT_ONLY = False+ hw_mod.CHAT_ONLY_REASON = None+ hw_mod.IS_ROCM = True+ hw_mod.DETECTION_COMPLETE.set()++ _asyncio.run(_run_shutdown(shutdown_mod, hw_mod))++ assert hw_mod.DEVICE is None+ assert not hw_mod.DETECTION_COMPLETE.is_set()+ assert hw_mod.CHAT_ONLY is True, (+ "a torn-down GPU verdict is still published as chat_only: false; the "+ "next lifespan offers Train and Export before detection has run"+ )+ assert hw_mod.CHAT_ONLY_REASON is None+ assert hw_mod.IS_ROCM is False, "a stale ROCm flag would mislabel the next host"+++class _FakeHardwareModule:+ """The minimal hardware surface run_lifespan_shutdown touches."""++ def __init__(self) -> None:+ self.DEVICE = None+ self.CHAT_ONLY = True+ self.CHAT_ONLY_REASON = None+ self.IS_ROCM = False+ self.DETECTION_COMPLETE = threading.Event()+++async def _run_shutdown(shutdown_mod, hw_mod) -> None:+ """Drive run_lifespan_shutdown with everything but the hardware reset stubbed."""+ await shutdown_mod.run_lifespan_shutdown(+ terminate_downloads = lambda: None,+ clear_compiled_cache = lambda: None,+ hw_module = hw_mod,+ )+++# ------------------------------------------- the post-warm worker rechecks+def test_the_post_warm_worker_rechecks_before_each_action():+ """One check after the join leaves a window shutdown can land in. The MLX autorepair and+ the RAG warm each take their own time, and the RAG warm can spawn a llama-server, so a+ generation read before each action is what keeps a stopped lifespan from starting one."""+ tree = ast.parse((_BACKEND / "main.py").read_text(encoding = "utf-8"))+ fn = next(+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.FunctionDef) and node.name == "_post_warm_background_work"+ )+ checks = [+ sub+ for sub in ast.walk(fn)+ if isinstance(sub, ast.Call)+ and isinstance(sub.func, ast.Name)+ and sub.func.id == "_post_warm_retired"+ ]+ assert len(checks) >= 3, (+ "the post-warm worker checks retirement fewer than once per action; a "+ "shutdown landing after the join can still start MLX autorepair or a "+ "llama-server for a lifespan that has stopped"+ )+++def test_the_retirement_check_reads_the_live_generation(monkeypatch):+ """It has to compare against the current counter, not a captured one."""+ import main as main_mod++ monkeypatch.setattr(main_mod, "_post_warm_current_generation", lambda: 7, raising = True)+ assert main_mod._post_warm_retired(7) is False+ assert main_mod._post_warm_retired(6) is True+ assert (+ main_mod._post_warm_retired(None) is False+ ), "a direct call with no generation must still run; that is the test path"+++# --------------------------------------- the saved GPU override goes off-loop+def test_the_saved_gpu_override_check_runs_off_the_event_loop():+ """The auto-switch path reaches this before any explicit-gpu_ids offload, and+ resolve_requested_gpu_ids() calls get_device() itself, so both wait on the+ detection lock while the warm imports torch."""+ path = _BACKEND / "routes" / "inference.py"+ tree = ast.parse(path.read_text(encoding = "utf-8"))+ fn = next(+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.AsyncFunctionDef) and node.name == "_override_gpu_ids_still_resolve"+ )+ nested = {+ sub+ for helper in ast.walk(fn)+ if isinstance(helper, ast.FunctionDef)+ for sub in ast.walk(helper)+ }+ inline = [+ sub+ for sub in ast.walk(fn)+ if isinstance(sub, ast.Call)+ and isinstance(sub.func, ast.Name)+ and sub.func.id in {"get_device", "resolve_requested_gpu_ids"}+ and sub not in nested+ ]+ assert not inline, (+ "get_device() or resolve_requested_gpu_ids() is called inline again; the "+ "first auto-switch to a model with a stored pin then holds the event loop "+ "for the whole torch import"+ )+ reached = {+ call.func.id+ for helper in ast.walk(fn)+ if isinstance(helper, ast.FunctionDef)+ for call in ast.walk(helper)+ if isinstance(call, ast.Call) and isinstance(call.func, ast.Name)+ }+ assert {"get_device", "resolve_requested_gpu_ids"} <= reached, (+ "the offloaded helper no longer does the device resolution; the check "+ "moved somewhere this test does not cover"+ )+++# ------------------------------------------ a retired detection cannot publish+def test_a_detection_retired_by_shutdown_does_not_publish(monkeypatch):+ """A detector inside the torch import must not put back what shutdown cleared.++ Shutdown cannot take _DETECT_LOCK to stop it -- that parks teardown behind the whole+ import -- so it retires the epoch. Otherwise the detector republishes a settled-looking+ verdict over the reset, and the next lifespan skips detection on a non-None DEVICE."""+ monkeypatch.setattr(hw, "DEVICE", None, raising = False)+ monkeypatch.setattr(hw, "CHAT_ONLY", True, raising = False)++ def _detect_and_get_retired():+ # Stands in for the torch import: shutdown lands while we are inside it.+ hw.DEVICE = hw.DeviceType.CUDA+ hw.CHAT_ONLY = False+ hw.invalidate_detection()+ return hw.DeviceType.CUDA++ monkeypatch.setattr(hw, "_detect_hardware_locked", _detect_and_get_retired)+ hw.DETECTION_COMPLETE.clear()+ hw.detect_hardware()++ assert hw.DEVICE is None, (+ "a retired detection published its verdict; the next lifespan skips "+ "detection and serves hardware the previous one measured"+ )+ assert hw.CHAT_ONLY is True+ assert not hw.DETECTION_COMPLETE.is_set()+++def test_a_detection_that_is_not_retired_still_publishes(monkeypatch):+ """Negative control: the epoch gate must not block ordinary detection."""+ monkeypatch.setattr(hw, "DEVICE", None, raising = False)+ monkeypatch.setattr(hw, "CHAT_ONLY", True, raising = False)++ def _ok():+ hw.DEVICE = hw.DeviceType.CUDA+ hw.CHAT_ONLY = False+ return hw.DeviceType.CUDA++ monkeypatch.setattr(hw, "_detect_hardware_locked", _ok)+ hw.DETECTION_COMPLETE.clear()+ try:+ assert hw.detect_hardware() is hw.DeviceType.CUDA+ assert hw.DEVICE is hw.DeviceType.CUDA+ assert hw.DETECTION_COMPLETE.is_set()+ finally:+ hw.DETECTION_COMPLETE.set()+++def test_shutdown_retires_the_detection_epoch():+ """run_lifespan_shutdown must move the epoch, not just clear the globals."""+ src = (_BACKEND / "utils" / "lifespan_shutdown.py").read_text(encoding = "utf-8")+ tree = ast.parse(src)+ fn = next(+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.AsyncFunctionDef) and node.name == "run_lifespan_shutdown"+ )+ names = {+ sub.value+ for sub in ast.walk(fn)+ if isinstance(sub, ast.Constant) and isinstance(sub.value, str)+ }+ assert "invalidate_detection" in names, (+ "shutdown no longer retires the detection epoch; a detector in the torch "+ "import republishes over the reset"+ )+++# ------------------------------------------- the MCP status tool stays off-loop+def test_the_mcp_status_tool_reads_hardware_off_the_event_loop():+ """get_gpu_utilization() reaches detection, which blocks on the warm import."""+ path = _BACKEND / "mcp_server.py"+ tree = ast.parse(path.read_text(encoding = "utf-8"))+ called_directly = [+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.Call)+ and isinstance(node.func, ast.Name)+ and node.func.id == "get_gpu_utilization"+ ]+ assert not called_directly, (+ "the MCP status tool calls get_gpu_utilization() inline again; it blocks "+ "the event loop on the warm's torch import"+ )+ offloaded = [+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.Call)+ and isinstance(node.func, ast.Attribute)+ and node.func.attr == "to_thread"+ and any(isinstance(a, ast.Name) and a.id == "get_gpu_utilization" for a in node.args)+ ]+ assert offloaded, "the hardware read is no longer handed to a worker thread"+++# -------------------------------- an authed reply is not both settled and not+def test_an_authed_reply_drops_the_provisional_marker():+ """base is built before the bearer await, so its marker can be out of date."""+ tree = ast.parse((_BACKEND / "main.py").read_text(encoding = "utf-8"))+ fn = next(+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.AsyncFunctionDef) and node.name == "health_check"+ )+ pops = [+ sub+ for sub in ast.walk(fn)+ if isinstance(sub, ast.Call)+ and isinstance(sub.func, ast.Attribute)+ and sub.func.attr == "pop"+ and any(isinstance(a, ast.Constant) and a.value == "hardware_detecting" for a in sub.args)+ ]+ assert pops, (+ "an authed reply can still carry hardware_detecting beside the measured "+ "verdict it qualifies; a client may believe either one"+ )+++# ----------------------------------------- deferred detection is not "in progress"+def test_health_marks_a_deferred_detection_as_deferred(monkeypatch):+ """With the warm off nothing settles, so a poller must be told to stop."""+ tree = ast.parse((_BACKEND / "main.py").read_text(encoding = "utf-8"))+ fn = next(+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.AsyncFunctionDef) and node.name == "health_check"+ )+ keys = {+ sub.slice.value+ for sub in ast.walk(fn)+ if isinstance(sub, ast.Subscript)+ and isinstance(sub.slice, ast.Constant)+ and isinstance(sub.slice.value, str)+ }+ assert "hardware_detection_deferred" in keys, (+ "health does not distinguish a deferred detection from one in flight; a "+ "client waiting for a measured verdict stalls every load for its whole "+ "budget, including /login"+ )+++# ------------------------------------ the warm stops once its lifespan is retired+def test_the_warm_stops_after_a_stage_its_lifespan_no_longer_owns():+ """Later stages build the orchestrator, which starts a fresh detection. Discarding the+ hardware stage's verdict is not enough: the inference_backend stage reaches get_device()+ and would republish DEVICE after teardown cleared it."""+ tree = ast.parse((_BACKEND / "utils" / "torch_warmup.py").read_text(encoding = "utf-8"))+ fn = next(+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.FunctionDef) and node.name == "_warm"+ )+ loops = [sub for sub in ast.walk(fn) if isinstance(sub, ast.For)]+ assert loops, "the warm no longer iterates its stages"+ checks = [+ sub+ for sub in ast.walk(loops[0])+ if isinstance(sub, ast.Call)+ and isinstance(sub.func, ast.Name)+ and sub.func.id == "_detection_epoch"+ ]+ assert checks, (+ "the stage loop does not re-check the detection epoch; a warm whose "+ "lifespan ended still runs the stages that rebuild the verdict"+ )+++# -------------------------------- describing what is loaded must not build it+def test_the_monitor_context_read_does_not_construct_the_backend():+ """It is called inline from the OpenAI, Responses and Anthropic paths."""+ tree = ast.parse((_BACKEND / "routes" / "inference.py").read_text(encoding = "utf-8"))+ fn = next(+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.FunctionDef) and node.name == "_monitor_context_length"+ )+ constructing = [+ sub+ for sub in ast.walk(fn)+ if isinstance(sub, ast.Call)+ and isinstance(sub.func, ast.Name)+ and sub.func.id == "get_inference_backend"+ ]+ assert not constructing, (+ "_monitor_context_length constructs the singleton again; the first API "+ "request during the warm then waits on the torch import on the loop"+ )+ peeking = [+ sub+ for sub in ast.walk(fn)+ if isinstance(sub, ast.Call)+ and isinstance(sub.func, ast.Name)+ and sub.func.id == "_peek_inference_backend"+ ]+ assert peeking, "the helper no longer reads the backend at all"+++def test_the_peek_never_constructs():+ """Behavioural: the peek must return None rather than build one."""+ from core.inference.orchestrator import peek_inference_backend+ import core.inference.orchestrator as orch++ before = orch._inference_backend+ try:+ orch._inference_backend = None+ assert peek_inference_backend() is None+ assert orch._inference_backend is None, "the peek constructed an orchestrator"+ finally:+ orch._inference_backend = before+++def test_the_metadata_cleanup_does_not_construct_the_backend():+ """A metadata-only cleanup has no reason to import torch."""+ tree = ast.parse((_BACKEND / "routes" / "models.py").read_text(encoding = "utf-8"))+ fn = next(+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.AsyncFunctionDef) and node.name == "discard_remote_code_download"+ )+ constructing = [+ sub+ for sub in ast.walk(fn)+ if isinstance(sub, ast.Call)+ and isinstance(sub.func, ast.Name)+ and sub.func.id == "get_inference_backend"+ ]+ assert (+ not constructing+ ), "the cleanup path constructs the ML backend again for a metadata-only decision"+ assert any(+ isinstance(sub, ast.Call)+ and isinstance(sub.func, ast.Name)+ and sub.func.id == "peek_inference_backend"+ for sub in ast.walk(fn)+ ), "the cleanup path no longer checks the loaded model at all"+++def test_the_research_probes_do_not_construct_the_backend():+ """A durable research run resumes on the loop as soon as the port is recorded, and+ calls these two sync probes inline, so a cold get_inference_backend() there parks+ uvicorn on the torch import for the rest of the warm."""+ tree = ast.parse((_BACKEND / "core" / "research_runs.py").read_text(encoding = "utf-8"))+ for name in ("_loaded_context_length", "_local_model_ready"):+ fn = next(+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.FunctionDef) and node.name == name+ )+ assert not [+ sub+ for sub in ast.walk(fn)+ if isinstance(sub, ast.Call)+ and isinstance(sub.func, ast.Name)+ and sub.func.id == "get_inference_backend"+ ], f"{name} constructs the singleton inline; a resumed run then blocks the loop"+ assert any(+ isinstance(sub, ast.Call)+ and isinstance(sub.func, ast.Name)+ and sub.func.id == "_peek_inference_backend"+ for sub in ast.walk(fn)+ ), f"{name} no longer reads the native backend at all"+++def test_the_research_peek_answers_cold_without_constructing():+ """Behavioural: with no orchestrator built, both probes answer and build nothing."""+ import core.inference.orchestrator as orch+ from core import research_runs++ before = orch._inference_backend+ try:+ orch._inference_backend = None+ assert research_runs._loaded_context_length() is None+ assert research_runs._local_model_ready() is False, (+ "no orchestrator means no native model is loaded; that is an answer, not a "+ "failed probe, so the run must not be told to go ahead"+ )+ assert orch._inference_backend is None, "a probe constructed an orchestrator"+ finally:+ orch._inference_backend = before+++class _DeferredThread:+ """A Thread whose start() only schedules; the test calls run() later. That gap is the+ race: the spawner has returned and shutdown has retired the epoch before the body runs."""++ instances: list = []++ def __init__(+ self,+ target = None,+ args = (),+ **_kw,+ ):+ self._target, self._args = target, args+ self._started = False+ _DeferredThread.instances.append(self)++ def start(self):+ self._started = True++ def is_alive(self):+ return self._started++ def run_now(self):+ self._target(*self._args)+++def test_a_warm_delayed_past_shutdown_is_already_retired(monkeypatch):+ """The epoch must be bound at spawn, not by the thread itself.++ The child may not run for a while after start() and a shutdown in that gap retires the+ lifespan. A thread reading the epoch itself would read the post-shutdown value and warm+ on, rebuilding DEVICE and the orchestrator after teardown cleared them."""+ import utils.torch_warmup as warm+ from utils.hardware import hardware as hw++ ran: list = []+ stages = tuple((name, lambda name = name: ran.append(name)) for name in ("hardware", "later"))+ monkeypatch.setattr(warm, "_STAGES", stages)+ monkeypatch.setattr(warm.threading, "Thread", _DeferredThread)+ monkeypatch.setattr(warm, "_thread", None)+ # Own the latch and the status: leaving them set shows the next test a live warm.+ monkeypatch.setattr(warm, "_status", {"started": False, "finished": False, "stages": {}})+ monkeypatch.delenv(warm.DISABLE_ENV_VAR, raising = False)+ _DeferredThread.instances.clear()++ assert warm.start_background_warm() is True+ hw.invalidate_detection() # the shutdown that lands before the thread runs+ _DeferredThread.instances[-1].run_now()++ assert ran == [], f"a warm retired before it ran did its stages anyway: {ran}"+++def test_a_warm_that_owns_its_epoch_still_runs(monkeypatch):+ """Negative control: the guard must not stop an ordinary warm."""+ import utils.torch_warmup as warm++ ran: list = []+ stages = tuple((name, lambda name = name: ran.append(name)) for name in ("hardware", "later"))+ monkeypatch.setattr(warm, "_STAGES", stages)+ monkeypatch.setattr(warm.threading, "Thread", _DeferredThread)+ monkeypatch.setattr(warm, "_thread", None)+ # Own the latch and the status: leaving them set shows the next test a live warm.+ monkeypatch.setattr(warm, "_status", {"started": False, "finished": False, "stages": {}})+ monkeypatch.delenv(warm.DISABLE_ENV_VAR, raising = False)+ _DeferredThread.instances.clear()++ assert warm.start_background_warm() is True+ _DeferredThread.instances[-1].run_now()++ assert ran == ["hardware", "later"], f"a live warm was stopped: {ran}"+++def test_a_detection_delayed_past_shutdown_does_not_publish(monkeypatch):+ """Same race on the other spawner: start_background_detection()'s worker."""+ from utils.hardware import hardware as hw++ monkeypatch.setattr(hw, "DEVICE", None)+ monkeypatch.setattr(hw, "_DETECT_THREAD", None)+ monkeypatch.setattr(hw.threading, "Thread", _DeferredThread)+ monkeypatch.setattr(hw, "_detect_hardware_locked", lambda: setattr(hw, "DEVICE", "cuda"))+ # A fresh Event, so clearing it cannot leak "not detected yet" into a later test.+ monkeypatch.setattr(hw, "DETECTION_COMPLETE", threading.Event())+ _DeferredThread.instances.clear()++ hw.start_background_detection()+ hw.invalidate_detection()+ _DeferredThread.instances[-1].run_now()++ assert hw.DEVICE is None, "a retired detection published a verdict after teardown"+ assert not hw.DETECTION_COMPLETE.is_set(), "a retired detection announced itself as settled"+++def test_both_spawners_read_the_epoch_before_start():+ """AST: the epoch is read by the spawner and handed over, never read in the thread. The+ target may be indirect (a successor when a retired warm is still running), so match the+ Thread call by the spawner it lives in, not by a literal target name."""+ readers = {"_detection_epoch", "current_detection_epoch"}+ for rel, spawner in (+ (("utils", "torch_warmup.py"), "start_background_warm"),+ (("utils", "hardware", "hardware.py"), "start_background_detection"),+ ):+ tree = ast.parse(_BACKEND.joinpath(*rel).read_text(encoding = "utf-8"))+ fn = next(+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.FunctionDef) and node.name == spawner+ )+ call = next(+ (+ sub+ for sub in ast.walk(fn)+ if isinstance(sub, ast.Call) and any(kw.arg == "target" for kw in sub.keywords)+ ),+ None,+ )+ assert call is not None, f"{spawner} no longer starts a thread"+ args_kw = next((kw for kw in call.keywords if kw.arg == "args"), None)+ assert args_kw is not None, f"{spawner} starts its worker with no epoch handed over"++ # Every name args can carry, through one level of local-assignment indirection.+ def _names(node):+ out = {sub.id for sub in ast.walk(node) if isinstance(sub, ast.Name)}+ for assign in ast.walk(fn):+ if isinstance(assign, ast.Assign) and any(+ isinstance(t, ast.Name) and t.id in out for t in assign.targets+ ):+ out |= {s.id for s in ast.walk(assign.value) if isinstance(s, ast.Name)}+ if isinstance(assign, ast.Assign) and isinstance(assign.targets[0], ast.Tuple):+ tgt = {t.id for t in assign.targets[0].elts if isinstance(t, ast.Name)}+ if tgt & out:+ out |= {s.id for s in ast.walk(assign.value) if isinstance(s, ast.Name)}+ return out++ inline = any(+ isinstance(sub, ast.Call) and isinstance(sub.func, ast.Name) and sub.func.id in readers+ for sub in ast.walk(args_kw.value)+ )+ carried = _names(args_kw.value)+ bound = any(+ isinstance(node, ast.Assign)+ and any(isinstance(t, ast.Name) and t.id in carried for t in node.targets)+ and any(+ isinstance(sub, ast.Call)+ and isinstance(sub.func, ast.Name)+ and sub.func.id in readers+ for sub in ast.walk(node.value)+ )+ for node in ast.walk(fn)+ )+ assert (+ inline or bound+ ), f"{spawner} hands its worker args that never carry the detection epoch"+++def test_a_new_lifespan_warms_even_when_the_retired_one_is_still_running():+ """Declining to a stale live warm leaves the new lifespan with no warm at all. A shutdown+ mid-warm cannot reset the latch and the stale worker stops at its next stage boundary;+ nothing retries, so without a hand-off the restart serves cold."""+ import utils.torch_warmup as warm+ from utils.hardware import hardware as hw++ saved_thread, saved_epoch = warm._thread, warm._thread_epoch+ saved_status = dict(warm._status)+ disable = os.environ.pop(warm.DISABLE_ENV_VAR, None)+ release, entered, ran = threading.Event(), threading.Event(), []+ try:+ warm._thread, warm._thread_epoch = None, None+ warm._status.update({"started": False, "finished": False, "stages": {}})++ def _slow():+ entered.set()+ release.wait(30)+ ran.append("stale")++ with mock.patch.object(warm, "_STAGES", (("slow", _slow),)):+ assert warm.start_background_warm() is True+ assert entered.wait(30), "the first warm never started"+ hw.invalidate_detection() # shutdown, with the warm still inside a stage+ # reset_background_warm() declines here, exactly as it does in the lifespan.+ assert warm.reset_background_warm() is False+ with mock.patch.object(warm, "_STAGES", (("fresh", lambda: ran.append("fresh")),)):+ assert warm.start_background_warm() is True, (+ "the new lifespan was refused a warm because the retired one was "+ "still running"+ )+ release.set()+ assert warm.join_background_warm(60) is True+ assert ran == [+ "stale",+ "fresh",+ ], f"expected the successor to wait out the retired warm, got {ran}"+ finally:+ release.set()+ warm.join_background_warm(30)+ if disable is not None:+ os.environ[warm.DISABLE_ENV_VAR] = disable+ warm._thread, warm._thread_epoch = saved_thread, saved_epoch+ warm._status.clear()+ warm._status.update(saved_status)+++def test_a_failed_forced_redetect_does_not_restore_a_retired_verdict():+ """detect_hardware()'s except path must honour the epoch too. It saves the verdict, clears+ DETECTION_COMPLETE, then re-detects; if shutdown retires the pass and the probe raises,+ restoring puts back exactly what shutdown cleared and the next lifespan skips detection.+ The success path checked, the failure path did not."""+ from utils.hardware import hardware as hw++ saved = (hw.DEVICE, hw.CHAT_ONLY, hw.CHAT_ONLY_REASON, hw.IS_ROCM)+ was_complete = hw.DETECTION_COMPLETE.is_set()+ try:+ hw.DEVICE = hw.DeviceType.MLX+ hw.CHAT_ONLY = True+ hw.CHAT_ONLY_REASON = "mlx_unavailable"+ hw.DETECTION_COMPLETE.set()++ def _shutdown_then_fail():+ hw.invalidate_detection() # the shutdown, mid-pass+ raise RuntimeError("probe blew up")++ with mock.patch.object(hw, "_detect_hardware_locked", _shutdown_then_fail):+ with pytest.raises(RuntimeError):+ hw.detect_hardware()++ assert hw.DEVICE is None, "a retired pass restored the verdict shutdown cleared"+ assert hw.CHAT_ONLY_REASON is None+ assert not hw.DETECTION_COMPLETE.is_set(), "a retired pass re-announced itself as settled"+ finally:+ hw.DEVICE, hw.CHAT_ONLY, hw.CHAT_ONLY_REASON, hw.IS_ROCM = saved+ hw.DETECTION_COMPLETE.set() if was_complete else hw.DETECTION_COMPLETE.clear()+++def test_a_failed_redetect_inside_its_own_lifespan_still_restores():+ """Negative control: without a shutdown, the rollback must still happen."""+ from utils.hardware import hardware as hw++ saved = (hw.DEVICE, hw.CHAT_ONLY, hw.CHAT_ONLY_REASON, hw.IS_ROCM)+ was_complete = hw.DETECTION_COMPLETE.is_set()+ try:+ hw.DEVICE = hw.DeviceType.MLX+ hw.CHAT_ONLY = True+ hw.CHAT_ONLY_REASON = "mlx_unavailable"+ hw.DETECTION_COMPLETE.set()++ def _just_fail():+ raise RuntimeError("probe blew up")++ with mock.patch.object(hw, "_detect_hardware_locked", _just_fail):+ with pytest.raises(RuntimeError):+ hw.detect_hardware()++ assert hw.DEVICE is hw.DeviceType.MLX, "a live lifespan lost its verdict to a failed probe"+ assert (+ hw.CHAT_ONLY_REASON == "mlx_unavailable"+ ), "losing the reason stops the sidebar's MLX recovery poll for good"+ assert hw.DETECTION_COMPLETE.is_set()+ finally:+ hw.DEVICE, hw.CHAT_ONLY, hw.CHAT_ONLY_REASON, hw.IS_ROCM = saved+ hw.DETECTION_COMPLETE.set() if was_complete else hw.DETECTION_COMPLETE.clear()+++def test_a_broken_torch_install_is_not_reported_as_a_host_without_a_gpu():+ """An installed torch whose import raises is a detection failure, not "no GPU".++ Widening _has_torch() to swallow every exception keeps the warm thread from making each+ later request retry the failing import. Reporting it as no_gpu, though, tells a GPU box+ it has no GPU and sends export_capability down "install PyTorch" for an installed one."""+ from utils.hardware import hardware as hw++ saved_error = hw.TORCH_IMPORT_ERROR+ real_import = builtins.__import__++ def _broken(name, *a, **k):+ if name == "torch" or name.startswith("torch."):+ raise OSError("libcudart.so.13: cannot open shared object file")+ return real_import(name, *a, **k)++ try:+ with mock.patch.object(builtins, "__import__", _broken):+ assert hw._has_torch() is False, "a broken torch must not count as importable"+ assert hw.TORCH_IMPORT_ERROR is not None, "the import failure was not recorded"+ assert "libcudart" in hw.TORCH_IMPORT_ERROR+ finally:+ hw.TORCH_IMPORT_ERROR = saved_error+++def test_an_absent_torch_is_still_just_absent():+ """Negative control: a genuinely missing package is not a broken install. Only+ ModuleNotFoundError named "torch" is narrow enough to trust; plain ImportError is what a+ broken wheel raises."""+ from utils.hardware import hardware as hw++ saved_error = hw.TORCH_IMPORT_ERROR+ real_import = builtins.__import__++ def _missing(name, *a, **k):+ if name == "torch" or name.startswith("torch."):+ raise ModuleNotFoundError("No module named 'torch'", name = "torch")+ return real_import(name, *a, **k)++ try:+ hw.TORCH_IMPORT_ERROR = "stale"+ with mock.patch.object(builtins, "__import__", _missing):+ assert hw._has_torch() is False+ assert (+ hw.TORCH_IMPORT_ERROR is None+ ), "a --no-torch install would be reported as a detection failure"+ finally:+ hw.TORCH_IMPORT_ERROR = saved_error+++ "exc",+ [+ # Linux: raised inside torch's own __init__ when a native dependency does not resolve.+ ImportError("libcudart.so.12: cannot open shared object file"),+ # Windows.+ OSError("[WinError 126] The specified module could not be found"),+ # A missing submodule still means torch itself is installed.+ ModuleNotFoundError("No module named 'torch._C'", name = "torch._C"),+ ],+ ids = ["import_error_native_lib", "os_error_windows", "missing_submodule"],+)+def test_a_broken_torch_is_never_mistaken_for_an_absent_one(exc):+ """ImportError is not a synonym for "not installed". Keying on the class reports a wheel+ with unresolved CUDA libraries as a host with no GPU, sends export_capability() down+ "install PyTorch" for one already installed, and re-runs the failing import every check."""+ from utils.hardware import hardware as hw++ saved_error = hw.TORCH_IMPORT_ERROR+ real_import = builtins.__import__++ def _broken(name, *a, **k):+ if name == "torch" or name.startswith("torch."):+ raise exc+ return real_import(name, *a, **k)++ try:+ hw.TORCH_IMPORT_ERROR = None+ with mock.patch.object(builtins, "__import__", _broken):+ assert hw._has_torch() is False+ assert (+ hw.TORCH_IMPORT_ERROR is not None+ ), f"{type(exc).__name__} from an installed torch was read as absent"+ finally:+ hw.TORCH_IMPORT_ERROR = saved_error+++def test_the_default_model_list_is_stamped_before_it_is_built():+ """AST: read the generation first, or a stale list is tagged current forever.+ get_default_models() settles detection and reads CHAT_ONLY, so a re-detection between+ that and the stamp marks the pre-repair list as post-repair, permanently."""+ tree = ast.parse(+ (_BACKEND / "core" / "inference" / "orchestrator.py").read_text(encoding = "utf-8")+ )++ def _line_of(fn, predicate):+ return next(+ sub.lineno for sub in ast.walk(fn) if isinstance(sub, ast.Assign) and predicate(sub)+ )++ cls = next(+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.ClassDef) and node.name == "InferenceOrchestrator"+ )+ # __init__ is single-threaded, so ordering suffices; a racing re-detect lands ahead.+ init = next(+ node for node in cls.body if isinstance(node, ast.FunctionDef) and node.name == "__init__"+ )+ stamp = _line_of(+ init,+ lambda a: any(+ isinstance(t, ast.Attribute) and t.attr == "_static_models_generation"+ for t in a.targets+ ),+ )+ build = _line_of(+ init,+ lambda a: any(+ isinstance(t, ast.Attribute) and t.attr == "_static_models" for t in a.targets+ ),+ )+ assert stamp < build, (+ "InferenceOrchestrator.__init__ stamps the generation after building the list, "+ "so a re-detection in between makes the stale list look current forever"+ )++ # Concurrent readers can commit out of order, so ordering is not enough: capture the+ # generation before building, commit only while still newest.+ fn = next(+ node+ for node in cls.body+ if isinstance(node, ast.FunctionDef) and node.name == "_refresh_static_models_if_stale"+ )+ capture = _line_of(+ fn,+ lambda a: any(isinstance(t, ast.Name) and t.id == "generation" for t in a.targets),+ )+ build_call = next(+ sub.lineno+ for sub in ast.walk(fn)+ if isinstance(sub, ast.Call)+ and isinstance(sub.func, ast.Name)+ and sub.func.id == "get_default_models"+ )+ assert (+ capture < build_call+ ), "_refresh_static_models_if_stale reads the generation after building the list"+ guarded = next(+ (+ node+ for node in ast.walk(fn)+ if isinstance(node, ast.With)+ and any(+ isinstance(sub, ast.Attribute) and sub.attr == "_static_models_lock"+ for item in node.items+ for sub in ast.walk(item.context_expr)+ )+ ),+ None,+ )+ assert guarded is not None, "the commit is not serialized against concurrent refreshes"+ assert any(+ isinstance(sub, ast.Compare)+ and any(isinstance(n, ast.Name) and n.id == "generation" for n in ast.walk(sub))+ for sub in ast.walk(guarded)+ ), "the commit does not re-check the generation it built against"+ assert all(+ _line_of(+ guarded,+ lambda a, attr = attr: any(+ isinstance(t, ast.Attribute) and t.attr == attr for t in a.targets+ ),+ )+ for attr in ("_static_models", "_static_models_generation")+ ), "the stamp and the value are not committed together under the lock"+++def test_a_redetect_during_the_bearer_await_leaves_the_reply_provisional():+ """AST: the authed branch must mark the reply when the second snapshot is None. base+ carries no chat_only_reason, so an unmarked reply is read as measured and stores+ chat_only with reason null, stopping the sidebar's mlx_unavailable poll."""+ tree = ast.parse((_BACKEND / "main.py").read_text(encoding = "utf-8"))+ fn = next(+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.AsyncFunctionDef) and node.name == "health_check"+ )+ branch = next(+ node+ for node in ast.walk(fn)+ if isinstance(node, ast.If)+ and any(+ isinstance(sub, ast.Subscript)+ and isinstance(sub.value, ast.Name)+ and sub.value.id == "authed"+ and getattr(sub.slice, "value", None) == "device_type"+ for sub in ast.walk(node)+ )+ )+ assert branch.orelse, "no else branch: a mid-await re-detect ships an unmarked reply"+ assert any(+ isinstance(sub, ast.Subscript)+ and isinstance(sub.value, ast.Name)+ and sub.value.id == "authed"+ and getattr(sub.slice, "value", None) == "hardware_detecting"+ for node in branch.orelse+ for sub in ast.walk(node)+ ), "the else branch does not mark the reply provisional"+++def test_the_unload_eviction_checks_are_offloaded():+ """AST: both _unload_may_evict() calls reach the singleton, so neither runs inline."""+ tree = ast.parse((_BACKEND / "routes" / "inference.py").read_text(encoding = "utf-8"))+ inline = [+ sub.lineno+ for sub in ast.walk(tree)+ if isinstance(sub, ast.Call)+ and isinstance(sub.func, ast.Name)+ and sub.func.id == "_unload_may_evict"+ ]+ assert not inline, (+ f"_unload_may_evict is called inline at {inline}; it reaches "+ "get_inference_backend(), so an unload during the warm stalls the loop"+ )+ offloaded = [+ sub.lineno+ for sub in ast.walk(tree)+ if isinstance(sub, ast.Call)+ and isinstance(sub.func, ast.Attribute)+ and sub.func.attr == "to_thread"+ and any(isinstance(a, ast.Name) and a.id == "_unload_may_evict" for a in sub.args)+ ]+ assert len(offloaded) == 2, f"expected both eviction checks offloaded, found {offloaded}"+++def test_a_stale_waiter_does_not_discard_the_new_lifespan_verdict():+ """Only discard what this call produced.++ A detection worker from the previous lifespan can still be blocked on _DETECT_LOCK when+ shutdown retires its epoch. The new lifespan's warm takes the lock first and publishes;+ the stale worker then enters, finds DEVICE set so runs no detection, and must not wipe a+ verdict it did not produce -- that leaves the restarted app provisional."""+ from utils.hardware import hardware as hw++ saved = (hw.DEVICE, hw.CHAT_ONLY, hw.CHAT_ONLY_REASON, hw.IS_ROCM)+ was_complete = hw.DETECTION_COMPLETE.is_set()+ try:+ stale_epoch = hw.current_detection_epoch()+ hw.invalidate_detection() # the shutdown the worker lost to+ # The new lifespan's verdict, already published while the stale worker waited.+ hw.DEVICE = hw.DeviceType.CUDA+ hw.CHAT_ONLY = False+ hw.CHAT_ONLY_REASON = None+ hw.DETECTION_COMPLETE.set()++ def _must_not_run():+ raise AssertionError("the stale waiter re-ran detection over a live verdict")++ with mock.patch.object(hw, "_detect_hardware_locked", _must_not_run):+ hw.ensure_hardware_detected(stale_epoch)++ assert (+ hw.DEVICE is hw.DeviceType.CUDA+ ), "a stale waiter discarded the new lifespan's verdict"+ assert hw.CHAT_ONLY is False+ assert hw.DETECTION_COMPLETE.is_set(), "the restart was left reporting as unsettled"+ finally:+ hw.DEVICE, hw.CHAT_ONLY, hw.CHAT_ONLY_REASON, hw.IS_ROCM = saved+ hw.DETECTION_COMPLETE.set() if was_complete else hw.DETECTION_COMPLETE.clear()+++def test_a_retired_pass_that_did_detect_still_discards():+ """Negative control: the discard must still fire for a verdict this call produced."""+ from utils.hardware import hardware as hw++ saved = (hw.DEVICE, hw.CHAT_ONLY, hw.CHAT_ONLY_REASON, hw.IS_ROCM)+ was_complete = hw.DETECTION_COMPLETE.is_set()+ try:+ hw.DEVICE = None+ hw.DETECTION_COMPLETE.clear()+ epoch = hw.current_detection_epoch()++ def _detect_then_shutdown():+ hw.DEVICE = hw.DeviceType.CUDA+ hw.CHAT_ONLY = False+ hw.invalidate_detection() # shutdown lands inside the pass++ with mock.patch.object(hw, "_detect_hardware_locked", _detect_then_shutdown):+ hw.ensure_hardware_detected(epoch)++ assert hw.DEVICE is None, "a retired pass published its own verdict anyway"+ assert not hw.DETECTION_COMPLETE.is_set()+ finally:+ hw.DEVICE, hw.CHAT_ONLY, hw.CHAT_ONLY_REASON, hw.IS_ROCM = saved+ hw.DETECTION_COMPLETE.set() if was_complete else hw.DETECTION_COMPLETE.clear()+++def test_the_warm_hands_its_epoch_to_detection():+ """The pre-stage check is not enough on its own. Shutdown can land between that check and+ _DETECT_LOCK, inside the torch import the hardware stage is running, so detection+ reading the epoch itself would bind to the retirement it should lose to."""+ import utils.torch_warmup as warm+ from utils.hardware import hardware as hw_mod++ # Patch the MODULE function, not the name the stage imports: utils.hardware wraps it by+ # hand and patching the bound name hops over the wrapper, which is how one that dropped+ # the argument (raising into _run_stage on every boot) went unnoticed.+ seen: list = []+ with mock.patch.object(hw_mod, "ensure_hardware_detected", lambda e = None: seen.append(e)):+ warm._warm_hardware(41)+ assert seen == [41], f"the hardware stage dropped its epoch: {seen}"+++def test_every_public_hardware_wrapper_accepts_what_it_delegates_to():+ """utils.hardware wraps rather than re-exports, so signatures can drift apart. A wrapper+ narrower than its target raises TypeError at the call site, which _run_stage catches and+ logs, so the stage is skipped and nothing detects the hardware."""+ import inspect+ import utils.hardware as pkg+ from utils.hardware import hardware as hw_mod++ for name in (+ "ensure_hardware_detected",+ "detect_hardware",+ "start_background_detection",+ "export_capability",+ "get_device",+ ):+ wrapper = getattr(pkg, name, None)+ target = getattr(hw_mod, name, None)+ if wrapper is None or target is None or wrapper is target:+ continue # a genuine re-export cannot drift+ w = inspect.signature(wrapper).parameters+ t = inspect.signature(target).parameters+ assert set(t) <= set(w), (+ f"utils.hardware.{name} accepts {sorted(w)} but delegates to one taking "+ f"{sorted(t)}; a caller passing the extra argument raises TypeError"+ )+++def test_the_warm_loop_passes_the_epoch_to_the_real_stage_only():+ """_warm() must bind the epoch onto the real hardware stage, and only that one. A patched+ _STAGES entry is a different object, so it keeps the zero-argument contract every other+ stage and every test stub relies on."""+ import utils.torch_warmup as warm+ from utils.hardware import hardware as hw++ got: list = []++ def _hardware(epoch = None):+ got.append(("hardware", epoch))++ zero_arg_calls: list = []+ stages = (("hardware", _hardware), ("later", lambda: zero_arg_calls.append("later")))+ with mock.patch.object(warm, "_STAGES", stages):+ warm._warm(hw.current_detection_epoch())+ # _hardware is not warm._warm_hardware, so it is called with no arguments.+ assert got == [("hardware", None)], got+ assert zero_arg_calls == ["later"]++ # The real stage does get it: assert on the call the loop builds.+ tree = ast.parse((_BACKEND / "utils" / "torch_warmup.py").read_text(encoding = "utf-8"))+ fn = next(+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.FunctionDef) and node.name == "_warm"+ )+ assert any(+ isinstance(sub, ast.Call)+ and isinstance(sub.func, ast.Name)+ and sub.func.id == "partial"+ and any(isinstance(a, ast.Name) and a.id == "epoch" for a in sub.args)+ for sub in ast.walk(fn)+ ), "_warm no longer binds the epoch onto the hardware stage"+++def test_deleting_a_cached_model_does_not_construct_the_backend():+ """A metadata-only delete has no reason to import torch. Off-loop already, so this is not+ a stall; it is the kill switch defeated, and the warm window paying a torch import to+ answer "nothing loaded"."""+ tree = ast.parse(+ (_BACKEND / "hub" / "services" / "models" / "deletion.py").read_text(encoding = "utf-8")+ )+ fn = next(+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.FunctionDef) and node.name == "_inference_backend_blocks_delete"+ )+ assert not [+ sub+ for sub in ast.walk(fn)+ if isinstance(sub, ast.Call)+ and isinstance(sub.func, ast.Name)+ and sub.func.id == "get_inference_backend"+ ], "the delete guard constructs the ML backend to learn that nothing is loaded"+ assert any(+ isinstance(sub, ast.Call)+ and isinstance(sub.func, ast.Name)+ and sub.func.id == "peek_inference_backend"+ for sub in ast.walk(fn)+ ), "the delete guard no longer checks the loaded model at all"+++def test_the_delete_guard_lets_a_delete_through_when_nothing_is_loaded():+ """Behavioural: no orchestrator means no standard model, so nothing blocks."""+ import core.inference.orchestrator as orch+ from hub.services.models import deletion++ before = orch._inference_backend+ try:+ orch._inference_backend = None+ assert deletion._inference_backend_blocks_delete("unsloth/Qwen3.5-2B") is False+ assert orch._inference_backend is None, "the delete guard constructed an orchestrator"+ finally:+ orch._inference_backend = before+++def test_the_warm_epoch_is_retired_before_any_shutdown_await():+ """The coordinated warm has to be stopped at shutdown entry too. run_lifespan_shutdown()+ invalidates, but only after several awaits, and a warm running through those keeps+ building the inference backend and importing for a lifespan that has stopped."""+ tree = ast.parse((_BACKEND / "main.py").read_text(encoding = "utf-8"))+ fn = next(+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.AsyncFunctionDef) and node.name == "lifespan"+ )+ yield_line = next(sub.lineno for sub in ast.walk(fn) if isinstance(sub, ast.Yield))+ awaits_after = sorted(+ sub.lineno for sub in ast.walk(fn) if isinstance(sub, ast.Await) and sub.lineno > yield_line+ )+ assert awaits_after, "the shutdown path no longer awaits anything; re-derive this"+ # The call goes through a getattr-bound name, so match the binding, not an attribute call.+ retire_lines = [+ node.lineno+ for node in ast.walk(fn)+ if isinstance(node, ast.Assign)+ and any(+ isinstance(sub, ast.Call)+ and isinstance(sub.func, ast.Name)+ and sub.func.id == "getattr"+ and any(+ isinstance(a, ast.Constant) and a.value == "invalidate_detection" for a in sub.args+ )+ for sub in ast.walk(node.value)+ )+ and node.lineno > yield_line+ ]+ assert retire_lines, "shutdown never retires the warm's detection epoch itself"+ assert min(retire_lines) < awaits_after[0], (+ f"the epoch is retired at line {min(retire_lines)}, after the first shutdown "+ f"await at {awaits_after[0]}; the warm keeps importing through that gap"+ )+++def test_the_post_warm_worker_is_retired_before_any_shutdown_await():+ """It has to stop first, not merely early. Everything the post-warm worker does next loads+ part of the ML stack, including starting a llama-server, and a warm finishing during a+ later shutdown await would still read the lifespan as current and go ahead."""+ tree = ast.parse((_BACKEND / "main.py").read_text(encoding = "utf-8"))+ fn = next(+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.AsyncFunctionDef) and node.name == "lifespan"+ )+ body = fn.body++ def _lineno(pred):+ return next(sub.lineno for sub in ast.walk(fn) if pred(sub))++ yield_line = _lineno(lambda n: isinstance(n, ast.Yield))+ stop_line = _lineno(+ lambda n: isinstance(n, ast.Call)+ and isinstance(n.func, ast.Name)+ and n.func.id == "_stop_post_warm_thread"+ )+ awaits_after_yield = sorted(+ sub.lineno for sub in ast.walk(fn) if isinstance(sub, ast.Await) and sub.lineno > yield_line+ )+ assert stop_line > yield_line, "_stop_post_warm_thread must run on shutdown"+ assert awaits_after_yield, "the shutdown path no longer awaits anything; re-derive this"+ assert stop_line < awaits_after_yield[0], (+ f"_stop_post_warm_thread runs at line {stop_line}, after the first shutdown "+ f"await at {awaits_after_yield[0]}; a warm finishing in that gap starts "+ "post-warm work on a lifespan that is already shutting down"+ )+ assert body # the walk above only makes sense on a non-empty body+++def test_a_finished_warm_still_holds_the_latch_inside_its_own_lifespan():+ """Repeat calls stay no-ops however fast the warm ran.++ Treating any finished thread as absent is timing-dependent: with a trivial stage the+ warm can finish between two calls and the second starts a whole second warm (green on+ Linux, red on macOS). Only a warm whose epoch shutdown has retired is stale."""+ import utils.torch_warmup as warm++ saved_thread, saved_epoch = warm._thread, warm._thread_epoch+ saved_status = dict(warm._status)+ disable = os.environ.pop(warm.DISABLE_ENV_VAR, None)+ try:+ warm._thread, warm._thread_epoch = None, None+ warm._status.update({"started": False, "finished": False, "stages": {}})+ with mock.patch.object(warm, "_STAGES", (("noop", lambda: None),)):+ assert warm.start_background_warm() is True+ assert warm.join_background_warm(60) is True+ # Finished, same lifespan: still latched.+ assert (+ warm.start_background_warm() is False+ ), "a second warm started beside a completed one in the same lifespan"+ # Shutdown retires the epoch, as run_lifespan_shutdown does.+ from utils.hardware import hardware as hw++ hw.invalidate_detection()+ assert (+ warm.start_background_warm() is True+ ), "the next lifespan skipped its warm over hardware state shutdown cleared"+ assert warm.join_background_warm(60) is True+ finally:+ if disable is not None:+ os.environ[warm.DISABLE_ENV_VAR] = disable+ warm._thread, warm._thread_epoch = saved_thread, saved_epoch+ warm._status.clear()+ warm._status.update(saved_status)+++def test_an_offline_first_read_does_not_retire_the_ranking_fetch():+ """Claiming the latch before the offline check disables the fetch for the process: an+ offline boot or a force_hf_offline() scope then never picks the ranking up again."""+ tree = ast.parse(+ (_BACKEND / "core" / "inference" / "orchestrator.py").read_text(encoding = "utf-8")+ )+ fn = next(+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.FunctionDef) and node.name == "_start_top_models_fetch"+ )+ offline_line = next(+ sub.lineno+ for sub in ast.walk(fn)+ if isinstance(sub, ast.Call)+ and isinstance(sub.func, ast.Name)+ and sub.func.id == "hf_env_offline"+ )+ claim_line = next(+ node.lineno+ for node in ast.walk(fn)+ if isinstance(node, ast.Assign)+ and any(+ isinstance(t, ast.Attribute) and t.attr == "_top_models_started" for t in node.targets+ )+ and isinstance(node.value, ast.Constant)+ and node.value.value is True+ )+ assert offline_line < claim_line, (+ f"the latch is claimed at line {claim_line}, before the offline check at "+ f"{offline_line}; an offline first read then retires the fetch permanently"+ )+++def test_an_offline_read_leaves_the_fetch_available():+ """Behavioural: offline must not consume the one-shot start."""+ import core.inference.orchestrator as orch++ started = []+ backend = orch.InferenceOrchestrator.__new__(orch.InferenceOrchestrator)+ backend._top_models_started = False+ with mock.patch.object(orch, "hf_env_offline", lambda: True):+ backend._start_top_models_fetch()+ assert (+ backend._top_models_started is False+ ), "an offline read consumed the latch, so the ranking can never be fetched again"+ with mock.patch.object(orch, "hf_env_offline", lambda: False):+ with mock.patch.object(orch.threading, "Thread") as thread:+ thread.side_effect = lambda **kw: started.append(kw) or mock.MagicMock()+ backend._start_top_models_fetch()+ assert (+ backend._top_models_started is True and started+ ), "coming back online did not start the fetch"+++def test_a_slow_refresh_cannot_overwrite_a_newer_default_list():+ """Two readers refreshing different generations must not commit out of order. An MLX+ repair plus a repeated lifespan gives several generations, and a reader that started+ earlier can finish later, leaving its stale list looking current for good."""+ import core.inference.orchestrator as orch+ import utils.hardware.hardware as hw_mod++ backend = orch.InferenceOrchestrator.__new__(orch.InferenceOrchestrator)+ backend._static_models_lock = threading.Lock()+ backend._static_models = ["gen0"]+ backend._static_models_generation = 0++ saved_generation = hw_mod.DETECTION_GENERATION+ try:+ # The newer reader has already committed generation 2.+ hw_mod.DETECTION_GENERATION = 2+ with mock.patch("core.inference.defaults.get_default_models", lambda: ["gen2"]):+ backend._refresh_static_models_if_stale()+ assert backend._static_models == ["gen2"]+ assert backend._static_models_generation == 2++ # Now the slow reader from generation 1 finishes and tries to commit.+ hw_mod.DETECTION_GENERATION = 1+ backend._static_models_generation_before = backend._static_models_generation+ with mock.patch("core.inference.defaults.get_default_models", lambda: ["gen1"]):+ backend._refresh_static_models_if_stale()+ assert backend._static_models == [+ "gen2"+ ], "an older reader overwrote the newer default list"+ assert backend._static_models_generation == 2+ finally:+ hw_mod.DETECTION_GENERATION = saved_generation+++def test_a_refresh_whose_generation_moved_mid_build_does_not_commit():+ """A list built against a generation that has since advanced is already stale."""+ import core.inference.orchestrator as orch+ import utils.hardware.hardware as hw_mod++ backend = orch.InferenceOrchestrator.__new__(orch.InferenceOrchestrator)+ backend._static_models_lock = threading.Lock()+ backend._static_models = ["old"]+ backend._static_models_generation = 1++ saved_generation = hw_mod.DETECTION_GENERATION+ try:+ hw_mod.DETECTION_GENERATION = 2++ def _slow_build():+ hw_mod.DETECTION_GENERATION = 3 # a re-detection lands mid-build+ return ["built-against-2"]++ with mock.patch("core.inference.defaults.get_default_models", _slow_build):+ backend._refresh_static_models_if_stale()+ assert backend._static_models == ["old"], "a list built against a retired generation landed"+ assert (+ backend._static_models_generation == 1+ ), "the stamp moved without the value, so the next read would not refresh"+ finally:+ hw_mod.DETECTION_GENERATION = saved_generation+++def test_an_ordinary_refresh_still_happens():+ """Negative control: a single reader on a newer generation must still refresh."""+ import core.inference.orchestrator as orch+ import utils.hardware.hardware as hw_mod++ backend = orch.InferenceOrchestrator.__new__(orch.InferenceOrchestrator)+ backend._static_models_lock = threading.Lock()+ backend._static_models = ["old"]+ backend._static_models_generation = 1++ saved_generation = hw_mod.DETECTION_GENERATION+ try:+ hw_mod.DETECTION_GENERATION = 2+ with mock.patch("core.inference.defaults.get_default_models", lambda: ["new"]):+ backend._refresh_static_models_if_stale()+ assert backend._static_models == ["new"]+ assert backend._static_models_generation == 2+ finally:+ hw_mod.DETECTION_GENERATION = saved_generation+++def test_a_retired_worker_does_not_probe_before_being_discarded():+ """Discarding after the probe still pays for the probe. A health-triggered thread can reach+ _DETECT_LOCK after shutdown retired its epoch; probing there imports the ML stack for a+ stopped lifespan, and the next warm queues on the same lock only to detect again."""+ from utils.hardware import hardware as hw++ saved = (hw.DEVICE, hw.CHAT_ONLY, hw.CHAT_ONLY_REASON, hw.IS_ROCM)+ was_complete = hw.DETECTION_COMPLETE.is_set()+ try:+ hw.DEVICE = None+ hw.DETECTION_COMPLETE.clear()+ stale_epoch = hw.current_detection_epoch()+ hw.invalidate_detection() # shutdown, before the worker gets the lock++ probed = []+ with mock.patch.object(hw, "_detect_hardware_locked", lambda: probed.append(1)):+ hw.ensure_hardware_detected(stale_epoch)++ assert probed == [], "a retired worker imported the ML stack anyway"+ assert hw.DEVICE is None+ assert not hw.DETECTION_COMPLETE.is_set()+ finally:+ hw.DEVICE, hw.CHAT_ONLY, hw.CHAT_ONLY_REASON, hw.IS_ROCM = saved+ hw.DETECTION_COMPLETE.set() if was_complete else hw.DETECTION_COMPLETE.clear()+++def test_a_live_worker_still_probes():+ """Negative control: an owner of the current epoch must detect as before."""+ from utils.hardware import hardware as hw++ saved = (hw.DEVICE, hw.CHAT_ONLY, hw.CHAT_ONLY_REASON, hw.IS_ROCM)+ was_complete = hw.DETECTION_COMPLETE.is_set()+ try:+ hw.DEVICE = None+ hw.DETECTION_COMPLETE.clear()+ probed = []++ def _probe():+ probed.append(1)+ hw.DEVICE = hw.DeviceType.CUDA++ with mock.patch.object(hw, "_detect_hardware_locked", _probe):+ hw.ensure_hardware_detected(hw.current_detection_epoch())++ assert probed == [1], "a live worker was refused its probe"+ assert hw.DETECTION_COMPLETE.is_set()+ finally:+ hw.DEVICE, hw.CHAT_ONLY, hw.CHAT_ONLY_REASON, hw.IS_ROCM = saved+ hw.DETECTION_COMPLETE.set() if was_complete else hw.DETECTION_COMPLETE.clear()+++def test_a_measured_authed_reply_drops_both_provisional_markers():+ """AST: publishing a measurement must clear the deferred marker too.++ With the kill switch on, base carries both markers. When a detection finishing during+ the bearer await makes the snapshot measured, a left-over hardware_detection_deferred+ pairs an accelerator verdict with a stale reason: the client reads that marker first."""+ tree = ast.parse((_BACKEND / "main.py").read_text(encoding = "utf-8"))+ fn = next(+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.AsyncFunctionDef) and node.name == "health_check"+ )+ branch = next(+ node+ for node in ast.walk(fn)+ if isinstance(node, ast.If)+ and any(+ isinstance(sub, ast.Subscript)+ and isinstance(sub.value, ast.Name)+ and sub.value.id == "authed"+ and getattr(sub.slice, "value", None) == "device_type"+ for sub in ast.walk(node)+ )+ )+ popped = {+ sub.args[0].value+ for sub in ast.walk(branch)+ if isinstance(sub, ast.Call)+ and isinstance(sub.func, ast.Attribute)+ and sub.func.attr == "pop"+ and isinstance(sub.func.value, ast.Name)+ and sub.func.value.id == "authed"+ and sub.args+ and isinstance(sub.args[0], ast.Constant)+ }+ assert {+ "hardware_detecting",+ "hardware_detection_deferred",+ } <= popped, f"the measured reply still carries a provisional marker; popped {sorted(popped)}"+++# ------------------------------ a shutdown inside a stage, not between two of them+def test_a_shutdown_inside_a_stage_cannot_republish_the_torn_down_verdict():+ """The stage-boundary checks miss a shutdown that lands mid-stage.++ _warm_inference_backend builds the orchestrator, whose constructor reaches+ get_default_models() -> get_device(), and get_device() takes no epoch. A shutdown after+ the pre-stage check but before that nested read used to let it adopt the epoch it was+ retiring into and publish DEVICE, so the next lifespan skipped detection altogether."""+ from utils.hardware import hardware as hw++ saved = (hw.DEVICE, hw.CHAT_ONLY, hw.CHAT_ONLY_REASON, hw.IS_ROCM)+ was_complete = hw.DETECTION_COMPLETE.is_set()+ try:+ hw.DEVICE = None+ hw.DETECTION_COMPLETE.clear()+ warm_epoch = hw.current_detection_epoch()++ def _probe():+ hw.DEVICE = hw.DeviceType.CUDA+ hw.CHAT_ONLY = False++ # Inside the warm's scope, standing in for the orchestrator constructor.+ with hw.owning_detection_epoch(warm_epoch):+ hw.invalidate_detection() # shutdown lands mid-stage+ with mock.patch.object(hw, "_detect_hardware_locked", _probe):+ hw.get_device()++ assert hw.DEVICE is None, (+ "a nested read inside a retired stage republished DEVICE after teardown; "+ "the next lifespan skips detection and serves the old verdict"+ )+ assert not hw.DETECTION_COMPLETE.is_set()+ finally:+ hw.DEVICE, hw.CHAT_ONLY, hw.CHAT_ONLY_REASON, hw.IS_ROCM = saved+ hw.DETECTION_COMPLETE.set() if was_complete else hw.DETECTION_COMPLETE.clear()+++def test_a_nested_read_in_a_live_stage_still_publishes():+ """Negative control: without a shutdown the scope changes nothing."""+ from utils.hardware import hardware as hw++ saved = (hw.DEVICE, hw.CHAT_ONLY, hw.CHAT_ONLY_REASON, hw.IS_ROCM)+ was_complete = hw.DETECTION_COMPLETE.is_set()+ try:+ hw.DEVICE = None+ hw.DETECTION_COMPLETE.clear()++ def _probe():+ hw.DEVICE = hw.DeviceType.CUDA++ with hw.owning_detection_epoch(hw.current_detection_epoch()):+ with mock.patch.object(hw, "_detect_hardware_locked", _probe):+ hw.get_device()++ assert hw.DEVICE is hw.DeviceType.CUDA, "the scope discarded a live verdict"+ assert hw.DETECTION_COMPLETE.is_set()+ finally:+ hw.DEVICE, hw.CHAT_ONLY, hw.CHAT_ONLY_REASON, hw.IS_ROCM = saved+ hw.DETECTION_COMPLETE.set() if was_complete else hw.DETECTION_COMPLETE.clear()+++def test_the_scope_is_per_thread_and_restores_what_it_replaced():+ """Nested, and invisible to other threads: an unrelated caller must not inherit it."""+ from utils.hardware import hardware as hw++ seen: dict = {}++ def _other() -> None:+ seen["value"] = getattr(hw._OWNING_EPOCH, "value", None)++ with hw.owning_detection_epoch(11):+ with hw.owning_detection_epoch(22):+ assert hw._OWNING_EPOCH.value == 22+ assert hw._OWNING_EPOCH.value == 11, "the inner scope did not restore the outer"+ thread = threading.Thread(target = _other)+ thread.start()+ thread.join()++ assert seen["value"] is None, "another thread inherited the warm's owning epoch"+ assert getattr(hw._OWNING_EPOCH, "value", None) is None+++def test_the_warm_runs_its_stages_inside_an_owning_scope():+ """AST: the guard is the scope around the loop, not any one stage. A future stage that+ reaches hardware some other way is covered only while the loop body stays inside it."""+ tree = ast.parse((_BACKEND / "utils" / "torch_warmup.py").read_text(encoding = "utf-8"))+ warm = next(+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.FunctionDef) and node.name == "_warm"+ )+ scoped = [+ node+ for node in warm.body+ if isinstance(node, ast.With)+ and any(+ isinstance(item.context_expr, ast.Call)+ and getattr(item.context_expr.func, "id", None) == "_owning_epoch"+ for item in node.items+ )+ ]+ assert scoped, "_warm no longer runs its stages inside _owning_epoch()"+ assert any(+ isinstance(node, ast.For) for node in scoped[0].body+ ), "the stage loop moved out of the owning scope"+++# ------------------------------- the MLX self-heal is a background worker too+def test_the_mlx_self_heal_cannot_republish_into_a_stopped_lifespan():+ """attempt_mlx_repair() is a pip install; shutdown can land anywhere inside it.++ detect_hardware() guards a shutdown landing mid-pass but read current itself, so a+ repair finishing after teardown adopted the epoch shutdown moved to and published for a+ lifespan that had ended. The next lifespan then found DEVICE set and skipped detection."""+ from utils.hardware import hardware as hw++ saved = (hw.DEVICE, hw.CHAT_ONLY, hw.CHAT_ONLY_REASON, hw.IS_ROCM)+ was_complete = hw.DETECTION_COMPLETE.is_set()+ try:+ hw.DEVICE = None+ hw.DETECTION_COMPLETE.clear()+ spawn_epoch = hw.current_detection_epoch()++ def _probe():+ hw.DEVICE = hw.DeviceType.MLX+ hw.CHAT_ONLY = False+ return hw.DEVICE++ hw.invalidate_detection() # shutdown, while the pip install was running+ with hw.owning_detection_epoch(spawn_epoch):+ with mock.patch.object(hw, "_detect_hardware_locked", _probe):+ hw.detect_hardware()++ assert hw.DEVICE is None, (+ "the MLX self-heal republished a verdict after teardown; the next "+ "lifespan skips detection and inherits it"+ )+ assert not hw.DETECTION_COMPLETE.is_set()+ finally:+ hw.DEVICE, hw.CHAT_ONLY, hw.CHAT_ONLY_REASON, hw.IS_ROCM = saved+ hw.DETECTION_COMPLETE.set() if was_complete else hw.DETECTION_COMPLETE.clear()+++def test_a_forced_redetect_with_no_shutdown_still_publishes():+ """Negative control: detect_hardware keeps working outside a retired scope."""+ from utils.hardware import hardware as hw++ saved = (hw.DEVICE, hw.CHAT_ONLY, hw.CHAT_ONLY_REASON, hw.IS_ROCM)+ was_complete = hw.DETECTION_COMPLETE.is_set()+ try:+ hw.DEVICE = None+ hw.DETECTION_COMPLETE.clear()++ def _probe():+ hw.DEVICE = hw.DeviceType.MLX+ return hw.DEVICE++ with hw.owning_detection_epoch(hw.current_detection_epoch()):+ with mock.patch.object(hw, "_detect_hardware_locked", _probe):+ hw.detect_hardware()++ assert hw.DEVICE is hw.DeviceType.MLX, "a live self-heal was discarded"+ assert hw.DETECTION_COMPLETE.is_set()+ finally:+ hw.DEVICE, hw.CHAT_ONLY, hw.CHAT_ONLY_REASON, hw.IS_ROCM = saved+ hw.DETECTION_COMPLETE.set() if was_complete else hw.DETECTION_COMPLETE.clear()+++def test_the_mlx_worker_reads_its_epoch_before_start():+ """Same spawn-time rule as the other workers: start() may not run for a while."""+ import utils.mlx_repair as repair++ captured: dict = {}++ class _Recorder:+ def __init__(self, *args, **kwargs):+ captured["args"] = kwargs.get("args", ())+ captured["target"] = kwargs.get("target")++ def start(self):+ captured["started"] = True++ with mock.patch.object(repair.threading, "Thread", _Recorder):+ with mock.patch.object(repair, "is_apple_silicon", lambda: True):+ with mock.patch.object(repair, "mlx_stack_available", lambda: False):+ with mock.patch.dict(os.environ, {}, clear = False):+ os.environ.pop(repair.DISABLE_ENV_VAR, None)+ repair._attempted = False+ repair.start_mlx_autorepair_if_needed()++ assert captured.get("started"), "the self-heal never spawned"+ assert captured["args"], (+ "the MLX worker is spawned with no epoch, so it reads one after start() and "+ "binds itself to whatever shutdown moved to"+ )+++# ------------------------------------------- the purge reports what it actually did+def test_an_interrupted_purge_reports_only_what_it_removed():+ """Returning the whole plan makes the warm claim a clean slate it did not deliver. The loop+ bails correctly when another importer republishes the parent, but the log and the return+ value used to describe every submodule it had intended to drop."""+ from utils import torch_warmup++ package = "unsloth_purge_probe"+ names = [f"{package}.{leaf}" for leaf in ("a", "b", "c")]++ class _RacingModules(dict):+ """sys.modules where another importer republishes the parent after one pop."""++ def pop(+ self,+ key,+ default = None,+ ):+ result = super().pop(key, default)+ self.setdefault(package, types.ModuleType(package))+ return result++ fake = _RacingModules({name: types.ModuleType(name) for name in names})++ with mock.patch.object(torch_warmup, "sys", types.SimpleNamespace(modules = fake)):+ removed = torch_warmup.purge_partial_import(package)++ assert len(removed) < len(names), (+ f"an interrupted purge reported {len(removed)} of {len(names)} submodules as "+ "removed; the warm claims the next import will be clean when it will not"+ )+ for name in removed:+ assert name not in fake, f"{name} was reported removed but is still present"+ assert [name for name in names if name in fake], "the purge did not actually stop"+++def test_a_late_repair_cannot_erase_the_restarted_lifespans_verdict():+ """A stale forced pass must bail before it touches anything.++ detect_hardware() clears DETECTION_COMPLETE, probes, then discards when the epoch moved.+ Reached with an already-stale owning epoch, that runs over a verdict the restarted+ lifespan had settled: the discard wipes DEVICE and the event, so it goes provisional."""+ from utils.hardware import hardware as hw++ saved = (hw.DEVICE, hw.CHAT_ONLY, hw.CHAT_ONLY_REASON, hw.IS_ROCM)+ was_complete = hw.DETECTION_COMPLETE.is_set()+ try:+ stale_epoch = hw.current_detection_epoch()+ hw.invalidate_detection() # the restart++ # The new lifespan has already measured and published.+ hw.DEVICE = hw.DeviceType.CUDA+ hw.CHAT_ONLY = False+ hw.CHAT_ONLY_REASON = None+ hw.DETECTION_COMPLETE.set()++ probed = []+ with hw.owning_detection_epoch(stale_epoch):+ with mock.patch.object(hw, "_detect_hardware_locked", lambda: probed.append(1)):+ hw.detect_hardware()++ assert probed == [], "a retired repair probed anyway, importing MLX for a dead lifespan"+ assert hw.DEVICE is hw.DeviceType.CUDA, (+ "a late MLX repair erased the restarted lifespan's verdict; the new lifespan "+ "drops back to provisional and re-detects"+ )+ assert hw.CHAT_ONLY is False+ assert hw.DETECTION_COMPLETE.is_set(), "the settled event was cleared by a stale pass"+ finally:+ hw.DEVICE, hw.CHAT_ONLY, hw.CHAT_ONLY_REASON, hw.IS_ROCM = saved+ hw.DETECTION_COMPLETE.set() if was_complete else hw.DETECTION_COMPLETE.clear()+++def test_a_repair_that_outlived_its_lifespan_still_reopens_train():+ """Declining the stale pass must not leave a repaired Mac chat-only for good. The install+ succeeded, so the running lifespan holds a verdict measured before mlx existed;+ _attempted is process-wide so no later repair revisits it, and health only reads the+ settled snapshot. Train and Export stay disabled until a restart."""+ import utils.mlx_repair as repair+ from utils.hardware import hardware as hw++ saved = (hw.DEVICE, hw.CHAT_ONLY, hw.CHAT_ONLY_REASON, hw.IS_ROCM)+ was_complete = hw.DETECTION_COMPLETE.is_set()+ try:+ spawn_epoch = hw.current_detection_epoch()+ hw.invalidate_detection() # the restart, while the install was still running++ # The successor measured before mlx landed and published chat-only.+ hw.DEVICE = hw.DeviceType.CPU+ hw.CHAT_ONLY = True+ hw.CHAT_ONLY_REASON = "mlx_unavailable"+ hw.DETECTION_COMPLETE.set()++ def _probe_now_that_mlx_works():+ hw.DEVICE = hw.DeviceType.MLX+ hw.CHAT_ONLY = False+ hw.CHAT_ONLY_REASON = None+ return hw.DEVICE++ with mock.patch.object(repair, "attempt_mlx_repair", lambda: True):+ with mock.patch.object(hw, "_detect_hardware_locked", _probe_now_that_mlx_works):+ repair._run_repair_and_redetect(spawn_epoch)++ assert hw.CHAT_ONLY is False, (+ "a successful repair that outlived its lifespan left the running one "+ "chat-only; Train and Export stay disabled until the process restarts"+ )+ assert hw.DEVICE is hw.DeviceType.MLX+ assert hw.CHAT_ONLY_REASON is None+ finally:+ hw.DEVICE, hw.CHAT_ONLY, hw.CHAT_ONLY_REASON, hw.IS_ROCM = saved+ hw.DETECTION_COMPLETE.set() if was_complete else hw.DETECTION_COMPLETE.clear()+++def test_a_cached_path_pass_does_not_publish_its_own_intermediate_state():+ """ensure_hardware_detected must clear the event before it mutates the globals.++ Shutdown clears DEVICE, a cached waiter then sets the event, and the next pass starts+ with the event set and DEVICE None. Every accelerator branch assigns CHAT_ONLY = False+ before a probe that can fall back to CPU, so health reads that candidate as settled."""+ from utils.hardware import hardware as hw++ saved = (hw.DEVICE, hw.CHAT_ONLY, hw.CHAT_ONLY_REASON, hw.IS_ROCM)+ was_complete = hw.DETECTION_COMPLETE.is_set()+ try:+ hw.DEVICE = None+ hw.CHAT_ONLY = True+ hw.DETECTION_COMPLETE.set() # the stale event++ seen = {}++ def _probe():+ # Mid-pass, exactly where the XPU branch sits before get_device_name().+ hw.DEVICE = hw.DeviceType.XPU+ hw.CHAT_ONLY = False+ seen["event_during_pass"] = hw.DETECTION_COMPLETE.is_set()+ return hw.DEVICE++ with mock.patch.object(hw, "_detect_hardware_locked", _probe):+ hw.ensure_hardware_detected()++ assert seen["event_during_pass"] is False, (+ "the completion event stayed set while the pass was mutating DEVICE and "+ "CHAT_ONLY, so health can serve the first candidate as a measurement"+ )+ assert hw.DETECTION_COMPLETE.is_set(), "the event was not republished once settled"+ finally:+ hw.DEVICE, hw.CHAT_ONLY, hw.CHAT_ONLY_REASON, hw.IS_ROCM = saved+ hw.DETECTION_COMPLETE.set() if was_complete else hw.DETECTION_COMPLETE.clear()diff --git a/studio/backend/utils/datasets/raw_text.py b/studio/backend/utils/datasets/raw_text.pyindex 112528fdd0b..a30eed953e6 100644--- a/studio/backend/utils/datasets/raw_text.py+++ b/studio/backend/utils/datasets/raw_text.py@@ -3,10 +3,15 @@"""Shared helpers for raw-text dataset preparation."""+# `Dataset` is annotation-only: a module-scope `datasets` import drags torch in via+# datasets.formatting.torch_formatter.+from __future__ import annotations+from dataclasses import dataclass-from typing import Literal+from typing import Literal, TYPE_CHECKING-from datasets import Dataset+if TYPE_CHECKING:+ from datasets import Dataset@dataclass(frozen = True)diff --git a/studio/backend/utils/hardware/__init__.py b/studio/backend/utils/hardware/__init__.pyindex 72e768a799f..4195d0c680d 100644--- a/studio/backend/utils/hardware/__init__.py+++ b/studio/backend/utils/hardware/__init__.py@@ -3,6 +3,8 @@"""Hardware detection and GPU utilities."""+from typing import Optional+from . import hardware as _hardwarefrom .hardware import (DeviceType,@@ -46,6 +48,21 @@ from .vram_estimation import ()+def ensure_hardware_detected(epoch: Optional[int] = None) -> DeviceType:+ """Detect once, from any thread; delegate so the live function always runs.++ Wrapper rather than re-export, like export_capability() below: a re-export is an unused+ module-level import, which scripts/verify_import_hoist.py flags. Must carry the epoch --+ dropping it raises into the warm's _run_stage, leaving detection undone.+ """+ return _hardware.ensure_hardware_detected(epoch)+++def start_background_detection() -> None:+ """Put detection on a daemon thread if nothing is running it yet."""+ _hardware.start_background_detection()++def export_capability() -> dict:"""Return live export capability from the hardware module."""return _hardware.export_capability()@@ -62,6 +79,8 @@ __all__ = ["CHAT_ONLY","IS_ROCM","detect_hardware",+ "ensure_hardware_detected",+ "start_background_detection","get_device","export_capability","is_apple_silicon",diff --git a/studio/backend/utils/hardware/hardware.py b/studio/backend/utils/hardware/hardware.pyindex 831bd6ca82a..d511a0a7fe3 100644--- a/studio/backend/utils/hardware/hardware.py+++ b/studio/backend/utils/hardware/hardware.py@@ -24,7 +24,9 @@ import platformimport reimport subprocessimport sys+import threadingimport types+from contextlib import contextmanagerfrom importlib.metadata import PackageNotFoundError, version as pkg_versionimport structlogfrom loggers import get_logger@@ -78,6 +80,103 @@ CHAT_ONLY: bool = True # No CUDA GPU -> GGUF chat only (Mac, CPU-only, etc.)CHAT_ONLY_REASON: Optional[str] = NoneIS_ROCM: bool = False # True when running on AMD ROCm (HIP) -- routes GPU monitoring to amd.py+# Detection has concurrent callers (the warm thread plus any early get_device()).+# Unlocked, two runs interleave on the globals above and a reader between the reset and+# the CUDA branch sees "chat only" on a GPU host. Re-entrant: get_device() nests.+_DETECT_LOCK = threading.RLock()++# Bumped by shutdown so a detection still inside the torch import cannot publish over+# the reset, leaving the next lifespan a non-None DEVICE that makes it skip detection.+# An epoch, not _DETECT_LOCK: taking that lock would park teardown behind the import.+_EPOCH_LOCK = threading.Lock()+DETECTION_EPOCH = 0+++def invalidate_detection() -> int:+ """Retire any detection in flight. Returns the new epoch."""+ global DETECTION_EPOCH+ with _EPOCH_LOCK:+ DETECTION_EPOCH += 1+ return DETECTION_EPOCH+++def current_detection_epoch() -> int:+ with _EPOCH_LOCK:+ return DETECTION_EPOCH+++# The epoch nested detections on this thread belong to. get_device() takes no epoch and+# the warm builds the orchestrator, whose constructor reaches it; without this a shutdown+# mid-stage lets the nested pass republish DEVICE over the teardown, so the next lifespan+# skips detection. Thread-local, so only the warm's own call stack is bound.+_OWNING_EPOCH = threading.local()+++@contextmanager+def owning_detection_epoch(epoch: Optional[int]):+ """Bind epoch-less detections on this thread to ``epoch`` for the block. Nested, not+ assigned: restoring the previous value keeps concurrent scopes on other threads apart."""+ previous = getattr(_OWNING_EPOCH, "value", None)+ _OWNING_EPOCH.value = epoch+ try:+ yield+ finally:+ _OWNING_EPOCH.value = previous+++def _discard_detection_locked() -> None:+ """Drop a verdict produced for an epoch that has been retired."""+ global DEVICE, CHAT_ONLY, CHAT_ONLY_REASON, IS_ROCM+ DEVICE = None+ CHAT_ONLY = True+ CHAT_ONLY_REASON = None+ IS_ROCM = False+ DETECTION_COMPLETE.clear()+++# Set once detection has a settled answer, including its CPU/chat-only fallback. Poll+# this, not DEVICE: DEVICE is assigned mid-detection and can be revised.+DETECTION_COMPLETE = threading.Event()+# Bumped every time detection settles. Detection is not once-per-process (the MLX+# self-heal re-detects and flips CHAT_ONLY), so snapshot holders can spot staleness.+DETECTION_GENERATION = 0++# Drives start_background_detection(). Separate from _DETECT_LOCK: never held across the import.+_DETECT_KICK_LOCK = threading.Lock()+_DETECT_THREAD: Optional[threading.Thread] = None+++def start_background_detection() -> None:+ """Run detection on a daemon thread if nothing is running it yet.++ For callers on a deadline that cannot await ensure_hardware_detected(), such as+ /api/health under the launcher's 2s timeout. They poll DEVICE against their own budget;+ this guarantees someone is filling it in even when the warm is past its hardware stage+ or a shutdown cleared the verdict. Callers skip it under+ UNSLOTH_STUDIO_DISABLE_TORCH_WARM=1, which means no background import at all.++ At most one thread, and none once DEVICE is set, so a route polling "still detecting"+ cannot pile them up. Not the asyncio executor: a to_thread outliving its awaiter holds+ a slot, and a polled endpoint would exhaust the pool during a slow import.+ """+ global _DETECT_THREAD+ if DEVICE is not None:+ return+ with _DETECT_KICK_LOCK:+ if DEVICE is not None:+ return+ if _DETECT_THREAD is not None and _DETECT_THREAD.is_alive():+ return+ # Epoch read before start(): the thread can be scheduled after a shutdown+ # retires this epoch, and it must lose to that, not adopt it.+ _DETECT_THREAD = threading.Thread(+ target = ensure_hardware_detected,+ args = (current_detection_epoch(),),+ daemon = True,+ name = "hardware-detect",+ )+ _DETECT_THREAD.start()+def _backend_label(device: DeviceType) -> str:"""Return the user-facing backend name for API responses.@@ -98,12 +197,41 @@ def is_apple_silicon() -> bool:return platform.system() == "Darwin" and platform.machine() == "arm64"+# Set by _has_torch() when torch is installed but its import blew up (unresolved CUDA+# libs). The CPU fallback reports that as a detection failure, not as "no GPU".+TORCH_IMPORT_ERROR: Optional[str] = None++def _has_torch() -> bool:- """True if PyTorch is importable."""+ """True if PyTorch is importable.++ Any failure counts as "no torch", not just ImportError: ensure_hardware_detected()+ re-runs while DEVICE is None, so an escaping OSError would make every request retry the+ import. Take the CPU path, but record the error, or the host is told to install the+ torch it already has.+ """+ global TORCH_IMPORT_ERRORtry:import torch+ TORCH_IMPORT_ERROR = Nonereturn True- except ImportError:+ except Exception as exc:+ # ImportError does NOT mean "not installed": a wheel with unresolved native libs+ # raises it from torch's own __init__ (OSError on Windows). Only ModuleNotFoundError+ # naming torch itself is absent; a failed submodule is a broken install. Both purge.+ absent = isinstance(exc, ModuleNotFoundError) and exc.name == "torch"+ TORCH_IMPORT_ERROR = None if absent else repr(exc)+ if TORCH_IMPORT_ERROR is not None:+ logger.error("torch is installed but failed to import: %r", exc)+ # A part-way failure leaves submodules cached under an evicted parent, so the next+ # importer gets a torch missing pieces. purge_partial_import() clears that.+ try:+ from utils.torch_warmup import purge_partial_import+ except Exception:+ # Also exec'd standalone (tests/python/test_e2e_no_torch_sandbox.py); nothing to purge.+ pass+ else:+ purge_partial_import("torch")return False@@ -185,13 +313,123 @@ def detect_hardware() -> DeviceType:4. MLX (Apple Silicon via MLX framework)5. CPU (fallback)"""+ global DEVICE, CHAT_ONLY, CHAT_ONLY_REASON, IS_ROCM, DETECTION_GENERATION+ with _DETECT_LOCK:+ # A forced pass mutates the globals partway through; leaving the event set lets+ # /api/health serve that as settled, so the sidebar MLX poll caches reason=None,+ # stops, and leaves Train hidden on a repaired host. Republished once it settles.+ was_complete = DETECTION_COMPLETE.is_set()+ # Snapshot the whole verdict, not just the event: a raise mid-pass leaves a+ # half-written answer the autorepair path swallows, and losing "mlx_unavailable"+ # stops the sidebar poll for good.+ published = (DEVICE, CHAT_ONLY, CHAT_ONLY_REASON, IS_ROCM)+ # Owning epoch first, current only as a fallback. The MLX self-heal calls this+ # after a pip install that can outlast the lifespan; reading current would adopt+ # the epoch shutdown moved to, so the next lifespan finds DEVICE set and skips+ # its own detection.+ epoch = getattr(_OWNING_EPOCH, "value", None)+ if epoch is None:+ epoch = current_detection_epoch()+ elif current_detection_epoch() != epoch:+ # Retired before this pass began, so leave the running lifespan alone. Going on+ # would clear DETECTION_COMPLETE over a settled verdict, probe, then discard: a+ # late repair would erase the restart's verdict, not merely fail to add its own.+ return DEVICE+ DETECTION_COMPLETE.clear()+ try:+ device = _detect_hardware_locked()+ except BaseException:+ if current_detection_epoch() != epoch:+ # Shutdown ran mid-pass. Restoring would put back the verdict it just+ # cleared, and the next lifespan would treat that as measured.+ _discard_detection_locked()+ raise+ DEVICE, CHAT_ONLY, CHAT_ONLY_REASON, IS_ROCM = published+ # Restore rather than leave it clear: start_background_detection() declines+ # once DEVICE is set, so an unset event keeps health provisional forever.+ if was_complete:+ DETECTION_COMPLETE.set()+ raise+ if current_detection_epoch() != epoch:+ # Shutdown ran mid-pass; this verdict belongs to a lifespan that ended.+ _discard_detection_locked()+ return device+ DETECTION_GENERATION += 1+ DETECTION_COMPLETE.set()+ return device+++def ensure_hardware_detected(epoch: Optional[int] = None) -> DeviceType:+ """Detect once, from any thread. Prefer this to detect_hardware() unless you want a+ forced re-detect: it collapses the warm thread and an early request into one pass, and+ a caller arriving mid-detection waits rather than starts a second.++ Never raises. A raise on the warm thread is swallowed and leaves DEVICE None, so every+ later request retries the failing import and /api/health, which waits on this, would+ 500. Record CPU + chat-only with a reason instead.++ ``epoch`` is the epoch this pass belongs to; a spawner passes the one it read before+ Thread.start(), since the thread can be scheduled after a shutdown retired it and+ reading it here would bind the pass to the retirement it must lose to. Direct callers+ pass nothing and own the current epoch."""+ global DEVICE, CHAT_ONLY, CHAT_ONLY_REASON, DETECTION_GENERATION+ with _DETECT_LOCK:+ if epoch is None:+ # A nested read inside an owning scope belongs to that pass, not to whatever+ # is current by the time it reaches here. See owning_detection_epoch().+ epoch = getattr(_OWNING_EPOCH, "value", None)+ if epoch is None:+ epoch = current_detection_epoch()+ elif DEVICE is None and current_detection_epoch() != epoch:+ # Retired before this worker reached the lock. Probing would import torch for a+ # stopped lifespan and the next warm would queue behind it only to re-detect.+ # Mid-probe shutdown: below.+ return DEVICE+ produced_here = DEVICE is None+ if produced_here:+ # Same reason detect_hardware() clears it: the pass below assigns DEVICE and+ # CHAT_ONLY before probes that can still fall back to CPU. A stale set event+ # (shutdown cleared DEVICE while a cached waiter went on to set it) would+ # publish the XPU candidate as settled. Republished below once final.+ DETECTION_COMPLETE.clear()+ try:+ _detect_hardware_locked()+ except BaseException as exc: # noqa: BLE001 - degrade, never 500 the health check+ logger.error("Hardware detection failed; falling back to CPU: %r", exc)+ DEVICE = DeviceType.CPU+ CHAT_ONLY = True+ CHAT_ONLY_REASON = "detection_failed"+ # Inside the branch: the orchestrator rebuilds its curated defaults whenever this+ # counter moves, so bumping on the cached path caused needless rebuilds. Forced+ # detect_hardware() bumps it too.+ DETECTION_GENERATION += 1+ if produced_here and current_detection_epoch() != epoch:+ # See detect_hardware(): a retired pass must not publish -- but only what this+ # call produced. A retired worker that waited out the lock and found DEVICE set+ # is looking at the new lifespan's verdict; discarding it would leave the+ # restart provisional.+ _discard_detection_locked()+ return DEVICE+ # Set only here, where a final value is guaranteed: a non-None DEVICE means only that+ # a candidate was picked (the XPU branch assigns before a probe that can raise), so a+ # waiter trusting it could publish training-enabled for a CPU/chat-only host.+ # Unconditional, unlike the counter: re-setting is a no-op and a late waiter needs it.+ DETECTION_COMPLETE.set()+ return DEVICE+++def _detect_hardware_locked() -> DeviceType:+ """detect_hardware() body. Call only with _DETECT_LOCK held."""global DEVICE, CHAT_ONLY, CHAT_ONLY_REASON, IS_ROCMCHAT_ONLY = True # reset -- only CUDA/ROCm/XPU/MLX sets it to FalseCHAT_ONLY_REASON = NoneIS_ROCM = False+ # Probe torch once per pass: a failed probe is expensive and a second can disagree.+ torch_ok = _has_torch()+# --- CUDA / ROCm / XPU: try PyTorch ---- if _has_torch():+ if torch_ok:import torch# --- Explicit-XPU hint ---@@ -255,7 +493,7 @@ def detect_hardware() -> DeviceType:return DEVICE# --- XPU: Intel GPU ---- if _has_torch():+ if torch_ok:import torchif hasattr(torch, "xpu") and torch.xpu.is_available():DEVICE = DeviceType.XPU@@ -292,6 +530,9 @@ def detect_hardware() -> DeviceType:"Train/Export disabled (chat-only). Run `unsloth studio update` to ""restore MLX training.")+ elif TORCH_IMPORT_ERROR is not None:+ # torch installed but broken, so this host was never measured. "no_gpu" would lie.+ CHAT_ONLY_REASON = "detection_failed"elif platform.system() == "Darwin":CHAT_ONLY_REASON = "intel_mac" # Intel Mac: no PyTorch/MLX -> GGUF-only by design.else:@@ -308,10 +549,7 @@ def get_device() -> DeviceType:Return the detected device, auto-detecting if detect_hardware() hasn't run.Prefer calling detect_hardware() explicitly at startup."""- global DEVICE- if DEVICE is None:- detect_hardware()- return DEVICE+ return ensure_hardware_detected()def export_capability() -> dict:@@ -329,9 +567,15 @@ def export_capability() -> dict:"export_unsupported_reason": None,"export_unsupported_message": None,}- # No accelerator: name the blocker. Apple Silicon first -- its path is MLX, so "install PyTorch"- # would be wrong advice on a Mac even when torch is also absent.- if is_apple_silicon():+ # No accelerator: name the blocker. Detection failure first -- the branches below all+ # describe a measured host, so a broken probe would tell a GPU box to install PyTorch.+ if CHAT_ONLY_REASON == "detection_failed":+ reason = "detection_failed"+ message = (+ "Hardware detection failed on this host, so export is disabled. The server log records "+ "the underlying error; restart Unsloth Studio to retry detection."+ )+ elif is_apple_silicon():reason = "mlx_unavailable"message = ("Export on Apple Silicon requires the MLX stack, which is unavailable or too old. Run "diff --git a/studio/backend/utils/lifespan_shutdown.py b/studio/backend/utils/lifespan_shutdown.pyindex 6e8371e53de..38f19346521 100644--- a/studio/backend/utils/lifespan_shutdown.py+++ b/studio/backend/utils/lifespan_shutdown.py@@ -46,9 +46,23 @@ async def run_lifespan_shutdown(logger.warning("terminate_downloads failed at shutdown: %s", exc)try:+ # Retire any detection still inside the torch import, so it cannot publish over the reset.+ invalidate = getattr(hw_module, "invalidate_detection", None)+ if invalidate is not None:+ invalidate()hw_module.DEVICE = None+ # /api/health reads a set event as "DEVICE is authoritative", so leaving it set over+ # a cleared DEVICE would publish a device that is gone. getattr: tests inject a stub.+ detection_complete = getattr(hw_module, "DETECTION_COMPLETE", None)+ if detection_complete is not None:+ detection_complete.clear()+ # Health falls back to a bare CHAT_ONLY read while the event is clear, so leaving it+ # False would show Train and Export on an unknown host. Hidden until detection says so.+ hw_module.CHAT_ONLY = True+ hw_module.CHAT_ONLY_REASON = None+ hw_module.IS_ROCM = Falseexcept Exception as exc:- logger.warning("clearing hardware DEVICE failed at shutdown: %s", exc)+ logger.warning("clearing hardware detection state failed at shutdown: %s", exc)try:clear_compiled_cache()diff --git a/studio/backend/utils/mlx_repair.py b/studio/backend/utils/mlx_repair.pyindex 8e2a6a77121..33dd8bd7cc8 100644--- a/studio/backend/utils/mlx_repair.py+++ b/studio/backend/utils/mlx_repair.py@@ -33,6 +33,7 @@ import sysimport tempfileimport threadingfrom pathlib import Path+from typing import Optionalimport structlog@@ -321,12 +322,22 @@ def attempt_mlx_repair(*, timeout: int = _REPAIR_TIMEOUT_S) -> bool:return True-def _run_repair_and_redetect() -> None:+def _run_repair_and_redetect(epoch: Optional[int] = None) -> None:if not attempt_mlx_repair():returntry:from utils.hardware import hardware as hw- hw.detect_hardware() # flips CHAT_ONLY / DEVICE now that mlx imports++ # A pip install, so shutdown can land anywhere inside it. Scoping to the epoch read+ # before start() discards the re-detect rather than republish for a dead lifespan.+ with hw.owning_detection_epoch(epoch):+ hw.detect_hardware() # flips CHAT_ONLY / DEVICE now that mlx imports+ if epoch is not None and hw.current_detection_epoch() != epoch:+ # The scoped pass declined: this repair outlived its lifespan. The install+ # still succeeded, so the live lifespan holds a verdict measured before mlx+ # existed and the _attempted latch blocks any later repair. Re-detect under+ # the live epoch, or a now-capable Mac stays chat-only until a restart.+ hw.detect_hardware()logger.info("MLX self-heal succeeded; Train/Export enabled (reload the page). chat_only=%s",hw.CHAT_ONLY,@@ -358,8 +369,13 @@ def start_mlx_autorepair_if_needed() -> bool:"Set %s=1 to disable.",DISABLE_ENV_VAR,)+ # Read before start(): the thread may not run for a while, so reading the epoch+ # inside it would bind the pass to a later shutdown.+ from utils.hardware import hardware as _hw+threading.Thread(target = _run_repair_and_redetect,+ args = (_hw.current_detection_epoch(),),daemon = True,name = "mlx-autorepair",).start()diff --git a/studio/backend/utils/models/model_config.py b/studio/backend/utils/models/model_config.pyindex eae831c7011..73ec0a415ea 100644--- a/studio/backend/utils/models/model_config.py+++ b/studio/backend/utils/models/model_config.py@@ -612,7 +612,24 @@ def _build_detection_sets():)-_VLM_MODEL_TYPES, _VLM_CLASS_NAMES, _AUDIO_ONLY_MODEL_TYPES = _build_detection_sets()+# Reading the registry imports transformers, hence torch: most of `import main` on a GPU+# host, spent before the port can bind. Only the capability checks need the sets, so build+# on first use, double-checked. _build_detection_sets() never raises (curated fallback).+_DETECTION_SETS: Optional[Tuple[frozenset, frozenset, frozenset]] = None+_DETECTION_SETS_LOCK = threading.Lock()+++def _detection_sets() -> Tuple[frozenset, frozenset, frozenset]:+ """(vlm_model_types, vlm_class_names, audio_model_types), built once."""+ global _DETECTION_SETS+ sets = _DETECTION_SETS+ if sets is None:+ with _DETECTION_SETS_LOCK:+ sets = _DETECTION_SETS+ if sets is None:+ sets = _DETECTION_SETS = _build_detection_sets()+ return sets+# Pre-computed .venv_t5 paths and backend dir for subprocess version switching.# Vision check uses the Gemma 4 5.5 sidecar for existing Gemma 4 architectures.@@ -623,6 +640,7 @@ _BACKEND_DIR = str(Path(__file__).resolve().parent.parent.parent)def _is_vlm(config) -> bool:+ vlm_types, vlm_classes, audio_types = _detection_sets()architectures = getattr(config, "architectures", None) or []model_type = getattr(config, "model_type", None)explicit_vision = (@@ -632,13 +650,13 @@ def _is_vlm(config) -> bool:or hasattr(config, "projector_config"))# Audio-only models are vision only if they carry an explicit vision sub-config.- if model_type in _AUDIO_ONLY_MODEL_TYPES and not explicit_vision:+ if model_type in audio_types and not explicit_vision:return Falsereturn (explicit_vision- or any(x in _VLM_CLASS_NAMES for x in architectures)+ or any(x in vlm_classes for x in architectures)or any(isinstance(x, str) and x.endswith(_VLM_ARCH_SUFFIXES) for x in architectures)- or model_type in _VLM_MODEL_TYPES+ or model_type in vlm_types)@@ -670,14 +688,15 @@ def _raw_config_has_vision_config(or "image_token_index" in configor "projector_config" in config)+ vlm_types, vlm_classes, audio_types = _detection_sets()# Audio-only models are vision only if they carry an explicit vision sub-config.- if model_type in _AUDIO_ONLY_MODEL_TYPES and not explicit_vision:+ if model_type in audio_types and not explicit_vision:return Falsereturn (explicit_vision- or any(isinstance(x, str) and x in _VLM_CLASS_NAMES for x in architectures)+ or any(isinstance(x, str) and x in vlm_classes for x in architectures)or any(isinstance(x, str) and x.endswith(_VLM_ARCH_SUFFIXES) for x in architectures)- or model_type in _VLM_MODEL_TYPES+ or model_type in vlm_types)except Exception as exc:logger.warning("Could not read config.json for '%s': %s", model_name, exc)@@ -686,34 +705,39 @@ def _raw_config_has_vision_config(# why: inline _is_vlm and constants are prepended so the subprocess stays# self-contained and does not import the parent backend module graph.-_VISION_CHECK_INLINE_HELPERS = (- "_VLM_ARCH_SUFFIXES = " + repr(tuple(_VLM_ARCH_SUFFIXES)) + "\n"- "_VLM_MODEL_TYPES = " + repr(set(_VLM_MODEL_TYPES)) + "\n"- "_VLM_CLASS_NAMES = " + repr(set(_VLM_CLASS_NAMES)) + "\n"- "_AUDIO_ONLY_MODEL_TYPES = " + repr(set(_AUDIO_ONLY_MODEL_TYPES)) + "\n"- "def _is_vlm(config):\n"- " architectures = getattr(config, 'architectures', None) or []\n"- " model_type = getattr(config, 'model_type', None)\n"- " explicit_vision = (\n"- " hasattr(config, 'vision_config')\n"- " or hasattr(config, 'img_processor')\n"- " or hasattr(config, 'image_token_index')\n"- " or hasattr(config, 'projector_config')\n"- " )\n"- " if model_type in _AUDIO_ONLY_MODEL_TYPES and not explicit_vision:\n"- " return False\n"- " return (\n"- " explicit_vision\n"- " or any(x in _VLM_CLASS_NAMES for x in architectures)\n"- " or any(isinstance(x, str) and x.endswith(_VLM_ARCH_SUFFIXES) for x in architectures)\n"- " or model_type in _VLM_MODEL_TYPES\n"- " )\n"-)+# Built on demand: interpolating the sets eagerly forces the registry read this module defers.+def _build_vision_check_inline_helpers() -> str:+ vlm_types, vlm_classes, audio_types = _detection_sets()+ return (+ "_VLM_ARCH_SUFFIXES = " + repr(tuple(_VLM_ARCH_SUFFIXES)) + "\n"+ "_VLM_MODEL_TYPES = " + repr(set(vlm_types)) + "\n"+ "_VLM_CLASS_NAMES = " + repr(set(vlm_classes)) + "\n"+ "_AUDIO_ONLY_MODEL_TYPES = " + repr(set(audio_types)) + "\n"+ "def _is_vlm(config):\n"+ " architectures = getattr(config, 'architectures', None) or []\n"+ " model_type = getattr(config, 'model_type', None)\n"+ " explicit_vision = (\n"+ " hasattr(config, 'vision_config')\n"+ " or hasattr(config, 'img_processor')\n"+ " or hasattr(config, 'image_token_index')\n"+ " or hasattr(config, 'projector_config')\n"+ " )\n"+ " if model_type in _AUDIO_ONLY_MODEL_TYPES and not explicit_vision:\n"+ " return False\n"+ " return (\n"+ " explicit_vision\n"+ " or any(x in _VLM_CLASS_NAMES for x in architectures)\n"+ " or any(isinstance(x, str) and x.endswith(_VLM_ARCH_SUFFIXES) for x in architectures)\n"+ " or model_type in _VLM_MODEL_TYPES\n"+ " )\n"+ )+# Subprocess script run with transformers 5.x active. Takes model_name and# token via argv, prints JSON result to stdout.-_VISION_CHECK_SCRIPT = (- r"""+def _build_vision_check_script() -> str:+ return (+ r"""import sys, os, jsonos.environ["TOKENIZERS_PARALLELISM"] = "false"@@ -728,8 +752,8 @@ if backend_dir not in sys.path:sys.path.insert(0, backend_dir)"""- + _VISION_CHECK_INLINE_HELPERS- + r"""+ + _build_vision_check_inline_helpers()+ + r"""try:from transformers import AutoConfig@@ -768,7 +792,36 @@ except Exception as exc:print(json.dumps({"error": str(exc)}))sys.exit(1)"""-)+ )+++# PEP 562 keeps the two script strings and three detection sets reachable under their+# original module-level names, including `from ... import _VLM_...`. Memoised so+# repeated access does not rebuild the ~40 KB script.+_LAZY_MODULE_ATTRS = {+ "_VLM_MODEL_TYPES": lambda: _detection_sets()[0],+ "_VLM_CLASS_NAMES": lambda: _detection_sets()[1],+ "_AUDIO_ONLY_MODEL_TYPES": lambda: _detection_sets()[2],+ "_VISION_CHECK_INLINE_HELPERS": _build_vision_check_inline_helpers,+ "_VISION_CHECK_SCRIPT": _build_vision_check_script,+}+_LAZY_MODULE_CACHE: Dict[str, Any] = {}+_LAZY_MODULE_LOCK = threading.Lock()+++def _lazy_module_attr(name: str) -> Any:+ """Build-once accessor. Also for in-module callers, where a bare global read would+ not reach PEP 562."""+ with _LAZY_MODULE_LOCK:+ if name not in _LAZY_MODULE_CACHE:+ _LAZY_MODULE_CACHE[name] = _LAZY_MODULE_ATTRS[name]()+ return _LAZY_MODULE_CACHE[name]+++def __getattr__(name: str) -> Any:+ if name not in _LAZY_MODULE_ATTRS:+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")+ return _lazy_module_attr(name)def _is_vision_model_subprocess(model_name: str, hf_token: Optional[str] = None) -> Optional[bool]:@@ -796,7 +849,7 @@ def _is_vision_model_subprocess(model_name: str, hf_token: Optional[str] = None)[sys.executable,"-c",- _VISION_CHECK_SCRIPT,+ _lazy_module_attr("_VISION_CHECK_SCRIPT"),sidecar_dir,_BACKEND_DIR,model_name,diff --git a/studio/backend/utils/torch_warmup.py b/studio/backend/utils/torch_warmup.pynew file mode 100644index 00000000000..333e22083fe--- /dev/null+++ b/studio/backend/utils/torch_warmup.py@@ -0,0 +1,380 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Import the ML stack on a background thread while the backend finishes booting.++torch (plus the sympy/scipy/pandas it drags in) used to be imported by `import+main`, so the port could not bind until it finished. Deferring it alone would just+move that cost to the first request; this module pays it concurrently instead.++Started from the last line of main.py's lifespan: everything above is on the+critical path to binding the socket and would contend for the GIL. Uvicorn binds as+soon as the lifespan returns, so the warm overlaps serving, not boot.++Contract:+ * idempotent -- one thread per process, repeat calls are no-ops+ * never fatal -- a failed stage is logged and left cold, retried by whoever needs it+ * no half-initialised state -- stages delegate to the module owning the cache+ (utils.hardware, model_config, hf_xet_fallback), which caches under a lock and+ only on success, so a racing request waits rather than sees a partial+ * same end state -- same imports, order and call sites as `import main`. A stage+ shortcutting to a bare `import x` can behave differently; see _warm_unsloth_zoo.++This does NOT make torch-dependent endpoints cheap while it runs: anything reaching+get_device() blocks until the hardware stage finishes, so `async def` handlers on+that path must use asyncio.to_thread (see main.py's /api/health).+"""++from __future__ import annotations++import importlib+import importlib.machinery+import importlib.util+import os+import sys+import threading+import time+from contextlib import contextmanager+from functools import partial+from typing import Optional++from loggers import get_logger++logger = get_logger(__name__)++DISABLE_ENV_VAR = "UNSLOTH_STUDIO_DISABLE_TORCH_WARM"++_start_lock = threading.Lock()+_thread: Optional[threading.Thread] = None+# Detection epoch of the live warm: "already warmed this lifespan" vs. one whose lifespan ended.+_thread_epoch: Optional[int] = None+_status: dict = {"started": False, "finished": False, "stages": {}}+++def _torch_installed() -> bool:+ """True if torch is importable without importing it, so torch-requiring stages are+ skipped on a --no-torch install rather than logging an error for a missing-on-purpose dep."""+ try:+ return importlib.util.find_spec("torch") is not None+ except (ImportError, ValueError):+ return False+++def _is_extension_module(name: str) -> bool:+ """True if sys.modules[name] is a compiled extension, not Python source."""+ module = sys.modules.get(name)+ origin = getattr(getattr(module, "__spec__", None), "origin", None) or getattr(+ module, "__file__", None+ )+ if not isinstance(origin, str):+ return False+ return origin.endswith(tuple(importlib.machinery.EXTENSION_SUFFIXES))+++def purge_partial_import(package: str) -> list:+ """Drop the submodules a failed package import left behind in sys.modules.++ When ``package/__init__.py`` raises, CPython evicts only the parent and keeps+ every submodule it already executed. The next import re-runs ``__init__`` with+ each ``from .x import y`` served from that cache, so attributes are never+ rebound: the package imports "successfully" but is missing pieces (the+ bitsandbytes case fixed in #7580). The warm makes this reachable -- it imports on+ a thread and swallows the failure, so the retry is somebody else's request.++ Acts only on that exact signature (parent gone, submodules present), so a+ concurrent, still-running import is left alone. Returns what it removed.++ Declines when any submodule is a loaded C extension: evicting one re-runs its+ module init, and pybind11 answers a duplicate type registration with+ std::terminate. A torch missing attributes is bad; SIGABRT mid-serve is worse.+ """+ if package in sys.modules:+ return []+ prefix = package + "."+ stale = [name for name in list(sys.modules) if name.startswith(prefix)]+ # Re-check before touching anything: a retrying importer publishes the parent as soon+ # as its __init__ begins, and popping submodules out from under it produces the very+ # half-initialised package this prevents. Narrows the window; CPython's lock is private.+ if package in sys.modules:+ logger.info(+ "not purging %s: another importer republished it while collecting its "+ "leftovers, so that import owns them now",+ package,+ )+ return []+ compiled = sorted(name for name in stale if _is_extension_module(name))+ if compiled:+ logger.warning(+ "not purging %s: %d of its submodule(s) are loaded C extensions and "+ "re-importing one aborts the process (%s). The next import will reuse "+ "the cached submodules and may be missing attributes.",+ package,+ len(compiled),+ ", ".join(compiled[:4]),+ )+ return []+ # Track what actually went: a partway bail must not report a clean slate that never happened.+ removed = []+ for name in stale:+ # Same race, per pop: bail the moment the parent is back.+ if package in sys.modules:+ logger.warning(+ "stopped purging %s partway: another importer republished it. The "+ "submodules already removed will be re-executed by that import.",+ package,+ )+ break+ if sys.modules.pop(name, None) is not None:+ removed.append(name)+ if removed:+ logger.warning(+ "purged %d half-imported %s submodule(s) so the next import re-runs clean: %s",+ len(removed),+ package,+ ", ".join(sorted(removed)[:8]),+ )+ return removed+++# Stage -> package to purge on failure. inference_backend is absent: it imports nothing.+_STAGE_PACKAGE = {+ "hardware": "torch",+ "transformers": "transformers",+ "datasets": "datasets",+ "unsloth_zoo": "unsloth_zoo",+}+++def _run_stage(name: str, fn) -> None:+ started = time.perf_counter()+ try:+ fn()+ except BaseException as exc: # noqa: BLE001 - a warm failure must be visible, not fatal+ _status["stages"][name] = {"ok": False, "error": repr(exc)}+ # warning, not debug: the stage stays cold and the first request pays for it.+ logger.warning("torch warm stage %r failed: %r", name, exc)+ package = _STAGE_PACKAGE.get(name)+ if package:+ purge_partial_import(package)+ else:+ _status["stages"][name] = {+ "ok": True,+ "seconds": round(time.perf_counter() - started, 3),+ }+++def _warm_hardware(epoch: Optional[int] = None) -> None:+ # Requests hit the same call, so they reuse the cache or block on this thread's lock,+ # never race a second detection. The epoch rides along: a shutdown landing between+ # _warm()'s check and _DETECT_LOCK would else publish for the lifespan that just ended.+ from utils.hardware import ensure_hardware_detected+ ensure_hardware_detected(epoch)+++def _warm_transformers() -> None:+ # Ahead of unsloth_zoo: that is the eager order, and unsloth_zoo patches it on import.+ from utils.models.model_config import _detection_sets+ _detection_sets()+++def _warm_datasets() -> None:+ # `import main` pulled it in; keep the first dataset op as cheap. Ungated: no torch needed.+ importlib.import_module("datasets")+++def _warm_unsloth_zoo() -> None:+ """Prime the download stall watchdog, the way the eager import primed it.++ Through utils.hf_xet_fallback, not a bare ``import unsloth_zoo``: the edge this+ replaces was orchestrator.py's ``from utils.hf_xet_fallback import+ DownloadStallError``, and the shim does more. When unsloth_zoo's GPU init raises it+ retries under UNSLOTH_ZOO_DISABLE_GPU_INIT=1 and injects triton/bitsandbytes stubs;+ a bare import skips that retry, so a host whose bitsandbytes cannot find libcudart+ would fail a stage startup used to complete.++ Skipped without torch: unsloth_zoo hard-requires it and the shim degrades to stubs.+ """+ if not _torch_installed():+ return+ # Private deliberately: the exact function the eager import drove. The public names+ # reach it only via an attribute whose degraded fallback looks like success.+ from utils.hf_xet_fallback import _load_shared++ if not _load_shared():+ # Downloads still work on the degraded stubs, but the stage is cold and+ # warm_status() must say so. Purge so the next importer re-runs __init__ clean;+ # the shim's negative cache stays pinned, as the raise site and `except` must+ # resolve to one DownloadStallError class or the stall handler is bypassed.+ purge_partial_import("unsloth_zoo")+ raise RuntimeError("unsloth_zoo unavailable; the download stall watchdog stays degraded")+++# _STAGES follows the eager import order: transformers before unsloth_zoo (which patches+# it on import), datasets between them because that is where `import main` reached it.+def _warm_inference_backend() -> None:+ # Its constructor reaches hw.get_device(), so whoever builds it first pays for detection+ # -- lazily that is some request, and sync helpers call the getter inline from async+ # handlers. Building it here makes the getter a dict read. After hardware, to reuse it.+ from core.inference import get_inference_backend+ get_inference_backend()+++_STAGES = (+ ("hardware", _warm_hardware),+ ("inference_backend", _warm_inference_backend),+ ("transformers", _warm_transformers),+ ("datasets", _warm_datasets),+ ("unsloth_zoo", _warm_unsloth_zoo),+)+++def _warm(epoch: Optional[int] = None) -> None:+ started = time.perf_counter()+ if epoch is None:+ epoch = _detection_epoch()+ # The boundary checks below only catch a shutdown between stages. Inside one, the+ # orchestrator constructor reaches get_device(), which takes no epoch; the scope binds+ # it to this pass so a mid-stage shutdown discards it instead of republishing DEVICE.+ with _owning_epoch(epoch):+ for name, fn in _STAGES:+ if epoch is not None and _detection_epoch() != epoch:+ # Checked before the first stage too: start_background_warm() reads the+ # epoch before start(), so a shutdown in that gap retires this thread+ # while it is still scheduled, with nothing yet run.+ logger.info("torch warm stopped before %s: its lifespan ended", name)+ return+ # Only the real stage takes the epoch; a patched _STAGES entry is called bare.+ _run_stage(name, partial(fn, epoch) if fn is _warm_hardware else fn)+ if epoch is not None and _detection_epoch() != epoch:+ # Shutdown retired this lifespan's detection. Later stages build the+ # orchestrator, which reaches get_device() and would start a fresh+ # detection, republishing DEVICE after teardown cleared it.+ logger.info("torch warm stopped after %s: its lifespan ended", name)+ return+ _status["finished"] = True+ _status["seconds"] = round(time.perf_counter() - started, 3)+ logger.info("torch warm finished in %.1fms", (time.perf_counter() - started) * 1000)+++@contextmanager+def _owning_epoch(epoch: Optional[int]):+ """hardware.owning_detection_epoch(), a no-op when hardware is not importable: a+ --no-torch host still runs the warm and each stage reports its own absence."""+ try:+ from utils.hardware import hardware as _hw+ scope = _hw.owning_detection_epoch(epoch)+ except Exception:+ yield+ return+ with scope:+ yield+++def _detection_epoch() -> Optional[int]:+ """The current detection epoch, or None if hardware is not importable."""+ try:+ from utils.hardware import hardware as _hw+ return _hw.current_detection_epoch()+ except Exception:+ return None+++def _warm_after(previous: threading.Thread, epoch: Optional[int]) -> None:+ """Wait out a retired warm, then warm for ``epoch``. One importer at a time."""+ previous.join()+ _warm(epoch)+++def start_background_warm() -> bool:+ """Start the warm thread once. Returns True iff this call started it.++ Runs on every host, torch or not: stage one is hardware detection, which must not+ wait for a request (it feeds /api/health's chat_only).++ A finished thread from an earlier lifespan does not count as one already running:+ reset_background_warm() declines mid-warm, so a shutdown then leaves the object in+ place, and treating that as "already started" would skip the warm over hardware+ state the same shutdown just cleared.+ """+ global _thread+ if os.environ.get(DISABLE_ENV_VAR) == "1":+ return False+ global _thread_epoch+ # Epoch read before start(): the child may not run for a while, and a shutdown in that+ # gap retires this lifespan. Reading it in the thread would adopt the post-shutdown one.+ epoch = _detection_epoch()+ with _start_lock:+ target, args = _warm, (epoch,)+ if _thread is not None:+ # A warm holds the latch while its own lifespan is current, so repeat calls+ # are no-ops. Once shutdown retires that epoch the next lifespan warms again.+ if _thread_epoch is not None and epoch == _thread_epoch:+ return False+ if _thread.is_alive():+ # Stale but mid-stage: it stops at the next boundary and nothing retries,+ # so this lifespan would serve cold. Hand off; the successor joins it+ # first, so only one thread imports.+ target, args = _warm_after, (_thread, epoch)+ else:+ _clear_finished_warm_locked()+ _thread = threading.Thread(+ target = target,+ args = args,+ daemon = True,+ name = "torch-warm",+ )+ _thread_epoch = epoch+ _status["started"] = True+ _thread.start()+ return True+++def reset_background_warm() -> bool:+ """Let a later lifespan in this process start a fresh warm. True iff reset.++ The same app can start twice (repeated ASGI lifespans, an embedded restart) and+ shutdown clears the hardware state the first warm produced; leaving the finished+ thread in place would make the second lifespan skip the warm and hand detection back+ to the first request, the stall this module removes.++ Declines while the previous warm runs, so two warms never share the same imports.+ Detection self-heals then: shutdown clears DETECTION_COMPLETE and /api/health kicks+ start_background_detection().+ """+ with _start_lock:+ thread = _thread+ if thread is not None and thread.is_alive():+ return False+ _clear_finished_warm_locked()+ return True+++def _clear_finished_warm_locked() -> None:+ """Drop the finished warm and its status. Caller holds ``_start_lock``."""+ global _thread, _thread_epoch+ _thread = None+ _thread_epoch = None+ _status["started"] = False+ _status["finished"] = False+ _status["stages"] = {}+ _status.pop("seconds", None)+++def warm_status() -> dict:+ """Snapshot of the warm for diagnostics and tests."""+ return {+ "started": _status["started"],+ "finished": _status["finished"],+ "alive": bool(_thread is not None and _thread.is_alive()),+ "stages": dict(_status["stages"]),+ "seconds": _status.get("seconds"),+ }+++def join_background_warm(timeout: Optional[float] = None) -> bool:+ """Wait for the warm thread. Returns True if it is done (or never ran)."""+ thread = _thread+ if thread is None:+ return True+ thread.join(timeout)+ return not thread.is_alive()diff --git a/studio/frontend/src/components/app-sidebar.tsx b/studio/frontend/src/components/app-sidebar.tsxindex e51628c30ed..9d0fe542163 100644--- a/studio/frontend/src/components/app-sidebar.tsx+++ b/studio/frontend/src/components/app-sidebar.tsx@@ -370,6 +370,7 @@ export function AppSidebar() {const chatOnly = usePlatformStore((s) => s.isChatOnly());const chatOnlyReason = usePlatformStore((s) => s.chatOnlyReason);+ const detectionDeferred = usePlatformStore((s) => s.detectionDeferred);// Explain a greyed-out Train (chat-only host) on hover instead of disabling silently. Export is// no longer disabled here: it stays navigable so its page can show a precise grayed-out reason.const trainDisabledHint: string | undefined = !chatOnly@@ -388,12 +389,14 @@ export function AppSidebar() {// recoverable mlx_unavailable case; the effect stops once Train/Export become// available (chatOnly flips false and this effect's guard returns early).useEffect(() => {- if (!chatOnly || chatOnlyReason !== "mlx_unavailable") return;+ // Also while deferred: under the kill switch health settles nothing, so only a+ // first-use operation detects and a GPU host would stay chat-only until a refresh.+ if (!chatOnly || (chatOnlyReason !== "mlx_unavailable" && !detectionDeferred)) return;const id = window.setInterval(() => {void fetchDeviceType({ force: true }).catch(() => undefined);}, 15000);return () => window.clearInterval(id);- }, [chatOnly, chatOnlyReason]);+ }, [chatOnly, chatOnlyReason, detectionDeferred]);const [shutdownOpen, setShutdownOpen] = useState(false);diff --git a/studio/frontend/src/config/env.ts b/studio/frontend/src/config/env.tsindex 63cdd031413..f531284fef6 100644--- a/studio/frontend/src/config/env.ts+++ b/studio/frontend/src/config/env.ts@@ -2,6 +2,11 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import { apiUrl } from "@/lib/api-base";+import {+ isDetectionDeferred,+ isProvisionalVerdict,+ resolveVerdict,+} from "@/config/hardware-verdict";import { create } from "zustand";export const env = {@@ -28,6 +33,9 @@ interface PlatformState {serverUrl: string | null;secure: boolean;fetched: boolean;+ // Last verdict came from a deferred reply (torch-warm kill switch): nothing settles+ // until a first-use operation detects, so the sidebar polls on this.+ detectionDeferred: boolean;isChatOnly: () => boolean;}@@ -51,6 +59,7 @@ export const usePlatformStore = create<PlatformState>()((_, get) => ({serverUrl: null,secure: false,fetched: false,+ detectionDeferred: false,isChatOnly: () => get().chatOnly,}));@@ -65,6 +74,13 @@ function shouldKeepAuthoritativePlatform(force?: boolean): boolean {return !force && usePlatformStore.getState().fetched;}+// How long fetchDeviceType waits out a backend that is still detecting, and how often+// it re-reads. Sized from the warm's torch import (~1-2s cold), plus headroom.+const HARDWARE_DETECT_WAIT_MS = 5000;+const HARDWARE_DETECT_POLL_MS = 200;+// The bounded wait above is spent at most once per page load: see fetchDeviceType.+let hardwareWaitSpent = false;+// `force` re-reads /api/health even if cached, to pick up a late-arriving tunnel URL.export async function fetchDeviceType(options?: {force?: boolean;@@ -80,14 +96,45 @@ export async function fetchDeviceType(options?: {typeof window === "undefined"? null: localStorage.getItem("unsloth_auth_token");- const res = await fetch(apiUrl("/api/health"), {- headers: token ? { Authorization: `Bearer ${token}` } : undefined,- });+ // Re-read while the backend is still measuring: chat_only is its pre-detection default+ // until then, and __root.tsx's beforeLoad acts on what this returns, sending a GPU host+ // to /chat with Train hidden. The window is only the torch import, so bound the re-read.+ const headers = token ? { Authorization: `Bearer ${token}` } : undefined;+ // Wait only when a measurement can arrive, and only once. /api/health reports+ // device_type to authed callers only, so an unauthenticated poll stays provisional and+ // would just hold /login (beforeLoad awaits this) behind the torch import. Claim the+ // latch after the wait, or a concurrent caller skips a window nobody has finished.+ const spendWait = Boolean(token) && !hardwareWaitSpent;+ const deadline = spendWait ? Date.now() + HARDWARE_DETECT_WAIT_MS : 0;+ let tokenRejected = false;+ let res = await fetch(apiUrl("/api/health"), { headers });+ while (res.ok && Date.now() < deadline) {+ const peek = (await res.clone().json()) as {+ hardware_detecting?: boolean;+ hardware_detection_deferred?: boolean;+ version?: string;+ };+ // Deferred is not "in progress": nothing will settle, so do not wait.+ if (!isProvisionalVerdict(peek) || isDetectionDeferred(peek)) break;+ // A rejected token gets the unauthenticated body, which never carries device_type.+ // `version` is authed-only, so its absence means this wait can only time out,+ // holding /login for the full window on a cold boot.+ if (peek.version === undefined) {+ tokenRejected = true;+ break;+ }+ await new Promise((resolve) => setTimeout(resolve, HARDWARE_DETECT_POLL_MS));+ res = await fetch(apiUrl("/api/health"), { headers });+ }+ // Not spent when the backend rejected the token: no window was actually waited+ // out, and signing in later in this same page load must still get one.+ if (spendWait && !tokenRejected) hardwareWaitSpent = true;if (res.ok) {const data = (await res.json()) as {device_type?: string;chat_only?: boolean;chat_only_reason?: string | null;+ hardware_detecting?: boolean;cloudflare_url?: string | null;server_url?: string | null;secure?: boolean;@@ -101,9 +148,15 @@ export async function fetchDeviceType(options?: {if (shouldKeepAuthoritativePlatform(options?.force)) {return usePlatformStore.getState().deviceType;}- const deviceType = data.device_type ?? detectLocalPlatform();- const chatOnly = data.chat_only ?? false;- const chatOnlyReason = data.chat_only_reason ?? null;+ const previous = usePlatformStore.getState();+ // A provisional reply omits device_type, so a forced refresh during the warm would+ // fall back to the browser platform and relabel a WSL, SSH or remote host as local,+ // changing model filtering, paths and install commands. Keep the server's answer.+ const keepPlatform = data.device_type === undefined && previous.fetched;+ const deviceType =+ data.device_type ?? (keepPlatform ? previous.deviceType : detectLocalPlatform());+ // A still-provisional reply keeps the stored verdict: see resolveVerdict.+ const { chatOnly, chatOnlyReason } = resolveVerdict(data, previous);// Cache only a server-reported platform. Unauthenticated responses fall// back to the browser platform, which can differ from the host (WSL,// SSH); keeping fetched=false retries once a token exists.@@ -114,7 +167,8 @@ export async function fetchDeviceType(options?: {cloudflareUrl: data.cloudflare_url ?? null,serverUrl: data.server_url ?? null,secure: data.secure ?? false,- fetched: data.device_type !== undefined,+ fetched: data.device_type !== undefined || keepPlatform,+ detectionDeferred: isDetectionDeferred(data),});return deviceType;}diff --git a/studio/frontend/src/config/hardware-verdict.ts b/studio/frontend/src/config/hardware-verdict.tsnew file mode 100644index 00000000000..cd6607f4e6e--- /dev/null+++ b/studio/frontend/src/config/hardware-verdict.ts@@ -0,0 +1,54 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Whether a /api/health reply carries a measured hardware verdict or the backend's+// pre-detection default. Its own import-free module so it is testable: env.ts reaches+// import.meta.env through api-base.ts, which only vite can load.++export type HealthVerdict = {+ chat_only?: boolean;+ chat_only_reason?: string | null;+ hardware_detecting?: boolean;+ hardware_detection_deferred?: boolean;+};++export type ResolvedVerdict = {+ chatOnly: boolean;+ chatOnlyReason: string | null;+};++/** True while the backend is still measuring the host, so chat_only is its+ * pre-detection default rather than an answer. */+export function isProvisionalVerdict(data: HealthVerdict): boolean {+ return data.hardware_detecting === true;+}++/** True when the backend deferred detection rather than started it.+ * UNSLOTH_STUDIO_DISABLE_TORCH_WARM=1 stops health kicking detection at all, so nothing+ * settles until a hardware-dependent operation runs, and waiting would stall every load. */+export function isDetectionDeferred(data: HealthVerdict): boolean {+ return data.hardware_detection_deferred === true;+}+++/** The verdict to store. A provisional reply keeps the previous values: storing+ * its chat_only tells a GPU host it has no GPU, and beforeLoad redirects on that. */+export function resolveVerdict(+ data: HealthVerdict,+ previous: ResolvedVerdict,+): ResolvedVerdict {+ if (isDetectionDeferred(data)) {+ // Nothing will settle, so keeping `previous` would leave the browser-platform default+ // (chatOnly false off macOS) in place all session and offer Train on a CPU-only host.+ // Take the backend's conservative chat_only, keeping any reason already explained.+ return {+ chatOnly: data.chat_only ?? true,+ chatOnlyReason: data.chat_only_reason ?? previous.chatOnlyReason,+ };+ }+ if (isProvisionalVerdict(data)) return previous;+ return {+ chatOnly: data.chat_only ?? false,+ chatOnlyReason: data.chat_only_reason ?? null,+ };+}diff --git a/studio/frontend/tests/provisional-hardware-verdict.test.ts b/studio/frontend/tests/provisional-hardware-verdict.test.tsnew file mode 100644index 00000000000..9aa7aec5b86--- /dev/null+++ b/studio/frontend/tests/provisional-hardware-verdict.test.ts@@ -0,0 +1,292 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// /api/health answers before the backend has measured the host: until the background torch+// import lands it reports its pre-detection default, chat_only: true, with+// hardware_detecting set and no device_type. __root.tsx's beforeLoad awaits fetchDeviceType+// then redirects on isChatOnly(), so storing that sends a GPU host's first load to /chat.++import assert from "node:assert/strict";+import test from "node:test";++import { registerBundlerResolver } from "./helpers/kit.ts";++registerBundlerResolver();++const { isDetectionDeferred, isProvisionalVerdict, resolveVerdict } = await import(+ "../src/config/hardware-verdict.ts"+);++const GPU_HOST = { chatOnly: false, chatOnlyReason: null };+const MAC_DEFAULT = { chatOnly: true, chatOnlyReason: null };++test("a detecting reply is provisional, a settled one is not", () => {+ assert.equal(isProvisionalVerdict({ hardware_detecting: true }), true);+ assert.equal(isProvisionalVerdict({ hardware_detecting: false }), false);+ assert.equal(+ isProvisionalVerdict({ chat_only: false }),+ false,+ "a reply with no hardware_detecting at all is a measured one",+ );+});++test("a provisional reply does not send a GPU host to chat-only", () => {+ const resolved = resolveVerdict(+ { chat_only: true, hardware_detecting: true },+ GPU_HOST,+ );+ assert.equal(+ resolved.chatOnly,+ false,+ "the provisional chat_only was stored; beforeLoad would redirect a GPU host to /chat",+ );+});++test("a provisional reply does not clear a reason the UI is explaining", () => {+ const resolved = resolveVerdict(+ { chat_only: true, hardware_detecting: true },+ { chatOnly: true, chatOnlyReason: "mlx_unavailable" },+ );+ assert.equal(+ resolved.chatOnlyReason,+ "mlx_unavailable",+ "the sidebar recovery poll only runs while it reads mlx_unavailable",+ );+});++test("a measured chat-only verdict is still honoured", () => {+ const resolved = resolveVerdict(+ { chat_only: true, chat_only_reason: "mlx_unavailable" },+ GPU_HOST,+ );+ assert.equal(resolved.chatOnly, true, "a real chat-only host was let into Train");+ assert.equal(resolved.chatOnlyReason, "mlx_unavailable");+});++test("a measured GPU verdict clears a chat-only default", () => {+ const resolved = resolveVerdict(+ { chat_only: false, chat_only_reason: null },+ MAC_DEFAULT,+ );+ assert.equal(+ resolved.chatOnly,+ false,+ "keeping the previous value has to stop once a measurement arrives",+ );+});++test("a measured reply with no chat_only field is not chat-only", () => {+ assert.equal(resolveVerdict({}, MAC_DEFAULT).chatOnly, false);+});++test("a deferred verdict is provisional but must not be waited on", () => {+ const deferred = { chat_only: true, hardware_detecting: true, hardware_detection_deferred: true };+ assert.equal(+ isProvisionalVerdict(deferred),+ true,+ "a deferred reply is still not a measurement, so it must not be stored",+ );+ assert.equal(+ isDetectionDeferred(deferred),+ true,+ "the kill switch stops anything settling, so the re-read loop must give up",+ );+});++test("a deferred verdict falls back to the backend's conservative default", () => {+ // Nothing settles while the kill switch is on, so keeping the previous value would leave+ // the browser-platform default (chatOnly false off macOS) up all session on a CPU host.+ const deferred = {+ chat_only: true,+ hardware_detecting: true,+ hardware_detection_deferred: true,+ };+ assert.equal(+ resolveVerdict(deferred, { chatOnly: false, chatOnlyReason: null }).chatOnly,+ true,+ "a never-settling reply left the optimistic platform default in place",+ );+});++test("a deferred verdict does not clear a reason the UI is explaining", () => {+ const deferred = {+ chat_only: true,+ hardware_detecting: true,+ hardware_detection_deferred: true,+ };+ assert.equal(+ resolveVerdict(deferred, { chatOnly: true, chatOnlyReason: "mlx_unavailable" })+ .chatOnlyReason,+ "mlx_unavailable",+ "the sidebar recovery poll only runs while it reads mlx_unavailable",+ );+});++test("an ordinary provisional reply is still not treated as deferred", () => {+ // The conservative fallback stays scoped to the kill switch: a warm-window reply+ // settles in ~1-2s, and taking its chat_only would send a GPU host to /chat.+ assert.equal(+ resolveVerdict({ chat_only: true, hardware_detecting: true }, GPU_HOST).chatOnly,+ false,+ );+});++test("an actively detecting reply is not deferred", () => {+ assert.equal(+ isDetectionDeferred({ chat_only: true, hardware_detecting: true }),+ false,+ "an ordinary warm-window reply must still be waited on",+ );+});++// The bounded re-read in config/env.ts is spent at most once per page load: a slow host+// leaves the reply provisional and `fetched` false, so an unguarded loop repeats the full+// wait on every navigation. Asserted on source: env.ts is not importable outside vite.+test("the bounded hardware wait is spent at most once per page load", async () => {+ const { readFile } = await import("node:fs/promises");+ const src = await readFile(+ new URL("../src/config/env.ts", import.meta.url),+ "utf8",+ );+ assert.match(+ src,+ /let hardwareWaitSpent = false/,+ "no once-per-load latch: every navigation can repeat the full wait",+ );+ assert.match(+ src,+ /const deadline = spendWait \? Date\.now\(\) \+ HARDWARE_DETECT_WAIT_MS : 0/,+ "the guard does not zero the deadline, so the wait is not actually skipped",+ );+});++// beforeLoad awaits fetchDeviceType on every route, /login included, and /api/health+// reports device_type to authed callers only. An unauthenticated poll can never turn+// provisional into measured, so it only holds the login form behind the torch import.+test("an unauthenticated read never spends the detection window", async () => {+ const { readFile } = await import("node:fs/promises");+ const src = await readFile(+ new URL("../src/config/env.ts", import.meta.url),+ "utf8",+ );+ assert.match(+ src,+ /const spendWait = Boolean\(token\) && !hardwareWaitSpent/,+ "the wait is not gated on having a token, so /login blocks on hardware detection",+ );+});++// main.tsx fires an unawaited fetchDeviceType while __root.tsx awaits its own. Claiming+// the latch inside the loop let the unawaited one consume a window it had not finished,+// leaving the awaited caller on the local default and redirecting a GPU host to /chat.+test("the latch is claimed after the wait, not during it", async () => {+ const { readFile } = await import("node:fs/promises");+ const src = await readFile(+ new URL("../src/config/env.ts", import.meta.url),+ "utf8",+ );+ const loopStart = src.indexOf("while (res.ok && Date.now() < deadline)");+ // Located by pattern: the claim carries guards, so a literal anchor goes stale.+ const loopEnd = src.search(/if \(spendWait[^)]*\) hardwareWaitSpent = true;/);+ assert.ok(loopStart > 0 && loopEnd > loopStart, "the wait loop or the latch moved");+ assert.ok(+ !src.slice(loopStart, loopEnd).includes("hardwareWaitSpent = true"),+ "the latch is claimed inside the loop, so a concurrent caller skips an unfinished window",+ );+});++// A provisional reply omits device_type. A forced refresh in that window must not fall+// back to the browser platform: on WSL, SSH or any remote session that relabels the host+// as local, changing model filtering, paths and install commands.+test("a provisional forced refresh keeps the server-reported platform", async () => {+ const { readFile } = await import("node:fs/promises");+ const src = await readFile(+ new URL("../src/config/env.ts", import.meta.url),+ "utf8",+ );+ assert.match(+ src,+ /const keepPlatform =\s*\n?\s*data\.device_type === undefined && previous\.fetched/,+ "no guard: a provisional forced refresh overwrites the authoritative platform",+ );+ assert.match(+ src,+ /keepPlatform \? previous\.deviceType : detectLocalPlatform\(\)/,+ "the guard does not actually keep the stored platform",+ );+ assert.match(+ src,+ /fetched: data\.device_type !== undefined \|\| keepPlatform/,+ "fetched drops to false, so the authoritative platform is not treated as held",+ );+});++// With the kill switch on nothing settles through health, so only a first-use operation+// detects. The sidebar's recovery poll was gated on mlx_unavailable alone, so a GPU host+// kept the conservative deferred verdict and stayed chat-only until a hard refresh.+test("a deferred verdict is recorded so the sidebar can poll out of it", async () => {+ const { readFile } = await import("node:fs/promises");+ const env = await readFile(new URL("../src/config/env.ts", import.meta.url), "utf8");+ const sidebar = await readFile(+ new URL("../src/components/app-sidebar.tsx", import.meta.url),+ "utf8",+ );+ assert.match(+ env,+ /detectionDeferred: isDetectionDeferred\(data\)/,+ "the store never records that the verdict came from a deferred reply",+ );+ assert.match(+ sidebar,+ /chatOnlyReason !== "mlx_unavailable" && !detectionDeferred/,+ "the recovery poll still ignores a deferred verdict, so it never recovers",+ );+});++// A token in localStorage is not proof of an accepted one. /api/health catches the auth+// failure and answers with the unauthenticated body, which never carries device_type, so+// a stale token spends the whole window and holds /login on a cold boot.+test("a rejected token stops the wait instead of polling it out", async () => {+ const { readFile } = await import("node:fs/promises");+ const src = await readFile(+ new URL("../src/config/env.ts", import.meta.url),+ "utf8",+ );+ const loopStart = src.indexOf("while (res.ok && Date.now() < deadline)");+ // Located by pattern: the claim carries guards, so a literal anchor goes stale.+ const loopEnd = src.search(/if \(spendWait[^)]*\) hardwareWaitSpent = true;/);+ assert.ok(loopStart > 0 && loopEnd > loopStart, "the wait loop or the latch moved");+ const loop = src.slice(loopStart, loopEnd);+ assert.ok(+ /if \(peek\.version === undefined\)\s*\{?[^}]*break;/.test(loop),+ "the loop keeps polling a reply with no authed-only field, so an expired token " ++ "waits out the full window on /login",+ );+ assert.match(+ loop,+ /version\?: string;/,+ "the peek type no longer reads the authed-only field it breaks on",+ );+});++// Breaking early on a rejected token must not consume the once-per-page-load window. A+// user who signs in before detection settles gets the first authenticated read; spending+// the latch on a refused token leaves the route guard on local defaults until a refresh.+test("a rejected token does not consume the once-per-load window", async () => {+ const { readFile } = await import("node:fs/promises");+ const src = await readFile(+ new URL("../src/config/env.ts", import.meta.url),+ "utf8",+ );+ assert.match(+ src,+ /if \(spendWait && !tokenRejected\) hardwareWaitSpent = true;/,+ "the latch is claimed even when the break came from a rejected token, so the " ++ "first accepted token in this page load skips its window",+ );+ assert.match(+ src,+ /tokenRejected = true;/,+ "nothing records that the break was caused by a rejected token",+ );+});