Skip to content

perf(studio): make local model inventory scans linear - #8043

Merged
danielhanchen merged 18 commits into
unslothai:mainfrom
Lyxot:fix/studio-inventory-scan
Aug 8, 2026
Merged

danielhanchen merged 18 commits into
unslothai:mainfrom
Lyxot:fix/studio-inventory-scan

Conversation

@Lyxot

@Lyxot Lyxot commented Aug 6, 2026 •

Copy link
Copy Markdown
Collaborator

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 called entry.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_thread scans 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

  • Enumerate manifest and cancellation state once, index it by exact repository/variant/cache ownership, and reuse the index across repository scans and multiple Hugging Face caches.
  • Preserve legacy unscoped state, cache-scoped state, cancellation-marker fail-closed behavior, expected-size accounting, partial downloads, completed variants, hidden infrastructure repositories, and variant deduplication.
  • Coalesce identical cached-GGUF, cached-model, canonical local, and compatibility local inventory requests into shielded single-flight workers. Changed cache or registered-folder inputs start separate work.
  • Keep read-only lookups non-creating and make Studio-state fixtures use an isolated temporary state root.
  • Handle corrupt, ambiguous, migrated, and orphaned legacy state conservatively without deleting valid active-download state.
  • Deduplicate Transformers shard filesystem probes.
  • Skip the picker mount refresh when its provider was cold at mount; warm picker openings still refresh normally.

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.

Endpoint main samples This branch samples Mean reduction
GET /api/models/local 14,937.67 ms 2,630.70 ms 82.4%
GET /api/hub/cached-gguf 70,982.47 / 71,901.06 ms 2,460.75 / 986.65 / 828.05 ms 98.0%
GET /api/hub/cached-models 27,790.79 / 53,279.54 ms 3,607.73 / 2,554.15 ms 92.4%
GET /api/hub/local 125,786.93 / 100,468.47 ms 2,807.38 / 1,198.98 / 2,734.09 ms 98.0%

The 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

  • 221 Hub backend tests passed.
  • 130 cached/local route tests passed.
  • 725 frontend tests passed.
  • Focused cold/warm mount-policy mutation check passed.
  • TypeScript and Vite production frontend build passed.
  • Real polluted-state benchmarks were read-only and left file/directory counts unchanged.
  • studio/backend/conftest.py remains absent; every affected test uses isolated temporary Studio state.

@Lyxot Lyxot changed the title fix(studio): make local model inventory scans linear perf(studio): make local model inventory scans linear Aug 6, 2026
@Lyxot
Lyxot marked this pull request as ready for review August 6, 2026 16:07
@Lyxot
Lyxot requested a review from danielhanchen as a code owner August 6, 2026 16:07
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: 5fcb51bcd3

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

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.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 7, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen and others added 2 commits August 7, 2026 08:31
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.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 7, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen and others added 2 commits August 7, 2026 08:58
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.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 7, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 7, 2026
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.
@danielhanchen

Copy link
Copy Markdown
Member

Ran the two test files this PR touches on real windows-latest, macos-14 and ubuntu-latest runners. macOS and Linux are green; Windows had three failures, all one root cause, so I pushed f4b82e3dd to the branch.

FAILED hub/tests/test_model_services.py::test_local_inventory_requests_share_scan[folders]
FAILED hub/tests/test_model_services.py::test_local_inventory_requests_share_scan[epoch]
FAILED tests/test_cached_gguf_routes.py::test_compat_local_inventory_requests_share_scan
AssertionError: assert 'd:\\a\\unsloth-staging-2\\unsloth-staging-2\\\x00' == '\x00'

_inventory_path_identity / _compat_inventory_path_identity wrap realpath in except (OSError, UnicodeError, ValueError) to stay total. On POSIX os.path.realpath("\0") raises ValueError, the fallback runs, and normcase is the identity, so the helper echoes the input back. On Windows non-strict realpath swallows that same ValueError internally and falls back to abspath, which joins the process cwd. The helper is still total and still deterministic, which is all the flight key needs, but the returned string is cwd-prefixed.

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: pip scan-packages :: studio and :: hf-stack are failing identically on main (run 31141376695 at 2d231f884), and this PR touches no requirements or lockfile, so they are not from these changes.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 7, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 7, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…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.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 7, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…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.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 7, 2026
@unslothai unslothai deleted a comment from Lyxot Aug 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 7, 2026
@unslothai unslothai deleted a comment from Lyxot Aug 7, 2026
@unslothai unslothai deleted a comment from Lyxot Aug 7, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: b36a2efa9b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

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".

@danielhanchen

Copy link
Copy Markdown
Member

CI summary for b36a2efa9, since the org queue is slow to drain and some of the red is not from this PR. I replicated the full workflow set on my own runners to get a clean read.

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 828s, 3.11 800s, 3.12 782s, 3.13 767s, all green. Upstream agrees where it has finished: 3.10 14m29s, 3.12 12m32s, 3.13 11m54s, all passing.

One thing worth flagging: that leaves very little headroom. Upstream 3.10 passed at 14m29s against a timeout-minutes: 15 cap, so 31 seconds spare, and 3.11 has now been cancelled at the cap twice, both times stalling early rather than running slow. The same commit passes 3.11 in 800s on an uncontended runner, so I read the cancellations as runner contention rather than a code problem, but the margin is thin enough that this job will keep flaking until either the cap goes up or more per-test overhead comes out.

Cross-platform. Ran the two test files this PR touches on real ubuntu-latest, macos-14 and windows-latest: all three green. That took three rounds, since my own regression tests for the undecodable-filename fixes were not portable, which is what f4b82e3dd and part of 50459d493 deal with.

Not from this PR:

  • pip scan-packages :: studio / :: hf-stack / :: extras. The first two fail identically on main (run 31141376695 at 2d231f884), and the findings are in third-party dependency trees (av, dns, scipy, tokenizers). This PR changes no requirements file, lockfile or pyproject.toml, so none of the three can be attributed to it.
  • Repo tests (CPU): tests/python/test_studio_runtime_gate.py::test_terminal_update_holds_the_gate_through_environment_mutation. Fails identically on main alone at 2c8d5a622 with this PR nowhere in the tree. The test does source.index("def _release_self_exe_lock_windows") and that name exists nowhere in the repository except the test itself, so it is looking for something that no longer exists.
  • One tests/test_openai_auto_switch.py::test_idle_loop_unloads_after_ttl_and_stashes_for_reload failure on 3.10 that passed on re-run of the same commit. Timing-dependent, flaky.

@oobabooga

Copy link
Copy Markdown
Member

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.

@danielhanchen
danielhanchen merged commit e96d020 into unslothai:main Aug 8, 2026
53 of 57 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Studio] On Device models take 15–25 seconds to appear after startup

3 participants