Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions litellm/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -1478,6 +1478,10 @@
SPEND_LOG_CLEANUP_JOB_NAME: Final = "spend_log_cleanup"
KEY_ROTATION_JOB_NAME: Final = "litellm_key_rotation_job"
EXPIRED_UI_SESSION_KEY_CLEANUP_JOB_NAME: Final = "litellm_expired_ui_session_key_cleanup_job"
WEEKLY_SPEND_REPORT_JOB_ID: Final = "weekly_spend_report_job"
MONTHLY_SPEND_REPORT_JOB_ID: Final = "monthly_spend_report_job"
PROMETHEUS_FALLBACK_STATS_JOB_ID: Final = "prometheus_fallback_stats_job"
SLACK_DAILY_REPORT_LOCK_ID: Final = "slack_daily_report"
SPEND_LOG_RUN_LOOPS: Final = int(os.getenv("SPEND_LOG_RUN_LOOPS", 500))
SPEND_LOG_CLEANUP_BATCH_SIZE: Final = int(os.getenv("SPEND_LOG_CLEANUP_BATCH_SIZE", 1000))
SPEND_LOG_CLEANUP_MAX_CONSECUTIVE_BATCH_FAILURES = int(os.getenv("SPEND_LOG_CLEANUP_MAX_CONSECUTIVE_BATCH_FAILURES", 3))
Expand Down
25 changes: 21 additions & 4 deletions litellm/integrations/SlackAlerting/slack_alerting.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
import litellm.types
from litellm._logging import verbose_logger, verbose_proxy_logger
from litellm.caching.caching import DualCache
from litellm.constants import HOURS_IN_A_DAY
from litellm.constants import HOURS_IN_A_DAY, SLACK_DAILY_REPORT_LOCK_ID
from litellm.integrations.custom_batch_logger import CustomBatchLogger
from litellm.integrations.SlackAlerting.budget_alert_types import get_budget_alert_type
from litellm.integrations.SlackAlerting.hanging_request_check import (
Expand Down Expand Up @@ -46,6 +46,7 @@
from .utils import process_slack_alerting_variables

if TYPE_CHECKING:
from litellm.proxy.db.db_transaction_queue.pod_lock_manager import PodLockManager
from litellm.router import Router as _Router

Router = _Router
Expand Down Expand Up @@ -1530,7 +1531,11 @@ async def async_log_failure_event(self, kwargs, response_obj, start_time, end_ti
except Exception:
pass

async def _run_scheduler_helper(self, llm_router) -> bool:
async def _run_scheduler_helper(
self,
llm_router,
pod_lock_manager: "PodLockManager | None" = None,
) -> bool:
"""
Returns:
- True -> report sent
Expand All @@ -1555,6 +1560,14 @@ async def _run_scheduler_helper(self, llm_router) -> bool:
interval_seconds: Final = self.alerting_args.daily_report_frequency

if current_time - report_sent >= interval_seconds:
if (
pod_lock_manager is not None
and (
await pod_lock_manager.acquire_lock(cronjob_id=SLACK_DAILY_REPORT_LOCK_ID, ttl=interval_seconds)
)
is False
):
return False
# Sneak in the reporting logic here
await self.send_daily_reports(router=llm_router)
# Also, don't forget to update the report_sent time after sending the report!
Expand All @@ -1566,7 +1579,11 @@ async def _run_scheduler_helper(self, llm_router) -> bool:

return report_sent_bool

async def _run_scheduled_daily_report(self, llm_router: Any | None = None):
async def _run_scheduled_daily_report(
self,
llm_router: Any | None = None,
pod_lock_manager: "PodLockManager | None" = None,
):
"""
If 'daily_reports' enabled

Expand All @@ -1579,7 +1596,7 @@ async def _run_scheduled_daily_report(self, llm_router: Any | None = None):

if "daily_reports" in self.alert_types:
while True:
await self._run_scheduler_helper(llm_router=llm_router)
await self._run_scheduler_helper(llm_router=llm_router, pod_lock_manager=pod_lock_manager)
interval = random.randint(
self.alerting_args.report_check_interval - 3,
self.alerting_args.report_check_interval + 3,
Expand Down
3 changes: 1 addition & 2 deletions litellm/proxy/db/db_transaction_queue/pod_lock_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,8 +98,7 @@ async def acquire_lock(
return True
else:
verbose_proxy_logger.info(
"Spend tracking - pod %s could not acquire lock for cronjob_id=%s, "
"held by pod %s. Spend updates in Redis will wait for the leader pod to commit.",
"Pod %s could not acquire lock for cronjob_id=%s, held by pod %s.",
self.pod_id,
cronjob_id,
current_value,
Expand Down
47 changes: 38 additions & 9 deletions litellm/proxy/proxy_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,13 +233,16 @@ def generate_feedback_box():
GLOBAL_PROXY_SPEND_CACHE_KEY,
LITELLM_PROXY_ADMIN_NAME,
LITELLM_PROXY_BUDGET_NAME,
MONTHLY_SPEND_REPORT_JOB_ID,
PROMETHEUS_FALLBACK_STATS_JOB_ID,
PROMETHEUS_FALLBACK_STATS_SEND_TIME_HOURS,
PROXY_BATCH_POLLING_ENABLED,
PROXY_BATCH_POLLING_INTERVAL,
PROXY_BATCH_WRITE_AT,
PROXY_BUDGET_RESCHEDULER_MAX_TIME,
PROXY_BUDGET_RESCHEDULER_MIN_TIME,
PROXY_CONFIG_RELOAD_INTERVAL_SECONDS,
WEEKLY_SPEND_REPORT_JOB_ID,
)
from litellm.exceptions import RejectedRequestError
from litellm.integrations.custom_guardrail import ModifyResponseException
Expand Down Expand Up @@ -9043,38 +9046,64 @@ async def _initialize_slack_alerting_jobs(
spend_report_frequency: Final[str] = general_settings.get("spend_report_frequency", "7d") or "7d"

days: Final = int(spend_report_frequency[:-1])
if spend_report_frequency[-1].lower() != "d":
raise ValueError("spend_report_frequency must be specified in days, e.g., '1d', '7d'")
if spend_report_frequency[-1].lower() != "d" or days <= 0:
raise ValueError("spend_report_frequency must be a positive number of days, e.g., '1d', '7d'")

pod_lock_manager: Final = proxy_logging_obj.db_spend_update_writer.pod_lock_manager
weekly_lock_ttl: Final = duration_in_seconds(spend_report_frequency) - 3600

async def _scheduled_weekly_spend_report() -> None:
# TTL spans the whole reporting window: each pod's interval anchor is its own
# boot time + jitter, so a shorter lock would let a later pod re-send the report.
# Minus an hour so the next window's first firer finds a free key
if (
await pod_lock_manager.acquire_lock(cronjob_id=WEEKLY_SPEND_REPORT_JOB_ID, ttl=weekly_lock_ttl)
is False
):
return
await proxy_logging_obj.slack_alerting_instance.send_weekly_spend_report(spend_report_frequency)

async def _scheduled_monthly_spend_report() -> None:
if await pod_lock_manager.acquire_lock(cronjob_id=MONTHLY_SPEND_REPORT_JOB_ID, ttl=3600) is False:
return
await proxy_logging_obj.slack_alerting_instance.send_monthly_spend_report()

scheduler.add_job(
proxy_logging_obj.slack_alerting_instance.send_weekly_spend_report,
_scheduled_weekly_spend_report,
"interval",
days=days,
next_run_time=datetime.now() + timedelta(seconds=10 + random.randint(0, 300)),
args=[spend_report_frequency],
id="weekly_spend_report_job",
id=WEEKLY_SPEND_REPORT_JOB_ID,
replace_existing=True,
misfire_grace_time=APSCHEDULER_MISFIRE_GRACE_TIME,
)

scheduler.add_job(
proxy_logging_obj.slack_alerting_instance.send_monthly_spend_report,
_scheduled_monthly_spend_report,
"cron",
day=1,
id="monthly_spend_report_job",
id=MONTHLY_SPEND_REPORT_JOB_ID,
replace_existing=True,
)

if os.getenv("PROMETHEUS_URL"):
from zoneinfo import ZoneInfo

async def _scheduled_fallback_stats() -> None:
if (
await pod_lock_manager.acquire_lock(cronjob_id=PROMETHEUS_FALLBACK_STATS_JOB_ID, ttl=3600)
is False
):
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
return
await proxy_logging_obj.slack_alerting_instance.send_fallback_stats_from_prometheus()

scheduler.add_job(
proxy_logging_obj.slack_alerting_instance.send_fallback_stats_from_prometheus,
_scheduled_fallback_stats,
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
"cron",
hour=PROMETHEUS_FALLBACK_STATS_SEND_TIME_HOURS,
minute=0,
timezone=ZoneInfo("America/Los_Angeles"),
id="prometheus_fallback_stats_job",
id=PROMETHEUS_FALLBACK_STATS_JOB_ID,
replace_existing=True,
)
await proxy_logging_obj.slack_alerting_instance.send_fallback_stats_from_prometheus()
Expand Down
5 changes: 4 additions & 1 deletion litellm/proxy/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -467,7 +467,10 @@ def startup_event(
and not self.daily_report_started
):
asyncio.create_task(
self.slack_alerting_instance._run_scheduled_daily_report(llm_router=llm_router)
self.slack_alerting_instance._run_scheduled_daily_report(
llm_router=llm_router,
pod_lock_manager=self.db_spend_update_writer.pod_lock_manager,
)
) # RUN DAILY REPORT (if scheduled)
self.daily_report_started = True

Expand Down
Loading
Loading