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.

Studio: price a partial GGUF by what is left to fetch (#8989)

Michael Han77bc10c6636a
diff --git a/studio/backend/hub/schemas/inventory.py b/studio/backend/hub/schemas/inventory.py
index 75f713b53cc..8a2fe6abd36 100644
--- a/studio/backend/hub/schemas/inventory.py
+++ b/studio/backend/hub/schemas/inventory.py
@@ -24,6 +24,14 @@ class GgufVariantDetail(BaseModel):
)
size_bytes: int = Field(0, description = "File size in bytes")
download_size_bytes: int = Field(0, description = "Total bytes needed to download this variant")
+ download_remaining_bytes: Optional[int] = Field(
+ None,
+ description = (
+ "Bytes a resume still has to fetch: the total minus what is already on disk "
+ "and reusable. Set only on a partial variant; null when not partial or when "
+ "the plan cannot be resolved."
+ ),
+ )
downloaded: bool = Field(
False, description = "Whether this variant is already in the local HF cache"
)
diff --git a/studio/backend/hub/services/models/gguf_variants.py b/studio/backend/hub/services/models/gguf_variants.py
index 6a5e6b75821..aeb64e6974a 100644
--- a/studio/backend/hub/services/models/gguf_variants.py
+++ b/studio/backend/hub/services/models/gguf_variants.py
@@ -57,6 +57,7 @@ from hub.utils.gguf_plan import (
GgufVariantPlan as _GgufVariantRequirement,
build_gguf_variant_plans,
is_main_gguf_variant_path,
+ plan_from_expected_files,
)
logger = get_logger(__name__)
@@ -387,6 +388,67 @@ def _variant_dependency_key(repo_id: str, filename: str) -> Optional[str]:
return None
+def variant_remaining_bytes(
+ repo_id: str,
+ requirement,
+ repo_cache_dir: Optional[Path] = None,
+) -> Optional[int]:
+ """Bytes a resume of this variant still has to fetch, or None when unknown.
+
+ Priced per file, which is what the transfer actually reuses: a finished shard is
+ kept, an unresumable partial is refetched whole, so a one-file quant reads back its
+ full size.
+
+ Counted in the root the row names, falling back to the active one. Pricing a pinned row
+ against the active root is wrong in both directions: shards in the pinned root earn no
+ credit, and a copy in the active root earns credit a resume cannot use.
+ """
+ if requirement is None or not requirement.required_hashes:
+ return None
+ try:
+ have = download_registry.existing_blob_bytes(
+ "model",
+ repo_id,
+ requirement.required_hashes,
+ root = repo_cache_dir.parent if repo_cache_dir is not None else None,
+ )
+ except Exception as e:
+ logger.warning(f"Remaining-bytes lookup failed for {repo_id}: {e}")
+ return None
+ return max(0, requirement.download_size_bytes - have)
+
+
+def variant_remaining_bytes_from_state(
+ repo_id: str, variant: str, repo_cache_dir: Optional[Path]
+) -> Optional[int]:
+ """:func:`variant_remaining_bytes` for the local and offline listings, which have no hub
+ plan. The worker writes a manifest before it fetches anything, so a partial row can still
+ be priced from the file list that produced it.
+
+ Deliberately not capped by the row's own size: a local listing sizes a variant from the
+ shards ON DISK, so on an early interruption that total is smaller than the transfer.
+ """
+ if not variant:
+ return None
+ try:
+ manifest = download_manifest.read_manifest(
+ "model",
+ repo_id,
+ variant,
+ hub_cache = repo_cache_dir.parent if repo_cache_dir is not None else None,
+ )
+ except Exception as e:
+ logger.warning(f"Manifest read failed while pricing {repo_id} [{variant}]: {e}")
+ return None
+ if manifest is None or not manifest.expected_files:
+ return None
+ return variant_remaining_bytes(
+ repo_id,
+ plan_from_expected_files(variant, manifest.expected_files),
+ repo_cache_dir,
+ )
+
+
def _partial_transport_for_variant(
repo_id: str,
variant: str,
@@ -1018,6 +1080,13 @@ async def get_gguf_variants_answer(
display_label = v.display_label,
size_bytes = v.size_bytes,
download_size_bytes = v.size_bytes,
+ download_remaining_bytes = (
+ None
+ if _downloaded(v)
+ else variant_remaining_bytes_from_state(
+ response_repo_id, v.quant, repo_cache_dir
+ )
+ ),
downloaded = _downloaded(v),
partial = not _downloaded(v),
dependency_key = _variant_dependency_key(response_repo_id, v.filename),
@@ -1042,6 +1111,11 @@ async def get_gguf_variants_answer(
display_label = v.display_label,
size_bytes = v.size_bytes,
download_size_bytes = v.download_size_bytes or v.size_bytes,
+ download_remaining_bytes = variant_remaining_bytes_from_state(
+ response_repo_id,
+ v.quant,
+ repo_cache_dir,
+ ),
downloaded = False,
partial = True,
partial_transport = _partial_transport_for_variant(
@@ -1078,6 +1152,11 @@ async def get_gguf_variants_answer(
display_label = v.display_label,
size_bytes = v.size_bytes,
download_size_bytes = v.download_size_bytes or v.size_bytes,
+ download_remaining_bytes = variant_remaining_bytes_from_state(
+ repo_id,
+ v.quant,
+ repo_cache_dir,
+ ),
downloaded = False,
partial = True,
partial_transport = _partial_transport_for_variant(
@@ -1486,6 +1565,12 @@ async def get_gguf_variants_answer(
download_size_bytes = (
requirement.download_size_bytes if requirement is not None else v.size_bytes
),
+ # Scanned per partial variant only: repos carry one, and the scan walks blobs/.
+ download_remaining_bytes = (
+ variant_remaining_bytes(repo_id, requirement, repo_cache_dir)
+ if is_partial
+ else None
+ ),
downloaded = downloaded,
update_available = downloaded
and _variant_update_available_from_requirement(
diff --git a/studio/backend/hub/tests/test_sparse_partial_bytes.py b/studio/backend/hub/tests/test_sparse_partial_bytes.py
new file mode 100644
index 00000000000..390c9cafeaf
--- /dev/null
+++ b/studio/backend/hub/tests/test_sparse_partial_bytes.py
@@ -0,0 +1,65 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The all-sparse partial: a file sized before a single byte of it is transferred.
+
+A parallel Range writer sets the ``.incomplete`` to its final length up front and then fills
+blocks out of order. In between the file is its full logical size with nothing allocated behind
+it, and crediting ``st_size`` there reads "0 B left" on a download that has not moved.
+"""
+
+import os
+from pathlib import Path
+
+import pytest
+
+from hub.utils import hf_cache_state
+from hub.utils.hf_cache_state import blob_bytes_present
+
+
+_SIZE = 8 * 1024 * 1024
+
+
+def _sized_but_unwritten(path: Path) -> Path:
+ """Full length, no blocks: what a preallocating writer leaves before its first chunk."""
+ with open(path, "wb") as handle:
+ handle.truncate(_SIZE)
+ return path
+
+
+def _needs_sparse_support(path: Path) -> None:
+ if not hf_cache_state._holds_no_data(_sized_but_unwritten(path.parent / ".probe")):
+ pytest.skip("filesystem does not report sparse extents")
+
+
+def test_a_sized_but_unwritten_partial_is_worth_nothing(tmp_path):
+ blob = _sized_but_unwritten(tmp_path / "a.incomplete")
+ _needs_sparse_support(blob)
+ assert os.stat(blob).st_size == _SIZE
+ assert blob_bytes_present(blob) == 0
+
+
+def test_the_first_chunk_to_land_is_counted(tmp_path):
+ """The zero is about emptiness, not about being sparse -- a written extent still counts."""
+ blob = _sized_but_unwritten(tmp_path / "b.incomplete")
+ _needs_sparse_support(blob)
+ with open(blob, "r+b") as handle:
+ handle.seek(_SIZE - 4096)
+ handle.write(b"x" * 4096)
+ present = blob_bytes_present(blob)
+ assert 0 < present <= _SIZE
+
+
+def test_a_filesystem_that_reports_no_blocks_still_falls_back_to_size(tmp_path, monkeypatch):
+ """Where the field is simply never populated, the logical size remains the best guess."""
+ blob = _sized_but_unwritten(tmp_path / "c.incomplete")
+ monkeypatch.setattr(hf_cache_state, "_holds_no_data", lambda _path: False)
+ assert blob_bytes_present(blob) == _SIZE
+
+
+def test_a_whole_file_is_still_measured_by_its_blocks(tmp_path):
+ """The dense case is unchanged: bytes actually written are what is present."""
+ blob = tmp_path / "d.incomplete"
+ blob.write_bytes(b"x" * 65536)
+ _needs_sparse_support(blob)
+ assert blob_bytes_present(blob) == 65536
diff --git a/studio/backend/hub/utils/download_registry.py b/studio/backend/hub/utils/download_registry.py
index 3b1c140b8db..a45f74e7f0b 100644
--- a/studio/backend/hub/utils/download_registry.py
+++ b/studio/backend/hub/utils/download_registry.py
@@ -80,6 +80,7 @@ from hub.utils.hf_cache_state import (
target_dir_name,
hf_cache_root,
ABANDONED_PARTIAL_SECONDS,
+ blob_bytes_present,
blob_download_lock_held,
hf_cache_roots,
incomplete_blob_hash,
@@ -1162,19 +1163,31 @@ def completed_blob_bytes(
return total
-def existing_blob_bytes(repo_type: str, repo_id: str, blob_hashes: frozenset[str]) -> int:
- """Bytes a download will NOT have to fetch again for *blob_hashes*, in the active HF cache
- root: finalized blobs, plus partials something can still resume from. A blob is in exactly
- one state, so summing both candidate names never double-counts. Used to size what a
- (possibly resumed) download still needs to write before the run starts."""
+def existing_blob_bytes(
+ repo_type: str,
+ repo_id: str,
+ blob_hashes: frozenset[str],
+ *,
+ root: Optional[Path] = None,
+) -> int:
+ """Bytes a download will NOT have to fetch again for *blob_hashes*, in *root* or, when it is
+ None, the active HF cache root: finalized blobs, plus partials something can still resume
+ from. A row pinned to another root must pass it, since a resume writes into the root the row
+ names and blobs in the active one are not bytes it can reuse. A blob is in exactly one state,
+ so summing both candidate names never double-counts. Used to size what a (possibly resumed)
+ download still needs to write before the run starts."""
if not blob_hashes:
return 0
- total = 0
- for entry in iter_active_repo_cache_dirs(repo_type, repo_id):
+ # One tally for ALL the repo dirs the root holds, not one per dir. The Hub resolves repo ids
+ # case-insensitively while huggingface_hub keeps the caller's casing in the folder name, so
+ # a case-sensitive filesystem really does end up with models--Org--Model beside
+ # models--org--model, each holding its own copy of the same blob. Summing the dirs counted
+ # that shard twice, and the caller's max(0, total - have) then clamped to zero.
+ present = {blob_hash: 0 for blob_hash in blob_hashes}
+ for entry in iter_active_repo_cache_dirs(repo_type, repo_id, root = root):
blobs_dir = entry / "blobs"
if not blobs_dir.is_dir():
continue
- present = {blob_hash: 0 for blob_hash in blob_hashes}
try:
entries = list(blobs_dir.iterdir())
except OSError:
@@ -1200,13 +1213,24 @@ def existing_blob_bytes(repo_type: str, repo_id: str, blob_hashes: frozenset[str
# on that lock and reuse the result, so those bytes are not ours to find
# room for. Two GGUF variants sharing an mmproj hit this every time.
continue
+ # A partial is measured by the bytes actually ON DISK, not by its logical
+ # length: hf_transfer's parallel Range writer leaves a sparse file whose
+ # st_size runs ahead of what has been written -- observed at 1.2 GB reported
+ # against 112 MB present, and once st_size reached the declared size the
+ # remainder read as zero for a file barely started. A finalized blob is whole
+ # by construction, so it keeps st_size: st_blocks is smaller than the file on
+ # a compressing filesystem.
+ bytes_here = (
+ blob_bytes_present(blob)
+ if partial_hash is not None
+ else max(0, int(blob.stat().st_size))
+ )
# Broken advisory locks can leave several process-unique writers for one etag.
# They are duplicate attempts, not additive completion, so keep the largest.
- present[blob_hash] = max(present[blob_hash], max(0, int(blob.stat().st_size)))
+ present[blob_hash] = max(present[blob_hash], max(0, int(bytes_here)))
except OSError:
continue
- total += sum(present.values())
- return total
+ return sum(present.values())
JobState = Literal["idle", "running", "cancelling", "cancelled", "complete", "error"]
diff --git a/studio/backend/hub/utils/hf_cache_state.py b/studio/backend/hub/utils/hf_cache_state.py
index 5504f09daa1..42e98b9b6e4 100644
--- a/studio/backend/hub/utils/hf_cache_state.py
+++ b/studio/backend/hub/utils/hf_cache_state.py
@@ -260,9 +260,16 @@ def blob_bytes_present(path: Path) -> int:
``st_blocks``, falling back to ``st_size`` where it is unreported (Windows,
some network filesystems)."""
st = path.stat()
- blocks = getattr(st, "st_blocks", 0)
- if blocks > 0:
+ blocks = getattr(st, "st_blocks", None)
+ if blocks is not None and blocks > 0:
return min(blocks * 512, st.st_size)
+ # A present zero is not a missing field. A parallel writer that sets the partial to its
+ # final length before its first chunk lands sits exactly here, and reading st_size then
+ # says "0 B left" on a download that has transferred nothing. The zero alone is not enough
+ # to act on -- a mount that never populates st_blocks looks the same -- so confirm the
+ # emptiness directly before believing it.
+ if blocks == 0 and _holds_no_data(path):
+ return 0
if sys.platform == "win32":
allocated = _windows_allocated_size(path)
if allocated is not None:
@@ -270,6 +277,28 @@ def blob_bytes_present(path: Path) -> int:
return st.st_size
+def _holds_no_data(path: Path) -> bool:
+ """Whether the file has no allocated extent anywhere, asked of the kernel rather than
+ inferred. ``SEEK_DATA`` past the end of the last extent is ENXIO, so a file with nothing
+ written raises on the very first seek. Every other answer -- an unsupported seek, an
+ unreadable path -- leaves the caller's size fallback in charge.
+ """
+ seek_data = getattr(os, "SEEK_DATA", None)
+ if seek_data is None:
+ return False
+ try:
+ fd = os.open(path, os.O_RDONLY)
+ except OSError:
+ return False
+ try:
+ os.lseek(fd, 0, seek_data)
+ except OSError as exc:
+ return exc.errno == errno.ENXIO
+ finally:
+ os.close(fd)
+ return False
+
+
def _windows_allocated_size(path: Path) -> Optional[int]:
"""Best-effort allocated-byte count for sparse files on Windows."""
if sys.platform != "win32":
diff --git a/studio/backend/tests/test_partial_remaining_bytes.py b/studio/backend/tests/test_partial_remaining_bytes.py
new file mode 100644
index 00000000000..cd659fc52e4
--- /dev/null
+++ b/studio/backend/tests/test_partial_remaining_bytes.py
@@ -0,0 +1,268 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""A partial row is priced by what a resume still has to fetch.
+
+The card used to print the variant total beside a resume button, so continuing a
+sharded download that was 40 GB in still read "56 GB". Bytes reused are whole
+files: a finished shard is kept, an unresumable partial is refetched, so a
+one-file quant really does read back its full size.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+from typing import Optional
+
+import pytest
+
+_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
+if _BACKEND_DIR not in sys.path:
+ sys.path.insert(0, _BACKEND_DIR)
+
+from hub.services.models.gguf_variants import (
+ variant_remaining_bytes,
+ variant_remaining_bytes_from_state,
+)
+from hub.utils import download_manifest, download_registry, hf_cache_state, state_dir
+from hub.utils.download_manifest import ExpectedFile
+from hub.utils.gguf_plan import plan_from_expected_files
+
+
+SHARD_A = "a" * 64
+SHARD_B = "b" * 64
+GB = 1024**3
+
+
+def blobs(monkeypatch, tmp_path):
+ blobs_root = tmp_path / "hub"
+ blobs_dir = blobs_root / "models--Org--Model" / "blobs"
+ blobs_dir.mkdir(parents = True)
+ monkeypatch.setenv("HF_HUB_CACHE", str(blobs_root))
+
+ # Honours an explicit root, which is what a row pinned to another cache passes. A stub that
+ # ignored the argument would hide exactly the bug the pinned tests are about.
+ def _root(*, root: Optional[Path] = None, **_kw):
+ return Path(root) if root is not None else blobs_root
+
+ monkeypatch.setattr(download_registry, "hf_cache_root", _root)
+ monkeypatch.setattr(hf_cache_state, "hf_cache_root", _root)
+ monkeypatch.setattr(hf_cache_state, "hf_cache_roots", lambda *_a, **_k: [blobs_root])
+ return blobs_dir
+
+
+def _write(path: Path, size: int) -> Path:
+ path.write_bytes(b"")
+ with path.open("wb") as handle:
+ handle.truncate(size)
+ return path
+
+
+def _split_plan():
+ """Two shards of one quant, 2 GB each."""
+ return plan_from_expected_files(
+ "Q4_K_M",
+ [
+ ExpectedFile(path = "model-Q4_K_M-00001-of-00002.gguf", size = 2 * GB, sha256 = SHARD_A),
+ ExpectedFile(path = "model-Q4_K_M-00002-of-00002.gguf", size = 2 * GB, sha256 = SHARD_B),
+ ],
+ )
+
+
+def test_a_finished_shard_is_subtracted(blobs):
+ _write(blobs / SHARD_A, 2 * GB)
+ assert variant_remaining_bytes("Org/Model", _split_plan()) == 2 * GB
+
+
+def test_nothing_on_disk_still_prices_the_whole_variant(blobs):
+ assert variant_remaining_bytes("Org/Model", _split_plan()) == 4 * GB
+
+
+def test_an_unresumable_partial_is_priced_as_a_full_refetch(blobs):
+ # 1.18+ writes <etag>.<nonce>.incomplete and never reopens it, so those bytes are gone.
+ _write(blobs / f"{SHARD_A}.deadbeef{hf_cache_state.INCOMPLETE_SUFFIX}", 2 * GB)
+ assert variant_remaining_bytes("Org/Model", _split_plan()) == 4 * GB
+
+
+def test_a_one_file_quant_reads_back_its_full_size(blobs):
+ """Nothing to keep, so a resume costs the whole quant -- the case users report as the
+ model downloading all over again, and the number has to say so."""
+ plan = plan_from_expected_files(
+ "Q4_K_M",
+ [ExpectedFile(path = "model-Q4_K_M.gguf", size = 4 * GB, sha256 = SHARD_A)],
+ )
+ _write(blobs / f"{SHARD_A}.deadbeef{hf_cache_state.INCOMPLETE_SUFFIX}", 3 * GB)
+ assert variant_remaining_bytes("Org/Model", plan) == 4 * GB
+
+
+def test_an_unresolvable_plan_reports_nothing_rather_than_guessing(blobs):
+ assert variant_remaining_bytes("Org/Model", None) is None
+ empty = plan_from_expected_files(
+ "Q4_K_M",
+ [ExpectedFile(path = "model-Q4_K_M.gguf", size = 4 * GB, sha256 = None)],
+ )
+ assert variant_remaining_bytes("Org/Model", empty) is None
+
+
+def test_a_complete_variant_has_nothing_left_to_fetch(blobs):
+ _write(blobs / SHARD_A, 2 * GB)
+ _write(blobs / SHARD_B, 2 * GB)
+ assert variant_remaining_bytes("Org/Model", _split_plan()) == 0
+
+
+# --------------------------------------------------------------------------------------------
+# Offline and local-cache listings, which have no hub plan to price from. The on-device card
+# asks for those (preferLocalCache), so leaving them unpriced showed the full total there.
+# --------------------------------------------------------------------------------------------
+
+
+def state(monkeypatch, tmp_path):
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ return tmp_path
+
+
+def _write_manifest(files):
+ assert download_manifest.write_manifest("model", "Org/Model", "Q4_K_M", files, "http")
+
+
+def test_the_worker_manifest_prices_a_local_partial(blobs, state):
+ _write_manifest(
+ [
+ ExpectedFile(path = "model-Q4_K_M-00001-of-00002.gguf", size = 2 * GB, sha256 = SHARD_A),
+ ExpectedFile(path = "model-Q4_K_M-00002-of-00002.gguf", size = 2 * GB, sha256 = SHARD_B),
+ ]
+ )
+ _write(blobs / SHARD_A, 2 * GB)
+
+ assert variant_remaining_bytes_from_state("Org/Model", "Q4_K_M", None) == 2 * GB
+
+
+def test_a_row_with_no_manifest_stays_unpriced(blobs, state):
+ assert variant_remaining_bytes_from_state("Org/Model", "Q4_K_M", None) is None
+
+
+def test_a_companion_the_row_does_not_count_is_still_priced(blobs, state):
+ # The mmproj comes down with the quant, so it belongs in the transfer even though the
+ # row's own size does not include it.
+ _write_manifest(
+ [
+ ExpectedFile(path = "model-Q4_K_M.gguf", size = 4 * GB, sha256 = SHARD_A),
+ ExpectedFile(path = "mmproj-F16.gguf", size = 1 * GB, sha256 = SHARD_B),
+ ]
+ )
+
+ assert variant_remaining_bytes_from_state("Org/Model", "Q4_K_M", None) == 5 * GB
+
+
+def test_an_unnamed_variant_is_not_priced(blobs, state):
+ assert variant_remaining_bytes_from_state("Org/Model", "", None) is None
+
+
+def test_a_local_row_is_not_capped_by_the_shards_it_already_has(blobs, state):
+ """A local scan sizes a variant from the shards ON DISK, so an early interruption makes
+ that total smaller than the transfer still to come."""
+ shard_c = "c" * 64
+ _write_manifest(
+ [
+ ExpectedFile(path = "m-Q4_K_M-00001-of-00003.gguf", size = 2 * GB, sha256 = SHARD_A),
+ ExpectedFile(path = "m-Q4_K_M-00002-of-00003.gguf", size = 2 * GB, sha256 = SHARD_B),
+ ExpectedFile(path = "m-Q4_K_M-00003-of-00003.gguf", size = 2 * GB, sha256 = shard_c),
+ ]
+ )
+ _write(blobs / SHARD_A, 2 * GB)
+
+ # 2 GB on disk, so the local row advertises 2 GB, but 4 GB is still to fetch.
+ assert variant_remaining_bytes_from_state("Org/Model", "Q4_K_M", None) == 4 * GB
+
+
+# --------------------------------------------------------------------------------------------
+# A partial is measured by the bytes really on disk, and one shard is credited once however
+# many repo directories the cache holds for the same repo. Both were observed against real
+# caches.
+# --------------------------------------------------------------------------------------------
+
+
+MB = 1024**2
+
+
+def _sparse(path: Path, written: int, logical: int) -> Path:
+ """A real sparse file: *written* bytes allocated, *logical* bytes reported."""
+ with path.open("wb") as handle:
+ handle.write(b"\xa5" * written)
+ handle.truncate(logical)
+ return path
+
+
+def test_a_sparse_partial_is_priced_by_the_bytes_it_actually_holds(blobs):
+ """hf_transfer's parallel Range writer leaves a partial whose st_size runs ahead of what has
+ been written, so crediting the logical size read "0 B left" for a file barely started."""
+ from filelock import FileLock
+
+ plan = plan_from_expected_files(
+ "Q4_K_M",
+ [ExpectedFile(path = "model-Q4_K_M.gguf", size = 64 * MB, sha256 = SHARD_A)],
+ )
+ partial = _sparse(
+ blobs / f"{SHARD_A}.deadbeef{hf_cache_state.INCOMPLETE_SUFFIX}", 4 * MB, 64 * MB
+ )
+ assert partial.stat().st_size == 64 * MB
+ assert partial.stat().st_blocks * 512 < 8 * MB
+
+ # Held lock: the one state in which a partial no later attempt could reopen still counts,
+ # because a live writer is finishing it. That is exactly when it is sparsest.
+ lock_path = blobs.parent.parent / ".locks" / blobs.parent.name / f"{SHARD_A}.lock"
+ lock_path.parent.mkdir(parents = True, exist_ok = True)
+ with FileLock(str(lock_path), timeout = 5):
+ remaining = variant_remaining_bytes("Org/Model", plan)
+
+ assert remaining is not None
+ assert remaining >= 64 * MB - 8 * MB, "credited the sparse file's logical size, not its bytes"
+
+
+def test_one_shard_in_two_case_variant_repo_dirs_is_credited_once(blobs, monkeypatch):
+ """The Hub resolves repo ids case-insensitively while huggingface_hub keeps the caller's
+ casing in the folder name, so a case-sensitive filesystem holds models--Org--Model beside
+ models--org--model. Summing the directories counted one shard twice."""
+ root = blobs.parent.parent
+ twin = root / "models--org--model" / "blobs"
+ twin.mkdir(parents = True)
+ _write(blobs / SHARD_A, 2 * GB)
+ _write(twin / SHARD_A, 2 * GB)
+
+ assert variant_remaining_bytes("Org/Model", _split_plan()) == 2 * GB
+
+
+# --------------------------------------------------------------------------------------------
+# A row pinned to another cache root. A resume writes into the root the row names, so blobs in
+# the active root are not bytes it can reuse. Both directions used to be wrong.
+# --------------------------------------------------------------------------------------------
+
+
+def test_a_pinned_root_gets_credit_for_the_shards_it_holds(blobs, tmp_path):
+ other_root = tmp_path / "previous-hub"
+ other_blobs = other_root / "models--Org--Model" / "blobs"
+ other_blobs.mkdir(parents = True)
+ _write(other_blobs / SHARD_A, 2 * GB)
+
+ pinned = other_root / "models--Org--Model"
+ assert variant_remaining_bytes("Org/Model", _split_plan(), pinned) == 2 * GB
+
+
+def test_the_active_roots_copy_does_not_pay_for_a_pinned_row(blobs, tmp_path):
+ # The whole variant sits in the active root and none of it in the pinned one, so counting
+ # it reported nothing left to fetch for a transfer that has everything still to do.
+ _write(blobs / SHARD_A, 2 * GB)
+ _write(blobs / SHARD_B, 2 * GB)
+ other_root = tmp_path / "previous-hub"
+ (other_root / "models--Org--Model" / "blobs").mkdir(parents = True)
+
+ pinned = other_root / "models--Org--Model"
+ assert variant_remaining_bytes("Org/Model", _split_plan(), pinned) == 4 * GB
+
+
+def test_an_unpinned_row_still_reads_the_active_root(blobs):
+ _write(blobs / SHARD_A, 2 * GB)
+ assert variant_remaining_bytes("Org/Model", _split_plan(), None) == 2 * GB
diff --git a/studio/frontend/src/features/hub/catalog/gguf-download-card.tsx b/studio/frontend/src/features/hub/catalog/gguf-download-card.tsx
index 714079e4ec0..efe0bf72530 100644
--- a/studio/frontend/src/features/hub/catalog/gguf-download-card.tsx
+++ b/studio/frontend/src/features/hub/catalog/gguf-download-card.tsx
@@ -56,7 +56,6 @@ import {
} from "../download-manager";
import { useOnlineStatus } from "../hooks/use-online-status";
import { type GgufVariantDetail, deleteCachedModel } from "../inventory";
-import { formatBytes } from "../lib/format";
import { type GgufFitClass, classifyGgufFit } from "../lib/gguf-fit";
import {
ggufFilenamesMatch,
@@ -64,7 +63,7 @@ import {
} from "../lib/gguf-filename";
import {
ggufVariantDisplayLabel,
- ggufVariantDownloadSizeBytes,
+ ggufVariantTransferLabel,
sortDownloadableGgufVariants,
} from "../lib/gguf-variant-sort";
import { HUB_GGUF_RUN_ACTIONS_VISIBLE } from "../lib/hub-feature-flags";
@@ -259,7 +258,7 @@ function createGgufVariantMenuItems(
fit: classifyGgufFit(variant.size_bytes, resources),
downloaded: Boolean(variant.downloaded),
partial: Boolean(variant.partial),
- downloadSizeLabel: formatBytes(ggufVariantDownloadSizeBytes(variant)),
+ downloadSizeLabel: ggufVariantTransferLabel(variant),
}));
}
@@ -743,7 +742,7 @@ export function GgufDownloadCard({
[gpuGb, selected?.size_bytes, systemRamGb],
);
const selectedDownloadSizeLabel = selected
- ? formatBytes(ggufVariantDownloadSizeBytes(selected))
+ ? ggufVariantTransferLabel(selected)
: null;
const updateAvailable =
selected?.downloaded === true && selected.update_available === true;
diff --git a/studio/frontend/src/features/hub/catalog/gguf-live-variant-states.ts b/studio/frontend/src/features/hub/catalog/gguf-live-variant-states.ts
index ca18a00bcee..3887225266b 100644
--- a/studio/frontend/src/features/hub/catalog/gguf-live-variant-states.ts
+++ b/studio/frontend/src/features/hub/catalog/gguf-live-variant-states.ts
@@ -8,6 +8,9 @@ import { normalizeGgufVariantIdentity } from "../lib/model-identity";
export type LiveGgufVariantState = {
state: ManagedDownload["state"];
expectedBytes: number;
+ transferredBytes: number;
+ /** Whether `transferredBytes` came from a poll that measured it. */
+ measuredTransfer: boolean;
startedAt: number;
};
@@ -49,6 +52,14 @@ export function createLiveGgufVariantStatesSelector(repoId: string): (state: {
{
state: job.state,
expectedBytes: job.expectedBytes,
+ // The in-flight counter alone, never max(downloaded, completed): a max
+ // could only fire on a HELD completed figure, which is priced against
+ // the previous baseline. After an XET-to-HTTP reclaim that subtracted
+ // 3 GB from a 0.5 GB remainder and the row read "0 B left".
+ transferredBytes: job.downloadedBytes,
+ // Undefined is a job that has not polled yet, which has no held
+ // figure to forward; only an explicit false is a held reading.
+ measuredTransfer: job.measuredTransfer !== false,
startedAt: job.startedAt,
},
]);
@@ -76,12 +87,42 @@ export function applyLiveGgufVariantStates(
variant.download_size_bytes ?? 0,
variant.size_bytes,
);
+ // The row says "N left", so N has to follow the transfer of a running job,
+ // and the backend's measured remainder covers every other case.
+ //
+ // Both terms come from the job and only from the job. snapshot_progress nets
+ // completed_baseline_bytes -- files a previous quant already fetched, an
+ // mmproj most often -- out of expected_bytes AND downloaded_bytes alike, so
+ // the pair is self-consistent while the catalog totals above are not.
+ // Subtracting the transfer from `expectedBytes`, the larger of the two
+ // scopes, adds that baseline back: 1 GB reused and 1 GB fetched of a 5 GB
+ // plan would read 4 GB left rather than 3 GB.
+ //
+ // Only while running: `transferredBytes` is progress, not bytes a resume can
+ // reuse. From huggingface_hub 1.18 the partial is process-unique and unlinked
+ // in a finally, so an interrupted transfer is refetched whole, which is how
+ // `existing_blob_bytes` already prices it. Subtracting a dead job's progress
+ // read "1.0 GB left" for a cancelled 18 GB download with all 18 GB to fetch.
+ //
+ // And only off a MEASURED reading: a held one is priced against the previous,
+ // larger total, so mixing it with the current one read "0 B left".
+ const liveRemaining =
+ activeDownloadState(live.state) &&
+ live.measuredTransfer &&
+ live.expectedBytes > 0 &&
+ live.transferredBytes > 0
+ ? Math.max(live.expectedBytes - live.transferredBytes, 0)
+ : null;
return {
...variant,
downloaded: liveComplete ? true : livePartial ? false : variant.downloaded,
partial: liveComplete ? false : livePartial || variant.partial,
download_size_bytes:
expectedBytes > 0 ? expectedBytes : variant.download_size_bytes,
+ download_remaining_bytes:
+ liveComplete
+ ? variant.download_remaining_bytes
+ : liveRemaining ?? variant.download_remaining_bytes,
};
});
}
diff --git a/studio/frontend/src/features/hub/catalog/local-on-device-card.tsx b/studio/frontend/src/features/hub/catalog/local-on-device-card.tsx
index db5f4dacbc4..a020dde3577 100644
--- a/studio/frontend/src/features/hub/catalog/local-on-device-card.tsx
+++ b/studio/frontend/src/features/hub/catalog/local-on-device-card.tsx
@@ -324,6 +324,11 @@ export function LocalOnDeviceCard({
...variant,
download_size_bytes:
remoteVariant.download_size_bytes || variant.download_size_bytes,
+ // Both sides measure the same cache; keep the local reading and let the
+ // remote one cover a row the local listing could not price.
+ download_remaining_bytes:
+ variant.download_remaining_bytes ??
+ remoteVariant.download_remaining_bytes,
update_available: remoteVariant.update_available === true,
};
});
diff --git a/studio/frontend/src/features/hub/download-manager/adopt-rules.ts b/studio/frontend/src/features/hub/download-manager/adopt-rules.ts
index a83f911eaef..dcc00f432d2 100644
--- a/studio/frontend/src/features/hub/download-manager/adopt-rules.ts
+++ b/studio/frontend/src/features/hub/download-manager/adopt-rules.ts
@@ -29,6 +29,21 @@ export function carriesOverSeed(
return persistedGeneration === probedGeneration;
}
+/**
+ * Whether an adopted job keeps the persisted held-transfer marker.
+ *
+ * It travels with the counters, because it is a statement ABOUT them: seeding the bytes while
+ * dropping the marker restores it as undefined, which reads as measured, and the row goes back
+ * to "0 B left". Not carrying the seed zeroes the counters, so there is no held figure left to
+ * distrust and undefined is the honest answer rather than a lost one.
+ */
+export function seededMeasuredTransfer(
+ carryOverSeed: boolean,
+ persistedMeasuredTransfer: boolean | undefined,
+): boolean | undefined {
+ return carryOverSeed ? persistedMeasuredTransfer : undefined;
+}
+
/**
* "active" (the job is adoptable) or "gone" (its cache was wiped), from one raw reading.
*
diff --git a/studio/frontend/src/features/hub/download-manager/download-manager-state.ts b/studio/frontend/src/features/hub/download-manager/download-manager-state.ts
index 37d335bc7be..d2ee7dbd8e2 100644
--- a/studio/frontend/src/features/hub/download-manager/download-manager-state.ts
+++ b/studio/frontend/src/features/hub/download-manager/download-manager-state.ts
@@ -32,7 +32,10 @@ import {
} from "./runtime-registry";
const PERSIST_KEY = "unsloth.studio.downloads";
-const PERSIST_VERSION = 1;
+// 2 is the first version whose records can say whether their byte counters were measured.
+// Below it, an absent marker is not evidence of anything, so the migration decides.
+const PERSIST_VERSION = 2;
+const MEASURED_TRANSFER_VERSION = 2;
const PERSIST_THROTTLE_MS = 1_000;
function isRecord(value: unknown): value is Record<string, unknown> {
@@ -47,7 +50,10 @@ function nonNegativeNumber(value: unknown, fallback = 0): number {
return Math.max(0, finiteNumber(value, fallback));
}
-function sanitizePersistedJob(value: unknown): ManagedDownload | null {
+function sanitizePersistedJob(
+ value: unknown,
+ legacy = false,
+): ManagedDownload | null {
if (!isRecord(value)) return null;
const kind = isDownloadKind(value.kind) ? value.kind : null;
const repoId = typeof value.repoId === "string" ? value.repoId : null;
@@ -80,6 +86,19 @@ function sanitizePersistedJob(value: unknown): ManagedDownload | null {
...(typeof value.checkpoint === "boolean"
? { checkpoint: value.checkpoint }
: {}),
+ // A held reading survives the reload that carried it: dropping the flag restores the stale
+ // downloadedBytes with the guard reading undefined (so, measured), which is the "0 B left"
+ // the guard exists to stop.
+ //
+ // Absent means "never polled" only for a record written since the field existed. Below that
+ // version a job that HAD polled says nothing either way, so a legacy record already carrying
+ // counters is read as held. It costs one poll of an untightened remainder; believing it
+ // costs the "0 B left" this whole marker is for.
+ ...(typeof value.measuredTransfer === "boolean"
+ ? { measuredTransfer: value.measuredTransfer }
+ : legacy && nonNegativeNumber(value.downloadedBytes) > 0
+ ? { measuredTransfer: false }
+ : {}),
...(isResolvedTransport(value.transport)
? { transport: value.transport }
: {}),
@@ -91,13 +110,14 @@ function sanitizePersistedJob(value: unknown): ManagedDownload | null {
function sanitizePersistedState(
persisted: unknown,
+ legacy = false,
): Partial<DownloadManagerState> {
if (!isRecord(persisted) || !isRecord(persisted.jobs)) {
return { jobs: {}, conflicts: {} };
}
const jobs: Record<string, ManagedDownload> = {};
for (const value of Object.values(persisted.jobs)) {
- const job = sanitizePersistedJob(value);
+ const job = sanitizePersistedJob(value, legacy);
if (job) jobs[job.key] = job;
}
return {
@@ -126,6 +146,9 @@ function toPersistedJob(
: {}),
...(job.scopedFiles !== undefined ? { scopedFiles: job.scopedFiles } : {}),
...(job.checkpoint !== undefined ? { checkpoint: job.checkpoint } : {}),
+ ...(job.measuredTransfer !== undefined
+ ? { measuredTransfer: job.measuredTransfer }
+ : {}),
...(job.transport !== undefined ? { transport: job.transport } : {}),
// Alongside the transport, never instead of it: a fallback run reads as
// plain HTTP without this and the reloaded card offers Pause for a stop
@@ -239,7 +262,8 @@ export const useDownloadManagerStore = create<DownloadManagerState>()(
? noopStorage
: createThrottledStorage(window.localStorage, PERSIST_THROTTLE_MS),
),
- migrate: (persisted) => sanitizePersistedState(persisted),
+ migrate: (persisted, version) =>
+ sanitizePersistedState(persisted, version < MEASURED_TRANSFER_VERSION),
merge: (persisted, current) => ({
...current,
...sanitizePersistedState(persisted),
diff --git a/studio/frontend/src/features/hub/download-manager/download-manager-types.ts b/studio/frontend/src/features/hub/download-manager/download-manager-types.ts
index 37cc940c2f7..4496efee4f0 100644
--- a/studio/frontend/src/features/hub/download-manager/download-manager-types.ts
+++ b/studio/frontend/src/features/hub/download-manager/download-manager-types.ts
@@ -14,6 +14,13 @@ export interface ManagedDownload {
variant: string | null;
state: DownloadJobState;
downloadedBytes: number;
+ /** False when the last poll HELD `downloadedBytes` rather than measuring it
+ * (see `resolveProgressUpdate`). A held figure belongs to the previous
+ * reading's total, so a surface that subtracts it from the current
+ * `expectedBytes` is mixing two plans and should fall back to the backend's
+ * own remainder. Undefined on a job that has not polled yet, which has no held
+ * bytes to forward. */
+ measuredTransfer?: boolean;
// Finalized bytes on disk (excludes the in-progress `.incomplete` portion in
// `downloadedBytes`). The completion fallback keys off this so a partial can't
// be marked complete.
diff --git a/studio/frontend/src/features/hub/download-manager/poll-loop.ts b/studio/frontend/src/features/hub/download-manager/poll-loop.ts
index 9ae111c7a06..83203d3bc65 100644
--- a/studio/frontend/src/features/hub/download-manager/poll-loop.ts
+++ b/studio/frontend/src/features/hub/download-manager/poll-loop.ts
@@ -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
-import { carriesOverSeed } from "./adopt-rules";
+import { carriesOverSeed, seededMeasuredTransfer } from "./adopt-rules";
import { invalidateGgufVariantsCache } from "../inventory/api";
import { getHfToken } from "../stores/hf-token-store";
import { bumpInventoryVersion } from "../stores/inventory-events";
@@ -144,6 +144,7 @@ export function applyProgressUpdate(
patchJob(key, {
expectedBytes: resolved.expected,
downloadedBytes: resolved.downloadedBytes,
+ measuredTransfer: resolved.measuredTransfer,
completedBytes: resolved.completedBytes,
completeOnDisk: resolved.completeOnDisk,
fraction: resolved.fraction,
@@ -328,14 +329,22 @@ function reconcileProgressAndSpeed(
progressResp: ProgressLike,
generationChanged: boolean,
): { madeProgress: boolean } {
- const { expected, downloadedBytes, completedBytes, completeOnDisk, fraction, madeProgress } =
- resolveProgressUpdate(current, progressResp, {
- resetMonotonic: generationChanged,
- });
+ const {
+ expected,
+ downloadedBytes,
+ measuredTransfer,
+ completedBytes,
+ completeOnDisk,
+ fraction,
+ madeProgress,
+ } = resolveProgressUpdate(current, progressResp, {
+ resetMonotonic: generationChanged,
+ });
const bytesPerSec = applySpeedSample(rt, downloadedBytes, expected, Date.now());
patchJob(key, {
expectedBytes: expected,
downloadedBytes,
+ measuredTransfer,
completedBytes,
completeOnDisk,
fraction,
@@ -595,6 +604,13 @@ export async function startJob(
const seedDownloaded = carryOverSeed ? (existing?.downloadedBytes ?? 0) : 0;
const seedCompleted = carryOverSeed ? (existing?.completedBytes ?? 0) : 0;
const seedFraction = carryOverSeed ? (existing?.fraction ?? 0) : 0;
+ // Whatever the counters mean, they keep meaning it. Seeding the bytes without
+ // this said "measured" for a figure the poll only held, which is the
+ // "0 B left" the guard exists to stop.
+ const seedMeasuredTransfer = seededMeasuredTransfer(
+ carryOverSeed,
+ existing?.measuredTransfer,
+ );
// An adopted job never called apiStart, so it learns the run's generation from
// the probe (or persisted value) to scope a later cancel to this exact run.
const seedGeneration = opts.adopt
@@ -637,6 +653,9 @@ export async function startJob(
...(adopted.cancelTransport
? { cancelTransport: adopted.cancelTransport }
: {}),
+ ...(seedMeasuredTransfer !== undefined
+ ? { measuredTransfer: seedMeasuredTransfer }
+ : {}),
...(Number.isSafeInteger(seedGeneration)
? { serverGeneration: seedGeneration }
: {}),
diff --git a/studio/frontend/src/features/hub/download-manager/progress-reconcile.ts b/studio/frontend/src/features/hub/download-manager/progress-reconcile.ts
index c5aadb97c45..fd6d5958776 100644
--- a/studio/frontend/src/features/hub/download-manager/progress-reconcile.ts
+++ b/studio/frontend/src/features/hub/download-manager/progress-reconcile.ts
@@ -38,6 +38,7 @@ export function resolveProgressUpdate(
): {
expected: number;
downloadedBytes: number;
+ measuredTransfer: boolean;
completedBytes: number;
completeOnDisk: boolean;
fraction: number;
@@ -76,11 +77,16 @@ export function resolveProgressUpdate(
// the movement it needs to publish a speed or an ETA. Only a zero is ignored,
// so every real change -- up or down -- still lands on the next poll.
const reportedDownloaded = finiteReading(progressResp.downloaded_bytes);
- const downloadedBytes = resetMonotonic
+ // Whether this poll MEASURED the transfer counter or merely held the last
+ // one. A held figure is fine to draw a bar with, but it is priced against the
+ // PREVIOUS total, so a caller subtracting it from the current expectedBytes
+ // gets a remainder for a plan that no longer exists. The XET fallback reclaim
+ // is exactly that pairing: the retry's first reading is a legitimate 0 against
+ // a shrunken total, and the 3 GB held behind it wipe out a 0.5 GB remainder.
+ const measuredTransfer = resetMonotonic || reportedDownloaded > 0;
+ const downloadedBytes = measuredTransfer
? Math.max(0, reportedDownloaded)
- : reportedDownloaded > 0
- ? reportedDownloaded
- : Math.max(previousDownloadedBytes, 0);
+ : Math.max(previousDownloadedBytes, 0);
// Same rule for the finalized counter.
const measuredCompleted = resetMonotonic || reportedCompleted > 0;
const completedBytes = resetMonotonic
@@ -131,6 +137,7 @@ export function resolveProgressUpdate(
return {
expected,
downloadedBytes,
+ measuredTransfer,
completedBytes,
completeOnDisk,
fraction,
diff --git a/studio/frontend/src/features/hub/inventory/api.ts b/studio/frontend/src/features/hub/inventory/api.ts
index 43085fdc72a..132bd193bce 100644
--- a/studio/frontend/src/features/hub/inventory/api.ts
+++ b/studio/frontend/src/features/hub/inventory/api.ts
@@ -165,6 +165,8 @@ export interface GgufVariantDetail {
display_label?: string | null;
size_bytes: number;
download_size_bytes?: number;
+ /** Bytes a resume still has to fetch. Set only on a partial variant. */
+ download_remaining_bytes?: number | null;
downloaded?: boolean;
update_available?: boolean;
partial?: boolean;
diff --git a/studio/frontend/src/features/hub/lib/gguf-variant-sort.ts b/studio/frontend/src/features/hub/lib/gguf-variant-sort.ts
index 3fe9e040d97..70244bb3a56 100644
--- a/studio/frontend/src/features/hub/lib/gguf-variant-sort.ts
+++ b/studio/frontend/src/features/hub/lib/gguf-variant-sort.ts
@@ -2,6 +2,7 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import type { GgufVariantDetail } from "@/features/hub/inventory";
+import { formatBytes } from "@/features/hub/lib/format";
import { classifyGgufFit } from "@/features/hub/lib/gguf-fit";
import { ggufVariantsMatch } from "@/features/hub/lib/model-identity";
@@ -22,6 +23,29 @@ export function ggufVariantDownloadSizeBytes(
return variant.download_size_bytes ?? variant.size_bytes;
}
+type GgufVariantTransfer = Pick<
+ GgufVariantDetail,
+ "download_size_bytes" | "size_bytes" | "download_remaining_bytes" | "partial"
+>;
+
+/** What starting this variant now would transfer. On a partial that is the
+ * remainder the backend measured; everywhere else it is the full size. An
+ * unmeasured partial falls back to the total, the costlier of the two. */
+export function ggufVariantTransferBytes(variant: GgufVariantTransfer): number {
+ const total = ggufVariantDownloadSizeBytes(variant);
+ if (!variant.partial) return total;
+ const remaining = variant.download_remaining_bytes;
+ return typeof remaining === "number" && remaining >= 0 ? remaining : total;
+}
+
+/** Labelled form of the above. A partial says what is LEFT: the full size there
+ * reads as "this downloads all over again", which is only true for a one-file
+ * quant. */
+export function ggufVariantTransferLabel(variant: GgufVariantTransfer): string {
+ const label = formatBytes(ggufVariantTransferBytes(variant));
+ return variant.partial ? `${label} left` : label;
+}
+
export function ggufVariantFitRank(
variant: GgufVariantDetail,
resources: GgufVariantResources,
diff --git a/studio/frontend/tests/download-adopt-and-hydrate.test.ts b/studio/frontend/tests/download-adopt-and-hydrate.test.ts
index 924604438b8..f246c1ae938 100644
--- a/studio/frontend/tests/download-adopt-and-hydrate.test.ts
+++ b/studio/frontend/tests/download-adopt-and-hydrate.test.ts
@@ -4,6 +4,7 @@
// Two decisions the download manager makes from a single reading, both of which used to be
// wrong in the same way: treating a zero byte count as evidence of something it is not.
+import { readFileSync } from "node:fs";
import assert from "node:assert/strict";
import test from "node:test";
@@ -11,7 +12,7 @@ import { registerBundlerResolver } from "./helpers/kit.ts";
registerBundlerResolver();
-const { carriesOverSeed, idleProbeVerdict } = await import(
+const { carriesOverSeed, idleProbeVerdict, seededMeasuredTransfer } = await import(
"../src/features/hub/download-manager/adopt-rules.ts"
);
@@ -96,3 +97,33 @@ test("a scan that never happened does not retire a job", () => {
assert.equal(idleProbeVerdict(0, null, null, true), "gone");
assert.equal(idleProbeVerdict(0, null, null, undefined), "gone");
});
+
+test("the held-transfer marker travels with the counters it describes", () => {
+ // Keeping the bytes while dropping it restores undefined, which reads as
+ // measured, and the row goes back to "0 B left".
+ assert.equal(seededMeasuredTransfer(true, false), false);
+ assert.equal(seededMeasuredTransfer(true, true), true);
+ // No seed means zeroed counters, so there is no held figure to distrust.
+ assert.equal(seededMeasuredTransfer(false, false), undefined);
+ // A job that never recorded one stays unknown rather than becoming held.
+ assert.equal(seededMeasuredTransfer(true, undefined), undefined);
+});
+
+test("the adoption path actually seeds the marker onto the job", () => {
+ // The helper above is pure, so it cannot catch the seed being computed and
+ // then left off the rebuilt job, which is how the marker was lost once.
+ const src = readFileSync(
+ new URL(
+ "../src/features/hub/download-manager/poll-loop.ts",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ assert.match(
+ src,
+ /measuredTransfer:\s*seedMeasuredTransfer/,
+ "startJob computes the seeded held-transfer marker but no longer puts it on "
+ + "the job, so an adopted run restores it as undefined (measured) and "
+ + "prices the retry against the dead run's bytes",
+ );
+});
diff --git a/studio/frontend/tests/download-held-transfer-persistence.test.ts b/studio/frontend/tests/download-held-transfer-persistence.test.ts
new file mode 100644
index 00000000000..d9f48714f69
--- /dev/null
+++ b/studio/frontend/tests/download-held-transfer-persistence.test.ts
@@ -0,0 +1,119 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// An XET-to-HTTP reclaim keeps the same generation, so the first reading for the
+// new run holds the dead run's downloadedBytes beside a shrunken expectedBytes,
+// and measuredTransfer marks it as held. If the flag does not survive a reload,
+// the restored job carries the stale bytes with the guard reading "measured"
+// again and the row reads "0 B left" until the first poll repairs it.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import type { ManagedDownload } from "../src/features/hub/download-manager/download-manager-types.ts";
+import {
+ installLocalStorageFake,
+ registerBundlerResolver,
+} from "./helpers/kit.ts";
+
+registerBundlerResolver();
+const { store } = installLocalStorageFake();
+
+const PERSIST_KEY = "unsloth.studio.downloads";
+let flushPersistedState: (() => void) | undefined;
+Object.assign(globalThis.window, {
+ addEventListener: (type: string, listener: () => void) => {
+ if (type === "pagehide") flushPersistedState = listener;
+ },
+});
+
+function persistedJob(repoId: string, extra: Record<string, unknown> = {}) {
+ return {
+ key: `model:${repoId}`,
+ kind: "model",
+ repoId,
+ variant: "Q4_K_M",
+ state: "running",
+ downloadedBytes: 3_000_000_000,
+ completedBytes: 0,
+ expectedBytes: 500_000_000,
+ fraction: 0.1,
+ error: null,
+ startedAt: 1,
+ ...extra,
+ };
+}
+
+store.set(
+ PERSIST_KEY,
+ JSON.stringify({
+ state: {
+ jobs: {
+ held: persistedJob("org/held-model", { measuredTransfer: false }),
+ measured: persistedJob("org/measured-model", {
+ measuredTransfer: true,
+ }),
+ unpolled: persistedJob("org/unpolled-model"),
+ },
+ conflicts: {},
+ },
+ version: 2,
+ }),
+);
+
+const { getState, jobKeyOf, putJob } = await import(
+ "../src/features/hub/download-manager/download-manager-state.ts"
+);
+
+test("a held reading is still held after the reload that carried it", () => {
+ const jobs = getState().jobs;
+ assert.equal(
+ jobs[jobKeyOf("model", "org/held-model", "Q4_K_M")]?.measuredTransfer,
+ false,
+ );
+});
+
+test("a measured reading restores as measured", () => {
+ const jobs = getState().jobs;
+ assert.equal(
+ jobs[jobKeyOf("model", "org/measured-model", "Q4_K_M")]?.measuredTransfer,
+ true,
+ );
+});
+
+test("a current record with no marker still means never polled", () => {
+ // Undefined, not false: written since the field existed, so its absence is
+ // the record saying it never polled rather than saying nothing.
+ const jobs = getState().jobs;
+ assert.equal(
+ jobs[jobKeyOf("model", "org/unpolled-model", "Q4_K_M")]?.measuredTransfer,
+ undefined,
+ );
+});
+
+test("the held marker is written out with the job", () => {
+ const key = jobKeyOf("model", "org/writeback-model", "Q4_K_M");
+ const job: ManagedDownload = {
+ key,
+ kind: "model",
+ repoId: "org/writeback-model",
+ variant: "Q4_K_M",
+ state: "running",
+ downloadedBytes: 3_000_000_000,
+ completedBytes: 0,
+ completeOnDisk: false,
+ expectedBytes: 500_000_000,
+ fraction: 0.1,
+ bytesPerSec: 0,
+ error: null,
+ startedAt: 2,
+ measuredTransfer: false,
+ };
+
+ putJob(job);
+ assert.ok(flushPersistedState);
+ flushPersistedState();
+
+ const persisted = JSON.parse(store.get(PERSIST_KEY) ?? "null");
+ assert.equal(persisted.state.jobs[key].measuredTransfer, false);
+});
diff --git a/studio/frontend/tests/download-legacy-measured-migration.test.ts b/studio/frontend/tests/download-legacy-measured-migration.test.ts
new file mode 100644
index 00000000000..71e2e1941cf
--- /dev/null
+++ b/studio/frontend/tests/download-legacy-measured-migration.test.ts
@@ -0,0 +1,80 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// A record written before measuredTransfer existed cannot say whether its byte
+// counters were measured, so an absent marker there is not the "never polled"
+// it means in a current record. The migration reads a legacy record that already
+// carries counters as held, so an upgrade landing mid-reclaim does not restore
+// the dead run's bytes as measured.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ installLocalStorageFake,
+ registerBundlerResolver,
+} from "./helpers/kit.ts";
+
+registerBundlerResolver();
+const { store } = installLocalStorageFake();
+
+const PERSIST_KEY = "unsloth.studio.downloads";
+let flushPersistedState: (() => void) | undefined;
+Object.assign(globalThis.window, {
+ addEventListener: (type: string, listener: () => void) => {
+ if (type === "pagehide") flushPersistedState = listener;
+ },
+});
+
+function legacyJob(repoId: string, downloadedBytes: number) {
+ return {
+ key: `model:${repoId}`,
+ kind: "model",
+ repoId,
+ variant: "Q4_K_M",
+ state: "running",
+ downloadedBytes,
+ completedBytes: 0,
+ expectedBytes: 500_000_000,
+ fraction: 0.1,
+ error: null,
+ startedAt: 1,
+ };
+}
+
+store.set(
+ PERSIST_KEY,
+ JSON.stringify({
+ state: {
+ jobs: {
+ carried: legacyJob("org/carried-model", 3_000_000_000),
+ fresh: legacyJob("org/fresh-model", 0),
+ },
+ conflicts: {},
+ },
+ // The version written before the marker existed.
+ version: 1,
+ }),
+);
+
+const { getState, jobKeyOf } = await import(
+ "../src/features/hub/download-manager/download-manager-state.ts"
+);
+
+test("a legacy record carrying counters is restored as held", () => {
+ const jobs = getState().jobs;
+ assert.equal(
+ jobs[jobKeyOf("model", "org/carried-model", "Q4_K_M")]?.measuredTransfer,
+ false,
+ );
+});
+
+test("a legacy record with nothing counted stays unknown", () => {
+ // No held figure to distrust, so undefined is the honest answer and the
+ // first poll writes the real one.
+ const jobs = getState().jobs;
+ assert.equal(
+ jobs[jobKeyOf("model", "org/fresh-model", "Q4_K_M")]?.measuredTransfer,
+ undefined,
+ );
+});
diff --git a/studio/frontend/tests/download-progress-reconcile.test.ts b/studio/frontend/tests/download-progress-reconcile.test.ts
index c3d2a126e7d..565ddb95982 100644
--- a/studio/frontend/tests/download-progress-reconcile.test.ts
+++ b/studio/frontend/tests/download-progress-reconcile.test.ts
@@ -328,3 +328,35 @@ test("a new generation resets the fraction, not only the bytes", () => {
const held = resolveProgressUpdate(job({ fraction: 0.99 }), emptyReading());
assert.equal(held.fraction, 0.99);
});
+
+test("a held transfer reading is reported as held, not as a measurement", () => {
+ // The card may keep drawing the last figure, but a consumer that subtracts it
+ // from the CURRENT expectedBytes is mixing two plans: after an XET-to-HTTP
+ // reclaim the retry's first reading is a legitimate zero against a shrunken
+ // total, and the bytes held behind it belong to the previous, larger one.
+ const held = resolveProgressUpdate(
+ job({ downloadedBytes: 3 * GB, completedBytes: 3 * GB }),
+ emptyReading({ expected_bytes: GB / 2 }),
+ );
+
+ assert.equal(held.measuredTransfer, false);
+ assert.equal(held.downloadedBytes, 3 * GB);
+ assert.equal(held.expected, GB / 2);
+
+ // The next poll that carries bytes is a measurement again.
+ const measured = resolveProgressUpdate(
+ job({ downloadedBytes: 3 * GB, completedBytes: 3 * GB }),
+ emptyReading({ downloaded_bytes: GB / 10, expected_bytes: GB / 2 }),
+ );
+
+ assert.equal(measured.measuredTransfer, true);
+ assert.equal(measured.downloadedBytes, GB / 10);
+
+ // A generation bump measures the new run's counter outright, zero included.
+ const reset = resolveProgressUpdate(job({ downloadedBytes: 3 * GB }), emptyReading(), {
+ resetMonotonic: true,
+ });
+
+ assert.equal(reset.measuredTransfer, true);
+ assert.equal(reset.downloadedBytes, 0);
+});
diff --git a/studio/frontend/tests/gguf-live-remaining-label.test.ts b/studio/frontend/tests/gguf-live-remaining-label.test.ts
new file mode 100644
index 00000000000..f8e934ed21a
--- /dev/null
+++ b/studio/frontend/tests/gguf-live-remaining-label.test.ts
@@ -0,0 +1,250 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// A row that is downloading says "N left", so N has to follow the transfer. The live overlay
+// only carried the expected size, leaving the label on whatever the one-time variant fetch had
+// measured -- or on the full total for a download that started after it, which reads as no
+// progress at all.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { registerBundlerResolver } from "./helpers/kit.ts";
+
+registerBundlerResolver();
+
+const { applyLiveGgufVariantStates, createLiveGgufVariantStatesSelector } =
+ await import("../src/features/hub/catalog/gguf-live-variant-states.ts");
+const { ggufVariantTransferLabel } = await import(
+ "../src/features/hub/lib/gguf-variant-sort.ts"
+);
+
+const GB = 1000 ** 3;
+
+const variant = (over: Record<string, unknown> = {}) => ({
+ quant: "Q4_K_M",
+ filename: "model-Q4_K_M.gguf",
+ size_bytes: 4 * GB,
+ download_size_bytes: 4 * GB,
+ download_remaining_bytes: null,
+ downloaded: false,
+ partial: false,
+ ...over,
+});
+
+const live = (over: Record<string, unknown> = {}) =>
+ new Map([
+ [
+ "q4_k_m",
+ {
+ state: "running",
+ expectedBytes: 4 * GB,
+ transferredBytes: 3 * GB,
+ measuredTransfer: true,
+ startedAt: 0,
+ ...over,
+ },
+ ],
+ ]);
+
+test("a running download prices the remainder from its own progress", () => {
+ const [row] = applyLiveGgufVariantStates([variant()], live() as never);
+
+ assert.equal(row.partial, true);
+ assert.equal(row.download_remaining_bytes, 1 * GB);
+ assert.equal(ggufVariantTransferLabel(row), "1.0 GB left");
+});
+
+test("progress replaces the remainder the one-time fetch measured", () => {
+ // The fetch saw 3.5 GB outstanding; 3 GB have since arrived.
+ const [row] = applyLiveGgufVariantStates(
+ [variant({ partial: true, download_remaining_bytes: 3.5 * GB })],
+ live() as never,
+ );
+
+ assert.equal(row.download_remaining_bytes, 1 * GB);
+});
+
+test("a job that has moved no bytes keeps the measured remainder", () => {
+ const [row] = applyLiveGgufVariantStates(
+ [variant({ partial: true, download_remaining_bytes: 3.5 * GB })],
+ live({ transferredBytes: 0 }) as never,
+ );
+
+ assert.equal(row.download_remaining_bytes, 3.5 * GB);
+});
+
+test("the remainder never goes negative when progress overruns the estimate", () => {
+ const [row] = applyLiveGgufVariantStates(
+ [variant()],
+ live({ transferredBytes: 5 * GB }) as never,
+ );
+
+ assert.equal(row.download_remaining_bytes, 0);
+});
+
+test("a completed download is left alone, so no row reads as partial", () => {
+ const [row] = applyLiveGgufVariantStates(
+ [variant({ partial: true, download_remaining_bytes: 3.5 * GB })],
+ live({ state: "complete", transferredBytes: 4 * GB }) as never,
+ );
+
+ assert.equal(row.downloaded, true);
+ assert.equal(row.partial, false);
+ assert.equal(ggufVariantTransferLabel(row), "4.0 GB");
+});
+
+test("a cancelled job keeps the remainder the backend measured", () => {
+ // Progress is not reusable bytes: from huggingface_hub 1.18 the partial is
+ // process-unique and unlinked in a finally, so an interrupted in-file transfer
+ // is refetched whole. Subtracting the dead job's 17 GB reported "1.0 GB left"
+ // for a resume that still has all 18 GB to fetch.
+ for (const state of ["cancelled", "error"]) {
+ const [row] = applyLiveGgufVariantStates(
+ [
+ variant({
+ size_bytes: 18 * GB,
+ download_size_bytes: 18 * GB,
+ partial: true,
+ download_remaining_bytes: 18 * GB,
+ }),
+ ],
+ live({
+ state,
+ expectedBytes: 18 * GB,
+ transferredBytes: 17 * GB,
+ }) as never,
+ );
+
+ assert.equal(row.partial, true);
+ assert.equal(row.download_remaining_bytes, 18 * GB);
+ assert.equal(ggufVariantTransferLabel(row), "18 GB left");
+ }
+});
+
+test("an XET fallback does not price the retry against the dead run's bytes", () => {
+ // The XET attempt finalized 3 GB of a 3.5 GB quant, then fell back to HTTP.
+ // The reclaim recomputes completed_baseline_bytes from disk, so the retry
+ // reports a 0.5 GB total with 0.1 GB moved and completed_bytes 0. Taking the
+ // max against the held 3 GB read "0 B left" with 0.4 GB still to fetch.
+ const select = createLiveGgufVariantStatesSelector("unsloth/model-GGUF");
+ const states = select({
+ jobs: {
+ "model:unsloth/model-GGUF:Q4_K_M": {
+ kind: "model",
+ repoId: "unsloth/model-GGUF",
+ variant: "Q4_K_M",
+ state: "running",
+ expectedBytes: 0.5 * GB,
+ downloadedBytes: 0.1 * GB,
+ completedBytes: 3 * GB,
+ startedAt: 0,
+ },
+ },
+ } as never);
+
+ const [row] = applyLiveGgufVariantStates(
+ [
+ variant({
+ size_bytes: 3.5 * GB,
+ download_size_bytes: 3.5 * GB,
+ partial: true,
+ download_remaining_bytes: 3.5 * GB,
+ }),
+ ],
+ states as never,
+ );
+
+ assert.equal(row.download_remaining_bytes, 0.4 * GB);
+});
+
+test("a retry that has not measured a byte yet keeps the backend remainder", () => {
+ // The reading right after the reclaim, before the HTTP run moves anything: a
+ // real downloaded_bytes 0 against a 0.5 GB total, behind which
+ // resolveProgressUpdate holds the dead run's 3 GB. Pricing the remainder off
+ // that held figure read "0 B left" with all 0.5 GB still to fetch.
+ const select = createLiveGgufVariantStatesSelector("unsloth/model-GGUF");
+ const states = select({
+ jobs: {
+ "model:unsloth/model-GGUF:Q4_K_M": {
+ kind: "model",
+ repoId: "unsloth/model-GGUF",
+ variant: "Q4_K_M",
+ state: "running",
+ expectedBytes: 0.5 * GB,
+ downloadedBytes: 3 * GB,
+ measuredTransfer: false,
+ completedBytes: 3 * GB,
+ startedAt: 0,
+ },
+ },
+ } as never);
+
+ const [row] = applyLiveGgufVariantStates(
+ [
+ variant({
+ size_bytes: 3.5 * GB,
+ download_size_bytes: 3.5 * GB,
+ partial: true,
+ download_remaining_bytes: 0.5 * GB,
+ }),
+ ],
+ states as never,
+ );
+
+ assert.equal(row.download_remaining_bytes, 0.5 * GB);
+ assert.equal(ggufVariantTransferLabel(row), "500 MB left");
+});
+
+test("the retry prices itself off the first reading that does measure", () => {
+ const select = createLiveGgufVariantStatesSelector("unsloth/model-GGUF");
+ const states = select({
+ jobs: {
+ "model:unsloth/model-GGUF:Q4_K_M": {
+ kind: "model",
+ repoId: "unsloth/model-GGUF",
+ variant: "Q4_K_M",
+ state: "running",
+ expectedBytes: 0.5 * GB,
+ downloadedBytes: 0.1 * GB,
+ measuredTransfer: true,
+ completedBytes: 0,
+ startedAt: 0,
+ },
+ },
+ } as never);
+
+ const [row] = applyLiveGgufVariantStates(
+ [
+ variant({
+ size_bytes: 3.5 * GB,
+ download_size_bytes: 3.5 * GB,
+ partial: true,
+ download_remaining_bytes: 0.5 * GB,
+ }),
+ ],
+ states as never,
+ );
+
+ assert.equal(row.download_remaining_bytes, 0.4 * GB);
+});
+
+test("a variant with no live job is returned untouched", () => {
+ const original = variant({ partial: true, download_remaining_bytes: 2 * GB });
+ const [row] = applyLiveGgufVariantStates([original], new Map() as never);
+
+ assert.equal(row, original);
+});
+
+test("a reused mmproj does not come back as bytes still to fetch", () => {
+ // snapshot_progress nets the baseline out of both of the job's counters, so
+ // 5 GB plan - 1 GB already on disk = a 4 GB job, 1 GB of which has arrived.
+ const [row] = applyLiveGgufVariantStates(
+ [variant({ size_bytes: 5 * GB, download_size_bytes: 5 * GB })],
+ live({ expectedBytes: 4 * GB, transferredBytes: 1 * GB }) as never,
+ );
+
+ assert.equal(row.download_remaining_bytes, 3 * GB);
+ // The catalog total still drives the size the row reports, untouched.
+ assert.equal(row.download_size_bytes, 5 * GB);
+});
diff --git a/studio/frontend/tests/gguf-variant-transfer-size.test.ts b/studio/frontend/tests/gguf-variant-transfer-size.test.ts
new file mode 100644
index 00000000000..9cee9930cd8
--- /dev/null
+++ b/studio/frontend/tests/gguf-variant-transfer-size.test.ts
@@ -0,0 +1,78 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// A partial row used to print the variant total next to its resume button, so continuing a
+// sharded download that was most of the way there still read "56 GB" and looked like the whole
+// model coming down again.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { registerBundlerResolver } from "./helpers/kit.ts";
+
+registerBundlerResolver();
+
+const { ggufVariantTransferBytes, ggufVariantTransferLabel } = await import(
+ "../src/features/hub/lib/gguf-variant-sort.ts"
+);
+
+const GB = 1000 ** 3;
+
+test("a partial is priced by what is left, not by the variant total", () => {
+ const variant = {
+ size_bytes: 56 * GB,
+ download_size_bytes: 56 * GB,
+ download_remaining_bytes: 16 * GB,
+ partial: true,
+ };
+
+ assert.equal(ggufVariantTransferBytes(variant), 16 * GB);
+ assert.equal(ggufVariantTransferLabel(variant), "16 GB left");
+});
+
+test("a one-file quant still prices the whole thing, and says so", () => {
+ // Nothing to keep: the interrupted file restarts, so "left" is the full size.
+ const variant = {
+ size_bytes: 18 * GB,
+ download_size_bytes: 18 * GB,
+ download_remaining_bytes: 18 * GB,
+ partial: true,
+ };
+
+ assert.equal(ggufVariantTransferLabel(variant), "18 GB left");
+});
+
+test("a variant that is not partial shows its plain size", () => {
+ const variant = {
+ size_bytes: 18 * GB,
+ download_size_bytes: 18 * GB,
+ download_remaining_bytes: null,
+ partial: false,
+ };
+
+ assert.equal(ggufVariantTransferBytes(variant), 18 * GB);
+ assert.equal(ggufVariantTransferLabel(variant), "18 GB");
+});
+
+test("an unmeasured partial falls back to the total, never to a smaller guess", () => {
+ for (const remaining of [null, undefined, -1]) {
+ const variant = {
+ size_bytes: 18 * GB,
+ download_size_bytes: 18 * GB,
+ download_remaining_bytes: remaining,
+ partial: true,
+ };
+ assert.equal(ggufVariantTransferBytes(variant), 18 * GB);
+ }
+});
+
+test("a partial with nothing left reads as zero rather than the total", () => {
+ const variant = {
+ size_bytes: 18 * GB,
+ download_size_bytes: 18 * GB,
+ download_remaining_bytes: 0,
+ partial: true,
+ };
+
+ assert.equal(ggufVariantTransferBytes(variant), 0);
+});