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(reset_budget_job): reconnect and retry on transient DB transport errors (#37705)
devin-ai-integration[bot]d8a57a1a2bb9
diff --git a/litellm/proxy/common_utils/reset_budget_job.py b/litellm/proxy/common_utils/reset_budget_job.pyindex 7b7cba5fc42..b28b7291a4c 100644--- a/litellm/proxy/common_utils/reset_budget_job.py+++ b/litellm/proxy/common_utils/reset_budget_job.py@@ -17,6 +17,7 @@ from litellm.constants import (RESET_BUDGET_JOB_MAX_CHUNKS_PER_RUN,)from litellm.proxy._types import (+ DB_RETRY_SAFE_ERROR_TYPES,LiteLLM_BudgetTableFull,LiteLLM_EndUserTable,LiteLLM_TeamTable,@@ -29,6 +30,7 @@ from litellm.proxy.common_utils.timezone_utils import (get_budget_reset_settings,)from litellm.proxy.common_utils.user_api_key_cache import tag_cache_key+from litellm.proxy.db.exception_handler import call_with_db_reconnect_retryfrom litellm.proxy.utils import PrismaClient, ProxyLoggingfrom litellm.repositories.organization_repository import OrganizationRepositoryfrom litellm.repositories.prisma_protocols import ReadOnlyTable, SpendLinkedTable@@ -236,6 +238,24 @@ class ResetBudgetJob:await self.reset_budget_for_litellm_budget_table()await self.reset_budget_windows()+ async def _with_db_retry(self, operation: Callable[[], Awaitable[_RowT]], *, reason: str) -> _RowT:+ """Reconnect and retry once on a transport error, so a dropped connection+ costs one retry instead of the whole tick.+ """+ return await call_with_db_reconnect_retry(self.prisma_client, operation, reason=reason)++ async def _with_db_write_retry(self, operation: Callable[[], Awaitable[_RowT]], *, reason: str) -> _RowT:+ """Same, for writes: only replay when the statements provably never+ reached the database. A reset zeroes spend unconditionally, so replaying+ an ambiguous commit would erase spend accrued since it landed.+ """+ return await call_with_db_reconnect_retry(+ self.prisma_client,+ operation,+ reason=reason,+ retry_safe_error_types=DB_RETRY_SAFE_ERROR_TYPES,+ )+@staticmethodasync def _invalidate_spend_counter(counter_key: str) -> None:"""Zero a spend counter so a DB-row reset takes effect immediately.@@ -301,16 +321,24 @@ class ResetBudgetJob:"""Read the rows the cascade will zero, so their counters can beinvalidated once the transaction commits."""try:- return tuple(await table.find_many(where=where))+ return tuple(+ await self._with_db_retry(+ lambda: table.find_many(where=where),+ reason=f"reset_budget_read_{log_subject.replace(' ', '_')}_failure",+ )+ )except Exception as e:verbose_proxy_logger.warning("Failed to fetch %s for counter invalidation: %s", log_subject, e)return ()async def _collect_endusers_to_reset(self, budget_ids: Sequence[str]) -> tuple[_EndUserRow, ...]:- linked: Final[Sequence[_EndUserRow] | None] = await self.prisma_client.get_data(- table_name="enduser",- query_type="find_all",- budget_id_list=list(budget_ids),+ linked: Final[Sequence[_EndUserRow] | None] = await self._with_db_retry(+ lambda: self.prisma_client.get_data(+ table_name="enduser",+ query_type="find_all",+ budget_id_list=list(budget_ids),+ ),+ reason="reset_budget_read_endusers_failure",)if litellm.max_end_user_budget_id is None or litellm.max_end_user_budget_id not in budget_ids:return tuple(linked or ())@@ -384,6 +412,12 @@ class ResetBudgetJob:if not cascade.budget_ids:return+ await self._with_db_write_retry(+ lambda: self._commit_budget_cascade_once(cascade),+ reason="reset_budget_write_budget_cascade_failure",+ )++ async def _commit_budget_cascade_once(self, cascade: _BudgetCascade) -> None:enduser_ids: Final = tuple(row.user_id for row in cascade.endusers)async with budget_cascade_unit_of_work(self.prisma_client.db.batch_) as uow:uow.team_memberships.queue_spend_zero(where=_budget_link_where(cascade.budget_ids))@@ -404,11 +438,14 @@ class ResetBudgetJob:async def _reset_expired_budget_cascade(self) -> _BudgetCascadeCommitted | _BudgetCascadeFailed:now: Final = datetime.now(timezone.utc)try:- budgets_to_reset: Final[Sequence[LiteLLM_BudgetTableFull] | None] = await self.prisma_client.get_data(- table_name="budget",- query_type="find_all",- reset_at=now,- limit=RESET_BUDGET_JOB_BATCH_SIZE,+ budgets_to_reset: Final[Sequence[LiteLLM_BudgetTableFull] | None] = await self._with_db_retry(+ lambda: self.prisma_client.get_data(+ table_name="budget",+ query_type="find_all",+ reset_at=now,+ limit=RESET_BUDGET_JOB_BATCH_SIZE,+ ),+ reason="reset_budget_read_budgets_failure",)cascade: Final = await self._collect_budget_cascade(budgets_to_reset or ())except Exception as e:@@ -492,11 +529,14 @@ class ResetBudgetJob:in-memory during auth checks."""table: Final[ReadOnlyTable] = EndUserRepository(self.prisma_client).table- rows: Final = await table.find_many(- where={- "budget_id": None,- "spend": {"gt": 0},- },+ rows: Final = await self._with_db_retry(+ lambda: table.find_many(+ where={+ "budget_id": None,+ "spend": {"gt": 0},+ },+ ),+ reason="reset_budget_read_endusers_without_budget_id_failure",)return [LiteLLM_EndUserTable.model_validate(row.dict()) for row in rows]@@ -511,6 +551,12 @@ class ResetBudgetJob:aborts the entire batch — silently leaving spend over the cap andbudget_reset_at unchanged forever."""+ await self._with_db_write_retry(+ lambda: self._write_key_reset_updates_once(updated_keys),+ reason="reset_budget_write_keys_failure",+ )++ async def _write_key_reset_updates_once(self, updated_keys: list[LiteLLM_VerificationToken]) -> None:async with spend_reset_unit_of_work(self.prisma_client.db.batch_) as uow:for k in updated_keys:if k.token is None:@@ -525,6 +571,12 @@ class ResetBudgetJob:that trips Prisma's DataError on rows carrying unrecognised fields(see #27730)."""+ await self._with_db_write_retry(+ lambda: self._write_user_reset_updates_once(updated_users),+ reason="reset_budget_write_users_failure",+ )++ async def _write_user_reset_updates_once(self, updated_users: list[LiteLLM_UserTable]) -> None:async with spend_reset_unit_of_work(self.prisma_client.db.batch_) as uow:for u in updated_users:uow.users.queue_spend_reset(user_id=u.user_id, budget_reset_at=u.budget_reset_at)@@ -537,6 +589,12 @@ class ResetBudgetJob:that trips Prisma's DataError on rows carrying unrecognised fields(see #27730)."""+ await self._with_db_write_retry(+ lambda: self._write_team_reset_updates_once(updated_teams),+ reason="reset_budget_write_teams_failure",+ )++ async def _write_team_reset_updates_once(self, updated_teams: list[LiteLLM_TeamTable]) -> None:async with spend_reset_unit_of_work(self.prisma_client.db.batch_) as uow:for t in updated_teams:uow.teams.queue_spend_reset(team_id=t.team_id, budget_reset_at=t.budget_reset_at)@@ -579,12 +637,15 @@ class ResetBudgetJob:start_time: Final = time.time()keys_to_reset: list[LiteLLM_VerificationToken] | None = Nonetry:- keys_to_reset = await self.prisma_client.get_data(- table_name="key",- query_type="find_all",- expires=now,- reset_at=now,- limit=RESET_BUDGET_JOB_BATCH_SIZE,+ keys_to_reset = await self._with_db_retry(+ lambda: self.prisma_client.get_data(+ table_name="key",+ query_type="find_all",+ expires=now,+ reset_at=now,+ limit=RESET_BUDGET_JOB_BATCH_SIZE,+ ),+ reason="reset_budget_read_keys_failure",)verbose_proxy_logger.debug("Keys to reset %s", json.dumps(keys_to_reset, indent=4, default=str))updated_keys: Final[list[LiteLLM_VerificationToken]] = []@@ -684,11 +745,14 @@ class ResetBudgetJob:start_time: Final = time.time()users_to_reset: list[LiteLLM_UserTable] | None = Nonetry:- users_to_reset = await self.prisma_client.get_data(- table_name="user",- query_type="find_all",- reset_at=now,- limit=RESET_BUDGET_JOB_BATCH_SIZE,+ users_to_reset = await self._with_db_retry(+ lambda: self.prisma_client.get_data(+ table_name="user",+ query_type="find_all",+ reset_at=now,+ limit=RESET_BUDGET_JOB_BATCH_SIZE,+ ),+ reason="reset_budget_read_users_failure",)updated_users: Final[list[LiteLLM_UserTable]] = []failed_users: Final = []@@ -795,11 +859,14 @@ class ResetBudgetJob:start_time: Final = time.time()teams_to_reset: list[LiteLLM_TeamTable] | None = Nonetry:- teams_to_reset = await self.prisma_client.get_data(- table_name="team",- query_type="find_all",- reset_at=now,- limit=RESET_BUDGET_JOB_BATCH_SIZE,+ teams_to_reset = await self._with_db_retry(+ lambda: self.prisma_client.get_data(+ table_name="team",+ query_type="find_all",+ reset_at=now,+ limit=RESET_BUDGET_JOB_BATCH_SIZE,+ ),+ reason="reset_budget_read_teams_failure",)updated_teams: Final[list[LiteLLM_TeamTable]] = []failed_teams: Final = []@@ -937,8 +1004,11 @@ class ResetBudgetJob:# --- Keys ---try:- key_rows: Final = await self.prisma_client.db.query_raw(- 'SELECT token, budget_limits FROM "LiteLLM_VerificationToken" WHERE budget_limits IS NOT NULL'+ key_rows: Final = await self._with_db_retry(+ lambda: self.prisma_client.db.query_raw(+ 'SELECT token, budget_limits FROM "LiteLLM_VerificationToken" WHERE budget_limits IS NOT NULL'+ ),+ reason="reset_budget_read_key_windows_failure",)for row in key_rows:raw = row["budget_limits"]@@ -957,17 +1027,23 @@ class ResetBudgetJob:):changed = Trueif changed:- await VerificationTokenRepository(self.prisma_client).table.update(- where={"token": row["token"]},- data={"budget_limits": json.dumps(windows)},+ await self._with_db_write_retry(+ lambda: VerificationTokenRepository(self.prisma_client).table.update(+ where={"token": row["token"]},+ data={"budget_limits": json.dumps(windows)},+ ),+ reason="reset_budget_write_key_windows_failure",)except Exception as e:verbose_proxy_logger.exception("Failed to reset budget windows for keys: %s", e)# --- Teams ---try:- team_rows: Final = await self.prisma_client.db.query_raw(- 'SELECT team_id, budget_limits FROM "LiteLLM_TeamTable" WHERE budget_limits IS NOT NULL'+ team_rows: Final = await self._with_db_retry(+ lambda: self.prisma_client.db.query_raw(+ 'SELECT team_id, budget_limits FROM "LiteLLM_TeamTable" WHERE budget_limits IS NOT NULL'+ ),+ reason="reset_budget_read_team_windows_failure",)for row in team_rows:raw = row["budget_limits"]@@ -986,9 +1062,12 @@ class ResetBudgetJob:):changed = Trueif changed:- await TeamRepository(self.prisma_client).table.update(- where={"team_id": row["team_id"]},- data={"budget_limits": json.dumps(windows)},+ await self._with_db_write_retry(+ lambda: TeamRepository(self.prisma_client).table.update(+ where={"team_id": row["team_id"]},+ data={"budget_limits": json.dumps(windows)},+ ),+ reason="reset_budget_write_team_windows_failure",)except Exception as e:verbose_proxy_logger.exception("Failed to reset budget windows for teams: %s", e)diff --git a/litellm/proxy/db/exception_handler.py b/litellm/proxy/db/exception_handler.pyindex f7a39aaa50f..5502543b926 100644--- a/litellm/proxy/db/exception_handler.py+++ b/litellm/proxy/db/exception_handler.py@@ -335,6 +335,7 @@ async def call_with_db_reconnect_retry(coro_factory: Callable[[], Awaitable[_ReadResultT]],*,reason: str,+ retry_safe_error_types: tuple[type[Exception], ...] | None = None,timeout_seconds: float | None = None,lock_timeout_seconds: float | None = None,) -> _ReadResultT:@@ -350,7 +351,8 @@ async def call_with_db_reconnect_retry(2. On exception, if it is NOT a transport error (per`is_database_transport_error`), re-raise — data-layer errors like`UniqueViolationError` mean the DB is reachable, reconnect would be- pointless.+ pointless. Transport errors outside `retry_safe_error_types` are+ re-raised too.3. If `prisma_client` does not expose `attempt_db_reconnect`, re-raise.This guards against partial stand-ins / older clients in tests.4. Call `prisma_client.attempt_db_reconnect(reason=...)`. If it returns@@ -371,6 +373,10 @@ async def call_with_db_reconnect_retry(`attempt_db_reconnect` and the `_db_auth_reconnect_*` defaults.coro_factory: Zero-arg callable returning the read awaitable.reason: Telemetry tag forwarded to `attempt_db_reconnect`.+ retry_safe_error_types: Which transport errors may be replayed, or+ None for every transport error. A non-idempotent write must narrow+ this to `DB_RETRY_SAFE_ERROR_TYPES`, where the statements provably+ never reached the database.timeout_seconds: Optional override for the reconnect cycle timeout.Defaults to `prisma_client._db_auth_reconnect_timeout_seconds`,then to 2.0s.@@ -392,6 +398,8 @@ async def call_with_db_reconnect_retry(except Exception as first_exc:if not PrismaDBExceptionHandler.is_database_transport_error(first_exc):raise+ if retry_safe_error_types is not None and not isinstance(first_exc, retry_safe_error_types):+ raiseif not hasattr(prisma_client, "attempt_db_reconnect"):raisediff --git a/tests/test_litellm/proxy/common_utils/test_reset_budget_job.py b/tests/test_litellm/proxy/common_utils/test_reset_budget_job.pyindex 608dc8cb5c8..c5bc4e29f81 100644--- a/tests/test_litellm/proxy/common_utils/test_reset_budget_job.py+++ b/tests/test_litellm/proxy/common_utils/test_reset_budget_job.py@@ -8,6 +8,8 @@ from datetime import time as dt_timefrom typing import Any, Dict, Listfrom unittest.mock import AsyncMock, MagicMock+import httpx+import prismaimport pytestsys.path.insert(0, os.path.abspath("../../..")) # Adds the parent directory to the system path@@ -1932,3 +1934,311 @@ def test_user_and_team_chunks_report_progress_despite_a_failed_row(assert client.fetches_by_table[table_name] == 2assert len(_batch_writes(client, table_name, op="update")) == 2assert [call["call_type"] for call in logging_obj.service_logging_obj.failure_calls] == [call_type]+++class FlakyPrismaClient(MockPrismaClient):+ """A client whose first N reads (or first N batch commits) fail with a+ transport error, and which records every reconnect attempt.+ """++ def __init__(self, *, read_failures: int = 0, commit_failures: int = 0, error: Exception | None = None):+ super().__init__()+ self.reconnect_reasons: List[str] = []+ self.read_attempts: int = 0+ self.commit_attempts: int = 0+ self._read_failures = read_failures+ self._commit_failures = commit_failures+ self._error = error or httpx.ConnectError("All connection attempts failed")++ outer = self+ original_batch = self.db.batch_++ def _batch_():+ batcher = original_batch()+ batch_commit = batcher.commit++ async def _maybe_failing_commit():+ outer.commit_attempts += 1+ if outer._commit_failures > 0:+ outer._commit_failures -= 1+ raise outer._error+ return await batch_commit()++ batcher.commit = _maybe_failing_commit+ return batcher++ self.db.batch_ = _batch_++ async def attempt_db_reconnect(self, *, reason, timeout_seconds=None, lock_timeout_seconds=None) -> bool:+ self.reconnect_reasons.append(reason)+ return True++ async def get_data(self, table_name, query_type, **kwargs):+ self.read_attempts += 1+ if self._read_failures > 0:+ self._read_failures -= 1+ raise self._error+ return await super().get_data(table_name, query_type, **kwargs)+++def _due_row(table: str, identifier: str):+ now = datetime.now(timezone.utc)+ id_field = {"key": "token", "user": "user_id", "team": "team_id"}[table]+ return type(+ "Row",+ (),+ {+ "spend": _DUE_ROW_SPEND,+ "budget_duration": "30d",+ "budget_reset_at": now - timedelta(seconds=1),+ id_field: identifier,+ },+ )+++ "phase, table_name, reason",+ [+ ("reset_budget_for_litellm_keys", "key", "reset_budget_read_keys_failure"),+ ("reset_budget_for_litellm_users", "user", "reset_budget_read_users_failure"),+ ("reset_budget_for_litellm_teams", "team", "reset_budget_read_teams_failure"),+ ],+ ids=["keys", "users", "teams"],+)+def test_transient_transport_error_on_read_reconnects_and_still_resets(phase, table_name, reason):+ """A dropped connection on the read must cost one reconnect-and-retry, not+ the whole tick (LIT-5372). Pre-fix the httpx.ConnectError was swallowed and+ the phase reset nothing until the next tick, 10 minutes later.+ """+ client = FlakyPrismaClient(read_failures=1)+ client.data[table_name] = [_due_row(table_name, "row-1")]+ job = ResetBudgetJob(proxy_logging_obj=MockProxyLogging(), prisma_client=client)++ asyncio.run(getattr(job, phase)())++ assert client.reconnect_reasons == [reason]+ assert len(_batch_writes(client, table_name, op="update")) == 1+++ "phase, table_name, reason",+ [+ ("reset_budget_for_litellm_keys", "key", "reset_budget_write_keys_failure"),+ ("reset_budget_for_litellm_users", "user", "reset_budget_write_users_failure"),+ ("reset_budget_for_litellm_teams", "team", "reset_budget_write_teams_failure"),+ ],+ ids=["keys", "users", "teams"],+)+def test_connect_error_on_write_reconnects_and_commits(phase, table_name, reason):+ """A ConnectError proves the commit never reached the database, so replaying+ it cannot double-apply anything: the rows still get reset on this tick.+ """+ client = FlakyPrismaClient(commit_failures=1)+ client.data[table_name] = [_due_row(table_name, "row-1")]+ job = ResetBudgetJob(proxy_logging_obj=MockProxyLogging(), prisma_client=client)++ asyncio.run(getattr(job, phase)())++ assert client.reconnect_reasons == [reason]+ assert client.commit_attempts == 2+ assert len(_batch_writes(client, table_name, op="update")) == 1++[email protected]("ambiguous_error_name", ["ReadError", "ReadTimeout"])+def test_ambiguous_transport_error_on_write_is_not_replayed(ambiguous_error_name):+ """A post-send transport error leaves the commit outcome unknown. Since the+ reset zeroes spend unconditionally, replaying it would erase spend accrued+ after a commit that actually landed, so only reads may retry these.+ """+ client = FlakyPrismaClient(+ commit_failures=1,+ error=getattr(httpx, ambiguous_error_name)("ambiguous"),+ )+ client.data["key"] = [_due_row("key", "tok-1")]+ job = ResetBudgetJob(proxy_logging_obj=MockProxyLogging(), prisma_client=client)++ asyncio.run(job.reset_budget_for_litellm_keys())++ assert client.reconnect_reasons == []+ assert client.commit_attempts == 1++[email protected]("ambiguous_error_name", ["ReadError", "ReadTimeout"])+def test_ambiguous_transport_error_on_read_still_retries(ambiguous_error_name):+ """Reads have nothing to double-apply, so the full transport class retries."""+ client = FlakyPrismaClient(read_failures=1, error=getattr(httpx, ambiguous_error_name)("ambiguous"))+ client.data["key"] = [_due_row("key", "tok-1")]+ job = ResetBudgetJob(proxy_logging_obj=MockProxyLogging(), prisma_client=client)++ asyncio.run(job.reset_budget_for_litellm_keys())++ assert client.reconnect_reasons == ["reset_budget_read_keys_failure"]+ assert len(_batch_writes(client, "key", op="update")) == 1+++def test_transport_error_on_budget_cascade_read_reconnects_and_commits():+ client = FlakyPrismaClient(read_failures=1)+ budget = _budget_row(budget_id="b-1", budget_duration="1d")+ client.data["budget"] = [budget]+ job = ResetBudgetJob(proxy_logging_obj=MockProxyLogging(), prisma_client=client)++ asyncio.run(job.reset_budget_for_litellm_budget_table())++ assert client.reconnect_reasons == ["reset_budget_read_budgets_failure"]+ assert [w["where"]["budget_id"] for w in _batch_writes(client, "budget", op="update_many")] == ["b-1"]+++def test_non_transport_error_still_surfaces_without_a_reconnect():+ """A UniqueViolationError means the DB is reachable and the statement was+ refused, so reconnecting would be pointless: the phase must fail as before.+ """+ client = FlakyPrismaClient(read_failures=1, error=prisma.errors.UniqueViolationError(MagicMock()))+ client.data["key"] = [_due_row("key", "tok-1")]+ job = ResetBudgetJob(proxy_logging_obj=MockProxyLogging(), prisma_client=client)++ asyncio.run(job.reset_budget_for_litellm_keys())++ assert client.reconnect_reasons == []+ assert client.read_attempts == 1+ assert _batch_writes(client, "key") == []+++def test_transport_error_that_outlives_the_reconnect_is_not_retried_forever():+ client = FlakyPrismaClient(read_failures=2)+ client.data["key"] = [_due_row("key", "tok-1")]+ job = ResetBudgetJob(proxy_logging_obj=MockProxyLogging(), prisma_client=client)++ asyncio.run(job.reset_budget_for_litellm_keys())++ assert client.reconnect_reasons == ["reset_budget_read_keys_failure"]+ assert client.read_attempts == 2+ assert _batch_writes(client, "key") == []+++def test_transport_error_on_window_read_reconnects_and_still_resets(monkeypatch):+ """The raw per-window queries are reads too, so a blip there must not cost+ the whole window-reset phase."""+ expired = (datetime.utcnow() - timedelta(minutes=5)).isoformat() + "Z"+ key_rows = [{"token": "sk-expired", "budget_limits": [{"budget_duration": "1d", "reset_at": expired}]}]+ job, prisma_client, _ = _make_reset_budget_windows_job(monkeypatch, key_rows=key_rows, team_rows=[])+ reconnect_reasons: List[str] = []+ good_query_raw = prisma_client.db.query_raw++ async def failing_once_query_raw(query: str, *args, **kwargs):+ if '"LiteLLM_VerificationToken"' in query and not reconnect_reasons:+ raise httpx.ConnectError("All connection attempts failed")+ return await good_query_raw(query, *args, **kwargs)++ async def record_reconnect(*, reason, timeout_seconds=None, lock_timeout_seconds=None) -> bool:+ reconnect_reasons.append(reason)+ return True++ prisma_client.db.query_raw = AsyncMock(side_effect=failing_once_query_raw)+ prisma_client.attempt_db_reconnect = record_reconnect++ asyncio.run(job.reset_budget_windows())++ assert reconnect_reasons == ["reset_budget_read_key_windows_failure"]+ prisma_client.db.litellm_verificationtoken.update.assert_awaited_once()+++def test_connect_error_on_window_write_reconnects_and_writes(monkeypatch):+ expired = (datetime.utcnow() - timedelta(minutes=5)).isoformat() + "Z"+ team_rows = [{"team_id": "team-expired", "budget_limits": [{"budget_duration": "1d", "reset_at": expired}]}]+ job, prisma_client, _ = _make_reset_budget_windows_job(monkeypatch, key_rows=[], team_rows=team_rows)+ reconnect_reasons: List[str] = []++ async def failing_once_update(**kwargs) -> None:+ if not reconnect_reasons:+ raise httpx.ConnectError("All connection attempts failed")++ async def record_reconnect(*, reason, timeout_seconds=None, lock_timeout_seconds=None) -> bool:+ reconnect_reasons.append(reason)+ return True++ prisma_client.db.litellm_teamtable.update = AsyncMock(side_effect=failing_once_update)+ prisma_client.attempt_db_reconnect = record_reconnect++ asyncio.run(job.reset_budget_windows())++ assert reconnect_reasons == ["reset_budget_write_team_windows_failure"]+ assert prisma_client.db.litellm_teamtable.update.await_count == 2+++_DUE_ROW_SPEND = 42.0+_SPEND_ACCRUED_AFTER_COMMIT = 7.5+++class AmbiguousCommitClient(MockPrismaClient):+ """A client whose batch commit lands in the database and only then fails in+ transit, so the caller cannot tell whether it committed.++ The queued spend-zero is applied to `key_spend`, and fresh usage accrues in+ the window between that landed commit and any replay, so a replay is+ observable as erased spend rather than merely as an extra commit.+ """++ def __init__(self, *, error: Exception, spend_accrued_after_commit: float):+ super().__init__()+ self.key_spend: float = _DUE_ROW_SPEND+ self.commit_attempts: int = 0+ self.reconnect_reasons: list[str] = []++ outer = self+ original_batch = self.db.batch_++ def _batch_():+ batcher = original_batch()+ batch_commit = batcher.commit++ async def _commit_then_lose_the_response():+ outer.commit_attempts += 1+ result = await batch_commit()+ for call in batcher.calls:+ if call["table"] == "key" and call["data"].get("spend") == 0:+ outer.key_spend = 0.0+ if outer.commit_attempts > 1:+ return result+ outer.key_spend += spend_accrued_after_commit+ raise error++ batcher.commit = _commit_then_lose_the_response+ return batcher++ self.db.batch_ = _batch_++ async def attempt_db_reconnect(self, *, reason, timeout_seconds=None, lock_timeout_seconds=None) -> bool:+ self.reconnect_reasons.append(reason)+ return True+++ "error, expected_commits, expected_spend, expected_reconnects",+ [+ (httpx.ReadError("response lost in transit"), 1, _SPEND_ACCRUED_AFTER_COMMIT, []),+ (httpx.ReadTimeout("response lost in transit"), 1, _SPEND_ACCRUED_AFTER_COMMIT, []),+ (httpx.ConnectError("never left the client"), 2, 0.0, ["reset_budget_write_keys_failure"]),+ ],+ ids=["read_error", "read_timeout", "connect_error_erasure_control"],+)+def test_ambiguous_commit_replay_does_not_erase_newly_accrued_spend(+ error, expected_commits, expected_spend, expected_reconnects+):+ """A reset zeroes spend unconditionally, so replaying a commit that already+ landed erases every dollar spent since it landed (LIT-5372 review finding).++ The `connect_error` case is the control: it is the one error class allowed+ to replay, and driving it through this same land-then-fail harness proves+ the spend assertion can actually observe an erasure. In production a+ ConnectError means the statements never reached the database, so its replay+ has nothing to erase.+ """+ client = AmbiguousCommitClient(error=error, spend_accrued_after_commit=_SPEND_ACCRUED_AFTER_COMMIT)+ client.data["key"] = [_due_row("key", "tok-1")]+ job = ResetBudgetJob(proxy_logging_obj=MockProxyLogging(), prisma_client=client)++ asyncio.run(job.reset_budget_for_litellm_keys())++ assert client.key_spend == expected_spend+ assert client.commit_attempts == expected_commits+ assert client.reconnect_reasons == expected_reconnectsdiff --git a/tests/test_litellm/proxy/db/test_exception_handler_reconnect_retry.py b/tests/test_litellm/proxy/db/test_exception_handler_reconnect_retry.pyindex ae0e1f845b0..0a25ed55e90 100644--- a/tests/test_litellm/proxy/db/test_exception_handler_reconnect_retry.py+++ b/tests/test_litellm/proxy/db/test_exception_handler_reconnect_retry.py@@ -14,7 +14,7 @@ from unittest.mock import AsyncMock, MagicMockimport httpximport pytest-from prisma.errors import UniqueViolationError+from prisma.errors import ClientNotConnectedError, UniqueViolationErrorsys.path.insert(0, os.path.abspath("../../.."))@@ -253,3 +253,45 @@ async def test_call_with_db_reconnect_retry_preserves_original_error_when_reconnassert exc_info.value is original_excassert exc_info.value.__cause__ is reconnect_excclient.attempt_db_reconnect.assert_awaited_once()++async def test_call_with_db_reconnect_retry_honors_narrowed_retry_safe_types():+ """A non-idempotent write can pass `retry_safe_error_types` to opt out of+ replaying post-send transport errors, whose commit outcome is unknown."""+ client = _make_client(attempt_db_reconnect_return=True)+ attempts = 0++ async def _factory():+ nonlocal attempts # rebind-ok: attempt counter for a two-call helper+ attempts += 1+ raise httpx.ReadError("ambiguous")++ with pytest.raises(httpx.ReadError):+ await call_with_db_reconnect_retry(+ client,+ _factory,+ reason="write_narrowed",+ retry_safe_error_types=(httpx.ConnectError,),+ )++ assert attempts == 1+ client.attempt_db_reconnect.assert_not_awaited()+++async def test_call_with_db_reconnect_retry_default_covers_every_transport_error():+ """Callers that don't narrow keep retrying anything+ `is_database_transport_error` accepts, not just the httpx types."""+ client = _make_client(attempt_db_reconnect_return=True)+ attempts = 0++ async def _factory():+ nonlocal attempts # rebind-ok: attempt counter for a two-call helper+ attempts += 1+ if attempts == 1:+ raise ClientNotConnectedError()+ return "ok"++ assert await call_with_db_reconnect_retry(client, _factory, reason="default_wide") == "ok"+ assert attempts == 2+ client.attempt_db_reconnect.assert_awaited_once()