The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(proxy): bound budget reservation per request instead of pinning to remaining headroom
Yuneng Jiangadc41ade8c0e
diff --git a/litellm/proxy/spend_tracking/budget_reservation.py b/litellm/proxy/spend_tracking/budget_reservation.pyindex 1d296611bfc..feae368d23f 100644--- a/litellm/proxy/spend_tracking/budget_reservation.py+++ b/litellm/proxy/spend_tracking/budget_reservation.py@@ -95,11 +95,9 @@ async def reserve_budget_for_request(route=route,llm_router=llm_router,)- if reservation_cost is None:- reservation_cost = await _get_smallest_remaining_budget(- counters=counters,- current_spend_by_counter_key=current_spend_by_counter_key,- )+ # estimate_request_max_cost still returns None when the model is unknown+ # to the cost map (no token-priced cost fields, e.g. image/audio routes).+ # In that case we fall back to read-time enforcement only.if reservation_cost is None or reservation_cost <= 0:return None@@ -553,32 +551,6 @@ def _coerce_window(window: Any) -> dict:return {}-async def _get_smallest_remaining_budget(- counters: List[_BudgetCounter],- current_spend_by_counter_key: Dict[str, float],-) -> Optional[float]:- remaining_budget: Optional[float] = None- for counter in counters:- current_spend = await _get_current_counter_value(counter=counter)- current_spend_by_counter_key[counter.counter_key] = current_spend- remaining = counter.max_budget - current_spend- if remaining <= 0:- raise litellm.BudgetExceededError(- current_cost=current_spend,- max_budget=counter.max_budget,- message=(- "Budget has been exceeded! "- f"{counter.entity_type}={counter.entity_id} "- f"Current cost: {current_spend}, "- f"Max budget: {counter.max_budget}"- ),- )- remaining_budget = (- remaining if remaining_budget is None else min(remaining_budget, remaining)- )- return remaining_budget--async def _reserve_counter(counter: _BudgetCounter,reservation_cost: float,@@ -946,6 +918,9 @@ def _estimate_input_tokens(return None+DEFAULT_MAX_OUTPUT_TOKENS_FALLBACK = 16384++def _estimate_output_tokens(request_body: dict,route: str,@@ -954,15 +929,27 @@ def _estimate_output_tokens(if _is_input_only_route(route=route):return 0+ requested: Optional[int] = Nonefor key in ("max_completion_tokens", "max_tokens", "max_output_tokens"):- max_tokens = _to_int(request_body.get(key))- if max_tokens is not None:- return max_tokens-- # If the caller did not cap output tokens, avoid reserving a model's- # theoretical maximum context. The caller can still admit one request by- # reserving the smallest remaining budget in reserve_budget_for_request().- return None+ requested = _to_int(request_body.get(key))+ if requested is not None:+ break++ # Clamp at min(requested-or-default, model_max-or-default). Two purposes:+ # (1) Without an explicit cap we still need a finite reservation so the+ # atomic admission counter actually bounds concurrent in-flight cost+ # (mirrors parallel_request_limiter_v3's DEFAULT_MAX_TOKENS_ESTIMATE).+ # (2) An adversarial caller cannot send max_tokens=999999999 to inflate+ # the reservation up to remaining team headroom and pin the counter+ # at the cap — the model can only physically emit max_output_tokens+ # anyway, so reserving more is both wasteful and a DoS surface.+ model_ceiling = (+ _to_int(model_info.get("max_output_tokens"))+ or DEFAULT_MAX_OUTPUT_TOKENS_FALLBACK+ )+ if requested is None:+ requested = DEFAULT_MAX_OUTPUT_TOKENS_FALLBACK+ return min(requested, model_ceiling)def _count_text_tokens(model: str, text: Any) -> int:diff --git a/tests/test_litellm/proxy/test_budget_reservation.py b/tests/test_litellm/proxy/test_budget_reservation.pyindex 070b232066a..0e2ca98a113 100644--- a/tests/test_litellm/proxy/test_budget_reservation.py+++ b/tests/test_litellm/proxy/test_budget_reservation.py@@ -585,15 +585,24 @@ async def test_should_cap_known_estimate_to_remaining_budget(@pytest.mark.asyncio-async def test_should_reserve_remaining_budget_when_output_cap_missing(+async def test_should_clamp_reservation_to_default_when_output_cap_missing(spend_counter_state,):+ """When max_tokens is not specified, _estimate_output_tokens falls back to+ DEFAULT_MAX_OUTPUT_TOKENS_FALLBACK (16K), clamped by the model's+ max_output_tokens. Reservation must be a bounded per-request amount+ (mirroring parallel_request_limiter_v3's DEFAULT_MAX_TOKENS_ESTIMATE),+ not the entire remaining headroom."""+ from litellm.proxy.spend_tracking.budget_reservation import (+ DEFAULT_MAX_OUTPUT_TOKENS_FALLBACK,+ )+counter_cache, key_cache = spend_counter_stateproxy_logging_obj = ProxyLogging(user_api_key_cache=key_cache)valid_token = UserAPIKeyAuth(token="key-budget-uncapped",spend=0.2,- max_budget=1.0,+ max_budget=10000.0,)await key_cache.async_set_cache(key="key-budget-uncapped",@@ -602,77 +611,24 @@ async def test_should_reserve_remaining_budget_when_output_cap_missing(request_body = _request_body()request_body.pop("max_tokens")+ output_cost_per_token = 1e-5 # roughly Opus 4.5/4.7 output rate+ expected_cost = DEFAULT_MAX_OUTPUT_TOKENS_FALLBACK * output_cost_per_token+with patch("litellm.proxy.spend_tracking.budget_reservation._get_model_cost_info",return_value={"input_cost_per_token": 0.0,- "output_cost_per_token": 100.0,- "max_output_tokens": 200000,+ "output_cost_per_token": output_cost_per_token,+ "max_output_tokens": 200000, # well above the 16K fallback},):- assert (- estimate_request_max_cost(- request_body=request_body,- route="/chat/completions",- llm_router=None,- )- is None- )- reservation = await reserve_budget_for_request(+ estimated = estimate_request_max_cost(request_body=request_body,route="/chat/completions",llm_router=None,- valid_token=valid_token,- team_object=None,- user_object=None,- prisma_client=None,- user_api_key_cache=key_cache,- proxy_logging_obj=proxy_logging_obj,- )-- assert reservation is not None- assert reservation["reserved_cost"] == pytest.approx(0.8)- assert counter_cache.in_memory_cache.get_cache(- key="spend:key:key-budget-uncapped"- ) == pytest.approx(1.0)-- await release_budget_reservation(reservation)---async def test_should_shrink_uncapped_reservation_when_counter_advances(- spend_counter_state,- monkeypatch,-):- counter_cache, key_cache = spend_counter_state- proxy_logging_obj = ProxyLogging(user_api_key_cache=key_cache)- valid_token = UserAPIKeyAuth(- token="key-budget-uncapped-race",- spend=0.2,- max_budget=1.0,- )- request_body = _request_body()- request_body.pop("max_tokens")-- from litellm.proxy.spend_tracking import budget_reservation-- async def stale_counter_read(counter):- await counter_cache.async_increment_cache(- key=counter.counter_key,- value=0.3,)- return 0.2+ assert estimated == pytest.approx(expected_cost)- monkeypatch.setattr(- budget_reservation,- "_get_current_counter_value",- stale_counter_read,- )-- with patch(- "litellm.proxy.spend_tracking.budget_reservation.estimate_request_max_cost",- return_value=None,- ):reservation = await reserve_budget_for_request(request_body=request_body,route="/chat/completions",@@ -686,69 +642,52 @@ async def test_should_shrink_uncapped_reservation_when_counter_advances()assert reservation is not None- assert reservation["reserved_cost"] == pytest.approx(0.7)- assert counter_cache.in_memory_cache.get_cache(- key="spend:key:key-budget-uncapped-race"- ) == pytest.approx(1.0)-+ assert reservation["reserved_cost"] == pytest.approx(expected_cost)await release_budget_reservation(reservation)- assert counter_cache.in_memory_cache.get_cache(- key="spend:key:key-budget-uncapped-race"- ) == pytest.approx(0.3)-@pytest.mark.asyncio-async def test_should_shrink_uncapped_reservation_multiple_times(+async def test_should_clamp_reservation_to_model_ceiling_when_caller_overrequests(spend_counter_state,- monkeypatch,):+ """An adversarial caller sending max_tokens=999_999_999 must not be able+ to inflate the per-request reservation up to the entire remaining team+ headroom. _estimate_output_tokens clamps the explicit value at the+ model's max_output_tokens — the model can only physically emit that+ many tokens anyway, so anything more is both wasteful and a DoS surface."""counter_cache, key_cache = spend_counter_stateproxy_logging_obj = ProxyLogging(user_api_key_cache=key_cache)valid_token = UserAPIKeyAuth(- token="key-budget-double-resize",- spend=0.2,- max_budget=1.0,- team_id="team-budget-double-resize",+ token="key-budget-overrequest",+ spend=0.0,+ max_budget=10000.0,)- team_object = LiteLLM_TeamTable(- team_id="team-budget-double-resize",- spend=0.2,- max_budget=1.0,+ await key_cache.async_set_cache(+ key="key-budget-overrequest",+ value=valid_token,)- request_body = _request_body()- request_body.pop("max_tokens")-- from litellm.proxy.spend_tracking import budget_reservation-- stale_spend_by_counter_key = {- "spend:key:key-budget-double-resize": 0.3,- "spend:team:team-budget-double-resize": 0.4,- }- async def stale_counter_read(counter):- await counter_cache.async_increment_cache(- key=counter.counter_key,- value=stale_spend_by_counter_key[counter.counter_key],- )- return 0.2+ request_body = _request_body()+ request_body["max_tokens"] = 999_999_999- monkeypatch.setattr(- budget_reservation,- "_get_current_counter_value",- stale_counter_read,- )+ output_cost_per_token = 1e-5+ model_ceiling = 128_000+ expected_cost = model_ceiling * output_cost_per_tokenwith patch(- "litellm.proxy.spend_tracking.budget_reservation.estimate_request_max_cost",- return_value=None,+ "litellm.proxy.spend_tracking.budget_reservation._get_model_cost_info",+ return_value={+ "input_cost_per_token": 0.0,+ "output_cost_per_token": output_cost_per_token,+ "max_output_tokens": model_ceiling,+ },):reservation = await reserve_budget_for_request(request_body=request_body,route="/chat/completions",llm_router=None,valid_token=valid_token,- team_object=team_object,+ team_object=None,user_object=None,prisma_client=None,user_api_key_cache=key_cache,@@ -756,31 +695,9 @@ async def test_should_shrink_uncapped_reservation_multiple_times()assert reservation is not None- assert reservation["reserved_cost"] == pytest.approx(0.6)- assert [entry["reserved_cost"] for entry in reservation["entries"]] == [- pytest.approx(0.6),- pytest.approx(0.6),- ]- assert [entry["applied_adjustment"] for entry in reservation["entries"]] == [- pytest.approx(0.0),- pytest.approx(0.0),- ]- assert counter_cache.in_memory_cache.get_cache(- key="spend:key:key-budget-double-resize"- ) == pytest.approx(0.9)- assert counter_cache.in_memory_cache.get_cache(- key="spend:team:team-budget-double-resize"- ) == pytest.approx(1.0)-+ assert reservation["reserved_cost"] == pytest.approx(expected_cost)await release_budget_reservation(reservation)- assert counter_cache.in_memory_cache.get_cache(- key="spend:key:key-budget-double-resize"- ) == pytest.approx(0.3)- assert counter_cache.in_memory_cache.get_cache(- key="spend:team:team-budget-double-resize"- ) == pytest.approx(0.4)-def test_should_start_window_without_reset_at_at_duration_boundary():before = datetime.now(timezone.utc) - timedelta(hours=1)@@ -1047,62 +964,6 @@ async def test_should_release_tracked_entry_when_reservation_fails_after_increme) == pytest.approx(0.0)-async def test_should_not_re_read_uncapped_budget_after_reservation_fallback(- spend_counter_state,- monkeypatch,-):- _, key_cache = spend_counter_state- proxy_logging_obj = ProxyLogging(user_api_key_cache=key_cache)- valid_token = UserAPIKeyAuth(- token="key-budget-uncapped-read-once",- spend=0.2,- max_budget=1.0,- )-- from litellm.proxy.spend_tracking import budget_reservation-- current_counter_reads = []-- async def mock_get_current_counter_value(counter):- current_counter_reads.append(counter.counter_key)- return counter.fallback_spend-- async def mock_reserve_counter(counter, reservation_cost):- return None-- monkeypatch.setattr(- budget_reservation,- "_get_current_counter_value",- mock_get_current_counter_value,- )- monkeypatch.setattr(- budget_reservation,- "_reserve_counter",- mock_reserve_counter,- )-- with patch(- "litellm.proxy.spend_tracking.budget_reservation.estimate_request_max_cost",- return_value=None,- ):- reservation = await reserve_budget_for_request(- request_body=_request_body(),- route="/chat/completions",- llm_router=None,- valid_token=valid_token,- team_object=None,- user_object=None,- prisma_client=None,- user_api_key_cache=key_cache,- proxy_logging_obj=proxy_logging_obj,- )-- assert reservation is not None- assert reservation["reserved_cost"] == pytest.approx(0.8)- assert current_counter_reads == ["spend:key:key-budget-uncapped-read-once"]--@pytest.mark.asyncioasync def test_should_reconcile_reserved_counter_to_actual_spend(spend_counter_state,@@ -1492,4 +1353,94 @@ async def test_should_reserve_all_budgeted_counters(spend_counter_state):counter_cache.in_memory_cache.get_cache(key="spend:team:team-budget-all") == 0.3)- await release_budget_reservation(reservation)++async def test_should_not_block_concurrent_team_request_when_first_request_lacks_max_tokens(+ spend_counter_state,+):+ """+ Regression test: a team-bound request with no max_tokens must not pin the+ team's spend counter at max_budget for the duration of the request.++ Repro of the integration-test team being falsely budget-blocked at the+ $2000 cap while DB spend is $0.144: the first request without max_tokens+ used to reserve the entire remaining headroom, leaving any subsequent+ request stuck behind a counter sitting at the cap until the success+ callback finished reconciling.+ """+ counter_cache, key_cache = spend_counter_state+ proxy_logging_obj = ProxyLogging(user_api_key_cache=key_cache)++ valid_token = UserAPIKeyAuth(+ token="key-team-integration-tests",+ spend=0.0,+ team_id="team-integration-tests",+ )+ team_object = LiteLLM_TeamTable(+ team_id="team-integration-tests",+ max_budget=2000.0,+ spend=0.144,+ )+ await key_cache.async_set_cache(+ key=f"team_id:{team_object.team_id}",+ value=team_object,+ )++ request_body = _request_body()+ request_body.pop("max_tokens")++ # Realistic Opus 4.7 output pricing — the 16K fallback × $25/M ≈ $0.40+ # reservation per request, leaving ~5000 admittable concurrent requests+ # against a $2000 team budget.+ with patch(+ "litellm.proxy.spend_tracking.budget_reservation._get_model_cost_info",+ return_value={+ "input_cost_per_token": 5e-6,+ "output_cost_per_token": 2.5e-5,+ "max_output_tokens": 128000,+ },+ ):+ first_reservation = await reserve_budget_for_request(+ request_body=request_body,+ route="/chat/completions",+ llm_router=None,+ valid_token=valid_token,+ team_object=team_object,+ user_object=None,+ prisma_client=None,+ user_api_key_cache=key_cache,+ proxy_logging_obj=proxy_logging_obj,+ )++ # The team counter must not be pinned at max_budget while the first+ # request is in flight, otherwise concurrent requests false-positive.+ team_counter_after_first = (+ counter_cache.in_memory_cache.get_cache(+ key=f"spend:team:{team_object.team_id}"+ )+ or 0.0+ )+ assert team_counter_after_first < team_object.max_budget, (+ f"Team counter sat at {team_counter_after_first} after one uncapped "+ f"reservation against a {team_object.max_budget} budget — concurrent "+ "requests will be falsely blocked."+ )++ # Second request — same shape — must succeed without raising.+ second_reservation = await reserve_budget_for_request(+ request_body=request_body,+ route="/chat/completions",+ llm_router=None,+ valid_token=valid_token,+ team_object=team_object,+ user_object=None,+ prisma_client=None,+ user_api_key_cache=key_cache,+ proxy_logging_obj=proxy_logging_obj,+ )+ assert second_reservation is not None++ if first_reservation is not None:+ await release_budget_reservation(first_reservation)+ if second_reservation is not None:+ await release_budget_reservation(second_reservation)