Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

fix(aiohttp_transport): map transport-internal CancelledError to a retryable ConnectError (#39240)

devin-ai-integration[bot]c00197515208
diff --git a/litellm/llms/custom_httpx/aiohttp_transport.py b/litellm/llms/custom_httpx/aiohttp_transport.py
index b6586481fd3..73adf9c7455 100644
--- a/litellm/llms/custom_httpx/aiohttp_transport.py
+++ b/litellm/llms/custom_httpx/aiohttp_transport.py
@@ -3,6 +3,7 @@ import concurrent.futures
import contextlib
import os
import ssl
+import sys
import typing
import urllib.request
from collections.abc import Callable, Generator
@@ -75,10 +76,22 @@ except ImportError:
pass
+def _current_task_is_cancelling() -> bool:
+ task: Final = asyncio.current_task()
+ if task is None or sys.version_info < (3, 11):
+ return True
+ return task.cancelling() > 0
+
+
@contextlib.contextmanager
def map_aiohttp_exceptions() -> Generator[None, None, None]:
try:
yield
+ except asyncio.CancelledError as exc:
+ # a closing connector cancels its shielded DNS task; that surfaces here without the request task being cancelled
+ if _current_task_is_cancelling():
+ raise
+ raise httpx.ConnectError("aiohttp transport cancelled the request internally") from exc
except Exception as exc:
mapped_exc: type[Exception] | None = None
diff --git a/tests/test_litellm/llms/custom_httpx/test_aiohttp_transport.py b/tests/test_litellm/llms/custom_httpx/test_aiohttp_transport.py
index 4c92c52d556..7509e35e3f7 100644
--- a/tests/test_litellm/llms/custom_httpx/test_aiohttp_transport.py
+++ b/tests/test_litellm/llms/custom_httpx/test_aiohttp_transport.py
@@ -1,7 +1,11 @@
import asyncio
import concurrent.futures
+import socket
+import sys
+from typing import Final
import aiohttp
+import aiohttp.abc
import aiohttp.client_exceptions
import aiohttp.http_exceptions
import httpx
@@ -1140,3 +1144,55 @@ async def test_stopped_loop_session_disposed_synchronously_on_recycle():
finally:
await new_session.close()
result["loop"].close()
+
+
+class _CancellingResolver(aiohttp.abc.AbstractResolver):
+ """Cancels the given task (or, by default, aiohttp's shielded DNS child task) mid-lookup."""
+
+ def __init__(self, task_to_cancel: "asyncio.Task[object] | None" = None):
+ self._task_to_cancel: Final = task_to_cancel
+
+ async def resolve(
+ self, host: str, port: int = 0, family: socket.AddressFamily = socket.AF_INET
+ ) -> list[aiohttp.abc.ResolveResult]:
+ target: Final = self._task_to_cancel or asyncio.current_task()
+ assert target is not None
+ target.cancel()
+ await asyncio.sleep(0)
+ raise OSError("resolver finished after the task was cancelled")
+
+ async def close(self) -> None:
+ return None
+
+
+ sys.version_info < (3, 11), reason="Task.cancelling() is needed to tell the two cancellations apart"
+)
+async def test_internal_dns_cancellation_maps_to_connect_error():
+ """A CancelledError the request task never asked for must surface as a mapped httpx transport error."""
+ session = aiohttp.ClientSession(connector=aiohttp.TCPConnector(resolver=_CancellingResolver()))
+ transport = LiteLLMAiohttpTransport(client=session)
+ try:
+ with pytest.raises(httpx.ConnectError):
+ await transport.handle_async_request(httpx.Request("GET", "http://example.invalid/"))
+ current = asyncio.current_task()
+ assert current is not None and current.cancelling() == 0
+ finally:
+ await transport.aclose()
+
+
+async def test_genuine_request_cancellation_still_propagates():
+ """Cancelling the request task itself (client disconnect, shutdown) must still propagate unmapped."""
+ current = asyncio.current_task()
+ assert current is not None
+ session = aiohttp.ClientSession(connector=aiohttp.TCPConnector(resolver=_CancellingResolver(current)))
+ transport = LiteLLMAiohttpTransport(client=session)
+ try:
+ with pytest.raises(asyncio.CancelledError):
+ await transport.handle_async_request(httpx.Request("GET", "http://example.invalid/"))
+ finally:
+ if sys.version_info >= (3, 11):
+ current.uncancel()
+ await transport.aclose()