Skip to content

The agent that grows with you

fix(telegram): try IPv4 API IPs before the dual-stack hostname

kshitijbd5565650d4b
diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.py
index aff16824bc6..84332a69eef 100644
--- a/plugins/platforms/telegram/adapter.py
+++ b/plugins/platforms/telegram/adapter.py
@@ -303,6 +303,7 @@ from plugins.platforms.telegram.telegram_ids import (
normalize_telegram_chat_id,
)
from plugins.platforms.telegram.telegram_network import (
+ SEED_FALLBACK_IPS,
TelegramFallbackTransport,
discover_fallback_ips,
parse_fallback_ip_env,
@@ -4400,12 +4401,13 @@ class TelegramAdapter(BasePlatformAdapter):
except Exception as exc:
logger.warning(
"[%s] Telegram fallback-IP discovery failed after %.0fs; "
- "continuing with the plain api.telegram.org path: %s",
+ "using seed IPv4 Telegram API IPs so a blackholed IPv6 "
+ "hostname path cannot hang initialize() (#87015): %s",
self.name,
discovery_timeout,
_redact_telegram_error_text(exc),
)
- fallback_ips = []
+ fallback_ips = list(SEED_FALLBACK_IPS)
else:
logger.info(
"[%s] Auto-discovered Telegram fallback IPs: %s",
diff --git a/plugins/platforms/telegram/telegram_network.py b/plugins/platforms/telegram/telegram_network.py
index aad93617673..2511438b627 100644
--- a/plugins/platforms/telegram/telegram_network.py
+++ b/plugins/platforms/telegram/telegram_network.py
@@ -38,9 +38,12 @@ _DOH_PROVIDERS: list[dict] = [
},
]
-# Last-resort IPs when DoH is also blocked. These are stable Telegram Bot API
-# endpoints in the 149.154.160.0/20 block (same seed used by OpenClaw).
-_SEED_FALLBACK_IPS: list[str] = ["149.154.166.110", "149.154.167.220"]
+# Last-resort IPv4 Telegram Bot API endpoints in 149.154.160.0/20
+# (same seed used by OpenClaw). Used when DoH is blocked AND as the
+# first-try connect targets so a blackholed IPv6 AAAA for the hostname
+# cannot pin initialize() (#87015).
+SEED_FALLBACK_IPS: list[str] = ["149.154.166.110", "149.154.167.220"]
+_SEED_FALLBACK_IPS = SEED_FALLBACK_IPS # back-compat alias
def _resolve_proxy_url(target_hosts=None) -> str | None:
@@ -76,6 +79,11 @@ class TelegramFallbackTransport(httpx.AsyncBaseTransport):
# Built on demand and discarded on failure — see _reset_fallback.
self._fallbacks: dict[str, httpx.AsyncHTTPTransport] = {}
self._fallback_lock = asyncio.Lock()
+ # ``_has_sticky`` distinguishes "unknown path" from "sticky primary"
+ # (``_sticky_ip is None``). A blackholed IPv6 AAAA for the hostname
+ # can sit in connect() without erroring, so the first request must
+ # try known IPv4 literals BEFORE ``api.telegram.org`` (#87015).
+ self._has_sticky: bool = False
self._sticky_ip: Optional[str] = None
self._sticky_lock = asyncio.Lock()
@@ -116,17 +124,30 @@ class TelegramFallbackTransport(httpx.AsyncBaseTransport):
except Exception as exc: # closing a broken pool must never mask the real error
logger.debug("[Telegram] Error closing fallback transport %s: %s", ip, exc)
+ def _attempt_order(self) -> list[Optional[str]]:
+ """IPv4 literals first; dual-stack hostname last.
+
+ A blackholed IPv6 path to ``api.telegram.org`` never errors — Happy
+ Eyeballs waits on AAAA until the OS TCP timeout, which can pin the
+ event loop so ``_await_with_thread_deadline`` never fires (#87015).
+ Known A-record IPs connect over IPv4 immediately. The hostname is
+ kept as a last resort for IPv6-only networks.
+ """
+ order: list[Optional[str]] = []
+ if self._has_sticky:
+ order.append(self._sticky_ip)
+ for ip in self._fallback_ips:
+ if ip not in order:
+ order.append(ip)
+ if None not in order:
+ order.append(None)
+ return order
+
async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
if request.url.host != _TELEGRAM_API_HOST or not self._fallback_ips:
return await self._primary.handle_async_request(request)
- sticky_ip = self._sticky_ip
- attempt_order: list[Optional[str]] = [sticky_ip] if sticky_ip else [None]
- if sticky_ip:
- attempt_order.append(None) # retry primary DNS after sticky failure
- for ip in self._fallback_ips:
- if ip != sticky_ip:
- attempt_order.append(ip)
+ attempt_order = self._attempt_order()
last_error: Exception | None = None
for ip in attempt_order:
@@ -134,36 +155,40 @@ class TelegramFallbackTransport(httpx.AsyncBaseTransport):
transport = self._primary if ip is None else await self._get_fallback(ip)
try:
response = await transport.handle_async_request(candidate)
- if ip is not None and self._sticky_ip != ip:
+ if not self._has_sticky or self._sticky_ip != ip:
async with self._sticky_lock:
- if self._sticky_ip != ip:
+ if not self._has_sticky or self._sticky_ip != ip:
+ self._has_sticky = True
self._sticky_ip = ip
- logger.warning(
- "[Telegram] Primary api.telegram.org path unreachable; using sticky fallback IP %s",
- ip,
- )
+ if ip is not None:
+ logger.warning(
+ "[Telegram] Using sticky IPv4 Telegram API path %s "
+ "(dual-stack hostname tried last — #87015)",
+ ip,
+ )
return response
except Exception as exc:
last_error = exc
if not _is_retryable_connect_error(exc):
raise
- if ip is not None and ip == self._sticky_ip:
+ if self._has_sticky and ip == self._sticky_ip:
async with self._sticky_lock:
- if self._sticky_ip == ip:
+ if self._has_sticky and self._sticky_ip == ip:
+ self._has_sticky = False
self._sticky_ip = None
logger.warning(
- "[Telegram] Sticky fallback IP %s failed; resetting to primary DNS path",
- ip,
+ "[Telegram] Sticky Telegram path %s failed; "
+ "re-walking IPv4 literals before the hostname",
+ ip if ip is not None else "api.telegram.org",
)
if ip is None:
await self._reset_primary(transport)
logger.warning(
- "[Telegram] Primary api.telegram.org connection failed (%s); trying fallback IPs %s",
+ "[Telegram] Dual-stack api.telegram.org path failed (%s)",
exc,
- ", ".join(self._fallback_ips),
)
continue
- logger.warning("[Telegram] Fallback IP %s failed: %s", ip, exc)
+ logger.warning("[Telegram] IPv4 Telegram API IP %s failed: %s", ip, exc)
await self._reset_fallback(ip)
continue
@@ -298,9 +323,9 @@ async def discover_fallback_ips() -> list[str]:
logger.info(
"DoH discovery yielded no usable IPs (system DNS: %s); using seed fallback IPs %s",
", ".join(system_ips) or "unknown",
- ", ".join(_SEED_FALLBACK_IPS),
+ ", ".join(SEED_FALLBACK_IPS),
)
- return list(_SEED_FALLBACK_IPS)
+ return list(SEED_FALLBACK_IPS)
def _rewrite_request_for_ip(request: httpx.Request, ip: str) -> httpx.Request:
diff --git a/tests/gateway/test_telegram_fallback_pool_release_71593.py b/tests/gateway/test_telegram_fallback_pool_release_71593.py
index d50cd36b96a..1d3bc3033d9 100644
--- a/tests/gateway/test_telegram_fallback_pool_release_71593.py
+++ b/tests/gateway/test_telegram_fallback_pool_release_71593.py
@@ -137,10 +137,13 @@ async def test_failed_primary_pool_is_discarded_and_closed(monkeypatch):
try:
response = await transport.handle_async_request(_telegram_request())
assert response.status_code == 200
- assert len(instances) == 3
- assert instances[0].closed
+ # IPv4-first (#87015): .220 succeeds on the first try, so the
+ # dual-stack hostname pool is never opened and never discarded.
+ # Instances: 1 primary (unused this request) + 1 fallback (.220).
+ assert len(instances) == 2
+ assert not instances[0].closed
assert not instances[1].closed
- assert not instances[2].closed
+ assert transport._sticky_ip == "149.154.167.220"
finally:
await transport.aclose()
diff --git a/tests/gateway/test_telegram_network.py b/tests/gateway/test_telegram_network.py
index 88861946e14..4d9f359daa9 100644
--- a/tests/gateway/test_telegram_network.py
+++ b/tests/gateway/test_telegram_network.py
@@ -10,9 +10,10 @@ servers still accept the request. This is the programmatic equivalent of:
curl --resolve api.telegram.org:443:149.154.167.220 https://api.telegram.org/bot<token>/getMe
-The TelegramFallbackTransport implements this: try the primary (DNS-resolved)
-path first, and on ConnectTimeout / ConnectError fall through to configured
-fallback IPs in order, then "stick" to whichever IP works.
+The TelegramFallbackTransport implements this: try known IPv4 Telegram API
+IPs first (so a blackholed IPv6 AAAA for the hostname cannot hang
+initialize — #87015), then fall through to the dual-stack hostname last,
+and "stick" to whichever path works.
"""
import httpx
@@ -114,10 +115,10 @@ class TestRewriteRequestForIp:
# ═══════════════════════════════════════════════════════════════════════════
class TestFallbackTransport:
- """Primary path fails → try fallback IPs → stick to whichever works."""
+ """IPv4 literals first → hostname last → stick to whichever works."""
@pytest.mark.asyncio
- async def test_falls_back_on_connect_timeout_and_becomes_sticky(self, monkeypatch):
+ async def test_ipv4_literal_tried_before_hostname_and_becomes_sticky(self, monkeypatch):
calls = []
behavior = {"api.telegram.org": "timeout", "149.154.167.220": "ok"}
monkeypatch.setattr(tnet.httpx, "AsyncHTTPTransport", _fake_transport_factory(calls, behavior))
@@ -126,12 +127,11 @@ class TestFallbackTransport:
resp = await transport.handle_async_request(_telegram_request())
assert resp.status_code == 200
+ assert transport._has_sticky is True
assert transport._sticky_ip == "149.154.167.220"
- # First attempt was primary (api.telegram.org), second was fallback
- assert calls[0]["url_host"] == "api.telegram.org"
- assert calls[1]["url_host"] == "149.154.167.220"
- assert calls[1]["host_header"] == "api.telegram.org"
- assert calls[1]["sni_hostname"] == "api.telegram.org"
+ assert [c["url_host"] for c in calls] == ["149.154.167.220"]
+ assert calls[0]["host_header"] == "api.telegram.org"
+ assert calls[0]["sni_hostname"] == "api.telegram.org"
# Second request goes straight to sticky IP
calls.clear()
@@ -153,7 +153,7 @@ class TestFallbackTransport:
transport = tnet.TelegramFallbackTransport(["149.154.167.220", "149.154.167.221"])
- # First request: primary fails → .220 works → becomes sticky
+ # First request: .220 works immediately (IPv4-first) → becomes sticky
await transport.handle_async_request(_telegram_request())
assert transport._sticky_ip == "149.154.167.220"
@@ -163,12 +163,54 @@ class TestFallbackTransport:
resp = await transport.handle_async_request(_telegram_request())
assert resp.status_code == 200
- # After #24511: when sticky fails the transport also resets and
- # re-tries the primary DNS path before falling through to other IPs.
- # Path: sticky (.220) → primary (api.telegram.org) → .221
- assert [c["url_host"] for c in calls] == ["149.154.167.220", "api.telegram.org", "149.154.167.221"]
+ # Sticky .220 fails → remaining IPv4 .221 works. Hostname is last
+ # and is never needed.
+ assert [c["url_host"] for c in calls] == ["149.154.167.220", "149.154.167.221"]
assert transport._sticky_ip == "149.154.167.221"
+ @pytest.mark.asyncio
+ async def test_blackholed_hostname_never_reached_when_ipv4_works(self, monkeypatch):
+ """#87015: a hostname connect that never returns must not run first."""
+ calls = []
+
+ class _HangOnHostname(FakeTransport):
+ async def handle_async_request(self, request):
+ if request.url.host == "api.telegram.org":
+ raise AssertionError(
+ "dual-stack hostname was tried before a working IPv4 literal"
+ )
+ return await super().handle_async_request(request)
+
+ def factory(**kwargs):
+ return _HangOnHostname(calls, {"149.154.167.220": "ok"})
+
+ monkeypatch.setattr(tnet.httpx, "AsyncHTTPTransport", factory)
+ transport = tnet.TelegramFallbackTransport(["149.154.167.220"])
+ resp = await transport.handle_async_request(_telegram_request())
+ assert resp.status_code == 200
+ assert calls[0]["url_host"] == "149.154.167.220"
+
+ def test_attempt_order_is_ipv4_then_hostname(self):
+ transport = tnet.TelegramFallbackTransport(["149.154.167.220", "149.154.166.110"])
+ assert transport._attempt_order() == [
+ "149.154.167.220",
+ "149.154.166.110",
+ None,
+ ]
+
+ @pytest.mark.asyncio
+ async def test_hostname_tried_last_when_ipv4_fails(self, monkeypatch):
+ """IPv6-only / seed-IP-blocked hosts still reach the hostname last."""
+ calls = []
+ behavior = {"149.154.167.220": "timeout", "api.telegram.org": "ok"}
+ monkeypatch.setattr(tnet.httpx, "AsyncHTTPTransport", _fake_transport_factory(calls, behavior))
+ transport = tnet.TelegramFallbackTransport(["149.154.167.220"])
+ resp = await transport.handle_async_request(_telegram_request())
+ assert resp.status_code == 200
+ assert [c["url_host"] for c in calls] == ["149.154.167.220", "api.telegram.org"]
+ assert transport._has_sticky is True
+ assert transport._sticky_ip is None
+
class TestFallbackTransportPassthrough:
"""Requests that don't need fallback behavior."""
diff --git a/tests/gateway/test_telegram_polling_progress.py b/tests/gateway/test_telegram_polling_progress.py
index 1cc85155675..a2176d108d1 100644
--- a/tests/gateway/test_telegram_polling_progress.py
+++ b/tests/gateway/test_telegram_polling_progress.py
@@ -243,8 +243,8 @@ async def test_fallback_disabled_skips_doh_discovery_on_connect(monkeypatch):
@pytest.mark.asyncio
-async def test_fallback_discovery_timeout_falls_back_to_plain_connect(monkeypatch):
- """A stuck DoH fallback lookup must not block Telegram cold connect."""
+async def test_fallback_discovery_timeout_uses_seed_ipv4(monkeypatch):
+ """A stuck DoH lookup must not block connect; seed IPv4 IPs are used instead."""
adapter = _make_adapter()
polling_app = _lifecycle_app()
@@ -263,9 +263,10 @@ async def test_fallback_discovery_timeout_falls_back_to_plain_connect(monkeypatc
monkeypatch.setattr(tg_adapter, "discover_fallback_ips", stuck_discovery)
assert await adapter.connect() is True
- assert "transport" not in (
- builders[0].polling_request.kwargs.get("httpx_kwargs") or {}
- )
+ httpx_kwargs = builders[0].polling_request.kwargs.get("httpx_kwargs") or {}
+ transport = httpx_kwargs.get("transport")
+ assert isinstance(transport, tg_adapter.TelegramFallbackTransport)
+ assert transport._fallback_ips == list(tg_adapter.SEED_FALLBACK_IPS)
await adapter.disconnect()
@@ -300,9 +301,10 @@ async def test_non_finite_fallback_discovery_timeout_uses_finite_default(monkeyp
monkeypatch.setattr(tg_adapter, "_await_with_thread_deadline", deadline)
assert await adapter.connect() is True
- assert "transport" not in (
- builders[0].polling_request.kwargs.get("httpx_kwargs") or {}
- )
+ httpx_kwargs = builders[0].polling_request.kwargs.get("httpx_kwargs") or {}
+ transport = httpx_kwargs.get("transport")
+ assert isinstance(transport, tg_adapter.TelegramFallbackTransport)
+ assert transport._fallback_ips == list(tg_adapter.SEED_FALLBACK_IPS)
await adapter.disconnect()
diff --git a/website/docs/user-guide/messaging/telegram.md b/website/docs/user-guide/messaging/telegram.md
index 993423874b7..5e94c3a2453 100644
--- a/website/docs/user-guide/messaging/telegram.md
+++ b/website/docs/user-guide/messaging/telegram.md
@@ -1137,9 +1137,9 @@ In some restricted networks, `api.telegram.org` may resolve to an IP that is unr
1. If `TELEGRAM_FALLBACK_IPS` is set, those IPs are used directly.
2. Otherwise, the adapter automatically queries **Google DNS** and **Cloudflare DNS** via DNS-over-HTTPS (DoH) to discover alternative IPs for `api.telegram.org`.
-3. IPs returned by DoH that differ from the system DNS result are used as fallbacks.
-4. If DoH is also blocked, a hardcoded seed IP (`149.154.167.220`) is used as a last resort.
-5. Once a fallback IP succeeds, it becomes "sticky" — subsequent requests use it directly without retrying the primary path first.
+3. Known IPv4 Telegram API IPs are tried **before** the dual-stack `api.telegram.org` hostname. A blackholed IPv6 path can sit in `connect()` without erroring, which used to pin the event loop so the 30s init deadline never fired.
+4. If DoH is also blocked or times out, a hardcoded IPv4 seed list (`149.154.166.110`, `149.154.167.220`) is used instead of falling through to the hostname.
+5. Once a path succeeds, it becomes "sticky" — subsequent requests use it directly. The hostname is kept as a last resort for IPv6-only networks.
### Configuration
@@ -1159,7 +1159,7 @@ platforms:
```
:::tip
-You usually don't need to configure this manually. The auto-discovery via DoH handles most restricted-network scenarios. The `TELEGRAM_FALLBACK_IPS` env var is only needed if DoH is also blocked on your network.
+You usually don't need to configure this manually. The auto-discovery via DoH handles most restricted-network scenarios. The `TELEGRAM_FALLBACK_IPS` env var is only needed if DoH is also blocked on your network. If IPv6 is broken on the host, you can also set `network.force_ipv4: true` in `config.yaml` to skip AAAA lookups process-wide.
:::
## Proxy Support