Skip to content

The agent that grows with you

fix(telegram+sqlite): resolve polling conflict loop + misleading WAL warning

kshitije05eba26a3af
diff --git a/hermes_state.py b/hermes_state.py
index 3810dbcbd7b..9b8215390d1 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -848,6 +848,34 @@ def _apply_delete_for_wal_reset_bug(
return "delete"
+def _wal_reset_repair_hint() -> str:
+ """Return a context-appropriate hint for repairing the SQLite runtime.
+
+ Uses the codebase's install-type detection so the hint matches what
+ ``hermes update`` can actually do for this install (#75153).
+ """
+ try:
+ from hermes_cli.config import (
+ detect_install_method,
+ recommended_update_command_for_method,
+ get_project_root,
+ )
+ method = detect_install_method(get_project_root())
+ cmd = recommended_update_command_for_method(method)
+ if method in {"git", "unknown"}:
+ return f"Hermes-managed installs can repair the embedded runtime with `{cmd}`"
+ if method == "docker":
+ return f"update the container image with `{cmd}`"
+ # nix/nixos
+ return cmd
+ except Exception:
+ pass
+ return (
+ "install a Python build bundled with SQLite 3.51.3+ "
+ "(or backports 3.50.7 / 3.44.6) and restart Hermes"
+ )
+
+
def _log_wal_reset_bug_once(
db_label: str,
*,
@@ -864,16 +892,20 @@ def _log_wal_reset_bug_once(
if kept_wal
else "using journal_mode=DELETE instead of enabling WAL"
)
+ # Check whether this is a Hermes-managed install (uv-managed venv)
+ # so the warning doesn't promise a repair path that doesn't exist
+ # for git/pip/system Python installs (#75153).
+ repair_hint = _wal_reset_repair_hint()
logger.warning(
"%s: linked SQLite %s is vulnerable to the WAL-reset corruption "
"bug (https://sqlite.org/wal.html#walresetbug) — %s. "
"Upgrade to SQLite 3.51.3+ (or backports 3.50.7 / 3.44.6); "
- "Hermes-managed installs can repair the embedded runtime with "
- "`hermes update`. See `hermes doctor`. This warning fires once per "
+ "%s. See `hermes doctor`. This warning fires once per "
"process per database.",
db_label,
sqlite3.sqlite_version,
action,
+ repair_hint,
)
diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.py
index 674a49d2be9..ea6258b9f2d 100644
--- a/plugins/platforms/telegram/adapter.py
+++ b/plugins/platforms/telegram/adapter.py
@@ -770,6 +770,7 @@ class TelegramAdapter(BasePlatformAdapter):
self._drop_delayed_deliveries = False
self._polling_error_task: Optional[asyncio.Task] = None
self._polling_conflict_count: int = 0
+ self._polling_conflict_recovery_generation: Optional[int] = None
self._polling_network_error_count: int = 0
self._polling_generation: int = 0
self._polling_progress_event = asyncio.Event()
@@ -2160,7 +2161,10 @@ class TelegramAdapter(BasePlatformAdapter):
return
self._polling_progress_event.set()
self._polling_network_error_count = 0
- self._polling_conflict_count = 0
+ if generation == self._polling_conflict_recovery_generation:
+ self._polling_conflict_recovery_generation = None
+ else:
+ self._polling_conflict_count = 0
self._send_path_degraded = False
def _observe_polling_request_result(self, request, generation, result):
@@ -3118,12 +3122,22 @@ class TelegramAdapter(BasePlatformAdapter):
# AttributeError deep inside start_polling instead of failing fast
# here, where the except below reschedules or escalates to fatal.
app = self._app
+ expected_generation = self._polling_generation + 1
+ if not app:
+ raise RuntimeError("Telegram application was torn down during conflict reconnect")
+ # drop_pending_updates=True tells Telegram to terminate any
+ # other active getUpdates sessions for this bot token. The
+ # competing session is either a zombie from the previous
+ # gateway process (whose long-poll hasn't expired server-side
+ # yet) or our own previous retry's still-expiring session.
+ # Without this, each retry starts a new getUpdates session
+ # that immediately gets 409'd by the previous one, creating
+ # the very conflict we are trying to recover from (#75017).
+ self._polling_conflict_recovery_generation = expected_generation
try:
- if not app:
- raise RuntimeError("Telegram application was torn down during conflict reconnect")
await self._start_polling_once(
app,
- drop_pending_updates=False,
+ drop_pending_updates=True,
error_callback=self._polling_error_callback_ref,
)
logger.info(
@@ -3164,6 +3178,9 @@ class TelegramAdapter(BasePlatformAdapter):
)
return
# Fall through to fatal on the last retry.
+ finally:
+ if self._polling_conflict_recovery_generation == expected_generation:
+ self._polling_conflict_recovery_generation = None
if getattr(self, "_polling_teardown_started", False):
return
diff --git a/tests/gateway/test_telegram_conflict.py b/tests/gateway/test_telegram_conflict.py
index 46ab719521a..711f8748541 100644
--- a/tests/gateway/test_telegram_conflict.py
+++ b/tests/gateway/test_telegram_conflict.py
@@ -142,6 +142,80 @@ async def test_polling_conflict_retries_before_fatal(monkeypatch):
await _cancel_heartbeat(adapter)
+async def test_conflict_retry_drops_pending_updates(monkeypatch):
+ """Conflict recovery must use drop_pending_updates=True (#75017).
+
+ Without this, each retry starts a new getUpdates session that
+ immediately gets 409'd by the previous still-expiring session,
+ creating the very conflict we are trying to recover from.
+ """
+ adapter = TelegramAdapter(PlatformConfig(enabled=True, token="***"))
+ adapter.set_fatal_error_handler(AsyncMock())
+ adapter._drain_polling_connections = AsyncMock()
+ monkeypatch.setattr("asyncio.sleep", AsyncMock())
+
+ captured = {}
+
+ async def fake_start_polling(**kwargs):
+ captured["drop_pending_updates"] = kwargs.get("drop_pending_updates")
+
+ updater = SimpleNamespace(
+ start_polling=AsyncMock(side_effect=fake_start_polling),
+ stop=AsyncMock(),
+ running=True,
+ )
+ adapter._app = SimpleNamespace(updater=updater)
+
+ conflict = type("Conflict", (Exception,), {})
+ await adapter._handle_polling_conflict(
+ conflict("Conflict: terminated by other getUpdates request")
+ )
+
+ assert captured.get("drop_pending_updates") is True, (
+ "Conflict retry must use drop_pending_updates=True to terminate "
+ "stale getUpdates sessions on Telegram's servers (#75017)"
+ )
+
+
+async def test_conflict_retry_progress_does_not_reset_retry_ladder(monkeypatch):
+ """First getUpdates progress after a conflict retry is not durable recovery.
+
+ Telegram can accept the first long-poll after a retry and then return a 409
+ from the still-expiring previous session. That transient success must not
+ reset the retry counter back to 0, or every new 409 looks like attempt 1/5
+ and the backoff never reaches the server-side expiry window.
+ """
+ adapter = TelegramAdapter(PlatformConfig(enabled=True, token="***"))
+ adapter.set_fatal_error_handler(AsyncMock())
+ adapter._drain_polling_connections = AsyncMock()
+ monkeypatch.setattr("asyncio.sleep", AsyncMock())
+
+ calls = {"n": 0}
+
+ async def fake_start_polling(**_kwargs):
+ calls["n"] += 1
+ adapter._record_polling_progress(adapter._polling_generation)
+
+ updater = SimpleNamespace(
+ start_polling=AsyncMock(side_effect=fake_start_polling),
+ stop=AsyncMock(),
+ running=True,
+ )
+ adapter._app = SimpleNamespace(updater=updater)
+
+ conflict = type("Conflict", (Exception,), {})
+ await adapter._handle_polling_conflict(
+ conflict("Conflict: terminated by other getUpdates request")
+ )
+
+ assert calls["n"] == 1
+ assert adapter._polling_conflict_count == 1
+ assert adapter._polling_conflict_recovery_generation is None
+ assert adapter._send_path_degraded is False
+
+
@pytest.mark.asyncio
async def test_polling_conflict_becomes_fatal_after_retries(monkeypatch):
"""After exhausting retries, the conflict should become fatal."""