Skip to content

The agent that grows with you

fix(models): catalog SWR refresh writes the requesting profile's cache (#103778, salvage #103779)

liuzikaii5f73e52c7e20
diff --git a/hermes_cli/model_catalog.py b/hermes_cli/model_catalog.py
index d15b6406cee..4a94b1316b8 100644
--- a/hermes_cli/model_catalog.py
+++ b/hermes_cli/model_catalog.py
@@ -8,6 +8,7 @@ whose callers fall back to the in-repo lists on ``None``.
from __future__ import annotations
+import contextvars
import json
import logging
import threading
@@ -163,22 +164,22 @@ def _write_disk_cache(data: dict[str, Any]) -> None:
logger.info("model catalog cache write failed: %s", exc)
-# Stale-while-revalidate: at most one background manifest refresh in flight per process. The
-# refreshed manifest lands on disk; the NEXT get_catalog() call picks it up via the mtime check.
+# Stale-while-revalidate: at most one background manifest refresh in flight per cache file (i.e.
+# per profile home — profile A's refresh must not suppress profile B's). The refreshed manifest
+# lands on disk; the NEXT get_catalog() call picks it up via the mtime check.
_catalog_swr_lock = threading.Lock()
-_catalog_swr_inflight = False
+_catalog_swr_inflight: set[str] = set()
def _spawn_catalog_swr_refresh(url: str) -> None:
- """Refresh the catalog manifest off-thread (fire-and-forget, deduped)."""
- global _catalog_swr_inflight
+ """Refresh the catalog manifest off-thread (fire-and-forget, deduped per cache path)."""
+ inflight_key = str(_cache_path())
with _catalog_swr_lock:
- if _catalog_swr_inflight:
+ if inflight_key in _catalog_swr_inflight:
return
- _catalog_swr_inflight = True
+ _catalog_swr_inflight.add(inflight_key)
def _refresh() -> None:
- global _catalog_swr_inflight
try:
fetched = _fetch_manifest_with_fallback(url, DEFAULT_FETCH_TIMEOUT)
if fetched is not None:
@@ -187,9 +188,12 @@ def _spawn_catalog_swr_refresh(url: str) -> None:
logger.debug("catalog SWR refresh failed", exc_info=True)
finally:
with _catalog_swr_lock:
- _catalog_swr_inflight = False
+ _catalog_swr_inflight.discard(inflight_key)
- threading.Thread(target=_refresh, daemon=True, name="model-catalog-swr").start()
+ # copy_context: the picker may be serving a profile scoped by the HERMES_HOME ContextVar
+ # (tui_gateway ``_profile_scoped``), so the worker must write THAT profile's cache file.
+ context = contextvars.copy_context()
+ threading.Thread(target=lambda: context.run(_refresh), daemon=True, name="model-catalog-swr").start()
def _remember(data: dict[str, Any], mtime: float) -> dict[str, Any]:
diff --git a/tests/hermes_cli/test_model_catalog.py b/tests/hermes_cli/test_model_catalog.py
index 7478d24a57f..086a2b4a353 100644
--- a/tests/hermes_cli/test_model_catalog.py
+++ b/tests/hermes_cli/test_model_catalog.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import json
import os
+import threading
import time
from pathlib import Path
from unittest.mock import patch
@@ -467,6 +468,96 @@ class TestIntegrationWithModelsModule:
# -----------------------------------------------------------------------------
+class TestSwrRefreshProfileScope:
+ """Two profile homes — A (process default) and B (routed via the HERMES_HOME ContextVar, as
+ tui_gateway ``_profile_scoped`` does). The off-thread stale-while-revalidate refresh spawned
+ under B must write B's cache file, and A's in-flight refresh must not suppress B's."""
+
+ _CFG = {"enabled": True, "url": "http://master", "ttl_hours": 1.0, "providers": {}}
+
+ @staticmethod
+ def _seed_expired(home: Path, manifest: dict) -> Path:
+ path = home / "cache" / "model_catalog.json"
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(manifest), encoding="utf-8")
+ os.utime(path, (1, 1)) # expired → served stale, refreshed off-thread
+ return path
+
+ @staticmethod
+ def _join_swr_threads() -> None:
+ for t in threading.enumerate():
+ if t.name == "model-catalog-swr":
+ t.join(5)
+
+ def test_refresh_under_profile_override_writes_that_profiles_cache(self, isolated_home, tmp_path):
+ from agent.secret_scope import set_multiplex_active
+ from hermes_cli import model_catalog
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+
+ old = _valid_manifest()
+ fresh = {**_valid_manifest(), "updated_at": "2026-05-01T00:00:00Z"}
+ path_a = self._seed_expired(isolated_home, old)
+ path_b = self._seed_expired(tmp_path / "profile-b", old)
+ a_before = path_a.read_bytes()
+ release = threading.Event()
+
+ def fetch(*_args, **_kwargs):
+ assert release.wait(5), "caller did not release the refresh"
+ return fresh
+
+ set_multiplex_active(True)
+ try:
+ with patch.object(model_catalog, "_load_catalog_config", return_value=self._CFG), \
+ patch.object(model_catalog, "_fetch_manifest_with_fallback", fetch):
+ token = set_hermes_home_override(path_b.parent.parent)
+ try:
+ assert model_catalog.get_catalog() == old # stale copy served without blocking
+ finally:
+ reset_hermes_home_override(token) # the handler returns before the fetch completes
+ release.set()
+ self._join_swr_threads()
+ finally:
+ set_multiplex_active(False)
+
+ assert json.loads(path_b.read_text(encoding="utf-8")) == fresh
+ assert path_a.read_bytes() == a_before
+
+ def test_inflight_refresh_for_one_profile_does_not_suppress_another(self, isolated_home, tmp_path):
+ from agent.secret_scope import set_multiplex_active
+ from hermes_cli import model_catalog
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+
+ old = _valid_manifest()
+ path_a = self._seed_expired(isolated_home, old)
+ path_b = self._seed_expired(tmp_path / "profile-b", old)
+ release = threading.Event()
+ refreshed_paths: list[str] = []
+ seen = threading.Lock()
+
+ def fetch(*_args, **_kwargs):
+ with seen:
+ refreshed_paths.append(str(model_catalog._cache_path()))
+ release.wait(5)
+ return None
+
+ set_multiplex_active(True)
+ try:
+ with patch.object(model_catalog, "_load_catalog_config", return_value=self._CFG), \
+ patch.object(model_catalog, "_fetch_manifest_with_fallback", fetch):
+ model_catalog.get_catalog() # A's refresh is now in flight (blocked on `release`)
+ token = set_hermes_home_override(path_b.parent.parent)
+ try:
+ model_catalog.get_catalog() # B must get its own refresh
+ finally:
+ reset_hermes_home_override(token)
+ release.set()
+ self._join_swr_threads()
+ finally:
+ set_multiplex_active(False)
+
+ assert sorted(refreshed_paths) == sorted([str(path_a), str(path_b)])
+
+
class TestManifestMatchesInRepoLists:
"""Fail if the on-disk manifest is out of date relative to in-repo lists."""