Skip to content

The agent that grows with you

fix(gateway): run wake-only kanban delivery before cursor advance with rewind/retry

Tekniumf57116b23135
diff --git a/gateway/kanban_watchers.py b/gateway/kanban_watchers.py
index 24864f7b118..703375c470e 100644
--- a/gateway/kanban_watchers.py
+++ b/gateway/kanban_watchers.py
@@ -604,8 +604,9 @@ class GatewayKanbanWatchersMixin:
if not send_passive:
# Wake-only subscriptions intentionally skip the
# visible platform message. The retained wake path
- # below is the sole delivery.
- sub_fail_counts.pop(sub_key, None)
+ # below is the sole delivery — the failure counter
+ # is resolved (reset or bumped) by the wake
+ # outcome there, not by skipping the send here.
continue
try:
_send_res = await adapter.send(
@@ -792,10 +793,111 @@ class GatewayKanbanWatchersMixin:
)
continue
+ async def _push_wake() -> None:
+ """Wake the creator session behind a push adapter.
+
+ Shared by the wake-only (pre-advance, delivery)
+ and notify+wake (post-advance, best-effort)
+ branches below; raises on failure so the caller
+ decides whether to rewind or merely log.
+ """
+ from gateway.session import SessionSource
+ from gateway.wake import deliver_wake
+ # Rebuild the creator's real session scope from
+ # the chat_type persisted on the subscription
+ # row (#56580). build_session_key() keys DMs
+ # (":dm:<chat_id>") on a wholly different shape
+ # from group/thread, so the old hardcoded
+ # "group" mis-routed DM/thread creators into a
+ # fresh session. Legacy rows written before the
+ # column existed may still carry chat_type in
+ # delivery_metadata (#60600 rows) — fall back
+ # to that, then to "group" (the historical
+ # default that suits the dashboard/group flows).
+ # handle_message() get_or_create_session's the
+ # target, so a mismatch only ever degrades to a
+ # fresh session, never an exception.
+ _chat_type = str(sub.get("chat_type") or "").strip()
+ if not _chat_type:
+ _delivery_meta = sub.get("delivery_metadata")
+ if isinstance(_delivery_meta, dict):
+ _chat_type = str(
+ _delivery_meta.get("chat_type") or ""
+ ).strip()
+ _chat_type = _chat_type or "group"
+ _source = SessionSource(
+ platform=plat,
+ chat_id=sub["chat_id"],
+ chat_type=_chat_type,
+ thread_id=sub.get("thread_id") or None,
+ user_id=sub.get("user_id"),
+ user_id_alt=sub.get("user_id_alt"),
+ profile=sub_profile or None,
+ scope_id=_wake_scope_id(adapter, sub),
+ )
+ # deliver_wake preserves the synthetic
+ # MessageEvent/handle_message path for
+ # push-capable adapters (the non-push /
+ # self-post branch is handled BEFORE the
+ # cursor advance above).
+ await deliver_wake(
+ adapter,
+ text=_synth,
+ session_id=_session_key,
+ source=_source,
+ )
+ logger.info(
+ "kanban notifier: woke agent for %s on %s/%s profile=%s events=%s",
+ sub["task_id"], platform_str, sub["chat_id"], sub_profile or "default", _wake_kinds,
+ )
+
+ if _is_push_adapter and not send_passive and _wake_kinds:
+ # Wake-only (delivery_mode='wake') push sub: the
+ # text ping was intentionally skipped above, so
+ # the wake IS the sole delivery. It must succeed
+ # BEFORE the cursor advances — advancing first
+ # would let a failed wake (previously swallowed
+ # by the best-effort except below) permanently
+ # lose the event. Mirrors the non-push
+ # (api_server) self-post ordering above.
+ try:
+ await _push_wake()
+ sub_fail_counts.pop(sub_key, None)
+ except Exception as _wk_err:
+ fails = sub_fail_counts.get(sub_key, 0) + 1
+ sub_fail_counts[sub_key] = fails
+ logger.warning(
+ "kanban notifier: wake-only delivery failed "
+ "for %s (attempt %d/%d): %s",
+ sub["task_id"], fails,
+ MAX_SEND_FAILURES, _wk_err, exc_info=True,
+ )
+ if fails >= MAX_SEND_FAILURES:
+ logger.warning(
+ "kanban notifier: dropping subscription "
+ "%s on %s after %d consecutive wake failures",
+ sub["task_id"], platform_str, fails,
+ )
+ await asyncio.to_thread(self._kanban_unsub, sub, board_slug)
+ sub_fail_counts.pop(sub_key, None)
+ else:
+ # Rewind the pre-send claim so the next
+ # tick retries the wake — the event is
+ # NOT lost.
+ await asyncio.to_thread(
+ self._kanban_rewind,
+ sub,
+ d["cursor"],
+ d.get("old_cursor", 0),
+ board_slug,
+ )
+ continue
+
# Delivery complete (text ping for push adapters, wake
- # self-post for non-push): advance cursor. The cursor
- # is the dedup mechanism — it prevents re-delivery
- # of the same event on subsequent ticks.
+ # self-post for non-push, wake injection for wake-only
+ # push subs): advance cursor. The cursor is the dedup
+ # mechanism — it prevents re-delivery of the same
+ # event on subsequent ticks.
await asyncio.to_thread(
self._kanban_advance, sub, d["cursor"], board_slug,
)
@@ -810,57 +912,12 @@ class GatewayKanbanWatchersMixin:
# dispatcher respawns the task and it cycles into the
# same state. See the longer comment on TERMINAL_KINDS
# above for the failure mode this prevents.
- if _is_push_adapter and _wake_kinds:
+ if _is_push_adapter and send_passive and _wake_kinds:
+ # notify+wake: the text ping above was the
+ # delivery and the cursor has advanced; the wake
+ # injection stays best-effort.
try:
- from gateway.session import SessionSource
- from gateway.wake import deliver_wake
- # Rebuild the creator's real session scope from
- # the chat_type persisted on the subscription
- # row (#56580). build_session_key() keys DMs
- # (":dm:<chat_id>") on a wholly different shape
- # from group/thread, so the old hardcoded
- # "group" mis-routed DM/thread creators into a
- # fresh session. Legacy rows written before the
- # column existed may still carry chat_type in
- # delivery_metadata (#60600 rows) — fall back
- # to that, then to "group" (the historical
- # default that suits the dashboard/group flows).
- # handle_message() get_or_create_session's the
- # target, so a mismatch only ever degrades to a
- # fresh session, never an exception.
- _chat_type = str(sub.get("chat_type") or "").strip()
- if not _chat_type:
- _delivery_meta = sub.get("delivery_metadata")
- if isinstance(_delivery_meta, dict):
- _chat_type = str(
- _delivery_meta.get("chat_type") or ""
- ).strip()
- _chat_type = _chat_type or "group"
- _source = SessionSource(
- platform=plat,
- chat_id=sub["chat_id"],
- chat_type=_chat_type,
- thread_id=sub.get("thread_id") or None,
- user_id=sub.get("user_id"),
- user_id_alt=sub.get("user_id_alt"),
- profile=sub_profile or None,
- scope_id=_wake_scope_id(adapter, sub),
- )
- # deliver_wake preserves the synthetic
- # MessageEvent/handle_message path for
- # push-capable adapters (the non-push /
- # self-post branch is handled BEFORE the
- # cursor advance above).
- await deliver_wake(
- adapter,
- text=_synth,
- session_id=_session_key,
- source=_source,
- )
- logger.info(
- "kanban notifier: woke agent for %s on %s/%s profile=%s events=%s",
- sub["task_id"], platform_str, sub["chat_id"], sub_profile or "default", _wake_kinds,
- )
+ await _push_wake()
except Exception as _wk_err:
# Best-effort: the notification itself already
# delivered and the cursor has advanced, so a
diff --git a/tests/gateway/test_kanban_notifier_wake_only_ordering.py b/tests/gateway/test_kanban_notifier_wake_only_ordering.py
new file mode 100644
index 00000000000..a563c4f5522
--- /dev/null
+++ b/tests/gateway/test_kanban_notifier_wake_only_ordering.py
@@ -0,0 +1,202 @@
+"""Wake-only (delivery_mode='wake') push-adapter delivery ordering.
+
+For a push-adapter subscription in wake-only mode the visible text ping is
+intentionally skipped (the ``send_passive`` gate), so the wake injection IS
+the sole delivery. The cursor must therefore only advance AFTER the wake
+succeeds: advancing first and running the wake best-effort afterwards let a
+failed wake permanently lose the event — the exact bug class the non-push
+(api_server) self-post branch already guards against with rewind/retry.
+
+Residual insight extracted from closed PR #84191 (@MaximCrabbe).
+"""
+
+import asyncio
+
+from gateway.config import Platform
+from gateway.run import GatewayRunner
+from hermes_cli import kanban_db as kb
+
+
+class RecordingAdapter:
+ """Push-capable adapter (no supports_async_delivery attr => push)."""
+
+ def __init__(self):
+ self.sent = []
+ self.handled = []
+
+ async def send(self, chat_id, text, metadata=None):
+ self.sent.append({"chat_id": chat_id, "text": text, "metadata": metadata or {}})
+
+ async def handle_message(self, event):
+ self.handled.append(event)
+
+
+class FailingWakeAdapter(RecordingAdapter):
+ """Push adapter whose wake injection (handle_message) always fails."""
+
+ async def handle_message(self, event):
+ self.handled.append(event)
+ raise RuntimeError("simulated wake failure")
+
+
+async def _run_one_notifier_tick(monkeypatch, runner):
+ real_sleep = asyncio.sleep
+
+ async def fake_sleep(delay):
+ if delay == 5:
+ return None
+ runner._running = False
+ await real_sleep(0)
+
+ monkeypatch.setattr(asyncio, "sleep", fake_sleep)
+ await runner._kanban_notifier_watcher(interval=1)
+
+
+def _make_runner(adapter):
+ runner = GatewayRunner.__new__(GatewayRunner)
+ runner._running = True
+ runner.adapters = {Platform.TELEGRAM: adapter}
+ runner._kanban_sub_fail_counts = {}
+ runner._kanban_dispatcher_lock_handle = object()
+ return runner
+
+
+def _make_completed_task(delivery_mode):
+ conn = kb.connect()
+ try:
+ tid = kb.create_task(
+ conn,
+ title="wake ordering task",
+ assignee="worker",
+ session_id="agent:main:telegram:dm:chat-1",
+ )
+ kb.add_notify_sub(
+ conn,
+ task_id=tid,
+ platform="telegram",
+ chat_id="chat-1",
+ chat_type="dm",
+ delivery_mode=delivery_mode,
+ )
+ kb.complete_task(conn, tid, summary="done")
+ return tid
+ finally:
+ conn.close()
+
+
+def _unseen_terminal_events(tid):
+ conn = kb.connect()
+ try:
+ _, events = kb.unseen_events_for_sub(
+ conn,
+ task_id=tid,
+ platform="telegram",
+ chat_id="chat-1",
+ kinds=["completed", "blocked", "gave_up", "crashed", "timed_out"],
+ )
+ return events
+ finally:
+ conn.close()
+
+
+def _subs(tid):
+ conn = kb.connect()
+ try:
+ return kb.list_notify_subs(conn, tid)
+ finally:
+ conn.close()
+
+
+def test_wake_only_success_advances_cursor_single_wake(tmp_path, monkeypatch):
+ """Wake succeeds: exactly one wake, no text ping, cursor advanced."""
+ monkeypatch.setenv("HERMES_KANBAN_DB", str(tmp_path / "wake-ok.db"))
+ kb.init_db()
+ tid = _make_completed_task("wake")
+
+ adapter = RecordingAdapter()
+ runner = _make_runner(adapter)
+ asyncio.run(_run_one_notifier_tick(monkeypatch, runner))
+
+ assert adapter.sent == [], "wake-only mode must not send a text ping"
+ assert len(adapter.handled) == 1, "wake injection is the sole delivery"
+ assert _unseen_terminal_events(tid) == [], (
+ "cursor must advance after a successful wake-only delivery"
+ )
+ assert runner._kanban_sub_fail_counts == {}
+
+
+def test_wake_only_failure_rewinds_and_redelivers(tmp_path, monkeypatch):
+ """Wake fails: cursor rewound, counter bumped, event retried next tick."""
+ monkeypatch.setenv("HERMES_KANBAN_DB", str(tmp_path / "wake-fail.db"))
+ kb.init_db()
+ tid = _make_completed_task("wake")
+
+ adapter = FailingWakeAdapter()
+ runner = _make_runner(adapter)
+ asyncio.run(_run_one_notifier_tick(monkeypatch, runner))
+
+ assert len(adapter.handled) == 1, "one wake attempt on the first tick"
+ events = _unseen_terminal_events(tid)
+ assert len(events) == 1, (
+ "a failed wake-only delivery must REWIND the claim so the event "
+ "is redelivered on a later tick — it was permanently lost before "
+ "this fix (cursor advanced before the best-effort wake)"
+ )
+ assert list(runner._kanban_sub_fail_counts.values()) == [1], (
+ "failure counter must bump on a failed wake-only delivery"
+ )
+ assert len(_subs(tid)) == 1, "one transient failure must not drop the sub"
+
+ # Next tick: the same event is claimed and the wake retried.
+ runner2 = _make_runner(adapter)
+ runner2._kanban_sub_fail_counts = runner._kanban_sub_fail_counts
+ asyncio.run(_run_one_notifier_tick(monkeypatch, runner2))
+ assert len(adapter.handled) == 2, "event must be redelivered next tick"
+ assert list(runner2._kanban_sub_fail_counts.values()) == [2]
+
+
+def test_notify_wake_failure_stays_best_effort(tmp_path, monkeypatch):
+ """notify+wake: text ping IS the delivery; failed wake must NOT rewind."""
+ monkeypatch.setenv("HERMES_KANBAN_DB", str(tmp_path / "notify-wake.db"))
+ kb.init_db()
+ tid = _make_completed_task("notify+wake")
+
+ adapter = FailingWakeAdapter()
+ runner = _make_runner(adapter)
+ asyncio.run(_run_one_notifier_tick(monkeypatch, runner))
+
+ assert len(adapter.sent) == 1, "text ping delivered"
+ assert len(adapter.handled) == 1, "wake attempted best-effort"
+ assert _unseen_terminal_events(tid) == [], (
+ "notify+wake: cursor advances on text delivery; a failed wake is "
+ "best-effort and must not rewind"
+ )
+ assert runner._kanban_sub_fail_counts == {}, (
+ "best-effort wake failure must not bump the send-failure counter"
+ )
+ # (The sub itself unsubscribes because the task reached 'done' —
+ # pre-existing task_terminal behavior, unrelated to the wake outcome.)
+
+
+def test_wake_only_failure_cap_drops_subscription(tmp_path, monkeypatch):
+ """After MAX_SEND_FAILURES consecutive wake failures the sub is dropped."""
+ monkeypatch.setenv("HERMES_KANBAN_DB", str(tmp_path / "wake-cap.db"))
+ kb.init_db()
+ tid = _make_completed_task("wake")
+
+ adapter = FailingWakeAdapter()
+ runner = _make_runner(adapter)
+ # Simulate 11 prior consecutive failures (MAX_SEND_FAILURES = 12).
+ runner._kanban_sub_fail_counts = {
+ (tid, "telegram", "chat-1", ""): 11,
+ }
+ asyncio.run(_run_one_notifier_tick(monkeypatch, runner))
+
+ assert len(adapter.handled) == 1
+ assert _subs(tid) == [], (
+ "subscription must drop after MAX_SEND_FAILURES consecutive "
+ "wake-only delivery failures, like text sends do"
+ )
+ assert runner._kanban_sub_fail_counts == {}, (
+ "counter entry must clear when the subscription is dropped"
+ )