Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: stop keeping download partials no huggingface_hub can resume (#8350)
Daniel Hanfbf18cb4bf8b
diff --git a/studio/backend/hub/services/download_lifecycle.py b/studio/backend/hub/services/download_lifecycle.pyindex da23a91064e..f549002012c 100644--- a/studio/backend/hub/services/download_lifecycle.py+++ b/studio/backend/hub/services/download_lifecycle.py@@ -776,6 +776,34 @@ def _repo_bytes_on_disk(repo_type, repo_id: str, cache_dir) -> "Optional[int]":return None if state is None else int(state[0])+def _sweep_ownership(metadata, own_blob_hashes, owned_for_sweep, repo_type: str, repo_id: str):+ """(owned hashes, owns-everything) for a job that has just reached a terminal state.++ A variant job whose API-side hash pre-resolution failed carries a non-null variant with an+ EMPTY hash set, so neither claim applies and its own fresh partial waits out a grace that+ exists to guess at a writer we already know is dead. The worker wrote a manifest naming the+ files it fetched, so read the ownership back off that.+ """+ if own_blob_hashes is None:+ return None, True+ if owned_for_sweep:+ return frozenset(owned_for_sweep), False+ from hub.utils import download_manifest++ manifest = download_manifest.read_manifest(+ repo_type,+ repo_id,+ getattr(metadata, "variant", None),+ hub_cache = getattr(metadata, "hub_cache", None),+ )+ recovered = {+ expected.sha256+ for expected in getattr(manifest, "expected_files", ()) or ()+ if getattr(expected, "sha256", None)+ }+ return frozenset(recovered), False++def _job_bytes_on_disk(repo_type, repo_id: str, cache_dir, blob_hashes) -> "Optional[int]":"""Bytes THIS job owns, or None when unmeasurable.@@ -926,6 +954,13 @@ def register_worker(if getattr(_metadata, "variant", None)else None)+ # Companions (a shared mmproj) live only in the progress set, and this worker was writing+ # one when it died just as much as it was writing the main quant.+ _owned_for_sweep = (+ getattr(_metadata, "progress_blob_hashes", None) or _own_blob_hashes+ if _own_blob_hashes is not None+ else None+ )# Sampled before the worker can write, so "did this job move bytes over Xet" is answerable on# exit. launch_worker samples BEFORE spawn(); sampling here would race a fast child that already# finalized its blobs, making a real transfer look like a no-op and leaving the streak uncleared.@@ -1099,6 +1134,43 @@ def register_worker()except Exception:logger.exception("post-finalize marker cleanup failed for %s", key)+ try:+ # The second look for anything prepare_cache_for_transport spared as too+ # recently written. A download runs for long enough that a partial orphaned+ # before it started is well past the grace by now, and the peer set still+ # shields a same-repo variant writing a shared companion right now.+ # This job's own blobs skip the abandonment wait, but ONLY once the job is+ # genuinely finished. A cancelled worker's partial was written seconds ago, so+ # the wait would strand it for the rest of the session; and its writer has just+ # been reaped, which is the very thing the wait is there to guess at. A retry+ # relaunched above leaves the job active, and then it is not ours to assume.+ terminal = registry.get_job(key).state not in ("running", "cancelling")+ _owned, _owns_all = (+ _sweep_ownership(+ _metadata, _own_blob_hashes, _owned_for_sweep, repo_type, repo_id+ )+ if terminal+ else (None, False)+ )+ swept = download_registry.sweep_abandoned_partials(+ repo_type,+ repo_id,+ protected_blob_hashes = registry.peer_blob_hashes(key),+ # A companion a sibling is writing right now is still held back by+ # peer_blob_hashes above, whatever this job believes it owns.+ owned_blob_hashes = _owned,+ owns_all_blobs = _owns_all,+ # The cache this worker actually wrote to. Resolving the live one instead+ # would miss the orphan whenever the download location changed mid-run,+ # and sweep a cache this job never touched.+ root = _cache_dir,+ )+ if swept:+ logger.info(+ "%sswept %d unresumable partial blob(s) for %s", log_prefix, swept, repo_id+ )+ except Exception:+ logger.exception("abandoned-partial sweep failed for %s", key)finally:hf_cache_scan.invalidate_hf_cache_scans()diff --git a/studio/backend/hub/services/models/downloads.py b/studio/backend/hub/services/models/downloads.pyindex 6ed216389c6..6802f091d92 100644--- a/studio/backend/hub/services/models/downloads.py+++ b/studio/backend/hub/services/models/downloads.py@@ -452,14 +452,23 @@ def _variant_transport_status(repo_id: str, variant: str, hf_token: Optional[strrepo_id,variant,)- has_matching_incomplete = bool(- incomplete_hashes and variant_hashes and incomplete_hashes.intersection(variant_hashes)+ # A partial only counts toward "resumable" while a writer that reopens it is installed,+ # since the UI turns the flag into "Resume with HTTP to keep the progress you already+ # have" and the next download start sweeps whatever cannot be reopened.+ resumable_hashes = download_registry.incomplete_blob_hashes(+ "model",+ repo_id,+ active_only = True,+ resumable_only = True,+ )+ has_resumable_incomplete = bool(+ resumable_hashes and variant_hashes and resumable_hashes.intersection(variant_hashes))return {"has_partial": has_partial,"last_transport": last_transport,"resumable": (- has_matching_incomplete and last_transport == download_registry.TRANSPORT_HTTP+ has_resumable_incomplete and last_transport == download_registry.TRANSPORT_HTTP),}diff --git a/studio/backend/hub/services/snapshot_progress.py b/studio/backend/hub/services/snapshot_progress.pyindex d93e0b23195..8112852d487 100644--- a/studio/backend/hub/services/snapshot_progress.py+++ b/studio/backend/hub/services/snapshot_progress.py@@ -506,9 +506,11 @@ def compute_snapshot_progress(variant_file_set_unknown = variant is not None and not expected_hashes# Resolved at most once, and only if a reading gets far enough to need it.metadata_files: "_Lazy[tuple[download_manifest.ExpectedFile, ...]]" = _Lazy(- lambda: tuple(expected_files_resolver(repo_id, hf_token))- if expected_files_resolver is not None- else ()+ lambda: (+ tuple(expected_files_resolver(repo_id, hf_token))+ if expected_files_resolver is not None+ else ()+ ))readings: list[tuple[int, int, Optional[str], bool, Optional[bool]]] = []@@ -598,6 +600,17 @@ def compute_snapshot_progress(# swept -- and an orphan outlives the process that would have unlinked it on the way out.for blob_hash in completed_hashes:partial_bytes.pop(blob_hash, None)+ # Largest wins, deliberately, even though a killed attempt's partial can sit beside its+ # replacement's under the same etag. Preferring the freshest mtime reads better against+ # a corpse but oscillates between two GENUINELY live writers, which is what a broken+ # advisory lock produces: each write makes a different one newest, so the bar would+ # jump between the leader and the straggler.+ #+ # A corpse is not this reading's problem to solve, because it should not outlive the+ # job that made it: a terminal job sweeps its own blobs without waiting out the+ # abandonment grace, and a backend that died before it could is caught at boot. If one+ # survives both (an unrelated client holding the blob lock over it) the bar over-reads+ # until the next sweep, which is a smaller wrong than a reading that will not sit still.in_progress_bytes = sum(partial_bytes.values())snapshot_dirs: "_Lazy[list[Path]]" = _Lazy(lambda entry = entry: _retained_snapshot_dirs(entry)diff --git a/studio/backend/hub/tests/test_model_services.py b/studio/backend/hub/tests/test_model_services.pyindex 3678078836f..f7f57f97520 100644--- a/studio/backend/hub/tests/test_model_services.py+++ b/studio/backend/hub/tests/test_model_services.py@@ -4849,6 +4849,10 @@ def test_prepare_cache_for_transport_purges_cross_transport_companion(monkeypatcdef test_prepare_cache_for_transport_preserves_same_transport_companion(monkeypatch, tmp_path):+ """Only a hub that can still append to the partial earns the same-transport reprieve."""+ # The purge asks partial_is_resumable, so patching the hub-version helper it wraps would+ # be a no-op here.+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name: True)blobs = _vision_cache_root(monkeypatch, tmp_path)companion = frozenset({"shared-mmproj"})@@ -4860,7 +4864,11 @@ def test_prepare_cache_for_transport_preserves_same_transport_companion(monkeypaonly_blob_hashes = frozenset({"q4-main"}),companion_blob_hashes = companion,)- (blobs / "shared-mmproj.incomplete").write_bytes(b"resumable")+ partial = blobs / "shared-mmproj.incomplete"+ partial.write_bytes(b"resumable")+ # Aged past the abandonment grace, so the reprieve is what preserves it, not its freshness.+ old = time.time() - download_registry.ABANDONED_PARTIAL_SECONDS - 60+ os.utime(partial, (old, old))purged = download_registry.prepare_cache_for_transport("model",@@ -4872,7 +4880,7 @@ def test_prepare_cache_for_transport_preserves_same_transport_companion(monkeypa)assert purged == 0- assert (blobs / "shared-mmproj.incomplete").exists()+ assert partial.exists()def test_prepare_cache_for_transport_protects_peer_companion(monkeypatch, tmp_path):diff --git a/studio/backend/hub/tests/test_process_unique_incomplete_repro.py b/studio/backend/hub/tests/test_process_unique_incomplete_repro.pyindex dfe5eb39ceb..075368f4f5f 100644--- a/studio/backend/hub/tests/test_process_unique_incomplete_repro.py+++ b/studio/backend/hub/tests/test_process_unique_incomplete_repro.py@@ -3,6 +3,8 @@"""Focused reproduction for Hugging Face's process-unique partial filenames."""+import os+import timefrom types import SimpleNamespacefrom hub.services import snapshot_progress@@ -46,6 +48,19 @@ def test_registry_groups_duplicate_process_unique_writers_by_blob(monkeypatch, t)assert download_registry.incomplete_blob_hashes("model", "Org/Model") == {_BLOB_HASH}+ # Nonce partials are refetched rather than resumed, so none of those bytes are bytes the+ # next attempt gets to skip. Their grouping is still asserted, one blob not two.+ assert (+ download_registry.existing_blob_bytes(+ "model",+ "Org/Model",+ frozenset({_BLOB_HASH}),+ )+ == 0+ )++ # The same grouping where the bytes DO count: a legacy partial under a writer that appends.+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name: True)assert (download_registry.existing_blob_bytes("model",@@ -359,3 +374,38 @@ def test_finalized_blob_supersedes_an_orphaned_partial(monkeypatch, tmp_path):assert result["downloaded_bytes"] == 100assert result["complete_on_disk"] is Trueassert result["progress"] == 1.0+++def test_progress_is_stable_across_which_racer_wrote_last(monkeypatch, tmp_path):+ """Two genuinely live writers must not make the bar jump between leader and straggler."""+ entry = tmp_path / "models--Org--Model-GGUF"+ blobs = entry / "blobs"+ blobs.mkdir(parents = True)+ leader = blobs / f"{_BLOB_HASH}.11111111.incomplete"+ leader.write_bytes(b"x" * 80)+ straggler = blobs / f"{_BLOB_HASH}.22222222.incomplete"+ straggler.write_bytes(b"x" * 10)++ monkeypatch.setattr(+ snapshot_progress,+ "preferred_repo_cache_dirs",+ lambda *_args, **_kwargs: [entry],+ )++ def _read():+ return snapshot_progress.compute_snapshot_progress(+ repo_type = "model",+ repo_id = "Org/Model-GGUF",+ job_key = "model:org/model-gguf#q4_k_m",+ expected_bytes = 100,+ hf_token = None,+ registry = _running_registry(),+ metadata_resolver = lambda *_args: (100, frozenset({_BLOB_HASH})),+ variant = "Q4_K_M",+ )++ now = time.time()+ for newest in (leader, straggler):+ # Whichever of them happened to write last, the answer has to be the same one.+ os.utime(newest, (now, now))+ assert _read()["downloaded_bytes"] == 80diff --git a/studio/backend/hub/tests/test_unresumable_partial_purge.py b/studio/backend/hub/tests/test_unresumable_partial_purge.pynew file mode 100644index 00000000000..13cab815235--- /dev/null+++ b/studio/backend/hub/tests/test_unresumable_partial_purge.py@@ -0,0 +1,814 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A partial no writer can reopen is litter, but only once nothing is writing it."""++import json+import os+import threading+import time++import pytest++from hub.utils import download_registry, hf_cache_state+++_MAIN = "a" * 64+_PEER = "b" * 64+_LEGACY_PARTIAL = f"{_MAIN}{hf_cache_state.INCOMPLETE_SUFFIX}"+_NONCE_PARTIAL = f"{_MAIN}.deadbeef{hf_cache_state.INCOMPLETE_SUFFIX}"+++def blobs(monkeypatch, tmp_path):+ root = tmp_path / "hub"+ blobs_dir = root / "models--Org--Model" / "blobs"+ blobs_dir.mkdir(parents = True)+ monkeypatch.setenv("HF_HUB_CACHE", str(root))+ monkeypatch.setattr(download_registry, "hf_cache_root", lambda **_kwargs: root)+ # The cache-dir iterators resolve the root through hf_cache_state, not the caller.+ monkeypatch.setattr(hf_cache_state, "hf_cache_root", lambda **_kwargs: root)+ monkeypatch.setattr(hf_cache_state, "hf_cache_roots", lambda *_a, **_k: [root])+ return blobs_dir+++def _join_background_sweep():+ """The all-caches pass is threaded so it cannot delay startup; wait for it here."""+ for thread in threading.enumerate():+ if thread.name == "hf-abandoned-partial-sweep":+ thread.join(10)+++def _abandon(path):+ """Backdate a partial past the grace, as an abandoned one would be."""+ old = time.time() - download_registry.ABANDONED_PARTIAL_SECONDS - 60+ os.utime(path, (old, old))+ return path+++def _prepare(**kwargs):+ return download_registry.prepare_cache_for_transport(+ "model",+ "Org/Model",+ download_registry.TRANSPORT_HTTP,+ "Q4_K_M",+ only_blob_hashes = frozenset({_MAIN}),+ **kwargs,+ )+++ "hf_version, resumable",+ [+ ("0.36.2", True),+ ("1.17.0", True),+ ("1.18.0", False),+ ("1.23.0", False),+ ("1.27.0", False),+ ("2.0.0.dev0", False),+ ("not-a-version", True),+ ],+)+def test_writer_resumability_tracks_the_installed_version(monkeypatch, hf_version, resumable):+ """1.18 is the line: before it a partial is appended to, after it a new file is written."""+ monkeypatch.setattr("huggingface_hub.__version__", hf_version, raising = False)+ hf_cache_state.hf_partials_are_resumable.cache_clear()+ try:+ assert hf_cache_state.hf_partials_are_resumable() is resumable+ finally:+ hf_cache_state.hf_partials_are_resumable.cache_clear()+++def test_a_nonce_partial_is_unresumable_even_under_a_legacy_writer(monkeypatch):+ """The nonce path is private to the process that made it; nothing reopens it by name."""+ monkeypatch.setattr(hf_cache_state, "hf_partials_are_resumable", lambda: True)++ assert hf_cache_state.partial_is_resumable(_LEGACY_PARTIAL) is True+ assert hf_cache_state.partial_is_resumable(_NONCE_PARTIAL) is False+++def test_unresumable_partial_is_purged_despite_a_matching_marker(monkeypatch, blobs):+ """The marker vouches for provenance, which is worth nothing with no resumer left."""+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name: False)+ _prepare() # writes the http marker+ partial = blobs / _NONCE_PARTIAL+ partial.write_bytes(b"x" * 25)+ _abandon(partial)++ assert _prepare() == 1+ assert not partial.exists()+++def test_resumable_partial_survives_a_matching_marker(monkeypatch, blobs):+ """Older hubs still append to it, so deleting it would throw away real bytes."""+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name: True)+ _prepare()+ partial = blobs / _LEGACY_PARTIAL+ partial.write_bytes(b"x" * 25)+ _abandon(partial)++ assert _prepare() == 0+ assert partial.exists()+++def test_a_partial_still_being_written_is_left_alone(monkeypatch, blobs):+ """It may belong to a client this backend's peer registry cannot see."""+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name: False)+ _prepare()+ partial = blobs / _NONCE_PARTIAL+ partial.write_bytes(b"x" * 25) # mtime is now, as a live writer's would be++ assert _prepare() == 0+ assert partial.exists()+++def test_a_mismatched_marker_still_purges_without_waiting(monkeypatch, blobs):+ """That purge stops a corrupt append, so it cannot defer to a grace period."""+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name: True)+ download_registry.prepare_cache_for_transport(+ "model",+ "Org/Model",+ download_registry.TRANSPORT_XET,+ "Q4_K_M",+ only_blob_hashes = frozenset({_MAIN}),+ )+ partial = blobs / _LEGACY_PARTIAL+ partial.write_bytes(b"x" * 25)++ assert _prepare() == 1+ assert not partial.exists()+++def test_a_peer_being_written_is_still_protected(monkeypatch, blobs):+ """Unresumable is not a licence to delete a blob another download is writing now."""+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name: False)+ _prepare()+ mine = blobs / _NONCE_PARTIAL+ mine.write_bytes(b"x" * 25)+ _abandon(mine)+ peer = blobs / f"{_PEER}.feedface{hf_cache_state.INCOMPLETE_SUFFIX}"+ peer.write_bytes(b"x" * 25)+ _abandon(peer)++ purged = download_registry.prepare_cache_for_transport(+ "model",+ "Org/Model",+ download_registry.TRANSPORT_HTTP,+ "Q4_K_M",+ only_blob_hashes = frozenset({_MAIN, _PEER}),+ protected_blob_hashes = frozenset({_PEER}),+ )++ assert purged == 1+ assert not mine.exists()+ assert peer.exists()+++def test_transport_status_does_not_promise_a_resume_it_cannot_keep(monkeypatch, blobs):+ """``resumable`` drives a dialog offering to keep existing progress."""+ monkeypatch.setattr(download_registry, "read_active_transport_marker", lambda *_a, **_k: "http")+ (blobs / _NONCE_PARTIAL).write_bytes(b"x" * 25)++ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name: True)+ assert download_registry.is_resumable_partial("model", "Org/Model") is True++ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name: False)+ assert download_registry.is_resumable_partial("model", "Org/Model") is False+++def test_a_skipped_partial_is_swept_once_it_ages_out(monkeypatch, blobs):+ """The start-of-download skip is not the last word on an orphan."""+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name: False)+ _prepare()+ partial = blobs / _NONCE_PARTIAL+ partial.write_bytes(b"x" * 25)++ # Too fresh at download start, so prepare leaves it alone.+ assert _prepare() == 0+ assert partial.exists()++ # By the time that download reaches a terminal state the grace has elapsed.+ _abandon(partial)+ assert download_registry.sweep_abandoned_partials("model", "Org/Model") == 1+ assert not partial.exists()+++def test_the_sweep_still_spares_a_live_writer_and_a_peer(monkeypatch, blobs):+ """A terminal state for one job says nothing about what another is writing."""+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name: False)+ live = blobs / _NONCE_PARTIAL+ live.write_bytes(b"x" * 25)+ peer = blobs / f"{_PEER}.feedface{hf_cache_state.INCOMPLETE_SUFFIX}"+ peer.write_bytes(b"x" * 25)+ _abandon(peer)++ swept = download_registry.sweep_abandoned_partials(+ "model",+ "Org/Model",+ protected_blob_hashes = frozenset({_PEER}),+ )++ assert swept == 0+ assert live.exists()+ assert peer.exists()+++def test_a_locked_blob_is_spared_however_stale_it_looks(monkeypatch, blobs):+ """A writer stalled past the grace still holds the lock, and still owns the file."""+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name: False)+ _prepare()+ partial = blobs / _NONCE_PARTIAL+ partial.write_bytes(b"x" * 25)+ _abandon(partial)++ monkeypatch.setattr(download_registry, "blob_download_lock_held", lambda *_a: True)+ assert _prepare() == 0+ assert partial.exists()++ monkeypatch.setattr(download_registry, "blob_download_lock_held", lambda *_a: False)+ assert _prepare() == 1+ assert not partial.exists()+++def test_the_lock_probe_reads_the_layout_hf_writes(tmp_path):+ """<hub cache>/.locks/<repo dir>/<etag>.lock, and no lock file means nobody is writing."""+ from filelock import FileLock++ entry = tmp_path / "models--Org--Model"+ lock_path = tmp_path / ".locks" / "models--Org--Model" / f"{_MAIN}.lock"+ lock_path.parent.mkdir(parents = True)++ assert hf_cache_state.blob_download_lock_held(entry, _MAIN) is False++ lock_path.touch()+ assert hf_cache_state.blob_download_lock_held(entry, _MAIN) is False++ with FileLock(str(lock_path), timeout = 0):+ assert hf_cache_state.blob_download_lock_held(entry, _MAIN) is True+++def test_unresumable_bytes_are_not_credited_against_the_disk_check(monkeypatch, blobs):+ """_preflight_disk_space subtracts this, so crediting a refetch can approve a full disk."""+ (blobs / _NONCE_PARTIAL).write_bytes(b"x" * 25)+ monkeypatch.setattr(+ download_registry,+ "iter_destructive_repo_cache_dirs",+ lambda *_a, **_k: [blobs.parent],+ )++ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name: False)+ assert download_registry.existing_blob_bytes("model", "Org/Model", frozenset({_MAIN})) == 0++ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name: True)+ assert download_registry.existing_blob_bytes("model", "Org/Model", frozenset({_MAIN})) == 25+++def test_a_finalized_blob_still_counts_against_the_disk_check(monkeypatch, blobs):+ """Only partials are in question; a finished blob is bytes nobody refetches."""+ (blobs / _MAIN).write_bytes(b"x" * 25)+ monkeypatch.setattr(+ download_registry,+ "iter_destructive_repo_cache_dirs",+ lambda *_a, **_k: [blobs.parent],+ )+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name: False)++ assert download_registry.existing_blob_bytes("model", "Org/Model", frozenset({_MAIN})) == 25+++def test_startup_sweep_does_not_depend_on_a_breadcrumb(monkeypatch, tmp_path, blobs):+ """finalize_worker_exit drops the breadcrumb, so the boot sweep cannot be driven off one."""+ workers = tmp_path / "workers"+ workers.mkdir() # deliberately empty, as it is once drop_process has run+ partial = blobs / _NONCE_PARTIAL+ partial.write_bytes(b"x" * 25)+ _abandon(partial)++ monkeypatch.setattr(download_registry.state_dir, "workers_dir", lambda: workers)+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name: False)+ monkeypatch.setattr(+ download_registry, "hf_cache_roots", lambda *_a, **_k: [blobs.parent.parent]+ )++ download_registry.reap_orphan_workers()+ _join_background_sweep()++ assert not partial.exists()+++def test_startup_sweep_leaves_a_resumable_partial_alone(monkeypatch, tmp_path, blobs):+ """Walking every cache at boot is not a licence to widen what gets deleted."""+ workers = tmp_path / "workers"+ workers.mkdir()+ partial = blobs / _LEGACY_PARTIAL+ partial.write_bytes(b"x" * 25)+ _abandon(partial)++ monkeypatch.setattr(download_registry.state_dir, "workers_dir", lambda: workers)+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name: True)+ monkeypatch.setattr(+ download_registry, "hf_cache_roots", lambda *_a, **_k: [blobs.parent.parent]+ )++ download_registry.reap_orphan_workers()+ _join_background_sweep()++ assert partial.exists()+++def test_a_reaped_job_does_not_wait_out_the_grace_on_its_own_blobs(monkeypatch, blobs):+ """Cancelling writes the partial seconds before the sweep, so waiting strands it."""+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name: False)+ partial = blobs / _NONCE_PARTIAL+ partial.write_bytes(b"x" * 25) # freshly written, as a just-cancelled download's would be+ monkeypatch.setattr(+ download_registry,+ "iter_destructive_repo_cache_dirs",+ lambda *_a, **_k: [blobs.parent],+ )++ # Without the ownership claim it has to wait, which is what stranded it for the session.+ assert download_registry.sweep_abandoned_partials("model", "Org/Model") == 0+ assert partial.exists()++ assert (+ download_registry.sweep_abandoned_partials(+ "model",+ "Org/Model",+ owned_blob_hashes = frozenset({_MAIN}),+ )+ == 1+ )+ assert not partial.exists()+++def test_ownership_never_overrides_the_lock(monkeypatch, blobs):+ """hf locks before it creates the temp file, so a locked blob has a live writer."""+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name: False)+ monkeypatch.setattr(download_registry, "blob_download_lock_held", lambda *_a: True)+ partial = blobs / _NONCE_PARTIAL+ partial.write_bytes(b"x" * 25)+ _abandon(partial)+ monkeypatch.setattr(+ download_registry,+ "iter_destructive_repo_cache_dirs",+ lambda *_a, **_k: [blobs.parent],+ )++ swept = download_registry.sweep_abandoned_partials(+ "model",+ "Org/Model",+ owned_blob_hashes = frozenset({_MAIN}),+ )++ assert swept == 0+ assert partial.exists()+++def test_ownership_never_overrides_peer_protection(monkeypatch, blobs):+ """A shared companion a sibling variant is writing stays out of reach."""+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name: False)+ partial = blobs / _NONCE_PARTIAL+ partial.write_bytes(b"x" * 25)+ monkeypatch.setattr(+ download_registry,+ "iter_destructive_repo_cache_dirs",+ lambda *_a, **_k: [blobs.parent],+ )++ swept = download_registry.sweep_abandoned_partials(+ "model",+ "Org/Model",+ protected_blob_hashes = frozenset({_MAIN}),+ owned_blob_hashes = frozenset({_MAIN}),+ )++ assert swept == 0+ assert partial.exists()+++def test_the_sweep_accepts_the_string_root_the_metadata_holds(monkeypatch, tmp_path):+ """DownloadMetadata.hub_cache is a str, and the caller hands it straight through.++ Deliberately not using the ``blobs`` fixture: patching hf_cache_root would hand the+ resolver a Path and hide the very conversion under test.+ """+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name: False)+ blobs = tmp_path / "hub" / "models--Org--Model" / "blobs"+ blobs.mkdir(parents = True)+ partial = blobs / _NONCE_PARTIAL+ partial.write_bytes(b"x" * 25)+ _abandon(partial)++ # A Path-only signature raised AttributeError here, and the caller's broad except+ # swallowed it, so the terminal sweep silently did nothing for every real download.+ swept = download_registry.sweep_abandoned_partials(+ "model",+ "Org/Model",+ root = str(blobs.parent.parent),+ )++ assert swept == 1+ assert not partial.exists()+++def test_a_job_owning_its_whole_repo_needs_no_hash_list(monkeypatch, blobs):+ """A download with no variant resolves no blob hashes, and claim() gives it the repo."""+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name: False)+ partial = blobs / _NONCE_PARTIAL+ partial.write_bytes(b"x" * 25) # fresh, as a just-cancelled snapshot download's would be+ monkeypatch.setattr(+ download_registry,+ "iter_destructive_repo_cache_dirs",+ lambda *_a, **_k: [blobs.parent],+ )++ assert download_registry.sweep_abandoned_partials("model", "Org/Model") == 0+ assert (+ download_registry.sweep_abandoned_partials("model", "Org/Model", owns_all_blobs = True) == 1+ )+ assert not partial.exists()+++def test_the_boot_sweep_runs_after_the_orphan_is_killed(monkeypatch, tmp_path, blobs):+ """Sweeping first reads the doomed worker's still-held lock and spares its partial."""+ workers = tmp_path / "workers"+ workers.mkdir()+ (workers / "job.json").write_text(+ json.dumps(+ {+ "pid": 4242,+ "repo_type": "model",+ "repo_id": "Org/Model",+ "variant": None,+ "transport": "http",+ "hub_cache": str(blobs.parent.parent),+ }+ ),+ encoding = "utf-8",+ )+ partial = blobs / _NONCE_PARTIAL+ partial.write_bytes(b"x" * 25)++ order = []+ locked = {"held": True}+ monkeypatch.setattr(download_registry.state_dir, "workers_dir", lambda: workers)+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name: False)+ monkeypatch.setattr(download_registry, "_process_alive", lambda _pid: True)+ monkeypatch.setattr(download_registry, "_is_our_worker", lambda *_a: True)+ monkeypatch.setattr(download_registry, "_settle_orphaned_download", lambda *_a, **_k: None)+ monkeypatch.setattr(+ download_registry,+ "hf_cache_roots",+ lambda *_a, **_k: [blobs.parent.parent],+ )+ monkeypatch.setattr(+ download_registry,+ "iter_destructive_repo_cache_dirs",+ lambda *_a, **_k: [blobs.parent],+ )++ def _kill(_pid):+ order.append("kill")+ locked["held"] = False # the lock dies with the process+ return True++ monkeypatch.setattr(download_registry, "_kill_orphan", _kill)+ monkeypatch.setattr(+ download_registry,+ "blob_download_lock_held",+ lambda *_a: order.append("sweep") or locked["held"],+ )++ download_registry.reap_orphan_workers()+ _join_background_sweep()++ assert order[0] == "kill"+ assert not partial.exists()+++def test_a_companion_the_dead_worker_was_writing_is_owned_too(monkeypatch, blobs):+ """A shared mmproj lives in progress_blob_hashes, never in the main blob_hashes set."""+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name: False)+ companion = blobs / f"{_PEER}.feedface{hf_cache_state.INCOMPLETE_SUFFIX}"+ companion.write_bytes(b"x" * 25) # fresh, as a just-cancelled worker's companion would be+ monkeypatch.setattr(+ download_registry,+ "iter_destructive_repo_cache_dirs",+ lambda *_a, **_k: [blobs.parent],+ )++ # Ownership limited to the variant's own quant leaves the companion waiting out the grace.+ assert (+ download_registry.sweep_abandoned_partials(+ "model",+ "Org/Model",+ owned_blob_hashes = frozenset({_MAIN}),+ )+ == 0+ )+ assert companion.exists()++ assert (+ download_registry.sweep_abandoned_partials(+ "model",+ "Org/Model",+ owned_blob_hashes = frozenset({_MAIN, _PEER}),+ )+ == 1+ )+ assert not companion.exists()+++def test_the_reaper_waits_for_the_worker_to_actually_die(monkeypatch):+ """SIGKILL only schedules the death; the lock outlives the signal by a moment."""+ alive = {"n": 3}++ def _still_alive(_pid):+ alive["n"] -= 1+ return alive["n"] > 0++ monkeypatch.setattr(download_registry.os, "kill", lambda *_a: None)+ monkeypatch.setattr(download_registry, "_process_alive", _still_alive)++ download_registry._kill_orphan(4242)++ assert alive["n"] == 0 # returned only once the process was gone, not straight after kill+++def test_a_worker_that_will_not_die_keeps_its_breadcrumb_and_its_partial(+ monkeypatch, tmp_path, blobs+):+ """An unreapable worker is still running, so nothing about it is ours to claim."""+ workers = tmp_path / "workers"+ workers.mkdir()+ crumb = workers / "job.json"+ crumb.write_text(+ json.dumps(+ {+ "pid": 4242,+ "repo_type": "model",+ "repo_id": "Org/Model",+ "variant": None,+ "transport": "http",+ "hub_cache": str(blobs.parent.parent),+ }+ ),+ encoding = "utf-8",+ )+ partial = blobs / _NONCE_PARTIAL+ partial.write_bytes(b"x" * 25)++ monkeypatch.setattr(download_registry.state_dir, "workers_dir", lambda: workers)+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name: False)+ monkeypatch.setattr(download_registry, "_process_alive", lambda _pid: True)+ monkeypatch.setattr(download_registry, "_is_our_worker", lambda *_a: True)+ monkeypatch.setattr(download_registry, "_kill_orphan", lambda _pid: False) # would not die+ monkeypatch.setattr(download_registry, "hf_cache_roots", lambda *_a, **_k: [tmp_path / "none"])++ download_registry.reap_orphan_workers()+ _join_background_sweep()++ assert partial.exists()+ assert crumb.exists() # still tracked, so the next boot tries again+++def test_a_locked_peer_partial_still_counts_against_the_disk_check(monkeypatch, blobs):+ """A sibling variant is finishing the shared companion, so we need no room for it."""+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name: False)+ (blobs / _NONCE_PARTIAL).write_bytes(b"x" * 25)+ monkeypatch.setattr(+ download_registry,+ "iter_active_repo_cache_dirs",+ lambda *_a, **_k: [blobs.parent],+ )++ monkeypatch.setattr(download_registry, "blob_download_lock_held", lambda *_a: False)+ assert download_registry.existing_blob_bytes("model", "Org/Model", frozenset({_MAIN})) == 0++ monkeypatch.setattr(download_registry, "blob_download_lock_held", lambda *_a: True)+ assert download_registry.existing_blob_bytes("model", "Org/Model", frozenset({_MAIN})) == 25+++def test_the_sweep_will_not_cross_a_case_variant_directory(monkeypatch, tmp_path):+ """owns_all_blobs plus a case-insensitive collision could otherwise reach a neighbour."""+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name: False)+ root = tmp_path / "hub"+ mine = root / "models--Org--Model" / "blobs"+ other = root / "models--org--model" / "blobs"+ mine.mkdir(parents = True)+ other.mkdir(parents = True)+ for blobs_dir in (mine, other):+ partial = blobs_dir / _NONCE_PARTIAL+ partial.write_bytes(b"x" * 25)+ _abandon(partial)++ download_registry.sweep_abandoned_partials(+ "model",+ "Org/Model",+ owns_all_blobs = True,+ root = str(root),+ )++ assert not (mine / _NONCE_PARTIAL).exists()+ assert (other / _NONCE_PARTIAL).exists()+++def test_ownership_is_recovered_from_the_manifest_when_hashes_never_resolved(monkeypatch):+ """A variant job whose API-side pre-resolution failed carries an EMPTY hash set."""+ from types import SimpleNamespace++ from hub.services import download_lifecycle+ from hub.utils import download_manifest++ metadata = SimpleNamespace(+ variant = "Q4_K_M",+ hub_cache = None,+ progress_blob_hashes = frozenset(),+ )+ manifest = download_manifest.Manifest(+ repo_type = "model",+ repo_id = "Org/Model",+ variant = "Q4_K_M",+ started_at = "",+ expected_files = (download_manifest.ExpectedFile(path = "m.gguf", size = 5, sha256 = _MAIN),),+ )+ monkeypatch.setattr(download_manifest, "read_manifest", lambda *_a, **_k: manifest)++ owned, owns_all = download_lifecycle._sweep_ownership(+ metadata, frozenset(), frozenset(), "model", "Org/Model"+ )++ assert owns_all is False # a variant job never owns its siblings' blobs+ assert owned == frozenset({_MAIN})+++def test_a_filesystem_without_flock_does_not_escape_the_probe(monkeypatch, tmp_path):+ """NotImplementedError used to travel out and fail the download on every retry."""+ import filelock++ entry = tmp_path / "models--Org--Model"+ lock_path = tmp_path / ".locks" / "models--Org--Model" / f"{_MAIN}.lock"+ lock_path.parent.mkdir(parents = True)++ class _NoFlock:+ def __init__(self, *_a, **_k):+ pass++ def __enter__(self):+ raise NotImplementedError(+ "FileSystem does not appear to support flock; use SoftFileLock instead"+ )++ def __exit__(self, *_a):+ return False++ monkeypatch.setattr(filelock, "FileLock", _NoFlock)++ # No lock file: nobody has locked this blob, whatever the filesystem supports.+ assert hf_cache_state.blob_download_lock_held(entry, _MAIN) is False++ # With one, the answer is "held" rather than an exception -- which is also what a+ # SoftFileLock would say, since its file IS the lock and that file is present.+ lock_path.touch()+ assert hf_cache_state.blob_download_lock_held(entry, _MAIN) is True+++def test_an_unprobeable_lock_reads_as_held(monkeypatch, tmp_path):+ """Ownership can skip the staleness gate, so a wrong 'free' deletes a live writer's file."""+ import filelock++ entry = tmp_path / "models--Org--Model"+ lock_path = tmp_path / ".locks" / "models--Org--Model" / f"{_MAIN}.lock"+ lock_path.parent.mkdir(parents = True)+ lock_path.touch()++ class _Broken:+ def __init__(self, *_a, **_k):+ pass++ def __enter__(self):+ raise RuntimeError("something unforeseen")++ def __exit__(self, *_a):+ return False++ monkeypatch.setattr(filelock, "FileLock", _Broken)++ assert hf_cache_state.blob_download_lock_held(entry, _MAIN) is True+++def test_unreadable_breadcrumbs_do_not_cancel_the_cache_sweep(monkeypatch, tmp_path, blobs):+ """The workers dir and the HF caches are separate trees; one failing is not the other."""+ workers = tmp_path / "workers"+ workers.mkdir()+ partial = blobs / _NONCE_PARTIAL+ partial.write_bytes(b"x" * 25)+ _abandon(partial)++ class _UnreadableDir:+ def iterdir(self):+ raise OSError("permission denied")++ monkeypatch.setattr(download_registry.state_dir, "workers_dir", lambda: _UnreadableDir())+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name: False)+ monkeypatch.setattr(+ download_registry, "hf_cache_roots", lambda *_a, **_k: [blobs.parent.parent]+ )++ download_registry.reap_orphan_workers()+ _join_background_sweep()++ assert not partial.exists()+++def test_an_owned_partial_that_is_still_growing_is_spared(monkeypatch, blobs):+ """Ownership proves OUR writer died, never that no other process shares the cache."""+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name: False)+ monkeypatch.setattr(download_registry, "blob_download_lock_held", lambda *_a: False) # lies+ monkeypatch.setattr(download_registry, "_STILLNESS_PROBE_SECONDS", 0.05)+ monkeypatch.setattr(+ download_registry,+ "iter_destructive_repo_cache_dirs",+ lambda *_a, **_k: [blobs.parent],+ )+ partial = blobs / _NONCE_PARTIAL+ partial.write_bytes(b"x" * 25)++ real_sleep = time.sleep++ def _write_while_we_watch(_seconds):+ real_sleep(_seconds)+ with partial.open("ab") as handle:+ handle.write(b"y" * 10) # an external writer, mid-transfer++ monkeypatch.setattr(download_registry.time, "sleep", _write_while_we_watch)++ swept = download_registry.sweep_abandoned_partials(+ "model",+ "Org/Model",+ owns_all_blobs = True,+ )++ assert swept == 0+ assert partial.exists()+++def test_an_owned_partial_that_never_moves_is_swept_without_the_full_grace(monkeypatch, blobs):+ """The corpse of a cancelled download must not outlive the retry that follows it."""+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name: False)+ monkeypatch.setattr(download_registry, "_STILLNESS_PROBE_SECONDS", 0.05)+ monkeypatch.setattr(+ download_registry,+ "iter_destructive_repo_cache_dirs",+ lambda *_a, **_k: [blobs.parent],+ )+ partial = blobs / _NONCE_PARTIAL+ partial.write_bytes(b"x" * 25) # written seconds ago, far inside the abandonment grace++ swept = download_registry.sweep_abandoned_partials(+ "model",+ "Org/Model",+ owns_all_blobs = True,+ )++ assert swept == 1+ assert not partial.exists()+++def test_a_breadcrumb_whose_worker_already_exited_is_claimed(monkeypatch, tmp_path, blobs):+ """A container restart leaves the crumb behind and the pid long gone."""+ workers = tmp_path / "workers"+ workers.mkdir()+ (workers / "job.json").write_text(+ json.dumps(+ {+ "pid": 4242,+ "repo_type": "model",+ "repo_id": "Org/Model",+ "variant": None,+ "transport": "http",+ "hub_cache": str(blobs.parent.parent),+ }+ ),+ encoding = "utf-8",+ )+ partial = blobs / _NONCE_PARTIAL+ partial.write_bytes(b"x" * 25) # fresh, so only an ownership claim reaches it++ monkeypatch.setattr(download_registry.state_dir, "workers_dir", lambda: workers)+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name: False)+ monkeypatch.setattr(download_registry, "_process_alive", lambda _pid: False) # already dead+ monkeypatch.setattr(download_registry, "_STILLNESS_PROBE_SECONDS", 0.05)+ monkeypatch.setattr(download_registry, "_settle_orphaned_download", lambda *_a, **_k: None)+ monkeypatch.setattr(download_registry, "hf_cache_roots", lambda *_a, **_k: [tmp_path / "none"])+ monkeypatch.setattr(+ download_registry,+ "iter_destructive_repo_cache_dirs",+ lambda *_a, **_k: [blobs.parent],+ )++ download_registry.reap_orphan_workers()+ _join_background_sweep()++ assert not partial.exists()diff --git a/studio/backend/hub/utils/download_registry.py b/studio/backend/hub/utils/download_registry.pyindex 3ea8b53b04b..91040f6868a 100644--- a/studio/backend/hub/utils/download_registry.py+++ b/studio/backend/hub/utils/download_registry.py@@ -9,9 +9,13 @@ machine plus the cache/marker inspection those workers depend on.Resume model-------------Only the HTTP transport supports true partial-file resume:-huggingface_hub's HTTP resumer opens ``<etag>.incomplete`` in append mode-and sends ``Range: bytes={resume_size}-`` to continue from disk.+Up to huggingface_hub 1.17 the HTTP transport supported true partial-file+resume: the resumer opened ``<etag>.incomplete`` in append mode and sent+``Range: bytes={resume_size}-`` to continue from disk. 1.18 replaced that with+a process-unique ``<etag>.<nonce>.incomplete`` opened ``"wb"`` and unlinked on+the way out, so no transport resumes within a file any more and a surviving+partial is litter (see :func:`hf_partials_are_resumable`). Resume is now+whole-file only: ``snapshot_download`` skips shards already materialized.The XET transport CANNOT resume from a ``.incomplete`` partial:``hf_xet.download_files`` rewrites the destination from scratch.@@ -69,7 +73,12 @@ from hub.utils.hf_cache_state import (repo_cache_dir_name,target_dir_name,hf_cache_root,+ ABANDONED_PARTIAL_SECONDS,+ blob_download_lock_held,+ hf_cache_roots,incomplete_blob_hash,+ iter_destructive_repo_cache_dirs,+ partial_is_resumable,)@@ -250,11 +259,30 @@ def _is_our_worker(pid: int, repo_id: Optional[str]) -> bool:return True-def _kill_orphan(pid: int) -> None:+def _kill_orphan(pid: int) -> bool:+ """Signal the process and wait for it to actually be gone. True once it is.++ The wait is what makes the boot sweep meaningful: the signal only schedules the death, and+ a sweep that runs a microsecond later still sees the worker's Hugging Face blob lock and+ spares a partial nothing will ever finish. Bounded, because a pid we cannot reap is not a+ reason to hold up startup -- and answering False there matters: a survivor must keep its+ breadcrumb and must not have its live partial claimed as ours to delete.+ """try:os.kill(pid, signal.SIGTERM if sys.platform == "win32" else signal.SIGKILL)except OSError:- pass+ return not _process_alive(pid)+ deadline = time.monotonic() + _ORPHAN_REAP_TIMEOUT_SECONDS+ while time.monotonic() < deadline:+ if not _process_alive(pid):+ return True+ time.sleep(0.05)+ logger.warning("Orphan worker pid=%s is still alive after the reap timeout.", pid)+ return False+++# Long enough for a SIGKILLed worker to be torn down, short enough not to delay a boot.+_ORPHAN_REAP_TIMEOUT_SECONDS = 5.0def _settle_orphaned_download(@@ -321,17 +349,23 @@ def reap_orphan_workers() -> None:Verifies each breadcrumb's PID is alive AND its command line is one of ourworkers before terminating, so a recycled PID can't take down an unrelated- process. Partial blobs are never touched, so a reaped download stays+ process. A resumable partial is never touched, so a reaped download staysresumable; an interrupted one with bytes on disk is settled to a cancelledmarker (see :func:`_settle_orphaned_download`) so its resume affordance- survives a hard crash like a graceful shutdown's does. Runs once at startup- and never raises."""+ survives a hard crash like a graceful shutdown's does. A partial nothing can+ resume has no affordance to preserve and is swept+ (see :func:`sweep_abandoned_partials`). Runs once at startup and never raises."""+ reaped: list[tuple[str, str, Optional[str]]] = []parent = state_dir.workers_dir()if parent is None:+ _boot_sweep(reaped)returntry:entries = list(parent.iterdir())except OSError:+ # Unreadable breadcrumbs means no worker can be claimed as reaped, not that the caches+ # go unswept: they are a separate tree and may well be readable.+ _boot_sweep(reaped)returnfor entry in entries:if not entry.is_file() or not entry.name.endswith(".json"):@@ -347,8 +381,25 @@ def reap_orphan_workers() -> None:_safe_unlink(entry)continuetry:- if _process_alive(pid) and _is_our_worker(pid, repo_id):- _kill_orphan(pid)+ if not _process_alive(pid):+ # Already gone, which is better proof than killing it ourselves. Its partial+ # is ours to sweep even though this invocation reaped nothing.+ reaped.append((data.get("repo_type") or "model", repo_id, data.get("hub_cache")))+ elif _is_our_worker(pid, repo_id):+ if not _kill_orphan(pid):+ # Still running. Keeping the breadcrumb keeps it tracked for the next boot,+ # and claiming no ownership keeps its live partial out of the sweep.+ logger.warning(+ "Could not reap download worker pid=%s repo=%s; leaving its "+ "breadcrumb and partial in place.",+ pid,+ repo_id,+ )+ continue+ # Its partial is unreadable now and its writer is gone, but only as of this+ # line. The sweep has to come after the kill, not before, or it reads the+ # still-held blob lock and spares a file nothing will ever finish.+ reaped.append((data.get("repo_type") or "model", repo_id, data.get("hub_cache")))logger.warning("Reaped orphaned download worker pid=%s repo=%s from a ""previous backend instance.",@@ -365,6 +416,48 @@ def reap_orphan_workers() -> None:except Exception as exc:logger.debug("Reaper failed for breadcrumb %s: %s", entry, exc)_safe_unlink(entry)+ _boot_sweep(reaped)+++def _boot_sweep(reaped: "Sequence[tuple[str, str, Optional[str]]]") -> None:+ """Startup cleanup, run only once every surviving worker above has been killed.++ The reaped repos are swept inline: that work is bounded by the breadcrumbs and it settles+ the caches a returning user is most likely to look at. The all-caches pass is not bounded+ by anything -- it walks every repo dir, stats every partial and probes locks -- so it goes+ to a thread rather than holding the lifespan open ahead of the first request.+ """+ swept = 0+ try:+ for repo_type, repo_id, hub_cache in reaped:+ # We killed this one ourselves a moment ago, so it need not look abandoned yet.+ swept += sweep_abandoned_partials(+ repo_type,+ repo_id,+ owns_all_blobs = True,+ root = hub_cache,+ )+ except Exception as exc:+ logger.debug("Boot sweep of reaped downloads failed: %s", exc)+ if swept:+ logger.info(+ "Swept %d unresumable partial blob(s) left by a previous backend instance.", swept+ )++ def _sweep_all_caches() -> None:+ try:+ removed = sweep_abandoned_partials_in_all_caches()+ except Exception as exc:+ logger.debug("Background sweep of abandoned partials failed: %s", exc)+ return+ if removed:+ logger.info("Swept %d unresumable partial blob(s) from the HF caches.", removed)++ threading.Thread(+ target = _sweep_all_caches,+ name = "hf-abandoned-partial-sweep",+ daemon = True,+ ).start()class _PurgeOutcome(NamedTuple):@@ -374,20 +467,44 @@ class _PurgeOutcome(NamedTuple):failed: int+# Only the unresumable sweep waits out ABANDONED_PARTIAL_SECONDS: it reclaims disk, while a+# marker-mismatch purge exists to stop a corrupt append and cannot defer.++def _purge_incomplete_blobs(entry: Path,only_hashes: Optional[frozenset[str]] = None,protected_hashes: Optional[frozenset[str]] = None,+ *,+ unresumable_only: bool = False,+ owned_hashes: Optional[frozenset[str]] = None,+ owns_all_blobs: bool = False,) -> _PurgeOutcome:"""Delete selected partials while preserving protected concurrent writes.Report failed deletions so sparse partials cannot receive an HTTP marker.++ ``unresumable_only`` restricts the sweep to partials no writer can reuse AND that nothing+ has touched for ``ABANDONED_PARTIAL_SECONDS``. Unlinking a live partial does not stop its+ writer on POSIX; it keeps filling an unlinked inode and then fails at the rename, so the+ cost of that mistake is another client's whole download.++ ``owned_hashes``, or ``owns_all_blobs`` for a job that owns its whole repo dir (one with no+ variant, which claim() will not let a sibling share), are blobs whose only Studio-side+ writer has just been reaped. Those do not wait out the full grace -- the corpse would+ outlive the retry that follows a cancel, which is the frozen bar this whole change is+ about -- but they are not simply trusted either: registry ownership proves OUR writer is+ gone, never that no independent process shares the cache. They go through a stillness+ probe instead, which is the one liveness test that survives a filesystem where flock is+ granted to every caller and the lock therefore reads free while somebody writes."""+ now = time.time()blobs_dir = entry / "blobs"if not blobs_dir.is_dir():return _PurgeOutcome(0, 0)removed = 0failed = 0+ watched: list[tuple[Path, str, int, float]] = []try:candidates = list(blobs_dir.iterdir())except OSError:@@ -404,6 +521,23 @@ def _purge_incomplete_blobs(continueif only_hashes is not None and blob_hash not in only_hashes:continue+ if unresumable_only:+ if partial_is_resumable(blob.name):+ continue+ # Two independent ways to spot a live writer, because neither is sufficient+ # alone: the lock is the precise signal but upstream calls it best-effort and+ # some filesystems grant it to everyone, while mtime cannot tell a dead writer+ # from one stalled on a slow network for longer than the grace.+ if blob_download_lock_held(entry, blob_hash):+ continue+ owned = owns_all_blobs or bool(owned_hashes and blob_hash in owned_hashes)+ if not owned:+ if now - blob.stat().st_mtime < ABANDONED_PARTIAL_SECONDS:+ continue+ elif now - blob.stat().st_mtime < ABANDONED_PARTIAL_SECONDS:+ stat = blob.stat()+ watched.append((blob, blob_hash, stat.st_size, stat.st_mtime))+ continueblob.unlink()removed += 1except FileNotFoundError:@@ -413,6 +547,38 @@ def _purge_incomplete_blobs(except OSError:failed += 1continue+ watched_outcome = _purge_still_partials(watched)+ return _PurgeOutcome(removed + watched_outcome.removed, failed + watched_outcome.failed)+++# One shared pause is enough to tell a frozen corpse from a writer mid-transfer: hf writes a+# partial continuously, so anything untouched across it is not being written by anyone.+_STILLNESS_PROBE_SECONDS = 2.0+++def _purge_still_partials(watched: "Sequence[tuple[Path, str, int, float]]") -> _PurgeOutcome:+ """Delete the owned partials that do not move while we watch them.++ Sampled once before, once after a single shared sleep, so the cost is one pause per sweep+ rather than one per file. Anything that grew or was touched in between has a live writer,+ whatever the advisory lock had to say about it.+ """+ if not watched:+ return _PurgeOutcome(0, 0)+ time.sleep(_STILLNESS_PROBE_SECONDS)+ removed = 0+ failed = 0+ for blob, _blob_hash, size, mtime in watched:+ try:+ stat = blob.stat()+ if stat.st_size != size or stat.st_mtime != mtime:+ continue # it moved, so somebody owns it after all+ blob.unlink()+ removed += 1+ except FileNotFoundError:+ continue+ except OSError:+ failed += 1return _PurgeOutcome(removed, failed)@@ -561,7 +727,10 @@ def prepare_cache_for_transport(- HTTP mode: a partial is trusted ONLY when its governing marker equals``"http"``. Any other case (missing/unreadable/mismatched marker) purges,since the HTTP resumer would otherwise append to a sparse- XET/parallel-Range partial and silently produce a corrupt blob.+ XET/parallel-Range partial and silently produce a corrupt blob. On+ huggingface_hub >= 1.18 there is no resumer left to trust a partial for+ (see ``hf_partials_are_resumable``), so the marker is bypassed and every+ selected partial purges.- XET mode: incomplete blobs are purged (``hf_xet.download_files`` rewritesfrom scratch, so this only fixes UI accounting — bytes already in CAS arereused via the chunk-cache). Scoped to ``only_blob_hashes``: companion@@ -617,14 +786,34 @@ def prepare_cache_for_transport(if mode == TRANSPORT_XET:main_purge = _purge_incomplete_blobs(entry, only_blob_hashes, protected)else:+ # A matching marker vouches for provenance, which is only worth something if+ # something can still append to the partial it vouches for. When nothing can, what+ # survives is dead weight that holds the disk the refetch needs and, carrying the+ # etag of the blob being refetched, pins the bar to its own stale high-water mark+ # until the new attempt overtakes it. Sweep it, but only once abandoned.if _read_marker(entry, variant) != mode:main_purge = _purge_incomplete_blobs(entry, only_blob_hashes, protected)- if companion_blob_hashes and _read_companion_marker(entry) != mode:- companion_purge = _purge_incomplete_blobs(+ else:+ main_purge = _purge_incomplete_blobs(entry,- companion_blob_hashes,+ only_blob_hashes,protected,+ unresumable_only = True,)+ if companion_blob_hashes:+ if _read_companion_marker(entry) != mode:+ companion_purge = _purge_incomplete_blobs(+ entry,+ companion_blob_hashes,+ protected,+ )+ else:+ companion_purge = _purge_incomplete_blobs(+ entry,+ companion_blob_hashes,+ protected,+ unresumable_only = True,+ )total_purged += main_purge.removed + companion_purge.removedrecord_unconditionally = mode == TRANSPORT_XETif record_unconditionally or not main_purge.failed:@@ -708,17 +897,82 @@ def read_active_transport_marker(return None+def sweep_abandoned_partials(+ repo_type: str,+ repo_id: str,+ *,+ only_blob_hashes: Optional[frozenset[str]] = None,+ protected_blob_hashes: Optional[frozenset[str]] = None,+ owned_blob_hashes: Optional[frozenset[str]] = None,+ owns_all_blobs: bool = False,+ root: Optional[str | Path] = None,+) -> int:+ """Remove partials nothing can resume and nothing has touched. Returns how many went.++ ``prepare_cache_for_transport`` runs once, before a download, and skips anything still+ inside the abandonment grace. That skip lands on the common case: the orphan is the file a+ hard kill left behind, and the user restarts within seconds of the kill that made it. Run+ this when a download reaches a terminal state and every file skipped then gets a second+ look, by which point the grace has long since elapsed.+ """+ # DownloadMetadata.hub_cache is a str, and every caller hands its captured root straight+ # through, so normalize here rather than trusting each one to remember.+ if isinstance(root, str):+ root = Path(root) if root else None+ removed = 0+ # The destructive iterator, not the active one: this deletes, and on a case-insensitive+ # collision the active iterator yields every spelling while this one resolves to the exact+ # directory or refuses. A job owning "its" repo does not own a differently-cased neighbour.+ for entry in iter_destructive_repo_cache_dirs(repo_type, repo_id, root = root):+ outcome = _purge_incomplete_blobs(+ entry,+ only_blob_hashes,+ protected_blob_hashes,+ unresumable_only = True,+ owned_hashes = owned_blob_hashes,+ owns_all_blobs = owns_all_blobs,+ )+ removed += outcome.removed+ return removed+++def sweep_abandoned_partials_in_all_caches() -> int:+ """Boot-time sweep across every known HF cache root. Returns how many partials went.++ Not driven off worker breadcrumbs, because ``drop_process`` removes a breadcrumb during+ ``finalize_worker_exit`` -- before the terminal-state sweep runs -- so a partial that sweep+ skips for being freshly written has no breadcrumb left to be found by. Walking the caches+ instead needs no record to survive, and every deletion still has to clear the same+ unresumable, unlocked and abandoned gates.+ """+ removed = 0+ for root in hf_cache_roots():+ try:+ entries = list(root.iterdir())+ except OSError:+ continue+ for entry in entries:+ if "--" not in entry.name or not (entry / "blobs").is_dir():+ continue+ removed += _purge_incomplete_blobs(entry, None, None, unresumable_only = True).removed+ return removed++def is_resumable_partial(repo_type: str,repo_id: str,variant: Optional[str] = None,) -> bool:- """True only when a partial exists AND was produced by a byte-resumable- writer (the HTTP transport). XET partials exist on disk but are discarded on- the next download attempt."""- if not has_active_incomplete_blobs(repo_type, repo_id):+ """True only when a partial exists AND something can still resume from it.++ Two ways to fail that. XET partials exist on disk but ``hf_xet`` rewrites the destination+ from scratch, so the marker has to say HTTP. And an HTTP partial is only resumable while a+ writer that reopens it is installed; the UI turns this flag into "Resume with HTTP to keep+ the progress you already have", which must not be promised for bytes about to be swept.+ """+ if read_active_transport_marker(repo_type, repo_id, variant) != TRANSPORT_HTTP:return False- return read_active_transport_marker(repo_type, repo_id, variant) == TRANSPORT_HTTP+ return bool(incomplete_blob_hashes(repo_type, repo_id, active_only = True, resumable_only = True))def incomplete_blob_hashes(@@ -726,8 +980,14 @@ def incomplete_blob_hashes(repo_id: str,*,active_only: bool = False,+ resumable_only: bool = False,root: Optional[Path] = None,) -> set[str]:+ """Logical blob hashes with a partial on disk.++ ``resumable_only`` keeps just the ones a later attempt could actually append to, which is+ what a "resume and keep your progress" claim has to be built on.+ """out: set[str] = set()entries = (iter_active_repo_cache_dirs(repo_type, repo_id, root = root)@@ -743,8 +1003,11 @@ def incomplete_blob_hashes(if not blob.is_file():continueblob_hash = incomplete_blob_hash(blob.name)- if blob_hash is not None:- out.add(blob_hash)+ if blob_hash is None:+ continue+ if resumable_only and not partial_is_resumable(blob.name):+ continue+ out.add(blob_hash)except OSError:continuereturn out@@ -782,10 +1045,10 @@ def completed_blob_bytes(def existing_blob_bytes(repo_type: str, repo_id: str, blob_hashes: frozenset[str]) -> int:- """Bytes already on disk (finalized + ``.incomplete``) for *blob_hashes* in- the active HF cache root. A blob is in exactly one state, so summing both- candidate names never double-counts. Used to size what a (possibly resumed)- download still needs to write before the run starts."""+ """Bytes a download will NOT have to fetch again for *blob_hashes*, in the active HF cache+ root: finalized blobs, plus partials something can still resume from. A blob is in exactly+ one state, so summing both candidate names never double-counts. Used to size what a+ (possibly resumed) download still needs to write before the run starts."""if not blob_hashes:return 0total = 0@@ -806,6 +1069,19 @@ def existing_blob_bytes(repo_type: str, repo_id: str, blob_hashes: frozenset[strblob_hash = partial_hash if partial_hash is not None else blob.nameif blob_hash not in present:continue+ if (+ partial_hash is not None+ and not partial_is_resumable(blob.name)+ and not blob_download_lock_held(entry, blob_hash)+ ):+ # Callers spend this on "bytes we will not have to fetch again", and+ # _preflight_disk_space subtracts it from the space a download needs. An+ # unresumable partial is refetched in full into a new path, so counting it+ # would clear a download for a disk that cannot hold it. A LOCKED one is+ # different: a live peer is finishing it and snapshot_download will block+ # on that lock and reuse the result, so those bytes are not ours to find+ # room for. Two GGUF variants sharing an mmproj hit this every time.+ continue# Broken advisory locks can leave several process-unique writers for one etag.# They are duplicate attempts, not additive completion, so keep the largest.present[blob_hash] = max(present[blob_hash], max(0, int(blob.stat().st_size)))diff --git a/studio/backend/hub/utils/hf_cache_state.py b/studio/backend/hub/utils/hf_cache_state.pyindex 2d82d7fe2bd..5504f09daa1 100644--- a/studio/backend/hub/utils/hf_cache_state.py+++ b/studio/backend/hub/utils/hf_cache_state.py@@ -9,6 +9,7 @@ import reimport shutilimport stat as stat_moduleimport sys+from functools import lru_cachefrom pathlib import Path, PureWindowsPathfrom typing import Iterable, Iterator, Optional@@ -48,6 +49,101 @@ def incomplete_blob_hash(name: str) -> Optional[str]:return process_unique.group("blob_hash") if process_unique else stem+# The last huggingface_hub line whose partials a later attempt can append to.+_LAST_RESUMABLE_PARTIAL_VERSION = (1, 17)++# How long a partial must sit untouched before it reads as abandoned rather than in flight.+# huggingface_hub writes to one continuously, so anything still advancing has a live writer --+# possibly a client in another process that no registry here can see. Shared by the sweep that+# deletes abandoned partials and the progress scan that must not report one as current.+ABANDONED_PARTIAL_SECONDS = 120+++@lru_cache(maxsize = 1)+def hf_partials_are_resumable() -> bool:+ """Whether an interrupted download leaves bytes the next attempt can reuse.++ Up to 1.17 huggingface_hub appended to a shared ``<etag>.incomplete`` and restarted from+ its length over a Range request. 1.18 moved the writer to a process-unique+ ``<etag>.<nonce>.incomplete``, opened ``"wb"`` and unlinked in a ``finally``+ (huggingface/huggingface_hub#4228), so an interrupted file is refetched from zero and+ whatever partial survives a hard kill can never be read again.++ An unreadable version answers True: not knowing which writer is installed is not grounds+ for deleting bytes that may still be resumable.+ """+ try:+ from huggingface_hub import __version__ as hf_version+ except Exception: # noqa: BLE001 - an unimportable hub is the caller's problem, not ours+ return True+ release = []+ for chunk in str(hf_version).split(".")[:2]:+ digits = ""+ for char in chunk:+ if not char.isdigit():+ break+ digits += char+ if not digits:+ return True+ release.append(int(digits))+ return tuple(release) <= _LAST_RESUMABLE_PARTIAL_VERSION+++def partial_is_process_unique(name: str) -> bool:+ """Whether a partial filename carries the 1.18+ per-process nonce."""+ if not name.endswith(INCOMPLETE_SUFFIX):+ return False+ return _PROCESS_UNIQUE_PARTIAL_RE.fullmatch(name[: -len(INCOMPLETE_SUFFIX)]) is not None+++def blob_download_lock_held(entry: Path, blob_hash: str) -> bool:+ """Whether some process holds huggingface_hub's per-blob download lock right now.++ hf takes ``<hub cache>/.locks/<repo dir>/<etag>.lock`` for the whole of a file download, so+ a lock we cannot take means a live writer -- including a client in another process that no+ peer registry here can see. It answers False when the lock cannot be probed at all, since+ upstream calls the lock best-effort and some filesystems grant it to everyone; callers pair+ it with a staleness check rather than trusting it alone.+ """+ lock_path = entry.parent / ".locks" / entry.name / f"{blob_hash}.lock"+ if not lock_path.exists():+ # hf creates the lock file before taking the lock, so no file means no writer. It is+ # also the answer for a SoftFileLock, whose file IS the lock (see below).+ return False+ try:+ from filelock import FileLock, Timeout+ except Exception: # noqa: BLE001 - no filelock at all means no opinion+ return False+ try:+ with FileLock(str(lock_path), timeout = 0):+ return False+ except Timeout:+ return True+ except Exception: # noqa: BLE001 - deliberately broad, see below+ # A filesystem without flock raises NotImplementedError here, and upstream's+ # WeakFileLock answers it by retrying as a SoftFileLock (huggingface_hub+ # utils/_fixes.py). Retrying is pointless for a PROBE: a soft lock is its file, and we+ # only reach this line because that file exists, so the soft answer is "held" too.+ # What matters is that the exception does not escape -- it used to travel out through+ # the purge and fail the download on every retry. Any other unprobeable error answers+ # the same way, because the caller's remaining guard is a staleness check that an+ # ownership claim may skip, and a wrong "free" there deletes a live writer's file.+ return True+++def partial_is_resumable(name: str) -> bool:+ """Whether any later attempt could append to this particular partial.++ Two conditions, and the layout half matters on its own: a nonce partial is private to the+ process that created it, so even a legacy writer will not reopen it. That combination is+ reachable whenever caches are shared across environments, which this repo's own pins+ produce (Python 3.10+ takes hub >= 1.23, older takes 0.36.2, one cache between them).+ """+ if partial_is_process_unique(name):+ return False+ return hf_partials_are_resumable()++def _safe_is_dir(path: Path, scan_errors: Optional[list] = None) -> bool:"""``Path.is_dir()`` returning False instead of raising when the path or aparent is unreadable (e.g. a restricted ``~/.cache/huggingface/hub``), so