The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
perf: parallelize provider model-list fetches in model picker
lepetitprince716-prog7e439dbb1bc7
diff --git a/hermes_cli/model_switch.py b/hermes_cli/model_switch.pyindex 3299843d2ab..9b88f8465fb 100644--- a/hermes_cli/model_switch.py+++ b/hermes_cli/model_switch.py@@ -21,7 +21,9 @@ OpenRouter variant suffixes (``:free``, ``:extended``, ``:fast``).from __future__ import annotationsimport logging+import osimport re+import timefrom dataclasses import dataclassfrom typing import Any, List, NamedTuple, Optional@@ -2054,6 +2056,262 @@ def _scoped_key_env(name: str) -> str:return ""+# --- Parallel prefetch for provider model catalogs -----------------------+#+# When the 1h disk cache lapses (or on first cold open), list_authenticated_providers()+# calls cached_provider_model_ids() serially for each authed provider. Each call+# that misses the cache blocks on a live /v1/models HTTP round-trip (1-8s per+# provider depending on endpoint latency). With 10+ authed providers the+# cumulative serial blocking time is 15-30+ seconds.+#+# This prefetch function runs those same cached_provider_model_ids() calls in+# parallel via ThreadPoolExecutor before the main picker build loop starts.+# The main loop then hits warm cache entries instead of blocking on live+# fetches. Providers whose cache was already fresh (SWR or within TTL) are+# skipped entirely — no wasted network calls.+#+# Net effect on a 13-provider setup with an expired cache:+# Before: ~20s serial blocking (sum of all provider latencies)+# After: ~8s parallel (max single provider latency), rest served from cache++_PARALLEL_PREFETCH_WORKERS = 8+++def _prefetch_provider_models_parallel(provider_slugs: list[str]) -> None:+ """Fetch model catalogs for multiple providers in parallel.++ Only providers whose cache entry is stale or missing are fetched; fresh+ entries are skipped to avoid unnecessary network calls. Each worker uses+ :func:`update_provider_cache_entry` (thread-safe) to persist its result,+ so concurrent writes to ``provider_models_cache.json`` don't clobber each+ other.++ :param provider_slugs: Hermes provider IDs to prefetch (e.g. ``["openrouter",+ "anthropic", "deepseek"]``). Unknown providers are silently skipped.+ """+ from hermes_cli.models import cached_provider_model_ids++ # Quick-stale-check: skip providers whose cache is already fresh so we+ # don't waste network calls on a warm cache. We check staleness the same+ # way cached_provider_model_ids does internally: load the cache, compare+ # age to TTL. This is a read-only check — if the cache file changes+ # between this check and the actual fetch, cached_provider_model_ids will+ # still do the right thing (it re-reads the cache internally).+ from hermes_cli.models import (+ _load_provider_models_cache,+ _credential_fingerprint,+ _PROVIDER_MODELS_CACHE_TTL,+ normalize_provider,+ )++ now = time.time()+ 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)+ fp = _credential_fingerprint(normalized)+ if (+ isinstance(entry, dict)+ and entry.get("fp") == fp+ and isinstance(entry.get("models"), list)+ and entry["models"]+ ):+ age = now - float(entry.get("at", 0))+ if age < _PROVIDER_MODELS_CACHE_TTL:+ continue # fresh, skip+ stale_slugs.append(normalized)++ if not stale_slugs:+ return++ import concurrent.futures++ def _fetch_one(slug: str) -> None:+ try:+ models = cached_provider_model_ids(slug, force_refresh=True)+ # cached_provider_model_ids already persists the result, but in a+ # non-locked read-modify-write. Re-persist via the thread-safe+ # path to guarantee no lost writes under concurrency.+ if models:+ from hermes_cli.models import update_provider_cache_entry+ update_provider_cache_entry(slug, models)+ except Exception:+ pass # best-effort; picker falls back to curated list++ with concurrent.futures.ThreadPoolExecutor(+ max_workers=min(_PARALLEL_PREFETCH_WORKERS, len(stale_slugs)),+ thread_name_prefix="model-cache-prefetch",+ ) as executor:+ list(executor.map(_fetch_one, stale_slugs))+++def _collect_authed_provider_slugs(+ models_dev_data: dict,+ curated: dict[str, list[str]],+ excluded: list[str],+) -> list[str]:+ """Quick-scan which providers have credentials, without fetching model lists.++ Mirrors the credential-check logic from sections 1, 2, and 2b of+ :func:`list_authenticated_providers` but **only** collects the provider+ slugs — it never calls ``cached_provider_model_ids``. The returned list+ is consumed by :func:`_prefetch_provider_models_parallel` to warm the disk+ cache in parallel before the serial picker build loop starts.++ :param models_dev_data: The models.dev registry dict (from ``fetch_models_dev()``).+ :param curated: The curated model-lists dict (``_PROVIDER_MODELS`` + extras).+ :param excluded: Provider slugs to exclude (from ``model_catalog.excluded_providers``).+ :returns: List of normalized provider slugs that have credentials.+ """+ import os+ from agent.models_dev import PROVIDER_TO_MODELS_DEV+ from hermes_cli.auth import PROVIDER_REGISTRY, _load_auth_store+ from hermes_cli.providers import HERMES_OVERLAYS, ALIASES as _PROVIDER_ALIAS_TABLE+ from hermes_cli.models import _AGGREGATOR_PROVIDERS as _AGG_PROVIDERS, CANONICAL_PROVIDERS++ _excluded_set = {str(p).strip().lower() for p in excluded if p}+ slugs: list[str] = []+ seen: set[str] = set()++ # --- Section 1: Hermes-mapped providers (PROVIDER_TO_MODELS_DEV) ---+ for hermes_id, mdev_id in PROVIDER_TO_MODELS_DEV.items():+ _alias_target = _PROVIDER_ALIAS_TABLE.get(hermes_id)+ if (+ _alias_target+ and _alias_target != hermes_id+ and _alias_target in _AGG_PROVIDERS+ ):+ continue+ _canonical = hermes_id+ try:+ from providers import get_provider_profile as _gpp+ _prof = _gpp(hermes_id)+ if _prof is not None:+ _canonical = _prof.name+ except Exception:+ pass+ if _canonical != hermes_id:+ continue+ if hermes_id.lower() in seen:+ continue+ if hermes_id.lower() in _excluded_set or mdev_id.lower() in _excluded_set:+ continue+ pdata = models_dev_data.get(mdev_id)+ if not isinstance(pdata, dict):+ continue+ pconfig = PROVIDER_REGISTRY.get(hermes_id)+ if pconfig and pconfig.auth_type != "api_key":+ continue+ from hermes_cli.auth import is_runtime_provider_routable+ if not is_runtime_provider_routable(hermes_id):+ continue+ if pconfig and pconfig.api_key_env_vars:+ env_vars = list(pconfig.api_key_env_vars)+ else:+ env_vars = pdata.get("env", [])+ if not isinstance(env_vars, list):+ continue+ has_creds = any(_scoped_key_env(ev) for ev in env_vars)+ if not has_creds:+ try:+ store = _load_auth_store()+ raw_pool_present = bool(+ store and store.get("credential_pool", {}).get(hermes_id)+ )+ if raw_pool_present:+ has_creds = _credential_pool_is_usable(+ hermes_id, raw_pool_present=True+ )+ except Exception:+ pass+ if has_creds:+ slugs.append(hermes_id)+ seen.add(hermes_id.lower())++ # --- Section 2: Hermes-only providers (HERMES_OVERLAYS) ---+ _mdev_to_hermes = {v: k for k, v in PROVIDER_TO_MODELS_DEV.items()}+ for pid, overlay in HERMES_OVERLAYS.items():+ if pid.lower() in seen:+ continue+ hermes_slug = _mdev_to_hermes.get(pid, pid)+ if hermes_slug.lower() in seen:+ continue+ if pid.lower() in _excluded_set or hermes_slug.lower() in _excluded_set:+ continue+ has_creds = False+ if overlay.auth_type == "aws_sdk":+ # Skip AWS SDK providers in prefetch — credential detection is heavier+ continue+ elif overlay.auth_type == "vertex":+ try:+ from agent.vertex_adapter import has_vertex_credentials+ has_creds = has_vertex_credentials()+ except Exception:+ pass+ elif overlay.extra_env_vars:+ has_creds = any(_scoped_key_env(ev) for ev in overlay.extra_env_vars)+ if not has_creds and overlay.auth_type == "api_key":+ for _key in (pid, hermes_slug):+ pcfg = PROVIDER_REGISTRY.get(_key)+ if pcfg and pcfg.api_key_env_vars:+ if any(_scoped_key_env(ev) for ev in pcfg.api_key_env_vars):+ has_creds = True+ break+ if not has_creds:+ try:+ store = _load_auth_store()+ providers_store = store.get("providers", {}) if store else {}+ if pid in providers_store or hermes_slug in providers_store:+ has_creds = True+ except Exception:+ pass+ if not has_creds:+ try:+ if _credential_pool_is_usable(hermes_slug):+ has_creds = True+ except Exception:+ pass+ if has_creds:+ slugs.append(hermes_slug)+ seen.add(pid.lower())+ seen.add(hermes_slug.lower())++ # --- Section 2b: Canonical providers cross-check ---+ for _cp in CANONICAL_PROVIDERS:+ if _cp.slug.lower() in seen:+ continue+ if _cp.slug.lower() in _excluded_set:+ continue+ _cp_config = PROVIDER_REGISTRY.get(_cp.slug)+ _cp_has_creds = False+ if _cp_config and _cp_config.api_key_env_vars:+ _cp_has_creds = any(_scoped_key_env(ev) for ev in _cp_config.api_key_env_vars)+ if not _cp_has_creds:+ try:+ _cp_store = _load_auth_store()+ _cp_providers_store = _cp_store.get("providers", {}) if _cp_store else {}+ if _cp.slug in _cp_providers_store:+ _cp_has_creds = True+ except Exception:+ pass+ if not _cp_has_creds:+ try:+ if _credential_pool_is_usable(_cp.slug):+ _cp_has_creds = True+ except Exception:+ pass+ if not _cp_has_creds and _cp_config and getattr(_cp_config, "auth_type", "") == "aws_sdk":+ continue # skip AWS SDK in prefetch+ if _cp_has_creds:+ slugs.append(_cp.slug)+ seen.add(_cp.slug.lower())++ return slugs++def list_authenticated_providers(current_provider: str = "",current_base_url: str = "",@@ -2129,7 +2387,6 @@ def list_authenticated_providers(except Exception:pass-results: List[dict] = []seen_slugs: set = set() # lowercase-normalized to catch case variants (#9545)_current_provider_norm = str(current_provider or "").strip().lower()@@ -2258,6 +2515,29 @@ def list_authenticated_providers(live = [current_model]curated["lmstudio"] = live+ # --- Parallel cache prefetch ---------------------------------------------+ # The serial loops below (sections 1, 2, 2b) each call+ # cached_provider_model_ids(slug) which blocks on a live /v1/models HTTP+ # round-trip when the disk cache is stale or missing. With many authed+ # providers those serial round-trips stack to 15-30s on a cold/expired+ # cache. Pre-scanning which providers have credentials (without fetching+ # their model lists) and warming their cache entries in parallel makes+ # the subsequent serial calls hit fresh cache entries instead.+ #+ # Skipped entirely when refresh=True (the serial path already force-refreshes)+ # and when there are 3 or fewer authed providers (serial is fast enough;+ # avoids thread-pool overhead for the common 1-2 provider case).+ _prefetch_slugs: list[str] = []+ if not refresh:+ _prefetch_slugs = _collect_authed_provider_slugs(+ data, curated, excluded_providers or []+ )+ if len(_prefetch_slugs) > 3:+ try:+ _prefetch_provider_models_parallel(_prefetch_slugs)+ except Exception:+ pass # best-effort; serial path still works as fallback+# --- 1. Check Hermes-mapped providers ---from hermes_cli.models import _AGGREGATOR_PROVIDERS as _AGG_PROVIDERSfrom hermes_cli.providers import ALIASES as _PROVIDER_ALIAS_TABLEdiff --git a/hermes_cli/models.py b/hermes_cli/models.pyindex d10e02b4127..2050fb53934 100644--- a/hermes_cli/models.py+++ b/hermes_cli/models.py@@ -3563,6 +3563,9 @@ def _load_provider_models_cache() -> dict:return {}+_cache_write_lock = threading.Lock()++def _save_provider_models_cache(data: dict) -> None:"""Persist the cache dict. Best-effort — silent on any error."""try:@@ -3574,6 +3577,31 @@ def _save_provider_models_cache(data: dict) -> None:pass+def update_provider_cache_entry(provider: str, models: list[str]) -> None:+ """Thread-safe single-entry update of the provider-models disk cache.++ Used by parallel prefetch workers so concurrent fetches don't clobber+ each other's writes via read-modify-write races on the shared JSON file.+ Each worker loads the latest cache state under the lock, writes its own+ entry, and saves — best-effort, silent on any error.+ """+ try:+ normalized = normalize_provider(provider) or (provider or "")+ if not normalized or not models:+ return+ fp = _credential_fingerprint(normalized)+ with _cache_write_lock:+ cache = _load_provider_models_cache()+ cache[normalized] = {+ "fp": fp,+ "at": time.time(),+ "models": list(models),+ }+ _save_provider_models_cache(cache)+ except Exception:+ pass++def cached_provider_model_ids(provider: Optional[str],*,diff --git a/tests/hermes_cli/test_model_cache_parallel_prefetch.py b/tests/hermes_cli/test_model_cache_parallel_prefetch.pynew file mode 100644index 00000000000..17a2ec202ef--- /dev/null+++ b/tests/hermes_cli/test_model_cache_parallel_prefetch.py@@ -0,0 +1,250 @@+"""Tests for parallel model-catalog prefetch and thread-safe cache writes.++Regression tests for the serial /v1/models bottleneck: when the 1h disk cache+lapses, ``list_authenticated_providers()`` previously fetched each authed+provider's model list serially. With 10+ providers this stacked to 15-30s of+blocking HTTP round-trips. The parallel prefetch warms stale cache entries+concurrently via ThreadPoolExecutor before the serial picker loop starts.+"""++from __future__ import annotations++import time+from unittest.mock import patch, MagicMock++import pytest+++# ---------------------------------------------------------------------------+# Thread-safe cache entry update (hermes_cli/models.py)+# ---------------------------------------------------------------------------++class TestUpdateProviderCacheEntry:+ """Verify ``update_provider_cache_entry`` writes safely under concurrency."""++ def test_writes_new_entry(self, tmp_path, monkeypatch):+ """A new entry is persisted to the cache file."""+ import hermes_cli.models as mod++ cache_path = tmp_path / "provider_models_cache.json"+ monkeypatch.setattr(mod, "_provider_models_cache_path", lambda: cache_path)++ with patch.object(mod, "_credential_fingerprint", return_value="fp1"):+ mod.update_provider_cache_entry("openrouter", ["m1", "m2"])++ cache = mod._load_provider_models_cache()+ assert "openrouter" in cache+ assert cache["openrouter"]["models"] == ["m1", "m2"]+ assert cache["openrouter"]["fp"] == "fp1"++ def test_does_not_clobber_other_entries(self, tmp_path, monkeypatch):+ """Concurrent writes to different providers don't lose entries."""+ import hermes_cli.models as mod++ cache_path = tmp_path / "provider_models_cache.json"+ monkeypatch.setattr(mod, "_provider_models_cache_path", lambda: cache_path)++ # Seed with one entry+ with patch.object(mod, "_credential_fingerprint", return_value="fp_a"):+ mod.update_provider_cache_entry("provider_a", ["a1"])++ # Write a second entry+ with patch.object(mod, "_credential_fingerprint", return_value="fp_b"):+ mod.update_provider_cache_entry("provider_b", ["b1"])++ cache = mod._load_provider_models_cache()+ assert "provider_a" in cache+ assert cache["provider_a"]["models"] == ["a1"]+ assert "provider_b" in cache+ assert cache["provider_b"]["models"] == ["b1"]++ def test_skips_empty_models(self, tmp_path, monkeypatch):+ """Empty model lists are not written to cache."""+ import hermes_cli.models as mod++ cache_path = tmp_path / "provider_models_cache.json"+ monkeypatch.setattr(mod, "_provider_models_cache_path", lambda: cache_path)++ mod.update_provider_cache_entry("empty_provider", [])+ cache = mod._load_provider_models_cache()+ assert "empty_provider" not in cache++ def test_concurrent_writes_no_lost_entries(self, tmp_path, monkeypatch):+ """Multiple threads writing different providers concurrently — all land."""+ import hermes_cli.models as mod+ import concurrent.futures++ cache_path = tmp_path / "provider_models_cache.json"+ monkeypatch.setattr(mod, "_provider_models_cache_path", lambda: cache_path)++ providers = [f"prov_{i}" for i in range(10)]++ with patch.object(mod, "_credential_fingerprint", side_effect=lambda p: f"fp_{p}"):+ with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:+ list(executor.map(+ lambda p: mod.update_provider_cache_entry(p, [f"model_{p}"]),+ providers,+ ))++ cache = mod._load_provider_models_cache()+ for p in providers:+ assert p in cache, f"{p} was lost in concurrent write"+ assert cache[p]["models"] == [f"model_{p}"]+++# ---------------------------------------------------------------------------+# Parallel prefetch (hermes_cli/model_switch.py)+# ---------------------------------------------------------------------------++class TestPrefetchProviderModelsParallel:+ """Verify ``_prefetch_provider_models_parallel`` fetches concurrently."""++ def test_skips_all_fresh_entries(self, monkeypatch):+ """When all cache entries are fresh, no fetch is made."""+ from hermes_cli.model_switch import _prefetch_provider_models_parallel++ fresh_cache = {+ "openrouter": {"fp": "fp", "at": time.time(), "models": ["m1"]},+ "anthropic": {"fp": "fp", "at": time.time(), "models": ["m2"]},+ }++ with patch("hermes_cli.models._load_provider_models_cache", return_value=fresh_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", "anthropic"])++ fetch.assert_not_called()++ def test_fetches_only_stale_entries(self, monkeypatch):+ """Only providers with stale/missing cache entries are fetched."""+ from hermes_cli.model_switch import _prefetch_provider_models_parallel++ cache = {+ "fresh_prov": {"fp": "fp_f", "at": time.time(), "models": ["m1"]},+ }++ fetch_calls = []++ def mock_fetch(slug, force_refresh=False):+ fetch_calls.append(slug)+ return [f"model_{slug}"]++ with patch("hermes_cli.models._load_provider_models_cache", return_value=cache), \+ patch("hermes_cli.models._credential_fingerprint", return_value="fp_f"), \+ patch("hermes_cli.models.cached_provider_model_ids", side_effect=mock_fetch), \+ patch("hermes_cli.models.update_provider_cache_entry"):+ _prefetch_provider_models_parallel(["fresh_prov", "stale_prov"])++ assert "fresh_prov" not in fetch_calls+ assert "stale_prov" in fetch_calls++ def test_fetches_in_parallel(self, monkeypatch):+ """Multiple providers are fetched concurrently, not serially."""+ from hermes_cli.model_switch import _prefetch_provider_models_parallel++ # Track overlap: if serial, no two fetches should overlap in time.+ active = []+ max_concurrent = [0]+ lock = __import__("threading").Lock()++ def mock_fetch(slug, force_refresh=False):+ with lock:+ active.append(slug)+ max_concurrent[0] = max(max_concurrent[0], len(active))+ time.sleep(0.05) # simulate network latency+ with lock:+ active.remove(slug)+ return [f"model_{slug}"]++ slugs = [f"prov_{i}" for i in range(6)]++ with patch("hermes_cli.models._load_provider_models_cache", return_value={}), \+ 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(slugs)++ assert max_concurrent[0] > 1, "fetches were serial, not parallel"++ def test_swallows_exceptions(self):+ """A failing provider fetch doesn't raise — best-effort."""+ from hermes_cli.model_switch import _prefetch_provider_models_parallel++ def mock_fetch(slug, force_refresh=False):+ raise ConnectionError("simulated network failure")++ with patch("hermes_cli.models._load_provider_models_cache", return_value={}), \+ 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"):+ # Should not raise+ _prefetch_provider_models_parallel(["failing_prov"])++ def test_empty_list_is_noop(self):+ """Empty provider list does nothing."""+ from hermes_cli.model_switch import _prefetch_provider_models_parallel++ with patch("hermes_cli.models.cached_provider_model_ids") as fetch:+ _prefetch_provider_models_parallel([])+ fetch.assert_not_called()+++# ---------------------------------------------------------------------------+# Integration: prefetch is called from list_authenticated_providers+# ---------------------------------------------------------------------------++class TestPrefetchIntegration:+ """Verify ``list_authenticated_providers`` triggers parallel prefetch."""++ def test_prefetch_called_with_more_than_3_providers(self):+ """When >3 providers are authed, parallel prefetch is invoked."""+ from hermes_cli import model_switch++ slugs = [f"prov_{i}" for i in range(5)]+ captured_slugs = []++ def mock_collect(data, curated, excluded):+ return slugs++ with patch.object(model_switch, "_collect_authed_provider_slugs", side_effect=mock_collect), \+ patch.object(model_switch, "_prefetch_provider_models_parallel") as prefetch:+ try:+ model_switch.list_authenticated_providers()+ except Exception:+ pass # we only care about the prefetch call+ captured_slugs = prefetch.call_args[0][0] if prefetch.called else []++ assert prefetch.called+ assert captured_slugs == slugs++ def test_prefetch_skipped_with_3_or_fewer_providers(self):+ """When ≤3 providers are authed, parallel prefetch is skipped."""+ from hermes_cli import model_switch++ slugs = ["prov_a", "prov_b"]++ def mock_collect(data, curated, excluded):+ return slugs++ with patch.object(model_switch, "_collect_authed_provider_slugs", side_effect=mock_collect), \+ patch.object(model_switch, "_prefetch_provider_models_parallel") as prefetch:+ try:+ model_switch.list_authenticated_providers()+ except Exception:+ pass++ prefetch.assert_not_called()++ def test_prefetch_skipped_on_refresh(self):+ """When refresh=True, prefetch is skipped (serial path force-refreshes)."""+ from hermes_cli import model_switch++ with patch.object(model_switch, "_collect_authed_provider_slugs") as collect, \+ patch.object(model_switch, "_prefetch_provider_models_parallel") as prefetch:+ try:+ model_switch.list_authenticated_providers(refresh=True)+ except Exception:+ pass++ collect.assert_not_called()+ prefetch.assert_not_called()