Skip to content

fix(proxy): close budget-window bypass when Redis window counter is lost - #40600

Open
Jackzigen wants to merge 2 commits into
BerriAI:mainfrom
Jackzigen:fix/budget-enforcement-window-counter-reseed
Open

Jackzigen wants to merge 2 commits into
BerriAI:mainfrom
Jackzigen:fix/budget-enforcement-window-counter-reseed

Conversation

@Jackzigen

Copy link
Copy Markdown

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_spend falls back to the caller-supplied fallback_spend when neither Redis nor in-memory has the counter. For window checks (_virtual_key_multi_budget_check / _team_multi_budget_check) that fallback was hard-coded 0.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

  1. 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.
  2. The caller fallback for window checks is now the entity's cumulative spend (conservative upper bound of any single window), 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.
  3. spend_counter_reseed.coalesced_window gains require_cache_warm (aligns with existing coalesced pattern) 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.py and tests/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 code
  • test_flushed_window_counter_with_over_budget_team_spend_still_rejects — same hole on the team side — red on unfixed code
  • test_get_current_spend_cold_window_counter_reseeds_from_db — cold window counter reseeds 31.0 from the maintained row and writes back to Redis
  • test_get_current_spend_window_rollover_admits_after_window_rollover — rollover + counter loss + cumulative 99 → must admit (guards against over-blocking)
  • plus rollover-reset and under-budget-loss regression tests

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_server suites: 2662 passed, 1 pre-existing date-dependent failure also present on base.

Closes #26672

…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).
@CLAassistant

CLAassistant commented Sep 10, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@codspeed

codspeed Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing Jackzigen:fix/budget-enforcement-window-counter-reseed (54d1424) with main (362033c)

Open in CodSpeed

@greptile-apps

greptile-apps Bot commented Sep 10, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR hardens per-window budget enforcement when shared counters disappear

  • It reseeds cold key and team window counters from persisted window totals
  • It uses cumulative entity spend when neither shared counters nor persisted window totals are available
  • It adds regression coverage for counter loss, rollover, database reseeding, and key and team enforcement
  • The recovery path still has two blocking correctness gaps and violates critical-path database-access and compatibility requirements

Confidence Score: 3/5

This 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

Important Files Changed

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 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

Comment on lines +2738 to +2749
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Reseed Restores Stale Spend

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

Comment on lines +2738 to +2746
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,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 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"],

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 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

codecov Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

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.
@Jackzigen

Copy link
Copy Markdown
Author

Thanks for the thorough review — all four points addressed in 54d1424.

1. Failed cache warm returned an un-coordinated snapshot (P1)
coalesced_window now drops the DB snapshot when the counter cannot be re-warmed and returns None, so the read path falls back to the caller's conservative cumulative spend instead of admitting on a value that never coordinated with concurrent reservations (test_coalesced_window_returns_none_when_warm_fails, test_get_current_spend_cold_window_counter_warm_failure_uses_conservative_fallback). The NX-loser branch also now adopts the winner's seeded value rather than returning its own un-coordinated snapshot.

2. Lagging persisted spend under-counted queued increments (P1)
The reseed path now floors the maintained row at the spend-logs aggregate (include_logs_floor=True): max(row, aggregate). The row lags increments queued on other pods by up to one flush interval; the aggregate cannot lag what pods already counted, so it floors the row. This stays off the steady-state stale-counter recheck (which has a performance pin): that path keeps the pure row read via include_logs_floor=False.

3. DB reseed on the request path
Kept intentionally, and scoped narrowly: the reseed only runs on a cold window counter (Redis flush / first read after deployment) — a rare event by design, not a per-request DB hit. Once seeded via SET NX, subsequent reads and increments stay in Redis, so the steady-state request path remains DB-free. The aggregate scan only happens on that rare cold reseed (or when no current row exists), never on the pinned steady-state recheck. Moving it to a background job would leave a window where a lost counter reads as a fresh empty budget — exactly the #26672 leak this PR fixes.

4. Cumulative-spend fallback changed degraded-path behavior
The key/team window fallback to cumulative spend (when both the counter and the per-window DB total are unreadable) is now gated behind general_settings.cumulative_window_fallback — default on (the fixed behavior), settable to false to to restore the pre-PR behavior for operators who prefer the old rollover semantics during a DB outage.

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,

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants