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: close the delete-vs-load races around the H3 companion repos (#8657)
Daniel Hanb4702b282473
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.pyindex 706aec01d06..3b65e6c3249 100644--- a/studio/backend/core/inference/video.py+++ b/studio/backend/core/inference/video.py@@ -1241,6 +1241,15 @@ class VideoBackend:transformer_quant = transformer_quant,text_encoder_quant = text_encoder_quant,)+ # Resolved out here so the companion claim is published in the SAME locked section as+ # _loading. begin_load returns as soon as the thread is scheduled, and a delete arriving in+ # that gap sees only repo_id and base_repo, passes the guard, and starts removing a+ # companion repo this load needs. A later claim does not revoke a delete already admitted.+ from .video_minimax_h3 import H3_COMPONENT_REPO, H3_GGUF_REPO, is_h3_native++ h3_native = is_h3_native(fam, resolve_video_model_kind(gguf_filename, model_kind))+ claimed_assets = (H3_GGUF_REPO, H3_COMPONENT_REPO) if h3_native else ()+with self._lock:if self._loading is not None and self._loading.error is None:raise RuntimeError("A video load is already in progress.")@@ -1250,7 +1259,11 @@ class VideoBackend:# drops _loading, so the next begin_load would clear the object that worker watches. A fresh object leaves it set.cancel_event = threading.Event()self._cancel_event = cancel_event- self._loading = _VideoLoadingState(repo_id = repo_id, base_repo = fam.base_repo)+ self._loading = _VideoLoadingState(+ repo_id = repo_id,+ base_repo = fam.base_repo,+ asset_repos = claimed_assets,+ )threading.Thread(target = self._run_load,@@ -1499,6 +1512,18 @@ class VideoBackend:filename = gguf_filename or ""qwen_filename = h3_text_encoder_filename(filename)+ # Claimed before anything slow, the preflight included: it can spend minutes installing the+ # sd-cli prebuilt, and asset_repos is what stops the delete-cached guard admitting a delete+ # of the H3 companion repos mid-load, which a later claim cannot revoke. The download list+ # pulls from both, and neither is repo_id or base_repo. loaded_repo_ids() is the committed+ # twin; expected_bytes stays below, where the sizes are known.+ # begin_load publishes the same claim with _loading, covering the gap before this thread is+ # scheduled. This one is for load_pipeline, which never goes through begin_load.+ with self._lock:+ if self._load_token == token and self._loading is not None:+ self._loading.base_repo = fam.base_repo+ self._loading.asset_repos = (H3_GGUF_REPO, H3_COMPONENT_REPO)+# BEFORE the download, not after it. The H3-gated ensure, not the plain one: a build that# predates H3 runs fine and so clears the version() gate below, then aborts on the first# generation. That is the whole reason this gate exists, and running it after the four-file@@ -1588,11 +1613,6 @@ class VideoBackend:total = 0with self._lock:if self._load_token == token and self._loading is not None:- self._loading.base_repo = fam.base_repo- # The download list below pulls from the H3 companion repos too, and neither is- # repo_id or base_repo, so without this the delete-cached guard would let one be- # deleted out from under the in-flight load. The committed twin is loaded_repo_ids().- self._loading.asset_repos = (H3_GGUF_REPO, H3_COMPONENT_REPO)self._loading.expected_bytes = total or Noneresolved: list[Path] = []diff --git a/studio/backend/hub/services/models/deletion.py b/studio/backend/hub/services/models/deletion.pyindex 5a62cf362f6..dd3af996b20 100644--- a/studio/backend/hub/services/models/deletion.py+++ b/studio/backend/hub/services/models/deletion.py@@ -820,6 +820,23 @@ async def delete_cached_model_response()raise HTTPException(status_code = 400, detail = detail)try:+ # Re-derived now the scope is reserved, as only_if_orphan re-derives its own answer+ # below. The first read ran before the reservation existed, so a load starting in+ # between published its claim too late to be seen, and begin_delete misses it too:+ # image and video loads download directly rather than through a registry claim.+ try:+ blocks_detail = 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(+ status_code = 503,+ detail = _LOAD_STATE_UNVERIFIABLE_DETAIL,+ )+ if blocks_detail:+ raise HTTPException(+ status_code = 400,+ detail = blocks_detail,+ )return await asyncio.to_thread(_delete_cached_model_blocking,repo_id,diff --git a/studio/backend/tests/test_cached_gguf_routes.py b/studio/backend/tests/test_cached_gguf_routes.pyindex 0ff486967d5..3bc9d822d7f 100644--- a/studio/backend/tests/test_cached_gguf_routes.py+++ b/studio/backend/tests/test_cached_gguf_routes.py@@ -2793,6 +2793,44 @@ def test_delete_cached_refuses_loaded_native_companion_repo(monkeypatch):assert "Unload the model before deleting" in e.detail+def test_delete_cached_rechecks_the_load_guard_after_reserving_the_scope(monkeypatch):+ # The first guard runs before begin_delete reserves the repo, so a load starting in that gap+ # publishes its claim too late to be seen, and begin_delete misses it too: video and image+ # loads download directly rather than through a registry claim. Deleting anyway unlinks blobs+ # under the running load, so the second read is what refuses it.+ from fastapi import HTTPException+ from hub.services.models import deletion+ import core.inference.diffusion_engine_router as der+ import core.inference.video as video_mod++ _clear_chat_delete_guards(monkeypatch)+ monkeypatch.setattr(der, "get_active_diffusion_engine", _idle_diffusion_engine)++ reads = {"n": 0}++ def _backend():+ def _loading_repo_ids():+ reads["n"] += 1+ # Idle for the pre-reservation read, loading by the time the scope is reserved.+ return () if reads["n"] == 1 else ("unsloth/MiniMax-H3-GGUF",)++ return SimpleNamespace(+ status = lambda: {"loaded": False, "repo_id": None},+ loaded_repo_ids = lambda: (),+ loading_repo_ids = _loading_repo_ids,+ )++ monkeypatch.setattr(video_mod, "get_video_backend", _backend)++ try:+ asyncio.run(deletion.delete_cached_model_response("unsloth/MiniMax-H3-GGUF"))+ assert False, "expected HTTPException refusing the delete admitted before the load claim"+ except HTTPException as e:+ assert e.status_code == 400+ assert "Video model load is using this repo" in e.detail+ assert reads["n"] >= 2, "the guard must be re-read after the delete scope is reserved"++def test_delete_cached_refuses_repo_a_diffusion_load_is_downloading(monkeypatch):# status().loaded is still False while a background Images load downloads the repo, so loading_repo_ids() must refuse the delete.from fastapi import HTTPExceptiondiff --git a/studio/backend/tests/test_video_backend.py b/studio/backend/tests/test_video_backend.pyindex 6875df03140..043c8e002d1 100644--- a/studio/backend/tests/test_video_backend.py+++ b/studio/backend/tests/test_video_backend.py@@ -3081,6 +3081,124 @@ def test_direct_h3_native_load_uses_sd_cpp_path(monkeypatch):assert calls[0]["gguf_filename"] == "minimax_h3_fl2va-Q4_K_M.gguf"+def test_h3_native_load_claims_the_companion_repos_before_the_preflight(monkeypatch, tmp_path):+ # asset_repos stops the delete-cached guard dropping the H3 companion repos mid-load, and the+ # preflight can spend minutes installing the sd-cli prebuilt. A delete admitted in that window+ # is not revoked by claiming the repos later.+ from core.inference import video as video_mod+ from core.inference import sd_cpp_backend, sd_cpp_engine+ from core.inference.video_minimax_h3 import H3_COMPONENT_REPO, H3_GGUF_REPO++ class _Api:+ def __init__(self, **_kwargs):+ pass++ def model_info(self, *_args, **_kwargs):+ return _PlanInfo([])++ monkeypatch.setattr("huggingface_hub.HfApi", _Api)+ monkeypatch.setattr(+ video_mod,+ "resolve_diffusion_device_target",+ lambda: types.SimpleNamespace(backend = "cpu", device = "cpu", dtype = None),+ )+ monkeypatch.setattr(sd_cpp_backend, "_install_allowed", lambda: True)++ seen: list[tuple[str, ...]] = []++ def _ensure(**_kwargs):+ # What the delete-cached guard would see while the install runs.+ seen.append(backend._loading.asset_repos)+ return "/existing/sd-cli"++ monkeypatch.setattr(sd_cpp_backend, "ensure_h3_sd_cpp_binary", _ensure)+ monkeypatch.setattr(sd_cpp_backend, "sd_cpp_binary_vets_for_h3", lambda _b: True)++ class _Engine:+ def __init__(self, binary):+ self.binary = binary++ def version(self):+ return "stub-version"++ monkeypatch.setattr(sd_cpp_engine, "SdCppEngine", _Engine)++ def _download(_repo, wanted, *_args, **_kwargs):+ path = tmp_path / Path(wanted).name+ path.write_bytes(b"x")+ return str(path)++ monkeypatch.setattr("utils.hf_xet_fallback.hf_hub_download_with_xet_fallback", _download)++ backend = VideoBackend()+ fam = _detect_load_family("unsloth/MiniMax-H3-GGUF", None, "minimax-h3")+ assert fam is not None+ backend._loading = video_mod._VideoLoadingState(+ repo_id = "unsloth/MiniMax-H3-GGUF", base_repo = fam.base_repo+ )+ backend._load_token = 11++ backend._run_load_h3_native(+ fam = fam,+ token = 11,+ cancel_event = threading.Event(),+ repo_id = "unsloth/MiniMax-H3-GGUF",+ gguf_filename = "minimax_h3_fl2va-Q4_K_M.gguf",+ )++ assert seen == [(H3_GGUF_REPO, H3_COMPONENT_REPO)]+++def test_begin_load_publishes_the_h3_companion_claim_with_the_loading_state(+ fake_runtime, monkeypatch+):+ # begin_load returns as soon as the worker thread is scheduled, so a claim made in the worker+ # leaves a window where the guard sees only repo_id and base_repo and admits a delete of a+ # companion repo. Admitting it is the irreversible part, so the claim has to be published in+ # the same locked section as _loading.+ import threading+ from types import SimpleNamespace++ from core.inference.video_minimax_h3 import H3_COMPONENT_REPO, H3_GGUF_REPO++ backend = VideoBackend()+ # Never started: the window under test is before the load thread is scheduled.+ monkeypatch.setattr(+ threading, "Thread", lambda *a, **k: SimpleNamespace(start = lambda: None, daemon = True)+ )++ backend.begin_load(+ "unsloth/MiniMax-H3-GGUF",+ gguf_filename = "minimax_h3_fl2va-Q4_K_M.gguf",+ family_override = "minimax-h3",+ model_kind = "gguf",+ )++ claimed = backend.loading_repo_ids()+ assert H3_GGUF_REPO in claimed+ assert H3_COMPONENT_REPO in claimed+++def test_begin_load_claims_no_companion_repos_for_a_non_h3_family(fake_runtime, monkeypatch):+ # H3-native only: naming the companions on a pipeline load would block deletes of repos it+ # never reads.+ import threading+ from types import SimpleNamespace++ from core.inference.video_minimax_h3 import H3_COMPONENT_REPO, H3_GGUF_REPO++ backend = VideoBackend()+ monkeypatch.setattr(+ threading, "Thread", lambda *a, **k: SimpleNamespace(start = lambda: None, daemon = True)+ )++ backend.begin_load("Wan-AI/Wan2.2-TI2V-5B-Diffusers", family_override = "wan2.2-ti2v-5b")++ claimed = backend.loading_repo_ids()+ assert H3_GGUF_REPO not in claimed+ assert H3_COMPONENT_REPO not in claimed++def test_h3_native_load_honors_install_switch_and_maps_xpu_to_vulkan(monkeypatch, tmp_path):from core.inference import video as video_modfrom core.inference import sd_cpp_backend, sd_cpp_engine