From 8c5fa0c0f9ec195636372bc8861f2f88402717f4 Mon Sep 17 00:00:00 2001 From: Thijmen Stavenuiter Date: Sat, 15 Aug 2026 20:05:43 +0200 Subject: [PATCH 01/12] feat: add show budget window usage --- .../key_management_endpoints.py | 62 ++++++ .../test_key_management_endpoints.py | 206 ++++++++++++++++++ 2 files changed, 268 insertions(+) diff --git a/litellm/proxy/management_endpoints/key_management_endpoints.py b/litellm/proxy/management_endpoints/key_management_endpoints.py index 7e190e8b19d..22edbf33f94 100644 --- a/litellm/proxy/management_endpoints/key_management_endpoints.py +++ b/litellm/proxy/management_endpoints/key_management_endpoints.py @@ -106,6 +106,7 @@ from litellm.proxy.management_helpers.team_member_permission_checks import ( TeamMemberPermissionChecks, ) from litellm.proxy.management_helpers.utils import management_endpoint_wrapper +from litellm.proxy.spend_tracking.budget_reservation import get_budget_window_start from litellm.proxy.spend_tracking.spend_tracking_utils import _is_master_key from litellm.proxy.ui_crud_endpoints.proxy_setting_endpoints import ( get_ui_settings_cached, @@ -3516,6 +3517,61 @@ async def _build_model_max_budget_usage( return result +async def _attach_budget_limits_usage(key_info: dict, api_key_hash: str) -> None: + """ + Attach current-window spend to each entry in key_info["budget_limits"], in place. + + Per-window spend is not persisted in the DB; it lives in the cross-pod spend + counters (spend:key:{hashed_token}:window:{budget_duration}) that + _virtual_key_multi_budget_check enforces against, so we read the same + counters via get_current_spend. Passing max_budget + window_start makes the + read re-check against the authoritative spend-log aggregate when the counter + is stale-low (e.g. after a Redis flush), same as the enforcement path. + """ + from litellm.proxy.proxy_server import get_current_spend + + budget_limits: Any = key_info.get("budget_limits") + if isinstance(budget_limits, str): + try: + budget_limits = json.loads(budget_limits) + except (TypeError, ValueError): + return + key_info["budget_limits"] = budget_limits + if not isinstance(budget_limits, list): + return + + for idx, window in enumerate(budget_limits): + w: dict | None = None + if isinstance(window, dict): + w = window + elif hasattr(window, "model_dump"): + try: + w = window.model_dump() + except Exception: # noqa: BLE001 + continue + budget_limits[idx] = w + if not w: + continue + duration: Any = w.get("budget_duration") + max_budget: Any = w.get("max_budget") + if not duration: + continue + try: + max_budget = float(max_budget) if max_budget is not None else None + except (TypeError, ValueError): + max_budget = None + counter_key: Final = f"spend:key:{api_key_hash}:window:{duration}" + spend: Final = await get_current_spend( + counter_key=counter_key, + fallback_spend=0.0, + max_budget=max_budget, + window_entity_type="Key", + window_entity_id=api_key_hash, + window_start=get_budget_window_start(w), + ) + w["current_spend"] = round(spend, 4) + + @router.post( "/v2/key/info", tags=["key management"], @@ -3597,6 +3653,8 @@ async def info_key_fn_v2( model_max_budget=model_max_budget, user_api_key_cache=user_api_key_cache, ) + if k_token_hash: + await _attach_budget_limits_usage(key_info=k_dict, api_key_hash=k_token_hash) filtered_key_info.append(k_dict) return {"key": data.keys, "info": filtered_key_info} @@ -3633,6 +3691,9 @@ async def info_key_fn( - model_max_budget: dict - Per-model budgets, e.g. {"gpt-4": {"budget_limit": 0.0005, "time_period": "30d"}} - model_max_budget_usage: dict | None - Current-window spend per model, present only when the key has per-model budgets + - budget_limits: list | None - Concurrent budget windows. Each entry includes + current_spend: spend accumulated in the window so far (read from the same cross-pod + spend counter the budget enforcement uses) - models: list - Model_name's the key is allowed to call - tpm_limit / rpm_limit: int | None - Tokens and requests per minute limits - metadata: dict - Metadata for the key, e.g. {"team": "core-infra"} @@ -3709,6 +3770,7 @@ async def info_key_fn( model_max_budget=model_max_budget, user_api_key_cache=user_api_key_cache, ) + await _attach_budget_limits_usage(key_info=key_info, api_key_hash=key_token_hash) # Attach object_permission if object_permission_id is set key_info = await attach_object_permission_to_dict(key_info, prisma_client) diff --git a/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py index bdf09a95e4b..59f7a2f1e8e 100644 --- a/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py +++ b/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py @@ -13789,6 +13789,212 @@ async def test_info_key_fn_v2_budget_table_fallback(monkeypatch): mock_prisma_client.db.query_raw.assert_not_awaited() +@pytest.mark.asyncio +async def test_info_key_fn_budget_limits_includes_current_spend(monkeypatch): + """ + /key/info should attach current_spend to each budget_limits window, read from + the same spend counter (spend:key:{token}:window:{duration}) that budget + enforcement uses. + """ + from unittest.mock import AsyncMock, MagicMock + + from litellm.proxy._types import LiteLLM_VerificationToken + from litellm.proxy.management_endpoints.key_management_endpoints import info_key_fn + + test_key_token = "hashed_token_window_test" + budget_limits = [ + { + "reset_at": "2026-08-15T18:00:00+00:00", + "max_budget": 2.0, + "budget_duration": "1h", + } + ] + + mock_prisma_client = AsyncMock() + monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client) + mock_user_api_key_cache = AsyncMock() + monkeypatch.setattr( + "litellm.proxy.proxy_server.user_api_key_cache", mock_user_api_key_cache + ) + mock_get_current_spend = AsyncMock(return_value=0.73) + monkeypatch.setattr( + "litellm.proxy.proxy_server.get_current_spend", mock_get_current_spend + ) + + mock_key_info = MagicMock(spec=LiteLLM_VerificationToken) + mock_key_info.token = test_key_token + mock_key_info.object_permission_id = None + mock_key_info.user_id = "user-w" + mock_key_info.team_id = None + mock_key_info.litellm_budget_table = None + mock_key_info.model_dump.return_value = { + "token": test_key_token, + "budget_limits": [dict(w) for w in budget_limits], + "user_id": "user-w", + "team_id": None, + "object_permission_id": None, + "litellm_budget_table": None, + } + mock_key_info.dict.return_value = mock_key_info.model_dump.return_value + + mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock( + return_value=mock_key_info + ) + + user_api_key_dict = UserAPIKeyAuth( + user_role=LitellmUserRoles.PROXY_ADMIN, + api_key="sk-test-window-key", + ) + + result = await info_key_fn( + key="sk-test-window-key", + user_api_key_dict=user_api_key_dict, + ) + + windows = result["info"]["budget_limits"] + assert len(windows) == 1 + assert windows[0]["current_spend"] == 0.73 + assert windows[0]["max_budget"] == 2.0 + assert windows[0]["budget_duration"] == "1h" + + mock_get_current_spend.assert_awaited_once() + call_kwargs = mock_get_current_spend.await_args.kwargs + assert call_kwargs["counter_key"] == f"spend:key:{test_key_token}:window:1h" + assert call_kwargs["max_budget"] == 2.0 + assert call_kwargs["window_entity_type"] == "Key" + assert call_kwargs["window_entity_id"] == test_key_token + assert call_kwargs["window_start"] is not None + + +@pytest.mark.asyncio +async def test_info_key_fn_no_budget_limits_skips_spend_lookup(monkeypatch): + """Keys without budget_limits should not trigger window spend lookups.""" + from unittest.mock import AsyncMock, MagicMock + + from litellm.proxy._types import LiteLLM_VerificationToken + from litellm.proxy.management_endpoints.key_management_endpoints import info_key_fn + + test_key_token = "hashed_token_no_windows" + + mock_prisma_client = AsyncMock() + monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client) + mock_user_api_key_cache = AsyncMock() + monkeypatch.setattr( + "litellm.proxy.proxy_server.user_api_key_cache", mock_user_api_key_cache + ) + mock_get_current_spend = AsyncMock(return_value=0.0) + monkeypatch.setattr( + "litellm.proxy.proxy_server.get_current_spend", mock_get_current_spend + ) + + mock_key_info = MagicMock(spec=LiteLLM_VerificationToken) + mock_key_info.token = test_key_token + mock_key_info.object_permission_id = None + mock_key_info.user_id = "user-nw" + mock_key_info.team_id = None + mock_key_info.litellm_budget_table = None + mock_key_info.model_dump.return_value = { + "token": test_key_token, + "budget_limits": None, + "user_id": "user-nw", + "team_id": None, + "object_permission_id": None, + "litellm_budget_table": None, + } + mock_key_info.dict.return_value = mock_key_info.model_dump.return_value + + mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock( + return_value=mock_key_info + ) + + user_api_key_dict = UserAPIKeyAuth( + user_role=LitellmUserRoles.PROXY_ADMIN, + api_key="sk-test-no-window-key", + ) + + result = await info_key_fn( + key="sk-test-no-window-key", + user_api_key_dict=user_api_key_dict, + ) + + assert result["info"]["budget_limits"] is None + mock_get_current_spend.assert_not_awaited() + + +@pytest.mark.asyncio +async def test_info_key_fn_v2_budget_limits_includes_current_spend(monkeypatch): + """/v2/key/info should attach current_spend to each budget_limits window.""" + from unittest.mock import AsyncMock, MagicMock + + from litellm.proxy._types import KeyRequest, LiteLLM_VerificationToken + from litellm.proxy.management_endpoints.key_management_endpoints import ( + info_key_fn_v2, + ) + + test_key_token = "hashed_token_v2_window_test" + + mock_prisma_client = AsyncMock() + monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client) + mock_user_api_key_cache = AsyncMock() + monkeypatch.setattr( + "litellm.proxy.proxy_server.user_api_key_cache", mock_user_api_key_cache + ) + mock_get_current_spend = AsyncMock(return_value=1.25) + monkeypatch.setattr( + "litellm.proxy.proxy_server.get_current_spend", mock_get_current_spend + ) + + mock_key = MagicMock(spec=LiteLLM_VerificationToken) + mock_key.token = test_key_token + mock_key.user_id = "user-v2-w" + mock_key.team_id = None + mock_key.model_dump.return_value = { + "token": test_key_token, + "budget_limits": [ + { + "reset_at": "2026-08-15T18:00:00+00:00", + "max_budget": 2.0, + "budget_duration": "1h", + }, + { + "reset_at": "2026-08-16T00:00:00+00:00", + "max_budget": 20.0, + "budget_duration": "1d", + }, + ], + "user_id": "user-v2-w", + "team_id": None, + "litellm_budget_table": None, + } + mock_key.dict.return_value = mock_key.model_dump.return_value + + mock_prisma_client.get_data = AsyncMock(return_value=[mock_key]) + + user_api_key_dict = UserAPIKeyAuth( + user_role=LitellmUserRoles.PROXY_ADMIN, + api_key="sk-admin-v2-w", + ) + + result = await info_key_fn_v2( + data=KeyRequest(keys=[test_key_token]), + user_api_key_dict=user_api_key_dict, + ) + + assert len(result["info"]) == 1 + windows = result["info"][0]["budget_limits"] + assert len(windows) == 2 + assert windows[0]["current_spend"] == 1.25 + assert windows[1]["current_spend"] == 1.25 + assert mock_get_current_spend.await_count == 2 + counter_keys = { + call.kwargs["counter_key"] for call in mock_get_current_spend.await_args_list + } + assert counter_keys == { + f"spend:key:{test_key_token}:window:1h", + f"spend:key:{test_key_token}:window:1d", + } + + @pytest.mark.asyncio async def test_info_key_fn_provider_prefix_spend_fallback(monkeypatch): """Cached spend for 'gpt-4o' matches budget key 'openai/gpt-4o' via suffix match.""" From 34bc22fffd3459954afc42ede850f622d1344520 Mon Sep 17 00:00:00 2001 From: Thijmen Stavenuiter Date: Sat, 15 Aug 2026 21:10:12 +0200 Subject: [PATCH 02/12] fix: address pr comments --- .../key_management_endpoints.py | 25 +++-- .../test_key_management_endpoints.py | 103 ++++++++++++++++++ 2 files changed, 119 insertions(+), 9 deletions(-) diff --git a/litellm/proxy/management_endpoints/key_management_endpoints.py b/litellm/proxy/management_endpoints/key_management_endpoints.py index 22edbf33f94..5e4642d66a9 100644 --- a/litellm/proxy/management_endpoints/key_management_endpoints.py +++ b/litellm/proxy/management_endpoints/key_management_endpoints.py @@ -3517,6 +3517,20 @@ async def _build_model_max_budget_usage( return result +def _budget_window_to_dict(window: object) -> dict | None: + """Coerce a budget_limits entry to a dict; None when the entry is unusable.""" + if isinstance(window, dict): + return window + model_dump = getattr(window, "model_dump", None) + if callable(model_dump): + try: + dumped: Any = model_dump() + except Exception: # noqa: BLE001 + return None + return dumped if isinstance(dumped, dict) else None + return None + + async def _attach_budget_limits_usage(key_info: dict, api_key_hash: str) -> None: """ Attach current-window spend to each entry in key_info["budget_limits"], in place. @@ -3541,17 +3555,10 @@ async def _attach_budget_limits_usage(key_info: dict, api_key_hash: str) -> None return for idx, window in enumerate(budget_limits): - w: dict | None = None - if isinstance(window, dict): - w = window - elif hasattr(window, "model_dump"): - try: - w = window.model_dump() - except Exception: # noqa: BLE001 - continue - budget_limits[idx] = w + w: Final = _budget_window_to_dict(window) if not w: continue + budget_limits[idx] = w duration: Any = w.get("budget_duration") max_budget: Any = w.get("max_budget") if not duration: diff --git a/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py index 59f7a2f1e8e..5df7c1cb28d 100644 --- a/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py +++ b/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py @@ -13995,6 +13995,109 @@ async def test_info_key_fn_v2_budget_limits_includes_current_spend(monkeypatch): } +@pytest.mark.asyncio +async def test_attach_budget_limits_usage_json_string_input(monkeypatch): + """budget_limits stored as a JSON string should be parsed and annotated.""" + import json as json_module + from unittest.mock import AsyncMock + + from litellm.proxy.management_endpoints.key_management_endpoints import ( + _attach_budget_limits_usage, + ) + + mock_get_current_spend = AsyncMock(return_value=0.5) + monkeypatch.setattr( + "litellm.proxy.proxy_server.get_current_spend", mock_get_current_spend + ) + + key_info = { + "budget_limits": json_module.dumps( + [{"budget_duration": "1h", "max_budget": 2.0, "reset_at": None}] + ) + } + await _attach_budget_limits_usage(key_info=key_info, api_key_hash="hash-1") + + assert isinstance(key_info["budget_limits"], list) + assert key_info["budget_limits"][0]["current_spend"] == 0.5 + + +@pytest.mark.asyncio +async def test_attach_budget_limits_usage_skips_unusable_inputs(monkeypatch): + """Invalid JSON strings, non-list values, and malformed windows are skipped.""" + from unittest.mock import AsyncMock + + from litellm.proxy.management_endpoints.key_management_endpoints import ( + _attach_budget_limits_usage, + ) + + mock_get_current_spend = AsyncMock(return_value=0.0) + monkeypatch.setattr( + "litellm.proxy.proxy_server.get_current_spend", mock_get_current_spend + ) + + # invalid JSON string + key_info = {"budget_limits": "{not json"} + await _attach_budget_limits_usage(key_info=key_info, api_key_hash="hash-1") + assert key_info["budget_limits"] == "{not json" + + # non-list value + key_info = {"budget_limits": {"budget_duration": "1h"}} + await _attach_budget_limits_usage(key_info=key_info, api_key_hash="hash-1") + + # windows that are falsy, missing budget_duration, or not dict-like + key_info = { + "budget_limits": [ + {}, + {"max_budget": 2.0}, + {"budget_duration": "1h", "max_budget": "not-a-number"}, + 42, + ] + } + await _attach_budget_limits_usage(key_info=key_info, api_key_hash="hash-1") + + # only the well-formed window (with unparseable max_budget coerced to None) + # triggers a spend lookup + mock_get_current_spend.assert_awaited_once() + call_kwargs = mock_get_current_spend.await_args.kwargs + assert call_kwargs["counter_key"] == "spend:key:hash-1:window:1h" + assert call_kwargs["max_budget"] is None + assert key_info["budget_limits"][2]["current_spend"] == 0.0 + assert key_info["budget_limits"][3] == 42 + + +@pytest.mark.asyncio +async def test_attach_budget_limits_usage_pydantic_windows(monkeypatch): + """Window objects with model_dump() are converted to dicts in place.""" + from unittest.mock import AsyncMock, MagicMock + + from litellm.proxy.management_endpoints.key_management_endpoints import ( + _attach_budget_limits_usage, + ) + + mock_get_current_spend = AsyncMock(return_value=1.0) + monkeypatch.setattr( + "litellm.proxy.proxy_server.get_current_spend", mock_get_current_spend + ) + + good_window = MagicMock() + good_window.model_dump.return_value = { + "budget_duration": "7d", + "max_budget": 10.0, + "reset_at": None, + } + bad_window = MagicMock() + bad_window.model_dump.side_effect = ValueError("boom") + + key_info = {"budget_limits": [good_window, bad_window]} + await _attach_budget_limits_usage(key_info=key_info, api_key_hash="hash-2") + + # good window converted to dict and annotated; failing window left as-is + assert isinstance(key_info["budget_limits"][0], dict) + assert key_info["budget_limits"][0]["current_spend"] == 1.0 + assert key_info["budget_limits"][1] is bad_window + mock_get_current_spend.assert_awaited_once() + + @pytest.mark.asyncio async def test_info_key_fn_provider_prefix_spend_fallback(monkeypatch): """Cached spend for 'gpt-4o' matches budget key 'openai/gpt-4o' via suffix match.""" From db67bafd59a0e131d70cfc4a5b1a3e494ca63373 Mon Sep 17 00:00:00 2001 From: Thijmen Stavenuiter Date: Sat, 15 Aug 2026 21:26:55 +0200 Subject: [PATCH 03/12] fix: drop Final from loop locals to stay within the basedpyright budget --- .../proxy/management_endpoints/key_management_endpoints.py | 6 +++--- ui/litellm-dashboard/src/lib/http/schema.d.ts | 3 +++ 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/litellm/proxy/management_endpoints/key_management_endpoints.py b/litellm/proxy/management_endpoints/key_management_endpoints.py index 5e4642d66a9..51b9ebf91d8 100644 --- a/litellm/proxy/management_endpoints/key_management_endpoints.py +++ b/litellm/proxy/management_endpoints/key_management_endpoints.py @@ -3555,7 +3555,7 @@ async def _attach_budget_limits_usage(key_info: dict, api_key_hash: str) -> None return for idx, window in enumerate(budget_limits): - w: Final = _budget_window_to_dict(window) + w = _budget_window_to_dict(window) if not w: continue budget_limits[idx] = w @@ -3567,8 +3567,8 @@ async def _attach_budget_limits_usage(key_info: dict, api_key_hash: str) -> None max_budget = float(max_budget) if max_budget is not None else None except (TypeError, ValueError): max_budget = None - counter_key: Final = f"spend:key:{api_key_hash}:window:{duration}" - spend: Final = await get_current_spend( + counter_key = f"spend:key:{api_key_hash}:window:{duration}" + spend = await get_current_spend( counter_key=counter_key, fallback_spend=0.0, max_budget=max_budget, diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.ts index 3b4b96bdd4e..f4703202b18 100644 --- a/ui/litellm-dashboard/src/lib/http/schema.d.ts +++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts @@ -7020,6 +7020,9 @@ export interface paths { * - model_max_budget: dict - Per-model budgets, e.g. {"gpt-4": {"budget_limit": 0.0005, "time_period": "30d"}} * - model_max_budget_usage: dict | None - Current-window spend per model, present only when * the key has per-model budgets + * - budget_limits: list | None - Concurrent budget windows. Each entry includes + * current_spend: spend accumulated in the window so far (read from the same cross-pod + * spend counter the budget enforcement uses) * - models: list - Model_name's the key is allowed to call * - tpm_limit / rpm_limit: int | None - Tokens and requests per minute limits * - metadata: dict - Metadata for the key, e.g. {"team": "core-infra"} From 31130036c0013b8c0ad34e6cffbd58b24ee8b78a Mon Sep 17 00:00:00 2001 From: Thijmen Stavenuiter Date: Mon, 17 Aug 2026 16:21:31 +0200 Subject: [PATCH 04/12] refactor: build budget window usage without in-place mutation Replace _attach_budget_limits_usage, which rewrote the caller's key_info dict, with _budget_limits_with_usage returning a new list. Callers assign the result once. Keeps the response shape and spend-counter read path identical while following the repo's no-mutation rule. --- .../key_management_endpoints.py | 119 +++++++++++------- .../test_key_management_endpoints.py | 83 ++++++------ 2 files changed, 121 insertions(+), 81 deletions(-) diff --git a/litellm/proxy/management_endpoints/key_management_endpoints.py b/litellm/proxy/management_endpoints/key_management_endpoints.py index 51b9ebf91d8..f6f739f3eae 100644 --- a/litellm/proxy/management_endpoints/key_management_endpoints.py +++ b/litellm/proxy/management_endpoints/key_management_endpoints.py @@ -3517,23 +3517,44 @@ async def _build_model_max_budget_usage( return result -def _budget_window_to_dict(window: object) -> dict | None: +def _budget_window_to_dict(window: object) -> Mapping[str, object] | None: """Coerce a budget_limits entry to a dict; None when the entry is unusable.""" if isinstance(window, dict): return window - model_dump = getattr(window, "model_dump", None) - if callable(model_dump): + model_dump: Final = getattr(window, "model_dump", None) + if not callable(model_dump): + return None + try: + dumped: Final = model_dump() + except Exception: # noqa: BLE001 # model_dump implementations can raise arbitrary errors + return None + return dumped if isinstance(dumped, dict) else None + + +def _coerce_budget_limits(budget_limits: object) -> Sequence[object] | None: + """Coerce budget_limits to a sequence of windows, parsing JSON strings; None when unusable.""" + if isinstance(budget_limits, str): try: - dumped: Any = model_dump() - except Exception: # noqa: BLE001 + parsed: Final = json.loads(budget_limits) + except (TypeError, ValueError): + return None + return parsed if isinstance(parsed, list) else None + return budget_limits if isinstance(budget_limits, list) else None + + +def _parse_window_max_budget(value: object) -> float | None: + """Coerce a window's max_budget to float; None when absent or unparseable.""" + if isinstance(value, (int, float, str)): + try: + return float(value) + except (TypeError, ValueError): return None - return dumped if isinstance(dumped, dict) else None return None -async def _attach_budget_limits_usage(key_info: dict, api_key_hash: str) -> None: +async def _budget_window_with_usage(window: Mapping[str, object], api_key_hash: str) -> Mapping[str, object]: """ - Attach current-window spend to each entry in key_info["budget_limits"], in place. + Return a copy of a budget window with current-window spend attached. Per-window spend is not persisted in the DB; it lives in the cross-pod spend counters (spend:key:{hashed_token}:window:{budget_duration}) that @@ -3544,39 +3565,43 @@ async def _attach_budget_limits_usage(key_info: dict, api_key_hash: str) -> None """ from litellm.proxy.proxy_server import get_current_spend - budget_limits: Any = key_info.get("budget_limits") - if isinstance(budget_limits, str): - try: - budget_limits = json.loads(budget_limits) - except (TypeError, ValueError): - return - key_info["budget_limits"] = budget_limits - if not isinstance(budget_limits, list): - return + duration: Final = window.get("budget_duration") + if not duration: + return dict(window) # mutable-ok: per-window response copy, built once per window + spend: Final = await get_current_spend( + counter_key=f"spend:key:{api_key_hash}:window:{duration}", + fallback_spend=0.0, + max_budget=_parse_window_max_budget(window.get("max_budget")), + window_entity_type="Key", + window_entity_id=api_key_hash, + window_start=get_budget_window_start(window), + ) + return {**window, "current_spend": round(spend, 4)} # mutable-ok: per-window response copy, built once per window - for idx, window in enumerate(budget_limits): - w = _budget_window_to_dict(window) - if not w: - continue - budget_limits[idx] = w - duration: Any = w.get("budget_duration") - max_budget: Any = w.get("max_budget") - if not duration: - continue - try: - max_budget = float(max_budget) if max_budget is not None else None - except (TypeError, ValueError): - max_budget = None - counter_key = f"spend:key:{api_key_hash}:window:{duration}" - spend = await get_current_spend( - counter_key=counter_key, - fallback_spend=0.0, - max_budget=max_budget, - window_entity_type="Key", - window_entity_id=api_key_hash, - window_start=get_budget_window_start(w), - ) - w["current_spend"] = round(spend, 4) + +async def _budget_limits_entry_with_usage(window: object, api_key_hash: str) -> object: + """Return the window as an enriched dict when dict-coercible; the original entry otherwise.""" + coerced: Final = _budget_window_to_dict(window) + if not coerced: + return window + return await _budget_window_with_usage(window=coerced, api_key_hash=api_key_hash) + + +async def _budget_limits_with_usage(budget_limits: object, api_key_hash: str) -> Sequence[object] | None: + """ + Return budget_limits as window dicts with current-window spend attached. + + None when budget_limits is not a usable (possibly JSON-encoded) list; the + caller keeps the original value then. Entries that are not dict-coercible + are preserved as-is. + """ + windows: Final = _coerce_budget_limits(budget_limits) + if windows is None: + return None + return [ # mutable-ok: entries are awaited, so they cannot be built inside a frozen wrapper + await _budget_limits_entry_with_usage(window=window, api_key_hash=api_key_hash) + for window in windows + ] @router.post( @@ -3661,7 +3686,12 @@ async def info_key_fn_v2( user_api_key_cache=user_api_key_cache, ) if k_token_hash: - await _attach_budget_limits_usage(key_info=k_dict, api_key_hash=k_token_hash) + budget_limits_usage = await _budget_limits_with_usage( + budget_limits=k_dict.get("budget_limits"), + api_key_hash=k_token_hash, + ) + if budget_limits_usage is not None: + k_dict["budget_limits"] = budget_limits_usage filtered_key_info.append(k_dict) return {"key": data.keys, "info": filtered_key_info} @@ -3777,7 +3807,12 @@ async def info_key_fn( model_max_budget=model_max_budget, user_api_key_cache=user_api_key_cache, ) - await _attach_budget_limits_usage(key_info=key_info, api_key_hash=key_token_hash) + budget_limits_usage: Final = await _budget_limits_with_usage( + budget_limits=key_info.get("budget_limits"), + api_key_hash=key_token_hash, + ) + if budget_limits_usage is not None: + key_info["budget_limits"] = budget_limits_usage # Attach object_permission if object_permission_id is set key_info = await attach_object_permission_to_dict(key_info, prisma_client) diff --git a/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py index 5df7c1cb28d..1f3b9042ed7 100644 --- a/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py +++ b/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py @@ -13996,13 +13996,13 @@ async def test_info_key_fn_v2_budget_limits_includes_current_spend(monkeypatch): @pytest.mark.asyncio -async def test_attach_budget_limits_usage_json_string_input(monkeypatch): +async def test_budget_limits_with_usage_json_string_input(monkeypatch): """budget_limits stored as a JSON string should be parsed and annotated.""" import json as json_module from unittest.mock import AsyncMock from litellm.proxy.management_endpoints.key_management_endpoints import ( - _attach_budget_limits_usage, + _budget_limits_with_usage, ) mock_get_current_spend = AsyncMock(return_value=0.5) @@ -14010,24 +14010,29 @@ async def test_attach_budget_limits_usage_json_string_input(monkeypatch): "litellm.proxy.proxy_server.get_current_spend", mock_get_current_spend ) - key_info = { - "budget_limits": json_module.dumps( - [{"budget_duration": "1h", "max_budget": 2.0, "reset_at": None}] - ) - } - await _attach_budget_limits_usage(key_info=key_info, api_key_hash="hash-1") + raw = json_module.dumps( + [{"budget_duration": "1h", "max_budget": 2.0, "reset_at": None}] + ) + result = await _budget_limits_with_usage(budget_limits=raw, api_key_hash="hash-1") - assert isinstance(key_info["budget_limits"], list) - assert key_info["budget_limits"][0]["current_spend"] == 0.5 + assert result == [ + { + "budget_duration": "1h", + "max_budget": 2.0, + "reset_at": None, + "current_spend": 0.5, + } + ] + mock_get_current_spend.assert_awaited_once() @pytest.mark.asyncio -async def test_attach_budget_limits_usage_skips_unusable_inputs(monkeypatch): +async def test_budget_limits_with_usage_skips_unusable_inputs(monkeypatch): """Invalid JSON strings, non-list values, and malformed windows are skipped.""" from unittest.mock import AsyncMock from litellm.proxy.management_endpoints.key_management_endpoints import ( - _attach_budget_limits_usage, + _budget_limits_with_usage, ) mock_get_current_spend = AsyncMock(return_value=0.0) @@ -14035,25 +14040,18 @@ async def test_attach_budget_limits_usage_skips_unusable_inputs(monkeypatch): "litellm.proxy.proxy_server.get_current_spend", mock_get_current_spend ) - # invalid JSON string - key_info = {"budget_limits": "{not json"} - await _attach_budget_limits_usage(key_info=key_info, api_key_hash="hash-1") - assert key_info["budget_limits"] == "{not json" - - # non-list value - key_info = {"budget_limits": {"budget_duration": "1h"}} - await _attach_budget_limits_usage(key_info=key_info, api_key_hash="hash-1") + # invalid JSON string and non-list values return None: callers keep the original + assert await _budget_limits_with_usage(budget_limits="{not json", api_key_hash="hash-1") is None + assert await _budget_limits_with_usage(budget_limits={"budget_duration": "1h"}, api_key_hash="hash-1") is None # windows that are falsy, missing budget_duration, or not dict-like - key_info = { - "budget_limits": [ - {}, - {"max_budget": 2.0}, - {"budget_duration": "1h", "max_budget": "not-a-number"}, - 42, - ] - } - await _attach_budget_limits_usage(key_info=key_info, api_key_hash="hash-1") + windows = [ + {}, + {"max_budget": 2.0}, + {"budget_duration": "1h", "max_budget": "not-a-number"}, + 42, + ] + result = await _budget_limits_with_usage(budget_limits=windows, api_key_hash="hash-1") # only the well-formed window (with unparseable max_budget coerced to None) # triggers a spend lookup @@ -14061,17 +14059,22 @@ async def test_attach_budget_limits_usage_skips_unusable_inputs(monkeypatch): call_kwargs = mock_get_current_spend.await_args.kwargs assert call_kwargs["counter_key"] == "spend:key:hash-1:window:1h" assert call_kwargs["max_budget"] is None - assert key_info["budget_limits"][2]["current_spend"] == 0.0 - assert key_info["budget_limits"][3] == 42 + assert result is not None + assert result[0] == {} + assert result[1] == {"max_budget": 2.0} + assert result[2] == {"budget_duration": "1h", "max_budget": "not-a-number", "current_spend": 0.0} + assert result[3] == 42 + # input is not mutated + assert windows[2] == {"budget_duration": "1h", "max_budget": "not-a-number"} @pytest.mark.asyncio -async def test_attach_budget_limits_usage_pydantic_windows(monkeypatch): - """Window objects with model_dump() are converted to dicts in place.""" +async def test_budget_limits_with_usage_pydantic_windows(monkeypatch): + """Window objects with model_dump() are converted to dicts; failing windows pass through.""" from unittest.mock import AsyncMock, MagicMock from litellm.proxy.management_endpoints.key_management_endpoints import ( - _attach_budget_limits_usage, + _budget_limits_with_usage, ) mock_get_current_spend = AsyncMock(return_value=1.0) @@ -14088,13 +14091,15 @@ async def test_attach_budget_limits_usage_pydantic_windows(monkeypatch): bad_window = MagicMock() bad_window.model_dump.side_effect = ValueError("boom") - key_info = {"budget_limits": [good_window, bad_window]} - await _attach_budget_limits_usage(key_info=key_info, api_key_hash="hash-2") + result = await _budget_limits_with_usage( + budget_limits=[good_window, bad_window], api_key_hash="hash-2" + ) # good window converted to dict and annotated; failing window left as-is - assert isinstance(key_info["budget_limits"][0], dict) - assert key_info["budget_limits"][0]["current_spend"] == 1.0 - assert key_info["budget_limits"][1] is bad_window + assert result is not None + assert isinstance(result[0], dict) + assert result[0]["current_spend"] == 1.0 + assert result[1] is bad_window mock_get_current_spend.assert_awaited_once() From 9b30e73d07ebccdf4e6ff24981110e238c080d4d Mon Sep 17 00:00:00 2001 From: Thijmen Stavenuiter Date: Mon, 17 Aug 2026 20:48:12 +0200 Subject: [PATCH 05/12] fix: cap /v2/key/info batch size to bound spend-log query fan-out --- .../key_management_endpoints.py | 16 +++++++++ .../test_key_management_endpoints.py | 33 +++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/litellm/proxy/management_endpoints/key_management_endpoints.py b/litellm/proxy/management_endpoints/key_management_endpoints.py index f6f739f3eae..46d7f617352 100644 --- a/litellm/proxy/management_endpoints/key_management_endpoints.py +++ b/litellm/proxy/management_endpoints/key_management_endpoints.py @@ -3604,6 +3604,11 @@ async def _budget_limits_with_usage(budget_limits: object, api_key_hash: str) -> ] +# Caps per-request fan-out: each key with budget windows costs one spend-counter +# read (worst case a SpendLogs aggregation) per window. +MAX_KEY_INFO_KEYS_PER_REQUEST: Final = 100 + + @router.post( "/v2/key/info", tags=["key management"], @@ -3643,6 +3648,17 @@ async def info_key_fn_v2( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail={"message": "Malformed request. No keys passed in."}, ) + requested_key_count: Final = len(data.keys or []) + len(data.key_aliases or []) + if requested_key_count > MAX_KEY_INFO_KEYS_PER_REQUEST: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail={ + "message": ( + f"Too many keys requested: {requested_key_count}. " + f"At most {MAX_KEY_INFO_KEYS_PER_REQUEST} keys and key_aliases combined per request." + ) + }, + ) # Resolve key_aliases to tokens so we never pass token=None (unbounded query) tokens_to_query: Final = list(data.keys) if data.keys else [] diff --git a/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py index 1f3b9042ed7..9194ffb603b 100644 --- a/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py +++ b/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py @@ -13995,6 +13995,39 @@ async def test_info_key_fn_v2_budget_limits_includes_current_spend(monkeypatch): } +@pytest.mark.asyncio +async def test_info_key_fn_v2_rejects_oversized_batch(monkeypatch): + """/v2/key/info must reject over-cap batches before doing any DB work.""" + from unittest.mock import AsyncMock + + from litellm.proxy._types import KeyRequest, ProxyException + from litellm.proxy.management_endpoints.key_management_endpoints import ( + MAX_KEY_INFO_KEYS_PER_REQUEST, + info_key_fn_v2, + ) + + mock_prisma_client = AsyncMock() + monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client) + monkeypatch.setattr("litellm.proxy.proxy_server.user_api_key_cache", AsyncMock()) + + user_api_key_dict = UserAPIKeyAuth( + user_role=LitellmUserRoles.PROXY_ADMIN, + api_key="sk-admin-batch-cap", + ) + + with pytest.raises(ProxyException) as exc_info: + await info_key_fn_v2( + data=KeyRequest( + keys=[f"hash-{i}" for i in range(MAX_KEY_INFO_KEYS_PER_REQUEST)], + key_aliases=["alias-over-cap"], + ), + user_api_key_dict=user_api_key_dict, + ) + + assert exc_info.value.code == "422" + mock_prisma_client.get_data.assert_not_awaited() + + @pytest.mark.asyncio async def test_budget_limits_with_usage_json_string_input(monkeypatch): """budget_limits stored as a JSON string should be parsed and annotated.""" From ffd23ab1319d0caf9c870be5849006cbc931f3d1 Mon Sep 17 00:00:00 2001 From: Thijmen Stavenuiter Date: Mon, 17 Aug 2026 21:00:24 +0200 Subject: [PATCH 06/12] style: apply ruff format to budget limits comprehension --- litellm/proxy/management_endpoints/key_management_endpoints.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/litellm/proxy/management_endpoints/key_management_endpoints.py b/litellm/proxy/management_endpoints/key_management_endpoints.py index 46d7f617352..170b431c1e2 100644 --- a/litellm/proxy/management_endpoints/key_management_endpoints.py +++ b/litellm/proxy/management_endpoints/key_management_endpoints.py @@ -3599,8 +3599,7 @@ async def _budget_limits_with_usage(budget_limits: object, api_key_hash: str) -> if windows is None: return None return [ # mutable-ok: entries are awaited, so they cannot be built inside a frozen wrapper - await _budget_limits_entry_with_usage(window=window, api_key_hash=api_key_hash) - for window in windows + await _budget_limits_entry_with_usage(window=window, api_key_hash=api_key_hash) for window in windows ] From 4e3e7d8cf6c0afe6171f784a1bba1b0080831edf Mon Sep 17 00:00:00 2001 From: Thijmen Stavenuiter Date: Mon, 17 Aug 2026 21:12:36 +0200 Subject: [PATCH 07/12] test: cover soft budget row creation and windows without max_budget --- .../test_key_management_endpoints.py | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py index 9194ffb603b..c05380dd054 100644 --- a/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py +++ b/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py @@ -540,6 +540,57 @@ async def test_key_generation_with_object_permission(monkeypatch): assert key_insert_calls[0]["data"].get("object_permission_id") == "objperm123" +@pytest.mark.asyncio +async def test_generate_key_with_soft_budget_creates_budget_row(monkeypatch): + """soft_budget on /key/generate must create a budget table row and link its budget_id to the key.""" + mock_prisma_client = AsyncMock() + mock_prisma_client.jsonify_object = lambda data: data + mock_prisma_client.db = MagicMock() + mock_budget_create = AsyncMock(return_value=MagicMock(budget_id="budget-soft-123")) + mock_prisma_client.db.litellm_budgettable = MagicMock() + mock_prisma_client.db.litellm_budgettable.create = mock_budget_create + + async def _insert_data_side_effect(*args, **kwargs): + if kwargs.get("table_name") == "user": + return MagicMock(models=[], spend=0) + return MagicMock( + token="hashed_token_soft", + litellm_budget_table=None, + object_permission=None, + ) + + mock_prisma_client.insert_data = AsyncMock(side_effect=_insert_data_side_effect) + monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client) + + from litellm.proxy._types import GenerateKeyRequest, LitellmUserRoles + from litellm.proxy.auth.user_api_key_auth import UserAPIKeyAuth + from litellm.proxy.management_endpoints.key_management_endpoints import ( + generate_key_fn, + ) + + await generate_key_fn( + data=GenerateKeyRequest(soft_budget=5.0), + user_api_key_dict=UserAPIKeyAuth( + user_role=LitellmUserRoles.PROXY_ADMIN, + api_key="sk-1234", + user_id="admin-1", + ), + ) + + mock_budget_create.assert_awaited_once() + created_budget = mock_budget_create.call_args.kwargs["data"] + assert created_budget["soft_budget"] == 5.0 + assert created_budget["created_by"] == "admin-1" + + key_insert_calls = [ + call.kwargs + for call in mock_prisma_client.insert_data.call_args_list + if call.kwargs.get("table_name") == "key" + ] + assert len(key_insert_calls) == 1 + assert key_insert_calls[0]["data"].get("budget_id") == "budget-soft-123" + + @pytest.mark.asyncio async def test_generate_key_debug_log_never_contains_raw_token(monkeypatch, caplog): """Regression for LIT-4356: /key/generate must never emit the raw virtual key @@ -14101,6 +14152,30 @@ async def test_budget_limits_with_usage_skips_unusable_inputs(monkeypatch): assert windows[2] == {"budget_duration": "1h", "max_budget": "not-a-number"} +@pytest.mark.asyncio +async def test_budget_limits_with_usage_window_without_max_budget(monkeypatch): + """A window with only budget_duration still gets current_spend, read without a budget ceiling.""" + from unittest.mock import AsyncMock + + from litellm.proxy.management_endpoints.key_management_endpoints import ( + _budget_limits_with_usage, + ) + + mock_get_current_spend = AsyncMock(return_value=0.75) + monkeypatch.setattr( + "litellm.proxy.proxy_server.get_current_spend", mock_get_current_spend + ) + + result = await _budget_limits_with_usage( + budget_limits=[{"budget_duration": "2d"}], api_key_hash="hash-no-max" + ) + + assert result == [{"budget_duration": "2d", "current_spend": 0.75}] + call_kwargs = mock_get_current_spend.await_args.kwargs + assert call_kwargs["counter_key"] == "spend:key:hash-no-max:window:2d" + assert call_kwargs["max_budget"] is None + + @pytest.mark.asyncio async def test_budget_limits_with_usage_pydantic_windows(monkeypatch): """Window objects with model_dump() are converted to dicts; failing windows pass through.""" From f4406b4060cddb60731f804513455bea321e7407 Mon Sep 17 00:00:00 2001 From: Thijmen Stavenuiter Date: Mon, 24 Aug 2026 08:52:18 +0200 Subject: [PATCH 08/12] fix(proxy): clear LIT002 in /v2/key/info batch-cap guard The two `or []` fallbacks only feed len(), so tuples do the job without a mutable literal. The detail dict mirrors the sibling HTTPException payload above and is never mutated, so it carries a mutable-ok reason. --- .../proxy/management_endpoints/key_management_endpoints.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/litellm/proxy/management_endpoints/key_management_endpoints.py b/litellm/proxy/management_endpoints/key_management_endpoints.py index 2b37d0bc8fc..85f6d25f6dc 100644 --- a/litellm/proxy/management_endpoints/key_management_endpoints.py +++ b/litellm/proxy/management_endpoints/key_management_endpoints.py @@ -3675,11 +3675,11 @@ async def info_key_fn_v2( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail={"message": "Malformed request. No keys passed in."}, ) - requested_key_count: Final = len(data.keys or []) + len(data.key_aliases or []) + requested_key_count: Final = len(data.keys or ()) + len(data.key_aliases or ()) if requested_key_count > MAX_KEY_INFO_KEYS_PER_REQUEST: raise HTTPException( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, - detail={ + detail={ # mutable-ok: one-shot HTTPException payload matching the sibling detail dict above; never mutated after construction "message": ( f"Too many keys requested: {requested_key_count}. " f"At most {MAX_KEY_INFO_KEYS_PER_REQUEST} keys and key_aliases combined per request." From 41ab7e57e8ac4f222fa6191d1940d7e636debffd Mon Sep 17 00:00:00 2001 From: Thijmen Stavenuiter Date: Mon, 24 Aug 2026 09:09:30 +0200 Subject: [PATCH 09/12] ci(test-unit): raise job timeout to 60m for the three 55m shards caching-local, proxy-extras and enterprise-package gave pytest 20m but capped the job at 55m; with a 35m setup ceiling plus 5m of runner overhead the job deadline could preempt pytest itself. --- .github/workflows/test-unit.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/test-unit.yml b/.github/workflows/test-unit.yml index a7c67f2b35d..2dfca3d308f 100644 --- a/.github/workflows/test-unit.yml +++ b/.github/workflows/test-unit.yml @@ -211,7 +211,7 @@ jobs: workers: 2 reruns: 2 timeout-minutes: 20 - job-timeout-minutes: 55 + job-timeout-minutes: 60 - shard: proxy-extras artifact-name: proxy-extras @@ -219,7 +219,7 @@ jobs: workers: 2 reruns: 2 timeout-minutes: 20 - job-timeout-minutes: 55 + job-timeout-minutes: 60 - shard: enterprise-package artifact-name: enterprise-package @@ -227,7 +227,7 @@ jobs: workers: 4 reruns: 2 timeout-minutes: 20 - job-timeout-minutes: 55 + job-timeout-minutes: 60 - shard: responses-caching-types artifact-name: responses-caching-types From d9c43d5e17746b11414c8aa17755b1e11bec16f6 Mon Sep 17 00:00:00 2001 From: ryan-crabbe-berri Date: Mon, 31 Aug 2026 20:07:28 -0700 Subject: [PATCH 10/12] fix(key management): read budget window usage from the window spend table Pass window_duration to get_current_spend so /key/info re-checks a stale-low counter against the LiteLLM_BudgetWindowSpend row instead of aggregating LiteLLM_SpendLogs, and reuse _budget_limit_windows for the stored-column coercion. Drop the /v2/key/info batch cap (a new 422 for callers that work today) and the unrelated CI timeout bump and soft_budget test --- .../key_management_endpoints.py | 103 +++--------- .../test_key_management_endpoints.py | 156 +++--------------- 2 files changed, 51 insertions(+), 208 deletions(-) diff --git a/litellm/proxy/management_endpoints/key_management_endpoints.py b/litellm/proxy/management_endpoints/key_management_endpoints.py index 03abcb2ff98..02bfa5c0ca8 100644 --- a/litellm/proxy/management_endpoints/key_management_endpoints.py +++ b/litellm/proxy/management_endpoints/key_management_endpoints.py @@ -3579,95 +3579,58 @@ async def _build_model_max_budget_usage( ) -def _budget_window_to_dict(window: object) -> Mapping[str, object] | None: - """Coerce a budget_limits entry to a dict; None when the entry is unusable.""" - if isinstance(window, dict): - return window - model_dump: Final = getattr(window, "model_dump", None) - if not callable(model_dump): +def _window_max_budget(window: Mapping[str, object]) -> float | None: + """A window's max_budget as a float; None when absent or unparseable.""" + value: Final = window.get("max_budget") + if not isinstance(value, (int, float, str)): return None try: - dumped: Final = model_dump() - except Exception: # noqa: BLE001 # model_dump implementations can raise arbitrary errors + return float(value) + except ValueError: return None - return dumped if isinstance(dumped, dict) else None - - -def _coerce_budget_limits(budget_limits: object) -> Sequence[object] | None: - """Coerce budget_limits to a sequence of windows, parsing JSON strings; None when unusable.""" - if isinstance(budget_limits, str): - try: - parsed: Final = json.loads(budget_limits) - except (TypeError, ValueError): - return None - return parsed if isinstance(parsed, list) else None - return budget_limits if isinstance(budget_limits, list) else None - - -def _parse_window_max_budget(value: object) -> float | None: - """Coerce a window's max_budget to float; None when absent or unparseable.""" - if isinstance(value, (int, float, str)): - try: - return float(value) - except (TypeError, ValueError): - return None - return None async def _budget_window_with_usage(window: Mapping[str, object], api_key_hash: str) -> Mapping[str, object]: """ - Return a copy of a budget window with current-window spend attached. + Copy of a budget window with current-window spend attached. - Per-window spend is not persisted in the DB; it lives in the cross-pod spend - counters (spend:key:{hashed_token}:window:{budget_duration}) that - _virtual_key_multi_budget_check enforces against, so we read the same - counters via get_current_spend. Passing max_budget + window_start makes the - read re-check against the authoritative spend-log aggregate when the counter - is stale-low (e.g. after a Redis flush), same as the enforcement path. + Reads the same cross-pod counter (spend:key:{hashed_token}:window:{budget_duration}) + that _virtual_key_multi_budget_check enforces against, passing the same + window_duration + window_start so a stale-low counter is re-checked against + the LiteLLM_BudgetWindowSpend row instead of a spend-log aggregate. """ from litellm.proxy.proxy_server import get_current_spend duration: Final = window.get("budget_duration") - if not duration: - return dict(window) # mutable-ok: per-window response copy, built once per window + if not isinstance(duration, str) or not duration: + return window spend: Final = await get_current_spend( counter_key=f"spend:key:{api_key_hash}:window:{duration}", fallback_spend=0.0, - max_budget=_parse_window_max_budget(window.get("max_budget")), + max_budget=_window_max_budget(window), window_entity_type="Key", window_entity_id=api_key_hash, + window_duration=duration, window_start=get_budget_window_start(window), ) return {**window, "current_spend": round(spend, 4)} # mutable-ok: per-window response copy, built once per window -async def _budget_limits_entry_with_usage(window: object, api_key_hash: str) -> object: - """Return the window as an enriched dict when dict-coercible; the original entry otherwise.""" - coerced: Final = _budget_window_to_dict(window) - if not coerced: - return window - return await _budget_window_with_usage(window=coerced, api_key_hash=api_key_hash) - - -async def _budget_limits_with_usage(budget_limits: object, api_key_hash: str) -> Sequence[object] | None: +async def _budget_limits_with_usage( + budget_limits: Sequence[object] | str | None, api_key_hash: str +) -> tuple[Mapping[str, object], ...] | None: """ - Return budget_limits as window dicts with current-window spend attached. - - None when budget_limits is not a usable (possibly JSON-encoded) list; the - caller keeps the original value then. Entries that are not dict-coercible - are preserved as-is. + budget_limits as window dicts with current-window spend attached; None when + the key has no windows so the caller keeps the stored value. """ - windows: Final = _coerce_budget_limits(budget_limits) - if windows is None: + windows: Final = _budget_limit_windows(budget_limits) + if not windows: return None - return [ # mutable-ok: entries are awaited, so they cannot be built inside a frozen wrapper - await _budget_limits_entry_with_usage(window=window, api_key_hash=api_key_hash) for window in windows - ] - - -# Caps per-request fan-out: each key with budget windows costs one spend-counter -# read (worst case a SpendLogs aggregation) per window. -MAX_KEY_INFO_KEYS_PER_REQUEST: Final = 100 + return tuple( + await asyncio.gather( + *(_budget_window_with_usage(window=window, api_key_hash=api_key_hash) for window in windows) + ) + ) @router.post( @@ -3712,18 +3675,6 @@ async def info_key_fn_v2( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail={"message": "Malformed request. No keys passed in."}, ) - requested_key_count: Final = len(data.keys or ()) + len(data.key_aliases or ()) - if requested_key_count > MAX_KEY_INFO_KEYS_PER_REQUEST: - raise HTTPException( - status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, - detail={ # mutable-ok: one-shot HTTPException payload matching the sibling detail dict above; never mutated after construction - "message": ( - f"Too many keys requested: {requested_key_count}. " - f"At most {MAX_KEY_INFO_KEYS_PER_REQUEST} keys and key_aliases combined per request." - ) - }, - ) - # Resolve key_aliases to tokens so we never pass token=None (unbounded query) tokens_to_query: Final = list(data.keys) if data.keys else [] if data.key_aliases: diff --git a/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py index a2f248ca55c..425365c8560 100644 --- a/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py +++ b/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py @@ -539,57 +539,6 @@ async def test_key_generation_with_object_permission(monkeypatch): assert key_insert_calls[0]["data"].get("object_permission_id") == "objperm123" -@pytest.mark.asyncio -async def test_generate_key_with_soft_budget_creates_budget_row(monkeypatch): - """soft_budget on /key/generate must create a budget table row and link its budget_id to the key.""" - mock_prisma_client = AsyncMock() - mock_prisma_client.jsonify_object = lambda data: data - mock_prisma_client.db = MagicMock() - mock_budget_create = AsyncMock(return_value=MagicMock(budget_id="budget-soft-123")) - mock_prisma_client.db.litellm_budgettable = MagicMock() - mock_prisma_client.db.litellm_budgettable.create = mock_budget_create - - async def _insert_data_side_effect(*args, **kwargs): - if kwargs.get("table_name") == "user": - return MagicMock(models=[], spend=0) - return MagicMock( - token="hashed_token_soft", - litellm_budget_table=None, - object_permission=None, - ) - - mock_prisma_client.insert_data = AsyncMock(side_effect=_insert_data_side_effect) - monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client) - - from litellm.proxy._types import GenerateKeyRequest, LitellmUserRoles - from litellm.proxy.auth.user_api_key_auth import UserAPIKeyAuth - from litellm.proxy.management_endpoints.key_management_endpoints import ( - generate_key_fn, - ) - - await generate_key_fn( - data=GenerateKeyRequest(soft_budget=5.0), - user_api_key_dict=UserAPIKeyAuth( - user_role=LitellmUserRoles.PROXY_ADMIN, - api_key="sk-1234", - user_id="admin-1", - ), - ) - - mock_budget_create.assert_awaited_once() - created_budget = mock_budget_create.call_args.kwargs["data"] - assert created_budget["soft_budget"] == 5.0 - assert created_budget["created_by"] == "admin-1" - - key_insert_calls = [ - call.kwargs - for call in mock_prisma_client.insert_data.call_args_list - if call.kwargs.get("table_name") == "key" - ] - assert len(key_insert_calls) == 1 - assert key_insert_calls[0]["data"].get("budget_id") == "budget-soft-123" - - @pytest.mark.asyncio async def test_generate_key_debug_log_never_contains_raw_token(monkeypatch, caplog): """Regression for LIT-4356: /key/generate must never emit the raw virtual key @@ -14267,6 +14216,7 @@ async def test_info_key_fn_budget_limits_includes_current_spend(monkeypatch): assert call_kwargs["max_budget"] == 2.0 assert call_kwargs["window_entity_type"] == "Key" assert call_kwargs["window_entity_id"] == test_key_token + assert call_kwargs["window_duration"] == "1h" assert call_kwargs["window_start"] is not None @@ -14397,39 +14347,9 @@ async def test_info_key_fn_v2_budget_limits_includes_current_spend(monkeypatch): f"spend:key:{test_key_token}:window:1h", f"spend:key:{test_key_token}:window:1d", } - - -@pytest.mark.asyncio -async def test_info_key_fn_v2_rejects_oversized_batch(monkeypatch): - """/v2/key/info must reject over-cap batches before doing any DB work.""" - from unittest.mock import AsyncMock - - from litellm.proxy._types import KeyRequest, ProxyException - from litellm.proxy.management_endpoints.key_management_endpoints import ( - MAX_KEY_INFO_KEYS_PER_REQUEST, - info_key_fn_v2, - ) - - mock_prisma_client = AsyncMock() - monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client) - monkeypatch.setattr("litellm.proxy.proxy_server.user_api_key_cache", AsyncMock()) - - user_api_key_dict = UserAPIKeyAuth( - user_role=LitellmUserRoles.PROXY_ADMIN, - api_key="sk-admin-batch-cap", - ) - - with pytest.raises(ProxyException) as exc_info: - await info_key_fn_v2( - data=KeyRequest( - keys=[f"hash-{i}" for i in range(MAX_KEY_INFO_KEYS_PER_REQUEST)], - key_aliases=["alias-over-cap"], - ), - user_api_key_dict=user_api_key_dict, - ) - - assert exc_info.value.code == "422" - mock_prisma_client.get_data.assert_not_awaited() + assert { + call.kwargs["window_duration"] for call in mock_get_current_spend.await_args_list + } == {"1h", "1d"} @pytest.mark.asyncio @@ -14452,7 +14372,7 @@ async def test_budget_limits_with_usage_json_string_input(monkeypatch): ) result = await _budget_limits_with_usage(budget_limits=raw, api_key_hash="hash-1") - assert result == [ + assert list(result) == [ { "budget_duration": "1h", "max_budget": 2.0, @@ -14464,8 +14384,8 @@ async def test_budget_limits_with_usage_json_string_input(monkeypatch): @pytest.mark.asyncio -async def test_budget_limits_with_usage_skips_unusable_inputs(monkeypatch): - """Invalid JSON strings, non-list values, and malformed windows are skipped.""" +async def test_budget_limits_with_usage_empty_windows_keep_stored_value(monkeypatch): + """A key with no windows (None, [], or "[]") returns None so /key/info keeps the stored value; no spend lookup runs.""" from unittest.mock import AsyncMock from litellm.proxy.management_endpoints.key_management_endpoints import ( @@ -14477,32 +14397,9 @@ async def test_budget_limits_with_usage_skips_unusable_inputs(monkeypatch): "litellm.proxy.proxy_server.get_current_spend", mock_get_current_spend ) - # invalid JSON string and non-list values return None: callers keep the original - assert await _budget_limits_with_usage(budget_limits="{not json", api_key_hash="hash-1") is None - assert await _budget_limits_with_usage(budget_limits={"budget_duration": "1h"}, api_key_hash="hash-1") is None - - # windows that are falsy, missing budget_duration, or not dict-like - windows = [ - {}, - {"max_budget": 2.0}, - {"budget_duration": "1h", "max_budget": "not-a-number"}, - 42, - ] - result = await _budget_limits_with_usage(budget_limits=windows, api_key_hash="hash-1") - - # only the well-formed window (with unparseable max_budget coerced to None) - # triggers a spend lookup - mock_get_current_spend.assert_awaited_once() - call_kwargs = mock_get_current_spend.await_args.kwargs - assert call_kwargs["counter_key"] == "spend:key:hash-1:window:1h" - assert call_kwargs["max_budget"] is None - assert result is not None - assert result[0] == {} - assert result[1] == {"max_budget": 2.0} - assert result[2] == {"budget_duration": "1h", "max_budget": "not-a-number", "current_spend": 0.0} - assert result[3] == 42 - # input is not mutated - assert windows[2] == {"budget_duration": "1h", "max_budget": "not-a-number"} + for stored in (None, [], "[]"): + assert await _budget_limits_with_usage(budget_limits=stored, api_key_hash="hash-1") is None + mock_get_current_spend.assert_not_awaited() @pytest.mark.asyncio @@ -14523,17 +14420,19 @@ async def test_budget_limits_with_usage_window_without_max_budget(monkeypatch): budget_limits=[{"budget_duration": "2d"}], api_key_hash="hash-no-max" ) - assert result == [{"budget_duration": "2d", "current_spend": 0.75}] + assert list(result) == [{"budget_duration": "2d", "current_spend": 0.75}] call_kwargs = mock_get_current_spend.await_args.kwargs assert call_kwargs["counter_key"] == "spend:key:hash-no-max:window:2d" + assert call_kwargs["window_duration"] == "2d" assert call_kwargs["max_budget"] is None @pytest.mark.asyncio async def test_budget_limits_with_usage_pydantic_windows(monkeypatch): - """Window objects with model_dump() are converted to dicts; failing windows pass through.""" - from unittest.mock import AsyncMock, MagicMock + """BudgetLimitEntry windows (the shape UserAPIKeyAuth carries) are dumped to dicts and annotated.""" + from unittest.mock import AsyncMock + from litellm.models.team import BudgetLimitEntry from litellm.proxy.management_endpoints.key_management_endpoints import ( _budget_limits_with_usage, ) @@ -14543,25 +14442,18 @@ async def test_budget_limits_with_usage_pydantic_windows(monkeypatch): "litellm.proxy.proxy_server.get_current_spend", mock_get_current_spend ) - good_window = MagicMock() - good_window.model_dump.return_value = { - "budget_duration": "7d", - "max_budget": 10.0, - "reset_at": None, - } - bad_window = MagicMock() - bad_window.model_dump.side_effect = ValueError("boom") - result = await _budget_limits_with_usage( - budget_limits=[good_window, bad_window], api_key_hash="hash-2" + budget_limits=[BudgetLimitEntry(budget_duration="7d", max_budget=10.0)], + api_key_hash="hash-2", ) - # good window converted to dict and annotated; failing window left as-is - assert result is not None - assert isinstance(result[0], dict) - assert result[0]["current_spend"] == 1.0 - assert result[1] is bad_window - mock_get_current_spend.assert_awaited_once() + assert list(result) == [ + {"budget_duration": "7d", "max_budget": 10.0, "reset_at": None, "current_spend": 1.0} + ] + call_kwargs = mock_get_current_spend.await_args.kwargs + assert call_kwargs["counter_key"] == "spend:key:hash-2:window:7d" + assert call_kwargs["window_duration"] == "7d" + assert call_kwargs["max_budget"] == 10.0 @pytest.mark.asyncio From 46d073b26f9b0037bb824384edf851155c9aecd6 Mon Sep 17 00:00:00 2001 From: ryan-crabbe-berri Date: Mon, 31 Aug 2026 20:48:42 -0700 Subject: [PATCH 11/12] refactor(key): report window spend under budget_limits_usage instead of inlining current_spend budget_limits now comes back exactly as stored on /key/info and /v2/key/info. The per-window usage moves to a sibling budget_limits_usage field keyed by budget_duration (current_spend, budget_limit, reset_at), mirroring model_max_budget_usage, so the stored shape that /key/update accepts never carries a computed field. --- .../key_management_endpoints.py | 52 +++++--- .../test_key_management_endpoints.py | 117 +++++++++--------- ui/litellm-dashboard/src/lib/http/schema.d.ts | 7 +- 3 files changed, 97 insertions(+), 79 deletions(-) diff --git a/litellm/proxy/management_endpoints/key_management_endpoints.py b/litellm/proxy/management_endpoints/key_management_endpoints.py index 02bfa5c0ca8..c43b6ddf06a 100644 --- a/litellm/proxy/management_endpoints/key_management_endpoints.py +++ b/litellm/proxy/management_endpoints/key_management_endpoints.py @@ -20,6 +20,7 @@ import secrets import traceback from collections.abc import Awaitable, Callable, Iterator, Mapping, Sequence from datetime import datetime, timedelta, timezone +from types import MappingProxyType from typing import TYPE_CHECKING, Any, Final, Literal, Optional, Protocol, TypeVar, cast import fastapi @@ -3590,9 +3591,12 @@ def _window_max_budget(window: Mapping[str, object]) -> float | None: return None -async def _budget_window_with_usage(window: Mapping[str, object], api_key_hash: str) -> Mapping[str, object]: +async def _budget_window_usage( + window: Mapping[str, object], api_key_hash: str +) -> tuple[str, Mapping[str, object]] | None: """ - Copy of a budget window with current-window spend attached. + (budget_duration, usage entry) for one budget window; None when the window + has no budget_duration to key it by. Reads the same cross-pod counter (spend:key:{hashed_token}:window:{budget_duration}) that _virtual_key_multi_budget_check enforces against, passing the same @@ -3603,34 +3607,41 @@ async def _budget_window_with_usage(window: Mapping[str, object], api_key_hash: duration: Final = window.get("budget_duration") if not isinstance(duration, str) or not duration: - return window + return None + max_budget: Final = _window_max_budget(window) spend: Final = await get_current_spend( counter_key=f"spend:key:{api_key_hash}:window:{duration}", fallback_spend=0.0, - max_budget=_window_max_budget(window), + max_budget=max_budget, window_entity_type="Key", window_entity_id=api_key_hash, window_duration=duration, window_start=get_budget_window_start(window), ) - return {**window, "current_spend": round(spend, 4)} # mutable-ok: per-window response copy, built once per window + return duration, MappingProxyType( + { + "current_spend": round(spend, 4), + "budget_limit": max_budget, + "reset_at": window.get("reset_at"), + } + ) -async def _budget_limits_with_usage( +async def _build_budget_limits_usage( budget_limits: Sequence[object] | str | None, api_key_hash: str -) -> tuple[Mapping[str, object], ...] | None: +) -> Mapping[str, Mapping[str, object]] | None: """ - budget_limits as window dicts with current-window spend attached; None when - the key has no windows so the caller keeps the stored value. + Current-window spend per budget window, keyed by budget_duration, reported + next to the stored budget_limits (which is returned untouched). None when + the key has no windows, so the field only appears on keys that have them. """ windows: Final = _budget_limit_windows(budget_limits) if not windows: return None - return tuple( - await asyncio.gather( - *(_budget_window_with_usage(window=window, api_key_hash=api_key_hash) for window in windows) - ) + usages: Final = await asyncio.gather( + *(_budget_window_usage(window=window, api_key_hash=api_key_hash) for window in windows) ) + return MappingProxyType({duration: usage for duration, usage in (u for u in usages if u is not None)}) @router.post( @@ -3717,12 +3728,12 @@ async def info_key_fn_v2( user_api_key_cache=model_max_budget_limiter.dual_cache, ) if k_token_hash: - budget_limits_usage = await _budget_limits_with_usage( + budget_limits_usage = await _build_budget_limits_usage( budget_limits=k_dict.get("budget_limits"), api_key_hash=k_token_hash, ) if budget_limits_usage is not None: - k_dict["budget_limits"] = budget_limits_usage + k_dict["budget_limits_usage"] = budget_limits_usage filtered_key_info.append(k_dict) return {"key": data.keys, "info": filtered_key_info} @@ -3759,9 +3770,10 @@ async def info_key_fn( - model_max_budget: dict - Per-model budgets, e.g. {"gpt-4": {"budget_limit": 0.0005, "time_period": "30d"}} - model_max_budget_usage: dict | None - Current-window spend per model, present only when the key has per-model budgets - - budget_limits: list | None - Concurrent budget windows. Each entry includes - current_spend: spend accumulated in the window so far (read from the same cross-pod - spend counter the budget enforcement uses) + - budget_limits: list | None - Concurrent budget windows, exactly as stored + - budget_limits_usage: dict | None - Current-window spend per budget window, keyed by + budget_duration, present only when the key has budget windows (read from the same + cross-pod spend counter the budget enforcement uses) - models: list - Model_name's the key is allowed to call - tpm_limit / rpm_limit: int | None - Tokens and requests per minute limits - metadata: dict - Metadata for the key, e.g. {"team": "core-infra"} @@ -3841,12 +3853,12 @@ async def info_key_fn( model_max_budget=model_max_budget, user_api_key_cache=model_max_budget_limiter.dual_cache, ) - budget_limits_usage: Final = await _budget_limits_with_usage( + budget_limits_usage: Final = await _build_budget_limits_usage( budget_limits=key_info.get("budget_limits"), api_key_hash=key_token_hash, ) if budget_limits_usage is not None: - key_info["budget_limits"] = budget_limits_usage + key_info["budget_limits_usage"] = budget_limits_usage # Attach object_permission if object_permission_id is set key_info = await attach_object_permission_to_dict(key_info, prisma_client) diff --git a/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py index 425365c8560..f6e57607717 100644 --- a/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py +++ b/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py @@ -14143,11 +14143,11 @@ async def test_info_key_fn_v2_budget_table_fallback(monkeypatch): @pytest.mark.asyncio -async def test_info_key_fn_budget_limits_includes_current_spend(monkeypatch): +async def test_info_key_fn_reports_budget_limits_usage(monkeypatch): """ - /key/info should attach current_spend to each budget_limits window, read from - the same spend counter (spend:key:{token}:window:{duration}) that budget - enforcement uses. + /key/info reports current-window spend per budget window under budget_limits_usage, + keyed by budget_duration and read from the same counter enforcement uses, while + budget_limits itself comes back exactly as stored. """ from unittest.mock import AsyncMock, MagicMock @@ -14204,11 +14204,14 @@ async def test_info_key_fn_budget_limits_includes_current_spend(monkeypatch): user_api_key_dict=user_api_key_dict, ) - windows = result["info"]["budget_limits"] - assert len(windows) == 1 - assert windows[0]["current_spend"] == 0.73 - assert windows[0]["max_budget"] == 2.0 - assert windows[0]["budget_duration"] == "1h" + assert result["info"]["budget_limits"] == budget_limits + assert result["info"]["budget_limits_usage"] == { + "1h": { + "current_spend": 0.73, + "budget_limit": 2.0, + "reset_at": "2026-08-15T18:00:00+00:00", + } + } mock_get_current_spend.assert_awaited_once() call_kwargs = mock_get_current_spend.await_args.kwargs @@ -14222,7 +14225,7 @@ async def test_info_key_fn_budget_limits_includes_current_spend(monkeypatch): @pytest.mark.asyncio async def test_info_key_fn_no_budget_limits_skips_spend_lookup(monkeypatch): - """Keys without budget_limits should not trigger window spend lookups.""" + """Keys without budget windows get no budget_limits_usage field and trigger no spend lookup.""" from unittest.mock import AsyncMock, MagicMock from litellm.proxy._types import LiteLLM_VerificationToken @@ -14272,12 +14275,13 @@ async def test_info_key_fn_no_budget_limits_skips_spend_lookup(monkeypatch): ) assert result["info"]["budget_limits"] is None + assert "budget_limits_usage" not in result["info"] mock_get_current_spend.assert_not_awaited() @pytest.mark.asyncio -async def test_info_key_fn_v2_budget_limits_includes_current_spend(monkeypatch): - """/v2/key/info should attach current_spend to each budget_limits window.""" +async def test_info_key_fn_v2_reports_budget_limits_usage(monkeypatch): + """/v2/key/info reports budget_limits_usage per window and leaves budget_limits as stored.""" from unittest.mock import AsyncMock, MagicMock from litellm.proxy._types import KeyRequest, LiteLLM_VerificationToken @@ -14286,6 +14290,18 @@ async def test_info_key_fn_v2_budget_limits_includes_current_spend(monkeypatch): ) test_key_token = "hashed_token_v2_window_test" + budget_limits = [ + { + "reset_at": "2026-08-15T18:00:00+00:00", + "max_budget": 2.0, + "budget_duration": "1h", + }, + { + "reset_at": "2026-08-16T00:00:00+00:00", + "max_budget": 20.0, + "budget_duration": "1d", + }, + ] mock_prisma_client = AsyncMock() monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client) @@ -14304,18 +14320,7 @@ async def test_info_key_fn_v2_budget_limits_includes_current_spend(monkeypatch): mock_key.team_id = None mock_key.model_dump.return_value = { "token": test_key_token, - "budget_limits": [ - { - "reset_at": "2026-08-15T18:00:00+00:00", - "max_budget": 2.0, - "budget_duration": "1h", - }, - { - "reset_at": "2026-08-16T00:00:00+00:00", - "max_budget": 20.0, - "budget_duration": "1d", - }, - ], + "budget_limits": [dict(w) for w in budget_limits], "user_id": "user-v2-w", "team_id": None, "litellm_budget_table": None, @@ -14335,10 +14340,19 @@ async def test_info_key_fn_v2_budget_limits_includes_current_spend(monkeypatch): ) assert len(result["info"]) == 1 - windows = result["info"][0]["budget_limits"] - assert len(windows) == 2 - assert windows[0]["current_spend"] == 1.25 - assert windows[1]["current_spend"] == 1.25 + assert result["info"][0]["budget_limits"] == budget_limits + assert result["info"][0]["budget_limits_usage"] == { + "1h": { + "current_spend": 1.25, + "budget_limit": 2.0, + "reset_at": "2026-08-15T18:00:00+00:00", + }, + "1d": { + "current_spend": 1.25, + "budget_limit": 20.0, + "reset_at": "2026-08-16T00:00:00+00:00", + }, + } assert mock_get_current_spend.await_count == 2 counter_keys = { call.kwargs["counter_key"] for call in mock_get_current_spend.await_args_list @@ -14353,13 +14367,13 @@ async def test_info_key_fn_v2_budget_limits_includes_current_spend(monkeypatch): @pytest.mark.asyncio -async def test_budget_limits_with_usage_json_string_input(monkeypatch): - """budget_limits stored as a JSON string should be parsed and annotated.""" +async def test_build_budget_limits_usage_json_string_input(monkeypatch): + """budget_limits stored as a JSON string is parsed and reported per window.""" import json as json_module from unittest.mock import AsyncMock from litellm.proxy.management_endpoints.key_management_endpoints import ( - _budget_limits_with_usage, + _build_budget_limits_usage, ) mock_get_current_spend = AsyncMock(return_value=0.5) @@ -14370,26 +14384,19 @@ async def test_budget_limits_with_usage_json_string_input(monkeypatch): raw = json_module.dumps( [{"budget_duration": "1h", "max_budget": 2.0, "reset_at": None}] ) - result = await _budget_limits_with_usage(budget_limits=raw, api_key_hash="hash-1") + result = await _build_budget_limits_usage(budget_limits=raw, api_key_hash="hash-1") - assert list(result) == [ - { - "budget_duration": "1h", - "max_budget": 2.0, - "reset_at": None, - "current_spend": 0.5, - } - ] + assert result == {"1h": {"current_spend": 0.5, "budget_limit": 2.0, "reset_at": None}} mock_get_current_spend.assert_awaited_once() @pytest.mark.asyncio -async def test_budget_limits_with_usage_empty_windows_keep_stored_value(monkeypatch): - """A key with no windows (None, [], or "[]") returns None so /key/info keeps the stored value; no spend lookup runs.""" +async def test_build_budget_limits_usage_empty_windows_returns_none(monkeypatch): + """A key with no windows (None, [], or "[]") returns None so the field is left off; no spend lookup runs.""" from unittest.mock import AsyncMock from litellm.proxy.management_endpoints.key_management_endpoints import ( - _budget_limits_with_usage, + _build_budget_limits_usage, ) mock_get_current_spend = AsyncMock(return_value=0.0) @@ -14398,17 +14405,17 @@ async def test_budget_limits_with_usage_empty_windows_keep_stored_value(monkeypa ) for stored in (None, [], "[]"): - assert await _budget_limits_with_usage(budget_limits=stored, api_key_hash="hash-1") is None + assert await _build_budget_limits_usage(budget_limits=stored, api_key_hash="hash-1") is None mock_get_current_spend.assert_not_awaited() @pytest.mark.asyncio -async def test_budget_limits_with_usage_window_without_max_budget(monkeypatch): - """A window with only budget_duration still gets current_spend, read without a budget ceiling.""" +async def test_build_budget_limits_usage_window_without_max_budget(monkeypatch): + """A window with only budget_duration still reports current_spend, read without a budget ceiling.""" from unittest.mock import AsyncMock from litellm.proxy.management_endpoints.key_management_endpoints import ( - _budget_limits_with_usage, + _build_budget_limits_usage, ) mock_get_current_spend = AsyncMock(return_value=0.75) @@ -14416,11 +14423,11 @@ async def test_budget_limits_with_usage_window_without_max_budget(monkeypatch): "litellm.proxy.proxy_server.get_current_spend", mock_get_current_spend ) - result = await _budget_limits_with_usage( + result = await _build_budget_limits_usage( budget_limits=[{"budget_duration": "2d"}], api_key_hash="hash-no-max" ) - assert list(result) == [{"budget_duration": "2d", "current_spend": 0.75}] + assert result == {"2d": {"current_spend": 0.75, "budget_limit": None, "reset_at": None}} call_kwargs = mock_get_current_spend.await_args.kwargs assert call_kwargs["counter_key"] == "spend:key:hash-no-max:window:2d" assert call_kwargs["window_duration"] == "2d" @@ -14428,13 +14435,13 @@ async def test_budget_limits_with_usage_window_without_max_budget(monkeypatch): @pytest.mark.asyncio -async def test_budget_limits_with_usage_pydantic_windows(monkeypatch): - """BudgetLimitEntry windows (the shape UserAPIKeyAuth carries) are dumped to dicts and annotated.""" +async def test_build_budget_limits_usage_pydantic_windows(monkeypatch): + """BudgetLimitEntry windows (the shape UserAPIKeyAuth carries) are dumped to dicts and reported.""" from unittest.mock import AsyncMock from litellm.models.team import BudgetLimitEntry from litellm.proxy.management_endpoints.key_management_endpoints import ( - _budget_limits_with_usage, + _build_budget_limits_usage, ) mock_get_current_spend = AsyncMock(return_value=1.0) @@ -14442,14 +14449,12 @@ async def test_budget_limits_with_usage_pydantic_windows(monkeypatch): "litellm.proxy.proxy_server.get_current_spend", mock_get_current_spend ) - result = await _budget_limits_with_usage( + result = await _build_budget_limits_usage( budget_limits=[BudgetLimitEntry(budget_duration="7d", max_budget=10.0)], api_key_hash="hash-2", ) - assert list(result) == [ - {"budget_duration": "7d", "max_budget": 10.0, "reset_at": None, "current_spend": 1.0} - ] + assert result == {"7d": {"current_spend": 1.0, "budget_limit": 10.0, "reset_at": None}} call_kwargs = mock_get_current_spend.await_args.kwargs assert call_kwargs["counter_key"] == "spend:key:hash-2:window:7d" assert call_kwargs["window_duration"] == "7d" diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.ts index 9b5adec516d..7b6f428c5a4 100644 --- a/ui/litellm-dashboard/src/lib/http/schema.d.ts +++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts @@ -7710,9 +7710,10 @@ export interface paths { * - model_max_budget: dict - Per-model budgets, e.g. {"gpt-4": {"budget_limit": 0.0005, "time_period": "30d"}} * - model_max_budget_usage: dict | None - Current-window spend per model, present only when * the key has per-model budgets - * - budget_limits: list | None - Concurrent budget windows. Each entry includes - * current_spend: spend accumulated in the window so far (read from the same cross-pod - * spend counter the budget enforcement uses) + * - budget_limits: list | None - Concurrent budget windows, exactly as stored + * - budget_limits_usage: dict | None - Current-window spend per budget window, keyed by + * budget_duration, present only when the key has budget windows (read from the same + * cross-pod spend counter the budget enforcement uses) * - models: list - Model_name's the key is allowed to call * - tpm_limit / rpm_limit: int | None - Tokens and requests per minute limits * - metadata: dict - Metadata for the key, e.g. {"team": "core-infra"} From 760b864e43045032bd76348650cf15f6e207b2a9 Mon Sep 17 00:00:00 2001 From: ryan-crabbe-berri Date: Mon, 31 Aug 2026 21:11:15 -0700 Subject: [PATCH 12/12] refactor(key): trim budget_limits_usage entries to current_spend max_budget and reset_at already live on the matching budget_limits entry, so repeating them (as budget_limit and reset_at) only invited confusion about which copy is authoritative. --- .../key_management_endpoints.py | 17 ++++-------- .../test_key_management_endpoints.py | 26 +++++-------------- ui/litellm-dashboard/src/lib/http/schema.d.ts | 6 ++--- 3 files changed, 14 insertions(+), 35 deletions(-) diff --git a/litellm/proxy/management_endpoints/key_management_endpoints.py b/litellm/proxy/management_endpoints/key_management_endpoints.py index c43b6ddf06a..99e201930c1 100644 --- a/litellm/proxy/management_endpoints/key_management_endpoints.py +++ b/litellm/proxy/management_endpoints/key_management_endpoints.py @@ -3608,23 +3608,16 @@ async def _budget_window_usage( duration: Final = window.get("budget_duration") if not isinstance(duration, str) or not duration: return None - max_budget: Final = _window_max_budget(window) spend: Final = await get_current_spend( counter_key=f"spend:key:{api_key_hash}:window:{duration}", fallback_spend=0.0, - max_budget=max_budget, + max_budget=_window_max_budget(window), window_entity_type="Key", window_entity_id=api_key_hash, window_duration=duration, window_start=get_budget_window_start(window), ) - return duration, MappingProxyType( - { - "current_spend": round(spend, 4), - "budget_limit": max_budget, - "reset_at": window.get("reset_at"), - } - ) + return duration, MappingProxyType({"current_spend": round(spend, 4)}) async def _build_budget_limits_usage( @@ -3771,9 +3764,9 @@ async def info_key_fn( - model_max_budget_usage: dict | None - Current-window spend per model, present only when the key has per-model budgets - budget_limits: list | None - Concurrent budget windows, exactly as stored - - budget_limits_usage: dict | None - Current-window spend per budget window, keyed by - budget_duration, present only when the key has budget windows (read from the same - cross-pod spend counter the budget enforcement uses) + - budget_limits_usage: dict | None - Current-window spend per budget window, e.g. + {"1h": {"current_spend": 0.0009}}, present only when the key has budget windows + (read from the same cross-pod spend counter the budget enforcement uses) - models: list - Model_name's the key is allowed to call - tpm_limit / rpm_limit: int | None - Tokens and requests per minute limits - metadata: dict - Metadata for the key, e.g. {"team": "core-infra"} diff --git a/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py index f6e57607717..b5a4204f0af 100644 --- a/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py +++ b/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py @@ -14205,13 +14205,7 @@ async def test_info_key_fn_reports_budget_limits_usage(monkeypatch): ) assert result["info"]["budget_limits"] == budget_limits - assert result["info"]["budget_limits_usage"] == { - "1h": { - "current_spend": 0.73, - "budget_limit": 2.0, - "reset_at": "2026-08-15T18:00:00+00:00", - } - } + assert result["info"]["budget_limits_usage"] == {"1h": {"current_spend": 0.73}} mock_get_current_spend.assert_awaited_once() call_kwargs = mock_get_current_spend.await_args.kwargs @@ -14342,16 +14336,8 @@ async def test_info_key_fn_v2_reports_budget_limits_usage(monkeypatch): assert len(result["info"]) == 1 assert result["info"][0]["budget_limits"] == budget_limits assert result["info"][0]["budget_limits_usage"] == { - "1h": { - "current_spend": 1.25, - "budget_limit": 2.0, - "reset_at": "2026-08-15T18:00:00+00:00", - }, - "1d": { - "current_spend": 1.25, - "budget_limit": 20.0, - "reset_at": "2026-08-16T00:00:00+00:00", - }, + "1h": {"current_spend": 1.25}, + "1d": {"current_spend": 1.25}, } assert mock_get_current_spend.await_count == 2 counter_keys = { @@ -14386,7 +14372,7 @@ async def test_build_budget_limits_usage_json_string_input(monkeypatch): ) result = await _build_budget_limits_usage(budget_limits=raw, api_key_hash="hash-1") - assert result == {"1h": {"current_spend": 0.5, "budget_limit": 2.0, "reset_at": None}} + assert result == {"1h": {"current_spend": 0.5}} mock_get_current_spend.assert_awaited_once() @@ -14427,7 +14413,7 @@ async def test_build_budget_limits_usage_window_without_max_budget(monkeypatch): budget_limits=[{"budget_duration": "2d"}], api_key_hash="hash-no-max" ) - assert result == {"2d": {"current_spend": 0.75, "budget_limit": None, "reset_at": None}} + assert result == {"2d": {"current_spend": 0.75}} call_kwargs = mock_get_current_spend.await_args.kwargs assert call_kwargs["counter_key"] == "spend:key:hash-no-max:window:2d" assert call_kwargs["window_duration"] == "2d" @@ -14454,7 +14440,7 @@ async def test_build_budget_limits_usage_pydantic_windows(monkeypatch): api_key_hash="hash-2", ) - assert result == {"7d": {"current_spend": 1.0, "budget_limit": 10.0, "reset_at": None}} + assert result == {"7d": {"current_spend": 1.0}} call_kwargs = mock_get_current_spend.await_args.kwargs assert call_kwargs["counter_key"] == "spend:key:hash-2:window:7d" assert call_kwargs["window_duration"] == "7d" diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.ts index 7b6f428c5a4..77e42c09525 100644 --- a/ui/litellm-dashboard/src/lib/http/schema.d.ts +++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts @@ -7711,9 +7711,9 @@ export interface paths { * - model_max_budget_usage: dict | None - Current-window spend per model, present only when * the key has per-model budgets * - budget_limits: list | None - Concurrent budget windows, exactly as stored - * - budget_limits_usage: dict | None - Current-window spend per budget window, keyed by - * budget_duration, present only when the key has budget windows (read from the same - * cross-pod spend counter the budget enforcement uses) + * - budget_limits_usage: dict | None - Current-window spend per budget window, e.g. + * {"1h": {"current_spend": 0.0009}}, present only when the key has budget windows + * (read from the same cross-pod spend counter the budget enforcement uses) * - models: list - Model_name's the key is allowed to call * - tpm_limit / rpm_limit: int | None - Tokens and requests per minute limits * - metadata: dict - Metadata for the key, e.g. {"team": "core-infra"}