~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(search): harden Elasticsearch availability probes (#5362)
Ziyang Guo40202459d88e
diff --git a/changelog.d/+elasticsearch-availability-followups.bugfix.md b/changelog.d/+elasticsearch-availability-followups.bugfix.mdnew file mode 100644index 0000000000..f1d5fc5005--- /dev/null+++ b/changelog.d/+elasticsearch-availability-followups.bugfix.md@@ -0,0 +1 @@+Elasticsearch availability checks now support IPv6 hosts, discard expired probe-cache entries, and cannot break successful engine construction when custom availability methods raise.diff --git a/docs/SearXNG-Setup.md b/docs/SearXNG-Setup.mdindex 0e645ca54e..615444bb33 100644--- a/docs/SearXNG-Setup.md+++ b/docs/SearXNG-Setup.md@@ -92,7 +92,7 @@ from web_search_engines.search_engine_factory import create_search_engineengine = create_search_engine("searxng")# Check if available-if engine and hasattr(engine, 'is_available') and engine.is_available:+if engine and getattr(engine, "_is_available", False):print(f"SearXNG configured with instance: {engine.instance_url}")print(f"Delay between requests: {engine.delay_between_requests} seconds")else:diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_elasticsearch.py b/src/local_deep_research/web_search_engines/engines/search_engine_elasticsearch.pyindex 3f5c993531..fb108e5015 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_elasticsearch.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_elasticsearch.py@@ -1,14 +1,14 @@import json-from ...security.secure_logging import logger+import threadingimport time as _timefrom typing import Any, Dict, List, Optionalfrom elasticsearch import Elasticsearchfrom langchain_core.language_models import BaseLLM-from ...constants import SNIPPET_LENGTH_SHORT+from ...constants import DEFAULT_SEARCH_TOOL, SNIPPET_LENGTH_SHORT+from ...security.secure_logging import loggerfrom ..search_engine_base import BaseSearchEngine, Exposure, Sensitivity-from ...constants import DEFAULT_SEARCH_TOOLclass ElasticsearchSearchEngine(BaseSearchEngine):@@ -81,12 +81,29 @@ class ElasticsearchSearchEngine(BaseSearchEngine):# A negative result (connection refused / timeout) is cached for the same TTL — we don't# want a misconfigured engine to cost a TCP round-trip on every research run._availability_cache: Dict[str, tuple[float, bool]] = {}+ _availability_cache_lock = threading.Lock()_AVAILABILITY_TTL_SECONDS = 60.0@classmethoddef clear_availability_cache(cls) -> None:"""Clear the cached availability probe results."""- cls._availability_cache.clear()+ with cls._availability_cache_lock:+ cls._availability_cache.clear()++ @classmethod+ def _get_cached_availability(+ cls, cache_key: str, now: float+ ) -> Optional[bool]:+ """Prune expired probe entries and return a fresh cached result."""+ with cls._availability_cache_lock:+ for key, (timestamp, _available) in list(+ cls._availability_cache.items()+ ):+ if now - timestamp >= cls._AVAILABILITY_TTL_SECONDS:+ cls._availability_cache.pop(key, None)++ cached = cls._availability_cache.get(cache_key)+ return cached[1] if cached is not None else None@classmethoddef is_available(@@ -141,14 +158,13 @@ class ElasticsearchSearchEngine(BaseSearchEngine):cache_key = str(hosts)now = _time.monotonic()- cached = cls._availability_cache.get(cache_key)+ cached = cls._get_cached_availability(cache_key, now)if cached is not None:- ts, available = cached- if now - ts < cls._AVAILABILITY_TTL_SECONDS:- return available+ return cachedavailable = cls._probe_hosts_available(hosts)- cls._availability_cache[cache_key] = (now, available)+ with cls._availability_cache_lock:+ cls._availability_cache[cache_key] = (now, available)if not available:logger.info("Elasticsearch availability probe failed; excluding from "@@ -169,9 +185,10 @@ class ElasticsearchSearchEngine(BaseSearchEngine):Any single host responding makes the engine available — matches theElasticsearch client behavior of treating the list as failover.- Cheap (no HTTP) and short-timeout (1s per host, capped at 2.0s aggregate- budget across all hosts) so the worst case is strictly bounded.- Each host is validated against SSRF rules before connecting.+ Cheap (no HTTP) and short-timeout (1s per host, capped at a 2.0s+ connection budget across all hosts). SSRF validation runs before each+ connection and can perform DNS resolution that cannot be interrupted+ by this connection-only budget."""import socketfrom urllib.parse import urlparse@@ -208,7 +225,13 @@ class ElasticsearchSearchEngine(BaseSearchEngine):else:continue- probe_url = f"{scheme}://{hostname}:{port}"+ connection_host = str(hostname).strip("[]")+ url_host = (+ f"[{connection_host}]"+ if ":" in connection_host+ else connection_host+ )+ probe_url = f"{scheme}://{url_host}:{port}"if not validate_url(probe_url, allow_localhost=True, allow_private_ips=True):@@ -220,7 +243,7 @@ class ElasticsearchSearchEngine(BaseSearchEngine):timeout = min(remaining, 1.0)try:with socket.create_connection(- (hostname, port), timeout=timeout+ (connection_host, port), timeout=timeout):return Trueexcept (OSError, socket.timeout, ValueError):diff --git a/src/local_deep_research/web_search_engines/search_engine_base.py b/src/local_deep_research/web_search_engines/search_engine_base.pyindex b3c77cbbaa..4a43612a98 100644--- a/src/local_deep_research/web_search_engines/search_engine_base.py+++ b/src/local_deep_research/web_search_engines/search_engine_base.py@@ -289,10 +289,11 @@ class BaseSearchEngine(ABC):hard-fail (e.g. Elasticsearch's ``client.info()`` raises``ConnectionError`` when the cluster is unreachable) should overridethis to fail closed: returning ``False`` causes the engine to be- omitted from the agent's tool surface AND the auto-search pool, so- the heartbeat never advertises a broken tool and the factory never- logs ``Failed to create search engine '<name>' (ConnectionError)``- per step.+ omitted from specialized agent tool surfaces and the auto-search+ candidate pool, so those paths do not advertise or instantiate a+ broken engine. The primary generic ``web_search`` tool and direct+ factory callers can still attempt construction and surface the+ underlying configuration or connection error.Default is ``True`` — engines that don't probe at init stayeligible. This is the opposite default of ``BaseLLMProvider`` becausediff --git a/src/local_deep_research/web_search_engines/search_engine_factory.py b/src/local_deep_research/web_search_engines/search_engine_factory.pyindex d988ff81e0..2517c061ab 100644--- a/src/local_deep_research/web_search_engines/search_engine_factory.py+++ b/src/local_deep_research/web_search_engines/search_engine_factory.py@@ -749,7 +749,22 @@ def get_search(settings_snapshot=settings_snapshot)except TypeError:- avail = engine.is_available()+ try:+ avail = engine.is_available()+ except Exception as exc:+ logger.debug(+ "Engine availability fallback failed for {} ({})",+ engine_type,+ type(exc).__name__,+ )+ avail = None+ except Exception as exc:+ logger.debug(+ "Engine availability check failed for {} ({})",+ engine_type,+ type(exc).__name__,+ )+ avail = Noneelse:avail = engine.is_availableif avail is not None:diff --git a/tests/web_search_engines/engines/test_search_engine_elasticsearch.py b/tests/web_search_engines/engines/test_search_engine_elasticsearch.pyindex 2d96d3766a..aa90cda6df 100644--- a/tests/web_search_engines/engines/test_search_engine_elasticsearch.py+++ b/tests/web_search_engines/engines/test_search_engine_elasticsearch.py@@ -906,6 +906,35 @@ class TestElasticsearchIsAvailable:assert ElasticsearchSearchEngine.is_available(snapshot) is Truemock_conn.assert_called_once_with(("localhost", 9200), timeout=1.0)+ def test_is_available_ipv6_host_brackets_validation_url(self):+ """IPv6 validation URLs keep brackets while sockets use the bare host."""+ from local_deep_research.web_search_engines.engines.search_engine_elasticsearch import (+ ElasticsearchSearchEngine,+ )++ with (+ patch(+ "local_deep_research.security.ssrf_validator.validate_url",+ return_value=True,+ ) as mock_validate,+ patch("socket.create_connection") as mock_conn,+ ):+ mock_conn.return_value.__enter__.return_value = MagicMock()+ snapshot = {+ "search.engine.web.elasticsearch.default_params.hosts": [+ "http://[::1]:9200"+ ]+ }++ assert ElasticsearchSearchEngine.is_available(snapshot) is True++ mock_validate.assert_called_once_with(+ "http://[::1]:9200",+ allow_localhost=True,+ allow_private_ips=True,+ )+ mock_conn.assert_called_once_with(("::1", 9200), timeout=1.0)+def test_is_available_cache_key_separation(self):"""Cache keys are separated across different host configurations."""from local_deep_research.web_search_engines.engines.search_engine_elasticsearch import (@@ -928,6 +957,41 @@ class TestElasticsearchIsAvailable:assert ElasticsearchSearchEngine.is_available(snapshot2) is Trueassert mock_conn.call_count == 2+ def test_is_available_prunes_expired_cache_entries(self):+ """A later probe removes expired entries for other host configs."""+ from local_deep_research.web_search_engines.engines.search_engine_elasticsearch import (+ ElasticsearchSearchEngine,+ )++ ElasticsearchSearchEngine._availability_cache.update(+ {+ "expired-hosts": (0.0, False),+ "fresh-hosts": (90.0, True),+ }+ )+ snapshot = {+ "search.engine.web.elasticsearch.default_params.hosts": [+ "http://localhost:9200"+ ]+ }+ with (+ patch(+ "local_deep_research.web_search_engines.engines.search_engine_elasticsearch._time.monotonic",+ return_value=100.0,+ ),+ patch.object(+ ElasticsearchSearchEngine,+ "_probe_hosts_available",+ return_value=True,+ ),+ ):+ assert ElasticsearchSearchEngine.is_available(snapshot) is True++ assert (+ "expired-hosts" not in ElasticsearchSearchEngine._availability_cache+ )+ assert "fresh-hosts" in ElasticsearchSearchEngine._availability_cache+def test_is_available_multi_host_failover(self):"""Tries next host when first host connection fails."""from local_deep_research.web_search_engines.engines.search_engine_elasticsearch import (diff --git a/tests/web_search_engines/test_search_engine_factory_coverage.py b/tests/web_search_engines/test_search_engine_factory_coverage.pyindex 07e16d6fdb..743dfdc224 100644--- a/tests/web_search_engines/test_search_engine_factory_coverage.py+++ b/tests/web_search_engines/test_search_engine_factory_coverage.py@@ -1536,3 +1536,40 @@ def test_factory_logging_passes_settings_snapshot_to_is_available():assert len(received_snapshots) > 0assert received_snapshots[-1] == snapshot+++def test_factory_logging_swallows_type_error_from_legacy_fallback():+ """Availability diagnostics cannot break a successfully created engine."""+ from local_deep_research.web_search_engines.search_engine_base import (+ BaseSearchEngine,+ )+ from local_deep_research.web_search_engines.search_engine_factory import (+ get_search,+ )++ class _MockEngine(BaseSearchEngine):+ def is_available(self):+ raise TypeError("internal availability failure")++ def _get_previews(self, query):+ return []++ def _get_full_content(self, items):+ return items++ with (+ _patches(+ config_return={"mock_eng": _engine_config()},+ class_return=_MockEngine,+ ),+ patch(+ "local_deep_research.web_search_engines.search_engine_factory.logger"+ ) as mock_logger,+ ):+ engine = get_search("mock_eng", Mock(), settings_snapshot={"a": "b"})++ assert isinstance(engine, _MockEngine)+ assert any(+ "Engine availability fallback failed" in str(call)+ for call in mock_logger.debug.call_args_list+ )