AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
test(backend): pin the credits rate-limit test's clock so window boundaries can't flake it (#15452)
Nicholas Tindle63eb1ca0867c
diff --git a/autogpt_platform/backend/backend/api/features/billing/credits_rate_limit_test.py b/autogpt_platform/backend/backend/api/features/billing/credits_rate_limit_test.pyindex 227f4fadd1..2653f4cf73 100644--- a/autogpt_platform/backend/backend/api/features/billing/credits_rate_limit_test.py+++ b/autogpt_platform/backend/backend/api/features/billing/credits_rate_limit_test.py@@ -3,7 +3,7 @@from __future__ import annotationsimport asyncio-from datetime import UTC, datetime+from datetime import UTC, datetime, timedeltafrom unittest.mock import AsyncMock, MagicMockimport fastapi@@ -13,6 +13,29 @@ from redis.exceptions import RedisClusterException, ResponseErrorfrom backend.api.features.billing import credits_rate_limit as rate_limit+# Windows are aligned to the epoch, so every whole minute starts one.+WINDOW_START = datetime(2026, 1, 1, 12, 0, tzinfo=UTC)+++class Clock:+ """The limiter's clock: frozen, and moved only by the test."""++ def __init__(self, now: datetime) -> None:+ self.now = now++[email protected](autouse=True)+def clock(mocker) -> Clock:+ """Freeze the limiter's clock at the start of a window, for every test.++ On the real clock, a sequence that happens to cross hh:mm:00 splits its+ count across two window keys and the cap never trips. No test here may+ depend on when it runs; one that needs a boundary moves ``clock.now``.+ """+ clock = Clock(WINDOW_START)+ mocker.patch.object(rate_limit, "datetime", MagicMock(now=lambda tz: clock.now))+ return clock+class FakeRedis:"""Minimal Redis stand-in that actually interprets the limiter's Lua.@@ -89,14 +112,10 @@ async def test_ttl_not_refreshed_on_later_hits(fake_redis):@pytest.mark.asyncio-async def test_window_rolls_over(fake_redis, mocker):+async def test_window_rolls_over(fake_redis, clock):"""A later window uses a different key, so the count starts fresh."""- base = datetime(2026, 1, 1, 12, 0, 0, tzinfo=UTC)- mocker.patch.object(rate_limit, "datetime", MagicMock(now=lambda tz: base))await rate_limit.enforce_subscription_status_rate_limit("u1")-- later = datetime(2026, 1, 1, 12, 1, 30, tzinfo=UTC)- mocker.patch.object(rate_limit, "datetime", MagicMock(now=lambda tz: later))+ clock.now = WINDOW_START + timedelta(seconds=90)await rate_limit.enforce_subscription_status_rate_limit("u1")assert len(fake_redis.counters) == 2@@ -113,6 +132,35 @@ async def test_cap_is_enforced_over_a_real_sequence(fake_redis):assert exc_info.value.status_code == 429+async def test_window_boundary_resets_the_count(fake_redis, clock):+ """Windows are fixed and aligned to the minute, not sliding.++ The count resets at exactly hh:mm:00, so a burst that straddles it gets the+ full cap on each side (up to twice the cap in a moment, the accepted cost of+ a fixed window), and a 429 a moment before it says to retry in 1s.+ """+ cap = rate_limit.SUBSCRIPTION_STATUS_MAX_REQUESTS+ window = rate_limit.SUBSCRIPTION_STATUS_WINDOW_SECONDS++ async def burst() -> fastapi.HTTPException:+ for _ in range(cap):+ await rate_limit.enforce_subscription_status_rate_limit("u1")+ with pytest.raises(fastapi.HTTPException) as exc_info:+ await rate_limit.enforce_subscription_status_rate_limit("u1")+ assert exc_info.value.status_code == 429+ return exc_info.value++ clock.now = WINDOW_START + timedelta(seconds=window, milliseconds=-1)+ assert (await burst()).headers == {"Retry-After": "1"}+ clock.now = WINDOW_START + timedelta(seconds=window)+ assert (await burst()).headers == {"Retry-After": str(window)}++ # One counter per window, each given the window's TTL once, when it opened.+ assert list(fake_redis.counters.values()) == [cap + 1, cap + 1]+ assert list(fake_redis.ttls.values()) == [window, window]++@pytest.mark.asyncioasync def test_over_limit_sets_retry_after(mock_redis):"""429 must carry Retry-After: without it clients retry blind and a single