Skip to content

Commit 70e50e1

Browse files
committed
Hub: honest offline-resume failure, cancel-watchdog re-probe, plus cleanup
- Fix silent wrong-completion: no-manifest offline resume now fails honestly instead of certifying a partial download as complete - Fix cancel watchdog mislabeling a completed-while-hidden download as "cancelled" (now re-probes the backend before finalizing) - Remove dead DownloadRegistry.persist_cancel_for_key - Simplify snapshot progress: drop always-true use_metadata_total_max param - Stop persisting write-only completeOnDisk in download-manager state - Add/harden hub worker tests for the offline-resume path
1 parent e171cb7 commit 70e50e1

8 files changed

Lines changed: 92 additions & 37 deletions

File tree

‎studio/backend/hub/services/datasets/downloads.py‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,6 @@ async def get_dataset_download_progress_response(
135135
hf_token = hf_token,
136136
registry = _registry,
137137
metadata_resolver = get_dataset_snapshot_metadata_cached,
138-
use_metadata_total_max = True,
139138
)
140139

141140

‎studio/backend/hub/services/models/downloads.py‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -395,7 +395,6 @@ def _metadata_resolver(
395395
registry = _registry,
396396
metadata_resolver = _metadata_resolver,
397397
variant = progress_variant,
398-
use_metadata_total_max = True,
399398
)
400399

401400

@@ -419,7 +418,6 @@ async def get_download_progress_response(
419418
hf_token = hf_token,
420419
registry = _registry,
421420
metadata_resolver = cache_inventory.get_repo_snapshot_metadata_cached,
422-
use_metadata_total_max = True,
423421
)
424422

425423

‎studio/backend/hub/services/snapshot_progress.py‎

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,6 @@ def compute_snapshot_progress(
8484
registry,
8585
metadata_resolver: SnapshotMetadataResolver,
8686
variant: Optional[str] = None,
87-
use_metadata_total_max: bool = False,
8887
) -> dict:
8988
"""Synchronous progress reading. Safe to run under ``asyncio.to_thread``."""
9089
empty = _empty_progress(expected_bytes)
@@ -104,11 +103,11 @@ def compute_snapshot_progress(
104103
# Always resolve the revision's blob hashes (cached) so stale blobs from a
105104
# superseded revision can't inflate the count even when the caller supplied
106105
# a total. Hashes degrade to empty (count-all) only when metadata is
107-
# unavailable, e.g. offline. ``expected_total`` falls back to the resolved
108-
# total only when the caller didn't supply a trustworthy one.
106+
# unavailable, e.g. offline. ``expected_total`` is the larger of the caller's
107+
# figure and the resolved total, so a stale or low caller hint can't cap the
108+
# bar below the revision's real size.
109109
meta_total, expected_hashes = metadata_resolver(repo_id, hf_token)
110-
if expected_total <= 0 or use_metadata_total_max:
111-
expected_total = max(expected_total, meta_total)
110+
expected_total = max(expected_total, meta_total)
112111

113112
# When hashes aren't resolved yet, a variant must not count finalized blobs
114113
# unscoped: sibling quants share one blobs/ dir and would inflate a fresh
@@ -240,7 +239,6 @@ async def snapshot_progress_response(
240239
registry,
241240
metadata_resolver: SnapshotMetadataResolver,
242241
variant: Optional[str] = None,
243-
use_metadata_total_max: bool = False,
244242
) -> dict:
245243
"""Async wrapper: offloads the blocking cache walk and never raises."""
246244
try:
@@ -254,7 +252,6 @@ async def snapshot_progress_response(
254252
registry = registry,
255253
metadata_resolver = metadata_resolver,
256254
variant = variant,
257-
use_metadata_total_max = use_metadata_total_max,
258255
)
259256
except Exception as e:
260257
logger.warning(

‎studio/backend/hub/tests/test_model_services.py‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -584,6 +584,9 @@ def _metadata(*_args, **_kwargs):
584584
monkeypatch.setattr(
585585
download_manifest, "write_manifest", lambda *args: written.append(args) or True
586586
)
587+
monkeypatch.setattr(
588+
hf_cache_state, "has_active_incomplete_blobs", lambda *_args, **_kwargs: False
589+
)
587590
monkeypatch.setitem(
588591
sys.modules,
589592
"huggingface_hub",
@@ -609,6 +612,48 @@ def _metadata(*_args, **_kwargs):
609612
assert verified == [("dataset", "Org/Data", None, str(tmp_path))]
610613

611614

615+
def test_download_snapshot_fails_when_metadata_unavailable_and_partial_remains(
616+
monkeypatch, tmp_path
617+
):
618+
"""No prior manifest + metadata still unavailable on resume + leftover
619+
.incomplete blobs means snapshot_download returned a cached partial without
620+
downloading. The worker must exit 1 (honest, resumable error) instead of
621+
deriving a self-certifying manifest from the finalized subset."""
622+
written = []
623+
verified = []
624+
625+
def _metadata(*_args, **_kwargs):
626+
raise RuntimeError("metadata down")
627+
628+
monkeypatch.setattr(hf_download, "_model_info_with_retry", _metadata)
629+
monkeypatch.setattr(
630+
hf_download, "_verify_completed_download", lambda *args, **kwargs: verified.append(args)
631+
)
632+
monkeypatch.setattr(
633+
download_registry, "prepare_cache_for_transport", lambda *_args, **_kwargs: 0
634+
)
635+
monkeypatch.setattr(download_manifest, "clear_cancel_marker", lambda *_args: None)
636+
monkeypatch.setattr(download_manifest, "read_manifest", lambda *_args, **_kwargs: None)
637+
monkeypatch.setattr(
638+
download_manifest, "write_manifest", lambda *args: written.append(args) or True
639+
)
640+
monkeypatch.setattr(
641+
hf_cache_state, "has_active_incomplete_blobs", lambda *_args, **_kwargs: True
642+
)
643+
monkeypatch.setitem(
644+
sys.modules,
645+
"huggingface_hub",
646+
SimpleNamespace(snapshot_download = lambda **_kwargs: str(tmp_path)),
647+
)
648+
649+
with pytest.raises(SystemExit) as excinfo:
650+
hf_download._download_snapshot("Org/Model", None, "http")
651+
652+
assert excinfo.value.code == 1
653+
assert written == []
654+
assert verified == []
655+
656+
612657
def test_purge_repo_cache_dirs_skips_top_level_symlink(monkeypatch, tmp_path):
613658
root = tmp_path / "hub"
614659
target = tmp_path / "target"

‎studio/backend/hub/utils/download_registry.py‎

Lines changed: 0 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -903,27 +903,6 @@ def get_job_metadata(self, key: str) -> Optional[DownloadMetadata]:
903903
with self._lock:
904904
return self._metadata.get(key)
905905

906-
def persist_cancel_for_key(
907-
self,
908-
key: str,
909-
*,
910-
repo_type: Optional[RepoType] = None,
911-
repo_id: Optional[str] = None,
912-
variant: Optional[str] = None,
913-
transport: Optional[str] = None,
914-
) -> None:
915-
key = normalize_job_key(key)
916-
metadata = self.get_job_metadata(key)
917-
if metadata is not None:
918-
persist_cancel_marker(
919-
metadata.repo_type,
920-
metadata.repo_id,
921-
metadata.variant,
922-
metadata.transport,
923-
)
924-
return
925-
persist_cancel_marker(repo_type, repo_id, variant, transport)
926-
927906
def _generation_matches_locked(
928907
self,
929908
key: str,

‎studio/backend/hub/workers/hf_download.py‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -413,8 +413,16 @@ def _recover_manifest_after_download(
413413
(huggingface_hub's auth/connection fallback returns snapshots/<sha> as-is),
414414
so rebuilding the manifest from the on-disk files here would record the
415415
partial set as the expected set and let _verify_completed_download certify a
416-
half-finished download as complete."""
416+
half-finished download as complete.
417+
418+
The same hazard exists with NO prior manifest: if metadata was unavailable on
419+
the first attempt too, none was written, so the guard above can't fire. When
420+
metadata is still unavailable here, leftover ``.incomplete`` blobs prove
421+
snapshot_download returned a cached partial without downloading, so we fail
422+
(exit 1) instead of deriving a self-certifying manifest from the finalized
423+
subset. The partial is left intact for a later resume."""
417424
from hub.utils import download_manifest
425+
from hub.utils.hf_cache_state import has_active_incomplete_blobs
418426

419427
if download_manifest.read_manifest(repo_type, repo_id, None) is not None:
420428
return
@@ -432,6 +440,17 @@ def _recover_manifest_after_download(
432440
except Exception as e:
433441
reason = f"{type(e).__name__}: {e}"
434442

443+
if has_active_incomplete_blobs(repo_type, repo_id):
444+
print(
445+
f"{label}could not reach Hugging Face for {repo_id} and the copy on "
446+
"disk is still incomplete. Access to a private or restricted repo may "
447+
"have been lost (HF token removed or changed), the connection dropped, "
448+
"or Hugging Face is temporarily unavailable. Set a valid HF token or "
449+
"reconnect, then resume the download.",
450+
file = sys.stderr,
451+
)
452+
sys.exit(1)
453+
435454
fallback_files = download_manifest.expected_files_from_snapshot_dir(
436455
Path(snapshot_path)
437456
)

‎studio/frontend/src/features/hub/download-manager/download-manager-state.ts‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,7 @@ function sanitizePersistedState(
138138

139139
function toPersistedJob(
140140
job: ManagedDownload,
141-
): Omit<ManagedDownload, "bytesPerSec"> {
141+
): Omit<ManagedDownload, "bytesPerSec" | "completeOnDisk"> {
142142
return {
143143
key: job.key,
144144
kind: job.kind,
@@ -147,7 +147,6 @@ function toPersistedJob(
147147
state: job.state,
148148
downloadedBytes: job.downloadedBytes,
149149
completedBytes: job.completedBytes,
150-
completeOnDisk: job.completeOnDisk,
151150
expectedBytes: job.expectedBytes,
152151
fraction: job.fraction,
153152
error: job.error,

‎studio/frontend/src/features/hub/download-manager/poll-loop.ts‎

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -718,12 +718,31 @@ function armCancelWatchdog(
718718
cancelEpoch: number,
719719
): void {
720720
rt.watchdog = window.setTimeout(() => {
721-
const live = runtimeRegistry.runtimes.get(key);
722-
if (!live || live.epoch !== cancelEpoch || !live.cancelRequested) return;
723-
finalize(key, "cancelled");
721+
void resolveCancelWatchdog(key, cancelEpoch);
724722
}, CANCEL_WATCHDOG_MS);
725723
}
726724

725+
async function resolveCancelWatchdog(
726+
key: string,
727+
cancelEpoch: number,
728+
): Promise<void> {
729+
const rt = runtimeRegistry.runtimes.get(key);
730+
if (!rt || rt.epoch !== cancelEpoch || !rt.cancelRequested) return;
731+
const job = getState().jobs[key];
732+
if (!job) return;
733+
const probe = await probeCancelOutcome(key, job, rt, cancelEpoch);
734+
if (probe === "stale") return;
735+
const live = runtimeRegistry.runtimes.get(key);
736+
if (!live || live.epoch !== cancelEpoch || !live.cancelRequested) return;
737+
if (probe.terminal === "complete") {
738+
finalize(key, "complete", { bytes: getState().jobs[key]?.downloadedBytes ?? 0 });
739+
} else if (probe.terminal === "error") {
740+
finalize(key, "error", { error: probe.error });
741+
} else {
742+
finalize(key, "cancelled");
743+
}
744+
}
745+
727746
function applyCancelResult(
728747
key: string,
729748
rt: JobRuntime | undefined,

0 commit comments

Comments
 (0)