The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(telegram): slim the scheduled typing re-arm and trim its tests to two invariants
teknium13250020b34dc
diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.pyindex 5b975546209..193f896e3b8 100644--- a/plugins/platforms/telegram/adapter.py+++ b/plugins/platforms/telegram/adapter.py@@ -3392,68 +3392,39 @@ class TelegramAdapter(BasePlatformAdapter):return _flood_cap_result(wait)raise- def _typing_retrigger_state(self) -> tuple[Dict[str, "asyncio.Task"], Dict[str, float], float]:- """Re-arm bookkeeping, materialised on demand — tests build adapters via ``object.__new__()``- (no ``__init__``), so these attributes are not guaranteed to exist."""- tasks = getattr(self, "_telegram_typing_retrigger_tasks", None)- if not isinstance(tasks, dict):- tasks = self._telegram_typing_retrigger_tasks = {}- sent_at = getattr(self, "_telegram_typing_retrigger_at", None)- if not isinstance(sent_at, dict):- sent_at = self._telegram_typing_retrigger_at = {}- try:- interval = float(getattr(self, "_telegram_typing_retrigger_interval", 2.0))- except (TypeError, ValueError):- interval = 2.0- return tasks, sent_at, interval-- def _clear_typing_retrigger(self, chat_id: str, finished: "asyncio.Task") -> None:- """Drop the in-flight slot, but only if it is still this task's (a newer one may own it)."""- tasks = getattr(self, "_telegram_typing_retrigger_tasks", None)- if isinstance(tasks, dict) and tasks.get(chat_id) is finished:- tasks.pop(chat_id, None)-- async def _send_typing_quietly(self, chat_id: str, metadata: Optional[Dict[str, Any]]) -> None:- """Best-effort typing send; ``send_typing`` already logs and backs off on its own failures."""- with contextlib.suppress(Exception):- await self.send_typing(chat_id, metadata=metadata)-async def _retrigger_typing(self, chat_id: str, metadata: Optional[Dict[str, Any]]) -> None:"""Re-arm typing after an intermediate send (Telegram clears it when a message lands). Skipped onthe FINAL reply (``metadata["notify"]``): the refresh loop is gone and no API cancels the bubble.- Scheduled rather than awaited. ``sendChatAction`` is a fire-and-forget UI hint whose result nobody- reads, but awaiting it here ran its TLS round-trip on the same event loop as the ``getUpdates``- long-polls. Streaming re-arms after *every* intermediate send, so with several agents streaming at- once the loop stayed pinned, the polls were never serviced, and they decayed into CLOSE-WAIT while- the adapter still reported ``connected`` (#111727). One in-flight re-arm per chat, at most one per- ``typing_retrigger_min_interval_seconds``."""- if (metadata or {}).get("notify"):- return- # Only _keep_typing consulted this, so the documented `typing_indicator: false` workaround still- # paid for a sendChatAction on every intermediate send.- if not getattr(getattr(self, "config", None), "typing_indicator", True):+ Scheduled, never awaited: ``sendChatAction`` is a fire-and-forget UI hint, and awaiting its TLS+ round-trip on the send path after *every* streamed chunk pinned the event loop the ``getUpdates``+ long-polls live on until they rotted into CLOSE-WAIT while the adapter still reported connected+ (#111727). ``_keep_typing`` already refreshes every 2s, so one in-flight re-arm per chat, at most+ one per ``typing_retrigger_min_interval_seconds``, covers the gap a landed message leaves."""+ if (metadata or {}).get("notify") or not getattr(getattr(self, "config", None), "typing_indicator", True):return- chat_key = str(chat_id)- tasks, sent_at, min_interval = self._typing_retrigger_state()- in_flight = tasks.get(chat_key)+ # __dict__.setdefault: tests build adapters via object.__new__() (no __init__).+ tasks: Dict[str, asyncio.Task] = self.__dict__.setdefault("_telegram_typing_retrigger_tasks", {})+ sent_at: Dict[str, float] = self.__dict__.setdefault("_telegram_typing_retrigger_at", {})+ key = str(chat_id)+ in_flight = tasks.get(key)if in_flight is not None and not in_flight.done():return- try:- loop = asyncio.get_running_loop()- except RuntimeError:- return+ loop = asyncio.get_running_loop()now = loop.time()- if min_interval > 0:- previous = sent_at.get(chat_key)- # Stamped at scheduling time, not completion: a burst of chunks must not all pass the- # check while the first round-trip is still open.- if previous is not None and (now - previous) < min_interval:- return- sent_at[chat_key] = now- task = loop.create_task(self._send_typing_quietly(chat_id, metadata))- tasks[chat_key] = task- task.add_done_callback(lambda finished, key=chat_key: self._clear_typing_retrigger(key, finished))+ # Stamped at scheduling time, not completion, so a burst of chunks cannot all pass while the+ # first round-trip is still open.+ if now - sent_at.get(key, float("-inf")) < getattr(self, "_telegram_typing_retrigger_interval", 2.0):+ return+ sent_at[key] = now++ async def _quiet() -> None:+ with contextlib.suppress(Exception):+ await self.send_typing(chat_id, metadata=metadata)++ task = loop.create_task(_quiet())+ tasks[key] = task+ task.add_done_callback(lambda done: tasks.get(key) is done and tasks.pop(key, None))# Shutdown cancels _background_tasks, so a detached re-arm cannot outlive the adapter.tracked = getattr(self, "_background_tasks", None)if isinstance(tracked, set):diff --git a/tests/gateway/test_telegram_typing_retrigger.py b/tests/gateway/test_telegram_typing_retrigger.pyindex ef02b83b568..d9d7013ce80 100644--- a/tests/gateway/test_telegram_typing_retrigger.py+++ b/tests/gateway/test_telegram_typing_retrigger.py@@ -1,190 +1,62 @@-"""Telegram post-send typing re-arm: off the critical path, deduped and rate-limited (#111727).+"""Telegram post-send typing re-arm is scheduled off the send path and collapsed per chat (#111727).Awaiting ``sendChatAction`` after every intermediate send ran its TLS round-trip on the same event-loop as the ``getUpdates`` long-polls; under concurrent streaming the polls were starved until they+loop as the ``getUpdates`` long-polls; under concurrent streaming the polls starved until theyrotted into CLOSE-WAIT while the adapter still reported ``connected``."""import asyncio-import sys-from pathlib import Path+from types import SimpleNamespacefrom unittest.mock import AsyncMockimport pytest-_repo = str(Path(__file__).resolve().parents[2])-if _repo not in sys.path:- sys.path.insert(0, _repo)from gateway.config import PlatformConfigfrom plugins.platforms.telegram.adapter import TelegramAdapter-def _make_adapter(**config_kwargs):- adapter = TelegramAdapter(PlatformConfig(enabled=True, token="test-token", **config_kwargs))+def _make_adapter():+ adapter = TelegramAdapter(PlatformConfig(enabled=True, token="test-token"))+ adapter._rich_messages_enabled = Falseadapter._bot = AsyncMock()+ adapter._bot.send_message = AsyncMock(return_value=SimpleNamespace(message_id=1))adapter._bot.send_chat_action = AsyncMock(return_value=None)return adapter-async def _drain(adapter, chat_id="123"):- """Await the scheduled re-arm so assertions see its effect."""- task = adapter._telegram_typing_retrigger_tasks.get(str(chat_id))- if task is not None:- await task+async def _drain(adapter):+ pending = [t for t in adapter._background_tasks if not t.done()]+ if pending:+ await asyncio.wait(pending, timeout=2)@pytest.mark.asyncio-async def test_retrigger_does_not_await_the_round_trip():- """The send path must return before sendChatAction completes — this is the whole fix."""+async def test_send_returns_without_waiting_on_typing():+ """An intermediate send completes while sendChatAction is still stalled."""adapter = _make_adapter()released = asyncio.Event()- started = asyncio.Event()async def blocking_action(**kwargs):- started.set()await released.wait()adapter._bot.send_chat_action = AsyncMock(side_effect=blocking_action)- # Would hang forever if the re-arm were still awaited inline.- await asyncio.wait_for(adapter._retrigger_typing("123", None), timeout=1.0)+ result = await asyncio.wait_for(adapter.send("123", "chunk"), timeout=1.0)- await asyncio.wait_for(started.wait(), timeout=1.0)- assert not adapter._telegram_typing_retrigger_tasks["123"].done()+ assert result.success is Truereleased.set()await _drain(adapter)assert adapter._bot.send_chat_action.await_count == 1@pytest.mark.asyncio-async def test_streaming_burst_collapses_to_one_chat_action():- """Every chunk of a streamed reply re-arms typing; within the interval that is one API call."""- adapter = _make_adapter()-- for _ in range(20):- await adapter._retrigger_typing("123", None)- await _drain(adapter)-- assert adapter._bot.send_chat_action.await_count == 1---async def test_retrigger_resumes_after_the_interval_elapses():+async def test_streaming_burst_collapses_to_one_chat_action_per_chat():+ """Every streamed chunk re-arms typing; within the interval that is one API call per chat."""adapter = _make_adapter()- adapter._telegram_typing_retrigger_interval = 2.0-- await adapter._retrigger_typing("123", None)- await _drain(adapter)- # Simulate the interval having passed rather than sleeping through it.- adapter._telegram_typing_retrigger_at["123"] -= 2.5- await adapter._retrigger_typing("123", None)+ for i in range(20):+ assert (await adapter.send("123", f"chunk {i}")).success+ assert (await adapter.send("456", f"chunk {i}")).successawait _drain(adapter)assert adapter._bot.send_chat_action.await_count == 2---async def test_throttle_is_per_chat():- adapter = _make_adapter()-- await adapter._retrigger_typing("123", None)- await adapter._retrigger_typing("456", None)- await _drain(adapter, "123")- await _drain(adapter, "456")-- assert adapter._bot.send_chat_action.await_count == 2---async def test_in_flight_rearm_is_not_duplicated():- """A slow round-trip must not accumulate one task per chunk."""- adapter = _make_adapter()- adapter._telegram_typing_retrigger_interval = 0.0 # throttle off: the in-flight guard alone- released = asyncio.Event()-- async def blocking_action(**kwargs):- await released.wait()-- adapter._bot.send_chat_action = AsyncMock(side_effect=blocking_action)-- for _ in range(10):- await adapter._retrigger_typing("123", None)-- assert len(adapter._telegram_typing_retrigger_tasks) == 1- released.set()- await _drain(adapter)- assert adapter._bot.send_chat_action.await_count == 1---async def test_typing_indicator_disabled_suppresses_rearm():- """`typing_indicator: false` only gated _keep_typing, so the re-arm still cost a call per send."""- adapter = _make_adapter(typing_indicator=False)-- await adapter._retrigger_typing("123", None)- await _drain(adapter)-- assert adapter._telegram_typing_retrigger_tasks == {}- adapter._bot.send_chat_action.assert_not_called()---async def test_final_reply_still_does_not_rearm():- adapter = _make_adapter()-- await adapter._retrigger_typing("123", {"notify": True})-- assert adapter._telegram_typing_retrigger_tasks == {}- adapter._bot.send_chat_action.assert_not_called()---async def test_rearm_is_tracked_for_shutdown_cancellation():- """Detached tasks must join _background_tasks or they outlive the adapter."""- adapter = _make_adapter()- released = asyncio.Event()-- async def blocking_action(**kwargs):- await released.wait()-- adapter._bot.send_chat_action = AsyncMock(side_effect=blocking_action)-- await adapter._retrigger_typing("123", None)- task = adapter._telegram_typing_retrigger_tasks["123"]- assert task in adapter._background_tasks-- await adapter.cancel_background_tasks()- assert task.cancelled() or task.done()- assert adapter._telegram_typing_retrigger_tasks == {}---async def test_rearm_failure_does_not_escape_to_the_send_path():- adapter = _make_adapter()- adapter._bot.send_chat_action = AsyncMock(side_effect=OSError("telegram network failure"))-- await adapter._retrigger_typing("123", None)- await _drain(adapter)-- assert adapter._telegram_typing_retrigger_tasks == {}---async def test_send_returns_without_waiting_on_typing():- """End-to-end: an intermediate send completes even while sendChatAction is stalled."""- adapter = _make_adapter()- adapter._rich_messages_enabled = False- adapter._bot.send_message = AsyncMock(return_value=type("Msg", (), {"message_id": 1})())- released = asyncio.Event()-- async def blocking_action(**kwargs):- await released.wait()-- adapter._bot.send_chat_action = AsyncMock(side_effect=blocking_action)-- result = await asyncio.wait_for(adapter.send("123", "chunk"), timeout=1.0)-- assert result.success is True- released.set()- await _drain(adapter)