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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(s3_v2): bound each upload attempt, add jitter, retry 429 and transport errors in the call (#46340)
ryan-crabbe-berri6e0f0f7adb30
diff --git a/litellm/constants.py b/litellm/constants.pyindex aed2b04b16b..9d18fe5489d 100644--- a/litellm/constants.py+++ b/litellm/constants.py@@ -93,6 +93,7 @@ DEFAULT_S3_FLUSH_INTERVAL_SECONDS: Final = int(os.getenv("DEFAULT_S3_FLUSH_INTERDEFAULT_S3_BATCH_SIZE: Final = int(os.getenv("DEFAULT_S3_BATCH_SIZE", 512))DEFAULT_S3_MAX_CONCURRENT_UPLOADS: Final = int(os.getenv("DEFAULT_S3_MAX_CONCURRENT_UPLOADS", "16"))DEFAULT_S3_MAX_ADAPTIVE_CONCURRENCY: Final = get_env_int("DEFAULT_S3_MAX_ADAPTIVE_CONCURRENCY", 200)+S3_UPLOAD_ATTEMPT_TIMEOUT_SECONDS: Final = get_env_int_in_range("S3_UPLOAD_ATTEMPT_TIMEOUT_SECONDS", 30, 1, 3600)# https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-keys.htmlMAX_S3_OBJECT_KEY_BYTES: Final = 1024S3_BOUNDED_OBJECT_KEY_HEAD_BYTES: Final = 64diff --git a/litellm/integrations/s3_v2.py b/litellm/integrations/s3_v2.pyindex 47d9b1c7b64..0b7a2609bcb 100644--- a/litellm/integrations/s3_v2.py+++ b/litellm/integrations/s3_v2.py@@ -10,13 +10,14 @@ import asyncioimport contextvarsimport loggingimport os+import randomimport reimport timefrom collections.abc import Awaitable, Callable, Mappingfrom dataclasses import dataclassfrom datetime import datetime, timezonefrom functools import partial-from typing import TYPE_CHECKING, Final, Literal, cast+from typing import TYPE_CHECKING, Final, Literal, TypeAlias, castfrom urllib.parse import quotefrom uuid import uuid4@@ -30,7 +31,9 @@ from litellm.constants import (DEFAULT_S3_MAX_ADAPTIVE_CONCURRENCY,DEFAULT_S3_MAX_CONCURRENT_UPLOADS,S3_PARTITION_GRANULARITY_ENV_VAR,+ S3_UPLOAD_ATTEMPT_TIMEOUT_SECONDS,)+from litellm.exceptions import Timeout as LiteLLMTimeoutfrom litellm.integrations.adaptive_concurrency import AdaptiveConcurrencyLimiter, PutSamplefrom litellm.integrations.s3 import (get_s3_object_download_filename,@@ -79,8 +82,13 @@ _TERMINAL_ERROR_CODES: Final = frozenset(})_BODY_CODED_STATUSES: Final = frozenset({400, 403})-_RETRYABLE_STATUSES: Final = frozenset({403, 500, 503})+_RETRYABLE_STATUSES: Final = frozenset({403, 429, 500, 503})_S3_ERROR_CODE: Final = re.compile(r"<Code>([^<]+)</Code>")+_TRANSIENT_ERRORS: Final = (httpx.TransportError, LiteLLMTimeout)+_UPLOAD_ATTEMPTS: Final = 3+_UPLOAD_ATTEMPT_TIMEOUT: Final = httpx.Timeout(S3_UPLOAD_ATTEMPT_TIMEOUT_SECONDS)++PutOutcome: TypeAlias = httpx.Response | Exception@dataclass(frozen=True, slots=True)@@ -105,6 +113,35 @@ def _s3_key_parent(s3_object_key: str) -> str:return s3_object_key.rsplit("/", 1)[0] if "/" in s3_object_key else ""+def _backoff_seconds(attempt: int) -> float:+ return (1 << attempt) * (0.5 + random.random())+++def _log_retry(level: int, attempt: int, reason: str, wait: float, s3_object_key: str) -> None:+ verbose_logger.log(+ level,+ "S3 upload attempt %s/%s failed with %s, retrying in %.2fs key=%s",+ attempt + 1,+ _UPLOAD_ATTEMPTS,+ reason,+ wait,+ s3_object_key,+ )+++def _response_or_raise(outcome: PutOutcome) -> httpx.Response:+ if isinstance(outcome, Exception):+ raise outcome+ outcome.raise_for_status()+ return outcome+++def _throttled(outcome: PutOutcome) -> bool:+ if isinstance(outcome, Exception):+ return True+ return outcome.status_code in (429, 503) or _s3_error_code(outcome) == "SlowDown"++class S3BatchUploadError(Exception):def __init__(self, failed: int, total: int) -> None:self.failed = failed@@ -566,7 +603,7 @@ class S3Logger(CustomBatchLogger, BaseAWSLLM):url: Final = self._build_object_url(batch_logging_element.s3_object_key)- async def signed_put(prepared: _PreparedPut) -> httpx.Response:+ async def signed_put(prepared: _PreparedPut) -> PutOutcome:credentials: Final = await asyncified_get_credentials(aws_access_key_id=self.s3_aws_access_key_id,aws_secret_access_key=self.s3_aws_secret_access_key,@@ -582,34 +619,16 @@ class S3Logger(CustomBatchLogger, BaseAWSLLM):self._sign_put, credentials, url, prepared.json_string, prepared.headers)try:- return await self.async_httpx_client.put(url, data=prepared.json_string, headers=signed_headers)+ return await self.async_httpx_client.put(+ url, data=prepared.json_string, headers=signed_headers, timeout=_UPLOAD_ATTEMPT_TIMEOUT+ )except httpx.HTTPStatusError as error:return error.response+ except _TRANSIENT_ERRORS as error:+ return error- max_retries: Final = 3prepared: Final = self._prepare_put(batch_logging_element)- for attempt in range(max_retries):- response = await self._recorded_put(partial(signed_put, prepared))- if (- response.status_code in _RETRYABLE_STATUSES- and not (self.s3_drop_on_terminal_error and _is_terminal(response))- and attempt < max_retries - 1- ):- wait_time = 1 << attempt # 1s, 2s- verbose_logger.log(- logging.DEBUG if _in_flush.get() else logging.WARNING,- "S3 upload returned %s, retrying in %ss (attempt %s/%s) key=%s",- response.status_code,- wait_time,- attempt + 1,- max_retries,- batch_logging_element.s3_object_key,- )- self._flush_retries += 1- await asyncio.sleep(wait_time)- continue- response.raise_for_status()- break+ await self._put_with_retries(partial(signed_put, prepared), batch_logging_element.s3_object_key)except Exception as e:verbose_logger.exception("Error uploading to s3: %s", e)self.handle_callback_failure(callback_name="S3Logger")@@ -678,9 +697,13 @@ class S3Logger(CustomBatchLogger, BaseAWSLLM):)dropped: Final = len(failed) - len(requeued)if dropped:+ terminal: Final = sum(1 for _, outcome in failed if outcome == "dropped")verbose_logger.warning(- "s3 logging: %s uploads dropped (terminal or retrying longer than s3_max_retry_age_seconds=%s)",+ "s3 logging: %s uploads dropped this flush: %s rejected as terminal by S3, "+ "%s retrying longer than s3_max_retry_age_seconds=%s",dropped,+ terminal,+ dropped - terminal,self.s3_max_retry_age_seconds,)if not requeued:@@ -728,22 +751,46 @@ class S3Logger(CustomBatchLogger, BaseAWSLLM):return "dropped"return "retry"- async def _recorded_put(self, signed_put: Callable[[], Awaitable[httpx.Response]]) -> httpx.Response:+ async def _recorded_put(self, signed_put: Callable[[], Awaitable[PutOutcome]]) -> PutOutcome:+ outcome: Final = await signed_put()limiter: Final = self._upload_limiter- adaptive: Final = limiter if isinstance(limiter, AdaptiveConcurrencyLimiter) else None- try:- response: Final = await signed_put()- except Exception:- if adaptive is not None:- adaptive.record(PutSample(throttled=True))- raise- if adaptive is not None:- adaptive.record(- PutSample(- throttled=response.status_code in (429, 503) or _s3_error_code(response) == "SlowDown",- )- )- return response+ if isinstance(limiter, AdaptiveConcurrencyLimiter):+ limiter.record(PutSample(throttled=_throttled(outcome)))+ return outcome++ def _retry_reason(self, outcome: PutOutcome) -> str | None:+ if isinstance(outcome, Exception):+ return type(outcome).__name__+ if outcome.status_code not in _RETRYABLE_STATUSES:+ return None+ if self.s3_drop_on_terminal_error and _is_terminal(outcome):+ return None+ return str(outcome.status_code)++ async def _put_with_retries(+ self, signed_put: Callable[[], Awaitable[PutOutcome]], s3_object_key: str+ ) -> httpx.Response:+ for attempt in range(_UPLOAD_ATTEMPTS - 1):+ outcome = await self._recorded_put(signed_put)+ reason = self._retry_reason(outcome)+ if reason is None:+ return _response_or_raise(outcome)+ wait = _backoff_seconds(attempt)+ _log_retry(logging.DEBUG if _in_flush.get() else logging.WARNING, attempt, reason, wait, s3_object_key)+ self._flush_retries += 1+ await asyncio.sleep(wait)+ return _response_or_raise(await self._recorded_put(signed_put))++ def _sync_put_with_retries(self, signed_put: Callable[[], PutOutcome], s3_object_key: str) -> httpx.Response:+ for attempt in range(_UPLOAD_ATTEMPTS - 1):+ outcome = signed_put()+ reason = self._retry_reason(outcome)+ if reason is None:+ return _response_or_raise(outcome)+ wait = _backoff_seconds(attempt)+ _log_retry(logging.WARNING, attempt, reason, wait, s3_object_key)+ time.sleep(wait)+ return _response_or_raise(signed_put())def _batch_file_elements(self, batch: tuple[s3BatchLoggingElement, ...]) -> tuple[s3BatchLoggingElement, ...]:now: Final = datetime.now(timezone.utc)@@ -879,7 +926,7 @@ class S3Logger(CustomBatchLogger, BaseAWSLLM):params=({"ssl_verify": self.s3_verify} if self.s3_verify is not None else None))- def signed_put(prepared_put: _PreparedPut) -> httpx.Response:+ def signed_put(prepared_put: _PreparedPut) -> PutOutcome:credentials: Final = self.get_credentials(aws_access_key_id=self.s3_aws_access_key_id,aws_secret_access_key=self.s3_aws_secret_access_key,@@ -887,29 +934,14 @@ class S3Logger(CustomBatchLogger, BaseAWSLLM):aws_region_name=self.s3_region_name,)signed_headers: Final = self._sign_put(credentials, url, prepared_put.json_string, prepared_put.headers)- return httpx_client.put(url, data=prepared_put.json_string, headers=signed_headers)-- max_retries: Final = 3- for attempt in range(max_retries):- response = signed_put(prepared)- if (- response.status_code in _RETRYABLE_STATUSES- and not (self.s3_drop_on_terminal_error and _is_terminal(response))- and attempt < max_retries - 1- ):- wait_time = 1 << attempt # 1s, 2s- verbose_logger.warning(- "S3 upload returned %s, retrying in %ss (attempt %s/%s) key=%s",- response.status_code,- wait_time,- attempt + 1,- max_retries,- batch_logging_element.s3_object_key,+ try:+ return httpx_client.put(+ url, data=prepared_put.json_string, headers=signed_headers, timeout=_UPLOAD_ATTEMPT_TIMEOUT)- time.sleep(wait_time)- continue- response.raise_for_status()- break+ except _TRANSIENT_ERRORS as error:+ return error++ self._sync_put_with_retries(partial(signed_put, prepared), batch_logging_element.s3_object_key)except Exception as e:verbose_logger.exception("Error uploading to s3: %s", e)self.handle_callback_failure(callback_name="S3Logger")diff --git a/tests/integration/observability/test_s3_v2_upload_fanout.py b/tests/integration/observability/test_s3_v2_upload_fanout.pyindex ead1e5b028b..54e35d993e6 100644--- a/tests/integration/observability/test_s3_v2_upload_fanout.py+++ b/tests/integration/observability/test_s3_v2_upload_fanout.py@@ -16,6 +16,7 @@ from _s3_v2_support import RecordingS3Sink, collect_payloadsfrom _s3_v2_support import s3_config as _recording_s3_configfrom integration._support.client import Gateway, JsonValue, eventuallyfrom integration._support.process import owned_proxy, owned_proxy_process+from integration._support.timing import assert_enforced_withinfrom integration._support.wire import Reply, Request, Wire, wire_serverBUCKET: Final = "integration-bucket"@@ -473,7 +474,7 @@ def test_s3_v2_aged_out_object_is_dropped_next_to_delivered_siblings(gateway: Ga_send(owned.gateway, model, key, f"{marker}-trigger")eventually(lambda: owned.log.read_text(),- lambda text: "retrying longer than s3_max_retry_age_seconds=1)" in text,+ lambda text: "0 rejected as terminal by S3, 1 retrying longer than s3_max_retry_age_seconds=1" in text,seconds=60,)exhausted: Final = sink.rejected_attempts@@ -565,30 +566,27 @@ def test_s3_v2_retry_age_zero_keeps_aged_object_queued(gateway: Gateway, tmp_pat)-def test_s3_v2_throttled_429_object_is_put_once_per_flush(gateway: Gateway, tmp_path: Path) -> None:+def test_s3_v2_throttled_429_object_backs_off_in_call_and_lands_once_cleared(gateway: Gateway, tmp_path: Path) -> None:marker: Final = "s3throttle" + uuid.uuid4().hex[:8]sink: Final = RejectingS3Sink(reject_marker=f"{marker}-throttled", reject_status=429, reject_code="TooManyRequests")with wire_server(_chat_reply) as provider, wire_server(sink.respond) as bucket:config: Final = _s3_config(tmp_path, bucket.url, {"s3_batch_file_upload": False})with (- owned_proxy(gateway, tmp_path, {"DEFAULT_S3_FLUSH_INTERVAL_SECONDS": "2"}, config=config) as candidate,+ owned_proxy(gateway, tmp_path, {"DEFAULT_S3_FLUSH_INTERVAL_SECONDS": "10"}, config=config) as candidate,candidate.scenario() as scenario,):model: Final = scenario.model(api_base=provider.url + "/v1", api_key="synthetic-provider-key")key: Final = scenario.key(models=[model])_send(candidate, model, key, f"{marker}-throttled")- _send_and_wait_until_landed(candidate, model, key, sink, f"{marker}-sibling")- _send_and_wait_until_landed(candidate, model, key, sink, f"{marker}-second-flush")- _send_and_wait_until_landed(candidate, model, key, sink, f"{marker}-third-flush")+ eventually(lambda: sink.rejected_attempts, lambda attempts: attempts >= 3, seconds=60)sink.reject_until = time.time()eventually(sink.landed_ids, lambda landed: f"{marker}-throttled" in landed, seconds=60)- assert sum(1 for r in provider.drain() if r.method == "POST") == 4- times: Final = tuple(sink.rejected_times)- gaps: Final = tuple(round(later - earlier, 3) for earlier, later in zip(times, times[1:]))- assert len(times) >= 3 and min(gaps) >= 1.5, (- f"PUTs for a 429 object ran {gaps} apart; the 2 s flush interval allows exactly one attempt per flush "- "because 429 is not an in-call retry status"+ assert sum(1 for r in provider.drain() if r.method == "POST") == 1+ first_backoff, second_backoff = (+ later - earlier for earlier, later in zip(sink.rejected_times[:2], sink.rejected_times[1:3]))+ assert_enforced_within(first_backoff, configured=1.5, slack=2.0, not_before=0.5)+ assert_enforced_within(second_backoff, configured=3.0, slack=2.0, not_before=1.0)def test_s3_v2_default_config_retries_access_denied_and_every_event_lands(gateway: Gateway, tmp_path: Path) -> None:diff --git a/tests/unit/integrations/test_s3_v2.py b/tests/unit/integrations/test_s3_v2.pyindex 8449eae7bf4..fcd2c5673af 100644--- a/tests/unit/integrations/test_s3_v2.py+++ b/tests/unit/integrations/test_s3_v2.py@@ -13,7 +13,7 @@ from contextvars import Contextfrom datetime import datetimefrom pathlib import Pathfrom typing import Final-from unittest.mock import AsyncMock, MagicMock, call, patch+from unittest.mock import AsyncMock, MagicMock, patchimport httpximport pytest@@ -28,7 +28,7 @@ from litellm.types.integrations.s3_v2 import s3BatchLoggingElementfrom litellm.types.utils import StandardLoggingPayloadfrom collections import defaultdictfrom litellm._logging import verbose_logger-from litellm.constants import LOGGING_WORKER_MAX_TIME_PER_COROUTINE+from litellm.constants import LOGGING_WORKER_MAX_TIME_PER_COROUTINE, S3_UPLOAD_ATTEMPT_TIMEOUT_SECONDSfrom litellm.litellm_core_utils.logging_worker import GLOBAL_LOGGING_WORKERfrom tests._vcr_conftest_common import install_live_call_probe, record_vcr_outcome@@ -36,6 +36,14 @@ _real_sleep: Final = asyncio.sleep_NOW: Final = 1_000_000.0+def _assert_jittered_backoff(sleep_mock: MagicMock, retries: int) -> None:+ """Each retry waits a jittered exponential backoff: attempt n sleeps somewhere in [2**n / 2, 2**n * 1.5)."""+ waits: Final = [sleep_call.args[0] for sleep_call in sleep_mock.call_args_list]+ assert len(waits) == retries, waits+ for attempt, wait in enumerate(waits):+ assert (1 << attempt) * 0.5 <= wait < (1 << attempt) * 1.5, (attempt, wait)++class TestS3V2UnitTests:"""Test that S3 v2 integration only uses safe_dumps and not json.dumps"""@@ -416,8 +424,7 @@ async def test_async_upload_retries_on_s3_503():# Verify PUT was called twice (retry after 503)assert logger.async_httpx_client.put.call_count == 2- # Verify sleep was called with the backoff delay- mock_sleep.assert_called_once_with(1) # 2**0 = 1s+ _assert_jittered_backoff(mock_sleep, 1)@pytest.mark.asyncio@@ -457,7 +464,7 @@ async def test_async_upload_retries_on_s3_500():await logger.async_upload_data_to_s3(test_element)assert logger.async_httpx_client.put.call_count == 2- mock_sleep.assert_called_once_with(1)+ _assert_jittered_backoff(mock_sleep, 1)@pytest.mark.asyncio@@ -596,17 +603,20 @@ def _generation(request: httpx.Request) -> tuple[str, str]:@asynccontextmanager-async def _s3_logger_on_production_handler(profile: str, statuses: list[int]):+async def _s3_logger_on_production_handler(profile: str, statuses: list[int | type[httpx.TransportError]]):"""S3Logger wired to the real AsyncHTTPHandler over an httpx MockTransport that answers with the given- statuses in order, so the handler's own raise_for_status behaviour is exercised end to end.+ statuses (or raises the given transport errors) in order, so the handler's own error mapping is exercised."""requests: list[httpx.Request] = []replies = iter(statuses)def respond(request: httpx.Request) -> httpx.Response:requests.append(request)- return httpx.Response(next(replies), request=request, text="<Error><Code>SignatureDoesNotMatch</Code></Error>")+ reply = next(replies)+ if not isinstance(reply, int):+ raise reply("S3 attempt failed", request=request)+ return httpx.Response(reply, request=request, text="<Error><Code>SignatureDoesNotMatch</Code></Error>")handler = AsyncHTTPHandler()handler.client = httpx.AsyncClient(transport=httpx.MockTransport(respond))@@ -663,7 +673,7 @@ async def test_async_upload_retries_403_with_fresh_credentials_and_signature(rotassert second_key == second_tokenassert int(second_key) > int(first_key)assert requests[1].headers["Authorization"] != requests[0].headers["Authorization"]- mock_sleep.assert_awaited_once_with(1)+ _assert_jittered_backoff(mock_sleep, 1)assert "Error uploading to s3" not in caplog.text@@ -678,7 +688,7 @@ async def test_async_upload_exhausts_403_retries_through_production_http_handlerawait logger.async_upload_data_to_s3(test_element)assert len(requests) == 3- assert mock_sleep.await_args_list == [call(1), call(2)]+ _assert_jittered_backoff(mock_sleep, 2)assert "Error uploading to s3" in caplog.text@@ -708,7 +718,7 @@ async def test_async_upload_recovers_from_transient_5xx_through_production_http_assert all(request.method == "PUT" for request in requests)assert requests[0].url == requests[1].urlassert requests[0].content == requests[1].content- mock_sleep.assert_awaited_once_with(1)+ _assert_jittered_backoff(mock_sleep, 1)assert "Error uploading to s3" not in caplog.text@@ -756,10 +766,165 @@ async def test_async_upload_access_denied_403_is_retried_and_then_requeued(rotatassert outcome is Falseassert len(requests) == 3- assert mock_sleep.await_args_list == [call(1), call(2)]+ _assert_jittered_backoff(mock_sleep, 2)assert "Error uploading to s3" in caplog.text+async def test_async_upload_retries_429_through_production_http_handler(rotating_profile: str, caplog):+ """S3 and S3-compatible stores answer throttling with 429 too, so it backs off and retries like a 503."""+ async with _s3_logger_on_production_handler(rotating_profile, [429, 200]) as (logger, requests, mock_sleep):+ uploaded = await logger.async_upload_data_to_s3(_element({"test": "429"}, "429"))++ assert uploaded is True+ assert len(requests) == 2+ assert requests[0].content == requests[1].content+ _assert_jittered_backoff(mock_sleep, 1)+ assert "Error uploading to s3" not in caplog.text+++async def test_async_upload_retries_a_timed_out_attempt_through_production_http_handler(rotating_profile: str, caplog):+ """AsyncHTTPHandler.put turns an httpx timeout into litellm.Timeout, which must count as a retryable attempt."""+ async with _s3_logger_on_production_handler(rotating_profile, [httpx.ReadTimeout, 200]) as (+ logger,+ requests,+ mock_sleep,+ ):+ uploaded = await logger.async_upload_data_to_s3(_element({"test": "timeout"}, "timeout"))++ assert uploaded is True+ assert len(requests) == 2+ _assert_jittered_backoff(mock_sleep, 1)+ assert "Error uploading to s3" not in caplog.text+++ "error",+ [+ pytest.param(httpx.ConnectError("connection refused"), id="connect-error"),+ pytest.param(httpx.RemoteProtocolError("server disconnected"), id="remote-protocol-error"),+ pytest.param(httpx.ReadTimeout("read timed out"), id="read-timeout"),+ ],+)+async def test_async_upload_retries_transport_errors_then_succeeds(error: Exception) -> None:+ logger = S3Logger(+ s3_bucket_name="test-bucket",+ s3_aws_access_key_id="test-key",+ s3_aws_secret_access_key="test-secret",+ s3_region_name="us-east-1",+ )+ logger.async_httpx_client = AsyncMock()+ logger.async_httpx_client.put = AsyncMock(side_effect=[error, _ok_response()])++ with patch("asyncio.sleep", new_callable=AsyncMock) as mock_sleep:+ uploaded = await logger.async_upload_data_to_s3(_element({"test": "transport"}, "transport"))++ assert uploaded is True+ assert logger.async_httpx_client.put.call_count == 2+ _assert_jittered_backoff(mock_sleep, 1)+++async def test_async_upload_exhausts_transport_error_retries_and_keeps_the_event_queued() -> None:+ logger = S3Logger(+ s3_bucket_name="test-bucket",+ s3_aws_access_key_id="test-key",+ s3_aws_secret_access_key="test-secret",+ s3_region_name="us-east-1",+ )+ logger.async_httpx_client = AsyncMock()+ logger.async_httpx_client.put = AsyncMock(side_effect=httpx.ConnectError("connection refused"))+ logger.log_queue = [_element({"test": "down"}, "down")]++ with patch("asyncio.sleep", new_callable=AsyncMock) as mock_sleep:+ await logger.flush_queue()++ assert logger.async_httpx_client.put.call_count == 3+ _assert_jittered_backoff(mock_sleep, 2)+ assert [element.s3_object_key for element in logger.log_queue] == ["2025-09-14/test-down.json"]+++async def test_async_upload_sends_every_attempt_with_a_finite_deadline(rotating_profile: str) -> None:+ """+ The logger's handler is built with explicit params and no timeout, and the handler forwards that None to+ httpx as "no timeout", so without a per-attempt deadline a stalled S3 endpoint pins the upload forever.+ """+ async with _s3_logger_on_production_handler(rotating_profile, [503, 200]) as (logger, requests, _):+ await logger.async_upload_data_to_s3(_element({"test": "deadline"}, "deadline"))++ assert len(requests) == 2+ for request in requests:+ deadlines = request.extensions["timeout"]+ assert all(isinstance(limit, (int, float)) and limit > 0 for limit in deadlines.values()), deadlines+++async def test_backoff_is_jittered_so_throttled_uploads_do_not_retry_in_lockstep() -> None:+ logger = S3Logger(+ s3_bucket_name="test-bucket",+ s3_aws_access_key_id="test-key",+ s3_aws_secret_access_key="test-secret",+ s3_region_name="us-east-1",+ )+ logger.async_httpx_client = AsyncMock()+ logger.async_httpx_client.put = AsyncMock(+ side_effect=[_transient_failure_response(), _ok_response(), _transient_failure_response(), _ok_response()]+ )++ with (+ patch("asyncio.sleep", new_callable=AsyncMock) as mock_sleep,+ patch("random.random", side_effect=[0.0, 0.999]),+ ):+ await logger.async_upload_data_to_s3(_element({"i": 0}, "0"))+ await logger.async_upload_data_to_s3(_element({"i": 1}, "1"))++ first, second = (sleep_call.args[0] for sleep_call in mock_sleep.call_args_list)+ assert first != second+ assert 0.5 <= first < 1.5 and 0.5 <= second < 1.5+++async def test_dropped_uploads_are_logged_once_per_flush_naming_each_reason(caplog) -> None:+ logger = S3Logger(+ s3_bucket_name="test-bucket",+ s3_aws_access_key_id="test-key",+ s3_aws_secret_access_key="test-secret",+ s3_region_name="us-east-1",+ )+ terminal = (_element({"i": "terminal-0"}, "terminal-0"), _element({"i": "terminal-1"}, "terminal-1"))+ expired = _element({"i": "expired"}, "expired").model_copy(update={"retrying_since": _NOW - 7200})+ fresh = _element({"i": "fresh"}, "fresh")++ async def put(+ url: str, data: str | None = None, headers: dict[str, str] | None = None, timeout: httpx.Timeout | None = None+ ) -> MagicMock:+ if "test-terminal-" in url:+ return _terminal_failure_response()+ if url.endswith("test-expired.json"):+ return _transient_failure_response()+ return _ok_response()++ logger.async_httpx_client = AsyncMock()+ logger.async_httpx_client.put = put+ logger.log_queue = [*terminal, expired, fresh]++ with (+ patch("asyncio.sleep", new_callable=AsyncMock),+ patch("time.monotonic", return_value=_NOW),+ ):+ await logger.flush_queue()++ assert logger.log_queue == []+ drop_lines = [record.getMessage() for record in caplog.records if "uploads dropped" in record.getMessage()]+ assert len(drop_lines) == 1, drop_lines+ assert "3 uploads dropped" in drop_lines[0]+ assert "2 rejected as terminal" in drop_lines[0]+ assert "1 retrying longer than s3_max_retry_age_seconds=3600" in drop_lines[0]++def test_sync_upload_retries_403_with_fresh_signature(rotating_profile: str, monkeypatch: pytest.MonkeyPatch):monkeypatch.delenv("AWS_ACCESS_KEY_ID", raising=False)monkeypatch.delenv("AWS_SECRET_ACCESS_KEY", raising=False)@@ -794,7 +959,7 @@ def test_sync_upload_retries_403_with_fresh_signature(rotating_profile: str, monassert first_key == first_tokenassert second_key == second_tokenassert int(second_key) > int(first_key)- mock_sleep.assert_called_once_with(1)+ _assert_jittered_backoff(mock_sleep, 1)def test_sync_upload_retries_on_s3_503():@@ -835,7 +1000,7 @@ def test_sync_upload_retries_on_s3_503():logger.upload_data_to_s3(test_element)assert mock_sync_client.put.call_count == 2- mock_sleep.assert_called_once_with(1)+ _assert_jittered_backoff(mock_sleep, 1)@pytest.mark.asyncio@@ -2866,7 +3031,13 @@ class _CountingPut:self.peak = 0self.calls = 0- async def __call__(self, url: str, data: str | None = None, headers: dict[str, str] | None = None) -> MagicMock:+ async def __call__(+ self,+ url: str,+ data: str | None = None,+ headers: dict[str, str] | None = None,+ timeout: httpx.Timeout | None = None,+ ) -> MagicMock:self.in_flight += 1self.peak = max(self.peak, self.in_flight)self.calls += 1@@ -2882,7 +3053,13 @@ class _RecordingPut:def __init__(self) -> None:self.calls: tuple[tuple[str, str | None, dict[str, str] | None], ...] = ()- async def __call__(self, url: str, data: str | None = None, headers: dict[str, str] | None = None) -> MagicMock:+ async def __call__(+ self,+ url: str,+ data: str | None = None,+ headers: dict[str, str] | None = None,+ timeout: httpx.Timeout | None = None,+ ) -> MagicMock:self.calls = (*self.calls, (url, data, headers))return _ok_response()@@ -2895,7 +3072,13 @@ class _LateAppendingPut:self.appended = Falseself.failed_key: str | None = None- async def __call__(self, url: str, data: str | None = None, headers: dict[str, str] | None = None) -> MagicMock:+ async def __call__(+ self,+ url: str,+ data: str | None = None,+ headers: dict[str, str] | None = None,+ timeout: httpx.Timeout | None = None,+ ) -> MagicMock:if not self.appended:self.appended = Trueself.logger.log_queue.append(self.element)@@ -2912,7 +3095,13 @@ class _AppendingFailingPut:self.elements = elementsself.appended = False- async def __call__(self, url: str, data: str | None = None, headers: dict[str, str] | None = None) -> MagicMock:+ async def __call__(+ self,+ url: str,+ data: str | None = None,+ headers: dict[str, str] | None = None,+ timeout: httpx.Timeout | None = None,+ ) -> MagicMock:if not self.appended:self.appended = Truefor element in self.elements:@@ -2926,7 +3115,13 @@ class _FailOnSuffixPut:self.suffixes = suffixesself.calls: tuple[str, ...] = ()- async def __call__(self, url: str, data: str | None = None, headers: dict[str, str] | None = None) -> MagicMock:+ async def __call__(+ self,+ url: str,+ data: str | None = None,+ headers: dict[str, str] | None = None,+ timeout: httpx.Timeout | None = None,+ ) -> MagicMock:self.calls = (*self.calls, url)if self.failing and url.endswith(self.suffixes):return _transient_failure_response()@@ -2939,7 +3134,13 @@ class _FailUntilClearedPut:self.response: Final = _coded_failure_response(status, code, raw_body)self.calls: tuple[tuple[str, str | None], ...] = ()- async def __call__(self, url: str, data: str | None = None, headers: dict[str, str] | None = None) -> MagicMock:+ async def __call__(+ self,+ url: str,+ data: str | None = None,+ headers: dict[str, str] | None = None,+ timeout: httpx.Timeout | None = None,+ ) -> MagicMock:self.calls = (*self.calls, (url, data))if self.failing:return self.response@@ -3357,7 +3558,13 @@ class _FailOnSuffixCodedPut:self.response: Final = _coded_failure_response(status, code, raw_body)self.calls: tuple[str, ...] = ()- async def __call__(self, url: str, data: str | None = None, headers: dict[str, str] | None = None) -> MagicMock:+ async def __call__(+ self,+ url: str,+ data: str | None = None,+ headers: dict[str, str] | None = None,+ timeout: httpx.Timeout | None = None,+ ) -> MagicMock:self.calls = (*self.calls, url)if url.endswith(self.suffixes):return self.response@@ -3734,7 +3941,13 @@ class _SyncRecordingClient:self.response: Final = responseself.put_calls: list = [] # mutable-ok: call log appended once per PUT- def put(self, url: str, data: str | None = None, headers: dict[str, str] | None = None) -> MagicMock:+ def put(+ self,+ url: str,+ data: str | None = None,+ headers: dict[str, str] | None = None,+ timeout: httpx.Timeout | None = None,+ ) -> MagicMock:self.put_calls.append(url)return self.response@@ -3760,16 +3973,16 @@ def test_sync_upload_404_is_single_attempt_without_sleep() -> None:@pytest.mark.parametrize(- ("status", "expected_puts", "expected_sleeps"),+ ("status", "expected_puts", "expected_retries"),[- pytest.param(429, 1, [], id="429-single"),- pytest.param(408, 1, [], id="408-single"),- pytest.param(502, 1, [], id="502-single"),- pytest.param(504, 1, [], id="504-single"),- pytest.param(503, 3, [call(1), call(2)], id="503-backoff"),+ pytest.param(408, 1, 0, id="408-single"),+ pytest.param(502, 1, 0, id="502-single"),+ pytest.param(504, 1, 0, id="504-single"),+ pytest.param(429, 3, 2, id="429-backoff"),+ pytest.param(503, 3, 2, id="503-backoff"),],)-def test_sync_upload_retry_set_matches_base(status: int, expected_puts: int, expected_sleeps: list) -> None:+def test_sync_upload_retry_set(status: int, expected_puts: int, expected_retries: int) -> None:logger = S3Logger(s3_bucket_name="test-bucket",s3_aws_access_key_id="test-key",@@ -3786,7 +3999,50 @@ def test_sync_upload_retry_set_matches_base(status: int, expected_puts: int, explogger.upload_data_to_s3(_element({"id": "sync"}, "sync"))assert len(sync_client.put_calls) == expected_puts- assert mock_sleep.call_args_list == expected_sleeps+ _assert_jittered_backoff(mock_sleep, expected_retries)+++ "failure",+ [pytest.param(httpx.ConnectError, id="connect-error"), pytest.param(httpx.ReadTimeout, id="read-timeout")],+)+def test_sync_upload_retries_a_failed_attempt_through_production_http_handler(+ failure: type[httpx.TransportError], caplog: pytest.LogCaptureFixture+) -> None:+ """HTTPHandler.put turns an httpx timeout into litellm.Timeout, and each attempt carries its own deadline."""+ requests: Final[list[httpx.Request]] = [] # mutable-ok: the transport records every attempt++ def respond(request: httpx.Request) -> httpx.Response:+ requests.append(request)+ if len(requests) == 1:+ raise failure("S3 attempt failed", request=request)+ return httpx.Response(200, request=request)++ handler: Final = HTTPHandler()+ handler.client = httpx.Client(transport=httpx.MockTransport(respond), timeout=None)+ logger: Final = S3Logger(+ s3_bucket_name="test-bucket",+ s3_aws_access_key_id="test-key",+ s3_aws_secret_access_key="test-secret",+ s3_region_name="us-east-1",+ )+ with (+ patch( # test-quality-ok: sync upload builds its HTTPHandler per call, there is no injection seam for it+ "litellm.integrations.s3_v2.get_httpx_client", return_value=handler+ ),+ patch("time.sleep") as mock_sleep,+ ):+ logger.upload_data_to_s3(_element({"id": "sync-transient"}, "sync-transient"))+ handler.client.close()++ assert len(requests) == 2+ assert requests[0].content == requests[1].content+ assert all(+ request.extensions["timeout"] == httpx.Timeout(S3_UPLOAD_ATTEMPT_TIMEOUT_SECONDS).as_dict()+ for request in requests+ )+ _assert_jittered_backoff(mock_sleep, 1)+ assert "Error uploading to s3" not in caplog.text@pytest.mark.asyncio@@ -3794,6 +4050,7 @@ def test_sync_upload_retry_set_matches_base(status: int, expected_puts: int, exp("status", "code"),[pytest.param(503, "SlowDown", id="503"),+ pytest.param(429, "SlowDown", id="429"),pytest.param(500, "InternalError", id="500"),pytest.param(403, "AccessDenied", id="access-denied-403"),],@@ -3816,7 +4073,7 @@ async def test_retryable_statuses_back_off_three_attempts(status: int, code: strawait logger.flush_queue()assert len(put.calls) == 3- assert mock_sleep.await_args_list == [call(1), call(2)]+ _assert_jittered_backoff(mock_sleep, 2)assert len(logger.log_queue) == 1@@ -3824,13 +4081,12 @@ async def test_retryable_statuses_back_off_three_attempts(status: int, code: str@pytest.mark.parametrize(("status", "code"),[- pytest.param(429, "TooManyRequests", id="429"),pytest.param(408, None, id="408"),pytest.param(502, None, id="502"),pytest.param(504, None, id="504"),],)-async def test_non_base_statuses_are_not_retried_in_call(status: int, code: str | None) -> None:+async def test_unlisted_statuses_are_not_retried_in_call(status: int, code: str | None) -> None:logger = S3Logger(s3_bucket_name="test-bucket",s3_aws_access_key_id="test-key",@@ -3858,7 +4114,13 @@ class _FirstFailThenOkPut:self.failed_once = Falseself.calls: tuple[str, ...] = ()- async def __call__(self, url: str, data: str | None = None, headers: dict[str, str] | None = None) -> MagicMock:+ async def __call__(+ self,+ url: str,+ data: str | None = None,+ headers: dict[str, str] | None = None,+ timeout: httpx.Timeout | None = None,+ ) -> MagicMock:self.calls = (*self.calls, url)if url.endswith(self.fail_suffix) and not self.failed_once:self.failed_once = True@@ -3971,7 +4233,13 @@ async def test_terminal_drop_of_one_element_does_not_drop_a_sibling_with_the_samdef __init__(self) -> None:self.calls: tuple[str | None, ...] = ()- async def __call__(self, url: str, data: str | None = None, headers: dict[str, str] | None = None) -> MagicMock:+ async def __call__(+ self,+ url: str,+ data: str | None = None,+ headers: dict[str, str] | None = None,+ timeout: httpx.Timeout | None = None,+ ) -> MagicMock:self.calls = (*self.calls, data)if data is not None and "terminal-marker" in data:return _terminal_failure_response()@@ -4321,7 +4589,13 @@ class _FailOncePerKeyPut:self.failed: set[str] = set()self.calls: tuple[str, ...] = ()- async def __call__(self, url: str, data: str | None = None, headers: dict[str, str] | None = None) -> MagicMock:+ async def __call__(+ self,+ url: str,+ data: str | None = None,+ headers: dict[str, str] | None = None,+ timeout: httpx.Timeout | None = None,+ ) -> MagicMock:self.calls = (*self.calls, url)if url not in self.failed:self.failed.add(url)@@ -4336,7 +4610,13 @@ class _SlowFailOncePerKeyPut:self.first_completed: int | None = Noneself.calls: tuple[str, ...] = ()- async def __call__(self, url: str, data: str | None = None, headers: dict[str, str] | None = None) -> MagicMock:+ async def __call__(+ self,+ url: str,+ data: str | None = None,+ headers: dict[str, str] | None = None,+ timeout: httpx.Timeout | None = None,+ ) -> MagicMock:self.calls = (*self.calls, url)await _real_sleep(0)if self.first_completed is None:@@ -4470,7 +4750,13 @@ class _AppendingSuffixFailingPut:self.fail_suffixes = fail_suffixesself.appended = False- async def __call__(self, url: str, data: str | None = None, headers: dict[str, str] | None = None) -> MagicMock:+ async def __call__(+ self,+ url: str,+ data: str | None = None,+ headers: dict[str, str] | None = None,+ timeout: httpx.Timeout | None = None,+ ) -> MagicMock:if not self.appended:self.appended = Trueself.logger.log_queue.append(self.element)@@ -4689,7 +4975,7 @@ def test_sync_upload_retries_access_denied_403(caplog):logger.upload_data_to_s3(test_element)assert mock_sync_client.put.call_count == 3- assert mock_sleep.call_args_list == [call(1), call(2)]+ _assert_jittered_backoff(mock_sleep, 2)assert "dropping object" not in caplog.text@@ -4940,7 +5226,13 @@ class _StatusPut:self.responses = responsesself.calls = 0- async def __call__(self, url: str, data: str | None = None, headers: dict[str, str] | None = None) -> MagicMock:+ async def __call__(+ self,+ url: str,+ data: str | None = None,+ headers: dict[str, str] | None = None,+ timeout: httpx.Timeout | None = None,+ ) -> MagicMock:self.calls += 1outcome = self.responses[min(self.calls - 1, len(self.responses) - 1)]if isinstance(outcome, Exception):@@ -5074,7 +5366,9 @@ async def test_a_slow_put_does_not_lower_the_adaptive_limit() -> None:logger = _override_logger(s3_adaptive_concurrency=True)logger.async_httpx_client = AsyncMock()- async def slow_put(url: str, data: str | None = None, headers: dict[str, str] | None = None) -> MagicMock:+ async def slow_put(+ url: str, data: str | None = None, headers: dict[str, str] | None = None, timeout: httpx.Timeout | None = None+ ) -> MagicMock:await _real_sleep(0)return _ok_response()@@ -5091,7 +5385,13 @@ class _FastOkPut:def __init__(self) -> None:self.calls = 0- async def __call__(self, url: str, data: str | None = None, headers: dict[str, str] | None = None) -> MagicMock:+ async def __call__(+ self,+ url: str,+ data: str | None = None,+ headers: dict[str, str] | None = None,+ timeout: httpx.Timeout | None = None,+ ) -> MagicMock:self.calls += 1await _real_sleep(0)return _ok_response()