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(proxy): stop retrying post-send ambiguous DB errors in every spend writer
Tin Chi Lo2e12614a5b1f
diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.pyindex 7575091be54..b94a34fa14c 100644--- a/litellm/proxy/_types.py+++ b/litellm/proxy/_types.py@@ -3638,6 +3638,13 @@ DB_CONNECTION_ERROR_TYPES = (httpx.ReadTimeout,)+# What a NON-IDEMPOTENT write (increment upsert) may retry: only ConnectError+# proves the statements never reached the database. Post-send errors are+# ambiguous; a stalled statement can leave its transaction open on the pooled+# connection, where a retry stacks a second increment set into the same commit.+# Idempotent writes (create_many with skip_duplicates) may retry the full tuple.+DB_RETRY_SAFE_ERROR_TYPES = (httpx.ConnectError,)+class SSOUserDefinedValues(TypedDict):models: List[str]diff --git a/litellm/proxy/db/db_spend_update_writer.py b/litellm/proxy/db/db_spend_update_writer.pyindex ebdb08a681a..fd8132fef22 100644--- a/litellm/proxy/db/db_spend_update_writer.py+++ b/litellm/proxy/db/db_spend_update_writer.py@@ -34,7 +34,7 @@ from litellm.constants import ()from litellm.litellm_core_utils.safe_json_loads import safe_json_loadsfrom litellm.proxy._types import (- DB_CONNECTION_ERROR_TYPES,+ DB_RETRY_SAFE_ERROR_TYPES,BaseDailySpendTransaction,DailyAgentSpendTransaction,DailyEndUserSpendTransaction,@@ -1121,7 +1121,7 @@ class DBSpendUpdateWriter:data={"spend": {"increment": response_cost}},)break- except DB_CONNECTION_ERROR_TYPES as e:+ except DB_RETRY_SAFE_ERROR_TYPES as e:if i >= n_retry_times: # If we've reached the maximum number of retries_raise_failed_update_spend_exception(e=e,@@ -1164,7 +1164,7 @@ class DBSpendUpdateWriter:},)break- except DB_CONNECTION_ERROR_TYPES as e:+ except DB_RETRY_SAFE_ERROR_TYPES as e:if i >= n_retry_times: # If we've reached the maximum number of retries_raise_failed_update_spend_exception(e=e,@@ -1197,7 +1197,7 @@ class DBSpendUpdateWriter:data={"spend": {"increment": response_cost}},)break- except DB_CONNECTION_ERROR_TYPES as e:+ except DB_RETRY_SAFE_ERROR_TYPES as e:if i >= n_retry_times: # If we've reached the maximum number of retries_raise_failed_update_spend_exception(e=e,@@ -1244,7 +1244,7 @@ class DBSpendUpdateWriter:)# Transaction succeeded, break out of retry loopbreak- except DB_CONNECTION_ERROR_TYPES as e:+ except DB_RETRY_SAFE_ERROR_TYPES as e:if i >= n_retry_times: # If we've reached the maximum number of retries_raise_failed_update_spend_exception(e=e,@@ -1286,7 +1286,7 @@ class DBSpendUpdateWriter:data={"spend": {"increment": response_cost}},)break- except DB_CONNECTION_ERROR_TYPES as e:+ except DB_RETRY_SAFE_ERROR_TYPES as e:if i >= n_retry_times: # If we've reached the maximum number of retries_raise_failed_update_spend_exception(e=e,@@ -1372,7 +1372,7 @@ class DBSpendUpdateWriter:data={"spend": {"increment": response_cost}},)break- except DB_CONNECTION_ERROR_TYPES as e:+ except DB_RETRY_SAFE_ERROR_TYPES as e:if i >= n_retry_times:_raise_failed_update_spend_exception(e=e,@@ -1669,7 +1669,7 @@ class DBSpendUpdateWriter:break- except DB_CONNECTION_ERROR_TYPES as e:+ except DB_RETRY_SAFE_ERROR_TYPES as e:if i >= n_retry_times:_raise_failed_update_spend_exception(e=e,diff --git a/litellm/proxy/db/spend_log_tool_index.py b/litellm/proxy/db/spend_log_tool_index.pyindex a478248b0fa..802e893d473 100644--- a/litellm/proxy/db/spend_log_tool_index.py+++ b/litellm/proxy/db/spend_log_tool_index.py@@ -18,7 +18,7 @@ from datetime import datetime, timezonefrom itertools import groupbyfrom typing import TYPE_CHECKING, Any, Sequence-import httpx+from litellm.proxy._types import DB_RETRY_SAFE_ERROR_TYPESif TYPE_CHECKING:from litellm.proxy.utils import PrismaClient@@ -144,7 +144,7 @@ async def flush_tool_usage_transactions(},)return- except httpx.ConnectError:+ except DB_RETRY_SAFE_ERROR_TYPES:if attempt >= n_retry_times:raiseawait asyncio.sleep(2**attempt + random.uniform(0, 1))diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.pyindex d7a95284818..924189fed4b 100644--- a/litellm/proxy/utils.py+++ b/litellm/proxy/utils.py@@ -41,6 +41,7 @@ from litellm.constants import ()from litellm.proxy._types import (DB_CONNECTION_ERROR_TYPES,+ DB_RETRY_SAFE_ERROR_TYPES,CommonProxyErrors,ProxyErrorTypes,ProxyException,@@ -5337,7 +5338,7 @@ class ProxyUpdateSpend:)break- except DB_CONNECTION_ERROR_TYPES as e:+ except DB_RETRY_SAFE_ERROR_TYPES as e:if i >= n_retry_times: # If we've reached the maximum number of retries_raise_failed_update_spend_exception(e=e, start_time=start_time, proxy_logging_obj=proxy_logging_objdiff --git a/tests/test_litellm/proxy/db/test_db_spend_update_writer.py b/tests/test_litellm/proxy/db/test_db_spend_update_writer.pyindex cd293325c15..191080e3a48 100644--- a/tests/test_litellm/proxy/db/test_db_spend_update_writer.py+++ b/tests/test_litellm/proxy/db/test_db_spend_update_writer.py@@ -308,6 +308,84 @@ async def test_update_daily_spend_with_null_entity_id():assert create_data["failed_requests"] == 0+def _daily_txn(user_id: str = "user1") -> dict:+ return {+ "user_id": user_id,+ "date": "2024-01-01",+ "api_key": "test-api-key",+ "model": "gpt-4",+ "custom_llm_provider": "openai",+ "prompt_tokens": 10,+ "completion_tokens": 20,+ "spend": 0.1,+ "api_requests": 1,+ "successful_requests": 1,+ "failed_requests": 0,+ }+++async def test_update_daily_spend_does_not_retry_post_send_ambiguous_errors():+ # Regression for the double-apply hazard: a ReadTimeout means the batch was+ # sent and its outcome is unknown; the engine can leave the transaction open+ # on the pooled connection, so retrying stacks a second set of increments+ # into it and one commit applies both. Post-send failures must drop the+ # batch (loudly), never retry it.+ import httpx++ mock_prisma_client = MagicMock()+ mock_prisma_client.db.batch_ = MagicMock(side_effect=httpx.ReadTimeout("ambiguous"))+ proxy_logging = MagicMock()+ proxy_logging.failure_handler = AsyncMock()++ with pytest.raises(httpx.ReadTimeout):+ await DBSpendUpdateWriter._update_daily_spend(+ n_retry_times=3,+ prisma_client=mock_prisma_client,+ proxy_logging_obj=proxy_logging,+ daily_spend_transactions={"k1": _daily_txn()},+ entity_type="user",+ entity_id_field="user_id",+ table_name="litellm_dailyuserspend",+ unique_constraint_name="user_id_date_api_key_model_custom_llm_provider_mcp_namespaced_tool_name_endpoint",+ )++ mock_prisma_client.db.batch_.assert_called_once()+++async def test_update_daily_spend_retries_connect_errors(monkeypatch):+ # ConnectError proves the statements never reached the database, so it is+ # the one failure the writer may retry.+ import httpx++ mock_batcher = MagicMock()+ good_ctx = MagicMock()+ good_ctx.__aenter__ = AsyncMock(return_value=mock_batcher)+ good_ctx.__aexit__ = AsyncMock(return_value=None)+ mock_prisma_client = MagicMock()+ mock_prisma_client.db.batch_ = MagicMock(side_effect=[httpx.ConnectError("down"), good_ctx])+ proxy_logging = MagicMock()+ proxy_logging.failure_handler = AsyncMock()++ async def fake_sleep(seconds: float) -> None:+ return None++ monkeypatch.setattr("litellm.proxy.db.db_spend_update_writer.asyncio.sleep", fake_sleep)+ await DBSpendUpdateWriter._update_daily_spend(+ n_retry_times=3,+ prisma_client=mock_prisma_client,+ proxy_logging_obj=proxy_logging,+ daily_spend_transactions={"k1": _daily_txn()},+ entity_type="user",+ entity_id_field="user_id",+ table_name="litellm_dailyuserspend",+ unique_constraint_name="user_id_date_api_key_model_custom_llm_provider_mcp_namespaced_tool_name_endpoint",+ )++ assert mock_prisma_client.db.batch_.call_count == 2++@pytest.mark.asyncioasync def test_update_daily_spend_sorting():"""diff --git a/tests/test_litellm/proxy/utils/prisma_and_spend/test_proxy_update_spend.py b/tests/test_litellm/proxy/utils/prisma_and_spend/test_proxy_update_spend.pyindex d5d4de7f2cf..f075acc7307 100644--- a/tests/test_litellm/proxy/utils/prisma_and_spend/test_proxy_update_spend.py+++ b/tests/test_litellm/proxy/utils/prisma_and_spend/test_proxy_update_spend.py@@ -68,12 +68,12 @@ async def test_update_end_user_spend_upserts_each_end_user(@pytest.mark.asyncio-async def test_update_end_user_spend_retries_on_connection_error(+async def test_update_end_user_spend_retries_on_connect_error(mock_prisma_client: Any, monkeypatch: pytest.MonkeyPatch) -> None:- """``DB_CONNECTION_ERROR_TYPES`` failures should be retried with backoff;- once retries are exhausted, ``_raise_failed_update_spend_exception`` is- invoked and the original exception bubbles up.+ """``DB_RETRY_SAFE_ERROR_TYPES`` (ConnectError, statements provably never+ sent) retries with backoff; once retries are exhausted the original+ exception bubbles up via ``_raise_failed_update_spend_exception``."""import httpximport litellm.proxy.utils as utils_mod@@ -85,11 +85,11 @@ async def test_update_end_user_spend_retries_on_connection_error(monkeypatch.setattr(utils_mod.asyncio, "sleep", _fake_sleep)- err = httpx.ReadError("conn reset")+ err = httpx.ConnectError("down")mock_prisma_client.db.tx = MagicMock(side_effect=err)proxy_logging = MagicMock()proxy_logging.failure_handler = AsyncMock()- with pytest.raises(httpx.ReadError):+ with pytest.raises(httpx.ConnectError):await ProxyUpdateSpend.update_end_user_spend(n_retry_times=1,prisma_client=mock_prisma_client,@@ -99,6 +99,29 @@ async def test_update_end_user_spend_retries_on_connection_error(assert sleeps == [1.0][email protected]("ambiguous_error_name", ["ReadTimeout", "ReadError"])+async def test_update_end_user_spend_does_not_retry_post_send_ambiguous_errors(+ mock_prisma_client: Any, ambiguous_error_name: str+) -> None:+ """Post-send errors are ambiguous and retrying can double-apply increments+ (see DB_RETRY_SAFE_ERROR_TYPES); they must raise on the first attempt."""+ import httpx++ err = getattr(httpx, ambiguous_error_name)("ambiguous")+ mock_prisma_client.db.tx = MagicMock(side_effect=err)+ proxy_logging = MagicMock()+ proxy_logging.failure_handler = AsyncMock()+ with pytest.raises((httpx.ReadTimeout, httpx.ReadError)):+ await ProxyUpdateSpend.update_end_user_spend(+ n_retry_times=3,+ prisma_client=mock_prisma_client,+ proxy_logging_obj=proxy_logging,+ end_user_list_transactions={"u": 1.0},+ )+ mock_prisma_client.db.tx.assert_called_once()++@pytest.mark.asyncioasync def test_update_end_user_spend_non_connection_error_raises_immediately(mock_prisma_client: Any,