farient-deckcheck / tests /test_rate_limit.py
Xander Labide
Claude Opus 4.7 (1M context)
Initial commit β€” Farient DeckCheck
fdfe81a
Raw History Blame Contribute Delete
7.12 kB
"""Unit tests for ``services.rate_limit.TokenRateLimiter``.
The limiter is a sliding-window TPM throttle. Tests cover:
* Calls within budget pass without waiting.
* Calls that would breach budget block until the oldest entry ages out.
* The window is per-model β€” gpt-4o and gpt-4o-mini have independent buckets.
* ``record`` lets callers backfill actual usage on top of the estimate.
* Single-call requests larger than the configured budget raise loudly
rather than block forever (defensive guard).
We use a fake monotonic clock so tests stay synchronous and deterministic.
"""
from __future__ import annotations
import asyncio
from typing import Iterable
import pytest
from services.rate_limit import (
TokenRateLimiter,
WINDOW_SECONDS,
)
class FakeClock:
"""Deterministic monotonic clock."""
def __init__(self) -> None:
self.now = 1000.0
def __call__(self) -> float:
return self.now
def advance(self, seconds: float) -> None:
self.now += seconds
def _make_limiter(
*,
budgets: dict[str, int] | None = None,
clock: FakeClock | None = None,
sleep_calls: list[float] | None = None,
) -> tuple[TokenRateLimiter, FakeClock, list[float]]:
"""Build a limiter wired to a fake clock + sleep tracker."""
clock = clock or FakeClock()
sleeps = sleep_calls if sleep_calls is not None else []
async def fake_sleep(seconds: float) -> None:
sleeps.append(seconds)
clock.advance(seconds)
limiter = TokenRateLimiter(
budgets=budgets or {"gpt-4o": 10_000},
time_fn=clock,
sleep=fake_sleep,
)
return limiter, clock, sleeps
# ---------------------------------------------------------------------------
# Basic behaviour
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_acquire_within_budget_does_not_wait():
"""A single call below budget returns immediately with no sleep."""
limiter, _clock, sleeps = _make_limiter()
await limiter.acquire(model="gpt-4o", tokens=2_000)
assert sleeps == []
assert limiter.current_usage("gpt-4o") == 2_000
@pytest.mark.asyncio
async def test_zero_tokens_is_noop():
"""``tokens=0`` is a fast no-op."""
limiter, _, sleeps = _make_limiter()
await limiter.acquire(model="gpt-4o", tokens=0)
assert sleeps == []
assert limiter.current_usage("gpt-4o") == 0
# ---------------------------------------------------------------------------
# Sliding window blocks when budget is full
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_acquire_blocks_until_window_clears():
"""When the window is full, ``acquire`` must wait for the oldest entry."""
limiter, clock, sleeps = _make_limiter(budgets={"gpt-4o": 5_000})
# Fill the window: 5 calls Γ— 1k tokens = exactly at budget.
for _ in range(5):
await limiter.acquire(model="gpt-4o", tokens=1_000)
assert limiter.current_usage("gpt-4o") == 5_000
# Sixth call has no headroom β€” it must hit the sleep path. Our
# fake_sleep advances the clock so the next iteration sees the oldest
# entry has aged out and acquires the slot.
await limiter.acquire(model="gpt-4o", tokens=1_000)
# We must have slept at least once with a positive duration.
assert any(s > 0 for s in sleeps), f"expected to sleep, got {sleeps}"
# The last entry was admitted only after the clock advanced β€” verify
# by checking total advance is at least one window-eviction worth.
# The first slot was placed at t=1000; eviction happens at tβ‰ˆ1060.
assert clock.now >= 1059, f"clock should have advanced, got {clock.now}"
@pytest.mark.asyncio
async def test_window_evicts_old_entries():
"""Entries older than WINDOW_SECONDS must not count toward the budget."""
limiter, clock, sleeps = _make_limiter(budgets={"gpt-4o": 5_000})
await limiter.acquire(model="gpt-4o", tokens=4_000)
# Advance past the window. The next acquire should NOT have to wait.
clock.advance(WINDOW_SECONDS + 1)
await limiter.acquire(model="gpt-4o", tokens=4_000)
# No sleeps because the first entry has aged out.
assert sleeps == []
# current_usage drops the stale entry on read.
assert limiter.current_usage("gpt-4o") == 4_000
# ---------------------------------------------------------------------------
# Per-model isolation
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_per_model_buckets_are_independent():
"""gpt-4o and gpt-4o-mini have independent windows."""
limiter, _, sleeps = _make_limiter(
budgets={"gpt-4o": 5_000, "gpt-4o-mini": 100_000}
)
# Fill gpt-4o to budget.
await limiter.acquire(model="gpt-4o", tokens=5_000)
# gpt-4o-mini still has plenty of headroom β€” must not wait.
await limiter.acquire(model="gpt-4o-mini", tokens=80_000)
assert sleeps == []
assert limiter.current_usage("gpt-4o") == 5_000
assert limiter.current_usage("gpt-4o-mini") == 80_000
# ---------------------------------------------------------------------------
# Defensive: single-call > budget
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_single_call_larger_than_budget_raises():
"""A single call that exceeds the entire budget must fail loudly."""
limiter, _, _ = _make_limiter(budgets={"gpt-4o": 1_000})
with pytest.raises(ValueError, match="exceeds budget"):
await limiter.acquire(model="gpt-4o", tokens=2_000)
# ---------------------------------------------------------------------------
# record() backfill
# ---------------------------------------------------------------------------
def test_record_appends_actual_usage():
"""Callers can post actual usage on top of the estimate."""
limiter, _, _ = _make_limiter(budgets={"gpt-4o": 10_000})
limiter.record(model="gpt-4o", tokens=500)
assert limiter.current_usage("gpt-4o") == 500
def test_record_zero_is_noop():
limiter, _, _ = _make_limiter()
limiter.record(model="gpt-4o", tokens=0)
assert limiter.current_usage("gpt-4o") == 0
# ---------------------------------------------------------------------------
# Default budget resolution
# ---------------------------------------------------------------------------
def test_default_budget_distinguishes_mini_from_full():
"""Mini-family models get a much higher default budget."""
limiter = TokenRateLimiter()
full = limiter.budget_for("gpt-4o")
mini = limiter.budget_for("gpt-4o-mini")
assert mini > full, f"expected mini > full, got mini={mini} full={full}"
# Sanity: defaults align with documented OpenAI caps minus headroom.
assert 20_000 <= full <= 30_000
assert 100_000 <= mini <= 200_000
def test_explicit_budget_override_wins():
"""Per-instance overrides take precedence over defaults."""
limiter = TokenRateLimiter(budgets={"gpt-4o": 7_777})
assert limiter.budget_for("gpt-4o") == 7_777