Skip to content

The agent that grows with you

fix(telegram): prevent Windows long-poll socket reuse deadlock

joaomarcosb02b7122f849
diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.py
index 6dbc5886505..f6dc8bc8b73 100644
--- a/plugins/platforms/telegram/adapter.py
+++ b/plugins/platforms/telegram/adapter.py
@@ -4594,8 +4594,18 @@ class TelegramAdapter(BasePlatformAdapter):
max_keepalive_connections=_base_limits.max_keepalive_connections,
keepalive_expiry=_base_limits.keepalive_expiry,
)
+ # A long-poll request is continuously active, so keepalive
+ # expiry cannot protect it from a server-side connection close.
+ # Never hand getUpdates a pooled socket from a previous poll;
+ # ordinary Bot API requests retain the shared reusable pool.
+ _updates_limits = _httpx.Limits(
+ max_connections=request_kwargs["connection_pool_size"],
+ max_keepalive_connections=0,
+ keepalive_expiry=_base_limits.keepalive_expiry,
+ )
else: # pragma: no cover — httpx always present alongside PTB
_pool_limits = None
+ _updates_limits = None
def _with_limits(httpx_kwargs: Optional[dict] = None) -> dict:
"""Merge tuned keepalive limits into httpx client kwargs.
@@ -4673,6 +4683,9 @@ class TelegramAdapter(BasePlatformAdapter):
if _pool_limits is not None:
_transport_kwargs["limits"] = _pool_limits
_transport_kwargs["socket_options"] = tcp_keepalive_socket_options()
+ _updates_transport_kwargs = dict(_transport_kwargs)
+ if _updates_limits is not None:
+ _updates_transport_kwargs["limits"] = _updates_limits
request = HTTPXRequest(
**request_kwargs,
httpx_kwargs={
@@ -4685,7 +4698,8 @@ class TelegramAdapter(BasePlatformAdapter):
**request_kwargs,
httpx_kwargs={
"transport": TelegramFallbackTransport(
- fallback_ips, **_transport_kwargs
+ fallback_ips,
+ **_updates_transport_kwargs,
)
},
)
@@ -4695,14 +4709,16 @@ class TelegramAdapter(BasePlatformAdapter):
**request_kwargs, proxy=proxy_url, httpx_kwargs=_with_limits()
)
get_updates_request = HTTPXRequest(
- **request_kwargs, proxy=proxy_url, httpx_kwargs=_with_limits()
+ **request_kwargs,
+ proxy=proxy_url,
+ httpx_kwargs={"limits": _updates_limits},
)
else:
if disable_fallback:
logger.info("[%s] Telegram fallback-IP transport disabled via env", self.name)
request = HTTPXRequest(**request_kwargs, httpx_kwargs=_with_limits())
get_updates_request = HTTPXRequest(
- **request_kwargs, httpx_kwargs=_with_limits()
+ **request_kwargs, httpx_kwargs={"limits": _updates_limits}
)
get_updates_request = self._instrument_polling_request(get_updates_request)
diff --git a/tests/gateway/test_telegram_closewait_limits_31599.py b/tests/gateway/test_telegram_closewait_limits_31599.py
index ca1bf0e7c56..33c69295070 100644
--- a/tests/gateway/test_telegram_closewait_limits_31599.py
+++ b/tests/gateway/test_telegram_closewait_limits_31599.py
@@ -135,12 +135,21 @@ def _assert_keepalive_tight(instances):
assert limits.max_connections is not None and limits.max_connections > 0
+def _assert_updates_pool_never_reuses(instance):
+ """The long-poll pool must not reuse server-closed connections (#87057)."""
+ limits = instance.kwargs.get("httpx_kwargs", {}).get("limits")
+ assert isinstance(limits, httpx.Limits)
+ assert limits.max_keepalive_connections == 0
+ assert limits.max_connections == 512
+
+
def test_proxy_branch_general_pool_has_tight_keepalive(monkeypatch):
"""The proxy path the #31599 reporter hit must wire tuned limits."""
instances = _drive_connect(monkeypatch, proxy_url="http://127.0.0.1:9/")
# Both the general request pool and the get_updates pool are built here.
assert len(instances) >= 2
- _assert_keepalive_tight(instances)
+ _assert_keepalive_tight(instances[:1])
+ _assert_updates_pool_never_reuses(instances[1])
# Sanity: the proxy was actually threaded through (we're on the proxy branch).
assert any(inst.kwargs.get("proxy") == "http://127.0.0.1:9/" for inst in instances)
@@ -156,7 +165,7 @@ def test_fallback_branch_forwards_tuned_limits_to_inner_transports(monkeypatch):
)
assert len(instances) >= 2
- for instance in instances:
+ for index, instance in enumerate(instances):
transport = instance.kwargs["httpx_kwargs"]["transport"]
assert isinstance(transport, tg_adapter.TelegramFallbackTransport)
limits = transport._transport_kwargs["limits"]
@@ -172,6 +181,10 @@ def test_fallback_branch_forwards_tuned_limits_to_inner_transports(monkeypatch):
and opt[2] == 1
for opt in sock_opts
)
+ if index == 0:
+ assert limits.max_keepalive_connections >= 1
+ else:
+ assert limits.max_keepalive_connections == 0
for instance in instances:
asyncio.run(instance.kwargs["httpx_kwargs"]["transport"].aclose())
diff --git a/tests/gateway/test_telegram_network_reconnect.py b/tests/gateway/test_telegram_network_reconnect.py
index c749bf36f4f..506bbedcbe4 100644
--- a/tests/gateway/test_telegram_network_reconnect.py
+++ b/tests/gateway/test_telegram_network_reconnect.py
@@ -1026,6 +1026,7 @@ async def test_drain_rebuild_does_not_block_loop_or_leak_cleanup_task(monkeypatc
async def aclose(self):
# Simulate httpcore cleanup that absorbs cancellation for a while.
+ # The detached cleanup must not stay registered forever.
for _ in range(20):
try:
await asyncio.sleep(0.01)
@@ -1046,6 +1047,7 @@ async def test_drain_rebuild_does_not_block_loop_or_leak_cleanup_task(monkeypatc
await asyncio.Event().wait()
async def initialize(self):
+ # Mirrors PTB: initialize() does nothing while is_closed is false.
if self._client.is_closed:
self._client = self._build_client()