Repository navigation
perf(studio): make local model inventory scans linear - #8043
Conversation
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
tmp_path_factory.mktemp scans the whole basetemp on every call to pick the next number, so the new autouse _isolate_studio_home fixture made per-test isolation quadratic in the number of tests. Across the ~17.7k backend tests that added roughly 200s per interpreter and pushed the 3.10, 3.11 and 3.13 jobs past the 15 minute cap. Allocate one session-scoped parent and give each test a counter-named subdirectory, so the per-test cost is a bare mkdir and the isolation guarantee is unchanged.
The pre-scan check only covered the source read. The walk itself takes seconds, which is exactly when a download or a deletion completes, so a repo deleted mid-scan was still listed in the response that came back after the deletion finished. Capture the rows and verify the epoch again before returning, matching what both local-inventory coordinators do. That widens the window in which a flight is superseded, so bound the retry loop as well: eight attempts, then serve the last scan that did confirm its epoch instead of restarting a full cache walk per epoch indefinitely.
The cached path caps its retries; the canonical /api/hub/local loop and the compatibility /api/models/local loop did not, so a churn rate above the scan rate (a batch delete invalidates once per reclaimed variant) kept restarting a full disk walk and the endpoint never returned. Cap both at eight attempts and carry the freshest scan on the sentinel, so the fallback is a one-epoch-stale listing rather than nothing: an empty local list would hide the user's own on-disk models. Read the epoch before the sources and folders each attempt, so a retry after a cache-home switch rescans the new root instead of walking the superseded one again. Classification moves onto the serve path so a discarded scan still costs no GGUF metadata reads.
The two flight-key identity tests pinned the exact string realpath() returns
for an embedded NUL. That is a POSIX result: os.path.realpath("\0") raises
ValueError there, so the helper falls back to normcase(raw) and echoes the
input back. On Windows non-strict realpath swallows the same ValueError and
falls back to abspath, which joins the process cwd, so the helper returns
"d:\...\repo\<nul>" and the assertions fail.
Assert what the flight key actually depends on, that the helper is total and
stable on hostile input, instead of one platform's spelling of it.
Windows runner before: 2 failed 158 passed in hub/tests/test_model_services.py
and 1 failed 127 passed in tests/test_cached_gguf_routes.py. After: green,
matching ubuntu-latest and macos-14.
|
Ran the two test files this PR touches on real
The production code is fine on both platforms. The tests were pinning one platform's spelling, so I changed them to assert the property instead: for hostile in ("\0", "\ud800"):
identity = local_inventory._inventory_path_identity(hostile)
assert identity == local_inventory._inventory_path_identity(hostile)
assert identity.endswith(hostile)That still covers "hostile input does not raise" and adds stability, and it passes on all three OSes. Worth flagging that neither of these files runs on a Windows job in CI today, so this would have landed silently and only bitten someone running the suite locally on Windows. For the record on the current red checks: |
A byte the filesystem encoding cannot decode comes back from iterdir() as a
lone surrogate. Both new state walks hand that name-derived variant to the
path helpers to work out whether the file is written under its canonical
spelling, and sha256(variant.encode("utf-8")) raises UnicodeEncodeError on a
surrogate.
Per-repo reads used to contain that to the repo that owned the file.
build_variant_state_index runs once per scan and outside the per-repository
try in _scan_cached_gguf, so the exception escaped to the endpoint: one
corrupt filename returned 500 for /api/hub/cached-gguf and hid every cached
model. _iter_variant_state_files had the same shape and would abort the
iteration, dropping the repo's valid state alongside the bad entry.
The canonical path only decides the "is this the canonical filename" half of
the entry's priority, so treat an unhashable variant as non-canonical and keep
going. iter_variant_markers now yields the same entries it did before this PR,
surrogate name included.
Reported by Codex on cache_inventory.py:472.
…t build build_variant_state_index runs once per scan and outside the per-repository try, so any repo identity it cannot hash took the whole endpoint with it. A cache directory name holding a byte the filesystem encoding cannot decode arrives from iterdir() as a lone surrogate, _filename_bytes() raises UnicodeEncodeError on it, and /api/hub/cached-gguf answers 500 with every valid row hidden. _scan_cached_models, routes.models and _scan_local_models already caught this and fell back to the per-repo reads the index replaced. _scan_cached_gguf did not, so it gets the same guard and its consumer now tolerates a None index, which _gguf_variant_state_summary already handled. _scan_hf_cache had the mirror image of the problem: it rebuilds the index when its caller passes None, which happens precisely when the caller's own guarded build just failed, so the bare call handed the same exception back and undid that guard. Guarded there too. Costs speed on a broken cache and nothing else. Reported by Codex on cache_inventory.py:472.
…dable A cancel marker whose payload will not parse stays fail-closed but loses its declared variant, so the only identity left is the filename. A variant that cannot be spelled literally (slashes, spaces, `--`, an existing hash prefix) is stored as `@sha256-...`, so that recovered identity is the digest rather than the variant, and the index recorded the marker under the digest. The inventory then asked VariantState.has_marker(variant), missed, and advertised a cancelled variant as complete, while has_cancel_marker still found the same file by rebuilding the same digest. Fail-closed on one path, fail-open on the other, for the same marker. has_marker now falls back to the fragments the variant could have been written under, which is what that per-variant lookup already does. The digest is taken over the normalized variant, so this matches only the variant that produced it. Adds state_dir.variant_key_fragments and refactors the fragment computation out of _entry_key so both spellings come from one place. Also makes the two portability failures from the previous commits pass: the undecodable-byte cases are POSIX-only, since Windows decodes filenames as UTF-8 with surrogatepass (a bare 0xff raises rather than becoming a surrogate) and macOS rejects such a name with EILSEQ at creation. Reported by Codex on download_manifest.py:1312.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Bravo. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
CI summary for Backend CI matrix. All four Python jobs complete now, where before the conftest change three of them were killed at the 15 minute cap at around 86%. Replicated durations: 3.10 One thing worth flagging: that leaves very little headroom. Upstream 3.10 passed at Cross-platform. Ran the two test files this PR touches on real Not from this PR:
|
|
I compared against the merge base rather than main, since unrelated commits sit in between. Read-only scans no longer create the state directories that were feeding the quadratic walk. On a polluted tree the GGUF scan went from 6.76s to 2.24s with the same rows, and all four inventory endpoints return identical payloads. LGTM. |
Summary
Fixes #7849.
Unsloth Studio local-model inventory became extremely slow when the Studio download-state tree contained many cache-scoped directories. This change makes inventory work scale with repositories plus state entries, coalesces concurrent scans, prevents read-only probes from creating state directories, isolates tests from the user's real Studio home, and avoids the frontend's redundant cold-mount refresh.
Root cause
cache_inventory._scan_cached_gguf()asks for manifest and cancellation state for every cached repository. The legacy state iterator rescanned shared state roots per repository and calledentry.is_file()before filtering names, so every cache-scoped directory was statted repeatedly. A polluted tree therefore turned inventory into repositories multiplied by all state entries/directories.Frontend retries and a forced picker refresh amplified the cost: timed-out requests left their
asyncio.to_threadscans running, while later requests launched overlapping or sequential duplicate work.The reproduced installation has approximately 484 GB in the Hugging Face cache, 121 repositories (104 model repositories), and 1,467 files across 23,343 Studio state directories. It includes empty cache-scoped directories and stale pytest records from older test runs.
What changed
Live comparison
These are observed end-to-end request timings from the same polluted installation. Requests overlapped as they do during real Studio page loads and navigation. The table includes every occurrence of each endpoint in the supplied logs and reports the reduction between their arithmetic means; it is not an isolated microbenchmark.
mainsamplesGET /api/models/localGET /api/hub/cached-ggufGET /api/hub/cached-modelsGET /api/hub/localThe final branch log also shows GGUF-variant requests completing in 574.99–829.08 ms while the inventory requests are active. Opening the picker cold no longer intentionally queues a second full refresh behind the provider's initial inventory fetch.
Validation
studio/backend/conftest.pyremains absent; every affected test uses isolated temporary Studio state.