diff --git a/agents/llm_client.py b/agents/llm_client.py index 050cb6c..7b6873d 100644 --- a/agents/llm_client.py +++ b/agents/llm_client.py @@ -177,16 +177,17 @@ def __init__(self, rpm: int): self.rpm = rpm self.interval = 60.0 / rpm # min seconds between calls self._lock = threading.Lock() - self._last_call = 0.0 + self._last_call = None def wait(self): """Block until a call is allowed.""" with self._lock: - now = time.time() - earliest = self._last_call + self.interval - if now < earliest: - time.sleep(earliest - now) - self._last_call = time.time() + now = time.monotonic() + if self._last_call is not None: + earliest = self._last_call + self.interval + if now < earliest: + time.sleep(earliest - now) + self._last_call = time.monotonic() def _http_timeout() -> httpx.Timeout: diff --git a/tests/test_provider_rate_clock.py b/tests/test_provider_rate_clock.py new file mode 100644 index 0000000..4f7bad2 --- /dev/null +++ b/tests/test_provider_rate_clock.py @@ -0,0 +1,44 @@ +import pytest + +from agents import llm_client + + +class Clock: + def __init__(self, monotonic=100.0): + self.elapsed = monotonic + self.wall = 1000.0 + self.sleeps = [] + + def sleep(self, duration): + self.sleeps.append(duration) + self.elapsed += duration + self.wall += duration + + +def use_clock(monkeypatch, clock): + monkeypatch.setattr(llm_client.time, "time", lambda: clock.wall) + monkeypatch.setattr(llm_client.time, "monotonic", lambda: clock.elapsed) + monkeypatch.setattr(llm_client.time, "sleep", clock.sleep) + + +@pytest.mark.parametrize("wall_jump", [-3600.0, 3600.0]) +def test_wall_clock_adjustments_do_not_change_request_spacing(monkeypatch, wall_jump): + clock = Clock() + use_clock(monkeypatch, clock) + limiter = llm_client._RateLimiter(60) + limiter.wait() + clock.wall += wall_jump + limiter.wait() + assert clock.sleeps == [1.0] + + +def test_first_request_does_not_wait_at_monotonic_epoch(monkeypatch): + clock = Clock(monotonic=0.0) + use_clock(monkeypatch, clock) + limiter = llm_client._RateLimiter(60) + limiter.wait() + assert clock.sleeps == [] + clock.elapsed += 2.0 + clock.wall += 2.0 + limiter.wait() + assert clock.sleeps == []