litellm/tests/unit/accounting/test_metrics.py
Mateo Wang cf1ebf8577
fix(accounting): split a lock-timed-out spend batch by team so a held lock delays only the teams behind it (#55601)
* fix(accounting): let one pod at a time deliver spend

Every pod ran the delivery loop on each flush. When most spend belongs to a
few teams, the pods queue on the same team advisory lock, the waiters hit
lock_timeout and roll back, and their rows move to the one-row-per-transaction
retry path.

Take a short-lived delivery lock around the fresh and retry loops so only one
pod claims deliveries at a time. The maintenance lock is untouched, so an
orphaned maintenance lock still cannot stall delivery. A crashed holder delays
delivery by at most the lock TTL, and without Redis delivery behaves as before.

Relates to #55172

Co-Authored-By: AaronHowell <111272993+AaronHowell@users.noreply.github.com>

* fix(accounting): keep the delivery lock as long as one batch may run

A single delivery batch runs in a transaction with a 60 second timeout, so a
30 second lock could expire while its holder was still delivering and let a
second pod start. Use 60 seconds so the lock outlives any one batch.

Co-Authored-By: AaronHowell <111272993+AaronHowell@users.noreply.github.com>

* fix(accounting): leave lock-timed-out spend deliveries for the next flush instead of the retry queue

Since every pod delivers spend at once, a delivery that times out waiting for a
hot team or key row bumped attempts on its whole batch, which moved up to 500
rows into the one-row-at-a-time retry queue. A lock timeout means the batch never
applied and rolled back, so leave the claimed rows as they were and let the next
flush deliver them in a batch.

This replaces the one-pod-at-a-time delivery lock from #55173, which stopped the
retries but delivered a third to a half fewer rows per minute than concurrent
pods. Thanks to @Bytechoreographer for tracking the stuck rows down to concurrent
delivery.

* fix(accounting): keep backoff for retried deliveries that hit a lock timeout

Only a new batch is left as it was after a lock timeout. A delivery already in the retry queue backs off again as before, so one busy row no longer holds up the other retries behind it. The worker now logs how many requests it left for the next flush.

* fix(accounting): never park a delivery for a lock timeout

A lock timeout that Postgres reports in another language came back as a plain DataError, which counted as a permanent failure, so a retried delivery on its last attempt was parked. Lock timeouts now always back off and retry.

* fix(accounting): count lock-timed-out deliveries on /metrics

* fix(accounting): split a lock-timed-out batch by team so one held lock defers only that team

A fresh batch that times out on a team lock, or whose transaction expires,
is split by the teams it charges. Each team's deliveries are claimed again
and applied in their own transaction, so a long-held lock on one team only
defers that team's rows, and those rows step back 5-15 s so newer
deliveries go first. After two contended teams the rest of the batch waits
for the next flush untried.

* fix(accounting): back off an expired single-team batch, cap the split at 5 s, and keep committed teams when the database drops

* fix(accounting): name the split limit in the deferred delivery log

---------

Co-authored-by: Rick <26716961+Bytechoreographer@users.noreply.github.com>
Co-authored-by: AaronHowell <111272993+AaronHowell@users.noreply.github.com>
2026-12-02 15:58:55 -08:00

88 lines
3.1 KiB
Python

import importlib.util
import sys
import pytest
from prometheus_client.metrics import MetricWrapperBase
from litellm.accounting import metrics
from litellm.accounting.metrics import Cadence, record_backlog, record_deferred, record_storage
from litellm.repositories.accounting_delivery_repository import DeliveryBacklog, DeliveryStorage
_BACKLOG = DeliveryBacklog(pending_count=4, parked_count=1, oldest_pending_seconds=-3.0)
_STORAGE = DeliveryStorage(batch_count=7, table_bytes=8192)
def _sample(metric: MetricWrapperBase, suffix: str = "") -> float:
family = metric.collect()[0]
return next(sample.value for sample in family.samples if sample.name == family.name + suffix)
def test_delivery_metrics_publish_backlog_and_clamp_clock_skew() -> None:
instruments = metrics._instruments()
assert instruments is not None
batches_before = _sample(instruments.batch_time, "_count")
record_backlog(_BACKLOG, 0.5)
record_storage(_STORAGE)
assert (
_sample(instruments.pending),
_sample(instruments.parked),
_sample(instruments.oldest),
_sample(instruments.batch_count),
_sample(instruments.table_bytes),
) == (4.0, 1.0, 0.0, 7.0, 8192.0)
assert _sample(instruments.batch_time, "_count") == batches_before + 1
def test_deferred_deliveries_add_up_across_flushes() -> None:
instruments = metrics._instruments()
assert instruments is not None
before = _sample(instruments.deferred, "_total")
record_deferred(3)
record_deferred(2)
assert _sample(instruments.deferred, "_total") == before + 5
def test_importing_metrics_defers_prometheus_client_import(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.delitem(sys.modules, "prometheus_client", raising=False)
spec = importlib.util.spec_from_file_location("accounting_metrics_lazy_import", metrics.__file__)
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
monkeypatch.setitem(sys.modules, spec.name, module)
spec.loader.exec_module(module)
assert "prometheus_client" not in sys.modules
def test_delivery_metrics_are_skipped_when_prometheus_client_is_not_installed(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setitem(sys.modules, "prometheus_client", None)
spec = importlib.util.spec_from_file_location("accounting_metrics_without_prometheus", metrics.__file__)
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
monkeypatch.setitem(sys.modules, spec.name, module)
spec.loader.exec_module(module)
assert module.record_backlog(_BACKLOG, 0.5) is None
assert module.record_storage(_STORAGE) is None
assert module.record_deferred(2) is None
def test_cadence_is_due_once_per_interval() -> None:
now = [100.0]
cadence = Cadence(lambda: now[0])
observed = []
for moment in (100.0, 101.0, 999.9, 1000.0, 1000.0, 1899.0, 1900.0):
now[0] = moment
observed.append(cadence.due(900))
assert observed == [True, False, False, True, False, False, True]