Skip to content

Commit bb93a06

Browse files
committed
Hub: fix GGUF download progress dip + backend hardening
- Fix the GGUF progress dip (~99% to ~56%) when two quants from the same repo download at once: retain the variant list across a same-repo refetch so a finishing quant's bar no longer rebinds to a still-downloading sibling - Keep a finished quant "On device" when the post-download refetch fails or lags, instead of reverting to "Partial" (durable completion memory) - Surface a failed variant refetch as a non-blocking "Retry" rather than a silent stale list, leaving the on-device Run button enabled - Run HF repo-case resolution off the event loop (asyncio.to_thread) in all async hub handlers (status, active, download, cancel, delete) - Scope a variant's in-progress (.incomplete) blob scan so a sibling quant's bytes never leak into its progress - Use the correct WinDLL(use_last_error)+argtypes/restype ctypes idiom for the Windows process-liveness probes - Remove dead InventoryHint hint-injection plumbing from the inventory hook/store and download cards - Add regression tests for the two-quant progress scenario - Fix a pre-existing hub test: inline asyncio.to_thread so asyncio.run's executor shutdown no longer trips the test's Thread monkeypatch
1 parent 70e50e1 commit bb93a06

20 files changed

Lines changed: 299 additions & 113 deletions

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

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -385,7 +385,9 @@ async def delete_cached_dataset_response(repo_id: str) -> dict:
385385
if not _is_valid_repo_id(repo_id):
386386
raise HTTPException(status_code = 400, detail = "Invalid repo_id format")
387387

388-
repo_key = resolve_cached_repo_id_case(repo_id, repo_type = "dataset")
388+
repo_key = await asyncio.to_thread(
389+
resolve_cached_repo_id_case, repo_id, repo_type = "dataset"
390+
)
389391
if not downloads.registry.begin_delete(repo_key):
390392
raise HTTPException(
391393
status_code = 400,

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

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55

66
from __future__ import annotations
77

8+
import asyncio
89
import threading
910
import time
1011
from collections import OrderedDict
@@ -162,7 +163,9 @@ async def download_dataset_response(
162163
detail = f"Invalid repo_id: {repo_id!r}",
163164
)
164165
# Canonicalize so two different-cased paste-ins share one job + cache dir.
165-
repo_id = resolve_cached_repo_id_case(repo_id, repo_type = "dataset")
166+
repo_id = await asyncio.to_thread(
167+
resolve_cached_repo_id_case, repo_id, repo_type = "dataset"
168+
)
166169
key = _download_job_key(repo_id)
167170

168171
transport = download_lifecycle.resolve_transport(body.use_xet)
@@ -219,7 +222,9 @@ async def cancel_dataset_download_response(body: CancelDatasetDownloadRequest) -
219222
status_code = 400,
220223
detail = f"Invalid repo_id: {repo_id!r}",
221224
)
222-
repo_id = resolve_cached_repo_id_case(repo_id, repo_type = "dataset")
225+
repo_id = await asyncio.to_thread(
226+
resolve_cached_repo_id_case, repo_id, repo_type = "dataset"
227+
)
223228
key = _download_job_key(repo_id)
224229

225230
state = download_lifecycle.cancel_worker(
@@ -239,7 +244,9 @@ async def get_dataset_download_status_response(
239244
repo_id = repo_id.strip()
240245
if not _is_valid_repo_id(repo_id):
241246
return DatasetDownloadJobStatus(state = "idle")
242-
repo_id = resolve_cached_repo_id_case(repo_id, repo_type = "dataset")
247+
repo_id = await asyncio.to_thread(
248+
resolve_cached_repo_id_case, repo_id, repo_type = "dataset"
249+
)
243250
return _dataset_status(_download_job_key(repo_id), repo_id = repo_id)
244251

245252

@@ -250,7 +257,9 @@ async def get_active_dataset_downloads_response(
250257
if repo_id and not _is_valid_repo_id(repo_id):
251258
return ActiveDownloadsResponse(downloads = [])
252259
canonical_repo_id = (
253-
resolve_cached_repo_id_case(repo_id, repo_type = "dataset") if repo_id else None
260+
await asyncio.to_thread(resolve_cached_repo_id_case, repo_id, repo_type = "dataset")
261+
if repo_id
262+
else None
254263
)
255264
return ActiveDownloadsResponse(
256265
downloads = download_lifecycle.active_download_refs(

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

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -359,7 +359,9 @@ async def delete_cached_model_response(
359359
detail = "Unload the model before deleting",
360360
)
361361

362-
repo_key = resolve_cached_repo_id_case(repo_id, repo_type = "model")
362+
repo_key = await asyncio.to_thread(
363+
resolve_cached_repo_id_case, repo_id, repo_type = "model"
364+
)
363365
if not downloads.registry.begin_delete(repo_key, variant):
364366
detail = (
365367
f"Cancel the {variant} download before deleting it."

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

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,9 @@ async def download_model_response(
8989
detail = f"Invalid repo_id: {repo_id!r}",
9090
)
9191
# Canonicalize so two different-cased paste-ins share one job + cache dir.
92-
repo_id = resolve_cached_repo_id_case(repo_id, repo_type = "model")
92+
repo_id = await asyncio.to_thread(
93+
resolve_cached_repo_id_case, repo_id, repo_type = "model"
94+
)
9395

9496
variant = (body.gguf_variant or "").strip() or None
9597
if variant is not None and not _is_valid_gguf_variant(variant):
@@ -203,7 +205,9 @@ async def cancel_download_model_response(body: CancelDownloadRequest):
203205
status_code = 400,
204206
detail = f"Invalid repo_id: {repo_id!r}",
205207
)
206-
repo_id = resolve_cached_repo_id_case(repo_id, repo_type = "model")
208+
repo_id = await asyncio.to_thread(
209+
resolve_cached_repo_id_case, repo_id, repo_type = "model"
210+
)
207211
variant = (body.gguf_variant or "").strip() or None
208212
if variant is not None and not _is_valid_gguf_variant(variant):
209213
raise HTTPException(
@@ -229,7 +233,9 @@ async def get_download_status_response(
229233
repo_id = repo_id.strip()
230234
if not _is_valid_repo_id(repo_id):
231235
return DownloadJobStatus(state = "idle")
232-
repo_id = resolve_cached_repo_id_case(repo_id, repo_type = "model")
236+
repo_id = await asyncio.to_thread(
237+
resolve_cached_repo_id_case, repo_id, repo_type = "model"
238+
)
233239
variant = (gguf_variant or "").strip() or None
234240
key = _download_job_key(repo_id, variant)
235241
return _job_status(key, repo_id = repo_id, variant = variant)
@@ -241,7 +247,9 @@ async def get_active_downloads_response(repo_id: str = "") -> ActiveDownloadsRes
241247
if repo_id and not _is_valid_repo_id(repo_id):
242248
return ActiveDownloadsResponse(downloads = [])
243249
canonical_repo_id = (
244-
resolve_cached_repo_id_case(repo_id, repo_type = "model") if repo_id else None
250+
await asyncio.to_thread(resolve_cached_repo_id_case, repo_id, repo_type = "model")
251+
if repo_id
252+
else None
245253
)
246254
return ActiveDownloadsResponse(
247255
downloads = download_lifecycle.active_download_refs(

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

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -109,9 +109,12 @@ def compute_snapshot_progress(
109109
meta_total, expected_hashes = metadata_resolver(repo_id, hf_token)
110110
expected_total = max(expected_total, meta_total)
111111

112-
# When hashes aren't resolved yet, a variant must not count finalized blobs
113-
# unscoped: sibling quants share one blobs/ dir and would inflate a fresh
114-
# variant. In-progress (.incomplete) blobs are always counted (own writes).
112+
# When hashes aren't resolved yet, a variant must not count UNSCOPED blobs
113+
# (finalized or .incomplete): sibling quants share one blobs/ dir, so a
114+
# sibling's bytes would be attributed to this variant. Counting a sibling's
115+
# .incomplete is what makes the bar jump backward (e.g. ~99% -> ~78%) the
116+
# instant this variant finalizes and its own finalized blob is dropped
117+
# unscoped. A no-variant snapshot owns the whole dir, so it counts unscoped.
115118
count_finalized_unscoped = variant is None
116119

117120
readings: list[tuple[int, int, Optional[str], bool]] = []
@@ -137,7 +140,10 @@ def compute_snapshot_progress(
137140
continue
138141
if f.name.endswith(INCOMPLETE_SUFFIX):
139142
blob_hash = f.name[: -len(INCOMPLETE_SUFFIX)]
140-
if expected_hashes and blob_hash not in expected_hashes:
143+
if expected_hashes:
144+
if blob_hash not in expected_hashes:
145+
continue
146+
elif not count_finalized_unscoped:
141147
continue
142148
in_progress_bytes += blob_bytes_present(f)
143149
else:

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

Lines changed: 85 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1152,19 +1152,25 @@ async def _run_inline(fn, *args, **kwargs):
11521152
assert result["complete_on_disk"] is False
11531153

11541154

1155-
def test_gguf_progress_unknown_hashes_still_counts_in_progress_blob(
1155+
def test_gguf_progress_unknown_hashes_drops_unscoped_incomplete_blob(
11561156
monkeypatch,
11571157
tmp_path,
11581158
):
1159-
# Even when the variant's hashes are unresolved, an in-progress
1160-
# (.incomplete) blob is this download's own active write and MUST be
1161-
# counted, so the bar shows real progress instead of a stuck 0% while the
1162-
# worker downloads and metadata/the manifest are still resolving. A
1163-
# finalized sibling blob present at the same time must still be ignored.
1159+
# When a variant's hashes are unresolved, an .incomplete blob in the shared
1160+
# per-repo blobs/ dir CANNOT be attributed to this variant: with two quants
1161+
# of one repo downloading at once, that .incomplete may be a sibling's own
1162+
# active write. Counting it leaks the sibling's bytes into this variant's
1163+
# numerator, which is what makes the bar jump backward (e.g. to ~78%) the
1164+
# instant this variant finalizes and its finalized blob is dropped unscoped.
1165+
# So an unscoped .incomplete is dropped for a variant, mirroring how the
1166+
# finalized-blob branch already drops unscoped blobs (the "instant ~900 MB"
1167+
# guard). In production the worker writes the variant manifest BEFORE any
1168+
# .incomplete blob exists, so hashes resolve via the manifest backstop and
1169+
# this empty-hashes window does not actually suppress real own progress.
11641170
entry = tmp_path / "models--Org--Model-GGUF"
11651171
blobs = entry / "blobs"
11661172
blobs.mkdir(parents = True)
1167-
(blobs / "activehash.incomplete").write_bytes(b"x" * 50) # this download
1173+
(blobs / "activehash.incomplete").write_bytes(b"x" * 50) # unattributable
11681174
(blobs / "siblinghash").write_bytes(b"z" * 900) # finalized sibling
11691175

11701176
async def _run_inline(fn, *args, **kwargs):
@@ -1200,8 +1206,73 @@ async def _run_inline(fn, *args, **kwargs):
12001206
)
12011207
)
12021208

1203-
assert result["downloaded_bytes"] == 50 # the .incomplete, not the sibling
1204-
assert result["completed_bytes"] == 0 # finalized sibling ignored
1209+
assert result["downloaded_bytes"] == 0 # unscoped .incomplete not leaked
1210+
assert result["completed_bytes"] == 0 # finalized sibling still ignored
1211+
1212+
1213+
def test_gguf_progress_unknown_hashes_no_backward_dip_when_variant_finalizes(
1214+
monkeypatch,
1215+
tmp_path,
1216+
):
1217+
# Regression for the two-variant dip: with hashes unresolved (empty), the
1218+
# first quant finalizes (its finalized blob is correctly dropped unscoped)
1219+
# while the sibling quant is still writing its own .incomplete. Before the
1220+
# fix the sibling's in-progress bytes leaked into this variant's numerator,
1221+
# so the bar jumped from ~99% backward to ~78% (sibling_partial / own_total)
1222+
# for one poll before flipping to On Device. The unscoped .incomplete must
1223+
# be dropped so the reading stays 0 (no leak) instead of the sibling ratio.
1224+
entry = tmp_path / "models--unsloth--SmolLM2-360M-Instruct-GGUF"
1225+
blobs = entry / "blobs"
1226+
snap = entry / "snapshots" / "rev0"
1227+
blobs.mkdir(parents = True)
1228+
snap.mkdir(parents = True)
1229+
own_total = 218_673_760 # Q2_K finished blob size (denominator)
1230+
sibling_total = 234_686_560 # Q3_K_M total
1231+
def _sparse_file(path: Path, size: int) -> None:
1232+
with path.open("wb") as handle:
1233+
handle.truncate(size)
1234+
1235+
own_finalized = blobs / "q2hash"
1236+
_sparse_file(own_finalized, own_total)
1237+
# ~72.7% of the sibling => sibling_partial / own_total == 0.78 pre-fix.
1238+
sibling_incomplete = blobs / "q3hash.incomplete"
1239+
_sparse_file(sibling_incomplete, int(sibling_total * 0.727))
1240+
1241+
async def _run_inline(fn, *args, **kwargs):
1242+
return fn(*args, **kwargs)
1243+
1244+
monkeypatch.setattr(downloads.asyncio, "to_thread", _run_inline)
1245+
monkeypatch.setattr(
1246+
downloads.gguf_variants,
1247+
"_gguf_variant_requirements",
1248+
lambda *_args, **_kwargs: None,
1249+
)
1250+
monkeypatch.setattr(
1251+
downloads.gguf_variants,
1252+
"_gguf_variant_blob_hashes",
1253+
lambda *_args, **_kwargs: frozenset(),
1254+
)
1255+
monkeypatch.setattr(
1256+
snapshot_progress,
1257+
"preferred_repo_cache_dirs",
1258+
lambda *_args, **_kwargs: [entry],
1259+
)
1260+
monkeypatch.setattr(
1261+
downloads,
1262+
"_registry",
1263+
SimpleNamespace(get_job = lambda _key: SimpleNamespace(state = "running")),
1264+
)
1265+
1266+
result = asyncio.run(
1267+
downloads.get_gguf_download_progress_response(
1268+
"unsloth/SmolLM2-360M-Instruct-GGUF",
1269+
variant = "Q2_K",
1270+
expected_bytes = own_total,
1271+
)
1272+
)
1273+
1274+
assert result["downloaded_bytes"] == 0 # sibling .incomplete did not leak
1275+
assert result["progress"] == 0 # no ~0.78 backward dip
12051276

12061277

12071278
def test_hf_cache_model_file_probe_is_bounded(monkeypatch, tmp_path):
@@ -2350,6 +2421,11 @@ def start(self):
23502421
lambda: invalidated.append(True),
23512422
)
23522423

2424+
async def _inline_to_thread(func, *args, **kwargs):
2425+
return func(*args, **kwargs)
2426+
2427+
monkeypatch.setattr(downloads.asyncio, "to_thread", _inline_to_thread)
2428+
23532429
result = asyncio.run(
23542430
downloads.download_model_response(
23552431
SimpleNamespace(repo_id = "Org/Model", gguf_variant = None, use_xet = False)

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

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -164,13 +164,19 @@ def _safe_unlink(path: Path) -> None:
164164
def _process_alive(pid: int) -> bool:
165165
if sys.platform == "win32":
166166
import ctypes
167+
from ctypes import wintypes
167168

168169
SYNCHRONIZE = 0x00100000
169170
ERROR_INVALID_PARAMETER = 87
170-
kernel32 = ctypes.windll.kernel32
171+
kernel32 = ctypes.WinDLL("kernel32", use_last_error = True)
172+
kernel32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
173+
kernel32.OpenProcess.restype = wintypes.HANDLE
174+
kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
175+
kernel32.CloseHandle.restype = wintypes.BOOL
176+
ctypes.set_last_error(0)
171177
handle = kernel32.OpenProcess(SYNCHRONIZE, False, pid)
172178
if not handle:
173-
return kernel32.GetLastError() != ERROR_INVALID_PARAMETER
179+
return ctypes.get_last_error() != ERROR_INVALID_PARAMETER
174180
kernel32.CloseHandle(handle)
175181
return True
176182
try:

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

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -114,14 +114,22 @@ def _parent_is_alive(parent_pid: int) -> bool:
114114
"""
115115
if sys.platform == "win32":
116116
import ctypes
117+
from ctypes import wintypes
117118

118119
SYNCHRONIZE = 0x00100000
119120
WAIT_OBJECT_0 = 0x0
120121
ERROR_INVALID_PARAMETER = 87
121-
kernel32 = ctypes.windll.kernel32
122+
kernel32 = ctypes.WinDLL("kernel32", use_last_error = True)
123+
kernel32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
124+
kernel32.OpenProcess.restype = wintypes.HANDLE
125+
kernel32.WaitForSingleObject.argtypes = [wintypes.HANDLE, wintypes.DWORD]
126+
kernel32.WaitForSingleObject.restype = wintypes.DWORD
127+
kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
128+
kernel32.CloseHandle.restype = wintypes.BOOL
129+
ctypes.set_last_error(0)
122130
handle = kernel32.OpenProcess(SYNCHRONIZE, False, parent_pid)
123131
if not handle:
124-
return kernel32.GetLastError() != ERROR_INVALID_PARAMETER
132+
return ctypes.get_last_error() != ERROR_INVALID_PARAMETER
125133
try:
126134
return kernel32.WaitForSingleObject(handle, 0) != WAIT_OBJECT_0
127135
finally:

‎studio/frontend/src/features/hub/catalog/dataset-download-section.tsx‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@ import {
2525
DownloadActionButton,
2626
DownloadCard,
2727
} from "./download-card";
28-
import type { InventoryHint } from "../inventory";
2928
import { useCardDelete } from "./use-card-delete";
3029
import { useDownloadCardState } from "./use-download-card-state";
3130

@@ -46,7 +45,7 @@ export function DatasetDownloadSection({
4645
cachePath?: string | null;
4746
knownBytes?: number | null;
4847
onTrain?: () => void;
49-
onChange?: (hint?: InventoryHint) => void;
48+
onChange?: () => void;
5049
}) {
5150
const hfToken = useHfTokenStore((s) => s.token);
5251
const [deleteOpen, setDeleteOpen] = useState(false);

‎studio/frontend/src/features/hub/catalog/download-section.tsx‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,7 @@
33

44
import { GgufDownloadCard } from "./gguf-download-card";
55
import { SafetensorsDownloadCard } from "./safetensors-download-card";
6-
import type { InventoryHint, ModelInventoryFormat } from "../inventory";
7-
8-
export type { InventoryHint } from "../inventory";
6+
import type { ModelInventoryFormat } from "../inventory";
97

108
export function DownloadSection({
119
repoId,
@@ -44,7 +42,7 @@ export function DownloadSection({
4442
onLoad: (opts: { ggufVariant?: string; expectedBytes?: number }) => void;
4543
onUseInChat?: () => void;
4644
onTrain?: () => void;
47-
onChange?: (hint?: InventoryHint) => void;
45+
onChange?: () => void;
4846
}) {
4947
if (isGguf) {
5048
return (

0 commit comments

Comments
 (0)