Skip to content

The agent that grows with you

fix(gateway): give up on an update notice whose platform never connects

gkd2323c601a8a17c222
diff --git a/gateway/run_notifications.py b/gateway/run_notifications.py
index f37178078f2..e2b6071dd6d 100644
--- a/gateway/run_notifications.py
+++ b/gateway/run_notifications.py
@@ -14,6 +14,7 @@ import json
import logging
import time
from contextlib import suppress
+from datetime import datetime
from pathlib import Path
from typing import Any, Dict, Optional, cast
@@ -32,6 +33,12 @@ _UPDATE_FAILED_NOTICE = (
"❌ Hermes update failed; the previous version is still running. Run `hermes update` on the "
"host to see the full error, or try /update again later.")
+# An update's completion notice waits for its target platform adapter to (re)connect before it
+# can be delivered. Nothing bounds that wait, so a marker naming a platform that is not
+# configured at all — no adapter will ever appear — would keep itself on disk and re-log a
+# deferred line on every poll, in every process, forever. Stop waiting past this age.
+_UPDATE_NOTIFY_MAX_ADAPTER_WAIT_SECONDS = 3600.0
+
def _served_notice_target_key(profile: Optional[str], platform_value: str, chat_id, thread_id) -> tuple:
"""Notice-dedupe key for one SERVED profile's home channel.
@@ -522,6 +529,24 @@ class GatewayNotificationsMixin:
return profile_from_session_key_namespace(parts[1])
return None
+ @staticmethod
+ def _marker_age_seconds(data: dict) -> Optional[float]:
+ """Age of a persisted update marker, from the ``timestamp`` stamped by its writer.
+
+ ``None`` when the marker carries no parseable stamp — the field is absent on markers
+ written before it existed, and callers keep the old retry behavior rather than guess.
+ """
+ raw = str(data.get("timestamp") or "").strip()
+ if not raw:
+ return None
+ try:
+ stamped = datetime.fromisoformat(raw)
+ except ValueError:
+ return None
+ # The writer stamps a naive local ``datetime.now()``; tolerate a tz-aware one too.
+ now = datetime.now(stamped.tzinfo) if stamped.tzinfo else datetime.now()
+ return (now - stamped).total_seconds()
+
def _resolve_update_target(self, paths: "_UpdatePaths") -> Optional["_UpdateTarget"]:
"""Resolve adapter/chat/session for update watcher messages from the pending marker."""
for path in (paths.claimed, paths.pending):
@@ -731,6 +756,18 @@ class GatewayNotificationsMixin:
platform = Platform(platform_str)
adapter = self._authorization_adapter(platform, self._marker_profile(pending))
if chat_id and not adapter:
+ age = self._marker_age_seconds(pending)
+ if age is not None and age > _UPDATE_NOTIFY_MAX_ADAPTER_WAIT_SECONDS:
+ # The platform never came back. Deferring forever leaks the markers and re-logs
+ # on every poll for the life of the install: the startup path reschedules this
+ # watcher whenever the markers are still on disk, so an undeliverable marker
+ # outlives every restart. Give up loudly, clear the markers, and report a
+ # definitive decision (True) so the caller stops rescheduling.
+ logger.warning(
+ "Post-update notification for %s:%s dropped after %.1fh: %s adapter never "
+ "connected", platform_str, chat_id, age / 3600.0, platform_str)
+ self._clear_update_markers(paths, pending.get("session_key"))
+ return True
# Target platform not reconnected yet (common right after the update's restart): keep the
# markers for a later retry instead of silently losing the notification.
return _defer("Update notification deferred: %s adapter not connected yet", platform_str)
diff --git a/tests/gateway/test_update_command.py b/tests/gateway/test_update_command.py
index 4d1faa57eb3..951778e2271 100644
--- a/tests/gateway/test_update_command.py
+++ b/tests/gateway/test_update_command.py
@@ -5,6 +5,7 @@ the _send_update_notification startup hook (sends results after restart).
"""
import json
+from datetime import datetime, timedelta
from pathlib import Path
from unittest.mock import patch, MagicMock, AsyncMock
@@ -363,6 +364,87 @@ class TestSendUpdateNotification:
assert "Update complete" in call_args[0][1] or "update finished" in call_args[0][1].lower()
+ @pytest.mark.asyncio
+ async def test_drops_stale_marker_when_the_platform_never_connects(self, tmp_path, caplog):
+ """A marker past the wait cap is abandoned instead of deferred forever.
+
+ Regression: an update notice addressed to a platform that has no adapter —
+ and never will, because the platform is not configured at all — kept its
+ markers on disk and re-logged a deferred line on every poll. The startup
+ path reschedules the watcher for as long as the markers exist, so the
+ notice outlived every restart, in every process.
+ """
+ runner = _make_runner()
+ hermes_home = tmp_path / "hermes"
+ hermes_home.mkdir()
+
+ pending_path = hermes_home / ".update_pending.json"
+ pending_path.write_text(json.dumps({
+ "platform": "telegram",
+ "chat_id": "67890",
+ "user_id": "12345",
+ "timestamp": (datetime.now() - timedelta(hours=2)).isoformat(),
+ }))
+ (hermes_home / ".update_exit_code").write_text("0")
+ # runner.adapters stays empty: no adapter for the target platform, ever.
+
+ with patch("gateway.run._hermes_home", hermes_home):
+ result = await runner._send_update_notification()
+
+ # True is the definitive answer the startup caller keys off to stop rescheduling.
+ assert result is True
+ assert not pending_path.exists()
+ assert not (hermes_home / ".update_pending.claimed.json").exists()
+ assert not (hermes_home / ".update_output.txt").exists()
+ assert not (hermes_home / ".update_exit_code").exists()
+ assert any("adapter never connected" in r.getMessage() for r in caplog.records)
+
+ @pytest.mark.asyncio
+ async def test_keeps_waiting_for_a_recent_marker(self, tmp_path):
+ """A recent marker is still held: the cap must not swallow its own notice.
+
+ Right after the update's restart the adapter is legitimately absent for a
+ while, which is the case the defer path exists to cover.
+ """
+ runner = _make_runner()
+ hermes_home = tmp_path / "hermes"
+ hermes_home.mkdir()
+
+ pending_path = hermes_home / ".update_pending.json"
+ pending_path.write_text(json.dumps({
+ "platform": "telegram",
+ "chat_id": "67890",
+ "user_id": "12345",
+ "timestamp": (datetime.now() - timedelta(minutes=5)).isoformat(),
+ }))
+ (hermes_home / ".update_exit_code").write_text("0")
+
+ with patch("gateway.run._hermes_home", hermes_home):
+ result = await runner._send_update_notification()
+
+ assert result is False
+ assert pending_path.exists(), "marker kept so a later poll can still deliver it"
+
+ @pytest.mark.asyncio
+ async def test_marker_without_a_timestamp_keeps_retrying(self, tmp_path):
+ """Markers written before the timestamp field existed keep previous behavior."""
+ runner = _make_runner()
+ hermes_home = tmp_path / "hermes"
+ hermes_home.mkdir()
+
+ pending_path = hermes_home / ".update_pending.json"
+ pending_path.write_text(json.dumps({
+ "platform": "telegram", "chat_id": "67890", "user_id": "12345",
+ }))
+ (hermes_home / ".update_exit_code").write_text("0")
+
+ with patch("gateway.run._hermes_home", hermes_home):
+ result = await runner._send_update_notification()
+
+ assert result is False
+ assert pending_path.exists()
+
+
@pytest.mark.asyncio
async def test_cleans_up_on_error(self, tmp_path):
"""Files are cleaned up even if notification fails."""