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.

Give huggingface_hub 1.18+ back its resumable HTTP partials (#9602)

Daniel Hana000e03e6366
diff --git a/studio/backend/hub/tests/test_model_services.py b/studio/backend/hub/tests/test_model_services.py
index 0366fb31bec..363e6b85209 100644
--- a/studio/backend/hub/tests/test_model_services.py
+++ b/studio/backend/hub/tests/test_model_services.py
@@ -4846,7 +4846,7 @@ def test_prepare_cache_for_transport_preserves_same_transport_companion(monkeypa
"""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)
+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name, _root = None: True)
blobs = _vision_cache_root(monkeypatch, tmp_path)
companion = frozenset({"shared-mmproj"})
diff --git a/studio/backend/hub/tests/test_process_unique_incomplete_repro.py b/studio/backend/hub/tests/test_process_unique_incomplete_repro.py
index 075368f4f5f..6a7aa36f560 100644
--- a/studio/backend/hub/tests/test_process_unique_incomplete_repro.py
+++ b/studio/backend/hub/tests/test_process_unique_incomplete_repro.py
@@ -60,7 +60,7 @@ def test_registry_groups_duplicate_process_unique_writers_by_blob(monkeypatch, t
)
# 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)
+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name, _root = None: True)
assert (
download_registry.existing_blob_bytes(
"model",
diff --git a/studio/backend/hub/tests/test_resumable_partials.py b/studio/backend/hub/tests/test_resumable_partials.py
new file mode 100644
index 00000000000..0624930c052
--- /dev/null
+++ b/studio/backend/hub/tests/test_resumable_partials.py
@@ -0,0 +1,853 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Restoring huggingface_hub's resumable HTTP partials.
+
+The patched writer has to be a faithful 1.17 caller and nothing more: a stable name, opened for
+append, told how far it got, and left alone on failure. It also has to stand down wherever it
+cannot prove that is safe, which is the whole reason 1.18 removed it.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+import builtins
+import errno
+import os
+import sys
+import types
+
+import pytest
+
+from hub.utils import resumable_partials as rp
+
+
[email protected](autouse = True)
+def _fresh_probe():
+ rp.reset_probe_cache_for_tests()
+ yield
+ rp.reset_probe_cache_for_tests()
+
+
+def _fake_file_download(monkeypatch, *, xet_available = False):
+ """A stand-in for huggingface_hub.file_download that records what the writer did."""
+ calls = {"http_get": [], "stock": [], "moved": []}
+
+ def http_get(
+ url,
+ handle,
+ *,
+ resume_size = 0,
+ headers = None,
+ expected_size = None,
+ tqdm_class = None,
+ ):
+ calls["http_get"].append({"resume_size": resume_size, "mode": handle.mode})
+ handle.write(b"x" * 10)
+
+ def stock(**kwargs):
+ calls["stock"].append(kwargs)
+
+ module = types.ModuleType("huggingface_hub.file_download")
+ module._download_to_tmp_and_move = stock
+ module.http_get = http_get
+ module._chmod_and_move = lambda src, dst: calls["moved"].append((src, dst))
+ module._check_disk_space = lambda size, path: None
+ module.is_xet_available = lambda: xet_available
+
+ hub = types.ModuleType("huggingface_hub")
+ hub.__version__ = "1.28.0"
+ hub.file_download = module
+ hub.constants = types.SimpleNamespace(HF_HUB_CACHE = None)
+
+ monkeypatch.setitem(sys.modules, "huggingface_hub", hub)
+ monkeypatch.setitem(sys.modules, "huggingface_hub.file_download", module)
+ monkeypatch.setattr(rp, "_exclusion_is_provable", lambda _c = None: True)
+ return module, calls
+
+
+def _patched_writer(module):
+ return module._download_to_tmp_and_move
+
+
+# ---------------------------------------------------------------------------------------------
+# When it engages
+# ---------------------------------------------------------------------------------------------
+
+
+ "version, expected",
+ [("0.36.2", False), ("1.17.0", False), ("1.18.0", True), ("1.28.0", True), ("2.0.0", False)],
+)
+def test_only_the_versions_that_need_it_and_that_it_has_been_read_against(
+ monkeypatch, version, expected
+):
+ module, _ = _fake_file_download(monkeypatch)
+ sys.modules["huggingface_hub"].__version__ = version
+ assert rp.can_restore_partials() is expected
+
+
+def test_a_filesystem_that_grants_the_lock_twice_keeps_the_stock_writer(monkeypatch):
+ _fake_file_download(monkeypatch)
+ monkeypatch.setattr(rp, "_exclusion_is_provable", lambda _c = None: False)
+ assert rp.can_restore_partials() is False
+ assert rp.restore_resumable_partials() is False
+
+
+def test_a_hub_missing_the_pieces_is_left_alone(monkeypatch):
+ module, _ = _fake_file_download(monkeypatch)
+ del module._chmod_and_move
+ assert rp.can_restore_partials() is False
+
+
+def test_the_lock_probe_reports_a_working_lock(tmp_path, monkeypatch):
+ """The real probe, on the real filesystem the tests run on."""
+ monkeypatch.setattr(rp, "_probe_dir", lambda _c = None: tmp_path)
+ monkeypatch.setattr(rp, "_filesystem_is_local", lambda _d: True)
+ assert rp._exclusion_is_provable() is True
+ assert not list(tmp_path.iterdir()), "the probe left its file behind"
+
+
+def test_the_probe_follows_the_cache_studio_is_using_now(tmp_path, monkeypatch):
+ """Not the one this process booted with.
+
+ huggingface_hub resolves HF_HUB_CACHE at import and moving the cache in Settings does not
+ rewrite the live process, so probing the constant would judge a different filesystem than the
+ one a freshly spawned worker writes its partial to.
+ """
+ live = tmp_path / "moved-cache"
+ fake = types.ModuleType("utils.hf_cache_settings")
+ fake.active_hf_hub_cache = lambda: str(live)
+ monkeypatch.setitem(sys.modules, "utils.hf_cache_settings", fake)
+
+ assert rp._probe_dir() == live
+ assert live.is_dir(), "the probe did not create the cache root"
+
+
+def test_moving_the_cache_re_probes_rather_than_reusing_the_old_verdict(tmp_path, monkeypatch):
+ """Two roots can sit on filesystems that disagree about flock, so the verdict is per root."""
+ probed: list[str] = []
+ monkeypatch.setattr(rp, "_filesystem_is_local", lambda _d: True)
+ monkeypatch.setattr(
+ rp, "_lock_is_honoured_at", lambda directory: probed.append(directory) or True
+ )
+
+ first, second = tmp_path / "one", tmp_path / "two"
+ monkeypatch.setattr(rp, "_probe_dir", lambda _c = None: first)
+ rp._exclusion_is_provable()
+ monkeypatch.setattr(rp, "_probe_dir", lambda _c = None: second)
+ rp._exclusion_is_provable()
+
+ assert probed == [str(first), str(second)]
+
+
+def test_a_network_cache_keeps_the_stock_writer(tmp_path, monkeypatch):
+ """A probe on this host cannot speak for another client.
+
+ NFS mounted -o local_lock=flock keeps flock locks client-local, so two hosts each take the
+ lock and neither is refused. Nothing measurable here would notice, so the mount type decides.
+ """
+ for fstype in ("nfs4", "lustre", "gpfs", "cifs"):
+ rp.invalidate_probe_cache()
+ monkeypatch.setattr(rp, "_mounts", lambda: [(str(tmp_path), fstype)], raising = False)
+ assert rp._filesystem_is_local(str(tmp_path)) is False, fstype
+
+
+def test_a_network_cache_stands_down_even_where_the_lock_probe_would_pass(tmp_path, monkeypatch):
+ """Locality gates the probe, not the other way round: on NFS the probe passes and lies."""
+ monkeypatch.setattr(rp, "_probe_dir", lambda _c = None: tmp_path)
+ monkeypatch.setattr(rp, "_lock_is_honoured_at", lambda _d: True)
+ monkeypatch.setattr(rp, "_filesystem_is_local", lambda _d: False)
+ assert rp._exclusion_is_provable() is False
+
+
+def test_an_unidentifiable_mount_is_not_treated_as_local(tmp_path, monkeypatch):
+ """Failing closed: this decides whether to re-enable a shared writer."""
+ rp.invalidate_probe_cache()
+ monkeypatch.setattr(rp, "_mounts", lambda: [], raising = False)
+ assert rp._filesystem_is_local(str(tmp_path)) is False
+
+
+def test_a_local_disk_is_local(tmp_path):
+ """The filesystem the tests actually run on."""
+ rp.invalidate_probe_cache()
+ assert rp._filesystem_is_local(str(tmp_path)) is True
+
+
+def test_an_unrecognised_mount_type_is_not_treated_as_local(tmp_path, monkeypatch):
+ """Locality is an allowlist, because a FUSE daemon picks its own name.
+
+ Unless it negotiates FUSE_FLOCK_LOCKS the kernel answers flock locally (libfuse
+ fuse_lowlevel.h), so a cache on object storage passes the same-host probe while excluding no
+ other client. A blank fstype says nothing either. Neither may read as local.
+ """
+ for fstype in ("fuse.rclone", "fuse.s3fs", "fuse.gocryptfs", "somethingnew", ""):
+ rp.invalidate_probe_cache()
+ monkeypatch.setattr(rp, "_mounts", lambda: [(str(tmp_path), fstype)], raising = False)
+ assert rp._filesystem_is_local(str(tmp_path)) is False, fstype
+
+
+def test_the_known_local_filesystems_are_local(tmp_path, monkeypatch):
+ """The allowlist still has to admit the disks people actually keep a cache on."""
+ for fstype in ("ext4", "xfs", "btrfs", "zfs", "apfs", "NTFS", "tmpfs", "overlay"):
+ rp.invalidate_probe_cache()
+ monkeypatch.setattr(rp, "_mounts", lambda: [(str(tmp_path), fstype)], raising = False)
+ assert rp._filesystem_is_local(str(tmp_path)) is True, fstype
+
+
+def test_each_cache_root_is_judged_on_its_own_filesystem(tmp_path, monkeypatch):
+ """Studio remembers several cache roots and they need not lock alike.
+
+ One global verdict taken from the selected cache would have the boot sweep delete a local
+ cache's still-appendable partials whenever the selected one sits on a network mount.
+ """
+ from hub.utils import hf_cache_state
+
+ local_root, network_root = tmp_path / "local", tmp_path / "network"
+ local_root.mkdir()
+ network_root.mkdir()
+ # Past the version gate, so the filesystem is what is left to decide.
+ monkeypatch.setattr("huggingface_hub.__version__", "1.28.0", raising = False)
+ monkeypatch.setattr(rp, "_hub_is_patchable", lambda: True)
+ monkeypatch.setattr(
+ rp,
+ "_mounts",
+ lambda: [(str(local_root), "ext4"), (str(network_root), "nfs4")],
+ raising = False,
+ )
+ hf_cache_state.invalidate_partial_resumability()
+
+ partial = f"{'a' * 40}.incomplete"
+ assert hf_cache_state.partial_is_resumable(partial, local_root) is True
+ assert hf_cache_state.partial_is_resumable(partial, network_root) is False
+ hf_cache_state.invalidate_partial_resumability()
+
+
+def test_a_named_root_that_is_gone_is_not_recreated(tmp_path):
+ """Asking about a detached cache must not bring it back, nor claim it locks."""
+ missing = tmp_path / "unplugged"
+ assert rp._probe_dir(missing) is None
+ assert not missing.exists()
+
+
+def test_only_contention_counts_as_a_working_lock(tmp_path, monkeypatch):
+ """A filesystem with no locking answers ENOLCK or EOPNOTSUPP.
+
+ Reading either as "refused" would enable the shared writer on exactly the mounts that cannot
+ support it, which is the opposite of what the probe is for. flock never answers EACCES; that
+ is fcntl's.
+ """
+ import errno as errno_mod
+
+ calls = {"n": 0}
+
+ def flock(fd, op):
+ calls["n"] += 1
+ if calls["n"] == 1:
+ return None
+ raise OSError(flock.errno_value, "nope")
+
+ fake = types.ModuleType("fcntl")
+ fake.flock = flock
+ fake.LOCK_EX, fake.LOCK_NB = 2, 4
+ monkeypatch.setitem(sys.modules, "fcntl", fake)
+
+ for value, expected in (
+ (errno_mod.EWOULDBLOCK, True),
+ (errno_mod.EAGAIN, True),
+ (errno_mod.ENOLCK, False),
+ (errno_mod.EOPNOTSUPP, False),
+ (errno_mod.EINTR, False),
+ (errno_mod.EACCES, False),
+ ):
+ rp.invalidate_probe_cache()
+ calls["n"] = 0
+ flock.errno_value = value
+ assert rp._lock_is_honoured_at(str(tmp_path)) is expected, errno_mod.errorcode[value]
+
+
+def test_the_probe_does_not_follow_a_planted_symlink(tmp_path):
+ """A shared cache is writable by others, and a predictable probe name is a truncation gadget.
+
+ Plants a symlink at the name a pid-based scheme would pick, pointing at a file the Studio
+ account owns. Opening that path "wb" follows the link and empties the target, so the probe has
+ to use a name nobody can guess and create it exclusively.
+ """
+ import os as os_mod
+
+ rp.invalidate_probe_cache()
+ victim = tmp_path / "victim"
+ victim.write_bytes(b"important")
+ cache = tmp_path / "cache"
+ cache.mkdir()
+ planted = cache / (".unsloth-flock-probe.%d" % os_mod.getpid())
+ planted.symlink_to(victim)
+
+ assert rp._lock_is_honoured_at(str(cache)) is True
+ assert victim.read_bytes() == b"important", "the probe followed the symlink and truncated it"
+ assert planted.is_symlink(), "the probe wrote through the planted name"
+ planted.unlink()
+ assert not list(cache.iterdir()), "the probe left its own file behind"
+
+
+def test_the_verdict_is_cached_per_directory(tmp_path):
+ """The hot path asks per blob, so a repeat on the same root must not re-probe."""
+ rp.invalidate_probe_cache()
+ root = tmp_path / "cache"
+ root.mkdir()
+ assert rp._lock_is_honoured_at(str(root)) is True
+ before = rp._lock_is_honoured_on.cache_info()
+ assert rp._lock_is_honoured_at(str(root)) is True
+ assert rp._lock_is_honoured_on.cache_info().hits == before.hits + 1
+
+
+def test_a_new_mount_at_the_same_path_is_re_probed(tmp_path, monkeypatch):
+ """The path is not the identity of a filesystem.
+
+ An external cache can be unmounted and something else mounted at the same name, and a verdict
+ about the old filesystem says nothing about the new one, so the device is part of the key.
+ """
+ rp.invalidate_probe_cache()
+ root = tmp_path / "cache"
+ root.mkdir()
+ devices = iter([101, 101, 202])
+ monkeypatch.setattr(rp, "_device_at", lambda _d: next(devices))
+
+ assert rp._lock_is_honoured_at(str(root)) is True
+ hits = rp._lock_is_honoured_on.cache_info().hits
+ assert rp._lock_is_honoured_at(str(root)) is True
+ assert rp._lock_is_honoured_on.cache_info().hits == hits + 1, "same device should have hit"
+ misses = rp._lock_is_honoured_on.cache_info().misses
+ assert rp._lock_is_honoured_at(str(root)) is True
+ assert rp._lock_is_honoured_on.cache_info().misses == misses + 1, "remount was not re-probed"
+
+
+def test_a_probe_that_could_not_run_is_not_remembered(tmp_path, monkeypatch):
+ """A full disk or a briefly unwritable cache is not a measurement.
+
+ Caching one would have the backend condemn partials a freshly spawned worker is happily
+ resuming, for the life of the process.
+ """
+ rp.invalidate_probe_cache()
+ attempts: list[int] = []
+
+ def fail_once():
+ attempts.append(1)
+ if len(attempts) == 1:
+ raise OSError("mount table briefly unreadable")
+ return [(str(tmp_path), "ext4")]
+
+ monkeypatch.setattr(rp, "_mounts", fail_once, raising = False)
+
+ with pytest.raises(rp._ProbeUnavailable):
+ rp._filesystem_is_local(str(tmp_path))
+ assert rp._filesystem_is_local(str(tmp_path)) is True, "the failure was cached"
+
+
+def test_an_unrunnable_probe_travels_up_rather_than_answering(tmp_path, monkeypatch):
+ """The probe layer must not turn "could not tell" into "no", or a caller would cache it."""
+ rp.invalidate_probe_cache()
+ monkeypatch.setattr(rp, "_probe_dir", lambda _c = None: tmp_path)
+ monkeypatch.setattr(
+ rp, "_device_at", lambda _d: (_ for _ in ()).throw(rp._ProbeUnavailable("gone"))
+ )
+ with pytest.raises(rp._ProbeUnavailable):
+ rp._exclusion_is_provable()
+
+ # And out through the public entry point, past the version gate.
+ monkeypatch.setattr("huggingface_hub.__version__", "1.28.0", raising = False)
+ monkeypatch.setattr(rp, "_hub_is_patchable", lambda: True)
+ with pytest.raises(rp._ProbeUnavailable):
+ rp.can_restore_partials()
+
+
+def test_the_capability_reads_false_when_the_probe_could_not_run(monkeypatch):
+ """Fail closed at the boundary the callers use, and do not remember it there either."""
+ from hub.utils import hf_cache_state
+
+ monkeypatch.setattr("huggingface_hub.__version__", "1.28.0", raising = False)
+ attempts: list[int] = []
+
+ def unavailable(_c = None):
+ attempts.append(1)
+ raise rp._ProbeUnavailable("mount table briefly unreadable")
+
+ monkeypatch.setattr(rp, "can_restore_partials", unavailable)
+ hf_cache_state.invalidate_partial_resumability()
+
+ assert hf_cache_state.hf_partials_are_resumable() is False
+ assert hf_cache_state.hf_partials_are_resumable() is False
+ assert len(attempts) == 2, "the failure was cached instead of being re-probed"
+
+
+def test_changing_the_cache_home_invalidates_the_verdict(monkeypatch):
+ """The one place the root can move at runtime must drop both cached answers."""
+ from hub.utils import hf_cache_state
+
+ monkeypatch.setattr(rp, "can_restore_partials", lambda _c = None: True)
+ monkeypatch.setattr("huggingface_hub.__version__", "1.28.0", raising = False)
+ hf_cache_state.invalidate_partial_resumability()
+ assert hf_cache_state.hf_partials_are_resumable() is True
+
+ monkeypatch.setattr(rp, "can_restore_partials", lambda _c = None: False)
+ # No cache at this layer any more: the verdict follows the filesystem, and a result kept
+ # against the path alone outlives a remount at the same name.
+ assert hf_cache_state.hf_partials_are_resumable() is False
+ hf_cache_state.invalidate_partial_resumability()
+
+
+# ---------------------------------------------------------------------------------------------
+# What it does once it has
+# ---------------------------------------------------------------------------------------------
+
+
+def test_it_appends_to_the_stable_name_and_says_how_far_it_got(monkeypatch, tmp_path):
+ module, calls = _fake_file_download(monkeypatch)
+ assert rp.restore_resumable_partials() is True
+
+ partial = tmp_path / "abc.incomplete"
+ partial.write_bytes(b"y" * 40)
+ destination = tmp_path / "abc"
+
+ _patched_writer(module)(
+ incomplete_path = partial,
+ destination_path = destination,
+ url_to_download = "https://example/f",
+ headers = {},
+ expected_size = 50,
+ filename = "f",
+ )
+
+ assert calls["http_get"] == [{"resume_size": 40, "mode": "ab"}]
+ assert calls["moved"] == [(partial, destination)]
+ assert calls["stock"] == []
+
+
+def test_a_planted_symlink_is_not_appended_to(monkeypatch, tmp_path):
+ """The stable name is predictable, so on a shared cache it can be pre-created.
+
+ An unguarded "ab" would follow the link and append the model to whatever it points at, and
+ _chmod_and_move would then chmod that file too.
+ """
+ module, calls = _fake_file_download(monkeypatch)
+ assert rp.restore_resumable_partials() is True
+
+ victim = tmp_path / "victim"
+ victim.write_bytes(b"keep me")
+ partial = tmp_path / "abc.incomplete"
+ partial.symlink_to(victim)
+
+ _patched_writer(module)(
+ incomplete_path = partial,
+ destination_path = tmp_path / "abc",
+ url_to_download = "https://example/f",
+ headers = {},
+ expected_size = 50,
+ filename = "f",
+ )
+
+ assert victim.read_bytes() == b"keep me", "the download was appended to the symlink target"
+ assert not partial.is_symlink(), "the planted link survived"
+ # Started from zero rather than trusting the target's length.
+ assert calls["http_get"] == [{"resume_size": 0, "mode": "ab"}]
+
+
+def test_a_partial_left_by_another_user_is_not_built_on(monkeypatch, tmp_path):
+ """Nothing about a plain file says who wrote it.
+
+ A partial another account left is bytes of their choosing, and appending the server's
+ remaining range to a chosen prefix publishes a blob of exactly the right length and entirely
+ the wrong contents. huggingface_hub checks the size afterwards and never the hash
+ (huggingface_hub#3643), so no later step would catch it.
+ """
+ module, calls = _fake_file_download(monkeypatch)
+ assert rp.restore_resumable_partials() is True
+
+ partial = tmp_path / "abc.incomplete"
+ partial.write_bytes(b"poison" * 100)
+
+ # Only the planted file reads as somebody else's: owning one for real needs root, and the
+ # fresh partial that replaces it has to still be ours or the test proves nothing about the
+ # retry. Keyed on which open it is rather than on the inode, since a filesystem is free to
+ # hand the replacement the inode the unlinked file just released.
+ real_fstat = os.fstat
+ opens: list[int] = []
+
+ class _Foreign:
+ def __init__(self, info):
+ self.st_mode, self.st_nlink = info.st_mode, info.st_nlink
+ self.st_dev, self.st_ino = info.st_dev, info.st_ino
+ self.st_uid = info.st_uid + 1
+
+ def fstat(descriptor, *args, **kwargs):
+ info = real_fstat(descriptor, *args, **kwargs)
+ opens.append(1)
+ return _Foreign(info) if len(opens) == 1 else info
+
+ monkeypatch.setattr(rp.os, "fstat", fstat)
+
+ _patched_writer(module)(
+ incomplete_path = partial,
+ destination_path = tmp_path / "abc",
+ url_to_download = "https://example/f",
+ headers = {},
+ expected_size = 50,
+ filename = "f",
+ )
+
+ assert calls["http_get"] == [{"resume_size": 0, "mode": "ab"}], "it resumed on foreign bytes"
+ assert partial.read_bytes() == b"x" * 10, "the foreign prefix survived into the blob"
+
+
+def test_an_unopenable_partial_defers_instead_of_failing_the_download(monkeypatch, tmp_path):
+ """A 0600 partial from another account answers EACCES, and that is not a reason to give up.
+
+ Stock writes a file of its own and never touches this one, so the download still happens.
+ Raising here would fail every attempt at that blob for good, which is worse than not resuming.
+ """
+ module, calls = _fake_file_download(monkeypatch)
+ assert rp.restore_resumable_partials() is True
+
+ partial = tmp_path / "abc.incomplete"
+ partial.write_bytes(b"someone else's")
+ real_open = os.open
+
+ def refuse(target, *args, **kwargs):
+ if str(target) == str(partial):
+ raise PermissionError(errno.EACCES, "Permission denied", str(target))
+ return real_open(target, *args, **kwargs)
+
+ monkeypatch.setattr(rp.os, "open", refuse)
+
+ _patched_writer(module)(
+ incomplete_path = partial,
+ destination_path = tmp_path / "abc",
+ url_to_download = "https://example/f",
+ headers = {},
+ expected_size = 50,
+ filename = "f",
+ )
+
+ assert len(calls["stock"]) == 1, "the download was abandoned rather than handed to stock"
+ assert calls["http_get"] == []
+ assert partial.read_bytes() == b"someone else's", "it deleted a partial it could not read"
+
+
+def test_a_partial_swapped_after_the_last_write_is_not_published(monkeypatch, tmp_path):
+ """_chmod_and_move resolves the name again, so the name has to still hold what was written.
+
+ Otherwise a shared cache lets another account replace the partial once writing stops and have
+ its file installed as the blob, under a descriptor that passed every check.
+ """
+ module, calls = _fake_file_download(monkeypatch)
+ assert rp.restore_resumable_partials() is True
+
+ partial = tmp_path / "abc.incomplete"
+ real_http_get = module.http_get
+
+ def swap_then_write(url, handle, **kwargs):
+ real_http_get(url, handle, **kwargs)
+ # The writer is finished with the descriptor; the name now points somewhere else.
+ partial.unlink()
+ partial.write_bytes(b"attacker's model")
+
+ module.http_get = swap_then_write
+
+ _patched_writer(module)(
+ incomplete_path = partial,
+ destination_path = tmp_path / "abc",
+ url_to_download = "https://example/f",
+ headers = {},
+ expected_size = 50,
+ filename = "f",
+ )
+
+ assert calls["moved"] == [], "the replacement was published as the blob"
+ assert partial.read_bytes() == b"attacker's model", "it should be left for the retry to judge"
+
+
+def test_ownership_that_cannot_be_established_is_an_objection(monkeypatch, tmp_path):
+ """Windows has no st_uid and no ACL read without pywin32, so nothing there can be vouched for.
+
+ _exclusion_is_provable keeps the shared writer off that platform, and this is the second line:
+ if it were ever enabled, an unknown owner still must not read as ours.
+ """
+ monkeypatch.delattr(rp.os, "geteuid", raising = False)
+ target = tmp_path / "partial"
+ target.write_bytes(b"whoever wrote this")
+ descriptor = os.open(target, os.O_RDONLY)
+ try:
+ assert rp._objection_to(descriptor) is not None
+ finally:
+ os.close(descriptor)
+
+
+def test_windows_keeps_the_stock_writer(monkeypatch, tmp_path):
+ """No fcntl and no way to establish ownership, so the shared name stays off.
+
+ os.name is faked as well as fcntl: on a posix box the answer would be False either way, and
+ a test that cannot tell the difference would not notice the writer being switched back on.
+ """
+ monkeypatch.setattr(rp, "_probe_dir", lambda _c = None: tmp_path)
+ monkeypatch.setattr(rp, "_filesystem_is_local", lambda _d: True)
+ monkeypatch.setattr(rp.os, "name", "nt")
+ real_import = builtins.__import__
+
+ def without_fcntl(name, *args, **kwargs):
+ if name == "fcntl":
+ raise ImportError("no fcntl on Windows")
+ return real_import(name, *args, **kwargs)
+
+ monkeypatch.setattr(builtins, "__import__", without_fcntl)
+ assert rp._exclusion_is_provable() is False
+
+
+def test_an_oversized_partial_is_restarted_rather_than_resumed(monkeypatch, tmp_path):
+ """A partial longer than the file cannot be resumed from.
+
+ A Range starting past the end answers 416, and it would answer 416 on every later attempt too,
+ so the download would be wedged where the stock writer's fresh name recovers.
+ """
+ module, calls = _fake_file_download(monkeypatch)
+ assert rp.restore_resumable_partials() is True
+
+ partial = tmp_path / "abc.incomplete"
+ partial.write_bytes(b"z" * 80)
+
+ _patched_writer(module)(
+ incomplete_path = partial,
+ destination_path = tmp_path / "abc",
+ url_to_download = "https://example/f",
+ headers = {},
+ expected_size = 50,
+ filename = "f",
+ )
+
+ assert calls["http_get"] == [{"resume_size": 0, "mode": "ab"}]
+ assert partial.read_bytes() == b"x" * 10, "the oversized bytes were kept"
+
+
+def test_a_complete_partial_is_left_for_upstream_to_finish(monkeypatch, tmp_path):
+ """Exactly the declared size is not the wedged case: http_get returns early and it publishes.
+
+ Restarting here would refetch the whole file for nothing, so the boundary is strictly greater.
+ """
+ module, calls = _fake_file_download(monkeypatch)
+ assert rp.restore_resumable_partials() is True
+
+ partial = tmp_path / "abc.incomplete"
+ partial.write_bytes(b"z" * 50)
+
+ _patched_writer(module)(
+ incomplete_path = partial,
+ destination_path = tmp_path / "abc",
+ url_to_download = "https://example/f",
+ headers = {},
+ expected_size = 50,
+ filename = "f",
+ )
+
+ assert calls["http_get"] == [{"resume_size": 50, "mode": "ab"}], "it restarted a finished file"
+
+
+def test_an_unavailable_probe_does_not_take_the_worker_down(monkeypatch):
+ """The worker patches at import, so this must never raise out of here.
+
+ _ProbeUnavailable is what a transient mount-table or write-probe failure raises; escaping it
+ would kill the download process instead of leaving it with the stock writer.
+ """
+ _fake_file_download(monkeypatch)
+
+ def unavailable(_c = None):
+ raise rp._ProbeUnavailable("mount table briefly unreadable")
+
+ monkeypatch.setattr(rp, "can_restore_partials", unavailable)
+ assert rp.restore_resumable_partials() is False
+
+
+def test_a_planted_hard_link_is_not_appended_to(monkeypatch, tmp_path):
+ """O_NOFOLLOW cannot see a hard link, so the size check is what catches this one."""
+ module, calls = _fake_file_download(monkeypatch)
+ assert rp.restore_resumable_partials() is True
+
+ victim = tmp_path / "victim"
+ victim.write_bytes(b"keep me")
+ partial = tmp_path / "abc.incomplete"
+ os.link(victim, partial)
+
+ _patched_writer(module)(
+ incomplete_path = partial,
+ destination_path = tmp_path / "abc",
+ url_to_download = "https://example/f",
+ headers = {},
+ expected_size = 50,
+ filename = "f",
+ )
+
+ assert victim.read_bytes() == b"keep me", "the download was appended through the hard link"
+ assert calls["http_get"] == [{"resume_size": 0, "mode": "ab"}]
+
+
+def test_a_planted_partial_that_cannot_be_removed_defers_to_stock(monkeypatch, tmp_path):
+ """Stock invents its own name, so it cannot be steered by a planted one either."""
+ module, calls = _fake_file_download(monkeypatch)
+ assert rp.restore_resumable_partials() is True
+
+ victim = tmp_path / "victim"
+ victim.write_bytes(b"keep me")
+ partial = tmp_path / "abc.incomplete"
+ partial.symlink_to(victim)
+
+ def refuse(_path):
+ raise PermissionError("sticky directory")
+
+ monkeypatch.setattr(rp.os, "unlink", refuse)
+
+ _patched_writer(module)(
+ incomplete_path = partial,
+ destination_path = tmp_path / "abc",
+ url_to_download = "https://example/f",
+ headers = {},
+ expected_size = 50,
+ filename = "f",
+ )
+
+ assert calls["http_get"] == [], "the patched writer wrote anyway"
+ assert len(calls["stock"]) == 1
+ assert victim.read_bytes() == b"keep me"
+
+
+def test_a_failed_download_leaves_the_partial_for_the_next_attempt(monkeypatch, tmp_path):
+ module, _ = _fake_file_download(monkeypatch)
+ rp.restore_resumable_partials()
+
+ def boom(*_args, **_kwargs):
+ raise OSError("connection reset")
+
+ module.http_get = boom
+ partial = tmp_path / "abc.incomplete"
+ partial.write_bytes(b"y" * 40)
+
+ with pytest.raises(OSError):
+ _patched_writer(module)(
+ incomplete_path = partial,
+ destination_path = tmp_path / "abc",
+ url_to_download = "https://example/f",
+ headers = {},
+ expected_size = 50,
+ filename = "f",
+ )
+ assert partial.exists() and partial.stat().st_size == 40
+
+
+def test_xet_keeps_its_own_writer(monkeypatch, tmp_path):
+ module, calls = _fake_file_download(monkeypatch, xet_available = True)
+ rp.restore_resumable_partials()
+
+ _patched_writer(module)(
+ incomplete_path = tmp_path / "abc.incomplete",
+ destination_path = tmp_path / "abc",
+ url_to_download = "https://example/f",
+ headers = {},
+ expected_size = 50,
+ filename = "f",
+ xet_file_data = object(),
+ )
+ assert calls["http_get"] == [] and len(calls["stock"]) == 1
+
+
+def test_a_xet_backed_repo_downloading_over_http_still_resumes(monkeypatch, tmp_path):
+ """xet_file_data is set for any XET-backed repo, including when hf_xet is off.
+
+ Gating on the metadata rather than on whether XET will actually run silently disables this for
+ most of the Hub.
+ """
+ module, calls = _fake_file_download(monkeypatch, xet_available = False)
+ rp.restore_resumable_partials()
+
+ _patched_writer(module)(
+ incomplete_path = tmp_path / "abc.incomplete",
+ destination_path = tmp_path / "abc",
+ url_to_download = "https://example/f",
+ headers = {},
+ expected_size = 50,
+ filename = "f",
+ xet_file_data = object(),
+ )
+ assert len(calls["http_get"]) == 1 and calls["stock"] == []
+
+
+def test_force_download_defers_to_stock(monkeypatch, tmp_path):
+ module, calls = _fake_file_download(monkeypatch)
+ rp.restore_resumable_partials()
+
+ _patched_writer(module)(
+ incomplete_path = tmp_path / "abc.incomplete",
+ destination_path = tmp_path / "abc",
+ url_to_download = "https://example/f",
+ headers = {},
+ expected_size = 50,
+ filename = "f",
+ force_download = True,
+ )
+ assert calls["http_get"] == [] and len(calls["stock"]) == 1
+
+
+def test_an_already_downloaded_blob_is_not_fetched_again(monkeypatch, tmp_path):
+ module, calls = _fake_file_download(monkeypatch)
+ rp.restore_resumable_partials()
+
+ destination = tmp_path / "abc"
+ destination.write_bytes(b"done")
+ _patched_writer(module)(
+ incomplete_path = tmp_path / "abc.incomplete",
+ destination_path = destination,
+ url_to_download = "https://example/f",
+ headers = {},
+ expected_size = 50,
+ filename = "f",
+ )
+ assert calls["http_get"] == [] and calls["stock"] == []
+
+
+def test_patching_twice_keeps_one_layer(monkeypatch):
+ module, _ = _fake_file_download(monkeypatch)
+ assert rp.restore_resumable_partials() is True
+ first = module._download_to_tmp_and_move
+ assert rp.restore_resumable_partials() is True
+ assert module._download_to_tmp_and_move is first
+
+
+# ---------------------------------------------------------------------------------------------
+# The capability the UI reads
+# ---------------------------------------------------------------------------------------------
+
+
+def test_the_ui_is_told_partials_are_resumable_again(monkeypatch):
+ from hub.utils import hf_cache_state
+
+ _fake_file_download(monkeypatch)
+ hf_cache_state.invalidate_partial_resumability()
+ monkeypatch.setattr(rp, "can_restore_partials", lambda _c = None: True)
+ assert hf_cache_state.hf_partials_are_resumable() is True
+
+ hf_cache_state.invalidate_partial_resumability()
+ monkeypatch.setattr(rp, "can_restore_partials", lambda _c = None: False)
+ assert hf_cache_state.hf_partials_are_resumable() is False
+ hf_cache_state.invalidate_partial_resumability()
+
+
+def test_the_worker_restores_it_on_import():
+ """A structural check: moving the call out of the worker fails here, not in the field."""
+ import ast
+
+ source = (Path(rp.__file__).parent.parent / "workers" / "hf_download.py").read_text(
+ encoding = "utf-8"
+ )
+ tree = ast.parse(source)
+ calls = {
+ node.func.id
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Name)
+ }
+ assert "restore_resumable_partials" in calls
diff --git a/studio/backend/hub/tests/test_unresumable_partial_purge.py b/studio/backend/hub/tests/test_unresumable_partial_purge.py
index fba304ee937..b5c1e228347 100644
--- a/studio/backend/hub/tests/test_unresumable_partial_purge.py
+++ b/studio/backend/hub/tests/test_unresumable_partial_purge.py
@@ -10,7 +10,7 @@ import time
import pytest
-from hub.utils import download_registry, hf_cache_state
+from hub.utils import download_registry, hf_cache_state, resumable_partials
_MAIN = "a" * 64
@@ -70,18 +70,48 @@ def _prepare(**kwargs):
],
)
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."""
+ """1.18 is the line: before it a partial is appended to, after it a new file is written.
+
+ Pinned with the restoration in :mod:`hub.utils.resumable_partials` unavailable, which is what
+ a machine whose filesystem cannot prove ``flock`` excludes a second writer sees.
+ """
+ monkeypatch.setattr(resumable_partials, "can_restore_partials", lambda _c = None: False)
monkeypatch.setattr("huggingface_hub.__version__", hf_version, raising = False)
- hf_cache_state.hf_partials_are_resumable.cache_clear()
+ hf_cache_state.invalidate_partial_resumability()
try:
assert hf_cache_state.hf_partials_are_resumable() is resumable
finally:
- hf_cache_state.hf_partials_are_resumable.cache_clear()
+ hf_cache_state.invalidate_partial_resumability()
+
+
[email protected]("hf_version", ["1.18.0", "1.23.0", "1.27.0"])
+def test_restoring_the_1_17_writer_makes_partials_resumable_again(monkeypatch, hf_version):
+ """Where the worker puts the append-mode writer back, a partial is worth keeping again."""
+ monkeypatch.setattr(resumable_partials, "can_restore_partials", lambda _c = None: True)
+ monkeypatch.setattr("huggingface_hub.__version__", hf_version, raising = False)
+ hf_cache_state.invalidate_partial_resumability()
+ try:
+ assert hf_cache_state.hf_partials_are_resumable() is True
+ finally:
+ hf_cache_state.invalidate_partial_resumability()
+
+
+def test_a_nonce_partial_stays_unresumable_after_the_writer_is_restored(monkeypatch):
+ """Bytes already on disk under a nonce name are still litter: the restored writer opens the
+ stable name, so it never finds them. Only what it writes from here is reusable."""
+ monkeypatch.setattr(resumable_partials, "can_restore_partials", lambda _c = None: True)
+ monkeypatch.setattr("huggingface_hub.__version__", "1.28.0", raising = False)
+ hf_cache_state.invalidate_partial_resumability()
+ try:
+ assert hf_cache_state.partial_is_resumable(_NONCE_PARTIAL) is False
+ assert hf_cache_state.partial_is_resumable(_LEGACY_PARTIAL) is True
+ finally:
+ hf_cache_state.invalidate_partial_resumability()
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)
+ monkeypatch.setattr(hf_cache_state, "hf_partials_are_resumable", lambda _root = None: True)
assert hf_cache_state.partial_is_resumable(_LEGACY_PARTIAL) is True
assert hf_cache_state.partial_is_resumable(_NONCE_PARTIAL) is False
@@ -89,7 +119,7 @@ def test_a_nonce_partial_is_unresumable_even_under_a_legacy_writer(monkeypatch):
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)
+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name, _root = None: False)
_prepare() # writes the http marker
partial = blobs / _NONCE_PARTIAL
partial.write_bytes(b"x" * 25)
@@ -101,7 +131,7 @@ def test_unresumable_partial_is_purged_despite_a_matching_marker(monkeypatch, bl
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)
+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name, _root = None: True)
_prepare()
partial = blobs / _LEGACY_PARTIAL
partial.write_bytes(b"x" * 25)
@@ -113,7 +143,7 @@ def test_resumable_partial_survives_a_matching_marker(monkeypatch, blobs):
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)
+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name, _root = None: False)
_prepare()
partial = blobs / _NONCE_PARTIAL
partial.write_bytes(b"x" * 25) # mtime is now, as a live writer's would be
@@ -124,7 +154,7 @@ def test_a_partial_still_being_written_is_left_alone(monkeypatch, blobs):
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)
+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name, _root = None: True)
download_registry.prepare_cache_for_transport(
"model",
"Org/Model",
@@ -141,7 +171,7 @@ def test_a_mismatched_marker_still_purges_without_waiting(monkeypatch, blobs):
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)
+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name, _root = None: False)
_prepare()
mine = blobs / _NONCE_PARTIAL
mine.write_bytes(b"x" * 25)
@@ -173,16 +203,16 @@ def test_transport_status_does_not_promise_a_resume_it_cannot_keep(monkeypatch,
download_registry._write_marker(blobs.parent, download_registry.TRANSPORT_HTTP)
(blobs / _NONCE_PARTIAL).write_bytes(b"x" * 25)
- monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name: True)
+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name, _root = None: True)
assert download_registry.is_resumable_partial("model", "Org/Model") is True
- monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name: False)
+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name, _root = None: 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)
+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name, _root = None: False)
_prepare()
partial = blobs / _NONCE_PARTIAL
partial.write_bytes(b"x" * 25)
@@ -199,7 +229,7 @@ def test_a_skipped_partial_is_swept_once_it_ages_out(monkeypatch, blobs):
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)
+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name, _root = None: False)
live = blobs / _NONCE_PARTIAL
live.write_bytes(b"x" * 25)
peer = blobs / f"{_PEER}.feedface{hf_cache_state.INCOMPLETE_SUFFIX}"
@@ -219,7 +249,7 @@ def test_the_sweep_still_spares_a_live_writer_and_a_peer(monkeypatch, blobs):
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)
+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name, _root = None: False)
_prepare()
partial = blobs / _NONCE_PARTIAL
partial.write_bytes(b"x" * 25)
@@ -260,10 +290,10 @@ def test_unresumable_bytes_are_not_credited_against_the_disk_check(monkeypatch,
lambda *_a, **_k: [blobs.parent],
)
- monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name: False)
+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name, _root = None: False)
assert download_registry.existing_blob_bytes("model", "Org/Model", frozenset({_MAIN})) == 0
- monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name: True)
+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name, _root = None: True)
assert download_registry.existing_blob_bytes("model", "Org/Model", frozenset({_MAIN})) == 25
@@ -275,7 +305,7 @@ def test_a_finalized_blob_still_counts_against_the_disk_check(monkeypatch, blobs
"iter_destructive_repo_cache_dirs",
lambda *_a, **_k: [blobs.parent],
)
- monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name: False)
+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name, _root = None: False)
assert download_registry.existing_blob_bytes("model", "Org/Model", frozenset({_MAIN})) == 25
@@ -289,7 +319,7 @@ def test_startup_sweep_does_not_depend_on_a_breadcrumb(monkeypatch, tmp_path, bl
_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, "partial_is_resumable", lambda _name, _root = None: False)
monkeypatch.setattr(
download_registry, "hf_cache_roots", lambda *_a, **_k: [blobs.parent.parent]
)
@@ -309,7 +339,7 @@ def test_startup_sweep_leaves_a_resumable_partial_alone(monkeypatch, tmp_path, b
_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, "partial_is_resumable", lambda _name, _root = None: True)
monkeypatch.setattr(
download_registry, "hf_cache_roots", lambda *_a, **_k: [blobs.parent.parent]
)
@@ -322,7 +352,7 @@ def test_startup_sweep_leaves_a_resumable_partial_alone(monkeypatch, tmp_path, b
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)
+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name, _root = None: False)
partial = blobs / _NONCE_PARTIAL
partial.write_bytes(b"x" * 25) # freshly written, as a just-cancelled download's would be
monkeypatch.setattr(
@@ -348,7 +378,7 @@ def test_a_reaped_job_does_not_wait_out_the_grace_on_its_own_blobs(monkeypatch,
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, "partial_is_resumable", lambda _name, _root = None: False)
monkeypatch.setattr(download_registry, "blob_download_lock_held", lambda *_a: True)
partial = blobs / _NONCE_PARTIAL
partial.write_bytes(b"x" * 25)
@@ -371,7 +401,7 @@ def test_ownership_never_overrides_the_lock(monkeypatch, blobs):
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)
+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name, _root = None: False)
partial = blobs / _NONCE_PARTIAL
partial.write_bytes(b"x" * 25)
monkeypatch.setattr(
@@ -397,7 +427,7 @@ def test_the_sweep_accepts_the_string_root_the_metadata_holds(monkeypatch, tmp_p
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)
+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name, _root = None: False)
blobs = tmp_path / "hub" / "models--Org--Model" / "blobs"
blobs.mkdir(parents = True)
partial = blobs / _NONCE_PARTIAL
@@ -418,7 +448,7 @@ def test_the_sweep_accepts_the_string_root_the_metadata_holds(monkeypatch, tmp_p
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)
+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name, _root = None: False)
partial = blobs / _NONCE_PARTIAL
partial.write_bytes(b"x" * 25) # fresh, as a just-cancelled snapshot download's would be
monkeypatch.setattr(
@@ -457,7 +487,7 @@ def test_the_boot_sweep_runs_after_the_orphan_is_killed(monkeypatch, tmp_path, b
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, "partial_is_resumable", lambda _name, _root = None: 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)
@@ -493,7 +523,7 @@ def test_the_boot_sweep_runs_after_the_orphan_is_killed(monkeypatch, tmp_path, b
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)
+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name, _root = None: 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(
@@ -564,7 +594,7 @@ def test_a_worker_that_will_not_die_keeps_its_breadcrumb_and_its_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, "partial_is_resumable", lambda _name, _root = None: 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
@@ -579,7 +609,7 @@ def test_a_worker_that_will_not_die_keeps_its_breadcrumb_and_its_partial(
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)
+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name, _root = None: False)
(blobs / _NONCE_PARTIAL).write_bytes(b"x" * 25)
monkeypatch.setattr(
download_registry,
@@ -596,7 +626,7 @@ def test_a_locked_peer_partial_still_counts_against_the_disk_check(monkeypatch,
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)
+ monkeypatch.setattr(download_registry, "partial_is_resumable", lambda _name, _root = None: False)
root = tmp_path / "hub"
mine = root / "models--Org--Model" / "blobs"
other = root / "models--org--model" / "blobs"
@@ -715,7 +745,7 @@ def test_unreadable_breadcrumbs_do_not_cancel_the_cache_sweep(monkeypatch, tmp_p
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, "partial_is_resumable", lambda _name, _root = None: False)
monkeypatch.setattr(
download_registry, "hf_cache_roots", lambda *_a, **_k: [blobs.parent.parent]
)
@@ -728,7 +758,7 @@ def test_unreadable_breadcrumbs_do_not_cancel_the_cache_sweep(monkeypatch, tmp_p
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, "partial_is_resumable", lambda _name, _root = None: False)
monkeypatch.setattr(download_registry, "blob_download_lock_held", lambda *_a: False) # lies
monkeypatch.setattr(download_registry, "_STILLNESS_PROBE_SECONDS", 0.05)
monkeypatch.setattr(
@@ -760,7 +790,7 @@ def test_an_owned_partial_that_is_still_growing_is_spared(monkeypatch, blobs):
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, "partial_is_resumable", lambda _name, _root = None: False)
monkeypatch.setattr(download_registry, "_STILLNESS_PROBE_SECONDS", 0.05)
monkeypatch.setattr(
download_registry,
@@ -801,7 +831,7 @@ def test_a_breadcrumb_whose_worker_already_exited_is_claimed(monkeypatch, tmp_pa
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, "partial_is_resumable", lambda _name, _root = None: 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)
diff --git a/studio/backend/hub/utils/download_registry.py b/studio/backend/hub/utils/download_registry.py
index a45f74e7f0b..bdcb20e54b2 100644
--- a/studio/backend/hub/utils/download_registry.py
+++ b/studio/backend/hub/utils/download_registry.py
@@ -571,7 +571,7 @@ def _purge_incomplete_blobs(
if only_hashes is not None and blob_hash not in only_hashes:
continue
if unresumable_only:
- if partial_is_resumable(blob.name):
+ if partial_is_resumable(blob.name, entry.parent):
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
@@ -1063,7 +1063,7 @@ def _resumable_blob_hashes(entry: Path) -> set[str]:
if not blob.is_file():
continue
blob_hash = incomplete_blob_hash(blob.name)
- if blob_hash is not None and partial_is_resumable(blob.name):
+ if blob_hash is not None and partial_is_resumable(blob.name, entry.parent):
out.add(blob_hash)
except OSError:
return out
@@ -1124,7 +1124,7 @@ def incomplete_blob_hashes(
blob_hash = incomplete_blob_hash(blob.name)
if blob_hash is None:
continue
- if resumable_only and not partial_is_resumable(blob.name):
+ if resumable_only and not partial_is_resumable(blob.name, entry.parent):
continue
out.add(blob_hash)
except OSError:
@@ -1202,7 +1202,7 @@ def existing_blob_bytes(
continue
if (
partial_hash is not None
- and not partial_is_resumable(blob.name)
+ and not partial_is_resumable(blob.name, entry.parent)
and not blob_download_lock_held(entry, blob_hash)
):
# Callers spend this on "bytes we will not have to fetch again", and
diff --git a/studio/backend/hub/utils/hf_cache_state.py b/studio/backend/hub/utils/hf_cache_state.py
index 42e98b9b6e4..a64775b4a04 100644
--- a/studio/backend/hub/utils/hf_cache_state.py
+++ b/studio/backend/hub/utils/hf_cache_state.py
@@ -9,7 +9,6 @@ import re
import shutil
import stat as stat_module
import sys
-from functools import lru_cache
from pathlib import Path, PureWindowsPath
from typing import Iterable, Iterator, Optional
@@ -59,8 +58,7 @@ _LAST_RESUMABLE_PARTIAL_VERSION = (1, 17)
ABANDONED_PARTIAL_SECONDS = 120
-@lru_cache(maxsize = 1)
-def hf_partials_are_resumable() -> bool:
+def hf_partials_are_resumable(hub_cache: Optional[str] = None) -> 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
@@ -71,6 +69,19 @@ def hf_partials_are_resumable() -> bool:
An unreadable version answers True: not knowing which writer is installed is not grounds
for deleting bytes that may still be resumable.
+
+ On 1.18+ this also asks whether the download worker will put the 1.17 writer back
+ (:mod:`hub.utils.resumable_partials`), since a restored resumer makes partials reusable again.
+ That half turns on the filesystem the partial is on, so *hub_cache* names the root being asked
+ about. Studio remembers several and they need not lock alike: without it, a selected cache on a
+ network mount would condemn a local cache's partials to the abandoned-partial sweep. Omitting it
+ asks about the cache in force, which is where a new download lands.
+
+ Deliberately not cached here. The verdict is a fact about a filesystem, not about a path, so a
+ result keyed on the path alone survives a remount at the same name and outlives a momentary
+ failure to probe. The expensive part, the lock probe, is cached in
+ :mod:`hub.utils.resumable_partials` against the mounted device instead, and a probe that could
+ not run raises rather than answering, so nothing remembers a bad moment.
"""
try:
from huggingface_hub import __version__ as hf_version
@@ -86,7 +97,35 @@ def hf_partials_are_resumable() -> bool:
if not digits:
return True
release.append(int(digits))
- return tuple(release) <= _LAST_RESUMABLE_PARTIAL_VERSION
+ if tuple(release) <= _LAST_RESUMABLE_PARTIAL_VERSION:
+ return True
+ try:
+ from hub.utils.resumable_partials import _ProbeUnavailable, can_restore_partials
+ try:
+ return can_restore_partials(hub_cache)
+ except _ProbeUnavailable:
+ # Nothing was shown, so nothing is promised -- and nothing is remembered either.
+ return False
+ except Exception: # noqa: BLE001 - no restoration is just the stock answer
+ from loggers import get_logger
+ get_logger(__name__).debug(
+ "Resumable-partial restoration unavailable; partials stay unresumable.",
+ exc_info = True,
+ )
+ return False
+
+
+def invalidate_partial_resumability() -> None:
+ """Re-decide resumability, for when the cache moves to another filesystem.
+
+ The verdict depends on whether ``flock`` excludes a second writer where the partial lands, so
+ it cannot be carried over from the old root.
+ """
+ try:
+ from hub.utils.resumable_partials import invalidate_probe_cache
+ invalidate_probe_cache()
+ except Exception: # noqa: BLE001 - nothing to invalidate is not an error
+ pass
def partial_is_process_unique(name: str) -> bool:
@@ -131,17 +170,20 @@ def blob_download_lock_held(entry: Path, blob_hash: str) -> bool:
return True
-def partial_is_resumable(name: str) -> bool:
+def partial_is_resumable(name: str, hub_cache: Optional[Path | str] = None) -> 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).
+
+ *hub_cache* is the root the partial lives under. Callers walking more than one cache must pass
+ it, since the answer is partly a property of that root's filesystem.
"""
if partial_is_process_unique(name):
return False
- return hf_partials_are_resumable()
+ return hf_partials_are_resumable(str(hub_cache) if hub_cache is not None else None)
def _safe_is_dir(path: Path, scan_errors: Optional[list] = None) -> bool:
diff --git a/studio/backend/hub/utils/resumable_partials.py b/studio/backend/hub/utils/resumable_partials.py
new file mode 100644
index 00000000000..6ded1fe867b
--- /dev/null
+++ b/studio/backend/hub/utils/resumable_partials.py
@@ -0,0 +1,576 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Give huggingface_hub >= 1.18 back its resumable HTTP partials.
+
+1.18 replaced the shared ``<etag>.incomplete``, opened append and continued with a Range request,
+with a process-unique ``<etag>.<nonce>.incomplete`` opened ``"wb"`` and unlinked on the way out
+(huggingface/huggingface_hub#4228). So a cancelled or killed transfer refetches from zero, and
+:mod:`hub.workers.hf_download`, whose SIGKILL then restart loop reads ``.incomplete`` for its resume
+offset, has nothing to read.
+
+Only the caller went. ``http_get`` still takes ``resume_size``, still sends the Range header, and
+still does ``seek(0)`` + ``truncate()`` when a server answers 200 to a Range request, the case that
+would otherwise duplicate bytes. This restores the 1.17 caller and nothing else.
+
+Upstream removed it because the shared name corrupts the cache where ``flock(2)`` does not exclude
+every caller (Lustre, GPFS, some NFS): two processes append to one file. So exclusion has to be
+shown, and where it cannot be, the stock writer stays and partials keep reporting as unresumable.
+
+Two things have to hold, because a probe run here can only speak for this host. The cache must be
+on a local filesystem: NFS mounted ``-o local_lock=flock`` keeps flock locks client-local, so two
+hosts each take "the" lock and neither sees ``EWOULDBLOCK``, and no test on one of them can notice.
+And ``flock`` must actually exclude a second holder here, which :func:`_lock_is_honoured_at`
+measures by taking the lock twice. Only ``EWOULDBLOCK``/``EAGAIN`` counts as exclusion: a
+filesystem with no locking answers ``ENOLCK`` or ``EOPNOTSUPP``, and reading that as "refused"
+would enable the shared writer on precisely the mounts that cannot support it.
+
+Neither can be shown on Windows, which has no ``fcntl`` and no way to establish who owns a file
+without pywin32, so the shared name stays off there and Windows keeps the stock writer.
+
+A predictable name is also something another account can get to first, so the partial itself is
+checked before a byte is appended: ``O_NOFOLLOW`` at open, and then owner, link count and file type
+on the descriptor rather than the path, since only the descriptor is the thing about to be written.
+See :func:`_objection_to`. Publishing re-checks that the name still holds what was written, because
+``_chmod_and_move`` resolves it again.
+
+The other corruption route, appending to a sparse XET or parallel-Range partial, belongs to the
+transport markers in :mod:`hub.utils.download_registry`. They are bypassed on >= 1.18 only because
+no resumer exists, so restoring one brings them back into force.
+"""
+
+from __future__ import annotations
+
+import errno
+import os
+import stat
+import tempfile
+from functools import lru_cache
+from pathlib import Path
+from typing import Any, Optional
+
+from loggers import get_logger
+
+logger = get_logger(__name__)
+
+# The last line whose partials the stock writer already appends to.
+LAST_STOCK_RESUMABLE_VERSION = (1, 17)
+# The newest major whose internals this has been read against. A 2.x is not assumed to look alike.
+MAX_SUPPORTED_MAJOR = 1
+
+# What flock reports when another holder has the lock, and nothing else. EACCES belongs to fcntl,
+# not flock; ENOLCK and EOPNOTSUPP mean this filesystem cannot lock at all.
+_CONTENDED = frozenset({errno.EWOULDBLOCK, errno.EAGAIN})
+
+# Filesystems backed by storage attached to this host, so a lock taken here is the only lock.
+# An allowlist rather than a list of network types: a FUSE mount reports whatever name its daemon
+# chose, and unless it negotiates FUSE_FLOCK_LOCKS the kernel answers flock locally (libfuse
+# fuse_lowlevel.h), so fuse.rclone or fuse.s3fs over shared object storage passes the probe while
+# excluding nobody. Naming the ones we know instead means an unrecognised or blank type keeps the
+# stock writer rather than silently re-enabling a shared one.
+_LOCAL_FSTYPES = frozenset(
+ {
+ # Linux
+ "bcachefs",
+ "btrfs",
+ "ext2",
+ "ext3",
+ "ext4",
+ "f2fs",
+ "jfs",
+ "nilfs2",
+ "reiser4",
+ "reiserfs",
+ "xfs",
+ "zfs",
+ # Block-backed FUSE (ntfs-3g and friends), container and memory-backed roots
+ "fuseblk",
+ "overlay",
+ "overlayfs",
+ "ramfs",
+ "tmpfs",
+ # Removable and cross-platform volumes
+ "exfat",
+ "fat",
+ "fat32",
+ "msdos",
+ "vfat",
+ # macOS
+ "apfs",
+ "hfs",
+ "hfsplus",
+ "ufs",
+ # Windows, where psutil reports the volume format
+ "ntfs",
+ "ntfs3",
+ "refs",
+ }
+)
+
+
+def _hub_version() -> tuple[int, ...]:
+ """``(major, minor)`` for the installed huggingface_hub, or ``()`` when it cannot be read."""
+ try:
+ from huggingface_hub import __version__ as raw
+ except Exception as exc: # noqa: BLE001 - an unimportable hub is not ours to diagnose
+ logger.debug("resumable partials: huggingface_hub unreadable (%s)", exc)
+ return ()
+ parts: list[int] = []
+ for chunk in str(raw).split(".")[:2]:
+ digits = ""
+ for char in chunk:
+ if not char.isdigit():
+ break
+ digits += char
+ if not digits:
+ return ()
+ parts.append(int(digits))
+ return tuple(parts)
+
+
+def _probe_dir(hub_cache: Optional[Path | str] = None) -> Optional[Path]:
+ """The cache whose filesystem decides, defaulting to the one the worker will use.
+
+ ``constants.HF_HUB_CACHE`` is resolved at import and moving the cache in Settings does not
+ rewrite the live process (see ``hub/services/download_lifecycle.py``), so probing it would
+ judge a different filesystem than the partial lands on. The constant is the fallback for
+ callers outside Studio.
+
+ *hub_cache* names a specific root instead. Studio remembers several, and a partial sitting in
+ one of them is governed by that root's filesystem, not by whichever is currently selected.
+ """
+ root = None
+ if hub_cache is not None:
+ root = Path(hub_cache)
+ else:
+ try:
+ from utils.hf_cache_settings import active_hf_hub_cache
+ root = Path(active_hf_hub_cache())
+ except Exception as exc: # noqa: BLE001 - outside Studio, use the library's own view
+ logger.debug("resumable partials: no Studio cache setting (%s)", exc)
+ if root is None:
+ try:
+ from huggingface_hub import constants
+ root = Path(constants.HF_HUB_CACHE)
+ except Exception as exc: # noqa: BLE001 - an unreadable cache is not a lock guarantee
+ logger.debug("resumable partials: no hub cache to probe (%s)", exc)
+ return None
+ if hub_cache is not None:
+ # Asked about a named root, so only report on one that is there. Creating it would
+ # resurrect a cache the user detached, and an absent root holds no partials to judge.
+ return root if root.is_dir() else None
+ try:
+ root.mkdir(parents = True, exist_ok = True)
+ return root
+ except Exception as exc: # noqa: BLE001 - an unwritable cache is not a lock guarantee
+ logger.debug("resumable partials: hub cache not writable (%s)", exc)
+ return None
+
+
+def _mounts() -> list[tuple[str, str]]:
+ """``(mountpoint, fstype)`` for every mount, via psutil so macOS and Windows answer too."""
+ import psutil
+ return [(part.mountpoint, part.fstype or "") for part in psutil.disk_partitions(all = True)]
+
+
+class _ProbeUnavailable(Exception):
+ """The probe could not be run. Not a measurement, so it must not be remembered as one."""
+
+
+def _device_at(directory: str) -> int:
+ """The device the path is mounted from, which changes when a different filesystem replaces it.
+
+ Part of the probe cache key: the path alone is not identity. An external cache can be unmounted
+ and something else mounted at the same name, and a verdict about the old filesystem says
+ nothing about the new one.
+ """
+ try:
+ return os.stat(directory).st_dev
+ except OSError as exc:
+ raise _ProbeUnavailable(f"cannot stat {directory}: {exc}") from exc
+
+
+def _filesystem_is_local(directory: str) -> bool:
+ """Whether *directory* sits on a filesystem whose locking this host can speak for."""
+ return _filesystem_is_local_on(directory, _device_at(directory))
+
+
+@lru_cache(maxsize = 8)
+def _filesystem_is_local_on(directory: str, device: int) -> bool:
+ """The cached half, keyed on the mounted device as well as the path.
+
+ A probe here cannot see another client, and NFS mounted ``-o local_lock=flock`` keeps flock
+ locks client-local, so two hosts would each take the lock and neither would be refused. A mount
+ we cannot identify counts as not local: this decides whether to re-enable a shared writer.
+ """
+ path = Path(directory).resolve()
+ if str(path).startswith("\\\\") or str(path).startswith("//"):
+ return False # UNC share
+ try:
+ table = _mounts()
+ except Exception as exc: # noqa: BLE001 - unreadable now does not mean unreadable next time
+ raise _ProbeUnavailable(f"could not read the mount table: {exc}") from exc
+ best, fstype = "", None
+ for mount, kind in table:
+ if str(path) == mount or str(path).startswith(mount.rstrip(os.sep) + os.sep):
+ if len(mount) >= len(best):
+ best, fstype = mount, kind.lower()
+ if fstype is None:
+ logger.debug("resumable partials: no mount found for %s", path)
+ return False
+ if fstype not in _LOCAL_FSTYPES:
+ logger.info(
+ "Download partials stay unresumable: %s is on %s, which is not a filesystem this host "
+ "can prove it locks alone.",
+ path,
+ fstype or "an unnamed type",
+ )
+ return False
+ return True
+
+
+def _lock_is_honoured_at(directory: str) -> bool:
+ """Whether ``flock`` under *directory* actually excludes a second holder."""
+ return _lock_is_honoured_on(directory, _device_at(directory))
+
+
+# Keyed on the directory and the device, so moving the cache, or swapping the mount under it,
+# re-probes instead of reusing a verdict about a filesystem that is no longer there.
+@lru_cache(maxsize = 8)
+def _lock_is_honoured_on(directory: str, device: int) -> bool:
+ """Take the lock twice and require the second to be refused.
+
+ Separate ``open()`` calls make separate open file descriptions and flock judges them
+ independently. Only contention counts as a refusal; a filesystem that grants both, or answers
+ anything else, leaves the stock writer in place. A probe that could not be run at all raises
+ instead, since a full disk or a briefly unwritable cache is not a measurement to remember.
+ """
+ import fcntl
+
+ # A random, exclusively created file: the cache can be shared, and a predictable name there
+ # lets another user pre-place a symlink that an unguarded open would follow and truncate.
+ try:
+ handle, name = tempfile.mkstemp(dir = directory, prefix = ".unsloth-flock-probe.")
+ except Exception as exc: # noqa: BLE001 - nowhere to probe now is not nowhere to probe later
+ raise _ProbeUnavailable(f"could not create the probe in {directory}: {exc}") from exc
+ second = None
+ try:
+ fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ second = os.open(name, os.O_RDWR | getattr(os, "O_NOFOLLOW", 0))
+ try:
+ fcntl.flock(second, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except OSError as exc:
+ if exc.errno in _CONTENDED:
+ return True
+ # ENOLCK / EOPNOTSUPP / EINTR: not a refusal, so nothing has been shown.
+ logger.info(
+ "Download partials stay unresumable: locking %s answered %s rather than "
+ "contention.",
+ directory,
+ errno.errorcode.get(exc.errno, exc.errno),
+ )
+ return False
+ logger.info(
+ "Download partials stay unresumable: %s grants the same lock twice, so a shared "
+ "partial could be written by two processes at once.",
+ directory,
+ )
+ return False
+ except Exception as exc: # noqa: BLE001 - same, an unprovable lock is not a working one
+ logger.debug("resumable partials: lock probe failed (%s)", exc)
+ return False
+ finally:
+ for fd in (second, handle):
+ if fd is not None:
+ try:
+ os.close(fd)
+ except OSError:
+ pass
+ try:
+ os.unlink(name)
+ except OSError:
+ pass
+
+
+def _exclusion_is_provable(hub_cache: Optional[Path | str] = None) -> bool:
+ """Whether a shared partial under *hub_cache* (default: the cache in force) has one writer."""
+ directory = _probe_dir(hub_cache)
+ if directory is None:
+ return False
+ try:
+ import fcntl # noqa: F401
+ except ImportError:
+ # No fcntl on Windows, where huggingface_hub locks via msvcrt: mandatory rather than
+ # advisory. A network share still cannot be spoken for, which the locality check catches.
+ # Windows has no way to establish who owns a partial: os.stat reports st_uid 0 for every
+ # file, and reading an ACL needs pywin32, which is not a dependency here. Without an owner
+ # check, another account on a shared NTFS cache could leave a partial with a chosen prefix
+ # and have the remaining range appended to it, which the size-only check downstream would
+ # pass. So the shared name stays off here and Windows keeps the stock writer.
+ return False
+ # _ProbeUnavailable is deliberately not caught: a probe that could not run is not an answer,
+ # and letting it out keeps any caller from caching one. Callers turn it into "not proven".
+ return _filesystem_is_local(str(directory)) and _lock_is_honoured_at(str(directory))
+
+
+def _hub_is_patchable() -> bool:
+ """Whether the installed hub exposes the pieces the restored caller needs."""
+ try:
+ from huggingface_hub import file_download
+ except Exception: # noqa: BLE001
+ return False
+ needed = ("_download_to_tmp_and_move", "http_get", "_chmod_and_move", "_check_disk_space")
+ return all(hasattr(file_download, name) for name in needed)
+
+
+def can_restore_partials(hub_cache: Optional[Path | str] = None) -> bool:
+ """Whether the shared-name writer is safe for partials under *hub_cache*.
+
+ Read by the server to decide what to tell the UI and by the worker before it patches, so both
+ answer the same. Default is the cache in force, which is the one a download will write; pass a
+ root to ask about partials already sitting in a different remembered cache, whose filesystem
+ may lock differently from the selected one.
+ """
+ version = _hub_version()
+ if not version or version <= LAST_STOCK_RESUMABLE_VERSION or version[0] > MAX_SUPPORTED_MAJOR:
+ return False
+ return _hub_is_patchable() and _exclusion_is_provable(hub_cache)
+
+
+def _objection_to(descriptor: int) -> Optional[str]:
+ """Why the partial now open on *descriptor* must not be appended to, or ``None``.
+
+ Judged on the descriptor rather than the path, so a swap between looking and opening cannot
+ slip a different file past: this is the thing that will actually be written.
+
+ Ownership is the load-bearing one. Nothing about a plain file betrays who wrote it, so a
+ partial another account left is bytes of their choosing, and appending the server's remaining
+ range to a chosen prefix publishes a blob that is the right length and the wrong file.
+ huggingface_hub checks only the size afterwards, never the hash (huggingface_hub#3643), so
+ nothing downstream would notice.
+ """
+ info = os.fstat(descriptor)
+ if not stat.S_ISREG(info.st_mode):
+ return "not a regular file"
+ if info.st_nlink > 1:
+ return "hard linked from elsewhere"
+ euid = getattr(os, "geteuid", None)
+ if euid is None:
+ # No owner to compare against, so nothing here can be vouched for. Reachable only if the
+ # writer is ever enabled without geteuid; _exclusion_is_provable refuses that today.
+ return "on a platform where ownership cannot be established"
+ if info.st_uid != euid():
+ return "owned by another user"
+ return None
+
+
+def _still_the_written_file(path: Path, written: os.stat_result) -> bool:
+ """Whether *path* still names the file described by *written*.
+
+ ``(st_dev, st_ino)`` identifies a file; the pathname does not. Checked before publishing
+ because the move re-resolves the name, and a shared cache directory lets another account
+ unlink or rename the partial after the last byte is written and leave something else there.
+
+ This narrows the window rather than closing it: nothing between this stat and the move is
+ atomic, and closing it properly needs a by-descriptor rename that Python does not expose
+ portably. Turning "an unrelated file is published as the model" into "the download is retried"
+ is the improvement available here.
+ """
+ try:
+ current = os.lstat(path)
+ except OSError as exc:
+ logger.warning("resumable partials: the partial at %s vanished (%s)", path, exc)
+ return False
+ return (current.st_dev, current.st_ino) == (written.st_dev, written.st_ino)
+
+
+def _open_stable_partial(path: Path) -> Optional[Any]:
+ """Open the stable partial for append, or ``None`` if it cannot be trusted.
+
+ The 1.18 nonce made this name unguessable; restoring the 1.17 name makes it predictable again,
+ so on a cache another account can write, the entry can be pre-created and an unguarded ``"ab"``
+ would build the blob on top of whatever is there. ``O_NOFOLLOW`` refuses a symlink outright;
+ everything else is settled on the open descriptor by :func:`_objection_to`. The one look at the
+ path is for Windows, which has no ``O_NOFOLLOW`` and so cannot refuse a link at open time.
+
+ A partial that fails any of it is removed and a clean one started. One that cannot be opened
+ at all is left untouched instead: ``EACCES`` from another account's ``0600`` file is not a
+ position from which to judge or delete it. Either way the caller falls back to the stock
+ writer, which invents its own name and cannot be steered.
+ """
+ nofollow = getattr(os, "O_NOFOLLOW", 0)
+ flags = os.O_WRONLY | os.O_CREAT | os.O_APPEND | nofollow | getattr(os, "O_BINARY", 0)
+ for last_attempt in (False, True):
+ objection = None
+ if not nofollow:
+ try:
+ if stat.S_ISLNK(os.lstat(path).st_mode):
+ objection = "a symlink"
+ except FileNotFoundError:
+ pass
+ except OSError as exc:
+ logger.debug("resumable partials: cannot stat %s (%s)", path, exc)
+ return None
+ if objection is None:
+ try:
+ descriptor = os.open(path, flags, 0o600)
+ except OSError as exc:
+ # ELOOP, or EMLINK on some BSDs: O_NOFOLLOW refused a symlink.
+ if exc.errno in (errno.ELOOP, errno.EMLINK):
+ objection = "a symlink"
+ else:
+ # Anything else is a partial this account cannot use and must not judge: a
+ # 0600 one left by another user answers EACCES, a directory in its place
+ # EISDIR. Raising would fail every attempt at the blob for good, while the
+ # stock writer creates a file of its own and does not need this one at all.
+ logger.warning(
+ "Cannot open the download partial at %s (%s); leaving it alone and "
+ "letting the stock writer fetch the file.",
+ path,
+ exc,
+ )
+ return None
+ else:
+ objection = _objection_to(descriptor)
+ if objection is None:
+ return os.fdopen(descriptor, "ab")
+ os.close(descriptor)
+ if last_attempt:
+ return None
+ logger.warning("Discarding the download partial at %s: it is %s.", path, objection)
+ try:
+ os.unlink(path)
+ except OSError as exc:
+ logger.warning("Could not remove it (%s); leaving the resume to the stock writer.", exc)
+ return None
+ return None
+
+
+def restore_resumable_partials() -> bool:
+ """Patch huggingface_hub in THIS process. Idempotent, and a no-op where it is unsafe."""
+ try:
+ permitted = can_restore_partials()
+ except _ProbeUnavailable as exc:
+ # The worker calls this at import, so an escaping exception would take the whole download
+ # process down instead of leaving it with the stock writer it can always fall back on.
+ logger.debug("resumable partials: %s", exc)
+ return False
+ if not permitted:
+ return False
+
+ from huggingface_hub import file_download
+
+ stock = file_download._download_to_tmp_and_move
+ if getattr(stock, "_unsloth_resumable", False):
+ return True
+
+ def _download_to_tmp_and_move(
+ incomplete_path: Path,
+ destination_path: Path,
+ url_to_download: str,
+ headers: dict,
+ expected_size: Optional[int],
+ filename: str,
+ force_download: bool = False,
+ xet_file_data: Any = None,
+ **kwargs: Any,
+ ) -> None:
+ if destination_path.exists() and not force_download:
+ return
+
+ # A XET-backed repo still comes down over HTTP when hf_xet is absent or disabled, so what
+ # matters is whether XET will run, not whether its metadata exists. XET writes its own way.
+ uses_xet = xet_file_data is not None and file_download.is_xet_available()
+ if force_download or uses_xet:
+ return stock(
+ incomplete_path = incomplete_path,
+ destination_path = destination_path,
+ url_to_download = url_to_download,
+ headers = headers,
+ expected_size = expected_size,
+ filename = filename,
+ force_download = force_download,
+ xet_file_data = xet_file_data,
+ **kwargs,
+ )
+
+ # The 1.17 caller: a stable name, opened for append, told how far it already got.
+ opened = _open_stable_partial(incomplete_path)
+ if opened is None:
+ return stock(
+ incomplete_path = incomplete_path,
+ destination_path = destination_path,
+ url_to_download = url_to_download,
+ headers = headers,
+ expected_size = expected_size,
+ filename = filename,
+ force_download = force_download,
+ xet_file_data = xet_file_data,
+ **kwargs,
+ )
+ written = os.fstat(opened.fileno())
+ with opened as handle:
+ resume_size = handle.tell()
+ if expected_size is not None and resume_size > expected_size:
+ # Longer than the file is supposed to be, so there is nothing to resume from: a
+ # Range starting past the end answers 416 and would do so on every retry, where
+ # the stock writer's fresh name recovers. Truncating through the handle we already
+ # validated, rather than unlinking, keeps the name from being swapped underneath.
+ logger.warning(
+ "Restarting '%s': the partial holds %s bytes but the file is %s.",
+ filename,
+ resume_size,
+ expected_size,
+ )
+ handle.seek(0)
+ handle.truncate()
+ resume_size = 0
+ if expected_size is not None:
+ file_download._check_disk_space(expected_size, incomplete_path.parent)
+ file_download._check_disk_space(expected_size, destination_path.parent)
+ if resume_size:
+ logger.info(
+ "Resuming '%s' from %s of %s bytes",
+ filename,
+ resume_size,
+ expected_size,
+ )
+ file_download.http_get(
+ url_to_download,
+ handle,
+ resume_size = resume_size,
+ headers = headers,
+ expected_size = expected_size,
+ tqdm_class = kwargs.get("tqdm_class"),
+ )
+ # _chmod_and_move resolves the name again, so publish only if the name still holds the
+ # file that was actually written. Otherwise another account could swap something in
+ # after the last write and have it installed as the blob under a verified descriptor.
+ if not _still_the_written_file(incomplete_path, written):
+ logger.warning(
+ "Not publishing '%s': the partial at %s was replaced while it was being written.",
+ filename,
+ incomplete_path,
+ )
+ return
+ # Only on success: a failure has to leave the partial where the next attempt looks for it.
+ file_download._chmod_and_move(incomplete_path, destination_path)
+
+ _download_to_tmp_and_move._unsloth_resumable = True
+ _download_to_tmp_and_move._unsloth_stock = stock
+ file_download._download_to_tmp_and_move = _download_to_tmp_and_move
+ logger.info("Restored resumable HTTP partials for huggingface_hub %s", _hub_version())
+ return True
+
+
+def invalidate_probe_cache() -> None:
+ """Forget every probed filesystem. Called when the cache location changes."""
+ # getattr: a test that replaced either probe outright has no cache to clear.
+ for probe in (_lock_is_honoured_on, _filesystem_is_local_on):
+ clear = getattr(probe, "cache_clear", None)
+ if clear is not None:
+ clear()
+
+
+def reset_probe_cache_for_tests() -> None:
+ invalidate_probe_cache()
diff --git a/studio/backend/hub/workers/hf_download.py b/studio/backend/hub/workers/hf_download.py
index 7557d8085fd..b66c1e2249f 100644
--- a/studio/backend/hub/workers/hf_download.py
+++ b/studio/backend/hub/workers/hf_download.py
@@ -17,6 +17,9 @@ Enforced by:
globally and simplifying reasoning about partial state during a SIGKILL.
- Letting ``prepare_cache_for_transport`` purge any pre-existing
``.incomplete`` blobs not provably from the same sequential writer.
+- Restoring huggingface_hub's 1.17 append-mode writer where that is safe
+ (see :mod:`hub.utils.resumable_partials`); 1.18+ writes a process-unique
+ partial and unlinks it, which leaves this loop nothing to resume from.
If the final byte count doesn't match what HF declared, huggingface_hub
raises ``EnvironmentError`` ("Consistency check failed: …"); we surface
@@ -55,6 +58,11 @@ from hub.utils.gguf_plan import (
sibling_sha256,
)
from hub.utils.state_dir import RepoType
+from hub.utils.resumable_partials import restore_resumable_partials
+
+# Put huggingface_hub's 1.17 HTTP writer back where it is safe to. The SIGKILL then restart loop
+# documented above reads ``.incomplete`` for its resume offset, and 1.18+ leaves nothing to read.
+_PARTIALS_RESUMABLE = restore_resumable_partials()
# typing.Union, not `str | bool | None`: an alias is evaluated on import and PEP 604 raises below 3.10.
HfTokenArg = Union[str, bool, None]
diff --git a/studio/backend/tests/test_hub_download_transport_auto.py b/studio/backend/tests/test_hub_download_transport_auto.py
index 841fa23636d..f48a12fe373 100644
--- a/studio/backend/tests/test_hub_download_transport_auto.py
+++ b/studio/backend/tests/test_hub_download_transport_auto.py
@@ -89,9 +89,9 @@ def test_auto_reports_http_when_hf_xet_is_missing(monkeypatch):
def test_capabilities_carry_the_partial_resume_verdict(monkeypatch):
"""The card labels a partial from this. huggingface_hub >= 1.18 refetches an interrupted file
from zero, so a byte-resume must not be offered there."""
- monkeypatch.setattr(download_registry, "hf_partials_are_resumable", lambda: False)
+ monkeypatch.setattr(download_registry, "hf_partials_are_resumable", lambda _root = None: False)
assert download_registry.get_download_transport_capabilities().partials_resumable is False
- monkeypatch.setattr(download_registry, "hf_partials_are_resumable", lambda: True)
+ monkeypatch.setattr(download_registry, "hf_partials_are_resumable", lambda _root = None: True)
assert download_registry.get_download_transport_capabilities().partials_resumable is True
diff --git a/studio/backend/tests/test_partial_resume_verdict.py b/studio/backend/tests/test_partial_resume_verdict.py
index 18b5476e5c4..dc687d1251a 100644
--- a/studio/backend/tests/test_partial_resume_verdict.py
+++ b/studio/backend/tests/test_partial_resume_verdict.py
@@ -43,7 +43,7 @@ def cache(monkeypatch, tmp_path):
for module in (download_registry, hf_cache_state):
monkeypatch.setattr(module, "hf_cache_root", lambda **_kw: root, raising = False)
monkeypatch.setattr(hf_cache_state, "hf_cache_roots", lambda *_a, **_k: [root])
- monkeypatch.setattr(hf_cache_state, "hf_partials_are_resumable", lambda: True)
+ monkeypatch.setattr(hf_cache_state, "hf_partials_are_resumable", lambda _root = None: True)
return entry
@@ -92,7 +92,7 @@ def test_a_row_with_no_partial_left_has_nothing_to_resume(cache):
def test_a_writer_that_cannot_reopen_anything_never_promises_a_resume(cache, monkeypatch):
"""The ordinary install: hub >= 1.18 refetches from zero, so even a legacy-named
survivor is litter."""
- monkeypatch.setattr(hf_cache_state, "hf_partials_are_resumable", lambda: False)
+ monkeypatch.setattr(hf_cache_state, "hf_partials_are_resumable", lambda _root = None: False)
_record("http", cache)
_partial(cache, LEGACY_PARTIAL)
assert partial_resume_available("model", "Org/Model", "Q4_K_M") is False
@@ -197,7 +197,7 @@ def split_cache(monkeypatch, tmp_path):
monkeypatch.setattr(
download_registry, "iter_active_repo_cache_dirs", lambda *_a, **_k: iter((first, second))
)
- monkeypatch.setattr(hf_cache_state, "hf_partials_are_resumable", lambda: True)
+ monkeypatch.setattr(hf_cache_state, "hf_partials_are_resumable", lambda _root = None: True)
return first, second
@@ -249,7 +249,7 @@ def two_roots(monkeypatch, tmp_path):
(root / "models--Org--Model" / "blobs").mkdir(parents = True)
monkeypatch.setenv("HF_HUB_CACHE", str(active))
monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
- monkeypatch.setattr(hf_cache_state, "hf_partials_are_resumable", lambda: True)
+ monkeypatch.setattr(hf_cache_state, "hf_partials_are_resumable", lambda _root = None: True)
for module in (download_registry, hf_cache_state):
monkeypatch.setattr(
module,
diff --git a/studio/backend/utils/hf_cache_settings.py b/studio/backend/utils/hf_cache_settings.py
index 73801101ec0..6c2d3d9f134 100644
--- a/studio/backend/utils/hf_cache_settings.py
+++ b/studio/backend/utils/hf_cache_settings.py
@@ -342,6 +342,11 @@ def set_hf_cache_home(cache_home: Optional[str]) -> HuggingFaceCachePaths:
from hub.utils.inventory_scan import invalidate_hf_cache_scans
invalidate_hf_cache_scans()
+ # Partial resumability is a property of the filesystem the cache sits on, so it is re-decided
+ # for the new root rather than carried over from the old one.
+ from hub.utils.hf_cache_state import invalidate_partial_resumability
+
+ invalidate_partial_resumability()
return get_hf_cache_paths()