Repository navigation
Conversation
…ost (BerriAI#26672) When a per-window spend counter (budget_duration windows) is lost — Redis flush/failover in multi-pod deployments — get_current_spend used to fall through to the caller-supplied fallback, which was hard-coded 0.0 for window checks. The window then read as brand-new and the budget gate admitted requests far past the window cap (issue BerriAI#26672: $30 cap, $99 spent, still admitted). Fix: - get_current_spend now reseeds a cold window counter from the per-window DB total (maintained window-spend row, spend-logs aggregate fallback) instead of trusting the missing counter. - The caller fallback for window checks is the entity's cumulative spend (conservative upper bound), applied only when the DB is also unreachable, so a lost counter can never read as an empty window while remaining fail-closed on DB outage. - spend_counter_reseed.coalesced_window gains require_cache_warm to keep write-path failure semantics unchanged. Verified red→green: 4 repro tests fail on unfixed code, all pass with the fix; window-rollover still admits correctly after reset (no over-blocking). 2662 tests in tests/proxy/auth + tests/proxy/proxy_server pass (1 pre-existing unrelated date-dependent failure on base).
Greptile SummaryThis PR hardens per-window budget enforcement when shared counters disappear
Confidence Score: 3/5This PR is not safe to merge until failed warming and lagging persisted spend cannot permit uncoordinated window-budget admission Missing counters can still produce low admission values when cache warming fails or persisted window rows lag queued spend, and the new request-path queries and rollover fallback violate repository requirements Files Needing Attention: litellm/proxy/db/spend_counter_reseed.py, litellm/proxy/proxy_server.py, litellm/proxy/auth/auth_checks.py
|
| Filename | Overview |
|---|---|
| litellm/proxy/auth/auth_checks.py | Changes key and team window fallbacks to cumulative spend, which protects enforcement but alters degraded rollover behavior without a flag |
| litellm/proxy/db/spend_counter_reseed.py | Makes cache warming optional for read-time reseeds, allowing admission from an uncoordinated database snapshot after warming fails |
| litellm/proxy/proxy_server.py | Adds request-path database reseeding that can restore lagging persisted spend and conflicts with critical-path database-access requirements |
| tests/test_litellm/proxy/auth/test_multi_budget_windows.py | Adds focused key and team regression tests for missing counters and cumulative fallbacks |
| tests/test_litellm/proxy/proxy_server/test_spend_counters.py | Adds cold-counter reseeding and rollover tests, but does not cover failed warming or queued unpersisted spend |
Reviews (1): Last reviewed commit: "fix(proxy): close budget-window bypass w..." | Re-trigger Greptile
| ) | ||
| raise | ||
| if require_cache_warm: | ||
| raise |
There was a problem hiding this comment.
Failed Warm Loses Coordination
If cache warming fails, admission trusts the DB snapshot while default reservations skip the cold counter, allowing concurrent requests to exceed the window
Knowledge Base Used: Spend, budgets, and rate limits
| if window_start is not None and window_entity_type is not None and window_entity_id is not None: | ||
| window_spend: Final = await SpendCounterReseed.coalesced_window( | ||
| prisma_client=prisma_client, | ||
| spend_counter_cache=spend_counter_cache, | ||
| counter_key=counter_key, | ||
| entity_type=window_entity_type, | ||
| entity_id=window_entity_id, | ||
| window_duration=window_duration, | ||
| window_start=window_start, | ||
| ) | ||
| if window_spend is not None: | ||
| return window_spend, True |
There was a problem hiding this comment.
A flush before queued spend reaches the database restores a low counter, which can admit traffic that already exceeds the window budget
Knowledge Base Used: Spend, budgets, and rate limits
| if window_start is not None and window_entity_type is not None and window_entity_id is not None: | ||
| window_spend: Final = await SpendCounterReseed.coalesced_window( | ||
| prisma_client=prisma_client, | ||
| spend_counter_cache=spend_counter_cache, | ||
| counter_key=counter_key, | ||
| entity_type=window_entity_type, | ||
| entity_id=window_entity_id, | ||
| window_duration=window_duration, | ||
| window_start=window_start, |
There was a problem hiding this comment.
Authentication Adds Direct Queries
Cold window authentication now queries persisted spend directly, violating the requirement that critical-path database access use get_team, get_user, or get_key helpers
Rule Used: What: In critical path of request, there should be no direct db queries. Only allow them to be made via the get_team/get_user/get_key object helper functions Why: prevent db regressions (source)
Knowledge Base Used: Spend, budgets, and rate limits
| counter_key=counter_key, | ||
| fallback_spend=0.0, | ||
| fallback_spend=valid_token.spend or 0.0, | ||
| max_budget=w["max_budget"], |
There was a problem hiding this comment.
Rollover Behavior Changes Unconditionally
Key and team windows now use cumulative spend during outages, violating the requirement to gate backward-incompatible behavior before merging
Rule Used: What: avoid backwards-incompatible changes without user-controlled flags Why: This breaks current behaviour for users using existing functionality Example of BAD: this PR (#22164) introduced run_post_custom... (source)
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
- Reseed floors the maintained row at the spend-logs aggregate: the row lags queued increments by up to one flush interval, so restoring a cold counter from it alone could admit traffic past the budget. - coalesced_window drops the DB snapshot when the counter cannot be re-warmed (it never coordinated with concurrent reservations) and returns None so callers use their conservative fallback; NX losers adopt the winner's value instead of an uncoordinated snapshot. - Gate the key/team cumulative-spend fallback behind general_settings.cumulative_window_fallback (default on) so degraded rollover behavior stays opt-out for existing setups.
|
Thanks for the thorough review — all four points addressed in 54d1424. 1. Failed cache warm returned an un-coordinated snapshot (P1) 2. Lagging persisted spend under-counted queued increments (P1) 3. DB reseed on the request path 4. Cumulative-spend fallback changed degraded-path behavior All 95 tests across the three touched suites pass locally; patch lines flagged by codecov are now covered. |
| return window_spend | ||
| # Without a warm counter the DB snapshot never coordinated | ||
| # with concurrent reservations (they skipped the cold counter | ||
| # instead of incrementing it), so returning it here would let |
| entity_type=window_entity_type, | ||
| entity_id=window_entity_id, | ||
| window_duration=window_duration, | ||
| window_start=window_start, |
Problem
Per-window budgets (via
budget_duration/budget_limits) can be bypassed when the Redis per-window spend counter is lost mid-window — e.g. Redis flush or failover in a multi-pod deployment. Reported in #26672: a key with a 30 USD/day hard cap kept being admitted at 99 USD spent. Not reproducible on a single pod (in-memory fallback there), which is why it went unfixed.Root cause
get_current_spendfalls back to the caller-suppliedfallback_spendwhen neither Redis nor in-memory has the counter. For window checks (_virtual_key_multi_budget_check/_team_multi_budget_check) that fallback was hard-coded0.0, and the existing DB-reseed path (SpendCounterReseed.coalesced) only covers primary (cumulative) counters — window counter keys (:window:) have no entity row to reseed from. Net effect: a lost counter makes the current window read as brand-new → budget gate waves everything through.Fix
get_current_spendnow reseeds a cold window counter from the per-window DB total (maintained window-spend row; spend-logs aggregate fallback) instead of trusting the missing counter.spend_counter_reseed.coalesced_windowgainsrequire_cache_warm(aligns with existingcoalescedpattern) so write-path failure semantics are unchanged.Why not just use cumulative spend as the fallback everywhere?
That over-blocks: after a legitimate window rollover + counter loss, the cumulative spend (99) would permanently block a fresh window (cap 30). The read-path DB reseed handles both cases correctly — in-window loss reseeds the true window spend; post-rollover loss reads the already-rolled row (0) and admits. The cumulative upper bound is only the last-resort when the DB is unreachable.
Tests (red → green verified)
New tests in
tests/test_litellm/proxy/proxy_server/test_spend_counters.pyandtests/test_litellm/proxy/auth/test_multi_budget_windows.py:test_flushed_window_counter_with_over_budget_key_spend_still_rejects— the [Bug]: Budget enforcement bypassed in v1.82.3 for key/user max_budget despite spend exceeding max_budget #26672 repro (flush + no DB + spend 99 > cap 30 → must reject) — red on unfixed codetest_flushed_window_counter_with_over_budget_team_spend_still_rejects— same hole on the team side — red on unfixed codetest_get_current_spend_cold_window_counter_reseeds_from_db— cold window counter reseeds 31.0 from the maintained row and writes back to Redistest_get_current_spend_window_rollover_admits_after_window_rollover— rollover + counter loss + cumulative 99 → must admit (guards against over-blocking)Confirmed by stashing the source changes: 4 repro tests fail on unfixed code, all pass with the fix. Full
tests/proxy/auth+tests/proxy/proxy_serversuites: 2662 passed, 1 pre-existing date-dependent failure also present on base.Closes #26672