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.

fix training start progress and metadata-only dataset caches (#8384)

Maheswar Kumarc9d92df12d2e
diff --git a/studio/backend/hub/services/datasets/cache_inventory.py b/studio/backend/hub/services/datasets/cache_inventory.py
index 34a9a726bbe..9097ce98f1d 100644
--- a/studio/backend/hub/services/datasets/cache_inventory.py
+++ b/studio/backend/hub/services/datasets/cache_inventory.py
@@ -14,10 +14,11 @@ from fastapi import HTTPException
from loggers import get_logger
from hub.services import resolve_destructive_repo_ids
-from hub.services.datasets import downloads
+from hub.services.datasets import downloads, local_options
from hub.utils import download_manifest
from hub.utils import inventory_scan as hf_cache_scan
from hub.utils.dataset_cache import (
+ dataset_snapshot_from_cache_path,
hf_datasets_cache_roots,
processed_dataset_cache_has_artifacts,
)
@@ -109,6 +110,166 @@ def _hub_dataset_snapshot_count(path: Path) -> int:
return 0
+# anything not named here counts as payload, so unknown formats are never read as an empty
+# snapshot. the windows names are spelled out because huggingface_hub only added them after 0.36;
+# the data-file names come from local_options so this and the resolver cannot drift apart.
+_DATASET_NON_PAYLOAD_FILENAMES = (
+ frozenset(
+ {
+ ".ds_store",
+ ".gitattributes",
+ ".huggingface.yaml",
+ "desktop.ini",
+ "license",
+ "license.md",
+ "license.txt",
+ "thumbs.db",
+ }
+ )
+ | {name.lower() for name in hf_cache_scan._CACHE_ENTRIES_TO_IGNORE}
+ | {name.lower() for name in local_options._IGNORED_DATA_FILENAMES}
+)
+
+
+# suffixes no loader can turn into rows: none is in `datasets`' extension map, and a script also
+# needs `trust_remote_code`, which no load path here passes and `datasets>=4` dropped.
+_DATASET_NON_PAYLOAD_SUFFIXES = frozenset({".cff", ".md", ".py", ".pyc"})
+
+
+def _is_payload_dir(name: str) -> bool:
+ # the only rule `datasets` applies to a directory, which also covers a Mac zip's `__MACOSX`.
+ # the metadata FILE names must not be applied here: `license/train.parquet` loads fine, and
+ # pruning that subtree hid the dataset from On Device.
+ return not name.startswith(".") and not name.startswith("__")
+
+
+def _is_payload_name(name: str) -> bool:
+ # as above, plus the metadata names: AppleDouble sidecars, every dotfile the list does not
+ # enumerate, and the cards and licences a cancelled download leaves behind.
+ if not _is_payload_dir(name):
+ return False
+ return name.lower() not in _DATASET_NON_PAYLOAD_FILENAMES
+
+
+def _is_payload_file(name: str) -> bool:
+ if not _is_payload_name(name):
+ return False
+ # the resolver's suffix rule, which walks the whole chain and drops a trailing compression
+ # suffix: `train.parquet.backup` is still parquet, `data.py.gz` is still a script.
+ suffix = local_options._data_suffix(name)
+ return suffix is None or suffix.lower() not in _DATASET_NON_PAYLOAD_SUFFIXES
+
+
+def _is_present_payload_file(path: Path) -> bool:
+ # existence is not enough. `_empty_payload` covers both shapes that look like payload and
+ # are not: a zero-byte file, and a `blobs/` link whose blob was pruned.
+ if not _is_payload_file(path.name):
+ return False
+ if local_options._empty_payload(path):
+ return False
+ # bytes are not rows: `_rowless` probes a header-only csv or a `[]` json, reading a short
+ # head for those two builders only. it drops the file, not the snapshot, as datasets does.
+ module = local_options._file_module(path.name)
+ return module is None or not local_options._rowless(path, path.name, module)
+
+
+def _snapshot_holds_payload(snapshot: Path) -> Optional[bool]:
+ """True/False for this snapshot, or None when a subtree could not be read.
+
+ None is not False: `os.walk` swallows `scandir` errors unless `onerror` is given, so a cache
+ on an unavailable mount would read as empty and hide a dataset that was merely uninspectable.
+ """
+ unreadable = False
+
+ def _note(_exc: OSError) -> None:
+ nonlocal unreadable
+ unreadable = True
+
+ # roots still to walk, and every directory already walked or queued by resolved path. a
+ # junction pointing at its own ancestor resolves back inside the snapshot, so containment
+ # alone leaves `data/loop/loop/...` descending until the path length gives out.
+ seen: set[Path] = set()
+ pending: list[Path] = []
+
+ def _book(entry: Path) -> Optional[Path]:
+ """The resolved path, booked as visited, or None when already seen or unresolvable."""
+ nonlocal unreadable
+ try:
+ resolved = entry.resolve(strict = True)
+ except (OSError, RuntimeError, ValueError):
+ unreadable = True
+ return None
+ if resolved in seen:
+ return None
+ seen.add(resolved)
+ return resolved
+
+ start = _book(snapshot)
+ if start is None:
+ return None
+ pending.append(start)
+
+ try:
+ while pending:
+ root = pending.pop()
+ for directory, dirnames, filenames in os.walk(root, followlinks = False, onerror = _note):
+ base = Path(directory)
+ kept = []
+ for name in dirnames:
+ # nothing under a hidden or `__`-prefixed dir can supply rows, so
+ # `.hidden/notes.txt` must not clear `partial`.
+ if not _is_payload_dir(name):
+ continue
+ entry = base / name
+ # containment, not a link-type test: `is_symlink()` is false for a Windows
+ # junction and `is_junction()` postdates 3.12, which this still supports, so
+ # only comparing resolved paths catches every redirect on every runtime.
+ try:
+ redirected = not entry.resolve(strict = True).is_relative_to(root)
+ linked = entry.is_symlink()
+ except (OSError, RuntimeError, ValueError):
+ unreadable = True
+ continue
+ # walked as a root of its own, not taken as proof: migrated caches keep
+ # their data behind a redirect, and a stale one holds nothing.
+ if redirected:
+ target = _book(entry)
+ if target is not None:
+ pending.append(target)
+ continue
+ # a symlink back inside this root is skipped: the walk never descends one,
+ # and booking its target would prune the real directory whenever `alias` is
+ # listed before `data`. a junction reports False here, hence the visited set.
+ if linked:
+ continue
+ if _book(entry) is None:
+ continue
+ kept.append(name)
+ dirnames[:] = kept
+ if any(_is_present_payload_file(base / name) for name in filenames):
+ return True
+ except OSError:
+ return None
+ return None if unreadable else False
+
+
+def _raw_dataset_cache_has_data(repo_id: str, cache_path: Path) -> bool:
+ """Whether the snapshot a load would actually open holds anything beyond metadata.
+
+ A cancelled download can leave just the card, which every structural check reads as complete,
+ so the repo was offered On Device and then failed in load_dataset().
+
+ Only the revision `dataset_snapshot_from_cache_path` selects counts, since that is what
+ `training_dataset_cache_pin` pins: a payload-bearing sibling revision would still not be the
+ one the run opens.
+ """
+ snapshot = dataset_snapshot_from_cache_path(str(cache_path), repo_id)
+ if snapshot is None:
+ return False
+ # True, or unreadable -- and an uninspectable cache is not an empty one.
+ return _snapshot_holds_payload(snapshot) is not False
+
+
def _scan_hub_dataset_cache_dirs() -> list[dict]:
"""Fallback scanner: ``scan_cache_dir()`` skips repos when one cache entry is partially corrupt, so this keeps On Device matching disk."""
seen_lower: dict[str, dict] = {}
@@ -128,14 +289,16 @@ def _scan_hub_dataset_cache_dirs() -> list[dict]:
continue
key = repo_id.lower()
existing = seen_lower.get(key)
- snapshot_partial = _hub_dataset_snapshot_count(
- entry
- ) == 0 or hf_cache_scan.is_snapshot_partial("dataset", repo_id, entry)
+ snapshot_partial = (
+ _hub_dataset_snapshot_count(entry) == 0
+ or hf_cache_scan.is_snapshot_partial("dataset", repo_id, entry)
+ or not _raw_dataset_cache_has_data(repo_id, entry)
+ )
row = {
"repo_id": repo_id,
"size_bytes": size_bytes,
"cache_path": str(entry.resolve()),
- # snapshot_count == 0 catches blobs-but-no-snapshot; is_snapshot_partial adds row-state checks.
+ # blobs-but-no-snapshot, then row state, then a card-only snapshot.
"partial": snapshot_partial,
"partial_transport": (
hf_cache_scan.partial_transport_for(
@@ -283,7 +446,7 @@ def _scan_hf_dataset_caches() -> list[dict]:
"dataset",
repo_info.repo_id,
cache_dir,
- )
+ ) or not _raw_dataset_cache_has_data(repo_info.repo_id, cache_dir)
row = {
"repo_id": repo_info.repo_id,
"size_bytes": total_size,
@@ -321,14 +484,18 @@ def _scan_hf_dataset_caches() -> list[dict]:
for row in _scan_processed_dataset_caches():
key = row["repo_id"].lower()
existing = seen_lower.get(key)
- if existing is None or (bool(existing.get("partial")) and not bool(row.get("partial"))):
+ if existing is None:
seen_lower[key] = row
- else:
- existing["size_bytes"] = max(existing["size_bytes"], row["size_bytes"])
- # Preserve the raw path for scoped deletion and expose the processed Arrow path separately.
- if row.get("processed_cache"):
- existing["processed_cache"] = True
- existing["load_cache_path"] = row.get("cache_path")
+ continue
+ existing["size_bytes"] = max(existing["size_bytes"], row["size_bytes"])
+ # Preserve the raw path for scoped deletion and expose the processed Arrow path separately.
+ if row.get("processed_cache"):
+ existing["processed_cache"] = True
+ existing["load_cache_path"] = row.get("cache_path")
+ # annotating rather than replacing keeps the hub cache_path that scoped deletion needs.
+ if existing.get("partial") and not row.get("partial"):
+ existing["partial"] = False
+ existing["partial_transport"] = None
for row in _scan_app_processed_dataset_caches():
key = row["repo_id"].lower()
existing = seen_lower.get(key)
diff --git a/studio/backend/hub/tests/test_dataset_services.py b/studio/backend/hub/tests/test_dataset_services.py
index 38dd96d93a6..1362871eb90 100644
--- a/studio/backend/hub/tests/test_dataset_services.py
+++ b/studio/backend/hub/tests/test_dataset_services.py
@@ -2,6 +2,7 @@
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import asyncio
+import os
import sys
from pathlib import Path
from types import SimpleNamespace
@@ -10,7 +11,13 @@ import pytest
from fastapi import HTTPException
from hub.schemas.datasets import CheckFormatRequest, LocalDatasetItem
-from hub.services.datasets import cache_inventory, downloads, formatting, local
+from hub.services.datasets import (
+ cache_inventory,
+ downloads,
+ formatting,
+ local,
+ local_options,
+)
from hub.utils import (
dataset_processed_cache,
download_manifest,
@@ -60,6 +67,7 @@ def test_dataset_cache_scan_merges_raw_and_processed_rows(monkeypatch):
"is_snapshot_partial",
lambda _repo_type, _repo_id, _cache_dir: False,
)
+ monkeypatch.setattr(cache_inventory, "_raw_dataset_cache_has_data", lambda *_args: True)
monkeypatch.setattr(
cache_inventory,
"_scan_hub_dataset_cache_dirs",
@@ -107,6 +115,7 @@ def test_dataset_cache_scan_attaches_app_bytes_without_replacing_raw_path(monkey
"is_snapshot_partial",
lambda *_args, **_kwargs: False,
)
+ monkeypatch.setattr(cache_inventory, "_raw_dataset_cache_has_data", lambda *_args: True)
monkeypatch.setattr(cache_inventory, "_scan_hub_dataset_cache_dirs", lambda: [])
monkeypatch.setattr(cache_inventory, "_scan_processed_dataset_caches", lambda: [])
monkeypatch.setattr(
@@ -140,6 +149,432 @@ def test_dataset_cache_scan_attaches_app_bytes_without_replacing_raw_path(monkey
]
+def _dataset_snapshot(monkeypatch, tmp_path: Path, filenames: tuple[str, ...]) -> Path:
+ hub_cache = tmp_path / "hub"
+ repo_root = hub_cache / "datasets--Org--Data"
+ snapshot = repo_root / "snapshots" / "abc"
+ snapshot.mkdir(parents = True)
+ for filename in filenames:
+ target = snapshot / filename
+ target.parent.mkdir(parents = True, exist_ok = True)
+ target.write_bytes(b"x")
+ monkeypatch.setattr(hf_cache_state, "hf_cache_roots", lambda **kw: [hub_cache])
+ return repo_root
+
+
+def test_raw_dataset_cache_has_data_rejects_a_metadata_only_snapshot(monkeypatch, tmp_path):
+ repo_root = _dataset_snapshot(
+ monkeypatch,
+ tmp_path,
+ (".gitattributes", "README.md", "dataset_infos.json", "LICENSE"),
+ )
+
+ assert cache_inventory._raw_dataset_cache_has_data("Org/Data", repo_root) is False
+
+
+def test_raw_dataset_cache_has_data_ignores_os_clutter(monkeypatch, tmp_path):
+ """Opening the cache dir in Finder or Explorer drops a `.DS_Store`/`Thumbs.db` beside the
+ card, which must not read as payload."""
+ repo_root = _dataset_snapshot(
+ monkeypatch,
+ tmp_path,
+ ("README.md", ".DS_Store", "Thumbs.db"),
+ )
+
+ assert cache_inventory._raw_dataset_cache_has_data("Org/Data", repo_root) is False
+
+
+def test_raw_dataset_cache_has_data_finds_nested_payload_of_any_format(monkeypatch, tmp_path):
+ """Image and audio repos ship no extension the app keeps a format list for, so the check
+ asks whether anything beyond metadata is present rather than matching known formats."""
+ repo_root = _dataset_snapshot(
+ monkeypatch,
+ tmp_path,
+ ("README.md", "data/train-00000-of-00001.parquet", "data/train/0001.png"),
+ )
+
+ assert cache_inventory._raw_dataset_cache_has_data("Org/Data", repo_root) is True
+
+
+def test_raw_dataset_cache_has_data_ignores_appledouble_sidecars(monkeypatch, tmp_path):
+ """A snapshot carried through a Mac zip picks up `._name` sidecars and a `__MACOSX`
+ tree. `datasets` skips dotted names and `__`-prefixed dirs when it resolves data files,
+ so counting them as payload offered a card-only snapshot On Device again."""
+ repo_root = _dataset_snapshot(
+ monkeypatch,
+ tmp_path,
+ ("README.md", "._README.md", "__MACOSX/._README.md"),
+ )
+
+ assert cache_inventory._raw_dataset_cache_has_data("Org/Data", repo_root) is False
+
+
+def test_raw_dataset_cache_has_data_ignores_a_citation_and_a_loading_script(monkeypatch, tmp_path):
+ """Neither suffix is in `datasets`' extension map, and a script also needs
+ `trust_remote_code`, which no load path here passes and `datasets>=4` removed."""
+ repo_root = _dataset_snapshot(
+ monkeypatch,
+ tmp_path,
+ ("README.md", "CITATION.cff", "data.py", "docs/usage.md"),
+ )
+
+ assert cache_inventory._raw_dataset_cache_has_data("Org/Data", repo_root) is False
+
+
+def test_raw_dataset_cache_has_data_counts_payload_beside_a_loading_script(monkeypatch, tmp_path):
+ """The suffix rule is for files only: a script beside real data is still payload."""
+ repo_root = _dataset_snapshot(
+ monkeypatch,
+ tmp_path,
+ ("README.md", "data.py", "data/train.parquet"),
+ )
+
+ assert cache_inventory._raw_dataset_cache_has_data("Org/Data", repo_root) is True
+
+
+def test_raw_dataset_cache_has_data_counts_payload_under_a_metadata_named_dir(
+ monkeypatch, tmp_path
+):
+ """`datasets` excludes only hidden and `__`-prefixed dirs, so `license/train.parquet`
+ resolves; applying the file list to the directory hid the dataset from On Device."""
+ repo_root = _dataset_snapshot(
+ monkeypatch,
+ tmp_path,
+ ("README.md", "license/train.parquet"),
+ )
+
+ assert cache_inventory._raw_dataset_cache_has_data("Org/Data", repo_root) is True
+
+
+def test_raw_dataset_cache_has_data_does_not_loop_on_a_link_to_an_ancestor(monkeypatch, tmp_path):
+ """A link back inside the snapshot passes containment, so only the visited set stops the
+ descent. Linux `os.walk` declines a symlink on its own, which would make this pass either
+ way, so the walk here descends it the way Windows descends a junction."""
+ repo_root = _dataset_snapshot(monkeypatch, tmp_path, ("README.md", "data/notes.md"))
+ data = next((repo_root / "snapshots").iterdir()) / "data"
+ (data / "loop").symlink_to(data, target_is_directory = True)
+ # a junction resolves like a link while reporting `is_symlink()` False, and Linux cannot
+ # create one, so this is a symlink that answers the way a junction does.
+ real_is_symlink = Path.is_symlink
+ monkeypatch.setattr(
+ Path,
+ "is_symlink",
+ lambda self: False if self.name == "loop" else real_is_symlink(self),
+ )
+ depth = 0
+
+ def _walk_following_junctions(
+ top,
+ followlinks = False,
+ onerror = None,
+ ):
+ nonlocal depth
+ stack = [Path(top)]
+ while stack:
+ base = stack.pop()
+ depth = max(depth, len(base.parts))
+ assert depth < 40, "the walk never pruned the link back to an ancestor"
+ names = sorted(entry.name for entry in base.iterdir())
+ dirnames = [name for name in names if (base / name).is_dir()]
+ filenames = [name for name in names if name not in dirnames]
+ yield str(base), dirnames, filenames
+ stack.extend(base / name for name in dirnames)
+
+ monkeypatch.setattr(cache_inventory.os, "walk", _walk_following_junctions)
+
+ assert cache_inventory._raw_dataset_cache_has_data("Org/Data", repo_root) is False
+
+
+def test_raw_dataset_cache_has_data_rejects_an_empty_payload_file(monkeypatch, tmp_path):
+ """A zero-byte file looks like payload and yields nothing, so this asks
+ `local_options._empty_payload` rather than settling for the file existing."""
+ repo_root = _dataset_snapshot(monkeypatch, tmp_path, ("README.md",))
+ snapshot = next((repo_root / "snapshots").iterdir())
+ (snapshot / "train.jsonl").write_bytes(b"")
+
+ assert cache_inventory._raw_dataset_cache_has_data("Org/Data", repo_root) is False
+
+ (snapshot / "train.jsonl").write_bytes(b'{"text": "x"}\n')
+
+ assert cache_inventory._raw_dataset_cache_has_data("Org/Data", repo_root) is True
+
+
+def test_raw_dataset_cache_has_data_rejects_a_payload_file_with_no_rows(monkeypatch, tmp_path):
+ """Bytes are not rows: `_rowless` probes a header-only csv and a `[]` json, from which the
+ picker resolves no split. A rowless file is dropped, but it does not condemn its siblings."""
+ repo_root = _dataset_snapshot(monkeypatch, tmp_path, ("README.md",))
+ snapshot = next((repo_root / "snapshots").iterdir())
+ (snapshot / "train.csv").write_bytes(b"text,label\n")
+ (snapshot / "extra.json").write_bytes(b"[]")
+
+ assert cache_inventory._raw_dataset_cache_has_data("Org/Data", repo_root) is False
+
+ (snapshot / "train.csv").write_bytes(b"text,label\nhello,1\n")
+
+ assert cache_inventory._raw_dataset_cache_has_data("Org/Data", repo_root) is True
+
+
+def test_raw_dataset_cache_has_data_walks_a_redirect_instead_of_trusting_it(monkeypatch, tmp_path):
+ """Pruning a redirect hid migrated caches; taking one as proof is the opposite error, since
+ a stale redirect holds no rows. The target is walked, not assumed."""
+ stale = tmp_path / "elsewhere" / "stale"
+ stale.mkdir(parents = True)
+ (stale / "README.md").write_bytes(b"x")
+ repo_root = _dataset_snapshot(monkeypatch, tmp_path, ("README.md",))
+ snapshot = next((repo_root / "snapshots").iterdir())
+ (snapshot / "data").symlink_to(stale, target_is_directory = True)
+
+ assert cache_inventory._raw_dataset_cache_has_data("Org/Data", repo_root) is False
+
+ (stale / "train.parquet").write_bytes(b"PAR1" + b"\0" * 64)
+
+ assert cache_inventory._raw_dataset_cache_has_data("Org/Data", repo_root) is True
+
+
+def test_raw_dataset_cache_has_data_keeps_the_real_dir_when_an_alias_precedes_it(
+ monkeypatch, tmp_path
+):
+ """The walk never descends the alias on POSIX, so booking its target pruned the real
+ directory and lost the payload under it, on nothing but enumeration order."""
+ repo_root = _dataset_snapshot(monkeypatch, tmp_path, ("README.md", "data/train.parquet"))
+ snapshot = next((repo_root / "snapshots").iterdir())
+ (snapshot / "alias").symlink_to(snapshot / "data", target_is_directory = True)
+
+ def _walk_alias_first(
+ top,
+ followlinks = False,
+ onerror = None,
+ ):
+ stack = [Path(top)]
+ while stack:
+ base = stack.pop()
+ names = sorted(entry.name for entry in base.iterdir())
+ dirnames = [name for name in names if (base / name).is_dir()]
+ filenames = [name for name in names if name not in dirnames]
+ yield str(base), dirnames, filenames
+ # POSIX: a symlinked directory is listed but not descended.
+ stack.extend(base / name for name in dirnames if not (base / name).is_symlink())
+
+ monkeypatch.setattr(cache_inventory.os, "walk", _walk_alias_first)
+
+ assert cache_inventory._raw_dataset_cache_has_data("Org/Data", repo_root) is True
+
+
+def test_raw_dataset_cache_has_data_reads_the_suffix_chain_like_the_resolver(monkeypatch, tmp_path):
+ """`_data_suffix` drops a trailing compression suffix then walks the rest. Reading only the
+ last suffix got both directions backwards."""
+ metadata_only = _dataset_snapshot(
+ monkeypatch,
+ tmp_path / "meta",
+ ("README.md", "CITATION.cff.zip", "loader.py.gz"),
+ )
+ compressed_payload = _dataset_snapshot(
+ monkeypatch,
+ tmp_path / "data",
+ ("README.md", "train.parquet.gz", "records.parquet.backup"),
+ )
+
+ assert cache_inventory._raw_dataset_cache_has_data("Org/Data", metadata_only) is False
+ assert cache_inventory._raw_dataset_cache_has_data("Org/Data", compressed_payload) is True
+
+
+def test_raw_dataset_cache_has_data_ignores_payload_links_whose_blob_is_gone(monkeypatch, tmp_path):
+ """`is_snapshot_partial` catches this on the newest snapshot, but this check judges the
+ pinned revision, so it must not depend on the two agreeing."""
+ repo_root = _dataset_snapshot(monkeypatch, tmp_path, ("README.md",))
+ snapshot = next((repo_root / "snapshots").iterdir())
+ (snapshot / "train.parquet").symlink_to("../../blobs/pruned")
+
+ assert cache_inventory._raw_dataset_cache_has_data("Org/Data", repo_root) is False
+
+
+def test_raw_dataset_cache_has_data_counts_a_linked_payload_directory(monkeypatch, tmp_path):
+ """A migrated or shared cache can keep its data behind a directory link. The walk must
+ not descend into one -- it can point anywhere -- but pruning it silently made the repo
+ read as metadata-only, and On Device drops every partial row."""
+ payload = tmp_path / "elsewhere"
+ payload.mkdir()
+ (payload / "train-00000-of-00001.parquet").write_bytes(b"PAR1")
+ repo_root = _dataset_snapshot(monkeypatch, tmp_path, ("README.md",))
+ (repo_root / "snapshots" / "abc" / "data").symlink_to(payload, target_is_directory = True)
+
+ assert cache_inventory._raw_dataset_cache_has_data("Org/Data", repo_root) is True
+
+
+def test_raw_dataset_cache_has_data_ignores_payload_in_an_unpinned_revision(monkeypatch, tmp_path):
+ """A payload-bearing sibling revision does not make the row usable.
+
+ `training_dataset_cache_pin` resolves through `dataset_snapshot_from_cache_path`, which
+ prefers the revision `refs/main` names. Clearing `partial` because some other revision
+ holds data would offer a row whose pinned load path is the metadata-only revision, so the
+ run falls back to the network and fails outright offline."""
+ repo_root = _dataset_snapshot(monkeypatch, tmp_path, ("README.md",))
+ (repo_root / "refs").mkdir(parents = True, exist_ok = True)
+ (repo_root / "refs" / "main").write_text("abc")
+ other = repo_root / "snapshots" / "def"
+ other.mkdir(parents = True)
+ (other / "train-00000-of-00001.parquet").write_bytes(b"PAR1")
+
+ assert cache_inventory._raw_dataset_cache_has_data("Org/Data", repo_root) is False
+
+
+def test_raw_dataset_cache_has_data_ignores_any_dotfile(monkeypatch, tmp_path):
+ """`.gitignore` and friends are not in the enumerated list, but `datasets` skips every
+ dotted name when resolving data files, so none of them can supply rows."""
+ repo_root = _dataset_snapshot(
+ monkeypatch,
+ tmp_path,
+ ("README.md", ".gitignore", ".gitattributes", ".hidden/notes.txt"),
+ )
+
+ assert cache_inventory._raw_dataset_cache_has_data("Org/Data", repo_root) is False
+
+
+def test_raw_dataset_cache_has_data_never_walks_outside_the_snapshot(monkeypatch, tmp_path):
+ """The prune is a containment test, not a link-type test.
+
+ `Path.is_symlink()` is false for a Windows junction and `Path.is_junction()` does not
+ exist before 3.12, which this package still supports, so a link-type test would let
+ `os.walk` descend a junction into an arbitrary external tree. A directory that resolves
+ outside the snapshot is left unvisited whatever kind of redirect it is."""
+ outside = tmp_path / "outside"
+ (outside / "deep").mkdir(parents = True)
+ (outside / "deep" / "huge.parquet").write_bytes(b"PAR1")
+ repo_root = _dataset_snapshot(monkeypatch, tmp_path, ("README.md",))
+ # Named like clutter, so it is not payload evidence either, and the tree behind it is
+ # never entered -- which is what stops a scan from stalling on someone else's disk.
+ (repo_root / "snapshots" / "abc" / ".hidden_link").symlink_to(outside, target_is_directory = True)
+
+ assert cache_inventory._raw_dataset_cache_has_data("Org/Data", repo_root) is False
+
+
+def test_raw_dataset_cache_has_data_does_not_read_an_unreadable_tree_as_empty(
+ monkeypatch, tmp_path
+):
+ """`os.walk` swallows `scandir` errors unless `onerror` is given, so a cache written by
+ another user answered "no payload" rather than "could not look", and a dataset that was
+ merely uninspectable vanished from On Device."""
+ repo_root = _dataset_snapshot(monkeypatch, tmp_path, ("README.md", "data/train.parquet"))
+ locked = repo_root / "snapshots" / "abc" / "data"
+ os.chmod(locked, 0o000)
+ try:
+ assert cache_inventory._raw_dataset_cache_has_data("Org/Data", repo_root) is True
+ finally:
+ os.chmod(locked, 0o755)
+
+
+def _metadata_only_raw_repo() -> SimpleNamespace:
+ return SimpleNamespace(
+ repo_id = "Org/Data",
+ repo_type = "dataset",
+ repo_path = "/cache/hub/datasets--Org--Data",
+ size_on_disk = 100,
+ revisions = [SimpleNamespace(files = [], commit_hash = "abc")],
+ )
+
+
+def test_dataset_cache_without_data_files_is_partial(monkeypatch):
+ """A snapshot holding only the dataset card passes every structural check but
+ cannot be loaded, so it must not be offered as usable On Device."""
+ monkeypatch.setattr(
+ cache_inventory,
+ "_collect_hf_cache_scans",
+ lambda: ([SimpleNamespace(repos = [_metadata_only_raw_repo()])], {"/cache/hub"}),
+ )
+ monkeypatch.setattr(
+ cache_inventory.hf_cache_scan,
+ "is_snapshot_partial",
+ lambda *_args, **_kwargs: False,
+ )
+ monkeypatch.setattr(cache_inventory, "_raw_dataset_cache_has_data", lambda *_args: False)
+ monkeypatch.setattr(cache_inventory, "_scan_hub_dataset_cache_dirs", lambda: [])
+ monkeypatch.setattr(cache_inventory, "_scan_processed_dataset_caches", lambda: [])
+ monkeypatch.setattr(cache_inventory, "_scan_app_processed_dataset_caches", lambda: [])
+
+ rows = cache_inventory._scan_hf_dataset_caches()
+
+ assert len(rows) == 1
+ assert rows[0]["partial"] is True
+
+
+def test_processed_cache_settles_a_partial_raw_row_without_losing_its_path(monkeypatch):
+ """The Arrow cache loads on its own, so it clears `partial`. The row must keep the hub
+ `cache_path`, which is the only handle `delete_cached_dataset_response` can scope a
+ hub-dir purge to."""
+ monkeypatch.setattr(
+ cache_inventory,
+ "_collect_hf_cache_scans",
+ lambda: ([SimpleNamespace(repos = [_metadata_only_raw_repo()])], {"/cache/hub"}),
+ )
+ monkeypatch.setattr(
+ cache_inventory.hf_cache_scan,
+ "is_snapshot_partial",
+ lambda *_args, **_kwargs: False,
+ )
+ monkeypatch.setattr(cache_inventory, "_raw_dataset_cache_has_data", lambda *_args: False)
+ monkeypatch.setattr(cache_inventory, "_scan_hub_dataset_cache_dirs", lambda: [])
+ monkeypatch.setattr(
+ cache_inventory,
+ "_scan_processed_dataset_caches",
+ lambda: [
+ {
+ "repo_id": "org/data",
+ "size_bytes": 250,
+ "cache_path": "/processed/org___data",
+ "processed_cache": True,
+ "partial": False,
+ }
+ ],
+ )
+ monkeypatch.setattr(cache_inventory, "_scan_app_processed_dataset_caches", lambda: [])
+
+ rows = cache_inventory._scan_hf_dataset_caches()
+
+ assert len(rows) == 1
+ assert rows[0]["cache_path"] == "/cache/hub/datasets--Org--Data"
+ assert rows[0]["load_cache_path"] == "/processed/org___data"
+ assert rows[0]["partial"] is False
+ assert rows[0]["partial_transport"] is None
+
+
+def test_app_processed_cache_never_settles_a_partial_raw_row(monkeypatch):
+ """App caches are written per snapshot commit but grouped without one, so a finished
+ cache proves nothing about the snapshot the loader will resolve."""
+ monkeypatch.setattr(
+ cache_inventory,
+ "_collect_hf_cache_scans",
+ lambda: ([SimpleNamespace(repos = [_metadata_only_raw_repo()])], {"/cache/hub"}),
+ )
+ monkeypatch.setattr(
+ cache_inventory.hf_cache_scan,
+ "is_snapshot_partial",
+ lambda *_args, **_kwargs: False,
+ )
+ monkeypatch.setattr(cache_inventory, "_raw_dataset_cache_has_data", lambda *_args: False)
+ monkeypatch.setattr(cache_inventory, "_scan_hub_dataset_cache_dirs", lambda: [])
+ monkeypatch.setattr(cache_inventory, "_scan_processed_dataset_caches", lambda: [])
+ monkeypatch.setattr(
+ cache_inventory,
+ "_scan_app_processed_dataset_caches",
+ lambda: [
+ {
+ "repo_id": "org/data",
+ "size_bytes": 40,
+ "cache_path": "/app/entry",
+ "processed_cache": True,
+ "app_processed_cache": True,
+ "app_processed_hub_cache": "/cache/hub",
+ "partial": True,
+ }
+ ],
+ )
+
+ rows = cache_inventory._scan_hf_dataset_caches()
+
+ assert len(rows) == 1
+ assert rows[0]["partial"] is True
+
+
def test_app_processed_cache_without_raw_snapshot_is_partial(monkeypatch):
monkeypatch.setattr(cache_inventory, "_collect_hf_cache_scans", lambda: ([], set()))
monkeypatch.setattr(cache_inventory, "_scan_hub_dataset_cache_dirs", lambda: [])
@@ -899,3 +1334,16 @@ def test_local_dataset_items_expose_recipe_and_upload_source(monkeypatch, tmp_pa
by_id = {item.id: item for item in response.datasets}
assert by_id["recipe_alpha"].source == "recipe"
assert by_id["manual.jsonl"].source == "upload"
+
+
+def test_raw_dataset_cache_has_data_ignores_every_datasets_metadata_name(monkeypatch, tmp_path):
+ """The non-payload set reuses `local_options._IGNORED_DATA_FILENAMES` rather than copying
+ it, so the check and the resolver that decides whether a cache yields rows cannot drift.
+ A snapshot holding only these has no rows to load however complete it looks."""
+ repo_root = _dataset_snapshot(
+ monkeypatch,
+ tmp_path,
+ tuple(sorted(local_options._IGNORED_DATA_FILENAMES)),
+ )
+
+ assert cache_inventory._raw_dataset_cache_has_data("Org/Data", repo_root) is False
diff --git a/studio/frontend/src/components/ui/progress.tsx b/studio/frontend/src/components/ui/progress.tsx
index 200bbcba31c..fb92dbea71c 100644
--- a/studio/frontend/src/components/ui/progress.tsx
+++ b/studio/frontend/src/components/ui/progress.tsx
@@ -11,10 +11,13 @@ import { cn } from "@/lib/utils";
function Progress({
className,
indicatorClassName,
+ indeterminate = false,
value,
...props
}: React.ComponentProps<typeof ProgressPrimitive.Root> & {
indicatorClassName?: string;
+ // work of unknown length: sweep a segment across the track instead of filling it.
+ indeterminate?: boolean;
}) {
return (
<ProgressPrimitive.Root
@@ -24,14 +27,24 @@ function Progress({
className,
)}
{...props}
+ // radix reads a missing value as the indeterminate state, which is what belongs here.
+ value={indeterminate ? undefined : value}
>
<ProgressPrimitive.Indicator
data-slot="progress-indicator"
className={cn(
- "bg-control-accent size-full flex-1 transition-all",
+ "bg-control-accent",
+ // one branch owns the width: tailwind-merge keeps both `size-full` and `w-1/3`.
+ indeterminate
+ ? "h-full w-1/3 loading-bar-slide"
+ : "size-full flex-1 transition-all",
indicatorClassName,
)}
- style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
+ style={
+ indeterminate
+ ? undefined
+ : { transform: `translateX(-${100 - (value || 0)}%)` }
+ }
/>
</ProgressPrimitive.Root>
);
diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.ts
index 2b28df20b47..c55913c64ce 100644
--- a/studio/frontend/src/features/chat/api/chat-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-api.ts
@@ -454,6 +454,8 @@ export interface DownloadProgressResponse {
* nothing is in flight.
*/
completed_bytes: number;
+ /** True once the backend verified a usable snapshot on disk; `progress` is capped at 0.99 until then. */
+ complete_on_disk: boolean;
expected_bytes: number;
progress: number;
/**
diff --git a/studio/frontend/src/features/studio/download-state.ts b/studio/frontend/src/features/studio/download-state.ts
index 55a97ecd6be..ebefa5f2fdc 100644
--- a/studio/frontend/src/features/studio/download-state.ts
+++ b/studio/frontend/src/features/studio/download-state.ts
@@ -1,19 +1,37 @@
// 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 download state the training-start overlay renders, plus the coercion that
-// decides whether a resource is still arriving or merely unverified. Kept apart
-// from the overlay so the rule can be exercised without mounting the component.
+// the download state the training-start overlay renders, kept apart from it so the rules can
+// be exercised without mounting the component.
+
+// restated rather than imported from the chat feature so this module stays out of its type graph.
+export type DownloadProgressReading = {
+ downloaded_bytes: number;
+ completed_bytes: number;
+ expected_bytes: number;
+ progress: number;
+ // optional on purpose: a backend older than this field is the one case where treating a
+ // missing value as `true` would settle a row that nothing verified.
+ complete_on_disk?: boolean;
+ // omitted, not nulled, when the cache could not be scanned at all.
+ cache_path?: string | null;
+};
export type DownloadState = {
downloadedBytes: number;
- // Finalized-blob bytes only, mirroring the backend field of the same name:
- // bytes still landing in a `.incomplete` blob count toward `downloadedBytes`
- // but not here.
+ // finalized blobs only; bytes still landing in a `.incomplete` blob are not counted here.
completedBytes: number;
totalBytes: number;
percent: number;
cachePath: string | null;
+ // the backend verified a usable snapshot on disk.
+ completeOnDisk: boolean;
+ // nothing left to transfer, by verification or by standing still.
+ settled: boolean;
+ // bytes moved between the last two readings, and the snapshot is not verified. Not
+ // `!settled`: an orphaned `.incomplete` blob keeps `downloaded !== completed` forever, so a
+ // row that will never settle is still not transferring anything.
+ moving: boolean;
};
export const EMPTY_DOWNLOAD_STATE: DownloadState = {
@@ -22,40 +40,59 @@ export const EMPTY_DOWNLOAD_STATE: DownloadState = {
totalBytes: 0,
percent: 0,
cachePath: null,
+ completeOnDisk: false,
+ settled: false,
+ moving: false,
};
-/**
- * Present a cached resource as ready once nothing is left to transfer.
- *
- * The backend holds progress at 99% until a Studio download manifest verifies the
- * snapshot on disk. Hugging Face cache entries created outside Studio -- or before
- * the manifest system existed -- never get one, so they stay unverified with every
- * byte already present, and the overlay rendered them as an active transfer
- * indefinitely (#7858).
- *
- * `completedBytes` is what separates the two cases: it counts finalized blobs
- * only, so all of them being present means nothing is in flight and the remaining
- * gap is verification rather than transfer. A resumed download -- where finalized
- * bytes can sit near the total while `.incomplete` blobs are still growing -- keeps
- * reporting progress, which is what the backend's 99% cap exists to protect.
- */
+// a training run fetches a subset of the repo, so completed_bytes never reaches expected_bytes
+// and the backend's verification never fires; standing still is the settled signal instead.
+export function downloadStateFromProgress(
+ reading: DownloadProgressReading,
+ previous: DownloadState = EMPTY_DOWNLOAD_STATE,
+): DownloadState {
+ const completeOnDisk = reading.complete_on_disk ?? false;
+ const totalBytes = reading.expected_bytes;
+ const downloadedBytes = reading.downloaded_bytes;
+ const completedBytes = reading.completed_bytes;
+ const nothingInFlight = downloadedBytes > 0 && downloadedBytes === completedBytes;
+ // two polls, because huggingface_hub finalizes each blob as it lands and a single quiet reading happens between files.
+ const unchanged =
+ downloadedBytes === previous.downloadedBytes &&
+ completedBytes === previous.completedBytes;
+ return {
+ downloadedBytes,
+ completedBytes,
+ totalBytes,
+ percent: totalBytes > 0 ? Math.min(100, Math.round(reading.progress * 100)) : 0,
+ cachePath: reading.cache_path ?? null,
+ completeOnDisk,
+ settled: completeOnDisk || (nothingInFlight && unchanged),
+ // A verified snapshot is not transferring whatever the byte counts did since the last
+ // reading -- and it is the condition the poll stops on, so a `true` here would freeze
+ // and suppress this row's preparation step for the rest of the run.
+ moving: !completeOnDisk && !unchanged,
+ };
+}
+
+// presents a settled resource as ready, which the backend's 99% cap never does on its own (#7858).
export function coerceCachedStateReady(state: DownloadState): DownloadState {
if (!state.cachePath) return state;
- const everyByteFinalized =
- state.totalBytes > 0 && state.completedBytes >= state.totalBytes;
- if (state.downloadedBytes > 0 && state.percent < 100 && !everyByteFinalized) {
+ if (!state.settled && state.downloadedBytes > 0 && state.percent < 100) {
return state;
}
- const totalBytes =
- state.totalBytes > 0 ? state.totalBytes : state.downloadedBytes;
- if (totalBytes <= 0) {
- return { ...state, percent: 100 };
+ if (state.downloadedBytes <= 0) {
+ // an unreadable-size entry settles so it cannot hang; one with bytes still expected has not started.
+ return state.totalBytes > 0
+ ? state
+ : { ...state, percent: 100, settled: true };
}
+ // the total becomes what was fetched, not expected_bytes, which counts files this run never wanted.
return {
...state,
- downloadedBytes: totalBytes,
- completedBytes: totalBytes,
- totalBytes,
+ completedBytes: state.downloadedBytes,
+ totalBytes: state.downloadedBytes,
percent: 100,
+ settled: true,
};
}
diff --git a/studio/frontend/src/features/studio/preparation-progress.ts b/studio/frontend/src/features/studio/preparation-progress.ts
new file mode 100644
index 00000000000..ad3093b064c
--- /dev/null
+++ b/studio/frontend/src/features/studio/preparation-progress.ts
@@ -0,0 +1,147 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// reads the worker's status message for the window between the last download and the first
+// training step, kept apart from the overlay so the parsing can be exercised on its own.
+
+import type { TrainingPhase } from "@/features/training";
+
+export type PreparationProgress = {
+ title: string;
+ // row counts behind a determinate bar, e.g. `32,000 / 207,865`.
+ detail: string | null;
+ // null for a bar of unknown length.
+ percent: number | null;
+};
+
+const PREPARATION_PHASES = new Set<TrainingPhase>([
+ "loading_model",
+ "loading_dataset",
+ "configuring",
+]);
+
+// `training` counts while the step is still 0: the worker reports that phase as soon as the
+// trainer is built, with dataset mapping still ahead of it.
+export function shouldShowPreparationStatus(
+ phase: TrainingPhase,
+ currentStep: number,
+ isStarting: boolean,
+): boolean {
+ if (isStarting) return true;
+ return (
+ PREPARATION_PHASES.has(phase) || (phase === "training" && currentStep <= 0)
+ );
+}
+
+// the worker's message, or the caller's fallback before it has sent one.
+export function resolvePreparationMessage(
+ message: string,
+ fallback: string,
+): string {
+ return message.trim() || fallback;
+}
+
+// `_monitor_tqdm` in core/training/worker.py emits `"<desc> <percent>% (<n>/<total>)"`.
+const COUNTED_PREPARATION_RE =
+ /^(?<label>.+?)\s+(?<percent>\d{1,3})%\s+\((?<current>[\d,]+)\s*\/\s*(?<total>[\d,]+)\)$/;
+
+// the audio loops report bare counts instead, e.g. `"Encoding audio... 100/1000"`.
+const TALLIED_PREPARATION_RE =
+ /^(?<label>.+?)\s+(?<current>[\d,]+)\s*\/\s*(?<total>[\d,]+)$/;
+
+function cleanPreparationTitle(label: string): string {
+ return label
+ .replace(/^Unsloth:\s*/i, "")
+ .replace(/\s*\(num_proc\s*=\s*\d+\)$/i, "")
+ .replace(/(?:\.\.\.|…)$/, "")
+ .trim();
+}
+
+function indeterminatePreparation(label: string): PreparationProgress {
+ return { title: cleanPreparationTitle(label), detail: null, percent: null };
+}
+
+export type PreparationTarget = "model" | "dataset";
+
+// a repo id must not match inside another: a bare `includes` routed a model status to the
+// dataset row whenever one id was a prefix of the other.
+const ID_CHAR = /[a-z0-9._/-]/;
+
+function mentionsResource(haystack: string, name?: string): boolean {
+ if (!name) return false;
+ let from = 0;
+ for (;;) {
+ const at = haystack.indexOf(name, from);
+ if (at < 0) return false;
+ const before = at > 0 ? haystack[at - 1] : "";
+ const after = haystack[at + name.length] ?? "";
+ if (!ID_CHAR.test(before) && !ID_CHAR.test(after)) return true;
+ from = at + 1;
+ }
+}
+
+// no bare `token` stem: `tokenizing` is dataset work, `tokenizer` is part of loading the model.
+// the audio codecs are here because they are loaded only to preprocess the dataset.
+const DATASET_PREPARATION_RE =
+ /tokenizing|dataset|standardiz|\bmap\b|\bfilter\b|generating|resolving data|casting|formatting|\bsamples\b|local files|encoding audio|preprocessing|\brows\b|slic|snac|bicodec|outetts|whisper|codec|audio|eval split|chat template|\bconverting\b/i;
+
+// checked before the dataset patterns: `Starting SNAC training...` names a codec only because
+// it names the run, and matching `snac` sent the trainer's own start line to the dataset row.
+const MODEL_PREPARATION_RE = /^(?:starting|initializing|queued)\b.*\btraining\b/i;
+
+// repo ids come first because the worker reports `Loading <repo_id>...`, which matches no
+// pattern; dataset work always names itself, so everything else belongs to the model.
+export function classifyPreparation(
+ title: string,
+ resources: {
+ modelName?: string | null;
+ datasetName?: string | null;
+ } = {},
+): PreparationTarget {
+ const haystack = title.toLowerCase();
+ const datasetName = resources.datasetName?.toLowerCase();
+ const modelName = resources.modelName?.toLowerCase();
+ const datasetHit = mentionsResource(haystack, datasetName);
+ const modelHit = mentionsResource(haystack, modelName);
+ // the Hub allows one owner/name as both repo types, and then the id decides nothing; fall
+ // through to the wording rather than handing every such message to the dataset.
+ const ambiguous = datasetHit && modelHit && datasetName === modelName;
+ // the longer id wins when both match, because one can contain the other:
+ // `Loading org/foo-base` mentions the model AND the dataset `org/foo`.
+ if (!ambiguous) {
+ if (datasetHit && (!modelHit || datasetName!.length >= modelName!.length)) {
+ return "dataset";
+ }
+ if (modelHit) return "model";
+ }
+ if (MODEL_PREPARATION_RE.test(title)) return "model";
+ return DATASET_PREPARATION_RE.test(title) ? "dataset" : "model";
+}
+
+export function parsePreparationProgress(
+ message: string,
+ fallback: string,
+): PreparationProgress {
+ const resolved = resolvePreparationMessage(message, fallback);
+ const groups =
+ COUNTED_PREPARATION_RE.exec(resolved)?.groups ??
+ TALLIED_PREPARATION_RE.exec(resolved)?.groups;
+ if (!groups) return indeterminatePreparation(resolved);
+
+ const current = Number(groups.current.replaceAll(",", ""));
+ const total = Number(groups.total.replaceAll(",", ""));
+ // the tqdm shape reports its own percent; recomputing it would disagree with the log line above.
+ const percent =
+ groups.percent === undefined
+ ? Math.floor((current / total) * 100)
+ : Number(groups.percent);
+ if (percent > 100 || total <= 0 || current > total) {
+ return indeterminatePreparation(groups.label);
+ }
+
+ return {
+ title: cleanPreparationTitle(groups.label),
+ detail: `${groups.current} / ${groups.total}`,
+ percent,
+ };
+}
diff --git a/studio/frontend/src/features/studio/training-start-overlay.tsx b/studio/frontend/src/features/studio/training-start-overlay.tsx
index 91392e95214..12616b3536e 100644
--- a/studio/frontend/src/features/studio/training-start-overlay.tsx
+++ b/studio/frontend/src/features/studio/training-start-overlay.tsx
@@ -29,8 +29,15 @@ import { formatEta, formatRate } from "@/features/chat/utils/format-transfer";
import {
EMPTY_DOWNLOAD_STATE,
coerceCachedStateReady,
+ downloadStateFromProgress,
type DownloadState,
} from "@/features/studio/download-state";
+import {
+ classifyPreparation,
+ parsePreparationProgress,
+ shouldShowPreparationStatus,
+ type PreparationProgress,
+} from "./preparation-progress";
import {
useTrainingActions,
useTrainingConfigStore,
@@ -95,25 +102,27 @@ function useHfDownloadProgress(
let cancelled = false;
let finished = false;
let interval: ReturnType<typeof setInterval> | null = null;
+ // settling compares against the previous reading, so the poll carries it rather than reading it back out of React.
+ let latest = EMPTY_DOWNLOAD_STATE;
+ // the tick does not wait for the request, so a slow response can land after a newer
+ // one. settling compares byte counts for equality, so a stale reading both revokes a
+ // correct settle and becomes the baseline the next poll settles against -- reporting
+ // the stale total as the row's size. discard anything older than what we already have.
+ let issued = 0;
+ let applied = 0;
const poll = async () => {
if (cancelled || finished) return;
+ const generation = ++issued;
try {
const prog = await fetcher(repoId);
- if (cancelled) return;
- const downloaded = prog.downloaded_bytes ?? 0;
- const total = prog.expected_bytes ?? 0;
- const ratio = prog.progress ?? 0;
- const pct =
- total > 0 ? Math.min(100, Math.round(ratio * 100)) : 0;
- setState({
- downloadedBytes: downloaded,
- completedBytes: prog.completed_bytes ?? 0,
- totalBytes: total,
- percent: pct,
- cachePath: prog.cache_path ?? null,
- });
- if (ratio >= 1.0) {
+ if (cancelled || generation <= applied) return;
+ applied = generation;
+ const next = downloadStateFromProgress(prog, latest);
+ latest = next;
+ setState(next);
+ // only a verified snapshot stops the tick; a settled row can still be waiting on files.
+ if (next.completeOnDisk) {
finished = true;
if (interval) {
clearInterval(interval);
@@ -145,55 +154,97 @@ function useDatasetDownloadProgress(datasetName: string | null): DownloadState {
return useHfDownloadProgress(datasetName, getDatasetDownloadProgress);
}
-type DownloadRowProps = {
+const PROGRESS_INDICATOR_CLASS =
+ "bg-[linear-gradient(90deg,var(--control-accent)_0%,color-mix(in_oklab,var(--control-accent)_72%,white)_100%)]";
+
+type ResourceRowProps = {
label: string;
state: DownloadState;
+ preparation: PreparationProgress | null;
};
-function DownloadRow({ label, state }: DownloadRowProps): ReactElement | null {
+// Whether the row would draw anything. The caller needs the same answer: the row is
+// mounted unconditionally now, and its `AnimatedSpan` wrapper still lays out a line even
+// when the row itself renders null, which left a blank gap in the terminal for a run whose
+// dataset never produces a transfer.
+export function resourceRowHasContent(
+ state: DownloadState,
+ preparation: PreparationProgress | null,
+): boolean {
+ return Boolean(preparation) || state.downloadedBytes > 0 || Boolean(state.cachePath);
+}
+
+// one row per resource for its whole setup: the transfer while bytes move, then that
+// resource's preparation step once they stop.
+function ResourceRow({
+ label,
+ state,
+ preparation,
+}: ResourceRowProps): ReactElement | null {
const t = useT();
// Rolling-window rate + ETA from the cumulative-byte series the poll hook
// produces, so we show "5.2 / 20.7 GB • 85.3 MB/s • 3m 12s left", not just the pair.
const stats = useTransferStats(state.downloadedBytes, state.totalBytes);
- if (state.downloadedBytes <= 0 && !state.cachePath) return null;
- const isComplete = state.totalBytes > 0 && state.percent >= 100;
- const statusLabel = isComplete
- ? t("studio.trainingStart.ready")
- : state.totalBytes > 0
- ? t("studio.trainingStart.downloading")
- : state.downloadedBytes === 0
- ? t("studio.trainingStart.preparing")
- : null;
+ if (!resourceRowHasContent(state, preparation)) return null;
+ // the coerced state: `coerceCachedStateReady` declines to rewrite a reading with no cache
+ // path, so `settled` alone put a green Ready next to a percent below 100.
+ const isComplete = state.settled && state.percent >= 100;
+ // gated on bytes actually moving, not on `!settled`: an orphaned `.incomplete` blob keeps
+ // `downloaded !== completed` forever, which kept a processed-cache load labelled Downloading.
+ const preparing = state.moving ? null : preparation;
+ const statusLabel = preparing
+ ? preparing.title
+ : isComplete
+ ? t("studio.trainingStart.ready")
+ : state.totalBytes > 0
+ ? t("studio.trainingStart.downloading")
+ : state.downloadedBytes === 0
+ ? t("studio.trainingStart.preparing")
+ : null;
const showRate = stats.stable && !isComplete;
const rateSuffix = showRate ? ` • ${formatRate(stats.rateBytesPerSecond)}` : "";
const etaStr =
showRate && state.totalBytes > 0 ? formatEta(stats.etaSeconds) : "--";
const etaSuffix =
etaStr !== "--" ? ` • ${t("studio.trainingStart.left", { eta: etaStr })}` : "";
- const sizeLabel =
- state.totalBytes > 0
+ // an unsettled transfer keeps its byte line under the preparation title: a stall and an
+ // orphaned blob look alike from byte counts, so a stalled download must not lose them.
+ const sizeLabel = preparing
+ ? (preparing.detail ??
+ (state.settled || state.totalBytes <= 0
+ ? null
+ : `${formatBytes(state.downloadedBytes)} / ${formatBytes(state.totalBytes)}`))
+ : state.totalBytes > 0
? `${formatBytes(state.downloadedBytes)} / ${formatBytes(state.totalBytes)}${rateSuffix}${etaSuffix}`
: state.downloadedBytes > 0
? `${t("studio.trainingStart.downloaded", {
size: formatBytes(state.downloadedBytes),
})}${rateSuffix}`
: null;
+ const percentLabel = preparing
+ ? preparing.percent !== null
+ ? `${preparing.percent}%`
+ : ""
+ : state.totalBytes > 0
+ ? `${state.percent}%`
+ : "";
return (
<div className="flex flex-col gap-1.5 rounded-md border border-border/50 bg-muted/20 px-3 py-2">
<div className="flex items-center justify-between gap-3">
- <div className="flex items-center gap-2">
- <span className="text-xs text-foreground/90">{label}</span>
+ <div className="flex min-w-0 items-center gap-2">
+ <span className="shrink-0 text-xs text-foreground/90">{label}</span>
{statusLabel ? (
<span
- className={`rounded-full px-1.5 py-0.5 text-ui-10 font-medium ${isComplete ? "bg-emerald-100 text-emerald-700 ring-1 ring-emerald-200/80 dark:bg-emerald-500/15 dark:text-emerald-300 dark:ring-emerald-500/30" : "bg-muted text-muted-foreground"}`}
+ className={`truncate rounded-full px-1.5 py-0.5 text-ui-10 font-medium ${isComplete && !preparing ? "bg-emerald-100 text-emerald-700 ring-1 ring-emerald-200/80 dark:bg-emerald-500/15 dark:text-emerald-300 dark:ring-emerald-500/30" : "bg-muted text-muted-foreground"}`}
+ title={statusLabel}
>
{statusLabel}
</span>
) : null}
</div>
- <span className="text-xs tabular-nums text-muted-foreground">
- {state.totalBytes > 0 ? `${state.percent}%` : ""}
+ <span className="shrink-0 text-xs tabular-nums text-muted-foreground">
+ {percentLabel}
</span>
</div>
{sizeLabel ? (
@@ -201,10 +252,16 @@ function DownloadRow({ label, state }: DownloadRowProps): ReactElement | null {
{sizeLabel}
</div>
) : null}
- {state.totalBytes > 0 ? (
+ {preparing ? (
+ <Progress
+ value={preparing.percent ?? undefined}
+ indeterminate={preparing.percent === null}
+ indicatorClassName={PROGRESS_INDICATOR_CLASS}
+ />
+ ) : state.totalBytes > 0 ? (
<Progress
value={state.percent}
- indicatorClassName="bg-[linear-gradient(90deg,var(--control-accent)_0%,color-mix(in_oklab,var(--control-accent)_72%,white)_100%)]"
+ indicatorClassName={PROGRESS_INDICATOR_CLASS}
/>
) : null}
{state.cachePath ? (
@@ -248,8 +305,6 @@ export function TrainingStartOverlay({
const hfDatasetName = datasetSource === "huggingface" ? dataset : null;
const hasStartResources = startModelName !== null;
const useConfiguredResources = !isStarting && !hasStartResources;
- const isDownloadPhase =
- phase === "downloading_model" || phase === "downloading_dataset";
const modelName = hasStartResources
? startModelName
: useConfiguredResources
@@ -261,17 +316,29 @@ export function TrainingStartOverlay({
? hfDatasetName
: null;
const displayMessage =
- startFromResume && !isDownloadPhase && /^download/i.test(message)
+ startFromResume && /^download/i.test(message)
? t("studio.trainingStart.resumingTraining")
: message || t("studio.trainingStart.startingTraining");
const rawModelDownload = useModelDownloadProgress(modelName);
const rawDatasetDownload = useDatasetDownloadProgress(datasetName);
- const modelDownload = isDownloadPhase
- ? rawModelDownload
- : coerceCachedStateReady(rawModelDownload);
- const datasetDownload = isDownloadPhase
- ? rawDatasetDownload
- : coerceCachedStateReady(rawDatasetDownload);
+ const modelDownload = coerceCachedStateReady(rawModelDownload);
+ const datasetDownload = coerceCachedStateReady(rawDatasetDownload);
+ // the raw message, not displayMessage: a resumed run rewrites its download statuses to
+ // "resuming training", which names no resource for the classifier to route on.
+ const preparationProgress = shouldShowPreparationStatus(
+ phase,
+ currentStep,
+ isStarting,
+ )
+ ? parsePreparationProgress(message, t("studio.trainingStart.preparing"))
+ : null;
+ const preparationTarget = preparationProgress
+ ? classifyPreparation(preparationProgress.title, { modelName, datasetName })
+ : null;
+ const datasetPreparation =
+ preparationTarget === "dataset" ? preparationProgress : null;
+ const modelPreparation =
+ preparationTarget === "model" ? preparationProgress : null;
const [cancelDialogOpen, setCancelDialogOpen] = useState(false);
const [cancelRequested, setCancelRequested] = useState(false);
@@ -364,22 +431,38 @@ export function TrainingStartOverlay({
})}
</AnimatedSpan>
{datasetStreaming ? (
- <AnimatedSpan className="mt-3 text-muted-foreground">
- {t("studio.trainingStart.datasetStreaming")}
- </AnimatedSpan>
- ) : datasetDownload.downloadedBytes > 0 || datasetDownload.cachePath ? (
+ <>
+ <AnimatedSpan className="mt-3 text-muted-foreground">
+ {t("studio.trainingStart.datasetStreaming")}
+ </AnimatedSpan>
+ {/* streaming has no transfer to show, but it still tokenizes and formats. the
+ row carries the preparation step on an empty state, so nothing implies a
+ download. */}
+ {datasetPreparation ? (
+ <AnimatedSpan className="mt-3">
+ <ResourceRow
+ label={t("studio.trainingStart.dataset")}
+ state={EMPTY_DOWNLOAD_STATE}
+ preparation={datasetPreparation}
+ />
+ </AnimatedSpan>
+ ) : null}
+ </>
+ ) : resourceRowHasContent(datasetDownload, datasetPreparation) ? (
<AnimatedSpan className="mt-3">
- <DownloadRow
+ <ResourceRow
label={t("studio.trainingStart.dataset")}
state={datasetDownload}
+ preparation={datasetPreparation}
/>
</AnimatedSpan>
) : null}
- {modelDownload.downloadedBytes > 0 || modelDownload.cachePath ? (
+ {resourceRowHasContent(modelDownload, modelPreparation) ? (
<AnimatedSpan className="mt-3">
- <DownloadRow
+ <ResourceRow
label={t("studio.trainingStart.modelWeights")}
state={modelDownload}
+ preparation={modelPreparation}
/>
</AnimatedSpan>
) : null}
diff --git a/studio/frontend/tests/training-start-cached-progress.test.ts b/studio/frontend/tests/training-start-cached-progress.test.ts
index 21ae994e030..4dbff2c2cc3 100644
--- a/studio/frontend/tests/training-start-cached-progress.test.ts
+++ b/studio/frontend/tests/training-start-cached-progress.test.ts
@@ -1,18 +1,21 @@
// 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 training-start overlay showed cached resources as "Downloading -- 99%" with no
-// download running (#7858): the backend caps progress at 99% until a Studio manifest
-// verifies the snapshot, and cache entries made outside Studio never have one. These
-// pin the distinction the overlay now draws -- finalized bytes decide whether anything
-// is still arriving -- including the resumed-download case the 99% cap exists for.
+// The training-start overlay showed resources as "Downloading -- 99%" with no download
+// running (#7858). The backend caps progress at 0.99 until it verifies the snapshot, and
+// verification compares against `expected_bytes`, which counts every file in the repo while a
+// training run fetches a subset -- so the cap never lifts. These pin the settling rule that
+// replaces it, and the readings it must refuse to settle.
import assert from "node:assert/strict";
import test from "node:test";
import {
+ type DownloadProgressReading,
type DownloadState,
+ EMPTY_DOWNLOAD_STATE,
coerceCachedStateReady,
+ downloadStateFromProgress,
} from "../src/features/studio/download-state.ts";
const MB = 1e6;
@@ -25,43 +28,142 @@ function state(over: Partial<DownloadState> = {}): DownloadState {
totalBytes: 0,
percent: 0,
cachePath: "/home/u/.cache/huggingface/hub/datasets--unsloth--alpaca-cleaned",
+ completeOnDisk: false,
+ settled: false,
+ moving: false,
...over,
};
}
-test("a cache entry with no manifest reads as ready, not as a transfer", () => {
- // Observed with unsloth/alpaca-cleaned: 42.3 MB of 42.3 MB, no worker running.
- const coerced = coerceCachedStateReady(
- state({
- downloadedBytes: 42.3 * MB,
- completedBytes: 42.3 * MB,
- totalBytes: 42.3 * MB,
- percent: 99,
+/** Feed the same reading twice, as the 1.5s poll would when nothing is moving. */
+function pollTwice(reading: DownloadProgressReading): DownloadState {
+ const first = downloadStateFromProgress(reading, EMPTY_DOWNLOAD_STATE);
+ return downloadStateFromProgress(reading, first);
+}
+
+test("a verified snapshot settles on the first reading", () => {
+ const verified = downloadStateFromProgress({
+ downloaded_bytes: 1.51 * GB,
+ completed_bytes: 1.51 * GB,
+ expected_bytes: 1.51 * GB,
+ progress: 1,
+ complete_on_disk: true,
+ cache_path: "/home/u/.cache/huggingface/hub/datasets--unsloth--LaTeX_OCR",
+ });
+ assert.equal(verified.percent, 100);
+ assert.equal(verified.settled, true);
+});
+
+test("a subset fetch settles once its bytes stop moving", () => {
+ // Qwen3.5-0.8B-Base: expected counts README.md, LICENSE and .gitattributes, which the
+ // trainer never fetches, so completed sits 16,640 bytes short and progress is pinned at
+ // the 0.99 cap for a model that is entirely present.
+ const reading: DownloadProgressReading = {
+ downloaded_bytes: 1_769_897_109,
+ completed_bytes: 1_769_897_109,
+ expected_bytes: 1_769_913_749,
+ progress: 0.99,
+ complete_on_disk: false,
+ cache_path: "/home/u/.cache/huggingface/hub/models--Qwen--Qwen3.5-0.8B-Base",
+ };
+ assert.equal(downloadStateFromProgress(reading).settled, false);
+ assert.equal(pollTwice(reading).settled, true);
+});
+
+test("a settled subset fetch reports the bytes it actually holds", () => {
+ // Not `expected_bytes`: OpenThoughts-1k-sample ships a second config load_dataset never
+ // wants, so settling at the expected total would claim 28.1 MB for a 14.0 MB fetch.
+ const settled = coerceCachedStateReady(
+ pollTwice({
+ downloaded_bytes: 14_002_749,
+ completed_bytes: 14_002_749,
+ expected_bytes: 28_059_770,
+ progress: 0.499,
+ complete_on_disk: false,
+ cache_path: "/home/u/.cache/huggingface/hub/datasets--ryanmarten--OpenThoughts-1k-sample",
}),
);
- assert.equal(coerced.percent, 100);
+ assert.equal(settled.percent, 100);
+ assert.equal(settled.totalBytes, 14_002_749);
});
-test("a resumed download still reports progress while blobs are incomplete", () => {
- // The case the backend's 99% cap protects: finalized bytes sit just under the
- // total while the remaining `.incomplete` blob is still growing.
- const resuming = state({
- downloadedBytes: 20 * GB,
- completedBytes: 19.9 * GB,
- totalBytes: 20 * GB,
- percent: 99,
+test("one quiet reading is not enough, because blobs finalize between files", () => {
+ // Mid-download, huggingface_hub has just linked a blob and not yet opened the next, so
+ // downloaded == completed for this single tick.
+ const betweenFiles = downloadStateFromProgress({
+ downloaded_bytes: 5 * GB,
+ completed_bytes: 5 * GB,
+ expected_bytes: 20 * GB,
+ progress: 0.25,
+ complete_on_disk: false,
+ cache_path: "/home/u/.cache/huggingface/hub/models--unsloth--gpt-oss-120b",
});
- assert.deepEqual(coerceCachedStateReady(resuming), resuming);
+ assert.equal(betweenFiles.settled, false);
+ assert.equal(coerceCachedStateReady(betweenFiles).percent, 25);
});
-test("an ordinary in-flight download is left alone", () => {
- const downloading = state({
- downloadedBytes: 5 * GB,
- completedBytes: 4.8 * GB,
- totalBytes: 20 * GB,
- percent: 25,
+test("bytes in flight never settle, however long they sit", () => {
+ // A resumed download: finalized bytes near the total with an `.incomplete` blob growing.
+ const resuming: DownloadProgressReading = {
+ downloaded_bytes: 20 * GB,
+ completed_bytes: 19.9 * GB,
+ expected_bytes: 20 * GB,
+ progress: 0.99,
+ complete_on_disk: false,
+ cache_path: "/home/u/.cache/huggingface/hub/models--unsloth--gpt-oss-120b",
+ };
+ assert.equal(pollTwice(resuming).settled, false);
+});
+
+test("a growing download never settles", () => {
+ const first = downloadStateFromProgress({
+ downloaded_bytes: 5 * GB,
+ completed_bytes: 5 * GB,
+ expected_bytes: 20 * GB,
+ progress: 0.25,
+ complete_on_disk: false,
+ cache_path: "/home/u/.cache/huggingface/hub/models--unsloth--gpt-oss-120b",
});
- assert.deepEqual(coerceCachedStateReady(downloading), downloading);
+ const second = downloadStateFromProgress(
+ {
+ downloaded_bytes: 6 * GB,
+ completed_bytes: 6 * GB,
+ expected_bytes: 20 * GB,
+ progress: 0.3,
+ complete_on_disk: false,
+ cache_path: "/home/u/.cache/huggingface/hub/models--unsloth--gpt-oss-120b",
+ },
+ first,
+ );
+ assert.equal(second.settled, false);
+});
+
+test("a transfer that stalled and resumed stops reading as settled", () => {
+ // A slow multi-file download can go quiet for two polls between files. Latching settlement
+ // would then show Ready, with no rate or progress, for the rest of the transfer.
+ const reading: DownloadProgressReading = {
+ downloaded_bytes: 5 * GB,
+ completed_bytes: 5 * GB,
+ expected_bytes: 20 * GB,
+ progress: 0.25,
+ complete_on_disk: false,
+ cache_path: "/home/u/.cache/huggingface/hub/models--unsloth--gpt-oss-120b",
+ };
+ const stalled = pollTwice(reading);
+ assert.equal(stalled.settled, true);
+
+ const resumed = downloadStateFromProgress(
+ { ...reading, downloaded_bytes: 5.2 * GB, completed_bytes: 5 * GB, progress: 0.26 },
+ stalled,
+ );
+ assert.equal(resumed.settled, false);
+ assert.equal(coerceCachedStateReady(resumed).percent, 26);
+});
+
+test("a cache dir with bytes still expected is not ready", () => {
+ // The repo dir exists from an earlier attempt, but nothing has arrived for this one.
+ const empty = state({ downloadedBytes: 0, completedBytes: 0, totalBytes: 20 * GB });
+ assert.deepEqual(coerceCachedStateReady(empty), empty);
});
test("a resource with no cache path is never coerced", () => {
@@ -71,13 +173,109 @@ test("a resource with no cache path is never coerced", () => {
totalBytes: 42.3 * MB,
percent: 99,
cachePath: null,
+ settled: true,
});
assert.deepEqual(coerceCachedStateReady(uncached), uncached);
});
test("a cached entry of unknown size still settles instead of hanging", () => {
- const unsized = coerceCachedStateReady(
- state({ downloadedBytes: 0, completedBytes: 0, totalBytes: 0, percent: 0 }),
- );
+ const unsized = coerceCachedStateReady(state());
assert.equal(unsized.percent, 100);
+ assert.equal(unsized.settled, true);
+});
+
+test("a response without complete_on_disk never settles on verification alone", () => {
+ // A backend older than the field. Reading a missing value as truthy would settle a row
+ // nothing has verified, and the poll would stop on its very first reading.
+ const legacy = {
+ downloaded_bytes: 400 * MB,
+ completed_bytes: 200 * MB,
+ expected_bytes: 20 * GB,
+ progress: 0.02,
+ cache_path: "/home/u/.cache/huggingface/hub/models--Qwen--Qwen3.5-0.8B-Base",
+ } as DownloadProgressReading;
+ const first = downloadStateFromProgress(legacy);
+ assert.equal(first.completeOnDisk, false);
+ assert.equal(first.settled, false);
+ assert.equal(downloadStateFromProgress(legacy, first).settled, false);
+});
+
+test("a stale reading cannot become the baseline the next poll settles against", () => {
+ // The poll is an interval, not a chain, so a slow request can resolve after a newer one.
+ // Comparing byte counts for equality means a stale pair looks exactly like a quiet one,
+ // and the row would settle reporting the STALE total as its size.
+ const fresh: DownloadProgressReading = {
+ downloaded_bytes: 12 * GB,
+ completed_bytes: 12 * GB,
+ expected_bytes: 20 * GB,
+ progress: 0.6,
+ complete_on_disk: false,
+ cache_path: "/home/u/.cache/huggingface/hub/models--Qwen--Qwen3.5-0.8B-Base",
+ };
+ const stale = { ...fresh, downloaded_bytes: 4 * GB, completed_bytes: 4 * GB, progress: 0.2 };
+ const settled = pollTwice(fresh);
+ assert.equal(settled.settled, true);
+ assert.equal(coerceCachedStateReady(settled).totalBytes, 12 * GB);
+ // The overlay drops the stale response by generation, so the row keeps the fresh total.
+ const afterStale = downloadStateFromProgress(stale, settled);
+ assert.equal(afterStale.settled, false);
+ assert.equal(downloadStateFromProgress(stale, afterStale).totalBytes, 20 * GB);
+});
+
+test("an orphaned .incomplete blob stops the transfer without ever settling", () => {
+ // A dataset that loads from its processed Arrow cache can still have a stray `.incomplete`
+ // blob in the raw hub cache. `downloaded_bytes` counts it and `completed_bytes` does not, so
+ // the row can never settle -- but nothing is transferring either, and gating preparation on
+ // `!settled` left tokenization labelled Downloading for the whole pre-step window.
+ const stuck: DownloadProgressReading = {
+ downloaded_bytes: 14.1 * MB,
+ completed_bytes: 13.4 * MB,
+ expected_bytes: 26.8 * MB,
+ progress: 0.52,
+ complete_on_disk: false,
+ cache_path: "/home/u/.cache/huggingface/hub/datasets--unsloth--alpaca-cleaned",
+ };
+ const quiet = pollTwice(stuck);
+ assert.equal(quiet.settled, false, "an unfinalized blob is never settled");
+ assert.equal(quiet.moving, false, "but no bytes are moving, so preparation may show");
+});
+
+test("a live transfer keeps reporting movement", () => {
+ const first = downloadStateFromProgress({
+ downloaded_bytes: 4 * GB,
+ completed_bytes: 3 * GB,
+ expected_bytes: 20 * GB,
+ progress: 0.2,
+ complete_on_disk: false,
+ cache_path: "/home/u/.cache/huggingface/hub/models--Qwen--Qwen3.5-0.8B-Base",
+ });
+ const second = downloadStateFromProgress(
+ {
+ downloaded_bytes: 6 * GB,
+ completed_bytes: 5 * GB,
+ expected_bytes: 20 * GB,
+ progress: 0.3,
+ complete_on_disk: false,
+ cache_path: "/home/u/.cache/huggingface/hub/models--Qwen--Qwen3.5-0.8B-Base",
+ },
+ first,
+ );
+ assert.equal(second.moving, true);
+ assert.equal(second.settled, false);
+});
+
+test("a verified snapshot is never reported as moving", () => {
+ // `complete_on_disk` is what stops the poll, so a `moving: true` recorded on the same
+ // reading freezes for the rest of the run and suppresses this row's preparation step --
+ // an already-cached model would never show "Loading <repo>".
+ const verified = downloadStateFromProgress({
+ downloaded_bytes: 1.51 * GB,
+ completed_bytes: 1.51 * GB,
+ expected_bytes: 1.51 * GB,
+ progress: 1,
+ complete_on_disk: true,
+ cache_path: "/home/u/.cache/huggingface/hub/models--Qwen--Qwen3.5-0.8B-Base",
+ });
+ assert.equal(verified.settled, true);
+ assert.equal(verified.moving, false, "verified means nothing is in flight");
});
diff --git a/studio/frontend/tests/training-start-preparation.test.ts b/studio/frontend/tests/training-start-preparation.test.ts
new file mode 100644
index 00000000000..7f2e509cc53
--- /dev/null
+++ b/studio/frontend/tests/training-start-preparation.test.ts
@@ -0,0 +1,286 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Between the last download and the first training step the overlay sat on a static
+// line while tokenizing ran for minutes. These pin the parsing of the worker's tqdm
+// status messages, whose exact shape is `f"{desc} {pct}% ({n:,}/{total:,})"` in
+// `_monitor_tqdm` (studio/backend/core/training/worker.py).
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ classifyPreparation,
+ parsePreparationProgress,
+ resolvePreparationMessage,
+ shouldShowPreparationStatus,
+} from "../src/features/studio/preparation-progress.ts";
+
+test("a preparation step routes to the resource row it belongs to", () => {
+ // Dataset work always names itself, so everything else belongs to the model row.
+ assert.equal(classifyPreparation('Tokenizing ["text"]'), "dataset");
+ assert.equal(classifyPreparation("Loading dataset"), "dataset");
+ assert.equal(classifyPreparation("Map"), "dataset");
+ assert.equal(classifyPreparation("Unsloth: Formatting dataset"), "dataset");
+ assert.equal(classifyPreparation("Loading checkpoint shards"), "model");
+ assert.equal(classifyPreparation("Loading model"), "model");
+ // "tokenizer" is model setup; only "tokenizing" is dataset work.
+ assert.equal(classifyPreparation("Loading tokenizer"), "model");
+ assert.equal(classifyPreparation("Configuring training"), "model");
+});
+
+test("every status the worker sends reaches a row", () => {
+ // Swept from the `_send_status`/`status_message` literals in studio/backend/core/training.
+ // Fifteen of these reached no row at all, and the three download lines were being
+ // replaced by a generic "Preparing" before they got that far.
+ const resources = {
+ modelName: "Qwen/Qwen3.5-0.8B-Base",
+ datasetName: "ryanmarten/OpenThoughts-1k-sample",
+ };
+ const datasetSteps = [
+ "Loading dataset...",
+ "Loading and formatting dataset...",
+ "Loading cached dataset: ryanmarten/OpenThoughts-1k-sample...",
+ "Downloading dataset: ryanmarten/OpenThoughts-1k-sample...",
+ "Downloading dataset from S3...",
+ "Downloaded ryanmarten/OpenThoughts-1k-sample (1,000 rows)",
+ "Streaming dataset: ryanmarten/OpenThoughts-1k-sample...",
+ "Formatting dataset (chatml)...",
+ "Formatting VLM dataset...",
+ "Dataset ready (1,000 samples, chatml format)",
+ "Sliced dataset to 500 rows (indices 0-500)",
+ "Loaded 1000 samples from local files",
+ "Encoding audio with SNAC...",
+ 'Tokenizing ["text"] (num_proc=4) 15% (32,000/207,865)',
+ ];
+ const audioSteps = [
+ // loaded only to preprocess the dataset, so they belong to its row; routing them to the
+ // model made the display flip between rows partway through one encoding pass.
+ "Loading SNAC codec model...",
+ "Loading BiCodec tokenizer...",
+ "Loading OuteTTS AudioProcessor...",
+ "Loading Whisper model for word timings...",
+ "Encoding audio with BiCodec... 100/1000",
+ "Preprocessing CSM... 5/100",
+ ];
+ const modelSteps = [
+ "Importing Unsloth...",
+ "Detecting model type...",
+ "Loading Qwen/Qwen3.5-0.8B-Base...",
+ "Loading model...",
+ "Configuring training...",
+ "Configuring LoRA adapters...",
+ "Preparing model for full finetuning...",
+ "Full finetuning mode - no LoRA adapters",
+ "Initializing MLX training...",
+ "Loading MLX libraries...",
+ "Starting training...",
+ "Saving model...",
+ ];
+ for (const message of [...datasetSteps, ...audioSteps]) {
+ const { title } = parsePreparationProgress(message, "Preparing");
+ assert.equal(classifyPreparation(title, resources), "dataset", message);
+ }
+ for (const message of modelSteps) {
+ const { title } = parsePreparationProgress(message, "Preparing");
+ assert.equal(classifyPreparation(title, resources), "model", message);
+ }
+});
+
+test("a step naming only a repo id routes by that name", () => {
+ // The worker reports `Loading <repo_id>...`, which carries no word the patterns match, so
+ // the row stayed empty through the whole model load.
+ const resources = {
+ modelName: "Qwen/Qwen3.5-0.8B-Base",
+ datasetName: "ryanmarten/OpenThoughts-1k-sample",
+ };
+ assert.equal(
+ classifyPreparation("Loading Qwen/Qwen3.5-0.8B-Base", resources),
+ "model",
+ );
+ assert.equal(
+ classifyPreparation("Loading ryanmarten/OpenThoughts-1k-sample", resources),
+ "dataset",
+ );
+ // Case folded, since the message echoes whatever casing the config carries.
+ assert.equal(
+ classifyPreparation("Loading qwen/qwen3.5-0.8b-base", resources),
+ "model",
+ );
+ // Unset resources fall through to the patterns rather than matching everything.
+ assert.equal(classifyPreparation("Loading checkpoint shards", {}), "model");
+});
+
+test("every tqdm description the dataset work emits reaches the dataset row", () => {
+ // Swept from the `desc =` literals under studio/backend. `_monitor_tqdm` forwards these
+ // verbatim, and none carried a word the earlier patterns matched, so a mapping pass that
+ // runs for minutes rendered under Model weights.
+ const resources = {
+ modelName: "Qwen/Qwen3-0.6B",
+ datasetName: "ryanmarten/OpenThoughts-1k-sample",
+ };
+ const descriptions = [
+ "Applying chat template to chatml 15% (32,000/207,865)",
+ "Applying chat template to sharegpt 15% (32,000/207,865)",
+ "Converting VLM samples 10% (100/1,000)",
+ "Converting ShareGPT+image 5% (50/1,000)",
+ ];
+ for (const message of descriptions) {
+ const { title } = parsePreparationProgress(message, "Preparing");
+ assert.equal(classifyPreparation(title, resources), "dataset", message);
+ }
+ // The model's own loading steps must not be pulled across by the added words.
+ assert.equal(classifyPreparation("Loading checkpoint shards", resources), "model");
+ assert.equal(classifyPreparation("Loading tokenizer", resources), "model");
+});
+
+test("an id shared by both repos routes by wording, not by the tie-break", () => {
+ // The Hub allows one owner/name as both repo types, and then the id decides nothing. The
+ // longer-id tie-break handed all of those to the dataset, emptying the model row.
+ const resources = { modelName: "org/foo", datasetName: "org/foo" };
+ assert.equal(classifyPreparation("Loading org/foo", resources), "model");
+ assert.equal(classifyPreparation("Tokenizing org/foo", resources), "dataset");
+ assert.equal(classifyPreparation("Loading checkpoint shards", resources), "model");
+ // A genuine prefix pair still resolves by length rather than falling through.
+ const distinct = { modelName: "org/foo-base", datasetName: "org/foo" };
+ assert.equal(classifyPreparation("Loading org/foo-base", distinct), "model");
+ assert.equal(classifyPreparation("Loading org/foo", distinct), "dataset");
+});
+
+test("the preparation row covers the gap up to the first step", () => {
+ assert.equal(shouldShowPreparationStatus("finalizing", 0, false), false);
+ assert.equal(shouldShowPreparationStatus("completed", 0, false), false);
+ assert.equal(shouldShowPreparationStatus("configuring", 0, false), true);
+ assert.equal(shouldShowPreparationStatus("loading_dataset", 0, false), true);
+ assert.equal(shouldShowPreparationStatus("idle", 0, true), true);
+ // The worker reports `training` as soon as the trainer is built, with dataset
+ // mapping still ahead of it, so the row stays until a step lands.
+ assert.equal(shouldShowPreparationStatus("training", 0, false), true);
+ assert.equal(shouldShowPreparationStatus("training", 1, false), false);
+});
+
+test("the fallback covers only the window before the worker reports", () => {
+ assert.equal(resolvePreparationMessage(" ", "Preparing"), "Preparing");
+ // "Downloading dataset: ..." is a real step of the dataset's setup, not a stale line to
+ // discard: dropping every message starting with "download" hid three of them.
+ assert.equal(
+ resolvePreparationMessage("Downloading dataset from S3...", "Preparing"),
+ "Downloading dataset from S3...",
+ );
+ assert.equal(
+ resolvePreparationMessage('Tokenizing ["text"] 15% (1/2)', "Preparing"),
+ 'Tokenizing ["text"] 15% (1/2)',
+ );
+});
+
+test("a counted message draws a determinate bar from the worker's own percent", () => {
+ assert.deepEqual(
+ parsePreparationProgress(
+ 'Tokenizing ["text"] (num_proc=4) 15% (32,000/207,865)',
+ "Preparing",
+ ),
+ {
+ title: 'Tokenizing ["text"]',
+ detail: "32,000 / 207,865",
+ percent: 15,
+ },
+ );
+ // 16,000/207,865 is 7.7%, and the worker truncates. Taking its number rather than
+ // recomputing keeps the bar and the log line above it showing the same figure.
+ assert.equal(
+ parsePreparationProgress("Filter (num_proc=4) 7% (16,000/207,865)", "Preparing")
+ .percent,
+ 7,
+ );
+});
+
+test("the audio loops report bare counts and still draw a bar", () => {
+ // `Encoding audio... {i}/{n}` and friends carry no percent, so the tqdm shape misses them
+ // and a long preprocessing pass swept indeterminately with the counts already in hand.
+ assert.deepEqual(
+ parsePreparationProgress("Encoding audio... 100/1000", "Preparing"),
+ { title: "Encoding audio", detail: "100 / 1000", percent: 10 },
+ );
+ assert.deepEqual(
+ parsePreparationProgress("Processing train audio... 1,500/12,000", "Preparing"),
+ { title: "Processing train audio", detail: "1,500 / 12,000", percent: 12 },
+ );
+});
+
+test("an uncounted message stays indeterminate", () => {
+ assert.deepEqual(parsePreparationProgress("Loading model...", "Preparing"), {
+ title: "Loading model",
+ detail: null,
+ percent: null,
+ });
+ assert.deepEqual(
+ parsePreparationProgress("Unsloth: Formatting dataset…", "Preparing"),
+ { title: "Formatting dataset", detail: null, percent: null },
+ );
+ assert.deepEqual(parsePreparationProgress("", "Preparing"), {
+ title: "Preparing",
+ detail: null,
+ percent: null,
+ });
+});
+
+test("counts that cannot describe a bar do not draw one", () => {
+ // A zero total, and a bar whose `n` overran `total` after a restart.
+ assert.deepEqual(parsePreparationProgress("Filter 100% (10/0)", "Preparing"), {
+ title: "Filter",
+ detail: null,
+ percent: null,
+ });
+ assert.deepEqual(parsePreparationProgress("Filter 100% (11/10)", "Preparing"), {
+ title: "Filter",
+ detail: null,
+ percent: null,
+ });
+});
+
+test("a trainer's own start line stays on the model row whatever it trains", () => {
+ // `Starting SNAC training...` and `Starting Whisper training...` name a codec only
+ // because it names the run. Matching `snac`/`whisper` sent them to the dataset row while
+ // the sibling `Starting CSM training...` went to the model row, so the same event landed
+ // in different places depending on which family was selected.
+ for (const message of [
+ "Starting SNAC training...",
+ "Starting Whisper training...",
+ "Starting CSM training...",
+ "Starting embedding training...",
+ "Starting training...",
+ "Initializing MLX training...",
+ "Queued MLX training setup",
+ ]) {
+ const { title } = parsePreparationProgress(message, "Preparing");
+ assert.equal(classifyPreparation(title), "model", message);
+ }
+});
+
+test("reloading the eval split is dataset work", () => {
+ // Says "eval split" rather than "dataset", so no pattern caught it and a dataset reload
+ // was reported on the model row.
+ const { title } = parsePreparationProgress(
+ "Cached eval split unavailable; reloading train and eval from the Hub...",
+ "Preparing",
+ );
+ assert.equal(classifyPreparation(title), "dataset");
+});
+
+test("one resource id being a prefix of the other does not steal the row", () => {
+ // `Loading org/foo-base` contains the dataset id `org/foo`, so a bare `includes` sent the
+ // model load to the dataset row and left the model row without its progress.
+ const resources = { modelName: "org/foo-base", datasetName: "org/foo" };
+ assert.equal(classifyPreparation("Loading org/foo-base", resources), "model");
+ assert.equal(classifyPreparation("Loading org/foo", resources), "dataset");
+ // And the other way round, where the dataset id is the longer one.
+ const swapped = { modelName: "org/foo", datasetName: "org/foo-sample" };
+ assert.equal(classifyPreparation("Loading org/foo-sample", swapped), "dataset");
+ assert.equal(classifyPreparation("Loading org/foo", swapped), "model");
+ // A trailing "..." or punctuation is still a boundary.
+ assert.equal(classifyPreparation("Loading org/foo-base...", resources), "model");
+ assert.equal(
+ classifyPreparation("Downloading dataset: org/foo (1,000 rows)", resources),
+ "dataset",
+ );
+});