~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(searxng): share SearXNG rate-limit state across per-call engine instances (#5353)
S0e36e006d361
diff --git a/changelog.d/5351.bugfix.md b/changelog.d/5351.bugfix.mdnew file mode 100644index 0000000000..198274d5c9--- /dev/null+++ b/changelog.d/5351.bugfix.md@@ -0,0 +1 @@+SearXNG search engine rate limiting (`delay_between_requests`) is now shared process-wide per instance URL, ensuring request throttling applies across per-call engine instances constructed during research agent tool calls.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.pynew file mode 100644index 0000000000..677c0e47ef--- /dev/null+++ b/src/local_deep_research/web_search_engines/engines/_searxng_rate_limiter.py@@ -0,0 +1,102 @@+"""Shared rate limiter for SearXNG engine instances.++The research agent constructs a fresh `SearXNGSearchEngine` for every+tool call, so the previous per-instance `last_request_time` only+throttled requests on engines that were explicitly reused (for example+the shared engine used by `JournalReputationFilter` for Tier 4). This+module provides a process-wide tracker keyed by SearXNG ``instance_url``+so the configured ``delay_between_requests`` actually applies across+per-call engine instances.++The locking pattern mirrors other per-key locks in the codebase+(see ``database/backup/backup_service.py`` and+``database/encrypted_db.py``): a meta-lock guards lazy creation of a+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`.+"""++import threading+import time++from ...security import redact_url_for_log+from ...security.secure_logging import logger++MAX_TRACKED_URLS = 1000++_meta_lock = threading.Lock()+_url_locks: dict[str, threading.Lock] = {}+_url_last_request: dict[str, float] = {}+++def _normalize_url(url: str) -> str:+ """Normalize instance URL for keying rate limits."""+ return url.rstrip("/")+++def _evict_stale_locks_unlocked() -> None:+ """Evict oldest entries when tracked URLs reach capacity.++ Must be called while holding ``_meta_lock``.+ """+ if len(_url_locks) < MAX_TRACKED_URLS:+ return+ # Remove oldest half of entries based on _url_last_request timestamp+ sorted_urls = sorted(+ _url_locks.keys(), key=lambda u: _url_last_request.get(u, 0.0)+ )+ 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)+++def _get_url_lock(normalized_url: str) -> threading.Lock:+ """Return the per-URL lock, creating it lazily.++ Expects an already normalized URL string.+ """+ with _meta_lock:+ lock = _url_locks.get(normalized_url)+ if lock is None:+ _evict_stale_locks_unlocked()+ lock = threading.Lock()+ _url_locks[normalized_url] = lock+ return lock+++def respect_rate_limit(instance_url: str, delay_seconds: float) -> None:+ """Ensure at least ``delay_seconds`` have passed since the previous call+ for this ``instance_url`` (does not wait on the first call for a URL).++ A ``delay_seconds`` of ``0`` (or less) returns immediately without+ touching the tracker, preserving the prior "no throttling" behavior+ when the user has not configured any delay.+ """+ if delay_seconds <= 0:+ return++ normalized_url = _normalize_url(instance_url)+ lock = _get_url_lock(normalized_url)+ with lock:+ now = time.monotonic()+ last = _url_last_request.get(normalized_url, 0.0)+ elapsed = now - last+ if last > 0 and elapsed < delay_seconds:+ wait_time = delay_seconds - elapsed+ logger.info(+ f"SearXNG rate limiting: waiting {wait_time:.2f}s for instance {redact_url_for_log(normalized_url)}"+ )+ time.sleep(wait_time)+ now = time.monotonic()+ _url_last_request[normalized_url] = 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()diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py b/src/local_deep_research/web_search_engines/engines/search_engine_searxng.pyindex fe4360efae..c54c9d03f1 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py@@ -1,7 +1,5 @@import enumimport json-import threading-import timefrom typing import Any, Dict, List, Optionalimport requests@@ -12,6 +10,7 @@ from ...security.safe_requests import safe_getfrom ..search_engine_base import BaseSearchEngine, Exposure, Sensitivityfrom ...security.secure_logging import logger+from ._searxng_rate_limiter import respect_rate_limit@enum.unique@@ -222,28 +221,16 @@ class SearXNGSearchEngine(BaseSearchEngine):safe_search=self.safe_search.value,)- self.last_request_time: float = 0.0- self._rate_limit_lock = threading.Lock()-def _respect_rate_limit(self):"""Apply self-imposed rate limiting between requests.- Holding ``_rate_limit_lock`` across ``time.sleep`` strictly serializes- concurrent searches on the same engine instance by ``delay_between_requests``- to enforce rate-limiting boundaries.+ Rate-limit state is shared across all `SearXNGSearchEngine`+ instances targeting the same ``instance_url`` (see+ ``_searxng_rate_limiter.py``) so the configured delay applies+ even when the research agent constructs a fresh engine for+ every tool call."""- with self._rate_limit_lock:- current_time = time.time()- time_since_last_request = current_time - self.last_request_time-- if time_since_last_request < self.delay_between_requests:- wait_time = (- self.delay_between_requests - time_since_last_request- )- logger.info(f"Rate limiting: waiting {wait_time:.2f} seconds")- time.sleep(wait_time)-- self.last_request_time = time.time()+ respect_rate_limit(self.instance_url, self.delay_between_requests)def _get_search_results(self, query: str, max_results: Optional[int] = Nonediff --git a/tests/search_engines/test_search_engine_searxng.py b/tests/search_engines/test_search_engine_searxng.pyindex 84b06d7e15..e6d5f8dea6 100644--- a/tests/search_engines/test_search_engine_searxng.py+++ b/tests/search_engines/test_search_engine_searxng.py@@ -298,6 +298,17 @@ class TestSearXNGSearchExecution:class TestSearXNGRateLimiting:"""Tests for SearXNG rate limiting."""+ @pytest.fixture(autouse=True)+ def auto_reset_rate_limiter(self):+ """Automatically reset rate limiter state before and after each test."""+ from local_deep_research.web_search_engines.engines import (+ _searxng_rate_limiter,+ )++ _searxng_rate_limiter.reset_for_tests()+ yield+ _searxng_rate_limiter.reset_for_tests()+@pytest.fixture(autouse=True)def mock_safe_get(self, monkeypatch):"""Mock safe_get to avoid HTTP requests."""@@ -327,16 +338,6 @@ class TestSearXNGRateLimiting:engine = SearXNGSearchEngine(delay_between_requests=2.5)assert engine.delay_between_requests == 2.5- def test_last_request_time_initialized(self):- """Test that last_request_time is initialized."""- from local_deep_research.web_search_engines.engines.search_engine_searxng import (- SearXNGSearchEngine,- )-- engine = SearXNGSearchEngine()- assert hasattr(engine, "last_request_time")- assert engine.last_request_time == 0-class TestSearXNGStaticMethods:"""Tests for SearXNG static methods."""@@ -870,41 +871,53 @@ class TestSearXNGRateLimitMethod:Mock(return_value=mock_response),)- def test_respect_rate_limit_updates_time(self, monkeypatch):- """Test that _respect_rate_limit updates last_request_time."""+ def test_respect_rate_limit_delegates_to_shared_limiter(self):+ """Test that _respect_rate_limit delegates to the shared rate limiter."""+ from unittest.mock import patch+ from local_deep_research.web_search_engines.engines import (+ _searxng_rate_limiter,+ )from local_deep_research.web_search_engines.engines.search_engine_searxng import (SearXNGSearchEngine,)- engine = SearXNGSearchEngine(delay_between_requests=0)- engine.last_request_time = 0+ _searxng_rate_limiter.reset_for_tests()+ engine = SearXNGSearchEngine(+ instance_url="http://localhost:8080",+ delay_between_requests=0.5,+ )- engine._respect_rate_limit()+ with patch("time.sleep") as mock_sleep:+ engine._respect_rate_limit()+ engine._respect_rate_limit()- assert engine.last_request_time > 0+ mock_sleep.assert_called_once()+ sleep_arg = mock_sleep.call_args.args[0]+ assert 0 < sleep_arg <= 0.5- def test_respect_rate_limit_waits_when_needed(self, monkeypatch):- """Test that _respect_rate_limit waits when delay is needed."""- import time+ def test_respect_rate_limit_no_wait_when_zero_delay(self):+ """Test that _respect_rate_limit does not wait when delay is 0."""+ from unittest.mock import patch+ from local_deep_research.web_search_engines.engines import (+ _searxng_rate_limiter,+ )from local_deep_research.web_search_engines.engines.search_engine_searxng import (SearXNGSearchEngine,)- sleep_called = []- monkeypatch.setattr(- "local_deep_research.web_search_engines.engines.search_engine_searxng.time.sleep",- lambda x: sleep_called.append(x),+ _searxng_rate_limiter.reset_for_tests()+ engine = SearXNGSearchEngine(+ instance_url="http://localhost:8080",+ delay_between_requests=0.0,)- engine = SearXNGSearchEngine(delay_between_requests=1.0)- engine.last_request_time = time.time()-- engine._respect_rate_limit()+ with patch("time.sleep") as mock_sleep:+ engine._respect_rate_limit()+ engine._respect_rate_limit()- # Should have called sleep- assert len(sleep_called) > 0+ mock_sleep.assert_not_called()class TestSearXNGInvokeMethod:diff --git a/tests/web_search_engines/engines/test_search_engine_searxng.py b/tests/web_search_engines/engines/test_search_engine_searxng.pyindex 67519ba7da..3c3b0d3ae7 100644--- a/tests/web_search_engines/engines/test_search_engine_searxng.py+++ b/tests/web_search_engines/engines/test_search_engine_searxng.py@@ -12,6 +12,7 @@ Tests cover:"""from unittest.mock import Mock, call, patch+import pytest@@ -380,12 +381,41 @@ class TestIsValidSearchResult:class TestRateLimiting:"""Tests for rate limiting functionality."""- def test_rate_limit_applied(self):- """Rate limiting is applied between requests."""+ @pytest.fixture(autouse=True)+ def auto_reset_rate_limiter(self):+ """Automatically reset rate limiter state before and after each test."""+ from local_deep_research.web_search_engines.engines import (+ _searxng_rate_limiter,+ )++ _searxng_rate_limiter.reset_for_tests()+ yield+ _searxng_rate_limiter.reset_for_tests()++ def test_reset_for_tests_clears_global_state(self):+ """reset_for_tests directly empties tracked locks and last-request timestamps."""+ from local_deep_research.web_search_engines.engines import (+ _searxng_rate_limiter,+ )++ _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+ )++ _searxng_rate_limiter.reset_for_tests()+ assert len(_searxng_rate_limiter._url_locks) == 0+ assert len(_searxng_rate_limiter._url_last_request) == 0++ def test_no_rate_limit_when_delay_is_zero_or_negative(self):+ """Delay of 0 or negative returns immediately without populating tracked state."""+ from local_deep_research.web_search_engines.engines import (+ _searxng_rate_limiter,+ )from local_deep_research.web_search_engines.engines.search_engine_searxng import (SearXNGSearchEngine,)- import timewith patch("local_deep_research.web_search_engines.engines.search_engine_searxng.safe_get"@@ -396,41 +426,184 @@ class TestRateLimiting:engine = SearXNGSearchEngine(instance_url="http://localhost:8080",- delay_between_requests=0.1,+ delay_between_requests=0.0,)- engine.last_request_time = time.time()-- with patch("time.sleep"):+ with patch("time.sleep") as mock_sleep:engine._respect_rate_limit()+ engine._respect_rate_limit()+ mock_sleep.assert_not_called()- # Should have been called to wait- # (may or may not depending on timing)+ _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- def test_no_rate_limit_first_request(self):- """No rate limiting on first request."""+ def test_rate_limit_shared_across_instances(self):+ """Two engines on the same URL share the rate-limit timestamp in global state."""+ from local_deep_research.web_search_engines.engines import (+ _searxng_rate_limiter,+ )from local_deep_research.web_search_engines.engines.search_engine_searxng import (SearXNGSearchEngine,)- with patch(- "local_deep_research.web_search_engines.engines.search_engine_searxng.safe_get"- ) as mock_get:- mock_response = Mock()- mock_response.status_code = 200- mock_get.return_value = mock_response+ def _make_engine():+ with patch(+ "local_deep_research.web_search_engines.engines.search_engine_searxng.safe_get"+ ) as mock_get:+ mock_response = Mock()+ mock_response.status_code = 200+ mock_get.return_value = mock_response+ return SearXNGSearchEngine(+ instance_url="http://localhost:8080",+ delay_between_requests=0.5,+ )- engine = SearXNGSearchEngine(- instance_url="http://localhost:8080",- delay_between_requests=1.0,+ first = _make_engine()+ second = _make_engine()++ with patch("time.sleep") as mock_sleep:+ first._respect_rate_limit()+ initial_ts = _searxng_rate_limiter._url_last_request.get(+ "http://localhost:8080")+ assert initial_ts is not None- # last_request_time is 0, so no wait needed- engine.last_request_time = 0+ second._respect_rate_limit()+ # Second call should have slept the configured delay because+ # the limiter is shared across the two engine instances.+ mock_sleep.assert_called_once()+ sleep_arg = mock_sleep.call_args.args[0]+ assert 0 < sleep_arg <= 0.5- with patch("time.sleep"):- engine._respect_rate_limit()- # Should not sleep on first request (time since last > delay)+ second_ts = _searxng_rate_limiter._url_last_request.get(+ "http://localhost:8080"+ )+ assert second_ts >= initial_ts++ def test_rate_limit_isolated_per_instance_url(self):+ """Engines targeting different URLs do not block each other."""+ from local_deep_research.web_search_engines.engines.search_engine_searxng import (+ SearXNGSearchEngine,+ )++ def _make_engine(url):+ with patch(+ "local_deep_research.web_search_engines.engines.search_engine_searxng.safe_get"+ ) as mock_get:+ mock_response = Mock()+ mock_response.status_code = 200+ mock_get.return_value = mock_response+ return SearXNGSearchEngine(+ instance_url=url,+ delay_between_requests=0.5,+ )++ first = _make_engine("http://localhost:8080")+ second = _make_engine("http://localhost:8081")++ with patch("time.sleep") as mock_sleep:+ first._respect_rate_limit()+ second._respect_rate_limit()+ mock_sleep.assert_not_called()++ def test_rate_limit_url_normalization(self):+ """URLs with and without trailing slashes map to the same rate limit bucket."""+ from local_deep_research.web_search_engines.engines import (+ _searxng_rate_limiter,+ )++ with patch("time.sleep") as mock_sleep:+ _searxng_rate_limiter.respect_rate_limit(+ "http://localhost:8080/", 0.5+ )+ _searxng_rate_limiter.respect_rate_limit(+ "http://localhost:8080", 0.5+ )+ mock_sleep.assert_called_once()++ def test_rate_limit_logging(self):+ """Sleeping logs an INFO message with the wait time."""+ from local_deep_research.web_search_engines.engines import (+ _searxng_rate_limiter,+ )++ with (+ patch(+ "local_deep_research.web_search_engines.engines._searxng_rate_limiter.logger"+ ) as mock_logger,+ patch("time.sleep"),+ ):+ _searxng_rate_limiter.respect_rate_limit(+ "http://localhost:8080", 0.5+ )+ _searxng_rate_limiter.respect_rate_limit(+ "http://localhost:8080", 0.5+ )++ mock_logger.info.assert_called_once()+ log_msg = mock_logger.info.call_args.args[0]+ assert "SearXNG rate limiting: waiting" in log_msg++ def test_rate_limiter_evicts_old_entries_at_max_capacity(self, monkeypatch):+ """Evict oldest entries when MAX_TRACKED_URLS capacity is reached."""+ from local_deep_research.web_search_engines.engines import (+ _searxng_rate_limiter,+ )++ monkeypatch.setattr(_searxng_rate_limiter, "MAX_TRACKED_URLS", 4)++ for i in range(4):+ _searxng_rate_limiter.respect_rate_limit(+ f"http://localhost:808{i}", 0.1+ )++ assert len(_searxng_rate_limiter._url_locks) == 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++ def test_rate_limit_multithreaded(self):+ """Multiple threads invoking respect_rate_limit concurrently are properly serialized."""+ import concurrent.futures+ import threading+ import time+ from local_deep_research.web_search_engines.engines import (+ _searxng_rate_limiter,+ )++ delay = 0.04+ num_threads = 5+ timestamps = []+ timestamps_lock = threading.Lock()++ def worker():+ t_start = time.monotonic()+ _searxng_rate_limiter.respect_rate_limit(+ "http://localhost:8080", delay+ )+ t_end = time.monotonic()+ with timestamps_lock:+ timestamps.append((t_start, t_end))++ start_time = time.monotonic()+ with concurrent.futures.ThreadPoolExecutor(+ max_workers=num_threads+ ) as executor:+ futures = [executor.submit(worker) for _ in range(num_threads)]+ concurrent.futures.wait(futures)+ total_time = time.monotonic() - start_time++ # Expected serialized duration for 5 calls is 4 * 0.04 = 0.16s.+ # Fully broken locking (concurrent sleep) completes in ~0.04s.+ # A 0.8x threshold (0.128s) reliably detects broken locking while+ # allowing margin for minor OS scheduling jitter.+ expected_serial_delay = (num_threads - 1) * delay+ assert total_time >= expected_serial_delay * 0.8, (+ f"Expected total_time >= {expected_serial_delay * 0.8:.3f}s, got {total_time:.3f}s"+ )def test_rate_limit_thread_safety(self):"""Concurrent calls to _respect_rate_limit serialize requests and enforce delays correctly with a mocked clock."""@@ -475,11 +648,11 @@ class TestRateLimiting:with (patch(- "local_deep_research.web_search_engines.engines.search_engine_searxng.time.time",+ "local_deep_research.web_search_engines.engines._searxng_rate_limiter.time.monotonic",side_effect=mock_time,),patch(- "local_deep_research.web_search_engines.engines.search_engine_searxng.time.sleep",+ "local_deep_research.web_search_engines.engines._searxng_rate_limiter.time.sleep",side_effect=mock_sleep,),):