The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): watcher idle probes fail open on an unavailable store and ignore cleared rows
kshitijk4poord54a1dee9154
diff --git a/gateway/run.py b/gateway/run.pyindex b4fcad130ac..a0fa7ae6c10 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -1806,6 +1806,20 @@ def _profile_session_db_probe(profile_home: "Path"):reset_hermes_home_override(token)+def _profile_meta_rows(profile_home: "Path", prefix: str) -> Optional[list]:+ """``list_meta_prefix(prefix)`` rows from the probe DB, or None when the store is unavailable or+ the read fails. None means "cannot prove emptiness": every idle gate treats it as work present, so+ a broken or migrating store can never suppress a heartbeat restore or a due loop (fail OPEN)."""+ db = _profile_session_db_probe(profile_home)+ if db is None:+ return None+ try:+ return db.list_meta_prefix(prefix)+ except Exception:+ logger.debug("meta probe %r failed for %s", prefix, profile_home, exc_info=True)+ return None++def load_gateway_config_for_runner() -> "GatewayConfig":"""Load gateway config for the process-level GatewayRunner. An UNSET ``multiplex_profiles`` issettled first by ``resolve_multiplex_mode`` (the default is on; the boot guard keeps a fleet thatdiff --git a/gateway/run_goals.py b/gateway/run_goals.pyindex c79c4a75414..80dbc16d101 100644--- a/gateway/run_goals.py+++ b/gateway/run_goals.py@@ -27,20 +27,20 @@ logger = logging.getLogger("gateway.run")async def _watcher_has_active_loops(runner: object, profile_home) -> bool:"""Idle gate for the loop wakeup watcher's per-profile scans: True when the profile'sstore holds an ACTIVE ``loop:*`` row — or when the probe can't prove otherwise (fail- OPEN: a probe error must never skip a due loop). The scan's SessionDB read goes through+ OPEN: an unavailable store, a failing read or a corrupt row must never skip a due loop). The scan's SessionDB read goes throughthe runner's executor hop (off the loop thread, #92413); runners without one (bare teststand-ins) skip the gate entirely and keep the historical always-enter behavior."""def _probe() -> bool:- from hermes_constants import reset_hermes_home_override, set_hermes_home_override- token = set_hermes_home_override(str(profile_home))- try:- from hermes_cli.loops import list_active_loops- return bool(list_active_loops())- except Exception:+ from gateway.run import _profile_meta_rows+ from hermes_cli.loops import _META_PREFIX, _parse_state++ rows = _profile_meta_rows(profile_home, _META_PREFIX)+ if rows is None:return True- finally:- reset_hermes_home_override(token)+ # ``list_active_loops()`` collapses an unavailable store to ``[]`` (fail CLOSED), so parse+ # the rows here; a corrupt row is "unknown" and keeps the scan.+ return any((state := _parse_state(raw)) is None or state.status == "active" for _key, raw in rows)offload = getattr(runner, "_run_in_executor_with_context", None)if not callable(offload):diff --git a/gateway/run_heartbeat_restore.py b/gateway/run_heartbeat_restore.pyindex fa44303ea69..1feb01d2bf9 100644--- a/gateway/run_heartbeat_restore.py+++ b/gateway/run_heartbeat_restore.py@@ -6,32 +6,32 @@ import logginglogger = logging.getLogger("gateway.run")-def _profile_has_heartbeat_keys(profile_home) -> bool:- """Indexed ``heartbeat:*`` probe on one profile's SessionDB — no config/secret parsing.+def _profile_has_active_heartbeat(profile_home) -> bool:+ """One profile's SessionDB holds a ``heartbeat:*`` row still ACTIVE — the only rows the sweep can+ restore (``HeartbeatManager.is_active``). Reads the goals-cached DB only: no config/secret parsing.+ Fails OPEN: an unavailable store, a failing read or a corrupt row all answer True, so the gate can+ never suppress a restore the full sweep would have made. ``clear``/``pause`` keep their rows (status+ ``cleared``/``paused``), so key existence alone would re-enable the sweep forever after first use."""+ from gateway.run import _profile_meta_rows+ from hermes_cli.heartbeat import HeartbeatState- Fails OPEN: a probe error or unavailable DB must not suppress the restore sweep.- """- from gateway.run import _profile_session_db_probe-- db = _profile_session_db_probe(profile_home)- if db is None:- return True- try:- return bool(db.list_meta_prefix("heartbeat:"))- except Exception:- logger.debug("heartbeat probe failed for %s; running full sweep", profile_home, exc_info=True)+ rows = _profile_meta_rows(profile_home, "heartbeat:")+ if rows is None:return True+ for _key, raw in rows:+ try:+ if HeartbeatState.from_json(raw).status == "active":+ return True+ except Exception:+ return True+ return False-def _served_profile_homes(runner, default_home):- """Homes whose SessionDBs may hold heartbeat state (multiplex set, else just the default)."""- try:- from hermes_cli.profiles import profiles_to_serve- multiplex = bool(getattr(getattr(runner, "config", None), "multiplex_profiles", False))- homes = [home for _name, home in profiles_to_serve(multiplex)]- return homes or [default_home]- except Exception:- return [default_home]+def _watched_homes(runner, default_home) -> list:+ """The gateway home plus every multiplexed secondary the watchers already poll."""+ from gateway.run import _handoff_watch_scopes++ return [default_home] + [home for _name, home in _handoff_watch_scopes(runner) if home is not None]async def restore_heartbeat_watches(runner) -> None:@@ -54,7 +54,7 @@ async def restore_heartbeat_watches(runner) -> None:home = getattr(store, "_routing_home", None) or get_hermes_home()# Cheap gate: with no heartbeat persisted in any served profile there is nothing to# restore — skip the per-origin profile-scope re-parse over every routed session.- if not any(_profile_has_heartbeat_keys(h) for h in _served_profile_homes(runner, home)):+ if not any(_profile_has_active_heartbeat(h) for h in _watched_homes(runner, home)):return restoredwith _profile_runtime_scope(home):entries = store.list_sessions()diff --git a/tests/gateway/test_handoff_watcher_multiprofile.py b/tests/gateway/test_handoff_watcher_multiprofile.pyindex c61deb449e9..54a1904d139 100644--- a/tests/gateway/test_handoff_watcher_multiprofile.py+++ b/tests/gateway/test_handoff_watcher_multiprofile.py@@ -89,98 +89,6 @@ class _RecordingDB:return []-class _ProbeDB:- """Probe-side store stub for the idle gate (goals SessionDB cache)."""-- def __init__(self, pending):- self._pending = pending-- def has_pending_handoffs(self):- return self._pending---async def test_watcher_gates_profile_scope_on_pending_handoffs(monkeypatch):- """Idle profiles must not pay the scope entry (config/secret re-parse) every tick.-- The gate probes the profile's store off-loop; only a store WITH a pending handoff gets- its scope entered by the tick. Both directions are the contract: no work → no scope- entry; work present → scope entered and the store polled. The startup reclaim is- exempt (once per boot, and it must also see 'running' leftovers)."""- scopes = [- (None, None),- ("bala", Path("/h/profiles/bala")),- ("medicina", Path("/h/profiles/medicina")),- ]- monkeypatch.setattr(run, "_handoff_watch_scopes", lambda _r: scopes)-- from hermes_cli import goals-- entered = []-- class _SpyScope:- def __init__(self, home):- self.home = home-- async def __aenter__(self):- entered.append(self.home)- return self-- async def __aexit__(self, *exc):- return False-- monkeypatch.setattr(run, "_async_profile_runtime_scope", _SpyScope)-- async def _no_sleep(_seconds):- return None-- monkeypatch.setattr(run.asyncio, "sleep", _no_sleep)-- homes = [h for _n, h in scopes[1:]]-- async def _run_once(pending_by_home):- monkeypatch.setattr(- goals, "_DB_CACHE",- {str(h): _ProbeDB(pending_by_home[h]) for h in homes})- entered.clear()- db = _RecordingDB()- states = iter([True, False])-- class _Running:- def __bool__(_self):- try:- return next(states)- except StopIteration:- return False-- fake = types.SimpleNamespace()- fake._session_db = db- fake._running = _Running()- fake._run_in_executor_with_context = asyncio.to_thread-- async def _process_handoff(row, profile_name=None):- return None-- fake._process_handoff = _process_handoff- coro = run.GatewayRunner._handoff_watcher(fake, interval=0.0)- await asyncio.wait_for(coro, timeout=5)- return db-- # Idle: nothing pending anywhere → the tick skips both named scopes (only the- # startup reclaim enters them, once each); the unscoped root poll still runs.- db = await _run_once({h: False for h in homes})- assert entered == homes, (- f"only the startup reclaim may enter idle profile scopes; got {entered}")- assert db.polls == 1, "only the root store is polled when no profile has work"-- # Work in one profile → the tick enters THAT profile's scope (reclaim + tick),- # while the still-idle profile is entered only by the reclaim.- db = await _run_once({homes[0]: True, homes[1]: False})- assert entered == [homes[0], homes[1], homes[0]], (- f"tick must enter exactly the profile with pending work; got {entered}")- assert db.polls == 2, "root + the busy profile are polled"--@pytest.mark.asyncioasync def test_watcher_enters_profile_scope_for_each_home(monkeypatch):"""Each non-root home is polled INSIDE ``_profile_runtime_scope``.