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
fix(slack_alerting): hold a pod lock so a fleet sends one deprecation alert per day
mateo1e63134adb7b
diff --git a/litellm/constants.py b/litellm/constants.pyindex e9d2d719ae2..5bd62ffed9e 100644--- a/litellm/constants.py+++ b/litellm/constants.py@@ -1485,6 +1485,7 @@ 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"+SLACK_MODEL_DEPRECATION_LOCK_ID: Final = "slack_model_deprecation_warning"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))diff --git a/litellm/integrations/SlackAlerting/slack_alerting.py b/litellm/integrations/SlackAlerting/slack_alerting.pyindex 9f9c26ae15c..71a5cad1331 100644--- a/litellm/integrations/SlackAlerting/slack_alerting.py+++ b/litellm/integrations/SlackAlerting/slack_alerting.py@@ -18,7 +18,11 @@ import litellm.litellm_core_utils.litellm_loggingimport litellm.typesfrom litellm._logging import verbose_logger, verbose_proxy_loggerfrom litellm.caching.caching import DualCache-from litellm.constants import HOURS_IN_A_DAY, SLACK_DAILY_REPORT_LOCK_ID+from litellm.constants import (+ HOURS_IN_A_DAY,+ SLACK_DAILY_REPORT_LOCK_ID,+ SLACK_MODEL_DEPRECATION_LOCK_ID,+)from litellm.integrations.custom_batch_logger import CustomBatchLoggerfrom litellm.integrations.SlackAlerting.budget_alert_types import get_budget_alert_typefrom litellm.integrations.SlackAlerting.hanging_request_check import (@@ -1087,8 +1091,22 @@ Model Info:)return True+ async def _claimed_deprecation_alert_window(self, pod_lock_manager: "PodLockManager | None") -> bool:+ """Without a redis backed lock there is no fleet to coordinate, so a lone pod always alerts"""+ if pod_lock_manager is None:+ return True+ return (+ await pod_lock_manager.acquire_lock(+ cronjob_id=SLACK_MODEL_DEPRECATION_LOCK_ID,+ ttl=DEFAULT_DEPRECATION_CHECK_INTERVAL_SECONDS,+ allow_reentrant=False,+ )+ ) is not False+async def run_scheduled_deprecation_check(- self, get_llm_router: Callable[[], Router | None] = _proxy_llm_router+ self,+ get_llm_router: Callable[[], Router | None] = _proxy_llm_router,+ pod_lock_manager: "PodLockManager | None" = None,) -> None:"""Alert once the router is loaded and the alert is on, then daily, re-reading both each pass"""while True:@@ -1096,7 +1114,8 @@ Model Info:await asyncio.sleep(DEPRECATION_IDLE_POLL_SECONDS)continuetry:- await self.send_model_deprecation_alert(llm_router=llm_router)+ if await self._claimed_deprecation_alert_window(pod_lock_manager):+ await self.send_model_deprecation_alert(llm_router=llm_router)except Exception as e: # noqa: BLE001 # a failed alert must not kill the daily loopverbose_proxy_logger.exception("Error in model deprecation alert loop: %s", e)await asyncio.sleep(DEFAULT_DEPRECATION_CHECK_INTERVAL_SECONDS)diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.pyindex bc73e4d3e5b..e180ba1742c 100644--- a/litellm/proxy/utils.py+++ b/litellm/proxy/utils.py@@ -503,7 +503,11 @@ class ProxyLogging:except RuntimeError:return- asyncio.create_task(self.slack_alerting_instance.run_scheduled_deprecation_check())+ asyncio.create_task(+ self.slack_alerting_instance.run_scheduled_deprecation_check(+ pod_lock_manager=self.db_spend_update_writer.pod_lock_manager+ )+ )self.deprecation_check_started = Truedef update_values(diff --git a/tests/test_litellm/integrations/SlackAlerting/test_model_deprecation_alert.py b/tests/test_litellm/integrations/SlackAlerting/test_model_deprecation_alert.pyindex f475a6d454e..5509933d739 100644--- a/tests/test_litellm/integrations/SlackAlerting/test_model_deprecation_alert.py+++ b/tests/test_litellm/integrations/SlackAlerting/test_model_deprecation_alert.py@@ -11,6 +11,7 @@ import pytestsys.path.insert(0, os.path.abspath("../../../.."))import litellm+from litellm.constants import SLACK_MODEL_DEPRECATION_LOCK_IDfrom litellm.integrations.SlackAlerting.slack_alerting import SlackAlertingfrom litellm.proxy._types import AlertTypefrom litellm.types.proxy.model_deprecation import (@@ -202,3 +203,53 @@ async def test_should_wait_for_the_router_instead_of_sleeping_a_full_day(monkeyp]mock_send_alert.assert_awaited_once()assert "dead-alias" in mock_send_alert.await_args.kwargs["message"]+++ "lock_acquired, expect_alert",+ [(True, True), (None, True), (False, False)],+ ids=["lock won", "no redis lock", "another pod holds the lock"],+)+async def test_should_alert_only_from_the_pod_holding_the_daily_lock(+ monkeypatch, lock_acquired, expect_alert+):+ """Every pod runs the loop, so a fleet must not send one identical alert per replica"""+ monkeypatch.setattr(+ litellm,+ "model_cost",+ {"dead-model": {"deprecation_date": "2020-01-01", "litellm_provider": "openai"}},+ )+ alerting = SlackAlerting(+ alerting=["slack"], alert_types=[AlertType.model_deprecation_warnings]+ )+ router = _make_router(+ [+ {+ "model_name": "dead-alias",+ "litellm_params": {"model": "dead-model"},+ "model_info": {"id": "1"},+ }+ ]+ )+ pod_lock_manager = MagicMock()+ pod_lock_manager.acquire_lock = AsyncMock(return_value=lock_acquired)++ with (+ patch.object(alerting, "send_alert", new_callable=AsyncMock) as mock_send_alert,+ patch(+ "litellm.integrations.SlackAlerting.slack_alerting.asyncio.sleep",+ side_effect=asyncio.CancelledError,+ ),+ pytest.raises(asyncio.CancelledError),+ ):+ await alerting.run_scheduled_deprecation_check(+ get_llm_router=lambda: router, pod_lock_manager=pod_lock_manager+ )++ assert mock_send_alert.await_count == int(expect_alert)+ assert pod_lock_manager.acquire_lock.await_args.kwargs == {+ "cronjob_id": SLACK_MODEL_DEPRECATION_LOCK_ID,+ "ttl": DEFAULT_DEPRECATION_CHECK_INTERVAL_SECONDS,+ "allow_reentrant": False,+ }diff --git a/tests/test_litellm/proxy/utils/proxy_logging/test_lifecycle.py b/tests/test_litellm/proxy/utils/proxy_logging/test_lifecycle.pyindex e45345877f3..a97dcb41e44 100644--- a/tests/test_litellm/proxy/utils/proxy_logging/test_lifecycle.py+++ b/tests/test_litellm/proxy/utils/proxy_logging/test_lifecycle.py@@ -142,7 +142,9 @@ async def test_startup_event_schedules_deprecation_check_before_its_alert_type_iproxy_logging.startup_event(llm_router=None, redis_usage_cache=None)assert proxy_logging.deprecation_check_started is True- proxy_logging.slack_alerting_instance.run_scheduled_deprecation_check.assert_called_once_with()+ proxy_logging.slack_alerting_instance.run_scheduled_deprecation_check.assert_called_once_with(+ pod_lock_manager=proxy_logging.db_spend_update_writer.pod_lock_manager+ )@pytest.mark.asyncio@@ -159,7 +161,9 @@ async def test_update_values_schedules_deprecation_check_when_alerting_arrives_lproxy_logging.update_values(alerting=["slack"])assert proxy_logging.deprecation_check_started is True- proxy_logging.slack_alerting_instance.run_scheduled_deprecation_check.assert_called_once_with()+ proxy_logging.slack_alerting_instance.run_scheduled_deprecation_check.assert_called_once_with(+ pod_lock_manager=proxy_logging.db_spend_update_writer.pod_lock_manager+ )def test_startup_event_propagates_init_callbacks_failure_raises(proxy_logging):