Skip to content

refactor(mcp): four copy-paste rate limiters should fold into the canonical RateLimiter #18087

Closed
1 of 1 issue completed

Description

@mrveiss

Summary

check_rate_limit has five definitions. Four are copy-paste — structurally identical in-process fixed-window limiters in the MCP API modules — and the canonical autobot_shared.rate_limiter.RateLimiter they should use already exists and is already used by api/secrets.py.

Found while retiring symbol-fork clusters under #12771. Deliberately not folded into #18082: that PR is mechanical renames, and this is a behaviour-changing migration of security-adjacent code. Different risk class, so it gets its own review.

The four

module counter limit constant
api/git_mcp.py:242 git_counter MAX_GIT_OPS_PER_MINUTE
api/browser_mcp.py:181 request_counter MAX_REQUESTS_PER_MINUTE
api/database_mcp.py:252 query_counter MAX_QUERIES_PER_MINUTE
api/http_client_mcp.py:298 request_counter MAX_REQUESTS_PER_MINUTE

Each is the same function with a different dict name, a different constant and differently-worded logging:

async with _rate_limit_lock:
    now = now_utc()
    elapsed = (now - <counter>["reset_time"]).total_seconds()
    if elapsed >= 60:
        <counter>["count"] = 0
        <counter>["reset_time"] = now
    if <counter>["count"] >= <MAX>:
        logger.warning(...)
        return False
    <counter>["count"] += 1
    return True

The fifth, api/secrets.py:522, is a different signature ((request) -> None, raises) and already delegates to the canonical limiter — it is the model to follow, not another fork.

This is the documented consolidation target

RateLimiter.acquire_window's own docstring records that it already absorbed three forks:

Generalizes the fixed minute/hour windows above to a caller-chosen window_seconds — folded in from agents/web_researcher.py, security/threat_intelligence.py and api/secrets.py (Issue #12646), each of which used one configurable window rather than the dual minute/hour scheme.

So these four are the next four, and the pattern is proven on a more sensitive surface than MCP.

Two behaviour changes a reviewer must sign off, not wave through

  1. Per-process → cross-process. The dict counters are per worker, so with N workers the effective limit is N× the intended one. Migrating makes the limit global. That is a fix, but it will look like a tightening to anyone who tuned the constants against observed behaviour.

  2. Fails closed → fails open. The dict counter always enforces. _try_acquire_window returns (True, 0.0) when Redis is unavailable, which its docstring states is the deliberate "graceful-degradation policy used everywhere else in this class". For git, database, http_client and browser MCP operations, a Redis outage would therefore remove rate limiting entirely.

Point 2 is the one that needs a decision rather than a migration. The house policy is fail-open and api/secrets.py already accepts it; whether MCP write operations should is a separate judgement, and if the answer is no then the canonical limiter needs a fail-closed option rather than these four keeping their own implementations.

Acceptance criteria

  • The four MCP modules obtain rate limiting from autobot_shared.rate_limiter.RateLimiter, with no local counter dict or lock left behind
  • A recorded decision on fail-open vs fail-closed for MCP operations, with a fail-closed option added to the canonical limiter if that is the answer
  • A test pinning the cross-process behaviour, so the per-worker multiplication cannot come back
  • check_rate_limit removed from repo_tests/symbol_fork_baseline.json (one definition left, in api/secrets.py)

Activity

  1. mrveiss commented on Oct 9, 2026

    @mrveiss
    OwnerAuthor

    Owner decision (2026-10-10): the four MCP limiters (git, browser, database, http_client) and the session password-change limiter count globally across workers, keeping the configured numbers. Before, each worker counted separately, so with N workers the effective limit becomes 1/N of what it was; that is the intended reading of the configured value, and it is the security-correct one for the password limiter. If MCP tools throttle too early under load, raise the env-backed limits; do not go back to per-worker counting. While Redis is unreachable these callers fall back to per-worker counting (WindowFailurePolicy.LOCAL) and do not fail open.

  2. mrveiss commented on Oct 16, 2026

    @mrveiss
    OwnerAuthor

    Verdict pass (read-only, origin/main 84faf18)

    • Canonical: autobot_shared/rate_limiter.py RateLimiter (12 prod importers; acquire_window is a Lua window that doesn't record rejects).
    • Fork: autobot_shared/rate_limit.py IPRateLimiter (3 importers) records rejects (ZADD before ZCARD, so the window extends) and falls back to an enforcing in-process window when Redis is down, where the canonical fails open. It is to be absorbed, then removed (under refactor: consolidate 4+ in-process rate-limit implementations into autobot_shared/rate_limit.py #7271).
    • This issue's scope is 6 MIGRATEs, not 4: the 4 MCP copies (git_mcp.py, browser_mcp.py, database_mcp.py, http_client_mcp.py), plus api/auth.py:79 and mcp_server/autobot_server.py:144 (_TokenBucket), which the audit missed. All are in-process per-worker dicts with literal limits and one global key each.
    • Prerequisite (slice S1): the canonical gains a failure policy (OPEN default / LOCAL fallback / CLOSED) and an env-backed 429 helper. It's behaviour-neutral for current callers. Migrating auth-adjacent limiters without it would make them fail open on a Redis outage.
    • Visible change to decide: per-worker counts become one global count, so the effective limit tightens by about the worker count unless the limits are rescaled. Owner decision pending.
    • No guard exists against hand-rolled limiters (symbol_forks only catches same-name functions); an AST guard is the last slice.
  3. mrveiss commented on Oct 16, 2026

    @mrveiss
    OwnerAuthor

    Owner decisions (2026-10-16): (1) after migration the limits are global at the currently configured values, so the effective limit tightens by about the worker count. The values become env-backed so they can be raised. (2) When Redis is down, security-relevant limiters (auth, password change, MCP tool calls) fail open, the canonical RateLimiter behaviour. No LOCAL/CLOSED policy is needed for these six.

  4. mrveiss commented on Oct 16, 2026

    @mrveiss
    OwnerAuthor

    Merged via #18616 in train 21 (#18619 → main 5f2c667). Evidence on origin/main:

    • AC1, ticked: git_mcp.py, browser_mcp.py, database_mcp.py and http_client_mcp.py each construct the canonical RateLimiter( (1 hit each), with no local counter state; utils/thread_safety_test.py asserts the latter per module.
    • AC3, ticked: autobot-backend/api/mcp_rate_limits_18087_test.py:140 test_two_workers_share_one_count and :166 test_password_change_limit_is_global_and_429_text_unchanged.
    • AC4, ticked: check_rate_limit is no longer in repo_tests/symbol_fork_baseline.json (only api/secrets.py still defines one).
    • AC2, NOT ticked as written: the decision IS recorded (owner, 2026-10-16, comment above): these limiters fail open, the canonical behaviour. But no fail-closed option was added to the canonical, because the owner chose fail-open, so the AC's second half doesn't apply. Leaving it unticked rather than ticking a different thing; the owner can strike it.
  5. mrveiss commented on Nov 6, 2026

    @mrveiss
    OwnerAuthor

    Reopened 2026-11-06 (maintainer decision: a closed issue whose work is not on main gets reopened). The rate-limiter fold from local branch issue-18087-rate-limiter-forks is not on main. The pending hunks are listed on umbrella #7271: #7271 (comment). Redo it on current main by hunk picks; never revive the branch whole-file.

  6. reopened this on Nov 6, 2026
  7. 10 remaining items

  8. added a commit that references this issue on Nov 20, 2026
  9. github-actions commented on Nov 20, 2026

    @github-actions
    Contributor

    Landed in #21823, merge bcd41c623d

  10. mrveiss commented on Nov 20, 2026

    @mrveiss
    OwnerAuthor

    Closure pass after #21823 merged (merge bcd41c623d). Verified against origin/main:

    • AC1 ✔ (already ticked): the MCP bridges use the canonical RateLimiter.
    • AC3 ✔ / AC4 ✔ (already ticked): unchanged by this check.
    • AC2 stays unticked. The fail-closed option now exists: WindowFailurePolicy.FAIL_CLOSED in autobot_shared/rate_limiter.py (~L498), alongside FAIL_OPEN (the default) and LOCAL. The MCP bridges still run on the default and fail open; docs/developer/ENV_VARS.md:371-375 say "Fails open while Redis is unreachable". No recorded sign-off on fail-open vs fail-closed for MCP operations exists, and this criterion requires one.

    Decision needed (owner):

    • A. Keep fail-open for MCP (current behaviour; recommended for availability). Record the decision here and the AC is met.
    • B. Fail-closed for MCP (deny during a Redis outage). This needs a small PR setting FAIL_CLOSED on the five MCP limiters and updating ENV_VARS.md.

    Follow-up from review: #21907 (eviction-sweep throttle).

  11. added
    needs-decisionBlocked on an owner decision; options and a recommendation are on the issue
    on Nov 20, 2026
  12. mrveiss commented on Nov 20, 2026

    @mrveiss
    OwnerAuthor

    Owner decision (2026-11-21): MCP operations keep FAIL-OPEN while Redis is unreachable. Behaviour on main already matches: the five MCP limiters use the default WindowFailurePolicy.FAIL_OPEN, documented in docs/developer/ENV_VARS.md:371-375. A fail-closed option exists (WindowFailurePolicy.FAIL_CLOSED, autobot_shared/rate_limiter.py) if this is revisited. AC2 is met. All four ACs are verified, so closing as completed via #21823 (merge bcd41c623d). #21907 (hardening) stays open on its own.

  13. removed
    needs-decisionBlocked on an owner decision; options and a recommendation are on the issue
    on Nov 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    backendneeds-structureMissing goal milestone, matching phase label or native parent (#19522)phase:M4.9One definition per concepttech-debt

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions