Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

test(e2e): assert the long budget window keeps blocking after the short window resets (#33832)

ryan-crabbe-berri595e72472a8f
diff --git a/tests/e2e/models.py b/tests/e2e/models.py
index 8d19e2f8965..97f72c487b7 100644
--- a/tests/e2e/models.py
+++ b/tests/e2e/models.py
@@ -6,6 +6,7 @@ response validates without mirroring every proxy field. No untyped dicts.
from __future__ import annotations
+from datetime import datetime
from typing import Literal
from pydantic import BaseModel, ConfigDict, RootModel, model_validator
@@ -23,6 +24,10 @@ class BudgetWindow(BaseModel):
max_budget: float
+class BudgetWindowState(BudgetWindow):
+ reset_at: datetime | None = None
+
+
class KeyLoggingCallbackVars(BaseModel):
langfuse_public_key: str | None = None
langfuse_secret_key: str | None = None
@@ -94,6 +99,7 @@ class KeyInfo(BaseModel):
budget_reset_at: str | None = None
budget_id: str | None = None
litellm_budget_table: LiteLLMBudgetTable | None = None
+ budget_limits: list[BudgetWindowState] | None = None
class KeyInfoResponse(BaseModel):
diff --git a/tests/e2e/quota_management/budgets/budget_client.py b/tests/e2e/quota_management/budgets/budget_client.py
index 53da8f68b1b..83e8f27b597 100644
--- a/tests/e2e/quota_management/budgets/budget_client.py
+++ b/tests/e2e/quota_management/budgets/budget_client.py
@@ -12,14 +12,16 @@ from __future__ import annotations
import time
from dataclasses import dataclass
+from datetime import datetime
from pydantic import AliasPath, BaseModel, Field, RootModel
-from proxy_client import ProxyClient
from e2e_http import NoBody, Result, StreamingResponse, Success, unwrap
+from proxy_client import ProxyClient
from models import (
AnthropicMessagesBody,
BudgetWindow,
+ BudgetWindowState,
ChatBody,
ChatMessage,
ChatMetadata,
@@ -130,8 +132,13 @@ class TeamInfoParams(BaseModel):
team_id: str
+class TeamInfoRow(BaseModel):
+ budget_limits: list[BudgetWindowState] | None = None
+
+
class TeamInfoResponse(BaseModel):
team_memberships: list[TeamMembershipRow] = []
+ team_info: TeamInfoRow | None = None
class TagNewBody(BaseModel):
@@ -173,6 +180,10 @@ class BudgetInfoResponse(RootModel[list[BudgetRow]]):
pass
+def window_reset_at(windows: list[BudgetWindowState], budget_duration: str) -> datetime | None:
+ return next((w.reset_at for w in windows if w.budget_duration == budget_duration), None)
+
+
def is_budget_block(result: StreamingResponse) -> bool:
"""True if the call was rejected for being over budget (vs a provider error)."""
return not result.ok and "budget_exceeded" in result.body
@@ -221,6 +232,20 @@ class BudgetClient:
def delete_key(self, key: str) -> None:
self.proxy.delete_key(key)
+ def key_budget_windows(self, key: str) -> list[BudgetWindowState]:
+ """A key's budget_limits windows as /key/info stores them. Each window's
+ reset_at is advanced by the reset job in the same pass that zeroes the
+ window's spend counter, so a strictly-later value proves the wipe ran."""
+ return self.proxy.key_info(key).budget_limits or []
+
+ def team_budget_windows(self, team_id: str) -> list[BudgetWindowState]:
+ """Team analog of key_budget_windows, read from /team/info."""
+ match self._team_info(team_id):
+ case Success(data=data) if data.team_info is not None:
+ return data.team_info.budget_limits or []
+ case _:
+ return []
+
def delete_customers(self, user_ids: list[str]) -> None:
self.proxy.delete_customers(user_ids)
@@ -386,15 +411,18 @@ class BudgetClient:
response_type=NoBody,
)
+ def _team_info(self, team_id: str) -> Result[TeamInfoResponse]:
+ return self.proxy.transport.get(
+ "/team/info",
+ headers=self.proxy.transport.master,
+ params=TeamInfoParams(team_id=team_id),
+ response_type=TeamInfoResponse,
+ )
+
def _wait_for_team(self, team_id: str) -> None:
last: Result[TeamInfoResponse] | None = None
for _ in range(_TEAM_READY_ATTEMPTS):
- last = self.proxy.transport.get(
- "/team/info",
- headers=self.proxy.transport.master,
- params=TeamInfoParams(team_id=team_id),
- response_type=TeamInfoResponse,
- )
+ last = self._team_info(team_id)
match last:
case Success():
return
@@ -448,13 +476,7 @@ class BudgetClient:
"""The member's per-team budget_reset_at as /team/info reports it, or None if
no reset is scheduled. The reset job advances this each time the window
elapses; a job that skips the row leaves it pinned forever."""
- result = self.proxy.transport.get(
- "/team/info",
- headers=self.proxy.transport.master,
- params=TeamInfoParams(team_id=team_id),
- response_type=TeamInfoResponse,
- )
- match result:
+ match self._team_info(team_id):
case Success(data=data):
return next(
(row.budget_reset_at for row in data.team_memberships if row.user_id == user_id),
diff --git a/tests/e2e/quota_management/budgets/test_multi_window_budget_e2e.py b/tests/e2e/quota_management/budgets/test_multi_window_budget_e2e.py
index 45e2bf539d4..e1cca0c0414 100644
--- a/tests/e2e/quota_management/budgets/test_multi_window_budget_e2e.py
+++ b/tests/e2e/quota_management/budgets/test_multi_window_budget_e2e.py
@@ -6,15 +6,22 @@ its 30s elapses and the reset job runs (rescheduled fast via
PROXY_BUDGET_RESCHEDULER_* in docker-compose) - the window resets and calls flow
again. Closes the multi-window gap (enforcement + per-window reset) in
BUDGET_TEST_COVERAGE_MATRIX.md, which the unit suite covered but no live test did.
+
+The second test is the long-window direction: one burn crosses
+both caps; after the 30s window's reset_at strictly advances (read post-block since
+a mint-time read races the boundary; the reset job zeroes the counter in the same
+pass), the key must still be refused with "over 1d budget". That check polls because
+enforcement's cached auth view lags the DB write; any 200 or non-budget error fails
+immediately.
"""
import time
import pytest
-from budget_client import BudgetClient, is_budget_block
+from budget_client import BudgetClient, is_budget_block, window_reset_at
+from e2e_http import StreamingResponse, require_successful_call
from e2e_config import CHEAP_OPENAI_MODEL, unique_marker
-from e2e_http import require_successful_call
from lifecycle import ResourceManager
from models import BudgetWindow
@@ -28,22 +35,33 @@ WINDOW_SECONDS = 30 # the tight window; calls succeed again only after it elaps
# max_tokens must be >1: gpt-5.5 refuses completions that hit the output limit
# mid-message when capped at 1 token.
MODEL = CHEAP_OPENAI_MODEL
+SHORT_WINDOW = f"{WINDOW_SECONDS}s"
+LONG_WINDOW = "1d"
+TINY_CAP = 1e-9
+LONG_CAP = 5e-7
+RESET_DEADLINE_SECONDS = 150
def _call(client: BudgetClient, key: str):
- return client.chat(
- key, MODEL, f"window {unique_marker()}", max_tokens=16
- )
+ return client.chat(key, MODEL, f"window {unique_marker()}", max_tokens=16)
+
+
+def _drive_to_block(client: BudgetClient, key: str) -> StreamingResponse:
+ for _ in range(20):
+ result = _call(client, key)
+ if is_budget_block(result):
+ return result
+ require_successful_call(result)
+ time.sleep(2)
+ pytest.fail("budget never enforced before block")
@pytest.mark.covers("quota_management.budget.key_multi_window.blocks_then_resets")
-def test_short_window_blocks_then_resets(
- client: BudgetClient, resources: ResourceManager
-) -> None:
+def test_short_window_blocks_then_resets(client: BudgetClient, resources: ResourceManager) -> None:
key = client.generate_key(
models=[MODEL],
budget_limits=[
- BudgetWindow(budget_duration=f"{WINDOW_SECONDS}s", max_budget=1e-9),
+ BudgetWindow(budget_duration=SHORT_WINDOW, max_budget=TINY_CAP),
BudgetWindow(budget_duration="1m", max_budget=1.0), # roomy: never blocks
],
)
@@ -51,15 +69,7 @@ def test_short_window_blocks_then_resets(
# 1. exhaust the tight window -> litellm returns budget_exceeded
start = time.monotonic()
- blocked = False
- for _ in range(20):
- result = _call(client, key)
- if is_budget_block(result):
- blocked = True
- break
- require_successful_call(result)
- time.sleep(2)
- assert blocked, f"{WINDOW_SECONDS}s window never enforced"
+ _drive_to_block(client, key)
# 2. the window resets at the next wall-clock-aligned boundary (up to a window
# after start), then the reset job (~15-20s rescheduler) zeroes the spend.
@@ -71,12 +81,66 @@ def test_short_window_blocks_then_resets(
result = _call(client, key)
if result.ok:
elapsed = time.monotonic() - start
- assert elapsed < WINDOW_SECONDS + 90, (
- f"reset took {elapsed:.0f}s - too long for a {WINDOW_SECONDS}s window"
- )
+ assert elapsed < WINDOW_SECONDS + 90, f"reset took {elapsed:.0f}s - too long for a {WINDOW_SECONDS}s window"
return
assert is_budget_block(result), (
- f"non-budget error during reset wait: status={result.status_code} "
- f"body={result.body[:200]}"
+ f"non-budget error during reset wait: status={result.status_code} body={result.body[:200]}"
)
pytest.fail(f"{WINDOW_SECONDS}s window never reset within 150s")
+
+
[email protected]("quota_management.budget.key_multi_window.blocks_then_resets")
+def test_long_window_blocks_after_short_window_resets(client: BudgetClient, resources: ResourceManager) -> None:
+ key = client.generate_key(
+ models=[MODEL],
+ budget_limits=[
+ BudgetWindow(budget_duration=SHORT_WINDOW, max_budget=TINY_CAP),
+ BudgetWindow(budget_duration=LONG_WINDOW, max_budget=LONG_CAP),
+ ],
+ )
+ resources.defer(lambda: client.delete_key(key))
+
+ # 1. drive the key to get blocked by SHORT_WINDOW, assert it's budget error
+ blocked = _drive_to_block(client, key)
+ assert blocked.status_code == 429, f"budget block was not a 429: {blocked.status_code} {blocked.body[:200]}"
+
+ # 2. check the reset times of both budget windows after we drove to being blocked
+ blocked_reset_at = window_reset_at(client.key_budget_windows(key), SHORT_WINDOW)
+ assert blocked_reset_at is not None, "short window missing from /key/info budget_limits"
+ blocked_long_reset_at = window_reset_at(client.key_budget_windows(key), LONG_WINDOW)
+ assert blocked_long_reset_at is not None, "long window missing from /key/info budget_limits"
+
+ # 3. poll every 5s for the SHORT_WINDOW reset time until it is past it, fails if it doesnt reset
+ deadline = time.monotonic() + RESET_DEADLINE_SECONDS
+ while time.monotonic() < deadline:
+ time.sleep(5)
+ current = window_reset_at(client.key_budget_windows(key), SHORT_WINDOW)
+ if current is not None and current > blocked_reset_at:
+ break
+ else:
+ pytest.fail(
+ f"{SHORT_WINDOW} window's reset_at never advanced past {blocked_reset_at} within {RESET_DEADLINE_SECONDS}s"
+ )
+
+ # 4. short window just reset in 3, so now make a call, check that its blocked (should be blocked by LONG_WINDOW because short window reset), also make sure its budget error
+ deadline = time.monotonic() + RESET_DEADLINE_SECONDS
+ last_body = ""
+ while time.monotonic() < deadline:
+ result = _call(client, key)
+ if result.ok:
+ rolled = window_reset_at(client.key_budget_windows(key), LONG_WINDOW) != blocked_long_reset_at
+ pytest.fail(
+ f"{LONG_WINDOW} window failed to block after the {SHORT_WINDOW} window reset"
+ + (f" (the {LONG_WINDOW} window itself rolled mid-test - boundary crossed; rerun)" if rolled else "")
+ )
+ assert is_budget_block(result), (
+ f"non-budget error while waiting for {LONG_WINDOW} attribution: "
+ f"status={result.status_code} body={result.body[:200]}"
+ )
+ if f"over {LONG_WINDOW} budget" in result.body:
+ return
+ last_body = result.body
+ time.sleep(5)
+ pytest.fail(
+ f"block never attributed to the {LONG_WINDOW} window within {RESET_DEADLINE_SECONDS}s: {last_body[:200]}"
+ )
diff --git a/tests/e2e/quota_management/budgets/test_team_multi_window_budget_e2e.py b/tests/e2e/quota_management/budgets/test_team_multi_window_budget_e2e.py
index c89807fd59d..1db68e6afe9 100644
--- a/tests/e2e/quota_management/budgets/test_team_multi_window_budget_e2e.py
+++ b/tests/e2e/quota_management/budgets/test_team_multi_window_budget_e2e.py
@@ -11,33 +11,52 @@ This also guards the /team/new write path: it must json.dumps the window list in
the Json? column. A raw list there made Prisma reject the create with a 500 (the key
path and /team/update already json.dumps first); a regression would fail team creation
here.
+
+The second test is the long-window direction, mirroring the
+key-side test (see its docstring): after the team's 30s window provably resets, the
+1d window the same burn crossed must still block the team key with "over 1d budget".
"""
import time
import pytest
-from budget_client import BudgetClient, is_budget_block
+from budget_client import BudgetClient, is_budget_block, window_reset_at
+from e2e_http import StreamingResponse, require_successful_call
from e2e_config import unique_marker
-from e2e_http import require_successful_call
from lifecycle import ResourceManager
from models import BudgetWindow
pytestmark = pytest.mark.e2e
WINDOW_SECONDS = 30
+SHORT_WINDOW = f"{WINDOW_SECONDS}s"
+LONG_WINDOW = "1d"
+TINY_CAP = 1e-9
+LONG_CAP = 5e-7
+RESET_DEADLINE_SECONDS = 150
def _call(client: BudgetClient, key: str):
return client.chat(key, "claude-haiku-4-5", f"team-window {unique_marker()}", max_tokens=16)
+def _drive_to_block(client: BudgetClient, key: str) -> StreamingResponse:
+ for _ in range(30):
+ result = _call(client, key)
+ if is_budget_block(result):
+ return result
+ require_successful_call(result)
+ time.sleep(1)
+ pytest.fail("team budget never enforced before block")
+
+
@pytest.mark.covers("quota_management.budget.team_multi_window.blocks_then_resets")
def test_team_short_window_blocks_then_resets(client: BudgetClient, resources: ResourceManager) -> None:
team_id = client.create_team(
alias=f"e2e-team-window-{unique_marker()}",
budget_limits=[
- BudgetWindow(budget_duration=f"{WINDOW_SECONDS}s", max_budget=3e-6),
+ BudgetWindow(budget_duration=SHORT_WINDOW, max_budget=3e-6),
BudgetWindow(budget_duration="1m", max_budget=1.0), # roomy: never blocks
],
)
@@ -47,15 +66,7 @@ def test_team_short_window_blocks_then_resets(client: BudgetClient, resources: R
# 1. exhaust the tight window -> litellm returns budget_exceeded
start = time.monotonic()
- blocked = False
- for _ in range(30):
- result = _call(client, key)
- if is_budget_block(result):
- blocked = True
- break
- require_successful_call(result)
- time.sleep(1)
- assert blocked, f"team {WINDOW_SECONDS}s window never enforced"
+ _drive_to_block(client, key)
# 2. the window resets at the next wall-clock-aligned boundary (up to a window
# after start), then the reset job (~15-20s rescheduler) zeroes the spend.
@@ -71,3 +82,65 @@ def test_team_short_window_blocks_then_resets(client: BudgetClient, resources: R
return
assert is_budget_block(result), f"non-budget error during reset wait: {result.body[:200]}"
pytest.fail(f"team {WINDOW_SECONDS}s window never reset within 150s")
+
+
[email protected]("quota_management.budget.team_multi_window.blocks_then_resets")
+def test_team_long_window_blocks_after_short_window_resets(client: BudgetClient, resources: ResourceManager) -> None:
+
+ # 0. key with a short budget window and a long budget window
+ team_id = client.create_team(
+ alias=f"e2e-team-long-window-{unique_marker()}",
+ budget_limits=[
+ BudgetWindow(budget_duration=SHORT_WINDOW, max_budget=TINY_CAP),
+ BudgetWindow(budget_duration=LONG_WINDOW, max_budget=LONG_CAP),
+ ],
+ )
+ resources.defer(lambda: client.delete_team(team_id))
+ key = client.generate_key(team_id=team_id, models=["claude-haiku-4-5"])
+ resources.defer(lambda: client.delete_key(key))
+
+ # 1. drive the key to being blocked, assert its blocked by budget budget_exceeded
+ blocked = _drive_to_block(client, key)
+ assert blocked.status_code == 429, f"budget block was not a 429: {blocked.status_code} {blocked.body[:200]}"
+
+ # 2. check the the teams budget windows
+ blocked_reset_at = window_reset_at(client.team_budget_windows(team_id), SHORT_WINDOW)
+ assert blocked_reset_at is not None, "short window missing from /team/info budget_limits"
+ blocked_long_reset_at = window_reset_at(client.team_budget_windows(team_id), LONG_WINDOW)
+ assert blocked_long_reset_at is not None, "long window missing from /team/info budget_limits"
+
+ # 3. keep checking that the short budget window reset, if it doesnt within the deadline then fail
+ deadline = time.monotonic() + RESET_DEADLINE_SECONDS
+ while time.monotonic() < deadline:
+ time.sleep(5)
+ current = window_reset_at(client.team_budget_windows(team_id), SHORT_WINDOW)
+ if current is not None and current > blocked_reset_at:
+ break
+ else:
+ pytest.fail(
+ f"team {SHORT_WINDOW} window's reset_at never advanced past "
+ f"{blocked_reset_at} within {RESET_DEADLINE_SECONDS}s"
+ )
+
+ # 4. short window just reset in 3, so now make another call, assert that the long window blocks the next call with budget_exceeded
+ deadline = time.monotonic() + RESET_DEADLINE_SECONDS
+ last_body = ""
+ while time.monotonic() < deadline:
+ result = _call(client, key)
+ if result.ok:
+ rolled = window_reset_at(client.team_budget_windows(team_id), LONG_WINDOW) != blocked_long_reset_at
+ pytest.fail(
+ f"team {LONG_WINDOW} window failed to block after the {SHORT_WINDOW} window reset"
+ + (f" (the {LONG_WINDOW} window itself rolled mid-test - boundary crossed; rerun)" if rolled else "")
+ )
+ assert is_budget_block(result), (
+ f"non-budget error while waiting for {LONG_WINDOW} attribution: "
+ f"status={result.status_code} body={result.body[:200]}"
+ )
+ if f"over {LONG_WINDOW} budget" in result.body:
+ return
+ last_body = result.body
+ time.sleep(5)
+ pytest.fail(
+ f"team block never attributed to the {LONG_WINDOW} window within {RESET_DEADLINE_SECONDS}s: {last_body[:200]}"
+ )