Skip to content

The agent that grows with you

fix(telegram): key the deaf-ingress report on dispatcher progress, not update age

kshitijk4poor78b98032c5a0
diff --git a/gateway/platforms/base.py b/gateway/platforms/base.py
index d712304a700..a37240b4cc7 100644
--- a/gateway/platforms/base.py
+++ b/gateway/platforms/base.py
@@ -1809,10 +1809,6 @@ class BasePlatformAdapter(ABC):
self.config = config
self.platform = platform
self._message_handler: Optional[MessageHandler] = None
- # Ingress delivery counter (#102260): a healthy transport can still discard 100% of
- # inbound; without a delivered-side counter a deaf gateway looks idle.
- self._inbound_delivered_total: int = 0
- self._last_inbound_delivered_monotonic: Optional[float] = None
self._no_message_handler_logged: bool = False
self._reaction_handler: Optional[Callable[[Dict[str, Any]], Awaitable[None]]] = None
# Runner-owned boundary for normalized events: auth/profile state never lives in an adapter.
@@ -2166,21 +2162,6 @@ class BasePlatformAdapter(ABC):
"""Check if adapter is currently connected."""
return self._running
- def note_inbound_delivered(self) -> None:
- """Record that one inbound event reached the gateway message handler.
-
- The delivered side of the ingress accounting introduced for #102260.
- Adapters that observe their own wire traffic (Telegram's getUpdates
- instrumentation) compare their received counter against this one to
- tell "nothing is arriving" apart from "everything arriving is being
- dropped downstream" — two failures that look identical from every
- transport-level health probe.
- """
- self._inbound_delivered_total = (
- getattr(self, "_inbound_delivered_total", 0) + 1
- )
- self._last_inbound_delivered_monotonic = time.monotonic()
-
def set_message_handler(self, handler: MessageHandler) -> None:
"""Set the incoming-message handler (MessageEvent -> optional response str)."""
self._message_handler = handler
@@ -3637,10 +3618,8 @@ class BasePlatformAdapter(ABC):
task so new messages (and interrupts) can arrive while an agent runs."""
event._gateway_accepted = False
if not self._message_handler:
- # A connected adapter with no message handler is silently deaf: it
- # polls, publishes "connected", and can still send — while every
- # inbound message is discarded here with no log at all. Say so once
- # per adapter so the failure is diagnosable (#102260).
+ # No handler = every inbound silently discarded on an adapter that still polls and sends;
+ # say so once per adapter (#102260).
if not getattr(self, "_no_message_handler_logged", False):
self._no_message_handler_logged = True
logger.error(
@@ -3651,8 +3630,6 @@ class BasePlatformAdapter(ABC):
)
return
- self.note_inbound_delivered()
-
if event.allow_gateway_control:
coerce_plaintext_gateway_command(event)
expected_session_key = str((event.metadata or {}).get("gateway_session_key") or "").strip()
diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.py
index 3710357aad0..4b1fda3ca33 100644
--- a/plugins/platforms/telegram/adapter.py
+++ b/plugins/platforms/telegram/adapter.py
@@ -344,10 +344,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 delivery gap (#102260): transport probes prove bytes move, not that any update reached a
-# handler. Generous because updates legitimately reach no gateway turn (own messages, reactions,
-# unmentioned group chatter); diagnostic only, never drives recovery.
-_INGRESS_DELIVERY_GAP_TIMEOUT = 300.0
+# Ingress dispatch stall (#102260): 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).
+_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.
_MEDIA_SEND_READ_TIMEOUT = 60.0
@@ -467,12 +467,11 @@ class TelegramAdapter(BasePlatformAdapter):
# began, and when the last successful getUpdates round-trip completed.
self._polling_generation_started_monotonic: Optional[float] = None
self._polling_last_progress_monotonic: Optional[float] = None
- # Ingress accounting (#102260): received (getUpdates wire) vs dispatched (PTB handler chain)
- # vs the base adapter's delivered counter.
+ # Ingress accounting (#102260): received (getUpdates wire) vs dispatched (PTB group-99 catch-all).
self._updates_received_total: int = 0
self._updates_dispatched_total: int = 0
- self._last_update_received_monotonic: Optional[float] = None
- self._ingress_gap_reported_at_received: Optional[int] = None
+ self._ingress_dispatched_seen: int = 0
+ self._ingress_stalled_heartbeats: int = 0
# Live @username: PTB caches getMe() at initialize() and only rewrites it inside get_me(), so a
# BotFather rename leaves self._bot.username stale; routing reads _current_bot_username().
self._bot_username_observed: Optional[str] = None
@@ -1591,12 +1590,15 @@ class TelegramAdapter(BasePlatformAdapter):
# See #92991.
self._polling_generation_started_monotonic = time.monotonic()
self._polling_last_progress_monotonic = None
+ # A rebuilt consumer drops whatever the old update_queue held; start the backlog from zero.
+ self._updates_received_total = self._updates_dispatched_total = 0
+ self._ingress_dispatched_seen = self._ingress_stalled_heartbeats = 0
return self._polling_generation, self._polling_progress_event
- def _record_polling_progress(self, generation: int) -> None:
- """Record successful getUpdates I/O for the current generation only."""
+ def _record_polling_progress(self, generation: int) -> bool:
+ """Record successful getUpdates I/O for the current generation only; True when accepted."""
if self._teardown_started or not self._polling_progress_accepting or generation != self._polling_generation:
- return
+ return False
if not self._polling_progress_event.is_set():
# First confirmed round-trip resolves the "health pending" line both reconnect paths end on.
logger.info("[%s] Telegram polling confirmed healthy: getUpdates progressing (generation %d)", self.name, generation)
@@ -1615,6 +1617,7 @@ class TelegramAdapter(BasePlatformAdapter):
"connected", platform_state="connected", error_code=None, error_message=None,
)
self._send_path_degraded = False
+ return True
def _observe_polling_request_result(self, request, generation, result):
"""Record getUpdates progress from an observed do_request result (purely observational: PTB still
@@ -1628,23 +1631,14 @@ class TelegramAdapter(BasePlatformAdapter):
except Exception:
return
if isinstance(envelope, dict) and envelope.get("ok") is True and "result" in envelope:
- self._record_polling_progress(generation)
- self._record_updates_received(envelope.get("result"))
+ if self._record_polling_progress(generation):
+ self._record_updates_received(envelope.get("result"))
def _record_updates_received(self, result) -> None:
- """Count updates Telegram handed us on the getUpdates wire (#102260).
-
- ``_record_polling_progress`` above proves the transport works; it says
- nothing about whether anything arrived. Only a non-empty ``result``
- means real updates entered this process, and that is the number the
- delivered counter has to be compared against.
- """
- if not isinstance(result, list) or not result:
- return
- self._updates_received_total = (
- getattr(self, "_updates_received_total", 0) + len(result)
- )
- self._last_update_received_monotonic = time.monotonic()
+ """Count updates Telegram handed us on the getUpdates wire (#102260). Only reached for the
+ accepted generation, so a late response from a fenced poll cannot inflate the backlog."""
+ if isinstance(result, list) and result:
+ self._updates_received_total = getattr(self, "_updates_received_total", 0) + len(result)
def _instrument_polling_request(self, request):
"""Instrument one dedicated PTB getUpdates request with progress tracking.
@@ -2058,10 +2052,8 @@ class TelegramAdapter(BasePlatformAdapter):
# 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()
- # Transport health is not delivery health: updates can arrive
- # and then die downstream with every probe above still green
- # (#102260). Pure local-state check — no Bot API call.
- self._check_ingress_delivery_gap()
+ # Transport health is not dispatch health (#102260). Pure local-state check.
+ self._check_ingress_dispatch_stall()
except asyncio.CancelledError:
return
except (asyncio.TimeoutError, OSError) as probe_err:
@@ -2144,73 +2136,33 @@ class TelegramAdapter(BasePlatformAdapter):
logger.warning(log_message, self.name)
self._polling_error_task = asyncio.get_running_loop().create_task(self._handle_polling_network_error(RuntimeError(reason)))
- def _check_ingress_delivery_gap(self) -> None:
- """Report updates that arrived on the wire but reached no gateway turn.
-
- Every other probe in this adapter measures the transport. When the
- transport is healthy and updates are still not being acted on, the
- gateway publishes ``connected``, logs nothing, and looks exactly like
- an idle bot — the failure mode of #102260, which stayed undiagnosed for
- three weeks because no counter existed on the delivered side.
-
- Three counters split the failure into its distinguishable causes:
-
- * ``received`` — updates Telegram handed this process (getUpdates).
- * ``dispatched`` — updates PTB's dispatcher carried through the whole
- handler chain. ``received > dispatched`` means the dispatcher is not
- draining; the transport is innocent.
- * ``delivered`` — inbound events that reached the gateway's message
- handler. ``dispatched > delivered`` means Hermes itself is dropping
- what arrives (authorization, mention/topic gating, a missing handler).
-
- Deliberately diagnostic only. A received update legitimately reaches no
- gateway turn (the bot's own messages, reactions, unmentioned group
- chatter), so this must never drive recovery on its own — reconnecting a
- healthy transport would not fix a dropped update anyway. It reports
- once per received-count so a persistent gap does not spam the log.
+ def _check_ingress_dispatch_stall(self) -> None:
+ """Report fetched updates PTB's dispatcher is not handing to handlers (#102260).
+
+ ``received`` and ``dispatched`` count the same population — every update in a getUpdates
+ result reaches the group-99 catch-all (no handler raises ApplicationHandlerStop and no error
+ handler is registered) — so a backlog that does not shrink across
+ ``_INGRESS_DISPATCH_STALL_HEARTBEATS`` heartbeats is a wedged dispatcher, whatever the traffic
+ rate. Keyed on dispatcher progress rather than update age: a steady trickle of new updates must
+ not keep resetting the clock. Reports once per stall and re-arms when dispatch resumes.
"""
- if self._webhook_mode:
- return
- if getattr(self, "_polling_teardown_started", False):
- return
- if self.has_fatal_error:
+ if self._webhook_mode or self._teardown_started or self.has_fatal_error:
return
received = getattr(self, "_updates_received_total", 0)
- if not received:
- return
- last_received = getattr(self, "_last_update_received_monotonic", None)
- if last_received is None:
- return
- delivered = getattr(self, "_inbound_delivered_total", 0)
- last_delivered = getattr(self, "_last_inbound_delivered_monotonic", None)
- # Something was delivered after the last update arrived: the chain is
- # working end to end. Re-arm so a later gap is reported again.
- if last_delivered is not None and last_delivered >= last_received:
- self._ingress_gap_reported_at_received = None
- return
- if time.monotonic() - last_received <= _INGRESS_DELIVERY_GAP_TIMEOUT:
+ dispatched = getattr(self, "_updates_dispatched_total", 0)
+ if received <= dispatched or dispatched != getattr(self, "_ingress_dispatched_seen", 0):
+ self._ingress_dispatched_seen = dispatched
+ self._ingress_stalled_heartbeats = 0
return
- if self._ingress_gap_reported_at_received == received:
+ self._ingress_stalled_heartbeats = getattr(self, "_ingress_stalled_heartbeats", 0) + 1
+ if self._ingress_stalled_heartbeats != _INGRESS_DISPATCH_STALL_HEARTBEATS:
return
- self._ingress_gap_reported_at_received = received
- dispatched = getattr(self, "_updates_dispatched_total", 0)
- if dispatched < received:
- where = (
- "PTB's dispatcher is not draining them (received > dispatched)"
- )
- else:
- where = (
- "they are being dropped inside Hermes before the gateway "
- "handler (dispatched > delivered) — check authorization, "
- "mention/topic gating, and the held-inbound queue"
- )
- logger.error(
- "[%s] Telegram ingress is healthy but deaf: %d update(s) received "
- "on the getUpdates wire, %d dispatched, %d delivered to the "
- "gateway, none delivered in the last %.0fs. Polling is fine — %s.",
- self.name, received, dispatched, delivered,
- time.monotonic() - last_received, where,
- )
+ logger.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,
+ getattr(self, "_polling_generation", 0))
async def _check_polling_stall(self) -> None:
"""Watchdog the last successful getUpdates round-trip: a long-poll can wedge without raising
@@ -2651,8 +2603,8 @@ class TelegramAdapter(BasePlatformAdapter):
async def _on_platform_update(self, update, context) -> None:
"""Catch-all PTB handler (group 99) firing ``gateway_platform_event`` per inbound update with a
stable envelope (no raw SDK objects) and an internal auth source. Never raises into PTB."""
- # Last handler group PTB runs: proves the dispatcher carried the update through the chain,
- # so stamp before any early return (#102260).
+ # Last handler group PTB runs: stamp before any early return so the dispatch counter covers
+ # gateways without the plugin hook (#102260).
self._updates_dispatched_total = getattr(self, "_updates_dispatched_total", 0) + 1
handler: Optional[Callable[[Dict[str, Any], Any], Awaitable[None]]] = getattr(self, "_platform_event_handler", None)
if handler is None:
diff --git a/tests/gateway/test_telegram_ingress_delivery_gap.py b/tests/gateway/test_telegram_ingress_delivery_gap.py
index f47c1a0e6fe..7ec4d8b5295 100644
--- a/tests/gateway/test_telegram_ingress_delivery_gap.py
+++ b/tests/gateway/test_telegram_ingress_delivery_gap.py
@@ -1,24 +1,11 @@
-"""Telegram ingress delivery accounting (#102260).
+"""Telegram ingress dispatch accounting (#102260).
-Every existing Telegram health probe measures the *transport*: a getUpdates
-round-trip that returns 200 proves bytes are moving and nothing else. When
-updates arrive and then die downstream — a dispatcher that never drains, a
-filter that never matches, an adapter with no gateway handler installed — the
-gateway publishes ``connected``, logs nothing at all, and is indistinguishable
-from an idle bot. That is #102260: three weeks of a bot reporting
-``telegram.state: "connected"`` and ``polling confirmed healthy`` while not one
-inbound message reached a handler.
-
-These tests pin the three counters that split the failure into causes:
-
-* ``_updates_received_total`` — updates Telegram handed the process.
-* ``_updates_dispatched_total`` — updates PTB carried through the handler chain.
-* ``_inbound_delivered_total`` — inbound events that reached the gateway.
+The transport probes prove getUpdates round-trips complete; these pin the one signal they cannot
+give — whether PTB's dispatcher hands the fetched updates to a handler — and the once-per-adapter
+report for an adapter with no gateway message handler at all.
"""
-import asyncio
import logging
-import time as _time
-from unittest.mock import AsyncMock, MagicMock
+from unittest.mock import MagicMock
import pytest
@@ -26,263 +13,89 @@ from gateway.config import PlatformConfig
from gateway.platforms.base import MessageEvent, MessageType, Platform, SessionSource
from plugins.platforms.telegram.adapter import TelegramAdapter
+_DEAF = "healthy but deaf"
+
-def _make_adapter() -> TelegramAdapter:
- adapter = TelegramAdapter(PlatformConfig(enabled=True, token="***"))
+def _polling_adapter() -> TelegramAdapter:
+ adapter = TelegramAdapter(PlatformConfig(enabled=True, token="test-token"))
adapter._webhook_mode = False
adapter._app = MagicMock()
- adapter._app.updater.running = True
+ adapter._begin_polling_generation()
return adapter
-def _envelope_request(result):
- """A PTB request double whose parser returns a getUpdates envelope."""
+def _receive(adapter: TelegramAdapter, n: int, generation: int | None = None) -> None:
request = MagicMock()
request.parse_json_payload = MagicMock(
- return_value={"ok": True, "result": result}
+ return_value={"ok": True, "result": [{"update_id": i} for i in range(n)]}
)
- return request
-
-
-# ---------------------------------------------------------------------------
-# received counter
-# ---------------------------------------------------------------------------
-
-
-def test_empty_getupdates_result_counts_no_updates():
- """An idle long-poll proves the transport, not that anything arrived."""
- adapter = _make_adapter()
- adapter._polling_generation = 1
- adapter._polling_progress_accepting = True
- adapter._polling_progress_event = asyncio.Event()
-
- adapter._observe_polling_request_result(_envelope_request([]), 1, (200, b"{}"))
-
- assert adapter._updates_received_total == 0
- assert adapter._last_update_received_monotonic is None
- # ...while transport progress is still recorded.
- assert adapter._polling_last_progress_monotonic is not None
-
-
-def test_non_empty_getupdates_result_counts_every_update():
- adapter = _make_adapter()
- adapter._polling_generation = 1
- adapter._polling_progress_accepting = True
- adapter._polling_progress_event = asyncio.Event()
-
adapter._observe_polling_request_result(
- _envelope_request([{"update_id": 1}, {"update_id": 2}]), 1, (200, b"{}")
+ request, adapter._polling_generation if generation is None else generation, (200, b"{}")
)
- assert adapter._updates_received_total == 2
- assert adapter._last_update_received_monotonic is not None
+def _deaf_reports(caplog) -> list[str]:
+ return [r.getMessage() for r in caplog.records if _DEAF in r.message]
-# ---------------------------------------------------------------------------
-# delivered counter
-# ---------------------------------------------------------------------------
-
-def _text_event() -> MessageEvent:
- return MessageEvent(
- text="hi",
- message_type=MessageType.TEXT,
- source=SessionSource(
- platform=Platform.TELEGRAM,
- chat_id="6053106869",
- user_id="6053106869",
- chat_type="dm",
- ),
- )
+async def test_dispatch_stall_is_reported_on_backlog_not_update_age(caplog):
+ """A wedged dispatcher is reported after two heartbeats even while new updates keep arriving;
+ dispatch progress re-arms it; a stale generation cannot inflate the backlog."""
+ adapter = _polling_adapter()
+ caplog.set_level(logging.WARNING)
+
+ # Healthy: every fetched update reaches the group-99 catch-all.
+ _receive(adapter, 2)
+ for _ in range(2):
+ await adapter._on_platform_update(MagicMock(), MagicMock())
+ for _ in range(3):
+ adapter._check_ingress_dispatch_stall()
+ assert _deaf_reports(caplog) == []
+
+ # Dispatcher wedged: a fresh update lands before every heartbeat, none dispatched.
+ _receive(adapter, 1)
+ adapter._check_ingress_dispatch_stall()
+ assert _deaf_reports(caplog) == [], "one heartbeat is not a stall"
+ _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
+ _receive(adapter, 1)
+ adapter._check_ingress_dispatch_stall()
+ assert len(_deaf_reports(caplog)) == 1, "a persistent stall is reported once"
+
+ # Dispatch resumes but only partially drains the backlog: progress re-arms the check, and the
+ # next two heartbeats without progress are a new stall.
+ await adapter._on_platform_update(MagicMock(), MagicMock())
+ adapter._check_ingress_dispatch_stall()
+ assert len(_deaf_reports(caplog)) == 1
+ for _ in range(2):
+ adapter._check_ingress_dispatch_stall()
+ assert len(_deaf_reports(caplog)) == 2
+
+ # A rebuilt consumer starts the backlog from zero, and a late response from the fenced
+ # generation is ignored.
+ stale_generation = adapter._polling_generation
+ adapter._begin_polling_generation()
+ assert adapter._record_polling_progress(stale_generation) is False
+ _receive(adapter, 5, generation=stale_generation)
+ assert adapter._updates_received_total == 0
+ for _ in range(3):
+ adapter._check_ingress_dispatch_stall()
+ assert len(_deaf_reports(caplog)) == 2
@pytest.mark.asyncio
async def test_missing_message_handler_is_logged_once_not_silent(caplog):
- """A connected adapter with no handler discards 100% of inbound.
-
- Before #102260 this returned with no log line at all, so a mis-wired
- adapter looked exactly like a quiet chat.
- """
- adapter = _make_adapter()
+ adapter = TelegramAdapter(PlatformConfig(enabled=True, token="test-token"))
adapter._message_handler = None
-
- with caplog.at_level(logging.ERROR):
- await adapter.handle_message(_text_event())
- await adapter.handle_message(_text_event())
-
- matches = [r for r in caplog.records if "no gateway message handler" in r.message]
- assert len(matches) == 1, "must report the deaf adapter exactly once"
- assert adapter._inbound_delivered_total == 0
-
-
-async def test_delivery_to_gateway_handler_increments_counter():
- adapter = _make_adapter()
- adapter.note_inbound_delivered()
-
- assert adapter._inbound_delivered_total == 1
- assert adapter._last_inbound_delivered_monotonic is not None
-
-
-# ---------------------------------------------------------------------------
-# gap watchdog
-# ---------------------------------------------------------------------------
-
-
-def _armed_gap_adapter(*, received=3, dispatched=3, delivered=0, age=600.0):
- adapter = _make_adapter()
- now = _time.monotonic()
- adapter._updates_received_total = received
- adapter._updates_dispatched_total = dispatched
- adapter._inbound_delivered_total = delivered
- adapter._last_update_received_monotonic = now - age
- adapter._last_inbound_delivered_monotonic = None
- return adapter
-
-
-def test_no_report_while_within_the_gap_window(caplog):
- adapter = _armed_gap_adapter(age=10.0)
- with caplog.at_level(logging.ERROR):
- adapter._check_ingress_delivery_gap()
- assert not [r for r in caplog.records if "healthy but deaf" in r.message]
-
-
-def test_no_report_when_nothing_was_ever_received(caplog):
- """An idle bot must never be accused of being deaf."""
- adapter = _make_adapter()
- with caplog.at_level(logging.ERROR):
- adapter._check_ingress_delivery_gap()
- assert not [r for r in caplog.records if "healthy but deaf" in r.message]
-
-
-def test_no_report_when_delivery_followed_the_last_update(caplog):
- adapter = _armed_gap_adapter()
- adapter._inbound_delivered_total = 3
- adapter._last_inbound_delivered_monotonic = (
- adapter._last_update_received_monotonic + 1
+ event = MessageEvent(
+ text="hi",
+ message_type=MessageType.TEXT,
+ source=SessionSource(platform=Platform.TELEGRAM, chat_id="1", user_id="1", chat_type="dm"),
)
with caplog.at_level(logging.ERROR):
- adapter._check_ingress_delivery_gap()
- assert not [r for r in caplog.records if "healthy but deaf" in r.message]
-
-
-def test_dispatched_shortfall_names_the_dispatcher(caplog):
- """received > dispatched: PTB never carried the updates to the handlers."""
- adapter = _armed_gap_adapter(received=5, dispatched=1)
- with caplog.at_level(logging.ERROR):
- adapter._check_ingress_delivery_gap()
- (record,) = [r for r in caplog.records if "healthy but deaf" in r.message]
- assert "dispatcher is not draining" in record.getMessage()
-
-
-def test_delivery_shortfall_names_hermes(caplog):
- """dispatched == received but nothing delivered: Hermes drops them."""
- adapter = _armed_gap_adapter(received=4, dispatched=4)
- with caplog.at_level(logging.ERROR):
- adapter._check_ingress_delivery_gap()
- (record,) = [r for r in caplog.records if "healthy but deaf" in r.message]
- message = record.getMessage()
- assert "dropped inside Hermes" in message
- assert "4 update(s) received" in message
-
-
-def test_report_is_not_repeated_until_more_updates_arrive(caplog):
- adapter = _armed_gap_adapter()
- with caplog.at_level(logging.ERROR):
- adapter._check_ingress_delivery_gap()
- adapter._check_ingress_delivery_gap()
- assert len([r for r in caplog.records if "healthy but deaf" in r.message]) == 1
-
- # A further update with still no delivery is a new, reportable data point.
- adapter._updates_received_total += 1
- adapter._updates_dispatched_total += 1
- with caplog.at_level(logging.ERROR):
- adapter._check_ingress_delivery_gap()
- assert len([r for r in caplog.records if "healthy but deaf" in r.message]) == 2
-
-
-def test_gap_check_never_triggers_recovery():
- """Reconnecting a healthy transport cannot fix a dropped update.
-
- The reconnect ladder belongs to the transport probes; this check is
- diagnosis only, so it must leave the ladder untouched.
- """
- adapter = _armed_gap_adapter()
- adapter._check_ingress_delivery_gap()
- assert adapter._polling_error_task is None
-
-
-def test_gap_check_skipped_in_webhook_mode(caplog):
- adapter = _armed_gap_adapter()
- adapter._webhook_mode = True
- with caplog.at_level(logging.ERROR):
- adapter._check_ingress_delivery_gap()
- assert not [r for r in caplog.records if "healthy but deaf" in r.message]
-
-
-def test_gap_check_skipped_during_teardown(caplog):
- adapter = _armed_gap_adapter()
- adapter._polling_teardown_started = True
- with caplog.at_level(logging.ERROR):
- adapter._check_ingress_delivery_gap()
- assert not [r for r in caplog.records if "healthy but deaf" in r.message]
-
-
-# ---------------------------------------------------------------------------
-# dispatched counter
-# ---------------------------------------------------------------------------
-
-
-async def test_catch_all_observer_counts_dispatch_before_early_return():
- """The counter must be stamped even when no plugin hook is installed.
-
- ``_on_platform_update`` returns immediately without a platform-event
- handler; if the counter sat after that return, every gateway without the
- hook would report a permanent dispatcher stall.
- """
- adapter = _make_adapter()
- adapter._platform_event_handler = None
-
- await adapter._on_platform_update(MagicMock(), MagicMock())
-
- assert adapter._updates_dispatched_total == 1
-
-
-async def test_heartbeat_runs_the_gap_check():
- """The check has to be wired into the loop that actually runs."""
- adapter = _make_adapter()
- bot = MagicMock()
- bot.get_me = AsyncMock()
- adapter._app.bot = bot
- adapter._bot = bot
- called = []
- adapter._check_ingress_delivery_gap = lambda: called.append(True)
- adapter._probe_pending_updates = AsyncMock()
- adapter._check_polling_stall = AsyncMock()
-
- real_sleep = asyncio.sleep
-
- async def fast_sleep(_delay, *args, **kwargs):
- await real_sleep(0)
-
- task = asyncio.get_running_loop().create_task(adapter._polling_heartbeat_loop())
- import plugins.platforms.telegram.adapter as tg_adapter
-
- original = tg_adapter.asyncio.sleep
- tg_adapter.asyncio.sleep = fast_sleep
- try:
- for _ in range(50):
- await real_sleep(0)
- if called:
- break
- finally:
- tg_adapter.asyncio.sleep = original
- task.cancel()
- try:
- await task
- except asyncio.CancelledError:
- pass
-
- assert called, "_polling_heartbeat_loop must run the ingress gap check"
+ await adapter.handle_message(event)
+ await adapter.handle_message(event)
+ assert len([r for r in caplog.records if "no gateway message handler" in r.message]) == 1