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: make image-model companion assets reusable, visible, and safely removable (#8223)
Daniel Han90cd82bb15bf
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex 036e8b73c7b..983459e0e1c 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -5690,7 +5690,23 @@ def _resolve_base_repo(# base_model, both of which must stay the vendor id. An EXPLICIT base_repo is verbatim.base = canonical_base(tag)# Returns the UPSTREAM id; the swap happens at the fetch sites only.- return resolve_base_repo(fam, base)+ resolved = resolve_base_repo(fam, base)+ _remember_companion_base(repo_id, resolved)+ return resolved+++def _remember_companion_base(repo_id: str, base: str) -> None:+ """Record that *repo_id* takes its companions from *base*, for the delete/cleanup guards.++ A card ``base_model`` tag is the one input this resolver has that a later offline scan cannot+ reconstruct -- a GGUF pick caches only the .gguf, never the card -- so the link is written+ where it is decided. Additive and best-effort: a failure here must never fail a load.+ """+ try:+ from hub.utils.companion_assets import record_companion_link+ record_companion_link(repo_id, base)+ except Exception as exc: # noqa: BLE001 -- bookkeeping only+ logger.debug("diffusion.companion_link_record_failed: %s", exc)def _hf_base_model(repo_id: str, hf_token: Optional[str]) -> Optional[str]:diff --git a/studio/backend/core/inference/diffusion_families.py b/studio/backend/core/inference/diffusion_families.pyindex efcf694977d..7ab161112b6 100644--- a/studio/backend/core/inference/diffusion_families.py+++ b/studio/backend/core/inference/diffusion_families.py@@ -1064,6 +1064,21 @@ def sd_cpp_companion_only_repo_ids() -> frozenset[str]:return frozenset(r.strip().lower() for r in companions - loadable if r)+def sd_cpp_text_encoder_candidates(fam: DiffusionFamily) -> tuple[tuple[str, str, str], ...]:+ """EVERY text-encoder set an sd.cpp load of *fam* could pick, unioned.++ For the guard, not for a load. A load reads the GGUF header and picks one; a guard+ reconstructing a checkpoint it cannot open has no header, and for FLUX.2-klein a renamed 9B+ file carries no size token either, so the string fallback answers 4B and the 9B encoder the+ load actually fetched is left unprotected. Naming both costs a delete that is refused and+ saves one that strands an installed model.+ """+ sets = [fam.sd_cpp_text_encoders]+ if fam.name == "flux.2-klein":+ sets.append(_FLUX2_KLEIN_9B_SD_CPP_TEXT_ENCODERS)+ return tuple(dict.fromkeys(entry for group in sets for entry in group or ()))++def sd_cpp_text_encoders_for(fam: DiffusionFamily,repo_id: Optional[str] = None,diff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.pyindex 28cc34e57a4..7b21643b521 100644--- a/studio/backend/core/inference/sd_cpp_backend.py+++ b/studio/backend/core/inference/sd_cpp_backend.py@@ -800,6 +800,24 @@ class SdCppDiffusionBackend:inner_dim = self._flux2_inner_dim(repo_id, gguf_filename, fam, hf_token, allow_network = False)+ # Same link the diffusers resolver records, so the delete guard protects a native pick's+ # companions too -- and here that means the repos _asset_specs actually FETCHES. The+ # native engine does not read the diffusers base: FLUX.2 takes its VAE from+ # unsloth/FLUX.2-VAE and its encoders from another repo again, so recording only the base+ # left every repo the pick really depends on outside the guard, and an unloaded model's+ # encoder could be deleted while its GGUF stayed installed. Best-effort bookkeeping;+ # never fails a load.+ try:+ from hub.utils.companion_assets import record_companion_link+ for asset_repo in dict.fromkeys(+ r+ for r, _f, kind in self._asset_specs(repo_id, gguf_filename, fam, inner_dim)+ if kind != "diffusion_model"+ ):+ record_companion_link(repo_id, asset_repo)+ record_companion_link(repo_id, base)+ except Exception as exc: # noqa: BLE001+ logger.debug("sd_cpp.companion_link_record_failed: %s", exc)with self._lock:if self._loading is not None and self._loading.error is None:raise RuntimeError("A diffusion load is already in progress.")@@ -897,6 +915,23 @@ class SdCppDiffusionBackend:self._loading.asset_repos = tuple(dict.fromkeys(r for r, _f, kind in specs if kind != "diffusion_model"))+ # And record them, from the SAME post-probe specs. begin_load records what it can, but+ # it resolves the header offline, so a remote or renamed FLUX.2-klein 9B checkpoint+ # with no cached probe records the default 4B encoder while this load fetches the 9B+ # one. Whatever that leaves unrecorded is a companion the delete guard would let go+ # while its GGUF is still installed. Recorded on the FETCH ids too, since a gated+ # mirror or a cached community repack is where the bytes actually land.+ try:+ from hub.utils.companion_assets import record_companion_link+ for asset_repo in dict.fromkeys(+ rid+ for repo, _f, kind in specs+ if kind != "diffusion_model"+ for rid in (repo, fetch_repo.get(repo, repo))+ ):+ record_companion_link(repo_id, asset_repo)+ except Exception as exc: # noqa: BLE001 -- bookkeeping never fails a load+ logger.debug("sd_cpp.companion_link_record_failed: %s", exc)# Same preflight the plan runs, on POST-swap repos: catch a gated companion here, not# 15 GiB into the prefetch, without refusing one an ungated mirror stands in for. The# plan alone is not enough: the images page falls back to this load when it fails.diff --git a/studio/backend/hub/routes/inventory.py b/studio/backend/hub/routes/inventory.pyindex dc3e3641bc3..b3bc0b310da 100644--- a/studio/backend/hub/routes/inventory.py+++ b/studio/backend/hub/routes/inventory.py@@ -27,17 +27,20 @@ from hub.schemas.inventory import (CachedGgufResponse,CachedModelsResponse,DeleteCachedModelResponse,+ DeleteImpactResponse,GgufVariantsResponse,HiddenModelsResponse,LocalModelListResponse,ModelsFolderResponse,RecommendedFoldersResponse,+ OrphanCompanionsResponse,RemoveScanFolderResponse,ScanFolderInfo,ScanFoldersResponse,)from hub.services.models import (cache_inventory,+ companion_cleanup,deletion,downloads,folder_browser,@@ -225,6 +228,27 @@ async def list_hidden_models(current_subject: str = Depends(get_current_subject)return HiddenModelsResponse(needles = needles, exact_ids = exact_ids, exact_paths = exact_paths)[email protected]("/delete-impact", response_model = DeleteImpactResponse)+async def delete_impact(+ repo_id: str = Body(...),+ variant: Optional[str] = Body(None),+ current_subject: str = Depends(get_current_subject),+):+ """Preview a delete: bytes reclaimed, shared assets retained, and anything blocking it.++ POST rather than GET because a repo id is a path-shaped value and this reads no cache of its+ own; it is a pure query and mutates nothing.+ """+ return await companion_cleanup.delete_impact_response(repo_id, variant)++[email protected]("/orphan-companions", response_model = OrphanCompanionsResponse)+async def orphan_companions(current_subject: str = Depends(get_current_subject)):+ """Cached companion assets no installed model needs. Listing only; removal goes through+ the ordinary guarded delete."""+ return await companion_cleanup.orphan_companions_response()++@router.delete("/delete-cached",response_model = DeleteCachedModelResponse,@@ -234,7 +258,11 @@ async def delete_cached_model(repo_id: str = Body(...),variant: Optional[str] = Body(None),cache_path: Optional[str] = Body(None),+ # Free up space's precondition: refuse with 409 if the repo is no longer an unused asset.+ only_if_orphan: bool = Body(False),hf_token: Optional[str] = Depends(get_hf_token),current_subject: str = Depends(get_current_subject),):- return await deletion.delete_cached_model_response(repo_id, variant, hf_token, cache_path)+ return await deletion.delete_cached_model_response(+ repo_id, variant, hf_token, cache_path, only_if_orphan+ )diff --git a/studio/backend/hub/schemas/inventory.py b/studio/backend/hub/schemas/inventory.pyindex 8a44654421b..4c5209b270f 100644--- a/studio/backend/hub/schemas/inventory.py+++ b/studio/backend/hub/schemas/inventory.py@@ -296,6 +296,48 @@ class DeleteCachedModelResponse(BaseModel):variant: Optional[str] = None+class CompanionAssetInfo(BaseModel):+ """A companion base repo (text encoders, VAE, tokenizer, configs) in the cache."""++ repo_id: str+ size_bytes: int = Field(0, description = "Real on-disk blob bytes, deduped per blob")+ needed_by: List[str] = Field(+ default_factory = list,+ description = "Installed models that still need it; empty means it is reclaimable",+ )+++class DeleteImpactResponse(BaseModel):+ """What a pending delete would actually do, so the confirm dialog can say it."""++ repo_id: str+ variant: Optional[str] = None+ reclaimed_bytes: int = Field(0, description = "Bytes this delete frees, from the cache scan")+ retained_companions: List[CompanionAssetInfo] = Field(+ default_factory = list,+ description = "Shared assets that stay because another installed model needs them",+ )+ freeable_companions: List[CompanionAssetInfo] = Field(+ default_factory = list,+ description = "Shared assets that become orphaned by this delete and can then be removed",+ )+ blocked_by: List[str] = Field(+ default_factory = list,+ description = "Installed models that make this delete impossible (shared-asset guard)",+ )+++class OrphanCompanionInfo(BaseModel):+ repo_id: str+ size_bytes: int = 0+ cache_path: Optional[str] = None+++class OrphanCompanionsResponse(BaseModel):+ companions: List[OrphanCompanionInfo] = Field(default_factory = list)+ total_bytes: int = 0++class BrowseEntry(BaseModel):"""A directory entry surfaced by the folder browser."""diff --git a/studio/backend/hub/services/models/companion_cleanup.py b/studio/backend/hub/services/models/companion_cleanup.pynew file mode 100644index 00000000000..1939358324b--- /dev/null+++ b/studio/backend/hub/services/models/companion_cleanup.py@@ -0,0 +1,283 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Delete preflight and orphaned-companion cleanup for image-model assets.++Three answers live here, all derived from the cache scan at call time (see+``hub.utils.companion_assets`` for why nothing is counted):++ :func:`delete_impact_response` what a pending delete reclaims, and what it leaves behind+ :func:`companion_dependents` who still needs a companion base, used as a delete guard+ :func:`orphan_companions_response` companion bases no installed model needs any more++Sizes are real on-disk blob bytes from the HF cache scan, deduped per blob, not Hub metadata:+the number in a delete dialog has to be the number the disk gives back.+"""++from __future__ import annotations++import asyncio+from pathlib import Path+from typing import Optional++from fastapi import HTTPException+from loggers import get_logger++from hub.utils import companion_assets+from hub.utils.gguf import gguf_variant_key+from hub.services.models import cache_inventory+from hub.services.models.common import _is_main_gguf_filename+from hub.utils.paths import is_valid_gguf_variant as _is_valid_gguf_variant+from hub.utils.paths import is_valid_repo_id as _is_valid_repo_id++logger = get_logger(__name__)+++def _repo_blob_bytes(repo_info, *, only = None) -> int:+ """On-disk bytes of *repo_info*, deduped by blob so a file shared across revisions counts once.++ ``only`` is an optional predicate on the snapshot-relative file name.+ """+ unique: dict[str, int] = {}+ for revision in getattr(repo_info, "revisions", ()) or ():+ rev_id = getattr(revision, "commit_hash", None) or str(id(revision))+ snapshot = getattr(revision, "snapshot_path", None)+ for f in getattr(revision, "files", ()) or ():+ name = str(getattr(f, "file_name", "") or "")+ path = getattr(f, "file_path", None)+ if path and snapshot:+ try:+ name = Path(path).relative_to(Path(snapshot)).as_posix()+ except ValueError:+ pass+ if only is not None and not only(name):+ continue+ blob_path = getattr(f, "blob_path", None)+ size = int(getattr(f, "size_on_disk", 0) or 0)+ unique[str(blob_path) if blob_path else f"{rev_id}:{name}"] = size+ return sum(unique.values())+++# One definition, so the orphan listing and the delete preview cannot disagree about which cached+# repos are leftovers (see companion_assets.repo_holds_denoiser).+_repo_holds_denoiser = companion_assets.repo_holds_denoiser+++def _repos_by_id(cache_scans) -> dict[str, list]:+ out: dict[str, list] = {}+ for scan in cache_scans or ():+ for repo in getattr(scan, "repos", ()) or ():+ try:+ if str(getattr(repo, "repo_type", "")) != "model":+ continue+ key = str(getattr(repo, "repo_id", "") or "").strip().lower()+ except Exception: # noqa: BLE001 -- one unreadable row never hides the rest+ continue+ if key:+ out.setdefault(key, []).append(repo)+ return out+++def _variant_keys(repo_info, variant: str) -> set[str]:+ """The variant keys *variant* names in *repo_info*, from the destructive path's own resolver.++ The inventory and the delete both identify a row by ``gguf_variant_key``, which for a+ path-qualified checkpoint (``distilled/ltx-2.3-22b-distilled-Q6_K``) is not the bare quant+ label. Comparing labels here made the preview miss the file entirely: 0 B reclaimed, and the+ last checkpoint of a repo read as if a sibling survived, so its companions were described as+ retained rather than freed."""+ from hub.services.models.deletion import _variant_keys_to_delete+ return {key.lower() for key in _variant_keys_to_delete(repo_info, variant)}+++def _variant_bytes(repo_info, variant: str) -> int:+ wanted = _variant_keys(repo_info, variant)++ def _matches(name: str) -> bool:+ return _is_main_gguf_filename(name) and gguf_variant_key(name).lower() in wanted++ return _repo_blob_bytes(repo_info, only = _matches)+++def _remaining_main_gguf_variants(repo_info, *, excluding: Optional[str] = None) -> set[str]:+ skip = _variant_keys(repo_info, excluding) if excluding else set()+ found: set[str] = set()+ for revision in getattr(repo_info, "revisions", ()) or ():+ snapshot = getattr(revision, "snapshot_path", None)+ for f in getattr(revision, "files", ()) or ():+ name = str(getattr(f, "file_name", "") or "")+ path = getattr(f, "file_path", None)+ if path and snapshot:+ try:+ name = Path(path).relative_to(Path(snapshot)).as_posix()+ except ValueError:+ pass+ if not _is_main_gguf_filename(name):+ continue+ key = gguf_variant_key(name).lower()+ if key and key not in skip:+ found.add(key)+ return found+++def companion_dependents(+ base_repo_id: str,+ cache_scans = None,+ *,+ ignore_repo_ids = (),+) -> list[str]:+ """Installed checkpoints that would still need *base_repo_id* after ignoring *ignore_repo_ids*.++ Sorted for a stable message. Empty means the base is safe to remove.+ """+ scans = cache_scans if cache_scans is not None else cache_inventory.all_hf_cache_scans()+ required = companion_assets.required_companion_bases(scans, ignore_repo_ids = ignore_repo_ids)+ return sorted(required.get((base_repo_id or "").strip().lower(), set()))+++def _variant_is_a_required_companion_asset(repo_id: str, variant: str) -> bool:+ """The deletion guard's predicate, shared so the preview and the refusal cannot disagree."""+ from hub.services.models.deletion import _variant_is_a_required_companion_asset as _impl+ return _impl(repo_id, variant)+++def _delete_impact_blocking(repo_id: str, variant: Optional[str]) -> dict:+ scans = cache_inventory.all_hf_cache_scans()+ by_id = _repos_by_id(scans)+ key = repo_id.strip().lower()+ repos = by_id.get(key, [])++ reclaimed = 0+ for repo_info in repos:+ reclaimed += _variant_bytes(repo_info, variant) if variant else _repo_blob_bytes(repo_info)++ # Would this delete leave the repo with no runnable checkpoint? Only then can its companions+ # become reclaimable; while a sibling quant survives they stay in use.+ removes_last_checkpoint = True+ if variant:+ for repo_info in repos:+ if _remaining_main_gguf_variants(repo_info, excluding = variant):+ removes_last_checkpoint = False+ break++ ignore = [repo_id] if removes_last_checkpoint else []+ required_after = companion_assets.required_companion_bases(scans, ignore_repo_ids = ignore)++ # Companion bases THIS pick uses, from the same derivation the loader's resolver feeds.+ own_bases = companion_assets.required_companion_bases(+ [_SingleRepoScan(repos)] if repos else [],+ )+ retained: list[dict] = []+ freeable: list[dict] = []+ offerable = companion_assets.known_companion_base_ids()+ for base_key in sorted(own_bases):+ base_repos = by_id.get(base_key, [])+ if not base_repos:+ continue+ base_bytes = sum(_repo_blob_bytes(r) for r in base_repos)+ display = str(getattr(base_repos[0], "repo_id", base_key))+ holders = sorted(required_after.get(base_key, set()))+ entry = {"repo_id": display, "size_bytes": base_bytes, "needed_by": holders}+ if holders:+ retained.append(entry)+ # The SAME offerability test orphan_companions_response applies, because this row is a+ # pointer at that list. A borrowed chat GGUF repo (the native Qwen-Image text encoder) is a+ # curated companion id but holds a denoiser, so the orphan endpoint skips it; advertising+ # it here sent the user to Free up space to remove a row that is never there. Per copy,+ # like the listing: one pipeline copy in another cache root must not hide a companion-only+ # copy that Free up space really will offer.+ elif base_key in offerable and any(not _repo_holds_denoiser(r) for r in base_repos):+ freeable.append(entry)+ # Else: a base only a recorded link names. It is unheld, but the orphan endpoint is+ # table-only by design (a mis-recorded link must never turn an unrelated repo into a+ # delete candidate), so advertising it here pointed the user at a Free up space list it+ # will never appear in.++ return {+ "repo_id": repo_id,+ "variant": variant,+ "reclaimed_bytes": reclaimed,+ "retained_companions": retained,+ "freeable_companions": freeable,+ # Same predicate the destructive path uses, so the dialog says what the delete will do.+ # A variant delete usually cannot strand anything, but the native Qwen-Image encoder is a+ # named quant inside a chat GGUF repo, and previewing only whole-repo deletes left Delete+ # enabled on it and the refusal to arrive after the user confirmed.+ "blocked_by": (+ companion_dependents(repo_id, scans, ignore_repo_ids = [repo_id])+ if companion_assets.is_companion_base(repo_id)+ and (variant is None or _variant_is_a_required_companion_asset(repo_id, variant))+ else []+ ),+ }+++class _SingleRepoScan:+ """Adapter presenting a fixed repo list with the attribute the derivation reads."""++ def __init__(self, repos):+ self.repos = repos+++async def delete_impact_response(repo_id: str, variant: Optional[str] = None) -> dict:+ """What a delete of *repo_id* (/*variant*) would reclaim, retain, and be blocked by."""+ if not _is_valid_repo_id(repo_id):+ raise HTTPException(status_code = 400, detail = "Invalid repo_id format")+ variant = (variant or "").strip() or None+ if variant is not None and not _is_valid_gguf_variant(variant):+ raise HTTPException(status_code = 400, detail = f"Invalid gguf_variant: {variant!r}")+ return await asyncio.to_thread(_delete_impact_blocking, repo_id, variant)+++def _orphan_companions_blocking() -> dict:+ scans = cache_inventory.all_hf_cache_scans()+ by_id = _repos_by_id(scans)+ required = companion_assets.required_companion_bases(scans)+ known = companion_assets.known_companion_base_ids()++ orphans: list[dict] = []+ for base_key in sorted(known & set(by_id)):+ if required.get(base_key):+ continue+ repos = by_id[base_key]+ # A repo that holds a runnable denoiser is a model the user installed, not a leftover.+ # Several curated bases are perfectly good pipelines in their own right, so this is the+ # difference between the two ways the same repo id reaches the cache: a companion fetch+ # takes everything BUT the denoiser folder (``_base_file_downloaded`` skips+ # ``transformer/``), while a pipeline pick takes it. Its presence is therefore the+ # derived answer to "did the user ask for this repo, or did a GGUF drag it in".+ # Per COPY, not pooled: the loop below emits one row per cache root because a delete is+ # scoped to one, so a full pipeline copy in one root must not suppress an orphaned+ # companion-only copy in another that nothing can otherwise reclaim.+ repos = [r for r in repos if not _repo_holds_denoiser(r)]+ if not repos:+ continue+ # One row per cache root. A delete is scoped to a single cache, so pooling copies from+ # several would promise bytes one removal cannot deliver.+ for repo in repos:+ size = _repo_blob_bytes(repo)+ if size <= 0:+ continue+ # The repo dir itself, not its parent: ``scoped_delete_root`` resolves the owning+ # cache by walking up to the ``models--`` component, so a bare root resolves to+ # nothing and the delete comes back "Invalid cache_path".+ try:+ cache_path = str(Path(getattr(repo, "repo_path")))+ except (TypeError, OSError):+ cache_path = None+ orphans.append(+ {+ "repo_id": str(getattr(repo, "repo_id", base_key)),+ "size_bytes": size,+ "cache_path": cache_path,+ }+ )+ return {+ "companions": orphans,+ "total_bytes": sum(o["size_bytes"] for o in orphans),+ }+++async def orphan_companions_response() -> dict:+ """Cached companion bases that no installed model needs. Listing only; nothing is deleted."""+ return await asyncio.to_thread(_orphan_companions_blocking)diff --git a/studio/backend/hub/services/models/deletion.py b/studio/backend/hub/services/models/deletion.pyindex f2cb0936577..82b3c1406a9 100644--- a/studio/backend/hub/services/models/deletion.py+++ b/studio/backend/hub/services/models/deletion.py@@ -704,17 +704,71 @@ def _video_blocks_delete(repo_id: str) -> Optional[str]:return None+def _is_companion_base_repo(repo_id: str) -> bool:+ """Whether *repo_id* is a curated image-family companion base (pure table lookup, no I/O)."""+ try:+ from hub.utils import companion_assets+ return companion_assets.is_companion_base(repo_id)+ except Exception as e: # noqa: BLE001 -- an unavailable table just skips the extra guard+ logger.debug(f"Companion base classification unavailable for {repo_id}: {e}")+ return False+++def _variant_is_a_required_companion_asset(repo_id: str, variant: str) -> bool:+ """Whether *variant* names a file an installed checkpoint's native load actually opens.++ Not "would this empty the repo": the asset is a FIXED filename, so a sibling quant left+ behind substitutes for nothing. Fails CLOSED, and cheaply -- a True here only runs the+ dependants check, which answers "nobody needs it" for every ordinary repo and lets the+ delete through.+ """+ from hub.services.models import cache_inventory+ from hub.utils import companion_assets+ from hub.utils.gguf import extract_quant_label++ try:+ wanted = companion_assets.required_companion_asset_files(+ cache_inventory.all_hf_cache_scans()+ ).get((repo_id or "").strip().lower(), set())+ target = (variant or "").strip().lower()+ return any(extract_quant_label(name).lower() == target for name in wanted)+ except Exception as exc: # noqa: BLE001 -- an unreadable cache is not permission to delete+ logger.warning(f"Could not check companion assets for {repo_id}: {exc}")+ return True+++def _companion_share_blocks_delete(repo_id: str) -> Optional[str]:+ """The 400 detail when installed models still need *repo_id*'s shared assets, else None."""+ from hub.services.models import companion_cleanup++ holders = companion_cleanup.companion_dependents(repo_id, ignore_repo_ids = [repo_id])+ if not holders:+ return None+ shown = ", ".join(holders[:3])+ extra = len(holders) - 3+ if extra > 0:+ shown = f"{shown} and {extra} more"+ return (+ f"{repo_id} holds the text encoder, VAE and tokenizer that {shown} still "+ "needs. Delete those models first, then remove these shared assets."+ )++async def delete_cached_model_response(repo_id: str,variant: Optional[str] = None,hf_token: Optional[str] = None,cache_path: Optional[str] = None,+ only_if_orphan: bool = False,):"""Delete a cached model repo (or a specific GGUF variant) from the HF cache.When *variant* is provided, only the GGUF files matching that quant labelare removed (e.g. ``UD-Q4_K_XL``). Otherwise the entire repo is deleted.Refuses if the model is currently loaded for inference.++ *only_if_orphan* is Free up space's precondition: 409 rather than delete when the repo has+ become an installed checkpoint since the list the caller is acting on was built."""if not _is_valid_repo_id(repo_id):raise HTTPException(status_code = 400, detail = "Invalid repo_id format")@@ -761,7 +815,12 @@ async def delete_cached_model_response(raise HTTPException(status_code = 400, detail = detail)try:return await asyncio.to_thread(- _delete_cached_model_blocking, repo_id, variant, hf_token, cache_path+ _delete_cached_model_blocking,+ repo_id,+ variant,+ hf_token,+ cache_path,+ only_if_orphan = only_if_orphan,)finally:downloads.registry.end_delete(repo_key, variant)@@ -773,7 +832,91 @@ def _delete_cached_model_blocking(variant: Optional[str],hf_token: Optional[str],cache_path: Optional[str] = None,+ *,+ only_if_orphan: bool = False,) -> dict:+ # Free up space asks for this: the row it is removing was an orphan when the list was built,+ # and the list can be minutes old. A download of that same repo finishing in the background+ # turns it into an installed checkpoint, and neither guard below catches that -- begin_delete+ # only refuses a download still in flight, and the companion guard deliberately ignores the+ # target as its own dependent. Re-derived here, after begin_delete has closed the repo to new+ # downloads, so the answer cannot go stale between the check and the unlink.+ if only_if_orphan:+ from hub.services.models import companion_cleanup+ from hub.utils import companion_assets++ try:+ copies = companion_cleanup._repos_by_id(cache_inventory.all_hf_cache_scans()).get(+ repo_id.strip().lower(), []+ )+ # Only the copy being removed. The orphan listing emits one row per cache root+ # precisely because a delete is scoped to one, so a full-pipeline copy in another+ # remembered cache must not veto removing the companion-only copy that was listed.+ if cache_path:+ wanted = Path(cache_path)+ copies = [+ r+ for r in copies+ if getattr(r, "repo_path", None) and Path(getattr(r, "repo_path")) == wanted+ ]+ if not copies:+ # No fallback to the other copies. An empty match means the target root is+ # not in this scan (its scan failed, or the copy is gone), and the delete+ # below can still purge that directory by path -- so concluding "orphan" from+ # copies we did not look at is exactly the fail-open this precondition exists+ # to prevent. Raising here lands in the fail-closed 503 below.+ raise RuntimeError(f"cache root not present in the scan: {cache_path}")+ still_orphan = not any(companion_assets.repo_holds_denoiser(repo) for repo in copies)+ except Exception as e:+ logger.warning(f"Orphan re-check failed for {repo_id}; refusing delete: {e}")+ raise HTTPException(+ status_code = 503,+ detail = ("Couldn't confirm these assets are still unused. Try again in a moment."),+ )+ if not still_orphan:+ raise HTTPException(+ status_code = 409,+ detail = (+ f"{repo_id} now holds an installed model, so it is no longer an unused "+ "asset. Reopen Free up space to see the current list."+ ),+ )++ # A companion base repo carries the text encoders, VAE and tokenizer for every quant of its+ # family, so removing it while one is installed leaves that quant unloadable with nothing on+ # screen to say why. Derived from what is installed right now, never from a stored count, and+ # only for a WHOLE-repo delete: a variant delete cannot touch another repo. Deleting the+ # dependants first makes the base an orphan, which Free up space then offers.+ #+ # Here rather than in the async caller so it shares this function's cache walk and its stubs:+ # the check IS part of the destructive stage, and a caller that replaces that stage should not+ # end up with half of it still running.+ # A variant delete normally cannot touch another repo, so the guard is a whole-repo check.+ # The exception is a companion whose asset IS a named GGUF variant: native Qwen-Image opens+ # exactly Qwen2.5-VL-7B-Instruct-Q4_K_M.gguf inside a chat GGUF repo, so removing that one+ # quant strands the image checkpoint however many siblings remain, and none of them is a+ # substitute for a fixed filename. A FLAG, never a rewrite of `variant`: that name is the+ # destructive scope, and widening it here would delete every revision and manifest the user+ # did not ask for, and purge a sibling quant out from under an in-flight download.+ guard_this_delete = variant is None or _variant_is_a_required_companion_asset(repo_id, variant)+ if guard_this_delete and _is_companion_base_repo(repo_id):+ # Fails CLOSED, and only here: the lookup above already established this repo IS a+ # companion base, so an unreadable cache means the dependants cannot be enumerated, not+ # that there are none. Every other repo skips the check entirely and is unaffected.+ try:+ shared_detail = _companion_share_blocks_delete(repo_id)+ except Exception as e:+ logger.warning(f"Companion dependency check failed for {repo_id}; refusing delete: {e}")+ raise HTTPException(+ status_code = 503,+ detail = (+ "Couldn't check whether other installed models still need these shared "+ "assets. Try again in a moment."+ ),+ )+ if shared_detail:+ raise HTTPException(status_code = 400, detail = shared_detail)+try:# If a sibling quant is downloading concurrently, restrict this delete to# the variant's own files and leave the shared mmproj companion for it.diff --git a/studio/backend/hub/tests/test_companion_assets.py b/studio/backend/hub/tests/test_companion_assets.pynew file mode 100644index 00000000000..e93f200b82a--- /dev/null+++ b/studio/backend/hub/tests/test_companion_assets.py@@ -0,0 +1,864 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Reuse, preflight and deletion of shared image-model companion assets (issue #8116).++The shape under test is the reporter's: ``unsloth/FLUX.2-klein-4B-GGUF`` holding two quants,+and one cached copy of ``black-forest-labs/FLUX.2-klein-4B`` carrying the 8.23 GB of text+encoder, VAE, tokenizer and configs that both quants load through.+"""++from __future__ import annotations++import asyncio+from types import SimpleNamespace++import pytest+from fastapi import HTTPException++from hub.services.models import cache_inventory, companion_cleanup, deletion+from hub.utils import companion_assets++GGUF_REPO = "unsloth/FLUX.2-klein-4B-GGUF"+BASE_REPO = "black-forest-labs/FLUX.2-klein-4B"+# Real byte counts, measured from a cache holding exactly this pair.+Q2_K_BYTES = 1_827_807_808+Q4_K_M_BYTES = 2_604_311_104+COMPANION_BYTES = 8_229_021_460++[email protected](autouse = True)+def _isolated_state_root(monkeypatch, tmp_path):+ """Companion links live under the app cache root; keep each test to its own."""+ monkeypatch.setattr("utils.paths.storage_roots.cache_root", lambda: tmp_path / "app-cache")+++def _file(+ name: str,+ size: int,+ *,+ snapshot: str = "/cache/snap",+):+ return SimpleNamespace(+ file_name = name.rsplit("/", 1)[-1],+ file_path = f"{snapshot}/{name}",+ blob_path = f"/cache/blobs/{name.replace('/', '_')}",+ size_on_disk = size,+ )+++def _repo(+ repo_id: str,+ files,+ *,+ cache: str = "/cache",+):+ snapshot = f"{cache}/models--{repo_id.replace('/', '--')}/snapshots/rev1"+ return SimpleNamespace(+ repo_id = repo_id,+ repo_type = "model",+ repo_path = f"{cache}/models--{repo_id.replace('/', '--')}",+ revisions = [+ SimpleNamespace(+ commit_hash = "rev1",+ snapshot_path = snapshot,+ files = [_file(name, size, snapshot = snapshot) for name, size in files],+ )+ ],+ )+++def _gguf_repo(*quants):+ return _repo(GGUF_REPO, [(f"flux-2-klein-4b-{q}.gguf", size) for q, size in quants])+++def _base_repo(repo_id: str = BASE_REPO):+ return _repo(+ repo_id,+ [+ ("model_index.json", 460),+ ("text_encoder/model-00001-of-00002.safetensors", COMPANION_BYTES - 1_000_000),+ ("vae/diffusion_pytorch_model.safetensors", 900_000),+ ("tokenizer/tokenizer.json", 99_540),+ ],+ )+++def _install(monkeypatch, *repos):+ scans = [SimpleNamespace(repos = list(repos))]+ monkeypatch.setattr(cache_inventory, "all_hf_cache_scans", lambda: scans)+ monkeypatch.setattr(companion_cleanup.cache_inventory, "all_hf_cache_scans", lambda: scans)+ return scans+++# --------------------------------------------------------------------------------------------+# 1. Compatible quants reuse ONE cached copy of the companion assets.+# --------------------------------------------------------------------------------------------+++def test_two_quants_of_one_family_resolve_to_a_single_companion_base():+ """Both quants derive the same base id, so the cache holds one copy, not two."""+ scans = [SimpleNamespace(repos = [_gguf_repo(("Q2_K", Q2_K_BYTES), ("Q4_K_M", Q4_K_M_BYTES))])]+ required = companion_assets.required_companion_bases(scans)+ assert BASE_REPO.lower() in required+ assert required[BASE_REPO.lower()] == {GGUF_REPO}+++# --------------------------------------------------------------------------------------------+# 2. Deletion shows what is reclaimed and what remains.+# --------------------------------------------------------------------------------------------+++def test_deleting_one_of_two_quants_retains_the_companions(monkeypatch):+ _install(monkeypatch, _gguf_repo(("Q2_K", Q2_K_BYTES), ("Q4_K_M", Q4_K_M_BYTES)), _base_repo())+ impact = asyncio.run(companion_cleanup.delete_impact_response(GGUF_REPO, "Q2_K"))+ assert impact["reclaimed_bytes"] == Q2_K_BYTES+ retained = impact["retained_companions"]+ assert [r["repo_id"] for r in retained] == [BASE_REPO]+ assert retained[0]["size_bytes"] == COMPANION_BYTES+ # The surviving quant is named as the reason, so the dialog can say who is holding it.+ assert retained[0]["needed_by"] == [GGUF_REPO]+ assert impact["freeable_companions"] == []+++def test_deleting_the_last_quant_reports_the_companions_as_freeable(monkeypatch):+ _install(monkeypatch, _gguf_repo(("Q4_K_M", Q4_K_M_BYTES)), _base_repo())+ impact = asyncio.run(companion_cleanup.delete_impact_response(GGUF_REPO, "Q4_K_M"))+ assert impact["reclaimed_bytes"] == Q4_K_M_BYTES+ assert impact["retained_companions"] == []+ freeable = impact["freeable_companions"]+ assert [f["repo_id"] for f in freeable] == [BASE_REPO]+ assert freeable[0]["size_bytes"] == COMPANION_BYTES+ assert freeable[0]["needed_by"] == []+++def test_whole_repo_delete_reclaims_every_quant(monkeypatch):+ _install(monkeypatch, _gguf_repo(("Q2_K", Q2_K_BYTES), ("Q4_K_M", Q4_K_M_BYTES)), _base_repo())+ impact = asyncio.run(companion_cleanup.delete_impact_response(GGUF_REPO))+ assert impact["reclaimed_bytes"] == Q2_K_BYTES + Q4_K_M_BYTES+ assert [f["repo_id"] for f in impact["freeable_companions"]] == [BASE_REPO]+++# --------------------------------------------------------------------------------------------+# 3. Shared assets are not removed while another installed model needs them. ADVERSARIAL.+# --------------------------------------------------------------------------------------------+++def test_shared_base_cannot_be_deleted_while_a_quant_is_installed(monkeypatch):+ """The whole point of the issue: this delete succeeded before the guard, and silently+ left both installed quants unloadable."""+ _install(monkeypatch, _gguf_repo(("Q2_K", Q2_K_BYTES), ("Q4_K_M", Q4_K_M_BYTES)), _base_repo())+ with pytest.raises(HTTPException) as excinfo:+ asyncio.run(deletion.delete_cached_model_response(BASE_REPO))+ assert excinfo.value.status_code == 400+ assert GGUF_REPO in excinfo.value.detail+ assert "Delete those models first" in excinfo.value.detail+++def test_shared_base_delete_is_still_blocked_by_a_single_remaining_quant(monkeypatch):+ _install(monkeypatch, _gguf_repo(("Q4_K_M", Q4_K_M_BYTES)), _base_repo())+ with pytest.raises(HTTPException) as excinfo:+ asyncio.run(deletion.delete_cached_model_response(BASE_REPO))+ assert excinfo.value.status_code == 400+++def test_shared_base_delete_is_blocked_through_the_ungated_mirror_identity(monkeypatch):+ """The same logical base has two ids. Deleting either must be refused while a quant needs it."""+ gguf = _repo("unsloth/FLUX.1-schnell-GGUF", [("flux1-schnell-Q4_K_M.gguf", Q4_K_M_BYTES)])+ _install(+ monkeypatch,+ gguf,+ _base_repo("unsloth/FLUX.1-schnell"),+ _base_repo("black-forest-labs/FLUX.1-schnell"),+ )+ for identity in ("unsloth/FLUX.1-schnell", "black-forest-labs/FLUX.1-schnell"):+ with pytest.raises(HTTPException) as excinfo:+ asyncio.run(deletion.delete_cached_model_response(identity))+ assert excinfo.value.status_code == 400, identity+++def test_a_base_reached_only_through_a_card_tag_is_still_protected(monkeypatch):+ """A GGUF pick caches no model card, so family detection alone answers the family DEFAULT+ base. The checkpoint's own identity names the variant it needs, and the link the resolver+ recorded at load time confirms it."""+ gguf = _repo("unsloth/FLUX.2-klein-9B-GGUF", [("flux-2-klein-9b-Q4_K_M.gguf", Q4_K_M_BYTES)])+ other_base = "black-forest-labs/FLUX.2-klein-9B"+ _install(monkeypatch, gguf, _base_repo(other_base))+ # Before any load has been recorded: the id says klein-9B, so the curated klein-9B base is+ # derived even though the family default is klein-4B.+ assert companion_cleanup.companion_dependents(other_base) == ["unsloth/FLUX.2-klein-9B-GGUF"]+ companion_assets.record_companion_link("unsloth/FLUX.2-klein-9B-GGUF", other_base)+ assert companion_cleanup.companion_dependents(other_base) == ["unsloth/FLUX.2-klein-9B-GGUF"]+ with pytest.raises(HTTPException) as excinfo:+ asyncio.run(deletion.delete_cached_model_response(other_base))+ assert excinfo.value.status_code == 400+++def test_a_link_for_an_uninstalled_checkpoint_does_not_protect_anything(monkeypatch):+ """Links are filtered by what is installed, so a stale one cannot strand assets forever."""+ companion_assets.record_companion_link(GGUF_REPO, BASE_REPO)+ _install(monkeypatch, _base_repo())+ assert companion_cleanup.companion_dependents(BASE_REPO) == []+++def test_delete_of_a_companion_base_fails_closed_when_the_cache_cannot_be_read(monkeypatch):+ """Unable to enumerate dependants is not the same as having none."""++ def _boom():+ raise OSError("cache unreadable")++ monkeypatch.setattr(cache_inventory, "all_hf_cache_scans", _boom)+ monkeypatch.setattr(companion_cleanup.cache_inventory, "all_hf_cache_scans", _boom)+ with pytest.raises(HTTPException) as excinfo:+ asyncio.run(deletion.delete_cached_model_response(BASE_REPO))+ assert excinfo.value.status_code == 503+++def test_the_guard_leaves_ordinary_repos_alone(monkeypatch):+ """Only a known companion base takes the extra check, so a chat GGUF is untouched by it."""+ assert not companion_assets.is_companion_base("unsloth/Qwen3-8B-GGUF")+ assert companion_assets.is_companion_base(BASE_REPO)+++# --------------------------------------------------------------------------------------------+# 4. Orphaned companion assets can be found and removed without hand-editing the HF cache.+# --------------------------------------------------------------------------------------------+++def test_orphan_listing_is_empty_while_a_quant_is_installed(monkeypatch):+ _install(monkeypatch, _gguf_repo(("Q4_K_M", Q4_K_M_BYTES)), _base_repo())+ result = asyncio.run(companion_cleanup.orphan_companions_response())+ assert result["companions"] == []+ assert result["total_bytes"] == 0+++def test_orphan_listing_reports_the_stranded_companions_once_the_quants_are_gone(monkeypatch):+ _install(monkeypatch, _base_repo())+ result = asyncio.run(companion_cleanup.orphan_companions_response())+ assert [c["repo_id"] for c in result["companions"]] == [BASE_REPO]+ assert result["total_bytes"] == COMPANION_BYTES+ # The repo dir, not the cache root: the delete route resolves the owning cache from it.+ assert (+ result["companions"][0]["cache_path"] == "/cache/models--black-forest-labs--FLUX.2-klein-4B"+ )+++def test_orphan_listing_never_offers_a_repo_that_holds_a_checkpoint(monkeypatch):+ """A base the user picked as a full pipeline, or one that also holds a GGUF, is a model."""+ base = _base_repo()+ base.revisions[0].files.append(+ _file("flux-2-klein-4b-Q4_K_M.gguf", Q4_K_M_BYTES, snapshot = base.revisions[0].snapshot_path)+ )+ _install(monkeypatch, base)+ assert asyncio.run(companion_cleanup.orphan_companions_response())["companions"] == []+++def test_orphan_listing_never_offers_an_unrecognised_repo(monkeypatch):+ """Only curated family bases are candidates, so a mis-recorded link cannot promote a repo."""+ stranger = _repo("someone/private-weights", [("model.safetensors", 1_000)])+ companion_assets.record_companion_link(GGUF_REPO, "someone/private-weights")+ _install(monkeypatch, stranger)+ assert asyncio.run(companion_cleanup.orphan_companions_response())["companions"] == []+++def test_a_repo_is_never_recorded_as_its_own_companion(monkeypatch):+ """A full pipeline is its own base. Recording that would make it a dependent of itself and+ block its own deletion forever, with no other model to delete to unblock it."""+ assert companion_assets.record_companion_link(BASE_REPO, BASE_REPO) is False+ assert companion_assets.record_companion_link(BASE_REPO, BASE_REPO.upper()) is False+ assert companion_assets.read_companion_links() == {}+ _install(monkeypatch, _base_repo())+ assert companion_cleanup.companion_dependents(BASE_REPO) == []+ assert [+ c["repo_id"]+ for c in asyncio.run(companion_cleanup.orphan_companions_response())["companions"]+ ] == [BASE_REPO]+++def test_orphan_listing_never_offers_a_base_installed_as_a_full_pipeline(monkeypatch):+ """Several curated bases run on their own. A companion fetch skips the denoiser folder and+ a pipeline pick takes it, so the denoiser's presence says which one put it on disk."""+ base = _base_repo()+ base.revisions[0].files.append(+ _file(+ "transformer/diffusion_pytorch_model-00001-of-00002.safetensors",+ 7_000_000_000,+ snapshot = base.revisions[0].snapshot_path,+ )+ )+ _install(monkeypatch, base)+ assert asyncio.run(companion_cleanup.orphan_companions_response())["companions"] == []+++def test_recording_a_link_keeps_the_ones_already_there():+ """Every write is a read-modify-write of one shared file, so a second checkpoint's link must+ not erase the first: the erased one would look orphaned and be offered for removal."""+ assert companion_assets.record_companion_link(GGUF_REPO, BASE_REPO) is True+ assert (+ companion_assets.record_companion_link(+ "unsloth/FLUX.2-klein-9B-GGUF", "black-forest-labs/FLUX.2-klein-9B"+ )+ is True+ )+ links = companion_assets.read_companion_links()+ assert links[GGUF_REPO.lower()] == [BASE_REPO]+ assert links["unsloth/flux.2-klein-9b-gguf"] == ["black-forest-labs/FLUX.2-klein-9B"]+ # Re-recording the same pair is a no-op rather than a duplicate.+ assert companion_assets.record_companion_link(GGUF_REPO, BASE_REPO) is False+ assert companion_assets.read_companion_links()[GGUF_REPO.lower()] == [BASE_REPO]+++def test_orphan_listing_reports_one_row_per_cache(monkeypatch):+ """A delete is scoped to a single cache, so two copies must not be pooled into one row that+ promises bytes one removal cannot deliver."""+ first = _base_repo()+ second = _repo(+ BASE_REPO,+ [("model_index.json", 460), ("vae/diffusion_pytorch_model.safetensors", 900_000)],+ cache = "/other-cache",+ )+ _install(monkeypatch, first, second)+ result = asyncio.run(companion_cleanup.orphan_companions_response())+ assert [c["cache_path"] for c in result["companions"]] == [+ "/cache/models--black-forest-labs--FLUX.2-klein-4B",+ "/other-cache/models--black-forest-labs--FLUX.2-klein-4B",+ ]+ assert [c["size_bytes"] for c in result["companions"]] == [COMPANION_BYTES, 900_460]+ assert result["total_bytes"] == COMPANION_BYTES + 900_460+++def test_a_cached_mirror_and_its_upstream_do_not_pin_each_other(monkeypatch):+ """Both identities of one base resolve their own family back to the upstream id. Treating+ that as a dependency would make a cache holding both unable to delete either, forever."""+ _install(+ monkeypatch,+ _base_repo("unsloth/FLUX.1-schnell"),+ _base_repo("black-forest-labs/FLUX.1-schnell"),+ )+ assert companion_cleanup.companion_dependents("unsloth/FLUX.1-schnell") == []+ assert companion_cleanup.companion_dependents("black-forest-labs/FLUX.1-schnell") == []+ offered = [+ c["repo_id"]+ for c in asyncio.run(companion_cleanup.orphan_companions_response())["companions"]+ ]+ assert offered == ["black-forest-labs/FLUX.1-schnell", "unsloth/FLUX.1-schnell"]+++def test_the_link_trim_keeps_the_newest_not_the_alphabetically_last(monkeypatch):+ """The cap drops the OLDEST recorded checkpoints, and insertion order is the only record of+ which those are. Serialising with sort_keys made the next read alphabetical, so the trim+ evicted the lexicographically smallest instead: a link recorded seconds ago could go, and+ its non-table companion base then looked deletable while the checkpoint was still installed.+ """+ monkeypatch.setattr(companion_assets, "_MAX_LINKS", 3)+ # Recorded newest-last but named so that alphabetical order is the exact reverse.+ for name in ("unsloth/zz-GGUF", "unsloth/mm-GGUF", "unsloth/aa-GGUF"):+ assert companion_assets.record_companion_link(name, BASE_REPO) is True+ assert list(companion_assets.read_companion_links()) == [+ "unsloth/zz-gguf",+ "unsloth/mm-gguf",+ "unsloth/aa-gguf",+ ]+ # A fourth evicts the oldest, which is the first recorded, not "aa".+ assert companion_assets.record_companion_link("unsloth/nn-GGUF", BASE_REPO) is True+ assert list(companion_assets.read_companion_links()) == [+ "unsloth/mm-gguf",+ "unsloth/aa-gguf",+ "unsloth/nn-gguf",+ ]+++def test_recording_a_second_base_refreshes_the_checkpoints_recency(monkeypatch):+ """Recording is the only recency signal there is, so a checkpoint that just resolved must+ move to the newest end rather than keep the position it was first written at."""+ monkeypatch.setattr(companion_assets, "_MAX_LINKS", 2)+ assert companion_assets.record_companion_link("unsloth/first-GGUF", BASE_REPO) is True+ assert companion_assets.record_companion_link("unsloth/second-GGUF", BASE_REPO) is True+ assert companion_assets.record_companion_link("unsloth/first-GGUF", "unsloth/other-base") is (+ True+ )+ assert list(companion_assets.read_companion_links()) == [+ "unsloth/second-gguf",+ "unsloth/first-gguf",+ ]+ assert companion_assets.read_companion_links()["unsloth/first-gguf"] == [+ BASE_REPO,+ "unsloth/other-base",+ ]+ # "second" is the oldest now, so it is what a third checkpoint displaces.+ assert companion_assets.record_companion_link("unsloth/third-GGUF", BASE_REPO) is True+ assert list(companion_assets.read_companion_links()) == [+ "unsloth/first-gguf",+ "unsloth/third-gguf",+ ]+++def test_freeable_companions_only_names_bases_free_up_space_can_offer(monkeypatch):+ """The delete preview told the user to remove the asset with Free up space, but that list is+ table-only by design (a mis-recorded link must never turn an unrelated repo into a delete+ candidate), so a base reached only through a recorded link was never in it. Advertising an+ action that does nothing is worse than not advertising it."""+ link_only = "some-vendor/private-encoder"+ companion_assets.record_companion_link(GGUF_REPO, link_only)+ _install(+ monkeypatch,+ _gguf_repo(("Q2_K", Q2_K_BYTES)),+ _repo(link_only, [("model_index.json", 460)]),+ )+ impact = asyncio.run(companion_cleanup.delete_impact_response(GGUF_REPO))+ assert [c["repo_id"] for c in impact["freeable_companions"]] == []+ # It is still PROTECTED, which is the half the guard owns.+ assert companion_assets.is_companion_base(link_only) is True+ offered = asyncio.run(companion_cleanup.orphan_companions_response())["companions"]+ assert [c["repo_id"] for c in offered] == []+++def test_reusing_an_existing_link_still_refreshes_its_recency(monkeypatch):+ """A checkpoint reloaded every day but first recorded long ago is the most-used link there+ is. Returning early because the base was already known left it at its original position, so+ the 512-link cap could throw away exactly the link that is in constant use, and for a+ card-tag-only base losing that link is the delete guard going quiet on it."""+ monkeypatch.setattr(companion_assets, "_MAX_LINKS", 2)+ assert companion_assets.record_companion_link("unsloth/old-GGUF", BASE_REPO) is True+ assert companion_assets.record_companion_link("unsloth/new-GGUF", BASE_REPO) is True+ # The old one resolves again to the SAME base: nothing new to record, but it is now the+ # freshest link, so the next checkpoint displaces the other one.+ assert companion_assets.record_companion_link("unsloth/old-GGUF", BASE_REPO) is False+ assert companion_assets.read_companion_links()["unsloth/old-gguf"] == [BASE_REPO]+ assert companion_assets.record_companion_link("unsloth/third-GGUF", BASE_REPO) is True+ assert list(companion_assets.read_companion_links()) == [+ "unsloth/old-gguf",+ "unsloth/third-gguf",+ ]+++def test_a_cached_community_repack_is_a_companion_identity_too(monkeypatch):+ """prefer_cached_legacy_source deliberately sends the native fetch back to a repack an+ upgraded install already holds, so on those machines the bytes protecting an installed GGUF+ sit under the OLD repo key. Expanding only the upstream/mirror pair left that copy+ unprotected: deletable after unload, and the GGUF stranded."""+ from core.inference.diffusion_families import legacy_source_repo++ mirror = "unsloth/Z-Image-Turbo-ComfyUI"+ repack = legacy_source_repo(mirror)+ assert repack, "the mirror table no longer names a legacy repack; pick another for this test"+ companion_assets.record_companion_link(GGUF_REPO, mirror)+ _install(+ monkeypatch,+ _gguf_repo(("Q2_K", Q2_K_BYTES)),+ _repo(repack, [("model_index.json", 460)]),+ )+ required = companion_assets.required_companion_bases(cache_inventory.all_hf_cache_scans())+ assert GGUF_REPO in required.get(repack.lower(), set())+ assert companion_cleanup.companion_dependents(repack) == [GGUF_REPO]+ # And it is refused as a delete while the GGUF is installed.+ assert companion_assets.is_companion_base(repack) is True+++def test_a_native_component_repo_is_offered_once_nothing_needs_it(monkeypatch):+ """For an sd.cpp pick the single-file VAE and text encoder ARE the companions, and the largest+ half of the footprint. Leaving that curated table out of the offerable set made them link-only+ strangers: dropped from the delete preview and never listed by Free up space, so exactly the+ assets this cleanup exists for stayed unreclaimable."""+ from core.inference.diffusion_families import sd_cpp_companion_only_repo_ids++ component = next(iter(sorted(sd_cpp_companion_only_repo_ids())))+ assert component in companion_assets.known_companion_base_ids()+ _install(monkeypatch, _repo(component, [("vae.safetensors", 900_000)]))+ offered = asyncio.run(companion_cleanup.orphan_companions_response())["companions"]+ assert [c["repo_id"].lower() for c in offered] == [component]+++def test_a_chat_model_borrowed_as_an_encoder_is_never_offered(monkeypatch):+ """That table deliberately includes repos that are perfectly good chat models sd.cpp also+ borrows. Offering one as an unused asset would take away a model the user downloaded on+ purpose; holding a GGUF is what keeps it out."""+ borrowed = "unsloth/Qwen2.5-VL-7B-Instruct-GGUF"+ _install(monkeypatch, _repo(borrowed, [("Qwen2.5-VL-7B-Instruct-Q4_K_M.gguf", 4_000_000)]))+ offered = asyncio.run(companion_cleanup.orphan_companions_response())["companions"]+ assert offered == []+++def test_a_family_named_only_by_the_cached_filename_still_pins_its_base(monkeypatch):+ """Both loaders detect a family from the filename as well as the repo id, so a runnable repo+ whose name says nothing was invisible to the dependency probe. That matters most on an+ upgraded install, where no links have been recorded yet and the probe is the whole guard."""+ _install(+ monkeypatch,+ _repo("some-owner/custom", [("FLUX.2-klein-4B-Q4_K_M.gguf", 2_000_000)]),+ _base_repo(),+ )+ required = companion_assets.required_companion_bases(cache_inventory.all_hf_cache_scans())+ assert "some-owner/custom" in required.get(BASE_REPO.lower(), set())+ assert companion_cleanup.companion_dependents(BASE_REPO) == ["some-owner/custom"]+ assert asyncio.run(companion_cleanup.orphan_companions_response())["companions"] == []+++def test_one_full_copy_does_not_hide_an_orphaned_copy_in_another_cache(monkeypatch):+ """A delete is scoped to one cache root, which is why the listing emits one row per root.+ Pooling the denoiser test across roots let a full pipeline copy in one suppress a+ companion-only copy in another that nothing else can reclaim."""+ full = _repo(+ BASE_REPO,+ [("transformer/diffusion_pytorch_model.safetensors", 5_000_000)],+ cache = "/full-cache",+ )+ orphan = _repo(BASE_REPO, [("vae/diffusion_pytorch_model.safetensors", 900_000)])+ _install(monkeypatch, full, orphan)+ offered = asyncio.run(companion_cleanup.orphan_companions_response())["companions"]+ assert [c["cache_path"] for c in offered] == [+ "/cache/models--black-forest-labs--FLUX.2-klein-4B"+ ]+++def test_a_preexisting_native_gguf_still_protects_its_encoder(monkeypatch):+ """The native engine never reads the diffusers base; it fetches a single-file VAE and text+ encoder from their own repos, and those repos are now offerable for deletion. With no+ recorded link -- an upgraded cache, or state loss -- the derived fallback has to name them,+ or Free up space lists the encoder of an installed checkpoint as an unused asset."""+ from core.inference.diffusion_families import (+ detect_family_for_pick,+ sd_cpp_text_encoders_for,+ )++ gguf = "Qwen-Image-Q4_K_M.gguf"+ fam = detect_family_for_pick("some-owner/custom", gguf)+ assert fam is not None and fam.sd_cpp_vae, "pick a family with a native VAE for this test"+ vae_repo = fam.sd_cpp_vae[0]+ encoder_repo = sd_cpp_text_encoders_for(fam, "some-owner/custom", gguf)[0][0]++ _install(+ monkeypatch,+ _repo("some-owner/custom", [(gguf, 2_000_000)]),+ _repo(vae_repo, [("vae.safetensors", 300_000)]),+ _repo(encoder_repo, [("encoder.gguf", 900_000)]),+ )+ required = companion_assets.required_companion_bases(cache_inventory.all_hf_cache_scans())+ assert "some-owner/custom" in required.get(vae_repo.lower(), set())+ assert "some-owner/custom" in required.get(encoder_repo.lower(), set())+ offered = [+ c["repo_id"]+ for c in asyncio.run(companion_cleanup.orphan_companions_response())["companions"]+ ]+ assert vae_repo not in offered and encoder_repo not in offered+++def test_deleting_the_companion_quant_itself_runs_the_guard(monkeypatch):+ """Native Qwen-Image opens exactly Qwen2.5-VL-7B-Instruct-Q4_K_M.gguf inside a chat GGUF+ repo, so removing that one quant strands the image checkpoint however many siblings remain:+ none of them is a substitute for a fixed filename. The guard only ran for whole-repo deletes.+ """+ from hub.services.models import deletion++ encoder_repo = "unsloth/Qwen2.5-VL-7B-Instruct-GGUF"+ _install(+ monkeypatch,+ _repo("some-owner/qwen-image", [("Qwen-Image-Q4_K_M.gguf", 9_000_000)]),+ _repo(+ encoder_repo,+ [+ ("Qwen2.5-VL-7B-Instruct-Q4_K_M.gguf", 4_000_000),+ ("Qwen2.5-VL-7B-Instruct-Q8_0.gguf", 8_000_000),+ ],+ ),+ )+ # The exact quant the image load opens is guarded even with a sibling still present.+ assert deletion._variant_is_a_required_companion_asset(encoder_repo, "Q4_K_M") is True+ # The sibling is nobody's asset, so an ordinary variant delete stays unguarded.+ assert deletion._variant_is_a_required_companion_asset(encoder_repo, "Q8_0") is False+ assert deletion._variant_is_a_required_companion_asset("some-owner/unrelated", "Q4_K_M") is (+ False+ )+ # ... and the guard reports the dependant, so the delete is refused rather than silently done.+ assert companion_cleanup.companion_dependents(encoder_repo) == ["some-owner/qwen-image"]+++def test_a_gguf_in_a_subdirectory_still_pins_its_base(monkeypatch):+ """``CachedFileInfo.file_name`` is the basename alone. A repo whose id says nothing and whose+ GGUF sits in a subdirectory carries its family only in the directory part, so a basename-only+ scan detected no family and Free up space would offer the base out from under it."""+ _install(+ monkeypatch,+ _repo("some-owner/custom", [("FLUX.2-klein-4B/model-Q4_K_M.gguf", 2_000_000)]),+ _base_repo(),+ )+ required = companion_assets.required_companion_bases(cache_inventory.all_hf_cache_scans())+ assert "some-owner/custom" in required.get(BASE_REPO.lower(), set())+ assert asyncio.run(companion_cleanup.orphan_companions_response())["companions"] == []+++def test_orphaned_native_components_do_not_hold_each_other_on_disk(monkeypatch):+ """A component repo is a companion, not a checkpoint. Several of those ids carry a family+ keyword of their own, so the derivation read a bare text-encoder fetch as an installed model+ and recorded the sibling VAE as still required: the pair survived every cleanup pass until the+ user happened to remove one of them by hand."""+ encoder = "unsloth/FLUX.2-dev-ComfyUI"+ vae = "unsloth/FLUX.2-VAE"+ _install(+ monkeypatch,+ _repo(+ encoder, [("split_files/text_encoders/mistral_3_small_flux2_bf16.safetensors", 9_000)]+ ),+ _repo(vae, [("split_files/vae/flux2-vae.safetensors", 300_000)]),+ )+ assert companion_cleanup.companion_dependents(vae) == []+ offered = {+ c["repo_id"]+ for c in asyncio.run(companion_cleanup.orphan_companions_response())["companions"]+ }+ assert offered == {encoder, vae}+++def test_a_component_repo_holding_a_checkpoint_is_still_a_checkpoint(monkeypatch):+ """The exclusion above is denoiser-gated, so a curated component id the user really did+ install a GGUF from keeps pinning what it needs."""+ encoder = "unsloth/FLUX.2-dev-ComfyUI"+ _install(+ monkeypatch,+ _repo(encoder, [("split_files/diffusion_models/flux2-dev-Q4_K_M.gguf", 8_000_000)]),+ _repo("unsloth/FLUX.2-VAE", [("split_files/vae/flux2-vae.safetensors", 300_000)]),+ )+ assert companion_cleanup.companion_dependents("unsloth/FLUX.2-VAE") == [encoder]+++def test_a_borrowed_chat_repo_is_never_advertised_as_freeable(monkeypatch):+ """The delete preview must point only at rows Free up space will really show. A borrowed chat+ GGUF repo is a curated companion id but holds a denoiser, so the orphan listing skips it;+ naming it here sent the user to remove something that is never on that list."""+ borrowed = "unsloth/Qwen2.5-VL-7B-Instruct-GGUF"+ checkpoint = "some-owner/qwen-image"+ _install(+ monkeypatch,+ _repo(checkpoint, [("Qwen-Image-Q4_K_M.gguf", 9_000_000)]),+ _repo(borrowed, [("Qwen2.5-VL-7B-Instruct-Q4_K_M.gguf", 4_000_000)]),+ )+ impact = asyncio.run(companion_cleanup.delete_impact_response(checkpoint))+ assert borrowed not in {c["repo_id"] for c in impact["freeable_companions"]}+ offered = {+ c["repo_id"]+ for c in asyncio.run(companion_cleanup.orphan_companions_response())["companions"]+ }+ assert borrowed not in offered+++def test_an_sdxl_single_file_install_is_never_offered_as_a_leftover(monkeypatch):+ """A single_file_is_pipeline family caches its whole checkpoint as ONE top-level file, so+ there is no denoiser folder to recognise. Its repo is also a curated companion base whose+ self-dependency is dropped, so the listing called an installed SDXL an unused leftover."""+ sdxl = "stabilityai/stable-diffusion-xl-base-1.0"+ _install(monkeypatch, _repo(sdxl, [("sd_xl_base_1.0.safetensors", 6_900_000_000)]))+ assert asyncio.run(companion_cleanup.orphan_companions_response())["companions"] == []+++def test_a_variant_named_by_an_alias_spelling_still_pins_its_base(monkeypatch):+ """Family detection accepts ``flux1-dev`` for the flux.1 family, so the curated name+ ``FLUX.1-dev`` has to be matched with punctuation folded away. One dot apart, the dev base was+ offerable while the dev checkpoint was installed."""+ dev = "black-forest-labs/FLUX.1-dev"+ _install(+ monkeypatch,+ _repo("some-owner/custom", [("flux1-dev-Q4_K_M.gguf", 2_000_000)]),+ _repo(dev, [("model_index.json", 460), ("text_encoder/m.safetensors", 9_000)]),+ )+ assert companion_cleanup.companion_dependents(dev) == ["some-owner/custom"]+ assert asyncio.run(companion_cleanup.orphan_companions_response())["companions"] == []+++def test_every_cached_gguf_in_one_repo_pins_its_own_base(monkeypatch):+ """One generic repo can hold checkpoints of two families in separate subdirectories, and the+ loader selects either by file name. Probing only the first left the other's base orphaned."""+ klein = "black-forest-labs/FLUX.2-klein-4B"+ dev = "black-forest-labs/FLUX.2-dev"+ _install(+ monkeypatch,+ _repo(+ "some-owner/multi",+ [("FLUX.2-klein-4B/a-Q4_K_M.gguf", 2_000_000), ("FLUX.2-dev/b-Q4_K_M.gguf", 3_000_000)],+ ),+ _repo(klein, [("model_index.json", 460)]),+ _repo(dev, [("model_index.json", 460)]),+ )+ assert companion_cleanup.companion_dependents(klein) == ["some-owner/multi"]+ assert companion_cleanup.companion_dependents(dev) == ["some-owner/multi"]+++def test_copies_in_two_cache_roots_are_probed_together(monkeypatch):+ """A remembered second cache holds its own copy of the same repo id. The probe kept the first+ copy's names and skipped the rest, so a family only the second copy names lost its base."""+ klein = "black-forest-labs/FLUX.2-klein-4B"+ qwen = "Qwen/Qwen-Image"+ scans = [+ SimpleNamespace(+ repos = [+ _repo(+ "some-owner/custom", [("FLUX.2-klein-4B-Q4_K_M.gguf", 2_000_000)], cache = "/c1"+ )+ ]+ ),+ SimpleNamespace(+ repos = [_repo("some-owner/custom", [("Qwen-Image-Q4_K_M.gguf", 9_000_000)], cache = "/c2")]+ ),+ SimpleNamespace(+ repos = [+ _repo(klein, [("model_index.json", 460)]),+ _repo(qwen, [("model_index.json", 460)]),+ ]+ ),+ ]+ monkeypatch.setattr(cache_inventory, "all_hf_cache_scans", lambda: scans)+ monkeypatch.setattr(companion_cleanup.cache_inventory, "all_hf_cache_scans", lambda: scans)+ assert companion_cleanup.companion_dependents(klein) == ["some-owner/custom"]+ assert companion_cleanup.companion_dependents(qwen) == ["some-owner/custom"]+++def test_a_single_file_safetensors_pick_pins_its_base(monkeypatch):+ """The loader hands a top-level single-file .safetensors to detect_family_for_pick exactly+ like a GGUF, so a cache holding only that file has a family. Probing GGUFs alone left the+ checkpoint's base reclaimable, and deleting it broke the installed pick offline."""+ dev = "black-forest-labs/FLUX.2-dev"+ _install(+ monkeypatch,+ _repo("unsloth/custom", [("FLUX.2-dev-fp8.safetensors", 9_000_000)]),+ _repo(dev, [("model_index.json", 460)]),+ )+ assert companion_cleanup.companion_dependents(dev) == ["unsloth/custom"]+ assert asyncio.run(companion_cleanup.orphan_companions_response())["companions"] == []+++def test_a_legacy_component_repack_is_not_read_as_a_checkpoint(monkeypatch):+ """An upgraded install holds the component under the repack id the native fetch fell back to.+ That id matches its family just as literally, so without expanding the exclusion through the+ same mirror identities the orphaned pair kept holding each other on disk."""+ legacy = "Comfy-Org/flux2-dev"+ vae = "unsloth/FLUX.2-VAE"+ _install(+ monkeypatch,+ _repo(+ legacy, [("split_files/text_encoders/mistral_3_small_flux2_bf16.safetensors", 9_000)]+ ),+ _repo(vae, [("split_files/vae/flux2-vae.safetensors", 300_000)]),+ )+ assert companion_cleanup.companion_dependents(vae) == []+ offered = {+ c["repo_id"]+ for c in asyncio.run(companion_cleanup.orphan_companions_response())["companions"]+ }+ assert offered == {legacy, vae}+++def test_free_up_space_refuses_a_row_that_became_an_installed_model(monkeypatch):+ """The listing can be minutes old. A download of the same repo finishing in the background+ turns an orphaned companion into an installed checkpoint, and neither existing guard sees it:+ begin_delete only refuses a download still in flight, and the companion guard ignores the+ target as its own dependent. Remove would then delete the model the user just downloaded."""+ from hub.services.models import deletion++ base = BASE_REPO+ # The companion-only copy Free up space listed, now carrying a downloaded denoiser.+ _install(monkeypatch, _repo(base, [("transformer/diffusion_pytorch_model.safetensors", 9_000)]))+ with pytest.raises(HTTPException) as excinfo:+ asyncio.run(deletion.delete_cached_model_response(base, only_if_orphan = True))+ assert excinfo.value.status_code == 409+ assert "no longer an unused asset" in excinfo.value.detail+++def test_the_orphan_precondition_lets_a_real_orphan_through(monkeypatch):+ """The precondition only refuses; a row that is still companion-only reaches the delete, and+ it must not become a second way for an ordinary delete to fail."""+ from hub.services.models import deletion++ _install(monkeypatch, _repo(BASE_REPO, [("model_index.json", 460)]))+ try:+ deletion._delete_cached_model_blocking(BASE_REPO, None, None, only_if_orphan = True)+ except HTTPException as exc:+ assert exc.status_code != 409, exc.detail+++def test_a_transformer_only_single_file_in_its_own_base_repo_is_a_checkpoint(monkeypatch):+ """Not only whole-pipeline families cache a root weight. A transformer-only single_file pick+ of a curated base repo does too, and its self-dependency is dropped, so the listing called an+ installed checkpoint a leftover and the orphan precondition would happily delete it."""+ from hub.services.models import deletion++ dev = "black-forest-labs/FLUX.2-dev"+ _install(monkeypatch, _repo(dev, [("flux2-dev-fp8.safetensors", 9_000_000)]))+ assert asyncio.run(companion_cleanup.orphan_companions_response())["companions"] == []+ with pytest.raises(HTTPException) as excinfo:+ deletion._delete_cached_model_blocking(dev, None, None, only_if_orphan = True)+ assert excinfo.value.status_code == 409+++def test_the_orphan_precondition_is_scoped_to_the_cache_being_deleted(monkeypatch):+ """The listing emits one row per cache root because a delete is scoped to one. A full pipeline+ copy in another remembered cache must not veto removing the companion-only copy that was+ listed, or that row 409s forever."""+ from hub.services.models import deletion++ dev = "black-forest-labs/FLUX.2-dev"+ _install(+ monkeypatch,+ _repo(dev, [("transformer/diffusion_pytorch_model.safetensors", 9_000)], cache = "/c1"),+ _repo(dev, [("model_index.json", 460)], cache = "/c2"),+ )+ rows = asyncio.run(companion_cleanup.orphan_companions_response())["companions"]+ assert [r["cache_path"] for r in rows] == ["/c2/models--black-forest-labs--FLUX.2-dev"]+ try:+ deletion._delete_cached_model_blocking(+ dev, None, None, rows[0]["cache_path"], only_if_orphan = True+ )+ except HTTPException as exc:+ assert exc.status_code != 409, exc.detail+++def test_one_checkpoints_recorded_bases_are_bounded(monkeypatch):+ """_MAX_LINKS counts checkpoints, not their bases, so a checkpoint resolved against a new+ explicit base each load grew the state file on its own, and every delete check parses and+ mirror-expands the whole list."""+ for i in range(companion_assets._MAX_BASES_PER_CHECKPOINT + 5):+ companion_assets.record_companion_link(GGUF_REPO, f"some-vendor/base-{i}")+ bases = companion_assets.read_companion_links()[GGUF_REPO.lower()]+ assert len(bases) == companion_assets._MAX_BASES_PER_CHECKPOINT+ # The most recent survive; the oldest go.+ assert bases[-1] == f"some-vendor/base-{companion_assets._MAX_BASES_PER_CHECKPOINT + 4}"+ assert "some-vendor/base-0" not in bases+++def test_re_resolving_a_base_refreshes_its_place_in_the_list(monkeypatch):+ """The cap is by recency, so a base still in use must not be evicted ahead of one nothing has+ resolved since."""+ companion_assets.record_companion_link(GGUF_REPO, "some-vendor/a")+ companion_assets.record_companion_link(GGUF_REPO, "some-vendor/b")+ companion_assets.record_companion_link(GGUF_REPO, "some-vendor/a")+ assert companion_assets.read_companion_links()[GGUF_REPO.lower()] == [+ "some-vendor/b",+ "some-vendor/a",+ ]+++def test_the_orphan_precondition_refuses_when_the_target_root_is_not_in_the_scan(monkeypatch):+ """An empty scoped match means the target root was not scanned, and the delete below can+ still purge that directory by path. Concluding "orphan" from copies we did not look at is the+ fail-open this precondition exists to prevent."""+ from hub.services.models import deletion++ dev = "black-forest-labs/FLUX.2-dev"+ _install(monkeypatch, _repo(dev, [("model_index.json", 460)], cache = "/c1"))+ with pytest.raises(HTTPException) as excinfo:+ deletion._delete_cached_model_blocking(+ dev, None, None, "/unscanned/models--black-forest-labs--FLUX.2-dev", only_if_orphan = True+ )+ assert excinfo.value.status_code == 503+++def test_the_preview_reads_a_path_qualified_variant(monkeypatch):+ """The inventory and the delete identify a row by gguf_variant_key, which for a checkpoint in+ its own directory is not the bare quant label. Comparing labels reported 0 B reclaimed and+ described the last checkpoint's companions as retained rather than freed."""+ repo = "unsloth/LTX-2.3-22B-GGUF"+ variant = "distilled/ltx-2.3-22b-distilled-Q6_K"+ _install(+ monkeypatch,+ _repo(repo, [("distilled/ltx-2.3-22b-distilled-Q6_K.gguf", 6_000_000)]),+ )+ impact = asyncio.run(companion_cleanup.delete_impact_response(repo, variant))+ assert impact["reclaimed_bytes"] == 6_000_000diff --git a/studio/backend/hub/utils/companion_assets.py b/studio/backend/hub/utils/companion_assets.pynew file mode 100644index 00000000000..a1cf85277d8--- /dev/null+++ b/studio/backend/hub/utils/companion_assets.py@@ -0,0 +1,631 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Which cached repos are companion assets, and which installed models still need them.++An image or video GGUF ships only the denoiser. Everything else the pipeline needs -- text+encoders, VAE, tokenizer, scheduler and the pipeline manifest -- comes from a separate+*companion base repo*, cached under its own ``models--`` directory. It is routinely the larger+half: FLUX.2 klein 4B is 2.6 GB of Q4_K_M against 8.23 GB of companions, and one copy serves+every quant in the GGUF repo.++That sharing is what makes deletion delicate. Two questions have to be answerable without a+counter, because a counter that drifts is worse than none:++ "is this repo a companion base?" -> :func:`is_companion_base`+ "what still needs it, right now?" -> :func:`required_companion_bases`++Both are DERIVED at call time from what is installed, using the same resolvers the loader uses+to pick a base (``detect_family_for_pick`` + ``resolve_base_repo`` + ``mirror_repo``). If family+detection fails for a cached repo, the loader cannot load it either, so there is no dependent to+protect -- the derivation and the thing it protects fail together, by construction.++The one case derivation cannot see offline is a checkpoint whose base comes from its Hub card's+``base_model`` tag rather than the family default (``_resolve_base_repo``), because a GGUF pick+caches only the ``.gguf`` file, never the card. :func:`record_companion_link` closes that: the+resolver records the pair it chose, and the reader unions those links into the derived set. It+is a LINK, not a count -- an entry can only ever ADD a dependent, is filtered by "is that+checkpoint still installed", and its loss degrades to the family default rather than to a wrong+answer. Nothing here deletes; callers do, and only for a base with an empty dependent set.+"""++from __future__ import annotations++import json+import os+import threading+import uuid+from pathlib import Path+from typing import Iterable, Optional++from loggers import get_logger++from hub.utils.state_dir import state_root++logger = get_logger(__name__)+++_LINKS_FILENAME = "companion-assets.json"+_LINKS_VERSION = 1+# A runaway writer must not grow an unbounded state file; oldest links are dropped first.+_MAX_LINKS = 512+# ... and per checkpoint, for the same reason: one key must not grow the file on its own.+_MAX_BASES_PER_CHECKPOINT = 16+# Serialises the read-modify-write below. Losing a link to a lost update is the one direction+# that matters: an unrecorded base can look orphaned and be offered for removal.+_WRITE_LOCK = threading.Lock()+++def _links_path(*, create: bool = False) -> Optional[Path]:+ root = state_root(create = create)+ if root is None:+ return None+ return root / _LINKS_FILENAME+++def _normalise(repo_id: Optional[str]) -> str:+ return (repo_id or "").strip().lower()+++def read_companion_links() -> dict[str, list[str]]:+ """``{checkpoint_repo_id_lower: [base_repo_id, ...]}`` recorded by past resolutions.++ Fails OPEN: a missing, unreadable or schema-mismatched file yields ``{}`` and every caller+ falls back to family-default derivation, which is what shipped before this file existed.+ """+ path = _links_path()+ if path is None:+ return {}+ try:+ payload = json.loads(path.read_text(encoding = "utf-8"))+ except (OSError, ValueError):+ return {}+ if not isinstance(payload, dict) or payload.get("version") != _LINKS_VERSION:+ return {}+ raw = payload.get("links")+ if not isinstance(raw, dict):+ return {}+ links: dict[str, list[str]] = {}+ for checkpoint, bases in raw.items():+ if not isinstance(checkpoint, str) or not isinstance(bases, list):+ continue+ clean = [b.strip() for b in bases if isinstance(b, str) and b.strip()]+ if clean:+ links[_normalise(checkpoint)] = clean+ return links+++def _write_companion_links(links: dict[str, list[str]]) -> bool:+ path = _links_path(create = True)+ if path is None:+ return False+ if len(links) > _MAX_LINKS:+ # dicts preserve insertion order, so this drops the oldest recorded checkpoints.+ links = dict(list(links.items())[-_MAX_LINKS:])+ payload = {"version": _LINKS_VERSION, "links": links}+ tmp = path.with_name(f".{path.name}.tmp-{uuid.uuid4().hex[:8]}")+ try:+ # NOT sort_keys: json.loads keeps document order, so the file IS the recency record the+ # trim above reads. Sorting it made the next read alphabetical, and the trim then evicted+ # the lexicographically smallest link rather than the oldest -- so a link recorded minutes+ # ago could go, and its base become deletable while the checkpoint was still installed.+ tmp.write_text(json.dumps(payload, indent = 2), encoding = "utf-8")+ os.replace(tmp, path)+ return True+ except OSError as exc:+ logger.debug("Could not record companion links at %s: %s", path, exc)+ try:+ tmp.unlink()+ except OSError:+ pass+ return False+++def record_companion_link(checkpoint_repo_id: str, base_repo_id: str) -> bool:+ """Remember that *checkpoint_repo_id* resolves its companions from *base_repo_id*.++ Called from the base resolvers, so it sees every pick the product makes. Additive and+ idempotent; a self-reference (a full pipeline is its own base) is dropped, since it would+ make the pipeline look like a dependent of itself and block its own deletion forever.+ Best-effort: a write failure is logged at debug and never reaches the caller's load.+ """+ checkpoint = (checkpoint_repo_id or "").strip()+ base = (base_repo_id or "").strip()+ if not checkpoint or not base or _normalise(checkpoint) == _normalise(base):+ return False+ # A local filesystem path is not a Hub id and never appears in a cache scan.+ if (+ "/" not in checkpoint.replace("\\", "/").strip("/")+ or Path(checkpoint).expanduser().exists()+ ):+ return False+ if Path(base).expanduser().exists():+ return False+ with _WRITE_LOCK:+ # Re-read inside the lock: a concurrent resolver's link must not be dropped by this write.+ links = read_companion_links()+ key = _normalise(checkpoint)+ existing = links.get(key, [])+ known = any(_normalise(b) == _normalise(base) for b in existing)+ # Re-inserted at the end, not updated in place: recording is the only recency signal the+ # trim has, so a checkpoint that just resolved must not keep an old position and be+ # evicted ahead of one nothing has touched since. That applies to a REPEAT resolution too+ # -- a checkpoint reloaded every day but first recorded long ago is the most-used link+ # there is, and returning early on it let the cap throw it away.+ links.pop(key, None)+ # Recency inside the list too, and capped: an explicit base_repo (or a card tag that+ # changes) makes one checkpoint resolve a new base each load, and appending forever grew+ # the file that _MAX_LINKS is supposed to bound -- it counts checkpoints, not their bases,+ # and every dependency check parses and mirror-expands the whole list. A checkpoint has+ # one or two bases in practice, so the cap is only ever reached by the runaway writer it+ # is here for, and dropping the least recently resolved degrades to derivation.+ fresh = [b for b in existing if _normalise(b) != _normalise(base)]+ links[key] = [*fresh, base][-_MAX_BASES_PER_CHECKPOINT:]+ wrote = _write_companion_links(links)+ # False when nothing NEW was recorded; the refresh above still happened.+ return wrote and not known+++def _snapshot_relative_names(repo) -> Iterable[str]:+ """Every cached file of *repo* as a SNAPSHOT-RELATIVE posix name.++ ``CachedFileInfo.file_name`` is the basename alone; the path inside the snapshot only comes+ back from ``file_path`` relative to ``snapshot_path``. Family detection reads the whole+ relative name, so a GGUF filed under ``FLUX.2-klein/model-Q4_K_M.gguf`` is a dependent that a+ basename-only scan cannot see. The inventory and cleanup scanners already reconstruct it this+ way; this is the same reconstruction, so all three agree on what a cached file is called."""+ for revision in getattr(repo, "revisions", ()) or ():+ snapshot = getattr(revision, "snapshot_path", None)+ for file in getattr(revision, "files", ()) or ():+ name = str(getattr(file, "file_name", "") or "")+ path = getattr(file, "file_path", None)+ if path and snapshot:+ try:+ name = Path(path).relative_to(Path(snapshot)).as_posix()+ except ValueError:+ pass+ if name:+ yield name+++def holds_denoiser(name: str) -> bool:+ """A denoiser weight by NAME alone: a GGUF anywhere, or a shard under the denoiser folder.++ Its presence is what separates a checkpoint the user installed from a companion-only fetch,+ which takes everything BUT the denoiser folder. Use :func:`repo_holds_denoiser` where the repo+ is available: an SDXL-style whole-pipeline single file is a denoiser too, and only the repo's+ family says so."""+ lowered = name.lower()+ if lowered.endswith(".gguf"):+ return True+ return lowered.startswith(_DENOISER_DIRS) and lowered.endswith(_WEIGHT_SUFFIXES)+++_DENOISER_DIRS = ("transformer/", "unet/")+_WEIGHT_SUFFIXES = (".safetensors", ".bin", ".ckpt", ".pt", ".pth", ".gguf")+++def repo_holds_denoiser(repo) -> bool:+ """Whether *repo* holds a runnable checkpoint, i.e. is a model the user installed.++ Beyond the name-only test: a single_file pick caches its checkpoint as ONE top-level file,+ ``sd_xl_base_1.0.safetensors`` for a whole-pipeline family and ``flux2-dev-fp8.safetensors``+ for a transformer-only one, with no denoiser folder to recognise. Those repos are curated+ companion bases whose self-dependency is dropped, so without this the orphan listing called an+ installed checkpoint an unused leftover and Free up space deleted it. A companion-only fetch+ never lands a weight at the snapshot root, and the two ways to be wrong are not symmetric: an+ orphan we decline to offer costs disk, a checkpoint we offer costs the model.++ The one root weight that is NOT a checkpoint is the curated component repos' own asset, which+ is why they are excluded by id: a single-file VAE or text encoder is the companion, and+ reading it as an installed model is what kept an orphaned pair pinned to disk."""+ names = list(_snapshot_relative_names(repo))+ if any(holds_denoiser(name) for name in names):+ return True+ repo_id = str(getattr(repo, "repo_id", "") or "")+ if _normalise(repo_id) in _component_only_repo_ids():+ return False+ for name in names:+ if "/" in name or not name.lower().endswith(_WEIGHT_SUFFIXES):+ continue+ if _detect_family(repo_id, name) is not None:+ return True+ return False+++def _component_only_repo_ids() -> set[str]:+ """Curated sd.cpp component repo ids, under every identity they can be cached as."""+ try:+ from core.inference.diffusion_families import sd_cpp_companion_only_repo_ids+ return {_normalise(r) for r in _with_mirrors(sd_cpp_companion_only_repo_ids())}+ except Exception as exc: # noqa: BLE001 -- no table means no exclusions, as before+ logger.debug("sd.cpp companion table unavailable: %s", exc)+ return set()+++def _is_checkpoint_pick_name(name: str) -> bool:+ """A cached file the loader would hand to ``detect_family_for_pick`` as the pick.++ Both kinds it accepts: a main GGUF anywhere in the repo, and a TOP-LEVEL single-file+ ``.safetensors``, which is how a transformer-only or whole-pipeline single_file pick is+ cached. Restricted to the snapshot root because that is where a single-file pick lands; a+ companion fetch's shards live under ``text_encoder/``, ``vae/`` and friends and say nothing+ about which checkpoint is installed."""+ lowered = name.lower()+ if lowered.endswith(".gguf"):+ return "mmproj" not in lowered+ return "/" not in name and lowered.endswith(".safetensors")+++def _cached_checkpoint_pick_names(cache_scans) -> dict[str, list[str]]:+ """``{repo_id_lower: [every cached file the loader could pick]}`` for the family probe below.++ Both diffusion loaders detect a family from the FILENAME as well as the repo id, so a+ perfectly runnable ``some-owner/custom`` holding ``flux-2-klein-4b-Q4_K_M.gguf`` is a+ dependent that a repo-id-only probe cannot see. That matters most where there is nothing else+ to fall back on: on an upgraded install no links have been recorded yet, so the family probe+ is the whole guard.++ EVERY name, and across EVERY cache root: one generic repo can hold checkpoints of two+ different families, in separate subdirectories or in two remembered caches, and the loader+ will select any of them by file name. Probing one left the others' bases looking orphaned."""+ names: dict[str, list[str]] = {}+ for scan in cache_scans or ():+ for repo in getattr(scan, "repos", ()) or ():+ try:+ if str(getattr(repo, "repo_type", "")) != "model":+ continue+ key = _normalise(str(getattr(repo, "repo_id", "") or ""))+ if not key:+ continue+ found = names.setdefault(key, [])+ for name in _snapshot_relative_names(repo):+ if _is_checkpoint_pick_name(name) and name not in found:+ found.append(name)+ except Exception: # noqa: BLE001 -- one unreadable row never hides the rest+ continue+ return {key: found for key, found in names.items() if found}+++def _denoiser_holding_repo_ids(cache_scans) -> set[str]:+ """Cached repos (lowercased ids) that hold a runnable denoiser, i.e. real checkpoints."""+ held: set[str] = set()+ for scan in cache_scans or ():+ for repo in getattr(scan, "repos", ()) or ():+ try:+ if str(getattr(repo, "repo_type", "")) != "model":+ continue+ key = _normalise(str(getattr(repo, "repo_id", "") or ""))+ if not key or key in held:+ continue+ if repo_holds_denoiser(repo):+ held.add(key)+ except Exception: # noqa: BLE001 -- one unreadable row never hides the rest+ continue+ return held+++def _family_bases_for_names(repo_id: str, gguf_filenames: Iterable[Optional[str]]) -> set[str]:+ """:func:`_family_bases` unioned over every cached GGUF name, plus the repo id on its own."""+ bases: set[str] = set()+ for name in dict.fromkeys([None, *(gguf_filenames or ())]):+ bases |= _family_bases(repo_id, name)+ return bases+++def _family_bases(repo_id: str, gguf_filename: Optional[str] = None) -> set[str]:+ """Companion base ids *repo_id* could resolve to, from the family tables alone.++ Both identities: the upstream the tables key on and its ungated unsloth mirror, because+ ``prefer_ungated_mirror`` picks between them per fetch and either may be what landed on disk.++ ``gguf_filename`` is a cached checkpoint from this repo, passed for the same reason the+ loaders pass it: a repo whose family keyword appears only in the file name still loads, and a+ dependent this probe cannot see is a companion cleanup will happily delete underneath it.+ """+ try:+ from core.inference.diffusion_families import (+ detect_family_for_pick,+ resolve_base_repo,+ )+ except Exception as exc: # noqa: BLE001 -- classification failure protects nothing new+ logger.debug("Companion base derivation unavailable for %s: %s", repo_id, exc)+ return set()+ try:+ fam = detect_family_for_pick(repo_id, gguf_filename)+ except Exception: # noqa: BLE001+ return set()+ if fam is None:+ # The loader resolves a base with this same call. No family means no load, so there is+ # no dependent here to protect -- not a gap, the two fail together.+ return set()+ bases = {resolve_base_repo(fam, None)}+ bases |= _curated_variant_bases(fam, repo_id, gguf_filename)+ # The NATIVE engine's companions as well. It never reads the diffusers base: it fetches a+ # single-file VAE and text encoder from their own repos, and those repos are offerable for+ # deletion, so a pre-existing native GGUF with no recorded link would have had its encoder+ # listed as an unused asset and removed underneath it. The recorded links cover a load that+ # has happened since; this covers the install that predates them.+ bases |= {repo for repo, _file in _sd_cpp_component_specs(fam, repo_id, gguf_filename)}+ return _with_mirrors(bases)+++def _curated_variant_bases(fam, repo_id: str, gguf_filename: Optional[str]) -> set[str]:+ """Curated bases of *fam* that the checkpoint's own identity names, beyond the family default.++ One family entry serves several sizes, and which one a pick uses comes from the Hub card's+ ``base_model`` tag. Offline that tag is gone, so ``resolve_base_repo(fam, None)`` answers the+ family DEFAULT: an installed ``unsloth/FLUX.2-klein-9B-GGUF`` derived as needing the 4B base,+ while its cached ``black-forest-labs/FLUX.2-klein-9B`` had no dependent at all. That base is+ in the curated offerable set, so before the checkpoint's first recorded load Free up space+ would list it and delete the companions of a model that is still installed.++ Conservative on both ends. Candidates come only from the curated tables, only from entries+ belonging to THIS family, and only when the checkpoint id or its GGUF file name names the+ base -- so a wrong guess can add a dependent, never invent a repo. Naming one base too many+ costs a delete that is refused; naming one too few costs an installed model.++ Matched with punctuation folded away, the way family detection accepts its own aliases:+ ``flux1-dev-Q4_K_M.gguf`` resolves to the flux.1 family, and a literal comparison against the+ curated name ``FLUX.1-dev`` missed it over one dot, leaving the dev base offerable while the+ dev checkpoint was installed."""+ family = _fold(getattr(fam, "name", "") or "")+ if not family:+ return set()+ identity = f"{_fold(repo_id)} {_fold(gguf_filename or '')}"+ out: set[str] = set()+ for candidate in _curated_base_ids():+ name = _fold(candidate.rsplit("/", 1)[-1])+ if name and name.startswith(family) and name in identity:+ out.add(candidate)+ return out+++def _fold(text: str) -> str:+ """Lowercased with every separator dropped, so ``FLUX.1-dev`` and ``flux1-dev`` compare equal."""+ return "".join(c for c in (text or "").lower() if c.isalnum())+++def _curated_base_ids() -> set[str]:+ """Curated family bases and their gated/mirror variants, as written in the tables."""+ ids: set[str] = set()+ try:+ from core.inference.diffusion_families import _FAMILIES+ ids |= {fam.base_repo for fam in _FAMILIES if getattr(fam, "base_repo", None)}+ except Exception as exc: # noqa: BLE001 -- no table means no extra candidates, as before+ logger.debug("Companion base table unavailable: %s", exc)+ ids |= _mirror_pair_ids()+ return ids+++def _sd_cpp_component_specs(+ fam, repo_id: str, gguf_filename: Optional[str]+) -> set[tuple[str, str]]:+ """``(repo, filename)`` for every single-file VAE / text encoder an sd.cpp load of *fam*+ opens. The FILENAME matters as much as the repo: the Qwen-Image encoder is one named quant+ inside a chat GGUF repo, so a sibling quant in the same repo is not a substitute for it.+ Never raises."""+ specs: set[tuple[str, str]] = set()+ try:+ from core.inference.diffusion_families import sd_cpp_text_encoder_candidates++ vae = getattr(fam, "sd_cpp_vae", None)+ if vae and vae[0]:+ specs.add((vae[0], vae[1]))+ # EVERY set the family could pick, not the one the string fallback guesses. There is no+ # header to read here, and a renamed FLUX.2-klein 9B file carries no size token either,+ # so guessing answers 4B and leaves the 9B encoder the load actually fetched unprotected.+ # Naming both costs a delete that is refused; guessing costs an installed model.+ for encoder in sd_cpp_text_encoder_candidates(fam) or ():+ if encoder and encoder[0]:+ specs.add((encoder[0], encoder[1]))+ except Exception as exc: # noqa: BLE001 -- one missing table never hides the rest+ logger.debug("sd.cpp component derivation unavailable for %s: %s", repo_id, exc)+ return specs+++def required_companion_asset_files(cache_scans) -> dict[str, set[str]]:+ """``{repo_id_lower: {filename, ...}}`` the installed checkpoints' native loads actually open.++ The repo-level view cannot answer a VARIANT delete. Native Qwen-Image opens exactly+ ``Qwen2.5-VL-7B-Instruct-Q4_K_M.gguf`` inside a chat GGUF repo, so removing that one quant+ strands the image checkpoint even though the repo still holds a Q8_0 nobody can substitute.+ """+ pick_names = _cached_checkpoint_pick_names(cache_scans)+ files: dict[str, set[str]] = {}+ for repo_id in _cached_model_repo_ids(cache_scans):+ # Every cached GGUF, because one repo can hold checkpoints of two families and each opens+ # its own components.+ for name in dict.fromkeys([None, *pick_names.get(_normalise(repo_id), [])]):+ fam = _detect_family(repo_id, name)+ if fam is None:+ continue+ for repo, filename in _sd_cpp_component_specs(fam, repo_id, name):+ if filename:+ files.setdefault(_normalise(repo), set()).add(filename)+ return files+++def _detect_family(repo_id: str, gguf_filename: Optional[str]):+ """``detect_family_for_pick`` that never raises and never imports at module scope."""+ try:+ from core.inference.diffusion_families import detect_family_for_pick+ return detect_family_for_pick(repo_id, gguf_filename)+ except Exception: # noqa: BLE001+ return None+++def _with_mirrors(bases: Iterable[str]) -> set[str]:+ """Every id one companion base can be cached under: itself, the upstream it copies, its+ ungated mirror, and the community repack that mirror stands in for.++ The repack matters as much as the mirror. ``prefer_cached_legacy_source`` deliberately sends+ the native fetch back to a repack an upgraded install already holds, so on those machines the+ bytes protecting an installed GGUF sit under the OLD repo key and nothing else names it. The+ live loaded-repo guard in the sd.cpp backend already expands all four; this is the same set,+ for the recorded links."""+ try:+ from core.inference.diffusion_families import (+ canonical_base,+ legacy_source_repo,+ mirror_repo,+ )+ except Exception: # noqa: BLE001+ return {b for b in bases if b}+ out: set[str] = set()+ for base in bases:+ if not base:+ continue+ out.add(base)+ upstream = canonical_base(base)+ if upstream:+ out.add(upstream)+ mirror = mirror_repo(upstream or base)+ if mirror:+ out.add(mirror)+ for candidate in (base, upstream, mirror):+ legacy = legacy_source_repo(candidate) if candidate else None+ if legacy:+ out.add(legacy)+ return out+++def known_companion_base_ids() -> set[str]:+ """Every id (lowercased) that is a curated image-family companion base, or its mirror.++ Deliberately NOT "anything a link ever named": orphan cleanup offers only repos this set+ recognises, so a mis-recorded link can never turn an unrelated repo into a delete candidate.+ """+ # Family bases and their gated/mirror variants. The pairs are companion bases by construction+ # -- they exist only because a GGUF pick of that family needs an ungated copy of them -- and+ # they cover the variants one family entry serves through a card tag (klein-9B under the+ # klein-4B family, and so on).+ bases = _curated_base_ids()+ # The native engine's component-only repos (a single-file VAE, a text encoder) are curated+ # table entries too, and for an sd.cpp pick they ARE the companions -- the largest half of the+ # footprint. Leaving them out made them link-only strangers: unlisted by Free up space and+ # dropped from the delete preview, so the assets this cleanup exists for stayed invisible.+ # Safe against the one hazard that table warns about, a chat model borrowed as a text encoder:+ # the orphan listing skips any repo holding a GGUF, so it is never offered as a leftover.+ try:+ from core.inference.diffusion_families import sd_cpp_companion_only_repo_ids+ bases |= set(sd_cpp_companion_only_repo_ids())+ except Exception as exc: # noqa: BLE001 -- one missing table never hides the rest+ logger.debug("sd.cpp companion table unavailable: %s", exc)+ return {_normalise(b) for b in _with_mirrors(bases)}+++def _mirror_pair_ids() -> set[str]:+ try:+ from core.inference.diffusion_families import _GATED_MIRROR_PAIRS+ except Exception: # noqa: BLE001+ return set()+ return {rid for pair in _GATED_MIRROR_PAIRS for rid in pair}+++def is_companion_base(repo_id: str) -> bool:+ """Whether deleting *repo_id* could strand an installed model's companions.++ Wider than :func:`known_companion_base_ids` on purpose, and the two are conservative in+ opposite directions. This one gates a REFUSAL, so it also admits any base a recorded link+ names: a checkpoint whose base came from its card tag can point anywhere, and missing it+ would leave exactly the hole this guard exists to close. :func:`known_companion_base_ids`+ gates an OFFER TO DELETE, so it stays table-only and a bad link can never reach it.+ """+ key = _normalise(repo_id)+ if key in known_companion_base_ids():+ return True+ # Through the same identity expansion required_companion_bases uses, so the two agree on+ # WHICH copy is protected. A link recorded against the unsloth mirror is satisfied on an+ # upgraded install by the community repack the fetch fell back to, and comparing the literal+ # id alone left that copy deletable while the checkpoint holding it was still installed.+ return any(+ key in {_normalise(rid) for rid in _with_mirrors([base])}+ for bases in read_companion_links().values()+ for base in bases+ )+++def _cached_model_repo_ids(cache_scans) -> list[str]:+ ids: list[str] = []+ seen: set[str] = set()+ for scan in cache_scans or ():+ for repo in getattr(scan, "repos", ()) or ():+ try:+ if str(getattr(repo, "repo_type", "")) != "model":+ continue+ repo_id = str(getattr(repo, "repo_id", "") or "")+ except Exception: # noqa: BLE001 -- one unreadable row never hides the rest+ continue+ key = _normalise(repo_id)+ if not repo_id or key in seen:+ continue+ seen.add(key)+ ids.append(repo_id)+ return ids+++def required_companion_bases(+ cache_scans, *, ignore_repo_ids: Iterable[str] = ()+) -> dict[str, set[str]]:+ """``{base_repo_id_lower: {checkpoint repo ids that still need it}}``.++ Derived from *cache_scans* -- what is installed at this instant -- unioned with the recorded+ links of those same installed checkpoints. *ignore_repo_ids* is the delete being previewed:+ dropping it answers "what would still need this base AFTER the delete" without mutating+ anything. A repo never counts as its own dependent.+ """+ ignored = {_normalise(r) for r in ignore_repo_ids}+ links = read_companion_links()+ pick_names = _cached_checkpoint_pick_names(cache_scans)+ component_only = _cached_component_only_repo_ids(cache_scans)+ required: dict[str, set[str]] = {}+ for repo_id in _cached_model_repo_ids(cache_scans):+ key = _normalise(repo_id)+ if key in ignored or key in component_only:+ continue+ bases = _family_bases_for_names(repo_id, pick_names.get(key, []))+ recorded = links.get(key)+ if recorded:+ bases |= _with_mirrors(recorded)+ # Canonical, not literal: a cached MIRROR of a base resolves its own family back to the+ # UPSTREAM id, which would make each identity a dependent of the other and leave a cache+ # holding both unable to delete either. They are copies of one repo, not a pair that+ # needs each other.+ self_keys = {key, _normalise(_canonical(repo_id))}+ for base in bases:+ base_key = _normalise(base)+ if not base_key or base_key in self_keys or _normalise(_canonical(base)) in self_keys:+ continue+ required.setdefault(base_key, set()).add(repo_id)+ return required+++def _cached_component_only_repo_ids(cache_scans) -> set[str]:+ """Cached curated component repos holding no denoiser: companions, never checkpoints.++ Several of those ids carry a family keyword of their own -- ``unsloth/FLUX.2-dev-ComfyUI``+ detects as flux.2-dev -- so the loop above read a bare text-encoder fetch as an installed+ checkpoint and recorded the sibling VAE as still required. The orphaned pair then held each+ other on disk: Free up space would not list them and a delete was refused, until the user+ happened to remove one component first. A repo that does hold a denoiser is a model the user+ installed and still counts, which is what keeps a borrowed chat GGUF a dependent of nothing+ and a checkpoint of itself.++ Through the same identity expansion the rest of this file uses, because an upgraded install+ holds the component under the legacy repack id the native fetch fell back to+ (``Comfy-Org/flux2-dev`` for ``unsloth/FLUX.2-dev-ComfyUI``). That id matches the flux.2-dev+ family just as literally, so leaving it out kept the very caches this exclusion is for."""+ curated = _component_only_repo_ids()+ if not curated:+ return set()+ return curated - _denoiser_holding_repo_ids(cache_scans)+++def _canonical(repo_id: str) -> str:+ """``canonical_base``, degrading to the id itself when the family tables are unavailable."""+ try:+ from core.inference.diffusion_families import canonical_base+ return canonical_base(repo_id)+ except Exception: # noqa: BLE001+ return repo_iddiff --git a/studio/backend/tests/test_cached_gguf_routes.py b/studio/backend/tests/test_cached_gguf_routes.pyindex c7e73de7e43..e1b5bdb2e3d 100644--- a/studio/backend/tests/test_cached_gguf_routes.py+++ b/studio/backend/tests/test_cached_gguf_routes.py@@ -2845,7 +2845,7 @@ def test_delete_cached_allows_sibling_of_loaded_diffusion_repo(monkeypatch):monkeypatch.setattr(deletion,"_delete_cached_model_blocking",- lambda repo_id, variant, hf_token, cache_path = None: {+ lambda repo_id, variant, hf_token, cache_path = None, **_kw: {"status": "deleted","repo_id": repo_id,},diff --git a/studio/frontend/src/features/hub/catalog/delete-impact.tsx b/studio/frontend/src/features/hub/catalog/delete-impact.tsxnew file mode 100644index 00000000000..712ec68aa57--- /dev/null+++ b/studio/frontend/src/features/hub/catalog/delete-impact.tsx@@ -0,0 +1,85 @@+// 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 { useEffect, useState } from "react";+import { formatBytes } from "@/features/hub/lib/format";+import { fetchDeleteImpact, type DeleteImpact } from "../inventory";++/**+ * Load the delete preview for a confirm dialog while it is open.+ *+ * An image GGUF is a small checkpoint plus a much larger companion base repo (text encoders,+ * VAE, tokenizer) shared by every quant of its family, so "removes it from disk" was never the+ * whole story: it could free 2.6 GB and silently leave 8.2 GB behind. Returns `null` until the+ * preview lands and if it fails, so the dialog opens either way.+ */+export function useDeleteImpact(+ open: boolean,+ repoId: string,+ variant?: string | null,+): DeleteImpact | null {+ const [impact, setImpact] = useState<DeleteImpact | null>(null);+ useEffect(() => {+ if (!open) {+ setImpact(null);+ return;+ }+ let cancelled = false;+ void fetchDeleteImpact(repoId, variant ?? undefined).then((result) => {+ if (!cancelled) setImpact(result);+ });+ return () => {+ cancelled = true;+ };+ }, [open, repoId, variant]);+ return impact;+}++function joinNames(names: string[]): string {+ if (names.length <= 2) return names.join(" and ");+ return `${names.slice(0, 2).join(", ")} and ${names.length - 2} more`;+}++/**+ * The truthful half of a delete confirmation: what comes back, and what does not.+ *+ * Deliberately says the retained number out loud even when it dwarfs the reclaimed one, and+ * says nothing at all rather than guess when the preview is unavailable.+ */+export function DeleteImpactSummary({ impact }: { impact: DeleteImpact | null }) {+ if (!impact) return null;+ if (impact.blocked_by.length > 0) {+ return (+ <span className="mt-2 block text-ui-12p5 text-destructive">+ These are shared assets that {joinNames(impact.blocked_by)} still needs, so they cannot+ be removed yet. Delete those models first.+ </span>+ );+ }+ const retained = impact.retained_companions.reduce((sum, c) => sum + c.size_bytes, 0);+ const freeable = impact.freeable_companions.reduce((sum, c) => sum + c.size_bytes, 0);+ return (+ <span className="mt-2 block space-y-1 text-ui-12p5">+ <span className="block text-foreground" data-testid="delete-impact-reclaimed">+ Frees {formatBytes(impact.reclaimed_bytes)} of disk space.+ </span>+ {retained > 0 ? (+ <span className="block text-muted-foreground" data-testid="delete-impact-retained">+ {formatBytes(retained)} of shared assets stay on disk:{" "}+ {joinNames(impact.retained_companions.map((c) => c.repo_id))} is still needed by{" "}+ {joinNames(+ Array.from(new Set(impact.retained_companions.flatMap((c) => c.needed_by))),+ )}+ .+ </span>+ ) : null}+ {freeable > 0 ? (+ <span className="block text-muted-foreground" data-testid="delete-impact-freeable">+ This also leaves {formatBytes(freeable)} of shared assets (+ {joinNames(impact.freeable_companions.map((c) => c.repo_id))}) that nothing else+ needs. Remove them with Free up space on the On Device tab.+ </span>+ ) : null}+ </span>+ );+}diff --git a/studio/frontend/src/features/hub/catalog/download-card.tsx b/studio/frontend/src/features/hub/catalog/download-card.tsxindex c313441c7e6..8f38f8d3e1c 100644--- a/studio/frontend/src/features/hub/catalog/download-card.tsx+++ b/studio/frontend/src/features/hub/catalog/download-card.tsx@@ -299,6 +299,7 @@ export function DeleteConfirmDialog({title,description,deleting,+ blocked = false,onConfirm,}: {open: boolean;@@ -306,6 +307,8 @@ export function DeleteConfirmDialog({title: string;description: ReactNode;deleting: boolean;+ /** Another installed model needs these files. Confirming would 400, so do not offer it. */+ blocked?: boolean;onConfirm: () => void;}) {return (@@ -319,7 +322,7 @@ export function DeleteConfirmDialog({<AlertDialogCancel disabled={deleting}>Cancel</AlertDialogCancel><AlertDialogActionvariant="destructive"- disabled={deleting}+ disabled={deleting || blocked}onClick={(e) => {e.preventDefault();onConfirm();diff --git a/studio/frontend/src/features/hub/catalog/free-up-space-dialog.tsx b/studio/frontend/src/features/hub/catalog/free-up-space-dialog.tsxnew file mode 100644index 00000000000..c9ff82b9771--- /dev/null+++ b/studio/frontend/src/features/hub/catalog/free-up-space-dialog.tsx@@ -0,0 +1,200 @@+// 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 { Button } from "@/components/ui/button";+import { Checkbox } from "@/components/ui/checkbox";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { Spinner } from "@/components/ui/spinner";+import { formatBytes } from "@/features/hub/lib/format";+import {+ type OrphanCompanion,+ deleteCachedModel,+ fetchOrphanCompanions,+} from "../inventory";+import { useHfTokenStore } from "@/features/hub/stores/hf-token-store";+import { toast } from "@/lib/toast";+import { useCallback, useEffect, useState } from "react";++/**+ * Remove companion assets that no installed model needs any more.+ *+ * An image GGUF loads its text encoders, VAE and tokenizer from a separate base repo that every+ * quant of the family shares, and that is usually the larger half of the footprint. Deleting the+ * last quant cannot take those with it, because the delete is scoped to one repo and nothing on+ * screen knows the sharing has ended. Without this dialog the only way to recover the space was+ * to hand-edit the Hugging Face cache.+ *+ * Nothing here runs on its own. The list is recomputed from what is installed each time the+ * dialog opens, every row is opt-in, and removal goes through the ordinary delete endpoint, so+ * the shared-asset guard applies to this path exactly as it does to a delete from a card.+ */+/**+ * One row per CACHE ROOT, so a repo cached twice appears twice and the repo id alone identifies+ * neither. Keying selection on it made one checkbox toggle both rows and gave the two list items+ * the same React key and the same checkbox id.+ */+const companionIdentity = (companion: OrphanCompanion) =>+ `${companion.repo_id}\u0000${companion.cache_path ?? ""}`;++export function FreeUpSpaceDialog({+ open,+ onOpenChange,+ onChange,+}: {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ onChange?: () => void;+}) {+ const [loading, setLoading] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [companions, setCompanions] = useState<OrphanCompanion[]>([]);+ const [selected, setSelected] = useState<Set<string>>(new Set());+ const [deleting, setDeleting] = useState(false);+ const hfToken = useHfTokenStore((s) => s.token);++ const refresh = useCallback(async () => {+ setLoading(true);+ setError(null);+ try {+ const result = await fetchOrphanCompanions();+ setCompanions(result.companions);+ // Empty, not everything. This dialog deletes, and its own contract is that every row is+ // opt-in; pre-checking them let one click remove every listed copy without the user having+ // chosen any of them.+ setSelected(new Set());+ } catch (e) {+ setError(e instanceof Error ? e.message : String(e));+ setCompanions([]);+ } finally {+ setLoading(false);+ }+ }, []);++ useEffect(() => {+ if (open) void refresh();+ }, [open, refresh]);++ const selectedCompanions = companions.filter((c) => selected.has(companionIdentity(c)));+ const selectedBytes = selectedCompanions.reduce(+ (sum, c) => sum + c.size_bytes,+ 0,+ );++ const runDelete = useCallback(async () => {+ setDeleting(true);+ let removed = 0;+ let freed = 0;+ try {+ for (const companion of selectedCompanions) {+ try {+ await deleteCachedModel(+ companion.repo_id,+ undefined,+ hfToken || undefined,+ companion.cache_path ?? undefined,+ true,+ );+ removed += 1;+ freed += companion.size_bytes;+ } catch (e) {+ toast.error(`Could not remove ${companion.repo_id}`, {+ description: e instanceof Error ? e.message : String(e),+ });+ }+ }+ } finally {+ setDeleting(false);+ }+ if (removed > 0) {+ toast.success(+ `Removed ${removed} unused asset${removed === 1 ? "" : "s"}, freeing ${formatBytes(freed)}`,+ );+ onChange?.();+ }+ onOpenChange(false);+ }, [hfToken, onChange, onOpenChange, selectedCompanions]);++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="max-w-[520px]">+ <DialogHeader>+ <DialogTitle>Free up space</DialogTitle>+ <DialogDescription>+ Shared model assets, such as text encoders, VAE and tokenizers, that no installed+ model needs any more. Anything still in use by a model on this device is not listed+ and cannot be removed here.+ </DialogDescription>+ </DialogHeader>+ {loading ? (+ <div className="flex items-center gap-2 py-6 text-ui-13 text-muted-foreground">+ <Spinner /> Checking what is still in use…+ </div>+ ) : error ? (+ <p className="py-6 text-ui-13 text-destructive">{error}</p>+ ) : companions.length === 0 ? (+ <p className="py-6 text-ui-13 text-muted-foreground" data-testid="free-up-space-empty">+ Nothing to clean up. Every cached asset is still needed by a model you have+ installed.+ </p>+ ) : (+ <ul className="flex max-h-[260px] flex-col gap-1 overflow-y-auto py-1">+ {companions.map((companion, index) => (+ <li+ key={companionIdentity(companion)}+ className="flex items-center gap-3 rounded-[10px] px-2 py-2 hover:bg-muted/50"+ >+ <Checkbox+ id={`orphan-${index}`}+ checked={selected.has(companionIdentity(companion))}+ onCheckedChange={(checked) =>+ setSelected((prev) => {+ const next = new Set(prev);+ if (checked) next.add(companionIdentity(companion));+ else next.delete(companionIdentity(companion));+ return next;+ })+ }+ />+ <label+ htmlFor={`orphan-${index}`}+ className="min-w-0 flex-1 cursor-pointer truncate text-ui-13"+ >+ {companion.repo_id}+ </label>+ <span className="shrink-0 text-ui-12p5 text-muted-foreground">+ {formatBytes(companion.size_bytes)}+ </span>+ </li>+ ))}+ </ul>+ )}+ <DialogFooter>+ <Button+ variant="ghost"+ disabled={deleting}+ onClick={() => onOpenChange(false)}+ >+ Cancel+ </Button>+ <Button+ variant="destructive"+ disabled={deleting || selectedCompanions.length === 0}+ onClick={() => void runDelete()}+ data-testid="free-up-space-confirm"+ >+ {deleting+ ? "Removing…"+ : `Remove ${formatBytes(selectedBytes)}`}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/studio/frontend/src/features/hub/catalog/gguf-download-card.tsx b/studio/frontend/src/features/hub/catalog/gguf-download-card.tsxindex ba0ef297131..d872047764c 100644--- a/studio/frontend/src/features/hub/catalog/gguf-download-card.tsx+++ b/studio/frontend/src/features/hub/catalog/gguf-download-card.tsx@@ -89,6 +89,7 @@ import {GgufDownloadStatusCard,GgufDownloadingFallbackCard,} from "./gguf-status-cards";+import { DeleteImpactSummary, useDeleteImpact } from "./delete-impact";import { useDeleteConfirmAction } from "./use-delete-confirm-action";import { useDownloadCardState } from "./use-download-card-state";import { useGgufVariantFetchState } from "./use-gguf-variant-fetch-state";@@ -787,6 +788,7 @@ export function GgufDownloadCard({const deleteTargetLabel = deleteTargetVariant? ggufVariantDisplayLabel(deleteTargetVariant): deleteTarget;+ const deleteImpact = useDeleteImpact(deleteTarget !== null, repoId, deleteTarget);const { deleting, runDelete } = useDeleteConfirmAction({action: async () => {if (!deleteTarget) return;@@ -899,6 +901,7 @@ export function GgufDownloadCard({}}title="Delete quantization?"deleting={deleting}+ blocked={(deleteImpact?.blocked_by.length ?? 0) > 0}onConfirm={() => void runDelete()}description={<>@@ -907,6 +910,7 @@ export function GgufDownloadCard({{repoId} ({deleteTargetLabel})</span>{" "}from disk. You can re-download it later.+ <DeleteImpactSummary impact={deleteImpact} /></>}/>diff --git a/studio/frontend/src/features/hub/catalog/local-on-device-card.tsx b/studio/frontend/src/features/hub/catalog/local-on-device-card.tsxindex dba89a018e6..db5f4dacbc4 100644--- a/studio/frontend/src/features/hub/catalog/local-on-device-card.tsx+++ b/studio/frontend/src/features/hub/catalog/local-on-device-card.tsx@@ -65,6 +65,7 @@ import {} from "./download-card";import { PathInfoButton } from "./path-info-button";import { TransportConflictDialog } from "./transport-conflict-dialog";+import { DeleteImpactSummary, useDeleteImpact } from "./delete-impact";import { useCardDelete } from "./use-card-delete";import { useGgufVariantFetchState } from "./use-gguf-variant-fetch-state";@@ -263,6 +264,7 @@ export function LocalOnDeviceCard({// Update availability is derived from the GGUF variant metadata; offline rows// keep the button hidden because there is no remote revision to fetch.const online = useOnlineStatus();+ const deleteImpact = useDeleteImpact(deleteOpen && Boolean(repoId), repoId ?? "");const { deleting, runDelete } = useCardDelete({action: async () => {if (!repoId) return;@@ -714,12 +716,16 @@ export function LocalOnDeviceCard({}}title="Delete cached model?"deleting={deleting}+ // Same gate the model row menu applies: when an installed image model still needs these+ // assets the summary says so, and leaving Delete enabled only bought the user a 400.+ blocked={(deleteImpact?.blocked_by.length ?? 0) > 0}onConfirm={() => void runDelete()}description={<>This will remove{" "}<span className="font-medium text-foreground">{repoId}</span> andits downloaded files from disk. You can re-download it later.+ <DeleteImpactSummary impact={deleteImpact} /></>}/>diff --git a/studio/frontend/src/features/hub/catalog/models-catalog-rows.tsx b/studio/frontend/src/features/hub/catalog/models-catalog-rows.tsxindex a6caadc3a9b..bc58fe5afdf 100644--- a/studio/frontend/src/features/hub/catalog/models-catalog-rows.tsx+++ b/studio/frontend/src/features/hub/catalog/models-catalog-rows.tsx@@ -762,6 +762,8 @@ export const InventoryRow = memo(function InventoryRow({}del={deletableRepoId ? {title: isDataset ? "Delete cached dataset?" : "Delete cached model?",+ // Datasets have no companion base repo, so only models get a preview.+ impact: isDataset ? undefined : { repoId: deletableRepoId },description: (<>This will remove{" "}diff --git a/studio/frontend/src/features/hub/catalog/models-toolbar.tsx b/studio/frontend/src/features/hub/catalog/models-toolbar.tsxindex 6190f96675c..22a938aceab 100644--- a/studio/frontend/src/features/hub/catalog/models-toolbar.tsx+++ b/studio/frontend/src/features/hub/catalog/models-toolbar.tsx@@ -15,6 +15,7 @@ import {AiChipIcon,CancelCircleIcon,Database02Icon,+ Delete02Icon,FolderSearchIcon,Search01Icon,SlidersHorizontalIcon,@@ -72,6 +73,7 @@ export const ModelsToolbar = memo(function ModelsToolbar({fitOnDeviceOnly,onFitOnDeviceOnlyChange,onManageLocalFolders,+ onFreeUpSpace,onOpenFineTune,}: {tab: ModelsTab;@@ -91,6 +93,7 @@ export const ModelsToolbar = memo(function ModelsToolbar({fitOnDeviceOnly: boolean;onFitOnDeviceOnlyChange: (value: boolean) => void;onManageLocalFolders: () => void;+ onFreeUpSpace: () => void;/** Opens the curated "Fine-tune ready" channel (discover only). Exposed as a* format-dropdown option rather than a standalone feed section. */onOpenFineTune: () => void;@@ -355,6 +358,32 @@ export const ModelsToolbar = memo(function ModelsToolbar({</Tooltip>)}+ {tab === "downloaded" && !isDataset && (+ <Tooltip>+ <TooltipTrigger asChild={true}>+ <button+ type="button"+ onClick={onFreeUpSpace}+ data-testid="free-up-space-trigger"+ className={cn(+ triggerBase,+ "field-filter inline-flex h-9 shrink-0 items-center gap-1.5 rounded-full px-3 text-ui-12p5",+ )}+ >+ <HugeiconsIcon+ icon={Delete02Icon}+ strokeWidth={1.75}+ className="size-3.5"+ />+ Free up space+ </button>+ </TooltipTrigger>+ <TooltipContent side="bottom" sideOffset={6}>+ Remove shared model assets no installed model needs+ </TooltipContent>+ </Tooltip>+ )}+{!isDataset && (<HubOptionMenu<FormatMenuValue>value={formatFilter}diff --git a/studio/frontend/src/features/hub/catalog/safetensors-download-card.tsx b/studio/frontend/src/features/hub/catalog/safetensors-download-card.tsxindex d1211942baf..4b79a37c967 100644--- a/studio/frontend/src/features/hub/catalog/safetensors-download-card.tsx+++ b/studio/frontend/src/features/hub/catalog/safetensors-download-card.tsx@@ -37,6 +37,7 @@ import {} from "./download-card";import { QuantOptionsMenu } from "./gguf-download-card";import { useCardDelete } from "./use-card-delete";+import { DeleteImpactSummary, useDeleteImpact } from "./delete-impact";import { useDownloadCardState } from "./use-download-card-state";function formatModelLabel(modelFormat?: ModelInventoryFormat | null): string {@@ -172,6 +173,14 @@ export function SafetensorsDownloadCard({!isActive &&!isLoadingThisModel;+ // Same preview the On Device and picker rows run: without it this card kept an enabled Delete+ // for a companion base an installed image GGUF still needs, and the refusal arrived as a 400+ // after the user confirmed.+ const deleteImpact = useDeleteImpact(+ deleteRepoOpen && Boolean(repoId),+ repoId ?? "",+ );+return (<div className="flex w-full flex-col gap-2"><DownloadCard@@ -185,6 +194,7 @@ export function SafetensorsDownloadCard({}}title="Delete cached model?"deleting={deleting}+ blocked={(deleteImpact?.blocked_by.length ?? 0) > 0}onConfirm={() => void runDelete()}description={<>@@ -195,6 +205,7 @@ export function SafetensorsDownloadCard({? ` (${formatBytes(modelTotalBytes)})`: ""}{" "}from disk. You can re-download it later.+ <DeleteImpactSummary impact={deleteImpact} /></>}/>diff --git a/studio/frontend/src/features/hub/hub-page.tsx b/studio/frontend/src/features/hub/hub-page.tsxindex e1c32c7d3ee..d8ae7d682d9 100644--- a/studio/frontend/src/features/hub/hub-page.tsx+++ b/studio/frontend/src/features/hub/hub-page.tsx@@ -59,6 +59,7 @@ import {ResultListHeader,} from "./catalog/models-table";import { ModelsToolbar } from "./catalog/models-toolbar";+import { FreeUpSpaceDialog } from "./catalog/free-up-space-dialog";import { OnDeviceFoldersDialog } from "./catalog/on-device-folders-dialog";import { OwnerScopeToggle } from "./catalog/owner-scope-toggle";import { useDiscoverSearch } from "./hooks/use-discover-search";@@ -574,6 +575,7 @@ export function ModelsPage() {const [inventoryTypeFilter, setInventoryTypeFilter] =useState<ModelTypeFilter>("all");const [foldersDialogOpen, setFoldersDialogOpen] = useState(false);+ const [freeUpSpaceOpen, setFreeUpSpaceOpen] = useState(false);const [discoverFetchIntent, setDiscoverFetchIntent] = useState(0);const [sortBrowseActive, setSortBrowseActive] = useState(false);@@ -1233,6 +1235,7 @@ export function ModelsPage() {() => setFoldersDialogOpen(true),[],);+ const handleFreeUpSpace = useCallback(() => setFreeUpSpaceOpen(true), []);const handleSwitchDevice = useCallback(() => handleTabChange("downloaded"),[handleTabChange],@@ -1884,6 +1887,7 @@ export function ModelsPage() {fitOnDeviceOnly={fitOnDeviceOnly}onFitOnDeviceOnlyChange={setFitOnDeviceOnly}onManageLocalFolders={handleManageLocalFolders}+ onFreeUpSpace={handleFreeUpSpace}onOpenFineTune={() => handleOpenList("finetune")}/></HubTopBar>@@ -1992,6 +1996,11 @@ export function ModelsPage() {onOpenChange={setFoldersDialogOpen}onInventoryChange={refreshInventory}/>+ <FreeUpSpaceDialog+ open={freeUpSpaceOpen}+ onOpenChange={setFreeUpSpaceOpen}+ onChange={refreshInventory}+ /><ExternalLinkConfirmDialog /></div>);diff --git a/studio/frontend/src/features/hub/index.ts b/studio/frontend/src/features/hub/index.tsindex 688095612bf..d5308b96f81 100644--- a/studio/frontend/src/features/hub/index.ts+++ b/studio/frontend/src/features/hub/index.ts@@ -117,6 +117,10 @@ export {DeleteConfirmDialog,UpdateConfirmDialog,} from "./catalog/download-card";+export {+ DeleteImpactSummary,+ useDeleteImpact,+} from "./catalog/delete-impact";export { HubOptionMenu, type HubOption } from "./catalog/hub-option-menu";export { DotTag } from "./catalog/dot-tag";export { TransportConflictDialog } from "./catalog/transport-conflict-dialog";diff --git a/studio/frontend/src/features/hub/inventory/api.ts b/studio/frontend/src/features/hub/inventory/api.tsindex bc9e713540a..f03483028f1 100644--- a/studio/frontend/src/features/hub/inventory/api.ts+++ b/studio/frontend/src/features/hub/inventory/api.ts@@ -283,13 +283,67 @@ export async function deleteCachedDataset(bumpInventoryVersion();}+export interface CompanionAssetInfo {+ repo_id: string;+ size_bytes: number;+ needed_by: string[];+}++export interface DeleteImpact {+ repo_id: string;+ variant?: string | null;+ reclaimed_bytes: number;+ retained_companions: CompanionAssetInfo[];+ freeable_companions: CompanionAssetInfo[];+ blocked_by: string[];+}++/** What a delete would actually reclaim and leave behind. Never throws: the confirm dialog+ * still has to open if this preview is unavailable, it just falls back to the plain wording. */+export async function fetchDeleteImpact(+ repoId: string,+ variant?: string | null,+): Promise<DeleteImpact | null> {+ try {+ const response = await authFetch("/api/hub/delete-impact", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(+ variant ? { repo_id: repoId, variant } : { repo_id: repoId },+ ),+ });+ if (!response.ok) return null;+ return (await response.json()) as DeleteImpact;+ } catch {+ return null;+ }+}++export interface OrphanCompanion {+ repo_id: string;+ size_bytes: number;+ cache_path?: string | null;+}++export async function fetchOrphanCompanions(): Promise<{+ companions: OrphanCompanion[];+ total_bytes: number;+}> {+ const response = await authFetch("/api/hub/orphan-companions");+ return await parseJsonOrThrow<{+ companions: OrphanCompanion[];+ total_bytes: number;+ }>(response);+}+export async function deleteCachedModel(repoId: string,variant?: string,hfToken?: string | null,cachePath?: string | null,+ onlyIfOrphan?: boolean,): Promise<void> {- const payload: Record<string, string> = { repo_id: repoId };+ const payload: Record<string, string | boolean> = { repo_id: repoId };if (variant) {payload.variant = variant;}@@ -297,6 +351,11 @@ export async function deleteCachedModel(if (cachePath) {payload.cache_path = cachePath;}+ // Free up space acts on a list that can be minutes old. The server re-derives the orphan+ // condition just before unlinking and 409s if a download turned the row into a real model.+ if (onlyIfOrphan) {+ payload.only_if_orphan = true;+ }const response = await authFetch("/api/hub/delete-cached", {method: "DELETE",headers: { "Content-Type": "application/json", ...hubTokenHeader(hfToken) },diff --git a/studio/frontend/src/features/hub/inventory/index.ts b/studio/frontend/src/features/hub/inventory/index.tsindex 5976d49ad31..d9b2802d1b5 100644--- a/studio/frontend/src/features/hub/inventory/index.ts+++ b/studio/frontend/src/features/hub/inventory/index.ts@@ -17,6 +17,8 @@ export {listCachedModels,deleteCachedDataset,deleteCachedModel,+ fetchDeleteImpact,+ fetchOrphanCompanions,invalidateGgufVariantsCache,listGgufVariants,listLocalDatasets,@@ -28,6 +30,8 @@ export {type CachedGgufRepo,type CachedModelRepo,type BaseModelSource,+ type CompanionAssetInfo,+ type DeleteImpact,type GgufVariantDetail,type GgufVariantsResponse,type LocalDatasetInfo,@@ -35,6 +39,7 @@ export {type LocalModelListResponse,type ModelInventoryFormat,type ModelInventoryRuntime,+ type OrphanCompanion,type ScanFolderInfo,} from "./api";export {diff --git a/studio/frontend/src/features/model-picker/components/model-selector/model-row-menu.tsx b/studio/frontend/src/features/model-picker/components/model-selector/model-row-menu.tsxindex 9de27f98f48..8f06ffd429c 100644--- a/studio/frontend/src/features/model-picker/components/model-selector/model-row-menu.tsx+++ b/studio/frontend/src/features/model-picker/components/model-selector/model-row-menu.tsx@@ -16,9 +16,11 @@ import { usePlatformStore } from "@/config/env";import { revealCachedModel } from "@/features/chat";import {DeleteConfirmDialog,+ DeleteImpactSummary,UpdateConfirmDialog,ggufVariantsMatch,subscribeJobListeners,+ useDeleteImpact,} from "@/features/hub";import { toast } from "@/lib/toast";import { cn } from "@/lib/utils";@@ -62,6 +64,9 @@ interface ModelRowMenuUpdate {interface ModelRowMenuDelete {title: string;description: ReactNode;+ /** Repo (and quant) to preview the delete for, so the dialog can state what it actually+ * reclaims and what shared assets it leaves behind. Omit to keep the plain wording. */+ impact?: { repoId: string; variant?: string | null };successMessage: string;disabled?: boolean;onConfirm: () => Promise<void> | void;@@ -104,6 +109,11 @@ export function ModelRowMenu({deviceType === "mac" ? "Reveal in Finder" : "Reveal in Folder";const [deleteOpen, setDeleteOpen] = useState(false);const [deleting, setDeleting] = useState(false);+ const deleteImpact = useDeleteImpact(+ deleteOpen && Boolean(del?.impact),+ del?.impact?.repoId ?? "",+ del?.impact?.variant,+ );const [updateOpen, setUpdateOpen] = useState(false);// Refresh the caller when this repo+variant's managed update completes@@ -288,8 +298,14 @@ export function ModelRowMenu({setDeleteOpen(nextOpen);}}title={del.title}- description={del.description}+ description={+ <>+ {del.description}+ <DeleteImpactSummary impact={deleteImpact} />+ </>+ }deleting={deleting}+ blocked={(deleteImpact?.blocked_by.length ?? 0) > 0}onConfirm={() => void handleDeleteConfirm()}/>)}diff --git a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsxindex 465cf964481..e60be6704b0 100644--- a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx+++ b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx@@ -1751,6 +1751,7 @@ function GgufVariantExpander({onDeleteVariant? {title: deleteVariantTitle,+ impact: { repoId, variant: v.quant },description: renderDeleteVariantDescription?.(v.quant,) ?? (@@ -3766,6 +3767,10 @@ export function HubModelPicker({}}del={{title: "Delete cached model?",+ // Same preview the Hub On Device row asks for, so a companion base an+ // installed image model still needs shows the reason and a disabled+ // Delete rather than an enabled one that comes back 400.+ impact: { repoId: entry.repoId, variant: entry.quant },description: (<>This will remove{" "}@@ -3860,6 +3865,7 @@ export function HubModelPicker({}}del={{title: "Delete cached model?",+ impact: { repoId: c.repo_id, variant: variant.quant },description: (<>This will remove{" "}@@ -4033,6 +4039,7 @@ export function HubModelPicker({}}del={{title: "Delete cached model?",+ impact: { repoId: c.repo_id },description: (<>This will remove{" "}