Skip to content

The agent that grows with you

fix(models): provider catalog cache writes re-read under a lock

Maciej Lisiewski619b6b7a8470
diff --git a/hermes_cli/model_switch_providers.py b/hermes_cli/model_switch_providers.py
index d23e0d5a1e0..1c1e9a02c9c 100644
--- a/hermes_cli/model_switch_providers.py
+++ b/hermes_cli/model_switch_providers.py
@@ -219,9 +219,8 @@ def _prefetch_provider_models_parallel(provider_slugs: list[str]) -> None:
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."""
+ non-blocking serial read for a parallel fetch the picker waits on. Persistence is
+ ``cached_provider_model_ids``'s own locked write; workers add none of their own."""
from hermes_cli.models import (
_credential_fingerprint, _disk_serve_tier, _load_provider_models_cache,
_normalized_cache_slug, cached_provider_model_ids)
@@ -246,12 +245,7 @@ def _prefetch_provider_models_parallel(provider_slugs: list[str]) -> None:
import concurrent.futures
def _fetch_one(slug: str) -> None:
try:
- models = cached_provider_model_ids(slug, force_refresh=True)
- # cached_provider_model_ids persists via a non-locked read-modify-write; re-persist
- # through the locked path so no write is lost under concurrency.
- if models:
- from hermes_cli.models import update_provider_cache_entry
- update_provider_cache_entry(slug, models)
+ cached_provider_model_ids(slug, force_refresh=True)
except Exception:
pass # best-effort; picker falls back to curated list
diff --git a/hermes_cli/models.py b/hermes_cli/models.py
index 5b900144ae3..d8910d415ae 100644
--- a/hermes_cli/models.py
+++ b/hermes_cli/models.py
@@ -1930,10 +1930,9 @@ def _spawn_swr_refresh(cache_key: str, refresh_fn=None) -> None:
try:
entry = (refresh_fn or _default_refresh)()
if entry:
- # Under the write lock: the GUI read path spawns one of these per stale provider, so
- # the plain load-modify-save would let concurrent warms drop each other's rows.
- with _cache_write_lock:
- _store_cache_entry(cache_key, entry)
+ # _store_cache_entry re-reads under the write lock: the GUI read path spawns one of these
+ # per stale provider, so a plain load-modify-save would let concurrent warms drop rows.
+ _store_cache_entry(cache_key, entry)
except Exception:
logger.debug("SWR refresh failed for %s", cache_key, exc_info=True)
finally:
@@ -2058,9 +2057,6 @@ 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:
@@ -2069,26 +2065,17 @@ def _save_provider_models_cache(data: dict) -> None:
pass
-def _store_cache_entry(cache_key: str, entry: dict, cache: Optional[dict] = None) -> None:
- """Write one row into the disk cache (reloading the latest state unless ``cache`` is given)."""
- if cache is None:
- cache = _load_provider_models_cache()
- cache[cache_key] = entry
- _save_provider_models_cache(cache)
+def _store_cache_entry(cache_key: str, entry: dict) -> None:
+ """Write one row into the disk cache, re-reading it under the thread + cross-process locks: a slow
+ fetch worker or another process must never write back the snapshot it loaded before fetching."""
+ from hermes_cli.models_cache_lock import write_under_cache_lock
+ def write_row() -> None:
+ cache = _load_provider_models_cache()
+ cache[cache_key] = entry
+ _save_provider_models_cache(cache)
-def update_provider_cache_entry(provider: str, models: list[str]) -> None:
- """Thread-safe single-entry update for parallel prefetch workers: load-modify-save under a lock
- so concurrent fetches don't clobber each other's rows. 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:
- _store_cache_entry(normalized, _cache_entry(fp, models))
- except Exception:
- pass
+ write_under_cache_lock(_provider_models_cache_path(), write_row)
def _normalized_cache_slug(provider: Optional[str]) -> str:
@@ -2146,13 +2133,13 @@ def cached_provider_model_ids(
if fresh is None:
# The live fetch degraded to the curated list; the account's real catalog is on disk.
return _chat_catalog_rows([model for model in entry["models"] if not _model_requires_account_discovery(normalized, model)])
- _store_cache_entry(normalized, fresh, cache)
+ _store_cache_entry(normalized, fresh)
return _chat_catalog_rows(list(live))
if is_ollama:
if _ollama_native_probe_reachable():
# A reachable empty native catalog is authoritative; do not resurrect a stale disk catalog.
- _store_cache_entry(normalized, _cache_entry(fp, [], now), cache)
+ _store_cache_entry(normalized, _cache_entry(fp, [], now))
return []
# A failed/non-native probe is not authoritative: keep a stale catalog rather than blanking
# the picker during a transient outage.
@@ -2999,7 +2986,7 @@ def cached_fetch_api_models(
live = _live()
if live or isinstance(live, _NativePickerModelList):
stored = _entry(live, now)
- _store_cache_entry(cache_key, stored, cache)
+ _store_cache_entry(cache_key, stored)
return _catalog(stored)
# Live returned nothing (offline, timeout, auth hiccup): a stale same-fingerprint entry beats it
# (non-empty only: an empty native row is not worth resurrecting over the generic fallback).
diff --git a/hermes_cli/models_cache_lock.py b/hermes_cli/models_cache_lock.py
new file mode 100644
index 00000000000..bddfae9b97a
--- /dev/null
+++ b/hermes_cli/models_cache_lock.py
@@ -0,0 +1,37 @@
+"""Cross-process lock for ``provider_models_cache.json`` read-modify-write.
+
+Parallel prefetch workers, SWR refresh threads and other Hermes processes (dashboard, desktop,
+CLI) all rewrite the one cache file; each write must re-read it under this lock or a slow writer
+puts back the snapshot it loaded before its fetch, dropping rows written meanwhile.
+"""
+
+import logging
+import threading
+from contextlib import contextmanager
+from pathlib import Path
+from typing import Callable
+
+logger = logging.getLogger(__name__)
+
+_thread_lock = threading.Lock()
+_holder = threading.local()
+
+
+@contextmanager
+def provider_models_cache_lock(path: Path):
+ from hermes_cli.auth import _file_lock
+ with _thread_lock, _file_lock(path.with_name(path.name + ".lock"), _holder, 10.0,
+ f"Timed out waiting for the provider models cache lock ({path})"):
+ yield
+
+
+def write_under_cache_lock(path: Path, write: Callable[[], None]) -> None:
+ """Run ``write`` (re-read, set one row, save) under the thread + cross-process lock.
+
+ The file is a cache: an unwritable home or a wedged lock skips the write instead of failing
+ the model listing that triggered it."""
+ try:
+ with provider_models_cache_lock(path):
+ write()
+ except (OSError, TimeoutError):
+ logger.debug("provider models cache write skipped (%s)", path, exc_info=True)
diff --git a/tests/agent/test_astra_baseline_runtime.py b/tests/agent/test_astra_baseline_runtime.py
index 68e50afa955..e4f42e6515c 100644
--- a/tests/agent/test_astra_baseline_runtime.py
+++ b/tests/agent/test_astra_baseline_runtime.py
@@ -100,7 +100,7 @@ def test_picker_revalidates_cached_astra_and_never_injects_saved_entitlement(mon
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
monkeypatch.setattr(models, "_credential_fingerprint", lambda _: "synthetic-account")
- models.update_provider_cache_entry(provider, ["gpt-5.6-sol", model])
+ models._store_cache_entry(provider, models._cache_entry("synthetic-account", ["gpt-5.6-sol", model]))
live = []
calls = []
diff --git a/tests/hermes_cli/test_cached_fetch_api_models.py b/tests/hermes_cli/test_cached_fetch_api_models.py
index f321244cc1f..7371ad2c244 100644
--- a/tests/hermes_cli/test_cached_fetch_api_models.py
+++ b/tests/hermes_cli/test_cached_fetch_api_models.py
@@ -20,6 +20,8 @@ from unittest.mock import patch
import pytest
+from tests.waiting import wait_until
+
class TestCachedFetchApiModels:
def _entry(self, models, age_seconds, fp="fp"):
@@ -359,7 +361,10 @@ class TestSalvageFollowups:
)
assert done.wait(timeout=5), "background refresh did not complete"
assert saved["custom:https://gw.example.com/v1#fp"]["models"] == ["refreshed"]
- assert "custom:https://gw.example.com/v1#fp" not in mod._swr_refresh_inflight
+ # The save fires before the worker's finally drops the inflight key (and the cache lock
+ # release sits between them): wait for the dedupe slot instead of racing the thread.
+ wait_until(lambda: "custom:https://gw.example.com/v1#fp" not in mod._swr_refresh_inflight,
+ what="SWR inflight key released")
def test_corrupt_at_field_degrades_to_live_fetch_instead_of_raising(self):
"""provider_models_cache.json is user-editable; a corrupted 'at' must
diff --git a/tests/hermes_cli/test_model_cache_parallel_prefetch.py b/tests/hermes_cli/test_model_cache_parallel_prefetch.py
index f5a80e61465..aad2568fbd1 100644
--- a/tests/hermes_cli/test_model_cache_parallel_prefetch.py
+++ b/tests/hermes_cli/test_model_cache_parallel_prefetch.py
@@ -16,8 +16,8 @@ from unittest.mock import patch
# Thread-safe cache entry update (hermes_cli/models.py)
# ---------------------------------------------------------------------------
-class TestUpdateProviderCacheEntry:
- """Verify ``update_provider_cache_entry`` writes safely under concurrency."""
+class TestStoreCacheEntry:
+ """Verify ``_store_cache_entry`` writes safely under concurrency."""
def test_writes_new_entry(self, tmp_path, monkeypatch):
"""A new entry is persisted to the cache file."""
@@ -26,8 +26,7 @@ class TestUpdateProviderCacheEntry:
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"])
+ mod._store_cache_entry("openrouter", mod._cache_entry("fp1", ["m1", "m2"]))
cache = mod._load_provider_models_cache()
assert "openrouter" in cache
@@ -42,12 +41,10 @@ class TestUpdateProviderCacheEntry:
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"])
+ mod._store_cache_entry("provider_a", mod._cache_entry("fp_a", ["a1"]))
# Write a second entry
- with patch.object(mod, "_credential_fingerprint", return_value="fp_b"):
- mod.update_provider_cache_entry("provider_b", ["b1"])
+ mod._store_cache_entry("provider_b", mod._cache_entry("fp_b", ["b1"]))
cache = mod._load_provider_models_cache()
assert "provider_a" in cache
@@ -55,17 +52,6 @@ class TestUpdateProviderCacheEntry:
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
@@ -76,12 +62,11 @@ class TestUpdateProviderCacheEntry:
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,
- ))
+ with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
+ list(executor.map(
+ lambda p: mod._store_cache_entry(p, mod._cache_entry(f"fp_{p}", [f"model_{p}"])),
+ providers,
+ ))
cache = mod._load_provider_models_cache()
for p in providers:
@@ -127,8 +112,7 @@ class TestPrefetchProviderModelsParallel:
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"):
+ patch("hermes_cli.models.cached_provider_model_ids", side_effect=mock_fetch):
_prefetch_provider_models_parallel(["fresh_prov", "stale_prov"])
assert "fresh_prov" not in fetch_calls
@@ -156,8 +140,7 @@ class TestPrefetchProviderModelsParallel:
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"):
+ patch("hermes_cli.models.cached_provider_model_ids", side_effect=mock_fetch):
_prefetch_provider_models_parallel(slugs)
assert max_concurrent[0] > 1, "fetches were serial, not parallel"
@@ -171,8 +154,7 @@ class TestPrefetchProviderModelsParallel:
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"):
+ patch("hermes_cli.models.cached_provider_model_ids", side_effect=mock_fetch):
# Should not raise
_prefetch_provider_models_parallel(["failing_prov"])
@@ -222,8 +204,54 @@ class TestPrefetchProviderModelsParallel:
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"):
+ patch("hermes_cli.models.cached_provider_model_ids", side_effect=mock_fetch):
_prefetch_provider_models_parallel(["openrouter"])
assert fetched == ["openrouter"]
+
+ def test_slow_worker_does_not_drop_rows_persisted_during_its_fetch(self, tmp_path, monkeypatch):
+ """A worker whose fetch outlasts another's must not write back its pre-fetch snapshot."""
+ import threading
+
+ import hermes_cli.models as mod
+ from hermes_cli.model_switch_providers import _prefetch_provider_models_parallel
+
+ monkeypatch.setattr(mod, "_provider_models_cache_path", lambda: tmp_path / "provider_models_cache.json")
+ monkeypatch.setattr(mod, "_credential_fingerprint", lambda provider: "fp")
+ fast_persisted = threading.Event()
+
+ def fake_provider_model_ids(slug, force_refresh=False):
+ if slug != "openrouter":
+ # The slow provider answers only after the fast one fully persisted.
+ assert fast_persisted.wait(10)
+ return [f"{slug}/model"]
+
+ real_store = mod._store_cache_entry
+
+ def store_then_signal(cache_key, entry):
+ real_store(cache_key, entry)
+ if cache_key == "openrouter":
+ fast_persisted.set()
+
+ monkeypatch.setattr(mod, "provider_model_ids", fake_provider_model_ids)
+ # Observe the canonical write: the slow worker's own store must re-read past the fast one's.
+ monkeypatch.setattr(mod, "_store_cache_entry", store_then_signal)
+ _prefetch_provider_models_parallel(["openrouter", "anthropic"])
+
+ assert sorted(mod._load_provider_models_cache()) == ["anthropic", "openrouter"]
+
+ def test_failed_live_fetch_leaves_the_stale_row_untouched(self, tmp_path, monkeypatch):
+ """A prefetch whose live fetch returns nothing serves the old rows but must not re-stamp
+ them: the stale row stays stale so the next open retries instead of trusting it for a TTL."""
+ import hermes_cli.models as mod
+ from hermes_cli.model_switch_providers import _prefetch_provider_models_parallel
+
+ monkeypatch.setattr(mod, "_provider_models_cache_path", lambda: tmp_path / "provider_models_cache.json")
+ monkeypatch.setattr(mod, "_credential_fingerprint", lambda provider: "fp")
+ monkeypatch.setattr(mod, "provider_model_ids", lambda slug, force_refresh=False: [])
+ stale_at = time.time() - mod._PROVIDER_MODELS_STALE_SERVE_MAX - 3600
+ mod._save_provider_models_cache({"openrouter": {"fp": "fp", "at": stale_at, "models": ["openrouter/model"]}})
+
+ _prefetch_provider_models_parallel(["openrouter"])
+
+ assert mod._load_provider_models_cache()["openrouter"]["at"] == stale_at
diff --git a/tests/hermes_cli/test_model_cache_swr.py b/tests/hermes_cli/test_model_cache_swr.py
index 2830f8338e4..cc683996785 100644
--- a/tests/hermes_cli/test_model_cache_swr.py
+++ b/tests/hermes_cli/test_model_cache_swr.py
@@ -126,9 +126,13 @@ class TestProviderModelsSWR:
}), encoding="utf-8")
os.utime(auth_path, ns=(mtime_ns, mtime_ns))
+ def seed(models):
+ fp = mod._credential_fingerprint("openai-codex")
+ mod._store_cache_entry("openai-codex", mod._cache_entry(fp, models))
+
write_auth(jwt("account-a", "user-a", "first"), 0, 1_000_000_000)
astra_models = ["gpt-6-astra", "gpt-6-astra-900k"]
- mod.update_provider_cache_entry("openai-codex", astra_models)
+ seed(astra_models)
# Routine OAuth rotation and pool counters rewrite auth.json, but the
# account-scoped catalog is still authoritative for the same principal.
@@ -143,7 +147,7 @@ class TestProviderModelsSWR:
assert mod.cached_provider_model_ids("openai-codex", non_blocking=True) == []
spawn.assert_called_once_with("openai-codex")
- mod.update_provider_cache_entry("openai-codex", astra_models)
+ seed(astra_models)
write_auth(jwt("account-b", "user-b", "new-account"), 0, 4_000_000_000)
with patch.object(mod, "_spawn_swr_refresh") as spawn:
assert mod.cached_provider_model_ids("openai-codex", non_blocking=True) == []
@@ -152,7 +156,7 @@ class TestProviderModelsSWR:
# An expired token only ever yields the static fallback (no Astra); the refresh to a live
# token for the same principal must bust that row instead of serving it for the whole TTL.
write_auth(jwt("account-b", "user-b", "stale", exp=time.time() - 60), 0, 5_000_000_000)
- mod.update_provider_cache_entry("openai-codex", ["gpt-5.6-sol"])
+ seed(["gpt-5.6-sol"])
write_auth(jwt("account-b", "user-b", "fresh", exp=time.time() + 3600), 0, 6_000_000_000)
with patch.object(mod, "_spawn_swr_refresh") as spawn:
assert mod.cached_provider_model_ids("openai-codex", non_blocking=True) == []
diff --git a/tests/hermes_cli/test_model_switch_custom_providers.py b/tests/hermes_cli/test_model_switch_custom_providers.py
index 4bc8d79beae..892b99cc888 100644
--- a/tests/hermes_cli/test_model_switch_custom_providers.py
+++ b/tests/hermes_cli/test_model_switch_custom_providers.py
@@ -137,7 +137,7 @@ def _age_cached_rows(seconds):
for row in cache.values():
row["at"] -= seconds
for key, row in cache.items():
- models_mod._store_cache_entry(key, row, cache)
+ models_mod._store_cache_entry(key, row)
def test_picker_native_catalog_uses_the_short_native_ttl(monkeypatch):