diff --git a/.test_durations b/.test_durations index 1e43cca8a9..b41f1e9875 100644 --- a/.test_durations +++ b/.test_durations @@ -38359,16 +38359,6 @@ "autobot_shared/proxy_utils_17848_test.py::test_no_header_or_empty_chain_gives_the_peer": 0.0016280500001357723, "autobot_shared/proxy_utils_17848_test.py::test_the_divergent_readers_now_use_the_shared_rule": 0.0017159999999876163, "autobot_shared/proxy_utils_17848_test.py::test_the_real_nginx_case_gives_the_client": 0.0016589159999966796, - "autobot_shared/rate_limit_test.py::TestIPRateLimiterConfig::test_limit_falls_back_to_default_when_env_unparseable": 0.002625079999688751, - "autobot_shared/rate_limit_test.py::TestIPRateLimiterConfig::test_limit_property_reads_env": 0.002269221000460675, - "autobot_shared/rate_limit_test.py::TestIPRateLimiterConfig::test_limit_uses_default_when_env_unset": 0.002361587999985204, - "autobot_shared/rate_limit_test.py::TestIPRateLimiterFallback::test_inprocess_at_limit_raises_429": 0.0030478170001515537, - "autobot_shared/rate_limit_test.py::TestIPRateLimiterFallback::test_pipeline_error_falls_back_to_inprocess": 0.004790315999798622, - "autobot_shared/rate_limit_test.py::TestIPRateLimiterFallback::test_redis_unavailable_falls_back_to_inprocess": 0.00444963000018106, - "autobot_shared/rate_limit_test.py::TestIPRateLimiterRedisPath::test_at_limit_raises_429": 0.003107105999788473, - "autobot_shared/rate_limit_test.py::TestIPRateLimiterRedisPath::test_below_limit_does_not_raise": 0.003361652999956277, - "autobot_shared/rate_limit_test.py::TestIPRateLimiterRedisPath::test_per_instance_prefix_keeps_buckets_independent": 0.0038290769998639007, - "autobot_shared/rate_limit_test.py::TestIPRateLimiterRedisPath::test_pipeline_uses_correct_key_and_ops": 0.00354667800002062, "autobot_shared/rate_limiter_log_label_18087_test.py::test_label_allowed_request_is_silent": 0.0037102420001247083, "autobot_shared/rate_limiter_log_label_18087_test.py::test_label_means_one_warning_without_the_key[call]": 0.0037832180000805238, "autobot_shared/rate_limiter_log_label_18087_test.py::test_label_means_one_warning_without_the_key[constructor]": 0.004609547000200109, diff --git a/autobot-backend/a2a/a2a_security_test.py b/autobot-backend/a2a/a2a_security_test.py index 25e0e85fc9..ad35339c91 100644 --- a/autobot-backend/a2a/a2a_security_test.py +++ b/autobot-backend/a2a/a2a_security_test.py @@ -301,23 +301,19 @@ async def test_verify_remote_card_missing_metadata(self): class TestRateLimiting: - """Rate-limit tests — use the in-process fallback path of the shared - IPRateLimiter so tests don't require a live Redis. The limiter logic - itself is comprehensively tested in - ``autobot_shared/rate_limit_test.py`` (#7271). These tests only verify - a2a's wiring + that the shared limiter behaves correctly when stubbed - to use the fallback path. - - Pre-#7271 this file directly poked module-level globals - (``_rate_buckets``, ``_check_rate_limit``, ``_RATE_LIMIT``). Those - symbols were collapsed into ``_a2a_limiter`` (an IPRateLimiter - instance); tests now exercise the limiter's public API. + """Rate-limit tests -- use the LOCAL fallback of the canonical RateLimiter + (Redis stubbed to None) so tests don't require a live Redis. The limiter + logic itself is tested in ``autobot_shared/rate_limiter_test.py`` and + ``autobot_shared/rate_limiter_window_18087_test.py``; these only verify + a2a's wiring (#7271, #18087). """ + _REDIS = "autobot_shared.rate_limiter.get_async_redis_client" + def teardown_method(self): from api.a2a import _a2a_limiter - _a2a_limiter._reset_inprocess() + _a2a_limiter.reset_local() @pytest.mark.asyncio async def test_within_limit_passes(self): @@ -325,11 +321,7 @@ async def test_within_limit_passes(self): from api.a2a import _a2a_limiter - # Stub Redis to None → forces in-process fallback path. - with patch( - "autobot_shared.redis_client.get_async_redis_client", - new=AsyncMock(return_value=None), - ): + with patch(self._REDIS, new=AsyncMock(return_value=None)): for _ in range(5): await _a2a_limiter.check_or_429("1.2.3.4") # should not raise @@ -341,31 +333,26 @@ async def test_exceeds_limit_raises(self): from api.a2a import _a2a_limiter - # Pre-seed the in-process bucket at the limit. - now = time.time() - _a2a_limiter._inprocess_buckets["9.9.9.9"] = [now] * _a2a_limiter.limit - with patch( - "autobot_shared.redis_client.get_async_redis_client", - new=AsyncMock(return_value=None), - ): + with patch(self._REDIS, new=AsyncMock(return_value=None)): + for _ in range(_a2a_limiter.max_requests): + await _a2a_limiter.check_or_429("9.9.9.9") with pytest.raises(HTTPException) as exc_info: await _a2a_limiter.check_or_429("9.9.9.9") assert exc_info.value.status_code == 429 @pytest.mark.asyncio async def test_old_entries_expire(self): + from collections import deque from unittest.mock import AsyncMock, patch from api.a2a import _a2a_limiter - # Entries from 2 minutes ago — outside the 60s sliding window. + # Entries from 2 minutes ago -- outside the 60s sliding window. old_time = time.time() - 120 - _a2a_limiter._inprocess_buckets["5.5.5.5"] = [old_time] * _a2a_limiter.limit - with patch( - "autobot_shared.redis_client.get_async_redis_client", - new=AsyncMock(return_value=None), - ): - await _a2a_limiter.check_or_429("5.5.5.5") # should NOT raise — entries are stale + hits = _a2a_limiter.limiter._local_windows._hits + hits["a2a:5.5.5.5"] = deque([old_time] * _a2a_limiter.max_requests) + with patch(self._REDIS, new=AsyncMock(return_value=None)): + await _a2a_limiter.check_or_429("5.5.5.5") # should NOT raise -- entries are stale # --------------------------------------------------------------------------- diff --git a/autobot-backend/api/a2a.py b/autobot-backend/api/a2a.py index fe43ebfe3b..911d317d63 100644 --- a/autobot-backend/api/a2a.py +++ b/autobot-backend/api/a2a.py @@ -72,22 +72,23 @@ ) # --------------------------------------------------------------------------- -# Rate limiting — per-IP sliding window via shared IPRateLimiter (#7270/#7271) +# Rate limiting — per-IP sliding window via the canonical RateLimiter (#7270/#7271) # --------------------------------------------------------------------------- # # #7270: pre-fix, this was an in-process dict with the same multi-worker -# undercount that #6588 fixed for /v1/chat/completions. State is now shared -# across all uvicorn workers via Redis sorted-set; the in-process fallback -# is reserved for Redis outages only. +# undercount that #6588 fixed for /v1/chat/completions. State is shared across +# all uvicorn workers; LOCAL (per-worker enforcement) is reserved for Redis +# outages only, so the control never turns off (#18087). from autobot_shared.proxy_utils import get_client_ip -from autobot_shared.rate_limit import IPRateLimiter +from autobot_shared.rate_limiter_window import WindowFailurePolicy, WindowQuota -_a2a_limiter = IPRateLimiter( - key_prefix="ratelimit:a2a", - limit_env="AUTOBOT_A2A_RATE_LIMIT", - default_limit=30, +_a2a_limiter = WindowQuota.for_scope( + "a2a", + policy=WindowFailurePolicy.LOCAL, + max_requests=30, window_seconds=60, + limit_env="AUTOBOT_A2A_RATE_LIMIT", ) diff --git a/autobot-backend/api/openai_compat.py b/autobot-backend/api/openai_compat.py index 997c5be6f9..00824078b5 100644 --- a/autobot-backend/api/openai_compat.py +++ b/autobot-backend/api/openai_compat.py @@ -71,21 +71,23 @@ _AUTO_MODEL_NAMES = frozenset({"auto", "auto-fast", "auto-quality"}) # --------------------------------------------------------------------------- -# Rate limiting — per-IP sliding window via shared IPRateLimiter (#7271) +# Rate limiting — per-IP sliding window via the canonical RateLimiter (#7271) # --------------------------------------------------------------------------- # -# #6588 originally hand-rolled the Redis sorted-set + in-process fallback -# directly here. #7271 extracted that into autobot_shared/rate_limit.py so -# it can be reused by /a2a (#7270) and any future per-IP limiter. +# #6588 hand-rolled the Redis sorted-set + in-process fallback here; #7271 and +# #18087 folded it into autobot_shared.rate_limiter. LOCAL keeps enforcing per +# worker while Redis is down (this endpoint is public; fail-open would switch +# the control off), which is what the per-IP limiter did before. from autobot_shared.proxy_utils import get_client_ip -from autobot_shared.rate_limit import IPRateLimiter +from autobot_shared.rate_limiter_window import WindowFailurePolicy, WindowQuota -_oai_limiter = IPRateLimiter( - key_prefix="ratelimit:oai", - limit_env="AUTOBOT_OAI_RATE_LIMIT", - default_limit=60, +_oai_limiter = WindowQuota.for_scope( + "oai", + policy=WindowFailurePolicy.LOCAL, + max_requests=60, window_seconds=60, + limit_env="AUTOBOT_OAI_RATE_LIMIT", ) diff --git a/autobot-backend/api/openai_compat_test.py b/autobot-backend/api/openai_compat_test.py index 733da9e3ef..f8f46456e0 100644 --- a/autobot-backend/api/openai_compat_test.py +++ b/autobot-backend/api/openai_compat_test.py @@ -5,10 +5,9 @@ """ Integration tests for the openai_compat rate-limit wiring (#7271). -Per-IP rate-limit logic itself lives in -``autobot_shared.rate_limit.IPRateLimiter`` and is comprehensively tested -in ``autobot_shared/rate_limit_test.py`` (covers Redis path, in-process -fallback, env-driven limit, etc.). +Per-IP rate-limit logic itself lives in the canonical +``autobot_shared.rate_limiter.RateLimiter`` (single-window mode, #18087) and +is tested in ``autobot_shared/rate_limiter_window_18087_test.py``. This file pins the openai_compat-specific configuration of that helper: the right key prefix, the right env var, and that the helper is the same @@ -28,7 +27,7 @@ from fastapi import HTTPException from api import openai_compat -from autobot_shared.rate_limit import IPRateLimiter +from autobot_shared.rate_limiter_window import WindowFailurePolicy, WindowQuota # #13113: asyncio.run() — pytest-asyncio owns the loop lifecycle, so a sync test @@ -86,21 +85,25 @@ async def run(): class TestOAIRateLimitWiring: - """Issue #7271: openai_compat uses the shared IPRateLimiter.""" + """Issue #7271/#18087: openai_compat uses the canonical window limiter.""" def test_module_exposes_limiter_instance(self): - """``_oai_limiter`` must be an IPRateLimiter (not the legacy func).""" - assert isinstance(openai_compat._oai_limiter, IPRateLimiter) + """``_oai_limiter`` must be a WindowQuota (not the legacy func).""" + assert isinstance(openai_compat._oai_limiter, WindowQuota) def test_limiter_uses_oai_specific_config(self): """The instance is configured for the /v1/chat/completions endpoint.""" - limiter = openai_compat._oai_limiter - # #6588 / #7271: prefix shared across uvicorn workers via Redis key. - assert limiter._key_prefix == "ratelimit:oai" + quota = openai_compat._oai_limiter + # #6588 / #7271: scope shared across uvicorn workers via the Redis key. + assert quota.limiter._prefix == "oai" # AUTOBOT_OAI_RATE_LIMIT env var; default 60/min preserved. - assert limiter._limit_env == "AUTOBOT_OAI_RATE_LIMIT" - assert limiter._default_limit == 60 - assert limiter._window_seconds == 60 + assert quota._limit_env == "AUTOBOT_OAI_RATE_LIMIT" + assert quota._default_max == 60 + assert quota.window_seconds == 60 + + def test_public_endpoint_keeps_enforcing_when_redis_is_down(self): + """The old per-IP limiter fell back to a per-worker bucket, never open.""" + assert openai_compat._oai_limiter.limiter._window_policy is WindowFailurePolicy.LOCAL @pytest.fixture diff --git a/autobot-backend/api/rum_ingest_bounds.py b/autobot-backend/api/rum_ingest_bounds.py index f875e41a9f..da01f3ec14 100644 --- a/autobot-backend/api/rum_ingest_bounds.py +++ b/autobot-backend/api/rum_ingest_bounds.py @@ -9,8 +9,8 @@ including ``/login`` and ``/shared/:token``. An open write must not be a free amplifier, so each request is held to the #17007 treatment: -* **rate-limited** per client address with the shared ``IPRateLimiter`` - (``AUTOBOT_RUM_INGEST_RATE_LIMIT``); over it, 429 and nothing is written; +* **rate-limited** per client address with the canonical + ``RateLimiter`` window (``AUTOBOT_RUM_INGEST_RATE_LIMIT``); over it, 429 and nothing is written; * **size-capped** while the body streams, before any JSON is parsed (``AUTOBOT_RUM_*_MAX_BYTES``, ``api.rum_body_cap``), 413; * **field-capped**: each identifying event string has a maximum length, and a @@ -32,15 +32,19 @@ from autobot_shared.env_registry import REGISTRY, env from autobot_shared.proxy_utils import get_client_ip -from autobot_shared.rate_limit import IPRateLimiter +from autobot_shared.rate_limiter_window import WindowFailurePolicy, WindowQuota _RATE_ENV = "AUTOBOT_RUM_INGEST_RATE_LIMIT" -_ingest_limiter = IPRateLimiter( - key_prefix="ratelimit:rum_ingest", - limit_env=_RATE_ENV, - default_limit=REGISTRY[_RATE_ENV].default, +# LOCAL keeps enforcing per worker while Redis is down: these routes are anonymous, +# so failing open would switch the control off (what the per-IP limiter did, #18087). +_ingest_limiter = WindowQuota.for_scope( + "rum_ingest", + policy=WindowFailurePolicy.LOCAL, + log_rejections=False, # anonymous: a flood must not amplify into the log + max_requests=REGISTRY[_RATE_ENV].default, window_seconds=60, + limit_env=_RATE_ENV, ) #: Longest accepted value of each top-level ``RumEvent`` string. The body cap diff --git a/autobot-backend/integrations/rate_limiter.py b/autobot-backend/integrations/rate_limiter.py index 3c144c198d..d632a65d97 100644 --- a/autobot-backend/integrations/rate_limiter.py +++ b/autobot-backend/integrations/rate_limiter.py @@ -5,22 +5,35 @@ """ Integration Rate Limiter (Issue #4162) -Async-native sliding-window rate limiter for external API integrations. -Tracks rate limit state per service key and supports header-based quota -updates (X-RateLimit-*, Retry-After) from GitHub and Slack API responses. - -Delegates to the shared ``autobot_shared.rate_limiter.RateLimiter`` for the -core sliding-window logic (Issue #4460). +Async-native rate limiter for external API integrations. Tracks rate limit +state per service key and supports header-based quota updates +(X-RateLimit-*, Retry-After) from GitHub and Slack API responses. + +What is distinct, and what is not (#18087, #7271): + +* Distinct: the provider-header state (``RateLimitState``, ``apply_response_headers``). + The provider's own ``X-RateLimit-*`` / ``Retry-After`` response headers + correct the local view, a feedback loop the canonical limiter does not have. +* Not distinct: the request-count windows. The per-minute and per-hour windows + are NOT implemented here; they are two ``LocalWindowCounter`` windows from + ``autobot_shared.rate_limiter_window`` -- the per-process engine behind + ``WindowFailurePolicy.LOCAL`` of the canonical ``RateLimiter``. Redis is + never consulted because the keys are API tokens, which must not become Redis + key names. Only the module-level ``integration_rate_limiter`` below is a + Redis-backed canonical ``RateLimiter`` instance. + +See ``repo_tests/one_rate_limiter_18087_test.py``. """ import asyncio import time -from collections import deque -from dataclasses import dataclass, field +from dataclasses import dataclass +from email.utils import parsedate_to_datetime from typing import Dict from autobot_shared.logging_manager import get_logger from autobot_shared.rate_limiter import RateLimiter as _SharedRateLimiter +from autobot_shared.rate_limiter_window import LocalWindowCounter logger = get_logger(__name__) @@ -28,6 +41,9 @@ GITHUB_REQUESTS_PER_HOUR = 5000 GITHUB_REQUESTS_PER_MINUTE = 90 # conservative local window +_MINUTE = 60.0 +_HOUR = 3600.0 + # Slack: variable per method; ~1 req/s for most Tier 1 methods SLACK_REQUESTS_PER_MINUTE = 50 SLACK_REQUESTS_PER_HOUR = 2000 @@ -35,75 +51,61 @@ @dataclass class RateLimitState: - """Sliding-window request history for a single service/token pair.""" - - requests_per_minute: int - requests_per_hour: int - # Timestamps of recent requests (epoch seconds) - history: deque = field(default_factory=deque) - # Absolute epoch time before which no new requests should be sent - retry_after_until: float = 0.0 - - def _prune(self, now: float) -> None: - """Remove history entries older than one hour.""" - cutoff = now - 3600.0 - while self.history and self.history[0] < cutoff: - self.history.popleft() - - def is_ready(self, now: float) -> tuple[bool, float]: - """Return (can_proceed, seconds_to_wait). - - Returns False and the wait duration when the service enforced a - Retry-After header or when local sliding windows are exhausted. - """ - if now < self.retry_after_until: - return False, self.retry_after_until - now - - self._prune(now) - - minute_window = now - 60.0 - now - 3600.0 - minute_count = sum(1 for t in self.history if t > minute_window) - hour_count = len(self.history) + """Provider-enforced pause for a single service/token pair. - if minute_count >= self.requests_per_minute: - oldest_in_minute = next(t for t in self.history if t > minute_window) - wait = 60.0 - (now - oldest_in_minute) - return False, max(wait, 0.0) - - if hour_count >= self.requests_per_hour: - oldest_in_hour = self.history[0] - wait = 3600.0 - (now - oldest_in_hour) - return False, max(wait, 0.0) + Holds only what the provider told us (``Retry-After`` / ``X-RateLimit-*``). + Request-count windows live in ``IntegrationRateLimiter`` on the canonical + ``LocalWindowCounter``. + """ - return True, 0.0 + # Absolute monotonic time before which no new requests should be sent + retry_after_until: float = 0.0 - def record(self, now: float) -> None: - """Record that a request was dispatched at *now*.""" - self._prune(now) - self.history.append(now) + def pending_wait(self, now: float) -> float: + """Return the seconds left on a provider-enforced pause (0.0 when none).""" + return max(self.retry_after_until - now, 0.0) def apply_retry_after(self, retry_after_seconds: float, now: float) -> None: - """Set a hard pause based on a Retry-After response header.""" - self.retry_after_until = now + retry_after_seconds + """Set a hard pause based on a Retry-After response header (never shortens a longer one).""" + self.retry_after_until = max(self.retry_after_until, now + retry_after_seconds) logger.warning("Rate limit enforced: pausing requests for %.1fs", retry_after_seconds) - def apply_github_headers(self, headers: Dict[str, str], now: float) -> None: + def apply_github_headers(self, headers: Dict[str, str], now: float, wall_now: float) -> None: """Update quota state from GitHub X-RateLimit-* response headers. GitHub provides: X-RateLimit-Remaining, X-RateLimit-Reset (epoch), - X-RateLimit-Limit. + X-RateLimit-Limit. *now* is the monotonic clock the pause deadline is + stored on; *wall_now* is ``time.time()``, the clock ``X-RateLimit-Reset`` + is an epoch on. The wait is measured on the wall clock and only then + added to the monotonic *now*; never subtract one clock from the other. """ remaining = headers.get("X-RateLimit-Remaining") or headers.get("x-ratelimit-remaining") reset = headers.get("X-RateLimit-Reset") or headers.get("x-ratelimit-reset") - if remaining is not None and int(remaining) == 0 and reset is not None: - wait = max(float(reset) - now, 1.0) - self.apply_retry_after(wait, now) - elif remaining is not None and int(remaining) < 10: + try: + remaining_n = int(remaining) if remaining is not None else None + reset_epoch = float(reset) if reset is not None else None + except ValueError: + logger.warning("Ignoring malformed GitHub rate-limit headers") + return + if remaining_n == 0 and reset_epoch is not None: + self.apply_retry_after(max(reset_epoch - wall_now, 1.0), now) + elif remaining_n is not None and remaining_n < 10: logger.warning("GitHub rate limit quota nearly exhausted: %s remaining", remaining) +def _retry_after_seconds(value: str, wall_now: float) -> float | None: + """Parse a ``Retry-After`` value: delta-seconds, or an HTTP-date (wall clock).""" + try: + return max(float(value), 0.0) + except ValueError: + pass + try: + return max(parsedate_to_datetime(value).timestamp() - wall_now, 0.0) + except (TypeError, ValueError): + return None + + class IntegrationRateLimiter: """Per-key async rate limiter for external integrations. @@ -133,6 +135,9 @@ def __init__( self._rpm = requests_per_minute self._rph = requests_per_hour self._states: Dict[str, RateLimitState] = {} + # One counter per window: its stale-key eviction is keyed to a single window size. + self._minute = LocalWindowCounter() + self._hour = LocalWindowCounter() # Lock is created lazily in acquire() so it always belongs to the # running event loop (avoids "lock created in different loop" hangs # in tests that create a new loop per test). @@ -140,43 +145,51 @@ def __init__( def _get_state(self, key: str) -> RateLimitState: if key not in self._states: - self._states[key] = RateLimitState( - requests_per_minute=self._rpm, - requests_per_hour=self._rph, - ) + self._states[key] = RateLimitState() return self._states[key] + def _windows(self) -> tuple[tuple[LocalWindowCounter, int, float], ...]: + """(counter, limit, window seconds) for the minute then the hour window.""" + return ((self._minute, self._rpm, _MINUTE), (self._hour, self._rph, _HOUR)) + def check(self, key: str) -> tuple[bool, float]: """Check whether a request for *key* may proceed right now. - Returns (can_proceed, seconds_to_wait). Non-blocking. + Returns (can_proceed, seconds_to_wait). Non-blocking. Waits on a + provider pause first, then on the minute window, then on the hour window. """ - state = self._get_state(key) - return state.is_ready(time.monotonic()) + wait = self._get_state(key).pending_wait(time.monotonic()) + if wait > 0.0: + return False, wait + for counter, limit, seconds in self._windows(): + used, reset_in = counter.usage(key, seconds) + if used >= limit: + return False, reset_in + return True, 0.0 def record(self, key: str) -> None: """Record that a request for *key* was dispatched.""" - state = self._get_state(key) - state.record(time.monotonic()) + for counter, _limit, seconds in self._windows(): + counter.record(key, seconds) def apply_response_headers(self, key: str, headers: Dict[str, str], service: str = "generic") -> None: """Update rate limit state from HTTP response headers. Supports GitHub X-RateLimit-* headers and the standard Retry-After - header used by Slack (HTTP 429). + header used by Slack (HTTP 429), as delta-seconds or an HTTP-date. """ now = time.monotonic() + wall_now = time.time() state = self._get_state(key) retry_after = headers.get("Retry-After") or headers.get("retry-after") if retry_after is not None: - try: - state.apply_retry_after(float(retry_after), now) - except ValueError: - pass + seconds = _retry_after_seconds(retry_after, wall_now) + if seconds is not None: + state.apply_retry_after(seconds, now) if service == "github": - state.apply_github_headers(headers, now) + state.apply_github_headers(headers, now, wall_now) async def acquire(self, key: str, max_wait: float = 120.0) -> None: """Async acquire: waits until the rate limit allows a request. diff --git a/autobot-backend/integrations/rate_limiter_test.py b/autobot-backend/integrations/rate_limiter_test.py index 82577ea2be..4b7048f75a 100644 --- a/autobot-backend/integrations/rate_limiter_test.py +++ b/autobot-backend/integrations/rate_limiter_test.py @@ -11,72 +11,88 @@ import asyncio import time +from email.utils import formatdate import pytest from integrations.rate_limiter import IntegrationRateLimiter, RateLimitState # --------------------------------------------------------------------------- -# RateLimitState: basic window logic +# RateLimitState: provider pause # --------------------------------------------------------------------------- -def test_state_allows_first_request(): - state = RateLimitState(requests_per_minute=10, requests_per_hour=100) +def test_state_has_no_pause_by_default(): + assert RateLimitState().pending_wait(time.monotonic()) == 0.0 + + +def test_state_retry_after_blocks(): + state = RateLimitState() now = time.monotonic() - can, wait = state.is_ready(now) - assert can is True - assert wait == 0.0 + state.apply_retry_after(30.0, now) + assert 28.0 < state.pending_wait(now + 1.0) <= 30.0 + + +def test_state_keeps_the_longer_provider_pause(): + state = RateLimitState() + now = time.monotonic() + state.apply_retry_after(120.0, now) + state.apply_retry_after(60.0, now) + assert 118.0 < state.pending_wait(now + 1.0) <= 120.0 -def test_state_blocks_when_minute_window_full(): - state = RateLimitState(requests_per_minute=3, requests_per_hour=1000) +def test_state_retry_after_expires(): + state = RateLimitState() now = time.monotonic() + state.apply_retry_after(10.0, now) + assert state.pending_wait(now + 15.0) == 0.0 + + +# --------------------------------------------------------------------------- +# IntegrationRateLimiter: window logic (delegated to LocalWindowCounter, #18087) +# --------------------------------------------------------------------------- + + +def test_limiter_blocks_when_minute_window_full(): + limiter = IntegrationRateLimiter(requests_per_minute=3, requests_per_hour=1000) for _ in range(3): - state.record(now) - can, wait = state.is_ready(now) + limiter.record("tok") + can, wait = limiter.check("tok") assert can is False - assert wait > 0.0 + assert 0.0 < wait <= 60.0 -def test_state_blocks_when_hour_window_full(): - state = RateLimitState(requests_per_minute=1000, requests_per_hour=3) - now = time.monotonic() +def test_limiter_blocks_when_hour_window_full(): + limiter = IntegrationRateLimiter(requests_per_minute=1000, requests_per_hour=3) for _ in range(3): - state.record(now) - can, wait = state.is_ready(now) + limiter.record("tok") + can, wait = limiter.check("tok") assert can is False - assert wait > 0.0 + assert 60.0 < wait <= 3600.0 -def test_state_allows_after_minute_window_expires(): - state = RateLimitState(requests_per_minute=2, requests_per_hour=1000) - now = time.monotonic() - # Fill minute window with old timestamps (65 s ago) - old = now - 65.0 - state.record(old) - state.record(old) - # Both old entries should be pruned from minute window - can, wait = state.is_ready(now) - assert can is True +def test_limiter_allows_after_minute_window_expires(monkeypatch): + limiter = IntegrationRateLimiter(requests_per_minute=2, requests_per_hour=1000) + real = time.time() + monkeypatch.setattr("autobot_shared.rate_limiter_window.time.time", lambda: real - 65.0) + limiter.record("tok") + limiter.record("tok") + monkeypatch.setattr("autobot_shared.rate_limiter_window.time.time", lambda: real) + assert limiter.check("tok") == (True, 0.0) -def test_state_retry_after_blocks(): - state = RateLimitState(requests_per_minute=1000, requests_per_hour=1000) - now = time.monotonic() - state.apply_retry_after(30.0, now) - can, wait = state.is_ready(now + 1.0) - assert can is False - assert 28.0 < wait <= 30.0 +def test_limiter_check_does_not_consume_a_slot(): + limiter = IntegrationRateLimiter(requests_per_minute=1, requests_per_hour=1000) + assert limiter.check("tok")[0] is True + assert limiter.check("tok")[0] is True -def test_state_retry_after_expires(): - state = RateLimitState(requests_per_minute=1000, requests_per_hour=1000) - now = time.monotonic() - state.apply_retry_after(10.0, now) - can, wait = state.is_ready(now + 15.0) - assert can is True - assert wait == 0.0 +def test_limiter_provider_pause_wins_over_open_windows(): + limiter = IntegrationRateLimiter(requests_per_minute=1000, requests_per_hour=1000) + limiter._get_state("tok").apply_retry_after(30.0, time.monotonic()) + can, wait = limiter.check("tok") + assert can is False + assert 28.0 < wait <= 30.0 # --------------------------------------------------------------------------- @@ -85,33 +101,53 @@ def test_state_retry_after_expires(): def test_github_headers_zero_remaining_sets_retry_after(): - state = RateLimitState(requests_per_minute=1000, requests_per_hour=1000) - time.monotonic() - reset_epoch = time.time() + 60 # 60 s from now (wall clock) - # Map monotonic now to wall-clock: we pass reset as monotonic equivalent + state = RateLimitState() + mono, wall = time.monotonic(), time.time() state.apply_github_headers( - { - "X-RateLimit-Remaining": "0", - "X-RateLimit-Reset": str(int(time.time()) + 60), - }, - time.time(), # apply_github_headers uses the passed 'now' as wall time + {"X-RateLimit-Remaining": "0", "X-RateLimit-Reset": str(int(wall) + 60)}, + mono, + wall, ) - # retry_after_until should be set to a future monotonic value - # We can't compare monotonic directly; just verify state blocked - # by calling is_ready shortly after - # Since we pass wall-clock 'now' but state stores monotonic, we test indirectly - assert state.retry_after_until > 0.0 + assert 58.0 < state.pending_wait(mono) <= 61.0 + + +def test_github_reset_epoch_through_the_entry_point_pauses_about_the_reset_delta(): + """#18087: the epoch is a wall-clock value; measured on the monotonic clock it paused ~1.7e9 s.""" + limiter = IntegrationRateLimiter(requests_per_minute=1000, requests_per_hour=5000) + limiter.apply_response_headers( + "tok", + {"X-RateLimit-Remaining": "0", "X-RateLimit-Reset": str(int(time.time()) + 60)}, + service="github", + ) + can, wait = limiter.check("tok") + assert can is False + assert 58.0 < wait <= 61.0 + + +def test_retry_after_http_date_is_a_wall_clock_delta(): + limiter = IntegrationRateLimiter(requests_per_minute=1000, requests_per_hour=5000) + date = formatdate(time.time() + 45, usegmt=True) + limiter.apply_response_headers("tok", {"Retry-After": date}) + can, wait = limiter.check("tok") + assert can is False + assert 43.0 < wait <= 46.0 + + +def test_unparseable_retry_after_is_ignored(): + limiter = IntegrationRateLimiter(requests_per_minute=1000, requests_per_hour=5000) + limiter.apply_response_headers("tok", {"Retry-After": "soon"}) + assert limiter.check("tok") == (True, 0.0) def test_github_headers_nonzero_remaining_no_block(): - state = RateLimitState(requests_per_minute=1000, requests_per_hour=1000) + state = RateLimitState() now = time.monotonic() state.apply_github_headers( {"X-RateLimit-Remaining": "100", "X-RateLimit-Reset": str(int(time.time()) + 3600)}, now, + time.time(), ) - can, _ = state.is_ready(now) - assert can is True + assert state.pending_wait(now) == 0.0 # --------------------------------------------------------------------------- diff --git a/autobot-backend/llm_shared/cross_worker_rate_limiter.py b/autobot-backend/llm_shared/cross_worker_rate_limiter.py index e142dffcf3..fd14dfb3b3 100644 --- a/autobot-backend/llm_shared/cross_worker_rate_limiter.py +++ b/autobot-backend/llm_shared/cross_worker_rate_limiter.py @@ -16,6 +16,17 @@ depending on the ``blocking`` flag). All workers share the same Redis keys, so the aggregate rate is correctly bounded regardless of worker count. +Why this is not ``autobot_shared.rate_limiter.RateLimiter`` (#18087) +-------------------------------------------------------------------- +A different algorithm, not a second copy of the same one. A sliding window +admits ``max`` requests at once and then nothing until the oldest hit ages out; +this bucket holds ``(tokens, ts)``, refills continuously and fractionally, and +separates burst capacity from the sustained rate, so a drained bucket admits one +request per ``1/rate`` seconds. The canonical limiter's only token bucket +(``acquire_token``) is in-process, so it cannot bound the aggregate across +workers, which is this module's whole purpose. Kept deliberately, with its +reason recorded in ``repo_tests/one_rate_limiter_18087_test.py``. + Token bucket algorithm ---------------------- Each provider bucket has two parameters: diff --git a/autobot-backend/tests/api/test_rum_access_16375.py b/autobot-backend/tests/api/test_rum_access_16375.py index 9bfc600ae4..258cf04891 100644 --- a/autobot-backend/tests/api/test_rum_access_16375.py +++ b/autobot-backend/tests/api/test_rum_access_16375.py @@ -25,7 +25,8 @@ import api.rum as rum_api import api.rum_ingest_bounds as bounds -from autobot_shared.rate_limit import IPRateLimiter +from autobot_shared import rate_limiter as rl_mod +from autobot_shared.rate_limiter_window import WindowFailurePolicy, WindowQuota _PREFIX = "/api/rum" _ADMIN, _USER, _OPEN = "admin", "user", "open" @@ -64,9 +65,16 @@ def rum_state(monkeypatch): monkeypatch.setattr(rum_api, "rum_sessions", {}) monkeypatch.setitem(rum_api.rum_config, "enabled", True) monkeypatch.setattr(rum_api, "rum_logger", MagicMock()) - limiter = IPRateLimiter(key_prefix="ratelimit:rum_test", limit_env=bounds._RATE_ENV, default_limit=120) + limiter = WindowQuota.for_scope( + "rum_test", + policy=WindowFailurePolicy.LOCAL, + log_rejections=False, + max_requests=120, + window_seconds=60, + limit_env=bounds._RATE_ENV, + ) monkeypatch.setattr(bounds, "_ingest_limiter", limiter) - monkeypatch.setattr("autobot_shared.redis_client.get_async_redis_client", AsyncMock(return_value=None)) + monkeypatch.setattr(rl_mod, "get_async_redis_client", AsyncMock(return_value=None)) return rum_api @@ -171,6 +179,19 @@ def test_a_flood_is_refused_after_the_limit(client, rum_state, monkeypatch) -> N assert len(rum_state.rum_events) == 3 +def test_a_refused_flood_request_logs_no_warning(client, monkeypatch, caplog) -> None: + monkeypatch.setenv("AUTOBOT_RUM_INGEST_RATE_LIMIT", "1") + test_client, _ = client + with caplog.at_level("WARNING"): + codes = [test_client.post("/api/rum/event", json=_event()).status_code for _ in range(3)] + assert codes == [200, 429, 429] + assert [r for r in caplog.records if "Rate limit exceeded" in r.getMessage()] == [] + + +def test_the_production_rum_limiter_is_silent_on_refusal() -> None: + assert bounds._ingest_limiter.limiter._log_label is None + + def test_the_event_buffer_and_session_table_are_capped(client, rum_state, monkeypatch) -> None: monkeypatch.setenv("AUTOBOT_RUM_MAX_EVENTS", "2") monkeypatch.setenv("AUTOBOT_RUM_MAX_SESSIONS", "2") diff --git a/autobot-backend/tests/test_concurrency_global_locks.py b/autobot-backend/tests/test_concurrency_global_locks.py index f04b3e8d26..beb3dd8f4c 100644 --- a/autobot-backend/tests/test_concurrency_global_locks.py +++ b/autobot-backend/tests/test_concurrency_global_locks.py @@ -5,21 +5,21 @@ """ Concurrency guard tests for async global mutations (Issue #10786). -These tests validate that the asyncio.Lock patterns used in: - - api/database_mcp.py (query_counter under _rate_limit_lock) - - api/http_client_mcp.py (request_counter under _rate_limit_lock) +These tests validate that the asyncio.Lock pattern used in: - api/monitoring.py (_alertmanager_cache under _alertmanager_cache_lock) -…actually prevent lost updates under concurrent asyncio coroutines. +actually prevents lost updates under concurrent asyncio coroutines. -The modules themselves cannot be imported in the CI test environment +The module itself cannot be imported in the CI test environment (transitive deps require a running Redis / compiled C extensions). -Instead each test replicates the exact lock + counter / cache pattern -verbatim, which is sufficient to prove the pattern is race-free. +Instead the test replicates the exact lock + cache pattern verbatim, which is +sufficient to prove the pattern is race-free. -Pattern used in database_mcp.py / http_client_mcp.py: - async with _rate_limit_lock: - counter["count"] += 1 +The ``database_mcp`` / ``http_client_mcp`` rate-limit counters this file used +to replicate no longer exist: they were folded into the canonical +``autobot_shared.rate_limiter.RateLimiter`` (#18087), and their concurrency +behaviour is pinned against the real implementation in +``autobot_shared/rate_limiter_window_18087_test.py``. Pattern added to monitoring.py (Issue #10786): async with _alertmanager_cache_lock: @@ -30,117 +30,6 @@ import time from typing import Any, Dict -# --------------------------------------------------------------------------- -# Helpers: replicate the exact module-level patterns -# --------------------------------------------------------------------------- - - -def _make_counter(limit: int) -> tuple[dict, asyncio.Lock]: - """Return (counter_dict, lock) as used in database_mcp / http_client_mcp.""" - counter: Dict[str, Any] = {"count": 0, "reset_time": time.monotonic()} - lock = asyncio.Lock() - return counter, lock - - -async def _check_rate_limit(counter: dict, lock: asyncio.Lock, limit: int) -> bool: - """Exact replica of check_rate_limit() from database_mcp / http_client_mcp.""" - async with lock: - now = time.monotonic() - elapsed = now - counter["reset_time"] - if elapsed >= 60: - counter["count"] = 0 - counter["reset_time"] = now - if counter["count"] >= limit: - return False - counter["count"] += 1 - return True - - -# --------------------------------------------------------------------------- -# database_mcp: query_counter concurrency test -# --------------------------------------------------------------------------- - - -async def test_database_mcp_counter_no_lost_updates() -> None: - """ - Concurrent calls to check_rate_limit (database_mcp pattern) must produce - an exact count — no lost updates, no double-increments. - - We call N times concurrently (N < MAX_QUERIES_PER_MINUTE=60) and assert - counter["count"] == N afterwards. - """ - N = 40 # well below MAX_QUERIES_PER_MINUTE=60 - limit = 60 - counter, lock = _make_counter(limit) - - results = await asyncio.gather(*[_check_rate_limit(counter, lock, limit) for _ in range(N)]) - - assert all(results), "All calls should be allowed (N < limit)" - assert counter["count"] == N, ( - f"Expected counter['count'] == {N}, got {counter['count']}. " - "Lost updates indicate the lock is not guarding the RMW correctly." - ) - - -async def test_database_mcp_counter_enforces_limit() -> None: - """ - After MAX_QUERIES_PER_MINUTE concurrent calls, further calls must be rejected. - """ - limit = 60 - counter, lock = _make_counter(limit) - - # Fill up to the limit exactly - first_batch = await asyncio.gather(*[_check_rate_limit(counter, lock, limit) for _ in range(limit)]) - assert all(first_batch), "First batch (==limit) should all be allowed" - assert counter["count"] == limit - - # One more should be rejected - over = await _check_rate_limit(counter, lock, limit) - assert not over, "Call beyond limit should be rejected" - assert counter["count"] == limit, "Rejected call must not increment the counter" - - -# --------------------------------------------------------------------------- -# http_client_mcp: request_counter concurrency test -# --------------------------------------------------------------------------- - - -async def test_http_client_mcp_counter_no_lost_updates() -> None: - """ - Concurrent calls to check_rate_limit (http_client_mcp pattern) must - produce an exact count — no lost updates. - - N < MAX_REQUESTS_PER_MINUTE=120. - """ - N = 80 # well below MAX_REQUESTS_PER_MINUTE=120 - limit = 120 - counter, lock = _make_counter(limit) - - results = await asyncio.gather(*[_check_rate_limit(counter, lock, limit) for _ in range(N)]) - - assert all(results), "All calls should be allowed (N < limit)" - assert counter["count"] == N, ( - f"Expected counter['count'] == {N}, got {counter['count']}. " - "Lost updates indicate the lock is not guarding the RMW correctly." - ) - - -async def test_http_client_mcp_counter_enforces_limit() -> None: - """ - After MAX_REQUESTS_PER_MINUTE concurrent calls, further calls must be rejected. - """ - limit = 120 - counter, lock = _make_counter(limit) - - first_batch = await asyncio.gather(*[_check_rate_limit(counter, lock, limit) for _ in range(limit)]) - assert all(first_batch), "First batch (==limit) should all be allowed" - assert counter["count"] == limit - - over = await _check_rate_limit(counter, lock, limit) - assert not over, "Call beyond limit should be rejected" - assert counter["count"] == limit, "Rejected call must not increment the counter" - - # --------------------------------------------------------------------------- # monitoring.py: _alertmanager_cache concurrency test (Issue #10786 fix) # --------------------------------------------------------------------------- diff --git a/autobot_shared/env_registry.py b/autobot_shared/env_registry.py index 06932e5e93..5e2fe07950 100644 --- a/autobot_shared/env_registry.py +++ b/autobot_shared/env_registry.py @@ -61,7 +61,6 @@ def env(name: str, default: Any = None) -> Any: from autobot_shared import env_registry_knowledge # noqa: E402,F401 from autobot_shared import env_registry_llc # noqa: E402,F401 from autobot_shared import env_registry_logging # noqa: E402,F401 -from autobot_shared import env_registry_memory # noqa: E402,F401 from autobot_shared import ( # noqa: E402,F401 env_registry_admin_files, env_registry_agent_tools, @@ -75,10 +74,12 @@ def env(name: str, default: Any = None) -> Any: env_registry_gateway, env_registry_kb_graph, env_registry_ledger, + env_registry_memory, env_registry_mesh_reembed, env_registry_npu, env_registry_postgres, env_registry_rag, + env_registry_rate_limit, env_registry_security, env_registry_slm, env_registry_slm_health, @@ -91,7 +92,6 @@ def env(name: str, default: Any = None) -> Any: ) # --- events (#14817, #14818) ------------------------------------------------- - register_env_var( EnvVarSpec( name="AUTOBOT_CHANNEL_SEQ_KEY_PREFIX", diff --git a/autobot_shared/env_registry_backend_services.py b/autobot_shared/env_registry_backend_services.py index 69a3447a6f..82f81e8fb6 100644 --- a/autobot_shared/env_registry_backend_services.py +++ b/autobot_shared/env_registry_backend_services.py @@ -595,3 +595,4 @@ ) from autobot_shared import env_registry_chat_attachments # noqa: E402,F401 -- registers #20195 vars; see its docstring +from autobot_shared import env_registry_rate_limit # noqa: E402,F401 -- registers #18087 vars; see its docstring diff --git a/autobot_shared/env_registry_rate_limit.py b/autobot_shared/env_registry_rate_limit.py new file mode 100644 index 0000000000..2bd2c31cf1 --- /dev/null +++ b/autobot_shared/env_registry_rate_limit.py @@ -0,0 +1,28 @@ +# Copyright 2025-2026 mrveiss +# SPDX-License-Identifier: Apache-2.0 +"""Rate-limit AUTOBOT_* environment variable registrations (#18087). + +Sibling module imported by ``env_registry`` and also chained from +``env_registry_backend_services``, because ``env_registry.py`` is closed to new +entries. Registration contract (import side effect, ordering): see +``env_registry`` (#16415). +""" + +from __future__ import annotations + +from autobot_shared.env_registry import EnvVarSpec, register_env_var + +register_env_var( + EnvVarSpec( + name="AUTOBOT_RATE_LIMIT_LOCAL_MAX_KEYS", + type=int, + default=10_000, + description=( + "Cap on distinct keys the per-process rate-limit fallback tracks before it evicts keys " + "whose every hit has aged out of the window (#18087). Only used while Redis is " + "unavailable and a limiter's window_failure_policy is LOCAL; bounds memory when an " + "outage outlasts the window." + ), + component="rate_limit", + ) +) diff --git a/autobot_shared/rate_limit.py b/autobot_shared/rate_limit.py deleted file mode 100644 index 90e39ceda3..0000000000 --- a/autobot_shared/rate_limit.py +++ /dev/null @@ -1,183 +0,0 @@ -# Copyright 2025-2026 mrveiss -# SPDX-License-Identifier: Apache-2.0 -# AutoBot - AI-Powered Automation Platform -# Author: mrveiss -""" -Shared per-key sliding-window rate limiter (#7271). - -Consolidates the duplicated implementation that previously lived (with -subtle differences and at least one P1 bug) in: - - * autobot-backend/api/openai_compat.py:_check_oai_rate_limit (#6588) - * autobot-backend/api/a2a.py:_check_rate_limit (#7270) - -State is shared across all uvicorn workers via a Redis sorted-set keyed -by ``f"{key_prefix}:{key}"``. Pipeline of: - - ZREMRANGEBYSCORE 0 (now - window_seconds) # drop expired - ZADD now uuid # record this request - ZCARD # count after add - EXPIRE 2 * window_seconds # auto-evict idle keys - -If Redis is unavailable (or the pipeline raises), the limiter falls back -to a per-process in-memory bucket so the endpoint stays responsive. -Degraded mode logs a warning and accepts the per-worker undercount — -strictly better than fail-closed for /v1/chat/completions. - -Usage:: - - from autobot_shared.rate_limit import IPRateLimiter - - _oai_limiter = IPRateLimiter( - key_prefix="ratelimit:oai", - limit_env="AUTOBOT_OAI_RATE_LIMIT", - default_limit=60, - window_seconds=60, - ) - - @router.post("/v1/chat/completions") - async def chat_completions(...) -> None: - await _oai_limiter.check_or_429(remote_addr) - ... -""" - -from __future__ import annotations - -import logging -import os -import time -from typing import Dict, List -from uuid import uuid4 - -from fastapi import HTTPException - -logger = logging.getLogger(__name__) - -# Default cap on the in-process fallback bucket — prevents unbounded memory -# growth when Redis has been unavailable for an extended window. -_DEFAULT_BUCKET_MAX_KEYS = 10_000 - - -class IPRateLimiter: - """Per-key sliding-window rate limiter, Redis-backed with in-process fallback. - - Args: - key_prefix: Stable prefix for Redis keys (e.g. ``"ratelimit:oai"``). - The full key is ``f"{key_prefix}:{key}"`` where *key* is whatever - is passed to :meth:`check_or_429` (typically a remote IP). - limit_env: Environment variable name to read the limit from. If unset - or unparseable, *default_limit* is used. - default_limit: Fallback limit when *limit_env* is unset or invalid. - window_seconds: Sliding window size (default 60). - bucket_max_keys: Cap on the in-process fallback bucket size before - stale-key eviction kicks in. Only applies to the fallback path. - - The Redis path is the production-correct enforcement; the in-process - path exists only so the endpoint stays responsive during Redis outages. - """ - - def __init__( - self, - *, - key_prefix: str, - limit_env: str, - default_limit: int, - window_seconds: int = 60, - bucket_max_keys: int = _DEFAULT_BUCKET_MAX_KEYS, - ) -> None: - self._key_prefix = key_prefix - self._limit_env = limit_env - self._default_limit = default_limit - self._window_seconds = window_seconds - self._bucket_max_keys = bucket_max_keys - # Per-process fallback only — production uses Redis sorted-set. - self._inprocess_buckets: Dict[str, List[float]] = {} - - @property - def limit(self) -> int: - """Read the limit from env each call so dynamic config is respected.""" - try: - return int(os.environ.get(self._limit_env, self._default_limit)) # ssot-config-exempt: dynamic env var name - except (TypeError, ValueError): - return self._default_limit - - def _redis_key(self, key: str) -> str: - return f"{self._key_prefix}:{key}" - - async def check_or_429(self, key: str) -> None: - """Enforce the limit; raise ``HTTPException(429)`` if exceeded. - - Tries Redis first. On Redis unavailability or pipeline error, falls - back to the in-process bucket and logs a warning. - - Args: - key: Stable per-caller identifier — typically remote IP. Combined - with *key_prefix* to form the Redis key. - """ - from autobot_shared.redis_client import get_async_redis_client - - redis = await get_async_redis_client() - if redis is None: - logger.warning( - "Redis unavailable for %s rate-limit; falling back to in-process bucket " - "(per-worker, undercounts under multi-worker)", - self._key_prefix, - ) - self._check_inprocess_or_429(key) - return - - full_key = self._redis_key(key) - now = time.time() - window_start = now - self._window_seconds - try: - async with redis.pipeline(transaction=False) as pipe: - pipe.zremrangebyscore(full_key, 0, window_start) - pipe.zadd(full_key, {f"{now}:{uuid4()}": now}) - pipe.zcard(full_key) - pipe.expire(full_key, 2 * self._window_seconds) - results = await pipe.execute() - count = int(results[2]) - except Exception as exc: - logger.warning( - "Redis %s rate-limit pipeline failed (%s) — falling back to in-process", - self._key_prefix, - exc, - ) - self._check_inprocess_or_429(key) - return - - if count > self.limit: - raise HTTPException( - status_code=429, - detail=f"Rate limit exceeded ({self.limit} requests/{self._window_seconds}s). Try again later.", - ) - - def _check_inprocess_or_429(self, key: str) -> None: - """Per-process fallback (#6588 pattern, retained for outage handling). - - State is per-worker — does NOT enforce the documented limit across - uvicorn workers. Only used when Redis is unreachable. - """ - now = time.time() - window_start = now - self._window_seconds - bucket = [t for t in self._inprocess_buckets.get(key, []) if t > window_start] - limit = self.limit - if len(bucket) >= limit: - raise HTTPException( - status_code=429, - detail=f"Rate limit exceeded ({limit} requests/{self._window_seconds}s). Try again later.", - ) - bucket.append(now) - self._inprocess_buckets[key] = bucket - if len(self._inprocess_buckets) > self._bucket_max_keys: - cutoff = now - self._window_seconds - stale = [k for k, ts in self._inprocess_buckets.items() if not any(t > cutoff for t in ts)] - for k in stale: - del self._inprocess_buckets[k] - - # Test/debug helper — production code should not depend on this. - def _reset_inprocess(self) -> None: # pragma: no cover - self._inprocess_buckets.clear() - - -__all__ = ["IPRateLimiter"] diff --git a/autobot_shared/rate_limit_test.py b/autobot_shared/rate_limit_test.py deleted file mode 100644 index 131c196d23..0000000000 --- a/autobot_shared/rate_limit_test.py +++ /dev/null @@ -1,233 +0,0 @@ -# Copyright 2025-2026 mrveiss -# SPDX-License-Identifier: Apache-2.0 -# AutoBot - AI-Powered Automation Platform -# Author: mrveiss -""" -Unit tests for autobot_shared.rate_limit.IPRateLimiter (#7271). - -This module replaces the per-file rate-limit tests that used to live in -``autobot-backend/api/openai_compat_test.py`` (#6588). The shared helper -is exercised here once; both consumers (``openai_compat._oai_limiter`` and -``a2a._a2a_limiter``) get their behavior covered by these tests through -the helper. - -Tests cover: - * Below-limit: no raise - * At-limit: HTTPException 429 - * Pipeline: ZREMRANGEBYSCORE + ZADD + ZCARD + EXPIRE in correct order - * Pipeline: per-instance key prefix is honored - * Redis unavailable: in-process fallback (degraded mode) - * Pipeline error: in-process fallback (degraded mode) - * Limit re-read from env each call (dynamic config) -""" - -from unittest.mock import AsyncMock, MagicMock, patch - -import pytest -from fastapi import HTTPException - -from autobot_shared.rate_limit import IPRateLimiter - - -class _FakePipeline: - """Minimal async-context-manager pipeline mock for redis.pipeline().""" - - def __init__(self, zcard_result: int) -> None: - self._zcard_result = zcard_result - self.commands: list = [] - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc, tb): - return False - - def zremrangebyscore(self, *args, **kwargs): - self.commands.append(("zremrangebyscore", args, kwargs)) - return self - - def zadd(self, *args, **kwargs): - self.commands.append(("zadd", args, kwargs)) - return self - - def zcard(self, *args, **kwargs): - self.commands.append(("zcard", args, kwargs)) - return self - - def expire(self, *args, **kwargs): - self.commands.append(("expire", args, kwargs)) - return self - - async def execute(self): - # ZREMRANGEBYSCORE → int dropped, ZADD → int added, - # ZCARD → int count, EXPIRE → bool. Index 2 is the count. - return [0, 1, self._zcard_result, True] - - -def _fake_redis(zcard_result: int) -> MagicMock: - fake = MagicMock() - fake.pipeline = MagicMock(return_value=_FakePipeline(zcard_result)) - return fake - - -def _make_limiter(prefix: str = "ratelimit:test", default_limit: int = 60) -> IPRateLimiter: - return IPRateLimiter( - key_prefix=prefix, - limit_env="UNIT_TEST_RATE_LIMIT", - default_limit=default_limit, - window_seconds=60, - ) - - -class TestIPRateLimiterRedisPath: - """Issue #7271: shared limiter — Redis pipeline + 429 enforcement.""" - - @pytest.mark.asyncio - async def test_below_limit_does_not_raise(self) -> None: - limiter = _make_limiter(default_limit=60) - with patch( - "autobot_shared.redis_client.get_async_redis_client", - new=AsyncMock(return_value=_fake_redis(zcard_result=10)), - ): - await limiter.check_or_429("1.2.3.4") # no exception - - @pytest.mark.asyncio - async def test_at_limit_raises_429(self) -> None: - limiter = _make_limiter(default_limit=5) - with patch( - "autobot_shared.redis_client.get_async_redis_client", - new=AsyncMock(return_value=_fake_redis(zcard_result=6)), - ): - with pytest.raises(HTTPException) as exc_info: - await limiter.check_or_429("9.9.9.9") - assert exc_info.value.status_code == 429 - assert "Rate limit exceeded" in exc_info.value.detail - - @pytest.mark.asyncio - async def test_pipeline_uses_correct_key_and_ops(self) -> None: - """Pipeline must build (key, 4 ops) in the documented order.""" - fake_pipe = _FakePipeline(zcard_result=1) - fake_redis = MagicMock() - fake_redis.pipeline = MagicMock(return_value=fake_pipe) - - limiter = _make_limiter(prefix="ratelimit:oai") - with patch( - "autobot_shared.redis_client.get_async_redis_client", - new=AsyncMock(return_value=fake_redis), - ): - await limiter.check_or_429("203.0.113.1") - - op_names = [c[0] for c in fake_pipe.commands] - assert op_names == ["zremrangebyscore", "zadd", "zcard", "expire"] - - # Each op uses the per-instance key prefix. - for _, args, _ in fake_pipe.commands: - assert args[0] == "ratelimit:oai:203.0.113.1" - - @pytest.mark.asyncio - async def test_per_instance_prefix_keeps_buckets_independent(self) -> None: - """Two limiters with different prefixes must keep keys separate.""" - oai_pipe = _FakePipeline(zcard_result=1) - a2a_pipe = _FakePipeline(zcard_result=1) - oai_redis = MagicMock(pipeline=MagicMock(return_value=oai_pipe)) - a2a_redis = MagicMock(pipeline=MagicMock(return_value=a2a_pipe)) - - oai = _make_limiter(prefix="ratelimit:oai") - a2a = _make_limiter(prefix="ratelimit:a2a") - - with patch( - "autobot_shared.redis_client.get_async_redis_client", - new=AsyncMock(return_value=oai_redis), - ): - await oai.check_or_429("8.8.8.8") - with patch( - "autobot_shared.redis_client.get_async_redis_client", - new=AsyncMock(return_value=a2a_redis), - ): - await a2a.check_or_429("8.8.8.8") - - assert oai_pipe.commands[0][1][0] == "ratelimit:oai:8.8.8.8" - assert a2a_pipe.commands[0][1][0] == "ratelimit:a2a:8.8.8.8" - - -class TestIPRateLimiterFallback: - """Issue #7271: shared limiter — in-process fallback paths.""" - - @pytest.mark.asyncio - async def test_redis_unavailable_falls_back_to_inprocess(self, caplog) -> None: - """Redis None → fallback to per-process bucket (degraded mode).""" - import logging - - limiter = _make_limiter(prefix="ratelimit:fb1", default_limit=60) - with patch( - "autobot_shared.redis_client.get_async_redis_client", - new=AsyncMock(return_value=None), - ): - with caplog.at_level(logging.WARNING, logger="autobot_shared.rate_limit"): - await limiter.check_or_429("8.8.8.8") - assert "8.8.8.8" in limiter._inprocess_buckets - assert any("Redis unavailable" in r.getMessage() for r in caplog.records) - - @pytest.mark.asyncio - async def test_pipeline_error_falls_back_to_inprocess(self, caplog): - """Redis pipeline raises → fallback to per-process bucket.""" - import logging - - class _BrokenPipeline: - async def __aenter__(self) -> None: - raise RuntimeError("redis down mid-pipeline") - - async def __aexit__(self, *a): - return False - - broken = MagicMock() - broken.pipeline = MagicMock(return_value=_BrokenPipeline()) - - limiter = _make_limiter(prefix="ratelimit:fb2", default_limit=60) - with patch( - "autobot_shared.redis_client.get_async_redis_client", - new=AsyncMock(return_value=broken), - ): - with caplog.at_level(logging.WARNING, logger="autobot_shared.rate_limit"): - await limiter.check_or_429("4.4.4.4") - assert "4.4.4.4" in limiter._inprocess_buckets - assert any("pipeline failed" in r.getMessage() for r in caplog.records) - - @pytest.mark.asyncio - async def test_inprocess_at_limit_raises_429(self) -> None: - """In-process fallback respects the limit too.""" - limiter = _make_limiter(prefix="ratelimit:fb3", default_limit=2) - # Pre-seed bucket so the next call exceeds the limit. - import time as _time - - now = _time.time() - limiter._inprocess_buckets["7.7.7.7"] = [now, now] # already at limit - - with patch( - "autobot_shared.redis_client.get_async_redis_client", - new=AsyncMock(return_value=None), - ): - with pytest.raises(HTTPException) as exc_info: - await limiter.check_or_429("7.7.7.7") - assert exc_info.value.status_code == 429 - - -class TestIPRateLimiterConfig: - """Issue #7271: limit is read from env each call (dynamic config).""" - - def test_limit_property_reads_env(self, monkeypatch) -> None: - limiter = _make_limiter(default_limit=60) - monkeypatch.setenv("UNIT_TEST_RATE_LIMIT", "120") - assert limiter.limit == 120 - monkeypatch.setenv("UNIT_TEST_RATE_LIMIT", "5") - assert limiter.limit == 5 - - def test_limit_falls_back_to_default_when_env_unparseable(self, monkeypatch) -> None: - limiter = _make_limiter(default_limit=60) - monkeypatch.setenv("UNIT_TEST_RATE_LIMIT", "not-a-number") - assert limiter.limit == 60 - - def test_limit_uses_default_when_env_unset(self, monkeypatch) -> None: - monkeypatch.delenv("UNIT_TEST_RATE_LIMIT", raising=False) - limiter = _make_limiter(default_limit=60) - assert limiter.limit == 60 diff --git a/autobot_shared/rate_limiter.py b/autobot_shared/rate_limiter.py index 8cbe98c9ea..ca1dafccaa 100644 --- a/autobot_shared/rate_limiter.py +++ b/autobot_shared/rate_limiter.py @@ -65,6 +65,7 @@ import uuid from autobot_shared.env_utils import env_float +from autobot_shared.rate_limiter_window import LocalWindowCounter, WindowFailurePolicy from autobot_shared.redis_client import get_async_redis_client from autobot_shared.ssot_constants import TTL_2_HOURS @@ -144,6 +145,9 @@ class RateLimiter: log_label: When set, ``acquire_window`` logs a warning (label, limit, window -- never the key) on each rejection; the default keeps it silent. + window_failure_policy: + What ``acquire_window`` does when Redis cannot answer: ``FAIL_OPEN`` (default, + allow), ``LOCAL`` (enforce per process) or ``FAIL_CLOSED`` (deny) (#18087). """ def __init__( @@ -154,8 +158,11 @@ def __init__( requests_per_hour: int | None = None, redis_database: str = "main", log_label: str | None = None, + window_failure_policy: WindowFailurePolicy = WindowFailurePolicy.FAIL_OPEN, ) -> None: self._prefix = scope_prefix + self._window_policy = window_failure_policy + self._local_windows = LocalWindowCounter() self._log_label = log_label # Logs name the limiter only (prefix + optional label), never a key (#18087). self._log_scope = f"{scope_prefix}/{log_label}" if log_label else scope_prefix @@ -177,18 +184,18 @@ def __init__( self.fail_open_count: int = 0 def _warn_fail_open(self, reason: str) -> None: - """Warn that a request was allowed because Redis is unavailable (#18617). - - Names the limiter scope only, never a key or key-derived value, and is - rate-limited per instance to one line per ``FAIL_OPEN_WARN_INTERVAL_SECONDS``. - """ + """Throttled warning (scope only, never a key) that Redis was down and a request was allowed (#18617).""" self.fail_open_count += 1 - mono = time.monotonic() - last = self._last_fail_open_warn - if last is not None and mono - last < FAIL_OPEN_WARN_INTERVAL_SECONDS: - return - self._last_fail_open_warn = mono - logger.warning("rate_limiter: %s for limiter '%s'; allowing request (fail-open)", reason, self._log_scope) + if self._warn_due(): + logger.warning("rate_limiter: %s for limiter '%s'; allowing request (fail-open)", reason, self._log_scope) + + def _warn_due(self) -> bool: + """True at most once per ``FAIL_OPEN_WARN_INTERVAL_SECONDS`` per instance (outage warnings).""" + mono, last = time.monotonic(), self._last_fail_open_warn + due = last is None or mono - last >= FAIL_OPEN_WARN_INTERVAL_SECONDS + if due: + self._last_fail_open_warn = mono + return due # ------------------------------------------------------------------ # Public API @@ -445,8 +452,7 @@ async def _try_acquire_window(self, key: str, max_requests: int, window_seconds: try: redis = await get_async_redis_client(database=self._db) if redis is None: - self._warn_fail_open("Redis unavailable") - return True, 0.0 + return self._window_unavailable(key, max_requests, window_seconds, "Redis unavailable") lua_script = """ local win_key = KEYS[1] @@ -478,8 +484,40 @@ async def _try_acquire_window(self, key: str, max_requests: int, window_seconds: result = await redis.eval(lua_script, 2, win_key, win_key + ":seq", now, window_seconds, max_requests) return bool(result[0]), max(0.0, float(result[1])) except Exception as exc: - self._warn_fail_open(f"window acquire error ({type(exc).__name__})") + return self._window_unavailable( + key, max_requests, window_seconds, f"window acquire error ({type(exc).__name__})" + ) + + def _window_unavailable(self, key: str, max_requests: int, window_seconds: int, reason: str) -> tuple[bool, float]: + """Apply ``window_failure_policy`` when Redis could not answer (#18087).""" + if self._window_policy is WindowFailurePolicy.FAIL_OPEN: + self._warn_fail_open(reason) return True, 0.0 + if self._warn_due(): + logger.warning("rate_limiter: %s for '%s'; policy=%s", reason, self._log_scope, self._window_policy.value) + if self._window_policy is WindowFailurePolicy.FAIL_CLOSED: + return False, float(window_seconds) + return self._local_windows.try_acquire(f"{self._prefix}:{key}", max_requests, window_seconds) + + async def get_window_usage(self, key: str, window_seconds: int) -> tuple[int, float]: + """Return ``(hits_in_window, seconds_until_the_oldest_hit_expires)`` for status endpoints.""" + local = f"{self._prefix}:{key}" + try: + redis = await get_async_redis_client(database=self._db) + if redis is None: + return self._local_windows.usage(local, window_seconds) + now = time.time() + win_key = self._redis_key(key, "window") + live = await redis.zrangebyscore(win_key, now - window_seconds, "+inf", start=0, num=1, withscores=True) + count = int(await redis.zcount(win_key, now - window_seconds, "+inf")) + return count, (max(0.0, window_seconds - (now - float(live[0][1]))) if live else 0.0) + except Exception as exc: + logger.warning("rate_limiter: window usage error (%s) for '%s'", type(exc).__name__, self._log_scope) + return self._local_windows.usage(local, window_seconds) + + def reset_local_windows(self) -> None: + """Drop the per-process ``LOCAL``-policy fallback state (tests).""" + self._local_windows.reset() async def get_remaining_in_window(self, key: str, max_requests: int, window_seconds: int) -> int: """Return how many more requests are allowed in the custom window. @@ -491,15 +529,25 @@ async def get_remaining_in_window(self, key: str, max_requests: int, window_seco try: redis = await get_async_redis_client(database=self._db) if redis is None: - self._warn_fail_open("Redis unavailable") - return max_requests + return self._remaining_unavailable(key, max_requests, window_seconds, "Redis unavailable") win_key = self._redis_key(key, "window") count = await redis.zcount(win_key, now - window_seconds, "+inf") return max(0, max_requests - int(count)) except Exception as exc: - self._warn_fail_open(f"get_remaining error ({type(exc).__name__})") + return self._remaining_unavailable( + key, max_requests, window_seconds, f"get_remaining error ({type(exc).__name__})" + ) + + def _remaining_unavailable(self, key: str, max_requests: int, window_seconds: int, reason: str) -> int: + """Remaining quota when Redis could not answer, per ``window_failure_policy``.""" + if self._window_policy is WindowFailurePolicy.FAIL_OPEN: + self._warn_fail_open(reason) return max_requests + if self._window_policy is WindowFailurePolicy.FAIL_CLOSED: + return 0 + used, _ = self._local_windows.usage(f"{self._prefix}:{key}", window_seconds) + return max(0, max_requests - used) # ------------------------------------------------------------------ # Token-bucket mode (Issue #12646 fold-in) diff --git a/autobot_shared/rate_limiter_log_label_18087_test.py b/autobot_shared/rate_limiter_log_label_18087_test.py index 944ae020ad..951b133d45 100644 --- a/autobot_shared/rate_limiter_log_label_18087_test.py +++ b/autobot_shared/rate_limiter_log_label_18087_test.py @@ -54,3 +54,18 @@ async def test_label_allowed_request_is_silent(caplog): with caplog.at_level(logging.DEBUG): assert await _limiter(True, log_label="lbl").acquire_window(CALLER_ID, 5, 60) is True assert _warnings(caplog) == [] + + +@pytest.mark.asyncio +async def test_local_outage_warns_once_and_refusals_stay_silent(caplog): + from unittest.mock import AsyncMock, patch + + from autobot_shared.rate_limiter_window import WindowFailurePolicy + + lim = RateLimiter("scope-x", window_failure_policy=WindowFailurePolicy.LOCAL) + with patch("autobot_shared.rate_limiter.get_async_redis_client", AsyncMock(return_value=None)): + with caplog.at_level(logging.WARNING): + results = [await lim.acquire_window(CALLER_ID, 1, 60) for _ in range(4)] + assert results == [True, False, False, False] + assert len(_warnings(caplog)) == 1 and "policy=local" in _warnings(caplog)[0] + assert CALLER_ID not in caplog.text diff --git a/autobot_shared/rate_limiter_window.py b/autobot_shared/rate_limiter_window.py new file mode 100644 index 0000000000..2b2a91cf3f --- /dev/null +++ b/autobot_shared/rate_limiter_window.py @@ -0,0 +1,219 @@ +# Copyright 2025-2026 mrveiss +# SPDX-License-Identifier: Apache-2.0 +# AutoBot - AI-Powered Automation Platform +# Author: mrveiss +"""Window-mode companions of the canonical ``RateLimiter`` (#18087, #7271). + +``autobot_shared.rate_limiter.RateLimiter`` is the one rate limiter. This module +holds the pieces its single-window mode needs so that call sites which used to +carry their own limiter can delegate instead of re-implementing it: + +* :class:`WindowFailurePolicy` -- what a window acquire does when Redis cannot + answer. The caller picks it; the default is the house policy (fail open). +* :class:`LocalWindowCounter` -- the per-process sliding window the ``LOCAL`` + policy degrades to. +* :class:`WindowQuota` -- one named quota (key, limit, window) bound to a + limiter, with the ``bool`` and HTTP-429 call shapes the old forks exposed. + +Why the policy is a parameter and not a decision made here +---------------------------------------------------------- +Three behaviours existed across the forks, and each is security- or +availability-relevant, so none is silently chosen for every caller: + + FAIL_OPEN Redis down -> allow. Never blocks traffic, but switches the control + off for the outage. The default, and what every ``acquire_window`` + caller had before this module. + LOCAL Redis down -> keep enforcing, per process. The limit is then + multiplied by the worker count, but the control never turns off. + What ``IPRateLimiter`` (public OpenAI/A2A endpoints) and the four + in-process MCP counters effectively did. + FAIL_CLOSED Redis down -> deny. For controls where over-admitting is worse than + an outage. With ``wait=True`` this blocks until Redis returns. + +One further difference is NOT a parameter: ``IPRateLimiter`` recorded a request +*before* counting it, so a rejected request extended the window and a client +that kept retrying stayed locked out indefinitely. The canonical window records +only admitted requests, which is the intended sliding-window behaviour; that +defect is not preserved behind an option. +""" + +from __future__ import annotations + +import threading +import time +from collections import deque +from enum import Enum +from typing import TYPE_CHECKING, Any + +from autobot_shared.env_utils import env_int +from autobot_shared.logging_manager import get_logger + +if TYPE_CHECKING: + from autobot_shared.rate_limiter import RateLimiter + +logger = get_logger(__name__) + +#: Cap on distinct keys the per-process fallback tracks; expired keys are evicted +#: first, and a new key is refused only when every tracked key is still live. +LOCAL_WINDOW_MAX_KEYS = env_int("AUTOBOT_RATE_LIMIT_LOCAL_MAX_KEYS", 10_000) + + +class WindowFailurePolicy(str, Enum): + """What a single-window acquire does when Redis cannot answer.""" + + FAIL_OPEN = "fail_open" + LOCAL = "local" + FAIL_CLOSED = "fail_closed" + + +class LocalWindowCounter: + """Per-process sliding window; only admitted hits are recorded. + + Each key keeps the window it was last used with, so a key admitted under a + long window is not evicted by a call that uses a short one. At most + ``max_keys`` distinct keys are tracked: once full and nothing has expired, a + new key is refused rather than evicting a live quota's history. + """ + + def __init__(self, max_keys: int = LOCAL_WINDOW_MAX_KEYS) -> None: + self._max_keys = max_keys + self._hits: dict[str, deque[float]] = {} + self._windows: dict[str, float] = {} + self._lock = threading.Lock() + + def _live(self, key: str, window_seconds: float, now: float) -> deque[float] | None: + """Return the key's live hits (trimmed), or ``None`` when the table has no room for it.""" + hits = self._hits.get(key) + if hits is None: + if len(self._hits) >= self._max_keys: + self._evict_stale(now) + if len(self._hits) >= self._max_keys: + return None + hits = self._hits[key] = deque() + self._windows[key] = max(window_seconds, self._windows.get(key, 0.0)) + while hits and hits[0] <= now - window_seconds: + hits.popleft() + return hits + + def try_acquire(self, key: str, max_requests: int, window_seconds: float) -> tuple[bool, float]: + """Return ``(allowed, retry_after_seconds)``; record only on admit.""" + now = time.time() + with self._lock: + hits = self._live(key, window_seconds, now) + if hits is None: + return False, float(window_seconds) + if len(hits) >= max_requests: + retry_after = window_seconds - (now - hits[0]) if hits else window_seconds + return False, max(0.0, retry_after) + hits.append(now) + return True, 0.0 + + def record(self, key: str, window_seconds: float) -> None: + """Record a hit unconditionally (the caller checked, or owes the count).""" + now = time.time() + with self._lock: + hits = self._live(key, window_seconds, now) + if hits is not None: + hits.append(now) + + def usage(self, key: str, window_seconds: float) -> tuple[int, float]: + """Return ``(hits_in_window, seconds_until_the_oldest_hit_expires)``; never creates a key.""" + now = time.time() + with self._lock: + hits = [h for h in self._hits.get(key, ()) if h > now - window_seconds] + return len(hits), (max(0.0, window_seconds - (now - hits[0])) if hits else 0.0) + + def _evict_stale(self, now: float) -> None: + """Drop keys whose every hit has aged out of that key's own window.""" + for stale in [k for k, h in self._hits.items() if not h or h[-1] <= now - self._windows[k]]: + del self._hits[stale] + del self._windows[stale] + + def reset(self) -> None: + """Forget every key (tests).""" + with self._lock: + self._hits.clear() + self._windows.clear() + + +class WindowQuota: + """One named window quota bound to a canonical :class:`RateLimiter`. + + ``key`` is the default subject (a fixed string for a global quota); pass a + per-call key to ``acquire`` / ``check_or_429`` for per-client quotas. + ``limit_env`` makes the limit re-read from that environment variable on + every call, with ``max_requests`` as the fallback. + """ + + def __init__( + self, + limiter: RateLimiter, + *, + max_requests: int, + window_seconds: int = 60, + key: str = "global", + label: str = "requests", + limit_env: str | None = None, + ) -> None: + self.limiter = limiter + self.window_seconds = window_seconds + self.label = label + self._key = key + self._default_max = max_requests + self._limit_env = limit_env + + @classmethod + def for_scope( + cls, + scope: str, + *, + policy: WindowFailurePolicy = WindowFailurePolicy.FAIL_OPEN, + log_rejections: bool = True, + **quota: Any, + ) -> WindowQuota: + """Build a quota on its own canonical ``RateLimiter`` for *scope*. + + *quota* is the keyword set of ``__init__`` after the limiter. The + limiter import is deferred because ``rate_limiter`` imports this module. + ``log_rejections=False`` keeps a refusal silent (anonymous routes, where + a flood would otherwise amplify into the log). + """ + from autobot_shared.rate_limiter import RateLimiter # noqa: PLC0415 + + limiter = RateLimiter(scope, log_label=scope if log_rejections else None, window_failure_policy=policy) + return cls(limiter, **quota) + + @property + def max_requests(self) -> int: + """The current limit (env-backed when ``limit_env`` was given).""" + if self._limit_env is None: + return self._default_max + return env_int(self._limit_env, self._default_max) + + async def acquire(self, key: str | None = None) -> bool: + """Atomically admit or refuse one request.""" + subject = key or self._key + return await self.limiter.acquire_window(subject, self.max_requests, self.window_seconds) + + async def check_or_429(self, key: str | None = None) -> None: + """``acquire``, raising ``HTTPException(429)`` when refused.""" + if await self.acquire(key): + return + from fastapi import HTTPException # noqa: PLC0415 + + raise HTTPException( + status_code=429, + detail=f"Rate limit exceeded ({self.max_requests} requests/{self.window_seconds}s). Try again later.", + ) + + async def status(self, key: str | None = None) -> dict[str, float | int]: + """Return ``{"current", "max", "reset_in_seconds"}`` for the quota.""" + used, reset_in = await self.limiter.get_window_usage(key or self._key, self.window_seconds) + return {"current": used, "max": self.max_requests, "reset_in_seconds": round(reset_in, 1)} + + def reset_local(self) -> None: + """Drop the per-process fallback state (tests).""" + self.limiter.reset_local_windows() + + +__all__ = ["LocalWindowCounter", "WindowFailurePolicy", "WindowQuota"] diff --git a/autobot_shared/rate_limiter_window_18087_test.py b/autobot_shared/rate_limiter_window_18087_test.py new file mode 100644 index 0000000000..0a4366ed17 --- /dev/null +++ b/autobot_shared/rate_limiter_window_18087_test.py @@ -0,0 +1,247 @@ +# Copyright 2025-2026 mrveiss +# SPDX-License-Identifier: Apache-2.0 +# AutoBot - AI-Powered Automation Platform +# Author: mrveiss +"""Behaviour of the canonical window limiter's failure policies (#18087, #7271). + +These pin the properties the folded forks relied on, each against the real +``RateLimiter`` with a stateful fake Redis -- not against a mock that returns +truthy: + +* cross-process: two workers sharing Redis admit ``limit`` requests in total, + not ``limit`` each (the per-worker multiplication the dict counters had); +* a REJECTED request is not recorded, so it never extends the window (the + ``IPRateLimiter`` ZADD-before-ZCARD defect); +* what happens when Redis is down is the caller's explicit choice, and each of + the three choices behaves as documented. +""" + +from __future__ import annotations + +import asyncio +from collections import deque +from unittest.mock import AsyncMock, patch + +import pytest +from fastapi import HTTPException + +from autobot_shared.rate_limiter import RateLimiter +from autobot_shared.rate_limiter_window import ( + LocalWindowCounter, + WindowFailurePolicy, + WindowQuota, +) + +_REDIS = "autobot_shared.rate_limiter.get_async_redis_client" + + +class FakeWindowRedis: + """Python re-statement of the canonical window Lua over shared state.""" + + def __init__(self) -> None: + self.zsets: dict[str, list[float]] = {} + + async def eval(self, script, numkeys, win_key, seq_key, now, window, max_requests): + hits = [t for t in self.zsets.get(win_key, []) if t > now - window] + self.zsets[win_key] = hits + if len(hits) >= max_requests: + return [0, str(window - (now - hits[0]))] + hits.append(now) + return [1, "0"] + + async def zcount(self, win_key, low, high): + return len([t for t in self.zsets.get(win_key, []) if t >= low]) + + async def zrangebyscore(self, win_key, low, high, start=0, num=1, withscores=False): + live = sorted(t for t in self.zsets.get(win_key, []) if t >= low)[start : start + num] + return [(b"m", t) for t in live] + + +def _quota(policy=WindowFailurePolicy.FAIL_OPEN, limit=3, **kw) -> WindowQuota: + return WindowQuota.for_scope("t18087", policy=policy, max_requests=limit, window_seconds=60, **kw) + + +def _run(coro): + return asyncio.run(coro) + + +async def _burst(quota: WindowQuota, n: int, key: str | None = None) -> list[bool]: + return [await quota.acquire(key) for _ in range(n)] + + +class TestCrossProcess: + def test_two_workers_share_one_limit(self): + redis = FakeWindowRedis() + worker_a, worker_b = _quota(limit=5), _quota(limit=5) + with patch(_REDIS, AsyncMock(return_value=redis)): + a = _run(_burst(worker_a, 5)) + b = _run(_burst(worker_b, 5)) + assert sum(a) + sum(b) == 5, "the limit is global, not per worker" + + def test_contrast_outage_local_state_is_per_worker(self): + """The cost of LOCAL, stated: two workers admit the limit EACH while Redis is down.""" + worker_a, worker_b = _quota(WindowFailurePolicy.LOCAL, 5), _quota(WindowFailurePolicy.LOCAL, 5) + with patch(_REDIS, AsyncMock(return_value=None)): + admitted = sum(_run(_burst(worker_a, 9))) + sum(_run(_burst(worker_b, 9))) + assert admitted == 10 + + +class TestRejectDoesNotExtendTheWindow: + def test_rejected_requests_are_not_recorded(self): + redis = FakeWindowRedis() + quota = _quota(limit=3) + with patch(_REDIS, AsyncMock(return_value=redis)): + results = _run(_burst(quota, 20)) + assert results == [True] * 3 + [False] * 17 + (hits,) = redis.zsets.values() + assert len(hits) == 3, "IPRateLimiter recorded all 20, so a retrying client never recovered" + + def test_local_path_does_not_record_rejections_either(self): + counter = LocalWindowCounter() + for _ in range(10): + counter.try_acquire("k", 2, 60) + assert counter.usage("k", 60)[0] == 2 + + +class TestFailurePolicy: + @pytest.mark.parametrize("fault", ["none", "raises"]) + def test_open_allows_everything(self, fault): + quota = _quota(WindowFailurePolicy.FAIL_OPEN) + patched = AsyncMock(return_value=None) if fault == "none" else AsyncMock(side_effect=ConnectionError("down")) + with patch(_REDIS, patched): + assert all(_run(_burst(quota, 10))) + + @pytest.mark.parametrize("fault", ["none", "raises"]) + def test_local_keeps_enforcing(self, fault): + quota = _quota(WindowFailurePolicy.LOCAL) + patched = AsyncMock(return_value=None) if fault == "none" else AsyncMock(side_effect=ConnectionError("down")) + with patch(_REDIS, patched): + assert _run(_burst(quota, 5)) == [True] * 3 + [False] * 2 + + @pytest.mark.parametrize("fault", ["none", "raises"]) + def test_closed_denies_everything(self, fault): + quota = _quota(WindowFailurePolicy.FAIL_CLOSED) + patched = AsyncMock(return_value=None) if fault == "none" else AsyncMock(side_effect=ConnectionError("down")) + with patch(_REDIS, patched): + assert not any(_run(_burst(quota, 3))) + + def test_default_policy_is_open(self): + assert RateLimiter("x")._window_policy is WindowFailurePolicy.FAIL_OPEN + + def test_local_policy_is_per_key(self): + quota = _quota(WindowFailurePolicy.LOCAL, limit=1) + with patch(_REDIS, AsyncMock(return_value=None)): + assert _run(quota.acquire("1.1.1.1")) and _run(quota.acquire("2.2.2.2")) + assert not _run(quota.acquire("1.1.1.1")) + + def test_concurrent_local_acquires_admit_exactly_the_limit(self): + quota = _quota(WindowFailurePolicy.LOCAL, limit=40) + + async def run() -> list[bool]: + return await asyncio.gather(*[quota.acquire() for _ in range(100)]) + + with patch(_REDIS, AsyncMock(return_value=None)): + assert sum(_run(run())) == 40 + + +class TestQuota: + def test_check_or_429_raises_with_the_documented_detail(self): + quota = _quota(WindowFailurePolicy.LOCAL, limit=1) + with patch(_REDIS, AsyncMock(return_value=None)): + _run(quota.check_or_429("ip")) + with pytest.raises(HTTPException) as err: + _run(quota.check_or_429("ip")) + assert err.value.status_code == 429 + assert err.value.detail == "Rate limit exceeded (1 requests/60s). Try again later." + + def test_limit_is_reread_from_env_each_call(self, monkeypatch): + quota = _quota(limit=7, limit_env="T18087_LIMIT") + assert quota.max_requests == 7 + monkeypatch.setenv("T18087_LIMIT", "2") + assert quota.max_requests == 2 + monkeypatch.setenv("T18087_LIMIT", "not-a-number") + assert quota.max_requests == 7 + + def test_scopes_do_not_share_state(self): + redis = FakeWindowRedis() + one = WindowQuota.for_scope("scope_one", max_requests=1) + two = WindowQuota.for_scope("scope_two", max_requests=1) + with patch(_REDIS, AsyncMock(return_value=redis)): + assert _run(one.acquire("k")) and _run(two.acquire("k")) + assert not _run(one.acquire("k")) + + def test_status_reports_usage_from_redis(self): + redis = FakeWindowRedis() + quota = _quota(limit=5) + with patch(_REDIS, AsyncMock(return_value=redis)): + _run(_burst(quota, 2)) + status = _run(quota.status()) + assert status["current"] == 2 and status["max"] == 5 + assert 0 < status["reset_in_seconds"] <= 60 + + def test_status_reports_usage_from_local_fallback(self): + quota = _quota(WindowFailurePolicy.LOCAL, limit=5) + with patch(_REDIS, AsyncMock(return_value=None)): + _run(_burst(quota, 3)) + assert _run(quota.status())["current"] == 3 + + def test_remaining_under_local_policy_reflects_local_hits(self): + quota = _quota(WindowFailurePolicy.LOCAL, limit=5) + with patch(_REDIS, AsyncMock(return_value=None)): + _run(_burst(quota, 2)) + assert _run(quota.limiter.get_remaining_in_window("global", 5, 60)) == 3 + + +class TestLocalWindowCounter: + def test_hits_expire_out_of_the_window(self): + counter = LocalWindowCounter() + counter._hits["k"] = deque([0.0] * 5) # the epoch: far outside any window + assert counter.try_acquire("k", 5, 60)[0] is True + + def test_stale_keys_are_evicted_past_the_cap(self): + counter = LocalWindowCounter(max_keys=2) + counter._hits.update({"old1": deque([0.0]), "old2": deque([0.0])}) + counter._windows.update({"old1": 60.0, "old2": 60.0}) + counter.try_acquire("live", 5, 60) + assert set(counter._hits) == {"live"} + + def test_a_zero_limit_refuses_with_the_full_window(self): + allowed, retry_after = LocalWindowCounter().try_acquire("k", 0, 60) + assert allowed is False and retry_after == 60 + + def test_live_keys_are_never_evicted_and_the_cap_holds(self): + counter = LocalWindowCounter(max_keys=2) + assert counter.try_acquire("a", 1, 60)[0] and counter.try_acquire("b", 1, 60)[0] + assert counter.try_acquire("c", 1, 60)[0] is False + counter.record("d", 60) + assert set(counter._hits) == {"a", "b"} + assert counter.try_acquire("a", 1, 60)[0] is False # history preserved + + def test_usage_does_not_create_a_key(self): + counter = LocalWindowCounter() + assert counter.usage("ghost", 60) == (0, 0.0) + assert counter._hits == {} + + def test_a_key_is_evicted_by_its_own_window_not_the_callers(self): + counter = LocalWindowCounter(max_keys=2) + counter.try_acquire("long", 1, 3600) + counter._hits["long"][0] -= 61 # 61s old: expired for a 60s window, live for 3600s + counter.try_acquire("short", 1, 60) + assert counter.try_acquire("new", 1, 60)[0] is False # full of live keys; "long" kept + assert counter.try_acquire("long", 1, 3600)[0] is False + + def test_retry_after_is_time_until_the_oldest_hit_expires(self): + counter = LocalWindowCounter() + counter.try_acquire("k", 1, 60) + allowed, retry_after = counter.try_acquire("k", 1, 60) + assert allowed is False and 59 < retry_after <= 60 + + +class TestLocalWindowCounterRecord: + def test_record_counts_without_checking(self): + counter = LocalWindowCounter() + for _ in range(3): + counter.record("k", 60) + used, reset_in = counter.usage("k", 60) + assert used == 3 and 59 < reset_in <= 60 + assert counter.try_acquire("k", 3, 60)[0] is False diff --git a/docs/developer/ENV_VARS.md b/docs/developer/ENV_VARS.md index f2a2fb2e89..5cc843ffb4 100644 --- a/docs/developer/ENV_VARS.md +++ b/docs/developer/ENV_VARS.md @@ -464,6 +464,7 @@ appears outside the known overlays. | `AUTOBOT_RAG_SCORE_THRESHOLD` | rag | float | `0.3` | Minimum relevance score a knowledge-retrieval result needs to be kept (constants.rag_graph_constants.RAG_SCORE_THRESHOLD, the one default, #19354). Range: 0.0–1.0. | | `AUTOBOT_RANKING_ALPHA` | code_analysis | float | `1.0` | Multiplicative weight applied to the runtime_risk boost when ranking anti-pattern findings (0 disables the boost; 1.0 lets a fully-risky file double its effective score). Raising it weights runtime risk more heavily in the ranking; lowering it toward 0 weights it less (code_analysis/src/anti_pattern_detector.py). | | `AUTOBOT_RATE_LIMITER_FAIL_OPEN_WARN_INTERVAL` | security | float | `60.0` | Minimum seconds between fail-open warnings per rate-limiter instance (#18617). While Redis is unreachable the limiters allow requests; the warning names only the limiter scope and is emitted at most once per interval so an outage cannot flood the log. | +| `AUTOBOT_RATE_LIMIT_LOCAL_MAX_KEYS` | rate_limit | int | `10000` | Cap on distinct keys the per-process rate-limit fallback tracks before it evicts keys whose every hit has aged out of the window (#18087). Only used while Redis is unavailable and a limiter's window_failure_policy is LOCAL; bounds memory when an outage outlasts the window. | | `AUTOBOT_REDIS_DB_ANALYTICS` | redis | int | *(none)* | Redis DB number for analytics data; unset uses redis-databases.yaml (#19232). Range: 0–15. | | `AUTOBOT_REDIS_DB_KNOWLEDGE` | redis | int | *(none)* | Redis DB number for knowledge-base vectors; unset uses redis-databases.yaml (#19232). Range: 0–15. | | `AUTOBOT_REDIS_DB_MAIN` | redis | int | *(none)* | Redis DB number for primary application data; unset uses redis-databases.yaml (#19232). Range: 0–15. | diff --git a/repo_tests/_reach_declared_scopes.py b/repo_tests/_reach_declared_scopes.py index c297cd5778..5431a86cd9 100644 --- a/repo_tests/_reach_declared_scopes.py +++ b/repo_tests/_reach_declared_scopes.py @@ -322,6 +322,7 @@ "slm-node-enum-members-exist": ("autobot-slm-backend",), "browser-worker-one-manifest-21852": ("autobot-browser-worker",), "one-playwright-server-scan": ("autobot-browser-worker", "autobot-infrastructure", "autobot-frontend"), + "one-rate-limiter-scan": ("autobot-backend", "autobot-slm-backend", "autobot_shared"), "fact-read-authorization-scan": ("autobot-backend", "autobot-slm-backend", "autobot_shared"), "llm-quality-seam-scan": ("autobot-backend/judges", "autobot-backend/rlm", "autobot-backend/agent_loop"), "one-permission-gate-scan": ("autobot-backend", "autobot-slm-backend", "autobot_shared"), diff --git a/repo_tests/_reach_policy_verdicts.py b/repo_tests/_reach_policy_verdicts.py index 206e429092..d68481212f 100644 --- a/repo_tests/_reach_policy_verdicts.py +++ b/repo_tests/_reach_policy_verdicts.py @@ -187,6 +187,11 @@ "SUBSET_DRIFTS", "Non-test knowledge_*.py route modules are a subset of tracked api files; the test-file share drifts.", ), + "one-rate-limiter-scan": ( + ABSOLUTE, + "SUBSET_DRIFTS", + "Production Python under three trees, against all tracked Python.", + ), "fact-read-authorization-scan": ( ABSOLUTE, "SUBSET_DRIFTS", diff --git a/repo_tests/_reach_roots_record.py b/repo_tests/_reach_roots_record.py index e4d5d18cbd..982cbabe48 100644 --- a/repo_tests/_reach_roots_record.py +++ b/repo_tests/_reach_roots_record.py @@ -323,6 +323,7 @@ "autobot-frontend", "autobot-infrastructure", ), + "repo_tests/one_rate_limiter_18087_test.py": ("autobot-backend", "autobot-slm-backend", "autobot_shared"), "repo_tests/one_semantic_chunker_14485_test.py": ("autobot-backend", "autobot_shared"), "repo_tests/one_serving_predicate_18820_test.py": ("autobot-backend", "autobot_shared", "libs", "plugins"), "repo_tests/one_session_ownership_validator_14016_test.py": ( diff --git a/repo_tests/one_rate_limiter_18087_test.py b/repo_tests/one_rate_limiter_18087_test.py new file mode 100644 index 0000000000..1cd47a6e01 --- /dev/null +++ b/repo_tests/one_rate_limiter_18087_test.py @@ -0,0 +1,297 @@ +# Copyright 2025-2026 mrveiss +# SPDX-License-Identifier: Apache-2.0 +# AutoBot - AI-Powered Automation Platform +# Author: mrveiss +"""One rate limiter: no second implementation appears outside the canonical module (#18087, #7271). + +``autobot_shared.rate_limiter.RateLimiter`` is the rate limiter. #12646 said so, then +``autobot_shared/rate_limit.py`` (``IPRateLimiter``) was added beside it under a name three +characters different, four MCP modules kept hand-rolled fixed-window counters, and a session +password limiter kept a per-worker dict -- none of which a symbol-fork detector could see, +because the forks did not share a name. Their behaviours differed in ways that matter +(fail-open vs per-worker enforcement; a rejected request extending the window), so picking the +wrong one was a behaviour change, not a style choice. + +WHAT THIS DETECTS (behaviour first, one name signal as a backstop), per non-test module: + + counter-dict a dict literal carrying both ``count`` and ``reset_time`` keys -- the + hand-rolled fixed-window counter the four MCP modules had. + zset-window a module using all of ZADD, ZCARD and ZREMRANGEBYSCORE (as calls or inside a + Lua string) -- the Redis sorted-set sliding window. + limiter-class a class whose name ends in ``Limiter``. + +WHAT IT IS BLIND TO, stated because a baseline cannot record what its detector never saw: a +limiter written with none of those shapes (an in-process list of timestamps under a method +named ``allow``), and anything outside the three scanned trees. The scan is a floor on +duplication, not a proof of its absence. + +THE ALLOWLIST is every module that trips a detector and is NOT the canonical limiter, each with +the reason it is a different concept. It is shrink-only and BIDIRECTIONAL: a new module fails, +and an entry that no longer trips fails just as loudly, so the list cannot tolerate whatever +takes that path next. +""" + +from __future__ import annotations + +import ast +import re +from pathlib import Path + +import pytest +from repo_tests._paths import repo_root +from repo_tests._reach import declare + +from autobot_shared.testfile_names import is_test_filename +from tools.lint import _parse_cache as parse_cache +from tools.lint._scan_helpers import EmptyEnumeration, tracked_paths + +REPO_ROOT = repo_root() + +SCANNED_TREES = ("autobot-backend", "autobot-slm-backend", "autobot_shared") + +#: The one rate limiter. Its companion ``rate_limiter_window`` holds the window failure +#: policies and per-process fallback it delegates to; it trips no detector by design. +CANONICAL = "autobot_shared/rate_limiter.py" + +_ZSET_COMMANDS = ("zadd", "zcard", "zremrangebyscore") +_LIMITER_CLASS = re.compile(r"Limiter$") + +#: module -> why it is a different concept and stays. Verified by behaviour, not by name. +DISTINCT_CONCEPTS: dict[str, str] = { + "autobot-backend/llm_shared/cross_worker_rate_limiter.py": ( + "Redis token bucket for LLM provider quota: state is (tokens, ts), refill is continuous and " + "fractional, burst is a capacity separate from the sustained rate. A sliding window admits `max` " + "at once then nothing until the oldest hit ages out; a bucket admits one per 1/rate. Per-provider " + "RPM/burst come from AUTOBOT_LLM_RL_*. Cannot be expressed as RateLimiter.acquire_window." + ), + "autobot-backend/integrations/rate_limiter.py": ( + "Outbound quota for GitHub/Slack calls whose pause state is corrected by the provider's own " + "X-RateLimit-*/Retry-After response headers (apply_response_headers) -- a feedback loop the canonical " + "class does not have. Only that header state is distinct: its request-count windows are two " + "LocalWindowCounter instances (the canonical LOCAL-policy engine), pinned by " + "test_integration_limiter_keeps_no_window_of_its_own." + ), + "autobot-backend/utils/conversation_rate_limiter.py": ( + "Outbound Claude API budget that also tracks payload size, warning thresholds and backoff " + "advice, with a synchronous dict-returning API. A per-process budget for one client, not a " + "request gate. Audited in #7271 as a different shape: the retired claude_api_optimization_suite " + "(deleted in 248d6dae1e, #10796) only imported ConversationRateLimiter and its successor claude_api_integration " + "delegates here." + ), + "autobot-backend/user_management/middleware/rate_limit.py": ( + "TargetedPasswordChangeRateLimiter counts FAILED attempts only (INCR + EXPIRE) and clears the " + "counter on success, keyed per target user and per calling actor. A lockout counter, not a " + "request-rate window." + ), + "autobot-backend/mcp_server/auth_throttle_store.py": ( + "Shared failed-authentication lockout state for the MCP pre-auth throttle, with an owner-decided " + "degrade-to-per-process policy documented in the module. A lockout, not a request-rate window." + ), + "autobot-backend/services/workflow_automation/concurrent_limiter.py": ( + "Caps CONCURRENT in-flight workflows (acquire/release), not requests per unit time." + ), + "autobot-backend/utils/task_queue.py": ( + "Job queue: uses ZADD/ZCARD/ZREMRANGEBYSCORE for pending/running/completed job sets and retention " + "trimming. No request is admitted or refused against a limit." + ), +} + + +def _is_test_path(path: str) -> bool: + return is_test_filename(path.rsplit("/", 1)[-1]) or "/tests/" in path + + +def _scanned_modules(root: Path) -> list[str]: + """Non-test Python modules under the scanned trees. + + An empty listing returns ``[]`` so the floor raises the typed ``ReachFloorError``; + ``reach_declarations_test`` hands every declaration an empty repository on purpose. + """ + try: + listed = tracked_paths(root, *SCANNED_TREES) + except EmptyEnumeration: + return [] + return sorted(p for p in listed if p.endswith(".py") and not _is_test_path(p)) + + +#: A sweep that lost its reach (wrong root, inverted filter) would report "nothing found" with +#: none of the evidence. ``floor=`` is pinned because a guard new in this PR has no declaration at +#: the base to compute one from (#19676); it sits mid-window (live population 3733, growth 200). +#: Drop the pin once this guard is on main, so the floor is computed from the base again. +REACH = declare( + "one-rate-limiter-scan", + discover=_scanned_modules, + floor=3623, + growth=200, + what="non-test Python modules", + roots=SCANNED_TREES, +) + + +def _zset_words(tree: ast.AST) -> set[str]: + found: set[str] = set() + for node in ast.walk(tree): + if isinstance(node, ast.Attribute) and node.attr.lower() in _ZSET_COMMANDS: + found.add(node.attr.lower()) + elif isinstance(node, ast.Constant) and isinstance(node.value, str): + found.update(c for c in _ZSET_COMMANDS if c in node.value.lower()) + return found + + +def signals(source: str) -> set[str]: + """Which rate-limiter shapes *source* contains (empty set: none).""" + tree = parse_cache.parse(source) + found: set[str] = set() + for node in ast.walk(tree): + if isinstance(node, ast.Dict): + keys = {k.value for k in node.keys if isinstance(k, ast.Constant)} + if {"count", "reset_time"} <= keys: + found.add("counter-dict") + elif isinstance(node, ast.ClassDef) and _LIMITER_CLASS.search(node.name): + found.add("limiter-class") + if _zset_words(tree) >= set(_ZSET_COMMANDS): + found.add("zset-window") + return found + + +def _scan(root: Path, rels: list[str]) -> tuple[dict[str, set[str]], dict[str, str]]: + """Return ``(modules with signals, {module: error})`` for every module that could not be parsed.""" + hits: dict[str, set[str]] = {} + failed: dict[str, str] = {} + for rel in rels: + try: + found = signals((root / rel).read_text(encoding="utf-8")) + except (SyntaxError, UnicodeDecodeError, OSError) as exc: + failed[rel] = f"{type(exc).__name__}: {exc}" + continue + if found: + hits[rel] = found + return hits, failed + + +def _tripping_modules(root: Path) -> dict[str, set[str]]: + hits, failed = _scan(root, REACH.examined(root)) + assert not failed, f"modules the scan could not parse (each counts toward the reach floor): {failed}" + return hits + + +# ---------------------------------------------------------------- the detector itself + +_FORK_COUNTER = """ +import asyncio +MAX_PER_MINUTE = 60 +request_counter = {"count": 0, "reset_time": 0} +_rate_limit_lock = asyncio.Lock() +""" + +_FORK_ZSET = """ +async def check(redis, key, now): + redis.zremrangebyscore(key, 0, now - 60) + redis.zadd(key, dict.fromkeys([str(now)], now)) + return redis.zcard(key) +""" + +_FORK_CLASS = """ +class HomeGrownRateLimiter: + pass +""" + +#: Mentions rate limiting everywhere a regex would catch it, implements nothing: docstring, +#: comment, string, an unrelated dict with a `count` key, a ZSET used for a queue (no trim). +_MENTIONS_ONLY = ''' +"""Calls out to the shared rate limiter; the rate limit counter lives in RateLimiter.""" +from autobot_shared.rate_limiter import RateLimiter # the rate limiter, not a copy + +# rate limit: 60 requests per minute, count and reset_time are tracked elsewhere +MESSAGE = "rate limit exceeded: count, reset_time" +stats = {"count": 0, "name": "requests"} + +def enqueue(redis, key, now): + redis.zadd(key, {"job": now}) + return redis.zcard(key) +''' + + +@pytest.mark.parametrize( + ("source", "expected"), + [(_FORK_COUNTER, "counter-dict"), (_FORK_ZSET, "zset-window"), (_FORK_CLASS, "limiter-class")], +) +def test_each_fork_shape_is_detected(source: str, expected: str) -> None: + assert expected in signals(source) + + +def test_contrast_a_module_that_only_mentions_rate_limiting_is_not_flagged() -> None: + """The contrast to the cases above: same words, no implementation.""" + assert signals(_MENTIONS_ONLY) == set() + + +# ---------------------------------------------------------------- the tree + + +def test_an_unparseable_module_is_reported_not_skipped(tmp_path: Path) -> None: + """Negative control: a broken module must surface as a failure, never silently drop out.""" + (tmp_path / "broken.py").write_text("def (:\n", encoding="utf-8") + (tmp_path / "quiet.py").write_text("x = 1\n", encoding="utf-8") + hits, failed = _scan(tmp_path, ["broken.py", "quiet.py"]) + assert hits == {} + assert list(failed) == ["broken.py"] + + +def test_the_sweep_reaches_the_codebase() -> None: + REACH.verify_floor(REPO_ROOT) + + +def test_the_detector_sees_the_canonical_limiter() -> None: + """Positive control: if this is empty the sweep examined something other than the limiter.""" + assert {"limiter-class", "zset-window"} <= _tripping_modules(REPO_ROOT).get(CANONICAL, set()) + + +def test_no_rate_limiter_implementation_outside_the_canonical_module() -> None: + unexpected = { + rel: sorted(found) + for rel, found in _tripping_modules(REPO_ROOT).items() + if rel != CANONICAL and rel not in DISTINCT_CONCEPTS + } + assert not unexpected, ( + f"second rate-limiter implementation(s): {unexpected}\n" + "Use autobot_shared.rate_limiter.RateLimiter (single window: acquire_window, or " + "rate_limiter_window.WindowQuota; pick window_failure_policy explicitly). If the behaviour is " + "genuinely a different concept, add it to DISTINCT_CONCEPTS with the reason." + ) + + +def test_the_allowlist_has_no_stale_entries() -> None: + """The other half of a ratchet: delete an entry when its module stops tripping or goes away.""" + tripping = _tripping_modules(REPO_ROOT) + stale = sorted(rel for rel in DISTINCT_CONCEPTS if rel not in tripping) + assert not stale, f"DISTINCT_CONCEPTS entries that no longer trip any detector (delete them): {stale}" + + +def test_every_distinct_concept_records_a_reason() -> None: + assert all(len(reason) > 40 for reason in DISTINCT_CONCEPTS.values()) + + +@pytest.mark.parametrize( + "rel", + [ + "autobot-backend/api/git_mcp.py", + "autobot-backend/api/browser_mcp.py", + "autobot-backend/api/database_mcp.py", + "autobot-backend/api/http_client_mcp.py", + ], +) +def test_the_mcp_modules_take_their_quota_from_the_canonical_limiter(rel: str) -> None: + """#18087 AC1: no local counter dict or lock is left behind, and the quota is the canonical one.""" + source = (REPO_ROOT / rel).read_text(encoding="utf-8") + assert "RateLimiter(" in source + assert "_rate_limit_lock" not in source + assert signals(source) == set() + + +def test_integration_limiter_keeps_no_window_of_its_own() -> None: + """#18087/#7271: only header state is distinct; the dual window must stay on the canonical engine.""" + source = (REPO_ROOT / "autobot-backend/integrations/rate_limiter.py").read_text(encoding="utf-8") + assert "LocalWindowCounter" in source + assert "deque" not in source + assert "history" not in source + assert "_prune" not in source diff --git a/repo_tests/reach_scope_claim_17844_test.py b/repo_tests/reach_scope_claim_17844_test.py index 3b282c26e2..0d78e30b88 100644 --- a/repo_tests/reach_scope_claim_17844_test.py +++ b/repo_tests/reach_scope_claim_17844_test.py @@ -72,6 +72,7 @@ import repo_tests.one_paths_filter_job_15360_test as _paths_filter_guard # noqa: F401 -- registers its scope import repo_tests.one_permission_gate_18263_test as _permission_gate_guard # noqa: F401 -- registers its scope import repo_tests.one_playwright_server_18549_test as _playwright_server_guard # noqa: F401 -- registers its scope +import repo_tests.one_rate_limiter_18087_test as _rate_limiter_guard # noqa: F401 -- registers its scope import repo_tests.one_semantic_chunker_14485_test as _semantic_chunker_guard # noqa: F401 -- registers its scope import repo_tests.one_serving_predicate_18820_test as _serving_predicate_guard # noqa: F401 -- registers its scope import repo_tests.one_session_ownership_validator_14016_test as _ownership_validator_guard # noqa: F401 -- registers its scope