unsloth/studio/backend/utils/hf_cache_settings.py
Michael Han aa9ca85459
Fix model picker stuck on "Loading variants" (#7767)
* Fix model picker stuck on "Loading variants"

The chat picker's GGUF variant listing was issued with no abort signal, no
timeout and no offline handling, so a request that never came back left the
expander spinning forever with no quant to click. Chat auto-load awaits the
same call per repo, so a stall there blocks loading too. The Model hub was
unaffected because its own client bounds the identical listing.

- bound the chat-side listing to 30s and give it an abort signal, matching
  the Hub client
- forward offline/prefer_local_cache so an unreachable Hub answers from cache
- abort the request when the expander's row collapses
- surface a timeout with a Retry button instead of a permanent spinner
- accept offline on /api/models/gguf-variants, for parity with the Hub route
- bound the native context cache walk so slow disk work cannot hold the
  quant rows back

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Harden the fix against findings from cross-engine and backend simulations

Two real gaps found by simulating the change rather than only unit testing it.

WebKit rejects a timed-out fetch with AbortError, not TimeoutError. Measured in
Playwright across chromium, firefox and webkit, current and with
AbortSignal.timeout/any removed. WebKit is what the desktop app embeds on macOS
and Linux, so matching only TimeoutError left exactly the reporting platform on
the generic message. Classification now covers both names, reads them by
property since DOMException does not inherit from Error in older WebKit, and
moves to its own module so it is testable outside JSX.

The context-read budget did not bind on tree size. _iter_gguf_paths yields only
.gguf files, so a large cache walks a long time yielding nothing and a budget
checked per yield never ran. The walk now takes the deadline itself, and the
budget is checked between caches so a repo in several caches cannot restart it.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Address Codex review: bound the context read properly, and honour offline when picking the copy to read

Both P2 comments reproduce. Each fix has a regression test verified to fail
without it.

Cache discovery ran before the deadline existed, so a slow enumeration handed
the walk a full fresh budget on top of its own cost. The deadline is now taken
first.

A single syscall that never returns cannot be interrupted from inside the walk,
so the route now bounds the read and reports no context length rather than
holding the variant listing. The read moves to its own small pool, so a stranded
read cannot starve the shared executor the rest of the app uses.

offline alone makes the shared service local-only, but the route still picked
the context source on prefer_local_cache, so variants came from local_path while
the length was read from repo_id, reporting another copy's context or none. Both
flags now count.

* Address second Codex pass: bound the whole listing, and un-vacuum the walk test

Both comments reproduce.

The dragging-walk test stopped exercising anything once production started
calling _iter_gguf_paths(root, deadline): the stub took only root, the TypeError
was swallowed by the broad handler, and the test passed in 0.000s having walked
nothing. Measured, then fixed, with an assertion that the walk ran so signature
drift cannot make it vacuous again.

Handing the signal to fetch left a hole: on a 401 authFetch awaits a shared
session refresh whose own fetch carries no signal, so the listing could still
hang there. The listing now settles on the bound whatever the request is doing.
Verified against the previous shape, which stays pending forever where this
rejects.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Do not let the bounded context read hang shutdown or drop lengths under load

Self-review of the previous commit, which nobody had reviewed yet. Two problems
with the dedicated thread pool it introduced, both measured.

A pool's workers are non-daemon and are joined at interpreter exit, so a read
abandoned on a hung mount held up process exit for the full length of the read:
measured 20s for a 20s read. The read now runs on a daemon thread, and exit
takes 1s with four reads still stranded.

Capping concurrency with a non-blocking acquire dropped most context lengths
whenever reads overlapped at all: on a healthy cache, 4 of 64 concurrent reads
kept theirs. The wait for a slot is now awaited rather than skipped, sharing one
budget with the read, so 200 concurrent reads all keep their length in 0.2s
while a hung mount still gives up inside the bound and starts no extra threads.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Coalesce identical variant scans so retries cannot pile up on the executor

Aborting the HTTP request cannot stop the scan already running in its thread, so
the Retry button this PR adds, and reopening a row, each started another against
a filesystem that was not answering. Measured against a wedged scan: 23 retries
created 20 threads, filling the whole default executor, after which unrelated
offloaded work no longer ran at all.

An identical request now joins the scan already in flight instead of starting
another. Same measurement afterwards: 1 thread, and unrelated offloaded work
runs immediately. Joining costs at most the running scan's own duration in
staleness, well inside the client's existing cache window.

The waiter is shielded, so one caller giving up leaves the scan for the others,
and a failed scan is not retained, so the next request tries again.

Note the scan itself is still unbounded, so one wedged scan still holds one
worker and delays exit. That is unchanged by this PR and wants its own fix.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Read the context length from the copy the listing actually answered from

The local-only path tries the HF cache before local_path, so picking the context
source from the request flags alone attached a length from one copy to variants
from another, or none at all. Selecting on offline made that reachable in a
second combination.

The service now reports the directory it answered from and the route follows it,
falling back to the pin and then the repo. Reported with the answer rather than
read afterwards, so coalesced callers all see the copy their listing came from.

get_gguf_variants_response keeps its shape for callers that only want the
listing. The route takes the new answer form, so a stub left on the old name
fails loudly instead of quietly not intercepting.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Scope the context read to the cache that answered, and rekey in-flight scans on cache storage

The cached-variants branch scopes its listing to the cache the request names, but
did not report which one, so the route fell back to a repo-wide walk that starts
at the active cache and could attach another copy's context length.

In-flight scan coalescing also keyed only on the request, so switching cache
storage joined a scan already stuck on the old volume instead of starting a
fresh one. The new key reads the configured location without resolving it,
since resolve() can block on that same volume.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: Unsloth <michaelhan@Michaels-MacBook-Pro.local>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Lee Jackson <130007945+Imagineer99@users.noreply.github.com>
2026-08-03 15:07:55 +01:00

408 lines
14 KiB
Python

# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
"""Live, persisted Hugging Face cache routing for Unsloth Studio.
Hugging Face reads cache environment variables at import time. Studio therefore
owns an explicit cache snapshot for each operation instead of trying to refresh
``huggingface_hub.constants`` in the long-running API process.
"""
from __future__ import annotations
import os
import shutil
import tempfile
import threading
from contextlib import contextmanager
from dataclasses import dataclass
from pathlib import Path
from typing import Iterator, Literal, Mapping, Optional
CACHE_HOME_SETTING_KEY = "hugging_face_cache_home"
CACHE_HISTORY_SETTING_KEY = "hugging_face_cache_history"
MAX_CACHE_HISTORY = 16
CacheSource = Literal["default", "studio", "environment"]
_CACHE_ENV_KEYS = (
"HF_HOME",
"HF_HUB_CACHE",
"HUGGINGFACE_HUB_CACHE",
"HF_XET_CACHE",
)
# Imported by storage_roots._setup_cache_env before Studio seeds defaults.
_EXPLICIT_CACHE_ENV = {
key: value.strip()
for key in _CACHE_ENV_KEYS
if (value := os.environ.get(key)) is not None and value.strip()
}
_settings_lock = threading.RLock()
_spawn_env_lock = threading.RLock()
@dataclass(frozen = True)
class HuggingFaceCachePaths:
cache_home: Path
hub_cache: Path
xet_cache: Path
source: CacheSource
environment_variable: Optional[str] = None
@property
def editable(self) -> bool:
return self.source != "environment"
@property
def is_custom(self) -> bool:
return self.source == "studio"
def child_env(self, base: Optional[Mapping[str, str]] = None) -> dict[str, str]:
# Scrub either way: an explicit base is usually the caller's own os.environ
# copy, so it carries any scoped offline flags an open guard has set.
from utils.utils import hf_environment_for_spawn, hf_environment_scrubbed
env = hf_environment_for_spawn() if base is None else hf_environment_scrubbed(base)
# Do not rewrite HF_HOME. It also owns HF's token path, and credentials
# must not be moved onto a removable cache volume.
env["HF_HUB_CACHE"] = str(self.hub_cache)
env["HF_XET_CACHE"] = str(self.xet_cache)
env.pop("HUGGINGFACE_HUB_CACHE", None)
return env
def _default_cache_home() -> Path:
xdg = (os.environ.get("XDG_CACHE_HOME") or "").strip()
return (Path(xdg).expanduser() if xdg else Path.home() / ".cache") / "huggingface"
def _canonical(path: Path | str) -> Path:
return Path(path).expanduser().resolve(strict = False)
def _environment_paths() -> Optional[HuggingFaceCachePaths]:
explicit_home = _EXPLICIT_CACHE_ENV.get("HF_HOME")
explicit_hub = _EXPLICIT_CACHE_ENV.get("HF_HUB_CACHE") or _EXPLICIT_CACHE_ENV.get(
"HUGGINGFACE_HUB_CACHE"
)
if not explicit_home and not explicit_hub:
return None
explicit_xet = _EXPLICIT_CACHE_ENV.get("HF_XET_CACHE")
default_home = _default_cache_home()
hf_home = _canonical(explicit_home) if explicit_home else default_home
hub = _canonical(explicit_hub) if explicit_hub else hf_home / "hub"
xet = _canonical(explicit_xet) if explicit_xet else hf_home / "xet"
controlling = next(
key
for key in ("HF_HUB_CACHE", "HUGGINGFACE_HUB_CACHE", "HF_HOME")
if key in _EXPLICIT_CACHE_ENV
)
# Settings describes model downloads, so an explicit hub path is the
# displayed/opened location even when HF_HOME points somewhere else for
# credentials or XET data.
display_home = (
(hub.parent if explicit_hub and hub.name.lower() == "hub" else hub)
if explicit_hub
else hf_home
)
return HuggingFaceCachePaths(display_home, hub, xet, "environment", controlling)
def _stored_cache_home() -> Optional[Path]:
try:
from storage.studio_db import get_app_setting
value = get_app_setting(CACHE_HOME_SETTING_KEY, None)
except Exception:
return None
if not isinstance(value, str) or not value.strip():
return None
try:
return _canonical(value.strip())
except (OSError, RuntimeError, ValueError):
return None
def configured_cache_key() -> str:
"""The configured cache location, for keying caches and in-flight work.
Deliberately unresolved: resolve() can block on the very volume a caller is
trying to move off. Only equality matters here, not the real path.
"""
explicit = (
_EXPLICIT_CACHE_ENV.get("HF_HUB_CACHE")
or _EXPLICIT_CACHE_ENV.get("HUGGINGFACE_HUB_CACHE")
or _EXPLICIT_CACHE_ENV.get("HF_HOME")
)
if explicit:
return "env:" + explicit
try:
from storage.studio_db import get_app_setting
value = get_app_setting(CACHE_HOME_SETTING_KEY, None)
except Exception:
return "default"
if isinstance(value, str) and value.strip():
return "studio:" + value.strip()
return "default"
def get_hf_cache_paths() -> HuggingFaceCachePaths:
env_paths = _environment_paths()
if env_paths is not None:
return env_paths
stored = _stored_cache_home()
if stored is not None:
xet = _EXPLICIT_CACHE_ENV.get("HF_XET_CACHE")
return HuggingFaceCachePaths(
stored,
stored / "hub",
_canonical(xet) if xet else stored / "xet",
"studio",
)
home = _default_cache_home()
xet = _EXPLICIT_CACHE_ENV.get("HF_XET_CACHE")
return HuggingFaceCachePaths(
home,
home / "hub",
_canonical(xet) if xet else home / "xet",
"default",
)
def active_hf_hub_cache() -> str:
"""Return the current hub cache as a string for library call kwargs."""
return str(get_hf_cache_paths().hub_cache)
@contextmanager
def _xet_loader_barrier() -> Iterator[None]:
"""Block while a Xet shim loader holds its process-wide env override. Never fails a spawn."""
try:
from utils.hf_xet_fallback import env_override_barrier
barrier = env_override_barrier()
except Exception: # noqa: BLE001 - the shim is optional; a spawn must never depend on it
yield
return
with barrier:
yield
@contextmanager
def child_environment_for_spawn(environment: Mapping[str, str]) -> Iterator[None]:
"""Apply captured env before spawn imports the child entrypoint.
Applying variables only inside the multiprocessing target can be too late
for libraries that snapshot environment variables at import. The lock keeps
this short parent-process override atomic through ``Process.start()``.
"""
from utils.utils import hf_environment_restored_for_spawn
# Also exclude the Xet shim's GPU-init override window: a child spawned inside it inherits the
# flag for life, whereupon unsloth_zoo hands it STUB triton and bitsandbytes and the run
# silently produces nothing. Filtering a child env dict cannot help here, since spawn copies the
# live environment and takes no env argument.
with _spawn_env_lock, _xet_loader_barrier(), hf_environment_restored_for_spawn():
missing = object()
saved_environment: dict[str, str | object] = {}
for key, value in environment.items():
saved_environment[key] = os.environ.get(key, missing)
os.environ[key] = value
try:
yield
finally:
for key, previous in saved_environment.items():
if previous is missing:
os.environ.pop(key, None)
else:
os.environ[key] = str(previous)
def initialize_hf_cache_environment() -> HuggingFaceCachePaths:
"""Seed import-time HF variables once during backend startup."""
paths = get_hf_cache_paths()
# Preserve an explicit HF_HOME, otherwise keep credentials at the platform
# default while routing cache bytes through the selected home.
if not os.environ.get("HF_HOME", "").strip():
os.environ["HF_HOME"] = str(_default_cache_home())
os.environ["HF_HUB_CACHE"] = str(paths.hub_cache)
os.environ["HF_XET_CACHE"] = str(paths.xet_cache)
if "HUGGINGFACE_HUB_CACHE" not in _EXPLICIT_CACHE_ENV:
os.environ.pop("HUGGINGFACE_HUB_CACHE", None)
for directory in (paths.hub_cache, paths.xet_cache):
try:
directory.mkdir(parents = True, exist_ok = True)
except OSError:
pass
return paths
def _validate_cache_home(raw_path: str) -> Path:
value = raw_path.strip()
if not value:
raise ValueError("Choose a cache folder.")
candidate = Path(value).expanduser()
if not candidate.is_absolute():
raise ValueError("The Hugging Face cache folder must be an absolute path.")
try:
resolved = candidate.resolve(strict = False)
except (OSError, RuntimeError, ValueError) as exc:
raise ValueError("The Hugging Face cache folder is invalid.") from exc
if resolved.parent == resolved:
raise ValueError("Choose a folder inside the filesystem or drive root.")
try:
from hub.storage.scan_folders import (
contains_sensitive_path_component,
is_denied_system_path,
)
except ImportError:
contains_sensitive_path_component = is_denied_system_path = None
if is_denied_system_path is not None and is_denied_system_path(str(resolved)):
raise ValueError("System folders cannot be used for model downloads.")
if contains_sensitive_path_component is not None and contains_sensitive_path_component(
str(resolved)
):
raise ValueError("Credential or config folders cannot be used for model downloads.")
parent = resolved.parent
if not parent.exists() or not parent.is_dir():
raise ValueError("The parent folder does not exist.")
try:
resolved.mkdir(exist_ok = True)
if not resolved.is_dir():
raise ValueError("The selected cache location is not a folder.")
for child in (resolved / "hub", resolved / "xet"):
child.mkdir(exist_ok = True)
with tempfile.NamedTemporaryFile(prefix = ".unsloth-write-test-", dir = child):
pass
except PermissionError as exc:
raise ValueError("Studio does not have permission to write to this folder.") from exc
except OSError as exc:
raise ValueError(f"Studio cannot use this cache folder: {exc}") from exc
return resolved
def _stored_history() -> list[Path]:
try:
from storage.studio_db import get_app_setting
raw = get_app_setting(CACHE_HISTORY_SETTING_KEY, [])
except Exception:
raw = []
if not isinstance(raw, list):
return []
out: list[Path] = []
seen: set[str] = set()
for value in raw:
if not isinstance(value, str) or not value.strip():
continue
try:
path = _canonical(value)
except (OSError, RuntimeError, ValueError):
continue
key = os.path.normcase(str(path))
if key in seen:
continue
seen.add(key)
out.append(path)
return out[:MAX_CACHE_HISTORY]
def set_hf_cache_home(cache_home: Optional[str]) -> HuggingFaceCachePaths:
if _environment_paths() is not None:
raise RuntimeError("The Hugging Face cache location is managed by an environment variable.")
with _settings_lock:
previous = _stored_cache_home()
next_home = _validate_cache_home(cache_home) if cache_home is not None else None
history = _stored_history()
if previous is not None and previous != next_home:
history.insert(0, previous)
deduped: list[str] = []
seen: set[str] = set()
for path in history:
key = os.path.normcase(str(path))
if key in seen or path == next_home:
continue
seen.add(key)
deduped.append(str(path))
if len(deduped) >= MAX_CACHE_HISTORY:
break
from storage.studio_db import upsert_app_settings
upsert_app_settings(
{
CACHE_HOME_SETTING_KEY: str(next_home) if next_home is not None else None,
CACHE_HISTORY_SETTING_KEY: deduped,
}
)
# Inventory scans are cached independently from settings. Invalidate after
# persistence so the next request sees both the new active root and history.
from hub.utils.inventory_scan import invalidate_hf_cache_scans
invalidate_hf_cache_scans()
return get_hf_cache_paths()
def known_hf_cache_homes() -> list[Path]:
paths = get_hf_cache_paths()
stored = _stored_cache_home()
candidates: list[Path] = []
if paths.source != "environment":
candidates.append(paths.cache_home)
elif explicit_home := _EXPLICIT_CACHE_ENV.get("HF_HOME"):
candidates.append(_canonical(explicit_home))
if stored is not None:
candidates.append(stored)
candidates.extend([*_stored_history(), _default_cache_home()])
out: list[Path] = []
seen: set[str] = set()
for candidate in candidates:
try:
canonical = _canonical(candidate)
except (OSError, RuntimeError, ValueError):
continue
key = os.path.normcase(str(canonical))
if key in seen:
continue
seen.add(key)
out.append(canonical)
return out
def known_hf_hub_caches() -> list[Path]:
active = get_hf_cache_paths()
out = [active.hub_cache]
seen = {os.path.normcase(str(_canonical(active.hub_cache)))}
for home in known_hf_cache_homes():
hub = _canonical(home / "hub")
key = os.path.normcase(str(hub))
if key not in seen:
seen.add(key)
out.append(hub)
return out
def cache_status(paths: Optional[HuggingFaceCachePaths] = None) -> dict:
paths = paths or get_hf_cache_paths()
available = paths.cache_home.is_dir()
writable = available and os.access(paths.cache_home, os.W_OK | os.X_OK)
free_bytes: Optional[int] = None
if available:
try:
free_bytes = int(shutil.disk_usage(paths.cache_home).free)
except OSError:
pass
return {
"cache_home": str(paths.cache_home),
"hub_cache": str(paths.hub_cache),
"xet_cache": str(paths.xet_cache),
"source": paths.source,
"editable": paths.editable,
"is_custom": paths.is_custom,
"available": available,
"writable": writable,
"free_bytes": free_bytes,
"environment_variable": paths.environment_variable,
}