Repository navigation
Give huggingface_hub 1.18+ back its resumable HTTP partials - #9602
Conversation
Cancel a download, or lose the process, and Studio refetches the whole file. On an 800MB GGUF that is the entire 800MB again. huggingface_hub 1.18 replaced the shared <etag>.incomplete, opened in append mode and continued with a Range request, with a process-unique <etag>.<nonce>.incomplete opened "wb" and unlinked in a finally (huggingface/huggingface_hub#4228). The nonce is fresh per download, so a partial can never be matched again, and upstream says as much in the code: "it could not be reused anyway since the temporary name is unique to this download". Studio pins huggingface_hub>=1.23 on Python 3.10+, so this is what every current install does. hub/workers/hf_download.py is built around the opposite. Its docstring says downloads must be single-stream sequential writers "so the parent's SIGKILL then restart loop can rely on os.path.getsize(.incomplete) to compute the correct resume offset". There has been nothing to compute it from. Only the caller was removed upstream. http_get still takes resume_size, still sends the Range header, and still does seek(0) plus truncate() when a server answers 200 to a Range request, which is the case that would otherwise duplicate bytes. So hub/utils/resumable_partials.py puts the 1.17 caller back: stable name, opened for append, told how far it got, left alone on failure. Upstream removed it for one hazard: on filesystems where flock silently succeeds for every caller (Lustre, GPFS, some NFS mounts) two processes append to one file and corrupt the cache. That is measured rather than assumed. The probe takes the lock twice and requires the second to be refused, and where that cannot be shown the stock writer stays and partials keep reporting as unresumable. Windows answers yes without probing, since huggingface_hub locks via msvcrt there and that is mandatory rather than advisory. The other corruption route, an HTTP resumer appending to a sparse XET or parallel-Range partial, is already handled by the transport markers in download_registry. Those are bypassed on 1.18+ precisely because no resumer exists, so restoring one brings them back into force. Partials already on disk under a nonce name stay unresumable and still purge: the restored writer opens the stable name and never finds them. hf_partials_are_resumable() now reports the restored writer, so the download cards offer Pause again instead of Cancel. Verified against real interrupted downloads of an 800MB GGUF on 1.28.0. Stock leaves a 346MB orphan and refetches from zero under a new nonce. Patched, one 262MB partial grows to 367MB and finishes, and after two interruptions the completed file's sha256 matches the blob name Hugging Face derives from its contents.
Two fixes. The probe read huggingface_hub.constants.HF_HUB_CACHE, which is resolved at import. Moving the cache in Settings does not rewrite the live process, as download_lifecycle.py already notes, while a spawned worker gets the new one. So the backend could cache a resumability verdict for the filesystem it booted on while the worker probed the one the partial actually lands on, and the two can disagree about flock. It now resolves active_hf_hub_cache(), keys the probe per directory, and set_hf_cache_home drops both cached answers next to the inventory-scan invalidation it already does. The lock probe also opened its file in text mode without an encoding, which tests/test_runtime_text_encoding.py and the Repo tests CPU guard both reject. It is a lock, never text, so it opens binary now. The test tree's read_text of the worker source names utf-8. Tests: the probe follows the live cache and creates it, moving the cache re-probes instead of reusing the old verdict, the per-directory cache still hits on a repeat so the per-blob hot path is unchanged, and changing the cache home invalidates. 647 backend tests pass, ruff clean.
Opening comment-reduction pass, scoped to the file this PR adds. hf_cache_settings.py is pre-existing and only gains two lines here, so rewriting its comments would churn code this PR has no business touching. Comments and docstrings only, AST-verified against 5a49a95.
Three holes in the lock probe:
- The probe file used a predictable pid-based name and was opened with
open("wb"), which follows symlinks, so anything that could write the cache
directory could point it at a victim file and have us truncate it. Now
tempfile.mkstemp picks the name and the second handle opens with O_NOFOLLOW.
- A bare except OSError read every error as contention, so ENOLCK and
EOPNOTSUPP (the filesystem does not lock at all) answered "honoured". Only
EWOULDBLOCK and EAGAIN mean a lock was held.
- A probe run in one process cannot say anything about a second host. On a
network mount with -o local_lock=flock the lock is client-local, so the
probe passes and cross-host exclusion still does not exist. The probe is now
gated on the directory sitting on a local filesystem.
End to end check on a real 50 GB fileRan the actual case this is for: Before, stock writer:
One new nonce partial per attempt, none of them growing. 1.66 GB of the 2.50 GB on disk is orphaned, and every attempt starts the 50 GB file from zero. After, with the patched writer:
One partial throughout, growing across attempts, so each restart picks up where the last one stopped. A fourth attempt then ran to completion and the finished blob was hashed: The hash matches the blob name, so a file assembled from four separate Range-resumed segments is byte for byte the same as one downloaded in a single pass. For completeness I measured the Xet path the same way and it is not a workaround: a cancelled Xet download rewrites the destination from scratch, and its chunk cache retained 0.1 MB of an 807 MB file after a kill. Xet is equally non-resumable at the file level, which is why this fix is scoped to HTTP and hands anything Xet-backed straight to the stock writer. |
Two ways the locality gate was still too generous. The mount check was a list of network filesystem types, so anything not on it read as local. A FUSE daemon reports whatever name it likes, and unless it negotiates FUSE_FLOCK_LOCKS the kernel answers flock locally (libfuse fuse_lowlevel.h), so a cache on fuse.rclone or fuse.s3fs over shared object storage passed the same-host probe while excluding no other client. A blank fstype did the same. It is now an allowlist of filesystems backed by storage attached to this host, and anything unrecognised keeps the stock writer. The verdict was also global while the answer had become a property of the filesystem. Studio remembers several cache roots, the boot sweep walks all of them, and partial_is_resumable() took only a filename, so a selected cache on a network mount condemned a local cache's still-appendable partials to deletion after the grace period, and the reverse advertised unsafe ones as resumable. The root is now threaded from the sweep and the disk accounting down into the probe, and asking about a detached root reports it gone rather than recreating it.
Restoring the 1.17 stable name makes <etag>.incomplete predictable again,
which the 1.18 nonce had incidentally fixed. On a cache another account can
write, the entry can be pre-created as a symlink or a hard link to any file
the Studio account may write, and open("ab") would append the model to it,
after which _chmod_and_move would chmod that file too.
The partial is now opened through a guard: an lstat rejects a hard link or
anything that is not a regular file, which O_NOFOLLOW cannot see and which
also covers Windows, and O_NOFOLLOW on the open closes the window between
the two syscalls. A planted entry is discarded and a clean partial started;
where even that is refused, the stock writer takes over, since it invents
its own name and cannot be steered.
Two more ways the restored writer trusted too much. A planted partial does not need to be a link. Another account can leave a plain <etag>.incomplete holding bytes of its choosing; the writer took its length as resume_size, appended the server's remaining range and published a blob of exactly the right size and entirely the wrong contents. huggingface_hub verifies the size after a download and never the hash (huggingface/huggingface_hub#3643), so nothing downstream would catch it. The checks now run against the open descriptor rather than the path, so a swap between looking and opening cannot slip a different file past, and they include the owner. O_NOFOLLOW still refuses a symlink at open; the one remaining look at the path is for Windows, which has no O_NOFOLLOW. The probe caches were keyed on the directory string alone, so a cache that was unmounted and replaced at the same name kept the old verdict, and a probe that could not run at all (full disk, briefly unwritable cache) was remembered as a measurement for the life of the process. They are now keyed on the mounted device as well, and an unrunnable probe raises rather than returning False, which lru_cache does not store, so the next caller probes again instead of inheriting a bad moment.
os.open on the shared name can fail for reasons that say nothing about a symlink: a 0600 partial left by another account answers EACCES, a directory in its place EISDIR. Re-raising those failed every HTTP attempt at the blob for good, even though the stock writer would have finished the download happily, since it creates a process-unique file and never touches this one. Anything other than the O_NOFOLLOW refusal now hands the download to stock and leaves the partial alone. Not judged, not deleted: an account that cannot read it is in no position to say what it is.
Four things, all reachable only on a cache another account can write, which is the case this whole module exists to be careful about. Publishing trusted the pathname. _chmod_and_move resolves it again, so the partial could be unlinked and replaced after the last byte was written and the replacement installed as the blob, under a descriptor that had passed every check. The identity of what was written is now captured from the descriptor and compared before the move. This narrows the window rather than closing it: a by-descriptor rename is not portable from Python, so turning "an unrelated file becomes the model" into "the download retries" is the improvement available. Ownership went unchecked wherever geteuid does not exist, which is Windows, while the writer was still enabled there on local NTFS. There is no way to establish an owner on Windows from the standard library (st_uid is always 0, ACLs need pywin32, not a dependency here), so the shared-name writer is now off on Windows and it keeps the stock one. An absent geteuid is also an objection in its own right rather than a skipped check. hf_partials_are_resumable kept an lru_cache keyed on the path, which undid the device-aware caching underneath it: a transient probe failure was remembered for the life of the process, and a remount at the same name kept the old verdict. That layer no longer caches at all. The expensive part is still cached against the device further down, and a probe that could not run now travels up as _ProbeUnavailable so no layer stores it. The foreign-owner test identified the planted file by inode, which a filesystem is free to hand to the replacement; it now keys on which open it is.
|
@codex review |
1 similar comment
|
@codex review |
The module docstring described only the exclusion proof, which is now about half of what the module is for, and said nothing about Windows being excluded or about the partial itself being validated before it is appended to. _open_stable_partial's docstring also predated the unopenable case, which defers without removing. Docstrings only; AST-verified as no code change.
Removing the cache from hf_partials_are_resumable left the import behind, which the repo's import-hoist lint fails on as a used-before-now-unused transition. Caught by staging CI rather than by ruff, whose default config here does not enable F401.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 83ac7d5b97
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
|
|
||
| def restore_resumable_partials() -> bool: | ||
| """Patch huggingface_hub in THIS process. Idempotent, and a no-op where it is unsafe.""" | ||
| if not can_restore_partials(): |
There was a problem hiding this comment.
Fall back when the lock probe is unavailable
When the mount table, cache stat, or temporary lock-file creation is transiently unavailable, can_restore_partials() deliberately raises _ProbeUnavailable, but this call does not catch it. Because hf_download.py invokes restore_resumable_partials() during module import, the exception terminates every download worker before it can use Hugging Face's safe stock writer; treat this verdict as unproven and return False, as hf_partials_are_resumable() already does.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed, and this is the second time I have made _ProbeUnavailable propagate without checking every caller. Last round I fixed the hf_cache_state entry point and left this one, and this is the worse of the two: hf_download.py does _PARTIALS_RESUMABLE = restore_resumable_partials() at module import, so a transient mount-table or write-probe failure would raise there and take the download worker down entirely, when the stock writer is the one thing always available to fall back on.
It now catches _ProbeUnavailable and returns False, same as hf_partials_are_resumable(). Mutation-checked: letting it escape again fails the new test. Fixed in c34aa9f.
| written = os.fstat(opened.fileno()) | ||
| with opened as handle: | ||
| resume_size = handle.tell() | ||
| if expected_size is not None: |
There was a problem hiding this comment.
Reset partials that exceed the declared size
If a prior attempt failed its consistency check after writing more than expected_size bytes, this path preserves that oversized partial and subsequently uses its length as resume_size. A server honoring Range requests then rejects the beyond-EOF range, so every ordinary retry fails on the same partial instead of recovering as the stock unique-file writer would; discard or truncate an existing partial when its size exceeds the declared size before calling http_get.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed, and the boundary you chose is the right one, which I checked in upstream's source rather than reasoning about it. http_get opens with:
if expected_size is not None and resume_size == expected_size:
# If the file is already fully downloaded, we don't need to download it again.
return
So an exactly-complete partial is fine and publishes as it stands; making the guard >= would refetch the whole file for nothing. Only strictly greater is the wedged case, where the Range starts past the end, 416 comes back, and every retry repeats it because the partial never changes. Stock recovers there purely because its name is fresh each time.
An oversized partial is now truncated rather than unlinked, deliberately: the truncate goes through the descriptor that already passed the owner and link checks, so the name cannot be swapped between judging it and clearing it.
Three mutations, all caught: keeping the oversized partial, letting the guard escape, and widening it to >= (which fails the complete-partial test). Fixed in c34aa9f.
Making _ProbeUnavailable propagate last round fixed the caching, and left restore_resumable_partials() exposed. The worker patches at import, so a transient mount-table or write-probe failure would raise there and take the whole download process down, when the one thing always available is the stock writer. It now answers False like the other entry point. Separately, a partial longer than the file it belongs to cannot be resumed from: a Range starting past the end answers 416, and would do so on every later attempt, wedging the download where the stock writer's fresh name recovers. Such a partial is now truncated through the descriptor already validated, rather than unlinked, so the name cannot be swapped underneath. The boundary is strictly greater: upstream http_get returns early when resume_size equals expected_size, so a complete partial publishes as it stands and restarting it would refetch the whole file for nothing.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Nice work! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Why
Cancel a download in Studio, or lose the process, and the next attempt refetches the whole file. On an 800MB GGUF that is the entire 800MB again.
huggingface_hub 1.18 replaced the shared
<etag>.incomplete, opened in append mode and continued with aRangerequest, with a process-unique<etag>.<nonce>.incompleteopened"wb"and unlinked in afinally(huggingface/huggingface_hub#4228, reported downstream as huggingface/huggingface_hub#4196). The nonce is fresh per download, so a partial can never be matched again. Upstream says so in the code:It was a deliberate trade for correctness on filesystems where
flock(2)silently succeeds for every caller (Lustre, GPFS, some NFS mounts), where two processes would otherwise append to one file and corrupt the cache.We are on the wrong side of that trade.
studio/backend/requirements/no-torch-runtime.txtpinshuggingface_hub>=1.23.0,<2.0on Python 3.10+, so this is what every current install does.And
hub/workers/hf_download.pyis built around the opposite. Its own docstring:There has been nothing to compute it from since 1.18.
What this does
Only the caller was removed upstream.
http_getstill takesresume_size, still sends the Range header, and still doesseek(0)plustruncate()when a server answers 200 to a Range request, which is the case that would otherwise duplicate bytes into an append-mode handle.So
hub/utils/resumable_partials.pyputs the 1.17 caller back: stable name, opened for append, told how far it got, and left alone on failure.hub/workers/hf_download.pyapplies it at import, in the worker process that actually downloads.The hazard upstream removed it for is measured, not assumed. The probe takes
flocktwice and requires the second to be refused, and onlyEWOULDBLOCK/EAGAINcounts as a refusal, since a filesystem with no locking answersENOLCKorEOPNOTSUPPand reading that as "refused" would enable the shared writer on exactly the mounts that cannot support it. Where exclusion cannot be shown, the stock writer stays and partials keep reporting as unresumable, so a cluster filesystem keeps upstream's safety.A probe here can only speak for this host, so locality gates it. The cache has to sit on a filesystem backed by storage attached to this machine, decided by an allowlist rather than a list of network types: a FUSE daemon reports whatever name it likes, and unless it negotiates
FUSE_FLOCK_LOCKSthe kernel answersflocklocally (libfusefuse_lowlevel.h), so a cache onfuse.rcloneorfuse.s3fsover shared object storage would pass a same-host probe while excluding nobody. NFS mounted-o local_lock=flockis the same story. Anything unrecognised, or with a blank fstype, keeps the stock writer.The verdict is per cache root, not global. Studio remembers several and they need not lock alike, so
partial_is_resumable()takes the root the partial lives under; otherwise a selected cache on a network mount would send a local cache's still-appendable partials to the abandoned-partial sweep. The probe result is cached against(directory, st_dev)so a mount replaced at the same pathname is re-probed, and a probe that could not run at all raises rather than answering, so no layer remembers a full disk or a briefly unreadable mount table as a measurement.Not enabled on Windows
Restoring the 1.17 stable name makes
<etag>.incompletepredictable again, which is fine only if a partial found there can be shown to be ours. On Windows it cannot:os.statreportsst_uid0 for every file and reading an ACL needs pywin32, which this repo does not depend on. Rather than run an ownership check that is a no-op on the one platform in question, the shared-name writer is disabled on Windows and Windows keeps the stock writer, exactly as today.That is a real loss for Windows users, who arguably need resume most. With pywin32 available,
GetFileSecurityplusGetSecurityDescriptorOwnerwould let it come back, and that is the obvious follow-up.Trusting the partial
On a cache another account can write, a predictable name is something to be careful with, so the partial is validated before anything is appended to it.
O_NOFOLLOWrefuses a symlink at open; the rest is settled on the open descriptor rather than the path, so a swap between looking and opening cannot slip a different file past. A hard link, a non-regular file, or an owner other than us is an objection, and an objectionable partial is discarded and a clean one started.Ownership is the load-bearing one. Nothing about a plain file betrays who wrote it, and huggingface_hub verifies the size of a download and never the hash (huggingface/huggingface_hub#3643 is a corrupted blob at exactly the expected size publishing with no error), so appending the remaining range to a chosen prefix would install a blob of the right length and the wrong contents with nothing downstream to catch it.
A partial that cannot be opened at all is left alone and the download handed to stock. A
0600file from another account answersEACCES, and an account that cannot read a file is in no position to say what it is or to delete it. Stock creates a file of its own and does not need this one, so the download still happens.Before publishing, the
(st_dev, st_ino)captured from the descriptor is compared against the pathname, because_chmod_and_moveresolves the name again and a replacement dropped in after the last write would otherwise be installed as the blob. This narrows that window rather than closing it: nothing between the check and the move is atomic, and a by-descriptor rename is not portable from Python. It turns "an unrelated file becomes the model" into "the download is retried".The other corruption route is already covered. An HTTP resumer appending to a sparse XET or parallel-Range partial is what the transport markers in
download_registryexist for. They are bypassed on 1.18+ because no resumer exists, so restoring one brings them back into force, which is where that check belongs. Partials already on disk under a nonce name stay unresumable and still purge: the restored writer opens the stable name and never finds them.It stands down for
force_download, and for XET, which has its own writer. Getting that second condition right mattered: an early version gated onxet_file_data is None, which silently disabled the whole thing, because a XET-backed repo still carries that metadata when it downloads over HTTP withhf_xetabsent or disabled. The test for it is in the suite.hf_partials_are_resumable()now reports the restored writer, so the download cards offer Pause again instead of Cancel.Verification
Real interrupted downloads of an 800MB GGUF against huggingface_hub 1.28.0, HTTP transport.
Stock, killed 8s in, then restarted:
With this change:
Resuming is only worth anything if the result is correct, so the same file was interrupted twice and then allowed to finish. Hugging Face names an LFS blob after the sha256 of its contents, so the cache carries its own expected digest:
The orphan accumulation goes away too: no more ~300MB of unreusable bytes per hard kill.
The same thing on the case it is actually for,
unsloth/Qwen3.8-27B-GGUFBF16/Qwen3.8-27B-BF16-00001-of-00002.gguf, a single 49.99GB file interrupted three times. Stock left one nonce partial per attempt, none of them growing, 1.66GB of the 2.50GB on disk orphaned. With this change one partial grew 0.50GB to 1.56GB to 2.22GB across the three, and a fourth attempt ran to completion:A 50GB file assembled from four separately Range-resumed segments is byte for byte what a single pass produces.
Xet is not an alternative here: a cancelled Xet download rewrites the destination from scratch, and its chunk cache held 0.1MB of an 807MB file after a kill. That is why this is scoped to HTTP and hands anything Xet-backed straight to the stock writer.
Tests
New
studio/backend/hub/tests/test_resumable_partials.py: which versions it engages for and which it refuses (including 2.x, which it has not been read against), a filesystem that grants the lock twice keeping the stock writer, a hub missing the pieces being left alone, the realflockprobe including that it cleans up after itself, append mode with the rightresume_size, a failed download leaving the partial where the next attempt looks, XET keeping its own writer, a XET-backed repo over HTTP still resuming,force_downloaddeferring to stock, an already-downloaded blob not being fetched again, double-patching keeping one layer, the capability the UI reads, and a structural check that the worker still calls it.test_unresumable_partial_purge.pyis updated: it pinned 1.18+ as unresumable, and now pins that as the behaviour with restoration unavailable, plus the restored case, plus a nonce partial staying unresumable either way.Also covered: the locality allowlist in both directions, a network mount standing down even where the lock probe would pass, an unrecognised or blank fstype not reading as local, each cache root judged on its own filesystem, a remount at the same path being re-probed, a probe that could not run not being remembered, a planted symlink and a planted hard link not being appended to, a partial left by another account not being built on, an unopenable partial deferring to stock instead of failing the download, a partial swapped after the last write not being published, and Windows keeping the stock writer.
hub/tests/and the download transport and scoped-download suites pass: 670 tests.ruff checkclean on the changed files.Every guard above was mutation-tested: the guard was removed or inverted one at a time, and each time exactly the test that names it failed. Two of them did not fail on the first attempt and the tests were rewritten rather than the finding waved through, once because an
lstatpre-check was catching the case ahead ofO_NOFOLLOWand once because a Windows assertion held on posix whichever way the code went.Follow-up
Worth proposing an opt-in upstream (
HF_HUB_RESUMABLE_PARTIALS=1or similar) with theflockprobe as the argument, so this does not have to live downstream. Upstream traded resume for safety on one class of filesystem; an opt-in gives both._download_to_tmp_and_moveis private, so the structural test above is what catches upstream drift.This also settles a copy question on #9272, which tells users HTTPS "resumes from the bytes already on disk". That is currently false on the pinned huggingface_hub. With this merged it is true again.