~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(egress): single source of truth for a run's primary engine (fixes mid-run scope_mismatch crash) (#4745)
LearningCircuit8f5d57aa47bd
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.pyindex ebebd3b4f2..5692c0addd 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@@ -19,11 +19,9 @@ from langchain_core.tools import toolfrom langgraph.errors import GraphRecursionErrorfrom loguru import logger-from ...utilities.type_utils import unwrap_settingfrom ...citation_handler import CitationHandlerfrom ..tools.fetch import FETCH_MODES, build_fetch_toolfrom .base_strategy import BaseSearchStrategy-from ...constants import DEFAULT_SEARCH_TOOLfrom ...security import sanitize_error_for_client# ---------------------------------------------------------------------------@@ -574,15 +572,23 @@ class LangGraphAgentStrategy(BaseSearchStrategy):from local_deep_research.security.egress.policy import (PolicyDeniedError,context_from_snapshot,+ resolve_run_primary_engine,)- primary = self._get_current_engine_name() or unwrap_setting(- self.settings_snapshot.get("search.tool")- )try:- return context_from_snapshot(- self.settings_snapshot, primary or DEFAULT_SEARCH_TOOL- )+ # Derive the primary engine the SAME way the factory PEP does —+ # from ``search.tool`` — NOT from the engine class name. Under the+ # default ADAPTIVE scope the primary IS what resolves the concrete+ # scope, so a divergent primary here silently under-filters the+ # agent's tool list: a private collection primary classified via the+ # class heuristic ("libraryrag" -> unknown -> BOTH) left public+ # engines visible, which the factory then hard-denied mid-run+ # (scope_mismatch_private_only). resolve_run_primary_engine raises+ # ValueError when no primary is configured; this advisory filter+ # then degrades to unfiltered (the factory PEP still enforces) —+ # research_service has already failed the run closed by that point.+ primary = resolve_run_primary_engine(self.settings_snapshot)+ return context_from_snapshot(self.settings_snapshot, primary)except PolicyDeniedError:# Corrupted/invalid policy.egress_scope — re-raise so the# caller fails closed instead of silently running unfiltered.diff --git a/src/local_deep_research/security/egress/policy.py b/src/local_deep_research/security/egress/policy.pyindex 9ca95c55b0..4d24c6091a 100644--- a/src/local_deep_research/security/egress/policy.py+++ b/src/local_deep_research/security/egress/policy.py@@ -28,7 +28,6 @@ from loguru import loggerfrom ..network_utils import is_private_ipfrom ...utilities.type_utils import unwrap_setting-from ...constants import DEFAULT_SEARCH_TOOL# Bounded DNS lookup timeout; getaddrinfo has no native timeout kwarg, so@@ -541,12 +540,7 @@ def filter_candidates_by_egress("adaptive",):return engine_names- primary = (- _get_setting_value(- settings_snapshot, "search.tool", DEFAULT_SEARCH_TOOL- )- or DEFAULT_SEARCH_TOOL- )+ primary = resolve_run_primary_engine(settings_snapshot)ctx = context_from_snapshot(settings_snapshot,primary,@@ -1330,6 +1324,63 @@ def _get_setting_value(snapshot: dict, key: str, default):return unwrap_setting(raw)+def resolve_run_primary_engine(+ settings_snapshot: Optional[dict], default: Optional[str] = None+) -> str:+ """Resolve a research run's primary search engine id from a snapshot.++ Single source of truth for "which engine drives this run's egress+ scope". Under the default ADAPTIVE scope the concrete scope is derived by+ classifying THIS primary, so run-scoped callers that build an+ ``EgressContext`` should derive the primary here. Otherwise two layers can+ resolve ADAPTIVE to different scopes and one silently under-enforces — the+ LangGraph tool-list filter once derived the primary from the engine CLASS+ name (a collection -> ``"libraryrag"`` -> unclassified -> BOTH) while the+ factory PEP derived it from ``search.tool`` (the real collection key ->+ PRIVATE_ONLY), so a public engine reached the agent and was then+ hard-denied mid-run (``scope_mismatch_private_only``).++ Reads ``search.tool`` (flat or ``{"value": ...}`` shaped). A blank-after-+ strip (``" "``) or non-string (``5``, list/dict) value is treated as+ MISSING — it must not slip through the truthiness check and classify to the+ permissive BOTH scope.++ A run with NO configured primary is a wiring error, not a normal state.+ Silently substituting a default would set the egress scope from an engine+ the user never chose — and since the system default is public (``searxng``),+ that fails OPEN. So a missing/empty ``search.tool`` raises ``ValueError``+ unless the caller passes an explicit ``default``:++ * run-level callers (research_service, the strategy tool-list filter,+ ``filter_candidates_by_egress``) pass none and fail closed — the worker+ refuses the run; advisory filters degrade to unfiltered with the factory+ PEP still enforcing.+ * the search-engine factory passes ``default=engine_name`` because it is+ evaluating that one specific engine, so deriving the scope from it is+ meaningful rather than arbitrary.++ Raises:+ ValueError: ``search.tool`` is missing/blank/non-string and no truthy+ ``default`` is given.+ """+ primary = (+ _get_setting_value(settings_snapshot, "search.tool", None)+ if settings_snapshot+ else None+ )+ # Blank-after-strip or non-string is not a usable engine id → missing.+ primary = primary.strip() if isinstance(primary, str) else None+ if primary:+ return primary+ if default:+ return default+ raise ValueError(+ "no primary search engine configured: settings 'search.tool' is "+ "missing, blank, or not a string, so the run's egress scope cannot "+ "be resolved"+ )++def _coerce_bool(value) -> bool:"""Coerce a setting value to bool, defensively.diff --git a/src/local_deep_research/web/queue/processor_v2.py b/src/local_deep_research/web/queue/processor_v2.pyindex 5754984f87..af1767bae2 100644--- a/src/local_deep_research/web/queue/processor_v2.py+++ b/src/local_deep_research/web/queue/processor_v2.py@@ -1171,7 +1171,15 @@ class QueueProcessorV2:complete_settings = settings_snapshot.get("settings_snapshot", {})else:submission_params = settings_snapshot- complete_settings = {}+ # A legacy-flat queued row (enqueued by an older version, pre-+ # "submission" wrapper) carries no settings_snapshot. Seed the run's+ # primary engine from the submitted search_engine so the worker's+ # egress build (resolve_run_primary_engine) doesn't fail closed on+ # an empty snapshot and refuse the run.+ _legacy_engine = submission_params.get("search_engine")+ complete_settings = (+ {"search.tool": _legacy_engine} if _legacy_engine else {}+ )try:research_thread = start_research_process(diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.pyindex 61a287d330..69b7056179 100644--- a/src/local_deep_research/web/routes/research_routes.py+++ b/src/local_deep_research/web/routes/research_routes.py@@ -231,6 +231,7 @@ def _precheck_engine_policy(settings_manager, params, search_engine, username):PolicyDeniedError,context_from_snapshot,evaluate_engine,+ resolve_run_primary_engine,)policy_snapshot = settings_manager.get_settings_snapshot()@@ -245,13 +246,16 @@ 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", DEFAULT_SEARCH_TOOL- )+ # Resolve the primary the SAME way the worker does (single source of+ # truth) so the precheck and the background worker agree on accept vs.+ # refuse — including the fail-closed missing-primary case, which the+ # ValueError handler below maps to a 400. (Previously this substituted+ # searxng and accepted runs the worker then refused.)try:+ primary = resolve_run_primary_engine(policy_snapshot)policy_ctx = context_from_snapshot(policy_snapshot,- primary or DEFAULT_SEARCH_TOOL,+ primary,username=username,)except PolicyDeniedError as exc:diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.pyindex bc4df9b0bc..032c877841 100644--- a/src/local_deep_research/web/services/research_service.py+++ b/src/local_deep_research/web/services/research_service.py@@ -34,7 +34,6 @@ from ...utilities.threading_utils import thread_context, thread_with_app_contextfrom ..models.database import calculate_durationfrom ...settings.env_registry import get_env_settingfrom .socket_service import SocketIOService-from ...constants import DEFAULT_SEARCH_TOOLOUTPUT_DIR = get_research_outputs_directory()@@ -941,20 +940,14 @@ def run_research_process(research_id, query, mode, **kwargs):from ...security.egress.policy import (PolicyDeniedError,context_from_snapshot,+ resolve_run_primary_engine,)try:- _egress_primary = settings_snapshot.get(- "search.tool", DEFAULT_SEARCH_TOOL- )- if (- isinstance(_egress_primary, dict)- and "value" in _egress_primary- ):- _egress_primary = _egress_primary["value"]+ _egress_primary = resolve_run_primary_engine(settings_snapshot)_egress_ctx = context_from_snapshot(settings_snapshot,- _egress_primary or DEFAULT_SEARCH_TOOL,+ _egress_primary,username=username,)_set_egress_ctx(_egress_ctx)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.pyindex eb0791d263..cf2c85fe9f 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@@ -3,7 +3,6 @@ from typing import Any, Dict, Optionalfrom loguru import logger-from ..utilities.type_utils import unwrap_settingfrom ..security.egress.policy import PolicyDeniedErrorfrom ..security.module_whitelist import get_safe_module_classfrom .retriever_registry import retriever_registry@@ -57,6 +56,7 @@ def create_search_engine(Decision,context_from_snapshot,evaluate_retriever,+ resolve_run_primary_engine,)if not settings_snapshot:@@ -65,13 +65,13 @@ def create_search_engine(target=engine_name,)- primary_raw = unwrap_setting(- settings_snapshot.get("search.tool", engine_name)+ primary = resolve_run_primary_engine(+ settings_snapshot, default=engine_name)try:_ctx = context_from_snapshot(settings_snapshot,- primary_raw or engine_name,+ primary,username=username,)except PolicyDeniedError:@@ -204,12 +204,15 @@ def create_search_engine(Decision,context_from_snapshot,evaluate_engine,+ resolve_run_primary_engine,)- primary_engine_raw = unwrap_setting(- settings_snapshot.get("search.tool", engine_name)+ # Resolve the run's primary via the shared helper so the scope this PEP+ # enforces matches the one the LangGraph tool-list filter pre-filters with+ # (default: this engine when search.tool is unset).+ primary_engine = resolve_run_primary_engine(+ settings_snapshot, default=engine_name)- primary_engine = primary_engine_raw or engine_nametry:ctx = context_from_snapshot(diff --git a/tests/security/test_egress_langgraph_tool_filter.py b/tests/security/test_egress_langgraph_tool_filter.pyindex 979dc4d7ba..3478ca8cdb 100644--- a/tests/security/test_egress_langgraph_tool_filter.py+++ b/tests/security/test_egress_langgraph_tool_filter.py@@ -87,7 +87,12 @@ def _patched_tool_factories():def _build_tool_names(- scope, available, *, retriever_meta=None, snapshot_extra=None+ scope,+ available,+ *,+ retriever_meta=None,+ snapshot_extra=None,+ primary="searxng",):"""Construct a minimal strategy under ``scope`` and run the REAL``_build_tools`` loop against the mocked engine discovery ``available``.@@ -98,11 +103,20 @@ def _build_tool_names(``retriever_meta`` (e.g. ``{"is_local": True}``) patches the retrieverregistry's metadata lookup so the retriever branch can be exercised.++ ``primary`` sets ``search.tool`` (a real run always has one). Pass+ ``primary=None`` to omit it entirely and exercise the fail-closed path."""snapshot = {"policy.egress_scope": scope,"search.fetch.mode": "disabled",}+ # A real run always has a configured primary. Explicit scopes ignore it+ # (they don't resolve ADAPTIVE); the ADAPTIVE tests override it via+ # snapshot_extra to drive scope resolution. primary=None omits it so+ # resolve_run_primary_engine fails closed (raises) — by design.+ if primary is not None:+ snapshot["search.tool"] = primaryif snapshot_extra:snapshot.update(snapshot_extra)@@ -260,3 +274,77 @@ class TestRetrieverFilter:assert self._RET in namesassert _specialized(names) == {self._RET}assert spec.call_args_list[0].args[0] == self._RET+++# ---------------------------------------------------------------------------+# ADAPTIVE (the DEFAULT scope): the concrete scope FOLLOWS the run's primary+# engine (search.tool) — the same value the factory PEP uses. These cover the+# real-world bug the explicit-scope tests above miss: a private collection+# primary must pull the run into PRIVATE_ONLY so public specialized engines+# never reach the agent. Regression for the silent under-filter where+# _build_egress_context derived the primary from the engine CLASS name instead+# of search.tool — a collection primary classified as unknown -> BOTH -> public+# engines (e.g. pubmed) stayed in the agent's tool list, and the factory then+# hard-denied them mid-run (scope_mismatch_private_only).+# ---------------------------------------------------------------------------+++class TestAdaptiveScopeFollowsPrimary:+ def test_private_primary_excludes_public_engine(self):+ names, spec = _build_tool_names(+ "adaptive",+ {+ _PUBLIC_ENGINE: {"description": "papers"},+ _PRIVATE_ENGINE: {"description": "docs"},+ },+ snapshot_extra={"search.tool": _PRIVATE_ENGINE},+ )+ # ADAPTIVE + private primary => PRIVATE_ONLY: the public engine is+ # filtered before it ever reaches the agent (name absent AND never+ # constructed), the local engine survives.+ assert _PUBLIC_ENGINE not in names+ called = {c.args[0] for c in spec.call_args_list}+ assert _PUBLIC_ENGINE not in called+ assert _specialized(names) == {_PRIVATE_ENGINE}++ def test_public_primary_excludes_private_engine(self):+ names, spec = _build_tool_names(+ "adaptive",+ {+ _PUBLIC_ENGINE: {"description": "papers"},+ _PRIVATE_ENGINE: {"description": "docs"},+ },+ snapshot_extra={"search.tool": _PUBLIC_ENGINE},+ )+ # ADAPTIVE + public primary => PUBLIC_ONLY: the mirror image — the+ # local engine is filtered, the public one survives.+ assert _PRIVATE_ENGINE not in names+ called = {c.args[0] for c in spec.call_args_list}+ assert _PRIVATE_ENGINE not in called+ assert _specialized(names) == {_PUBLIC_ENGINE}+++# ---------------------------------------------------------------------------+# No configured primary: resolve_run_primary_engine raises ValueError inside+# _build_egress_context, which catches it and returns None — the advisory+# tool-list filter degrades to UNFILTERED (the factory PEP still enforces at+# instantiation) instead of crashing the agent. This locks in the fail-closed+# contract so the resolve call can't be moved back outside the try/except.+# ---------------------------------------------------------------------------+++class TestMissingPrimaryDegradesToUnfiltered:+ def test_no_primary_does_not_crash_and_leaves_tools_unfiltered(self):+ # Restrictive scope + NO search.tool. Without the in-try catch this+ # would raise out of _build_tools; with it, policy_ctx is None so the+ # filter loop never runs and every discovered engine survives (the+ # public one is refused later by the factory PEP, not here).+ names, _ = _build_tool_names(+ "private_only",+ {+ _PUBLIC_ENGINE: {"description": "papers"},+ _PRIVATE_ENGINE: {"description": "docs"},+ },+ primary=None,+ )+ assert _specialized(names) == {_PUBLIC_ENGINE, _PRIVATE_ENGINE}diff --git a/tests/security/test_egress_policy.py b/tests/security/test_egress_policy.pyindex b9d02d772d..54e52c4788 100644--- a/tests/security/test_egress_policy.py+++ b/tests/security/test_egress_policy.py@@ -18,6 +18,7 @@ from local_deep_research.security.egress.policy import (evaluate_llm_endpoint,evaluate_url,filter_engines_by_egress,+ resolve_run_primary_engine,)@@ -2474,3 +2475,99 @@ def test_fetch_quota_falls_back_to_local_ctx_without_run_context():for _ in range(5):evaluate_url("http://10.0.0.5/", ctx)assert ctx._fetch_denial_count["count"] == 5+++# ---------------------------------------------------------------------------+# resolve_run_primary_engine: the single source of truth for a run's primary+# engine (what ADAPTIVE classifies). Every run-scoped EgressContext builder+# routes through this so the scope can't be resolved inconsistently across+# layers (factory PEP vs. LangGraph tool-list pre-filter).+# ---------------------------------------------------------------------------+++class TestResolveRunPrimaryEngine:+ def test_reads_flat_search_tool(self):+ assert resolve_run_primary_engine({"search.tool": "pubmed"}) == "pubmed"++ def test_reads_nested_value_shape(self):+ # The {"value": ...} settings shape is unwrapped like everywhere else.+ assert (+ resolve_run_primary_engine({"search.tool": {"value": "paperless"}})+ == "paperless"+ )++ # --- Fail closed: a missing/empty primary must NOT silently become a+ # default (public) engine, which would set the egress scope from an engine+ # the user never chose. Run-level callers pass no default and must raise.++ def test_missing_key_raises(self):+ with pytest.raises(ValueError, match="no primary search engine"):+ resolve_run_primary_engine({})++ def test_none_snapshot_raises(self):+ with pytest.raises(ValueError, match="no primary search engine"):+ resolve_run_primary_engine(None)++ def test_empty_value_raises(self):+ with pytest.raises(ValueError, match="no primary search engine"):+ resolve_run_primary_engine({"search.tool": ""})++ def test_blank_nested_value_raises(self):+ # A {"value": ""} shape unwraps to "" — still no configured primary.+ with pytest.raises(ValueError, match="no primary search engine"):+ resolve_run_primary_engine({"search.tool": {"value": ""}})++ # --- Explicit default escape hatch: the factory passes default=engine_name+ # because it is evaluating that one specific engine.++ def test_custom_default_used_when_missing(self):+ assert resolve_run_primary_engine({}, default="arxiv") == "arxiv"++ def test_custom_default_used_when_empty(self):+ assert (+ resolve_run_primary_engine({"search.tool": ""}, default="arxiv")+ == "arxiv"+ )++ def test_explicit_value_wins_over_custom_default(self):+ assert (+ resolve_run_primary_engine(+ {"search.tool": "wikipedia"}, default="arxiv"+ )+ == "wikipedia"+ )++ # --- A truthy-but-unusable primary (whitespace / non-string) must NOT+ # slip past the fail-closed guard and classify to the permissive BOTH.++ def test_whitespace_only_raises(self):+ with pytest.raises(ValueError, match="no primary search engine"):+ resolve_run_primary_engine({"search.tool": " "})++ def test_whitespace_is_stripped(self):+ assert (+ resolve_run_primary_engine({"search.tool": " pubmed "})+ == "pubmed"+ )++ def test_non_string_raises(self):+ for bad in (5, True, ["arxiv"], {"nested": 1}):+ with pytest.raises(ValueError, match="no primary search engine"):+ resolve_run_primary_engine({"search.tool": bad})++ def test_nested_whitespace_value_raises(self):+ with pytest.raises(ValueError, match="no primary search engine"):+ resolve_run_primary_engine({"search.tool": {"value": " "}})++ def test_empty_default_is_treated_as_no_default(self):+ # default="" must not satisfy the fail-closed guard (the old+ # `if default is not None` would have returned "").+ with pytest.raises(ValueError, match="no primary search engine"):+ resolve_run_primary_engine({}, default="")++ def test_whitespace_default_falls_through_to_value(self):+ # A blank default doesn't mask a real primary.+ assert (+ resolve_run_primary_engine({"search.tool": "arxiv"}, default=" ")+ == "arxiv"+ )diff --git a/tests/web/queue/test_processor_v2_real.py b/tests/web/queue/test_processor_v2_real.pyindex a9fcc91252..81122d1fb8 100644--- a/tests/web/queue/test_processor_v2_real.py+++ b/tests/web/queue/test_processor_v2_real.py@@ -633,6 +633,42 @@ class TestStartResearch:assert call_kwargs["model"] == "claude-3"assert call_kwargs["settings_snapshot"] == {}+ @patch(f"{MODULE}.start_research_process")+ def test_legacy_format_seeds_search_tool_from_search_engine(+ self, mock_start_research+ ):+ """A legacy-flat row that carries a search_engine seeds the (otherwise+ empty) settings_snapshot with search.tool, so the worker's egress build+ (resolve_run_primary_engine) doesn't fail closed on an empty snapshot+ and refuse a replayed pre-upgrade queued run."""+ from local_deep_research.constants import ResearchStatus++ processor = _make_processor()+ mock_thread = Mock()+ mock_thread.ident = 1+ mock_start_research.return_value = mock_thread++ mock_session = MagicMock()+ mock_research = Mock()+ mock_research.status = ResearchStatus.QUEUED+ mock_session.query.return_value.filter_by.return_value.first.return_value = mock_research++ queued = Mock()+ queued.research_id = "r-102"+ queued.query = "legacy query"+ queued.mode = "standard"+ queued.settings_snapshot = {+ "model_provider": "anthropic",+ "search_engine": "pubmed",+ }++ with patch(f"{MODULE}.UserActiveResearch"):+ processor._start_research(mock_session, "alice", "pw", queued)++ call_kwargs = mock_start_research.call_args.kwargs+ assert call_kwargs["settings_snapshot"] == {"search.tool": "pubmed"}+ assert call_kwargs["search_engine"] == "pubmed"+@patch(f"{MODULE}.start_research_process")def test_none_settings_snapshot_handled(self, mock_start_research):"""None settings_snapshot treated as empty dict."""diff --git a/tests/web/routes/test_research_routes_policy.py b/tests/web/routes/test_research_routes_policy.pyindex 683e240dbb..806c6e3ddc 100644--- a/tests/web/routes/test_research_routes_policy.py+++ b/tests/web/routes/test_research_routes_policy.py@@ -63,6 +63,11 @@ class TestApplyPolicyOverrides:def _mgr(snapshot, primary="arxiv"):m = Mock()+ # A real settings snapshot always carries the primary under "search.tool".+ # The precheck now resolves the primary FROM the snapshot (matching the+ # worker via resolve_run_primary_engine), so reflect that here.+ if isinstance(snapshot, dict) and "search.tool" not in snapshot:+ snapshot = {**snapshot, "search.tool": primary}m.get_settings_snapshot.return_value = snapshotm.get_setting.side_effect = lambda key, default=None: (primary if key == "search.tool" else default@@ -103,6 +108,15 @@ class TestPrecheckEnginePolicy:mgr = _mgr(None)assert _precheck_engine_policy(mgr, {}, "library", "user") is None+ def test_missing_primary_returns_400(self, app_ctx):+ # No configured primary (empty search.tool) => the precheck fails+ # CLOSED at the API boundary (400), matching the worker — no silent+ # searxng fallback that would accept a run the worker then refuses.+ mgr = _mgr({"policy.egress_scope": "public_only", "search.tool": ""})+ result = _precheck_engine_policy(mgr, {}, "arxiv", "user")+ assert result is not None+ assert result[1] == 400+def test_per_research_override_tightens_scope(self, app_ctx):# Saved scope is permissive (both) but the form overrides to# public_only for THIS run => a local engine must be refused.diff --git a/tests/web/services/test_research_service_coverage.py b/tests/web/services/test_research_service_coverage.pyindex aa49a6434f..c62d5bdf35 100644--- a/tests/web/services/test_research_service_coverage.py+++ b/tests/web/services/test_research_service_coverage.py@@ -677,7 +677,7 @@ class TestRunResearchProcessQuickMode:kwargs = dict(username="alice",- settings_snapshot={},+ settings_snapshot={"search.tool": "searxng"},**extra_kwargs,)@@ -967,7 +967,7 @@ class TestRunResearchProcessQuickMode:"test","quick",username="alice",- settings_snapshot={},+ settings_snapshot={"search.tool": "searxng"},model="m",search_engine="s",)@@ -1082,7 +1082,7 @@ class TestRunResearchProcessDetailedMode:"query","detailed",username="alice",- settings_snapshot={},+ settings_snapshot={"search.tool": "searxng"},model="m",search_engine="s",)@@ -1212,7 +1212,7 @@ class TestRunResearchProcessDetailedMode:"query","detailed",username="alice",- settings_snapshot={},+ settings_snapshot={"search.tool": "searxng"},model="m",search_engine="s",)@@ -1302,7 +1302,7 @@ class TestRunResearchProcessDetailedMode:"query","detailed",username="alice",- settings_snapshot={},+ settings_snapshot={"search.tool": "searxng"},model="m",search_engine="s",)@@ -1370,7 +1370,7 @@ class TestRunResearchProcessSearchErrors:"query","quick",username="alice",- settings_snapshot={},+ settings_snapshot={"search.tool": "searxng"},model="m",search_engine="s",)@@ -1450,7 +1450,7 @@ class TestRunResearchProcessLLMConfigErrors:"query","quick",username="alice",- settings_snapshot={},+ settings_snapshot={"search.tool": "searxng"},model="m",model_provider="llamacpp",)@@ -1508,7 +1508,7 @@ class TestRunResearchProcessLLMConfigErrors:"query","quick",username="alice",- settings_snapshot={},+ settings_snapshot={"search.tool": "searxng"},model="m",search_engine="searxng",)@@ -1572,7 +1572,7 @@ class TestRunResearchProcessErrorHandler:"query","quick",username="alice",- settings_snapshot={},+ settings_snapshot={"search.tool": "searxng"},model="m",search_engine="s",)@@ -1633,7 +1633,7 @@ class TestRunResearchProcessErrorHandler:"query","quick",username="alice",- settings_snapshot={},+ settings_snapshot={"search.tool": "searxng"},model="m",search_engine="s",)@@ -1696,7 +1696,7 @@ class TestRunResearchProcessErrorHandler:"query","quick",username="alice",- settings_snapshot={},+ settings_snapshot={"search.tool": "searxng"},model="m",search_engine="s",)@@ -1759,7 +1759,7 @@ class TestRunResearchProcessErrorHandler:"query","quick",username="alice",- settings_snapshot={},+ settings_snapshot={"search.tool": "searxng"},model="m",search_engine="s",)@@ -1820,7 +1820,7 @@ class TestRunResearchProcessErrorHandler:"query","quick",username="alice",- settings_snapshot={},+ settings_snapshot={"search.tool": "searxng"},model="m",search_engine="s",)@@ -1880,7 +1880,7 @@ class TestRunResearchProcessErrorHandler:"query","quick",username="alice",- settings_snapshot={},+ settings_snapshot={"search.tool": "searxng"},model="m",search_engine="s",)@@ -1953,7 +1953,7 @@ class TestRunResearchProcessResearchContext:"follow-up query","quick",username="alice",- settings_snapshot={},+ settings_snapshot={"search.tool": "searxng"},model="m",search_engine="s",research_context={@@ -1985,13 +1985,17 @@ class TestRunResearchProcessSettingsContext:mock_storage.save_report.return_value = Truemock_qp = MagicMock()- # Settings snapshot with both raw values and setting objects+ # Settings snapshot with both raw values and setting objects.+ # Includes search.tool so the run proceeds past the egress build+ # (which fails closed on a snapshot with no primary) to the+ # SettingsContext extraction under test.snapshot = {"report.citation_format": {"value": "number_hyperlinks","type": "str",},"search.max_results": 10, # raw value+ "search.tool": "searxng",}with (@@ -2132,7 +2136,7 @@ class TestRunResearchProcessSubscription:"query","quick",username="alice",- settings_snapshot={},+ settings_snapshot={"search.tool": "searxng"},model="m",search_engine="s",)@@ -2210,7 +2214,7 @@ class TestRunResearchProcessFinallyBlock:"query","quick",username="alice",- settings_snapshot={},+ settings_snapshot={"search.tool": "searxng"},model="m",search_engine="s",)@@ -2288,7 +2292,7 @@ class TestRunResearchProcessFinallyBlock:"query","quick",username="alice",- settings_snapshot={},+ settings_snapshot={"search.tool": "searxng"},model="m",search_engine="s",)@@ -2361,7 +2365,7 @@ class TestRunResearchProcessSaveReportFailure:"query","quick",username="alice",- settings_snapshot={},+ settings_snapshot={"search.tool": "searxng"},model="m",search_engine="s",)diff --git a/tests/web/services/test_research_service_coverage_gaps.py b/tests/web/services/test_research_service_coverage_gaps.pyindex daef770a24..3d40aceafe 100644--- a/tests/web/services/test_research_service_coverage_gaps.py+++ b/tests/web/services/test_research_service_coverage_gaps.py@@ -245,7 +245,7 @@ class TestSettingsContextInnerClass:"test","quick",username="user1",- settings_snapshot={},+ settings_snapshot={"search.tool": "searxng"},)finally:for p in stack:@@ -256,6 +256,51 @@ class TestSettingsContextInnerClass:assert ctx.get_setting("nonexistent.key") is None+# ---------------------------------------------------------------------------+# 2b. Worker fails closed when the run has no configured primary engine+# ---------------------------------------------------------------------------+++class TestWorkerFailsClosedOnMissingPrimary:+ """The CLI/scheduler/queue path bypasses the API precheck, so the worker is+ the only gate. A snapshot with no ``search.tool`` must make+ run_research_process refuse the run at the egress build+ (resolve_run_primary_engine raises ValueError) — fail closed — rather than+ silently running on the public ``searxng`` default. Regression guard for+ the security-relevant fail-closed change."""++ def test_missing_primary_never_reaches_search_system(self):+ func = _get_raw_run_research_process()++ mock_system = MagicMock()+ mock_system.analyze_topic.return_value = {+ "findings": "x",+ "formatted_findings": "x",+ }+ patches = _base_run_patches()+ patches[f"{MODULE}.AdvancedSearchSystem"] = MagicMock(+ return_value=mock_system+ )++ stack = []+ for target, mock_obj in patches.items():+ p = patch(target, mock_obj)+ stack.append(p)+ p.start()+ try:+ # Empty snapshot => no search.tool => egress build raises =>+ # run_research_process handles it as a failed run internally.+ func(1, "test", "quick", username="user1", settings_snapshot={})+ finally:+ for p in stack:+ p.stop()++ # Fail closed: the run aborted before the search system ran. (A+ # realistic snapshot WITH search.tool does reach analyze_topic — see+ # TestSettingsContextInnerClass — so this isolates the egress refusal.)+ mock_system.analyze_topic.assert_not_called()++# ---------------------------------------------------------------------------# 3. progress_callback termination check (lines 428-434)# ---------------------------------------------------------------------------@@ -303,7 +348,13 @@ class TestProgressCallbackTerminationCheck:p.start()try:# The function catches ResearchTerminatedException internally- func(1, "test", "quick", username="user1", settings_snapshot={})+ func(+ 1,+ "test",+ "quick",+ username="user1",+ settings_snapshot={"search.tool": "searxng"},+ )finally:for p in stack:p.stop()@@ -345,7 +396,7 @@ class TestLLMConfigErrorRaisesValueError:username="user1",model=model,model_provider=provider,- settings_snapshot={},+ settings_snapshot={"search.tool": "searxng"},)finally:for p in stack:@@ -419,7 +470,7 @@ class TestSearchEngineConfigError:"quick",username="user1",search_engine=search_engine,- settings_snapshot={},+ settings_snapshot={"search.tool": "searxng"},)finally:for p in stack:@@ -496,7 +547,7 @@ class TestSearchErrorClassification:"test","quick",username="user1",- settings_snapshot={},+ settings_snapshot={"search.tool": "searxng"},)finally:for p in stack:diff --git a/tests/web/services/test_research_service_deep_coverage.py b/tests/web/services/test_research_service_deep_coverage.pyindex ae2c2fdd9a..a304a3a5ea 100644--- a/tests/web/services/test_research_service_deep_coverage.py+++ b/tests/web/services/test_research_service_deep_coverage.py@@ -555,7 +555,11 @@ class TestLLMConfigErrorPaths:username="user1",model=model,model_provider=model_provider,- settings_snapshot={},+ # Realistic primary so the run reaches the LLM-error+ # path under test (not the egress fail-closed raise).+ settings_snapshot={+ "search.tool": "searxng"+ },)return mock_qpdiff --git a/tests/web/services/test_research_service_progress_integration.py b/tests/web/services/test_research_service_progress_integration.pyindex c495b379ba..a7f0cebc53 100644--- a/tests/web/services/test_research_service_progress_integration.py+++ b/tests/web/services/test_research_service_progress_integration.py@@ -144,6 +144,11 @@ def captured_progress_callback(mode, flask_app):query="test query",mode=mode,username="testuser",+ # A real run always has a configured primary; without it the+ # egress context build fails closed (resolve_run_primary_engine+ # raises) and the worker refuses the run before the callback+ # wiring under test runs.+ settings_snapshot={"search.tool": "searxng"},)yield captured.get("callback"), progress_state, update_calls