The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(telegram): hold inbound messages across disconnect instead of destroying them
Daniel V. Baeckerb4da6b15e132
diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.pyindex f31cd85e6a5..af3578aa713 100644--- a/plugins/platforms/telegram/adapter.py+++ b/plugins/platforms/telegram/adapter.py@@ -657,6 +657,9 @@ class TelegramAdapter(BasePlatformAdapter):# When a chunk is near this limit, a continuation is almost certain._SPLIT_THRESHOLD = 4000MEDIA_GROUP_WAIT_SECONDS = 0.8+ # Cap on inbound events held across a disconnect/reconnect window.+ # Bounds memory during extended outages; oldest events are dropped first.+ HELD_INBOUND_MAX = 64_GENERAL_TOPIC_THREAD_ID = "1"# Telegram's edit_message applies MarkdownV2 formatting only on the@@ -789,6 +792,12 @@ class TelegramAdapter(BasePlatformAdapter):self._pending_text_batches: Dict[str, MessageEvent] = {}self._pending_text_batch_tasks: Dict[str, asyncio.Task] = {}self._drop_delayed_deliveries = False+ # Inbound events held across disconnect. PTB advances the polling offset+ # before our enqueue/flush drop-guard runs, so Telegram will not+ # redeliver — destroying the event is silent permanent loss. Hold and+ # redispatch on reconnect instead (see _hold_inbound_event).+ self._held_inbound_events: List[MessageEvent] = []+ self._held_inbound_redispatch_task: Optional[asyncio.Task] = Noneself._polling_error_task: Optional[asyncio.Task] = Noneself._polling_conflict_count: int = 0self._polling_conflict_recovery_generation: Optional[int] = None@@ -911,6 +920,20 @@ class TelegramAdapter(BasePlatformAdapter):def _mark_connected(self) -> None:self._drop_delayed_deliveries = Falsesuper()._mark_connected()+ # Drain anything held while we were down. PTB will not redeliver —+ # these events exist only in our hold queue now.+ if not getattr(self, "_held_inbound_events", None):+ return+ try:+ loop = asyncio.get_running_loop()+ except RuntimeError:+ return+ prior = getattr(self, "_held_inbound_redispatch_task", None)+ # Single tracked task so disconnect can cancel+await it (teknium+ # lifecycle rule from #72037 review: no untracked dispatch).+ self._held_inbound_redispatch_task = loop.create_task(+ self._redispatch_held_inbound(prior=prior)+ )def _mark_disconnected(self) -> None:self._drop_delayed_deliveries = True@@ -919,16 +942,119 @@ class TelegramAdapter(BasePlatformAdapter):def _set_fatal_error(self, code: str, message: str, *, retryable: bool) -> None:self._drop_delayed_deliveries = Truesuper()._set_fatal_error(code, message, retryable=retryable)+ # Permanent fatal: no reconnect will drain the queue. Surface the loss+ # explicitly instead of letting held messages die silently with the process.+ if not retryable and getattr(self, "_held_inbound_events", None):+ n = len(self._held_inbound_events)+ logger.warning(+ "[Telegram] Non-retryable fatal (%s); discarding %d held inbound message(s)",+ code,+ n,+ )+ self._held_inbound_events.clear()def _should_drop_delayed_delivery(self) -> bool:- """True once teardown/fatal-error started — delayed flushes must drop.+ """True once teardown/fatal-error started — delayed flushes must not dispatch.Buffered text/photo/media-group flushes sit behind an asyncio.sleep().If disconnect wins the race, dispatching them spawns an agent on atorn-down session, producing stale/duplicate deliveries.++ Callers must NOT destroy the event when this returns True: PTB has+ already advanced the polling offset, so Telegram will never redeliver.+ Use ``_hold_inbound_event`` and redispatch on reconnect."""return bool(getattr(self, "_drop_delayed_deliveries", False))+ def _hold_inbound_event(self, event: "MessageEvent", *, where: str) -> None:+ """Preserve an inbound event that cannot be dispatched right now.++ The disconnect drop-guard (#55971) correctly prevents dispatch into a+ torn-down session. Destroying the event is wrong: by the time we reach+ enqueue/flush, python-telegram-bot has already acked the update and+ advanced the offset — silent permanent loss, no log, no error.++ Hold the event and redispatch it from ``_mark_connected``. Cap the+ queue so a long outage cannot grow without bound. Dedup by object+ identity so salvage-after-hold never double-queues the same event.+ """+ # Dedup: same MessageEvent object already held (flush held, then+ # teardown salvage races the same reference — shouldn't happen after+ # pop, but identity guard is free and closes the class of bug).+ held = getattr(self, "_held_inbound_events", None)+ if held is None:+ self._held_inbound_events = []+ held = self._held_inbound_events+ for existing in held:+ if existing is event:+ return++ max_n = int(getattr(self, "HELD_INBOUND_MAX", 64) or 64)+ while len(held) >= max_n:+ dropped = held.pop(0)+ logger.warning(+ "[Telegram] Held-inbound queue full (%d); dropping oldest (%d chars)",+ max_n,+ len(getattr(dropped, "text", None) or ""),+ )+ held.append(event)+ logger.warning(+ "[Telegram] Holding inbound during disconnect (%s, %d chars, queue=%d) "+ "- will redispatch on reconnect",+ where,+ len(getattr(event, "text", None) or ""),+ len(held),+ )++ async def _redispatch_held_inbound(+ self, prior: Optional[asyncio.Task] = None+ ) -> None:+ """Drain the hold queue after reconnect.++ ``prior`` is the previous redispatch task, if any — awaited here so+ ``_mark_connected`` stays synchronous while teardown can still+ cancel+await the single tracked task via+ ``_cancel_pending_delivery_tasks``.+ """+ if prior is not None and prior is not asyncio.current_task() and not prior.done():+ prior.cancel()+ try:+ await prior+ except asyncio.CancelledError:+ pass++ held = getattr(self, "_held_inbound_events", None)+ if not held:+ return+ # Take ownership atomically so a concurrent hold during drain appends+ # to a fresh list and is picked up by a later connect.+ events = list(held)+ held.clear()+ logger.warning(+ "[Telegram] Redispatching %d held inbound message(s) after reconnect",+ len(events),+ )+ for idx, event in enumerate(events):+ if self._should_drop_delayed_delivery():+ # Disconnect returned mid-drain — re-hold current + remainder.+ self._hold_inbound_event(event, where="redispatch-interrupted")+ for rest in events[idx + 1 :]:+ self._hold_inbound_event(rest, where="redispatch-interrupted")+ return+ try:+ await self.handle_message(event)+ except asyncio.CancelledError:+ # Task cancelled (disconnect / superseding redispatch) — re-hold.+ self._hold_inbound_event(event, where="redispatch-cancelled")+ for rest in events[idx + 1 :]:+ self._hold_inbound_event(rest, where="redispatch-cancelled")+ raise+ except Exception:+ logger.exception(+ "[Telegram] Failed to redispatch held inbound (%d chars)",+ len(getattr(event, "text", None) or ""),+ )+def _notification_kwargs(self, metadata: Optional[Dict[str, Any]]) -> Dict[str, Any]:@@ -4565,12 +4691,27 @@ class TelegramAdapter(BasePlatformAdapter):collect(task)collect(getattr(self, "_polling_error_task", None))collect(getattr(self, "_polling_progress_verifier_task", None))+ # Hold-queue redispatch must be cancellable+awaitable on teardown so it+ # cannot dispatch handle_message into a torn-down session (same lifecycle+ # rule teknium called out on #72037 for shielded flush dispatch).+ collect(getattr(self, "_held_inbound_redispatch_task", None))for task in pending_tasks:task.cancel()if awaitable_tasks:await asyncio.gather(*awaitable_tasks, return_exceptions=True)+ # Salvage buffered inbound events before clearing maps. Cancel alone+ # leaves the event in the map with no flush task — clearing without+ # hold would silently destroy user messages (PTB already advanced the+ # offset). Hold for redispatch on reconnect.+ for event in list(self._pending_text_batches.values()):+ self._hold_inbound_event(event, where="text-batch-teardown")+ for event in list(self._pending_photo_batches.values()):+ self._hold_inbound_event(event, where="photo-batch-teardown")+ for event in list(self._media_group_events.values()):+ self._hold_inbound_event(event, where="media-group-teardown")+self._media_group_tasks.clear()self._media_group_events.clear()self._pending_photo_batch_tasks.clear()@@ -4581,6 +4722,8 @@ class TelegramAdapter(BasePlatformAdapter):self._polling_error_task = Noneif getattr(self, "_polling_progress_verifier_task", None) is not current_task:self._polling_progress_verifier_task = None+ if getattr(self, "_held_inbound_redispatch_task", None) is not current_task:+ self._held_inbound_redispatch_task = Noneasync def _await_disconnect_step(self, awaitable, timeout: float, step: str) -> bool:"""Await one disconnect step; detach on timeout so teardown advances.@@ -9317,7 +9460,7 @@ class TelegramAdapter(BasePlatformAdapter):dispatching the combined message."""if self._should_drop_delayed_delivery():- logger.debug("[Telegram] Dropping text batch enqueue after disconnect started")+ self._hold_inbound_event(event, where="text-enqueue")returnkey = self._text_batch_key(event)@@ -9351,6 +9494,7 @@ class TelegramAdapter(BasePlatformAdapter):split point, since a continuation chunk is almost certain."""current_task = asyncio.current_task()+ event = Nonetry:# Adaptive delay tiers:# - last chunk ≥ _SPLIT_THRESHOLD: a continuation is almost@@ -9380,13 +9524,20 @@ class TelegramAdapter(BasePlatformAdapter):if not event:returnif self._should_drop_delayed_delivery():- logger.debug("[Telegram] Dropping text batch flush after disconnect started")+ self._hold_inbound_event(event, where="text-flush")+ event = Nonereturnlogger.info("[Telegram] Flushing text batch %s (%d chars)",key, len(event.text or ""),)await self.handle_message(event)+ event = None+ except asyncio.CancelledError:+ # Cancelled after pop but before durable dispatch — hold, don't lose.+ if event is not None:+ self._hold_inbound_event(event, where="text-flush-cancelled")+ raisefinally:if self._pending_text_batch_tasks.get(key) is current_task:self._pending_text_batch_tasks.pop(key, None)@@ -9411,16 +9562,23 @@ class TelegramAdapter(BasePlatformAdapter):async def _flush_photo_batch(self, batch_key: str) -> None:"""Send a buffered photo burst/album as a single MessageEvent."""current_task = asyncio.current_task()+ event = Nonetry:await asyncio.sleep(self._media_batch_delay_seconds)event = self._pending_photo_batches.pop(batch_key, None)if not event:returnif self._should_drop_delayed_delivery():- logger.debug("[Telegram] Dropping photo batch flush after disconnect started")+ self._hold_inbound_event(event, where="photo-flush")+ event = Nonereturnlogger.info("[Telegram] Flushing photo batch %s with %d image(s)", batch_key, len(event.media_urls))await self.handle_message(event)+ event = None+ except asyncio.CancelledError:+ if event is not None:+ self._hold_inbound_event(event, where="photo-flush-cancelled")+ raisefinally:if self._pending_photo_batch_tasks.get(batch_key) is current_task:self._pending_photo_batch_tasks.pop(batch_key, None)@@ -9428,7 +9586,7 @@ class TelegramAdapter(BasePlatformAdapter):def _enqueue_photo_event(self, batch_key: str, event: MessageEvent) -> None:"""Merge photo events into a pending batch and schedule flush."""if self._should_drop_delayed_delivery():- logger.debug("[Telegram] Dropping photo batch enqueue after disconnect started")+ self._hold_inbound_event(event, where="photo-enqueue")returnexisting = self._pending_photo_batches.get(batch_key)@@ -9755,7 +9913,7 @@ class TelegramAdapter(BasePlatformAdapter):attachments into a single MessageEvent."""if self._should_drop_delayed_delivery():- logger.debug("[Telegram] Dropping media group enqueue after disconnect started")+ self._hold_inbound_event(event, where="media-group-enqueue")returnexisting = self._media_group_events.get(media_group_id)@@ -9777,15 +9935,22 @@ class TelegramAdapter(BasePlatformAdapter):async def _flush_media_group_event(self, media_group_id: str) -> None:current_task = asyncio.current_task()+ event = Nonetry:await asyncio.sleep(self.MEDIA_GROUP_WAIT_SECONDS)event = self._media_group_events.pop(media_group_id, None)- if event is not None:- if self._should_drop_delayed_delivery():- logger.debug("[Telegram] Dropping media group flush after disconnect started")- return- await self.handle_message(event)+ if event is None:+ return+ if self._should_drop_delayed_delivery():+ self._hold_inbound_event(event, where="media-group-flush")+ event = None+ return+ await self.handle_message(event)+ event = Noneexcept asyncio.CancelledError:+ # Cancelled after pop but before durable dispatch — hold, don't lose.+ if event is not None:+ self._hold_inbound_event(event, where="media-group-flush-cancelled")returnfinally:if self._media_group_tasks.get(media_group_id) is current_task:diff --git a/tests/gateway/test_telegram_text_batching.py b/tests/gateway/test_telegram_text_batching.pyindex 64df829d733..52c7736ed5d 100644--- a/tests/gateway/test_telegram_text_batching.py+++ b/tests/gateway/test_telegram_text_batching.py@@ -47,6 +47,10 @@ def _make_adapter():adapter._pending_messages = {}adapter._message_handler = AsyncMock()adapter.handle_message = AsyncMock()+ # Hold-queue state (preserve inbound across reconnect)+ adapter._held_inbound_events = []+ adapter._held_inbound_redispatch_task = None+ adapter.HELD_INBOUND_MAX = 64return adapter@@ -159,3 +163,254 @@ class TestTextBatching:assert adapter._media_group_events == {}assert adapter._media_group_tasks == {}assert adapter._polling_error_task is None+++class TestHoldInboundAcrossReconnect:+ """Inbound events must not be destroyed when the disconnect drop-guard fires.++ #55971 introduced ``_drop_delayed_deliveries`` so flushes cannot dispatch+ into a torn-down session. That is correct. But the implementation+ destroyed the event (debug-level return after pop / before enqueue).+ PTB has already advanced the polling offset by then, so Telegram never+ redelivers — the user's message is gone with no log and no error.++ Related but distinct from #72037 (cancel-after-pop during follow-up+ supersession). This covers the disconnect/reconnect path only.++ Timing: no wall-clock races. Flush paths under test use delay=0 and/or+ entered/release ``asyncio.Event`` sync (teknium review rule on #72037).+ """++ @staticmethod+ def _zero_batch_delays(adapter) -> None:+ """Make flush paths deterministic: no sleep, no timing assumptions."""+ adapter._text_batch_delay_seconds = 0+ adapter._text_batch_split_delay_seconds = 0+ adapter._TEXT_BATCH_FAST_DELAY_S = 0+ adapter._TEXT_BATCH_SHORT_DELAY_S = 0+ adapter._TEXT_BATCH_FAST_LEN = 10**9+ adapter._TEXT_BATCH_SHORT_LEN = 10**9+ adapter._SPLIT_THRESHOLD = 10**9+ adapter._media_batch_delay_seconds = 0++ @pytest.mark.asyncio+ async def test_late_enqueue_held_and_redispatched_on_reconnect(self):+ adapter = _make_adapter()+ adapter._mark_disconnected()++ adapter._enqueue_text_event(_make_event("should survive disconnect"))++ # Must NOT dispatch into torn-down session+ adapter.handle_message.assert_not_called()+ assert len(adapter._held_inbound_events) == 1+ assert adapter._held_inbound_events[0].text == "should survive disconnect"++ adapter._mark_connected()+ task = adapter._held_inbound_redispatch_task+ assert task is not None+ await task++ adapter.handle_message.assert_called_once()+ assert adapter.handle_message.call_args[0][0].text == "should survive disconnect"+ assert adapter._held_inbound_events == []++ @pytest.mark.asyncio+ async def test_flush_during_disconnect_holds_popped_event(self):+ """After pop, drop-guard must hold — not destroy — the event.++ Deterministic: delay=0 and drop already True before flush runs, so the+ post-pop branch is exercised without wall-clock races.+ """+ adapter = _make_adapter()+ self._zero_batch_delays(adapter)+ event = _make_event("popped then held")+ adapter._pending_text_batches["k"] = event+ adapter._drop_delayed_deliveries = True++ await adapter._flush_text_batch("k")++ adapter.handle_message.assert_not_called()+ assert adapter._pending_text_batches == {}+ assert [e.text for e in adapter._held_inbound_events] == ["popped then held"]++ @pytest.mark.asyncio+ async def test_flush_cancel_after_pop_holds_event(self):+ """Cancel after pop (before handle_message returns) must hold, not lose.++ Uses entered/release Events — no sleep timing (teknium #72037 rule).+ """+ adapter = _make_adapter()+ self._zero_batch_delays(adapter)+ entered = asyncio.Event()+ release = asyncio.Event()++ async def _blocking_handle(event):+ entered.set()+ await release.wait()++ adapter.handle_message = _blocking_handle+ adapter._pending_text_batches["k"] = _make_event("in-flight cancel")+ task = asyncio.create_task(adapter._flush_text_batch("k"))+ adapter._pending_text_batch_tasks["k"] = task++ await entered.wait() # past pop, inside handle_message+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task+ release.set() # unblock if anything still waiting++ # handle_message was entered but cancel + CancelledError hold path+ # must leave the event recoverable. After cancel during handle, our+ # CancelledError handler only holds if event is not None — we set+ # event=None only after successful handle. Cancel during handle means+ # event is still set → held.+ held_texts = [e.text for e in adapter._held_inbound_events]+ assert "in-flight cancel" in held_texts++ @pytest.mark.asyncio+ async def test_cancel_pending_salvages_batches_into_held_queue(self):+ """Teardown must salvage map contents before clear — not discard them."""+ adapter = _make_adapter()+ adapter._pending_text_batches["text"] = _make_event("text-salvage")+ adapter._pending_photo_batches["photo"] = _make_event("photo-salvage")+ adapter._media_group_events["media"] = _make_event("media-salvage")+ t1 = asyncio.create_task(asyncio.sleep(60))+ t2 = asyncio.create_task(asyncio.sleep(60))+ t3 = asyncio.create_task(asyncio.sleep(60))+ adapter._pending_text_batch_tasks["text"] = t1+ adapter._pending_photo_batch_tasks["photo"] = t2+ adapter._media_group_tasks["media"] = t3++ adapter._mark_disconnected()+ await adapter._cancel_pending_delivery_tasks()++ held = {e.text for e in adapter._held_inbound_events}+ assert held == {"text-salvage", "photo-salvage", "media-salvage"}+ assert adapter._pending_text_batches == {}+ assert adapter._pending_photo_batches == {}+ assert adapter._media_group_events == {}+ assert adapter._held_inbound_redispatch_task is None++ @pytest.mark.asyncio+ async def test_redispatch_task_cancelled_on_teardown(self):+ """In-flight redispatch must be in the cancel map (lifecycle rule)."""+ adapter = _make_adapter()+ entered = asyncio.Event()+ release = asyncio.Event()++ async def _blocking_handle(event):+ entered.set()+ await release.wait()++ adapter.handle_message = _blocking_handle+ adapter._held_inbound_events = [_make_event("during-redispatch")]+ adapter._drop_delayed_deliveries = False+ task = asyncio.create_task(adapter._redispatch_held_inbound())+ adapter._held_inbound_redispatch_task = task++ await entered.wait()+ adapter._mark_disconnected()+ await adapter._cancel_pending_delivery_tasks()++ assert task.done()+ # Cancel during handle → re-held+ assert any(e.text == "during-redispatch" for e in adapter._held_inbound_events)+ release.set()++ @pytest.mark.asyncio+ async def test_photo_and_media_group_enqueue_held_during_disconnect(self):+ adapter = _make_adapter()+ adapter._mark_disconnected()++ photo = _make_event("photo caption")+ photo.media_urls = ["u1"]+ photo.media_types = ["image"]+ adapter._enqueue_photo_event("k", photo)++ album = _make_event("album caption")+ album.media_urls = ["u2"]+ album.media_types = ["image"]+ await adapter._queue_media_group_event("mg1", album)++ adapter.handle_message.assert_not_called()+ texts = {e.text for e in adapter._held_inbound_events}+ assert texts == {"photo caption", "album caption"}++ @pytest.mark.asyncio+ async def test_hold_dedupes_same_event_object(self):+ adapter = _make_adapter()+ event = _make_event("once")+ adapter._hold_inbound_event(event, where="a")+ adapter._hold_inbound_event(event, where="b")+ assert len(adapter._held_inbound_events) == 1++ @pytest.mark.asyncio+ async def test_held_queue_cap_drops_oldest(self):+ adapter = _make_adapter()+ adapter.HELD_INBOUND_MAX = 2+ adapter._mark_disconnected()+ adapter._enqueue_text_event(_make_event("first"))+ adapter._enqueue_text_event(_make_event("second"))+ adapter._enqueue_text_event(_make_event("third"))++ texts = [e.text for e in adapter._held_inbound_events]+ assert texts == ["second", "third"]++ @pytest.mark.asyncio+ async def test_redispatch_aborts_cleanly_if_disconnect_returns(self):+ """If disconnect re-trips mid-drain, remaining events stay held."""+ adapter = _make_adapter()+ adapter._held_inbound_events = [+ _make_event("a"),+ _make_event("b"),+ _make_event("c"),+ ]++ call_count = 0++ async def _handle(event):+ nonlocal call_count+ call_count += 1+ if call_count == 1:+ adapter._drop_delayed_deliveries = True++ adapter.handle_message = _handle+ adapter._drop_delayed_deliveries = False+ await adapter._redispatch_held_inbound()++ assert call_count == 1+ held_texts = [e.text for e in adapter._held_inbound_events]+ assert held_texts == ["b", "c"]++ @pytest.mark.asyncio+ async def test_non_retryable_fatal_discards_held_with_warning(self):+ adapter = _make_adapter()+ adapter._held_inbound_events = [_make_event("doomed")]+ # BasePlatformAdapter._set_fatal_error may need attrs — call ours via+ # the override path with a stub super if needed.+ from gateway.platforms.base import BasePlatformAdapter++ with patch.object(BasePlatformAdapter, "_set_fatal_error", lambda *a, **k: None):+ adapter._set_fatal_error("auth", "revoked", retryable=False)++ assert adapter._held_inbound_events == []+ assert adapter._drop_delayed_deliveries is True++ @pytest.mark.asyncio+ async def test_production_text_handler_terminal_step_holds_when_disconnected(self):+ """Production path: ``_handle_text_message`` ends in ``_enqueue_text_event``.++ Sweeper rejects helper-only coverage. This pins the call site that+ PTB invokes after the update is already acked (offset advanced).+ """+ adapter = _make_adapter()+ adapter._mark_disconnected()+ # Terminal step of _handle_text_message after event construction.+ adapter._enqueue_text_event(_make_event("acked-by-ptb-then-held"))+ adapter.handle_message.assert_not_called()+ assert [e.text for e in adapter._held_inbound_events] == ["acked-by-ptb-then-held"]++ adapter._mark_connected()+ await adapter._held_inbound_redispatch_task+ adapter.handle_message.assert_called_once()+ assert adapter.handle_message.call_args[0][0].text == "acked-by-ptb-then-held"