Skip to content

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

test(search): exercise settings through real consumers (#7452)

LearningCircuitc5ac2ba1aa49
diff --git a/docs/developing.md b/docs/developing.md
index 45f5a04c92..7650be4d5e 100644
--- a/docs/developing.md
+++ b/docs/developing.md
@@ -214,6 +214,10 @@ Always commit `pdm.lock` alongside `pyproject.toml` changes to ensure reproducib
### Backend Tests (Pytest)
+For the focused caller-to-consumer search-setting checks, including real
+provider requests and local chunk retrieval, see
+[Search setting contracts](developing/search-settings-contracts.md).
+
We support two modes of backend testing:
#### 1. Isolated Testing (No Server Required)
diff --git a/docs/developing/search-settings-contracts.md b/docs/developing/search-settings-contracts.md
new file mode 100644
index 0000000000..a680770238
--- /dev/null
+++ b/docs/developing/search-settings-contracts.md
@@ -0,0 +1,79 @@
+# Search setting contracts
+
+Issue [#6651](https://github.com/LearningCircuit/local-deep-research/issues/6651)
+tracks prevention coverage for settings lost between callers, constructors and
+consumers after #6490. These tests run in the ordinary pytest suite. The dev
+dependencies include the optional MCP SDK so its caller contracts execute in
+the normal test image. No server, API credentials, model download or E2E label
+is required.
+
+From an environment installed with `pdm install`, run:
+
+```bash
+PYTHONPATH=src python -m pytest \
+ tests/web_search_engines/test_search_settings_library_contracts.py \
+ tests/web_search_engines/test_search_settings_contracts.py \
+ tests/citation_handlers/test_base_citation_handler.py \
+ -q -o addopts=
+```
+
+The focused command passed **116 tests in 22.51 seconds** on Linux/Python 3.12
+during implementation. Runtime depends on the machine. The FAISS bindings
+reported three existing SWIG deprecation warnings.
+
+## Coverage map
+
+| Mechanism from #6490 | Observable contract |
+| --- | --- |
+| Snapshot-only settings forwarding | Both scalar and `{value: ...}` snapshots control SearXNG snippets/page content, the real relevance filter's result count, and provider HTTP arguments. |
+| Constructor-signature filtering | Real SearXNG/TinyFish constructors and Mojeek's `**kwargs` path initialize and run; observing the real base constructor also verifies the snippet flag survives filtering without duplicate kwargs. |
+| Provider aliases | Captured Mojeek, Serper, TinyFish and ScaleSerp requests preserve their region/location and language formats. Real SearXNG sends `de`; the real HTML downloader/extraction pipeline receives `German` and produces article text. |
+| SearXNG snippet forwarding | The real factory, engine and full-search wrapper return snippets or extract full pages according to the resolved mode. |
+| Caller overrides | MCP's real search entry honors the snapshot. MCP and `get_search` retrieve complete chunks through actual library/collection engines, SQLite, FAISS and DB hydration. LangGraph web/specialized tools explicitly force snippets, as intended by #7189. |
+| Strategy execution flag | Constructing `SourceBasedSearchStrategy` changes an oppositely configured real library engine; `BaseSearchEngine.run()` then returns the requested snippet/full chunk. Updating only `include_full_content` fails this check. |
+| Citation fallback | The existing citation tests now follow missing, null and empty full content through document creation into the actual standard citation prompt; valid full content takes precedence over a distinct snippet. |
+
+Existing factory/wrapper routing tests and strategy unit tests remain useful.
+The new tests complement their mocked-constructor and attribute assertions
+with real execution. They do not require every registered provider to support
+every global setting.
+
+## Precedence protected by the suite
+
+The table describes direct `create_search_engine` calls. `get_search` also
+forwards its named argument defaults for the providers that accept them.
+
+| Setting | Contract |
+| --- | --- |
+| `search.snippets_only` | An explicit caller mode wins over the snapshot. A missing setting retains the safe engine default; malformed values fail closed. The LangGraph tools deliberately supply their own snippets-only override. |
+| `search.max_filtered_results` | An explicit argument wins over the global snapshot, which wins over engine defaults. Missing or malformed global values preserve the engine default. The assertions use the real relevance filter and selected result count. |
+| `search.region` | An explicit region wins over the global value; the global value overrides the engine's default region. Only TinyFish receives an automatic ISO `location` alias. `all` and `wt-wt` are not country locations. ScaleSerp retains its place-name default. |
+| Safe search | SearXNG's own enum default takes precedence over the global boolean; an explicit enum override wins. Other representative providers retain their documented boolean/request semantics. |
+| Language | Provider-specific `language` defaults and explicit overrides retain precedence. The extraction language is resolved separately: `search_language`, then the global search language, then the provider `language`, converted to a language name. |
+
+HTTP responses, DNS, LLM responses and embedding generation are isolated at
+their external boundaries. The library fixture replaces encrypted-engine
+discovery with temporary SQLite while retaining the production session scope,
+index service, integrity records, FAISS persistence and chunk rehydration. It
+sets and restores a background password context and closes its sessions.
+
+## Regression controls
+
+Implementation review verified the following eight deliberate mutations in a
+separate scratch checkout. All eight were detected by assertion or document
+construction failures, with no collection errors or skips:
+
+- Remove snapshot snippet forwarding from the factory.
+- Update only the strategy's unused `include_full_content` attribute.
+- Pass the provider code `de` into full-page extraction.
+- Drop supported base parameters from a real `**kwargs` constructor.
+- Remove snapshot forwarding of the relevance-filter result limit.
+- Treat ScaleSerp's free-text location as an ISO country alias.
+- Restore the citation fallback that fails on present-but-null/empty content.
+- Drop the engine's configured relevance-filter default when the global value
+ is missing or malformed.
+
+The production behavior is already correct; these are prevention tests, so
+passing against unchanged main is expected. No new pre-commit hook or workflow
+is needed. The accessor cleanup claimed separately in the #6651 conversation,
+fetch-cache behavior and summary budgeting remain separate work.
diff --git a/pdm.lock b/pdm.lock
index 1f6470ff1e..d76ad75369 100644
--- a/pdm.lock
+++ b/pdm.lock
@@ -5,7 +5,7 @@
groups = ["default", "dev", "mcp"]
strategy = ["inherit_metadata"]
lock_version = "4.5.0"
-content_hash = "sha256:b245a7768177b1f5b715b1fb775fa4cc5824705ffba124f944fec1a4ba7bdd9e"
+content_hash = "sha256:c2c238e3d205301f86f787ff4eb830dde0c73de0f05779503639d62faf163770"
[[metadata.targets]]
requires_python = ">=3.12,<3.15"
@@ -204,7 +204,7 @@ name = "annotated-doc"
version = "0.0.5"
requires_python = ">=3.9"
summary = "Document parameters, class attributes, return types, and variables inline, with Annotated."
-groups = ["default", "mcp"]
+groups = ["default", "dev", "mcp"]
files = [
{file = "annotated_doc-0.0.5-py3-none-any.whl", hash = "sha256:117bac03a25ede5df5440e855b32d556049ca169ead221505badf432fed4b101"},
{file = "annotated_doc-0.0.5.tar.gz", hash = "sha256:c7e58ce09192557605d8bbd92836d7e1d520ac9580096042c0bfd197efacf1bb"},
@@ -215,7 +215,7 @@ name = "annotated-types"
version = "0.8.0"
requires_python = ">=3.10"
summary = "Reusable constraint types to use with typing.Annotated"
-groups = ["default", "mcp"]
+groups = ["default", "dev", "mcp"]
files = [
{file = "annotated_types-0.8.0-py3-none-any.whl", hash = "sha256:f072f4d804ea359e4eaf198b1af7a8b0943881a87f31bb764f8bf219bb9419e0"},
{file = "annotated_types-0.8.0.tar.gz", hash = "sha256:13b2beaad985e05e2d6407ee4c4f35590b11f8d693a258a561055cac8f64cab7"},
@@ -246,7 +246,7 @@ name = "anyio"
version = "4.15.1"
requires_python = ">=3.10"
summary = "High-level concurrency and networking framework on top of asyncio or Trio"
-groups = ["default", "mcp"]
+groups = ["default", "dev", "mcp"]
dependencies = [
"exceptiongroup>=1.0.2; python_version < \"3.11\"",
"idna>=2.8",
@@ -329,7 +329,7 @@ name = "attrs"
version = "26.1.0"
requires_python = ">=3.9"
summary = "Classes Without Boilerplate"
-groups = ["default", "mcp"]
+groups = ["default", "dev", "mcp"]
files = [
{file = "attrs-26.1.0-py3-none-any.whl", hash = "sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309"},
{file = "attrs-26.1.0.tar.gz", hash = "sha256:d03ceb89cb322a8fd706d4fb91940737b6642aa36998fe130a9bc96c985eff32"},
@@ -491,7 +491,7 @@ name = "cffi"
version = "2.1.1"
requires_python = ">=3.10"
summary = "Foreign Function Interface for Python calling C code."
-groups = ["default", "mcp"]
+groups = ["default", "dev", "mcp"]
dependencies = [
"pycparser; implementation_name != \"PyPy\"",
]
@@ -1066,7 +1066,7 @@ name = "cryptography"
version = "50.0.2"
requires_python = "!=3.9.0,!=3.9.1,>=3.9"
summary = "cryptography is a package which provides cryptographic recipes and primitives to Python developers."
-groups = ["default", "mcp"]
+groups = ["default", "dev", "mcp"]
dependencies = [
"cffi>=2.0.0; platform_python_implementation != \"PyPy\"",
"typing-extensions>=4.13.2; python_full_version < \"3.11\"",
@@ -1815,7 +1815,7 @@ name = "h11"
version = "0.16.0"
requires_python = ">=3.8"
summary = "A pure-Python, bring-your-own-I/O implementation of HTTP/1.1"
-groups = ["default", "mcp"]
+groups = ["default", "dev", "mcp"]
files = [
{file = "h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86"},
{file = "h11-0.16.0.tar.gz", hash = "sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1"},
@@ -1927,7 +1927,7 @@ name = "httpcore"
version = "1.0.9"
requires_python = ">=3.8"
summary = "A minimal low-level HTTP client."
-groups = ["default", "mcp"]
+groups = ["default", "dev", "mcp"]
dependencies = [
"certifi",
"h11>=0.16",
@@ -2020,7 +2020,7 @@ name = "httpx"
version = "0.28.1"
requires_python = ">=3.8"
summary = "The next generation HTTP client."
-groups = ["default", "mcp"]
+groups = ["default", "dev", "mcp"]
dependencies = [
"anyio",
"certifi",
@@ -2037,7 +2037,7 @@ name = "httpx-sse"
version = "0.4.3"
requires_python = ">=3.9"
summary = "Consume Server-Sent Event (SSE) messages with HTTPX."
-groups = ["default", "mcp"]
+groups = ["default", "dev", "mcp"]
files = [
{file = "httpx_sse-0.4.3-py3-none-any.whl", hash = "sha256:0ac1c9fe3c0afad2e0ebb25a934a59f4c7823b60792691f779fad2c5568830fc"},
{file = "httpx_sse-0.4.3.tar.gz", hash = "sha256:9b1ed0127459a66014aec3c56bebd93da3c1bc8bb6618c8082039a44889a755d"},
@@ -2391,7 +2391,7 @@ name = "jsonschema"
version = "4.26.0"
requires_python = ">=3.10"
summary = "An implementation of JSON Schema validation for Python"
-groups = ["default", "mcp"]
+groups = ["default", "dev", "mcp"]
dependencies = [
"attrs>=22.2.0",
"jsonschema-specifications>=2023.03.6",
@@ -2408,7 +2408,7 @@ name = "jsonschema-specifications"
version = "2025.9.1"
requires_python = ">=3.9"
summary = "The JSON Schema meta-schemas and vocabularies, exposed as a Registry"
-groups = ["default", "mcp"]
+groups = ["default", "dev", "mcp"]
dependencies = [
"referencing>=0.31.0",
]
@@ -3426,7 +3426,7 @@ name = "mcp"
version = "1.30.0"
requires_python = ">=3.10"
summary = "Model Context Protocol SDK"
-groups = ["mcp"]
+groups = ["dev", "mcp"]
dependencies = [
"anyio>=4.5",
"httpx-sse>=0.4",
@@ -3457,7 +3457,7 @@ version = "1.30.0"
extras = ["cli"]
requires_python = ">=3.10"
summary = "Model Context Protocol SDK"
-groups = ["mcp"]
+groups = ["dev", "mcp"]
dependencies = [
"mcp==1.30.0",
"python-dotenv>=1.0.0",
@@ -4501,7 +4501,7 @@ name = "pycparser"
version = "3.11"
requires_python = ">=3.10"
summary = "C parser in Python"
-groups = ["default", "mcp"]
+groups = ["default", "dev", "mcp"]
marker = "implementation_name != \"PyPy\""
files = [
{file = "pycparser-3.11-py3-none-any.whl", hash = "sha256:51d5a8ba2be0bbe440b99d2112604c95bbbc3c2748a64260186c541e1729cd80"},
@@ -4513,7 +4513,7 @@ name = "pydantic"
version = "2.14.1"
requires_python = ">=3.10"
summary = "Data validation using Python type hints"
-groups = ["default", "mcp"]
+groups = ["default", "dev", "mcp"]
dependencies = [
"annotated-types>=0.6.0",
"pydantic-core==2.50.1",
@@ -4530,7 +4530,7 @@ name = "pydantic-core"
version = "2.50.1"
requires_python = ">=3.10"
summary = "Core functionality for Pydantic validation and serialization"
-groups = ["default", "mcp"]
+groups = ["default", "dev", "mcp"]
dependencies = [
"typing-extensions>=4.16.0",
]
@@ -4604,7 +4604,7 @@ name = "pydantic-settings"
version = "2.15.0"
requires_python = ">=3.10"
summary = "Settings management using Pydantic"
-groups = ["default", "mcp"]
+groups = ["default", "dev", "mcp"]
dependencies = [
"pydantic>=2.7.0",
"python-dotenv>=0.21.0",
@@ -4656,7 +4656,7 @@ name = "pyjwt"
version = "2.15.1"
requires_python = ">=3.9"
summary = "JSON Web Token implementation in Python"
-groups = ["mcp"]
+groups = ["dev", "mcp"]
dependencies = [
"typing-extensions>=4.0; python_version < \"3.11\"",
]
@@ -4671,7 +4671,7 @@ version = "2.15.1"
extras = ["crypto"]
requires_python = ">=3.9"
summary = "JSON Web Token implementation in Python"
-groups = ["mcp"]
+groups = ["dev", "mcp"]
dependencies = [
"cryptography>=3.4.0",
"pyjwt==2.15.1",
@@ -4939,7 +4939,7 @@ name = "python-dotenv"
version = "1.2.4"
requires_python = ">=3.10"
summary = "Read key-value pairs from a .env file and set them as environment variables"
-groups = ["default", "mcp"]
+groups = ["default", "dev", "mcp"]
files = [
{file = "python_dotenv-1.2.4-py3-none-any.whl", hash = "sha256:42269a8a5b3fd54ffa6f3d84b18abed50064717576b4ecf03dc4a55d8aa04fdc"},
{file = "python_dotenv-1.2.4.tar.gz", hash = "sha256:f0d53e69935a851c0dcc78f3ab7aaccd8cabef0b92382b576b824212902873c0"},
@@ -4986,7 +4986,7 @@ name = "python-multipart"
version = "0.0.32"
requires_python = ">=3.10"
summary = "A streaming multipart parser for Python"
-groups = ["default", "mcp"]
+groups = ["default", "dev", "mcp"]
files = [
{file = "python_multipart-0.0.32-py3-none-any.whl", hash = "sha256:ff6d3f776f16878c894e52e107296ffc890e913c611b1a4ec6c44e2821fe2e23"},
{file = "python_multipart-0.0.32.tar.gz", hash = "sha256:be54b7f3fa167bb83e4fcd936b887b708f4e57fe75911c02aebf53efaf8d938e"},
@@ -5069,7 +5069,7 @@ name = "pywin32"
version = "312"
requires_python = ">=3.9"
summary = "Python for Windows Extensions"
-groups = ["mcp"]
+groups = ["dev", "mcp"]
marker = "sys_platform == \"win32\""
files = [
{file = "pywin32-312-cp312-cp312-win32.whl", hash = "sha256:dab4f65ac9c4e48400a2a0530c46c3c579cd5905ecd11b80692373915269208b"},
@@ -5251,7 +5251,7 @@ name = "referencing"
version = "0.37.0"
requires_python = ">=3.10"
summary = "JSON Referencing + Python"
-groups = ["default", "mcp"]
+groups = ["default", "dev", "mcp"]
dependencies = [
"attrs>=22.2.0",
"rpds-py>=0.7.0",
@@ -5415,7 +5415,7 @@ name = "rpds-py"
version = "2026.9.1"
requires_python = ">=3.11"
summary = "Python bindings to Rust's persistent data structures (rpds)"
-groups = ["default", "mcp"]
+groups = ["default", "dev", "mcp"]
files = [
{file = "rpds_py-2026.9.1-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:50906f5aea24b5a865cbd0a589698288631d9f3a54c3a937c83aefa95a0d14af"},
{file = "rpds_py-2026.9.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:e21c1429e205828ea886a2293a4a2c8e01f4c25d9893ca330e97a6cf73f52e7b"},
@@ -5743,7 +5743,7 @@ name = "shellingham"
version = "1.5.4"
requires_python = ">=3.7"
summary = "Tool to Detect Surrounding Shell"
-groups = ["default", "mcp"]
+groups = ["default", "dev", "mcp"]
files = [
{file = "shellingham-1.5.4-py2.py3-none-any.whl", hash = "sha256:7ecfff8f2fd72616f7481040475a65b2bf8af90a56c89140852d1120324e8686"},
{file = "shellingham-1.5.4.tar.gz", hash = "sha256:8dbca0739d487e5bd35ab3ca4b36e11c4078f3a234bfce294b0a0291363404de"},
@@ -6025,7 +6025,7 @@ name = "sse-starlette"
version = "3.5.0"
requires_python = ">=3.10"
summary = "SSE plugin for Starlette"
-groups = ["mcp"]
+groups = ["dev", "mcp"]
dependencies = [
"anyio>=4.7.0",
"starlette>=0.49.1",
@@ -6040,7 +6040,7 @@ name = "starlette"
version = "1.3.1"
requires_python = ">=3.10"
summary = "The little ASGI library that shines."
-groups = ["default", "mcp"]
+groups = ["default", "dev", "mcp"]
dependencies = [
"anyio<5,>=3.6.2",
"typing-extensions>=4.10.0; python_version < \"3.13\"",
@@ -6386,7 +6386,7 @@ name = "typer"
version = "0.27.3"
requires_python = ">=3.10"
summary = "Typer, build great CLIs. Easy to code. Based on Python type hints."
-groups = ["default", "mcp"]
+groups = ["default", "dev", "mcp"]
dependencies = [
"annotated-doc>=0.0.2",
"colorama; platform_system == \"Windows\"",
@@ -6454,7 +6454,7 @@ name = "typing-inspection"
version = "0.4.4"
requires_python = ">=3.10"
summary = "Runtime typing introspection tools"
-groups = ["default", "mcp"]
+groups = ["default", "dev", "mcp"]
dependencies = [
"typing-extensions>=4.15.0",
]
@@ -6653,7 +6653,7 @@ name = "uvicorn"
version = "0.54.0"
requires_python = ">=3.10"
summary = "The lightning-fast ASGI server."
-groups = ["default", "mcp"]
+groups = ["default", "dev", "mcp"]
dependencies = [
"click>=7.0",
"h11>=0.8",
diff --git a/pyproject.toml b/pyproject.toml
index 02c4bc0758..827ee92f5a 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -271,6 +271,7 @@ dev = [
"pytest-timeout~=2.4",
"pytest-asyncio~=1.3",
"pytest-xdist~=3.8",
+ "mcp[cli]~=1.2", # exercise MCP caller contracts in ordinary pytest CI
"ruff~=0.15",
"freezegun~=1.5",
"mypy~=1.19",
diff --git a/tests/citation_handlers/test_base_citation_handler.py b/tests/citation_handlers/test_base_citation_handler.py
index 0f07c00684..afd5801c26 100644
--- a/tests/citation_handlers/test_base_citation_handler.py
+++ b/tests/citation_handlers/test_base_citation_handler.py
@@ -11,6 +11,7 @@ Tests the concrete methods in the base class:
from unittest.mock import MagicMock
from typing import Dict, Any, List, Union
+import pytest
from langchain_core.documents import Document
from local_deep_research.citation_handlers.base_citation_handler import (
@@ -335,8 +336,13 @@ class TestCreateDocuments:
def test_prefers_full_content_over_snippet(self):
"""Test full_content is preferred over snippet."""
+ from local_deep_research.citation_handlers.standard_citation_handler import (
+ StandardCitationHandler,
+ )
+
mock_llm = MagicMock()
- handler = ConcreteCitationHandler(mock_llm)
+ mock_llm.invoke.return_value = "Answer [1]."
+ handler = StandardCitationHandler(mock_llm)
search_results = [
{
@@ -347,30 +353,43 @@ class TestCreateDocuments:
}
]
- docs = handler._create_documents(search_results)
+ result = handler.analyze_initial("question", search_results)
assert (
- docs[0].page_content
+ result["documents"][0].page_content
== "This is the full content which is much longer"
)
+ prompt = mock_llm.invoke.call_args.args[0]
+ assert "This is the full content which is much longer" in prompt
+ assert "Short snippet" not in prompt
+
+ @pytest.mark.parametrize(
+ "content_fields", [{}, {"full_content": None}, {"full_content": ""}]
+ )
+ def test_falls_back_to_snippet_when_full_content_is_unavailable(
+ self, content_fields
+ ):
+ """Missing, null and empty full content reach the citation prompt (#6651)."""
+ from local_deep_research.citation_handlers.standard_citation_handler import (
+ StandardCitationHandler,
+ )
- def test_falls_back_to_snippet_when_full_content_is_none(self):
- """Test falls back to snippet when full_content is explicitly None (#6489)."""
mock_llm = MagicMock()
- handler = ConcreteCitationHandler(mock_llm)
+ mock_llm.invoke.return_value = "Answer [1]."
+ handler = StandardCitationHandler(mock_llm)
search_results = [
{
"link": "https://example.com",
"title": "Result",
"snippet": "Fallback snippet",
- "full_content": None,
+ **content_fields,
}
]
- docs = handler._create_documents(search_results)
-
- assert docs[0].page_content == "Fallback snippet"
+ result = handler.analyze_initial("question", search_results)
+ assert result["documents"][0].page_content == "Fallback snippet"
+ assert "Fallback snippet" in mock_llm.invoke.call_args.args[0]
def test_handles_empty_list(self):
"""Test handles empty search results list."""
diff --git a/tests/web_search_engines/test_search_settings_contracts.py b/tests/web_search_engines/test_search_settings_contracts.py
new file mode 100644
index 0000000000..279f4b3ffe
--- /dev/null
+++ b/tests/web_search_engines/test_search_settings_contracts.py
@@ -0,0 +1,473 @@
+"""Caller-to-consumer contracts from #6651; only external I/O is replaced.
+
+The real registry, settings readers, factory signature filter, constructors,
+engine execution and HTML extraction remain in the path. See the companion
+developer guide for precedence, intentional agent overrides and mutation checks.
+"""
+
+import json
+import socket
+from types import SimpleNamespace
+from unittest.mock import Mock
+from urllib.parse import urlsplit
+
+import pytest
+import requests
+from langchain_core.language_models.fake import FakeListLLM
+
+from local_deep_research.advanced_search_system.strategies import (
+ langgraph_agent_strategy as agent,
+)
+from local_deep_research.mcp.server import _execute_search
+from local_deep_research.research_library.downloaders import html
+from local_deep_research.web_search_engines import search_engine_factory
+from local_deep_research.web_search_engines.engines import (
+ search_engine_mojeek,
+ search_engine_scaleserp,
+ search_engine_searxng,
+ search_engine_serper,
+ search_engine_tinyfish,
+)
+from local_deep_research.web_search_engines.search_engine_base import (
+ BaseSearchEngine,
+)
+
+
+ARTICLE_URL = "https://93.184.216.34/article"
+SNIPPET = "Short provider snippet."
+ARTICLE_TEXT = (
+ "Die Forschung untersucht die Wirkung von Licht auf Pflanzen. "
+ "Die Ergebnisse zeigen, dass die Pflanzen mit Licht besser wachsen. "
+ "Diese ausführlichen Beobachtungen stehen nur im vollständigen Artikel. "
+) * 8
+ARTICLE_HTML = (
+ f"<html><body><article><p>{ARTICLE_TEXT}</p></article></body></html>"
+)
+pytestmark = pytest.mark.usefixtures("loguru_caplog")
+
+
+def _response(url, *, payload=None, text=""):
+ response = requests.Response()
+ response.status_code = 200
+ response.url = url
+ response.encoding = "utf-8"
+ response.headers["Content-Type"] = (
+ "application/json"
+ if payload is not None
+ else "text/html; charset=utf-8"
+ )
+ response._content = (
+ json.dumps(payload).encode() if payload is not None else text.encode()
+ )
+ return response
+
+
[email protected](params=["scalar", "envelope"])
+def snapshot(request):
+ def build(engine="searxng", **values):
+ settings = {
+ "policy.egress_scope": "public_only",
+ "search.tool": engine,
+ "search.engine.library.enabled": False,
+ "search.snippets_only": True,
+ "search.max_filtered_results": 2,
+ "search.region": "gb",
+ "search.safe_search": True,
+ "search.search_language": "German",
+ f"search.engine.web.{engine}.enabled": True,
+ f"search.engine.web.{engine}.requires_api_key": engine != "searxng",
+ f"search.engine.web.{engine}.api_key": "offline-contract-credential",
+ f"search.engine.web.{engine}.supports_full_search": True,
+ f"search.engine.web.{engine}.default_params.enable_llm_relevance_filter": False,
+ }
+ if engine == "searxng":
+ settings.update(
+ {
+ "search.engine.web.searxng.default_params.instance_url": "https://93.184.216.35",
+ "search.engine.web.searxng.default_params.result_format": "json",
+ }
+ )
+ settings.update(values)
+ if request.param == "envelope":
+ return {key: {"value": value} for key, value in settings.items()}
+ return settings
+
+ return build
+
+
+def offline_http(monkeypatch, tmp_path):
+ """Replace HTTP/DNS, retaining real engine parsing and page extraction."""
+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path / "data"))
+ state = SimpleNamespace(requests=[], pages=[], extraction_languages=[])
+
+ def dns(host, port, *args, **kwargs):
+ return [
+ (
+ socket.AF_INET,
+ socket.SOCK_STREAM,
+ socket.IPPROTO_TCP,
+ "",
+ ("93.184.216.34", port or 443),
+ )
+ ]
+
+ monkeypatch.setattr(socket, "getaddrinfo", dns)
+
+ def provider(url, **kwargs):
+ state.requests.append((url, kwargs))
+ item = {
+ "title": "Light and plants",
+ "url": ARTICLE_URL,
+ "link": ARTICLE_URL,
+ "snippet": SNIPPET,
+ "content": SNIPPET,
+ "desc": SNIPPET,
+ }
+ items = [
+ {
+ **item,
+ "url": f"{ARTICLE_URL}?result={i}",
+ "link": f"{ARTICLE_URL}?result={i}",
+ }
+ for i in range(3)
+ ]
+ return _response(
+ url,
+ payload={
+ "results": items,
+ "organic": items,
+ "organic_results": items,
+ "response": {
+ "status": "OK",
+ "results": items,
+ },
+ },
+ )
+
+ for module, name in [
+ (search_engine_searxng, "safe_get"),
+ (search_engine_mojeek, "safe_get"),
+ (search_engine_scaleserp, "safe_get"),
+ (search_engine_serper, "safe_post"),
+ (search_engine_tinyfish, "safe_get"),
+ ]:
+ monkeypatch.setattr(module, name, provider)
+
+ def transport(self, request, **kwargs):
+ assert urlsplit(request.url).path == "/article", request.url
+ state.pages.append(request.url)
+ return _response(request.url, text=ARTICLE_HTML)
+
+ monkeypatch.setattr(requests.adapters.HTTPAdapter, "send", transport)
+ extract = html.extract_content_with_metadata
+
+ def observe_extraction(source, **kwargs):
+ state.extraction_languages.append(kwargs["language"])
+ return extract(source, **kwargs)
+
+ monkeypatch.setattr(
+ html, "extract_content_with_metadata", observe_extraction
+ )
+ return state
+
+
+def _run(settings, **overrides):
+ engine = search_engine_factory.create_search_engine(
+ "searxng",
+ settings_snapshot=settings,
+ programmatic_mode=True,
+ **overrides,
+ )
+ assert engine is not None
+ try:
+ return engine.run("light and plants")
+ finally:
+ engine.close()
+
+
+ ("setting", "full"),
+ [
+ (True, False),
+ (False, True),
+ ("false", True),
+ ("maybe", False),
+ ("", False),
+ (123, False),
+ (None, False),
+ ],
+)
+def test_snapshot_selects_real_searxng_execution(
+ snapshot, offline_http, setting, full
+):
+ settings = snapshot(**{"search.snippets_only": setting})
+ results = _run(settings)
+
+ assert results and results[0]["snippet"] == SNIPPET
+ request = next(
+ kwargs["params"]
+ for _, kwargs in offline_http.requests
+ if "params" in kwargs
+ )
+ assert request["language"] == "de"
+ assert request["safesearch"] == 1
+ if full:
+ assert ARTICLE_TEXT[:100] in results[0]["full_content"]
+ assert offline_http.pages
+ assert offline_http.extraction_languages == ["German"] * len(
+ offline_http.pages
+ )
+ else:
+ assert "full_content" not in results[0]
+ assert offline_http.pages == []
+ assert offline_http.extraction_languages == []
+
+
+def test_missing_snippet_setting_uses_safe_engine_default(
+ snapshot, offline_http
+):
+ settings = snapshot()
+ del settings["search.snippets_only"]
+ results = _run(settings)
+ assert results[0]["snippet"] == SNIPPET
+ assert "full_content" not in results[0]
+ assert offline_http.pages == []
+
+
[email protected]("snippets_only", [False, True])
[email protected]("caller", ["factory", "get_search"])
+def test_explicit_mode_overrides_opposite_snapshot(
+ snapshot, offline_http, snippets_only, caller
+):
+ settings = snapshot(**{"search.snippets_only": not snippets_only})
+ if caller == "factory":
+ results = _run(settings, search_snippets_only=snippets_only)
+ else:
+ engine = search_engine_factory.get_search(
+ "searxng",
+ None,
+ search_snippets_only=snippets_only,
+ settings_snapshot=settings,
+ programmatic_mode=True,
+ )
+ assert engine is not None
+ try:
+ results = engine.run("light and plants")
+ finally:
+ engine.close()
+ assert bool(results[0].get("full_content")) is not snippets_only
+ assert bool(offline_http.pages) is not snippets_only
+
+
+ ("provider", "expected"),
+ [
+ ("mojeek", {"rb": "gb", "lb": "de", "safe": 1}),
+ ("serper", {"gl": "gb", "hl": "de"}),
+ ("tinyfish", {"location": "GB", "language": "de"}),
+ # ScaleSerp's location is a place name, not an ISO country code.
+ ("scaleserp", {"location": "United States", "hl": "de", "safe": "on"}),
+ ],
+)
+def test_real_provider_requests_use_their_own_alias_formats(
+ snapshot, offline_http, provider, expected
+):
+ engine = search_engine_factory.create_search_engine(
+ provider, settings_snapshot=snapshot(provider), programmatic_mode=True
+ )
+ assert engine is not None
+ try:
+ results = engine.run("light and plants")
+ finally:
+ engine.close()
+ assert results[0]["snippet"] == SNIPPET
+ _, kwargs = offline_http.requests[-1]
+ sent = kwargs.get("params", kwargs.get("json"))
+ assert {key: sent[key] for key in expected} == expected
+ assert offline_http.pages == []
+
+
+def test_engine_defaults_and_explicit_aliases_have_documented_precedence(
+ snapshot, offline_http
+):
+ settings = snapshot(
+ **{
+ "search.engine.web.searxng.default_params.language": "fr",
+ "search.engine.web.searxng.default_params.safe_search": "STRICT",
+ }
+ )
+ _run(settings)
+ sent = offline_http.requests[-1][1]["params"]
+ assert (sent["language"], sent["safesearch"]) == ("fr", 2)
+
+ _run(settings, language="es", safe_search="OFF")
+ sent = offline_http.requests[-1][1]["params"]
+ assert (sent["language"], sent["safesearch"]) == ("es", 0)
+
+
+def test_kwargs_base_constructor_keeps_snippet_flag_without_duplicates(
+ snapshot, offline_http, monkeypatch
+):
+ calls = []
+ original = BaseSearchEngine.__init__
+
+ def observe(self, *args, **kwargs):
+ calls.append(dict(kwargs))
+ original(self, *args, **kwargs)
+
+ monkeypatch.setattr(BaseSearchEngine, "__init__", observe)
+ engine = search_engine_factory.create_search_engine(
+ "mojeek",
+ settings_snapshot=snapshot("mojeek", **{"search.snippets_only": False}),
+ programmatic_mode=True,
+ use_full_search=False,
+ )
+ assert isinstance(engine, search_engine_mojeek.MojeekSearchEngine)
+ try:
+ assert calls[0]["search_snippets_only"] is False
+ assert engine.run("light and plants")[0]["snippet"] == SNIPPET
+ finally:
+ engine.close()
+
+
[email protected]("limit", [1, 2])
+def test_snapshot_filter_limit_reaches_real_relevance_filter(
+ snapshot, offline_http, limit
+):
+ settings = snapshot(
+ **{
+ "search.max_filtered_results": str(limit),
+ "search.engine.web.searxng.default_params.enable_llm_relevance_filter": True,
+ }
+ )
+ engine = search_engine_factory.create_search_engine(
+ "searxng",
+ llm=FakeListLLM(responses=["0, 1, 2"]),
+ settings_snapshot=settings,
+ programmatic_mode=True,
+ )
+ assert engine is not None
+ try:
+ assert len(engine.run("light and plants")) == limit
+ finally:
+ engine.close()
+
+
+ ("setting", "overrides", "expected"),
+ [
+ (None, {}, 1),
+ ("not-a-number", {}, 1),
+ (2, {"max_filtered_results": 3}, 3),
+ (2, {}, 2),
+ ],
+)
+def test_filter_limit_missing_malformed_and_explicit_precedence(
+ snapshot, offline_http, setting, overrides, expected
+):
+ settings = snapshot(
+ **{
+ "search.max_filtered_results": setting,
+ "search.engine.web.searxng.default_params.max_filtered_results": 1,
+ "search.engine.web.searxng.default_params.enable_llm_relevance_filter": True,
+ }
+ )
+ if setting is None:
+ del settings["search.max_filtered_results"]
+ engine = search_engine_factory.create_search_engine(
+ "searxng",
+ llm=FakeListLLM(responses=["0, 1, 2"]),
+ settings_snapshot=settings,
+ programmatic_mode=True,
+ **overrides,
+ )
+ assert engine is not None
+ try:
+ assert len(engine.run("light and plants")) == expected
+ finally:
+ engine.close()
+
+
[email protected]("region", ["all", "wt-wt"])
+def test_non_country_region_does_not_become_tinyfish_location(
+ snapshot, offline_http, region
+):
+ engine = search_engine_factory.create_search_engine(
+ "tinyfish",
+ settings_snapshot=snapshot("tinyfish", **{"search.region": region}),
+ programmatic_mode=True,
+ )
+ assert engine is not None
+ try:
+ assert engine.run("light and plants")
+ finally:
+ engine.close()
+ assert offline_http.requests[-1][1]["params"]["location"] == "US"
+
+
+def test_region_overrides_engine_default_but_explicit_argument_wins(
+ snapshot, offline_http
+):
+ settings = snapshot(
+ "mojeek", **{"search.engine.web.mojeek.default_params.region": "fr"}
+ )
+ for overrides, expected in [({}, "gb"), ({"region": "es"}, "es")]:
+ engine = search_engine_factory.create_search_engine(
+ "mojeek",
+ settings_snapshot=settings,
+ programmatic_mode=True,
+ **overrides,
+ )
+ assert engine is not None
+ try:
+ assert engine.run("light and plants")
+ finally:
+ engine.close()
+ assert offline_http.requests[-1][1]["params"]["rb"] == expected
+
+
[email protected]("snippets_only", [True, False])
+def test_mcp_snapshot_controls_real_factory_and_page_extraction(
+ snapshot, offline_http, snippets_only
+):
+ result = _execute_search(
+ "light and plants",
+ "searxng",
+ 3,
+ snapshot(**{"search.snippets_only": snippets_only}),
+ )
+ assert result["status"] == "success"
+ assert result["result_count"] == 3
+ assert bool(result["results"][0].get("full_content")) is not snippets_only
+ assert bool(offline_http.pages) is not snippets_only
+
+
[email protected]("kind", ["web", "specialized"])
+def test_agent_explicit_snippet_override_survives_real_execution(
+ snapshot, offline_http, kind
+):
+ settings = snapshot(**{"search.snippets_only": False})
+ collector = agent.SearchResultsCollector()
+ if kind == "web":
+ tool = agent._make_web_search_tool(
+ search_engine_name="searxng",
+ model=Mock(),
+ settings_snapshot=settings,
+ collector=collector,
+ programmatic_mode=True,
+ )
+ else:
+ tool = agent._make_specialized_search_tool(
+ engine_name="searxng",
+ description="Offline contract search",
+ model=Mock(),
+ settings_snapshot=settings,
+ collector=collector,
+ programmatic_mode=True,
+ )
+ output = tool.invoke({"query": "light and plants"})
+ assert SNIPPET in output
+ assert collector.results
+ assert all("full_content" not in item for item in collector.results)
+ assert offline_http.pages == []
diff --git a/tests/web_search_engines/test_search_settings_library_contracts.py b/tests/web_search_engines/test_search_settings_library_contracts.py
new file mode 100644
index 0000000000..2fb9971493
--- /dev/null
+++ b/tests/web_search_engines/test_search_settings_library_contracts.py
@@ -0,0 +1,246 @@
+"""Real local retrieval contracts: snapshots must preserve complete chunks."""
+
+import hashlib
+import threading
+
+import pytest
+from langchain_core.embeddings import Embeddings
+from langchain_core.language_models.fake import FakeListLLM
+from sqlalchemy import create_engine, event, select
+from sqlalchemy.orm import Session
+
+from local_deep_research.advanced_search_system.strategies.source_based_strategy import (
+ SourceBasedSearchStrategy,
+)
+from local_deep_research.database.models import Base
+from local_deep_research.database.models.library import (
+ Collection,
+ Document,
+ DocumentChunk,
+ EmbeddingProvider,
+ SourceType,
+)
+from local_deep_research.database.thread_local_session import (
+ thread_session_manager,
+)
+from local_deep_research.mcp.server import _execute_search
+from local_deep_research.research_library.services.library_rag_service import (
+ LibraryRAGService,
+)
+from local_deep_research.settings.manager import SettingsManager
+from local_deep_research.utilities.thread_context import (
+ clear_search_context,
+ get_search_context,
+ set_search_context,
+)
+from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ get_search,
+)
+from local_deep_research.web_search_engines.search_engines_config import (
+ invalidate_collection_engines_cache,
+)
+
+from .test_search_settings_contracts import snapshot as snapshot
+
+
+USERNAME = "settings-contract-user"
+COLLECTION_ID = "22222222-2222-4222-8222-222222222222"
+DOCUMENT_ID = "11111111-1111-4111-8111-111111111111"
+CHUNK_TEXT = "Detailed local research evidence. " * 40 + "END-OF-COMPLETE-CHUNK"
+pytestmark = pytest.mark.usefixtures("loguru_caplog")
+
+
+class OfflineEmbeddings(Embeddings):
+ """Replace the model boundary; FAISS and DB chunk hydration stay real."""
+
+ def embed_documents(self, texts):
+ return [[0.2, 0.4, 0.8] for _ in texts]
+
+ def embed_query(self, text):
+ return [0.2, 0.4, 0.8]
+
+
+def indexed_library(tmp_path, monkeypatch):
+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path / "data"))
+ engine = create_engine(f"sqlite:///{tmp_path / 'library.db'}")
+
+ @event.listens_for(engine, "connect")
+ def sqlite_transactions(connection, record):
+ connection.isolation_level = None
+ connection.execute("PRAGMA journal_mode=WAL")
+
+ @event.listens_for(engine, "begin")
+ def begin(connection):
+ connection.exec_driver_sql("BEGIN")
+
+ Base.metadata.create_all(engine)
+ per_thread = threading.local()
+ sessions = []
+
+ def discover_session(username, password):
+ assert username == USERNAME
+ if not hasattr(per_thread, "session"):
+ per_thread.session = Session(engine)
+ sessions.append(per_thread.session)
+ return per_thread.session
+
+ # Retain the production scope-depth, nested transaction and cleanup
+ # behavior. Only encrypted-engine discovery points at isolated SQLite.
+ monkeypatch.setattr(
+ "local_deep_research.database.thread_local_session.get_metrics_session",
+ discover_session,
+ )
+ monkeypatch.setattr(
+ "local_deep_research.embeddings.get_embeddings",
+ lambda **kwargs: OfflineEmbeddings(),
+ )
+ previous_context = get_search_context()
+ set_search_context(
+ {"username": USERNAME, "user_password": "contract-password"}
+ )
+ invalidate_collection_engines_cache(USERNAME)
+
+ try:
+ with Session(engine) as session:
+ settings = SettingsManager(session)
+ for key, value in {
+ "policy.egress_scope": "private_only",
+ "search.tool": "library",
+ "local_search_embedding_provider": "ollama",
+ "local_search_embedding_model": "contract-offline-model",
+ }.items():
+ assert settings.set_setting(key, value)
+ session.add_all(
+ [
+ SourceType(
+ id="upload", name="user_upload", display_name="Upload"
+ ),
+ Collection(
+ id=COLLECTION_ID,
+ name="Contract evidence",
+ is_public=False,
+ embedding_model="contract-offline-model",
+ embedding_model_type=EmbeddingProvider.OLLAMA,
+ chunk_size=10000,
+ chunk_overlap=0,
+ ),
+ Document(
+ id=DOCUMENT_ID,
+ source_type_id="upload",
+ title="Complete evidence",
+ filename="evidence.txt",
+ text_content=CHUNK_TEXT,
+ file_size=len(CHUNK_TEXT.encode()),
+ file_type="txt",
+ storage_mode="none",
+ document_hash=hashlib.sha256(
+ CHUNK_TEXT.encode()
+ ).hexdigest(),
+ ),
+ ]
+ )
+ session.commit()
+
+ with LibraryRAGService(
+ username=USERNAME,
+ db_password="contract-password",
+ embedding_model="contract-offline-model",
+ embedding_provider="ollama",
+ chunk_size=10000,
+ chunk_overlap=0,
+ ) as service:
+ result = service.index_document(DOCUMENT_ID, COLLECTION_ID)
+ assert result["status"] == "success", result
+ with Session(engine) as session:
+ chunks = session.scalars(select(DocumentChunk)).all()
+ assert len(chunks) == 1
+ assert chunks[0].chunk_text == CHUNK_TEXT
+ yield engine
+ finally:
+ if previous_context is None:
+ clear_search_context()
+ else:
+ set_search_context(previous_context)
+ invalidate_collection_engines_cache(USERNAME)
+ thread_session_manager.cleanup_thread()
+ for session in sessions:
+ session.close()
+ engine.dispose()
+
+
+def _local_snapshot(snapshot, name, snippets_only):
+ settings = snapshot(
+ name,
+ **{
+ "policy.egress_scope": "private_only",
+ "search.engine.library.enabled": True,
+ "search.snippets_only": snippets_only,
+ "search.rag.enable_relevance_filter": False,
+ "local_search_embedding_provider": "ollama",
+ "local_search_embedding_model": "contract-offline-model",
+ "local_search_chunk_size": 10000,
+ "local_search_chunk_overlap": 0,
+ },
+ )
+ settings["_username"] = USERNAME
+ return settings
+
+
+def _assert_chunk(results, snippets_only):
+ assert len(results) == 1
+ assert results[0]["snippet"] != CHUNK_TEXT
+ assert "END-OF-COMPLETE-CHUNK" not in results[0]["snippet"]
+ if snippets_only:
+ assert "full_content" not in results[0]
+ else:
+ assert results[0]["full_content"] == CHUNK_TEXT
+
+
[email protected]("name", ["library", f"collection_{COLLECTION_ID}"])
[email protected]("snippets_only", [False, True])
[email protected]("caller", ["get_search", "mcp"])
+def test_local_snapshot_controls_real_chunk_hydration(
+ indexed_library, snapshot, name, snippets_only, caller
+):
+ settings = _local_snapshot(snapshot, name, snippets_only)
+ if caller == "mcp":
+ result = _execute_search("local research", name, 3, settings)
+ assert result["status"] == "success", result
+ results = result["results"]
+ else:
+ engine = get_search(
+ name, None, settings_snapshot=settings, programmatic_mode=True
+ )
+ assert engine is not None
+ try:
+ results = engine.run("local research")
+ finally:
+ engine.close()
+ _assert_chunk(results, snippets_only)
+
+
[email protected]("include_text_content", [False, True])
+def test_strategy_changes_the_branch_used_by_real_engine_execution(
+ indexed_library, snapshot, include_text_content
+):
+ settings = _local_snapshot(snapshot, "library", include_text_content)
+ engine = create_search_engine(
+ "library", settings_snapshot=settings, programmatic_mode=True
+ )
+ assert engine is not None
+ try:
+ strategy = SourceBasedSearchStrategy(
+ search=engine,
+ model=FakeListLLM(responses=["Unused model response."]),
+ include_text_content=include_text_content,
+ settings_snapshot=settings,
+ )
+ # Before strategy construction the engine has the opposite mode.
+ # Updating only include_full_content (the old dead attribute) must
+ # fail on the actual BaseSearchEngine.run() branch and chunk output.
+ results = strategy.search.run("local research")
+ _assert_chunk(results, not include_text_content)
+ finally:
+ engine.close()