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
perf(reset_budget_job): elect one sweeper per tick and bound the window scan (#36497)
Yassin Kortam66a89f5a6ef5
diff --git a/litellm/constants.py b/litellm/constants.pyindex 774df63de17..ebda5a4d244 100644--- a/litellm/constants.py+++ b/litellm/constants.py@@ -1537,6 +1537,11 @@ DEFAULT_CRON_JOB_LOCK_TTL_SECONDS: Final = int(os.getenv("DEFAULT_CRON_JOB_LOCK_PROXY_BUDGET_RESCHEDULER_MIN_TIME: Final = int(os.getenv("PROXY_BUDGET_RESCHEDULER_MIN_TIME", 597))RESET_BUDGET_JOB_BATCH_SIZE: Final = max(1, int(os.getenv("RESET_BUDGET_JOB_BATCH_SIZE", "500")))RESET_BUDGET_JOB_MAX_CHUNKS_PER_RUN: Final = max(1, int(os.getenv("RESET_BUDGET_JOB_MAX_CHUNKS_PER_RUN", "100")))+RESET_BUDGET_JOB_NAME: Final = "reset_budget_job"+# Comfortably longer than one PROXY_BUDGET_RESCHEDULER_MIN_TIME tick, so a healthy+# leader keeps the lease across its own run, and a crashed one strands the sweep for+# at most a single tick.+RESET_BUDGET_JOB_LOCK_TTL_SECONDS: Final[int] = 900PROXY_BATCH_POLLING_INTERVAL: Final = int(os.getenv("PROXY_BATCH_POLLING_INTERVAL", 3600))MAX_OBJECTS_PER_POLL_CYCLE: Final = max(1, int(os.getenv("MAX_OBJECTS_PER_POLL_CYCLE", 50)))MANAGED_OBJECT_STALENESS_CUTOFF_DAYS: Final = max(1, int(os.getenv("MANAGED_OBJECT_STALENESS_CUTOFF_DAYS", 7)))diff --git a/litellm/proxy/common_utils/reset_budget_job.py b/litellm/proxy/common_utils/reset_budget_job.pyindex b28b7291a4c..8fcb184b26a 100644--- a/litellm/proxy/common_utils/reset_budget_job.py+++ b/litellm/proxy/common_utils/reset_budget_job.py@@ -4,6 +4,7 @@ import timefrom collections.abc import Awaitable, Callable, Iterable, Mapping, Sequencefrom dataclasses import dataclassfrom datetime import datetime, timezone+from enum import Enumfrom types import MappingProxyTypefrom typing import Final, Literal, Protocol, TypeVar, assert_never@@ -14,7 +15,9 @@ from litellm.constants import (GLOBAL_PROXY_SPEND_CACHE_KEY,LITELLM_PROXY_BUDGET_NAME,RESET_BUDGET_JOB_BATCH_SIZE,+ RESET_BUDGET_JOB_LOCK_TTL_SECONDS,RESET_BUDGET_JOB_MAX_CHUNKS_PER_RUN,+ RESET_BUDGET_JOB_NAME,)from litellm.proxy._types import (DB_RETRY_SAFE_ERROR_TYPES,@@ -30,6 +33,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.db_transaction_queue.pod_lock_manager import PodLockManagerfrom litellm.proxy.db.exception_handler import call_with_db_reconnect_retryfrom litellm.proxy.utils import PrismaClient, ProxyLoggingfrom litellm.repositories.organization_repository import OrganizationRepository@@ -195,12 +199,94 @@ async def _run_phase_in_chunks(process_chunk: Callable[[], Awaitable[_ChunkOutcoreturn+@dataclass(frozen=True, slots=True)+class _LazyJson:+ """Serialize only if a log record is actually emitted.++ ``logger.debug("... %s", json.dumps(rows))`` evaluates the dump before the+ logger decides to drop the record, so a chunk of rows is serialized on the+ event loop on every tick at any log level. Passing this instead defers the+ work to the formatter.+ """++ value: object++ def __str__(self) -> str:+ return json.dumps(self.value, indent=4, default=str)+++class _Lease(Enum):+ """Whether this pod may sweep, and whether it owes a lock release."""++ LEADER = "leader"+ UNGUARDED = "unguarded"+ FOLLOWER = "follower"+++async def _write_key_windows(prisma_client: PrismaClient, row_id: str, payload: str) -> None:+ await VerificationTokenRepository(prisma_client).table.update(+ where={"token": row_id},+ data={"budget_limits": payload},+ )+++async def _write_team_windows(prisma_client: PrismaClient, row_id: str, payload: str) -> None:+ await TeamRepository(prisma_client).table.update(+ where={"team_id": row_id},+ data={"budget_limits": payload},+ )+++@dataclass(frozen=True, slots=True)+class _WindowSource:+ """A table whose rows carry their own per-window budget limits."""++ table: str+ id_column: str+ counter_prefix: str+ log_subject: str+ retry_subject: str+ write: Callable[[PrismaClient, str, str], Awaitable[None]]++ def page_query(self) -> str:+ """One keyset page, ordered by the primary key so the cursor never repeats a row.++ prisma-client-python cannot null-filter a ``Json?`` column (no DbNull /+ JsonNull sentinel, RobertCraigie/prisma-client-py#714), so the read stays+ raw SQL; the table and column names are module constants, never input.+ Writes still go through the ORM.+ """+ return (+ f'SELECT {self.id_column}, budget_limits FROM "{self.table}" '+ f"WHERE budget_limits IS NOT NULL AND {self.id_column} > $1 "+ f"ORDER BY {self.id_column} LIMIT $2"+ )+++_WINDOW_SOURCES: Final[tuple[_WindowSource, ...]] = (+ _WindowSource(+ table="LiteLLM_VerificationToken",+ id_column="token",+ counter_prefix="spend:key",+ log_subject="keys",+ retry_subject="key",+ write=_write_key_windows,+ ),+ _WindowSource(+ table="LiteLLM_TeamTable",+ id_column="team_id",+ counter_prefix="spend:team",+ log_subject="teams",+ retry_subject="team",+ write=_write_team_windows,+ ),+)++def _budget_cascade_event_metadata(cascade: _BudgetCascade) -> dict[str, object]:return {"num_budgets_found": len(cascade.budgets),- "budgets_found": json.dumps(cascade.budgets, indent=4, default=str),"num_endusers_found": len(cascade.endusers),- "endusers_found": json.dumps(cascade.endusers, indent=4, default=str),}@@ -214,10 +300,61 @@ class ResetBudgetJob:proxy_logging_obj: ProxyLogging,prisma_client: PrismaClient,reset_settings: BudgetResetSettings | None = None,+ pod_lock_manager: PodLockManager | None = None,):self.proxy_logging_obj: ProxyLogging = proxy_logging_objself.prisma_client: PrismaClient = prisma_clientself.reset_settings: BudgetResetSettings = reset_settings or get_budget_reset_settings()+ self.pod_lock_manager: PodLockManager | None = pod_lock_manager++ async def _lease_is_held(self, lock_manager: PodLockManager) -> bool:+ """True only when the lease is readable and someone holds it.++ An unreadable lock reports as unheld so the caller sweeps rather than+ skipping; being wrong here costs a duplicate sweep, and the alternative+ strands every expired budget at its cap.+ """+ if lock_manager.redis_cache is None:+ return False+ try:+ lock_key: Final = lock_manager.get_redis_lock_key(RESET_BUDGET_JOB_NAME)+ return bool(await lock_manager.redis_cache.async_get_cache(lock_key))+ except Exception as exc: # noqa: BLE001 # an unreadable lease must not strand the sweep+ verbose_proxy_logger.warning("Reset budget job: could not read the reset lease: %s", exc)+ return False++ async def _acquire_lease(self) -> _Lease:+ """Elect one sweeper per tick.++ Every pod schedules this job, and each one otherwise re-reads the whole+ due population and writes it back at the same calendar boundary, so a+ fleet multiplies one sweep's Postgres load by its replica count. A+ deployment with no Redis-backed lock manager runs unguarded, as it+ always has.+ """+ lock_manager: Final = self.pod_lock_manager+ if lock_manager is None or lock_manager.redis_cache is None:+ return _Lease.UNGUARDED++ if await lock_manager.acquire_lock(+ cronjob_id=RESET_BUDGET_JOB_NAME,+ ttl=RESET_BUDGET_JOB_LOCK_TTL_SECONDS,+ ):+ return _Lease.LEADER++ if await self._lease_is_held(lock_manager):+ verbose_proxy_logger.debug("Reset budget job: another pod holds the reset lease, skipping this tick")+ return _Lease.FOLLOWER++ # acquire_lock reports contention and an unreachable Redis identically, so+ # treating a failed acquire as contention would skip the sweep on every pod+ # at once for as long as Redis is down. Sweeping unguarded costs duplicate+ # work; not sweeping leaves every expired budget pinned at its cap.+ verbose_proxy_logger.warning(+ "Reset budget job: could not take the reset lease and no other pod holds it, "+ "sweeping unguarded rather than skipping the tick"+ )+ return _Lease.UNGUARDEDasync def reset_budget(self,@@ -228,15 +365,25 @@ class ResetBudgetJob:Resets their spendUpdates db++ Runs on one pod per tick where a Redis lease is available."""if self.prisma_client is None:return- await self.reset_budget_for_litellm_keys()- await self.reset_budget_for_litellm_users()- await self.reset_budget_for_litellm_teams()- await self.reset_budget_for_litellm_budget_table()- await self.reset_budget_windows()+ lease: Final = await self._acquire_lease()+ if lease is _Lease.FOLLOWER:+ return++ try:+ await self.reset_budget_for_litellm_keys()+ await self.reset_budget_for_litellm_users()+ await self.reset_budget_for_litellm_teams()+ await self.reset_budget_for_litellm_budget_table()+ await self.reset_budget_windows()+ finally:+ if lease is _Lease.LEADER and self.pod_lock_manager is not None:+ await self.pod_lock_manager.release_lock(cronjob_id=RESET_BUDGET_JOB_NAME)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@@ -647,7 +794,7 @@ class ResetBudgetJob:),reason="reset_budget_read_keys_failure",)- verbose_proxy_logger.debug("Keys to reset %s", json.dumps(keys_to_reset, indent=4, default=str))+ verbose_proxy_logger.debug("Keys to reset %s", _LazyJson(keys_to_reset))updated_keys: Final[list[LiteLLM_VerificationToken]] = []failed_keys: Final = []if keys_to_reset is not None and len(keys_to_reset) > 0:@@ -666,7 +813,7 @@ class ResetBudgetJob:failed_keys.append({"key": key, "error": str(e)})verbose_proxy_logger.exception("Failed to reset budget for key: %s", key)- verbose_proxy_logger.debug("Updated keys %s", json.dumps(updated_keys, indent=4, default=str))+ verbose_proxy_logger.debug("Updated keys %s", _LazyJson(updated_keys))if updated_keys:await self._write_key_reset_updates(updated_keys=updated_keys)@@ -691,7 +838,6 @@ class ResetBudgetJob:end_time=end_time,event_metadata={"num_keys_found": len(keys_to_reset) if keys_to_reset else 0,- "keys_found": json.dumps(keys_to_reset, indent=4, default=str),},)return outcome@@ -705,11 +851,8 @@ class ResetBudgetJob:end_time=end_time,event_metadata={"num_keys_found": len(keys_to_reset) if keys_to_reset else 0,- "keys_found": json.dumps(keys_to_reset, indent=4, default=str),"num_keys_updated": len(updated_keys),- "keys_updated": json.dumps(updated_keys, indent=4, default=str),"num_keys_failed": len(failed_keys),- "keys_failed": json.dumps(failed_keys, indent=4, default=str),},))@@ -725,7 +868,6 @@ class ResetBudgetJob:end_time=end_time,event_metadata={"num_keys_found": len(keys_to_reset) if keys_to_reset else 0,- "keys_found": json.dumps(keys_to_reset, indent=4, default=str),},))@@ -777,7 +919,7 @@ class ResetBudgetJob:failed_users.append({"user": user, "error": str(e)})verbose_proxy_logger.exception("Failed to reset budget for user: %s", user)- verbose_proxy_logger.debug("Updated users %s", json.dumps(updated_users, indent=4, default=str))+ verbose_proxy_logger.debug("Updated users %s", _LazyJson(updated_users))if updated_users:await self._write_user_reset_updates(updated_users=updated_users)for u in updated_users:@@ -805,7 +947,6 @@ class ResetBudgetJob:end_time=end_time,event_metadata={"num_users_found": len(users_to_reset) if users_to_reset else 0,- "users_found": json.dumps(users_to_reset, indent=4, default=str),},)return outcome@@ -819,11 +960,8 @@ class ResetBudgetJob:end_time=end_time,event_metadata={"num_users_found": len(users_to_reset) if users_to_reset else 0,- "users_found": json.dumps(users_to_reset, indent=4, default=str),"num_users_updated": len(updated_users),- "users_updated": json.dumps(updated_users, indent=4, default=str),"num_users_failed": len(failed_users),- "users_failed": json.dumps(failed_users, indent=4, default=str),},))@@ -839,7 +977,6 @@ class ResetBudgetJob:end_time=end_time,event_metadata={"num_users_found": len(users_to_reset) if users_to_reset else 0,- "users_found": json.dumps(users_to_reset, indent=4, default=str),},))@@ -891,7 +1028,7 @@ class ResetBudgetJob:failed_teams.append({"team": team, "error": str(e)})verbose_proxy_logger.exception("Failed to reset budget for team: %s", team)- verbose_proxy_logger.debug("Updated teams %s", json.dumps(updated_teams, indent=4, default=str))+ verbose_proxy_logger.debug("Updated teams %s", _LazyJson(updated_teams))if updated_teams:await self._write_team_reset_updates(updated_teams=updated_teams)for t in updated_teams:@@ -917,7 +1054,6 @@ class ResetBudgetJob:end_time=end_time,event_metadata={"num_teams_found": len(teams_to_reset) if teams_to_reset else 0,- "teams_found": json.dumps(teams_to_reset, indent=4, default=str),},)return outcome@@ -931,11 +1067,8 @@ class ResetBudgetJob:end_time=end_time,event_metadata={"num_teams_found": len(teams_to_reset) if teams_to_reset else 0,- "teams_found": json.dumps(teams_to_reset, indent=4, default=str),"num_teams_updated": len(updated_teams),- "teams_updated": json.dumps(updated_teams, indent=4, default=str),"num_teams_failed": len(failed_teams),- "teams_failed": json.dumps(failed_teams, indent=4, default=str),},))@@ -951,7 +1084,6 @@ class ResetBudgetJob:end_time=end_time,event_metadata={"num_teams_found": len(teams_to_reset) if teams_to_reset else 0,- "teams_found": json.dumps(teams_to_reset, indent=4, default=str),},))@@ -995,82 +1127,82 @@ class ResetBudgetJob:from litellm.proxy.proxy_server import spend_counter_cachenow: Final = datetime.utcnow()+ for source in _WINDOW_SOURCES:+ try:+ await self._reset_windows_for(source=source, now=now, spend_counter_cache=spend_counter_cache)+ except Exception as e:+ verbose_proxy_logger.exception("Failed to reset budget windows for %s: %s", source.log_subject, e)- # Note on raw SQL: prisma-client-python does not support null-filtering- # on `Json?` columns (no DbNull/JsonNull sentinel — see- # RobertCraigie/prisma-client-py#714). We use `query_raw` with- # `IS NOT NULL` so we don't materialize every key/team row on each- # tick of the reset job. Writes still go through the ORM.-- # --- Keys ---- try:- 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",+ async def _reset_windows_for(+ self,+ source: _WindowSource,+ now: datetime,+ spend_counter_cache: DualCache,+ ) -> None:+ """Walk one table's windowed rows a page at a time, to the end.++ Paging is what bounds the memory: the previous form pulled every row+ carrying budget_limits into one result set on every tick, which grows+ with the deployment's key count and is paid on the event loop.++ The walk deliberately has no per-run page cap. A cap has to remember+ where it stopped, and that position cannot live in the process: the+ lease is released after each sweep, so the next tick can elect a+ different pod whose own position is unset. It would restart at the first+ row and never reach the tail, pinning those windows at their cap for+ good. The cursor strictly advances, so the walk terminates on its own+ without needing a bound.+ """+ cursor = ""+ while True:+ next_cursor = await self._reset_window_page(+ source=source,+ cursor=cursor,+ now=now,+ spend_counter_cache=spend_counter_cache,)- for row in key_rows:- raw = row["budget_limits"]- if not raw:- continue- windows: list = raw if isinstance(raw, list) else json.loads(raw)- changed = False- for window in windows:- counter_key = f"spend:key:{row['token']}:window:{window['budget_duration']}"- if await ResetBudgetJob._reset_expired_window(- window,- counter_key,- spend_counter_cache,- now,- self.reset_settings,- ):- changed = True- if changed:- 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)+ if next_cursor is None:+ return+ cursor = next_cursor- # --- Teams ---- try:- 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"]- if not raw:- continue- windows = raw if isinstance(raw, list) else json.loads(raw)- changed = False- for window in windows:- counter_key = f"spend:team:{row['team_id']}:window:{window['budget_duration']}"- if await ResetBudgetJob._reset_expired_window(- window,- counter_key,- spend_counter_cache,- now,- self.reset_settings,- ):- changed = True- if changed:- 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)+ async def _reset_window_page(+ self,+ source: _WindowSource,+ cursor: str,+ now: datetime,+ spend_counter_cache: DualCache,+ ) -> str | None:+ """Reset one page of windows; return the next cursor, or None when drained."""+ rows: Final = await self._with_db_retry(+ lambda: self.prisma_client.db.query_raw(source.page_query(), cursor, RESET_BUDGET_JOB_BATCH_SIZE),+ reason=f"reset_budget_read_{source.retry_subject}_windows_failure",+ )+ for row in rows:+ raw = row["budget_limits"]+ if not raw:+ continue+ row_id: str = row[source.id_column]+ windows: list = raw if isinstance(raw, list) else json.loads(raw)+ changed = False+ for window in windows:+ counter_key = f"{source.counter_prefix}:{row_id}:window:{window['budget_duration']}"+ if await ResetBudgetJob._reset_expired_window(+ window,+ counter_key,+ spend_counter_cache,+ now,+ self.reset_settings,+ ):+ changed = True+ if changed:+ await self._with_db_write_retry(+ lambda: source.write(self.prisma_client, row_id, json.dumps(windows)),+ reason=f"reset_budget_write_{source.retry_subject}_windows_failure",+ )++ if len(rows) < RESET_BUDGET_JOB_BATCH_SIZE:+ return None+ return rows[-1][source.id_column]@staticmethodasync def _reset_budget_common(diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex 4b97cade7f0..448810a5931 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -8875,6 +8875,7 @@ class ProxyStartupEvent:proxy_logging_obj=proxy_logging_obj,prisma_client=prisma_client,reset_settings=get_budget_reset_settings(),+ pod_lock_manager=proxy_logging_obj.db_spend_update_writer.pod_lock_manager,)scheduler.add_job(diff --git a/tests/litellm_utils_tests/test_proxy_budget_reset.py b/tests/litellm_utils_tests/test_proxy_budget_reset.pyindex b13b7342c25..a188fcf9d72 100644--- a/tests/litellm_utils_tests/test_proxy_budget_reset.py+++ b/tests/litellm_utils_tests/test_proxy_budget_reset.py@@ -748,8 +748,9 @@ async def test_service_logger_keys_failure():) = proxy_logging_obj.service_logging_obj.async_service_failure_hook.call_argsevent_metadata = kwargs.get("event_metadata", {})assert event_metadata.get("num_keys_found") == len(keys)- keys_found_str = event_metadata.get("keys_found", "")- assert "key1" in keys_found_str+ # the row payload is deliberately absent: serializing every found row on the+ # event loop is what blocked auth on the sweeping pod+ assert "keys_found" not in event_metadata# Success hook should not be called.proxy_logging_obj.service_logging_obj.async_service_success_hook.assert_not_called()@@ -866,8 +867,7 @@ async def test_service_logger_users_failure():) = proxy_logging_obj.service_logging_obj.async_service_failure_hook.call_argsevent_metadata = kwargs.get("event_metadata", {})assert event_metadata.get("num_users_found") == len(users)- users_found_str = event_metadata.get("users_found", "")- assert "user1" in users_found_str+ assert "users_found" not in event_metadataproxy_logging_obj.service_logging_obj.async_service_success_hook.assert_not_called()@@ -983,8 +983,7 @@ async def test_service_logger_teams_failure():) = proxy_logging_obj.service_logging_obj.async_service_failure_hook.call_argsevent_metadata = kwargs.get("event_metadata", {})assert event_metadata.get("num_teams_found") == len(teams)- teams_found_str = event_metadata.get("teams_found", "")- assert "team1" in teams_found_str+ assert "teams_found" not in event_metadataproxy_logging_obj.service_logging_obj.async_service_success_hook.assert_not_called()@@ -1113,8 +1112,8 @@ async def test_service_logger_endusers_failure():event_metadata = kwargs.get("event_metadata", {})assert event_metadata.get("num_budgets_found") == len(budgets)assert event_metadata.get("num_endusers_found") == len(endusers)- endusers_found_str = event_metadata.get("endusers_found", "")- assert "user1" in endusers_found_str+ assert "endusers_found" not in event_metadata+ assert "budgets_found" not in event_metadataproxy_logging_obj.service_logging_obj.async_service_success_hook.assert_not_called()diff --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 c5bc4e29f81..8233b0d3864 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@@ -16,6 +16,11 @@ sys.path.insert(0, os.path.abspath("../../..")) # Adds the parent directory tofrom litellm.proxy._types import LiteLLM_VerificationTokenfrom litellm.proxy.common_utils import reset_budget_job as reset_budget_job_module+from litellm.constants import (+ PROXY_BUDGET_RESCHEDULER_MIN_TIME,+ RESET_BUDGET_JOB_LOCK_TTL_SECONDS,+ RESET_BUDGET_JOB_NAME,+)from litellm.proxy.common_utils.reset_budget_job import ResetBudgetJobfrom litellm.proxy.common_utils.timezone_utils import BudgetResetSettings@@ -1906,10 +1911,7 @@ def test_key_reset_keeps_paging_when_some_rows_in_a_chunk_fail(monkeypatch):assert client.fetches_by_table["key"] == 2assert [w["where"]["token"] for w in _batch_writes(client, "key", op="update")] == ["k1", "k2"]assert [call["call_type"] for call in logging_obj.service_logging_obj.failure_calls] == ["reset_budget_keys"]- assert set(logging_obj.service_logging_obj.failure_calls[0]["event_metadata"]) == {- "num_keys_found",- "keys_found",- }+ assert set(logging_obj.service_logging_obj.failure_calls[0]["event_metadata"]) == {"num_keys_found"}assert [call["call_type"] for call in logging_obj.service_logging_obj.success_calls] == ["reset_budget_keys"]@@ -1936,6 +1938,352 @@ def test_user_and_team_chunks_report_progress_despite_a_failed_row(assert [call["call_type"] for call in logging_obj.service_logging_obj.failure_calls] == [call_type]+class FakePodLockManager:+ """Stands in for the redis-backed PodLockManager.++ Lets a test pick which of the three states a pod lands in: it wins the+ lease, another pod already holds it, or redis cannot answer at all.+ """++ def __init__(self, *, acquired: bool, held_by_other: bool = False, has_redis: bool = True):+ self.redis_cache = MagicMock() if has_redis else None+ if self.redis_cache is not None:+ self.redis_cache.async_get_cache = AsyncMock(return_value="another-pod" if held_by_other else None)+ self._acquired = acquired+ self.acquire_calls: List[Dict[str, Any]] = []+ self.release_calls: List[str] = []++ @staticmethod+ def get_redis_lock_key(cronjob_id: str) -> str:+ return f"cronjob_lock:{cronjob_id}"++ async def acquire_lock(self, cronjob_id: str, ttl: Any = None) -> bool:+ self.acquire_calls.append({"cronjob_id": cronjob_id, "ttl": ttl})+ return self._acquired++ async def release_lock(self, cronjob_id: str) -> None:+ self.release_calls.append(cronjob_id)+++def _make_leader_election_job(monkeypatch, pod_lock_manager):+ """A ResetBudgetJob wired to one lock manager, with every read observable.++ `prisma_client.get_data_calls` plus `prisma_client.db.query_raw` together+ cover every read the sweep makes, so a pod that skipped the tick leaves+ both untouched.+ """+ prisma_client = MockPrismaClient()+ prisma_client.db.query_raw = AsyncMock(return_value=[])++ spend_counter_cache = MagicMock()+ spend_counter_cache.redis_cache = None+ fake_module = types.ModuleType("litellm.proxy.proxy_server")+ fake_module.spend_counter_cache = spend_counter_cache+ monkeypatch.setitem(sys.modules, "litellm.proxy.proxy_server", fake_module)++ job = ResetBudgetJob(+ proxy_logging_obj=MockProxyLogging(),+ prisma_client=prisma_client,+ pod_lock_manager=pod_lock_manager,+ )+ return job, prisma_client+++def _swept(prisma_client) -> bool:+ return bool(prisma_client.get_data_calls) or prisma_client.db.query_raw.await_count > 0+++def test_reset_budget_sweeps_and_releases_when_it_wins_the_lease(monkeypatch):+ """The elected pod does the work and hands the lease back, so the next tick+ can elect any pod rather than waiting out the TTL."""+ lock = FakePodLockManager(acquired=True)+ job, prisma_client = _make_leader_election_job(monkeypatch, lock)++ asyncio.run(job.reset_budget())++ assert _swept(prisma_client)+ assert [call["cronjob_id"] for call in lock.acquire_calls] == [RESET_BUDGET_JOB_NAME]+ assert lock.release_calls == [RESET_BUDGET_JOB_NAME]+++def test_reset_budget_does_nothing_when_another_pod_holds_the_lease(monkeypatch):+ """The whole point of the lease: a fleet must not multiply one sweep by its+ replica count. A pod that loses the election issues no query at all, and+ must not release a lease it never took."""+ lock = FakePodLockManager(acquired=False, held_by_other=True)+ job, prisma_client = _make_leader_election_job(monkeypatch, lock)++ asyncio.run(job.reset_budget())++ assert not _swept(prisma_client)+ assert lock.release_calls == []+++def test_reset_budget_sweeps_unguarded_when_redis_cannot_answer(monkeypatch):+ """acquire_lock reports contention and an unreachable redis identically, so+ reading a failed acquire as contention would strand every expired budget at+ its cap on every pod for as long as redis is down. No holder means sweep."""+ lock = FakePodLockManager(acquired=False, held_by_other=False)+ job, prisma_client = _make_leader_election_job(monkeypatch, lock)++ asyncio.run(job.reset_budget())++ assert _swept(prisma_client)+ assert lock.release_calls == []+++def test_reset_budget_sweeps_when_the_deployment_has_no_redis(monkeypatch):+ """A single-pod or redis-less deployment keeps its pre-election behavior."""+ lock = FakePodLockManager(acquired=False, has_redis=False)+ job, prisma_client = _make_leader_election_job(monkeypatch, lock)++ asyncio.run(job.reset_budget())++ assert _swept(prisma_client)+ assert lock.acquire_calls == []+ assert lock.release_calls == []+++def test_reset_budget_sweeps_when_no_lock_manager_is_injected(monkeypatch):+ """Callers that construct the job without a lock manager still sweep."""+ job, prisma_client = _make_leader_election_job(monkeypatch, None)++ asyncio.run(job.reset_budget())++ assert _swept(prisma_client)+++def test_reset_budget_releases_the_lease_when_a_phase_raises(monkeypatch):+ """A crash mid-sweep must not hold the lease for its whole TTL, which would+ stop every pod resetting budgets until it expired."""+ lock = FakePodLockManager(acquired=True)+ job, _ = _make_leader_election_job(monkeypatch, lock)++ async def boom() -> None:+ raise RuntimeError("phase exploded")++ monkeypatch.setattr(job, "reset_budget_for_litellm_keys", boom)++ with pytest.raises(RuntimeError):+ asyncio.run(job.reset_budget())++ assert lock.release_calls == [RESET_BUDGET_JOB_NAME]+++def test_reset_budget_lease_outlives_one_scheduler_tick(monkeypatch):+ """A lease shorter than the gap between ticks expires mid-sweep and lets a+ second pod start sweeping, which is the amplification the lease removes."""+ lock = FakePodLockManager(acquired=True)+ job, _ = _make_leader_election_job(monkeypatch, lock)++ asyncio.run(job.reset_budget())++ assert lock.acquire_calls[0]["ttl"] == RESET_BUDGET_JOB_LOCK_TTL_SECONDS+ assert RESET_BUDGET_JOB_LOCK_TTL_SECONDS > PROXY_BUDGET_RESCHEDULER_MIN_TIME+++def _window_row(source_id_column: str, row_id: str, reset_at: datetime) -> Dict[str, Any]:+ return {+ source_id_column: row_id,+ "budget_limits": [{"budget_duration": "1h", "reset_at": reset_at.isoformat(), "max_budget": 10}],+ }+++def _paginating_window_job(monkeypatch, pages_by_table: Dict[str, List[List[Dict[str, Any]]]]):+ """Serve each table a canned sequence of pages and record every query.++ Returns (job, calls) where calls is a list of (sql, cursor, limit).+ """+ prisma_client = MagicMock()+ remaining = {table: list(pages) for table, pages in pages_by_table.items()}+ calls: List[Dict[str, Any]] = []++ async def fake_query_raw(query: str, *args, **kwargs):+ table = "key" if '"LiteLLM_VerificationToken"' in query else "team"+ calls.append({"table": table, "sql": query, "cursor": args[0], "limit": args[1]})+ pages = remaining[table]+ return pages.pop(0) if pages else []++ prisma_client.db.query_raw = AsyncMock(side_effect=fake_query_raw)+ prisma_client.db.litellm_verificationtoken.update = AsyncMock(return_value=None)+ prisma_client.db.litellm_teamtable.update = AsyncMock(return_value=None)++ spend_counter_cache = MagicMock()+ spend_counter_cache.redis_cache = None+ fake_module = types.ModuleType("litellm.proxy.proxy_server")+ fake_module.spend_counter_cache = spend_counter_cache+ monkeypatch.setitem(sys.modules, "litellm.proxy.proxy_server", fake_module)++ job = ResetBudgetJob(proxy_logging_obj=MagicMock(), prisma_client=prisma_client)+ return job, calls+++def test_reset_budget_windows_pages_by_cursor_instead_of_reading_the_table(monkeypatch):+ """The window scan used to read every row carrying budget_limits in one+ statement, so its memory and its statement cost grew with the deployment's+ key count. It now walks pages, and each page resumes past the last row.+ """+ monkeypatch.setattr(reset_budget_job_module, "RESET_BUDGET_JOB_BATCH_SIZE", 2)+ past = datetime.utcnow() - timedelta(hours=2)+ job, calls = _paginating_window_job(+ monkeypatch,+ {+ "key": [+ [_window_row("token", "k1", past), _window_row("token", "k2", past)],+ [_window_row("token", "k3", past)],+ ],+ "team": [[]],+ },+ )++ asyncio.run(job.reset_budget_windows())++ key_calls = [call for call in calls if call["table"] == "key"]+ assert [call["cursor"] for call in key_calls] == ["", "k2"], "second page must resume past the last row read"+ assert {call["limit"] for call in key_calls} == {2}+ assert all("LIMIT $2" in call["sql"] for call in key_calls)+ # the short second page ends the scan; a third query would re-read forever+ assert len(key_calls) == 2+++def test_reset_budget_windows_pages_to_the_end_of_a_large_table(monkeypatch):+ """The scan must reach the last row within one tick.++ Capping the pages per run would need a resume position, and that position+ cannot live in the process: the lease is released after every sweep, so a+ later tick can elect a pod whose position is unset, restart at the first+ row, and leave the tail pinned at its cap forever. Paging alone bounds the+ memory, so the walk runs to completion instead.+ """+ monkeypatch.setattr(reset_budget_job_module, "RESET_BUDGET_JOB_BATCH_SIZE", 1)+ # the table needs far more pages than any per-run cap would allow, so a+ # capped walk stops short and only an uncapped one reaches the last row+ monkeypatch.setattr(reset_budget_job_module, "RESET_BUDGET_JOB_MAX_CHUNKS_PER_RUN", 3)+ past = datetime.utcnow() - timedelta(hours=2)+ rows = [_window_row("token", f"k{i:03d}", past) for i in range(1, 26)]+ job, visited = _cursor_paginating_window_job(monkeypatch, rows)++ asyncio.run(job.reset_budget_windows())++ assert visited == [f"k{i:03d}" for i in range(1, 26)], visited+++def test_reset_budget_windows_survives_one_table_failing(monkeypatch):+ """A broken key scan must not cost the team scan its sweep."""+ prisma_client = MagicMock()++ async def fake_query_raw(query: str, *args, **kwargs):+ if '"LiteLLM_VerificationToken"' in query:+ raise RuntimeError("key scan exploded")+ return []++ prisma_client.db.query_raw = AsyncMock(side_effect=fake_query_raw)+ spend_counter_cache = MagicMock()+ spend_counter_cache.redis_cache = None+ fake_module = types.ModuleType("litellm.proxy.proxy_server")+ fake_module.spend_counter_cache = spend_counter_cache+ monkeypatch.setitem(sys.modules, "litellm.proxy.proxy_server", fake_module)+ job = ResetBudgetJob(proxy_logging_obj=MagicMock(), prisma_client=prisma_client)++ asyncio.run(job.reset_budget_windows())++ queried = [call.args[0] for call in prisma_client.db.query_raw.await_args_list]+ assert any('"LiteLLM_TeamTable"' in sql for sql in queried)+++def test_row_payloads_stay_out_of_reset_job_event_metadata(monkeypatch):+ """Every found and updated row used to be JSON-serialized into the service+ hook's metadata on every chunk, on the event loop, whether or not any+ consumer read it. Only the counts are reported now."""+ client = ChunkedPrismaClient({"key": [[_key_row("k1"), _key_row("k2")]]})+ logging_obj = RecordingProxyLogging()+ job = ResetBudgetJob(proxy_logging_obj=logging_obj, prisma_client=client)++ _run_and_drain_hooks(job.reset_budget_for_litellm_keys)++ metadata = logging_obj.service_logging_obj.success_calls[0]["event_metadata"]+ assert metadata["num_keys_found"] == 2+ assert metadata["num_keys_updated"] == 2+ assert {"keys_found", "keys_updated", "keys_failed"}.isdisjoint(metadata)+ assert all(isinstance(value, int) for value in metadata.values()), metadata+++def test_debug_row_dump_is_deferred_until_a_record_is_emitted():+ """`logger.debug("%s", json.dumps(rows))` serializes before the logger drops+ the record, so the sweep paid for a full dump of every chunk at any log+ level. The wrapper defers the work to the formatter."""+ serialized = []++ class Tracked:+ def __repr__(self) -> str:+ serialized.append("serialized")+ return "tracked"++ lazy = reset_budget_job_module._LazyJson([Tracked()])+ assert serialized == [], "constructing the wrapper must not serialize"++ assert "tracked" in str(lazy)+ assert serialized == ["serialized"]+++def _cursor_paginating_window_job(monkeypatch, key_rows: List[Dict[str, Any]]):+ """Serve real keyset pages out of one ordered table, honouring the cursor.++ Unlike the canned-page helper above, this models the database: a page is+ whatever rows sort after the cursor, so a scan that forgets its cursor+ genuinely re-reads the same prefix.+ """+ prisma_client = MagicMock()+ ordered = sorted(key_rows, key=lambda r: r["token"])+ visited: List[str] = []++ async def fake_query_raw(query: str, *args, **kwargs):+ if '"LiteLLM_TeamTable"' in query:+ return []+ cursor, limit = args[0], args[1]+ page = [row for row in ordered if row["token"] > cursor][:limit]+ visited.extend(row["token"] for row in page)+ return page++ prisma_client.db.query_raw = AsyncMock(side_effect=fake_query_raw)+ prisma_client.db.litellm_verificationtoken.update = AsyncMock(return_value=None)+ prisma_client.db.litellm_teamtable.update = AsyncMock(return_value=None)++ spend_counter_cache = MagicMock()+ spend_counter_cache.redis_cache = None+ fake_module = types.ModuleType("litellm.proxy.proxy_server")+ fake_module.spend_counter_cache = spend_counter_cache+ monkeypatch.setitem(sys.modules, "litellm.proxy.proxy_server", fake_module)++ job = ResetBudgetJob(proxy_logging_obj=MagicMock(), prisma_client=prisma_client)+ return job, visited+++def test_every_tick_sweeps_the_whole_window_table_whichever_pod_won(monkeypatch):+ """Coverage must not depend on which pod was elected.++ The lease is released after each sweep, so consecutive ticks routinely run+ on different pods. A scan carrying a resume position in process memory would+ have a fresh pod start over at the first row, so rows past one run's reach+ would never be swept by anyone. Two independent job instances, standing in+ for two pods, must each cover the table end to end.+ """+ monkeypatch.setattr(reset_budget_job_module, "RESET_BUDGET_JOB_BATCH_SIZE", 2)+ monkeypatch.setattr(reset_budget_job_module, "RESET_BUDGET_JOB_MAX_CHUNKS_PER_RUN", 2)+ past = datetime.utcnow() - timedelta(hours=2)+ rows = [_window_row("token", f"k{i:03d}", past) for i in range(1, 12)]+ expected = [f"k{i:03d}" for i in range(1, 12)]++ pod_a, visited_a = _cursor_paginating_window_job(monkeypatch, rows)+ pod_b, visited_b = _cursor_paginating_window_job(monkeypatch, rows)++ asyncio.run(pod_a.reset_budget_windows())+ asyncio.run(pod_b.reset_budget_windows())++ assert visited_a == expected, visited_a+ assert visited_b == expected, visited_b++class FlakyPrismaClient(MockPrismaClient):"""A client whose first N reads (or first N batch commits) fail with atransport error, and which records every reconnect attempt.