Skip to content

The agent that grows with you

fix: follow-ups for salvaged PR #80740

kshitij7cf71c32bbd2
diff --git a/acp_adapter/server.py b/acp_adapter/server.py
index 44d1df5ecc9..83d7c8509d2 100644
--- a/acp_adapter/server.py
+++ b/acp_adapter/server.py
@@ -114,7 +114,7 @@ def _named_custom_provider_catalogs() -> list[tuple[str, str, list[tuple[str, st
is_provider_enabled,
load_config,
)
- from hermes_cli.models import fetch_api_models
+ from hermes_cli.models import cached_fetch_api_models
from hermes_cli.providers import custom_provider_slug
except ImportError:
return []
@@ -176,7 +176,7 @@ def _named_custom_provider_catalogs() -> list[tuple[str, str, list[tuple[str, st
discover = discover.lower() not in {"false", "no", "0"}
if discover and api_key:
try:
- live = fetch_api_models(
+ live = cached_fetch_api_models(
api_key, base_url, api_mode=entry.get("api_mode")
)
except Exception:
diff --git a/hermes_cli/models.py b/hermes_cli/models.py
index 5c92c20ca2e..c18b29dc1fb 100644
--- a/hermes_cli/models.py
+++ b/hermes_cli/models.py
@@ -19,7 +19,10 @@ import urllib.error
import time
from difflib import get_close_matches
from pathlib import Path
-from typing import Any, NamedTuple, Optional
+from typing import Any, NamedTuple, Optional, TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from typing import TypeGuard
from hermes_cli import __version__ as _HERMES_VERSION
from hermes_cli.urllib_security import open_credentialed_url
@@ -3106,37 +3109,50 @@ _swr_refresh_inflight: set = set()
_swr_refresh_lock = threading.Lock()
-def _spawn_swr_refresh(provider: str) -> None:
- """Kick a background refresh of *provider*'s model-id cache entry.
+def _spawn_swr_refresh(cache_key: str, refresh_fn=None) -> None:
+ """Kick a background refresh of *cache_key*'s model-id cache entry.
- Fire-and-forget daemon thread; at most one in flight per provider.
+ Fire-and-forget daemon thread; at most one in flight per cache key.
Failures are swallowed — the stale entry stays served until a later
refresh succeeds (same degradation the blocking path already had).
+
+ ``refresh_fn`` (no-args, returns the fresh cache-entry dict or ``None``)
+ lets non-slug keys (``custom:<base_url>`` entries from
+ :func:`cached_fetch_api_models`) reuse the same inflight-dedupe and
+ thread scaffolding. When omitted, *cache_key* is treated as a
+ ``PROVIDER_REGISTRY`` slug and refreshed via :func:`provider_model_ids`
+ (the original behavior).
"""
with _swr_refresh_lock:
- if provider in _swr_refresh_inflight:
+ if cache_key in _swr_refresh_inflight:
return
- _swr_refresh_inflight.add(provider)
+ _swr_refresh_inflight.add(cache_key)
+
+ def _default_refresh():
+ live = provider_model_ids(cache_key, force_refresh=True)
+ if not live:
+ return None
+ return {
+ "fp": _credential_fingerprint(cache_key),
+ "at": time.time(),
+ "models": list(live),
+ }
def _refresh() -> None:
try:
- live = provider_model_ids(provider, force_refresh=True)
- if live:
+ entry = (refresh_fn or _default_refresh)()
+ if entry:
cache = _load_provider_models_cache()
- cache[provider] = {
- "fp": _credential_fingerprint(provider),
- "at": time.time(),
- "models": list(live),
- }
+ cache[cache_key] = entry
_save_provider_models_cache(cache)
except Exception:
- logger.debug("SWR refresh failed for %s", provider, exc_info=True)
+ logger.debug("SWR refresh failed for %s", cache_key, exc_info=True)
finally:
with _swr_refresh_lock:
- _swr_refresh_inflight.discard(provider)
+ _swr_refresh_inflight.discard(cache_key)
threading.Thread(
- target=_refresh, daemon=True, name=f"model-cache-swr-{provider}"
+ target=_refresh, daemon=True, name=f"model-cache-swr-{cache_key}"
).start()
@@ -4668,6 +4684,23 @@ def _custom_endpoint_fingerprint(
return hashlib.blake2b(blob, digest_size=8).hexdigest()
+def _cache_entry_valid(entry: Any, fp: str) -> "TypeGuard[dict[str, Any]]":
+ """True when *entry* is a well-formed cache row for fingerprint *fp*.
+
+ Requires a numeric ``at`` so corrupt disk state (hand-edited JSON with
+ ``"at": "yesterday"`` or ``null``) degrades to a cache miss / live fetch
+ instead of raising out of the wrapper.
+ """
+ return (
+ isinstance(entry, dict)
+ and entry.get("fp") == fp
+ and isinstance(entry.get("models"), list)
+ and bool(entry["models"])
+ and isinstance(entry.get("at"), (int, float))
+ and not isinstance(entry.get("at"), bool)
+ )
+
+
def cached_fetch_api_models(
api_key: Optional[str],
base_url: Optional[str],
@@ -4680,29 +4713,23 @@ def cached_fetch_api_models(
) -> Optional[list[str]]:
"""Disk-cached wrapper around :func:`fetch_api_models` for custom endpoints.
- Mirrors :func:`cached_provider_model_ids` but keys
- ``provider_models_cache.json`` off ``custom:<base_url>`` instead of a
- ``PROVIDER_REGISTRY`` slug, since custom endpoints (named
- ``custom_providers`` rows, bare ``provider: custom``, and per-endpoint-map
- entries) have none. Same stale-beats-nothing fallback policy as
- ``cached_provider_model_ids``: a live-fetch failure serves the last
- same-fingerprint result rather than an empty list. Always returns
- whatever :func:`fetch_api_models` would (a list or ``None``), never
- raises.
+ Mirrors :func:`cached_provider_model_ids` — including its
+ stale-while-revalidate tier — but keys ``provider_models_cache.json``
+ off ``custom:<base_url>`` instead of a ``PROVIDER_REGISTRY`` slug, since
+ custom endpoints (named ``custom_providers`` rows, bare
+ ``provider: custom``, and per-endpoint-map entries) have none. Same
+ stale-beats-nothing fallback policy: a live-fetch failure serves the
+ last same-fingerprint result rather than an empty list. Returns whatever
+ :func:`fetch_api_models` would (a list or ``None``); corrupt cache rows
+ degrade to a live fetch instead of raising.
"""
- # Only forward api_mode when the caller actually set it — none of the
- # current probe call sites do, and omitting it (rather than passing
- # api_mode=None) keeps the live-call signature identical to a direct
- # fetch_api_models() call.
- live_kwargs: dict[str, Any] = {"timeout": timeout, "headers": headers}
- if api_mode is not None:
- live_kwargs["api_mode"] = api_mode
-
normalized_url = str(base_url or "").strip().rstrip("/").lower()
if not normalized_url:
# No base_url means nothing to key the cache on — fall through to a
# live call so callers keep getting fetch_api_models' own behavior.
- return fetch_api_models(api_key, base_url, **live_kwargs)
+ return fetch_api_models(
+ api_key, base_url, timeout=timeout, api_mode=api_mode, headers=headers
+ )
cache_key = f"custom:{normalized_url}"
fp = _custom_endpoint_fingerprint(api_key, api_mode, headers)
@@ -4710,17 +4737,30 @@ def cached_fetch_api_models(
entry = cache.get(cache_key)
now = time.time()
- if (
- not force_refresh
- and isinstance(entry, dict)
- and entry.get("fp") == fp
- and isinstance(entry.get("models"), list)
- and entry["models"]
- and (now - float(entry.get("at", 0))) < ttl_seconds
- ):
- return list(entry["models"])
+ if not force_refresh and _cache_entry_valid(entry, fp):
+ age = now - entry["at"]
+ if age < ttl_seconds:
+ return list(entry["models"])
+ if age < _PROVIDER_MODELS_STALE_SERVE_MAX:
+ # Stale-while-revalidate: serve the expired entry immediately so
+ # picker opens never block on a live /v1/models round-trip
+ # (#72762's stall class, which a plain TTL would reintroduce an
+ # hour into the session); refresh off-thread for the next open.
+ def _refresh_custom():
+ live = fetch_api_models(
+ api_key, base_url,
+ timeout=timeout, api_mode=api_mode, headers=headers,
+ )
+ if not live:
+ return None
+ return {"fp": fp, "at": time.time(), "models": list(live)}
+
+ _spawn_swr_refresh(cache_key, _refresh_custom)
+ return list(entry["models"])
- live = fetch_api_models(api_key, base_url, **live_kwargs)
+ live = fetch_api_models(
+ api_key, base_url, timeout=timeout, api_mode=api_mode, headers=headers
+ )
if live:
cache[cache_key] = {"fp": fp, "at": now, "models": list(live)}
_save_provider_models_cache(cache)
@@ -4728,12 +4768,7 @@ def cached_fetch_api_models(
# Live fetch returned nothing (offline endpoint, timeout, auth hiccup).
# A stale same-fingerprint entry beats an empty result.
- if (
- isinstance(entry, dict)
- and entry.get("fp") == fp
- and isinstance(entry.get("models"), list)
- and entry["models"]
- ):
+ if _cache_entry_valid(entry, fp):
return list(entry["models"])
return live
diff --git a/tests/hermes_cli/test_cached_fetch_api_models.py b/tests/hermes_cli/test_cached_fetch_api_models.py
index 05cc27d0cd8..346a0e4f764 100644
--- a/tests/hermes_cli/test_cached_fetch_api_models.py
+++ b/tests/hermes_cli/test_cached_fetch_api_models.py
@@ -55,7 +55,11 @@ class TestCachedFetchApiModels:
def test_expired_entry_triggers_live_fetch_and_is_persisted(self):
import hermes_cli.models as mod
- cache = {"custom:https://gw.example.com/v1": self._entry(["old"], age_seconds=99999)}
+ # Beyond the stale-serve window, so the wrapper must block on a
+ # live fetch (within the window it stale-serves + refreshes off
+ # thread — covered in TestSalvageFollowups).
+ too_old = mod._PROVIDER_MODELS_STALE_SERVE_MAX + 60
+ cache = {"custom:https://gw.example.com/v1": self._entry(["old"], age_seconds=too_old)}
saved = {}
with patch.object(mod, "_load_provider_models_cache", return_value=cache), \
patch.object(mod, "_custom_endpoint_fingerprint", return_value="fp"), \
@@ -205,3 +209,87 @@ class TestCachedFetchApiModelsDiskRoundTrip:
cache = mod._load_provider_models_cache()
assert cache["custom:https://openrouter.ai/v1"]["models"] == ["custom-endpoint-model"]
assert cache["openrouter"]["models"] == ["openrouter-curated-model"]
+
+
+class TestSalvageFollowups:
+ """Follow-up behaviors added while salvaging PR #80740: SWR stale-serve
+ parity with cached_provider_model_ids, and corrupt-cache degradation."""
+
+ def _entry(self, models, age_seconds, fp="fp"):
+ return {"fp": fp, "at": time.time() - age_seconds, "models": list(models)}
+
+ def test_expired_entry_within_stale_window_is_served_and_refreshed_off_thread(self):
+ """TTL-expired (but < stale-serve max) entries must be served
+ immediately — the picker never blocks on a live round-trip — while a
+ background refresh is spawned for the next open."""
+ import hermes_cli.models as mod
+
+ cache = {"custom:https://gw.example.com/v1": self._entry(["stale-ok"], age_seconds=7200)}
+ with patch.object(mod, "_load_provider_models_cache", return_value=cache), \
+ patch.object(mod, "_custom_endpoint_fingerprint", return_value="fp"), \
+ patch.object(mod, "_spawn_swr_refresh") as spawn, \
+ patch.object(mod, "fetch_api_models") as live:
+ out = mod.cached_fetch_api_models(
+ "sk-key", "https://gw.example.com/v1", ttl_seconds=3600
+ )
+ assert out == ["stale-ok"]
+ live.assert_not_called()
+ spawn.assert_called_once()
+ assert spawn.call_args[0][0] == "custom:https://gw.example.com/v1"
+
+ def test_entry_beyond_stale_window_blocks_on_live_fetch(self):
+ import hermes_cli.models as mod
+
+ too_old = mod._PROVIDER_MODELS_STALE_SERVE_MAX + 60
+ cache = {"custom:https://gw.example.com/v1": self._entry(["ancient"], age_seconds=too_old)}
+ with patch.object(mod, "_load_provider_models_cache", return_value=cache), \
+ patch.object(mod, "_custom_endpoint_fingerprint", return_value="fp"), \
+ patch.object(mod, "_save_provider_models_cache"), \
+ patch.object(mod, "_spawn_swr_refresh") as spawn, \
+ patch.object(mod, "fetch_api_models", return_value=["fresh"]) as live:
+ out = mod.cached_fetch_api_models("sk-key", "https://gw.example.com/v1")
+ assert out == ["fresh"]
+ live.assert_called_once()
+ spawn.assert_not_called()
+
+ def test_swr_refresh_fn_writes_custom_entry_through_shared_scaffolding(self):
+ """The generalized _spawn_swr_refresh(key, refresh_fn) must persist a
+ custom-endpoint entry via the shared inflight-dedupe machinery."""
+ import threading as _threading
+
+ import hermes_cli.models as mod
+
+ done = _threading.Event()
+ saved = {}
+
+ def fake_save(data):
+ saved.update(data)
+ done.set()
+
+ with patch.object(mod, "_load_provider_models_cache", return_value={}), \
+ patch.object(mod, "_save_provider_models_cache", side_effect=fake_save):
+ mod._spawn_swr_refresh(
+ "custom:https://gw.example.com/v1",
+ lambda: {"fp": "fp", "at": time.time(), "models": ["refreshed"]},
+ )
+ assert done.wait(timeout=5), "background refresh did not complete"
+ assert saved["custom:https://gw.example.com/v1"]["models"] == ["refreshed"]
+ assert "custom:https://gw.example.com/v1" not in mod._swr_refresh_inflight
+
+ def test_corrupt_at_field_degrades_to_live_fetch_instead_of_raising(self):
+ """provider_models_cache.json is user-editable; a corrupted 'at' must
+ be a cache miss (live fetch), never an exception out of the wrapper."""
+ import hermes_cli.models as mod
+
+ cache = {
+ "custom:https://gw.example.com/v1": {
+ "fp": "fp", "at": "yesterday", "models": ["corrupt-row"],
+ }
+ }
+ with patch.object(mod, "_load_provider_models_cache", return_value=cache), \
+ patch.object(mod, "_custom_endpoint_fingerprint", return_value="fp"), \
+ patch.object(mod, "_save_provider_models_cache"), \
+ patch.object(mod, "fetch_api_models", return_value=["live-models"]) as live:
+ out = mod.cached_fetch_api_models("sk-key", "https://gw.example.com/v1")
+ assert out == ["live-models"]
+ live.assert_called_once()
diff --git a/tests/hermes_cli/test_model_switch_custom_providers.py b/tests/hermes_cli/test_model_switch_custom_providers.py
index 710a176d1a9..e7139e7dac4 100644
--- a/tests/hermes_cli/test_model_switch_custom_providers.py
+++ b/tests/hermes_cli/test_model_switch_custom_providers.py
@@ -640,7 +640,11 @@ def test_custom_providers_uses_live_models_for_multi_model_endpoint(monkeypatch)
assert gateway_prov is not None, "Custom provider group not found in results"
assert calls == [
- ("sk-gateway-key", "https://gateway.example.com/v1", {"timeout": 5.0, "headers": None})
+ (
+ "sk-gateway-key",
+ "https://gateway.example.com/v1",
+ {"timeout": 5.0, "api_mode": None, "headers": None},
+ )
], "fetch_api_models must be called with the custom provider's credentials"
assert gateway_prov["models"] == [
"gateway-model-a",
diff --git a/tests/hermes_cli/test_user_providers_model_switch.py b/tests/hermes_cli/test_user_providers_model_switch.py
index 36c1d6d13cf..5fe4a74178e 100644
--- a/tests/hermes_cli/test_user_providers_model_switch.py
+++ b/tests/hermes_cli/test_user_providers_model_switch.py
@@ -158,7 +158,13 @@ def test_list_authenticated_providers_uses_live_models_for_user_provider(monkeyp
)
assert user_prov is not None
- assert calls == [("sk-test", "http://127.0.0.1:3000/api/v1", {"timeout": 5.0, "headers": None})]
+ assert calls == [
+ (
+ "sk-test",
+ "http://127.0.0.1:3000/api/v1",
+ {"timeout": 5.0, "api_mode": None, "headers": None},
+ )
+ ]
assert user_prov["models"] == ["old-configured-model", "new-live-model"]
assert user_prov["total_models"] == 2
@@ -497,7 +503,7 @@ def test_section3_probes_no_key_endpoint_without_explicit_models(monkeypatch):
assert probed.get("called") is True, "no-key bare endpoint should be probed"
assert probed["api_key"] == ""
- assert probed["kwargs"] == {"timeout": 5.0, "headers": None}
+ assert probed["kwargs"] == {"timeout": 5.0, "api_mode": None, "headers": None}
row = next(p for p in providers if p["slug"] == "local-llamacpp")
assert row["models"] == ["live-model-1", "live-model-2", "live-model-3"]
assert row["total_models"] == 3