Skip to content

The agent that grows with you

fix(heartbeat): let one driver claim an overdue tick

unsupportedpastelsee208f149dd6
diff --git a/hermes_cli/heartbeat.py b/hermes_cli/heartbeat.py
index b10a5846fbf..2e5548bf969 100644
--- a/hermes_cli/heartbeat.py
+++ b/hermes_cli/heartbeat.py
@@ -10,6 +10,7 @@ from __future__ import annotations
import json
import logging
import re
+import threading
import time
from dataclasses import asdict, dataclass
from typing import Any, Optional
@@ -100,6 +101,7 @@ def _get_session_db() -> Optional[Any]:
_META_PREFIX = "heartbeat:"
+_CLAIM_LOCK = threading.Lock() # every driver of a session's heartbeat runs in its owning gateway process
def load_heartbeat(session_id: str) -> Optional[HeartbeatState]:
@@ -220,14 +222,21 @@ class HeartbeatManager:
double-fire the same tick. Missed ticks coalesce: the anchor resets to NOW, not the theoretical
schedule.
"""
- s = self._state
- if s is None or not s.is_due(now):
- return None
- self._last_claim = (s.last_fired_at, s.fire_count)
- s.last_fired_at = now if now is not None else time.time()
- s.fire_count += 1
- save_heartbeat(self.session_id, s)
- return s.render_prompt()
+ with _CLAIM_LOCK:
+ s = self._state
+ if s is None or not s.is_due(now):
+ return None
+ # Compare-and-set on the stored row: the gateway poller and a viewer's due_prompt RPC each hold
+ # their own manager over it, and only one may take the tick.
+ stored = load_heartbeat(self.session_id)
+ if stored is not None and (stored.last_fired_at, stored.fire_count) != (s.last_fired_at, s.fire_count):
+ self._state = stored
+ return None
+ self._last_claim = (s.last_fired_at, s.fire_count)
+ s.last_fired_at = now if now is not None else time.time()
+ s.fire_count += 1
+ save_heartbeat(self.session_id, s)
+ return s.render_prompt()
def abandon_fire(self) -> bool:
"""Rewind the fire recorded by the last :meth:`due_prompt` whose turn never started, so the tick stays
diff --git a/tests/gateway/test_local_chat_delivery.py b/tests/gateway/test_local_chat_delivery.py
index 4d84cdad3ca..8693bfbd451 100644
--- a/tests/gateway/test_local_chat_delivery.py
+++ b/tests/gateway/test_local_chat_delivery.py
@@ -5,6 +5,7 @@ rides the event stream), so a Kanban wake, a due heartbeat or a cron result that
adapter path was refused or silently dropped.
"""
import asyncio
+import threading
import time
import pytest
@@ -28,20 +29,50 @@ async def test_kanban_wake_is_admitted_into_a_local_chat(tmp_path, monkeypatch):
assert len(_admissions(authority, ref, 'card t1 done')) == 1
+def _overdue_heartbeat(session_id):
+ from hermes_cli.heartbeat import HeartbeatManager, save_heartbeat
+ state = HeartbeatManager(session_id).set('status tick', 60)
+ state.created_at = time.time() - 120 # one interval overdue
+ save_heartbeat(session_id, state)
+
+
+def _heartbeat_admissions(authority, ref):
+ from hermes_state_runtime import list_session_admissions
+ rows = list_session_admissions(authority.db, session_id=ref.session_id, pending_only=False)
+ return [row for row in rows if row['payload'].get('local_automation_v1', {}).get('heartbeat')]
+
+
@pytest.mark.asyncio
async def test_due_heartbeat_is_admitted_into_a_local_chat(tmp_path, monkeypatch):
from gateway.run_heartbeat_restore import restore_heartbeat_watches
- from hermes_cli.heartbeat import HeartbeatManager, load_heartbeat, save_heartbeat
runner, authority, ref, _ = await _local(tmp_path, monkeypatch)
- HeartbeatManager(ref.session_id).set('status tick', 60)
- state = load_heartbeat(ref.session_id)
- state.created_at = time.time() - 120 # one interval overdue
- save_heartbeat(ref.session_id, state)
+ _overdue_heartbeat(ref.session_id)
await restore_heartbeat_watches(runner)
await runner._heartbeat_poll_once(runner._heartbeat_watch)
- from hermes_state_runtime import list_session_admissions
- rows = list_session_admissions(authority.db, session_id=ref.session_id, pending_only=False)
- assert [row for row in rows if row['payload'].get('local_automation_v1', {}).get('heartbeat')]
+ assert _heartbeat_admissions(authority, ref)
+
+
+async def test_overdue_heartbeat_fires_once_with_a_classic_cli_also_polling(tmp_path, monkeypatch):
+ from gateway.run_heartbeat_restore import restore_heartbeat_watches
+ from gateway.session_viewer_automation import invoke
+ from hermes_cli.heartbeat import HeartbeatManager
+ runner, authority, ref, _ = await _local(tmp_path, monkeypatch)
+ _overdue_heartbeat(ref.session_id)
+ await restore_heartbeat_watches(runner)
+ loop, claim, polled = asyncio.get_running_loop(), HeartbeatManager.due_prompt, []
+
+ def due_prompt(self, now=None):
+ # The CLI's due_prompt RPC (worker thread) has loaded the overdue row when the gateway poller claims it.
+ if threading.current_thread() is not threading.main_thread() and not polled:
+ polled.append(True)
+ asyncio.run_coroutine_threadsafe(runner._heartbeat_poll_once(runner._heartbeat_watch), loop).result()
+ return claim(self, now)
+
+ monkeypatch.setattr(HeartbeatManager, 'due_prompt', due_prompt)
+ cli = await asyncio.to_thread(invoke, runner, 'heartbeat', ref.session_id, 'due_prompt', [], {})
+ assert polled
+ assert len(_heartbeat_admissions(authority, ref)) + bool(cli['value']) == 1
@pytest.mark.asyncio