litellm/tests/unit/redis/stores/test_spend_counters.py
zoveki abe3b11f7a
fix(proxy): show committed spend in the remaining budget gauges (#49199)
* fix(proxy): report live key and team spend to budget gauges within the key cache TTL

* fix(prometheus): carry live spend for the user, org and customer budget gauges too

The remaining budget gauges for users, orgs and customers read the same cached rows as the key and
team gauges, so they read high for about a minute after a charge. Auth now carries the live counter
for each budgeted entity in one snapshot that only the gauges read, floored at the spend auth loaded.
The x-litellm-key-spend header and logging spend fields keep their current values.

* fix(prometheus): show committed spend in the remaining budget gauges

Reads twin counters that take only charged cost, so a worst-case budget hold
never shows as spent and a request that finishes last cannot set a gauge back.
The twins exist only while the Prometheus logger is registered, and every path
that resets a spend counter drops them. Failed requests now set the org gauge
from the carried org row and committed spend, not the cached org row.

* fix(prometheus): count a charge the cached customer row already holds once

* fix(prometheus): keep committed spend only for budgeted entities and drop it on spend resets

Auth now reads committed spend through the admission MGET and names the counters a charge
may move, so the master key and unbudgeted entities get no twin. Organization spend edits
and the global spend reset drop their twins, and a long request no longer reads as charged.

* fix(prometheus): read the committed org spend on failed requests without the auth object

* test(prometheus): cover a failed request with no carried org

* fix(prometheus): move the committed counters for charges with no auth on the row

A billed background response is charged from its creator's stored attribution, after the request's auth is gone. Its charge moved the live counters but not the committed ones, so every gauge read one charge behind. It now moves the committed counters that already exist, and its own gauge adds its cost to them.

* fix(prometheus): keep the gauges right for pass-through rows, overlapping charges and slow DB spend writes

Pass-through rows carry the auth object, so a cold committed counter gets seeded there too. The gauges read a
charge still waiting in the post-call pipeline as not counted, whatever other charges reached the counter. Committed
counters outlive two DB spend writes. Cold seeds read the DB once per worker, and the global spend reset reads keys
and teams in bounded pages.

* fix(prometheus): count a charged failure's own cost in the org gauge

A stream cut mid-response still charges for what it delivered, and that charge is usually still queued when the failure logs. The failure path passed a cost of 0, so the org gauge left that charge out until the worker's next request

* fix(prometheus): skip twins for window-named ids, drop twins on delete, keep auth out of PostHog

* fix(prometheus): keep the auth object off pass-through rows and drop user twins on every user delete

Pass-through rows now carry only the committed spend in litellm_params, so loggers that dump the row's metadata never get the auth object. Every user delete path, SCIM and bulk delete included, drops the deleted users' committed spend twins

* fix(prometheus): keep committed spend values out of logger dumps of pass-through rows

CommittedBudgetSpend fields are repr=False, so Athina's payload, Sentry breadcrumbs and debug logs that str() a pass-through row's litellm_params show no spend values

* fix(prometheus): keep the gauge fallback on a slow committed read and refresh committed twin TTLs on cluster

The success-path committed read now gets half the per-request budget, so a slow Redis falls back to stored spend before the outer timeout cancels the gauges. Post-call charges refresh a committed twin's TTL on Redis Cluster too, so a twin never expires while its charges are still on their way to the DB. Also applies cargo fmt to the PR's Rust files

* fix(proxy): key the global reset's committed-spend page queries so the Prisma span check reads them

---------

Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com>
2026-11-09 20:05:37 +00:00

208 lines
8.4 KiB
Python

import json
from typing import Final
import pytest
from litellm._internal_context import current_service_target
from litellm.caching.redis_batch import Batch, request_redis_batch_scope
from litellm.caching.redis_cache import RedisCache
from litellm.redis.stores.connection import RedisStores, connect
from litellm.redis.stores.spend_counters import (
SPEND_COUNTERS_TARGET,
SpendCounterStore,
committed_counter,
end_user_counter,
is_unavailable,
key_counter,
key_window_counter,
model_access_group_counter,
org_counter,
project_counter,
shadow_eval_counter,
tag_counter,
team_counter,
team_member_counter,
team_window_counter,
user_counter,
)
from litellm.redis.store_settings import RedisStoreSettings
from litellm.rust_bridge._native import NativeRedisClient, NativeRedisStoreError, NativeSpendCounters, SpendRead
from tests.unit.caching.test_redis_batch import FakeNatives, fake_send
from .spend_counters_double import FakeSettlement, FakeSpendCounters
_KEYS: Final = (
(
key_counter("88dc28d0f030c55ed4ab77ed8faf098196cb1c05df778539800c9f1243fe6b4b"),
"spend:key:88dc28d0f030c55ed4ab77ed8faf098196cb1c05df778539800c9f1243fe6b4b",
),
(key_window_counter("88dc28d0", "30d"), "spend:key:88dc28d0:window:30d"),
(team_counter("team-a"), "spend:team:team-a"),
(team_window_counter("team-a", "1h"), "spend:team:team-a:window:1h"),
(team_member_counter("user:with:colons", "team-a"), "spend:team_member:user:with:colons:team-a"),
(user_counter("user@example.com"), "spend:user:user@example.com"),
(end_user_counter("customer é 1"), "spend:end_user:customer é 1"),
(org_counter("org-1"), "spend:org:org-1"),
(tag_counter("prod:eu"), "spend:tag:prod:eu"),
(project_counter("proj-1"), "spend:project:proj-1"),
(model_access_group_counter("gpt-group"), "spend:model_access_group:gpt-group"),
(shadow_eval_counter("job-7"), "spend:shadow_eval:job-7"),
(committed_counter(key_counter("88dc28d0")), "spend:committed:key:88dc28d0"),
(committed_counter(team_counter("team-a")), "spend:committed:team:team-a"),
(committed_counter(user_counter("user@example.com")), "spend:committed:user:user@example.com"),
(committed_counter(org_counter("org-1")), "spend:committed:org:org-1"),
(committed_counter(end_user_counter("customer é 1")), "spend:committed:end_user:customer é 1"),
)
@pytest.mark.parametrize(("built", "key"), _KEYS, ids=[key for _, key in _KEYS])
def test_python_builds_every_key_the_native_store_formats(built: str, key: str) -> None:
store: Final = NativeSpendCounters(None)
store.set_local(built, 1.5)
assert built == key
assert store.snapshot() == {key: 1.5}
@pytest.mark.parametrize(
("spend", "wire"), [(0.0, "0.0"), (12, "12"), (1e-05, "1e-05"), (0.30000000000000004, "0.30000000000000004")]
)
def test_a_reset_writes_what_redis_cache_set_cache_writes(spend: float, wire: str) -> None:
assert json.dumps(spend) == wire
@pytest.mark.parametrize(("spend", "wire"), [(2.5, "2.5"), (100, "100"), (1e-05, "1e-05")])
def test_a_repair_writes_what_redis_cache_set_max_writes(spend: float, wire: str) -> None:
assert str(spend) == wire
@pytest.mark.parametrize(("wire", "spend"), [("7.25", 7.25), ("3", 3), ("0.0", 0.0), ("1e-05", 1e-05)])
def test_a_read_decodes_what_redis_cache_decodes(wire: str, spend: float) -> None:
decoded: Final = RedisCache._get_cache_logic( # pyright: ignore[reportPrivateUsage] # main's codec is the contract
RedisCache.__new__(RedisCache), wire.encode()
)
assert decoded == spend
assert type(decoded) is type(spend)
@pytest.mark.parametrize(
"key",
[
"spend_db_floor:spend:key:k",
"virtual_key_spend:k:gpt:1d",
"spend:unknown:k",
"spend:committed:key:k:window:1d",
"spend:committed:tag:prod",
"spend:committed:committed:key:k",
],
)
def test_the_native_store_refuses_keys_outside_the_spend_counter_keyspace(key: str) -> None:
with pytest.raises(ValueError, match="a spend counter is a spend:\* key"):
NativeSpendCounters(None).get_local(key)
@pytest.mark.asyncio
async def test_without_redis_the_native_store_counts_and_answers_from_memory() -> None:
store: Final = SpendCounterStore(connect(None).spend_counters())
first: Final = await store.increment("spend:key:k", 2)
second: Final = await store.increment_many((("spend:key:k", 0.5), ("spend:team:t", 1.0)))
seeded: Final = await store.seed("spend:org:o", 4.0, increment_if_lost=False)
repaired: Final = await store.set_max("spend:key:k", 9.0)
assert (first, second, seeded, repaired) == (2, (2.5, 1.0), 4.0, None)
assert await store.read("spend:key:k") == (9.0, False)
assert await store.read_many(("spend:key:k",), batch=Batch.NONE) is None
assert not store.has_redis
assert not store.increment_many_post_call((("spend:key:k", 1.0),))
def test_a_broadcast_writes_and_drops_only_spend_counter_copies() -> None:
store: Final = SpendCounterStore(connect(None).spend_counters())
store.set_local("spend:key:k", 5.0)
store.set_local("spend:team:t", 5.0)
store.apply_broadcast("spend:key:k", 0.0, 60)
store.apply_broadcast("spend:team:t", None, None)
store.apply_broadcast("spend_db_floor:spend:key:k", 1.0, 5)
store.apply_broadcast("spend:unknown:x", 1.0, None)
assert store.snapshot() == {"spend:key:k": 0.0}
@pytest.mark.parametrize(
"kind, dropped",
[("timeout", True), ("breaker_open", True), ("transport", False), ("rejected", False), ("memory", False)],
)
def test_only_a_timeout_or_an_open_breaker_lets_a_post_call_increment_drop(kind: str, dropped: bool) -> None:
assert is_unavailable(NativeRedisStoreError(kind, "message")) is dropped
assert not is_unavailable(TimeoutError(kind))
def _connection(host: str, *, ttl: int) -> RedisStores:
client: Final = NativeRedisClient.connect(
RedisStoreSettings(redis_kwargs={"host": host, "port": 1}, namespace=None, default_ttl=ttl, breaker=None)
)
assert client is not None
return RedisStores(client)
def test_redis_attaches_once_keeping_memory_and_its_ttl_is_the_lease_the_store_reports() -> None:
store: Final = SpendCounterStore(connect(None).spend_counters())
store.set_local(team_counter("team-a"), 4.5)
store.attach_redis(connect(None))
assert not store.has_redis
store.attach_redis(_connection("127.0.0.1", ttl=30))
store.attach_redis(_connection("127.0.0.2", ttl=90))
assert store.has_redis
assert store.redis_ttl == 30
assert store.get_local(team_counter("team-a")) == 4.5
@pytest.mark.asyncio
async def test_post_call_increments_go_on_the_requests_native_post_call_batch_under_the_spend_counters_target() -> None:
natives: Final = FakeNatives()
targets: Final[list[str | None]] = []
class Recording(FakeSpendCounters):
def increment_many_post_call(self, request: object, increments: object) -> FakeSettlement | None:
targets.append(current_service_target())
return super().increment_many_post_call(request, increments) # pyright: ignore[reportArgumentType] # recorded as given
spend: Final = Recording()
store: Final = spend.store()
outside: Final = store.increment_many_post_call((("spend:key:k", 1.0),))
with request_redis_batch_scope(native_factory=natives, native_send_factory=fake_send): # pyright: ignore[reportArgumentType] # test double
inside: Final = store.increment_many_post_call((("spend:key:k", 1.0),))
empty: Final = store.increment_many_post_call(())
assert (outside, empty) == (None, None)
assert spend.post_call == [(natives.built[0], (("spend:key:k", 1.0),), inside)]
assert targets == [SPEND_COUNTERS_TARGET]
@pytest.mark.asyncio
async def test_an_unreachable_redis_fails_writes_as_transport_and_serves_reads_from_memory() -> None:
store: Final = NativeSpendCounters(
NativeRedisClient.connect(
RedisStoreSettings(
redis_kwargs={"host": "127.0.0.1", "port": 1, "socket_timeout": 0.2},
namespace=None,
default_ttl=60,
breaker=None,
)
)
)
store.set_local("spend:key:k", 4.0)
with pytest.raises(NativeRedisStoreError) as failure:
await store.increment("spend:key:k", 1.0)
assert failure.value.args[0] == "transport"
assert not is_unavailable(failure.value)
assert await store.read("spend:key:k") == SpendRead(None, from_redis=False)