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: resolve trust_remote_code off the event loop in /api/inference/status (#10830)
Wenrui LIc3d48ce55305
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex c9af3127731..fbde1e49287 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -19242,6 +19242,28 @@ def _requires_trust_remote_code_for_model(return False+def _stored_trust_remote_code(+ model_info,+ inference_config,+ trust_remote_code_used = False,+) -> Optional[bool]:+ """Network-free part of the resolution order; None = only ``auto_map`` can answer."""+ stored = (model_info or {}).get("requires_trust_remote_code")+ if stored is not None:+ return bool(stored)+ if trust_remote_code_used or bool((inference_config or {}).get("trust_remote_code", False)):+ return True+ return None+++def _auto_map_trust_remote_code(model_id, hf_token = None) -> bool:+ """Raw ``auto_map`` check; can reach the Hub, so keep it off the event loop."""+ try:+ return bool(_requires_trust_remote_code_for_model(model_id, hf_token))+ except Exception:+ return False++def _resolve_loaded_trust_remote_code(model_id,model_info,@@ -19261,16 +19283,11 @@ def _resolve_loaded_trust_remote_code(Resolution order: a value stored on the model at load time (so a status refresh doesnot re-derive it) -> the trust_remote_code the load actually used -> the YAML default- -> the raw ``auto_map`` check (reads the loaded model's cached config; no network)."""- stored = (model_info or {}).get("requires_trust_remote_code")- if stored is not None:- return bool(stored)- if trust_remote_code_used or bool((inference_config or {}).get("trust_remote_code", False)):- return True- try:- return bool(_requires_trust_remote_code_for_model(model_id, hf_token))- except Exception:- return False+ -> the raw ``auto_map`` check (reads the config from the cache, or the Hub on a miss)."""+ known = _stored_trust_remote_code(model_info, inference_config, trust_remote_code_used)+ if known is not None:+ return known+ return _auto_map_trust_remote_code(model_id, hf_token)def _requires_security_review_for_model(@@ -21675,9 +21692,12 @@ async def _slot_status(current_subject: str):audio_type = Nonehas_audio_input = Falsehas_video_input = False+ # Snapshot before the await below: a load landing mid-await must not mix two models.+ _active = backend.active_model_name+ _loaded = list(backend.models.keys())model_info = {}- if backend.active_model_name:- model_info = backend.models.get(backend.active_model_name, {})+ if _active:+ model_info = backend.models.get(_active, {})is_vision = model_info.get("is_vision", False)is_audio = model_info.get("is_audio", False)audio_type = model_info.get("audio_type")@@ -21690,9 +21710,7 @@ async def _slot_status(current_subject: str):# Non-GGUF: classify from the loaded template._sf_flags, _ = _sf_rendered_features(backend, model_info)- inference_config = (- load_inference_config(backend.active_model_name) if backend.active_model_name else None- )+ inference_config = load_inference_config(_active) if _active else None# The backend and the attempt registry name the same load, so compare public ids# or a model loaded from a path is listed twice.@@ -21702,19 +21720,31 @@ async def _slot_status(current_subject: str):):_loading_models.append(_tracked_loading_id)+ # Only the auto_map fallback can reach the Hub; skip the guard's probe otherwise.+ _requires_trc = False+ if _active:+ _known = _stored_trust_remote_code(model_info, inference_config)+ if _known is not None:+ _requires_trc = _known+ else:+ _requires_trc = await asyncio.get_running_loop().run_in_executor(+ _STATUS_PROBE_EXECUTOR,+ functools.partial(+ _offline_guarded, [_active], _auto_map_trust_remote_code, _active+ ),+ )+return InferenceStatusResponse(engine = model_info.get("engine", "auto"),engine_parallelism = model_info.get("engine_parallelism", "tensor"),engine_precision = model_info.get("engine_precision", "auto"),gpu_ids = model_info.get("gpu_ids"),tensor_parallel = bool(model_info.get("tensor_parallel", False)),- active_model = backend.active_model_name,- model_identifier = backend.active_model_name,+ active_model = _active,+ model_identifier = _active,is_vision = is_vision,is_gguf = False,- is_local_model = bool(- backend.active_model_name and is_local_path(backend.active_model_name)- ),+ is_local_model = bool(_active and is_local_path(_active)),is_audio = is_audio,audio_type = audio_type,has_audio_input = has_audio_input,@@ -21743,11 +21773,9 @@ async def _slot_status(current_subject: str):chat_template_override = model_info.get("chat_template_override_requested"),chat_template_override_reason = model_info.get("chat_template_override_reason"),loading = _loading_models,- loaded = list(backend.models.keys()),+ loaded = _loaded,inference = inference_config,- requires_trust_remote_code = _resolve_loaded_trust_remote_code(- backend.active_model_name, model_info, inference_config- ),+ requires_trust_remote_code = _requires_trc,supports_reasoning = _sf_flags["supports_reasoning"],reasoning_style = _sf_flags["reasoning_style"],reasoning_effort_levels = _sf_flags.get("reasoning_effort_levels", []),diff --git a/studio/backend/tests/test_status_trust_remote_code_off_event_loop.py b/studio/backend/tests/test_status_trust_remote_code_off_event_loop.pynew file mode 100644index 00000000000..acc063a42be--- /dev/null+++ b/studio/backend/tests/test_status_trust_remote_code_off_event_loop.py@@ -0,0 +1,123 @@+# 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/inference/status is polled: its auto_map fallback can reach the Hub, so it must not+run on the event loop thread (an unreachable Hub parked the loop and /api/liveness)."""++from __future__ import annotations++import asyncio+import threading+from types import SimpleNamespace++import routes.inference as inference_routes+++def _backend(active = "unsloth/Qwen3-8B", info = None):+ return SimpleNamespace(+ active_model_name = active,+ models = {active: dict(info or {})} if active else {},+ loading_models = set(),+ )+++def _run(coro):+ return asyncio.new_event_loop().run_until_complete(coro)+++def _status():+ return _run(inference_routes._slot_status(current_subject = "t"))+++def test_the_auto_map_fallback_runs_off_the_event_loop_thread(monkeypatch):+ threads: list[tuple[int, str]] = []++ def _auto_map(*_args, **_kwargs):+ threads.append((threading.get_ident(), threading.current_thread().name))+ return False++ monkeypatch.setattr(inference_routes, "_peek_inference_backend", lambda *a, **k: _backend())+ monkeypatch.setattr(inference_routes, "_auto_map_trust_remote_code", _auto_map)++ loop_thread = threading.get_ident()+ _status()++ assert threads, "status never ran the auto_map fallback"+ assert all(ident != loop_thread for ident, _ in threads)+ # Not the default executor: it drives local token streaming.+ assert all(name.startswith("inference-status") for _, name in threads), threads+++def test_the_fallback_runs_inside_the_offline_guard(monkeypatch):+ guarded: list[tuple] = []++ def _offline_guarded(targets, fn, /, *args, **kwargs):+ guarded.append(tuple(targets))+ return fn(*args, **kwargs)++ monkeypatch.setattr(inference_routes, "_peek_inference_backend", lambda *a, **k: _backend())+ monkeypatch.setattr(inference_routes, "_offline_guarded", _offline_guarded)+ monkeypatch.setattr(inference_routes, "_auto_map_trust_remote_code", lambda *a, **k: False)++ _status()++ assert guarded == [("unsloth/Qwen3-8B",)]+++def test_a_trust_decision_stored_at_load_skips_the_guard_and_the_thread(monkeypatch):+ entered: list[str] = []++ monkeypatch.setattr(+ inference_routes,+ "_peek_inference_backend",+ lambda *a, **k: _backend(info = {"requires_trust_remote_code": True}),+ )+ monkeypatch.setattr(+ inference_routes,+ "_offline_guarded",+ lambda *a, **k: entered.append("guard") or False,+ )+ monkeypatch.setattr(+ inference_routes,+ "_auto_map_trust_remote_code",+ lambda *a, **k: entered.append("auto_map") or False,+ )++ response = _status()++ assert response.requires_trust_remote_code is True+ assert entered == []+++def test_a_load_completing_mid_resolve_does_not_mix_two_models(monkeypatch):+ backend = _backend("unsloth/Qwen3-8B")++ def _auto_map(*_args, **_kwargs):+ backend.active_model_name = "unsloth/Llama-3.1-8B"+ backend.models = {"unsloth/Llama-3.1-8B": {}}+ return True++ monkeypatch.setattr(inference_routes, "_peek_inference_backend", lambda *a, **k: backend)+ monkeypatch.setattr(inference_routes, "_auto_map_trust_remote_code", _auto_map)++ response = _status()++ assert response.active_model == "unsloth/Qwen3-8B"+ assert response.requires_trust_remote_code is True+ assert response.loaded == ["unsloth/Qwen3-8B"]+++def test_no_loaded_model_reads_nothing(monkeypatch):+ called: list[int] = []++ monkeypatch.setattr(inference_routes, "_peek_inference_backend", lambda *a, **k: _backend(None))+ monkeypatch.setattr(+ inference_routes,+ "_auto_map_trust_remote_code",+ lambda *a, **k: called.append(1) or False,+ )++ response = _status()++ assert not called+ assert response.requires_trust_remote_code is Falsediff --git a/tests/studio/test_model_picker_contracts.py b/tests/studio/test_model_picker_contracts.pyindex 8a137b8dad7..0ef31cc6fa1 100644--- a/tests/studio/test_model_picker_contracts.py+++ b/tests/studio/test_model_picker_contracts.py@@ -1088,7 +1088,7 @@ def test_local_mtp_warning_uses_backend_source_metadata():# Both GGUF responses report it: the status poll and the already_loaded# dedup reply. Either one re-deriving it reintroduces the flip.assert route.count("is_local_model = _loaded_is_local_model(") >= 2- assert "backend.active_model_name and is_local_path(backend.active_model_name)" in route+ assert "is_local_model = bool(_active and is_local_path(_active))" in routedef test_fixed_layer_gguf_pins_displayed_context():