Skip to content

The agent that grows with you

fix: keep heartbeat watches in their route and profile lifecycle

Teknium27fa0b7eef48
diff --git a/gateway/run_goals.py b/gateway/run_goals.py
index b3f6e80c871..2d54e93606c 100644
--- a/gateway/run_goals.py
+++ b/gateway/run_goals.py
@@ -103,9 +103,7 @@ class GatewayGoalsMixin:
return MessageEvent(text=text, message_type=MessageType.TEXT, source=source, internal=internal)
def _register_heartbeat_watch(self, quick_key: str, source: Any, session_id: str) -> None:
- """Track a session with an active heartbeat (``quick_key`` → ``(source, session_id)``) and
- start the poller. In-memory by design: heartbeat STATE survives restarts in SessionDB, but
- firing resumes only when the user touches /heartbeat again."""
+ """Track the canonical route and start the restart-recoverable poller."""
watch = getattr(self, "_heartbeat_watch", None)
if watch is None:
watch = self._heartbeat_watch = {}
@@ -117,40 +115,49 @@ class GatewayGoalsMixin:
async def _heartbeat_poll_once(self, watch: dict) -> None:
"""Wake each idle watched session once; leave busy sessions' ticks unclaimed."""
- # Off-loop warm-up covers the degraded path where /heartbeat's own warm-up failed.
- await self._warm_goals_session_db("heartbeat poll")
for quick_key, (source, session_id) in list(watch.items()):
try:
- adapter = self._adapter_for_source(source)
- if adapter is None or not adapter._message_handler:
- continue
- if (
- self._is_session_running(quick_key)
- or quick_key in adapter._active_sessions
- or self._queue_depth(quick_key, adapter=adapter) > 0
- ):
- continue # keep missed intervals due until user work has drained
- from hermes_cli.heartbeat import HeartbeatManager
-
- mgr = HeartbeatManager(session_id=session_id)
- if not mgr.has_heartbeat():
- watch.pop(quick_key, None)
- continue
- prompt = mgr.due_prompt()
- if not prompt:
- continue
- event = self._synthetic_prompt_event(source, prompt)
- event.metadata["gateway_session_key"] = quick_key
- # A pinned route skips topic recovery: no await between the idle
- # check and adapter claim. FIFO alone never wakes an idle session.
- try:
- await adapter.handle_message(event)
- finally:
- if quick_key not in adapter._active_sessions:
- mgr.abandon_fire()
+ with self._profile_scope_for_source(source):
+ await self._heartbeat_poll_watch(watch, quick_key, source, session_id)
except Exception as exc:
logger.debug("heartbeat poll for %s failed: %s", quick_key, exc)
+ async def _heartbeat_poll_watch(self, watch, quick_key, source, session_id):
+ await self._warm_goals_session_db("heartbeat poll")
+ store = getattr(self, "session_store", None)
+ if store is not None:
+ current = store.peek_session_id(quick_key)
+ if current:
+ session_id = current
+ watch[quick_key] = (source, session_id)
+ adapter = self._adapter_for_source(source)
+ if adapter is None or not adapter._message_handler:
+ return
+ if (
+ self._is_session_running(quick_key)
+ or quick_key in adapter._active_sessions
+ or self._queue_depth(quick_key, adapter=adapter) > 0
+ ):
+ return # keep missed intervals due until user work has drained
+ from hermes_cli.heartbeat import HeartbeatManager
+
+ mgr = HeartbeatManager(session_id=session_id)
+ if not mgr.has_heartbeat():
+ watch.pop(quick_key, None)
+ return
+ prompt = mgr.due_prompt()
+ if not prompt:
+ return
+ event = self._synthetic_prompt_event(source, prompt)
+ event.metadata["gateway_session_key"] = quick_key
+ # A pinned route skips topic recovery: no await between the idle
+ # check and adapter claim. FIFO alone never wakes an idle session.
+ try:
+ await adapter.handle_message(event)
+ finally:
+ if quick_key not in adapter._active_sessions:
+ mgr.abandon_fire()
+
def _start_heartbeat_poller(self) -> None:
"""Start the single gateway-wide heartbeat poll task (idempotent)."""
existing = getattr(self, "_heartbeat_poll_task", None)
@@ -162,6 +169,8 @@ class GatewayGoalsMixin:
async def _poll_loop():
while True:
await asyncio.sleep(POLL_SECONDS)
+ from gateway.run_heartbeat_restore import restore_heartbeat_watches
+ await restore_heartbeat_watches(self)
watch = getattr(self, "_heartbeat_watch", None)
if watch:
await self._heartbeat_poll_once(watch)
diff --git a/tests/gateway/test_heartbeat_watch_lifecycle.py b/tests/gateway/test_heartbeat_watch_lifecycle.py
new file mode 100644
index 00000000000..f09bf34830a
--- /dev/null
+++ b/tests/gateway/test_heartbeat_watch_lifecycle.py
@@ -0,0 +1,76 @@
+"""Heartbeat watches follow their route and profile, not the poller's creator."""
+import asyncio
+from types import SimpleNamespace
+
+import pytest
+
+from gateway.config import Platform
+from gateway.run import GatewayRunner, _profile_runtime_scope
+from gateway.session import SessionSource
+from hermes_cli.heartbeat import HeartbeatManager, HeartbeatState, save_heartbeat, migrate_heartbeat_to_session
+from hermes_constants import get_hermes_home
+
+
+async def test_watches_read_and_admit_in_each_owner_profile(tmp_path, monkeypatch):
+ monkeypatch.setattr('pathlib.Path.home', lambda: tmp_path)
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path / '.hermes'))
+ runner = object.__new__(GatewayRunner)
+ runner.config = SimpleNamespace(multiplex_profiles=True)
+ runner._run_in_executor_with_context = asyncio.to_thread
+ runner._is_session_running = lambda key: False
+ runner._queue_depth = lambda key, adapter: 0
+ rows = []
+
+ class Adapter:
+ _message_handler = True
+ _active_sessions = {}
+
+ async def handle_message(self, event):
+ rows.append((event.source.profile, str(get_hermes_home()), event.text))
+ self._active_sessions[event.metadata['gateway_session_key']] = True
+
+ runner._adapter_for_source = lambda source: Adapter()
+ watch = {}
+ for name in ('alpha', 'beta'):
+ home = tmp_path / '.hermes' / 'profiles' / name
+ home.mkdir(parents=True, exist_ok=True)
+ (home / 'config.yaml').write_text('{}\n')
+ with _profile_runtime_scope(home):
+ await runner._warm_goals_session_db('test')
+ save_heartbeat(name, HeartbeatState(prompt=name, interval_seconds=60, created_at=1))
+ watch[name] = (SessionSource(platform=Platform.TELEGRAM, chat_id=name, profile=name), name)
+ with _profile_runtime_scope(tmp_path / '.hermes' / 'profiles' / 'alpha'):
+ await runner._heartbeat_poll_once(watch)
+ assert {row[0] for row in rows} == {'alpha', 'beta'}
+ assert all(row[1] == str(tmp_path / '.hermes' / 'profiles' / row[0]) for row in rows)
+ assert len(watch) == 2
+
+
+async def test_watch_tracks_rotated_route_owner_without_reviving_parent():
+ runner = object.__new__(GatewayRunner)
+ runner._run_in_executor_with_context = asyncio.to_thread
+ runner._is_session_running = lambda key: False
+ runner._queue_depth = lambda key, adapter: 0
+ runner.session_store = SimpleNamespace(peek_session_id=lambda key: 'child')
+ events = []
+
+ class Adapter:
+ _message_handler = True
+ _active_sessions = {}
+
+ async def handle_message(self, event):
+ events.append(event)
+ self._active_sessions['route'] = True
+
+ runner._adapter_for_source = lambda source: Adapter()
+ await runner._warm_goals_session_db('test')
+ save_heartbeat('parent', HeartbeatState(prompt='follow rotation', interval_seconds=60, created_at=1))
+ assert migrate_heartbeat_to_session('parent', 'child')
+ source = SessionSource(platform=Platform.TELEGRAM, chat_id='chat')
+ watch = {'route': (source, 'parent')}
+ await runner._heartbeat_poll_once(watch)
+ assert len(events) == 1
+ assert watch['route'][1] == 'child'
+ assert HeartbeatManager('parent').state is None