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.

Studio: fix STT download progress and cache safety (#8035)

oobabooga3654a75b5e3a
diff --git a/studio/backend/core/inference/stt_download_worker.py b/studio/backend/core/inference/stt_download_worker.py
index 9555c319059..cf35d374e2f 100644
--- a/studio/backend/core/inference/stt_download_worker.py
+++ b/studio/backend/core/inference/stt_download_worker.py
@@ -16,15 +16,26 @@ import argparse
import os
import subprocess
import sys
+import threading
+import time
from pathlib import Path
from typing import Optional, Sequence
+# How long a cancelled worker gets to exit on SIGTERM before it is killed.
+TERMINATE_GRACE_SECONDS = 15.0
+
+
def backend_dir() -> Path:
return Path(__file__).resolve().parent.parent.parent
-def spawn_download(args: Sequence[str], hf_token: Optional[str] = None) -> subprocess.Popen:
+def spawn_download(
+ args: Sequence[str],
+ hf_token: Optional[str] = None,
+ *,
+ hub_cache: Optional[Path] = None,
+) -> subprocess.Popen:
"""Run this module as a child process performing ``args``' download.
The token travels in the environment, never argv, so it stays out of ``ps``.
@@ -33,8 +44,12 @@ def spawn_download(args: Sequence[str], hf_token: Optional[str] = None) -> subpr
from utils.hf_cache_settings import get_hf_cache_paths
env = get_hf_cache_paths().child_env()
+ if hub_cache is not None:
+ env["HF_HUB_CACHE"] = str(hub_cache)
env["HF_HUB_DISABLE_PROGRESS_BARS"] = "1"
env["HF_HUB_DISABLE_TELEMETRY"] = "1"
+ # Xet's out-of-order chunks do not provide steady partial-file progress.
+ env["HF_HUB_DISABLE_XET"] = "1"
# Parallel Range chunks leave sparse partials a resumed sequential writer
# cannot reuse, which defeats the point of cancelling.
env["HF_HUB_ENABLE_HF_TRANSFER"] = "0"
@@ -70,6 +85,29 @@ def spawn_download(args: Sequence[str], hf_token: Optional[str] = None) -> subpr
return process
+def terminate_download(process: subprocess.Popen) -> None:
+ """SIGTERM now, SIGKILL after a grace, so cancel() still returns at once.
+
+ The canceller holds the repository reservation until the reap returns, so a
+ worker that ignores SIGTERM would lock every Model Hub write on that repo
+ until Studio restarts.
+ """
+ try:
+ process.terminate()
+ except Exception: # noqa: BLE001
+ return
+
+ def escalate() -> None:
+ time.sleep(TERMINATE_GRACE_SECONDS)
+ try:
+ if process.poll() is None:
+ process.kill()
+ except Exception: # noqa: BLE001
+ pass
+
+ threading.Thread(target = escalate, daemon = True).start()
+
+
def reap_download(process: subprocess.Popen) -> bytes:
"""Wait for a worker and drop its PID. Returns its stderr.
@@ -82,39 +120,30 @@ def reap_download(process: subprocess.Popen) -> bytes:
try:
_, stderr = process.communicate()
finally:
- forget_pid(process.pid)
+ pid = getattr(process, "pid", None)
+ if isinstance(pid, int):
+ forget_pid(pid)
return stderr or b""
def main(argv: Optional[Sequence[str]] = None) -> int:
parser = argparse.ArgumentParser(description = "Download one dictation model.")
parser.add_argument("--repo-id", required = True)
- # GGML is a single file; Transformers is a snapshot pinned to the revision
- # the sidecar already validated.
- parser.add_argument("--filename")
+ # Explicit filenames prevent repository patterns from widening the download.
+ parser.add_argument("--filename", action = "append", required = True)
parser.add_argument("--revision")
- parser.add_argument("--allow-pattern", action = "append", default = [])
args = parser.parse_args(argv)
token = os.environ.get("HF_TOKEN") or None
- if args.filename:
- from huggingface_hub import hf_hub_download
+ from huggingface_hub import hf_hub_download
+
+ for filename in args.filename:
hf_hub_download(
repo_id = args.repo_id,
- filename = args.filename,
+ filename = filename,
revision = args.revision,
token = token,
)
- return 0
-
- from huggingface_hub import snapshot_download
-
- snapshot_download(
- repo_id = args.repo_id,
- revision = args.revision,
- allow_patterns = list(args.allow_pattern) or None,
- token = token,
- )
return 0
diff --git a/studio/backend/core/inference/stt_ggml_sidecar.py b/studio/backend/core/inference/stt_ggml_sidecar.py
index 0d3a7bfb609..7dfa8c54358 100644
--- a/studio/backend/core/inference/stt_ggml_sidecar.py
+++ b/studio/backend/core/inference/stt_ggml_sidecar.py
@@ -50,10 +50,18 @@ from core.inference.stt_sidecar import (
SttModelIdError,
SttModelNotDownloadedError,
SttUnavailableError,
+ _capture_stt_hub_cache,
+ _claim_stt_repository,
_decode_audio_bounded,
+ _downloaded_file_bytes,
+ _fallback_revisions,
+ _HF_COMMIT_SHA,
_known_whisper_languages,
+ _prepare_stt_cache_for_http,
+ _read_revision_record,
_TARGET_SAMPLE_RATE,
_training_active,
+ _write_revision_record,
normalize_whisper_language,
)
from utils.prebuilt.child_env import isolate_home, scrub_env, wsl_system_rocm_lib_dirs
@@ -339,23 +347,48 @@ def _whisper_server_child_env(binary: str) -> dict[str, str]:
# ---------------------------------------------------------------------------
-def _cached_model_path(model_id: str) -> Optional[str]:
+def _cached_model_path(
+ model_id: str,
+ *,
+ hub_cache: Optional[Path] = None,
+ revision: Optional[str] = None,
+) -> Optional[str]:
"""Path of a fully downloaded GGML file in the shared HF cache, else None."""
from huggingface_hub import hf_hub_download
from core.inference.stt_sidecar import _active_hf_hub_cache
- try:
- return hf_hub_download(
- repo_id = GGML_STT_REPOS[model_id],
- filename = GGML_STT_MODELS[model_id],
- local_files_only = True,
- # The worker spawns with get_hf_cache_paths(), so a cache relocated
- # in Studio settings is written there and has to be read there too.
- cache_dir = str(_active_hf_hub_cache()),
- )
- except Exception:
- return None
+ repo_id = GGML_STT_REPOS[model_id]
+ root = hub_cache if hub_cache is not None else _active_hf_hub_cache()
+
+ def cached_at(candidate_revision: str) -> Optional[str]:
+ try:
+ return hf_hub_download(
+ repo_id = repo_id,
+ filename = GGML_STT_MODELS[model_id],
+ revision = candidate_revision,
+ local_files_only = True,
+ cache_dir = str(root),
+ )
+ except Exception:
+ return None
+
+ # Explicit revisions keep verification on the downloaded commit.
+ if revision is not None:
+ return cached_at(revision)
+
+ recorded = _read_revision_record(repo_id)
+ if recorded:
+ cached = cached_at(recorded)
+ if cached is not None:
+ return cached
+
+ for candidate in _fallback_revisions(repo_id, hub_cache = root):
+ cached = cached_at(candidate)
+ if cached is not None:
+ _write_revision_record(repo_id, candidate)
+ return cached
+ return None
class _GgmlDownloadState:
@@ -369,19 +402,30 @@ class _GgmlDownloadState:
self._error: Optional[str] = None
self._total_bytes: Optional[int] = None
self._etag: Optional[str] = None
+ self._revision: Optional[str] = None
+ self._hub_cache: Optional[Path] = None
self._cancelled = False
def status(self) -> dict:
with self._lock:
downloading = self._thread is not None and self._thread.is_alive()
- return {
+ snapshot = {
"downloading": downloading,
"model": self._model_id if downloading else None,
"error": self._error,
"cancelled": self._cancelled,
"bytes_total": self._total_bytes if downloading else None,
- "bytes_done": self._incomplete_bytes() if downloading else None,
}
+ captured = (
+ self._model_id,
+ self._etag,
+ self._total_bytes,
+ self._hub_cache,
+ self._revision,
+ )
+ # Outside the lock: _downloaded_bytes() stats the cache, and a cancel must not queue.
+ snapshot["bytes_done"] = self._downloaded_bytes(*captured) if downloading else None
+ return snapshot
def cancel(self) -> bool:
"""Stop an in-flight download. False when none was running.
@@ -394,34 +438,40 @@ class _GgmlDownloadState:
self._cancelled = True
process = self._process
if process is not None and process.poll() is None:
- process.terminate()
+ from core.inference.stt_download_worker import terminate_download
+ terminate_download(process)
return True
- def _incomplete_bytes(self) -> Optional[int]:
- """Best-effort progress: size of the in-flight blob in the HF cache.
-
- hf_hub_download writes ``blobs/<etag>.incomplete``; prefer this file's
- etag, else the largest in-flight blob.
+ def _downloaded_bytes(
+ self,
+ model_id: Optional[str] = None,
+ etag: Optional[str] = None,
+ total: Optional[int] = None,
+ hub_cache: Optional[Path] = None,
+ revision: Optional[str] = None,
+ ) -> Optional[int]:
+ """Count this file across partial, finalized, and snapshot locations.
+
+ status() captures these under the lock and passes them in: reading them
+ here would let a run that starts mid-probe pair its bytes with the total
+ of the run that just ended.
"""
try:
- from core.inference.stt_sidecar import _repo_cache_dir
-
- # Caller may hold the non-reentrant self._lock; bare reads are safe.
- model_id = self._model_id
- if not model_id:
+ model_id = model_id if model_id is not None else self._model_id
+ etag = etag if etag is not None else self._etag
+ total = total if total is not None else self._total_bytes
+ hub_cache = hub_cache if hub_cache is not None else self._hub_cache
+ revision = revision if revision is not None else self._revision
+ if not model_id or not etag or total is None or hub_cache is None:
return None
- # The active cache, not the import-time constant: the worker writes
- # to whichever one Studio settings point at.
- repo_dir = _repo_cache_dir(GGML_STT_REPOS[model_id]) / "blobs"
- if not repo_dir.is_dir():
- return None
- etag = self._etag
- if etag:
- target = repo_dir / f"{etag}.incomplete"
- if target.is_file():
- return target.stat().st_size
- sizes = [p.stat().st_size for p in repo_dir.glob("*.incomplete") if p.is_file()]
- return max(sizes) if sizes else None
+ return _downloaded_file_bytes(
+ hub_cache = hub_cache,
+ repo = GGML_STT_REPOS[model_id],
+ filename = GGML_STT_MODELS[model_id],
+ size = total,
+ blob_key = etag,
+ revision = revision,
+ )
except Exception:
return None
@@ -431,10 +481,16 @@ class _GgmlDownloadState:
hf_token: Optional[str] = None,
) -> None:
model_id = resolve_ggml_model_id(model_id)
+ hub_cache = _capture_stt_hub_cache()
with self._lock:
if self._thread is not None and self._thread.is_alive():
if self._model_id == model_id:
- return
+ # Joining a cancelling run would silently download nothing.
+ if not self._cancelled:
+ return
+ raise SttModelIdError(
+ f"'{model_id}' is still cancelling; try again in a moment."
+ )
raise SttModelIdError(
f"Another GGUF dictation model ('{self._model_id}') is still "
"downloading; wait for it to finish."
@@ -443,46 +499,108 @@ class _GgmlDownloadState:
self._error = None
self._total_bytes = None
self._etag = None
+ self._revision = None
+ self._hub_cache = hub_cache
self._cancelled = False
self._process = None
- thread = threading.Thread(target = self._run, args = (model_id, hf_token), daemon = True)
+ thread = threading.Thread(
+ target = self._run,
+ args = (model_id, hf_token),
+ daemon = True,
+ )
self._thread = thread
thread.start()
- def _run(self, model_id: str, hf_token: Optional[str]) -> None:
+ def _run(
+ self,
+ model_id: str,
+ hf_token: Optional[str],
+ hub_cache: Optional[Path] = None,
+ ) -> None:
+ if hub_cache is None:
+ from core.inference.stt_sidecar import _active_hf_hub_cache
+ hub_cache = self._hub_cache or _active_hf_hub_cache()
repo_id = GGML_STT_REPOS[model_id]
filename = GGML_STT_MODELS[model_id]
+ registry = None
+ owner = None
try:
from huggingface_hub import get_hf_file_metadata, hf_hub_url
try:
- # One HEAD request for the total and etag.
meta = get_hf_file_metadata(hf_hub_url(repo_id, filename), token = hf_token or None)
- with self._lock:
- self._total_bytes = meta.size
- self._etag = meta.etag
- except Exception:
- pass
+ total_bytes = int(meta.size or 0)
+ except (AttributeError, TypeError, ValueError) as exc:
+ raise RuntimeError("could not resolve GGML download metadata") from exc
+ revision = meta.commit_hash
+ etag = meta.etag
+ if not isinstance(revision, str) or not _HF_COMMIT_SHA.fullmatch(revision):
+ raise RuntimeError("could not resolve an immutable GGML revision")
+ if not isinstance(etag, str) or not etag:
+ raise RuntimeError("could not resolve the GGML blob identity")
+ if total_bytes <= 0:
+ raise RuntimeError("could not resolve the GGML file size")
+ # A cancel during metadata has no child to stop. Without these the
+ # run still reserves the repo and rewrites the cache after the stop.
+ with self._lock:
+ if self._cancelled:
+ return
+ registry, owner = _claim_stt_repository(repo_id)
+ with self._lock:
+ if self._cancelled:
+ return
+ _prepare_stt_cache_for_http(repo_id, hub_cache)
+ with self._lock:
+ self._total_bytes = total_bytes
+ self._etag = etag
+ self._revision = revision
# Out of process so cancel() can terminate it; a thread blocked in
# hf_hub_download could not be interrupted.
- from core.inference.stt_download_worker import reap_download, spawn_download
+ from core.inference.stt_download_worker import (
+ reap_download,
+ spawn_download,
+ terminate_download,
+ )
+ args = [
+ "--repo-id",
+ repo_id,
+ "--revision",
+ revision,
+ "--filename",
+ filename,
+ ]
process = spawn_download(
- ["--repo-id", repo_id, "--filename", filename],
+ args,
hf_token = hf_token or None,
+ hub_cache = hub_cache,
)
with self._lock:
if self._cancelled:
# cancel() landed between start() and the spawn.
- process.terminate()
+ terminate_download(process)
self._process = process
# reap_download(), not communicate(): only it drops the adopted PID,
# which could otherwise be reused and then signalled by terminate_all.
stderr = reap_download(process)
- if process.returncode == 0:
+ with self._lock:
+ if self._process is process:
+ self._process = None
+ cancelled = self._cancelled
+ if process.returncode == 0 and not cancelled:
+ if (
+ _cached_model_path(
+ model_id,
+ hub_cache = hub_cache,
+ revision = revision,
+ )
+ is None
+ ):
+ raise RuntimeError("downloaded file is missing from the captured cache")
+ _write_revision_record(repo_id, revision)
return
with self._lock:
- if self._cancelled or process.returncode < 0:
+ if cancelled or process.returncode < 0:
self._cancelled = True
return
detail = (stderr or b"").decode("utf-8", "replace").strip()
@@ -490,9 +608,13 @@ class _GgmlDownloadState:
with self._lock:
self._error = f"Download failed for '{model_id}'."
except Exception as exc:
- logger.warning("GGUF STT download failed for %s: %s", model_id, exc)
with self._lock:
- self._error = f"Download failed for '{model_id}'."
+ if not self._cancelled:
+ logger.warning("GGUF STT download failed for %s: %s", model_id, exc)
+ self._error = f"Download failed for '{model_id}'."
+ finally:
+ if registry is not None and owner is not None:
+ registry.release_repository_owner(repo_id, owner)
_download_state = _GgmlDownloadState()
diff --git a/studio/backend/core/inference/stt_mtmd_sidecar.py b/studio/backend/core/inference/stt_mtmd_sidecar.py
index 3184ddd7afc..8dda0438b85 100644
--- a/studio/backend/core/inference/stt_mtmd_sidecar.py
+++ b/studio/backend/core/inference/stt_mtmd_sidecar.py
@@ -38,9 +38,18 @@ from core.inference.stt_sidecar import (
SttModelIdError,
SttModelNotDownloadedError,
SttUnavailableError,
+ _SelectedHubFile,
+ _capture_stt_hub_cache,
+ _claim_stt_repository,
_decode_audio_bounded,
+ _downloaded_file_bytes,
+ _fallback_revisions,
+ _HF_COMMIT_SHA,
+ _prepare_stt_cache_for_http,
+ _read_revision_record,
_TARGET_SAMPLE_RATE,
_training_active,
+ _write_revision_record,
normalize_whisper_language,
)
@@ -174,42 +183,75 @@ def _reap(process: Optional[subprocess.Popen]) -> None:
forget_pid(process.pid)
-def _cached_main_revision(repo: str) -> Optional[str]:
- """The commit `main` currently points at in the cache, if it is recorded."""
- from core.inference.stt_sidecar import _repo_cache_dir
-
- try:
- revision = (_repo_cache_dir(repo) / "refs" / "main").read_text(encoding = "utf-8").strip()
- except OSError:
- return None
- return revision or None
-
-
-def _cached_file(model_id: str, filename: str) -> Optional[str]:
+def _cached_file(
+ model_id: str,
+ filename: str,
+ *,
+ hub_cache: Optional[Path] = None,
+ revision: Optional[str] = None,
+) -> Optional[str]:
from huggingface_hub import hf_hub_download
from core.inference.stt_sidecar import _active_hf_hub_cache
+
+ root = hub_cache if hub_cache is not None else _active_hf_hub_cache()
try:
return hf_hub_download(
repo_id = MTMD_STT_MODELS[model_id].repo,
filename = filename,
+ revision = revision,
local_files_only = True,
- # The worker spawns with get_hf_cache_paths(), so a cache relocated
- # in Studio settings is written there and has to be read there too.
- cache_dir = str(_active_hf_hub_cache()),
+ cache_dir = str(root),
)
except Exception:
return None
-def _cached_model_paths(model_id: str) -> Optional[tuple[str, str]]:
+def _cached_model_paths(
+ model_id: str,
+ *,
+ hub_cache: Optional[Path] = None,
+ revision: Optional[str] = None,
+) -> Optional[tuple[str, str]]:
"""Both cached files, or None when either is missing."""
spec = MTMD_STT_MODELS[model_id]
- model = _cached_file(model_id, spec.model_file)
- mmproj = _cached_file(model_id, spec.mmproj_file)
- if model is None or mmproj is None:
- return None
- return model, mmproj
+ from core.inference.stt_sidecar import _active_hf_hub_cache
+
+ root = hub_cache if hub_cache is not None else _active_hf_hub_cache()
+
+ def cached_at(candidate_revision: str) -> Optional[tuple[str, str]]:
+ model = _cached_file(
+ model_id,
+ spec.model_file,
+ hub_cache = root,
+ revision = candidate_revision,
+ )
+ mmproj = _cached_file(
+ model_id,
+ spec.mmproj_file,
+ hub_cache = root,
+ revision = candidate_revision,
+ )
+ if model is None or mmproj is None:
+ return None
+ return model, mmproj
+
+ # Explicit revisions keep both files on the downloaded commit.
+ if revision is not None:
+ return cached_at(revision)
+
+ recorded = _read_revision_record(spec.repo)
+ if recorded:
+ cached = cached_at(recorded)
+ if cached is not None:
+ return cached
+
+ for candidate in _fallback_revisions(spec.repo, hub_cache = root):
+ cached = cached_at(candidate)
+ if cached is not None:
+ _write_revision_record(spec.repo, candidate)
+ return cached
+ return None
# The panel polls every model every 750ms, and each answer is two hf_hub_download()
@@ -258,6 +300,9 @@ class _MtmdDownloadState:
self._model_id: Optional[str] = None
self._error: Optional[str] = None
self._total_bytes: Optional[int] = None
+ self._selected_files: tuple[_SelectedHubFile, ...] = ()
+ self._revision: Optional[str] = None
+ self._hub_cache: Optional[Path] = None
self._cancelled = False
def status(self) -> dict:
@@ -271,8 +316,15 @@ class _MtmdDownloadState:
"cancelled": self._cancelled,
"bytes_total": self._total_bytes if downloading else None,
}
- # Outside the lock: _cache_bytes() walks the cache blobs, and a cancel must not queue.
- snapshot["bytes_done"] = self._cache_bytes(model_id) if downloading else None
+ captured = (
+ model_id,
+ self._hub_cache,
+ self._selected_files,
+ self._revision,
+ self._total_bytes,
+ )
+ # Outside the lock: _downloaded_bytes() stats the cache, and a cancel must not queue.
+ snapshot["bytes_done"] = self._downloaded_bytes(*captured) if downloading else None
return snapshot
def cancel(self) -> bool:
@@ -283,21 +335,45 @@ class _MtmdDownloadState:
self._cancelled = True
process = self._process
if process is not None and process.poll() is None:
- process.terminate()
+ from core.inference.stt_download_worker import terminate_download
+ terminate_download(process)
return True
- def _cache_bytes(self, model_id: Optional[str] = None) -> Optional[int]:
- """Best-effort progress: cache blob bytes. model_id lets status() call it unlocked."""
+ def _downloaded_bytes(
+ self,
+ model_id: Optional[str] = None,
+ hub_cache: Optional[Path] = None,
+ selected_files: Optional[tuple[_SelectedHubFile, ...]] = None,
+ revision: Optional[str] = None,
+ total: Optional[int] = None,
+ ) -> Optional[int]:
+ """Count only the two selected files in their three cache forms.
+
+ status() captures these under the lock and passes them in: reading them
+ here would let a run that starts mid-probe pair its bytes with the total
+ of the run that just ended.
+ """
try:
- from core.inference.stt_sidecar import _repo_cache_dir
-
model_id = model_id or self._model_id
- if not model_id:
+ hub_cache = hub_cache if hub_cache is not None else self._hub_cache
+ selected_files = selected_files if selected_files is not None else self._selected_files
+ revision = revision if revision is not None else self._revision
+ total = total if total is not None else self._total_bytes
+ if not model_id or hub_cache is None or not selected_files:
return None
- blobs = _repo_cache_dir(MTMD_STT_MODELS[model_id].repo) / "blobs"
- if not blobs.is_dir():
- return 0
- return sum(p.stat().st_size for p in blobs.iterdir() if p.is_file())
+ repo = MTMD_STT_MODELS[model_id].repo
+ done = sum(
+ _downloaded_file_bytes(
+ hub_cache = hub_cache,
+ repo = repo,
+ filename = selected.path,
+ size = selected.size,
+ blob_key = selected.blob_key,
+ revision = revision,
+ )
+ for selected in selected_files
+ )
+ return min(done, total) if total is not None else done
except Exception:
return None
@@ -307,10 +383,16 @@ class _MtmdDownloadState:
hf_token: Optional[str] = None,
) -> None:
model_id = resolve_mtmd_model_id(model_id)
+ hub_cache = _capture_stt_hub_cache()
with self._lock:
if self._thread is not None and self._thread.is_alive():
if self._model_id == model_id:
- return
+ # Joining a cancelling run would silently download nothing.
+ if not self._cancelled:
+ return
+ raise SttModelIdError(
+ f"'{model_id}' is still cancelling; try again in a moment."
+ )
raise SttModelIdError(
f"Another dictation model ('{self._model_id}') is still "
"downloading; wait for it to finish."
@@ -318,66 +400,117 @@ class _MtmdDownloadState:
self._model_id = model_id
self._error = None
self._total_bytes = None
+ self._selected_files = ()
+ self._revision = None
+ self._hub_cache = hub_cache
self._cancelled = False
self._process = None
- thread = threading.Thread(target = self._run, args = (model_id, hf_token), daemon = True)
+ thread = threading.Thread(
+ target = self._run,
+ args = (model_id, hf_token),
+ daemon = True,
+ )
self._thread = thread
thread.start()
- def _run(self, model_id: str, hf_token: Optional[str]) -> None:
+ def _run(
+ self,
+ model_id: str,
+ hf_token: Optional[str],
+ hub_cache: Optional[Path] = None,
+ ) -> None:
+ if hub_cache is None:
+ from core.inference.stt_sidecar import _active_hf_hub_cache
+ hub_cache = self._hub_cache or _active_hf_hub_cache()
spec = MTMD_STT_MODELS[model_id]
+ registry = None
+ owner = None
try:
from huggingface_hub import get_hf_file_metadata, hf_hub_url
- total = 0
+ selected: list[_SelectedHubFile] = []
+ revision: Optional[str] = None
for filename in (spec.model_file, spec.mmproj_file):
- try:
- meta = get_hf_file_metadata(
- hf_hub_url(spec.repo, filename), token = hf_token or None
+ meta = get_hf_file_metadata(
+ hf_hub_url(spec.repo, filename, revision = revision),
+ token = hf_token or None,
+ )
+ if revision is None:
+ revision = meta.commit_hash
+ if not isinstance(revision, str) or not _HF_COMMIT_SHA.fullmatch(revision):
+ raise RuntimeError("could not resolve an immutable mtmd revision")
+ if meta.commit_hash != revision:
+ raise RuntimeError("could not pin both mtmd files to one revision")
+ selected.append(
+ _SelectedHubFile(
+ path = filename,
+ size = max(0, int(meta.size or 0)),
+ blob_key = meta.etag,
)
- total += int(meta.size or 0)
- except Exception:
- pass
+ )
+ # A cancel during metadata has no child to stop. Without these the
+ # run still reserves the repo and rewrites the cache after the stop.
with self._lock:
- self._total_bytes = total or None
-
- from core.inference.stt_download_worker import reap_download, spawn_download
+ if self._cancelled:
+ return
+ registry, owner = _claim_stt_repository(spec.repo)
+ with self._lock:
+ if self._cancelled:
+ return
+ _prepare_stt_cache_for_http(spec.repo, hub_cache)
+ with self._lock:
+ self._total_bytes = sum(item.size for item in selected) or None
+ self._selected_files = tuple(selected)
+ self._revision = revision
+
+ from core.inference.stt_download_worker import (
+ reap_download,
+ spawn_download,
+ terminate_download,
+ )
- # One worker per file. Both are required, so a cancel between them
- # leaves the model not downloaded. The first resolves "main" and the
- # second is pinned to whatever it landed on, so a repo update
- # mid-download cannot mix two commits. The first stays unpinned
- # because hf_hub_download only writes refs/main for a named
- # revision, and _cached_file() resolves through that ref.
- revision: Optional[str] = None
- for filename in (spec.model_file, spec.mmproj_file):
- process = spawn_download(
- ["--repo-id", spec.repo, "--filename", filename]
- + (["--revision", revision] if revision else []),
- hf_token = hf_token or None,
- )
- with self._lock:
- if self._cancelled:
- process.terminate()
- self._process = process
- stderr = reap_download(process)
- if process.returncode == 0:
- revision = revision or _cached_main_revision(spec.repo)
- continue
- with self._lock:
- if self._cancelled or process.returncode < 0:
- self._cancelled = True
- return
- detail = (stderr or b"").decode("utf-8", "replace").strip()
- logger.warning("mtmd STT download failed for %s: %s", model_id, detail)
- with self._lock:
- self._error = f"Download failed for '{model_id}'."
+ args = ["--repo-id", spec.repo, "--revision", revision]
+ for item in selected:
+ args.extend(("--filename", item.path))
+ process = spawn_download(args, hf_token = hf_token or None, hub_cache = hub_cache)
+ with self._lock:
+ if self._cancelled:
+ terminate_download(process)
+ self._process = process
+ stderr = reap_download(process)
+ with self._lock:
+ if self._process is process:
+ self._process = None
+ cancelled = self._cancelled
+ if process.returncode == 0 and not cancelled:
+ if (
+ _cached_model_paths(
+ model_id,
+ hub_cache = hub_cache,
+ revision = revision,
+ )
+ is None
+ ):
+ raise RuntimeError("downloaded mtmd files are missing from the captured cache")
+ _write_revision_record(spec.repo, revision)
return
- except Exception as exc:
- logger.warning("mtmd STT download failed for %s: %s", model_id, exc)
+ with self._lock:
+ if cancelled or process.returncode < 0:
+ self._cancelled = True
+ return
+ detail = stderr.decode("utf-8", "replace").strip()
+ logger.warning("mtmd STT download failed for %s: %s", model_id, detail)
with self._lock:
self._error = f"Download failed for '{model_id}'."
+ except Exception as exc:
+ with self._lock:
+ if not self._cancelled:
+ logger.warning("mtmd STT download failed for %s: %s", model_id, exc)
+ self._error = f"Download failed for '{model_id}'."
finally:
+ # Release first: it is the half that would wedge the repository.
+ if registry is not None and owner is not None:
+ registry.release_repository_owner(spec.repo, owner)
# The memo is stale however this ended; dropping it now lets the next poll settle.
_forget_downloaded_probe(model_id)
diff --git a/studio/backend/core/inference/stt_sidecar.py b/studio/backend/core/inference/stt_sidecar.py
index f97df9d3671..bcb2477e111 100644
--- a/studio/backend/core/inference/stt_sidecar.py
+++ b/studio/backend/core/inference/stt_sidecar.py
@@ -86,6 +86,91 @@ class _CachedSttSnapshot:
is_multilingual: Optional[bool]
+class SttDownloadCacheError(RuntimeError):
+ """The shared Hub cache cannot safely admit an STT HTTP writer."""
+
+
+def _capture_stt_hub_cache() -> Path:
+ """Capture the configured Hub cache once for one STT download run."""
+ from utils.hf_cache_settings import get_hf_cache_paths
+ return Path(get_hf_cache_paths().hub_cache).expanduser()
+
+
+def _claim_stt_repository(repo: str) -> tuple[object, object]:
+ """Reserve *repo* against every Model Hub writer and delete."""
+ from hub.utils.download_registry import get_models_registry
+
+ registry = get_models_registry()
+ owner = object()
+ claimed, state = registry.claim_repository_owner(repo, owner)
+ if not claimed:
+ raise SttDownloadCacheError(
+ f"'{repo}' is already active in the Model Hub ({state}); wait for it to finish."
+ )
+ return registry, owner
+
+
+def _prepare_stt_cache_for_http(repo: str, hub_cache: Path) -> None:
+ """Prepare *repo* for HTTP, rejecting unverified transport markers."""
+ from hub.utils.download_registry import TRANSPORT_HTTP, prepare_cache_for_transport
+ from hub.utils.hf_cache_state import (
+ TRANSPORT_MARKER_NAME,
+ iter_active_repo_cache_dirs,
+ repo_cache_dir_name,
+ )
+
+ canonical = hub_cache / repo_cache_dir_name("model", repo)
+ try:
+ canonical.mkdir(parents = True, exist_ok = True)
+ except OSError as exc:
+ raise SttDownloadCacheError(
+ f"Could not make the Hugging Face cache safe for '{repo}'. "
+ "Close other programs using that cache and try again."
+ ) from exc
+ prepare_cache_for_transport("model", repo, TRANSPORT_HTTP, root = hub_cache)
+ entries = list(iter_active_repo_cache_dirs("model", repo, root = hub_cache))
+ try:
+ all_marked_http = bool(entries) and all(
+ (entry / TRANSPORT_MARKER_NAME).read_text(encoding = "utf-8").strip() == TRANSPORT_HTTP
+ for entry in (*entries, canonical)
+ )
+ except (OSError, UnicodeDecodeError):
+ all_marked_http = False
+ if not all_marked_http:
+ raise SttDownloadCacheError(
+ f"Could not make the Hugging Face cache safe for '{repo}'. "
+ "Close other programs using that cache and try again."
+ )
+
+
+def _downloaded_file_bytes(
+ *,
+ hub_cache: Path,
+ repo: str,
+ filename: str,
+ size: int,
+ blob_key: Optional[str],
+ revision: Optional[str],
+) -> int:
+ """Count one selected file across partial, finalized, and snapshot forms."""
+ repo_cache = _repo_cache_dir(repo, hub_cache = hub_cache)
+ candidates: list[Path] = []
+ if blob_key:
+ blobs = repo_cache / "blobs"
+ candidates.extend((blobs / f"{blob_key}.incomplete", blobs / blob_key))
+ if revision:
+ candidates.append(repo_cache / "snapshots" / revision / filename)
+ sizes: list[int] = []
+ for candidate in candidates:
+ try:
+ if candidate.is_file():
+ sizes.append(max(0, int(candidate.stat().st_size)))
+ except OSError:
+ continue
+ done = max(sizes, default = 0)
+ return min(done, max(0, int(size)))
+
+
class SttUnavailableError(RuntimeError):
"""The STT backend (PyTorch/Transformers or PyAV) is not installed."""
@@ -222,26 +307,36 @@ def _read_json_object(path: Path) -> dict:
def _active_hf_hub_cache() -> Path:
- """Return the active Hub cache while respecting runtime test overrides."""
- explicit = (os.environ.get("HF_HUB_CACHE") or "").strip()
- if explicit:
- return Path(explicit).expanduser()
- hf_home = (os.environ.get("HF_HOME") or "").strip()
- if hf_home:
- return Path(hf_home).expanduser() / "hub"
- # The download workers spawn with get_hf_cache_paths(), which also honours a
- # cache location set in Studio. Read the same source, or a relocated cache
- # is written by the worker and looked for here in the old place.
+ """Return the currently configured Hub cache, including live relocation."""
try:
from utils.hf_cache_settings import get_hf_cache_paths
- return Path(get_hf_cache_paths().hub_cache)
+
+ paths = get_hf_cache_paths()
+ # Studio's live cache setting takes precedence over environment defaults.
+ if paths.source == "studio":
+ return Path(paths.hub_cache)
+ explicit = (os.environ.get("HF_HUB_CACHE") or "").strip()
+ if explicit:
+ return Path(explicit).expanduser()
+ hf_home = (os.environ.get("HF_HOME") or "").strip()
+ if hf_home:
+ return Path(hf_home).expanduser() / "hub"
+ return Path(paths.hub_cache)
except Exception:
+ explicit = (os.environ.get("HF_HUB_CACHE") or "").strip()
+ if explicit:
+ return Path(explicit).expanduser()
+ hf_home = (os.environ.get("HF_HOME") or "").strip()
+ if hf_home:
+ return Path(hf_home).expanduser() / "hub"
from huggingface_hub.constants import HF_HUB_CACHE
+
return Path(HF_HUB_CACHE)
-def _repo_cache_dir(repo: str) -> Path:
- return _active_hf_hub_cache() / f"models--{repo.replace('/', '--')}"
+def _repo_cache_dir(repo: str, *, hub_cache: Optional[Path] = None) -> Path:
+ root = hub_cache if hub_cache is not None else _active_hf_hub_cache()
+ return root / f"models--{repo.replace('/', '--')}"
def _revision_record_path(repo: str) -> Path:
@@ -286,6 +381,32 @@ def _read_revision_record(repo: str) -> Optional[str]:
return revision if isinstance(revision, str) and _HF_COMMIT_SHA.fullmatch(revision) else None
+def _fallback_revisions(repo: str, *, hub_cache: Optional[Path] = None) -> list[str]:
+ """Cached commits to try when no revision record survives, newest first.
+
+ Pinned downloads never write refs/main, so without this a lost record would
+ hide an already downloaded model and re-download it on every launch.
+ """
+ repo_cache = _repo_cache_dir(repo, hub_cache = hub_cache)
+ candidates: list[str] = []
+ try:
+ main_revision = (repo_cache / "refs" / "main").read_text(encoding = "utf-8").strip()
+ if _HF_COMMIT_SHA.fullmatch(main_revision):
+ candidates.append(main_revision)
+ except OSError:
+ pass
+ try:
+ snapshots = sorted(
+ (p for p in (repo_cache / "snapshots").iterdir() if _HF_COMMIT_SHA.fullmatch(p.name)),
+ key = lambda p: p.stat().st_mtime,
+ reverse = True,
+ )
+ except OSError:
+ snapshots = []
+ candidates.extend(p.name for p in snapshots if p.name not in candidates)
+ return candidates
+
+
def _safe_snapshot_for_revision(repo: str, revision: str) -> Optional[Path]:
"""Resolve a canonical SHA below this repository's active snapshots dir."""
if not _HF_COMMIT_SHA.fullmatch(revision):
@@ -513,6 +634,8 @@ class _SnapshotDownloadState:
self._process: Optional[subprocess.Popen] = None
self._model_id: Optional[str] = None
self._repo: Optional[str] = None
+ self._revision: Optional[str] = None
+ self._hub_cache: Optional[Path] = None
self._error: Optional[str] = None
self._total_bytes: Optional[int] = None
self._selected_files: tuple[_SelectedHubFile, ...] = ()
@@ -523,14 +646,23 @@ class _SnapshotDownloadState:
with self._lock:
downloading = self._thread is not None and self._thread.is_alive()
show_progress = downloading or self._complete
- return {
+ snapshot = {
"downloading": downloading,
"model": self._model_id if downloading else None,
"error": self._error,
"cancelled": self._cancelled,
"bytes_total": self._total_bytes if show_progress else None,
- "bytes_done": self._blob_bytes() if show_progress else None,
}
+ captured = (
+ self._repo,
+ self._revision,
+ self._hub_cache,
+ self._selected_files,
+ self._total_bytes,
+ )
+ # Outside the lock: _downloaded_bytes() stats the cache, and a cancel must not queue.
+ snapshot["bytes_done"] = self._downloaded_bytes(*captured) if show_progress else None
+ return snapshot
def cancel(self) -> bool:
"""Stop an in-flight download. False when none was running.
@@ -543,38 +675,75 @@ class _SnapshotDownloadState:
self._cancelled = True
process = self._process
if process is not None and process.poll() is None:
- process.terminate()
+ from core.inference.stt_download_worker import terminate_download
+ terminate_download(process)
return True
- def _blob_bytes(self) -> Optional[int]:
- """Best-effort progress: bytes in the repo's HF cache blobs.
-
- Counts only the selected support files and one selected weight format,
- including in-progress ``.incomplete`` blobs.
+ def _downloaded_bytes(
+ self,
+ repo: Optional[str] = None,
+ revision: Optional[str] = None,
+ hub_cache: Optional[Path] = None,
+ selected_files: Optional[tuple[_SelectedHubFile, ...]] = None,
+ total: Optional[int] = None,
+ ) -> Optional[int]:
+ """Count selected files across partial, blob, and snapshot locations.
+
+ status() captures these under the lock and passes them in: reading them
+ here would let a run that starts mid-probe pair its bytes with the total
+ of the run that just ended.
"""
try:
- # Caller may hold the non-reentrant self._lock; a bare read is safe.
- repo = self._repo
- selected_files = self._selected_files
- if not repo or not selected_files:
+ repo = repo if repo is not None else self._repo
+ revision = revision if revision is not None else self._revision
+ hub_cache = hub_cache or self._hub_cache or _active_hf_hub_cache()
+ selected_files = selected_files if selected_files is not None else self._selected_files
+ total = total if total is not None else self._total_bytes
+ if not repo or hub_cache is None or not selected_files:
return None
- blobs = _repo_cache_dir(repo) / "blobs"
- if not blobs.is_dir():
- return 0
- done = 0
- for selected in selected_files:
- if not selected.blob_key:
- continue
- complete = blobs / selected.blob_key
- incomplete = blobs / f"{selected.blob_key}.incomplete"
- candidate = complete if complete.is_file() else incomplete
- if candidate.is_file():
- done += min(candidate.stat().st_size, selected.size)
- total = self._total_bytes
+ done = sum(
+ _downloaded_file_bytes(
+ hub_cache = hub_cache,
+ repo = repo,
+ filename = selected.path,
+ size = selected.size,
+ blob_key = selected.blob_key,
+ revision = revision,
+ )
+ for selected in selected_files
+ )
return min(done, total) if total is not None else done
except Exception:
return None
+ def _run_worker(
+ self, args: list[str], hf_token: Optional[str], hub_cache: Path
+ ) -> tuple[bool, bytes]:
+ from core.inference.stt_download_worker import (
+ reap_download,
+ spawn_download,
+ terminate_download,
+ )
+
+ process = spawn_download(args, hf_token = hf_token or None, hub_cache = hub_cache)
+ with self._lock:
+ if self._cancelled:
+ terminate_download(process)
+ self._process = process
+ stderr = reap_download(process)
+ with self._lock:
+ if self._process is process:
+ self._process = None
+ cancelled = self._cancelled
+ if process.returncode == 0 and not cancelled:
+ return True, stderr
+ if cancelled or process.returncode < 0:
+ with self._lock:
+ self._cancelled = True
+ return False, stderr
+ detail = stderr.decode("utf-8", "replace").strip()
+ raise SttModelCompatibilityError(f"Download worker failed for '{self._repo}': {detail}")
+
def start(
self,
model_id: str,
@@ -582,16 +751,24 @@ class _SnapshotDownloadState:
revision: Optional[str] = None,
) -> None:
model_id = resolve_model_id(model_id)
+ hub_cache = _capture_stt_hub_cache()
with self._lock:
if self._thread is not None and self._thread.is_alive():
if self._model_id == model_id:
- return
+ # Joining a cancelling run would silently download nothing.
+ if not self._cancelled:
+ return
+ raise SttModelIdError(
+ f"'{model_id}' is still cancelling; try again in a moment."
+ )
raise SttModelIdError(
f"Another dictation model ('{self._model_id}') is still "
"downloading; wait for it to finish."
)
self._model_id = model_id
self._repo = resolve_model_repo(model_id)
+ self._revision = None
+ self._hub_cache = hub_cache
self._error = None
self._total_bytes = None
self._selected_files = ()
@@ -599,7 +776,9 @@ class _SnapshotDownloadState:
self._cancelled = False
self._process = None
thread = threading.Thread(
- target = self._run, args = (self._repo, hf_token, revision), daemon = True
+ target = self._run,
+ args = (self._repo, hf_token, revision),
+ daemon = True,
)
self._thread = thread
thread.start()
@@ -609,7 +788,11 @@ class _SnapshotDownloadState:
repo: str,
hf_token: Optional[str],
revision: Optional[str] = None,
+ hub_cache: Optional[Path] = None,
) -> None:
+ hub_cache = hub_cache or self._hub_cache or _active_hf_hub_cache()
+ registry = None
+ owner = None
try:
from huggingface_hub import HfApi, hf_hub_download
@@ -626,12 +809,33 @@ class _SnapshotDownloadState:
f"Could not resolve an immutable revision for STT model '{repo}'."
)
+ # A cancel during metadata has no child to stop. Without these the
+ # run still reserves the repo and rewrites the cache after the stop.
+ with self._lock:
+ if self._cancelled:
+ return
+ registry, owner = _claim_stt_repository(repo)
+ with self._lock:
+ if self._cancelled:
+ return
+ _prepare_stt_cache_for_http(repo, hub_cache)
+ with self._lock:
+ self._revision = revision
+
def load_index(filename: str) -> dict:
+ completed, _stderr = self._run_worker(
+ ["--repo-id", repo, "--revision", revision, "--filename", filename],
+ hf_token,
+ hub_cache,
+ )
+ if not completed:
+ return {}
path = hf_hub_download(
repo_id = repo,
filename = filename,
revision = revision,
- token = hf_token or None,
+ local_files_only = True,
+ cache_dir = str(hub_cache),
)
return _read_json_object(Path(path))
@@ -640,29 +844,13 @@ class _SnapshotDownloadState:
with self._lock:
self._selected_files = selected_files
self._total_bytes = total or None
- # Out of process so cancel() can terminate it; a thread blocked in
- # snapshot_download could not be interrupted.
- from core.inference.stt_download_worker import reap_download, spawn_download
-
args = ["--repo-id", repo, "--revision", revision]
for selected in selected_files:
- args += ["--allow-pattern", selected.path]
- process = spawn_download(args, hf_token = hf_token or None)
- with self._lock:
- if self._cancelled:
- # cancel() landed between start() and the spawn.
- process.terminate()
- self._process = process
- stderr = reap_download(process)
- if process.returncode != 0:
- with self._lock:
- if self._cancelled or process.returncode < 0:
- self._cancelled = True
- return
- detail = (stderr or b"").decode("utf-8", "replace").strip()
- raise SttModelCompatibilityError(f"Download worker failed for '{repo}': {detail}")
- # The worker writes the same cache layout snapshot_download did.
- snapshot = _repo_cache_dir(repo) / "snapshots" / revision
+ args += ["--filename", selected.path]
+ completed, _stderr = self._run_worker(args, hf_token, hub_cache)
+ if not completed:
+ return
+ snapshot = _repo_cache_dir(repo, hub_cache = hub_cache) / "snapshots" / revision
if not _snapshot_is_complete(snapshot):
raise SttModelCompatibilityError(
f"Downloaded STT snapshot for '{repo}' is incomplete."
@@ -671,9 +859,13 @@ class _SnapshotDownloadState:
with self._lock:
self._complete = True
except Exception as exc:
- logger.warning("STT snapshot download failed for %s: %s", repo, exc)
with self._lock:
- self._error = f"Download failed for '{repo}'."
+ if not self._cancelled:
+ logger.warning("STT snapshot download failed for %s: %s", repo, exc)
+ self._error = f"Download failed for '{repo}'."
+ finally:
+ if registry is not None and owner is not None:
+ registry.release_repository_owner(repo, owner)
_download_state = _SnapshotDownloadState()
diff --git a/studio/backend/hub/services/download_lifecycle.py b/studio/backend/hub/services/download_lifecycle.py
index 9e564ee09c3..da44b39c7a5 100644
--- a/studio/backend/hub/services/download_lifecycle.py
+++ b/studio/backend/hub/services/download_lifecycle.py
@@ -523,11 +523,14 @@ def _try_http_retry(
)
if claimed:
break
- if conflict_state == "deleting":
+ # An STT owner is not an active job, so mark_pending_cancel cannot reach
+ # this loop; waiting it out here would be an uninterruptible spin.
+ if conflict_state in ("deleting", "repository_owned"):
logger.debug(
- "%s XET retry claim rejected for %s; repo is being deleted",
+ "%s XET retry claim rejected for %s; blocked by %s",
log_prefix,
label,
+ conflict_state,
)
_set_retry_failure_state(
registry,
diff --git a/studio/backend/hub/tests/test_stt_repository_ownership.py b/studio/backend/hub/tests/test_stt_repository_ownership.py
new file mode 100644
index 00000000000..0ecddc6e03e
--- /dev/null
+++ b/studio/backend/hub/tests/test_stt_repository_ownership.py
@@ -0,0 +1,92 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Atomic ownership between STT and Model Hub writers."""
+
+from __future__ import annotations
+
+import pytest
+
+from hub.utils.download_registry import DownloadRegistry
+
+
+_CASES = (
+ ("same-blob", "Org/Repo::Q4_K_M", "Q4_K_M", frozenset({"shared"})),
+ ("disjoint-blob", "Org/Repo::Q8_0", "Q8_0", frozenset({"other"})),
+ ("full-snapshot", "Org/Repo", None, frozenset({"snapshot"})),
+ ("same-repo-variant", "Org/Repo::F16", "F16", frozenset({"variant"})),
+)
+
+
[email protected]("_label,key,variant,blob_hashes", _CASES)
+def test_stt_owner_published_first_blocks_every_same_repo_model_hub_shape(
+ _label, key, variant, blob_hashes
+):
+ registry = DownloadRegistry()
+ owner = object()
+
+ assert registry.claim_repository_owner("Org/Repo", owner) == (True, "owned")
+ claimed, state = registry.claim(
+ key,
+ "xet",
+ repo_type = "model",
+ repo_id = "Org/Repo",
+ variant = variant,
+ blob_hashes = blob_hashes,
+ progress_blob_hashes = blob_hashes,
+ )
+
+ assert claimed is False
+ assert state == "repository_owned"
+ assert registry.release_repository_owner("Org/Repo", owner) is True
+
+
[email protected]("_label,key,variant,blob_hashes", _CASES)
+def test_model_hub_published_first_blocks_stt_for_every_same_repo_shape(
+ _label, key, variant, blob_hashes
+):
+ registry = DownloadRegistry()
+ claimed, _state = registry.claim(
+ key,
+ "xet",
+ repo_type = "model",
+ repo_id = "Org/Repo",
+ variant = variant,
+ blob_hashes = blob_hashes,
+ progress_blob_hashes = blob_hashes,
+ )
+ assert claimed is True
+
+ assert registry.claim_repository_owner("Org/Repo", object())[0] is False
+
+
+def test_stt_owner_and_model_hub_job_can_use_unrelated_repositories():
+ registry = DownloadRegistry()
+ owner = object()
+ assert registry.claim_repository_owner("Org/Stt", owner)[0] is True
+
+ claimed, _state = registry.claim(
+ "Org/Chat::Q4_K_M",
+ "xet",
+ repo_type = "model",
+ repo_id = "Org/Chat",
+ variant = "Q4_K_M",
+ blob_hashes = frozenset({"blob"}),
+ )
+
+ assert claimed is True
+ assert registry.begin_delete("Org/Stt") is False
+ assert registry.begin_delete("Org/Other") is True
+ registry.end_delete("Org/Other")
+ assert registry.release_repository_owner("Org/Stt", owner) is True
+ assert registry.begin_delete("Org/Stt") is True
+
+
+def test_only_the_current_stt_owner_can_release_a_repository():
+ registry = DownloadRegistry()
+ owner = object()
+ assert registry.claim_repository_owner("Org/Repo", owner)[0] is True
+
+ assert registry.release_repository_owner("Org/Repo", object()) is False
+ assert registry.claim_repository_owner("Org/Repo", object())[0] is False
+ assert registry.release_repository_owner("Org/Repo", owner) is True
diff --git a/studio/backend/hub/utils/download_registry.py b/studio/backend/hub/utils/download_registry.py
index ec7ccf27c89..916a28460f8 100644
--- a/studio/backend/hub/utils/download_registry.py
+++ b/studio/backend/hub/utils/download_registry.py
@@ -47,7 +47,7 @@ import time
import weakref
from dataclasses import dataclass, field, replace
from pathlib import Path
-from typing import Callable, Iterator, Literal, Optional, Sequence
+from typing import Callable, Iterator, Literal, NamedTuple, Optional, Sequence
from loggers import get_logger
@@ -367,26 +367,32 @@ def reap_orphan_workers() -> None:
_safe_unlink(entry)
+class _PurgeOutcome(NamedTuple):
+ """Number of selected partials removed and number that could not be removed."""
+
+ removed: int
+ failed: int
+
+
def _purge_incomplete_blobs(
entry: Path,
only_hashes: Optional[frozenset[str]] = None,
protected_hashes: Optional[frozenset[str]] = None,
-) -> int:
- """Delete matching ``*.incomplete`` blobs beneath *entry*; return the count
- removed. Per-file failures are swallowed.
+) -> _PurgeOutcome:
+ """Delete selected partials while preserving protected concurrent writes.
- ``only_hashes`` whitelists which partials may be purged; ``None`` means
- every partial (full-repo snapshot/dataset). ``protected_hashes`` is honoured
- unconditionally, even when ``only_hashes`` is ``None``, so a blob a
- concurrent same-repo peer is writing is never purged from under it."""
+ Report failed deletions so sparse partials cannot receive an HTTP marker.
+ """
blobs_dir = entry / "blobs"
if not blobs_dir.is_dir():
- return 0
+ return _PurgeOutcome(0, 0)
removed = 0
+ failed = 0
try:
candidates = list(blobs_dir.iterdir())
except OSError:
- return 0
+ # Nothing in an unreadable directory can be certified as safe.
+ return _PurgeOutcome(0, 1)
for blob in candidates:
try:
if not blob.is_file():
@@ -400,11 +406,14 @@ def _purge_incomplete_blobs(
continue
blob.unlink()
removed += 1
+ except FileNotFoundError:
+ # A peer finalized or removed it after enumeration. The requested
+ # end state was reached, so this is not a failed purge.
+ continue
except OSError:
- # Swallow; downstream snapshot_download surfaces a precise error if
- # it actually can't proceed.
+ failed += 1
continue
- return removed
+ return _PurgeOutcome(removed, failed)
def _iter_active_snapshot_dirs(
@@ -564,7 +573,9 @@ def prepare_cache_for_transport(
Scope: ``root`` selects the cache captured by the caller. It defaults to the
active ``HF_HUB_CACHE`` root for workers that inherit their cache through
- the environment. Markers are written for the new mode before returning.
+ the environment. Markers are written for the new mode before returning,
+ except when an HTTP purge cannot remove every selected partial. Withholding
+ the marker keeps the surviving partial untrusted.
"""
if mode not in VALID_TRANSPORTS:
if mode == TRANSPORT_AUTO:
@@ -601,15 +612,24 @@ def prepare_cache_for_transport(
has_companion = bool(companion_blob_hashes)
total_purged = 0
for entry in entries:
+ main_purge = _PurgeOutcome(0, 0)
+ companion_purge = _PurgeOutcome(0, 0)
if mode == TRANSPORT_XET:
- total_purged += _purge_incomplete_blobs(entry, only_blob_hashes, protected)
+ main_purge = _purge_incomplete_blobs(entry, only_blob_hashes, protected)
else:
if _read_marker(entry, variant) != mode:
- total_purged += _purge_incomplete_blobs(entry, only_blob_hashes, protected)
+ main_purge = _purge_incomplete_blobs(entry, only_blob_hashes, protected)
if companion_blob_hashes and _read_companion_marker(entry) != mode:
- total_purged += _purge_incomplete_blobs(entry, companion_blob_hashes, protected)
- _write_marker(entry, mode, variant)
- if has_companion:
+ companion_purge = _purge_incomplete_blobs(
+ entry,
+ companion_blob_hashes,
+ protected,
+ )
+ total_purged += main_purge.removed + companion_purge.removed
+ record_unconditionally = mode == TRANSPORT_XET
+ if record_unconditionally or not main_purge.failed:
+ _write_marker(entry, mode, variant)
+ if has_companion and (record_unconditionally or not companion_purge.failed):
_write_companion_marker(entry, mode)
return total_purged
@@ -678,8 +698,10 @@ def read_active_transport_marker(
repo_type: str,
repo_id: str,
variant: Optional[str] = None,
+ *,
+ root: Optional[Path] = None,
) -> Optional[str]:
- for entry in iter_active_repo_cache_dirs(repo_type, repo_id):
+ for entry in iter_active_repo_cache_dirs(repo_type, repo_id, root = root):
value = _read_marker(entry, variant)
if value is not None:
return value
@@ -913,6 +935,8 @@ class DownloadRegistry:
# prior generation (which would let a stale cancel match a new run).
self._generation_seq = 0
self._deleting: dict[str, set[Optional[str]]] = {}
+ # Publish external cache owners under the same lock as Model Hub jobs.
+ self._repository_owners: dict[str, object] = {}
self._lock = threading.Lock()
_REGISTRIES.add(self)
self._max_terminal = max_terminal
@@ -1158,6 +1182,8 @@ class DownloadRegistry:
requested_hashes = blob_hashes or frozenset()
requested_progress_hashes = progress_blob_hashes or frozenset()
with self._lock:
+ if repo in self._repository_owners:
+ return False, "repository_owned"
# Run the final external admission check while the registry lock is
# held, immediately before inspecting and publishing active state.
# The GGUF load path establishes its marker before calling
@@ -1247,6 +1273,35 @@ class DownloadRegistry:
self._cancel_marker_transports.pop(key, None)
return True, "running"
+ def claim_repository_owner(self, repo_id: str, owner: object) -> tuple[bool, str]:
+ """Atomically reserve all cache writes for one repository.
+
+ This covers snapshots, GGUF variants, and deletion. The opaque owner
+ prevents a stale run from releasing a newer claim.
+ """
+ repo = normalize_repo_key(repo_id)
+ with self._lock:
+ if repo in self._repository_owners:
+ return False, "repository_owned"
+ if repo in self._deleting:
+ return False, "deleting"
+ for key, job in self._jobs.items():
+ if _repo_of_key(key) != repo or job.state not in _ACTIVE_STATES:
+ continue
+ # Retry handoffs can temporarily disappear from _repo_active.
+ return False, job.state
+ self._repository_owners[repo] = owner
+ return True, "owned"
+
+ def release_repository_owner(self, repo_id: str, owner: object) -> bool:
+ """Release *repo_id* only when *owner* still holds its reservation."""
+ repo = normalize_repo_key(repo_id)
+ with self._lock:
+ if self._repository_owners.get(repo) is not owner:
+ return False
+ self._repository_owners.pop(repo, None)
+ return True
+
def adoptable(self, key: str) -> bool:
"""True when *key* itself has a live job a client can attach to.
@@ -1393,6 +1448,8 @@ class DownloadRegistry:
repo_id = normalize_repo_key(repo_id)
variant_key = (variant or "").strip().lower() or None
with self._lock:
+ if repo_id in self._repository_owners:
+ return False
if self._delete_blocked_by_active_locked(repo_id, variant_key):
return False
self._deleting.setdefault(repo_id, set()).add(variant_key)
diff --git a/studio/backend/tests/test_stt_download_followups.py b/studio/backend/tests/test_stt_download_followups.py
new file mode 100644
index 00000000000..9ab09cf4f26
--- /dev/null
+++ b/studio/backend/tests/test_stt_download_followups.py
@@ -0,0 +1,275 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Follow-ups to the STT HTTP download work.
+
+Pinning downloads to a commit stopped huggingface_hub writing refs/main, and
+reserving the repository made a cancelled or wedged run everyone else's problem.
+These cover what that changed.
+"""
+
+import subprocess
+import sys
+import threading
+import time
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from core.inference import stt_download_worker as worker_mod
+from core.inference import stt_ggml_sidecar as ggml_mod
+from core.inference import stt_mtmd_sidecar as mtmd_mod
+from core.inference import stt_sidecar as snapshot_mod
+
+
+class _FakeMeta:
+ """One Hub file's metadata, pinned to an immutable commit."""
+
+ commit_hash = "a" * 40
+ etag = "etag"
+ size = 1
+
+
+class _FakeInfo:
+ """One repo's metadata, pinned to an immutable commit."""
+
+ sha = "a" * 40
+
+
+def _write_snapshot(hub_cache: Path, repo: str, revision: str, filename: str) -> Path:
+ """Lay out one finished pinned download: a blob plus its snapshot entry."""
+ repo_cache = hub_cache / f"models--{repo.replace('/', '--')}"
+ blob = repo_cache / "blobs" / "etag"
+ blob.parent.mkdir(parents = True, exist_ok = True)
+ blob.write_bytes(b"weights")
+ entry = repo_cache / "snapshots" / revision / filename
+ entry.parent.mkdir(parents = True, exist_ok = True)
+ entry.write_bytes(b"weights")
+ return entry
+
+
+def test_a_lost_revision_record_still_finds_the_downloaded_model(tmp_path, monkeypatch):
+ """A pinned download writes no refs/main, so the record is the only pointer.
+
+ Its write swallows OSError, so without a snapshot fallback an unwritable
+ profile would re-download the model on every launch.
+ """
+ revision = "a" * 40
+ repo = ggml_mod.GGML_STT_REPOS["tiny"]
+ _write_snapshot(tmp_path, repo, revision, ggml_mod.GGML_STT_MODELS["tiny"])
+ monkeypatch.setattr(ggml_mod, "_read_revision_record", lambda repo_id: None)
+ recorded = []
+ monkeypatch.setattr(
+ ggml_mod, "_write_revision_record", lambda repo_id, rev: recorded.append((repo_id, rev))
+ )
+
+ assert snapshot_mod._fallback_revisions(repo, hub_cache = tmp_path) == [revision]
+ assert ggml_mod._cached_model_path("tiny", hub_cache = tmp_path) is not None
+ assert recorded == [(repo, revision)], "the record was not rebuilt from the cache"
+
+
+def test_fallback_revisions_prefers_refs_main_and_skips_junk(tmp_path):
+ """refs/main first when it exists, and only 40-hex snapshot dirs qualify."""
+ repo = "owner/repo"
+ repo_cache = tmp_path / "models--owner--repo"
+ (repo_cache / "snapshots" / ("b" * 40)).mkdir(parents = True)
+ (repo_cache / "snapshots" / "not-a-sha").mkdir(parents = True)
+ (repo_cache / "refs").mkdir(parents = True)
+ (repo_cache / "refs" / "main").write_text("c" * 40, encoding = "utf-8")
+
+ assert snapshot_mod._fallback_revisions(repo, hub_cache = tmp_path) == ["c" * 40, "b" * 40]
+
+
+ "module, state_factory, model_id",
+ [
+ (snapshot_mod, snapshot_mod._SnapshotDownloadState, "unsloth/whisper-tiny"),
+ (ggml_mod, ggml_mod._GgmlDownloadState, "tiny"),
+ (mtmd_mod, mtmd_mod._MtmdDownloadState, "qwen3-asr-0.6b"),
+ ],
+)
+def test_a_cancel_during_metadata_leaves_the_shared_cache_alone(
+ module, state_factory, model_id, monkeypatch, tmp_path
+):
+ """cancel() has no child to stop while metadata resolves.
+
+ Claiming the repository would lock out the Model Hub, and preparing the
+ cache would purge partials, both after the user was told it stopped.
+ """
+ claims, prepares, spawns = [], [], []
+ # Stub the Hub metadata call. Unstubbed it reaches huggingface.co, and when that
+ # fails (offline CI) the exception lands in _run's handler before the guard under
+ # test, so every assertion below passes without the guard existing at all.
+ import huggingface_hub
+
+ monkeypatch.setattr(huggingface_hub, "get_hf_file_metadata", lambda *a, **k: _FakeMeta())
+ monkeypatch.setattr(
+ huggingface_hub,
+ "HfApi",
+ lambda *a, **k: SimpleNamespace(model_info = lambda *a, **k: _FakeInfo()),
+ )
+ monkeypatch.setattr(
+ module, "_claim_stt_repository", lambda repo: claims.append(repo) or (None, None)
+ )
+ monkeypatch.setattr(
+ module, "_prepare_stt_cache_for_http", lambda repo, cache: prepares.append(repo)
+ )
+ monkeypatch.setattr(
+ worker_mod, "spawn_download", lambda *a, **k: spawns.append(a) or pytest.fail("spawned")
+ )
+
+ state = state_factory()
+ state._cancelled = True # as cancel() leaves it during metadata
+ state._run(model_id, None, hub_cache = tmp_path)
+
+ assert claims == [], "a cancelled run still reserved the repository"
+ assert prepares == [], "a cancelled run still rewrote the shared cache"
+ assert spawns == []
+
+
+ "state_factory, model_id",
+ [
+ (snapshot_mod._SnapshotDownloadState, "unsloth/whisper-tiny"),
+ (ggml_mod._GgmlDownloadState, "tiny"),
+ (mtmd_mod._MtmdDownloadState, "qwen3-asr-0.6b"),
+ ],
+)
+def test_restarting_a_cancelling_download_is_not_a_silent_no_op(state_factory, model_id):
+ """The same-model early return would join a run that will download nothing."""
+ state = state_factory()
+ release = threading.Event()
+ state._model_id = model_id
+ state._cancelled = True
+ state._thread = threading.Thread(target = release.wait, daemon = True)
+ state._thread.start()
+ try:
+ with pytest.raises(snapshot_mod.SttModelIdError, match = "cancelling"):
+ state.start(model_id)
+ finally:
+ release.set()
+ state._thread.join(timeout = 5)
+
+
+def test_a_worker_that_ignores_sigterm_is_killed():
+ """The canceller holds the repository reservation until the reap returns."""
+ process = subprocess.Popen(
+ [
+ sys.executable,
+ "-c",
+ "import signal, time; signal.signal(signal.SIGTERM, signal.SIG_IGN); time.sleep(30)",
+ ]
+ )
+ try:
+ with pytest.MonkeyPatch.context() as patch:
+ patch.setattr(worker_mod, "TERMINATE_GRACE_SECONDS", 0.2)
+ started = time.monotonic()
+ worker_mod.terminate_download(process)
+ assert time.monotonic() - started < 0.2, "cancel() waited on the worker"
+ assert process.wait(timeout = 10) != 0
+ finally:
+ if process.poll() is None:
+ process.kill()
+ process.wait(timeout = 10)
+
+
+ "state_factory, model_id",
+ [
+ (snapshot_mod._SnapshotDownloadState, "unsloth/whisper-tiny"),
+ (ggml_mod._GgmlDownloadState, "tiny"),
+ (mtmd_mod._MtmdDownloadState, "qwen3-asr-0.6b"),
+ ],
+)
+def test_status_never_stats_the_cache_under_the_download_lock(state_factory, model_id):
+ """Progress is now three stats per selected file; a cancel must not queue."""
+ state = state_factory()
+ observed = []
+
+ def probe(*args, **kwargs):
+ observed.append(state._lock.acquire(blocking = False))
+ if observed[-1]:
+ state._lock.release()
+ return 1
+
+ state._downloaded_bytes = probe
+ state._model_id = model_id
+ state._thread = threading.Thread(target = lambda: time.sleep(0.3), daemon = True)
+ state._thread.start()
+ try:
+ assert state.status()["bytes_done"] == 1
+ finally:
+ state._thread.join(timeout = 5)
+ assert observed == [True], "progress was computed while holding the download lock"
+
+
+ "state_factory, model_id, restart",
+ [
+ (
+ snapshot_mod._SnapshotDownloadState,
+ "unsloth/whisper-tiny",
+ lambda s: setattr(s, "_repo", "org/next") or setattr(s, "_selected_files", ()),
+ ),
+ (ggml_mod._GgmlDownloadState, "tiny", lambda s: setattr(s, "_etag", None)),
+ (
+ mtmd_mod._MtmdDownloadState,
+ "qwen3-asr-0.6b",
+ lambda s: setattr(s, "_selected_files", ()),
+ ),
+ ],
+)
+def test_progress_cannot_mix_a_new_runs_bytes_with_the_old_runs_total(
+ state_factory, model_id, restart, tmp_path
+):
+ """status() reports bytes_total from under the lock and probes the cache after.
+
+ A run that starts in that gap replaces the fields the probe reads, so reading
+ them there paired one run's total with another's bytes, or blanked it.
+ """
+ state = state_factory()
+ state._model_id = model_id
+ state._repo = "org/repo"
+ state._hub_cache = tmp_path
+ state._total_bytes = 1000
+ state._etag = "etag"
+ state._selected_files = (snapshot_mod._SelectedHubFile(path = "f", size = 1000, blob_key = None),)
+ release = threading.Event()
+ state._thread = threading.Thread(target = release.wait, daemon = True)
+ state._thread.start()
+
+ real = state._downloaded_bytes
+
+ def probe_after_a_restart(*args, **kwargs):
+ restart(state) # the next run lands between the lock release and the probe
+ return real(*args, **kwargs)
+
+ state._downloaded_bytes = probe_after_a_restart
+ try:
+ status = state.status()
+ finally:
+ release.set()
+ state._thread.join(timeout = 5)
+
+ assert status["bytes_total"] == 1000
+ assert status["bytes_done"] == 0, "the probe read the restarted run's fields"
+
+
+def test_mtmd_rejects_a_revision_that_is_not_an_immutable_commit(monkeypatch, tmp_path):
+ """The other two backends validate the SHA; a bad one here would be pinned
+ into --revision and then silently dropped by the revision record."""
+
+ class _Meta:
+ commit_hash = "main"
+ etag = "etag"
+ size = 1
+
+ monkeypatch.setattr(mtmd_mod, "_claim_stt_repository", lambda repo: pytest.fail("claimed"))
+ import huggingface_hub
+
+ monkeypatch.setattr(huggingface_hub, "get_hf_file_metadata", lambda *a, **k: _Meta())
+ state = mtmd_mod._MtmdDownloadState()
+ state._run("qwen3-asr-0.6b", None, hub_cache = tmp_path)
+
+ assert state.status()["error"] is not None
diff --git a/studio/backend/tests/test_stt_http_downloads.py b/studio/backend/tests/test_stt_http_downloads.py
new file mode 100644
index 00000000000..6d8b5636ff2
--- /dev/null
+++ b/studio/backend/tests/test_stt_http_downloads.py
@@ -0,0 +1,643 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Sequential HTTP transport and exact STT progress invariants."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from core.inference import (
+ stt_download_worker,
+ stt_ggml_sidecar,
+ stt_mtmd_sidecar,
+ stt_sidecar,
+)
+from hub.utils import download_registry
+
+
+def _repo_dir(root: Path, repo: str) -> Path:
+ return root / f"models--{repo.replace('/', '--')}"
+
+
+def _case_insensitive(root: Path) -> bool:
+ """macOS and Windows fold case, so two case variants are one directory there."""
+ probe = root / "CaseProbe"
+ probe.mkdir()
+ try:
+ return (root / "caseprobe").is_dir()
+ finally:
+ probe.rmdir()
+
+
+def test_http_cache_preparation_fails_closed_when_blob_directory_is_unreadable(
+ monkeypatch, tmp_path
+):
+ repo = "Org/Repo"
+ entry = _repo_dir(tmp_path, repo)
+ blobs = entry / "blobs"
+ blobs.mkdir(parents = True)
+ (entry / ".transport").write_text("xet", encoding = "utf-8")
+ (blobs / "sparse.incomplete").write_bytes(b"x" * 64)
+ real_iterdir = Path.iterdir
+
+ def unreadable(self):
+ if self == blobs:
+ raise PermissionError("unreadable")
+ return real_iterdir(self)
+
+ monkeypatch.setattr(Path, "iterdir", unreadable)
+
+ with pytest.raises(stt_sidecar.SttDownloadCacheError):
+ stt_sidecar._prepare_stt_cache_for_http(repo, tmp_path)
+
+ assert (entry / ".transport").read_text(encoding = "utf-8") == "xet"
+ assert (blobs / "sparse.incomplete").is_file()
+
+
+def test_http_cache_preparation_requires_marker_readback(monkeypatch, tmp_path):
+ real_read_text = Path.read_text
+
+ def unreadable_marker(self, *args, **kwargs):
+ if self.name == download_registry.TRANSPORT_MARKER_NAME:
+ raise PermissionError("unreadable")
+ return real_read_text(self, *args, **kwargs)
+
+ monkeypatch.setattr(Path, "read_text", unreadable_marker)
+
+ with pytest.raises(stt_sidecar.SttDownloadCacheError):
+ stt_sidecar._prepare_stt_cache_for_http("Org/Repo", tmp_path)
+
+
+ "canonical_first",
+ (False, True),
+ ids = ("alias-first", "canonical-first"),
+)
+def test_http_cache_preparation_requires_every_case_variant_marker(
+ monkeypatch, tmp_path, canonical_first
+):
+ if _case_insensitive(tmp_path):
+ pytest.skip("case-folding filesystem: the alias and the canonical dir are one entry")
+ repo = "Org/Repo"
+ alias = _repo_dir(tmp_path, "org/repo")
+ canonical = _repo_dir(tmp_path, repo)
+ alias.mkdir(parents = True)
+ canonical_blobs = canonical / "blobs"
+ canonical_blobs.mkdir(parents = True)
+ (alias / ".transport").write_text("http", encoding = "utf-8")
+ (canonical / ".transport").write_text("xet", encoding = "utf-8")
+ partial = canonical_blobs / "sparse.incomplete"
+ partial.write_bytes(b"x" * 64)
+ ordered_entries = (canonical, alias) if canonical_first else (alias, canonical)
+ real_iterdir = Path.iterdir
+
+ def ordered_unreadable(self):
+ if self == tmp_path:
+ return iter(ordered_entries)
+ if self == canonical_blobs:
+ raise PermissionError("unreadable")
+ return real_iterdir(self)
+
+ monkeypatch.setattr(Path, "iterdir", ordered_unreadable)
+
+ with pytest.raises(stt_sidecar.SttDownloadCacheError):
+ stt_sidecar._prepare_stt_cache_for_http(repo, tmp_path)
+
+ spawned = []
+
+ class Registry:
+ @staticmethod
+ def release_repository_owner(_repo, _owner):
+ return True
+
+ monkeypatch.setattr(
+ stt_ggml_sidecar,
+ "_claim_stt_repository",
+ lambda _repo: (Registry(), object()),
+ )
+ monkeypatch.setattr("huggingface_hub.get_hf_file_metadata", lambda *_a, **_k: None)
+ monkeypatch.setattr("huggingface_hub.hf_hub_url", lambda *_a, **_k: "https://example")
+ monkeypatch.setattr(
+ stt_download_worker,
+ "spawn_download",
+ lambda *_a, **_k: spawned.append(True),
+ )
+
+ state = stt_ggml_sidecar._GgmlDownloadState()
+ state._run("tiny", None, hub_cache = tmp_path)
+
+ assert spawned == []
+ assert (canonical / ".transport").read_text(encoding = "utf-8") == "xet"
+ assert partial.read_bytes() == b"x" * 64
+
+
+def test_http_retry_keeps_its_owned_partial_and_cross_transport_retry_purges_it(tmp_path):
+ repo = "Org/Repo"
+ entry = _repo_dir(tmp_path, repo)
+ blobs = entry / "blobs"
+ blobs.mkdir(parents = True)
+
+ stt_sidecar._prepare_stt_cache_for_http(repo, tmp_path)
+ partial = blobs / "etag.incomplete"
+ partial.write_bytes(b"x" * 64)
+ stt_sidecar._prepare_stt_cache_for_http(repo, tmp_path)
+ assert partial.stat().st_size == 64
+
+ (entry / ".transport").write_text("xet", encoding = "utf-8")
+ stt_sidecar._prepare_stt_cache_for_http(repo, tmp_path)
+ assert not partial.exists()
+
+
+def test_spawned_stt_worker_is_http_only_and_uses_the_captured_cache(monkeypatch, tmp_path):
+ observed = {}
+
+ class Process:
+ pid = 12345
+
+ def popen(argv, **kwargs):
+ observed["argv"] = argv
+ observed["env"] = kwargs["env"]
+ return Process()
+
+ monkeypatch.setattr(stt_download_worker.subprocess, "Popen", popen)
+ monkeypatch.setattr("utils.process_lifetime.adopt_pid", lambda _pid: None)
+ monkeypatch.setattr("utils.process_lifetime.child_popen_kwargs", lambda: {})
+
+ stt_download_worker.spawn_download(
+ ["--repo-id", "Org/Repo", "--filename", "model.bin"],
+ hub_cache = tmp_path,
+ )
+
+ assert observed["env"]["HF_HUB_CACHE"] == str(tmp_path)
+ assert observed["env"]["HF_HUB_DISABLE_XET"] == "1"
+ assert observed["env"]["HF_HUB_ENABLE_HF_TRANSFER"] == "0"
+ assert observed["argv"][-4:] == ["--repo-id", "Org/Repo", "--filename", "model.bin"]
+
+
+def test_captured_cache_worker_stays_online_during_temporary_offline_guard(monkeypatch, tmp_path):
+ fake_package = tmp_path / "modules" / "huggingface_hub"
+ fake_package.mkdir(parents = True)
+ observed_path = tmp_path / "worker-environment.json"
+ fake_package.joinpath("__init__.py").write_text(
+ """import json
+import os
+
+def hf_hub_download(**kwargs):
+ with open(os.environ["STT_WORKER_ENV_PATH"], "w", encoding="utf-8") as handle:
+ json.dump({
+ "hub_cache": os.environ.get("HF_HUB_CACHE"),
+ "hub_offline": os.environ.get("HF_HUB_OFFLINE"),
+ "transformers_offline": os.environ.get("TRANSFORMERS_OFFLINE"),
+ }, handle)
+""",
+ encoding = "utf-8",
+ )
+ monkeypatch.setenv("PYTHONPATH", str(tmp_path / "modules"))
+ monkeypatch.setenv("STT_WORKER_ENV_PATH", str(observed_path))
+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
+ monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)
+
+ from utils.utils import force_hf_offline
+
+ captured_cache = tmp_path / "captured-hub"
+ with force_hf_offline():
+ process = stt_download_worker.spawn_download(
+ ["--repo-id", "Org/Repo", "--filename", "model.bin"],
+ hub_cache = captured_cache,
+ )
+ stderr = stt_download_worker.reap_download(process)
+
+ assert process.returncode == 0, stderr.decode("utf-8", "replace")
+ assert json.loads(observed_path.read_text(encoding = "utf-8")) == {
+ "hub_cache": str(captured_cache),
+ "hub_offline": None,
+ "transformers_offline": None,
+ }
+
+
+def test_worker_downloads_only_the_exact_repeated_filenames(monkeypatch):
+ calls = []
+ monkeypatch.setattr(
+ "huggingface_hub.hf_hub_download",
+ lambda **kwargs: calls.append(kwargs),
+ )
+
+ assert (
+ stt_download_worker.main(
+ [
+ "--repo-id",
+ "Org/Repo",
+ "--revision",
+ "a" * 40,
+ "--filename",
+ "literal[1].json",
+ "--filename",
+ "weights/*.safetensors",
+ ]
+ )
+ == 0
+ )
+ assert [call["filename"] for call in calls] == ["literal[1].json", "weights/*.safetensors"]
+
+
+def test_selected_file_progress_covers_partial_final_and_windows_snapshot(tmp_path):
+ repo = "Org/Repo"
+ revision = "b" * 40
+ entry = _repo_dir(tmp_path, repo)
+ blobs = entry / "blobs"
+ blobs.mkdir(parents = True)
+ partial = blobs / "etag.incomplete"
+ partial.write_bytes(b"x" * 40)
+ kwargs = {
+ "hub_cache": tmp_path,
+ "repo": repo,
+ "filename": "nested/model.bin",
+ "size": 100,
+ "blob_key": "etag",
+ "revision": revision,
+ }
+ assert stt_sidecar._downloaded_file_bytes(**kwargs) == 40
+
+ partial.rename(blobs / "etag")
+ assert stt_sidecar._downloaded_file_bytes(**kwargs) == 40
+ (blobs / "etag").unlink()
+ snapshot = entry / "snapshots" / revision / "nested"
+ snapshot.mkdir(parents = True)
+ (snapshot / "model.bin").write_bytes(b"x" * 120)
+ assert stt_sidecar._downloaded_file_bytes(**kwargs) == 100
+
+
+def test_mtmd_progress_counts_only_its_two_exact_files(tmp_path):
+ model_id = "qwen3-asr-0.6b"
+ spec = stt_mtmd_sidecar.MTMD_STT_MODELS[model_id]
+ entry = _repo_dir(tmp_path, spec.repo)
+ blobs = entry / "blobs"
+ blobs.mkdir(parents = True)
+ (blobs / "main").write_bytes(b"x" * 80)
+ (blobs / "mmproj.incomplete").write_bytes(b"x" * 15)
+ (blobs / "unrelated").write_bytes(b"x" * 1000)
+ state = stt_mtmd_sidecar._MtmdDownloadState()
+ state._model_id = model_id
+ state._hub_cache = tmp_path
+ state._revision = "c" * 40
+ state._selected_files = (
+ stt_sidecar._SelectedHubFile(spec.model_file, 80, "main"),
+ stt_sidecar._SelectedHubFile(spec.mmproj_file, 20, "mmproj"),
+ )
+ state._total_bytes = 100
+
+ assert state._downloaded_bytes() == 95
+
+
+def test_mtmd_run_holds_one_owner_and_one_cache_through_final_lookup(monkeypatch, tmp_path):
+ model_id = "qwen3-asr-0.6b"
+ spec = stt_mtmd_sidecar.MTMD_STT_MODELS[model_id]
+ revision = "d" * 40
+ events = []
+
+ class Registry:
+ def release_repository_owner(self, repo, owner):
+ events.append(("release", repo, owner))
+ return True
+
+ owner = object()
+ monkeypatch.setattr(
+ stt_mtmd_sidecar,
+ "_claim_stt_repository",
+ lambda repo: (events.append(("claim", repo)) or (Registry(), owner)),
+ )
+ monkeypatch.setattr(
+ stt_mtmd_sidecar,
+ "_prepare_stt_cache_for_http",
+ lambda repo, root: events.append(("prepare", repo, root)),
+ )
+
+ def metadata(url, token = None):
+ name = spec.model_file if spec.model_file in url else spec.mmproj_file
+ return SimpleNamespace(size = 10, etag = name, commit_hash = revision)
+
+ monkeypatch.setattr("huggingface_hub.get_hf_file_metadata", metadata)
+ monkeypatch.setattr(
+ "huggingface_hub.hf_hub_url",
+ lambda repo, filename, revision = None: f"https://example/{repo}/{filename}?rev={revision}",
+ )
+
+ class Process:
+ returncode = 0
+
+ def poll(self):
+ return 0
+
+ def terminate(self):
+ events.append(("terminate",))
+
+ def spawn(
+ args,
+ hf_token = None,
+ *,
+ hub_cache = None,
+ ):
+ events.append(("spawn", args, hub_cache))
+ return Process()
+
+ monkeypatch.setattr("core.inference.stt_download_worker.spawn_download", spawn)
+ monkeypatch.setattr("core.inference.stt_download_worker.reap_download", lambda _process: b"")
+ monkeypatch.setattr(
+ stt_mtmd_sidecar,
+ "_cached_model_paths",
+ lambda model, *, hub_cache, revision: (
+ events.append(("lookup", model, hub_cache, revision)) or ("model", "mmproj")
+ ),
+ )
+ monkeypatch.setattr(
+ stt_mtmd_sidecar,
+ "_write_revision_record",
+ lambda repo, rev: events.append(("record", repo, rev)),
+ )
+
+ state = stt_mtmd_sidecar._MtmdDownloadState()
+ state._hub_cache = tmp_path
+ state._run(model_id, None)
+
+ spawn_event = next(event for event in events if event[0] == "spawn")
+ assert spawn_event[2] == tmp_path
+ assert spawn_event[1] == [
+ "--repo-id",
+ spec.repo,
+ "--revision",
+ revision,
+ "--filename",
+ spec.model_file,
+ "--filename",
+ spec.mmproj_file,
+ ]
+ assert [event[0] for event in events] == [
+ "claim",
+ "prepare",
+ "spawn",
+ "lookup",
+ "record",
+ "release",
+ ]
+
+
+def test_ggml_metadata_revision_pins_progress_worker_and_cached_lookup(monkeypatch, tmp_path):
+ model_id = "tiny"
+ repo = stt_ggml_sidecar.GGML_STT_REPOS[model_id]
+ filename = stt_ggml_sidecar.GGML_STT_MODELS[model_id]
+ revision_a = "a" * 40
+ revision_b = "b" * 40
+ entry = _repo_dir(tmp_path, repo)
+ blobs = entry / "blobs"
+ blobs.mkdir(parents = True)
+ (blobs / "etag-a.incomplete").write_bytes(b"a" * 25)
+ (blobs / "etag-b").write_bytes(b"b" * 100)
+ observed = {}
+ cached_model_path = stt_ggml_sidecar._cached_model_path
+
+ class Registry:
+ @staticmethod
+ def release_repository_owner(_repo, _owner):
+ return True
+
+ class Process:
+ returncode = 0
+
+ @staticmethod
+ def poll():
+ return 0
+
+ state = stt_ggml_sidecar._GgmlDownloadState()
+ state._model_id = model_id
+ state._hub_cache = tmp_path
+ monkeypatch.setattr(
+ stt_ggml_sidecar,
+ "_claim_stt_repository",
+ lambda _repo: (Registry(), object()),
+ )
+ monkeypatch.setattr(stt_ggml_sidecar, "_prepare_stt_cache_for_http", lambda *_args: None)
+ monkeypatch.setattr(
+ "huggingface_hub.get_hf_file_metadata",
+ lambda *_args, **_kwargs: SimpleNamespace(
+ size = 100,
+ etag = "etag-a",
+ commit_hash = revision_a,
+ ),
+ )
+ monkeypatch.setattr(
+ "huggingface_hub.hf_hub_url",
+ lambda *_args, **_kwargs: f"https://example/{repo}/{filename}",
+ )
+
+ def spawn(
+ args,
+ hf_token = None,
+ *,
+ hub_cache = None,
+ ):
+ observed["args"] = args
+ observed["hub_cache"] = hub_cache
+ observed["progress"] = state._downloaded_bytes()
+ observed["mutable_main"] = revision_b
+ return Process()
+
+ def lookup(
+ model,
+ *,
+ hub_cache = None,
+ revision = None,
+ ):
+ observed["lookup"] = (model, hub_cache, revision)
+ return str(entry / "snapshots" / revision / filename)
+
+ monkeypatch.setattr("core.inference.stt_download_worker.spawn_download", spawn)
+ monkeypatch.setattr("core.inference.stt_download_worker.reap_download", lambda _process: b"")
+ monkeypatch.setattr(stt_ggml_sidecar, "_cached_model_path", lookup)
+ monkeypatch.setattr(
+ stt_ggml_sidecar,
+ "_write_revision_record",
+ lambda recorded_repo, revision: observed.update(record = (recorded_repo, revision)),
+ )
+
+ state._run(model_id, None)
+
+ assert observed["args"] == [
+ "--repo-id",
+ repo,
+ "--revision",
+ revision_a,
+ "--filename",
+ filename,
+ ]
+ assert observed["hub_cache"] == tmp_path
+ assert observed["progress"] == 25
+ assert observed["mutable_main"] == revision_b
+ assert observed["lookup"] == (model_id, tmp_path, revision_a)
+ assert observed["record"] == (repo, revision_a)
+
+ monkeypatch.setattr(
+ stt_ggml_sidecar,
+ "_read_revision_record",
+ lambda recorded_repo: observed["record"][1] if recorded_repo == repo else None,
+ )
+ monkeypatch.setattr(
+ "huggingface_hub.hf_hub_download",
+ lambda **kwargs: observed.update(later_lookup = kwargs) or "/cached/model.bin",
+ )
+ assert cached_model_path(model_id, hub_cache = tmp_path) == "/cached/model.bin"
+ assert observed["later_lookup"]["revision"] == revision_a
+
+
+def test_ggml_metadata_failure_spawns_nothing_and_leaks_no_owner(monkeypatch, tmp_path):
+ events = []
+
+ def metadata_failure(*_args, **_kwargs):
+ raise RuntimeError("metadata unavailable")
+
+ monkeypatch.setattr("huggingface_hub.get_hf_file_metadata", metadata_failure)
+ monkeypatch.setattr("huggingface_hub.hf_hub_url", lambda *_args, **_kwargs: "https://example")
+ monkeypatch.setattr(
+ stt_ggml_sidecar,
+ "_claim_stt_repository",
+ lambda _repo: events.append("claim"),
+ )
+ monkeypatch.setattr(
+ stt_download_worker,
+ "spawn_download",
+ lambda *_args, **_kwargs: events.append("spawn"),
+ )
+
+ state = stt_ggml_sidecar._GgmlDownloadState()
+ state._run("tiny", None, hub_cache = tmp_path)
+
+ assert events == []
+ assert state.status()["error"] == "Download failed for 'tiny'."
+
+
+def test_ggml_stale_record_falls_back_to_active_cache_main(monkeypatch, tmp_path):
+ model_id = "tiny"
+ repo = stt_ggml_sidecar.GGML_STT_REPOS[model_id]
+ filename = stt_ggml_sidecar.GGML_STT_MODELS[model_id]
+ stale_revision = "a" * 40
+ active_revision = "b" * 40
+ entry = _repo_dir(tmp_path, repo)
+ (entry / "refs").mkdir(parents = True)
+ (entry / "refs" / "main").write_text(active_revision, encoding = "utf-8")
+ cached_file = entry / "snapshots" / active_revision / filename
+ cached_file.parent.mkdir(parents = True)
+ cached_file.write_bytes(b"model")
+ records = []
+
+ monkeypatch.setattr(stt_ggml_sidecar, "_read_revision_record", lambda _repo: stale_revision)
+ monkeypatch.setattr(
+ stt_ggml_sidecar,
+ "_write_revision_record",
+ lambda recorded_repo, revision: records.append((recorded_repo, revision)),
+ )
+
+ assert stt_ggml_sidecar._cached_model_path(model_id, hub_cache = tmp_path) == str(cached_file)
+ assert records == [(repo, active_revision)]
+
+
+def test_mtmd_stale_record_falls_back_to_one_active_cache_revision(monkeypatch, tmp_path):
+ model_id = "qwen3-asr-0.6b"
+ spec = stt_mtmd_sidecar.MTMD_STT_MODELS[model_id]
+ stale_revision = "c" * 40
+ active_revision = "d" * 40
+ entry = _repo_dir(tmp_path, spec.repo)
+ (entry / "refs").mkdir(parents = True)
+ (entry / "refs" / "main").write_text(active_revision, encoding = "utf-8")
+ snapshot = entry / "snapshots" / active_revision
+ snapshot.mkdir(parents = True)
+ model_file = snapshot / spec.model_file
+ mmproj_file = snapshot / spec.mmproj_file
+ model_file.write_bytes(b"model")
+ mmproj_file.write_bytes(b"mmproj")
+ records = []
+
+ monkeypatch.setattr(stt_mtmd_sidecar, "_read_revision_record", lambda _repo: stale_revision)
+ monkeypatch.setattr(
+ stt_mtmd_sidecar,
+ "_write_revision_record",
+ lambda recorded_repo, revision: records.append((recorded_repo, revision)),
+ )
+
+ assert stt_mtmd_sidecar._cached_model_paths(model_id, hub_cache = tmp_path) == (
+ str(model_file),
+ str(mmproj_file),
+ )
+ assert records == [(spec.repo, active_revision)]
+
+
+def test_start_captures_the_configured_hub_cache_once(monkeypatch, tmp_path):
+ calls = []
+ monkeypatch.setattr(
+ stt_sidecar,
+ "_capture_stt_hub_cache",
+ lambda: (calls.append("capture") or tmp_path),
+ )
+ state = stt_sidecar._SnapshotDownloadState()
+ observed = []
+ monkeypatch.setattr(
+ state,
+ "_run",
+ lambda repo, token, revision: observed.append((repo, state._hub_cache)),
+ )
+
+ state.start("tiny")
+ state._thread.join(timeout = 5)
+
+ assert calls == ["capture"]
+ assert observed == [(stt_sidecar.STT_MODELS["tiny"], tmp_path)]
+
+
+def test_live_studio_cache_wins_over_the_stale_startup_environment(monkeypatch, tmp_path):
+ old_cache = tmp_path / "old" / "hub"
+ new_cache = tmp_path / "new" / "hub"
+ monkeypatch.setenv("HF_HUB_CACHE", str(old_cache))
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.get_hf_cache_paths",
+ lambda: SimpleNamespace(hub_cache = new_cache, source = "studio"),
+ )
+
+ assert stt_sidecar._capture_stt_hub_cache() == new_cache
+ assert stt_sidecar._active_hf_hub_cache() == new_cache
+
+
+ "state_factory",
+ (
+ stt_sidecar._SnapshotDownloadState,
+ stt_ggml_sidecar._GgmlDownloadState,
+ stt_mtmd_sidecar._MtmdDownloadState,
+ ),
+)
+def test_each_stt_download_path_terminates_its_worker_on_cancel(state_factory):
+ class Thread:
+ @staticmethod
+ def is_alive():
+ return True
+
+ class Process:
+ terminated = False
+
+ @staticmethod
+ def poll():
+ return None
+
+ def terminate(self):
+ self.terminated = True
+
+ state = state_factory()
+ process = Process()
+ state._thread = Thread()
+ state._process = process
+
+ assert state.cancel() is True
+ assert state._cancelled is True
+ assert process.terminated is True
diff --git a/studio/backend/tests/test_stt_review_fixes_2.py b/studio/backend/tests/test_stt_review_fixes_2.py
index 8dfa6d61cff..cf725b1f2f3 100644
--- a/studio/backend/tests/test_stt_review_fixes_2.py
+++ b/studio/backend/tests/test_stt_review_fixes_2.py
@@ -234,7 +234,12 @@ def test_download_pins_revision_and_limits_patterns(monkeypatch):
def communicate(self):
return (None, b"")
- def fake_spawn_download(args, hf_token = None):
+ def fake_spawn_download(
+ args,
+ hf_token = None,
+ *,
+ hub_cache = None,
+ ):
# The transfer moved to a worker process; pinning is now in its argv.
remaining = iter(args)
patterns: list[str] = []
@@ -242,7 +247,7 @@ def test_download_pins_revision_and_limits_patterns(monkeypatch):
value = next(remaining)
if flag == "--revision":
captured["revision"] = value
- elif flag == "--allow-pattern":
+ elif flag == "--filename":
patterns.append(value)
captured["allow_patterns"] = patterns
return _FakeProcess()
diff --git a/studio/backend/tests/test_stt_review_fixes_4.py b/studio/backend/tests/test_stt_review_fixes_4.py
index fdbf6cff220..c7600dae35f 100644
--- a/studio/backend/tests/test_stt_review_fixes_4.py
+++ b/studio/backend/tests/test_stt_review_fixes_4.py
@@ -333,18 +333,18 @@ def test_unknown_model_is_never_memoised(monkeypatch):
def test_download_status_reports_progress_without_holding_the_lock():
- """_cache_bytes() walks the cache; a cancel must not queue behind it."""
+ """_downloaded_bytes() stats the cache; a cancel must not queue behind it."""
state = mtmd_mod._MtmdDownloadState()
observed = []
- def slow_cache_bytes(model_id = None):
+ def slow_downloaded_bytes(*_args, **_kwargs):
# The lock must be free while this runs.
observed.append(state._lock.acquire(blocking = False))
if observed[-1]:
state._lock.release()
return 1
- state._cache_bytes = slow_cache_bytes
+ state._downloaded_bytes = slow_downloaded_bytes
state._model_id = "qwen3-asr-0.6b"
state._thread = threading.Thread(target = lambda: time.sleep(0.5), daemon = True)
state._thread.start()
diff --git a/studio/backend/tests/test_stt_sidecar.py b/studio/backend/tests/test_stt_sidecar.py
index 477ba018bea..f6ab3abd07f 100644
--- a/studio/backend/tests/test_stt_sidecar.py
+++ b/studio/backend/tests/test_stt_sidecar.py
@@ -480,9 +480,11 @@ def test_load_uses_model_hub_cache_without_implicit_download(monkeypatch):
WhisperSttSidecar(keep_alive_seconds = 0).load("small")
+ # str(Path(...)), so the separator is the platform's.
+ cached = str(Path("/cached/model"))
assert {(kind, repo) for kind, repo, _ in calls} == {
- ("processor", "/cached/model"),
- ("model", "/cached/model"),
+ ("processor", cached),
+ ("model", cached),
}
# Never fetch weights implicitly; the Model Hub owns downloads.
assert all(kwargs.get("local_files_only") is True for _, _, kwargs in calls)
@@ -1122,7 +1124,7 @@ class _FakeDownloadProcess:
def _worker_args(args) -> dict:
"""Parse the download worker's argv into the fields tests assert on."""
- parsed: dict = {"allow_patterns": []}
+ parsed: dict = {"filenames": []}
remaining = iter(args)
for flag in remaining:
value = next(remaining)
@@ -1131,9 +1133,7 @@ def _worker_args(args) -> dict:
elif flag == "--revision":
parsed["revision"] = value
elif flag == "--filename":
- parsed["filename"] = value
- elif flag == "--allow-pattern":
- parsed["allow_patterns"].append(value)
+ parsed["filenames"].append(value)
return parsed
@@ -1156,7 +1156,12 @@ def test_download_metadata_and_snapshot_use_the_same_revision(monkeypatch, tmp_p
calls.append(("info", repo, kwargs))
return SimpleNamespace(sha = revision, siblings = siblings)
- def fake_spawn_download(args, hf_token = None):
+ def fake_spawn_download(
+ args,
+ hf_token = None,
+ *,
+ hub_cache = None,
+ ):
calls.append(("snapshot", _worker_args(args)))
return _FakeDownloadProcess()
@@ -1180,8 +1185,8 @@ def test_download_metadata_and_snapshot_use_the_same_revision(monkeypatch, tmp_p
)
assert calls[1][0] == "snapshot"
assert calls[1][1]["revision"] == revision
- assert "model.safetensors" in calls[1][1]["allow_patterns"]
- assert "pytorch_model.bin" not in calls[1][1]["allow_patterns"]
+ assert "model.safetensors" in calls[1][1]["filenames"]
+ assert "pytorch_model.bin" not in calls[1][1]["filenames"]
def test_download_status_is_idle_before_any_download():
diff --git a/studio/frontend/src/features/hub/download-manager/api.ts b/studio/frontend/src/features/hub/download-manager/api.ts
index 6876e1be61f..5ec3b7996b0 100644
--- a/studio/frontend/src/features/hub/download-manager/api.ts
+++ b/studio/frontend/src/features/hub/download-manager/api.ts
@@ -46,7 +46,11 @@ export interface DownloadJobStatus {
generation?: number;
}
-export type DownloadStartState = DownloadJobState | "deleting";
+// "repository_owned": a dictation model download holds this repository's cache.
+export type DownloadStartState =
+ | DownloadJobState
+ | "deleting"
+ | "repository_owned";
export interface DownloadStartResult {
state: DownloadStartState;
diff --git a/studio/frontend/src/features/hub/download-manager/download-api-adapter.ts b/studio/frontend/src/features/hub/download-manager/download-api-adapter.ts
index ec73c58ba8b..9947c5e7fe2 100644
--- a/studio/frontend/src/features/hub/download-manager/download-api-adapter.ts
+++ b/studio/frontend/src/features/hub/download-manager/download-api-adapter.ts
@@ -222,6 +222,8 @@ export function describeUnacceptedStart(state: DownloadStartState): string {
switch (state) {
case "deleting":
return "This repository is being removed. Try again once it finishes.";
+ case "repository_owned":
+ return "A dictation model download is using this repository. Try again once it finishes.";
case "running":
case "cancelling":
return "Another download for this repository is already in progress. Wait for it to finish or cancel it first.";