Skip to content

The agent that grows with you

fix(telegram): watchdog silent long-poll death via last getUpdates progress (#92991)

Finn763bf15b050b1ab
diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.py
index 9624fe5f69b..9b651284b5c 100644
--- a/plugins/platforms/telegram/adapter.py
+++ b/plugins/platforms/telegram/adapter.py
@@ -638,6 +638,15 @@ _POLLING_ERROR_TASK_STUCK_TIMEOUT = 300.0
# A generation is not healthy until the dedicated getUpdates request returns
# successfully. This exceeds a normal long-poll cycle for healthy idle bots.
_POLLING_PROGRESS_TIMEOUT = 60.0
+# Telegram holds a long-poll open for at most ~50s before answering (empty or
+# not), so a healthy idle poller completes a getUpdates round-trip well inside
+# this window. If no round-trip has completed for longer than this — while
+# get_me() on the general request path stays healthy and no updates are queued
+# server-side — the long-poll consumer is wedged on a socket that never
+# raises (CLOSE-WAIT behind a TUN/proxy route flip, #92991) and no other probe
+# can see it. ~3x the worst-case poll window leaves ample margin against false
+# positives while still recovering within a few heartbeat intervals.
+_POLLING_STALL_TIMEOUT = 150.0
# Telegram transcodes an uploaded video before it answers sendVideo, so the
# wait for the response is unrelated to how fast the bytes went out and can
# outlast the 20s read timeout the rest of the Bot API is tuned for. Only
@@ -832,6 +841,11 @@ class TelegramAdapter(BasePlatformAdapter):
self._polling_teardown_started: bool = False
self._polling_error_callback_ref = None
self._polling_heartbeat_task: Optional[asyncio.Task] = None
+ # Monotonic timestamps for the polling stall watchdog (#92991): when
+ # the current polling generation began, and when the last successful
+ # getUpdates round-trip completed. None = unknown / not yet observed.
+ self._polling_generation_started_monotonic: Optional[float] = None
+ self._polling_last_progress_monotonic: Optional[float] = None
# Live @username, refreshed whenever Telegram tells us what it is.
# PTB caches getMe() in Bot._bot_user at initialize() and only rewrites
# it inside get_me(), so a BotFather rename leaves self._bot.username
@@ -2553,6 +2567,10 @@ class TelegramAdapter(BasePlatformAdapter):
self._polling_progress_event = asyncio.Event()
self._polling_progress_accepting = True
self._send_path_degraded = True
+ # Reset the stall-watchdog timestamps (#92991): this generation has not
+ # proven getUpdates progress yet, and its age is measured from here.
+ self._polling_generation_started_monotonic = time.monotonic()
+ self._polling_last_progress_monotonic = None
return self._polling_generation, self._polling_progress_event
def _record_polling_progress(self, generation: int) -> None:
@@ -2577,6 +2595,7 @@ class TelegramAdapter(BasePlatformAdapter):
generation,
)
self._polling_progress_event.set()
+ self._polling_last_progress_monotonic = time.monotonic()
self._polling_network_error_count = 0
if generation == self._polling_conflict_recovery_generation:
self._polling_conflict_recovery_generation = None
@@ -3204,6 +3223,11 @@ class TelegramAdapter(BasePlatformAdapter):
# a single in-flight update (consumed before the next probe)
# never trips recovery.
await self._probe_pending_updates(bot, PROBE_TIMEOUT)
+ # Even an empty queue cannot hide a wedged long-poll forever:
+ # Telegram answers within ~50s, so a consumer with no
+ # successful round-trip past the stall threshold is dead
+ # (#92991). Pure local-state check — no Bot API call needed.
+ await self._check_polling_stall()
except asyncio.CancelledError:
return
except (asyncio.TimeoutError, OSError) as probe_err:
@@ -3324,6 +3348,67 @@ class TelegramAdapter(BasePlatformAdapter):
)
)
+ async def _check_polling_stall(self) -> None:
+ """Watchdog the last successful getUpdates round-trip (#92991).
+
+ PTB's long-poll can wedge without ever raising: the TCP connection
+ dies mid-read (e.g. a TUN/proxy route flip leaves the socket in
+ CLOSE-WAIT) and the pending read simply never returns and never
+ errors. In that state ``updater.running`` stays True, ``get_me()`` on
+ the general request path stays healthy, and — while no messages are
+ queued server-side — ``pending_update_count`` stays 0, so every other
+ probe is blind and the gateway goes silently, permanently deaf.
+
+ Telegram answers a long-poll within ~50s at most, so a poller that has
+ completed no getUpdates round-trip for ``_POLLING_STALL_TIMEOUT``
+ seconds is unambiguously wedged. Escalate loudly through the same
+ bounded reconnect ladder every other polling failure uses, so the
+ wedged updater is cancelled and rebuilt instead of hanging forever.
+
+ Called from ``_polling_heartbeat_loop`` and independently testable.
+ """
+ if self._webhook_mode:
+ return
+ if getattr(self, "_polling_teardown_started", False):
+ return
+ if self.has_fatal_error:
+ return
+ if self._polling_error_task and not self._polling_error_task.done():
+ return
+ now = time.monotonic()
+ last_progress = getattr(self, "_polling_last_progress_monotonic", None)
+ generation_started = getattr(
+ self, "_polling_generation_started_monotonic", None
+ )
+ if last_progress is not None:
+ stalled_for = now - last_progress
+ elif generation_started is not None:
+ # No round-trip ever completed in this generation. The one-shot
+ # progress verifier owns the immediate post-start window; this
+ # branch is the belt-and-braces fallback when it could not run.
+ stalled_for = now - generation_started
+ else:
+ return
+ if stalled_for <= _POLLING_STALL_TIMEOUT:
+ return
+ logger.error(
+ "[%s] Telegram polling stalled: no getUpdates progress for %.0fs "
+ "(generation %d). Rebuilding the long-poll consumer through the "
+ "reconnect ladder instead of staying silently deaf.",
+ self.name, stalled_for, getattr(self, "_polling_generation", 0),
+ )
+ loop = asyncio.get_running_loop()
+ self._polling_error_task = loop.create_task(
+ self._handle_polling_network_error(
+ RuntimeError(
+ "getUpdates made no progress for %.0fs (polling stall "
+ "watchdog)" % stalled_for
+ )
+ )
+ )
+ self._background_tasks.add(self._polling_error_task)
+ self._polling_error_task.add_done_callback(self._background_tasks.discard)
+
async def _verify_polling_after_reconnect(
self,
generation: Optional[int] = None,
diff --git a/tests/gateway/test_telegram_polling_stall_watchdog.py b/tests/gateway/test_telegram_polling_stall_watchdog.py
new file mode 100644
index 00000000000..8b2da920d88
--- /dev/null
+++ b/tests/gateway/test_telegram_polling_stall_watchdog.py
@@ -0,0 +1,153 @@
+"""TelegramAdapter polling-stall watchdog (#92991).
+
+A wedged getUpdates long-poll can be invisible to every other probe: the
+TCP connection dies mid-read (CLOSE-WAIT behind a TUN/proxy route flip),
+``updater.running`` stays True, ``get_me()`` on the general request path
+stays healthy, and — while no messages are queued server-side —
+``pending_update_count`` stays 0. The gateway then goes silently deaf and
+only a full restart recovers it.
+
+``_check_polling_stall`` closes that hole: Telegram answers a long-poll
+within ~50s, so a poller with no successful getUpdates round-trip for
+``_POLLING_STALL_TIMEOUT`` seconds is unambiguously wedged, and the check
+escalates loudly through the existing reconnect ladder
+(``_handle_polling_network_error``). ``_polling_heartbeat_loop`` runs the
+check every probe, so steady-state wedges are caught without any Bot API
+call.
+"""
+import asyncio
+import time as _time
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from gateway.config import PlatformConfig
+from plugins.platforms.telegram.adapter import TelegramAdapter
+
+
+def _make_adapter(*, stalled_seconds: float) -> TelegramAdapter:
+ """Build a polling-mode adapter whose long-poll last succeeded
+ ``stalled_seconds`` ago, with a healthy general request path and an
+ EMPTY server-side queue (so the pending-count probe stays blind)."""
+ adapter = TelegramAdapter(PlatformConfig(enabled=True, token="***"))
+ adapter._webhook_mode = False
+ adapter._app = MagicMock()
+ adapter._app.updater.running = True
+ bot = MagicMock()
+ bot.get_me = AsyncMock()
+ bot.get_webhook_info = AsyncMock(
+ return_value=MagicMock(pending_update_count=0)
+ )
+ adapter._app.bot = bot
+ adapter._bot = bot
+ adapter._polling_generation = 2
+ now = _time.monotonic()
+ adapter._polling_generation_started_monotonic = now - 500
+ adapter._polling_last_progress_monotonic = now - stalled_seconds
+ return adapter
+
+
+async def test_recent_progress_does_not_escalate():
+ """A healthy poller (fresh round-trip) must never trip the watchdog."""
+ adapter = _make_adapter(stalled_seconds=1)
+ with patch.object(adapter, "_handle_polling_network_error", new=AsyncMock()) as rec:
+ await adapter._check_polling_stall()
+ assert adapter._polling_error_task is None
+ rec.assert_not_called()
+
+
+async def test_stalled_long_poll_escalates_to_reconnect_ladder():
+ """#92991: with an empty queue and healthy get_me(), only the stall
+ timestamp can detect the wedged consumer — and it must."""
+ adapter = _make_adapter(stalled_seconds=400)
+ recovery = AsyncMock()
+ with patch.object(adapter, "_handle_polling_network_error", new=recovery):
+ await adapter._check_polling_stall()
+ task = adapter._polling_error_task
+ assert task is not None
+ await task
+ recovery.assert_awaited_once()
+
+
+async def test_generation_with_no_progress_ever_uses_generation_age():
+ """A generation that never completes one round-trip still trips the
+ watchdog once its age passes the stall threshold (verifier fallback)."""
+ adapter = _make_adapter(stalled_seconds=0)
+ adapter._polling_last_progress_monotonic = None
+ recovery = AsyncMock()
+ with patch.object(adapter, "_handle_polling_network_error", new=recovery):
+ await adapter._check_polling_stall()
+ task = adapter._polling_error_task
+ assert task is not None
+ await task
+ recovery.assert_awaited_once()
+
+
+async def test_stall_ignored_while_recovery_in_flight():
+ """An in-flight reconnect owns recovery; the watchdog must not pile on."""
+ adapter = _make_adapter(stalled_seconds=400)
+ inflight = MagicMock()
+ inflight.done.return_value = False
+ adapter._polling_error_task = inflight
+ with patch.object(adapter, "_handle_polling_network_error", new=AsyncMock()) as rec:
+ await adapter._check_polling_stall()
+ rec.assert_not_called()
+ assert adapter._polling_error_task is inflight
+
+
+async def test_stall_check_skipped_in_webhook_mode():
+ """Webhook mode has no long-poll socket to wedge."""
+ adapter = _make_adapter(stalled_seconds=400)
+ adapter._webhook_mode = True
+ with patch.object(adapter, "_handle_polling_network_error", new=AsyncMock()) as rec:
+ await adapter._check_polling_stall()
+ rec.assert_not_called()
+ assert adapter._polling_error_task is None
+
+
+async def test_heartbeat_detects_wedged_long_poll_with_empty_queue():
+ """End-to-end (#92991): drive the lifetime heartbeat loop against a
+ wedged poller with a healthy general path and an empty queue. Before the
+ stall watchdog, this setup produces total silence — no probe fires and
+ no recovery is ever scheduled. After it, the first stall observation
+ escalates through the reconnect ladder."""
+ adapter = _make_adapter(stalled_seconds=400)
+ real_sleep = asyncio.sleep
+
+ async def fast_sleep(delay, *args, **kwargs):
+ await real_sleep(0)
+
+ with patch("asyncio.sleep", new=fast_sleep):
+ with patch.object(adapter, "_handle_polling_network_error", new=AsyncMock()) as rec:
+ loop_task = asyncio.ensure_future(adapter._polling_heartbeat_loop())
+ try:
+ # Run probe cycles until the stall watchdog escalates (the
+ # fix) — bounded so the pre-fix state fails cleanly instead
+ # of hanging.
+ for _ in range(50):
+ await real_sleep(0)
+ if adapter._polling_error_task is not None:
+ break
+ # Let the loop observe the teardown flag and exit on its own.
+ # Never cancel(): CPython 3.11's wait_for can swallow task
+ # cancellation while its inner future is already done, which
+ # leaves the busy loop un-cancellable and the test spinning
+ # forever.
+ adapter._polling_teardown_started = True
+ await asyncio.wait_for(loop_task, 10)
+ finally:
+ if not loop_task.done():
+ loop_task.cancel()
+ task = adapter._polling_error_task
+ assert task is not None, (
+ "heartbeat probes saw a wedged long-poll (no getUpdates progress for "
+ "400s) but scheduled no recovery"
+ )
+ await task
+ rec.assert_awaited_once()