The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(telegram): share exception-graph walk across classifiers
kshitijk4poor6681f9ebc30f
diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.pyindex 1eccbebd092..a6eb37fa00a 100644--- a/plugins/platforms/telegram/adapter.py+++ b/plugins/platforms/telegram/adapter.py@@ -19,7 +19,7 @@ import threadingimport timefrom contextvars import ContextVarfrom datetime import datetime, timezone-from typing import Any, Awaitable, Callable, Dict, List, Optional, Set+from typing import Any, Awaitable, Callable, Dict, Iterator, List, Optional, Setlogger = logging.getLogger(__name__)@@ -93,6 +93,32 @@ async def _await_with_thread_deadline(awaitable, timeout: float, *, on_abandon=Nreturn result.value+def _iter_exception_graph(error: BaseException) -> "Iterator[BaseException]":+ """Yield ``error`` and every ``__cause__``/``__context__`` ancestor.++ PTB wraps httpx exceptions (``TimedOut`` wrapping ``httpx.PoolTimeout``+ wrapping …), and re-raised errors accumulate ``__context__`` chains, so a+ classifier must inspect the whole graph, not just the top frame. DFS with+ an identity-based ``seen`` set guards the cycles malformed chains can+ contain. Shared by the connect-timeout and pool-timeout classifiers.+ """+ seen: set[int] = set()+ stack: list[BaseException] = [error]+ while stack:+ cur = stack.pop()+ ident = id(cur)+ if ident in seen:+ continue+ seen.add(ident)+ yield cur+ cause = getattr(cur, "__cause__", None)+ context = getattr(cur, "__context__", None)+ if cause is not None:+ stack.append(cause)+ if context is not None:+ stack.append(context)++async def _first_completed(*futures: "asyncio.Future") -> None:"""Return when the first of ``futures`` completes.@@ -1857,24 +1883,11 @@ class TelegramAdapter(BasePlatformAdapter):should not be re-sent. A ConnectTimeout means the TCP connection wasnever established, so retrying is safe and prevents silent drops."""- seen: set[int] = set()- stack: list[BaseException] = [error]- while stack:- cur = stack.pop()- ident = id(cur)- if ident in seen:- continue- seen.add(ident)+ for cur in _iter_exception_graph(error):name = cur.__class__.__name__.lower()text = str(cur).lower()if "connecttimeout" in name or "connect timeout" in text or "connect timed out" in text:return True- cause = getattr(cur, "__cause__", None)- context = getattr(cur, "__context__", None)- if cause is not None:- stack.append(cause)- if context is not None:- stack.append(context)return False@staticmethod@@ -1890,26 +1903,13 @@ class TelegramAdapter(BasePlatformAdapter):wrapped ``httpx.PoolTimeout`` class as well as the message string so thecheck survives PTB message-wording changes."""- seen: set[int] = set()- stack: list[BaseException] = [error]- while stack:- cur = stack.pop()- ident = id(cur)- if ident in seen:- continue- seen.add(ident)+ for cur in _iter_exception_graph(error):name = cur.__class__.__name__.lower()text = str(cur).lower()if "pooltimeout" in name or "pool timeout" in text or ("connection pool" in text and "occupied" in text):return True- cause = getattr(cur, "__cause__", None)- context = getattr(cur, "__context__", None)- if cause is not None:- stack.append(cause)- if context is not None:- stack.append(context)return Falsedef _coerce_bool_extra(self, key: str, default: bool = False) -> bool:diff --git a/tests/gateway/test_telegram_network_reconnect.py b/tests/gateway/test_telegram_network_reconnect.pyindex f4bb3e269ab..1686e58470c 100644--- a/tests/gateway/test_telegram_network_reconnect.py+++ b/tests/gateway/test_telegram_network_reconnect.py@@ -850,3 +850,112 @@ async def test_disconnect_advances_past_cancellation_swallowing_lifecycle(monkeyrelease.set()await asyncio.wait({wedged}, timeout=0.2)+++# ---------------------------------------------------------------------------+# Exception-graph walker + pool/connect classifier contracts (PR #98094+# follow-up): the two classifiers previously had no direct tests at all.+# ---------------------------------------------------------------------------+class TestIterExceptionGraph:+ def test_flat_single(self):+ err = ValueError("boom")+ assert list(tg_adapter._iter_exception_graph(err)) == [err]++ def test_walks_cause_chain(self):+ root = ValueError("root")+ mid = RuntimeError("mid")+ mid.__cause__ = root+ top = Exception("top")+ top.__cause__ = mid+ seen = list(tg_adapter._iter_exception_graph(top))+ assert top in seen and mid in seen and root in seen++ def test_walks_context_chain(self):+ root = ValueError("during handling")+ top = RuntimeError("top")+ top.__context__ = root+ seen = list(tg_adapter._iter_exception_graph(top))+ assert top in seen and root in seen++ def test_cycle_guard(self):+ a = ValueError("a")+ b = RuntimeError("b")+ a.__cause__ = b+ b.__cause__ = a # cycle+ seen = list(tg_adapter._iter_exception_graph(a))+ assert seen.count(a) == 1 and seen.count(b) == 1 # terminates, no dupes++ def test_diamond_no_duplicates(self):+ root = ValueError("root")+ left = RuntimeError("left"); left.__cause__ = root+ right = TypeError("right"); right.__cause__ = root+ top = Exception("top"); top.__cause__ = left; top.__context__ = right+ seen = list(tg_adapter._iter_exception_graph(top))+ assert seen.count(root) == 1+++class TestPoolTimeoutClassifier:+ def test_ptb_pool_timeout_message(self):+ err = Exception(+ "Pool timeout: All connections in the connection pool are occupied. "+ "Request was *not* sent to Telegram."+ )+ assert TelegramAdapter._looks_like_pool_timeout(err) is True++ def test_wrapped_httpx_pooltimeout_class(self):+ try:+ raise ConnectionError("inner")+ except ConnectionError as inner:+ err = Exception("Timed out")+ err.__context__ = inner+ assert TelegramAdapter._looks_like_pool_timeout(err) is False++ def test_httpx_pooltimeout_class_name(self):+ class FakePoolTimeout(Exception):+ pass+ err = Exception("Timed out")+ err.__cause__ = FakePoolTimeout("x")+ assert TelegramAdapter._looks_like_pool_timeout(err) is True++ def test_generic_timeout_negative(self):+ assert TelegramAdapter._looks_like_pool_timeout(Exception("Timed out")) is False+ assert TelegramAdapter._looks_like_pool_timeout(Exception("Bad Gateway")) is False++ def test_occupied_connection_pool_substring(self):+ # Both substrings present -> match even without "pool timeout" phrasing.+ assert TelegramAdapter._looks_like_pool_timeout(+ Exception("All connections in the connection pool are occupied")+ ) is True+ # "occupied" alone (no "connection pool") must not match.+ assert TelegramAdapter._looks_like_pool_timeout(+ Exception("seat was occupied")+ ) is False+ # "connection pool" alone (no "occupied") must not match.+ assert TelegramAdapter._looks_like_pool_timeout(+ Exception("connection pool sizing")+ ) is False+++class TestConnectTimeoutClassifier:+ def test_class_name_match(self):+ class FakeConnectTimeout(Exception):+ pass+ assert TelegramAdapter._looks_like_connect_timeout(FakeConnectTimeout("x")) is True++ def test_message_match(self):+ assert TelegramAdapter._looks_like_connect_timeout(+ Exception("connect timeout")+ ) is True+ assert TelegramAdapter._looks_like_connect_timeout(+ Exception("connect timed out")+ ) is True++ def test_wrapped_in_cause(self):+ class FakeConnectTimeout(Exception):+ pass+ err = Exception("Timed out")+ err.__cause__ = FakeConnectTimeout("x")+ assert TelegramAdapter._looks_like_connect_timeout(err) is True++ def test_generic_negative(self):+ assert TelegramAdapter._looks_like_connect_timeout(Exception("Timed out")) is False