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]

feat(proxy): add maximum_health_check_retention_period to bound the health-check table (#37681)

devin-ai-integration[bot]22e8b45c689b
diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.py
index 05fc6e07176..8856e68698a 100644
--- a/litellm/proxy/_types.py
+++ b/litellm/proxy/_types.py
@@ -2551,6 +2551,14 @@ class ConfigGeneralSettings(LiteLLMPydanticObjectBase):
None,
description="Maximum retention period for auto-router benchmark session rollup rows (e.g., '365d'). Rows whose last turn is older than this are deleted by the spend log cleanup job, on that job's schedule. Unset means rollup rows are never deleted.",
)
+ maximum_health_check_retention_period: str | None = Field(
+ None,
+ description=(
+ "Maximum retention period for health-check rows (e.g., '30d'). Rows whose checked_at is older than this "
+ "are deleted by the spend log cleanup job, on that job's schedule. Unset means rows are never deleted. "
+ "Set this well above health_check_interval because /health and the UI read the latest row per model."
+ ),
+ )
use_spend_logs_partitioning: bool | None = Field(
None,
description="If True and LiteLLM_SpendLogs has been converted to a range-partitioned table (db_scripts/partition_spend_logs.sql), retention cleanup drops expired partitions instead of deleting rows, and pre-creates upcoming partitions. Default is False.",
diff --git a/litellm/proxy/db/db_transaction_queue/spend_log_cleanup.py b/litellm/proxy/db/db_transaction_queue/spend_log_cleanup.py
index d19023862cb..e97e9f6e683 100644
--- a/litellm/proxy/db/db_transaction_queue/spend_log_cleanup.py
+++ b/litellm/proxy/db/db_transaction_queue/spend_log_cleanup.py
@@ -222,6 +222,21 @@ class SpendLogCleanup:
remaining_ms: Final = int((deadline - time.monotonic()) * 1000)
return max(1, min(int(self.batch_timeout_seconds * 1000), remaining_ms))
+ @staticmethod
+ def _group_deadline(overall_deadline: float, groups_remaining: int) -> float:
+ """
+ Give each pending cleanup group an equal share of the time left.
+
+ A single group keeps the whole run budget, while a persistent backlog
+ on an earlier group cannot starve a later group.
+ """
+ if groups_remaining == 1:
+ return overall_deadline
+ current_time: Final = time.monotonic()
+ if current_time >= overall_deadline:
+ return overall_deadline
+ return current_time + (overall_deadline - current_time) / groups_remaining
+
def _remaining_timeout_ms(self, deadline: float) -> RemainingTimeoutMs:
"""
The per-statement bound for work this job delegates, as a callable.
@@ -477,6 +492,18 @@ class SpendLogCleanup:
deadline=deadline,
)
+ async def _delete_old_health_check_rows(
+ self, prisma_client: PrismaClient, cutoff_date: datetime, deadline: float
+ ) -> TableCleanupResult:
+ return await self._delete_old_rows_batched(
+ prisma_client,
+ cutoff_date,
+ table_name="LiteLLM_HealthCheckTable",
+ key_columns=("health_check_id",),
+ time_column="checked_at",
+ deadline=deadline,
+ )
+
async def _clean_spend_log_tables(
self, prisma_client: PrismaClient, deadline: float
) -> tuple[TableCleanupResult, ...]:
@@ -526,6 +553,19 @@ class SpendLogCleanup:
verbose_proxy_logger.info("Deleted %s expired auto-router session rollup rows", sessions_result.rows_deleted)
return (sessions_result,)
+ async def _clean_health_checks(
+ self, prisma_client: PrismaClient, retention_seconds: int, deadline: float
+ ) -> tuple[TableCleanupResult, ...]:
+ health_check_cutoff: Final = datetime.now(timezone.utc) - timedelta(seconds=float(retention_seconds))
+ health_checks_result: Final = await self._delete_old_health_check_rows(
+ prisma_client, health_check_cutoff, deadline
+ )
+ verbose_proxy_logger.info(
+ "Deleted %s expired health-check rows",
+ health_checks_result.rows_deleted,
+ )
+ return (health_checks_result,)
+
@staticmethod
def _run_outcome(results: tuple[TableCleanupResult, ...]) -> RunOutcome:
"""
@@ -558,7 +598,12 @@ class SpendLogCleanup:
autorouter_retention_seconds: Final = self._retention_seconds_for(
"maximum_autorouter_session_retention_period"
)
- if not delete_spend_logs and autorouter_retention_seconds is None:
+ health_check_retention_seconds: Final = self._retention_seconds_for("maximum_health_check_retention_period")
+ if (
+ not delete_spend_logs
+ and autorouter_retention_seconds is None
+ and health_check_retention_seconds is None
+ ):
SpendLogCleanupMetrics.record_run("skipped_disabled")
return
@@ -585,19 +630,45 @@ class SpendLogCleanup:
return
deadline: Final = time.monotonic() + self.run_budget_seconds
+ configured_group_count: Final = (
+ int(delete_spend_logs and self.retention_seconds is not None)
+ + int(autorouter_retention_seconds is not None)
+ + int(health_check_retention_seconds is not None)
+ )
spend_log_results: Final = (
- await self._clean_spend_log_tables(prisma_client, deadline)
+ await self._clean_spend_log_tables(
+ prisma_client,
+ self._group_deadline(deadline, configured_group_count),
+ )
if delete_spend_logs and self.retention_seconds is not None
else ()
)
+ remaining_groups_after_spend_logs: Final = int(autorouter_retention_seconds is not None) + int(
+ health_check_retention_seconds is not None
+ )
session_results: Final = (
- await self._clean_session_rollup(prisma_client, autorouter_retention_seconds, deadline)
+ await self._clean_session_rollup(
+ prisma_client,
+ autorouter_retention_seconds,
+ self._group_deadline(deadline, remaining_groups_after_spend_logs),
+ )
if autorouter_retention_seconds is not None
else ()
)
+ health_check_results: Final = (
+ await self._clean_health_checks(
+ prisma_client,
+ health_check_retention_seconds,
+ deadline,
+ )
+ if health_check_retention_seconds is not None
+ else ()
+ )
- SpendLogCleanupMetrics.record_run(self._run_outcome(spend_log_results + session_results))
+ SpendLogCleanupMetrics.record_run(
+ self._run_outcome(spend_log_results + session_results + health_check_results)
+ )
except Exception as e:
# .exception() captures the traceback; str(e) alone on a Prisma/DB
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index b94a663fc15..711775ee0cf 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -6315,7 +6315,8 @@ class ProxyConfig:
# Schedule new job if retention period is set (not None)
retention_period: Final = general_settings.get("maximum_spend_logs_retention_period")
autorouter_retention: Final = general_settings.get("maximum_autorouter_session_retention_period")
- if retention_period is not None or autorouter_retention is not None:
+ health_check_retention: Final = general_settings.get("maximum_health_check_retention_period")
+ if retention_period is not None or autorouter_retention is not None or health_check_retention is not None:
from litellm.proxy.db.db_transaction_queue.spend_log_cleanup import (
SpendLogCleanup,
)
@@ -6470,6 +6471,13 @@ class ProxyConfig:
if old_session_value != new_session_value:
await self._reschedule_spend_log_cleanup_job()
+ if "maximum_health_check_retention_period" in _general_settings:
+ old_health_check_value: Final = general_settings.get("maximum_health_check_retention_period")
+ new_health_check_value: Final = _general_settings["maximum_health_check_retention_period"]
+ general_settings["maximum_health_check_retention_period"] = new_health_check_value
+ if old_health_check_value != new_health_check_value:
+ await self._reschedule_spend_log_cleanup_job()
+
## SPEND LOG CLEANUP BOUNDS ##
# The dashboard writes these straight to the DB, so without copying them
# here the running cleanup job never sees them. A key the DB no longer
@@ -9085,6 +9093,7 @@ class ProxyStartupEvent:
if (
general_settings.get("maximum_spend_logs_retention_period") is not None
or general_settings.get("maximum_autorouter_session_retention_period") is not None
+ or general_settings.get("maximum_health_check_retention_period") is not None
):
spend_log_cleanup: Final = SpendLogCleanup()
cleanup_cron: Final = general_settings.get("maximum_spend_logs_cleanup_cron")
@@ -15820,6 +15829,7 @@ _GENERAL_SETTINGS_CONFIG_LIST_FIELD_TYPES: Final[Mapping[str, str]] = MappingPro
"store_model_in_db": "Boolean",
"store_prompts_in_spend_logs": "Boolean",
"maximum_spend_logs_retention_period": "String",
+ "maximum_health_check_retention_period": "String",
"maximum_spend_logs_cleanup_batch_size": "Integer",
"maximum_spend_logs_cleanup_max_batches": "Integer",
"maximum_spend_logs_cleanup_run_budget": "String",
diff --git a/tests/test_litellm/proxy/proxy_server/test_proxy_config.py b/tests/test_litellm/proxy/proxy_server/test_proxy_config.py
index 58465772b3b..d8047cca728 100644
--- a/tests/test_litellm/proxy/proxy_server/test_proxy_config.py
+++ b/tests/test_litellm/proxy/proxy_server/test_proxy_config.py
@@ -2617,6 +2617,33 @@ async def test_ProxyConfig__reschedule_spend_log_cleanup_job_invalid_cron(monkey
assert fake_scheduler.add_job.call_count == 0
+async def test_ProxyConfig__reschedule_spend_log_cleanup_job_health_check_retention(monkeypatch):
+ fake_scheduler = MagicMock()
+ monkeypatch.setattr("litellm.proxy.proxy_server.scheduler", fake_scheduler)
+ monkeypatch.setattr(
+ "litellm.proxy.proxy_server.general_settings",
+ {"maximum_health_check_retention_period": "30d"},
+ )
+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", None)
+ pc = ProxyConfig()
+ await pc._reschedule_spend_log_cleanup_job()
+ assert fake_scheduler.add_job.call_count == 1
+ assert fake_scheduler.add_job.call_args.kwargs["id"] == "spend_log_cleanup_job"
+
+
+async def test_ProxyConfig__update_general_settings_updates_health_check_retention(monkeypatch):
+ settings = {}
+ monkeypatch.setattr("litellm.proxy.proxy_server.general_settings", settings)
+ pc = ProxyConfig()
+ reschedule = AsyncMock()
+ monkeypatch.setattr(pc, "_reschedule_spend_log_cleanup_job", reschedule)
+ await pc._update_general_settings({"maximum_health_check_retention_period": "30d"})
+ assert settings["maximum_health_check_retention_period"] == "30d"
+ reschedule.assert_awaited_once()
+
+
# ---------------------------------------------------------------------------
# ProxyConfig._update_general_settings
# ---------------------------------------------------------------------------
diff --git a/tests/test_litellm/proxy/test_spend_log_cleanup.py b/tests/test_litellm/proxy/test_spend_log_cleanup.py
index 87fbdd4c933..ce0b6b755cc 100644
--- a/tests/test_litellm/proxy/test_spend_log_cleanup.py
+++ b/tests/test_litellm/proxy/test_spend_log_cleanup.py
@@ -793,6 +793,7 @@ async def test_spend_logs_retention_alone_does_not_touch_the_session_rollup():
tables = [call[0][0] for call in client.db.execute_raw.call_args_list]
assert any('"LiteLLM_SpendLogs"' in sql for sql in tables)
assert not any('"LiteLLM_AutoRouterSession"' in sql for sql in tables)
+ assert not any('"LiteLLM_HealthCheckTable"' in sql for sql in tables)
@pytest.mark.asyncio
@@ -807,25 +808,47 @@ async def test_session_retention_alone_cleans_only_the_session_rollup():
@pytest.mark.asyncio
-async def test_each_retention_key_cuts_off_at_its_own_horizon():
- from datetime import datetime, timezone
+async def test_health_check_retention_alone_cleans_only_the_health_check_table():
+ client = _mock_prisma_for_retention([0])
+ cleaner = SpendLogCleanup(general_settings={"maximum_health_check_retention_period": "30d"})
+ cleaner.pod_lock_manager = None
+ await cleaner.cleanup_old_spend_logs(client)
+ tables = [call[0][0] for call in client.db.execute_raw.call_args_list]
+ assert len(tables) == 1
+ assert '"LiteLLM_HealthCheckTable"' in tables[0]
+ assert '"health_check_id"' in tables[0]
+ assert '"checked_at"' in tables[0]
+ cutoff_date = client.db.execute_raw.call_args[0][1]
+ expected_cutoff = datetime.now(timezone.utc) - timedelta(days=30)
+ assert abs((cutoff_date - expected_cutoff).total_seconds()) < 1
- client = _mock_prisma_for_retention([0, 0, 0])
+
+async def test_each_retention_key_cuts_off_at_its_own_horizon():
+ client = _mock_prisma_for_retention([0, 0, 0, 0])
cleaner = SpendLogCleanup(
general_settings={
"maximum_spend_logs_retention_period": "7d",
"maximum_autorouter_session_retention_period": "365d",
+ "maximum_health_check_retention_period": "30d",
}
)
cleaner.pod_lock_manager = None
await cleaner.cleanup_old_spend_logs(client)
cutoffs = {
- ("LiteLLM_AutoRouterSession" if '"LiteLLM_AutoRouterSession"' in call[0][0] else "logs"): call[0][1]
+ (
+ "LiteLLM_AutoRouterSession"
+ if '"LiteLLM_AutoRouterSession"' in call[0][0]
+ else "LiteLLM_HealthCheckTable"
+ if '"LiteLLM_HealthCheckTable"' in call[0][0]
+ else "logs"
+ ): call[0][1]
for call in client.db.execute_raw.call_args_list
}
now = datetime.now(timezone.utc)
assert (now - cutoffs["logs"]).days == 7
assert (now - cutoffs["LiteLLM_AutoRouterSession"]).days == 365
+ assert (now - cutoffs["LiteLLM_HealthCheckTable"]).days == 30
@pytest.mark.asyncio
@@ -910,6 +933,32 @@ async def test_run_budget_is_shared_across_tables_not_granted_per_table():
assert "LiteLLM_SpendLogs" in tables_touched
+async def test_cleanup_groups_share_budget_so_health_checks_still_get_a_delete():
+ mock_prisma_client = MagicMock()
+ _wire_tx(mock_prisma_client.db)
+ mock_db = MagicMock()
+ _wire_tx(mock_db)
+ mock_db.execute_raw = AsyncMock(return_value=1000)
+ mock_prisma_client.db = mock_db
+
+ cleaner = SpendLogCleanup(
+ general_settings={
+ "maximum_spend_logs_retention_period": "7d",
+ "maximum_health_check_retention_period": "30d",
+ "maximum_spend_logs_cleanup_max_batches": 50,
+ "maximum_spend_logs_cleanup_run_budget": "1s",
+ }
+ )
+ cleaner.pod_lock_manager = None
+
+ await cleaner.cleanup_old_spend_logs(mock_prisma_client)
+
+ tables_touched = {call[0][0].split('"')[1] for call in mock_db.execute_raw.call_args_list}
+ assert "LiteLLM_SpendLogs" in tables_touched
+ assert "LiteLLM_HealthCheckTable" in tables_touched
+
+
@pytest.mark.asyncio
async def test_each_batch_carries_a_statement_and_lock_timeout():
"""
diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.ts
index 847fe65a5cc..23b34ba2726 100644
--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts
+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts
@@ -24135,6 +24135,11 @@ export interface components {
* @description Maximum retention period for auto-router benchmark session rollup rows (e.g., '365d'). Rows whose last turn is older than this are deleted by the spend log cleanup job, on that job's schedule. Unset means rollup rows are never deleted.
*/
maximum_autorouter_session_retention_period?: string | null;
+ /**
+ * Maximum Health Check Retention Period
+ * @description Maximum retention period for health-check rows (e.g., '30d'). Rows whose checked_at is older than this are deleted by the spend log cleanup job, on that job's schedule. Unset means rows are never deleted. Set this well above health_check_interval because /health and the UI read the latest row per model.
+ */
+ maximum_health_check_retention_period?: string | null;
/**
* Maximum Spend Logs Cleanup Batch Size
* @description Rows deleted per DELETE statement by the spend log cleanup job. Defaults to 1000.