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.

feat!: remove the auto and parallel meta search engines (#4534)

LearningCircuit81e7a5707af4
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
index c7f9b7f460..530c575e4c 100644
--- a/.github/CODEOWNERS
+++ b/.github/CODEOWNERS
@@ -113,7 +113,6 @@
# Search engine settings (schema only, no secrets)
/src/local_deep_research/defaults/settings/search_engines/elasticsearch.json @scottvr @tombii @prashant-sharma-cmd @elpikola @shreydekate @LearningCircuit @hashedviking @djpetti
/src/local_deep_research/defaults/settings/search_engines/paperless.json @scottvr @tombii @prashant-sharma-cmd @elpikola @shreydekate @LearningCircuit @hashedviking @djpetti
-/src/local_deep_research/defaults/settings/search_engines/parallel.json @scottvr @tombii @prashant-sharma-cmd @elpikola @shreydekate @LearningCircuit @hashedviking @djpetti
/src/local_deep_research/defaults/settings/search_engines/scaleserp.json @scottvr @tombii @prashant-sharma-cmd @elpikola @shreydekate @LearningCircuit @hashedviking @djpetti
/src/local_deep_research/defaults/settings/search_engines/serper.json @scottvr @tombii @prashant-sharma-cmd @elpikola @shreydekate @LearningCircuit @hashedviking @djpetti
diff --git a/.pre-commit-hooks/recommend-performance-tests.py b/.pre-commit-hooks/recommend-performance-tests.py
index b480c31a35..7304b2b649 100755
--- a/.pre-commit-hooks/recommend-performance-tests.py
+++ b/.pre-commit-hooks/recommend-performance-tests.py
@@ -43,7 +43,7 @@ PATH_RULES = [
"prefixes": ("src/local_deep_research/web_search_engines/engines/",),
"fast_tests": [
"tests/web_search_engines/test_search_engine_base.py",
- "tests/web_search_engines/test_parallel_search_engine.py",
+ "tests/web_search_engines/engines/test_full_search.py",
],
"perf_dir": "tests/performance/search_engines/",
"perf_exists": True,
@@ -53,7 +53,7 @@ PATH_RULES = [
"prefixes": ("src/local_deep_research/web_search_engines/",),
"fast_tests": [
"tests/web_search_engines/test_search_engine_base.py",
- "tests/web_search_engines/test_parallel_search_engine.py",
+ "tests/web_search_engines/test_search_engine_factory.py",
],
"perf_dir": None,
"perf_exists": False,
diff --git a/README.md b/README.md
index 2c1f16a2a1..ccd68ec6f7 100644
--- a/README.md
+++ b/README.md
@@ -472,6 +472,7 @@ search(query="copyright fair use precedents", engine="openclaw")
### Upgrading from earlier versions
- **`llm.model` no longer has a default.** Pre-1.7 installs auto-filled `gemma3:12b` (Ollama) when no model was configured, which silently downloaded a multi-GB binary. The field is now empty by default — pick a model in Settings → LLM, or research will fail loudly with a clear error.
+- **The `auto` and `parallel` meta search engines were removed.** The default langgraph-agent strategy selects engines dynamically per query, which replaces them. Stored settings are migrated automatically (removed values become `searxng`); update any explicit `search_tool="auto"` API calls or `LDR_SEARCH_TOOL=auto` env overrides to a concrete engine such as `searxng`.
- **The `llamacpp` provider now uses HTTP instead of in-process loading.** If you previously set `llm.llamacpp_model_path` to a local `.gguf` file, that setting is no longer read. Instead, run `llama-server -m <your-model.gguf>` (it ships with every modern llama.cpp build) and the default `llm.llamacpp.url` of `http://localhost:8080/v1` will pick it up. Optional API key support is available via `llm.llamacpp.api_key` if you put `llama-server` behind an auth proxy.
## 📚 Documentation
diff --git a/changelog.d/+egress-adaptive-default-upgrade-note.breaking.md b/changelog.d/+egress-adaptive-default-upgrade-note.breaking.md
index bd53d87406..676dc70410 100644
--- a/changelog.d/+egress-adaptive-default-upgrade-note.breaking.md
+++ b/changelog.d/+egress-adaptive-default-upgrade-note.breaking.md
@@ -1 +1 @@
-**Upgrade behaviour change:** the default egress scope is now `adaptive` (was effectively `both`). Adaptive follows your primary search engine, so on upgrade a config with a *concrete* primary may narrow: a public primary (e.g. SearXNG/arXiv) now excludes local collections (public-only behaviour), and a *private collection* primary forces local LLM + embeddings. A meta-picker primary (`auto`/`parallel`) is unaffected (resolves to `both`). To keep the previous "any engine, cloud inference" behaviour, set Egress Scope to **Both**. See docs/egress-modes.md.
+**Upgrade behaviour change:** the default egress scope is now `adaptive` (was effectively `both`). Adaptive follows your primary search engine, so on upgrade a config with a *concrete* primary may narrow: a public primary (e.g. SearXNG/arXiv) now excludes local collections (public-only behaviour), and a *private collection* primary forces local LLM + embeddings. To keep the previous "any engine, cloud inference" behaviour, set Egress Scope to **Both**. See docs/egress-modes.md.
diff --git a/changelog.d/+remove-auto-parallel-engines.breaking.md b/changelog.d/+remove-auto-parallel-engines.breaking.md
new file mode 100644
index 0000000000..344b38d7bb
--- /dev/null
+++ b/changelog.d/+remove-auto-parallel-engines.breaking.md
@@ -0,0 +1 @@
+**The `auto` and `parallel` meta search engines have been removed** (including the `meta` and `parallel_scientific` aliases). The default langgraph-agent strategy replaces them — it selects search engines dynamically per query, so a separate LLM-based engine picker is redundant. Stored values (`search.tool` setting, news subscriptions, queued researches, saved benchmark configs) are migrated automatically on upgrade (migration 0013; `search.tool` values pointing at a removed engine become `searxng`). **What to do:** API callers passing `search_tool="auto"` or `"parallel"` must pick a concrete engine (e.g. `searxng`), and `LDR_SEARCH_TOOL=auto` environment overrides must be updated likewise.
diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md
index a908fb7c15..e12694e852 100644
--- a/docs/CONFIGURATION.md
+++ b/docs/CONFIGURATION.md
@@ -191,7 +191,7 @@ They are not available in the Web UI because they are needed to start the applic
| `notifications.rate_limit_per_day` | `LDR_NOTIFICATIONS_RATE_LIMIT_PER_DAY` | `50` | Maximum number of notifications per day per user. Daily cap prevents notification fatigue. Default of 50 balances staying informed with avoiding excessive alerts. | APP |
| `notifications.rate_limit_per_hour` | `LDR_NOTIFICATIONS_RATE_LIMIT_PER_HOUR` | `10` | Maximum number of notifications per hour per user. Prevents notification spam during burst activity. Default of 10 allows important notifications through while limiting noise. | APP |
| `notifications.service_url` | `LDR_NOTIFICATIONS_SERVICE_URL` | `` | Notification service URL(s). Supports multiple comma-separated URLs to send notifications to multiple destinations (e.g., discord://YOUR_WEBHOOK_ID/YOUR_TOKEN, mailto://YOUR_USER:[email protected][email protected]). See <a href="https://github.com/LearningCircuit/local-deep-research/blob/main/docs/NOTIFICATIONS.md" target="_blank">documentation</a> for supported services. | APP |
-| `policy.egress_scope` | `LDR_POLICY_EGRESS_SCOPE` | `adaptive` | EXPERIMENTAL — this egress boundary is new defense-in-depth, not an absolute guarantee yet; don't rely on it as your only protection for highly sensitive data. Restrict which search engines a research run may use. ADAPTIVE (default) = follow your primary engine: a private primary keeps everything local, a public primary allows public engines, a meta-picker allows both. STRICT = only the primary engine you picked; PUBLIC_ONLY = any public web/academic engine; PRIVATE_ONLY = any local engine (library, paperless, etc.); BOTH = any classified engine. STRICT is incompatible with auto/meta/parallel primaries. | SEARCH |
+| `policy.egress_scope` | `LDR_POLICY_EGRESS_SCOPE` | `adaptive` | EXPERIMENTAL — this egress boundary is new defense-in-depth, not an absolute guarantee yet; don't rely on it as your only protection for highly sensitive data. Restrict which search engines a research run may use. ADAPTIVE (default) = follow your primary engine: a private primary keeps everything local, a public primary allows public engines. STRICT = only the primary engine you picked; PUBLIC_ONLY = any public web/academic engine; PRIVATE_ONLY = any local engine (library, paperless, etc.); BOTH = any classified engine. | SEARCH |
| `rag.indexing_batch_size` | `LDR_RAG_INDEXING_BATCH_SIZE` | `15` | Number of documents to process in parallel during RAG indexing. Higher values are faster but use more memory. | APP |
| `rate_limiting.decay_per_day` | `LDR_RATE_LIMITING_DECAY_PER_DAY` | `0.95` | How much to trust old rate limit data as it ages (0.5-0.99). At 0.95, data retains 95% reliability per day. Lower values discard old data faster, forcing the system to re-learn optimal wait times. | APP |
| `rate_limiting.enabled` | `LDR_RATE_LIMITING_ENABLED` | `true` | Enable adaptive rate limiting that learns optimal wait times for each search engine to avoid hitting API rate limits. When disabled, requests are sent with minimal delay (0.1s), which may trigger rate limit errors from some APIs. | APP |
@@ -216,15 +216,6 @@ They are not available in the Web UI because they are needed to start the applic
| `search.cross_engine_max_context_items` | `LDR_SEARCH_CROSS_ENGINE_MAX_CONTEXT_ITEMS` | `30` | Maximum number of search result previews sent to the LLM for relevance ranking during cross-engine filtering. Higher values let the model evaluate more candidates, improving recall at the cost of increased prompt size and latency. | SEARCH |
| `search.cross_engine_max_results` | `LDR_SEARCH_CROSS_ENGINE_MAX_RESULTS` | `100` | Maximum number of search results to keep after cross-engine filtering. When results from multiple search engines are combined, this limits how many total results are displayed. Higher values show more comprehensive results. | SEARCH |
| `search.engine.DEFAULT_SEARCH_ENGINE` | `LDR_SEARCH_ENGINE_DEFAULT_SEARCH_ENGINE` | `wikipedia` | Fallback search engine used when the configured engine is unavailable or has errors. | SEARCH |
-| `search.engine.auto.default_params.max_engines_to_try` | `LDR_SEARCH_ENGINE_AUTO_DEFAULT_PARAMS_MAX_ENGINES_TO_TRY` | `3` | Maximum number of search engines to try before returning results. Auto mode selects the best engine(s) based on your query type. | SEARCH |
-| `search.engine.auto.default_params.use_api_key_services` | `LDR_SEARCH_ENGINE_AUTO_DEFAULT_PARAMS_USE_API_KEY_SERVICES` | `true` | Whether to include paid API services (Brave, SerpAPI, etc.) in auto-selection. Disable to only use free search engines. | SEARCH |
-| `search.engine.auto.description` | `LDR_SEARCH_ENGINE_AUTO_DESCRIPTION` | `Attempt to choose the best combination of search engines automatically.` | Human-readable description of the search engine. | SEARCH |
-| `search.engine.auto.display_name` | `LDR_SEARCH_ENGINE_AUTO_DISPLAY_NAME` | `Auto` | Display name to use in the U.I. for this search engine. | SEARCH |
-| `search.engine.auto.reliability` | `LDR_SEARCH_ENGINE_AUTO_RELIABILITY` | `0.85` | Reliability rating for auto mode. Varies based on which underlying engine is selected. | SEARCH |
-| `search.engine.auto.requires_api_key` | `LDR_SEARCH_ENGINE_AUTO_REQUIRES_API_KEY` | `false` | Whether auto mode requires API keys. False because it can fall back to free engines like Wikipedia. | SEARCH |
-| `search.engine.auto.requires_llm` | `LDR_SEARCH_ENGINE_AUTO_REQUIRES_LLM` | `true` | Whether auto mode uses LLM to select the best engine. When disabled, falls back to rule-based selection. | SEARCH |
-| `search.engine.auto.strengths` | `LDR_SEARCH_ENGINE_AUTO_STRENGTHS` | ``["intelligent engine selection", "adaptable to query type", "fallback capabilities"]`` | Key advantages of auto mode: Intelligently selects the best engine for each query type, tries multiple sources if needed. | SEARCH |
-| `search.engine.auto.weaknesses` | `LDR_SEARCH_ENGINE_AUTO_WEAKNESSES` | ``["slightly slower due to LLM analysis"]`` | Limitations of auto mode: May use more API calls trying multiple engines, selection heuristics may not always be optimal. | SEARCH |
| `search.engine.web.arxiv.default_params.max_results` | `LDR_SEARCH_ENGINE_WEB_ARXIV_DEFAULT_PARAMS_MAX_RESULTS` | `20` | Maximum number of papers to retrieve from arXiv per search query. | SEARCH |
| `search.engine.web.arxiv.default_params.sort_by` | `LDR_SEARCH_ENGINE_WEB_ARXIV_DEFAULT_PARAMS_SORT_BY` | `relevance` | How to sort arXiv results: 'relevance' for best match, 'lastUpdatedDate' for recently updated, 'submittedDate' for newest submissions. | SEARCH |
| `search.engine.web.arxiv.default_params.sort_order` | `LDR_SEARCH_ENGINE_WEB_ARXIV_DEFAULT_PARAMS_SORT_ORDER` | `descending` | Sort order for arXiv results: 'descending' (newest/most relevant first) or 'ascending' (oldest/least relevant first). | SEARCH |
@@ -375,18 +366,6 @@ They are not available in the Web UI because they are needed to start the applic
| `search.engine.web.paperless.strengths` | `LDR_SEARCH_ENGINE_WEB_PAPERLESS_STRENGTHS` | ``["personal documents", "OCR-processed content", "tagged and organized", "full-text search", "no rate limits", "private data"]`` | Strengths of this search engine | SEARCH |
| `search.engine.web.paperless.supports_full_search` | `LDR_SEARCH_ENGINE_WEB_PAPERLESS_SUPPORTS_FULL_SEARCH` | `true` | Whether this engine supports full document search | SEARCH |
| `search.engine.web.paperless.weaknesses` | `LDR_SEARCH_ENGINE_WEB_PAPERLESS_WEAKNESSES` | ``["keyword-based search only", "no semantic understanding", "limited query operators"]`` | Weaknesses of this search engine | SEARCH |
-| `search.engine.web.parallel.default_params.allow_local_engines` | `LDR_SEARCH_ENGINE_WEB_PARALLEL_DEFAULT_PARAMS_ALLOW_LOCAL_ENGINES` | `false` | ⚠️ PRIVACY WARNING: Allow local/private document engines in parallel search. This may expose personal data from your documents to web search queries and LLMs. Only enable if you understand the privacy implications. | SEARCH |
-| `search.engine.web.parallel.default_params.enable_llm_relevance_filter` | `LDR_SEARCH_ENGINE_WEB_PARALLEL_DEFAULT_PARAMS_ENABLE_LLM_RELEVANCE_FILTER` | `true` | Enable LLM-based relevance filtering to improve result quality by filtering out irrelevant results. This adds an extra LLM call but significantly improves result relevance. | SEARCH |
-| `search.engine.web.parallel.default_params.max_engines_to_select` | `LDR_SEARCH_ENGINE_WEB_PARALLEL_DEFAULT_PARAMS_MAX_ENGINES_TO_SELECT` | `5` | Maximum number of search engines to select and run in parallel | SEARCH |
-| `search.engine.web.parallel.default_params.use_api_key_services` | `LDR_SEARCH_ENGINE_WEB_PARALLEL_DEFAULT_PARAMS_USE_API_KEY_SERVICES` | `true` | Include search engines that require API keys | SEARCH |
-| `search.engine.web.parallel.description` | `LDR_SEARCH_ENGINE_WEB_PARALLEL_DESCRIPTION` | `Executes multiple search engines in parallel and combines their results. Uses LLM to select the most appropriate engines for each query.` | Human-readable description of the search engine. | SEARCH |
-| `search.engine.web.parallel.display_name` | `LDR_SEARCH_ENGINE_WEB_PARALLEL_DISPLAY_NAME` | `Parallel Search` | Display name to use in the U.I. for this search engine. | SEARCH |
-| `search.engine.web.parallel.reliability` | `LDR_SEARCH_ENGINE_WEB_PARALLEL_RELIABILITY` | `0.9` | Reliability of the parallel search engine | SEARCH |
-| `search.engine.web.parallel.requires_api_key` | `LDR_SEARCH_ENGINE_WEB_PARALLEL_REQUIRES_API_KEY` | `false` | Whether this search engine requires an API key | SEARCH |
-| `search.engine.web.parallel.requires_llm` | `LDR_SEARCH_ENGINE_WEB_PARALLEL_REQUIRES_LLM` | `true` | Whether this search engine requires an LLM for engine selection | SEARCH |
-| `search.engine.web.parallel.strengths` | `LDR_SEARCH_ENGINE_WEB_PARALLEL_STRENGTHS` | `["Comprehensive results from multiple sources", "Parallel execution for faster results", "Intelligent engine selection", "Automatic deduplication", "Combines strengths of all engines"]` | Strengths of this search engine | SEARCH |
-| `search.engine.web.parallel.supports_full_search` | `LDR_SEARCH_ENGINE_WEB_PARALLEL_SUPPORTS_FULL_SEARCH` | `false` | Whether this search engine supports full document search | SEARCH |
-| `search.engine.web.parallel.weaknesses` | `LDR_SEARCH_ENGINE_WEB_PARALLEL_WEAKNESSES` | `["Higher resource usage", "May hit rate limits on multiple engines", "Results may vary in quality", "Requires LLM for optimal selection"]` | Weaknesses of this search engine | SEARCH |
| `search.engine.web.pubchem` | `LDR_SEARCH_ENGINE_WEB_PUBCHEM` | ``{"requires_api_key": false, "requires_llm": true, "description": "Search millions of chemical compounds with structures, properties, and bioactivity data.", "reliability": 0.95}`` | PubChem search engine configuration | SEARCH |
| `search.engine.web.pubchem.default_params.include_synonyms` | `LDR_SEARCH_ENGINE_WEB_PUBCHEM_DEFAULT_PARAMS_INCLUDE_SYNONYMS` | `true` | Include compound synonyms in full content results. | SEARCH |
| `search.engine.web.pubchem.default_params.max_results` | `LDR_SEARCH_ENGINE_WEB_PUBCHEM_DEFAULT_PARAMS_MAX_RESULTS` | `10` | Maximum number of results to retrieve from PubChem. | SEARCH |
@@ -579,7 +558,7 @@ They are not available in the Web UI because they are needed to start the applic
| `search.skip_relevance_filter` | `LDR_SEARCH_SKIP_RELEVANCE_FILTER` | `true` | When checked, LLM-based relevance filtering is suppressed for general-purpose search engines that do not require it. Keyword-based engines (arXiv, PubMed, Wikipedia, GitHub, etc.) always run the filter regardless of this checkbox; per-engine settings override both. | SEARCH |
| `search.snippets_only` | `LDR_SEARCH_SNIPPETS_ONLY` | `true` | Only retrieve search snippets instead of full webpage content. Reduces API usage and processing time, but provides less context for analysis. | SEARCH |
| `search.time_period` | `LDR_SEARCH_TIME_PERIOD` | `y` | Time range filter for search results. Limits results to content published within the specified period (day, week, month, year, or all time). | SEARCH |
-| `search.tool` | `LDR_SEARCH_TOOL` | `searxng` | Search engine to use for research queries. 'Auto' intelligently selects the best engine for each query type. Each engine may require its own API key or service to be configured separately. | SEARCH |
+| `search.tool` | `LDR_SEARCH_TOOL` | `searxng` | Search engine to use for research queries. The default langgraph-agent strategy can additionally pick specialized engines per query as tools. Each engine may require its own API key or service to be configured separately. | SEARCH |
| `security.account_lockout_duration_minutes` | `LDR_SECURITY_ACCOUNT_LOCKOUT_DURATION_MINUTES` | `15` | Duration in minutes that an account remains locked after exceeding the failed login threshold. Only configurable via environment variable (LDR_SECURITY_ACCOUNT_LOCKOUT_DURATION_MINUTES). | APP |
| `security.account_lockout_threshold` | `LDR_SECURITY_ACCOUNT_LOCKOUT_THRESHOLD` | `10` | Number of consecutive failed login attempts before an account is temporarily locked out. Only configurable via environment variable (LDR_SECURITY_ACCOUNT_LOCKOUT_THRESHOLD). | APP |
| `security.rate_limit_default` | `LDR_SECURITY_RATE_LIMIT_DEFAULT` | `5000 per hour;50000 per day` | Default rate limit for all HTTP endpoints. Configured via LDR_SECURITY_RATE_LIMIT_DEFAULT environment variable. Multiple limits can be separated by semicolons (e.g., '5000 per hour;50000 per day'). Format: 'N per hour/minute/day'. Requires server restart. | APP |
diff --git a/docs/LANGCHAIN_RETRIEVER_INTEGRATION.md b/docs/LANGCHAIN_RETRIEVER_INTEGRATION.md
index 11d89a3dc7..2b237f5c1c 100644
--- a/docs/LANGCHAIN_RETRIEVER_INTEGRATION.md
+++ b/docs/LANGCHAIN_RETRIEVER_INTEGRATION.md
@@ -51,7 +51,9 @@ result = detailed_research(
"graph_db": graph_retriever,
"sql_db": sql_retriever
},
- search_tool="auto" # Use all retrievers
+ search_tool="vector_db" # Primary retriever; with the default
+ # langgraph-agent strategy, every registered retriever is also
+ # exposed to the research agent as a search tool
)
```
@@ -61,8 +63,8 @@ result = detailed_research(
result = quick_summary(
query="Compare internal and external practices",
retrievers={"internal": internal_retriever},
- search_tool="auto",
- search_engines=["internal", "wikipedia", "searxng"]
+ search_tool="searxng" # Web engine as primary; the langgraph-agent
+ # strategy can also query the registered "internal" retriever
)
```
@@ -100,8 +102,7 @@ Any LangChain `BaseRetriever` implementation works:
All research functions (`quick_summary`, `detailed_research`, `generate_report`) accept:
- `retrievers`: Optional[Dict[str, BaseRetriever]] - Dictionary of retrievers
-- `search_tool`: str - Name of retriever to use (or "auto" for all)
-- `search_engines`: List[str] - Specific engines/retrievers to use with meta search
+- `search_tool`: str - Name of the retriever (or built-in engine) to use as the primary search source
### Example with Complex Setup
@@ -138,7 +139,7 @@ result = quick_summary(
## Benefits
1. **Zero Coupling**: LDR doesn't need to know retriever internals
-2. **Full Compatibility**: Works with all LDR features (strategies, meta search, etc.)
+2. **Full Compatibility**: Works with all LDR features (strategies, agentic engine selection, etc.)
3. **Clean API**: Just pass a dictionary of retrievers
4. **Flexible**: Mix retrievers with web search seamlessly
diff --git a/docs/cli-tools.md b/docs/cli-tools.md
index ca646023ca..77df6c4b59 100644
--- a/docs/cli-tools.md
+++ b/docs/cli-tools.md
@@ -254,7 +254,7 @@ Set via Claude Desktop config `env` block or shell environment:
| `LDR_LLM_PROVIDER` | LLM provider | `openai`, `ollama`, `anthropic` |
| `LDR_LLM_MODEL` | Model name | `gpt-4`, `llama3:8b` |
| `LDR_LLM_OPENAI_API_KEY` | OpenAI API key | `sk-...` |
-| `LDR_SEARCH_TOOL` | Default search engine | `auto`, `arxiv`, `wikipedia` |
+| `LDR_SEARCH_TOOL` | Default search engine | `searxng`, `arxiv`, `wikipedia` |
| `LDR_SEARCH_SEARCH_STRATEGY` | Default strategy | `source-based`, `focused-iteration` |
See [MCP Server Guide](mcp-server.md) for full documentation.
diff --git a/docs/developing/resource-cleanup.md b/docs/developing/resource-cleanup.md
index ec9196f2ee..7f5f77abd6 100644
--- a/docs/developing/resource-cleanup.md
+++ b/docs/developing/resource-cleanup.md
@@ -354,9 +354,9 @@ here is the full ledger:
- **Daemon threads without explicit shutdown.** `search_cache.py`
cache-cleanup thread, `journal_reputation_filter.py` background
- fetcher, `log_utils.py` queue processor, `parallel_search_engine.py`
- global executor. All daemonized — reaped by the OS at process exit.
- Not steady-state leaks; no per-request growth.
+ fetcher, `log_utils.py` queue processor. All daemonized — reaped by
+ the OS at process exit. Not steady-state leaks; no per-request
+ growth.
- **Abandoned-research thread on socket disconnect.** If a client
closes the tab mid-research, the socket subscription is removed but
the research thread keeps running until completion;
diff --git a/docs/egress-modes.md b/docs/egress-modes.md
index 6935ab0f78..0e7da1a44d 100644
--- a/docs/egress-modes.md
+++ b/docs/egress-modes.md
@@ -41,8 +41,6 @@ mode for each run:
arXiv, PubMed) → behaves like **Public only**.
- Primary is a **private** source (a local collection, your library) →
behaves like **Private only** (and therefore forces local LLM + embeddings).
-- Primary is a **meta-picker** (`auto`, `parallel`, `meta`) → behaves like
- **Both** (the meta-picker fans out to whatever fits).
Why it's the default: you choose a search engine anyway, and the privacy
posture "just matches" it. If you make a **private collection** your primary,
@@ -81,8 +79,7 @@ connections. **Nothing leaves the machine.**
## <a id="strict"></a>🎯 Strict
The tightest mode: **only your single primary engine** runs — no expansion to
-any other engine at all. (It's incompatible with a meta-picker primary like
-`auto`/`parallel`, since those have no single concrete engine.) At the URL
+any other engine at all. At the URL
layer it behaves like Private-only (private hosts allowed, public blocked), but
it does **not** force local inference — set the *Require local* toggles if you
also want local LLM/embeddings.
diff --git a/docs/faq.md b/docs/faq.md
index 160d86eb02..85ab56e3e6 100644
--- a/docs/faq.md
+++ b/docs/faq.md
@@ -248,7 +248,7 @@ After installing, restart LDR and re-export the PDF.
Solutions:
1. Check status: `python -m local_deep_research.web_search_engines.rate_limiting status`
2. Reset limits: `python -m local_deep_research.web_search_engines.rate_limiting reset`
-3. Use `auto` search tool for automatic fallbacks
+3. Use the langgraph-agent strategy (the default), which can route around rate-limited engines
4. Add premium search engines
### "Invalid value" errors from SearXNG
diff --git a/docs/features.md b/docs/features.md
index 097e48dcb4..969c6c53ff 100644
--- a/docs/features.md
+++ b/docs/features.md
@@ -100,7 +100,7 @@ Simultaneously query multiple search engines for comprehensive results.
### Intelligent Query Routing
-The system automatically selects appropriate search engines based on query type:
+The default langgraph-agent strategy selects appropriate search engines dynamically based on query type:
- Scientific queries → Academic engines
- Code questions → GitHub + technical sources
- General knowledge → Wikipedia + web search
diff --git a/docs/library-and-rag.md b/docs/library-and-rag.md
index 6af9f8a443..0dea95dd99 100644
--- a/docs/library-and-rag.md
+++ b/docs/library-and-rag.md
@@ -152,7 +152,7 @@ Once indexed, search your documents using natural language.
When conducting research, you can:
1. Set search tool to your collection name
2. LDR will search your documents instead of the web
-3. Combine with web search using "auto" mode
+3. Combine with web search via the default langgraph-agent strategy, which can query your collections and web engines in the same run
Example with Python API:
```python
diff --git a/docs/mcp-server.md b/docs/mcp-server.md
index 595e231a3a..7fd7abb19e 100644
--- a/docs/mcp-server.md
+++ b/docs/mcp-server.md
@@ -99,7 +99,7 @@ The MCP server uses the same settings system as the main LDR application. There
| Variable | Description | Example |
|----------|-------------|---------|
-| `LDR_SEARCH_TOOL` | Default search engine | `auto`, `arxiv`, `wikipedia` |
+| `LDR_SEARCH_TOOL` | Default search engine | `searxng`, `arxiv`, `wikipedia` |
| `LDR_SEARCH_SEARCH_STRATEGY` | Default strategy | `source-based`, `focused-iteration` |
| `LDR_SEARCH_ITERATIONS` | Default iteration count | `2` |
| `LDR_SEARCH_QUESTIONS_PER_ITERATION` | Questions per iteration | `3` |
@@ -183,7 +183,7 @@ Fast research summary. Typically takes **1-5 minutes**.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `query` | string | Yes | Research question (max 10,000 chars) |
-| `search_engine` | string | No | Search engine to use (e.g., `"arxiv"`, `"wikipedia"`, `"auto"`) |
+| `search_engine` | string | No | Search engine to use (e.g., `"searxng"`, `"arxiv"`, `"wikipedia"`) |
| `strategy` | string | No | Research strategy (e.g., `"source-based"`, `"focused-iteration"`) |
| `iterations` | integer | No | Number of search iterations (1-10) |
| `questions_per_iteration` | integer | No | Questions per iteration (1-10) |
diff --git a/docs/news-subscriptions.md b/docs/news-subscriptions.md
index 3003b62f3d..236be7340f 100644
--- a/docs/news-subscriptions.md
+++ b/docs/news-subscriptions.md
@@ -57,7 +57,7 @@ Access subscriptions at: `http://localhost:5000/news/subscriptions`
|-------|---------|-------------|
| Model Provider | OLLAMA | LLM provider to use |
| Model | (varies) | Specific model |
-| Search Engine | auto | Search engine to use |
+| Search Engine | (your default search tool) | Search engine to use |
| Iterations | 3 | Research depth |
| Questions per Iteration | 5 | Breadth per cycle |
| Strategy | source-based | Research approach |
@@ -253,7 +253,7 @@ response = requests.post(
"name": "AI Safety Updates",
"refresh_minutes": 1440, # Daily
"model_provider": "ollama",
- "search_engine": "auto",
+ "search_engine": "searxng",
"iterations": 3
},
cookies={"session": your_session_cookie}
diff --git a/docs/search-engines.md b/docs/search-engines.md
index e7b99a7b14..f67216d13c 100644
--- a/docs/search-engines.md
+++ b/docs/search-engines.md
@@ -13,17 +13,20 @@ LDR supports three categories of search engines:
## Search Engine Selection
-### Auto Engine (Recommended)
+### Dynamic Engine Selection (Recommended)
-The `auto` search engine intelligently selects the most appropriate engines based on your query:
+The default `langgraph-agent` strategy selects the most appropriate engines dynamically per query: every enabled engine (and any registered retriever or local collection) is exposed to the research agent as a tool, and the agent decides which to call for each sub-question. You only pick a primary engine (`searxng` is the recommended default):
```python
result = quick_summary(
query="What are the latest advances in quantum computing?",
- search_tool="auto" # Automatically selects best engines
+ search_tool="searxng" # Primary engine; the langgraph-agent strategy
+ # can still pull in other enabled engines per query
)
```
+> **Note**: The former `auto` and `parallel` meta engines were removed — the langgraph-agent strategy replaces them. Stored settings are migrated automatically; explicit `search_tool="auto"` callers should switch to a concrete engine like `searxng`.
+
## Free Search Engines
### Academic Search Engines
@@ -197,12 +200,13 @@ python -m local_deep_research.web_search_engines.rate_limiting reset
LDR supports multiple search strategies that determine how queries are processed:
+- **langgraph-agent**: Agentic research that picks engines dynamically per query (default)
- **source-based**: Single query, fast results
-- **focused_iteration**: Iterative refinement for accuracy (recommended)
+- **focused_iteration**: Iterative refinement for accuracy
## Best Practices
-1. **For General Research**: Use `auto` or `searxng`
+1. **For General Research**: Use `searxng` with the default langgraph-agent strategy
2. **For Academic Research**: Combine `arxiv`, `pubmed`, and `semantic_scholar`
3. **For Technical Questions**: Use `github` with `searxng`
4. **For Maximum Privacy**: Use `searxng` with local Ollama models
@@ -218,7 +222,7 @@ LDR supports multiple search strategies that determine how queries are processed
### Rate Limit Errors
- Wait a few minutes and retry
-- Use `auto` engine for automatic fallbacks
+- Use the langgraph-agent strategy, which can route around rate-limited engines
- Consider adding premium engines for higher limits
### No Results Found
@@ -231,18 +235,11 @@ LDR supports multiple search strategies that determine how queries are processed
### Configuring Search Engines
-You can enable/disable specific search engines and adjust their reliability parameters in the settings. This affects which engines are used in 'auto' mode and how the system handles rate limiting.
+You can enable/disable specific search engines and adjust their reliability parameters in the settings. This affects which engines the langgraph-agent strategy can choose from and how the system handles rate limiting.
-### Parallel Search Configuration
+### Multi-Engine Research
-Adjust parallel search settings:
-```python
-result = quick_summary(
- query="your query",
- max_parallel_searches=5, # Number of engines to query simultaneously
- timeout_per_engine=30 # Seconds per engine
-)
-```
+The former `auto` and `parallel` meta engines (which fanned a query out over several engines) have been removed. To research across multiple engines, use the default langgraph-agent strategy: it calls any enabled engine as a tool, in parallel where useful, and picks per sub-question which engines to query.
## Related Documentation
diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md
index 60353798ae..f1d4da1ee3 100644
--- a/docs/troubleshooting.md
+++ b/docs/troubleshooting.md
@@ -189,10 +189,8 @@ This guide covers common issues and their solutions.
search.rate_limiting.profile = conservative
```
-4. **Use multiple search engines** to distribute load:
- ```
- search.tool = auto # Automatically selects engines
- ```
+4. **Use the langgraph-agent strategy** (the default) to distribute load — it
+ selects engines dynamically per query and can route around rate-limited ones.
### Rate Limiting CLI Commands
diff --git a/examples/api_usage/programmatic/README.md b/examples/api_usage/programmatic/README.md
index d6ac613fc7..d371cc839e 100644
--- a/examples/api_usage/programmatic/README.md
+++ b/examples/api_usage/programmatic/README.md
@@ -49,7 +49,7 @@ result = quick_summary(
- `detailed_research()` - Comprehensive research with findings
- `generate_report()` - Create full markdown reports
- Custom search parameters
-- Different search tools (Wikipedia, auto, etc.)
+- Different search tools (Wikipedia, SearXNG, etc.)
### search_strategies_example.py
**Purpose:** Explain and demonstrate the two main search strategies.
@@ -63,7 +63,6 @@ result = quick_summary(
- Multiple named retrievers for different document types
- Combining custom retrievers with web search
- Source analysis and tracking
-- Meta search configuration
### advanced_features_example.py
**Purpose:** Demonstrate advanced programmatic features and analysis capabilities.
@@ -107,9 +106,11 @@ result = quick_summary(
Available search tools include:
- `wikipedia` - Wikipedia search
- `arxiv` - Academic papers
-- `searxng` - Web search via SearXNG
-- `auto` - Automatically select best tool
-- `meta` - Combine multiple tools
+- `searxng` - Web search via SearXNG (recommended default)
+
+With the default langgraph-agent strategy, the research agent can also call
+other enabled engines dynamically per query — the former `auto`/`meta`
+engines were removed in favor of this.
### Custom Retrievers
You can provide your own retrievers:
diff --git a/examples/api_usage/programmatic/hybrid_search_example.py b/examples/api_usage/programmatic/hybrid_search_example.py
index 6cc5423ed1..9d1ab93f31 100644
--- a/examples/api_usage/programmatic/hybrid_search_example.py
+++ b/examples/api_usage/programmatic/hybrid_search_example.py
@@ -127,10 +127,12 @@ Each provides different perspectives on the same topic.
business_retriever = BusinessDocsRetriever()
kb_retriever = create_knowledge_base_retriever()
- # Configure settings
+ # Configure settings. Registered retrievers are addressable by name;
+ # with the default langgraph-agent strategy, every registered retriever
+ # is also exposed to the research agent as a search tool.
settings = create_settings_snapshot(
{
- "search.tool": "auto", # Will use all provided retrievers
+ "search.tool": "knowledge_base", # Primary retriever
}
)
@@ -143,7 +145,7 @@ Each provides different perspectives on the same topic.
"business": business_retriever,
"knowledge_base": kb_retriever,
},
- search_tool="auto", # Use all retrievers
+ search_tool="knowledge_base", # Primary retriever (others stay available)
iterations=2,
questions_per_iteration=2,
programmatic_mode=True,
@@ -312,56 +314,6 @@ Analyzing source quality and relevance:
return result
-def demonstrate_meta_search_config():
- """Show how to use meta search configuration for complex setups."""
- print("\n" + "=" * 70)
- print("META SEARCH CONFIGURATION")
- print("=" * 70)
- print("""
-Using meta search for sophisticated search strategies:
-- Combine multiple search engines
-- Configure aggregation and deduplication
-- Control search priority and weighting
- """)
-
- # Create retrievers
- tech_retriever = TechnicalDocsRetriever()
-
- settings = create_settings_snapshot({})
-
- # Advanced meta search configuration
- result = quick_summary(
- query="Quantum computing applications",
- settings_snapshot=settings,
- retrievers={
- "tech_docs": tech_retriever,
- },
- search_tool="meta", # Use meta search
- meta_search_config={
- "retrievers": ["tech_docs"], # Include custom retriever
- "engines": ["wikipedia", "arxiv"], # Also search these
- "aggregate": True, # Combine results
- "deduplicate": True, # Remove duplicate content
- "max_results_per_engine": 5, # Limit per source
- },
- iterations=2,
- questions_per_iteration=3,
- programmatic_mode=True,
- )
-
- print("\nMeta search results:")
- print(f" - Total sources: {len(result.get('sources', []))}")
- print(f" - Summary length: {len(result.get('summary', ''))} chars")
- print(f" - Findings: {len(result.get('findings', []))}")
-
- print("\nMeta search advantages:")
- print(" - Comprehensive coverage from multiple sources")
- print(" - Automatic deduplication of similar content")
- print(" - Balanced perspective from different source types")
-
- return result
-
-
def main():
"""Run all hybrid search demonstrations."""
print("=" * 70)
@@ -371,14 +323,13 @@ def main():
This example shows how to combine multiple search sources:
- Custom retrievers for proprietary knowledge
- Web search engines for public information
-- Meta search for sophisticated strategies
+- Source analysis across origins
""")
# Run demonstrations
demonstrate_multiple_retrievers()
demonstrate_retriever_plus_web()
demonstrate_source_analysis()
- demonstrate_meta_search_config()
print("\n" + "=" * 70)
print("KEY TAKEAWAYS")
@@ -387,13 +338,11 @@ This example shows how to combine multiple search sources:
1. Multiple Retrievers: Use specialized retrievers for different document types
2. Hybrid Search: Combine internal knowledge with web search for comprehensive results
3. Source Analysis: Track and analyze sources to understand information origin
-4. Meta Search: Configure complex search strategies with aggregation and deduplication
Best Practices:
- Name your retrievers descriptively for easy tracking
- Balance internal and external sources based on your needs
- Use source analysis to verify information consistency
-- Configure meta search for optimal result aggregation
""")
print("\n✓ Hybrid search demonstration complete!")
diff --git a/examples/api_usage/programmatic/simple_programmatic_example.py b/examples/api_usage/programmatic/simple_programmatic_example.py
index f4b3191b68..20c1e676fa 100755
--- a/examples/api_usage/programmatic/simple_programmatic_example.py
+++ b/examples/api_usage/programmatic/simple_programmatic_example.py
@@ -54,7 +54,7 @@ print(f"Sources: {len(result.get('sources', []))}")
print("\n=== Custom Search Parameters ===")
result = quick_summary(
query="renewable energy trends 2024",
- search_tool="auto", # Auto-select best search engine
+ search_tool="searxng", # Recommended general-purpose engine
iterations=1,
questions_per_iteration=3,
temperature=0.5, # Lower temperature for focused results
diff --git a/examples/llm_integration/basic_custom_llm.py b/examples/llm_integration/basic_custom_llm.py
index f0c751943a..6d830d3656 100644
--- a/examples/llm_integration/basic_custom_llm.py
+++ b/examples/llm_integration/basic_custom_llm.py
@@ -76,7 +76,7 @@ def main():
snapshot = create_settings_snapshot(
provider="factory_llm",
temperature=0.3,
- overrides={"search.tool": "auto"},
+ overrides={"search.tool": "wikipedia"},
)
result = quick_summary(
query="Explain the benefits of renewable energy",
diff --git a/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.py b/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.py
index 3d50816030..9a7d750377 100644
--- a/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.py
+++ b/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.py
@@ -290,7 +290,7 @@ class JournalReputationFilter(BaseFilter):
# Stored in `threading.local()` so concurrent `filter_results`
# calls on the same cached filter instance (the parallel search
# engine reuses instances across worker threads — see
- # parallel_search_engine.py:177) can't clobber each other's
+ # concurrent engine threads) can't clobber each other's
# counter. Per-thread state is reset at the top of every
# `filter_results` invocation.
self.__tls = threading.local()
@@ -349,10 +349,10 @@ class JournalReputationFilter(BaseFilter):
context_from_snapshot,
)
- primary_raw = snapshot.get("search.tool", "auto")
+ primary_raw = snapshot.get("search.tool", "searxng")
if isinstance(primary_raw, dict) and "value" in primary_raw:
primary_raw = primary_raw["value"]
- ctx = context_from_snapshot(snapshot, primary_raw or "auto")
+ ctx = context_from_snapshot(snapshot, primary_raw or "searxng")
return ctx.scope in (EgressScope.PRIVATE_ONLY, EgressScope.STRICT)
except PolicyDeniedError:
# Corrupt/unknown scope value — we cannot certify that a public
@@ -1332,7 +1332,7 @@ JOURNAL INFORMATION:
# Reset the per-thread fail-fast counter for each batch.
# The counter lives in `threading.local()` so concurrent
# callers on the same filter instance don't clobber each
- # other (see Bug A3 / parallel_search_engine.py:177).
+ # other (see Bug A3).
self.__reset_searxng_failures()
# Pass 1: collect the richest metadata per journal (the result
diff --git a/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py b/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py
index 4d018d6dfc..c1c213e0c0 100644
--- a/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py
@@ -554,7 +554,7 @@ class LangGraphAgentStrategy(BaseSearchStrategy):
primary = primary["value"]
try:
return context_from_snapshot(
- self.settings_snapshot, primary or "auto"
+ self.settings_snapshot, primary or "searxng"
)
except PolicyDeniedError:
# Corrupted/invalid policy.egress_scope — re-raise so the
@@ -632,7 +632,7 @@ class LangGraphAgentStrategy(BaseSearchStrategy):
)
current = self._get_current_engine_name()
for name, config in available.items():
- if name in ("auto", "meta") or name == current:
+ if name == current:
continue
# Per-collection usability switch (independent of egress): a
diff --git a/src/local_deep_research/advanced_search_system/strategies/mcp_strategy.py b/src/local_deep_research/advanced_search_system/strategies/mcp_strategy.py
index 56cbc36bf1..e130a10608 100644
--- a/src/local_deep_research/advanced_search_system/strategies/mcp_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/mcp_strategy.py
@@ -609,11 +609,11 @@ class MCPSearchStrategy(BaseSearchStrategy):
context_from_snapshot,
)
- _primary = self.settings_snapshot.get("search.tool", "auto")
+ _primary = self.settings_snapshot.get("search.tool", "searxng")
if isinstance(_primary, dict) and "value" in _primary:
_primary = _primary["value"]
policy_ctx = context_from_snapshot(
- self.settings_snapshot, _primary or "auto"
+ self.settings_snapshot, _primary or "searxng"
)
except PolicyDeniedError:
# Corrupt / incoherent scope → fail closed: expose no
@@ -627,11 +627,7 @@ class MCPSearchStrategy(BaseSearchStrategy):
available_engines = self._get_available_search_engines()
for engine_name, engine_config in available_engines.items():
# Skip the currently selected engine (already available via web_search)
- # Skip 'auto' and meta engines
- if (
- engine_name in ("auto", "meta")
- or engine_name == self._get_current_engine_name()
- ):
+ if engine_name == self._get_current_engine_name():
continue
# Apply the egress filter computed above.
@@ -758,15 +754,14 @@ class MCPSearchStrategy(BaseSearchStrategy):
# (allow MCP). Live deployments always have the module.
return False, ""
- primary = snapshot.get("search.tool", "auto")
+ primary = snapshot.get("search.tool", "searxng")
if isinstance(primary, dict) and "value" in primary:
primary = primary["value"]
try:
- ctx = context_from_snapshot(snapshot, primary or "auto")
+ ctx = context_from_snapshot(snapshot, primary or "searxng")
except (PolicyDeniedError, ValueError) as exc:
- # Policy itself is unevaluable (corrupt scope value, or
- # STRICT + meta-picker incoherence). Cannot certify MCP is
- # safe — fail closed.
+ # Policy itself is unevaluable (corrupt scope value).
+ # Cannot certify MCP is safe — fail closed.
return True, f"policy_unavailable:{exc}"
if ctx.scope in (EgressScope.STRICT, EgressScope.PRIVATE_ONLY):
@@ -1321,17 +1316,19 @@ class MCPSearchStrategy(BaseSearchStrategy):
"download_content; using SSRF-only check"
)
else:
- primary = self.settings_snapshot.get("search.tool", "auto")
+ primary = self.settings_snapshot.get(
+ "search.tool", "searxng"
+ )
if isinstance(primary, dict) and "value" in primary:
primary = primary["value"]
try:
egress_context = context_from_snapshot(
- self.settings_snapshot, primary or "auto"
+ self.settings_snapshot, primary or "searxng"
)
except (PolicyDeniedError, ValueError) as exc:
# Snapshot was supplied but the policy itself
- # cannot be evaluated (corrupt scope value, or
- # STRICT + meta-picker incoherence). Fail closed
+ # cannot be evaluated (corrupt scope value).
+ # Fail closed
# — the previous bare-except dropped to
# SSRF-only here, which allows public-IP fetches
# under PRIVATE_ONLY.
diff --git a/src/local_deep_research/api/research_functions.py b/src/local_deep_research/api/research_functions.py
index 89cb43d926..84847f08d4 100644
--- a/src/local_deep_research/api/research_functions.py
+++ b/src/local_deep_research/api/research_functions.py
@@ -64,7 +64,7 @@ def _init_search_system(
openai_endpoint_url: Custom endpoint URL to use (if None, uses database
setting)
progress_callback: Optional callback function to receive progress updates
- search_tool: Search engine to use (auto, wikipedia, arxiv, etc.). If None, uses default
+ search_tool: Search engine to use (searxng, wikipedia, arxiv, etc.). If None, uses default
search_strategy: Search strategy to use (modular, source_based, etc.). If None, uses default
iterations: Number of research cycles to perform
questions_per_iteration: Number of questions to generate per cycle
@@ -606,7 +606,7 @@ def detailed_research(
"sources": results.get("all_links_of_system", []),
"metadata": {
"timestamp": datetime.now(UTC).isoformat(),
- "search_tool": kwargs.get("search_tool", "auto"),
+ "search_tool": kwargs.get("search_tool", "searxng"),
"iterations_requested": kwargs.get("iterations", 1),
"strategy": kwargs.get("search_strategy", "source_based"),
},
diff --git a/src/local_deep_research/config/llm_config.py b/src/local_deep_research/config/llm_config.py
index 30d8c65d74..0fbefced80 100644
--- a/src/local_deep_research/config/llm_config.py
+++ b/src/local_deep_research/config/llm_config.py
@@ -325,7 +325,7 @@ def get_llm(
target=provider,
)
else:
- primary_engine_raw = settings_snapshot.get("search.tool", "auto")
+ primary_engine_raw = settings_snapshot.get("search.tool", "searxng")
if (
isinstance(primary_engine_raw, dict)
and "value" in primary_engine_raw
@@ -334,11 +334,11 @@ def get_llm(
try:
ctx = context_from_snapshot(
- settings_snapshot, primary_engine_raw or "auto"
+ settings_snapshot, primary_engine_raw or "searxng"
)
except ValueError as exc:
- # STRICT + meta-picker is incoherent. Failing closed here is
- # essential — previously we silently fell back to ctx=None
+ # An invalid policy config must fail closed here — this is
+ # essential; previously we silently fell back to ctx=None
# which skipped the LLM endpoint check entirely, opening a
# cloud-LLM bypass under the very configuration the user
# asked to be strict about. Raise PolicyDeniedError instead
@@ -720,7 +720,11 @@ def get_llm(
settings_snapshot=settings_snapshot,
)
_normalized = normalize_url(lmstudio_url)
- base_url = _normalized if _normalized.rstrip("/").endswith("/v1") else _normalized.rstrip("/") + "/v1"
+ base_url = (
+ _normalized
+ if _normalized.rstrip("/").endswith("/v1")
+ else _normalized.rstrip("/") + "/v1"
+ )
# Optional API key for LM Studio with auth enabled. Empty/whitespace
# falls back to a placeholder ChatOpenAI accepts; a no-auth LM Studio
# ignores it. Whitespace stripping mirrors LMStudioProvider.create_llm.
diff --git a/src/local_deep_research/database/migrations/versions/0013_remove_meta_search_engines.py b/src/local_deep_research/database/migrations/versions/0013_remove_meta_search_engines.py
new file mode 100644
index 0000000000..052e3da46f
--- /dev/null
+++ b/src/local_deep_research/database/migrations/versions/0013_remove_meta_search_engines.py
@@ -0,0 +1,229 @@
+"""Remove the 'auto' and 'parallel' meta search engines from stored data.
+
+Background
+==========
+The ``auto`` (MetaSearchEngine, aliased ``meta``) and ``parallel`` /
+``parallel_scientific`` (ParallelSearchEngine) meta engines were removed:
+the langgraph-agent strategy (the default) selects engines dynamically per
+tool call, which made the LLM-based meta-pickers redundant. The search
+engine factory fails closed on unknown engine names, so any stored
+reference to a removed engine would raise at research time.
+
+What this migration does
+========================
+1. ``settings``: rewrites ``search.tool`` values naming a removed engine
+ to ``"searxng"`` (the canonical default in ``default_settings.json``).
+2. ``settings``: deletes orphaned per-engine setting rows
+ (``search.engine.auto.*`` and ``search.engine.web.parallel.*``).
+3. ``news_subscriptions``: sets ``search_engine`` to NULL where it names a
+ removed engine — the scheduler treats a falsy value as "use the user's
+ default search tool", which matches what "auto" meant on a
+ subscription.
+4. ``queued_researches``: queued rows are replayed after a restart, so
+ ``settings_snapshot`` JSON is rewritten (submission.search_engine and
+ any embedded ``search.tool`` setting) to ``"searxng"``.
+5. ``benchmark_runs`` / ``benchmark_configs``: ``search_config`` JSON
+ ``search_tool`` values are rewritten so saved configs and resumable
+ runs keep working.
+
+Storage note: the settings ``value`` column uses SQLAlchemy's ``JSON``
+type, which stores strings as quoted TEXT — the WHERE clause matches the
+JSON-encoded form (``'"auto"'`` with quotes). See migration 0009 for the
+same pattern.
+
+Revision ID: 0013
+Revises: 0012
+Create Date: 2026-06-12
+"""
+
+from __future__ import annotations
+
+import json
+
+import sqlalchemy as sa
+from alembic import op
+from loguru import logger
+from sqlalchemy import inspect
+
+revision = "0013"
+down_revision = "0012"
+branch_labels = None
+depends_on = None
+
+REMOVED_ENGINES = ("auto", "meta", "parallel", "parallel_scientific")
+REMOVED_ENGINES_JSON = tuple(json.dumps(name) for name in REMOVED_ENGINES)
+REPLACEMENT_ENGINE = "searxng"
+REPLACEMENT_ENGINE_JSON = json.dumps(REPLACEMENT_ENGINE)
+
+ORPHAN_KEY_PREFIXES = ("search.engine.auto.", "search.engine.web.parallel.")
+
+
+def _rewrite_search_tool_setting(conn) -> None:
+ result = conn.execute(
+ sa.text(
+ "UPDATE settings SET value = :new_value "
+ "WHERE key = 'search.tool' AND value IN :old_values"
+ ).bindparams(sa.bindparam("old_values", expanding=True)),
+ {
+ "new_value": REPLACEMENT_ENGINE_JSON,
+ "old_values": list(REMOVED_ENGINES_JSON),
+ },
+ )
+ if result.rowcount:
+ logger.info(
+ "Migrated search.tool from a removed meta engine to {!r} "
+ "({} row(s)).",
+ REPLACEMENT_ENGINE,
+ result.rowcount,
+ )
+
+
+def _delete_orphan_engine_settings(conn) -> None:
+ for prefix in ORPHAN_KEY_PREFIXES:
+ result = conn.execute(
+ sa.text("DELETE FROM settings WHERE key LIKE :prefix"),
+ {"prefix": prefix + "%"},
+ )
+ if result.rowcount:
+ logger.info(
+ "Deleted {} orphaned setting row(s) under {!r}.",
+ result.rowcount,
+ prefix,
+ )
+
+
+def _null_news_subscription_engines(conn) -> None:
+ result = conn.execute(
+ sa.text(
+ "UPDATE news_subscriptions SET search_engine = NULL "
+ "WHERE search_engine IN :old_values"
+ ).bindparams(sa.bindparam("old_values", expanding=True)),
+ {"old_values": list(REMOVED_ENGINES)},
+ )
+ if result.rowcount:
+ logger.info(
+ "Cleared removed meta engine from {} news subscription(s); "
+ "they fall back to the user's default search tool.",
+ result.rowcount,
+ )
+
+
+def _rewrite_snapshot(snapshot: dict) -> bool:
+ """Rewrite removed engine names inside a queued-research snapshot.
+
+ Handles both the new structure ({"submission": {...},
+ "settings_snapshot": {...}}) and the legacy flat structure where the
+ submission params are the snapshot itself.
+ """
+ changed = False
+
+ submission = (
+ snapshot.get("submission")
+ if isinstance(snapshot.get("submission"), dict)
+ else snapshot
+ )
+ if submission.get("search_engine") in REMOVED_ENGINES:
+ submission["search_engine"] = REPLACEMENT_ENGINE
+ changed = True
+
+ complete = snapshot.get("settings_snapshot")
+ if isinstance(complete, dict) and "search.tool" in complete:
+ entry = complete["search.tool"]
+ if isinstance(entry, dict):
+ if entry.get("value") in REMOVED_ENGINES:
+ entry["value"] = REPLACEMENT_ENGINE
+ changed = True
+ elif entry in REMOVED_ENGINES:
+ complete["search.tool"] = REPLACEMENT_ENGINE
+ changed = True
+
+ return changed
+
+
+def _rewrite_queued_research_snapshots(conn) -> None:
+ rows = conn.execute(
+ sa.text("SELECT id, settings_snapshot FROM queued_researches")
+ ).fetchall()
+
+ rewritten = 0
+ for row_id, raw in rows:
+ if not raw:
+ continue
+ snapshot = json.loads(raw) if isinstance(raw, str) else raw
+ if not isinstance(snapshot, dict):
+ continue
+ if _rewrite_snapshot(snapshot):
+ conn.execute(
+ sa.text(
+ "UPDATE queued_researches SET settings_snapshot = :snap "
+ "WHERE id = :id"
+ ),
+ {"snap": json.dumps(snapshot), "id": row_id},
+ )
+ rewritten += 1
+
+ if rewritten:
+ logger.info(
+ "Rewrote removed meta engine in {} queued research row(s).",
+ rewritten,
+ )
+
+
+def _rewrite_benchmark_search_configs(conn, table: str) -> None:
+ rows = conn.execute(
+ sa.text(f"SELECT id, search_config FROM {table}") # noqa: S608 — table is a hardcoded literal
+ ).fetchall()
+
+ rewritten = 0
+ for row_id, raw in rows:
+ if not raw:
+ continue
+ config = json.loads(raw) if isinstance(raw, str) else raw
+ if not isinstance(config, dict):
+ continue
+ if config.get("search_tool") in REMOVED_ENGINES:
+ config["search_tool"] = REPLACEMENT_ENGINE
+ conn.execute(
+ sa.text(
+ f"UPDATE {table} SET search_config = :config " # noqa: S608 — table is a hardcoded literal
+ "WHERE id = :id"
+ ),
+ {"config": json.dumps(config), "id": row_id},
+ )
+ rewritten += 1
+
+ if rewritten:
+ logger.info(
+ "Rewrote removed meta engine in {} {} row(s).",
+ rewritten,
+ table,
+ )
+
+
+def upgrade() -> None:
+ conn = op.get_bind()
+ inspector = inspect(conn)
+
+ if inspector.has_table("settings"):
+ _rewrite_search_tool_setting(conn)
+ _delete_orphan_engine_settings(conn)
+
+ if inspector.has_table("news_subscriptions"):
+ _null_news_subscription_engines(conn)
+
+ if inspector.has_table("queued_researches"):
+ _rewrite_queued_research_snapshots(conn)
+
+ for table in ("benchmark_runs", "benchmark_configs"):
+ if inspector.has_table(table):
+ _rewrite_benchmark_search_configs(conn, table)
+
+
+def downgrade() -> None:
+ """No-op.
+
+ The removed engines no longer exist in the codebase, so restoring
+ references to them would only recreate broken state. The deleted
+ orphan settings rows are re-seeded from defaults files by older code
+ versions if ever needed.
+ """
diff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.json
index 665ea92e22..8ae357bcf6 100644
--- a/src/local_deep_research/defaults/default_settings.json
+++ b/src/local_deep_research/defaults/default_settings.json
@@ -1398,16 +1398,12 @@
},
"search.tool": {
"category": "search_general",
- "description": "Search engine to use for research queries. 'Auto' intelligently selects the best engine for each query type. Each engine may require its own API key or service to be configured separately.",
+ "description": "Search engine to use for research queries. The default langgraph-agent strategy can additionally pick specialized engines per query as tools. Each engine may require its own API key or service to be configured separately.",
"editable": true,
"max_value": null,
"min_value": null,
"name": "Search Engine",
"options": [
- {
- "label": "Auto (Default)",
- "value": "auto"
- },
{
"label": "Arxiv",
"value": "arxiv"
@@ -1475,14 +1471,6 @@
{
"label": "Local All",
"value": "local_all"
- },
- {
- "label": "Multi-Engine Search",
- "value": "parallel"
- },
- {
- "label": "Scientific Search (Academic Focus)",
- "value": "parallel_scientific"
}
],
"step": null,
@@ -1667,138 +1655,6 @@
],
"visible": true
},
- "search.engine.auto.display_name": {
- "category": "auto",
- "description": "Display name to use in the U.I. for this search engine.",
- "editable": false,
- "max_value": null,
- "min_value": null,
- "name": "Display Name",
- "options": null,
- "step": null,
- "type": "SEARCH",
- "ui_element": "text",
- "value": "Auto",
- "visible": false
- },
- "search.engine.auto.description": {
- "category": "auto",
- "description": "Human-readable description of the search engine.",
- "editable": false,
- "max_value": null,
- "min_value": null,
- "name": "Description",
- "options": null,
- "step": null,
- "type": "SEARCH",
- "ui_element": "text",
- "value": "Attempt to choose the best combination of search engines automatically.",
- "visible": false
- },
- "search.engine.auto.default_params.max_engines_to_try": {
- "category": "auto",
- "description": "Maximum number of search engines to try before returning results. Auto mode selects the best engine(s) based on your query type.",
- "editable": true,
- "max_value": null,
- "min_value": 1,
- "name": "Max Engines To Try",
- "options": null,
- "step": null,
- "type": "SEARCH",
- "ui_element": "number",
- "value": 3,
- "visible": true
- },
- "search.engine.auto.default_params.use_api_key_services": {
- "category": "auto",
- "description": "Whether to include paid API services (Brave, SerpAPI, etc.) in auto-selection. Disable to only use free search engines.",
- "editable": true,
- "max_value": null,
- "min_value": null,
- "name": "Use Api Key Services",
- "options": null,
- "step": null,
- "type": "SEARCH",
- "ui_element": "checkbox",
- "value": true,
- "visible": true
- },
- "search.engine.auto.reliability": {
- "category": "auto",
- "description": "Reliability rating for auto mode. Varies based on which underlying engine is selected.",
- "editable": true,
- "max_value": 1.0,
- "min_value": 0.0,
- "name": "Reliability",
- "options": null,
- "step": 0.05,
- "type": "SEARCH",
- "ui_element": "range",
- "value": 0.85,
- "visible": true
- },
- "search.engine.auto.requires_api_key": {
- "category": "auto",
- "description": "Whether auto mode requires API keys. False because it can fall back to free engines like Wikipedia.",
- "editable": true,
- "max_value": null,
- "min_value": null,
- "name": "Requires Api Key",
- "options": null,
- "step": null,
- "type": "SEARCH",
- "ui_element": "checkbox",
- "value": false,
- "visible": true
- },
- "search.engine.auto.requires_llm": {
- "category": "auto",
- "description": "Whether auto mode uses LLM to select the best engine. When disabled, falls back to rule-based selection.",
- "editable": true,
- "max_value": null,
- "min_value": null,
- "name": "Requires Llm",
- "options": null,
- "step": null,
- "type": "SEARCH",
- "ui_element": "checkbox",
- "value": true,
- "visible": true
- },
- "search.engine.auto.strengths": {
- "category": "auto",
- "description": "Key advantages of auto mode: Intelligently selects the best engine for each query type, tries multiple sources if needed.",
- "editable": true,
- "max_value": null,
- "min_value": null,
- "name": "Strengths",
- "options": null,
- "step": null,
- "type": "SEARCH",
- "ui_element": "json",
- "value": [
- "intelligent engine selection",
- "adaptable to query type",
- "fallback capabilities"
- ],
- "visible": true
- },
- "search.engine.auto.weaknesses": {
- "category": "auto",
- "description": "Limitations of auto mode: May use more API calls trying multiple engines, selection heuristics may not always be optimal.",
- "editable": true,
- "max_value": null,
- "min_value": null,
- "name": "Weaknesses",
- "options": null,
- "step": null,
- "type": "SEARCH",
- "ui_element": "json",
- "value": [
- "slightly slower due to LLM analysis"
- ],
- "visible": true
- },
"search.engine.web.brave.display_name": {
"category": "brave",
"description": "Display name to use in the U.I. for this search engine.",
@@ -5114,7 +4970,7 @@
},
"policy.egress_scope": {
"category": "policy",
- "description": "EXPERIMENTAL — this egress boundary is new defense-in-depth, not an absolute guarantee yet; don't rely on it as your only protection for highly sensitive data. Restrict which search engines a research run may use. ADAPTIVE (default) = follow your primary engine: a private primary keeps everything local, a public primary allows public engines, a meta-picker allows both. STRICT = only the primary engine you picked; PUBLIC_ONLY = any public web/academic engine; PRIVATE_ONLY = any local engine (library, paperless, etc.); BOTH = any classified engine. STRICT is incompatible with auto/meta/parallel primaries.",
+ "description": "EXPERIMENTAL — this egress boundary is new defense-in-depth, not an absolute guarantee yet; don't rely on it as your only protection for highly sensitive data. Restrict which search engines a research run may use. ADAPTIVE (default) = follow your primary engine: a private primary keeps everything local, a public primary allows public engines. STRICT = only the primary engine you picked; PUBLIC_ONLY = any public web/academic engine; PRIVATE_ONLY = any local engine (library, paperless, etc.); BOTH = any classified engine.",
"editable": true,
"max_value": null,
"min_value": null,
diff --git a/src/local_deep_research/defaults/settings/search_engines/parallel.json b/src/local_deep_research/defaults/settings/search_engines/parallel.json
deleted file mode 100644
index d5704fd22f..0000000000
--- a/src/local_deep_research/defaults/settings/search_engines/parallel.json
+++ /dev/null
@@ -1,170 +0,0 @@
-{
- "search.engine.web.parallel.display_name": {
- "category": "parallel",
- "description": "Display name to use in the U.I. for this search engine.",
- "editable": false,
- "max_value": null,
- "min_value": null,
- "name": "Display Name",
- "options": null,
- "step": null,
- "type": "SEARCH",
- "ui_element": "text",
- "value": "Parallel Search",
- "visible": true
- },
- "search.engine.web.parallel.description": {
- "category": "parallel",
- "description": "Human-readable description of the search engine.",
- "editable": false,
- "max_value": null,
- "min_value": null,
- "name": "Description",
- "options": null,
- "step": null,
- "type": "SEARCH",
- "ui_element": "text",
- "value": "Executes multiple search engines in parallel and combines their results. Uses LLM to select the most appropriate engines for each query.",
- "visible": true
- },
- "search.engine.web.parallel.default_params.max_engines_to_select": {
- "category": "parallel",
- "description": "Maximum number of search engines to select and run in parallel",
- "editable": true,
- "max_value": 10,
- "min_value": 1,
- "name": "Max Engines to Select",
- "options": null,
- "step": 1,
- "type": "SEARCH",
- "ui_element": "number",
- "value": 5,
- "visible": true
- },
- "search.engine.web.parallel.default_params.use_api_key_services": {
- "category": "parallel",
- "description": "Include search engines that require API keys",
- "editable": true,
- "max_value": null,
- "min_value": null,
- "name": "Use API Key Services",
- "options": null,
- "step": null,
- "type": "SEARCH",
- "ui_element": "checkbox",
- "value": true,
- "visible": true
- },
- "search.engine.web.parallel.default_params.allow_local_engines": {
- "category": "parallel",
- "description": "⚠️ PRIVACY WARNING: Allow local/private document engines in parallel search. This may expose personal data from your documents to web search queries and LLMs. Only enable if you understand the privacy implications.",
- "editable": true,
- "max_value": null,
- "min_value": null,
- "name": "Allow Local Engines",
- "options": null,
- "step": null,
- "type": "SEARCH",
- "ui_element": "checkbox",
- "value": false,
- "visible": true
- },
- "search.engine.web.parallel.default_params.enable_llm_relevance_filter": {
- "category": "parallel",
- "description": "Enable LLM-based relevance filtering to improve result quality by filtering out irrelevant results. This adds an extra LLM call but significantly improves result relevance.",
- "editable": true,
- "max_value": null,
- "min_value": null,
- "name": "Enable LLM Relevance Filter",
- "options": null,
- "step": null,
- "type": "SEARCH",
- "ui_element": "checkbox",
- "value": true,
- "visible": true
- },
- "search.engine.web.parallel.reliability": {
- "category": "parallel",
- "description": "Reliability of the parallel search engine",
- "editable": true,
- "max_value": 1.0,
- "min_value": 0.0,
- "name": "Reliability",
- "options": null,
- "step": 0.05,
- "type": "SEARCH",
- "ui_element": "range",
- "value": 0.9,
- "visible": true
- },
- "search.engine.web.parallel.requires_api_key": {
- "category": "parallel",
- "description": "Whether this search engine requires an API key",
- "editable": true,
- "max_value": null,
- "min_value": null,
- "name": "Requires Api Key",
- "options": null,
- "step": null,
- "type": "SEARCH",
- "ui_element": "checkbox",
- "value": false,
- "visible": true
- },
- "search.engine.web.parallel.requires_llm": {
- "category": "parallel",
- "description": "Whether this search engine requires an LLM for engine selection",
- "editable": true,
- "max_value": null,
- "min_value": null,
- "name": "Requires LLM",
- "options": null,
- "step": null,
- "type": "SEARCH",
- "ui_element": "checkbox",
- "value": true,
- "visible": true
- },
- "search.engine.web.parallel.supports_full_search": {
- "category": "parallel",
- "description": "Whether this search engine supports full document search",
- "editable": true,
- "max_value": null,
- "min_value": null,
- "name": "Supports Full Search",
- "options": null,
- "step": null,
- "type": "SEARCH",
- "ui_element": "checkbox",
- "value": false,
- "visible": true
- },
- "search.engine.web.parallel.strengths": {
- "category": "parallel",
- "description": "Strengths of this search engine",
- "editable": true,
- "max_value": null,
- "min_value": null,
- "name": "Strengths",
- "options": null,
- "step": null,
- "type": "SEARCH",
- "ui_element": "json",
- "value": "[\"Comprehensive results from multiple sources\", \"Parallel execution for faster results\", \"Intelligent engine selection\", \"Automatic deduplication\", \"Combines strengths of all engines\"]",
- "visible": true
- },
- "search.engine.web.parallel.weaknesses": {
- "category": "parallel",
- "description": "Weaknesses of this search engine",
- "editable": true,
- "max_value": null,
- "min_value": null,
- "name": "Weaknesses",
- "options": null,
- "step": null,
- "type": "SEARCH",
- "ui_element": "json",
- "value": "[\"Higher resource usage\", \"May hit rate limits on multiple engines\", \"Results may vary in quality\", \"Requires LLM for optimal selection\"]",
- "visible": true
- }
-}
diff --git a/src/local_deep_research/embeddings/embeddings_config.py b/src/local_deep_research/embeddings/embeddings_config.py
index 59a06cef41..e2b29469e1 100644
--- a/src/local_deep_research/embeddings/embeddings_config.py
+++ b/src/local_deep_research/embeddings/embeddings_config.py
@@ -206,10 +206,10 @@ def get_embeddings(
primary = (
get_setting_from_snapshot(
"search.tool",
- default="auto",
+ default="searxng",
settings_snapshot=settings_snapshot,
)
- or "auto"
+ or "searxng"
)
try:
ctx = context_from_snapshot(settings_snapshot, primary)
diff --git a/src/local_deep_research/embeddings/providers/implementations/sentence_transformers.py b/src/local_deep_research/embeddings/providers/implementations/sentence_transformers.py
index 9389a3275e..40f1333caa 100644
--- a/src/local_deep_research/embeddings/providers/implementations/sentence_transformers.py
+++ b/src/local_deep_research/embeddings/providers/implementations/sentence_transformers.py
@@ -112,10 +112,10 @@ class SentenceTransformersProvider(BaseEmbeddingProvider):
_primary = (
get_setting_from_snapshot(
"search.tool",
- default="auto",
+ default="searxng",
settings_snapshot=settings_snapshot,
)
- or "auto"
+ or "searxng"
)
require_local = context_from_snapshot(
settings_snapshot, _primary
diff --git a/src/local_deep_research/mcp/server.py b/src/local_deep_research/mcp/server.py
index 4b209e70ac..dfbb923fe6 100644
--- a/src/local_deep_research/mcp/server.py
+++ b/src/local_deep_research/mcp/server.py
@@ -241,7 +241,7 @@ def quick_research(
Args:
query: The research question or topic to investigate.
- search_engine: Search engine to use (e.g., "wikipedia", "arxiv", "searxng", "auto").
+ search_engine: Search engine to use (e.g., "wikipedia", "arxiv", "searxng").
Use list_search_engines() to see available options.
strategy: Research strategy to use (e.g., "source-based", "rapid", "iterative").
Use list_strategies() to see available options.
@@ -330,7 +330,7 @@ def detailed_research(
Args:
query: The research question or topic to investigate.
- search_engine: Search engine to use (e.g., "wikipedia", "arxiv", "searxng", "auto").
+ search_engine: Search engine to use (e.g., "wikipedia", "arxiv", "searxng").
strategy: Research strategy to use (e.g., "source-based", "iterative", "evidence").
iterations: Number of search iterations (1-10). More iterations = deeper research.
questions_per_iteration: Questions to generate per iteration (1-5).
@@ -420,7 +420,7 @@ def generate_report(
Args:
query: The research question or topic for the report.
- search_engine: Search engine to use (e.g., "wikipedia", "arxiv", "searxng", "auto").
+ search_engine: Search engine to use (e.g., "wikipedia", "arxiv", "searxng").
searches_per_section: Number of searches per report section (1-10). Default is 2.
Returns:
@@ -713,12 +713,12 @@ def _egress_audit_net(settings: Dict[str, Any]):
if not settings or get_active_context() is not None:
return nullcontext()
try:
- primary = settings.get("search.tool", "auto")
+ primary = settings.get("search.tool", "searxng")
if isinstance(primary, dict) and "value" in primary:
primary = primary["value"]
ctx = context_from_snapshot(
settings,
- primary or "auto",
+ primary or "searxng",
username=settings.get("_username"),
)
except (PolicyDeniedError, ValueError):
@@ -906,7 +906,7 @@ def get_configuration() -> Dict[str, Any]:
},
"search": {
"default_engine": extract_setting_value(
- settings, "search.tool", "auto"
+ settings, "search.tool", "searxng"
),
"default_strategy": extract_setting_value(
settings, "search.search_strategy", "source-based"
diff --git a/src/local_deep_research/news/api.py b/src/local_deep_research/news/api.py
index f55d5ed2f8..f26907700e 100644
--- a/src/local_deep_research/news/api.py
+++ b/src/local_deep_research/news/api.py
@@ -921,16 +921,16 @@ def _validate_subscription_policy(
snapshot = settings_manager.get_settings_snapshot()
if not isinstance(snapshot, dict):
return None
- primary = settings_manager.get_setting("search.tool", "auto")
+ primary = settings_manager.get_setting("search.tool", "searxng")
try:
ctx = context_from_snapshot(
- snapshot, primary or "auto", username=user_id
+ snapshot, primary or "searxng", username=user_id
)
except PolicyDeniedError as exc:
return f"egress policy refused: {exc.decision.reason}"
except ValueError as exc:
- # An incoherent egress config (e.g. STRICT scope + a meta-picker
- # primary engine) makes context_from_snapshot raise ValueError.
+ # An incoherent egress config makes context_from_snapshot
+ # raise ValueError.
# Surface it as a validation failure at subscription create/update
# time instead of letting the outer except silently skip the
# check — otherwise the subscription persists and only fails at
diff --git a/src/local_deep_research/news/web.py b/src/local_deep_research/news/web.py
index 30bd7eddb8..79a3716569 100644
--- a/src/local_deep_research/news/web.py
+++ b/src/local_deep_research/news/web.py
@@ -56,7 +56,7 @@ def create_news_blueprint():
default_settings = {
"iterations": 3,
"questions_per_iteration": 5,
- "search_engine": "auto",
+ "search_engine": "searxng",
"model_provider": "ollama",
"model": "",
"search_strategy": "source-based",
@@ -93,7 +93,7 @@ def create_news_blueprint():
default_settings = {
"iterations": 3,
"questions_per_iteration": 5,
- "search_engine": "auto",
+ "search_engine": "searxng",
"model_provider": "ollama",
"model": "",
"search_strategy": "source-based",
@@ -204,7 +204,7 @@ def load_user_settings(default_settings, db_session=None, username=None):
"search.questions_per_iteration", 5
),
"search_engine": settings_manager.get_setting(
- "search.tool", "auto"
+ "search.tool", "searxng"
),
"model_provider": settings_manager.get_setting(
"llm.provider", "ollama"
diff --git a/src/local_deep_research/notifications/manager.py b/src/local_deep_research/notifications/manager.py
index 5721be7da6..125b5c3042 100644
--- a/src/local_deep_research/notifications/manager.py
+++ b/src/local_deep_research/notifications/manager.py
@@ -340,11 +340,11 @@ class NotificationManager:
)
return service_urls
- primary_raw = snapshot.get("search.tool", "auto")
+ primary_raw = snapshot.get("search.tool", "searxng")
if isinstance(primary_raw, dict) and "value" in primary_raw:
primary_raw = primary_raw["value"]
try:
- ctx = context_from_snapshot(snapshot, primary_raw or "auto")
+ ctx = context_from_snapshot(snapshot, primary_raw or "searxng")
except (PolicyDeniedError, ValueError) as exc:
# Snapshot present but policy cannot be evaluated. The
# previous bare-except dropped to "return service_urls"
diff --git a/src/local_deep_research/research_library/routes/rag_routes.py b/src/local_deep_research/research_library/routes/rag_routes.py
index a5710c3174..bc0833fd91 100644
--- a/src/local_deep_research/research_library/routes/rag_routes.py
+++ b/src/local_deep_research/research_library/routes/rag_routes.py
@@ -515,10 +515,10 @@ def get_available_models():
primary = (
get_setting_from_snapshot(
"search.tool",
- default="auto",
+ default="searxng",
settings_snapshot=settings_snapshot,
)
- or "auto"
+ or "searxng"
)
ctx = context_from_snapshot(settings_snapshot, primary)
if not ctx.require_local_embeddings:
diff --git a/src/local_deep_research/research_library/services/download_service.py b/src/local_deep_research/research_library/services/download_service.py
index efb3db00b3..573d3d43a4 100644
--- a/src/local_deep_research/research_library/services/download_service.py
+++ b/src/local_deep_research/research_library/services/download_service.py
@@ -252,8 +252,8 @@ class DownloadService:
the pre-policy behavior (back-compat with non-scheduler callers).
Sets ``self._policy_locked = True`` when a snapshot WAS supplied
- but the policy itself cannot be evaluated (corrupt scope value,
- STRICT + meta-picker incoherence). The check_url method honors
+ but the policy itself cannot be evaluated (corrupt scope
+ value). The check_url method honors
this flag and fails closed — the previous code returned None on
PolicyDeniedError and check_url then returned ``(True,
"no_context")``, which silently allowed every download under a
@@ -278,13 +278,13 @@ class DownloadService:
)
return None
- primary_raw = settings_snapshot.get("search.tool", "auto")
+ primary_raw = settings_snapshot.get("search.tool", "searxng")
if isinstance(primary_raw, dict) and "value" in primary_raw:
primary_raw = primary_raw["value"]
try:
return context_from_snapshot(
settings_snapshot,
- primary_raw or "auto",
+ primary_raw or "searxng",
username=self.username,
)
except (PolicyDeniedError, ValueError) as exc:
diff --git a/src/local_deep_research/research_library/services/library_rag_service.py b/src/local_deep_research/research_library/services/library_rag_service.py
index 2055dfb53d..78b69b74a6 100644
--- a/src/local_deep_research/research_library/services/library_rag_service.py
+++ b/src/local_deep_research/research_library/services/library_rag_service.py
@@ -217,8 +217,8 @@ class LibraryRAGService:
# code both hardcoded scope=BOTH and gated on the raw flag, so
# a PRIVATE_ONLY corpus could be embedded by a cloud provider.
primary = (
- _get_setting_value(settings_snapshot, "search.tool", "auto")
- or "auto"
+ _get_setting_value(settings_snapshot, "search.tool", "searxng")
+ or "searxng"
)
try:
policy_ctx = context_from_snapshot(
diff --git a/src/local_deep_research/research_library/services/rag_service_factory.py b/src/local_deep_research/research_library/services/rag_service_factory.py
index bf0ccbddbf..b7e4fa3181 100644
--- a/src/local_deep_research/research_library/services/rag_service_factory.py
+++ b/src/local_deep_research/research_library/services/rag_service_factory.py
@@ -69,7 +69,7 @@ def _enforce_embeddings_policy(
}
# Build the ctx from the ACTUAL scope so PRIVATE_ONLY forces local
# embeddings even when the raw flag is False. primary_engine="library"
- # is concrete (not a meta-picker) so STRICT won't raise here.
+ # is concrete.
try:
ctx = context_from_snapshot(snapshot, "library", username=username)
except PolicyDeniedError:
diff --git a/src/local_deep_research/scheduler/background.py b/src/local_deep_research/scheduler/background.py
index 164330cd39..d7dd2b371c 100644
--- a/src/local_deep_research/scheduler/background.py
+++ b/src/local_deep_research/scheduler/background.py
@@ -725,9 +725,9 @@ class BackgroundJobScheduler:
snapshot = settings_manager.get_settings_snapshot()
if not isinstance(snapshot, dict):
return
- primary = settings_manager.get_setting("search.tool", "auto")
+ primary = settings_manager.get_setting("search.tool", "searxng")
ctx = context_from_snapshot(
- snapshot, primary or "auto", username=username
+ snapshot, primary or "searxng", username=username
)
set_active_context(ctx)
except Exception:
@@ -1565,7 +1565,7 @@ class BackgroundJobScheduler:
else:
# Use the user's default search tool from their settings
default_search_tool = settings_snapshot.get(
- "search.tool", "auto"
+ "search.tool", "searxng"
)
logger.info(
f"Using user's default search tool: '{default_search_tool}' for {subscription['id']}"
diff --git a/src/local_deep_research/search_system.py b/src/local_deep_research/search_system.py
index 8d5b62302c..48f8398a4b 100644
--- a/src/local_deep_research/search_system.py
+++ b/src/local_deep_research/search_system.py
@@ -339,17 +339,17 @@ class AdvancedSearchSystem:
return False
try:
- primary = self.settings_snapshot.get("search.tool", "auto")
+ primary = self.settings_snapshot.get("search.tool", "searxng")
if isinstance(primary, dict) and "value" in primary:
primary = primary["value"]
ctx = context_from_snapshot(
self.settings_snapshot,
- primary or "auto",
+ primary or "searxng",
username=self.username,
)
except (PolicyDeniedError, ValueError):
- # Corrupted scope / STRICT+meta-picker: the explicit PEPs and the
- # run-start precheck handle these; don't arm a partial backstop.
+ # Corrupted scope: the explicit PEPs and the run-start
+ # precheck handle these; don't arm a partial backstop.
logger.bind(policy_audit=True).debug(
"egress backstop not armed: policy unevaluable", exc_info=True
)
diff --git a/src/local_deep_research/security/egress/README.md b/src/local_deep_research/security/egress/README.md
index 5868107d83..a95ef25bbb 100644
--- a/src/local_deep_research/security/egress/README.md
+++ b/src/local_deep_research/security/egress/README.md
@@ -27,11 +27,11 @@ engines/destinations are permitted.
| Scope | Meaning |
|---|---|
-| `adaptive` *(default)* | **Follow the primary engine.** A private primary → behaves PRIVATE_ONLY; a public primary → PUBLIC_ONLY; a meta-picker (`auto`/`parallel`/`meta`) or unclassifiable primary → BOTH. Resolved to a concrete scope at run start. Classification uses the engine's **static class flags** (e.g. SearXNG is always public because it queries the internet), not the network location of its server — with one asymmetric **fail-up** exception: a local-nature engine (Elasticsearch, Paperless) whose configured URL resolves to a *public* host is reclassified public, because querying it sends data off the box. The override only ever tightens. |
+| `adaptive` *(default)* | **Follow the primary engine.** A private primary → behaves PRIVATE_ONLY; a public primary → PUBLIC_ONLY; an unclassifiable primary → BOTH. Resolved to a concrete scope at run start. Classification uses the engine's **static class flags** (e.g. SearXNG is always public because it queries the internet), not the network location of its server — with one asymmetric **fail-up** exception: a local-nature engine (Elasticsearch, Paperless) whose configured URL resolves to a *public* host is reclassified public, because querying it sends data off the box. The override only ever tightens. |
| `both` | Any classified engine (the pre-policy behaviour). |
| `public_only` | Only public web/academic engines. Local collections excluded. |
| `private_only` | Only local engines (library, collections, Ollama). **Forces local LLM + embeddings inference** so nothing leaves the box. Note: a locally-hosted SearXNG is still treated as *public* because it proxies to internet search engines — only its *connection target* is local, not its *data source*. |
-| `strict` | Only the user's *primary* engine; no expansion at all. Incompatible with a meta-picker primary. |
+| `strict` | Only the user's *primary* engine; no expansion at all. |
Two independent toggles refine inference locality (and are **implied** under
PRIVATE_ONLY / Adaptive-private):
@@ -68,7 +68,7 @@ Vocabulary borrowed from XACML / zero-trust:
| `audit_hook.py` | A process-wide **PEP-578 `sys.audit` hook** on `socket.connect`. The *secondary* net: catches outbound connections from code paths the explicit PEPs don't cover (third-party libs, new contributors using raw `requests`). Inactive until a worker calls `set_active_context(ctx)`; only gates PRIVATE_ONLY / STRICT. |
| `fetch.py` | `policy_aware_validate_url()` — the egress-scope-aware SSRF wrapper (lets PRIVATE_ONLY reach private lab hosts without disabling SSRF globally; metadata IPs stay blocked). Depends on `../ssrf_validator.py`, not the other way around. |
| `warnings.py` | The three UI banner checks (`check_public_egress_enabled`, `check_cloud_llm_enabled`, `check_cloud_embeddings_enabled`), each with its own dismiss key. Pure functions; the `web/warning_checks` orchestrator calls them. |
-| `validators.py` | Settings-save cross-field validators (`validate_strict_meta_combo`, `validate_allowed_local_hostnames`). Pure functions; the settings write routes call them. |
+| `validators.py` | Settings-save cross-field validators (`validate_allowed_local_hostnames`). Pure functions; the settings write routes call them. |
| `__init__.py` | Re-exports the public PDP / audit-hook API. |
### Public API
@@ -106,7 +106,6 @@ actually enforces the policy":
| Search engine creation | `web_search_engines/search_engine_factory.py` (`create_search_engine`) | `evaluate_engine` / `evaluate_retriever` |
| LangGraph agent tools | `advanced_search_system/strategies/langgraph_agent_strategy.py` (`_build_tools`) | `evaluate_engine` / `evaluate_retriever` (tool-list filter) |
| MCP agent tools | `advanced_search_system/strategies/mcp_strategy.py` (`_build_tool_descriptions`) | `evaluate_engine` / `evaluate_retriever` (tool-list filter) |
-| Meta / parallel search | `web_search_engines/engines/{meta,parallel}_search_engine.py` | `evaluate_engine` at child instantiation |
| Full-content fetch | `web_search_engines/engines/full_search.py` | `evaluate_url` |
| Content fetcher tool | `content_fetcher/fetcher.py` | `policy_aware_validate_url` + `evaluate_url` |
| Library downloads | `research_library/services/download_service.py` | `evaluate_url` at the fetch fire-points |
@@ -114,7 +113,7 @@ actually enforces the policy":
| Embeddings | `embeddings/embeddings_config.py`, `…/implementations/sentence_transformers.py`, `web_search_engines/engines/local_embedding_manager.py` | `evaluate_embeddings` / scope-coupled require-local |
| Journal reputation fetch | `advanced_search_system/filters/journal_reputation_filter.py` | scope skip |
| Run-start precheck | `web/routes/research_routes.py` (`_precheck_engine_policy`) | `evaluate_engine` (clean 400 at the API boundary) |
-| Settings validation | `web/routes/settings_routes.py` (calls `egress/validators.py`) | `validate_strict_meta_combo`, `validate_allowed_local_hostnames` |
+| Settings validation | `web/routes/settings_routes.py` (calls `egress/validators.py`) | `validate_allowed_local_hostnames` |
| Secondary net (all sockets) | `audit_hook.py` (installed at `security/__init__`) | `evaluate_url` on every `socket.connect` |
Adjacent (general security utils, not egress-specific — used here but live one level up):
@@ -204,7 +203,7 @@ flowchart TD
Scope -->|adaptive| Adapt{"_resolve_adaptive_scope()\nclassify PRIMARY engine"}
Adapt -->|private primary| PRIV
Adapt -->|public primary| PUB
- Adapt -->|meta-picker / unknown| BOTH
+ Adapt -->|unknown| BOTH
Scope -->|private_only| PRIV["PRIVATE_ONLY\n(forces require_local_llm\n+ require_local_embeddings)"]
Scope -->|public_only| PUB[PUBLIC_ONLY]
@@ -247,12 +246,11 @@ flowchart TD
### Egress vector x scope decision matrix
-Each cell is the decision produced by the real `evaluate_*` logic / PEP for that vector. ADAPTIVE has no cell of its own: at run start it is resolved (`_resolve_adaptive_scope`) to PRIVATE_ONLY (private primary), PUBLIC_ONLY (public primary), or BOTH (meta-picker/unclassifiable), so it inherits that column. STRICT additionally requires the engine to BE the primary.
+Each cell is the decision produced by the real `evaluate_*` logic / PEP for that vector. ADAPTIVE has no cell of its own: at run start it is resolved (`_resolve_adaptive_scope`) to PRIVATE_ONLY (private primary), PUBLIC_ONLY (public primary), or BOTH (unclassifiable), so it inherits that column. STRICT additionally requires the engine to BE the primary.
| Egress vector | adaptive (resolves to →) | both | public_only | private_only | strict |
|---|---|---|---|---|---|
| **Search engine selection** (`evaluate_engine`) | PRIVATE_ONLY \| PUBLIC_ONLY \| BOTH | any classified engine ALLOWED; unclassified BLOCKED | public engines ALLOWED; private collections BLOCKED | local engines ALLOWED; public BLOCKED | only PRIMARY engine ALLOWED; all others BLOCKED |
-| **Child-engine expansion** (meta/parallel child instantiation → `evaluate_engine`) | follows resolved scope | each child ALLOWED if classified | public children ALLOWED; private BLOCKED | local children ALLOWED; public BLOCKED | BLOCKED — meta-picker primary is rejected (`strict_with_meta_picker`); no expansion |
| **LLM inference** (`evaluate_llm_endpoint` + `get_llm`) | private→forced-local; public→cloud ALLOWED (unless toggle) | ALLOWED unless `llm.require_local_endpoint` set | ALLOWED unless toggle set (not scope-forced) | **forced-local** — cloud providers BLOCKED (`require_local_llm` implied) | ALLOWED unless toggle set (STRICT is orthogonal to inference) |
| **Embeddings / index** (`evaluate_embeddings`) | private→forced-local; public→cloud ALLOWED (unless toggle) | ALLOWED unless `embeddings.require_local` set | ALLOWED unless toggle set | **forced-local** — cloud embedders BLOCKED (`require_local_embeddings` implied) | ALLOWED unless toggle set |
| **Arbitrary URL fetch** (`evaluate_url`, content fetcher / full_search) | private→private-host only; public→public-host only | any classified host ALLOWED; unclassified BLOCKED | public host ALLOWED; private host BLOCKED | private host ALLOWED; **public host BLOCKED** | private host ALLOWED; public host BLOCKED |
@@ -267,18 +265,18 @@ Each cell is the decision produced by the real `evaluate_*` logic / PEP for that
|---|---|
| **private_only blocks ALL external data egress** | engine selection (`evaluate_engine` → `scope_mismatch_private_only`), URL/library/webhook fetch (`evaluate_url` PRIVATE_ONLY branch), LLM (`require_local_llm` forced in `context_from_snapshot` → `provider_cloud_only`), embeddings (`require_local_embeddings` forced → `provider_cloud`), and the raw-socket audit-hook net armed for PRIVATE_ONLY (`audit_hook.py`). No vector permits a public destination. |
| **public_only stays open to public sources** | public engines pass `evaluate_engine` (private collections BLOCKED via `scope_mismatch_public_only`); `evaluate_url` allows public hosts, blocks private; inference is NOT scope-forced (toggles still apply); the audit hook stays INACTIVE (only PRIVATE_ONLY/STRICT arm it) so legitimate local infra traffic — local Ollama, settings DB — is never falsely blocked. |
-| **adaptive just matches the primary engine** | `_resolve_adaptive_scope`: private primary → PRIVATE_ONLY, public primary → PUBLIC_ONLY, meta-picker/unknown → BOTH. A registered local retriever primary also resolves PRIVATE_ONLY. Uses the engine's **static class flags** (`is_public`/`is_local` on the Python class), not the network location of the engine's server — so a locally-hosted SearXNG (class `is_public=True`) resolves to PUBLIC_ONLY. Resolved once at run start; the stored `EgressContext` carries the concrete scope, not ADAPTIVE. |
+| **adaptive just matches the primary engine** | `_resolve_adaptive_scope`: private primary → PRIVATE_ONLY, public primary → PUBLIC_ONLY, unknown → BOTH. A registered local retriever primary also resolves PRIVATE_ONLY. Uses the engine's **static class flags** (`is_public`/`is_local` on the Python class), not the network location of the engine's server — so a locally-hosted SearXNG (class `is_public=True`) resolves to PUBLIC_ONLY. Resolved once at run start; the stored `EgressContext` carries the concrete scope, not ADAPTIVE. |
| **A private RAG collection as ADAPTIVE primary pulls the whole run local** | `_resolve_collection_is_public` defaults private → `_engine_bucket` returns local → adaptive resolves PRIVATE_ONLY → forces local LLM + embeddings. Mark the collection `is_public` to opt into cloud inference. |
| **Cloud-metadata is never reachable, under any scope** | `evaluate_url` runs `is_ip_blocked(..., allow_private_ips=True)` before scope logic; `_classify_host` applies the same metadata block on BOTH the literal-IP and DNS-resolved paths; NAT64-wrapped metadata is reclassified PUBLIC. |
### Advisory candidate pre-filter
-The meta/parallel engines call `filter_candidates_by_egress(names,
+LLM-selection callers can use `filter_candidates_by_egress(names,
snapshot)`, which handles the snapshot plumbing (scope/primary extraction,
context build, fail-open on any error) and delegates to
`filter_engines_by_egress(names, ctx, snapshot)`, which strips engines the scope
**actively denies** (scope mismatches, STRICT violations, unclassified
-registry engines) from meta/parallel LLM candidate lists, so selection
+registry engines) from LLM candidate lists, so selection
slots aren't wasted on engines the factory would refuse. It is advisory,
not enforcement: names unknown to the static registry are KEPT (they may
be retriever-backed or dynamically injected engines the factory evaluates
diff --git a/src/local_deep_research/security/egress/guidance.py b/src/local_deep_research/security/egress/guidance.py
index c94a546a1e..0ba583ec58 100644
--- a/src/local_deep_research/security/egress/guidance.py
+++ b/src/local_deep_research/security/egress/guidance.py
@@ -56,13 +56,6 @@ _GUIDANCE: dict[str, tuple[str, str]] = {
"To use {target}, either make it your primary engine, or change "
"your Egress Scope away from Strict in {scope_setting}.",
),
- "strict_with_meta_picker": (
- "Strict scope can't be combined with a meta-picker primary engine "
- "(auto / meta / parallel), which has no single concrete engine to "
- "restrict to.",
- "Pick a specific primary engine (e.g. arxiv, searxng), or change your "
- "Egress Scope away from Strict in {scope_setting}.",
- ),
"blocked_metadata_ip": (
"{target} was blocked because it targets a cloud-metadata endpoint "
"(e.g. 169.254.169.254). These are NEVER permitted under any scope — "
diff --git a/src/local_deep_research/security/egress/policy.py b/src/local_deep_research/security/egress/policy.py
index cbfffda2bc..f348c46d3f 100644
--- a/src/local_deep_research/security/egress/policy.py
+++ b/src/local_deep_research/security/egress/policy.py
@@ -65,7 +65,7 @@ class EgressScope(str, Enum):
- BOTH: any classified engine (preserves pre-policy behavior).
- ADAPTIVE: scope FOLLOWS the primary engine — a concrete private
primary behaves as PRIVATE_ONLY, a concrete public primary as
- PUBLIC_ONLY, and a meta-picker / unclassifiable primary as BOTH.
+ PUBLIC_ONLY, and an unclassifiable primary as BOTH.
The default: most users never touch scope and "it just matches my
main engine." Resolved to a concrete scope at context construction;
the stored EgressContext carries the RESOLVED scope, not ADAPTIVE.
@@ -146,11 +146,6 @@ class PolicyDeniedError(RuntimeError):
super().__init__(f"policy_denied: {decision.reason}")
-_META_PICKER_ENGINES = frozenset(
- {"auto", "meta", "parallel", "parallel_scientific"}
-)
-
-
def _is_nat64_wrapped_metadata(hostname: str) -> bool:
"""True iff ``hostname`` parses as an IPv6 NAT64 address wrapping a
cloud-metadata IPv4 (AWS / Azure / GCE / etc).
@@ -470,7 +465,6 @@ _PREFILTER_STRIP_REASONS = frozenset(
"scope_mismatch_public_only",
"scope_mismatch_private_only",
"strict_not_primary",
- "strict_with_meta_picker",
# Registered engine without classification flags: the factory's
# evaluate_engine call fails it closed too, so stripping matches
# enforcement exactly.
@@ -497,11 +491,11 @@ def filter_engines_by_egress(
registry lookup — exactly as it does in the factory):
they may be retriever-backed or dynamically injected engines that the
factory evaluates via its own retriever path; dropping them here would
- silently hide legitimate engines from meta/parallel selection. The
- factory still denies anything truly disallowed at instantiation.
+ silently hide legitimate engines from LLM selection. The factory
+ still denies anything truly disallowed at instantiation.
- Callers: parallel/meta engine candidate lists, LangGraph tool builder,
- or any code that builds a selection set before presenting it to an LLM.
+ Callers: the LangGraph tool builder, or any code that builds a
+ selection set before presenting it to an LLM.
"""
allowed: list[str] = []
for name in engine_names:
@@ -519,8 +513,8 @@ def filter_candidates_by_egress(
) -> list[str]:
"""Best-effort scope pre-filter for an LLM candidate list.
- Wraps ``filter_engines_by_egress`` with the snapshot plumbing the meta
- and parallel engines share: read ``policy.egress_scope`` /
+ Wraps ``filter_engines_by_egress`` with the snapshot plumbing
+ LLM-selection callers share: read ``policy.egress_scope`` /
``search.tool`` from the snapshot (flat or ``{"value": ...}`` shaped),
build the context, filter. Returns the input list unchanged when the
snapshot is missing, the scope is BOTH (nothing to strip), or anything
@@ -546,8 +540,8 @@ def filter_candidates_by_egress(
):
return engine_names
primary = (
- _get_setting_value(settings_snapshot, "search.tool", "auto")
- or "auto"
+ _get_setting_value(settings_snapshot, "search.tool", "searxng")
+ or "searxng"
)
ctx = context_from_snapshot(
settings_snapshot,
@@ -583,23 +577,6 @@ def evaluate_engine(
if settings_snapshot is None:
return Decision(False, "no_snapshot")
try:
- # STRICT + meta-picker is incoherent (the user shouldn't have been
- # allowed to save this combination at the API layer, but defend
- # in depth at the factory too).
- if (
- ctx.scope == EgressScope.STRICT
- and ctx.primary_engine in _META_PICKER_ENGINES
- ):
- return Decision(False, "strict_with_meta_picker")
-
- # Meta-pickers (auto, parallel, ...) are delegators — the policy
- # gates their *children* at child instantiation time. The meta
- # engine itself is permitted under all non-STRICT scopes.
- if engine_name in _META_PICKER_ENGINES:
- if ctx.scope == EgressScope.STRICT:
- return Decision(False, "strict_with_meta_picker")
- return Decision(True, "meta_picker_delegator")
-
# STRICT: only the primary engine is permitted.
if (
ctx.scope == EgressScope.STRICT
@@ -1181,8 +1158,8 @@ def _resolve_adaptive_scope(
public rather than pulling the run into PRIVATE_ONLY.
private primary => PRIVATE_ONLY, public primary => PUBLIC_ONLY,
- meta-picker / unknown / classification-error => BOTH (adaptive's
- documented permissive fallback, equivalent to pre-policy behavior, so a
+ unknown / classification-error => BOTH (adaptive's documented
+ permissive fallback, equivalent to pre-policy behavior, so a
classification hiccup never hard-fails the run).
A registered LangChain retriever (private KB) is not in ENGINE_REGISTRY,
@@ -1190,7 +1167,7 @@ def _resolve_adaptive_scope(
retriever registry so a local retriever primary resolves to PRIVATE_ONLY
(forcing local inference) rather than leaking the corpus to cloud models.
"""
- if not primary_engine or primary_engine in _META_PICKER_ENGINES:
+ if not primary_engine:
return EgressScope.BOTH
try:
probe_ctx = EgressContext(
@@ -1245,11 +1222,8 @@ def context_from_snapshot(
getaddrinfo when classifying a URL-configurable primary engine — used by
the advisory warning-banner render path so a settings-page load never
blocks on DNS. Enforcement callers leave it True so classification is
- accurate. (Has no effect for non-ADAPTIVE scopes or meta-picker primaries,
- which never resolve a URL.)
-
- Raises ``ValueError`` for cross-field invariant violations
- (e.g., ``STRICT`` + a meta-picker primary engine).
+ accurate. (Has no effect for non-ADAPTIVE scopes, which never resolve
+ a URL.)
"""
if settings_snapshot is None:
raise ValueError("settings_snapshot is required")
@@ -1302,8 +1276,8 @@ def context_from_snapshot(
# ADAPTIVE resolves to a concrete scope by classifying the primary
# engine: a concrete private primary => PRIVATE_ONLY, a concrete public
- # primary => PUBLIC_ONLY, a meta-picker / unclassifiable primary =>
- # BOTH. The resolved scope is what the EgressContext stores and what
+ # primary => PUBLIC_ONLY, an unclassifiable primary => BOTH.
+ # The resolved scope is what the EgressContext stores and what
# every downstream PEP enforces. Classification reuses _engine_bucket
# via a throwaway BOTH-scoped context (its DNS cache is discarded).
if scope == EgressScope.ADAPTIVE:
@@ -1332,14 +1306,6 @@ def context_from_snapshot(
require_local_llm = True
require_local_embeddings = True
- # Cross-field invariant: STRICT + meta-picker is incoherent.
- if scope == EgressScope.STRICT and primary_engine in _META_PICKER_ENGINES:
- raise ValueError(
- "STRICT egress scope is incompatible with a meta-picker "
- "primary engine (auto, meta, parallel, parallel_scientific). "
- "Choose a concrete primary engine or change scope."
- )
-
return EgressContext(
scope=scope,
primary_engine=primary_engine,
diff --git a/src/local_deep_research/security/egress/validators.py b/src/local_deep_research/security/egress/validators.py
index 34bc4eb175..71111ca14e 100644
--- a/src/local_deep_research/security/egress/validators.py
+++ b/src/local_deep_research/security/egress/validators.py
@@ -13,56 +13,11 @@ but the egress rules themselves live here next to the policy they encode.
from .policy import (
EgressContext,
EgressScope,
- _META_PICKER_ENGINES,
_classify_host,
_resolve_with_timeout,
)
-def validate_strict_meta_combo(form_data, all_db_settings):
- """Cross-field guard: STRICT egress scope + a meta-picker primary
- engine (auto / meta / parallel / parallel_scientific) is incoherent
- — STRICT means "only the primary engine", but a meta-picker has no
- single concrete primary. Returns a validation-error dict to surface
- in the save response, or None when the combination is fine.
-
- Effective values prefer the about-to-be-saved form value and fall
- back to the current DB value so the check is correct whether the
- user is changing scope, engine, or both.
- """
-
- def _effective(key):
- if key in form_data:
- return form_data[key]
- db_setting = all_db_settings.get(key)
- return db_setting.value if db_setting is not None else None
-
- scope_raw = _effective("policy.egress_scope")
- engine_raw = _effective("search.tool")
- if scope_raw is None or engine_raw is None:
- return None
- try:
- scope = EgressScope(str(scope_raw).lower())
- except ValueError:
- # Unknown scope value is handled elsewhere (runtime fail-closed);
- # don't block the save on it here.
- return None
- if (
- scope == EgressScope.STRICT
- and str(engine_raw).lower() in _META_PICKER_ENGINES
- ):
- return {
- "key": "policy.egress_scope",
- "error": (
- "STRICT egress scope requires a concrete primary search "
- f"engine, but the current search tool is '{engine_raw}' "
- "(a meta-picker). Choose a specific engine (e.g. arxiv, "
- "searxng) or pick a less restrictive egress scope."
- ),
- }
- return None
-
-
def validate_allowed_local_hostnames(form_data, all_db_settings):
"""Reject public hostnames being added to llm.allowed_local_hostnames.
@@ -105,7 +60,7 @@ def validate_allowed_local_hostnames(form_data, all_db_settings):
# correctly. Empty local_hostnames => classify purely on IP class.
probe_ctx = EgressContext(
scope=EgressScope.BOTH,
- primary_engine="auto",
+ primary_engine="searxng",
require_local_llm=False,
require_local_embeddings=False,
local_hostnames=(),
diff --git a/src/local_deep_research/security/egress/warnings.py b/src/local_deep_research/security/egress/warnings.py
index d83ef04cec..eb2c41d74b 100644
--- a/src/local_deep_research/security/egress/warnings.py
+++ b/src/local_deep_research/security/egress/warnings.py
@@ -41,9 +41,9 @@ def check_public_egress_enabled(
"""
if acknowledged:
return None
- # "adaptive" can resolve to a public-allowing scope (public or meta-picker
- # primary), so warn conservatively — better a dismissible banner than a
- # silent public-egress path the user didn't expect.
+ # "adaptive" can resolve to a public-allowing scope (public or
+ # unclassifiable primary), so warn conservatively — better a dismissible
+ # banner than a silent public-egress path the user didn't expect.
if egress_scope not in ("both", "public_only", "adaptive"):
return None
@@ -111,14 +111,15 @@ def check_effective_scope(
"not queried."
),
}
- # both (meta-picker primary) / unclassifiable
+ # both (unclassifiable primary)
return {
**base,
"icon": "🔀",
"title": "Adaptive → Public + private searches enabled",
"message": (
- f"Your primary ('{primary}') is a meta-picker, so this run can "
- "use both public engines and your local collections."
+ f"Your primary ('{primary}') could not be classified as public "
+ "or private, so this run can use both public engines and your "
+ "local collections."
),
}
diff --git a/src/local_deep_research/security/module_whitelist.py b/src/local_deep_research/security/module_whitelist.py
index 4d9c66b48f..22add19ea3 100644
--- a/src/local_deep_research/security/module_whitelist.py
+++ b/src/local_deep_research/security/module_whitelist.py
@@ -28,8 +28,6 @@ ALLOWED_MODULE_PATHS: frozenset[str] = frozenset(
# Relative imports only (relative to local_deep_research.web_search_engines)
# Absolute paths are NOT allowed for security reasons
".engines.full_search",
- ".engines.meta_search_engine",
- ".engines.parallel_search_engine",
".engines.search_engine_arxiv",
".engines.search_engine_brave",
".engines.search_engine_collection",
@@ -87,13 +85,11 @@ ALLOWED_CLASS_NAMES: frozenset[str] = frozenset(
"GooglePSESearchEngine",
"GuardianSearchEngine",
"LibraryRAGSearchEngine",
- "MetaSearchEngine",
"MojeekSearchEngine",
"NasaAdsSearchEngine",
"OpenAlexSearchEngine",
"OpenLibrarySearchEngine",
"PaperlessSearchEngine",
- "ParallelSearchEngine",
"PubChemSearchEngine",
"PubMedSearchEngine",
"RetrieverSearchEngine",
diff --git a/src/local_deep_research/utilities/enums.py b/src/local_deep_research/utilities/enums.py
index 596ed9480f..f5df919c84 100644
--- a/src/local_deep_research/utilities/enums.py
+++ b/src/local_deep_research/utilities/enums.py
@@ -7,12 +7,3 @@ class KnowledgeAccumulationApproach(Enum):
ITERATION = "ITERATION"
NO_KNOWLEDGE = "NO_KNOWLEDGE"
MAX_NR_OF_CHARACTERS = "MAX_NR_OF_CHARACTERS"
-
-
-class SearchMode(Enum):
- """Search mode for filtering search engines."""
-
- ALL = "all" # Include all available search engines
- SCIENTIFIC = (
- "scientific" # Include only scientific and generic search engines
- )
diff --git a/src/local_deep_research/web/api.py b/src/local_deep_research/web/api.py
index 0b45bf916b..f9877c89b5 100644
--- a/src/local_deep_research/web/api.py
+++ b/src/local_deep_research/web/api.py
@@ -280,7 +280,7 @@ def api_quick_summary():
POST /api/v1/quick_summary
{
"query": "Advances in fusion energy research",
- "search_tool": "auto", # Optional: search engine to use
+ "search_tool": "searxng", # Optional: search engine to use (defaults to your configured search.tool setting)
"iterations": 2, # Optional: number of search iterations
"temperature": 0.7 # Optional: LLM temperature
}
@@ -332,9 +332,10 @@ def api_quick_summary():
f"Processing quick_summary request: query='{query}' for user='{username}'"
)
- # Set reasonable defaults for API use
+ # Set reasonable defaults for API use. search_tool deliberately has
+ # no default here: when omitted, quick_summary reads the user's
+ # configured search.tool from the settings snapshot.
params.setdefault("temperature", 0.7)
- params.setdefault("search_tool", "auto")
params.setdefault("iterations", 1)
error = _load_user_context_into_params(
diff --git a/src/local_deep_research/web/routes/api_routes.py b/src/local_deep_research/web/routes/api_routes.py
index c1d93156f6..914254f844 100644
--- a/src/local_deep_research/web/routes/api_routes.py
+++ b/src/local_deep_research/web/routes/api_routes.py
@@ -639,7 +639,7 @@ def api_get_config():
"provider", "ollama"
),
"search_tool": current_app.config.get("SEARCH_CONFIG", {}).get(
- "search_tool", "auto"
+ "search_tool", "searxng"
),
"features": {
"notifications": current_app.config.get(
diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.py
index 4d5474c812..05cb4b933b 100644
--- a/src/local_deep_research/web/routes/research_routes.py
+++ b/src/local_deep_research/web/routes/research_routes.py
@@ -240,10 +240,10 @@ def _precheck_engine_policy(settings_manager, params, search_engine, username):
# a global settings save).
_apply_policy_overrides(policy_snapshot, params)
- primary = settings_manager.get_setting("search.tool", "auto")
+ primary = settings_manager.get_setting("search.tool", "searxng")
try:
policy_ctx = context_from_snapshot(
- policy_snapshot, primary or "auto", username=username
+ policy_snapshot, primary or "searxng", username=username
)
except PolicyDeniedError as exc:
return (
@@ -259,7 +259,7 @@ def _precheck_engine_policy(settings_manager, params, search_engine, username):
400,
)
except ValueError as exc:
- # STRICT + meta-picker is incoherent. Previously this
+ # An invalid policy config is unrecoverable. Previously this
# raised, fell through to the outer ``except Exception``
# below, and silently returned None — so the run started
# successfully at the precheck and only failed at a
diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.py
index 7d4604ef67..a922915330 100644
--- a/src/local_deep_research/web/routes/settings_routes.py
+++ b/src/local_deep_research/web/routes/settings_routes.py
@@ -68,7 +68,6 @@ from ...security.decorators import require_json_body
from ...security.egress.policy import DEFAULT_EGRESS_SCOPE
from ...security.egress.validators import (
validate_allowed_local_hostnames,
- validate_strict_meta_combo,
)
from ..auth.decorators import login_required
from ..utils.request_helpers import parse_bool_arg
@@ -245,10 +244,10 @@ def _model_list_local_only() -> bool:
snap = sm.get_settings_snapshot()
if isinstance(snap, dict):
- primary = sm.get_setting("search.tool", "auto")
+ primary = sm.get_setting("search.tool", "searxng")
return bool(
context_from_snapshot(
- snap, primary or "auto", username=username
+ snap, primary or "searxng", username=username
).require_local_llm
)
return False
@@ -390,26 +389,6 @@ def save_all_settings(db_session=None, settings_manager=None):
# Fetch all settings and remove non-editable keys
all_db_settings = _filter_editable_settings(form_data, db_session)
- # Cross-field egress-policy validation (H4 layer 2): reject the
- # incoherent STRICT + meta-picker combination at save time so the
- # user finds out immediately, instead of mid-research when the
- # factory PEP raises. Effective values are the about-to-be-saved
- # form values, falling back to the current DB value when the form
- # doesn't include that key.
- _policy_err = validate_strict_meta_combo(form_data, all_db_settings)
- if _policy_err is not None:
- validation_errors.append(_policy_err)
- return (
- jsonify(
- {
- "status": "error",
- "message": "Validation errors",
- "errors": validation_errors,
- }
- ),
- 400,
- )
-
# Reject public hostnames being added to the local-hosts allowlist.
_hosts_err = validate_allowed_local_hostnames(
form_data, all_db_settings
@@ -504,7 +483,7 @@ def save_all_settings(db_session=None, settings_manager=None):
elif key == "llm.provider":
value = "ollama"
elif key == "search.tool":
- value = "auto"
+ value = "searxng"
elif key in ["app.theme", "app.default_theme"]:
value = "dark"
else:
@@ -775,12 +754,9 @@ def save_settings(db_session=None, settings_manager=None):
# Egress-policy validators — the JSON route (save_all_settings) runs
# these; the POST fallback must too, or a JS-disabled client could
- # persist a STRICT+meta-picker combo or whitelist a public hostname
- # as "local", neither of which the JSON route permits.
- for _policy_validator in (
- validate_strict_meta_combo,
- validate_allowed_local_hostnames,
- ):
+ # whitelist a public hostname as "local", which the JSON route does
+ # not permit.
+ for _policy_validator in (validate_allowed_local_hostnames,):
_policy_err = _policy_validator(form_data, all_db_settings)
if _policy_err is not None:
flash(
@@ -998,9 +974,8 @@ def api_update_setting(key, db_session=None):
# Cross-field egress-policy validation. The full-form saves
# (save_all_settings / save_settings) run these guards, but this
- # single-key PUT endpoint did not — letting a client persist an
- # incoherent STRICT + meta-picker combo, or smuggle a public
- # hostname into llm.allowed_local_hostnames (which the host
+ # single-key PUT endpoint did not — letting a client smuggle a
+ # public hostname into llm.allowed_local_hostnames (which the host
# classifier then trusts as local), one key at a time. Run the
# same validators here for the keys they govern.
if key in (
@@ -1012,10 +987,7 @@ def api_update_setting(key, db_session=None):
s.key: s for s in db_session.query(Setting).all()
}
_form = {key: value}
- for _validator in (
- validate_strict_meta_combo,
- validate_allowed_local_hostnames,
- ):
+ for _validator in (validate_allowed_local_hostnames,):
_err = _validator(_form, _all_db_settings)
if _err is not None:
logger.bind(policy_audit=True).warning(
@@ -2166,7 +2138,7 @@ def fix_corrupted_settings(db_session=None):
default_value = 1024
elif setting.key.startswith("search."):
if setting.key == "search.tool":
- default_value = "auto"
+ default_value = "searxng"
elif setting.key == "search.max_results":
default_value = 10
elif setting.key == "search.region":
diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.py
index 687b489092..809c4f08c8 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -937,7 +937,9 @@ def run_research_process(research_id, query, mode, **kwargs):
)
try:
- _egress_primary = settings_snapshot.get("search.tool", "auto")
+ _egress_primary = settings_snapshot.get(
+ "search.tool", "searxng"
+ )
if (
isinstance(_egress_primary, dict)
and "value" in _egress_primary
@@ -945,12 +947,12 @@ def run_research_process(research_id, query, mode, **kwargs):
_egress_primary = _egress_primary["value"]
_egress_ctx = context_from_snapshot(
settings_snapshot,
- _egress_primary or "auto",
+ _egress_primary or "searxng",
username=username,
)
_set_egress_ctx(_egress_ctx)
except (PolicyDeniedError, ValueError) as _ctx_err:
- # STRICT+meta-picker or corrupted scope. The run-start
+ # Corrupted scope or invalid policy config. The run-start
# precheck already rejects this at the API boundary;
# if we get here it is because the run was launched
# without going through the precheck (CLI, scheduler).
diff --git a/src/local_deep_research/web/static/js/components/research.js b/src/local_deep_research/web/static/js/components/research.js
index e46e43d5eb..72c19f9674 100644
--- a/src/local_deep_research/web/static/js/components/research.js
+++ b/src/local_deep_research/web/static/js/components/research.js
@@ -384,9 +384,6 @@
// Finally, load settings after data is available
loadSettings();
-
- // H4: set STRICT-scope availability for the initial engine.
- updateStrictScopeAvailability();
}).catch(error => {
SafeLogger.error('Failed to load options:', error);
@@ -396,8 +393,6 @@
// Still load settings even if data loading fails
loadSettings();
- updateStrictScopeAvailability();
-
if (window.ui && window.ui.showAlert) {
window.ui.showAlert('Some options could not be loaded. Using defaults instead.', 'warning');
}
@@ -527,10 +522,6 @@
seHidden.value = value;
}
- // H4: re-evaluate whether STRICT egress scope is allowed
- // for this engine.
- updateStrictScopeAvailability();
-
// Save search engine selection to settings - only if not initializing
if (!isInitializing) {
saveSearchEngineSettings(value);
@@ -631,51 +622,6 @@
}
}
- // Engines that delegate to children and therefore have no single
- // concrete "primary" — STRICT egress scope is incompatible with these
- // (mirrors _META_PICKER_ENGINES in security/egress/policy.py).
- const META_PICKER_ENGINES = ['auto', 'meta', 'parallel', 'parallel_scientific'];
-
- /**
- * H4 layer 1: disable the STRICT egress-scope option when the selected
- * search engine is a meta-picker. The server also rejects this combo
- * (save-time validation + the research-route pre-check), but disabling
- * it here prevents the user from choosing an incoherent combination in
- * the first place. If STRICT was already selected when the engine
- * switches to a meta-picker, fall back to "both" and surface a hint.
- */
- function updateStrictScopeAvailability() {
- const scopeSelect = document.getElementById('policy_egress_scope');
- if (!scopeSelect) return;
- const strictOption = scopeSelect.querySelector('option[value="strict"]');
- if (!strictOption) return;
-
- const hiddenInput = document.getElementById('search_engine_hidden');
- const engine = (hiddenInput && hiddenInput.value
- ? hiddenInput.value
- : (typeof selectedSearchEngineValue !== 'undefined' ? selectedSearchEngineValue : '')
- ).toString().toLowerCase();
-
- const helpEl = document.getElementById('policy_egress_scope_help');
- const isMetaPicker = META_PICKER_ENGINES.includes(engine);
-
- if (isMetaPicker) {
- strictOption.disabled = true;
- // If STRICT was selected, revert to the safe default and explain.
- if (scopeSelect.value === 'strict') {
- scopeSelect.value = 'both';
- if (helpEl) {
- helpEl.textContent =
- '"Primary only" is unavailable while the search engine is "' + engine +
- '" (a meta-picker with no single primary). Pick a specific ' +
- 'engine to use Primary only. Scope reset to Public + private.';
- }
- }
- } else {
- strictOption.disabled = false;
- }
- }
-
/**
* Setup event listeners
*/
diff --git a/src/local_deep_research/web/static/js/components/settings.js b/src/local_deep_research/web/static/js/components/settings.js
index c1c7a2039d..22dc868646 100644
--- a/src/local_deep_research/web/static/js/components/settings.js
+++ b/src/local_deep_research/web/static/js/components/settings.js
@@ -3684,7 +3684,7 @@
const dropdown = window.setupCustomDropdown(
searchEngineInput,
dropdownList,
- () => (searchEngineOptions.length > 0 ? searchEngineOptions : [{ value: 'auto', label: 'Auto (Default)' }]),
+ () => (searchEngineOptions.length > 0 ? searchEngineOptions : [{ value: 'searxng', label: 'SearXNG' }]),
(value) => {
SafeLogger.log('Search engine selected:', value);
// Update the hidden input value
@@ -3708,7 +3708,7 @@
}
}
if (!currentValue) {
- currentValue = 'auto'; // Default value, actual value comes from DB
+ currentValue = 'searxng'; // Default value, actual value comes from DB
}
// Set initial value
@@ -4160,7 +4160,7 @@
searchEngineOptions : [
{ value: 'google_pse', label: 'Google Programmable Search' },
{ value: 'duckduckgo', label: 'DuckDuckGo' },
- { value: 'auto', label: 'Auto (Default)' }
+ { value: 'searxng', label: 'SearXNG' }
];
}
diff --git a/src/local_deep_research/web/templates/pages/news-subscription-form.html b/src/local_deep_research/web/templates/pages/news-subscription-form.html
index c772c15cef..1e3b5acafc 100644
--- a/src/local_deep_research/web/templates/pages/news-subscription-form.html
+++ b/src/local_deep_research/web/templates/pages/news-subscription-form.html
@@ -310,7 +310,7 @@ async function loadSearchEngines() {
}
} catch (error) {
console.error('Error loading search engines:', error);
- searchEngineOptions = [{ value: 'auto', label: 'Auto' }];
+ searchEngineOptions = [{ value: 'searxng', label: 'SearXNG' }];
}
}
@@ -837,7 +837,7 @@ async function handleCreateAndRun(event) {
// Search configuration
const searchEngineHidden = document.getElementById('subscription-search-engine_hidden');
- const searchEngine = searchEngineHidden ? searchEngineHidden.value : 'auto';
+ const searchEngine = searchEngineHidden ? searchEngineHidden.value : 'searxng';
const iterations = document.getElementById('subscription-iterations').value;
const questionsPerIteration = document.getElementById('subscription-questions').value;
const strategy = document.getElementById('subscription-strategy').value;
diff --git a/src/local_deep_research/web/templates/pages/research.html b/src/local_deep_research/web/templates/pages/research.html
index 73bcd121f1..d548314b01 100644
--- a/src/local_deep_research/web/templates/pages/research.html
+++ b/src/local_deep_research/web/templates/pages/research.html
@@ -116,7 +116,7 @@
</div>
<div class="ldr-form-row" style="margin:0;">
<div class="ldr-form-group ldr-half">
- <label for="policy_egress_scope">{{ tooltip("Egress Scope", "Adaptive (default): follows your primary engine — a private primary keeps everything local, a public primary allows public engines, a meta-picker allows both. Public + private: any classified engine. Public only: any public web/academic engine, no local sources. Private only: only local engines (library, paperless, etc.). Primary only: the selected search engine and nothing else — incompatible with auto / meta / parallel primaries.") }}</label>
+ <label for="policy_egress_scope">{{ tooltip("Egress Scope", "Adaptive (default): follows your primary engine — a private primary keeps everything local, a public primary allows public engines. Public + private: any classified engine. Public only: any public web/academic engine, no local sources. Private only: only local engines (library, paperless, etc.). Primary only: the selected search engine and nothing else.") }}</label>
<select id="policy_egress_scope" name="policy_egress_scope" class="ldr-form-control">
<option value="adaptive" {% if not settings.policy_egress_scope or settings.policy_egress_scope == "adaptive" %}selected{% endif %}>Adaptive (default — follows primary)</option>
<option value="both" {% if settings.policy_egress_scope == "both" %}selected{% endif %}>Public + private (any engine)</option>
diff --git a/src/local_deep_research/web/warning_checks/__init__.py b/src/local_deep_research/web/warning_checks/__init__.py
index 459e97a2ca..284e46827e 100644
--- a/src/local_deep_research/web/warning_checks/__init__.py
+++ b/src/local_deep_research/web/warning_checks/__init__.py
@@ -136,7 +136,9 @@ def calculate_warnings() -> List[dict]:
require_local_embeddings = bool(
settings_manager.get_setting("embeddings.require_local", False)
)
- primary_engine = settings_manager.get_setting("search.tool", "auto")
+ primary_engine = settings_manager.get_setting(
+ "search.tool", "searxng"
+ )
# Resolve the EFFECTIVE posture so the banners are accurate. For
# `adaptive`, this turns the opaque "follows the primary" into a
@@ -160,7 +162,7 @@ def calculate_warnings() -> List[dict]:
# classification — accuracy here is best-effort by design.
_eff_ctx = context_from_snapshot(
_snap,
- primary_engine or "auto",
+ primary_engine or "searxng",
username=username,
allow_dns=False,
)
diff --git a/src/local_deep_research/web_search_engines/engine_registry.py b/src/local_deep_research/web_search_engines/engine_registry.py
index 1dadab02d5..4aae627a8a 100644
--- a/src/local_deep_research/web_search_engines/engine_registry.py
+++ b/src/local_deep_research/web_search_engines/engine_registry.py
@@ -97,10 +97,6 @@ ENGINE_REGISTRY: Dict[str, EngineEntry] = {
module_path=".engines.search_engine_paperless",
class_name="PaperlessSearchEngine",
),
- "parallel": EngineEntry(
- module_path=".engines.parallel_search_engine",
- class_name="ParallelSearchEngine",
- ),
"scaleserp": EngineEntry(
module_path=".engines.search_engine_scaleserp",
class_name="ScaleSerpSearchEngine",
@@ -152,11 +148,6 @@ ENGINE_REGISTRY: Dict[str, EngineEntry] = {
module_path=".engines.search_engine_guardian",
class_name="GuardianSearchEngine",
),
- # --- Meta engine ---
- "auto": EngineEntry(
- module_path=".engines.meta_search_engine",
- class_name="MetaSearchEngine",
- ),
}
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
deleted file mode 100644
index 09396aa508..0000000000
--- a/src/local_deep_research/web_search_engines/engines/meta_search_engine.py
+++ /dev/null
@@ -1,587 +0,0 @@
-from typing import Any, Dict, List, Optional
-
-from loguru import logger
-
-from ...config.search_config import get_setting_from_snapshot
-from ...security.egress.policy import (
- PolicyDeniedError,
- filter_candidates_by_egress,
-)
-from ...utilities.thread_context import get_search_context
-from ...web.services.socket_service import SocketIOService
-from ..search_engine_base import BaseSearchEngine
-from ..search_engine_factory import create_search_engine
-from ..search_engines_config import get_available_engines
-from .search_engine_wikipedia import WikipediaSearchEngine
-
-
-class MetaSearchEngine(BaseSearchEngine):
- """
- LLM-powered meta search engine that intelligently selects and uses
- the appropriate search engines based on query analysis
- """
-
- def __init__(
- self,
- llm,
- max_results: int = 10,
- use_api_key_services: bool = True,
- max_engines_to_try: int = 3,
- max_filtered_results: Optional[int] = None,
- _engine_selection_callback=None,
- settings_snapshot: Optional[Dict[str, Any]] = None,
- programmatic_mode: bool = False,
- **kwargs,
- ):
- """
- Initialize the meta search engine.
-
- Args:
- llm: Language model instance for query classification and relevance filtering
- max_results: Maximum number of search results to return
- use_api_key_services: Whether to include services that require API keys
- max_engines_to_try: Maximum number of engines to try before giving up
- max_filtered_results: Maximum number of results to keep after filtering
- settings_snapshot: Settings snapshot for thread context
- programmatic_mode: If True, disables database operations and metrics tracking
- **kwargs: Additional parameters (ignored but accepted for compatibility)
- """
- # Initialize the BaseSearchEngine with the LLM, max_filtered_results, and max_results
- super().__init__(
- llm=llm,
- max_filtered_results=max_filtered_results,
- max_results=max_results,
- settings_snapshot=settings_snapshot,
- programmatic_mode=programmatic_mode,
- )
-
- self.use_api_key_services = use_api_key_services
- self.max_engines_to_try = max_engines_to_try
- self.settings_snapshot = settings_snapshot or {}
-
- # Cache for engine instances
- self.engine_cache: Dict[str, Any] = {}
-
- # Get available engines (excluding 'meta' and 'auto')
- self.available_engines = self._get_available_engines()
- logger.info(
- f"Meta Search Engine initialized with {len(self.available_engines)} available engines: {', '.join(self.available_engines)}"
- )
-
- # Wikipedia fallback. Gated by the egress policy: under STRICT
- # (or any scope that disallows the wikipedia engine) we don't
- # construct a fallback at all, so the meta engine surfaces an
- # empty result rather than silently bypassing policy. When the
- # policy permits it (or can't be determined), construct as
- # before. ``fallback_engine`` stays a plain attribute so callers
- # / tests can reassign it.
- self.fallback_engine: Optional[BaseSearchEngine] = None
- if self._wikipedia_fallback_allowed():
- self.fallback_engine = WikipediaSearchEngine(
- max_results=self.max_results,
- llm=llm,
- max_filtered_results=max_filtered_results,
- )
-
- def _wikipedia_fallback_allowed(self) -> bool:
- """Return True if the egress policy permits the wikipedia
- fallback engine. Fail closed: any policy-related error → False.
-
- Previously this swallowed every Exception and returned True,
- which let a corrupted policy.egress_scope (PolicyDeniedError out
- of context_from_snapshot) construct WikipediaSearchEngine
- directly, bypassing the factory PEP. See plan C3.
- """
- from ...security.egress.policy import (
- PolicyDeniedError,
- context_from_snapshot,
- evaluate_engine,
- )
-
- if not self.settings_snapshot:
- # No snapshot — the meta engine's children will be gated by
- # the factory PEP. Allow the fallback in this offline path.
- return True
- try:
- primary = get_setting_from_snapshot(
- "search.tool",
- "auto",
- settings_snapshot=self.settings_snapshot,
- )
- ctx = context_from_snapshot(
- self.settings_snapshot, primary or "auto"
- )
- except PolicyDeniedError as exc:
- logger.bind(policy_audit=True).warning(
- "wikipedia fallback denied: policy context build failed",
- reason=exc.decision.reason,
- )
- return False
- except ValueError as exc:
- # context_from_snapshot raises ValueError on cross-field
- # invariant violations (e.g. STRICT + meta-picker primary).
- # ValueError has no .decision, so handle it separately — and
- # fail closed (no fallback) rather than let it propagate.
- logger.bind(policy_audit=True).warning(
- "wikipedia fallback denied: invalid policy config",
- error=str(exc),
- )
- return False
- decision = evaluate_engine(
- "wikipedia",
- ctx,
- settings_snapshot=self.settings_snapshot,
- )
- if not decision.allowed:
- logger.bind(policy_audit=True).info(
- "wikipedia fallback disabled by egress policy",
- reason=decision.reason,
- )
- return False
- return True
-
- def _get_search_config(self) -> Dict[str, Any]:
- """Get search config for available engines (used for reliability/strengths lookups)."""
- return get_available_engines(
- settings_snapshot=self.settings_snapshot,
- use_api_key_services=self.use_api_key_services,
- )
-
- def _get_available_engines(self) -> List[str]:
- """Get list of available engines based on user settings."""
- available = get_available_engines(
- settings_snapshot=self.settings_snapshot,
- use_api_key_services=self.use_api_key_services,
- )
-
- if not available:
- error_msg = "No search engines enabled for auto search. Please enable at least one engine in settings."
- logger.error(error_msg)
- raise RuntimeError(error_msg)
-
- names = list(available.keys())
-
- # Egress scope pre-filter so the LLM doesn't pick engines that
- # would be denied at instantiation (advisory only; the factory
- # PEP enforces at child instantiation).
- return filter_candidates_by_egress(names, self.settings_snapshot)
-
- def analyze_query(self, query: str) -> List[str]:
- """
- Analyze the query to determine the best search engines to use.
- Prioritizes SearXNG for general queries, but selects specialized engines
- for domain-specific queries (e.g., scientific papers, code).
-
- Args:
- query: The search query
-
- Returns:
- List of search engine names sorted by suitability
- """
- try:
- # First check if this is a specialized query that should use specific engines
- specialized_domains = {
- "scientific paper": ["arxiv", "pubmed", "wikipedia"],
- "medical research": ["pubmed", "searxng"],
- "clinical": ["pubmed", "searxng"],
- "github": ["github", "searxng"],
- "repository": ["github", "searxng"],
- "code": ["github", "searxng"],
- "programming": ["github", "searxng"],
- }
-
- # Quick heuristic check for specialized queries
- query_lower = query.lower()
- for term, engines in specialized_domains.items():
- if term in query_lower:
- valid_engines = []
- for engine in engines:
- if engine in self.available_engines:
- valid_engines.append(engine)
-
- if valid_engines:
- logger.info(
- f"Detected specialized query type: {term}, using engines: {valid_engines}"
- )
- return valid_engines
-
- # For searches containing "arxiv", prioritize the arxiv engine
- if "arxiv" in query_lower and "arxiv" in self.available_engines:
- return ["arxiv"] + [
- e for e in self.available_engines if e != "arxiv"
- ]
-
- # For searches containing "pubmed", prioritize the pubmed engine
- if "pubmed" in query_lower and "pubmed" in self.available_engines:
- return ["pubmed"] + [
- e for e in self.available_engines if e != "pubmed"
- ]
-
- # Check if SearXNG is available and prioritize it for general queries
- if "searxng" in self.available_engines:
- # For general queries, return SearXNG first followed by reliability-ordered engines
- engines_without_searxng = [
- e for e in self.available_engines if e != "searxng"
- ]
- reliability_sorted = sorted(
- engines_without_searxng,
- key=lambda x: (
- self._get_search_config()
- .get(x, {})
- .get("reliability", 0)
- ),
- reverse=True,
- )
- return ["searxng"] + reliability_sorted
-
- # If LLM is not available or SearXNG is not available, fall back to reliability
- if not self.llm or "searxng" not in self.available_engines:
- logger.warning(
- "No LLM available or SearXNG not available, using reliability-based engines"
- )
- # Return engines sorted by reliability
- return sorted(
- self.available_engines,
- key=lambda x: (
- self._get_search_config()
- .get(x, {})
- .get("reliability", 0)
- ),
- reverse=True,
- )
-
- # Create a prompt that outlines the available search engines and their strengths
- engines_info = []
- for engine_name in self.available_engines:
- try:
- if engine_name in self._get_search_config():
- strengths = self._get_search_config()[engine_name].get(
- "strengths", "General search"
- )
- weaknesses = self._get_search_config()[engine_name].get(
- "weaknesses", "None specified"
- )
- description = self._get_search_config()[
- engine_name
- ].get("description", engine_name)
- engines_info.append(
- f"- {engine_name}: {description}\n Strengths: {strengths}\n Weaknesses: {weaknesses}"
- )
- except KeyError:
- logger.exception(f"Missing key for engine {engine_name}")
-
- # Only proceed if we have engines available to choose from
- if not engines_info:
- logger.warning(
- "No engine information available for prompt, using reliability-based sorting instead"
- )
- return sorted(
- self.available_engines,
- key=lambda x: (
- self._get_search_config()
- .get(x, {})
- .get("reliability", 0)
- ),
- reverse=True,
- )
-
- # Use a stronger prompt that emphasizes SearXNG preference for general queries
- prompt = f"""You are a search query analyst. Consider this search query:
-
-QUERY: {query}
-
-I have these search engines available:
-{chr(10).join(engines_info)}
-
-Determine which search engines would be most appropriate for answering this query.
-First analyze the nature of the query: Is it factual, scientific, code-related, medical, etc.?
-
-IMPORTANT GUIDELINES:
-- Use SearXNG for most general queries as it combines results from multiple search engines
-- For academic/scientific searches, prefer arXiv
-- For medical research, prefer PubMed
-- For code repositories and programming, prefer GitHub
-- For every other query type, SearXNG is usually the best option
-
-Output ONLY a comma-separated list of 1-3 search engine names in order of most appropriate to least appropriate.
-Example output: searxng,wikipedia,brave"""
-
- # Get analysis from LLM
- response = self.llm.invoke(prompt)
-
- # Handle different response formats
- if hasattr(response, "content"):
- content = response.content.strip()
- else:
- content = str(response).strip()
-
- # Extract engine names
- valid_engines = []
- for engine_name in content.split(","):
- cleaned_name = engine_name.strip().lower()
- if cleaned_name in self.available_engines:
- valid_engines.append(cleaned_name)
-
- # If SearXNG is available but not selected by the LLM, add it as a fallback
- if (
- "searxng" in self.available_engines
- and "searxng" not in valid_engines
- ):
- # Add it as the last option if the LLM selected others
- if valid_engines:
- valid_engines.append("searxng")
- # Use it as the first option if no valid engines were selected
- else:
- valid_engines = ["searxng"]
-
- # If still no valid engines, use reliability-based ordering
- if not valid_engines:
- valid_engines = sorted(
- self.available_engines,
- key=lambda x: (
- self._get_search_config()
- .get(x, {})
- .get("reliability", 0)
- ),
- reverse=True,
- )
-
- return valid_engines
- except Exception:
- logger.exception("Error analyzing query with LLM")
- # Fall back to SearXNG if available, then reliability-based ordering
- if "searxng" in self.available_engines:
- return ["searxng"] + sorted(
- [e for e in self.available_engines if e != "searxng"],
- key=lambda x: (
- self._get_search_config()
- .get(x, {})
- .get("reliability", 0)
- ),
- reverse=True,
- )
- return sorted(
- self.available_engines,
- key=lambda x: (
- self._get_search_config().get(x, {}).get("reliability", 0)
- ),
- reverse=True,
- )
-
- def _get_previews(self, query: str) -> List[Dict[str, Any]]:
- """
- Get preview information by selecting the best search engine for this query.
-
- Args:
- query: The search query
-
- Returns:
- List of preview dictionaries
- """
- # Get ranked list of engines for this query
- ranked_engines = self.analyze_query(query)
-
- if not ranked_engines:
- logger.warning(
- "No suitable search engines found for query, using fallback engine"
- )
- fallback = self.fallback_engine
- if fallback is None:
- # Egress policy disallowed the wikipedia fallback; surface
- # an empty result set instead of silently bypassing.
- return []
- return fallback._get_previews(query)
-
- # Limit the number of engines to try
- engines_to_try = ranked_engines[: self.max_engines_to_try]
- logger.info(
- f"SEARCH_PLAN: Will try these engines in order: {', '.join(engines_to_try)}"
- )
-
- all_errors = []
- # Try each engine in order
- for engine_name in engines_to_try:
- logger.info(f"Trying search engine: {engine_name}")
-
- # Get or create the engine instance
- engine = self._get_engine_instance(engine_name)
-
- if not engine:
- logger.warning(f"Failed to initialize {engine_name}, skipping")
- all_errors.append(f"Failed to initialize {engine_name}")
- continue
-
- try:
- # Get previews from this engine
- previews = engine._get_previews(query)
-
- # If search was successful, return results
- if previews and len(previews) > 0:
- logger.info(f"ENGINE_SELECTED: {engine_name}")
- logger.info(
- f"Successfully got {len(previews)} preview results from {engine_name}"
- )
- # Store selected engine for later use
- self._selected_engine = engine
- self._selected_engine_name = engine_name
-
- # Emit a socket event to inform about the selected engine.
- # This runs in a research worker thread (no Flask request
- # context), so the owning user is resolved from the search
- # context that the research service propagates to workers.
- # The emit is scoped to that user's per-user room — never
- # broadcast — so one user's research activity is not
- # visible to other accounts on this shared Socket.IO
- # server. Without a username (programmatic mode, missing
- # context) there is no user tab to notify, so we skip the
- # emit entirely rather than fall back to a broadcast.
- try:
- context = get_search_context()
- username = context.get("username") if context else None
- if username:
- socket_service = SocketIOService()
- socket_service.emit_socket_event(
- "search_engine_selected",
- {
- "engine": engine_name,
- "result_count": len(previews),
- },
- room=socket_service.user_room(username),
- )
- except Exception:
- logger.exception("Socket emit error (non-critical)")
-
- return previews
-
- logger.info(f"{engine_name} returned no previews")
- all_errors.append(f"{engine_name} returned no previews")
-
- except Exception as e:
- error_msg = f"Error getting previews from {engine_name}: {e!s}"
- logger.exception(error_msg)
- all_errors.append(error_msg)
-
- # If we reach here, all engines failed, use fallback
- logger.warning(
- f"All engines failed or returned no preview results: {', '.join(all_errors)}"
- )
- fallback = self.fallback_engine
- if fallback is None:
- # Under STRICT/PRIVATE_ONLY the wikipedia fallback is not
- # permitted; surface the failure to the caller instead of
- # silently bypassing policy.
- return []
- logger.info("Using fallback Wikipedia engine for previews")
- self._selected_engine = fallback
- self._selected_engine_name = "wikipedia"
- return fallback._get_previews(query)
-
- def _get_full_content(
- self, relevant_items: List[Dict[str, Any]]
- ) -> List[Dict[str, Any]]:
- """
- Get full content using the engine that provided the previews.
-
- Args:
- relevant_items: List of relevant preview dictionaries
-
- Returns:
- List of result dictionaries with full content
- """
- # Check if we should get full content
- if get_setting_from_snapshot(
- "search.snippets_only",
- True,
- settings_snapshot=self.settings_snapshot,
- ):
- logger.info("Snippet-only mode, skipping full content retrieval")
- return relevant_items
-
- logger.info("Getting full content for relevant items")
-
- # Use the selected engine to get full content
- if hasattr(self, "_selected_engine"):
- try:
- logger.info(
- f"Using {self._selected_engine_name} to get full content"
- )
- return self._selected_engine._get_full_content(relevant_items)
- except Exception:
- logger.exception(
- f"Error getting full content from {self._selected_engine_name}"
- )
- # Fall back to returning relevant items without full content
- return relevant_items
- else:
- logger.warning(
- "No engine was selected during preview phase, returning relevant items as-is"
- )
- return relevant_items
-
- def _get_engine_instance(
- self, engine_name: str
- ) -> Optional[BaseSearchEngine]:
- """Get or create an instance of the specified search engine"""
- # Return cached instance if available
- if engine_name in self.engine_cache:
- return self.engine_cache[engine_name] # type: ignore[no-any-return]
-
- # Create a new instance
- engine = None
- try:
- # Only pass parameters that all engines accept
- common_params = {"llm": self.llm, "max_results": self.max_results}
-
- # Add max_filtered_results if specified
- if self.max_filtered_results is not None:
- common_params["max_filtered_results"] = (
- self.max_filtered_results
- )
-
- engine = create_search_engine(
- engine_name,
- settings_snapshot=self.settings_snapshot,
- programmatic_mode=self.programmatic_mode,
- **common_params, # type: ignore[arg-type]
- )
- except PolicyDeniedError as exc:
- # A child engine was refused by egress policy (scope mismatch or
- # a corrupt policy config). Skipping it is fail-closed — the
- # forbidden engine never runs — but log with policy_audit so the
- # denial isn't silent (the broad except below would hide it) and
- # the operator can see which engine the scope filtered out.
- logger.bind(policy_audit=True).warning(
- "meta engine: child engine '{}' denied by egress policy ({})",
- engine_name,
- exc.decision.reason,
- )
- return None
- except Exception:
- logger.exception(
- f"Error creating engine instance for {engine_name}"
- )
- return None
-
- if engine:
- # Cache the instance
- self.engine_cache[engine_name] = engine
-
- return engine
-
- def close(self):
- """Close all cached child search engines, fallback engine, and own resources."""
- from ...utilities.resource_utils import safe_close
-
- for engine in self.engine_cache.values():
- safe_close(engine, "child search engine")
- self.engine_cache.clear()
- if (
- hasattr(self, "fallback_engine")
- and self.fallback_engine is not None
- ):
- safe_close(self.fallback_engine, "fallback search engine")
- super().close()
-
- def invoke(self, query: str) -> List[Dict[str, Any]]:
- """Compatibility method for LangChain tools"""
- return self.run(query)
diff --git a/src/local_deep_research/web_search_engines/engines/parallel_search_engine.py b/src/local_deep_research/web_search_engines/engines/parallel_search_engine.py
deleted file mode 100644
index 527a8ae284..0000000000
--- a/src/local_deep_research/web_search_engines/engines/parallel_search_engine.py
+++ /dev/null
@@ -1,745 +0,0 @@
-import os
-import concurrent.futures
-from typing import Any, Dict, List, Optional
-from threading import Lock
-import atexit
-
-from loguru import logger
-
-from ...config.search_config import get_setting_from_snapshot
-from ...database.thread_local_session import cleanup_current_thread
-from ...security.egress.policy import (
- PolicyDeniedError,
- filter_candidates_by_egress,
-)
-from ...utilities.enums import SearchMode
-from ...utilities.json_utils import extract_json, get_llm_response_text
-from ...utilities.thread_context import (
- clear_search_context,
- get_search_context,
- set_search_context,
-)
-from ..search_engine_base import BaseSearchEngine
-from ..search_engine_factory import create_search_engine
-from ..search_engines_config import get_available_engines
-
-# Global thread pool shared by all ParallelSearchEngine instances
-# This prevents creating multiple thread pools and having more threads than expected
-_global_executor: Optional[concurrent.futures.ThreadPoolExecutor] = None
-_global_executor_lock = Lock()
-
-
-def _get_global_executor(
- max_workers: Optional[int] = None,
-) -> Optional[concurrent.futures.ThreadPoolExecutor]:
- """
- Get or initialize the global thread pool executor.
- Thread-safe lazy initialization ensures only one pool is created.
-
- Args:
- max_workers: Number of worker threads. If None, uses Python's recommended
- formula: min(32, (os.cpu_count() or 1) + 4) for I/O-bound operations.
- Only used on first initialization; subsequent calls ignore this parameter.
-
- Returns:
- The global ThreadPoolExecutor instance, or None if initialization fails
- """
- global _global_executor
-
- with _global_executor_lock:
- if _global_executor is None:
- if max_workers is None:
- max_workers = min(32, (os.cpu_count() or 1) + 4)
-
- try:
- _global_executor = concurrent.futures.ThreadPoolExecutor(
- max_workers=max_workers,
- thread_name_prefix="parallel_search_",
- )
- logger.info(
- f"Initialized global ThreadPool with {max_workers} workers "
- f"(shared by all ParallelSearchEngine instances)"
- )
- except Exception:
- logger.exception(
- "Failed to create global ThreadPoolExecutor, parallel search will not work"
- )
- return None
-
- return _global_executor
-
-
-def shutdown_global_executor(wait: bool = True):
- """
- Shutdown the global thread pool executor.
-
- This is called automatically at process exit via atexit.
- After calling this, any new ParallelSearchEngine instances will create a new pool.
-
- Args:
- wait: If True, wait for all threads to complete before returning
- """
- global _global_executor
-
- with _global_executor_lock:
- if _global_executor is not None:
- try:
- _global_executor.shutdown(wait=wait)
- logger.info("Global ThreadPool shutdown complete")
- except Exception:
- logger.exception("Error shutting down global ThreadPool")
- finally:
- _global_executor = None
-
-
-# Register automatic cleanup at process exit
-atexit.register(lambda: shutdown_global_executor(wait=True))
-
-
-class ParallelSearchEngine(BaseSearchEngine):
- """
- Parallel search engine that executes multiple search engines simultaneously.
- Uses LLM to select appropriate engines based on query, then runs them all in parallel.
-
- Thread Pool Management:
- All instances share a single global thread pool to prevent thread proliferation.
- The pool is automatically cleaned up at process exit.
-
- Usage:
- engine = ParallelSearchEngine(llm)
- results = engine.run("query")
- # No manual cleanup needed - global pool is shared and cleaned up automatically
- """
-
- def __init__(
- self,
- llm,
- max_results: int = 10,
- use_api_key_services: bool = True,
- max_engines_to_select: int = 100, # Allow selecting all available engines
- allow_local_engines: bool = False, # Disabled by default for privacy
- include_generic_engines: bool = True, # Always include generic search engines
- search_mode: SearchMode = SearchMode.ALL,
- max_filtered_results: Optional[int] = None,
- settings_snapshot: Optional[Dict[str, Any]] = None,
- programmatic_mode: bool = False,
- max_workers: Optional[
- int
- ] = None, # Thread pool size (None = auto-detect)
- **kwargs,
- ):
- """
- Initialize the parallel search engine.
-
- All instances share a global thread pool. The first instance created will
- initialize the pool with the specified max_workers (or auto-detected value).
- Subsequent instances reuse the existing pool.
-
- Args:
- llm: Language model instance for query classification
- max_results: Maximum number of search results to return per engine
- use_api_key_services: Whether to include services that require API keys
- max_engines_to_select: Maximum number of engines to select for parallel execution
- allow_local_engines: Whether to include local/private engines (WARNING: May expose personal data to web)
- include_generic_engines: Always include generic search engines (searxng, brave, ddg, etc.)
- search_mode: SearchMode enum value - ALL for all engines, SCIENTIFIC for scientific + generic engines only
- max_filtered_results: Maximum number of results to keep after filtering
- settings_snapshot: Settings snapshot for thread context
- programmatic_mode: If True, disables database operations and metrics tracking
- max_workers: Thread pool size for the FIRST instance only. If None, uses Python's
- recommended formula: min(32, (os.cpu_count() or 1) + 4) for I/O-bound operations.
- Ignored if the global pool is already initialized.
- **kwargs: Additional parameters (ignored but accepted for compatibility)
- """
- # Parallel search aggregates results from multiple engines, so
- # it runs with a higher post-filter cap than a single-engine
- # search would get from DEFAULT_MAX_FILTERED_RESULTS.
- if max_filtered_results is None:
- max_filtered_results = 50
- logger.info(
- f"Setting max_filtered_results to {max_filtered_results} for parallel search"
- )
-
- super().__init__(
- llm=llm,
- max_filtered_results=max_filtered_results,
- max_results=max_results,
- settings_snapshot=settings_snapshot,
- programmatic_mode=programmatic_mode,
- )
-
- self.use_api_key_services = use_api_key_services
- self.max_engines_to_select = max_engines_to_select
- self.allow_local_engines = allow_local_engines
- self.include_generic_engines = include_generic_engines
- self.search_mode = search_mode
- self.settings_snapshot = settings_snapshot or {}
-
- # Disable LLM relevance filtering at the parallel level by default
- # Individual engines can still filter their own results
- # Double filtering (engines + parallel) is too aggressive
- self.enable_llm_relevance_filter = kwargs.get(
- "enable_llm_relevance_filter", False
- )
-
- # Cache for engine instances
- self.engine_cache: Dict[str, Any] = {}
- self.cache_lock = Lock()
-
- # Initialize global thread pool (thread-safe, only happens once)
- # All instances share the same pool to prevent thread proliferation
- _get_global_executor(max_workers)
-
- # Get available engines (excluding 'meta', 'auto', and 'parallel')
- self.available_engines = self._get_available_engines()
- logger.info(
- f"Parallel Search Engine initialized with {len(self.available_engines)} available engines: {', '.join(self.available_engines)}"
- )
-
- def _get_search_config(self) -> Dict[str, Any]:
- """Get search config for available engines."""
- return get_available_engines(
- settings_snapshot=self.settings_snapshot,
- use_api_key_services=self.use_api_key_services,
- )
-
- def _get_available_engines(self) -> List[str]:
- """Get list of available engines, applying parallel-specific filters
- (is_public, search mode) on top of the shared base filter."""
- base_available = get_available_engines(
- settings_snapshot=self.settings_snapshot,
- use_api_key_services=self.use_api_key_services,
- )
-
- available = []
- for name, config_ in base_available.items():
- # Try to get the engine class to check is_public flag
- success, engine_class, error_msg = (
- BaseSearchEngine._load_engine_class(name, config_)
- )
-
- if not success:
- logger.debug(error_msg)
- continue
-
- # Check if engine is public or if local engines are allowed
- if hasattr(engine_class, "is_public"):
- if not engine_class.is_public and not self.allow_local_engines:
- logger.debug(f"Skipping local/private engine: {name}")
- continue
- if not engine_class.is_public and self.allow_local_engines:
- logger.warning(
- f"Including local/private engine {name} - data may be exposed"
- )
- else:
- # No is_public flag - assume it's private/local for safety
- if not self.allow_local_engines:
- logger.debug(
- f"Skipping engine {name} - no is_public flag and local engines not allowed"
- )
- continue
-
- # Apply scientific mode filtering if enabled
- if self.search_mode == SearchMode.SCIENTIFIC:
- is_scientific = getattr(engine_class, "is_scientific", False)
- is_generic = getattr(engine_class, "is_generic", False)
-
- if not (is_scientific or is_generic):
- logger.debug(
- f"Skipping {name} in scientific mode (not scientific or generic)"
- )
- continue
-
- logger.debug(
- f"Including {name} in scientific mode (scientific={is_scientific}, generic={is_generic})"
- )
-
- available.append(name)
-
- # Egress scope pre-filter: remove engines that would be denied at
- # instantiation so the LLM doesn't waste selection slots on them
- # (advisory only; the factory PEP enforces at child instantiation).
- return filter_candidates_by_egress(
- available, self.settings_snapshot
- )
-
- def _get_available_generic_engines(self) -> List[str]:
- """Get list of available generic search engines that pass API key checks"""
- generic_engines = []
- config_data = self._get_search_config()
-
- for name, config_ in config_data.items():
- # Skip if not in available engines (already filtered for API keys etc)
- if name not in self.available_engines:
- continue
-
- # Load the engine class to check is_generic flag
- success, engine_class, error_msg = (
- BaseSearchEngine._load_engine_class(name, config_)
- )
-
- if not success:
- logger.debug(
- f"Could not check if {name} is generic: {error_msg}"
- )
- continue
-
- # Check if engine is generic
- if getattr(engine_class, "is_generic", False):
- generic_engines.append(name)
- logger.debug(f"Found generic engine: {name}")
-
- return generic_engines
-
- def select_engines(self, query: str) -> List[str]:
- """
- Use LLM to select appropriate search engines based only on names.
-
- Args:
- query: The search query
-
- Returns:
- List of selected engine names
- """
- if not self.llm or not self.available_engines:
- logger.warning(
- "No LLM or no available engines, using all available"
- )
- return self.available_engines[: self.max_engines_to_select]
-
- try:
- # Get list of engines for LLM to select from (exclude generic ones if they'll be auto-added)
- engines_for_selection = self.available_engines.copy()
- generic_engines = []
-
- if self.include_generic_engines:
- generic_engines = self._get_available_generic_engines()
- # Remove generic engines from selection since they'll be added automatically
- engines_for_selection = [
- e for e in engines_for_selection if e not in generic_engines
- ]
- logger.debug(
- f"Excluding generic engines from LLM selection: {generic_engines}"
- )
-
- # If no specialized engines available, just return the generic ones
- if not engines_for_selection:
- logger.info(
- f"No specialized engines available, using generic engines: {generic_engines}"
- )
- return generic_engines
-
- # Create a simple prompt with just non-generic engine names
- engine_list = "\n".join(
- [
- f"[{i}] {name}"
- for i, name in enumerate(engines_for_selection)
- ]
- )
-
- logger.debug(f"Engines for LLM selection: {engines_for_selection}")
-
- prompt = f"""Query: {query}
-
-Available search engines:
-{engine_list}
-
-Select the most appropriate search engines for this query. Return ONLY a JSON array of indices.
-Example: [0, 2, 5]
-
-Select up to {self.max_engines_to_select} engines that would best answer this query."""
-
- logger.debug("Sending prompt to LLM for engine selection")
- # Get LLM response
- response = self.llm.invoke(prompt)
- content = get_llm_response_text(response)
-
- indices = extract_json(content, expected_type=list)
-
- if indices is not None:
- # Convert indices to engine names (from the filtered list)
- selected_engines = []
- for idx in indices:
- if isinstance(idx, int) and 0 <= idx < len(
- engines_for_selection
- ):
- selected_engines.append(engines_for_selection[idx])
-
- if selected_engines:
- # Add generic search engines (they were excluded from selection)
- if self.include_generic_engines:
- for engine in generic_engines:
- if engine not in selected_engines:
- selected_engines.append(engine)
- logger.debug(f"Added generic engine: {engine}")
-
- logger.info(f"Final selected engines: {selected_engines}")
- return selected_engines
-
- # Fallback if parsing fails - return generic engines plus some specialized ones
- logger.warning(
- "Failed to parse LLM response, using generic engines + top specialized"
- )
- result = (
- generic_engines.copy() if self.include_generic_engines else []
- )
- for engine in self.available_engines[: self.max_engines_to_select]:
- if engine not in result:
- result.append(engine)
- return result
-
- except Exception:
- logger.exception("Error selecting engines with LLM")
- # Fallback to using generic engines + available engines
- if self.include_generic_engines:
- generic_engines = self._get_available_generic_engines()
- result = generic_engines.copy()
- for engine in self.available_engines[
- : self.max_engines_to_select
- ]:
- if engine not in result:
- result.append(engine)
- return result
- return self.available_engines[: self.max_engines_to_select]
-
- def _get_engine_instance(
- self, engine_name: str
- ) -> Optional[BaseSearchEngine]:
- """Get or create an instance of the specified search engine"""
- with self.cache_lock:
- # Return cached instance if available
- if engine_name in self.engine_cache:
- return self.engine_cache[engine_name] # type: ignore[no-any-return]
-
- # Create a new instance
- engine = None
- try:
- # Only pass parameters that all engines accept
- common_params = {
- "llm": self.llm,
- "max_results": self.max_results,
- }
-
- # Add max_filtered_results if specified
- if self.max_filtered_results is not None:
- common_params["max_filtered_results"] = (
- self.max_filtered_results
- )
-
- engine = create_search_engine(
- engine_name,
- settings_snapshot=self.settings_snapshot,
- programmatic_mode=self.programmatic_mode,
- **common_params, # type: ignore[arg-type]
- )
-
- # Individual engines use their auto-detected filtering settings
- # The factory enables LLM filtering for scientific engines (arXiv, etc.)
- # and disables it for generic engines (Google, Brave, etc.)
- except PolicyDeniedError as exc:
- # Child engine refused by egress policy. Skipping is
- # fail-closed (the forbidden engine never runs); log with
- # policy_audit so the denial isn't silent.
- logger.bind(policy_audit=True).warning(
- "parallel engine: child engine '{}' denied by egress "
- "policy ({})",
- engine_name,
- exc.decision.reason,
- )
- return None
- except Exception:
- logger.exception(
- f"Error creating engine instance for {engine_name}"
- )
- return None
-
- if engine:
- # Cache the instance
- self.engine_cache[engine_name] = engine
-
- return engine
-
- def _execute_single_engine(
- self, engine_name: str, query: str
- ) -> Dict[str, Any]:
- """
- Execute a single search engine and return results.
-
- Context propagation and thread-local cleanup are handled by
- ``_run_with_context`` at the submit site in ``_get_previews``,
- which captures the submitter's context once per request.
-
- Args:
- engine_name: Name of the engine to execute
- query: The search query
-
- Returns:
- Dictionary with engine name and results or error
- """
- logger.info(f"Executing search on {engine_name}")
-
- engine = self._get_engine_instance(engine_name)
- if not engine:
- return {
- "engine": engine_name,
- "success": False,
- "error": f"Failed to initialize {engine_name}",
- "results": [],
- }
-
- try:
- # Run the engine properly through its run() method
- # This ensures proper filter application, context propagation, etc.
- results = engine.run(query)
-
- if results and len(results) > 0:
- logger.info(f"Got {len(results)} results from {engine_name}")
- return {
- "engine": engine_name,
- "success": True,
- "results": results,
- "count": len(results),
- }
- return {
- "engine": engine_name,
- "success": False,
- "error": "No results",
- "results": [],
- }
-
- except Exception:
- logger.exception(f"Error executing {engine_name}")
- return {
- "engine": engine_name,
- "success": False,
- "error": f"Engine {engine_name} failed",
- "results": [],
- }
-
- def _get_previews(self, query: str) -> List[Dict[str, Any]]:
- """
- Get preview information by executing selected engines in parallel.
-
- Args:
- query: The search query
-
- Returns:
- Combined list of preview dictionaries from all successful engines
- """
- # Select engines for this query
- selected_engines = self.select_engines(query)
-
- if not selected_engines:
- logger.warning("No engines selected")
- return []
-
- logger.info(
- f"PARALLEL_SEARCH: Executing {len(selected_engines)} engines in parallel: {', '.join(selected_engines)}"
- )
-
- # NOTE: no socket event is emitted here on purpose. The old
- # "parallel_search_started" event had no frontend listener and was
- # broadcast to *every* connected client, leaking the user's query to
- # other accounts in multi-user deployments (same CWE-200 class as the
- # settings_changed leak fixed for user-scoped rooms).
-
- # Execute all engines in parallel using persistent thread pool
- all_results = []
- engine_results = {}
-
- # Get the global thread pool
- executor = _get_global_executor()
- if executor is None:
- logger.error(
- "Global thread pool not available, cannot execute parallel search"
- )
- return []
-
- # Capture submitter's research context ONCE (in the request thread,
- # where it is populated by the strategy's caller). Workers in the
- # global pool do not inherit thread-local state, so we must re-apply
- # it per task and clear it (+ clean up thread-local DB/session/password
- # state) in a finally block so nothing leaks to the next task that
- # lands on the same worker.
- submitter_ctx = get_search_context()
- # Also capture the egress audit-hook context: threading.local is NOT
- # inherited by pool workers, so the PEP-578 socket backstop would be
- # inactive on the worker that runs the actual search/LLM sockets
- # unless we re-arm it per task (mirrors the search-context handling).
- try:
- from ...security.egress.audit_hook import (
- get_active_context as _get_egress_ctx,
- )
-
- submitter_egress_ctx = _get_egress_ctx()
- except Exception:
- submitter_egress_ctx = None
-
- def _run_with_context(fn, *fargs):
- if submitter_ctx is not None:
- set_search_context(submitter_ctx)
- if submitter_egress_ctx is not None:
- from ...security.egress.audit_hook import (
- set_active_context as _set_egress_ctx,
- )
-
- _set_egress_ctx(submitter_egress_ctx)
- try:
- return fn(*fargs)
- finally:
- if submitter_egress_ctx is not None:
- from ...security.egress.audit_hook import (
- clear_active_context as _clear_egress_ctx,
- )
-
- _clear_egress_ctx()
- clear_search_context()
- try:
- cleanup_current_thread()
- except Exception:
- logger.debug(
- "parallel_search submit wrapper: cleanup_current_thread failed",
- exc_info=True,
- )
-
- # Submit all tasks to the global executor
- future_to_engine = {
- executor.submit(
- _run_with_context,
- self._execute_single_engine,
- engine_name,
- query,
- ): engine_name
- for engine_name in selected_engines
- }
-
- # Collect results as they complete
- for future in concurrent.futures.as_completed(future_to_engine):
- engine_name = future_to_engine[future]
- try:
- result = future.result()
- engine_results[engine_name] = result
-
- if result["success"]:
- # Add source information to each result
- for item in result["results"]:
- item["search_engine"] = engine_name
- all_results.extend(result["results"])
- # NOTE: the old per-engine "engine_completed" socket event was
- # removed: it had no frontend listener and was broadcast to
- # every connected client, leaking engine names / error details
- # across user accounts in multi-user deployments.
-
- except Exception:
- logger.exception(f"Failed to get result from {engine_name}")
- engine_results[engine_name] = {
- "engine": engine_name,
- "success": False,
- "error": "Search execution failed",
- "results": [],
- }
-
- # Log summary
- successful_engines = [
- name for name, res in engine_results.items() if res["success"]
- ]
- failed_engines = [
- name for name, res in engine_results.items() if not res["success"]
- ]
-
- logger.info(
- f"PARALLEL_SEARCH_COMPLETE: {len(successful_engines)} succeeded, {len(failed_engines)} failed"
- )
- if successful_engines:
- logger.info(f"Successful engines: {', '.join(successful_engines)}")
- if failed_engines:
- logger.info(f"Failed engines: {', '.join(failed_engines)}")
-
- # Log sample result to understand structure
- if all_results:
- logger.debug(
- f"Sample result keys from first result: {list(all_results[0].keys())}"
- )
- logger.debug(f"Sample result: {str(all_results[0])[:500]}")
-
- logger.info(f"Total results from all engines: {len(all_results)}")
-
- # Store the engine results for potential use in _get_full_content
- self._engine_results = engine_results
- self._successful_engines = successful_engines
-
- return all_results
-
- def _get_full_content(
- self, relevant_items: List[Dict[str, Any]]
- ) -> List[Dict[str, Any]]:
- """
- Get full content for the relevant items.
- Since we ran multiple engines, we'll group items by their source engine
- and get full content from each engine for its own results.
-
- Args:
- relevant_items: List of relevant preview dictionaries
-
- Returns:
- List of result dictionaries with full content
- """
- # Check if we should get full content
- if get_setting_from_snapshot(
- "search.snippets_only",
- True,
- settings_snapshot=self.settings_snapshot,
- ):
- logger.info("Snippet-only mode, skipping full content retrieval")
- return relevant_items
-
- logger.info("Getting full content for relevant items")
-
- # Group items by their source engine
- items_by_engine: Dict[str, List[Dict[str, Any]]] = {}
- for item in relevant_items:
- engine_name = item.get("search_engine")
- if engine_name:
- if engine_name not in items_by_engine:
- items_by_engine[engine_name] = []
- items_by_engine[engine_name].append(item)
-
- # Get full content from each engine for its items
- all_full_content = []
-
- for engine_name, items in items_by_engine.items():
- engine = self._get_engine_instance(engine_name)
- if engine:
- try:
- logger.info(
- f"Getting full content from {engine_name} for {len(items)} items"
- )
- full_content = engine._get_full_content(items)
- all_full_content.extend(full_content)
- except Exception:
- logger.exception(
- f"Error getting full content from {engine_name}"
- )
- # Fall back to returning items without full content
- all_full_content.extend(items)
- else:
- # No engine available, return items as-is
- all_full_content.extend(items)
-
- return all_full_content
-
- def close(self):
- """Close all cached child search engines and own resources."""
- from ...utilities.resource_utils import safe_close
-
- for engine in self.engine_cache.values():
- safe_close(engine, "child search engine")
- self.engine_cache.clear()
- super().close()
-
- def invoke(self, query: str) -> List[Dict[str, Any]]:
- """Compatibility method for LangChain tools"""
- return self.run(query)
-
- # Note: No shutdown() or context manager methods needed
- # The global thread pool is automatically cleaned up at process exit via atexit
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.py
index 2569aa6f3e..689053a3a5 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
@@ -49,10 +49,10 @@ class ElasticsearchSearchEngine(BaseSearchEngine):
primary = (
get_setting_from_snapshot(
"search.tool",
- default="auto",
+ default="searxng",
settings_snapshot=snapshot,
)
- or "auto"
+ or "searxng"
)
ctx = context_from_snapshot(snapshot, primary)
return ctx.scope in (
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.py
index 3f767b3359..1560ae3e3d 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
@@ -1084,12 +1084,12 @@ class BaseSearchEngine(ABC):
)
return None
- primary_raw = self.settings_snapshot.get("search.tool", "auto")
+ primary_raw = self.settings_snapshot.get("search.tool", "searxng")
if isinstance(primary_raw, dict) and "value" in primary_raw:
primary_raw = primary_raw["value"]
try:
return context_from_snapshot(
- self.settings_snapshot, primary_raw or "auto"
+ self.settings_snapshot, primary_raw or "searxng"
)
except (PolicyDeniedError, ValueError) as exc:
logger.bind(policy_audit=True).warning(
diff --git a/src/local_deep_research/web_search_engines/search_engine_factory.py b/src/local_deep_research/web_search_engines/search_engine_factory.py
index d2404952f6..16dded653f 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
@@ -5,7 +5,6 @@ from loguru import logger
from ..security.egress.policy import PolicyDeniedError
from ..security.module_whitelist import get_safe_module_class
-from ..utilities.enums import SearchMode
from .retriever_registry import retriever_registry
from .search_engine_base import BaseSearchEngine
from .search_engines_config import search_config
@@ -24,7 +23,7 @@ def create_search_engine(
Args:
engine_name: Name of the search engine to create
- llm: Language model instance (required for some engines like meta)
+ llm: Language model instance (passed to engines that accept one)
programmatic_mode: If True, disables database operations and metrics tracking
**kwargs: Additional parameters to override defaults
@@ -37,33 +36,9 @@ def create_search_engine(
)
# Egress policy PEP runs AFTER retriever-registry + config lookup, so
- # registered retrievers and meta-pickers (handled separately below)
- # don't go through engine-name classification. The actual call site
- # is right before engine instantiation, further down.
-
- # Handle special parallel search engine variants
- if engine_name == "parallel_scientific":
- logger.info("Creating scientific parallel search engine")
- from .engines.parallel_search_engine import ParallelSearchEngine
-
- return ParallelSearchEngine(
- llm=llm,
- search_mode=SearchMode.SCIENTIFIC,
- settings_snapshot=settings_snapshot,
- programmatic_mode=programmatic_mode,
- **kwargs,
- )
- if engine_name == "parallel":
- logger.info("Creating standard parallel search engine")
- from .engines.parallel_search_engine import ParallelSearchEngine
-
- return ParallelSearchEngine(
- llm=llm,
- search_mode=SearchMode.ALL,
- settings_snapshot=settings_snapshot,
- programmatic_mode=programmatic_mode,
- **kwargs,
- )
+ # registered retrievers don't go through engine-name classification.
+ # The actual call site is right before engine instantiation, further
+ # down.
# Check if this is a registered retriever first
retriever = retriever_registry.get(engine_name)
@@ -76,7 +51,7 @@ def create_search_engine(
# NB: PolicyDeniedError is imported at MODULE level — importing it
# again here (function-local) would shadow it across the whole
# function and make the outer `except PolicyDeniedError` an unbound
- # local on code paths that skip this branch (e.g. meta-pickers).
+ # local on code paths that skip this branch.
from ..security.egress.policy import (
Decision,
context_from_snapshot,
@@ -150,13 +125,13 @@ def create_search_engine(
if engine_name == "none":
# Reject the literal string "none". Historically this silently fell
- # through to the "auto" engine and hit live networks — callers that
+ # through to a meta engine and hit live networks — callers that
# wanted an offline pipeline were unknowingly doing real searches.
raise ValueError(
"search.tool='none' is not a valid engine. Register a LangChain "
"retriever via `retrievers={...}` (see "
"examples/llm_integration/mock_llm_example.py) or pick a real "
- "engine. Previously this silently fell back to 'auto'."
+ "engine."
)
if engine_name not in config:
@@ -199,76 +174,68 @@ def create_search_engine(
engine_name = config_key
break
- # If still not found, FAIL CLOSED. Previously the factory silently
- # rewrote unknown engine names to "auto", which then matched the
- # local skip-list at line 213 below and bypassed evaluate_engine
- # entirely. Callers that want auto behavior must pass "auto"
- # explicitly. See plan C2 (cryptic-tinkering-iverson.md).
+ # If still not found, FAIL CLOSED.
# We raise a plain ValueError (not PolicyDeniedError) because
# "unknown engine name" is a config/wiring error, not a policy
# decision — keeping the exception type clean lets policy-aware
# callers tell them apart.
if engine_name not in config:
logger.bind(policy_audit=True).warning(
- "unknown engine name rejected (was silently rewritten to 'auto' previously)",
+ "unknown engine name rejected",
engine=engine_name,
available=list(config.keys()),
)
raise ValueError(
f"Unknown search engine '{engine_name}'. Available: "
- f"{sorted(config.keys())}. To use auto-selection, "
- "pass engine_name='auto' explicitly."
+ f"{sorted(config.keys())}. The 'auto', 'meta', 'parallel' "
+ "and 'parallel_scientific' meta engines were removed — the "
+ "langgraph-agent strategy (the default) selects engines "
+ "dynamically; pick a concrete engine instead."
)
# Egress policy PEP: gate the resolved engine against the user's declared
# scope. Lazy import to break the circular dependency
# (security/egress/policy.py → web_search_engines/* → security/*).
- # Skipped for engines registered dynamically (`auto`, `meta`, `parallel`,
- # `parallel_scientific` — their children are gated when instantiated).
- if engine_name not in ("auto", "meta", "parallel", "parallel_scientific"):
- # PolicyDeniedError comes from the module-level import (see the note
- # in the retriever branch above — re-importing it here would shadow
- # it function-wide and break the outer except clause).
- from ..security.egress.policy import (
- Decision,
- context_from_snapshot,
- evaluate_engine,
- )
-
- primary_engine_raw = settings_snapshot.get("search.tool", engine_name)
- if (
- isinstance(primary_engine_raw, dict)
- and "value" in primary_engine_raw
- ):
- primary_engine_raw = primary_engine_raw["value"]
- primary_engine = primary_engine_raw or engine_name
+ # PolicyDeniedError comes from the module-level import (see the note
+ # in the retriever branch above — re-importing it here would shadow
+ # it function-wide and break the outer except clause).
+ from ..security.egress.policy import (
+ Decision,
+ context_from_snapshot,
+ evaluate_engine,
+ )
- try:
- ctx = context_from_snapshot(
- settings_snapshot, primary_engine, username=username
- )
- except ValueError as exc:
- raise PolicyDeniedError(
- Decision(False, "invalid_policy_config"),
- target=engine_name,
- ) from exc
+ primary_engine_raw = settings_snapshot.get("search.tool", engine_name)
+ if isinstance(primary_engine_raw, dict) and "value" in primary_engine_raw:
+ primary_engine_raw = primary_engine_raw["value"]
+ primary_engine = primary_engine_raw or engine_name
- # Pass the engine config entry as metadata so a per-collection
- # is_public classification is honored without a redundant DB lookup.
- decision = evaluate_engine(
- engine_name,
- ctx,
- settings_snapshot=settings_snapshot,
- metadata=config.get(engine_name),
+ try:
+ ctx = context_from_snapshot(
+ settings_snapshot, primary_engine, username=username
)
- if not decision.allowed:
- logger.bind(policy_audit=True).warning(
- "engine denied by egress policy",
- engine=engine_name,
- scope=ctx.scope.value,
- reason=decision.reason,
- )
- raise PolicyDeniedError(decision, target=engine_name)
+ except ValueError as exc:
+ raise PolicyDeniedError(
+ Decision(False, "invalid_policy_config"),
+ target=engine_name,
+ ) from exc
+
+ # Pass the engine config entry as metadata so a per-collection
+ # is_public classification is honored without a redundant DB lookup.
+ decision = evaluate_engine(
+ engine_name,
+ ctx,
+ settings_snapshot=settings_snapshot,
+ metadata=config.get(engine_name),
+ )
+ if not decision.allowed:
+ logger.bind(policy_audit=True).warning(
+ "engine denied by egress policy",
+ engine=engine_name,
+ scope=ctx.scope.value,
+ reason=decision.reason,
+ )
+ raise PolicyDeniedError(decision, target=engine_name)
# Get engine configuration
engine_config = config[engine_name]
diff --git a/src/local_deep_research/web_search_engines/search_engines_config.py b/src/local_deep_research/web_search_engines/search_engines_config.py
index 9bea0aabc7..50aa9d881f 100644
--- a/src/local_deep_research/web_search_engines/search_engines_config.py
+++ b/src/local_deep_research/web_search_engines/search_engines_config.py
@@ -117,14 +117,6 @@ def search_config(
search_engines = _extract_per_engine_config(config_data)
- search_engines["auto"] = _get_setting(
- "search.engine.auto",
- {},
- db_session=db_session,
- settings_snapshot=settings_snapshot,
- username=username,
- )
-
# Inject module/class from the hardcoded engine registry.
# This is the single source of truth for which Python module implements
# each engine — these values are never read from the settings DB.
@@ -167,10 +159,6 @@ def search_config(
)
logger.info(f"\n {', '.join(sorted(search_engines.keys()))} \n")
- # Add alias for 'auto' if it exists
- if "auto" in search_engines and "meta" not in search_engines:
- search_engines["meta"] = search_engines["auto"]
-
# Register Library RAG as a search engine
library_enabled = _get_setting(
"search.engine.library.enabled",
@@ -292,9 +280,9 @@ def get_available_engines(
Return search engines that are actually usable: enabled for auto-search
and with valid API keys when required.
- This is the single shared filter used by MetaSearchEngine,
- ParallelSearchEngine, and MCPSearchStrategy so they all agree on which
- engines are available.
+ This is the single shared filter used by the langgraph-agent tool
+ builder and MCPSearchStrategy so they all agree on which engines are
+ available.
Args:
settings_snapshot: Thread-safe settings snapshot.
@@ -314,9 +302,7 @@ def get_available_engines(
return {}
all_engines = search_config(settings_snapshot=settings_snapshot)
- excluded = {"meta", "auto", "parallel"}
- if exclude_engines:
- excluded |= exclude_engines
+ excluded = set(exclude_engines) if exclude_engines else set()
available: Dict[str, Any] = {}
diff --git a/tests/api/conftest.py b/tests/api/conftest.py
index 4cbb6747b1..acc9eb1e92 100644
--- a/tests/api/conftest.py
+++ b/tests/api/conftest.py
@@ -69,7 +69,7 @@ def sample_settings_snapshot():
"llm.provider": {"value": "ollama", "ui_element": "select"},
"llm.model": {"value": "gemma3:12b", "ui_element": "text"},
"llm.temperature": {"value": 0.7, "ui_element": "range"},
- "search.tool": {"value": "auto", "ui_element": "select"},
+ "search.tool": {"value": "searxng", "ui_element": "select"},
"search.iterations": {"value": 2, "ui_element": "number"},
"search.questions_per_iteration": {"value": 3, "ui_element": "number"},
"search.max_results": {"value": 20, "ui_element": "number"},
diff --git a/tests/api/test_research_functions.py b/tests/api/test_research_functions.py
index a80c4b164d..cd83963157 100644
--- a/tests/api/test_research_functions.py
+++ b/tests/api/test_research_functions.py
@@ -317,7 +317,9 @@ class TestQuickSummary:
"""Test that provided settings_snapshot is used."""
# Create a valid settings snapshot with required keys
custom_snapshot = {
- "search.tool": {"value": "auto"},
+ # "library" is always available without extra engine config
+ # (searxng needs an instance URL before the factory accepts it).
+ "search.tool": {"value": "library"},
"custom": "settings",
}
with patch(
diff --git a/tests/api_tests/populate_search_engines.py b/tests/api_tests/populate_search_engines.py
index 017e5698e4..3c42543d36 100644
--- a/tests/api_tests/populate_search_engines.py
+++ b/tests/api_tests/populate_search_engines.py
@@ -67,72 +67,9 @@ def populate_search_engines():
},
}
- # Also add the auto option
- auto_engine = {
- "auto": {
- "display_name": "Auto (Multiple Engines)",
- "description": "Automatically select best search engines",
- "strengths": ["Adaptive", "Multiple sources", "Best coverage"],
- }
- }
-
session = get_db_session()
try:
- # Add auto engine
- for key, props in auto_engine.items():
- # Display name
- display_setting = Setting(
- key="search.engine.auto.display_name",
- value=props["display_name"],
- type="SEARCH",
- category="search",
- name="Auto Display Name",
- description="Display name for auto search engine",
- )
- existing = (
- session.query(Setting)
- .filter_by(key=display_setting.key)
- .first()
- )
- if not existing:
- session.add(display_setting)
- logger.info(f"Added {display_setting.key}")
-
- # Description
- desc_setting = Setting(
- key="search.engine.auto.description",
- value=props["description"],
- type="SEARCH",
- category="search",
- name="Auto Description",
- description="Description for auto search engine",
- )
- existing = (
- session.query(Setting).filter_by(key=desc_setting.key).first()
- )
- if not existing:
- session.add(desc_setting)
- logger.info(f"Added {desc_setting.key}")
-
- # Strengths
- strengths_setting = Setting(
- key="search.engine.auto.strengths",
- value=props["strengths"],
- type="SEARCH",
- category="search",
- name="Auto Strengths",
- description="Strengths of auto search engine",
- )
- existing = (
- session.query(Setting)
- .filter_by(key=strengths_setting.key)
- .first()
- )
- if not existing:
- session.add(strengths_setting)
- logger.info(f"Added {strengths_setting.key}")
-
# Add web search engines
for engine_name, props in search_engines.items():
# Display name
diff --git a/tests/api_tests_with_login/pytest_tests/test_export_formats.py b/tests/api_tests_with_login/pytest_tests/test_export_formats.py
index 5e1aa23ad2..3e654ad2bd 100644
--- a/tests/api_tests_with_login/pytest_tests/test_export_formats.py
+++ b/tests/api_tests_with_login/pytest_tests/test_export_formats.py
@@ -21,7 +21,7 @@ def test_export_latex(auth_session, base_url):
# First, start a simple research
research_data = {
"query": f"Test LaTeX export {time.time()}",
- "search_engine": "auto",
+ "search_engine": "searxng",
"model": "gemma3n:e2b",
"model_provider": "OLLAMA",
"mode": "quick",
@@ -103,7 +103,7 @@ def test_export_pdf_via_javascript(auth_session, base_url):
# First, start a simple research
research_data = {
"query": f"Test PDF export {time.time()}",
- "search_engine": "auto",
+ "search_engine": "searxng",
"model": "gemma3n:e2b",
"model_provider": "OLLAMA",
"mode": "quick",
@@ -167,7 +167,7 @@ def test_export_markdown(auth_session, base_url):
# First, start a simple research
research_data = {
"query": f"Test Markdown export {time.time()}",
- "search_engine": "auto",
+ "search_engine": "searxng",
"model": "gemma3n:e2b",
"model_provider": "OLLAMA",
"mode": "quick",
@@ -255,7 +255,7 @@ def test_export_quarto(auth_session, base_url):
# First, start a simple research
research_data = {
"query": f"Test Quarto export {time.time()}",
- "search_engine": "auto",
+ "search_engine": "searxng",
"model": "gemma3n:e2b",
"model_provider": "OLLAMA",
"mode": "quick",
@@ -321,7 +321,7 @@ def test_export_ris(auth_session, base_url):
# First, start a simple research
research_data = {
"query": f"Test RIS export {time.time()}",
- "search_engine": "auto",
+ "search_engine": "searxng",
"model": "gemma3n:e2b",
"model_provider": "OLLAMA",
"mode": "quick",
diff --git a/tests/api_tests_with_login/pytest_tests/test_model_parameter.py b/tests/api_tests_with_login/pytest_tests/test_model_parameter.py
index 85b1fd4470..3810200e7b 100644
--- a/tests/api_tests_with_login/pytest_tests/test_model_parameter.py
+++ b/tests/api_tests_with_login/pytest_tests/test_model_parameter.py
@@ -12,7 +12,7 @@ def test_model_parameter_in_logs(auth_session, base_url):
# Start research with specific model
research_data = {
"query": "Test model parameter passing",
- "search_engine": "auto",
+ "search_engine": "searxng",
"model": "gemma3n:e2b",
"model_provider": "OLLAMA",
"mode": "quick",
@@ -59,7 +59,7 @@ def test_empty_model_parameter_allowed(auth_session, base_url):
research_data = {
"query": "Test with empty model",
- "search_engine": "auto",
+ "search_engine": "searxng",
"model": "", # Empty model should use default
"model_provider": "OLLAMA",
"mode": "quick",
diff --git a/tests/api_tests_with_login/pytest_tests/test_research_completion.py b/tests/api_tests_with_login/pytest_tests/test_research_completion.py
index df142ea5d9..1f88e19319 100644
--- a/tests/api_tests_with_login/pytest_tests/test_research_completion.py
+++ b/tests/api_tests_with_login/pytest_tests/test_research_completion.py
@@ -14,7 +14,7 @@ def test_research_completion_time(auth_session, base_url):
# Start research
research_data = {
"query": "Quick test for completion time",
- "search_engine": "auto",
+ "search_engine": "searxng",
"model": "gemma3n:e2b",
"model_provider": "OLLAMA",
"mode": "quick",
diff --git a/tests/api_tests_with_login/pytest_tests/test_research_results.py b/tests/api_tests_with_login/pytest_tests/test_research_results.py
index f7977747ac..8796fe5eba 100644
--- a/tests/api_tests_with_login/pytest_tests/test_research_results.py
+++ b/tests/api_tests_with_login/pytest_tests/test_research_results.py
@@ -13,7 +13,7 @@ def test_research_produces_valid_report(auth_session, base_url):
# Start research
research_data = {
"query": "Test query for report validation",
- "search_engine": "auto",
+ "search_engine": "searxng",
"model": "gemma3n:e2b",
"model_provider": "OLLAMA",
"mode": "quick",
diff --git a/tests/api_tests_with_login/pytest_tests/test_start_research.py b/tests/api_tests_with_login/pytest_tests/test_start_research.py
index ef3c39e336..82f9ee047d 100644
--- a/tests/api_tests_with_login/pytest_tests/test_start_research.py
+++ b/tests/api_tests_with_login/pytest_tests/test_start_research.py
@@ -21,7 +21,7 @@ def test_start_research_with_model(auth_session, base_url):
# Start research
research_data = {
"query": f"Test research with model validation {time.time()}",
- "search_engine": "auto",
+ "search_engine": "searxng",
"model": "gemma3n:e2b",
"model_provider": "OLLAMA",
"mode": "quick",
diff --git a/tests/api_tests_with_login/test_export_minimal.js b/tests/api_tests_with_login/test_export_minimal.js
index 4e32962f8c..b5d59bfcb0 100644
--- a/tests/api_tests_with_login/test_export_minimal.js
+++ b/tests/api_tests_with_login/test_export_minimal.js
@@ -22,7 +22,7 @@ describe('Export Functionality Tests', function() {
it('should start research and wait for completion', async () => {
const researchData = {
query: `Test export functionality ${Date.now()}`,
- search_engine: 'auto',
+ search_engine: 'searxng',
model: 'gemma3n:e2b',
model_provider: 'OLLAMA',
mode: 'quick',
diff --git a/tests/api_tests_with_login/test_research_api_enhanced.js b/tests/api_tests_with_login/test_research_api_enhanced.js
index 0320bd7427..702c2b678b 100644
--- a/tests/api_tests_with_login/test_research_api_enhanced.js
+++ b/tests/api_tests_with_login/test_research_api_enhanced.js
@@ -31,7 +31,7 @@ describe('Enhanced Research API - Validates Model Usage', function() {
// This is a simpler test - just verify the API accepts the model parameter
const requestData = {
query: 'Simple test for model parameter',
- search_engine: 'auto',
+ search_engine: 'searxng',
model: 'gemma3n:e2b',
model_provider: 'OLLAMA',
mode: 'quick',
@@ -75,7 +75,7 @@ describe('Enhanced Research API - Validates Model Usage', function() {
},
data: {
query: 'Test query to verify model usage',
- search_engine: 'auto',
+ search_engine: 'searxng',
model: 'gemma3n:e2b',
model_provider: 'OLLAMA',
mode: 'quick',
diff --git a/tests/database/test_alembic_migrations.py b/tests/database/test_alembic_migrations.py
index e29974485b..67412fdaf5 100644
--- a/tests/database/test_alembic_migrations.py
+++ b/tests/database/test_alembic_migrations.py
@@ -5538,8 +5538,7 @@ class TestMigrationAppliesSchemaChanges:
command.upgrade(cfg, "head")
col_map = {
- c["name"]: c
- for c in inspect(engine).get_columns("collections")
+ c["name"]: c for c in inspect(engine).get_columns("collections")
}
assert "is_public" in col_map
assert col_map["is_public"]["nullable"] is True
@@ -5548,11 +5547,12 @@ class TestMigrationAppliesSchemaChanges:
with engine.connect() as conn:
val = conn.execute(
text(
- "SELECT is_public FROM collections "
- "WHERE id='legacy-c1'"
+ "SELECT is_public FROM collections WHERE id='legacy-c1'"
)
).scalar()
- assert not val, f"existing row not private after upgrade: {val!r}"
+ assert not val, (
+ f"existing row not private after upgrade: {val!r}"
+ )
finally:
engine.dispose()
@@ -6003,6 +6003,9 @@ class TestMigrationSafetyGuards:
# data migrations that delete stale keys with no consumers).
INTENTIONAL_NOOP_DOWNGRADES = {
"0004_migrate_legacy_app_settings.py",
+ # 0013: restoring 'auto'/'parallel' references would recreate
+ # broken state — those engines no longer exist in the codebase.
+ "0013_remove_meta_search_engines.py",
}
# Migrations whose downgrade is intentionally NotImplementedError
diff --git a/tests/database/test_migration_0013_remove_meta_engines.py b/tests/database/test_migration_0013_remove_meta_engines.py
new file mode 100644
index 0000000000..24bd99e53d
--- /dev/null
+++ b/tests/database/test_migration_0013_remove_meta_engines.py
@@ -0,0 +1,303 @@
+"""Tests for migration 0013: remove the auto/parallel meta search engines.
+
+Pins the upgrade semantics:
+- ``search.tool`` rows naming a removed engine (auto / meta / parallel /
+ parallel_scientific) are rewritten to ``searxng``; concrete engine
+ choices are preserved.
+- Orphaned ``search.engine.auto.*`` / ``search.engine.web.parallel.*``
+ setting rows are deleted; sibling keys (e.g. ``use_in_auto_search``
+ flags under other engines) survive.
+- ``news_subscriptions.search_engine`` is NULLed for removed engines
+ (falsy means "use the user's default search tool" in the scheduler).
+- ``queued_researches.settings_snapshot`` JSON has its
+ ``submission.search_engine`` (and embedded ``search.tool``) rewritten,
+ for both the new nested and the legacy flat snapshot structure.
+- ``benchmark_runs`` / ``benchmark_configs`` ``search_config.search_tool``
+ is rewritten.
+- Idempotency: re-running the upgrade is a no-op.
+
+The settings ``value`` column stores JSON text (``"auto"`` with quotes);
+seeding mirrors that encoding so the WHERE clauses match production.
+"""
+
+import json
+
+import pytest
+from alembic import command
+from sqlalchemy import create_engine, text
+
+from local_deep_research.database.alembic_runner import (
+ get_alembic_config,
+)
+
+REMOVED = ["auto", "meta", "parallel", "parallel_scientific"]
+
+
+def _run_upgrade_to(engine, revision):
+ config = get_alembic_config(engine)
+ with engine.begin() as conn:
+ config.attributes["connection"] = conn
+ command.upgrade(config, revision)
+
+
+def _seed_setting(engine, key, value):
+ with engine.begin() as conn:
+ conn.execute(
+ text(
+ "INSERT INTO settings "
+ "(key, value, type, name, ui_element, visible, editable) "
+ "VALUES (:key, :value, 'search', :name, 'select', 1, 1)"
+ ),
+ {"key": key, "value": json.dumps(value), "name": key},
+ )
+
+
+def _read_setting(engine, key):
+ with engine.begin() as conn:
+ row = conn.execute(
+ text("SELECT value FROM settings WHERE key = :key"),
+ {"key": key},
+ ).fetchone()
+ if row is None:
+ return None
+ raw = row[0]
+ return json.loads(raw) if isinstance(raw, str) else raw
+
+
+def migrated_to_0012_engine(tmp_path):
+ """Database fully migrated through 0012 (the revision before 0013)."""
+ db_path = tmp_path / "test_0013.db"
+ engine = create_engine(f"sqlite:///{db_path}")
+ _run_upgrade_to(engine, "0012")
+ yield engine
+ engine.dispose()
+
+
+class TestMigration0013Settings:
+ @pytest.mark.parametrize("removed_value", REMOVED)
+ def test_search_tool_rewritten_to_searxng(
+ self, migrated_to_0012_engine, removed_value
+ ):
+ engine = migrated_to_0012_engine
+ _seed_setting(engine, "search.tool", removed_value)
+
+ _run_upgrade_to(engine, "0013")
+
+ assert _read_setting(engine, "search.tool") == "searxng"
+
+ @pytest.mark.parametrize("concrete", ["searxng", "wikipedia", "arxiv"])
+ def test_concrete_engine_choice_preserved(
+ self, migrated_to_0012_engine, concrete
+ ):
+ engine = migrated_to_0012_engine
+ _seed_setting(engine, "search.tool", concrete)
+
+ _run_upgrade_to(engine, "0013")
+
+ assert _read_setting(engine, "search.tool") == concrete
+
+ def test_orphan_engine_settings_deleted(self, migrated_to_0012_engine):
+ engine = migrated_to_0012_engine
+ _seed_setting(engine, "search.engine.auto.display_name", "Auto")
+ _seed_setting(engine, "search.engine.web.parallel.reliability", 0.5)
+ # Sibling keys under other engines must survive — including the
+ # use_in_auto_search flags whose names merely contain "auto".
+ _seed_setting(
+ engine, "search.engine.web.searxng.use_in_auto_search", True
+ )
+
+ _run_upgrade_to(engine, "0013")
+
+ assert _read_setting(engine, "search.engine.auto.display_name") is None
+ assert (
+ _read_setting(engine, "search.engine.web.parallel.reliability")
+ is None
+ )
+ assert (
+ _read_setting(
+ engine, "search.engine.web.searxng.use_in_auto_search"
+ )
+ is True
+ )
+
+ def test_upgrade_is_idempotent(self, migrated_to_0012_engine):
+ engine = migrated_to_0012_engine
+ _seed_setting(engine, "search.tool", "auto")
+
+ _run_upgrade_to(engine, "0013")
+ _run_upgrade_to(engine, "0013")
+
+ assert _read_setting(engine, "search.tool") == "searxng"
+
+ def test_missing_rows_are_a_clean_noop(self, migrated_to_0012_engine):
+ engine = migrated_to_0012_engine
+
+ _run_upgrade_to(engine, "0013")
+
+ assert _read_setting(engine, "search.tool") is None
+
+
+class TestMigration0013NewsSubscriptions:
+ def _seed_subscription(self, engine, sub_id, search_engine):
+ with engine.begin() as conn:
+ conn.execute(
+ text(
+ "INSERT INTO news_subscriptions "
+ "(id, subscription_type, query_or_topic, search_engine) "
+ "VALUES (:id, 'search', 'test query', :se)"
+ ),
+ {"id": sub_id, "se": search_engine},
+ )
+
+ def _read_subscription_engine(self, engine, sub_id):
+ with engine.begin() as conn:
+ return conn.execute(
+ text(
+ "SELECT search_engine FROM news_subscriptions "
+ "WHERE id = :id"
+ ),
+ {"id": sub_id},
+ ).fetchone()[0]
+
+ def test_removed_engine_nulled_concrete_preserved(
+ self, migrated_to_0012_engine
+ ):
+ engine = migrated_to_0012_engine
+ self._seed_subscription(engine, "sub-auto", "auto")
+ self._seed_subscription(engine, "sub-parallel", "parallel")
+ self._seed_subscription(engine, "sub-wiki", "wikipedia")
+ self._seed_subscription(engine, "sub-null", None)
+
+ _run_upgrade_to(engine, "0013")
+
+ assert self._read_subscription_engine(engine, "sub-auto") is None
+ assert self._read_subscription_engine(engine, "sub-parallel") is None
+ assert self._read_subscription_engine(engine, "sub-wiki") == "wikipedia"
+ assert self._read_subscription_engine(engine, "sub-null") is None
+
+
+class TestMigration0013QueuedResearches:
+ def _seed_queued(self, engine, research_id, snapshot):
+ with engine.begin() as conn:
+ conn.execute(
+ text(
+ "INSERT INTO queued_researches "
+ "(username, research_id, query, mode, settings_snapshot, "
+ "position) "
+ "VALUES ('tester', :rid, 'q', 'quick', :snap, 1)"
+ ),
+ {"rid": research_id, "snap": json.dumps(snapshot)},
+ )
+
+ def _read_snapshot(self, engine, research_id):
+ with engine.begin() as conn:
+ raw = conn.execute(
+ text(
+ "SELECT settings_snapshot FROM queued_researches "
+ "WHERE research_id = :rid"
+ ),
+ {"rid": research_id},
+ ).fetchone()[0]
+ return json.loads(raw) if isinstance(raw, str) else raw
+
+ def test_nested_submission_engine_rewritten(self, migrated_to_0012_engine):
+ engine = migrated_to_0012_engine
+ self._seed_queued(
+ engine,
+ "rid-nested",
+ {
+ "submission": {"search_engine": "auto", "model": "m"},
+ "settings_snapshot": {
+ "search.tool": {"value": "auto", "type": "SEARCH"}
+ },
+ },
+ )
+
+ _run_upgrade_to(engine, "0013")
+
+ snap = self._read_snapshot(engine, "rid-nested")
+ assert snap["submission"]["search_engine"] == "searxng"
+ assert snap["settings_snapshot"]["search.tool"]["value"] == "searxng"
+
+ def test_legacy_flat_snapshot_rewritten(self, migrated_to_0012_engine):
+ engine = migrated_to_0012_engine
+ self._seed_queued(
+ engine, "rid-flat", {"search_engine": "parallel", "model": "m"}
+ )
+
+ _run_upgrade_to(engine, "0013")
+
+ snap = self._read_snapshot(engine, "rid-flat")
+ assert snap["search_engine"] == "searxng"
+
+ def test_concrete_engine_snapshot_untouched(self, migrated_to_0012_engine):
+ engine = migrated_to_0012_engine
+ original = {
+ "submission": {"search_engine": "wikipedia"},
+ "settings_snapshot": {"search.tool": "wikipedia"},
+ }
+ self._seed_queued(engine, "rid-wiki", original)
+
+ _run_upgrade_to(engine, "0013")
+
+ assert self._read_snapshot(engine, "rid-wiki") == original
+
+
+class TestMigration0013Benchmarks:
+ def _seed_config(self, engine, name, search_tool):
+ search_config = json.dumps(
+ {"search_tool": search_tool, "iterations": 2}
+ )
+ with engine.begin() as conn:
+ conn.execute(
+ text(
+ "INSERT INTO benchmark_configs "
+ "(name, config_hash, search_config, evaluation_config, "
+ "datasets_config, created_at, updated_at, is_default, "
+ "is_public, usage_count) "
+ "VALUES (:name, 'abcd1234', :sc, '{}', '{}', "
+ "CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, 0, 0, 0)"
+ ),
+ {"name": name, "sc": search_config},
+ )
+
+ def _read_config_tool(self, engine, name):
+ with engine.begin() as conn:
+ raw = conn.execute(
+ text(
+ "SELECT search_config FROM benchmark_configs "
+ "WHERE name = :name"
+ ),
+ {"name": name},
+ ).fetchone()[0]
+ config = json.loads(raw) if isinstance(raw, str) else raw
+ return config["search_tool"]
+
+ def test_benchmark_config_search_tool_rewritten(
+ self, migrated_to_0012_engine
+ ):
+ engine = migrated_to_0012_engine
+ self._seed_config(engine, "cfg-auto", "auto")
+ self._seed_config(engine, "cfg-searxng", "searxng")
+
+ _run_upgrade_to(engine, "0013")
+
+ assert self._read_config_tool(engine, "cfg-auto") == "searxng"
+ assert self._read_config_tool(engine, "cfg-searxng") == "searxng"
+
+
+class TestMigration0013HeadAlignment:
+ def test_0013_chains_correctly_to_0012(self):
+ from alembic.config import Config
+ from alembic.script import ScriptDirectory
+
+ from local_deep_research.database.alembic_runner import (
+ get_migrations_dir,
+ )
+
+ config = Config()
+ config.set_main_option("script_location", str(get_migrations_dir()))
+ script = ScriptDirectory.from_config(config)
+ rev_0013 = script.get_revision("0013")
+ assert rev_0013.down_revision == "0012"
diff --git a/tests/langchain_integration/test_combined_llm_retriever.py b/tests/langchain_integration/test_combined_llm_retriever.py
index 4b242a9e20..15a11007b2 100644
--- a/tests/langchain_integration/test_combined_llm_retriever.py
+++ b/tests/langchain_integration/test_combined_llm_retriever.py
@@ -194,7 +194,7 @@ class TestCombinedLLMRetriever:
"llm.supports_max_tokens": {"value": True, "type": "bool"},
"llm.max_tokens": {"value": 4096, "type": "int"},
"rate_limiting.llm_enabled": {"value": False, "type": "bool"},
- "search.tool": {"value": "auto", "type": "str"},
+ "search.tool": {"value": "searxng", "type": "str"},
"search.max_results": {"value": 10, "type": "int"},
"search.cross_engine_max_results": {"value": 100, "type": "int"},
"search.cross_engine_use_reddit": {"value": False, "type": "bool"},
diff --git a/tests/langchain_integration/test_custom_langchain_retriever.py b/tests/langchain_integration/test_custom_langchain_retriever.py
index 522c209e7c..73e8840a39 100644
--- a/tests/langchain_integration/test_custom_langchain_retriever.py
+++ b/tests/langchain_integration/test_custom_langchain_retriever.py
@@ -120,7 +120,7 @@ class TestCustomLangChainRetriever:
"llm.supports_max_tokens": {"value": True, "type": "bool"},
"llm.max_tokens": {"value": 4096, "type": "int"},
"rate_limiting.llm_enabled": {"value": False, "type": "bool"},
- "search.tool": {"value": "auto", "type": "str"},
+ "search.tool": {"value": "searxng", "type": "str"},
"search.max_results": {"value": 10, "type": "int"},
"search.cross_engine_max_results": {"value": 100, "type": "int"},
"search.cross_engine_use_reddit": {"value": False, "type": "bool"},
@@ -212,8 +212,7 @@ class TestCustomLangChainRetriever:
"local_deep_research.api.research_functions.get_llm",
return_value=mock_llm,
):
- # Use a specific registered retriever as search_tool; "auto" does
- # not auto-discover registered retrievers.
+ # Use a specific registered retriever as search_tool.
result = detailed_research(
query="What are the latest developments in deep learning?",
research_id="test-67890",
diff --git a/tests/mcp/conftest.py b/tests/mcp/conftest.py
index 3a5887b91b..cb519606e4 100644
--- a/tests/mcp/conftest.py
+++ b/tests/mcp/conftest.py
@@ -122,7 +122,7 @@ def mock_settings_snapshot():
"llm.provider": {"value": "openai"},
"llm.model": {"value": "gpt-4"},
"llm.temperature": {"value": 0.7},
- "search.tool": {"value": "auto"},
+ "search.tool": {"value": "searxng"},
"search.search_strategy": {"value": "source-based"},
"search.iterations": {"value": 2},
"search.questions_per_iteration": {"value": 3},
diff --git a/tests/mcp/test_egress_audit_net.py b/tests/mcp/test_egress_audit_net.py
index 39af26b40c..04b29ad60b 100644
--- a/tests/mcp/test_egress_audit_net.py
+++ b/tests/mcp/test_egress_audit_net.py
@@ -55,7 +55,7 @@ def test_already_armed_context_is_kept():
"""When a caller already armed a context (web research worker), the
MCP net must not replace it."""
outer = context_from_snapshot(
- {"policy.egress_scope": {"value": "both"}}, "auto"
+ {"policy.egress_scope": {"value": "both"}}, "searxng"
)
with active_egress_context(outer):
with _egress_audit_net(
diff --git a/tests/mcp/test_server.py b/tests/mcp/test_server.py
index 9c0a52b701..c38285d904 100644
--- a/tests/mcp/test_server.py
+++ b/tests/mcp/test_server.py
@@ -356,7 +356,7 @@ class TestSearch:
from local_deep_research.mcp.server import search
mock_engines_config = {
- "auto": {"description": "Auto", "requires_api_key": False},
+ "searxng": {"description": "SearXNG", "requires_api_key": False},
}
with (
@@ -373,7 +373,7 @@ class TestSearch:
return_value=None,
),
):
- result = search(query="test", engine="auto")
+ result = search(query="test", engine="searxng")
assert result["status"] == "error"
assert "configuration_error" in result["error_type"]
diff --git a/tests/news/subscription_manager/test_scheduler.py b/tests/news/subscription_manager/test_scheduler.py
index 7e5520fe4c..9c78cca20f 100644
--- a/tests/news/subscription_manager/test_scheduler.py
+++ b/tests/news/subscription_manager/test_scheduler.py
@@ -494,7 +494,7 @@ class TestCheckSubscription:
mock_subscription.model_provider = "test"
mock_subscription.model = "test"
mock_subscription.search_strategy = "news_aggregation"
- mock_subscription.search_engine = "auto"
+ mock_subscription.search_engine = "searxng"
with patch(
"local_deep_research.database.session_context.get_user_db_session"
@@ -552,7 +552,7 @@ class TestTriggerSubscriptionResearchSync:
"model_provider": "openai",
"model": "gpt-4",
"search_strategy": "news_aggregation",
- "search_engine": "auto",
+ "search_engine": "searxng",
}
with patch(
diff --git a/tests/news/subscription_manager/test_scheduler_coverage.py b/tests/news/subscription_manager/test_scheduler_coverage.py
index f23d874983..d9e6013622 100644
--- a/tests/news/subscription_manager/test_scheduler_coverage.py
+++ b/tests/news/subscription_manager/test_scheduler_coverage.py
@@ -950,7 +950,7 @@ class TestCheckSubscriptionReschedule:
sub.model_provider = "test"
sub.model = "test"
sub.search_strategy = "news"
- sub.search_engine = "auto"
+ sub.search_engine = "searxng"
mock_db = _ctx(MagicMock())
mock_db.query.return_value.get.return_value = sub
@@ -1020,7 +1020,7 @@ class TestCheckSubscriptionReschedule:
class TestTriggerResearchSync:
- def _base_sub(self, search_engine="auto"):
+ def _base_sub(self, search_engine="searxng"):
return {
"id": 1,
"name": "T",
@@ -1362,7 +1362,7 @@ class TestSnapshotSettingsContext:
"model_provider": "openai",
"model": "gpt-4",
"search_strategy": "news",
- "search_engine": "auto",
+ "search_engine": "searxng",
}
mock_db = _ctx(MagicMock())
diff --git a/tests/news/test_news_api_extended.py b/tests/news/test_news_api_extended.py
index a4fdffb2a1..9a32ecf646 100644
--- a/tests/news/test_news_api_extended.py
+++ b/tests/news/test_news_api_extended.py
@@ -704,23 +704,25 @@ class TestSubscriptionOperations:
with patch(
"local_deep_research.news.api._notify_scheduler_about_subscription_change"
):
- # Use "auto" (a known meta-picker) instead of the
+ # Use "searxng" (a registered engine) instead of the
# legacy "google" placeholder — the news subscription
# policy precheck now properly rejects engine_unknown
# names (was previously silently allowed via the
- # engine_unknown bypass — see plan C1).
+ # engine_unknown bypass — see plan C1). The provider must
+ # be local ("ollama"): with the default snapshot the
+ # precheck's egress context denies cloud-only providers.
result = create_subscription(
user_id="testuser",
query="AI News",
subscription_type="search",
refresh_minutes=120,
- model_provider="openai",
- model="gpt-4",
+ model_provider="ollama",
+ model="llama3",
search_strategy="deep_analysis",
name="My AI Subscription",
folder_id="folder123",
is_active=True,
- search_engine="auto",
+ search_engine="searxng",
search_iterations=5,
questions_per_iteration=3,
)
diff --git a/tests/news/test_web_blueprint.py b/tests/news/test_web_blueprint.py
index afecbecdc8..daf0e5366a 100644
--- a/tests/news/test_web_blueprint.py
+++ b/tests/news/test_web_blueprint.py
@@ -260,7 +260,7 @@ class TestNewSubscriptionPageRoute:
assert kwargs["default_settings"]["questions_per_iteration"] == 5
def test_new_subscription_page_has_default_search_engine(self, client):
- """Test default search_engine is 'auto'."""
+ """Test default search_engine is 'searxng'."""
with patch(
"local_deep_research.news.web.render_template"
) as mock_render:
@@ -269,7 +269,7 @@ class TestNewSubscriptionPageRoute:
client.get("/news/subscriptions/new")
args, kwargs = mock_render.call_args
- assert kwargs["default_settings"]["search_engine"] == "auto"
+ assert kwargs["default_settings"]["search_engine"] == "searxng"
def test_new_subscription_page_has_default_model_provider(self, client):
"""Test default model_provider is 'OLLAMA'."""
@@ -696,7 +696,7 @@ class TestLoadUserSettings:
"""Test that search_engine setting comes from 'search.tool'."""
from local_deep_research.news.web import load_user_settings
- default_settings = {"search_engine": "auto"}
+ default_settings = {"search_engine": "searxng"}
with patch(
"local_deep_research.utilities.db_utils.get_settings_manager"
@@ -808,7 +808,7 @@ class TestLoadUserSettings:
default_settings = {
"iterations": 3,
"questions_per_iteration": 5,
- "search_engine": "auto",
+ "search_engine": "searxng",
}
with patch(
@@ -824,7 +824,7 @@ class TestLoadUserSettings:
# Defaults should be preserved
assert default_settings["iterations"] == 3
assert default_settings["questions_per_iteration"] == 5
- assert default_settings["search_engine"] == "auto"
+ assert default_settings["search_engine"] == "searxng"
def test_load_user_settings_calls_get_settings_manager(self):
"""Test that get_settings_manager is called with correct args."""
diff --git a/tests/news/test_web_blueprint_extended.py b/tests/news/test_web_blueprint_extended.py
index efdd361cd3..1227775833 100644
--- a/tests/news/test_web_blueprint_extended.py
+++ b/tests/news/test_web_blueprint_extended.py
@@ -56,7 +56,7 @@ class TestDefaultSettings:
default_settings = {
"iterations": 3,
"questions_per_iteration": 5,
- "search_engine": "auto",
+ "search_engine": "searxng",
"model_provider": "OLLAMA",
"model": "",
"search_strategy": "source-based",
@@ -74,12 +74,12 @@ class TestDefaultSettings:
assert default_settings["questions_per_iteration"] == 5
def test_default_search_engine(self):
- """Default search_engine is auto."""
+ """Default search_engine is searxng."""
default_settings = {
- "search_engine": "auto",
+ "search_engine": "searxng",
}
- assert default_settings["search_engine"] == "auto"
+ assert default_settings["search_engine"] == "searxng"
def test_default_model_provider(self):
"""Default model_provider is OLLAMA."""
diff --git a/tests/news/test_web_routes_comprehensive.py b/tests/news/test_web_routes_comprehensive.py
index c86a433f1b..ffad9cce01 100644
--- a/tests/news/test_web_routes_comprehensive.py
+++ b/tests/news/test_web_routes_comprehensive.py
@@ -374,7 +374,7 @@ class TestDefaultSettings:
client.get("/news/subscriptions/new")
call_kwargs = mock_render.call_args[1]
settings = call_kwargs["default_settings"]
- assert settings["search_engine"] == "auto"
+ assert settings["search_engine"] == "searxng"
def test_new_subscription_default_model_provider(self):
"""Test default model_provider value."""
diff --git a/tests/notifications/test_manager.py b/tests/notifications/test_manager.py
index 85945c8642..bea055f134 100644
--- a/tests/notifications/test_manager.py
+++ b/tests/notifications/test_manager.py
@@ -843,7 +843,7 @@ class TestPerUserRateLimiting:
class TestEgressPolicyURLFilter:
"""_filter_urls_by_egress_policy gates notification dispatch by scope."""
- def _mgr(self, scope, tool="auto"):
+ def _mgr(self, scope, tool="searxng"):
snap = {
"policy.egress_scope": {"value": scope},
"search.tool": {"value": tool},
diff --git a/tests/performance/_shared/run_full_search.py b/tests/performance/_shared/run_full_search.py
index 7f60ee0d63..0a13b3fd5c 100644
--- a/tests/performance/_shared/run_full_search.py
+++ b/tests/performance/_shared/run_full_search.py
@@ -49,9 +49,6 @@ VALID_ENGINES = [
"openalex",
"wikipedia",
"searxng",
- "parallel",
- "parallel_scientific",
- "auto",
]
diff --git a/tests/retriever_integration/test_api_integration.py b/tests/retriever_integration/test_api_integration.py
index a10eb57a61..c786ea9233 100644
--- a/tests/retriever_integration/test_api_integration.py
+++ b/tests/retriever_integration/test_api_integration.py
@@ -112,14 +112,14 @@ class TestAPIIntegration:
quick_summary(
query="multi retriever test",
retrievers=retrievers,
- search_tool="auto",
+ search_tool="kb1",
)
# Verify that the function works correctly without checking registry state
- # The search_tool="auto" should work with the registered retrievers
+ # The search_tool="kb1" should work with the registered retrievers
mock_init.assert_called_once()
call_kwargs = mock_init.call_args[1]
- assert call_kwargs.get("search_tool") == "auto"
+ assert call_kwargs.get("search_tool") == "kb1"
@patch("local_deep_research.api.research_functions._init_search_system")
def test_detailed_research_with_retrievers(self, mock_init):
diff --git a/tests/retriever_integration/test_e2e_basic.py b/tests/retriever_integration/test_e2e_basic.py
index 7e970a985e..3425e219bd 100644
--- a/tests/retriever_integration/test_e2e_basic.py
+++ b/tests/retriever_integration/test_e2e_basic.py
@@ -115,7 +115,7 @@ class TestE2EBasic:
result = detailed_research(
query="What are the implications of AI?",
retrievers={"tech": tech_retriever, "business": business_retriever},
- search_tool="auto",
+ search_tool="tech",
iterations=1,
)
diff --git a/tests/search_engines/test_meta_search_engine.py b/tests/search_engines/test_meta_search_engine.py
deleted file mode 100644
index 30b170acb1..0000000000
--- a/tests/search_engines/test_meta_search_engine.py
+++ /dev/null
@@ -1,672 +0,0 @@
-"""
-Comprehensive tests for web_search_engines/engines/meta_search_engine.py
-
-Tests cover:
-- MetaSearchEngine initialization
-- Available engines detection
-- Query analysis
-- Engine selection
-- Preview and full content retrieval
-- Engine caching
-- Error handling
-"""
-
-import pytest
-from unittest.mock import Mock, patch
-
-
-class TestMetaSearchEngineInit:
- """Tests for MetaSearchEngine initialization."""
-
- def test_init_with_llm(self):
- """Test initialization with LLM."""
- from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
- )
-
- mock_llm = Mock()
-
- with patch.object(
- MetaSearchEngine, "_get_available_engines", return_value=["searxng"]
- ):
- engine = MetaSearchEngine(llm=mock_llm)
-
- assert engine.llm == mock_llm
- assert engine.max_results == 10 # default
- assert engine.use_api_key_services is True
- assert engine.max_engines_to_try == 3
-
- def test_init_custom_parameters(self):
- """Test initialization with custom parameters."""
- from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
- )
-
- mock_llm = Mock()
-
- with patch.object(
- MetaSearchEngine, "_get_available_engines", return_value=["searxng"]
- ):
- engine = MetaSearchEngine(
- llm=mock_llm,
- max_results=20,
- use_api_key_services=False,
- max_engines_to_try=5,
- max_filtered_results=10,
- )
-
- assert engine.max_results == 20
- assert engine.use_api_key_services is False
- assert engine.max_engines_to_try == 5
- assert engine.max_filtered_results == 10
-
- def test_init_with_settings_snapshot(self):
- """Test initialization with settings snapshot."""
- from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
- )
-
- mock_llm = Mock()
- snapshot = {"search.engine.web.searxng.use_in_auto_search": True}
-
- with patch.object(
- MetaSearchEngine, "_get_available_engines", return_value=["searxng"]
- ):
- engine = MetaSearchEngine(
- llm=mock_llm,
- settings_snapshot=snapshot,
- )
-
- assert engine.settings_snapshot == snapshot
-
- def test_init_creates_fallback_engine(self):
- """Test that fallback Wikipedia engine is created."""
- from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
- )
-
- mock_llm = Mock()
-
- with patch.object(
- MetaSearchEngine, "_get_available_engines", return_value=["searxng"]
- ):
- engine = MetaSearchEngine(llm=mock_llm)
-
- assert engine.fallback_engine is not None
-
-
-class TestGetAvailableEngines:
- """Tests for _get_available_engines method."""
-
- def test_get_available_engines_from_snapshot(self):
- """Test getting available engines from settings snapshot."""
- from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
- )
-
- mock_llm = Mock()
- snapshot = {
- "search.engine.web.searxng.use_in_auto_search": True,
- "search.engine.web.wikipedia.use_in_auto_search": True,
- }
-
- with patch(
- "local_deep_research.config.search_config.get_setting_from_snapshot",
- return_value=True,
- ):
- with patch.object(
- MetaSearchEngine,
- "_get_search_config",
- return_value={"searxng": {}, "wikipedia": {}},
- ):
- engine = MetaSearchEngine(
- llm=mock_llm, settings_snapshot=snapshot
- )
-
- # Available engines should include those with use_in_auto_search=True
- assert len(engine.available_engines) >= 0
-
- def test_get_available_engines_excludes_meta(self):
- """Test that 'meta' and 'auto' are excluded."""
- from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
- )
-
- mock_llm = Mock()
- # Provide settings_snapshot to avoid recursion
- snapshot = {"search.engine.web.searxng.use_in_auto_search": True}
-
- with patch(
- "local_deep_research.config.search_config.get_setting_from_snapshot",
- return_value=True,
- ):
- with patch.object(
- MetaSearchEngine,
- "_get_search_config",
- return_value={"meta": {}, "auto": {}, "searxng": {}},
- ):
- engine = MetaSearchEngine(
- llm=mock_llm, settings_snapshot=snapshot
- )
-
- assert "meta" not in engine.available_engines
- assert "auto" not in engine.available_engines
-
- def test_get_available_engines_no_engines_raises(self):
- """Test that RuntimeError is raised when no engines available."""
- from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
- )
-
- mock_llm = Mock()
-
- with patch(
- "local_deep_research.config.search_config.get_setting_from_snapshot",
- return_value=False, # All engines disabled
- ):
- with patch.object(
- MetaSearchEngine,
- "_get_search_config",
- return_value={"searxng": {}},
- ):
- with pytest.raises(
- RuntimeError, match="No search engines enabled"
- ):
- MetaSearchEngine(llm=mock_llm)
-
-
-class TestAnalyzeQuery:
- """Tests for analyze_query method."""
-
- @pytest.fixture
- def engine(self):
- """Create a MetaSearchEngine instance for testing."""
- from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
- )
-
- mock_llm = Mock()
- # Provide settings_snapshot to avoid recursion in _get_search_config
- snapshot = {"search.engine.web.searxng.use_in_auto_search": True}
-
- with patch.object(
- MetaSearchEngine,
- "_get_available_engines",
- return_value=["searxng", "arxiv", "pubmed", "github"],
- ):
- return MetaSearchEngine(llm=mock_llm, settings_snapshot=snapshot)
-
- def test_analyze_scientific_query(self, engine):
- """Test that scientific queries prefer arxiv/pubmed."""
- result = engine.analyze_query(
- "latest scientific paper on machine learning"
- )
-
- # Should prioritize arxiv or pubmed
- assert any(e in result for e in ["arxiv", "pubmed"])
-
- def test_analyze_medical_query(self, engine):
- """Test that medical queries prefer pubmed."""
- result = engine.analyze_query(
- "clinical trial results for diabetes treatment"
- )
-
- assert "pubmed" in result
-
- def test_analyze_code_query(self, engine):
- """Test that code queries prefer github."""
- result = engine.analyze_query("github repository for machine learning")
-
- assert "github" in result
-
- def test_analyze_query_with_searxng_available(self, engine):
- """Test that SearXNG is used for general queries."""
- result = engine.analyze_query("latest news about technology")
-
- assert "searxng" in result
-
- def test_analyze_query_no_llm(self, engine):
- """Test query analysis without LLM."""
- engine.llm = None
-
- result = engine.analyze_query("test query")
-
- # Should fall back to reliability-based ordering
- assert isinstance(result, list)
-
- def test_analyze_query_llm_error(self, engine):
- """Test error handling in query analysis."""
- engine.llm.invoke.side_effect = Exception("LLM error")
-
- result = engine.analyze_query("test query")
-
- # Should fall back gracefully
- assert isinstance(result, list)
- assert len(result) > 0
-
-
-class TestGetPreviews:
- """Tests for _get_previews method."""
-
- @pytest.fixture
- def engine(self):
- """Create a MetaSearchEngine instance for testing."""
- from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
- )
-
- mock_llm = Mock()
-
- with patch.object(
- MetaSearchEngine, "_get_available_engines", return_value=["searxng"]
- ):
- return MetaSearchEngine(llm=mock_llm)
-
- def test_get_previews_success(self, engine):
- """Test successful preview retrieval."""
- mock_search_engine = Mock()
- mock_search_engine._get_previews.return_value = [
- {"id": "1", "title": "Result 1"},
- {"id": "2", "title": "Result 2"},
- ]
-
- with patch.object(engine, "analyze_query", return_value=["searxng"]):
- with patch.object(
- engine, "_get_engine_instance", return_value=mock_search_engine
- ):
- results = engine._get_previews("test query")
-
- assert len(results) == 2
- assert engine._selected_engine == mock_search_engine
-
- def test_get_previews_tries_multiple_engines(self, engine):
- """Test that multiple engines are tried on failure."""
- engine.available_engines = ["engine1", "engine2"]
-
- mock_engine1 = Mock()
- mock_engine1._get_previews.return_value = [] # No results
-
- mock_engine2 = Mock()
- mock_engine2._get_previews.return_value = [{"id": "1"}]
-
- def get_engine(name):
- if name == "engine1":
- return mock_engine1
- return mock_engine2
-
- with patch.object(
- engine, "analyze_query", return_value=["engine1", "engine2"]
- ):
- with patch.object(
- engine, "_get_engine_instance", side_effect=get_engine
- ):
- results = engine._get_previews("test")
-
- assert len(results) == 1
-
- def test_get_previews_fallback_to_wikipedia(self, engine):
- """Test fallback to Wikipedia when all engines fail."""
- mock_engine = Mock()
- mock_engine._get_previews.return_value = []
-
- engine.fallback_engine._get_previews = Mock(
- return_value=[{"id": "wiki1"}]
- )
-
- with patch.object(engine, "analyze_query", return_value=["searxng"]):
- with patch.object(
- engine, "_get_engine_instance", return_value=mock_engine
- ):
- results = engine._get_previews("test")
-
- assert len(results) == 1
- assert engine._selected_engine == engine.fallback_engine
-
- def test_get_previews_engine_error(self, engine):
- """Test handling of engine errors."""
- mock_engine = Mock()
- mock_engine._get_previews.side_effect = Exception("Engine error")
-
- engine.fallback_engine._get_previews = Mock(return_value=[{"id": "1"}])
-
- with patch.object(engine, "analyze_query", return_value=["searxng"]):
- with patch.object(
- engine, "_get_engine_instance", return_value=mock_engine
- ):
- results = engine._get_previews("test")
-
- # Should use fallback
- assert len(results) == 1
-
-
-class TestGetFullContent:
- """Tests for _get_full_content method."""
-
- @pytest.fixture
- def engine(self):
- """Create a MetaSearchEngine instance for testing."""
- from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
- )
-
- mock_llm = Mock()
-
- with patch.object(
- MetaSearchEngine, "_get_available_engines", return_value=["searxng"]
- ):
- return MetaSearchEngine(llm=mock_llm)
-
- def test_get_full_content_uses_selected_engine(self, engine):
- """Test that full content uses selected engine."""
- mock_selected = Mock()
- mock_selected._get_full_content.return_value = [
- {"id": "1", "full_content": "Content here"}
- ]
-
- engine._selected_engine = mock_selected
- engine._selected_engine_name = "test_engine"
-
- items = [{"id": "1"}]
-
- # Patch at the module level where get_setting_from_snapshot is called
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.get_setting_from_snapshot",
- return_value=False, # Not snippets only
- ):
- results = engine._get_full_content(items)
-
- mock_selected._get_full_content.assert_called_once_with(items)
- assert results[0]["full_content"] == "Content here"
-
- def test_get_full_content_snippets_only(self, engine):
- """Test snippets-only mode."""
- items = [{"id": "1", "title": "Test"}]
-
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.get_setting_from_snapshot",
- return_value=True, # Snippets only
- ):
- results = engine._get_full_content(items)
-
- assert results == items
-
- def test_get_full_content_no_selected_engine(self, engine):
- """Test handling when no engine was selected."""
- items = [{"id": "1"}]
-
- # Remove selected engine
- if hasattr(engine, "_selected_engine"):
- delattr(engine, "_selected_engine")
-
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.get_setting_from_snapshot",
- return_value=False,
- ):
- results = engine._get_full_content(items)
-
- assert results == items
-
-
-class TestGetEngineInstance:
- """Tests for _get_engine_instance method."""
-
- @pytest.fixture
- def engine(self):
- """Create a MetaSearchEngine instance for testing."""
- from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
- )
-
- mock_llm = Mock()
-
- with patch.object(
- MetaSearchEngine, "_get_available_engines", return_value=["searxng"]
- ):
- return MetaSearchEngine(llm=mock_llm)
-
- def test_get_engine_instance_creates_new(self, engine):
- """Test creating new engine instance."""
- mock_created_engine = Mock()
-
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.create_search_engine",
- return_value=mock_created_engine,
- ):
- result = engine._get_engine_instance("wikipedia")
-
- assert result == mock_created_engine
- assert "wikipedia" in engine.engine_cache
-
- def test_get_engine_instance_returns_cached(self, engine):
- """Test returning cached engine instance."""
- mock_cached = Mock()
- engine.engine_cache["wikipedia"] = mock_cached
-
- result = engine._get_engine_instance("wikipedia")
-
- assert result == mock_cached
-
- def test_get_engine_instance_error(self, engine):
- """Test error handling in engine creation."""
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.create_search_engine",
- side_effect=Exception("Creation error"),
- ):
- result = engine._get_engine_instance("failing_engine")
-
- assert result is None
-
-
-class TestInvoke:
- """Tests for invoke method."""
-
- @pytest.fixture
- def engine(self):
- """Create a MetaSearchEngine instance for testing."""
- from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
- )
-
- mock_llm = Mock()
-
- with patch.object(
- MetaSearchEngine, "_get_available_engines", return_value=["searxng"]
- ):
- return MetaSearchEngine(llm=mock_llm)
-
- def test_invoke_calls_run(self, engine):
- """Test that invoke calls run method."""
- with patch.object(
- engine, "run", return_value=[{"id": "1"}]
- ) as mock_run:
- result = engine.invoke("test query")
-
- mock_run.assert_called_once_with("test query")
- assert result == [{"id": "1"}]
-
-
-class TestGetSearchConfig:
- """Tests for _get_search_config method."""
-
- @pytest.fixture
- def engine(self):
- """Create a MetaSearchEngine instance for testing."""
- from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
- )
-
- mock_llm = Mock()
- snapshot = {
- "search.engine.web.searxng.description": "SearXNG search",
- "search.engine.web.searxng.reliability": 0.9,
- }
-
- with patch.object(
- MetaSearchEngine, "_get_available_engines", return_value=["searxng"]
- ):
- return MetaSearchEngine(llm=mock_llm, settings_snapshot=snapshot)
-
- def test_get_search_config_from_snapshot(self, engine):
- """Test getting search config from settings snapshot."""
- config = engine._get_search_config()
-
- assert isinstance(config, dict)
-
-
-class TestSpecializedDomainDetection:
- """Tests for specialized domain detection in analyze_query."""
-
- @pytest.fixture
- def engine(self):
- """Create a MetaSearchEngine instance for testing."""
- from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
- )
-
- mock_llm = Mock()
-
- with patch.object(
- MetaSearchEngine,
- "_get_available_engines",
- return_value=["searxng", "arxiv", "pubmed", "github", "wikipedia"],
- ):
- return MetaSearchEngine(llm=mock_llm)
-
- def test_detect_arxiv_keyword(self, engine):
- """Test arxiv keyword detection."""
- result = engine.analyze_query("find arxiv papers on transformers")
-
- assert result[0] == "arxiv"
-
- def test_detect_pubmed_keyword(self, engine):
- """Test pubmed keyword detection."""
- result = engine.analyze_query("pubmed articles on cancer research")
-
- assert result[0] == "pubmed"
-
- def test_detect_programming_query(self, engine):
- """Test programming query detection."""
- result = engine.analyze_query(
- "programming tutorial for web development"
- )
-
- assert "github" in result
-
-
-class TestEngineSelectionCallback:
- """Tests for engine selection callback."""
-
- @staticmethod
- def _engine_with_mock_search():
- """A MetaSearchEngine whose selected engine returns one preview."""
- from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
- )
-
- mock_llm = Mock()
-
- with patch.object(
- MetaSearchEngine, "_get_available_engines", return_value=["searxng"]
- ):
- engine = MetaSearchEngine(llm=mock_llm)
-
- mock_search_engine = Mock()
- mock_search_engine._get_previews.return_value = [{"id": "1"}]
- return engine, mock_search_engine
-
- def test_engine_selection_emits_scoped_to_owning_user_room(self):
- """The search_engine_selected event is emitted only to the owning
- user's per-user room — never broadcast — so one user's research
- activity is not visible to other connected accounts."""
- from local_deep_research.utilities.thread_context import (
- search_context,
- )
-
- engine, mock_search_engine = self._engine_with_mock_search()
-
- with patch.object(engine, "analyze_query", return_value=["searxng"]):
- with patch.object(
- engine, "_get_engine_instance", return_value=mock_search_engine
- ):
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.SocketIOService"
- ) as mock_socket:
- mock_socket_instance = Mock()
- mock_socket_instance.user_room.side_effect = lambda u: (
- f"user:{u}"
- )
- mock_socket.return_value = mock_socket_instance
-
- with search_context(
- {"research_id": "r1", "username": "alice"}
- ):
- engine._get_previews("test")
-
- mock_socket_instance.emit_socket_event.assert_called_once()
- _, kwargs = mock_socket_instance.emit_socket_event.call_args
- assert kwargs["room"] == "user:alice"
-
- def test_engine_selection_no_emit_without_search_context(self):
- """Without a search context (programmatic mode, missing propagation)
- there is no user tab to notify, so nothing is emitted — never a
- broadcast fallback."""
- engine, mock_search_engine = self._engine_with_mock_search()
-
- with patch.object(engine, "analyze_query", return_value=["searxng"]):
- with patch.object(
- engine, "_get_engine_instance", return_value=mock_search_engine
- ):
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.SocketIOService"
- ) as mock_socket:
- mock_socket_instance = Mock()
- mock_socket.return_value = mock_socket_instance
-
- result = engine._get_previews("test")
-
- mock_socket_instance.emit_socket_event.assert_not_called()
- # The search itself still succeeds
- assert len(result) == 1
-
- def test_engine_selection_no_emit_without_username_in_context(self):
- """A search context without a username cannot be scoped to a user,
- so nothing is emitted rather than broadcasting."""
- from local_deep_research.utilities.thread_context import (
- search_context,
- )
-
- engine, mock_search_engine = self._engine_with_mock_search()
-
- with patch.object(engine, "analyze_query", return_value=["searxng"]):
- with patch.object(
- engine, "_get_engine_instance", return_value=mock_search_engine
- ):
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.SocketIOService"
- ) as mock_socket:
- mock_socket_instance = Mock()
- mock_socket.return_value = mock_socket_instance
-
- with search_context({"research_id": "r1"}):
- engine._get_previews("test")
-
- mock_socket_instance.emit_socket_event.assert_not_called()
-
-
-class TestProgrammaticMode:
- """Tests for programmatic mode."""
-
- def test_programmatic_mode_initialization(self):
- """Test initialization in programmatic mode."""
- from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
- )
-
- mock_llm = Mock()
-
- with patch.object(
- MetaSearchEngine, "_get_available_engines", return_value=["searxng"]
- ):
- engine = MetaSearchEngine(llm=mock_llm, programmatic_mode=True)
-
- assert engine.programmatic_mode is True
diff --git a/tests/search_engines/test_meta_search_logic.py b/tests/search_engines/test_meta_search_logic.py
deleted file mode 100644
index 164bd61a61..0000000000
--- a/tests/search_engines/test_meta_search_logic.py
+++ /dev/null
@@ -1,398 +0,0 @@
-"""Tests for MetaSearchEngine — engine filtering, API key validation, query analysis, content retrieval."""
-
-from unittest.mock import MagicMock, patch
-
-import pytest
-
-from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
-)
-
-
-# ---------------------------------------------------------------------------
-# Helpers
-# ---------------------------------------------------------------------------
-
-
-def _make_settings_snapshot(engines, auto_settings=None):
- """Build a settings_snapshot dict that MetaSearchEngine expects.
-
- Args:
- engines: dict mapping engine_name -> {config keys like requires_api_key, api_key, ...}
- auto_settings: dict of per-engine use_in_auto_search overrides (default all True)
- """
- snapshot = {}
- for name, config in engines.items():
- for key, value in config.items():
- snapshot[f"search.engine.web.{name}.{key}"] = value
- # Enable for auto search by default unless overridden
- if auto_settings and name in auto_settings:
- snapshot[f"search.engine.web.{name}.use_in_auto_search"] = (
- auto_settings[name]
- )
- else:
- snapshot[f"search.engine.web.{name}.use_in_auto_search"] = True
- return snapshot
-
-
-def _make_meta_engine(settings_snapshot, use_api_key_services=True, llm=None):
- """Create MetaSearchEngine with mocked dependencies."""
- if llm is None:
- llm = MagicMock()
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.WikipediaSearchEngine"
- ):
- return MetaSearchEngine(
- llm=llm,
- max_results=5,
- use_api_key_services=use_api_key_services,
- settings_snapshot=settings_snapshot,
- )
-
-
-# ===========================================================================
-# 1. _get_available_engines — basic filtering
-# ===========================================================================
-
-
-class TestGetAvailableEngines:
- """Verify engine filtering logic in _get_available_engines."""
-
- def test_meta_and_auto_excluded(self):
- """Engines named 'meta' and 'auto' are always excluded."""
- snapshot = _make_settings_snapshot(
- {
- "searxng": {},
- "meta": {},
- "auto": {},
- }
- )
- engine = _make_meta_engine(snapshot)
- assert "meta" not in engine.available_engines
- assert "auto" not in engine.available_engines
- assert "searxng" in engine.available_engines
-
- def test_engine_disabled_for_auto_search(self):
- """Engines with use_in_auto_search=False are excluded."""
- snapshot = _make_settings_snapshot(
- {"searxng": {}, "brave": {}},
- auto_settings={"brave": False},
- )
- engine = _make_meta_engine(snapshot)
- assert "brave" not in engine.available_engines
- assert "searxng" in engine.available_engines
-
- def test_no_engines_available_raises(self):
- """RuntimeError when no engines pass the filter."""
- snapshot = _make_settings_snapshot(
- {"brave": {}},
- auto_settings={"brave": False},
- )
- with pytest.raises(RuntimeError, match="No search engines enabled"):
- _make_meta_engine(snapshot)
-
-
-# ===========================================================================
-# 2. API key validation combinations
-# ===========================================================================
-
-
-class TestAPIKeyValidation:
- """Verify API key filtering logic."""
-
- def test_engine_requires_key_and_key_present(self):
- """Engine with required key and key present is included."""
- snapshot = _make_settings_snapshot(
- {
- "brave": {"requires_api_key": True, "api_key": "sk-xxx"},
- }
- )
- engine = _make_meta_engine(snapshot)
- assert "brave" in engine.available_engines
-
- def test_engine_requires_key_but_key_missing(self):
- """Engine with required key but no key is excluded."""
- snapshot = _make_settings_snapshot(
- {
- "brave": {"requires_api_key": True},
- "searxng": {},
- }
- )
- engine = _make_meta_engine(snapshot)
- assert "brave" not in engine.available_engines
-
- def test_engine_requires_key_but_api_services_disabled(self):
- """Engine requiring key excluded when use_api_key_services=False."""
- snapshot = _make_settings_snapshot(
- {
- "brave": {"requires_api_key": True, "api_key": "sk-xxx"},
- "searxng": {},
- }
- )
- engine = _make_meta_engine(snapshot, use_api_key_services=False)
- assert "brave" not in engine.available_engines
- assert "searxng" in engine.available_engines
-
-
-# ===========================================================================
-# 3. analyze_query — specialized domain detection
-# ===========================================================================
-
-
-class TestAnalyzeQuery:
- """Verify query analysis and engine selection logic."""
-
- def test_scientific_paper_query(self):
- """Query containing 'scientific paper' selects arxiv/pubmed if available."""
- snapshot = _make_settings_snapshot({"arxiv": {}, "searxng": {}})
- engine = _make_meta_engine(snapshot)
- result = engine.analyze_query(
- "latest scientific paper on quantum computing"
- )
- assert result[0] == "arxiv"
-
- def test_code_query_selects_github(self):
- """Query about code selects github if available."""
- snapshot = _make_settings_snapshot({"github": {}, "searxng": {}})
- engine = _make_meta_engine(snapshot)
- result = engine.analyze_query("python code for sorting algorithms")
- assert "github" in result
-
- def test_arxiv_keyword_prioritizes_arxiv(self):
- """Query containing 'arxiv' puts arxiv first."""
- snapshot = _make_settings_snapshot({"arxiv": {}, "searxng": {}})
- engine = _make_meta_engine(snapshot)
- result = engine.analyze_query("find arxiv papers on transformers")
- assert result[0] == "arxiv"
-
- def test_pubmed_keyword_prioritizes_pubmed(self):
- """Query containing 'pubmed' puts pubmed first."""
- snapshot = _make_settings_snapshot({"pubmed": {}, "searxng": {}})
- engine = _make_meta_engine(snapshot)
- result = engine.analyze_query("search pubmed for covid studies")
- assert result[0] == "pubmed"
-
- def test_general_query_prefers_searxng(self):
- """General queries prefer searxng when available."""
- snapshot = _make_settings_snapshot({"searxng": {}, "brave": {}})
- engine = _make_meta_engine(snapshot)
- result = engine.analyze_query("what is the weather today")
- assert result[0] == "searxng"
-
- def test_no_llm_falls_back_to_reliability(self):
- """Without LLM and without SearXNG, engines sorted by reliability."""
- snapshot = _make_settings_snapshot(
- {
- "brave": {"reliability": 0.9},
- "wikipedia": {"reliability": 0.7},
- }
- )
- engine = _make_meta_engine(snapshot, llm=None)
- engine.llm = None
- result = engine.analyze_query("anything")
- # Should be sorted by reliability (descending)
- assert result[0] == "brave"
-
-
-# ===========================================================================
-# 4. analyze_query — exception handling
-# ===========================================================================
-
-
-class TestAnalyzeQueryExceptions:
- """Verify exception handling in analyze_query."""
-
- def test_llm_exception_falls_back_to_searxng(self):
- """LLM error falls back to searxng-first ordering."""
- snapshot = _make_settings_snapshot(
- {
- "searxng": {"strengths": "general", "description": "meta"},
- "brave": {"strengths": "web", "description": "search"},
- }
- )
- llm = MagicMock()
- llm.invoke.side_effect = RuntimeError("LLM down")
- engine = _make_meta_engine(snapshot, llm=llm)
-
- result = engine.analyze_query("test query")
- assert result[0] == "searxng"
-
- def test_llm_returns_empty_response(self):
- """LLM returns empty string — falls back gracefully."""
- snapshot = _make_settings_snapshot(
- {
- "searxng": {"strengths": "general", "description": "meta"},
- }
- )
- llm = MagicMock()
- llm.invoke.return_value = MagicMock(content="")
- engine = _make_meta_engine(snapshot, llm=llm)
-
- result = engine.analyze_query("test query")
- # searxng should still be included via the fallback
- assert "searxng" in result
-
- def test_llm_returns_invalid_engine_names(self):
- """LLM returns engine names that don't exist — falls back gracefully."""
- snapshot = _make_settings_snapshot(
- {
- "searxng": {"strengths": "general", "description": "meta"},
- }
- )
- llm = MagicMock()
- llm.invoke.return_value = MagicMock(content="nonexistent1,nonexistent2")
- engine = _make_meta_engine(snapshot, llm=llm)
-
- result = engine.analyze_query("test query")
- # searxng should be added as fallback since no valid engines were selected
- assert "searxng" in result
-
-
-# ===========================================================================
-# 5. _get_full_content — failure scenarios
-# ===========================================================================
-
-
-class TestGetFullContent:
- """Verify _get_full_content failure paths."""
-
- def test_snippets_only_skips_content(self):
- """When snippets_only=True, items returned as-is."""
- snapshot = _make_settings_snapshot({"searxng": {}})
- snapshot["search.snippets_only"] = True
- engine = _make_meta_engine(snapshot)
-
- items = [{"title": "Test", "snippet": "content"}]
- result = engine._get_full_content(items)
- assert result == items
-
- def test_selected_engine_exception_returns_items(self):
- """Exception in selected engine returns items unchanged."""
- snapshot = _make_settings_snapshot({"searxng": {}})
- snapshot["search.snippets_only"] = False
- engine = _make_meta_engine(snapshot)
-
- mock_selected = MagicMock()
- mock_selected._get_full_content.side_effect = RuntimeError("failed")
- engine._selected_engine = mock_selected
- engine._selected_engine_name = "searxng"
-
- items = [{"title": "Test"}]
- result = engine._get_full_content(items)
- assert result == items
-
- def test_no_selected_engine_returns_items(self):
- """No selected engine returns items unchanged."""
- snapshot = _make_settings_snapshot({"searxng": {}})
- snapshot["search.snippets_only"] = False
- engine = _make_meta_engine(snapshot)
-
- # Ensure _selected_engine is not set
- if hasattr(engine, "_selected_engine"):
- delattr(engine, "_selected_engine")
-
- items = [{"title": "Test"}]
- result = engine._get_full_content(items)
- assert result == items
-
-
-# ===========================================================================
-# 6. _get_engine_instance — caching and failure
-# ===========================================================================
-
-
-class TestGetEngineInstance:
- """Verify engine instance caching and creation failure."""
-
- def test_cached_engine_returned(self):
- """Cached engine instance is reused."""
- snapshot = _make_settings_snapshot({"searxng": {}})
- engine = _make_meta_engine(snapshot)
-
- mock_cached = MagicMock()
- engine.engine_cache["test_engine"] = mock_cached
-
- result = engine._get_engine_instance("test_engine")
- assert result is mock_cached
-
- @patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.create_search_engine"
- )
- def test_creation_failure_returns_none(self, mock_create):
- """Engine creation failure returns None."""
- mock_create.side_effect = RuntimeError("init failed")
- snapshot = _make_settings_snapshot({"searxng": {}})
- engine = _make_meta_engine(snapshot)
-
- result = engine._get_engine_instance("bad_engine")
- assert result is None
-
- @patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.create_search_engine"
- )
- def test_max_filtered_results_zero_passed(self, mock_create):
- """max_filtered_results=0 (falsy) should NOT be passed when it's None check."""
- mock_create.return_value = MagicMock()
- snapshot = _make_settings_snapshot({"searxng": {}})
-
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.WikipediaSearchEngine"
- ):
- engine = MetaSearchEngine(
- llm=MagicMock(),
- max_results=5,
- max_filtered_results=0,
- settings_snapshot=snapshot,
- )
-
- engine._get_engine_instance("new_engine")
- # max_filtered_results=0 is not None, so should be passed
- call_kwargs = mock_create.call_args
- # 0 is not None, so the "if self.max_filtered_results is not None" check passes
- # and max_filtered_results should be in the params
- assert "max_filtered_results" in (
- call_kwargs.kwargs if call_kwargs.kwargs else call_kwargs[1]
- )
-
-
-# ===========================================================================
-# 7. _get_previews — engine fallthrough
-# ===========================================================================
-
-
-class TestGetPreviews:
- """Verify _get_previews tries engines in order and falls back."""
-
- def test_first_engine_succeeds(self):
- """First engine returning results is used."""
- snapshot = _make_settings_snapshot({"searxng": {}})
- engine = _make_meta_engine(snapshot)
-
- mock_search = MagicMock()
- mock_search._get_previews.return_value = [{"title": "Result 1"}]
- engine._get_engine_instance = MagicMock(return_value=mock_search)
-
- with patch.object(engine, "analyze_query", return_value=["searxng"]):
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.SocketIOService"
- ):
- result = engine._get_previews("test query")
-
- assert len(result) == 1
-
- def test_all_engines_fail_uses_fallback(self):
- """All engines failing falls back to Wikipedia."""
- snapshot = _make_settings_snapshot({"searxng": {}})
- engine = _make_meta_engine(snapshot)
- engine._get_engine_instance = MagicMock(return_value=None)
-
- mock_fallback = MagicMock()
- mock_fallback._get_previews.return_value = [
- {"title": "Wikipedia result"}
- ]
- engine.fallback_engine = mock_fallback
-
- with patch.object(engine, "analyze_query", return_value=["searxng"]):
- result = engine._get_previews("test query")
-
- assert result[0]["title"] == "Wikipedia result"
diff --git a/tests/security/test_egress_adaptive_resolution_followup.py b/tests/security/test_egress_adaptive_resolution_followup.py
index 86c3c0fdcd..5aa36114e2 100644
--- a/tests/security/test_egress_adaptive_resolution_followup.py
+++ b/tests/security/test_egress_adaptive_resolution_followup.py
@@ -7,8 +7,9 @@ These cover gaps not already exercised by
* ADAPTIVE resolution of *registered retriever* primaries (local => PRIVATE_ONLY,
public => PUBLIC_ONLY) via the retriever registry path inside
``_resolve_adaptive_scope``.
-* The full meta-picker frozenset (meta / parallel / parallel_scientific, not
- just "auto") resolving to BOTH, and raising under STRICT.
+* Stray removed meta-engine names (auto / meta / parallel /
+ parallel_scientific) being unclassifiable and resolving to BOTH under
+ ADAPTIVE, and leaving STRICT intact (no ValueError) under STRICT.
* The PRIVATE_ONLY -> require_local_llm/require_local_embeddings *coupling* on a
direct (non-adaptive) PRIVATE_ONLY scope, and the deliberate absence of that
coupling under STRICT.
@@ -72,14 +73,16 @@ def test_resolve_adaptive_concrete_private_engine_is_private_only():
# ---------------------------------------------------------------------------
-# ADAPTIVE: meta-picker frozenset -> BOTH (every member, not just "auto")
+# ADAPTIVE: stray removed meta-engine names -> BOTH (unclassifiable fallback)
# ---------------------------------------------------------------------------
@pytest.mark.parametrize(
"picker", ["auto", "meta", "parallel", "parallel_scientific"]
)
-def test_resolve_adaptive_meta_picker_members_resolve_to_both(picker):
+def test_resolve_adaptive_stray_meta_names_resolve_to_both(picker):
+ # The meta engines were removed; a stray name left in the DB is simply
+ # unclassifiable and falls through to BOTH (no special-case branch).
scope = _resolve_adaptive_scope(
picker,
{},
@@ -101,9 +104,10 @@ def test_resolve_adaptive_empty_primary_is_both():
@pytest.mark.parametrize("picker", ["meta", "parallel", "parallel_scientific"])
-def test_context_adaptive_meta_picker_members_resolve_to_both(picker):
- """Through the public entrypoint: ADAPTIVE + each meta-picker -> BOTH and
- leaves inference requirements untouched (no PRIVATE_ONLY coupling)."""
+def test_context_adaptive_stray_meta_names_resolve_to_both(picker):
+ """Through the public entrypoint: ADAPTIVE + each stray removed meta name
+ -> BOTH and leaves inference requirements untouched (no PRIVATE_ONLY
+ coupling)."""
ctx = context_from_snapshot(
_adaptive_snapshot(picker), primary_engine=picker
)
@@ -251,18 +255,21 @@ def test_strict_preserves_explicit_local_inference_flags():
# ---------------------------------------------------------------------------
-# STRICT + meta-picker -> ValueError (every member except the one already
-# covered by the existing suite)
+# STRICT + stray removed meta name -> STRICT context (no ValueError); the
+# stray name only ever matches itself under the STRICT identity check, and as
+# an unknown engine it is denied (engine_unknown) anyway.
# ---------------------------------------------------------------------------
[email protected]("picker", ["meta", "parallel", "parallel_scientific"])
-def test_strict_with_each_meta_picker_raises_value_error(picker):
- with pytest.raises(ValueError):
- context_from_snapshot(
- {"policy.egress_scope": {"value": "strict"}},
- primary_engine=picker,
- )
+ "picker", ["auto", "meta", "parallel", "parallel_scientific"]
+)
+def test_strict_with_stray_meta_name_builds_strict_context(picker):
+ ctx = context_from_snapshot(
+ {"policy.egress_scope": {"value": "strict"}},
+ primary_engine=picker,
+ )
+ assert ctx.scope == EgressScope.STRICT
def test_strict_with_concrete_primary_does_not_raise():
diff --git a/tests/security/test_egress_guidance.py b/tests/security/test_egress_guidance.py
index f9cf0ecc6b..c8ab317903 100644
--- a/tests/security/test_egress_guidance.py
+++ b/tests/security/test_egress_guidance.py
@@ -23,7 +23,6 @@ from local_deep_research.security.egress.guidance import denial_guidance
["Public only", "Egress Scope"],
),
("strict_not_primary", "wikipedia", ["Strict", "primary"]),
- ("strict_with_meta_picker", None, ["Strict", "meta-picker"]),
# Inference blocks name the require-local toggle.
("provider_cloud_only", "openai", ["Require local LLM", "openai"]),
("provider_cloud", "openai", ["Require local embeddings"]),
diff --git a/tests/security/test_egress_mcp_scope_gating.py b/tests/security/test_egress_mcp_scope_gating.py
index 1c1fed8468..06296db699 100644
--- a/tests/security/test_egress_mcp_scope_gating.py
+++ b/tests/security/test_egress_mcp_scope_gating.py
@@ -111,13 +111,12 @@ def test_scope_blocked_corrupt_scope_fails_closed():
assert reason.startswith("policy_unavailable:")
-def test_scope_blocked_strict_meta_picker_fails_closed():
- """STRICT + meta-picker primary ('auto') is incoherent -> fail closed
- (ValueError from the cross-field invariant), not a silent allow."""
+def test_scope_blocked_strict_stray_meta_primary_still_blocks():
+ """STRICT with a stray removed meta-engine primary ('auto') no longer
+ raises at context construction, but the scope is still STRICT — MCP stays
+ blocked, never a silent allow."""
strat = make_strategy(snapshot=snap("strict", primary="auto"))
- blocked, reason = strat._mcp_scope_blocked()
- assert blocked is True
- assert reason.startswith("policy_unavailable:")
+ assert strat._mcp_scope_blocked() == (True, "strict")
# ---------------------------------------------------------------------------
diff --git a/tests/security/test_egress_news_subscription_callsite.py b/tests/security/test_egress_news_subscription_callsite.py
index 22c59c3e83..481c6a1f4c 100644
--- a/tests/security/test_egress_news_subscription_callsite.py
+++ b/tests/security/test_egress_news_subscription_callsite.py
@@ -9,9 +9,9 @@ call-site functions ``create_subscription`` / ``update_subscription`` in
* blocks persistence (no ``session.add`` / ``session.commit``) when the
chosen search engine or LLM provider violates the user's egress scope,
* lets a coherent config through to persistence,
- * surfaces an incoherent egress config (STRICT + meta-picker primary) as a
- misconfiguration error at create/update time rather than silently skipping
- it, and
+ * still blocks a forbidden engine when the configured primary is a stray
+ removed meta-engine name (STRICT + "auto") rather than silently skipping
+ the check, and
* skips the (best-effort) pre-check when the settings backend or the request
context needed to resolve the user is unavailable — the execution-time
factory PEP remains the backstop.
@@ -50,9 +50,9 @@ REQUIRE_LOCAL = {
"policy.egress_scope": "both",
"llm.require_local_endpoint": True,
}
-# STRICT scope with a meta-picker primary is an incoherent combination that
-# makes context_from_snapshot raise ValueError.
-INCOHERENT = {"policy.egress_scope": "strict", "search.tool": "auto"}
+# STRICT scope with a stray removed meta-engine primary: the context still
+# builds as STRICT, so every engine except the (nonexistent) primary is denied.
+STRAY_META_PRIMARY = {"policy.egress_scope": "strict", "search.tool": "auto"}
def _settings_manager(snapshot, primary="arxiv"):
@@ -174,15 +174,16 @@ def test_create_allows_local_provider():
# ---------------------------------------------------------------------------
-# create_subscription — incoherent config surfaces (not silently skipped)
+# create_subscription — stray removed meta primary still blocks (fail closed)
# ---------------------------------------------------------------------------
-def test_create_surfaces_incoherent_egress_config():
- """STRICT + meta-picker primary makes context_from_snapshot raise
- ValueError; the call site must surface it as a misconfiguration error at
- create time and block persistence, NOT let the broad except swallow it."""
- sm = _settings_manager(INCOHERENT, primary="auto")
+def test_create_blocks_engine_under_stray_meta_primary():
+ """STRICT + a stray removed meta-engine primary ("auto") no longer raises
+ at context construction; the STRICT identity check must still reject a
+ non-primary engine at create time and block persistence — never a silent
+ allow."""
+ sm = _settings_manager(STRAY_META_PRIMARY, primary="auto")
with (
_db_session() as session,
patch(SM_PATH, return_value=sm),
@@ -195,7 +196,7 @@ def test_create_surfaces_incoherent_egress_config():
search_engine="pubmed",
refresh_minutes=60,
)
- assert "misconfigured" in exc.value.message
+ assert "strict_not_primary" in exc.value.message
session.add.assert_not_called()
diff --git a/tests/security/test_egress_pep_coverage.py b/tests/security/test_egress_pep_coverage.py
index c113b04764..8a90b50aaa 100644
--- a/tests/security/test_egress_pep_coverage.py
+++ b/tests/security/test_egress_pep_coverage.py
@@ -8,7 +8,6 @@ surfaces here.
Targets:
- fetch tools _enforce_url_policy (per-URL fetch PEP)
-- meta_search_engine._wikipedia_fallback_allowed (fail-closed fallback gate)
- egress_policy.evaluate_engine for dynamic collection_<id>/library engines
- app_factory handle_policy_denied Flask error handler
"""
@@ -67,60 +66,22 @@ class TestEnforceUrlPolicy:
# ---------------------------------------------------------------------------
-# meta_search_engine._wikipedia_fallback_allowed
+# Removed meta engines fail closed in evaluate_engine
# ---------------------------------------------------------------------------
-class TestWikipediaFallbackAllowed:
- """Fail-closed gate for the meta engine's wikipedia fallback. Wikipedia
- is public, so it's allowed under PUBLIC_ONLY/BOTH and refused under
- PRIVATE_ONLY. A corrupt scope (PolicyDeniedError) or an invalid combo
- (ValueError, e.g. STRICT+meta) must BOTH fail closed (return False)."""
+class TestRemovedMetaEnginesUnknown:
+ """The auto/meta/parallel/parallel_scientific meta engines were removed.
+ Their names no longer get a delegator carve-out in evaluate_engine — a
+ stray name left in a config must be denied as engine_unknown."""
- def _engine(self, snapshot):
- from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
- )
-
- # Bypass __init__ — we only need settings_snapshot for this method.
- engine = MetaSearchEngine.__new__(MetaSearchEngine)
- engine.settings_snapshot = snapshot
- return engine
-
- def test_no_snapshot_allows_fallback(self):
- # Offline path — children gated by the factory PEP downstream.
- assert self._engine(None)._wikipedia_fallback_allowed() is True
- assert self._engine({})._wikipedia_fallback_allowed() is True
-
- def test_public_only_allows_wikipedia(self):
- eng = self._engine(
- {"policy.egress_scope": "public_only", "search.tool": "arxiv"}
- )
- assert eng._wikipedia_fallback_allowed() is True
-
- def test_private_only_refuses_wikipedia(self):
- eng = self._engine(
- {"policy.egress_scope": "private_only", "search.tool": "library"}
- )
- assert eng._wikipedia_fallback_allowed() is False
-
- def test_corrupt_scope_fails_closed(self):
- # Unknown scope => context_from_snapshot raises PolicyDeniedError
- # => fallback must be refused, not allowed.
- eng = self._engine(
- {"policy.egress_scope": "garbage", "search.tool": "arxiv"}
- )
- assert eng._wikipedia_fallback_allowed() is False
-
- def test_strict_meta_value_error_fails_closed(self):
- # STRICT + meta-picker primary => context_from_snapshot raises
- # ValueError (not PolicyDeniedError). The handler must catch it
- # too and fail closed. Regression: ValueError was previously
- # uncaught and propagated.
- eng = self._engine(
- {"policy.egress_scope": "strict", "search.tool": "meta"}
- )
- assert eng._wikipedia_fallback_allowed() is False
+ @pytest.mark.parametrize(
+ "name", ["auto", "meta", "parallel", "parallel_scientific"]
+ )
+ def test_removed_meta_name_denied_as_unknown(self, name):
+ d = evaluate_engine(name, _ctx("both"), settings_snapshot={})
+ assert not d.allowed
+ assert d.reason == "engine_unknown"
# ---------------------------------------------------------------------------
diff --git a/tests/security/test_egress_pep_factory_callsite.py b/tests/security/test_egress_pep_factory_callsite.py
index d0afc9b3e0..5dbc3f335f 100644
--- a/tests/security/test_egress_pep_factory_callsite.py
+++ b/tests/security/test_egress_pep_factory_callsite.py
@@ -176,45 +176,35 @@ class TestStrictScope:
# ---------------------------------------------------------------------------
-# Meta-picker delegation + STRICT/meta incoherence at the factory.
+# Removed meta-pickers (auto/meta/parallel/parallel_scientific) fail closed.
# ---------------------------------------------------------------------------
-class TestMetaPickerDelegation:
- """Meta-pickers (auto/meta) are delegators: the factory permits them under
- non-STRICT scopes and gates their CHILDREN at child-instantiation time. The
- incoherent STRICT + meta-picker-primary combination is rejected at the
- factory PEP, because constructing the EgressContext for a concrete child
- under that snapshot raises (translated to invalid_policy_config)."""
+class TestRemovedMetaEnginesFailClosed:
+ """The meta-picker engines were removed. Their names no longer get a
+ skip-the-PEP fast path at the factory: they are unknown engine names and
+ must be rejected (ValueError) before any construction — never silently
+ delegated or rewritten to a concrete engine."""
- def test_meta_permitted_under_both(self):
- snap = _snapshot("both", "auto")
- with _stub_engine_construction() as loader:
- engine = factory.create_search_engine(
- "meta", settings_snapshot=snap
- )
- assert isinstance(engine, _FakeEngine)
- loader.assert_called()
-
- def test_auto_permitted_under_public_only(self):
- snap = _snapshot("public_only", "auto")
+ @pytest.mark.parametrize(
+ "name", ["auto", "meta", "parallel", "parallel_scientific"]
+ )
+ def test_removed_meta_name_raises_value_error(self, name):
+ snap = _snapshot("both", "arxiv", "arxiv")
with _stub_engine_construction() as loader:
- engine = factory.create_search_engine(
- "auto", settings_snapshot=snap
- )
- assert isinstance(engine, _FakeEngine)
- loader.assert_called()
+ with pytest.raises(ValueError, match="removed"):
+ factory.create_search_engine(name, settings_snapshot=snap)
+ loader.assert_not_called()
- def test_strict_with_meta_primary_refused(self):
- # scope=STRICT with a meta-picker primary is incoherent. Building a
- # concrete child engine under that snapshot makes the factory PEP
- # construct an EgressContext, which raises and is surfaced as a
- # PolicyDeniedError(invalid_policy_config) — never silently allowed.
+ def test_strict_with_stray_meta_primary_still_denies_non_primary(self):
+ # A stray 'meta' primary left in the DB under STRICT no longer raises
+ # at context construction; the STRICT identity check still refuses any
+ # concrete engine that isn't the (nonexistent) primary — fail closed.
snap = _snapshot("strict", "meta", "arxiv")
with _stub_engine_construction() as loader:
with pytest.raises(PolicyDeniedError) as exc:
factory.create_search_engine("arxiv", settings_snapshot=snap)
- assert exc.value.decision.reason == "invalid_policy_config"
+ assert exc.value.decision.reason == "strict_not_primary"
loader.assert_not_called()
diff --git a/tests/security/test_egress_policy.py b/tests/security/test_egress_policy.py
index 1a75aa9d20..01b3f2f655 100644
--- a/tests/security/test_egress_policy.py
+++ b/tests/security/test_egress_policy.py
@@ -91,7 +91,9 @@ def _scope_snapshot(scope, tool):
}
-def test_adaptive_meta_picker_primary_resolves_to_both():
+def test_adaptive_stray_auto_primary_resolves_to_both():
+ # "auto" is no longer a registered engine (meta-pickers were removed); a
+ # stray value left in the DB is unclassifiable and falls through to BOTH.
ctx = context_from_snapshot(
_scope_snapshot("adaptive", "auto"), primary_engine="auto"
)
@@ -222,10 +224,16 @@ def test_context_from_snapshot_reads_nested_value_dicts():
assert ctx.require_local_llm is True
-def test_context_rejects_strict_with_meta_picker():
+def test_context_strict_with_stray_meta_name_builds_strict_context():
+ # Meta-pickers were removed: STRICT + a stray "auto" primary no longer
+ # raises ValueError at context construction. The context stays STRICT and
+ # the stray engine itself is denied downstream (engine_unknown).
snapshot = {"policy.egress_scope": "strict"}
- with pytest.raises(ValueError):
- context_from_snapshot(snapshot, primary_engine="auto")
+ ctx = context_from_snapshot(snapshot, primary_engine="auto")
+ assert ctx.scope == EgressScope.STRICT
+ decision = evaluate_engine("auto", ctx, settings_snapshot={})
+ assert not decision.allowed
+ assert decision.reason == "engine_unknown"
def test_context_unknown_scope_raises_policy_denied():
@@ -274,11 +282,12 @@ def test_evaluate_engine_strict_non_primary_denied():
assert decision.reason == "strict_not_primary"
-def test_evaluate_engine_strict_with_meta_picker_engine():
- # auto/meta/parallel can never be permitted under STRICT.
+def test_evaluate_engine_strict_with_removed_meta_engine():
+ # The removed auto/meta/parallel names can never be permitted under STRICT.
ctx = make_ctx(scope=EgressScope.STRICT, primary="arxiv")
decision = evaluate_engine("auto", ctx, settings_snapshot={})
assert not decision.allowed
+ assert decision.reason == "strict_not_primary"
# ---------------------------------------------------------------------------
@@ -1760,23 +1769,6 @@ def test_n8_unknown_scope_raises_after_context_from_snapshot():
assert excinfo.value.decision.reason == "unknown_egress_scope"
-def test_h1_strict_meta_picker_raises_in_llm_config():
- """H1: STRICT + meta-picker primary engine must raise
- PolicyDeniedError(invalid_policy_config), not silently bypass.
- """
- from local_deep_research.config import llm_config
-
- snapshot = {
- "policy.egress_scope": "strict",
- "search.tool": "auto",
- "llm.provider": "openai",
- "llm.openai.api_key": "fake",
- }
- with pytest.raises(PolicyDeniedError) as excinfo:
- llm_config.get_llm(provider="openai", settings_snapshot=snapshot)
- assert excinfo.value.decision.reason == "invalid_policy_config"
-
-
def test_c8_banner_suppressed_for_private_base_url():
"""C8: cloud-embeddings banner suppressed when base_url points to
any private IP (RFC1918, CGNAT, link-local, IPv6 private). The old
@@ -1999,61 +1991,6 @@ def test_local_embedding_manager_propagates_policy_denied():
assert excinfo.value.decision.reason == "embeddings_model_not_cached"
-def test_h4_strict_meta_save_validation():
- """H4 layer 2: validate_strict_meta_combo rejects STRICT + a
- meta-picker primary at settings-save time, using effective values
- (form override falling back to DB)."""
- from types import SimpleNamespace
-
- from local_deep_research.security.egress.validators import (
- validate_strict_meta_combo,
- )
-
- def _db(value):
- return SimpleNamespace(value=value)
-
- # STRICT + auto (both from DB) → rejected.
- db_settings = {
- "policy.egress_scope": _db("strict"),
- "search.tool": _db("auto"),
- }
- err = validate_strict_meta_combo({}, db_settings)
- assert err is not None
- assert err["key"] == "policy.egress_scope"
-
- # STRICT + concrete engine → allowed.
- db_settings = {
- "policy.egress_scope": _db("strict"),
- "search.tool": _db("arxiv"),
- }
- assert validate_strict_meta_combo({}, db_settings) is None
-
- # Form changing engine to a concrete one while DB scope is strict →
- # allowed (effective engine = form value).
- db_settings = {
- "policy.egress_scope": _db("strict"),
- "search.tool": _db("auto"),
- }
- assert (
- validate_strict_meta_combo({"search.tool": "searxng"}, db_settings)
- is None
- )
-
- # Form setting scope=strict while DB engine is a meta-picker → rejected.
- db_settings = {"search.tool": _db("parallel")}
- err = validate_strict_meta_combo(
- {"policy.egress_scope": "strict"}, db_settings
- )
- assert err is not None
-
- # Non-strict scope → always fine.
- db_settings = {
- "policy.egress_scope": _db("both"),
- "search.tool": _db("auto"),
- }
- assert validate_strict_meta_combo({}, db_settings) is None
-
-
def test_n14_subscription_policy_rejects_forbidden_engine():
"""N14: _validate_subscription_policy returns a rejection reason when
the subscription's engine violates the user's egress policy, and None
@@ -2118,11 +2055,10 @@ def test_n14_subscription_policy_skips_without_settings():
)
-def test_n15_subscription_policy_rejects_incoherent_egress_config():
- """R3 #8: an incoherent egress config (STRICT scope + meta-picker primary)
- makes context_from_snapshot raise ValueError; subscription validation must
- surface that as a misconfiguration message (fail-fast at create/update
- time), NOT let the outer except silently skip the check."""
+def test_n15_subscription_policy_rejects_stray_meta_primary_config():
+ """R3 #8 follow-up: a stray removed meta-picker primary ("auto") under
+ STRICT no longer raises at context construction — it must STILL reject a
+ non-primary subscription engine (fail closed), never silently allow it."""
from unittest.mock import MagicMock, patch
from local_deep_research.news import api as news_api
@@ -2145,7 +2081,7 @@ def test_n15_subscription_policy_rejects_incoherent_egress_config():
model_provider=None,
)
assert reason is not None
- assert "misconfigured" in reason
+ assert "strict_not_primary" in reason
# ---------------------------------------------------------------------------
diff --git a/tests/security/test_egress_settings_save_validators.py b/tests/security/test_egress_settings_save_validators.py
index 8e49354fa6..459cd0d0ce 100644
--- a/tests/security/test_egress_settings_save_validators.py
+++ b/tests/security/test_egress_settings_save_validators.py
@@ -5,9 +5,6 @@ These drive the REAL cross-field policy validators in
them (``web/routes/settings_routes.py``: ``save_all_settings`` /
``save_settings`` / ``api_update_setting``):
-- ``validate_strict_meta_combo``: STRICT egress scope is incoherent with a
- meta-picker primary engine (auto / meta / parallel / parallel_scientific)
- because STRICT means "only the one concrete primary engine".
- ``validate_allowed_local_hostnames``: a PUBLIC hostname may not be smuggled
into ``llm.allowed_local_hostnames`` (the host classifier would then trust
external hosts as "local"); private / loopback hosts are accepted.
@@ -24,17 +21,14 @@ literal — no network round-trip, fully deterministic.
"""
from contextlib import contextmanager
-from types import SimpleNamespace
from unittest.mock import MagicMock, patch
import pytest
from flask import Flask
from local_deep_research.security.egress import validators
-from local_deep_research.security.egress.policy import _META_PICKER_ENGINES
from local_deep_research.security.egress.validators import (
validate_allowed_local_hostnames,
- validate_strict_meta_combo,
)
from local_deep_research.web.routes.settings_routes import settings_bp
@@ -45,99 +39,16 @@ MODULE = "local_deep_research.web.routes.settings_routes"
DECORATOR_MODULE = "local_deep_research.web.utils.route_decorators"
-def _db_row(value):
- """Minimal stand-in for a Setting ORM row: the validators only read ``.value``."""
- return SimpleNamespace(value=value)
-
-
# ---------------------------------------------------------------------------
-# validate_strict_meta_combo (STRICT + meta-picker primary)
+# Removed validator regression guard
# ---------------------------------------------------------------------------
-def test_strict_with_meta_picker_primary_in_form_is_rejected():
- """STRICT scope + auto engine, both arriving in the same save, is rejected."""
- err = validate_strict_meta_combo(
- {SCOPE_KEY: "strict", ENGINE_KEY: "auto"}, {}
- )
- assert err is not None
- assert err["key"] == SCOPE_KEY
- assert "meta-picker" in err["error"]
-
-
-def test_strict_with_concrete_primary_in_form_is_accepted():
- """The allow side of the pair: STRICT + a concrete engine is coherent."""
- assert (
- validate_strict_meta_combo(
- {SCOPE_KEY: "strict", ENGINE_KEY: "arxiv"}, {}
- )
- is None
- )
-
-
-def test_non_strict_scope_with_meta_picker_is_accepted():
- """A meta-picker is only incoherent under STRICT — PUBLIC_ONLY allows it."""
- assert (
- validate_strict_meta_combo(
- {SCOPE_KEY: "public_only", ENGINE_KEY: "auto"}, {}
- )
- is None
- )
-
-
-def test_every_meta_picker_engine_is_rejected_under_strict():
- """All declared meta-picker engines trip the STRICT guard; a concrete one
- does not. Pins the guard to the real ``_META_PICKER_ENGINES`` set."""
- for engine in _META_PICKER_ENGINES:
- err = validate_strict_meta_combo(
- {SCOPE_KEY: "strict", ENGINE_KEY: engine}, {}
- )
- assert err is not None, engine
- assert (
- validate_strict_meta_combo(
- {SCOPE_KEY: "strict", ENGINE_KEY: "searxng"}, {}
- )
- is None
- )
-
-
-def test_strict_in_form_uses_db_engine_fallback_for_rejection():
- """Changing ONLY the scope to STRICT must still see the existing DB engine
- (auto) and reject — the effective-value fallback is load-bearing."""
- db = {ENGINE_KEY: _db_row("auto")}
- err = validate_strict_meta_combo({SCOPE_KEY: "strict"}, db)
- assert err is not None
- assert err["key"] == SCOPE_KEY
-
-
-def test_meta_engine_in_form_uses_db_scope_fallback_for_rejection():
- """Changing ONLY the engine to a meta-picker must see the existing STRICT
- scope in the DB and reject (mirror direction of the fallback)."""
- db = {SCOPE_KEY: _db_row("strict")}
- err = validate_strict_meta_combo({ENGINE_KEY: "parallel"}, db)
- assert err is not None
-
-
-def test_strict_with_concrete_db_engine_is_accepted():
- """Allow side of the DB-fallback pair: STRICT form + concrete DB engine."""
- db = {ENGINE_KEY: _db_row("searxng")}
- assert validate_strict_meta_combo({SCOPE_KEY: "strict"}, db) is None
-
-
-def test_missing_scope_or_engine_returns_none():
- """No decision can be made when either field is absent in form and DB."""
- assert validate_strict_meta_combo({SCOPE_KEY: "strict"}, {}) is None
- assert validate_strict_meta_combo({ENGINE_KEY: "auto"}, {}) is None
-
-
-def test_unknown_scope_value_is_not_blocked_here():
- """An unparseable scope is left to runtime fail-closed, not blocked at save."""
- assert (
- validate_strict_meta_combo(
- {SCOPE_KEY: "nonsense", ENGINE_KEY: "auto"}, {}
- )
- is None
- )
+def test_validate_strict_meta_combo_is_gone():
+ """The meta-picker engines were removed, so the STRICT+meta-picker
+ save-time validator must no longer exist (stray meta names are denied at
+ runtime by ``evaluate_engine`` as ``engine_unknown`` instead)."""
+ assert not hasattr(validators, "validate_strict_meta_combo")
# ---------------------------------------------------------------------------
@@ -349,20 +260,6 @@ def test_route_accepts_private_local_hostname():
assert "error" not in resp.get_json()
-def test_route_rejects_strict_scope_with_db_meta_picker():
- """PUT policy.egress_scope=strict while DB search.tool=auto -> 400."""
- settings = [
- _make_setting(SCOPE_KEY, "both"),
- _make_setting(ENGINE_KEY, "auto"),
- ]
- with _routed_client(settings) as client:
- resp = client.put(
- f"/settings/api/{SCOPE_KEY}", json={"value": "strict"}
- )
- assert resp.status_code == 400
- assert "meta-picker" in resp.get_json()["error"]
-
-
def test_route_accepts_strict_scope_with_db_concrete_engine():
"""Allow counterpart: STRICT scope with a concrete DB engine saves (200)."""
settings = [
diff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.json
index fe6876a48c..94b8dfcd63 100644
--- a/tests/settings/golden_master_settings.json
+++ b/tests/settings/golden_master_settings.json
@@ -2151,7 +2151,7 @@
},
"policy.egress_scope": {
"category": "policy",
- "description": "EXPERIMENTAL — this egress boundary is new defense-in-depth, not an absolute guarantee yet; don't rely on it as your only protection for highly sensitive data. Restrict which search engines a research run may use. ADAPTIVE (default) = follow your primary engine: a private primary keeps everything local, a public primary allows public engines, a meta-picker allows both. STRICT = only the primary engine you picked; PUBLIC_ONLY = any public web/academic engine; PRIVATE_ONLY = any local engine (library, paperless, etc.); BOTH = any classified engine. STRICT is incompatible with auto/meta/parallel primaries.",
+ "description": "EXPERIMENTAL — this egress boundary is new defense-in-depth, not an absolute guarantee yet; don't rely on it as your only protection for highly sensitive data. Restrict which search engines a research run may use. ADAPTIVE (default) = follow your primary engine: a private primary keeps everything local, a public primary allows public engines. STRICT = only the primary engine you picked; PUBLIC_ONLY = any public web/academic engine; PRIVATE_ONLY = any local engine (library, paperless, etc.); BOTH = any classified engine.",
"editable": true,
"max_value": null,
"min_value": null,
@@ -2602,138 +2602,6 @@
"value": "wikipedia",
"visible": true
},
- "search.engine.auto.default_params.max_engines_to_try": {
- "category": "auto",
- "description": "Maximum number of search engines to try before returning results. Auto mode selects the best engine(s) based on your query type.",
- "editable": true,
- "max_value": null,
- "min_value": 1,
- "name": "Max Engines To Try",
- "options": null,
- "step": null,
- "type": "SEARCH",
- "ui_element": "number",
- "value": 3,
- "visible": true
- },
- "search.engine.auto.default_params.use_api_key_services": {
- "category": "auto",
- "description": "Whether to include paid API services (Brave, SerpAPI, etc.) in auto-selection. Disable to only use free search engines.",
- "editable": true,
- "max_value": null,
- "min_value": null,
- "name": "Use Api Key Services",
- "options": null,
- "step": null,
- "type": "SEARCH",
- "ui_element": "checkbox",
- "value": true,
- "visible": true
- },
- "search.engine.auto.description": {
- "category": "auto",
- "description": "Human-readable description of the search engine.",
- "editable": false,
- "max_value": null,
- "min_value": null,
- "name": "Description",
- "options": null,
- "step": null,
- "type": "SEARCH",
- "ui_element": "text",
- "value": "Attempt to choose the best combination of search engines automatically.",
- "visible": false
- },
- "search.engine.auto.display_name": {
- "category": "auto",
- "description": "Display name to use in the U.I. for this search engine.",
- "editable": false,
- "max_value": null,
- "min_value": null,
- "name": "Display Name",
- "options": null,
- "step": null,
- "type": "SEARCH",
- "ui_element": "text",
- "value": "Auto",
- "visible": false
- },
- "search.engine.auto.reliability": {
- "category": "auto",
- "description": "Reliability rating for auto mode. Varies based on which underlying engine is selected.",
- "editable": true,
- "max_value": 1.0,
- "min_value": 0.0,
- "name": "Reliability",
- "options": null,
- "step": 0.05,
- "type": "SEARCH",
- "ui_element": "range",
- "value": 0.85,
- "visible": true
- },
- "search.engine.auto.requires_api_key": {
- "category": "auto",
- "description": "Whether auto mode requires API keys. False because it can fall back to free engines like Wikipedia.",
- "editable": true,
- "max_value": null,
- "min_value": null,
- "name": "Requires Api Key",
- "options": null,
- "step": null,
- "type": "SEARCH",
- "ui_element": "checkbox",
- "value": false,
- "visible": true
- },
- "search.engine.auto.requires_llm": {
- "category": "auto",
- "description": "Whether auto mode uses LLM to select the best engine. When disabled, falls back to rule-based selection.",
- "editable": true,
- "max_value": null,
- "min_value": null,
- "name": "Requires Llm",
- "options": null,
- "step": null,
- "type": "SEARCH",
- "ui_element": "checkbox",
- "value": true,
- "visible": true
- },
- "search.engine.auto.strengths": {
- "category": "auto",
- "description": "Key advantages of auto mode: Intelligently selects the best engine for each query type, tries multiple sources if needed.",
- "editable": true,
- "max_value": null,
- "min_value": null,
- "name": "Strengths",
- "options": null,
- "step": null,
- "type": "SEARCH",
- "ui_element": "json",
- "value": [
- "intelligent engine selection",
- "adaptable to query type",
- "fallback capabilities"
- ],
- "visible": true
- },
- "search.engine.auto.weaknesses": {
- "category": "auto",
- "description": "Limitations of auto mode: May use more API calls trying multiple engines, selection heuristics may not always be optimal.",
- "editable": true,
- "max_value": null,
- "min_value": null,
- "name": "Weaknesses",
- "options": null,
- "step": null,
- "type": "SEARCH",
- "ui_element": "json",
- "value": [
- "slightly slower due to LLM analysis"
- ],
- "visible": true
- },
"search.engine.web.arxiv.default_params.max_results": {
"category": "arxiv",
"description": "Maximum number of papers to retrieve from arXiv per search query.",
@@ -5027,174 +4895,6 @@
],
"visible": true
},
- "search.engine.web.parallel.default_params.allow_local_engines": {
- "category": "parallel",
- "description": "⚠️ PRIVACY WARNING: Allow local/private document engines in parallel search. This may expose personal data from your documents to web search queries and LLMs. Only enable if you understand the privacy implications.",
- "editable": true,
- "max_value": null,
- "min_value": null,
- "name": "Allow Local Engines",
- "options": null,
- "step": null,
- "type": "SEARCH",
- "ui_element": "checkbox",
- "value": false,
- "visible": true
- },
- "search.engine.web.parallel.default_params.enable_llm_relevance_filter": {
- "category": "parallel",
- "description": "Enable LLM-based relevance filtering to improve result quality by filtering out irrelevant results. This adds an extra LLM call but significantly improves result relevance.",
- "editable": true,
- "max_value": null,
- "min_value": null,
- "name": "Enable LLM Relevance Filter",
- "options": null,
- "step": null,
- "type": "SEARCH",
- "ui_element": "checkbox",
- "value": true,
- "visible": true
- },
- "search.engine.web.parallel.default_params.max_engines_to_select": {
- "category": "parallel",
- "description": "Maximum number of search engines to select and run in parallel",
- "editable": true,
- "max_value": 10,
- "min_value": 1,
- "name": "Max Engines to Select",
- "options": null,
- "step": 1,
- "type": "SEARCH",
- "ui_element": "number",
- "value": 5,
- "visible": true
- },
- "search.engine.web.parallel.default_params.use_api_key_services": {
- "category": "parallel",
- "description": "Include search engines that require API keys",
- "editable": true,
- "max_value": null,
- "min_value": null,
- "name": "Use API Key Services",
- "options": null,
- "step": null,
- "type": "SEARCH",
- "ui_element": "checkbox",
- "value": true,
- "visible": true
- },
- "search.engine.web.parallel.description": {
- "category": "parallel",
- "description": "Human-readable description of the search engine.",
- "editable": false,
- "max_value": null,
- "min_value": null,
- "name": "Description",
- "options": null,
- "step": null,
- "type": "SEARCH",
- "ui_element": "text",
- "value": "Executes multiple search engines in parallel and combines their results. Uses LLM to select the most appropriate engines for each query.",
- "visible": true
- },
- "search.engine.web.parallel.display_name": {
- "category": "parallel",
- "description": "Display name to use in the U.I. for this search engine.",
- "editable": false,
- "max_value": null,
- "min_value": null,
- "name": "Display Name",
- "options": null,
- "step": null,
- "type": "SEARCH",
- "ui_element": "text",
- "value": "Parallel Search",
- "visible": true
- },
- "search.engine.web.parallel.reliability": {
- "category": "parallel",
- "description": "Reliability of the parallel search engine",
- "editable": true,
- "max_value": 1.0,
- "min_value": 0.0,
- "name": "Reliability",
- "options": null,
- "step": 0.05,
- "type": "SEARCH",
- "ui_element": "range",
- "value": 0.9,
- "visible": true
- },
- "search.engine.web.parallel.requires_api_key": {
- "category": "parallel",
- "description": "Whether this search engine requires an API key",
- "editable": true,
- "max_value": null,
- "min_value": null,
- "name": "Requires Api Key",
- "options": null,
- "step": null,
- "type": "SEARCH",
- "ui_element": "checkbox",
- "value": false,
- "visible": true
- },
- "search.engine.web.parallel.requires_llm": {
- "category": "parallel",
- "description": "Whether this search engine requires an LLM for engine selection",
- "editable": true,
- "max_value": null,
- "min_value": null,
- "name": "Requires LLM",
- "options": null,
- "step": null,
- "type": "SEARCH",
- "ui_element": "checkbox",
- "value": true,
- "visible": true
- },
- "search.engine.web.parallel.strengths": {
- "category": "parallel",
- "description": "Strengths of this search engine",
- "editable": true,
- "max_value": null,
- "min_value": null,
- "name": "Strengths",
- "options": null,
- "step": null,
- "type": "SEARCH",
- "ui_element": "json",
- "value": "[\"Comprehensive results from multiple sources\", \"Parallel execution for faster results\", \"Intelligent engine selection\", \"Automatic deduplication\", \"Combines strengths of all engines\"]",
- "visible": true
- },
- "search.engine.web.parallel.supports_full_search": {
- "category": "parallel",
- "description": "Whether this search engine supports full document search",
- "editable": true,
- "max_value": null,
- "min_value": null,
- "name": "Supports Full Search",
- "options": null,
- "step": null,
- "type": "SEARCH",
- "ui_element": "checkbox",
- "value": false,
- "visible": true
- },
- "search.engine.web.parallel.weaknesses": {
- "category": "parallel",
- "description": "Weaknesses of this search engine",
- "editable": true,
- "max_value": null,
- "min_value": null,
- "name": "Weaknesses",
- "options": null,
- "step": null,
- "type": "SEARCH",
- "ui_element": "json",
- "value": "[\"Higher resource usage\", \"May hit rate limits on multiple engines\", \"Results may vary in quality\", \"Requires LLM for optimal selection\"]",
- "visible": true
- },
"search.engine.web.pubchem": {
"category": "pubchem",
"description": "PubChem search engine configuration",
@@ -8162,16 +7862,12 @@
},
"search.tool": {
"category": "search_general",
- "description": "Search engine to use for research queries. 'Auto' intelligently selects the best engine for each query type. Each engine may require its own API key or service to be configured separately.",
+ "description": "Search engine to use for research queries. The default langgraph-agent strategy can additionally pick specialized engines per query as tools. Each engine may require its own API key or service to be configured separately.",
"editable": true,
"max_value": null,
"min_value": null,
"name": "Search Engine",
"options": [
- {
- "label": "Auto (Default)",
- "value": "auto"
- },
{
"label": "Arxiv",
"value": "arxiv"
@@ -8239,14 +7935,6 @@
{
"label": "Local All",
"value": "local_all"
- },
- {
- "label": "Multi-Engine Search",
- "value": "parallel"
- },
- {
- "label": "Scientific Search (Academic Focus)",
- "value": "parallel_scientific"
}
],
"step": null,
diff --git a/tests/settings/test_settings_defaults_integrity.py b/tests/settings/test_settings_defaults_integrity.py
index 8b31ae9189..809bd47275 100644
--- a/tests/settings/test_settings_defaults_integrity.py
+++ b/tests/settings/test_settings_defaults_integrity.py
@@ -94,8 +94,6 @@ KNOWN_SNAPSHOT_DIVERGENCES = {
"search.engine.web.zenodo",
# List values stored as JSON strings in snapshot but parsed by get_setting()
"mcp.servers",
- "search.engine.web.parallel.strengths",
- "search.engine.web.parallel.weaknesses",
}
# ---------------------------------------------------------------------------
diff --git a/tests/strategies/test_langgraph_agent_strategy.py b/tests/strategies/test_langgraph_agent_strategy.py
index c1a4085fd7..83c84b28b1 100644
--- a/tests/strategies/test_langgraph_agent_strategy.py
+++ b/tests/strategies/test_langgraph_agent_strategy.py
@@ -912,8 +912,7 @@ class TestEgressScopeFiltering:
# Available-engines fixture. ``arxiv`` and ``pubmed`` are registered
# public engines (``is_public = True`` on their classes); ``library``
- # is hardcoded local in ``evaluate_engine`` (line 322-326). ``auto``
- # and ``meta`` are meta-pickers that the loop skips by name.
+ # is hardcoded local in ``evaluate_engine`` (line 322-326).
# ``duckduckgo`` is the current primary — already added as
# ``web_search`` and explicitly skipped at line 618.
_FIXTURE_AVAILABLE = {
@@ -942,8 +941,6 @@ class TestEgressScopeFiltering:
"description": "My research papers (Collection)",
"strengths": ["curated documents"],
},
- "auto": {"description": "auto picker"},
- "meta": {"description": "meta picker"},
"duckduckgo": {
"is_local": False,
"description": "DuckDuckGo",
@@ -1096,11 +1093,10 @@ class TestEgressScopeFiltering:
def test_both_scope_registers_every_classified_engine(self):
"""The default scope BOTH must register every classified engine
- in the available dict. ``auto``/``meta``/the current primary
- are excluded by the explicit ``continue`` at line 618 — NOT by
- the scope filter — so a regression that moved them into the
- scope-mismatch path would still be caught by the assertion that
- they're absent.
+ in the available dict. The current primary is excluded by the
+ explicit ``continue`` at line 618 — NOT by the scope filter — so
+ a regression that moved it into the scope-mismatch path would
+ still be caught by the assertion that it's absent.
"""
strategy = self._make_strategy(scope="both")
with patch(
@@ -1114,11 +1110,9 @@ class TestEgressScopeFiltering:
assert expected in names, (
f"Expected {expected} under BOTH but got: {sorted(names)}"
)
- # Current engine and meta-pickers are NEVER added as specialized
- # tools regardless of scope.
+ # The current engine is NEVER added as a specialized tool
+ # regardless of scope.
assert "search_duckduckgo" not in names
- assert "search_auto" not in names
- assert "search_meta" not in names
# ------------------------------------------------------------------
# Fail-closed: corrupted scope value
diff --git a/tests/test_api_key_configuration.py b/tests/test_api_key_configuration.py
index 39ada2a4ab..3135e90f9f 100644
--- a/tests/test_api_key_configuration.py
+++ b/tests/test_api_key_configuration.py
@@ -92,7 +92,16 @@ class TestAPIKeyConfiguration:
"llm.openai_endpoint.url": "https://openrouter.ai/api/v1",
"llm.context_window_unrestricted": True,
"llm.context_window_size": 128000,
- "search.tool": "auto",
+ # "library" is the only engine the factory can instantiate
+ # from this minimal snapshot (searxng et al. need an instance
+ # URL), and the research path does create the engine. But
+ # "library" is a PRIVATE engine, so under the default adaptive
+ # egress scope it would resolve to PRIVATE_ONLY and force
+ # local LLM — denying the remote openai_endpoint provider this
+ # test configures. Pin the scope to "both" so the test stays
+ # about LLM-provider config, not egress.
+ "search.tool": "library",
+ "policy.egress_scope": "both",
"search.max_results": 10,
"search.cross_engine_max_results": 100,
"search.cross_engine_use_reddit": False,
diff --git a/tests/test_llm_provider_integration.py b/tests/test_llm_provider_integration.py
index a38da69250..cc855d59df 100644
--- a/tests/test_llm_provider_integration.py
+++ b/tests/test_llm_provider_integration.py
@@ -123,11 +123,13 @@ class TestLLMProviderIntegration:
# The fixture sets search.tool="searxng", but searxng is only an
# available engine once an instance URL is configured (it isn't
- # here). The factory now fails closed on an unknown engine instead
- # of silently rewriting it to "auto". This test exercises the LLM
- # provider path, not search, so point it at the always-available
- # "auto" engine (AdvancedSearchSystem is mocked below anyway).
- settings_snapshot["search.tool"]["value"] = "auto"
+ # here) and the research path instantiates the engine. Point it at
+ # the always-available "library" engine instead. "library" is
+ # PRIVATE, so pin the egress scope to "both" — otherwise the
+ # default adaptive scope resolves to PRIVATE_ONLY, forces local
+ # LLM, and denies the OpenRouter provider this test configures.
+ settings_snapshot["search.tool"]["value"] = "library"
+ settings_snapshot["policy.egress_scope"] = {"value": "both"}
# Verify settings are correct - get_all_settings returns nested dicts
assert (
diff --git a/tests/test_programmatic_custom_llm_retriever.py b/tests/test_programmatic_custom_llm_retriever.py
index d176d83311..66602eec6b 100644
--- a/tests/test_programmatic_custom_llm_retriever.py
+++ b/tests/test_programmatic_custom_llm_retriever.py
@@ -380,7 +380,7 @@ def test_multiple_retrievers_with_ollama():
"ml_applications": app_retriever,
},
provider="ollama",
- search_tool="auto", # Use all retrievers
+ search_tool="ml_concepts", # Use a registered retriever
)
assert "summary" in result
diff --git a/tests/test_search_engines_enhanced.py b/tests/test_search_engines_enhanced.py
index 75757c6228..944473a024 100644
--- a/tests/test_search_engines_enhanced.py
+++ b/tests/test_search_engines_enhanced.py
@@ -223,7 +223,6 @@ class TestSearchEngineFactory:
},
"search.engine.DEFAULT_SEARCH_ENGINE": "wikipedia",
"search.max_results": 10,
- "search.engine.auto": {},
"search.engine.local": {},
}
create_mock_db_utils(monkeypatch, search_engine_config)
diff --git a/tests/ui_tests/NO_CI_test_egress_policy_live_research.js b/tests/ui_tests/NO_CI_test_egress_policy_live_research.js
index 97f3937ab2..b90575fe98 100644
--- a/tests/ui_tests/NO_CI_test_egress_policy_live_research.js
+++ b/tests/ui_tests/NO_CI_test_egress_policy_live_research.js
@@ -8,7 +8,8 @@
*
* - configures Ollama + SearXNG endpoints
* - kicks off a real research run under each scope and verifies the
- * run actually starts (or correctly refuses, in the STRICT+auto case)
+ * run actually starts (or correctly refuses, in the STRICT +
+ * non-primary-engine case)
* - exercises the require-local-LLM toggle by trying to use a cloud
* provider through the form
* - captures screenshots of each run state so the UX can be eyeballed
@@ -362,13 +363,15 @@ async function main() {
await page.waitForSelector('#policy_egress_scope', { timeout: 10000 });
// -----------------------------------------------------------
- // 5. STRICT + auto via API — server-side guard refuses even
- // if the UI guard is bypassed. We send a payload that the
- // UI dropdown would not allow.
+ // 5. STRICT + non-primary engine via API — server-side guard
+ // refuses even if the UI guard is bypassed. STRICT permits
+ // only the user's primary engine (search.tool), so a direct
+ // POST naming a different engine must be rejected.
// -----------------------------------------------------------
- await run('5. STRICT + auto via API: server-side refusal', async () => {
- // Force the back-end to see scope=strict + search.tool=auto.
- await saveSetting(page, 'search.tool', 'auto');
+ await run('5. STRICT + non-primary engine via API: server-side refusal', async () => {
+ // Force the back-end to see scope=strict with searxng as
+ // the primary engine, then request a different engine.
+ await saveSetting(page, 'search.tool', 'searxng');
await saveSetting(page, 'policy.egress_scope', 'strict');
// Bypass the UI guard with a direct POST mimicking the form.
@@ -384,10 +387,10 @@ async function main() {
},
credentials: 'same-origin',
body: JSON.stringify({
- query: 'strict-auto-incoherent',
+ query: 'strict-non-primary-incoherent',
mode: 'quick',
model_provider: 'ollama',
- search_engine: 'auto',
+ search_engine: 'wikipedia',
policy_egress_scope: 'strict',
}),
});
@@ -397,18 +400,16 @@ async function main() {
},
BASE_URL,
);
- // The precheck (research_routes.py) now surfaces this as a
- // clean 400 with reason text. Old behaviour returned None
- // and silently allowed the run.
+ // The precheck (research_routes.py) surfaces this as a
+ // clean 400 with reason text (strict_not_primary).
record(
- 'strict-auto-refused-400',
+ 'strict-non-primary-refused-400',
result.status === 400,
`status=${result.status} msg=${(result.body && result.body.message || '').slice(0, 120)}`,
);
- await screenshot(page, '05-strict-auto-api-refusal');
+ await screenshot(page, '05-strict-non-primary-api-refusal');
// Restore.
- await saveSetting(page, 'search.tool', 'searxng');
await saveSetting(page, 'policy.egress_scope', 'both');
});
diff --git a/tests/ui_tests/test_egress_policy_ui.js b/tests/ui_tests/test_egress_policy_ui.js
index 8b2a04cbf8..67bd8f7f73 100644
--- a/tests/ui_tests/test_egress_policy_ui.js
+++ b/tests/ui_tests/test_egress_policy_ui.js
@@ -4,9 +4,9 @@
*
* Exercises the Privacy & Egress feature surface that does NOT need a
* live LLM or search engine: dropdown, scope-derived colour cues, live
- * propagation to body[data-scope], STRICT + meta-picker guard, settings
- * persistence across reloads, chat-page inheritance, warning banner
- * presence/absence per scope, and the require-local toggles.
+ * propagation to body[data-scope], settings persistence across reloads,
+ * chat-page inheritance, warning banner presence/absence per scope, and
+ * the require-local toggles.
*
* Live-engine work (real research runs against Ollama/SearXNG) lives in
* NO_CI_test_egress_policy_live_research.js — runner skips it in CI.
@@ -116,61 +116,6 @@ async function readPanelDataScope(page) {
});
}
-/**
- * The STRICT scope option is disabled when search_engine resolves to a
- * meta-picker (auto/meta/parallel*). Returns true if STRICT is currently
- * a disabled option.
- */
-async function strictOptionDisabled(page) {
- return page.evaluate(() => {
- const opt = document.querySelector(
- '#policy_egress_scope option[value="strict"]',
- );
- return opt ? !!opt.disabled : null;
- });
-}
-
-/**
- * Persist the search engine via the settings save endpoint, then
- * reload the page. The STRICT-availability guard
- * (updateStrictScopeAvailability) is module-scoped inside the
- * research.js IIFE — the only external triggers are the custom-select
- * callback and init-time evaluation. Reloading is the cleanest way to
- * exercise the init path with a known engine value without simulating
- * the entire custom-select dance.
- */
-async function setSearchEngine(page, value) {
- // The settings save endpoint is PUT /settings/api/<key> with body
- // {"value": ...} — same as saveSearchSetting() in research.js. The
- // CSRF token comes from the meta tag rendered by base.html.
- const result = await page.evaluate(
- async (v, base) => {
- const csrfMeta = document.querySelector('meta[name="csrf-token"]');
- const csrf = csrfMeta ? csrfMeta.getAttribute('content') : '';
- const resp = await fetch(`${base}/settings/api/search.tool`, {
- method: 'PUT',
- headers: {
- 'Content-Type': 'application/json',
- 'X-CSRFToken': csrf,
- },
- credentials: 'same-origin',
- body: JSON.stringify({ value: v }),
- });
- return resp.status;
- },
- value,
- BASE_URL,
- );
- if (result !== 200 && result !== 204) {
- throw new Error(`settings save failed: status=${result} key=search.tool value=${value}`);
- }
- await page.reload({ waitUntil: 'domcontentloaded' });
- await page.waitForSelector('#policy_egress_scope', { timeout: 10000 });
- // Wait for the search-engine dropdown bootstrap + the init-time
- // strict-availability evaluation (line 389 / 399 in research.js).
- await sleep(IS_CI ? 1500 : 800);
-}
-
/**
* Run a single test scenario inside a try/catch so one failure does
* not poison the rest of the suite (a flaky CI assertion shouldn't
@@ -324,21 +269,9 @@ async function main() {
});
// -----------------------------------------------------------
- // 6. Switch to STRICT (with a concrete engine first so it's
- // selectable) → violet
+ // 6. Switch to STRICT → violet
// -----------------------------------------------------------
- await run('6. STRICT paints violet when engine is concrete', async () => {
- // Pin the engine to "wikipedia" so STRICT is allowed. The
- // hidden field is what the guard inspects (see
- // updateStrictScopeAvailability in research.js).
- await setSearchEngine(page, 'wikipedia');
- const stillDisabled = await strictOptionDisabled(page);
- record(
- 'strict-enabled-on-concrete',
- stillDisabled === false,
- `option.disabled=${stillDisabled}`,
- );
-
+ await run('6. STRICT paints violet', async () => {
const bodyScope = await selectScope(page, 'strict');
record('body-scope-strict', bodyScope === 'strict');
@@ -353,79 +286,9 @@ async function main() {
});
// -----------------------------------------------------------
- // 7. STRICT + meta-picker guard: switching engine to "auto"
- // must disable the STRICT option AND fall back to "both"
- // if STRICT was selected.
- // -----------------------------------------------------------
- await run('7. STRICT + meta-picker guard (client disables, server rejects)', async () => {
- // Persist a COHERENT combo first: the scope must not be STRICT
- // before we persist a meta-picker engine, otherwise the server's
- // cross-field validator (validate_strict_meta_combo) correctly
- // 400s the incoherent STRICT+meta-picker save — which is exactly
- // the server-side guarantee asserted at the end of this step. We
- // drive the save endpoints directly (not the custom-select UI
- // dance), so set scope=both, then engine=auto, then reload to
- // exercise the init-time guard.
- await selectScope(page, 'both');
- await setSearchEngine(page, 'auto');
-
- // Layer 1 — client guard (init path): the STRICT option is
- // disabled while the engine is a meta-picker, so the user can't
- // pick the incoherent combo in the first place.
- const disabled = await strictOptionDisabled(page);
- record(
- 'strict-disabled-on-auto',
- disabled === true,
- `option.disabled=${disabled}`,
- );
-
- // The scope select must not be sitting on STRICT now that the
- // engine is a meta-picker.
- const scopeNow = await page.$eval(
- '#policy_egress_scope',
- (el) => el.value,
- );
- record(
- 'scope-not-strict-under-meta-picker',
- scopeNow !== 'strict',
- `scope=${scopeNow}`,
- );
-
- // Layer 2 — server guard: even if the client guard were bypassed,
- // persisting STRICT while the engine is a meta-picker is refused
- // (HTTP 400, fail-closed). This is the real defense.
- const strictSaveStatus = await page.evaluate(async (base) => {
- const csrf =
- document
- .querySelector('meta[name="csrf-token"]')
- ?.getAttribute('content') || '';
- const resp = await fetch(
- `${base}/settings/api/policy.egress_scope`,
- {
- method: 'PUT',
- headers: {
- 'Content-Type': 'application/json',
- 'X-CSRFToken': csrf,
- },
- credentials: 'same-origin',
- body: JSON.stringify({ value: 'strict' }),
- },
- );
- return resp.status;
- }, BASE_URL);
- record(
- 'server-rejects-strict-meta-combo',
- strictSaveStatus === 400,
- `status=${strictSaveStatus}`,
- );
-
- await screenshot(page, '06-strict-disabled-on-auto');
- });
-
- // -----------------------------------------------------------
- // 8. Require-local toggles persist to settings DB
+ // 7. Require-local toggles persist to settings DB
// -----------------------------------------------------------
- await run('8. Local-inference checkboxes toggle + persist', async () => {
+ await run('7. Local-inference checkboxes toggle + persist', async () => {
const llmInitial = await page.$eval('#llm_require_local_endpoint', (el) => el.checked);
await page.click('#llm_require_local_endpoint');
await sleep(IS_CI ? 500 : 300);
@@ -446,7 +309,7 @@ async function main() {
`${embInitial} → ${embAfter}`,
);
- await screenshot(page, '07-toggles-flipped');
+ await screenshot(page, '06-toggles-flipped');
// Reload — toggles must persist (proves settings save fired).
await page.reload({ waitUntil: 'domcontentloaded' });
@@ -464,7 +327,7 @@ async function main() {
`reloaded=${embReloaded}`,
);
- await screenshot(page, '08-toggles-after-reload');
+ await screenshot(page, '07-toggles-after-reload');
// Restore to original to leave the env clean for repeat runs.
if (llmAfter !== llmInitial) await page.click('#llm_require_local_endpoint');
@@ -473,9 +336,9 @@ async function main() {
});
// -----------------------------------------------------------
- // 9. Settings dashboard exposes the egress-policy keys
+ // 8. Settings dashboard exposes the egress-policy keys
// -----------------------------------------------------------
- await run('9. Settings dashboard lists policy keys', async () => {
+ await run('8. Settings dashboard lists policy keys', async () => {
await page.goto(`${BASE_URL}/settings/`, {
waitUntil: 'domcontentloaded',
timeout: 30000,
@@ -496,23 +359,19 @@ async function main() {
haveLocalLLM ? 'found' : 'missing',
);
- await screenshot(page, '09-settings-page');
+ await screenshot(page, '08-settings-page');
});
// -----------------------------------------------------------
- // 10. base.html scope cue propagates to OTHER pages
+ // 9. base.html scope cue propagates to OTHER pages
// -----------------------------------------------------------
- await run('10. Scope cue carries to history & metrics pages', async () => {
+ await run('9. Scope cue carries to history & metrics pages', async () => {
// Set a memorable scope first on the research page.
await page.goto(`${BASE_URL}/`, {
waitUntil: 'domcontentloaded',
timeout: 30000,
});
await page.waitForSelector('#policy_egress_scope', { timeout: 10000 });
- // Make sure the search engine is concrete so STRICT is allowed
- // — otherwise selectScope('strict') falls back to "both" via
- // the guard and our cross-page check would assert the wrong thing.
- await setSearchEngine(page, 'wikipedia');
await selectScope(page, 'private_only');
const pages = [
@@ -533,7 +392,7 @@ async function main() {
bodyScope === 'private_only',
`data-scope=${bodyScope}`,
);
- await screenshot(page, `10-cross-page-${p.name.toLowerCase()}`);
+ await screenshot(page, `09-cross-page-${p.name.toLowerCase()}`);
}
// Reset to "both" so a follow-up test run is deterministic.
@@ -546,9 +405,9 @@ async function main() {
});
// -----------------------------------------------------------
- // 11. Warning banner appears/disappears with scope
+ // 10. Warning banner appears/disappears with scope
// -----------------------------------------------------------
- await run('11. Public-egress warning banner reflects scope', async () => {
+ await run('10. Public-egress warning banner reflects scope', async () => {
// Force scope=both, ack=false → banner SHOULD show. We don't
// have a clean handle for the ack flag from JS so we
// approximate by looking for the icon + text. This test is
@@ -570,20 +429,20 @@ async function main() {
hasEgressBanner ? 'visible' : 'absent (likely already acked)',
);
- await screenshot(page, '11-warning-banners-both');
+ await screenshot(page, '10-warning-banners-both');
// Switch to private_only and verify the warning text is gone
// for the public-egress banner (other banners may remain).
await selectScope(page, 'private_only');
await sleep(500);
- await screenshot(page, '11-warning-banners-private');
+ await screenshot(page, '10-warning-banners-private');
record('warning-screenshot-private', true);
});
// -----------------------------------------------------------
- // 12. Privacy panel header icon adopts the scope cue
+ // 11. Privacy panel header icon adopts the scope cue
// -----------------------------------------------------------
- await run('12. Privacy panel header reflects scope colour', async () => {
+ await run('11. Privacy panel header reflects scope colour', async () => {
await selectScope(page, 'private_only');
const headerColor = await page.evaluate(() => {
const el = document.querySelector('.ldr-privacy-panel-header');
@@ -595,13 +454,13 @@ async function main() {
!!headerColor && headerColor !== 'rgb(0, 0, 0)',
`header.color=${headerColor}`,
);
- await screenshot(page, '12-panel-header-private');
+ await screenshot(page, '11-panel-header-private');
});
// -----------------------------------------------------------
- // 13. Tooltip explains each scope
+ // 12. Tooltip explains each scope
// -----------------------------------------------------------
- await run('13. Scope dropdown carries an explanatory tooltip', async () => {
+ await run('12. Scope dropdown carries an explanatory tooltip', async () => {
const tipText = await page.evaluate(() => {
const lbl = document.querySelector('label[for="policy_egress_scope"]');
if (!lbl) return null;
@@ -616,9 +475,9 @@ async function main() {
});
// -----------------------------------------------------------
- // 14. Per-research overrides survive a form-state roundtrip
+ // 13. Per-research overrides survive a form-state roundtrip
// -----------------------------------------------------------
- await run('14. Per-research override values are read back by the form', async () => {
+ await run('13. Per-research override values are read back by the form', async () => {
// Set a deliberate combination, save by changing each
// control, then reload and verify the form reflects them.
await selectScope(page, 'public_only');
@@ -648,7 +507,7 @@ async function main() {
`checked=${llmReloaded}`,
);
- await screenshot(page, '14-roundtrip-public-only-require-local');
+ await screenshot(page, '13-roundtrip-public-only-require-local');
// Clean up.
if (llmReloaded) await page.click('#llm_require_local_endpoint');
@@ -656,9 +515,9 @@ async function main() {
});
// -----------------------------------------------------------
- // 15. Chat page inherits scope cue (only if chat is enabled)
+ // 14. Chat page inherits scope cue (only if chat is enabled)
// -----------------------------------------------------------
- await run('15. Chat page inherits data-scope', async () => {
+ await run('14. Chat page inherits data-scope', async () => {
await selectScope(page, 'strict');
const chatRes = await page.goto(`${BASE_URL}/chat/`, {
waitUntil: 'domcontentloaded',
@@ -680,7 +539,7 @@ async function main() {
bodyScope === 'strict',
`data-scope=${bodyScope}`,
);
- await screenshot(page, '15-chat-page-strict');
+ await screenshot(page, '14-chat-page-strict');
// Reset.
await page.goto(`${BASE_URL}/`, {
diff --git a/tests/utilities/test_enums.py b/tests/utilities/test_enums.py
index 3861e877a7..3c99356f78 100644
--- a/tests/utilities/test_enums.py
+++ b/tests/utilities/test_enums.py
@@ -3,11 +3,8 @@ Tests for utilities/enums.py
Tests cover:
- KnowledgeAccumulationApproach enum
-- SearchMode enum
"""
-import pytest
-
class TestKnowledgeAccumulationApproach:
"""Tests for KnowledgeAccumulationApproach enum."""
@@ -57,38 +54,9 @@ class TestKnowledgeAccumulationApproach:
assert len(KnowledgeAccumulationApproach) == 4
+ def test_search_mode_enum_removed(self):
+ """SearchMode was removed along with the parallel meta engines —
+ guard against it reappearing."""
+ import local_deep_research.utilities.enums as enums
-class TestSearchMode:
- """Tests for SearchMode enum."""
-
- def test_all_value(self):
- """Test ALL enum value."""
- from local_deep_research.utilities.enums import SearchMode
-
- assert SearchMode.ALL.value == "all"
-
- def test_scientific_value(self):
- """Test SCIENTIFIC enum value."""
- from local_deep_research.utilities.enums import SearchMode
-
- assert SearchMode.SCIENTIFIC.value == "scientific"
-
- def test_all_values_exist(self):
- """Test all expected values exist in enum."""
- from local_deep_research.utilities.enums import SearchMode
-
- assert len(SearchMode) == 2
-
- def test_search_mode_from_string(self):
- """Test creating SearchMode from string value."""
- from local_deep_research.utilities.enums import SearchMode
-
- assert SearchMode("all") == SearchMode.ALL
- assert SearchMode("scientific") == SearchMode.SCIENTIFIC
-
- def test_search_mode_invalid_value_raises(self):
- """Test that invalid value raises ValueError."""
- from local_deep_research.utilities.enums import SearchMode
-
- with pytest.raises(ValueError):
- SearchMode("invalid")
+ assert not hasattr(enums, "SearchMode")
diff --git a/tests/web/routes/test_research_routes_policy.py b/tests/web/routes/test_research_routes_policy.py
index d02371a896..683e240dbb 100644
--- a/tests/web/routes/test_research_routes_policy.py
+++ b/tests/web/routes/test_research_routes_policy.py
@@ -4,9 +4,9 @@
Targets:
- _apply_policy_overrides: overlays per-research form overrides onto the
snapshot (pure dict logic).
-- _precheck_engine_policy: rejects a forbidden engine / corrupt scope /
- STRICT+meta at /api/start_research with a 400, or returns None to
- continue. Needs a Flask app context for jsonify.
+- _precheck_engine_policy: rejects a forbidden engine / corrupt scope
+ at /api/start_research with a 400, or returns None to continue.
+ Needs a Flask app context for jsonify.
"""
from unittest.mock import Mock
@@ -98,14 +98,6 @@ class TestPrecheckEnginePolicy:
assert result is not None
assert result[1] == 400
- def test_strict_meta_value_error_returns_400(self, app_ctx):
- # STRICT + meta-picker primary => ValueError => surfaced as 400
- # (regression: previously fell through to None and started the run).
- mgr = _mgr({"policy.egress_scope": "strict"}, primary="meta")
- result = _precheck_engine_policy(mgr, {}, "meta", "user")
- assert result is not None
- assert result[1] == 400
-
def test_non_dict_snapshot_returns_none(self, app_ctx):
# No real snapshot => skip precheck (factory PEP backstops).
mgr = _mgr(None)
diff --git a/tests/web/routes/test_settings_routes_corrupted_coverage.py b/tests/web/routes/test_settings_routes_corrupted_coverage.py
index f9549d2d7d..fb5f9e493d 100644
--- a/tests/web/routes/test_settings_routes_corrupted_coverage.py
+++ b/tests/web/routes/test_settings_routes_corrupted_coverage.py
@@ -131,9 +131,9 @@ class TestSaveAllSettingsCorruptedValues:
def test_bracket_open_detected_as_corrupted_for_search_tool(
self, mock_v, mock_c, mock_s
):
- """Value '[' is detected as corrupted; search.tool gets default 'auto'."""
+ """Value '[' is detected as corrupted; search.tool gets default 'searxng'."""
setting = _make_setting(
- key="search.tool", value="auto", ui_element="text", editable=True
+ key="search.tool", value="searxng", ui_element="text", editable=True
)
setting.type = "search"
@@ -154,10 +154,11 @@ class TestSaveAllSettingsCorruptedValues:
json={"search.tool": "["},
)
assert resp.status_code == 200
- # The coerced value should have been replaced with "auto"
+ # The coerced value should have been replaced with "searxng"
call_args = mock_c.call_args
assert (
- call_args[1]["value"] == "auto" or call_args[0][0] == "search.tool"
+ call_args[1]["value"] == "searxng"
+ or call_args[0][0] == "search.tool"
)
@patch(f"{MODULE}.set_setting", return_value=True)
@@ -374,7 +375,7 @@ class TestFixCorruptedSettingsDuplicatesAndDefaults:
mock_session.delete.assert_called_once_with(dupe2)
# Corrupted values should be fixed with defaults
assert corrupted_search_region.value == "us"
- assert corrupted_search_tool.value == "auto"
+ assert corrupted_search_tool.value == "searxng"
assert corrupted_app_theme.value == "dark"
assert corrupted_app_port.value == 5000
# search.questions_per_iteration (empty dict -> corrupted)
diff --git a/tests/web/routes/test_settings_routes_coverage.py b/tests/web/routes/test_settings_routes_coverage.py
index e2d2c2167d..99415e667b 100644
--- a/tests/web/routes/test_settings_routes_coverage.py
+++ b/tests/web/routes/test_settings_routes_coverage.py
@@ -826,9 +826,9 @@ class TestSaveAllSettings:
assert resp.status_code == 200
def test_corrupted_search_tool(self, authenticated_client):
- """Corrupted search.tool value gets corrected to 'auto'."""
+ """Corrupted search.tool value gets corrected to 'searxng'."""
setting = _make_setting(
- key="search.tool", value="auto", ui_element="text", editable=True
+ key="search.tool", value="searxng", ui_element="text", editable=True
)
setting.type = "search"
@@ -843,7 +843,8 @@ class TestSaveAllSettings:
)
mock_ctx.return_value.__exit__ = MagicMock(return_value=False)
with patch(
- f"{ROUTES_MODULE}.coerce_setting_for_write", return_value="auto"
+ f"{ROUTES_MODULE}.coerce_setting_for_write",
+ return_value="searxng",
):
with patch(
f"{ROUTES_MODULE}.validate_setting",
diff --git a/tests/web/routes/test_settings_routes_deep_coverage2.py b/tests/web/routes/test_settings_routes_deep_coverage2.py
index be0d389ed7..ca1e83c8ca 100644
--- a/tests/web/routes/test_settings_routes_deep_coverage2.py
+++ b/tests/web/routes/test_settings_routes_deep_coverage2.py
@@ -507,14 +507,14 @@ class TestApiGetAllSettingsWithCategory:
)
llm_setting.category = "llm_general"
search_setting = _make_setting(
- key="search.tool", value="auto", setting_type="search"
+ key="search.tool", value="searxng", setting_type="search"
)
search_setting.category = "search_general"
mock_sm = MagicMock()
mock_sm.get_all_settings.return_value = {
"llm.model": "gpt-4",
- "search.tool": "auto",
+ "search.tool": "searxng",
}
with _authenticated_client(
@@ -646,7 +646,7 @@ class TestSaveAllSettingsMultipleMessage:
)
s1.type = "llm"
s2 = _make_setting(
- key="search.tool", value="auto", ui_element="text", editable=True
+ key="search.tool", value="searxng", ui_element="text", editable=True
)
s2.type = "search"
diff --git a/tests/web/routes/test_settings_routes_save_validation_coverage.py b/tests/web/routes/test_settings_routes_save_validation_coverage.py
index 573c679321..1f037f3153 100644
--- a/tests/web/routes/test_settings_routes_save_validation_coverage.py
+++ b/tests/web/routes/test_settings_routes_save_validation_coverage.py
@@ -391,7 +391,7 @@ class TestApiGetSettingsFilteredByCategory:
)
search_setting = _make_setting(
key="search.tool",
- value="auto",
+ value="searxng",
category="search_general",
)
@@ -399,7 +399,7 @@ class TestApiGetSettingsFilteredByCategory:
# get_all_settings returns a flat dict of key→value
mock_settings_manager.get_all_settings.return_value = {
"llm.model": "gpt-4",
- "search.tool": "auto",
+ "search.tool": "searxng",
}
mock_db_session = MagicMock()
diff --git a/tests/web/test_api_coverage.py b/tests/web/test_api_coverage.py
index 8112b68ba9..d56038ded8 100644
--- a/tests/web/test_api_coverage.py
+++ b/tests/web/test_api_coverage.py
@@ -342,7 +342,7 @@ class TestQuickSummary:
def test_missing_query_returns_400(self, authed_client):
with _mock_access_control():
resp = authed_client.post(
- "/api/v1/quick_summary", json={"search_tool": "auto"}
+ "/api/v1/quick_summary", json={"search_tool": "searxng"}
)
assert resp.status_code == 400
diff --git a/tests/web_search_engines/engines/test_meta_search_coverage.py b/tests/web_search_engines/engines/test_meta_search_coverage.py
deleted file mode 100644
index c448d40acc..0000000000
--- a/tests/web_search_engines/engines/test_meta_search_coverage.py
+++ /dev/null
@@ -1,1012 +0,0 @@
-"""
-Comprehensive pytest tests for MetaSearchEngine targeting coverage gaps.
-
-Focuses on:
-- Config extraction edge cases (_get_search_config)
-- Engine filtering/selection (_get_available_engines)
-- Result merging and fallback logic (_get_previews, _get_full_content)
-- Error handling paths
-- close() method
-- analyze_query LLM invocation path (reachable when SearXNG absent + LLM truthy
- but with engines_info populated)
-- Edge cases in engine instance creation
-"""
-
-import pytest
-from unittest.mock import Mock, patch
-
-from local_deep_research.config.constants import DEFAULT_MAX_FILTERED_RESULTS
-from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
-)
-
-
-# ---------------------------------------------------------------------------
-# Helpers
-# ---------------------------------------------------------------------------
-
-
-def _bypass_init(available_engines=None, settings_snapshot=None, llm=None):
- """Create MetaSearchEngine bypassing __init__ for pure logic tests."""
- with patch.object(
- MetaSearchEngine, "__init__", lambda self, *a, **kw: None
- ):
- engine = MetaSearchEngine.__new__(MetaSearchEngine)
- engine.available_engines = available_engines or []
- engine.settings_snapshot = settings_snapshot
- engine.llm = llm
- engine.engine_cache = {}
- engine.max_results = 10
- engine.max_filtered_results = None
- engine.max_engines_to_try = 3
- engine.use_api_key_services = True
- engine.programmatic_mode = True
- engine.fallback_engine = Mock()
- return engine
-
-
-def _make_engine_with_init(
- available_engines, llm=None, settings=None, **kwargs
-):
- """Create MetaSearchEngine via __init__ but mock _get_available_engines."""
- if llm is None:
- llm = Mock()
- if settings is None:
- settings = {"search.max_results": {"value": 10}}
-
- with patch.object(
- MetaSearchEngine,
- "_get_available_engines",
- return_value=available_engines,
- ):
- engine = MetaSearchEngine(
- llm=llm,
- settings_snapshot=settings,
- programmatic_mode=True,
- **kwargs,
- )
- return engine
-
-
-# ===========================================================================
-# 1. _get_search_config edge cases
-# ===========================================================================
-
-
-class TestGetSearchConfigEdgeCases:
- """Tests for _get_search_config (now delegates to get_available_engines)."""
-
- def test_delegates_to_get_available_engines(self):
- """_get_search_config returns output of get_available_engines."""
- expected = {"brave": {"reliability": 0.9}}
- engine = _bypass_init(settings_snapshot={"search.max_results": 10})
-
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.get_available_engines",
- return_value=expected,
- ):
- config = engine._get_search_config()
- assert config == expected
-
- def test_empty_settings_snapshot_returns_empty(self):
- """Empty settings_snapshot returns empty dict."""
- engine = _bypass_init(settings_snapshot={})
- config = engine._get_search_config()
- assert config == {}
-
- def test_none_settings_snapshot_returns_empty(self):
- """None settings_snapshot returns empty dict."""
- engine = _bypass_init(settings_snapshot=None)
- config = engine._get_search_config()
- assert config == {}
-
-
-# ===========================================================================
-# 2. _get_available_engines edge cases (now via shared get_available_engines)
-# ===========================================================================
-
-
-class TestGetAvailableEnginesEdgeCases:
- """Edge cases in engine filtering via shared get_available_engines."""
-
- def test_api_key_empty_string_excluded(self):
- """Engine with requires_api_key=True and no key is excluded by shared filter."""
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- # Shared function already filters brave (no valid key)
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.get_available_engines",
- return_value={"wikipedia": {}},
- ):
- engine = MetaSearchEngine(
- llm=mock_llm,
- settings_snapshot=settings,
- programmatic_mode=True,
- )
-
- assert "brave" not in engine.available_engines
- assert "wikipedia" in engine.available_engines
-
- def test_api_key_none_excluded(self):
- """Engine with requires_api_key=True and api_key=None is excluded."""
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.get_available_engines",
- return_value={"wikipedia": {}},
- ):
- engine = MetaSearchEngine(
- llm=mock_llm,
- settings_snapshot=settings,
- programmatic_mode=True,
- )
-
- assert "brave" not in engine.available_engines
-
- def test_requires_api_key_false_included_regardless(self):
- """Engine with requires_api_key=False included even without api_key."""
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.get_available_engines",
- return_value={"brave": {"requires_api_key": False}},
- ):
- engine = MetaSearchEngine(
- llm=mock_llm,
- settings_snapshot=settings,
- programmatic_mode=True,
- )
-
- assert "brave" in engine.available_engines
-
- def test_only_meta_and_auto_raises_runtime_error(self):
- """Only meta and auto in config raises RuntimeError."""
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.get_setting_from_snapshot"
- ) as mock_gs:
- mock_gs.return_value = True
-
- with patch.object(
- MetaSearchEngine,
- "_get_search_config",
- return_value={"meta": {}, "auto": {}},
- ):
- with pytest.raises(
- RuntimeError, match="No search engines enabled"
- ):
- MetaSearchEngine(
- llm=mock_llm,
- settings_snapshot=settings,
- programmatic_mode=True,
- )
-
- def test_mixed_enabled_and_disabled_engines(self):
- """Mix of enabled and disabled engines filters correctly via shared function."""
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- # Shared function returns only enabled engines (brave, searxng)
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.get_available_engines",
- return_value={"brave": {}, "searxng": {}},
- ):
- engine = MetaSearchEngine(
- llm=mock_llm,
- settings_snapshot=settings,
- programmatic_mode=True,
- )
-
- assert "brave" in engine.available_engines
- assert "searxng" in engine.available_engines
- assert "wikipedia" not in engine.available_engines
-
-
-# ===========================================================================
-# 3. analyze_query - LLM invocation path
-# ===========================================================================
-
-
-class TestAnalyzeQueryLLMPath:
- """Test the LLM invocation path in analyze_query.
-
- Note: The LLM path is only reachable when SearXNG is available AND
- the code doesn't short-circuit on the SearXNG general path.
- Actually, looking at the code more carefully: lines 216-228 always
- return when SearXNG is available. So the LLM path (line 244+)
- is unreachable in the current code. But we test the exception
- and other edge cases.
- """
-
- def test_analyze_query_exception_with_searxng_available(self):
- """Exception in analyze_query with SearXNG available returns SearXNG first."""
- engine = _bypass_init(
- available_engines=["searxng", "brave"],
- settings_snapshot={},
- )
- # Pass None to trigger AttributeError on .lower()
- result = engine.analyze_query(None)
- assert result[0] == "searxng"
- assert "brave" in result
-
- def test_analyze_query_exception_without_searxng(self):
- """Exception in analyze_query without SearXNG returns reliability-sorted."""
- engine = _bypass_init(
- available_engines=["brave", "wikipedia"],
- )
- engine._get_search_config = Mock(
- return_value={
- "brave": {"reliability": 0.6},
- "wikipedia": {"reliability": 0.9},
- }
- )
- result = engine.analyze_query(None)
- assert result[0] == "wikipedia"
- assert result[1] == "brave"
-
- def test_specialized_domain_no_available_engines_falls_through(self):
- """Specialized domain match with none available falls through."""
- engine = _bypass_init(
- available_engines=["searxng", "brave"],
- settings_snapshot={},
- )
- # "scientific paper" maps to [arxiv, pubmed, wikipedia] - none available
- result = engine.analyze_query("scientific paper on physics")
- # Falls through to SearXNG general path
- assert result[0] == "searxng"
-
- def test_specialized_domain_partial_match(self):
- """Only some specialized engines available."""
- engine = _bypass_init(available_engines=["wikipedia", "brave"])
- result = engine.analyze_query("scientific paper on biology")
- # Only wikipedia from [arxiv, pubmed, wikipedia]
- assert result == ["wikipedia"]
-
- def test_all_specialized_domains(self):
- """All specialized domain keywords produce expected results."""
- test_cases = [
- ("scientific paper on AI", ["arxiv", "pubmed", "wikipedia"]),
- ("medical research findings", ["pubmed", "searxng"]),
- ("clinical trial data", ["pubmed", "searxng"]),
- ("github actions workflow", ["github", "searxng"]),
- ("code repository for ML", ["github", "searxng"]),
- ("repository for NLP", ["github", "searxng"]),
- ("programming language design", ["github", "searxng"]),
- ]
-
- all_engines = [
- "arxiv",
- "pubmed",
- "wikipedia",
- "github",
- "searxng",
- "brave",
- ]
- for query, expected_engines in test_cases:
- engine = _bypass_init(available_engines=list(all_engines))
- result = engine.analyze_query(query)
- assert result == expected_engines, f"Failed for query: {query}"
-
- def test_arxiv_keyword_not_in_available(self):
- """'arxiv' in query but arxiv not available falls through."""
- engine = _bypass_init(
- available_engines=["searxng", "brave"],
- settings_snapshot={},
- )
- result = engine.analyze_query("arxiv paper on attention")
- # arxiv not available, falls through to SearXNG general path
- assert result[0] == "searxng"
-
- def test_pubmed_keyword_not_in_available(self):
- """'pubmed' in query but pubmed not available falls through."""
- engine = _bypass_init(
- available_engines=["searxng", "brave"],
- settings_snapshot={},
- )
- result = engine.analyze_query("pubmed articles on genetics")
- assert result[0] == "searxng"
-
- def test_general_query_no_searxng_no_llm_reliability_sort(self):
- """General query without SearXNG or LLM uses reliability sort."""
- engine = _bypass_init(
- available_engines=["brave", "wikipedia"],
- llm=None,
- )
- engine._get_search_config = Mock(
- return_value={
- "brave": {"reliability": 0.5},
- "wikipedia": {"reliability": 0.8},
- }
- )
- result = engine.analyze_query("what is the meaning of life")
- assert result[0] == "wikipedia"
- assert result[1] == "brave"
-
- def test_general_query_searxng_present_sorts_remaining(self):
- """General query with SearXNG returns SearXNG first, rest sorted."""
- engine = _bypass_init(
- available_engines=["brave", "searxng", "wikipedia", "arxiv"],
- )
- engine._get_search_config = Mock(
- return_value={
- "brave": {"reliability": 0.5},
- "wikipedia": {"reliability": 0.8},
- "arxiv": {"reliability": 0.3},
- "searxng": {"reliability": 0.9},
- }
- )
- result = engine.analyze_query("general knowledge question")
- assert result[0] == "searxng"
- assert result[1] == "wikipedia"
- assert result[2] == "brave"
- assert result[3] == "arxiv"
-
-
-# ===========================================================================
-# 4. _get_previews edge cases
-# ===========================================================================
-
-
-class TestGetPreviewsEdgeCases:
- """Edge cases in _get_previews."""
-
- def test_empty_ranked_engines_uses_fallback(self):
- """Empty ranked engines list uses fallback."""
- engine = _bypass_init(available_engines=[])
- engine.fallback_engine._get_previews.return_value = [
- {"title": "Wiki", "url": "http://wiki.com"}
- ]
-
- with patch.object(engine, "analyze_query", return_value=[]):
- result = engine._get_previews("test query")
-
- assert len(result) == 1
- assert result[0]["title"] == "Wiki"
-
- def test_max_engines_to_try_limits_attempts(self):
- """max_engines_to_try limits the number of engines tried."""
- engine = _bypass_init(available_engines=["e1", "e2", "e3", "e4", "e5"])
- engine.max_engines_to_try = 2
-
- call_order = []
-
- def mock_get_instance(name):
- call_order.append(name)
- mock = Mock()
- mock._get_previews.return_value = [] # All return empty
- return mock
-
- engine._get_engine_instance = mock_get_instance
- engine.fallback_engine._get_previews.return_value = [
- {"title": "Fallback"}
- ]
-
- with patch.object(
- engine, "analyze_query", return_value=["e1", "e2", "e3", "e4", "e5"]
- ):
- engine._get_previews("test query")
-
- # Only 2 engines should be tried
- assert len(call_order) == 2
- assert call_order == ["e1", "e2"]
-
- def test_first_engine_succeeds_no_more_tried(self):
- """When first engine succeeds, no more engines are tried."""
- engine = _bypass_init(available_engines=["brave", "wikipedia"])
-
- call_count = []
-
- def mock_get_instance(name):
- call_count.append(name)
- mock = Mock()
- mock._get_previews.return_value = [
- {"title": f"Result from {name}", "url": f"http://{name}.com"}
- ]
- return mock
-
- engine._get_engine_instance = mock_get_instance
-
- with patch.object(
- engine, "analyze_query", return_value=["brave", "wikipedia"]
- ):
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.SocketIOService"
- ):
- result = engine._get_previews("test")
-
- assert len(call_count) == 1
- assert call_count[0] == "brave"
- assert result[0]["title"] == "Result from brave"
-
- def test_engine_returns_none_from_get_instance_skipped(self):
- """Engine that returns None from _get_engine_instance is skipped."""
- engine = _bypass_init(available_engines=["broken", "working"])
-
- mock_working = Mock()
- mock_working._get_previews.return_value = [
- {"title": "Working result", "url": "http://work.com"}
- ]
-
- def mock_get_instance(name):
- if name == "broken":
- return None
- return mock_working
-
- engine._get_engine_instance = mock_get_instance
-
- with patch.object(
- engine, "analyze_query", return_value=["broken", "working"]
- ):
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.SocketIOService"
- ):
- result = engine._get_previews("test")
-
- assert len(result) == 1
- assert result[0]["title"] == "Working result"
-
- def test_engine_raises_exception_skipped(self):
- """Engine that raises exception is skipped to next."""
- engine = _bypass_init(available_engines=["failing", "ok"])
-
- mock_failing = Mock()
- mock_failing._get_previews.side_effect = ConnectionError(
- "Network error"
- )
-
- mock_ok = Mock()
- mock_ok._get_previews.return_value = [
- {"title": "OK result", "url": "http://ok.com"}
- ]
-
- def mock_get_instance(name):
- if name == "failing":
- return mock_failing
- return mock_ok
-
- engine._get_engine_instance = mock_get_instance
-
- with patch.object(
- engine, "analyze_query", return_value=["failing", "ok"]
- ):
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.SocketIOService"
- ):
- result = engine._get_previews("test")
-
- assert len(result) == 1
- assert result[0]["title"] == "OK result"
-
- def test_all_engines_return_empty_results_uses_fallback(self):
- """All engines returning empty results uses fallback."""
- engine = _bypass_init(available_engines=["e1", "e2"])
-
- def mock_get_instance(name):
- mock = Mock()
- mock._get_previews.return_value = []
- return mock
-
- engine._get_engine_instance = mock_get_instance
- engine.fallback_engine._get_previews.return_value = [
- {"title": "Fallback result"}
- ]
-
- with patch.object(engine, "analyze_query", return_value=["e1", "e2"]):
- result = engine._get_previews("test")
-
- assert result[0]["title"] == "Fallback result"
- assert engine._selected_engine is engine.fallback_engine
- assert engine._selected_engine_name == "wikipedia"
-
- def test_successful_engine_stores_selected_engine(self):
- """Successful engine is stored as _selected_engine."""
- engine = _bypass_init(available_engines=["brave"])
-
- mock_brave = Mock()
- mock_brave._get_previews.return_value = [
- {"title": "Result", "url": "http://brave.com"}
- ]
- engine._get_engine_instance = lambda name: mock_brave
-
- with patch.object(engine, "analyze_query", return_value=["brave"]):
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.SocketIOService"
- ):
- engine._get_previews("test")
-
- assert engine._selected_engine is mock_brave
- assert engine._selected_engine_name == "brave"
-
- def test_socket_io_error_non_critical(self):
- """SocketIO emit failure does not affect results."""
- from local_deep_research.utilities.thread_context import (
- search_context,
- )
-
- engine = _bypass_init(available_engines=["brave"])
-
- mock_brave = Mock()
- mock_brave._get_previews.return_value = [
- {"title": "Result", "url": "http://test.com"}
- ]
- engine._get_engine_instance = lambda name: mock_brave
-
- with patch.object(engine, "analyze_query", return_value=["brave"]):
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.SocketIOService"
- ) as mock_sio:
- mock_sio.return_value.emit_socket_event.side_effect = (
- RuntimeError("Socket broken")
- )
- # A username in the search context is required for the emit
- # to be attempted at all (it is scoped to the user's room).
- with search_context({"username": "alice"}):
- result = engine._get_previews("test")
-
- mock_sio.return_value.emit_socket_event.assert_called_once()
- assert len(result) == 1
- assert result[0]["title"] == "Result"
-
- def test_none_previews_treated_as_empty(self):
- """Engine returning None previews is treated as no results."""
- engine = _bypass_init(available_engines=["e1"])
-
- mock_e = Mock()
- mock_e._get_previews.return_value = None
-
- engine._get_engine_instance = lambda name: mock_e
- engine.fallback_engine._get_previews.return_value = [
- {"title": "Fallback"}
- ]
-
- with patch.object(engine, "analyze_query", return_value=["e1"]):
- result = engine._get_previews("test")
-
- assert result[0]["title"] == "Fallback"
-
-
-# ===========================================================================
-# 5. _get_full_content edge cases
-# ===========================================================================
-
-
-class TestGetFullContentEdgeCases:
- """Edge cases in _get_full_content."""
-
- def test_snippets_only_mode_returns_items_unchanged(self):
- """snippets_only=True returns items as-is."""
- engine = _bypass_init(
- settings_snapshot={"search.snippets_only": {"value": True}}
- )
-
- items = [{"title": "Test", "snippet": "content"}]
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.get_setting_from_snapshot",
- return_value=True,
- ):
- result = engine._get_full_content(items)
- assert result is items
-
- def test_selected_engine_used_for_full_content(self):
- """Selected engine is used to get full content."""
- engine = _bypass_init()
- mock_selected = Mock()
- mock_selected._get_full_content.return_value = [
- {"title": "Full", "full_content": "Full text"}
- ]
- engine._selected_engine = mock_selected
- engine._selected_engine_name = "brave"
-
- items = [{"title": "Test"}]
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.get_setting_from_snapshot",
- return_value=False,
- ):
- result = engine._get_full_content(items)
-
- mock_selected._get_full_content.assert_called_once_with(items)
- assert result[0]["full_content"] == "Full text"
-
- def test_selected_engine_exception_returns_items(self):
- """Exception in selected engine returns items unchanged."""
- engine = _bypass_init()
- mock_selected = Mock()
- mock_selected._get_full_content.side_effect = RuntimeError(
- "Fetch failed"
- )
- engine._selected_engine = mock_selected
- engine._selected_engine_name = "brave"
-
- items = [{"title": "Test", "url": "http://example.com"}]
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.get_setting_from_snapshot",
- return_value=False,
- ):
- result = engine._get_full_content(items)
-
- assert result is items
-
- def test_no_selected_engine_returns_items(self):
- """No _selected_engine attribute returns items unchanged."""
- engine = _bypass_init()
- # Ensure _selected_engine is not set
- assert not hasattr(engine, "_selected_engine")
-
- items = [{"title": "Test"}]
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.get_setting_from_snapshot",
- return_value=False,
- ):
- result = engine._get_full_content(items)
-
- assert result is items
-
-
-# ===========================================================================
-# 6. _get_engine_instance edge cases
-# ===========================================================================
-
-
-class TestGetEngineInstanceEdgeCases:
- """Edge cases in _get_engine_instance."""
-
- def test_cached_engine_returned_without_creating(self):
- """Cached engine returned without calling create_search_engine."""
- engine = _bypass_init()
- mock_cached = Mock()
- engine.engine_cache["brave"] = mock_cached
-
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.create_search_engine"
- ) as mock_create:
- result = engine._get_engine_instance("brave")
-
- mock_create.assert_not_called()
- assert result is mock_cached
-
- def test_new_engine_created_and_cached(self):
- """New engine is created and added to cache."""
- engine = _bypass_init()
- mock_new = Mock()
-
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.create_search_engine",
- return_value=mock_new,
- ):
- result = engine._get_engine_instance("brave")
-
- assert result is mock_new
- assert engine.engine_cache["brave"] is mock_new
-
- def test_creation_failure_returns_none(self):
- """Engine creation failure returns None."""
- engine = _bypass_init()
-
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.create_search_engine",
- side_effect=ValueError("Bad config"),
- ):
- result = engine._get_engine_instance("bad_engine")
-
- assert result is None
- assert "bad_engine" not in engine.engine_cache
-
- def test_max_filtered_results_none_defaults_to_constant(self):
- """max_filtered_results=None is coerced to DEFAULT_MAX_FILTERED_RESULTS."""
- engine = _bypass_init()
- engine.max_filtered_results = None
- # The property setter in BaseSearchEngine converts None -> DEFAULT_MAX_FILTERED_RESULTS
- assert engine.max_filtered_results == DEFAULT_MAX_FILTERED_RESULTS
-
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.create_search_engine",
- return_value=Mock(),
- ) as mock_create:
- engine._get_engine_instance("brave")
-
- _, kwargs = mock_create.call_args
- # Always passed since the property never returns None
- assert kwargs["max_filtered_results"] == DEFAULT_MAX_FILTERED_RESULTS
-
- def test_max_filtered_results_set_is_passed(self):
- """max_filtered_results when set is passed to create_search_engine."""
- engine = _bypass_init()
- engine.max_filtered_results = 5
-
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.create_search_engine",
- return_value=Mock(),
- ) as mock_create:
- engine._get_engine_instance("brave")
-
- _, kwargs = mock_create.call_args
- assert kwargs["max_filtered_results"] == 5
-
- def test_max_filtered_results_zero_is_passed(self):
- """max_filtered_results=0 (falsy but not None) is passed."""
- engine = _bypass_init()
- engine.max_filtered_results = 0
-
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.create_search_engine",
- return_value=Mock(),
- ) as mock_create:
- engine._get_engine_instance("brave")
-
- _, kwargs = mock_create.call_args
- assert "max_filtered_results" in kwargs
- assert kwargs["max_filtered_results"] == 0
-
- def test_create_engine_returns_none_not_cached(self):
- """If create_search_engine returns None, it's not cached."""
- engine = _bypass_init()
-
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.create_search_engine",
- return_value=None,
- ):
- result = engine._get_engine_instance("brave")
-
- assert result is None
- assert "brave" not in engine.engine_cache
-
-
-# ===========================================================================
-# 7. close() method
-# ===========================================================================
-
-
-class TestClose:
- """Tests for close() method."""
-
- def test_close_closes_cached_engines(self):
- """close() calls close() on all cached engines."""
- engine = _bypass_init()
- mock_e1 = Mock()
- mock_e2 = Mock()
- engine.engine_cache = {"e1": mock_e1, "e2": mock_e2}
-
- with patch.object(
- type(engine).__bases__[0], "close", return_value=None
- ):
- engine.close()
-
- mock_e1.close.assert_called_once()
- mock_e2.close.assert_called_once()
-
- def test_close_clears_cache(self):
- """close() clears the engine cache."""
- engine = _bypass_init()
- engine.engine_cache = {"e1": Mock(), "e2": Mock()}
-
- with patch.object(
- type(engine).__bases__[0], "close", return_value=None
- ):
- engine.close()
-
- assert engine.engine_cache == {}
-
- def test_close_closes_fallback_engine(self):
- """close() closes the fallback engine."""
- engine = _bypass_init()
- mock_fallback = Mock()
- engine.fallback_engine = mock_fallback
-
- with patch.object(
- type(engine).__bases__[0], "close", return_value=None
- ):
- engine.close()
-
- mock_fallback.close.assert_called_once()
-
- def test_close_handles_cached_engine_close_exception(self):
- """close() handles exception from cached engine close()."""
- engine = _bypass_init()
- mock_e1 = Mock()
- mock_e1.close.side_effect = RuntimeError("Close failed")
- mock_e2 = Mock()
- engine.engine_cache = {"e1": mock_e1, "e2": mock_e2}
-
- with patch.object(
- type(engine).__bases__[0], "close", return_value=None
- ):
- # Should not raise
- engine.close()
-
- # e2.close should still be called despite e1 raising
- mock_e2.close.assert_called_once()
-
- def test_close_handles_fallback_close_exception(self):
- """close() handles exception from fallback engine close()."""
- engine = _bypass_init()
- mock_fallback = Mock()
- mock_fallback.close.side_effect = RuntimeError("Fallback close failed")
- engine.fallback_engine = mock_fallback
-
- with patch.object(
- type(engine).__bases__[0], "close", return_value=None
- ):
- # Should not raise
- engine.close()
-
- def test_close_with_no_fallback_engine(self):
- """close() handles missing fallback_engine gracefully."""
- engine = _bypass_init()
- engine.fallback_engine = None
-
- with patch.object(
- type(engine).__bases__[0], "close", return_value=None
- ):
- # Should not raise
- engine.close()
-
- def test_close_with_empty_cache(self):
- """close() works with empty cache."""
- engine = _bypass_init()
- engine.engine_cache = {}
-
- with patch.object(
- type(engine).__bases__[0], "close", return_value=None
- ):
- engine.close()
-
- assert engine.engine_cache == {}
-
- def test_close_calls_super_close(self):
- """close() calls super().close()."""
- engine = _bypass_init()
- engine.engine_cache = {}
-
- with patch.object(
- type(engine).__bases__[0], "close", return_value=None
- ) as mock_super_close:
- engine.close()
-
- mock_super_close.assert_called_once()
-
-
-# ===========================================================================
-# 8. invoke() method
-# ===========================================================================
-
-
-class TestInvoke:
- """Tests for invoke() method."""
-
- def test_invoke_delegates_to_run(self):
- """invoke() calls self.run() with the query."""
- engine = _bypass_init()
-
- with patch.object(
- engine, "run", return_value=[{"title": "Result"}]
- ) as mock_run:
- result = engine.invoke("test query")
-
- mock_run.assert_called_once_with("test query")
- assert result == [{"title": "Result"}]
-
- def test_invoke_propagates_run_exception(self):
- """invoke() propagates exceptions from run()."""
- engine = _bypass_init()
-
- with patch.object(
- engine, "run", side_effect=RuntimeError("Search failed")
- ):
- with pytest.raises(RuntimeError, match="Search failed"):
- engine.invoke("test query")
-
-
-# ===========================================================================
-# 9. Integration-style tests (using __init__ with mocks)
-# ===========================================================================
-
-
-class TestInitIntegration:
- """Integration tests using actual __init__."""
-
- def test_init_stores_settings_snapshot(self):
- """__init__ stores settings_snapshot."""
- settings = {"search.max_results": {"value": 10}}
- engine = _make_engine_with_init(["wikipedia"], settings=settings)
- assert engine.settings_snapshot is settings
-
- def test_init_default_use_api_key_services(self):
- """Default use_api_key_services is True."""
- engine = _make_engine_with_init(["wikipedia"])
- assert engine.use_api_key_services is True
-
- def test_init_custom_use_api_key_services(self):
- """Custom use_api_key_services is respected."""
- engine = _make_engine_with_init(
- ["wikipedia"], use_api_key_services=False
- )
- assert engine.use_api_key_services is False
-
- def test_init_default_max_engines_to_try(self):
- """Default max_engines_to_try is 3."""
- engine = _make_engine_with_init(["wikipedia"])
- assert engine.max_engines_to_try == 3
-
- def test_init_custom_max_engines_to_try(self):
- """Custom max_engines_to_try is stored."""
- engine = _make_engine_with_init(["wikipedia"], max_engines_to_try=7)
- assert engine.max_engines_to_try == 7
-
- def test_init_creates_empty_engine_cache(self):
- """__init__ creates empty engine cache."""
- engine = _make_engine_with_init(["wikipedia"])
- assert engine.engine_cache == {}
-
- def test_init_accepts_extra_kwargs(self):
- """__init__ accepts and ignores extra kwargs."""
- # Should not raise
- engine = _make_engine_with_init(
- ["wikipedia"],
- extra_param="ignored",
- another_param=42,
- )
- assert engine is not None
-
- def test_init_with_max_filtered_results(self):
- """__init__ stores max_filtered_results."""
- engine = _make_engine_with_init(["wikipedia"], max_filtered_results=15)
- assert engine.max_filtered_results == 15
-
- def test_init_with_max_filtered_results_default(self):
- """__init__ defaults max_filtered_results to DEFAULT_MAX_FILTERED_RESULTS."""
- engine = _make_engine_with_init(["wikipedia"])
- assert engine.max_filtered_results == DEFAULT_MAX_FILTERED_RESULTS
-
-
-# ===========================================================================
-# 10. Analyze query with empty available_engines
-# ===========================================================================
-
-
-class TestAnalyzeQueryEmptyEngines:
- """Test analyze_query behavior with edge case engine configurations."""
-
- def test_empty_available_engines_returns_empty_list(self):
- """analyze_query with empty available_engines returns empty list."""
- engine = _bypass_init(available_engines=[], llm=None)
- result = engine.analyze_query("anything")
- assert result == []
-
- def test_single_engine_available_returned(self):
- """Single available engine is returned regardless of query."""
- engine = _bypass_init(available_engines=["brave"])
- result = engine.analyze_query("general question")
- # No SearXNG, no LLM -> reliability sort with single engine
- assert result == ["brave"]
-
- def test_arxiv_keyword_with_only_arxiv_available(self):
- """'arxiv' keyword with only arxiv available returns just arxiv."""
- engine = _bypass_init(available_engines=["arxiv"])
- result = engine.analyze_query("arxiv paper on NLP")
- assert result == ["arxiv"]
-
- def test_pubmed_keyword_with_only_pubmed_available(self):
- """'pubmed' keyword with only pubmed available returns just pubmed."""
- engine = _bypass_init(available_engines=["pubmed"])
- result = engine.analyze_query("pubmed article on COVID")
- assert result == ["pubmed"]
-
- def test_case_insensitive_specialized_detection(self):
- """Specialized domain detection is case-insensitive."""
- engine = _bypass_init(available_engines=["github", "searxng"])
- result = engine.analyze_query("GITHUB Repository for Deep Learning")
- assert "github" in result
-
- def test_specialized_before_explicit_keyword(self):
- """Specialized domain match takes priority over explicit keyword match."""
- engine = _bypass_init(
- available_engines=["arxiv", "pubmed", "wikipedia", "searxng"]
- )
- # "scientific paper" matches specialized domain before "arxiv" keyword check
- result = engine.analyze_query("scientific paper on arxiv about AI")
- assert result == ["arxiv", "pubmed", "wikipedia"]
diff --git a/tests/web_search_engines/engines/test_meta_search_deep_coverage.py b/tests/web_search_engines/engines/test_meta_search_deep_coverage.py
deleted file mode 100644
index cd2de28889..0000000000
--- a/tests/web_search_engines/engines/test_meta_search_deep_coverage.py
+++ /dev/null
@@ -1,476 +0,0 @@
-"""
-Deep coverage tests for MetaSearchEngine targeting remaining uncovered statements.
-
-Focuses on:
-- analyze_query LLM invocation path (no SearXNG, LLM present, engines_info populated)
-- LLM response parsing (.content attribute vs plain string)
-- SearXNG fallback injection when LLM omits it
-- empty engines_info branch (no matching engines in config)
-- use_api_key_services=False filtering path
-- _get_available_engines with all engines needing API keys disabled
-- _get_engine_instance with max_filtered_results=None (not passed)
-- analyze_query exception path when SearXNG absent
-- all-engines-fail then fallback in _get_previews with error accumulation
-"""
-
-from unittest.mock import Mock, patch
-
-from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
-)
-
-MODULE = "local_deep_research.web_search_engines.engines.meta_search_engine"
-
-# ---------------------------------------------------------------------------
-# Helpers
-# ---------------------------------------------------------------------------
-
-
-def _bypass_init(available_engines=None, settings_snapshot=None, llm=None):
- """Create MetaSearchEngine bypassing __init__ for pure logic tests."""
- with patch.object(
- MetaSearchEngine, "__init__", lambda self, *a, **kw: None
- ):
- engine = MetaSearchEngine.__new__(MetaSearchEngine)
- engine.available_engines = (
- available_engines if available_engines is not None else []
- )
- engine.settings_snapshot = settings_snapshot
- engine.llm = llm
- engine.engine_cache = {}
- engine.max_results = 10
- engine.max_filtered_results = None
- engine.max_engines_to_try = 3
- engine.use_api_key_services = True
- engine.programmatic_mode = True
- engine.fallback_engine = Mock()
- return engine
-
-
-# ===========================================================================
-# 1. analyze_query - LLM invocation path (no SearXNG, LLM present)
-# ===========================================================================
-
-
-class TestAnalyzeQueryNoSearxngPath:
- """
- Tests for the analyze_query path when SearXNG is absent.
-
- Note: Lines 244-335 (LLM invocation) are structurally dead code in the
- current implementation — when SearXNG is absent line 231 always returns.
- These tests cover the reliability-sort path (lines 231-242) and the
- exception handler (lines 337-355) which are reached in practice.
- """
-
- def _make_engine_with_config(self, available_engines, config, llm=None):
- engine = _bypass_init(
- available_engines=available_engines,
- settings_snapshot={},
- llm=llm or Mock(),
- )
- engine._get_search_config = Mock(return_value=config)
- return engine
-
- def test_no_searxng_llm_present_uses_reliability_sort(self):
- """No SearXNG + LLM present still uses reliability-based sort (line 231 branch)."""
- config = {
- "brave": {"reliability": 0.6},
- "wikipedia": {"reliability": 0.9},
- }
- mock_llm = Mock()
- engine = self._make_engine_with_config(
- available_engines=["brave", "wikipedia"],
- config=config,
- llm=mock_llm,
- )
-
- result = engine.analyze_query("general question about technology")
-
- # Line 231 fires (searxng not available), returns reliability sort
- mock_llm.invoke.assert_not_called()
- assert result[0] == "wikipedia"
- assert result[1] == "brave"
-
- def test_no_searxng_no_llm_uses_reliability_sort(self):
- """No SearXNG, no LLM: reliability sort is used."""
- config = {
- "brave": {"reliability": 0.5},
- "arxiv": {"reliability": 0.85},
- }
- engine = self._make_engine_with_config(
- available_engines=["brave", "arxiv"],
- config=config,
- llm=None,
- )
-
- result = engine.analyze_query("what is machine learning")
- assert result[0] == "arxiv"
- assert result[1] == "brave"
-
- def test_reliability_missing_defaults_to_zero(self):
- """Engines with no reliability in config default to 0 for sorting."""
- config = {
- "brave": {}, # no reliability key
- "wikipedia": {"reliability": 0.5},
- }
- engine = self._make_engine_with_config(
- available_engines=["brave", "wikipedia"],
- config=config,
- llm=None,
- )
-
- result = engine.analyze_query("some query without domain")
- assert result[0] == "wikipedia"
- assert result[1] == "brave"
-
- def test_searxng_present_sorts_remaining_by_reliability(self):
- """SearXNG available: searxng first, others sorted by reliability."""
- config = {
- "searxng": {"reliability": 1.0},
- "brave": {"reliability": 0.4},
- "wikipedia": {"reliability": 0.8},
- }
- engine = self._make_engine_with_config(
- available_engines=["brave", "searxng", "wikipedia"],
- config=config,
- )
-
- result = engine.analyze_query("general tech question")
- assert result[0] == "searxng"
- assert result[1] == "wikipedia"
- assert result[2] == "brave"
-
- def test_engines_info_config_keys_irrelevant_to_no_searxng_path(self):
- """Config has entries but no SearXNG still triggers reliability sort (not LLM)."""
- mock_llm = Mock()
- config = {
- "brave": {
- "description": "Brave",
- "strengths": "speed",
- "weaknesses": "none",
- "reliability": 0.5,
- },
- "wikipedia": {
- "description": "Wikipedia",
- "strengths": "accuracy",
- "weaknesses": "none",
- "reliability": 0.9,
- },
- }
- engine = self._make_engine_with_config(
- available_engines=["brave", "wikipedia"],
- config=config,
- llm=mock_llm,
- )
-
- result = engine.analyze_query("what is artificial intelligence")
- # No searxng -> line 231 branch, reliability sort, LLM never called
- assert set(result) == {"brave", "wikipedia"}
- mock_llm.invoke.assert_not_called()
-
- def test_searxng_first_with_no_config_for_others(self):
- """SearXNG + engines with no config entry still returns searxng first."""
- # Config has no entries for brave/arxiv
- engine = self._make_engine_with_config(
- available_engines=["brave", "searxng", "arxiv"],
- config={"searxng": {"reliability": 0.9}},
- )
-
- result = engine.analyze_query("general question")
- assert result[0] == "searxng"
- assert set(result) == {"brave", "searxng", "arxiv"}
-
- def test_query_exception_no_searxng_reliability_sort(self):
- """analyze_query exception without SearXNG returns reliability-ordered."""
- config = {
- "brave": {"reliability": 0.5},
- "wikipedia": {"reliability": 0.9},
- }
- mock_llm = Mock()
- engine = _bypass_init(
- available_engines=["brave", "wikipedia"],
- settings_snapshot={},
- llm=mock_llm,
- )
- engine._get_search_config = Mock(return_value=config)
-
- # Pass None to trigger exception in query.lower()
- result = engine.analyze_query(None)
- assert result[0] == "wikipedia"
- assert result[1] == "brave"
-
- def test_query_exception_with_searxng_reliability_sort_rest(self):
- """analyze_query exception with SearXNG returns searxng first, rest by reliability."""
- config = {
- "searxng": {"reliability": 1.0},
- "brave": {"reliability": 0.3},
- "wikipedia": {"reliability": 0.8},
- }
- mock_llm = Mock()
- engine = _bypass_init(
- available_engines=["searxng", "brave", "wikipedia"],
- settings_snapshot={},
- llm=mock_llm,
- )
- engine._get_search_config = Mock(return_value=config)
-
- result = engine.analyze_query(None)
- assert result[0] == "searxng"
- assert result[1] == "wikipedia"
- assert result[2] == "brave"
-
-
-# ===========================================================================
-# 2. _get_available_engines - use_api_key_services=False path
-# ===========================================================================
-
-
-class TestGetAvailableEnginesApiKeyServices:
- """Test the use_api_key_services flag via the shared get_available_engines."""
-
- def test_api_key_service_disabled_excludes_requiring_key(self):
- """use_api_key_services=False excludes engines requiring an API key."""
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- # Simulate get_available_engines returning only wikipedia when
- # use_api_key_services=False (brave filtered out by shared fn)
- with patch(
- f"{MODULE}.get_available_engines",
- return_value={"wikipedia": {}},
- ):
- engine = MetaSearchEngine(
- llm=mock_llm,
- settings_snapshot=settings,
- use_api_key_services=False,
- programmatic_mode=True,
- )
-
- assert "brave" not in engine.available_engines
- assert "wikipedia" in engine.available_engines
-
- def test_api_key_service_enabled_includes_valid_key_engine(self):
- """use_api_key_services=True includes engines with valid API keys."""
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- with patch(
- f"{MODULE}.get_available_engines",
- return_value={
- "brave": {
- "requires_api_key": True,
- "api_key": "valid_key_123",
- },
- "wikipedia": {},
- },
- ):
- engine = MetaSearchEngine(
- llm=mock_llm,
- settings_snapshot=settings,
- use_api_key_services=True,
- programmatic_mode=True,
- )
-
- assert "brave" in engine.available_engines
- assert "wikipedia" in engine.available_engines
-
-
-# ===========================================================================
-# 3. _get_engine_instance - max_filtered_results=None not passed
-# ===========================================================================
-
-
-class TestGetEngineInstanceMaxFilteredResults:
- """Test max_filtered_results handling in _get_engine_instance."""
-
- def test_max_filtered_results_value_passed_to_create(self):
- """max_filtered_results value is forwarded to create_search_engine."""
- engine = _bypass_init()
- engine.max_filtered_results = 7
-
- mock_created = Mock()
- with patch(
- f"{MODULE}.create_search_engine", return_value=mock_created
- ) as mock_create:
- result = engine._get_engine_instance("wikipedia")
-
- _, kwargs = mock_create.call_args
- assert kwargs["max_filtered_results"] == 7
- assert result is mock_created
-
- def test_programmatic_mode_forwarded_to_create(self):
- """programmatic_mode is forwarded to create_search_engine."""
- engine = _bypass_init()
- engine.max_filtered_results = 5
-
- mock_created = Mock()
- with patch(
- f"{MODULE}.create_search_engine", return_value=mock_created
- ) as mock_create:
- engine._get_engine_instance("brave")
-
- _, kwargs = mock_create.call_args
- assert kwargs["programmatic_mode"] is True
-
- def test_settings_snapshot_forwarded_to_create(self):
- """settings_snapshot is forwarded to create_search_engine."""
- snapshot = {"key": "value"}
- engine = _bypass_init(settings_snapshot=snapshot)
- engine.max_filtered_results = 5
-
- mock_created = Mock()
- with patch(
- f"{MODULE}.create_search_engine", return_value=mock_created
- ) as mock_create:
- engine._get_engine_instance("brave")
-
- _, kwargs = mock_create.call_args
- assert kwargs["settings_snapshot"] is snapshot
-
-
-# ===========================================================================
-# 4. _get_previews - all engines fail with accumulated errors
-# ===========================================================================
-
-
-class TestGetPreviewsAllEnginesFail:
- """Test the path where all engines fail and errors accumulate."""
-
- def test_all_engines_raise_exception_fallback_used(self):
- """When every engine raises, fallback is used and errors are accumulated."""
- engine = _bypass_init(available_engines=["e1", "e2", "e3"])
- engine.max_engines_to_try = 3
-
- call_log = []
-
- def mock_get_instance(name):
- call_log.append(name)
- mock = Mock()
- mock._get_previews.side_effect = TimeoutError(f"{name} timed out")
- return mock
-
- engine._get_engine_instance = mock_get_instance
- engine.fallback_engine._get_previews.return_value = [
- {"title": "Fallback Wikipedia", "url": "http://wiki.org"}
- ]
-
- with patch.object(
- engine, "analyze_query", return_value=["e1", "e2", "e3"]
- ):
- result = engine._get_previews("test query")
-
- # All 3 should have been tried
- assert call_log == ["e1", "e2", "e3"]
- # Fallback result returned
- assert result[0]["title"] == "Fallback Wikipedia"
- # Fallback engine is stored
- assert engine._selected_engine is engine.fallback_engine
- assert engine._selected_engine_name == "wikipedia"
-
- def test_mix_of_none_instance_and_exception_and_empty(self):
- """Mix of None instance, exception, and empty results all fall through to fallback."""
- engine = _bypass_init(
- available_engines=["none_engine", "exc_engine", "empty_engine"]
- )
- engine.max_engines_to_try = 3
-
- mock_exc = Mock()
- mock_exc._get_previews.side_effect = ValueError("bad config")
- mock_empty = Mock()
- mock_empty._get_previews.return_value = []
-
- def mock_get_instance(name):
- if name == "none_engine":
- return None
- if name == "exc_engine":
- return mock_exc
- return mock_empty
-
- engine._get_engine_instance = mock_get_instance
- engine.fallback_engine._get_previews.return_value = [
- {"title": "Wiki fallback"}
- ]
-
- with patch.object(
- engine,
- "analyze_query",
- return_value=["none_engine", "exc_engine", "empty_engine"],
- ):
- result = engine._get_previews("some query")
-
- assert result[0]["title"] == "Wiki fallback"
-
-
-# ===========================================================================
-# 5. _get_search_config with dict values containing nested dict
-# ===========================================================================
-
-
-class TestGetSearchConfigValueExtraction:
- """Test _get_search_config delegates to get_available_engines."""
-
- def test_delegates_to_shared_function(self):
- """_get_search_config returns whatever get_available_engines returns."""
- expected = {"brave": {"api_key": "mykey", "reliability": 0.85}}
- engine = _bypass_init(settings_snapshot={"search.max_results": 10})
-
- with patch(
- f"{MODULE}.get_available_engines",
- return_value=expected,
- ):
- config = engine._get_search_config()
-
- assert config == expected
-
- def test_returns_empty_without_snapshot(self):
- """Returns empty dict when settings_snapshot is empty/falsy."""
- engine = _bypass_init(settings_snapshot={})
- config = engine._get_search_config()
- assert config == {}
-
-
-# ===========================================================================
-# 6. analyze_query - searxng in exception handler with no searxng available
-# ===========================================================================
-
-
-class TestAnalyzeQueryExceptionHandlerPaths:
- """Test both branches of the exception handler in analyze_query."""
-
- def test_exception_with_searxng_available_sorts_rest_by_reliability(self):
- """Exception + SearXNG available: searxng first, rest sorted by reliability."""
- engine = _bypass_init(
- available_engines=["searxng", "brave", "wikipedia"],
- )
- engine._get_search_config = Mock(
- return_value={
- "brave": {"reliability": 0.3},
- "wikipedia": {"reliability": 0.8},
- "searxng": {"reliability": 0.5},
- }
- )
- # Pass None to trigger AttributeError on .lower()
- result = engine.analyze_query(None)
-
- assert result[0] == "searxng"
- # wikipedia has higher reliability
- assert result[1] == "wikipedia"
- assert result[2] == "brave"
-
- def test_exception_without_searxng_returns_reliability_ordered(self):
- """Exception + no SearXNG: returns all engines sorted by reliability."""
- engine = _bypass_init(
- available_engines=["brave", "arxiv", "pubmed"],
- )
- engine._get_search_config = Mock(
- return_value={
- "brave": {"reliability": 0.4},
- "arxiv": {"reliability": 0.9},
- "pubmed": {"reliability": 0.7},
- }
- )
- result = engine.analyze_query(None)
-
- assert result[0] == "arxiv"
- assert result[1] == "pubmed"
- assert result[2] == "brave"
diff --git a/tests/web_search_engines/engines/test_meta_search_engine.py b/tests/web_search_engines/engines/test_meta_search_engine.py
deleted file mode 100644
index a91c80ab46..0000000000
--- a/tests/web_search_engines/engines/test_meta_search_engine.py
+++ /dev/null
@@ -1,774 +0,0 @@
-"""
-Tests for the MetaSearchEngine class.
-
-Tests cover:
-- Initialization and configuration
-- Query analysis and engine selection
-- Preview retrieval with fallback
-- Full content retrieval
-- Engine caching
-"""
-
-from unittest.mock import Mock, patch
-
-
-class TestMetaSearchEngineInit:
- """Tests for MetaSearchEngine initialization."""
-
- def test_init_with_required_params(self):
- """Initialize with required parameters."""
- 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
- )
-
- assert engine.llm is mock_llm
- assert engine.max_results == 10
- assert engine.programmatic_mode is True
-
- def test_init_with_custom_max_results(self):
- """Initialize with custom max_results."""
- 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,
- max_results=25,
- settings_snapshot=settings,
- programmatic_mode=True,
- )
-
- assert engine.max_results == 25
-
- def test_init_with_max_engines_to_try(self):
- """Initialize with custom max_engines_to_try."""
- 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,
- max_engines_to_try=5,
- settings_snapshot=settings,
- programmatic_mode=True,
- )
-
- assert engine.max_engines_to_try == 5
-
- def test_init_creates_engine_cache(self):
- """Initialize creates empty engine cache."""
- 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
- )
-
- assert engine.engine_cache == {}
-
- def test_init_creates_fallback_engine(self):
- """Initialize creates Wikipedia fallback engine."""
- 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
- )
-
- assert engine.fallback_engine is not None
-
-
-class TestMetaSearchEngineQueryAnalysis:
- """Tests for MetaSearchEngine query analysis."""
-
- def test_analyze_query_scientific_paper(self):
- """Analyze query detects scientific paper queries."""
- from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
- )
-
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- with patch.object(
- MetaSearchEngine,
- "_get_available_engines",
- return_value=["arxiv", "pubmed", "wikipedia"],
- ):
- engine = MetaSearchEngine(
- llm=mock_llm, settings_snapshot=settings, programmatic_mode=True
- )
-
- result = engine.analyze_query(
- "scientific paper about quantum computing"
- )
-
- assert "arxiv" in result or "pubmed" in result
-
- def test_analyze_query_github_code(self):
- """Analyze query detects code queries."""
- from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
- )
-
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- with patch.object(
- MetaSearchEngine,
- "_get_available_engines",
- return_value=["github", "searxng"],
- ):
- engine = MetaSearchEngine(
- llm=mock_llm, settings_snapshot=settings, programmatic_mode=True
- )
-
- result = engine.analyze_query("code for sorting algorithms")
-
- assert "github" in result
-
- def test_analyze_query_medical_research(self):
- """Analyze query detects medical queries."""
- from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
- )
-
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- with patch.object(
- MetaSearchEngine,
- "_get_available_engines",
- return_value=["pubmed", "searxng"],
- ):
- engine = MetaSearchEngine(
- llm=mock_llm, settings_snapshot=settings, programmatic_mode=True
- )
-
- result = engine.analyze_query("clinical trial results for diabetes")
-
- assert "pubmed" in result
-
- def test_analyze_query_prioritizes_searxng_for_general(self):
- """Analyze query prioritizes SearXNG for general queries."""
- from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
- )
-
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- with patch.object(
- MetaSearchEngine,
- "_get_available_engines",
- return_value=["searxng", "wikipedia", "brave"],
- ):
- engine = MetaSearchEngine(
- llm=mock_llm, settings_snapshot=settings, programmatic_mode=True
- )
-
- result = engine.analyze_query("best restaurants in Paris")
-
- assert result[0] == "searxng"
-
- def test_analyze_query_arxiv_keyword(self):
- """Analyze query detects arxiv keyword."""
- from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
- )
-
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- with patch.object(
- MetaSearchEngine,
- "_get_available_engines",
- return_value=["arxiv", "wikipedia"],
- ):
- engine = MetaSearchEngine(
- llm=mock_llm, settings_snapshot=settings, programmatic_mode=True
- )
-
- result = engine.analyze_query(
- "find arxiv paper on machine learning"
- )
-
- assert result[0] == "arxiv"
-
- def test_analyze_query_pubmed_keyword(self):
- """Analyze query detects pubmed keyword."""
- from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
- )
-
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- with patch.object(
- MetaSearchEngine,
- "_get_available_engines",
- return_value=["pubmed", "wikipedia"],
- ):
- engine = MetaSearchEngine(
- llm=mock_llm, settings_snapshot=settings, programmatic_mode=True
- )
-
- result = engine.analyze_query("search pubmed for cancer research")
-
- assert result[0] == "pubmed"
-
-
-class TestMetaSearchEngineGetPreviews:
- """Tests for MetaSearchEngine _get_previews method."""
-
- def test_get_previews_returns_results(self):
- """_get_previews returns results from successful engine."""
- from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
- )
-
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- mock_engine = Mock()
- mock_engine._get_previews.return_value = [
- {"title": "Result 1", "url": "http://a.com", "snippet": "Snippet 1"}
- ]
-
- with patch.object(
- MetaSearchEngine,
- "_get_available_engines",
- return_value=["wikipedia"],
- ):
- with patch.object(
- MetaSearchEngine,
- "_get_engine_instance",
- return_value=mock_engine,
- ):
- engine = MetaSearchEngine(
- llm=mock_llm,
- settings_snapshot=settings,
- programmatic_mode=True,
- )
-
- results = engine._get_previews("test query")
-
- assert len(results) == 1
- assert results[0]["title"] == "Result 1"
-
- def test_get_previews_falls_back_on_empty_results(self):
- """_get_previews falls back to Wikipedia on empty results."""
- from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
- )
-
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- mock_engine = Mock()
- mock_engine._get_previews.return_value = []
-
- with patch.object(
- MetaSearchEngine, "_get_available_engines", return_value=["brave"]
- ):
- with patch.object(
- MetaSearchEngine,
- "_get_engine_instance",
- return_value=mock_engine,
- ):
- engine = MetaSearchEngine(
- llm=mock_llm,
- settings_snapshot=settings,
- programmatic_mode=True,
- )
-
- # Mock fallback engine
- engine.fallback_engine = Mock()
- engine.fallback_engine._get_previews.return_value = [
- {"title": "Wikipedia Result", "url": "http://wiki.com"}
- ]
-
- results = engine._get_previews("test query")
-
- assert len(results) == 1
- assert results[0]["title"] == "Wikipedia Result"
-
- def test_get_previews_falls_back_on_exception(self):
- """_get_previews falls back to Wikipedia on exception."""
- from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
- )
-
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- mock_engine = Mock()
- mock_engine._get_previews.side_effect = Exception("Search failed")
-
- with patch.object(
- MetaSearchEngine, "_get_available_engines", return_value=["brave"]
- ):
- with patch.object(
- MetaSearchEngine,
- "_get_engine_instance",
- return_value=mock_engine,
- ):
- engine = MetaSearchEngine(
- llm=mock_llm,
- settings_snapshot=settings,
- programmatic_mode=True,
- )
-
- # Mock fallback engine
- engine.fallback_engine = Mock()
- engine.fallback_engine._get_previews.return_value = [
- {"title": "Wikipedia Fallback", "url": "http://wiki.com"}
- ]
-
- results = engine._get_previews("test query")
-
- assert len(results) == 1
- assert results[0]["title"] == "Wikipedia Fallback"
-
- def test_get_previews_tries_multiple_engines(self):
- """_get_previews tries multiple engines before fallback."""
- from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
- )
-
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- call_count = [0]
-
- def engine_factory(name):
- call_count[0] += 1
- mock = Mock()
- if call_count[0] < 3:
- mock._get_previews.return_value = []
- else:
- mock._get_previews.return_value = [
- {"title": "Result from engine 3", "url": "http://c.com"}
- ]
- return mock
-
- with patch.object(
- MetaSearchEngine,
- "_get_available_engines",
- return_value=["engine1", "engine2", "engine3"],
- ):
- with patch.object(
- MetaSearchEngine,
- "_get_engine_instance",
- side_effect=engine_factory,
- ):
- engine = MetaSearchEngine(
- llm=mock_llm,
- max_engines_to_try=3,
- settings_snapshot=settings,
- programmatic_mode=True,
- )
-
- results = engine._get_previews("test query")
-
- assert call_count[0] == 3
- assert len(results) == 1
-
-
-class TestMetaSearchEngineGetFullContent:
- """Tests for MetaSearchEngine _get_full_content method."""
-
- def test_get_full_content_uses_selected_engine(self):
- """_get_full_content uses the engine that provided previews."""
- from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
- )
-
- mock_llm = Mock()
- settings = {
- "search.max_results": {"value": 10},
- "search.snippets_only": {"value": False},
- }
-
- with patch.object(
- MetaSearchEngine,
- "_get_available_engines",
- return_value=["wikipedia"],
- ):
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.get_setting_from_snapshot",
- return_value=False, # Not snippets_only mode
- ):
- engine = MetaSearchEngine(
- llm=mock_llm,
- settings_snapshot=settings,
- programmatic_mode=True,
- )
-
- # Simulate having selected an engine during previews
- mock_selected = Mock()
- mock_selected._get_full_content.return_value = [
- {"title": "Result", "full_content": "Full text here"}
- ]
- engine._selected_engine = mock_selected
- engine._selected_engine_name = "brave"
-
- items = [{"title": "Result", "url": "http://a.com"}]
- results = engine._get_full_content(items)
-
- mock_selected._get_full_content.assert_called_once_with(items)
- assert results[0]["full_content"] == "Full text here"
-
- def test_get_full_content_returns_items_when_snippets_only(self):
- """_get_full_content returns items as-is when snippets_only is True."""
- from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
- )
-
- mock_llm = Mock()
- settings = {
- "search.max_results": {"value": 10},
- "search.snippets_only": {"value": True},
- }
-
- with patch.object(
- MetaSearchEngine,
- "_get_available_engines",
- return_value=["wikipedia"],
- ):
- engine = MetaSearchEngine(
- llm=mock_llm, settings_snapshot=settings, programmatic_mode=True
- )
-
- items = [
- {"title": "Result", "url": "http://a.com", "snippet": "Snippet"}
- ]
- results = engine._get_full_content(items)
-
- assert results == items
-
- def test_get_full_content_returns_items_when_no_selected_engine(self):
- """_get_full_content returns items when no engine was selected."""
- from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
- )
-
- mock_llm = Mock()
- settings = {
- "search.max_results": {"value": 10},
- "search.snippets_only": {"value": False},
- }
-
- with patch.object(
- MetaSearchEngine,
- "_get_available_engines",
- return_value=["wikipedia"],
- ):
- engine = MetaSearchEngine(
- llm=mock_llm, settings_snapshot=settings, programmatic_mode=True
- )
-
- # Don't set _selected_engine
- items = [{"title": "Result", "url": "http://a.com"}]
- results = engine._get_full_content(items)
-
- assert results == items
-
-
-class TestMetaSearchEngineEngineCaching:
- """Tests for MetaSearchEngine engine caching."""
-
- def test_get_engine_instance_creates_new_engine(self):
- """_get_engine_instance creates new engine when not cached."""
- from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
- )
-
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- mock_created_engine = Mock()
-
- with patch.object(
- MetaSearchEngine,
- "_get_available_engines",
- return_value=["wikipedia"],
- ):
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.create_search_engine",
- return_value=mock_created_engine,
- ) as mock_create:
- engine = MetaSearchEngine(
- llm=mock_llm,
- settings_snapshot=settings,
- programmatic_mode=True,
- )
-
- result = engine._get_engine_instance("brave")
-
- mock_create.assert_called_once()
- assert result is mock_created_engine
-
- def test_get_engine_instance_returns_cached(self):
- """_get_engine_instance returns cached engine."""
- from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
- )
-
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- cached_engine = Mock()
-
- with patch.object(
- MetaSearchEngine,
- "_get_available_engines",
- return_value=["wikipedia"],
- ):
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.create_search_engine"
- ) as mock_create:
- engine = MetaSearchEngine(
- llm=mock_llm,
- settings_snapshot=settings,
- programmatic_mode=True,
- )
-
- # Pre-populate cache
- engine.engine_cache["brave"] = cached_engine
-
- result = engine._get_engine_instance("brave")
-
- # Should not call create_search_engine
- mock_create.assert_not_called()
- assert result is cached_engine
-
- def test_get_engine_instance_handles_creation_error(self):
- """_get_engine_instance handles engine creation errors."""
- from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
- )
-
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- with patch.object(
- MetaSearchEngine,
- "_get_available_engines",
- return_value=["wikipedia"],
- ):
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.create_search_engine",
- side_effect=Exception("Creation failed"),
- ):
- engine = MetaSearchEngine(
- llm=mock_llm,
- settings_snapshot=settings,
- programmatic_mode=True,
- )
-
- result = engine._get_engine_instance("failing_engine")
-
- assert result is None
-
-
-class TestMetaSearchEngineInvoke:
- """Tests for MetaSearchEngine invoke method."""
-
- def test_invoke_calls_run(self):
- """invoke method calls run."""
- from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
- )
-
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- with patch.object(
- MetaSearchEngine,
- "_get_available_engines",
- return_value=["wikipedia"],
- ):
- with patch.object(
- MetaSearchEngine, "run", return_value=[{"title": "Result"}]
- ) as mock_run:
- engine = MetaSearchEngine(
- llm=mock_llm,
- settings_snapshot=settings,
- programmatic_mode=True,
- )
-
- result = engine.invoke("test query")
-
- mock_run.assert_called_once_with("test query")
- assert result == [{"title": "Result"}]
-
-
-class TestMetaSearchEngineGetAvailableEngines:
- """Tests for MetaSearchEngine _get_available_engines method."""
-
- def test_get_available_engines_filters_meta_and_auto(self):
- """_get_available_engines filters out meta and auto."""
- 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},
- "search.engine.web.meta.use_in_auto_search": {"value": True},
- "search.engine.web.auto.use_in_auto_search": {"value": True},
- }
-
- # Use a real instance to test _get_available_engines
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.get_setting_from_snapshot"
- ) as mock_get_setting:
-
- def setting_side_effect(key, default, settings_snapshot=None):
- if "wikipedia" in key and "use_in_auto_search" in key:
- return True
- return default
-
- mock_get_setting.side_effect = setting_side_effect
-
- with patch.object(
- MetaSearchEngine,
- "_get_search_config",
- return_value={"wikipedia": {}, "meta": {}, "auto": {}},
- ):
- engine = MetaSearchEngine(
- llm=mock_llm,
- settings_snapshot=settings,
- programmatic_mode=True,
- )
-
- assert "meta" not in engine.available_engines
- assert "auto" not in engine.available_engines
-
- def test_get_available_engines_raises_when_none_available(self):
- """_get_available_engines raises RuntimeError when no engines available."""
- from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
- )
- import pytest
-
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.get_setting_from_snapshot",
- return_value=False, # All engines disabled
- ):
- with patch.object(
- MetaSearchEngine,
- "_get_search_config",
- return_value={"wikipedia": {}, "brave": {}},
- ):
- with pytest.raises(RuntimeError) as exc_info:
- MetaSearchEngine(
- llm=mock_llm,
- settings_snapshot=settings,
- programmatic_mode=True,
- )
-
- 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/engines/test_meta_search_engine_extended.py b/tests/web_search_engines/engines/test_meta_search_engine_extended.py
deleted file mode 100644
index a8c6af37c5..0000000000
--- a/tests/web_search_engines/engines/test_meta_search_engine_extended.py
+++ /dev/null
@@ -1,395 +0,0 @@
-"""Extended tests for meta_search_engine.py - targeting untested paths.
-
-Covers:
-- analyze_query() LLM invocation path (lines 256-346)
-- analyze_query() LLM response parsing (content attr vs str)
-- analyze_query() SearXNG fallback when LLM omits it
-- analyze_query() no valid engines from LLM → reliability sort
-- analyze_query() exception → fallback
-- analyze_query() no engines_info → reliability sort
-- _get_search_config() from settings_snapshot
-- _get_available_engines() API key filtering
-- _get_full_content() exception in selected engine
-- _get_previews() engine init failure → skip
-"""
-
-from unittest.mock import Mock, patch
-
-
-def _make_engine(available_engines, llm=None, settings=None):
- """Helper to create MetaSearchEngine with mocked _get_available_engines."""
- from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
- )
-
- if llm is None:
- llm = Mock()
- if settings is None:
- settings = {"search.max_results": {"value": 10}}
-
- with patch.object(
- MetaSearchEngine,
- "_get_available_engines",
- return_value=available_engines,
- ):
- engine = MetaSearchEngine(
- llm=llm,
- settings_snapshot=settings,
- programmatic_mode=True,
- )
-
- return engine
-
-
-# ── analyze_query: LLM invocation path ──────────────────────────
-
-
-class TestAnalyzeQueryAdvancedPaths:
- """Tests for analyze_query paths not covered by existing tests.
-
- Note: The LLM invocation path (lines 255-346) is currently unreachable
- because line 227 catches SearXNG-present case and line 242 catches
- SearXNG-absent case, both returning before LLM is invoked. These tests
- cover the reachable but untested paths.
- """
-
- def test_no_llm_no_searxng_reliability_sort(self):
- """When LLM is None and SearXNG unavailable, reliability sort is used."""
- engine = _make_engine(["brave", "wikipedia"], llm=None)
-
- engine._get_search_config = lambda: {
- "brave": {"reliability": 0.8},
- "wikipedia": {"reliability": 0.95},
- }
-
- result = engine.analyze_query("query without llm")
-
- assert result[0] == "wikipedia"
- assert result[1] == "brave"
-
- def test_truthy_llm_no_searxng_reliability_sort(self):
- """When LLM is truthy but SearXNG absent, reliability sort is used (line 242)."""
- mock_llm = Mock()
-
- engine = _make_engine(["brave", "wikipedia"], llm=mock_llm)
- engine._get_search_config = lambda: {
- "brave": {"reliability": 0.6},
- "wikipedia": {"reliability": 0.9},
- }
-
- result = engine.analyze_query("general question about history")
-
- # Line 242 catches this: "searxng" not in available_engines → True
- assert result[0] == "wikipedia"
- assert result[1] == "brave"
- mock_llm.invoke.assert_not_called()
-
- def test_searxng_present_reliability_sort_for_remaining(self):
- """SearXNG present → first, remaining sorted by reliability (line 227)."""
- engine = _make_engine(["searxng", "brave", "wikipedia"])
- engine._get_search_config = lambda: {
- "brave": {"reliability": 0.9},
- "wikipedia": {"reliability": 0.7},
- }
-
- result = engine.analyze_query("general web search")
-
- assert result[0] == "searxng"
- assert result[1] == "brave"
- assert result[2] == "wikipedia"
-
- def test_multiple_specialized_terms_first_match_wins(self):
- """First matching specialized term in dict order determines engines."""
- engine = _make_engine(["github", "pubmed", "searxng"])
-
- # "clinical" appears before "code" in the specialized_domains dict,
- # so "clinical" match wins
- result = engine.analyze_query("code for clinical analysis")
-
- assert result[0] == "pubmed"
-
- def test_specialized_match_skips_unavailable_engines(self):
- """Specialized match only includes available engines."""
- engine = _make_engine(["wikipedia", "searxng"])
-
- # "scientific paper" wants arxiv, pubmed, wikipedia
- result = engine.analyze_query("scientific paper on climate")
-
- # Only wikipedia is available from the specialized list
- assert result == ["wikipedia"]
-
- def test_exception_in_analyze_with_searxng_available(self):
- """Exception in try block with SearXNG → SearXNG first + reliability."""
- engine = _make_engine(["searxng", "brave"])
- engine._get_search_config = lambda: {
- "searxng": {"reliability": 0.7},
- "brave": {"reliability": 0.9},
- }
-
- # Cause exception by passing non-string query (no .lower() method)
- result = engine.analyze_query(None)
-
- assert result[0] == "searxng"
- assert result[1] == "brave"
-
- def test_exception_in_analyze_without_searxng(self):
- """Exception in try block without SearXNG → reliability sort."""
- engine = _make_engine(["brave", "wikipedia"])
- engine._get_search_config = lambda: {
- "brave": {"reliability": 0.6},
- "wikipedia": {"reliability": 0.9},
- }
-
- # Cause exception by passing non-string query
- result = engine.analyze_query(None)
-
- assert result[0] == "wikipedia"
- assert result[1] == "brave"
-
- def test_arxiv_keyword_puts_arxiv_first_includes_others(self):
- """'arxiv' keyword → arxiv first, all others follow."""
- engine = _make_engine(["arxiv", "wikipedia", "brave"])
-
- result = engine.analyze_query("find arxiv papers on transformers")
-
- assert result[0] == "arxiv"
- assert set(result[1:]) == {"wikipedia", "brave"}
-
- def test_pubmed_keyword_puts_pubmed_first_includes_others(self):
- """'pubmed' keyword → pubmed first, all others follow."""
- engine = _make_engine(["pubmed", "wikipedia", "brave"])
-
- result = engine.analyze_query("search pubmed for cancer treatment")
-
- assert result[0] == "pubmed"
- assert set(result[1:]) == {"wikipedia", "brave"}
-
-
-# ── _get_search_config from settings_snapshot ────────────────────
-
-
-class TestGetSearchConfigFromSnapshot:
- """Tests for _get_search_config (now delegates to get_available_engines)."""
-
- def test_delegates_to_get_available_engines(self):
- """_get_search_config returns the output of get_available_engines."""
- expected = {
- "brave": {"class_name": "BraveSearchEngine", "api_key": "key123"},
- "wikipedia": {"class_name": "WikipediaSearchEngine"},
- }
-
- engine = _make_engine(["brave", "wikipedia"])
-
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.get_available_engines",
- return_value=expected,
- ):
- config = engine._get_search_config()
-
- assert config == expected
-
- def test_returns_empty_without_snapshot(self):
- """Returns empty dict when settings_snapshot is empty."""
- engine = _make_engine(["wikipedia"], settings={})
- config = engine._get_search_config()
- assert config == {}
-
-
-# ── _get_available_engines: API key filtering ────────────────────
-
-
-class TestGetAvailableEnginesFiltering:
- """Tests for _get_available_engines filtering (now via shared get_available_engines)."""
-
- def test_requires_api_key_but_missing_excluded(self):
- """Engine with requires_api_key=True but no key is excluded."""
- from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
- )
-
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- # Shared function already filters out brave (no key)
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.get_available_engines",
- return_value={"wikipedia": {}},
- ):
- engine = MetaSearchEngine(
- llm=mock_llm,
- settings_snapshot=settings,
- programmatic_mode=True,
- )
-
- assert "brave" not in engine.available_engines
- assert "wikipedia" in engine.available_engines
-
- def test_requires_api_key_with_key_present_included(self):
- """Engine with requires_api_key=True and key present is included."""
- from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
- )
-
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.get_available_engines",
- return_value={
- "brave": {"requires_api_key": True, "api_key": "sk-123"},
- },
- ):
- engine = MetaSearchEngine(
- llm=mock_llm,
- settings_snapshot=settings,
- programmatic_mode=True,
- )
-
- assert "brave" in engine.available_engines
-
- def test_use_api_key_services_false_skips_api_engines(self):
- """When use_api_key_services=False, API key engines are excluded."""
- from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
- )
-
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- # Shared function with use_api_key_services=False filters brave
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.get_available_engines",
- return_value={"wikipedia": {}},
- ):
- engine = MetaSearchEngine(
- llm=mock_llm,
- use_api_key_services=False,
- settings_snapshot=settings,
- programmatic_mode=True,
- )
-
- assert "brave" not in engine.available_engines
- assert "wikipedia" in engine.available_engines
-
-
-# ── _get_full_content: exception in selected engine ──────────────
-
-
-class TestGetFullContentException:
- """Tests for _get_full_content exception handling."""
-
- def test_exception_in_selected_engine_returns_items(self):
- """Exception in selected engine → returns items without full content."""
- engine = _make_engine(["wikipedia"])
-
- mock_selected = Mock()
- mock_selected._get_full_content.side_effect = RuntimeError(
- "Fetch failed"
- )
- engine._selected_engine = mock_selected
- engine._selected_engine_name = "wikipedia"
-
- items = [{"title": "Result", "url": "http://example.com"}]
-
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.get_setting_from_snapshot",
- return_value=False, # Not snippets_only
- ):
- result = engine._get_full_content(items)
-
- assert result == items
-
-
-# ── _get_previews: engine init failure ───────────────────────────
-
-
-class TestGetPreviewsEngineInitFailure:
- """Tests for _get_previews when engine initialization fails."""
-
- def test_init_failure_skips_to_next_engine(self):
- """Failed engine init skips to next engine in list."""
- engine = _make_engine(["broken", "working"])
-
- mock_working = Mock()
- mock_working._get_previews.return_value = [
- {"title": "From working", "url": "http://ok.com"}
- ]
-
- def get_instance(name):
- if name == "broken":
- return None # Init failed
- return mock_working
-
- engine._get_engine_instance = get_instance
-
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.SocketIOService"
- ):
- results = engine._get_previews("test query")
-
- assert len(results) == 1
- assert results[0]["title"] == "From working"
-
- def test_all_engines_fail_uses_fallback(self):
- """All engines failing → Wikipedia fallback is used."""
- engine = _make_engine(["bad1", "bad2"])
-
- engine._get_engine_instance = lambda name: None # All fail
-
- mock_fallback = Mock()
- mock_fallback._get_previews.return_value = [
- {"title": "Wiki fallback", "url": "http://wiki.com"}
- ]
- engine.fallback_engine = mock_fallback
-
- results = engine._get_previews("test query")
-
- assert results[0]["title"] == "Wiki fallback"
- assert engine._selected_engine_name == "wikipedia"
-
- def test_successful_engine_stores_selection(self):
- """Successful engine is stored as _selected_engine."""
- engine = _make_engine(["brave"])
-
- mock_brave = Mock()
- mock_brave._get_previews.return_value = [
- {"title": "Brave result", "url": "http://brave.com"}
- ]
- engine._get_engine_instance = lambda name: mock_brave
-
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.SocketIOService"
- ):
- engine._get_previews("test query")
-
- assert engine._selected_engine is mock_brave
- assert engine._selected_engine_name == "brave"
-
- def test_socket_emit_failure_non_critical(self):
- """SocketIO emit failure doesn't affect results."""
- from local_deep_research.utilities.thread_context import (
- search_context,
- )
-
- engine = _make_engine(["brave"])
-
- mock_brave = Mock()
- mock_brave._get_previews.return_value = [
- {"title": "Result", "url": "http://test.com"}
- ]
- engine._get_engine_instance = lambda name: mock_brave
-
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.SocketIOService"
- ) as mock_sio:
- mock_sio.return_value.emit_socket_event.side_effect = RuntimeError(
- "Socket error"
- )
- # A username in the search context is required for the emit to be
- # attempted at all (it is scoped to the user's room).
- with search_context({"username": "alice"}):
- results = engine._get_previews("test query")
-
- mock_sio.return_value.emit_socket_event.assert_called_once()
- assert len(results) == 1
- assert results[0]["title"] == "Result"
diff --git a/tests/web_search_engines/engines/test_meta_search_engine_gaps_coverage.py b/tests/web_search_engines/engines/test_meta_search_engine_gaps_coverage.py
deleted file mode 100644
index 82cdd81378..0000000000
--- a/tests/web_search_engines/engines/test_meta_search_engine_gaps_coverage.py
+++ /dev/null
@@ -1,176 +0,0 @@
-"""
-Tests for MetaSearchEngine covering the LLM-based _analyze_query_with_llm path
-(lines 259-350) and related branches.
-
-Covers:
-- Lines 259-350: Full LLM-based engine selection flow
-- Engine info prompt building with config
-- Response parsing (content attr vs str)
-- SearXNG fallback when not selected by LLM
-- No valid engines → reliability fallback
-- Exception in LLM invocation → fallback
-"""
-
-from unittest.mock import MagicMock, patch
-
-
-MODULE = "local_deep_research.web_search_engines.engines.meta_search_engine"
-
-
-def _make_meta_engine(
- available_engines=None,
- llm_response="searxng,wikipedia",
- settings_snapshot=None,
-):
- """Create a MetaSearchEngine with mocked internals."""
- from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
- )
-
- mock_llm = MagicMock()
- mock_llm.invoke.return_value = MagicMock(content=llm_response)
-
- with patch.object(
- MetaSearchEngine,
- "_get_available_engines",
- return_value=available_engines or ["searxng", "wikipedia", "brave"],
- ):
- with patch(f"{MODULE}.WikipediaSearchEngine"):
- engine = MetaSearchEngine(
- llm=mock_llm,
- max_results=10,
- settings_snapshot=settings_snapshot or {},
- )
-
- return engine
-
-
-class TestAnalyzeQueryLLMPath:
- """Test the LLM-based engine selection in analyze_query (lines 259-350)."""
-
- def test_no_searxng_no_llm_returns_reliability_sorted(self):
- """Without searxng and no LLM, reliability-based sorting is used."""
- engine = _make_meta_engine(
- available_engines=["brave", "wikipedia", "arxiv"],
- )
- engine.llm = None
- result = engine.analyze_query("generic query")
- assert isinstance(result, list)
- assert len(result) == 3
-
- def test_analyze_query_specialized_domain(self):
- """Specialized query terms like 'scientific paper' select specific engines."""
- engine = _make_meta_engine(
- available_engines=["arxiv", "pubmed", "wikipedia", "searxng"],
- )
- result = engine.analyze_query("scientific paper on quantum computing")
- assert result[0] == "arxiv"
-
- def test_analyze_query_arxiv_keyword(self):
- """Query containing 'arxiv' prioritizes arxiv engine."""
- engine = _make_meta_engine(
- available_engines=["arxiv", "wikipedia", "searxng"],
- )
- result = engine.analyze_query("arxiv papers on AI")
- assert result[0] == "arxiv"
-
- def test_analyze_query_pubmed_keyword(self):
- """Query containing 'pubmed' prioritizes pubmed engine."""
- engine = _make_meta_engine(
- available_engines=["pubmed", "wikipedia", "searxng"],
- )
- result = engine.analyze_query("pubmed clinical trials")
- assert result[0] == "pubmed"
-
- def test_analyze_query_searxng_first_for_general(self):
- """General query with searxng available returns searxng first."""
- engine = _make_meta_engine(
- available_engines=["searxng", "wikipedia", "brave"],
- )
- result = engine.analyze_query("what is the weather today")
- assert result[0] == "searxng"
-
- def test_analyze_query_no_searxng_no_llm(self):
- """Without searxng or LLM, returns reliability-sorted engines."""
- engine = _make_meta_engine(
- available_engines=["wikipedia", "brave"],
- )
- engine.llm = None
- result = engine.analyze_query("general question")
- assert isinstance(result, list)
- assert len(result) == 2
-
- def test_analyze_query_no_searxng_with_llm(self):
- """Without searxng but with LLM, line 245 returns reliability-sorted."""
- engine = _make_meta_engine(
- available_engines=["wikipedia", "brave"],
- )
- result = engine.analyze_query("general question")
- # Line 245 condition: searxng not in available → returns reliability sort
- assert isinstance(result, list)
-
- def test_analyze_query_specialized_no_matching_engines(self):
- """Specialized term but no matching engines available → falls through."""
- engine = _make_meta_engine(
- available_engines=["searxng", "brave"],
- )
- # "scientific paper" matches but neither arxiv nor pubmed nor wikipedia available
- result = engine.analyze_query("scientific paper on topic")
- # Falls through to searxng-first path
- assert result[0] == "searxng"
-
- def test_analyze_query_code_related(self):
- """Code-related query selects github if available."""
- engine = _make_meta_engine(
- available_engines=["github", "searxng", "wikipedia"],
- )
- result = engine.analyze_query("code implementation of binary search")
- assert "github" in result
-
- def test_analyze_query_github_related(self):
- """Repository-related query selects github."""
- engine = _make_meta_engine(
- available_engines=["github", "searxng", "wikipedia"],
- )
- result = engine.analyze_query("repository for machine learning models")
- assert "github" in result
-
- def test_analyze_query_medical(self):
- """Medical/clinical query selects pubmed if available."""
- engine = _make_meta_engine(
- available_engines=["pubmed", "searxng", "wikipedia"],
- )
- result = engine.analyze_query("clinical trial results for aspirin")
- assert result[0] == "pubmed"
-
-
-class TestGetSearchConfig:
- """Test _get_search_config method."""
-
- def test_empty_snapshot(self):
- """Empty settings_snapshot returns empty config."""
- engine = _make_meta_engine(settings_snapshot={})
- engine.settings_snapshot = {}
- config = engine._get_search_config()
- assert config == {} or isinstance(config, dict)
-
- def test_no_snapshot(self):
- """None settings_snapshot logs warning and returns empty."""
- engine = _make_meta_engine(settings_snapshot={})
- engine.settings_snapshot = None
- config = engine._get_search_config()
- assert config == {}
-
- def test_delegates_to_get_available_engines(self):
- """_get_search_config delegates to the shared get_available_engines function."""
- expected = {"brave": {"api_key": "test-key", "reliability": 0.8}}
- engine = _make_meta_engine(settings_snapshot={"search.max_results": 10})
- engine.settings_snapshot = {"search.max_results": 10}
-
- with patch(
- "local_deep_research.web_search_engines.engines.meta_search_engine.get_available_engines",
- return_value=expected,
- ):
- config = engine._get_search_config()
- assert "brave" in config
- assert config["brave"]["api_key"] == "test-key"
diff --git a/tests/web_search_engines/engines/test_meta_search_engine_high_value.py b/tests/web_search_engines/engines/test_meta_search_engine_high_value.py
deleted file mode 100644
index 866a822644..0000000000
--- a/tests/web_search_engines/engines/test_meta_search_engine_high_value.py
+++ /dev/null
@@ -1,245 +0,0 @@
-"""High-value pure logic tests for MetaSearchEngine.
-
-Tests focus on _get_search_config() and analyze_query() without network calls.
-"""
-
-from unittest.mock import Mock, patch
-
-
-from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
-)
-
-MODULE = "local_deep_research.web_search_engines.engines.meta_search_engine"
-
-
-def _make_engine(available_engines=None, settings_snapshot=None, llm=None):
- """Create a MetaSearchEngine instance bypassing __init__."""
- with patch.object(
- MetaSearchEngine, "__init__", lambda self, *a, **kw: None
- ):
- engine = MetaSearchEngine.__new__(MetaSearchEngine)
- engine.available_engines = available_engines or []
- engine.settings_snapshot = settings_snapshot
- engine.llm = llm
- engine.engine_cache = {}
- engine.max_results = 10
- engine.max_filtered_results = None
- engine.use_api_key_services = True
- return engine
-
-
-class TestGetSearchConfig:
- """Tests for MetaSearchEngine._get_search_config() (delegates to get_available_engines)."""
-
- def test_returns_empty_dict_when_no_settings_snapshot(self):
- engine = _make_engine(settings_snapshot=None)
- result = engine._get_search_config()
- assert result == {}
-
- def test_returns_empty_dict_when_settings_snapshot_is_empty(self):
- engine = _make_engine(settings_snapshot={})
- result = engine._get_search_config()
- assert result == {}
-
- def test_delegates_to_get_available_engines(self):
- expected = {
- "brave": {
- "api_key": "test-key-123",
- "module_path": ".engines.search_engine_brave",
- "class_name": "BraveSearchEngine",
- },
- }
- engine = _make_engine(settings_snapshot={"search.max_results": 10})
- engine.use_api_key_services = True
- with patch(f"{MODULE}.get_available_engines", return_value=expected):
- config = engine._get_search_config()
- assert config == expected
-
-
-class TestAnalyzeQuerySpecializedDomains:
- """Tests for analyze_query() heuristic matching of specialized domains."""
-
- def test_scientific_paper_returns_arxiv_pubmed_wikipedia(self):
- engine = _make_engine(
- available_engines=["arxiv", "pubmed", "wikipedia", "searxng"]
- )
- result = engine.analyze_query("find a scientific paper on transformers")
- assert result == ["arxiv", "pubmed", "wikipedia"]
-
- def test_medical_research_returns_pubmed_searxng(self):
- engine = _make_engine(
- available_engines=["arxiv", "pubmed", "searxng", "wikipedia"]
- )
- result = engine.analyze_query("medical research on cancer treatment")
- assert result == ["pubmed", "searxng"]
-
- def test_clinical_returns_pubmed_searxng(self):
- engine = _make_engine(available_engines=["pubmed", "searxng", "brave"])
- result = engine.analyze_query("clinical trials for diabetes drugs")
- assert result == ["pubmed", "searxng"]
-
- def test_github_returns_github_searxng(self):
- engine = _make_engine(available_engines=["github", "searxng", "brave"])
- result = engine.analyze_query("github repo for machine learning")
- assert result == ["github", "searxng"]
-
- def test_code_query_returns_github_searxng(self):
- engine = _make_engine(available_engines=["github", "searxng", "arxiv"])
- result = engine.analyze_query("python code for sorting algorithms")
- assert result == ["github", "searxng"]
-
- def test_programming_query_returns_github_searxng(self):
- engine = _make_engine(
- available_engines=["github", "searxng", "wikipedia"]
- )
- result = engine.analyze_query("programming tutorial for rust")
- assert result == ["github", "searxng"]
-
- def test_repository_query_returns_github_searxng(self):
- engine = _make_engine(available_engines=["github", "searxng"])
- result = engine.analyze_query("best repository for NLP models")
- assert result == ["github", "searxng"]
-
- def test_specialized_domain_filters_unavailable_engines(self):
- """If specialized engines aren't available, skip to next heuristic."""
- engine = _make_engine(
- available_engines=["searxng", "brave"],
- )
- engine._get_search_config = Mock(
- return_value={
- "searxng": {"reliability": 0.9},
- "brave": {"reliability": 0.5},
- }
- )
- result = engine.analyze_query("scientific paper on quantum computing")
- assert result[0] == "searxng"
-
- def test_specialized_domain_partial_availability(self):
- """Only available engines from the specialized list are returned."""
- engine = _make_engine(
- available_engines=["wikipedia", "brave", "searxng"]
- )
- result = engine.analyze_query("scientific paper on dark matter")
- assert result == ["wikipedia"]
-
- def test_case_insensitive_matching(self):
- engine = _make_engine(available_engines=["pubmed", "searxng"])
- result = engine.analyze_query("MEDICAL RESEARCH on hypertension")
- assert result == ["pubmed", "searxng"]
-
-
-class TestAnalyzeQueryArxivPubmedPriority:
- """Tests for arxiv/pubmed keyword prioritization in analyze_query()."""
-
- def test_arxiv_in_query_prioritizes_arxiv(self):
- engine = _make_engine(available_engines=["searxng", "arxiv", "brave"])
- result = engine.analyze_query("search arxiv for attention mechanisms")
- assert result[0] == "arxiv"
- assert "searxng" in result
- assert "brave" in result
-
- def test_arxiv_in_query_but_not_available_falls_through(self):
- engine = _make_engine(
- available_engines=["searxng", "brave"],
- )
- engine._get_search_config = Mock(
- return_value={
- "searxng": {"reliability": 0.9},
- "brave": {"reliability": 0.5},
- }
- )
- result = engine.analyze_query("look on arxiv for papers")
- assert result[0] == "searxng"
-
- def test_pubmed_in_query_prioritizes_pubmed(self):
- engine = _make_engine(available_engines=["searxng", "pubmed", "brave"])
- result = engine.analyze_query("search pubmed for drug interactions")
- assert result[0] == "pubmed"
- assert "searxng" in result
- assert "brave" in result
-
- def test_pubmed_in_query_but_not_available_falls_through(self):
- engine = _make_engine(
- available_engines=["searxng", "brave"],
- )
- engine._get_search_config = Mock(
- return_value={
- "searxng": {"reliability": 0.9},
- "brave": {"reliability": 0.5},
- }
- )
- result = engine.analyze_query("find pubmed articles")
- assert result[0] == "searxng"
-
-
-class TestAnalyzeQueryGeneralAndFallback:
- """Tests for general query handling and fallback logic in analyze_query()."""
-
- def test_general_query_with_searxng_returns_searxng_first(self):
- engine = _make_engine(
- available_engines=["brave", "searxng", "wikipedia"],
- )
- engine._get_search_config = Mock(
- return_value={
- "brave": {"reliability": 0.5},
- "wikipedia": {"reliability": 0.8},
- "searxng": {"reliability": 0.9},
- }
- )
- result = engine.analyze_query("what is the weather today")
- assert result[0] == "searxng"
- assert "searxng" not in result[1:] # no duplicate
-
- def test_general_query_without_searxng_uses_reliability(self):
- engine = _make_engine(
- available_engines=["brave", "wikipedia"],
- llm=None,
- )
- engine._get_search_config = Mock(
- return_value={
- "brave": {"reliability": 0.9},
- "wikipedia": {"reliability": 0.7},
- }
- )
- result = engine.analyze_query("what is the capital of France")
- assert result[0] == "brave"
- assert result[1] == "wikipedia"
-
- def test_reliability_sorting_with_no_reliability_keys(self):
- """Engines with no reliability config get default 0."""
- engine = _make_engine(
- available_engines=["brave", "wikipedia"],
- llm=None,
- )
- engine._get_search_config = Mock(return_value={})
- result = engine.analyze_query("generic search query")
- assert set(result) == {"brave", "wikipedia"}
-
- def test_empty_engines_returns_empty_list(self):
- """With no available engines, analyze_query returns empty list."""
- engine = _make_engine(
- available_engines=[],
- llm=None,
- )
- result = engine.analyze_query("anything")
- assert result == []
-
- def test_searxng_general_query_sorts_remaining_by_reliability(self):
- engine = _make_engine(
- available_engines=["brave", "searxng", "wikipedia", "arxiv"],
- )
- engine._get_search_config = Mock(
- return_value={
- "brave": {"reliability": 0.5},
- "wikipedia": {"reliability": 0.8},
- "arxiv": {"reliability": 0.3},
- "searxng": {"reliability": 0.9},
- }
- )
- result = engine.analyze_query("latest news on AI")
- assert result[0] == "searxng"
- # Remaining sorted by reliability descending
- assert result[1] == "wikipedia"
- assert result[2] == "brave"
- assert result[3] == "arxiv"
diff --git a/tests/web_search_engines/engines/test_meta_search_extra_coverage.py b/tests/web_search_engines/engines/test_meta_search_extra_coverage.py
deleted file mode 100644
index 46acb92318..0000000000
--- a/tests/web_search_engines/engines/test_meta_search_extra_coverage.py
+++ /dev/null
@@ -1,301 +0,0 @@
-"""Extra coverage tests for meta_search_engine.py targeting LLM-based query analysis.
-
-Targets branches NOT covered by test_meta_search_deep_coverage.py:
-- LLM-based query analysis (lines 244-335): when SearXNG IS available + engines_info populated
-- LLM response with .content attribute vs raw string
-- Engine selection from LLM output: valid names, invalid names
-- SearXNG fallback injection when LLM omits/includes it
-- LLM exception fallback (with SearXNG available)
-- API key filtering (requires_api_key with missing key)
-"""
-
-from unittest.mock import Mock, patch
-
-from local_deep_research.web_search_engines.engines.meta_search_engine import (
- MetaSearchEngine,
-)
-
-MODULE = "local_deep_research.web_search_engines.engines.meta_search_engine"
-
-
-# ---------------------------------------------------------------------------
-# Helpers
-# ---------------------------------------------------------------------------
-
-
-def _bypass_init(available_engines=None, settings_snapshot=None, llm=None):
- """Create MetaSearchEngine bypassing __init__ for pure logic tests."""
- with patch.object(
- MetaSearchEngine, "__init__", lambda self, *a, **kw: None
- ):
- engine = MetaSearchEngine.__new__(MetaSearchEngine)
- engine.available_engines = (
- available_engines if available_engines is not None else []
- )
- engine.settings_snapshot = settings_snapshot
- engine.llm = llm
- engine.engine_cache = {}
- engine.max_results = 10
- engine.max_filtered_results = None
- engine.max_engines_to_try = 3
- engine.use_api_key_services = True
- engine.programmatic_mode = True
- engine.fallback_engine = Mock()
- return engine
-
-
-def _make_engine_with_searxng_and_llm(llm, extra_engines=None):
- """Create engine with SearXNG available + LLM + engines_info config."""
- engines = ["searxng"] + (extra_engines or ["brave", "wikipedia"])
- config = {
- "searxng": {
- "description": "Meta search aggregator",
- "strengths": "Broad coverage",
- "weaknesses": "Slow",
- "reliability": 0.95,
- },
- "brave": {
- "description": "Privacy search",
- "strengths": "Fast",
- "weaknesses": "Limited",
- "reliability": 0.7,
- },
- "wikipedia": {
- "description": "Encyclopedia",
- "strengths": "Factual",
- "weaknesses": "Not current",
- "reliability": 0.9,
- },
- }
- engine = _bypass_init(
- available_engines=engines, settings_snapshot={}, llm=llm
- )
- engine._get_search_config = Mock(return_value=config)
- return engine
-
-
-# ---------------------------------------------------------------------------
-# LLM-based query analysis — non-heuristic path
-# ---------------------------------------------------------------------------
-
-
-class TestLLMBasedQueryAnalysis:
- """Tests for analyze_query LLM invocation (lines 244-335).
-
- These paths are reached when:
- 1. Query doesn't match any heuristic domain
- 2. SearXNG IS in available_engines (so line 216-228 returns early)
-
- Wait — reading the code again, if SearXNG is available, line 216-228
- returns SearXNG + reliability-sorted. The LLM path (244+) is only
- reached when there's no SearXNG AND llm is present AND no heuristic match.
- But line 231 catches that case: "if not self.llm or 'searxng' not in self.available_engines".
- So the LLM path is indeed structurally unreachable in current code.
-
- However, we can still test the SearXNG-present heuristic paths and
- the exception path with SearXNG available.
- """
-
- def test_searxng_available_general_query(self):
- """General query with SearXNG → returns SearXNG first + reliability sorted."""
- llm = Mock()
- engine = _make_engine_with_searxng_and_llm(llm)
-
- result = engine.analyze_query("what is quantum computing")
-
- # SearXNG first, then reliability-sorted rest
- assert result[0] == "searxng"
- assert "wikipedia" in result
- assert "brave" in result
- # LLM should NOT be invoked (SearXNG short-circuit)
- llm.invoke.assert_not_called()
-
- def test_llm_response_content_attribute(self):
- """LLM returning object with .content attribute."""
- # This tests the response handling at line 302-303
- # We need to bypass the SearXNG short circuit to reach the LLM path.
- # Since current code always short-circuits, test via heuristic match instead.
- mock_llm = Mock()
- # arxiv heuristic: "arxiv" in query
- engine = _bypass_init(
- available_engines=["arxiv", "brave"],
- settings_snapshot={},
- llm=mock_llm,
- )
- engine._get_search_config = Mock(
- return_value={
- "arxiv": {"reliability": 0.9},
- "brave": {"reliability": 0.5},
- }
- )
-
- result = engine.analyze_query("find arxiv papers on transformers")
-
- assert result[0] == "arxiv"
- assert "brave" in result
-
- def test_llm_raw_string_response(self):
- """LLM returning plain string (no .content) — str() fallback."""
- # Test via pubmed heuristic
- engine = _bypass_init(
- available_engines=["pubmed", "wikipedia"],
- settings_snapshot={},
- llm=Mock(),
- )
- engine._get_search_config = Mock(
- return_value={
- "pubmed": {"reliability": 0.85},
- "wikipedia": {"reliability": 0.9},
- }
- )
-
- result = engine.analyze_query("pubmed studies on diabetes treatment")
-
- assert result[0] == "pubmed"
-
-
-# ---------------------------------------------------------------------------
-# Engine selection from heuristic/LLM output
-# ---------------------------------------------------------------------------
-
-
-class TestEngineSelection:
- def test_valid_specialized_engine_names(self):
- """Specialized query matching heuristic → valid engines selected."""
- engine = _bypass_init(
- available_engines=["github", "searxng", "brave"],
- settings_snapshot={},
- llm=Mock(),
- )
- engine._get_search_config = Mock(return_value={})
-
- result = engine.analyze_query("github repository for machine learning")
-
- assert "github" in result
- assert "searxng" in result
-
- def test_specialized_engines_not_available(self):
- """Specialized query but engines not available → falls through to SearXNG."""
- engine = _bypass_init(
- available_engines=["searxng", "brave"],
- settings_snapshot={},
- llm=Mock(),
- )
- engine._get_search_config = Mock(
- return_value={
- "searxng": {"reliability": 0.9},
- "brave": {"reliability": 0.5},
- }
- )
-
- # "scientific paper" matches heuristic but arxiv/pubmed not available
- result = engine.analyze_query("scientific paper on climate change")
-
- # Falls through heuristic (no valid engines), hits SearXNG path
- assert result[0] == "searxng"
-
-
-# ---------------------------------------------------------------------------
-# LLM exception fallback
-# ---------------------------------------------------------------------------
-
-
-class TestLLMExceptionFallback:
- def test_exception_with_searxng_available(self):
- """Exception in specialized_domains check → SearXNG fallback."""
- # Patch available_engines property to raise on iteration for heuristic check
- engine = _bypass_init(
- available_engines=["searxng", "brave"],
- settings_snapshot={},
- llm=Mock(),
- )
- config = {
- "searxng": {"reliability": 0.9},
- "brave": {"reliability": 0.5},
- }
- engine._get_search_config = Mock(return_value=config)
-
- # Make the specialized_domains dict iteration raise by patching
- # the built-in str.lower on the query side — simplest approach
- # is to trigger an exception in the try block by passing a non-string
- # that can't do .lower()
- class BadQuery:
- def lower(self):
- raise RuntimeError("simulated error")
-
- result = engine.analyze_query(BadQuery())
-
- # Exception caught → SearXNG + reliability sorted rest
- assert result[0] == "searxng"
-
- def test_exception_without_searxng(self):
- """Exception + no SearXNG → reliability-sorted fallback."""
- engine = _bypass_init(
- available_engines=["brave", "wikipedia"],
- settings_snapshot={},
- llm=Mock(),
- )
- config = {
- "brave": {"reliability": 0.5},
- "wikipedia": {"reliability": 0.9},
- }
- engine._get_search_config = Mock(return_value=config)
-
- result = engine.analyze_query(
- type(
- "BadQ",
- (),
- {"lower": lambda s: (_ for _ in ()).throw(RuntimeError("err"))},
- )()
- )
-
- assert result[0] == "wikipedia"
- assert result[1] == "brave"
-
-
-# ---------------------------------------------------------------------------
-# API key filtering
-# ---------------------------------------------------------------------------
-
-
-class TestAPIKeyFiltering:
- def test_engine_requires_api_key_not_configured(self):
- """Engine requires API key but none configured → skipped by shared filter."""
- with patch.object(
- MetaSearchEngine, "__init__", lambda self, *a, **kw: None
- ):
- engine = MetaSearchEngine.__new__(MetaSearchEngine)
- engine.settings_snapshot = {"search.max_results": 10}
- engine.use_api_key_services = True
-
- # Shared function already filters out tavily (no key)
- with patch(
- f"{MODULE}.get_available_engines",
- return_value={
- "brave": {"requires_api_key": False, "reliability": 0.7}
- },
- ):
- available = engine._get_available_engines()
-
- assert "brave" in available
- assert "tavily" not in available
-
- def test_use_api_key_services_false_skips_api_engines(self):
- """use_api_key_services=False → engines with requires_api_key skipped."""
- with patch.object(
- MetaSearchEngine, "__init__", lambda self, *a, **kw: None
- ):
- engine = MetaSearchEngine.__new__(MetaSearchEngine)
- engine.settings_snapshot = {}
- engine.use_api_key_services = False
-
- with patch(
- f"{MODULE}.get_available_engines",
- return_value={
- "brave": {"requires_api_key": False, "reliability": 0.7}
- },
- ):
- available = engine._get_available_engines()
-
- assert "brave" in available
- assert "tavily" not in available
diff --git a/tests/web_search_engines/engines/test_parallel_search_coverage.py b/tests/web_search_engines/engines/test_parallel_search_coverage.py
deleted file mode 100644
index d0675f7fdb..0000000000
--- a/tests/web_search_engines/engines/test_parallel_search_coverage.py
+++ /dev/null
@@ -1,531 +0,0 @@
-"""
-Additional coverage tests for parallel_search_engine.py.
-
-Targets ~41 missing statements focusing on:
-- shutdown_global_executor error/finally paths
-- _get_global_executor failure path (ThreadPoolExecutor raises)
-- _get_available_engines branching: local engine warning, no is_public flag,
- scientific mode filtering, requires_api_key + use_api_key_services=False
-- _get_available_generic_engines: engine not in available, load failure, is_generic
-- select_engines: no specialized engines (only generic), LLM returns indices that
- partially match, include_generic_engines=False fallback on error
-- _get_previews: no engines selected, executor=None path, future raises exception
-- _get_full_content: engine._get_full_content raises exception (fallback to items)
-- close method
-"""
-
-import concurrent.futures
-from unittest.mock import Mock, patch
-
-MODULE = "local_deep_research.web_search_engines.engines.parallel_search_engine"
-
-
-def _make_engine(settings=None, llm=None, **kwargs):
- """Helper to create a ParallelSearchEngine in programmatic mode."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- if llm is None:
- llm = Mock()
- if settings is None:
- settings = {"search.max_results": {"value": 10}}
- return ParallelSearchEngine(
- llm=llm, settings_snapshot=settings, programmatic_mode=True, **kwargs
- )
-
-
-# ---------------------------------------------------------------------------
-# shutdown_global_executor
-# ---------------------------------------------------------------------------
-
-
-class TestShutdownGlobalExecutor:
- def test_shutdown_when_executor_is_none_does_nothing(self):
- """Calling shutdown when executor is None should not raise."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- shutdown_global_executor,
- )
-
- with patch(f"{MODULE}._global_executor", None):
- shutdown_global_executor(wait=False) # should not raise
-
-
-# ---------------------------------------------------------------------------
-# _get_global_executor failure path
-# ---------------------------------------------------------------------------
-
-
-class TestGetGlobalExecutorFailure:
- def test_returns_none_when_threadpoolexecutor_raises(self):
- """If ThreadPoolExecutor() raises, _get_global_executor returns None."""
- from local_deep_research.web_search_engines.engines import (
- parallel_search_engine as mod,
- )
-
- original = mod._global_executor
- mod._global_executor = None
- try:
- with patch(
- f"{MODULE}.concurrent.futures.ThreadPoolExecutor",
- side_effect=OSError("no threads"),
- ):
- result = mod._get_global_executor()
- finally:
- mod._global_executor = original or mod._get_global_executor()
-
- assert result is None
-
-
-# ---------------------------------------------------------------------------
-# _get_available_engines branching
-# ---------------------------------------------------------------------------
-
-
-class TestGetAvailableEnginesBranching:
- def _make_engine_class(
- self, is_public=True, is_scientific=False, is_generic=False
- ):
- cls = Mock()
- cls.is_public = is_public
- cls.is_scientific = is_scientific
- cls.is_generic = is_generic
- return cls
-
- def test_local_engine_warning_when_allow_local_engines(self):
- """When allow_local_engines=True and is_public=False, engine is included with warning."""
- engine = _make_engine(allow_local_engines=True)
-
- fake_class = self._make_engine_class(is_public=False)
- config_data = {"mylocal": {"requires_api_key": False}}
-
- with (
- patch(f"{MODULE}.get_available_engines", return_value=config_data),
- patch(
- f"{MODULE}.BaseSearchEngine._load_engine_class",
- return_value=(True, fake_class, ""),
- ),
- ):
- result = engine._get_available_engines()
-
- assert "mylocal" in result
-
- def test_engine_skipped_when_no_is_public_flag_and_local_not_allowed(self):
- """Engines without is_public attribute are skipped when allow_local_engines=False."""
- engine = _make_engine(allow_local_engines=False)
-
- fake_class = Mock(spec=[]) # no is_public attribute
- config_data = {"nopublic": {"requires_api_key": False}}
-
- with (
- patch(f"{MODULE}.get_available_engines", return_value=config_data),
- patch(
- f"{MODULE}.BaseSearchEngine._load_engine_class",
- return_value=(True, fake_class, ""),
- ),
- ):
- result = engine._get_available_engines()
-
- assert "nopublic" not in result
-
- def test_engine_included_when_no_is_public_flag_and_local_allowed(self):
- """Engines without is_public attribute are included when allow_local_engines=True."""
- engine = _make_engine(allow_local_engines=True)
-
- fake_class = Mock(spec=[]) # no is_public attribute
- config_data = {"nopublic": {"requires_api_key": False}}
-
- with (
- patch(f"{MODULE}.get_available_engines", return_value=config_data),
- patch(
- f"{MODULE}.BaseSearchEngine._load_engine_class",
- return_value=(True, fake_class, ""),
- ),
- ):
- result = engine._get_available_engines()
-
- assert "nopublic" in result
-
- def test_scientific_mode_skips_non_scientific_non_generic(self):
- """In SCIENTIFIC mode, engines that are neither scientific nor generic are skipped."""
- from local_deep_research.utilities.enums import SearchMode
-
- engine = _make_engine(search_mode=SearchMode.SCIENTIFIC)
-
- fake_class = self._make_engine_class(
- is_public=True, is_scientific=False, is_generic=False
- )
- config_data = {"specialised": {"requires_api_key": False}}
-
- with (
- patch(f"{MODULE}.get_available_engines", return_value=config_data),
- patch(
- f"{MODULE}.BaseSearchEngine._load_engine_class",
- return_value=(True, fake_class, ""),
- ),
- ):
- result = engine._get_available_engines()
-
- assert "specialised" not in result
-
- def test_scientific_mode_includes_scientific_engine(self):
- """In SCIENTIFIC mode, scientific engines are included."""
- from local_deep_research.utilities.enums import SearchMode
-
- engine = _make_engine(search_mode=SearchMode.SCIENTIFIC)
-
- fake_class = self._make_engine_class(
- is_public=True, is_scientific=True, is_generic=False
- )
- config_data = {"arxiv_like": {"requires_api_key": False}}
-
- with (
- patch(f"{MODULE}.get_available_engines", return_value=config_data),
- patch(
- f"{MODULE}.BaseSearchEngine._load_engine_class",
- return_value=(True, fake_class, ""),
- ),
- ):
- result = engine._get_available_engines()
-
- assert "arxiv_like" in result
-
- def test_skips_api_key_engine_when_use_api_key_services_false(self):
- """Engine requiring API key is filtered by shared get_available_engines."""
- engine = _make_engine(use_api_key_services=False)
-
- fake_class = self._make_engine_class(is_public=True)
- # Shared function already filters paid engines when use_api_key_services=False
- config_data = {"freeengine": {"requires_api_key": False}}
-
- with (
- patch(f"{MODULE}.get_available_engines", return_value=config_data),
- patch(
- f"{MODULE}.BaseSearchEngine._load_engine_class",
- return_value=(True, fake_class, ""),
- ),
- ):
- result = engine._get_available_engines()
-
- assert "paidengine" not in result
- assert "freeengine" in result
-
-
-# ---------------------------------------------------------------------------
-# _get_available_generic_engines branching
-# ---------------------------------------------------------------------------
-
-
-class TestGetAvailableGenericEnginesBranching:
- def test_skips_engine_not_in_available_engines(self):
- """Engine not in available_engines is skipped."""
- engine = _make_engine()
- engine.available_engines = ["eng_a"] # eng_b is absent
-
- config_data = {"eng_b": {}}
-
- with patch.object(
- engine, "_get_search_config", return_value=config_data
- ):
- result = engine._get_available_generic_engines()
-
- assert "eng_b" not in result
-
- def test_skips_engine_when_load_class_fails(self):
- """Engine whose class cannot be loaded is skipped."""
- engine = _make_engine()
- engine.available_engines = ["faileng"]
- config_data = {"faileng": {}}
-
- with (
- patch(f"{MODULE}.get_available_engines", return_value=config_data),
- patch(
- f"{MODULE}.BaseSearchEngine._load_engine_class",
- return_value=(False, None, "load error"),
- ),
- ):
- result = engine._get_available_generic_engines()
-
- assert "faileng" not in result
-
- def test_includes_generic_engine(self):
- """Engine with is_generic=True is included."""
- engine = _make_engine()
- engine.available_engines = ["gen_engine"]
- config_data = {"gen_engine": {}}
-
- fake_class = Mock()
- fake_class.is_generic = True
-
- with (
- patch(f"{MODULE}.get_available_engines", return_value=config_data),
- patch(
- f"{MODULE}.BaseSearchEngine._load_engine_class",
- return_value=(True, fake_class, ""),
- ),
- ):
- result = engine._get_available_generic_engines()
-
- assert "gen_engine" in result
-
- def test_excludes_non_generic_engine(self):
- """Engine with is_generic=False is excluded."""
- engine = _make_engine()
- engine.available_engines = ["spec_engine"]
- config_data = {"spec_engine": {}}
-
- fake_class = Mock()
- fake_class.is_generic = False
-
- with (
- patch(f"{MODULE}.get_available_engines", return_value=config_data),
- patch(
- f"{MODULE}.BaseSearchEngine._load_engine_class",
- return_value=(True, fake_class, ""),
- ),
- ):
- result = engine._get_available_generic_engines()
-
- assert "spec_engine" not in result
-
-
-# ---------------------------------------------------------------------------
-# select_engines: only generic engines available
-# ---------------------------------------------------------------------------
-
-
-class TestSelectEnginesOnlyGeneric:
- def test_returns_generic_engines_when_no_specialized(self):
- """When all available engines are generic, returns them without LLM call."""
- engine = _make_engine(include_generic_engines=True)
- engine.available_engines = ["ddg", "brave"]
-
- with patch.object(
- engine,
- "_get_available_generic_engines",
- return_value=["ddg", "brave"],
- ):
- result = engine.select_engines("any query")
-
- # LLM should not be called; generic engines returned directly
- assert "ddg" in result
- assert "brave" in result
- engine.llm.invoke.assert_not_called()
-
- def test_select_engines_fallback_includes_generic_on_llm_error_with_include_generic_false(
- self,
- ):
- """When include_generic_engines=False and LLM errors, returns available engines."""
- mock_llm = Mock()
- mock_llm.invoke.side_effect = RuntimeError("LLM down")
- engine = _make_engine(llm=mock_llm, include_generic_engines=False)
- engine.available_engines = ["eng1", "eng2"]
-
- result = engine.select_engines("query")
-
- assert isinstance(result, list)
- # should contain available engines as fallback
- assert set(result).issubset({"eng1", "eng2"})
-
- def test_select_engines_llm_returns_out_of_range_indices(self):
- """LLM returns indices out of range; valid ones are used, rest ignored."""
- mock_llm = Mock()
- mock_llm.invoke.return_value = Mock(content="[0, 999]")
- engine = _make_engine(llm=mock_llm, include_generic_engines=False)
- engine.available_engines = ["pubmed", "arxiv"]
-
- result = engine.select_engines("science query")
-
- # Index 0 is valid (pubmed), 999 is out of range - only pubmed selected
- assert "pubmed" in result
- assert "arxiv" not in result # index 1 was not in LLM response
-
-
-# ---------------------------------------------------------------------------
-# _get_previews: executor=None and future raises
-# ---------------------------------------------------------------------------
-
-
-class TestGetPreviewsEdgeCases:
- def test_get_previews_returns_empty_when_executor_none(self):
- """Returns empty list when global executor is None."""
- engine = _make_engine()
- engine.available_engines = ["eng1"]
-
- with (
- patch.object(engine, "select_engines", return_value=["eng1"]),
- patch(f"{MODULE}._get_global_executor", return_value=None),
- ):
- result = engine._get_previews("query")
-
- assert result == []
-
- def test_get_previews_handles_future_exception(self):
- """Results from futures that raise are stored as failure."""
- engine = _make_engine()
- engine.available_engines = ["bad_eng"]
-
- # Build a future that raises when .result() is called
- future = concurrent.futures.Future()
- future.set_exception(RuntimeError("thread crash"))
-
- mock_executor = Mock()
- mock_executor.submit.return_value = future
-
- with (
- patch.object(engine, "select_engines", return_value=["bad_eng"]),
- patch(f"{MODULE}._get_global_executor", return_value=mock_executor),
- patch(
- f"{MODULE}.concurrent.futures.as_completed",
- return_value=[future],
- ),
- ):
- result = engine._get_previews("query")
-
- # No crash; bad engine counted as failure; all_results empty
- assert isinstance(result, list)
- assert result == []
-
- def test_get_previews_collects_results_on_success(self):
- """Successful engine results are aggregated and source-tagged."""
- engine = _make_engine()
- engine.available_engines = ["good_eng"]
-
- future = concurrent.futures.Future()
- future.set_result(
- {
- "engine": "good_eng",
- "success": True,
- "results": [{"title": "T", "link": "http://x.com"}],
- "count": 1,
- }
- )
-
- mock_executor = Mock()
- mock_executor.submit.return_value = future
-
- with (
- patch.object(engine, "select_engines", return_value=["good_eng"]),
- patch(f"{MODULE}._get_global_executor", return_value=mock_executor),
- patch(
- f"{MODULE}.concurrent.futures.as_completed",
- return_value=[future],
- ),
- ):
- result = engine._get_previews("query")
-
- assert len(result) == 1
- assert result[0]["search_engine"] == "good_eng"
-
- def test_get_previews_failed_engine_returns_no_results(self):
- """A failed engine contributes no results and does not crash."""
- engine = _make_engine()
- engine.available_engines = ["fail_eng"]
-
- future = concurrent.futures.Future()
- future.set_result(
- {
- "engine": "fail_eng",
- "success": False,
- "error": "timeout",
- "results": [],
- }
- )
-
- mock_executor = Mock()
- mock_executor.submit.return_value = future
-
- with (
- patch.object(engine, "select_engines", return_value=["fail_eng"]),
- patch(f"{MODULE}._get_global_executor", return_value=mock_executor),
- patch(
- f"{MODULE}.concurrent.futures.as_completed",
- return_value=[future],
- ),
- ):
- result = engine._get_previews("query")
-
- assert result == []
-
-
-# ---------------------------------------------------------------------------
-# _get_full_content: engine raises on _get_full_content
-# ---------------------------------------------------------------------------
-
-
-class TestGetFullContentException:
- def test_falls_back_to_items_when_engine_full_content_raises(self):
- """When engine._get_full_content raises, items are returned as-is."""
- engine = _make_engine()
-
- mock_sub_engine = Mock()
- mock_sub_engine._get_full_content.side_effect = RuntimeError(
- "full content error"
- )
- engine.engine_cache["eng_x"] = mock_sub_engine
-
- items = [
- {"title": "A", "url": "http://a.com", "search_engine": "eng_x"}
- ]
-
- with (
- patch(f"{MODULE}.get_setting_from_snapshot", return_value=False),
- patch.object(
- engine, "_get_engine_instance", return_value=mock_sub_engine
- ),
- ):
- result = engine._get_full_content(items)
-
- # Falls back to original items
- assert len(result) == 1
- assert result[0]["title"] == "A"
-
- def test_returns_items_when_no_search_engine_key(self):
- """Items without search_engine key are not grouped and not returned (no engine)."""
- engine = _make_engine()
-
- items = [{"title": "NoEngine", "url": "http://b.com"}]
-
- with patch(f"{MODULE}.get_setting_from_snapshot", return_value=False):
- result = engine._get_full_content(items)
-
- # Items with no search_engine key produce empty all_full_content
- assert result == []
-
-
-# ---------------------------------------------------------------------------
-# close method
-# ---------------------------------------------------------------------------
-
-
-class TestCloseMethod:
- def test_close_clears_engine_cache(self):
- """close() clears the engine cache."""
- engine = _make_engine()
-
- mock_child = Mock()
- engine.engine_cache["child1"] = mock_child
-
- with patch(
- "local_deep_research.utilities.resource_utils.safe_close"
- ) as mock_safe_close:
- engine.close()
-
- mock_safe_close.assert_called_once_with(
- mock_child, "child search engine"
- )
- assert engine.engine_cache == {}
-
- def test_close_calls_super(self):
- """close() calls parent close()."""
- engine = _make_engine()
-
- with (
- patch("local_deep_research.utilities.resource_utils.safe_close"),
- patch(
- "local_deep_research.web_search_engines.search_engine_base.BaseSearchEngine.close"
- ) as mock_super_close,
- ):
- engine.close()
-
- mock_super_close.assert_called_once()
diff --git a/tests/web_search_engines/engines/test_parallel_search_engine.py b/tests/web_search_engines/engines/test_parallel_search_engine.py
deleted file mode 100644
index 33f8ea1b27..0000000000
--- a/tests/web_search_engines/engines/test_parallel_search_engine.py
+++ /dev/null
@@ -1,782 +0,0 @@
-"""
-Tests for the ParallelSearchEngine class.
-
-Tests cover:
-- Initialization and configuration
-- Engine selection logic
-- Parallel execution
-- Result aggregation
-- Error handling
-- Global executor management
-- API key availability checking
-- Engine instance caching
-"""
-
-from unittest.mock import Mock, patch
-
-from local_deep_research.utilities.enums import SearchMode
-
-
-class TestParallelSearchEngineInit:
- """Tests for ParallelSearchEngine initialization."""
-
- def test_init_with_defaults(self):
- """Initialize with default values."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- engine = ParallelSearchEngine(
- llm=mock_llm, settings_snapshot=settings, programmatic_mode=True
- )
-
- assert engine.llm is mock_llm
- assert engine.max_results == 10
-
- def test_init_with_custom_max_results(self):
- """Initialize with custom max_results."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- engine = ParallelSearchEngine(
- llm=mock_llm,
- max_results=25,
- settings_snapshot=settings,
- programmatic_mode=True,
- )
-
- assert engine.max_results == 25
-
- def test_init_stores_settings_snapshot(self):
- """Initialize stores settings snapshot."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_llm = Mock()
- settings = {
- "search.max_results": {"value": 10},
- "custom_key": {"value": "test"},
- }
-
- engine = ParallelSearchEngine(
- llm=mock_llm, settings_snapshot=settings, programmatic_mode=True
- )
-
- assert engine.settings_snapshot == settings
-
- def test_init_with_max_filtered_results(self):
- """Initialize with custom max_filtered_results."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- engine = ParallelSearchEngine(
- llm=mock_llm,
- settings_snapshot=settings,
- programmatic_mode=True,
- max_filtered_results=100,
- )
-
- assert engine.max_filtered_results == 100
-
- def test_init_default_max_filtered_results_is_50(self):
- """Default max_filtered_results is 50 for parallel search."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- engine = ParallelSearchEngine(
- llm=mock_llm, settings_snapshot=settings, programmatic_mode=True
- )
-
- assert engine.max_filtered_results == 50
-
- def test_init_with_use_api_key_services_false(self):
- """Initialize with use_api_key_services disabled."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- engine = ParallelSearchEngine(
- llm=mock_llm,
- settings_snapshot=settings,
- programmatic_mode=True,
- use_api_key_services=False,
- )
-
- assert engine.use_api_key_services is False
-
- def test_init_with_allow_local_engines(self):
- """Initialize with allow_local_engines enabled."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- engine = ParallelSearchEngine(
- llm=mock_llm,
- settings_snapshot=settings,
- programmatic_mode=True,
- allow_local_engines=True,
- )
-
- assert engine.allow_local_engines is True
-
- def test_init_with_scientific_search_mode(self):
- """Initialize with scientific search mode."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- engine = ParallelSearchEngine(
- llm=mock_llm,
- settings_snapshot=settings,
- programmatic_mode=True,
- search_mode=SearchMode.SCIENTIFIC,
- )
-
- assert engine.search_mode == SearchMode.SCIENTIFIC
-
- def test_init_disables_llm_relevance_filter_by_default(self):
- """LLM relevance filter is disabled by default at parallel level."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- engine = ParallelSearchEngine(
- llm=mock_llm, settings_snapshot=settings, programmatic_mode=True
- )
-
- assert engine.enable_llm_relevance_filter is False
-
-
-class TestParallelSearchEngineClassAttributes:
- """Tests for ParallelSearchEngine class attributes."""
-
- def test_class_attributes_exist(self):
- """ParallelSearchEngine has expected class attributes."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- # Check that expected attributes exist
- assert hasattr(ParallelSearchEngine, "is_public")
- assert hasattr(ParallelSearchEngine, "is_generic")
-
-
-class TestGlobalExecutorManagement:
- """Tests for global executor management."""
-
- def test_get_global_executor_returns_executor(self):
- """_get_global_executor returns a ThreadPoolExecutor."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- _get_global_executor,
- )
-
- executor = _get_global_executor()
-
- assert executor is not None
-
- def test_get_global_executor_same_instance(self):
- """_get_global_executor returns same instance on subsequent calls."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- _get_global_executor,
- )
-
- executor1 = _get_global_executor()
- executor2 = _get_global_executor()
-
- assert executor1 is executor2
-
- def test_shutdown_global_executor(self):
- """shutdown_global_executor shuts down the executor."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- _get_global_executor,
- shutdown_global_executor,
- )
-
- # Ensure executor exists
- executor = _get_global_executor()
- assert executor is not None
-
- # Shutdown
- shutdown_global_executor(wait=True)
-
- # Note: After shutdown, _global_executor should be None
- # but we can't directly test this due to module-level state
-
-
-class TestParallelSearchEngineGetPreviews:
- """Tests for _get_previews method."""
-
- def test_get_previews_returns_list(self):
- """_get_previews returns a list."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- engine = ParallelSearchEngine(
- llm=mock_llm, settings_snapshot=settings, programmatic_mode=True
- )
-
- # With no engines configured, should return empty list
- results = engine._get_previews("test query")
-
- assert isinstance(results, list)
-
- def test_get_previews_with_empty_engines(self):
- """_get_previews handles empty engines."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- engine = ParallelSearchEngine(
- llm=mock_llm, settings_snapshot=settings, programmatic_mode=True
- )
-
- # Should not raise even with no engines
- results = engine._get_previews("test query")
-
- assert results == []
-
-
-class TestParallelSearchEngineRun:
- """Tests for run method."""
-
- def test_run_returns_list(self):
- """run method returns a list."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- engine = ParallelSearchEngine(
- llm=mock_llm, settings_snapshot=settings, programmatic_mode=True
- )
-
- results = engine.run("test query")
-
- assert isinstance(results, list)
-
-
-class TestParallelSearchEngineGetFullContent:
- """Tests for _get_full_content method."""
-
- def test_get_full_content_returns_items(self):
- """_get_full_content returns the input items."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- engine = ParallelSearchEngine(
- llm=mock_llm, settings_snapshot=settings, programmatic_mode=True
- )
-
- items = [
- {"title": "Result 1", "url": "http://a.com", "snippet": "Text 1"},
- {"title": "Result 2", "url": "http://b.com", "snippet": "Text 2"},
- ]
-
- result = engine._get_full_content(items)
-
- # ParallelSearchEngine typically returns items as-is
- assert len(result) == 2
-
-
-class TestParallelSearchEngineScientificMode:
- """Tests for scientific parallel search mode."""
-
- def test_creates_scientific_engine(self):
- """Can create scientific parallel search engine."""
- from local_deep_research.web_search_engines.search_engine_factory import (
- create_search_engine,
- )
-
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- engine = create_search_engine(
- engine_name="parallel_scientific",
- llm=mock_llm,
- settings_snapshot=settings,
- )
-
- assert engine is not None
- assert "ParallelSearchEngine" in type(engine).__name__
-
- def test_creates_standard_parallel_engine(self):
- """Can create standard parallel search engine."""
- from local_deep_research.web_search_engines.search_engine_factory import (
- create_search_engine,
- )
-
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- engine = create_search_engine(
- engine_name="parallel",
- llm=mock_llm,
- settings_snapshot=settings,
- )
-
- assert engine is not None
- assert "ParallelSearchEngine" in type(engine).__name__
-
-
-class TestResolveApiKey:
- """Tests for the shared _resolve_api_key helper used by get_available_engines."""
-
- def test_returns_key_from_snapshot(self):
- """Returns API key found in settings snapshot."""
- from local_deep_research.web_search_engines.search_engines_config import (
- _resolve_api_key,
- )
-
- snapshot = {
- "search.engine.web.brave.api_key": {"value": "brave-key-123"},
- }
- result = _resolve_api_key("brave", {}, snapshot)
- assert result == "brave-key-123"
-
- def test_returns_key_from_engine_config_fallback(self):
- """Falls back to api_key in engine config dict."""
- from local_deep_research.web_search_engines.search_engines_config import (
- _resolve_api_key,
- )
-
- result = _resolve_api_key("brave", {"api_key": "config-key"}, {})
- assert result == "config-key"
-
- def test_returns_none_when_no_key(self):
- """Returns None when no API key is available."""
- from local_deep_research.web_search_engines.search_engines_config import (
- _resolve_api_key,
- )
-
- result = _resolve_api_key("brave", {}, {})
- assert result is None
-
- def test_rejects_placeholder_values(self):
- """Rejects common placeholder API key values."""
- from local_deep_research.web_search_engines.search_engines_config import (
- _resolve_api_key,
- )
-
- for placeholder in [
- "PLACEHOLDER",
- "YOUR_API_KEY_HERE",
- "null",
- "None",
- "YOUR_key",
- "BRAVE_API_KEY",
- ]:
- result = _resolve_api_key("test", {"api_key": placeholder}, {})
- assert result is None, f"Should reject placeholder: {placeholder}"
-
- def test_rejects_empty_and_whitespace(self):
- """Rejects empty or whitespace-only API keys."""
- from local_deep_research.web_search_engines.search_engines_config import (
- _resolve_api_key,
- )
-
- result = _resolve_api_key("test", {"api_key": " "}, {})
- assert result is None
-
-
-class TestGetSearchConfig:
- """Tests for _get_search_config method (now delegates to get_available_engines)."""
-
- def test_returns_empty_dict_without_settings_snapshot(self):
- """Returns empty dict when no settings snapshot."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_llm = Mock()
-
- engine = ParallelSearchEngine(
- llm=mock_llm, settings_snapshot=None, programmatic_mode=True
- )
-
- config = engine._get_search_config()
-
- assert config == {}
-
-
-class TestSelectEngines:
- """Tests for select_engines method."""
-
- def test_returns_all_engines_without_llm(self):
- """Returns all available engines when no LLM."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- settings = {"search.max_results": {"value": 10}}
-
- engine = ParallelSearchEngine(
- llm=None, settings_snapshot=settings, programmatic_mode=True
- )
- engine.available_engines = ["engine1", "engine2", "engine3"]
-
- result = engine.select_engines("test query")
-
- assert len(result) <= engine.max_engines_to_select
-
- def test_returns_empty_when_no_available_engines(self):
- """Returns empty when no available engines."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- engine = ParallelSearchEngine(
- llm=mock_llm, settings_snapshot=settings, programmatic_mode=True
- )
- engine.available_engines = []
-
- result = engine.select_engines("test query")
-
- assert result == []
-
- def test_llm_selects_engines_from_list(self):
- """LLM selects engines from available list."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_llm = Mock()
- mock_llm.invoke.return_value = Mock(content="[0, 1]")
- settings = {"search.max_results": {"value": 10}}
-
- engine = ParallelSearchEngine(
- llm=mock_llm,
- settings_snapshot=settings,
- programmatic_mode=True,
- include_generic_engines=False,
- )
- engine.available_engines = ["pubmed", "arxiv", "openalex"]
-
- result = engine.select_engines("cancer research")
-
- assert "pubmed" in result
- assert "arxiv" in result
-
- def test_handles_llm_error_gracefully(self):
- """Handles LLM error and returns fallback engines."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_llm = Mock()
- mock_llm.invoke.side_effect = Exception("LLM error")
- settings = {"search.max_results": {"value": 10}}
-
- engine = ParallelSearchEngine(
- llm=mock_llm, settings_snapshot=settings, programmatic_mode=True
- )
- engine.available_engines = ["engine1", "engine2"]
-
- result = engine.select_engines("test query")
-
- # Should return some engines despite error
- assert isinstance(result, list)
-
- def test_handles_invalid_llm_response(self):
- """Handles invalid LLM JSON response."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_llm = Mock()
- mock_llm.invoke.return_value = Mock(content="not valid json")
- settings = {"search.max_results": {"value": 10}}
-
- engine = ParallelSearchEngine(
- llm=mock_llm, settings_snapshot=settings, programmatic_mode=True
- )
- engine.available_engines = ["engine1", "engine2"]
-
- result = engine.select_engines("test query")
-
- # Should return fallback engines
- assert isinstance(result, list)
-
-
-class TestGetEngineInstance:
- """Tests for _get_engine_instance method."""
-
- def test_caches_engine_instances(self):
- """Engine instances are cached."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- engine = ParallelSearchEngine(
- llm=mock_llm, settings_snapshot=settings, programmatic_mode=True
- )
-
- mock_search_engine = Mock()
- with patch(
- "local_deep_research.web_search_engines.engines.parallel_search_engine.create_search_engine",
- return_value=mock_search_engine,
- ):
- # First call creates instance
- instance1 = engine._get_engine_instance("test_engine")
- # Second call returns cached instance
- instance2 = engine._get_engine_instance("test_engine")
-
- assert instance1 is instance2
-
- def test_returns_none_on_creation_error(self):
- """Returns None when engine creation fails."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- engine = ParallelSearchEngine(
- llm=mock_llm, settings_snapshot=settings, programmatic_mode=True
- )
-
- with patch(
- "local_deep_research.web_search_engines.engines.parallel_search_engine.create_search_engine",
- side_effect=Exception("Creation error"),
- ):
- result = engine._get_engine_instance("failing_engine")
-
- assert result is None
-
-
-class TestExecuteSingleEngine:
- """Tests for _execute_single_engine method."""
-
- def test_returns_success_with_results(self):
- """Returns success result when engine returns results."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- engine = ParallelSearchEngine(
- llm=mock_llm, settings_snapshot=settings, programmatic_mode=True
- )
-
- mock_search_engine = Mock()
- mock_search_engine.run.return_value = [
- {"title": "Result 1", "link": "http://example.com"}
- ]
- engine.engine_cache["test_engine"] = mock_search_engine
-
- result = engine._execute_single_engine("test_engine", "test query")
-
- assert result["success"] is True
- assert result["engine"] == "test_engine"
- assert len(result["results"]) == 1
-
- def test_returns_failure_when_no_engine(self):
- """Returns failure when engine cannot be instantiated."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- engine = ParallelSearchEngine(
- llm=mock_llm, settings_snapshot=settings, programmatic_mode=True
- )
-
- with patch.object(engine, "_get_engine_instance", return_value=None):
- result = engine._execute_single_engine("missing_engine", "query")
-
- assert result["success"] is False
- assert "Failed to initialize" in result["error"]
-
- def test_returns_failure_when_no_results(self):
- """Returns failure when engine returns no results."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- engine = ParallelSearchEngine(
- llm=mock_llm, settings_snapshot=settings, programmatic_mode=True
- )
-
- mock_search_engine = Mock()
- mock_search_engine.run.return_value = []
- engine.engine_cache["test_engine"] = mock_search_engine
-
- result = engine._execute_single_engine("test_engine", "test query")
-
- assert result["success"] is False
- assert result["error"] == "No results"
-
- def test_handles_engine_exception(self):
- """Handles exception from engine execution."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- engine = ParallelSearchEngine(
- llm=mock_llm, settings_snapshot=settings, programmatic_mode=True
- )
-
- mock_search_engine = Mock()
- mock_search_engine.run.side_effect = Exception("Search error")
- engine.engine_cache["test_engine"] = mock_search_engine
-
- result = engine._execute_single_engine("test_engine", "test query")
-
- assert result["success"] is False
- assert "failed" in result["error"].lower()
-
-
-class TestGetFullContentWithGrouping:
- """Tests for _get_full_content with engine grouping."""
-
- def test_groups_items_by_engine(self):
- """Groups items by their source engine."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_llm = Mock()
- settings = {
- "search.max_results": {"value": 10},
- "search.snippets_only": {"value": False},
- }
-
- engine = ParallelSearchEngine(
- llm=mock_llm, settings_snapshot=settings, programmatic_mode=True
- )
-
- # Create mock engines in cache
- mock_engine1 = Mock()
- mock_engine1._get_full_content.return_value = [
- {"title": "Result 1", "full_content": "Full 1"}
- ]
- mock_engine2 = Mock()
- mock_engine2._get_full_content.return_value = [
- {"title": "Result 2", "full_content": "Full 2"}
- ]
-
- engine.engine_cache["engine1"] = mock_engine1
- engine.engine_cache["engine2"] = mock_engine2
-
- items = [
- {"title": "Result 1", "search_engine": "engine1"},
- {"title": "Result 2", "search_engine": "engine2"},
- ]
-
- # Mock get_setting_from_snapshot to return False for snippets_only
- with patch(
- "local_deep_research.web_search_engines.engines.parallel_search_engine.get_setting_from_snapshot",
- return_value=False,
- ):
- engine._get_full_content(items)
-
- mock_engine1._get_full_content.assert_called_once()
- mock_engine2._get_full_content.assert_called_once()
-
- def test_handles_missing_engine_gracefully(self):
- """Returns items as-is when engine not in cache."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_llm = Mock()
- settings = {
- "search.max_results": {"value": 10},
- "search.snippets_only": {"value": False},
- }
-
- engine = ParallelSearchEngine(
- llm=mock_llm, settings_snapshot=settings, programmatic_mode=True
- )
-
- with patch.object(engine, "_get_engine_instance", return_value=None):
- items = [
- {"title": "Result 1", "search_engine": "missing_engine"},
- ]
-
- result = engine._get_full_content(items)
-
- assert len(result) == 1
- assert result[0]["title"] == "Result 1"
-
-
-class TestInvoke:
- """Tests for invoke method."""
-
- def test_invoke_delegates_to_run(self):
- """Invoke method delegates to run."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
-
- engine = ParallelSearchEngine(
- llm=mock_llm, settings_snapshot=settings, programmatic_mode=True
- )
-
- with patch.object(
- engine, "run", return_value=[{"title": "Result"}]
- ) as mock_run:
- result = engine.invoke("test query")
-
- mock_run.assert_called_once_with("test query")
- assert result == [{"title": "Result"}]
diff --git a/tests/web_search_engines/engines/test_parallel_search_engine_concurrency.py b/tests/web_search_engines/engines/test_parallel_search_engine_concurrency.py
deleted file mode 100644
index 62bf838dec..0000000000
--- a/tests/web_search_engines/engines/test_parallel_search_engine_concurrency.py
+++ /dev/null
@@ -1,140 +0,0 @@
-"""Regression tests for thread-local leak prevention in ParallelSearchEngine.
-
-These tests pin the executor to ``max_workers=1`` so two back-to-back
-submissions are guaranteed to land on the same worker thread, which is
-the scenario where leaks would be observable.
-"""
-
-import concurrent.futures
-from unittest.mock import Mock, patch
-
-from local_deep_research.database.thread_metrics import metrics_writer
-from local_deep_research.utilities.thread_context import (
- get_search_context,
- set_search_context,
- clear_search_context,
-)
-
-
-class TestParallelSearchEngineThreadLocalIsolation:
- """Verify the submit-site wrapper in ``_get_previews`` cleans up
- thread-local state (search_context + metrics_writer passwords) so that
- the next task on the same worker starts with a clean slate."""
-
- def _make_pinned_executor(self):
- return concurrent.futures.ThreadPoolExecutor(
- max_workers=1, thread_name_prefix="test_pinned_"
- )
-
- def _make_engine(self):
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_llm = Mock()
- settings = {"search.max_results": {"value": 10}}
- return ParallelSearchEngine(
- llm=mock_llm,
- settings_snapshot=settings,
- programmatic_mode=True,
- )
-
- def test_worker_thread_has_no_stale_context_between_tasks(self):
- """First task contaminates the worker's thread-local state; the
- second task's pre-run snapshot must show that state cleared."""
- from local_deep_research.web_search_engines.engines import (
- parallel_search_engine as pse_mod,
- )
-
- engine = self._make_engine()
-
- # Record what the worker thread sees at task entry.
- entry_snapshots: list[dict] = []
- dirty_writes = {"userA_pw": "secret_A"}
-
- def fake_execute(self_engine, engine_name, query):
- entry_snapshots.append(
- {
- "engine_name": engine_name,
- "search_context": get_search_context(),
- "passwords_copy": dict(
- getattr(metrics_writer._thread_local, "passwords", {})
- ),
- }
- )
- # Simulate a metrics call on the worker thread that writes a
- # password into thread-local storage mid-task. The submit-site
- # wrapper's finally must clear this before the next task runs.
- metrics_writer.set_user_password("userA", dirty_writes["userA_pw"])
- return {
- "engine": engine_name,
- "success": True,
- "results": [{"title": f"r-{engine_name}"}],
- "count": 1,
- }
-
- pinned = self._make_pinned_executor()
- try:
- with (
- patch.object(
- pse_mod, "_get_global_executor", return_value=pinned
- ),
- patch.object(
- engine,
- "select_engines",
- side_effect=[["engine_first"], ["engine_second"]],
- ),
- patch.object(
- pse_mod.ParallelSearchEngine,
- "_execute_single_engine",
- new=fake_execute,
- ),
- ):
- # First "request": submitter has a research context.
- set_search_context({"username": "userA", "research_id": "r-1"})
- try:
- engine._get_previews("q1")
- finally:
- clear_search_context()
-
- # Second "request": submitter has NO context (simulating a
- # different user whose code path didn't populate one, or a
- # background call).
- assert get_search_context() is None
- engine._get_previews("q2")
- finally:
- pinned.shutdown(wait=True)
-
- assert len(entry_snapshots) == 2, entry_snapshots
-
- # First task saw the submitter's context applied by _run_with_context.
- assert entry_snapshots[0]["search_context"] == {
- "username": "userA",
- "research_id": "r-1",
- }
-
- # Second task entered with a CLEAN worker thread: no context and no
- # lingering password from the first task's mid-run write.
- assert entry_snapshots[1]["search_context"] is None, (
- "Worker thread leaked search_context across tasks: "
- f"{entry_snapshots[1]['search_context']!r}"
- )
- assert entry_snapshots[1]["passwords_copy"] == {}, (
- "Worker thread leaked metrics_writer passwords across tasks: "
- f"{entry_snapshots[1]['passwords_copy']!r}"
- )
-
- def test_class_level_preserve_research_context_is_removed(self):
- """The class-def-time @preserve_research_context wrap was a no-op
- and has been removed. Its import should also be gone."""
- import inspect
-
- from local_deep_research.web_search_engines.engines import (
- parallel_search_engine as pse_mod,
- )
-
- source = inspect.getsource(pse_mod)
- assert "preserve_research_context" not in source, (
- "preserve_research_context should no longer be referenced in "
- "parallel_search_engine.py — the class-def usage was a no-op."
- )
diff --git a/tests/web_search_engines/test_engine_registry.py b/tests/web_search_engines/test_engine_registry.py
index 37cf14fb3e..6c5bfaf6fb 100644
--- a/tests/web_search_engines/test_engine_registry.py
+++ b/tests/web_search_engines/test_engine_registry.py
@@ -148,10 +148,12 @@ class TestRegistryCoverage:
f"these should be in engine_registry.py instead"
)
- def test_auto_engine_in_registry(self):
- """The 'auto' meta engine must be in the registry."""
- assert "auto" in ENGINE_REGISTRY
- assert ENGINE_REGISTRY["auto"].class_name == "MetaSearchEngine"
+ def test_removed_meta_engines_not_in_registry(self):
+ """The removed meta engines must not reappear in the registry."""
+ assert "auto" not in ENGINE_REGISTRY
+ assert "meta" not in ENGINE_REGISTRY
+ assert "parallel" not in ENGINE_REGISTRY
+ assert "parallel_scientific" not in ENGINE_REGISTRY
class TestEngineEntryDataclass:
@@ -243,8 +245,8 @@ class TestSearchConfigInjection:
assert result["brave"]["full_search_module"] == ".engines.full_search"
assert result["brave"]["full_search_class"] == "FullSearchResults"
- def test_auto_engine_gets_registry_data(self):
- """The auto engine should get module_path/class_name from registry."""
+ def test_removed_meta_engines_absent_from_search_config(self):
+ """search_config() should not contain the removed meta engines."""
from unittest.mock import patch
from local_deep_research.web_search_engines.search_engines_config import (
@@ -252,8 +254,6 @@ class TestSearchConfigInjection:
)
def mock_get_setting(key, default, **kwargs):
- if key == "search.engine.auto":
- return {"reliability": 0.85}
return default
with (
@@ -268,6 +268,7 @@ class TestSearchConfigInjection:
mock_registry.list_registered.return_value = []
result = search_config()
- assert "auto" in result
- assert result["auto"]["module_path"] == ".engines.meta_search_engine"
- assert result["auto"]["class_name"] == "MetaSearchEngine"
+ assert "auto" not in result
+ assert "meta" not in result
+ assert "parallel" not in result
+ assert "parallel_scientific" not in result
diff --git a/tests/web_search_engines/test_parallel_engine_filtering.py b/tests/web_search_engines/test_parallel_engine_filtering.py
deleted file mode 100644
index 26ce15abe3..0000000000
--- a/tests/web_search_engines/test_parallel_engine_filtering.py
+++ /dev/null
@@ -1,298 +0,0 @@
-"""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
-
-
-def mock_get_available():
- """Patch the shared get_available_engines function."""
- with patch(
- "local_deep_research.web_search_engines.engines.parallel_search_engine.get_available_engines"
- ) 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, mock_get_available
- ):
- """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()
- mock_get_available.return_value = {
- "arxiv": {},
- "searxng": {},
- "guardian": {},
- }
-
- engine = ParallelSearchEngine(
- llm=Mock(),
- search_mode=SearchMode.SCIENTIFIC,
- settings_snapshot={"search.max_results": 10},
- 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, mock_get_available
- ):
- """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()
- mock_get_available.return_value = {
- "local_rag": {},
- "searxng": {},
- }
-
- engine = ParallelSearchEngine(
- llm=Mock(),
- allow_local_engines=False,
- settings_snapshot={"search.max_results": 10},
- 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, mock_get_available
- ):
- """Self-referential engines (meta, auto, parallel) are already excluded
- by the shared get_available_engines function."""
- mock_load_engine_class.return_value = (
- True,
- make_engine_class(is_public=True, is_generic=True),
- None,
- )
- mock_executor.return_value = Mock()
- # Shared function excludes meta/auto/parallel, only returns searxng
- mock_get_available.return_value = {"searxng": {}}
-
- engine = ParallelSearchEngine(
- llm=Mock(),
- settings_snapshot={"search.max_results": 10},
- 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
-
- 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
-
- 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_parallel_search_engine.py b/tests/web_search_engines/test_parallel_search_engine.py
deleted file mode 100644
index 86a1cbfa57..0000000000
--- a/tests/web_search_engines/test_parallel_search_engine.py
+++ /dev/null
@@ -1,824 +0,0 @@
-"""
-Tests for the ParallelSearchEngine class.
-
-Tests cover:
-- Global executor management
-- Initialization
-- API key availability checking
-- Engine selection
-- Engine instance caching
-- Parallel execution
-- Full content retrieval
-"""
-
-import concurrent.futures
-from unittest.mock import Mock, patch
-
-
-from local_deep_research.utilities.enums import SearchMode
-
-
-class TestGlobalExecutor:
- """Tests for global executor functions."""
-
- def test_get_global_executor_creates_pool(self):
- """_get_global_executor creates a thread pool."""
- from local_deep_research.web_search_engines.engines import (
- parallel_search_engine,
- )
-
- # Reset global executor
- with parallel_search_engine._global_executor_lock:
- old_executor = parallel_search_engine._global_executor
- parallel_search_engine._global_executor = None
-
- try:
- executor = parallel_search_engine._get_global_executor(
- max_workers=2
- )
- assert executor is not None
- assert isinstance(executor, concurrent.futures.ThreadPoolExecutor)
- finally:
- # Restore
- with parallel_search_engine._global_executor_lock:
- if parallel_search_engine._global_executor:
- parallel_search_engine._global_executor.shutdown(wait=False)
- parallel_search_engine._global_executor = old_executor
-
- def test_get_global_executor_returns_cached(self):
- """_get_global_executor returns cached executor on subsequent calls."""
- from local_deep_research.web_search_engines.engines import (
- parallel_search_engine,
- )
-
- # Reset global executor
- with parallel_search_engine._global_executor_lock:
- old_executor = parallel_search_engine._global_executor
- parallel_search_engine._global_executor = None
-
- try:
- executor1 = parallel_search_engine._get_global_executor(
- max_workers=2
- )
- executor2 = parallel_search_engine._get_global_executor(
- max_workers=10
- )
-
- # Should be the same instance (max_workers ignored on second call)
- assert executor1 is executor2
- finally:
- # Restore
- with parallel_search_engine._global_executor_lock:
- if parallel_search_engine._global_executor:
- parallel_search_engine._global_executor.shutdown(wait=False)
- parallel_search_engine._global_executor = old_executor
-
- def test_shutdown_global_executor(self):
- """shutdown_global_executor shuts down and clears the pool."""
- from local_deep_research.web_search_engines.engines import (
- parallel_search_engine,
- )
-
- # Reset global executor
- with parallel_search_engine._global_executor_lock:
- old_executor = parallel_search_engine._global_executor
- parallel_search_engine._global_executor = None
-
- try:
- # Create an executor
- parallel_search_engine._get_global_executor(max_workers=2)
- assert parallel_search_engine._global_executor is not None
-
- # Shut it down
- parallel_search_engine.shutdown_global_executor(wait=True)
- assert parallel_search_engine._global_executor is None
- finally:
- # Restore
- with parallel_search_engine._global_executor_lock:
- parallel_search_engine._global_executor = old_executor
-
- def test_shutdown_global_executor_when_none(self):
- """shutdown_global_executor handles None executor gracefully."""
- from local_deep_research.web_search_engines.engines import (
- parallel_search_engine,
- )
-
- # Reset global executor
- with parallel_search_engine._global_executor_lock:
- old_executor = parallel_search_engine._global_executor
- parallel_search_engine._global_executor = None
-
- try:
- # Should not raise
- parallel_search_engine.shutdown_global_executor(wait=True)
- finally:
- # Restore
- with parallel_search_engine._global_executor_lock:
- parallel_search_engine._global_executor = old_executor
-
-
-class TestParallelSearchEngineInit:
- """Tests for ParallelSearchEngine initialization."""
-
- @patch(
- "local_deep_research.web_search_engines.engines.parallel_search_engine._get_global_executor"
- )
- def test_init_default_values(self, mock_get_executor):
- """ParallelSearchEngine initializes with default values."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_get_executor.return_value = Mock()
- mock_llm = Mock()
-
- with patch.object(
- ParallelSearchEngine, "_get_available_engines", return_value=[]
- ):
- engine = ParallelSearchEngine(llm=mock_llm)
-
- assert engine.use_api_key_services is True
- assert engine.max_engines_to_select == 100
- assert engine.allow_local_engines is False
- assert engine.include_generic_engines is True
- assert engine.search_mode == SearchMode.ALL
-
- @patch(
- "local_deep_research.web_search_engines.engines.parallel_search_engine._get_global_executor"
- )
- def test_init_custom_values(self, mock_get_executor):
- """ParallelSearchEngine initializes with custom values."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_get_executor.return_value = Mock()
- mock_llm = Mock()
-
- with patch.object(
- ParallelSearchEngine, "_get_available_engines", return_value=[]
- ):
- engine = ParallelSearchEngine(
- llm=mock_llm,
- use_api_key_services=False,
- max_engines_to_select=5,
- allow_local_engines=True,
- include_generic_engines=False,
- search_mode=SearchMode.SCIENTIFIC,
- )
-
- assert engine.use_api_key_services is False
- assert engine.max_engines_to_select == 5
- assert engine.allow_local_engines is True
- assert engine.include_generic_engines is False
- assert engine.search_mode == SearchMode.SCIENTIFIC
-
- @patch(
- "local_deep_research.web_search_engines.engines.parallel_search_engine._get_global_executor"
- )
- def test_init_sets_max_filtered_results(self, mock_get_executor):
- """ParallelSearchEngine sets max_filtered_results to 50 by default."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_get_executor.return_value = Mock()
- mock_llm = Mock()
-
- with patch.object(
- ParallelSearchEngine, "_get_available_engines", return_value=[]
- ):
- engine = ParallelSearchEngine(llm=mock_llm)
-
- assert engine.max_filtered_results == 50
-
- @patch(
- "local_deep_research.web_search_engines.engines.parallel_search_engine._get_global_executor"
- )
- def test_init_disables_llm_relevance_filter_by_default(
- self, mock_get_executor
- ):
- """ParallelSearchEngine disables LLM relevance filter by default."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_get_executor.return_value = Mock()
- mock_llm = Mock()
-
- with patch.object(
- ParallelSearchEngine, "_get_available_engines", return_value=[]
- ):
- engine = ParallelSearchEngine(llm=mock_llm)
-
- assert engine.enable_llm_relevance_filter is False
-
-
-class TestParallelSearchEngineApiKeyCheck:
- """Tests for API key availability checking."""
-
- def test_api_key_validation_in_shared_function(self):
- """API key filtering is now handled by the shared get_available_engines function.
- See tests/web_search_engines/engines/test_parallel_search_engine.py::TestResolveApiKey."""
- from local_deep_research.web_search_engines.search_engines_config import (
- _resolve_api_key,
- )
-
- # Valid key
- assert (
- _resolve_api_key("brave", {"api_key": "real-key"}, {}) == "real-key"
- )
- # Missing key
- assert _resolve_api_key("brave", {}, {}) is None
- # Placeholder key
- assert _resolve_api_key("brave", {"api_key": "PLACEHOLDER"}, {}) is None
-
-
-class TestParallelSearchEngineSelectEngines:
- """Tests for engine selection with LLM."""
-
- @patch(
- "local_deep_research.web_search_engines.engines.parallel_search_engine._get_global_executor"
- )
- def test_select_engines_no_llm(self, mock_get_executor):
- """select_engines returns all available when no LLM."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_get_executor.return_value = Mock()
-
- with patch.object(
- ParallelSearchEngine,
- "_get_available_engines",
- return_value=["duckduckgo", "brave", "arxiv"],
- ):
- engine = ParallelSearchEngine(llm=None)
- engine.max_engines_to_select = 2
-
- result = engine.select_engines("test query")
-
- assert len(result) == 2
- assert result == ["duckduckgo", "brave"]
-
- @patch(
- "local_deep_research.web_search_engines.engines.parallel_search_engine._get_global_executor"
- )
- def test_select_engines_no_available(self, mock_get_executor):
- """select_engines returns empty list when no engines available."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_get_executor.return_value = Mock()
- mock_llm = Mock()
-
- with patch.object(
- ParallelSearchEngine, "_get_available_engines", return_value=[]
- ):
- engine = ParallelSearchEngine(llm=mock_llm)
-
- result = engine.select_engines("test query")
-
- assert result == []
-
- @patch(
- "local_deep_research.web_search_engines.engines.parallel_search_engine._get_global_executor"
- )
- def test_select_engines_with_llm(self, mock_get_executor):
- """select_engines uses LLM to select engines."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_get_executor.return_value = Mock()
- mock_llm = Mock()
- mock_llm.invoke.return_value = Mock(content="[0, 2]")
-
- with patch.object(
- ParallelSearchEngine,
- "_get_available_engines",
- return_value=["arxiv", "pubmed", "semantic_scholar"],
- ):
- with patch.object(
- ParallelSearchEngine,
- "_get_available_generic_engines",
- return_value=[],
- ):
- engine = ParallelSearchEngine(
- llm=mock_llm, include_generic_engines=False
- )
-
- result = engine.select_engines("machine learning research")
-
- mock_llm.invoke.assert_called_once()
- assert "arxiv" in result
- assert "semantic_scholar" in result
-
- @patch(
- "local_deep_research.web_search_engines.engines.parallel_search_engine._get_global_executor"
- )
- def test_select_engines_adds_generic_engines(self, mock_get_executor):
- """select_engines adds generic engines to selection."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_get_executor.return_value = Mock()
- mock_llm = Mock()
- mock_llm.invoke.return_value = Mock(content="[0]")
-
- with patch.object(
- ParallelSearchEngine,
- "_get_available_engines",
- return_value=["duckduckgo", "arxiv", "pubmed"],
- ):
- with patch.object(
- ParallelSearchEngine,
- "_get_available_generic_engines",
- return_value=["duckduckgo"],
- ):
- engine = ParallelSearchEngine(
- llm=mock_llm, include_generic_engines=True
- )
-
- result = engine.select_engines("test query")
-
- # Should have arxiv (selected) plus duckduckgo (generic)
- assert "duckduckgo" in result
-
- @patch(
- "local_deep_research.web_search_engines.engines.parallel_search_engine._get_global_executor"
- )
- def test_select_engines_llm_invalid_response(self, mock_get_executor):
- """select_engines handles invalid LLM response."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_get_executor.return_value = Mock()
- mock_llm = Mock()
- mock_llm.invoke.return_value = Mock(content="invalid response")
-
- with patch.object(
- ParallelSearchEngine,
- "_get_available_engines",
- return_value=["duckduckgo", "brave"],
- ):
- with patch.object(
- ParallelSearchEngine,
- "_get_available_generic_engines",
- return_value=["duckduckgo"],
- ):
- engine = ParallelSearchEngine(llm=mock_llm)
-
- result = engine.select_engines("test query")
-
- # Should fallback to available engines
- assert len(result) > 0
-
-
-class TestParallelSearchEngineEngineInstance:
- """Tests for engine instance management."""
-
- @patch(
- "local_deep_research.web_search_engines.engines.parallel_search_engine._get_global_executor"
- )
- @patch(
- "local_deep_research.web_search_engines.engines.parallel_search_engine.create_search_engine"
- )
- def test_get_engine_instance_creates_new(
- self, mock_create, mock_get_executor
- ):
- """_get_engine_instance creates new engine instance."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_get_executor.return_value = Mock()
- mock_llm = Mock()
- mock_engine = Mock()
- mock_create.return_value = mock_engine
-
- with patch.object(
- ParallelSearchEngine, "_get_available_engines", return_value=[]
- ):
- engine = ParallelSearchEngine(llm=mock_llm)
-
- result = engine._get_engine_instance("duckduckgo")
-
- mock_create.assert_called_once()
- assert result is mock_engine
-
- @patch(
- "local_deep_research.web_search_engines.engines.parallel_search_engine._get_global_executor"
- )
- @patch(
- "local_deep_research.web_search_engines.engines.parallel_search_engine.create_search_engine"
- )
- def test_get_engine_instance_returns_cached(
- self, mock_create, mock_get_executor
- ):
- """_get_engine_instance returns cached instance."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_get_executor.return_value = Mock()
- mock_llm = Mock()
- mock_engine = Mock()
- mock_create.return_value = mock_engine
-
- with patch.object(
- ParallelSearchEngine, "_get_available_engines", return_value=[]
- ):
- engine = ParallelSearchEngine(llm=mock_llm)
-
- result1 = engine._get_engine_instance("duckduckgo")
- result2 = engine._get_engine_instance("duckduckgo")
-
- # Should only create once
- assert mock_create.call_count == 1
- assert result1 is result2
-
- @patch(
- "local_deep_research.web_search_engines.engines.parallel_search_engine._get_global_executor"
- )
- @patch(
- "local_deep_research.web_search_engines.engines.parallel_search_engine.create_search_engine"
- )
- def test_get_engine_instance_handles_creation_error(
- self, mock_create, mock_get_executor
- ):
- """_get_engine_instance handles creation errors."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_get_executor.return_value = Mock()
- mock_llm = Mock()
- mock_create.side_effect = Exception("Creation failed")
-
- with patch.object(
- ParallelSearchEngine, "_get_available_engines", return_value=[]
- ):
- engine = ParallelSearchEngine(llm=mock_llm)
-
- result = engine._get_engine_instance("broken_engine")
-
- assert result is None
-
-
-class TestParallelSearchEngineExecution:
- """Tests for search execution."""
-
- @patch(
- "local_deep_research.web_search_engines.engines.parallel_search_engine._get_global_executor"
- )
- def test_execute_single_engine_success(self, mock_get_executor):
- """_execute_single_engine returns results on success."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_get_executor.return_value = Mock()
- mock_llm = Mock()
- mock_engine = Mock()
- mock_engine.run.return_value = [
- {"title": "Result 1", "link": "https://example.com"},
- ]
-
- with patch.object(
- ParallelSearchEngine, "_get_available_engines", return_value=[]
- ):
- engine = ParallelSearchEngine(llm=mock_llm)
- engine.engine_cache["test_engine"] = mock_engine
-
- result = engine._execute_single_engine("test_engine", "test query")
-
- assert result["success"] is True
- assert result["engine"] == "test_engine"
- assert len(result["results"]) == 1
-
- @patch(
- "local_deep_research.web_search_engines.engines.parallel_search_engine._get_global_executor"
- )
- def test_execute_single_engine_no_results(self, mock_get_executor):
- """_execute_single_engine handles no results."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_get_executor.return_value = Mock()
- mock_llm = Mock()
- mock_engine = Mock()
- mock_engine.run.return_value = []
-
- with patch.object(
- ParallelSearchEngine, "_get_available_engines", return_value=[]
- ):
- engine = ParallelSearchEngine(llm=mock_llm)
- engine.engine_cache["test_engine"] = mock_engine
-
- result = engine._execute_single_engine("test_engine", "test query")
-
- assert result["success"] is False
- assert result["error"] == "No results"
-
- @patch(
- "local_deep_research.web_search_engines.engines.parallel_search_engine._get_global_executor"
- )
- def test_execute_single_engine_error(self, mock_get_executor):
- """_execute_single_engine handles engine errors."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_get_executor.return_value = Mock()
- mock_llm = Mock()
- mock_engine = Mock()
- mock_engine.run.side_effect = Exception("Search failed")
-
- with patch.object(
- ParallelSearchEngine, "_get_available_engines", return_value=[]
- ):
- engine = ParallelSearchEngine(llm=mock_llm)
- engine.engine_cache["test_engine"] = mock_engine
-
- result = engine._execute_single_engine("test_engine", "test query")
-
- assert result["success"] is False
- assert "failed" in result["error"].lower()
-
- @patch(
- "local_deep_research.web_search_engines.engines.parallel_search_engine._get_global_executor"
- )
- def test_execute_single_engine_missing_engine(self, mock_get_executor):
- """_execute_single_engine handles missing engine instance."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_get_executor.return_value = Mock()
- mock_llm = Mock()
-
- with patch.object(
- ParallelSearchEngine, "_get_available_engines", return_value=[]
- ):
- with patch.object(
- ParallelSearchEngine,
- "_get_engine_instance",
- return_value=None,
- ):
- engine = ParallelSearchEngine(llm=mock_llm)
-
- result = engine._execute_single_engine(
- "missing_engine", "test query"
- )
-
- assert result["success"] is False
- assert "initialize" in result["error"].lower()
-
-
-class TestParallelSearchEnginePreviews:
- """Tests for preview retrieval."""
-
- @patch(
- "local_deep_research.web_search_engines.engines.parallel_search_engine._get_global_executor"
- )
- def test_get_previews_no_engines_selected(self, mock_get_executor):
- """_get_previews returns empty list when no engines selected."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_get_executor.return_value = Mock()
- mock_llm = Mock()
-
- with patch.object(
- ParallelSearchEngine, "_get_available_engines", return_value=[]
- ):
- with patch.object(
- ParallelSearchEngine,
- "select_engines",
- return_value=[],
- ):
- engine = ParallelSearchEngine(llm=mock_llm)
-
- result = engine._get_previews("test query")
-
- assert result == []
-
- @patch(
- "local_deep_research.web_search_engines.engines.parallel_search_engine._get_global_executor"
- )
- def test_get_previews_no_executor(self, mock_get_executor):
- """_get_previews handles missing executor."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- # Return None for executor
- mock_get_executor.return_value = None
- mock_llm = Mock()
-
- with patch.object(
- ParallelSearchEngine,
- "_get_available_engines",
- return_value=["engine1"],
- ):
- with patch.object(
- ParallelSearchEngine,
- "select_engines",
- return_value=["engine1"],
- ):
- engine = ParallelSearchEngine(llm=mock_llm)
-
- result = engine._get_previews("test query")
-
- assert result == []
-
-
-class TestParallelSearchEngineFullContent:
- """Tests for full content retrieval."""
-
- @patch(
- "local_deep_research.web_search_engines.engines.parallel_search_engine._get_global_executor"
- )
- @patch("local_deep_research.config.search_config.get_setting_from_snapshot")
- def test_get_full_content_snippets_only(
- self, mock_get_setting, mock_get_executor
- ):
- """_get_full_content returns items as-is in snippets-only mode."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_get_executor.return_value = Mock()
- mock_get_setting.return_value = True # snippets_only = True
- mock_llm = Mock()
-
- with patch.object(
- ParallelSearchEngine, "_get_available_engines", return_value=[]
- ):
- engine = ParallelSearchEngine(llm=mock_llm)
-
- items = [{"title": "Test", "search_engine": "duckduckgo"}]
- result = engine._get_full_content(items)
-
- assert result == items
-
- @patch(
- "local_deep_research.web_search_engines.engines.parallel_search_engine._get_global_executor"
- )
- def test_get_full_content_groups_by_engine(self, mock_get_executor):
- """_get_full_content groups items by source engine."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_get_executor.return_value = Mock()
- mock_llm = Mock()
-
- mock_engine = Mock()
- mock_engine._get_full_content.return_value = [
- {"title": "Full content", "content": "Full text"},
- ]
-
- # Provide settings_snapshot with snippets_only = False (simplified format)
- settings_snapshot = {"search.snippets_only": False}
-
- with patch.object(
- ParallelSearchEngine, "_get_available_engines", return_value=[]
- ):
- engine = ParallelSearchEngine(
- llm=mock_llm, settings_snapshot=settings_snapshot
- )
- engine.engine_cache["test_engine"] = mock_engine
-
- items = [
- {"title": "Result 1", "search_engine": "test_engine"},
- ]
- result = engine._get_full_content(items)
-
- mock_engine._get_full_content.assert_called_once()
- assert len(result) == 1
-
- @patch(
- "local_deep_research.web_search_engines.engines.parallel_search_engine._get_global_executor"
- )
- @patch("local_deep_research.config.search_config.get_setting_from_snapshot")
- def test_get_full_content_handles_missing_engine(
- self, mock_get_setting, mock_get_executor
- ):
- """_get_full_content handles missing engine instance."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_get_executor.return_value = Mock()
- mock_get_setting.return_value = False
- mock_llm = Mock()
-
- with patch.object(
- ParallelSearchEngine, "_get_available_engines", return_value=[]
- ):
- with patch.object(
- ParallelSearchEngine,
- "_get_engine_instance",
- return_value=None,
- ):
- engine = ParallelSearchEngine(llm=mock_llm)
-
- items = [
- {"title": "Result 1", "search_engine": "missing_engine"},
- ]
- result = engine._get_full_content(items)
-
- # Should return items as-is when engine not available
- assert result == items
-
-
-class TestParallelSearchEngineInvoke:
- """Tests for invoke method."""
-
- @patch(
- "local_deep_research.web_search_engines.engines.parallel_search_engine._get_global_executor"
- )
- def test_invoke_calls_run(self, mock_get_executor):
- """invoke() calls run() for compatibility."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_get_executor.return_value = Mock()
- mock_llm = Mock()
-
- with patch.object(
- ParallelSearchEngine, "_get_available_engines", return_value=[]
- ):
- engine = ParallelSearchEngine(llm=mock_llm)
-
- with patch.object(
- engine, "run", return_value=[{"title": "Test"}]
- ) as mock_run:
- result = engine.invoke("test query")
-
- mock_run.assert_called_once_with("test query")
- assert result == [{"title": "Test"}]
-
-
-class TestParallelSearchEngineSearchConfig:
- """Tests for search config retrieval."""
-
- @patch(
- "local_deep_research.web_search_engines.engines.parallel_search_engine._get_global_executor"
- )
- def test_get_search_config_delegates_to_shared(self, mock_get_executor):
- """_get_search_config delegates to get_available_engines."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_get_executor.return_value = Mock()
- mock_llm = Mock()
-
- expected = {"brave": {"api_key": "test_key"}, "duckduckgo": {}}
-
- with patch.object(
- ParallelSearchEngine, "_get_available_engines", return_value=[]
- ):
- engine = ParallelSearchEngine(
- llm=mock_llm,
- settings_snapshot={"search.max_results": 10},
- )
-
- with patch(
- "local_deep_research.web_search_engines.engines.parallel_search_engine.get_available_engines",
- return_value=expected,
- ):
- config = engine._get_search_config()
-
- assert "duckduckgo" in config
- assert "brave" in config
-
- @patch(
- "local_deep_research.web_search_engines.engines.parallel_search_engine._get_global_executor"
- )
- def test_get_search_config_no_snapshot(self, mock_get_executor):
- """_get_search_config returns empty dict without settings."""
- from local_deep_research.web_search_engines.engines.parallel_search_engine import (
- ParallelSearchEngine,
- )
-
- mock_get_executor.return_value = Mock()
- mock_llm = Mock()
-
- with patch.object(
- ParallelSearchEngine, "_get_available_engines", return_value=[]
- ):
- engine = ParallelSearchEngine(llm=mock_llm, settings_snapshot=None)
-
- config = engine._get_search_config()
-
- assert config == {}
diff --git a/tests/web_search_engines/test_search_engine_factory.py b/tests/web_search_engines/test_search_engine_factory.py
index 81ebe0893b..e44c61639e 100644
--- a/tests/web_search_engines/test_search_engine_factory.py
+++ b/tests/web_search_engines/test_search_engine_factory.py
@@ -5,7 +5,7 @@ Tests cover:
- create_search_engine function
- get_search function
- _create_full_search_wrapper function
-- Parallel search engine variants
+- Removed meta engines ('auto', 'parallel', ...) rejected with ValueError
- API key and LLM requirements
- LLM relevance filter settings
"""
@@ -14,58 +14,31 @@ import pytest
from unittest.mock import Mock, patch
-class TestCreateSearchEngineParallel:
- """Tests for create_search_engine with parallel variants."""
+class TestRemovedMetaEnginesRejected:
+ """The 'auto'/'meta'/'parallel' meta engines were removed — the factory
+ must reject them like any unknown engine, with a message pointing at
+ the removal."""
- def test_create_parallel_scientific_engine(self):
- """Test creating parallel_scientific engine."""
- mock_llm = Mock()
-
- with patch(
- "local_deep_research.web_search_engines.engines.parallel_search_engine.ParallelSearchEngine"
- ) as mock_class:
- mock_engine = Mock()
- mock_class.return_value = mock_engine
-
- from local_deep_research.web_search_engines.search_engine_factory import (
- create_search_engine,
- )
- from local_deep_research.utilities.enums import SearchMode
-
- create_search_engine(
- engine_name="parallel_scientific",
- llm=mock_llm,
- settings_snapshot={"test": "value"},
- )
-
- mock_class.assert_called_once()
- call_kwargs = mock_class.call_args[1]
- assert call_kwargs["search_mode"] == SearchMode.SCIENTIFIC
-
- def test_create_parallel_engine(self):
- """Test creating parallel engine."""
- mock_llm = Mock()
+ @pytest.mark.parametrize(
+ "engine_name", ["auto", "meta", "parallel", "parallel_scientific"]
+ )
+ def test_removed_engine_raises_value_error(self, engine_name):
+ """Creating a removed meta engine raises ValueError mentioning the removal."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
with patch(
- "local_deep_research.web_search_engines.engines.parallel_search_engine.ParallelSearchEngine"
- ) as mock_class:
- mock_engine = Mock()
- mock_class.return_value = mock_engine
-
- from local_deep_research.web_search_engines.search_engine_factory import (
- create_search_engine,
- )
- from local_deep_research.utilities.enums import SearchMode
-
- create_search_engine(
- engine_name="parallel",
- llm=mock_llm,
- settings_snapshot={"test": "value"},
- )
+ "local_deep_research.web_search_engines.search_engine_factory.retriever_registry"
+ ) as mock_registry:
+ mock_registry.get.return_value = None
- mock_class.assert_called_once()
- call_kwargs = mock_class.call_args[1]
- assert call_kwargs["search_mode"] == SearchMode.ALL
+ with pytest.raises(ValueError, match="meta engines were removed"):
+ create_search_engine(
+ engine_name=engine_name,
+ llm=Mock(),
+ settings_snapshot={"test": "value"},
+ )
class TestCreateSearchEngineRetriever:
diff --git a/tests/web_search_engines/test_search_engine_factory_coverage.py b/tests/web_search_engines/test_search_engine_factory_coverage.py
index 9050af2c17..8885125a6d 100644
--- a/tests/web_search_engines/test_search_engine_factory_coverage.py
+++ b/tests/web_search_engines/test_search_engine_factory_coverage.py
@@ -791,56 +791,33 @@ class TestLlmRelevanceFilter:
# ---------------------------------------------------------------------------
-# Tests: Parallel engine creation
+# Tests: removed meta engines ('auto', 'meta', 'parallel', ...) are rejected
# ---------------------------------------------------------------------------
-class TestParallelEngineCreation:
- """Test parallel engine special-case handling."""
+class TestRemovedMetaEnginesRejected:
+ """The parallel/auto meta engines were removed — no special-case
+ short-circuit remains, so they fail like any unknown engine."""
- def test_parallel_scientific_passes_kwargs(self):
- """Extra kwargs are forwarded to ParallelSearchEngine."""
+ @pytest.mark.parametrize(
+ "engine_name", ["auto", "meta", "parallel", "parallel_scientific"]
+ )
+ def test_removed_engine_raises_value_error(self, engine_name):
+ """Removed meta engine names raise ValueError mentioning the removal."""
from local_deep_research.web_search_engines.search_engine_factory import (
create_search_engine,
)
with patch(
"local_deep_research.web_search_engines.search_engine_factory.retriever_registry"
- ):
- with patch(
- "local_deep_research.web_search_engines.engines.parallel_search_engine.ParallelSearchEngine"
- ) as mock_cls:
- mock_cls.return_value = Mock()
+ ) as mock_reg:
+ mock_reg.get.return_value = None
+ with pytest.raises(ValueError, match="meta engines were removed"):
create_search_engine(
- "parallel_scientific",
+ engine_name,
llm=Mock(),
settings_snapshot={"s": 1},
- max_results=15,
)
- call_kwargs = mock_cls.call_args[1]
- assert call_kwargs["max_results"] == 15
-
- def test_parallel_passes_settings_snapshot(self):
- """settings_snapshot is forwarded to ParallelSearchEngine."""
- from local_deep_research.web_search_engines.search_engine_factory import (
- create_search_engine,
- )
-
- snapshot = {"key": "val"}
- with patch(
- "local_deep_research.web_search_engines.search_engine_factory.retriever_registry"
- ):
- with patch(
- "local_deep_research.web_search_engines.engines.parallel_search_engine.ParallelSearchEngine"
- ) as mock_cls:
- mock_cls.return_value = Mock()
- create_search_engine(
- "parallel",
- llm=Mock(),
- settings_snapshot=snapshot,
- )
- call_kwargs = mock_cls.call_args[1]
- assert call_kwargs["settings_snapshot"] is snapshot
# ---------------------------------------------------------------------------
@@ -1124,24 +1101,24 @@ class TestExceptionHandling:
class TestSettingsSnapshotRequired:
- """Test that settings_snapshot=None raises RuntimeError for non-parallel,
+ """Test that settings_snapshot=None raises RuntimeError for
non-retriever engines."""
- def test_parallel_does_not_need_settings_snapshot(self):
- """Parallel engines work without settings_snapshot (they short-circuit)."""
+ def test_parallel_also_needs_settings_snapshot(self):
+ """'parallel' no longer short-circuits — like every other engine name
+ it requires a settings_snapshot."""
from local_deep_research.web_search_engines.search_engine_factory import (
create_search_engine,
)
with patch(
- "local_deep_research.web_search_engines.engines.parallel_search_engine.ParallelSearchEngine"
- ) as mock_cls:
- mock_cls.return_value = Mock()
- # Should not raise even with settings_snapshot=None
- result = create_search_engine(
- "parallel", llm=Mock(), settings_snapshot=None
- )
- assert result is not None
+ "local_deep_research.web_search_engines.search_engine_factory.retriever_registry"
+ ) as mock_reg:
+ mock_reg.get.return_value = None
+ with pytest.raises(RuntimeError, match="settings_snapshot"):
+ create_search_engine(
+ "parallel", llm=Mock(), settings_snapshot=None
+ )
# ---------------------------------------------------------------------------
@@ -1327,24 +1304,6 @@ class TestProgrammaticModePostConstructionPatch:
assert result is not None
assert result.programmatic_mode is True
- def test_parallel_path_propagates_programmatic_mode(self):
- """The parallel early-return path returns before the post-construction
- patch — verify programmatic_mode is passed at construction.
- """
- from local_deep_research.web_search_engines.search_engine_factory import (
- create_search_engine,
- )
-
- result = create_search_engine(
- "parallel",
- llm=Mock(),
- settings_snapshot={"x": 1},
- programmatic_mode=True,
- )
-
- assert result is not None
- assert result.programmatic_mode is True
-
# ---------------------------------------------------------------------------
# Tests: factory enforces programmatic_mode regardless of subclass __init__
diff --git a/tests/web_search_engines/test_search_engine_factory_deep_coverage.py b/tests/web_search_engines/test_search_engine_factory_deep_coverage.py
index b30f17b59f..f131ac76af 100644
--- a/tests/web_search_engines/test_search_engine_factory_deep_coverage.py
+++ b/tests/web_search_engines/test_search_engine_factory_deep_coverage.py
@@ -2,10 +2,9 @@
Deep coverage tests for search_engine_factory.py
Focuses on gaps not addressed by test_search_engine_factory_coverage.py:
-- Unknown engine that falls back to 'auto' when available
-- Unknown engine with no 'auto' fallback → returns None
+- Unknown engine names fail closed with ValueError
- Registered retriever path
-- parallel / parallel_scientific special paths
+- removed parallel / parallel_scientific names are rejected
- Missing settings_snapshot raises RuntimeError
- max_results defaulting from settings_snapshot
- API-key required but missing → None
@@ -76,42 +75,21 @@ def _make_snapshot(max_results=None, extra=None):
# ---------------------------------------------------------------------------
-# parallel / parallel_scientific special paths
+# removed parallel / parallel_scientific names are rejected
# ---------------------------------------------------------------------------
-class TestParallelEngineCreation:
- def test_parallel_scientific_returns_parallel_engine(self):
+class TestRemovedParallelEnginesRejected:
+ @pytest.mark.parametrize("engine_name", ["parallel", "parallel_scientific"])
+ def test_removed_parallel_name_raises_value_error(self, engine_name):
+ """The parallel meta engines were removed — the factory rejects the
+ names with a ValueError pointing at the removal."""
from local_deep_research.web_search_engines.search_engine_factory import (
create_search_engine,
)
- mock_engine = MagicMock()
- with patch(
- "local_deep_research.web_search_engines.engines.parallel_search_engine.ParallelSearchEngine",
- return_value=mock_engine,
- ):
- result = create_search_engine(
- "parallel_scientific",
- settings_snapshot={"dummy": "x"},
- )
- # Either the mock engine or a ParallelSearchEngine instance
- assert result is not None
-
- def test_parallel_returns_engine(self):
- from local_deep_research.web_search_engines.search_engine_factory import (
- create_search_engine,
- )
-
- mock_engine = MagicMock()
- with patch(
- "local_deep_research.web_search_engines.engines.parallel_search_engine.ParallelSearchEngine",
- return_value=mock_engine,
- ):
- result = create_search_engine(
- "parallel", settings_snapshot={"dummy": "x"}
- )
- assert result is not None
+ with pytest.raises(ValueError, match="meta engines were removed"):
+ create_search_engine(engine_name, settings_snapshot={"dummy": "x"})
# ---------------------------------------------------------------------------
diff --git a/tests/web_search_engines/test_search_engines_config.py b/tests/web_search_engines/test_search_engines_config.py
index b1eeffc648..4ca47e10cb 100644
--- a/tests/web_search_engines/test_search_engines_config.py
+++ b/tests/web_search_engines/test_search_engines_config.py
@@ -271,26 +271,10 @@ class TestSearchConfig:
@patch(
"local_deep_research.web_search_engines.search_engines_config._get_setting"
)
- def test_includes_auto_config(self, mock_get_setting, mock_registry):
- """Should include 'auto' key in result."""
- mock_get_setting.return_value = {}
- mock_registry.list_registered.return_value = []
-
- from local_deep_research.web_search_engines.search_engines_config import (
- search_config,
- )
-
- result = search_config()
- assert "auto" in result
-
- @patch(
- "local_deep_research.web_search_engines.retriever_registry.retriever_registry"
- )
- @patch(
- "local_deep_research.web_search_engines.search_engines_config._get_setting"
- )
- def test_adds_meta_alias_for_auto(self, mock_get_setting, mock_registry):
- """Should add 'meta' as alias for 'auto'."""
+ def test_excludes_removed_meta_engines(
+ self, mock_get_setting, mock_registry
+ ):
+ """Should not include the removed 'auto'/'meta'/'parallel' engines."""
mock_get_setting.return_value = {}
mock_registry.list_registered.return_value = []
@@ -299,8 +283,10 @@ class TestSearchConfig:
)
result = search_config()
- assert "meta" in result
- assert result["meta"] == result["auto"]
+ assert "auto" not in result
+ assert "meta" not in result
+ assert "parallel" not in result
+ assert "parallel_scientific" not in result
@patch(
"local_deep_research.web_search_engines.retriever_registry.retriever_registry"