"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(rate-limiter): remove unused import, guard against non-positive max
santhreal2dad0e7769aa
diff --git a/agent/src/api/system_routes.py b/agent/src/api/system_routes.pyindex 30e52b2f6..5d7f23021 100644--- a/agent/src/api/system_routes.py+++ b/agent/src/api/system_routes.py@@ -10,7 +10,7 @@ import osimport signalimport threadingimport time-from collections import defaultdict, deque+from collections import dequefrom datetime import datetime, timezonefrom typing import Deque, Dict, Optional, Tuple@@ -71,19 +71,50 @@ class _SlidingWindowRateLimiter:def __init__(self, max_requests: int, window_seconds: float) -> None:self._max = max_requestsself._window = window_seconds- self._hits: Dict[str, Deque[float]] = defaultdict(deque)+ self._hits: Dict[str, Deque[float]] = {}self._lock = threading.Lock()+ self._last_sweep: float = 0.0++ def _sweep_expired_locked(self, cutoff: float) -> None:+ """Drop buckets whose entries have all expired. Caller holds the lock."""+ stale_keys = [+ k for k, b in self._hits.items()+ if not b or b[0] < cutoff+ ]+ for k in stale_keys:+ # Pop expired entries; if the bucket is empty, remove it.+ b = self._hits[k]+ while b and b[0] < cutoff:+ b.popleft()+ if not b:+ del self._hits[k]def allow(self, key: str) -> bool:"""Record a hit for ``key`` and report whether it stays within budget."""now = time.monotonic()cutoff = now - self._windowwith self._lock:- bucket = self._hits[key]- while bucket and bucket[0] < cutoff:- bucket.popleft()- if len(bucket) >= self._max:+ if self._max <= 0:return False+ # Periodic sweep: clean up expired buckets so keys that were+ # accessed once and never again do not accumulate without bound.+ # Throttled to once per window to avoid sweeping on every call.+ if now - self._last_sweep >= self._window:+ self._sweep_expired_locked(cutoff)+ self._last_sweep = now++ bucket = self._hits.get(key)+ if bucket is not None:+ while bucket and bucket[0] < cutoff:+ bucket.popleft()+ if len(bucket) >= self._max:+ return False+ if not bucket:+ del self._hits[key]+ bucket = None+ if bucket is None:+ bucket = deque()+ self._hits[key] = bucketbucket.append(now)return Truediff --git a/agent/tests/test_rate_limiter_memory.py b/agent/tests/test_rate_limiter_memory.pynew file mode 100644index 000000000..452a25cb1--- /dev/null+++ b/agent/tests/test_rate_limiter_memory.py@@ -0,0 +1,109 @@+"""Regression: _SlidingWindowRateLimiter must not leak memory on unique keys.++The limiter keys on client IP. A burst of unique IPs (a scan, a botnet, a+proxy farm) creates one deque per IP in ``_hits``. The original code used+``defaultdict(deque)``, which creates an empty deque on every lookup — even+for a key that is immediately rejected — and never removes empty buckets.+Over time ``_hits`` grows without bound.++The fix: use a plain dict, and delete a bucket once all its entries expire.+"""++from __future__ import annotations++import time++from src.api.system_routes import _SlidingWindowRateLimiter+++def test_allows_within_budget() -> None:+ limiter = _SlidingWindowRateLimiter(max_requests=3, window_seconds=60.0)+ assert limiter.allow("1.2.3.4") is True+ assert limiter.allow("1.2.3.4") is True+ assert limiter.allow("1.2.3.4") is True+++def test_denies_over_budget() -> None:+ limiter = _SlidingWindowRateLimiter(max_requests=2, window_seconds=60.0)+ limiter.allow("1.2.3.4")+ limiter.allow("1.2.3.4")+ assert limiter.allow("1.2.3.4") is False+++def test_unique_keys_do_not_grow_hits_dict() -> None:+ """A burst of unique IPs must not leave empty buckets behind."""+ limiter = _SlidingWindowRateLimiter(max_requests=1, window_seconds=60.0)+ for i in range(1000):+ limiter.allow(f"10.0.0.{i}")+ # Each IP hit the limiter once (allowed), so each has a bucket with 1+ # entry. That is expected — the buckets are still within their window.+ # The leak we are guarding against is *empty* buckets surviving after+ # eviction.+ assert len(limiter._hits) == 1000+++def test_empty_buckets_are_evicted_after_window_expires() -> None:+ """After the window expires, buckets with no surviving entries are removed."""+ limiter = _SlidingWindowRateLimiter(max_requests=5, window_seconds=0.05)+ limiter.allow("1.2.3.4")+ limiter.allow("5.6.7.8")+ assert len(limiter._hits) == 2++ time.sleep(0.06)++ # A new key triggers cleanup of expired buckets.+ limiter.allow("9.10.11.12")+ # The two old buckets had all entries expire and should be gone.+ assert "1.2.3.4" not in limiter._hits+ assert "5.6.7.8" not in limiter._hits+ # The new key's bucket is present.+ assert "9.10.11.12" in limiter._hits+++def test_over_limit_key_with_expired_entries_is_cleaned() -> None:+ """A key that was over-limit but whose entries have all expired is dropped."""+ limiter = _SlidingWindowRateLimiter(max_requests=1, window_seconds=0.05)+ assert limiter.allow("1.2.3.4") is True+ assert limiter.allow("1.2.3.4") is False # over limit++ time.sleep(0.06)++ # The next call should clean the expired bucket and allow the request.+ assert limiter.allow("1.2.3.4") is True+++def test_reset_clears_all_buckets() -> None:+ limiter = _SlidingWindowRateLimiter(max_requests=5, window_seconds=60.0)+ limiter.allow("1.2.3.4")+ limiter.allow("5.6.7.8")+ assert len(limiter._hits) == 2+ limiter.reset()+ assert len(limiter._hits) == 0+++def test_no_defaultdict_side_effect_on_lookup() -> None:+ """Looking up a never-seen key must not create an empty bucket.++ The old ``defaultdict(deque)`` created a bucket on every ``self._hits[key]``+ access — even when the key was immediately rejected. The plain-dict fix+ must not exhibit this behaviour.+ """+ limiter = _SlidingWindowRateLimiter(max_requests=1, window_seconds=60.0)+ # Access the internal dict directly to simulate a lookup side effect.+ _ = limiter._hits.get("never-seen")+ assert "never-seen" not in limiter._hits++++def test_zero_limit_denies_all_requests() -> None:+ """A limiter with max_requests=0 must deny every request without creating a bucket."""+ limiter = _SlidingWindowRateLimiter(max_requests=0, window_seconds=60.0)+ assert limiter.allow("1.2.3.4") is False+ assert "1.2.3.4" not in limiter._hits+++def test_negative_limit_denies_all_requests() -> None:+ """A limiter with a negative max must deny every request."""+ limiter = _SlidingWindowRateLimiter(max_requests=-1, window_seconds=60.0)+ assert limiter.allow("1.2.3.4") is False+ assert "1.2.3.4" not in limiter._hits\ No newline at end of file