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(alerting): claim the deprecation lock only with content and retry failed claims next poll

mateo-berri308865bad0a2
diff --git a/litellm/integrations/SlackAlerting/slack_alerting.py b/litellm/integrations/SlackAlerting/slack_alerting.py
index 71a5cad1331..2f86f92d06c 100644
--- a/litellm/integrations/SlackAlerting/slack_alerting.py
+++ b/litellm/integrations/SlackAlerting/slack_alerting.py
@@ -1062,8 +1062,16 @@ Model Info:
def _deprecation_alerts_enabled(self) -> bool:
return self.alerting is not None and AlertType.model_deprecation_warnings in self.alert_types
- async def send_model_deprecation_alert(self, llm_router: Router | None = None) -> bool:
- """Alert on the router's deprecated and imminent models, True when one was sent"""
+ async def send_model_deprecation_alert(
+ self,
+ llm_router: Router | None = None,
+ pod_lock_manager: "PodLockManager | None" = None,
+ ) -> bool:
+ """Alert on the router's deprecated and imminent models, True when one was sent
+
+ The daily lock is claimed only once there is something to say, so an empty pass never blocks a
+ later real one, and a sent alert is stamped in the shared cache for a day so sibling pods stop asking
+ """
if not self._deprecation_alerts_enabled():
return False
@@ -1076,6 +1084,8 @@ Model Info:
message: Final = format_deprecation_alert_message(snapshot)
if message is None:
return False
+ if not await self._claimed_deprecation_alert_window(pod_lock_manager):
+ return False
level: Final[Literal["Low", "Medium", "High"]] = "High" if snapshot.deprecated else "Medium"
@@ -1089,6 +1099,11 @@ Model Info:
"upcoming_count": len(snapshot.upcoming),
},
)
+ await self.internal_usage_cache.async_set_cache(
+ key=SlackAlertingCacheKeys.deprecation_alert_sent_key.value,
+ value=time.time(),
+ ttl=DEFAULT_DEPRECATION_CHECK_INTERVAL_SECONDS,
+ )
return True
async def _claimed_deprecation_alert_window(self, pod_lock_manager: "PodLockManager | None") -> bool:
@@ -1103,22 +1118,36 @@ Model Info:
)
) is not False
+ async def _deprecation_alert_sent_within_a_day(self) -> bool:
+ return (
+ await self.internal_usage_cache.async_get_cache(key=SlackAlertingCacheKeys.deprecation_alert_sent_key.value)
+ ) is not None
+
+ async def _run_deprecation_alert_pass(
+ self, llm_router: Router | None, pod_lock_manager: "PodLockManager | None"
+ ) -> bool:
+ if llm_router is None or not self._deprecation_alerts_enabled():
+ return False
+ if await self._deprecation_alert_sent_within_a_day():
+ return False
+ return await self.send_model_deprecation_alert(llm_router=llm_router, pod_lock_manager=pod_lock_manager)
+
async def run_scheduled_deprecation_check(
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"""
+ """Poll every pass for a loaded router, the alert being on, and no alert in the last day, then alert
+
+ A pass that could not alert (no router yet, alert type off, a sibling pod holds the daily lock, or a
+ redis blip at claim time) is retried on the next poll instead of costing a day
+ """
while True:
- if (llm_router := get_llm_router()) is None or not self._deprecation_alerts_enabled():
- await asyncio.sleep(DEPRECATION_IDLE_POLL_SECONDS)
- continue
try:
- 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 loop
+ await self._run_deprecation_alert_pass(get_llm_router(), pod_lock_manager)
+ except Exception as e: # noqa: BLE001 # a failed alert must not kill the loop
verbose_proxy_logger.exception("Error in model deprecation alert loop: %s", e)
- await asyncio.sleep(DEFAULT_DEPRECATION_CHECK_INTERVAL_SECONDS)
+ await asyncio.sleep(DEPRECATION_IDLE_POLL_SECONDS)
async def send_webhook_alert(self, webhook_event: WebhookEvent) -> bool:
"""
diff --git a/litellm/types/integrations/slack_alerting.py b/litellm/types/integrations/slack_alerting.py
index 768b5d35597..b1b7bc3541a 100644
--- a/litellm/types/integrations/slack_alerting.py
+++ b/litellm/types/integrations/slack_alerting.py
@@ -121,6 +121,7 @@ class SlackAlertingCacheKeys(Enum):
failed_requests_key = "failed_requests_daily_metrics"
latency_key = "latency_daily_metrics"
report_sent_key = "daily_metrics_report_sent"
+ deprecation_alert_sent_key = "model_deprecation_alert_sent"
class AlertType(str, Enum):
diff --git a/tests/test_litellm/integrations/SlackAlerting/test_model_deprecation_alert.py b/tests/test_litellm/integrations/SlackAlerting/test_model_deprecation_alert.py
index 5509933d739..9556775dad0 100644
--- a/tests/test_litellm/integrations/SlackAlerting/test_model_deprecation_alert.py
+++ b/tests/test_litellm/integrations/SlackAlerting/test_model_deprecation_alert.py
@@ -14,11 +14,21 @@ import litellm
from litellm.constants import SLACK_MODEL_DEPRECATION_LOCK_ID
from litellm.integrations.SlackAlerting.slack_alerting import SlackAlerting
from litellm.proxy._types import AlertType
+from litellm.types.integrations.slack_alerting import SlackAlertingCacheKeys
from litellm.types.proxy.model_deprecation import (
DEFAULT_DEPRECATION_CHECK_INTERVAL_SECONDS,
DEPRECATION_IDLE_POLL_SECONDS,
)
+DEAD_MODEL_COST = {
+ "dead-model": {"deprecation_date": "2020-01-01", "litellm_provider": "openai"}
+}
+DEAD_ALIAS_DEPLOYMENT = {
+ "model_name": "dead-alias",
+ "litellm_params": {"model": "dead-model"},
+ "model_info": {"id": "1"},
+}
+
def _make_router(deployments):
router = MagicMock()
@@ -105,6 +115,12 @@ async def test_should_dispatch_high_severity_when_deprecated(monkeypatch):
assert call_kwargs["alerting_metadata"]["deprecated_count"] == 1
assert call_kwargs["alerting_metadata"]["imminent_count"] == 0
assert "dead-alias" in call_kwargs["message"]
+ assert isinstance(
+ await alerting.internal_usage_cache.async_get_cache(
+ key=SlackAlertingCacheKeys.deprecation_alert_sent_key.value
+ ),
+ float,
+ )
@pytest.mark.asyncio
@@ -130,29 +146,26 @@ async def test_should_alert_once_the_alert_type_and_router_arrive_after_startup(
slept: list[float] = []
- async def stop_after_second_pass(seconds):
+ async def stop_after_third_pass(seconds):
slept.append(seconds)
if alerting.alert_types == [AlertType.llm_exceptions]:
alerting.update_values(
alert_types=[AlertType.model_deprecation_warnings]
) # simulates a config reload enabling the alert
- return
- raise asyncio.CancelledError
+ if len(slept) == 3:
+ raise asyncio.CancelledError
with (
patch.object(alerting, "send_alert", new_callable=AsyncMock) as mock_send_alert,
patch(
"litellm.integrations.SlackAlerting.slack_alerting.asyncio.sleep",
- side_effect=stop_after_second_pass,
+ side_effect=stop_after_third_pass,
),
pytest.raises(asyncio.CancelledError),
):
await alerting.run_scheduled_deprecation_check(get_llm_router=lambda: router)
- assert slept == [
- DEPRECATION_IDLE_POLL_SECONDS,
- DEFAULT_DEPRECATION_CHECK_INTERVAL_SECONDS,
- ]
+ assert slept == [DEPRECATION_IDLE_POLL_SECONDS] * 3
mock_send_alert.assert_awaited_once()
assert "dead-alias" in mock_send_alert.await_args.kwargs["message"]
@@ -198,9 +211,7 @@ async def test_should_wait_for_the_router_instead_of_sleeping_a_full_day(monkeyp
get_llm_router=lambda: next(routers)
)
- assert slept == [DEPRECATION_IDLE_POLL_SECONDS] * router_absent_passes + [
- DEFAULT_DEPRECATION_CHECK_INTERVAL_SECONDS
- ]
+ assert slept == [DEPRECATION_IDLE_POLL_SECONDS] * (router_absent_passes + 1)
mock_send_alert.assert_awaited_once()
assert "dead-alias" in mock_send_alert.await_args.kwargs["message"]
@@ -253,3 +264,98 @@ async def test_should_alert_only_from_the_pod_holding_the_daily_lock(
"ttl": DEFAULT_DEPRECATION_CHECK_INTERVAL_SECONDS,
"allow_reentrant": False,
}
+
+
+async def test_should_retry_on_the_next_poll_when_the_lock_claim_fails(monkeypatch):
+ """A redis blip at claim time returns False like a held lock, and must not cost every pod a day of alerts"""
+ monkeypatch.setattr(litellm, "model_cost", DEAD_MODEL_COST)
+ alerting = SlackAlerting(
+ alerting=["slack"], alert_types=[AlertType.model_deprecation_warnings]
+ )
+ router = _make_router([DEAD_ALIAS_DEPLOYMENT])
+ pod_lock_manager = MagicMock()
+ pod_lock_manager.acquire_lock = AsyncMock(side_effect=[False, True])
+ slept: list[float] = []
+
+ async def stop_after_second_pass(seconds):
+ slept.append(seconds)
+ if len(slept) == 2:
+ raise asyncio.CancelledError
+
+ with (
+ patch.object(alerting, "send_alert", new_callable=AsyncMock) as mock_send_alert,
+ patch(
+ "litellm.integrations.SlackAlerting.slack_alerting.asyncio.sleep",
+ side_effect=stop_after_second_pass,
+ ),
+ pytest.raises(asyncio.CancelledError),
+ ):
+ await alerting.run_scheduled_deprecation_check(
+ get_llm_router=lambda: router, pod_lock_manager=pod_lock_manager
+ )
+
+ assert slept == [DEPRECATION_IDLE_POLL_SECONDS] * 2
+ assert pod_lock_manager.acquire_lock.await_count == 2
+ mock_send_alert.assert_awaited_once()
+
+
+async def test_should_not_claim_the_lock_when_there_is_nothing_to_report(monkeypatch):
+ """An empty pass must not hold the daily lock, or a sunset added later waits out the whole window"""
+ monkeypatch.setattr(litellm, "model_cost", {})
+ alerting = SlackAlerting(
+ alerting=["slack"], alert_types=[AlertType.model_deprecation_warnings]
+ )
+ router = _make_router(
+ [
+ {
+ "model_name": "fresh",
+ "litellm_params": {"model": "openai/gpt-4o"},
+ "model_info": {"id": "x"},
+ }
+ ]
+ )
+ pod_lock_manager = MagicMock()
+ pod_lock_manager.acquire_lock = AsyncMock(return_value=True)
+
+ with patch.object(alerting, "send_alert", new_callable=AsyncMock) as mock_send_alert:
+ sent = await alerting.send_model_deprecation_alert(
+ llm_router=router, pod_lock_manager=pod_lock_manager
+ )
+
+ assert sent is False
+ pod_lock_manager.acquire_lock.assert_not_awaited()
+ mock_send_alert.assert_not_awaited()
+
+
+async def test_should_not_alert_or_claim_the_lock_within_a_day_of_a_sent_alert(monkeypatch):
+ """The shared sent stamp keeps sibling pods and restarts from re-alerting or re-asking redis for a day"""
+ monkeypatch.setattr(litellm, "model_cost", DEAD_MODEL_COST)
+ alerting = SlackAlerting(
+ alerting=["slack"], alert_types=[AlertType.model_deprecation_warnings]
+ )
+ await alerting.internal_usage_cache.async_set_cache(
+ key=SlackAlertingCacheKeys.deprecation_alert_sent_key.value,
+ value=1.0,
+ ttl=DEFAULT_DEPRECATION_CHECK_INTERVAL_SECONDS,
+ )
+ router = _make_router([DEAD_ALIAS_DEPLOYMENT])
+ pod_lock_manager = MagicMock()
+ pod_lock_manager.acquire_lock = AsyncMock(return_value=True)
+
+ 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
+ )
+
+ pod_lock_manager.acquire_lock.assert_not_awaited()
+ mock_send_alert.assert_not_awaited()