litellm/tests/unit/router_utils/test_ptu_shares.py
devin-ai-integration[bot] e344dbd8db
feat(proxy): split Azure PTU deployments across teams with per-team PTU ceilings and PTU-hour reporting (#43043)
* feat(proxy): split Azure PTU deployments across teams by share

A PTU deployment's model_info takes ptu_shares (team_id -> whole PTUs adding up to
ptu_count) in place of a single team_id. With LITELLM_ENABLE_PTU_COST_ATTRIBUTION on,
routing hides the deployment from teams holding no share, the v3 limiter enforces each
share as a per-team TPM ceiling from Azure's per-model TPM-per-PTU sizing, the daily
flat-cost rollup splits the hourly cost by share, and /team/daily/activity plus the Team
Usage page report PTU-hours next to tokens.

* fix(proxy): weight cached input in PTU ceilings and size team-scoped deployments by public name

The PTU flag is read from the process environment on every check instead of
through the secret-manager path, so a proxy with a hosted secret manager does
not pay a round trip per request. A team's ceiling now carries the model's
cached-input ratio and settlement charges cache reads at that ratio, matching
how Azure sizes a PTU. A deployment registered for one team is found by its
team_public_model_name for PTU-hours and the ceiling, since its model_name is
rewritten to a unique internal name. ptu_shares are StrictInt on ModelInfo and
parsed_ptu_shares refuses booleans, strings, and non-string team ids, a
fractional ptu_count reserves nothing, and models_processed counts distinct
deployments rather than holdings.

* fix(proxy): reserve PTU ceilings in normalized tokens, keep share routing flag-independent, and warn only shared or Azure reservations

* fix(proxy): size the uncapped output floor against the PTU share in raw output tokens and escape the exported team id

* fix(ptu): refuse ptu_shares naming a team that does not exist

* refactor(ptu): keep Azure detection under llms/azure and check share teams with one query

* fix(proxy): drop the reverted TeamIdSearchFilter import after merging main

Main reverted the team key search change that added TeamIdSearchFilter, so the PTU share team check types its where clause locally

* fix(proxy): chunk the ptu_shares team lookup under the IN-list bound

* fix(proxy): count a request naming a shared PTU deployment directly against its group's ceiling

* fix(proxy): resolve every name a shared PTU deployment is served under to its group's ceiling

* fix(ptu): refuse ptu_shares declared without ptu_count and cost_per_ptu_per_hour

* fix(ui): seed total_ptu_hours in the empty daily activity metadata

* fix(ptu): size usage rows by the name the request used

* fix(ptu): size a team's usage rows by the deployment it is served from

* fix(ptu): never size a team's usage row by another team's reservation

* fix(ptu): reserve an uncapped request against the cap the proxy writes, not its prompt length

* fix(ptu): read a share map only through the terms registration requires

A ptu_shares map stored without ptu_count, cost_per_ptu_per_hour and
ptu_effective_from, or one that does not add up to ptu_count, is refused at
registration but was enforced once loaded: every other team got the 400 and
the share holder a ceiling while no flat cost accrued. _deployment_shares now
reads the shares through ptu_terms, so such a row reserves nothing, the same
as before the map was read.

* fix(ptu): keep a declared split as the access rule and check a config split at boot with the flag off

6fb24d1d read ptu_shares through the pricing terms so a termless map reserved
nothing, but with the flag off the router skips ptu_config_error for config.yaml
entries, so such an entry loaded and served every team, against the rule that a
declared split restricts access whether or not cost attribution is on.
_deployment_shares reads the declared map again, and the router now raises
ptu_config_error for a config-sourced entry declaring ptu_shares regardless of
the flag, so a malformed split is refused at boot instead of being honoured or
ignored silently.

* fix(ptu): charge wildcard-served names, pass-through usage, and team-less settlements against the team's PTU ceiling

A name served by a wildcard route now resolves to the shared deployment behind it, so the
limiter's ceiling and the team daily activity sizing both find it. Pass-through responses
settle the PTU counter from combined_usage_object in Azure-normalized tokens, and a
reservation taken at admission is settled even when the success metadata lost the team.

* fix(ptu): resolve a wildcard-served name to the one pattern the router picks, and a deployment id before any wildcard

A team's wildcard reservation behind an open proxy-wide * route was charged and sized for traffic the * route served, and naming a shared deployment by id next to a catch-all wildcard escaped its per-team ceiling. Router.wildcard_route_deployments now owns the most-specific-proxy-wide-else-team precedence, and both the limiter and the consumption page resolve through it after listed rows and deployment ids.

* test(router): pin the wildcard route precedence that PTU sizing and the router share

* fix(proxy): accept whole-number PTU shares written as floats, as ptu_count already does

A share of 2.0 now reads as 2 on POST /model/new and in config.yaml, where it was
refused with a 422 and dropped at load. Fractional, infinite, boolean and string
shares stay refused. Adds unit tests for the malformed-rate, provider-over-prefix,
zero-token Responses usage, fractional-count and sizing-warning paths.

* fix(proxy): settle team PTU reservations in their own minute and keep billed PTU days when shares move

* fix(proxy): write each PTU deployment day's team charges in one transaction

The backfill counts a deployment day as priced once any team's row exists for it,
so a rollup that wrote team A's share and lost team C's left team C unbilled for
good. Each deployment day's team rows now go through one Prisma batch with the
retry around the whole batch, so a day is fully written or not written at all and
the next backfill prices it for every team.

* fix(proxy): read the PTU flag from a secret manager, serve share holders from their share, and refuse unfittable calls and share-holding team deletes

* test(router): list the cached PTU ceiling helpers in the router coverage check

* fix(proxy): read the PTU flag only for share holders, guard org and SCIM team deletes, keep share holders on their shared deployment through retries and the scheduler, and date PTU-hours by the terms in force

* fix(proxy): bill a rerun PTU day to the current share holders alone

* fix(proxy): replace a PTU day's rows by day and deployment, not a negated team list

* fix(proxy): read the PTU flag from the secret manager first, like get_secret

* fix(router): scope retry health lookups to the caller only for PTU share holders

* fix(router): move the share-holder retry check into ptu_shares

Adds ptu_hours and total_ptu_hours to the daily activity integration goldens and fixtures, since every route now reports them

* test(integration): cover PTU shares across routing, delete guards, cost attribution and config regex timing

---------

Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com>
2026-10-15 18:44:30 +00:00

301 lines
14 KiB
Python

"""Tests for per-team PTU shares: who a shared deployment is served to and what a share is worth."""
from datetime import date
from typing import Final
import pytest
from litellm.llms.azure.ptu_capacity import AZURE_PTU_CAPACITY
from litellm.router_utils.ptu_shares import (
filter_ptu_shared_deployments,
model_group_deployments,
model_group_ptu_capacity,
ptu_capacity_warning,
ptu_share_teams,
PTUTeamCeiling,
share_holder_request_kwargs,
team_ptu_ceiling,
team_servable_deployments,
)
_GPT41: Final = AZURE_PTU_CAPACITY["gpt-4.1"]
_GPT4O: Final = AZURE_PTU_CAPACITY["gpt-4o"]
_GPT6SOL: Final = AZURE_PTU_CAPACITY["gpt-6-sol"]
_SHARES: Final = {"team-a": 30, "team-b": 20}
def _shared(
model: str = "azure/gpt-4.1", shares: object = _SHARES, deployment_id: str = "shared", ptu_count: int | None = None
) -> dict:
return {
"model_name": "gpt-4.1-ptu",
"litellm_params": {"model": model},
"model_info": {
"id": deployment_id,
"ptu_count": ptu_count or (sum(shares.values()) if isinstance(shares, dict) else 50),
"cost_per_ptu_per_hour": 1.0,
"ptu_effective_from": "2026-01-01T00:00:00Z",
"ptu_shares": shares,
},
}
def _single_team(model: str = "azure/gpt-4.1") -> dict:
return {
"model_name": "gpt-4.1-ptu",
"litellm_params": {"model": model},
"model_info": {
"id": "single",
"team_id": "team-a",
"ptu_count": 50,
"cost_per_ptu_per_hour": 1.0,
"ptu_effective_from": "2026-01-01T00:00:00Z",
},
}
_OPEN: Final = {"model_name": "gpt-4.1-ptu", "litellm_params": {"model": "azure/gpt-4.1"}, "model_info": {"id": "open"}}
def _no_wildcard_route(_: str) -> tuple[()]:
return ()
def _unaliased_ceiling(deployments: list[dict], team_id: str, requested_model: str) -> PTUTeamCeiling | None:
return team_ptu_ceiling(deployments, deployments, team_id, requested_model, _no_wildcard_route)
def test_a_team_holding_a_share_is_served_from_its_share_alone():
"""An open deployment beside the shared one would put the team's pay-as-you-go traffic
under its PTU ceiling and into its PTU-hours, so only the teams holding no share get it."""
result: Final = filter_ptu_shared_deployments([_shared(), _OPEN], "team-a")
assert [d["model_info"]["id"] for d in result.deployments] == ["shared"]
def test_a_team_without_a_share_only_sees_the_unshared_deployments():
result: Final = filter_ptu_shared_deployments([_shared(), _OPEN], "team-c")
assert [d["model_info"]["id"] for d in result.deployments] == ["open"]
assert result.withheld is True
def test_a_caller_with_no_team_holds_no_share():
for team_id in (None, ""):
result = filter_ptu_shared_deployments([_shared()], team_id)
assert result.deployments == ()
assert result.withheld is True
def test_a_single_team_deployment_and_a_malformed_share_map_are_not_filtered_here():
"""A ``team_id`` deployment is scoped by the router's team filter, and an unusable
``ptu_shares`` is refused at registration, so neither is withheld by the share filter."""
result: Final = filter_ptu_shared_deployments([_single_team(), _shared(shares={"team-a": 0})], "team-z")
assert [d["model_info"]["id"] for d in result.deployments] == ["single", "shared"]
assert result.withheld is False
def test_only_a_share_holders_request_keeps_its_team_for_the_retry_lookup():
"""A team owning a deployment through ``team_id`` keeps the router's unscoped retry lookup."""
share_teams: Final = ptu_share_teams([_shared(shares={"team-b": 50}), _single_team()])
holder: Final = {"metadata": {"user_api_key_team_id": "team-b"}}
messages_holder: Final = {"litellm_metadata": {"user_api_key_team_id": "team-b"}}
assert share_holder_request_kwargs(holder, share_teams) is holder
assert share_holder_request_kwargs(messages_holder, share_teams) is messages_holder
assert share_holder_request_kwargs({"metadata": {"user_api_key_team_id": "team-a"}}, share_teams) is None
assert share_holder_request_kwargs({"metadata": {}}, share_teams) is None
_TERMLESS_SHARED: Final = {
"model_name": "gpt-4.1-ptu",
"litellm_params": {"model": "azure/gpt-4.1"},
"model_info": {"id": "shared", "ptu_shares": _SHARES},
}
def test_a_declared_split_is_the_access_rule_even_without_pricing_terms():
"""A map that reached the router without the count, rate and start registration now demands
still names who the deployment is for, so it is served to those teams alone and sized from
their shares; only the flat cost, which needs the terms, goes unattributed."""
assert filter_ptu_shared_deployments([_TERMLESS_SHARED], "team-z").withheld is True
assert filter_ptu_shared_deployments([_TERMLESS_SHARED], "team-a").withheld is False
ceiling: Final = _unaliased_ceiling([_TERMLESS_SHARED], "team-a", "gpt-4.1-ptu")
assert ceiling is not None
assert ceiling.tpm_limit == 30 * _GPT41.input_tpm_per_ptu
@pytest.mark.parametrize("team_id", ["team-a", "team-b"])
def test_a_team_holding_a_share_is_served_from_it_and_nothing_else_in_the_group(team_id: str):
servable: Final = team_servable_deployments([_single_team(), _OPEN, _shared()], team_id)
assert [d["model_info"]["id"] for d in servable] == ["shared"]
def test_a_team_holding_no_share_gets_the_open_deployment_and_never_another_teams_reservation():
servable: Final = team_servable_deployments([_single_team(), _OPEN, _shared()], "team-c")
assert [d["model_info"]["id"] for d in servable] == ["open"]
def test_a_share_converts_to_the_models_input_tpm_per_ptu():
ceiling: Final = _unaliased_ceiling([_shared()], "team-a", "gpt-4.1-ptu")
assert ceiling == PTUTeamCeiling(
model_group="gpt-4.1-ptu",
tpm_limit=30 * _GPT41.input_tpm_per_ptu,
output_to_input_ratio=_GPT41.output_to_input_ratio,
cached_input_ratio=_GPT41.cached_input_ratio,
)
def test_shares_across_deployments_add_up_and_the_larger_output_ratio_wins():
gpt4o: Final = _shared(model="azure/gpt-4o", shares={"team-a": 10}, deployment_id="shared-4o")
ceiling: Final = _unaliased_ceiling([_shared(), gpt4o, _OPEN], "team-a", "gpt-4.1-ptu")
assert ceiling is not None
assert ceiling.tpm_limit == 30 * _GPT41.input_tpm_per_ptu + 10 * _GPT4O.input_tpm_per_ptu
assert ceiling.output_to_input_ratio == max(_GPT41.output_to_input_ratio, _GPT4O.output_to_input_ratio)
def test_the_larger_cached_input_ratio_wins_across_deployments():
"""A team sharing two models is weighted by the one that charges more for cache reads,
whichever order the deployments come in."""
gpt6sol: Final = _shared(model="azure/gpt-6-sol", shares={"team-a": 10}, deployment_id="shared-6")
ceiling: Final = _unaliased_ceiling([_shared(), gpt6sol], "team-a", "gpt-4.1-ptu")
assert ceiling is not None
assert _GPT41.cached_input_ratio < _GPT6SOL.cached_input_ratio
assert ceiling.cached_input_ratio == _GPT6SOL.cached_input_ratio
def test_a_group_is_served_by_name_or_by_a_team_scoped_deployments_public_name():
"""A deployment registered for one team is renamed to a unique internal name and keeps
the name callers use in ``team_public_model_name``."""
team_scoped: Final = {
"model_name": "gpt-4.1-ptu-3f9c1b",
"litellm_params": {"model": "azure/gpt-4.1"},
"model_info": {"id": "team-scoped", "team_id": "team-a", "team_public_model_name": "gpt-4.1-ptu"},
}
other: Final = {"model_name": "other", "litellm_params": {"model": "azure/gpt-4o"}, "model_info": {"id": "other"}}
deployments: Final = [team_scoped, _OPEN, other]
served: Final = model_group_deployments(deployments, "gpt-4.1-ptu")
assert [d["model_info"]["id"] for d in served] == ["team-scoped", "open"]
assert model_group_deployments(deployments, "gpt-4.1-ptu-3f9c1b") == (team_scoped,)
assert model_group_deployments(deployments, "missing") == ()
def test_no_share_or_no_sizing_row_sets_no_ceiling():
assert _unaliased_ceiling([_shared()], "team-c", "gpt-4.1-ptu") is None
assert _unaliased_ceiling([_shared(model="azure/unknown-deployment")], "team-a", "gpt-4.1-ptu") is None
assert _unaliased_ceiling([_single_team(), _OPEN], "team-a", "gpt-4.1-ptu") is None
def test_naming_a_shared_deployment_by_id_or_provider_model_draws_on_its_groups_ceiling():
"""The router serves a deployment id or a provider model string when no group has that
name, so those names share the group's ceiling instead of bypassing it."""
payg: Final = {"model_name": "gpt-4.1-payg", "litellm_params": {"model": "azure/gpt-4.1"}, "model_info": {"id": "payg"}}
deployments: Final = [payg, _shared(), _OPEN]
by_group: Final = _unaliased_ceiling(deployments, "team-a", "gpt-4.1-ptu")
assert by_group is not None
assert by_group.model_group == "gpt-4.1-ptu"
assert _unaliased_ceiling(deployments, "team-a", "shared") == by_group
assert _unaliased_ceiling(deployments, "team-a", "azure/gpt-4.1") == by_group
assert _unaliased_ceiling(deployments, "team-a", "payg") is None
assert _unaliased_ceiling(deployments, "team-a", "missing") is None
def test_a_group_name_wins_over_a_deployment_id_it_collides_with():
"""The router routes a name that is both a group and a deployment id to the group."""
colliding: Final = {
"model_name": "shared",
"litellm_params": {"model": "azure/gpt-4o"},
"model_info": {"id": "colliding"},
}
assert _unaliased_ceiling([_shared(), colliding], "team-a", "shared") is None
def test_a_team_scoped_deployment_named_by_id_draws_on_its_public_groups_ceiling():
team_scoped: Final = {
"model_name": "gpt-4.1-ptu-3f9c1b",
"litellm_params": {"model": "azure/gpt-4.1"},
"model_info": {**_shared()["model_info"], "id": "team-scoped", "team_public_model_name": "gpt-4.1-ptu"},
}
ceiling: Final = _unaliased_ceiling([team_scoped], "team-a", "team-scoped")
assert ceiling is not None
assert ceiling.model_group == "gpt-4.1-ptu"
assert ceiling == _unaliased_ceiling([team_scoped], "team-a", "gpt-4.1-ptu")
def test_alias_and_routing_group_copies_do_not_split_a_deployments_ceiling():
"""The router lists alias and routing-group copies of a deployment under their own names
ahead of its own rows, so every name still resolves to the deployment's group."""
shared: Final = _shared()
listed: Final = [{**shared, "model_name": "ptu-alias"}, {**shared, "model_name": "ptu-routing-group"}, shared]
by_group: Final = team_ptu_ceiling(listed, [shared], "team-a", "gpt-4.1-ptu", _no_wildcard_route)
assert by_group is not None
assert by_group.model_group == "gpt-4.1-ptu"
for name in ("shared", "azure/gpt-4.1", "ptu-routing-group"):
assert team_ptu_ceiling(listed, [shared], "team-a", name, _no_wildcard_route) == by_group
def test_a_provider_model_draws_on_the_group_where_the_team_holds_its_share():
"""Two groups share deployments of one provider model among different teams, and the router
serves each team only the one it holds a share of."""
east: Final = _shared(shares={"team-a": 30}, deployment_id="east")
west: Final = {**_shared(shares={"team-b": 20}, deployment_id="west"), "model_name": "gpt-4.1-ptu-west"}
by_provider_model: Final = _unaliased_ceiling([east, west], "team-b", "azure/gpt-4.1")
assert by_provider_model is not None
assert by_provider_model.model_group == "gpt-4.1-ptu-west"
assert by_provider_model == _unaliased_ceiling([east, west], "team-b", "gpt-4.1-ptu-west")
assert _unaliased_ceiling([east, west], "team-a", "azure/gpt-4.1") == _unaliased_ceiling(
[east, west], "team-a", "gpt-4.1-ptu"
)
def test_a_groups_capacity_comes_from_its_first_reserved_deployment_with_a_row():
day: Final = date(2026, 9, 23)
assert model_group_ptu_capacity([_OPEN, _single_team()], day) is _GPT41
assert model_group_ptu_capacity([_shared(model="azure/unknown"), _shared(model="azure/gpt-4o")], day) is _GPT4O
assert model_group_ptu_capacity([_OPEN], day) is None
assert model_group_ptu_capacity([], day) is None
def test_a_groups_capacity_on_a_day_comes_from_the_reservation_covering_that_day():
ended: Final = {**_shared(), "model_info": {**_shared()["model_info"], "ptu_effective_to": "2026-06-01T00:00:00Z"}}
current: Final = {
**_shared(model="azure/gpt-4o", deployment_id="current"),
"model_info": {**_shared(deployment_id="current")["model_info"], "ptu_effective_from": "2026-06-01T00:00:00Z"},
}
assert model_group_ptu_capacity([ended, current], date(2026, 5, 31)) is _GPT41
assert model_group_ptu_capacity([ended, current], date(2026, 6, 1)) is _GPT4O
assert model_group_ptu_capacity([ended], date(2026, 6, 1)) is None
assert model_group_ptu_capacity([current], date(2025, 12, 31)) is None
def test_a_reserved_deployment_without_a_sizing_row_is_warned_about_by_name():
warning: Final = ptu_capacity_warning("gpt-4.1-ptu", _shared(model="azure/my-ptu-deployment"))
assert warning is not None
assert "gpt-4.1-ptu" in warning
assert "base_model" in warning
def test_a_sized_reservation_and_an_unreserved_deployment_raise_no_warning():
assert ptu_capacity_warning("gpt-4.1-ptu", _shared()) is None
assert ptu_capacity_warning("gpt-4.1-ptu", _single_team()) is None
unsized_open: Final = {**_OPEN, "litellm_params": {"model": "azure/my-ptu-deployment"}}
assert ptu_capacity_warning("gpt-4.1-ptu", unsized_open) is None
def test_an_unsized_single_team_azure_reservation_is_warned_about_its_ptu_hours_only():
warning: Final = ptu_capacity_warning("gpt-4.1-ptu", _single_team(model="azure/my-ptu-deployment"))
assert warning is not None
assert "PTU hours" in warning
assert "ceiling" not in warning
def test_an_unsized_single_team_reservation_on_another_provider_is_not_warned_about():
assert ptu_capacity_warning("claude-ptu", _single_team(model="anthropic/claude-sonnet-4-5")) is None
def test_a_bare_model_name_counts_as_azure_through_custom_llm_provider():
deployment: Final = {
**_single_team(model="my-ptu-deployment"),
"litellm_params": {"model": "my-ptu-deployment", "custom_llm_provider": "azure"},
}
warning: Final = ptu_capacity_warning("gpt-4.1-ptu", deployment)
assert warning is not None
assert "PTU hours" in warning