Skip to content

The agent that grows with you

perf(picker): stop blocking the model picker on TTL-expired catalogs

lepetitprince716-progfc1c260d259b
diff --git a/hermes_cli/model_switch_providers.py b/hermes_cli/model_switch_providers.py
index 565932522c0..05fa5b5f420 100644
--- a/hermes_cli/model_switch_providers.py
+++ b/hermes_cli/model_switch_providers.py
@@ -209,31 +209,32 @@ def prewarm_picker_cache_async() -> Optional["_threading.Thread"]:
def _prefetch_provider_models_parallel(provider_slugs: list[str]) -> None:
- """Fetch stale/missing provider catalogs in parallel before the serial picker loop.
-
- On a cold cache the serial loop would block 1-8s per provider; after the prefetch the wait is
- the slowest single provider. Each worker re-persists through the thread-safe
- ``update_provider_cache_entry`` so concurrent writes cannot clobber each other."""
+ """Fetch the provider catalogs the serial picker loop would block on, in parallel.
+
+ Only providers the serial call cannot serve from disk are fetched — missing,
+ fingerprint-mismatched, or hard-expired entries. TTL-expired non-empty rows are served
+ inside the stale-serve window while revalidating off-thread, and an empty local-ollama
+ catalog is authoritative inside its own short native TTL, so prefetching either trades a
+ non-blocking serial read for a parallel fetch the picker waits on. Each worker re-persists
+ through the thread-safe ``update_provider_cache_entry`` so concurrent writes cannot
+ clobber each other."""
from hermes_cli.models import (
- _PROVIDER_MODELS_CACHE_TTL, _credential_fingerprint, _load_provider_models_cache,
- cached_provider_model_ids, normalize_provider)
+ _credential_fingerprint, _disk_serve_tier, _load_provider_models_cache,
+ _normalized_cache_slug, cached_provider_model_ids)
- # Read-only staleness check mirroring cached_provider_model_ids (which re-reads the cache
- # itself, so a concurrent change between check and fetch is harmless).
now = time.time()
+
+ # Gate on the row the serial call actually reads — _normalized_cache_slug keeps a bare
+ # "ollama" as its own key instead of letting normalize_provider fold it into "custom".
+ # cached_provider_model_ids re-reads the cache itself, so a concurrent change between
+ # check and fetch is harmless.
stale_slugs: list[str] = []
cache = _load_provider_models_cache()
for slug in provider_slugs:
- normalized = normalize_provider(slug) or (slug or "")
- if not normalized:
- continue
- entry = cache.get(normalized)
- if (
- isinstance(entry, dict) and entry.get("fp") == _credential_fingerprint(normalized)
- and isinstance(entry.get("models"), list) and entry["models"]
- and now - float(entry.get("at", 0)) < _PROVIDER_MODELS_CACHE_TTL):
- continue
- stale_slugs.append(normalized)
+ key = _normalized_cache_slug(slug)
+ if key and _disk_serve_tier(cache.get(key), _credential_fingerprint(key), now,
+ is_ollama=key == "ollama") is None:
+ stale_slugs.append(key)
if not stale_slugs:
return
diff --git a/hermes_cli/models.py b/hermes_cli/models.py
index b445198c9e0..6624aca5b3d 100644
--- a/hermes_cli/models.py
+++ b/hermes_cli/models.py
@@ -1907,15 +1907,11 @@ def cached_provider_model_ids(
entry = cache.get(normalized)
now = time.time()
- if not force_refresh and _cache_entry_valid(entry, fp, allow_empty=is_ollama):
- age = now - entry["at"]
- if age < (_PROVIDER_MODELS_FALLBACK_TTL if entry.get("fallback") else ttl_seconds):
- return list(entry["models"])
- # Empty native catalogs are authoritative only for the short native TTL — never served
- # through the stale window. Non-empty stale rows are served immediately (SWR) so picker
- # opens never block on serial /v1/models round-trips.
- if entry["models"] and not entry.get("fallback") and age < _PROVIDER_MODELS_STALE_SERVE_MAX:
- _spawn_swr_refresh(normalized)
+ if not force_refresh:
+ tier = _disk_serve_tier(entry, fp, now, is_ollama=is_ollama, ttl_seconds=ttl_seconds)
+ if tier is not None:
+ if tier == "stale":
+ _spawn_swr_refresh(normalized)
return list(entry["models"])
if non_blocking and not force_refresh:
@@ -2693,6 +2689,27 @@ def _cache_entry_valid(
and not isinstance(entry.get("at"), bool))
+def _disk_serve_tier(entry: Any, fp: str, now: float, *, is_ollama: bool,
+ ttl_seconds: int = _PROVIDER_MODELS_CACHE_TTL) -> Optional[str]:
+ """How :func:`cached_provider_model_ids` serves *entry* without the network.
+
+ ``"fresh"`` inside the row's TTL (a curated fallback row only for
+ ``_PROVIDER_MODELS_FALLBACK_TTL``), ``"stale"`` for a non-empty, non-fallback row inside
+ ``_PROVIDER_MODELS_STALE_SERVE_MAX`` (served while an SWR thread revalidates), else ``None``:
+ the call would block on a live fetch. Empty native catalogs are authoritative only inside the
+ short native TTL, never through the stale window."""
+ if is_ollama:
+ ttl_seconds = min(ttl_seconds, _OLLAMA_LOCAL_MODELS_CACHE_TTL)
+ if not _cache_entry_valid(entry, fp, allow_empty=is_ollama):
+ return None
+ age = now - entry["at"]
+ if age < (_PROVIDER_MODELS_FALLBACK_TTL if entry.get("fallback") else ttl_seconds):
+ return "fresh"
+ if entry["models"] and not entry.get("fallback") and age < _PROVIDER_MODELS_STALE_SERVE_MAX:
+ return "stale"
+ return None
+
+
def cached_fetch_api_models(
api_key: Any, base_url: Optional[str], *, timeout: float = 5.0,
api_mode: Optional[str] = None, headers: Optional[dict[str, str]] = None,
diff --git a/tests/hermes_cli/test_model_cache_parallel_prefetch.py b/tests/hermes_cli/test_model_cache_parallel_prefetch.py
index c163d431a36..49827b3b323 100644
--- a/tests/hermes_cli/test_model_cache_parallel_prefetch.py
+++ b/tests/hermes_cli/test_model_cache_parallel_prefetch.py
@@ -187,6 +187,154 @@ class TestPrefetchProviderModelsParallel:
_prefetch_provider_models_parallel([])
fetch.assert_not_called()
+ def test_skips_ttl_expired_entries_the_serial_path_can_still_serve(self):
+ """A TTL-expired entry inside the stale-serve window is not prefetched.
+
+ ``cached_provider_model_ids`` returns such an entry from disk right
+ away and revalidates on a background thread, so blocking the picker
+ on a parallel fetch buys nothing. ``_PROVIDER_MODELS_STALE_SERVE_MAX``
+ is far longer than ``_PROVIDER_MODELS_CACHE_TTL``, so this is the
+ state every picker open a TTL after the previous one lands in.
+ """
+ import hermes_cli.models as models_mod
+ from hermes_cli.model_switch_providers import _prefetch_provider_models_parallel
+
+ expired = time.time() - models_mod._PROVIDER_MODELS_CACHE_TTL - 60
+ cache = {"openrouter": {"fp": "fp", "at": expired, "models": ["m1"]}}
+
+ with patch("hermes_cli.models._load_provider_models_cache", return_value=cache), \
+ patch("hermes_cli.models._credential_fingerprint", return_value="fp"), \
+ patch("hermes_cli.models.cached_provider_model_ids") as fetch:
+ _prefetch_provider_models_parallel(["openrouter"])
+
+ fetch.assert_not_called()
+
+ def test_fetches_curated_fallback_rows_past_their_short_ttl(self):
+ """A curated-fallback row is served only for ``_PROVIDER_MODELS_FALLBACK_TTL``
+ and never through the stale window, so the serial call blocks on it and the
+ parallel prefetch must fetch it."""
+ from hermes_cli.model_switch_providers import _prefetch_provider_models_parallel
+
+ cache = {"openrouter": {"fp": "fp", "at": time.time() - 7200, "models": ["m1"],
+ "fallback": True}}
+ fetched = []
+
+ def mock_fetch(slug, force_refresh=False):
+ fetched.append(slug)
+ return ["m1"]
+
+ with patch("hermes_cli.models._load_provider_models_cache", return_value=cache), \
+ patch("hermes_cli.models._credential_fingerprint", return_value="fp"), \
+ patch("hermes_cli.models.cached_provider_model_ids", side_effect=mock_fetch), \
+ patch("hermes_cli.models.update_provider_cache_entry"):
+ _prefetch_provider_models_parallel(["openrouter"])
+
+ assert fetched == ["openrouter"]
+
+ def test_fetches_when_credentials_rotated_inside_the_window(self):
+ """A fingerprint mismatch is fetched however recent the entry is.
+
+ The cached catalog belongs to the previous credential; serving it
+ would show the old account's models after a key swap.
+ """
+ from hermes_cli.model_switch_providers import _prefetch_provider_models_parallel
+
+ cache = {"openrouter": {"fp": "old_fp", "at": time.time(), "models": ["m1"]}}
+ fetched = []
+
+ def mock_fetch(slug, force_refresh=False):
+ fetched.append(slug)
+ return ["m2"]
+
+ with patch("hermes_cli.models._load_provider_models_cache", return_value=cache), \
+ patch("hermes_cli.models._credential_fingerprint", return_value="new_fp"), \
+ patch("hermes_cli.models.cached_provider_model_ids", side_effect=mock_fetch), \
+ patch("hermes_cli.models.update_provider_cache_entry"):
+ _prefetch_provider_models_parallel(["openrouter"])
+
+ assert fetched == ["openrouter"]
+
+ def test_fetches_entries_cached_as_empty(self):
+ """An empty cached catalog is not servable — prefetch it."""
+ from hermes_cli.model_switch_providers import _prefetch_provider_models_parallel
+
+ cache = {"openrouter": {"fp": "fp", "at": time.time(), "models": []}}
+ fetched = []
+
+ def mock_fetch(slug, force_refresh=False):
+ fetched.append(slug)
+ return ["m1"]
+
+ with patch("hermes_cli.models._load_provider_models_cache", return_value=cache), \
+ patch("hermes_cli.models._credential_fingerprint", return_value="fp"), \
+ patch("hermes_cli.models.cached_provider_model_ids", side_effect=mock_fetch), \
+ patch("hermes_cli.models.update_provider_cache_entry"):
+ _prefetch_provider_models_parallel(["openrouter"])
+
+ assert fetched == ["openrouter"]
+
+ def test_bare_ollama_reads_and_warms_its_own_cache_row(self):
+ """The gate must key on the row the serial call actually reads.
+
+ ``normalize_provider("ollama")`` is ``"custom"``, but
+ ``cached_provider_model_ids`` deliberately keeps a bare ``ollama`` as
+ its own key. Gating on ``custom`` answers about a different row, and
+ then warms that row instead of the one nobody looked at.
+ """
+ from hermes_cli.model_switch_providers import _prefetch_provider_models_parallel
+
+ cache = {"ollama": {"fp": "fp", "at": time.time(), "models": ["llama3"]}}
+
+ with patch("hermes_cli.models._load_provider_models_cache", return_value=cache), \
+ patch("hermes_cli.models._credential_fingerprint", return_value="fp"), \
+ patch("hermes_cli.models.cached_provider_model_ids") as fetch:
+ _prefetch_provider_models_parallel(["ollama"])
+
+ fetch.assert_not_called()
+
+ def test_empty_ollama_catalog_inside_its_native_ttl_is_not_prefetched(self):
+ """A reachable-but-empty local catalog is authoritative for that TTL.
+
+ ``cached_provider_model_ids`` returns the empty list with no round
+ trip, so prefetching it is redundant work the picker waits on.
+ """
+ import hermes_cli.models as models_mod
+ from hermes_cli.model_switch_providers import _prefetch_provider_models_parallel
+
+ recent = time.time() - models_mod._OLLAMA_LOCAL_MODELS_CACHE_TTL / 2
+ cache = {"ollama": {"fp": "fp", "at": recent, "models": []}}
+
+ with patch("hermes_cli.models._load_provider_models_cache", return_value=cache), \
+ patch("hermes_cli.models._credential_fingerprint", return_value="fp"), \
+ patch("hermes_cli.models.cached_provider_model_ids") as fetch:
+ _prefetch_provider_models_parallel(["ollama"])
+
+ fetch.assert_not_called()
+
+ def test_empty_ollama_catalog_past_its_native_ttl_is_prefetched(self):
+ """Past the native TTL an empty row gets no stale-serve window.
+
+ The serial call re-probes, so newly pulled models become visible —
+ and that re-probe blocks, which is exactly what prefetch is for.
+ """
+ import hermes_cli.models as models_mod
+ from hermes_cli.model_switch_providers import _prefetch_provider_models_parallel
+
+ expired = time.time() - models_mod._OLLAMA_LOCAL_MODELS_CACHE_TTL - 60
+ cache = {"ollama": {"fp": "fp", "at": expired, "models": []}}
+ fetched = []
+
+ def mock_fetch(slug, force_refresh=False):
+ fetched.append(slug)
+ return ["llama3"]
+
+ with patch("hermes_cli.models._load_provider_models_cache", return_value=cache), \
+ patch("hermes_cli.models._credential_fingerprint", return_value="fp"), \
+ patch("hermes_cli.models.cached_provider_model_ids", side_effect=mock_fetch):
+ _prefetch_provider_models_parallel(["ollama"])
+
+ assert fetched == ["ollama"]
+
# ---------------------------------------------------------------------------
# Integration: prefetch is called from list_authenticated_providers