Skip to content

Studio: optimize model picker scans with shared inventory caching - #8381

Merged
danielhanchen merged 5 commits into
unslothai:mainfrom
oobabooga:fix/studio-model-inventory-scan-cache
Aug 11, 2026
Merged

danielhanchen merged 5 commits into
unslothai:mainfrom
oobabooga:fix/studio-model-inventory-scan-cache

Conversation

@oobabooga

Copy link
Copy Markdown
Member

Opening Studio's model picker repeatedly scans the same model folders, even when Chat completed the same scan only seconds earlier. Each unnecessary scan took 0.6 to 2.8 seconds on the test machine and repeated the same disk and CPU work.

This change makes Chat and the model picker use the same inventory result. A completed scan can be reused for 30 seconds, and a picker opened while a scan is running joins that scan instead of scheduling another one.

What changed

  • Deleting a model or changing the configured scan folders still forces a new scan immediately.
  • An empty result is confirmed with one real second scan before Studio treats it as settled. That confirmed empty result can then be reused across picker opens for 30 seconds.
  • A failed scan is retried, and changing the inventory key clears the previous result's freshness.

Results

Scenario: load /chat, wait 8 seconds, then open and close the model picker three times.

Observed in the browser Main This change
Local inventory requests 5 1
Request durations 0.584s, 2.795s, 2.534s, 2.300s, 1.732s 0.843s

Testing

  • node --experimental-strip-types --test tests/inventory-freshness.test.ts tests/inventory-settlement.test.ts (9 passed)
  • npm run typecheck
  • npm run build
  • Repeated the picker-open scenario in a live browser against main and this branch.

@danielhanchen

Copy link
Copy Markdown
Member

Reviewed and measured this one. It does what it says, and by a wider margin than the description claims.

Verification

Frontend gate at a6590c450: npm test 1620 passed / 0 failed, npm run typecheck clean, npm run build clean.

The red checks on this PR are all pre-existing on main at unrelated SHAs, not caused by the change:

  • Chat UI Tests fails at Image model full-footprint selector regression (Playwright), which also fails on main at e7417a38d and 08dfbdf45.
  • (Python 3.10-3.13) Backend tests, Core (HF=latest + TRL=latest) and pip scan-packages are Python backend jobs (diffusers version, db tests); this PR touches no Python.

Measurement

Two isolated Studio installs from install.sh --local, merge base af53029c1 vs head a6590c450, driven by the same Playwright scene against a custom scan folder holding 120 stub GGUFs. Counts are requests observed in the browser, not in a log.

Scenario: load /chat, wait 8s, open and close the model picker 3 times.

Merge base This PR
Inventory requests, total 13 3
/api/models/local 4 0
/api/hub/local 3 1
/api/hub/cached-gguf 3 1
/api/hub/cached-models 3 1
The 3 picker opens alone 12 2
Request time 0.81s 0.13s

Worth calling out the /api/models/local row, because it is easy to miss and it is the biggest single win: Chat's own listLocalModels() calls a different route from the shared inventory's /api/hub/local. My first pass counted only the /api/hub/* paths and scored main at 9 rather than 13, hiding exactly the call this PR removes.

The one thing I went looking for, and did not find

use-hub-inventory confirms an empty inventory with one extra forced scan before it treats the emptiness as settled. On main that is a one-shot latch on lastEmptyRevalidationSignature; here it becomes !emptyRevalidationFresh, which is the same 30s timer, driven by a const now = Date.now() read in the render body. Nothing schedules a render at the 30s boundary, but plenty of things render this hook incidentally, so on paper the confirmation can re-arm and a user sitting on an empty inventory pays a new forced rescan every 30s. A render-every-second simulation of both versions gives 1 forced rescan over 120s on main and 4 on this branch.

Live it does not happen. An open picker on an empty Studio, left alone:

Merge base This PR
Inventory requests over 90s 7 5
Inventory requests over 300s 7 5

Same numbers at both windows, so the renders that would re-arm it are not occurring. Not a blocker, just the fragile part of the change: it now depends on render cadence rather than on a latch.

One behaviour note

Chat's local model list moves from /api/models/local to /api/hub/local, and those are two separate implementations. The hub one caps a custom scan folder at _MAX_MODELS_PER_CUSTOM_FOLDER = 200 (local_inventory.py:790); the compat one does not. On the 120-stub folder above they answer 242 rows and 202. So a user with more than 200 entries in a single custom folder will see fewer models in Chat's local list than before. That is a pre-existing backend divergence rather than something this PR introduces, and the flip side is that Chat and the picker now agree with each other, which they did not past that cap. Flagging it so it is a decision rather than a surprise.

No screenshots: the picker renders identically on both sides, as it should for a change about when a scan runs. Posting a pair here would prove nothing.

Also note #8043 attacks the same problem from the backend with no file overlap, so the two are complementary rather than competing.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: a6590c450e

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

Date.now() follows the system clock, so an NTP correction, a VM resume or a
user editing the clock can leave a refresh stamp in the future. now - stamp is
then negative, which read as younger than the freshness window: every picker
open reused, and the local model list stayed frozen for the length of the skew.
refreshIfOlderThan(0), which means refresh unconditionally, became a no-op the
same way.

Share one isInventoryStampFresh helper between the reuse decision and the
empty-inventory revalidation check so the guard cannot be missed in one of
them.
danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Aug 11, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member

Pushed one fix to this branch (8162d7f) after simulating the change rather than only reading it. Details below, including what I could not break.

The bug: a backwards clock step freezes the inventory

Date.now() follows the system clock, and the freshness window subtracts two of its readings. Only performance.now() is monotonic (MDN, HR-Time); an NTP correction larger than about 125ms steps the wall clock rather than slewing it, and a VM resume or a user editing the clock does the same.

When the clock steps backwards, now - refreshedAt goes negative. Negative is < maxAgeMs, so inventoryRefreshDecision returned reuse, and Studio stopped scanning for the whole length of the skew. emptyRevalidationFresh in use-hub-inventory.ts had the identical shape. The sharpest form: refreshIfOlderThan(0) means "refresh unconditionally", and it became a no-op.

The fix is one shared helper so the guard cannot be present in one place and missing in the other:

export function isInventoryStampFresh(stamp: number | null, now: number, maxAgeMs: number) {
  if (stamp === null) return false;
  const age = now - stamp;
  return age >= 0 && age < Math.max(0, maxAgeMs);
}

Three regression tests added to tests/inventory-freshness.test.ts.

How it was found and what else was checked

I wrote the failure modes down first and then built simulations to decide each one.

Layer What it does Result
Exhaustive unit Cartesian over inventoryRefreshDecision (ready x loading x error x key match x 7 stamp positions x 3 max ages) and all 2^5 resolveInventorySettlement inputs, checked against a written spec rather than against the implementation: 568 cases 6 failures, all the future-stamp case. 568/568 after the fix
Real store, faked transport The actual use-device-inventory store in node across 15 scenarios: in-flight join, force-during-flight queue collapsing, error then retry, key change mid-flight, token-fingerprint switch, double mount, 25 rapid opens 15/15 pass, unchanged by the fix
Browser matrix chromium, firefox and webkit against a real Studio: three opens inside the window, then one past it, asserting the picker actually opened Identical on all three: 2 scans for three opens inside, 3 after expiry
Install paths The PR installed into an isolated uv pip venv home, and installed over a pre-PR home in place Fresh boots clean. Upgrade keeps the old credential, the scan folders and all 202 local models
Cross-OS CI ubuntu-latest, macos-14, windows-latest plus a live Playwright run, on a staging repo All green

Re-measured the original scenario at the fixed head to confirm the fix did not cost anything: still 13 inventory requests -> 3, the three picker opens alone still 12 -> 2, 0.88s -> 0.13s of request time. Idle on an empty inventory is unchanged at 7 -> 5 over both 90s and 300s.

On breaking existing installs

Deliberately checked, all negative:

  • No GPU or hardware path is touched. The diff is studio/frontend/src/features/{chat,hub,model-picker} plus tests, so there is no accelerator branch to regress.
  • No new backend dependency. /api/hub/local is already called by main's picker, so an old backend with a new frontend is no worse off than today.
  • No persisted state. useDeviceInventoryStore has no persist middleware, so refreshedAt and revalidatedAt are memory-only and there is no stored shape for an old install to carry in.
  • Worth noting the installer's rollback works: I broke a build on purpose mid-run and it restored the previous environment cleanly.

Two things left alone, on purpose

  1. const now = Date.now() is read in the render body of use-hub-inventory.ts. It is impure, but it feeds inventorySettled, which consumers read during render, so it cannot move into the effect without breaking the settled state. Left as is.
  2. Chat's local list moves from /api/models/local to /api/hub/local, and only the latter caps a custom folder at _MAX_MODELS_PER_CUSTOM_FOLDER = 200 (local_inventory.py:790). On a 120-model folder they answer 242 rows and 202. That is a pre-existing divergence between two backend routes rather than something this PR introduces, and the upside is that Chat and the picker now agree past that cap. Flagging rather than widening this PR; happy to open a separate one for the backend if you want them reconciled.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

The compat /api/models/local endpoint and the shared /api/hub/local inventory
do not agree on three points, and moving Chat across lost models on each.

Ollama: the compat scanner labelled pulled models "custom", the shared one
reports source "ollama", so the source filter dropped every Ollama model.

Multi-format directories: the shared inventory keys a row on (format, path),
so a directory holding GGUF and safetensors weights arrives as two rows with
one load id. The selector keys on that id, so both collided on a React key and
rendered as selected together. Collapse to one option per load id, as the
compat endpoint returned.

Empty revalidation: any forced scan stamped revalidatedAt, so a manual refresh
of a populated inventory that came back empty recorded itself as its own
confirmation and settled the picker on "no models" after one scan. Stamp only
when the scan confirms an inventory that was already observed empty.

Chat's mapping moves to local-model-options.ts so it can be tested directly.
danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Aug 11, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

The revalidation stamp means an empty inventory has been seen twice, so a scan
that returns rows has to clear it. It did not: the stamp was decided from the
previous state alone, so a forced scan that found rows kept refreshing it, and
a later first empty scan inside the 30s window read as already confirmed. The
picker then settled on no models after one look.

Fold both ends into nextRevalidationStamp: rows found clears, a forced scan
over an inventory already observed empty stamps, everything else carries for
the same key.
danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Aug 11, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Reverts the Ollama source I added two commits ago. /api/hub/local scans
read-only and returns an opaque ollama-manifest: reference as the row id, which
only materialize_ollama_model_ref can turn into a .gguf path, and nothing calls
that function. Selecting one of those rows fails instead of loading, so the
list entry was worse than its absence.

The picker withholds the same rows through PICKER_LOCAL_SOURCES for this exact
reason, so Chat now matches it. Restoring Ollama models to both belongs in the
load path, not in a wider source filter.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 11, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 11, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 11, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 11, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 11, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 11, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Aug 11, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: ec148d1a91

ℹ️ 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

Review converged. Codex approved the head and the cross-platform runs are green, so this is the wrap-up.

What landed on top of the original change

Commit Fix
8162d7f A backwards clock step (NTP, VM resume, manual change) made now - refreshedAt negative, which read as inside the window, so the inventory froze for the length of the skew and refreshIfOlderThan(0) became a no-op
83f0980 A directory with GGUF and safetensors weights arrives as two rows sharing one load id, which collided on the selector's React key and rendered both as selected; collapsed to one option per load id
83f0980 Any forced scan stamped revalidatedAt, so a refresh of a populated inventory that returned empty recorded itself as its own confirmation and settled the picker on "no models" after one scan
182713a The same stamp was not cleared when a scan found rows, so a later first empty scan inside the window also read as pre-confirmed
ec148d1 Reverted an Ollama source filter I added earlier; see below

The Ollama one is worth calling out because I got it wrong first. Chat losing Ollama models on the endpoint switch is real, but the fix is not to widen the filter: /api/hub/local scans read-only and returns an opaque ollama-manifest: id, materialize_ollama_model_ref has no caller, and the picker already withholds those rows through PICKER_LOCAL_SOURCES for exactly that reason. Offering them would have produced entries that fail on click. Chat now matches the picker.

Verification

  • Frontend suite 1629 passing, npm run typecheck and npm run build clean.
  • Cross-platform CI on ubuntu-latest, macos-14 and windows-latest plus a live Playwright run, all green at the final head.
  • 568-case exhaustive check of the two decision functions against a written spec; the real inventory store driven through 15 concurrency scenarios; the reuse window exercised in chromium, firefox and webkit; the build installed into a clean home and installed over a pre-PR home, which kept its credential, scan folders and all 202 local models.
  • The original saving is intact after all of it: 13 inventory requests to 3 for "load /chat, wait 8s, open and close the picker three times", and 0.88s to 0.13s of request time.

Two gaps left for the backend, deliberately

Both are pre-existing divergences between /api/models/local and /api/hub/local that this PR exposes to Chat rather than creates, and both need backend changes with a wider blast radius than a frontend PR should carry:

  1. A directory holding a valid model.safetensors with no config.json is returned by the compat endpoint only; _is_supported gates custom folders on {gguf, safetensors, adapter} and it classifies as unknown.
  2. Ollama models are now invisible to both Chat and the picker until the load path resolves ollama-manifest: references.

Happy to open separate PRs for either.

@danielhanchen
danielhanchen merged commit d707c4e into unslothai:main Aug 11, 2026
32 of 40 checks passed
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 11, 2026
unslothai#8381 added refreshInventoryIfOlderThan to the chat picker inventory hook at
the same call site this branch passes allowedHiddenModelIds through, so both
are kept.
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.

2 participants