Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

Merge branch 'litellm_window_spend_schema' into litellm_window_spend_writer

ryan-crabbe-berri4e22a5ef5a81
diff --cc litellm/proxy/common_utils/reset_budget_job.py
index 0fb82c75274,d065b062517..2bf5b7b9283
--- a/litellm/proxy/common_utils/reset_budget_job.py
+++ b/litellm/proxy/common_utils/reset_budget_job.py
@@@ -1,19 -1,29 +1,31 @@@
import asyncio
import json
+ import math
import time
- from collections.abc import Callable, Mapping, Sequence
+ from collections.abc import Awaitable, Callable, Iterable, Mapping, Sequence
+ from dataclasses import dataclass, field
-from datetime import datetime, timezone
+from datetime import datetime, timedelta, timezone
- from typing import Final, Literal, Protocol, TypeVar
+ from enum import Enum
+ from types import MappingProxyType
+ from typing import Final, Literal, Protocol, TypeVar, assert_never
import litellm
from litellm._logging import verbose_proxy_logger
from litellm.caching.dual_cache import DualCache
- from litellm.constants import GLOBAL_PROXY_SPEND_CACHE_KEY, LITELLM_PROXY_BUDGET_NAME
+ 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.litellm_core_utils.duration_parser import duration_in_seconds
from litellm.proxy._types import (
+ DB_RETRY_SAFE_ERROR_TYPES,
LiteLLM_BudgetTableFull,
LiteLLM_EndUserTable,
+ Litellm_EntityType,
LiteLLM_TeamTable,
LiteLLM_UserTable,
LiteLLM_VerificationToken,
@@@ -23,9 -33,12 +35,13 @@@ from litellm.proxy.common_utils.timezon
compute_budget_reset_at,
get_budget_reset_settings,
)
+ from litellm.proxy.common_utils.user_api_key_cache import tag_cache_key
+from litellm.proxy.db.budget_window_spend_writer import roll_window_spend_row
+ from litellm.proxy.db.db_transaction_queue.pod_lock_manager import PodLockManager
+ from litellm.proxy.db.exception_handler import call_with_db_reconnect_retry
from litellm.proxy.utils import PrismaClient, ProxyLogging
from litellm.repositories.organization_repository import OrganizationRepository
+ from litellm.repositories.prisma_protocols import SpendLinkedTable
from litellm.repositories.table_repositories import (
EndUserRepository,
TagRepository,
@@@ -126,8 -150,230 +153,233 @@@ def _tag_counter_key(row: _TagRow) -> s
return f"spend:tag:{row.tag_name}"
- def _tag_cache_key(row: _TagRow) -> str:
- return f"tag:{row.tag_name}"
+ def _tag_cache_keys(row: _TagRow) -> tuple[str, ...]:
+ return (tag_cache_key(row.tag_name),)
+
+
+ def _budget_link_where(
+ budget_ids: Sequence[str],
+ extra: Mapping[str, object] = MappingProxyType({}),
+ ) -> dict[str, object]:
+ return {"budget_id": {"in": list(budget_ids)}, **extra}
+
+
+ def _queue_budget_linked_resets(
+ writes: LinkedSpendResetWrites,
+ cascade: "_BudgetCascade",
+ extra: Mapping[str, object] = MappingProxyType({}),
+ ) -> None:
+ """Reset one linked table's spend for every expiring tier: tiers with a
+ rollover cap keep spend beyond the cap (decrement preserves writes racing
+ the reset), everything else is zeroed as before. Zero the under-cap rows
+ BEFORE decrementing the over-cap ones: the statements run sequentially in
+ one transaction, so the reverse order lets the zero re-match a row the
+ decrement just moved into the (0, cap] range and erase its carried spend."""
+ for budget_id, cap in cascade.rollover_caps.items():
+ writes.queue_spend_zero(
+ where={"budget_id": budget_id, **extra, "spend": {"gt": 0, "lte": cap}}
+ ) # mutable-ok: prisma where filter must be a dict
+ writes.queue_spend_decrement(
+ where={"budget_id": budget_id, **extra, "spend": {"gt": cap}}, amount=cap
+ ) # mutable-ok: prisma where filter must be a dict
+ plain_ids: Final = tuple(bid for bid in cascade.budget_ids if bid not in cascade.rollover_caps)
+ if plain_ids:
+ writes.queue_spend_zero(where=_budget_link_where(plain_ids, extra))
+
+
+ def _queue_enduser_resets(writes: LinkedSpendResetWrites, cascade: "_BudgetCascade") -> None:
+ """End users are matched by id rather than budget link: rows with no
+ budget_id ride the default budget tier (litellm.max_end_user_budget_id).
+ Zero-before-decrement ordering matters here too (see
+ _queue_budget_linked_resets)."""
+ if not cascade.rollover_caps:
+ if cascade.endusers:
+ writes.queue_spend_zero(
+ where={"user_id": {"in": [row.user_id for row in cascade.endusers]}}
+ ) # mutable-ok: prisma where filter must be a dict
+ return
+ tiered: Final = tuple((row.budget_id or litellm.max_end_user_budget_id, row.user_id) for row in cascade.endusers)
+ for budget_id, cap in cascade.rollover_caps.items():
+ if not (
+ user_ids := [uid for bid, uid in tiered if bid == budget_id]
+ ): # mutable-ok: prisma "in" filter takes a list
+ continue
+ writes.queue_spend_zero(
+ where={"user_id": {"in": user_ids}, "spend": {"lte": cap}}
+ ) # mutable-ok: prisma where filter must be a dict
+ writes.queue_spend_decrement(
+ where={"user_id": {"in": user_ids}, "spend": {"gt": cap}}, amount=cap
+ ) # mutable-ok: prisma where filter must be a dict
+ plain: Final = [
+ uid for bid, uid in tiered if bid is None or bid not in cascade.rollover_caps
+ ] # mutable-ok: prisma "in" filter takes a list
+ if plain:
+ writes.queue_spend_zero(where={"user_id": {"in": plain}}) # mutable-ok: prisma where filter must be a dict
+
+
+ @dataclass(frozen=True, slots=True)
+ class _BudgetCascade:
+ """Everything one budget-tier reset touches, resolved before any write."""
+
+ budgets: tuple[LiteLLM_BudgetTableFull, ...] = ()
+ budget_ids: tuple[str, ...] = ()
+ budget_resets: tuple[tuple[str, datetime], ...] = ()
+ endusers: tuple[_EndUserRow, ...] = ()
+ counter_resets: tuple[tuple[str, float], ...] = ()
+ cache_keys: tuple[str, ...] = ()
+ rollover_caps: Mapping[str, float] = field(default_factory=lambda: MappingProxyType({}))
+
+
+ @dataclass(frozen=True, slots=True)
+ class _BudgetCascadeCommitted:
+ cascade: _BudgetCascade
+ advanced: int
+
+
+ @dataclass(frozen=True, slots=True)
+ class _BudgetCascadeFailed:
+ cascade: _BudgetCascade
+ error: Exception
+
+
+ _EMPTY_CASCADE: Final = _BudgetCascade()
+
+
+ @dataclass(frozen=True, slots=True)
+ class _ChunkOutcome:
+ """One chunk of a reset phase: rows read, and rows whose new budget_reset_at
+ cleared the due cutoff. Anything else is still due and would come straight
+ back on the next fetch, so it is not progress."""
+
+ fetched: int
+ advanced: int
+
+
+ _NO_PROGRESS: Final = _ChunkOutcome(fetched=0, advanced=0)
+
+
+ def _as_utc(moment: datetime) -> datetime:
+ return moment if moment.tzinfo is not None else moment.replace(tzinfo=timezone.utc)
+
+
+ def _count_advanced(reset_ats: Iterable[object], cutoff: datetime) -> int:
+ """How many rows the write actually moved past the due cutoff.
+
+ A budget_duration of "0s" (or one the parser cannot read) resolves to the
+ current time, so the row is written and stays due. Counting it as progress
+ would re-read the same chunk until the per-run cap on every tick.
+ """
+ utc_cutoff: Final = _as_utc(cutoff)
+ return sum(1 for reset_at in reset_ats if isinstance(reset_at, datetime) and _as_utc(reset_at) > utc_cutoff)
+
+
+ def _phase_is_drained(outcome: _ChunkOutcome) -> bool:
+ """A short chunk means the due rows ran out. A full chunk that advanced
+ nothing would be re-read unchanged forever, so it ends the phase too and
+ those rows wait for the next tick."""
+ return outcome.fetched < RESET_BUDGET_JOB_BATCH_SIZE or outcome.advanced == 0
+
+
+ async def _run_phase_in_chunks(process_chunk: Callable[[], Awaitable[_ChunkOutcome]]) -> None:
+ """Drive one reset phase a chunk at a time, capped so a single run cannot
+ spin unbounded: leftovers are picked up by the next tick."""
+ for _ in range(RESET_BUDGET_JOB_MAX_CHUNKS_PER_RUN):
+ if _phase_is_drained(await process_chunk()):
+ return
+
+
+ @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
++ entity_type: Litellm_EntityType
+ 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",
++ entity_type=Litellm_EntityType.KEY,
+ counter_prefix="spend:key",
+ log_subject="keys",
+ retry_subject="key",
+ write=_write_key_windows,
+ ),
+ _WindowSource(
+ table="LiteLLM_TeamTable",
+ id_column="team_id",
++ entity_type=Litellm_EntityType.TEAM,
+ 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),
+ "num_endusers_found": len(cascade.endusers),
+ }
class ResetBudgetJob:
@@@ -796,62 -1218,39 +1227,84 @@@
reset_at: Final = datetime.fromisoformat(reset_at_str.replace("Z", "+00:00")).replace(tzinfo=None)
if reset_at > now:
return False
- spend_counter_cache.in_memory_cache.set_cache(key=counter_key, value=0.0)
+ new_value: Final = await ResetBudgetJob._window_carried_spend(window, counter_key, spend_counter_cache)
+ spend_counter_cache.in_memory_cache.set_cache(key=counter_key, value=new_value)
if spend_counter_cache.redis_cache is not None:
try:
- await spend_counter_cache.redis_cache.async_set_cache(key=counter_key, value=0.0)
+ await spend_counter_cache.redis_cache.async_set_cache(key=counter_key, value=new_value)
except Exception as redis_err:
verbose_proxy_logger.warning("Failed to reset Redis counter %s: %s", counter_key, redis_err)
- window["reset_at"] = compute_budget_reset_at(
- budget_duration=window["budget_duration"], settings=reset_settings
- ).isoformat()
+ budget_duration: Final = window["budget_duration"]
+ next_reset_at: Final = compute_budget_reset_at(budget_duration=budget_duration, settings=reset_settings)
+ window["reset_at"] = next_reset_at.isoformat()
+ await ResetBudgetJob._roll_window_spend_row(
+ prisma_client=prisma_client,
+ entity_type=entity_type,
+ entity_id=entity_id,
+ budget_duration=budget_duration,
+ next_reset_at=next_reset_at,
+ )
return True
+ @staticmethod
+ async def _roll_window_spend_row(
+ prisma_client: PrismaClient,
+ entity_type: Litellm_EntityType,
+ entity_id: str,
+ budget_duration: str,
+ next_reset_at: datetime,
+ ) -> None:
+ """Move this window's LiteLLM_BudgetWindowSpend row onto the window
+ that just started, so the maintained total the read path uses starts
+ from zero alongside the counter.
+
+ Best effort: the row is an optimization over aggregating
+ LiteLLM_SpendLogs, so a failure here must not stop the remaining
+ windows from having their counters reset.
+ """
+ try:
+ window_start: Final = next_reset_at - timedelta(seconds=duration_in_seconds(budget_duration))
+ except Exception as e: # noqa: BLE001 # duration_in_seconds raises bare exceptions on bad input
+ verbose_proxy_logger.warning("Unparseable budget_duration %s: %s", budget_duration, e)
+ return
+ try:
+ await roll_window_spend_row(
+ prisma_client=prisma_client,
+ entity_type=entity_type.value,
+ entity_id=entity_id,
+ window_duration=budget_duration,
+ new_window_start=window_start,
+ )
+ except Exception as e: # noqa: BLE001 # the row is best effort; counter resets must still land
+ verbose_proxy_logger.warning(
+ "Failed to roll budget window spend row for %s=%s window=%s: %s",
+ entity_type.value,
+ entity_id,
+ budget_duration,
+ e,
+ )
+
+ @staticmethod
+ async def _window_carried_spend(
+ window: Mapping[str, object], counter_key: str, spend_counter_cache: DualCache
+ ) -> float:
+ """Per-window spend lives only in the counter, so the carried overage is
+ read from it before the reset overwrites it."""
+ if not _rollover_enabled():
+ return 0.0
+ window_max: Final = window.get("max_budget")
+ cap: Final = _rollover_cap(window_max) if isinstance(window_max, (int, float)) else None
+ if cap is None:
+ return 0.0
+ try:
+ current: Final = await spend_counter_cache.async_get_cache(key=counter_key)
+ except Exception as e: # noqa: BLE001 # an unreadable counter falls back to a plain zero reset
+ verbose_proxy_logger.warning("Failed to read spend counter %s for rollover: %s", counter_key, e)
+ return 0.0
+ if not isinstance(current, (int, float)):
+ return 0.0
+ return _carried_spend(float(current), cap)
+
async def reset_budget_windows(self) -> None:
"""
For keys and teams with budget_limits, reset any individual windows where
@@@ -861,76 -1260,82 +1314,85 @@@
from litellm.proxy.proxy_server import spend_counter_cache
now: 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.prisma_client.db.query_raw(
- 'SELECT token, budget_limits FROM "LiteLLM_VerificationToken" WHERE budget_limits IS NOT NULL'
+ 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,
- prisma_client=self.prisma_client,
- entity_type=Litellm_EntityType.KEY,
- entity_id=row["token"],
- ):
- changed = True
- if changed:
- await VerificationTokenRepository(self.prisma_client).table.update(
- where={"token": row["token"]},
- data={"budget_limits": json.dumps(windows)}, # type: ignore[arg-type]
- )
- 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.prisma_client.db.query_raw(
- 'SELECT team_id, budget_limits FROM "LiteLLM_TeamTable" WHERE budget_limits IS NOT NULL'
- )
- 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,
- prisma_client=self.prisma_client,
- entity_type=Litellm_EntityType.TEAM,
- entity_id=row["team_id"],
- ):
- changed = True
- if changed:
- await TeamRepository(self.prisma_client).table.update(
- where={"team_id": row["team_id"]},
- data={"budget_limits": json.dumps(windows)}, # type: ignore[arg-type]
- )
- 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[dict[str, object]] = 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,
++ prisma_client=self.prisma_client,
++ entity_type=source.entity_type,
++ entity_id=row_id,
+ ):
+ 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]
@staticmethod
async def _reset_budget_common(
diff --cc litellm/proxy/db/db_spend_update_writer.py
index 4e0137e33c6,3f2777ff1f3..193f41901cd
--- a/litellm/proxy/db/db_spend_update_writer.py
+++ b/litellm/proxy/db/db_spend_update_writer.py
@@@ -12,10 -12,8 +12,9 @@@ import o
import random
import time
import traceback
- from collections.abc import Mapping, Sequence
++from collections.abc import Sequence
from datetime import datetime, timedelta, timezone
- from types import MappingProxyType
- from typing import TYPE_CHECKING, Any, Final, Literal, cast, overload
+ from typing import TYPE_CHECKING, Any, Final, Literal, Protocol, cast, overload
import litellm
from litellm._logging import verbose_proxy_logger
@@@ -859,9 -913,17 +926,18 @@@ class DBSpendUpdateWriter
daily_org_spend_update_transactions,
daily_end_user_spend_update_transactions,
daily_agent_spend_update_transactions,
+ window_spend_update_transactions,
) = await self.redis_update_buffer.get_all_transactions_from_redis_buffer_pipeline()
+ uncommitted = { # mutable-ok: drives which popped categories still need re-queuing
+ "db_spend_update_transactions": db_spend_update_transactions,
+ "daily_spend_update_transactions": daily_spend_update_transactions,
+ "daily_team_spend_update_transactions": daily_team_spend_update_transactions,
+ "daily_org_spend_update_transactions": daily_org_spend_update_transactions,
+ "daily_end_user_spend_update_transactions": daily_end_user_spend_update_transactions,
+ "daily_agent_spend_update_transactions": daily_agent_spend_update_transactions,
+ }
+
if db_spend_update_transactions is not None:
verbose_proxy_logger.info(
"Spend tracking - committing spend updates from Redis to DB: "
@@@ -919,11 -988,7 +1002,12 @@@
proxy_logging_obj=proxy_logging_obj,
daily_spend_transactions=daily_agent_spend_update_transactions,
)
+ uncommitted.pop("daily_agent_spend_update_transactions", None)
+ if window_spend_update_transactions is not None:
+ await DBSpendUpdateWriter._commit_window_spend_updates(
+ prisma_client=prisma_client,
+ window_spend_transactions=window_spend_update_transactions,
+ )
except Exception as e:
spend_log_error(
"Spend tracking - failed to commit spend updates from Redis to DB. "
@@@ -1115,36 -1168,37 +1198,67 @@@
cronjob_id=DB_DAILY_TAG_SPEND_UPDATE_JOB_NAME,
)
+ @staticmethod
+ async def _commit_window_spend_updates(
+ prisma_client: PrismaClient,
+ window_spend_transactions: Sequence[WindowSpendTransaction],
+ ) -> None:
+ """
+ Commit per-budget-window spend increments to LiteLLM_BudgetWindowSpend.
+
+ Failures are logged rather than raised: these rows exist so budget
+ enforcement can stop aggregating LiteLLM_SpendLogs, and the read path
+ falls back to that aggregate, so a failed commit must not abort the
+ entity and daily spend commits that share this scheduler tick.
+ """
+ from litellm.proxy.db.budget_window_spend_writer import (
+ commit_window_spend_updates,
+ )
+
+ try:
+ await commit_window_spend_updates(
+ prisma_client=prisma_client,
+ transactions=window_spend_transactions,
+ )
+ except Exception as e: # noqa: BLE001 # any DB failure here must stay contained to the window rows
+ spend_log_error(
+ "Spend tracking - failed to commit budget window spend updates. %d window increments lost. Error: %s",
+ len(window_spend_transactions),
+ str(e),
+ exc=e,
+ )
+
+ async def _drain_and_commit_daily_tag_spend_from_redis(
+ self,
+ prisma_client: PrismaClient,
+ n_retry_times: int,
+ proxy_logging_obj: ProxyLogging,
+ ) -> None:
+ """
+ Drain the Redis tag spend buffer and commit it, restoring the drained transactions if the commit fails.
+
+ The drain is destructive, so a failed commit must push the transactions back for the next tick
+ or their spend is lost permanently.
+ """
+ daily_tag_spend_update_transactions: Final = (
+ await self.redis_update_buffer.get_all_daily_tag_spend_update_transactions_from_redis_buffer()
+ )
+ if not daily_tag_spend_update_transactions:
+ return
+
+ try:
+ await DBSpendUpdateWriter.update_daily_tag_spend(
+ n_retry_times=n_retry_times,
+ prisma_client=prisma_client,
+ proxy_logging_obj=proxy_logging_obj,
+ daily_spend_transactions=daily_tag_spend_update_transactions,
+ )
+ except Exception:
+ await self.redis_update_buffer.restore_transactions_to_redis(
+ daily_tag_spend_update_transactions=daily_tag_spend_update_transactions,
+ )
+ raise
+
async def _flush_tool_discovery_queue(
self,
prisma_client: PrismaClient,
diff --cc litellm/proxy/db/db_transaction_queue/redis_update_buffer.py
index d5786aa7088,ad92902221a..8c53c03031b
--- a/litellm/proxy/db/db_transaction_queue/redis_update_buffer.py
+++ b/litellm/proxy/db/db_transaction_queue/redis_update_buffer.py
@@@ -392,9 -424,59 +444,62 @@@ class RedisUpdateBuffer
if daily_txns:
await daily_queue.update_queue.put(daily_txns)
+ if window_spend_update_transactions and window_spend_update_queue is not None:
+ await window_spend_update_queue.update_queue.put(window_spend_update_transactions)
+
+ async def restore_transactions_to_redis(
+ self,
+ db_spend_update_transactions: DBSpendUpdateTransactions | None = None,
+ daily_spend_update_transactions: Mapping[str, BaseDailySpendTransaction] | None = None,
+ daily_team_spend_update_transactions: Mapping[str, BaseDailySpendTransaction] | None = None,
+ daily_org_spend_update_transactions: Mapping[str, BaseDailySpendTransaction] | None = None,
+ daily_end_user_spend_update_transactions: Mapping[str, BaseDailySpendTransaction] | None = None,
+ daily_agent_spend_update_transactions: Mapping[str, BaseDailySpendTransaction] | None = None,
+ daily_tag_spend_update_transactions: Mapping[str, BaseDailySpendTransaction] | None = None,
+ ) -> None:
+ """
+ Re-push transactions that were popped from Redis but not committed to the DB.
+
+ The leader drains the buffers with a destructive ``lpop`` before committing to
+ the database. When a commit fails after its retries are exhausted, the popped
+ transactions must be pushed back so a later scheduler tick can retry them;
+ otherwise the aggregated spend is lost permanently. The re-pushed payloads use
+ the same JSON encoding as the store path, so the next drain parses them normally.
+ """
+ if self.redis_cache is None:
+ return
+
+ restore_configs: Final = (
+ (db_spend_update_transactions, REDIS_UPDATE_BUFFER_KEY),
+ (daily_spend_update_transactions, REDIS_DAILY_SPEND_UPDATE_BUFFER_KEY),
+ (daily_team_spend_update_transactions, REDIS_DAILY_TEAM_SPEND_UPDATE_BUFFER_KEY),
+ (daily_org_spend_update_transactions, REDIS_DAILY_ORG_SPEND_UPDATE_BUFFER_KEY),
+ (daily_end_user_spend_update_transactions, REDIS_DAILY_END_USER_SPEND_UPDATE_BUFFER_KEY),
+ (daily_agent_spend_update_transactions, REDIS_DAILY_AGENT_SPEND_UPDATE_BUFFER_KEY),
+ (daily_tag_spend_update_transactions, REDIS_DAILY_TAG_SPEND_UPDATE_BUFFER_KEY),
+ )
+
+ rpush_list: Final = tuple(
+ RedisPipelineRpushOperation(key=redis_key, values=(safe_dumps(transactions),))
+ for transactions, redis_key in restore_configs
+ if transactions
+ )
+ if len(rpush_list) == 0:
+ return
+
+ try:
+ await self.redis_cache.async_rpush_pipeline(rpush_list=rpush_list)
+ verbose_proxy_logger.info(
+ "Spend tracking - restored %d uncommitted transaction set(s) to Redis for retry on next tick.",
+ len(rpush_list),
+ )
+ except RedisError as e:
+ verbose_proxy_logger.error(
+ "Spend tracking - failed to restore uncommitted transactions to Redis. "
+ "These spend updates are lost. Error: %s",
+ str(e),
+ )
+
@staticmethod
def _number_of_transactions_to_store_in_redis(
db_spend_update_transactions: DBSpendUpdateTransactions,
diff --cc litellm/proxy/proxy_server.py
index 9a28c274f92,3a70750528f..4bb2feff426
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@@ -348,10 -392,10 +392,13 @@@ from litellm.proxy.config_resolvers.ale
)
from litellm.proxy.container_endpoints.endpoints import router as container_router
from litellm.proxy.credential_endpoints.endpoints import router as credential_router
- from litellm.proxy.db.db_transaction_queue.spend_log_cleanup import SpendLogCleanup
+ from litellm.proxy.db.db_transaction_queue.spend_log_cleanup import (
+ SPEND_LOG_CLEANUP_BOUND_SETTINGS,
+ SpendLogCleanup,
+ )
+from litellm.proxy.db.db_transaction_queue.window_spend_update_queue import (
+ build_window_spend_transaction,
+)
from litellm.proxy.db.exception_handler import (
PrismaDBExceptionHandler,
call_with_db_reconnect_retry,
diff --cc tests/test_litellm/proxy/common_utils/test_reset_budget_job.py
index c7d31972d87,5d3afd95a55..6d362db3c76
--- a/tests/test_litellm/proxy/common_utils/test_reset_budget_job.py
+++ b/tests/test_litellm/proxy/common_utils/test_reset_budget_job.py
@@@ -625,269 -793,842 +793,982 @@@ def test_reset_budget_skips_null_budget
},
)
- asyncio.run(reset_budget_job.reset_budget_for_tags_linked_to_budgets(budgets_to_reset=[test_budget]))
+ mock_prisma_client.data["budget"] = [test_budget]
- calls = mock_prisma_client.db.litellm_tagtable.update_many_calls
- assert len(calls) == 1
- call = calls[0]
- assert call["where"]["budget_id"] == {"in": ["30d-tag-budget"]}
- assert call["where"]["spend"] == {"gt": 0}
- assert call["data"]["spend"] == 0
+ asyncio.run(reset_budget_job.reset_budget_for_litellm_budget_table())
+ # Should NOT have queried for NULL-budget-id end users
+ find_many_calls = mock_prisma_client.db.litellm_endusertable.find_many_calls
+ assert len(find_many_calls) == 0
- def test_reset_budget_for_tags_linked_to_budgets_empty(reset_budget_job, mock_prisma_client):
+ litellm.max_end_user_budget_id = None
+
+
+ # ---------------------------------------------------------------------------
+ # reset_budget_windows (per-key / per-team concurrent window resets)
+ # ---------------------------------------------------------------------------
+
+
+ def _make_reset_budget_windows_job(
+ monkeypatch,
+ key_rows: List[Dict[str, Any]],
+ team_rows: List[Dict[str, Any]],
+ ):
+ """Build a ResetBudgetJob with a fully-mocked prisma client and a fake
+ `litellm.proxy.proxy_server` module exposing a stub `spend_counter_cache`.
+
+ Returns (job, prisma_client_mock, spend_counter_cache_mock).
"""
- Test that when there are no budgets to reset, no update is performed
- on the tag table.
+ prisma_client = MagicMock()
+
+ async def fake_query_raw(query: str, *args, **kwargs):
+ # Dispatch by table name in the SQL so a single stub covers both calls.
+ if '"LiteLLM_VerificationToken"' in query:
+ return key_rows
+ if '"LiteLLM_TeamTable"' in query:
+ return team_rows
+ raise AssertionError(f"Unexpected query_raw call: {query}")
+
+ prisma_client.db.query_raw = AsyncMock(side_effect=fake_query_raw)
++ prisma_client.db.execute_raw = AsyncMock(return_value=1)
+ prisma_client.db.litellm_verificationtoken.update = AsyncMock(return_value=None)
+ prisma_client.db.litellm_teamtable.update = AsyncMock(return_value=None)
+
+ # Stub out litellm.proxy.proxy_server so the in-function
+ # `from litellm.proxy.proxy_server import spend_counter_cache` resolves
+ # without importing the real (heavy) module.
+ spend_counter_cache = MagicMock()
+ spend_counter_cache.in_memory_cache.set_cache = MagicMock()
+ spend_counter_cache.redis_cache = None # skip the async redis branch
+
+ 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, prisma_client, spend_counter_cache
+
+
+ def test_reset_budget_windows_uses_is_not_null_filter(monkeypatch):
+ """Regression guard for the Prisma client limitation documented in
+ RobertCraigie/prisma-client-py#714: `{"not": None}` on a `Json?` column
+ raises `MissingRequiredValueError`. We work around it by using `query_raw`
+ with `IS NOT NULL`. If someone reverts to the ORM filter, this test fails.
"""
- asyncio.run(reset_budget_job.reset_budget_for_tags_linked_to_budgets(budgets_to_reset=[]))
- calls = mock_prisma_client.db.litellm_tagtable.update_many_calls
- assert len(calls) == 0
+ job, prisma_client, _ = _make_reset_budget_windows_job(monkeypatch, key_rows=[], team_rows=[])
+
+ asyncio.run(job.reset_budget_windows())
+
+ queries = [call.args[0] for call in prisma_client.db.query_raw.await_args_list]
+ assert len(queries) == 2, queries
+ key_query, team_query = queries
+
+ assert '"LiteLLM_VerificationToken"' in key_query
+ assert "budget_limits IS NOT NULL" in key_query
+ assert '"LiteLLM_TeamTable"' in team_query
+ assert "budget_limits IS NOT NULL" in team_query
+
+
+ def test_reset_budget_windows_resets_expired_key_window(monkeypatch):
+ """A key whose window's `reset_at` has passed gets an update with a new
+ `reset_at` in the future, and the in-memory spend counter is cleared."""
+ now = datetime.utcnow()
+ expired = (now - timedelta(minutes=5)).isoformat() + "Z"
+
+ key_rows = [
+ {
+ "token": "sk-expired",
+ "budget_limits": [{"budget_duration": "1d", "reset_at": expired}],
+ }
+ ]
+ job, prisma_client, spend_counter_cache = _make_reset_budget_windows_job(
+ monkeypatch, key_rows=key_rows, team_rows=[]
+ )
+
+ asyncio.run(job.reset_budget_windows())
+
+ # Update should have been called exactly once with the expired token.
+ prisma_client.db.litellm_verificationtoken.update.assert_awaited_once()
+ call_kwargs = prisma_client.db.litellm_verificationtoken.update.await_args.kwargs
+ assert call_kwargs["where"] == {"token": "sk-expired"}
+
+ # The `budget_limits` payload is re-serialized JSON with a bumped reset_at.
+ written_windows = json.loads(call_kwargs["data"]["budget_limits"])
+ assert len(written_windows) == 1
+ new_reset_at = datetime.fromisoformat(written_windows[0]["reset_at"].replace("Z", "+00:00")).replace(tzinfo=None)
+ assert new_reset_at > now
+
+ # The spend counter for this key+window was cleared.
+ spend_counter_cache.in_memory_cache.set_cache.assert_any_call(key="spend:key:sk-expired:window:1d", value=0.0)
+
+
++def _window_spend_rolls(prisma_client):
++ return [
++ call.args
++ for call in prisma_client.db.execute_raw.await_args_list
++ if "LiteLLM_BudgetWindowSpend" in call.args[0]
++ ]
++
++
++def test_reset_budget_windows_rolls_the_key_window_spend_row(monkeypatch):
++ """The maintained per-window total has to start the new window at zero
++ alongside the counter, or enforcement keeps reading the old window's spend."""
++ now = datetime.utcnow()
++ expired = (now - 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=[])
++
++ asyncio.run(job.reset_budget_windows())
++
++ rolls = _window_spend_rolls(prisma_client)
++ assert len(rolls) == 1
++ query, entity_type, entity_id, window_duration, new_window_start, _updated_at = rolls[0]
++ assert (entity_type, entity_id, window_duration) == ("key", "sk-expired", "1d")
++ assert "spend = 0" in " ".join(query.split())
++
++ # window_start is the start of the window that just began: new reset_at minus the duration.
++ written_windows = json.loads(
++ prisma_client.db.litellm_verificationtoken.update.await_args.kwargs["data"]["budget_limits"]
++ )
++ new_reset_at = datetime.fromisoformat(written_windows[0]["reset_at"].replace("Z", "+00:00")).replace(tzinfo=None)
++ assert new_window_start == pytest.approx(
++ new_reset_at - timedelta(days=1),
++ abs=timedelta(seconds=1),
++ )
++
++
++def test_reset_budget_windows_roll_is_conditional_on_an_older_stored_window(monkeypatch):
++ """Another pod may already have rolled the row; clobbering it would drop
++ spend that landed under the new window."""
++ now = datetime.utcnow()
++ expired = (now - 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=[])
++
++ asyncio.run(job.reset_budget_windows())
++
++ query = " ".join(_window_spend_rolls(prisma_client)[0][0].split())
++ assert "AND window_start < ($4::timestamptz AT TIME ZONE 'UTC')" in query
++
++
++def test_reset_budget_windows_rolls_the_team_window_spend_row(monkeypatch):
++ now = datetime.utcnow()
++ expired = (now - timedelta(minutes=1)).isoformat() + "Z"
++
++ team_rows = [
++ {
++ "team_id": "team-expired",
++ "budget_limits": [{"budget_duration": "30d", "reset_at": expired}],
++ }
++ ]
++ job, prisma_client, _ = _make_reset_budget_windows_job(monkeypatch, key_rows=[], team_rows=team_rows)
++
++ asyncio.run(job.reset_budget_windows())
++
++ rolls = _window_spend_rolls(prisma_client)
++ assert len(rolls) == 1
++ assert rolls[0][1:4] == ("team", "team-expired", "30d")
++
++
++def test_reset_budget_windows_does_not_roll_an_unexpired_window(monkeypatch):
++ now = datetime.utcnow()
++ future = (now + timedelta(hours=1)).isoformat() + "Z"
++
++ key_rows = [
++ {
++ "token": "sk-future",
++ "budget_limits": [{"budget_duration": "1d", "reset_at": future}],
++ }
++ ]
++ job, prisma_client, _ = _make_reset_budget_windows_job(monkeypatch, key_rows=key_rows, team_rows=[])
++
++ asyncio.run(job.reset_budget_windows())
++
++ assert _window_spend_rolls(prisma_client) == []
++
++
++def test_reset_budget_windows_rolls_only_the_expired_window_of_a_key(monkeypatch):
++ now = datetime.utcnow()
++ key_rows = [
++ {
++ "token": "sk-mixed",
++ "budget_limits": [
++ {"budget_duration": "1d", "reset_at": (now - timedelta(minutes=5)).isoformat() + "Z"},
++ {"budget_duration": "30d", "reset_at": (now + timedelta(days=2)).isoformat() + "Z"},
++ ],
++ }
++ ]
++ job, prisma_client, _ = _make_reset_budget_windows_job(monkeypatch, key_rows=key_rows, team_rows=[])
++
++ asyncio.run(job.reset_budget_windows())
++
++ rolls = _window_spend_rolls(prisma_client)
++ assert [roll[3] for roll in rolls] == ["1d"]
++
++
++def test_reset_budget_windows_survives_a_failed_window_spend_roll(monkeypatch):
++ """The row is an optimization over aggregating LiteLLM_SpendLogs; a DB
++ failure there must not stop the counter reset from being persisted."""
++ now = datetime.utcnow()
++ expired = (now - timedelta(minutes=5)).isoformat() + "Z"
++
++ key_rows = [
++ {
++ "token": "sk-expired",
++ "budget_limits": [{"budget_duration": "1d", "reset_at": expired}],
++ }
++ ]
++ job, prisma_client, spend_counter_cache = _make_reset_budget_windows_job(
++ monkeypatch, key_rows=key_rows, team_rows=[]
++ )
++ prisma_client.db.execute_raw = AsyncMock(side_effect=Exception("connection reset"))
++
++ asyncio.run(job.reset_budget_windows())
++
++ prisma_client.db.litellm_verificationtoken.update.assert_awaited_once()
++ spend_counter_cache.in_memory_cache.set_cache.assert_any_call(key="spend:key:sk-expired:window:1d", value=0.0)
++
++
+ def test_reset_budget_windows_skips_unexpired_key_window(monkeypatch):
+ """If `reset_at` is in the future, no write should happen for that key."""
+ now = datetime.utcnow()
+ future = (now + timedelta(hours=1)).isoformat() + "Z"
+
+ key_rows = [
+ {
+ "token": "sk-future",
+ "budget_limits": [{"budget_duration": "1d", "reset_at": future}],
+ }
+ ]
+ job, prisma_client, _ = _make_reset_budget_windows_job(monkeypatch, key_rows=key_rows, team_rows=[])
+
+ asyncio.run(job.reset_budget_windows())
+
+ prisma_client.db.litellm_verificationtoken.update.assert_not_awaited()
+
+
+ def test_reset_budget_windows_resets_expired_team_window(monkeypatch):
+ """Same as the key test, but for teams."""
+ now = datetime.utcnow()
+ expired = (now - timedelta(minutes=1)).isoformat() + "Z"
+
+ team_rows = [
+ {
+ "team_id": "team-expired",
+ "budget_limits": [{"budget_duration": "30d", "reset_at": expired}],
+ }
+ ]
+ job, prisma_client, spend_counter_cache = _make_reset_budget_windows_job(
+ monkeypatch, key_rows=[], team_rows=team_rows
+ )
+
+ asyncio.run(job.reset_budget_windows())
+
+ prisma_client.db.litellm_teamtable.update.assert_awaited_once()
+ call_kwargs = prisma_client.db.litellm_teamtable.update.await_args.kwargs
+ assert call_kwargs["where"] == {"team_id": "team-expired"}
+ assert "budget_limits" in call_kwargs["data"]
+
+ spend_counter_cache.in_memory_cache.set_cache.assert_any_call(key="spend:team:team-expired:window:30d", value=0.0)
+
+
+ def test_reset_budget_windows_handles_string_budget_limits(monkeypatch):
+ """Defensive: if `query_raw` returns `budget_limits` as a JSON-encoded
+ string (driver-dependent), the code still parses and resets it.
+ """
+ now = datetime.utcnow()
+ expired = (now - timedelta(minutes=1)).isoformat() + "Z"
+
+ key_rows = [
+ {
+ "token": "sk-string-limits",
+ "budget_limits": json.dumps([{"budget_duration": "1d", "reset_at": expired}]),
+ }
+ ]
+ job, prisma_client, _ = _make_reset_budget_windows_job(monkeypatch, key_rows=key_rows, team_rows=[])
+
+ asyncio.run(job.reset_budget_windows())
+
+ prisma_client.db.litellm_verificationtoken.update.assert_awaited_once()
+
+
+ def test_reset_budget_windows_skips_row_with_empty_budget_limits(monkeypatch):
+ """A row whose `budget_limits` comes back as an empty/falsy payload
+ (shouldn't happen given the WHERE filter, but we guard anyway) must not
+ trigger an update or crash the loop."""
+ key_rows = [
+ {"token": "sk-empty-list", "budget_limits": []},
+ {"token": "sk-empty-str", "budget_limits": ""},
+ ]
+ job, prisma_client, _ = _make_reset_budget_windows_job(monkeypatch, key_rows=key_rows, team_rows=[])
+
+ asyncio.run(job.reset_budget_windows())
+
+ prisma_client.db.litellm_verificationtoken.update.assert_not_awaited()
+
+
+ def test_reset_budget_windows_query_error_does_not_break_team_path(monkeypatch):
+ """If the key query raises, the teams path still runs (and vice-versa).
+ Each side has its own try/except; this locks that in."""
+ now = datetime.utcnow()
+ expired = (now - timedelta(minutes=1)).isoformat() + "Z"
+
+ prisma_client = MagicMock()
+
+ async def fake_query_raw(query: str, *args, **kwargs):
+ if '"LiteLLM_VerificationToken"' in query:
+ raise RuntimeError("boom")
+ if '"LiteLLM_TeamTable"' in query:
+ return [
+ {
+ "team_id": "team-ok",
+ "budget_limits": [{"budget_duration": "1d", "reset_at": expired}],
+ }
+ ]
+ raise AssertionError(query)
+
+ prisma_client.db.query_raw = AsyncMock(side_effect=fake_query_raw)
+ prisma_client.db.litellm_teamtable.update = AsyncMock(return_value=None)
+
+ spend_counter_cache = MagicMock()
+ spend_counter_cache.in_memory_cache.set_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()) # must not raise
+
+ prisma_client.db.litellm_teamtable.update.assert_awaited_once()
+
+
+ # ---------------------------------------------------------------------------
+ # Counter invalidation on budget reset
+ # ---------------------------------------------------------------------------
+
+
+ def _make_counter_invalidation_job(monkeypatch):
+ """Stub spend_counter_cache (and user_api_key_cache) so we can observe
+ invalidation calls.
+
+ Both caches are looked up via ``from litellm.proxy.proxy_server import
+ <name>`` inside the reset job, so we publish them on a fake module.
+ """
+ spend_counter_cache = MagicMock()
+ spend_counter_cache.in_memory_cache.set_cache = MagicMock()
+ spend_counter_cache.redis_cache = MagicMock()
+ spend_counter_cache.redis_cache.async_set_cache = AsyncMock()
+
+ user_api_key_cache = MagicMock()
+ user_api_key_cache.async_delete_cache = AsyncMock()
+
+ fake_module = types.ModuleType("litellm.proxy.proxy_server")
+ fake_module.spend_counter_cache = spend_counter_cache
+ fake_module.user_api_key_cache = user_api_key_cache
+ monkeypatch.setitem(sys.modules, "litellm.proxy.proxy_server", fake_module)
+
+ spend_counter_cache.user_api_key_cache = user_api_key_cache
+ return spend_counter_cache
+
+
+ def test_reset_budget_for_keys_invalidates_redis_counter(reset_budget_job, mock_prisma_client, monkeypatch):
+ """Key budget reset must clear the Redis spend counter."""
+ counter_cache = _make_counter_invalidation_job(monkeypatch)
+
+ now = datetime.now(timezone.utc)
+ mock_prisma_client.data["key"] = [
+ type(
+ "Key",
+ (),
+ {
+ "spend": 100.0,
+ "budget_duration": "30d",
+ "budget_reset_at": now,
+ "id": "key-1",
+ "token": "sk-abc",
+ },
+ )
+ ]
+
+ asyncio.run(reset_budget_job.reset_budget_for_litellm_keys())
+
+ counter_cache.in_memory_cache.set_cache.assert_any_call(key="spend:key:sk-abc", value=0.0, ttl=60)
+
+
+ def test_reset_budget_for_users_invalidates_redis_counter(reset_budget_job, mock_prisma_client, monkeypatch):
+ """User budget reset must clear the Redis spend counter."""
+ counter_cache = _make_counter_invalidation_job(monkeypatch)
+ now = datetime.now(timezone.utc)
+ mock_prisma_client.data["user"] = [
+ type(
+ "User",
+ (),
+ {
+ "spend": 50.0,
+ "budget_duration": "7d",
+ "budget_reset_at": now,
+ "id": "user-1",
+ "user_id": "alice",
+ },
+ )
+ ]
- @pytest.mark.parametrize(
- "budget_duration, expected_day, expected_month",
- [
- ("30d", 1, 7), # 30d → 1st of next month
- ("1mo", 1, 7), # 1mo → 1st of next month
- ("1d", 16, 6), # 1d → next midnight (same month)
- ],
- ids=["30d-calendar-month", "1mo-calendar-month", "1d-next-midnight"],
- )
- def test_reset_budget_reset_at_date_calendar_aligned(budget_duration, expected_day, expected_month):
+ asyncio.run(reset_budget_job.reset_budget_for_litellm_users())
+
+ counter_cache.in_memory_cache.set_cache.assert_any_call(key="spend:user:alice", value=0.0, ttl=60)
+
+
+ def test_reset_budget_for_proxy_budget_row_invalidates_global_spend_cache(
+ reset_budget_job, mock_prisma_client, monkeypatch
+ ):
+ """Regression for LIT-4309: resetting the proxy-wide budget aggregate row
+ ("litellm-proxy-budget") must also drop the cached global-spend
+ accumulator ("{admin}:spend") that _global_proxy_budget_check enforces
+ against. Without the invalidation, the cached value survives the DB reset
+ and the global cap keeps blocking requests for the whole next window."""
+ counter_cache = _make_counter_invalidation_job(monkeypatch)
+
+ now = datetime.now(timezone.utc)
+ mock_prisma_client.data["user"] = [
+ type(
+ "User",
+ (),
+ {
+ "spend": 150.0,
+ "budget_duration": "30d",
+ "budget_reset_at": now,
+ "id": "row-1",
+ "user_id": "litellm-proxy-budget",
+ },
+ )
+ ]
+
+ asyncio.run(reset_budget_job.reset_budget_for_litellm_users())
+
+ counter_cache.user_api_key_cache.async_delete_cache.assert_any_call(key="default_user_id:spend")
+
+
+ def test_reset_budget_for_ordinary_user_does_not_touch_global_spend_cache(
+ reset_budget_job, mock_prisma_client, monkeypatch
+ ):
+ """The global-spend accumulator must only be dropped when the proxy
+ budget aggregate row itself resets, not on every user reset."""
+ counter_cache = _make_counter_invalidation_job(monkeypatch)
+
+ now = datetime.now(timezone.utc)
+ mock_prisma_client.data["user"] = [
+ type(
+ "User",
+ (),
+ {
+ "spend": 50.0,
+ "budget_duration": "7d",
+ "budget_reset_at": now,
+ "id": "user-1",
+ "user_id": "alice",
+ },
+ )
+ ]
+
+ asyncio.run(reset_budget_job.reset_budget_for_litellm_users())
+
+ assert not any(
+ call.kwargs.get("key") == "default_user_id:spend"
+ for call in counter_cache.user_api_key_cache.async_delete_cache.call_args_list
+ )
+
+
+ def test_reset_budget_for_teams_invalidates_redis_counter(reset_budget_job, mock_prisma_client, monkeypatch):
+ """Team budget reset must clear the Redis spend counter."""
+ counter_cache = _make_counter_invalidation_job(monkeypatch)
+
+ now = datetime.now(timezone.utc)
+ mock_prisma_client.data["team"] = [
+ type(
+ "Team",
+ (),
+ {
+ "spend": 200.0,
+ "budget_duration": "1mo",
+ "budget_reset_at": now,
+ "id": "team-1",
+ "team_id": "team-x",
+ },
+ )
+ ]
+
+ asyncio.run(reset_budget_job.reset_budget_for_litellm_teams())
+
+ counter_cache.in_memory_cache.set_cache.assert_any_call(key="spend:team:team-x", value=0.0, ttl=60)
+
+
+ def test_reset_does_not_zero_counter_when_db_write_fails(monkeypatch):
"""
- Verify that _reset_budget_reset_at_date produces calendar-aligned reset
- times (matching get_budget_reset_time), not sliding-window offsets.
+ Regression for #27730 (the bypass-half).
+
+ If the DB write inside the reset job raises (e.g. Prisma DataError on a
+ row carrying object_permission_id or budget_limits), the Redis spend
+ counter MUST NOT be zeroed — that would let get_current_spend admit
+ requests past the cap while the DB row still holds the over-budget
+ spend.
+
+ Pre-fix: _reset_budget_common pre-zeroed the counter before the DB
+ write attempt, opening the bypass window.
+ Post-fix: counter invalidation lives in the caller, AFTER the DB write
+ commits. If the write raises, the post-write invalidation never runs.
"""
- from unittest.mock import patch
+ counter_cache = _make_counter_invalidation_job(monkeypatch)
- # Fix "now" to 2023-06-15 10:30:00 UTC for deterministic results
- fixed_now = datetime(2023, 6, 15, 10, 30, 0, tzinfo=timezone.utc)
+ now = datetime.now(timezone.utc)
+ prisma_client = MagicMock()
- test_budget = type(
- "LiteLLM_BudgetTableFull",
+ matching_key = type(
+ "Key",
(),
{
- "budget_duration": budget_duration,
- "budget_reset_at": fixed_now - timedelta(hours=1),
- "budget_id": "test-budget",
- "created_at": fixed_now - timedelta(days=30),
+ "spend": 100.0,
+ "budget_duration": "30d",
+ "budget_reset_at": now - timedelta(seconds=1),
+ "token": "sk-failing",
+ },
+ )
+
+ # get_data returns one key needing reset; the batched DB write then explodes.
+ async def fake_get_data(table_name, query_type, **kwargs):
+ if table_name == "key":
+ return [matching_key]
+ return []
+
+ prisma_client.get_data = fake_get_data
+
+ batcher = MagicMock()
+ batcher.litellm_verificationtoken.update = MagicMock()
+
+ async def failing_commit():
+ raise RuntimeError("simulated Prisma DataError on update")
+
+ batcher.commit = failing_commit
+ prisma_client.db.batch_ = MagicMock(return_value=batcher)
+
+ job = ResetBudgetJob(proxy_logging_obj=MockProxyLogging(), prisma_client=prisma_client)
+
+ asyncio.run(job.reset_budget_for_litellm_keys())
+
+ # CRITICAL: counter invalidation must NOT have been called at all —
+ # the DB write raised before the post-write invalidation loop. Using
+ # assert_not_called() instead of iterating call_args_list, because the
+ # latter is vacuously true when the list is empty (would pass even if
+ # the bypass were re-introduced via a different code path).
+ counter_cache.in_memory_cache.set_cache.assert_not_called()
+
+
+ def test_reset_budget_for_keys_writes_only_spend_and_reset_at(reset_budget_job, mock_prisma_client):
+ """
+ Regression for #27730 (the trigger-half).
+
+ The reset job must write only {spend, budget_reset_at} per row — never
+ the full key object. Sending the full object via the old update_data
+ batcher path made Prisma reject any row carrying object_permission_id
+ or budget_limits (both became non-NULL on UI-created keys after v1.84.0).
+ """
+ now = datetime.now(timezone.utc)
+ key_with_problematic_fields = type(
+ "LiteLLM_VerificationToken",
+ (),
+ {
+ "spend": 50.0,
+ "budget_duration": "30d",
+ "budget_reset_at": now,
+ "token": "sk-problematic",
+ "object_permission_id": "perm-abc", # would be rejected on update
+ "budget_limits": [{"max_budget": 5}], # would be rejected on update
+ "metadata": {"some": "thing"},
},
)
+ mock_prisma_client.data["key"] = [key_with_problematic_fields]
+
+ asyncio.run(reset_budget_job.reset_budget_for_litellm_keys())
+
+ key_writes = [c for c in mock_prisma_client.db.batch_calls if c["table"] == "key"]
+ assert len(key_writes) == 1
+ payload_keys = set(key_writes[0]["data"].keys())
+ assert payload_keys == {"spend", "budget_reset_at"}, (
+ f"reset payload must not include any field besides spend / budget_reset_at, "
+ f"got: {payload_keys}. Any extra field (object_permission_id, budget_limits, etc.) "
+ f"trips Prisma DataError and detonates the whole batch."
+ )
+
+
+ _INVALIDATION_CASES = [
+ (
+ "litellm_teammembership",
+ type("Membership", (), {"user_id": "alice", "team_id": "team-x", "budget_id": "budget-1"}),
+ "spend:team_member:alice:team-x",
+ {"team-x_alice"},
+ ),
+ (
+ "litellm_verificationtoken",
+ type("Key", (), {"token": "sk-linked"}),
+ "spend:key:sk-linked",
+ {"sk-linked"},
+ ),
+ (
+ "litellm_organizationtable",
+ type("Org", (), {"organization_id": "org-acme"}),
+ "spend:org:org-acme",
+ {"org_id:org-acme", "org_id:org-acme:with_budget"},
+ ),
+ (
+ "litellm_tagtable",
+ type("Tag", (), {"tag_name": "tenant-42"}),
+ "spend:tag:tenant-42",
+ {"tag:tenant-42"},
+ ),
+ ]
+
+
+ @pytest.mark.parametrize(
+ "table_attr, linked_row, counter_key, cache_keys",
+ _INVALIDATION_CASES,
+ ids=["team_membership", "key", "org", "tag"],
+ )
+ def test_budget_table_reset_invalidates_counters_and_management_cache(
+ reset_budget_job, mock_prisma_client, monkeypatch, table_attr, linked_row, counter_key, cache_keys
+ ):
+ """Every row the cascade zeroes gets its spend counter cleared and its
+ management-cache entry dropped.
+
+ Both matter. ``SpendCounterReseed.from_db`` returns None for tags, so once
+ the counter expires the budget check falls back to the cached row's
+ ``.spend``; and for keys, orgs and team memberships another pod's cached
+ object can stay pinned above the zeroed DB row until its TTL. Team
+ membership cache keys follow auth's ``{team_id}_{user_id}`` shape, and orgs
+ carry both the plain and the ``:with_budget`` entry.
+ """
+ counter_cache = _make_counter_invalidation_job(monkeypatch)
+ mock_prisma_client.data["budget"] = [_budget_row(budget_id="budget-1")]
+ getattr(mock_prisma_client.db, table_attr).set_find_many_results([linked_row])
+
+ asyncio.run(reset_budget_job.reset_budget_for_litellm_budget_table())
+
+ counter_cache.in_memory_cache.set_cache.assert_any_call(key=counter_key, value=0.0, ttl=60)
+ counter_cache.redis_cache.async_set_cache.assert_any_await(key=counter_key, value=0.0, ttl=60)
+ deleted = {call.kwargs.get("key") for call in counter_cache.user_api_key_cache.async_delete_cache.await_args_list}
+ assert cache_keys <= deleted
+
+
+ def test_budget_table_reset_invalidates_every_tag_not_just_the_first(reset_budget_job, mock_prisma_client, monkeypatch):
+ """When several tags share the expiring tier, all of them are evicted."""
+ counter_cache = _make_counter_invalidation_job(monkeypatch)
+ mock_prisma_client.data["budget"] = [_budget_row(budget_id="budget-1")]
+ mock_prisma_client.db.litellm_tagtable.set_find_many_results(
+ [type("Tag", (), {"tag_name": name}) for name in ("tenant-a", "tenant-b", "tenant-c")]
+ )
+
+ asyncio.run(reset_budget_job.reset_budget_for_litellm_budget_table())
+
+ deleted = {call.kwargs.get("key") for call in counter_cache.user_api_key_cache.async_delete_cache.await_args_list}
+ assert deleted == {"tag:tenant-a", "tag:tenant-b", "tag:tenant-c"}
+
+
+ def test_budget_table_reset_commits_even_when_cache_eviction_fails(reset_budget_job, mock_prisma_client, monkeypatch):
+ """Eviction runs after the commit, so a broken cache cannot undo the write."""
+ counter_cache = _make_counter_invalidation_job(monkeypatch)
+ counter_cache.user_api_key_cache.async_delete_cache = AsyncMock(side_effect=RuntimeError("cache unavailable"))
+ mock_prisma_client.data["budget"] = [_budget_row(budget_id="budget-1")]
+ mock_prisma_client.db.litellm_tagtable.set_find_many_results([type("Tag", (), {"tag_name": "tenant-42"})])
+
+ asyncio.run(reset_budget_job.reset_budget_for_litellm_budget_table())
+
+ assert len(_batch_writes(mock_prisma_client, "tag", op="update_many")) == 1
+ assert mock_prisma_client.db.batchers[0].committed is True
+
+
+ # ---------------------------------------------------------------------------
+ # Atomicity of the budget-table cascade (LIT-5138)
+ # ---------------------------------------------------------------------------
+
+
+ class FailingCommitDB(MockDB):
+ """Batches that blow up at commit, like a Postgres timeout mid-cascade."""
+
+ def batch_(self):
+ batcher = super().batch_()
+
+ async def _fail():
+ raise RuntimeError("simulated Postgres timeout mid-cascade")
+
+ batcher.commit = _fail
+ return batcher
+
+
+ class FailingTeamMembershipDB(MockDB):
+ """Queueing the team-membership reset raises, i.e. the cascade breaks after
+ earlier writes are already queued."""
+
+ def batch_(self):
+ batcher = super().batch_()
+
+ def _fail(where, data):
+ raise RuntimeError("simulated failure queueing the team-membership reset")
+
+ batcher.litellm_teammembership.update_many = _fail
+ return batcher
+
+
+ class OrderRecordingDB(MockDB):
+ """Appends a marker to a shared list when a batch commits."""
+
+ def __init__(self, events):
+ super().__init__()
+ self._events = events
+
+ def batch_(self):
+ batcher = super().batch_()
+ wrapped = batcher.commit
+
+ async def _record_commit():
+ self._events.append("commit")
+ return await wrapped()
+
+ batcher.commit = _record_commit
+ return batcher
+
+
+ def _job_with_expired_budget(db, proxy_logging=None):
+ """A job with one due tier and a linked tag, so cache invalidation has
+ something to invalidate and its absence is a real signal."""
+ prisma_client = MockPrismaClient()
+ prisma_client.db = db
+ prisma_client.data["budget"] = [_budget_row(budget_id="budget-1", budget_duration="7d")]
+ db.litellm_tagtable.set_find_many_results([type("Tag", (), {"tag_name": "tenant-42"})])
+ job = ResetBudgetJob(
+ proxy_logging_obj=proxy_logging or MockProxyLogging(),
+ prisma_client=prisma_client,
+ )
+ return job, prisma_client
- with patch("litellm.proxy.common_utils.timezone_utils.datetime") as mock_dt:
- mock_dt.now.return_value = fixed_now
- mock_dt.side_effect = lambda *args, **kwargs: datetime(*args, **kwargs)
- asyncio.run(ResetBudgetJob._reset_budget_reset_at_date(test_budget, fixed_now, BudgetResetSettings()))
- assert test_budget.budget_reset_at.day == expected_day
- assert test_budget.budget_reset_at.month == expected_month
- assert test_budget.budget_reset_at.hour == 0
- assert test_budget.budget_reset_at.minute == 0
- assert test_budget.budget_reset_at.second == 0
+ @pytest.mark.parametrize(
+ "db_factory",
+ [FailingCommitDB, FailingTeamMembershipDB],
+ ids=["commit-fails", "queueing-fails"],
+ )
+ def test_budget_reset_at_is_not_advanced_when_the_cascade_fails(db_factory, monkeypatch):
+ """Regression for LIT-5138.
+
+ The old code committed the new budget_reset_at first and zeroed the
+ dependent spend afterwards. A failure part-way through left the tier
+ stamped for the next window, so every later tick skipped it and team
+ member / enduser / org / tag spend stayed at the cap for the whole window.
+ One transaction means a failure anywhere persists nothing and the tier is
+ still due on the next tick.
+ """
+ counter_cache = _make_counter_invalidation_job(monkeypatch)
+ job, prisma_client = _job_with_expired_budget(db_factory())
+ asyncio.run(job.reset_budget_for_litellm_budget_table()) # swallowed, retried next tick
- def test_reset_budget_reset_at_date_7d_next_monday():
- """Verify 7d budget duration resets to next Monday at midnight."""
- from unittest.mock import patch
+ assert prisma_client.db.batch_calls == [], "a failed cascade must not persist any write"
+ assert prisma_client.db.batchers[0].committed is False
+ assert prisma_client.updated_data["budget"] == [], "budget_reset_at must not be advanced outside the transaction"
+ counter_cache.in_memory_cache.set_cache.assert_not_called()
+ counter_cache.user_api_key_cache.async_delete_cache.assert_not_awaited()
- # 2023-06-14 is a Wednesday
- fixed_now = datetime(2023, 6, 14, 10, 30, 0, tzinfo=timezone.utc)
- test_budget = type(
- "LiteLLM_BudgetTableFull",
- (),
- {
- "budget_duration": "7d",
- "budget_reset_at": fixed_now - timedelta(hours=1),
- "budget_id": "test-budget",
- "created_at": fixed_now - timedelta(days=7),
- },
- )
+ def test_budget_cascade_writes_land_in_a_single_transaction(reset_budget_job, mock_prisma_client, monkeypatch):
+ """Dependent spend and the budget_reset_at advance ride one batch."""
+ _make_counter_invalidation_job(monkeypatch)
+ now = datetime.now(timezone.utc)
+ budget = _budget_row(budget_id="budget-1", budget_duration="7d")
+ mock_prisma_client.data["budget"] = [budget]
+ mock_prisma_client.data["enduser"] = [
+ type("EndUser", (), {"spend": 5.0, "litellm_budget_table": budget, "user_id": "enduser-1", "budget_id": "budget-1"})
+ ]
- with patch("litellm.proxy.common_utils.timezone_utils.datetime") as mock_dt:
- mock_dt.now.return_value = fixed_now
- mock_dt.side_effect = lambda *args, **kwargs: datetime(*args, **kwargs)
- asyncio.run(ResetBudgetJob._reset_budget_reset_at_date(test_budget, fixed_now, BudgetResetSettings()))
+ asyncio.run(reset_budget_job.reset_budget_for_litellm_budget_table())
- # Next Monday after Wednesday June 14 is June 19
- assert test_budget.budget_reset_at.day == 19
- assert test_budget.budget_reset_at.month == 6
- assert test_budget.budget_reset_at.weekday() == 0 # Monday
- assert test_budget.budget_reset_at.hour == 0
+ assert len(mock_prisma_client.db.batchers) == 1, "the cascade must not be split across transactions"
+ batcher = mock_prisma_client.db.batchers[0]
+ assert batcher.committed is True
+ assert {(call["table"], call["op"]) for call in batcher.calls} == {
+ ("team_membership", "update_many"),
+ ("key", "update_many"),
+ ("org", "update_many"),
+ ("tag", "update_many"),
+ ("enduser", "update_many"),
+ ("budget", "update_many"),
+ }
+ budget_write = next(call for call in batcher.calls if call["table"] == "budget")
+ assert budget_write["data"]["budget_reset_at"] > now
- def test_reset_budget_reset_at_date_none_duration():
- """Verify that budget_reset_at is unchanged when budget_duration is None."""
- original_reset_at = datetime(2023, 6, 20, 0, 0, 0, tzinfo=timezone.utc)
- now = datetime(2023, 6, 15, 10, 0, 0, tzinfo=timezone.utc)
+ def test_caches_are_invalidated_only_after_the_transaction_commits(monkeypatch):
+ """A counter zeroed before the write lands would admit requests past the
+ cap while the DB still holds the over-budget spend."""
+ events = []
+ counter_cache = _make_counter_invalidation_job(monkeypatch)
+ counter_cache.in_memory_cache.set_cache.side_effect = lambda **kwargs: events.append("counter")
- test_budget = type(
- "LiteLLM_BudgetTableFull",
- (),
- {
- "budget_duration": None,
- "budget_reset_at": original_reset_at,
- "budget_id": "test-budget",
- "created_at": now - timedelta(days=30),
- },
- )
+ job, _ = _job_with_expired_budget(OrderRecordingDB(events))
- asyncio.run(ResetBudgetJob._reset_budget_reset_at_date(test_budget, now, BudgetResetSettings()))
- assert test_budget.budget_reset_at == original_reset_at
+ asyncio.run(job.reset_budget_for_litellm_budget_table())
+ assert events == ["commit", "counter"]
- def test_reset_budget_reset_at_date_none_reset_at():
- """Verify that budget_reset_at is set correctly even when previously None."""
+
+ def test_failed_cascade_is_logged_as_a_cascade_failure(monkeypatch):
+ """The failure log has to name what actually broke. The old catch-all
+ blamed end users even when the team-membership write was the failure."""
from unittest.mock import patch
- fixed_now = datetime(2023, 6, 15, 10, 30, 0, tzinfo=timezone.utc)
+ _make_counter_invalidation_job(monkeypatch)
+ job, _ = _job_with_expired_budget(FailingTeamMembershipDB())
- test_budget = type(
- "LiteLLM_BudgetTableFull",
- (),
- {
- "budget_duration": "30d",
- "budget_reset_at": None,
- "budget_id": "test-budget",
- "created_at": fixed_now - timedelta(days=5),
- },
- )
+ with patch("litellm.proxy.common_utils.reset_budget_job.verbose_proxy_logger.exception") as mock_exception:
+ asyncio.run(job.reset_budget_for_litellm_budget_table())
- with patch("litellm.proxy.common_utils.timezone_utils.datetime") as mock_dt:
- mock_dt.now.return_value = fixed_now
- mock_dt.side_effect = lambda *args, **kwargs: datetime(*args, **kwargs)
- asyncio.run(ResetBudgetJob._reset_budget_reset_at_date(test_budget, fixed_now, BudgetResetSettings()))
+ assert mock_exception.call_count == 1
+ message = mock_exception.call_args.args[0]
+ assert "cascade" in message
+ for mentioned in ("team member", "enduser", "org", "tag", "budget_reset_at"):
+ assert mentioned in message, f"failure log should mention {mentioned}: {message}"
- # Should be set to 1st of next month (July 1)
- assert test_budget.budget_reset_at is not None
- assert test_budget.budget_reset_at.day == 1
- assert test_budget.budget_reset_at.month == 7
+ def _extract_reset_where(find_many_mock):
+ """Return the ``where`` dict passed to a mocked repository ``find_many``."""
+ assert find_many_mock.await_count == 1
+ _, kwargs = find_many_mock.await_args
+ return kwargs["where"]
- def test_budget_table_reset_also_resets_linked_keys(reset_budget_job, mock_prisma_client):
- """
- Integration-style test: when reset_budget_for_litellm_budget_table runs,
- it should also reset spend for keys linked to the expiring budget tiers
- (in addition to end-users and team members).
+
+ def _asserts_null_reset_is_due(where):
+ """A budget-reset ``find_many`` filter must select rows whose
+ ``budget_reset_at`` is NULL but which have a ``budget_duration`` set, in
+ addition to rows whose ``budget_reset_at`` is already in the past.
+
+ Regression guard: a user/team seeded from ``default_internal_user_params``
+ (or created via ``/user/new`` without an explicit ``budget_reset_at``) has
+ ``budget_duration`` set but ``budget_reset_at = NULL``. A plain
+ ``{"budget_reset_at": {"lt": now}}`` filter never matches NULL, so such rows
+ would never be reset and their spend would accumulate for the lifetime of
+ the row, silently exceeding ``max_budget``.
"""
- now = datetime.now(timezone.utc)
+ branches = where.get("OR")
+ assert isinstance(branches, list), f"expected an OR filter, got {where!r}"
- test_budget = type(
- "LiteLLM_BudgetTableFull",
- (),
- {
- "max_budget": 10.0,
- "budget_duration": "7d",
- "budget_reset_at": now - timedelta(hours=1),
- "budget_id": "7d-budget-tier",
- "created_at": now - timedelta(days=7),
- },
- )
+ has_null_branch = {"budget_reset_at": None} in branches
+ has_expired_branch = any(isinstance(b, dict) and isinstance(b.get("budget_reset_at"), dict) for b in branches)
+ assert has_null_branch, f"missing NULL-reset_at branch in {where!r}"
+ assert has_expired_branch, f"missing expired-reset_at branch in {where!r}"
+ assert where.get("NOT") == {"budget_duration": None}, f"NULL reset_at is only due with a duration: {where!r}"
- mock_prisma_client.data["budget"] = [test_budget]
- # Run the full budget table reset
- asyncio.run(reset_budget_job.reset_budget_for_litellm_budget_table())
+ _RESET_TABLE_ATTRS = {
+ "user": "litellm_usertable",
+ "team": "litellm_teamtable",
+ "budget": "litellm_budgettable",
+ "key": "litellm_verificationtoken",
+ }
- # Verify that keys linked to the budget were also reset
- calls = mock_prisma_client.db.litellm_verificationtoken.update_many_calls
- assert len(calls) == 1, (
- "Expected reset_budget_for_litellm_budget_table to also reset keys "
- f"linked to expiring budgets, but got {len(calls)} update_many calls"
- )
- assert calls[0]["where"]["budget_id"] == {"in": ["7d-budget-tier"]}
- assert calls[0]["data"]["spend"] == 0
+ def _run_reset_query(table_name, **extra):
+ """Run ``get_data`` for one table's budget-reset query against a mocked
+ prisma handle, and hand back the ``find_many`` mock it drove."""
+ from litellm.proxy.utils import PrismaClient
- def test_budget_table_reset_also_resets_linked_orgs(reset_budget_job, mock_prisma_client):
- """
- Integration-style test: when reset_budget_for_litellm_budget_table runs,
- it should also reset spend for orgs linked to the expiring budget tiers
- (in addition to end-users, team members, and keys).
- """
- now = datetime.now(timezone.utc)
+ client = PrismaClient.__new__(PrismaClient)
+ client.db = MagicMock()
+ find_many = AsyncMock(return_value=[])
+ setattr(getattr(client.db, _RESET_TABLE_ATTRS[table_name]), "find_many", find_many)
- test_budget = type(
- "LiteLLM_BudgetTableFull",
- (),
- {
- "max_budget": 100.0,
- "budget_duration": "30d",
- "budget_reset_at": now - timedelta(hours=1),
- "budget_id": "30d-org-budget",
- "created_at": now - timedelta(days=30),
- },
- )
+ now = datetime.now(timezone.utc)
+ expires = {"expires": now} if table_name == "key" else {}
+ asyncio.run(client.get_data(table_name=table_name, query_type="find_all", reset_at=now, **expires, **extra))
+ return find_many
- mock_prisma_client.data["budget"] = [test_budget]
- asyncio.run(reset_budget_job.reset_budget_for_litellm_budget_table())
+ @pytest.mark.parametrize("table_name", ["user", "team", "budget", "key"])
+ def test_get_data_reset_query_applies_the_row_limit(table_name):
+ """The reset job pages through due rows, so ``limit`` has to reach prisma as
+ ``take``. Dropped, every worker goes back to pulling the entire expired set
+ in one unbounded query at the same calendar boundary."""
+ find_many = _run_reset_query(table_name, limit=7)
- calls = mock_prisma_client.db.litellm_organizationtable.update_many_calls
- assert len(calls) == 1, (
- "Expected reset_budget_for_litellm_budget_table to also reset orgs "
- f"linked to expiring budgets, but got {len(calls)} update_many calls"
- )
- assert calls[0]["where"]["budget_id"] == {"in": ["30d-org-budget"]}
- assert calls[0]["data"]["spend"] == 0
+ assert find_many.await_args.kwargs["take"] == 7
- def test_budget_table_reset_also_resets_linked_tags(reset_budget_job, mock_prisma_client):
+ @pytest.mark.parametrize("table_name", ["user", "team", "budget", "key"])
+ def test_get_data_reset_query_skips_rows_with_no_budget_duration(table_name):
+ """A row with a past budget_reset_at but no budget_duration has no next
+ window to move to, so it stays due forever. Fetching it means re-reading and
+ re-zeroing it on every tick, and a full chunk of such rows makes the paged
+ scan report no progress and starve the whole phase.
"""
- Integration-style test: when reset_budget_for_litellm_budget_table runs,
- it should also reset spend for tags linked to the expiring budget tiers.
- """
- now = datetime.now(timezone.utc)
+ find_many = _run_reset_query(table_name)
- test_budget = type(
- "LiteLLM_BudgetTableFull",
- (),
- {
- "max_budget": 50.0,
- "budget_duration": "30d",
- "budget_reset_at": now - timedelta(hours=1),
- "budget_id": "30d-tag-budget",
- "created_at": now - timedelta(days=30),
- },
- )
+ assert find_many.await_args.kwargs["where"]["NOT"] == {"budget_duration": None}
- mock_prisma_client.data["budget"] = [test_budget]
- asyncio.run(reset_budget_job.reset_budget_for_litellm_budget_table())
+ @pytest.mark.parametrize("table_name", ["user", "team", "budget", "key"])
+ def test_get_data_reset_query_is_unlimited_when_no_limit_is_passed(table_name):
+ """Callers that pass no limit keep the old unbounded behaviour."""
+ find_many = _run_reset_query(table_name)
- calls = mock_prisma_client.db.litellm_tagtable.update_many_calls
- assert len(calls) == 1, (
- "Expected reset_budget_for_litellm_budget_table to also reset tags "
- f"linked to expiring budgets, but got {len(calls)} update_many calls"
- )
- assert calls[0]["where"]["budget_id"] == {"in": ["30d-tag-budget"]}
- assert calls[0]["data"]["spend"] == 0
+ assert find_many.await_args.kwargs.get("take") is None
- def test_reset_budget_resets_endusers_with_null_budget_id(reset_budget_job, mock_prisma_client):
- """
- When litellm.max_end_user_budget_id is configured and that budget is
- being reset, end users with budget_id=NULL should also have their spend
- reset. These users were implicitly created and have no budget_id persisted,
- but are enforced against the default budget in-memory.
- """
- import litellm
+ @pytest.mark.parametrize("table_name", ["user", "team"])
+ def test_get_data_reset_query_selects_null_budget_reset_at(table_name):
+ """``PrismaClient.get_data(..., reset_at=...)`` for the user and team tables
+ must select rows with a NULL ``budget_reset_at`` (and a non-NULL
+ ``budget_duration``), matching the budget-table query. Without this, users
+ auto-created from ``default_internal_user_params`` are never reset."""
+ from litellm.proxy.utils import PrismaClient
+
+ # Build a PrismaClient without running its heavy __init__; only .db is used.
+ client = PrismaClient.__new__(PrismaClient)
+ client.db = MagicMock()
+
+ find_many = AsyncMock(return_value=[])
+ table_attr = {
+ "user": "litellm_usertable",
+ "team": "litellm_teamtable",
+ }[table_name]
+ setattr(getattr(client.db, table_attr), "find_many", find_many)
now = datetime.now(timezone.utc)
- default_budget_id = "default-enduser-budget"
- litellm.max_end_user_budget_id = default_budget_id
+ asyncio.run(client.get_data(table_name=table_name, query_type="find_all", reset_at=now))
- # Budget that is due for reset — matches the default end user budget
- test_budget = type(
- "LiteLLM_BudgetTableFull",
+ _asserts_null_reset_is_due(_extract_reset_where(find_many))
+
+
+ def _key_row(token: str, budget_duration: Any = "30d"):
+ """A key that is already due for a reset, shaped like a get_data() row."""
+ now = datetime.now(timezone.utc)
+ return type(
+ "LiteLLM_VerificationToken",
(),
{
- "max_budget": 50.0,
- "budget_duration": "1d",
+ "spend": 100.0,
+ "budget_duration": budget_duration,
"budget_reset_at": now - timedelta(hours=1),
- "budget_id": default_budget_id,
- "created_at": now - timedelta(days=1),
+ "token": token,
},
)
diff --cc tests/test_litellm/proxy/db/db_transaction_queue/test_redis_update_buffer.py
index d884a9becaf,fb0c994a476..78aa10929e8
--- a/tests/test_litellm/proxy/db/db_transaction_queue/test_redis_update_buffer.py
+++ b/tests/test_litellm/proxy/db/db_transaction_queue/test_redis_update_buffer.py
@@@ -303,9 -262,73 +298,73 @@@ async def test_get_all_transactions_fro
"""When redis_cache is None, should return all Nones"""
buffer = RedisUpdateBuffer(redis_cache=None)
result = await buffer.get_all_transactions_from_redis_buffer_pipeline()
- assert result == (None, None, None, None, None, None)
+ assert result == (None, None, None, None, None, None, None)
+ @pytest.mark.asyncio
+ async def test_restore_transactions_to_redis_pushes_only_provided(
+ redis_update_buffer, mock_redis_cache
+ ):
+ """
+ restore_transactions_to_redis re-pushes only the transaction sets it was
+ given, to their matching buffer keys, so uncommitted spend can be retried.
+ """
+ from litellm.constants import (
+ REDIS_DAILY_SPEND_UPDATE_BUFFER_KEY,
+ REDIS_UPDATE_BUFFER_KEY,
+ )
+
+ mock_redis_cache.async_rpush_pipeline = AsyncMock(return_value=[1, 1])
+
+ db_spend = {"key_list_transactions": {"key1": 1.0}}
+ daily_user = {"user_key1": {"spend": 1.0}}
+
+ await redis_update_buffer.restore_transactions_to_redis(
+ db_spend_update_transactions=db_spend,
+ daily_spend_update_transactions=daily_user,
+ )
+
+ mock_redis_cache.async_rpush_pipeline.assert_called_once()
+ rpush_list = mock_redis_cache.async_rpush_pipeline.call_args.kwargs["rpush_list"]
+ pushed_keys = {op["key"] for op in rpush_list}
+ assert pushed_keys == {
+ REDIS_UPDATE_BUFFER_KEY,
+ REDIS_DAILY_SPEND_UPDATE_BUFFER_KEY,
+ }
+ # Payloads round-trip through the same JSON encoding used on the store path
+ payloads = {op["key"]: json.loads(op["values"][0]) for op in rpush_list}
+ assert payloads[REDIS_UPDATE_BUFFER_KEY] == db_spend
+ assert payloads[REDIS_DAILY_SPEND_UPDATE_BUFFER_KEY] == daily_user
+
+
+ @pytest.mark.asyncio
+ async def test_restore_transactions_to_redis_noop_when_empty(
+ redis_update_buffer, mock_redis_cache
+ ):
+ """Nothing to restore -> no Redis call."""
+ mock_redis_cache.async_rpush_pipeline = AsyncMock()
+ await redis_update_buffer.restore_transactions_to_redis()
+ mock_redis_cache.async_rpush_pipeline.assert_not_called()
+
+
+ @pytest.mark.asyncio
+ async def test_restore_transactions_to_redis_swallows_redis_error(
+ redis_update_buffer, mock_redis_cache
+ ):
+ """A Redis failure during restore must not propagate to the caller's finally block."""
+ from redis.exceptions import RedisError
+
+ mock_redis_cache.async_rpush_pipeline = AsyncMock(
+ side_effect=RedisError("redis down")
+ )
+
+ await redis_update_buffer.restore_transactions_to_redis(
+ db_spend_update_transactions={"key_list_transactions": {"key1": 1.0}},
+ )
+
+ mock_redis_cache.async_rpush_pipeline.assert_called_once()
+
+
def test_validate_redis_transaction_buffer_raises_without_redis():
"""
When use_redis_transaction_buffer=true but no Redis cache is configured,
diff --cc tests/test_litellm/proxy/db/test_db_spend_update_writer.py
index bd55703408e,b1f647bdd3d..8165dbbe3d1
--- a/tests/test_litellm/proxy/db/test_db_spend_update_writer.py
+++ b/tests/test_litellm/proxy/db/test_db_spend_update_writer.py
@@@ -1,15 -1,11 +1,11 @@@
import asyncio
import copy
import json
- import os
- import sys
-
- sys.path.insert(
- 0, os.path.abspath("../../../..")
- ) # Adds the parent directory to the system path
+ import re
-
+ from collections.abc import Callable
+from contextlib import asynccontextmanager
from datetime import datetime, timezone
from unittest.mock import AsyncMock, MagicMock, call, patch
@@@ -1770,9 -1726,9 +1729,9 @@@ async def test_commit_spend_updates_use
mock_redis_update_buffer = AsyncMock()
mock_redis_update_buffer.store_in_memory_spend_updates_in_redis = AsyncMock()
- # Return all-None tuple (no data to commit)
+ # Return all-None tuple (no data to commit); the pipeline yields 6 slots
mock_redis_update_buffer.get_all_transactions_from_redis_buffer_pipeline = (
- AsyncMock(return_value=(None, None, None, None, None, None))
+ AsyncMock(return_value=(None, None, None, None, None, None, None))
)
db_writer.redis_update_buffer = mock_redis_update_buffer
@@@ -1803,6 -1759,225 +1762,225 @@@
mock_redis_update_buffer.get_all_daily_tag_spend_update_transactions_from_redis_buffer.assert_not_called()
+ @pytest.mark.asyncio
+ async def test_commit_with_redis_requeues_all_on_db_failure():
+ """
+ Regression for #33872: if the DB commit fails after the leader has already
+ popped transactions from Redis, the popped transactions must be re-queued to
+ Redis so a later tick can retry them, instead of being silently lost.
+ """
+ db_writer = DBSpendUpdateWriter()
+
+ db_spend = {
+ "user_list_transactions": {"user1": 1.5},
+ "end_user_list_transactions": {},
+ "key_list_transactions": {"key1": 1.5},
+ "team_list_transactions": {},
+ "team_member_list_transactions": {},
+ "org_list_transactions": {},
+ "tag_list_transactions": {},
+ "agent_list_transactions": {},
+ }
+ daily_user = {"user_key1": {"spend": 1.5, "api_requests": 1}}
+
+ mock_redis_update_buffer = AsyncMock()
+ mock_redis_update_buffer.get_all_transactions_from_redis_buffer_pipeline = AsyncMock(
- return_value=(db_spend, daily_user, None, None, None, None)
++ return_value=(db_spend, daily_user, None, None, None, None, None)
+ )
+ mock_redis_update_buffer.restore_transactions_to_redis = AsyncMock()
+ db_writer.redis_update_buffer = mock_redis_update_buffer
+
+ mock_pod_lock_manager = AsyncMock()
+ mock_pod_lock_manager.acquire_lock = AsyncMock(return_value=True)
+ mock_pod_lock_manager.release_lock = AsyncMock()
+ db_writer.pod_lock_manager = mock_pod_lock_manager
+
+ # Every DB write raises -> simulates a full database outage
+ db_writer._commit_spend_updates_to_db = AsyncMock(side_effect=Exception("db down"))
+
+ with patch.object(
+ DBSpendUpdateWriter,
+ "update_daily_user_spend",
+ new=AsyncMock(side_effect=Exception("db down")),
+ ):
+ await db_writer._commit_spend_updates_to_db_with_redis(
+ prisma_client=MagicMock(),
+ n_retry_times=0,
+ proxy_logging_obj=MagicMock(),
+ )
+
+ # Both failed categories must be re-queued to Redis, nothing lost
+ mock_redis_update_buffer.restore_transactions_to_redis.assert_awaited_once()
+ _, kwargs = mock_redis_update_buffer.restore_transactions_to_redis.call_args
+ assert kwargs["db_spend_update_transactions"] == db_spend
+ assert kwargs["daily_spend_update_transactions"] == daily_user
+ # The lock must still be released
+ mock_pod_lock_manager.release_lock.assert_awaited_once()
+
+
+ @pytest.mark.asyncio
+ async def test_commit_with_redis_only_requeues_failed_category():
+ """
+ A partial DB failure must not re-queue categories that already committed,
+ otherwise their spend would be double-counted on the next tick.
+ """
+ db_writer = DBSpendUpdateWriter()
+
+ db_spend = {
+ "user_list_transactions": {"user1": 1.5},
+ "end_user_list_transactions": {},
+ "key_list_transactions": {},
+ "team_list_transactions": {},
+ "team_member_list_transactions": {},
+ "org_list_transactions": {},
+ "tag_list_transactions": {},
+ "agent_list_transactions": {},
+ }
+ daily_user = {"user_key1": {"spend": 1.5, "api_requests": 1}}
+
+ mock_redis_update_buffer = AsyncMock()
+ mock_redis_update_buffer.get_all_transactions_from_redis_buffer_pipeline = AsyncMock(
- return_value=(db_spend, daily_user, None, None, None, None)
++ return_value=(db_spend, daily_user, None, None, None, None, None)
+ )
+ mock_redis_update_buffer.restore_transactions_to_redis = AsyncMock()
+ db_writer.redis_update_buffer = mock_redis_update_buffer
+
+ mock_pod_lock_manager = AsyncMock()
+ mock_pod_lock_manager.acquire_lock = AsyncMock(return_value=True)
+ mock_pod_lock_manager.release_lock = AsyncMock()
+ db_writer.pod_lock_manager = mock_pod_lock_manager
+
+ # db_spend commits fine; only the daily user commit fails
+ db_writer._commit_spend_updates_to_db = AsyncMock()
+
+ with patch.object(
+ DBSpendUpdateWriter,
+ "update_daily_user_spend",
+ new=AsyncMock(side_effect=Exception("db down")),
+ ):
+ await db_writer._commit_spend_updates_to_db_with_redis(
+ prisma_client=MagicMock(),
+ n_retry_times=0,
+ proxy_logging_obj=MagicMock(),
+ )
+
+ mock_redis_update_buffer.restore_transactions_to_redis.assert_awaited_once()
+ _, kwargs = mock_redis_update_buffer.restore_transactions_to_redis.call_args
+ # Only the failed daily category is requeued; the committed db_spend is not
+ assert kwargs == {"daily_spend_update_transactions": daily_user}
+
+
+ @pytest.mark.asyncio
+ async def test_commit_with_redis_no_requeue_on_success():
+ """When all commits succeed, nothing should be re-queued to Redis."""
+ db_writer = DBSpendUpdateWriter()
+
+ db_spend = {
+ "user_list_transactions": {"user1": 1.5},
+ "end_user_list_transactions": {},
+ "key_list_transactions": {},
+ "team_list_transactions": {},
+ "team_member_list_transactions": {},
+ "org_list_transactions": {},
+ "tag_list_transactions": {},
+ "agent_list_transactions": {},
+ }
+
+ mock_redis_update_buffer = AsyncMock()
+ mock_redis_update_buffer.get_all_transactions_from_redis_buffer_pipeline = AsyncMock(
- return_value=(db_spend, None, None, None, None, None)
++ return_value=(db_spend, None, None, None, None, None, None)
+ )
+ mock_redis_update_buffer.restore_transactions_to_redis = AsyncMock()
+ db_writer.redis_update_buffer = mock_redis_update_buffer
+
+ mock_pod_lock_manager = AsyncMock()
+ mock_pod_lock_manager.acquire_lock = AsyncMock(return_value=True)
+ mock_pod_lock_manager.release_lock = AsyncMock()
+ db_writer.pod_lock_manager = mock_pod_lock_manager
+
+ db_writer._commit_spend_updates_to_db = AsyncMock()
+
+ await db_writer._commit_spend_updates_to_db_with_redis(
+ prisma_client=MagicMock(),
+ n_retry_times=0,
+ proxy_logging_obj=MagicMock(),
+ )
+
+ mock_redis_update_buffer.restore_transactions_to_redis.assert_not_awaited()
+
+
+ @pytest.mark.asyncio
+ async def test_commit_daily_tag_spend_requeues_on_db_failure():
+ """A failed daily tag commit must re-queue the popped tag transactions and release the lock."""
+ db_writer = DBSpendUpdateWriter()
+
+ daily_tag = {"tag_key1": {"spend": 1.5, "api_requests": 1}}
+
+ mock_redis_update_buffer = AsyncMock()
+ mock_redis_update_buffer.store_in_memory_daily_tag_spend_updates_in_redis = AsyncMock()
+ mock_redis_update_buffer.get_all_daily_tag_spend_update_transactions_from_redis_buffer = AsyncMock(
+ return_value=daily_tag
+ )
+ mock_redis_update_buffer.restore_transactions_to_redis = AsyncMock()
+ db_writer.redis_update_buffer = mock_redis_update_buffer
+
+ mock_pod_lock_manager = AsyncMock()
+ mock_pod_lock_manager.acquire_lock = AsyncMock(return_value=True)
+ mock_pod_lock_manager.release_lock = AsyncMock()
+ db_writer.pod_lock_manager = mock_pod_lock_manager
+
+ with patch.object(
+ DBSpendUpdateWriter,
+ "update_daily_tag_spend",
+ new=AsyncMock(side_effect=Exception("db down")),
+ ):
+ await db_writer._commit_daily_tag_spend_to_db_with_redis(
+ prisma_client=MagicMock(),
+ n_retry_times=0,
+ proxy_logging_obj=MagicMock(),
+ )
+
+ mock_redis_update_buffer.restore_transactions_to_redis.assert_awaited_once_with(
+ daily_tag_spend_update_transactions=daily_tag,
+ )
+ mock_pod_lock_manager.release_lock.assert_awaited_once()
+
+
+ @pytest.mark.asyncio
+ async def test_commit_daily_tag_spend_no_requeue_on_success():
+ """A successful daily tag commit must not re-queue anything."""
+ db_writer = DBSpendUpdateWriter()
+
+ daily_tag = {"tag_key1": {"spend": 1.5, "api_requests": 1}}
+
+ mock_redis_update_buffer = AsyncMock()
+ mock_redis_update_buffer.store_in_memory_daily_tag_spend_updates_in_redis = AsyncMock()
+ mock_redis_update_buffer.get_all_daily_tag_spend_update_transactions_from_redis_buffer = AsyncMock(
+ return_value=daily_tag
+ )
+ mock_redis_update_buffer.restore_transactions_to_redis = AsyncMock()
+ db_writer.redis_update_buffer = mock_redis_update_buffer
+
+ mock_pod_lock_manager = AsyncMock()
+ mock_pod_lock_manager.acquire_lock = AsyncMock(return_value=True)
+ mock_pod_lock_manager.release_lock = AsyncMock()
+ db_writer.pod_lock_manager = mock_pod_lock_manager
+
+ with patch.object(
+ DBSpendUpdateWriter,
+ "update_daily_tag_spend",
+ new=AsyncMock(),
+ ):
+ await db_writer._commit_daily_tag_spend_to_db_with_redis(
+ prisma_client=MagicMock(),
+ n_retry_times=0,
+ proxy_logging_obj=MagicMock(),
+ )
+
+ mock_redis_update_buffer.restore_transactions_to_redis.assert_not_awaited()
+ mock_pod_lock_manager.release_lock.assert_awaited_once()
+
+
@pytest.mark.parametrize(
"bucket_name,input_dict,table_attr,method_name,where_key,expected_order",
[
@@@ -2242,256 -2421,426 +2424,681 @@@ async def test_daily_transaction_compre
assert transaction["prompt_caching_savings_spend"] == 0
+# ---------------------------------------------------------------------------
+# Budget window spend flush (LiteLLM_BudgetWindowSpend)
+# ---------------------------------------------------------------------------
+
+
+class _WindowSpendFakeBatcher:
+ def __init__(self):
+ self.calls = []
+
+ def execute_raw(self, query, *args):
+ self.calls.append((query, args))
+
+
+class _WindowSpendFakeDB:
+ """Minimal prisma_client.db that records the raw statements it is handed."""
+
+ def __init__(self, existing_rows=None):
+ self.existing_rows = existing_rows or []
+ self.query_raw_calls = []
+ self.batcher = _WindowSpendFakeBatcher()
+
+ async def query_raw(self, query, *args):
+ self.query_raw_calls.append((query, args))
+ if "LiteLLM_BudgetWindowSpend" in query:
+ return self.existing_rows
+ return []
+
+ @asynccontextmanager
+ async def _tx(self):
+ yield self
+
+ def tx(self, timeout=None):
+ return self._tx()
+
+ @asynccontextmanager
+ async def _batch(self):
+ yield self.batcher
+
+ def batch_(self):
+ return self._batch()
+
+
+class _WindowSpendFakePrisma:
+ def __init__(self, db):
+ self.db = db
+
+
+def _window_spend_upserts(db):
+ return [
+ params for query, params in db.batcher.calls if "LiteLLM_BudgetWindowSpend" in query
+ ]
+
+
+async def test_window_spend_queue_is_flushed_without_redis_buffer():
+ """The in-memory window queue must reach the DB on the same scheduler tick
+ as the other spend queues when the Redis buffer is off."""
+ db_writer = DBSpendUpdateWriter()
+ await db_writer.window_spend_update_queue.add_update(
+ build_window_spend_transaction(
+ entity_type="key",
+ entity_id="hashed-token",
+ window_duration="30d",
+ window_start=datetime(2026, 8, 1, tzinfo=timezone.utc),
+ spend=0.5,
+ )
+ )
+ db = _WindowSpendFakeDB(
+ existing_rows=[
+ {"entity_type": "key", "entity_id": "hashed-token", "window_duration": "30d"}
+ ]
+ )
+
+ await db_writer._commit_spend_updates_to_db_without_redis_buffer(
+ prisma_client=_WindowSpendFakePrisma(db),
+ n_retry_times=0,
+ proxy_logging_obj=MagicMock(),
+ )
+
+ upserts = _window_spend_upserts(db)
+ assert len(upserts) == 1
+ assert upserts[0][0] == "key"
+ assert upserts[0][1] == "hashed-token"
+ assert upserts[0][2] == "30d"
+ assert upserts[0][5] == pytest.approx(0.5)
+ assert db_writer.window_spend_update_queue.update_queue.qsize() == 0
+
+
+async def test_window_spend_queue_is_handed_to_the_redis_buffer():
+ """Multi-pod deployments buffer through Redis, so the window queue has to
+ ride the same rpush path as the daily queues."""
+ db_writer = DBSpendUpdateWriter()
+ mock_redis_update_buffer = AsyncMock()
+ mock_redis_update_buffer.get_all_transactions_from_redis_buffer_pipeline = AsyncMock(
+ return_value=(None, None, None, None, None, None, None)
+ )
+ db_writer.redis_update_buffer = mock_redis_update_buffer
+ db_writer.pod_lock_manager = AsyncMock()
+ db_writer.pod_lock_manager.acquire_lock = AsyncMock(return_value=True)
+
+ await db_writer._commit_spend_updates_to_db_with_redis(
+ prisma_client=MagicMock(),
+ n_retry_times=0,
+ proxy_logging_obj=MagicMock(),
+ )
+
+ stored = mock_redis_update_buffer.store_in_memory_spend_updates_in_redis.call_args[1]
+ assert stored["window_spend_update_queue"] is db_writer.window_spend_update_queue
+
+
+async def test_window_spend_transactions_from_redis_are_committed_by_the_lock_winner():
+ db_writer = DBSpendUpdateWriter()
+ window_transactions = (
+ build_window_spend_transaction(
+ entity_type="team",
+ entity_id="team-1",
+ window_duration="7d",
+ window_start=datetime(2026, 8, 1, tzinfo=timezone.utc),
+ spend=2.0,
+ ),
+ )
+ mock_redis_update_buffer = AsyncMock()
+ mock_redis_update_buffer.get_all_transactions_from_redis_buffer_pipeline = AsyncMock(
+ return_value=(None, None, None, None, None, None, window_transactions)
+ )
+ db_writer.redis_update_buffer = mock_redis_update_buffer
+ db_writer.pod_lock_manager = AsyncMock()
+ db_writer.pod_lock_manager.acquire_lock = AsyncMock(return_value=True)
+ db = _WindowSpendFakeDB(
+ existing_rows=[{"entity_type": "team", "entity_id": "team-1", "window_duration": "7d"}]
+ )
+
+ await db_writer._commit_spend_updates_to_db_with_redis(
+ prisma_client=_WindowSpendFakePrisma(db),
+ n_retry_times=0,
+ proxy_logging_obj=MagicMock(),
+ )
+
+ upserts = _window_spend_upserts(db)
+ assert len(upserts) == 1
+ assert upserts[0][:3] == ("team", "team-1", "7d")
+ assert upserts[0][5] == pytest.approx(2.0)
+
+
+async def test_window_spend_transactions_are_not_committed_without_the_pod_lock():
+ """Every pod buffers to Redis but only the lock winner may drain it."""
+ db_writer = DBSpendUpdateWriter()
+ mock_redis_update_buffer = AsyncMock()
+ db_writer.redis_update_buffer = mock_redis_update_buffer
+ db_writer.pod_lock_manager = AsyncMock()
+ db_writer.pod_lock_manager.acquire_lock = AsyncMock(return_value=False)
+ db = _WindowSpendFakeDB()
+
+ await db_writer._commit_spend_updates_to_db_with_redis(
+ prisma_client=_WindowSpendFakePrisma(db),
+ n_retry_times=0,
+ proxy_logging_obj=MagicMock(),
+ )
+
+ mock_redis_update_buffer.get_all_transactions_from_redis_buffer_pipeline.assert_not_called()
+ assert _window_spend_upserts(db) == []
+
+
+async def test_failed_window_spend_commit_does_not_abort_the_rest_of_the_flush():
+ """Window rows are an optimization over aggregating LiteLLM_SpendLogs, so a
+ failure must not take the tool registry flush down with it."""
+ db_writer = DBSpendUpdateWriter()
+ await db_writer.window_spend_update_queue.add_update(
+ build_window_spend_transaction(
+ entity_type="key",
+ entity_id="hashed-token",
+ window_duration="30d",
+ window_start=datetime(2026, 8, 1, tzinfo=timezone.utc),
+ spend=0.5,
+ )
+ )
+ db = _WindowSpendFakeDB()
+ db.query_raw = AsyncMock(side_effect=Exception("connection reset"))
+ db_writer._flush_tool_discovery_queue = AsyncMock()
+
+ await db_writer._commit_spend_updates_to_db_without_redis_buffer(
+ prisma_client=_WindowSpendFakePrisma(db),
+ n_retry_times=0,
+ proxy_logging_obj=MagicMock(),
+ )
+
+ db_writer._flush_tool_discovery_queue.assert_called_once()
+
+
+async def test_update_database_returns_the_spend_log_request_id():
+ """The budget-window seed excludes the log rows its increments already
+ cover, so the caller needs the id this call was recorded under. It cannot
+ be re-derived: cache hits append time.time() to the id."""
+ db_writer = DBSpendUpdateWriter()
+ db_writer._insert_spend_log_to_db = AsyncMock()
+ db_writer._enqueue_tool_usage_transaction = AsyncMock()
+
+ with (
+ patch("litellm.proxy.proxy_server.disable_spend_logs", False),
+ patch("litellm.proxy.proxy_server.prisma_client", MagicMock()),
+ patch("litellm.proxy.proxy_server.litellm_proxy_budget_name", "test-budget"),
+ ):
+ request_id = await db_writer.update_database(
+ token="test-token",
+ user_id="test-user",
+ end_user_id=None,
+ team_id="test-team",
+ org_id=None,
+ kwargs={"model": "gpt-4", "custom_llm_provider": "openai", "litellm_call_id": "call-xyz"},
+ completion_response=MagicMock(),
+ start_time=datetime.now(),
+ end_time=datetime.now(),
+ response_cost=0.1,
+ )
+ await asyncio.sleep(0)
+
+ assert request_id is not None
+ # Same id the spend log row was queued under.
+ assert request_id == db_writer._insert_spend_log_to_db.call_args[1]["payload"]["request_id"]
+
+
+async def test_update_database_returns_none_when_the_payload_cannot_be_built():
+ db_writer = DBSpendUpdateWriter()
+
+ with (
+ patch("litellm.proxy.proxy_server.disable_spend_logs", False),
+ patch("litellm.proxy.proxy_server.prisma_client", MagicMock()),
+ patch("litellm.proxy.proxy_server.litellm_proxy_budget_name", "test-budget"),
+ patch(
+ "litellm.proxy.spend_tracking.spend_tracking_utils.get_logging_payload",
+ side_effect=Exception("payload boom"),
+ ),
+ ):
+ request_id = await db_writer.update_database(
+ token="test-token",
+ user_id="test-user",
+ end_user_id=None,
+ team_id="test-team",
+ org_id=None,
+ kwargs={"model": "gpt-4"},
+ completion_response=MagicMock(),
+ start_time=datetime.now(),
+ end_time=datetime.now(),
+ response_cost=0.1,
+ )
+
+ assert request_id is None
++
++
+ @pytest.mark.asyncio
+ async def test_commit_spend_updates_to_db_does_not_stamp_key_settings_updated_at():
+ """Spend flushes must leave settings_updated_at alone, or it decays into
+ another `updated_at` and stops being an audit signal."""
+ db_writer = DBSpendUpdateWriter()
+
+ mock_batcher = MagicMock()
+ mock_batcher.litellm_verificationtoken = MagicMock()
+ mock_batcher.litellm_verificationtoken.update_many = MagicMock()
+ mock_batcher.litellm_usertable = MagicMock()
+ mock_batcher.litellm_usertable.update_many = MagicMock()
+ mock_batcher.litellm_teamtable = MagicMock()
+ mock_batcher.litellm_teamtable.update_many = MagicMock()
+ mock_batcher.litellm_teammembership = MagicMock()
+ mock_batcher.litellm_teammembership.update_many = MagicMock()
+ mock_batcher.litellm_organizationtable = MagicMock()
+ mock_batcher.litellm_organizationtable.update_many = MagicMock()
+ mock_batcher.litellm_tagtable = MagicMock()
+ mock_batcher.litellm_tagtable.update_many = MagicMock()
+ mock_batcher.litellm_agentstable = MagicMock()
+ mock_batcher.litellm_agentstable.update_many = MagicMock()
+
+ mock_transaction = AsyncMock()
+ mock_transaction.__aenter__ = AsyncMock(return_value=mock_transaction)
+ mock_transaction.__aexit__ = AsyncMock(return_value=False)
+ mock_transaction.batch_ = MagicMock(
+ return_value=AsyncMock(
+ __aenter__=AsyncMock(return_value=mock_batcher),
+ __aexit__=AsyncMock(return_value=False),
+ )
+ )
+
+ mock_prisma_client = MagicMock()
+ mock_prisma_client.db = MagicMock()
+ mock_prisma_client.db.tx = MagicMock(return_value=mock_transaction)
+
+ token = "hashed-token-abc"
+ response_cost = 0.25
+ db_spend_update_transactions = {
+ "user_list_transactions": {},
+ "end_user_list_transactions": {},
+ "key_list_transactions": {token: response_cost},
+ "team_list_transactions": {},
+ "team_member_list_transactions": {},
+ "org_list_transactions": {},
+ "tag_list_transactions": {},
+ "agent_list_transactions": {},
+ }
+
+ with patch("litellm.proxy.utils._raise_failed_update_spend_exception"):
+ await db_writer._commit_spend_updates_to_db(
+ prisma_client=mock_prisma_client,
+ n_retry_times=0,
+ proxy_logging_obj=MagicMock(),
+ db_spend_update_transactions=db_spend_update_transactions,
+ )
+
+ mock_batcher.litellm_verificationtoken.update_many.assert_called_once()
+ call_kwargs = mock_batcher.litellm_verificationtoken.update_many.call_args[1]
+ assert call_kwargs["where"] == {"token": token}
+ assert set(call_kwargs["data"]) == {"spend", "last_active"}
+ assert call_kwargs["data"]["spend"] == {"increment": response_cost}
+
+
+ @pytest.mark.asyncio
+ async def test_daily_transaction_internal_call_keeps_spend_but_not_request_counts():
+ """Internal sub-calls (auto-router classifier, shadow eval's shadow and judge) bill
+ spend and tokens to the key but are not requests the caller made: api_requests,
+ successful_requests, and autorouter_savings_spend must all stay zero for them."""
+ writer = DBSpendUpdateWriter()
+ mock_prisma = MagicMock()
+ mock_prisma.get_request_status = MagicMock(return_value="success")
+
+ def _payload(metadata: dict) -> dict:
+ return {
+ "request_id": "req-internal-1",
+ "user": "test-user",
+ "startTime": "2026-08-11T00:00:00",
+ "api_key": "test-key",
+ "model": "claude-sonnet-5",
+ "custom_llm_provider": "anthropic",
+ "model_group": "claude-sonnet-5",
+ "call_type": "acompletion",
+ "prompt_tokens": 100,
+ "completion_tokens": 10,
+ "spend": 0.05,
+ "metadata": json.dumps(metadata),
+ }
+
+ internal = await writer._common_add_spend_log_transaction_to_daily_transaction(
+ payload=_payload({"internal_call_origin": "shadow_eval_judge"}),
+ prisma_client=mock_prisma,
+ type="user",
+ )
+ user_sent = await writer._common_add_spend_log_transaction_to_daily_transaction(
+ payload=_payload({}),
+ prisma_client=mock_prisma,
+ type="user",
+ )
+
+ assert internal is not None and user_sent is not None
+ assert internal["spend"] == 0.05
+ assert internal["prompt_tokens"] == 100
+ assert internal["api_requests"] == 0
+ assert internal["successful_requests"] == 0
+ assert internal["failed_requests"] == 0
+ assert internal["autorouter_savings_spend"] == 0.0
+ assert user_sent["api_requests"] == 1
+ assert user_sent["successful_requests"] == 1
+
+
+ def _deadlock_error():
+ from prisma.errors import RawQueryError
+
+ return RawQueryError(
+ data={"user_facing_error": {"error_code": "P2034", "meta": {"table": "LiteLLM_VerificationToken"}}}
+ )
+
+
+ def _empty_spend_transactions(**overrides):
+ base = {
+ "user_list_transactions": {},
+ "end_user_list_transactions": {},
+ "key_list_transactions": {},
+ "team_list_transactions": {},
+ "team_member_list_transactions": {},
+ "org_list_transactions": {},
+ "tag_list_transactions": {},
+ "agent_list_transactions": {},
+ }
+ return {**base, **overrides}
+
+
+ def _good_tx(mock_batcher):
+ tx = AsyncMock()
+ tx.__aenter__ = AsyncMock(return_value=tx)
+ tx.__aexit__ = AsyncMock(return_value=False)
+ tx.batch_ = MagicMock(
+ return_value=AsyncMock(
+ __aenter__=AsyncMock(return_value=mock_batcher),
+ __aexit__=AsyncMock(return_value=False),
+ )
+ )
+ return tx
+
+
+ def _failing_tx(error):
+ tx = MagicMock()
+ tx.__aenter__ = AsyncMock(side_effect=error)
+ tx.__aexit__ = AsyncMock(return_value=False)
+ return tx
+
+
+ @pytest.mark.asyncio
+ async def test_commit_spend_updates_retries_deadlock_then_commits(monkeypatch):
+ """Regression: a deadlock on the key-spend UPDATE is retried and commits the increment exactly once."""
+ slept = []
+ monkeypatch.setattr(
+ "litellm.proxy.db.db_spend_update_writer.asyncio.sleep",
+ AsyncMock(side_effect=lambda s: slept.append(s)),
+ )
+
+ mock_batcher = MagicMock()
+ mock_prisma_client = MagicMock()
+ mock_prisma_client.db.tx = MagicMock(side_effect=[_failing_tx(_deadlock_error()), _good_tx(mock_batcher)])
+
+ proxy_logging = MagicMock()
+ proxy_logging.failure_handler = AsyncMock()
+
+ await DBSpendUpdateWriter()._commit_spend_updates_to_db(
+ prisma_client=mock_prisma_client,
+ n_retry_times=3,
+ proxy_logging_obj=proxy_logging,
+ db_spend_update_transactions=_empty_spend_transactions(key_list_transactions={"sk-abc": 0.5}),
+ )
+
+ assert mock_prisma_client.db.tx.call_count == 2
+ mock_batcher.litellm_verificationtoken.update_many.assert_called_once()
+ call_kwargs = mock_batcher.litellm_verificationtoken.update_many.call_args[1]
+ assert call_kwargs["where"] == {"token": "sk-abc"}
+ assert call_kwargs["data"]["spend"] == {"increment": 0.5}
+ assert len(slept) == 1
+ proxy_logging.failure_handler.assert_not_called()
+
+
+ @pytest.mark.asyncio
+ async def test_commit_spend_updates_raises_after_exhausting_deadlock_retries(monkeypatch):
+ """A deadlock that never clears must surface after the retry budget is spent, not loop or swallow."""
+ monkeypatch.setattr("litellm.proxy.db.db_spend_update_writer.asyncio.sleep", AsyncMock(return_value=None))
+
+ mock_prisma_client = MagicMock()
+ mock_prisma_client.db.tx = MagicMock(side_effect=lambda *a, **k: _failing_tx(_deadlock_error()))
+
+ proxy_logging = MagicMock()
+ proxy_logging.failure_handler = AsyncMock()
+
+ from prisma.errors import RawQueryError
+
+ with pytest.raises(RawQueryError):
+ await DBSpendUpdateWriter()._commit_spend_updates_to_db(
+ prisma_client=mock_prisma_client,
+ n_retry_times=2,
+ proxy_logging_obj=proxy_logging,
+ db_spend_update_transactions=_empty_spend_transactions(key_list_transactions={"sk-abc": 0.5}),
+ )
+
+ assert mock_prisma_client.db.tx.call_count == 3
+
+
+ @pytest.mark.asyncio
+ async def test_commit_spend_updates_does_not_retry_non_deadlock_data_error(monkeypatch):
+ """A non-retryable data-layer error raises on the first attempt, never retried against the increment."""
+ monkeypatch.setattr("litellm.proxy.db.db_spend_update_writer.asyncio.sleep", AsyncMock(return_value=None))
+
+ from prisma.errors import UniqueViolationError
+
+ non_deadlock = UniqueViolationError(
+ data={"user_facing_error": {"error_code": "P2002", "meta": {"table": "LiteLLM_VerificationToken"}}}
+ )
+ mock_prisma_client = MagicMock()
+ mock_prisma_client.db.tx = MagicMock(side_effect=lambda *a, **k: _failing_tx(non_deadlock))
+
+ proxy_logging = MagicMock()
+ proxy_logging.failure_handler = AsyncMock()
+
+ with pytest.raises(UniqueViolationError):
+ await DBSpendUpdateWriter()._commit_spend_updates_to_db(
+ prisma_client=mock_prisma_client,
+ n_retry_times=3,
+ proxy_logging_obj=proxy_logging,
+ db_spend_update_transactions=_empty_spend_transactions(key_list_transactions={"sk-abc": 0.5}),
+ )
+
+ mock_prisma_client.db.tx.assert_called_once()
+
+
+ @pytest.mark.asyncio
+ async def test_update_daily_spend_retries_deadlock(monkeypatch):
+ """The daily-spend upsert path retries a deadlock on the bulk upsert and then drains successfully."""
+ mock_prisma_client = MagicMock()
+ mock_prisma_client.db.execute_raw = AsyncMock(side_effect=[_deadlock_error(), None])
+ proxy_logging = MagicMock()
+ proxy_logging.failure_handler = AsyncMock()
+
+ monkeypatch.setattr("litellm.proxy.db.db_spend_update_writer.asyncio.sleep", AsyncMock(return_value=None))
+ daily_spend_transactions = {"k1": _daily_txn()}
+ await DBSpendUpdateWriter._update_daily_spend(
+ n_retry_times=3,
+ prisma_client=mock_prisma_client,
+ proxy_logging_obj=proxy_logging,
+ daily_spend_transactions=daily_spend_transactions,
+ entity_type="user",
+ entity_id_field="user_id",
+ )
+
+ assert mock_prisma_client.db.execute_raw.call_count == 2
+ assert daily_spend_transactions == {}
+ proxy_logging.failure_handler.assert_not_called()
+
+
+ @pytest.mark.parametrize(
+ "transactions_key, sample_key",
+ [
+ ("user_list_transactions", "user-1"),
+ ("team_list_transactions", "team-1"),
+ ("team_member_list_transactions", "team_id::team-1::user_id::user-1"),
+ ("org_list_transactions", "org-1"),
+ ("tag_list_transactions", "tag-1"),
+ ("agent_list_transactions", "agent-1"),
+ ],
+ )
+ @pytest.mark.asyncio
+ async def test_commit_spend_updates_retries_deadlock_on_every_entity_path(monkeypatch, transactions_key, sample_key):
+ """Every per-entity spend path, not just keys, retries a deadlock instead of dropping the increment."""
+ monkeypatch.setattr("litellm.proxy.db.db_spend_update_writer.asyncio.sleep", AsyncMock(return_value=None))
+
+ mock_batcher = MagicMock()
+ mock_prisma_client = MagicMock()
+ mock_prisma_client.db.tx = MagicMock(side_effect=[_failing_tx(_deadlock_error()), _good_tx(mock_batcher)])
+
+ proxy_logging = MagicMock()
+ proxy_logging.failure_handler = AsyncMock()
+ proxy_logging.call_details = {}
+
+ await DBSpendUpdateWriter()._commit_spend_updates_to_db(
+ prisma_client=mock_prisma_client,
+ n_retry_times=3,
+ proxy_logging_obj=proxy_logging,
+ db_spend_update_transactions=_empty_spend_transactions(**{transactions_key: {sample_key: 0.5}}),
+ )
+
+ assert mock_prisma_client.db.tx.call_count == 2
+ proxy_logging.failure_handler.assert_not_called()
+
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "call_type, expects_flush",
+ [("aresponses", True), ("responses", True), ("acompletion", False)],
+ )
+ async def test_insert_spend_log_asks_for_an_immediate_flush_on_responses_calls(
+ call_type: str, expects_flush: bool
+ ):
+ """
+ A `previous_response_id` chained straight off the previous turn reads the DB, so a
+ Responses row cannot sit in this worker's queue until the monitor's next poll.
+ """
+ from litellm.proxy.utils import PrismaClient
+
+ db_writer = DBSpendUpdateWriter()
+ prisma = _tool_usage_prisma()
+ PrismaClient.spend_log_flush_requested.clear()
+
+ await db_writer._insert_spend_log_to_db(
+ payload={"request_id": "req-1", "call_type": call_type},
+ prisma_client=prisma,
+ )
+
+ assert prisma.spend_log_transactions == [{"request_id": "req-1", "call_type": call_type}]
+ assert PrismaClient.spend_log_flush_requested.is_set() is expects_flush
+ PrismaClient.spend_log_flush_requested.clear()
+
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "injected_deployment, attributed",
+ [
+ pytest.param("dep-of-this-row", True, id="this-deployment-injected"),
+ pytest.param("dep-of-a-sibling-leg", False, id="a-sibling-deployment-injected"),
+ pytest.param("", True, id="injected-before-a-deployment-was-chosen"),
+ ],
+ )
+ async def test_caching_savings_are_attributed_to_the_deployment_that_was_injected(
+ injected_deployment, attributed
+ ):
+ """Retries, same-group failover and cross-model-group fallbacks all reuse one metadata
+ bucket and one litellm_call_id, so a marker written by the leg that injected is
+ visible to every sibling and nothing request-scoped can tell them apart.
+
+ Naming the deployment it injected for is what keeps the credit on that leg: a row
+ billed for a different deployment reads it as no injection, so no seam has to strip
+ it and a deployment that injected nothing is never credited for the one that did.
+
+ An injection that ran before any deployment was chosen, which is what the proxy does
+ for prompt templates, is written into the payload every leg goes on to send, so it
+ marks the request for all of them and each leg keeps the credit.
+ """
+ writer = DBSpendUpdateWriter()
+ mock_prisma = MagicMock()
+ mock_prisma.get_request_status = MagicMock(return_value="success")
+
+ payload = {
+ "request_id": "req-fallback-leg",
+ "user": "test-user",
+ "startTime": "2026-07-17T00:00:00",
+ "api_key": "test-key",
+ "model": "claude-sonnet-5",
+ "custom_llm_provider": "anthropic",
+ "model_group": "claude-sonnet-5",
+ "model_id": "dep-of-this-row",
+ "call_type": "anthropic_messages",
+ "prompt_tokens": 5000,
+ "completion_tokens": 10,
+ "spend": 0.05,
+ "metadata": json.dumps(
+ {
+ "usage_object": {"cache_read_input_tokens": 4242, "cache_creation_input_tokens": 1111},
+ "litellm_gateway_injected_cache": injected_deployment,
+ }
+ ),
+ }
+
+ transaction = await writer._common_add_spend_log_transaction_to_daily_transaction(
+ payload=payload,
+ prisma_client=mock_prisma,
+ type="user",
+ )
+
+ assert transaction is not None
+ assert transaction["prompt_caching_savings_spend"] != 0.0
+ assert (transaction["gateway_injected_caching_savings_spend"] != 0.0) is attributed
+
+
+ @pytest.mark.asyncio
+ async def test_daily_transaction_attributes_caching_savings_only_with_an_injection_marker():
+ """Cached usage with no litellm_gateway_injected_cache marker is still a real saving.
+
+ Client-sent cache_control and implicit provider caching leave no marker, so the row
+ keeps the total the customer actually got while the gateway-attributed column stays
+ empty, which is what separates what caching saved from what litellm can claim.
+ """
+ writer = DBSpendUpdateWriter()
+ mock_prisma = MagicMock()
+ mock_prisma.get_request_status = MagicMock(return_value="success")
+
+ payload = {
+ "request_id": "req-ungated-caching",
+ "user": "test-user",
+ "startTime": "2026-07-17T00:00:00",
+ "api_key": "test-key",
+ "model": "claude-sonnet-5",
+ "custom_llm_provider": "anthropic",
+ "model_group": "claude-sonnet-5",
+ "call_type": "anthropic_messages",
+ "prompt_tokens": 5000,
+ "completion_tokens": 10,
+ "spend": 0.05,
+ "metadata": json.dumps(
+ {"usage_object": {"cache_read_input_tokens": 4242, "cache_creation_input_tokens": 1111}}
+ ),
+ }
+
+ transaction = await writer._common_add_spend_log_transaction_to_daily_transaction(
+ payload=payload,
+ prisma_client=mock_prisma,
+ type="user",
+ )
+
+ assert transaction is not None
+ assert transaction["cache_read_input_tokens"] == 4242
+ assert transaction["cache_creation_input_tokens"] == 1111
+ assert transaction["prompt_caching_savings_spend"] != 0.0
+ assert transaction["gateway_injected_caching_savings_spend"] == 0.0
diff --cc tests/test_litellm/proxy/test_proxy_server.py
index f11d2e00f72,949088ea3ba..70736949628
--- a/tests/test_litellm/proxy/test_proxy_server.py
+++ b/tests/test_litellm/proxy/test_proxy_server.py
@@@ -11019,284 -11130,676 +11131,959 @@@ def test_startup_is_silent_when_mock_te
assert MOCK_TESTING_CONFIG_KEY not in caplog.text
+# ---------------------------------------------------------------------------
+# Budget window spend row enqueue (LiteLLM_BudgetWindowSpend writer)
+# ---------------------------------------------------------------------------
+
+
+def _window_spend_enqueue_env(cached_objects: dict):
+ """Point increment_spend_counters at throwaway caches and a real
+ WindowSpendUpdateQueue, and hand back the queue to inspect."""
+ from litellm.caching.dual_cache import DualCache
+ from litellm.proxy.db.db_transaction_queue.window_spend_update_queue import (
+ WindowSpendUpdateQueue,
+ )
+ import litellm.proxy.proxy_server as ps
+
+ user_api_key_cache = MagicMock()
+ user_api_key_cache.async_get_cache = AsyncMock(side_effect=lambda key, **_: cached_objects.get(key))
+
+ queue = WindowSpendUpdateQueue()
+ proxy_logging_obj = MagicMock()
+ proxy_logging_obj.db_spend_update_writer.window_spend_update_queue = queue
+
+ originals = (
+ ps.user_api_key_cache,
+ ps.spend_counter_cache,
+ ps.prisma_client,
+ ps.proxy_logging_obj,
+ )
+ ps.user_api_key_cache = user_api_key_cache
+ ps.spend_counter_cache = DualCache()
+ ps.prisma_client = None
+ ps.proxy_logging_obj = proxy_logging_obj
+ try:
+ yield queue
+ finally:
+ (
+ ps.user_api_key_cache,
+ ps.spend_counter_cache,
+ ps.prisma_client,
+ ps.proxy_logging_obj,
+ ) = originals
+
+
+async def _drain(queue):
+ return list(await queue.flush_and_get_aggregated_window_spend_transactions())
+
+
+async def test_key_window_spend_row_is_enqueued_with_the_actual_cost():
+ from litellm.proxy.proxy_server import increment_spend_counters
+
+ reset_at = datetime.now(timezone.utc) + timedelta(days=10)
+ key_obj = MagicMock()
+ key_obj.budget_limits = [
+ {"budget_duration": "30d", "max_budget": 100.0, "reset_at": reset_at.isoformat()}
+ ]
+
+ with _window_spend_enqueue_env({"hashed-token": key_obj}) as queue:
+ await increment_spend_counters(
+ token="hashed-token", team_id=None, user_id=None, response_cost=0.25
+ )
+ enqueued = await _drain(queue)
+
+ assert len(enqueued) == 1
+ assert enqueued[0]["entity_type"] == "key"
+ assert enqueued[0]["entity_id"] == "hashed-token"
+ assert enqueued[0]["window_duration"] == "30d"
+ assert enqueued[0]["spend"] == pytest.approx(0.25)
+ assert enqueued[0]["window_start"] == (reset_at - timedelta(days=30)).astimezone(timezone.utc).replace(
+ tzinfo=None
+ ).isoformat(timespec="microseconds")
+
+
+async def test_team_window_spend_row_is_enqueued():
+ from litellm.proxy.proxy_server import increment_spend_counters
+
+ reset_at = datetime.now(timezone.utc) + timedelta(days=3)
+ team_obj = MagicMock()
+ team_obj.budget_limits = [
+ {"budget_duration": "7d", "max_budget": 50.0, "reset_at": reset_at.isoformat()}
+ ]
+
+ with _window_spend_enqueue_env({"team_id:team-1": team_obj}) as queue:
+ await increment_spend_counters(
+ token=None, team_id="team-1", user_id=None, response_cost=1.5
+ )
+ enqueued = await _drain(queue)
+
+ assert len(enqueued) == 1
+ assert enqueued[0]["entity_type"] == "team"
+ assert enqueued[0]["entity_id"] == "team-1"
+ assert enqueued[0]["window_duration"] == "7d"
+ assert enqueued[0]["spend"] == pytest.approx(1.5)
+
+
+async def test_window_spend_row_is_enqueued_even_when_the_counter_was_reserved():
+ """A reservation only pre-charged the cache counter with an estimate; the
+ row still owes the actual cost, so the enqueue must not be skipped."""
+ from litellm.proxy.proxy_server import increment_spend_counters
+ import litellm.proxy.spend_tracking.budget_reservation as br
+
+ reset_at = datetime.now(timezone.utc) + timedelta(days=10)
+ key_obj = MagicMock()
+ key_obj.budget_limits = [
+ {"budget_duration": "30d", "max_budget": 100.0, "reset_at": reset_at.isoformat()}
+ ]
+ reservation = {
+ "entries": [
+ {"counter_key": "spend:key:hashed-token", "reserved": 1.0},
+ {"counter_key": "spend:key:hashed-token:window:30d", "reserved": 1.0},
+ ]
+ }
+
+ original_reconcile = br.reconcile_budget_reservation
+ br.reconcile_budget_reservation = AsyncMock(return_value=None)
+ try:
+ with _window_spend_enqueue_env({"hashed-token": key_obj}) as queue:
+ await increment_spend_counters(
+ token="hashed-token",
+ team_id=None,
+ user_id=None,
+ response_cost=0.25,
+ budget_reservation=reservation,
+ )
+ enqueued = await _drain(queue)
+ finally:
+ br.reconcile_budget_reservation = original_reconcile
+
+ assert len(enqueued) == 1
+ assert enqueued[0]["spend"] == pytest.approx(0.25)
+
+
+async def test_sliding_window_without_reset_at_is_not_enqueued():
+ """Windows with no reset_at slide with wall clock, so window_start moves on
+ every request and no single row can represent them; the read path keeps
+ using its LiteLLM_SpendLogs fallback instead."""
+ from litellm.proxy.proxy_server import increment_spend_counters
+
+ key_obj = MagicMock()
+ key_obj.budget_limits = [{"budget_duration": "30d", "max_budget": 100.0}]
+
+ with _window_spend_enqueue_env({"hashed-token": key_obj}) as queue:
+ await increment_spend_counters(
+ token="hashed-token", team_id=None, user_id=None, response_cost=0.25
+ )
+ enqueued = await _drain(queue)
+
+ assert enqueued == []
+
+
+async def test_each_configured_window_gets_its_own_row_enqueue():
+ from litellm.proxy.proxy_server import increment_spend_counters
+
+ now = datetime.now(timezone.utc)
+ key_obj = MagicMock()
+ key_obj.budget_limits = [
+ {"budget_duration": "1d", "max_budget": 5.0, "reset_at": (now + timedelta(hours=5)).isoformat()},
+ {"budget_duration": "30d", "max_budget": 100.0, "reset_at": (now + timedelta(days=10)).isoformat()},
+ ]
+
+ with _window_spend_enqueue_env({"hashed-token": key_obj}) as queue:
+ await increment_spend_counters(
+ token="hashed-token", team_id=None, user_id=None, response_cost=0.25
+ )
+ enqueued = await _drain(queue)
+
+ assert sorted(item["window_duration"] for item in enqueued) == ["1d", "30d"]
+ assert all(item["spend"] == pytest.approx(0.25) for item in enqueued)
+
+
+async def test_no_window_spend_row_enqueued_without_budget_limits():
+ from litellm.proxy.proxy_server import increment_spend_counters
+
+ key_obj = MagicMock()
+ key_obj.budget_limits = None
+
+ with _window_spend_enqueue_env({"hashed-token": key_obj}) as queue:
+ await increment_spend_counters(
+ token="hashed-token", team_id=None, user_id=None, response_cost=0.25
+ )
+ enqueued = await _drain(queue)
+
+ assert enqueued == []
+
+
+async def test_window_spend_row_carries_the_spend_log_request_id():
+ """The flush excludes these ids from its one-time seed, so the id threaded
+ here has to be the same one the LiteLLM_SpendLogs row was written under."""
+ from litellm.proxy.proxy_server import increment_spend_counters
+
+ reset_at = datetime.now(timezone.utc) + timedelta(days=10)
+ key_obj = MagicMock()
+ key_obj.budget_limits = [
+ {"budget_duration": "30d", "max_budget": 100.0, "reset_at": reset_at.isoformat()}
+ ]
+
+ with _window_spend_enqueue_env({"hashed-token": key_obj}) as queue:
+ await increment_spend_counters(
+ token="hashed-token",
+ team_id=None,
+ user_id=None,
+ response_cost=0.25,
+ request_id="chatcmpl-abc123",
+ )
+ enqueued = await _drain(queue)
+
+ assert enqueued[0]["request_ids"] == ("chatcmpl-abc123",)
+
+
+async def test_window_spend_row_carries_the_request_start_time():
+ """The seed only excludes a batch id whose LiteLLM_SpendLogs.startTime is at
+ or after this, so it must be the same start the spend log was written with."""
+ from litellm.proxy.proxy_server import increment_spend_counters
+
+ reset_at = datetime.now(timezone.utc) + timedelta(days=10)
+ key_obj = MagicMock()
+ key_obj.budget_limits = [
+ {"budget_duration": "30d", "max_budget": 100.0, "reset_at": reset_at.isoformat()}
+ ]
+
+ with _window_spend_enqueue_env({"hashed-token": key_obj}) as queue:
+ await increment_spend_counters(
+ token="hashed-token",
+ team_id=None,
+ user_id=None,
+ response_cost=0.25,
+ request_id="chatcmpl-abc123",
+ request_started_at=datetime(2026, 8, 10, 12, 0, 0, 500_000, tzinfo=timezone.utc),
+ )
+ enqueued = await _drain(queue)
+
+ assert enqueued[0]["started_at"] == "2026-08-10T12:00:00.500000"
+
+
+async def test_window_spend_row_without_a_request_id_excludes_nothing():
+ from litellm.proxy.proxy_server import increment_spend_counters
+
+ reset_at = datetime.now(timezone.utc) + timedelta(days=10)
+ key_obj = MagicMock()
+ key_obj.budget_limits = [
+ {"budget_duration": "30d", "max_budget": 100.0, "reset_at": reset_at.isoformat()}
+ ]
+
+ with _window_spend_enqueue_env({"hashed-token": key_obj}) as queue:
+ await increment_spend_counters(
+ token="hashed-token", team_id=None, user_id=None, response_cost=0.25
+ )
+ enqueued = await _drain(queue)
+
+ assert enqueued[0]["request_ids"] == ()
+
+
+async def test_team_window_spend_row_carries_the_request_id():
+ from litellm.proxy.proxy_server import increment_spend_counters
+
+ reset_at = datetime.now(timezone.utc) + timedelta(days=3)
+ team_obj = MagicMock()
+ team_obj.budget_limits = [
+ {"budget_duration": "7d", "max_budget": 50.0, "reset_at": reset_at.isoformat()}
+ ]
+
+ with _window_spend_enqueue_env({"team_id:team-1": team_obj}) as queue:
+ await increment_spend_counters(
+ token=None,
+ team_id="team-1",
+ user_id=None,
+ response_cost=1.5,
+ request_id="chatcmpl-team",
+ )
+ enqueued = await _drain(queue)
+
+ assert enqueued[0]["request_ids"] == ("chatcmpl-team",)
++
++
+ def _mock_startup_prisma_client(health_check_error=None, connect_error=None):
+ client = MagicMock()
+ client.connect = AsyncMock(side_effect=connect_error)
+ client.db.start_token_refresh_task = AsyncMock()
+ client.check_view_exists = AsyncMock()
+ client._set_spend_logs_row_count_in_proxy_state = AsyncMock()
+ client.start_db_health_watchdog_task = AsyncMock()
+ client.health_check = AsyncMock(side_effect=health_check_error)
+ return client
+
+
+ async def _run_setup_prisma_client(mock_client):
+ from litellm.proxy.proxy_server import ProxyStartupEvent
+
+ with patch.object(proxy_server_module, "PrismaClient", return_value=mock_client):
+ result = await ProxyStartupEvent._setup_prisma_client(
+ database_url="postgresql://litellm:litellm@localhost:5432/litellm",
+ proxy_logging_obj=MagicMock(),
+ user_api_key_cache=DualCache(),
+ )
+ await asyncio.sleep(0.05)
+ return result
+
+
+ @pytest.mark.asyncio
+ async def test_setup_prisma_client_retains_connected_client_when_startup_health_check_fails(
+ monkeypatch,
+ ):
+ """A transient failure of the startup ``SELECT 1`` must not discard a client
+ whose ``connect()`` already succeeded.
+
+ Discarding it assigns ``None`` to the module-level ``prisma_client`` for the
+ life of the process, so a database that came back a second later is never
+ used again until the proxy is restarted."""
+ monkeypatch.setenv("DISABLE_PRISMA_HEALTH_CHECK_ON_STARTUP", "False")
+ monkeypatch.setattr(
+ proxy_server_module,
+ "general_settings",
+ {"allow_requests_on_db_unavailable": True},
+ )
+
+ mock_client = _mock_startup_prisma_client(health_check_error=httpx.ReadTimeout("startup health check timed out"))
+ result = await _run_setup_prisma_client(mock_client)
+
+ assert mock_client.connect.await_count == 1
+ assert mock_client.health_check.await_count == 1
+ assert result is mock_client
+
+
+ @pytest.mark.asyncio
+ async def test_setup_prisma_client_arms_health_watchdog_before_startup_health_check(
+ monkeypatch,
+ ):
+ """The health watchdog is the only thing that reconnects a dropped DB, so it
+ has to be armed before the startup health check can fail.
+
+ Armed after, the single failure it exists to recover from is exactly the one
+ that skips it, and recovery never happens."""
+ monkeypatch.setenv("DISABLE_PRISMA_HEALTH_CHECK_ON_STARTUP", "False")
+ monkeypatch.setattr(
+ proxy_server_module,
+ "general_settings",
+ {"allow_requests_on_db_unavailable": True},
+ )
+
+ mock_client = _mock_startup_prisma_client(health_check_error=httpx.ReadTimeout("startup health check timed out"))
+ call_order = MagicMock()
+ call_order.attach_mock(mock_client.start_db_health_watchdog_task, "watchdog")
+ call_order.attach_mock(mock_client.health_check, "health_check")
+
+ await _run_setup_prisma_client(mock_client)
+
+ assert mock_client.start_db_health_watchdog_task.await_count == 1
+ assert [call[0] for call in call_order.mock_calls] == ["watchdog", "health_check"]
+
+
+ @pytest.mark.asyncio
+ async def test_setup_prisma_client_raises_when_db_unavailable_is_not_allowed(monkeypatch):
+ """Without ``allow_requests_on_db_unavailable`` a failed startup health check
+ must still hard-fail startup. Retaining the client is a fallback for
+ operators who opted into serving traffic without a database, never a way to
+ boot a proxy whose DB never answered."""
+ monkeypatch.setenv("DISABLE_PRISMA_HEALTH_CHECK_ON_STARTUP", "False")
+ monkeypatch.setattr(
+ proxy_server_module,
+ "general_settings",
+ {"allow_requests_on_db_unavailable": False},
+ )
+
+ mock_client = _mock_startup_prisma_client(health_check_error=httpx.ReadTimeout("startup health check timed out"))
+ with pytest.raises(httpx.ReadTimeout):
+ await _run_setup_prisma_client(mock_client)
+
+
+ @pytest.mark.asyncio
+ async def test_setup_prisma_client_returns_none_when_connect_itself_fails(monkeypatch):
+ """Retaining only ever applies to a client that connected. If ``connect()``
+ failed there is no usable client and no watchdog to recover it, so the caller
+ must still get ``None``."""
+ monkeypatch.setenv("DISABLE_PRISMA_HEALTH_CHECK_ON_STARTUP", "False")
+ monkeypatch.setattr(
+ proxy_server_module,
+ "general_settings",
+ {"allow_requests_on_db_unavailable": True},
+ )
+
+ mock_client = _mock_startup_prisma_client(connect_error=httpx.ConnectError("connection refused"))
+ result = await _run_setup_prisma_client(mock_client)
+
+ assert result is None
+ assert mock_client.start_db_health_watchdog_task.await_count == 0
+ assert mock_client.health_check.await_count == 0
+
+
+ async def _run_scheduled_background_jobs():
+ from litellm.proxy.proxy_server import ProxyStartupEvent
+ from litellm.proxy.utils import ProxyLogging
+
+ mock_prisma_client = MagicMock()
+ mock_prisma_client.db.litellm_config.find_first = AsyncMock(return_value=None)
+
+ mock_proxy_logging = MagicMock(spec=ProxyLogging)
+ mock_proxy_logging.slack_alerting_instance = MagicMock()
+ mock_proxy_logging.db_spend_update_writer = MagicMock()
+ mock_proxy_config = AsyncMock()
+
+ with (
+ patch("litellm.proxy.proxy_server.proxy_config", mock_proxy_config),
+ patch("litellm.proxy.proxy_server.store_model_in_db", True),
+ patch("litellm.proxy.proxy_server.get_secret_bool", return_value=True),
+ ):
+ await ProxyStartupEvent.initialize_scheduled_background_jobs(
+ general_settings={},
+ prisma_client=mock_prisma_client,
+ proxy_budget_rescheduler_min_time=1,
+ proxy_budget_rescheduler_max_time=2,
+ proxy_batch_write_at=5,
+ proxy_logging_obj=mock_proxy_logging,
+ )
+
+ import litellm.proxy.proxy_server as ps
+
+ assert ps.scheduler is not None
+ return ps.scheduler
+
+
+ @pytest.mark.asyncio
+ async def test_ptu_rollup_job_registered_at_startup(monkeypatch):
+ """The PTU rollup cron is registered once an operator opts in; only models with PTU config accrue flat cost (asserted in test_ptu_flat_cost_rollup.py)."""
+ monkeypatch.delenv("STORE_MODEL_IN_DB", raising=False)
+ from litellm.proxy.spend_tracking.ptu_feature_flag import PTU_COST_ATTRIBUTION_ENV_VAR
+ from litellm.proxy.spend_tracking.ptu_flat_cost_rollup import (
+ PTU_ROLLUP_JOB_ID,
+ )
+
+ monkeypatch.setenv(PTU_COST_ATTRIBUTION_ENV_VAR, "true")
+
+ scheduler = await _run_scheduled_background_jobs()
+
+ assert scheduler.get_job(PTU_ROLLUP_JOB_ID) is not None
+
+
+ @pytest.mark.asyncio
+ async def test_ptu_rollup_job_hands_the_rollup_the_proxys_router(monkeypatch):
+ """The rollup prices PTU deployments declared in config.yaml, which only the router
+ knows about. It takes the router as an argument, so nothing but this call site puts the
+ proxy's own router in front of it: without it that half of the feature is dead."""
+ monkeypatch.delenv("STORE_MODEL_IN_DB", raising=False)
+ from litellm.proxy.spend_tracking import ptu_flat_cost_rollup
+ from litellm.proxy.spend_tracking.ptu_feature_flag import PTU_COST_ATTRIBUTION_ENV_VAR
+ from litellm.proxy.spend_tracking.ptu_flat_cost_rollup import PTU_ROLLUP_JOB_ID
+
+ monkeypatch.setenv(PTU_COST_ATTRIBUTION_ENV_VAR, "true")
+ calls = []
+ monkeypatch.setattr(
+ ptu_flat_cost_rollup,
+ "run_scheduled_ptu_rollup",
+ AsyncMock(side_effect=lambda *args, **kwargs: calls.append(kwargs)),
+ )
+
+ scheduler = await _run_scheduled_background_jobs()
+
+ import litellm.proxy.proxy_server as ps
+
+ router = MagicMock()
+ monkeypatch.setattr(ps, "llm_router", router)
+ await scheduler.get_job(PTU_ROLLUP_JOB_ID).func()
+
+ assert [call["router"] for call in calls] == [router]
+
+
+ @pytest.mark.asyncio
+ async def test_ptu_rollup_job_not_registered_without_opt_in(monkeypatch):
+ """Without LITELLM_ENABLE_PTU_COST_ATTRIBUTION the rollup never runs, so no sentinel row
+ is ever written. This is the gate that keeps the whole feature inert by default."""
+ monkeypatch.delenv("STORE_MODEL_IN_DB", raising=False)
+ from litellm.proxy.spend_tracking.ptu_feature_flag import PTU_COST_ATTRIBUTION_ENV_VAR
+ from litellm.proxy.spend_tracking.ptu_flat_cost_rollup import (
+ PTU_ROLLUP_JOB_ID,
+ )
+
+ monkeypatch.delenv(PTU_COST_ATTRIBUTION_ENV_VAR, raising=False)
+
+ scheduler = await _run_scheduled_background_jobs()
+
+ assert scheduler.get_job(PTU_ROLLUP_JOB_ID) is None
+ assert len(scheduler.get_jobs()) > 0
+
+
+ @pytest.mark.asyncio
+ async def test_moderations_reraises_proxy_exception_unwrapped():
+ """A 400 ProxyException from request validation must surface as-is,
+ not be re-wrapped into a code-500 ProxyException."""
+ from litellm.proxy._types import ProxyErrorTypes, ProxyException
+
+ exc = ProxyException(
+ message="Invalid type for 'metadata': expected an object, but got a string instead.",
+ type=ProxyErrorTypes.bad_request_error,
+ param="metadata",
+ code=400,
+ )
+
+ request = MagicMock()
+ request.body = AsyncMock(return_value=b'{"input": "hi", "metadata": "abc"}')
+
+ with (
+ patch.object(proxy_server_module, "add_litellm_data_to_request", new=AsyncMock(side_effect=exc)),
+ patch.object(proxy_server_module, "proxy_logging_obj") as mock_logging,
+ ):
+ mock_logging.post_call_failure_hook = AsyncMock()
+ with pytest.raises(ProxyException) as exc_info:
+ await proxy_server_module.moderations(
+ request=request,
+ fastapi_response=MagicMock(),
+ user_api_key_dict=MagicMock(),
+ )
+
+ assert exc_info.value is exc
+ assert exc_info.value.code == "400"
+ assert exc_info.value.param == "metadata"
+ mock_logging.post_call_failure_hook.assert_awaited_once()
+
+
+ @pytest.mark.asyncio
+ async def test_init_agents_in_db_rebuilds_registry_under_agent_reconcile_lock(monkeypatch):
+ from litellm.proxy.agent_endpoints.agent_registry import (
+ AGENT_RECONCILE_LOCK,
+ global_agent_registry,
+ )
+ from litellm.proxy.proxy_server import ProxyConfig
+
+ lock_states: list[bool] = []
+
+ async def fake_get_all_agents_from_db(prisma_client) -> list:
+ lock_states.append(AGENT_RECONCILE_LOCK.locked())
+ return []
+
+ def fake_load_agents_from_db_and_config(db_agents) -> None:
+ lock_states.append(AGENT_RECONCILE_LOCK.locked())
+
+ monkeypatch.setattr(global_agent_registry, "get_all_agents_from_db", fake_get_all_agents_from_db)
+ monkeypatch.setattr(global_agent_registry, "load_agents_from_db_and_config", fake_load_agents_from_db_and_config)
+
+ await ProxyConfig()._init_agents_in_db(prisma_client=MagicMock())
+
+ assert lock_states == [True, True]
+ assert not AGENT_RECONCILE_LOCK.locked()
+
+
+ @pytest.mark.asyncio
+ async def test_init_guardrails_in_db_snapshots_and_reconciles_under_guardrail_reconcile_lock(monkeypatch):
+ from litellm.proxy.guardrails.guardrail_registry import (
+ GUARDRAIL_RECONCILE_LOCK,
+ IN_MEMORY_GUARDRAIL_HANDLER,
+ GuardrailRegistry,
+ )
+ from litellm.proxy.proxy_server import ProxyConfig
+
+ lock_states: list[bool] = []
+
+ async def fake_get_all_guardrails_from_db(prisma_client) -> list:
+ lock_states.append(GUARDRAIL_RECONCILE_LOCK.locked())
+ return []
+
+ def fake_reconcile_db_guardrails(db_guardrail_ids) -> list:
+ lock_states.append(GUARDRAIL_RECONCILE_LOCK.locked())
+ return []
+
+ monkeypatch.setattr(GuardrailRegistry, "get_all_guardrails_from_db", fake_get_all_guardrails_from_db)
+ monkeypatch.setattr(IN_MEMORY_GUARDRAIL_HANDLER, "reconcile_db_guardrails", fake_reconcile_db_guardrails)
+
+ await ProxyConfig()._init_guardrails_in_db(prisma_client=MagicMock())
+
+ assert lock_states == [True, True]
+ assert not GUARDRAIL_RECONCILE_LOCK.locked()
+
+
+
+ @pytest.mark.asyncio
+ async def test_init_prompts_in_db_reloads_rows_patched_on_another_worker(monkeypatch):
+ from litellm.proxy.prompts.prompt_registry import IN_MEMORY_PROMPT_REGISTRY
+ from litellm.proxy.proxy_server import ProxyConfig
+
+ monkeypatch.setattr(litellm, "callbacks", [])
+
+ def db_row(content: str) -> MagicMock:
+ row = MagicMock()
+ row.model_dump.return_value = {
+ "prompt_id": "greeting_sync",
+ "version": 1,
+ "environment": "development",
+ "created_by": None,
+ "litellm_params": json.dumps(
+ {
+ "prompt_id": "greeting_sync",
+ "prompt_integration": "dotprompt",
+ "prompt_data": {"content": content, "metadata": {}},
+ }
+ ),
+ "prompt_info": json.dumps({"prompt_type": "db"}),
+ "created_at": None,
+ "updated_at": None,
+ }
+ return row
+
+ def served_content() -> str:
+ callback = IN_MEMORY_PROMPT_REGISTRY.get_prompt_callback_by_id("greeting_sync.v1")
+ assert callback is not None
+ return callback.prompt_manager.get_prompt("greeting_sync").content
+
+ prisma_client = MagicMock()
+ try:
+ prisma_client.db.litellm_prompttable.find_many = AsyncMock(return_value=[db_row("Begin every reply with AHOY")])
+ await ProxyConfig()._init_prompts_in_db(prisma_client=prisma_client)
+ assert served_content() == "Begin every reply with AHOY"
+
+ prisma_client.db.litellm_prompttable.find_many = AsyncMock(return_value=[db_row("Begin every reply with HOWDY")])
+ await ProxyConfig()._init_prompts_in_db(prisma_client=prisma_client)
+
+ assert served_content() == "Begin every reply with HOWDY"
+ assert litellm.callbacks == [IN_MEMORY_PROMPT_REGISTRY.get_prompt_callback_by_id("greeting_sync.v1")]
+ finally:
+ IN_MEMORY_PROMPT_REGISTRY.delete_prompts_by_base_id("greeting_sync")
+
+
+ @pytest.mark.asyncio
+ async def test_init_prompts_in_db_syncs_remaining_rows_when_one_row_fails(monkeypatch):
+ from litellm.proxy.prompts.prompt_registry import IN_MEMORY_PROMPT_REGISTRY
+ from litellm.proxy.proxy_server import ProxyConfig
+
+ monkeypatch.setattr(litellm, "callbacks", [])
+
+ def db_row(prompt_id: str, integration: str) -> MagicMock:
+ row = MagicMock()
+ row.model_dump.return_value = {
+ "prompt_id": prompt_id,
+ "version": 1,
+ "environment": "development",
+ "created_by": None,
+ "litellm_params": json.dumps(
+ {
+ "prompt_id": prompt_id,
+ "prompt_integration": integration,
+ "prompt_data": {"content": "Begin every reply with AHOY", "metadata": {}},
+ }
+ ),
+ "prompt_info": json.dumps({"prompt_type": "db"}),
+ "created_at": None,
+ "updated_at": None,
+ }
+ return row
+
+ prisma_client = MagicMock()
+ try:
+ prisma_client.db.litellm_prompttable.find_many = AsyncMock(
+ return_value=[db_row("broken_sync", "does_not_exist"), db_row("healthy_sync", "dotprompt")]
+ )
+ await ProxyConfig()._init_prompts_in_db(prisma_client=prisma_client)
+
+ assert IN_MEMORY_PROMPT_REGISTRY.get_prompt_by_id("broken_sync.v1") is None
+ assert IN_MEMORY_PROMPT_REGISTRY.get_prompt_callback_by_id("healthy_sync.v1") is not None
+ assert litellm.callbacks == [IN_MEMORY_PROMPT_REGISTRY.get_prompt_callback_by_id("healthy_sync.v1")]
+ finally:
+ IN_MEMORY_PROMPT_REGISTRY.delete_prompts_by_base_id("healthy_sync")
+ IN_MEMORY_PROMPT_REGISTRY.delete_prompts_by_base_id("broken_sync")
+
+
+ @pytest.mark.asyncio
+ async def test_init_prompts_in_db_serves_the_newest_row_when_environments_collide_on_a_versioned_id(monkeypatch):
+ from litellm.proxy.prompts.prompt_registry import IN_MEMORY_PROMPT_REGISTRY
+ from litellm.proxy.proxy_server import ProxyConfig
+
+ monkeypatch.setattr(litellm, "callbacks", [])
+
+ def db_row(environment: str, content: str, updated_at: datetime) -> MagicMock:
+ row = MagicMock()
+ row.model_dump.return_value = {
+ "prompt_id": "greeting_env",
+ "version": 1,
+ "environment": environment,
+ "created_by": None,
+ "litellm_params": json.dumps(
+ {
+ "prompt_id": "greeting_env",
+ "prompt_integration": "dotprompt",
+ "prompt_data": {"content": content, "metadata": {}},
+ }
+ ),
+ "prompt_info": json.dumps({"prompt_type": "db"}),
+ "created_at": None,
+ "updated_at": updated_at,
+ }
+ return row
+
+ freshly_patched = db_row(
+ "production", "Begin every reply with HOWDY", datetime(2026, 8, 26, 12, 0, tzinfo=timezone.utc)
+ )
+ stale_sibling = db_row(
+ "development", "Begin every reply with AHOY", datetime(2026, 8, 26, 11, 0, tzinfo=timezone.utc)
+ )
+
+ prisma_client = MagicMock()
+ try:
+ prisma_client.db.litellm_prompttable.find_many = AsyncMock(return_value=[freshly_patched, stale_sibling])
+ await ProxyConfig()._init_prompts_in_db(prisma_client=prisma_client)
+
+ first_callback = IN_MEMORY_PROMPT_REGISTRY.get_prompt_callback_by_id("greeting_env.v1")
+ assert first_callback is not None
+ assert first_callback.prompt_manager.get_prompt("greeting_env").content == "Begin every reply with HOWDY"
+
+ await ProxyConfig()._init_prompts_in_db(prisma_client=prisma_client)
+
+ assert IN_MEMORY_PROMPT_REGISTRY.get_prompt_callback_by_id("greeting_env.v1") is first_callback
+ assert litellm.callbacks == [first_callback]
+ finally:
+ IN_MEMORY_PROMPT_REGISTRY.delete_prompts_by_base_id("greeting_env")
+
+
+ def _prompt_db_row(prompt_id: str, litellm_params: str) -> MagicMock:
+ row = MagicMock()
+ row.model_dump.return_value = {
+ "prompt_id": prompt_id,
+ "version": 1,
+ "environment": "development",
+ "created_by": None,
+ "litellm_params": litellm_params,
+ "prompt_info": json.dumps({"prompt_type": "db"}),
+ "created_at": None,
+ "updated_at": None,
+ }
+ return row
+
+
+ def _dotprompt_params(prompt_id: str) -> str:
+ return json.dumps(
+ {
+ "prompt_id": prompt_id,
+ "prompt_integration": "dotprompt",
+ "prompt_data": {"content": "Begin every reply with AHOY", "metadata": {}},
+ }
+ )
+
+
+ @pytest.mark.asyncio
+ async def test_init_prompts_in_db_unloads_rows_deleted_on_another_worker(monkeypatch):
+ from litellm.proxy.prompts.prompt_registry import IN_MEMORY_PROMPT_REGISTRY
+ from litellm.proxy.proxy_server import ProxyConfig
+
+ monkeypatch.setattr(litellm, "callbacks", [])
+
+ prisma_client = MagicMock()
+ try:
+ prisma_client.db.litellm_prompttable.find_many = AsyncMock(
+ return_value=[_prompt_db_row("greeting_del", _dotprompt_params("greeting_del"))]
+ )
+ await ProxyConfig()._init_prompts_in_db(prisma_client=prisma_client)
+ assert IN_MEMORY_PROMPT_REGISTRY.get_prompt_callback_by_id("greeting_del.v1") is not None
+
+ prisma_client.db.litellm_prompttable.find_many = AsyncMock(return_value=[])
+ await ProxyConfig()._init_prompts_in_db(prisma_client=prisma_client)
+
+ assert IN_MEMORY_PROMPT_REGISTRY.get_prompt_by_id("greeting_del.v1") is None
+ assert IN_MEMORY_PROMPT_REGISTRY.get_prompt_callback_by_id("greeting_del.v1") is None
+ assert litellm.callbacks == []
+ finally:
+ IN_MEMORY_PROMPT_REGISTRY.delete_prompts_by_base_id("greeting_del")
+
+
+ @pytest.mark.asyncio
+ async def test_init_prompts_in_db_keeps_config_prompts_when_their_id_has_no_db_row(monkeypatch):
+ from litellm.proxy.prompts.prompt_registry import IN_MEMORY_PROMPT_REGISTRY
+ from litellm.proxy.proxy_server import ProxyConfig
+ from litellm.types.prompts.init_prompts import PromptInfo, PromptLiteLLMParams, PromptSpec
+
+ monkeypatch.setattr(litellm, "callbacks", [])
+
+ config_prompt = PromptSpec(
+ prompt_id="greeting_cfg",
+ litellm_params=PromptLiteLLMParams(
+ prompt_id="greeting_cfg",
+ prompt_integration="dotprompt",
+ prompt_data={"content": "Begin every reply with AHOY", "metadata": {}},
+ ),
+ prompt_info=PromptInfo(prompt_type="config"),
+ )
+
+ prisma_client = MagicMock()
+ try:
+ IN_MEMORY_PROMPT_REGISTRY.initialize_prompt(prompt=config_prompt)
+ prisma_client.db.litellm_prompttable.find_many = AsyncMock(return_value=[])
+
+ await ProxyConfig()._init_prompts_in_db(prisma_client=prisma_client)
+
+ assert IN_MEMORY_PROMPT_REGISTRY.get_prompt_callback_by_id("greeting_cfg") is not None
+ assert len(litellm.callbacks) == 1
+ finally:
+ IN_MEMORY_PROMPT_REGISTRY.remove_prompt(prompt_id="greeting_cfg")
+
+
+ @pytest.mark.asyncio
+ async def test_init_prompts_in_db_keeps_the_in_memory_copy_when_a_row_fails_to_parse(monkeypatch):
+ from litellm.proxy.prompts.prompt_registry import IN_MEMORY_PROMPT_REGISTRY
+ from litellm.proxy.proxy_server import ProxyConfig
+
+ monkeypatch.setattr(litellm, "callbacks", [])
+
+ prisma_client = MagicMock()
+ try:
+ prisma_client.db.litellm_prompttable.find_many = AsyncMock(
+ return_value=[_prompt_db_row("greeting_broken", _dotprompt_params("greeting_broken"))]
+ )
+ await ProxyConfig()._init_prompts_in_db(prisma_client=prisma_client)
+ loaded_callback = IN_MEMORY_PROMPT_REGISTRY.get_prompt_callback_by_id("greeting_broken.v1")
+ assert loaded_callback is not None
+
+ prisma_client.db.litellm_prompttable.find_many = AsyncMock(
+ return_value=[_prompt_db_row("greeting_broken", "this is not json")]
+ )
+ await ProxyConfig()._init_prompts_in_db(prisma_client=prisma_client)
+
+ assert IN_MEMORY_PROMPT_REGISTRY.get_prompt_callback_by_id("greeting_broken.v1") is loaded_callback
+ assert litellm.callbacks == [loaded_callback]
+ finally:
+ IN_MEMORY_PROMPT_REGISTRY.delete_prompts_by_base_id("greeting_broken")
+
+
+ @pytest.mark.asyncio
+ async def test_init_prompts_in_db_keeps_a_prompt_created_while_the_sync_was_reading(monkeypatch):
+ from litellm.proxy.prompts.prompt_registry import IN_MEMORY_PROMPT_REGISTRY
+ from litellm.proxy.proxy_server import ProxyConfig
+ from litellm.types.prompts.init_prompts import PromptInfo, PromptLiteLLMParams, PromptSpec
+
+ monkeypatch.setattr(litellm, "callbacks", [])
+
+ prisma_client = MagicMock()
+ try:
+
+ async def create_prompt_behind_the_select() -> list:
+ IN_MEMORY_PROMPT_REGISTRY.initialize_prompt(
+ prompt=PromptSpec(
+ prompt_id="greeting_race.v1",
+ litellm_params=PromptLiteLLMParams(
+ prompt_id="greeting_race",
+ prompt_integration="dotprompt",
+ prompt_data={"content": "Begin every reply with AHOY", "metadata": {}},
+ ),
+ prompt_info=PromptInfo(prompt_type="db"),
+ )
+ )
+ return []
+
+ prisma_client.db.litellm_prompttable.find_many = AsyncMock(side_effect=create_prompt_behind_the_select)
+ await ProxyConfig()._init_prompts_in_db(prisma_client=prisma_client)
+
+ surviving_callback = IN_MEMORY_PROMPT_REGISTRY.get_prompt_callback_by_id("greeting_race.v1")
+ assert IN_MEMORY_PROMPT_REGISTRY.get_prompt_by_id("greeting_race.v1") is not None
+ assert surviving_callback is not None
+ assert litellm.callbacks == [surviving_callback]
+ finally:
+ IN_MEMORY_PROMPT_REGISTRY.delete_prompts_by_base_id("greeting_race")
+
+
+ class TestEmbeddingsFailureHookRequestData:
+ @pytest.mark.asyncio
+ async def test_failure_hook_gets_post_setup_data_with_logging_obj(self):
+ """Request setup replaces the processor's data dict (adding the logging
+ object the failure hook needs to lift token usage from); the embeddings
+ exception handler must pass that replaced dict, not the raw request body
+ dict it was rebuilt from."""
+ from litellm.proxy._types import ProxyException
+
+ captured = {}
+ logging_obj_sentinel = MagicMock()
+
+ async def fake_process(self, **kwargs):
+ self.data = {**self.data, "litellm_logging_obj": logging_obj_sentinel}
+ captured["processor_data"] = self.data
+ raise RuntimeError("provider timeout")
+
+ with (
+ patch.object(
+ proxy_server_module,
+ "_read_request_body",
+ new=AsyncMock(return_value={"model": "my-embed", "input": "hello"}),
+ ),
+ patch.object(
+ proxy_server_module.ProxyBaseLLMRequestProcessing,
+ "base_process_llm_request",
+ new=fake_process,
+ ),
+ patch.object(proxy_server_module, "proxy_logging_obj") as mock_logging,
+ ):
+ mock_logging.post_call_failure_hook = AsyncMock(return_value=None)
+ with pytest.raises(ProxyException):
+ await proxy_server_module.embeddings(
+ request=MagicMock(),
+ fastapi_response=MagicMock(),
+ user_api_key_dict=UserAPIKeyAuth(),
+ )
+
+ hook_request_data = mock_logging.post_call_failure_hook.await_args.kwargs["request_data"]
+ assert hook_request_data is captured["processor_data"]
+ assert hook_request_data["litellm_logging_obj"] is logging_obj_sentinel
+
+
+ @pytest.mark.asyncio
+ async def test_authoritative_floor_spend_keeps_a_reset_marker_written_during_the_db_read():
+ """A team-member spend reset writes the post-reset floor to the spend_db_floor marker
+ (auth_checks.invalidate_team_member_spend_state). A floor read already in flight when the
+ reset commits would otherwise cache its stale pre-reset DB value over the fresh marker,
+ letting a budget check raise the counter right back above the just-reset spend
+ (regression: PR #37971 Greptile finding)."""
+ from litellm.proxy.proxy_server import _authoritative_floor_spend
+
+ real_spend_counter_cache = DualCache()
+ counter_key = "spend:team_member:user-1:team-1"
+ marker_key = f"spend_db_floor:{counter_key}"
+
+ async def db_read_racing_with_a_reset(prisma_client, counter_key):
+ real_spend_counter_cache.in_memory_cache.set_cache(key=marker_key, value=0.0)
+ return 999.0
+
+ with (
+ patch.object( # test-quality-ok: injects a real DualCache for the module global, not a behavior mock
+ proxy_server_module, "spend_counter_cache", real_spend_counter_cache
+ ),
+ patch.object( # test-quality-ok: the DB read must race the reset; no injectable seam for module-global prisma reads
+ proxy_server_module.SpendCounterReseed,
+ "from_db",
+ AsyncMock(side_effect=db_read_racing_with_a_reset),
+ ),
+ ):
+ result = await _authoritative_floor_spend(counter_key=counter_key)
+
+ assert result == 0.0
+ assert real_spend_counter_cache.in_memory_cache.get_cache(key=marker_key) == 0.0, (
+ "the in-flight DB read clobbered the post-reset floor marker with the stale pre-reset value"
+ )
+
+
+ @pytest.mark.asyncio
+ async def test_load_config_router_authorizes_fallback_targets_against_the_calling_key(tmp_path):
+ from litellm.proxy.auth.fallback_model_access import router_fallback_access_check
+ from litellm.proxy.proxy_server import ProxyConfig
+
+ config_file = tmp_path / "config.yaml"
+ config_file.write_text(
+ yaml.dump({"model_list": [{"model_name": "m", "litellm_params": {"model": "openai/m", "api_key": "k"}}]})
+ )
+
+ router, _, _ = await ProxyConfig().load_config(router=None, config_file_path=str(config_file))
+
+ assert router.fallback_access_check is router_fallback_access_check