litellm/tests/unit/redis/stores/test_spend_counters.py
ishaan-j-berri 6eda17aadb
fix(proxy): enforce settled customer budgets across workers (#51568)
* fix(proxy): enforce settled customer budgets across workers

Co-Authored-By: Ishaan Jaffer <155045088+ishaan-berri@users.noreply.github.com>

* fix(proxy): sync customer budget reset API types

Co-Authored-By: Ishaan Jaffer <155045088+ishaan-berri@users.noreply.github.com>

* fix(proxy): reseed customer spend through shared counters

Co-Authored-By: Ishaan Jaffer <155045088+ishaan-berri@users.noreply.github.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Ishaan Jaffer <155045088+ishaan-berri@users.noreply.github.com>
2026-11-13 07:33:24 -08:00

214 lines
8.7 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.redis_batch_double 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"),
("spend:customer_org:tenant:lifetime", "spend:customer_org:tenant:lifetime"),
(
"spend:customer_team:tenant:team:2026-01-01T00:00:00+00:00",
"spend:customer_team:tenant:team:2026-01-01T00:00:00+00:00",
),
("spend:customer_member:user@example.com:lifetime", "spend:customer_member:user@example.com:lifetime"),
(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)