Skip to content

The agent that grows with you

fix(gateway): skip heartbeat restore sweep when no heartbeat is persisted

Andre5d7fa6bc2034
diff --git a/gateway/run_heartbeat_restore.py b/gateway/run_heartbeat_restore.py
index 724572b78b9..80d1f0949c7 100644
--- a/gateway/run_heartbeat_restore.py
+++ b/gateway/run_heartbeat_restore.py
@@ -6,6 +6,37 @@ import logging
logger = logging.getLogger("gateway.run")
+def _profile_has_heartbeat_keys(profile_home) -> bool:
+ """Indexed ``heartbeat:*`` probe on one profile's SessionDB — no config/secret parsing.
+
+ Only the HERMES_HOME override (a contextvar) is installed; the expensive secret/terminal
+ scopes are skipped. Fails OPEN: a probe error must not suppress the restore sweep.
+ """
+ from hermes_cli.goals import _get_session_db
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+
+ token = set_hermes_home_override(str(profile_home))
+ try:
+ db = _get_session_db()
+ return bool(db is not None and db.list_meta_prefix("heartbeat:"))
+ except Exception:
+ logger.debug("heartbeat probe failed for %s; running full sweep", profile_home, exc_info=True)
+ return True
+ finally:
+ reset_hermes_home_override(token)
+
+
+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]
+
+
async def restore_heartbeat_watches(runner) -> None:
"""Retryable startup/poll scan; failed reads never prune existing watches.
@@ -24,6 +55,10 @@ async def restore_heartbeat_watches(runner) -> None:
# The poller may have been spawned by a named profile's /heartbeat command.
# Anchor even default origins to the gateway home, not inherited context.
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)):
+ return restored
with _profile_runtime_scope(home):
entries = store.list_sessions()
for entry in entries:
diff --git a/tests/gateway/test_heartbeat_watch_restore.py b/tests/gateway/test_heartbeat_watch_restore.py
index 8561485b2b6..e88559cea4c 100644
--- a/tests/gateway/test_heartbeat_watch_restore.py
+++ b/tests/gateway/test_heartbeat_watch_restore.py
@@ -79,6 +79,44 @@ async def test_restore_retries_persisted_routes_in_their_own_profiles(tmp_path,
db.close()
+async def test_restore_skips_session_sweep_when_no_heartbeats_exist(tmp_path, monkeypatch):
+ """Idle case: no ``heartbeat:*`` key in any served profile → the restore poll must not
+ sweep the routing index (each swept origin re-parses that profile's config/secrets)."""
+ from gateway.run_heartbeat_restore import restore_heartbeat_watches
+
+ home = tmp_path / '.hermes'
+ named = home / 'profiles' / 'work'
+ named.mkdir(parents=True)
+ (named / 'config.yaml').write_text('{}')
+ monkeypatch.setattr(Path, 'home', lambda: tmp_path)
+ monkeypatch.setenv('HERMES_HOME', str(home))
+ dbs = {str(p): SessionDB(db_path=p / 'state.db') for p in (home, named)}
+ monkeypatch.setattr(goals, '_DB_CACHE', dbs)
+ config = GatewayConfig(multiplex_profiles=True)
+ store = SessionStore(home / 'sessions', config)
+ try:
+ source = SessionSource(platform=Platform.TELEGRAM, chat_id='chat',
+ thread_id='7', profile=None, scope_id=None)
+ store.get_or_create_session(source)
+ runner = GatewayRunner.__new__(GatewayRunner)
+ runner.config = config
+ runner.session_store = store
+ runner._heartbeat_watch = {}
+ runner._run_in_executor_with_context = asyncio.to_thread
+ sweeps = []
+ original = store.list_sessions
+ monkeypatch.setattr(store, 'list_sessions',
+ lambda: (sweeps.append(1), original())[1])
+ await restore_heartbeat_watches(runner)
+ assert sweeps == []
+ assert runner._heartbeat_watch == {}
+ finally:
+ store.close_all_db_handles()
+ for db in dbs.values():
+ db.close()
+
+
@pytest.mark.asyncio
async def test_startup_arms_retry_poller_even_without_any_watches(monkeypatch):
runner = GatewayRunner.__new__(GatewayRunner)