Skip to content

The agent that grows with you

fix(gateway): keep heartbeat admission on its watched route

Teknium3be1b87af10f
diff --git a/evals/heartbeat_idle_wire.py b/evals/heartbeat_idle_wire.py
new file mode 100644
index 00000000000..d9e88e848b6
--- /dev/null
+++ b/evals/heartbeat_idle_wire.py
@@ -0,0 +1,136 @@
+"""Wire-contract probe: real poller, SQLite, adapter lifecycle; fake model/transport.
+
+Run from the repo with a clean environment and a temporary HERMES_HOME:
+ .venv/bin/python evals/heartbeat_idle_wire.py
+Pass --base-poller /tmp/run_goals_base.py to compare the old poller. No network.
+"""
+
+import argparse
+import asyncio
+import json
+import os
+import sys
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import patch
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from gateway.config import GatewayConfig, Platform, PlatformConfig # noqa: E402
+from gateway.platforms.base import BasePlatformAdapter, MessageEvent, SendResult # noqa: E402
+from gateway.run import GatewayRunner # noqa: E402
+from gateway.session import SessionSource, SessionStore, build_session_key # noqa: E402
+from hermes_cli import heartbeat # noqa: E402
+
+
+class WireAdapter(BasePlatformAdapter):
+ async def connect(self, *, is_reconnect=False):
+ return True
+
+ async def disconnect(self):
+ pass
+
+ async def get_chat_info(self, chat_id):
+ return {}
+
+ async def send(self, chat_id, content, reply_to=None, metadata=None):
+ self.wire.append(content)
+ return SendResult(success=True, message_id=str(len(self.wire)))
+
+
+async def main(base_poller):
+ assert os.environ.get("HERMES_HOME"), "Use a temporary HERMES_HOME"
+ runner = object.__new__(GatewayRunner)
+ runner._running_agents = {}
+ runner._run_in_executor_with_context = asyncio.to_thread
+ adapter = WireAdapter(PlatformConfig(enabled=True, typing_indicator=False), Platform.TELEGRAM)
+ adapter.wire = []
+ runner._adapter_for_source = lambda source: adapter
+ source = SessionSource(platform=Platform.TELEGRAM, chat_id="42", user_id="42", chat_type="dm")
+ key = build_session_key(source)
+ watch = {key: (source, "wire-session")}
+ if base_poller:
+ scope = {"__name__": "heartbeat_base"}
+ exec(compile(Path(base_poller).read_text(encoding="utf-8"), base_poller, "exec"), scope)
+ runner._heartbeat_poll_once = scope["GatewayGoalsMixin"]._heartbeat_poll_once.__get__(runner)
+ await runner._warm_goals_session_db("wire-contract")
+ clock = SimpleNamespace(now=1000.0)
+ received = []
+ release = asyncio.Event()
+
+ async def handler(event):
+ received.append(event.text)
+ await release.wait()
+ return "wire reply"
+
+ async def drain():
+ while adapter._background_tasks:
+ await asyncio.gather(*list(adapter._background_tasks))
+
+ def snapshot():
+ return {"turns": len(received), "queue_depth": runner._queue_depth(key, adapter=adapter),
+ "fire_count": heartbeat.HeartbeatManager("wire-session").state.fire_count}
+
+ adapter.set_message_handler(handler)
+ await adapter.connect()
+ with patch.object(heartbeat, "time", SimpleNamespace(time=lambda: clock.now)):
+ heartbeat.HeartbeatManager("wire-session").set("check status", 60)
+ for _ in range(15):
+ clock.now += 60
+ await runner._heartbeat_poll_once(watch)
+ await asyncio.sleep(0)
+ print(json.dumps({"phase": "15 minute polls, first turn held", **snapshot()}))
+ release.set()
+ await adapter.handle_message(MessageEvent(text="real-user-wire-input", source=source))
+ await drain()
+ print(json.dumps({"phase": "user wake drain", "wire_sends": len(adapter.wire), **snapshot()}))
+ if not base_poller:
+ assert len(received) == 2 and len(adapter.wire) == 2
+ assert snapshot()["queue_depth"] == 0
+ # A genuinely idle 15-minute gap coalesces to one, even with repeated polls.
+ heartbeat.HeartbeatManager("wire-session").set("check status", 60)
+ before = len(received)
+ clock.now += 900
+ for _ in range(5):
+ await runner._heartbeat_poll_once(watch)
+ await drain()
+ assert len(received) - before == 1
+ assert heartbeat.HeartbeatManager("wire-session").state.fire_count == 1
+ print(json.dumps({"phase": "idle 15-minute gap + 5 same-time polls", "new_turns": 1,
+ "queue_depth": snapshot()["queue_depth"], "fire_count": 1}))
+ # A pinned route must not enter the pre-claim executor recovery gap.
+ # The callback represents competing traffic changing the last active topic.
+ recovery = []
+ adapter._topic_recovery_fn = lambda source: recovery.append(source) or "foreign-topic"
+ clock.now += 60
+ await runner._heartbeat_poll_once(watch)
+ assert key in adapter._active_sessions and recovery == []
+ await drain()
+ print(json.dumps({"phase": "pinned route", "recovery_calls": len(recovery)}))
+ runner.config = GatewayConfig()
+ runner.session_store = SessionStore(
+ sessions_dir=Path(os.environ["HERMES_HOME"]) / "sessions", config=runner.config)
+ runner.adapters = {Platform.TELEGRAM: adapter}
+ runner._profile_adapters = {}
+ runner._recover_telegram_topic_thread_id = adapter._topic_recovery_fn
+ event = MessageEvent(text="pinned heartbeat", source=source,
+ metadata={"gateway_session_key": key})
+ resolved = await runner._hmwa_resolve_session(event, source)
+ assert resolved is not None and resolved[2] == key and recovery == []
+ print(json.dumps({"phase": "runner pinned route", "session_key": resolved[2],
+ "recovery_calls": len(recovery)}))
+ # Route mismatch is a real adapter rejection, not a fabricated return value.
+ adapter._session_key_profile = lambda source: "different-profile"
+ clock.now += 60
+ before = heartbeat.HeartbeatManager("wire-session").state.to_json()
+ await runner._heartbeat_poll_once(watch)
+ assert heartbeat.HeartbeatManager("wire-session").state.to_json() == before
+ assert snapshot()["queue_depth"] == 0
+ print(json.dumps({"phase": "rejected route", "claim_refunded": True}))
+ await adapter.disconnect()
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--base-poller")
+ asyncio.run(main(parser.parse_args().base_poller))
diff --git a/gateway/platforms/base.py b/gateway/platforms/base.py
index e575aa7634a..5c115fcf59a 100644
--- a/gateway/platforms/base.py
+++ b/gateway/platforms/base.py
@@ -3569,12 +3569,13 @@ class BasePlatformAdapter(ABC):
return
if event.allow_gateway_control:
coerce_plaintext_gateway_command(event)
- # Topic recovery is Telegram-DM-only; skip the executor hop for group traffic.
- if (getattr(self, "_topic_recovery_fn", None) is not None
+ expected_session_key = str((event.metadata or {}).get("gateway_session_key") or "").strip()
+ # Explicitly routed events already name their destination; recovering a
+ # different topic would redirect them and yield before the session claim.
+ if (not expected_session_key and getattr(self, "_topic_recovery_fn", None) is not None
and event.source.platform == Platform.TELEGRAM and event.source.chat_type == "dm"):
await asyncio.to_thread(self._apply_topic_recovery, event)
session_key = self._event_session_key(event)
- expected_session_key = str((event.metadata or {}).get("gateway_session_key") or "").strip()
if expected_session_key and session_key != expected_session_key:
logger.warning("Dropping internally routed event: expected session=%s derived=%s",
expected_session_key, session_key)
diff --git a/gateway/run_turn.py b/gateway/run_turn.py
index f6ed37af2a0..dc6e59997cb 100644
--- a/gateway/run_turn.py
+++ b/gateway/run_turn.py
@@ -258,7 +258,10 @@ class GatewayTurnMixin:
the event."""
# Topic-mode DMs: rewrite a stale/foreign thread_id to the user's last-active topic so a
# cross-topic Reply doesn't fragment the conversation.
- recovered = await asyncio.to_thread(self._recover_telegram_topic_thread_id, source)
+ event_metadata = getattr(event, "metadata", None) or {}
+ expected_session_key = str(event_metadata.get("gateway_session_key") or "").strip()
+ recovered = (await asyncio.to_thread(self._recover_telegram_topic_thread_id, source)
+ if not expected_session_key else None)
if recovered is not None:
logger.info(
"telegram topic recovery: chat=%s user=%s %r -> %s",
@@ -268,8 +271,6 @@ class GatewayTurnMixin:
with suppress(Exception):
event.source = source
- event_metadata = getattr(event, "metadata", None) or {}
- expected_session_key = str(event_metadata.get("gateway_session_key") or "").strip()
if expected_session_key:
derived_session_key = self._session_key_for_source(source)
if derived_session_key != expected_session_key:
diff --git a/tests/gateway/test_heartbeat_poller.py b/tests/gateway/test_heartbeat_poller.py
new file mode 100644
index 00000000000..a49547e7771
--- /dev/null
+++ b/tests/gateway/test_heartbeat_poller.py
@@ -0,0 +1,111 @@
+"""Heartbeat polls wake idle adapters, never accumulate deferred ticks."""
+
+import asyncio
+from types import SimpleNamespace
+
+import pytest
+
+from gateway.config import Platform, PlatformConfig
+from gateway.platforms.base import BasePlatformAdapter, MessageEvent, SendResult
+from gateway.run import GatewayRunner
+from gateway.session import SessionSource, build_session_key
+from hermes_cli.heartbeat import HeartbeatManager
+
+
+class _HeartbeatAdapter(BasePlatformAdapter):
+ """Real adapter lifecycle with an in-memory wire transport, no bot/model."""
+
+ async def connect(self, *, is_reconnect=False):
+ return True
+
+ async def disconnect(self):
+ pass
+
+ async def get_chat_info(self, chat_id):
+ return {}
+
+ async def send(self, chat_id, content, reply_to=None, metadata=None):
+ return SendResult(success=True, message_id="wire-1")
+
+
+def poller(monkeypatch):
+ from hermes_cli import goals, heartbeat
+
+ goals._DB_CACHE.clear()
+ goals._get_session_db()
+ clock = SimpleNamespace(now=1000.0)
+ monkeypatch.setattr(heartbeat, "time", SimpleNamespace(time=lambda: clock.now))
+ source = SessionSource(platform=Platform.TELEGRAM, chat_id="42", user_id="42", chat_type="dm")
+ key = build_session_key(source)
+ adapter = _HeartbeatAdapter(PlatformConfig(enabled=True, typing_indicator=False), Platform.TELEGRAM)
+ runner = object.__new__(GatewayRunner)
+ runner._running_agents = {}
+ runner._adapter_for_source = lambda source: adapter
+ runner._run_in_executor_with_context = asyncio.to_thread
+ watch = {key: (source, "heartbeat-session")}
+ HeartbeatManager("heartbeat-session").set("check status", 60)
+ yield runner, adapter, watch, key, clock
+ goals._DB_CACHE.clear()
+
+
+async def test_idle_wake_coalesces_intervals_while_adapter_owns_turn(poller):
+ runner, adapter, watch, key, clock = poller
+ started, release = asyncio.Event(), asyncio.Event()
+ received = []
+
+ async def handler(event):
+ received.append(event)
+ started.set()
+ await release.wait()
+ return None
+
+ adapter.set_message_handler(handler)
+ # A remembered topic must not redirect the watched session or introduce an
+ # executor yield between the idle check and the adapter's session claim.
+ adapter._topic_recovery_fn = lambda source: "another-topic"
+ try:
+ clock.now += 60
+ await runner._heartbeat_poll_once(watch)
+ assert key in adapter._active_sessions, "idle poll must start a turn, not park it in FIFO"
+ await asyncio.wait_for(started.wait(), 2)
+ for _ in range(14):
+ clock.now += 60
+ await runner._heartbeat_poll_once(watch)
+ assert len(received) == 1
+ assert not received[0].internal # authorization and emergency-stop still apply
+ assert runner._queue_depth(key, adapter=adapter) == 0
+ assert HeartbeatManager("heartbeat-session").state.fire_count == 1
+ finally:
+ release.set()
+ await asyncio.gather(*adapter._background_tasks)
+
+
+async def test_unavailable_or_busy_session_leaves_persisted_tick_due(poller):
+ runner, adapter, watch, key, clock = poller
+ clock.now += 900
+ original = HeartbeatManager("heartbeat-session").state.to_json()
+ user = MessageEvent(text="user follow-up", source=watch[key][0])
+ # Missing adapter and missing handler must not consume a due tick.
+ runner._adapter_for_source = lambda source: None
+ await runner._heartbeat_poll_once(watch)
+ runner._adapter_for_source = lambda source: adapter
+ await runner._heartbeat_poll_once(watch)
+
+ async def handler(event):
+ return None
+
+ adapter.set_message_handler(handler)
+ for state in (runner._running_agents, adapter._active_sessions, adapter._pending_messages):
+ state[key] = user
+ await runner._heartbeat_poll_once(watch)
+ assert state[key] is user
+ state.pop(key)
+ assert HeartbeatManager("heartbeat-session").state.to_json() == original
+ await runner._heartbeat_poll_once(watch)
+ assert key in adapter._active_sessions
+ await asyncio.gather(*adapter._background_tasks)
+ assert HeartbeatManager("heartbeat-session").state.fire_count == 1
+ assert runner._queue_depth(key, adapter=adapter) == 0
diff --git a/website/docs/user-guide/features/heartbeat.md b/website/docs/user-guide/features/heartbeat.md
index 87c49e25f8a..56895fb1f94 100644
--- a/website/docs/user-guide/features/heartbeat.md
+++ b/website/docs/user-guide/features/heartbeat.md
@@ -41,7 +41,7 @@ Rule of thumb: if the recurring prompt needs the conversation's context, use `/h
## Behavior details
-- **Idle-only.** A heartbeat never interrupts a running turn. If the agent is busy when the tick comes due, it fires at the next idle poll.
+- **Idle-only.** A heartbeat never interrupts a running turn. If the agent is busy when the tick comes due, it fires at the next idle poll. In the gateway, an idle watched session wakes proactively; no new inbound message is needed.
- **Missed ticks coalesce.** If the session was busy (or the process wasn't running) through several intervals, you get **one** heartbeat turn, not a backlog. The timer re-anchors on every fire.
- **User messages win.** A queued user message always takes priority; the heartbeat waits for the input queue to drain.
- **Cache-safe.** The injected prompt is an ordinary user message. No system-prompt mutation, no toolset change.