litellm/tests/unit/proxy/spend_tracking/test_budget_reservation.py
joshua-berri 906fa7ed28
feat(accounting): add opt-in SpendLogs ledger (#49856)
* feat(accounting): add opt-in SpendLogs ledger delivery

* fix(accounting): preserve missing organization daily spend parity

* fix(accounting): preserve ledger receipts when replaying migration

* fix(accounting): preserve callback windows and tune ledger batches

* fix(accounting): preserve window charges and bound ledger statements

* test(accounting): verify budget callback registration order

* test(accounting): verify captured charges after repeated startup

* feat(accounting): store durable payloads independently of spend logs

* fix(accounting): preserve first delivery and trace ledger writes

* fix(accounting): keep SDK imports independent of proxy tracing

* fix(accounting): honor log retention during batch takeover

* test(accounting): cover retained batch alerts and invalid settings

* test(accounting): verify downgrade command against pending work

* fix(accounting): drain retries without starving fresh deliveries

* test(accounting): cover delivery projection, metrics and window key reads

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(accounting): read delivery metrics without the shared registry

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(accounting): charge a leftover $0 batch row when its claim fails

A failed batch claim buffers the retrieve's row and reports it charged. At flush the
row conflicted with the pre-upgrade $0 SpendLogs row, so its delivery was rolled back
and the charge never reached the spend tables. The flush now takes that row over in the
same transaction and keeps the delivery.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(accounting): trace the batch takeover at flush as a SpendLogs update

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(accounting): keep local spend logs when SPEND_LOGS_URL has no export client

The export client is never created, so main always writes SpendLogs to the proxy's own
database even with SPEND_LOGS_URL set. The ledger skipped local rows whenever the URL was
set, which dropped those request logs. It now treats a flush as an export only when the
client exists, and batch claims write local rows as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(accounting): keep every request's charge when its log row is shared, evicted or rejected

- Key non-batch deliveries on a per-request delivery_id so a reused client call id is still
  charged once per request, while buffer replays stay deduplicated
- Persist the redacted api_key instead of an opaque bearer token
- Keep the accounting payload when the spend-log queue evicts a row or Postgres rejects it
- Strip NUL from payloads and skip non-text tags so projection never parks a paid request

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(accounting): isolate a raw-SQL spend log row Postgres rejects instead of requeueing the batch

A rejected row on the ledger insert path raises RawQueryError, which the exact DataError check missed, so the whole batch was requeued every flush. Data and integrity SQLSTATE classes now bisect like before, while missing tables and deadlocks keep retrying

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(accounting): keep charging a request whose tag is too long for the daily tag index

A tag past Postgres's btree entry limit failed the DailyTagSpend upsert, and on the ledger path that rolled back the request's key, team and user charges with it. Such tags are now left out of the daily tag rollup only

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(accounting): store only guardrail billing fields in the accounting payload

The ledger payload copied whole guardrail records, including responses and match details, into LiteLLM_SpendLogDelivery even when spend logs were disabled. It now keeps the id, name, usage and cost fields the projection reads. NUL stripping reuses safe_json_structure instead of a recursive walk

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(proxy): move spend payload stamping out of update_database

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(proxy): restore the modules the import-layering guard evicts

The guard popped litellm.proxy.utils from sys.modules for good, so later tests on the same xdist worker patched a fresh module while calling functions bound to the old one, and spend queue tests failed depending on scheduling

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(proxy): keep update_database's payload stamping on its own local

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(accounting): type guardrail entries and use a public key redaction helper

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(accounting): keep charging requests whose end-user id is too long for an index

An oversized end-user id failed the SpendLogs insert with SQLSTATE 54000, which was requeued forever, and failed the end-user upsert in the delivery, which parked the key and team charge with it. Class 54 rows are now isolated like other rejected rows, and such ids are left out of the end-user rollups only

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(proxy): type the spend log queue snapshot

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(accounting): leave out any projected row Postgres cannot index or store

Caller-supplied ids and counters, such as a long tag or end-user id or an out-of-range compression count, failed the delivery transaction and rolled back the request's key, team and user charges. One check in project() now drops only the row that cannot be stored, replacing the per-field cutoffs

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(accounting): keep the guardrail fields compression savings are counted from

Slimming the guardrail records dropped the provider and the tokens_saved figure that Headroom compression savings are read from, and dropped a bare-dict record entirely. The payload now keeps both while still leaving out guardrail content

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(accounting): cap projected counters so daily totals cannot overflow

Counters such as a caller-supplied compression count fit one by one but overflowed the bigint daily total once summed across requests, rolling back the key, team and user charges in the same transaction. Each counter is now capped at 2^40, far below any total that could overflow

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(accounting): let a buffered batch charge take over its zero-cost receipt

A batch charge queued after a failed lookup hit the $0 receipt an earlier poll left behind, and ON CONFLICT dropped it. The buffered insert now runs the same receipt takeover as a live retrieve

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(accounting): read a rescued batch row's spend from its accounting payload

Rows rescued from an overflowing queue keep only the accounting payload, so the buffered takeover never saw their positive spend and left the $0 receipt uncharged

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(accounting): read budget windows through the delivery transaction

Window seed and existing-row reads used a separate connection while the delivery transaction held one, so with a one-connection pool they waited on their own transaction until it timed out. Inside an enclosing transaction they now share its connection

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(accounting): retry a transient failure while keeping a dropped row's charge

The rescue swallowed every error, so a database blip right after a row was rejected lost the unpaid charge. Only a rejected row is still logged and skipped, anything else propagates so the flush retries

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(accounting): give delivery projection payloads their charged entities

project() now reads entities only from accounting_entities, so the hand-built
delivery payloads carry them like real stored payloads do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(accounting): own ledger rows by their payload and key batches on the batch id

Drop the accounting_path stamp and its SpendLogs column. A buffered row that
carries an accounting payload is ledger owned, one without it is legacy, and
spend counters get a plain windows_from_ledger flag. Window seeding tells
applied ledger rows apart by their delivery row.

A ledger batch is plain transaction A keyed by the batch id, so a repeated
completed retrieve conflicts and charges nothing. A $0 retrieve records no
delivery, a batch a legacy retrieve already charged is not charged again, and
the legacy batch path is unchanged from main apart from refusing a batch the
ledger already owns. Batch takeover and its delta bookkeeping are removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(accounting): drop a projection test duplicated while rebasing

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(accounting): drop previous_payload now that deliveries are never replaced

Batch takeover was the only writer of previous_payload, so the worker applies
each delivery's payload as stored and the column leaves the migration.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(accounting): drop the ledger downgrade checklist script

The use_spend_logs_ledger flag is the rollback path, so a separate downgrade
gate is no longer needed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(accounting): name the window seed reads so their Prisma span resolves

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(accounting): remove the unused accounting event types and protocols

types.py, protocols.py and measurements.py were left from the old event
scaffolding. Nothing outside the package imports them, so they go with their
tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(accounting): park only deliveries whose own data fails

A delivery that keeps failing on a database outage, lock timeout or deadlock
stays pending and retries with capped backoff, so a recovered database applies
it. Only a data error or an invalid payload parks the isolated row.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(accounting): isolate a spend log row the insert statement rejects

The raw SpendLogs insert validates columns and JSON before Postgres sees the
row, so a row that fails there is now bisected out and dropped alone while its
charge is kept, instead of failing and replaying the whole flush.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(accounting): carry a job's model window on every completed poll in ledger mode

The ledger keeps the poll whose delivery claims the job, which need not be the
poll that won the limiter's in-memory charge. Every completed poll now carries
the job's window, so the delivery that lands always has it, while the live
model budget is still charged once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(accounting): leave model-budget windows on the existing window writer

Model-budget windows are written by the model budget limiter rather than
derived from a request's spend, so they stay on main's window queue like live
budget counters do. This drops window capture from the accounting payload,
the deferred limiter registration and the job-window capture, and the ledger
keeps owning key and team budget windows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(accounting): keep a delivery pending when the database is unreachable

Prisma reports a can't reach database server outage as a DataError, so the
worker now checks for an unavailable database before treating a data error
as the delivery's own fault.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(accounting): isolate only rows the raw insert cannot encode

Catching every ValueError also swallowed unexpected insert errors that main
re-raises. The raw insert now raises RejectedSpendLogRow for an unknown column
or non-JSON value, and only that is isolated as a rejected row.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(accounting): store zero savings when caller data makes them uncomputable

A huge caller-supplied tokens_saved overflowed the savings math inside
build_accounting_payload, which dropped the request's charge in ledger mode.
Savings that cannot be computed are now recorded as zero and the charge lands.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Joshua Valluru <326636767+joshua-berri@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 17:49:15 -08:00

597 lines
22 KiB
Python

from __future__ import annotations
import math
from datetime import datetime, timedelta, timezone
from typing import Final
import pytest
import litellm
from litellm.caching import DualCache
from litellm.models.budget import LiteLLM_BudgetTable
from litellm.proxy import proxy_server
from litellm.proxy._types import (
LiteLLM_OrganizationTable,
LiteLLM_ProjectTableCachedObj,
LiteLLM_TeamMembership,
LiteLLM_TeamTable,
LiteLLM_UserTable,
UserAPIKeyAuth,
)
from litellm.proxy.common_utils.user_api_key_cache import (
UserApiKeyCache,
project_cache_key,
team_membership_reservation_cache_key,
)
from litellm.proxy.spend_tracking.budget_reservation import (
_get_team_member_budget_counter,
estimate_request_max_cost,
get_budget_window_start,
release_unbound_budget_reservation,
count_request_input_tokens,
reserve_budget_for_request,
)
from litellm.proxy.utils import ProxyLogging
from litellm.router import Router
from litellm.types.router import Deployment, LiteLLM_Params, ModelInfo
TOKEN_COUNTING_ROUTES: Final = (
"/responses/input_tokens",
"/v1/responses/input_tokens",
"/openai/v1/responses/input_tokens",
"/utils/token_counter",
"/v1/messages/count_tokens",
"/v1beta/models/gemini-3.8-flash:countTokens",
"/models/gemini-3.8-flash:countTokens",
"/bedrock/v1/messages/count-tokens",
"/bedrock/model/us.anthropic.claude-sonnet-4-6/count-tokens",
"/vertex_ai/v1/projects/p/locations/us-east5/publishers/anthropic/models/count-tokens:rawPredict",
"/vertex-ai/v1/projects/p/locations/us-east5/publishers/anthropic/models/count-tokens:rawPredict",
)
def _budgeted_token() -> UserAPIKeyAuth:
return UserAPIKeyAuth(api_key="sk-test", token="hashed-token", max_budget=100.0, spend=0.0)
async def _reserve(route: str) -> dict | None:
return await reserve_budget_for_request(
request_body={"model": "gpt-4o", "input": "hello"},
route=route,
llm_router=None,
valid_token=_budgeted_token(),
team_object=None,
user_object=None,
prisma_client=None,
user_api_key_cache=UserApiKeyCache(),
proxy_logging_obj=ProxyLogging(user_api_key_cache=DualCache()),
)
@pytest.mark.asyncio
@pytest.mark.parametrize("route", TOKEN_COUNTING_ROUTES)
async def test_token_counting_routes_are_exempt_from_budget_reservation(route):
assert await _reserve(route) is None
@pytest.mark.asyncio
async def test_non_exempt_llm_route_still_reserves_budget():
reservation: Final = await _reserve("/v1/responses")
assert reservation is not None
assert reservation["reserved_cost"] > 0
@pytest.mark.asyncio
async def test_reservation_carries_the_admission_input_token_count():
reservation: Final = await _reserve("/v1/responses")
expected: Final = litellm.token_counter(model="gpt-4o", text="hello")
assert reservation is not None
assert expected > 0
assert reservation["input_tokens"] == expected
ANTHROPIC_MESSAGES: Final = [{"role": "user", "content": "hello!!!"}]
COUNT_TOKENS_REQUESTS: Final[tuple[tuple[str, dict[str, object]], ...]] = (
("/v1/messages/count_tokens", {"model": "claude-sonnet-5", "messages": ANTHROPIC_MESSAGES}),
("/v1beta/models/gemini-3.8-flash:countTokens", {"contents": [{"role": "user", "parts": [{"text": "hello!!!"}]}]}),
(
"/vertex_ai/v1/projects/p/locations/us-east5/publishers/anthropic/models/count-tokens:rawPredict",
{"model": "claude-sonnet-5", "messages": ANTHROPIC_MESSAGES},
),
("/bedrock/v1/messages/count-tokens", {"model": "claude-sonnet-5", "messages": ANTHROPIC_MESSAGES}),
)
TINY_BUDGET_KEY_TOKEN: Final = "hashed-count-tokens-key"
@pytest.fixture
def spend_counter_cache(monkeypatch: pytest.MonkeyPatch) -> DualCache:
cache: Final = DualCache()
monkeypatch.setattr(proxy_server, "spend_counter_cache", cache)
monkeypatch.setattr(proxy_server, "prisma_client", None)
return cache
async def _reserve_for_tiny_budget_key(route: str, request_body: dict[str, object]) -> dict[str, object] | None:
return await reserve_budget_for_request(
request_body=request_body,
route=route,
llm_router=None,
valid_token=UserAPIKeyAuth(token=TINY_BUDGET_KEY_TOKEN, max_budget=0.01, spend=0.0),
team_object=None,
user_object=None,
prisma_client=None,
user_api_key_cache=UserApiKeyCache(),
proxy_logging_obj=ProxyLogging(user_api_key_cache=DualCache()),
)
@pytest.mark.asyncio
@pytest.mark.parametrize(("route", "request_body"), COUNT_TOKENS_REQUESTS)
async def test_repeated_token_counting_never_touches_a_tiny_budget(
spend_counter_cache: DualCache, route: str, request_body: dict[str, object]
):
counter_key: Final = f"spend:key:{TINY_BUDGET_KEY_TOKEN}"
assert await _reserve_for_tiny_budget_key(route, request_body) is None
assert await _reserve_for_tiny_budget_key(route, request_body) is None
assert spend_counter_cache.in_memory_cache.get_cache(key=counter_key) is None
completion: Final = await _reserve_for_tiny_budget_key(
"/v1/messages", {"model": "claude-sonnet-5", "max_tokens": 16, "messages": ANTHROPIC_MESSAGES}
)
assert completion is not None
reserved_cost: Final = completion["reserved_cost"]
assert isinstance(reserved_cost, float)
assert reserved_cost > 0
assert spend_counter_cache.in_memory_cache.get_cache(key=counter_key) == pytest.approx(reserved_cost)
BEDROCK_SONNET: Final = "us.anthropic.claude-sonnet-4-6"
CONVERSE_BODY: Final = {
"messages": [{"role": "user", "content": [{"text": "Reply with one word: pong"}]}],
"inferenceConfig": {"maxTokens": 5},
}
INVOKE_BODY: Final = {
"anthropic_version": "bedrock-2023-05-31",
"max_tokens": 5,
"messages": [{"role": "user", "content": "Reply with one word: pong"}],
}
def test_bedrock_converse_body_reserves_the_prompt_not_the_context_window():
converse_cost: Final = estimate_request_max_cost(
request_body=CONVERSE_BODY,
route=f"/bedrock/model/{BEDROCK_SONNET}/converse",
llm_router=None,
input_token_counts={},
)
invoke_cost: Final = estimate_request_max_cost(
request_body=INVOKE_BODY,
route=f"/bedrock/model/{BEDROCK_SONNET}/invoke",
llm_router=None,
input_token_counts={},
)
assert converse_cost is not None and invoke_cost is not None
assert invoke_cost < converse_cost < 2 * invoke_cost
def _tiered_deployment(input_cost_per_token: float) -> Deployment:
return Deployment(
model_name="tiered-group",
litellm_params=LiteLLM_Params(model="dashscope/qwen3-max", api_key="sk-fake"),
model_info=ModelInfo(
id="tiered-deployment",
max_output_tokens=1000,
tiered_pricing=[
{
"input_cost_per_token": input_cost_per_token,
"output_cost_per_token": input_cost_per_token,
"range": [0, 128000],
}
],
),
)
TIERED_BODY: Final = {"model": "tiered-group", "messages": [{"role": "user", "content": "hello"}], "max_tokens": 10}
def test_repeated_estimates_reuse_cached_model_cost_info() -> None:
router: Final = Router(model_list=[_tiered_deployment(1e-06).model_dump()])
first: Final = estimate_request_max_cost(request_body=TIERED_BODY, route="/chat/completions", llm_router=router)
hits_before: Final = router.cached_deployment_model_info.cache_info().hits
second: Final = estimate_request_max_cost(request_body=TIERED_BODY, route="/chat/completions", llm_router=router)
assert second == first
assert router.cached_deployment_model_info.cache_info().hits == hits_before + 1
def test_deployment_pricing_update_invalidates_cached_estimate() -> None:
router: Final = Router(model_list=[_tiered_deployment(1e-06).model_dump()])
before: Final = estimate_request_max_cost(request_body=TIERED_BODY, route="/chat/completions", llm_router=router)
assert before is not None
router.upsert_deployment(_tiered_deployment(1e-03))
after: Final = estimate_request_max_cost(request_body=TIERED_BODY, route="/chat/completions", llm_router=router)
assert after is not None
assert math.isclose(after, before * 1000)
@pytest.mark.asyncio
@pytest.mark.parametrize(
"expiry_offset, expected_max_budget",
[
(timedelta(days=1), 3.0),
(timedelta(days=-1), 2.0),
],
)
async def test_team_member_reservation_counter_honours_temp_budget_increase(
expiry_offset: timedelta, expected_max_budget: float
) -> None:
user_id: Final = "member-temp"
team_id: Final = "team-temp"
cache: Final = UserApiKeyCache()
await cache.async_set_cache(
key=team_membership_reservation_cache_key(user_id=user_id, team_id=team_id),
value=LiteLLM_TeamMembership(
user_id=user_id,
team_id=team_id,
spend=0.5,
budget_id="budget-temp",
litellm_budget_table=LiteLLM_BudgetTable(
max_budget=2.0,
temp_budget_increase=1.0,
temp_budget_expiry=datetime.now(timezone.utc) + expiry_offset,
),
),
)
counter: Final = await _get_team_member_budget_counter(
valid_token=UserAPIKeyAuth(token="hashed", user_id=user_id, team_id=team_id),
team_object=LiteLLM_TeamTable(team_id=team_id),
user_object=LiteLLM_UserTable(user_id=user_id),
user_api_key_cache=cache,
)
assert counter is not None
assert counter.max_budget == expected_max_budget
assert counter.fallback_spend == 0.5
@pytest.mark.asyncio
@pytest.mark.parametrize(
"default_cap, expiry_offset, expected_max_budget",
[
(2.0, timedelta(days=1), 3.0),
(2.0, timedelta(days=-1), 2.0),
(0.0, timedelta(days=1), None),
],
)
async def test_team_member_reservation_counter_adds_temp_increase_to_live_team_default(
default_cap: float, expiry_offset: timedelta, expected_max_budget: float | None
) -> None:
user_id: Final = "member-bare"
team_id: Final = "team-bare"
cache: Final = UserApiKeyCache()
await cache.async_set_cache(
key="team_member_default_budget:default-bare",
value=LiteLLM_BudgetTable(budget_id="default-bare", max_budget=default_cap),
)
await cache.async_set_cache(
key=team_membership_reservation_cache_key(user_id=user_id, team_id=team_id),
value=LiteLLM_TeamMembership(
user_id=user_id,
team_id=team_id,
spend=0.5,
budget_id="budget-bare",
litellm_budget_table=LiteLLM_BudgetTable(
max_budget=None,
temp_budget_increase=1.0,
temp_budget_expiry=datetime.now(timezone.utc) + expiry_offset,
),
),
)
counter: Final = await _get_team_member_budget_counter(
valid_token=UserAPIKeyAuth(token="hashed", user_id=user_id, team_id=team_id),
team_object=LiteLLM_TeamTable(team_id=team_id, metadata={"team_member_budget_id": "default-bare"}),
user_object=LiteLLM_UserTable(user_id=user_id),
user_api_key_cache=cache,
)
if expected_max_budget is None:
assert counter is None
return
assert counter is not None
assert counter.max_budget == expected_max_budget
assert counter.fallback_spend == 0.5
@pytest.mark.asyncio
async def test_reservation_starts_unbound_to_any_callback():
reservation: Final = await _reserve("/v1/responses")
assert reservation is not None
assert reservation["callback_bound"] is False
@pytest.mark.asyncio
async def test_release_unbound_budget_reservation_frees_the_counter(spend_counter_cache: DualCache):
counter_key: Final = f"spend:key:{TINY_BUDGET_KEY_TOKEN}"
reservation: Final = await _reserve_for_tiny_budget_key(
"/v1/chat/completions", {"model": "gpt-4o", "messages": [{"role": "user", "content": "hello"}]}
)
assert reservation is not None
assert spend_counter_cache.in_memory_cache.get_cache(key=counter_key) == pytest.approx(reservation["reserved_cost"])
await release_unbound_budget_reservation(reservation)
assert spend_counter_cache.in_memory_cache.get_cache(key=counter_key) == pytest.approx(0.0)
assert reservation["finalized"] is True
@pytest.mark.asyncio
async def test_release_unbound_budget_reservation_leaves_a_bound_one_to_its_callback(spend_counter_cache: DualCache):
counter_key: Final = f"spend:key:{TINY_BUDGET_KEY_TOKEN}"
reservation: Final = await _reserve_for_tiny_budget_key(
"/v1/chat/completions", {"model": "gpt-4o", "messages": [{"role": "user", "content": "hello"}]}
)
assert reservation is not None
reservation["callback_bound"] = True
await release_unbound_budget_reservation(reservation)
assert spend_counter_cache.in_memory_cache.get_cache(key=counter_key) == pytest.approx(reservation["reserved_cost"])
assert reservation["finalized"] is False
@pytest.mark.asyncio
async def test_reservation_holds_cost_against_cached_org_and_project_budgets(spend_counter_cache: DualCache):
cache: Final = UserApiKeyCache()
await cache.async_set_cache(
key="org_id:org-budgeted:with_budget",
value=LiteLLM_OrganizationTable(
organization_id="org-budgeted",
budget_id="org-budget",
spend=1.5,
models=[],
created_by="admin",
updated_by="admin",
litellm_budget_table=LiteLLM_BudgetTable(max_budget=10.0),
),
model_type=LiteLLM_OrganizationTable,
)
await cache.async_set_cache(
key=project_cache_key("project-budgeted"),
value=LiteLLM_ProjectTableCachedObj(
project_id="project-budgeted", spend=2.5, litellm_budget_table=LiteLLM_BudgetTable(max_budget=20.0)
),
model_type=LiteLLM_ProjectTableCachedObj,
)
reservation: Final = await reserve_budget_for_request(
request_body={"model": "gpt-4o", "input": "hello"},
route="/v1/responses",
llm_router=None,
valid_token=UserAPIKeyAuth(token="hashed-org-project", org_id="org-budgeted", project_id="project-budgeted"),
team_object=None,
user_object=None,
prisma_client=None,
user_api_key_cache=cache,
proxy_logging_obj=ProxyLogging(user_api_key_cache=DualCache()),
)
assert reservation is not None
reserved_cost: Final = reservation["reserved_cost"]
assert reserved_cost > 0
assert reservation["entries"] == [
{
"counter_key": "spend:org:org-budgeted",
"entity_type": "Organization",
"entity_id": "org-budgeted",
"reserved_cost": reserved_cost,
"applied_adjustment": 0.0,
},
{
"counter_key": "spend:project:project-budgeted",
"entity_type": "Project",
"entity_id": "project-budgeted",
"reserved_cost": reserved_cost,
"applied_adjustment": 0.0,
},
]
assert spend_counter_cache.in_memory_cache.get_cache(key="spend:org:org-budgeted") == pytest.approx(reserved_cost)
assert spend_counter_cache.in_memory_cache.get_cache(key="spend:project:project-budgeted") == pytest.approx(
reserved_cost
)
@pytest.mark.parametrize(
("window", "expected"),
[
(
'{"budget_duration": "1h", "reset_at": "2030-01-01T01:00:00Z"}',
datetime(2030, 1, 1, 0, 0, tzinfo=timezone.utc),
),
('{"reset_at": "2030-01-01T01:00:00Z"}', None),
("{}", None),
('["budget_duration", "1h"]', None),
('"1h"', None),
("null", None),
("not json", None),
],
)
def test_budget_window_start_reads_json_encoded_windows(window: str, expected: datetime | None) -> None:
assert get_budget_window_start(window) == expected
@pytest.mark.asyncio
async def test_reservation_counts_a_pdf_with_the_deployment_behind_a_gpt_named_group() -> None:
from litellm.proxy.spend_tracking.input_tokens import count_input_tokens_for_model
from tests.unit.proxy.spend_tracking.test_input_tokens import _one_page_pdf_message
request_body: Final = {"model": "gpt-4o", "messages": _one_page_pdf_message()}
router: Final = Router(
model_list=[{"model_name": "gpt-4o", "litellm_params": {"model": "anthropic/claude-haiku-5-5", "api_key": "x"}}]
)
counts: Final = await count_request_input_tokens(
request_body=request_body, route="/chat/completions", llm_router=router, team_id=None
)
assert counts == {"gpt-4o": count_input_tokens_for_model(request_body=request_body, model="claude-haiku-5-5")}
assert counts["gpt-4o"] > count_input_tokens_for_model(request_body=request_body, model="gpt-4o")
_MULTILINGUAL_MESSAGES: Final = [{"role": "user", "content": "日本語のテキストとहिन्दी पाठ और русский текст. " * 20}]
def _router_with_groups(*groups: tuple[str, str]) -> Router:
return Router(
model_list=[
{"model_name": name, "litellm_params": {"model": model, "api_key": "sk-test"}} for name, model in groups
]
)
async def _input_tokens(router: Router, model: str) -> dict[str, int]:
return dict(
await count_request_input_tokens(
request_body={"model": model, "messages": _MULTILINGUAL_MESSAGES},
route="/v1/chat/completions",
llm_router=router,
team_id=None,
)
)
async def _reserved_input_tokens(router: Router, model: str, route: str, messages: list[dict[str, object]]) -> int:
counts: Final = await count_request_input_tokens(
request_body={"model": model, "messages": messages}, route=route, llm_router=router, team_id=None
)
return counts[model]
@pytest.mark.asyncio
async def test_an_openai_chat_request_reserves_what_openai_chat_bills_on_top_of_each_pdf_files_pages() -> None:
from litellm.constants import OPENAI_CHAT_PDF_FILE_TOKENS
from tests.unit.proxy.spend_tracking.test_input_tokens import _one_page_pdf_message
router: Final = _router_with_groups(("on-openai", "openai/gpt-5.6-sol"), ("on-azure", "azure/gpt-5.6-sol"))
two_pdfs: Final = [*_one_page_pdf_message(), *_one_page_pdf_message()]
assert await _reserved_input_tokens(router, "on-openai", "/v1/chat/completions", two_pdfs) == (
await _reserved_input_tokens(router, "on-azure", "/v1/chat/completions", two_pdfs)
+ 2 * OPENAI_CHAT_PDF_FILE_TOKENS
)
assert await _reserved_input_tokens(router, "on-openai", "/v1/messages", two_pdfs) == (
await _reserved_input_tokens(router, "on-azure", "/v1/messages", two_pdfs)
)
assert await _reserved_input_tokens(router, "on-openai", "/v1/chat/completions", _MULTILINGUAL_MESSAGES) == (
await _reserved_input_tokens(router, "on-azure", "/v1/chat/completions", _MULTILINGUAL_MESSAGES)
)
@pytest.mark.asyncio
async def test_alias_group_of_an_openai_model_reserves_on_that_models_token_count():
router: Final = _router_with_groups(("gpt-6.1-sol", "openai/gpt-6.1-sol"), ("prod-gpt-6", "openai/gpt-6.1-sol"))
by_name: Final = await _input_tokens(router, "gpt-6.1-sol")
assert await _input_tokens(router, "prod-gpt-6") == {"prod-gpt-6": by_name["gpt-6.1-sol"]}
@pytest.mark.asyncio
async def test_model_group_alias_of_an_openai_group_reserves_on_that_groups_token_count():
router: Final = Router(
model_list=[
{"model_name": "gpt-6.1-sol", "litellm_params": {"model": "openai/gpt-6.1-sol", "api_key": "sk-test"}}
],
model_group_alias={"prod": "gpt-6.1-sol"},
)
by_name: Final = await _input_tokens(router, "gpt-6.1-sol")
assert await _input_tokens(router, "prod") == {"prod": by_name["gpt-6.1-sol"]}
@pytest.mark.asyncio
async def test_model_group_alias_of_a_group_no_openai_model_serves_reserves_on_the_alias_as_written():
router: Final = Router(
model_list=[
{
"model_name": "claude-sonnet-5-5",
"litellm_params": {"model": "anthropic/claude-sonnet-5-5", "api_key": "sk-test"},
}
],
model_group_alias={"claude-alias": "claude-sonnet-5-5"},
)
assert await _input_tokens(router, "claude-alias") == {
"claude-alias": litellm.token_counter(model="claude-alias", messages=_MULTILINGUAL_MESSAGES)
}
@pytest.mark.asyncio
@pytest.mark.parametrize("name", ["gpt-6-claude", "o4-alias"])
async def test_release_named_group_or_alias_no_openai_model_serves_reserves_on_an_unknown_names_count(
name: str,
) -> None:
router: Final = Router(
model_list=[
{"model_name": group, "litellm_params": {"model": "anthropic/claude-sonnet-5-5", "api_key": "sk-test"}}
for group in ("claude-sonnet-5-5", "gpt-6-claude")
],
model_group_alias={"o4-alias": "claude-sonnet-5-5"},
)
assert await _input_tokens(router, name) == {
name: litellm.token_counter(model="my-model", messages=_MULTILINGUAL_MESSAGES)
}
@pytest.mark.asyncio
@pytest.mark.parametrize(
("group", "counted_as"),
[("gpt-6.1-sol", "my-model"), ("openai/gpt-6.1-sol", "my-model"), ("mixed", "my-model"), ("gpt-4o", "gpt-4o")],
)
async def test_group_mixing_in_a_non_openai_model_reserves_on_its_name_as_written_and_its_openai_models(
group: str, counted_as: str
):
served: Final = ("openai/gpt-6.1-sol", "cohere/command-r-plus")
router: Final = _router_with_groups(*((group, model) for model in served))
reserved: Final = (await _input_tokens(router, group))[group]
assert reserved == max(
litellm.token_counter(model=counted_as, messages=_MULTILINGUAL_MESSAGES),
litellm.token_counter(model="openai/gpt-6.1-sol", messages=_MULTILINGUAL_MESSAGES),
)
@pytest.mark.asyncio
async def test_group_reserves_on_its_current_deployments_after_another_vendors_deployment_joins():
router: Final = _router_with_groups(("prod", "openai/gpt-6.1-sol"))
openai_only: Final = (await _input_tokens(router, "prod"))["prod"]
router.add_deployment(
Deployment(
model_name="prod",
litellm_params=LiteLLM_Params(model="anthropic/claude-sonnet-5-5", api_key="sk-test"),
)
)
by_own_name: Final = litellm.token_counter(model="prod", messages=_MULTILINGUAL_MESSAGES)
assert openai_only != by_own_name
assert (await _input_tokens(router, "prod"))["prod"] == by_own_name
@pytest.mark.parametrize("window", [{}, {"budget_duration": "1d"}, {"reset_at": "2026-11-03T00:00:00Z"}])
def test_fixed_budget_window_requires_duration_and_reset_boundary(window: object) -> None:
from litellm.proxy.spend_tracking.budget_reservation import fixed_budget_window
assert fixed_budget_window(window) is None