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
Fix Studio progress for Hugging Face process-unique partials (#8288)
Lee Jackson18b9c6cfc05f
diff --git a/studio/backend/hub/services/models/gguf_variants.py b/studio/backend/hub/services/models/gguf_variants.pyindex ccf014fe25a..bd87ebdd954 100644--- a/studio/backend/hub/services/models/gguf_variants.py+++ b/studio/backend/hub/services/models/gguf_variants.py@@ -24,7 +24,7 @@ from hub.utils import download_registryfrom hub.utils import inventory_scan as hf_cache_scanfrom hub.utils.hf_errors import hf_error_statusfrom hub.utils.hf_cache_state import (- INCOMPLETE_SUFFIX,+ incomplete_blob_hash,iter_destructive_repo_cache_dirs,repo_cache_dir_name,)@@ -538,14 +538,21 @@ def delete_variant_incomplete_blobs_result(blobs_dir = entry / "blobs"if not blobs_dir.is_dir():continue- for h in target_hashes:- incomplete = blobs_dir / f"{h}{INCOMPLETE_SUFFIX}"- if incomplete.exists():- try:- incomplete.unlink()- deleted += 1- except OSError as e:- logger.warning(f"Failed to unlink {incomplete}: {e}")+ try:+ candidates = list(blobs_dir.iterdir())+ except OSError as e:+ logger.warning(f"Failed to list partial blobs in {blobs_dir}: {e}")+ continue+ for incomplete in candidates:+ try:+ if not incomplete.is_file():+ continue+ if incomplete_blob_hash(incomplete.name) not in target_hashes:+ continue+ incomplete.unlink()+ deleted += 1+ except OSError as e:+ logger.warning(f"Failed to unlink {incomplete}: {e}")return VariantIncompleteDeleteResult(deleted = deleted, unresolved = False)diff --git a/studio/backend/hub/services/snapshot_progress.py b/studio/backend/hub/services/snapshot_progress.pyindex f8a925cd155..aaeec3fe61b 100644--- a/studio/backend/hub/services/snapshot_progress.py+++ b/studio/backend/hub/services/snapshot_progress.py@@ -25,8 +25,8 @@ from hub.utils import download_registryfrom hub.utils import inventory_scan as hf_cache_scanfrom hub.utils.state_dir import RepoTypefrom hub.utils.hf_cache_state import (- INCOMPLETE_SUFFIX,blob_bytes_present,+ incomplete_blob_hash,preferred_repo_cache_dirs,snapshot_selection_key,)@@ -125,15 +125,17 @@ def _variant_bytes_on_disk(manifest: Optional[download_manifest.Manifest],snapshot_dir: Optional[Path],variant_file_matcher: Optional["VariantFileMatcher"],+ active_partial_hashes: "frozenset[str]" = frozenset(),) -> int:"""Bytes a variant owns, read from the snapshot dir instead of ``blobs/``.- Only used when the expected blob hashes could not be resolved. The snapshot- dir is the one variant-scoped view of the cache: its entries are named per- file, so a sibling quant is excluded by name, whereas in the shared- ``blobs/`` dir a sibling's bytes are indistinguishable from this variant's- and counting them wholesale is the "instant ~900 MB" bug. ``stat`` follows- HF's symlink layout and reads the Windows copy layout directly.+ The snapshot dir is the one variant-scoped view of the cache: its entries+ are named per file, so a sibling quant is excluded by name, whereas in the+ shared ``blobs/`` dir a sibling's bytes are indistinguishable from this+ variant's and counting them wholesale is the "instant ~900 MB" bug.+ ``stat`` follows HF's symlink layout and reads the Windows copy layout+ directly. The latter matters even with resolved hashes: recent Hub clients+ can materialize completed files without retaining a finalized blob entry."""if snapshot_dir is None:return 0@@ -142,6 +144,11 @@ def _variant_bytes_on_disk(for expected in manifest.expected_files:if not download_manifest.expected_path_is_safe(expected.path):continue+ if expected.sha256 and expected.sha256 in active_partial_hashes:+ # A force/retry can leave the previous materialized file in the snapshot while+ # a replacement for the same logical blob is being written. Count the current+ # partial, not both generations of the file.+ continuetry:total += (snapshot_dir / expected.path).stat().st_sizeexcept OSError:@@ -372,24 +379,70 @@ def _snapshot_complete_on_disk(return False+def _referenced_commits(entry: Path) -> "frozenset[str]":+ """Commits this repo cache dir still points at.++ HF records the commit a branch or tag resolved to in ``refs/<revision>`` on every+ snapshot_download whose revision was not already a raw sha, so for the default ``main``+ the file is always there. It is the one revision marker that survives without a manifest.+ """+ commits: set[str] = set()+ try:+ refs = list((entry / "refs").rglob("*"))+ except OSError:+ return frozenset()+ for ref in refs:+ try:+ if not ref.is_file():+ continue+ commit = download_manifest.normalized_commit_hash(ref.read_text().strip())+ except (OSError, ValueError):+ continue+ if commit:+ commits.add(commit)+ return frozenset(commits)+++def _snapshot_is_stale_copy(+ snapshot: Path, manifest: "Optional[download_manifest.Manifest]"+) -> bool:+ """Whether ``snapshot`` names a revision this cache dir has moved off.++ Only asked where there is no symlink to read. HF names a snapshot dir after its commit, so+ a dir named by neither the manifest's recorded commit nor any live ref is an older+ revision, and its same-named files are not this download's bytes. Neither marker present+ leaves the question unanswerable, and unanswerable is not a mismatch.+ """+ commit_hash = download_manifest.normalized_commit_hash(getattr(manifest, "commit_hash", None))+ if commit_hash:+ return snapshot.name != commit_hash+ referenced = _referenced_commits(snapshot.parent.parent)+ return bool(referenced) and snapshot.name not in referenced++def _snapshot_resolves_to(- manifest: download_manifest.Manifest, snapshot: Path, expected_hashes: "frozenset[str]"+ manifest: "Optional[download_manifest.Manifest]",+ snapshot: Path,+ expected_hashes: "frozenset[str]",) -> bool:"""Whether every expected file in ``snapshot`` points at one of ``expected_hashes``.HF names a blob by its hash and the snapshot entry links to it, so the link target settleswhich revision is materialized here. A copy-layout cache (Windows without symlinks) has no- target to read: unanswerable is not a mismatch, so it passes -- and it does not have to be- answered, because the byte tally that gates completion only ever counts blobs whose name IS- an expected hash, so the expected revision is already proven present in this cache dir.+ target to read, and neither does a reading with no manifest to name the files, so both fall+ back to dating the snapshot by revision."""+ if manifest is None:+ return not _snapshot_is_stale_copy(snapshot, None)for expected in getattr(manifest, "expected_files", ()) or ():if not download_manifest.expected_path_is_safe(expected.path):continueentry = snapshot / expected.pathtry:if not entry.is_symlink():- continue # copy layout: nothing to compare against+ if _snapshot_is_stale_copy(snapshot, manifest):+ return False+ continuetarget = os.path.basename(os.readlink(entry))except OSError:continue@@ -476,7 +529,10 @@ def compute_snapshot_progress()for entry in cache_dirs:completed_bytes = 0- in_progress_bytes = 0+ # Keyed by logical blob: a broken advisory lock leaves several process-unique writers+ # racing on one etag, and each downloads the WHOLE file, so summing them overshoots.+ partial_bytes: dict[str, int] = {}+ completed_hashes: set[str] = set()# A partial this reading could not attribute to any target. It is not evidence FOR this# variant -- it may be a sibling quant's -- but with the hashes unresolved it is not# evidence against it either, and the by-name scan cannot see it because a partial is@@ -508,21 +564,24 @@ def compute_snapshot_progress(try:if not f.is_file():continue- if f.name.endswith(INCOMPLETE_SUFFIX):- blob_hash = f.name[: -len(INCOMPLETE_SUFFIX)]+ partial_hash = incomplete_blob_hash(f.name)+ if partial_hash is not None:if expected_hashes:- if blob_hash not in expected_hashes:+ if partial_hash not in expected_hashes:continueelif not count_unscoped:unattributable_partial = Truecontinue- in_progress_bytes += blob_bytes_present(f)+ partial_bytes[partial_hash] = max(+ partial_bytes.get(partial_hash, 0), blob_bytes_present(f)+ )else:if expected_hashes:if f.name not in expected_hashes:continueelif not count_unscoped:continue+ completed_hashes.add(f.name)completed_bytes += f.stat().st_sizeexcept OSError as exc:# A blob we could not inspect is not a blob that is not there. Swallowing it@@ -530,6 +589,14 @@ def compute_snapshot_progress(# persisted download whose target may be intact behind the error.scan_errors.append(exc)continue+ # A finalized blobs/<hash> supersedes every partial for the same logical blob: the racer+ # that installed the file settled it, so a leftover writer's bytes are a duplicate, not+ # progress. Counting both overshot the expected total and, because completion requires+ # no bytes in flight, pinned a fully downloaded variant at 0.99 until the orphan was+ # 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)+ in_progress_bytes = sum(partial_bytes.values())snapshot_dirs: "_Lazy[list[Path]]" = _Lazy(lambda entry = entry: _retained_snapshot_dirs(entry))@@ -541,21 +608,29 @@ def compute_snapshot_progress(hub_cache = entry.parent,))- if variant_file_set_unknown:+ if variant is not None:# The best reading across every retained snapshot, for the same reason presence is# established across all of them: the variant can live in an older revision while# the newest holds a sibling, and reading only the newest reported 0 bytes for a- # complete cached quant.+ # complete cached quant. Do this even when hashes resolved: huggingface_hub 1.18's+ # Windows copy layout can move a completed file directly into the snapshot and+ # leave no finalized entry in blobs/, so a blob-only tally stays at zero.+ manifest = entry_manifest.get()on_disk = max((- _variant_bytes_on_disk(entry_manifest.get(), snap, variant_file_matcher)+ _variant_bytes_on_disk(+ manifest,+ snap,+ variant_file_matcher,+ frozenset(partial_bytes),+ )for snap in snapshot_dirs.get()+ if not expected_hashes or _snapshot_resolves_to(manifest, snap, expected_hashes)),default = 0,)- # Clamped, because the matcher behind the no-manifest half of that- # reading accepts every companion in the repo and so can overshoot.- # A bar reading "44 GB of 33 GB" is a worse answer than a pinned one.+ # Clamped, because the matcher behind the no-manifest half of that reading accepts+ # every companion in the repo and so can overshoot.if expected_total > 0:on_disk = min(on_disk, expected_total)completed_bytes = max(completed_bytes, on_disk)diff --git a/studio/backend/hub/tests/test_process_unique_incomplete_repro.py b/studio/backend/hub/tests/test_process_unique_incomplete_repro.pynew file mode 100644index 00000000000..dfe5eb39ceb--- /dev/null+++ b/studio/backend/hub/tests/test_process_unique_incomplete_repro.py@@ -0,0 +1,361 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Focused reproduction for Hugging Face's process-unique partial filenames."""++from types import SimpleNamespace++from hub.services import snapshot_progress+from hub.utils import download_manifest, download_registry+from hub.utils.hf_cache_state import incomplete_blob_hash+++_BLOB_HASH = "a" * 64+++def _running_registry():+ return SimpleNamespace(+ get_job = lambda _key: SimpleNamespace(state = "running"),+ get_job_metadata = lambda _key: SimpleNamespace(completed_baseline_bytes = 0),+ )+++def test_incomplete_blob_hash_supports_legacy_and_process_unique_names():+ assert incomplete_blob_hash(f"{_BLOB_HASH}.incomplete") == _BLOB_HASH+ assert incomplete_blob_hash(f"{_BLOB_HASH}.deadbeef.incomplete") == _BLOB_HASH+ assert incomplete_blob_hash(_BLOB_HASH) is None+++def test_registry_groups_duplicate_process_unique_writers_by_blob(monkeypatch, tmp_path):+ """Parallel partial attempts are one logical blob, not additive progress."""+ entry = tmp_path / "models--Org--Model"+ blobs = entry / "blobs"+ blobs.mkdir(parents = True)+ (blobs / f"{_BLOB_HASH}.11111111.incomplete").write_bytes(b"x" * 3)+ (blobs / f"{_BLOB_HASH}.22222222.incomplete").write_bytes(b"x" * 5)++ monkeypatch.setattr(+ download_registry,+ "iter_repo_cache_dirs",+ lambda *_args, **_kwargs: [entry],+ )+ monkeypatch.setattr(+ download_registry,+ "iter_active_repo_cache_dirs",+ lambda *_args, **_kwargs: [entry],+ )++ assert download_registry.incomplete_blob_hashes("model", "Org/Model") == {_BLOB_HASH}+ assert (+ download_registry.existing_blob_bytes(+ "model",+ "Org/Model",+ frozenset({_BLOB_HASH}),+ )+ == 5+ )+++def test_registry_purges_process_unique_partial(tmp_path):+ entry = tmp_path / "models--Org--Model"+ blobs = entry / "blobs"+ blobs.mkdir(parents = True)+ partial = blobs / f"{_BLOB_HASH}.deadbeef.incomplete"+ partial.write_bytes(b"x" * 5)++ outcome = download_registry._purge_incomplete_blobs(+ entry,+ only_hashes = frozenset({_BLOB_HASH}),+ )++ assert outcome == (1, 0)+ assert not partial.exists()+++def test_progress_counts_process_unique_incomplete_blob(monkeypatch, tmp_path):+ """An active ``<etag>.<uuid>.incomplete`` target must contribute bytes."""+ entry = tmp_path / "models--Org--Model-GGUF"+ blobs = entry / "blobs"+ blobs.mkdir(parents = True)+ (blobs / f"{_BLOB_HASH}.deadbeef.incomplete").write_bytes(b"x" * 5)++ monkeypatch.setattr(+ snapshot_progress,+ "preferred_repo_cache_dirs",+ lambda *_args, **_kwargs: [entry],+ )+ result = 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",+ )++ assert result["completed_bytes"] == 0+ assert result["downloaded_bytes"] == 5+ assert result["progress"] == 0.05+++def test_progress_counts_completed_materialized_snapshot_file(monkeypatch, tmp_path):+ """A Windows copy-layout snapshot must count without a finalized blob file."""+ entry = tmp_path / "models--Org--Model"+ snapshot = entry / "snapshots" / "revision"+ (entry / "blobs").mkdir(parents = True)+ snapshot.mkdir(parents = True)+ (snapshot / "model.safetensors").write_bytes(b"x" * 5)+ manifest = download_manifest.Manifest(+ repo_type = "model",+ repo_id = "Org/Model",+ variant = "@diffusion",+ started_at = "",+ expected_files = (+ download_manifest.ExpectedFile(+ path = "model.safetensors",+ size = 5,+ sha256 = _BLOB_HASH,+ ),+ ),+ )++ monkeypatch.setattr(+ snapshot_progress,+ "preferred_repo_cache_dirs",+ lambda *_args, **_kwargs: [entry],+ )+ monkeypatch.setattr(+ snapshot_progress.download_manifest,+ "read_manifest",+ lambda *_args, **_kwargs: manifest,+ )++ result = snapshot_progress.compute_snapshot_progress(+ repo_type = "model",+ repo_id = "Org/Model",+ job_key = "model:org/model#@diffusion",+ expected_bytes = 100,+ hf_token = None,+ registry = _running_registry(),+ metadata_resolver = lambda *_args: (100, frozenset({_BLOB_HASH})),+ variant = "@diffusion",+ variant_file_matcher = lambda path, **_kwargs: path == "model.safetensors",+ )++ assert result["completed_bytes"] == 5+ assert result["downloaded_bytes"] == 5+ assert result["progress"] == 0.05+++def test_progress_groups_duplicate_process_unique_writers(monkeypatch, tmp_path):+ """Racing writers for one etag each fetch the whole file, so keep the largest."""+ entry = tmp_path / "models--Org--Model-GGUF"+ blobs = entry / "blobs"+ blobs.mkdir(parents = True)+ (blobs / f"{_BLOB_HASH}.11111111.incomplete").write_bytes(b"x" * 60)+ (blobs / f"{_BLOB_HASH}.22222222.incomplete").write_bytes(b"x" * 60)++ monkeypatch.setattr(+ snapshot_progress,+ "preferred_repo_cache_dirs",+ lambda *_args, **_kwargs: [entry],+ )+ result = 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",+ )++ assert result["downloaded_bytes"] == 60+ assert result["progress"] == 0.6+++def test_progress_ignores_stale_revision_in_copy_layout(monkeypatch, tmp_path):+ """A copy-layout snapshot from another commit is not this download's bytes.++ Written the way production writes it: model, GGUF and scoped manifests all go through+ ``write_manifest`` without a commit, so ``refs/main`` is the only marker available.+ """+ commit = "b" * 40+ entry = tmp_path / "models--Org--Model"+ (entry / "blobs").mkdir(parents = True)+ (entry / "refs").mkdir(parents = True)+ (entry / "refs" / "main").write_text(commit)+ stale = entry / "snapshots" / ("c" * 40)+ stale.mkdir(parents = True)+ (stale / "model.safetensors").write_bytes(b"x" * 100)+ (entry / "snapshots" / commit).mkdir(parents = True)+ manifest = download_manifest.Manifest(+ repo_type = "model",+ repo_id = "Org/Model",+ variant = "@diffusion",+ started_at = "",+ expected_files = (+ download_manifest.ExpectedFile(+ path = "model.safetensors",+ size = 100,+ sha256 = _BLOB_HASH,+ ),+ ),+ )++ monkeypatch.setattr(+ snapshot_progress,+ "preferred_repo_cache_dirs",+ lambda *_args, **_kwargs: [entry],+ )+ monkeypatch.setattr(+ snapshot_progress.download_manifest,+ "read_manifest",+ lambda *_args, **_kwargs: manifest,+ )+ result = snapshot_progress.compute_snapshot_progress(+ repo_type = "model",+ repo_id = "Org/Model",+ job_key = "model:org/model#@diffusion",+ expected_bytes = 100,+ hf_token = None,+ registry = _running_registry(),+ metadata_resolver = lambda *_args: (100, frozenset({_BLOB_HASH})),+ variant = "@diffusion",+ variant_file_matcher = lambda path, **_kwargs: path == "model.safetensors",+ )++ assert result["completed_bytes"] == 0+ assert result["downloaded_bytes"] == 0+++def test_progress_ignores_stale_revision_without_a_manifest(monkeypatch, tmp_path):+ """No manifest is not a licence to count any retained snapshot."""+ commit = "b" * 40+ entry = tmp_path / "models--Org--Model"+ (entry / "blobs").mkdir(parents = True)+ (entry / "refs").mkdir(parents = True)+ (entry / "refs" / "main").write_text(commit)+ stale = entry / "snapshots" / ("c" * 40)+ stale.mkdir(parents = True)+ (stale / "model.safetensors").write_bytes(b"x" * 100)+ (entry / "snapshots" / commit).mkdir(parents = True)++ monkeypatch.setattr(+ snapshot_progress,+ "preferred_repo_cache_dirs",+ lambda *_args, **_kwargs: [entry],+ )+ monkeypatch.setattr(+ snapshot_progress.download_manifest,+ "read_manifest",+ lambda *_args, **_kwargs: None,+ )+ result = snapshot_progress.compute_snapshot_progress(+ repo_type = "model",+ repo_id = "Org/Model",+ job_key = "model:org/model#@diffusion",+ expected_bytes = 100,+ hf_token = None,+ registry = _running_registry(),+ metadata_resolver = lambda *_args: (100, frozenset({_BLOB_HASH})),+ variant = "@diffusion",+ variant_file_matcher = lambda path, **_kwargs: path == "model.safetensors",+ )++ assert result["completed_bytes"] == 0+ assert result["downloaded_bytes"] == 0+++def test_progress_counts_the_snapshot_the_refs_point_at(monkeypatch, tmp_path):+ """The revision check must not cost the Windows copy-layout fix it guards."""+ commit = "b" * 40+ entry = tmp_path / "models--Org--Model"+ (entry / "blobs").mkdir(parents = True)+ (entry / "refs").mkdir(parents = True)+ (entry / "refs" / "main").write_text(commit)+ current = entry / "snapshots" / commit+ current.mkdir(parents = True)+ (current / "model.safetensors").write_bytes(b"x" * 100)++ monkeypatch.setattr(+ snapshot_progress,+ "preferred_repo_cache_dirs",+ lambda *_args, **_kwargs: [entry],+ )+ monkeypatch.setattr(+ snapshot_progress.download_manifest,+ "read_manifest",+ lambda *_args, **_kwargs: None,+ )+ result = snapshot_progress.compute_snapshot_progress(+ repo_type = "model",+ repo_id = "Org/Model",+ job_key = "model:org/model#@diffusion",+ expected_bytes = 100,+ hf_token = None,+ registry = _running_registry(),+ metadata_resolver = lambda *_args: (100, frozenset({_BLOB_HASH})),+ variant = "@diffusion",+ variant_file_matcher = lambda path, **_kwargs: path == "model.safetensors",+ )++ assert result["completed_bytes"] == 100+++def test_finalized_blob_supersedes_an_orphaned_partial(monkeypatch, tmp_path):+ """A racer that installed the blob settles it; the loser's leftover is not progress."""+ commit = "b" * 40+ entry = tmp_path / "models--Org--Model-GGUF"+ blobs = entry / "blobs"+ blobs.mkdir(parents = True)+ (blobs / _BLOB_HASH).write_bytes(b"x" * 100)+ (blobs / f"{_BLOB_HASH}.22222222.incomplete").write_bytes(b"x" * 60)+ (entry / "refs").mkdir(parents = True)+ (entry / "refs" / "main").write_text(commit)+ snapshot = entry / "snapshots" / commit+ snapshot.mkdir(parents = True)+ (snapshot / "model-Q4_K_M.gguf").symlink_to(blobs / _BLOB_HASH)+ manifest = download_manifest.Manifest(+ repo_type = "model",+ repo_id = "Org/Model-GGUF",+ variant = "Q4_K_M",+ started_at = "",+ expected_files = (+ download_manifest.ExpectedFile(+ path = "model-Q4_K_M.gguf",+ size = 100,+ sha256 = _BLOB_HASH,+ ),+ ),+ )++ monkeypatch.setattr(+ snapshot_progress,+ "preferred_repo_cache_dirs",+ lambda *_args, **_kwargs: [entry],+ )+ monkeypatch.setattr(+ snapshot_progress.download_manifest,+ "read_manifest",+ lambda *_args, **_kwargs: manifest,+ )+ result = 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",+ variant_file_matcher = lambda path, **_kwargs: path == "model-Q4_K_M.gguf",+ )++ # 160 of 100 bytes before, and completion refused for as long as the orphan survived.+ assert result["downloaded_bytes"] == 100+ assert result["complete_on_disk"] is True+ assert result["progress"] == 1.0diff --git a/studio/backend/hub/utils/download_registry.py b/studio/backend/hub/utils/download_registry.pyindex 916a28460f8..3ea8b53b04b 100644--- a/studio/backend/hub/utils/download_registry.py+++ b/studio/backend/hub/utils/download_registry.py@@ -57,7 +57,6 @@ from hub.utils.state_dir import RepoTypelogger = get_logger(__name__)from hub.utils.hf_cache_state import (- INCOMPLETE_SUFFIX,TRANSPORT_AUTO,TRANSPORT_HTTP,TRANSPORT_XET,@@ -70,6 +69,7 @@ from hub.utils.hf_cache_state import (repo_cache_dir_name,target_dir_name,hf_cache_root,+ incomplete_blob_hash,)@@ -397,9 +397,9 @@ def _purge_incomplete_blobs(try:if not blob.is_file():continue- if not blob.name.endswith(INCOMPLETE_SUFFIX):+ blob_hash = incomplete_blob_hash(blob.name)+ if blob_hash is None:continue- blob_hash = blob.name[: -len(INCOMPLETE_SUFFIX)]if protected_hashes and blob_hash in protected_hashes:continueif only_hashes is not None and blob_hash not in only_hashes:@@ -740,8 +740,11 @@ def incomplete_blob_hashes(continuetry:for blob in blobs_dir.iterdir():- if blob.is_file() and blob.name.endswith(INCOMPLETE_SUFFIX):- out.add(blob.name[: -len(INCOMPLETE_SUFFIX)])+ if not blob.is_file():+ continue+ blob_hash = incomplete_blob_hash(blob.name)+ if blob_hash is not None:+ out.add(blob_hash)except OSError:continuereturn out@@ -790,14 +793,25 @@ def existing_blob_bytes(repo_type: str, repo_id: str, blob_hashes: frozenset[strblobs_dir = entry / "blobs"if not blobs_dir.is_dir():continue- for blob_hash in blob_hashes:- for name in (blob_hash, f"{blob_hash}{INCOMPLETE_SUFFIX}"):- blob = blobs_dir / name- try:- if blob.is_file():- total += max(0, int(blob.stat().st_size))- except OSError:+ present = {blob_hash: 0 for blob_hash in blob_hashes}+ try:+ entries = list(blobs_dir.iterdir())+ except OSError:+ continue+ for blob in entries:+ try:+ if not blob.is_file():+ continue+ partial_hash = incomplete_blob_hash(blob.name)+ blob_hash = partial_hash if partial_hash is not None else blob.name+ if blob_hash not in present: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)))+ except OSError:+ continue+ total += sum(present.values())return totaldiff --git a/studio/backend/hub/utils/hf_cache_state.py b/studio/backend/hub/utils/hf_cache_state.pyindex 17f113e9538..2d82d7fe2bd 100644--- a/studio/backend/hub/utils/hf_cache_state.py+++ b/studio/backend/hub/utils/hf_cache_state.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport errnoimport os+import reimport shutilimport stat as stat_moduleimport sys@@ -24,6 +25,27 @@ TRANSPORT_AUTO = "auto"VALID_TRANSPORT_MODES = frozenset({TRANSPORT_HTTP, TRANSPORT_XET, TRANSPORT_AUTO})TRANSPORT_MARKER_NAME = ".transport"INCOMPLETE_SUFFIX = ".incomplete"+_PROCESS_UNIQUE_PARTIAL_RE = re.compile(+ r"^(?P<blob_hash>(?:[0-9a-fA-F]{40}|[0-9a-fA-F]{64}))\.[0-9a-fA-F]{8}$"+)+++def incomplete_blob_hash(name: str) -> Optional[str]:+ """Return the logical HF blob hash represented by a partial filename.++ huggingface_hub historically wrote ``<etag>.incomplete``. Version 1.18+ changed the writer to a process-unique ``<etag>.<8 hex>.incomplete`` path+ before atomically moving it into place. Hub etags used as cache blob names+ are Git SHA-1 or LFS SHA-256 hex digests, which lets us remove the nonce+ without mis-parsing an arbitrary legacy filename containing a dot.+ """+ if not name.endswith(INCOMPLETE_SUFFIX):+ return None+ stem = name[: -len(INCOMPLETE_SUFFIX)]+ if not stem:+ return None+ process_unique = _PROCESS_UNIQUE_PARTIAL_RE.fullmatch(stem)+ return process_unique.group("blob_hash") if process_unique else stemdef _safe_is_dir(path: Path, scan_errors: Optional[list] = None) -> bool:diff --git a/studio/backend/hub/utils/inventory_scan.py b/studio/backend/hub/utils/inventory_scan.pyindex f811124366d..92e1d8bc9db 100644--- a/studio/backend/hub/utils/inventory_scan.py+++ b/studio/backend/hub/utils/inventory_scan.py@@ -38,9 +38,9 @@ from hub.utils.gguf import (from hub.utils.state_dir import RepoTypefrom hub.utils.hf_cache_state import (- INCOMPLETE_SUFFIX,has_incomplete_blobs,hf_cache_roots,+ incomplete_blob_hash,iter_repo_cache_dirs,latest_snapshot_dir,repo_cache_dir_has_incomplete_blobs,@@ -525,8 +525,11 @@ def _repo_cache_dir_incomplete_hashes(repo_cache_dir: Path) -> set[str]:return hashesfor blob in entries:try:- if blob.is_file() and blob.name.endswith(INCOMPLETE_SUFFIX):- hashes.add(blob.name[: -len(INCOMPLETE_SUFFIX)])+ if not blob.is_file():+ continue+ blob_hash = incomplete_blob_hash(blob.name)+ if blob_hash is not None:+ hashes.add(blob_hash)except OSError:continuereturn hashes