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.

test: add high-value tests for real functionality + fix infinite recursion bug (#2341)

LearningCircuit09502c5959e3
diff --git a/src/local_deep_research/web_search_engines/engines/meta_search_engine.py b/src/local_deep_research/web_search_engines/engines/meta_search_engine.py
index 0e1fb7ef51..c921fb87ab 100644
--- a/src/local_deep_research/web_search_engines/engines/meta_search_engine.py
+++ b/src/local_deep_research/web_search_engines/engines/meta_search_engine.py
@@ -70,7 +70,7 @@ class MetaSearchEngine(BaseSearchEngine):
)
def _get_search_config(self) -> Dict[str, Any]:
- """Get search config from settings_snapshot or fallback to self._get_search_config()"""
+ """Get search config from settings_snapshot or return empty dict."""
if self.settings_snapshot:
# Extract search engine configs from settings snapshot
config_data = {}
@@ -104,8 +104,7 @@ class MetaSearchEngine(BaseSearchEngine):
)
return config_data
else:
- # Fallback to search_config if no snapshot
- return self._get_search_config()
+ return {}
def _get_available_engines(self) -> List[str]:
"""Get list of available engines, excluding 'meta' and 'auto', based on user settings"""
diff --git a/tests/utilities/test_json_utils_real_world.py b/tests/utilities/test_json_utils_real_world.py
new file mode 100644
index 0000000000..245daeb957
--- /dev/null
+++ b/tests/utilities/test_json_utils_real_world.py
@@ -0,0 +1,110 @@
+"""Tests for real-world LLM output patterns that extract_json encounters in production.
+
+These tests document edge cases observed in actual LLM responses that aren't
+covered by the basic test_json_utils.py tests.
+"""
+
+from local_deep_research.utilities.json_utils import (
+ extract_json,
+ get_llm_response_text,
+)
+
+
+class TestMultipleCodeFences:
+ """Tests for LLM responses containing multiple code fences."""
+
+ def test_multiple_json_code_fences_uses_first(self):
+ """When an LLM self-corrects by producing two ```json blocks,
+ _strip_code_fences uses the first one. This documents the behavior
+ since it could arguably pick either."""
+ text = (
+ "Let me try:\n"
+ '```json\n{"answer": "first attempt"}\n```\n'
+ "Wait, let me correct that:\n"
+ '```json\n{"answer": "corrected"}\n```'
+ )
+ result = extract_json(text)
+ # Documents current behavior: first ```json block wins
+ assert result == {"answer": "first attempt"}
+
+ def test_non_json_language_tag_code_fence(self):
+ """A ```python fence doesn't match ```json, so it falls through
+ to the bare ``` path which extracts between the first pair of ```."""
+ text = (
+ "Here is the data:\n"
+ '```python\ndata = {"key": "value"}\n```\n'
+ "That's it."
+ )
+ result = extract_json(text)
+ # The bare ``` path extracts: 'python\ndata = {"key": "value"}'
+ # Then bracket extraction finds {"key": "value"} inside
+ assert result == {"key": "value"}
+
+
+class TestUrlsAndCommentRegex:
+ """Tests for interaction between URLs in JSON values and the // comment removal regex."""
+
+ def test_malformed_json_with_urls_comment_regex_interaction(self):
+ """When JSON has a trailing comma (triggering artifact cleaning),
+ the // comment-removal regex strips everything after // in URLs.
+ This documents a known limitation."""
+ text = '{"url": "https://example.com/page", "count": 1,}'
+ result = extract_json(text)
+ # The trailing comma makes direct parse fail.
+ # Artifact cleaning: removes trailing comma AND removes "//example.com/page"
+ # After cleaning: {"url": "https:, "count": 1} -- which is invalid JSON
+ # This is a known limitation: malformed JSON + URLs = potential breakage
+ # The result depends on whether the cleaned version happens to parse
+ # The important thing is it doesn't crash
+ assert result is None or isinstance(result, (dict, list))
+
+ def test_valid_json_with_double_slash_in_string_parses_directly(self):
+ """Valid JSON with // in string values parses on the direct parse step
+ and never hits artifact cleaning, so URLs are preserved."""
+ text = '{"url": "https://example.com/path", "title": "Test"}'
+ result = extract_json(text)
+ assert result == {"url": "https://example.com/path", "title": "Test"}
+
+
+class TestContentAttributeFormats:
+ """Tests for different LangChain content attribute formats."""
+
+ def test_content_attribute_is_list_of_content_blocks(self):
+ """LangChain multimodal AIMessage can have content as a list of blocks.
+ get_llm_response_text should convert this to a string."""
+
+ class FakeMessage:
+ content = [
+ {"type": "text", "text": '{"key": "value"}'},
+ {"type": "image_url", "image_url": "data:..."},
+ ]
+
+ text = get_llm_response_text(FakeMessage())
+ # content is a list (not str), so it gets converted via str()
+ assert isinstance(text, str)
+ # The string representation should contain the JSON
+ assert "key" in text
+ assert "value" in text
+
+
+class TestBracketMismatchEdgeCases:
+ """Tests for bracket extraction edge cases with multiple JSON objects."""
+
+ def test_bracket_mismatch_across_separate_json_objects(self):
+ """Text like '{"a": 1} middle {"b": 2}' - rfind grabs the last },
+ so extraction spans from first { to last }, giving
+ '{"a": 1} middle {"b": 2}' which isn't valid JSON."""
+ text = 'Here is {"a": 1} and also {"b": 2} done'
+ result = extract_json(text)
+ # The bracket extraction grabs from first { to last }:
+ # '{"a": 1} and also {"b": 2}'
+ # This isn't valid JSON, so it fails. Artifact cleaning won't help.
+ # Result should be None since the combined span isn't valid JSON.
+ assert result is None
+
+ def test_single_json_object_in_prose_succeeds(self):
+ """Single JSON object in prose works because find/rfind grab
+ matching brackets correctly."""
+ text = 'The result is {"status": "ok", "count": 42} as expected.'
+ result = extract_json(text)
+ assert result == {"status": "ok", "count": 42}
diff --git a/tests/utilities/test_search_cache_persistence.py b/tests/utilities/test_search_cache_persistence.py
new file mode 100644
index 0000000000..9c0a5accb5
--- /dev/null
+++ b/tests/utilities/test_search_cache_persistence.py
@@ -0,0 +1,175 @@
+"""Tests for search cache persistence and caching edge cases.
+
+These tests exercise the SearchCache's persistence across instances,
+the get_or_fetch lifecycle with falsy results, and JSON serialization
+roundtrips through SQLite.
+"""
+
+import pytest
+
+from local_deep_research.utilities.search_cache import SearchCache
+
+
+def cache_dir(tmp_path):
+ """Provide a temporary cache directory."""
+ return str(tmp_path / "test_cache")
+
+
+def cache(cache_dir):
+ """Provide a SearchCache instance with a temporary directory."""
+ c = SearchCache(cache_dir=cache_dir)
+ yield c
+ c.dispose()
+
+
+class TestPersistenceAcrossInstances:
+ """Tests for data surviving across cache instance lifecycles."""
+
+ def test_persistence_across_cache_instances(self, cache_dir):
+ """Data put with instance 1 survives after dispose and re-creation.
+ This is the fundamental purpose of the persistent cache."""
+ cache1 = SearchCache(cache_dir=cache_dir)
+ results = [{"title": "Persistent Result", "url": "https://example.com"}]
+ cache1.put("persistent query", results, "test_engine")
+ cache1.dispose()
+
+ # Create a new instance with the same directory
+ cache2 = SearchCache(cache_dir=cache_dir)
+ retrieved = cache2.get("persistent query", "test_engine")
+ cache2.dispose()
+
+ assert retrieved is not None
+ assert len(retrieved) == 1
+ assert retrieved[0]["title"] == "Persistent Result"
+
+
+class TestGetOrFetchWithFalsyResults:
+ """Tests for get_or_fetch behavior with empty/None results."""
+
+ def test_empty_list_result_not_cached_via_get_or_fetch(self, cache):
+ """fetch_func returns [] (falsy) — it's returned to caller but NOT
+ cached, causing re-fetch on next call. This documents the behavior
+ where put() rejects empty results."""
+ call_count = 0
+
+ def fetch_empty():
+ nonlocal call_count
+ call_count += 1
+ return []
+
+ # First call: fetches and returns []
+ result1 = cache.get_or_fetch("empty query", fetch_empty, "test_engine")
+ assert result1 == []
+ assert call_count == 1
+
+ # Clear memory cache to force DB lookup
+ cache._memory_cache.clear()
+
+ # Second call: fetches AGAIN because [] wasn't cached
+ result2 = cache.get_or_fetch("empty query", fetch_empty, "test_engine")
+ assert result2 == []
+ assert (
+ call_count == 2
+ ) # Called again because empty results aren't cached
+
+ def test_fetch_returning_none_path(self, cache):
+ """fetch_func returning None (not exception) goes through the full
+ stampede protection path and returns None."""
+
+ def fetch_none():
+ return None
+
+ result = cache.get_or_fetch("none query", fetch_none, "test_engine")
+ assert result is None
+
+ def test_fetch_exception_returns_none(self, cache):
+ """fetch_func raising an exception returns None (not the exception)."""
+
+ def fetch_error():
+ raise RuntimeError("network error")
+
+ result = cache.get_or_fetch("error query", fetch_error, "test_engine")
+ assert result is None
+
+
+class TestMemoryCacheMasksDbAccess:
+ """Tests documenting memory cache interaction with DB stats."""
+
+ def test_memory_cache_masks_db_access_count(self, cache):
+ """Memory cache satisfies reads, so DB access_count never increments
+ beyond the initial put. This documents a stats limitation."""
+ results = [{"title": "Test", "url": "https://example.com"}]
+ cache.put("stats query", results, "test_engine")
+
+ # Multiple reads from memory cache
+ for _ in range(5):
+ cache.get("stats query", "test_engine")
+
+ # Check DB access_count - should be 1 (from initial put)
+ # because all reads were served from memory cache
+ with cache.Session() as session:
+ from local_deep_research.database.models import (
+ SearchCache as SearchCacheModel,
+ )
+
+ query_hash = cache._get_query_hash("stats query", "test_engine")
+ entry = (
+ session.query(SearchCacheModel)
+ .filter_by(query_hash=query_hash)
+ .first()
+ )
+ assert entry is not None
+ # access_count stays at 1 because memory cache serves all reads
+ assert entry.access_count == 1
+
+
+class TestJsonSerializationRoundtrip:
+ """Tests for complex data surviving SQLite JSON serialization."""
+
+ def test_complex_nested_results_json_roundtrip(self, cache_dir):
+ """Deeply nested structures with None, unicode, and special chars
+ survive the SQLite JSON serialization roundtrip."""
+ complex_results = [
+ {
+ "title": "Unicode Test: \u00e4\u00f6\u00fc \u00df \u2603 \u2764",
+ "url": "https://example.com/path?q=test&lang=en",
+ "metadata": {
+ "nested": {
+ "deep": {
+ "value": 42,
+ "list": [1, None, "three", True, False],
+ }
+ },
+ "empty_dict": {},
+ "empty_list": [],
+ "null_value": None,
+ },
+ "snippet": 'Text with "quotes" and\nnewlines\tand\ttabs',
+ }
+ ]
+
+ cache = SearchCache(cache_dir=cache_dir)
+ cache.put("complex query", complex_results, "test_engine")
+ cache.dispose()
+
+ # Retrieve from a fresh instance (forces DB read)
+ cache2 = SearchCache(cache_dir=cache_dir)
+ retrieved = cache2.get("complex query", "test_engine")
+ cache2.dispose()
+
+ assert retrieved is not None
+ assert len(retrieved) == 1
+ result = retrieved[0]
+ assert "\u00e4\u00f6\u00fc" in result["title"]
+ assert result["metadata"]["nested"]["deep"]["value"] == 42
+ assert result["metadata"]["nested"]["deep"]["list"] == [
+ 1,
+ None,
+ "three",
+ True,
+ False,
+ ]
+ assert result["metadata"]["null_value"] is None
+ assert "\n" in result["snippet"]
diff --git a/tests/utilities/test_thread_context_semantics.py b/tests/utilities/test_thread_context_semantics.py
new file mode 100644
index 0000000000..aa876cc72f
--- /dev/null
+++ b/tests/utilities/test_thread_context_semantics.py
@@ -0,0 +1,145 @@
+"""Tests documenting critical behavioral semantics of thread_context.py.
+
+These tests document non-obvious behaviors that are important for correctness
+when using ThreadPoolExecutor with research context propagation.
+"""
+
+from local_deep_research.utilities.thread_context import (
+ clear_search_context,
+ get_search_context,
+ preserve_research_context,
+ search_context,
+ set_search_context,
+)
+
+
+class TestPreserveResearchContextDecorator:
+ """Tests for @preserve_research_context decorator semantics."""
+
+ def test_preserve_research_context_captures_at_decoration_time(self):
+ """Context is captured when @preserve_research_context is applied,
+ NOT when the decorated function is called. This is the most important
+ behavioral property — it's what makes thread context propagation work."""
+ # Set context BEFORE decorating
+ set_search_context({"research_id": "captured-at-decoration"})
+
+ @preserve_research_context
+ def task():
+ return get_search_context()
+
+ # Clear context AFTER decorating but BEFORE calling
+ clear_search_context()
+
+ # The decorated function should still see the context from decoration time
+ result = task()
+ assert result is not None
+ assert result["research_id"] == "captured-at-decoration"
+
+ def test_multiple_decorated_functions_carry_independent_snapshots(self):
+ """Two functions decorated at different times carry their own
+ independent context snapshots."""
+ set_search_context({"research_id": "snapshot-1", "phase": "first"})
+
+ @preserve_research_context
+ def task_1():
+ return get_search_context()
+
+ # Change context before decorating second function
+ set_search_context({"research_id": "snapshot-2", "phase": "second"})
+
+ @preserve_research_context
+ def task_2():
+ return get_search_context()
+
+ clear_search_context()
+
+ result_1 = task_1()
+ result_2 = task_2()
+
+ assert result_1["research_id"] == "snapshot-1"
+ assert result_1["phase"] == "first"
+ assert result_2["research_id"] == "snapshot-2"
+ assert result_2["phase"] == "second"
+
+ def test_decorator_with_no_context_is_noop(self):
+ """When no context is set at decoration time, the decorator
+ doesn't fail — it simply doesn't set/clear any context."""
+ clear_search_context()
+
+ @preserve_research_context
+ def task():
+ return get_search_context()
+
+ result = task()
+ # No context was set at decoration time, so context remains None
+ assert result is None
+
+ def test_decorator_clears_context_in_finally(self):
+ """The decorator clears context after the function runs,
+ even if the context was set. This prevents leakage in thread pools."""
+ set_search_context({"research_id": "will-be-cleared"})
+
+ @preserve_research_context
+ def task():
+ ctx = get_search_context()
+ return ctx
+
+ clear_search_context()
+
+ # Run the decorated function
+ task()
+
+ # After the decorated function returns, context should be cleared
+ # because the finally block calls clear_search_context()
+ assert get_search_context() is None
+
+
+class TestSearchContextManager:
+ """Tests for the search_context context manager."""
+
+ def test_context_manager_destroys_pre_existing_context(self):
+ """with search_context(...) clears any previously-set context in finally.
+ This is destructive — the pre-existing context is NOT restored."""
+ set_search_context({"research_id": "pre-existing"})
+
+ with search_context({"research_id": "temporary"}):
+ ctx = get_search_context()
+ assert ctx["research_id"] == "temporary"
+
+ # After exiting, context is CLEARED (not restored to pre-existing)
+ assert get_search_context() is None
+
+ def test_context_manager_clears_on_exception(self):
+ """Context is cleared even if an exception occurs inside the block."""
+ try:
+ with search_context({"research_id": "will-fail"}):
+ raise ValueError("test error")
+ except ValueError:
+ pass
+
+ assert get_search_context() is None
+
+
+class TestShallowCopySemantics:
+ """Tests documenting shallow copy behavior of get_search_context."""
+
+ def test_shallow_copy_allows_nested_mutation_leakage(self):
+ """get_search_context() returns a shallow copy — top-level keys
+ are independent, but nested dict mutations leak to the original."""
+ original = {
+ "research_id": "test",
+ "metadata": {"depth": 1, "tags": ["a"]},
+ }
+ set_search_context(original)
+
+ retrieved = get_search_context()
+
+ # Top-level mutation doesn't leak
+ retrieved["research_id"] = "modified"
+ assert get_search_context()["research_id"] == "test"
+
+ # But nested mutation DOES leak (shallow copy)
+ retrieved["metadata"]["depth"] = 999
+ assert get_search_context()["metadata"]["depth"] == 999
+
+ clear_search_context()
diff --git a/tests/web_search_engines/engines/test_meta_search_engine.py b/tests/web_search_engines/engines/test_meta_search_engine.py
index 7e3877a610..a91c80ab46 100644
--- a/tests/web_search_engines/engines/test_meta_search_engine.py
+++ b/tests/web_search_engines/engines/test_meta_search_engine.py
@@ -735,3 +735,40 @@ class TestMetaSearchEngineGetAvailableEngines:
)
assert "No search engines enabled" in str(exc_info.value)
+
+
+class TestMetaSearchEngineGetSearchConfig:
+ """Tests for MetaSearchEngine _get_search_config method."""
+
+ def test_get_search_config_without_snapshot_returns_empty(self):
+ """_get_search_config() returns {} when settings_snapshot=None.
+
+ Regression test: previously this method called itself recursively
+ when settings_snapshot was None, causing infinite recursion
+ (RecursionError / stack overflow).
+ """
+ from local_deep_research.web_search_engines.engines.meta_search_engine import (
+ MetaSearchEngine,
+ )
+
+ mock_llm = Mock()
+ settings = {
+ "search.max_results": {"value": 10},
+ "search.engine.web.wikipedia.use_in_auto_search": {"value": True},
+ }
+
+ with patch.object(
+ MetaSearchEngine,
+ "_get_available_engines",
+ return_value=["wikipedia"],
+ ):
+ engine = MetaSearchEngine(
+ llm=mock_llm, settings_snapshot=settings, programmatic_mode=True
+ )
+
+ # Now set settings_snapshot to None and call _get_search_config
+ engine.settings_snapshot = None
+
+ # This should return {} instead of recursing infinitely
+ result = engine._get_search_config()
+ assert result == {}
diff --git a/tests/web_search_engines/test_factory_full_search_wrapper.py b/tests/web_search_engines/test_factory_full_search_wrapper.py
new file mode 100644
index 0000000000..69098ead64
--- /dev/null
+++ b/tests/web_search_engines/test_factory_full_search_wrapper.py
@@ -0,0 +1,258 @@
+"""Tests for _create_full_search_wrapper in search_engine_factory.py.
+
+The entire _create_full_search_wrapper function (~160 lines) was never called
+in any test. These tests exercise the wrapper creation logic, parameter
+filtering, and API key extraction from settings snapshots.
+"""
+
+from unittest.mock import Mock, patch
+
+import pytest
+
+from local_deep_research.web_search_engines.search_engine_factory import (
+ _create_full_search_wrapper,
+)
+
+
+def base_engine():
+ """Provide a mock base engine."""
+ return Mock()
+
+
+def mock_llm():
+ """Provide a mock LLM."""
+ return Mock()
+
+
+class TestWrapperCreationConditions:
+ """Tests for when the wrapper is and isn't created."""
+
+ def test_wrapper_returns_base_engine_when_config_not_found(
+ self, base_engine, mock_llm
+ ):
+ """Missing engine config -> returns base engine unchanged."""
+ settings_snapshot = {
+ # No search.engine.web.* keys for our engine
+ "search.other_setting": {"value": "something"},
+ }
+
+ result = _create_full_search_wrapper(
+ "nonexistent_engine",
+ base_engine,
+ mock_llm,
+ {},
+ settings_snapshot=settings_snapshot,
+ )
+
+ assert result is base_engine
+
+ def test_wrapper_returns_base_engine_on_exception(
+ self, base_engine, mock_llm
+ ):
+ """Exception in wrapper creation -> fallback to base engine."""
+ settings_snapshot = {
+ "search.engine.web.test_engine.full_search_module": {
+ "value": "nonexistent.module"
+ },
+ "search.engine.web.test_engine.full_search_class": {
+ "value": "NonexistentClass"
+ },
+ }
+
+ with patch(
+ "local_deep_research.web_search_engines.search_engine_factory.get_safe_module_class",
+ side_effect=ImportError("module not found"),
+ ):
+ result = _create_full_search_wrapper(
+ "test_engine",
+ base_engine,
+ mock_llm,
+ {},
+ settings_snapshot=settings_snapshot,
+ )
+
+ assert result is base_engine
+
+ def test_wrapper_returns_base_when_no_full_search_config(
+ self, base_engine, mock_llm
+ ):
+ """Missing full_search_module/class in config -> returns base engine."""
+ settings_snapshot = {
+ "search.engine.web.test_engine.class_name": {"value": "TestEngine"},
+ # No full_search_module or full_search_class
+ }
+
+ result = _create_full_search_wrapper(
+ "test_engine",
+ base_engine,
+ mock_llm,
+ {},
+ settings_snapshot=settings_snapshot,
+ )
+
+ assert result is base_engine
+
+
+class _FakeWrapperAcceptsAll:
+ """Fake wrapper class that accepts specific init params."""
+
+ def __init__(self, llm=None, web_search=None):
+ self.llm = llm
+ self.web_search = web_search
+
+
+class _FakeWrapperWithApiKey:
+ """Fake wrapper class that accepts api_key and llm."""
+
+ def __init__(self, api_key=None, llm=None):
+ self.api_key = api_key
+ self.llm = llm
+
+
+class TestWrapperParameterFiltering:
+ """Tests for parameter filtering during wrapper creation."""
+
+ def test_wrapper_filters_init_params(self, base_engine, mock_llm):
+ """Only params accepted by wrapper __init__ are passed."""
+ settings_snapshot = {
+ "search.engine.web.test_engine.full_search_module": {
+ "value": "some.module"
+ },
+ "search.engine.web.test_engine.full_search_class": {
+ "value": "SomeClass"
+ },
+ }
+
+ params = {
+ "llm": mock_llm,
+ "web_search": base_engine,
+ "unsupported_param": "should_be_filtered",
+ "another_unsupported": 42,
+ }
+
+ with patch(
+ "local_deep_research.web_search_engines.search_engine_factory.get_safe_module_class",
+ return_value=_FakeWrapperAcceptsAll,
+ ):
+ result = _create_full_search_wrapper(
+ "test_engine",
+ base_engine,
+ mock_llm,
+ params,
+ settings_snapshot=settings_snapshot,
+ )
+
+ assert isinstance(result, _FakeWrapperAcceptsAll)
+ assert result.llm is mock_llm
+ assert result.web_search is base_engine
+
+
+class TestApiKeyExtraction:
+ """Tests for API key extraction from settings snapshots."""
+
+ def test_api_key_from_settings_snapshot_dict_format(
+ self, base_engine, mock_llm
+ ):
+ """API key extraction from {"value": "key"} format in settings."""
+ settings_snapshot = {
+ "search.engine.web.brave.full_search_module": {
+ "value": "some.module"
+ },
+ "search.engine.web.brave.full_search_class": {
+ "value": "BraveSearch"
+ },
+ "search.engine.web.brave.api_key": {"value": "test-api-key-123"},
+ }
+
+ with patch(
+ "local_deep_research.web_search_engines.search_engine_factory.get_safe_module_class",
+ return_value=_FakeWrapperWithApiKey,
+ ):
+ result = _create_full_search_wrapper(
+ "brave",
+ base_engine,
+ mock_llm,
+ {},
+ settings_snapshot=settings_snapshot,
+ )
+
+ assert isinstance(result, _FakeWrapperWithApiKey)
+ assert result.api_key == "test-api-key-123"
+
+ def test_api_key_from_settings_snapshot_plain_format(
+ self, base_engine, mock_llm
+ ):
+ """API key extraction from plain string format in settings."""
+ settings_snapshot = {
+ "search.engine.web.brave.full_search_module": {
+ "value": "some.module"
+ },
+ "search.engine.web.brave.full_search_class": {
+ "value": "BraveSearch"
+ },
+ "search.engine.web.brave.api_key": "plain-api-key-456",
+ }
+
+ with patch(
+ "local_deep_research.web_search_engines.search_engine_factory.get_safe_module_class",
+ return_value=_FakeWrapperWithApiKey,
+ ):
+ result = _create_full_search_wrapper(
+ "brave",
+ base_engine,
+ mock_llm,
+ {},
+ settings_snapshot=settings_snapshot,
+ )
+
+ assert isinstance(result, _FakeWrapperWithApiKey)
+ assert result.api_key == "plain-api-key-456"
+
+ def test_api_key_fallback_to_engine_config(self, base_engine, mock_llm):
+ """When settings key is missing, wrapper still works — API key
+ may come from other sources or be optional."""
+ settings_snapshot = {
+ "search.engine.web.brave.full_search_module": {
+ "value": "some.module"
+ },
+ "search.engine.web.brave.full_search_class": {
+ "value": "BraveSearch"
+ },
+ # No api_key in settings
+ }
+
+ with patch(
+ "local_deep_research.web_search_engines.search_engine_factory.get_safe_module_class",
+ return_value=_FakeWrapperWithApiKey,
+ ):
+ result = _create_full_search_wrapper(
+ "brave",
+ base_engine,
+ mock_llm,
+ {},
+ settings_snapshot=settings_snapshot,
+ )
+
+ assert isinstance(result, _FakeWrapperWithApiKey)
+ # api_key should be None since it's not in settings
+ assert result.api_key is None
+
+ def test_wrapper_with_no_settings_snapshot(self, base_engine, mock_llm):
+ """When settings_snapshot is None, it attempts search_config fallback
+ which may return empty config and return base engine."""
+ with patch(
+ "local_deep_research.web_search_engines.search_engine_factory.search_config",
+ return_value={},
+ ):
+ result = _create_full_search_wrapper(
+ "test_engine",
+ base_engine,
+ mock_llm,
+ {},
+ settings_snapshot=None,
+ )
+
+ # Engine not found in empty config -> returns base engine
+ assert result is base_engine
diff --git a/tests/web_search_engines/test_parallel_engine_filtering.py b/tests/web_search_engines/test_parallel_engine_filtering.py
new file mode 100644
index 0000000000..9d221f183f
--- /dev/null
+++ b/tests/web_search_engines/test_parallel_engine_filtering.py
@@ -0,0 +1,323 @@
+"""Tests for ParallelSearchEngine engine selection and concurrent execution.
+
+Covers SearchMode filtering, is_public exclusion, self-referential engine
+filtering, and ThreadPoolExecutor result merging.
+"""
+
+import concurrent.futures
+from unittest.mock import Mock, patch
+
+import pytest
+
+from local_deep_research.utilities.enums import SearchMode
+from local_deep_research.web_search_engines.engines.parallel_search_engine import (
+ ParallelSearchEngine,
+)
+
+
+def make_engine_class(is_public=True, is_generic=False, is_scientific=False):
+ """Create a mock engine class with the given flags."""
+ cls = Mock()
+ cls.is_public = is_public
+ cls.is_generic = is_generic
+ cls.is_scientific = is_scientific
+ return cls
+
+
+def mock_load_engine_class():
+ """Patch _load_engine_class on BaseSearchEngine."""
+ with patch(
+ "local_deep_research.web_search_engines.search_engine_base.BaseSearchEngine._load_engine_class"
+ ) as mock:
+ yield mock
+
+
+def mock_executor():
+ """Patch the global executor."""
+ with patch(
+ "local_deep_research.web_search_engines.engines.parallel_search_engine._get_global_executor"
+ ) as mock:
+ yield mock
+
+
+class TestSearchModeFiltering:
+ """Tests for engine selection based on SearchMode."""
+
+ def test_scientific_mode_includes_scientific_and_generic(
+ self, mock_load_engine_class, mock_executor
+ ):
+ """SearchMode.SCIENTIFIC includes scientific AND generic engines,
+ excludes others."""
+ engine_classes = {
+ "arxiv": make_engine_class(
+ is_public=True, is_scientific=True, is_generic=False
+ ),
+ "searxng": make_engine_class(
+ is_public=True, is_scientific=False, is_generic=True
+ ),
+ "guardian": make_engine_class(
+ is_public=True, is_scientific=False, is_generic=False
+ ),
+ }
+
+ def load_side_effect(name, config):
+ if name in engine_classes:
+ return (True, engine_classes[name], None)
+ return (False, None, f"Unknown engine {name}")
+
+ mock_load_engine_class.side_effect = load_side_effect
+ mock_executor.return_value = Mock()
+
+ settings = {
+ "search.engine.web.arxiv.module_path": {"value": "some.module"},
+ "search.engine.web.arxiv.class_name": {"value": "ArxivEngine"},
+ "search.engine.web.searxng.module_path": {"value": "some.module"},
+ "search.engine.web.searxng.class_name": {"value": "SearxngEngine"},
+ "search.engine.web.guardian.module_path": {"value": "some.module"},
+ "search.engine.web.guardian.class_name": {
+ "value": "GuardianEngine"
+ },
+ }
+
+ engine = ParallelSearchEngine(
+ llm=Mock(),
+ search_mode=SearchMode.SCIENTIFIC,
+ settings_snapshot=settings,
+ programmatic_mode=True,
+ )
+
+ assert "arxiv" in engine.available_engines
+ assert "searxng" in engine.available_engines
+ assert "guardian" not in engine.available_engines
+
+ def test_private_engine_excluded_by_default(
+ self, mock_load_engine_class, mock_executor
+ ):
+ """is_public=False excluded when allow_local_engines=False."""
+ engine_classes = {
+ "local_rag": make_engine_class(is_public=False),
+ "searxng": make_engine_class(is_public=True, is_generic=True),
+ }
+
+ def load_side_effect(name, config):
+ if name in engine_classes:
+ return (True, engine_classes[name], None)
+ return (False, None, f"Unknown engine {name}")
+
+ mock_load_engine_class.side_effect = load_side_effect
+ mock_executor.return_value = Mock()
+
+ settings = {
+ "search.engine.web.local_rag.module_path": {"value": "some.module"},
+ "search.engine.web.local_rag.class_name": {"value": "LocalRAG"},
+ "search.engine.web.searxng.module_path": {"value": "some.module"},
+ "search.engine.web.searxng.class_name": {"value": "SearxngEngine"},
+ }
+
+ engine = ParallelSearchEngine(
+ llm=Mock(),
+ allow_local_engines=False,
+ settings_snapshot=settings,
+ programmatic_mode=True,
+ )
+
+ assert "local_rag" not in engine.available_engines
+ assert "searxng" in engine.available_engines
+
+ def test_meta_auto_parallel_always_excluded(
+ self, mock_load_engine_class, mock_executor
+ ):
+ """Self-referential engines (meta, auto, parallel) are filtered out
+ to prevent infinite recursion."""
+ engine_classes = {
+ "meta": make_engine_class(is_public=True),
+ "auto": make_engine_class(is_public=True),
+ "parallel": make_engine_class(is_public=True),
+ "searxng": make_engine_class(is_public=True, is_generic=True),
+ }
+
+ def load_side_effect(name, config):
+ if name in engine_classes:
+ return (True, engine_classes[name], None)
+ return (False, None, f"Unknown engine {name}")
+
+ mock_load_engine_class.side_effect = load_side_effect
+ mock_executor.return_value = Mock()
+
+ settings = {
+ "search.engine.web.meta.module_path": {"value": "some.module"},
+ "search.engine.web.meta.class_name": {"value": "MetaEngine"},
+ "search.engine.web.auto.module_path": {"value": "some.module"},
+ "search.engine.web.auto.class_name": {"value": "AutoEngine"},
+ "search.engine.web.parallel.module_path": {"value": "some.module"},
+ "search.engine.web.parallel.class_name": {
+ "value": "ParallelEngine"
+ },
+ "search.engine.web.searxng.module_path": {"value": "some.module"},
+ "search.engine.web.searxng.class_name": {"value": "SearxngEngine"},
+ }
+
+ engine = ParallelSearchEngine(
+ llm=Mock(),
+ settings_snapshot=settings,
+ programmatic_mode=True,
+ )
+
+ assert "meta" not in engine.available_engines
+ assert "auto" not in engine.available_engines
+ # 'parallel' key in config is also excluded by name check
+ assert "searxng" in engine.available_engines
+
+
+class TestConcurrentExecution:
+ """Tests for ThreadPoolExecutor concurrent execution and result merging."""
+
+ def test_concurrent_execution_merges_results_with_engine_tag(
+ self, mock_load_engine_class, mock_executor
+ ):
+ """Real ThreadPoolExecutor run -> results tagged with search_engine key."""
+ mock_load_engine_class.return_value = (
+ True,
+ make_engine_class(is_public=True, is_generic=True),
+ None,
+ )
+
+ # Use a real ThreadPoolExecutor
+ real_executor = concurrent.futures.ThreadPoolExecutor(max_workers=2)
+ mock_executor.return_value = real_executor
+
+ settings = {
+ "search.engine.web.engine_a.module_path": {"value": "some.module"},
+ "search.engine.web.engine_a.class_name": {"value": "EngineA"},
+ }
+
+ engine = ParallelSearchEngine(
+ llm=Mock(),
+ settings_snapshot=settings,
+ programmatic_mode=True,
+ )
+
+ # Mock select_engines to return specific engines
+ engine.select_engines = Mock(return_value=["engine_a"])
+
+ # Mock _execute_single_engine to return tagged results
+ def mock_execute(engine_name, query):
+ return {
+ "engine": engine_name,
+ "success": True,
+ "results": [
+ {
+ "title": f"Result from {engine_name}",
+ "url": "http://a.com",
+ }
+ ],
+ "count": 1,
+ }
+
+ engine._execute_single_engine = mock_execute
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.parallel_search_engine.SocketIOService"
+ ):
+ results = engine._get_previews("test query")
+
+ real_executor.shutdown(wait=False)
+
+ assert len(results) >= 1
+ assert results[0]["search_engine"] == "engine_a"
+
+ def test_future_exception_records_failure(
+ self, mock_load_engine_class, mock_executor
+ ):
+ """Engine failure in thread -> recorded, other engines still return results."""
+ mock_load_engine_class.return_value = (
+ True,
+ make_engine_class(is_public=True, is_generic=True),
+ None,
+ )
+
+ real_executor = concurrent.futures.ThreadPoolExecutor(max_workers=2)
+ mock_executor.return_value = real_executor
+
+ settings = {
+ "search.engine.web.good_engine.module_path": {
+ "value": "some.module"
+ },
+ "search.engine.web.good_engine.class_name": {"value": "GoodEngine"},
+ "search.engine.web.bad_engine.module_path": {
+ "value": "some.module"
+ },
+ "search.engine.web.bad_engine.class_name": {"value": "BadEngine"},
+ }
+
+ engine = ParallelSearchEngine(
+ llm=Mock(),
+ settings_snapshot=settings,
+ programmatic_mode=True,
+ )
+
+ engine.select_engines = Mock(return_value=["good_engine", "bad_engine"])
+
+ def mock_execute(engine_name, query):
+ if engine_name == "bad_engine":
+ raise RuntimeError("Engine crashed")
+ return {
+ "engine": engine_name,
+ "success": True,
+ "results": [{"title": "Good result", "url": "http://good.com"}],
+ "count": 1,
+ }
+
+ engine._execute_single_engine = mock_execute
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.parallel_search_engine.SocketIOService"
+ ):
+ results = engine._get_previews("test query")
+
+ real_executor.shutdown(wait=False)
+
+ # Good engine results should still be present
+ assert any(r.get("title") == "Good result" for r in results)
+
+
+class TestSelectEnginesEdgeCases:
+ """Tests for edge cases in engine selection."""
+
+ def test_select_engines_llm_out_of_range_index_ignored(
+ self, mock_load_engine_class, mock_executor
+ ):
+ """Invalid LLM-returned index is silently skipped."""
+ mock_load_engine_class.return_value = (
+ True,
+ make_engine_class(is_public=True),
+ None,
+ )
+ mock_executor.return_value = Mock()
+
+ settings = {
+ "search.engine.web.arxiv.module_path": {"value": "some.module"},
+ "search.engine.web.arxiv.class_name": {"value": "ArxivEngine"},
+ }
+
+ mock_llm = Mock()
+ # LLM returns out-of-range indices
+ mock_llm.invoke.return_value = Mock(content="[0, 99, -1]")
+
+ engine = ParallelSearchEngine(
+ llm=mock_llm,
+ settings_snapshot=settings,
+ programmatic_mode=True,
+ include_generic_engines=False,
+ )
+
+ selected = engine.select_engines("test query")
+
+ # Only index 0 is valid (arxiv), indices 99 and -1 are out of range
+ # The engine should handle this gracefully
+ assert isinstance(selected, list)
+ # Valid index 0 should be included if it maps to an available engine
+ if engine.available_engines:
+ assert all(e in engine.available_engines for e in selected)
diff --git a/tests/web_search_engines/test_search_engine_base_retry.py b/tests/web_search_engines/test_search_engine_base_retry.py
new file mode 100644
index 0000000000..95cf6a756b
--- /dev/null
+++ b/tests/web_search_engines/test_search_engine_base_retry.py
@@ -0,0 +1,215 @@
+"""Tests for BaseSearchEngine retry logic, context management, and lifecycle.
+
+The tenacity retry decorator path in search_engine_base.py:330-469 had zero
+tests exercising actual retry behavior. These tests cover the retry flow,
+rate limiting integration, and context manager lifecycle.
+"""
+
+from unittest.mock import Mock, patch
+
+
+from local_deep_research.web_search_engines.rate_limiting import RateLimitError
+from local_deep_research.web_search_engines.search_engine_base import (
+ BaseSearchEngine,
+)
+
+
+class ConcreteSearchEngine(BaseSearchEngine):
+ """Concrete implementation of BaseSearchEngine for testing."""
+
+ def __init__(self, previews_func=None, **kwargs):
+ super().__init__(**kwargs)
+ self._previews_func = previews_func
+
+ def _get_previews(self, query):
+ if self._previews_func:
+ return self._previews_func(query)
+ return []
+
+ def _get_full_content(self, relevant_items):
+ return relevant_items
+
+
+class TestRetryOnRateLimit:
+ """Tests for retry behavior when rate limiting is enabled."""
+
+ def test_retry_on_rate_limit_when_enabled(self):
+ """With rate_tracker.enabled=True, RateLimitError triggers retry
+ up to 3 attempts before exhaustion."""
+ call_count = 0
+
+ def previews_func(query):
+ nonlocal call_count
+ call_count += 1
+ if call_count < 3:
+ raise RateLimitError("rate limited")
+ return [{"title": "Success", "snippet": "found it"}]
+
+ tracker = Mock()
+ tracker.enabled = True
+ tracker.get_wait_time.return_value = 0.0
+
+ engine = ConcreteSearchEngine(
+ previews_func=previews_func,
+ programmatic_mode=True,
+ settings_snapshot={},
+ )
+ engine.rate_tracker = tracker
+
+ results = engine.run("test query")
+
+ assert call_count == 3
+ assert len(results) == 1
+ assert results[0]["title"] == "Success"
+
+ def test_exhausted_retries_returns_empty_list(self):
+ """All 3 attempts fail with RateLimitError -> RetryError caught -> returns []."""
+
+ def always_fail(query):
+ raise RateLimitError("always rate limited")
+
+ tracker = Mock()
+ tracker.enabled = True
+ tracker.get_wait_time.return_value = 0.0
+
+ engine = ConcreteSearchEngine(
+ previews_func=always_fail,
+ programmatic_mode=True,
+ settings_snapshot={},
+ )
+ engine.rate_tracker = tracker
+
+ results = engine.run("test query")
+
+ assert results == []
+
+ def test_first_attempt_success_records_outcome(self):
+ """Successful first attempt calls record_outcome with success=True."""
+
+ def success_func(query):
+ return [{"title": "Result", "snippet": "text"}]
+
+ tracker = Mock()
+ tracker.enabled = True
+ tracker.get_wait_time.return_value = 0.0
+
+ engine = ConcreteSearchEngine(
+ previews_func=success_func,
+ programmatic_mode=True,
+ settings_snapshot={},
+ )
+ engine.rate_tracker = tracker
+
+ results = engine.run("test query")
+
+ assert len(results) == 1
+ # record_outcome should be called with success=True
+ tracker.record_outcome.assert_called()
+ call_kwargs = tracker.record_outcome.call_args
+ assert call_kwargs[1].get("success") or call_kwargs[0][2] is True
+
+ def test_rate_limit_disabled_treats_as_regular_error(self):
+ """With rate_tracker.enabled=False, RateLimitError returns []
+ without retry."""
+ call_count = 0
+
+ def rate_limited(query):
+ nonlocal call_count
+ call_count += 1
+ raise RateLimitError("rate limited")
+
+ tracker = Mock()
+ tracker.enabled = False
+
+ engine = ConcreteSearchEngine(
+ previews_func=rate_limited,
+ programmatic_mode=True,
+ settings_snapshot={},
+ )
+ engine.rate_tracker = tracker
+
+ results = engine.run("test query")
+
+ assert results == []
+ assert call_count == 1 # No retry
+
+
+class TestContextManagerLifecycle:
+ """Tests for __enter__/__exit__ and close() lifecycle."""
+
+ def test_context_manager_enter_exit_lifecycle(self):
+ """__enter__ returns self, __exit__ calls close()."""
+ engine = ConcreteSearchEngine(
+ programmatic_mode=True, settings_snapshot={}
+ )
+
+ result = engine.__enter__()
+ assert result is engine
+
+ # __exit__ should call close() and return False
+ engine.session = Mock()
+ exit_result = engine.__exit__(None, None, None)
+ assert exit_result is False
+ engine.session.close.assert_called_once()
+
+ def test_close_handles_missing_session(self):
+ """close() on engine without session attribute doesn't crash."""
+ engine = ConcreteSearchEngine(
+ programmatic_mode=True, settings_snapshot={}
+ )
+ # Don't set session attribute
+ assert not hasattr(engine, "session")
+
+ # Should not raise
+ engine.close()
+
+ def test_close_handles_none_session(self):
+ """close() with session=None doesn't crash."""
+ engine = ConcreteSearchEngine(
+ programmatic_mode=True, settings_snapshot={}
+ )
+ engine.session = None
+
+ # Should not raise
+ engine.close()
+
+
+class TestSearchContextPropagation:
+ """Tests for research_context propagation in run()."""
+
+ def test_search_context_set_and_cleared_in_finally(self):
+ """research_context propagated via set_search_context / clear_search_context
+ in run(), cleared even on exception."""
+
+ def failing_previews(query):
+ raise ValueError("search failed")
+
+ engine = ConcreteSearchEngine(
+ previews_func=failing_previews,
+ programmatic_mode=False,
+ settings_snapshot={},
+ )
+ engine.rate_tracker = Mock(enabled=False)
+
+ context = {"research_id": "test-123"}
+
+ with (
+ patch(
+ "local_deep_research.web_search_engines.search_engine_base.set_search_context"
+ ) as mock_set,
+ patch(
+ "local_deep_research.web_search_engines.search_engine_base.clear_search_context"
+ ) as mock_clear,
+ patch(
+ "local_deep_research.metrics.search_tracker.get_search_tracker",
+ return_value=Mock(),
+ ),
+ ):
+ results = engine.run("test query", research_context=context)
+
+ # Context should have been set
+ mock_set.assert_called_once_with(context)
+ # Context should have been cleared in finally block
+ mock_clear.assert_called_once()
+ # Should return empty list after exception
+ assert results == []