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(proxy): retry model cost map fetch with Retry-After-aware backoff and keep current map on reload failure (#35739)

ryan-crabbe-berriabe3289398bb
diff --git a/litellm/litellm_core_utils/get_model_cost_map.py b/litellm/litellm_core_utils/get_model_cost_map.py
index e87e3d8aca2..5d36e391fbc 100644
--- a/litellm/litellm_core_utils/get_model_cost_map.py
+++ b/litellm/litellm_core_utils/get_model_cost_map.py
@@ -8,9 +8,14 @@ export LITELLM_LOCAL_MODEL_COST_MAP=True
```
"""
+import asyncio
import json
import os
+import random
+from collections.abc import Awaitable, Callable
+from dataclasses import dataclass
from importlib.resources import files
+from typing import Protocol
import httpx
@@ -161,6 +166,158 @@ class GetModelCostMap:
return response.json()
+RETRYABLE_FETCH_STATUS_CODES = frozenset({429, 500, 502, 503, 504})
+MODEL_COST_MAP_FETCH_MAX_ATTEMPTS = 3
+MODEL_COST_MAP_FETCH_MAX_WAIT_SECONDS = 30.0
+
+
+@dataclass(frozen=True, slots=True)
+class ModelCostMapReloaded:
+ model_cost_map: dict # mutable-ok: adopted as litellm.model_cost, whose consumer contract is a plain mutable dict
+
+
+@dataclass(frozen=True, slots=True)
+class ModelCostMapReloadUnavailable:
+ reason: str
+
+
+ModelCostMapReloadResult = ModelCostMapReloaded | ModelCostMapReloadUnavailable
+
+
+@dataclass(frozen=True, slots=True)
+class _FetchAttemptRetryable:
+ reason: str
+ retry_after_seconds: float | None
+
+
+def _parse_retry_after_seconds(response: httpx.Response) -> float | None:
+ header = response.headers.get("Retry-After")
+ if header is None:
+ return None
+ try:
+ seconds = float(header)
+ except ValueError:
+ return None
+ return seconds if seconds >= 0 else None
+
+
+def _retry_wait_seconds(outcome: _FetchAttemptRetryable, attempt: int, rng: random.Random) -> float:
+ if outcome.retry_after_seconds is not None:
+ return min(outcome.retry_after_seconds, MODEL_COST_MAP_FETCH_MAX_WAIT_SECONDS)
+ return min(float(2**attempt) + rng.uniform(0.0, 1.0), MODEL_COST_MAP_FETCH_MAX_WAIT_SECONDS)
+
+
+class _AsyncGetClient(Protocol):
+ def get(self, url: str, *, timeout: float | None = None) -> Awaitable[httpx.Response]: ...
+
+
+def _default_reload_client() -> _AsyncGetClient:
+ from litellm.llms.custom_httpx.http_handler import get_async_httpx_client
+ from litellm.types.llms.custom_http import httpxSpecialProvider
+
+ return get_async_httpx_client(llm_provider=httpxSpecialProvider.ModelCostMap)
+
+
+async def _attempt_fetch(
+ client: _AsyncGetClient, url: str, timeout: int
+) -> ModelCostMapReloaded | ModelCostMapReloadUnavailable | _FetchAttemptRetryable:
+ try:
+ response = await client.get(url, timeout=timeout)
+ except httpx.HTTPError as e:
+ return _FetchAttemptRetryable(reason=f"{type(e).__name__} fetching {url}: {e}", retry_after_seconds=None)
+ if response.status_code in RETRYABLE_FETCH_STATUS_CODES:
+ return _FetchAttemptRetryable(
+ reason=f"HTTP {response.status_code} from {url}",
+ retry_after_seconds=_parse_retry_after_seconds(response),
+ )
+ if response.is_error:
+ return ModelCostMapReloadUnavailable(reason=f"HTTP {response.status_code} from {url}")
+ try:
+ parsed = response.json()
+ except ValueError as e:
+ return ModelCostMapReloadUnavailable(reason=f"invalid JSON from {url}: {e}")
+ if not isinstance(parsed, dict):
+ return ModelCostMapReloadUnavailable(reason=f"expected a JSON object from {url}, got {type(parsed).__name__}")
+ return ModelCostMapReloaded(model_cost_map=parsed)
+
+
+async def _fetch_remote_model_cost_map_with_retry(
+ url: str,
+ timeout: int,
+ max_attempts: int,
+ sleep: Callable[[float], Awaitable[None]],
+ rng: random.Random,
+ client: _AsyncGetClient,
+) -> ModelCostMapReloadResult:
+ for attempt in range(1, max_attempts + 1):
+ outcome = await _attempt_fetch(client=client, url=url, timeout=timeout)
+ if not isinstance(outcome, _FetchAttemptRetryable):
+ return outcome
+ if attempt == max_attempts:
+ return ModelCostMapReloadUnavailable(reason=f"{outcome.reason} (after {max_attempts} attempts)")
+ wait_seconds = _retry_wait_seconds(outcome=outcome, attempt=attempt, rng=rng)
+ verbose_logger.warning(
+ "LiteLLM: model cost map fetch attempt %d/%d failed (%s); retrying in %.1fs",
+ attempt,
+ max_attempts,
+ outcome.reason,
+ wait_seconds,
+ )
+ await sleep(wait_seconds)
+ return ModelCostMapReloadUnavailable(reason="model cost map fetch failed")
+
+
+async def refetch_model_cost_map(
+ url: str,
+ timeout: int = 5,
+ max_attempts: int = MODEL_COST_MAP_FETCH_MAX_ATTEMPTS,
+ sleep: Callable[[float], Awaitable[None]] = asyncio.sleep,
+ rng: random.Random | None = None,
+ client: "_AsyncGetClient | None" = None,
+) -> ModelCostMapReloadResult:
+ """
+ Re-fetch the model cost map for a runtime reload, retrying transient HTTP
+ errors (429/5xx/transport) with Retry-After-aware backoff.
+
+ Unlike ``get_model_cost_map`` this never falls back to the packaged backup:
+ on failure it returns ``ModelCostMapReloadUnavailable`` so callers keep the
+ map they already have.
+ """
+ if os.getenv("LITELLM_LOCAL_MODEL_COST_MAP", "").lower() == "true":
+ _cost_map_source_info.source = "local"
+ _cost_map_source_info.url = None
+ _cost_map_source_info.is_env_forced = True
+ _cost_map_source_info.fallback_reason = None
+ return ModelCostMapReloaded(
+ model_cost_map=_finalize_model_cost_map(GetModelCostMap.load_local_model_cost_map())
+ )
+
+ result = await _fetch_remote_model_cost_map_with_retry(
+ url=url,
+ timeout=timeout,
+ max_attempts=max_attempts,
+ sleep=sleep,
+ rng=rng if rng is not None else random.Random(),
+ client=client if client is not None else _default_reload_client(),
+ )
+ if isinstance(result, ModelCostMapReloadUnavailable):
+ verbose_logger.warning(
+ "LiteLLM: model cost map reload failed: %s. Keeping the currently loaded map.",
+ result.reason,
+ )
+ return result
+ if not GetModelCostMap.validate_model_cost_map(
+ fetched_map=result.model_cost_map,
+ backup_model_count=GetModelCostMap._get_backup_model_count(),
+ ):
+ return ModelCostMapReloadUnavailable(reason=f"model cost map from {url} failed integrity validation")
+ _cost_map_source_info.source = "remote"
+ _cost_map_source_info.url = url
+ _cost_map_source_info.is_env_forced = False
+ _cost_map_source_info.fallback_reason = None
+ return ModelCostMapReloaded(model_cost_map=_finalize_model_cost_map(result.model_cost_map))
+
+
class ModelCostMapSourceInfo:
"""Tracks the source of the currently loaded model cost map."""
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index 16a63540d4d..e8299be8f07 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -6538,11 +6538,18 @@ class ProxyConfig:
if should_reload:
# Perform the reload
from litellm.litellm_core_utils.get_model_cost_map import (
- get_model_cost_map,
+ ModelCostMapReloadUnavailable,
+ refetch_model_cost_map,
)
model_cost_map_url = litellm.model_cost_map_url
- new_model_cost_map = get_model_cost_map(url=model_cost_map_url)
+ reload_result = await refetch_model_cost_map(url=model_cost_map_url)
+ if isinstance(reload_result, ModelCostMapReloadUnavailable):
+ verbose_proxy_logger.warning(
+ f"Model cost map reload failed ({reload_result.reason}); keeping current pricing data, will retry on the next config poll"
+ )
+ return
+ new_model_cost_map = reload_result.model_cost_map
litellm.model_cost = new_model_cost_map
# Invalidate case-insensitive lookup map since model_cost was replaced
_invalidate_model_cost_lowercase_map()
@@ -15836,10 +15843,19 @@ async def reload_model_cost_map(
raise HTTPException(status_code=500, detail="Database connection not available")
# Immediately reload the model cost map in the current pod
- from litellm.litellm_core_utils.get_model_cost_map import get_model_cost_map
+ from litellm.litellm_core_utils.get_model_cost_map import (
+ ModelCostMapReloadUnavailable,
+ refetch_model_cost_map,
+ )
model_cost_map_url = litellm.model_cost_map_url
- new_model_cost_map = get_model_cost_map(url=model_cost_map_url)
+ reload_result = await refetch_model_cost_map(url=model_cost_map_url)
+ if isinstance(reload_result, ModelCostMapReloadUnavailable):
+ raise HTTPException(
+ status_code=502,
+ detail=f"Failed to reload model cost map: {reload_result.reason}. Current pricing data was kept.",
+ )
+ new_model_cost_map = reload_result.model_cost_map
litellm.model_cost = new_model_cost_map
# Invalidate case-insensitive lookup map since model_cost was replaced
_invalidate_model_cost_lowercase_map()
@@ -15881,6 +15897,8 @@ async def reload_model_cost_map(
"models_count": models_count,
"timestamp": current_time.isoformat(),
}
+ except HTTPException:
+ raise
except Exception as e:
verbose_proxy_logger.exception("Failed to reload model cost map: %s", e)
raise HTTPException(status_code=500, detail=f"Failed to reload model cost map: {e}")
diff --git a/litellm/types/llms/custom_http.py b/litellm/types/llms/custom_http.py
index d7dfc0e486b..548dde4c04d 100644
--- a/litellm/types/llms/custom_http.py
+++ b/litellm/types/llms/custom_http.py
@@ -30,6 +30,7 @@ class httpxSpecialProvider(str, Enum):
PromptManagement = "prompt_management"
UI = "ui"
Sandbox = "sandbox"
+ ModelCostMap = "model_cost_map"
VerifyTypes = Union[str, bool, ssl.SSLContext]
diff --git a/tests/test_litellm/litellm_core_utils/test_get_model_cost_map.py b/tests/test_litellm/litellm_core_utils/test_get_model_cost_map.py
index f21c667276e..463bdc6161f 100644
--- a/tests/test_litellm/litellm_core_utils/test_get_model_cost_map.py
+++ b/tests/test_litellm/litellm_core_utils/test_get_model_cost_map.py
@@ -248,3 +248,186 @@ def test_azure_ai_claude_1m_context_entries(cost_map: dict):
"azure_ai/claude-haiku-4-5",
]:
assert cost_map[model]["max_input_tokens"] == 200000, model
+
+
+# ---------------------------------------------------------------------------
+# refetch_model_cost_map: retry/backoff behavior for runtime reloads
+# ---------------------------------------------------------------------------
+
+import functools
+import random
+
+import httpx
+
+from litellm.litellm_core_utils.get_model_cost_map import (
+ ModelCostMapReloaded,
+ ModelCostMapReloadUnavailable,
+ refetch_model_cost_map,
+)
+
+_URL = "https://example.invalid/model_prices.json"
+
+
[email protected]_cache(maxsize=1)
+def _real_map_bytes() -> bytes:
+ return json.dumps(_load_root_cost_map()).encode()
+
+
+class _SleepRecorder:
+ """Injected in place of asyncio.sleep so tests assert waits without real delay."""
+
+ def __init__(self):
+ self.waits = []
+
+ async def __call__(self, seconds: float) -> None:
+ self.waits.append(seconds)
+
+
[email protected](autouse=True)
+def _unset_local_cost_map_env(monkeypatch):
+ """CI exports LITELLM_LOCAL_MODEL_COST_MAP=True; clear it so fetch behavior is deterministic."""
+ monkeypatch.delenv("LITELLM_LOCAL_MODEL_COST_MAP", raising=False)
+
+
+def _mock_client(outcomes):
+ """httpx client over a MockTransport serving one outcome per request; an exception instance is raised."""
+ calls = {"count": 0}
+
+ def handler(request):
+ idx = min(calls["count"], len(outcomes) - 1)
+ calls["count"] += 1
+ outcome = outcomes[idx]
+ if isinstance(outcome, Exception):
+ raise outcome
+ return outcome
+
+ return httpx.AsyncClient(transport=httpx.MockTransport(handler)), calls
+
+
+async def test_refetch_retries_429_honoring_retry_after():
+ """Two 429s with Retry-After then success: waits follow the header, not backoff."""
+ client, calls = _mock_client(
+ [
+ httpx.Response(429, headers={"Retry-After": "7"}),
+ httpx.Response(429, headers={"Retry-After": "7"}),
+ httpx.Response(200, content=_real_map_bytes()),
+ ]
+ )
+ sleeper = _SleepRecorder()
+ result = await refetch_model_cost_map(
+ url=_URL, sleep=sleeper, rng=random.Random(0), client=client
+ )
+ assert isinstance(result, ModelCostMapReloaded)
+ assert len(result.model_cost_map) > 100
+ assert calls["count"] == 3
+ assert sleeper.waits == [7.0, 7.0]
+
+
+async def test_refetch_gives_up_after_max_attempts_with_exponential_backoff():
+ """All 429 without Retry-After: exponential backoff waits, then a failure value."""
+ client, calls = _mock_client([httpx.Response(429)])
+ sleeper = _SleepRecorder()
+ result = await refetch_model_cost_map(
+ url=_URL, sleep=sleeper, rng=random.Random(0), client=client
+ )
+ assert isinstance(result, ModelCostMapReloadUnavailable)
+ assert "429" in result.reason
+ assert "after 3 attempts" in result.reason
+ assert calls["count"] == 3
+ assert len(sleeper.waits) == 2
+ assert 2.0 <= sleeper.waits[0] < 3.0
+ assert 4.0 <= sleeper.waits[1] < 5.0
+
+
+async def test_refetch_caps_retry_after_wait():
+ """A hostile/huge Retry-After is capped so reloads never sleep unbounded."""
+ client, _calls = _mock_client(
+ [
+ httpx.Response(429, headers={"Retry-After": "9999"}),
+ httpx.Response(200, content=_real_map_bytes()),
+ ]
+ )
+ sleeper = _SleepRecorder()
+ result = await refetch_model_cost_map(
+ url=_URL, sleep=sleeper, rng=random.Random(0), client=client
+ )
+ assert isinstance(result, ModelCostMapReloaded)
+ assert sleeper.waits == [30.0]
+
+
+async def test_refetch_retries_transport_errors():
+ """Connection failures are transient: retried like 5xx, succeeding when the network heals."""
+ client, calls = _mock_client(
+ [
+ httpx.ConnectError("connection refused"),
+ httpx.Response(200, content=_real_map_bytes()),
+ ]
+ )
+ sleeper = _SleepRecorder()
+ result = await refetch_model_cost_map(
+ url=_URL, sleep=sleeper, rng=random.Random(0), client=client
+ )
+ assert isinstance(result, ModelCostMapReloaded)
+ assert calls["count"] == 2
+ assert len(sleeper.waits) == 1
+
+
+async def test_refetch_non_retryable_status_fails_immediately():
+ """A 404 is permanent: one attempt, no sleeps, failure value."""
+ client, calls = _mock_client([httpx.Response(404)])
+ sleeper = _SleepRecorder()
+ result = await refetch_model_cost_map(
+ url=_URL, sleep=sleeper, rng=random.Random(0), client=client
+ )
+ assert isinstance(result, ModelCostMapReloadUnavailable)
+ assert "404" in result.reason
+ assert calls["count"] == 1
+ assert sleeper.waits == []
+
+
+async def test_refetch_invalid_json_fails_immediately():
+ client, calls = _mock_client([httpx.Response(200, content=b"not json")])
+ sleeper = _SleepRecorder()
+ result = await refetch_model_cost_map(
+ url=_URL, sleep=sleeper, rng=random.Random(0), client=client
+ )
+ assert isinstance(result, ModelCostMapReloadUnavailable)
+ assert "invalid JSON" in result.reason
+ assert calls["count"] == 1
+ assert sleeper.waits == []
+
+
+async def test_refetch_shrunk_map_fails_integrity_not_swapped_in():
+ """A drastically shrunk upstream file is rejected instead of being adopted."""
+ tiny = json.dumps(_make_models(60)).encode()
+ client, _calls = _mock_client([httpx.Response(200, content=tiny)])
+ result = await refetch_model_cost_map(
+ url=_URL, sleep=_SleepRecorder(), rng=random.Random(0), client=client
+ )
+ assert isinstance(result, ModelCostMapReloadUnavailable)
+ assert "integrity validation" in result.reason
+
+
+async def test_refetch_respects_local_env_override(monkeypatch):
+ """LITELLM_LOCAL_MODEL_COST_MAP=True short-circuits to the bundled backup, zero HTTP."""
+ monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True")
+
+ def _fail(request):
+ raise AssertionError("no HTTP request should be made when local map is forced")
+
+ result = await refetch_model_cost_map(
+ url=_URL,
+ sleep=_SleepRecorder(),
+ rng=random.Random(0),
+ client=httpx.AsyncClient(transport=httpx.MockTransport(_fail)),
+ )
+ assert isinstance(result, ModelCostMapReloaded)
+ assert len(result.model_cost_map) > 100
diff --git a/tests/test_litellm/proxy/common_utils/test_config_sync_pubsub.py b/tests/test_litellm/proxy/common_utils/test_config_sync_pubsub.py
index 6872407808c..e357f25123b 100644
--- a/tests/test_litellm/proxy/common_utils/test_config_sync_pubsub.py
+++ b/tests/test_litellm/proxy/common_utils/test_config_sync_pubsub.py
@@ -776,8 +776,14 @@ async def test_model_cost_map_reload_does_not_publish_config_change() -> None:
original_model_cost = litellm.model_cost.copy()
_set_redis_usage_cache(_FakeRedisCache(client))
try:
- with patch("litellm.litellm_core_utils.get_model_cost_map.get_model_cost_map") as mock_get_map:
- mock_get_map.return_value = {"gpt-5.2": {"input_cost_per_token": 0.001}}
+ from litellm.litellm_core_utils.get_model_cost_map import ModelCostMapReloaded
+
+ with patch(
+ "litellm.litellm_core_utils.get_model_cost_map.refetch_model_cost_map",
+ new=AsyncMock(
+ return_value=ModelCostMapReloaded(model_cost_map={"gpt-5.2": {"input_cost_per_token": 0.001}})
+ ),
+ ):
await ProxyConfig()._check_and_reload_model_cost_map(prisma_client=prisma_client)
finally:
litellm.model_cost = original_model_cost
diff --git a/tests/test_litellm/proxy/proxy_server/test_routes_model_cost_map.py b/tests/test_litellm/proxy/proxy_server/test_routes_model_cost_map.py
index 16e410f1b1e..df1d096b3e2 100644
--- a/tests/test_litellm/proxy/proxy_server/test_routes_model_cost_map.py
+++ b/tests/test_litellm/proxy/proxy_server/test_routes_model_cost_map.py
@@ -48,6 +48,7 @@ def _attach_litellm_config(mock_prisma):
def test_reload_model_cost_map_happy(client, auth_as, monkeypatch, mock_prisma):
"""Admin can trigger a manual reload; handler returns model count + status."""
+ from litellm.litellm_core_utils.get_model_cost_map import ModelCostMapReloaded
from litellm.proxy import proxy_server as ps
from litellm.proxy._types import LitellmUserRoles
@@ -56,8 +57,8 @@ def test_reload_model_cost_map_happy(client, auth_as, monkeypatch, mock_prisma):
fake_cost_map = {"gpt-4": {"input_cost": 0.03}, "gpt-3.5": {"input_cost": 0.002}}
monkeypatch.setattr(
- "litellm.litellm_core_utils.get_model_cost_map.get_model_cost_map",
- lambda url=None: fake_cost_map,
+ "litellm.litellm_core_utils.get_model_cost_map.refetch_model_cost_map",
+ AsyncMock(return_value=ModelCostMapReloaded(model_cost_map=fake_cost_map)),
)
monkeypatch.setattr("litellm.add_known_models", lambda model_cost_map=None: None)
monkeypatch.setattr("litellm.model_cost", {}, raising=False)
@@ -85,6 +86,46 @@ def test_reload_model_cost_map_happy(client, auth_as, monkeypatch, mock_prisma):
assert table.upsert.await_count == 1
+def test_reload_model_cost_map_fetch_failure_502_keeps_map(
+ client, auth_as, monkeypatch, mock_prisma
+):
+ """Fetch failure returns 502 with the reason; the pod's map and DB flag are untouched.
+
+ Regression: the endpoint used to report success after silently swapping in
+ the stale packaged backup.
+ """
+ from litellm.litellm_core_utils.get_model_cost_map import (
+ ModelCostMapReloadUnavailable,
+ )
+ from litellm.proxy import proxy_server as ps
+ from litellm.proxy._types import LitellmUserRoles
+
+ table = _attach_litellm_config(mock_prisma)
+ monkeypatch.setattr(ps, "prisma_client", mock_prisma)
+
+ sentinel_map = {"existing-model": {"input_cost": 0.01}}
+ monkeypatch.setattr("litellm.model_cost", sentinel_map, raising=False)
+ monkeypatch.setattr(
+ "litellm.litellm_core_utils.get_model_cost_map.refetch_model_cost_map",
+ AsyncMock(
+ return_value=ModelCostMapReloadUnavailable(
+ reason="HTTP 429 from upstream (after 3 attempts)"
+ )
+ ),
+ )
+
+ with auth_as(LitellmUserRoles.PROXY_ADMIN):
+ response = client.post("/reload/model_cost_map")
+ assert response.status_code == 502
+ detail = response.json().get("detail", "")
+ assert "HTTP 429 from upstream" in detail
+ assert "Current pricing data was kept" in detail
+ import litellm as litellm_module
+
+ assert litellm_module.model_cost is sentinel_map
+ assert table.upsert.await_count == 0
+
+
def test_reload_model_cost_map_not_admin_forbidden(client, auth_as):
"""Non-admin caller gets 403 with a role-specific detail."""
from litellm.proxy._types import LitellmUserRoles
diff --git a/tests/test_litellm/proxy/test_proxy_server.py b/tests/test_litellm/proxy/test_proxy_server.py
index ab64224fdc3..67e76585485 100644
--- a/tests/test_litellm/proxy/test_proxy_server.py
+++ b/tests/test_litellm/proxy/test_proxy_server.py
@@ -3622,14 +3622,18 @@ class TestPriceDataReloadAPI:
# Save the original model_cost so the endpoint's direct assignment
# (litellm.model_cost = new_model_cost_map) does not contaminate
# subsequent tests running in the same worker process.
+ from litellm.litellm_core_utils.get_model_cost_map import ModelCostMapReloaded
+
original_model_cost = litellm.model_cost.copy()
try:
with patch(
- "litellm.litellm_core_utils.get_model_cost_map.get_model_cost_map"
- ) as mock_get_map:
- mock_get_map.return_value = {
- "gpt-3.5-turbo": {"input_cost_per_token": 0.001}
- }
+ "litellm.litellm_core_utils.get_model_cost_map.refetch_model_cost_map",
+ new=AsyncMock(
+ return_value=ModelCostMapReloaded(
+ model_cost_map={"gpt-3.5-turbo": {"input_cost_per_token": 0.001}}
+ )
+ ),
+ ):
# Mock the database connection
with patch("litellm.proxy.proxy_server.prisma_client") as mock_prisma:
mock_prisma.db.litellm_config.find_unique = AsyncMock(
@@ -3684,10 +3688,9 @@ class TestPriceDataReloadAPI:
def test_reload_model_cost_map_error_handling(self, client_with_auth):
"""Test error handling in the reload endpoint"""
with patch(
- "litellm.litellm_core_utils.get_model_cost_map.get_model_cost_map"
- ) as mock_get_map:
- mock_get_map.side_effect = Exception("Network error")
-
+ "litellm.litellm_core_utils.get_model_cost_map.refetch_model_cost_map",
+ new=AsyncMock(side_effect=Exception("Network error")),
+ ):
# Mock the database connection
with patch("litellm.proxy.proxy_server.prisma_client") as mock_prisma:
mock_prisma.db.litellm_config.find_unique = AsyncMock(return_value=None)
@@ -3697,7 +3700,7 @@ class TestPriceDataReloadAPI:
assert (
response.status_code == 500
- ) # The new implementation immediately reloads and fails on error
+ ) # An unexpected exception still maps to 500
data = response.json()
assert "Failed to reload model cost map" in data["detail"]
@@ -3885,13 +3888,16 @@ class TestPriceDataReloadIntegration:
"gpt-4": {"input_cost_per_token": 0.03, "output_cost_per_token": 0.06},
}
+ from litellm.litellm_core_utils.get_model_cost_map import ModelCostMapReloaded
+
original_model_cost = litellm.model_cost.copy()
try:
with patch(
- "litellm.litellm_core_utils.get_model_cost_map.get_model_cost_map"
- ) as mock_get_map:
- mock_get_map.return_value = mock_cost_map
-
+ "litellm.litellm_core_utils.get_model_cost_map.refetch_model_cost_map",
+ new=AsyncMock(
+ return_value=ModelCostMapReloaded(model_cost_map=mock_cost_map)
+ ),
+ ):
# Mock the database connection
with patch("litellm.proxy.proxy_server.prisma_client") as mock_prisma:
mock_prisma.db.litellm_config.find_unique = AsyncMock(
@@ -3956,15 +3962,18 @@ class TestPriceDataReloadIntegration:
mock_prisma.get_generic_data = AsyncMock(return_value=mock_config)
mock_prisma.db.litellm_config.upsert = AsyncMock(return_value=None)
+ from litellm.litellm_core_utils.get_model_cost_map import ModelCostMapReloaded
+
original_model_cost = litellm.model_cost.copy()
try:
with patch(
- "litellm.litellm_core_utils.get_model_cost_map.get_model_cost_map"
- ) as mock_get_map:
- mock_get_map.return_value = {
- "gpt-3.5-turbo": {"input_cost_per_token": 0.001}
- }
-
+ "litellm.litellm_core_utils.get_model_cost_map.refetch_model_cost_map",
+ new=AsyncMock(
+ return_value=ModelCostMapReloaded(
+ model_cost_map={"gpt-3.5-turbo": {"input_cost_per_token": 0.001}}
+ )
+ ),
+ ):
# Should reload due to force flag
asyncio.run(proxy_config._check_and_reload_model_cost_map(mock_prisma))
@@ -3999,13 +4008,18 @@ class TestPriceDataReloadIntegration:
mock_prisma.get_generic_data = AsyncMock(return_value=mock_config)
mock_prisma.db.litellm_config.upsert = AsyncMock(return_value=None)
+ from litellm.litellm_core_utils.get_model_cost_map import ModelCostMapReloaded
+
original_model_cost = litellm.model_cost.copy()
try:
with patch(
- "litellm.litellm_core_utils.get_model_cost_map.get_model_cost_map"
- ) as mock_get_map:
- mock_get_map.return_value = {"gpt-4": {"input_cost_per_token": 0.001}}
-
+ "litellm.litellm_core_utils.get_model_cost_map.refetch_model_cost_map",
+ new=AsyncMock(
+ return_value=ModelCostMapReloaded(
+ model_cost_map={"gpt-4": {"input_cost_per_token": 0.001}}
+ )
+ ),
+ ):
asyncio.run(proxy_config._check_and_reload_model_cost_map(mock_prisma))
# Verify the upsert update branch preserves interval_hours
@@ -4022,6 +4036,47 @@ class TestPriceDataReloadIntegration:
litellm.model_cost = original_model_cost
_invalidate_model_cost_lowercase_map()
+ def test_distributed_reload_keeps_current_map_when_fetch_fails(self):
+ """Fetch failure during a periodic/forced reload must not downgrade the pod.
+
+ Regression: a 429/network failure used to silently replace litellm.model_cost
+ with the stale packaged backup, stamp last_run, and clear force_reload.
+ """
+ from litellm.litellm_core_utils.get_model_cost_map import (
+ ModelCostMapReloadUnavailable,
+ )
+ from litellm.proxy import proxy_server as ps
+ from litellm.proxy.proxy_server import ProxyConfig
+
+ proxy_config = ProxyConfig()
+ mock_prisma = MagicMock()
+
+ mock_config = MagicMock()
+ mock_config.param_value = {"interval_hours": 6, "force_reload": True}
+ mock_prisma.db.litellm_config.find_unique = AsyncMock(return_value=mock_config)
+ mock_prisma.get_generic_data = AsyncMock(return_value=mock_config)
+ mock_prisma.db.litellm_config.upsert = AsyncMock(return_value=None)
+
+ original_model_cost = litellm.model_cost
+ with patch(
+ "litellm.litellm_core_utils.get_model_cost_map.refetch_model_cost_map",
+ new=AsyncMock(
+ return_value=ModelCostMapReloadUnavailable(reason="HTTP 429 from upstream")
+ ),
+ ):
+ with patch("litellm.proxy.proxy_server.last_model_cost_map_reload", None):
+ asyncio.run(proxy_config._check_and_reload_model_cost_map(mock_prisma))
+ assert ps.last_model_cost_map_reload is None, (
+ "a failed reload must not stamp the pod's last reload time, "
+ "otherwise the retry waits a full interval"
+ )
+
+ assert litellm.model_cost is original_model_cost, (
+ "a failed reload must keep the currently loaded cost map, "
+ "not swap in the packaged backup"
+ )
+ mock_prisma.db.litellm_config.upsert.assert_not_called()
+
def test_manual_reload_preserves_interval_hours(self):
"""Test that manual reload via /reload/model_cost_map preserves existing interval_hours.
@@ -4041,13 +4096,18 @@ class TestPriceDataReloadIntegration:
app.dependency_overrides[user_api_key_auth] = lambda: mock_auth
client = TestClient(app)
+ from litellm.litellm_core_utils.get_model_cost_map import ModelCostMapReloaded
+
original_model_cost = litellm.model_cost.copy()
try:
with patch(
- "litellm.litellm_core_utils.get_model_cost_map.get_model_cost_map"
- ) as mock_get_map:
- mock_get_map.return_value = {"gpt-4": {"input_cost_per_token": 0.001}}
-
+ "litellm.litellm_core_utils.get_model_cost_map.refetch_model_cost_map",
+ new=AsyncMock(
+ return_value=ModelCostMapReloaded(
+ model_cost_map={"gpt-4": {"input_cost_per_token": 0.001}}
+ )
+ ),
+ ):
with patch("litellm.proxy.proxy_server.prisma_client") as mock_prisma:
# Simulate existing config with a schedule
mock_existing = MagicMock()