litellm/tests/integration/database/test_spendlogs_ledger_parity.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

1437 lines
74 KiB
Python

import contextlib
import asyncio
import json
import os
import uuid
import subprocess
import sys
import time
from collections.abc import Iterator
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Final
import psycopg
from psycopg import sql
import pytest
import litellm
from litellm.accounting.application import apply_deliveries
from litellm.caching.dual_cache import DualCache
from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache
from litellm.constants import BILLED_RETRY_ATTEMPT_METADATA_KEY, INTERNAL_CALL_ORIGIN_METADATA_KEY
from litellm.proxy.spend_tracking.spend_tracking_utils import spend_log_row_with_retained_metadata
from litellm.proxy import proxy_server
from litellm.proxy._types import SpendLogsMetadataFields
from litellm.proxy.db.db_spend_update_writer import DBSpendUpdateWriter
from litellm.proxy.db.model_usage_rollup import flush_model_usage_transactions
from litellm.proxy.guardrails.usage_tracking import PendingRollups, process_spend_logs_guardrail_usage
from litellm.proxy.utils import PrismaClient
from litellm.proxy.hooks.model_budget_shared_windows import DatabaseSharedWindows
from litellm.proxy.hooks.model_max_budget_limiter import PROXY_VirtualKeyModelMaxBudgetLimiter
from litellm.repositories.accounting_delivery_repository import AccountingDeliveryRepository
from litellm.repositories.table_repositories import SpendLogsRepository
from litellm.responses.streaming_iterator import drain_logging_tasks
from litellm.types.utils import ModelResponse, Usage
from tests.integration._support.database import scratch_database
_ROOT: Final = Path(__file__).resolve().parents[3]
_NOW: Final = datetime(2026, 11, 2, tzinfo=timezone.utc)
_ENTITY_TABLES: Final = (
"LiteLLM_VerificationToken",
"LiteLLM_UserTable",
"LiteLLM_TeamTable",
"LiteLLM_TeamMembership",
"LiteLLM_OrganizationTable",
"LiteLLM_OrganizationMembership",
"LiteLLM_EndUserTable",
"LiteLLM_AgentsTable",
"LiteLLM_TagTable",
"LiteLLM_ProjectTable",
"LiteLLM_ModelAccessGroupBudgetTable",
)
_DAILY_TABLES: Final = (
"LiteLLM_DailyUserSpend",
"LiteLLM_DailyTeamSpend",
"LiteLLM_DailyOrganizationSpend",
"LiteLLM_DailyEndUserSpend",
"LiteLLM_DailyAgentSpend",
"LiteLLM_DailyTagSpend",
"LiteLLM_DailyModelUsage",
"LiteLLM_DailyGuardrailUsageUnits",
"LiteLLM_BudgetWindowSpend",
)
@pytest.mark.parametrize("batch_size,row_count,expected,distinct_models", [(None, 251, 251, False), ("200", 251, 200, False), (None, 10001, 10000, False), (None, 3001, 3001, True)])
@pytest.mark.asyncio
async def test_worker_applies_the_configured_backlog_in_one_transaction(
parity_database: str, monkeypatch: pytest.MonkeyPatch, batch_size: str | None, row_count: int, expected: int, distinct_models: bool
):
from litellm.accounting.worker import flush_accounting_deliveries
monkeypatch.setenv("DATABASE_URL", parity_database)
if batch_size is None:
monkeypatch.delenv("LITELLM_ACCOUNTING_DELIVERY_BATCH_SIZE", raising=False)
else:
monkeypatch.setenv("LITELLM_ACCOUNTING_DELIVERY_BATCH_SIZE", batch_size)
monkeypatch.setattr(proxy_server, "general_settings", {"use_spend_logs_ledger": True})
monkeypatch.setattr(proxy_server, "disable_spend_logs", False)
client = PrismaClient(database_url=parity_database, proxy_logging_obj=proxy_server.proxy_logging_obj)
client.spend_log_transactions = []
monkeypatch.setattr(proxy_server, "prisma_client", client)
monkeypatch.setattr(proxy_server, "user_api_key_cache", UserApiKeyCache())
writer = DBSpendUpdateWriter()
await client.db.connect()
try:
assert await _retrieve_batch(writer, 0.25)
stored = await client.writer_db.query_raw('SELECT to_jsonb(s) AS row FROM "LiteLLM_SpendLogs" s')
delivery = (await client.writer_db.query_raw('SELECT accounting_payload FROM "LiteLLM_SpendLogDelivery"'))[0]["accounting_payload"]
assert await SpendLogsRepository(client).insert_with_deliveries(tuple(
{**stored[0]["row"], "request_id": f"backlog-{index:05}", "model": f"backlog-model-{index}" if distinct_models else stored[0]["row"]["model"], "accounting_payload": {**delivery, "request_id": f"backlog-{index:05}", "model": f"backlog-model-{index}" if distinct_models else delivery["model"]}} for index in range(row_count - 1)
)) == row_count - 1
started = time.monotonic()
await flush_accounting_deliveries(writer, client, proxy_server.proxy_logging_obj)
print(f"Ledger batch applied={expected} queued={row_count} seconds={time.monotonic() - started:.3f}")
with psycopg.connect(parity_database) as connection:
assert connection.execute('SELECT COUNT(*) FROM "LiteLLM_SpendLogDelivery" WHERE state=\'applied\'').fetchone() == (expected,)
assert connection.execute('SELECT COUNT(*) FROM "LiteLLM_SpendLogDelivery" WHERE state=\'pending\'').fetchone() == (row_count - expected,)
assert connection.execute('SELECT COUNT(DISTINCT applied_at) FROM "LiteLLM_SpendLogDelivery"').fetchone() == (1,)
assert connection.execute('SELECT spend FROM "LiteLLM_UserTable" WHERE user_id=\'user\'').fetchone() == (expected * 0.25,)
assert connection.execute('SELECT COUNT(*) FROM "LiteLLM_DailyUserSpend"').fetchone() == (expected if distinct_models else 1,)
finally:
await client.db.disconnect()
@pytest.mark.parametrize("ledger", [False, True])
@pytest.mark.parametrize("exclude_messages", [False, True])
@pytest.mark.asyncio
async def test_registered_proxy_callbacks_charge_model_windows_before_persisting_spend(
parity_database: str, monkeypatch: pytest.MonkeyPatch, ledger: bool, exclude_messages: bool
):
from litellm.accounting.worker import flush_accounting_deliveries
from litellm.utils import Rules, function_setup
monkeypatch.setenv("DATABASE_URL", parity_database)
monkeypatch.setenv("LITELLM_COLLECTOR_ENABLED", "false")
for name in ("callbacks", "input_callback", "success_callback", "failure_callback", "_async_success_callback", "_async_failure_callback"):
monkeypatch.setattr(litellm, name, [])
monkeypatch.setattr(litellm, "standard_logging_payload_excluded_fields", ["messages"] if exclude_messages else [])
monkeypatch.setattr(proxy_server, "general_settings", {"use_spend_logs_ledger": ledger})
monkeypatch.setattr(proxy_server, "disable_spend_logs", False)
client = PrismaClient(database_url=parity_database, proxy_logging_obj=proxy_server.proxy_logging_obj)
client.spend_log_transactions = []
client.model_usage_transactions = []
monkeypatch.setattr(proxy_server, "prisma_client", client)
monkeypatch.setattr(proxy_server, "user_api_key_cache", UserApiKeyCache())
writer = DBSpendUpdateWriter()
monkeypatch.setattr(proxy_server.proxy_logging_obj, "db_spend_update_writer", writer)
limiter = PROXY_VirtualKeyModelMaxBudgetLimiter(
dual_cache=DualCache(), clock=lambda: _NOW.timestamp(),
shared_windows=DatabaseSharedWindows(prisma_client_source=lambda: client),
)
monkeypatch.setattr(proxy_server, "model_max_budget_limiter", limiter)
litellm.logging_callback_manager.add_litellm_callback(limiter)
proxy_server.cost_tracking()
logging, _ = function_setup("acompletion", Rules(), _NOW, model="ledger-test", messages=[], litellm_call_id="registered-window")
logging.update_environment_variables(
optional_params={}, custom_llm_provider="openai",
litellm_params={"metadata": {"user_api_key": "2c70e12b7a0646f92279f427c7b38e7334d8e5389cff167a1dc30e73f826b683", "user_api_key_model_max_budget": {
"ledger-test": {"max_budget": 100, "budget_duration": "1d"}
}}},
)
logging.model_call_details["response_cost"] = 0.25
response = ModelResponse(id="registered-window", model="ledger-test", usage=Usage(prompt_tokens=10, completion_tokens=5))
await client.db.connect()
try:
await logging.async_success_handler(response, _NOW, _NOW, standard_logging_object={
"model": "ledger-test", "model_group": "ledger-test", "response_cost": 0.25,
"metadata": {"user_api_key_hash": "2c70e12b7a0646f92279f427c7b38e7334d8e5389cff167a1dc30e73f826b683"},
"model_map_information": {}, "hidden_params": {}, "request_tags": [],
})
await drain_logging_tasks()
await SpendLogsRepository(client).insert_with_deliveries(tuple(client.spend_log_transactions))
if ledger:
await flush_accounting_deliveries(writer, client, proxy_server.proxy_logging_obj)
await writer._commit_spend_updates_to_db_without_redis_buffer(client, 0, proxy_server.proxy_logging_obj)
with psycopg.connect(parity_database) as connection:
assert connection.execute('SELECT spend FROM "LiteLLM_BudgetWindowSpend" WHERE entity_type=\'model_max_budget\'').fetchall() == [(0.25,)]
assert connection.execute('SELECT spend FROM "LiteLLM_SpendLogs"').fetchall() == [(0.25,)]
finally:
await client.db.disconnect()
@pytest.fixture(scope="module")
def ledger_schema() -> str:
return subprocess.run(
[
sys.executable,
"-I",
"-m",
"prisma",
"migrate",
"diff",
"--from-empty",
"--to-schema-datamodel",
str(_ROOT / "schema.prisma"),
"--script",
],
check=True,
capture_output=True,
text=True,
cwd=_ROOT,
).stdout
@pytest.fixture
def parity_database(ledger_schema: str) -> Iterator[str]:
with scratch_database("spendlogs_parity") as url, psycopg.connect(url, autocommit=True) as connection:
connection.execute(ledger_schema)
connection.execute(
"INSERT INTO \"LiteLLM_BudgetTable\" (budget_id, created_by, updated_by) VALUES ('budget', 'test', 'test')"
)
connection.execute("INSERT INTO \"LiteLLM_UserTable\" (user_id) VALUES ('user')")
connection.execute("INSERT INTO \"LiteLLM_TeamTable\" (team_id) VALUES ('team')")
connection.execute(
'INSERT INTO "LiteLLM_OrganizationTable" '
"(organization_id, organization_alias, budget_id, created_by, updated_by) "
"VALUES ('org', 'org', 'budget', 'test', 'test')"
)
connection.execute("INSERT INTO \"LiteLLM_TeamMembership\" (team_id, user_id) VALUES ('team', 'user')")
connection.execute(
"INSERT INTO \"LiteLLM_OrganizationMembership\" (organization_id, user_id) VALUES ('org', 'user')"
)
connection.execute("INSERT INTO \"LiteLLM_VerificationToken\" (token) VALUES ('2c70e12b7a0646f92279f427c7b38e7334d8e5389cff167a1dc30e73f826b683')")
connection.execute("INSERT INTO \"LiteLLM_EndUserTable\" (user_id) VALUES ('end-user')")
connection.execute(
'INSERT INTO "LiteLLM_AgentsTable" '
"(agent_id, agent_name, agent_card_params, created_by, updated_by) "
"VALUES ('agent', 'agent', '{}', 'test', 'test')"
)
connection.execute(
'INSERT INTO "LiteLLM_ProjectTable" (project_id, created_by, updated_by) '
"VALUES ('project', 'test', 'test')"
)
connection.execute("INSERT INTO \"LiteLLM_TagTable\" (tag_name) VALUES ('tag')")
connection.execute("INSERT INTO \"LiteLLM_ModelAccessGroupBudgetTable\" (access_group_name) VALUES ('group')")
yield url
def _snapshot(url: str) -> dict[str, list[object]]:
with psycopg.connect(url) as connection:
return {
table: [
row[0]
for row in connection.execute(
sql.SQL(
"SELECT to_jsonb(t) - 'id' - 'created_at' - 'updated_at' - 'request_id' - 'last_active' FROM {} t "
"ORDER BY (to_jsonb(t) - 'id' - 'created_at' - 'updated_at' - 'request_id' - 'last_active')::text"
).format(sql.Identifier(table))
).fetchall()
]
for table in (*_ENTITY_TABLES, *_DAILY_TABLES)
}
def _reset(url: str) -> None:
with psycopg.connect(url, autocommit=True) as connection:
for table in _ENTITY_TABLES:
connection.execute(sql.SQL("UPDATE {} SET spend=0").format(sql.Identifier(table)))
for table in (*_DAILY_TABLES, "LiteLLM_SpendLogs", "LiteLLM_SpendLogDelivery"):
connection.execute(sql.SQL("TRUNCATE {}").format(sql.Identifier(table)))
connection.execute('UPDATE "LiteLLM_VerificationToken" SET total_spend=0')
connection.execute('UPDATE "LiteLLM_TeamMembership" SET total_spend=0')
async def _assert_legacy_database_parity(
parity_database: str,
monkeypatch: pytest.MonkeyPatch,
status: str,
origin: str | None,
cost: float,
retention: str,
reset_kind: str | None = None,
correction_order: str | None = None,
toggle_after_capture: bool = False,
fallback_narrowing: bool = False,
failing_table: str | None = None,
organization_id: str | None = "org",
export_url: str | None = None,
export_failure: bool = False,
):
monkeypatch.setitem(
litellm.model_cost,
"ledger-test",
{
"input_cost_per_token": 0.002,
"output_cost_per_token": 0.004,
"cache_read_input_token_cost": 0.0005,
"cache_creation_input_token_cost": 0.003,
"litellm_provider": "openai",
"mode": "chat",
"max_tokens": 4096,
},
)
if fallback_narrowing:
monkeypatch.setattr(proxy_server, "llm_router", litellm.Router(model_list=[{
"model_name": "ledger-test",
"litellm_params": {"model": "openai/ledger-test", "api_key": "test"},
"model_info": {"id": "deployment", "access_groups": ["group"]},
}]))
with psycopg.connect(parity_database, autocommit=True) as connection:
connection.execute(
"INSERT INTO \"LiteLLM_ModelAccessGroupBudgetTable\" (access_group_name) VALUES ('unserved-group')"
)
monkeypatch.setenv("DATABASE_URL", parity_database)
client = PrismaClient(database_url=parity_database, proxy_logging_obj=proxy_server.proxy_logging_obj)
client.spend_log_transactions = []
client.model_usage_transactions = []
monkeypatch.setattr(proxy_server, "prisma_client", client)
monkeypatch.setattr(proxy_server, "disable_spend_logs", False)
await client.db.connect()
results = []
try:
for path in ("legacy", "ledger"):
_reset(parity_database)
if reset_kind is not None:
_prime_reset(parity_database, reset_kind)
monkeypatch.setattr(proxy_server, "general_settings", {"use_spend_logs_ledger": path == "ledger"})
monkeypatch.setattr(proxy_server, "disable_spend_logs", path == "ledger" and retention == "lean")
writer = DBSpendUpdateWriter()
monkeypatch.setattr(proxy_server.proxy_logging_obj, "db_spend_update_writer", writer)
monkeypatch.setattr(proxy_server, "user_api_key_cache", UserApiKeyCache())
monkeypatch.setattr(proxy_server, "spend_counter_cache", DualCache())
for cache_key in ("2c70e12b7a0646f92279f427c7b38e7334d8e5389cff167a1dc30e73f826b683", "team_id:team"):
await proxy_server.user_api_key_cache.async_set_cache(
key=cache_key,
value={
"budget_limits": [
{"budget_duration": "1d", "max_budget": 100, "reset_at": "2026-11-04T00:00:00+00:00"}
]
},
)
request_kwargs = {
"model": "ledger-test",
"custom_llm_provider": "openai",
"call_type": "acompletion",
"litellm_call_id": "request",
"standard_logging_object": {
"model": "ledger-test",
"model_group": "ledger-test",
"metadata": {
"user_api_key_hash": "2c70e12b7a0646f92279f427c7b38e7334d8e5389cff167a1dc30e73f826b683",
"usage_object": {
"prompt_tokens": 10,
"completion_tokens": 5,
"cache_read_input_tokens": 4,
"cache_creation_input_tokens": 1,
},
},
"model_map_information": {},
"hidden_params": {},
"request_tags": ["tag"],
"model_id": "deployment",
"response_cost": cost,
"autorouter_savings": 0.125,
"guardrail_information": [
{
"guardrail_id": "guard",
"guardrail_name": "guard",
"guardrail_status": "success",
"guardrail_usage": {"text": 2},
"guardrail_cost_by_unit": {"text": 0.02},
"guardrail_cost_in_spend": True,
}
],
},
"agent_id": "agent",
"user": "end-user",
"litellm_params": {
"metadata": {
"user_api_key": "2c70e12b7a0646f92279f427c7b38e7334d8e5389cff167a1dc30e73f826b683",
"user_api_key_model_max_budget": {"ledger-test": {"max_budget": 100, "budget_duration": "1d"}},
"user_api_key_user_id": "user",
"user_api_key_team_id": "team",
"user_api_key_org_id": organization_id,
"user_api_key_project_id": "project",
"user_api_key_end_user_id": "end-user",
"tags": ["tag"],
"user_api_key_matched_model_access_groups": ["group", "unserved-group"] if fallback_narrowing else ["group"],
"model_info": {"id": "deployment"},
"litellm_gateway_injected_cache": "deployment",
"compression_savings": {"tokens_before": 20, "tokens_after": 10, "tokens_saved": 10},
"status": status,
**({BILLED_RETRY_ATTEMPT_METADATA_KEY: True} if origin == "billed_retry" else {}),
**({INTERNAL_CALL_ORIGIN_METADATA_KEY: origin} if origin == "auto_router" else {}),
},
"user": "end-user",
},
}
limiter = PROXY_VirtualKeyModelMaxBudgetLimiter(
dual_cache=proxy_server.spend_counter_cache,
clock=lambda: _NOW.timestamp(),
shared_windows=DatabaseSharedWindows(prisma_client_source=lambda: client),
)
if status == "success":
await limiter.async_log_success_event(request_kwargs, None, _NOW, _NOW)
charged = await writer.update_database(
token="2c70e12b7a0646f92279f427c7b38e7334d8e5389cff167a1dc30e73f826b683",
user_id="user",
end_user_id="end-user",
team_id="team",
org_id=organization_id,
project_id="project",
kwargs=request_kwargs,
completion_response=ModelResponse(
id="request", model="ledger-test", usage=Usage(prompt_tokens=10, completion_tokens=5)
),
start_time=_NOW,
end_time=_NOW,
response_cost=cost,
)
assert charged
await proxy_server.increment_spend_counters(
token="2c70e12b7a0646f92279f427c7b38e7334d8e5389cff167a1dc30e73f826b683",
team_id="team",
user_id="user",
response_cost=cost,
request_started_at=_NOW,
**({"windows_from_ledger": True} if path == "ledger" else {}),
)
await drain_logging_tasks()
rows = tuple(client.spend_log_transactions)
client.spend_log_transactions = []
assert len(rows) == 1
if path == "ledger" and retention == "lean":
assert rows[0]["accounting_log_disabled"] is True
frozen = rows[0]["accounting_payload"]
if isinstance(frozen, str):
frozen = json.loads(frozen)
assert not {"messages", "response", "proxy_server_request"}.intersection(frozen)
stored_rows = (
tuple(spend_log_row_with_retained_metadata(row, SpendLogsMetadataFields(include=())) for row in rows)
if retention == "stripped"
else rows
)
if toggle_after_capture:
for enabled in (True, False, True):
monkeypatch.setattr(proxy_server, "general_settings", {"use_spend_logs_ledger": enabled})
await SpendLogsRepository(client).insert_with_deliveries(stored_rows)
elif path == "ledger" and export_url is not None:
import httpx
from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler
from litellm.proxy.utils import ProxyUpdateSpend
monkeypatch.setenv("SPEND_LOGS_URL", export_url)
handler = AsyncHTTPHandler(timeout=10)
wire_rows = [
{key: value.isoformat() if isinstance(value, datetime) else value for key, value in row.items()}
for row in stored_rows
]
try:
if export_failure:
with pytest.raises(httpx.HTTPStatusError):
await ProxyUpdateSpend.update_spend_logs(0, client, handler, proxy_server.proxy_logging_obj, wire_rows)
else:
await ProxyUpdateSpend.update_spend_logs(0, client, handler, proxy_server.proxy_logging_obj, wire_rows)
finally:
await handler.close()
else:
await SpendLogsRepository(client).insert_with_deliveries(stored_rows)
if path == "ledger" and (retention == "lean" or export_url is not None):
assert await client.writer_db.query_raw('SELECT COUNT(*) AS count FROM "LiteLLM_SpendLogs"') == [{"count": 0}]
if reset_kind is not None:
await _apply_reset(reset_kind, client)
if correction_order == "before":
await _publish_savings_correction(client, stored_rows[0])
if path != "ledger":
await writer._commit_spend_updates_to_db_without_redis_buffer(client, 0, proxy_server.proxy_logging_obj)
await writer.commit_daily_tag_spend_to_db(client, 0, proxy_server.proxy_logging_obj)
await flush_model_usage_transactions(prisma_client=client, transactions=client.model_usage_transactions)
client.model_usage_transactions = []
await process_spend_logs_guardrail_usage(client, rows, pending=PendingRollups())
else:
async def apply(transaction, deliveries, writer: DBSpendUpdateWriter = writer):
await apply_deliveries(
transaction,
deliveries,
prisma_client=client,
writer=writer,
proxy_logging_obj=proxy_server.proxy_logging_obj,
)
if failing_table is not None:
before_failure = _snapshot(parity_database)
with psycopg.connect(parity_database, autocommit=True) as connection:
connection.execute(sql.SQL('ALTER TABLE {} ADD CONSTRAINT reject_spend CHECK (spend = 0)').format(sql.Identifier(failing_table)))
failed = await AccountingDeliveryRepository(client.writer_db).apply_pending(apply)
assert (failed.applied, failed.failed) == (0, 1)
assert _snapshot(parity_database) == before_failure
with psycopg.connect(parity_database, autocommit=True) as connection:
assert connection.execute('SELECT state::text, attempts FROM "LiteLLM_SpendLogDelivery"').fetchall() == [("pending", 1)]
connection.execute(sql.SQL('ALTER TABLE {} DROP CONSTRAINT reject_spend').format(sql.Identifier(failing_table)))
connection.execute('UPDATE "LiteLLM_SpendLogDelivery" SET next_attempt_at=CURRENT_TIMESTAMP')
result = await AccountingDeliveryRepository(client.writer_db).apply_pending(apply)
assert result.applied == 1, result
await writer._commit_spend_updates_to_db_without_redis_buffer(client, 0, proxy_server.proxy_logging_obj)
if correction_order == "after":
await _publish_savings_correction(client, stored_rows[0])
results.append(_snapshot(parity_database))
differences = {
(index, table): (results[0][table], result[table])
for index, result in enumerate(results[1:], 1)
for table in results[0]
if results[0][table] != result[table]
}
assert not differences, differences
prior_spend = 5 if reset_kind is not None and reset_kind != "scheduled" else 0
assert results[-1]["LiteLLM_UserTable"][0]["spend"] == cost + prior_spend
daily = results[-1]["LiteLLM_DailyUserSpend"][0]
assert daily["compression_savings_spend"] > 0, results[-1]["LiteLLM_DailyUserSpend"]
assert daily["prompt_caching_savings_spend"] != 0
assert daily["gateway_injected_caching_savings_spend"] != 0
assert daily["autorouter_savings_spend"] == pytest.approx(
(0 if origin == "auto_router" else 0.125) + (0.2 if correction_order else 0)
)
group_spend = {row["access_group_name"]: row["spend"] for row in results[-1]["LiteLLM_ModelAccessGroupBudgetTable"]}
assert group_spend == {"group": cost + prior_spend, **({"unserved-group": prior_spend} if fallback_narrowing else {})}
assert results[-1]["LiteLLM_DailyGuardrailUsageUnits"]
windows = results[-1]["LiteLLM_BudgetWindowSpend"]
assert len(windows) == (2 if cost else 0) + (1 if status == "success" else 0)
assert all(row["spend"] == cost for row in windows)
if reset_kind == "window_rollover":
model_window = next(row for row in windows if row["entity_type"] == "model_max_budget")
assert model_window["window_start"].startswith("2026-11-04")
if reset_kind in ("key", "global", "scheduled"):
assert results[-1]["LiteLLM_VerificationToken"][0]["spend"] == cost
if reset_kind in ("global", "scheduled"):
assert results[-1]["LiteLLM_TeamTable"][0]["spend"] == cost
if reset_kind == "team_member":
assert results[-1]["LiteLLM_TeamMembership"][0]["spend"] == cost
finally:
await client.db.disconnect()
@pytest.mark.parametrize(
"status,origin,cost",
[
("success", None, 0.25),
("failure", None, 0.25),
("success", None, 0.0),
("success", "auto_router", 0.25),
("failure", "billed_retry", 0.25),
],
)
@pytest.mark.parametrize("retention", ["full", "stripped", "lean"])
@pytest.mark.asyncio
async def test_stored_ledger_matches_real_legacy_database_updates(
parity_database: str, monkeypatch: pytest.MonkeyPatch, status: str, origin: str | None, cost: float, retention: str
):
await _assert_legacy_database_parity(parity_database, monkeypatch, status, origin, cost, retention)
@pytest.mark.parametrize("retention", ["full", "stripped", "lean"])
@pytest.mark.asyncio
async def test_missing_organization_matches_legacy_daily_rollups(parity_database, monkeypatch, retention):
await _assert_legacy_database_parity(
parity_database, monkeypatch, "success", None, 0.25, retention, organization_id=None
)
with psycopg.connect(parity_database) as connection:
assert connection.execute('SELECT count(*) FROM "LiteLLM_DailyOrganizationSpend"').fetchone() == (0,)
@pytest.mark.parametrize("reset_kind", ["scheduled", "key", "team_member", "global", "window_rollover"])
@pytest.mark.asyncio
async def test_pending_delivery_after_reset_matches_queued_legacy_spend(
parity_database: str, monkeypatch: pytest.MonkeyPatch, reset_kind: str
):
await _assert_legacy_database_parity(parity_database, monkeypatch, "success", None, 0.25, "full", reset_kind)
def _prime_reset(url: str, reset_kind: str) -> None:
with psycopg.connect(url, autocommit=True) as connection:
for table in _ENTITY_TABLES:
connection.execute(sql.SQL("UPDATE {} SET spend=5").format(sql.Identifier(table)))
if reset_kind == "scheduled":
for table in ("LiteLLM_VerificationToken", "LiteLLM_UserTable", "LiteLLM_TeamTable", "LiteLLM_BudgetTable"):
connection.execute(
sql.SQL("UPDATE {} SET budget_duration='1d', budget_reset_at='2026-11-01'").format(
sql.Identifier(table)
)
)
connection.execute("UPDATE \"LiteLLM_ModelAccessGroupBudgetTable\" SET budget_id='budget'")
async def _apply_reset(reset_kind: str, client: PrismaClient) -> None:
from litellm.proxy._types import ResetSpendRequest, UserAPIKeyAuth, LitellmUserRoles
from litellm.proxy.common_utils.reset_budget_job import ResetBudgetJob
from litellm.proxy.management_endpoints.key_management_endpoints import reset_key_spend_fn
from litellm.proxy.management_endpoints.team_endpoints import reset_team_member_spend_fn
from litellm.proxy.spend_tracking.spend_management_endpoints import global_spend_reset
admin = UserAPIKeyAuth(user_id="admin", user_role=LitellmUserRoles.PROXY_ADMIN)
if reset_kind == "window_rollover":
from litellm.proxy.db.budget_window_spend_writer import roll_window_spend_row
windows = await client.writer_db.query_raw('SELECT * FROM "LiteLLM_BudgetWindowSpend"')
assert windows
for window in windows:
await roll_window_spend_row(
client, window["entity_type"], window["entity_id"], window["window_duration"], _NOW + timedelta(days=2)
)
elif reset_kind == "global":
await global_spend_reset()
elif reset_kind == "key":
await reset_key_spend_fn(
key="2c70e12b7a0646f92279f427c7b38e7334d8e5389cff167a1dc30e73f826b683", data=ResetSpendRequest(reset_to=0), user_api_key_dict=admin, litellm_changed_by=None
)
elif reset_kind == "team_member":
await reset_team_member_spend_fn(
team_id="team", user_id="user", data=ResetSpendRequest(reset_to=0), user_api_key_dict=admin
)
else:
await ResetBudgetJob(proxy_server.proxy_logging_obj, client).reset_budget()
@pytest.mark.parametrize("correction_order", ["before", "after"])
@pytest.mark.asyncio
async def test_baseline_correction_order_preserves_frozen_request_savings(
parity_database: str, monkeypatch: pytest.MonkeyPatch, correction_order: str
):
await _assert_legacy_database_parity(
parity_database, monkeypatch, "success", None, 0.25, "full", correction_order=correction_order
)
async def _publish_savings_correction(client: PrismaClient, row) -> None:
from litellm.proxy.route_llm_request import ROUTE_ENDPOINT_MAPPING
from litellm.proxy.db.baseline_accounting import (
BaselinePublication,
DailyBaselineAttribution,
DailyBaselineTarget,
_Change,
_publish,
)
metadata_before = (
await client.writer_db.query_raw(
'SELECT metadata FROM "LiteLLM_SpendLogs" WHERE request_id=$1', row["request_id"]
)
)[0]["metadata"]
if isinstance(metadata_before, str):
metadata_before = json.loads(metadata_before)
change = _Change(
request_id=row["request_id"],
publication=BaselinePublication(
comparison_id="autorouter-baseline:v3:" + "a" * 64,
comparison_started_at=_NOW.timestamp(),
status="estimated",
reason="modeled",
provenance="modeled",
actual_spend=0.25,
baseline_spend=0.575,
),
api_key=row["api_key"],
session_id="session",
router_name="router",
baseline_model="ledger-test",
covered_delta=0,
actual_delta=0.0,
savings_delta=0.2,
daily=DailyBaselineAttribution(
date=_NOW.date().isoformat(),
api_key=row["api_key"],
model=row["model"],
custom_llm_provider=row["custom_llm_provider"],
model_group=row["model_group"],
endpoint=ROUTE_ENDPOINT_MAPPING.get(row["call_type"]),
targets=tuple(
DailyBaselineTarget(entity=entity, entity_id=identity)
for entity, identity in (
("user", "user"),
("team", "team"),
("org", "org"),
("end_user", "end-user"),
("agent", "agent"),
("tag", "tag"),
)
),
),
)
async with client.writer_db.tx() as transaction:
await _publish(transaction, (change,))
metadata_after = (
await client.writer_db.query_raw(
'SELECT metadata FROM "LiteLLM_SpendLogs" WHERE request_id=$1', row["request_id"]
)
)[0]["metadata"]
if isinstance(metadata_after, str):
metadata_after = json.loads(metadata_after)
assert metadata_after["autorouter_savings"] == pytest.approx(0.325)
if "accounting_payload" in row:
delivery = (await client.writer_db.query_raw(
'SELECT accounting_payload FROM "LiteLLM_SpendLogDelivery" WHERE request_id=$1', row["request_id"]
))[0]["accounting_payload"]
assert delivery["metadata"]["accounting_savings"]["autorouter"] == pytest.approx(0.125)
@pytest.mark.asyncio
async def test_flag_changes_do_not_reclassify_or_reapply_buffered_rows(
parity_database: str,
monkeypatch: pytest.MonkeyPatch,
):
await _assert_legacy_database_parity(
parity_database,
monkeypatch,
"success",
None,
0.25,
"stripped",
toggle_after_capture=True,
)
@pytest.mark.parametrize("entity_type", ["key", "team"])
@pytest.mark.asyncio
async def test_window_seed_excludes_pending_and_parked_but_preserves_legacy_cutoff(
parity_database: str,
monkeypatch: pytest.MonkeyPatch,
entity_type: str,
):
from datetime import timedelta
from litellm.proxy.db.budget_window_spend_writer import spend_logs_seed_totals, commit_window_spend_updates
monkeypatch.setenv("DATABASE_URL", parity_database)
client = PrismaClient(database_url=parity_database, proxy_logging_obj=proxy_server.proxy_logging_obj)
await client.db.connect()
try:
for request_id, cost, offset in (
("old-legacy", 2.0, -1),
("current-legacy", 5.0, 0),
("applied", 3.0, 1),
("pending", 7.0, 0),
("parked", 11.0, 0),
):
await client.writer_db.execute_raw(
'INSERT INTO "LiteLLM_SpendLogs" '
'(request_id,call_type,api_key,team_id,spend,"startTime","endTime") '
"VALUES ($1,'acompletion','key','team',$2::float8,$3::timestamp,$3::timestamp)",
request_id,
cost,
_NOW + timedelta(seconds=offset),
)
for request_id, state in (("applied", "applied"), ("pending", "pending"), ("parked", "parked")):
await client.writer_db.execute_raw(
'INSERT INTO "LiteLLM_SpendLogDelivery" (request_id,state,accounting_payload,is_batch) VALUES ($1,$2::"AccountingDeliveryState",$$ {} $$::jsonb,false)',
request_id,
state,
)
start = _NOW - timedelta(hours=1)
totals = await spend_logs_seed_totals(client, entity_type, entity_type, start, _NOW)
assert totals is not None and totals.total == 10.0 and totals.before_batch == 5.0
unbounded = await spend_logs_seed_totals(client, entity_type, entity_type, start, None)
assert unbounded is not None and unbounded.total == unbounded.before_batch == 10.0
await commit_window_spend_updates(
client,
(
{
"entity_type": entity_type,
"entity_id": entity_type,
"window_duration": "1d",
"window_start": start.isoformat(),
"started_at": _NOW.isoformat(),
"spend": 5.0,
},
),
)
rows = await client.writer_db.query_raw('SELECT spend FROM "LiteLLM_BudgetWindowSpend"')
assert rows[0]["spend"] == 10.0
finally:
await client.db.disconnect()
@pytest.mark.parametrize("disable_logs", [False, True])
@pytest.mark.asyncio
async def test_batch_claim_failure_queues_an_atomic_retry_and_repeated_retrieve_does_not_charge(
parity_database: str, monkeypatch: pytest.MonkeyPatch, disable_logs: bool
):
from litellm.accounting.worker import flush_accounting_deliveries
monkeypatch.setenv("DATABASE_URL", parity_database)
client = PrismaClient(database_url=parity_database, proxy_logging_obj=proxy_server.proxy_logging_obj)
client.spend_log_transactions = []
writer = DBSpendUpdateWriter()
monkeypatch.setattr(proxy_server, "prisma_client", client)
monkeypatch.setattr(proxy_server, "general_settings", {"use_spend_logs_ledger": True})
monkeypatch.setattr(proxy_server, "disable_spend_logs", disable_logs)
monkeypatch.setattr(proxy_server, "user_api_key_cache", UserApiKeyCache())
await client.db.connect()
try:
with psycopg.connect(parity_database, autocommit=True) as connection:
connection.execute(
'ALTER TABLE "LiteLLM_SpendLogDelivery" ADD CONSTRAINT reject_batch '
"CHECK (request_id <> 'batch_batch_cost')"
)
assert await _retrieve_batch(writer, 0.25)
with psycopg.connect(parity_database) as connection:
assert connection.execute('SELECT COUNT(*) FROM "LiteLLM_SpendLogs"').fetchone() == (0,)
assert connection.execute('SELECT COUNT(*) FROM "LiteLLM_SpendLogDelivery"').fetchone() == (0,)
assert len(client.spend_log_transactions) == 1
queued = tuple(client.spend_log_transactions)
assert "accounting_payload" in queued[0]
with psycopg.connect(parity_database, autocommit=True) as connection:
connection.execute('ALTER TABLE "LiteLLM_SpendLogDelivery" DROP CONSTRAINT reject_batch')
assert await SpendLogsRepository(client).insert_with_deliveries(queued) == 1
assert await _retrieve_batch(writer, 0.25) is False
await flush_accounting_deliveries(writer, client, proxy_server.proxy_logging_obj)
await flush_accounting_deliveries(writer, client, proxy_server.proxy_logging_obj)
with psycopg.connect(parity_database) as connection:
assert connection.execute('SELECT spend FROM "LiteLLM_VerificationToken" WHERE token=\'2c70e12b7a0646f92279f427c7b38e7334d8e5389cff167a1dc30e73f826b683\'').fetchone() == (0.25,)
assert connection.execute('SELECT spend FROM "LiteLLM_UserTable" WHERE user_id=\'user\'').fetchone() == (0.25,)
assert connection.execute('SELECT state::text FROM "LiteLLM_SpendLogDelivery"').fetchall() == [("applied",)]
assert connection.execute('SELECT COUNT(*) FROM "LiteLLM_SpendLogs"').fetchone() == (int(not disable_logs),)
finally:
await client.db.disconnect()
@pytest.mark.asyncio
async def test_failed_claim_over_a_legacy_zero_batch_row_still_charges_it_once(
parity_database: str, monkeypatch: pytest.MonkeyPatch
):
from litellm.accounting.worker import flush_accounting_deliveries
monkeypatch.setenv("DATABASE_URL", parity_database)
client = PrismaClient(database_url=parity_database, proxy_logging_obj=proxy_server.proxy_logging_obj)
client.spend_log_transactions = []
client.model_usage_transactions = []
writer = DBSpendUpdateWriter()
monkeypatch.setattr(proxy_server, "prisma_client", client)
monkeypatch.setattr(proxy_server, "general_settings", {"use_spend_logs_ledger": False})
monkeypatch.setattr(proxy_server, "disable_spend_logs", False)
monkeypatch.setattr(proxy_server, "user_api_key_cache", UserApiKeyCache())
await client.db.connect()
try:
assert await _retrieve_batch(writer, 0)
await drain_logging_tasks()
await SpendLogsRepository(client).insert_with_deliveries(tuple(client.spend_log_transactions))
client.spend_log_transactions = []
monkeypatch.setattr(proxy_server, "general_settings", {"use_spend_logs_ledger": True})
with psycopg.connect(parity_database, autocommit=True) as connection:
assert connection.execute(
'SELECT spend FROM "LiteLLM_SpendLogs" WHERE request_id=\'batch_batch_cost\''
).fetchall() == [(0.0,)]
connection.execute('ALTER TABLE "LiteLLM_SpendLogDelivery" RENAME TO "LiteLLM_SpendLogDelivery_unavailable"')
assert await _retrieve_batch(writer, 0.25)
queued = tuple(client.spend_log_transactions)
assert ["accounting_payload" in row for row in queued] == [True]
with psycopg.connect(parity_database, autocommit=True) as connection:
connection.execute('ALTER TABLE "LiteLLM_SpendLogDelivery_unavailable" RENAME TO "LiteLLM_SpendLogDelivery"')
assert await SpendLogsRepository(client).insert_with_deliveries(queued) == 1
await flush_accounting_deliveries(writer, client, proxy_server.proxy_logging_obj)
assert await _retrieve_batch(writer, 0.25) is False
await flush_accounting_deliveries(writer, client, proxy_server.proxy_logging_obj)
with psycopg.connect(parity_database) as connection:
assert connection.execute('SELECT spend FROM "LiteLLM_VerificationToken" WHERE token=\'2c70e12b7a0646f92279f427c7b38e7334d8e5389cff167a1dc30e73f826b683\'').fetchone() == (0.25,)
assert connection.execute(
'SELECT spend FROM "LiteLLM_SpendLogs" WHERE request_id=\'batch_batch_cost\''
).fetchall() == [(0.0,)]
assert connection.execute('SELECT state::text FROM "LiteLLM_SpendLogDelivery"').fetchall() == [("applied",)]
finally:
await client.db.disconnect()
@pytest.mark.asyncio
async def test_worker_exposes_invalid_accounting_as_delayed_then_parked_work(
parity_database: str, monkeypatch: pytest.MonkeyPatch
):
from prometheus_client import REGISTRY
from litellm.accounting.worker import flush_accounting_deliveries
monkeypatch.setenv("DATABASE_URL", parity_database)
client = PrismaClient(database_url=parity_database, proxy_logging_obj=proxy_server.proxy_logging_obj)
writer = DBSpendUpdateWriter()
await client.db.connect()
try:
with psycopg.connect(parity_database, autocommit=True) as connection:
connection.execute(
'INSERT INTO "LiteLLM_SpendLogDelivery" (request_id, created_at, accounting_payload, is_batch) '
"VALUES ('invalid-accounting', CURRENT_TIMESTAMP - INTERVAL '1 hour', "
'$$ {"metadata": {"accounting_windows": [{}]}} $$::jsonb, false)'
)
await flush_accounting_deliveries(writer, client, proxy_server.proxy_logging_obj)
assert REGISTRY.get_sample_value("litellm_accounting_pending") == 1
assert REGISTRY.get_sample_value("litellm_accounting_parked") == 0
with psycopg.connect(parity_database, autocommit=True) as connection:
assert connection.execute(
'SELECT state::text, attempts, last_error FROM "LiteLLM_SpendLogDelivery"'
).fetchall() == [("pending", 1, "KeyError")]
connection.execute(
'UPDATE "LiteLLM_SpendLogDelivery" SET attempts=4, next_attempt_at=CURRENT_TIMESTAMP'
)
await flush_accounting_deliveries(writer, client, proxy_server.proxy_logging_obj)
assert REGISTRY.get_sample_value("litellm_accounting_pending") == 0
assert REGISTRY.get_sample_value("litellm_accounting_parked") == 1
with psycopg.connect(parity_database) as connection:
assert connection.execute(
'SELECT state::text, attempts, last_error FROM "LiteLLM_SpendLogDelivery"'
).fetchall() == [("parked", 5, "KeyError")]
assert connection.execute('SELECT spend FROM "LiteLLM_UserTable" WHERE user_id=\'user\'').fetchone() == (0,)
finally:
await client.db.disconnect()
@pytest.mark.asyncio
async def test_fallback_charges_only_groups_declared_by_the_served_deployment(
parity_database: str, monkeypatch: pytest.MonkeyPatch
):
await _assert_legacy_database_parity(
parity_database, monkeypatch, "success", None, 0.25, "stripped", fallback_narrowing=True
)
@pytest.mark.asyncio
async def test_worker_skips_another_leader_and_releases_its_redis_lock_after_retry(
parity_database: str, monkeypatch: pytest.MonkeyPatch
):
from litellm.accounting.worker import flush_accounting_deliveries
from litellm.caching.redis_cache import RedisCache
from litellm.proxy.db.db_transaction_queue.pod_lock_manager import PodLockManager
monkeypatch.setenv("DATABASE_URL", parity_database)
cache = RedisCache(host=os.environ["REDIS_HOST"], port=int(os.environ["REDIS_PORT"]), namespace=uuid.uuid4().hex)
other_leader = PodLockManager(cache)
writer = DBSpendUpdateWriter(redis_cache=cache)
writer.pod_lock_manager.redis_cache = cache
client = PrismaClient(database_url=parity_database, proxy_logging_obj=proxy_server.proxy_logging_obj)
await client.db.connect()
try:
with psycopg.connect(parity_database, autocommit=True) as connection:
connection.execute('INSERT INTO "LiteLLM_SpendLogDelivery" (request_id, accounting_payload, is_batch) VALUES ($$invalid-row$$, $$ {"metadata": {"accounting_windows": [{}]}} $$::jsonb, false)')
assert await other_leader.acquire_lock(cronjob_id="accounting_delivery", allow_reentrant=False)
await flush_accounting_deliveries(writer, client, proxy_server.proxy_logging_obj)
with psycopg.connect(parity_database) as connection:
assert connection.execute('SELECT attempts FROM "LiteLLM_SpendLogDelivery"').fetchall() == [(0,)]
await other_leader.release_lock(cronjob_id="accounting_delivery")
await flush_accounting_deliveries(writer, client, proxy_server.proxy_logging_obj)
with psycopg.connect(parity_database) as connection:
assert connection.execute('SELECT attempts FROM "LiteLLM_SpendLogDelivery"').fetchall() == [(1,)]
assert await other_leader.acquire_lock(cronjob_id="accounting_delivery", allow_reentrant=False)
finally:
await other_leader.release_lock(cronjob_id="accounting_delivery")
await client.db.disconnect()
await cache.disconnect()
async def _retrieve_batch(writer: DBSpendUpdateWriter, cost: float) -> bool:
return await writer.update_database(
token="2c70e12b7a0646f92279f427c7b38e7334d8e5389cff167a1dc30e73f826b683", user_id="user", end_user_id=None, team_id="team", org_id=None,
kwargs={
"model": "ledger-test", "call_type": "aretrieve_batch", "litellm_call_id": "batch",
"litellm_params": {"metadata": {"status": "success", "user_api_key": "2c70e12b7a0646f92279f427c7b38e7334d8e5389cff167a1dc30e73f826b683"}},
},
completion_response={"id": "batch", "status": "completed"},
start_time=_NOW, end_time=_NOW, response_cost=cost,
)
@pytest.mark.parametrize("ledger_after_zero_row,delivery_unavailable", [(False, False), (True, False), (True, True)])
@pytest.mark.asyncio
async def test_zero_cost_legacy_batch_row_is_charged_once_across_a_flag_change(
parity_database: str, monkeypatch: pytest.MonkeyPatch, ledger_after_zero_row: bool, delivery_unavailable: bool
):
from litellm.accounting.worker import flush_accounting_deliveries
monkeypatch.setenv("DATABASE_URL", parity_database)
client = PrismaClient(database_url=parity_database, proxy_logging_obj=proxy_server.proxy_logging_obj)
client.spend_log_transactions = []
client.model_usage_transactions = []
writer = DBSpendUpdateWriter()
monkeypatch.setattr(proxy_server, "prisma_client", client)
monkeypatch.setattr(proxy_server, "general_settings", {"use_spend_logs_ledger": False})
monkeypatch.setattr(proxy_server, "disable_spend_logs", False)
await client.db.connect()
try:
assert await _retrieve_batch(writer, 0)
await drain_logging_tasks()
monkeypatch.setattr(proxy_server, "general_settings", {"use_spend_logs_ledger": ledger_after_zero_row})
assert await _retrieve_batch(writer, 0.25)
await drain_logging_tasks()
assert await _retrieve_batch(writer, 0.25) is False
with psycopg.connect(parity_database) as connection:
assert connection.execute('SELECT spend FROM "LiteLLM_UserTable" WHERE user_id=\'user\'').fetchone() == (0,)
assert connection.execute('SELECT spend FROM "LiteLLM_SpendLogs"').fetchall() == [
(0.0 if ledger_after_zero_row else 0.25,)
]
assert connection.execute('SELECT COUNT(*) FROM "LiteLLM_SpendLogDelivery"').fetchone() == (
int(ledger_after_zero_row),
)
if delivery_unavailable:
with psycopg.connect(parity_database, autocommit=True) as connection:
connection.execute('ALTER TABLE "LiteLLM_SpendLogDelivery" RENAME TO temporarily_unavailable_delivery')
try:
await writer.db_update_spend_transaction_handler(client, 0, proxy_server.proxy_logging_obj)
finally:
if delivery_unavailable:
with psycopg.connect(parity_database, autocommit=True) as connection:
connection.execute('ALTER TABLE temporarily_unavailable_delivery RENAME TO "LiteLLM_SpendLogDelivery"')
await flush_accounting_deliveries(writer, client, proxy_server.proxy_logging_obj)
with psycopg.connect(parity_database) as connection:
assert connection.execute('SELECT spend FROM "LiteLLM_UserTable" WHERE user_id=\'user\'').fetchone() == (0.25,)
assert connection.execute('SELECT spend, api_requests FROM "LiteLLM_DailyUserSpend"').fetchall() == [(0.25, 2)]
finally:
await client.db.disconnect()
@pytest.mark.parametrize("failing_table", [
"LiteLLM_UserTable", "LiteLLM_VerificationToken", "LiteLLM_TeamTable", "LiteLLM_TeamMembership",
"LiteLLM_OrganizationMembership", "LiteLLM_OrganizationTable", "LiteLLM_ProjectTable", "LiteLLM_AgentsTable", "LiteLLM_EndUserTable",
])
@pytest.mark.asyncio
async def test_destination_failure_rolls_back_all_earlier_updates_before_retry(
parity_database: str, monkeypatch: pytest.MonkeyPatch, failing_table: str
):
await _assert_legacy_database_parity(
parity_database, monkeypatch, "success", None, 0.25, "full", failing_table=failing_table
)
@pytest.mark.asyncio
async def test_spend_logs_cleanup_does_not_remove_pending_accounting(parity_database, monkeypatch):
from litellm.accounting.worker import flush_accounting_deliveries
from litellm.proxy.db.db_transaction_queue.spend_log_cleanup import SpendLogCleanup
monkeypatch.setenv("DATABASE_URL", parity_database)
client = PrismaClient(database_url=parity_database, proxy_logging_obj=proxy_server.proxy_logging_obj)
writer = DBSpendUpdateWriter()
monkeypatch.setattr(proxy_server, "prisma_client", client)
monkeypatch.setattr(proxy_server, "general_settings", {"use_spend_logs_ledger": True})
monkeypatch.setattr(proxy_server, "disable_spend_logs", False)
cleanup = SpendLogCleanup(clock=lambda: 0)
await client.db.connect()
try:
assert await _retrieve_batch(writer, 0.25)
delete_sql = 'DELETE FROM "LiteLLM_SpendLogs" WHERE request_id IN (SELECT request_id FROM "LiteLLM_SpendLogs" WHERE "startTime" < $1::timestamp LIMIT $2::integer)'
assert await cleanup._execute_delete_batch(client, delete_sql, _NOW + timedelta(days=1), "LiteLLM_SpendLogs", 60) == 1
await flush_accounting_deliveries(writer, client, proxy_server.proxy_logging_obj)
assert await _retrieve_batch(writer, 0.25) is False
with psycopg.connect(parity_database) as connection:
assert connection.execute('SELECT COUNT(*) FROM "LiteLLM_SpendLogs"').fetchone() == (0,)
assert connection.execute('SELECT spend FROM "LiteLLM_UserTable" WHERE user_id=$$user$$').fetchone() == (0.25,)
assert connection.execute('SELECT state::text FROM "LiteLLM_SpendLogDelivery"').fetchall() == [("applied",)]
finally:
await client.db.disconnect()
@pytest.mark.parametrize("mode", ["local", "url", "disabled"])
@pytest.mark.parametrize("receipt_state", ["pending", "parked", "applied", "retained"])
@pytest.mark.asyncio
async def test_ledger_charged_batch_is_not_charged_again_after_flag_disable(
parity_database: str, monkeypatch: pytest.MonkeyPatch, receipt_state: str, mode: str
):
from litellm.accounting.worker import flush_accounting_deliveries
monkeypatch.setenv("DATABASE_URL", parity_database)
client = PrismaClient(database_url=parity_database, proxy_logging_obj=proxy_server.proxy_logging_obj)
writer = DBSpendUpdateWriter()
monkeypatch.setattr(proxy_server, "prisma_client", client)
monkeypatch.setattr(proxy_server, "general_settings", {"use_spend_logs_ledger": True})
monkeypatch.setattr(proxy_server, "disable_spend_logs", mode == "disabled")
if mode == "url":
monkeypatch.setenv("SPEND_LOGS_URL", "http://127.0.0.1:1")
await client.db.connect()
try:
assert await _retrieve_batch(writer, 0)
assert await _retrieve_batch(writer, 0.25)
if receipt_state in ("applied", "retained"):
await flush_accounting_deliveries(writer, client, proxy_server.proxy_logging_obj)
with psycopg.connect(parity_database, autocommit=True) as connection:
if receipt_state == "retained":
connection.execute("UPDATE \"LiteLLM_SpendLogDelivery\" SET applied_at = CURRENT_TIMESTAMP - INTERVAL '400 days'")
if receipt_state == "parked":
connection.execute('UPDATE "LiteLLM_SpendLogDelivery" SET state=\'parked\'')
assert await AccountingDeliveryRepository(client.writer_db).cleanup_applied() == 0
monkeypatch.setattr(proxy_server, "general_settings", {"use_spend_logs_ledger": False})
assert await _retrieve_batch(writer, 0.25) is False
await flush_accounting_deliveries(writer, client, proxy_server.proxy_logging_obj)
with psycopg.connect(parity_database) as connection:
assert connection.execute('SELECT spend FROM "LiteLLM_SpendLogs"').fetchall() == (
[(0.25,)] if mode != "disabled" else []
)
expected_spend = 0 if receipt_state == "parked" else 0.25
expected_state = "parked" if receipt_state == "parked" else "applied"
assert connection.execute('SELECT spend FROM "LiteLLM_UserTable" WHERE user_id=\'user\'').fetchone() == (expected_spend,)
assert connection.execute('SELECT state::text FROM "LiteLLM_SpendLogDelivery"').fetchall() == [(expected_state,)]
finally:
await client.db.disconnect()
@pytest.mark.parametrize("disabled", [False, True])
@pytest.mark.parametrize("export_status", [200, 500])
@pytest.mark.asyncio
async def test_export_failure_does_not_change_committed_accounting(parity_database, monkeypatch, export_status, disabled):
requests = asyncio.Queue()
async def receive(reader, writer):
header = await reader.readuntil(b"\r\n\r\n")
length = next(int(line.split(b":", 1)[1]) for line in header.split(b"\r\n") if line.lower().startswith(b"content-length:"))
body = await reader.readexactly(length)
await requests.put(json.loads(body))
writer.write(f"HTTP/1.1 {export_status} Result\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{{}}".encode())
await writer.drain()
writer.close()
await writer.wait_closed()
server = await asyncio.start_server(receive, "127.0.0.1", 0)
try:
port = server.sockets[0].getsockname()[1]
await _assert_legacy_database_parity(
parity_database, monkeypatch, "success", None, 0.25, "lean" if disabled else "full",
export_url=f"http://127.0.0.1:{port}", export_failure=export_status == 500 and not disabled,
)
assert requests.qsize() == int(not disabled)
if disabled:
return
exported = await asyncio.wait_for(requests.get(), timeout=5)
assert len(exported) == 1
assert exported[0]["spend"] == 0.25
assert "accounting_payload" not in exported[0]
assert "accounting_log_disabled" not in exported[0]
finally:
server.close()
await server.wait_closed()
@pytest.mark.asyncio
async def test_spend_logs_url_without_an_export_client_keeps_local_logs_and_charges_once(
parity_database: str, monkeypatch: pytest.MonkeyPatch
):
from litellm.accounting.worker import flush_accounting_deliveries
from litellm.proxy.utils import ProxyUpdateSpend
monkeypatch.setenv("DATABASE_URL", parity_database)
monkeypatch.setenv("SPEND_LOGS_URL", "http://127.0.0.1:1")
client = PrismaClient(database_url=parity_database, proxy_logging_obj=proxy_server.proxy_logging_obj)
client.spend_log_transactions = []
client.model_usage_transactions = []
writer = DBSpendUpdateWriter()
monkeypatch.setattr(proxy_server, "prisma_client", client)
monkeypatch.setattr(proxy_server, "general_settings", {"use_spend_logs_ledger": True})
monkeypatch.setattr(proxy_server, "disable_spend_logs", False)
monkeypatch.setattr(proxy_server, "user_api_key_cache", UserApiKeyCache())
await client.db.connect()
try:
assert await writer.update_database(
token="2c70e12b7a0646f92279f427c7b38e7334d8e5389cff167a1dc30e73f826b683", user_id="user", end_user_id=None, team_id="team", org_id=None,
kwargs={
"model": "ledger-test", "call_type": "acompletion", "litellm_call_id": "url-request",
"litellm_params": {"metadata": {"status": "success", "user_api_key": "2c70e12b7a0646f92279f427c7b38e7334d8e5389cff167a1dc30e73f826b683"}},
},
completion_response=ModelResponse(
id="url-request", model="ledger-test", usage=Usage(prompt_tokens=10, completion_tokens=5)
),
start_time=_NOW, end_time=_NOW, response_cost=0.25,
)
await drain_logging_tasks()
rows = [
{key: value.isoformat() if isinstance(value, datetime) else value for key, value in row.items()}
for row in client.spend_log_transactions
]
client.spend_log_transactions = []
await ProxyUpdateSpend.update_spend_logs(0, client, None, proxy_server.proxy_logging_obj, rows)
await flush_accounting_deliveries(writer, client, proxy_server.proxy_logging_obj)
with psycopg.connect(parity_database) as connection:
assert connection.execute(
'SELECT spend FROM "LiteLLM_SpendLogs" WHERE request_id=\'url-request\''
).fetchall() == [(0.25,)]
assert connection.execute('SELECT state::text FROM "LiteLLM_SpendLogDelivery"').fetchall() == [("applied",)]
assert connection.execute('SELECT spend FROM "LiteLLM_VerificationToken" WHERE token=\'2c70e12b7a0646f92279f427c7b38e7334d8e5389cff167a1dc30e73f826b683\'').fetchone() == (0.25,)
finally:
await client.db.disconnect()
@contextlib.asynccontextmanager
async def _ledger_client(parity_database: str, monkeypatch: pytest.MonkeyPatch):
monkeypatch.setenv("DATABASE_URL", parity_database)
client = PrismaClient(database_url=parity_database, proxy_logging_obj=proxy_server.proxy_logging_obj)
client.spend_log_transactions = []
client.model_usage_transactions = []
monkeypatch.setattr(proxy_server, "prisma_client", client)
monkeypatch.setattr(proxy_server, "general_settings", {"use_spend_logs_ledger": True})
monkeypatch.setattr(proxy_server, "disable_spend_logs", False)
monkeypatch.setattr(proxy_server, "user_api_key_cache", UserApiKeyCache())
await client.db.connect()
try:
yield client
finally:
await client.db.disconnect()
async def _record_call(
writer: DBSpendUpdateWriter, call_id: str, *, token: str = "2c70e12b7a0646f92279f427c7b38e7334d8e5389cff167a1dc30e73f826b683", user: str = "user", tags: object = None
) -> None:
metadata = {"status": "success", "user_api_key": token, **({"tags": tags} if tags is not None else {})}
assert await writer.update_database(
token=token, user_id=user, end_user_id=None, team_id="team", org_id=None,
kwargs={
"model": "ledger-test", "call_type": "aembedding", "litellm_call_id": call_id,
"litellm_params": {"metadata": metadata},
},
completion_response=None, start_time=_NOW, end_time=_NOW, response_cost=0.25,
)
await drain_logging_tasks()
def _wire(rows) -> list[dict[str, object]]:
return [
{key: value.isoformat() if isinstance(value, datetime) else value for key, value in row.items()}
for row in rows
]
async def _flush(writer: DBSpendUpdateWriter, client: PrismaClient) -> None:
from litellm.accounting.worker import flush_accounting_deliveries
from litellm.proxy.utils import ProxyUpdateSpend
rows = _wire(client.spend_log_transactions)
client.spend_log_transactions = []
await ProxyUpdateSpend.update_spend_logs(0, client, None, proxy_server.proxy_logging_obj, rows)
await flush_accounting_deliveries(writer, client, proxy_server.proxy_logging_obj)
def _key_spend(parity_database: str) -> object:
with psycopg.connect(parity_database) as connection:
return connection.execute(
'SELECT spend FROM "LiteLLM_VerificationToken" WHERE token=%s', ("2c70e12b7a0646f92279f427c7b38e7334d8e5389cff167a1dc30e73f826b683",)
).fetchone()
@pytest.mark.asyncio
async def test_requests_sharing_a_client_call_id_are_each_charged_but_a_replay_is_not(
parity_database: str, monkeypatch: pytest.MonkeyPatch
):
async with _ledger_client(parity_database, monkeypatch) as client:
writer = DBSpendUpdateWriter()
await _record_call(writer, "shared-call-id")
await _record_call(writer, "shared-call-id")
buffered = _wire(client.spend_log_transactions)
await _flush(writer, client)
assert await SpendLogsRepository(client).insert_with_deliveries(buffered) == 0
await _flush(writer, client)
assert _key_spend(parity_database) == (0.5,)
with psycopg.connect(parity_database) as connection:
assert connection.execute(
'SELECT request_id, state::text FROM "LiteLLM_SpendLogDelivery"'
).fetchall() == [("shared-call-id", "applied"), ("shared-call-id", "applied")]
assert connection.execute('SELECT COUNT(*) FROM "LiteLLM_SpendLogs"').fetchone() == (1,)
@pytest.mark.asyncio
async def test_an_opaque_bearer_token_is_never_stored_in_a_delivery(
parity_database: str, monkeypatch: pytest.MonkeyPatch
):
async with _ledger_client(parity_database, monkeypatch) as client:
writer = DBSpendUpdateWriter()
await _record_call(writer, "opaque-call", token="opaque-bearer-secret")
await _flush(writer, client)
with psycopg.connect(parity_database) as connection:
stored = connection.execute('SELECT accounting_payload::text, state::text FROM "LiteLLM_SpendLogDelivery"').fetchall()
assert [state for _, state in stored] == ["applied"]
assert "opaque-bearer-secret" not in stored[0][0]
@pytest.mark.asyncio
async def test_an_evicted_spend_log_still_charges_its_request(parity_database: str, monkeypatch: pytest.MonkeyPatch):
from litellm.proxy.utils import enqueue_spend_logs
async with _ledger_client(parity_database, monkeypatch) as client:
writer = DBSpendUpdateWriter()
await _record_call(writer, "evicted-call")
await _record_call(writer, "kept-call")
queued = tuple(client.spend_log_transactions)
client.spend_log_transactions = []
await enqueue_spend_logs(client, queued, max_bytes=1)
assert [row.get("accounting_log_disabled") for row in client.spend_log_transactions] == [True, False]
await _flush(writer, client)
assert _key_spend(parity_database) == (0.5,)
with psycopg.connect(parity_database) as connection:
assert connection.execute('SELECT request_id FROM "LiteLLM_SpendLogs"').fetchall() == [("kept-call",)]
@pytest.mark.parametrize("isolation_budget", [5, 0], ids=["isolated", "budget_exhausted"])
@pytest.mark.asyncio
async def test_a_spend_log_postgres_rejects_still_charges_its_request_and_the_rest_of_the_batch(
parity_database: str, monkeypatch: pytest.MonkeyPatch, isolation_budget: int
):
from prisma.errors import DataError
from litellm.accounting.worker import flush_accounting_deliveries
from litellm.proxy.utils import _create_spend_logs_with_poison_isolation
class RejectsOneLog:
def __init__(self, repository: SpendLogsRepository) -> None:
self.repository = repository
async def insert_with_deliveries(self, rows, *, write_spend_logs: bool = True) -> int:
if any(row["request_id"] == "poison-call" and not row.get("accounting_log_disabled") for row in rows):
raise DataError({"user_facing_error": {"message": 'invalid byte sequence for encoding "UTF8": 0x00'}})
return await self.repository.insert_with_deliveries(rows, write_spend_logs=write_spend_logs)
async with _ledger_client(parity_database, monkeypatch) as client:
writer = DBSpendUpdateWriter()
await _record_call(writer, "poison-call")
await _record_call(writer, "clean-call")
rows = tuple(client.jsonify_object(row) for row in client.spend_log_transactions)
client.spend_log_transactions = []
await _create_spend_logs_with_poison_isolation(RejectsOneLog(SpendLogsRepository(client)), rows, isolation_budget)
await flush_accounting_deliveries(writer, client, proxy_server.proxy_logging_obj)
assert _key_spend(parity_database) == (0.5,)
with psycopg.connect(parity_database) as connection:
assert connection.execute('SELECT request_id FROM "LiteLLM_SpendLogs"').fetchall() == (
[("clean-call",)] if isolation_budget else []
)
assert connection.execute(
'SELECT state::text, COUNT(*) FROM "LiteLLM_SpendLogDelivery" GROUP BY 1'
).fetchall() == [("applied", 2)]
@pytest.mark.asyncio
async def test_a_request_with_a_non_text_tag_is_still_charged(parity_database: str, monkeypatch: pytest.MonkeyPatch):
async with _ledger_client(parity_database, monkeypatch) as client:
writer = DBSpendUpdateWriter()
await _record_call(writer, "tagged-call", tags=[None, "real-tag"])
await _flush(writer, client)
assert _key_spend(parity_database) == (0.25,)
with psycopg.connect(parity_database) as connection:
assert connection.execute(
'SELECT tag, spend FROM "LiteLLM_DailyTagSpend" WHERE tag=\'real-tag\''
).fetchall() == [("real-tag", 0.25)]
@pytest.mark.parametrize("threshold", ["count", "bytes"])
@pytest.mark.asyncio
async def test_retained_batch_storage_threshold_alerts_without_deleting_receipts(
parity_database: str, monkeypatch: pytest.MonkeyPatch, threshold: str
):
from types import SimpleNamespace
from unittest.mock import AsyncMock
from litellm.accounting.worker import flush_accounting_deliveries
from litellm.types.integrations.slack_alerting import AlertType
monkeypatch.setenv("DATABASE_URL", parity_database)
monkeypatch.setenv("LITELLM_ACCOUNTING_BATCH_DELIVERY_ALERT_COUNT", "1" if threshold == "count" else "1000000")
monkeypatch.setenv("LITELLM_ACCOUNTING_DELIVERY_ALERT_BYTES", "1" if threshold == "bytes" else "1073741824")
client = PrismaClient(database_url=parity_database, proxy_logging_obj=proxy_server.proxy_logging_obj)
alerts = SimpleNamespace(alerting_handler=AsyncMock())
await client.db.connect()
try:
with psycopg.connect(parity_database, autocommit=True) as connection:
connection.execute(
'INSERT INTO "LiteLLM_SpendLogDelivery" (request_id, state, applied_at, accounting_payload, is_batch) '
"VALUES ('old-batch', 'applied', CURRENT_TIMESTAMP - INTERVAL '400 days', '{}', true)"
)
await flush_accounting_deliveries(DBSpendUpdateWriter(), client, alerts)
with psycopg.connect(parity_database) as connection:
assert connection.execute('SELECT request_id, state::text FROM "LiteLLM_SpendLogDelivery"').fetchall() == [
("old-batch", "applied")
]
table_bytes = connection.execute(
'SELECT pg_total_relation_size(\'"LiteLLM_SpendLogDelivery"\')'
).fetchone()[0]
alerts.alerting_handler.assert_awaited_once_with(
message=f"Accounting delivery storage requires review. Retained batches=1, table bytes={table_bytes}.",
level="High", alert_type=AlertType.failed_tracking_spend,
)
finally:
await client.db.disconnect()
@pytest.mark.parametrize("backlog", ["retries", "expired"])
@pytest.mark.parametrize("batch_size", [1, 1100])
@pytest.mark.asyncio
async def test_worker_drains_recovered_and_expired_work_at_its_configured_capacity(
parity_database, monkeypatch, backlog, batch_size
):
from litellm.accounting.worker import flush_accounting_deliveries
monkeypatch.setenv("DATABASE_URL", parity_database)
monkeypatch.setenv("LITELLM_ACCOUNTING_DELIVERY_BATCH_SIZE", str(batch_size))
monkeypatch.setattr(proxy_server, "general_settings", {"use_spend_logs_ledger": True})
monkeypatch.setattr(proxy_server, "disable_spend_logs", False)
client = PrismaClient(database_url=parity_database, proxy_logging_obj=proxy_server.proxy_logging_obj)
writer = DBSpendUpdateWriter()
monkeypatch.setattr(proxy_server, "prisma_client", client)
await client.db.connect()
try:
assert await _retrieve_batch(writer, 0.25)
with psycopg.connect(parity_database, autocommit=True) as connection:
if backlog == "retries":
connection.execute(
'INSERT INTO "LiteLLM_SpendLogDelivery" (request_id, accounting_payload, is_batch, attempts) '
"SELECT 'retry-' || i, accounting_payload, false, 1 "
'FROM "LiteLLM_SpendLogDelivery" CROSS JOIN generate_series(1, 3) i'
)
else:
connection.execute(
'INSERT INTO "LiteLLM_SpendLogDelivery" (request_id, accounting_payload, is_batch, state, applied_at) '
"SELECT 'expired-' || i, '{}', false, 'applied', CURRENT_TIMESTAMP - INTERVAL '2 days' "
'FROM generate_series(1, 1100) i'
)
await flush_accounting_deliveries(writer, client, proxy_server.proxy_logging_obj)
with psycopg.connect(parity_database) as connection:
assert connection.execute('SELECT spend FROM "LiteLLM_UserTable" WHERE user_id=\'user\'').fetchone() == (
0.25 * (1 + min(batch_size, 3)) if backlog == "retries" else 0.25,
)
assert connection.execute(
'SELECT COUNT(*) FROM "LiteLLM_SpendLogDelivery" WHERE state=\'pending\' OR request_id LIKE \'expired-%\''
).fetchone() == ((3 - min(batch_size, 3)) if backlog == "retries" else max(0, 1100 - batch_size * 2),)
finally:
await client.db.disconnect()
@pytest.mark.asyncio
async def test_analytics_overflow_across_requests_still_applies_every_charge(
parity_database: str, monkeypatch: pytest.MonkeyPatch
):
from litellm.accounting.worker import flush_accounting_deliveries
monkeypatch.setenv("DATABASE_URL", parity_database)
monkeypatch.setattr(proxy_server, "general_settings", {"use_spend_logs_ledger": True})
monkeypatch.setattr(proxy_server, "disable_spend_logs", False)
client = PrismaClient(database_url=parity_database, proxy_logging_obj=proxy_server.proxy_logging_obj)
client.spend_log_transactions = []
monkeypatch.setattr(proxy_server, "prisma_client", client)
monkeypatch.setattr(proxy_server, "user_api_key_cache", UserApiKeyCache())
writer = DBSpendUpdateWriter()
await client.db.connect()
try:
assert await _retrieve_batch(writer, 0.25)
stored = await client.writer_db.query_raw('SELECT to_jsonb(s) AS row FROM "LiteLLM_SpendLogs" s')
delivery = (await client.writer_db.query_raw('SELECT accounting_payload FROM "LiteLLM_SpendLogDelivery"'))[0][
"accounting_payload"
]
oversized_savings = {**delivery["metadata"], "compression_savings": {"tokens_saved": 2**62}}
assert await SpendLogsRepository(client).insert_with_deliveries(
tuple(
{
**stored[0]["row"],
"request_id": f"overflow-{index}",
"accounting_payload": {**delivery, "request_id": f"overflow-{index}", "metadata": oversized_savings},
}
for index in range(3)
)
) == 3
await flush_accounting_deliveries(writer, client, proxy_server.proxy_logging_obj)
with psycopg.connect(parity_database) as connection:
assert connection.execute(
'SELECT state::text, COUNT(*) FROM "LiteLLM_SpendLogDelivery" GROUP BY state'
).fetchall() == [("applied", 4)]
assert connection.execute('SELECT spend FROM "LiteLLM_UserTable" WHERE user_id=\'user\'').fetchone() == (1.0,)
assert connection.execute(
'SELECT api_requests, compression_saved_tokens FROM "LiteLLM_DailyUserSpend"'
).fetchone() == (4, 3 * 2**40)
finally:
await client.db.disconnect()