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(http_handler): only replay POST and PATCH when the request never reached the upstream (#46336)

Mateo Wangccc656873d84
diff --git a/litellm/llms/custom_httpx/aiohttp_transport.py b/litellm/llms/custom_httpx/aiohttp_transport.py
index f02540eb657..b8cb183c02f 100644
--- a/litellm/llms/custom_httpx/aiohttp_transport.py
+++ b/litellm/llms/custom_httpx/aiohttp_transport.py
@@ -53,7 +53,7 @@ AIOHTTP_EXC_MAP: Final[dict[type[BaseException], type[Exception]]] = {
aiohttp.ServerFingerprintMismatch: httpx.ProtocolError,
# Network related exceptions
aiohttp.ClientConnectorError: httpx.ConnectError,
- aiohttp.ClientOSError: httpx.ConnectError,
+ aiohttp.ClientOSError: httpx.ReadError,
aiohttp.ClientPayloadError: httpx.ReadError,
# Connection disconnection exceptions
aiohttp.ServerDisconnectedError: httpx.ReadError,
diff --git a/litellm/llms/custom_httpx/http_handler.py b/litellm/llms/custom_httpx/http_handler.py
index 3351d34b16f..cc34b4ff873 100644
--- a/litellm/llms/custom_httpx/http_handler.py
+++ b/litellm/llms/custom_httpx/http_handler.py
@@ -848,12 +848,13 @@ class AsyncHTTPHandler:
_anchor_handler_to(response, self)
response.raise_for_status()
return response
- except (httpx.RemoteProtocolError, httpx.ConnectError):
+ except httpx.ConnectError:
# Retry the request with a new session if there is a connection error
new_client: Final = self.create_client(timeout=timeout, event_hooks=self.event_hooks)
try:
- return await self.single_connection_post_request(
+ return await self.single_connection_request(
url=url,
+ method="POST",
client=new_client,
data=data,
json=json,
@@ -989,12 +990,13 @@ class AsyncHTTPHandler:
response: Final = await self.client.send(req)
response.raise_for_status()
return response
- except (httpx.RemoteProtocolError, httpx.ConnectError):
+ except httpx.ConnectError:
# Retry the request with a new session if there is a connection error
new_client: Final = self.create_client(timeout=timeout, event_hooks=self.event_hooks)
try:
- return await self.single_connection_post_request(
+ return await self.single_connection_request(
url=url,
+ method="PATCH",
client=new_client,
data=data,
json=json,
@@ -1060,8 +1062,9 @@ class AsyncHTTPHandler:
# Retry the request with a new session if there is a connection error
new_client: Final = self.create_client(timeout=timeout, event_hooks=self.event_hooks)
try:
- return await self.single_connection_post_request(
+ return await self.single_connection_request(
url=url,
+ method="DELETE",
client=new_client,
data=data,
json=json,
@@ -1077,9 +1080,10 @@ class AsyncHTTPHandler:
except Exception as e:
raise e
- async def single_connection_post_request(
+ async def single_connection_request(
self,
url: str,
+ method: str,
client: httpx.AsyncClient,
data: dict | str | bytes | None = None,
json: dict | None = None,
@@ -1089,7 +1093,7 @@ class AsyncHTTPHandler:
content: _RequestContent | None = None,
):
"""
- Making POST request for a single connection client.
+ Making request for a single connection client.
Used for retrying connection client errors.
"""
@@ -1097,7 +1101,7 @@ class AsyncHTTPHandler:
request_data, request_content = _prepare_request_data_and_content(data, content)
req: Final = client.build_request(
- "POST",
+ method,
url,
data=request_data,
json=json,
diff --git a/tests/unit/llms/custom_httpx/test_aiohttp_transport.py b/tests/unit/llms/custom_httpx/test_aiohttp_transport.py
index 7c44d61451c..0765371dc4a 100644
--- a/tests/unit/llms/custom_httpx/test_aiohttp_transport.py
+++ b/tests/unit/llms/custom_httpx/test_aiohttp_transport.py
@@ -2,6 +2,7 @@ import aiohttp as aiohttp_aiohttp_handler, asyncio, importlib, litellm
import concurrent.futures
import socket
import sys
+import struct
from typing import Final
import aiohttp
@@ -1273,3 +1274,39 @@ async def test_refused_connection_maps_to_httpx_connect_error(
assert isinstance(cause, aiohttp_aiohttp_handler.ClientConnectorError)
assert cause.ssl is expected_ssl
assert (cause.host, cause.port) == ("127.0.0.1", port)
+
+
+async def test_reset_after_request_is_not_replayed(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("NO_PROXY", "127.0.0.1")
+ monkeypatch.setenv("no_proxy", "127.0.0.1")
+ received_requests: Final[list[bytes]] = [] # mutable-ok: local server captures requests
+
+ async def reset_after_request(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
+ headers: Final = await reader.readuntil(b"\r\n\r\n")
+ content_length: Final = next(
+ (
+ int(header.split(b":", 1)[1])
+ for header in headers.split(b"\r\n")
+ if header.lower().startswith(b"content-length:")
+ ),
+ 0,
+ )
+ await reader.readexactly(content_length)
+ received_requests.append(headers)
+ transport_socket: Final = writer.get_extra_info("socket")
+ assert transport_socket is not None
+ transport_socket.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0))
+ writer.transport.abort()
+
+ server: Final = await asyncio.start_server(reset_after_request, "127.0.0.1", 0)
+ port: Final = server.sockets[0].getsockname()[1]
+ handler: Final = AsyncHTTPHandler()
+ try:
+ async with server:
+ with pytest.raises(httpx.ReadError):
+ await handler.post(f"http://127.0.0.1:{port}/", content=b'{"a":1}')
+
+ assert len(received_requests) == 1
+ finally:
+ await handler.close()
diff --git a/tests/unit/llms/custom_httpx/test_http_handler.py b/tests/unit/llms/custom_httpx/test_http_handler.py
index b9dbf7f9359..bd4ed4c99cc 100644
--- a/tests/unit/llms/custom_httpx/test_http_handler.py
+++ b/tests/unit/llms/custom_httpx/test_http_handler.py
@@ -1476,13 +1476,13 @@ class _RetryClientHandler(AsyncHTTPHandler):
@pytest.mark.asyncio
@pytest.mark.parametrize("method", ["post", "put", "patch", "delete"])
async def test_connection_error_retry_forwards_content(method: str):
- captured: list[bytes] = [] # mutable-ok: async closure capture buffer
+ captured: Final[list[tuple[str, bytes]]] = [] # mutable-ok: async closure capture buffer
async def raise_connection_error(request: httpx.Request) -> httpx.Response:
- raise httpx.RemoteProtocolError("connection dropped", request=request)
+ raise httpx.ConnectError("connection dropped", request=request)
async def capture_and_succeed(request: httpx.Request) -> httpx.Response:
- captured.append(request.content)
+ captured.append((request.method, request.content))
return httpx.Response(200, request=request)
first: Final = httpx.AsyncClient(transport=httpx.MockTransport(raise_connection_error))
@@ -1490,10 +1490,59 @@ async def test_connection_error_retry_forwards_content(method: str):
async with first, retry:
handler: Final = _RetryClientHandler(first=first, retry=retry)
- body = b'{"post": ["run1"]}'
+ body: Final = b'{"post": ["run1"]}'
await getattr(handler, method)("https://api.example.com/runs/batch", content=body)
- assert captured == [body], "the retried request must carry the same content= body"
+ assert captured == [(method.upper(), body)]
+ await handler.close()
+
+
[email protected]("method", ["post", "patch"])
+async def test_disconnect_after_send_is_not_replayed(method: str) -> None:
+ retried_requests: Final[list[httpx.Request]] = [] # mutable-ok: async closure capture buffer
+
+ async def raise_disconnect(request: httpx.Request) -> httpx.Response:
+ raise httpx.RemoteProtocolError("connection dropped after send", request=request)
+
+ async def capture_retry(request: httpx.Request) -> httpx.Response:
+ retried_requests.append(request)
+ return httpx.Response(200, request=request)
+
+ first: Final = httpx.AsyncClient(transport=httpx.MockTransport(raise_disconnect))
+ retry: Final = httpx.AsyncClient(transport=httpx.MockTransport(capture_retry))
+ async with first, retry:
+ handler: Final = _RetryClientHandler(first=first, retry=retry)
+
+ with pytest.raises(httpx.RemoteProtocolError):
+ await getattr(handler, method)("https://api.example.com/runs/batch", content=b'{"a":1}')
+
+ assert retried_requests == []
+ await handler.close()
+
+
[email protected]("method", ["put", "delete"])
+async def test_idempotent_disconnect_is_replayed(method: str) -> None:
+ captured: Final[list[tuple[str, bytes]]] = [] # mutable-ok: async closure capture buffer
+
+ async def raise_disconnect(request: httpx.Request) -> httpx.Response:
+ raise httpx.RemoteProtocolError("connection dropped after send", request=request)
+
+ async def capture_retry(request: httpx.Request) -> httpx.Response:
+ captured.append((request.method, request.content))
+ return httpx.Response(200, request=request)
+
+ first: Final = httpx.AsyncClient(transport=httpx.MockTransport(raise_disconnect))
+ retry: Final = httpx.AsyncClient(transport=httpx.MockTransport(capture_retry))
+ async with first, retry:
+ handler: Final = _RetryClientHandler(first=first, retry=retry)
+
+ body: Final = b'{"a":1}'
+ response: Final = await getattr(handler, method)("https://api.example.com/runs/batch", content=body)
+
+ assert response.status_code == 200
+ assert captured == [(method.upper(), body)]
await handler.close()