Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: resume paused and interrupted model downloads on Windows (#16828)
Nilay628b0c9b7b18
diff --git a/studio/backend/hub/tests/test_resumable_partials.py b/studio/backend/hub/tests/test_resumable_partials.pyindex f3275d75e19..ec14d37beaa 100644--- a/studio/backend/hub/tests/test_resumable_partials.py+++ b/studio/backend/hub/tests/test_resumable_partials.py@@ -406,6 +406,30 @@ def test_a_planted_symlink_is_not_appended_to(monkeypatch, tmp_path):assert calls["http_get"] == [{"resume_size": 0, "mode": "ab"}]+def test_a_link_swapped_in_after_the_lstat_is_not_appended_to(monkeypatch, tmp_path):+ """Without O_NOFOLLOW (Windows) the open follows a link planted between the lstat and the open."""+ calls, module, partial, victim = _shared_setup_3(monkeypatch, tmp_path)+ partial.write_bytes(b"y" * 40)+ monkeypatch.delattr(rp.os, "O_NOFOLLOW", raising = False)+ real_open, swapped = os.open, []++ def swap_then_open(path, *args, **kwargs):+ if Path(path) == partial and not swapped:+ swapped.append(1)+ partial.unlink()+ partial.symlink_to(victim)+ return real_open(path, *args, **kwargs)++ monkeypatch.setattr(rp.os, "open", swap_then_open)++ _shared_setup_1(module, partial, tmp_path)++ assert (+ victim.read_bytes() == b"keep me"+ ), "the download was appended to the swapped-in link target"+ assert calls["http_get"] == [{"resume_size": 0, "mode": "ab"}]++def test_a_partial_left_by_another_user_is_not_built_on(monkeypatch, tmp_path):"""Never append to a partial another account wrote; upstream checks size, never the hash."""calls, module, partial = _shared_setup_2(monkeypatch, tmp_path)@@ -457,14 +481,16 @@ def test_an_unopenable_partial_defers_instead_of_failing_the_download(monkeypatcdef test_a_partial_swapped_after_the_last_write_is_not_published(monkeypatch, tmp_path):"""_chmod_and_move re-resolves the name, so the partial must still be the file written, not a swap."""calls, module, partial = _shared_setup_2(monkeypatch, tmp_path)- real_http_get = module.http_get+ real_check = rp._still_the_written_file- def swap_then_write(url, handle, **kwargs):- real_http_get(url, handle, **kwargs)- partial.unlink()- partial.write_bytes(b"attacker's model")+ # After the handle closes: Windows refuses to move an open file. Moved aside, not unlinked, so the inode cannot be reused.+ def swap_then_check(path, written):+ if calls["http_get"]:+ path.rename(tmp_path / "moved-aside")+ path.write_bytes(b"attacker's model")+ return real_check(path, written)- module.http_get = swap_then_write+ monkeypatch.setattr(rp, "_still_the_written_file", swap_then_check)_shared_setup_1(module, partial, tmp_path)@@ -475,6 +501,7 @@ def test_a_partial_swapped_after_the_last_write_is_not_published(monkeypatch, tmdef test_ownership_that_cannot_be_established_is_an_objection(monkeypatch, tmp_path):"""An owner that cannot be established is an objection, so an unknown owner never reads as ours."""monkeypatch.delattr(rp.os, "geteuid", raising = False)+ monkeypatch.setattr(rp.os, "name", "posix")target = tmp_path / "partial"target.write_bytes(b"whoever wrote this")descriptor = os.open(target, os.O_RDONLY)@@ -484,11 +511,10 @@ def test_ownership_that_cannot_be_established_is_an_objection(monkeypatch, tmp_pos.close(descriptor)-def test_windows_keeps_the_stock_writer(monkeypatch, tmp_path):- """Without fcntl or provable ownership the shared name stays off; os.name and fcntl are both faked."""+def test_windows_byte_range_locks_count_as_exclusion(monkeypatch, tmp_path):+ """No fcntl on Windows: filelock, and so huggingface_hub, locks there with msvcrt instead."""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):@@ -497,7 +523,57 @@ def test_windows_keeps_the_stock_writer(monkeypatch, tmp_path):return real_import(name, *args, **kwargs)monkeypatch.setattr(builtins, "__import__", without_fcntl)- assert rp._exclusion_is_provable() is False+ held: list[int] = []++ def locking(fd, mode, nbytes):+ if held and locking.excludes:+ raise OSError(errno.EACCES, "locked")+ held.append(fd)++ monkeypatch.setitem(sys.modules, "msvcrt", types.SimpleNamespace(locking = locking, LK_NBLCK = 2))+ for excludes in (True, False):+ rp.invalidate_probe_cache()+ held.clear()+ locking.excludes = excludes+ assert rp._exclusion_is_provable() is excludes+ assert not list(tmp_path.iterdir()), "the probe left its file behind"+++windows_only = pytest.mark.skipif(sys.platform != "win32", reason = "real Windows locks and owners")+++@windows_only+def test_a_local_windows_cache_resumes_partials(tmp_path):+ assert rp.can_restore_partials(tmp_path) is True+++@windows_only+def test_a_partial_this_account_wrote_is_appended_to_on_windows(tmp_path):+ target = tmp_path / "abc.incomplete"+ target.write_bytes(b"mine")+ descriptor = os.open(target, os.O_WRONLY | os.O_APPEND)+ try:+ assert rp._objection_to(descriptor) is None+ finally:+ os.close(descriptor)+++@windows_only+def test_a_partial_another_account_owns_is_refused_on_windows(tmp_path):+ import subprocess++ target = tmp_path / "abc.incomplete"+ target.write_bytes(b"planted")+ # LocalSystem stands in for another account; changing the owner needs an administrator.+ if subprocess.run(+ ["icacls", str(target), "/setowner", "*S-1-5-18"], capture_output = True+ ).returncode:+ pytest.skip(reason = "changing a file owner needs administrator rights")+ descriptor = os.open(target, os.O_WRONLY | os.O_APPEND)+ try:+ assert rp._objection_to(descriptor) == "owned by another user"+ finally:+ os.close(descriptor)def test_an_oversized_partial_is_restarted_rather_than_resumed(monkeypatch, tmp_path):diff --git a/studio/backend/hub/utils/resumable_partials.py b/studio/backend/hub/utils/resumable_partials.pyindex 8697c8062a9..e39165e7c91 100644--- a/studio/backend/hub/utils/resumable_partials.py+++ b/studio/backend/hub/utils/resumable_partials.py@@ -1,7 +1,7 @@# 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, so 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, since NFS mounted ``-o local_lock=flock`` keeps flock locks client-local so two hosts each take "the" lock and neither sees ``EWOULDBLOCK``; and ``flock`` must actually exclude a second holder here, which :func:`_lock_is_honoured_at` measures by taking the lock twice, where only ``EWOULDBLOCK``/``EAGAIN`` counts as exclusion, since 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. 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."""+"""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, so 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, since NFS mounted ``-o local_lock=flock`` keeps flock locks client-local so two hosts each take "the" lock and neither sees ``EWOULDBLOCK``; and ``flock`` must actually exclude a second holder here, which :func:`_lock_is_honoured_at` measures by taking the lock twice, where only ``EWOULDBLOCK``/``EAGAIN`` counts as exclusion, since 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. Windows has no ``fcntl``, so there the probe takes the ``msvcrt`` byte-range lock that filelock, and so huggingface_hub, uses instead. 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@@ -164,6 +164,16 @@ def _filesystem_is_local_on(directory: str, device: int) -> bool:return True+def _nonblocking_lock():+ try:+ import fcntl+ except ImportError:+ # filelock's Windows lock, which reads EACCES as held elsewhere.+ import msvcrt+ return lambda fd: msvcrt.locking(fd, msvcrt.LK_NBLCK, 1), frozenset({errno.EACCES})+ return lambda fd: fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB), _CONTENDED++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))@@ -173,8 +183,6 @@ def _lock_is_honoured_at(directory: str) -> bool:@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 lets another user pre-place a symlink an unguarded open would follow and truncate.try:handle, name = tempfile.mkstemp(dir = directory, prefix = ".unsloth-flock-probe.")@@ -182,12 +190,13 @@ def _lock_is_honoured_on(directory: str, device: int) -> bool:raise _ProbeUnavailable(f"could not create the probe in {directory}: {exc}") from excsecond = Nonetry:- fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)+ lock, contended = _nonblocking_lock()+ lock(handle)second = os.open(name, os.O_RDWR | getattr(os, "O_NOFOLLOW", 0))try:- fcntl.flock(second, fcntl.LOCK_EX | fcntl.LOCK_NB)+ lock(second)except OSError as exc:- if exc.errno in _CONTENDED:+ if exc.errno in contended:return True# ENOLCK / EOPNOTSUPP / EINTR: not a refusal, so nothing has been shown.logger.info(@@ -224,11 +233,6 @@ def _exclusion_is_provable(hub_cache: Optional[Path | str] = None) -> bool: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, and 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), so 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 would pass.- 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.return _filesystem_is_local(str(directory)) and _lock_is_honoured_at(str(directory))@@ -260,13 +264,63 @@ def _objection_to(descriptor: int) -> Optional[str]: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.+ if os.name == "nt":+ try:+ owned = _owned_by_this_account(descriptor)+ except Exception: # noqa: BLE001 - an owner that cannot be read is not ours+ owned = False+ return None if owned else "owned by another user"return "on a platform where ownership cannot be established"if info.st_uid != euid():return "owned by another user"return None+def _owned_by_this_account(descriptor: int) -> bool:+ # os.fstat reports st_uid 0 on Windows, so read the owner SID off the handle instead.+ import ctypes+ import msvcrt+ from ctypes import wintypes++ advapi32 = ctypes.WinDLL("advapi32", use_last_error = True)+ kernel32 = ctypes.WinDLL("kernel32", use_last_error = True)+ kernel32.GetCurrentProcess.restype = wintypes.HANDLE+ SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION, TOKEN_QUERY = 1, 1, 0x0008+ TOKEN_USER, TOKEN_OWNER = 1, 4++ owner, security = ctypes.c_void_p(), ctypes.c_void_p()+ if advapi32.GetSecurityInfo(+ wintypes.HANDLE(msvcrt.get_osfhandle(descriptor)),+ SE_FILE_OBJECT,+ OWNER_SECURITY_INFORMATION,+ ctypes.byref(owner),+ None,+ None,+ None,+ ctypes.byref(security),+ ):+ return False+ token = wintypes.HANDLE()+ try:+ process = wintypes.HANDLE(kernel32.GetCurrentProcess())+ if not advapi32.OpenProcessToken(process, TOKEN_QUERY, ctypes.byref(token)):+ return False+ # An elevated administrator's new files are owned by the Administrators group, its token owner.+ for token_class in (TOKEN_USER, TOKEN_OWNER):+ size = wintypes.DWORD()+ advapi32.GetTokenInformation(token, token_class, None, 0, ctypes.byref(size))+ info = ctypes.create_string_buffer(size.value)+ if advapi32.GetTokenInformation(+ token, token_class, info, size, ctypes.byref(size)+ ) and advapi32.EqualSid(owner, ctypes.c_void_p.from_buffer(info)):+ return True+ return False+ finally:+ if token:+ kernel32.CloseHandle(token)+ kernel32.LocalFree(security)++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, so turning "an unrelated file is published as the model" into "the download is retried" is the improvement available here."""try:@@ -310,6 +364,13 @@ def _open_stable_partial(path: Path) -> Optional[Any]:return Noneelse:objection = _objection_to(descriptor)+ # Without O_NOFOLLOW a link swapped in after the lstat above is followed; the name must still be the opened file.+ if (+ objection is None+ and not nofollow+ and not _still_the_written_file(path, os.fstat(descriptor))+ ):+ objection = "a symlink"if objection is None:return os.fdopen(descriptor, "ab")os.close(descriptor)