Repository navigation
studio: cache the servability scan behind GET /v1/models - #9998
Conversation
GET /v1/models measured 316-621ms on a user's server against 13-34ms for the internal GET /api/models/list, which touches no filesystem at all. The catalog scan behind it is already cached for 30s, but the per entry servability check was not: _servable_catalog_rows called local_servable_model for every catalog entry on every request, and each of those stats several files and reads a config.json. An API client that lists models before each request pays that walk every time. Cache the scan against the catalog stamp, the same way _validated_media_picks already does, so a catalog rescan is the only thing that invalidates it and nothing can go stale behind a second independent TTL. Residency is deliberately left per request, since it changes on every load and unload. The cache is keyed on the catalog identity as well as the stamp. _CATALOG_CACHE["at"] starts at 0.0 and only advances inside _cached_local_catalog, so keying on the stamp alone would serve one catalog's rows to a caller that supplied a different catalog from anywhere else.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Simulations for the cases a request-path cache has to survive. A wrong answer here is worse than the latency it saves: it would advertise a model the server cannot serve, or hide one it can. - 16 threads x 20 calls against the same catalog, asserting every caller sees the whole catalog and nothing raises. - A replaced catalog under an unchanged stamp is never served from the old entry, including the 0.0 stamp a fresh process starts with. - Residency is recomputed on every call and a load between calls is visible immediately, since it changes on every load and unload. - A raising resolver propagates instead of caching "this server can serve nothing" for the life of the catalog. - Empty and 500-entry catalogs, no-stamp callers, and the media/STT/TTS task exclusions that must keep working.
…y per call Two review findings, both reachable on ordinary concurrent /v1/models traffic. Publish the cache entry as one tuple. The fast path reads the cache without the lock, and three separate assignments could be caught half-replaced: a request holding the previous catalog still matched the old stamp and old catalog object while `rows` already pointed at the next catalog's rows, so it was served another catalog's model ids, paths and quants. One assignment of (at, catalog, rows), and one read of it, cannot tear. Cache the source path, not the resolved snapshot. For a non-GGUF model in the HF cache, `info.path` is the repository directory and `local_load_dir` resolves the snapshot it currently points at. A download that lands inside the catalog's 30s lifetime moves that pointer, and a cached snapshot path then reported a model that had just been loaded as unloaded until the catalog expired. The scan keeps the stable path and residency resolves the current snapshot on every call, which is one resolve rather than the full servability walk the cache exists to avoid.
…idated A delete invalidates the local model resolver but not _CATALOG_CACHE, so the catalog behind the scan cache stayed standing for the rest of its 30s TTL and /v1/models kept advertising the removed model or quant for that window. The per-request scan used to drop it at once. local_model_resolver now carries a generation counter that invalidate_index bumps, and the scan cache is keyed on it alongside the catalog stamp and identity. Every existing invalidation site (model delete, export, finished download) therefore clears this cache too, with no new call site to keep in sync. The generation is read before the scan and stored, so an invalidation that lands mid-scan makes the entry stale rather than being recorded as already seen.
The resolver generation alone was too narrow. Two paths change the answer without touching the resolver, and the catalog behind the cache is the coarsest of the three, so a stale row could outlive the event that should have retired it where the per-request scan re-derived one each time: - Deleting a cached Hub model or GGUF variant. deletion.py invalidates the HF cache scans in its finally and never calls invalidate_index, so /v1/models kept advertising the removed repo or quant for the rest of the 30s catalog TTL. - Hardware re-detection. local_servable_model decides non-GGUF servability from hardware.DEVICE, and an Apple Silicon MLX self-repair flips CPU to MLX after startup. An early /v1/models would otherwise hide those checkpoints until the TTL expired. The key is now the triple (resolver index generation, HF cache scan epoch, hardware detection generation). All three are module-state reads and nothing here touches the filesystem. The imports are deliberately not guarded: a missing counter would pin the key at a constant and quietly undo the invalidation, which is worse than an import error that says so.
|
The The assertion is in What I checked before saying so:
So the check is unstable on the merge base itself and happens to pass on main some of the time. Turn 1 is byte identical across both runs, which says the same model and quant is serving, so this is llama-server prompt cache reuse across the two passes rather than anything in either branch. Worth fixing separately: as written the check cannot distinguish a real determinism regression from this, which is the more expensive problem. I will raise that on its own rather than touch it here. |
…leted An outputs or exports directory can be registered as a custom model scan folder, so a model removed through delete_finetuned_model may be one /v1/models is advertising. The successful deletion branch called neither invalidate_index nor invalidate_hf_cache_scans, so with the scan now cached those rows stayed fresh until the catalog TTL expired, where the per-request scan dropped the deleted path or quant at once. The route invalidates the resolver index before reporting success.
…st one Deleting a single GGUF variant returns before the full-model delete, so the invalidation added last round did not cover it: /v1/models kept advertising the deleted quant, or the model itself when it was the sole variant, until the catalog TTL expired. Both branches now call a named _invalidate_local_scans() helper rather than repeating the import, so the requirement is visible at each return. The test walks every success return and asserts an invalidation belongs to that branch, with nothing else returning in between, so a third branch added later cannot quietly skip it.
|
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". |
…tion off the loop Two problems with the previous revision. A caller captures the generation, misses, and queues on the scan lock. While it waits the first scanner finishes and a delete lands. That scanner correctly stamps its entry with the generation it started with, and the waiter wakes holding the same value, so the double check agreed and handed back rows examined before the delete. The generation is now re-read under the lock, which is the only read that can see that the world moved. And _invalidate_local_scans ran inline in an async route. invalidate_index takes the resolver lock, which _index() holds across a full multi-root filesystem scan, so a deletion overlapping a rebuild stalled the event loop and every unrelated request and inference stream behind it. It is now a coroutine using asyncio.to_thread, matching the other async invalidation sites in this file, and both call sites await it. The race test drives the real sequence rather than approximating it, and both tests were confirmed by mutation: reverting either fix fails its own test and only its own.
…n TTL The generation check still had a gap on the lock-free path, which is where most requests land: a delete completing between the generation read and the entry read was accepted anyway. The read is now a seqlock, generation then entry then generation. The counter only ever advances, so equal ends mean no invalidation landed in between, and an unequal pair means the rows in hand may predate one. This covers the in-lock read too, since invalidate_index does not take the scan lock. The three counters also only cover Studio's own paths. A file removed from a scan folder by hand moves none of them, and the per-request scan used to notice at once, so the entry now carries its own 5 second TTL as well. A directory mtime would not serve here: deleting or editing a file inside a nested directory does not bump the root's mtime, which is why the resolver's own mtime memo was dropped earlier in this work. Five seconds still collapses the polling burst that motivated the cache; a client polling every second takes four hits out of five. Both confirmed by mutation: dropping either check fails its own test and only its own.
|
@codex review |
|
Codex Review: Didn't find any major issues. What shall we delve into next? 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". |
test_the_invalidation_helper_stays_off_the_event_loop was defined twice, which the repo's duplicate-definition lint caught. My own edit to remove a superseded copy of a different test sliced the wrong range and left this one doubled. The two copies were byte identical, so no coverage was lost, but the earlier definition was dead and the lint is right to refuse it.
Summary
GET /v1/modelsmeasured 316-621ms on a user's server, against 13-34ms for the internalGET /api/models/liston the same box in the same session. The internal route touches no filesystem at all, which is most of the gap.The catalog scan behind
/v1/modelsis already cached for 30s. The per entry servability check was not._servable_catalog_rowscalledlocal_servable_modelfor every catalog entry on every request, and each of those stats several files and reads aconfig.json. An API client that lists models before each request pays that whole walk every time.Changes
Cache the scan, and key it on everything the servability answer actually depends on.
The cache key
The catalog stamp alone is not enough, because the catalog is the coarsest of the signals and would pin a stale answer for the rest of its 30s TTL where the per-request scan re-derived one each time. The key is:
_CATALOG_CACHE["at"]starts at0.0and only advances inside_cached_local_catalog, so the stamp alone would serve one catalog's rows to a caller that supplied a different catalog from anywhere else.local_model_resolver, bumped byinvalidate_index. Every existing invalidation site therefore retires this cache too, with no new call site to keep in sync.delete_cached_model_responseinvalidates only the HF cache scans and never the resolver, so deleting a cached Hub model or variant needs this one.local_servable_modeldecides non-GGUF servability fromhardware.DEVICE, and an Apple Silicon MLX self-repair flips CPU to MLX after startup. An early/v1/modelswould otherwise hide those checkpoints until the TTL expired.All four are module state reads; the triple costs about 0.6us per call against the 316-621ms being removed.
Reading it safely
The entry and the generation are read as a seqlock: generation, entry, generation. The counter only ever advances, so equal ends mean no invalidation landed between them. Without the second read, a delete completing between the generation read and the entry read is accepted anyway, on the lock-free path where most requests land and under the lock alike, since
invalidate_indexdoes not take the scan lock. The stored generation is the one captured before the scan, so an invalidation that lands mid-scan makes the entry stale rather than being stamped in as if the scan had seen it.Deletion paths
delete_finetuned_modelinvalidated nothing, and an outputs or exports directory can be a registered custom scan folder, so what it removes can be a model/v1/modelsis advertising. Both of its successful returns now go through one named helper, including the GGUF-variant branch that returns earlier than the full-model delete. The helper is a coroutine usingasyncio.to_thread, matching the other async invalidation sites in the file:invalidate_indextakes the resolver lock, which_index()holds across a full multi-root filesystem scan, so calling it inline from an async route would stall the event loop and every unrelated request and inference stream behind a rebuild.A bounded fallback
The counters only cover Studio's own paths. A file removed from a scan folder by hand moves none of them, and the per-request scan used to notice immediately, so the entry also carries its own 5 second TTL. A directory mtime would not serve here: deleting or editing a file inside a nested directory does not bump the root's mtime. Five seconds still collapses the polling burst the cache exists for, and a client polling every second takes four hits out of five.
Residency is deliberately left per request, since it changes on every load and unload. The returned row shape is unchanged.
Why not memoize lower down
The first version of this cached inside
local_model_resolverkeyed on the model directory mtime. That is wrong for the reason above, and four existing tests intest_openai_auto_switch.pycaught it. Caching at the catalog layer avoids the problem rather than trying to build a change stamp that covers every file the resolver reads.Testing
test_openai_models_servable_cache.py(6): one scan per catalog stamp, residency recomputed on every call, a replaced catalog forcing a rescan, no stamp preserving the original uncached behaviour, unchanged row shape, unservable entries still dropped.test_openai_models_servable_cache_edges.py(24): concurrency across 16 threads, atomic publication of the entry, a failed scan not being cached, each of the three counters retiring the entry, an invalidation landing mid-scan, a generation moving mid-read, a waiter overtaken while queued on the lock, the out-of-band file change surfacing within the TTL, every delete branch invalidating, and the helper staying off the event loop. A further test asserts the counters do not drift on their own, since that would quietly undo the caching this PR exists to add.Every fix in this PR was confirmed by mutation: reverting it fails its own test and only its own.
Existing suites pass:
test_openai_catalog,test_openai_models_media,test_openai_models_path_leak,test_openai_auto_switch,test_openai_auto_download,test_media_auto_switch,test_delete_finetuned_diffusion_guard,test_local_model_dir_discovery,test_local_model_format,test_last_local_model_setting.Cross-platform CI was run on owned staging repos rather than the org queue: ubuntu-latest, macos-15 and windows-latest all pass.
The
multi_turn_chat.pydeterminism check fails on this branch. It also fails on the merge base with zero changes, on two unrelated PRs, and on both Linux and macOS while Windows passes. Tracked separately in #10004; it is not caused by this PR.Notes
Separate from the Studio freeze work in #9997 and independent of it. This is a latency fix; the set of models
/v1/modelsreturns is unchanged, and the invalidation work above exists to keep it that way.