The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(telegram): escalate ingress dispatch stall to supervisor rebuild
JerryLiu3693671e521f2c0
diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.pyindex 8e726ac6828..33c5f828ea9 100644--- a/plugins/platforms/telegram/adapter.py+++ b/plugins/platforms/telegram/adapter.py@@ -470,9 +470,10 @@ _POLLING_PROGRESS_TIMEOUT = 60.0 # generation unhealthy until getUpdates return# #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-# Ingress dispatch stall (#102260): the transport probes prove getUpdates round-trips complete, not+# Ingress dispatch stall (#102260, #130407): the transport probes prove getUpdates round-trips complete, not# that PTB's dispatcher ever handed the fetched updates to a handler. Two heartbeats (180s) with a-# backlog and no dispatch progress: diagnostic only, never drives recovery (#71240 owns that).+# backlog and no dispatch progress: warn once per stall and hand the adapter to the supervisor for a+# rebuild (an in-place polling restart keeps the wedged dispatcher). Re-arms on dispatch progress._INGRESS_DISPATCH_STALL_HEARTBEATS = 2# sendVideo transcodes before answering, outlasting the 20s read timeout; also how long a user waits# to hear the attachment failed, so kept modest.@@ -507,6 +508,15 @@ class _PollingStallError(RuntimeError):"""+class _IngressDispatchStallError(_PollingStallError):+ """A confirmed PTB dispatcher stall: getUpdates fetches but no handler dispatch (#102260, #130407).++ Subclasses ``_PollingStallError`` so the recovery ladder hands the adapter to the supervisor for a+ rebuild instead of restarting the same Updater in place: an in-place polling restart keeps the same+ ``Application`` (and its wedged dispatcher task), while a rebuild constructs a fresh dispatcher.+ """++class TelegramAdapter(BasePlatformAdapter):"""Telegram bot adapter: users/groups, MarkdownV2 replies, forum topics, media."""@@ -2349,14 +2359,15 @@ class TelegramAdapter(BasePlatformAdapter):self._polling_error_task = asyncio.get_running_loop().create_task(self._handle_polling_network_error(RuntimeError(reason)))def _check_ingress_dispatch_stall(self) -> None:- """Report fetched updates PTB's dispatcher is not handing to handlers (#102260).+ """Escalate fetched updates PTB's dispatcher is not handing to handlers (#102260, #130407).``received`` and ``dispatched`` count the same population (every fetched update reaches thegroup-99 catch-all: no handler raises ApplicationHandlerStop, no error handler is registered),so a backlog with no dispatch progress across ``_INGRESS_DISPATCH_STALL_HEARTBEATS`` heartbeats- is a wedged dispatcher at any traffic rate. Reports once per stall, re-arms on progress.+ is a wedged dispatcher at any traffic rate. Warns once per stall, marks the adapter degraded,+ and hands it to the supervisor for a rebuild; re-arms on dispatch progress."""- if self._webhook_mode or self._teardown_started or self.has_fatal_error:+ if self._webhook_mode or self._teardown_started or self.has_fatal_error or self._recovery_in_flight():returnreceived = getattr(self, "_updates_received_total", 0)dispatched = getattr(self, "_updates_dispatched_total", 0)@@ -2370,12 +2381,25 @@ class TelegramAdapter(BasePlatformAdapter):self._ingress_stalled_heartbeats = stalled + 1if stalled + 1 < _INGRESS_DISPATCH_STALL_HEARTBEATS:return+ backlog = received - dispatchedlogger.warning("[%s] Telegram ingress is healthy but deaf: %d update(s) fetched by getUpdates have not been ""dispatched to any handler across %d heartbeats (%d received, %d dispatched, generation %d). ""Polling is fine; PTB's dispatcher is not draining its queue.",- self.name, received - dispatched, _INGRESS_DISPATCH_STALL_HEARTBEATS, received, dispatched,+ self.name, backlog, _INGRESS_DISPATCH_STALL_HEARTBEATS, received, dispatched,getattr(self, "_polling_generation", 0))+ try:+ self._schedule_polling_recovery(+ _IngressDispatchStallError(+ "PTB dispatcher made no progress for %d heartbeats "+ "(%d received, %d dispatched, generation %d; ingress dispatch stall watchdog)"+ % (_INGRESS_DISPATCH_STALL_HEARTBEATS, received, dispatched,+ getattr(self, "_polling_generation", 0))),+ reason="ingress dispatch stall watchdog")+ except RuntimeError:+ # No running event loop (unit-test direct call): the warning above is the+ # diagnostic; the next heartbeat with a loop drives recovery.+ logger.debug("[%s] Ingress dispatch stall recovery deferred (no running loop)", self.name)async def _check_polling_stall(self) -> None:"""Watchdog the last successful getUpdates round-trip: a long-poll can wedge without raisingdiff --git a/tests/gateway/test_telegram_ingress_delivery_gap.py b/tests/gateway/test_telegram_ingress_delivery_gap.pyindex da1411601cc..2e4372c5474 100644--- a/tests/gateway/test_telegram_ingress_delivery_gap.py+++ b/tests/gateway/test_telegram_ingress_delivery_gap.py@@ -1,11 +1,15 @@-"""Telegram ingress dispatch accounting (#102260).+"""Telegram ingress dispatch accounting (#102260, #130407).The transport probes prove getUpdates round-trips complete; these pin the one signal they cannotgive — whether PTB's dispatcher hands the fetched updates to a handler — and the once-per-adapterreport for an adapter with no gateway message handler at all.++Recovery escalation (warn + supervisor rebuild) is pinned separately in+``test_telegram_ingress_dispatch_recovery.py``; the counting tests below stub+``_schedule_polling_recovery`` so the real fatal handoff does not fire mid-test."""import logging-from unittest.mock import MagicMock+from unittest.mock import MagicMock, patchimport pytest@@ -58,9 +62,10 @@ async def test_stall_reported_once_on_backlog_regardless_of_update_age(caplog):_heartbeats(adapter, 3)assert _deaf_reports(caplog) == []- for _ in range(3): # a fresh update lands before every heartbeat, none dispatched- _receive(adapter, 1)- adapter._check_ingress_dispatch_stall()+ with patch.object(adapter, "_schedule_polling_recovery"):+ for _ in range(3): # a fresh update lands before every heartbeat, none dispatched+ _receive(adapter, 1)+ adapter._check_ingress_dispatch_stall()(report,) = _deaf_reports(caplog)assert "2 update(s) fetched" in report and "4 received, 2 dispatched" in report@@ -69,15 +74,16 @@ async def test_stall_reported_once_on_backlog_regardless_of_update_age(caplog):async def test_dispatch_progress_rearms_the_report(caplog):adapter = _polling_adapter()caplog.set_level(logging.WARNING)- _receive(adapter, 3)- _heartbeats(adapter, 3)- assert len(_deaf_reports(caplog)) == 1+ with patch.object(adapter, "_schedule_polling_recovery"):+ _receive(adapter, 3)+ _heartbeats(adapter, 3)+ assert len(_deaf_reports(caplog)) == 1- await _dispatch(adapter, 1) # partial drain: progress, backlog remains- adapter._check_ingress_dispatch_stall()- assert len(_deaf_reports(caplog)) == 1- _heartbeats(adapter, 2)- assert len(_deaf_reports(caplog)) == 2+ await _dispatch(adapter, 1) # partial drain: progress, backlog remains+ adapter._check_ingress_dispatch_stall()+ assert len(_deaf_reports(caplog)) == 1+ _heartbeats(adapter, 2)+ assert len(_deaf_reports(caplog)) == 2def test_new_generation_restarts_backlog_and_ignores_fenced_polls(caplog):diff --git a/tests/gateway/test_telegram_ingress_dispatch_recovery.py b/tests/gateway/test_telegram_ingress_dispatch_recovery.pynew file mode 100644index 00000000000..f8f2a1b1d78--- /dev/null+++ b/tests/gateway/test_telegram_ingress_dispatch_recovery.py@@ -0,0 +1,214 @@+"""Telegram ingress dispatch stall recovery (#130407).++Section 1 of #130407: getUpdates kept fetching inbound messages while the PTB+Application dispatcher stopped draining its local queue. The adapter logged+"healthy but deaf" yet kept reporting ``connected`` and never initiated+recovery — a manual restart was required.++The fix: :meth:`_check_ingress_dispatch_stall` warns once per stall AND hands+the adapter to the supervisor for a rebuild via ``_schedule_polling_recovery``+with :class:`_IngressDispatchStallError` (a ``_PollingStallError`` subclass, so+the ladder skips the in-place Updater restart — the wedged dispatcher lives on+the same ``Application`` — and goes retryable-fatal). ``_schedule`` also marks+the adapter degraded so ``gateway_state.json`` stops saying ``connected``.++These pin the recovery contract; the pure counting/reporting contract lives in+``test_telegram_ingress_delivery_gap.py`` (which stubs recovery).+"""+import asyncio+import logging+from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from gateway.config import PlatformConfig+from plugins.platforms.telegram import adapter as tg_adapter+from plugins.platforms.telegram.adapter import TelegramAdapter++_DEAF = "healthy but deaf"+++def _polling_adapter() -> TelegramAdapter:+ adapter = TelegramAdapter(PlatformConfig(enabled=True, token="test-token"))+ adapter._webhook_mode = False+ adapter._begin_polling_generation()+ return adapter+++def _receive(adapter: TelegramAdapter, n: int) -> None:+ request = MagicMock()+ request.parse_json_payload = MagicMock(+ return_value={"ok": True, "result": [{"update_id": i} for i in range(n)]}+ )+ adapter._observe_polling_request_result(+ request, adapter._polling_generation, (200, b"{}")+ )+++async def _dispatch(adapter: TelegramAdapter, n: int) -> None:+ for _ in range(n):+ await adapter._on_platform_update(MagicMock(), MagicMock())+++def _deaf_reports(caplog) -> list[str]:+ return [r.getMessage() for r in caplog.records if _DEAF in r.message]+++async def test_no_backlog_never_schedules_recovery(caplog):+ """Balanced receive/dispatch is healthy: no warning, no recovery task."""+ adapter = _polling_adapter()+ caplog.set_level(logging.WARNING)+ _receive(adapter, 2)+ await _dispatch(adapter, 2)+ with patch.object(adapter, "_schedule_polling_recovery") as sched:+ for _ in range(3):+ adapter._check_ingress_dispatch_stall()+ assert _deaf_reports(caplog) == []+ sched.assert_not_called()+ assert adapter._polling_error_task is None+++async def test_single_heartbeat_does_not_schedule_recovery(caplog):+ """Debounce: one heartbeat with a backlog only arms, never escalates."""+ adapter = _polling_adapter()+ caplog.set_level(logging.WARNING)+ _receive(adapter, 3)+ with patch.object(adapter, "_schedule_polling_recovery") as sched:+ adapter._check_ingress_dispatch_stall()+ assert _deaf_reports(caplog) == []+ sched.assert_not_called()+ assert adapter._polling_error_task is None+++async def test_two_heartbeats_schedule_dispatch_stall_rebuild(caplog):+ """#130407 §1: two heartbeats with no dispatch progress warn once AND schedule a rebuild."""+ adapter = _polling_adapter()+ caplog.set_level(logging.WARNING)+ _receive(adapter, 3)+ recovery = AsyncMock()+ with patch.object(adapter, "_handle_polling_network_error", new=recovery):+ adapter._check_ingress_dispatch_stall()+ assert adapter._polling_error_task is None+ adapter._check_ingress_dispatch_stall()+ task = adapter._polling_error_task+ assert task is not None+ await task+ (report,) = _deaf_reports(caplog)+ assert "3 update(s) fetched" in report+ recovery.assert_awaited_once()+ (err,) = recovery.await_args.args+ assert isinstance(err, tg_adapter._IngressDispatchStallError)+ assert isinstance(err, tg_adapter._PollingStallError)+++async def test_dispatch_stall_marks_degraded_and_goes_fatal():+ """A confirmed dispatch stall is a handoff, not a retry: degraded status,+ retryable fatal, no in-place updater restart, no backoff sleep."""+ adapter = _polling_adapter()+ adapter._running = True+ adapter._mark_degraded = MagicMock()+ updater = MagicMock()+ updater.stop = AsyncMock(return_value=None)+ updater.start_polling = AsyncMock()+ adapter._app = MagicMock()+ adapter._app.updater = updater+ adapter._drain_polling_connections = AsyncMock()+ adapter._notify_fatal_error = AsyncMock()+ _receive(adapter, 2)++ try:+ with patch("asyncio.sleep", new=AsyncMock()) as sleep:+ adapter._check_ingress_dispatch_stall()+ assert adapter._polling_error_task is None+ adapter._check_ingress_dispatch_stall()+ task = adapter._polling_error_task+ assert task is not None+ await task+ assert adapter.has_fatal_error+ assert adapter.fatal_error_retryable is True+ adapter._notify_fatal_error.assert_awaited_once()+ adapter._mark_degraded.assert_called_once()+ updater.start_polling.assert_not_awaited()+ updater.stop.assert_not_awaited()+ sleep.assert_not_awaited()+ adapter._drain_polling_connections.assert_not_awaited()+ finally:+ for pending in tuple(adapter._background_tasks):+ pending.cancel()+ await asyncio.gather(*tuple(adapter._background_tasks), return_exceptions=True)+++async def test_recovery_in_flight_suppresses_reschedule(caplog):+ """An in-flight reconnect owns recovery; the dispatch watchdog must not pile on."""+ adapter = _polling_adapter()+ caplog.set_level(logging.WARNING)+ _receive(adapter, 3)+ inflight = MagicMock()+ inflight.done.return_value = False+ adapter._polling_error_task = inflight+ with patch.object(adapter, "_handle_polling_network_error", new=AsyncMock()) as rec:+ adapter._check_ingress_dispatch_stall()+ adapter._check_ingress_dispatch_stall()+ rec.assert_not_called()+ assert adapter._polling_error_task is inflight+ assert _deaf_reports(caplog) == []+++async def test_webhook_teardown_and_fatal_skip_recovery():+ """Webhook mode has no PTB dispatcher queue to wedge; teardown/fatal never re-escalate."""+ for mutate in (+ lambda a: setattr(a, "_webhook_mode", True),+ lambda a: setattr(a, "_polling_teardown_started", True),+ lambda a: a._set_fatal_error("telegram_network_error", "boom", retryable=True),+ ):+ adapter = _polling_adapter()+ mutate(adapter)+ _receive(adapter, 2)+ with patch.object(adapter, "_schedule_polling_recovery") as sched:+ adapter._check_ingress_dispatch_stall()+ adapter._check_ingress_dispatch_stall()+ sched.assert_not_called()+ assert adapter._polling_error_task is None or adapter._polling_error_task.done() is False+++async def test_dispatch_progress_rearms_recovery_scheduling(caplog):+ """With the handoff stubbed (no fatal), partial dispatch progress re-arms the next escalation."""+ adapter = _polling_adapter()+ caplog.set_level(logging.WARNING)+ _receive(adapter, 3)+ with patch.object(adapter, "_schedule_polling_recovery") as sched:+ adapter._check_ingress_dispatch_stall()+ adapter._check_ingress_dispatch_stall()+ assert sched.call_count == 1+ assert len(_deaf_reports(caplog)) == 1+ await _dispatch(adapter, 1)+ adapter._check_ingress_dispatch_stall()+ assert sched.call_count == 1+ adapter._check_ingress_dispatch_stall()+ adapter._check_ingress_dispatch_stall()+ assert sched.call_count == 2+ assert len(_deaf_reports(caplog)) == 2+ for call in sched.call_args_list:+ (err,) = call.args+ assert isinstance(err, tg_adapter._IngressDispatchStallError)+++def test_without_running_loop_falls_back_to_diagnostic(caplog):+ """A direct sync call with no event loop must not raise: the warning is the+ diagnostic and the next heartbeat with a loop drives recovery."""+ adapter = _polling_adapter()+ caplog.set_level(logging.WARNING)+ _receive(adapter, 2)+ adapter._check_ingress_dispatch_stall()+ assert _deaf_reports(caplog) == []+ # Second heartbeat crosses the threshold with no running loop in this sync test.+ adapter._check_ingress_dispatch_stall()+ (report,) = _deaf_reports(caplog)+ assert "2 update(s) fetched" in report