Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
16c9f10
refactor(rate-limit): fold IPRateLimiter, the four MCP counters and t…
mrveiss Oct 9, 2026
22cf95e
refactor(rate-limit): guard that no second rate limiter appears outsi…
mrveiss Oct 9, 2026
2326f95
refactor(rate-limit): drop .test_durations entries for the deleted ra…
mrveiss Oct 9, 2026
157e6db
refactor(rate-limit): IntegrationRateLimiter windows ride the canonic…
mrveiss Oct 9, 2026
5120930
fix(integrations): a GitHub rate-limit reset is measured on the wall …
mrveiss Oct 9, 2026
aa2b019
Merge origin/main into issue-18087-rate-limiter-forks; rebase the win…
mrveiss Nov 18, 2026
9d1bd32
Merge remote-tracking branch 'origin/main' into HEAD
mrveiss Nov 18, 2026
7749fb9
refactor(rate-limit): RUM ingest rides the canonical limiter; the IP …
mrveiss Nov 18, 2026
834b9dc
Merge remote-tracking branch 'origin/main' into HEAD
mrveiss Nov 18, 2026
fa08246
fix(rate-limit): the window limiter tests track the canonical limiter…
mrveiss Nov 18, 2026
27c4bd8
fix(rate-limit): RUM rejections do not log per request; drop the dele…
mrveiss Nov 19, 2026
f442228
fix(rate-limit): record the 18087 guard's reach roots (#18087)
mrveiss Nov 19, 2026
507981f
Merge branch 'main' into issue-18087-rate-limiter-forks
mrveiss Nov 19, 2026
63a9dc5
Merge remote-tracking branch 'origin/main' into HEAD
mrveiss Nov 19, 2026
a686121
fix(rate-limit): register the rate-limit env module, one SSOT for pol…
mrveiss Nov 19, 2026
90f3728
Merge remote-tracking branch 'origin/main' into HEAD
mrveiss Nov 19, 2026
570b1e5
Merge branch 'main' into issue-18087-rate-limiter-forks
mrveiss Nov 19, 2026
2b85daf
docs(rate-limit): the rate-limit registry docstring and the guard's p…
mrveiss Nov 19, 2026
933bdbd
Merge remote-tracking branch 'origin/issue-18087-rate-limiter-forks' …
mrveiss Nov 19, 2026
8daf2b5
Merge branch 'main' into issue-18087-rate-limiter-forks
mrveiss Nov 20, 2026
d2ede48
fix(rate-limit): bound local window keys, keep longer provider pause,…
mrveiss Nov 20, 2026
bf75ed8
Merge branch 'main' into issue-18087-rate-limiter-forks
mrveiss Nov 20, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 0 additions & 10 deletions .test_durations
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
49 changes: 18 additions & 31 deletions autobot-backend/a2a/a2a_security_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -301,35 +301,27 @@ 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):
from unittest.mock import AsyncMock, patch

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

Expand All @@ -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


# ---------------------------------------------------------------------------
Expand Down
19 changes: 10 additions & 9 deletions autobot-backend/api/a2a.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
)


Expand Down
20 changes: 11 additions & 9 deletions autobot-backend/api/openai_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
)


Expand Down
31 changes: 17 additions & 14 deletions autobot-backend/api/openai_compat_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
18 changes: 11 additions & 7 deletions autobot-backend/api/rum_ingest_bounds.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
Loading
Loading