Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(searxng): keep the rate-limit lock and timestamp in one tracked entry (#5688)

Ehsan37394d3c0bc6
diff --git a/changelog.d/5669.bugfix.md b/changelog.d/5669.bugfix.md
new file mode 100644
index 0000000000..156c7c1789
--- /dev/null
+++ b/changelog.d/5669.bugfix.md
@@ -0,0 +1 @@
+The SearXNG rate limiter now keeps each URL's lock and its last-request time in one tracked entry, so a URL evicted while one of its requests is still in flight can no longer leave its timestamp behind. Tracked state is now bounded by `MAX_TRACKED_URLS` as the module documented, rather than only the locks being bounded.
diff --git a/src/local_deep_research/web_search_engines/engines/_searxng_rate_limiter.py b/src/local_deep_research/web_search_engines/engines/_searxng_rate_limiter.py
index 23b25c18a4..64916600ed 100644
--- a/src/local_deep_research/web_search_engines/engines/_searxng_rate_limiter.py
+++ b/src/local_deep_research/web_search_engines/engines/_searxng_rate_limiter.py
@@ -14,22 +14,31 @@ The locking pattern mirrors other per-key locks in the codebase
per-URL lock, and that per-URL lock guards updates to the timestamp.
Note on memory:
-`_url_locks` and `_url_last_request` are bounded to a maximum capacity
-(`MAX_TRACKED_URLS`). When capacity is reached, stale/least-recently-used
-entries are evicted under `_meta_lock`.
+`_url_state` is bounded to a maximum capacity (`MAX_TRACKED_URLS`). When
+capacity is reached, stale/least-recently-used entries are evicted under
+`_meta_lock`.
"""
import threading
import time
+from dataclasses import dataclass, field
from ...security import redact_url_for_log
from ...security.secure_logging import logger
MAX_TRACKED_URLS = 1000
+
+@dataclass
+class _UrlState:
+ """Lock for one tracked URL, and when it was last requested."""
+
+ lock: threading.Lock = field(default_factory=threading.Lock)
+ last_request: float = 0.0 # monotonic; 0.0 means "no request yet"
+
+
_meta_lock = threading.Lock()
-_url_locks: dict[str, threading.Lock] = {}
-_url_last_request: dict[str, float] = {}
+_url_state: dict[str, _UrlState] = {}
def _normalize_url(url: str) -> str:
@@ -47,44 +56,46 @@ def _evict_stale_locks_unlocked() -> None:
``MAX_TRACKED_URLS`` until one is released.
``locked()`` is not a complete answer, and this function does not make it
- one. ``respect_rate_limit`` fetches its lock from ``_get_url_lock`` under
- ``_meta_lock`` and acquires it afterwards, so between those two steps the
- object reports ``locked() == False`` and stays evictable. A URL evicted in
- that window loses its timestamp and skips one delay. The window is narrower
- than the one this check closes, which spans ``time.sleep(wait_time)``, and
- closing it as well would mean holding ``_meta_lock`` across the sleep.
+ one. ``respect_rate_limit`` fetches its state from ``_get_url_state`` under
+ ``_meta_lock`` and acquires the lock afterwards, so between those two steps
+ the object reports ``locked() == False`` and stays evictable. A URL evicted
+ in that window loses its timestamp and skips one delay. The window is
+ narrower than the one this check closes, which spans
+ ``time.sleep(wait_time)``, and closing it as well would mean holding
+ ``_meta_lock`` across the sleep.
Must be called while holding ``_meta_lock``.
"""
- if len(_url_locks) < MAX_TRACKED_URLS:
+ if len(_url_state) < MAX_TRACKED_URLS:
return
- evictable = [url for url, lock in _url_locks.items() if not lock.locked()]
+ evictable = [
+ url for url, state in _url_state.items() if not state.lock.locked()
+ ]
if not evictable:
logger.warning(
- f"SearXNG rate limiter: all {len(_url_locks)} tracked URL locks "
+ f"SearXNG rate limiter: all {len(_url_state)} tracked URL locks "
"are in use, so none can be evicted at capacity"
)
return
- # Remove oldest half of entries based on _url_last_request timestamp
- sorted_urls = sorted(evictable, key=lambda u: _url_last_request.get(u, 0.0))
+ # Remove oldest half of entries based on their last_request timestamp
+ sorted_urls = sorted(evictable, key=lambda u: _url_state[u].last_request)
to_remove = sorted_urls[: max(1, len(sorted_urls) // 2)]
for url in to_remove:
- _url_locks.pop(url, None)
- _url_last_request.pop(url, None)
+ _url_state.pop(url, None)
-def _get_url_lock(normalized_url: str) -> threading.Lock:
- """Return the per-URL lock, creating it lazily.
+def _get_url_state(normalized_url: str) -> _UrlState:
+ """Return the per-URL state, creating it lazily.
Expects an already normalized URL string.
"""
with _meta_lock:
- lock = _url_locks.get(normalized_url)
- if lock is None:
+ state = _url_state.get(normalized_url)
+ if state is None:
_evict_stale_locks_unlocked()
- lock = threading.Lock()
- _url_locks[normalized_url] = lock
- return lock
+ state = _UrlState()
+ _url_state[normalized_url] = state
+ return state
def respect_rate_limit(instance_url: str, delay_seconds: float) -> None:
@@ -99,10 +110,10 @@ def respect_rate_limit(instance_url: str, delay_seconds: float) -> None:
return
normalized_url = _normalize_url(instance_url)
- lock = _get_url_lock(normalized_url)
- with lock:
+ state = _get_url_state(normalized_url)
+ with state.lock:
now = time.monotonic()
- last = _url_last_request.get(normalized_url, 0.0)
+ last = state.last_request
elapsed = now - last
if last > 0 and elapsed < delay_seconds:
wait_time = delay_seconds - elapsed
@@ -111,11 +122,11 @@ def respect_rate_limit(instance_url: str, delay_seconds: float) -> None:
)
time.sleep(wait_time)
now = time.monotonic()
- _url_last_request[normalized_url] = now
+ # Attribute write on a held reference: an evicted entry stays evicted.
+ state.last_request = now
def reset_for_tests() -> None:
"""Clear all tracked state. Intended for unit tests only."""
with _meta_lock:
- _url_locks.clear()
- _url_last_request.clear()
+ _url_state.clear()
diff --git a/tests/web_search_engines/engines/test_search_engine_searxng.py b/tests/web_search_engines/engines/test_search_engine_searxng.py
index a54faf26c5..3c3d5e8f0a 100644
--- a/tests/web_search_engines/engines/test_search_engine_searxng.py
+++ b/tests/web_search_engines/engines/test_search_engine_searxng.py
@@ -399,14 +399,12 @@ class TestRateLimiting:
)
_searxng_rate_limiter.respect_rate_limit("http://localhost:8080", 0.5)
- assert "http://localhost:8080" in _searxng_rate_limiter._url_locks
- assert (
- "http://localhost:8080" in _searxng_rate_limiter._url_last_request
- )
+ state = _searxng_rate_limiter._url_state.get("http://localhost:8080")
+ assert state is not None
+ assert state.last_request > 0
_searxng_rate_limiter.reset_for_tests()
- assert len(_searxng_rate_limiter._url_locks) == 0
- assert len(_searxng_rate_limiter._url_last_request) == 0
+ assert len(_searxng_rate_limiter._url_state) == 0
def test_no_rate_limit_when_delay_is_zero_or_negative(self):
"""Delay of 0 or negative returns immediately without populating tracked state."""
@@ -435,8 +433,7 @@ class TestRateLimiting:
mock_sleep.assert_not_called()
_searxng_rate_limiter.respect_rate_limit("http://localhost:8080", -1.0)
- assert len(_searxng_rate_limiter._url_locks) == 0
- assert len(_searxng_rate_limiter._url_last_request) == 0
+ assert len(_searxng_rate_limiter._url_state) == 0
def test_rate_limit_shared_across_instances(self):
"""Two engines on the same URL share the rate-limit timestamp in global state."""
@@ -464,10 +461,10 @@ class TestRateLimiting:
with patch("time.sleep") as mock_sleep:
first._respect_rate_limit()
- initial_ts = _searxng_rate_limiter._url_last_request.get(
+ initial_ts = _searxng_rate_limiter._url_state[
"http://localhost:8080"
- )
- assert initial_ts is not None
+ ].last_request
+ assert initial_ts > 0
second._respect_rate_limit()
# Second call should have slept the configured delay because
@@ -476,9 +473,9 @@ class TestRateLimiting:
sleep_arg = mock_sleep.call_args.args[0]
assert 0 < sleep_arg <= 0.5
- second_ts = _searxng_rate_limiter._url_last_request.get(
+ second_ts = _searxng_rate_limiter._url_state[
"http://localhost:8080"
- )
+ ].last_request
assert second_ts >= initial_ts
def test_rate_limit_isolated_per_instance_url(self):
@@ -558,12 +555,12 @@ class TestRateLimiting:
f"http://localhost:808{i}", 0.1
)
- assert len(_searxng_rate_limiter._url_locks) == 4
+ assert len(_searxng_rate_limiter._url_state) == 4
# Adding a 5th URL should trigger eviction of older entries
_searxng_rate_limiter.respect_rate_limit("http://localhost:8084", 0.1)
- assert len(_searxng_rate_limiter._url_locks) <= 3
- assert "http://localhost:8084" in _searxng_rate_limiter._url_locks
+ assert len(_searxng_rate_limiter._url_state) <= 3
+ assert "http://localhost:8084" in _searxng_rate_limiter._url_state
def test_eviction_skips_a_lock_another_thread_holds(self, monkeypatch):
"""The oldest entry is held, so eviction must move on to the next one."""
@@ -580,7 +577,8 @@ class TestRateLimiting:
)
held_url = "http://localhost:8080"
- held_lock = _searxng_rate_limiter._url_locks[held_url]
+ held_state = _searxng_rate_limiter._url_state[held_url]
+ held_lock = held_state.lock
acquired = threading.Event()
release = threading.Event()
@@ -596,9 +594,9 @@ class TestRateLimiting:
_searxng_rate_limiter.respect_rate_limit(
"http://localhost:8084", 0.1
)
- assert _searxng_rate_limiter._url_locks.get(held_url) is held_lock
+ assert _searxng_rate_limiter._url_state.get(held_url) is held_state
assert (
- "http://localhost:8081" not in _searxng_rate_limiter._url_locks
+ "http://localhost:8081" not in _searxng_rate_limiter._url_state
)
finally:
release.set()
@@ -624,7 +622,7 @@ class TestRateLimiting:
release = threading.Event()
def holder(url):
- with _searxng_rate_limiter._url_locks[url]:
+ with _searxng_rate_limiter._url_state[url].lock:
all_acquired.wait(10)
release.wait(10)
@@ -636,14 +634,64 @@ class TestRateLimiting:
_searxng_rate_limiter.respect_rate_limit(
"http://localhost:8084", 0.1
)
- assert len(_searxng_rate_limiter._url_locks) == 5
+ assert len(_searxng_rate_limiter._url_state) == 5
for url in urls:
- assert url in _searxng_rate_limiter._url_locks
+ assert url in _searxng_rate_limiter._url_state
finally:
release.set()
for thread in threads:
thread.join(10)
+ def test_eviction_mid_call_leaves_no_tracked_entry_behind(
+ self, monkeypatch
+ ):
+ """A URL evicted while its call is in flight stays evicted."""
+ import threading
+ from local_deep_research.web_search_engines.engines import (
+ _searxng_rate_limiter,
+ )
+
+ monkeypatch.setattr(_searxng_rate_limiter, "MAX_TRACKED_URLS", 4)
+
+ victim = "http://localhost:8080"
+ real_get_url_state = _searxng_rate_limiter._get_url_state
+ in_window = threading.Event()
+ resume = threading.Event()
+
+ def park_inside_the_window(normalized_url):
+ state = real_get_url_state(normalized_url)
+ if normalized_url == victim:
+ in_window.set()
+ resume.wait(10)
+ return state
+
+ monkeypatch.setattr(
+ _searxng_rate_limiter, "_get_url_state", park_inside_the_window
+ )
+ caller = threading.Thread(
+ target=_searxng_rate_limiter.respect_rate_limit,
+ args=(victim, 0.1),
+ )
+ caller.start()
+ try:
+ assert in_window.wait(10)
+ # The victim holds no lock yet and has no timestamp, so eviction
+ # both admits it and sorts it oldest.
+ for i in range(1, 6):
+ _searxng_rate_limiter.respect_rate_limit(
+ f"http://localhost:808{i}", 0.1
+ )
+ assert victim not in _searxng_rate_limiter._url_state
+ finally:
+ resume.set()
+ caller.join(10)
+
+ assert victim not in _searxng_rate_limiter._url_state
+ assert (
+ len(_searxng_rate_limiter._url_state)
+ <= _searxng_rate_limiter.MAX_TRACKED_URLS
+ )
+
def test_rate_limit_multithreaded(self):
"""Multiple threads invoking respect_rate_limit concurrently are properly serialized."""
import concurrent.futures