The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
feat(budgets): add configurable budget_reset_time of day (#31007)
ryan-crabbe-berriefa997dfe0c0
diff --git a/litellm/litellm_core_utils/duration_parser.py b/litellm/litellm_core_utils/duration_parser.pyindex 438ff5600ba..79036367652 100644--- a/litellm/litellm_core_utils/duration_parser.py+++ b/litellm/litellm_core_utils/duration_parser.py@@ -7,8 +7,8 @@ duration_in_seconds is used in diff parts of the code base, example"""import re-import time-from datetime import datetime, timedelta, timezone, tzinfo+import time as time_module+from datetime import datetime, time, timedelta, timezone, tzinfofrom typing import Optional, Tuplefrom zoneinfo import ZoneInfo@@ -61,7 +61,7 @@ def duration_in_seconds(duration: str) -> int:elif unit == "w":return value * 604800elif unit == "mo":- now = time.time()+ now = time_module.time()current_time = datetime.fromtimestamp(now)# Calculate target month and year, handling overflow past December@@ -94,12 +94,17 @@ def duration_in_seconds(duration: str) -> int:raise ValueError(f"Unsupported duration unit, passed duration: {duration}")-def get_next_standardized_reset_time(duration: str, current_time: datetime, timezone_str: str = "UTC") -> datetime:+def get_next_standardized_reset_time(+ duration: str,+ current_time: datetime,+ timezone_str: str = "UTC",+ reset_time_of_day: time = time(0, 0),+) -> datetime:"""Get the next standardized reset time based on the duration.All durations will reset at predictable intervals, aligned from the current time:- - Nd: If N=1, reset at next midnight; if N>1, reset every N days from now+ - Nd: If N=1, reset at the next `reset_time_of_day`; if N>1, reset every N days from now- Nh: Every N hours, aligned to hour boundaries (e.g., 1:00, 2:00)- Nm: Every N minutes, aligned to minute boundaries (e.g., 1:05, 1:10)- Ns: Every N seconds, aligned to second boundaries@@ -108,12 +113,15 @@ def get_next_standardized_reset_time(duration: str, current_time: datetime, time- duration: Duration string (e.g. "30s", "30m", "30h", "30d")- current_time: Current datetime- timezone_str: Timezone string (e.g. "UTC", "US/Eastern", "Asia/Kolkata")+ - reset_time_of_day: Wall-clock time the reset lands on for day/week/month+ durations (defaults to midnight). Ignored for sub-day durations, where a+ time-of-day is meaningless.Returns:- Next reset time at a standardized interval in the specified timezone"""# Set up timezone and normalize current time- current_time, tz = _setup_timezone(current_time, timezone_str)+ current_time, _ = _setup_timezone(current_time, timezone_str)# Parse durationvalue, unit = _parse_duration(duration)@@ -126,9 +134,9 @@ def get_next_standardized_reset_time(duration: str, current_time: datetime, time# Handle different time unitsif unit == "d":- return _handle_day_reset(current_time, base_midnight, value, tz)+ return _handle_day_reset(current_time, base_midnight, value, reset_time_of_day)elif unit == "w":- return _handle_day_reset(current_time, base_midnight, value * 7, tz)+ return _handle_day_reset(current_time, base_midnight, value * 7, reset_time_of_day)elif unit == "h":return _handle_hour_reset(current_time, base_midnight, value)elif unit == "m":@@ -136,7 +144,7 @@ def get_next_standardized_reset_time(duration: str, current_time: datetime, timeelif unit == "s":return _handle_second_reset(current_time, base_midnight, value)elif unit == "mo":- return _handle_month_reset(current_time, base_midnight, value)+ return _handle_month_reset(current_time, base_midnight, value, reset_time_of_day)else:# Unrecognized unit, default to next midnightreturn base_midnight + timedelta(days=1)@@ -175,46 +183,58 @@ def _parse_duration(duration: str) -> Tuple[Optional[int], Optional[str]]:return int(value), unit-def _handle_day_reset(current_time: datetime, base_midnight: datetime, value: int, tz: tzinfo) -> datetime:+def _apply_time_of_day(dt: datetime, reset_time_of_day: time) -> datetime:+ """Set the wall-clock time of `dt` to `reset_time_of_day`, keeping its date and tzinfo."""+ return dt.replace(+ hour=reset_time_of_day.hour,+ minute=reset_time_of_day.minute,+ second=reset_time_of_day.second,+ microsecond=reset_time_of_day.microsecond,+ )+++def _next_occurrence(+ boundary_midnight: datetime,+ reset_time_of_day: time,+ current_time: datetime,+ period: timedelta,+) -> datetime:+ """Place the reset at `reset_time_of_day` on the boundary day, rolling forward one+ `period` if that instant has already passed (or is exactly now)."""+ candidate = _apply_time_of_day(boundary_midnight, reset_time_of_day)+ if candidate <= current_time:+ return candidate + period+ return candidate+++def _first_of_next_month(first_of_month: datetime) -> datetime:+ """Given the 1st of some month, return the 1st of the following month."""+ if first_of_month.month == 12:+ return first_of_month.replace(year=first_of_month.year + 1, month=1)+ return first_of_month.replace(month=first_of_month.month + 1)+++def _handle_day_reset(+ current_time: datetime,+ base_midnight: datetime,+ value: int,+ reset_time_of_day: time,+) -> datetime:"""Handle day-based reset times."""# Handle zero value - immediate expirationif value == 0:return current_time- if value == 1: # Daily reset at midnight- return base_midnight + timedelta(days=1)- elif value == 7: # Weekly reset on Monday at midnight+ if value == 1: # Daily reset at the configured time of day+ return _next_occurrence(base_midnight, reset_time_of_day, current_time, timedelta(days=1))+ elif value == 7: # Weekly reset on Monday at the configured time of daydays_until_monday = (7 - current_time.weekday()) % 7- if days_until_monday == 0: # If today is Monday- days_until_monday = 7- return base_midnight + timedelta(days=days_until_monday)- elif value == 30: # Monthly reset on 1st at midnight- # Get 1st of next month at midnight- if current_time.month == 12:- next_reset = datetime(- year=current_time.year + 1,- month=1,- day=1,- hour=0,- minute=0,- second=0,- microsecond=0,- tzinfo=tz,- )- else:- next_reset = datetime(- year=current_time.year,- month=current_time.month + 1,- day=1,- hour=0,- minute=0,- second=0,- microsecond=0,- tzinfo=tz,- )- return next_reset- else: # Custom day value - next interval is value days from current- return current_time.replace(hour=0, minute=0, second=0, microsecond=0) + timedelta(days=value)+ upcoming_monday = base_midnight + timedelta(days=days_until_monday)+ return _next_occurrence(upcoming_monday, reset_time_of_day, current_time, timedelta(days=7))+ elif value == 30: # Monthly reset on 1st at the configured time of day+ return _handle_month_reset(current_time, base_midnight, 1, reset_time_of_day)+ else: # Custom day value - next interval is value days from the start of today+ return _apply_time_of_day(base_midnight + timedelta(days=value), reset_time_of_day)def _handle_hour_reset(current_time: datetime, base_midnight: datetime, value: int) -> datetime:@@ -316,36 +336,30 @@ def _handle_second_reset(current_time: datetime, base_midnight: datetime, value:return current_time.replace(hour=next_hour, minute=next_minute, second=next_second, microsecond=0)-def _handle_month_reset(current_time: datetime, base_midnight: datetime, value: int) -> datetime:+def _handle_month_reset(+ current_time: datetime,+ base_midnight: datetime,+ value: int,+ reset_time_of_day: time,+) -> datetime:"""- Handle monthly reset times. For monthly resets, we always reset at the start of the next month.+ Handle monthly reset times. Resets land on the 1st at `reset_time_of_day`; if the+ 1st of the current month at that time has already passed, roll to the 1st of next month.Args:current_time: Current datetimebase_midnight: Midnight of current dayvalue: Number of months (currently only supports 1 month resets)+ reset_time_of_day: Wall-clock time the reset lands onReturns:- datetime: First day of next month at midnight+ datetime: First day of the next reset month at `reset_time_of_day`"""if value != 1:raise ValueError("Monthly resets currently only support 1 month intervals")- # Get the first day of next month- if current_time.month == 12:- next_month = 1- next_year = current_time.year + 1- else:- next_month = current_time.month + 1- next_year = current_time.year-- return datetime(- year=next_year,- month=next_month,- day=1,- hour=0,- minute=0,- second=0,- microsecond=0,- tzinfo=current_time.tzinfo,- )+ first_of_this_month = base_midnight.replace(day=1)+ candidate = _apply_time_of_day(first_of_this_month, reset_time_of_day)+ if candidate <= current_time:+ return _apply_time_of_day(_first_of_next_month(first_of_this_month), reset_time_of_day)+ return candidatediff --git a/litellm/proxy/common_utils/reset_budget_job.py b/litellm/proxy/common_utils/reset_budget_job.pyindex e758420ee37..23a5b8f9c53 100644--- a/litellm/proxy/common_utils/reset_budget_job.py+++ b/litellm/proxy/common_utils/reset_budget_job.py@@ -13,6 +13,11 @@ from litellm.proxy._types import (LiteLLM_UserTable,LiteLLM_VerificationToken,)+from litellm.proxy.common_utils.timezone_utils import (+ BudgetResetSettings,+ compute_budget_reset_at,+ get_budget_reset_settings,+)from litellm.proxy.utils import PrismaClient, ProxyLoggingfrom litellm.repositories.organization_repository import OrganizationRepositoryfrom litellm.repositories.table_repositories import (@@ -32,9 +37,15 @@ class ResetBudgetJob:Resets the budget for all the keys, users, and teams that need it"""- def __init__(self, proxy_logging_obj: ProxyLogging, prisma_client: PrismaClient):+ def __init__(+ self,+ proxy_logging_obj: ProxyLogging,+ prisma_client: PrismaClient,+ reset_settings: BudgetResetSettings | None = None,+ ):self.proxy_logging_obj: ProxyLogging = proxy_logging_objself.prisma_client: PrismaClient = prisma_client+ self.reset_settings: BudgetResetSettings = reset_settings or get_budget_reset_settings()async def reset_budget(self,@@ -237,7 +248,7 @@ class ResetBudgetJob:if budgets_to_reset is not None and len(budgets_to_reset) > 0:for budget in budgets_to_reset:- budget = await ResetBudgetJob._reset_budget_reset_at_date(budget, now)+ budget = await ResetBudgetJob._reset_budget_reset_at_date(budget, now, self.reset_settings)await self.prisma_client.update_data(query_type="update_many",@@ -442,7 +453,11 @@ class ResetBudgetJob:if keys_to_reset is not None and len(keys_to_reset) > 0:for key in keys_to_reset:try:- updated_key = await ResetBudgetJob._reset_budget_for_key(key=key, current_time=now)+ updated_key = await ResetBudgetJob._reset_budget_for_key(+ key=key,+ current_time=now,+ reset_settings=self.reset_settings,+ )if updated_key is not None:updated_keys.append(updated_key)else:@@ -513,7 +528,11 @@ class ResetBudgetJob:if users_to_reset is not None and len(users_to_reset) > 0:for user in users_to_reset:try:- updated_user = await ResetBudgetJob._reset_budget_for_user(user=user, current_time=now)+ updated_user = await ResetBudgetJob._reset_budget_for_user(+ user=user,+ current_time=now,+ reset_settings=self.reset_settings,+ )if updated_user is not None:updated_users.append(updated_user)else:@@ -588,7 +607,11 @@ class ResetBudgetJob:if teams_to_reset is not None and len(teams_to_reset) > 0:for team in teams_to_reset:try:- updated_team = await ResetBudgetJob._reset_budget_for_team(team=team, current_time=now)+ updated_team = await ResetBudgetJob._reset_budget_for_team(+ team=team,+ current_time=now,+ reset_settings=self.reset_settings,+ )if updated_team is not None:updated_teams.append(updated_team)else:@@ -655,10 +678,9 @@ class ResetBudgetJob:counter_key: str,spend_counter_cache: Any,now: datetime,+ reset_settings: BudgetResetSettings,) -> bool:"""Reset a single budget window if expired. Returns True if the window was reset."""- from litellm.proxy.common_utils.timezone_utils import get_budget_reset_time-reset_at_str = window.get("reset_at")if not reset_at_str:return False@@ -671,7 +693,9 @@ class ResetBudgetJob:await spend_counter_cache.redis_cache.async_set_cache(key=counter_key, value=0.0)except Exception as redis_err:verbose_proxy_logger.warning("Failed to reset Redis counter %s: %s", counter_key, redis_err)- window["reset_at"] = get_budget_reset_time(budget_duration=window["budget_duration"]).isoformat()+ window["reset_at"] = compute_budget_reset_at(+ budget_duration=window["budget_duration"], settings=reset_settings+ ).isoformat()return Trueasync def reset_budget_windows(self) -> None:@@ -703,7 +727,13 @@ class ResetBudgetJob:changed = Falsefor 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):+ if await ResetBudgetJob._reset_expired_window(+ window,+ counter_key,+ spend_counter_cache,+ now,+ self.reset_settings,+ ):changed = Trueif changed:await VerificationTokenRepository(self.prisma_client).table.update(@@ -726,7 +756,13 @@ class ResetBudgetJob:changed = Falsefor 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):+ if await ResetBudgetJob._reset_expired_window(+ window,+ counter_key,+ spend_counter_cache,+ now,+ self.reset_settings,+ ):changed = Trueif changed:await TeamRepository(self.prisma_client).table.update(@@ -741,6 +777,7 @@ class ResetBudgetJob:item: Union[LiteLLM_TeamTable, LiteLLM_UserTable, LiteLLM_VerificationToken],current_time: datetime,item_type: Literal["key", "team", "user"],+ reset_settings: BudgetResetSettings,):"""In-place, updates spend=0, and sets budget_reset_at to current_time + budget_duration@@ -755,24 +792,40 @@ class ResetBudgetJob:try:item.spend = 0.0if hasattr(item, "budget_duration") and item.budget_duration is not None:- from litellm.proxy.common_utils.timezone_utils import (- get_budget_reset_time,+ item.budget_reset_at = compute_budget_reset_at(+ budget_duration=item.budget_duration, settings=reset_settings)-- item.budget_reset_at = get_budget_reset_time(budget_duration=item.budget_duration)return itemexcept Exception as e:verbose_proxy_logger.exception("Error resetting budget for %s: %s. Item: %s", item_type, e, item)raise e@staticmethod- async def _reset_budget_for_team(team: LiteLLM_TeamTable, current_time: datetime) -> Optional[LiteLLM_TeamTable]:- await ResetBudgetJob._reset_budget_common(item=team, current_time=current_time, item_type="team")+ async def _reset_budget_for_team(+ team: LiteLLM_TeamTable,+ current_time: datetime,+ reset_settings: BudgetResetSettings,+ ) -> LiteLLM_TeamTable | None:+ await ResetBudgetJob._reset_budget_common(+ item=team,+ current_time=current_time,+ item_type="team",+ reset_settings=reset_settings,+ )return team@staticmethod- async def _reset_budget_for_user(user: LiteLLM_UserTable, current_time: datetime) -> Optional[LiteLLM_UserTable]:- await ResetBudgetJob._reset_budget_common(item=user, current_time=current_time, item_type="user")+ async def _reset_budget_for_user(+ user: LiteLLM_UserTable,+ current_time: datetime,+ reset_settings: BudgetResetSettings,+ ) -> LiteLLM_UserTable | None:+ await ResetBudgetJob._reset_budget_common(+ item=user,+ current_time=current_time,+ item_type="user",+ reset_settings=reset_settings,+ )return user@staticmethod@@ -788,15 +841,15 @@ class ResetBudgetJob:@staticmethodasync def _reset_budget_reset_at_date(- budget: LiteLLM_BudgetTableFull, current_time: datetime+ budget: LiteLLM_BudgetTableFull,+ current_time: datetime,+ reset_settings: BudgetResetSettings,) -> LiteLLM_BudgetTableFull:try:if budget.budget_duration is not None:- from litellm.proxy.common_utils.timezone_utils import (- get_budget_reset_time,+ budget.budget_reset_at = compute_budget_reset_at(+ budget_duration=budget.budget_duration, settings=reset_settings)-- budget.budget_reset_at = get_budget_reset_time(budget_duration=budget.budget_duration)except Exception as e:verbose_proxy_logger.exception("Error resetting budget_reset_at for budget: %s. Item: %s", e, budget)raise e@@ -804,7 +857,14 @@ class ResetBudgetJob:@staticmethodasync def _reset_budget_for_key(- key: LiteLLM_VerificationToken, current_time: datetime- ) -> Optional[LiteLLM_VerificationToken]:- await ResetBudgetJob._reset_budget_common(item=key, current_time=current_time, item_type="key")+ key: LiteLLM_VerificationToken,+ current_time: datetime,+ reset_settings: BudgetResetSettings,+ ) -> LiteLLM_VerificationToken | None:+ await ResetBudgetJob._reset_budget_common(+ item=key,+ current_time=current_time,+ item_type="key",+ reset_settings=reset_settings,+ )return keydiff --git a/litellm/proxy/common_utils/timezone_utils.py b/litellm/proxy/common_utils/timezone_utils.pyindex 32f9f47d519..a50daf40144 100644--- a/litellm/proxy/common_utils/timezone_utils.py+++ b/litellm/proxy/common_utils/timezone_utils.py@@ -1,10 +1,47 @@-from datetime import datetime, timezone+from datetime import datetime, time, timezone++from pydantic import BaseModel, ConfigDictimport litellmfrom litellm.litellm_core_utils.duration_parser import get_next_standardized_reset_time-def get_budget_reset_timezone():+class BudgetResetSettings(BaseModel):+ """Immutable, validated settings that govern when budgets reset.++ Parsed once from `litellm_settings` and injected into consumers (the reset+ job, management endpoints) so reset times never depend on reaching into+ module-level globals at call time.+ """++ model_config = ConfigDict(frozen=True)++ timezone: str = "UTC"+ reset_time_of_day: time = time(0, 0)+++def parse_budget_reset_time(raw: object) -> time:+ """Parse a `budget_reset_time` config value (e.g. "12:00") into a `time`.++ Falls back to midnight when unset; raises a clear error on a malformed value+ so a bad config fails loudly at startup instead of silently resetting at midnight.+ """+ if raw is None or raw == "":+ return time(0, 0)+ if not isinstance(raw, str):+ raise ValueError(f"Invalid budget_reset_time {raw!r}; must be a quoted 24-hour 'HH:MM' string, e.g. \"12:00\"")+ for fmt in ("%H:%M", "%H:%M:%S"):+ try:+ parsed = datetime.strptime(raw, fmt)+ return time(hour=parsed.hour, minute=parsed.minute, second=parsed.second)+ except ValueError:+ continue+ raise ValueError(+ f"Invalid budget_reset_time {raw!r}; expected a 24-hour 'HH:MM' or 'HH:MM:SS' string, e.g. \"12:00\""+ )+++def get_budget_reset_timezone() -> str:"""Get the budget reset timezone from litellm_settings.Falls back to UTC if not specified.@@ -15,15 +52,29 @@ def get_budget_reset_timezone():return getattr(litellm, "timezone", None) or "UTC"-def get_budget_reset_time(budget_duration: str) -> datetime:- """- Get the budget reset time based on the configured timezone.- Falls back to UTC if not specified.- """+def get_budget_reset_settings() -> BudgetResetSettings:+ """Build validated reset settings from litellm_settings. Raises on a malformed+ `budget_reset_time`, which lets the proxy fail fast at startup."""+ return BudgetResetSettings(+ timezone=get_budget_reset_timezone(),+ reset_time_of_day=parse_budget_reset_time(getattr(litellm, "budget_reset_time", None)),+ )+- reset_at = get_next_standardized_reset_time(+def compute_budget_reset_at(budget_duration: str, settings: BudgetResetSettings) -> datetime:+ """Compute the next reset time for a budget duration using injected settings."""+ return get_next_standardized_reset_time(duration=budget_duration,current_time=datetime.now(timezone.utc),- timezone_str=get_budget_reset_timezone(),+ timezone_str=settings.timezone,+ reset_time_of_day=settings.reset_time_of_day,)- return reset_at+++def get_budget_reset_time(budget_duration: str) -> datetime:+ """Get the budget reset time using the globally-configured timezone and reset time.++ Thin wrapper over `compute_budget_reset_at` for callers that don't yet receive+ `BudgetResetSettings` by injection (creation/update endpoints, startup backfill).+ """+ return compute_budget_reset_at(budget_duration, get_budget_reset_settings())diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex 3b40abed19e..50fd85a3932 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -319,7 +319,10 @@ from litellm.proxy.common_utils.openai_endpoint_utils import (from litellm.proxy.common_utils.proxy_state import ProxyStatefrom litellm.proxy.common_utils.reset_budget_job import ResetBudgetJobfrom litellm.proxy.common_utils.swagger_utils import ERROR_RESPONSES-from litellm.proxy.common_utils.timezone_utils import get_budget_reset_time+from litellm.proxy.common_utils.timezone_utils import (+ get_budget_reset_settings,+ get_budget_reset_time,+)from litellm.proxy.common_utils.user_api_key_cache import (UserApiKeyCache,get_management_object_ttl,@@ -4597,6 +4600,13 @@ class ProxyConfig:litellm.json_logs = Truelitellm._turn_on_json()verbose_proxy_logger.debug(f"{blue_color_code} Enabled JSON logging via config{reset_color_code}")+ elif key == "budget_reset_time":+ from litellm.proxy.common_utils.timezone_utils import (+ parse_budget_reset_time,+ )++ parse_budget_reset_time(value)+ setattr(litellm, key, value)else:verbose_proxy_logger.debug(f"{blue_color_code} setting litellm.{key}={_redact_general_setting_value(key, value, is_full_admin=False)}{reset_color_code}"@@ -7868,6 +7878,7 @@ class ProxyStartupEvent:budget_reset_job = ResetBudgetJob(proxy_logging_obj=proxy_logging_obj,prisma_client=prisma_client,+ reset_settings=get_budget_reset_settings(),)scheduler.add_job(diff --git a/tests/litellm_utils_tests/test_proxy_budget_reset.py b/tests/litellm_utils_tests/test_proxy_budget_reset.pyindex 5c96eb619bf..44da3ea06a0 100644--- a/tests/litellm_utils_tests/test_proxy_budget_reset.py+++ b/tests/litellm_utils_tests/test_proxy_budget_reset.py@@ -30,6 +30,7 @@ def _attrify(d: dict):None)` (et al), which returns None for plain dicts — that would silentlyskip the row."""+class _AttrDict(dict):def __getattr__(self, k):try:@@ -120,9 +121,11 @@ async def test_reset_budget_keys_partial_failure():key1, key2, key3, key4, key5, key6 = (_attrify(k) for k in [key1, key2, key3, key4, key5, key6])- prisma_client.get_data = AsyncMock(return_value=[key1, key2, key3, key4, key5, key6])+ prisma_client.get_data = AsyncMock(+ return_value=[key1, key2, key3, key4, key5, key6]+ )- async def fake_reset_key(key, current_time):+ async def fake_reset_key(key, current_time, reset_settings=None):if key["id"] == "key1":# Simulate a failure on key1 (for example, this might be due to an invariant check)raise Exception("Simulated failure for key1")@@ -207,9 +210,11 @@ async def test_reset_budget_users_partial_failure():user1, user2, user3, user4, user5, user6 = (_attrify(u) for u in [user1, user2, user3, user4, user5, user6])- prisma_client.get_data = AsyncMock(return_value=[user1, user2, user3, user4, user5, user6])+ prisma_client.get_data = AsyncMock(+ return_value=[user1, user2, user3, user4, user5, user6]+ )- async def fake_reset_user(user, current_time):+ async def fake_reset_user(user, current_time, reset_settings=None):if user["id"] == "user1":raise Exception("Simulated failure for user1")else:@@ -397,7 +402,7 @@ async def test_reset_budget_teams_partial_failure():team1, team2 = _attrify(team1), _attrify(team2)prisma_client.get_data = AsyncMock(return_value=[team1, team2])- async def fake_reset_team(team, current_time):+ async def fake_reset_team(team, current_time, reset_settings=None):if team["id"] == "team1":raise Exception("Simulated failure for team1")else:@@ -513,14 +518,14 @@ async def test_reset_budget_continues_other_categories_on_failure():job = ResetBudgetJob(proxy_logging_obj, prisma_client)- async def fake_reset_key(key, current_time):+ async def fake_reset_key(key, current_time, reset_settings=None):key["spend"] = 0.0key["budget_reset_at"] = (current_time + timedelta(seconds=key["budget_duration"])).isoformat()return key- async def fake_reset_user(user, current_time):+ async def fake_reset_user(user, current_time, reset_settings=None):if user["id"] == "user1":raise Exception("Simulated failure for user1")user["spend"] = 0.0@@ -529,7 +534,7 @@ async def test_reset_budget_continues_other_categories_on_failure():).isoformat()return user- async def fake_reset_team(team, current_time):+ async def fake_reset_team(team, current_time, reset_settings=None):team["spend"] = 0.0team["budget_reset_at"] = (current_time + timedelta(seconds=team["budget_duration"])@@ -632,7 +637,7 @@ async def test_service_logger_keys_success():job = ResetBudgetJob(proxy_logging_obj, prisma_client)- async def fake_reset_key(key, current_time):+ async def fake_reset_key(key, current_time, reset_settings=None):key["spend"] = 0.0key["budget_reset_at"] = (current_time + timedelta(seconds=key["budget_duration"])@@ -688,7 +693,7 @@ async def test_service_logger_keys_failure():job = ResetBudgetJob(proxy_logging_obj, prisma_client)- async def fake_reset_key(key, current_time):+ async def fake_reset_key(key, current_time, reset_settings=None):if key["id"] == "key1":raise Exception("Simulated failure for key1")key["spend"] = 0.0@@ -750,7 +755,7 @@ async def test_service_logger_users_success():job = ResetBudgetJob(proxy_logging_obj, prisma_client)- async def fake_reset_user(user, current_time):+ async def fake_reset_user(user, current_time, reset_settings=None):user["spend"] = 0.0user["budget_reset_at"] = (current_time + timedelta(seconds=user["budget_duration"])@@ -802,7 +807,7 @@ async def test_service_logger_users_failure():job = ResetBudgetJob(proxy_logging_obj, prisma_client)- async def fake_reset_user(user, current_time):+ async def fake_reset_user(user, current_time, reset_settings=None):if user["id"] == "user1":raise Exception("Simulated failure for user1")user["spend"] = 0.0@@ -863,7 +868,7 @@ async def test_service_logger_teams_success():job = ResetBudgetJob(proxy_logging_obj, prisma_client)- async def fake_reset_team(team, current_time):+ async def fake_reset_team(team, current_time, reset_settings=None):team["spend"] = 0.0team["budget_reset_at"] = (current_time + timedelta(seconds=team["budget_duration"])@@ -915,7 +920,7 @@ async def test_service_logger_teams_failure():job = ResetBudgetJob(proxy_logging_obj, prisma_client)- async def fake_reset_team(team, current_time):+ async def fake_reset_team(team, current_time, reset_settings=None):if team["id"] == "team1":raise Exception("Simulated failure for team1")team["spend"] = 0.0diff --git a/tests/test_litellm/litellm_core_utils/test_duration_parser.py b/tests/test_litellm/litellm_core_utils/test_duration_parser.pyindex 3e4446c6672..b6b617610a8 100644--- a/tests/test_litellm/litellm_core_utils/test_duration_parser.py+++ b/tests/test_litellm/litellm_core_utils/test_duration_parser.py@@ -1,5 +1,5 @@import unittest-from datetime import datetime, timezone+from datetime import datetime, time, timezonefrom zoneinfo import ZoneInfofrom litellm.litellm_core_utils.duration_parser import get_next_standardized_reset_time@@ -199,5 +199,122 @@ class TestStandardizedResetTime(unittest.TestCase):self.assertEqual(result, expected)+class TestResetTimeOfDay(unittest.TestCase):+ """A configurable reset_time_of_day shifts day/week/month resets off midnight."""++ def test_daily_reset_before_offset_is_today(self):+ now = datetime(2023, 5, 15, 8, 0, 0, tzinfo=timezone.utc)+ result = get_next_standardized_reset_time(+ "1d", now, "UTC", reset_time_of_day=time(12, 0)+ )+ self.assertEqual(result, datetime(2023, 5, 15, 12, 0, 0, tzinfo=timezone.utc))++ def test_daily_reset_after_offset_is_tomorrow(self):+ now = datetime(2023, 5, 15, 14, 0, 0, tzinfo=timezone.utc)+ result = get_next_standardized_reset_time(+ "1d", now, "UTC", reset_time_of_day=time(12, 0)+ )+ self.assertEqual(result, datetime(2023, 5, 16, 12, 0, 0, tzinfo=timezone.utc))++ def test_daily_reset_exactly_at_offset_rolls_forward(self):+ now = datetime(2023, 5, 15, 12, 0, 0, tzinfo=timezone.utc)+ result = get_next_standardized_reset_time(+ "1d", now, "UTC", reset_time_of_day=time(12, 0)+ )+ self.assertEqual(result, datetime(2023, 5, 16, 12, 0, 0, tzinfo=timezone.utc))++ def test_daily_reset_with_seconds_offset(self):+ now = datetime(2023, 5, 15, 8, 0, 0, tzinfo=timezone.utc)+ result = get_next_standardized_reset_time(+ "1d", now, "UTC", reset_time_of_day=time(9, 30, 15)+ )+ self.assertEqual(result, datetime(2023, 5, 15, 9, 30, 15, tzinfo=timezone.utc))++ def test_offset_applies_in_configured_timezone(self):+ # 2023-05-15 22:30 UTC == 2023-05-16 01:30 in Jerusalem (IDT, UTC+3),+ # so the next noon-Jerusalem reset is 2023-05-16 12:00 IDT.+ now = datetime(2023, 5, 15, 22, 30, 0, tzinfo=timezone.utc)+ result = get_next_standardized_reset_time(+ "1d", now, "Asia/Jerusalem", reset_time_of_day=time(12, 0)+ )+ jerusalem = result.astimezone(ZoneInfo("Asia/Jerusalem"))+ self.assertEqual(+ (jerusalem.year, jerusalem.month, jerusalem.day), (2023, 5, 16)+ )+ self.assertEqual(jerusalem.hour, 12)+ self.assertEqual(jerusalem.minute, 0)++ def test_weekly_reset_lands_on_monday_at_offset(self):+ wednesday = datetime(2023, 5, 17, 15, 45, 0, tzinfo=timezone.utc)+ result = get_next_standardized_reset_time(+ "7d", wednesday, "UTC", reset_time_of_day=time(12, 0)+ )+ self.assertEqual(result, datetime(2023, 5, 22, 12, 0, 0, tzinfo=timezone.utc))++ def test_weekly_reset_today_is_monday_before_offset_is_today(self):+ monday_morning = datetime(2023, 5, 22, 9, 0, 0, tzinfo=timezone.utc)+ result = get_next_standardized_reset_time(+ "7d", monday_morning, "UTC", reset_time_of_day=time(12, 0)+ )+ self.assertEqual(result, datetime(2023, 5, 22, 12, 0, 0, tzinfo=timezone.utc))++ def test_weekly_reset_today_is_monday_after_offset_is_next_week(self):+ monday_afternoon = datetime(2023, 5, 22, 15, 0, 0, tzinfo=timezone.utc)+ result = get_next_standardized_reset_time(+ "7d", monday_afternoon, "UTC", reset_time_of_day=time(12, 0)+ )+ self.assertEqual(result, datetime(2023, 5, 29, 12, 0, 0, tzinfo=timezone.utc))++ def test_monthly_30d_lands_on_first_at_offset(self):+ now = datetime(2023, 5, 15, 10, 30, 0, tzinfo=timezone.utc)+ result = get_next_standardized_reset_time(+ "30d", now, "UTC", reset_time_of_day=time(12, 0)+ )+ self.assertEqual(result, datetime(2023, 6, 1, 12, 0, 0, tzinfo=timezone.utc))++ def test_monthly_1mo_today_is_first_before_offset_is_today(self):+ now = datetime(2023, 5, 1, 9, 0, 0, tzinfo=timezone.utc)+ result = get_next_standardized_reset_time(+ "1mo", now, "UTC", reset_time_of_day=time(12, 0)+ )+ self.assertEqual(result, datetime(2023, 5, 1, 12, 0, 0, tzinfo=timezone.utc))++ def test_monthly_year_rollover_at_offset(self):+ now = datetime(2023, 12, 15, 9, 0, 0, tzinfo=timezone.utc)+ result = get_next_standardized_reset_time(+ "1mo", now, "UTC", reset_time_of_day=time(12, 0)+ )+ self.assertEqual(result, datetime(2024, 1, 1, 12, 0, 0, tzinfo=timezone.utc))++ def test_custom_day_reset_applies_offset(self):+ now = datetime(2023, 5, 15, 10, 30, 0, tzinfo=timezone.utc)+ result = get_next_standardized_reset_time(+ "3d", now, "UTC", reset_time_of_day=time(12, 0)+ )+ self.assertEqual(result, datetime(2023, 5, 18, 12, 0, 0, tzinfo=timezone.utc))++ def test_sub_day_durations_ignore_offset(self):+ base = datetime(2023, 5, 15, 15, 20, 30, tzinfo=timezone.utc)+ self.assertEqual(+ get_next_standardized_reset_time(+ "2h", base, "UTC", reset_time_of_day=time(12, 0)+ ),+ datetime(2023, 5, 15, 16, 0, 0, tzinfo=timezone.utc),+ )+ self.assertEqual(+ get_next_standardized_reset_time(+ "30m", base, "UTC", reset_time_of_day=time(12, 0)+ ),+ datetime(2023, 5, 15, 15, 30, 0, tzinfo=timezone.utc),+ )++ def test_default_offset_is_midnight(self):+ now = datetime(2023, 5, 15, 10, 30, 0, tzinfo=timezone.utc)+ self.assertEqual(+ get_next_standardized_reset_time("1d", now, "UTC"),+ datetime(2023, 5, 16, 0, 0, 0, tzinfo=timezone.utc),+ )++if __name__ == "__main__":unittest.main()diff --git a/tests/test_litellm/proxy/common_utils/test_reset_budget_job.py b/tests/test_litellm/proxy/common_utils/test_reset_budget_job.pyindex 5e348b1bb7e..be5bc74c385 100644--- a/tests/test_litellm/proxy/common_utils/test_reset_budget_job.py+++ b/tests/test_litellm/proxy/common_utils/test_reset_budget_job.py@@ -5,25 +5,23 @@ import sysimport timeimport typesfrom datetime import datetime, timedelta, timezone+from datetime import time as dt_timefrom typing import Any, Dict, Listfrom unittest.mock import AsyncMock, MagicMockimport pytest-sys.path.insert(- 0, os.path.abspath("../../..")-) # Adds the parent directory to the system path+sys.path.insert(0, os.path.abspath("../../..")) # Adds the parent directory to the system pathfrom litellm._logging import verbose_proxy_loggerfrom litellm.proxy.common_utils.reset_budget_job import ResetBudgetJob+from litellm.proxy.common_utils.timezone_utils import BudgetResetSettingsfrom litellm.proxy.utils import ProxyLogging# Mock classes for testingclass MockLiteLLMTeamMembership:- async def update_many(- self, where: Dict[str, Any], data: Dict[str, Any]- ) -> Dict[str, Any]:+ async def update_many(self, where: Dict[str, Any], data: Dict[str, Any]) -> Dict[str, Any]:# Mock the update_many method for litellm_teammembershipreturn {"count": 1}@@ -32,9 +30,7 @@ class MockLiteLLMVerificationToken:def __init__(self):self.update_many_calls: List[Dict[str, Any]] = []- async def update_many(- self, where: Dict[str, Any], data: Dict[str, Any]- ) -> Dict[str, Any]:+ async def update_many(self, where: Dict[str, Any], data: Dict[str, Any]) -> Dict[str, Any]:self.update_many_calls.append({"where": where, "data": data})return {"count": 1}@@ -52,9 +48,7 @@ class MockLiteLLMOrganizationTable:self.find_many_calls.append({"where": where})return self._find_many_results- async def update_many(- self, where: Dict[str, Any], data: Dict[str, Any]- ) -> Dict[str, Any]:+ async def update_many(self, where: Dict[str, Any], data: Dict[str, Any]) -> Dict[str, Any]:self.update_many_calls.append({"where": where, "data": data})return {"count": 1}@@ -72,9 +66,7 @@ class MockLiteLLMTagTable:self.find_many_calls.append({"where": where})return self._find_many_results- async def update_many(- self, where: Dict[str, Any], data: Dict[str, Any]- ) -> Dict[str, Any]:+ async def update_many(self, where: Dict[str, Any], data: Dict[str, Any]) -> Dict[str, Any]:self.update_many_calls.append({"where": where, "data": data})return {"count": 1}@@ -110,9 +102,7 @@ class MockBatcher:_self._outer = outerdef update(_self, where, data):- _self._outer.calls.append(- {"table": _self._table_name, "where": where, "data": data}- )+ _self._outer.calls.append({"table": _self._table_name, "where": where, "data": data})self.litellm_verificationtoken = _Table("key", self)self.litellm_usertable = _Table("user", self)@@ -172,11 +162,7 @@ class MockPrismaClient:return [item for item in data if hasattr(item, "budget_reset_at")]# Handle specific filtering for enduser table queries- if (- table_name == "enduser"- and query_type == "find_all"- and "budget_id_list" in kwargs- ):+ if table_name == "enduser" and query_type == "find_all" and "budget_id_list" in kwargs:budget_id_list = kwargs["budget_id_list"]# Return endusers that match the budget IDsreturn [@@ -188,11 +174,7 @@ class MockPrismaClient:]# Handle key queries with expires and reset_at- if (- table_name == "key"- and query_type == "find_all"- and ("expires" in kwargs or "reset_at" in kwargs)- ):+ if table_name == "key" and query_type == "find_all" and ("expires" in kwargs or "reset_at" in kwargs):return [item for item in data if hasattr(item, "budget_reset_at")]return data@@ -227,9 +209,7 @@ def mock_proxy_logging():@pytest.fixturedef reset_budget_job(mock_prisma_client, mock_proxy_logging):- return ResetBudgetJob(- proxy_logging_obj=mock_proxy_logging, prisma_client=mock_prisma_client- )+ return ResetBudgetJob(proxy_logging_obj=mock_proxy_logging, prisma_client=mock_prisma_client)# Helper function to run async tests@@ -270,6 +250,40 @@ def test_reset_budget_for_key(reset_budget_job, mock_prisma_client):assert set(write["data"].keys()) == {"spend", "budget_reset_at"}+def test_reset_budget_for_key_honors_injected_reset_time(mock_prisma_client, mock_proxy_logging):+ """Injected BudgetResetSettings drives the written reset time end to end (DI, no globals).++ Before the configurable-reset-time change this wrote a midnight reset_at (hour 0);+ with noon injected it must write a noon reset_at.+ """+ job = ResetBudgetJob(+ proxy_logging_obj=mock_proxy_logging,+ prisma_client=mock_prisma_client,+ reset_settings=BudgetResetSettings(timezone="UTC", reset_time_of_day=dt_time(12, 0)),+ )+ now = datetime.now(timezone.utc)+ test_key = type(+ "LiteLLM_VerificationToken",+ (),+ {+ "spend": 100.0,+ "budget_duration": "1d",+ "budget_reset_at": now,+ "id": "test-key-noon",+ "token": "tok-noon",+ },+ )+ mock_prisma_client.data["key"] = [test_key]++ asyncio.run(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+ reset_at = key_writes[0]["data"]["budget_reset_at"].astimezone(timezone.utc)+ assert reset_at.hour == 12+ assert reset_at.minute == 0++def test_reset_budget_for_user(reset_budget_job, mock_prisma_client):# Setup test data with timezone-aware datetimenow = datetime.now(timezone.utc)@@ -486,11 +500,7 @@ def test_reset_budget_for_keys_linked_to_budgets(reset_budget_job, mock_prisma_cbudgets_to_reset = [test_budget]# Run the method- asyncio.run(- reset_budget_job.reset_budget_for_keys_linked_to_budgets(- budgets_to_reset=budgets_to_reset- )- )+ asyncio.run(reset_budget_job.reset_budget_for_keys_linked_to_budgets(budgets_to_reset=budgets_to_reset))# Verify that update_many was called on litellm_verificationtokencalls = mock_prisma_client.db.litellm_verificationtoken.update_many_calls@@ -531,11 +541,7 @@ def test_reset_budget_for_keys_linked_to_budgets_excludes_keys_with_own_budget_dbudgets_to_reset = [test_budget]- asyncio.run(- reset_budget_job.reset_budget_for_keys_linked_to_budgets(- budgets_to_reset=budgets_to_reset- )- )+ asyncio.run(reset_budget_job.reset_budget_for_keys_linked_to_budgets(budgets_to_reset=budgets_to_reset))calls = mock_prisma_client.db.litellm_verificationtoken.update_many_callsassert len(calls) == 1@@ -548,17 +554,13 @@ def test_reset_budget_for_keys_linked_to_budgets_excludes_keys_with_own_budget_dassert call["where"]["budget_id"] == {"in": ["7d-budget-tier"]}-def test_reset_budget_for_keys_linked_to_budgets_empty(- reset_budget_job, mock_prisma_client-):+def test_reset_budget_for_keys_linked_to_budgets_empty(reset_budget_job, mock_prisma_client):"""Test that when there are no budgets to reset, no update is performedon the verification token table."""# Run with empty list- asyncio.run(- reset_budget_job.reset_budget_for_keys_linked_to_budgets(budgets_to_reset=[])- )+ asyncio.run(reset_budget_job.reset_budget_for_keys_linked_to_budgets(budgets_to_reset=[]))# Verify no update_many calls were madecalls = mock_prisma_client.db.litellm_verificationtoken.update_many_calls@@ -584,11 +586,7 @@ def test_reset_budget_for_orgs_linked_to_budgets(reset_budget_job, mock_prisma_c},)- asyncio.run(- reset_budget_job.reset_budget_for_orgs_linked_to_budgets(- budgets_to_reset=[test_budget]- )- )+ asyncio.run(reset_budget_job.reset_budget_for_orgs_linked_to_budgets(budgets_to_reset=[test_budget]))calls = mock_prisma_client.db.litellm_organizationtable.update_many_callsassert len(calls) == 1@@ -598,16 +596,12 @@ def test_reset_budget_for_orgs_linked_to_budgets(reset_budget_job, mock_prisma_cassert call["data"]["spend"] == 0-def test_reset_budget_for_orgs_linked_to_budgets_empty(- reset_budget_job, mock_prisma_client-):+def test_reset_budget_for_orgs_linked_to_budgets_empty(reset_budget_job, mock_prisma_client):"""Test that when there are no budgets to reset, no update is performedon the organization table."""- asyncio.run(- reset_budget_job.reset_budget_for_orgs_linked_to_budgets(budgets_to_reset=[])- )+ asyncio.run(reset_budget_job.reset_budget_for_orgs_linked_to_budgets(budgets_to_reset=[]))calls = mock_prisma_client.db.litellm_organizationtable.update_many_callsassert len(calls) == 0@@ -631,11 +625,7 @@ def test_reset_budget_for_tags_linked_to_budgets(reset_budget_job, mock_prisma_c},)- asyncio.run(- reset_budget_job.reset_budget_for_tags_linked_to_budgets(- budgets_to_reset=[test_budget]- )- )+ asyncio.run(reset_budget_job.reset_budget_for_tags_linked_to_budgets(budgets_to_reset=[test_budget]))calls = mock_prisma_client.db.litellm_tagtable.update_many_callsassert len(calls) == 1@@ -645,16 +635,12 @@ def test_reset_budget_for_tags_linked_to_budgets(reset_budget_job, mock_prisma_cassert call["data"]["spend"] == 0-def test_reset_budget_for_tags_linked_to_budgets_empty(- reset_budget_job, mock_prisma_client-):+def test_reset_budget_for_tags_linked_to_budgets_empty(reset_budget_job, mock_prisma_client):"""Test that when there are no budgets to reset, no update is performedon the tag table."""- asyncio.run(- reset_budget_job.reset_budget_for_tags_linked_to_budgets(budgets_to_reset=[])- )+ asyncio.run(reset_budget_job.reset_budget_for_tags_linked_to_budgets(budgets_to_reset=[]))calls = mock_prisma_client.db.litellm_tagtable.update_many_callsassert len(calls) == 0@@ -668,9 +654,7 @@ def test_reset_budget_for_tags_linked_to_budgets_empty(],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-):+def test_reset_budget_reset_at_date_calendar_aligned(budget_duration, expected_day, expected_month):"""Verify that _reset_budget_reset_at_date produces calendar-aligned resettimes (matching get_budget_reset_time), not sliding-window offsets.@@ -694,7 +678,7 @@ def test_reset_budget_reset_at_date_calendar_aligned(with patch("litellm.proxy.common_utils.timezone_utils.datetime") as mock_dt:mock_dt.now.return_value = fixed_nowmock_dt.side_effect = lambda *args, **kwargs: datetime(*args, **kwargs)- asyncio.run(ResetBudgetJob._reset_budget_reset_at_date(test_budget, fixed_now))+ asyncio.run(ResetBudgetJob._reset_budget_reset_at_date(test_budget, fixed_now, BudgetResetSettings()))assert test_budget.budget_reset_at.day == expected_dayassert test_budget.budget_reset_at.month == expected_month@@ -724,7 +708,7 @@ def test_reset_budget_reset_at_date_7d_next_monday():with patch("litellm.proxy.common_utils.timezone_utils.datetime") as mock_dt:mock_dt.now.return_value = fixed_nowmock_dt.side_effect = lambda *args, **kwargs: datetime(*args, **kwargs)- asyncio.run(ResetBudgetJob._reset_budget_reset_at_date(test_budget, fixed_now))+ asyncio.run(ResetBudgetJob._reset_budget_reset_at_date(test_budget, fixed_now, BudgetResetSettings()))# Next Monday after Wednesday June 14 is June 19assert test_budget.budget_reset_at.day == 19@@ -749,7 +733,7 @@ def test_reset_budget_reset_at_date_none_duration():},)- asyncio.run(ResetBudgetJob._reset_budget_reset_at_date(test_budget, now))+ asyncio.run(ResetBudgetJob._reset_budget_reset_at_date(test_budget, now, BudgetResetSettings()))assert test_budget.budget_reset_at == original_reset_at@@ -773,7 +757,7 @@ def test_reset_budget_reset_at_date_none_reset_at():with patch("litellm.proxy.common_utils.timezone_utils.datetime") as mock_dt:mock_dt.now.return_value = fixed_nowmock_dt.side_effect = lambda *args, **kwargs: datetime(*args, **kwargs)- asyncio.run(ResetBudgetJob._reset_budget_reset_at_date(test_budget, fixed_now))+ asyncio.run(ResetBudgetJob._reset_budget_reset_at_date(test_budget, fixed_now, BudgetResetSettings()))# Should be set to 1st of next month (July 1)assert test_budget.budget_reset_at is not None@@ -781,9 +765,7 @@ def test_reset_budget_reset_at_date_none_reset_at():assert test_budget.budget_reset_at.month == 7-def test_budget_table_reset_also_resets_linked_keys(- reset_budget_job, mock_prisma_client-):+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@@ -818,9 +800,7 @@ def test_budget_table_reset_also_resets_linked_keys(assert calls[0]["data"]["spend"] == 0-def test_budget_table_reset_also_resets_linked_orgs(- reset_budget_job, mock_prisma_client-):+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@@ -853,9 +833,7 @@ def test_budget_table_reset_also_resets_linked_orgs(assert calls[0]["data"]["spend"] == 0-def test_budget_table_reset_also_resets_linked_tags(- reset_budget_job, mock_prisma_client-):+def test_budget_table_reset_also_resets_linked_tags(reset_budget_job, mock_prisma_client):"""Integration-style test: when reset_budget_for_litellm_budget_table runs,it should also reset spend for tags linked to the expiring budget tiers.@@ -887,9 +865,7 @@ def test_budget_table_reset_also_resets_linked_tags(assert calls[0]["data"]["spend"] == 0-def test_reset_budget_resets_endusers_with_null_budget_id(- reset_budget_job, mock_prisma_client-):+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 isbeing reset, end users with budget_id=NULL should also have their spend@@ -959,17 +935,13 @@ def test_reset_budget_resets_endusers_with_null_budget_id(mock_prisma_client.data["enduser"] = [enduser_with_budget]# Set up the DB mock for NULL-budget-id end users- mock_prisma_client.db.litellm_endusertable.set_find_many_results(- [enduser_no_budget_row]- )+ mock_prisma_client.db.litellm_endusertable.set_find_many_results([enduser_no_budget_row])asyncio.run(reset_budget_job.reset_budget_for_litellm_budget_table())# Both end users should have been resetupdated = mock_prisma_client.updated_data["enduser"]- assert (- len(updated) == 2- ), f"Expected 2 endusers reset (1 explicit + 1 implicit), got {len(updated)}"+ assert len(updated) == 2, f"Expected 2 endusers reset (1 explicit + 1 implicit), got {len(updated)}"user_ids = {u.user_id for u in updated}assert "enduser-explicit" in user_ids@@ -986,9 +958,7 @@ def test_reset_budget_resets_endusers_with_null_budget_id(litellm.max_end_user_budget_id = None-def test_reset_budget_skips_null_budget_id_endusers_when_default_not_configured(- reset_budget_job, mock_prisma_client-):+def test_reset_budget_skips_null_budget_id_endusers_when_default_not_configured(reset_budget_job, mock_prisma_client):"""When litellm.max_end_user_budget_id is NOT configured, end users withbudget_id=NULL should NOT be fetched or reset.@@ -1073,20 +1043,14 @@ def test_reset_budget_for_team_members_preserves_total_spend():mock_prisma_client = MagicMock()mock_prisma_client.db.litellm_teammembership.find_many = AsyncMock(return_value=[])- mock_prisma_client.db.litellm_teammembership.update_many = AsyncMock(- return_value={"count": 1}- )+ mock_prisma_client.db.litellm_teammembership.update_many = AsyncMock(return_value={"count": 1})- job = ResetBudgetJob(- proxy_logging_obj=MagicMock(), prisma_client=mock_prisma_client- )+ job = ResetBudgetJob(proxy_logging_obj=MagicMock(), prisma_client=mock_prisma_client)asyncio.run(job.reset_budget_for_litellm_team_members([expired_budget]))mock_prisma_client.db.litellm_teammembership.update_many.assert_called_once()- call_kwargs = (- mock_prisma_client.db.litellm_teammembership.update_many.call_args.kwargs- )+ call_kwargs = mock_prisma_client.db.litellm_teammembership.update_many.call_args.kwargsassert call_kwargs["where"]["budget_id"]["in"] == ["budget-1"]assert call_kwargs["data"] == {"spend": 0}assert "total_spend" not in call_kwargs["data"]@@ -1142,9 +1106,7 @@ def test_reset_budget_windows_uses_is_not_null_filter(monkeypatch):raises `MissingRequiredValueError`. We work around it by using `query_raw`with `IS NOT NULL`. If someone reverts to the ORM filter, this test fails."""- job, prisma_client, _ = _make_reset_budget_windows_job(- monkeypatch, key_rows=[], team_rows=[]- )+ job, prisma_client, _ = _make_reset_budget_windows_job(monkeypatch, key_rows=[], team_rows=[])asyncio.run(job.reset_budget_windows())@@ -1184,15 +1146,11 @@ def test_reset_budget_windows_resets_expired_key_window(monkeypatch):# 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)+ 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- )+ 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):@@ -1206,9 +1164,7 @@ def test_reset_budget_windows_skips_unexpired_key_window(monkeypatch):"budget_limits": [{"budget_duration": "1d", "reset_at": future}],}]- job, prisma_client, _ = _make_reset_budget_windows_job(- monkeypatch, key_rows=key_rows, team_rows=[]- )+ job, prisma_client, _ = _make_reset_budget_windows_job(monkeypatch, key_rows=key_rows, team_rows=[])asyncio.run(job.reset_budget_windows())@@ -1237,9 +1193,7 @@ def test_reset_budget_windows_resets_expired_team_window(monkeypatch):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- )+ 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):@@ -1252,14 +1206,10 @@ def test_reset_budget_windows_handles_string_budget_limits(monkeypatch):key_rows = [{"token": "sk-string-limits",- "budget_limits": json.dumps(- [{"budget_duration": "1d", "reset_at": expired}]- ),+ "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=[]- )+ job, prisma_client, _ = _make_reset_budget_windows_job(monkeypatch, key_rows=key_rows, team_rows=[])asyncio.run(job.reset_budget_windows())@@ -1274,9 +1224,7 @@ def test_reset_budget_windows_skips_row_with_empty_budget_limits(monkeypatch):{"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=[]- )+ job, prisma_client, _ = _make_reset_budget_windows_job(monkeypatch, key_rows=key_rows, team_rows=[])asyncio.run(job.reset_budget_windows())@@ -1361,27 +1309,17 @@ def test_reset_budget_for_team_members_invalidates_redis_counter(monkeypatch):)prisma_client = MagicMock()- prisma_client.db.litellm_teammembership.find_many = AsyncMock(- return_value=[membership]- )- prisma_client.db.litellm_teammembership.update_many = AsyncMock(- return_value={"count": 1}- )+ prisma_client.db.litellm_teammembership.find_many = AsyncMock(return_value=[membership])+ prisma_client.db.litellm_teammembership.update_many = AsyncMock(return_value={"count": 1})job = ResetBudgetJob(proxy_logging_obj=MagicMock(), prisma_client=prisma_client)asyncio.run(job.reset_budget_for_litellm_team_members([expired_budget]))- counter_cache.in_memory_cache.set_cache.assert_any_call(- key="spend:team_member:alice:team-x", value=0.0, ttl=60- )- counter_cache.redis_cache.async_set_cache.assert_any_await(- key="spend:team_member:alice:team-x", value=0.0, ttl=60- )+ counter_cache.in_memory_cache.set_cache.assert_any_call(key="spend:team_member:alice:team-x", value=0.0, ttl=60)+ counter_cache.redis_cache.async_set_cache.assert_any_await(key="spend:team_member:alice:team-x", value=0.0, ttl=60)-def test_reset_budget_for_keys_invalidates_redis_counter(- reset_budget_job, mock_prisma_client, monkeypatch-):+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)@@ -1402,14 +1340,10 @@ def test_reset_budget_for_keys_invalidates_redis_counter(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- )+ 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-):+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)@@ -1430,14 +1364,10 @@ def test_reset_budget_for_users_invalidates_redis_counter(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- )+ counter_cache.in_memory_cache.set_cache.assert_any_call(key="spend:user:alice", value=0.0, ttl=60)-def test_reset_budget_for_teams_invalidates_redis_counter(- reset_budget_job, mock_prisma_client, monkeypatch-):+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)@@ -1458,9 +1388,7 @@ def test_reset_budget_for_teams_invalidates_redis_counter(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- )+ 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):@@ -1511,9 +1439,7 @@ def test_reset_does_not_zero_counter_when_db_write_fails(monkeypatch):batcher.commit = failing_commitprisma_client.db.batch_ = MagicMock(return_value=batcher)- job = ResetBudgetJob(- proxy_logging_obj=MockProxyLogging(), prisma_client=prisma_client- )+ job = ResetBudgetJob(proxy_logging_obj=MockProxyLogging(), prisma_client=prisma_client)asyncio.run(job.reset_budget_for_litellm_keys())@@ -1543,8 +1469,8 @@ def test_reset_budget_for_keys_writes_only_spend_and_reset_at(reset_budget_job,"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+ "object_permission_id": "perm-abc", # would be rejected on update+ "budget_limits": [{"max_budget": 5}], # would be rejected on update"metadata": {"some": "thing"},},)@@ -1570,19 +1496,13 @@ def test_reset_budget_for_keys_linked_to_budgets_invalidates_redis_counter(monkelinked_key = type("Key", (), {"token": "sk-linked"})prisma_client = MagicMock()- prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(- return_value=[linked_key]- )- prisma_client.db.litellm_verificationtoken.update_many = AsyncMock(- return_value={"count": 1}- )+ prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(return_value=[linked_key])+ prisma_client.db.litellm_verificationtoken.update_many = AsyncMock(return_value={"count": 1})job = ResetBudgetJob(proxy_logging_obj=MagicMock(), prisma_client=prisma_client)asyncio.run(job.reset_budget_for_keys_linked_to_budgets([expired_budget]))- counter_cache.in_memory_cache.set_cache.assert_any_call(- key="spend:key:sk-linked", value=0.0, ttl=60- )+ counter_cache.in_memory_cache.set_cache.assert_any_call(key="spend:key:sk-linked", value=0.0, ttl=60)def test_reset_budget_for_orgs_linked_to_budgets_invalidates_redis_counter(monkeypatch):@@ -1593,22 +1513,14 @@ def test_reset_budget_for_orgs_linked_to_budgets_invalidates_redis_counter(monkelinked_org = type("Org", (), {"organization_id": "org-acme"})prisma_client = MagicMock()- prisma_client.db.litellm_organizationtable.find_many = AsyncMock(- return_value=[linked_org]- )- prisma_client.db.litellm_organizationtable.update_many = AsyncMock(- return_value={"count": 1}- )+ prisma_client.db.litellm_organizationtable.find_many = AsyncMock(return_value=[linked_org])+ prisma_client.db.litellm_organizationtable.update_many = AsyncMock(return_value={"count": 1})job = ResetBudgetJob(proxy_logging_obj=MagicMock(), prisma_client=prisma_client)asyncio.run(job.reset_budget_for_orgs_linked_to_budgets([expired_budget]))- counter_cache.in_memory_cache.set_cache.assert_any_call(- key="spend:org:org-acme", value=0.0, ttl=60- )- counter_cache.redis_cache.async_set_cache.assert_any_await(- key="spend:org:org-acme", value=0.0, ttl=60- )+ counter_cache.in_memory_cache.set_cache.assert_any_call(key="spend:org:org-acme", value=0.0, ttl=60)+ counter_cache.redis_cache.async_set_cache.assert_any_await(key="spend:org:org-acme", value=0.0, ttl=60)def test_reset_budget_for_tags_linked_to_budgets_invalidates_redis_counter(monkeypatch):@@ -1625,12 +1537,8 @@ def test_reset_budget_for_tags_linked_to_budgets_invalidates_redis_counter(monkejob = ResetBudgetJob(proxy_logging_obj=MagicMock(), prisma_client=prisma_client)asyncio.run(job.reset_budget_for_tags_linked_to_budgets([expired_budget]))- counter_cache.in_memory_cache.set_cache.assert_any_call(- key="spend:tag:tenant-42", value=0.0, ttl=60- )- counter_cache.redis_cache.async_set_cache.assert_any_await(- key="spend:tag:tenant-42", value=0.0, ttl=60- )+ counter_cache.in_memory_cache.set_cache.assert_any_call(key="spend:tag:tenant-42", value=0.0, ttl=60)+ counter_cache.redis_cache.async_set_cache.assert_any_await(key="spend:tag:tenant-42", value=0.0, ttl=60)def test_reset_budget_for_tags_linked_to_budgets_invalidates_management_cache(@@ -1657,9 +1565,7 @@ def test_reset_budget_for_tags_linked_to_budgets_invalidates_management_cache(job = ResetBudgetJob(proxy_logging_obj=MagicMock(), prisma_client=prisma_client)asyncio.run(job.reset_budget_for_tags_linked_to_budgets([expired_budget]))- counter_cache.user_api_key_cache.async_delete_cache.assert_any_await(- key="tag:tenant-42"- )+ counter_cache.user_api_key_cache.async_delete_cache.assert_any_await(key="tag:tenant-42")def test_reset_budget_for_tags_linked_to_budgets_invalidates_each_tag_management_cache(@@ -1684,8 +1590,7 @@ def test_reset_budget_for_tags_linked_to_budgets_invalidates_each_tag_managementasyncio.run(job.reset_budget_for_tags_linked_to_budgets([expired_budget]))deleted_keys = {- call.kwargs.get("key")- for call in counter_cache.user_api_key_cache.async_delete_cache.await_args_list+ call.kwargs.get("key") for call in counter_cache.user_api_key_cache.async_delete_cache.await_args_list}assert deleted_keys == {"tag:tenant-a", "tag:tenant-b", "tag:tenant-c"}@@ -1711,19 +1616,13 @@ def test_reset_budget_for_keys_linked_to_budgets_invalidates_management_cache(linked_key = type("Key", (), {"token": "sk-linked"})prisma_client = MagicMock()- prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(- return_value=[linked_key]- )- prisma_client.db.litellm_verificationtoken.update_many = AsyncMock(- return_value={"count": 1}- )+ prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(return_value=[linked_key])+ prisma_client.db.litellm_verificationtoken.update_many = AsyncMock(return_value={"count": 1})job = ResetBudgetJob(proxy_logging_obj=MagicMock(), prisma_client=prisma_client)asyncio.run(job.reset_budget_for_keys_linked_to_budgets([expired_budget]))- counter_cache.user_api_key_cache.async_delete_cache.assert_any_await(- key="sk-linked"- )+ counter_cache.user_api_key_cache.async_delete_cache.assert_any_await(key="sk-linked")def test_reset_budget_for_orgs_linked_to_budgets_invalidates_management_cache(@@ -1736,19 +1635,14 @@ def test_reset_budget_for_orgs_linked_to_budgets_invalidates_management_cache(linked_org = type("Org", (), {"organization_id": "org-acme"})prisma_client = MagicMock()- prisma_client.db.litellm_organizationtable.find_many = AsyncMock(- return_value=[linked_org]- )- prisma_client.db.litellm_organizationtable.update_many = AsyncMock(- return_value={"count": 1}- )+ prisma_client.db.litellm_organizationtable.find_many = AsyncMock(return_value=[linked_org])+ prisma_client.db.litellm_organizationtable.update_many = AsyncMock(return_value={"count": 1})job = ResetBudgetJob(proxy_logging_obj=MagicMock(), prisma_client=prisma_client)asyncio.run(job.reset_budget_for_orgs_linked_to_budgets([expired_budget]))deleted_keys = {- call.kwargs.get("key")- for call in counter_cache.user_api_key_cache.async_delete_cache.await_args_list+ call.kwargs.get("key") for call in counter_cache.user_api_key_cache.async_delete_cache.await_args_list}assert deleted_keys == {"org_id:org-acme",@@ -1768,19 +1662,13 @@ def test_reset_budget_for_team_members_invalidates_management_cache(monkeypatch))prisma_client = MagicMock()- prisma_client.db.litellm_teammembership.find_many = AsyncMock(- return_value=[membership]- )- prisma_client.db.litellm_teammembership.update_many = AsyncMock(- return_value={"count": 1}- )+ prisma_client.db.litellm_teammembership.find_many = AsyncMock(return_value=[membership])+ prisma_client.db.litellm_teammembership.update_many = AsyncMock(return_value={"count": 1})job = ResetBudgetJob(proxy_logging_obj=MagicMock(), prisma_client=prisma_client)asyncio.run(job.reset_budget_for_litellm_team_members([expired_budget]))- counter_cache.user_api_key_cache.async_delete_cache.assert_any_await(- key="team-x_alice"- )+ counter_cache.user_api_key_cache.async_delete_cache.assert_any_await(key="team-x_alice")def test_reset_budget_for_tags_linked_to_budgets_management_cache_delete_failure_still_resets(@@ -1788,9 +1676,7 @@ def test_reset_budget_for_tags_linked_to_budgets_management_cache_delete_failure):"""If ``async_delete_cache`` raises, the DB cascade must still complete."""counter_cache = _make_counter_invalidation_job(monkeypatch)- counter_cache.user_api_key_cache.async_delete_cache = AsyncMock(- side_effect=RuntimeError("cache unavailable")- )+ counter_cache.user_api_key_cache.async_delete_cache = AsyncMock(side_effect=RuntimeError("cache unavailable"))expired_budget = type("B", (), {"budget_id": "budget-1"})linked_tag = type("Tag", (), {"tag_name": "tenant-42"})diff --git a/tests/test_litellm/proxy/common_utils/test_timezone_utils.py b/tests/test_litellm/proxy/common_utils/test_timezone_utils.pyindex 80b813226df..7f686c53c95 100644--- a/tests/test_litellm/proxy/common_utils/test_timezone_utils.py+++ b/tests/test_litellm/proxy/common_utils/test_timezone_utils.py@@ -1,19 +1,33 @@import osimport sys-from datetime import datetime, timezone+from datetime import datetime, time, timezonefrom zoneinfo import ZoneInfo+import pytest+sys.path.insert(0, os.path.abspath("../../..")) # Adds the parent directory to the system pathimport litellmfrom litellm.proxy.common_utils.timezone_utils import (+ BudgetResetSettings,+ compute_budget_reset_at,+ get_budget_reset_settings,get_budget_reset_time,get_budget_reset_timezone,+ parse_budget_reset_time,)+def _restore_attr(obj, name, original):+ if original is None:+ if hasattr(obj, name):+ delattr(obj, name)+ else:+ setattr(obj, name, original)++def test_get_budget_reset_time():"""Test that the budget reset time is set to the first of the next month@@ -100,3 +114,69 @@ def test_get_budget_reset_time_respects_timezone():delattr(litellm, "timezone")else:litellm.timezone = original+++def test_parse_budget_reset_time_hh_mm():+ assert parse_budget_reset_time("12:00") == time(12, 0)+++def test_parse_budget_reset_time_hh_mm_ss():+ assert parse_budget_reset_time("09:30:15") == time(9, 30, 15)+++def test_parse_budget_reset_time_unset_defaults_to_midnight():+ assert parse_budget_reset_time(None) == time(0, 0)+ assert parse_budget_reset_time("") == time(0, 0)+++def test_parse_budget_reset_time_invalid_string_raises():+ with pytest.raises(ValueError):+ parse_budget_reset_time("25:00")+ with pytest.raises(ValueError):+ parse_budget_reset_time("noon")+++def test_parse_budget_reset_time_non_string_raises():+ # Unquoted "12:00" in YAML parses to the int 720; it must fail loudly,+ # not silently fall back to midnight.+ with pytest.raises(ValueError):+ parse_budget_reset_time(720)+++def test_get_budget_reset_settings_reads_globals():+ orig_tz = getattr(litellm, "timezone", None)+ orig_rt = getattr(litellm, "budget_reset_time", None)+ try:+ litellm.timezone = "Asia/Jerusalem"+ litellm.budget_reset_time = "12:00"+ settings = get_budget_reset_settings()+ assert settings.timezone == "Asia/Jerusalem"+ assert settings.reset_time_of_day == time(12, 0)+ finally:+ _restore_attr(litellm, "timezone", orig_tz)+ _restore_attr(litellm, "budget_reset_time", orig_rt)+++def test_compute_budget_reset_at_applies_offset():+ settings = BudgetResetSettings(+ timezone="Asia/Jerusalem", reset_time_of_day=time(12, 0)+ )+ reset_at = compute_budget_reset_at("1d", settings)+ jerusalem = reset_at.astimezone(ZoneInfo("Asia/Jerusalem"))+ assert jerusalem.hour == 12+ assert jerusalem.minute == 0+ assert reset_at > datetime.now(timezone.utc)+++def test_get_budget_reset_time_honors_global_budget_reset_time():+ orig_tz = getattr(litellm, "timezone", None)+ orig_rt = getattr(litellm, "budget_reset_time", None)+ try:+ litellm.timezone = "UTC"+ litellm.budget_reset_time = "12:00"+ reset_at = get_budget_reset_time(budget_duration="1d")+ assert reset_at.astimezone(timezone.utc).hour == 12+ assert reset_at.astimezone(timezone.utc).minute == 0+ finally:+ _restore_attr(litellm, "timezone", orig_tz)+ _restore_attr(litellm, "budget_reset_time", orig_rt)