litellm/litellm-rust/crates/redis-store/AGENTS.md
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

4.9 KiB

  • One folder per Redis family (router_cooldowns/, router_usage/, spend_counters/, auth_cache/, rate_limits/), each with mod.rs (the store and its ops), keys.rs (key types and spellings) and types.rs (the family's values, with the FromValue / IntoValue codecs for what it stores in Redis). It is the only place that family's keys, value codec and scripts are written, and it takes domain ids, never keys. Shared pieces live once at the crate root: Error and ErrorKind (error.rs), Memory and Clock (memory.rs), Pending (request.rs), Remote and its attach-once RemoteSlot, which knows nothing of memory (remote.rs), DualCache (dual_cache/) and the Python codecs (codec.rs, value.rs)
  • An op declared on a Send returns Pending<T>, a lazy future built when the op is declared. An op that only means something on Redis (an MGET the caller falls back from, a script) returns None without one, and an op that replaced a DualCache call answers from memory. A post-call method returns false when there was no Redis to declare on, or None when it returns a settlement the caller waits on, like SpendCounterStore::increment_many_post_call
  • A store that sends a pipeline of its own uses RedisBatch::pipelined, never Pipeline and raw Values
  • Python and Rust pods share these keys during a rolling deploy, so a module writes the bytes main's Python writes and reads everything main reads. Python formats go through litellm-python-compat (repr, literal_eval, json), never a hand-rolled codec
  • A family holds one DualCache per DualCache its Python held on main, and each DualCache method is the Python method it names, so a family op that was a DualCache call is one call here. Where main's Python reached past DualCache to in_memory_cache or redis_cache, the family does the same through memory() and redis(), which keeps that reach visible. Caches a family's Python attached to one RedisCache share one Arc<RemoteSlot>. Only a family that batch-reads builds its cache with DualCache::batch_reading from a TierPolicy the host passes in, and the Python host fills it from what main reads from the environment or litellm globals (litellm/rust_bridge/host/settings.py, router_tiers). Callers pass a Remote (or none), never a cache. Redis-only families are plain functions over &RedisClient
  • Every family works with no Redis, answering from memory. attach adds the Redis tier at most once and keeps memory, as DualCache.attach_redis_cache does, so a host builds the store at startup and never rebuilds it to connect
  • Where main swallows a Redis failure and serves memory, the family does the same and logs. It never turns a failure into a miss that main would not
  • Key suffixes and wire spellings derive from strum on the family's enums. A value the family stores in Redis implements FromValue / IntoValue over litellm_python_compat::Value. An argument or reply is a typed record, never a positional tuple: a frozen Python dataclass read in python-bridge by a #[derive(FromPyObject)] struct with #[pyo3(attribute)] fields and converted into the family's type with From, and a reply returned as a frozen #[pyclass]. The bridge reads an enum through its strum spelling, never a hand-written match
  • Wire contracts are hand-written cases with expected values, inlined as the same literals in this crate's test and in tests/unit/redis/stores/, checked here against real Redis and there against Python's own codec. Change both sides together
  • rate_limits.rs keeps the v3 limiter's Lua byte for byte (rate_limits/lua.rs) so pods on either stack share one script SHA; the admission decisions stay in the Python limiter
  • RequestRedis is one request's batches: a pre-call and a post-call RedisBatch per client, the post one flushed by flush_post or its deadline. Each op exists once and takes a Send (Now, PreCall, PostCall) picked by the caller, and the store calls send.batch(&client). A store never encodes a phase in a method name. A post-call method exists only where a follow-up runs after the write settles (token_increment_post_call), as a thin wrapper over the shared op. Send::Now is an alone batch, so a script call outside a request goes out alone, like a redis-py Script outside a pipeline, so NOSCRIPT costs SCRIPT LOAD and one more EVALSHA the way it does on main. Only what main's Python puts on its request pipeline rides these batches. An op main sends on its own round trip, like a deployment's tpm and rpm increment, stays on its own round trip here
  • Every store sends the commands main's RedisCache sends for that operation: MGET where Python reads several keys at once, SET ... EX, and INCRBYFLOAT with EXPIRE or TTL. A MONITOR diff against main is a parity check, and any difference is a defect
  • Tests run against litellm-redis-testing on standalone and cluster. A test is single-topology only for outages