litellm/tests/integration/database/test_spendlogs_ledger_parity.py
Yassin Kortam adc4c01aa9
chore: move scripts and runtime sources under litellm (#51006)
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-11-12 04:19:57 +00:00

1549 lines
79 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,transactions,distinct_models", [(None, 251, 1, False), (None, 1001, 3, False), ("200", 251, 2, False), ("3001", 3001, 1, True)])
@pytest.mark.asyncio
async def test_worker_drains_a_backlog_in_one_run_one_configured_batch_per_transaction(
parity_database: str, monkeypatch: pytest.MonkeyPatch, batch_size: str | None, row_count: int, transactions: 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 backlog 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() == (row_count,)
assert connection.execute('SELECT COUNT(*) FROM "LiteLLM_SpendLogDelivery" WHERE state=\'pending\'').fetchone() == (0,)
assert connection.execute('SELECT COUNT(DISTINCT applied_at) FROM "LiteLLM_SpendLogDelivery"').fetchone() == (transactions,)
assert connection.execute('SELECT spend FROM "LiteLLM_UserTable" WHERE user_id=\'user\'').fetchone() == (row_count * 0.25,)
assert connection.execute('SELECT COUNT(*) FROM "LiteLLM_DailyUserSpend"').fetchone() == (row_count if distinct_models else 1,)
finally:
await client.db.disconnect()
@pytest.mark.asyncio
async def test_worker_removes_more_expired_receipts_than_one_cleanup_batch_in_one_run(
parity_database: str, monkeypatch: pytest.MonkeyPatch
):
from litellm.accounting.worker import flush_accounting_deliveries
monkeypatch.setenv("DATABASE_URL", parity_database)
monkeypatch.setenv("LITELLM_ACCOUNTING_DELIVERY_BATCH_SIZE", "100")
client = PrismaClient(database_url=parity_database, proxy_logging_obj=proxy_server.proxy_logging_obj)
with psycopg.connect(parity_database, autocommit=True) as connection:
connection.execute(
'INSERT INTO "LiteLLM_SpendLogDelivery" (request_id, accounting_payload, is_batch, state, applied_at) '
"SELECT 'expired-' || n, '{}'::jsonb, false, 'applied', CURRENT_TIMESTAMP - INTERVAL '2 days' "
"FROM generate_series(1, 501) AS n"
)
await client.db.connect()
try:
await flush_accounting_deliveries(DBSpendUpdateWriter(), client, proxy_server.proxy_logging_obj)
with psycopg.connect(parity_database) as connection:
assert connection.execute('SELECT COUNT(*) FROM "LiteLLM_SpendLogDelivery"').fetchone() == (0,)
finally:
await client.db.disconnect()
@pytest.mark.asyncio
async def test_worker_checks_storage_and_repeats_delay_alerts_once_per_interval(
parity_database: str, monkeypatch: pytest.MonkeyPatch
):
from litellm.accounting.worker import flush_accounting_deliveries
class _Alerts:
def __init__(self) -> None:
self.messages: list[str] = [] # mutable-ok: alert sink the worker appends to
async def alerting_handler(self, message: str, level: str, alert_type: object) -> None:
self.messages.append(message)
class _Clock:
def __init__(self) -> None:
self.now = 0.0
def __call__(self) -> float:
return self.now
monkeypatch.setenv("DATABASE_URL", parity_database)
monkeypatch.setenv("LITELLM_ACCOUNTING_DELIVERY_ALERT_BYTES", "1")
with psycopg.connect(parity_database, autocommit=True) as connection:
connection.execute(
'INSERT INTO "LiteLLM_SpendLogDelivery" '
"(delivery_id, request_id, accounting_payload, is_batch, attempts, created_at, next_attempt_at) "
"VALUES ('stuck', 'stuck', '{}'::jsonb, false, 1, CURRENT_TIMESTAMP - INTERVAL '1 hour', "
"CURRENT_TIMESTAMP + INTERVAL '1 hour')"
)
client: Final = PrismaClient(database_url=parity_database, proxy_logging_obj=proxy_server.proxy_logging_obj)
clock: Final = _Clock()
writer: Final = DBSpendUpdateWriter(accounting_clock=clock)
alerts: Final = _Alerts()
monkeypatch.setenv("LITELLM_ACCOUNTING_DELIVERY_CHECK_INTERVAL_SECONDS", "100")
async def flush_at(moment: float) -> tuple[str, ...]:
clock.now = moment
before: Final = len(alerts.messages)
await flush_accounting_deliveries(writer, client, alerts)
return tuple(message.split(",")[0] for message in alerts.messages[before:])
await client.db.connect()
try:
first: Final = await flush_at(0.0)
with psycopg.connect(parity_database, autocommit=True) as connection:
connection.execute(
'INSERT INTO "LiteLLM_SpendLogDelivery" (delivery_id, request_id, accounting_payload, is_batch, state) '
"VALUES ('batch', 'batch', '{}'::jsonb, true, 'applied')"
)
within: Final = (await flush_at(10.0), await flush_at(99.0))
after: Final = await flush_at(100.0)
finally:
await client.db.disconnect()
delayed: Final = "Accounting deliveries are delayed. Pending=1"
assert first == ("Accounting delivery storage requires review. Retained batches=0", delayed)
assert within == ((), ())
assert after == ("Accounting delivery storage requires review. Retained batches=1", delayed)
@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 / "litellm/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": 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
assert not {"messages", "response", "proxy_server_request", "metadata"}.intersection(rows[0])
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)
)
assert daily["guardrail_spend"] == pytest.approx(min(0.02, cost))
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_delivers_under_another_leaders_lock_then_cleans_reports_and_releases_its_lock(
parity_database: str, monkeypatch: pytest.MonkeyPatch
):
from prometheus_client import REGISTRY
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)
monkeypatch.setenv("LITELLM_ACCOUNTING_DELIVERY_RETENTION_DAYS", "1")
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:
reports_before: Final = REGISTRY.get_sample_value("litellm_accounting_batch_seconds_count")
assert reports_before is not None
with psycopg.connect(parity_database, autocommit=True) as connection:
connection.execute(
'INSERT INTO "LiteLLM_SpendLogDelivery" (request_id, accounting_payload, is_batch, attempts) '
"VALUES ('fresh', %s::jsonb, false, 0), ('retry', %s::jsonb, false, 1)",
(
json.dumps({"spend": 0.25, "metadata": {"accounting_entities": {"user": "user"}}}),
json.dumps({"spend": 0.5, "metadata": {"accounting_entities": {"user": "user"}}}),
),
)
connection.execute(
'INSERT INTO "LiteLLM_SpendLogDelivery" '
'(request_id, accounting_payload, is_batch, state, applied_at) '
"VALUES ('expired', '{}'::jsonb, false, 'applied', CURRENT_TIMESTAMP - INTERVAL '2 days')"
)
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 request_id, state::text, attempts FROM "LiteLLM_SpendLogDelivery" ORDER BY request_id'
).fetchall() == [("expired", "applied", 0), ("fresh", "applied", 0), ("retry", "applied", 1)]
assert connection.execute('SELECT spend FROM "LiteLLM_UserTable" WHERE user_id=\'user\'').fetchone() == (0.75,)
assert REGISTRY.get_sample_value("litellm_accounting_batch_seconds_count") == reports_before
assert await writer.pod_lock_manager.acquire_lock(cronjob_id="accounting_delivery", allow_reentrant=False) is False
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 request_id, state::text, attempts FROM "LiteLLM_SpendLogDelivery" ORDER BY request_id'
).fetchall() == [("fresh", "applied", 0), ("retry", "applied", 1)]
assert connection.execute('SELECT spend FROM "LiteLLM_UserTable" WHERE user_id=\'user\'').fetchone() == (0.75,)
assert REGISTRY.get_sample_value("litellm_accounting_batch_seconds_count") == reports_before + 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()