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(proxy): show the newest health check per model group on the model hub (#47552)
michelligabriele1c6d55c7e879
diff --git a/litellm/proxy/db/health_check_latest.py b/litellm/proxy/db/health_check_latest.pyindex 7672ed89e9a..024be7603d6 100644--- a/litellm/proxy/db/health_check_latest.py+++ b/litellm/proxy/db/health_check_latest.py@@ -10,8 +10,9 @@ worker on every call. ``SELECT DISTINCT ON`` keeps the transfer at one row perfrom __future__ import annotationsimport json-from collections.abc import Mapping, Sequence+from collections.abc import Iterable, Mapping, Sequencefrom datetime import datetime, timezone+from types import MappingProxyTypefrom typing import TYPE_CHECKING, Final, Protocolfrom pydantic import ConfigDict, JsonValue, TypeAdapter, field_validator@@ -113,3 +114,13 @@ async def fetch_latest_health_checks_for_models(except Exception as query_err: # noqa: BLE001 # a paged model list must not fail on its health decorationverbose_proxy_logger.error("Error getting latest health checks for models: %s", query_err)return ()+++def latest_by_model_name(rows: Iterable[LatestHealthCheckRow]) -> Mapping[str, LatestHealthCheckRow]:+ """The newest row per model name.++ The queries above return one row per (model_id, model_name), so a model group with several+ deployments comes back as several rows, plus one without a model_id if it was ever checked by+ name. They arrive in model_id order with NULL last, which says nothing about which check is newest.+ """+ return MappingProxyType({row.model_name: row for row in sorted(rows, key=lambda row: row.checked_at)})diff --git a/litellm/proxy/public_endpoints/public_endpoints.py b/litellm/proxy/public_endpoints/public_endpoints.pyindex 8903b22c120..6ced7827846 100644--- a/litellm/proxy/public_endpoints/public_endpoints.py+++ b/litellm/proxy/public_endpoints/public_endpoints.py@@ -22,6 +22,7 @@ from litellm.litellm_core_utils.get_model_cost_map import GetModelCostMapfrom litellm.proxy._types import (CommonProxyErrors,)+from litellm.proxy.db.health_check_latest import latest_by_model_namefrom litellm.proxy.utils import get_custom_urlfrom litellm.repositories.table_repositories import ClaudeCodePluginRepositoryfrom litellm.router_strategy.complexity_router.fuse_presets import FusePresetCatalog, get_fuse_presets@@ -295,13 +296,8 @@ async def public_model_hub():if prisma_client is not None:try:latest_checks: Final = await prisma_client.get_all_latest_health_checks()- for check in latest_checks:- key = check.model_id if check.model_id else check.model_name- if key:- health_check_dict = convert_health_check_to_dict(check)- health_checks_map[key] = health_check_dict- if check.model_name:- health_checks_map[check.model_name] = health_check_dict+ for model_name, check in latest_by_model_name(latest_checks).items():+ health_checks_map[model_name] = convert_health_check_to_dict(check)except Exception:passdiff --git a/litellm/proxy/public_endpoints/public_v1/model_hub.py b/litellm/proxy/public_endpoints/public_v1/model_hub.pyindex 2f5eeeb3d4b..cd634e490b6 100644--- a/litellm/proxy/public_endpoints/public_v1/model_hub.py+++ b/litellm/proxy/public_endpoints/public_v1/model_hub.py@@ -12,6 +12,7 @@ import litellmfrom litellm._logging import verbose_proxy_loggerfrom litellm.proxy._types import CommonProxyErrors, UserAPIKeyAuthfrom litellm.proxy.auth.user_api_key_auth import user_api_key_auth+from litellm.proxy.db.health_check_latest import latest_by_model_namefrom litellm.proxy.list_api.common import PROBLEM_TYPE_BASE, ManagementProblemfrom litellm.proxy.list_api.in_memory import Cells, InMemoryListExecutorfrom litellm.proxy.list_api.list_framework import (@@ -59,12 +60,12 @@ class PrismaHealthSnapshotLookup:checks: Final = await self.prisma_client.get_latest_health_checks_for_models(model_groups)return MappingProxyType({- check.model_name: HealthSnapshot(+ model_group: HealthSnapshot(status=check.status,response_time_ms=check.response_time_ms,checked_at=check.checked_at.isoformat() if check.checked_at else None,)- for check in checks+ for model_group, check in latest_by_model_name(checks).items()})diff --git a/tests/unit/proxy/db/test_health_check_latest.py b/tests/unit/proxy/db/test_health_check_latest.pyindex 29063d7b060..2f27be4fe61 100644--- a/tests/unit/proxy/db/test_health_check_latest.py+++ b/tests/unit/proxy/db/test_health_check_latest.py@@ -7,8 +7,10 @@ import pytestfrom litellm.proxy.db.health_check_latest import (LATEST_HEALTH_CHECKS_FOR_MODELS_SQL,LATEST_HEALTH_CHECKS_SQL,+ LatestHealthCheckRow,fetch_latest_health_checks,fetch_latest_health_checks_for_models,+ latest_by_model_name,query_latest_health_checks,)from tests.unit.proxy.db.fake_prisma_engine import engine_call@@ -129,3 +131,36 @@ async def test_the_latest_health_check_read_renders_a_postgres_select_span() -> None:assert await fetch_latest_health_checks(_prisma([])) == ()assert await postgres_span_names() == ("postgres.select LiteLLM_HealthCheckTable",)+++def _latest_row(**overrides) -> LatestHealthCheckRow:+ return LatestHealthCheckRow.model_validate(_raw_row(**overrides))++[email protected]("reverse", [False, True], ids=["sql-order", "reversed"])+def test_latest_by_model_name_keeps_each_groups_newest_row_whatever_its_model_id(reverse):+ """model_id ASC puts a name probe's NULL row, or a deleted deployment's larger id, after the fresh rows."""+ fresh = _latest_row(health_check_id="hc-a", model_id="deployment-a", checked_at="2026-10-16T11:10:00+00:00")+ deleted = _latest_row(+ health_check_id="hc-z", model_id="deployment-z", status="unhealthy", checked_at="2026-09-04T11:00:00+00:00"+ )+ name_probe = _latest_row(+ health_check_id="hc-null", model_id=None, status="unhealthy", checked_at="2026-09-04T11:20:04+00:00"+ )+ other_group = _latest_row(health_check_id="hc-c", model_name="claude", model_id="deployment-c")+ rows = (other_group, fresh, deleted, name_probe)++ latest = latest_by_model_name(rows[::-1] if reverse else rows)++ assert latest == {"gpt-4": fresh, "claude": other_group}+++def test_latest_by_model_name_lets_a_newer_name_probe_speak_for_the_group():+ per_deployment = _latest_row(+ health_check_id="hc-a", model_id="deployment-a", checked_at="2026-10-16T11:10:00+00:00"+ )+ name_probe = _latest_row(+ health_check_id="hc-null", model_id=None, status="unhealthy", checked_at="2026-10-16T12:00:00+00:00"+ )++ assert latest_by_model_name((per_deployment, name_probe))["gpt-4"] is name_probediff --git a/tests/unit/proxy/public_endpoints/public_v1/test_model_hub.py b/tests/unit/proxy/public_endpoints/public_v1/test_model_hub.pyindex 07886745222..43cdebd54b6 100644--- a/tests/unit/proxy/public_endpoints/public_v1/test_model_hub.py+++ b/tests/unit/proxy/public_endpoints/public_v1/test_model_hub.py@@ -61,13 +61,19 @@ def _groups(response) -> list[str]:return [row["model_group"] for row in response.json()["data"]]-def _health_check(model_name: str, status: str = "healthy"):+def _health_check(+ model_name: str,+ status: str = "healthy",+ *,+ model_id: str | None = None,+ checked_at: datetime = datetime(2026, 8, 1, 9, 30, tzinfo=timezone.utc),+):check = MagicMock()check.model_name = model_name- check.model_id = None+ check.model_id = model_idcheck.status = statuscheck.response_time_ms = 12.5- check.checked_at = datetime(2026, 8, 1, 9, 30, tzinfo=timezone.utc)+ check.checked_at = checked_atreturn check@@ -154,6 +160,21 @@ def test_the_latest_health_check_lands_on_its_row(monkeypatch):assert rows["model-000"]["health_status"] is None+def test_a_stale_row_sorting_after_the_fresh_one_does_not_speak_for_the_group(monkeypatch):+ """The read orders by model_id with NULL last; that order used to pick the group's health."""+ fresh = _health_check(+ "model-001", model_id="deployment-a", checked_at=datetime(2026, 10, 16, 11, 10, tzinfo=timezone.utc)+ )+ stale = _health_check("model-001", status="unhealthy", checked_at=datetime(2026, 9, 4, 11, 20, tzinfo=timezone.utc))+ prisma_client, _ = _recording_prisma([fresh, stale])+ _publish(monkeypatch, _named(3), prisma_client=prisma_client)++ rows = {row["model_group"]: row for row in _get().json()["data"]}++ assert rows["model-001"]["health_status"] == "healthy"+ assert rows["model-001"]["health_checked_at"] == "2026-10-16T11:10:00+00:00"++def test_a_health_read_that_returns_nothing_still_serves_the_page(monkeypatch):prisma_client, read = _recording_prisma()read.return_value = []diff --git a/tests/unit/proxy/public_endpoints/test_public_endpoints.py b/tests/unit/proxy/public_endpoints/test_public_endpoints.pyindex d5bacd9fd3c..8f27365fcc1 100644--- a/tests/unit/proxy/public_endpoints/test_public_endpoints.py+++ b/tests/unit/proxy/public_endpoints/test_public_endpoints.py@@ -15,6 +15,7 @@ from pydantic import TypeAdapterimport litellmfrom litellm.proxy.auth.user_api_key_auth import user_api_key_auth+from litellm.proxy.db.health_check_latest import LatestHealthCheckRowfrom litellm.proxy.public_endpoints import routerfrom litellm.router_strategy.complexity_router.fuse_presets import get_fuse_presetsfrom litellm.types.proxy.management_endpoints.model_management_endpoints import (@@ -852,6 +853,46 @@ def test_public_model_hub_mixed_health_statuses():app.dependency_overrides.clear()+def _stored_health_check(model_id: str | None, status: str, checked_at: datetime) -> LatestHealthCheckRow:+ return LatestHealthCheckRow(+ health_check_id=f"hc-{model_id}",+ model_name="gpt-4",+ model_id=model_id,+ status=status,+ checked_at=checked_at,+ created_at=checked_at,+ updated_at=checked_at,+ )+++def test_public_model_hub_reports_the_newest_check_of_a_group_not_the_last_row_read():+ """Rows come back in model_id order with NULL last, so a stale name-probe row used to overwrite the fresh one."""+ app = FastAPI()+ app.include_router(router)+ app.dependency_overrides[user_api_key_auth] = lambda: MagicMock()+ client = TestClient(app)+ fresh = _stored_health_check("deployment-a", "healthy", datetime(2026, 10, 16, 11, 10, tzinfo=timezone.utc))+ stale = _stored_health_check(None, "unhealthy", datetime(2026, 9, 4, 11, 20, tzinfo=timezone.utc))+ mock_prisma = MagicMock()+ mock_prisma.get_all_latest_health_checks = AsyncMock(return_value=(fresh, stale))++ with (+ patch("litellm.public_model_groups", ["gpt-4"]),+ patch("litellm.proxy.proxy_server.get_model_group_info") as mock_get_info,+ patch("litellm.proxy.proxy_server.llm_router", MagicMock()),+ patch("litellm.proxy.proxy_server.prisma_client", mock_prisma),+ ):+ mock_get_info.return_value = [+ ModelGroupInfoProxy(model_group="gpt-4", providers=["openai"], is_public_model_group=True)+ ]+ response = client.get("/public/model_hub", headers={"Authorization": "Bearer test-key"})++ assert response.status_code == 200+ assert response.json()[0]["health_status"] == "healthy"+ assert response.json()[0]["health_checked_at"] == "2026-10-16T11:10:00+00:00"+ app.dependency_overrides.clear()++# ---------------------------------------------------------------------------# /public/agent_hub# ---------------------------------------------------------------------------