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

512 lines
25 KiB
Python

import asyncio
import os
from collections.abc import AsyncIterator, Iterator, Mapping, Sequence
from pathlib import Path
from typing import Final
from urllib.parse import urlsplit, urlunsplit
import psycopg
import pytest
import pytest_asyncio
from prisma import Prisma
from litellm.repositories.accounting_delivery_repository import (
AccountingDeliveryRepository,
DeliveryProjection,
LedgerTransaction,
)
from litellm.repositories.spend_log_insert import spend_log_insert_statement
from tests.integration._support.database import scratch_database
_MIGRATIONS: Final = Path(__file__).resolve().parents[3] / "litellm-proxy-extras/litellm_proxy_extras/migrations"
@pytest.fixture
def delivery_database(request: pytest.FixtureRequest) -> Iterator[psycopg.Connection[tuple[object, ...]]]:
with scratch_database("spendlogs_delivery") as url, psycopg.connect(url, autocommit=True) as connection:
if getattr(request, "param", "public") == "ledger_tenant":
connection.execute("CREATE SCHEMA ledger_tenant")
connection.execute("SET search_path TO ledger_tenant")
connection.execute((_MIGRATIONS / "20261027000000_add_accounting_ledger_tables/migration.sql").read_text())
connection.execute("""CREATE TABLE "LiteLLM_SpendLogs" (
request_id text PRIMARY KEY, call_type text NOT NULL, spend float8 NOT NULL DEFAULT 0,
status text,
metadata jsonb DEFAULT '{}', "startTime" timestamp(3) NOT NULL,
created_at timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP
)""")
connection.execute((_MIGRATIONS / "20261103010000_spendlogs_accounting_delivery/migration.sql").read_text())
yield connection
def _insert(
connection: psycopg.Connection[tuple[object, ...]], rows: Sequence[Mapping[str, object]], *, ledger: bool = True
) -> None:
from psycopg.types.json import Jsonb
statement: Final = spend_log_insert_statement(rows)
with connection.transaction():
inserted: Final = {
row[0] for row in connection.execute(statement[0].replace("$1", "%s"), (statement[1],)).fetchall()
}
for row in rows:
if ledger and row["request_id"] in inserted:
connection.execute(
'INSERT INTO "LiteLLM_SpendLogDelivery" (delivery_id, request_id, accounting_payload, is_batch) '
"VALUES (%s, %s, %s, %s)",
(row["request_id"], row["request_id"], Jsonb(dict(row)), row.get("call_type") == "aretrieve_batch"),
)
def _with_payload(row: Mapping[str, object]) -> Mapping[str, object]:
return {**row, "accounting_payload": dict(row)}
def _row(request_id: str) -> Mapping[str, object]:
return {
"request_id": request_id,
"call_type": "acompletion",
"spend": 0.5,
"startTime": "2026-11-02T12:00:00+00:00",
"metadata": '{"accounting_savings":{"compression":0.2}}',
}
@pytest.mark.parametrize("call_type", ["acompletion", "aretrieve_batch"])
@pytest.mark.parametrize("mode", ["local", "url", "disabled"])
@pytest.mark.parametrize("partitioned", [False, True])
@pytest.mark.asyncio
async def test_delivery_first_acceptance_deduplicates_all_storage_modes(
delivery_database, delivery_client, mode, partitioned, call_type
):
from types import SimpleNamespace
from litellm.repositories.table_repositories import SpendLogsRepository
if partitioned:
delivery_database.execute('ALTER TABLE "LiteLLM_SpendLogs" RENAME TO spend_template')
delivery_database.execute(
'CREATE TABLE "LiteLLM_SpendLogs" (LIKE spend_template INCLUDING DEFAULTS INCLUDING CONSTRAINTS, PRIMARY KEY(request_id, "startTime")) PARTITION BY RANGE ("startTime")'
)
delivery_database.execute('CREATE TABLE "LiteLLM_SpendLogs_p20261102" PARTITION OF "LiteLLM_SpendLogs" DEFAULT')
delivery_database.execute("DROP TABLE spend_template")
repository = SpendLogsRepository(SimpleNamespace(db=delivery_client, writer_db=delivery_client))
row = {**_with_payload({**_row("shared"), "call_type": call_type}), "accounting_log_disabled": mode == "disabled"}
results = await asyncio.gather(
repository.insert_with_deliveries((row,), write_spend_logs=mode != "url"),
repository.insert_with_deliveries(
({**row, "startTime": "2026-11-03T12:00:00"},), write_spend_logs=mode != "url"
),
)
assert sorted(results) == [0, 1]
assert delivery_database.execute('SELECT COUNT(*) FROM "LiteLLM_SpendLogs"').fetchone() == (int(mode == "local"),)
assert delivery_database.execute(
"SELECT accounting_payload->>'spend', state::text FROM \"LiteLLM_SpendLogDelivery\""
).fetchall() == [("0.5", "pending")]
if partitioned:
delivery_database.execute('DROP TABLE "LiteLLM_SpendLogs_p20261102"')
else:
delivery_database.execute('DELETE FROM "LiteLLM_SpendLogs"')
async def apply(transaction, deliveries):
await transaction.execute_raw("UPDATE totals SET spend = spend + $1::float8", float(deliveries[0].row["spend"]))
worker = AccountingDeliveryRepository(delivery_client)
assert (await worker.apply_pending(apply)).applied == 1
assert (await worker.apply_pending(apply)).applied == 0
assert delivery_database.execute("SELECT spend FROM totals").fetchone() == (0.5,)
@pytest.mark.parametrize("mode", ["local", "url", "disabled"])
@pytest.mark.asyncio
async def test_duplicate_rows_in_one_flush_keep_first_accounting_payload(delivery_database, delivery_client, mode):
from types import SimpleNamespace
from litellm.repositories.table_repositories import SpendLogsRepository
repository = SpendLogsRepository(SimpleNamespace(db=delivery_client, writer_db=delivery_client))
first = {**_with_payload(_row("repeated")), "accounting_log_disabled": mode == "disabled"}
later = {
**_with_payload({**_row("repeated"), "spend": 9.0, "startTime": "2026-11-03T12:00:00+00:00"}),
"accounting_log_disabled": mode == "disabled",
}
assert await repository.insert_with_deliveries((first, later), write_spend_logs=mode != "url") == 1
assert delivery_database.execute(
'SELECT accounting_payload FROM "LiteLLM_SpendLogDelivery"'
).fetchone() == (first["accounting_payload"],)
assert delivery_database.execute('SELECT spend FROM "LiteLLM_SpendLogs"').fetchall() == (
[(first["spend"],)] if mode == "local" else []
)
@pytest.mark.parametrize(("legacy_spend", "accepted"), [(0.5, 0), (0.0, 1)])
@pytest.mark.asyncio
async def test_batch_charged_before_the_ledger_is_not_charged_again(
delivery_database, delivery_client, legacy_spend, accepted
):
from types import SimpleNamespace
from litellm.repositories.table_repositories import SpendLogsRepository
batch: Final = {**_row("batch_legacy"), "call_type": "aretrieve_batch", "status": "success"}
_insert(delivery_database, ({**batch, "spend": legacy_spend},), ledger=False)
repository = SpendLogsRepository(SimpleNamespace(db=delivery_client, writer_db=delivery_client))
assert await repository.insert_with_deliveries((_with_payload({**batch, "spend": 1.0}),)) == accepted
assert delivery_database.execute('SELECT COUNT(*) FROM "LiteLLM_SpendLogDelivery"').fetchone() == (accepted,)
assert delivery_database.execute('SELECT spend FROM "LiteLLM_SpendLogs"').fetchall() == [(legacy_spend,)]
@pytest.mark.parametrize("table", ["LiteLLM_SpendLogs", "LiteLLM_SpendLogDelivery"])
@pytest.mark.asyncio
async def test_transaction_a_rolls_back_payload_and_log_on_failure(delivery_database, delivery_client, table):
from types import SimpleNamespace
from prisma.errors import PrismaError
from psycopg import sql
from litellm.repositories.table_repositories import SpendLogsRepository
delivery_database.execute(
sql.SQL("ALTER TABLE {} ADD CONSTRAINT reject_poison CHECK (request_id <> 'poison')").format(
sql.Identifier(table)
)
)
repository = SpendLogsRepository(SimpleNamespace(db=delivery_client, writer_db=delivery_client))
with pytest.raises(PrismaError):
await repository.insert_with_deliveries(tuple(_with_payload(_row(name)) for name in ("good", "poison")))
assert delivery_database.execute('SELECT COUNT(*) FROM "LiteLLM_SpendLogDelivery"').fetchone() == (0,)
assert delivery_database.execute('SELECT COUNT(*) FROM "LiteLLM_SpendLogs"').fetchone() == (0,)
@pytest.mark.asyncio
async def test_worker_rolls_back_destinations_and_parks_only_isolated_failure(
delivery_database: psycopg.Connection[tuple[object, ...]],
) -> None:
url: Final = urlunsplit(urlsplit(os.environ["DATABASE_URL"])._replace(path=f"/{delivery_database.info.dbname}"))
client: Final = Prisma(datasource={"url": url})
delivery_database.execute("CREATE TABLE totals (spend float8 NOT NULL)")
delivery_database.execute("INSERT INTO totals VALUES (0)")
_insert(delivery_database, (_row("bad"), _row("good")))
async def apply(transaction: LedgerTransaction, rows: tuple[DeliveryProjection, ...]) -> None:
await transaction.execute_raw(
"UPDATE totals SET spend = spend + $1::float8", sum(float(str(row.row["spend"])) for row in rows)
)
if any(row.row["request_id"] == "bad" for row in rows):
raise ValueError("Invalid projected destination")
await client.connect()
try:
repository: Final = AccountingDeliveryRepository(client)
failed: Final = await repository.apply_pending(apply, max_attempts=2)
assert failed.failed == 2
assert failed.parked == ()
assert delivery_database.execute("SELECT spend FROM totals").fetchone() == (0.0,)
assert delivery_database.execute(
'SELECT DISTINCT state::text, attempts FROM "LiteLLM_SpendLogDelivery"'
).fetchall() == [("pending", 1)]
delivery_database.execute('UPDATE "LiteLLM_SpendLogDelivery" SET next_attempt_at = CURRENT_TIMESTAMP')
isolated: Final = await repository.apply_pending(apply, max_attempts=2)
assert isolated.parked == ("bad",)
applied: Final = await repository.apply_pending(apply, max_attempts=2)
assert applied.applied == 1
assert delivery_database.execute("SELECT spend FROM totals").fetchone() == (0.5,)
assert delivery_database.execute(
'SELECT request_id, state::text FROM "LiteLLM_SpendLogDelivery" ORDER BY request_id'
).fetchall() == [("bad", "parked"), ("good", "applied")]
assert (await repository.apply_pending(apply)).applied == 0
finally:
await client.disconnect()
@pytest.mark.asyncio
async def test_a_locked_database_never_parks_a_valid_delivery(delivery_database, delivery_client):
_insert(delivery_database, (_row("valid"),))
async def apply(transaction, deliveries):
await transaction.execute_raw("SET LOCAL lock_timeout = '50ms'")
await transaction.execute_raw(
"UPDATE totals SET spend = spend + $1::float8", sum(float(row.row["spend"]) for row in deliveries)
)
repository = AccountingDeliveryRepository(delivery_client)
with psycopg.connect(
urlunsplit(urlsplit(os.environ["DATABASE_URL"])._replace(path=f"/{delivery_database.info.dbname}"))
) as locker:
locker.execute("LOCK TABLE totals IN ACCESS EXCLUSIVE MODE")
for _ in range(4):
result = await repository.apply_pending(apply, max_attempts=2)
assert result.failed == 1 and result.parked == ()
delivery_database.execute('UPDATE "LiteLLM_SpendLogDelivery" SET next_attempt_at = CURRENT_TIMESTAMP')
assert delivery_database.execute('SELECT state::text, attempts FROM "LiteLLM_SpendLogDelivery"').fetchall() == [
("pending", 4)
]
assert (await repository.apply_pending(apply, max_attempts=2)).applied == 1
assert delivery_database.execute("SELECT spend FROM totals").fetchone() == (0.5,)
@pytest.mark.asyncio
async def test_an_unreachable_database_reported_as_a_data_error_never_parks_a_delivery(
delivery_database, delivery_client
):
from prisma.errors import DataError
_insert(delivery_database, (_row("valid"),))
async def unreachable(transaction, deliveries):
raise DataError(data={"user_facing_error": {"message": "Can't reach database server at `db`:`5432`"}})
repository = AccountingDeliveryRepository(delivery_client)
for _ in range(3):
assert (await repository.apply_pending(unreachable, max_attempts=2)).parked == ()
delivery_database.execute('UPDATE "LiteLLM_SpendLogDelivery" SET next_attempt_at = CURRENT_TIMESTAMP')
assert delivery_database.execute('SELECT state::text, attempts FROM "LiteLLM_SpendLogDelivery"').fetchall() == [
("pending", 3)
]
@pytest_asyncio.fixture(loop_scope="function")
async def delivery_client(delivery_database: psycopg.Connection[tuple[object, ...]]) -> AsyncIterator[Prisma]:
url: Final = urlunsplit(urlsplit(os.environ["DATABASE_URL"])._replace(path=f"/{delivery_database.info.dbname}"))
client: Final = Prisma(datasource={"url": url})
delivery_database.execute("CREATE TABLE totals (spend float8 NOT NULL)")
delivery_database.execute("INSERT INTO totals VALUES (0)")
await client.connect()
try:
yield client
finally:
await client.disconnect()
@pytest.mark.asyncio
async def test_two_workers_claim_disjoint_rows_and_apply_once(
delivery_database: psycopg.Connection[tuple[object, ...]],
delivery_client: Prisma,
) -> None:
_insert(delivery_database, (_row("first"), _row("second")))
entered: Final[asyncio.Queue[str]] = asyncio.Queue()
release: Final = asyncio.Event()
async def apply(transaction: LedgerTransaction, rows: tuple[DeliveryProjection, ...]) -> None:
assert len(rows) == 1
await entered.put(str(rows[0].row["request_id"]))
await release.wait()
await transaction.execute_raw("UPDATE totals SET spend = spend + $1::float8", float(str(rows[0].row["spend"])))
repository: Final = AccountingDeliveryRepository(delivery_client)
first: Final = asyncio.create_task(repository.apply_pending(apply, batch_size=1))
first_id: Final = await asyncio.wait_for(entered.get(), timeout=10)
second: Final = asyncio.create_task(repository.apply_pending(apply, batch_size=1))
try:
second_id: Final = await asyncio.wait_for(entered.get(), timeout=10)
assert first_id != second_id
finally:
release.set()
results: Final = await asyncio.gather(first, second)
assert sum(result.applied for result in results) == 2
assert delivery_database.execute("SELECT spend FROM totals").fetchone() == (1.0,)
assert delivery_database.execute(
"SELECT COUNT(*) FROM \"LiteLLM_SpendLogDelivery\" WHERE state = 'applied'"
).fetchone() == (2,)
@pytest.mark.asyncio
async def test_cancelled_worker_rolls_back_and_restart_applies_once(
delivery_database: psycopg.Connection[tuple[object, ...]],
delivery_client: Prisma,
) -> None:
_insert(delivery_database, (_row("restart"),))
wrote: Final = asyncio.Event()
hold: Final = asyncio.Event()
async def interrupted(transaction: LedgerTransaction, rows: tuple[DeliveryProjection, ...]) -> None:
await transaction.execute_raw("UPDATE totals SET spend = spend + $1::float8", float(str(rows[0].row["spend"])))
wrote.set()
await hold.wait()
repository: Final = AccountingDeliveryRepository(delivery_client)
task: Final = asyncio.create_task(repository.apply_pending(interrupted))
await asyncio.wait_for(wrote.wait(), timeout=10)
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
assert delivery_database.execute("SELECT spend FROM totals").fetchone() == (0.0,)
assert delivery_database.execute('SELECT state::text, attempts FROM "LiteLLM_SpendLogDelivery"').fetchone() == (
"pending",
0,
)
async def complete(transaction: LedgerTransaction, rows: tuple[DeliveryProjection, ...]) -> None:
await transaction.execute_raw("UPDATE totals SET spend = spend + $1::float8", float(str(rows[0].row["spend"])))
assert (await repository.apply_pending(complete)).applied == 1
assert (await repository.apply_pending(complete)).applied == 0
assert delivery_database.execute("SELECT spend FROM totals").fetchone() == (0.5,)
@pytest.mark.asyncio
async def test_worker_applies_accounting_after_spend_logs_are_deleted(
delivery_database: psycopg.Connection[tuple[object, ...]], delivery_client: Prisma
) -> None:
_insert(delivery_database, (_row("removed"),))
delivery_database.execute('DELETE FROM "LiteLLM_SpendLogs"')
async def apply(transaction: LedgerTransaction, rows: tuple[DeliveryProjection, ...]) -> None:
await transaction.execute_raw("UPDATE totals SET spend = spend + $1::float8", float(str(rows[0].row["spend"])))
repository: Final = AccountingDeliveryRepository(delivery_client)
assert (await repository.apply_pending(apply)).applied == 1
assert (await repository.apply_pending(apply)).applied == 0
assert delivery_database.execute("SELECT spend FROM totals").fetchone() == (0.5,)
@pytest.mark.asyncio
async def test_receipt_cleanup_keeps_pending_and_parked_rows_and_reports_lag(
delivery_database: psycopg.Connection[tuple[object, ...]], delivery_client: Prisma
) -> None:
_insert(delivery_database, tuple(_row(state) for state in ("pending", "parked", "applied")))
delivery_database.execute(
'UPDATE "LiteLLM_SpendLogDelivery" '
'SET state = request_id::"AccountingDeliveryState", '
"created_at = CURRENT_TIMESTAMP - INTERVAL '40 days', "
"applied_at = CURRENT_TIMESTAMP - INTERVAL '40 days'"
)
repository = AccountingDeliveryRepository(delivery_client)
assert await repository.cleanup_applied() == 1
metrics = await repository.metrics()
assert metrics.pending_count == 1
assert metrics.parked_count == 1
assert metrics.oldest_pending_seconds >= 40 * 86400
assert delivery_database.execute(
'SELECT request_id FROM "LiteLLM_SpendLogDelivery" ORDER BY request_id'
).fetchall() == [("parked",), ("pending",)]
@pytest.mark.parametrize("delivery_database", ["public", "ledger_tenant"], indirect=True)
@pytest.mark.parametrize("state", [None, "pending", "parked", "applied"])
def test_delivery_migration_replay_preserves_ledger_receipts(delivery_database, state):
if state is not None:
_insert(delivery_database, (_row("replay"),))
delivery_database.execute(
'UPDATE "LiteLLM_SpendLogDelivery" SET state=%s, attempts=3, last_error=%s',
(state, "retained failure"),
)
before = delivery_database.execute('SELECT * FROM "LiteLLM_SpendLogDelivery"').fetchall()
migration = (_MIGRATIONS / "20261103010000_spendlogs_accounting_delivery/migration.sql").read_text()
delivery_database.execute(migration)
delivery_database.execute(migration)
assert delivery_database.execute('SELECT * FROM "LiteLLM_SpendLogDelivery"').fetchall() == before
assert delivery_database.execute('SELECT count(*) FROM "LiteLLM_SpendLogs"').fetchone() == (int(state is not None),)
@pytest.mark.parametrize("state", ["pending", "parked"])
def test_delivery_migration_preserves_unused_old_receipts(state):
with scratch_database("spendlogs_old_delivery") as url, psycopg.connect(url, autocommit=True) as connection:
connection.execute((_MIGRATIONS / "20261027000000_add_accounting_ledger_tables/migration.sql").read_text())
connection.execute('CREATE TABLE "LiteLLM_SpendLogs" (request_id text PRIMARY KEY)')
connection.execute(
'INSERT INTO "LiteLLM_AccountingDelivery" (event_id, target, version, state) VALUES (%s, %s, 1, %s)',
("old-event", "LiteLLM_UserTable", state),
)
connection.execute((_MIGRATIONS / "20261103010000_spendlogs_accounting_delivery/migration.sql").read_text())
assert connection.execute('SELECT event_id, state::text FROM "LiteLLM_AccountingDelivery"').fetchall() == [
("old-event", state)
]
assert connection.execute('SELECT COUNT(*) FROM "LiteLLM_SpendLogDelivery"').fetchone() == (0,)
@pytest.mark.asyncio
async def test_malformed_payload_is_parked_without_losing_other_deliveries(delivery_database, delivery_client):
_insert(delivery_database, (_row("bad"), _row("good")))
delivery_database.execute(
'UPDATE "LiteLLM_SpendLogDelivery" SET accounting_payload=$$ [] $$::jsonb WHERE request_id=$$bad$$'
)
async def apply(transaction, deliveries):
await transaction.execute_raw(
"UPDATE totals SET spend = spend + $1::float8", sum(float(row.row["spend"]) for row in deliveries)
)
repository = AccountingDeliveryRepository(delivery_client)
assert (await repository.apply_pending(apply, max_attempts=2)).failed == 2
assert delivery_database.execute("SELECT spend FROM totals").fetchone() == (0.0,)
delivery_database.execute('UPDATE "LiteLLM_SpendLogDelivery" SET next_attempt_at=CURRENT_TIMESTAMP')
assert (await repository.apply_pending(apply, max_attempts=2)).parked == ("bad",)
assert (await repository.apply_pending(apply, max_attempts=2)).applied == 1
assert delivery_database.execute("SELECT spend FROM totals").fetchone() == (0.5,)
@pytest.mark.asyncio
async def test_retention_keeps_batch_receipts_indefinitely(delivery_database, delivery_client):
_insert(delivery_database, (_row("normal"), {**_row("batch"), "call_type": "aretrieve_batch"}))
delivery_database.execute(
"UPDATE \"LiteLLM_SpendLogDelivery\" SET state='applied', applied_at=CURRENT_TIMESTAMP - INTERVAL '400 days'"
)
repository = AccountingDeliveryRepository(delivery_client)
assert await repository.cleanup_applied() == 1
assert await repository.cleanup_applied() == 0
assert delivery_database.execute('SELECT request_id FROM "LiteLLM_SpendLogDelivery"').fetchall() == [("batch",)]
metrics = await repository.metrics()
assert metrics.batch_count == 1
assert metrics.table_bytes > 0
@pytest.mark.parametrize("disabled", [False, True])
@pytest.mark.asyncio
async def test_ledger_batch_retrieves_charge_once_in_every_logging_mode(
delivery_database, delivery_client, monkeypatch, disabled
):
from types import SimpleNamespace
from litellm.proxy import proxy_server
from litellm.proxy.db.db_spend_update_writer import DBSpendUpdateWriter
from litellm.proxy.utils import jsonify_object
completed = {
**_row("batch_completed"), "call_type": "aretrieve_batch", "status": "success", "spend": 0.5,
"metadata": '{"status":"success","private":"request detail"}',
"accounting_payload": {
"request_id": "batch_completed", "call_type": "aretrieve_batch", "status": "success", "spend": 0.5,
"metadata": {"accounting_savings": {"compression": 0.2}},
},
}
monkeypatch.setattr(proxy_server, "general_settings", {"spend_logs_metadata_fields": {"include": ["status"]}})
client = SimpleNamespace(db=delivery_client, writer_db=delivery_client, jsonify_object=jsonify_object)
writer = DBSpendUpdateWriter()
first = await writer._claim_settle_once_cost_row(payload=completed, prisma_client=client, disable_spend_logs=disabled)
again = await writer._claim_settle_once_cost_row(
payload={**completed, "startTime": "2026-11-05T12:00:00+00:00"}, prisma_client=client, disable_spend_logs=disabled
)
assert (first, again) == (True, False)
assert delivery_database.execute('SELECT spend, metadata FROM "LiteLLM_SpendLogs"').fetchall() == (
[] if disabled else [(0.5, {"status": "success"})]
)
assert delivery_database.execute(
'SELECT delivery_id, accounting_payload FROM "LiteLLM_SpendLogDelivery"'
).fetchall() == [("batch_completed", completed["accounting_payload"])]
@pytest.mark.parametrize("setting", ["retention_days", "batch_size"])
@pytest.mark.asyncio
async def test_invalid_cleanup_settings_preserve_receipts(delivery_database, delivery_client, setting):
_insert(delivery_database, (_row("protected"),))
with pytest.raises(ValueError, match="positive"):
await AccountingDeliveryRepository(delivery_client).cleanup_applied(**{setting: 0})
assert delivery_database.execute('SELECT request_id, state::text FROM "LiteLLM_SpendLogDelivery"').fetchall() == [
("protected", "pending")
]
@pytest.mark.parametrize("setting", ["max_attempts", "batch_size"])
@pytest.mark.asyncio
async def test_invalid_worker_settings_preserve_pending_work(delivery_database, delivery_client, setting):
from unittest.mock import AsyncMock
_insert(delivery_database, (_row("protected"),))
apply = AsyncMock()
with pytest.raises(ValueError, match="positive"):
await AccountingDeliveryRepository(delivery_client).apply_pending(apply, **{setting: 0})
apply.assert_not_awaited()
assert delivery_database.execute(
'SELECT request_id, state::text, attempts FROM "LiteLLM_SpendLogDelivery"'
).fetchall() == [("protected", "pending", 0)]