Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

fix(ptu): refuse an incomplete config.yaml reservation the way the endpoints do (#37703)

yucheng-berriabdde94ad5e0
diff --git a/litellm/litellm_core_utils/ptu_pricing.py b/litellm/litellm_core_utils/ptu_pricing.py
index a1f8bb36e27..6923e6beb96 100644
--- a/litellm/litellm_core_utils/ptu_pricing.py
+++ b/litellm/litellm_core_utils/ptu_pricing.py
@@ -79,6 +79,45 @@ def _as_utc(value: object) -> datetime | None:
return None
+def _named(reason: str, model_name: str | None) -> str:
+ """The reason on its own for a caller that already has the deployment in hand, else named."""
+ return reason if model_name is None else f"PTU configuration on model '{model_name}' is invalid: {reason}"
+
+
+def ptu_config_error(model_info: Mapping[str, object], *, model_name: str | None = None) -> str | None:
+ """Why this PTU configuration cannot be honoured, else None.
+
+ Both the model endpoints and config.yaml registration ask this, so a deployment that
+ one refuses is refused by the other for the same stated reason.
+
+ Window ordering is checked before the count/rate gate. A patch that touches only one end
+ of the window carries no count or rate, so leaving the order to that gate would let an
+ inverted window reach the row; the next load then fails to parse it and drops the
+ deployment out of the router, where no further patch can repair it.
+ """
+ effective_from: Final = _as_utc(model_info.get("ptu_effective_from"))
+ effective_to: Final = _as_utc(model_info.get("ptu_effective_to"))
+ if effective_from is not None and effective_to is not None and effective_to <= effective_from:
+ return _named("ptu_effective_to must be after ptu_effective_from", model_name)
+
+ has_count: Final = model_info.get("ptu_count") is not None
+ has_rate: Final = model_info.get("cost_per_ptu_per_hour") is not None
+ if not has_count and not has_rate:
+ return None
+ if has_count != has_rate:
+ return _named("ptu_count and cost_per_ptu_per_hour must be set together", model_name)
+ if effective_from is None:
+ return _named(
+ "ptu_effective_from is required when PTU fields are set. Flat cost accrues from that "
+ "instant, so without it the start would have to be inferred and a deployment configured "
+ "today could be billed for days it did not exist",
+ model_name,
+ )
+ if not model_info.get("team_id"):
+ return _named("team_id is required when PTU fields are set (one model maps to one team)", model_name)
+ return None
+
+
def ptu_terms(model_info: Mapping[str, object]) -> PTUTerms | None:
"""The reservation this deployment accrues flat cost for, else None.
diff --git a/litellm/proxy/management_endpoints/model_management_endpoints.py b/litellm/proxy/management_endpoints/model_management_endpoints.py
index 1b49e2455e4..ec98d7d65f1 100644
--- a/litellm/proxy/management_endpoints/model_management_endpoints.py
+++ b/litellm/proxy/management_endpoints/model_management_endpoints.py
@@ -30,6 +30,7 @@ from litellm.litellm_core_utils.ptu_pricing import (
PTU_ZEROED_PRICING_FIELDS,
PTU_ZEROED_TABLE_FIELDS,
SEARCH_CONTEXT_SIZES,
+ ptu_config_error,
)
from litellm.proxy._types import (
BlockModelRequest,
@@ -308,42 +309,13 @@ def _raise_if_ptu_cost_attribution_disabled(incoming_model_info: Mapping[str, ob
def _validate_ptu_model_info(model_info: Mapping[str, object]) -> None:
"""Enforce the PTU cross-field invariant on the effective model_info.
- ptu_count and cost_per_ptu_per_hour must be set together, and a team_id and a
- ptu_effective_from are required when they are. The start is mandatory rather than
- defaulted because flat cost accrues from it: inferring one would let a deployment
- configured today be billed for days it did not exist. Per-field bounds (positive
- count, non-negative rate) are enforced by ModelInfo itself.
-
- Window ordering is checked before the count/rate gate. A patch that touches only one
- end of the window carries no count or rate, and ModelInfo sees one field at a time, so
- leaving it to either would let an inverted window reach the row; the next load then
- fails to parse it and drops the deployment out of the router, where no further patch
- can repair it because each one re-parses the stored value first.
+ The rules live in litellm_core_utils.ptu_pricing so that config.yaml registration
+ refuses the same deployments this endpoint does, for the same reason. Per-field bounds
+ (positive count, non-negative rate) are enforced by ModelInfo itself.
"""
- effective_from: Final = _coerce_ptu_datetime(model_info.get("ptu_effective_from"))
- effective_to: Final = _coerce_ptu_datetime(model_info.get("ptu_effective_to"))
- if effective_from is not None and effective_to is not None and effective_to <= effective_from:
- raise HTTPException(status_code=400, detail="ptu_effective_to must be after ptu_effective_from")
-
- has_count: Final = model_info.get("ptu_count") is not None
- has_rate: Final = model_info.get("cost_per_ptu_per_hour") is not None
- if not has_count and not has_rate:
- return
- if has_count != has_rate:
- raise HTTPException(status_code=400, detail="ptu_count and cost_per_ptu_per_hour must be set together")
- if effective_from is None:
- raise HTTPException(
- status_code=400,
- detail=(
- "ptu_effective_from is required when PTU fields are set. Flat cost accrues from that "
- "instant, so without it the start would have to be inferred and a deployment configured "
- "today could be billed for days it did not exist"
- ),
- )
- if not model_info.get("team_id"):
- raise HTTPException(
- status_code=400, detail="team_id is required when PTU fields are set (one model maps to one team)"
- )
+ error: Final = ptu_config_error(model_info)
+ if error is not None:
+ raise HTTPException(status_code=400, detail=error)
# The mirrored per-token pricing fields plus the three remaining fields
@@ -515,28 +487,6 @@ def _ptu_priced_deployment(model_params: Deployment) -> Deployment:
)
-def _parse_ptu_datetime(value: object) -> datetime.datetime | None:
- """``value`` as a datetime, parsing an ISO string, else None."""
- if isinstance(value, datetime.datetime):
- return value
- if not isinstance(value, str):
- return None
- try:
- return datetime.datetime.fromisoformat(value.replace("Z", "+00:00"))
- except ValueError:
- return None
-
-
-def _coerce_ptu_datetime(value: object) -> datetime.datetime | None:
- """Coerce a model_info effective-window value (datetime or ISO string) to UTC, else None."""
- parsed: Final = _parse_ptu_datetime(value)
- if parsed is None:
- return None
- if parsed.tzinfo is None:
- return parsed.replace(tzinfo=datetime.timezone.utc)
- return parsed.astimezone(datetime.timezone.utc)
-
-
def update_db_model(db_model: Deployment, updated_patch: updateDeployment) -> PrismaCompatibleUpdateDBModel:
if updated_patch.model_info is not None:
_raise_if_ptu_cost_attribution_disabled(updated_patch.model_info.model_dump(exclude_none=True))
diff --git a/litellm/router.py b/litellm/router.py
index e4e3a857411..b5bba45f1e6 100644
--- a/litellm/router.py
+++ b/litellm/router.py
@@ -64,7 +64,11 @@ from litellm.litellm_core_utils.coroutine_checker import coroutine_checker
from litellm.litellm_core_utils.credential_accessor import CredentialAccessor
from litellm.litellm_core_utils.dd_tracing import tracer
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLogging
-from litellm.litellm_core_utils.ptu_pricing import zeroed_ptu_pricing
+from litellm.litellm_core_utils.ptu_pricing import (
+ is_ptu_cost_attribution_enabled,
+ ptu_config_error,
+ zeroed_ptu_pricing,
+)
from litellm.litellm_core_utils.request_timeout_resolver import (
get_configured_request_timeout,
)
@@ -7701,9 +7705,11 @@ class Router:
- None: If the deployment is not active for the current environment (if 'supported_environments' is set in litellm_params)
"""
try:
- zeroed_pricing: Final = (
- zeroed_ptu_pricing(_model_info, _litellm_params) if _model_info.get("db_model") is not True else None
- )
+ config_sourced: Final = _model_info.get("db_model") is not True
+ ptu_error: Final = ptu_config_error(_model_info, model_name=_model_name) if config_sourced else None
+ if ptu_error is not None and is_ptu_cost_attribution_enabled():
+ raise ValueError(ptu_error)
+ zeroed_pricing: Final = zeroed_ptu_pricing(_model_info, _litellm_params) if config_sourced else None
litellm_params: Final[LiteLLM_Params] = LiteLLM_Params(
**(
_litellm_params
diff --git a/tests/test_litellm/litellm_core_utils/test_ptu_pricing.py b/tests/test_litellm/litellm_core_utils/test_ptu_pricing.py
index 270c59f595f..b953bfaa565 100644
--- a/tests/test_litellm/litellm_core_utils/test_ptu_pricing.py
+++ b/tests/test_litellm/litellm_core_utils/test_ptu_pricing.py
@@ -7,6 +7,7 @@ from unittest.mock import patch
import pytest
from litellm.litellm_core_utils.ptu_pricing import (
+ ptu_config_error,
CUSTOM_PRICING_FIELDS,
PTU_EMPTIED_PRICING_FIELDS,
PTU_ZEROED_PRICING_FIELDS,
@@ -161,3 +162,50 @@ def test_a_setting_that_is_not_a_charge_is_left_alone():
assert override is not None
assert "output_vector_size" not in override
+
+
+# --- the rule both the endpoints and config.yaml registration enforce ---------------
+
+
+def test_a_complete_reservation_has_no_error():
+ assert ptu_config_error(_VALID) is None
+
+
+def test_a_deployment_with_no_ptu_fields_is_not_a_ptu_deployment():
+ """The gate must stay scoped to PTU configuration, or it would reject every ordinary
+ deployment for lacking a team_id."""
+ assert ptu_config_error({"team_id": "team-alpha"}) is None
+ assert ptu_config_error({}) is None
+
+
+ "override, expected",
+ [
+ ({"team_id": None}, "team_id is required when PTU fields are set (one model maps to one team)"),
+ ({"team_id": ""}, "team_id is required when PTU fields are set (one model maps to one team)"),
+ ({"cost_per_ptu_per_hour": None}, "ptu_count and cost_per_ptu_per_hour must be set together"),
+ ({"ptu_count": None}, "ptu_count and cost_per_ptu_per_hour must be set together"),
+ ({"ptu_effective_to": "2025-01-01T00:00:00Z"}, "ptu_effective_to must be after ptu_effective_from"),
+ ],
+ ids=["no team", "blank team", "count without rate", "rate without count", "inverted window"],
+)
+def test_an_incoherent_reservation_names_its_reason(override, expected):
+ assert ptu_config_error({**_VALID, **override}) == expected
+
+
+def test_a_missing_start_is_explained_rather_than_inferred():
+ error = ptu_config_error({k: v for k, v in _VALID.items() if k != "ptu_effective_from"})
+
+ assert error is not None
+ assert error.startswith("ptu_effective_from is required when PTU fields are set")
+
+
+def test_an_inverted_window_is_caught_before_the_count_and_rate_gate():
+ """A patch that moves one end of the window carries no count or rate, so ordering has to
+ be checked first or an inverted window reaches the row and the next load cannot parse it."""
+ window_only = {
+ "ptu_effective_from": "2026-01-01T00:00:00Z",
+ "ptu_effective_to": "2025-01-01T00:00:00Z",
+ }
+
+ assert ptu_config_error(window_only) == "ptu_effective_to must be after ptu_effective_from"
diff --git a/tests/test_litellm/test_router_model_cost_isolation.py b/tests/test_litellm/test_router_model_cost_isolation.py
index 4674a8b1dfa..e3c2cc988c7 100644
--- a/tests/test_litellm/test_router_model_cost_isolation.py
+++ b/tests/test_litellm/test_router_model_cost_isolation.py
@@ -20,6 +20,7 @@ sys.path.insert(
import litellm
from litellm import Router
+from litellm.litellm_core_utils.ptu_pricing import ptu_config_error
from litellm.types.router import Deployment, LiteLLM_Params, ModelInfo
from litellm.utils import (
_invalidate_model_cost_lowercase_map,
@@ -1689,11 +1690,77 @@ def test_nothing_is_zeroed_while_the_feature_is_off():
@pytest.mark.parametrize("dropped", ["team_id", "ptu_effective_from"], ids=["no team_id", "no ptu_effective_from"])
-def test_a_deployment_the_rollup_will_not_charge_is_not_zeroed(dropped):
- """The rollup refuses to price a reservation missing either field, so zeroing on the
- looser count-and-rate test alone would leave the deployment serving for free with
- nothing charged in its place."""
+def test_an_incomplete_reservation_is_refused_rather_than_served(dropped):
+ """POST /model/new answers 400 for exactly this config, so config.yaml must not quietly
+ accept it. Serving it would bill per token while accruing no flat cost, which is the
+ state the operator was trying to leave."""
incomplete = {k: v for k, v in _PTU_MODEL_INFO.items() if k != dropped}
- entry = _ptu_router(model_info=incomplete, litellm_params={"input_cost_per_token": 5e-06}).model_list[0]
+
+ with pytest.raises(ValueError) as raised:
+ _ptu_router(model_info=incomplete, litellm_params={"input_cost_per_token": 5e-06})
+
+ assert "gpt-4o-ptu" in str(raised.value)
+
+
+ "dropped, expected",
+ [
+ ("team_id", "team_id is required when PTU fields are set (one model maps to one team)"),
+ ("cost_per_ptu_per_hour", "ptu_count and cost_per_ptu_per_hour must be set together"),
+ ],
+ ids=["no team_id", "count without rate"],
+)
+def test_the_refusal_reason_is_the_one_the_model_endpoint_answers_with(dropped, expected):
+ """One rule, stated once. If these drift, an operator gets contradictory guidance
+ depending on which path they used."""
+ incomplete = {k: v for k, v in _PTU_MODEL_INFO.items() if k != dropped}
+
+ assert ptu_config_error(incomplete) == expected
+ with pytest.raises(ValueError) as raised:
+ _ptu_router(model_info=incomplete)
+
+ assert expected in str(raised.value)
+
+
[email protected]("dropped", ["team_id", "ptu_effective_from"], ids=["no team_id", "no ptu_effective_from"])
+def test_an_incomplete_reservation_is_left_alone_while_the_feature_is_off(dropped):
+ """Nothing accrues with the flag off, so refusing a deployment there would take a
+ serving model away from an operator who never opted in."""
+ incomplete = {k: v for k, v in _PTU_MODEL_INFO.items() if k != dropped}
+ entry = _ptu_router(
+ model_info=incomplete, litellm_params={"input_cost_per_token": 5e-06}, ptu_enabled=False
+ ).model_list[0]
assert entry["litellm_params"]["input_cost_per_token"] == 5e-06
+
+
[email protected]("dropped", ["team_id", "ptu_effective_from"], ids=["no team_id", "no ptu_effective_from"])
+def test_the_proxy_drops_the_deployment_rather_than_failing_to_boot(dropped):
+ """The proxy builds its router with ignore_invalid_deployments, so one bad entry must
+ cost that entry and not the whole config."""
+ incomplete = {k: v for k, v in _PTU_MODEL_INFO.items() if k != dropped}
+ with patch.dict(os.environ, {"LITELLM_ENABLE_PTU_COST_ATTRIBUTION": "True"}, clear=False):
+ router = Router(
+ model_list=[
+ {
+ "model_name": "gpt-4o-ptu",
+ "litellm_params": {"model": "anthropic/claude-sonnet-4-5-20250929", "api_key": "sk-not-used"},
+ "model_info": dict(incomplete),
+ },
+ {
+ "model_name": "plain-sibling",
+ "litellm_params": {"model": "anthropic/claude-sonnet-4-5-20250929", "api_key": "sk-not-used"},
+ },
+ ],
+ ignore_invalid_deployments=True,
+ )
+
+ assert [entry["model_name"] for entry in router.model_list] == ["plain-sibling"]
+
+
+def test_a_complete_reservation_still_registers():
+ """The refusal must be scoped to a broken reservation, not to PTU configuration."""
+ entry = _ptu_router().model_list[0]
+
+ assert entry["model_name"] == "gpt-4o-ptu"
+ assert entry["litellm_params"]["input_cost_per_token"] == 0.0