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.

117 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

"""GGUF variant resolution."""

from __future__ import annotations

from hub.services.models import account_access

import asyncio
import contextvars
import functools
import hashlib
import json
import os
import re
import threading
import time
import weakref
from collections import OrderedDict
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from typing import NamedTuple, Optional

from fastapi import HTTPException
from loggers import get_logger

from hub.schemas.inventory import GgufVariantDetail, GgufVariantsResponse
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.hf_errors import hf_error_status, modelscope_missing
from hub.utils.hf_tokens import cached_read_refused as hub_cached_read_refused
from hub.utils.hf_tokens import call_with_anonymous_retry
from hub.utils.hf_cache_state import (
    cached_repo_ref_for_path,
    incomplete_blob_hash,
    iter_destructive_repo_cache_dirs,
    repo_cache_dir_name,
)
from hub.utils.gguf import (
    HUB_MODEL_INFO_SINK,
    GgufVariantInfo,
    extract_quant_label,
    gguf_variant_family,
    gguf_variant_key,
    iter_hf_cache_snapshots,
    is_big_endian_gguf_path,
    list_empty_gguf_variant_dirs,
    list_gguf_variants,
    list_local_gguf_variants,
    list_partial_gguf_variants_from_state,
    default_gguf_scope,
    pick_best_gguf,
    merge_sibling_snapshot_variants,
    select_gguf_cache_snapshot,
)
from hub.utils.paths import (
    is_local_path,
    is_valid_repo_id as _is_valid_repo_id,
)

# Loader's normalizer, not the hub's: they disagree on WSL, and only it names what the load opens.
from utils.paths import normalize_path as _loader_normalize_path
from hub.services.models.common import (
    _is_imatrix_filename,
    _is_mmproj_filename,
    _is_mtp_drafter_path,
    _iter_gguf_paths,
)
from hub.utils.gguf_plan import (
    GgufVariantPlan as _GgufVariantRequirement,
    build_gguf_variant_plans,
    is_main_gguf_variant_path,
    plan_from_expected_files,
    precision_folder_plans,
    sibling_sha256,
)
from utils.paths.path_utils import is_appledouble_metadata

logger = get_logger(__name__)

_VARIANT_HASH_CACHE: "OrderedDict[tuple[str, str, str, bool], tuple[frozenset[str], float]]" = (
    OrderedDict()
)
_VARIANT_REQUIREMENT_CACHE: "OrderedDict[tuple[str, str, str], tuple[_GgufVariantRequirement, float]]" = OrderedDict()
_VARIANT_REQUIREMENT_NEG_CACHE: "OrderedDict[tuple[str, str], float]" = OrderedDict()
_VARIANT_HASH_MAX = 512
# Hashes derive from mutable remote revision metadata; same TTL as requirements.
_VARIANT_HASH_POS_TTL = 60.0
# Requirements expire on a TTL so a moved repo revision is picked up, not pinned for the process.
_VARIANT_REQUIREMENT_POS_TTL = 60.0
# Suppress retries on a metadata-fetch failure so a slow/flaky link doesn't re-hammer the API on every page refresh.
_VARIANT_REQUIREMENT_NEG_TTL = 60.0
# Fail fast on a slow link so the variant render isn't blocked for seconds.
_GGUF_METADATA_TIMEOUT_SECONDS = 5.0
_VARIANT_HASH_LOCK = threading.Lock()


class VariantIncompleteDeleteResult(NamedTuple):
    deleted: int
    unresolved: bool


def _variant_hash_cache_key(
    repo_id: str, variant: str, hf_token: Optional[str]
) -> tuple[str, str, str]:
    return (
        repo_id.lower(),
        variant.lower(),
        hf_cache_scan.token_fingerprint(hf_token),
    )


def _variant_blob_hash_cache_key(
    repo_id: str, variant: str, hf_token: Optional[str], include_companions: bool
) -> tuple[str, str, str, bool]:
    base = _variant_hash_cache_key(repo_id, variant, hf_token)
    return (*base, include_companions)


def _variant_repo_cache_key(repo_id: str, hf_token: Optional[str]) -> tuple[str, str]:
    return (repo_id.lower(), hf_cache_scan.token_fingerprint(hf_token))


def _variant_requirement_neg_cache_active(key: tuple[str, str]) -> bool:
    with _VARIANT_HASH_LOCK:
        cached_at = _VARIANT_REQUIREMENT_NEG_CACHE.get(key)
        if cached_at is None:
            return False
        if (time.monotonic() - cached_at) < _VARIANT_REQUIREMENT_NEG_TTL:
            _VARIANT_REQUIREMENT_NEG_CACHE.move_to_end(key)
            # Split-named link on an ordinary target: loads as-is, nothing missing.
            return True
        _VARIANT_REQUIREMENT_NEG_CACHE.pop(key, None)
        return False


def _variant_requirement_neg_cache_set(key: tuple[str, str]) -> None:
    with _VARIANT_HASH_LOCK:
        _VARIANT_REQUIREMENT_NEG_CACHE[key] = time.monotonic()
        _VARIANT_REQUIREMENT_NEG_CACHE.move_to_end(key)
        while len(_VARIANT_REQUIREMENT_NEG_CACHE) > _VARIANT_HASH_MAX:
            _VARIANT_REQUIREMENT_NEG_CACHE.popitem(last = False)


def _variant_requirement_neg_cache_clear(key: tuple[str, str]) -> None:
    with _VARIANT_HASH_LOCK:
        _VARIANT_REQUIREMENT_NEG_CACHE.pop(key, None)


def _variant_hash_cache_get(key: tuple[str, str, str, bool]) -> Optional[frozenset[str]]:
    with _VARIANT_HASH_LOCK:
        cached = _VARIANT_HASH_CACHE.get(key)
        if cached is None:
            return None
        hashes, ts = cached
        if (time.monotonic() - ts) >= _VARIANT_HASH_POS_TTL:
            _VARIANT_HASH_CACHE.pop(key, None)
            return None
        _VARIANT_HASH_CACHE.move_to_end(key)
        return hashes


def _variant_hash_cache_set(key: tuple[str, str, str, bool], hashes: frozenset[str]) -> None:
    with _VARIANT_HASH_LOCK:
        _VARIANT_HASH_CACHE[key] = (hashes, time.monotonic())
        _VARIANT_HASH_CACHE.move_to_end(key)
        while len(_VARIANT_HASH_CACHE) > _VARIANT_HASH_MAX:
            _VARIANT_HASH_CACHE.popitem(last = False)


def _variant_requirement_cache_get(key: tuple[str, str, str]) -> Optional[_GgufVariantRequirement]:
    with _VARIANT_HASH_LOCK:
        cached = _VARIANT_REQUIREMENT_CACHE.get(key)
        if cached is None:
            return None
        requirement, ts = cached
        if (time.monotonic() - ts) >= _VARIANT_REQUIREMENT_POS_TTL:
            _VARIANT_REQUIREMENT_CACHE.pop(key, None)
            return None
        _VARIANT_REQUIREMENT_CACHE.move_to_end(key)
        return requirement


def _variant_requirement_cache_set_many(
    repo_id: str, hf_token: Optional[str], requirements: dict[str, _GgufVariantRequirement]
) -> None:
    global _VARIANT_REQUIREMENT_FORGOTTEN
    with _VARIANT_HASH_LOCK:
        now = time.monotonic()
        for quant, requirement in requirements.items():
            key = _variant_hash_cache_key(repo_id, quant, hf_token)
            _VARIANT_REQUIREMENT_CACHE[key] = (requirement, now)
            _VARIANT_REQUIREMENT_CACHE.move_to_end(key)
            known = key[:2]
            _VARIANT_REQUIREMENT_LAST_KNOWN[known] = requirement
            _VARIANT_REQUIREMENT_LAST_KNOWN.move_to_end(known)
        while len(_VARIANT_REQUIREMENT_CACHE) > _VARIANT_HASH_MAX:
            _VARIANT_REQUIREMENT_CACHE.popitem(last = False)
        while len(_VARIANT_REQUIREMENT_LAST_KNOWN) > _VARIANT_REQUIREMENT_LAST_KNOWN_MAX:
            _VARIANT_REQUIREMENT_LAST_KNOWN.popitem(last = False)
            _VARIANT_REQUIREMENT_FORGOTTEN = True


# Kept past TTL so expired entries never read as nothing required; not keyed by credential.
_VARIANT_REQUIREMENT_LAST_KNOWN: "OrderedDict[tuple[str, str], _GgufVariantRequirement]" = (
    OrderedDict()
)
# After any eviction an absent entry may be a forgotten companion.
_VARIANT_REQUIREMENT_LAST_KNOWN_MAX = 65536
_VARIANT_REQUIREMENT_FORGOTTEN = False


def _variant_requirement_last_known(key: tuple[str, ...]) -> Optional[_GgufVariantRequirement]:
    with _VARIANT_HASH_LOCK:
        return _VARIANT_REQUIREMENT_LAST_KNOWN.get(key[:2])


def _variant_requirement_may_be_forgotten() -> bool:
    with _VARIANT_HASH_LOCK:
        return _VARIANT_REQUIREMENT_FORGOTTEN


def _build_gguf_variant_requirements(siblings: list) -> dict[str, _GgufVariantRequirement]:
    return build_gguf_variant_plans(siblings) or precision_folder_plans(siblings)


def gguf_variant_requirements(
    repo_id: str,
    variant: str,
    hf_token: Optional[str] = None,
) -> Optional[_GgufVariantRequirement]:
    # A scope is never in the repo's quant listing, so it would miss the cache and refetch model_info every call.
    if _is_scope_key(variant):
        return None
    key = _variant_hash_cache_key(repo_id, variant, hf_token)
    cached = _variant_requirement_cache_get(key)
    if cached is not None:
        return cached
    requirements = _fetch_gguf_variant_requirements(repo_id, hf_token)
    return requirements.get(variant.lower())


def _fetch_gguf_variant_requirements(
    repo_id: str,
    hf_token: Optional[str] = None,
    *,
    siblings: Optional[list] = None,
) -> dict[str, _GgufVariantRequirement]:
    repo_key = _variant_repo_cache_key(repo_id, hf_token)
    if siblings is None:
        if _variant_requirement_neg_cache_active(repo_key):
            return {}
        try:
            from huggingface_hub import HfApi
            info = call_with_anonymous_retry(
                lambda token: HfApi(token = token).model_info(
                    repo_id,
                    files_metadata = True,
                    timeout = _GGUF_METADATA_TIMEOUT_SECONDS,
                ),
                hf_token,
            )
        except Exception as e:
            logger.warning(
                "model_info failed resolving GGUF files for %s: %s",
                repo_id,
                download_registry.scrub_secrets(str(e), hf_token = hf_token),
            )
            _variant_requirement_neg_cache_set(repo_key)
            return {}
        siblings = list(info.siblings)
    requirements = _build_gguf_variant_requirements(siblings)
    if requirements:
        _variant_requirement_cache_set_many(repo_id, hf_token, requirements)
    _variant_requirement_neg_cache_clear(repo_key)
    return requirements


def _gguf_all_variant_requirements(
    repo_id: str,
    hf_token: Optional[str] = None,
    *,
    siblings: Optional[list] = None,
) -> dict[str, _GgufVariantRequirement]:
    return _fetch_gguf_variant_requirements(repo_id, hf_token, siblings = siblings)


def _manifest_variant_blob_hashes(
    repo_id: str,
    variant: str,
    *,
    include_companions: bool = True,
    repo_cache_dir: Optional[Path] = None,
) -> frozenset[str]:
    manifest = download_manifest.read_manifest(
        "model",
        repo_id,
        variant,
        hub_cache = repo_cache_dir.parent if repo_cache_dir is not None else None,
    )
    if manifest is None:
        return frozenset()
    variant_key = variant.lower()
    hashes: set[str] = set()
    for expected in manifest.expected_files:
        if not expected.sha256:
            continue
        if include_companions:
            hashes.add(expected.sha256)
            continue
        if is_main_gguf_variant_path(expected.path, variant_key):
            hashes.add(expected.sha256)
    return frozenset(hashes)


def gguf_variant_blob_hashes(
    repo_id: str,
    variant: str,
    hf_token: Optional[str] = None,
    *,
    include_companions: bool = True,
    allow_remote: bool = True,
    repo_cache_dir: Optional[Path] = None,
) -> frozenset[str]:
    key = _variant_blob_hash_cache_key(
        repo_id,
        variant,
        hf_token,
        include_companions,
    )
    cached = _variant_hash_cache_get(key)
    if cached is not None:
        return cached
    hashes = _manifest_variant_blob_hashes(
        repo_id,
        variant,
        include_companions = include_companions,
        repo_cache_dir = repo_cache_dir,
    )
    if hashes:
        return hashes
    requirement_key = _variant_hash_cache_key(repo_id, variant, hf_token)
    requirement = _variant_requirement_cache_get(requirement_key)
    if requirement is None and allow_remote:
        requirement = gguf_variant_requirements(repo_id, variant, hf_token)
    if requirement is not None:
        hashes = requirement.required_hashes if include_companions else requirement.main_hashes
        if hashes:
            _variant_hash_cache_set(key, hashes)
        return hashes
    return frozenset()


def _is_scope_key(variant: str) -> bool:
    """An @-prefixed key is a download scope, not a quant, so listing it would duplicate its file."""
    return variant.startswith("@")


def _quants_from_state(
    repo_id: str, hub_cache: Optional[Path]
) -> Optional[tuple[list[GgufVariantInfo], bool]]:
    """Scope-only state returns None, so the caller falls through rather than serve a phantom .gguf."""
    partial = list_partial_gguf_variants_from_state(repo_id, hub_cache = hub_cache)
    if partial is None:
        return None
    variants, has_vision = partial
    variants = [v for v in variants if not (v.quant and _is_scope_key(v.quant))]
    if not variants:
        return None
    return variants, has_vision


def _variant_dependency_key(repo_id: str, filename: str) -> Optional[str]:
    """Groups variants by companion footprint, which varies by family and checkpoint size; never raises."""
    try:
        from core.inference.diffusion_families import (
            detect_family_for_pick,
            sd_cpp_text_encoders_for,
        )

        fam = detect_family_for_pick(repo_id, filename)
        if fam is None:
            return None
        inner_dim = None
        if fam.name == "flux.2-klein":
            from core.inference.diffusion_compat import flux2_inner_dim_for_pick

            inner_dim = flux2_inner_dim_for_pick(repo_id, filename, allow_network = False)
            identity = f"{repo_id}/{filename}".lower()
            sized = re.search(r"(?<![a-z0-9])(?:4b|9b)(?![a-z0-9])", identity)
            if (
                inner_dim is None
                and sized is None
                and "klein4b" not in identity
                and "klein9b" not in identity
            ):
                unknown = hashlib.sha256(filename.lower().encode("utf-8")).hexdigest()[:16]
                return f"{fam.name}:unknown:{unknown}"
        encoders = sd_cpp_text_encoders_for(fam, repo_id, filename, inner_dim = inner_dim)
        # Hashed: the encoder table is long and the key is opaque to the client.
        digest = hashlib.sha256(
            "\n".join("/".join(str(part) for part in entry) for entry in encoders).encode("utf-8")
        ).hexdigest()[:16]
        return f"{fam.name}:{digest}"
    except Exception as e:
        logger.debug("Dependency key unavailable for %s/%s: %s", repo_id, filename, e)
        return None


def variant_remaining_bytes(
    repo_id: str,
    requirement,
    repo_cache_dir: Optional[Path] = None,
) -> Optional[int]:
    """Priced per file in the row's root, not the active one; shards elsewhere earn no resume credit."""
    if requirement is None or not requirement.required_hashes:
        return None
    try:
        have = download_registry.existing_blob_bytes(
            "model",
            repo_id,
            requirement.required_hashes,
            root = repo_cache_dir.parent if repo_cache_dir is not None else None,
        )
    except Exception as e:
        logger.warning(f"Remaining-bytes lookup failed for {repo_id}: {e}")
        return None
    return max(0, requirement.download_size_bytes - have)


def variant_remaining_bytes_from_state(
    repo_id: str, variant: str, repo_cache_dir: Optional[Path]
) -> Optional[int]:
    """Not capped by the row's size: an early interruption leaves fewer shards on disk than the transfer."""
    if not variant:
        return None
    try:
        manifest = download_manifest.read_manifest(
            "model",
            repo_id,
            variant,
            hub_cache = repo_cache_dir.parent if repo_cache_dir is not None else None,
        )
    except Exception as e:
        logger.warning(f"Manifest read failed while pricing {repo_id} [{variant}]: {e}")
        return None
    if manifest is None or not manifest.expected_files:
        return None
    return variant_remaining_bytes(
        repo_id,
        plan_from_expected_files(variant, manifest.expected_files),
        repo_cache_dir,
    )


def _audio_cpp_remaining_bytes(
    repo_id: str, key: str, missing_files: list, missing_companion_bytes: Optional[int]
) -> Optional[int]:
    """What resuming an audio.cpp row still fetches. Its whole manifest, not the generic plan, which keeps
    one GGUF per quant and so drops a package's other components; without a manifest, the missing files."""
    try:
        manifest = download_manifest.read_manifest("model", repo_id, key)
        files = manifest.expected_files if manifest is not None else ()
        if files:
            have = download_registry.existing_blob_bytes(
                "model", repo_id, frozenset(f.sha256 for f in files if f.sha256)
            )
            return max(0, sum(max(0, int(f.size or 0)) for f in files) - have)
    except Exception as e:
        logger.warning(f"Manifest pricing failed for {repo_id} [{key}]: {e}")
    if missing_companion_bytes is None:
        return None
    return sum(size for _path, size in missing_files) + missing_companion_bytes


def _partial_transport_for_variant(
    repo_id: str,
    variant: str,
    repo_cache_dir: Optional[Path] = None,
) -> Optional[str]:
    return hf_cache_scan.partial_transport_for(
        "model",
        repo_id,
        variant,
        repo_cache_dir,
    )


def _partial_resumable_for_variant(
    repo_id: str,
    variant: str,
    repo_cache_dir: Optional[Path] = None,
) -> bool:
    return hf_cache_scan.partial_resume_available(
        "model",
        repo_id,
        variant,
        repo_cache_dir,
    )


def _local_main_gguf_blobs_by_quant(
    repo_id: str, repo_cache_dir: Optional[Path] = None
) -> dict[str, dict[str, set[str]]]:
    """Shared companions are copied into every quant bucket, so update checks need no remote call."""
    result: dict[str, dict[str, set[str]]] = {}
    companion_blobs: dict[str, set[str]] = {}
    try:
        from hub.services.models import cache_inventory
        scans = cache_inventory.all_hf_cache_scans()
    except Exception as e:
        logger.warning("Failed to scan local GGUF blobs for %s: %s", repo_id, e)
        return result

    target_lower = repo_id.lower()
    for hf_cache in scans:
        for repo_info in hf_cache.repos:
            if str(getattr(repo_info, "repo_type", "")) != "model":
                continue
            if str(getattr(repo_info, "repo_id", "")).lower() != target_lower:
                continue
            if repo_cache_dir is not None:
                try:
                    if Path(repo_info.repo_path).resolve(strict = False) != repo_cache_dir.resolve(
                        strict = False
                    ):
                        continue
                except (AttributeError, OSError, RuntimeError, ValueError):
                    continue
            for path, hashes in cache_inventory._repo_gguf_blob_map(
                repo_info,
                include_companions = True,
            ).items():
                normalized = str(path).replace("\\", "/")
                if not hashes:
                    continue
                if _is_imatrix_filename(normalized):
                    # Nothing fetches an imatrix, so a stale copy on disk must not vouch for a variant's blobs.
                    continue
                if _is_mmproj_filename(normalized) or _is_mtp_drafter_path(normalized):
                    companion_blobs.setdefault(normalized, set()).update(
                        str(blob) for blob in hashes if blob
                    )
                    continue
                quant = gguf_variant_key(normalized).lower()
                # The endian predicate reads a quant TOKEN; a qualified key would misread the path.
                if is_big_endian_gguf_path(normalized, extract_quant_label(normalized)):
                    continue
                bucket = result.setdefault(quant, {}).setdefault(normalized, set())
                bucket.update(str(blob) for blob in hashes if blob)
    if companion_blobs:
        for local_blobs in result.values():
            for path, hashes in companion_blobs.items():
                local_blobs.setdefault(path, set()).update(hashes)
    return result


def _size_identity_matches(local_set: set[str], remote_size: int) -> bool:
    """Size alone judges no-blob files; an equal-size requant is missed, not shown as a phantom update."""
    size = int(remote_size or 0)
    if size <= 0:
        return False
    from hub.services.models import cache_inventory

    return cache_inventory.local_size_identity(size) in local_set


def _variant_update_available_from_requirement(
    local_blobs: dict[str, set[str]], requirement: Optional[_GgufVariantRequirement], variant: str
) -> bool:
    if requirement is None or not local_blobs:
        return False
    local_by_posix = {path.replace("\\", "/"): blobs for path, blobs in local_blobs.items()}
    for expected in requirement.expected_files:
        path = str(expected.path).replace("\\", "/")
        if not (
            is_main_gguf_variant_path(path, variant)
            or _is_mmproj_filename(path)
            or _is_mtp_drafter_path(path)
        ):
            continue
        remote_blob = expected.sha256
        if not remote_blob:
            continue
        local_set = local_by_posix.get(path)
        if not local_set:
            return True
        if remote_blob in local_set:
            continue
        if _size_identity_matches(local_set, expected.size):
            continue
        return True
    return False


def delete_variant_incomplete_blobs_result(
    repo_id: str,
    variant: str,
    hf_token: Optional[str],
    *,
    extra_hashes: frozenset[str] = frozenset(),
    companions: bool = True,
    root: Optional[Path] = None,
) -> VariantIncompleteDeleteResult:
    # With a sibling downloading, companions=False keeps a shared mmproj.
    target_hashes = (
        gguf_variant_blob_hashes(repo_id, variant, hf_token, include_companions = companions)
        | extra_hashes
    )
    if not target_hashes:
        has_variant_partial_state = hf_cache_scan.is_variant_partial(
            repo_id,
            variant,
            incomplete_blob_hashes = set(),
            variant_blob_hashes = frozenset(),
        )
        has_repo_partials = bool(download_registry.incomplete_blob_hashes("model", repo_id))
        return VariantIncompleteDeleteResult(
            deleted = 0,
            unresolved = has_variant_partial_state and has_repo_partials,
        )
    deleted = 0
    # Exact-case match only, so a case-variant sibling repo's partials are never unlinked.
    for entry in iter_destructive_repo_cache_dirs("model", repo_id, root = root):
        blobs_dir = entry / "blobs"
        if not blobs_dir.is_dir():
            continue
        try:
            candidates = list(blobs_dir.iterdir())
        except OSError as e:
            logger.warning(f"Failed to list partial blobs in {blobs_dir}: {e}")
            continue
        for incomplete in candidates:
            try:
                if not incomplete.is_file():
                    continue
                if incomplete_blob_hash(incomplete.name) not in target_hashes:
                    continue
                incomplete.unlink()
                deleted += 1
            except OSError as e:
                logger.warning(f"Failed to unlink {incomplete}: {e}")
    return VariantIncompleteDeleteResult(deleted = deleted, unresolved = False)


def _snapshot_scope_for_request(repo_id: str, local_path: Optional[str]) -> Optional[Path]:
    """A row pinned to a snapshot loads only from that directory, so readiness is counted there."""
    if not local_path:
        return None
    try:
        local = Path(local_path).expanduser().resolve(strict = False)
    except (OSError, RuntimeError, ValueError):
        return None
    if local.parent.name != "snapshots" or not local.is_dir():
        return None
    expected = repo_cache_dir_name("model", repo_id).lower()
    return local if local.parent.parent.name.lower() == expected else None


def pinned_snapshot_for_request(repo_id: str, local_path: Optional[str]) -> Optional[str]:
    """The snapshot *local_path* pins, for callers outside this module that must read that copy."""
    scope = _snapshot_scope_for_request(repo_id, local_path)
    return str(scope) if scope is not None else None


def _repo_cache_dir_for_request(repo_id: str, local_path: Optional[str]) -> Path:
    """Resolve the one Hub repo cache represented by this variant request."""
    expected_name = repo_cache_dir_name("model", repo_id).lower()
    if local_path:
        try:
            local = Path(local_path).expanduser().resolve(strict = False)
            for candidate in (local, *local.parents):
                if candidate.name.lower() == expected_name:
                    return candidate
        except (OSError, RuntimeError, ValueError):
            pass
    from utils.hf_cache_settings import get_hf_cache_paths

    return get_hf_cache_paths().hub_cache / repo_cache_dir_name("model", repo_id)


def _mark_empty_dir_cleanables(
    repo_id: str,
    response: GgufVariantsResponse,
    repo_cache_dir: Optional[Path] = None,
) -> GgufVariantsResponse:
    """Surfaces empty leftover quant folders as partial, so the UI can delete them on local paths too."""
    try:
        empty_labels = (
            list_empty_gguf_variant_dirs(repo_id, root = repo_cache_dir.parent)
            if repo_cache_dir is not None
            else list_empty_gguf_variant_dirs(repo_id)
        )
    except Exception as e:
        logger.warning(f"Failed to scan empty GGUF variant folders for {repo_id}: {e}")
        return response
    if not empty_labels:
        return response
    empty_by_key = {label.lower(): label for label in empty_labels}
    variants = list(response.variants)
    listed = {v.quant.lower() for v in variants}
    for i, v in enumerate(variants):
        if v.quant.lower() in empty_by_key and not v.downloaded and not v.partial:
            variants[i] = v.model_copy(update = {"partial": True})
    for key, label in sorted(empty_by_key.items()):
        if key not in listed:
            variants.append(
                GgufVariantDetail(
                    filename = f"{label}.gguf", quant = label, partial = True, cleanable = True
                )
            )
    return response.model_copy(update = {"variants": variants})


def _direct_gguf_loads(path: Path) -> bool:
    """Mirrors detect_gguf_model: refuses companion files and big-endian builds by name and parent."""
    # Load extractor, not the hub one: they disagree on F16-be-checkpoint-Q4_K_M.
    from utils.models.model_config import _extract_quant_label

    context = f"{path.parent.name}/{path.name}"
    return not (
        _is_mmproj_filename(path.name)
        or _is_mtp_drafter_path(context)
        or _is_imatrix_filename(path.name)
        or is_big_endian_gguf_path(context, _extract_quant_label(context))
        or is_appledouble_metadata(path)
    )


# llama.cpp split grammar wants exactly five digits, unlike the cache scan's form.
_DIRECT_SPLIT_RE = re.compile(r"^(?P<stem>.+)-(?P<index>\d{5})-of-(?P<total>\d{5})$", re.IGNORECASE)


def _direct_gguf_split_is_whole(path: Path) -> bool:
    """Split siblings must sit beside the main shard for llama.cpp; unknown reports whole."""
    match = _DIRECT_SPLIT_RE.match(path.name.rsplit(".", 1)[0])
    if match is None:
        return True
    total = int(match.group("total"))
    if total < 2:
        return True
    sibling = re.compile(
        re.escape(match.group("stem"))
        + r"-(\d{"
        + str(len(match.group("index")))
        + r"})-of-"
        + re.escape(match.group("total"))
        + r"\.gguf$",
        re.IGNORECASE,
    )

    def _indexes_beside(target: Path, pattern) -> set:
        return {
            int(m.group(1))
            for p in target.parent.iterdir()
            if (m := pattern.match(p.name)) and p.is_file() and p.stat().st_size > 0
        }

    def _target_set_is_whole(target: Path) -> bool:
        """Checks the symlink target's own declared split total, since the load launches whatever it
        declares."""
        m = _DIRECT_SPLIT_RE.match(target.name.rsplit(".", 1)[0])
        if m is None:
            return True
        target_total = int(m.group("total"))
        pattern = re.compile(
            re.escape(m.group("stem"))
            + r"-(\d{"
            + str(len(m.group("index")))
            + r"})-of-"
            + re.escape(m.group("total"))
            + r"\.gguf$",
            re.IGNORECASE,
        )
        return _indexes_beside(target, pattern) >= set(range(1, target_total + 1))

    try:
        found = _indexes_beside(path, sibling)
        if not found >= set(range(1, total + 1)) and path.is_symlink():
            # Siblings resolve from the TARGET, so a renamed alias loads the target's set.
            return _target_set_is_whole(path.resolve())
    except OSError:
        return True
    # Declared indexes, not a count: a stray must not cover a missing shard; zero-byte siblings are torn.
    return found >= set(range(1, total + 1))


# Only enumerates candidates for the resolver to adjudicate; drift costs a candidate, not a verdict.
_KNOWN_QUANT_RE = re.compile(
    r"(UD-)?"
    r"(MXFP[0-9]+(?:_[A-Z0-9]+)*"
    r"|NVFP[0-9]+(?:_[A-Z0-9]+)*"
    r"(?=(?:-[0-9]+(?:[.][0-9]+)?bpw)?(?:-[0-9]{3,}-of-[0-9]{3,})?(?:[.]gguf)?$)"
    r"|IQ[0-9]+_[A-Z]+(?:_[A-Z0-9]+)?"
    r"|P?TQ[0-9]+_[0-9]+"
    r"|Q[0-9]+_K_[A-Z]+"
    r"|P?Q[0-9]+_(?:[0-9]+(?:_G[0-9]+)?|G[0-9]+)"
    r"|Q[0-9]+_K"
    r"|BF16|F16|F32)"
    r"(-[0-9]+(?:\.[0-9]+)?bpw)?",
    re.IGNORECASE,
)


def _will_serve(resolved: Optional[str]) -> bool:
    """The resolver accepts empty or torn files by extension; this checks what llama-server would open."""
    if not resolved:
        return False
    try:
        path = Path(resolved)
        # stat(), not exists(): exists() swallows OSError on 3.14 (sharing violation).
        try:
            size = path.stat().st_size
        except (FileNotFoundError, NotADirectoryError):
            return False
        return size > 0 and _direct_gguf_split_is_whole(path)
    except OSError:
        return True


def _loadable_variants(identifier: str, variants):
    """Quants a load would serve, from the same resolver /api/inference/load uses; local answers only."""
    from utils.models.model_config import _find_local_gguf_by_variant

    # Only directories consult the variant. stat(), not is_file(): a locked file stays unanswered.
    import stat as _stat

    try:
        if _stat.S_ISREG(Path(identifier).expanduser().stat().st_mode):
            return None
    except (FileNotFoundError, NotADirectoryError):
        pass
    except OSError:
        return None

    # Dedupe spellings via seen first; each alias is still confirmed so a wrong file is never advertised.
    accepted: list = []
    seen = set()
    for variant in variants:
        quant = getattr(variant, "quant", None)
        if not isinstance(quant, str) or not quant:
            continue
        try:
            bound = _find_local_gguf_by_variant(identifier, quant)
            if not _will_serve(bound):
                continue
        except Exception:
            continue
        key = quant.strip().lower()
        if key not in seen:
            seen.add(key)
            accepted.append(quant)
        # Resolve relative identifiers the resolver's way, unresolved first (symlinks out of tree).
        relative = Path(bound).name
        for base_raw, bound_path in (
            (Path(identifier).expanduser(), Path(bound)),
            (Path(identifier).expanduser().resolve(), Path(bound).resolve()),
        ):
            try:
                base = base_raw.parent if base_raw.is_file() else base_raw
                relative = bound_path.relative_to(base).as_posix()
                break
            except (OSError, ValueError):
                continue
        basename = Path(bound).name
        derived = {
            re.sub(r"-\d{3,}-of-\d{3,}$", "", relative.rsplit(".", 1)[0]),
            re.sub(r"-\d{3,}-of-\d{3,}$", "", basename.rsplit(".", 1)[0]),
        }
        for match in _KNOWN_QUANT_RE.finditer(basename.rsplit(".", 1)[0]):
            prefix, core, bpw = match.group(1) or "", match.group(2), match.group(3) or ""
            derived.add(f"{prefix}{core}")
            if bpw:
                derived.add(f"{prefix}{core}{bpw}")
        for spelling in sorted(derived):
            key = spelling.strip().lower()
            if not key or key in seen:
                continue
            seen.add(key)
            try:
                if _will_serve(_find_local_gguf_by_variant(identifier, spelling)):
                    accepted.append(spelling)
            except Exception:
                continue
    return accepted


def _loads_without_variant(identifier: str) -> bool:
    """Whether a variantless load of *identifier* would serve GGUF weights."""
    from utils.models.model_config import detect_gguf_model
    try:
        return _will_serve(detect_gguf_model(identifier))
    except Exception:
        return False


def _complete_quants_under(snapshot: str):
    """Returns None on any scan error, so rows keep reporting downloaded rather than marked unusable."""
    try:
        complete = hf_cache_scan.complete_snapshot_variants(snapshot)
    except Exception:
        return None
    if complete is None:
        return None
    return complete


def _complete_with_servable(snapshot: str, complete, variants):
    """Asks the resolver which quants load serves; the scan's looser split grammar can misread a file."""
    if complete is None:
        return None
    from utils.models.model_config import _find_local_gguf_by_variant

    repaired = set(complete)
    for variant in variants:
        quant = getattr(variant, "quant", None)
        if not isinstance(quant, str) or not quant or quant in repaired:
            continue
        try:
            if _will_serve(_find_local_gguf_by_variant(snapshot, quant)):
                repaired.add(quant)
        except Exception:
            continue
    return repaired


# Coalesce identical scans: aborted requests cannot stop a running scan and exhausted the executor.
_VARIANTS_INFLIGHT: "weakref.WeakKeyDictionary" = weakref.WeakKeyDictionary()

# Not the default executor: a stalled Hub holds a remote listing's thread until it answers, and enough
# of them blocked every asyncio.to_thread caller (load, chat) and the On Device disk-only listing (#14038).
_HUB_LISTING_POOL = ThreadPoolExecutor(thread_name_prefix = "gguf-hub-listing")
_DISK_LISTING_POOL = ThreadPoolExecutor(thread_name_prefix = "gguf-disk-listing")


async def listing_thread(offline: bool, fn, /, *args, **kwargs):
    """``asyncio.to_thread`` on the listing pool for *offline* (context variables carried along)."""
    loop = asyncio.get_running_loop()
    call = functools.partial(contextvars.copy_context().run, fn, *args, **kwargs)
    return await loop.run_in_executor(_DISK_LISTING_POOL if offline else _HUB_LISTING_POOL, call)


async def _shared_variants_scan(
    key: tuple,
    compute,
    offline: bool = False,
):
    """*compute* in a thread, shared with any identical request already running."""
    loop = asyncio.get_running_loop()
    inflight = _VARIANTS_INFLIGHT.get(loop)
    if inflight is None:
        inflight = {}
        _VARIANTS_INFLIGHT[loop] = inflight

    task = inflight.get(key)
    if task is None:
        task = asyncio.ensure_future(listing_thread(offline, compute))

        def _release(finished: asyncio.Future) -> None:
            inflight.pop(key, None)
            if not finished.cancelled():
                finished.exception()

        inflight[key] = task
        task.add_done_callback(_release)
    # Shielded: one caller giving up must not cancel the scan the others are waiting on.
    return await asyncio.shield(task)


class VariantsAnswer(NamedTuple):
    """The listing, plus the directory it came from so a caller reading metadata reads the
    same copy. None means no single directory: the repo's caches answered."""

    response: GgufVariantsResponse
    context_source: Optional[str]
    # False if the caller may not read the repo's caches; readers then use repo id, not context_source.
    cache_authorized: bool = True
    # per-quant source for resolving row metadata when one shared directory cannot answer
    variant_context_sources: Optional[dict[str, str]] = None


def _default_variant_candidates(variants, repo_id: Optional[str] = None) -> list[str]:
    """return scoped filenames in the order used by the automatic default picker."""
    return [v.filename for v in default_gguf_scope(variants, repo_id, key = lambda v: v.quant)]


def _default_variant_key(variants, repo_id: Optional[str] = None) -> Optional[str]:
    """return the listed default key because custom-folder builds can share a derived quant key."""
    best = pick_best_gguf(_default_variant_candidates(variants, repo_id))
    if not best:
        return None
    listed = next((v.quant for v in variants if v.filename == best and v.quant), None)
    return listed or gguf_variant_key(best)


async def _audio_cpp_variants_answer(
    repo_id: str, hf_token: Optional[str], offline: bool
) -> Optional[VariantsAnswer]:
    """group audio.cpp umbrella and package components; generic single-file repos return None."""
    from core.inference import audio_cpp_models
    from core.inference.audio_cpp_failures import estimate_resident_gb, gpu_estimate_applies

    text = (repo_id or "").strip()
    umbrella = audio_cpp_models.is_umbrella_id(text)
    if not umbrella and not (_is_valid_repo_id(text) and text.lower().startswith("audio-cpp/")):
        return None
    real_repo = audio_cpp_models.repo_of(text) or text
    network = not (offline or audio_cpp_models.hub_offline())
    if account_access.managed_account():
        # Offline: the disk pool and a disk-only grant check, never queued behind Hub listings.
        await listing_thread(
            not network,
            account_access.require_model_access,
            real_repo,
            **({} if network else {"offline": True}),
        )
    try:
        model = await listing_thread(
            not network, audio_cpp_models.resolve, text, None, hf_token, network = network
        )
    except Exception as exc:  # noqa: BLE001 - the generic lister reports an unreadable repo
        logger.debug("audio.cpp variants for %s unavailable: %s", text, exc)
        model = None
    if model is None:
        if umbrella:
            raise HTTPException(status_code = 404, detail = f"No GGUF variants found in {text}.")
        return None
    if not umbrella and not model.is_package:
        return None
    from core.inference import audio_cpp_files

    def _details():
        companions = [
            audio_cpp_models.resolve(c.id, c.variant, hf_token, network = network)
            for c in model.companions
        ]
        companions_cached = all(
            c is not None and audio_cpp_files.cached_files(c) is not None for c in companions
        )
        companion_bytes = sum(c.variant.size_bytes for c in companions if c is not None)
        # An unresolved companion (offline, nothing cached) has an unknown size: no remainder then.
        missing_companion_bytes = (
            None
            if any(c is None for c in companions)
            else sum(
                c.variant.size_bytes for c in companions if audio_cpp_files.cached_files(c) is None
            )
        )
        try:
            incomplete = download_registry.incomplete_blob_hashes(
                "model", model.repo_id, active_only = True
            )
        except Exception as e:
            logger.warning(f"Partial check failed for {model.id}: {e}")
            incomplete = set()
        # A file every row lists (a package's configs, a voice folder) says nothing about one row.
        counts: dict[str, int] = {}
        for variant in model.variants:
            for path in {f.path for f in variant.files}:
                counts[path] = counts.get(path, 0) + 1
        gpu_placed = gpu_estimate_applies(model.audio_type)
        rows = []
        for variant in model.variants:
            row_model = model.with_variant(variant)
            downloaded = companions_cached and audio_cpp_files.cached_files(row_model) is not None
            partial = False
            remaining = None
            key = variant.key if model.is_package else gguf_variant_key(variant.primary)
            if not downloaded:
                missing_files = audio_cpp_files.missing_files(row_model)
                missing = {path for path, _size in missing_files}
                own_cached = any(
                    f.path not in missing and counts.get(f.path, 0) == 1 for f in variant.files
                )
                try:
                    partial = own_cached or hf_cache_scan.is_variant_partial(
                        model.repo_id,
                        key,
                        incomplete_blob_hashes = incomplete,
                        variant_blob_hashes = gguf_variant_blob_hashes(
                            model.repo_id,
                            key,
                            hf_token,
                            include_companions = False,
                            allow_remote = False,
                        ),
                    )
                except Exception as e:
                    logger.warning(f"Partial check failed for {model.id} [{variant.key}]: {e}")
                    partial = own_cached
                if partial:
                    remaining = (
                        None
                        if model.is_package
                        else variant_remaining_bytes_from_state(model.repo_id, key, None)
                    )
                    if remaining is None:
                        remaining = _audio_cpp_remaining_bytes(
                            model.repo_id, key, missing_files, missing_companion_bytes
                        )
            rows.append(
                GgufVariantDetail(
                    filename = variant.main_file,
                    quant = variant.key,
                    display_label = variant.label,
                    size_bytes = variant.size_bytes,
                    download_size_bytes = variant.size_bytes + companion_bytes,
                    estimated_resident_gb = (
                        estimate_resident_gb(variant.size_bytes, model.family)
                        if gpu_placed and not row_model.cpu_only
                        else None
                    ),
                    download_remaining_bytes = remaining,
                    downloaded = downloaded,
                    partial = partial,
                    partial_transport = (
                        _partial_transport_for_variant(model.repo_id, key) if partial else None
                    ),
                    partial_resumable = partial
                    and _partial_resumable_for_variant(model.repo_id, key),
                )
            )
        return rows

    details = await listing_thread(not network, _details)
    loadable = [row.quant for row in details if row.downloaded]
    return VariantsAnswer(
        GgufVariantsResponse(
            repo_id = model.id,
            variants = details,
            has_vision = False,
            default_variant = model.default_variant,
            dependencies_resolved = True,
            loadable_variants = loadable,
            loadable = bool(loadable),
        ),
        None,
        # No llama.cpp context window to read off these files.
        cache_authorized = False,
    )


_VISION_PIPELINE_TAGS = frozenset(
    {"image-text-to-text", "image-to-text", "visual-question-answering"}
)


async def _mlx_precision_variants_answer(
    repo_id: str,
    hf_token: Optional[str],
    offline: bool,
    cache_readable: bool = True,
    info = None,
) -> Optional[VariantsAnswer]:
    """The precision folders of an MLX repo (``4-bit/``, ``6-bit/``, ``8bit/``) as its variants,
    else None. Each folder is a whole checkpoint, so a pick downloads and loads that folder alone.
    *info* is this request's own ``model_info`` (same token, files_metadata), reused if given."""
    if is_local_path(repo_id) or not _is_valid_repo_id(repo_id):
        return None
    from hub.utils.mlx_variants import cached_precision_folder, looks_like_mlx_repo
    from hub.utils.snapshot_filters import (
        precision_variant_subfolders,
        repo_ships_root_safetensors,
    )
    from utils.utils import hf_cache_snapshot_dir_for_repo

    def _listing() -> Optional[GgufVariantsResponse]:
        sizes: dict[str, int] = {}
        hashes: dict[str, Optional[str]] = {}
        has_vision = False
        if not offline:
            from huggingface_hub import HfApi
            try:
                hub_info = info
                if hub_info is None:
                    hub_info = call_with_anonymous_retry(
                        lambda token: HfApi(token = token).model_info(
                            repo_id, files_metadata = True, timeout = 5.0
                        ),
                        hf_token,
                    )
            except Exception as exc:  # noqa: BLE001 - fall back to the cached copy below
                logger.debug("MLX precision folders for %s unavailable: %s", repo_id, exc)
            else:
                tags = {str(tag).lower() for tag in (hub_info.tags or [])}
                if (
                    "mlx" not in tags
                    and str(hub_info.library_name or "").lower() != "mlx"
                    and not looks_like_mlx_repo(repo_id)
                ):
                    return None
                sizes = {s.rfilename: int(s.size or 0) for s in (hub_info.siblings or [])}
                hashes = {s.rfilename: sibling_sha256(s) for s in (hub_info.siblings or [])}
                has_vision = str(hub_info.pipeline_tag or "").lower() in _VISION_PIPELINE_TAGS
        if not sizes:
            # A caller refused this repo's cache learns nothing from it.
            if not cache_readable:
                return None
            snapshot = hf_cache_snapshot_dir_for_repo(repo_id)
            if snapshot is None:
                return None
            sizes = {
                path.relative_to(snapshot).as_posix(): path.stat().st_size
                for path in snapshot.rglob("*")
                if path.is_file()
            }
            for folder in precision_variant_subfolders(sizes):
                try:
                    config = json.loads((snapshot / folder / "config.json").read_text("utf-8"))
                except (OSError, ValueError):
                    continue
                has_vision = has_vision or isinstance(config.get("vision_config"), dict)
        folders = precision_variant_subfolders(sizes)
        if not folders:
            return None

        def _weights(names) -> Optional[tuple[str, ...]]:
            # Content hashes: two folders of one architecture and dtype can match in size alone.
            found = [hashes.get(name) for name in names if name.lower().endswith(".safetensors")]
            return tuple(sorted(found)) if found and all(found) else None

        root_weights = (
            _weights([name for name in sizes if "/" not in name])
            if repo_ships_root_safetensors(sizes)
            else None
        )
        rows = sorted(
            (
                GgufVariantDetail(
                    filename = f"{folder}/",
                    quant = folder,
                    size_bytes = sum(sizes[name] for name in names),
                    download_size_bytes = sum(sizes[name] for name in names),
                    downloaded = cache_readable
                    and cached_precision_folder(repo_id, folder) is not None,
                )
                for folder, names in folders.items()
            ),
            key = lambda row: row.size_bytes,
        )
        default = next(
            (
                folder
                for folder, names in folders.items()
                if root_weights and _weights(names) == root_weights
            ),
            None,
        )
        loadable = [row.quant for row in rows if row.downloaded]
        return GgufVariantsResponse(
            repo_id = repo_id,
            variants = rows,
            has_vision = has_vision,
            default_variant = default,
            dependencies_resolved = True,
            loadable_variants = loadable,
            variant_format = "mlx",
        )

    response = await listing_thread(offline, _listing)
    if response is None:
        return None
    return VariantsAnswer(response, None, cache_authorized = False)


_LOOKUP_REMOTE_ENV = "UNSLOTH_LOOKUP_TABLE_REMOTE"
_LOOKUP_DEADLINE_S = 2.0
_LOOKUP_CONCURRENCY = 4
_LOOKUP_ARCH_TTL_S = 6 * 3600.0
_LOOKUP_ARCH_FAIL_TTL_S = 600.0
_lookup_arch_cache: dict[tuple[str, str], tuple[Optional[str], float]] = {}
_lookup_arch_lock = threading.Lock()
# Key of a read in flight -> its done event, so a second listing waits for it instead of skipping.
_lookup_inflight: dict = {}
_LOOKUP_POOL = ThreadPoolExecutor(
    max_workers = _LOOKUP_CONCURRENCY, thread_name_prefix = "gguf-lookup-tables"
)


async def _lookup_thread(fn, /, *args):
    loop = asyncio.get_running_loop()
    call = functools.partial(contextvars.copy_context().run, fn, *args)
    return await loop.run_in_executor(_LOOKUP_POOL, call)


def _claim_lookup(key) -> tuple[Optional[threading.Event], Optional[threading.Event]]:
    """``(None, own)`` once ``key`` is claimed here, else ``(held, None)``: the done event
    of the read already holding it."""
    with _lookup_arch_lock:
        held = _lookup_inflight.get(key)
        if held is not None:
            return held, None
        own = _lookup_inflight[key] = threading.Event()
        return None, own


def _release_lookup(key, own: threading.Event) -> None:
    """Release ``key`` if ``own`` still holds it: a late worker never drops a newer claim."""
    with _lookup_arch_lock:
        if _lookup_inflight.get(key) is own:
            del _lookup_inflight[key]
    own.set()


async def _wait_for_lookup(done: threading.Event, deadline: float) -> bool:
    """Whether another listing's read of the same key ended before ``deadline`` (loop time)."""
    loop = asyncio.get_running_loop()
    while not done.is_set():
        if loop.time() >= deadline:
            return False
        await asyncio.sleep(0.02)
    return True


def _release_unrun_lookup(started: list, key, own, task: "asyncio.Future") -> None:
    """Release the inflight key of a read that never ran."""
    if not started and (task.cancelled() or task.exception() is not None):
        _release_lookup(key, own)


async def _lookup_await_once(key, deadline: float, fn, /, *args):
    """``fn(*args)`` on the lookup pool, awaited until ``deadline`` (loop time). A call
    already in flight under ``key`` is waited for, then ``fn`` reruns on its cached answer
    (or retries, when that call left none)."""
    while True:
        held, own = _claim_lookup(key)
        if own is not None:
            break
        if not await _wait_for_lookup(held, deadline):
            return None

    started: list = []
    # Set at the deadline: a worker freeing up mid-cancel skips the call instead of running late.
    expired = threading.Event()

    def _run():
        started.append(True)
        try:
            return None if expired.is_set() else fn(*args)
        finally:
            _release_lookup(key, own)

    task = asyncio.ensure_future(_lookup_thread(_run))
    task.add_done_callback(functools.partial(_release_unrun_lookup, started, key, own))
    loop = asyncio.get_running_loop()
    done, _pending = await asyncio.wait({task}, timeout = max(0.0, deadline - loop.time()))
    if task not in done:
        expired.set()
        task.cancel()
        return None
    if task.cancelled() or task.exception() is not None:
        return None
    return task.result()


def _cached_hub_repo_architecture(repo_id: str, hf_token: Optional[str]):
    """``(known, architecture)`` from the cache alone; never blocks on the Hub."""
    key = (repo_id.lower(), hf_cache_scan.token_fingerprint(hf_token))
    with _lookup_arch_lock:
        hit = _lookup_arch_cache.get(key)
    if hit is not None and hit[1] > time.monotonic():
        return True, hit[0]
    return False, None


_LOOKUP_HOST_TTL_S = 60.0
_lookup_host_streams: list = [None, 0.0]


def _host_streams_lookup_tables() -> bool:
    """Whether a default launch here streams the tables (an iGPU / APU reads them resident)."""
    now = time.monotonic()
    with _lookup_arch_lock:
        streams, expires = _lookup_host_streams
    if streams is not None and expires > now:
        return streams
    try:
        from routes.inference import get_llama_cpp_backend
        streams = bool(get_llama_cpp_backend().lookup_tables_stream_by_default())
    except Exception:  # noqa: BLE001 -- unknown: price the tables as resident
        streams = False
    with _lookup_arch_lock:
        _lookup_host_streams[:] = [streams, now + _LOOKUP_HOST_TTL_S]
    return streams


def _listing_lazy_mode() -> str:
    """The lazy mode a default launch here runs under."""
    try:
        from core.inference.llama_cpp import _effective_lazy_mode
        from routes.inference import get_llama_cpp_backend

        flag = get_llama_cpp_backend().probe_server_capabilities().get("lazy_mode_flag")
        mode = _effective_lazy_mode(None, os.environ, flag = str(flag or "--lazy-mode"))
    except Exception:  # noqa: BLE001 -- unknown build: the default threshold
        return "auto"
    return "on" if mode == "on" else "auto"


def _lookup_remote_enabled() -> bool:
    return (os.environ.get(_LOOKUP_REMOTE_ENV) or "").strip().lower() not in (
        "0",
        "off",
        "false",
        "no",
    )


def _hub_repo_architecture(repo_id: str, hf_token: Optional[str]) -> Optional[str]:
    """``general.architecture`` the Hub reports for a GGUF repo, cached per repo and token."""
    key = (repo_id.lower(), hf_cache_scan.token_fingerprint(hf_token))
    now = time.monotonic()
    with _lookup_arch_lock:
        hit = _lookup_arch_cache.get(key)
    if hit is not None and hit[1] > now:
        return hit[0]
    arch: Optional[str] = None
    ttl = _LOOKUP_ARCH_FAIL_TTL_S
    try:
        from huggingface_hub import HfApi

        info = HfApi().model_info(repo_id, expand = ["gguf"], token = hf_token or None, timeout = 5)
        gguf_meta = getattr(info, "gguf", None) or {}
        arch = str(gguf_meta.get("architecture") or "") or None
        ttl = _LOOKUP_ARCH_TTL_S
    except Exception as exc:  # noqa: BLE001 -- unknown arch: no remote reads
        logger.debug("lookup tables: no architecture for %s (%s)", repo_id, exc)
    with _lookup_arch_lock:
        _lookup_arch_cache[key] = (arch, now + ttl)
    return arch


def _local_variant_gguf(
    answer: "VariantsAnswer",
    repo_id: str,
    variant,
    local_path: Optional[str] = None,
) -> Optional[str]:
    """The on-disk main GGUF behind a listed row, or None."""
    filename = str(variant.filename or "")
    sources = answer.variant_context_sources or {}
    candidates = [sources.get(str(variant.quant or "").lower())]
    roots = [repo_id] if is_local_path(repo_id) else []
    if answer.context_source:
        roots.append(answer.context_source)
    pinned = _snapshot_scope_for_request(repo_id, local_path)
    if pinned is not None:
        roots.append(str(pinned))
    for root in roots:
        path = Path(root).expanduser()
        candidates.append(str((path.parent if path.is_file() else path) / filename))
    for candidate in candidates:
        if candidate and os.path.isfile(candidate):
            return candidate
    if (
        variant.downloaded
        and answer.cache_authorized
        and not is_local_path(repo_id)
        and _is_valid_repo_id(repo_id)
    ):
        try:
            from huggingface_hub import try_to_load_from_cache

            repo_dir = _repo_cache_dir_for_request(repo_id, local_path)
            found = try_to_load_from_cache(repo_id, filename, cache_dir = str(repo_dir.parent))
            if isinstance(found, str) and os.path.isfile(found):
                return found
        except Exception:  # noqa: BLE001 -- not cached here
            return None
    return None


def _remote_lookup_bytes(
    repo_id: str,
    filename: str,
    hf_token,
    identity,
    mode = "auto",
    known_arch: Optional[str] = None,
) -> int:
    from hub.utils.gguf_lookup_tables import remote_lookup_info
    return remote_lookup_info(
        repo_id, filename, hf_token, identity = identity, mode = mode, known_arch = known_arch
    )[1]


async def _with_lookup_tables(
    answer: "VariantsAnswer",
    repo_id: str,
    *,
    hf_token: Optional[str],
    offline: bool,
    prefer_local_cache: bool,
    local_path: Optional[str] = None,
) -> "VariantsAnswer":
    """``answer`` with ``lookup_table_bytes`` filled per variant."""
    try:
        from core.inference.lookup_tables import LAZY_READ_AUTO_MIN_BYTES
        from hub.utils.gguf_lookup_tables import (
            lazy_architecture,
            local_lookup_info,
            remote_cached,
        )

        variants = list(answer.response.variants or ())
        # A host that reads the tables resident lists no discount: no header is worth reading.
        if not variants or not await listing_thread(True, _host_streams_lookup_tables):
            return answer
        mode = await listing_thread(True, _listing_lazy_mode)
        found: dict[int, int] = {}
        arch: Optional[str] = None
        unresolved = []
        for index, v in enumerate(variants):
            if not str(v.filename or "").lower().endswith(".gguf"):
                continue
            # An update's cached file is the old revision: online, read the published header.
            published = v.update_available and not offline and not prefer_local_cache
            path = (
                None
                if published and not is_local_path(repo_id)
                else await listing_thread(True, _local_variant_gguf, answer, repo_id, v, local_path)
            )
            if path:
                local_arch, table = await listing_thread(True, local_lookup_info, path, mode)
                # Only a lazy one speaks for the repo: a repo can hold several families.
                if lazy_architecture(local_arch):
                    arch = arch or local_arch
                if local_arch is not None:
                    found[index] = table
                    continue
            # Not on disk, or unreadable there (a shard still downloading): the Hub's header.
            unresolved.append((index, v))
        remote_ok = (
            unresolved
            and not offline
            and not prefer_local_cache
            and _lookup_remote_enabled()
            and not is_local_path(repo_id)
            and _is_valid_repo_id(repo_id)
        )
        if remote_ok:
            # Its own try: a Hub failure must not drop the local answers above.
            try:
                deadline = asyncio.get_running_loop().time() + _LOOKUP_DEADLINE_S
                if arch is None:
                    known, arch = _cached_hub_repo_architecture(repo_id, hf_token)
                    if not known and (
                        mode == "on"
                        or any(
                            int(v.size_bytes or 0) > LAZY_READ_AUTO_MIN_BYTES
                            for _i, v in unresolved
                        )
                    ):
                        arch = await _lookup_await_once(
                            ("arch", repo_id.lower(), hf_cache_scan.token_fingerprint(hf_token)),
                            deadline,
                            _hub_repo_architecture,
                            repo_id,
                            hf_token,
                        )
                if lazy_architecture(arch):
                    _fingerprint = hf_cache_scan.token_fingerprint(hf_token)
                    tasks = {}
                    for index, v in unresolved:
                        identity = int(v.size_bytes or 0)
                        # Under auto only a tensor over the threshold streams.
                        if mode != "on" and 0 < identity <= LAZY_READ_AUTO_MIN_BYTES:
                            continue
                        cached = remote_cached(repo_id, v.filename, None, identity, mode = mode)
                        if cached is not None:
                            found[index] = cached[1]
                            continue
                        key = ("table", repo_id.lower(), v.filename, identity, mode, _fingerprint)
                        task = asyncio.ensure_future(
                            _lookup_await_once(
                                key,
                                deadline,
                                _remote_lookup_bytes,
                                repo_id,
                                v.filename,
                                hf_token,
                                identity,
                                mode,
                                arch,
                            )
                        )
                        tasks[task] = index
                    for task, value in zip(tasks, await asyncio.gather(*tasks)):
                        found[tasks[task]] = int(value or 0)
            except Exception as exc:  # noqa: BLE001 -- keep the local answers
                logger.debug("lookup tables: Hub reads skipped for %s (%s)", repo_id, exc)
        if not any(found.values()):
            return answer
        updated = [
            v.model_copy(update = {"lookup_table_bytes": int(found.get(i, 0) or 0)})
            if found.get(i)
            else v
            for i, v in enumerate(variants)
        ]
        return answer._replace(response = answer.response.model_copy(update = {"variants": updated}))
    except Exception as exc:  # noqa: BLE001 -- the listing never fails on this
        logger.debug("lookup tables: listing annotation skipped for %s (%s)", repo_id, exc)
        return answer


async def get_gguf_variants_answer(
    repo_id: str,
    prefer_local_cache: bool = False,
    offline: bool = False,
    local_path: Optional[str] = None,
    hf_token: Optional[str] = None,
    include_cache_locations: bool = False,
) -> VariantsAnswer:
    """Returns each quant with file sizes, vision support and the recommended default; local folders too."""
    access_options = {"offline": True} if offline else {}
    if local_path:
        if account_access.managed_account():
            await listing_thread(
                offline, account_access.require_model_access, local_path, **access_options
            )
    hf_token = account_access.account_hf_token(hf_token)
    from core.inference.audio_cpp_models import is_umbrella_id

    # Umbrella folder and package repo (YuE2) On Device rows send their row id as local_path.
    row_id = bool(local_path) and local_path.strip().lower() == (repo_id or "").strip().lower()
    if not local_path or is_umbrella_id(repo_id) or row_id:
        audio_cpp_answer = await _audio_cpp_variants_answer(repo_id, hf_token, offline)
        if audio_cpp_answer is not None:
            return audio_cpp_answer
    if account_access.managed_account():
        try:
            await listing_thread(
                offline, account_access.require_model_access, repo_id, **access_options
            )
        except HTTPException:
            # No grant before first download: a private repo needs own token; offline needs grant or public proof.
            if offline or not isinstance(hf_token, str) or not hf_token.strip():
                raise
            if is_local_path(repo_id) or not _is_valid_repo_id(repo_id):
                raise
            await listing_thread(
                False, account_access.authorize_download, repo_id, "model", hf_token
            )
    # Sent back since the HF cache answers before local_path; callers cannot infer the copy.
    answered_from: list[Optional[str]] = [None]
    # A repo id naming a directory is answered by that directory alone, or a GGUF-less dir evicts it.
    answered_locally = [False]
    # Read by the route before its own cache walk, which this listing does not cover.
    cache_authorized = [True]
    variant_context_sources: dict[str, str] = {}
    hub_listing = None
    hub_model_info: list = []
    # The downloaded rows a Hub-less answer proved complete from disk, see _locally_resolved.
    locally_proven: list[Optional[frozenset]] = [None]

    def _compute(local_path: Optional[str] = local_path) -> GgufVariantsResponse:
        nonlocal hub_listing
        repo_cache_dir = (
            None if is_local_path(repo_id) else _repo_cache_dir_for_request(repo_id, local_path)
        )
        hub_cache = repo_cache_dir.parent if repo_cache_dir is not None else None
        snapshot_scope = _snapshot_scope_for_request(repo_id, local_path)

        def _merge_when_the_repo_id_loads(response_repo_id, cached, root):
            """Searches all revisions only where the repo id is the load target; a snapshot-dir row
            loads alone."""
            variants, has_vision, complete, snapshot = cached
            if not complete:
                return cached
            try:
                from hub.utils.hf_cache_state import same_existing_path
                from utils.hf_cache_settings import get_hf_cache_paths

                repo_dir = snapshot.parent.parent
                if not same_existing_path(repo_dir.parent, get_hf_cache_paths().hub_cache):
                    return cached
                default_snapshot = hf_cache_scan.default_ref_snapshot(repo_dir)
                if default_snapshot is None or not same_existing_path(default_snapshot, snapshot):
                    return cached
            except (OSError, RuntimeError, ValueError):
                return cached
            return merge_sibling_snapshot_variants(response_repo_id, cached, root = root)

        def _local_response(
            response_repo_id: str,
            variants,
            has_vision: bool,
            complete = None,
            context_root: Optional[str] = None,
        ) -> GgufVariantsResponse:
            """mark *complete* quants ready, keep incomplete rows manageable, and treat None as all ready."""

            def _downloaded(v) -> bool:
                # unlabelled quants cannot be judged and remain ready
                return complete is None or not v.quant or v.quant in complete

            if context_root:
                # absolute, since detect_gguf_model answers absolute paths for a relative id
                root = Path(context_root).expanduser().absolute()
                source_root = root.parent if root.is_file() else root
                rows_by_legacy_key: dict[str, list] = {}
                for variant in variants:
                    if variant.quant and variant.filename:
                        rows_by_legacy_key.setdefault(
                            gguf_variant_key(variant.filename).lower(), []
                        ).append(variant)
                for rows in rows_by_legacy_key.values():
                    if len(rows) < 2:
                        continue
                    for variant in rows:
                        if not _downloaded(variant):
                            continue
                        source = source_root / variant.filename
                        if source.is_file():
                            variant_context_sources[variant.quant.lower()] = str(source)

            ready = [v for v in variants if _downloaded(v)]
            default_variant = _default_variant_key(ready or variants, repo_id)
            if context_root:
                if any(len(rows) > 1 for rows in rows_by_legacy_key.values()):
                    try:
                        from utils.models.model_config import detect_gguf_model

                        detected = detect_gguf_model(str(root))
                        relative = (
                            Path(detected).relative_to(source_root).as_posix() if detected else None
                        )
                        preferred = next(
                            (v for v in ready or variants if v.quant == default_variant), None
                        )
                        preferred_group = (
                            gguf_variant_key(preferred.filename).lower() if preferred else None
                        )
                        # detection only breaks ties between builds of the preferred quant
                        selected = next(
                            (
                                variant
                                for variant in ready or variants
                                if variant.filename == relative
                                and gguf_variant_key(variant.filename).lower() == preferred_group
                                and len(rows_by_legacy_key.get(preferred_group, [])) > 1
                            ),
                            None,
                        )
                        # the loader-detected row only wins inside the bare id's default scope
                        if (
                            selected is not None
                            and selected.filename
                            in _default_variant_candidates(ready or variants, repo_id)
                        ):
                            default_variant = selected.quant
                    except (OSError, RuntimeError, ValueError):
                        pass

            return GgufVariantsResponse(
                repo_id = response_repo_id,
                variants = [
                    GgufVariantDetail(
                        filename = v.filename,
                        quant = v.quant,
                        display_label = v.display_label,
                        size_bytes = v.size_bytes,
                        download_size_bytes = v.size_bytes,
                        download_remaining_bytes = (
                            None
                            if _downloaded(v)
                            else variant_remaining_bytes_from_state(
                                response_repo_id, v.quant, repo_cache_dir
                            )
                        ),
                        downloaded = _downloaded(v),
                        partial = not _downloaded(v),
                        dependency_key = _variant_dependency_key(response_repo_id, v.filename),
                    )
                    for v in variants
                ],
                has_vision = has_vision,
                default_variant = default_variant,
            )

        def _partial_local_response(
            response_repo_id: str, variants, has_vision: bool
        ) -> GgufVariantsResponse:
            default_variant = _default_variant_key(variants, repo_id)
            return GgufVariantsResponse(
                repo_id = response_repo_id,
                variants = [
                    GgufVariantDetail(
                        filename = v.filename,
                        quant = v.quant,
                        display_label = v.display_label,
                        size_bytes = v.size_bytes,
                        download_size_bytes = v.download_size_bytes or v.size_bytes,
                        download_remaining_bytes = variant_remaining_bytes_from_state(
                            response_repo_id,
                            v.quant,
                            repo_cache_dir,
                        ),
                        downloaded = False,
                        partial = True,
                        partial_transport = _partial_transport_for_variant(
                            response_repo_id,
                            v.quant,
                            repo_cache_dir,
                        ),
                        partial_resumable = _partial_resumable_for_variant(
                            response_repo_id,
                            v.quant,
                            repo_cache_dir,
                        ),
                        dependency_key = _variant_dependency_key(response_repo_id, v.filename),
                    )
                    for v in variants
                ],
                has_vision = has_vision,
                default_variant = default_variant,
            )

        def _with_state_partials(
            response: GgufVariantsResponse, snapshot_dir: Optional[Path]
        ) -> GgufVariantsResponse:
            """Overlays download state on cache rows; a cancel marker stays authoritative until cleared."""
            state = _quants_from_state(repo_id, hub_cache)
            if state is None:
                return response

            state_by_quant = {v.quant.lower(): v for v in state[0] if v.quant}
            listed: set[str] = set()
            variants: list[GgufVariantDetail] = []
            changed = False
            repo_signal_applies = hf_cache_scan.repo_signal_applies_to_snapshot(
                repo_cache_dir,
                snapshot_dir,
            )
            complete_here = (
                {quant.lower() for quant in (_complete_quants_under(str(snapshot_dir)) or ())}
                if snapshot_dir is not None
                else set()
            )

            for detail in response.variants:
                key = detail.quant.lower() if detail.quant else ""
                if key:
                    listed.add(key)
                state_variant = state_by_quant.get(key)
                if state_variant is None:
                    variants.append(detail)
                    continue
                try:
                    is_partial = hf_cache_scan.is_variant_partial(
                        repo_id,
                        detail.quant,
                        snapshot_dir,
                        repo_cache_dir = repo_cache_dir,
                        # a ready row absent here comes from a complete sibling snapshot.
                        repo_signal_applies = (
                            repo_signal_applies if key in complete_here else not detail.downloaded
                        ),
                    )
                except Exception as e:
                    logger.warning(
                        "State-based partial check failed for %s/%s: %s",
                        repo_id,
                        detail.quant,
                        e,
                    )
                    variants.append(detail)
                    continue
                if not is_partial:
                    variants.append(detail)
                    continue

                state_download_size = int(
                    state_variant.download_size_bytes or state_variant.size_bytes or 0
                )
                detail = detail.model_copy(
                    update = {
                        "download_size_bytes": (
                            state_download_size
                            if state_download_size > 0
                            else detail.download_size_bytes
                        ),
                        "download_remaining_bytes": variant_remaining_bytes_from_state(
                            repo_id,
                            detail.quant,
                            repo_cache_dir,
                        ),
                        "downloaded": False,
                        "partial": True,
                        "partial_transport": _partial_transport_for_variant(
                            repo_id,
                            detail.quant,
                            repo_cache_dir,
                        ),
                        "partial_resumable": _partial_resumable_for_variant(
                            repo_id,
                            detail.quant,
                            repo_cache_dir,
                        ),
                    }
                )
                changed = True
                variants.append(detail)

            extra = [
                GgufVariantDetail(
                    filename = v.filename,
                    quant = v.quant,
                    display_label = v.display_label,
                    size_bytes = v.size_bytes,
                    download_size_bytes = v.download_size_bytes or v.size_bytes,
                    download_remaining_bytes = variant_remaining_bytes_from_state(
                        repo_id,
                        v.quant,
                        repo_cache_dir,
                    ),
                    downloaded = False,
                    partial = True,
                    partial_transport = _partial_transport_for_variant(
                        repo_id, v.quant, repo_cache_dir
                    ),
                    partial_resumable = _partial_resumable_for_variant(
                        repo_id, v.quant, repo_cache_dir
                    ),
                    dependency_key = _variant_dependency_key(repo_id, v.filename),
                )
                for v in state[0]
                if v.quant and v.quant.lower() not in listed
            ]
            if not (changed or extra):
                return response
            variants.extend(extra)
            ready = [v for v in variants if v.downloaded and not v.partial]
            default_variant = _default_variant_key(ready or variants, repo_id)
            return response.model_copy(
                update = {
                    "variants": variants,
                    "default_variant": default_variant,
                }
            )

        # normalize once so discovery and loading classify relative, WSL, and direct GGUF paths alike
        local_id = _loader_normalize_path(repo_id) if is_local_path(repo_id) else repo_id
        local_target = None
        try:
            probe = Path(local_id).expanduser()
            if is_local_path(repo_id) or probe.exists():
                local_target = probe
        except OSError:
            local_target = None
        if local_target is not None:
            variants, has_vision = list_local_gguf_variants(local_id)
            if local_target.is_file():
                # the loader opens this file whatever variant is named: same-quant siblings would load it
                # by shard-stripped family: a split row is listed under its first shard
                target_family = gguf_variant_family(local_target.name).lower()
                chosen = next(
                    (
                        v
                        for v in variants
                        if gguf_variant_family(Path(v.filename).name).lower() == target_family
                    ),
                    None,
                )
                if chosen is not None:
                    chosen_key = gguf_variant_key(chosen.filename).lower()
                    variants = [
                        v
                        for v in variants
                        if v is chosen or gguf_variant_key(v.filename).lower() != chosen_key
                    ]
            # The load id is this path, so a scan-torn quant is still ready when the file the resolver binds opens fine.
            complete = _complete_with_servable(local_id, _complete_quants_under(local_id), variants)
            if (
                not variants
                and local_target.is_file()
                and local_target.suffix.lower() == ".gguf"
                and _direct_gguf_loads(local_target)
            ):
                # detect_gguf_model still loads an unmarked-parent .gguf the dir scan skips.
                try:
                    size = local_target.stat().st_size
                except OSError:
                    size = 0
                # Load resolver's extractor; the hub one differs on F16-checkpoint-Q4_K_M.
                from utils.models.model_config import _extract_quant_label

                variants = [
                    GgufVariantInfo(
                        filename = local_target.name,
                        quant = _extract_quant_label(
                            f"{local_target.parent.name}/{local_target.name}"
                        ),
                        size_bytes = size,
                    )
                ]
                # Shard scan resolves to the marked parent; ask an unmarked file directly.
                complete = None if size > 0 and _direct_gguf_split_is_whole(local_target) else set()
            answered_from[0] = repo_id
            answered_locally[0] = True
            # Report the resolution so the CLI gate matches the resolver, not the id's shape.
            return _local_response(
                repo_id, variants, has_vision, complete, context_root = local_id
            ).model_copy(
                update = {
                    "resolved_locally": True,
                    "loadable_variants": _loadable_variants(local_id, variants),
                    "loadable": _loads_without_variant(local_id),
                }
            )

        # Reject malformed repo_ids with 400 up front, like download/delete, not a 500 from the HF client.
        if not _is_valid_repo_id(repo_id):
            raise HTTPException(status_code = 400, detail = f"Invalid repo_id: {repo_id!r}")

        # Gate HF cache reads: a denied caller could read a cached private repo's file list.
        # Shared gate keeps cached PUBLIC repos for the anonymous sentinel; one memoized probe.
        # is_cached=True: any narrower predicate would itself read the cache this gate withholds.
        cache_reads_authorized = not hub_cached_read_refused(
            hf_token, repo_id = repo_id, is_cached = lambda: True, offline = bool(offline)
        )

        def _locally_resolved(
            response: GgufVariantsResponse, snapshot: Optional[Path]
        ) -> GgufVariantsResponse:
            """Sets dependencies_resolved only when the Hub is unreadable and the disk alone proves
            rows loadable."""
            if snapshot is None or response.dependencies_resolved:
                return response
            from hub.utils.gguf_sources import (
                cached_gguf_manifest_complete,
                cached_gguf_source_partial,
            )

            downloaded = [v for v in response.variants if v.downloaded]
            if not downloaded or any(v.partial for v in downloaded):
                return response
            proven = set()
            for v in downloaded:
                if not v.quant or not v.filename:
                    return response
                try:
                    if not (snapshot / v.filename).is_file():
                        return response
                    if cached_gguf_source_partial(response.repo_id, v.quant, snapshot):
                        return response
                    if not cached_gguf_manifest_complete(response.repo_id, v.quant, snapshot):
                        return response
                    requirement = _variant_requirement_last_known(
                        _variant_hash_cache_key(response.repo_id, v.quant, hf_token)
                    )
                    if requirement is None and _variant_requirement_may_be_forgotten():
                        return response
                    for expected in requirement.expected_files if requirement is not None else ():
                        target = snapshot / expected.path
                        if not target.is_file() or (
                            expected.size and target.stat().st_size != expected.size
                        ):
                            return response
                except (OSError, RuntimeError, ValueError):
                    return response
                proven.add((v.quant.lower(), v.filename))
            locally_proven[0] = frozenset(proven)
            return response.model_copy(update = {"dependencies_resolved": True})

        def _scoped_local_response():
            """The pinned snapshot's own answer, or None when it holds nothing."""
            if snapshot_scope is None or not cache_reads_authorized:
                return None
            variants, has_vision = list_local_gguf_variants(str(snapshot_scope))
            if not (variants or has_vision):
                return None
            answered_from[0] = str(snapshot_scope)
            return _with_state_partials(
                _local_response(
                    repo_id, variants, has_vision, _complete_quants_under(str(snapshot_scope))
                ),
                snapshot_scope,
            )

        local_only = prefer_local_cache or offline
        if local_only:
            scoped_response = _scoped_local_response()
            if scoped_response is not None:
                return (
                    _locally_resolved(scoped_response, snapshot_scope)
                    if offline
                    else scoped_response
                )
            cached = (
                select_gguf_cache_snapshot(repo_id, root = hub_cache)
                if cache_reads_authorized
                else None
            )
            if cached is not None:
                variants, has_vision, complete, snapshot = _merge_when_the_repo_id_loads(
                    repo_id, cached, hub_cache
                )
                # Name the answering snapshot so context length reads from the same revision.
                answered_from[0] = str(snapshot)
                # The lister leaves torn quants in: they stay listed for management, but not ready.
                response = _with_state_partials(
                    _local_response(repo_id, variants, has_vision, complete),
                    snapshot,
                )
                return _locally_resolved(response, snapshot) if offline else response
            if local_path and is_local_path(local_path):
                # named Hub snapshots remain cache reads during filesystem fallback
                cached_ref = cached_repo_ref_for_path(local_path)
                if cached_ref is not None and hub_cached_read_refused(
                    hf_token,
                    repo_id = cached_ref[0],
                    repo_type = cached_ref[1],
                    is_cached = lambda: True,
                    offline = bool(offline),
                ):
                    raise HTTPException(status_code = 404, detail = "Model not found")
                variants, has_vision = list_local_gguf_variants(local_path)
                if variants or has_vision:
                    answered_from[0] = local_path
                    # torn quants remain ready when their resolver-selected files are servable
                    complete = _complete_with_servable(
                        local_path, _complete_quants_under(local_path), variants
                    )
                    return _local_response(
                        repo_id, variants, has_vision, complete, context_root = local_path
                    )
            partial = _quants_from_state(repo_id, hub_cache) if cache_reads_authorized else None
            if partial is not None:
                variants, has_vision = partial
                return _partial_local_response(repo_id, variants, has_vision)
            if local_path and offline:
                return GgufVariantsResponse(
                    repo_id = repo_id,
                    variants = [],
                    has_vision = False,
                    default_variant = None,
                )
            if offline:
                raise HTTPException(
                    status_code = 404,
                    detail = "No cached GGUF variants available while offline.",
                )

        def _cache_fallback_response():
            """Scopes the cached answer to the cache this request names, so the listing matches that
            copy."""
            if not cache_reads_authorized:
                # An unauthorized caller whose hub call failed gets that failure, not the cache's answer to it.
                return None
            scoped_response = _scoped_local_response()
            if scoped_response is not None:
                return _locally_resolved(scoped_response, snapshot_scope)
            cached = select_gguf_cache_snapshot(repo_id, root = hub_cache)
            if cached is not None:
                variants, has_vision, complete, snapshot = _merge_when_the_repo_id_loads(
                    repo_id, cached, hub_cache
                )
                answered_from[0] = str(snapshot)
                # As in local_only: an unreachable Hub leaves resumes nowhere to surface, so keep state partials.
                return _locally_resolved(
                    _with_state_partials(
                        _local_response(repo_id, variants, has_vision, complete),
                        snapshot,
                    ),
                    snapshot,
                )
            partial = _quants_from_state(repo_id, hub_cache)
            if partial is not None:
                variants, has_vision = partial
                return _partial_local_response(repo_id, variants, has_vision)
            return None

        try:
            if hub_listing is None:
                sink_token = HUB_MODEL_INFO_SINK.set(hub_model_info)
                try:
                    hub_listing = list_gguf_variants(repo_id, hf_token = hf_token)
                finally:
                    HUB_MODEL_INFO_SINK.reset(sink_token)
            variants, has_vision, siblings = hub_listing
        except Exception:
            # Ungated: _cache_fallback_response already refuses an unauthorized caller.
            fallback = _cache_fallback_response()
            if fallback is not None:
                return fallback
            raise

        # repo-wide cache answers still use this request's cache to determine readiness
        if siblings is None:
            if not cache_reads_authorized:
                # falling through would expose the first cache answer despite rejecting the second read
                raise HTTPException(
                    status_code = 404,
                    detail = "No GGUF variants available without Hub authorization.",
                )
            fallback = _cache_fallback_response()
            if fallback is not None:
                return fallback

        default_variant = _default_variant_key(variants, repo_id)

        # snapshot totals keep shard sets intact, take maximum sizes, and compare keys case-insensitively
        cached_snapshots: list[tuple[dict[str, int], dict[str, int]]] = []
        # public listings do not authorize exposing a caller's cached download and partial state
        if _is_valid_repo_id(repo_id) and cache_reads_authorized:
            # pinned rows resolve inside one snapshot and ignore other cached copies
            scoped_snapshots = (
                [snapshot_scope]
                if snapshot_scope is not None
                else iter_hf_cache_snapshots(repo_id, root = hub_cache)
            )
            for snap in scoped_snapshots:
                try:
                    gguf_paths = list(_iter_gguf_paths(snap))
                except (OSError, RuntimeError, ValueError) as e:
                    logger.debug("Skipping GGUF cache snapshot %s: %s", snap, e)
                    continue
                by_filename: dict[str, int] = {}
                by_quant: dict[str, int] = {}
                for f in gguf_paths:
                    try:
                        rel = f.relative_to(snap).as_posix()
                        size = f.stat().st_size
                    except (OSError, RuntimeError, ValueError) as e:
                        logger.debug("Skipping GGUF cache file %s: %s", f, e)
                        continue
                    key = rel.lower()
                    by_filename[key] = max(by_filename.get(key, 0), size)
                    if (
                        _is_mmproj_filename(f.name)
                        or _is_mtp_drafter_path(rel)
                        or _is_imatrix_filename(f.name)
                    ):
                        continue
                    q = gguf_variant_key(rel)
                    if is_big_endian_gguf_path(rel, extract_quant_label(rel)):
                        continue
                    q = q.lower()
                    by_quant[q] = by_quant.get(q, 0) + size
                if by_filename or by_quant:
                    cached_snapshots.append((by_filename, by_quant))

        requirements_by_quant = {
            v.quant.lower(): _variant_requirement_cache_get(
                _variant_hash_cache_key(repo_id, v.quant, hf_token)
            )
            for v in variants
        }
        if any(req is None for req in requirements_by_quant.values()):
            fetched_requirements = _gguf_all_variant_requirements(
                repo_id, hf_token, siblings = siblings
            )
            for v in variants:
                key = v.quant.lower()
                if requirements_by_quant.get(key) is None:
                    requirements_by_quant[key] = fetched_requirements.get(key)

        def _filenames_cached_in_snapshot(
            by_filename: dict[str, int], filenames: frozenset[str], expected_size: int
        ) -> bool:
            if not filenames:
                return False
            wanted = [name.lower() for name in filenames]
            cached = 0
            for name in wanted:
                size = by_filename.get(name)
                if size is None:
                    return False
                cached += size
            return expected_size <= 0 or cached >= expected_size * 0.99

        def _filenames_cached(filenames: frozenset[str], expected_size: int) -> bool:
            # All files must live in a single snapshot, not spread across several.
            return any(
                _filenames_cached_in_snapshot(by_filename, filenames, expected_size)
                for by_filename, _by_quant in cached_snapshots
            )

        def _any_mmproj_cached(filenames: frozenset[str]) -> bool:
            if any(
                by_filename.get(name.lower()) is not None
                for by_filename, _by_quant in cached_snapshots
                for name in filenames
            ):
                return True
            return any(
                _is_mmproj_filename(name.rsplit("/", 1)[-1])
                for by_filename, _by_quant in cached_snapshots
                for name in by_filename
            )

        def _non_mmproj_companions(requirement: Optional[_GgufVariantRequirement]) -> tuple:
            if requirement is None:
                return ()
            return tuple(
                file
                for file in requirement.expected_files
                if _is_mtp_drafter_path(file.path) and not _is_mmproj_filename(file.path)
            )

        def _snapshot_has_companions(by_filename: dict[str, int], companions: tuple) -> bool:
            return all(
                _filenames_cached_in_snapshot(
                    by_filename,
                    frozenset({file.path}),
                    max(0, int(file.size or 0)),
                )
                for file in companions
            )

        def _main_and_companions_ready(requirement: _GgufVariantRequirement) -> bool:
            companions = _non_mmproj_companions(requirement)
            return any(
                _filenames_cached_in_snapshot(
                    by_filename,
                    requirement.main_filenames,
                    requirement.main_size_bytes,
                )
                and _snapshot_has_companions(by_filename, companions)
                for by_filename, _by_quant in cached_snapshots
            )

        def _quant_and_companions_ready(quant: str, size_bytes: int, companions: tuple) -> bool:
            if size_bytes <= 0:
                return False
            return any(
                by_quant.get(quant, 0) >= size_bytes * 0.99
                and _snapshot_has_companions(by_filename, companions)
                for by_filename, by_quant in cached_snapshots
            )

        def _pending_drafter(requirement: Optional[_GgufVariantRequirement], quant: str):
            """Name one companion-only transfer without mislabelling a model pull."""
            if requirement is None:
                return None
            for by_filename, _by_quant in cached_snapshots:
                if not _filenames_cached_in_snapshot(
                    by_filename, requirement.main_filenames, requirement.main_size_bytes
                ):
                    continue
                missing = tuple(
                    file
                    for file in _non_mmproj_companions(requirement)
                    if not _filenames_cached_in_snapshot(
                        by_filename, frozenset({file.path}), max(0, int(file.size or 0))
                    )
                )
                if len(missing) != 1:
                    continue
                local_blobs = local_blobs_by_quant.get(quant.lower(), {})
                for expected in requirement.expected_files:
                    if expected.path == missing[0].path:
                        continue
                    if not _filenames_cached_in_snapshot(
                        by_filename, frozenset({expected.path}), expected.size
                    ):
                        break
                    # Only subtract files the worker can reuse at the planned revision.
                    identities = local_blobs.get(expected.path.replace("\\", "/"), set())
                    if (
                        expected.sha256
                        and expected.sha256 not in identities
                        and not _size_identity_matches(identities, expected.size)
                    ):
                        break
                else:
                    return missing[0]
            return None

        def _is_fully_downloaded(variant) -> bool:
            quant = variant.quant.lower()
            requirement = requirements_by_quant.get(quant)
            # Non-mmproj companions (MTP, DSpark, DFlash) must be present: else the loader fetches
            # gigabytes inline with no Downloads row. Any mmproj precision still suffices.
            companions = _non_mmproj_companions(requirement)
            # Vision repos ship an mmproj adapter; any precision on disk suffices.
            if (
                requirement is not None
                and _main_and_companions_ready(requirement)
                and (
                    not requirement.mmproj_filenames
                    or _any_mmproj_cached(requirement.mmproj_filenames)
                )
            ):
                return True
            # Byte fallback stops a filename mismatch demoting a present quant; vision still needs an mmproj.
            if not _quant_and_companions_ready(quant, variant.size_bytes, companions):
                return False
            if (
                requirement is not None
                and requirement.mmproj_filenames
                and not _any_mmproj_cached(requirement.mmproj_filenames)
            ):
                return False
            return True

        partial_quants: set[str] = set()
        partial_quant_transports: dict[str, Optional[str]] = {}
        # Registry, markers and manifests read the operator's disk too: same authorization.
        partial_scan_variants = variants if cache_reads_authorized else ()
        incomplete_hashes: set = set()
        if cache_reads_authorized:
            try:
                incomplete_hashes = download_registry.incomplete_blob_hashes(
                    "model",
                    repo_id,
                    active_only = True,
                    root = hub_cache,
                )
            except Exception as e:
                logger.warning(f"Failed to compute partial GGUF variants for {repo_id}: {e}")
                incomplete_hashes = set()
        scan_snapshot_dir = snapshot_scope or hf_cache_scan.resolve_snapshot_dir_for_scan(
            "model",
            repo_id,
            repo_cache_dir,
        )
        # A marker or manifest carries no revision, so attribute it like the inventory row.
        repo_signal_applies = hf_cache_scan.repo_signal_applies_to_snapshot(
            repo_cache_dir, scan_snapshot_dir
        )
        # A quant this snapshot lacks stays the cancelled download (keeps resume/delete).
        excused_quants = (
            frozenset()
            if repo_signal_applies or scan_snapshot_dir is None
            else frozenset(
                q.lower() for q in (_complete_quants_under(str(scan_snapshot_dir)) or ())
            )
        )

        def _repo_signals_apply_to(quant: str) -> bool:
            return repo_signal_applies or quant.lower() not in excused_quants

        # Manifest, marker and blob checks catch cancelled downloads and missing or undersized shards.
        for variant in partial_scan_variants:
            try:
                requirement = requirements_by_quant.get(variant.quant.lower())
                variant_hashes = requirement.main_hashes if requirement is not None else None
                if variant_hashes is None and incomplete_hashes:
                    variant_hashes = gguf_variant_blob_hashes(
                        repo_id,
                        variant.quant,
                        hf_token,
                        include_companions = False,
                        repo_cache_dir = repo_cache_dir,
                    )
                if hf_cache_scan.is_variant_partial(
                    repo_id,
                    variant.quant,
                    scan_snapshot_dir,
                    incomplete_blob_hashes = incomplete_hashes,
                    variant_blob_hashes = variant_hashes,
                    repo_cache_dir = repo_cache_dir,
                    repo_signal_applies = _repo_signals_apply_to(variant.quant),
                ):
                    partial_quants.add(variant.quant)
                    partial_quant_transports[variant.quant] = _partial_transport_for_variant(
                        repo_id,
                        variant.quant,
                        repo_cache_dir,
                    )
            except Exception as e:
                logger.warning(
                    f"Manifest-based partial check failed for " f"{repo_id}/{variant.quant}: {e}"
                )
        # Same attribution as above: a pinned snapshot is not judged by a newer attempt's blobs.
        if incomplete_hashes:
            for variant in partial_scan_variants:
                requirement = requirements_by_quant.get(variant.quant.lower())
                if requirement is None or not _repo_signals_apply_to(variant.quant):
                    continue
                # companion_hashes adds the MTP drafter; mmproj_hashes covers all mmproj precisions in the repo.
                if (
                    (requirement.mmproj_hashes | requirement.companion_hashes) & incomplete_hashes
                ) and _filenames_cached(
                    requirement.main_filenames,
                    requirement.main_size_bytes,
                ):
                    partial_quants.add(variant.quant)
                    partial_quant_transports.setdefault(
                        variant.quant,
                        _partial_transport_for_variant(
                            repo_id,
                            variant.quant,
                            repo_cache_dir,
                        ),
                    )

        # Complete main, unstarted companion: no partial signal; stay visible unless readiness says loadable.
        for variant in partial_scan_variants:
            if variant.quant in partial_quants:
                continue
            requirement = requirements_by_quant.get(variant.quant.lower())
            if requirement is None or _is_fully_downloaded(variant):
                continue
            if not (
                _filenames_cached(requirement.main_filenames, requirement.main_size_bytes)
                or _quant_and_companions_ready(variant.quant.lower(), variant.size_bytes, ())
            ):
                continue
            partial_quants.add(variant.quant)
            partial_quant_transports.setdefault(
                variant.quant,
                _partial_transport_for_variant(
                    repo_id,
                    variant.quant,
                    repo_cache_dir,
                ),
            )

        local_blobs_by_quant = (
            _local_main_gguf_blobs_by_quant(repo_id, repo_cache_dir)
            if cache_reads_authorized
            else {}
        )

        def _variant_detail(v) -> GgufVariantDetail:
            is_partial = v.quant in partial_quants
            requirement = requirements_by_quant.get(v.quant.lower())
            downloaded = _is_fully_downloaded(v) and not is_partial
            pending_drafter = _pending_drafter(requirement, v.quant)
            return GgufVariantDetail(
                filename = v.filename,
                quant = v.quant,
                display_label = v.display_label,
                size_bytes = v.size_bytes,
                download_size_bytes = (
                    requirement.download_size_bytes if requirement is not None else v.size_bytes
                ),
                pending_drafter_filename = (
                    pending_drafter.path if pending_drafter is not None else None
                ),
                pending_drafter_size_bytes = (
                    max(0, int(pending_drafter.size or 0)) if pending_drafter is not None else 0
                ),
                # Scanned per partial variant only: repos carry one, and the scan walks blobs/.
                download_remaining_bytes = (
                    variant_remaining_bytes(repo_id, requirement, repo_cache_dir)
                    if is_partial
                    else None
                ),
                downloaded = downloaded,
                update_available = downloaded
                and _variant_update_available_from_requirement(
                    local_blobs_by_quant.get(v.quant.lower(), {}),
                    requirement,
                    v.quant,
                ),
                partial = is_partial,
                partial_transport = (partial_quant_transports.get(v.quant) if is_partial else None),
                partial_resumable = (
                    is_partial and _partial_resumable_for_variant(repo_id, v.quant, repo_cache_dir)
                ),
                dependency_key = _variant_dependency_key(repo_id, v.filename),
            )

        return GgufVariantsResponse(
            repo_id = repo_id,
            variants = [_variant_detail(v) for v in variants],
            has_vision = has_vision,
            default_variant = default_variant,
            dependencies_resolved = siblings is not None,
        )

    def _compute_with_cleanables() -> VariantsAnswer:
        # Returned with the answer: coalesced callers must all see the copy it answered from.
        response = _compute_response()
        return VariantsAnswer(
            response, answered_from[0], cache_authorized[0], variant_context_sources
        )

    def _compute_response() -> GgufVariantsResponse:
        skip = is_local_path(repo_id) or not _is_valid_repo_id(repo_id)
        # Same authorization as the listing, or a 200 with an empty folder reveals a cached private repo.
        if not skip and hub_cached_read_refused(
            hf_token, repo_id = repo_id, is_cached = lambda: True, offline = bool(offline)
        ):
            skip = True
            # Carried out: the route's context-length fallback walks these same caches.
            cache_authorized[0] = False
        # Scoped online verdicts: only the Hub answer for a copy's snapshot says if it is complete.
        scoped_responses = {}

        def _scoped_variant_row(snapshot: Path, quant: str):
            cached = scoped_responses.get(snapshot)
            if cached is None:
                original_source = answered_from[0]
                original_local = answered_locally[0]
                original_proven = locally_proven[0]
                try:
                    scoped = _compute(str(snapshot))
                finally:
                    locally_proven[0] = original_proven
                    answered_from[0] = original_source
                    # Restored: leaving it set would suppress the merge that reads it.
                    answered_locally[0] = original_local
                cached = {item.quant.lower(): item for item in scoped.variants}
                scoped_responses[snapshot] = cached
            return cached.get(quant.lower()) if quant else None

        def _scoped_quant_ready(snapshot: Path, quant: str) -> Optional[bool]:
            """Returns None for local-only requests, since companion readiness comes from Hub metadata."""
            if prefer_local_cache or offline:
                return None
            row = _scoped_variant_row(snapshot, quant)
            return None if row is None else bool(row.downloaded)

        sources = {}
        if (
            include_cache_locations
            and not skip
            # hub_cached_read_refused already gates this; re-testing dropped authorized anonymous reads.
            and (not local_path or local_path == repo_id)
        ):
            from hub.utils.gguf_sources import (
                cached_gguf_source_partial,
                cached_gguf_sources,
            )
            sources = cached_gguf_sources(repo_id, scoped_ready = _scoped_quant_ready)
        try:
            response = _compute()
        except Exception as exc:
            if sources and (prefer_local_cache or offline or hf_error_status(exc) is None):
                response = GgufVariantsResponse(repo_id = repo_id, variants = [])
            else:
                if skip:
                    raise
                enriched = _mark_empty_dir_cleanables(
                    repo_id,
                    GgufVariantsResponse(repo_id = repo_id, variants = []),
                    _repo_cache_dir_for_request(repo_id, local_path),
                )
                if enriched.variants:
                    return enriched
                raise
        if sources and not answered_locally[0]:
            variants = {v.quant.lower(): v for v in response.variants}
            online_answer = not (prefer_local_cache or offline or answered_from[0])
            for key, source in sources.items():
                v = source.variant
                previous = variants.get(key)
                active_repo_dir = _repo_cache_dir_for_request(repo_id, None)
                if previous is not None and source.cache_path == str(active_repo_dir):
                    if previous.downloaded:
                        previous.cache_path = source.cache_path
                        variant_context_sources[key] = str(source.snapshot / v.filename)
                    continue
                variant_context_sources[key] = str(source.snapshot / v.filename)
                detail = GgufVariantDetail(
                    filename = v.filename,
                    quant = v.quant,
                    display_label = v.display_label,
                    size_bytes = v.size_bytes,
                    download_size_bytes = v.size_bytes,
                    # A source its snapshot lists as incomplete is a resumable row, not a copy to load.
                    downloaded = not source.incomplete,
                    partial = source.incomplete,
                    cache_path = source.cache_path,
                    dependency_key = _variant_dependency_key(repo_id, v.filename),
                )
                if source.incomplete:
                    variant_context_sources.pop(key, None)
                if online_answer:
                    # Apply the same readiness and update checks as a request for this snapshot.
                    checked = _scoped_variant_row(source.snapshot, key)
                    if checked is not None:
                        detail = checked.model_copy(update = {"cache_path": source.cache_path})
                        if detail.downloaded:
                            detail.filename = v.filename
                            detail.size_bytes = v.size_bytes
                        else:
                            variant_context_sources.pop(key, None)
                    elif cached_gguf_source_partial(repo_id, v.quant, source.snapshot):
                        # The current revision no longer covers this quant; only the copy's manifest and marker can judge it.
                        variant_context_sources.pop(key, None)
                        detail.downloaded = False
                        detail.partial = True
                elif cached_gguf_source_partial(repo_id, v.quant, source.snapshot):
                    # Local twin of the Hub check: an incomplete remembered copy must not be offered to load.
                    variant_context_sources.pop(key, None)
                    detail.downloaded = False
                    detail.partial = True
                if detail.partial:
                    # Downloads land in the ACTIVE cache, so resume metadata comes from the active copy only.
                    # -- that is what delete and load resolve -- while the resume affordance
                    resume_cache_dir = (
                        Path(source.cache_path)
                        if source.cache_path == str(active_repo_dir)
                        else active_repo_dir
                    )
                    detail = detail.model_copy(
                        update = {
                            "download_remaining_bytes": variant_remaining_bytes_from_state(
                                repo_id, v.quant, resume_cache_dir
                            ),
                            "partial_transport": _partial_transport_for_variant(
                                repo_id, v.quant, resume_cache_dir
                            ),
                            "partial_resumable": _partial_resumable_for_variant(
                                repo_id, v.quant, resume_cache_dir
                            ),
                        }
                    )
                variants[key] = detail
            response.variants = list(variants.values())
            response.has_vision = response.has_vision or any(s.has_vision for s in sources.values())
            # merged sources require a new default that prefers ready rows
            if sources or not response.default_variant:
                ready = [v for v in response.variants if v.downloaded and not v.partial]
                response.default_variant = _default_variant_key(ready or response.variants, repo_id)
        if response.dependencies_resolved and locally_proven[0] is not None:
            rows = frozenset(
                (v.quant.lower(), v.filename)
                for v in response.variants
                if v.downloaded and v.quant and v.filename
            )
            if rows != locally_proven[0] or any(
                v.partial for v in response.variants if v.downloaded
            ):
                response = response.model_copy(update = {"dependencies_resolved": False})
        if skip or answered_locally[0]:
            return response
        return _mark_empty_dir_cleanables(
            repo_id, response, _repo_cache_dir_for_request(repo_id, local_path)
        )

    from utils.hf_cache_settings import configured_cache_key

    inflight_key = (
        repo_id,
        bool(prefer_local_cache),
        bool(offline),
        bool(include_cache_locations),
        local_path or "",
        hf_cache_scan.token_fingerprint(hf_token),
        # Switching cache storage must start a fresh scan rather than join one that is stuck on the old volume.
        configured_cache_key(),
    )
    try:
        answer = await _shared_variants_scan(
            inflight_key, _compute_with_cleanables, offline = bool(offline)
        )
        # Only after an empty GGUF listing, so GGUF answers never change.
        if not answer.response.variants and not local_path:
            mlx_answer = await _mlx_precision_variants_answer(
                repo_id,
                hf_token,
                offline,
                cache_readable = answer.cache_authorized,
                info = hub_model_info[-1] if hub_model_info and not offline else None,
            )
            if mlx_answer is not None:
                return mlx_answer
        return await _with_lookup_tables(
            answer,
            repo_id,
            hf_token = hf_token,
            offline = bool(offline),
            prefer_local_cache = bool(prefer_local_cache),
            local_path = local_path,
        )
    except HTTPException as exc:
        # Offline, a repo with no cached GGUF raises here, before the MLX fallback above.
        if (
            offline
            and exc.status_code == 404
            and not local_path
            and not hub_cached_read_refused(
                hf_token, repo_id = repo_id, is_cached = lambda: True, offline = True
            )
        ):
            mlx_answer = await _mlx_precision_variants_answer(repo_id, hf_token, True)
            if mlx_answer is not None:
                return mlx_answer
        raise
    except Exception as e:
        scrubbed = modelscope_missing(e) or download_registry.scrub_secrets(
            str(e), hf_token = hf_token
        )
        # Client-side HF error (missing repo, gated, bad token): pass the status through.
        status = hf_error_status(e)
        if status is not None:
            raise HTTPException(status_code = status, detail = scrubbed)
        logger.error("Error listing GGUF variants for %s: %s", repo_id, scrubbed)
        raise HTTPException(
            status_code = 500,
            detail = "Failed to list GGUF variants: " + scrubbed,
        )


async def get_gguf_variants_response(
    repo_id: str,
    prefer_local_cache: bool = False,
    offline: bool = False,
    local_path: Optional[str] = None,
    hf_token: Optional[str] = None,
    include_cache_locations: bool = False,
) -> GgufVariantsResponse:
    """return the listing without same-copy metadata."""
    answer = await get_gguf_variants_answer(
        repo_id,
        prefer_local_cache = prefer_local_cache,
        offline = offline,
        local_path = local_path,
        hf_token = hf_token,
        include_cache_locations = include_cache_locations,
    )
    return answer.response


async def cached_gguf_variant_source_path(
    repo_id: str,
    variant: str,
    hf_token: Optional[str] = None,
) -> Optional[str]:
    """return the exact cached file selected after online readiness checks."""
    answer = await get_gguf_variants_answer(
        repo_id,
        hf_token = hf_token,
        include_cache_locations = True,
    )
    return (answer.variant_context_sources or {}).get((variant or "").strip().lower())