Spaces:
Sleeping
Sleeping
File size: 7,115 Bytes
fdfe81a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 | """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
|