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]

fix(budgets): drop the bespoke access group cache TTL and format the repository

ryan-crabbe-berri06d0665f5026
diff --git a/litellm/constants.py b/litellm/constants.py
index 2139b12e024..6ee4f151bc0 100644
--- a/litellm/constants.py
+++ b/litellm/constants.py
@@ -1681,7 +1681,6 @@ DEFAULT_MCP_NAMESPACE_CSV_MAX_TOKENS: Final = 16
# Ceilings on the cached auth registries; larger tables fall back to per-row lookups
# instead of holding an unbounded id set in every worker.
TAG_REGISTRY_MAX_SIZE: Final = 5000
-DEFAULT_MODEL_ACCESS_GROUP_CACHE_TTL: Final = int(os.getenv("DEFAULT_MODEL_ACCESS_GROUP_CACHE_TTL", 600))
MODEL_ACCESS_GROUP_REGISTRY_MAX_SIZE: Final = 5000
END_USER_RESTRICTED_REGISTRY_MAX_SIZE: Final = 5000
# How long a failed registry load is remembered as "unusable", so a degraded Postgres
diff --git a/litellm/proxy/auth/auth_checks.py b/litellm/proxy/auth/auth_checks.py
index cd4d03e08e2..19e4f158144 100644
--- a/litellm/proxy/auth/auth_checks.py
+++ b/litellm/proxy/auth/auth_checks.py
@@ -30,7 +30,6 @@ from litellm.constants import (
DEFAULT_ACCESS_GROUP_CACHE_TTL,
DEFAULT_IN_MEMORY_TTL,
DEFAULT_MAX_RECURSE_DEPTH,
- DEFAULT_MODEL_ACCESS_GROUP_CACHE_TTL,
EMAIL_BUDGET_ALERT_MAX_SPEND_ALERT_PERCENTAGE,
END_USER_RESTRICTED_REGISTRY_MAX_SIZE,
MODEL_ACCESS_GROUP_REGISTRY_MAX_SIZE,
@@ -1951,7 +1950,7 @@ async def _fetch_uncached_model_access_group_budgets(
key=model_access_group_cache_key(fetched_name),
value=fetched_obj,
model_type=ModelAccessGroupBudget,
- ttl=DEFAULT_MODEL_ACCESS_GROUP_CACHE_TTL,
+ ttl=get_management_object_ttl(user_api_key_cache),
)
except Exception as e: # noqa: BLE001 # fail-safe: a budget fetch error must yield "no budget rows", never break auth
verbose_proxy_logger.debug("Error batch fetching model access group budgets from database: %s", e)
diff --git a/litellm/repositories/table_repositories.py b/litellm/repositories/table_repositories.py
index de13e5aeb6c..fac142bb017 100644
--- a/litellm/repositories/table_repositories.py
+++ b/litellm/repositories/table_repositories.py
@@ -100,9 +100,7 @@ class TagRepository(PrismaTableRepository["prisma_models.LiteLLM_TagTable"]):
table_name = "litellm_tagtable"
-class ModelAccessGroupBudgetRepository(
- PrismaTableRepository["prisma_models.LiteLLM_ModelAccessGroupBudgetTable"]
-):
+class ModelAccessGroupBudgetRepository(PrismaTableRepository["prisma_models.LiteLLM_ModelAccessGroupBudgetTable"]):
table_name = "litellm_modelaccessgroupbudgettable"
diff --git a/tests/test_litellm/repositories/test_unit_of_work.py b/tests/test_litellm/repositories/test_unit_of_work.py
index 1ebfd917e36..1a76b537e95 100644
--- a/tests/test_litellm/repositories/test_unit_of_work.py
+++ b/tests/test_litellm/repositories/test_unit_of_work.py
@@ -1,9 +1,11 @@
+from dataclasses import fields
from datetime import datetime, timezone
from typing import Any, Dict, List, Mapping, Tuple
import pytest
from litellm.repositories.unit_of_work import (
+ LinkedSpendResetWrites,
budget_cascade_unit_of_work,
spend_reset_unit_of_work,
)
@@ -32,6 +34,7 @@ class FakeBatch:
self.litellm_teammembership = FakeBatchTable("litellm_teammembership", self.calls)
self.litellm_organizationtable = FakeBatchTable("litellm_organizationtable", self.calls)
self.litellm_tagtable = FakeBatchTable("litellm_tagtable", self.calls)
+ self.litellm_modelaccessgroupbudgettable = FakeBatchTable("litellm_modelaccessgroupbudgettable", self.calls)
self.litellm_endusertable = FakeBatchTable("litellm_endusertable", self.calls)
async def commit(self) -> None:
@@ -90,6 +93,7 @@ async def test_budget_cascade_dependents_and_window_advance_share_one_batch():
uow.keys.queue_spend_zero(where=linked)
uow.organizations.queue_spend_zero(where=linked)
uow.tags.queue_spend_zero(where=linked)
+ uow.model_access_groups.queue_spend_zero(where=linked)
uow.endusers.queue_spend_zero(where={"user_id": {"in": ["enduser-1"]}})
uow.budgets.queue_window_advance(budget_id="budget-1", budget_reset_at=reset_at)
assert batch.commit_count == 0
@@ -100,6 +104,7 @@ async def test_budget_cascade_dependents_and_window_advance_share_one_batch():
("litellm_verificationtoken.update_many", linked, {"spend": 0}),
("litellm_organizationtable.update_many", linked, {"spend": 0}),
("litellm_tagtable.update_many", linked, {"spend": 0}),
+ ("litellm_modelaccessgroupbudgettable.update_many", linked, {"spend": 0}),
("litellm_endusertable.update_many", {"user_id": {"in": ["enduser-1"]}}, {"spend": 0}),
("litellm_budgettable.update_many", {"budget_id": "budget-1"}, {"budget_reset_at": reset_at}),
]
@@ -117,6 +122,39 @@ async def test_budget_window_advance_tolerates_a_tier_deleted_mid_chunk():
assert [call[0] for call in batch.calls] == ["litellm_budgettable.update_many"]
+async def test_every_cascade_dependent_writes_to_its_own_table_on_the_one_batch():
+ """Walks the dataclass instead of naming tables, so a dependent added to
+ BudgetCascadeUnitOfWork later cannot go uncovered.
+
+ The named test above only proves the tables it lists, and an unbound
+ dependent surfaces as an AttributeError from whichever tests happen to
+ open a cascade. This pins the real contract: every field writes, each to a
+ distinct table, all on the same batch.
+ """
+ reset_at = datetime(2026, 8, 3, 12, 0, tzinfo=timezone.utc)
+ batches: List[FakeBatch] = []
+
+ def _new_batch() -> FakeBatch:
+ # Fresh per call like db.batch_(), unlike the `lambda: batch` above: a
+ # second transaction would otherwise alias onto the first and hide.
+ batches.append(FakeBatch())
+ return batches[-1]
+
+ async with budget_cascade_unit_of_work(_new_batch) as uow:
+ writes = [getattr(uow, field.name) for field in fields(uow)]
+ for write in writes:
+ if isinstance(write, LinkedSpendResetWrites):
+ write.queue_spend_zero(where={"budget_id": "budget-1"})
+ else:
+ write.queue_window_advance(budget_id="budget-1", budget_reset_at=reset_at)
+
+ assert len(batches) == 1, "the cascade must open exactly one transaction"
+ batch = batches[0]
+ assert len(batch.calls) == len(writes), "a dependent bound to a batch of its own would not land here"
+ assert len({call[0] for call in batch.calls}) == len(writes), "two dependents share one table"
+ assert batch.commit_count == 1
+
+
async def test_budget_cascade_raising_inside_block_skips_commit():
"""A failure part-way through must leave budget_reset_at where it was, so
the tier is still due on the next tick."""