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.

fix(web): synchronize runtime overrides with settings snapshot and search system (#6517)

Sef757cfe9890
diff --git a/changelog.d/+runtime-parameters-snapshot-persistence.bugfix.md b/changelog.d/+runtime-parameters-snapshot-persistence.bugfix.md
new file mode 100644
index 0000000000..2d7de5f137
--- /dev/null
+++ b/changelog.d/+runtime-parameters-snapshot-persistence.bugfix.md
@@ -0,0 +1,70 @@
+Synchronized per-research runtime parameter overrides (`search_engine`,
+`model_provider`, `model`, `custom_endpoint`, `iterations`,
+`questions_per_iteration`, `strategy`, `max_results`, `time_period`) onto the
+captured `settings_snapshot` in the start-research precheck, the persisted
+snapshot, and the background worker. Previously those kwargs were not written
+into the snapshot, so LangGraph tools, telemetry, and source-based iteration
+counts read saved database defaults instead of the run's explicit overrides.
+
+Envelope metadata (`{"value": ...}`) is preserved when overlaying so
+snapshot readers that call `.get("value")` keep working.
+
+Plumbed `max_iterations` and `questions_per_iteration` through
+`SourceBasedSearchStrategy`, `create_strategy`, and
+`EnhancedContextualFollowUpStrategy` (forwarded to its delegate strategy).
+Programmatic `_init_search_system` only overlays kwargs that were actually
+passed, so a snapshot-only `quick_summary` / MCP call is no longer forced to
+`source-based` with 1 iteration.
+
+Added boundary validation for `iterations` (1–100) and
+`questions_per_iteration` (1–20) at entrypoints, rejecting non-integers,
+booleans, floats, JSON `Infinity`/`NaN`, and out-of-bounds values with 400.
+
+User-visible behavior changes:
+* REST `quick_summary` no longer forces `iterations=1`, allowing runs to
+ inherit the caller's configured `search.iterations` setting (or fall back to
+ the router default of 5 when unset in the database).
+* Under `policy.egress_scope == strict`, the requested per-run engine is no
+ longer written into `search.tool` by any overlay (start-research precheck,
+ REST `/api/v1/quick_summary`, programmatic
+ `quick_summary` / `generate_report` / `detailed_research`, background
+ worker). The saved primary remains the STRICT reference on every path —
+ a STRICT user can no longer use `search_engine="searxng"` to widen a
+ run whose saved primary is, e.g., `library`. A run with no valid saved
+ STRICT primary (blank/missing `search.tool`) now fails closed instead of
+ letting the request choose its own primary. Under ADAPTIVE egress
+ scope, the start-research precheck still evaluates the requested engine
+ as the run primary, aligning the precheck with worker-level policy
+ enforcement and updating which engine override requests receive 400
+ refusals.
+
+Report-generation fix:
+* `IntegratedReportGenerator._research_and_generate_sections` now also
+ overrides `max_iterations` on the active strategy's `delegate_strategy`
+ (e.g. the `SourceBasedSearchStrategy` wrapped by
+ `EnhancedContextualFollowUpStrategy`) for the duration of each subsection
+ search. Previously the override only touched the wrapper, so under the
+ follow-up strategy each report subsection ran the delegate's full
+ configured iteration loop instead of one, multiplying search/LLM work
+ and latency across every section of every detailed report.
+
+Request-validation order:
+* A missing `query` now outranks `iterations` /
+ `questions_per_iteration` validation on `POST /api/start_research`
+ (both the wrapper and `_start_research_sync`): a body with no query
+ reports "Query is required" even when the iteration fields are also
+ invalid, matching the `api_v1` query-first order.
+
+Worker context:
+* Under non-STRICT scopes, `build_run_egress_context` with a valid saved
+ primary and no requested engine now proceeds with the saved engine
+ (previously raised). No request influence; blank saved + blank
+ requested still refuses.
+
+REST error contract:
+* `POST /api/v1/quick_summary`, `/generate_report`, and
+ `/analyze_documents` map a `PolicyDeniedError` from the research call
+ (e.g. STRICT blank saved primary) to a curated 400 ("Egress policy
+ refused this request: ...") instead of the generic 500 — a curated 400
+ like the global handler's, in the api_v1 `{"error": ...}` envelope
+ matching its sibling 400/504s.
diff --git a/src/local_deep_research/advanced_search_system/strategies/source_based_strategy.py b/src/local_deep_research/advanced_search_system/strategies/source_based_strategy.py
index f89deff45a..4e95b839cd 100644
--- a/src/local_deep_research/advanced_search_system/strategies/source_based_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/source_based_strategy.py
@@ -77,6 +77,8 @@ class SourceBasedSearchStrategy(BaseSearchStrategy):
use_atomic_facts: bool = False,
settings_snapshot=None,
search_original_query: bool = True,
+ max_iterations: int | None = None,
+ questions_per_iteration: int | None = None,
):
"""Initialize with optional dependency injection for testing.
@@ -110,6 +112,8 @@ class SourceBasedSearchStrategy(BaseSearchStrategy):
# Model and search are always provided by AdvancedSearchSystem
self.model = model
self.search = search
+ self.max_iterations = max_iterations
+ self.questions_per_iteration = questions_per_iteration
# Note: progress_callback and questions_by_iteration are already set by parent class
# Resolve include_text_content:
@@ -224,11 +228,17 @@ class SourceBasedSearchStrategy(BaseSearchStrategy):
}
# Determine number of iterations to run
- iterations_to_run = self.get_setting("search.iterations", 2)
- iterations_to_run = int(iterations_to_run)
- questions_per_iteration = self.get_setting(
- "search.questions_per_iteration", 3
- )
+ if self.max_iterations is not None:
+ iterations_to_run = int(self.max_iterations)
+ else:
+ iterations_to_run = int(self.get_setting("search.iterations", 2))
+
+ if self.questions_per_iteration is not None:
+ questions_per_iteration = int(self.questions_per_iteration)
+ else:
+ questions_per_iteration = int(
+ self.get_setting("search.questions_per_iteration", 3)
+ )
logger.info(
f"SourceBasedStrategy configuration - iterations: {iterations_to_run}, questions_per_iteration: {questions_per_iteration}"
@@ -290,11 +300,7 @@ class SourceBasedSearchStrategy(BaseSearchStrategy):
questions = self.question_generator.generate_questions(
current_knowledge=context,
query=query,
- questions_per_iteration=int(
- self.get_setting(
- "search.questions_per_iteration", 5
- ) # Default to 5 if not set
- ),
+ questions_per_iteration=questions_per_iteration,
questions_by_iteration=self.questions_by_iteration,
)
@@ -354,11 +360,7 @@ class SourceBasedSearchStrategy(BaseSearchStrategy):
questions = self.question_generator.generate_questions(
current_knowledge=context,
query=query,
- questions_per_iteration=int(
- self.get_setting(
- "search.questions_per_iteration", 2
- )
- ),
+ questions_per_iteration=questions_per_iteration,
questions_by_iteration=self.questions_by_iteration,
)
diff --git a/src/local_deep_research/api/research_functions.py b/src/local_deep_research/api/research_functions.py
index bbf124248d..9119304445 100644
--- a/src/local_deep_research/api/research_functions.py
+++ b/src/local_deep_research/api/research_functions.py
@@ -16,6 +16,7 @@ from ..report_generator import IntegratedReportGenerator
from ..search_system import AdvancedSearchSystem
from ..utilities.db_utils import no_db_settings
from ..utilities.thread_context import clear_search_context, set_search_context
+from ..utilities.type_utils import overlay_runtime_settings
from .settings_utils import create_settings_snapshot
from ..utilities.llm_utils import invoke_llm_sync
@@ -38,9 +39,9 @@ def _init_search_system(
openai_endpoint_url: str | None = None,
progress_callback: Callable[[str, int, dict], None] | None = None,
search_tool: str | None = None,
- search_strategy: str = "source_based",
- iterations: int = 1,
- questions_per_iteration: int = 1,
+ search_strategy: str | None = None,
+ iterations: int | None = None,
+ questions_per_iteration: int | None = None,
retrievers: dict[str, Any] | None = None,
llms: dict[str, Any] | None = None,
username: str | None = None,
@@ -64,11 +65,10 @@ 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 (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
- search_strategy: The name of the search strategy to use.
+ search_tool: Search engine to use (searxng, wikipedia, arxiv, etc.). If None, uses snapshot/default
+ search_strategy: Search strategy to use. If None, uses snapshot or source-based
+ iterations: Number of research cycles to perform. If None, uses snapshot/default
+ questions_per_iteration: Number of questions to generate per cycle. If None, uses snapshot/default
retrievers: Optional dictionary of {name: retriever} pairs to use as search engines
llms: Optional dictionary of {name: llm} pairs to use as language models
programmatic_mode: If True, disables database operations and metrics tracking
@@ -99,6 +99,26 @@ def _init_search_system(
if settings_snapshot is None:
settings_snapshot = kwargs.get("settings_snapshot")
+ if settings_snapshot is not None:
+ settings_snapshot = dict(settings_snapshot)
+ overlay_runtime_settings(
+ settings_snapshot,
+ search_tool=search_tool,
+ model_provider=provider,
+ model=model_name,
+ custom_endpoint=openai_endpoint_url,
+ iterations=iterations,
+ questions_per_iteration=questions_per_iteration,
+ search_strategy=search_strategy,
+ )
+
+ if search_strategy is None and settings_snapshot:
+ search_strategy = get_setting_from_snapshot(
+ "search.search_strategy",
+ default=None,
+ settings_snapshot=settings_snapshot,
+ )
+
# Get language model with custom temperature
llm = get_llm(
temperature=temperature,
@@ -118,7 +138,7 @@ def _init_search_system(
# If no search_tool provided, get from settings_snapshot
if not search_tool and settings_snapshot:
search_tool = get_setting_from_snapshot(
- "search.tool", settings_snapshot=settings_snapshot
+ "search.tool", default=None, settings_snapshot=settings_snapshot
)
if search_tool:
@@ -139,13 +159,15 @@ def _init_search_system(
system = AdvancedSearchSystem(
llm=llm,
search=search_engine,
- strategy_name=search_strategy,
+ strategy_name=search_strategy or "source-based",
username=username,
research_id=research_id,
research_context=research_context,
settings_snapshot=settings_snapshot,
programmatic_mode=programmatic_mode,
search_original_query=search_original_query,
+ max_iterations=iterations,
+ questions_per_iteration=questions_per_iteration,
)
except Exception:
from ..utilities.resource_utils import safe_close
@@ -153,10 +175,6 @@ def _init_search_system(
safe_close(llm, "init LLM")
raise
- # Override default settings with user-provided values
- system.max_iterations = iterations
- system.questions_per_iteration = questions_per_iteration
-
# Set progress callback if provided
if progress_callback:
system.set_progress_callback(progress_callback)
diff --git a/src/local_deep_research/report_generator.py b/src/local_deep_research/report_generator.py
index feb41bee9a..62f1779a93 100644
--- a/src/local_deep_research/report_generator.py
+++ b/src/local_deep_research/report_generator.py
@@ -1518,6 +1518,21 @@ class IntegratedReportGenerator:
# strategies that cache it at __init__ time
original_max_iter = getattr(strategy, "max_iterations", None)
strategy.max_iterations = 1
+ # If the strategy wraps a delegate (e.g.
+ # EnhancedContextualFollowUpStrategy), the actual research
+ # happens inside ``delegate_strategy.analyze_topic`` and the
+ # delegate has its own cached ``max_iterations`` from
+ # construction — without this extra override the per-subsection
+ # cap never reaches the worker and each subsection runs the
+ # full configured loop instead of one iteration.
+ delegate = getattr(strategy, "delegate_strategy", None)
+ original_delegate_max_iter = (
+ getattr(delegate, "max_iterations", None)
+ if delegate is not None
+ else None
+ )
+ if delegate is not None and hasattr(delegate, "max_iterations"):
+ delegate.max_iterations = 1
try:
# Perform search for this subsection
@@ -1536,6 +1551,13 @@ class IntegratedReportGenerator:
)
if original_max_iter is not None:
strategy.max_iterations = original_max_iter
+ if delegate is not None and hasattr(
+ delegate, "max_iterations"
+ ):
+ if original_delegate_max_iter is not None:
+ delegate.max_iterations = original_delegate_max_iter
+ else:
+ delegate.max_iterations = None
completed_subsections += 1
diff --git a/src/local_deep_research/search_system.py b/src/local_deep_research/search_system.py
index 2a94f0ed8c..27d46bf778 100644
--- a/src/local_deep_research/search_system.py
+++ b/src/local_deep_research/search_system.py
@@ -224,6 +224,8 @@ class AdvancedSearchSystem:
settings_snapshot=self.settings_snapshot,
knowledge_accumulation_mode=True,
search_original_query=self.search_original_query,
+ max_iterations=self.max_iterations,
+ questions_per_iteration=self.questions_per_iteration,
)
# Create the contextual follow-up strategy with the delegate
diff --git a/src/local_deep_research/search_system_factory.py b/src/local_deep_research/search_system_factory.py
index 3390f93b2f..e0b4b0dcac 100644
--- a/src/local_deep_research/search_system_factory.py
+++ b/src/local_deep_research/search_system_factory.py
@@ -75,6 +75,8 @@ def create_strategy(
use_atomic_facts=kwargs.get("use_atomic_facts", False),
settings_snapshot=settings_snapshot,
search_original_query=kwargs.get("search_original_query", True),
+ max_iterations=kwargs.get("max_iterations"),
+ questions_per_iteration=kwargs.get("questions_per_iteration"),
)
# Focused iteration strategy
diff --git a/src/local_deep_research/security/egress/policy.py b/src/local_deep_research/security/egress/policy.py
index e79fed9688..2afaf28649 100644
--- a/src/local_deep_research/security/egress/policy.py
+++ b/src/local_deep_research/security/egress/policy.py
@@ -2373,13 +2373,28 @@ def build_run_egress_context(
carrying an operator-disabled ``unprotected`` scope is coerced to a
protected scope here (via the read-time backstop in
``context_from_snapshot``), not at queue extraction time.
+
+ Under ``STRICT`` the primary is the *saved* snapshot primary only — a
+ blank/missing saved primary raises ``ValueError`` (fail closed) rather
+ than letting the request choose its own primary. Under every other
+ scope the requested engine wins when present, matching
+ ``_precheck_engine_policy``.
"""
from ...settings.manager import (
apply_environment_overrides_to_snapshot,
)
effective = apply_environment_overrides_to_snapshot(settings_snapshot or {})
- primary = resolve_run_primary_engine({"search.tool": search_engine})
+ scope_raw = _get_setting_value(
+ effective, "policy.egress_scope", DEFAULT_EGRESS_SCOPE
+ )
+ if str(scope_raw).strip().lower() == EgressScope.STRICT.value:
+ primary = resolve_run_primary_engine(effective)
+ else:
+ saved_primary = resolve_run_primary_engine(
+ effective, default=search_engine or None
+ )
+ primary = search_engine or saved_primary
return context_from_snapshot(effective, primary, username=username)
diff --git a/src/local_deep_research/utilities/type_utils.py b/src/local_deep_research/utilities/type_utils.py
index a4a18e60d9..36611fe941 100644
--- a/src/local_deep_research/utilities/type_utils.py
+++ b/src/local_deep_research/utilities/type_utils.py
@@ -80,6 +80,106 @@ def unwrap_setting(val: Any) -> Any:
return val
+def overlay_snapshot_value(snapshot: dict, key: str, value: Any) -> None:
+ """Write an override into a settings snapshot without dropping envelope metadata.
+
+ Snapshots from ``SettingsManager.get_all_settings`` store
+ ``{"value": actual, "ui_element": ...}``. Replacing the whole entry with a
+ raw value breaks readers that call ``.get("value")``. Copy the envelope
+ and replace only ``value`` when present; otherwise assign ``value`` raw.
+ """
+ existing = snapshot.get(key)
+ if isinstance(existing, dict) and "value" in existing:
+ snapshot[key] = {**existing, "value": value}
+ else:
+ snapshot[key] = value
+
+
+_RUNTIME_SETTING_MAP = (
+ ("search_engine", "search.tool"),
+ ("search_tool", "search.tool"),
+ ("model_provider", "llm.provider"),
+ ("model", "llm.model"),
+ ("custom_endpoint", "llm.openai_endpoint.url"),
+ ("iterations", "search.iterations"),
+ ("questions_per_iteration", "search.questions_per_iteration"),
+ ("strategy", "search.search_strategy"),
+ ("search_strategy", "search.search_strategy"),
+ ("max_results", "search.max_results"),
+ ("time_period", "search.time_period"),
+)
+
+
+def _is_strict_scope(snapshot: dict) -> bool:
+ """Best-effort STRICT-scope detection on a settings snapshot.
+
+ Returns True when ``policy.egress_scope`` resolves to ``strict``,
+ honoring the operator env override ``LDR_POLICY_EGRESS_SCOPE`` that
+ ``context_from_snapshot`` itself honors. Used by
+ :func:`overlay_runtime_settings` to leave ``search.tool`` untouched
+ when STRICT is active — see the helper's docstring for the
+ security rationale.
+
+ The env lookup goes through ``SettingsManager.check_env_setting``
+ (lazy import) to match the rest of the codebase's policy plumbing
+ and to honor the project's env-var hook. When the snapshot is
+ missing/corrupt and the env var is unset we return False so the
+ overlay still works for callers that genuinely need it (e.g. tests
+ with synthetic snapshots).
+ """
+ try:
+ from ..settings.manager import check_env_setting
+ except ImportError:
+ return False
+
+ env_scope = check_env_setting("policy.egress_scope")
+ if env_scope:
+ return str(env_scope).strip().lower() == "strict"
+ raw = snapshot.get("policy.egress_scope")
+ if isinstance(raw, dict) and "value" in raw:
+ raw = raw["value"]
+ if raw is None:
+ return False
+ return str(raw).strip().lower() == "strict"
+
+
+def overlay_runtime_settings(
+ snapshot: dict | None, **runtime: Any
+) -> dict | None:
+ """Overlay per-run kwargs onto a settings snapshot in place.
+
+ ``None`` values are skipped so callers can pass through unspecified
+ fields without clobbering snapshot defaults.
+
+ STRICT-scope security note: under ``policy.egress_scope == strict``
+ the factory PEP only admits the saved primary engine
+ (``search.tool``), so overwriting ``search.tool`` with the requested
+ ``search_engine``/``search_tool`` kwarg would silently widen the
+ run to that engine — every other entrypoint (start-research
+ precheck, REST ``/api/v1/quick_summary``, programmatic
+ ``quick_summary`` / ``generate_report`` / ``detailed_research``,
+ the background worker) feeds its kwargs through this helper, so the
+ skip MUST live here, not at any individual call site. The precheck
+ still evaluates against the saved primary; this skip just keeps
+ that contract true for every other entrypoint too.
+ """
+ if not isinstance(snapshot, dict):
+ return snapshot
+ # Resolve STRICT once; only the two kwargs that write search.tool
+ # are affected (search_engine + the legacy search_tool alias).
+ strict_scope = _is_strict_scope(snapshot)
+ for arg, key in _RUNTIME_SETTING_MAP:
+ if arg in runtime and runtime[arg] is not None:
+ if (
+ strict_scope
+ and key == "search.tool"
+ and arg in ("search_engine", "search_tool")
+ ):
+ continue
+ overlay_snapshot_value(snapshot, key, runtime[arg])
+ return snapshot
+
+
def resolve_snippets_only(
settings_snapshot: Optional[Dict[str, Any]],
) -> Optional[bool]:
diff --git a/src/local_deep_research/web/routers/api_v1.py b/src/local_deep_research/web/routers/api_v1.py
index 3c957ead22..51d96b0913 100644
--- a/src/local_deep_research/web/routers/api_v1.py
+++ b/src/local_deep_research/web/routers/api_v1.py
@@ -31,6 +31,12 @@ from ..dependencies.rate_limit import (
set_request_api_rate_limit,
)
from ..dependencies.threadpool import run_db_sync
+from ..routes.research_validation import (
+ ITERATIONS_MAX,
+ ITERATIONS_MIN,
+ QUESTIONS_PER_ITERATION_MAX,
+ QUESTIONS_PER_ITERATION_MIN,
+)
router = APIRouter(prefix="/api/v1", tags=["API v1"])
@@ -535,46 +541,12 @@ _SERVER_PATH_PARAMS = frozenset({"output_file"})
# left as another silent gap in a set whose own comment claims
# completeness.
#
-# ``iterations``/``questions_per_iteration`` are forwarded (see
-# ``_init_search_system``'s ``system.max_iterations = iterations`` /
-# ``system.questions_per_iteration = questions_per_iteration``) but are
-# deliberately NOT in ``_TYPE_VALIDATED_PARAMS``, for the opposite reason
-# from ``search_tool`` above: tracing their actual consumer shows there is
-# nothing to protect. Both assignments are bare attribute writes with no
-# operation performed on the value at that call site, so no JSON type
-# whatsoever raises there. And unlike ``max_iterations``/
-# ``questions_per_iteration`` passed directly into ``AdvancedSearchSystem``
-# (which DO feed ``range(1, self.max_iterations + 1)`` in
-# ``advanced_search_system/strategies/focused_iteration_strategy.py``),
-# ``_init_search_system`` never passes either kwarg into the
-# ``AdvancedSearchSystem(...)`` constructor call above — only the
-# post-construction attribute-assignment lines do — and nothing anywhere
-# in the tree reads ``system.max_iterations``/``system.questions_per_iteration``
-# back out afterward (``report_generator.py`` reads ``strategy.``, not
-# ``system.``). ``AdvancedSearchSystem`` instead resolves its own
-# ``self.max_iterations``/``self.questions_per_iteration`` from
-# ``search.iterations``/``search.questions_per_iteration`` in the settings
-# snapshot whenever the constructor argument is ``None`` — which it always
-# is here, since ``_init_search_system`` never supplies one. So on the
-# REST path (unlike a direct in-process ``AdvancedSearchSystem(...)`` call
-# with ``max_iterations=`` set), both are pure no-ops regardless of what a
-# caller posts for them — an earlier version of this comment claimed
-# ``iterations`` reaches ``range(1, self.max_iterations + 1)`` and crashes
-# mid-research on a bad type; that was traced to the wrong constructor
-# call and is false. Given that, type-validating ``iterations`` would be
-# cosmetic only — no crash exists to prevent, unlike ``model_name``/
-# ``search_strategy``/``search_tool`` above — so it is left out rather
-# than added for symmetry alone. Both stay forwarded rather than moved
-# into ``_ACCEPTED_BUT_INEFFECTIVE_PARAMS`` alongside ``temperature``:
-# unlike ``temperature``, neither has a rescue endpoint to point callers
-# at (``analyze_documents`` doesn't accept an ``iterations`` parameter at
-# all), and popping a kwarg that already does nothing would only change
-# whether the research function *sees* an inert value, not any observable
-# behavior — so this pass limits itself to correcting the record (this
-# comment, the docs strings, the changelog) rather than also changing the
-# accepted/forwarded shape. ``search_tool`` is unaffected by any of this —
-# it IS read (``config/search_config.get_search``), which is exactly why
-# it gets the type check above.
+# ``iterations``/``questions_per_iteration`` are forwarded into
+# ``_init_search_system`` when present. Omitted keys stay omitted so the
+# snapshot's ``search.iterations`` / ``search.questions_per_iteration``
+# are used. When present, they are boundary-validated in
+# ``_validate_param_types`` (finite ints, 1..100 for iterations, 1..20 for
+# questions_per_iteration) before reaching downstream consumers.
_REJECTED_BODY_PARAMS = (
_REGISTRY_PARAMS
| _CALLABLE_PARAMS
@@ -646,10 +618,10 @@ def _pop_ineffective_params(params: Dict[str, Any]) -> list:
# Forwarded **kwargs keys with a confirmed unconditional, un-type-checked
# operation performed on them by their first consumer (see the
# ``model_name``/``search_strategy``/``search_tool`` bullets in the
-# ``_REJECTED_BODY_PARAMS`` comment above for the exact call sites and why
-# ``iterations``/``questions_per_iteration`` are deliberately NOT here —
-# their consumer is a bare attribute assignment, so no type ever crashes
-# there). A JSON body sending the wrong scalar type for one of these three
+# ``_REJECTED_BODY_PARAMS`` comment above for the exact call sites;
+# ``iterations``/``questions_per_iteration`` are validated separately
+# below in ``_validate_param_types`` for integer type and range). A JSON
+# body sending the wrong scalar type for one of these three
# reaches that operation and 500s — the same opaque-500 shape
# ``_ANALYZE_DOCUMENTS_PARAMS`` exists to prevent for analyze_documents,
# applied here to the keys on this reject-list path with a confirmed
@@ -718,6 +690,30 @@ def _validate_param_types(data: Dict[str, Any]) -> Optional[JSONResponse]:
f"'{key}' must be a {expected_type.__name__}, got "
f"{type(value).__name__} instead"
)
+
+ if "iterations" in data:
+ val = data["iterations"]
+ if val is not None:
+ if type(val) is not int or not (
+ ITERATIONS_MIN <= val <= ITERATIONS_MAX
+ ):
+ errors.append(
+ f"'iterations' must be an integer between {ITERATIONS_MIN} and {ITERATIONS_MAX}"
+ )
+
+ if "questions_per_iteration" in data:
+ val = data["questions_per_iteration"]
+ if val is not None:
+ if type(val) is not int or not (
+ QUESTIONS_PER_ITERATION_MIN
+ <= val
+ <= QUESTIONS_PER_ITERATION_MAX
+ ):
+ errors.append(
+ f"'questions_per_iteration' must be an integer between "
+ f"{QUESTIONS_PER_ITERATION_MIN} and {QUESTIONS_PER_ITERATION_MAX}"
+ )
+
if errors:
return JSONResponse({"error": "; ".join(errors)}, status_code=400)
return None
@@ -907,7 +903,7 @@ def api_documentation(
"parameters": {
"query": "Research query (required)",
"search_tool": "Search engine to use (optional)",
- "iterations": "Accepted for backward compatibility, but currently has NO observable effect via the REST API: the value is only ever assigned to an attribute nothing reads back, so the research run always uses the account's stored search.iterations setting instead (optional)",
+ "iterations": "Number of research cycles. If omitted, uses the account's stored search.iterations setting (optional)",
"allow_default_settings": "Set to true to proceed with default settings (and NO egress policy) when your stored settings cannot be loaded; default is to refuse with 503 (optional)",
"temperature": "Accepted for backward compatibility but has NO effect on this endpoint (dropped before the research call; a 'warnings' entry is returned when set) — use POST /api/v1/analyze_documents for temperature control (optional)",
},
@@ -1110,14 +1106,13 @@ async def api_quick_summary(
for k, v in data.items()
if k not in ("query", "allow_default_settings")
}
- # Set a reasonable default 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. ``temperature`` is
- # popped out (not defaulted) here — quick_summary only reads its own
- # temperature argument in the branch that builds a settings_snapshot
- # from scratch, which the REST path never takes, so it can't be
- # rescued by forwarding it; see _pop_ineffective_params.
- params.setdefault("iterations", 1)
+ # search_tool and iterations deliberately have no default here: when
+ # omitted, _init_search_system reads the user's configured values from
+ # the settings snapshot. Defaulting iterations to 1 would clobber
+ # stored search.iterations. ``temperature`` is popped out (not
+ # defaulted) here — quick_summary only reads its own temperature
+ # argument in the branch that builds a settings_snapshot from scratch,
+ # which the REST path never takes; see _pop_ineffective_params.
param_warnings = _pop_ineffective_params(params)
error = await run_db_sync(
@@ -1126,6 +1121,8 @@ async def api_quick_summary(
if error is not None:
return error
+ from ...security.egress.policy import PolicyDeniedError
+
try:
from ...api.research_functions import quick_summary
@@ -1159,6 +1156,21 @@ async def api_quick_summary(
},
status_code=504,
)
+ except PolicyDeniedError as exc:
+ # A STRICT blank-primary (or other policy) denial from
+ # _init_search_system / the factory PEP must surface as a curated
+ # 400, not the generic 500 below (which would swallow it before
+ # the global PolicyDeniedError handler can render it). Keeps the
+ # error contract consistent with POST /api/start_research.
+ reason = getattr(getattr(exc, "decision", None), "reason", "denied")
+ logger.bind(policy_audit=True).warning(
+ "POST /api/v1/quick_summary policy denied",
+ reason=reason,
+ )
+ return JSONResponse(
+ {"error": f"Egress policy refused this request: {reason}"},
+ status_code=400,
+ )
except Exception:
logger.exception("Error in quick_summary API")
return JSONResponse(
@@ -1237,6 +1249,8 @@ async def api_generate_report(
if error is not None:
return error
+ from ...security.egress.policy import PolicyDeniedError
+
try:
from ...api.research_functions import generate_report
@@ -1271,6 +1285,17 @@ async def api_generate_report(
{"error": "Request timed out. Please try with a simpler query."},
status_code=504,
)
+ except PolicyDeniedError as exc:
+ # Same 500-vs-400 contract as api_quick_summary above.
+ reason = getattr(getattr(exc, "decision", None), "reason", "denied")
+ logger.bind(policy_audit=True).warning(
+ "POST /api/v1/generate_report policy denied",
+ reason=reason,
+ )
+ return JSONResponse(
+ {"error": f"Egress policy refused this request: {reason}"},
+ status_code=400,
+ )
except Exception:
logger.exception("Error in generate_report API")
return JSONResponse(
@@ -1345,6 +1370,8 @@ async def api_analyze_documents(
if error is not None:
return error
+ from ...security.egress.policy import PolicyDeniedError
+
try:
# run_db_sync: analyze_documents runs local-collection search which
# opens the per-user DB session on the worker thread.
@@ -1355,6 +1382,19 @@ async def api_analyze_documents(
# analyze_documents returns error text under the `summary` key.
_scrub_error_fields(result)
return result
+ except PolicyDeniedError as exc:
+ # Same 500-vs-400 contract as api_quick_summary/generate_report:
+ # a STRICT blank-primary (or other policy) denial from get_llm /
+ # get_search must surface as a curated 400, not the generic 500.
+ reason = getattr(getattr(exc, "decision", None), "reason", "denied")
+ logger.bind(policy_audit=True).warning(
+ "POST /api/v1/analyze_documents policy denied",
+ reason=reason,
+ )
+ return JSONResponse(
+ {"error": f"Egress policy refused this request: {reason}"},
+ status_code=400,
+ )
except Exception:
logger.exception("Error in analyze_documents API")
return JSONResponse(
diff --git a/src/local_deep_research/web/routers/research.py b/src/local_deep_research/web/routers/research.py
index 8b8aa3c518..1313781261 100644
--- a/src/local_deep_research/web/routers/research.py
+++ b/src/local_deep_research/web/routers/research.py
@@ -45,7 +45,7 @@ from ...security import (
sanitize_filename,
strip_settings_snapshot,
)
-from ...utilities.type_utils import to_bool
+from ...utilities.type_utils import overlay_runtime_settings, to_bool
from ...utilities.url_utils import is_safe_custom_llm_endpoint
@@ -80,6 +80,10 @@ from ..services.research_service import (
)
from ..routes.research_validation import (
+ ITERATIONS_MAX,
+ ITERATIONS_MIN,
+ QUESTIONS_PER_ITERATION_MAX,
+ QUESTIONS_PER_ITERATION_MIN,
validate_research_query_length,
validate_search_overrides,
)
@@ -252,9 +256,7 @@ def _extract_research_params(data, settings_manager):
# rejected here. Private IPs stay allowed; cloud-metadata and bad
# schemes are still blocked.
if not is_safe_custom_llm_endpoint(custom_endpoint):
- raise ValueError(
- "custom_endpoint is not a valid HTTP(S) URL or points to a blocked address"
- )
+ raise ValueError("Invalid custom endpoint URL")
ollama_url = data.get("ollama_url")
if not ollama_url and model_provider == "ollama":
@@ -275,11 +277,30 @@ def _extract_research_params(data, settings_manager):
time_period = data.get("time_period")
iterations = data.get("iterations")
- if iterations is None:
+ if iterations is not None:
+ if (
+ type(iterations) is not int
+ or not ITERATIONS_MIN <= iterations <= ITERATIONS_MAX
+ ):
+ raise ValueError(
+ f"iterations must be an integer between {ITERATIONS_MIN} and {ITERATIONS_MAX}"
+ )
+ else:
iterations = settings_manager.get_setting("search.iterations", 5)
questions_per_iteration = data.get("questions_per_iteration")
- if questions_per_iteration is None:
+ if questions_per_iteration is not None:
+ if (
+ type(questions_per_iteration) is not int
+ or not QUESTIONS_PER_ITERATION_MIN
+ <= questions_per_iteration
+ <= QUESTIONS_PER_ITERATION_MAX
+ ):
+ raise ValueError(
+ f"questions_per_iteration must be an integer between "
+ f"{QUESTIONS_PER_ITERATION_MIN} and {QUESTIONS_PER_ITERATION_MAX}"
+ )
+ else:
questions_per_iteration = settings_manager.get_setting(
"search.questions_per_iteration", 5
)
@@ -406,8 +427,15 @@ def _precheck_collection_agent_enabled(
def _precheck_engine_policy(settings_manager, params, search_engine, username):
- """Validate the requested search engine against the saved egress
- policy at the request boundary.
+ """Validate the requested search engine against this run's egress policy.
+
+ Under non-STRICT scopes the requested engine is overlaid as
+ ``search.tool`` before resolving the primary, matching the worker,
+ so ADAPTIVE scope follows the run engine rather than the saved
+ database default. Under STRICT there is no overlay: the saved
+ primary is resolved first and a blank/missing saved primary fails
+ closed (400), so the request can never choose its own STRICT
+ primary.
Returns a ``JSONResponse`` when the request should be rejected, or
``None`` to continue. Falls through (returns None) when there's no
@@ -416,7 +444,10 @@ def _precheck_engine_policy(settings_manager, params, search_engine, username):
"""
try:
from ...security.egress.policy import (
+ DEFAULT_EGRESS_SCOPE,
+ EgressScope,
PolicyDeniedError,
+ _get_setting_value,
context_from_snapshot,
evaluate_engine,
resolve_run_primary_engine,
@@ -439,7 +470,42 @@ def _precheck_engine_policy(settings_manager, params, search_engine, username):
# searxng and accepted runs the worker then refused.)
try:
_apply_policy_overrides(policy_snapshot, params)
- primary = resolve_run_primary_engine(policy_snapshot)
+
+ scope_raw = _get_setting_value(
+ policy_snapshot, "policy.egress_scope", DEFAULT_EGRESS_SCOPE
+ )
+ from ...settings.manager import check_env_setting
+
+ env_scope = check_env_setting("policy.egress_scope")
+ if env_scope is not None:
+ scope_raw = env_scope
+ scope_str = str(scope_raw).strip().lower()
+
+ if scope_str == EgressScope.STRICT.value:
+ # STRICT must never fall back to the requested engine: a
+ # blank/missing saved primary is a wiring error and must
+ # fail closed (ValueError -> 400 below), not let the
+ # request choose its own primary.
+ saved_primary = resolve_run_primary_engine(policy_snapshot)
+ primary = saved_primary
+ else:
+ saved_primary = resolve_run_primary_engine(
+ policy_snapshot, default=search_engine or None
+ )
+ primary = search_engine or saved_primary
+
+ overlay_runtime_settings(
+ policy_snapshot,
+ search_engine=search_engine,
+ model_provider=params.get("model_provider"),
+ model=params.get("model"),
+ custom_endpoint=params.get("custom_endpoint"),
+ iterations=params.get("iterations"),
+ questions_per_iteration=params.get("questions_per_iteration"),
+ strategy=params.get("strategy"),
+ max_results=params.get("max_results"),
+ time_period=params.get("time_period"),
+ )
policy_ctx = context_from_snapshot(
policy_snapshot,
primary,
@@ -480,15 +546,16 @@ def _precheck_engine_policy(settings_manager, params, search_engine, username):
status_code=400,
)
+ target_engine = search_engine or primary
decision = evaluate_engine(
- search_engine,
+ target_engine,
policy_ctx,
settings_snapshot=policy_snapshot,
)
if not decision.allowed:
logger.bind(policy_audit=True).warning(
"POST /api/start_research search_engine refused",
- engine=search_engine,
+ engine=target_engine,
reason=decision.reason,
)
# Local import: this module imports the egress policy lazily inside
@@ -520,15 +587,15 @@ def _precheck_engine_policy(settings_manager, params, search_engine, username):
# ``_scope_mismatch_how``.
"message": denial_guidance(
decision.reason,
- target=f"Search engine '{search_engine}'",
+ target=f"Search engine '{target_engine}'",
# Raw engine id, used by the guidance to decide
# whether Adaptive (default) is a reliable
# remedy for a scope-mismatch denial (see
# ``_scope_mismatch_how`` — kept separate from
# ``target`` so the formatted display string
# above doesn't break the equality check).
- target_id=search_engine,
- primary_engine=policy_ctx.primary_engine,
+ target_id=target_engine,
+ primary_engine=saved_primary,
),
"reason": decision.reason,
# The frontend uses this to highlight the offending
@@ -614,8 +681,8 @@ def _apply_policy_overrides(settings_snapshot, params):
"""Overlay form-supplied egress policy values onto the snapshot.
Per-research overrides: the user picked these values for this
- specific run and they do NOT persist to the settings DB. Mirrors
- how model / search_engine overrides work today.
+ specific run and they do NOT persist to the settings DB. Search
+ engine / model / iteration overlays live in ``overlay_runtime_settings``.
"""
if not isinstance(settings_snapshot, dict):
return
@@ -646,10 +713,6 @@ def _apply_policy_overrides(settings_snapshot, params):
settings_snapshot["embeddings.require_local"] = to_bool(
params["embeddings_require_local"]
)
- # NOTE: the per-run `custom_endpoint` form value is deliberately NOT
- # overlaid onto llm.openai_endpoint.url — that kwarg is non-functional
- # (config/llm_config.py) and the run reads the URL from the DB setting, so
- # the snapshot already carries the endpoint the run actually uses.
def _research_not_found(research_id, message="Research not found"):
@@ -793,6 +856,14 @@ async def start_research(
{"status": "error", "message": "metadata must be an object"},
status_code=400,
)
+ # Missing query outranks parameter validation so a body with no
+ # query and an invalid iterations value reports "Query is required"
+ # (the more useful message when both are wrong). Mirrors the early
+ # return in _start_research_sync and the api_v1 query-first order.
+ if not query:
+ return JSONResponse(
+ {"status": "error", "message": "Query is required"}, status_code=400
+ )
validation_error = validate_search_overrides(data)
if validation_error is not None:
return JSONResponse(
@@ -825,6 +896,18 @@ def _start_research_sync(
query = data.get("query")
mode = data.get("mode", "quick")
+ # Missing query outranks parameter validation: a body with no query
+ # and an invalid iterations value reports "Query is required" (the
+ # more useful message when both are wrong). The no-query log-preview
+ # probe only exercises the two log sites above this return ("Request
+ # data keys", news "triggered_by"); the sites below (model/provider/
+ # engine/iterations/strategy lines) need a query to run and are pinned
+ # by the with-query probe variant. See #6517 review and #6756.
+ if not query:
+ return JSONResponse(
+ {"status": "error", "message": "Query is required"}, status_code=400
+ )
+
# Replace date placeholders if they exist
if query and "YYYY-MM-DD" in query:
# Use local system time
@@ -852,12 +935,23 @@ def _start_research_sync(
settings_manager = SettingsManager(db_session=db_session)
try:
params = _extract_research_params(data, settings_manager)
- except ValueError:
- # SSRF guard in _extract_research_params rejected the
- # custom_endpoint — return main's clean 400 contract
- # instead of an unhandled 500.
+ except ValueError as exc:
+ # SSRF guard or parameter validation in _extract_research_params
+ # rejected the input — return main's clean 400 contract
+ # instead of an unhandled 500. Map to explicit error messages to
+ # avoid exposing internal exception details (CodeQL py/stack-trace-exposure).
+ msg = str(exc)
+ if "iterations" in msg:
+ error_msg = f"iterations must be an integer between {ITERATIONS_MIN} and {ITERATIONS_MAX}"
+ elif "questions_per_iteration" in msg:
+ error_msg = (
+ f"questions_per_iteration must be an integer between "
+ f"{QUESTIONS_PER_ITERATION_MIN} and {QUESTIONS_PER_ITERATION_MAX}"
+ )
+ else:
+ error_msg = "Invalid custom endpoint URL"
return JSONResponse(
- {"status": "error", "message": "Invalid custom endpoint URL"},
+ {"status": "error", "message": error_msg},
status_code=400,
)
@@ -872,12 +966,10 @@ def _start_research_sync(
strategy = params["strategy"]
# Egress policy: server-side check on the requested search
- # engine BEFORE we enqueue the research. Defends against an API
- # client posting an engine name that violates the saved policy
- # (e.g. ``{"search_engine": "pubmed"}`` under STRICT+primary=arxiv).
- # The factory PEP catches the same case at instantiation time,
- # but rejecting at the request boundary lets us return a clean
- # 4xx instead of an opaque background failure.
+ # engine BEFORE we enqueue the research. The requested engine is
+ # the run primary (same overlay the worker applies), so ADAPTIVE
+ # scope follows this run's engine rather than the saved DB default.
+ # The factory PEP still enforces expanded engines at instantiation.
policy_error = _precheck_engine_policy(
settings_manager, params, search_engine, username
)
@@ -934,10 +1026,9 @@ def _start_research_sync(
_log_value_preview(strategy),
)
- if not query:
- return JSONResponse(
- {"status": "error", "message": "Query is required"}, status_code=400
- )
+ # NOTE: the missing-query 400 lives at the top of this function
+ # (before _extract_research_params) so it outranks parameter
+ # validation — see the comment there.
# Cap query length to defend against accidental prompt blowups that would
# bloat ResearchHistory storage and run up LLM context. The queue replay
@@ -1160,6 +1251,18 @@ def _start_research_sync(
# values override saved settings JUST FOR THIS RUN; they do
# not persist to the user's settings DB).
_apply_policy_overrides(all_settings, params)
+ overlay_runtime_settings(
+ all_settings,
+ search_engine=search_engine,
+ model_provider=model_provider,
+ model=model,
+ custom_endpoint=custom_endpoint,
+ iterations=iterations,
+ questions_per_iteration=questions_per_iteration,
+ strategy=strategy,
+ max_results=max_results,
+ time_period=time_period,
+ )
# Add settings snapshot to metadata
research_settings["settings_snapshot"] = all_settings
diff --git a/src/local_deep_research/web/routes/research_validation.py b/src/local_deep_research/web/routes/research_validation.py
index 2590f44f99..6cb0cd7a37 100644
--- a/src/local_deep_research/web/routes/research_validation.py
+++ b/src/local_deep_research/web/routes/research_validation.py
@@ -13,6 +13,11 @@ MAX_RESULTS_MAX: Final = 50
MAX_QUERY_LENGTH: Final = 10_000
ALLOWED_TIME_PERIODS: Final = frozenset({"d", "w", "m", "y", "all"})
+ITERATIONS_MIN: Final = 1
+ITERATIONS_MAX: Final = 100
+QUESTIONS_PER_ITERATION_MIN: Final = 1
+QUESTIONS_PER_ITERATION_MAX: Final = 20
+
JsonScalar: TypeAlias = str | int | float | bool | None
JsonValue: TypeAlias = JsonScalar | list["JsonValue"] | dict[str, "JsonValue"]
@@ -51,4 +56,23 @@ def validate_search_overrides(data: Mapping[str, JsonValue]) -> str | None:
):
return "time_period must be one of: d, w, m, y, all"
+ iterations = data.get("iterations")
+ if iterations is not None and (
+ type(iterations) is not int
+ or not ITERATIONS_MIN <= iterations <= ITERATIONS_MAX
+ ):
+ return f"iterations must be an integer between {ITERATIONS_MIN} and {ITERATIONS_MAX}"
+
+ questions = data.get("questions_per_iteration")
+ if questions is not None and (
+ type(questions) is not int
+ or not QUESTIONS_PER_ITERATION_MIN
+ <= questions
+ <= QUESTIONS_PER_ITERATION_MAX
+ ):
+ return (
+ f"questions_per_iteration must be an integer between "
+ f"{QUESTIONS_PER_ITERATION_MIN} and {QUESTIONS_PER_ITERATION_MAX}"
+ )
+
return None
diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.py
index e9b9f1d99e..21b8e4b53b 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -35,6 +35,7 @@ from ...search_system import AdvancedSearchSystem
from ...text_optimization import CitationFormatter, CitationMode
from ...utilities.log_utils import log_for_research
from ...utilities.search_utilities import extract_links_from_search_results
+from ...utilities.type_utils import overlay_runtime_settings
from ..models.database import calculate_duration
from ...settings.env_registry import get_env_setting
from .socketio_asgi import (
@@ -1062,10 +1063,18 @@ def run_research_process(research_id, query, mode, **kwargs):
settings_snapshot = apply_environment_overrides_to_snapshot(
settings_snapshot
)
- if max_results is not None:
- settings_snapshot["search.max_results"] = max_results
- if time_period is not None:
- settings_snapshot["search.time_period"] = time_period
+ overlay_runtime_settings(
+ settings_snapshot,
+ search_engine=search_engine,
+ model_provider=model_provider,
+ model=model,
+ custom_endpoint=custom_endpoint,
+ iterations=iterations,
+ questions_per_iteration=questions_per_iteration,
+ strategy=strategy,
+ max_results=max_results,
+ time_period=time_period,
+ )
# Create a settings context that uses snapshot - no database access in threads
settings_context = SnapshotSettingsContext(
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 dbcf625431..0bacaf9d61 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
@@ -8,7 +8,11 @@ from ..security.secure_logging import logger
from .engine_groups import is_collection_engine
from .retriever_registry import retriever_registry
from ..utilities.search_utilities import LANGUAGE_CODE_MAP
-from ..utilities.type_utils import resolve_snippets_only, to_bool
+from ..utilities.type_utils import (
+ _is_strict_scope,
+ resolve_snippets_only,
+ to_bool,
+)
from .search_engine_base import BaseSearchEngine
from .search_engines_config import search_config
@@ -194,10 +198,17 @@ def create_search_engine(
target=engine_name,
)
- primary = resolve_run_primary_engine(
- settings_snapshot, default=engine_name
- )
try:
+ # STRICT must never let the request choose its own primary: a
+ # blank/missing saved primary fails closed (ValueError ->
+ # PolicyDeniedError below) instead of falling back to the
+ # engine being instantiated.
+ if _is_strict_scope(settings_snapshot):
+ primary = resolve_run_primary_engine(settings_snapshot)
+ else:
+ primary = resolve_run_primary_engine(
+ settings_snapshot, default=engine_name
+ )
_ctx = context_from_snapshot(
settings_snapshot,
primary,
@@ -339,13 +350,18 @@ def create_search_engine(
)
# 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
- )
-
+ # enforces matches the one the LangGraph tool-list filter pre-filters with.
+ # Under STRICT a blank/missing saved primary fails closed instead of
+ # falling back to the engine being instantiated (which would make the
+ # STRICT check trivially true).
try:
+ if _is_strict_scope(settings_snapshot):
+ primary_engine = resolve_run_primary_engine(settings_snapshot)
+ else:
+ # (default: this engine when search.tool is unset).
+ primary_engine = resolve_run_primary_engine(
+ settings_snapshot, default=engine_name
+ )
ctx = context_from_snapshot(
settings_snapshot, primary_engine, username=username
)
diff --git a/tests/api/test_research_api.py b/tests/api/test_research_api.py
index 375b21563b..127355c350 100644
--- a/tests/api/test_research_api.py
+++ b/tests/api/test_research_api.py
@@ -106,9 +106,9 @@ class TestInitSearchSystem:
mock_system = MagicMock()
mock_system_class.return_value = mock_system
- result = _init_search_system(iterations=5)
+ _init_search_system(iterations=5)
- assert result.max_iterations == 5
+ assert mock_system_class.call_args[1]["max_iterations"] == 5
@patch("local_deep_research.api.research_functions.get_llm")
@patch("local_deep_research.api.research_functions.AdvancedSearchSystem")
@@ -125,9 +125,9 @@ class TestInitSearchSystem:
mock_system = MagicMock()
mock_system_class.return_value = mock_system
- result = _init_search_system(questions_per_iteration=3)
+ _init_search_system(questions_per_iteration=3)
- assert result.questions_per_iteration == 3
+ assert mock_system_class.call_args[1]["questions_per_iteration"] == 3
@patch("local_deep_research.api.research_functions.get_llm")
@patch("local_deep_research.api.research_functions.AdvancedSearchSystem")
diff --git a/tests/api/test_research_functions.py b/tests/api/test_research_functions.py
index 1054d7f6e2..e1cfb8e96a 100644
--- a/tests/api/test_research_functions.py
+++ b/tests/api/test_research_functions.py
@@ -82,28 +82,20 @@ class TestInitSearchSystem:
assert mock_search.call_args[0][0] == "wikipedia"
def test_sets_iterations(self, mock_get_llm, mock_get_search):
- """Test that max_iterations is set on system."""
+ """Test that max_iterations is passed to AdvancedSearchSystem."""
with patch(
"local_deep_research.api.research_functions.AdvancedSearchSystem"
) as mock_class:
- mock_system = MagicMock()
- mock_class.return_value = mock_system
-
_init_search_system(iterations=5)
-
- assert mock_system.max_iterations == 5
+ assert mock_class.call_args[1]["max_iterations"] == 5
def test_sets_questions_per_iteration(self, mock_get_llm, mock_get_search):
- """Test that questions_per_iteration is set on system."""
+ """Test that questions_per_iteration is passed to AdvancedSearchSystem."""
with patch(
"local_deep_research.api.research_functions.AdvancedSearchSystem"
) as mock_class:
- mock_system = MagicMock()
- mock_class.return_value = mock_system
-
_init_search_system(questions_per_iteration=10)
-
- assert mock_system.questions_per_iteration == 10
+ assert mock_class.call_args[1]["questions_per_iteration"] == 10
def test_sets_progress_callback(self, mock_get_llm, mock_get_search):
"""Test that progress callback is set."""
@@ -161,6 +153,44 @@ class TestInitSearchSystem:
call_kwargs = mock_class.call_args[1]
assert call_kwargs["settings_snapshot"] == sample_settings_snapshot
+ def test_absent_snapshot_keys_default_to_none_and_source_based(
+ self, mock_get_llm, mock_get_search
+ ):
+ """When settings_snapshot is empty or missing search.tool/search.search_strategy,
+ _init_search_system gracefully defaults without raising KeyError.
+ """
+ with patch(
+ "local_deep_research.api.research_functions.AdvancedSearchSystem"
+ ) as mock_class:
+ _init_search_system(settings_snapshot={})
+ call_kwargs = mock_class.call_args[1]
+ assert call_kwargs["strategy_name"] == "source-based"
+ assert call_kwargs["search"] is None
+
+ def test_strict_scope_does_not_overwrite_search_tool(
+ self, mock_get_llm, mock_get_search
+ ):
+ """Programmatic _init_search_system must keep the saved primary
+ when policy.egress_scope == strict. Otherwise a STRICT user calling
+ ``quick_summary(search_tool='searxng')`` with a saved
+ ``search.tool='library'`` would silently widen the run.
+ """
+ snapshot = {
+ "policy.egress_scope": {
+ "value": "strict",
+ "ui_element": "select",
+ },
+ "search.tool": {"value": "library", "ui_element": "select"},
+ }
+ with patch(
+ "local_deep_research.api.research_functions.AdvancedSearchSystem"
+ ) as mock_class:
+ _init_search_system(
+ search_tool="searxng", settings_snapshot=snapshot
+ )
+ forwarded_snapshot = mock_class.call_args[1]["settings_snapshot"]
+ assert forwarded_snapshot["search.tool"]["value"] == "library"
+
class TestQuickSummary:
"""Tests for quick_summary function."""
diff --git a/tests/connected/test_research_submission_policy.py b/tests/connected/test_research_submission_policy.py
index 3ea1edac18..671b752bfc 100644
--- a/tests/connected/test_research_submission_policy.py
+++ b/tests/connected/test_research_submission_policy.py
@@ -16,6 +16,7 @@ from local_deep_research.database.models import (
UserActiveResearch,
)
from local_deep_research.settings import SettingsManager
+from local_deep_research.utilities.type_utils import unwrap_setting
from tests.connected.conftest import csrf_headers, register_connected_user
@@ -246,3 +247,79 @@ def test_denied_submission_creates_no_research_state(
)
== 0
)
+
+
+def test_submission_persists_runtime_parameter_overrides_in_snapshot(
+ registered_connected_user: ConnectedUserFixture,
+):
+ case = registered_connected_user
+ database_session = db_manager.get_session(case.username)
+ assert database_session is not None
+ with database_session:
+ settings_manager = SettingsManager(database_session)
+ assert settings_manager.set_setting("search.tool", "arxiv")
+ assert settings_manager.set_setting("llm.provider", "ollama")
+ assert settings_manager.set_setting(
+ "llm.model", "connected-policy-model"
+ )
+ assert settings_manager.set_setting("search.iterations", 2)
+ assert settings_manager.set_setting("search.questions_per_iteration", 3)
+ assert settings_manager.set_setting(
+ "search.search_strategy", "source-based"
+ )
+
+ with patch(
+ "local_deep_research.web.routers.research.start_research_process",
+ return_value=Thread(),
+ ):
+ submission_response = case.client.post(
+ "/api/start_research",
+ json={
+ "query": "How do runtime overrides persist in settings snapshot?",
+ "mode": "quick",
+ "model_provider": "ollama",
+ "model": "connected-policy-model",
+ "search_engine": "wikipedia",
+ "iterations": 5,
+ "questions_per_iteration": 4,
+ "strategy": "news",
+ },
+ headers=csrf_headers(case.client),
+ )
+
+ assert submission_response.status_code == 200, submission_response.text[
+ :500
+ ]
+ submission = submission_response.json()
+ assert submission["status"] == "success"
+ research_id = submission["research_id"]
+
+ persisted_session = db_manager.get_session(case.username)
+ assert persisted_session is not None
+ with persisted_session:
+ research_metadata = persisted_session.scalar(
+ select(ResearchHistory.research_meta).where(
+ ResearchHistory.id == research_id
+ )
+ )
+ assert isinstance(research_metadata, dict)
+ snapshot = research_metadata["settings_snapshot"]
+ assert isinstance(snapshot, dict)
+ assert unwrap_setting(snapshot["search.tool"]) == "wikipedia"
+ assert unwrap_setting(snapshot["search.iterations"]) == 5
+ assert unwrap_setting(snapshot["search.questions_per_iteration"]) == 4
+ assert unwrap_setting(snapshot["search.search_strategy"]) == "news"
+ assert snapshot["search.tool"].get("ui_element") == "select"
+
+ # User's persistent settings in the database must remain unchanged
+ settings_session = db_manager.get_session(case.username)
+ assert settings_session is not None
+ with settings_session:
+ saved_settings = SettingsManager(settings_session)
+ assert saved_settings.get_setting("search.tool") == "arxiv"
+ assert saved_settings.get_setting("search.iterations") == 2
+ assert saved_settings.get_setting("search.questions_per_iteration") == 3
+ assert (
+ saved_settings.get_setting("search.search_strategy")
+ == "source-based"
+ )
diff --git a/tests/report/test_followup_report_delegate_override.py b/tests/report/test_followup_report_delegate_override.py
new file mode 100644
index 0000000000..1ad39c6aff
--- /dev/null
+++ b/tests/report/test_followup_report_delegate_override.py
@@ -0,0 +1,222 @@
+"""Regression tests for the composed follow-up + report generation path.
+
+Reproduces the failure mode reported on PR #6517: ``EnhancedContextualFollowUpStrategy``
+wraps a delegate (``SourceBasedSearchStrategy``) and the report generator's
+per-subsection ``max_iterations`` override was only being applied to the
+wrapper, so the delegate still ran its full configured iteration loop for
+each subsection. The composed test below uses the real wrapper, the real
+delegate, and the real report section generator to pin the override end-to-end.
+"""
+
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from local_deep_research.advanced_search_system.strategies.followup.enhanced_contextual_followup import (
+ EnhancedContextualFollowUpStrategy,
+)
+from local_deep_research.advanced_search_system.strategies.source_based_strategy import (
+ SourceBasedSearchStrategy,
+)
+from local_deep_research.report_generator import IntegratedReportGenerator
+from local_deep_research.search_system import AdvancedSearchSystem
+from local_deep_research.utilities.type_utils import unwrap_setting
+
+
+def _build_followup_system(max_iterations=4):
+ """Build a real AdvancedSearchSystem wrapping a real
+ EnhancedContextualFollowUpStrategy around a real
+ SourceBasedSearchStrategy delegate.
+
+ LLM and search engine are mocked to keep the test offline.
+ """
+ mock_model = MagicMock()
+ mock_search = MagicMock()
+ mock_search.run.return_value = []
+ mock_search.include_full_content = True
+
+ snapshot = {
+ "search.iterations": {"value": max_iterations},
+ "search.questions_per_iteration": {"value": 2},
+ }
+ system = AdvancedSearchSystem(
+ llm=mock_model,
+ search=mock_search,
+ strategy_name="enhanced-contextual-followup",
+ settings_snapshot=snapshot,
+ max_iterations=max_iterations,
+ questions_per_iteration=2,
+ research_context={"delegate_strategy": "source-based"},
+ )
+ return system, mock_search
+
+
+class TestFollowupReportComposedPath:
+ def test_delegate_max_iterations_overridden_during_subsection(self):
+ """During a report subsection search, the wrapped delegate must run
+ with ``max_iterations=1`` even though both the wrapper and the
+ delegate were constructed with ``max_iterations=4``.
+
+ This is the exact composition the reviewer reproduced: a real
+ AdvancedSearchSystem with enhanced-contextual-followup feeding the
+ real IntegratedReportGenerator, with only LLM/search responses mocked.
+ """
+ system, _ = _build_followup_system(max_iterations=4)
+ assert isinstance(system.strategy, EnhancedContextualFollowUpStrategy)
+ delegate = system.strategy.delegate_strategy
+ assert isinstance(delegate, SourceBasedSearchStrategy)
+ assert delegate.max_iterations == 4
+
+ # Wire the report generator around the real system. The LLM only
+ # needs to answer the section-research call; report assembly stays
+ # in the existing pipeline. Stub ``analyze_topic`` to capture the
+ # delegate's iteration count at the moment the call lands.
+ generator = IntegratedReportGenerator.__new__(IntegratedReportGenerator)
+ generator.search_system = system
+ generator.model = MagicMock()
+ generator.searches_per_section = 2
+ generator.max_context_sections = 3
+ generator.max_context_chars = 4000
+ generator._owns_llm = False
+
+ captured_max = {}
+
+ def fake_delegate_analyze(query):
+ # While the report subsection is being processed, the override
+ # must already have taken effect on the DELEGATE (where the
+ # actual search loop runs), not just on the wrapper.
+ captured_max["delegate"] = delegate.max_iterations
+ captured_max["wrapper"] = system.strategy.max_iterations
+ captured_max["snapshot_iter"] = (
+ system.strategy.settings_snapshot.get("search.iterations")
+ )
+ return {
+ "current_knowledge": "ok",
+ "questions_by_iteration": {},
+ }
+
+ with patch.object(
+ delegate, "analyze_topic", side_effect=fake_delegate_analyze
+ ):
+ structure = [
+ {
+ "name": "S",
+ "subsections": [{"name": "Sub", "purpose": "p"}],
+ }
+ ]
+ generator._research_and_generate_sections(
+ {"current_knowledge": "init"}, structure, "q"
+ )
+
+ assert captured_max["delegate"] == 1, (
+ "delegate.max_iterations must be overridden to 1 during the "
+ "subsection search; otherwise the per-subsection cap never "
+ "reaches the worker and each subsection runs the full configured "
+ "loop"
+ )
+ assert captured_max["wrapper"] == 1
+ assert captured_max["snapshot_iter"] == 1
+
+ def test_delegate_max_iterations_restored_after_subsection(self):
+ """After the report subsection loop, the delegate must have its
+ original ``max_iterations`` restored, so subsequent calls outside
+ the report context see the configured value again.
+
+ Also captures the during-call state to prove the override was
+ actually applied — otherwise this assertion would vacuously pass
+ with a no-op fix that never overrides the delegate.
+ """
+ system, _ = _build_followup_system(max_iterations=4)
+ delegate = system.strategy.delegate_strategy
+
+ generator = IntegratedReportGenerator.__new__(IntegratedReportGenerator)
+ generator.search_system = system
+ generator.model = MagicMock()
+ generator.searches_per_section = 2
+ generator.max_context_sections = 3
+ generator.max_context_chars = 4000
+ generator._owns_llm = False
+
+ captured = {}
+
+ def fake_delegate_analyze(query):
+ captured["during"] = delegate.max_iterations
+ return {
+ "current_knowledge": "ok",
+ "questions_by_iteration": {},
+ }
+
+ with patch.object(
+ delegate, "analyze_topic", side_effect=fake_delegate_analyze
+ ):
+ structure = [
+ {
+ "name": "S",
+ "subsections": [{"name": "Sub", "purpose": "p"}],
+ }
+ ]
+ generator._research_and_generate_sections(
+ {"current_knowledge": "init"}, structure, "q"
+ )
+
+ # The override must actually have applied during the call.
+ assert captured["during"] == 1
+ # …and must be back to the configured value after.
+ assert delegate.max_iterations == 4
+ assert (
+ unwrap_setting(
+ system.strategy.settings_snapshot["search.iterations"]
+ )
+ == 4
+ )
+
+ def test_delegate_max_iterations_restored_on_exception(self):
+ """If the delegate raises mid-subsection, the delegate
+ ``max_iterations`` and the snapshot must still be restored.
+
+ Also captures the during-call state to prove the override was
+ applied before the exception was raised.
+ """
+ system, _ = _build_followup_system(max_iterations=4)
+ delegate = system.strategy.delegate_strategy
+
+ generator = IntegratedReportGenerator.__new__(IntegratedReportGenerator)
+ generator.search_system = system
+ generator.model = MagicMock()
+ generator.searches_per_section = 2
+ generator.max_context_sections = 3
+ generator.max_context_chars = 4000
+ generator._owns_llm = False
+
+ captured = {}
+
+ def fake_delegate_analyze(query):
+ captured["during"] = delegate.max_iterations
+ raise RuntimeError("boom")
+
+ with patch.object(
+ delegate, "analyze_topic", side_effect=fake_delegate_analyze
+ ):
+ structure = [
+ {
+ "name": "S",
+ "subsections": [{"name": "Sub", "purpose": "p"}],
+ }
+ ]
+ with pytest.raises(RuntimeError, match="boom"):
+ generator._research_and_generate_sections(
+ {"current_knowledge": "init"},
+ structure,
+ "q",
+ )
+
+ # The override must actually have applied before the raise.
+ assert captured["during"] == 1
+ # …and must still be restored to the configured value after.
+ assert delegate.max_iterations == 4
+ assert (
+ unwrap_setting(
+ system.strategy.settings_snapshot["search.iterations"]
+ )
+ == 4
+ )
diff --git a/tests/security/test_api_v1_boundary_fastapi.py b/tests/security/test_api_v1_boundary_fastapi.py
index b2a5d4c161..0bea90873b 100644
--- a/tests/security/test_api_v1_boundary_fastapi.py
+++ b/tests/security/test_api_v1_boundary_fastapi.py
@@ -872,15 +872,8 @@ class TestUnsafeForwardParamsRejection:
``TestForwardedParamTypeValidation``).
``iterations``/``questions_per_iteration`` are real kwargs
- forwarded through quick_summary's/generate_report's ``**kwargs``
- (never gated behind the settings_snapshot branch), so asserting
- against the mocked call here genuinely proves they REACH the
- research function's call site — but that is as far as it goes:
- both are pure no-ops one level below this mock (see
- ``TestForwardedParamTypeValidation``'s docstring for the traced
- reason), so this test intentionally does not claim they have any
- further observable effect, only that the boundary doesn't
- collaterally strip or reject them.
+ forwarded through quick_summary's/generate_report's ``**kwargs``.
+ This test only proves the boundary doesn't strip or reject them.
"""
client, _username = _api_user(live_app)
@@ -925,23 +918,12 @@ class TestForwardedParamTypeValidation:
wrong type at the boundary instead, with a 400 naming the offending
key(s).
- ``iterations`` is NOT covered here (found in post-merge review of PR
- #5533, then corrected in a further post-merge review pass): its only
- consumer on the REST path is ``system.max_iterations = iterations`` in
- ``research_functions.py`` - a bare attribute assignment with no
- operation performed on the value, so no JSON type ever crashes there.
- An earlier version of this module claimed ``iterations`` reaches
- ``range(1, self.max_iterations + 1)`` in
- ``focused_iteration_strategy.py`` and crashes mid-research on a bad
- type; that traced to the wrong constructor call
- (``AdvancedSearchSystem`` is built WITHOUT ``max_iterations`` in
- ``_init_search_system``, so that strategy resolves its iteration count
- from the settings snapshot instead, never from this kwarg) and is
- false - ``iterations`` is a pure no-op on the REST path regardless of
- type. See ``TestUnsafeForwardParamsRejection.
- test_clean_request_with_documented_params_still_succeeds`` for proof it
- is still accepted and forwarded unchanged (that no-op behavior is
- itself unaffected by this fix).
+ ``iterations`` is NOT covered here: when omitted it is not forwarded
+ (snapshot ``search.iterations`` is used). When present it is passed
+ into ``AdvancedSearchSystem``. See
+ ``TestUnsafeForwardParamsRejection.
+ test_clean_request_with_documented_params_still_succeeds`` for proof
+ an explicit value is still accepted and forwarded.
"""
@pytest.mark.parametrize(
@@ -958,12 +940,36 @@ class TestForwardedParamTypeValidation:
("search_strategy", 5),
("search_tool", ["searxng"]),
("search_tool", {"tool": "searxng"}),
+ ("iterations", 0),
+ ("iterations", -1),
+ ("iterations", 101),
+ ("iterations", "3"),
+ ("iterations", 1.5),
+ ("iterations", True),
+ ("questions_per_iteration", 0),
+ ("questions_per_iteration", -1),
+ ("questions_per_iteration", 21),
+ ("questions_per_iteration", "3"),
+ ("questions_per_iteration", 1.5),
+ ("questions_per_iteration", False),
],
ids=[
"model_name-int",
"search_strategy-int",
"search_tool-list",
"search_tool-dict",
+ "iterations-0",
+ "iterations-neg",
+ "iterations-101",
+ "iterations-str",
+ "iterations-float",
+ "iterations-bool",
+ "questions_per_iteration-0",
+ "questions_per_iteration-neg",
+ "questions_per_iteration-21",
+ "questions_per_iteration-str",
+ "questions_per_iteration-float",
+ "questions_per_iteration-bool",
],
)
def test_wrong_type_is_rejected_with_400(
@@ -1012,6 +1018,7 @@ class TestForwardedParamTypeValidation:
"search_strategy": "source_based",
"search_tool": "wikipedia",
"iterations": 3,
+ "questions_per_iteration": 2,
},
)
@@ -1020,6 +1027,7 @@ class TestForwardedParamTypeValidation:
assert research_fn.call_args.kwargs["search_strategy"] == "source_based"
assert research_fn.call_args.kwargs["search_tool"] == "wikipedia"
assert research_fn.call_args.kwargs["iterations"] == 3
+ assert research_fn.call_args.kwargs["questions_per_iteration"] == 2
@pytest.mark.parametrize(
"label,path,target",
@@ -1030,7 +1038,7 @@ class TestForwardedParamTypeValidation:
)
@pytest.mark.parametrize(
"key",
- ["model_name", "search_tool"],
+ ["model_name", "search_tool", "iterations", "questions_per_iteration"],
)
def test_null_is_let_through_for_none_as_sentinel_params(
self, live_app, label, path, target, key
@@ -1470,3 +1478,97 @@ class TestErrorScrubWiring:
assert _PLANTED_CREDENTIAL not in resp.text, (
f"{label}: the exception text reached the client"
)
+
+
+class TestStrictEgressScopeRespectedOnRestPath:
+ """The /api/v1 quick_summary/generate_report endpoints feed runtime
+ overrides through ``overlay_runtime_settings`` on the way to
+ ``_init_search_system``. Under STRICT egress scope, that overlay
+ MUST NOT overwrite the saved primary ``search.tool`` — otherwise a
+ STRICT user with a saved ``library`` primary could widen the run to
+ ``searxng`` purely by sending a JSON body.
+ """
+
+ @pytest.mark.parametrize(
+ "label,path,target",
+ [
+ ("quick_summary", QUICK_SUMMARY_PATH, QUICK_SUMMARY_TARGET),
+ ("generate_report", GENERATE_REPORT_PATH, GENERATE_REPORT_TARGET),
+ ],
+ )
+ def test_search_tool_override_does_not_widen_run_under_strict(
+ self, live_app, label, path, target
+ ):
+ client, username = _api_user(live_app)
+ _store_setting(username, "policy.egress_scope", "strict")
+ _store_setting(username, "search.tool", "library")
+
+ with patch(target) as research_fn:
+ research_fn.return_value = {"summary": "fine", "findings": []}
+ resp = _post(
+ client,
+ path,
+ {"query": QUERY, "search_tool": "searxng"},
+ )
+
+ assert resp.status_code == 200, f"{label}: {resp.text[:400]}"
+ forwarded_snapshot = research_fn.call_args.kwargs["settings_snapshot"]
+ # REST snapshot is flat (SettingsManager.get_settings_snapshot
+ # strips the ``{"value": ...}`` envelope) — the saved primary
+ # is just the string under ``search.tool``.
+ assert forwarded_snapshot["search.tool"] == "library", (
+ f"{label}: STRICT user must keep saved primary; got "
+ f"{forwarded_snapshot['search.tool']!r}"
+ )
+
+ @pytest.mark.parametrize(
+ "label,path,target",
+ [
+ ("quick_summary", QUICK_SUMMARY_PATH, QUICK_SUMMARY_TARGET),
+ ("generate_report", GENERATE_REPORT_PATH, GENERATE_REPORT_TARGET),
+ (
+ "analyze_documents",
+ ANALYZE_DOCUMENTS_PATH,
+ ANALYZE_DOCUMENTS_TARGET,
+ ),
+ ],
+ )
+ def test_strict_blank_saved_primary_fails_closed_as_400_not_500(
+ self, live_app, label, path, target
+ ):
+ """STRICT + blank saved primary + explicit engine on REST must be
+ a curated 400, not the generic 500.
+
+ The route-level ``except Exception`` used to swallow the
+ ``PolicyDeniedError`` from ``_init_search_system``/factory before
+ the global handler could render its 400. Pins the
+ ``except PolicyDeniedError`` arm in ``api_v1.py``.
+ """
+ from local_deep_research.security.egress.policy import (
+ Decision,
+ PolicyDeniedError,
+ )
+
+ client, _username = _api_user(live_app)
+ body = {"query": QUERY, "search_tool": "searxng"}
+ if label == "analyze_documents":
+ # search_tool is not an analyze_documents param (unknown-param
+ # 400); the STRICT blank-primary denial there comes from
+ # get_llm/get_search, so pin the except arm with a valid body.
+ body = {"query": QUERY, "collection_name": COLLECTION}
+ with patch(target) as research_fn:
+ research_fn.side_effect = PolicyDeniedError(
+ Decision(False, "invalid_policy_config"),
+ target="searxng",
+ )
+ resp = _post(
+ client,
+ path,
+ body,
+ )
+ assert resp.status_code == 400, (
+ f"{label}: expected curated 400, got {resp.status_code} / "
+ f"{resp.text[:400]}"
+ )
+ assert "Egress policy refused this request" in resp.json()["error"]
+ assert "invalid_policy_config" in resp.json()["error"]
diff --git a/tests/security/test_egress_policy.py b/tests/security/test_egress_policy.py
index a4b88c57f3..ba3c155654 100644
--- a/tests/security/test_egress_policy.py
+++ b/tests/security/test_egress_policy.py
@@ -995,6 +995,126 @@ def test_factory_raises_policy_denied_under_strict_non_primary():
assert exc_info.value.decision.reason == "strict_not_primary"
+ "snapshot",
+ [
+ {"policy.egress_scope": "strict", "search.tool": ""},
+ {"policy.egress_scope": "strict", "search.tool": " "},
+ {"policy.egress_scope": "strict", "search.tool": {"value": ""}},
+ {"policy.egress_scope": "strict"},
+ ],
+ ids=["flat-blank", "flat-whitespace", "envelope-blank", "missing"],
+)
+def test_factory_strict_blank_saved_primary_fails_closed(snapshot):
+ """STRICT + blank/missing saved primary + explicit requested engine must
+ fail closed, not let the request become its own primary (which would make
+ the STRICT check trivially true)."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ # Use wikipedia (not arxiv): arxiv's constructor builds an LLM whose
+ # own PEP also denies with invalid_policy_config, so an arxiv test
+ # stays green even with the factory PEP reverted. Wikipedia builds
+ # no LLM, so only the factory PEP can deny — a real pin for it.
+ # Enable it in the snapshot so the factory reaches the PEP (otherwise
+ # it fails earlier with "unknown engine").
+ snapshot = {
+ **dict(snapshot),
+ "search.engine.web.wikipedia.use_in_auto_search": True,
+ }
+ with pytest.raises(PolicyDeniedError) as exc_info:
+ create_search_engine(
+ "wikipedia", llm=None, settings_snapshot=dict(snapshot)
+ )
+ assert exc_info.value.decision.reason == "invalid_policy_config"
+
+
+def test_retriever_strict_blank_saved_primary_fails_closed():
+ """Retriever branch: STRICT + blank saved primary must fail closed at
+ the factory PEP, not let the retriever instantiate."""
+ from unittest.mock import MagicMock
+
+ from local_deep_research.web_search_engines.retriever_registry import (
+ retriever_registry,
+ )
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ name = "_strict_blank_retriever_pin"
+ retriever_registry.register(name, MagicMock(), is_local=True)
+ try:
+ snapshot = {
+ "policy.egress_scope": "strict",
+ "search.tool": "",
+ }
+ with pytest.raises(PolicyDeniedError) as exc_info:
+ create_search_engine(
+ name, llm=None, settings_snapshot=dict(snapshot)
+ )
+ assert exc_info.value.decision.reason == "invalid_policy_config"
+ finally:
+ retriever_registry.unregister(name)
+
+
+def test_build_run_egress_context_strict_blank_saved_primary_fails_closed():
+ """Worker seam: STRICT + blank saved primary + explicit requested engine
+ must raise (fail closed), matching the precheck. Non-STRICT scopes keep
+ the requested-engine fallback; STRICT + valid saved keeps the saved."""
+ from local_deep_research.security.egress.policy import (
+ build_run_egress_context,
+ )
+
+ # STRICT blank + requested -> ValueError (worker converts to a failed run).
+ with pytest.raises(ValueError, match="no primary search engine"):
+ build_run_egress_context(
+ {"policy.egress_scope": "strict", "search.tool": ""},
+ "arxiv",
+ username="user",
+ )
+ # STRICT envelope blank + requested -> same.
+ with pytest.raises(ValueError, match="no primary search engine"):
+ build_run_egress_context(
+ {
+ "policy.egress_scope": {"value": "strict"},
+ "search.tool": {"value": " "},
+ },
+ "arxiv",
+ username="user",
+ )
+ # STRICT valid saved + different requested -> saved stays the primary.
+ ctx = build_run_egress_context(
+ {"policy.egress_scope": "strict", "search.tool": "library"},
+ "arxiv",
+ username="user",
+ )
+ assert ctx.primary_engine == "library"
+ # ADAPTIVE blank + requested -> requested wins (existing contract).
+ ctx = build_run_egress_context(
+ {"policy.egress_scope": "adaptive", "search.tool": ""},
+ "arxiv",
+ username="user",
+ )
+ assert ctx.primary_engine == "arxiv"
+ # Non-STRICT valid saved + no requested -> saved stays the primary
+ # (previously raised; safe direction — no request influence — but
+ # pinned here so a future refactor can't silently revert it).
+ ctx = build_run_egress_context(
+ {"policy.egress_scope": "adaptive", "search.tool": "library"},
+ None,
+ username="user",
+ )
+ assert ctx.primary_engine == "library"
+ # Blank + blank still refuses on every scope.
+ with pytest.raises(ValueError, match="no primary search engine"):
+ build_run_egress_context(
+ {"policy.egress_scope": "adaptive", "search.tool": ""},
+ None,
+ username="user",
+ )
+
+
def test_get_llm_blocks_cloud_under_require_local():
"""End-to-end: get_llm() must raise PolicyDeniedError when the user
has require_local_endpoint=true and asks for a cloud provider.
diff --git a/tests/test_report_generator_coverage.py b/tests/test_report_generator_coverage.py
index 6db59fca77..d150b78b1d 100644
--- a/tests/test_report_generator_coverage.py
+++ b/tests/test_report_generator_coverage.py
@@ -543,6 +543,123 @@ class TestIterationOverrideRestore:
assert captured_value["max_iterations"] == 1
+class TestDelegateIterationOverride:
+ """Tests that the per-subsection ``max_iterations`` override reaches the
+ actual delegate (e.g. ``SourceBasedSearchStrategy`` wrapped by
+ ``EnhancedContextualFollowUpStrategy``) — the delegate caches its own
+ ``max_iterations`` at construction, so the wrapper-only override never
+ limits subsection work unless it propagates here.
+ """
+
+ def test_override_reaches_delegate_during_call(self, generator):
+ """During analyze_topic the delegate's max_iterations must be 1."""
+ wrapper = MagicMock()
+ wrapper.settings_snapshot = {"search.iterations": 4}
+ wrapper.max_iterations = 4
+ delegate = MagicMock()
+ delegate.max_iterations = 4
+ wrapper.delegate_strategy = delegate
+
+ captured = {}
+
+ def capture(query):
+ captured["wrapper_max"] = wrapper.max_iterations
+ captured["delegate_max"] = delegate.max_iterations
+ return {"current_knowledge": "content"}
+
+ generator.search_system.strategy = wrapper
+ generator.search_system.analyze_topic.side_effect = capture
+
+ structure = [
+ {"name": "S", "subsections": [{"name": "Sub", "purpose": "p"}]}
+ ]
+ generator._research_and_generate_sections(
+ {"current_knowledge": "init"}, structure, "q"
+ )
+
+ assert captured["wrapper_max"] == 1
+ assert captured["delegate_max"] == 1
+
+ def test_delegate_max_iterations_restored_after_call(self, generator):
+ """After the subsection loop, the delegate's max_iterations must be
+ restored to its original cached value."""
+ wrapper = MagicMock()
+ wrapper.settings_snapshot = {"search.iterations": 4}
+ wrapper.max_iterations = 4
+ delegate = MagicMock()
+ delegate.max_iterations = 4
+ wrapper.delegate_strategy = delegate
+
+ generator.search_system.strategy = wrapper
+ generator.search_system.analyze_topic.return_value = {
+ "current_knowledge": "content"
+ }
+
+ structure = [
+ {"name": "S", "subsections": [{"name": "Sub", "purpose": "p"}]}
+ ]
+ generator._research_and_generate_sections(
+ {"current_knowledge": "init"}, structure, "q"
+ )
+
+ assert wrapper.max_iterations == 4
+ assert delegate.max_iterations == 4
+ assert wrapper.settings_snapshot["search.iterations"] == 4
+
+ def test_delegate_max_iterations_restored_on_exception(self, generator):
+ """If analyze_topic raises, both wrapper and delegate
+ ``max_iterations`` must still be restored."""
+ wrapper = MagicMock()
+ wrapper.settings_snapshot = {"search.iterations": 4}
+ wrapper.max_iterations = 4
+ delegate = MagicMock()
+ delegate.max_iterations = 4
+ wrapper.delegate_strategy = delegate
+
+ generator.search_system.strategy = wrapper
+ generator.search_system.analyze_topic.side_effect = RuntimeError("boom")
+
+ structure = [
+ {"name": "S", "subsections": [{"name": "Sub", "purpose": "p"}]}
+ ]
+
+ with pytest.raises(RuntimeError, match="boom"):
+ generator._research_and_generate_sections(
+ {"current_knowledge": "init"}, structure, "q"
+ )
+
+ assert wrapper.max_iterations == 4
+ assert delegate.max_iterations == 4
+
+ def test_delegate_without_max_iterations_attribute_is_left_alone(
+ self, generator
+ ):
+ """If the delegate lacks ``max_iterations`` (unusual but possible),
+ the wrapper-only override still runs and is still restored."""
+ wrapper = MagicMock()
+ wrapper.settings_snapshot = {"search.iterations": 4}
+ wrapper.max_iterations = 4
+ # Plain object: no ``max_iterations`` attribute and no
+ # ``delegate_strategy`` delegation magic.
+ delegate = object()
+ wrapper.delegate_strategy = delegate
+
+ generator.search_system.strategy = wrapper
+ generator.search_system.analyze_topic.return_value = {
+ "current_knowledge": "content"
+ }
+
+ structure = [
+ {"name": "S", "subsections": [{"name": "Sub", "purpose": "p"}]}
+ ]
+ generator._research_and_generate_sections(
+ {"current_knowledge": "init"}, structure, "q"
+ )
+
+ assert wrapper.max_iterations == 4
+ assert wrapper.settings_snapshot["search.iterations"] == 4
+
+
# ---------------------------------------------------------------------------
# _research_and_generate_sections -- section with pipe in name
# ---------------------------------------------------------------------------
diff --git a/tests/utilities/test_type_utils.py b/tests/utilities/test_type_utils.py
index e276d50f16..ca7b0442ae 100644
--- a/tests/utilities/test_type_utils.py
+++ b/tests/utilities/test_type_utils.py
@@ -494,6 +494,109 @@ class TestToBoolEnvironmentVariableSimulation:
assert to_bool("'true'") is False
+class TestOverlaySnapshotValue:
+ def test_preserves_envelope_metadata(self):
+ from local_deep_research.utilities.type_utils import (
+ overlay_snapshot_value,
+ )
+
+ snapshot = {
+ "search.tool": {"value": "arxiv", "ui_element": "select"},
+ }
+ overlay_snapshot_value(snapshot, "search.tool", "wikipedia")
+ assert snapshot["search.tool"]["value"] == "wikipedia"
+ assert snapshot["search.tool"]["ui_element"] == "select"
+
+ def test_assigns_raw_when_unwrapped(self):
+ from local_deep_research.utilities.type_utils import (
+ overlay_snapshot_value,
+ )
+
+ snapshot = {"search.tool": "arxiv"}
+ overlay_snapshot_value(snapshot, "search.tool", "wikipedia")
+ assert snapshot["search.tool"] == "wikipedia"
+
+ def test_runtime_skips_none_and_maps_kwargs(self):
+ from local_deep_research.utilities.type_utils import (
+ overlay_runtime_settings,
+ )
+
+ snapshot = {
+ "search.tool": {"value": "arxiv", "ui_element": "select"},
+ "search.iterations": {"value": 2, "ui_element": "number"},
+ }
+ overlay_runtime_settings(
+ snapshot,
+ search_engine="wikipedia",
+ iterations=None,
+ questions_per_iteration=4,
+ )
+ assert snapshot["search.tool"]["value"] == "wikipedia"
+ assert snapshot["search.iterations"]["value"] == 2
+ assert snapshot["search.questions_per_iteration"] == 4
+
+ def test_runtime_skips_search_tool_under_strict_scope(self):
+ # Under STRICT, overwriting search.tool would silently widen the
+ # run to the requested engine (saved primary -> requested engine),
+ # bypassing the factory PEP gate. The helper MUST leave search.tool
+ # alone while still overlaying every other runtime kwarg.
+ from local_deep_research.utilities.type_utils import (
+ overlay_runtime_settings,
+ )
+
+ snapshot = {
+ "policy.egress_scope": {
+ "value": "strict",
+ "ui_element": "select",
+ },
+ "search.tool": {"value": "library", "ui_element": "select"},
+ "search.iterations": {"value": 2, "ui_element": "number"},
+ }
+ overlay_runtime_settings(
+ snapshot,
+ search_engine="searxng",
+ iterations=5,
+ )
+ assert snapshot["search.tool"]["value"] == "library"
+ assert snapshot["search.iterations"]["value"] == 5
+
+ def test_runtime_skips_search_tool_under_strict_env_override(
+ self, monkeypatch
+ ):
+ # The operator env override LDR_POLICY_EGRESS_SCOPE takes precedence
+ # over the saved scope — same precedence context_from_snapshot uses.
+ from local_deep_research.utilities.type_utils import (
+ overlay_runtime_settings,
+ )
+
+ monkeypatch.setenv("LDR_POLICY_EGRESS_SCOPE", "strict")
+ snapshot = {
+ "policy.egress_scope": {
+ "value": "adaptive",
+ "ui_element": "select",
+ },
+ "search.tool": {"value": "library", "ui_element": "select"},
+ }
+ overlay_runtime_settings(snapshot, search_engine="searxng")
+ assert snapshot["search.tool"]["value"] == "library"
+
+ def test_runtime_overlays_search_tool_under_non_strict_scope(self):
+ # Sanity: the skip is STRICT-only; ADAPTIVE / PUBLIC_ONLY /
+ # PRIVATE_ONLY must still overlay search.tool so per-run engine
+ # overrides keep working as documented.
+ from local_deep_research.utilities.type_utils import (
+ overlay_runtime_settings,
+ )
+
+ for scope in ("adaptive", "public_only", "private_only"):
+ snapshot = {
+ "policy.egress_scope": {"value": scope, "ui_element": "select"},
+ "search.tool": {"value": "library", "ui_element": "select"},
+ }
+ overlay_runtime_settings(snapshot, search_engine="searxng")
+ assert snapshot["search.tool"]["value"] == "searxng", scope
+
+
class TestResolveSnippetsOnly:
"""Tests for resolve_snippets_only in type_utils."""
diff --git a/tests/web/routers/test_api_v1_external_contract.py b/tests/web/routers/test_api_v1_external_contract.py
index 42bd02339f..c8802790b6 100644
--- a/tests/web/routers/test_api_v1_external_contract.py
+++ b/tests/web/routers/test_api_v1_external_contract.py
@@ -33,10 +33,10 @@ What this file pins, and why each piece was not already pinned:
(``grep -r page_content tests/web tests/security`` and
``grep -r content_truncated tests/`` both come back empty of api_v1).
-3. **The request contract.** The server-side defaults (``iterations``,
- ``searches_per_section``) and the deliberate ABSENCE of a
- ``search_tool`` default are part of what a caller gets when they omit
- a key. ``tests/security/test_api_v1_boundary_fastapi.py`` pins the
+3. **The request contract.** The server-side default
+ (``searches_per_section``) and the deliberate ABSENCE of
+ ``search_tool`` / ``iterations`` defaults are part of what a caller
+ gets when they omit a key. ``tests/security/test_api_v1_boundary_fastapi.py`` pins the
identity params (``username`` / ``settings_snapshot``); the defaults
were unpinned. ``temperature`` is NOT defaulted, and never reaches the
research function, on ``quick_summary``/``generate_report`` — it is a
@@ -516,14 +516,18 @@ class TestQuickSummaryResponseShape:
class TestServerSideRequestDefaults:
- def test_quick_summary_defaults_iterations(self, authenticated_client):
+ def test_quick_summary_does_not_default_iterations(
+ self, authenticated_client
+ ):
+ """Omitted ``iterations`` must not be filled with 1: that would
+ clobber the caller's stored ``search.iterations``."""
with patch(QS_TARGET, return_value={"summary": "s"}) as fn:
resp = authenticated_client.post(QUICK, json={"query": "q"})
assert resp.status_code == 200, resp.text[:300]
args, kwargs = fn.call_args
assert args == ("q",), "query is passed positionally"
- assert kwargs["iterations"] == 1
+ assert "iterations" not in kwargs
def test_quick_summary_does_not_default_search_tool(
self, authenticated_client
diff --git a/tests/web/routers/test_research_model_log_preview_bound.py b/tests/web/routers/test_research_model_log_preview_bound.py
index 1bc95244ef..3a94706af3 100644
--- a/tests/web/routers/test_research_model_log_preview_bound.py
+++ b/tests/web/routers/test_research_model_log_preview_bound.py
@@ -262,8 +262,8 @@ class TestBodyValueLogSites:
assert CountingValue.reprs < 100
def test_start_research_sync_does_not_repr_every_body_entry(self):
- """Catches (W1) and (W2) at every ``_start_research_sync`` value
- site at once, through the real call path.
+ """Catches (W1) and (W2) at the above-early-return value sites,
+ through the real call path.
The body carries a 50,000-entry dict for EVERY raw value the
function logs (``model``, logged three times along the path,
@@ -271,11 +271,17 @@ class TestBodyValueLogSites:
``Additional parameters`` values and the news-search
``triggered_by``; the two name fields as ``WideNameValue`` so the
name-shaped code before the log lines lets them through) and no
- ``query``, so the call runs every log line and then returns the
- 400 for the missing query. Measured: 100 element reprs with the
- bounded preview (10 per log of a wide value), 450,000 with the
- eager f-strings; one eager stringification of any single one of
- those values (e.g. ``_audit = repr(search_engine)``) adds 50,000.
+ ``query``. Since #6517 the missing-query 400 lives at the top of
+ ``_start_research_sync`` (before ``_extract_research_params``), so
+ this probe only exercises the two log sites above that return
+ (``Request data keys``, news ``triggered_by``) and then returns
+ the 400 for the missing query. The sites below the return need a
+ query to run and are pinned by
+ ``test_start_research_sync_does_not_repr_below_return_entries``.
+ Measured: ~10 element reprs with the bounded preview (10 per log
+ of a wide value that actually runs); one eager stringification at
+ a site above the return (e.g. ``_audit = repr(triggered_by)``)
+ adds 50,000.
"""
body = {
"model_provider": _wide_name(),
@@ -307,6 +313,59 @@ class TestBodyValueLogSites:
}
assert CountingValue.reprs < 200
+ def test_start_research_sync_does_not_repr_below_return_entries(self):
+ """Catches (W1) and (W2) at the below-early-return value sites,
+ through the real call path (#6517 follow-up).
+
+ The no-query probe above returns before ``_extract_research_params``,
+ so the ``Extracted model value``, ``Starting research with
+ provider``, and ``Additional parameters`` lines never run there (a
+ planted eager ``repr()`` below the return escapes it). This probe
+ posts a query plus wide unvalidated values (``strategy`` is the
+ unvalidated ``Additional parameters`` field; ``iterations`` /
+ ``questions_per_iteration`` stay valid ints so validation passes)
+ and forces the query-length gate to refuse right after the log
+ lines, so every below-return preview runs and nothing heavier does.
+ Measured: ~70 element reprs with the bounded preview (10 per log
+ of a wide value), 250,000+ with the eager f-strings; one eager
+ stringification of any single below-return value (e.g. ``_audit =
+ repr(strategy)``) adds 50,000.
+ """
+ body = {
+ "query": "probe query",
+ "model_provider": _wide_name(),
+ "model": _wide(),
+ "search_engine": _wide_name(),
+ "iterations": 5,
+ "questions_per_iteration": 5,
+ "strategy": _wide(),
+ }
+
+ @contextmanager
+ def _session_ctx(*args, **kwargs):
+ yield MagicMock()
+
+ CountingValue.reprs = 0
+ with (
+ patch.object(research_module, "get_user_db_session", _session_ctx),
+ patch(_SETTINGS_MANAGER, return_value=_settings_manager()),
+ patch.object(
+ research_module,
+ "validate_research_query_length",
+ return_value="Query too long",
+ ),
+ ):
+ response = research_module._start_research_sync(
+ body, "testuser", "http://testserver/", None
+ )
+
+ assert response.status_code == 400
+ assert json.loads(response.body) == {
+ "status": "error",
+ "message": "Query too long",
+ }
+ assert CountingValue.reprs < 200
+
def test_start_research_sync_does_not_repr_every_body_key(self):
"""Catches (W1) and (W2) at the ``Request data keys`` line, the
first line of ``_start_research_sync``, through the real call.
diff --git a/tests/web/routers/test_start_research_port_gaps.py b/tests/web/routers/test_start_research_port_gaps.py
index c6b4453280..f7353c4e38 100644
--- a/tests/web/routers/test_start_research_port_gaps.py
+++ b/tests/web/routers/test_start_research_port_gaps.py
@@ -22,9 +22,9 @@ What is recovered:
* the ``search_tool`` alias and ``search_engine``-wins precedence -- a live
API alias with no test at all;
-* the falsy-value asymmetry: ``iterations``/``questions_per_iteration``
- guard on ``is None`` (so ``0`` is preserved) while
- ``model_provider``/``model``/``strategy`` guard on truthiness (so ``""``
+* boundary validation on ``iterations`` (1..100) and
+ ``questions_per_iteration`` (1..20), rejecting non-ints, <= 0, or over cap,
+ while ``model_provider``/``model``/``strategy`` guard on truthiness (so ``""``
falls back). A refactor that flattens both to one style is invisible
today;
* the ``DEFAULT_OLLAMA_URL`` fallback, and ``ollama_url is None`` for a
@@ -162,22 +162,47 @@ def test_ollama_url_is_not_resolved_for_a_non_ollama_provider():
assert result["ollama_url"] is None
-def test_zero_iterations_is_preserved_not_replaced_by_the_default():
- """``iterations`` guards on ``is None``, deliberately: ``0`` is a
- value a caller can mean. A truthiness check here silently turns it
- into the saved default."""
+ "bad_val",
+ [0, -1, 101, 1000000000, 1.5, True, False, float("inf"), float("nan"), "5"],
+)
+def test_invalid_iterations_is_rejected(bad_val):
+ """iterations must be a finite int between 1 and 100."""
+ with pytest.raises(
+ ValueError, match="iterations must be an integer between 1 and 100"
+ ):
+ _extract({"iterations": bad_val}, _make_settings_manager())
+
+
[email protected]("good_val", [1, 5, 100])
+def test_valid_iterations_is_preserved(good_val):
result = _extract(
- {"iterations": 0}, _make_settings_manager({"search.iterations": 5})
+ {"iterations": good_val},
+ _make_settings_manager({"search.iterations": 5}),
)
- assert result["iterations"] == 0
+ assert result["iterations"] == good_val
+
+
+ "bad_val",
+ [0, -1, 21, 100, 1.5, True, False, float("inf"), float("nan"), "5"],
+)
+def test_invalid_questions_per_iteration_is_rejected(bad_val):
+ """questions_per_iteration must be a finite int between 1 and 20."""
+ with pytest.raises(
+ ValueError,
+ match="questions_per_iteration must be an integer between 1 and 20",
+ ):
+ _extract({"questions_per_iteration": bad_val}, _make_settings_manager())
-def test_zero_questions_per_iteration_is_preserved():
[email protected]("good_val", [1, 5, 20])
+def test_valid_questions_per_iteration_is_preserved(good_val):
result = _extract(
- {"questions_per_iteration": 0},
+ {"questions_per_iteration": good_val},
_make_settings_manager({"search.questions_per_iteration": 5}),
)
- assert result["questions_per_iteration"] == 0
+ assert result["questions_per_iteration"] == good_val
def test_empty_string_model_provider_falls_back_to_the_setting():
@@ -435,6 +460,34 @@ def _start_mocks(sm, session, spawn=None):
yield spawn_mock
+def test_start_research_rejects_invalid_iterations(client):
+ response = _post_start(
+ client,
+ {"query": "boundary test", "model": "llama3", "iterations": 0},
+ )
+ assert response.status_code == 400
+ assert (
+ "iterations must be an integer between 1 and 100"
+ in response.json()["message"]
+ )
+
+
+def test_start_research_rejects_invalid_questions_per_iteration(client):
+ response = _post_start(
+ client,
+ {
+ "query": "boundary test",
+ "model": "llama3",
+ "questions_per_iteration": 25,
+ },
+ )
+ assert response.status_code == 400
+ assert (
+ "questions_per_iteration must be an integer between 1 and 20"
+ in response.json()["message"]
+ )
+
+
def test_date_placeholder_in_the_query_is_replaced_with_today(client):
"""``YYYY-MM-DD`` is the documented placeholder for news
subscriptions and the news page's canned queries. The replacement
diff --git a/tests/web/routes/test_research_routes_policy.py b/tests/web/routes/test_research_routes_policy.py
index 917fdb9aa0..7bc8ee9e6f 100644
--- a/tests/web/routes/test_research_routes_policy.py
+++ b/tests/web/routes/test_research_routes_policy.py
@@ -225,6 +225,12 @@ class TestPrecheckEnginePolicy:
assert body["field"] is None
assert body["reason"] == "engine_unknown"
+ def test_adaptive_requested_engine_overrides_saved_primary(self):
+ # Saved primary is private; this run requests a public engine.
+ # ADAPTIVE must follow the requested engine, not the DB default.
+ mgr = _mgr({"policy.egress_scope": "adaptive"}, primary="library")
+ assert _precheck_engine_policy(mgr, {}, "arxiv", "user") is None
+
def test_scope_mismatch_message_omits_adaptive_when_target_isnt_primary(
self,
):
@@ -272,12 +278,15 @@ class TestPrecheckEnginePolicy:
mgr = _mgr(None)
assert _precheck_engine_policy(mgr, {}, "library", "user") is None
- def test_missing_primary_returns_400(self):
- # 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.
+ def test_missing_saved_primary_uses_requested_engine(self):
+ # Empty saved search.tool is filled by the requested engine overlay
+ # before resolve, matching the worker's kwargs primary.
mgr = _mgr({"policy.egress_scope": "public_only", "search.tool": ""})
- result = _precheck_engine_policy(mgr, {}, "arxiv", "user")
+ assert _precheck_engine_policy(mgr, {}, "arxiv", "user") is None
+
+ def test_missing_primary_and_requested_engine_returns_400(self):
+ mgr = _mgr({"policy.egress_scope": "public_only", "search.tool": ""})
+ result = _precheck_engine_policy(mgr, {}, "", "user")
assert result is not None
assert result.status_code == 400
body = json.loads(result.body)
@@ -285,8 +294,6 @@ class TestPrecheckEnginePolicy:
body["message"]
== "Egress policy refused this run due to an invalid policy configuration."
)
- # Raw resolver detail (e.g. "no primary search engine configured ...")
- # must not reach the client.
assert "search engine configured" not in body["message"]
def test_per_research_override_tightens_scope(self):
@@ -355,6 +362,99 @@ class TestPrecheckEnginePolicy:
)
assert result is None
+ def test_env_override_egress_scope_takes_precedence_at_precheck(
+ self, monkeypatch
+ ):
+ from local_deep_research.api.settings_utils import (
+ InMemorySettingsManager,
+ )
+
+ mgr = InMemorySettingsManager()
+ mgr.set_setting("policy.egress_scope", "adaptive")
+ mgr.set_setting("search.tool", "library")
+ monkeypatch.setenv("LDR_POLICY_EGRESS_SCOPE", "private_only")
+
+ # Requesting a public engine (searxng) under env-locked private_only is rejected
+ result = _precheck_engine_policy(mgr, {}, "searxng", "user")
+ assert result is not None
+ assert result.status_code == 400
+ body = json.loads(result.body)
+ assert body["reason"] == "scope_mismatch_private_only"
+
+ def test_precheck_overlays_max_results_and_time_period(self):
+ with patch(
+ "local_deep_research.web.routers.research.overlay_runtime_settings"
+ ) as mock_overlay:
+ mgr = _mgr({"policy.egress_scope": "adaptive"})
+ params = {
+ "max_results": 42,
+ "time_period": "w",
+ "model_provider": "openai",
+ "model": "gpt-4",
+ }
+ _precheck_engine_policy(mgr, params, "arxiv", "user")
+ mock_overlay.assert_called_once()
+ assert mock_overlay.call_args[1]["max_results"] == 42
+ assert mock_overlay.call_args[1]["time_period"] == "w"
+
+ def test_precheck_strict_scope_keeps_saved_primary(self):
+ # STRICT + a saved ``library`` primary + a request for ``searxng``
+ # must evaluate the saved primary. The precheck passes the
+ # saved primary into context_from_snapshot, so even though the
+ # overlay writes the requested engine onto search.tool, the
+ # context still classifies against the saved primary and the
+ # factory PEP refuses the run with strict_not_primary.
+ from local_deep_research.security.egress import policy as policy_mod
+
+ mgr = _mgr({"policy.egress_scope": "strict"}, primary="library")
+ with patch.object(policy_mod, "context_from_snapshot") as mock_ctx:
+ mock_ctx.return_value = MagicMock(
+ scope="strict", primary_engine="library"
+ )
+ with patch.object(policy_mod, "evaluate_engine") as mock_eval:
+ mock_eval.return_value = MagicMock(
+ allowed=False, reason="strict_not_primary"
+ )
+ result = _precheck_engine_policy(mgr, {}, "searxng", "user")
+
+ assert result is not None
+ assert result.status_code == 400
+ assert mock_ctx.call_args.args[1] == "library"
+
+ @pytest.mark.parametrize(
+ "snapshot",
+ [
+ {"policy.egress_scope": "strict", "search.tool": ""},
+ {"policy.egress_scope": "strict", "search.tool": " "},
+ {"policy.egress_scope": "strict", "search.tool": {"value": ""}},
+ {"policy.egress_scope": "strict", "search.tool": {"value": " "}},
+ {"policy.egress_scope": "strict"},
+ ],
+ ids=[
+ "flat-blank",
+ "flat-whitespace",
+ "envelope-blank",
+ "envelope-ws",
+ "missing",
+ ],
+ )
+ def test_precheck_strict_blank_saved_primary_fails_closed(self, snapshot):
+ # STRICT + a blank/missing saved primary + an explicit requested
+ # engine must fail closed (400 invalid config), not let the request
+ # choose its own primary. Non-STRICT scopes deliberately fall back
+ # to the requested engine (see
+ # test_missing_saved_primary_uses_requested_engine).
+ m = Mock()
+ m.get_settings_snapshot.return_value = dict(snapshot)
+ result = _precheck_engine_policy(m, {}, "arxiv", "user")
+ assert result is not None
+ assert result.status_code == 400
+ body = json.loads(result.body)
+ assert (
+ body["message"]
+ == "Egress policy refused this run due to an invalid policy configuration."
+ )
+
# ---------------------------------------------------------------------------
# _precheck_collection_agent_enabled (LangGraph-only usability flag)
diff --git a/tests/web/services/test_research_service_coverage_main_port.py b/tests/web/services/test_research_service_coverage_main_port.py
index b077eda3a4..e40528c1b7 100644
--- a/tests/web/services/test_research_service_coverage_main_port.py
+++ b/tests/web/services/test_research_service_coverage_main_port.py
@@ -957,7 +957,7 @@ class TestRunResearchProcessDetailedMode:
username="alice",
settings_snapshot={"search.tool": "searxng"},
model="m",
- search_engine="s",
+ search_engine="searxng",
)
assert research.status == "completed"
diff --git a/tests/web/services/test_research_service_runtime_overrides.py b/tests/web/services/test_research_service_runtime_overrides.py
new file mode 100644
index 0000000000..1c8aebc77b
--- /dev/null
+++ b/tests/web/services/test_research_service_runtime_overrides.py
@@ -0,0 +1,389 @@
+from contextlib import ExitStack
+from unittest.mock import MagicMock, patch
+import pytest
+
+from local_deep_research.advanced_search_system.strategies.source_based_strategy import (
+ SourceBasedSearchStrategy,
+)
+from local_deep_research.api.research_functions import _init_search_system
+from local_deep_research.search_system import AdvancedSearchSystem
+from local_deep_research.search_system_factory import create_strategy
+from tests.web.services.helpers import (
+ MODULE,
+ _base_run_patches,
+ _get_raw_run_research_process,
+)
+
+
[email protected](autouse=True)
+def _clear_egress_context():
+ from local_deep_research.security.egress.audit_hook import (
+ clear_active_context,
+ )
+
+ clear_active_context()
+ yield
+ clear_active_context()
+
+
+class TestResearchServiceRuntimeOverrides:
+ def test_run_research_process_overlays_runtime_overrides_onto_snapshot(
+ self,
+ ):
+ """Worker thread must overlay runtime kwargs onto settings_snapshot."""
+ captured_snapshot = {}
+ captured_factory_search_tool = None
+
+ raw_run = _get_raw_run_research_process()
+ patches = _base_run_patches()
+
+ initial_snapshot = {
+ "search.tool": {"value": "initial_engine", "ui_element": "select"},
+ "search.iterations": {"value": 1, "ui_element": "number"},
+ "search.questions_per_iteration": {
+ "value": 1,
+ "ui_element": "number",
+ },
+ "search.search_strategy": {
+ "value": "initial_strategy",
+ "ui_element": "select",
+ },
+ "llm.provider": {"value": "openai", "ui_element": "select"},
+ "llm.model": {"value": "gpt-3.5", "ui_element": "text"},
+ }
+
+ def mock_factory_get_search(search_tool, *args, **kwargs):
+ nonlocal captured_factory_search_tool
+ captured_factory_search_tool = search_tool
+ return MagicMock()
+
+ def mock_system_cls(*args, **kwargs):
+ nonlocal captured_snapshot
+ captured_snapshot = kwargs.get("settings_snapshot", {})
+ system = MagicMock()
+ system.analyze_topic.return_value = {
+ "findings": "test findings",
+ "formatted_findings": "formatted findings",
+ }
+ return system
+
+ patches[f"{MODULE}.apply_environment_overrides_to_snapshot"] = (
+ lambda s: dict(s)
+ )
+ patches[f"{MODULE}.get_llm"] = MagicMock(return_value=MagicMock())
+ patches[f"{MODULE}.AdvancedSearchSystem"] = mock_system_cls
+
+ with ExitStack() as stack:
+ stack.enter_context(
+ patch(
+ "local_deep_research.config.search_config.factory_get_search",
+ mock_factory_get_search,
+ )
+ )
+ stack.enter_context(
+ patch(
+ "local_deep_research.security.egress.policy.context_from_snapshot",
+ return_value=MagicMock(),
+ )
+ )
+ stack.enter_context(
+ patch(
+ "local_deep_research.security.egress.run_classification.audit_run_from_snapshot",
+ return_value=MagicMock(allowed=True),
+ )
+ )
+ for target, mock_obj in patches.items():
+ stack.enter_context(patch(target, mock_obj))
+
+ raw_run(
+ research_id="test_run_123",
+ query="test query",
+ mode="quick",
+ search_engine="searxng",
+ model_provider="ollama",
+ model="llama3",
+ custom_endpoint="http://localhost:11434/v1",
+ iterations=5,
+ questions_per_iteration=4,
+ strategy="source-based",
+ settings_snapshot=initial_snapshot,
+ username="testuser",
+ )
+
+ # Verify search engine factory received overridden search tool
+ assert captured_factory_search_tool == "searxng"
+
+ assert captured_snapshot["search.tool"]["value"] == "searxng"
+ assert captured_snapshot["search.tool"]["ui_element"] == "select"
+ assert captured_snapshot["search.iterations"]["value"] == 5
+ assert captured_snapshot["search.questions_per_iteration"]["value"] == 4
+ assert (
+ captured_snapshot["search.search_strategy"]["value"]
+ == "source-based"
+ )
+ assert captured_snapshot["llm.provider"]["value"] == "ollama"
+ assert captured_snapshot["llm.model"]["value"] == "llama3"
+ assert (
+ captured_snapshot["llm.openai_endpoint.url"]
+ == "http://localhost:11434/v1"
+ )
+
+ def test_run_research_process_does_not_widen_search_tool_under_strict(
+ self, monkeypatch
+ ):
+ """Worker thread must NOT overwrite the saved primary when
+ policy.egress_scope == strict — that would let the factory PEP
+ silently widen the run to the requested engine even though the
+ user locked scope to strict.
+ """
+ monkeypatch.delenv("LDR_POLICY_EGRESS_SCOPE", raising=False)
+
+ raw_run = _get_raw_run_research_process()
+ patches = _base_run_patches()
+
+ initial_snapshot = {
+ "policy.egress_scope": {
+ "value": "strict",
+ "ui_element": "select",
+ },
+ "search.tool": {"value": "library", "ui_element": "select"},
+ "search.iterations": {"value": 1, "ui_element": "number"},
+ "llm.provider": {"value": "openai", "ui_element": "select"},
+ "llm.model": {"value": "gpt-3.5", "ui_element": "text"},
+ }
+
+ captured_snapshot = {}
+
+ def mock_system_cls(*args, **kwargs):
+ nonlocal captured_snapshot
+ captured_snapshot = kwargs.get("settings_snapshot", {})
+ system = MagicMock()
+ system.analyze_topic.return_value = {
+ "findings": "test findings",
+ "formatted_findings": "formatted findings",
+ }
+ return system
+
+ patches[f"{MODULE}.apply_environment_overrides_to_snapshot"] = (
+ lambda s: dict(s)
+ )
+ patches[f"{MODULE}.get_llm"] = MagicMock(return_value=MagicMock())
+ patches[f"{MODULE}.AdvancedSearchSystem"] = mock_system_cls
+
+ with ExitStack() as stack:
+ stack.enter_context(
+ patch(
+ "local_deep_research.config.search_config.factory_get_search",
+ return_value=MagicMock(),
+ )
+ )
+ stack.enter_context(
+ patch(
+ "local_deep_research.security.egress.policy.context_from_snapshot",
+ return_value=MagicMock(),
+ )
+ )
+ stack.enter_context(
+ patch(
+ "local_deep_research.security.egress.run_classification.audit_run_from_snapshot",
+ return_value=MagicMock(allowed=True),
+ )
+ )
+ for target, mock_obj in patches.items():
+ stack.enter_context(patch(target, mock_obj))
+
+ raw_run(
+ research_id="strict_run",
+ query="test query",
+ mode="quick",
+ search_engine="searxng",
+ model_provider="ollama",
+ model="llama3",
+ iterations=5,
+ settings_snapshot=initial_snapshot,
+ username="testuser",
+ )
+
+ # STRICT: search.tool stays on the saved primary (library).
+ assert captured_snapshot["search.tool"]["value"] == "library"
+ # Other non-engine kwargs still overlay as documented.
+ assert captured_snapshot["search.iterations"]["value"] == 5
+ assert captured_snapshot["llm.provider"]["value"] == "ollama"
+
+
+class TestSourceBasedStrategyIterationPlumbing:
+ def test_source_based_strategy_respects_max_iterations_and_questions(self):
+ """SourceBasedSearchStrategy must use explicit max_iterations and questions_per_iteration."""
+ mock_model = MagicMock()
+ mock_search = MagicMock()
+ mock_search.run.return_value = []
+ mock_search.include_full_content = True
+
+ strategy = SourceBasedSearchStrategy(
+ model=mock_model,
+ search=mock_search,
+ max_iterations=4,
+ questions_per_iteration=6,
+ settings_snapshot={
+ "search.iterations": {"value": 1},
+ "search.questions_per_iteration": {"value": 2},
+ },
+ )
+
+ assert strategy.max_iterations == 4
+ assert strategy.questions_per_iteration == 6
+
+ # When analyzing topic, it should execute 4 iterations with questions_per_iteration=6
+ with patch.object(
+ strategy.question_generator,
+ "generate_questions",
+ return_value=["q1", "q2"],
+ ) as mock_gen:
+ strategy.analyze_topic("test topic")
+ assert mock_gen.call_count == 4
+ for call in mock_gen.call_args_list:
+ assert call.kwargs["questions_per_iteration"] == 6
+
+ def test_source_based_strategy_falls_back_to_settings(self):
+ """When max_iterations is None, SourceBasedSearchStrategy falls back to settings."""
+ mock_model = MagicMock()
+ mock_search = MagicMock()
+ mock_search.run.return_value = []
+ mock_search.include_full_content = True
+
+ strategy = SourceBasedSearchStrategy(
+ model=mock_model,
+ search=mock_search,
+ settings_snapshot={
+ "search.iterations": {"value": 2},
+ "search.questions_per_iteration": {"value": 3},
+ },
+ )
+
+ assert strategy.max_iterations is None
+ assert strategy.questions_per_iteration is None
+
+ with patch.object(
+ strategy.question_generator,
+ "generate_questions",
+ return_value=["q1", "q2"],
+ ) as mock_gen:
+ strategy.analyze_topic("test topic")
+ assert mock_gen.call_count == 2
+ for call in mock_gen.call_args_list:
+ assert call.kwargs["questions_per_iteration"] == 3
+
+ def test_create_strategy_passes_iterations_to_source_based(self):
+ """Factory must forward max_iterations and questions_per_iteration."""
+ mock_model = MagicMock()
+ mock_search = MagicMock()
+
+ strategy = create_strategy(
+ strategy_name="source-based",
+ model=mock_model,
+ search=mock_search,
+ max_iterations=7,
+ questions_per_iteration=8,
+ )
+
+ assert isinstance(strategy, SourceBasedSearchStrategy)
+ assert strategy.max_iterations == 7
+ assert strategy.questions_per_iteration == 8
+
+
+class TestSearchSystemPlumbing:
+ def test_search_system_followup_passes_iterations_to_delegate(self):
+ """EnhancedContextualFollowUpStrategy delegate must receive max_iterations."""
+ mock_model = MagicMock()
+ mock_search = MagicMock()
+
+ system = AdvancedSearchSystem(
+ llm=mock_model,
+ search=mock_search,
+ strategy_name="enhanced-contextual-followup",
+ max_iterations=3,
+ questions_per_iteration=5,
+ research_context={"delegate_strategy": "source-based"},
+ )
+
+ delegate = system.strategy.delegate_strategy
+ assert isinstance(delegate, SourceBasedSearchStrategy)
+ assert delegate.max_iterations == 3
+ assert delegate.questions_per_iteration == 5
+
+ def test_init_search_system_programmatic_plumbing(self):
+ """_init_search_system overlays snapshot and constructs AdvancedSearchSystem with iterations."""
+ mock_llm = MagicMock()
+ mock_search = MagicMock()
+ snapshot = {}
+
+ with (
+ patch(
+ "local_deep_research.api.research_functions.get_llm",
+ return_value=mock_llm,
+ ),
+ patch(
+ "local_deep_research.api.research_functions.get_search",
+ return_value=mock_search,
+ ),
+ patch(
+ "local_deep_research.api.research_functions.AdvancedSearchSystem"
+ ) as mock_sys_cls,
+ ):
+ _init_search_system(
+ search_tool="searxng",
+ iterations=4,
+ questions_per_iteration=6,
+ search_strategy="source-based",
+ settings_snapshot=snapshot,
+ )
+
+ mock_sys_cls.assert_called_once()
+ _, kwargs = mock_sys_cls.call_args
+ overlaid = kwargs["settings_snapshot"]
+ assert overlaid["search.tool"] == "searxng"
+ assert overlaid["search.iterations"] == 4
+ assert overlaid["search.questions_per_iteration"] == 6
+ assert overlaid["search.search_strategy"] == "source-based"
+ assert snapshot == {}
+ assert kwargs["max_iterations"] == 4
+ assert kwargs["questions_per_iteration"] == 6
+ assert kwargs["strategy_name"] == "source-based"
+
+ def test_init_search_system_does_not_clobber_snapshot_defaults(self):
+ snapshot = {
+ "search.tool": {"value": "wikipedia"},
+ "search.iterations": {"value": 5},
+ "search.questions_per_iteration": {"value": 4},
+ "search.search_strategy": {"value": "langgraph-agent"},
+ }
+
+ with (
+ patch(
+ "local_deep_research.api.research_functions.get_llm",
+ return_value=MagicMock(),
+ ),
+ patch(
+ "local_deep_research.api.research_functions.get_search",
+ return_value=MagicMock(),
+ ),
+ patch(
+ "local_deep_research.api.research_functions.AdvancedSearchSystem"
+ ) as mock_sys_cls,
+ ):
+ _init_search_system(settings_snapshot=snapshot)
+
+ _, kwargs = mock_sys_cls.call_args
+ overlaid = kwargs["settings_snapshot"]
+ assert overlaid["search.tool"]["value"] == "wikipedia"
+ assert overlaid["search.iterations"]["value"] == 5
+ assert overlaid["search.questions_per_iteration"]["value"] == 4
+ assert overlaid["search.search_strategy"]["value"] == (
+ "langgraph-agent"
+ )
+ assert kwargs["strategy_name"] == "langgraph-agent"
+ assert kwargs["max_iterations"] is None
+ assert kwargs["questions_per_iteration"] is None
+ assert snapshot["search.search_strategy"]["value"] == (
+ "langgraph-agent"
+ )