The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): retry failed session database opens
fangliquanflq4b659f0e3301
diff --git a/gateway/readiness.py b/gateway/readiness.pyindex d49ea820482..9cffd39cce1 100644--- a/gateway/readiness.py+++ b/gateway/readiness.py@@ -86,6 +86,20 @@ def _probe_gateway(runtime_status: dict[str, Any]) -> dict[str, Any]:return _check(status, state=state, connected_platforms=connected, platforms=configured)+def _probe_session_store(+ runtime_status: dict[str, Any], state_db_probe: dict[str, Any]+) -> dict[str, Any]:+ """Report the running gateway cache state, not an independent reopen."""+ runtime_store = runtime_status.get("session_store")+ if isinstance(runtime_store, dict):+ state = str(runtime_store.get("status") or "unknown")+ if state in {"ok", "unavailable", "retrying"}:+ return _check(state)+ # Older gateways do not publish a cache state. Preserve their readiness+ # behavior until their process restarts onto a version that does.+ return _check("ok" if state_db_probe.get("status") == "ok" else "unavailable")++def collect_runtime_readiness(*,configured_model: str,@@ -102,8 +116,10 @@ def collect_runtime_readiness("""home = get_hermes_home()runtime = runtime_status if isinstance(runtime_status, dict) else {}+ state_db_probe = _probe_state_db(home)checks = {- "state_db": _probe_state_db(home),+ "state_db": state_db_probe,+ "session_store": _probe_session_store(runtime, state_db_probe),"config": _probe_config(home),"model": _check("ok" if str(configured_model or "").strip() else "degraded"),"disk": _probe_disk(home),diff --git a/gateway/run.py b/gateway/run.pyindex 606412d6337..83e222d6429 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -7146,6 +7146,12 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewself._session_db_pinned: Any = _SESSION_DB_UNPINNEDself._session_db_handles: Dict[Path, Any] = {}self._session_db_handles_lock = threading.Lock()+ from gateway.session_db_recovery import RecoverableHandleCache++ self._session_db_handle_cache = RecoverableHandleCache(+ handles=self._session_db_handles,+ lock=self._session_db_handles_lock,+ )try:self._open_session_db_for_active_scope(raise_on_error=True)except Exception as e:@@ -7271,29 +7277,46 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewsearch on a multiplexed gateway read the *serving profile's* storerather than the root one.- One ``AsyncSessionDB`` is cached per resolved path under a lock, so+ One ``AsyncSessionDB`` is cached per resolved path, sothe wrapper identity is stable per profile (callers compare and stash- it) and two profiles never share a handle. A construction failure is- cached as ``None`` for that path so a broken store degrades once, not- per command; ``raise_on_error=True`` (construction-time priming)- propagates the failure instead so ``__init__`` can record- ``_session_db_init_error`` for the #88235 broadcast.+ it) and two profiles never share a handle. A construction failure+ enters bounded backoff; one caller retries after the deadline while+ concurrent callers continue to see the unavailable fallback.+ ``raise_on_error=True`` (construction-time priming) propagates the+ failure after recording that recoverable state so ``__init__`` can+ record ``_session_db_init_error`` for the #88235 broadcast."""from hermes_state import AsyncSessionDB, SessionDB, _default_db_path+ from gateway.session_db_recovery import RecoverableHandleCachepath = Path(_default_db_path())- with self._session_db_handles_lock:- if path in self._session_db_handles:- return self._session_db_handles[path]- db = None+ cache = getattr(self, "_session_db_handle_cache", None)+ if cache is None:+ # Compatibility for lightweight test runners built with+ # object.__new__ rather than GatewayRunner.__init__.+ cache = RecoverableHandleCache(+ handles=self._session_db_handles,+ lock=self._session_db_handles_lock,+ )+ self._session_db_handle_cache = cache++ def _open():try:- db = AsyncSessionDB(SessionDB())- except Exception as e:- if raise_on_error:- raise- logger.warning("SQLite session store not available: %s", e)- self._session_db_handles[path] = db- return db+ return AsyncSessionDB(SessionDB())+ except Exception as exc:+ logger.warning("SQLite session store not available: %s", exc)+ raise++ def _recovered() -> None:+ self._session_db_init_error = None+ logger.info("SQLite session store recovered")++ return cache.get(+ path,+ _open,+ raise_on_error=raise_on_error,+ on_recovered=_recovered,+ )@propertydef _session_db(self) -> Any:@@ -7320,18 +7343,17 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew``SessionStore.close_all_db_handles``. Handles are drained under thelock and closed outside it; a pinned handle is the pinner's to close."""- with self._session_db_handles_lock:- handles = [db for db in self._session_db_handles.values() if db is not None]- self._session_db_handles.clear()- for db in handles:+ def _close(db) -> None:inner = getattr(db, "_db", db)if inner is None or not hasattr(inner, "close"):- continue+ returntry:inner.close()except Exception as exc:logger.debug("SessionDB close error during handle sweep: %s", exc)+ self._session_db_handle_cache.close_all(_close)+def _wire_teams_pipeline_runtime(self) -> None:"""Bind the Teams meeting pipeline runtime to Graph webhook ingress.@@ -24564,7 +24586,7 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew"2. Salvage with: sqlite3 ~/.hermes/state.db \".recover\" ""(then replace state.db)\n""3. Restore from a backup in ~/.hermes/backups/\n"- f"Error: {error}"+ "Run `hermes doctor` for sanitized diagnostics.")else:message = (diff --git a/gateway/session.py b/gateway/session.pyindex be74201c9fc..ca613ebe8f8 100644--- a/gateway/session.py+++ b/gateway/session.py@@ -1315,6 +1315,12 @@ class SessionStore:self._db_pinned = _DB_UNPINNEDself._db_handles: Dict[Path, Any] = {}self._db_handles_lock = threading.Lock()+ from gateway.session_db_recovery import RecoverableHandleCache++ self._db_handle_cache = RecoverableHandleCache(+ handles=self._db_handles,+ lock=self._db_handles_lock,+ )self._open_session_db_for_active_scope()def _open_session_db_for_active_scope(self):@@ -1329,23 +1335,16 @@ class SessionStore:Handles are cached per resolved path, so a hot inbound path opensSQLite once per profile rather than once per message, and two- profiles never share a handle. Construction is done under the lock- so a concurrent first message on the same profile cannot open (and- then leak) a second handle for the same path.-- A construction failure is cached as ``None`` for that path, matching- the previous behavior where a failed startup left ``_db`` None for- the life of the store and callers fell back to JSONL.+ profiles never share a handle. Failed opens enter a bounded backoff;+ once it expires, one caller reopens while concurrent callers keep+ using the JSONL fallback."""from hermes_state import SessionDB, _default_db_pathpath = Path(_default_db_path())- with self._db_handles_lock:- if path in self._db_handles:- return self._db_handles[path]- db = None+ def _open():try:- db = SessionDB()+ return SessionDB()except RuntimeError as e:if "live-system guard" in str(e):# Test-isolation guard fired: a pytest-context process@@ -1355,10 +1354,18 @@ class SessionStore:# guard must fire again on the next attempt.raiseprint(f"[gateway] Warning: SQLite session store unavailable, falling back to JSONL: {e}")+ raiseexcept Exception as e:print(f"[gateway] Warning: SQLite session store unavailable, falling back to JSONL: {e}")- self._db_handles[path] = db- return db+ raise++ return self._db_handle_cache.get(+ path,+ _open,+ non_cacheable=lambda exc: (+ isinstance(exc, RuntimeError) and "live-system guard" in str(exc)+ ),+ )@propertydef _db(self):@@ -1399,15 +1406,14 @@ class SessionStore:handle (``store._db = fake``) is deliberately not closed here — thepinner owns its lifecycle."""- with self._db_handles_lock:- handles = [db for db in self._db_handles.values() if db is not None]- self._db_handles.clear()- for db in handles:+ def _close(db) -> None:try:db.close()except Exception as exc:logger.debug("SessionDB close error during handle sweep: %s", exc)+ self._db_handle_cache.close_all(_close)+def _has_active_processes_safe(self, session_key: str, *, context: str) -> bool:"""Return whether a session has active work, failing closed on registry errors."""if self._has_active_processes_fn is None:diff --git a/gateway/session_db_recovery.py b/gateway/session_db_recovery.pynew file mode 100644index 00000000000..d3fa53671fd--- /dev/null+++ b/gateway/session_db_recovery.py@@ -0,0 +1,159 @@+"""Recoverable per-path SessionDB handle caches for the gateway."""++from __future__ import annotations++import threading+import time+import weakref+from dataclasses import dataclass+from pathlib import Path+from typing import Any, Callable+++_INITIAL_RETRY_DELAY_SECONDS = 1.0+_MAX_RETRY_DELAY_SECONDS = 60.0+++@dataclass+class _Unavailable:+ failures: int = 0+ next_retry_at: float = 0.0+ in_flight: bool = False+++class _HealthSource:+ pass+++_health_lock = threading.Lock()+_health_states: weakref.WeakKeyDictionary[_HealthSource, dict[Path, str]] = (+ weakref.WeakKeyDictionary()+)+++def _publish_health(source: _HealthSource, path: Path, state: str) -> None:+ """Publish one privacy-safe aggregate for every live gateway DB cache."""+ with _health_lock:+ states = _health_states.setdefault(source, {})+ states[path] = state+ all_states = [value for item in _health_states.values() for value in item.values()]+ if "retrying" in all_states:+ aggregate = "retrying"+ elif "unavailable" in all_states:+ aggregate = "unavailable"+ else:+ aggregate = "ok"++ try:+ from gateway.status import write_runtime_status++ write_runtime_status(session_store={"status": aggregate})+ except Exception:+ # Runtime health is diagnostic only; persistence must not depend on it.+ pass+++class RecoverableHandleCache:+ """Cache handles by path while allowing failed opens to heal in-process."""++ def __init__(+ self,+ *,+ handles: dict[Path, Any] | None = None,+ lock: threading.Lock | None = None,+ clock: Callable[[], float] = time.monotonic,+ initial_retry_delay: float = _INITIAL_RETRY_DELAY_SECONDS,+ max_retry_delay: float = _MAX_RETRY_DELAY_SECONDS,+ ) -> None:+ self.handles = handles if handles is not None else {}+ self.lock = lock if lock is not None else threading.Lock()+ self._clock = clock+ self._initial_retry_delay = max(0.0, float(initial_retry_delay))+ self._max_retry_delay = max(+ self._initial_retry_delay, float(max_retry_delay)+ )+ self._unavailable: dict[Path, _Unavailable] = {}+ self._health_source = _HealthSource()++ def get(+ self,+ path: Path,+ opener: Callable[[], Any],+ *,+ raise_on_error: bool = False,+ on_recovered: Callable[[], None] | None = None,+ non_cacheable: Callable[[Exception], bool] | None = None,+ ) -> Any:+ """Return a cached handle or make one bounded, single-flight open attempt."""+ path = Path(path)+ with self.lock:+ if path in self.handles:+ return self.handles[path]++ unavailable = self._unavailable.setdefault(path, _Unavailable())+ now = self._clock()+ if unavailable.in_flight or now < unavailable.next_retry_at:+ return None+ unavailable.in_flight = True+ was_unavailable = unavailable.failures > 0++ if was_unavailable:+ _publish_health(self._health_source, path, "retrying")++ try:+ handle = opener()+ except Exception as exc:+ if non_cacheable is not None and non_cacheable(exc):+ with self.lock:+ self._unavailable.pop(path, None)+ raise+ with self.lock:+ unavailable = self._unavailable[path]+ unavailable.failures += 1+ delay = min(+ self._initial_retry_delay+ * (2 ** min(unavailable.failures - 1, 30)),+ self._max_retry_delay,+ )+ unavailable.next_retry_at = self._clock() + delay+ unavailable.in_flight = False+ _publish_health(self._health_source, path, "unavailable")+ if raise_on_error:+ raise+ return None++ with self.lock:+ self.handles[path] = handle+ self._unavailable.pop(path, None)+ _publish_health(self._health_source, path, "ok")+ if was_unavailable and on_recovered is not None:+ on_recovered()+ return handle++ def close_all(self, close: Callable[[Any], None]) -> None:+ """Drain cached handles under the lock and close them outside it."""+ with self.lock:+ handles = list(self.handles.values())+ paths = set(self.handles) | set(self._unavailable)+ self.handles.clear()+ self._unavailable.clear()+ for handle in handles:+ try:+ close(handle)+ except Exception:+ pass+ with _health_lock:+ states = _health_states.get(self._health_source)+ if states is not None:+ for path in paths:+ states.pop(path, None)++ def status_for(self, path: Path) -> str:+ """Return a sanitized state for tests and internal diagnostics."""+ with self.lock:+ if Path(path) in self.handles:+ return "ok"+ unavailable = self._unavailable.get(Path(path))+ if unavailable is None:+ return "unknown"+ return "retrying" if unavailable.in_flight else "unavailable"diff --git a/gateway/status.py b/gateway/status.pyindex 1fbbe10a1e2..161cd30e4a4 100644--- a/gateway/status.py+++ b/gateway/status.py@@ -669,6 +669,7 @@ def _build_runtime_status_record() -> dict[str, Any]:"restart_requested": False,"active_agents": 0,"platforms": {},+ "session_store": {"status": "unknown"},"updated_at": _utc_now_iso(),})payload.update(_get_code_identity_fields())@@ -1072,6 +1073,7 @@ def write_runtime_status(needs_attention: Any = _UNSET,retrying_since: Any = _UNSET,served_profiles: Any = _UNSET,+ session_store: Any = _UNSET,clear_profile_platforms: bool = False,) -> None:"""Persist gateway runtime health information for diagnostics/status."""@@ -1117,6 +1119,13 @@ def write_runtime_status(# for a single-profile gateway. Lets `hermes status` show per-profile# coverage without a second probe.payload["served_profiles"] = list(served_profiles or [])+ if session_store is not _UNSET:+ state = "unknown"+ if isinstance(session_store, dict):+ candidate = str(session_store.get("status") or "unknown")+ if candidate in {"ok", "unavailable", "retrying", "unknown"}:+ state = candidate+ payload["session_store"] = {"status": state}if platform is not _UNSET:platform_payload = payload["platforms"].get(platform, {})diff --git a/tests/gateway/test_readiness.py b/tests/gateway/test_readiness.pyindex ef5f7848d40..b9bb48333c9 100644--- a/tests/gateway/test_readiness.py+++ b/tests/gateway/test_readiness.py@@ -31,6 +31,7 @@ def test_collect_runtime_readiness_reports_healthy_local_runtime(tmp_path, monkeassert result["status"] == "ok"assert result["checks"]["state_db"]["status"] == "ok"+ assert result["checks"]["session_store"]["status"] == "ok"assert result["checks"]["config"]["status"] == "ok"assert result["checks"]["model"]["status"] == "ok"assert result["checks"]["gateway"]["status"] == "ok"@@ -59,3 +60,36 @@ def test_collect_runtime_readiness_degrades_on_invalid_config_and_stopped_gatewaassert (home / "config.yaml").read_text(encoding="utf-8") == "model: [unterminated"+def test_readiness_uses_running_session_store_state_over_independent_probe(+ tmp_path, monkeypatch+):+ home = tmp_path / ".hermes"+ home.mkdir()+ with sqlite3.connect(home / "state.db") as conn:+ conn.execute("CREATE TABLE probe (id INTEGER PRIMARY KEY)")+ monkeypatch.setenv("HERMES_HOME", str(home))++ unavailable = collect_runtime_readiness(+ configured_model="test/model",+ runtime_status={+ "gateway_state": "running",+ "platforms": {},+ "session_store": {"status": "unavailable"},+ },+ )++ assert unavailable["checks"]["state_db"]["status"] == "ok"+ assert unavailable["checks"]["session_store"] == {"status": "unavailable"}+ assert unavailable["status"] == "degraded"++ recovered = collect_runtime_readiness(+ configured_model="test/model",+ runtime_status={+ "gateway_state": "running",+ "platforms": {},+ "session_store": {"status": "ok"},+ },+ )+ assert recovered["checks"]["session_store"] == {"status": "ok"}++diff --git a/tests/gateway/test_session_db_recovery.py b/tests/gateway/test_session_db_recovery.pynew file mode 100644index 00000000000..28d2d85dbe6--- /dev/null+++ b/tests/gateway/test_session_db_recovery.py@@ -0,0 +1,198 @@+"""Regression coverage for recoverable gateway SessionDB opens (#93088)."""++from __future__ import annotations++import threading+from pathlib import Path+from unittest.mock import patch++from gateway.session_db_recovery import RecoverableHandleCache+++class _Clock:+ def __init__(self) -> None:+ self.now = 0.0++ def __call__(self) -> float:+ return self.now+++def test_failed_open_obeys_backoff_then_recovers() -> None:+ clock = _Clock()+ cache = RecoverableHandleCache(clock=clock, initial_retry_delay=2, max_retry_delay=8)+ path = Path("profile/state.db")+ handle = object()+ calls = 0++ def opener():+ nonlocal calls+ calls += 1+ if calls == 1:+ raise OSError("private/path/state.db is unavailable")+ return handle++ assert cache.get(path, opener) is None+ assert cache.status_for(path) == "unavailable"+ clock.now = 1.99+ assert cache.get(path, opener) is None+ assert calls == 1++ clock.now = 2.0+ assert cache.get(path, opener) is handle+ assert cache.get(path, opener) is handle+ assert calls == 2+ assert cache.status_for(path) == "ok"+++def test_retry_is_single_flight_for_concurrent_callers() -> None:+ clock = _Clock()+ cache = RecoverableHandleCache(clock=clock, initial_retry_delay=1, max_retry_delay=8)+ path = Path("profile/state.db")+ entered = threading.Event()+ release = threading.Event()+ handle = object()+ calls = 0++ def opener():+ nonlocal calls+ calls += 1+ if calls == 1:+ raise OSError("first open fails")+ entered.set()+ assert release.wait(timeout=5)+ return handle++ assert cache.get(path, opener) is None+ clock.now = 1.0+ result: list[object] = []+ thread = threading.Thread(target=lambda: result.append(cache.get(path, opener)))+ thread.start()+ assert entered.wait(timeout=5)++ # The opener runs outside the state lock. Other callers observe in-flight+ # and keep using the fallback rather than opening or blocking behind it.+ assert cache.get(path, opener) is None+ assert calls == 2+ assert cache.status_for(path) == "retrying"++ release.set()+ thread.join(timeout=5)+ assert not thread.is_alive()+ assert result == [handle]+ assert cache.get(path, opener) is handle+ assert calls == 2+++def test_runtime_health_is_sanitized_and_recovers() -> None:+ clock = _Clock()+ cache = RecoverableHandleCache(clock=clock, initial_retry_delay=1)+ path = Path("secret/profile/state.db")+ writes: list[dict] = []+ calls = 0++ def opener():+ nonlocal calls+ calls += 1+ if calls == 1:+ raise RuntimeError("database disk image is malformed at secret/profile/state.db")+ return object()++ with patch("gateway.status.write_runtime_status", side_effect=lambda **kw: writes.append(kw)):+ assert cache.get(path, opener) is None+ clock.now = 1.0+ assert cache.get(path, opener) is not None++ assert writes[-1] == {"session_store": {"status": "ok"}}+ serialized = repr(writes)+ assert "secret/profile" not in serialized+ assert "malformed" not in serialized+++def test_session_store_and_runner_reopen_after_failed_construction(monkeypatch, tmp_path) -> None:+ import hermes_state+ from gateway.run import GatewayRunner, _SESSION_DB_UNPINNED+ from gateway.session import SessionStore, _DB_UNPINNED++ db_path = tmp_path / "state.db"+ clock = _Clock()+ opened: list[object] = []++ def fail_once_session_db():+ if not opened:+ opened.append(None)+ raise OSError("temporary open failure")+ handle = object()+ opened.append(handle)+ return handle++ monkeypatch.setattr(hermes_state, "SessionDB", fail_once_session_db)+ monkeypatch.setattr(hermes_state, "_default_db_path", lambda: db_path)++ store = object.__new__(SessionStore)+ store._db_pinned = _DB_UNPINNED+ store._db_handles = {}+ store._db_handles_lock = threading.Lock()+ store._db_handle_cache = RecoverableHandleCache(+ handles=store._db_handles,+ lock=store._db_handles_lock,+ clock=clock,+ initial_retry_delay=1,+ )+ assert store._db is None+ assert store._db is None+ assert len(opened) == 1+ clock.now = 1.0+ assert store._db is opened[-1]++ runner_opened: list[object] = []++ def runner_fail_once():+ if not runner_opened:+ runner_opened.append(None)+ raise OSError("temporary open failure")+ handle = object()+ runner_opened.append(handle)+ return handle++ monkeypatch.setattr(hermes_state, "SessionDB", runner_fail_once)+ monkeypatch.setattr(hermes_state, "AsyncSessionDB", lambda db: ("async", db))+ runner = object.__new__(GatewayRunner)+ runner._session_db_pinned = _SESSION_DB_UNPINNED+ runner._session_db_init_error = "temporary open failure"+ runner._session_db_handles = {}+ runner._session_db_handles_lock = threading.Lock()+ runner._session_db_handle_cache = RecoverableHandleCache(+ handles=runner._session_db_handles,+ lock=runner._session_db_handles_lock,+ clock=clock,+ initial_retry_delay=1,+ )+ assert runner._session_db is None+ assert runner._session_db is None+ assert len(runner_opened) == 1+ clock.now = 2.0+ assert runner._session_db == ("async", runner_opened[-1])+ assert runner._session_db_init_error is None+++def test_non_cacheable_guard_is_retried_immediately() -> None:+ cache = RecoverableHandleCache()+ path = Path("state.db")+ calls = 0++ def opener():+ nonlocal calls+ calls += 1+ raise RuntimeError("live-system guard")++ for _ in range(2):+ try:+ cache.get(+ path,+ opener,+ non_cacheable=lambda exc: "live-system guard" in str(exc),+ )+ except RuntimeError:+ pass+ assert calls == 2+ assert cache.status_for(path) == "unknown"