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: retry Xet once on a stall before falling back to HTTP (#8166)

Daniel Hand882da2c4554
diff --git a/studio/backend/hub/services/download_lifecycle.py b/studio/backend/hub/services/download_lifecycle.py
index da44b39c7a5..da23a91064e 100644
--- a/studio/backend/hub/services/download_lifecycle.py
+++ b/studio/backend/hub/services/download_lifecycle.py
@@ -419,7 +419,33 @@ def _set_retry_failure_state(
return state
-def _try_http_retry(
+# "no byte baseline was handed to us, sample one" -- distinct from a sampled None (unmeasurable).
+_UNSAMPLED = object()
+
+
+def _is_data_phase_stall(message: str) -> bool:
+ """Did the watchdog trip AFTER bytes had flowed? Delegates to the shared rule so "worth
+ retrying" and "worth recording against the machine" can never disagree, with the same literal
+ check inline as the degraded fallback."""
+ try:
+ from utils.hf_xet_fallback import is_data_phase_stall
+ return is_data_phase_stall(message)
+ except Exception: # noqa: BLE001
+ return "did not start" not in (message or "")
+
+
+def _xet_attempt_budget() -> int:
+ """How many XET workers one download may spend before HTTP. Degrades to 1 (the pre-retry
+ ladder) if the shared helper cannot be imported, so a broken unsloth_zoo never turns into an
+ extra stall the user waits through."""
+ try:
+ from utils.hf_xet_fallback import xet_attempts
+ return xet_attempts()
+ except Exception: # noqa: BLE001
+ return 1
+
+
+def _try_transport_retry(
registry: download_registry.DownloadRegistry,
key: str,
*,
@@ -430,21 +456,49 @@ def _try_http_retry(
repo_type: RepoType,
repo_id: str,
watch_name: str,
+ retry_transport: str = download_registry.TRANSPORT_HTTP,
+ xet_attempt: int = 1,
+ pending_xet_failure: Optional[str] = None,
+ bytes_before: "Optional[int]" = _UNSAMPLED,
) -> bool:
- """Reclaim *key* with HTTP transport and spawn a recovery worker.
+ """Reclaim *key* under *retry_transport* and spawn a recovery worker.
- Returns ``True`` when the HTTP worker was successfully registered.
+ Returns ``True`` when the recovery worker was successfully registered.
Caller is responsible for ensuring this is only called when: the job is
- in ``"error"`` state, the original transport was XET, and HTTP is available.
+ in ``"error"`` state, the original transport was XET, and the target
+ transport is available.
+
+ Two directions share this body. ``TRANSPORT_HTTP`` is terminal: the
+ transport changes, so the worker's own ``prepare_cache_for_transport``
+ purges the XET partial an HTTP resume would corrupt. ``TRANSPORT_XET`` is
+ the stall retry: same transport, same marker, one more child, bounded by
+ *xet_attempt* rather than by the transport check that stops the HTTP one.
+
+ *pending_xet_failure* is a stall verdict held back from the health tracker
+ and carried into the next worker, so a download that recovers on its second
+ Xet attempt reports nothing and one that does not reports exactly one
+ failure. *bytes_before* is the ORIGINAL pre-Xet baseline: resampling would
+ fold the killed worker's partial writes in and make a recovered attempt
+ read as a cached no-op.
Derives variant and blob-hash metadata from the registry entry written by
the original XET claim so callers do not re-construct worker arguments.
Re-queries peer protection hashes at spawn time to reflect any concurrent
sibling changes between the XET failure and this call.
"""
+ retry_over_xet = retry_transport == download_registry.TRANSPORT_XET
+ retry_name = "XET" if retry_over_xet else "HTTP"
+
+ def _give_up() -> None:
+ """Ladder ends here, so a held-back verdict must still reach the health tracker: otherwise a
+ stall followed by a failed reclaim is silently forgiven."""
+ if pending_xet_failure:
+ _record_xet_failure(pending_xet_failure, logger)
+
original_metadata = registry.get_job_metadata(key)
if original_metadata is None:
logger.debug("%s XET retry skipped for %s; metadata unavailable", log_prefix, label)
+ _give_up()
_set_retry_failure_state(
registry,
key,
@@ -463,6 +517,7 @@ def _try_http_retry(
label,
original_metadata.transport,
)
+ _give_up()
_set_retry_failure_state(
registry,
key,
@@ -491,10 +546,11 @@ def _try_http_retry(
registry.release_active_slot(key)
while True:
if registry.cancel_requested(key):
+ # A user cancel is not evidence against Xet: a held-back stall is dropped, not charged.
_set_retry_failure_state(
registry,
key,
- "HTTP retry cancelled before reclaiming the download slot",
+ f"{retry_name} retry cancelled before reclaiming the download slot",
repo_type = repo_type,
repo_id = repo_id,
fallback_variant = variant,
@@ -505,7 +561,10 @@ def _try_http_retry(
claimed, conflict_state = registry.claim(
key,
- download_registry.TRANSPORT_HTTP,
+ # A XET retry re-claims the SAME transport, the permissive case in claim(): only a
+ # cross-transport claim serializes against a sibling, since only that can mix an HTTP
+ # resume with a XET rewrite over one shared blob.
+ retry_transport,
repo_type = repo_type,
repo_id = repo_id,
variant = variant,
@@ -532,10 +591,11 @@ def _try_http_retry(
label,
conflict_state,
)
+ _give_up()
_set_retry_failure_state(
registry,
key,
- "HTTP retry could not reclaim the download slot",
+ f"{retry_name} retry could not reclaim the download slot",
repo_type = repo_type,
repo_id = repo_id,
fallback_variant = variant,
@@ -556,18 +616,27 @@ def _try_http_retry(
args.append("--dataset")
elif variant:
args.extend(["--variant", variant])
- # A scoped job must retry as the SAME scoped download; without its file list the HTTP worker would fall through to a full snapshot.
+ # A scoped job must retry as the SAME scoped download; without its file list the recovery worker would fall through to a full snapshot.
if original_metadata.scoped_files:
args.extend(["--files-json", write_files_manifest(original_metadata.scoped_files)])
# Re-query at spawn time: sibling state may have changed since XET failed.
peer_hashes = registry.peer_blob_hashes(key) if variant else frozenset()
- logger.warning(
- "%s XET worker failed for %s; retrying over HTTP",
- log_prefix,
- label,
- )
+ if retry_over_xet:
+ logger.warning(
+ "%s XET worker stalled for %s; retrying on XET (attempt %d of %d)",
+ log_prefix,
+ label,
+ xet_attempt,
+ _xet_attempt_budget(),
+ )
+ else:
+ logger.warning(
+ "%s XET worker failed for %s; retrying over HTTP",
+ log_prefix,
+ label,
+ )
try:
cache_env = (
{
@@ -578,7 +647,7 @@ def _try_http_retry(
else None
)
spawn_kwargs = {
- "use_xet": False,
+ "use_xet": retry_over_xet,
"protected_blob_hashes": peer_hashes or None,
}
if cache_env is not None:
@@ -591,12 +660,39 @@ def _try_http_retry(
except Exception as exc:
scrubbed = download_registry.scrub_secrets(str(exc), hf_token = hf_token)
logger.error(
- "%s HTTP retry spawn failed for %s: %s",
+ "%s %s retry spawn failed for %s: %s",
log_prefix,
+ retry_name,
label,
scrubbed,
)
registry.update_job_transport(key, original_metadata.transport)
+ if retry_over_xet:
+ # The EXTRA worker could not be started (fd exhaustion, a broken interpreter path): a
+ # local failure, not a verdict on the download, so drop to the rung this job would have
+ # taken without the retry instead of stranding it in "error". Bounded: the HTTP
+ # direction never re-enters this branch.
+ logger.warning(
+ "%s XET retry could not be spawned for %s; falling back to HTTP",
+ log_prefix,
+ label,
+ )
+ return _try_transport_retry(
+ registry,
+ key,
+ hf_token = hf_token,
+ label = label,
+ log_prefix = log_prefix,
+ logger = logger,
+ repo_type = repo_type,
+ repo_id = repo_id,
+ watch_name = watch_name,
+ retry_transport = download_registry.TRANSPORT_HTTP,
+ xet_attempt = xet_attempt,
+ pending_xet_failure = pending_xet_failure,
+ bytes_before = bytes_before,
+ )
+ _give_up()
_set_retry_failure_state(
registry,
key,
@@ -619,9 +715,20 @@ def _try_http_retry(
logger = logger,
repo_type = repo_type,
repo_id = repo_id,
- transport = download_registry.TRANSPORT_HTTP,
+ transport = retry_transport,
cancel_marker_transport = original_metadata.transport,
watch_name = watch_name,
+ xet_attempt = xet_attempt,
+ pending_xet_failure = pending_xet_failure,
+ bytes_before = bytes_before,
+ )
+
+
+def _try_http_retry(registry: download_registry.DownloadRegistry, key: str, **kwargs) -> bool:
+ """Reclaim *key* over HTTP: the terminal rung of the recovery ladder. Thin alias kept because
+ "retry over HTTP" is what most call sites mean and read better than the transport keyword."""
+ return _try_transport_retry(
+ registry, key, retry_transport = download_registry.TRANSPORT_HTTP, **kwargs
)
@@ -669,9 +776,6 @@ def _repo_bytes_on_disk(repo_type, repo_id: str, cache_dir) -> "Optional[int]":
return None if state is None else int(state[0])
-_UNSAMPLED = object()
-
-
def _job_bytes_on_disk(repo_type, repo_id: str, cache_dir, blob_hashes) -> "Optional[int]":
"""Bytes THIS job owns, or None when unmeasurable.
@@ -721,9 +825,15 @@ def _start_stall_watchdog(
``None`` when no watchdog could be started.
SIGKILL rather than a polite signal: the worker traps SIGTERM and exits 130 ("cancelled"), which
- would record a user cancel and skip the HTTP retry. An untrapped kill lands as "error", which is
- what triggers the retry, and the worker's writer is sequential and resumable so the partial
- survives.
+ would record a user cancel and skip the recovery ladder. An untrapped kill lands as "error",
+ which is what triggers the retry.
+
+ What survives the kill depends on the transport the retry picks. Over HTTP the writer is
+ sequential and the partial genuinely resumes. Over XET it does not: hf_xet reconstructs a file
+ from offset zero rather than resuming it, so the recovery worker's own
+ ``prepare_cache_for_transport(..., "xet", ...)`` purges the partial on startup and re-fetches the
+ in-flight file. Every file already finalized into a blob is kept either way, and the worker runs
+ ``snapshot_download(max_workers=1)``, so at most one file is ever replayed.
"""
try:
from utils.hf_xet_fallback import start_watchdog
@@ -790,7 +900,16 @@ def register_worker(
cancel_marker_transport: Optional[str] = None,
watch_name: str,
bytes_before: "Optional[int]" = _UNSAMPLED,
+ xet_attempt: int = 1,
+ pending_xet_failure: Optional[str] = None,
) -> bool:
+ """Watch *proc* to completion and drive the recovery ladder off its exit.
+
+ *xet_attempt* (1-based) bounds the XET->XET stall retry, the way ``transport == TRANSPORT_XET``
+ bounds the terminal XET->HTTP one. *pending_xet_failure* is an earlier attempt's stall verdict,
+ held back from the health tracker until the XET phase ends so one download can never spend the
+ two consecutive failures that demote a machine.
+ """
if not registry.register_process(key, proc):
kill_and_reap_process(proc, label = label, logger = logger)
return False
@@ -861,6 +980,20 @@ def register_worker(
# Stop measuring once the worker is reaped: post-download work (symlinking,
# verification) makes no byte-level progress and must not read as a stall.
watchdog_stop.set()
+ # A hung Xet transfer usually clears on a fresh process, so spend one more XET worker
+ # before changing transport. Only a DATA-phase verdict qualifies: retrying a pre-byte
+ # trip would buy a second full 600s connect window before HTTP ever starts, and that
+ # trip is as likely slow metadata as a broken Xet.
+ retry_xet = (
+ can_retry_http
+ and state == "error"
+ and bool(stalled)
+ and _is_data_phase_stall(stalled[0])
+ and xet_attempt < _xet_attempt_budget()
+ )
+ # Evidence for the WHOLE Xet phase: what earlier attempts held back, updated with this
+ # worker's verdict. Reported once, when the phase ends.
+ xet_failure = pending_xet_failure
if stalled:
# Exclude only the PRE-BYTE trip: "did not start" means no byte ever arrived, as
# likely slow metadata, a queue of HEADs or a cache lock as a broken Xet, and two
@@ -874,8 +1007,8 @@ def register_worker(
# kill lands, so a worker that completed or was cancelled in that instant would be
# charged a failure it did not earn -- and on the completed path that also skips the
# success-clearing below, costing two streak steps the wrong way.
- if state == "error" and "did not start" not in stalled[0]:
- _record_xet_failure(stalled[0], logger)
+ if state == "error" and _is_data_phase_stall(stalled[0]):
+ xet_failure = stalled[0]
else:
logger.debug(
"%s not recording a Xet health failure (state=%s): %s",
@@ -883,7 +1016,18 @@ def register_worker(
state,
stalled[0],
)
- elif transport == download_registry.TRANSPORT_XET and state == "complete":
+ if state == "cancelled" or (
+ state == "complete" and transport == download_registry.TRANSPORT_XET
+ ):
+ # A XET completion proved Xet works here, and a cancel was never evidence against
+ # it: either way an earlier stall is dropped. An HTTP completion proves nothing
+ # about Xet, so a verdict carried onto that rung is still charged below.
+ xet_failure = None
+ if xet_failure is not None and not retry_xet:
+ # Xet phase over (HTTP next, or nothing left to try): report it, once.
+ _record_xet_failure(xet_failure, logger)
+ xet_failure = None
+ if not stalled and transport == download_registry.TRANSPORT_XET and state == "complete":
# Clear the streak so "two failures in a row" means in a row: otherwise a stall
# today and another next week count as consecutive despite every download between
# them succeeding, pinning Auto to HTTP for no reason. Only a job that actually
@@ -899,12 +1043,11 @@ def register_worker(
and bytes_after > _bytes_before
):
_record_xet_success(logger)
- # XET-to-HTTP recovery: when a non-cancelled XET worker fails and
- # HTTP is available, attempt one automatic retry over HTTP. The
- # transport check is the recursion guard: an HTTP worker that errors
- # never satisfies `transport == TRANSPORT_XET`, so it stays terminal.
+ # Recovery: spend another XET worker if the stall looked recoverable and the budget
+ # allows, else fall back to HTTP. One guard per direction: `transport == TRANSPORT_XET`
+ # (inside can_retry_http) makes the HTTP rung terminal, `xet_attempt` bounds the XET one.
if can_retry_http and state == "error":
- _try_http_retry(
+ _try_transport_retry(
registry,
key,
hf_token = worker_token,
@@ -914,6 +1057,16 @@ def register_worker(
repo_type = repo_type,
repo_id = repo_id,
watch_name = watch_name,
+ retry_transport = (
+ download_registry.TRANSPORT_XET
+ if retry_xet
+ else download_registry.TRANSPORT_HTTP
+ ),
+ xet_attempt = xet_attempt + 1 if retry_xet else xet_attempt,
+ pending_xet_failure = xet_failure,
+ # The ORIGINAL pre-Xet baseline: resampling would fold the killed worker's
+ # partial writes in, so a recovered attempt would read as a cached no-op.
+ bytes_before = _bytes_before,
)
except Exception:
if watchdog_stop is not None:
diff --git a/studio/backend/hub/tests/test_download_lifecycle.py b/studio/backend/hub/tests/test_download_lifecycle.py
index 89bb7c381e0..9e646117003 100644
--- a/studio/backend/hub/tests/test_download_lifecycle.py
+++ b/studio/backend/hub/tests/test_download_lifecycle.py
@@ -118,6 +118,180 @@ def test_xet_failure_retries_over_http_for_model_and_dataset(monkeypatch, tmp_pa
assert registry.current_generation(key) == generation
+def test_a_stalled_xet_worker_respawns_over_xet_keeping_its_claim(monkeypatch, tmp_path):
+ """End-to-end through the real reclaim: the recovery worker spawns with use_xet=True, the job
+ keeps the XET transport (so the UI and the .transport marker stay truthful), and the blob
+ metadata survives the re-claim."""
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ monkeypatch.setattr(download_lifecycle.threading, "Thread", _ImmediateThread)
+
+ def _start(registry, key, proc, *, on_stall, **kwargs):
+ on_stall("Download appears stalled (xet transport) -- no progress for 30s")
+ return None
+
+ monkeypatch.setattr(download_lifecycle, "_start_stall_watchdog", _start)
+ monkeypatch.setattr(
+ download_lifecycle, "_record_xet_failure", lambda *a: pytest.fail("charged")
+ )
+ register_worker = download_lifecycle.register_worker
+
+ registry = download_registry.DownloadRegistry()
+ key = download_registry.normalize_job_key("Org/Model")
+ assert registry.claim(
+ key,
+ download_registry.TRANSPORT_XET,
+ repo_type = "model",
+ repo_id = "Org/Model",
+ variant = None,
+ blob_hashes = frozenset({"blob"}),
+ )[0]
+ generation = registry.current_generation(key)
+ spawned = []
+
+ def fake_spawn(
+ args,
+ _token,
+ *,
+ use_xet,
+ protected_blob_hashes = None,
+ ):
+ spawned.append((args, use_xet))
+ return _Proc(0)
+
+ def fake_retry_register(*_args, **kwargs):
+ assert kwargs["transport"] == download_registry.TRANSPORT_XET
+ assert kwargs["xet_attempt"] == 2
+ return True
+
+ monkeypatch.setattr(download_lifecycle, "spawn_worker", fake_spawn)
+ monkeypatch.setattr(download_lifecycle, "register_worker", fake_retry_register)
+ assert register_worker(
+ registry,
+ key,
+ _Proc(1, b"killed"),
+ hf_token = None,
+ label = "Org/Model",
+ log_prefix = "Download",
+ logger = logging.getLogger("test"),
+ repo_type = "model",
+ repo_id = "Org/Model",
+ transport = download_registry.TRANSPORT_XET,
+ watch_name = "model-watch",
+ )
+
+ assert spawned == [(["--repo-id", "Org/Model"], True)]
+ metadata = registry.get_job_metadata(key)
+ assert metadata.transport == download_registry.TRANSPORT_XET
+ assert metadata.blob_hashes == frozenset({"blob"})
+ assert registry.current_generation(key) == generation
+
+
+def test_an_unspawnable_xet_retry_falls_through_to_http(monkeypatch, tmp_path):
+ """The extra Xet worker is a bonus rung: if it cannot be spawned at all, the download must
+ still get the HTTP fallback it would have had without the retry, not end in "error"."""
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ monkeypatch.setattr(download_lifecycle.threading, "Thread", _ImmediateThread)
+
+ spawned = []
+
+ def flaky_spawn(
+ args,
+ _token,
+ *,
+ use_xet,
+ protected_blob_hashes = None,
+ **_kw,
+ ):
+ spawned.append(use_xet)
+ if use_xet:
+ raise OSError("cannot fork")
+ return _Proc(0)
+
+ monkeypatch.setattr(download_lifecycle, "spawn_worker", flaky_spawn)
+ monkeypatch.setattr(download_lifecycle, "register_worker", lambda *a, **k: True)
+
+ registry = download_registry.DownloadRegistry()
+ key = download_registry.normalize_job_key("Org/Model")
+ assert registry.claim(
+ key,
+ download_registry.TRANSPORT_XET,
+ repo_type = "model",
+ repo_id = "Org/Model",
+ variant = None,
+ blob_hashes = frozenset({"blob"}),
+ )[0]
+
+ assert download_lifecycle._try_transport_retry(
+ registry,
+ key,
+ hf_token = None,
+ label = "Org/Model",
+ log_prefix = "Download",
+ logger = logging.getLogger("test"),
+ repo_type = "model",
+ repo_id = "Org/Model",
+ watch_name = "model-watch",
+ retry_transport = download_registry.TRANSPORT_XET,
+ xet_attempt = 2,
+ )
+ assert spawned == [True, False], "the failed XET respawn must be followed by an HTTP one"
+
+
+def test_a_verdict_carried_onto_the_http_rung_is_still_charged(monkeypatch, tmp_path):
+ """That fallthrough is the one path that hands a held stall to an HTTP worker. HTTP completing
+ says nothing about Xet, so clearing the verdict there would lose the only evidence a repeatedly
+ stalling machine ever produces."""
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ monkeypatch.setattr(download_lifecycle.threading, "Thread", _ImmediateThread)
+ verdict = "Download appears stalled (xet transport) -- no progress for 30s"
+
+ def _start(registry, key, proc, *, on_stall, **_kwargs):
+ on_stall(verdict)
+ return None
+
+ def flaky_spawn(
+ args,
+ _token,
+ *,
+ use_xet,
+ protected_blob_hashes = None,
+ ):
+ if use_xet:
+ raise OSError("cannot fork")
+ return _Proc(0) # the HTTP worker starts and completes
+
+ monkeypatch.setattr(download_lifecycle, "_start_stall_watchdog", _start)
+ monkeypatch.setattr(download_lifecycle, "spawn_worker", flaky_spawn)
+
+ recorded = []
+ monkeypatch.setattr(download_lifecycle, "_record_xet_failure", lambda m, _l: recorded.append(m))
+
+ registry = download_registry.DownloadRegistry()
+ key = download_registry.normalize_job_key("Org/Model")
+ assert registry.claim(
+ key,
+ download_registry.TRANSPORT_XET,
+ repo_type = "model",
+ repo_id = "Org/Model",
+ variant = None,
+ blob_hashes = frozenset({"blob"}),
+ )[0]
+ download_lifecycle.register_worker(
+ registry,
+ key,
+ _Proc(1, b"killed"),
+ hf_token = None,
+ label = "Org/Model",
+ log_prefix = "Download",
+ logger = logging.getLogger("test"),
+ repo_type = "model",
+ repo_id = "Org/Model",
+ transport = download_registry.TRANSPORT_XET,
+ watch_name = "model-watch",
+ )
+ assert recorded == [verdict], "a real Xet stall was dropped when HTTP finished the download"
+
+
def test_http_failure_remains_terminal(monkeypatch, tmp_path):
monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
monkeypatch.setattr(download_lifecycle.threading, "Thread", _ImmediateThread)
@@ -279,8 +453,15 @@ def _trip_xet_worker(
tmp_path,
message,
rc = 1,
+ xet_attempt = 2,
+ retries = None,
):
- """Run a Xet worker whose watchdog trips with *message*; return the health failures recorded."""
+ """Run a Xet worker whose watchdog trips with *message*; return the health failures recorded.
+
+ *xet_attempt* defaults to the LAST attempt of the default budget, since that is where the Xet
+ phase ends and a held-back verdict is finally reported. Pass 1 to exercise the deferral.
+ *retries* collects ``(retry_transport, xet_attempt, pending_xet_failure)`` for each respawn.
+ """
monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
monkeypatch.setattr(download_lifecycle.threading, "Thread", _ImmediateThread)
@@ -290,7 +471,19 @@ def _trip_xet_worker(
monkeypatch.setattr(download_lifecycle, "_start_stall_watchdog", _start)
monkeypatch.setattr(download_lifecycle, "spawn_worker", lambda *a, **k: _Proc(0))
- monkeypatch.setattr(download_lifecycle, "register_worker", lambda *a, **k: True)
+
+ def _fake_register(*_args, **kwargs):
+ if retries is not None:
+ retries.append(
+ (
+ kwargs.get("transport"),
+ kwargs.get("xet_attempt"),
+ kwargs.get("pending_xet_failure"),
+ )
+ )
+ return True
+
+ monkeypatch.setattr(download_lifecycle, "register_worker", _fake_register)
recorded = []
monkeypatch.setattr(download_lifecycle, "_record_xet_failure", lambda m, _l: recorded.append(m))
@@ -320,12 +513,14 @@ def _trip_xet_worker(
repo_id = "Org/Model",
transport = download_registry.TRANSPORT_XET,
watch_name = "model-watch",
+ xet_attempt = xet_attempt,
)
return recorded
def test_a_data_phase_stall_is_recorded_against_the_machine(monkeypatch, tmp_path):
- """A frozen partial with bytes already flowing is genuinely Xet misbehaving."""
+ """A frozen partial with bytes already flowing is genuinely Xet misbehaving -- charged once the
+ Xet phase is out of attempts."""
monkeypatch.setattr(
download_lifecycle, "_REAL_REGISTER", download_lifecycle.register_worker, raising = False
)
@@ -337,6 +532,73 @@ def test_a_data_phase_stall_is_recorded_against_the_machine(monkeypatch, tmp_pat
), "a real data-phase stall must still be recorded"
+def test_a_first_stall_buys_another_xet_worker_and_records_nothing(monkeypatch, tmp_path):
+ """A wedged Xet transfer usually clears on a fresh process, so the first data-phase stall
+ respawns over XET. Nothing is recorded yet: if the retry succeeds the stall was noise, and
+ charging both attempts would let ONE download hit the two-failure demotion threshold."""
+ monkeypatch.setattr(
+ download_lifecycle, "_REAL_REGISTER", download_lifecycle.register_worker, raising = False
+ )
+ retries = []
+ verdict = "Download appears stalled (xet transport) -- no progress for 30s"
+ assert (
+ _trip_xet_worker(monkeypatch, tmp_path, verdict, xet_attempt = 1, retries = retries) == []
+ ), "the first stall must not be charged to the machine"
+ assert retries == [(download_registry.TRANSPORT_XET, 2, verdict)]
+
+
+def test_the_last_xet_stall_falls_back_to_http_and_charges_once(monkeypatch, tmp_path):
+ """Out of Xet attempts: the transport changes, and the single accumulated verdict is reported."""
+ monkeypatch.setattr(
+ download_lifecycle, "_REAL_REGISTER", download_lifecycle.register_worker, raising = False
+ )
+ retries = []
+ recorded = _trip_xet_worker(
+ monkeypatch,
+ tmp_path,
+ "Download appears stalled (xet transport) -- no progress for 30s",
+ xet_attempt = 2,
+ retries = retries,
+ )
+ assert len(recorded) == 1
+ # The HTTP rung carries no pending verdict: it was just recorded.
+ assert retries == [(download_registry.TRANSPORT_HTTP, 2, None)]
+
+
+def test_a_pre_byte_trip_never_buys_another_xet_worker(monkeypatch, tmp_path):
+ """Retrying "did not start" would buy a second full 600s connect window before HTTP ever
+ starts, and that trip is as likely slow metadata as a broken Xet."""
+ monkeypatch.setattr(
+ download_lifecycle, "_REAL_REGISTER", download_lifecycle.register_worker, raising = False
+ )
+ retries = []
+ _trip_xet_worker(
+ monkeypatch,
+ tmp_path,
+ "Download did not start (xet transport) -- no data after 600s",
+ xet_attempt = 1,
+ retries = retries,
+ )
+ assert retries == [(download_registry.TRANSPORT_HTTP, 1, None)]
+
+
+def test_the_attempts_knob_of_one_restores_the_straight_to_http_ladder(monkeypatch, tmp_path):
+ monkeypatch.setenv("UNSLOTH_XET_ATTEMPTS", "1")
+ monkeypatch.setattr(
+ download_lifecycle, "_REAL_REGISTER", download_lifecycle.register_worker, raising = False
+ )
+ retries = []
+ recorded = _trip_xet_worker(
+ monkeypatch,
+ tmp_path,
+ "Download appears stalled (xet transport) -- no progress for 30s",
+ xet_attempt = 1,
+ retries = retries,
+ )
+ assert len(recorded) == 1
+ assert retries == [(download_registry.TRANSPORT_HTTP, 1, None)]
+
+
def test_a_pre_byte_trip_does_not_poison_the_machines_health_record(monkeypatch, tmp_path):
"""Two recorded failures pin this machine to HTTP for 24h, and "did not start" means not one
byte arrived, as likely slow metadata, a queue of HEADs or a cache lock as a broken Xet. The
diff --git a/studio/backend/utils/hf_xet_fallback.py b/studio/backend/utils/hf_xet_fallback.py
index 0c9985ce4f2..77364ae05b3 100644
--- a/studio/backend/utils/hf_xet_fallback.py
+++ b/studio/backend/utils/hf_xet_fallback.py
@@ -20,6 +20,7 @@ never triggers the heavy load.
from __future__ import annotations
+import os
import threading
from functools import partial
from pathlib import Path
@@ -35,6 +36,10 @@ DEFAULT_HEARTBEAT_INTERVAL = 30.0
DEFAULT_STALL_TIMEOUT = 30.0
DEFAULT_CONNECT_TIMEOUT = 90.0
DEFAULT_HTTP_STALL_TIMEOUT = 180.0
+# Xet workers spent per download before the transport changes. A wedged transfer usually clears on a
+# fresh process, and the retry replays only the in-flight file: the worker runs
+# snapshot_download(max_workers=1), so every finished shard is already a blob and is skipped.
+DEFAULT_XET_ATTEMPTS = 2
# --- lazy shared-backend loader ----------------------------------------------------------------
_shared: Any = None
@@ -286,6 +291,34 @@ def child_should_disable_xet(config: dict) -> bool:
return bool(config.get("disable_xet"))
+def is_data_phase_stall(message: str) -> bool:
+ """Whether a watchdog verdict fired AFTER bytes had flowed (mirrors
+ ``unsloth_zoo.hf_xet_fallback.is_data_phase_stall``).
+
+ "did not start" is the pre-first-byte trip, as likely slow metadata or a cache lock as a broken
+ Xet; the others mean the transfer moved and then wedged, which a fresh worker recovers from. The
+ lifecycle decides both whether to spend another Xet worker and whether to charge a health
+ failure on this one rule, so the two cannot disagree. Local for the same reason as
+ ``child_should_disable_xet``: the stall path must not depend on the heavy import."""
+ return "did not start" not in (message or "")
+
+
+def xet_attempts() -> int:
+ """Xet workers a download may spend before HTTP (mirrors
+ ``unsloth_zoo.hf_xet_fallback.xet_attempts``): ``UNSLOTH_XET_ATTEMPTS``, default 2, clamped to 8;
+ junk or non-positive falls back to the default. ``1`` restores the straight-to-HTTP ladder."""
+ raw = os.environ.get("UNSLOTH_XET_ATTEMPTS")
+ if not raw:
+ return DEFAULT_XET_ATTEMPTS
+ try:
+ value = int(str(raw).strip())
+ except (TypeError, ValueError):
+ return DEFAULT_XET_ATTEMPTS
+ if value <= 0:
+ return DEFAULT_XET_ATTEMPTS
+ return min(value, 8)
+
+
# --- degraded stubs (used only when unsloth_zoo is unavailable) -------------------------------
class _DegradedDownloadStallError(RuntimeError):
"""Stub mirror so callers' ``except`` clauses resolve; never raised in degraded mode."""
@@ -507,8 +540,11 @@ __all__ = [
"DEFAULT_HEARTBEAT_INTERVAL",
"DEFAULT_HTTP_STALL_TIMEOUT",
"DEFAULT_STALL_TIMEOUT",
+ "DEFAULT_XET_ATTEMPTS",
"DownloadStallError",
"child_should_disable_xet",
+ "is_data_phase_stall",
+ "xet_attempts",
"get_hf_download_state",
"record_xet_outcome",
"start_watchdog",