litellm/tests/unit/proxy/management_endpoints/test_subscription_accounts.py
devin-ai-integration[bot] b8283d8b61
feat(usage): show subscription-covered providers and account fees separately (#44772)
* feat(usage): show subscription-covered providers and account fees separately

* fix(usage): write only the named fee columns and sync the root schema

The fee update now writes just the columns the request names, so two admins changing
different fields at once both land, and the dashboard edit form sends only what changed.
The root schema.prisma carries the new table like the two copies, and a billing period
anchored in the calendar's last month ends on December 31, 9999 instead of failing.

* fix(usage): register the subscription table span and keep provider logic under llms

* fix(subscription_accounts): register the fee routes as management routes and reject an empty account id

* fix(usage): run the new tests in CI and close subscription card review gaps

Adds the subscription test file to its unit shard, sets the migration lock timeout, rejects infinite fees, keeps the card from rewriting login files, lists each deployment once without aliases, shows the provider badge on entity views, and asks before removing a fee

* fix(usage): resolve named-credential ChatGPT accounts and keep admin viewers read-only on the fee card

* fix(usage): count a subscription fee only for accounts behind a current deployment

Usage listed a fee row for an account no deployment uses while another ChatGPT
deployment existed and dropped it when none did. It now lists only accounts behind a
current deployment in both cases. Adds a real proxy and Postgres integration test for
the fee API and for ChatGPT Responses rows on a deployment's own login, and names the
card's multi-component test with the integration suffix.

* fix(usage): keep a stored subscription fee listed after its account's deployments are removed

The usage route lists every account behind a subscription deployment plus every account carrying a stored fee, and reads the fees on every proxy, so a fee stays visible, counted, and editable for past ranges after its last deployment goes. The integration test now polls every day the calls spanned, so a UTC midnight crossing no longer fails it.

---------

Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com>
2026-10-30 03:58:36 -07:00

438 lines
17 KiB
Python

from collections.abc import Iterator
from datetime import datetime, timezone
from typing import Final
from uuid import uuid4
from unittest.mock import MagicMock
import pytest
from fastapi import FastAPI, HTTPException, Request
from fastapi.testclient import TestClient
from pydantic import ValidationError
from litellm.models.subscription_account import LiteLLM_SubscriptionAccountTable
from litellm.proxy._types import LiteLLM_JWTAuth, LitellmUserRoles, UserAPIKeyAuth
from litellm.proxy.auth.auth_checks import allowed_routes_check
from litellm.proxy.auth.route_checks import RouteChecks
from litellm.proxy.auth.user_api_key_auth import user_api_key_auth
from litellm.proxy.management_endpoints.subscription_accounts import (
SubscriptionDeployment,
get_subscription_account_repository,
get_subscription_deployments,
router,
subscription_deployments_from_model_list,
subscription_deployments_of_router,
)
from litellm.router import Router
from litellm.types.proxy.management_endpoints.subscription_accounts import (
SubscriptionAccountFeeRequest,
UpdateSubscriptionAccountFeeRequest,
)
from litellm.repositories.subscription_account_repository import (
DuplicateSubscriptionAccount,
SubscriptionAccountFeeChanges,
SubscriptionAccountFeeFields,
)
_ACCOUNT: Final = "org-team-workspace"
_TEST_FEE: Final = {
"custom_llm_provider": "chatgpt",
"account_id": _ACCOUNT,
"monthly_fee": 25.0,
"currency": "USD",
"billing_period_start": "2026-10-01",
"label": "Team plan (test value)",
}
_TWO_DEPLOYMENTS_ONE_ACCOUNT: Final = (
SubscriptionDeployment(model_name="gpt-5.6-terra", custom_llm_provider="chatgpt", account_id=_ACCOUNT),
SubscriptionDeployment(model_name="gpt-5.6-sol", custom_llm_provider="chatgpt", account_id=_ACCOUNT),
)
class _FakeStore:
def __init__(self) -> None:
self.rows: dict[str, LiteLLM_SubscriptionAccountTable] = {}
self.written_columns: list[dict[str, float | str | None]] = []
async def list_all(self) -> list[LiteLLM_SubscriptionAccountTable]:
return sorted(self.rows.values(), key=lambda row: row.created_at)
async def find_by_id(self, id_value: str) -> LiteLLM_SubscriptionAccountTable | None:
return self.rows.get(id_value)
async def create_account(
self, custom_llm_provider: str, account_id: str, fee: SubscriptionAccountFeeFields, created_by: str
) -> LiteLLM_SubscriptionAccountTable | DuplicateSubscriptionAccount:
for row in self.rows.values():
if (row.custom_llm_provider, row.account_id) == (custom_llm_provider, account_id):
return DuplicateSubscriptionAccount(custom_llm_provider=custom_llm_provider, account_id=account_id)
now = datetime.now(timezone.utc)
row = LiteLLM_SubscriptionAccountTable(
subscription_account_id=str(uuid4()),
custom_llm_provider=custom_llm_provider,
account_id=account_id,
label=fee.label,
monthly_fee=fee.monthly_fee,
currency=fee.currency,
billing_period_start=fee.billing_period_start,
created_at=now,
created_by=created_by,
updated_at=now,
updated_by=created_by,
)
self.rows[row.subscription_account_id] = row
return row
async def update_fee(
self, subscription_account_id: str, changes: SubscriptionAccountFeeChanges, updated_by: str
) -> LiteLLM_SubscriptionAccountTable | None:
columns = dict(changes.columns())
self.written_columns.append(columns)
existing = self.rows.get(subscription_account_id)
if existing is None:
return None
updated = existing.model_copy(
update={**columns, "updated_by": updated_by, "updated_at": datetime.now(timezone.utc)}
)
self.rows[subscription_account_id] = updated
return updated
async def delete_account(self, subscription_account_id: str) -> LiteLLM_SubscriptionAccountTable | None:
return self.rows.pop(subscription_account_id, None)
def _resolve_auth(request: Request) -> UserAPIKeyAuth:
role: Final = LitellmUserRoles(request.headers.get("x-user-role", LitellmUserRoles.PROXY_ADMIN.value))
return UserAPIKeyAuth(user_id="admin", user_role=role, api_key="sk-test")
@pytest.fixture
def deployments() -> tuple[SubscriptionDeployment, ...]:
return _TWO_DEPLOYMENTS_ONE_ACCOUNT
@pytest.fixture
def client(deployments: tuple[SubscriptionDeployment, ...]) -> Iterator[tuple[TestClient, _FakeStore]]:
store: Final = _FakeStore()
app: Final = FastAPI()
app.include_router(router)
app.dependency_overrides[get_subscription_account_repository] = lambda: store
app.dependency_overrides[get_subscription_deployments] = lambda: deployments
app.dependency_overrides[user_api_key_auth] = _resolve_auth
with TestClient(app) as test_client:
yield test_client, store
def _usage(test_client: TestClient, start_date: str, end_date: str, **headers: str) -> dict:
response = test_client.get(
"/subscription_accounts/usage", params={"start_date": start_date, "end_date": end_date}, headers=headers
)
assert response.status_code == 200, response.text
return response.json()
def test_untracked_account_lists_its_deployments_with_no_fee(client):
test_client, _ = client
body = _usage(test_client, "2026-10-01", "2026-10-07")
assert body["subscription_providers"] == ["chatgpt"]
assert body["accounts"] == [
{
"custom_llm_provider": "chatgpt",
"account_id": _ACCOUNT,
"deployments": ["gpt-5.6-sol", "gpt-5.6-terra"],
"fee": None,
"billing_periods": [],
"fixed_cost": None,
}
]
def test_fee_counts_once_per_billing_period_however_many_deployments_share_the_account(client):
test_client, _ = client
created = test_client.post("/subscription_accounts/new", json=_TEST_FEE)
assert created.status_code == 200, created.text
one_period = _usage(test_client, "2026-10-01", "2026-10-07")
two_periods = _usage(test_client, "2026-09-15", "2026-11-15")
between_starts = _usage(test_client, "2026-10-02", "2026-10-31")
(account,) = one_period["accounts"]
assert account["deployments"] == ["gpt-5.6-sol", "gpt-5.6-terra"]
assert account["fee"]["monthly_fee"] == 25.0
assert account["fee"]["currency"] == "USD"
assert account["fee"]["label"] == "Team plan (test value)"
assert account["billing_periods"] == [{"start": "2026-10-01", "end": "2026-10-31"}]
assert account["fixed_cost"] == 25.0
assert two_periods["accounts"][0]["fixed_cost"] == 50.0
assert [period["start"] for period in two_periods["accounts"][0]["billing_periods"]] == [
"2026-10-01",
"2026-11-01",
]
assert between_starts["accounts"][0]["fixed_cost"] == 0.0
assert between_starts["accounts"][0]["billing_periods"] == []
def test_fee_of_an_account_no_deployment_uses_stays_listed_and_counted(client):
test_client, _ = client
other = {**_TEST_FEE, "account_id": "org-other", "monthly_fee": 200.0, "currency": "EUR"}
assert test_client.post("/subscription_accounts/new", json=other).status_code == 200
assert test_client.post("/subscription_accounts/new", json=_TEST_FEE).status_code == 200
body = _usage(test_client, "2026-10-01", "2026-10-07")
unused, used = body["accounts"]
assert (unused["account_id"], unused["deployments"], unused["fee"]["currency"]) == ("org-other", [], "EUR")
assert unused["fixed_cost"] == 200.0
assert (used["account_id"], used["fixed_cost"]) == (_ACCOUNT, 25.0)
@pytest.mark.parametrize(
"deployments",
[(SubscriptionDeployment(model_name="gpt-5.6-terra", custom_llm_provider="chatgpt", account_id=None),)],
)
def test_account_not_signed_in_shows_no_account_and_takes_no_fee(client):
test_client, _ = client
assert test_client.post("/subscription_accounts/new", json=_TEST_FEE).status_code == 200
body = _usage(test_client, "2026-10-01", "2026-10-07")
unsigned = next(account for account in body["accounts"] if account["account_id"] is None)
assert unsigned["deployments"] == ["gpt-5.6-terra"]
assert unsigned["fee"] is None
assert unsigned["fixed_cost"] is None
def test_update_changes_the_fee_and_delete_returns_the_account_to_untracked(client):
test_client, store = client
created = test_client.post("/subscription_accounts/new", json=_TEST_FEE).json()
account_id = created["subscription_account_id"]
updated = test_client.post(
"/subscription_accounts/update",
json={"subscription_account_id": account_id, "monthly_fee": 30.0, "billing_period_start": "2026-10-05"},
)
assert updated.status_code == 200, updated.text
assert updated.json()["monthly_fee"] == 30.0
assert updated.json()["currency"] == "USD"
assert updated.json()["billing_period_start"] == "2026-10-05"
assert updated.json()["label"] == _TEST_FEE["label"]
assert _usage(test_client, "2026-10-01", "2026-10-07")["accounts"][0]["fixed_cost"] == 30.0
cleared = test_client.post(
"/subscription_accounts/update", json={"subscription_account_id": account_id, "label": None}
)
assert cleared.status_code == 200, cleared.text
assert cleared.json()["label"] is None
assert cleared.json()["monthly_fee"] == 30.0
assert store.written_columns == [{"monthly_fee": 30.0, "billing_period_start": "2026-10-05"}, {"label": None}]
unknown = test_client.post(
"/subscription_accounts/update", json={"subscription_account_id": "no-such-account", "monthly_fee": 1.0}
)
assert unknown.status_code == 404
deleted = test_client.post("/subscription_accounts/delete", json={"subscription_account_id": account_id})
assert deleted.status_code == 200, deleted.text
assert store.rows == {}
assert _usage(test_client, "2026-10-01", "2026-10-07")["accounts"][0]["fixed_cost"] is None
missing = test_client.post("/subscription_accounts/delete", json={"subscription_account_id": account_id})
assert missing.status_code == 404
def test_rejects_a_second_fee_for_the_same_account(client):
test_client, _ = client
assert test_client.post("/subscription_accounts/new", json=_TEST_FEE).status_code == 200
duplicate = test_client.post("/subscription_accounts/new", json={**_TEST_FEE, "monthly_fee": 99.0})
assert duplicate.status_code == 400
assert "/subscription_accounts/update" in duplicate.json()["detail"]["error"]
def test_rejects_a_fee_on_a_metered_provider(client):
test_client, store = client
response = test_client.post("/subscription_accounts/new", json={**_TEST_FEE, "custom_llm_provider": "openai"})
assert response.status_code == 400
assert store.rows == {}
@pytest.mark.parametrize(
"payload",
[
{**_TEST_FEE, "monthly_fee": 0},
{**_TEST_FEE, "account_id": ""},
{**_TEST_FEE, "currency": "usd"},
{**_TEST_FEE, "currency": "$"},
{**_TEST_FEE, "billing_period_start": "10/01/2026"},
],
)
def test_rejects_malformed_fee_fields(client, payload):
test_client, store = client
assert test_client.post("/subscription_accounts/new", json=payload).status_code == 422
assert store.rows == {}
def test_rejects_an_infinite_monthly_fee():
with pytest.raises(ValidationError):
SubscriptionAccountFeeRequest.model_validate({**_TEST_FEE, "monthly_fee": float("inf")})
with pytest.raises(ValidationError):
UpdateSubscriptionAccountFeeRequest.model_validate(
{"subscription_account_id": "fee-1", "monthly_fee": float("inf")}
)
@pytest.mark.parametrize("deployments", [()])
def test_fee_stays_listed_after_the_last_subscription_deployment_is_removed(client):
test_client, _ = client
assert test_client.post("/subscription_accounts/new", json=_TEST_FEE).status_code == 200
body = _usage(test_client, "2026-10-01", "2026-10-07")
(account,) = body["accounts"]
assert (account["account_id"], account["deployments"], account["fixed_cost"]) == (_ACCOUNT, [], 25.0)
def test_usage_rejects_a_malformed_or_inverted_range(client):
test_client, _ = client
malformed = [
test_client.get("/subscription_accounts/usage", params={"start_date": start, "end_date": "2026-10-07"})
for start in ("2026-10-1", "20261001", "2026-W40-1", "2026-13-01")
]
inverted = test_client.get(
"/subscription_accounts/usage", params={"start_date": "2026-10-07", "end_date": "2026-10-01"}
)
assert [response.status_code for response in malformed] == [400, 400, 400, 400]
assert inverted.status_code == 400
def test_viewer_reads_usage_but_cannot_write(client):
test_client, store = client
viewer = {"x-user-role": LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY.value}
assert _usage(test_client, "2026-10-01", "2026-10-07", **viewer)["accounts"][0]["account_id"] == _ACCOUNT
assert test_client.post("/subscription_accounts/new", json=_TEST_FEE, headers=viewer).status_code == 403
assert store.rows == {}
_SUBSCRIPTION_ROUTES: Final = (
"/subscription_accounts/usage",
"/subscription_accounts/new",
"/subscription_accounts/update",
"/subscription_accounts/delete",
)
def test_routes_follow_the_admin_route_policy():
jwt_admin_defaults = LiteLLM_JWTAuth()
for route in _SUBSCRIPTION_ROUTES:
assert allowed_routes_check(
user_role=LitellmUserRoles.PROXY_ADMIN, user_route=route, litellm_proxy_roles=jwt_admin_defaults
)
assert RouteChecks.is_management_route(route)
def test_viewer_route_gate_reads_usage_and_blocks_writes():
viewer_role: Final = LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY.value
get_usage = MagicMock(spec=Request, method="GET", query_params={})
post_new = MagicMock(spec=Request, method="POST", query_params={})
RouteChecks._check_proxy_admin_viewer_access(
route="/subscription_accounts/usage", _user_role=viewer_role, request_data={}, request=get_usage
)
with pytest.raises(HTTPException) as denied:
RouteChecks._check_proxy_admin_viewer_access(
route="/subscription_accounts/new", _user_role=viewer_role, request_data=_TEST_FEE, request=post_new
)
assert denied.value.status_code == 403
def test_internal_user_cannot_read_subscription_accounts(client):
test_client, _ = client
response = test_client.get(
"/subscription_accounts/usage",
params={"start_date": "2026-10-01", "end_date": "2026-10-07"},
headers={"x-user-role": LitellmUserRoles.INTERNAL_USER.value},
)
assert response.status_code == 403
def test_deployments_take_the_account_of_their_own_login():
model_list = [
{"model_name": "gpt-5.6-terra", "litellm_params": {"model": "chatgpt/gpt-5.6-terra"}},
{"model_name": "gpt-5.6-sol", "litellm_params": {"model": "chatgpt/gpt-5.6-sol"}},
{
"model_name": "gpt-5.6-luna",
"litellm_params": {"model": "chatgpt/gpt-5.6-luna", "chatgpt_auth_file": "/logins/other.json"},
},
{"model_name": "sonnet", "litellm_params": {"model": "anthropic/claude-sonnet-4-5", "api_key": "sk-x"}},
{"model_name": "broken", "litellm_params": {"model": "no-such-provider-model"}},
]
lookups: list[tuple[str, object]] = []
def resolver(provider: str, litellm_params) -> str | None:
lookups.append((provider, litellm_params.get("model")))
return "org-other" if litellm_params.get("chatgpt_auth_file") == "/logins/other.json" else _ACCOUNT
deployments = subscription_deployments_from_model_list(model_list, resolver)
assert deployments == (
*_TWO_DEPLOYMENTS_ONE_ACCOUNT,
SubscriptionDeployment(model_name="gpt-5.6-luna", custom_llm_provider="chatgpt", account_id="org-other"),
)
assert lookups == [
("chatgpt", "chatgpt/gpt-5.6-terra"),
("chatgpt", "chatgpt/gpt-5.6-sol"),
("chatgpt", "chatgpt/gpt-5.6-luna"),
]
def test_deployments_list_each_router_deployment_once_by_the_name_callers_use():
llm_router: Final = Router(
model_list=[
{"model_name": "gpt-5.6-sol", "litellm_params": {"model": "chatgpt/gpt-5.6-sol"}},
{
"model_name": "model_name_team-1_7f3a",
"litellm_params": {"model": "chatgpt/gpt-5.6-terra"},
"model_info": {"team_id": "team-1", "team_public_model_name": "team-terra"},
},
],
model_group_alias={"sol-alias": "gpt-5.6-sol"},
)
deployments = subscription_deployments_of_router(llm_router, lambda provider, litellm_params: _ACCOUNT)
assert sorted(deployment.model_name for deployment in deployments) == ["gpt-5.6-sol", "team-terra"]
@pytest.mark.parametrize(
"deployments",
[
(
*_TWO_DEPLOYMENTS_ONE_ACCOUNT,
SubscriptionDeployment(model_name="gpt-5.6-luna", custom_llm_provider="chatgpt", account_id="org-other"),
)
],
)
def test_two_logins_each_count_their_own_fee_once(client):
test_client, _ = client
other = {**_TEST_FEE, "account_id": "org-other", "monthly_fee": 40.0}
assert test_client.post("/subscription_accounts/new", json=_TEST_FEE).status_code == 200
assert test_client.post("/subscription_accounts/new", json=other).status_code == 200
body = _usage(test_client, "2026-10-01", "2026-10-07")
assert [(a["account_id"], a["deployments"], a["fixed_cost"]) for a in body["accounts"]] == [
("org-other", ["gpt-5.6-luna"], 40.0),
(_ACCOUNT, ["gpt-5.6-sol", "gpt-5.6-terra"], 25.0),
]