Files
pipewright/tests/test_scheduler.py
T

113 lines
3.2 KiB
Python

import asyncio
import time
import pytest
from pipewright.errors import BudgetExceeded
from pipewright.scheduler import BudgetTracker, RateLimiter, SlotPool
def test_rate_limiter_paces_requests_per_window():
async def main():
lim = RateLimiter(requests_per_minute=3, window=0.4)
t0 = time.monotonic()
times = []
for _ in range(6):
await lim.acquire(10)
times.append(time.monotonic() - t0)
return times
times = asyncio.run(main())
assert max(times[:3]) < 0.1 # first window admits 3 immediately
assert times[3] >= 0.35 and times[5] >= 0.35 # the rest waits for the window to roll
def test_rejected_requests_count_and_close_gate():
async def main():
lim = RateLimiter(requests_per_minute=100, window=1.0)
await lim.acquire(1)
lim.reject(retry_after=0.3) # 429 with Retry-After
t0 = time.monotonic()
await lim.acquire(1)
return time.monotonic() - t0, lim.snapshot()
waited, snap = asyncio.run(main())
assert waited >= 0.3
assert snap["rejected"] == 1 and snap["in_window"] == 2 # the rejected request still counts
def test_output_token_budget_uses_estimate_and_settles():
async def main():
lim = RateLimiter(output_tokens_per_minute=1000, window=0.3, initial_output_estimate=400)
a = await lim.acquire(0)
b = await lim.acquire(0)
t0 = time.monotonic()
a.settle(10)
b.settle(10) # actual output much smaller than the estimate
await lim.acquire(0)
return time.monotonic() - t0
assert asyncio.run(main()) < 0.1
def test_priority_order():
async def main():
lim = RateLimiter(requests_per_minute=1, window=0.2)
await lim.acquire(0)
order = []
async def req(name, prio):
await lim.acquire(0, priority=prio)
order.append(name)
await asyncio.gather(req("shallow", 0), req("deep", -5), req("mid", -2))
return order
assert asyncio.run(main()) == ["deep", "mid", "shallow"]
def test_slot_pool_limits_concurrency():
async def main():
pool = SlotPool(2)
live, peak = 0, 0
async def work():
nonlocal live, peak
await pool.acquire()
live += 1
peak = max(peak, live)
await asyncio.sleep(0.02)
live -= 1
pool.release()
await asyncio.gather(*(work() for _ in range(7)))
return peak, pool.in_use
assert asyncio.run(main()) == (2, 0)
def test_budget():
b = BudgetTracker(usd=1.0)
b.add(usd=0.4)
b.check()
b.add(usd=0.7)
with pytest.raises(BudgetExceeded):
b.check()
assert "usd" in b.snapshot()["exceeded"]
def test_counter_budget_limits_only_that_counter():
import pytest
from pipewright.errors import BudgetExceeded
from pipewright.scheduler import BudgetTracker
b = BudgetTracker(counters={"rollouts.terra": 2})
b.count("rollouts.terra")
b.count("rollouts.terra")
with pytest.raises(BudgetExceeded):
b.count("rollouts.terra")
b.count("other", 5) # unlimited counters are tracked
b.check() # global budget not exceeded
assert b.snapshot()["counters"] == {"rollouts.terra": 2, "other": 5}