Skip to content

Commit b0152f7

Browse files
committed
fix(hub): harden download watchdog + registry/progress bookkeeping
- worker: wrap the watchdog's stderr diagnostic in try/except so a broken pipe on a dead parent can't kill the thread before os._exit(130) - registry: _repo_active is now a set[str] read from the authoritative _metadata (drops the redundant transport copy), and the 64-job cap eviction moves into _put_terminal_job_locked so the claim/register cancel path enforces it too - lifecycle: read cancel metadata before the terminal set_job so eviction can't drop it first - progress: subtract the companion baseline only while it is still counted in completed_bytes and the variant is not yet verified complete (a departed companion was zeroing genuine progress) - tests: cover the cancel/eviction ordering and the progress-baseline cases
1 parent 62de08d commit b0152f7

5 files changed

Lines changed: 116 additions & 35 deletions

File tree

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

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -266,12 +266,12 @@ def finalize_worker_exit(
266266
except Exception as exc:
267267
logger.debug(f"clear_cancel_marker failed for {repo_id} (rc=0): {exc}")
268268
elif state == "cancelled":
269+
# Read metadata before the terminal set_job so a concurrent eviction
270+
# can't drop it; its original casing is only the offline quant label
271+
# (listing dedupes case-insensitively), the job key the fallback.
272+
metadata = registry.get_job_metadata(key)
269273
registry.set_job(key, "cancelled")
270274
logger.info(f"{log_prefix} cancelled: {label} (rc={rc})")
271-
# Persist the original variant casing from metadata so the marker matches
272-
# the manifest; the lowercased job key is only a fallback once metadata is
273-
# gone. Mismatched casing would otherwise double-list the variant offline.
274-
metadata = registry.get_job_metadata(key)
275275
download_registry.persist_cancel_marker(
276276
repo_type,
277277
repo_id,

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

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -182,13 +182,14 @@ def compute_snapshot_progress(
182182

183183
completed_bytes, in_progress_bytes, cache_path, complete_on_disk = selected
184184
downloaded_bytes = completed_bytes + in_progress_bytes
185-
# While the variant is still downloading, the baseline hides companion bytes
186-
# that were already on disk before this job started. Once it is verified
187-
# complete, report the full figures instead: a baseline equal to the total
188-
# would zero out expected/completed/downloaded and make the frontend read a
189-
# finished variant as 0-byte and evict it as gone.
185+
# Subtract the companion baseline only while it is still counted in
186+
# completed_bytes (else a companion that left the count zeros genuine main
187+
# progress) and the variant is not yet verified complete (else a full-size
188+
# baseline reads a finished variant as 0-byte).
190189
effective_baseline_bytes = (
191-
0 if complete_on_disk else min(completed_baseline_bytes, completed_bytes)
190+
completed_baseline_bytes
191+
if not complete_on_disk and completed_baseline_bytes <= completed_bytes
192+
else 0
192193
)
193194
display_completed_bytes = max(0, completed_bytes - effective_baseline_bytes)
194195
display_downloaded_bytes = max(0, downloaded_bytes - effective_baseline_bytes)

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

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -923,6 +923,81 @@ async def _run_inline(fn, *args, **kwargs):
923923
assert result["progress"] == 0
924924

925925

926+
def test_gguf_progress_shows_main_when_companion_left_the_count(
927+
monkeypatch,
928+
tmp_path,
929+
):
930+
# The mmproj companion that seeded the baseline is gone, so completed_bytes
931+
# is main-only and below the baseline; it must not be subtracted to 0.
932+
entry = tmp_path / "models--Org--Model-GGUF"
933+
blobs = entry / "blobs"
934+
blobs.mkdir(parents = True)
935+
(blobs / "mainhash").write_bytes(b"x" * 20)
936+
monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
937+
938+
requirement = gguf_variants._GgufVariantRequirement(
939+
main_filenames = frozenset({"model-Q4_K_M.gguf"}),
940+
target_filenames = ("model-Q4_K_M.gguf", "mmproj-F16.gguf"),
941+
main_hashes = frozenset({"mainhash"}),
942+
required_hashes = frozenset({"mainhash", "mmprojhash"}),
943+
companion_hashes = frozenset({"mmprojhash"}),
944+
mmproj_filenames = frozenset({"mmproj-F16.gguf"}),
945+
mmproj_hashes = frozenset({"mmprojhash"}),
946+
expected_files = (
947+
download_manifest.ExpectedFile(
948+
path = "model-Q4_K_M.gguf",
949+
size = 100,
950+
sha256 = "mainhash",
951+
),
952+
download_manifest.ExpectedFile(
953+
path = "mmproj-F16.gguf",
954+
size = 30,
955+
sha256 = "mmprojhash",
956+
),
957+
),
958+
main_size_bytes = 100,
959+
download_size_bytes = 130,
960+
)
961+
962+
async def _run_inline(fn, *args, **kwargs):
963+
return fn(*args, **kwargs)
964+
965+
monkeypatch.setattr(downloads.asyncio, "to_thread", _run_inline)
966+
monkeypatch.setattr(
967+
downloads.gguf_variants,
968+
"_gguf_variant_requirements",
969+
lambda *_args, **_kwargs: requirement,
970+
)
971+
monkeypatch.setattr(
972+
snapshot_progress,
973+
"preferred_repo_cache_dirs",
974+
lambda *_args, **_kwargs: [entry],
975+
)
976+
monkeypatch.setattr(
977+
downloads,
978+
"_registry",
979+
SimpleNamespace(
980+
get_job = lambda _key: SimpleNamespace(state = "running"),
981+
get_job_metadata = lambda _key: SimpleNamespace(
982+
completed_baseline_bytes = 30,
983+
),
984+
),
985+
)
986+
987+
result = asyncio.run(
988+
downloads.get_gguf_download_progress_response(
989+
"Org/Model-GGUF",
990+
variant = "Q4_K_M",
991+
expected_bytes = 130,
992+
)
993+
)
994+
995+
assert result["completed_bytes"] == 20
996+
assert result["downloaded_bytes"] == 20
997+
assert result["expected_bytes"] == 130
998+
assert result["complete_on_disk"] is False
999+
1000+
9261001
def test_gguf_progress_complete_on_disk_ignores_full_baseline(
9271002
monkeypatch,
9281003
tmp_path,

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

Lines changed: 20 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -853,7 +853,7 @@ class DownloadRegistry:
853853
def __init__(self, max_terminal: int = 64) -> None:
854854
self._jobs: dict[str, DownloadState] = {}
855855
self._processes: dict[str, subprocess.Popen] = {}
856-
self._repo_active: dict[str, dict[str, str]] = {}
856+
self._repo_active: dict[str, set[str]] = {}
857857
self._metadata: dict[str, DownloadMetadata] = {}
858858
self._pending_cancel: dict[str, Optional[int]] = {}
859859
self._generations: dict[str, int] = {}
@@ -870,6 +870,14 @@ def _put_terminal_job_locked(
870870
) -> None:
871871
self._jobs.pop(key, None)
872872
self._jobs[key] = DownloadState(state, error)
873+
if len(self._jobs) > self._max_terminal:
874+
for stale_key, stale in list(self._jobs.items()):
875+
if stale.state in TERMINAL_STATES and stale_key != key:
876+
self._jobs.pop(stale_key, None)
877+
self._metadata.pop(stale_key, None)
878+
self._generations.pop(stale_key, None)
879+
if len(self._jobs) <= self._max_terminal:
880+
break
873881

874882
def set_job(self, key: str, state: JobState, error: Optional[str] = None) -> None:
875883
key = normalize_job_key(key)
@@ -880,17 +888,9 @@ def set_job(self, key: str, state: JobState, error: Optional[str] = None) -> Non
880888
repo = _repo_of_key(key)
881889
active = self._repo_active.get(repo)
882890
if active is not None:
883-
active.pop(key, None)
891+
active.discard(key)
884892
if not active:
885893
self._repo_active.pop(repo, None)
886-
if len(self._jobs) > self._max_terminal:
887-
for stale_key, stale in list(self._jobs.items()):
888-
if stale.state in TERMINAL_STATES and stale_key != key:
889-
self._jobs.pop(stale_key, None)
890-
self._metadata.pop(stale_key, None)
891-
self._generations.pop(stale_key, None)
892-
if len(self._jobs) <= self._max_terminal:
893-
break
894894
else:
895895
self._jobs[key] = DownloadState(state, error)
896896

@@ -937,7 +937,7 @@ def register_process(self, key: str, proc: subprocess.Popen) -> bool:
937937
repo = _repo_of_key(key)
938938
active = self._repo_active.get(repo)
939939
if active is not None:
940-
active.pop(key, None)
940+
active.discard(key)
941941
if not active:
942942
self._repo_active.pop(repo, None)
943943
else:
@@ -1024,7 +1024,7 @@ def claim(
10241024
None in deleting_scopes or variant_from_key(key) in deleting_scopes
10251025
):
10261026
return False, "deleting"
1027-
active = self._repo_active.get(repo, {})
1027+
active = self._repo_active.get(repo, set())
10281028
stale_keys: list[str] = []
10291029
conflict_state: Optional[str] = None
10301030
for other_key in active:
@@ -1047,14 +1047,14 @@ def claim(
10471047
and other_metadata is not None
10481048
and other_metadata.repo_type == "model"
10491049
and bool(other_metadata.variant)
1050-
and active.get(other_key) == transport
1050+
and other_metadata.transport == transport
10511051
)
10521052
if concurrent_gguf_variants:
10531053
continue
10541054
conflict_state = other_status.state
10551055
break
10561056
for stale_key in stale_keys:
1057-
active.pop(stale_key, None)
1057+
active.discard(stale_key)
10581058
if conflict_state is not None:
10591059
return False, conflict_state
10601060
current = self._jobs.get(key, DownloadState("idle")).state
@@ -1063,7 +1063,7 @@ def claim(
10631063
self._generation_seq += 1
10641064
self._generations[key] = self._generation_seq
10651065
self._jobs[key] = DownloadState("running")
1066-
self._repo_active.setdefault(repo, active)[key] = transport
1066+
self._repo_active.setdefault(repo, active).add(key)
10671067
if repo_type and repo_id:
10681068
self._metadata[key] = DownloadMetadata(
10691069
repo_type = repo_type,
@@ -1106,7 +1106,7 @@ def _delete_blocked_by_active_locked(
11061106
download. A variant delete conflicts only with that same variant or a
11071107
whole-repo (non-variant) download writing the shared snapshot; other
11081108
quantizations of the repo download concurrently and never block it."""
1109-
for key in self._repo_active.get(repo_id, {}):
1109+
for key in self._repo_active.get(repo_id, set()):
11101110
job = self._jobs.get(key)
11111111
if job is None or job.state not in _ACTIVE_STATES:
11121112
continue
@@ -1126,7 +1126,7 @@ def peer_blob_hashes(self, key: str) -> frozenset[str]:
11261126
repo = _repo_of_key(key)
11271127
out: set[str] = set()
11281128
with self._lock:
1129-
for other_key in self._repo_active.get(repo, {}):
1129+
for other_key in self._repo_active.get(repo, set()):
11301130
if other_key == key:
11311131
continue
11321132
job = self._jobs.get(other_key)
@@ -1142,7 +1142,7 @@ def active_jobs(self, repo_id: str) -> dict[str, str]:
11421142
repo_id = normalize_repo_key(repo_id)
11431143
with self._lock:
11441144
result: dict[str, str] = {}
1145-
for key in self._repo_active.get(repo_id, {}):
1145+
for key in self._repo_active.get(repo_id, set()):
11461146
job = self._jobs.get(key)
11471147
if job is not None and job.state in _ACTIVE_STATES:
11481148
metadata = self._metadata.get(key)
@@ -1158,7 +1158,7 @@ def active_job_refs(self, repo_id: Optional[str] = None) -> list[ActiveDownloadR
11581158
repo_key = normalize_repo_key(repo_id) if repo_id else None
11591159
with self._lock:
11601160
if repo_key:
1161-
candidate_keys = list(self._repo_active.get(repo_key, {}))
1161+
candidate_keys = list(self._repo_active.get(repo_key, set()))
11621162
else:
11631163
candidate_keys = [
11641164
key for active in self._repo_active.values() for key in active
@@ -1214,7 +1214,7 @@ def has_active_peer_variant(self, repo_id: str, variant: Optional[str]) -> bool:
12141214
repo_id = normalize_repo_key(repo_id)
12151215
target = (variant or "").strip().lower() or None
12161216
with self._lock:
1217-
for key in self._repo_active.get(repo_id, {}):
1217+
for key in self._repo_active.get(repo_id, set()):
12181218
job = self._jobs.get(key)
12191219
if job is None or job.state not in _ACTIVE_STATES:
12201220
continue

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

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -148,11 +148,16 @@ def _terminate_orphaned_self() -> None:
148148
# the main thread is GIL-blocked in a C socket read (the reason the parent
149149
# cancel path uses SIGKILL); the partial .incomplete resumes byte-exact and
150150
# marker/manifest writes are atomic, so the cancelled code 130 is safe here.
151-
print(
152-
"Parent process exited; stopping orphaned download worker.",
153-
file = sys.stderr,
154-
)
155-
sys.stderr.flush()
151+
# The diagnostic is best-effort: a dead parent closes its stderr pipe read
152+
# end, so the write can raise BrokenPipeError and must never preempt the exit.
153+
try:
154+
print(
155+
"Parent process exited; stopping orphaned download worker.",
156+
file = sys.stderr,
157+
)
158+
sys.stderr.flush()
159+
except Exception:
160+
pass
156161
os._exit(130)
157162

158163

0 commit comments

Comments
 (0)