Skip to content

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.

59.7 KB
Raw Blame
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0

"""Cached model deletion."""

from __future__ import annotations

from hub.services.models import account_access

import asyncio
import errno
import inspect
from pathlib import Path
from typing import Optional

try:
    from huggingface_hub.utils._shared_blobs import shared_blob_target, sweep_shared_blob

    # Private huggingface_hub API: a release that keeps the names but changes the arguments would raise TypeError mid-delete, after the snapshot links are gone, so fall back to the plain unlink instead.
    inspect.signature(shared_blob_target).bind(Path(), Path())
    inspect.signature(sweep_shared_blob).bind(Path(), cache_dir = Path())
except (ImportError, TypeError, ValueError):
    shared_blob_target = None
    sweep_shared_blob = None

from fastapi import HTTPException
from loggers import get_logger

from hub.utils import download_manifest
from hub.utils import download_registry
from hub.utils import inventory_scan as hf_cache_scan
from hub.utils.gguf import (
    bare_quant_alias,
    extract_quant_token,
    gguf_listed_checkpoints,
    group_gguf_variant_files,
    gguf_variant_family,
    gguf_variant_key,
    gguf_variant_keys_by_checkpoint,
    is_qualified_gguf_variant_key,
    quant_token_with_bpw,
    remove_appledouble_sidecar,
    is_reclaimable_drafter_path as _is_reclaimable_drafter_path,
)
from hub.utils.hf_cache_state import (
    INCOMPLETE_SUFFIX,
    iter_repo_cache_dirs,
    purge_partial_repo,
    purge_repo_cache_dirs,
    resolve_delete_target_root,
    snapshot_selection_key,
)
from hub.utils.paths import (
    is_valid_gguf_variant as _is_valid_gguf_variant,
    is_valid_repo_id as _is_valid_repo_id,
    resolve_cached_repo_id_case,
)
from hub.services import resolve_destructive_repo_ids
from hub.services.models import cache_inventory, downloads, gguf_variants
from hub.services.models.common import (
    _is_gguf_filename,
    _is_imatrix_filename,
    _is_main_gguf_filename,
    _is_mmproj_filename,
)
from utils.paths.path_utils import is_appledouble_metadata

logger = get_logger(__name__)


def _snapshot_blob_reference_counts(repo_dir: Optional[Path]) -> dict[Path, int]:
    """Map each blob's realpath to its live snapshot symlink count, so per-variant deletion never unlinks a blob another revision still references (call after the target variant's own symlinks are removed)."""
    counts: dict[Path, int] = {}
    if repo_dir is None:
        return counts
    snapshots = repo_dir / "snapshots"
    if not snapshots.is_dir():
        return counts
    try:
        entries = list(snapshots.rglob("*"))
    except OSError:
        return counts
    for link in entries:
        try:
            if not link.is_symlink():
                continue
            target = link.resolve()
        except OSError:
            continue
        counts[target] = counts.get(target, 0) + 1
    return counts


def _blob_hash_from_path(blob: Path) -> Optional[str]:
    name = blob.name
    if not name or name.endswith(INCOMPLETE_SUFFIX):
        return None
    return name


def _unlink_variant_blob(blob: Path, cache_dir: Optional[Path]) -> int:
    shared_target = None
    if shared_blob_target is not None:
        # huggingface_hub matches paths lexically, so try the cache root in the blob's own form first: a resolved root misses a symlinked cache or a Windows 8.3 short name and would leak the payload.
        for root in dict.fromkeys(
            r for r in (blob.parent.parent.parent, cache_dir) if r is not None
        ):
            shared_target = shared_blob_target(blob, root)
            if shared_target is not None:
                cache_dir = root
                break
    if shared_target is None:
        freed = blob.stat().st_size
        blob.unlink()
        return freed
    blob.unlink()
    return sweep_shared_blob(shared_target, cache_dir = cache_dir)


def _path_exists_or_symlink(path: Path) -> bool:
    try:
        return path.is_symlink() or path.exists()
    except OSError:
        return False


def _unlink_snapshot_entry(snap: Path) -> int:
    """unlink a snapshot entry and its AppleDouble sidecar, counting only the entry."""
    removed = 0
    if _path_exists_or_symlink(snap):
        snap.unlink()
        removed += 1
    remove_appledouble_sidecar(snap)
    return removed


def _revision_file_matches(revision, predicate) -> list[tuple[Path, Optional[Path], str]]:
    matches: list[tuple[Path, Optional[Path], str]] = []
    snapshot = getattr(revision, "snapshot_path", None)
    for f in getattr(revision, "files", ()):
        name = str(getattr(f, "file_name", ""))
        file_path = getattr(f, "file_path", None)
        if snapshot and file_path:
            try:
                name = Path(file_path).relative_to(Path(snapshot)).as_posix()
            except ValueError:
                pass
        if not predicate(name):
            continue
        if not file_path:
            continue
        # skip only proven AppleDouble metadata; any other matching name is a deletion target.
        if is_appledouble_metadata(Path(file_path)):
            continue
        blob_path = getattr(f, "blob_path", None)
        matches.append(
            (
                Path(file_path),
                Path(blob_path) if blob_path else None,
                name,
            )
        )
    return matches


def _repo_file_matches(target_repo, predicate) -> list[tuple[Path, Optional[Path], str]]:
    """match relative paths because bare names lose layouts such as ``dspark/`` and ``MTP/``."""
    matches: list[tuple[Path, Optional[Path], str]] = []
    for revision in getattr(target_repo, "revisions", ()):
        matches.extend(_revision_file_matches(revision, predicate))
    return matches


def _has_remaining_main_gguf(target_repo) -> bool:
    return any(
        _path_exists_or_symlink(snap)
        for snap, _blob, _name in _repo_file_matches(
            target_repo,
            _is_main_gguf_filename,
        )
    )


def _remove_empty_variant_dirs(
    target_repos: list,
    variant: str,
    protected_revisions: frozenset[str] = frozenset(),
) -> tuple[int, list[str]]:
    """remove empty variant folders and return their count plus non-concurrent failures."""
    # qualified keys own only their exact folder because token-only folders can be another build.
    qualified = (
        is_qualified_gguf_variant_key(variant)
        or (quant_token_with_bpw(variant) or "").lower() == variant.lower()
    )
    variant_key = (
        variant.lower() if qualified else (extract_quant_token(variant) or variant).lower()
    )
    removed = 0
    failures: list[str] = []
    for target_repo in target_repos:
        repo_path = getattr(target_repo, "repo_path", None)
        if not repo_path:
            continue
        snapshots = Path(repo_path) / "snapshots"
        if not snapshots.is_dir():
            continue
        try:
            snap_dirs = [s for s in snapshots.iterdir() if s.is_dir() and not s.is_symlink()]
        except OSError:
            continue
        for snap in snap_dirs:
            if snap.name in protected_revisions:
                continue
            try:
                subs = list(snap.iterdir())
            except OSError:
                continue
            for sub in subs:
                try:
                    if sub.is_symlink() or not sub.is_dir():
                        continue
                    folder_quant = quant_token_with_bpw(sub.name)
                    matches = (
                        folder_quant is not None and folder_quant.lower() == variant_key
                    ) or sub.name.lower() == variant.lower()
                    if not matches or any(sub.iterdir()):
                        continue
                except OSError:
                    continue
                try:
                    sub.rmdir()
                    removed += 1
                except OSError as e:
                    # ignore ENOTEMPTY from concurrent refills; surface locked or read-only directories.
                    if e.errno != errno.ENOTEMPTY:
                        failures.append(f"{sub.name}: {e}")
    return removed, failures


def _remove_empty_snapshot_dirs(
    target_repos: list, protected_revisions: frozenset[str] = frozenset()
) -> tuple[int, list[str]]:
    removed = 0
    failures: list[str] = []
    for target_repo in target_repos:
        repo_path = getattr(target_repo, "repo_path", None)
        if not repo_path:
            continue
        snapshots = Path(repo_path) / "snapshots"
        if not snapshots.is_dir():
            continue
        try:
            snap_dirs = [s for s in snapshots.iterdir() if s.is_dir() and not s.is_symlink()]
        except OSError:
            continue
        for snap in snap_dirs:
            if snap.name in protected_revisions:
                continue
            try:
                snap.rmdir()
                removed += 1
            except OSError as e:
                if e.errno != errno.ENOTEMPTY:
                    failures.append(f"{snap.name}: {e}")
    return removed, failures


def _revision_selection_key(revision) -> tuple[float, str]:
    snapshot = getattr(revision, "snapshot_path", None)
    return snapshot_selection_key(Path(snapshot)) if snapshot else (0.0, "")


def _rank_complete_snapshots(
    repo_id: str, revisions: list, complete: list[set[str]]
) -> list[set[str]]:
    from hub.utils.gguf_sources import _prefer_duplicate

    selected: dict[str, tuple[int, Path]] = {}
    for index, (revision, variants) in enumerate(zip(revisions, complete)):
        snapshot_path = getattr(revision, "snapshot_path", None)
        if not snapshot_path:
            continue
        snapshot = Path(snapshot_path)
        for variant in variants:
            key = variant.lower()
            previous = selected.get(key)
            if previous is None or _prefer_duplicate(repo_id, variant, previous[1], snapshot):
                selected[key] = (index, snapshot)
    return [
        {variant for variant in variants if selected[variant.lower()][0] == index}
        for index, variants in enumerate(complete)
    ]


def _main_gguf_variant_keys(target_repo, preferred_path: Optional[str] = None) -> dict[Path, str]:
    """use the lister's cross-snapshot readiness ranking so unlisted builds cannot claim the row."""
    revisions = sorted(
        getattr(target_repo, "revisions", ()), key = _revision_selection_key, reverse = True
    )
    matches = [_revision_file_matches(revision, _is_main_gguf_filename) for revision in revisions]
    names = [[name for _snap, _blob, name in revision] for revision in matches]
    complete = []
    for revision, revision_names in zip(revisions, names):
        snapshot = getattr(revision, "snapshot_path", None)
        snapshot_complete = (
            hf_cache_scan.complete_snapshot_variants(str(snapshot)) if snapshot else set()
        )
        listed_rows = group_gguf_variant_files((name, 0) for name in revision_names)
        complete.append({key for key in listed_rows if key in snapshot_complete})
    repo_id = str(getattr(target_repo, "repo_id", ""))
    if repo_id:
        complete = _rank_complete_snapshots(repo_id, revisions, complete)
    listed = gguf_listed_checkpoints(names, complete)
    if preferred_path:
        wanted_path = Path(preferred_path)
        preferred_name = next(
            (name for revision in matches for snap, _blob, name in revision if snap == wanted_path),
            None,
        )
        if preferred_name is not None:
            listed.update(gguf_listed_checkpoints(((preferred_name,),)))
    keys: dict[Path, str] = {}
    for revision, revision_names in zip(matches, names):
        revision_keys = gguf_variant_keys_by_checkpoint(revision_names, listed)
        keys.update({snap: revision_keys[name] for snap, _blob, name in revision})
    return keys


def _main_key(snap: Path, main_keys: dict[Path, str]) -> str:
    return (main_keys.get(snap) or "").lower()


def _variant_keys_to_delete(
    target_repo,
    variant: str,
    preferred_path: Optional[str] = None,
) -> set[str]:
    """return lowercase keys, accepting a bare-quant alias only for one path-qualified key."""
    wanted = (variant or "").strip().lower()
    if not wanted or "/" in wanted:
        return {wanted}
    keys = {key.lower() for key in _main_gguf_variant_keys(target_repo, preferred_path).values()}
    if wanted in keys:
        return {wanted}
    # use path-qualified keys, not is_qualified_gguf_variant_key; H3 bare quants span partitions.
    aliased = {key for key in keys if "/" in key and bare_quant_alias(key).lower() == wanted}
    return aliased if len(aliased) == 1 else {wanted}


def _audio_cpp_package_scope(target_repo, variant: str) -> tuple[frozenset[str], frozenset[str]]:
    """return audio.cpp mix files and files protected by complete sibling mixes, else empty sets."""
    try:
        from core.inference.audio_cpp_models import package_variant_files
    except Exception:  # noqa: BLE001 - no audio.cpp support, no package layout
        return frozenset(), frozenset()
    names = [name for _snap, _blob, name in _repo_file_matches(target_repo, lambda name: True)]
    packages = package_variant_files(names)
    if not packages:
        return _umbrella_variant_scope(target_repo, variant)
    wanted = (variant or "").strip().lower()
    own = next((files for key, files in packages.items() if key.lower() == wanted), ())
    protected = {path for key, files in packages.items() if key.lower() != wanted for path in files}
    return frozenset(own), frozenset(protected)


def _umbrella_variant_scope(target_repo, variant: str) -> tuple[frozenset[str], frozenset[str]]:
    """``(own files, protected files)`` of one umbrella folder variant (``<Folder>/<file>`` key): its
    voice embeddings and configs go with it, unless another cached variant of the folder lists them.
    A sibling in the same directory still downloading is not listed yet, so its extras stay."""
    from core.inference.audio_cpp_models import folder_row_for_download, resolve

    repo_id = str(getattr(target_repo, "repo_id", ""))
    row = folder_row_for_download(repo_id, variant)
    model = resolve(row[0], network = False) if row else None
    if model is None:
        return frozenset(), frozenset()
    # Every umbrella folder downloads on the same repo, so only a peer under this directory counts.
    sibling_active = downloads.registry.has_active_peer_variant(
        repo_id, variant, prefix = variant.rsplit("/", 1)[0] + "/"
    )
    own: set[str] = set()
    protected: set[str] = set()
    for candidate in model.cache_variants:
        files = {f.path for f in candidate.files}
        if candidate.primary and gguf_variant_key(candidate.primary).lower() == variant.lower():
            own |= files if not sibling_active else {candidate.primary}
        else:
            protected |= files
    return frozenset(own - protected), frozenset(protected)


def _delete_gguf_variant_from_repos(
    repo_id: str,
    variant: str,
    target_repos: list,
    hf_token: Optional[str],
    *,
    sibling_active: bool = False,
    root: Optional[Path] = None,
    preferred_path: Optional[str] = None,
) -> dict:
    failures: list[str] = []
    removed_snapshots = 0
    deleted_bytes = 0
    deleted_blobs = 0
    completed_hashes: set[str] = set()
    selected_families: set[str] = set()

    for target_repo in target_repos:
        repo_dir = Path(target_repo.repo_path) if getattr(target_repo, "repo_path", None) else None
        wanted_keys = _variant_keys_to_delete(target_repo, variant, preferred_path)
        main_keys = _main_gguf_variant_keys(target_repo, preferred_path)
        package_files, protected = _audio_cpp_package_scope(target_repo, variant)
        matched = [
            match
            for match in _repo_file_matches(
                target_repo,
                lambda name: name in package_files or _is_main_gguf_filename(name),
            )
            if match[2] in package_files or _main_key(match[0], main_keys) in wanted_keys
            # keep components used by another downloaded mix, including MiniMax's shared decoder.
            if match[2] not in protected
        ]
        selected_families.update(
            gguf_variant_family(name).lower()
            for _snap, _blob, name in matched
            if _is_main_gguf_filename(name)
        )

        for snap, _blob, name in matched:
            try:
                removed_snapshots += _unlink_snapshot_entry(snap)
            except OSError as e:
                failures.append(f"{name}: {e}")

        companion_matches: list[tuple[Path, Optional[Path], str]] = []
        if matched and not sibling_active and not _has_remaining_main_gguf(target_repo):
            companion_matches = _repo_file_matches(
                target_repo,
                # no main GGUF remains, so its companions cannot be launched.
                lambda name: _is_gguf_filename(name)
                and (
                    _is_mmproj_filename(name)
                    or _is_reclaimable_drafter_path(name)
                    or _is_imatrix_filename(name)
                ),
            )
            for snap, _blob, name in companion_matches:
                try:
                    removed_snapshots += _unlink_snapshot_entry(snap)
                except OSError as e:
                    failures.append(f"{name}: {e}")

        ref_counts = _snapshot_blob_reference_counts(repo_dir)
        cache_dir = root
        if cache_dir is None and repo_dir is not None:
            cache_dir = repo_dir.parent
        seen_blobs: set[Path] = set()
        for _snap, blob, name in [*matched, *companion_matches]:
            if blob is None:
                continue
            blob_hash = _blob_hash_from_path(blob)
            if blob_hash:
                completed_hashes.add(blob_hash)
            try:
                blob_key = blob.resolve()
            except OSError:
                blob_key = blob
            if blob_key in seen_blobs:
                continue
            seen_blobs.add(blob_key)
            if ref_counts.get(blob_key, 0) > 0:
                continue
            try:
                if blob.exists():
                    deleted_bytes += _unlink_variant_blob(blob, cache_dir)
                    deleted_blobs += 1
            except OSError as e:
                failures.append(f"{name}: {e}")

    if failures:
        raise HTTPException(
            status_code = 409,
            detail = (
                f"Couldn't fully delete {variant} for {repo_id}: "
                f"{len(failures)} file(s) are in use. "
                "Unload the model and try again."
            ),
        )

    cleanup_variant: Optional[str] = variant
    protected_revisions: set[str] = set()
    manifest = download_manifest.read_manifest("model", repo_id, variant, hub_cache = root)
    manifest_families = (
        {
            gguf_variant_family(expected.path).lower()
            for expected in manifest.expected_files
            if _is_main_gguf_filename(expected.path)
        }
        if manifest is not None
        else set()
    )
    # bare-quant state is safe to purge only when its readable manifest identifies this checkpoint.
    if selected_families and not (
        manifest_families and manifest_families.issubset(selected_families)
    ):
        exact_family = next(iter(selected_families)) if len(selected_families) == 1 else None
        cleanup_variant = (
            exact_family if exact_family is not None and exact_family != variant.lower() else None
        )
        if manifest is not None and manifest.commit_hash:
            protected_revisions.add(manifest.commit_hash)

    if cleanup_variant is None:
        incomplete_result = gguf_variants.VariantIncompleteDeleteResult(deleted = 0, unresolved = False)
    else:
        incomplete_result = gguf_variants.delete_variant_incomplete_blobs_result(
            repo_id,
            cleanup_variant,
            hf_token,
            extra_hashes = frozenset(completed_hashes),
            companions = not sibling_active,
            root = root,
        )
    if incomplete_result.unresolved:
        raise HTTPException(
            status_code = 409,
            detail = (
                f"Couldn't fully delete {variant} for {repo_id}: partial "
                "download bytes exist but this variant's blob hashes are unavailable. "
                "Reconnect or provide access to the repo, then try again."
            ),
        )

    state_purged = (
        download_manifest.purge_state("model", repo_id, cleanup_variant, hub_cache = root)
        if cleanup_variant is not None
        else False
    )
    removed_dirs, dir_failures = (
        _remove_empty_variant_dirs(target_repos, cleanup_variant)
        if cleanup_variant is not None
        else (0, [])
    )
    removed_snap_dirs, snap_dir_failures = _remove_empty_snapshot_dirs(
        target_repos, frozenset(protected_revisions)
    )
    removed_dirs += removed_snap_dirs
    dir_failures.extend(snap_dir_failures)
    if dir_failures:
        raise HTTPException(
            status_code = 409,
            detail = (
                f"Couldn't fully delete {variant} for {repo_id}: "
                f"{len(dir_failures)} folder(s) could not be removed "
                "(read-only cache or in use). Try again."
            ),
        )
    if (
        removed_snapshots == 0
        and deleted_blobs == 0
        and incomplete_result.deleted == 0
        and not state_purged
        and removed_dirs == 0
    ):
        raise HTTPException(
            status_code = 404,
            detail = f"Variant {variant} not found in cache for {repo_id}",
        )

    freed_mb = deleted_bytes / (1024 * 1024)
    logger.info(
        f"Deleted {removed_snapshots} file(s) for {repo_id} variant {variant}: "
        f"{freed_mb:.1f} MB freed"
    )
    return {"status": "deleted", "repo_id": repo_id, "variant": variant}


def reclaim_replaced_gguf_variant(
    repo_id: str,
    variant: str,
    keep_main_hashes: frozenset[str],
    hf_token: Optional[str] = None,
    *,
    hub_cache: Optional[str | Path] = None,
    protected_revisions: frozenset[str] = frozenset(),
) -> dict:
    """Prune stale main-GGUF files for a variant after a replacement verified. Intentionally narrower than user-driven delete: it removes only same-variant main files whose local blob hash is not in *keep_main_hashes*, then unlinks their blobs only if no remaining snapshot references them. Shared companions and sibling variants are left intact.

    A publication-protocol caller holds its lock throughout this call and passes
    the published and in-flight commits as ``protected_revisions``.
    """
    if not keep_main_hashes:
        logger.info(
            "Skipping stale GGUF reclaim for %s [%s]: current main hashes unresolved",
            repo_id,
            variant,
        )
        return {
            "status": "skipped",
            "repo_id": repo_id,
            "variant": variant,
            "reason": "unresolved_hashes",
        }
    if not _is_valid_repo_id(repo_id) or not _is_valid_gguf_variant(variant):
        return {
            "status": "skipped",
            "repo_id": repo_id,
            "variant": variant,
            "reason": "invalid_target",
        }

    failures: list[str] = []
    removed_snapshots = 0
    deleted_blobs = 0
    deleted_bytes = 0
    variant_key = variant.lower()

    try:
        cache_scans = cache_inventory.all_hf_cache_scans()
    except Exception as e:
        logger.warning(
            "Skipping stale GGUF reclaim for %s [%s]: cache scan failed: %s",
            repo_id,
            variant,
            download_registry.scrub_secrets(str(e), hf_token = hf_token),
        )
        return {
            "status": "skipped",
            "repo_id": repo_id,
            "variant": variant,
            "reason": "scan_failed",
        }

    if hub_cache is None:
        from utils.hf_cache_settings import get_hf_cache_paths
        hub_cache = get_hf_cache_paths().hub_cache
    try:
        target_hub_cache = Path(hub_cache).expanduser().resolve(strict = False)
    except (OSError, RuntimeError, ValueError):
        target_hub_cache = Path(hub_cache).expanduser()

    candidate_repos = [
        repo_info
        for hf_cache in cache_scans
        for repo_info in hf_cache.repos
        if str(getattr(repo_info, "repo_type", "")) == "model"
        and str(getattr(repo_info, "repo_id", "")).lower() == repo_id.lower()
        and getattr(repo_info, "repo_path", None)
        and Path(repo_info.repo_path).parent.resolve(strict = False) == target_hub_cache
    ]
    try:
        matched_repo_ids = resolve_destructive_repo_ids(
            repo_id,
            [str(getattr(repo_info, "repo_id", "")) for repo_info in candidate_repos],
            noun = "models",
        )
    except HTTPException as e:
        detail = getattr(e, "detail", str(e))
        logger.warning(
            "Skipping stale GGUF reclaim for %s [%s]: %s",
            repo_id,
            variant,
            download_registry.scrub_secrets(str(detail), hf_token = hf_token),
        )
        return {
            "status": "skipped",
            "repo_id": repo_id,
            "variant": variant,
            "reason": "ambiguous_repo",
        }
    target_repos = [
        repo_info
        for repo_info in candidate_repos
        if str(getattr(repo_info, "repo_id", "")) in matched_repo_ids
    ]

    for target_repo in target_repos:
        repo_dir = Path(target_repo.repo_path) if getattr(target_repo, "repo_path", None) else None
        stale_matches: list[tuple[Path, Optional[Path], str]] = []
        # hashes from another build at this quant would look stale for this build.
        main_keys = _main_gguf_variant_keys(target_repo)
        matches = [
            match
            for match in _repo_file_matches(target_repo, _is_main_gguf_filename)
            if _main_key(match[0], main_keys) == variant_key
        ]
        for snap, blob, name in matches:
            if repo_dir is None:
                continue
            try:
                commit = snap.relative_to(repo_dir / "snapshots").parts[0]
            except (ValueError, IndexError):
                continue
            if commit in protected_revisions:
                continue
            # prune confirmed stale blobs only; non-symlink snapshot files lack identifiable hashes.
            blob_hash = (
                _blob_hash_from_path(blob)
                if cache_inventory._is_real_cache_blob(blob, repo_dir)
                else None
            )
            if blob_hash is None or blob_hash in keep_main_hashes:
                continue
            stale_matches.append((snap, blob, name))

        if not stale_matches:
            continue

        for snap, _blob, name in stale_matches:
            try:
                removed_snapshots += _unlink_snapshot_entry(snap)
            except OSError as e:
                failures.append(f"{name}: {e}")

        ref_counts = _snapshot_blob_reference_counts(repo_dir)
        seen_blobs: set[Path] = set()
        for _snap, blob, name in stale_matches:
            if blob is None:
                continue
            try:
                blob_key = blob.resolve()
            except OSError:
                blob_key = blob
            if blob_key in seen_blobs:
                continue
            seen_blobs.add(blob_key)
            if ref_counts.get(blob_key, 0) > 0:
                continue
            try:
                if blob.exists():
                    deleted_bytes += _unlink_variant_blob(blob, target_hub_cache)
                    deleted_blobs += 1
            except OSError as e:
                failures.append(f"{name}: {e}")

    removed_dirs = 0
    dir_failures: list[str] = []
    if target_repos:
        removed_dirs, dir_failures = _remove_empty_variant_dirs(
            target_repos, variant, protected_revisions
        )
        removed_snap_dirs, snap_dir_failures = _remove_empty_snapshot_dirs(
            target_repos, protected_revisions
        )
        removed_dirs += removed_snap_dirs
        dir_failures.extend(snap_dir_failures)
        failures.extend(dir_failures)

    if failures:
        logger.warning(
            "Stale GGUF reclaim for %s [%s] left %d failure(s): %s",
            repo_id,
            variant,
            len(failures),
            "; ".join(failures[:3]),
        )

    if removed_snapshots or deleted_blobs or removed_dirs:
        cache_inventory.invalidate_hf_cache_scans()
        logger.info(
            "Reclaimed stale GGUF %s [%s]: snapshots=%d blobs=%d dirs=%d freed=%.1f MB",
            repo_id,
            variant,
            removed_snapshots,
            deleted_blobs,
            removed_dirs,
            deleted_bytes / (1024 * 1024),
        )

    return {
        "status": "reclaimed",
        "repo_id": repo_id,
        "variant": variant,
        "removed_snapshots": removed_snapshots,
        "deleted_blobs": deleted_blobs,
        "removed_dirs": removed_dirs,
    }


def _loaded_id_matches_repo(loaded_id: str, repo_id: str) -> bool:
    """Match a loaded repo ID or an on-disk path inside any copy of the repo."""
    rid = repo_id.lower()
    lid = loaded_id.lower()
    if lid == rid or lid.startswith(f"{rid}/"):
        return True

    try:
        loaded_path = Path(loaded_id).expanduser().resolve(strict = False)
    except (OSError, RuntimeError, ValueError):
        return False
    # An on-device model outside the cache is named by its path (local_model_actions).
    if Path(repo_id).is_absolute():
        try:
            held = Path(repo_id).resolve(strict = False)
        except (OSError, RuntimeError, ValueError):
            return False
        return loaded_path == held or loaded_path.is_relative_to(held)
    for repo_dir in iter_repo_cache_dirs("model", repo_id):
        try:
            resolved_repo = repo_dir.resolve(strict = False)
            if loaded_path == resolved_repo or loaded_path.is_relative_to(resolved_repo):
                return True
        except (OSError, RuntimeError, ValueError):
            continue
    return False


def _loaded_repo_variant_blocks_delete(
    loaded_id: str, repo_id: str, delete_variant: Optional[str], loaded_variant: Optional[str]
) -> bool:
    if not _loaded_id_matches_repo(loaded_id, repo_id):
        return False
    if not delete_variant:
        return True
    if not loaded_variant:
        return True
    return loaded_variant.lower() == delete_variant.lower()


_LOAD_STATE_UNVERIFIABLE_DETAIL = (
    "Couldn't verify whether this model is still loaded for inference. "
    "Unload it if it is active, then try deleting again."
)


def _llama_cpp_blocks_delete(repo_id: str, variant: Optional[str]) -> bool:
    """Whether the llama.cpp backend holds *repo_id* (/variant). Acquiring fails open (import error means nothing loaded); reading load state is unguarded so a raise propagates and the caller fails closed rather than delete a live model."""
    try:
        from core.inference import model_slots
        from routes.inference import get_llama_cpp_backend

        backends = [get_llama_cpp_backend(), *(slot.llama for slot in model_slots.resident())]
        filling = model_slots.filling_model()
    except Exception as e:
        logger.debug(f"llama.cpp backend unavailable during delete guard for {repo_id}: {e}")
        return False
    if filling and _loaded_id_matches_repo(filling, repo_id):
        return True
    for backend in backends:
        loaded_id = backend.model_identifier
        if (backend.is_active or backend.is_loaded) and loaded_id:
            if _loaded_repo_variant_blocks_delete(
                loaded_id,
                repo_id,
                variant,
                getattr(backend, "hf_variant", None),
            ):
                return True
    return False


def _inference_backend_blocks_delete(repo_id: str) -> bool:
    """Whether the subprocess inference backend holds *repo_id*; same fail-open-on-acquire / surface-on-query contract as :func:`_llama_cpp_blocks_delete`."""
    try:
        from core.inference.orchestrator import peek_inference_backend
        from core.inference import model_slots

        primary = peek_inference_backend()
        kept = [slot.orchestrator for slot in model_slots.resident()]
    except Exception as e:
        logger.debug(f"Inference backend unavailable during delete guard for {repo_id}: {e}")
        return False
    for backend in (primary, *kept):
        if backend is None:
            continue
        active_name = backend.active_model_name
        if active_name and _loaded_id_matches_repo(active_name, repo_id):
            return True
    for backend in kept:
        if any(_loaded_id_matches_repo(m, repo_id) for m in getattr(backend, "loading_models", ())):
            return True
    return False


def _diffusion_blocks_delete(repo_id: str) -> Optional[str]:
    """The 400 detail if the Images backend holds *repo_id*, else None. Queries the ACTIVE engine: on a native selection the diffusers singleton reports unloaded while sd-cli still generates from the cached GGUF. Same fail-open-on-acquire contract as :func:`_llama_cpp_blocks_delete`."""
    try:
        from core.inference.diffusion_engine_router import get_active_diffusion_engine
        engine = get_active_diffusion_engine()
    except Exception as e:
        logger.debug(f"Diffusion engine unavailable during delete guard for {repo_id}: {e}")
        return None
    status = engine.status()
    if status.get("loaded") and status.get("repo_id"):
        if _loaded_id_matches_repo(str(status["repo_id"]), repo_id):
            return "Unload the model before deleting"
    # sd.cpp re-reads companion VAE / text-encoder files every generation and status().repo_id covers only the main GGUF, so refuse the companions too.
    for lid in getattr(engine, "loaded_repo_ids", tuple)():
        if _loaded_id_matches_repo(str(lid), repo_id):
            return "Unload the model before deleting"
    # A downloading repo still reports loaded=False, but deleting would pull blobs from under the in-flight fetch.
    for lid in getattr(engine, "loading_repo_ids", tuple)():
        if _loaded_id_matches_repo(str(lid), repo_id):
            return "An Images model load is using this repo; wait for it to finish"
    # Cancelled but not yet unwound: deleting here yanks blobs from under a live Hub call.
    for lid in getattr(engine, "draining_repo_ids", tuple)():
        if _loaded_id_matches_repo(str(lid), repo_id):
            return "An Images model load is still releasing this repo; wait for it to finish"
    return None


def any_model_load_blocks_cache_clear() -> Optional[str]:
    """Any loaded model blocks a clear (sd.cpp rereads companion files); a raising backend fails closed."""
    try:
        from core.inference import model_slots
        from routes.inference import get_llama_cpp_backend

        backend = get_llama_cpp_backend()
        kept = model_slots.resident()
        kept_loading = model_slots.any_loading()
    except Exception as exc:  # noqa: BLE001 - unavailable is not "in use"
        logger.debug(f"llama.cpp backend unavailable during the cache-clear guard: {exc}")
    else:
        if (backend.is_loaded or backend.is_active) and backend.model_identifier:
            return "Unload the model before clearing the model cache"
        if any(
            model_slots.in_use(slot) or slot.llama.is_loaded or slot.llama.is_active
            for slot in kept
        ):
            return "Unload the model before clearing the model cache"
        if kept_loading:
            return "A model load is using the cache; wait for it to finish"

    # An HF-backed chat load has no llama-server until its GGUF downloads, and those files
    # bypass the download registry, so is_active and the reservation miss it.
    try:
        from core.inference.llama_cpp import chat_load_active
        loading_chat = chat_load_active()
    except Exception as exc:  # noqa: BLE001 - unavailable is not "in use", as above
        logger.debug(f"Chat load state unavailable during the cache-clear guard: {exc}")
    else:
        if loading_chat:
            return "A model load is using the cache; wait for it to finish"

    try:
        from core.inference.orchestrator import peek_inference_backend

        # Peek, never construct: building one just to learn nothing is loaded imports torch.
        engine = peek_inference_backend()
    except Exception as exc:  # noqa: BLE001
        logger.debug(f"Inference backend unavailable during the cache-clear guard: {exc}")
    else:
        if engine is not None and engine.active_model_name:
            return "Unload the model before clearing the model cache"

    for label, load in (
        ("Images", "core.inference.diffusion_engine_router:get_active_diffusion_engine"),
        ("Video", "core.inference.video:get_video_backend"),
    ):
        module_name, _, attr = load.partition(":")
        try:
            module = __import__(module_name, fromlist = [attr])
            held = getattr(module, attr)()
        except Exception as exc:  # noqa: BLE001
            logger.debug(f"{label} backend unavailable during the cache-clear guard: {exc}")
            continue
        if held is None:
            continue
        if held.status().get("loaded"):
            return "Unload the model before clearing the model cache"
        if any(getattr(held, "loaded_repo_ids", tuple)()):
            return "Unload the model before clearing the model cache"
        if any(getattr(held, "loading_repo_ids", tuple)()):
            return f"An {label} model load is using the cache; wait for it to finish"
        # Cancelled loads keep reading in _prefetch_files while draining; clear-all must refuse too.
        if any(getattr(held, "draining_repo_ids", tuple)()):
            return f"An {label} model load is still unwinding; wait for it to finish"

    # Dictation sidecars read the same hub cache, so a resident STT worker blocks the clear.
    try:
        from core.inference import stt_registry
        dictation = stt_registry.resident()
    except Exception as exc:  # noqa: BLE001 - unavailable is not "in use", as above
        logger.debug(f"Dictation unavailable during the cache-clear guard: {exc}")
    else:
        if dictation.get("model"):
            return "Unload the dictation model before clearing the model cache"
        if dictation.get("loading"):
            return "A dictation model load is using the cache; wait for it to finish"
    return None


def _video_blocks_delete(repo_id: str) -> Optional[str]:
    """The 400 detail if the Video backend holds or is fetching *repo_id*, else None. Video repos share the On Device delete action, so a live Wan / LTX / Hunyuan pipeline could otherwise lose its snapshot. Mirrors :func:`_diffusion_blocks_delete`."""
    try:
        from core.inference.video import get_video_backend
        backend = get_video_backend()
    except Exception as e:
        logger.debug(f"Video backend unavailable during delete guard for {repo_id}: {e}")
        return None
    status = backend.status()
    if status.get("loaded"):
        # repo_id names the checkpoint; for a GGUF / single-file load the companion base supplies the VAE and text encoders, so refuse it too.
        for key in ("repo_id", "base_repo"):
            held = status.get(key)
            if held and _loaded_id_matches_repo(str(held), repo_id):
                return "Unload the model before deleting"
    # The native H3 runtime re-reads its Qwen encoder and both VAEs from companion repos that are neither of the two ids above, so refuse those as well.
    for lid in getattr(backend, "loaded_repo_ids", tuple)():
        if _loaded_id_matches_repo(str(lid), repo_id):
            return "Unload the model before deleting"
    for lid in getattr(backend, "loading_repo_ids", tuple)():
        if _loaded_id_matches_repo(str(lid), repo_id):
            return "A Video model load is using this repo; wait for it to finish"
    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,
):
    """only_if_orphan turns a repo that became an installed checkpoint since listing into a 409."""
    account_access.require_installation_owner()
    from core.inference.audio_cpp_models import cached_folder_target, folder_row_for_download

    # Delete an umbrella folder's own variant keys, never the repo, which holds every other folder.
    folder = await asyncio.to_thread(cached_folder_target, repo_id, (variant or "").strip() or None)
    if folder is not None:
        umbrella, keys = folder
        if not keys:
            raise HTTPException(status_code = 404, detail = "Model not found in cache")
        # Reserve every key first, so a later key's download cannot start midway.
        repo_key = await asyncio.to_thread(resolve_cached_repo_id_case, umbrella, repo_type = "model")
        reserved: list[str] = []
        try:
            for key in keys:
                if not downloads.registry.begin_delete(repo_key, key):
                    raise HTTPException(
                        status_code = 400,
                        detail = "Cancel the active downloads before deleting.",
                    )
                reserved.append(key)
            result: dict = {}
            for key in keys:
                result = await delete_cached_model_response(
                    umbrella,
                    key,
                    hf_token,
                    cache_path,
                    only_if_orphan = only_if_orphan,
                )
        finally:
            for key in reserved:
                downloads.registry.end_delete(repo_key, key)
        return {**result, "repo_id": repo_id, "variant": variant}
    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}",
        )
    guard_id = (await asyncio.to_thread(folder_row_for_download, repo_id, variant) or (repo_id,))[0]
    # A base listed from its artifact mirror's copy deletes that copy, so guard both identities.
    mirror_id = (
        await asyncio.to_thread(cache_inventory.artifact_mirror_delete_id, repo_id, cache_path)
        if variant is None
        else None
    )
    guard_ids = (guard_id, mirror_id) if mirror_id else (guard_id,)

    # Fail closed with 503 rather than unlink weights under a running process.
    def _load_state_blocks_delete() -> Optional[str]:
        for gid in guard_ids:
            if _llama_cpp_blocks_delete(gid, variant) or _inference_backend_blocks_delete(gid):
                return "Unload the model before deleting"
            if _audio_cpp_blocks_delete(gid):
                return "Unload the audio model before deleting"
            blocked = _diffusion_blocks_delete(gid) or _video_blocks_delete(gid)
            if blocked:
                return blocked
        return None

    try:
        blocks_detail = await asyncio.to_thread(_load_state_blocks_delete)
    except Exception as e:
        logger.warning(f"Load-state verification failed for {repo_id}; refusing delete: {e}")
        raise HTTPException(
            status_code = 503,
            detail = _LOAD_STATE_UNVERIFIABLE_DETAIL,
        )
    if blocks_detail:
        raise HTTPException(
            status_code = 400,
            detail = blocks_detail,
        )

    repo_key = await asyncio.to_thread(resolve_cached_repo_id_case, repo_id, repo_type = "model")
    reserved_keys = [repo_key]
    if mirror_id:
        reserved_keys.append(
            await asyncio.to_thread(resolve_cached_repo_id_case, mirror_id, repo_type = "model")
        )
    reserved: list[str] = []
    for key in reserved_keys:
        if not downloads.registry.begin_delete(key, variant):
            for held in reserved:
                downloads.registry.end_delete(held, variant)
            detail = (
                f"Cancel the {variant} download before deleting it."
                if variant is not None
                else "Cancel the active downloads before deleting."
            )
            raise HTTPException(status_code = 400, detail = detail)
        reserved.append(key)
    try:
        # recheck after reserving the scope so a concurrent load claim is visible.
        try:
            blocks_detail = await asyncio.to_thread(_load_state_blocks_delete)
        except Exception as e:
            logger.warning(f"Load-state verification failed for {repo_id}; refusing delete: {e}")
            raise HTTPException(
                status_code = 503,
                detail = _LOAD_STATE_UNVERIFIABLE_DETAIL,
            )
        if blocks_detail:
            raise HTTPException(
                status_code = 400,
                detail = blocks_detail,
            )
        preferred_path = None
        if variant is not None:
            try:
                preferred_path = await gguf_variants.cached_gguf_variant_source_path(
                    repo_id, variant, hf_token
                )
            except Exception as exc:  # noqa: BLE001 -- local readiness is the offline fallback
                logger.debug(
                    "Could not resolve the scoped GGUF source for %s [%s]: %s",
                    repo_id,
                    variant,
                    download_registry.scrub_secrets(str(exc), hf_token = hf_token),
                )
        result = await asyncio.to_thread(
            _delete_cached_model_blocking,
            mirror_id or repo_id,
            variant,
            hf_token,
            cache_path,
            only_if_orphan = only_if_orphan,
            preferred_path = preferred_path,
        )
        # prune stale audio.cpp hardlinks that retain deleted blobs; current farms are unchanged.
        from core.inference.audio_cpp_files import prune_link_farm
        from hub.utils.hf_cache_state import hf_cache_roots

        # prune every remembered root because the owning cache may not be active.
        def _prune_all() -> None:
            for root in hf_cache_roots():
                prune_link_farm(root)

        await asyncio.to_thread(_prune_all)
        from core.inference.audio_cpp_models import forget

        forget()
        return {**result, "repo_id": repo_id} if mirror_id else result
    finally:
        for key in reserved:
            downloads.registry.end_delete(key, variant)
        cache_inventory.invalidate_hf_cache_scans()


def _audio_cpp_blocks_delete(repo_id: str) -> bool:
    """Whether an audio.cpp model from this repo is resident or loading. An umbrella id names a
    subfolder of the repo, so the id comparisons of the other guards never match it."""
    from core.inference.audio_cpp_models import (
        is_umbrella_id,
        parse_identifier,
        resolve,
        split_variant_ref,
    )
    from core.inference.orchestrator import peek_inference_backend
    from core.inference.stt_audiocpp_sidecar import QWEN3_ALIGNER, get_audio_cpp_stt_sidecar

    wanted = (repo_id or "").strip().lower()

    def holds(name) -> bool:
        if not isinstance(name, str):
            return False
        base = split_variant_ref(name)[0]
        ref = parse_identifier(base) if not base.lower().endswith(".gguf") else None
        if ref is None or not ref.repo_id:
            return False
        # A folder is also held by a model loading it as a companion (MioTTS opens MioCodec).
        if wanted in (ref.repo_id.lower(), ref.id.lower()):
            return True
        if not is_umbrella_id(wanted):
            return False
        model = resolve(base, network = False)
        return bool(model and any(c.id.lower() == wanted for c in model.companions))

    backend = peek_inference_backend()
    active = getattr(backend, "active_model_name", None) if backend is not None else None
    loading = tuple(getattr(backend, "loading_models", ()) or ()) if backend is not None else ()
    sidecar = get_audio_cpp_stt_sidecar()
    if wanted == QWEN3_ALIGNER.id.lower() and sidecar.holds_timestamp_aligner:
        return True
    return (
        holds(active)
        or any(holds(name) for name in loading)
        or holds(sidecar.loaded_model)
        or holds(sidecar.loading_model)
    )


def _delete_cached_model_blocking(
    repo_id: str,
    variant: Optional[str],
    hf_token: Optional[str],
    cache_path: Optional[str] = None,
    *,
    only_if_orphan: bool = False,
    preferred_path: Optional[str] = None,
) -> dict:
    from hub.utils.gguf_sources import cached_gguf_action_path

    cache_path = cached_gguf_action_path(repo_id, variant, cache_path, preferred_path)
    # recheck orphan status because a download can finish after the free-space listing.
    if only_if_orphan:
        from hub.services.models import companion_cleanup
        from hub.utils import companion_assets

        try:
            scans = cache_inventory.all_hf_cache_scans()
            copies = companion_cleanup._repos_by_id(scans).get(repo_id.strip().lower(), [])
            # check only this root; a full copy elsewhere must not block deleting this orphan row.
            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:
                    # An empty match means the target root is not in this scan, and concluding "orphan" from copies we did not look at is the fail-open this precondition prevents; raising lands in the 503.
                    raise RuntimeError(f"cache root not present in the scan: {cache_path}")
            still_orphan = not any(companion_assets.repo_is_install(repo, scans) 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; 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 stubs: the check IS part of the destructive stage. 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.
        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.
        sibling_active = bool(
            variant and downloads.registry.has_active_peer_variant(repo_id, variant)
        )

        cache_scans = cache_inventory.all_hf_cache_scans()

        # A repo can live in several remembered caches, so target exactly one or a delete removes copies in other, previously selected caches.
        owners: dict = {}
        for hf_cache in cache_scans:
            for repo_info in hf_cache.repos:
                if str(repo_info.repo_type) != "model":
                    continue
                if repo_info.repo_id.lower() != repo_id.lower():
                    continue
                try:
                    owner = Path(repo_info.repo_path).parent.resolve(strict = False)
                except (OSError, RuntimeError, ValueError):
                    continue
                owners.setdefault(owner, []).append((hf_cache, repo_info))

        target_root = resolve_delete_target_root("model", repo_id, cache_path, owners.keys())
        if target_root is None:
            raise HTTPException(status_code = 400, detail = "Invalid cache_path")
        candidate_entries = owners.get(target_root, [])

        matched_repo_ids = resolve_destructive_repo_ids(
            repo_id,
            [str(repo_info.repo_id) for _hf_cache, repo_info in candidate_entries],
            noun = "models",
        )
        target_entries = [
            (hf_cache, repo_info)
            for hf_cache, repo_info in candidate_entries
            if str(repo_info.repo_id) in matched_repo_ids
        ]

        if not target_entries:
            if variant is None:
                cache_purged = purge_repo_cache_dirs(
                    "model", repo_id, root = target_root
                ) or purge_partial_repo("model", repo_id, root = target_root)
                state_purged = (
                    download_manifest.purge_all_state_for_repo(
                        "model", repo_id, hub_cache = target_root
                    )
                    > 0
                )
                if cache_purged or state_purged:
                    return {"status": "deleted", "repo_id": repo_id}
            if variant:
                incomplete_result = gguf_variants.delete_variant_incomplete_blobs_result(
                    repo_id,
                    variant,
                    hf_token,
                    companions = not sibling_active,
                    root = target_root,
                )
                if incomplete_result.unresolved:
                    raise HTTPException(
                        status_code = 409,
                        detail = (
                            f"Couldn't fully delete {variant} for {repo_id}: partial "
                            "download bytes exist but this variant's blob hashes are unavailable. "
                            "Reconnect or provide access to the repo, then try again."
                        ),
                    )
                state_purged = download_manifest.purge_state(
                    "model",
                    repo_id,
                    variant,
                    hub_cache = target_root,
                )
                if incomplete_result.deleted > 0 or state_purged:
                    return {
                        "status": "deleted",
                        "repo_id": repo_id,
                        "variant": variant,
                    }
            raise HTTPException(status_code = 404, detail = "Model not found in cache")

        if variant:
            return _delete_gguf_variant_from_repos(
                repo_id,
                variant,
                [repo for _cache, repo in target_entries],
                hf_token,
                sibling_active = sibling_active,
                root = target_root,
                preferred_path = preferred_path,
            )

        deleted_revisions = False
        for hf_cache, repo_info in target_entries:
            revision_hashes = [
                rev.commit_hash for rev in repo_info.revisions if getattr(rev, "commit_hash", None)
            ]
            if not revision_hashes:
                continue
            delete_strategy = hf_cache.delete_revisions(*revision_hashes)
            logger.info(
                f"Deleting cached model {repo_id} from "
                f"{getattr(hf_cache, 'cache_dir', '<unknown>')}: "
                f"{delete_strategy.expected_freed_size_str} will be freed"
            )
            delete_strategy.execute()
            deleted_revisions = True

        cache_purged = purge_repo_cache_dirs("model", repo_id, root = target_root)
        partial_purged = purge_partial_repo("model", repo_id, root = target_root)
        state_purged = (
            download_manifest.purge_all_state_for_repo("model", repo_id, hub_cache = target_root) > 0
        )

        if not (deleted_revisions or cache_purged or partial_purged or state_purged):
            raise HTTPException(status_code = 404, detail = "No revisions found for model")

        return {"status": "deleted", "repo_id": repo_id}

    except HTTPException:
        raise
    except Exception as e:
        logger.error(
            "Error deleting cached model %s: %s",
            repo_id,
            download_registry.scrub_secrets(str(e), hf_token = hf_token),
        )
        raise HTTPException(
            status_code = 500,
            detail = "Failed to delete cached model: "
            + download_registry.scrub_secrets(str(e), hf_token = hf_token),
        )