Skip to content

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

feat(search): per-engine time_period "Use global default" (inherit) semantics (#5587) (#5588)

LearningCircuita2df3447936c
diff --git a/changelog.d/5587.breaking.md b/changelog.d/5587.breaking.md
new file mode 100644
index 0000000000..412c85134d
--- /dev/null
+++ b/changelog.d/5587.breaking.md
@@ -0,0 +1 @@
+**Per-engine time-period settings now support "Use global default".** The `search.engine.web.{brave,serpapi,tavily}.default_params.time_period` settings are now dropdowns defaulting to **Use global default** (`inherit`): they follow Settings → Search → Time Period unless a specific period is chosen, in which case the per-engine choice overrides the global one for that engine (one resolution order on every path, highest first: a `time_period` passed in code; a per-engine environment variable `LDR_SEARCH_ENGINE_WEB_<ENGINE>_DEFAULT_PARAMS_TIME_PERIOD`; `LDR_SEARCH_TIME_PERIOD`; a per-request `time_period` on `/research/api/start`; the per-engine choice saved in Settings; the global setting saved in Settings; `all` when none is set). An omitted global setting in a partial programmatic snapshot, or a stored global setting with no value, uses the documented `all` default. A malformed selected period raises a configuration error instead of selecting another period or removing the filter; only the explicit per-engine `inherit` choice follows the global setting. Migration 0034 updates rows still holding the old shipped defaults (`y` for Brave/SerpAPI, `all` for Tavily) to `inherit` and refreshes the fields' dropdown metadata. Brave and SerpAPI used to be free-text fields, so it also repairs legacy values the strict resolver would otherwise reject on every search: a case or whitespace variant of a period code (for example `Y` or ` w `) becomes that period (Brave ignored such variants before, so it now applies them), and any other value (blank, null, free text such as `year`, or a literal `inherit` typed into Brave's old text field) becomes what it effectively meant before, which is `all` for Brave (it ignored the value) and `inherit` for SerpAPI and Tavily (the global setting shadowed the value). Other explicitly-chosen values are preserved, but a deliberately re-selected shipped default is indistinguishable from an inherited one and flips too — re-select it in Settings after upgrading if you relied on it. Note the flip side: a previously-ignored per-engine choice (these fields used to be silently overridden by the global setting) now takes effect after upgrading, as do old per-engine values carried in externally-stored settings snapshots or exports and, for SerpAPI and Tavily, values pinned via `LDR_SEARCH_ENGINE_WEB_*_DEFAULT_PARAMS_TIME_PERIOD` environment variables (the global setting used to shadow those too). Environment pins are operator policy: the migration cannot rewrite them, no per-request period replaces them, and `LDR_SEARCH_TIME_PERIOD` keeps outranking a period saved for a single engine (now for Brave as well). Research jobs already queued when you upgrade keep the settings captured at submission and are not migrated: unless the job carried its own `time_period`, an old SerpAPI `y` or Tavily `all` in one now applies to that run instead of the global setting (Brave's `y` applied before too), and an unrecognized legacy period in one makes that run fail with the time-period configuration error, so resubmit those jobs. Behavior change: **Brave now follows the global time-period setting by default** — previously its per-engine `y` silently pinned Brave to Past-year on every search path, so with the global default of "All time", Brave searches are no longer year-restricted unless a period is selected.
diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md
index 5b571fa03d..6b7e22f616 100644
--- a/docs/CONFIGURATION.md
+++ b/docs/CONFIGURATION.md
@@ -247,7 +247,7 @@ They are not available in the Web UI because they are needed to start the applic
| `search.engine.web.brave.default_params.region` | `LDR_SEARCH_ENGINE_WEB_BRAVE_DEFAULT_PARAMS_REGION` | `US` | Geographic region code for Brave search results (e.g., 'US', 'UK', 'DE'). | SEARCH |
| `search.engine.web.brave.default_params.safe_search` | `LDR_SEARCH_ENGINE_WEB_BRAVE_DEFAULT_PARAMS_SAFE_SEARCH` | `true` | Enable safe search filtering for Brave to exclude adult content. | SEARCH |
| `search.engine.web.brave.default_params.search_language` | `LDR_SEARCH_ENGINE_WEB_BRAVE_DEFAULT_PARAMS_SEARCH_LANGUAGE` | `English` | Preferred language for Brave search results. | SEARCH |
-| `search.engine.web.brave.default_params.time_period` | `LDR_SEARCH_ENGINE_WEB_BRAVE_DEFAULT_PARAMS_TIME_PERIOD` | `y` | Time range filter for Brave results (e.g., 'd' for day, 'w' for week, 'm' for month, 'y' for year). | SEARCH |
+| `search.engine.web.brave.default_params.time_period` | `LDR_SEARCH_ENGINE_WEB_BRAVE_DEFAULT_PARAMS_TIME_PERIOD` | `inherit` | Time range filter for Brave results. 'Use global default' follows Settings → Search → Time Period; a specific value here overrides that saved global setting for this engine ('all' = no filter). When the LDR_SEARCH_TIME_PERIOD environment variable is set it takes precedence over a value saved here, and this engine's own environment variable takes precedence over both. | SEARCH |
| `search.engine.web.brave.description` | `LDR_SEARCH_ENGINE_WEB_BRAVE_DESCRIPTION` | `Search the web using the Brave search engine.` | Human-readable description of the search engine. | SEARCH |
| `search.engine.web.brave.display_name` | `LDR_SEARCH_ENGINE_WEB_BRAVE_DISPLAY_NAME` | `Brave` | Display name to use in the U.I. for this search engine. | SEARCH |
| `search.engine.web.brave.reliability` | `LDR_SEARCH_ENGINE_WEB_BRAVE_RELIABILITY` | `0.7` | Reliability rating (0-1) for Brave Search. Good general-purpose search with privacy focus. | SEARCH |
@@ -508,7 +508,7 @@ They are not available in the Web UI because they are needed to start the applic
| `search.engine.web.serpapi.default_params.region` | `LDR_SEARCH_ENGINE_WEB_SERPAPI_DEFAULT_PARAMS_REGION` | `us` | Geographic region for search results (e.g., 'us', 'uk'). Results prioritized from this region. | SEARCH |
| `search.engine.web.serpapi.default_params.safe_search` | `LDR_SEARCH_ENGINE_WEB_SERPAPI_DEFAULT_PARAMS_SAFE_SEARCH` | `true` | Enable safe search to filter explicit content from results. | SEARCH |
| `search.engine.web.serpapi.default_params.search_language` | `LDR_SEARCH_ENGINE_WEB_SERPAPI_DEFAULT_PARAMS_SEARCH_LANGUAGE` | `English` | Language for search queries and results. Filters results by language. | SEARCH |
-| `search.engine.web.serpapi.default_params.time_period` | `LDR_SEARCH_ENGINE_WEB_SERPAPI_DEFAULT_PARAMS_TIME_PERIOD` | `y` | Time range filter for SerpAPI results: 'd' (day), 'w' (week), 'm' (month), 'y' (year), or 'all' (no filter). Overridden by the global Search → Time Period setting whenever that is set (the normal case); applies only to programmatic snapshots without it. | SEARCH |
+| `search.engine.web.serpapi.default_params.time_period` | `LDR_SEARCH_ENGINE_WEB_SERPAPI_DEFAULT_PARAMS_TIME_PERIOD` | `inherit` | Time range filter for SerpAPI results. 'Use global default' follows Settings → Search → Time Period; a specific value here overrides that saved global setting for this engine ('all' = no filter). When the LDR_SEARCH_TIME_PERIOD environment variable is set it takes precedence over a value saved here, and this engine's own environment variable takes precedence over both. | SEARCH |
| `search.engine.web.serpapi.description` | `LDR_SEARCH_ENGINE_WEB_SERPAPI_DESCRIPTION` | `Search the web with Google's search API.` | Human-readable description of the search engine. | SEARCH |
| `search.engine.web.serpapi.display_name` | `LDR_SEARCH_ENGINE_WEB_SERPAPI_DISPLAY_NAME` | `SerpApi` | Display name to use in the U.I. for this search engine. | SEARCH |
| `search.engine.web.serpapi.reliability` | `LDR_SEARCH_ENGINE_WEB_SERPAPI_RELIABILITY` | `0.6` | Reliability score (0-1). SerpAPI rated moderate (0.6) - good for general search but less authoritative than specialized sources. | SEARCH |
@@ -574,7 +574,7 @@ They are not available in the Web UI because they are needed to start the applic
| `search.engine.web.tavily.api_key` | `LDR_SEARCH_ENGINE_WEB_TAVILY_API_KEY` | `` | The Tavily API key to use. | SEARCH |
| `search.engine.web.tavily.default_params.include_full_content` | `LDR_SEARCH_ENGINE_WEB_TAVILY_DEFAULT_PARAMS_INCLUDE_FULL_CONTENT` | `true` | Include full webpage content in results | SEARCH |
| `search.engine.web.tavily.default_params.search_depth` | `LDR_SEARCH_ENGINE_WEB_TAVILY_DEFAULT_PARAMS_SEARCH_DEPTH` | `basic` | Search depth - basic for speed, advanced for quality | SEARCH |
-| `search.engine.web.tavily.default_params.time_period` | `LDR_SEARCH_ENGINE_WEB_TAVILY_DEFAULT_PARAMS_TIME_PERIOD` | `all` | Time range filter for Tavily results: 'd' (day), 'w' (week), 'm' (month), 'y' (year), or 'all' (no filter). Overridden by the global Search → Time Period setting whenever that is set (the normal case); applies only to programmatic snapshots without it. | SEARCH |
+| `search.engine.web.tavily.default_params.time_period` | `LDR_SEARCH_ENGINE_WEB_TAVILY_DEFAULT_PARAMS_TIME_PERIOD` | `inherit` | Time range filter for Tavily results. 'Use global default' follows Settings → Search → Time Period; a specific value here overrides that saved global setting for this engine ('all' = no filter). When the LDR_SEARCH_TIME_PERIOD environment variable is set it takes precedence over a value saved here, and this engine's own environment variable takes precedence over both. | SEARCH |
| `search.engine.web.tavily.description` | `LDR_SEARCH_ENGINE_WEB_TAVILY_DESCRIPTION` | `AI-powered search engine optimized for research with built-in answer extraction.` | Human-readable description of the search engine. | SEARCH |
| `search.engine.web.tavily.display_name` | `LDR_SEARCH_ENGINE_WEB_TAVILY_DISPLAY_NAME` | `Tavily` | Display name to use in the U.I. for this search engine. | SEARCH |
| `search.engine.web.tavily.reliability` | `LDR_SEARCH_ENGINE_WEB_TAVILY_RELIABILITY` | `0.8` | Reliability score (0-1). Tavily rated high (0.8) - AI-optimized search designed for research applications. | SEARCH |
diff --git a/docs/env_configuration.md b/docs/env_configuration.md
index 91412f6fa1..bc3fbeac70 100644
--- a/docs/env_configuration.md
+++ b/docs/env_configuration.md
@@ -28,7 +28,7 @@ For example:
>
> **Note on empty values:** Empty environment variables (e.g., `LDR_LLM_PROVIDER=""`) are treated as **not set** — they will not override anything and the setting remains editable in the UI. This is by design: deployment tools like Unraid and Docker Compose templates often create all environment variables even when fields are left blank. Only non-empty values act as overrides. To remove an override, delete the environment variable entirely rather than setting it to an empty string.
>
-> **Per-run overrides:** When starting research via the API or web UI, explicit per-run parameters (`max_results`, `time_period`, `iterations`, `questions_per_iteration`, `strategy`) take precedence over both database settings **and** environment variable overrides for that specific run. Environment variables still lock the stored setting and UI; the per-run exception applies only to the explicit request payload, not to persisted configuration.
+> **Per-run overrides:** When starting research via the API or web UI, explicit per-run parameters (`max_results`, `iterations`, `questions_per_iteration`, `strategy`) take precedence over both database settings **and** environment variable overrides for that specific run. `time_period` follows one order on every path, because environment values are operator policy: a `time_period` passed in code, then a per-engine variable such as `LDR_SEARCH_ENGINE_WEB_SERPAPI_DEFAULT_PARAMS_TIME_PERIOD`, then `LDR_SEARCH_TIME_PERIOD`, then a per-run `time_period`, then the engine's own choice saved in Settings, then the saved Search → Time Period (`all` if none is set). So `LDR_SEARCH_TIME_PERIOD` also outranks a period saved for a single engine, with or without a per-run value. Environment variables still lock the stored setting and UI; the per-run exception applies only to the explicit request payload, not to persisted configuration.
For the complete list of all settings, their environment variable names, and default values, see [CONFIGURATION.md](CONFIGURATION.md).
diff --git a/src/local_deep_research/config/search_config.py b/src/local_deep_research/config/search_config.py
index c3d7438164..ba3d44d29d 100644
--- a/src/local_deep_research/config/search_config.py
+++ b/src/local_deep_research/config/search_config.py
@@ -90,12 +90,11 @@ def get_search(
username=username,
settings_snapshot=settings_snapshot,
),
- "time_period": get_setting_from_snapshot(
- "search.time_period",
- "all",
- username=username,
- settings_snapshot=settings_snapshot,
- ),
+ # time_period is deliberately NOT forwarded here: passing it as an
+ # explicit kwarg would override per-engine
+ # default_params.time_period settings. create_search_engine()
+ # resolves per-engine > global search.time_period from the
+ # settings_snapshot passed below.
"safe_search": get_setting_from_snapshot(
"search.safe_search",
True,
@@ -124,7 +123,7 @@ def get_search(
# Log NULL parameters for debugging
logger.info(
- f"Search config: tool={tool}, max_results={params['max_results']}, time_period={params['time_period']}"
+ f"Search config: tool={tool}, max_results={params['max_results']}"
)
logger.info(f"Full params dict: {params}")
diff --git a/src/local_deep_research/database/migrations/versions/0034_per_engine_time_period_inherit.py b/src/local_deep_research/database/migrations/versions/0034_per_engine_time_period_inherit.py
new file mode 100644
index 0000000000..e19e7c3fb1
--- /dev/null
+++ b/src/local_deep_research/database/migrations/versions/0034_per_engine_time_period_inherit.py
@@ -0,0 +1,314 @@
+"""Flip per-engine time_period defaults to the "inherit" sentinel.
+
+Background
+==========
+Issue #5587 (follow-up to #4978): the per-engine
+``search.engine.web.<engine>.default_params.time_period`` settings shipped
+as materialized values (``"y"`` for brave/serpapi, ``"all"`` for tavily),
+which made them indistinguishable from deliberate user choices. After #4978
+made the global ``search.time_period`` take precedence, the serpapi/tavily
+fields became controls that look live but do nothing.
+
+The fix gives per-engine time_period an explicit ``"inherit"`` state
+("Use global default") as the shipped default. The factory resolves:
+explicit kwarg > per-engine value when not ``"inherit"`` > global
+``search.time_period`` > the documented "all" default when absent. Invalid
+selected values raise instead of selecting another period. Brave joins the
+global resolution: previously its per-engine ``"y"`` silently pinned Brave
+to Past-year on every path.
+
+What this migration does
+========================
+Each of the three per-engine keys is rewritten, row by row, to a value the
+strict resolver accepts:
+
+* The old shipped default (exactly ``"y"`` for brave/serpapi, ``"all"`` for
+ tavily) becomes ``"inherit"``. Users who deliberately re-selected the
+ shipped default are indistinguishable from inheritors and flip too — they
+ can re-select the value in Settings; same documented trade-off as
+ migration 0030.
+* Any other ``d``/``w``/``m``/``y``/``all`` choice is kept. A case or
+ whitespace variant of a choice (``"Y"``, ``" w "``) becomes the canonical
+ choice, as does a variant of ``inherit`` for SerpAPI and Tavily.
+* Any other stored value becomes what it effectively meant before. For Brave
+ that includes a literal ``inherit`` (or a variant): its text field never
+ knew the sentinel, so it was ignored like any other free text.
+
+ - Brave only forwards the exact codes d/w/m/y to its freshness parameter,
+ so every other value, including ``"all"``, searched unfiltered and the
+ global setting never applied: ``"all"``.
+ - SerpAPI and Tavily never saw the stored value, because since #4978 the
+ global ``search.time_period`` shadows it (and with no global setting an
+ unrecognized value meant no filter, which is what ``inherit`` gives): so
+ ``"inherit"``.
+
+ Brave and SerpAPI were free-text fields, so a row can hold blank or
+ whitespace-only text, JSON null or SQL NULL, a number, a boolean, a list or
+ an object, or free text such as ``"year"``, ``"py"`` or ``"none"``. Left
+ as they are, these would make the strict resolver raise on every search
+ with that engine. A cell that is not valid JSON at all is left exactly as
+ it is.
+
+The mapping reads pre-upgrade data and is not meant to run twice over its own
+output. Alembic runs it once; a downgrade first restores the old defaults
+(``inherit`` back to ``y``/``all``), after which a later upgrade reads a
+canonical ``y`` (brave/serpapi) or ``all`` (tavily) as the old default again.
+
+The select UI metadata (``ui_element``/``options``) IS updated here as well:
+the ``import_settings(overwrite=False)`` reconciliation that refreshes row
+metadata from the defaults JSON only runs on a package-version bump, which
+lands on its own schedule — without the metadata update a user upgrading
+between bumps would see a plain text box containing the literal string
+"inherit". Descriptions are left to the reconciliation (cosmetic only).
+
+Storage note: the ``value`` column uses SQLAlchemy's ``JSON`` type; string
+values are stored as their json.dumps TEXT form, and SQLite hands numbers
+back as numbers, so each cell is decoded in Python before it is mapped.
+
+Downgrade restores ``"inherit"`` to the old shipped default and Brave's
+``"all"`` to the blank text that meant no filter before; see ``downgrade``.
+
+Revision ID: 0034
+Revises: 0033
+Create Date: 2026-08-15
+"""
+
+from __future__ import annotations
+
+import json
+
+import sqlalchemy as sa
+from alembic import op
+from loguru import logger
+from sqlalchemy import inspect
+
+revision = "0034"
+down_revision = "0033"
+branch_labels = None
+depends_on = None
+
+INHERIT = "inherit"
+INHERIT_JSON = '"inherit"'
+ALL_JSON = '"all"'
+EMPTY_STRING_JSON = '""'
+
+BRAVE_KEY = "search.engine.web.brave.default_params.time_period"
+SERPAPI_KEY = "search.engine.web.serpapi.default_params.time_period"
+TAVILY_KEY = "search.engine.web.tavily.default_params.time_period"
+
+# key -> old shipped default, as the exact string a row holds
+OLD_DEFAULTS = {BRAVE_KEY: "y", SERPAPI_KEY: "y", TAVILY_KEY: "all"}
+
+# The values a row may hold afterwards: the period codes plus the sentinel.
+CHOICES = frozenset({"d", "w", "m", "y", "all", INHERIT})
+
+# The choices a stored value may be spelled as (any case, any surrounding
+# whitespace) and still be taken as that choice. Brave's old text field never
+# knew "inherit": it forwarded only the exact codes d/w/m/y, so a typed
+# "inherit" searched unfiltered like any other unrecognized text.
+RECOGNIZED_CHOICES = {
+ BRAVE_KEY: CHOICES - {INHERIT},
+ SERPAPI_KEY: CHOICES,
+ TAVILY_KEY: CHOICES,
+}
+
+# key -> what a stored value that is not a recognizable choice effectively
+# meant before this migration (see "What this migration does" above).
+UNRECOGNIZED_BECOMES = {
+ BRAVE_KEY: "all",
+ SERPAPI_KEY: INHERIT,
+ TAVILY_KEY: INHERIT,
+}
+
+# The select options every per-engine time_period row gets on upgrade
+# (mirrors defaults/default_settings.json; the options column stores JSON).
+NEW_OPTIONS_JSON = (
+ '[{"label": "Use global default", "value": "inherit"}, '
+ '{"label": "Past 24 hours", "value": "d"}, '
+ '{"label": "Past week", "value": "w"}, '
+ '{"label": "Past month", "value": "m"}, '
+ '{"label": "Past year", "value": "y"}, '
+ '{"label": "All time", "value": "all"}]'
+)
+
+# Pre-upgrade metadata per key, restored on downgrade. Brave/serpapi were
+# free-text fields; tavily was already a select with the five period codes.
+OLD_TAVILY_OPTIONS_JSON = (
+ '[{"label": "Past 24 hours", "value": "d"}, '
+ '{"label": "Past week", "value": "w"}, '
+ '{"label": "Past month", "value": "m"}, '
+ '{"label": "Past year", "value": "y"}, '
+ '{"label": "All time", "value": "all"}]'
+)
+OLD_METADATA = {
+ BRAVE_KEY: ("text", None),
+ SERPAPI_KEY: ("text", None),
+ TAVILY_KEY: ("select", OLD_TAVILY_OPTIONS_JSON),
+}
+
+_NOT_JSON = object()
+
+
+def _decode_cell(raw):
+ """Decode a raw ``settings.value`` cell, or return ``_NOT_JSON``."""
+ if raw is None:
+ return None # SQL NULL reads like JSON null
+ if isinstance(raw, (bytes, bytearray, memoryview)):
+ try:
+ raw = bytes(raw).decode("utf-8")
+ except UnicodeDecodeError:
+ return _NOT_JSON
+ if isinstance(raw, str):
+ try:
+ return json.loads(raw)
+ except (ValueError, RecursionError):
+ return _NOT_JSON
+ if isinstance(raw, (int, float)):
+ return raw # SQLite hands JSON numbers back as numbers
+ return _NOT_JSON
+
+
+def upgraded_value(key, stored):
+ """Return the choice ``key`` should hold, given its decoded stored value."""
+ if isinstance(stored, str):
+ if stored == OLD_DEFAULTS[key]:
+ return INHERIT
+ canonical = stored.strip().lower()
+ if canonical in RECOGNIZED_CHOICES[key]:
+ return canonical
+ return UNRECOGNIZED_BECOMES[key]
+
+
+def _rewrite_values(conn, key):
+ """Map every stored value of ``key`` onto a valid choice."""
+ rows = conn.execute(
+ sa.text("SELECT value FROM settings WHERE key = :key"), {"key": key}
+ ).fetchall()
+ for (raw,) in rows:
+ stored = _decode_cell(raw)
+ if stored is _NOT_JSON:
+ continue
+ new_value = upgraded_value(key, stored)
+ if stored == new_value:
+ continue
+ # Match the cell exactly as read (NULL needs IS NULL), so only this
+ # row changes and a row that changed meanwhile is left alone.
+ params = {"key": key, "new_value": json.dumps(new_value)}
+ if raw is None:
+ statement = sa.text(
+ "UPDATE settings SET value = :new_value "
+ "WHERE key = :key AND value IS NULL"
+ )
+ else:
+ statement = sa.text(
+ "UPDATE settings SET value = :new_value "
+ "WHERE key = :key AND value = :raw"
+ )
+ params["raw"] = raw
+ result = conn.execute(statement, params)
+ if result.rowcount:
+ logger.info(
+ "Migrated setting {!r} to {!r} (valid time_period choice).",
+ key,
+ new_value,
+ )
+
+
+def upgrade() -> None:
+ conn = op.get_bind()
+
+ inspector = inspect(conn)
+ if not inspector.has_table("settings"):
+ return
+
+ # Legacy / pre-Alembic settings tables may predate the ui_element and
+ # options columns (later schema migrations add them); the value rewrite
+ # below only needs key/value, but the metadata refresh must be skipped
+ # on such schemas or the whole chain aborts on "no such column".
+ settings_columns = {
+ col["name"] for col in inspector.get_columns("settings")
+ }
+ has_metadata_columns = {"ui_element", "options"} <= settings_columns
+
+ for key in OLD_DEFAULTS:
+ _rewrite_values(conn, key)
+
+ # Refresh the UI metadata unconditionally for the key (idempotent),
+ # so the select renders and validates immediately after upgrade
+ # instead of waiting for the next version-bump reconciliation.
+ if has_metadata_columns:
+ conn.execute(
+ sa.text(
+ "UPDATE settings SET ui_element = 'select', "
+ "options = :options WHERE key = :key"
+ ),
+ {"options": NEW_OPTIONS_JSON, "key": key},
+ )
+
+
+def downgrade() -> None:
+ """Revert previously-migrated rows to their old shipped defaults.
+
+ Rows currently holding ``"inherit"`` go back to the old shipped default.
+ Rows the user explicitly set to "Use global default" post-upgrade are
+ indistinguishable from migrated rows and revert too, since the
+ pre-upgrade schema had no inherit state. A canonical ``"y"``
+ (brave/serpapi) or ``"all"`` (tavily) is the old shipped default again,
+ so a later upgrade flips it to ``"inherit"``.
+
+ Explicit d/w/m/y/all choices are otherwise left alone, with one
+ exception: Brave rows holding ``"all"`` become the blank text that meant
+ no filter before. The upgrade writes ``"all"`` for the values Brave
+ ignored, and its pre-upgrade free-text field had no distinct "all"
+ choice. SerpAPI and Tavily keep ``"all"``, which was a documented choice
+ for them before.
+ """
+ conn = op.get_bind()
+
+ inspector = inspect(conn)
+ if not inspector.has_table("settings"):
+ return
+
+ settings_columns = {
+ col["name"] for col in inspector.get_columns("settings")
+ }
+ has_metadata_columns = {"ui_element", "options"} <= settings_columns
+
+ for key, old_default in OLD_DEFAULTS.items():
+ conn.execute(
+ sa.text(
+ "UPDATE settings SET value = :old_value "
+ "WHERE key = :key AND value = :new_value"
+ ),
+ {
+ "old_value": json.dumps(old_default),
+ "key": key,
+ "new_value": INHERIT_JSON,
+ },
+ )
+
+ if has_metadata_columns:
+ old_ui_element, old_options = OLD_METADATA[key]
+ conn.execute(
+ sa.text(
+ "UPDATE settings SET ui_element = :ui_element, "
+ "options = :options WHERE key = :key"
+ ),
+ {
+ "ui_element": old_ui_element,
+ "options": old_options,
+ "key": key,
+ },
+ )
+
+ conn.execute(
+ sa.text(
+ "UPDATE settings SET value = :old_value "
+ "WHERE key = :key AND value = :new_value"
+ ),
+ {
+ "old_value": EMPTY_STRING_JSON,
+ "key": BRAVE_KEY,
+ "new_value": ALL_JSON,
+ },
+ )
diff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.json
index b70429bc86..bb0330f897 100644
--- a/src/local_deep_research/defaults/default_settings.json
+++ b/src/local_deep_research/defaults/default_settings.json
@@ -1968,16 +1968,41 @@
},
"search.engine.web.brave.default_params.time_period": {
"category": "brave",
- "description": "Time range filter for Brave results (e.g., 'd' for day, 'w' for week, 'm' for month, 'y' for year).",
+ "description": "Time range filter for Brave results. 'Use global default' follows Settings → Search → Time Period; a specific value here overrides that saved global setting for this engine ('all' = no filter). When the LDR_SEARCH_TIME_PERIOD environment variable is set it takes precedence over a value saved here, and this engine's own environment variable takes precedence over both.",
"editable": true,
"max_value": null,
"min_value": null,
"name": "Time Period",
- "options": null,
+ "options": [
+ {
+ "label": "Use global default",
+ "value": "inherit"
+ },
+ {
+ "label": "Past 24 hours",
+ "value": "d"
+ },
+ {
+ "label": "Past week",
+ "value": "w"
+ },
+ {
+ "label": "Past month",
+ "value": "m"
+ },
+ {
+ "label": "Past year",
+ "value": "y"
+ },
+ {
+ "label": "All time",
+ "value": "all"
+ }
+ ],
"step": null,
"type": "SEARCH",
- "ui_element": "text",
- "value": "y",
+ "ui_element": "select",
+ "value": "inherit",
"visible": true
},
"search.engine.web.brave.reliability": {
@@ -3088,16 +3113,41 @@
},
"search.engine.web.serpapi.default_params.time_period": {
"category": "serpapi",
- "description": "Time range filter for SerpAPI results: 'd' (day), 'w' (week), 'm' (month), 'y' (year), or 'all' (no filter). Overridden by the global Search → Time Period setting whenever that is set (the normal case); applies only to programmatic snapshots without it.",
+ "description": "Time range filter for SerpAPI results. 'Use global default' follows Settings → Search → Time Period; a specific value here overrides that saved global setting for this engine ('all' = no filter). When the LDR_SEARCH_TIME_PERIOD environment variable is set it takes precedence over a value saved here, and this engine's own environment variable takes precedence over both.",
"editable": true,
"max_value": null,
"min_value": null,
"name": "Time Period",
- "options": null,
+ "options": [
+ {
+ "label": "Use global default",
+ "value": "inherit"
+ },
+ {
+ "label": "Past 24 hours",
+ "value": "d"
+ },
+ {
+ "label": "Past week",
+ "value": "w"
+ },
+ {
+ "label": "Past month",
+ "value": "m"
+ },
+ {
+ "label": "Past year",
+ "value": "y"
+ },
+ {
+ "label": "All time",
+ "value": "all"
+ }
+ ],
"step": null,
"type": "SEARCH",
- "ui_element": "text",
- "value": "y",
+ "ui_element": "select",
+ "value": "inherit",
"visible": true
},
"search.engine.web.serpapi.reliability": {
@@ -4014,12 +4064,16 @@
},
"search.engine.web.tavily.default_params.time_period": {
"category": "tavily",
- "description": "Time range filter for Tavily results: 'd' (day), 'w' (week), 'm' (month), 'y' (year), or 'all' (no filter). Overridden by the global Search → Time Period setting whenever that is set (the normal case); applies only to programmatic snapshots without it.",
+ "description": "Time range filter for Tavily results. 'Use global default' follows Settings → Search → Time Period; a specific value here overrides that saved global setting for this engine ('all' = no filter). When the LDR_SEARCH_TIME_PERIOD environment variable is set it takes precedence over a value saved here, and this engine's own environment variable takes precedence over both.",
"editable": true,
"max_value": null,
"min_value": null,
"name": "Time Period",
"options": [
+ {
+ "label": "Use global default",
+ "value": "inherit"
+ },
{
"label": "Past 24 hours",
"value": "d"
@@ -4044,7 +4098,7 @@
"step": null,
"type": "SEARCH",
"ui_element": "select",
- "value": "all",
+ "value": "inherit",
"visible": true
},
"search.engine.web.tavily.requires_api_key": {
diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.py
index ce5c1f6074..95365c6aa6 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -1253,6 +1253,17 @@ def run_research_process(research_id, query, mode, **kwargs):
max_results=max_results,
time_period=time_period,
)
+ if time_period is not None:
+ # A per-request period replaces the saved global and per-engine
+ # choices for this run: besides the global slot, per-engine
+ # time_period choices (which outrank the saved global in
+ # create_search_engine's resolution) are reset to inherit in this
+ # run's snapshot copy. Environment pins still outrank it.
+ from ...web_search_engines.search_engine_factory import (
+ apply_time_period_override,
+ )
+
+ apply_time_period_override(settings_snapshot, 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 d12ecd072b..fbba47203c 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
@@ -1,10 +1,12 @@
import inspect
-from typing import Any, Dict, Optional
+from typing import Any, Dict, Optional, TypeGuard
from ..security.egress.policy import PolicyDeniedError
from ..security.log_sanitizer import scrub_error
from ..security.module_whitelist import get_safe_module_class
from ..security.secure_logging import logger
+from ..config.thread_settings import get_setting_from_snapshot
+from ..settings.manager import SettingsManager, check_env_setting
from ..settings.exceptions import SettingsValueError
from .engine_groups import is_collection_engine
from .retriever_registry import retriever_registry
@@ -12,16 +14,166 @@ from ..utilities.search_utilities import LANGUAGE_CODE_MAP
from ..utilities.type_utils import (
_is_strict_scope,
resolve_snippets_only,
+ overlay_snapshot_value,
to_bool,
)
-from .search_engine_base import BaseSearchEngine
+from .search_engine_base import VALID_TIME_PERIODS, BaseSearchEngine
from .search_engines_config import search_config
-# Engines whose constructors accept the global ``search.time_period`` filter.
-# Used both by get_search()'s explicit forwarding and by
-# create_search_engine()'s settings-snapshot fallback so that direct callers
-# (langgraph-agent strategy tools, MCP server) honor the setting too.
-TIME_PERIOD_ENGINES = ("serpapi", "tavily", "wikinews")
+# Engines whose constructors accept the shared time-period choices. Resolution
+# (see _resolve_time_period) is, highest first: explicit caller override,
+# per-engine environment variable, LDR_SEARCH_TIME_PERIOD, concrete per-engine
+# choice in the settings, global setting. A missing global setting (absent, or
+# a stored null) uses the documented "all" default; malformed values never
+# select another period. Wikinews has no per-engine setting by default.
+TIME_PERIOD_ENGINES = ("brave", "serpapi", "tavily", "wikinews")
+TIME_PERIOD_INHERIT = "inherit"
+TIME_PERIOD_CHOICES = VALID_TIME_PERIODS | {"all"}
+_TIME_PERIOD_UNSET = object()
+
+
+def _is_time_period_choice(value: object) -> TypeGuard[str]:
+ """True when ``value`` is a concrete, valid period selection.
+
+ A type guard for the static checker only: a caller that has just run it
+ on a raw (untyped) setting value may use that value as ``str``. Nothing
+ changes at runtime.
+ """
+ return isinstance(value, str) and value in TIME_PERIOD_CHOICES
+
+
+def _require_time_period(value: object, key: str) -> str:
+ """Reject malformed selected values without including them in errors."""
+ if not _is_time_period_choice(value):
+ raise ValueError(f"{key} must be one of d, w, m, y, all")
+ return value
+
+
+def _require_env_time_period(
+ value: object, key: str, *, allow_inherit: bool = False
+) -> str:
+ """Like ``_require_time_period`` for a value read from the environment.
+
+ Names the variable and says that case and surrounding whitespace matter
+ (a carriage return left by a Windows-edited ``.env``, or ``Y``, is the
+ usual cause), still without echoing the value. ``allow_inherit`` is for
+ the per-engine variable, which accepts the ``inherit`` sentinel too.
+ """
+ if not _is_time_period_choice(value):
+ variable = SettingsManager.get_env_var_for_setting(key)
+ choices = ("inherit, " if allow_inherit else "") + "d, w, m, y, all"
+ raise ValueError(
+ f"Environment variable {variable} must be one of {choices}; "
+ "case and surrounding whitespace matter"
+ )
+ return value
+
+
+def _resolve_time_period(engine_name, engine_config, settings_snapshot, kwargs):
+ """Return the validated period (d/w/m/y/all) for a time-period engine.
+
+ One order on every path, highest first: an explicit ``time_period``
+ kwarg; the engine's own environment variable; ``LDR_SEARCH_TIME_PERIOD``;
+ a concrete per-engine choice in the settings snapshot; the snapshot's
+ global ``search.time_period`` (``all`` when absent or null). Environment
+ values are operator policy, so the global pin outranks a per-engine
+ choice saved in Settings whether or not the request carried a period.
+ ``inherit`` (as a kwarg or a saved per-engine choice) defers to the next
+ level; the engine's environment variable set to ``inherit`` also hides a
+ saved per-engine choice. A selected value that is malformed raises
+ ``ValueError`` (naming the variable when it came from the environment)
+ and never falls through to a lower level.
+ """
+ explicit = kwargs.get("time_period", _TIME_PERIOD_UNSET)
+ if explicit is not _TIME_PERIOD_UNSET and explicit != TIME_PERIOD_INHERIT:
+ return _require_time_period(explicit, "time_period")
+
+ # nosemgrep: semgrep.rules.sql-string-concatenation, reason: settings lookup key and never a SQL query
+ per_engine_key = (
+ f"search.engine.web.{engine_name}.default_params.time_period"
+ )
+ engine_pin = check_env_setting(per_engine_key)
+ if engine_pin is not None and engine_pin != TIME_PERIOD_INHERIT:
+ return _require_env_time_period(
+ engine_pin, per_engine_key, allow_inherit=True
+ )
+
+ global_pin = check_env_setting("search.time_period")
+ if global_pin is not None:
+ return _require_env_time_period(global_pin, "search.time_period")
+
+ if engine_pin is None:
+ saved = (engine_config.get("default_params") or {}).get(
+ "time_period", _TIME_PERIOD_UNSET
+ )
+ if saved is not _TIME_PERIOD_UNSET and saved != TIME_PERIOD_INHERIT:
+ return _require_time_period(saved, per_engine_key)
+
+ # The ordinary typed lookup also preserves bound settings-context reads.
+ global_period = get_setting_from_snapshot(
+ "search.time_period", "all", settings_snapshot=settings_snapshot
+ )
+ if global_period is None:
+ # A stored null means "not set", as it always has. It arrives as
+ # {"value": None} in a full snapshot and as a bare None once
+ # SettingsManager.get_settings_snapshot() (REST /api/v1, scheduled
+ # news runs) unwraps the entry. Use the documented default rather
+ # than failing every search on those paths.
+ global_period = "all"
+ return _require_time_period(global_period, "search.time_period")
+
+
+def apply_time_period_override(settings_snapshot, time_period) -> None:
+ """Apply a per-request time-period override to a run-scoped snapshot.
+
+ Writes the value into the global ``search.time_period`` slot, keeping the
+ entry's envelope metadata, and resets any per-engine override present in
+ the snapshot to the inherit sentinel, so the request-level choice wins
+ for this run even though per-engine settings normally outrank the global
+ slot. Mutates ``settings_snapshot`` in place; callers must pass the run's
+ own snapshot copy, never a shared or cached one.
+
+ Environment values remain operator policy. When ``LDR_SEARCH_TIME_PERIOD``
+ is set, that value (not the request's) is what the global slot receives,
+ and a per-engine key pinned by its own environment variable is not
+ reset. (``_resolve_time_period`` ranks both kinds of pin above saved
+ per-engine choices on every path, request or not; the reset below is what
+ lets a request replace the saved choices of engines that have no pin of
+ their own while ``LDR_SEARCH_TIME_PERIOD`` is unset.) An invalid request
+ value, or an invalid global environment value, raises ``ValueError``
+ before the snapshot is mutated.
+
+ A pin is recognized by looking the variable up in the environment
+ (``check_env_setting``), which covers raw-valued and metadata-wrapped
+ entries alike. ``apply_environment_overrides_to_snapshot``
+ (settings/manager.py) also marks the entries it pins with
+ ``editable: False``, but that marker is deliberately NOT consulted:
+ ``SettingsManager.get_all_settings`` sets it on every database-backed
+ entry when ``app.lock_settings`` is on, and the research start snapshot
+ is taken that way, so honoring it would stop a per-request period from
+ replacing explicit per-engine choices on a locked installation. Per
+ ``apply_environment_overrides_to_snapshot``, "environment values are
+ operator policy and retain highest precedence at actual dispatch time",
+ and the changelog states that an environment-pinned value is a deliberate
+ override that a per-request period does not replace.
+ """
+ _require_time_period(time_period, "time_period")
+ operator_period = check_env_setting("search.time_period")
+ effective_period = (
+ time_period
+ if operator_period is None
+ else _require_env_time_period(operator_period, "search.time_period")
+ )
+ overlay_snapshot_value(
+ settings_snapshot, "search.time_period", effective_period
+ )
+ for engine_name in TIME_PERIOD_ENGINES:
+ # nosemgrep: semgrep.rules.sql-string-concatenation, reason: settings lookup key and never a SQL query
+ key = f"search.engine.web.{engine_name}.default_params.time_period"
+ if key not in settings_snapshot or check_env_setting(key) is not None:
+ continue
+ overlay_snapshot_value(settings_snapshot, key, TIME_PERIOD_INHERIT)
+
# Non-geographic region sentinels that should not be mapped to provider `location`
_NON_LOCATION_REGIONS = frozenset({"wt-wt", "all", "none", "worldwide", ""})
@@ -416,24 +568,12 @@ def create_search_engine(
max_results = 20
kwargs["max_results"] = max_results
- # Route the global time filter to engines that understand it when the
- # caller didn't pass one explicitly. get_search() forwards it as a kwarg,
- # but direct callers (langgraph-agent strategy tools, the MCP server)
- # only pass a settings_snapshot — without this fallback the user's
- # Settings → Search → Time Period choice is silently ignored on those
- # paths. Placed in kwargs so it takes precedence over per-engine
- # default_params, matching get_search()'s behavior.
- if (
- engine_name in TIME_PERIOD_ENGINES
- and "time_period" not in kwargs
- and settings_snapshot
- and "search.time_period" in settings_snapshot
- ):
- raw_time_period = _resolve_setting(
- settings_snapshot, "search.time_period", "all"
+ # Resolve and validate before the constructor catch: configuration errors
+ # must reach the caller rather than becoming a missing search engine.
+ if engine_name in TIME_PERIOD_ENGINES:
+ kwargs["time_period"] = _resolve_time_period(
+ engine_name, engine_config, settings_snapshot, kwargs
)
- if raw_time_period is not None:
- kwargs["time_period"] = str(raw_time_period)
# Route search.snippets_only to engines when the caller didn't pass one
# explicitly. get_search() forwards it as a kwarg, and langgraph-agent
@@ -612,8 +752,10 @@ def create_search_engine(
for p in engine_init_signature.parameters.values()
)
- # Combine default parameters with provided ones
- all_params = {**engine_config.get("default_params", {}), **kwargs}
+ # Combine default parameters with provided ones. ``or {}`` guards a
+ # config row whose default_params is JSON null (None): dict.get returns
+ # that None (the key exists), and ``{**None}`` would raise TypeError.
+ all_params = {**(engine_config.get("default_params") or {}), **kwargs}
# The shared research cache is a factory-level argument, not an
# engine default — inject it so engines that accept it (or **kwargs)
# receive the single cache for the whole research run.
@@ -1058,7 +1200,7 @@ def get_search(
llm_instance,
max_results: int = 10,
region: str = "us",
- time_period: str = "all",
+ time_period: Optional[str] = None,
safe_search: bool = True,
search_snippets_only: Optional[bool] = None,
search_language: str = "English",
@@ -1076,7 +1218,10 @@ def get_search(
llm_instance: Language model instance
max_results: Maximum number of search results
region: Search region/locale
- time_period: Time period for search results
+ time_period: Explicit time filter override (d/w/m/y/all). None (the
+ default) defers to create_search_engine()'s resolution: the
+ per-engine default_params.time_period when not "inherit", else
+ the global search.time_period from the settings snapshot.
safe_search: Whether to enable safe search
search_snippets_only: Whether to return just snippets (vs. full content).
Defaults to None (defers to settings_snapshot or engine default).
@@ -1173,7 +1318,7 @@ def get_search(
# snippet-only unless the setting is forwarded in params or snapshot.
pass
- if search_tool in TIME_PERIOD_ENGINES:
+ if search_tool in TIME_PERIOD_ENGINES and time_period is not None:
params["time_period"] = time_period
# Create and return the search engine
diff --git a/tests/config/test_search_config.py b/tests/config/test_search_config.py
index 2c27172223..780e15ad67 100644
--- a/tests/config/test_search_config.py
+++ b/tests/config/test_search_config.py
@@ -173,7 +173,11 @@ class TestGetSearch:
call_kwargs = mock_factory.call_args[1]
assert call_kwargs["max_results"] == 20
assert call_kwargs["region"] == "us-en"
- assert call_kwargs["time_period"] == "w"
+ # time_period is deliberately NOT forwarded by the wrapper: an
+ # explicit kwarg would override per-engine default_params in
+ # create_search_engine()'s resolution (#5587); it flows via the
+ # settings_snapshot instead.
+ assert "time_period" not in call_kwargs
assert call_kwargs["safe_search"] is False
assert call_kwargs["search_snippets_only"] is False
assert call_kwargs["search_language"] == "German"
diff --git a/tests/database/test_migration_0034_per_engine_time_period_inherit.py b/tests/database/test_migration_0034_per_engine_time_period_inherit.py
new file mode 100644
index 0000000000..ac2bfb8f3e
--- /dev/null
+++ b/tests/database/test_migration_0034_per_engine_time_period_inherit.py
@@ -0,0 +1,636 @@
+"""Tests for migration 0034: per-engine time_period defaults → 'inherit'.
+
+Pins the upgrade/downgrade semantics for the three per-engine keys
+(``search.engine.web.{brave,serpapi,tavily}.default_params.time_period``):
+- Rows holding the old shipped default (``"y"`` for brave/serpapi,
+ ``"all"`` for tavily) get flipped to ``"inherit"``.
+- Rows users explicitly chose are left untouched — including ``"all"`` for
+ brave/serpapi and ``"y"`` for tavily (each engine only matches its OWN
+ old default).
+- Case/whitespace variants of a choice become the canonical choice.
+- Any other legacy value (brave/serpapi were free text) becomes what it
+ effectively meant on main: ``"all"`` for Brave, which ignored it, and
+ ``"inherit"`` for SerpAPI/Tavily, whose value the global setting shadowed.
+ No row is left holding a value the strict resolver rejects.
+- The global ``search.time_period`` key is not affected.
+- Idempotency: a second upgrade is a no-op once values are migrated.
+
+The on-disk encoding is JSON-text (quoted literals), matching production
+storage through SQLAlchemy's JSON column type.
+"""
+
+import json
+import shutil
+
+import pytest
+from alembic import command
+from sqlalchemy import create_engine, text
+
+from local_deep_research.database.alembic_runner import (
+ get_alembic_config,
+)
+
+BRAVE_KEY = "search.engine.web.brave.default_params.time_period"
+SERPAPI_KEY = "search.engine.web.serpapi.default_params.time_period"
+TAVILY_KEY = "search.engine.web.tavily.default_params.time_period"
+
+# key -> old shipped default that the migration flips
+OLD_DEFAULTS = {BRAVE_KEY: "y", SERPAPI_KEY: "y", TAVILY_KEY: "all"}
+
+ENGINE_KEYS = {
+ "brave": BRAVE_KEY,
+ "serpapi": SERPAPI_KEY,
+ "tavily": TAVILY_KEY,
+}
+
+# stored value -> (brave, serpapi, tavily) value after the upgrade. The old
+# shipped default flips to inherit, other choices are kept, variants of a
+# choice are canonicalized, and anything else becomes what it effectively
+# meant on main: "all" for Brave (it ignored the value and the global
+# setting), "inherit" for SerpAPI and Tavily (the global setting shadowed it).
+LEGACY_VALUES = [
+ pytest.param("y", "inherit", "inherit", "y", id="y"),
+ pytest.param("all", "all", "all", "inherit", id="all"),
+ pytest.param("d", "d", "d", "d", id="d"),
+ pytest.param("w", "w", "w", "w", id="w"),
+ pytest.param("m", "m", "m", "m", id="m"),
+ # A typed "inherit": SerpAPI and Tavily would have followed the global
+ # setting anyway, but Brave's old text field never knew the sentinel and
+ # ignored it (unfiltered), so only Brave maps it to "all".
+ pytest.param("inherit", "all", "inherit", "inherit", id="text-inherit"),
+ pytest.param("Y", "y", "y", "y", id="upper-y"),
+ pytest.param(" y", "y", "y", "y", id="leading-space-y"),
+ pytest.param("y ", "y", "y", "y", id="trailing-space-y"),
+ pytest.param("\u00a0y\u00a0", "y", "y", "y", id="nbsp-y"),
+ pytest.param("\tW\n", "w", "w", "w", id="tab-upper-w-newline"),
+ pytest.param("D", "d", "d", "d", id="upper-d"),
+ pytest.param(" m ", "m", "m", "m", id="padded-m"),
+ pytest.param("ALL", "all", "all", "all", id="upper-all"),
+ pytest.param(" All ", "all", "all", "all", id="padded-mixed-all"),
+ pytest.param(
+ "Inherit", "all", "inherit", "inherit", id="text-mixed-inherit"
+ ),
+ pytest.param(
+ " INHERIT ", "all", "inherit", "inherit", id="text-padded-inherit"
+ ),
+ pytest.param("", "all", "inherit", "inherit", id="blank"),
+ pytest.param(" ", "all", "inherit", "inherit", id="whitespace-only"),
+ pytest.param("year", "all", "inherit", "inherit", id="word-year"),
+ pytest.param("py", "all", "inherit", "inherit", id="brave-native-py"),
+ pytest.param("none", "all", "inherit", "inherit", id="word-none"),
+ pytest.param("None", "all", "inherit", "inherit", id="python-none"),
+ pytest.param("undefined", "all", "inherit", "inherit", id="undefined"),
+ pytest.param("past year", "all", "inherit", "inherit", id="two-words"),
+ pytest.param("7", "all", "inherit", "inherit", id="numeric-string"),
+ pytest.param("yy", "all", "inherit", "inherit", id="doubled-code"),
+ pytest.param("\uff39", "all", "inherit", "inherit", id="fullwidth-y"),
+ pytest.param(None, "all", "inherit", "inherit", id="json-null"),
+ pytest.param(7, "all", "inherit", "inherit", id="json-int"),
+ pytest.param(1.5, "all", "inherit", "inherit", id="json-float"),
+ pytest.param(True, "all", "inherit", "inherit", id="json-true"),
+ pytest.param(False, "all", "inherit", "inherit", id="json-false"),
+ pytest.param(["y"], "all", "inherit", "inherit", id="json-list"),
+ pytest.param({"a": 1}, "all", "inherit", "inherit", id="json-object"),
+]
+
+# The rows that are not a recognizable choice at all.
+UNRECOGNIZED_VALUES = [
+ pytest.param(p.values[0], id=p.id)
+ for p in LEGACY_VALUES
+ if p.values[1:] == ("all", "inherit", "inherit")
+]
+
+
+def _run_upgrade_to(engine, revision):
+ config = get_alembic_config(engine)
+ with engine.begin() as conn:
+ config.attributes["connection"] = conn
+ command.upgrade(config, revision)
+
+
+def _run_downgrade_to(engine, revision):
+ config = get_alembic_config(engine)
+ with engine.begin() as conn:
+ config.attributes["connection"] = conn
+ command.downgrade(config, revision)
+
+
+def _seed_setting(engine, key, value, ui_element="select", options=None):
+ """Insert a setting matching production's JSON-text storage."""
+ with engine.begin() as conn:
+ conn.execute(
+ text(
+ "INSERT INTO settings "
+ "(key, value, type, name, ui_element, options, "
+ "visible, editable) "
+ "VALUES (:key, :value, 'search', :name, :ui_element, "
+ ":options, 1, 1)"
+ ),
+ {
+ "key": key,
+ "value": json.dumps(value),
+ "name": key,
+ "ui_element": ui_element,
+ "options": json.dumps(options) if options is not None else None,
+ },
+ )
+
+
+def _seed_raw(engine, key, raw, ui_element="text"):
+ """Insert a settings row whose value cell is exactly ``raw`` (SQL NULL
+ for None), bypassing JSON encoding."""
+ with engine.begin() as conn:
+ conn.execute(
+ text(
+ "INSERT INTO settings "
+ "(key, value, type, name, ui_element, visible, editable) "
+ "VALUES (:key, :value, 'search', :name, :ui_element, 1, 1)"
+ ),
+ {"key": key, "value": raw, "name": key, "ui_element": ui_element},
+ )
+
+
+def _read_raw(engine, key):
+ with engine.begin() as conn:
+ row = conn.execute(
+ text("SELECT value FROM settings WHERE key = :key"),
+ {"key": key},
+ ).fetchone()
+ return row[0]
+
+
+def _read_metadata(engine, key):
+ """Return (ui_element, parsed options) for a settings row."""
+ with engine.begin() as conn:
+ row = conn.execute(
+ text("SELECT ui_element, options FROM settings WHERE key = :key"),
+ {"key": key},
+ ).fetchone()
+ if row is None:
+ return None
+ ui_element, raw_options = row
+ options = (
+ json.loads(raw_options) if isinstance(raw_options, str) else raw_options
+ )
+ return ui_element, options
+
+
+def _read_setting(engine, key):
+ with engine.begin() as conn:
+ row = conn.execute(
+ text("SELECT value FROM settings WHERE key = :key"),
+ {"key": key},
+ ).fetchone()
+ if row is None:
+ return None
+ raw = row[0]
+ return json.loads(raw) if isinstance(raw, str) else raw
+
+
[email protected](scope="module")
+def _migrated_to_0033_template(tmp_path_factory):
+ """Template DB fully migrated through 0033, built once per module.
+
+ Same cost-amortization pattern as test_migration_0030's template: the
+ full 0001->0033 chain is built once; each test copies the file.
+ """
+ template_dir = tmp_path_factory.mktemp("migration_0034_template")
+ db_path = template_dir / "template_0033.db"
+ engine = create_engine(f"sqlite:///{db_path}")
+ _run_upgrade_to(engine, "0033")
+ engine.dispose()
+ return db_path
+
+
+def migrated_to_0033_engine(tmp_path, _migrated_to_0033_template):
+ """Per-test isolated database at revision 0033 (the one before 0034)."""
+ db_path = tmp_path / "test_0034.db"
+ shutil.copy2(_migrated_to_0033_template, db_path)
+ engine = create_engine(f"sqlite:///{db_path}")
+ yield engine
+ engine.dispose()
+
+
+class TestMigration0034Upgrade:
+ @pytest.mark.parametrize("key", [BRAVE_KEY, SERPAPI_KEY, TAVILY_KEY])
+ def test_old_default_is_migrated_to_inherit(
+ self, migrated_to_0033_engine, key
+ ):
+ engine = migrated_to_0033_engine
+ _seed_setting(engine, key, OLD_DEFAULTS[key])
+
+ _run_upgrade_to(engine, "0034")
+
+ assert _read_setting(engine, key) == "inherit"
+
+ @pytest.mark.parametrize(
+ ("key", "explicit_value"),
+ [
+ # Values that differ from each engine's own old default must
+ # survive — including the OTHER engines' defaults.
+ (BRAVE_KEY, "d"),
+ (BRAVE_KEY, "w"),
+ (BRAVE_KEY, "all"),
+ (SERPAPI_KEY, "m"),
+ (SERPAPI_KEY, "all"),
+ (TAVILY_KEY, "y"),
+ (TAVILY_KEY, "d"),
+ ],
+ )
+ def test_explicit_choices_are_preserved(
+ self, migrated_to_0033_engine, key, explicit_value
+ ):
+ engine = migrated_to_0033_engine
+ _seed_setting(engine, key, explicit_value)
+
+ _run_upgrade_to(engine, "0034")
+
+ assert _read_setting(engine, key) == explicit_value
+
+ def test_global_time_period_key_is_not_touched(
+ self, migrated_to_0033_engine
+ ):
+ """The global search.time_period holds 'y'-adjacent values too; the
+ per-engine migration must never rewrite it."""
+ engine = migrated_to_0033_engine
+ _seed_setting(engine, "search.time_period", "y")
+
+ _run_upgrade_to(engine, "0034")
+
+ assert _read_setting(engine, "search.time_period") == "y"
+
+ def test_upgrade_is_idempotent(self, migrated_to_0033_engine):
+ engine = migrated_to_0033_engine
+ _seed_setting(engine, SERPAPI_KEY, "y")
+
+ _run_upgrade_to(engine, "0034")
+ _run_upgrade_to(engine, "0034")
+
+ assert _read_setting(engine, SERPAPI_KEY) == "inherit"
+
+ def test_no_rows_does_not_error(self, migrated_to_0033_engine):
+ """A DB without any per-engine rows migrates cleanly (no-op)."""
+ engine = migrated_to_0033_engine
+
+ _run_upgrade_to(engine, "0034")
+
+ for key in OLD_DEFAULTS:
+ assert _read_setting(engine, key) is None
+
+ def test_upgrade_refreshes_select_metadata(self, migrated_to_0033_engine):
+ """The migration itself sets ui_element/options for the three keys:
+ the defaults-JSON reconciliation only runs on a version bump, so
+ without this a user upgrading between bumps would see a text box
+ containing the literal string 'inherit' (#5588 review)."""
+ engine = migrated_to_0033_engine
+ _seed_setting(engine, BRAVE_KEY, "y", ui_element="text", options=None)
+
+ _run_upgrade_to(engine, "0034")
+
+ ui_element, options = _read_metadata(engine, BRAVE_KEY)
+ assert ui_element == "select"
+ assert [o["value"] for o in options] == [
+ "inherit",
+ "d",
+ "w",
+ "m",
+ "y",
+ "all",
+ ]
+ assert options[0]["label"] == "Use global default"
+
+ def test_metadata_refresh_applies_even_to_explicit_values(
+ self, migrated_to_0033_engine
+ ):
+ """Metadata is refreshed unconditionally — a row with an explicit
+ (preserved) value still becomes a proper select."""
+ engine = migrated_to_0033_engine
+ _seed_setting(engine, SERPAPI_KEY, "d", ui_element="text", options=None)
+
+ _run_upgrade_to(engine, "0034")
+
+ assert _read_setting(engine, SERPAPI_KEY) == "d"
+ ui_element, options = _read_metadata(engine, SERPAPI_KEY)
+ assert ui_element == "select"
+ assert len(options) == 6
+
+ @pytest.mark.parametrize(
+ ("stored", "brave", "serpapi", "tavily"), LEGACY_VALUES
+ )
+ def test_legacy_value_becomes_a_valid_choice(
+ self, migrated_to_0033_engine, stored, brave, serpapi, tavily
+ ):
+ """Brave and SerpAPI were free-text fields, so a row can hold any
+ JSON value. Each ends up as a choice the strict resolver accepts:
+ variants are canonicalized and anything unrecognised becomes what it
+ effectively meant on main (Brave: unfiltered; SerpAPI and Tavily:
+ shadowed by the global setting)."""
+ engine = migrated_to_0033_engine
+ for name, key in ENGINE_KEYS.items():
+ _seed_setting(
+ engine,
+ key,
+ stored,
+ ui_element="select" if name == "tavily" else "text",
+ )
+
+ _run_upgrade_to(engine, "0034")
+
+ assert [_read_setting(engine, key) for key in ENGINE_KEYS.values()] == [
+ brave,
+ serpapi,
+ tavily,
+ ]
+
+ @pytest.mark.parametrize(
+ ("key", "expected"),
+ [
+ (BRAVE_KEY, "all"),
+ (SERPAPI_KEY, "inherit"),
+ (TAVILY_KEY, "inherit"),
+ ],
+ )
+ def test_sql_null_cell_is_treated_like_json_null(
+ self, migrated_to_0033_engine, key, expected
+ ):
+ engine = migrated_to_0033_engine
+ _seed_raw(engine, key, None)
+
+ _run_upgrade_to(engine, "0034")
+
+ assert _read_setting(engine, key) == expected
+
+ def test_blob_cell_holding_json_is_migrated(self, migrated_to_0033_engine):
+ """Some drivers hand TEXT back as bytes; the cell is still JSON."""
+ engine = migrated_to_0033_engine
+ _seed_raw(engine, BRAVE_KEY, b'"year"')
+
+ _run_upgrade_to(engine, "0034")
+
+ assert _read_setting(engine, BRAVE_KEY) == "all"
+
+ def test_undecodable_blob_cell_is_left_alone(self, migrated_to_0033_engine):
+ engine = migrated_to_0033_engine
+ _seed_raw(engine, BRAVE_KEY, b"\xff\xfe")
+
+ _run_upgrade_to(engine, "0034")
+
+ assert _read_raw(engine, BRAVE_KEY) == b"\xff\xfe"
+
+ def test_other_engines_time_period_vocabulary_is_not_touched(
+ self, migrated_to_0033_engine
+ ):
+ """Serper's per-engine time_period (day/week/month/year or null) is a
+ different vocabulary outside this scheme and must pass through."""
+ engine = migrated_to_0033_engine
+ serper_key = "search.engine.web.serper.default_params.time_period"
+ _seed_setting(engine, serper_key, "day", ui_element="select")
+
+ _run_upgrade_to(engine, "0034")
+
+ assert _read_setting(engine, serper_key) == "day"
+
+ @pytest.mark.parametrize("stored", ["inherit", "Inherit", " INHERIT "])
+ def test_brave_text_inherit_is_unrecognized_text_not_the_sentinel(
+ self, migrated_to_0033_engine, stored
+ ):
+ """Brave's old free-text field never knew the sentinel and ignored a
+ typed "inherit" (unfiltered, the global setting never applied), so the
+ migration writes "all" for it. SerpAPI and Tavily, whose value the
+ global setting shadowed, keep "inherit"."""
+ engine = migrated_to_0033_engine
+ for name, key in ENGINE_KEYS.items():
+ _seed_setting(
+ engine,
+ key,
+ stored,
+ ui_element="select" if name == "tavily" else "text",
+ )
+
+ _run_upgrade_to(engine, "0034")
+
+ assert _read_setting(engine, BRAVE_KEY) == "all"
+ assert _read_setting(engine, SERPAPI_KEY) == "inherit"
+ assert _read_setting(engine, TAVILY_KEY) == "inherit"
+
+ @pytest.mark.parametrize("stored", UNRECOGNIZED_VALUES)
+ def test_unrecognized_values_keep_their_effective_period(
+ self, migrated_to_0033_engine, monkeypatch, stored
+ ):
+ """With a global of "d", Brave searched unfiltered (it ignored both
+ the stored value and the global setting) while SerpAPI and Tavily
+ followed the global one (it shadowed their stored value). The
+ migrated rows resolve to the same periods instead of raising."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ _resolve_time_period,
+ )
+
+ monkeypatch.delenv("LDR_SEARCH_TIME_PERIOD", raising=False)
+ engine = migrated_to_0033_engine
+ for name, key in ENGINE_KEYS.items():
+ monkeypatch.delenv(
+ f"LDR_SEARCH_ENGINE_WEB_{name.upper()}_DEFAULT_PARAMS_TIME_PERIOD",
+ raising=False,
+ )
+ _seed_setting(engine, key, stored, ui_element="text")
+
+ _run_upgrade_to(engine, "0034")
+
+ periods = {
+ name: _resolve_time_period(
+ name,
+ {"default_params": {"time_period": _read_setting(engine, key)}},
+ {"search.time_period": "d"},
+ {},
+ )
+ for name, key in ENGINE_KEYS.items()
+ }
+ assert periods == {"brave": "all", "serpapi": "d", "tavily": "d"}
+
+ def test_legacy_blank_migration_is_idempotent(
+ self, migrated_to_0033_engine
+ ):
+ engine = migrated_to_0033_engine
+ _seed_setting(engine, BRAVE_KEY, "")
+
+ _run_upgrade_to(engine, "0034")
+ _run_upgrade_to(engine, "0034")
+
+ assert _read_setting(engine, BRAVE_KEY) == "all"
+
+ def test_malformed_value_is_left_alone(self, migrated_to_0033_engine):
+ """A cell that is not valid JSON (here the bare text ``y``) must not
+ be rewritten (same safe-no-op posture as migration 0030)."""
+ engine = migrated_to_0033_engine
+ with engine.begin() as conn:
+ conn.execute(
+ text(
+ "INSERT INTO settings "
+ "(key, value, type, name, ui_element, visible, editable) "
+ "VALUES (:key, 'y', 'search', 'period', 'select', 1, 1)"
+ ),
+ {"key": BRAVE_KEY},
+ )
+
+ _run_upgrade_to(engine, "0034")
+
+ with engine.begin() as conn:
+ row = conn.execute(
+ text("SELECT value FROM settings WHERE key = :key"),
+ {"key": BRAVE_KEY},
+ ).fetchone()
+ assert row[0] == "y" # bare bytes untouched
+
+
+class TestMigration0034Downgrade:
+ @pytest.mark.parametrize("key", [BRAVE_KEY, SERPAPI_KEY, TAVILY_KEY])
+ def test_downgrade_reverts_inherit_to_old_default(
+ self, migrated_to_0033_engine, key
+ ):
+ engine = migrated_to_0033_engine
+ _seed_setting(engine, key, OLD_DEFAULTS[key])
+
+ _run_upgrade_to(engine, "0034")
+ _run_downgrade_to(engine, "0033")
+
+ assert _read_setting(engine, key) == OLD_DEFAULTS[key]
+
+ def test_downgrade_preserves_explicit_choices(
+ self, migrated_to_0033_engine
+ ):
+ engine = migrated_to_0033_engine
+ _seed_setting(engine, BRAVE_KEY, "d")
+
+ _run_upgrade_to(engine, "0034")
+ _run_downgrade_to(engine, "0033")
+
+ assert _read_setting(engine, BRAVE_KEY) == "d"
+
+ def test_downgrade_reverts_brave_all_to_blank(
+ self, migrated_to_0033_engine
+ ):
+ """The upgrade writes "all" for the values Brave ignored; the old
+ free-text field had no distinct "all", so downgrade restores the
+ blank text that meant no filter."""
+ engine = migrated_to_0033_engine
+ _seed_setting(engine, BRAVE_KEY, "year", ui_element="text")
+
+ _run_upgrade_to(engine, "0034")
+ assert _read_setting(engine, BRAVE_KEY) == "all"
+ _run_downgrade_to(engine, "0033")
+
+ assert _read_setting(engine, BRAVE_KEY) == ""
+
+ @pytest.mark.parametrize("key", [SERPAPI_KEY, TAVILY_KEY])
+ def test_downgrade_keeps_all_for_serpapi_and_tavily(
+ self, migrated_to_0033_engine, key
+ ):
+ """ "all" was a documented choice for these two before, and the
+ upgrade never invents it for them, so downgrade leaves it alone."""
+ engine = migrated_to_0033_engine
+ _seed_setting(engine, key, " All ")
+
+ _run_upgrade_to(engine, "0034")
+ _run_downgrade_to(engine, "0033")
+
+ assert _read_setting(engine, key) == "all"
+
+ def test_downgrade_sends_unrecognized_serpapi_value_to_old_default(
+ self, migrated_to_0033_engine
+ ):
+ engine = migrated_to_0033_engine
+ _seed_setting(engine, SERPAPI_KEY, "year", ui_element="text")
+
+ _run_upgrade_to(engine, "0034")
+ assert _read_setting(engine, SERPAPI_KEY) == "inherit"
+ _run_downgrade_to(engine, "0033")
+
+ assert _read_setting(engine, SERPAPI_KEY) == "y"
+
+ def test_downgrade_restores_old_metadata(self, migrated_to_0033_engine):
+ """Downgrade reverts metadata to the pre-upgrade shapes: text/no
+ options for brave/serpapi, the old five-option select for tavily."""
+ engine = migrated_to_0033_engine
+ _seed_setting(engine, BRAVE_KEY, "y", ui_element="text", options=None)
+ _seed_setting(
+ engine, TAVILY_KEY, "all", ui_element="select", options=None
+ )
+
+ _run_upgrade_to(engine, "0034")
+ _run_downgrade_to(engine, "0033")
+
+ brave_ui, brave_options = _read_metadata(engine, BRAVE_KEY)
+ assert brave_ui == "text"
+ assert brave_options is None
+
+ tavily_ui, tavily_options = _read_metadata(engine, TAVILY_KEY)
+ assert tavily_ui == "select"
+ assert [o["value"] for o in tavily_options] == [
+ "d",
+ "w",
+ "m",
+ "y",
+ "all",
+ ]
+
+
+class TestMigration0034HeadAlignment:
+ """Chain-anchoring guard; deliberately no literal head pin (see the
+ rationale in test_migration_0030_default_time_period_all.py)."""
+
+ def test_0034_chains_correctly_to_0033(self):
+ from alembic.config import Config
+ from alembic.script import ScriptDirectory
+
+ from local_deep_research.database.alembic_runner import (
+ get_migrations_dir,
+ )
+
+ config = Config()
+ config.set_main_option("script_location", str(get_migrations_dir()))
+ script = ScriptDirectory.from_config(config)
+ rev_0034 = script.get_revision("0034")
+ assert rev_0034.down_revision == "0033"
+
+
+def _load_migration_0034_module():
+ """Import the 0034 migration module by path (its name starts with a digit,
+ so it can't be imported normally) to read its module-level constants."""
+ import importlib.util
+ from pathlib import Path
+
+ path = (
+ Path(__file__).resolve().parents[2]
+ / "src/local_deep_research/database/migrations/versions"
+ / "0034_per_engine_time_period_inherit.py"
+ )
+ spec = importlib.util.spec_from_file_location("_migration_0034", path)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+class TestMigrationConstantsMatchDefaults:
+ """Guard against silent drift between the migration's hardcoded select
+ options and defaults/default_settings.json — the two are hand-mirrored, so
+ a change to one that misses the other would ship a broken dropdown."""
+
+ def test_new_options_json_matches_default_settings(self):
+ from pathlib import Path
+
+ mig = _load_migration_0034_module()
+ new_options = json.loads(mig.NEW_OPTIONS_JSON)
+
+ defaults = json.loads(
+ (
+ Path(__file__).resolve().parents[2]
+ / "src/local_deep_research/defaults/default_settings.json"
+ ).read_text()
+ )
+ for engine in ("brave", "serpapi", "tavily"):
+ key = f"search.engine.web.{engine}.default_params.time_period"
+ assert new_options == defaults[key]["options"], (
+ f"migration 0034 NEW_OPTIONS_JSON drifted from "
+ f"default_settings.json for {key}"
+ )
diff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.json
index 567a7f31c5..6eb8680cd2 100644
--- a/tests/settings/golden_master_settings.json
+++ b/tests/settings/golden_master_settings.json
@@ -3218,16 +3218,41 @@
},
"search.engine.web.brave.default_params.time_period": {
"category": "brave",
- "description": "Time range filter for Brave results (e.g., 'd' for day, 'w' for week, 'm' for month, 'y' for year).",
+ "description": "Time range filter for Brave results. 'Use global default' follows Settings → Search → Time Period; a specific value here overrides that saved global setting for this engine ('all' = no filter). When the LDR_SEARCH_TIME_PERIOD environment variable is set it takes precedence over a value saved here, and this engine's own environment variable takes precedence over both.",
"editable": true,
"max_value": null,
"min_value": null,
"name": "Time Period",
- "options": null,
+ "options": [
+ {
+ "label": "Use global default",
+ "value": "inherit"
+ },
+ {
+ "label": "Past 24 hours",
+ "value": "d"
+ },
+ {
+ "label": "Past week",
+ "value": "w"
+ },
+ {
+ "label": "Past month",
+ "value": "m"
+ },
+ {
+ "label": "Past year",
+ "value": "y"
+ },
+ {
+ "label": "All time",
+ "value": "all"
+ }
+ ],
"step": null,
"type": "SEARCH",
- "ui_element": "text",
- "value": "y",
+ "ui_element": "select",
+ "value": "inherit",
"visible": true
},
"search.engine.web.brave.description": {
@@ -7122,16 +7147,41 @@
},
"search.engine.web.serpapi.default_params.time_period": {
"category": "serpapi",
- "description": "Time range filter for SerpAPI results: 'd' (day), 'w' (week), 'm' (month), 'y' (year), or 'all' (no filter). Overridden by the global Search → Time Period setting whenever that is set (the normal case); applies only to programmatic snapshots without it.",
+ "description": "Time range filter for SerpAPI results. 'Use global default' follows Settings → Search → Time Period; a specific value here overrides that saved global setting for this engine ('all' = no filter). When the LDR_SEARCH_TIME_PERIOD environment variable is set it takes precedence over a value saved here, and this engine's own environment variable takes precedence over both.",
"editable": true,
"max_value": null,
"min_value": null,
"name": "Time Period",
- "options": null,
+ "options": [
+ {
+ "label": "Use global default",
+ "value": "inherit"
+ },
+ {
+ "label": "Past 24 hours",
+ "value": "d"
+ },
+ {
+ "label": "Past week",
+ "value": "w"
+ },
+ {
+ "label": "Past month",
+ "value": "m"
+ },
+ {
+ "label": "Past year",
+ "value": "y"
+ },
+ {
+ "label": "All time",
+ "value": "all"
+ }
+ ],
"step": null,
"type": "SEARCH",
- "ui_element": "text",
- "value": "y",
+ "ui_element": "select",
+ "value": "inherit",
"visible": true
},
"search.engine.web.serpapi.description": {
@@ -8150,12 +8200,16 @@
},
"search.engine.web.tavily.default_params.time_period": {
"category": "tavily",
- "description": "Time range filter for Tavily results: 'd' (day), 'w' (week), 'm' (month), 'y' (year), or 'all' (no filter). Overridden by the global Search → Time Period setting whenever that is set (the normal case); applies only to programmatic snapshots without it.",
+ "description": "Time range filter for Tavily results. 'Use global default' follows Settings → Search → Time Period; a specific value here overrides that saved global setting for this engine ('all' = no filter). When the LDR_SEARCH_TIME_PERIOD environment variable is set it takes precedence over a value saved here, and this engine's own environment variable takes precedence over both.",
"editable": true,
"max_value": null,
"min_value": null,
"name": "Time Period",
"options": [
+ {
+ "label": "Use global default",
+ "value": "inherit"
+ },
{
"label": "Past 24 hours",
"value": "d"
@@ -8180,7 +8234,7 @@
"step": null,
"type": "SEARCH",
"ui_element": "select",
- "value": "all",
+ "value": "inherit",
"visible": true
},
"search.engine.web.tavily.description": {
diff --git a/tests/web/services/test_research_service_search_limit_precedence.py b/tests/web/services/test_research_service_search_limit_precedence.py
index 94bcda132e..2404fbc32a 100644
--- a/tests/web/services/test_research_service_search_limit_precedence.py
+++ b/tests/web/services/test_research_service_search_limit_precedence.py
@@ -38,6 +38,7 @@ def _dispatch_search_limits(
"search.tool": "searxng",
"search.max_results": 7,
"search.time_period": "y",
+ "search.engine.web.serpapi.default_params.time_period": "y",
}
effective = {
"llm.provider": "openai_endpoint",
@@ -46,6 +47,7 @@ def _dispatch_search_limits(
"search.tool": "searxng",
"search.max_results": 13,
"search.time_period": "m",
+ "search.engine.web.serpapi.default_params.time_period": "y",
}
search_factory = MagicMock(return_value=MagicMock())
system = MagicMock()
@@ -98,13 +100,26 @@ def test_explicit_search_limits_override_effective_snapshot_at_consumer():
# When: the worker dispatches the run with explicit limits.
search_factory, system_cls = _dispatch_search_limits(limits)
- # Then: the real search consumer and system snapshot use explicit limits.
+ # Then: the snapshot carries the explicit limits; time_period is NOT
+ # forwarded as a kwarg (create_search_engine resolves it from the
+ # snapshot since #5587), and the per-request override resets per-engine
+ # time_period choices to "inherit" so it wins for this run.
search_factory.assert_called_once()
assert search_factory.call_args.kwargs["max_results"] == 19
- assert search_factory.call_args.kwargs["time_period"] == "w"
+ assert "time_period" not in search_factory.call_args.kwargs
+ factory_snapshot = search_factory.call_args.kwargs["settings_snapshot"]
+ assert factory_snapshot["search.time_period"] == "w"
+ assert (
+ factory_snapshot["search.engine.web.serpapi.default_params.time_period"]
+ == "inherit"
+ )
system_snapshot = system_cls.call_args.kwargs["settings_snapshot"]
assert system_snapshot["search.max_results"] == 19
assert system_snapshot["search.time_period"] == "w"
+ assert (
+ system_snapshot["search.engine.web.serpapi.default_params.time_period"]
+ == "inherit"
+ )
def test_omitted_search_limits_preserve_effective_snapshot():
@@ -117,7 +132,14 @@ def test_omitted_search_limits_preserve_effective_snapshot():
# Then: the real search consumer and system snapshot use 13 and "m".
search_factory.assert_called_once()
assert search_factory.call_args.kwargs["max_results"] == 13
- assert search_factory.call_args.kwargs["time_period"] == "m"
+ assert "time_period" not in search_factory.call_args.kwargs
+ factory_snapshot = search_factory.call_args.kwargs["settings_snapshot"]
+ assert factory_snapshot["search.time_period"] == "m"
+ # No per-request override: the per-engine choice is left untouched.
+ assert (
+ factory_snapshot["search.engine.web.serpapi.default_params.time_period"]
+ == "y"
+ )
system_snapshot = system_cls.call_args.kwargs["settings_snapshot"]
assert system_snapshot["search.max_results"] == 13
assert system_snapshot["search.time_period"] == "m"
@@ -133,7 +155,14 @@ def test_none_search_limits_preserve_effective_snapshot():
# Then: the real search consumer and system snapshot use 13 and "m".
search_factory.assert_called_once()
assert search_factory.call_args.kwargs["max_results"] == 13
- assert search_factory.call_args.kwargs["time_period"] == "m"
+ assert "time_period" not in search_factory.call_args.kwargs
+ factory_snapshot = search_factory.call_args.kwargs["settings_snapshot"]
+ assert factory_snapshot["search.time_period"] == "m"
+ # No per-request override: the per-engine choice is left untouched.
+ assert (
+ factory_snapshot["search.engine.web.serpapi.default_params.time_period"]
+ == "y"
+ )
system_snapshot = system_cls.call_args.kwargs["settings_snapshot"]
assert system_snapshot["search.max_results"] == 13
assert system_snapshot["search.time_period"] == "m"
diff --git a/tests/web_search_engines/engines/test_search_engine_brave.py b/tests/web_search_engines/engines/test_search_engine_brave.py
index 592990af0d..6f6fc44006 100644
--- a/tests/web_search_engines/engines/test_search_engine_brave.py
+++ b/tests/web_search_engines/engines/test_search_engine_brave.py
@@ -164,7 +164,7 @@ class TestBraveSearchEngineInit:
@pytest.mark.parametrize(
"bad_value",
- ["garbage", "year", "D", "", None, {"a": 1}, ["y"], 7, True],
+ ["garbage", "year", "inherit", "D", "", None, {"a": 1}, ["y"], 7, True],
)
def test_init_with_unrecognized_time_period_omits_freshness(
self, bad_value
diff --git a/tests/web_search_engines/engines/test_search_engine_serpapi.py b/tests/web_search_engines/engines/test_search_engine_serpapi.py
index bbf879ce20..d01ee9beae 100644
--- a/tests/web_search_engines/engines/test_search_engine_serpapi.py
+++ b/tests/web_search_engines/engines/test_search_engine_serpapi.py
@@ -94,7 +94,7 @@ class TestSerpAPISearchEngineInit:
@pytest.mark.parametrize(
"bad_value",
- ["garbage", "year", "D", "", None, {"a": 1}, ["y"], 7, True],
+ ["garbage", "year", "inherit", "D", "", None, {"a": 1}, ["y"], 7, True],
)
def test_init_with_unrecognized_time_period_omits_tbs(self, bad_value):
"""Unrecognized or non-string time_period values omit tbs (no filter).
diff --git a/tests/web_search_engines/engines/test_search_engine_tavily.py b/tests/web_search_engines/engines/test_search_engine_tavily.py
index 4c7c4d80bd..464b5a850e 100644
--- a/tests/web_search_engines/engines/test_search_engine_tavily.py
+++ b/tests/web_search_engines/engines/test_search_engine_tavily.py
@@ -616,7 +616,7 @@ class TestTimePeriod:
assert "time_range" not in payload
@pytest.mark.parametrize(
- "bad_value", [None, "", "garbage", "D", "Year", "y ", " y"]
+ "bad_value", [None, "", "garbage", "inherit", "D", "Year", "y ", " y"]
)
def test_get_previews_unrecognized_time_period_omits_time_range(
self, bad_value
diff --git a/tests/web_search_engines/engines/test_search_engine_wikinews.py b/tests/web_search_engines/engines/test_search_engine_wikinews.py
index 7dfbd76e18..6fcd4d09fd 100644
--- a/tests/web_search_engines/engines/test_search_engine_wikinews.py
+++ b/tests/web_search_engines/engines/test_search_engine_wikinews.py
@@ -13,6 +13,8 @@ Tests cover:
from datetime import datetime, timedelta, UTC
from unittest.mock import Mock, patch
+import pytest
+
class TestWikinewsSearchEngineInit:
"""Tests for WikinewsSearchEngine initialization."""
@@ -84,6 +86,22 @@ class TestWikinewsSearchEngineInit:
expected_from = datetime.now(UTC) - timedelta(days=7)
assert abs((engine.from_date - expected_from).total_seconds()) < 60
+ @pytest.mark.parametrize("value", ["all", "inherit", "garbage", "Y", ""])
+ def test_init_with_all_or_unrecognized_time_period_applies_no_filter(
+ self, value
+ ):
+ """ "all" and any unrecognized value must apply NO lower date bound
+ (from_date == datetime.min), never silently fall back to a one-year
+ window — mirrors the brave/serpapi/tavily "bad value → no filter"
+ contract that this engine's siblings already assert."""
+ from local_deep_research.web_search_engines.engines.search_engine_wikinews import (
+ WikinewsSearchEngine,
+ )
+
+ engine = WikinewsSearchEngine(time_period=value)
+
+ assert engine.from_date == datetime.min.replace(tzinfo=UTC)
+
def test_init_with_adaptive_search_disabled(self):
"""Initialize with adaptive_search disabled."""
from local_deep_research.web_search_engines.engines.search_engine_wikinews import (
diff --git a/tests/web_search_engines/test_search_engine_factory_coverage.py b/tests/web_search_engines/test_search_engine_factory_coverage.py
index 13d7a64a70..ae2d063c5d 100644
--- a/tests/web_search_engines/test_search_engine_factory_coverage.py
+++ b/tests/web_search_engines/test_search_engine_factory_coverage.py
@@ -486,9 +486,10 @@ class TestTimePeriodSnapshotFallback:
assert EngCls._call_kwargs["time_period"] == "w"
- def test_snapshot_beats_per_engine_default_params(self):
- """The global setting wins over default_params, matching get_search()'s
- precedence on the forwarding path."""
+ def test_per_engine_value_beats_snapshot(self):
+ """An explicit (non-inherit) per-engine default_params.time_period
+ overrides the global setting — the point of #5587's inherit design:
+ a user who deliberately set the per-engine field wins."""
from local_deep_research.web_search_engines.search_engine_factory import (
create_search_engine,
)
@@ -498,7 +499,28 @@ class TestTimePeriodSnapshotFallback:
with _patches(
config_return={
- "tavily": _engine_config(default_params={"time_period": "all"})
+ "tavily": _engine_config(default_params={"time_period": "y"})
+ },
+ class_return=EngCls,
+ ):
+ create_search_engine("tavily", settings_snapshot=snapshot)
+
+ assert EngCls._call_kwargs["time_period"] == "y"
+
+ def test_per_engine_inherit_falls_back_to_snapshot(self):
+ """The "inherit" sentinel means "use the global setting"."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class("max_results", "time_period")
+ snapshot = {"search.time_period": {"value": "d"}}
+
+ with _patches(
+ config_return={
+ "tavily": _engine_config(
+ default_params={"time_period": "inherit"}
+ )
},
class_return=EngCls,
):
@@ -506,9 +528,56 @@ class TestTimePeriodSnapshotFallback:
assert EngCls._call_kwargs["time_period"] == "d"
- def test_non_forwarding_engine_not_injected(self):
- """Engines outside TIME_PERIOD_ENGINES (e.g. brave, governed by its
- per-engine default_params) don't get the global value injected."""
+ def test_inherit_falls_back_to_all_when_no_global_setting(self):
+ """ "inherit" must never reach an engine: with no global setting in the
+ snapshot the factory falls back to "all" (no filter), NOT the engine's
+ class default — brave/serpapi default to a restrictive "y", which would
+ silently re-pin them to Past-year in this corner."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class("max_results", "time_period")
+ snapshot = {"dummy": "value"}
+
+ with _patches(
+ config_return={
+ "tavily": _engine_config(
+ default_params={"time_period": "inherit"}
+ )
+ },
+ class_return=EngCls,
+ ):
+ create_search_engine("tavily", settings_snapshot=snapshot)
+
+ assert EngCls._call_kwargs["time_period"] == "all"
+
+ def test_explicit_kwarg_beats_per_engine_value(self):
+ """An explicit caller kwarg outranks even a non-inherit per-engine
+ value (top of the precedence chain)."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class("max_results", "time_period")
+
+ with _patches(
+ config_return={
+ "tavily": _engine_config(default_params={"time_period": "y"})
+ },
+ class_return=EngCls,
+ ):
+ create_search_engine(
+ "tavily",
+ settings_snapshot={"search.time_period": {"value": "d"}},
+ time_period="w",
+ )
+
+ assert EngCls._call_kwargs["time_period"] == "w"
+
+ def test_brave_receives_global_setting(self):
+ """Brave is in TIME_PERIOD_ENGINES since #5587: with no per-engine
+ override it follows the global setting like the other engines."""
from local_deep_research.web_search_engines.search_engine_factory import (
create_search_engine,
)
@@ -522,11 +591,416 @@ class TestTimePeriodSnapshotFallback:
):
create_search_engine("brave", settings_snapshot=snapshot)
+ assert EngCls._call_kwargs["time_period"] == "d"
+
+ def test_non_forwarding_engine_not_injected(self):
+ """Engines outside TIME_PERIOD_ENGINES never get the global value
+ injected."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class("max_results", "time_period")
+ snapshot = {"search.time_period": {"value": "d"}}
+
+ with _patches(
+ config_return={"myeng": _engine_config()},
+ class_return=EngCls,
+ ):
+ create_search_engine("myeng", settings_snapshot=snapshot)
+
assert "time_period" not in EngCls._call_kwargs
- def test_no_snapshot_key_leaves_constructor_default(self):
- """Without search.time_period in the snapshot, nothing is injected and
- the engine's own constructor default applies."""
+ @pytest.mark.parametrize("junk", ["Y", " y", "7", "", None, 7, ["d"]])
+ def test_invalid_per_engine_value_raises_instead_of_selecting_global(
+ self, junk
+ ):
+ """Malformed per-engine choices fail; only explicit inherit uses global."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class("max_results", "time_period")
+ snapshot = {"search.time_period": {"value": "d"}}
+
+ with _patches(
+ config_return={
+ "tavily": _engine_config(default_params={"time_period": junk})
+ },
+ class_return=EngCls,
+ ):
+ with pytest.raises(
+ ValueError, match="tavily.default_params.time_period"
+ ):
+ create_search_engine("tavily", settings_snapshot=snapshot)
+
+ assert EngCls._call_kwargs is None
+
+ @pytest.mark.parametrize("junk", ["Y", "garbage", "", None, 7])
+ def test_invalid_per_engine_value_without_global_raises(self, junk):
+ """A missing global value cannot legitimize a malformed per-engine choice."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class("max_results", "time_period")
+ snapshot = {"dummy": "value"}
+
+ with _patches(
+ config_return={
+ "tavily": _engine_config(default_params={"time_period": junk})
+ },
+ class_return=EngCls,
+ ):
+ with pytest.raises(
+ ValueError, match="tavily.default_params.time_period"
+ ):
+ create_search_engine("tavily", settings_snapshot=snapshot)
+
+ assert EngCls._call_kwargs is None
+
+ def test_explicit_inherit_kwarg_resolves_to_global(self):
+ """An explicit time_period="inherit" kwarg means "resolve normally"
+ — identical to omitting the kwarg, so the global setting applies."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class("max_results", "time_period")
+ snapshot = {"search.time_period": {"value": "d"}}
+
+ with _patches(
+ config_return={"tavily": _engine_config()},
+ class_return=EngCls,
+ ):
+ create_search_engine(
+ "tavily", settings_snapshot=snapshot, time_period="inherit"
+ )
+
+ assert EngCls._call_kwargs["time_period"] == "d"
+
+ def test_corrupted_global_value_raises(self):
+ """Global inherit/junk is invalid rather than an unrestricted search."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class("max_results", "time_period")
+ snapshot = {"search.time_period": {"value": "inherit"}}
+
+ with _patches(
+ config_return={"tavily": _engine_config()},
+ class_return=EngCls,
+ ):
+ with pytest.raises(ValueError, match="search.time_period"):
+ create_search_engine("tavily", settings_snapshot=snapshot)
+
+ assert EngCls._call_kwargs is None
+
+ @pytest.mark.parametrize("engine", ["tavily", "serpapi", "brave"])
+ def test_wrapped_null_global_falls_back_to_all(self, engine):
+ """A stored global row with no value (a metadata-wrapped null, the
+ shape of a database-backed snapshot) means "not set": it falls back to
+ the documented "all" default, as it did before inherit semantics,
+ rather than failing every search."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class("max_results", "time_period")
+ snapshot = {
+ "search.time_period": {"value": None, "ui_element": "select"}
+ }
+
+ with _patches(
+ config_return={engine: _engine_config()},
+ class_return=EngCls,
+ ):
+ create_search_engine(engine, settings_snapshot=snapshot)
+
+ assert EngCls._call_kwargs["time_period"] == "all"
+
+ def test_bare_none_global_falls_back_to_all(self):
+ """A stored null reaches the resolver as a bare None once
+ SettingsManager.get_settings_snapshot() unwraps the entry (REST
+ /api/v1, scheduled news runs). It means "not set" there exactly as the
+ wrapped {"value": None} does, so it falls back to "all"."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class("max_results", "time_period")
+
+ with _patches(
+ config_return={"tavily": _engine_config()},
+ class_return=EngCls,
+ ):
+ create_search_engine(
+ "tavily", settings_snapshot={"search.time_period": None}
+ )
+
+ assert EngCls._call_kwargs["time_period"] == "all"
+
+ def test_brave_absent_global_falls_back_to_all_not_class_default(self):
+ """Finding A: with the global setting ABSENT from the snapshot (a
+ partial/programmatic snapshot), Brave — whose class default is a
+ restrictive "y" (Past Year) — must fall back to "all" (no filter), not
+ silently re-pin to a one-year window."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class("max_results", "time_period")
+ with _patches(
+ config_return={"brave": _engine_config()},
+ class_return=EngCls,
+ ):
+ create_search_engine("brave", settings_snapshot={"dummy": "v"})
+
+ assert EngCls._call_kwargs["time_period"] == "all"
+
+ def test_serpapi_invalid_global_raises_before_construction(self):
+ """An invalid operator global value fails instead of changing the filter."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class("max_results", "time_period")
+ snapshot = {"search.time_period": "not-a-valid-period"}
+ with _patches(
+ config_return={"serpapi": _engine_config()},
+ class_return=EngCls,
+ ):
+ with pytest.raises(ValueError, match="search.time_period"):
+ create_search_engine("serpapi", settings_snapshot=snapshot)
+
+ assert EngCls._call_kwargs is None
+
+ def test_null_default_params_does_not_crash(self):
+ """A config row whose default_params is JSON null (None) must not crash
+ the merge (``{**None}`` -> TypeError); None is treated as empty and the
+ engine is still created with the resolved global time_period."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class("max_results", "time_period")
+ with _patches(
+ config_return={"tavily": _engine_config(default_params=None)},
+ class_return=EngCls,
+ ):
+ result = create_search_engine(
+ "tavily",
+ settings_snapshot={"search.time_period": {"value": "w"}},
+ )
+
+ assert result is not None
+ assert EngCls._call_kwargs["time_period"] == "w"
+
+
+class TestApplyTimePeriodOverride:
+ """apply_time_period_override(): the per-request override helper used by
+ run_research_process — must beat per-engine choices for that run."""
+
+ def test_sets_global_and_resets_present_per_engine_keys(self):
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ apply_time_period_override,
+ )
+
+ snapshot = {
+ "search.time_period": {"value": "all"},
+ "search.engine.web.serpapi.default_params.time_period": {
+ "value": "y"
+ },
+ "search.engine.web.tavily.default_params.time_period": "all",
+ "unrelated.key": {"value": "x"},
+ }
+
+ apply_time_period_override(snapshot, "d")
+
+ assert snapshot["search.time_period"] == {"value": "d"}
+ assert snapshot[
+ "search.engine.web.serpapi.default_params.time_period"
+ ] == {"value": "inherit"}
+ assert (
+ snapshot["search.engine.web.tavily.default_params.time_period"]
+ == "inherit"
+ )
+ assert snapshot["unrelated.key"] == {"value": "x"}
+
+ @pytest.mark.parametrize("wrapped", [True, False])
+ def test_env_pinned_per_engine_key_is_not_reset_to_inherit(
+ self, monkeypatch, wrapped
+ ):
+ """An LDR_*_DEFAULT_PARAMS_TIME_PERIOD env var is operator policy and
+ must survive a per-request override. The pin is recognized from the
+ environment itself, so raw-valued and metadata-wrapped entries are
+ protected alike; a neighboring key without a pin is still reset."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ apply_time_period_override,
+ )
+
+ monkeypatch.delenv("LDR_SEARCH_TIME_PERIOD", raising=False)
+ monkeypatch.delenv(
+ "LDR_SEARCH_ENGINE_WEB_SERPAPI_DEFAULT_PARAMS_TIME_PERIOD",
+ raising=False,
+ )
+ monkeypatch.setenv(
+ "LDR_SEARCH_ENGINE_WEB_BRAVE_DEFAULT_PARAMS_TIME_PERIOD", "w"
+ )
+ pinned = {"value": "w", "editable": False} if wrapped else "w"
+ saved = {"value": "y", "editable": True} if wrapped else "y"
+ snapshot = {
+ "search.time_period": {"value": "all"},
+ "search.engine.web.brave.default_params.time_period": pinned,
+ "search.engine.web.serpapi.default_params.time_period": saved,
+ }
+
+ apply_time_period_override(snapshot, "d")
+
+ assert snapshot["search.time_period"] == {"value": "d"}
+ # The pinned value survives unchanged, metadata and all.
+ assert (
+ snapshot["search.engine.web.brave.default_params.time_period"]
+ == pinned
+ )
+ # The unpinned per-engine value is reset so the request wins.
+ assert snapshot[
+ "search.engine.web.serpapi.default_params.time_period"
+ ] == ({"value": "inherit", "editable": True} if wrapped else "inherit")
+
+ def test_non_editable_entries_without_an_env_pin_are_still_reset(
+ self, monkeypatch
+ ):
+ """SettingsManager.get_all_settings sets editable=False on every
+ database-backed entry while app.lock_settings is on, and the research
+ start snapshot is taken that way. That marker alone is not an env
+ pin: a per-request period must still replace explicit per-engine
+ choices on a locked installation."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ apply_time_period_override,
+ )
+
+ monkeypatch.delenv("LDR_SEARCH_TIME_PERIOD", raising=False)
+ for engine in ("BRAVE", "SERPAPI", "TAVILY"):
+ monkeypatch.delenv(
+ f"LDR_SEARCH_ENGINE_WEB_{engine}_DEFAULT_PARAMS_TIME_PERIOD",
+ raising=False,
+ )
+ snapshot = {
+ "search.time_period": {"value": "all", "editable": False},
+ "search.engine.web.brave.default_params.time_period": {
+ "value": "w",
+ "editable": False,
+ },
+ "search.engine.web.serpapi.default_params.time_period": {
+ "value": "y",
+ "editable": False,
+ },
+ "search.engine.web.tavily.default_params.time_period": {
+ "value": "m",
+ "editable": False,
+ },
+ }
+
+ apply_time_period_override(snapshot, "d")
+
+ assert snapshot["search.time_period"] == {
+ "value": "d",
+ "editable": False,
+ }
+ for engine in ("brave", "serpapi", "tavily"):
+ assert snapshot[
+ f"search.engine.web.{engine}.default_params.time_period"
+ ] == {"value": "inherit", "editable": False}
+
+ def test_absent_per_engine_keys_stay_absent(self):
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ apply_time_period_override,
+ )
+
+ snapshot = {"search.time_period": "all"}
+
+ apply_time_period_override(snapshot, "w")
+
+ assert snapshot["search.time_period"] == "w"
+ assert (
+ "search.engine.web.brave.default_params.time_period" not in snapshot
+ )
+
+ def test_override_wins_end_to_end_against_per_engine_choice(self):
+ """Full chain: override applied to a snapshot whose per-engine value
+ would otherwise win — the engine must receive the override. The
+ mocked search_config derives default_params from the LIVE snapshot
+ (like the real extraction does), so this genuinely exercises the
+ helper's per-engine reset: without it, the per-engine "y" would win
+ and the assertion below would fail."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ apply_time_period_override,
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class("max_results", "time_period")
+ snapshot = {
+ "search.time_period": {"value": "all"},
+ "search.engine.web.tavily.default_params.time_period": {
+ "value": "y"
+ },
+ }
+ apply_time_period_override(snapshot, "d")
+
+ def _config_from_snapshot(*args, **kw):
+ snap = kw.get("settings_snapshot") or {}
+ per = snap.get(
+ "search.engine.web.tavily.default_params.time_period"
+ )
+ if isinstance(per, dict):
+ per = per.get("value")
+ default_params = {} if per is None else {"time_period": per}
+ return {"tavily": _engine_config(default_params=default_params)}
+
+ with _patches(class_return=EngCls) as (_mock_reg, mock_sc, _mock_gsmc):
+ mock_sc.side_effect = _config_from_snapshot
+ create_search_engine("tavily", settings_snapshot=snapshot)
+
+ assert EngCls._call_kwargs["time_period"] == "d"
+
+ def test_per_engine_choice_wins_without_override_helper(self):
+ """Control for the end-to-end test above: the same snapshot WITHOUT
+ apply_time_period_override applied — the per-engine "y" must win,
+ proving the snapshot-derived config path is live in both tests."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ EngCls = _make_engine_class("max_results", "time_period")
+ snapshot = {
+ "search.time_period": {"value": "d"},
+ "search.engine.web.tavily.default_params.time_period": {
+ "value": "y"
+ },
+ }
+
+ def _config_from_snapshot(*args, **kw):
+ snap = kw.get("settings_snapshot") or {}
+ per = snap.get(
+ "search.engine.web.tavily.default_params.time_period"
+ )
+ if isinstance(per, dict):
+ per = per.get("value")
+ default_params = {} if per is None else {"time_period": per}
+ return {"tavily": _engine_config(default_params=default_params)}
+
+ with _patches(class_return=EngCls) as (_mock_reg, mock_sc, _mock_gsmc):
+ mock_sc.side_effect = _config_from_snapshot
+ create_search_engine("tavily", settings_snapshot=snapshot)
+
+ assert EngCls._call_kwargs["time_period"] == "y"
+
+ def test_no_snapshot_key_falls_back_to_all(self):
+ """Without search.time_period in the snapshot, the factory injects the
+ neutral "all" (no filter) fallback rather than leaving the engine's own
+ constructor default to apply (restrictive "y" for brave/serpapi)."""
from local_deep_research.web_search_engines.search_engine_factory import (
create_search_engine,
)
@@ -540,7 +1014,7 @@ class TestTimePeriodSnapshotFallback:
):
create_search_engine("tavily", settings_snapshot=snapshot)
- assert "time_period" not in EngCls._call_kwargs
+ assert EngCls._call_kwargs["time_period"] == "all"
# ---------------------------------------------------------------------------
@@ -1254,11 +1728,12 @@ class TestGetSearchParameterRouting:
call_kwargs = mock_create.call_args[1]
assert call_kwargs["time_period"] == "w"
- def test_get_search_default_time_period_is_all(self):
- """get_search() function-level default is 'all', matching the engine
- constructor default. Pinning this so a future revert that flips the
- function signature back to 'y' fails loudly — that inconsistency
- silently year-restricts programmatic callers.
+ def test_get_search_default_defers_time_period_resolution(self):
+ """get_search() with no explicit time_period must NOT forward one:
+ forwarding a default here would override per-engine
+ default_params.time_period in create_search_engine()'s resolution
+ (#5587). Pinning this so a future revert to an "all"/"y" signature
+ default fails loudly.
"""
from local_deep_research.web_search_engines.search_engine_factory import (
get_search,
@@ -1276,7 +1751,7 @@ class TestGetSearchParameterRouting:
)
call_kwargs = mock_create.call_args[1]
- assert call_kwargs["time_period"] == "all"
+ assert "time_period" not in call_kwargs
def test_get_search_sofya_params(self):
"""Sofya gets search_snippets_only forwarded: it derives its request
diff --git a/tests/web_search_engines/test_time_period_settings.py b/tests/web_search_engines/test_time_period_settings.py
new file mode 100644
index 0000000000..05903bc1bf
--- /dev/null
+++ b/tests/web_search_engines/test_time_period_settings.py
@@ -0,0 +1,719 @@
+"""Time-period settings must preserve operator policy and reject bad inputs."""
+
+from types import SimpleNamespace
+from unittest.mock import Mock, patch
+
+import pytest
+
+from local_deep_research.config.search_config import get_search
+from local_deep_research.security.egress.policy import Decision
+from local_deep_research.settings.manager import (
+ apply_environment_overrides_to_snapshot,
+)
+from local_deep_research.utilities.type_utils import overlay_runtime_settings
+from local_deep_research.web_search_engines.search_engine_factory import (
+ apply_time_period_override,
+)
+
+
+class CapturingEngine:
+ def __init__(self, time_period="y", max_results=10, **kwargs):
+ self.time_period = time_period
+
+
[email protected]("wrapped", [False, True])
+ (
+ "global_env",
+ "per_engine_env",
+ "request_period",
+ "saved_per_engine",
+ "expected",
+ ),
+ [
+ pytest.param(
+ "w", None, "d", "y", "w", id="global-operator-pin-survives-request"
+ ),
+ pytest.param(
+ "w", None, None, "inherit", "w", id="global-pin-no-request-control"
+ ),
+ pytest.param(None, None, "d", "y", "d", id="unlocked-request-control"),
+ pytest.param(None, "w", "d", "y", "w", id="per-engine-pin-control"),
+ # The same rule without a request (the common case): an operator's
+ # global pin outranks a per-engine choice saved in Settings, and the
+ # engine's own pin outranks the global one, request or not.
+ pytest.param(
+ "w", None, None, "y", "w", id="global-pin-outranks-saved-choice"
+ ),
+ pytest.param(
+ "w", "m", None, "y", "m", id="engine-pin-outranks-global-pin"
+ ),
+ pytest.param(
+ "w", "m", "d", "y", "m", id="engine-pin-outranks-global-pin-request"
+ ),
+ pytest.param(
+ None, None, None, "y", "y", id="saved-choice-without-any-pin"
+ ),
+ ],
+)
+def test_operator_period_dispatch(
+ monkeypatch,
+ global_env,
+ per_engine_env,
+ request_period,
+ saved_per_engine,
+ expected,
+ wrapped,
+):
+ for name, value in [
+ ("LDR_SEARCH_TIME_PERIOD", global_env),
+ (
+ "LDR_SEARCH_ENGINE_WEB_SERPAPI_DEFAULT_PARAMS_TIME_PERIOD",
+ per_engine_env,
+ ),
+ ]:
+ if value is None:
+ monkeypatch.delenv(name, raising=False)
+ else:
+ monkeypatch.setenv(name, value)
+ snapshot = {
+ "search.time_period": {
+ "value": "all",
+ "ui_element": "select",
+ "editable": True,
+ },
+ "search.engine.web.serpapi.default_params.time_period": {
+ "value": saved_per_engine,
+ "ui_element": "select",
+ "editable": True,
+ },
+ "search.engine.library.enabled": False,
+ }
+ if not wrapped:
+ snapshot = {
+ key: value["value"] if isinstance(value, dict) else value
+ for key, value in snapshot.items()
+ }
+ effective = apply_environment_overrides_to_snapshot(snapshot)
+ overlay_runtime_settings(effective, time_period=request_period)
+ if request_period is not None:
+ apply_time_period_override(effective, request_period)
+ with (
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.retriever_registry",
+ SimpleNamespace(get=lambda *a, **k: None),
+ ),
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.get_safe_module_class",
+ return_value=CapturingEngine,
+ ),
+ patch(
+ "local_deep_research.security.egress.policy.evaluate_engine",
+ return_value=Decision(True, "local_review"),
+ ),
+ ):
+ engine = get_search(
+ "serpapi", llm_instance=Mock(), settings_snapshot=effective
+ )
+ assert engine is not None
+ assert engine.time_period == expected
+
+
+ ("key", "bad_value"),
+ [
+ (key, bad_value)
+ for key in (
+ "search.time_period",
+ "search.engine.web.serpapi.default_params.time_period",
+ )
+ for bad_value in (
+ "typo-private-marker",
+ "",
+ None,
+ 1,
+ True,
+ ["w"],
+ {"period": "w"},
+ )
+ # A null global is "not set" (see the null-global tests below), not
+ # a malformed selection: a stored null reaches the resolver as a
+ # bare None once get_settings_snapshot() unwraps it.
+ if not (key == "search.time_period" and bad_value is None)
+ ],
+)
+def test_invalid_selected_period_fails_before_engine_construction(
+ monkeypatch, key, bad_value
+):
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ monkeypatch.delenv("LDR_SEARCH_TIME_PERIOD", raising=False)
+ monkeypatch.delenv(
+ "LDR_SEARCH_ENGINE_WEB_SERPAPI_DEFAULT_PARAMS_TIME_PERIOD",
+ raising=False,
+ )
+ snapshot = {
+ "search.time_period": "d",
+ "search.engine.web.serpapi.default_params.time_period": "inherit",
+ "search.engine.library.enabled": False,
+ }
+ snapshot[key] = bad_value
+ with (
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.retriever_registry",
+ SimpleNamespace(get=lambda *a, **k: None),
+ ),
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.get_safe_module_class",
+ return_value=CapturingEngine,
+ ) as constructor,
+ patch(
+ "local_deep_research.security.egress.policy.evaluate_engine",
+ return_value=Decision(True, "local_review"),
+ ),
+ pytest.raises(ValueError) as error,
+ ):
+ create_search_engine("serpapi", settings_snapshot=snapshot)
+ assert str(error.value) == f"{key} must be one of d, w, m, y, all"
+ assert error.value.__context__ is None
+ constructor.assert_not_called()
+
+
+ "key",
+ [
+ "search.time_period",
+ "search.engine.web.serpapi.default_params.time_period",
+ ],
+)
+def test_invalid_operator_period_does_not_reuse_saved_choice(monkeypatch, key):
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ monkeypatch.delenv("LDR_SEARCH_TIME_PERIOD", raising=False)
+ monkeypatch.delenv(
+ "LDR_SEARCH_ENGINE_WEB_SERPAPI_DEFAULT_PARAMS_TIME_PERIOD",
+ raising=False,
+ )
+ monkeypatch.setenv(
+ "LDR_" + key.replace(".", "_").upper(), "typo-private-marker"
+ )
+ snapshot = {
+ "search.time_period": "d",
+ "search.engine.web.serpapi.default_params.time_period": "inherit",
+ "search.engine.library.enabled": False,
+ }
+ with (
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.retriever_registry",
+ SimpleNamespace(get=lambda *a, **k: None),
+ ),
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.get_safe_module_class",
+ return_value=CapturingEngine,
+ ) as constructor,
+ patch(
+ "local_deep_research.security.egress.policy.evaluate_engine",
+ return_value=Decision(True, "local_review"),
+ ),
+ pytest.raises(ValueError) as error,
+ ):
+ create_search_engine("serpapi", settings_snapshot=snapshot)
+ variable, choices = {
+ "search.time_period": ("LDR_SEARCH_TIME_PERIOD", "d, w, m, y, all"),
+ "search.engine.web.serpapi.default_params.time_period": (
+ "LDR_SEARCH_ENGINE_WEB_SERPAPI_DEFAULT_PARAMS_TIME_PERIOD",
+ "inherit, d, w, m, y, all",
+ ),
+ }[key]
+ # The error names the environment variable it came from, not the key.
+ assert str(error.value) == (
+ f"Environment variable {variable} must be one of {choices}; "
+ "case and surrounding whitespace matter"
+ )
+ assert "typo-private-marker" not in str(error.value)
+ constructor.assert_not_called()
+
+
+ "variable",
+ [
+ "LDR_SEARCH_TIME_PERIOD",
+ "LDR_SEARCH_ENGINE_WEB_SERPAPI_DEFAULT_PARAMS_TIME_PERIOD",
+ ],
+)
+ "value",
+ ["y\r", "Y", " y", "y ", "\ty", "yy", "ALL", "Inherit", "past-year"],
+)
+def test_environment_pin_with_wrong_case_or_whitespace_names_the_variable(
+ monkeypatch, variable, value
+):
+ """A value copied from a Windows-edited .env ("y" plus a carriage return)
+ or typed in capitals is rejected. The error says which variable to fix
+ and that case and surrounding whitespace matter, without echoing it."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ monkeypatch.delenv("LDR_SEARCH_TIME_PERIOD", raising=False)
+ monkeypatch.delenv(
+ "LDR_SEARCH_ENGINE_WEB_SERPAPI_DEFAULT_PARAMS_TIME_PERIOD",
+ raising=False,
+ )
+ monkeypatch.setenv(variable, value)
+ snapshot = {
+ "search.time_period": "d",
+ "search.engine.web.serpapi.default_params.time_period": "inherit",
+ "search.engine.library.enabled": False,
+ }
+ with (
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.retriever_registry",
+ SimpleNamespace(get=lambda *a, **k: None),
+ ),
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.get_safe_module_class",
+ return_value=CapturingEngine,
+ ),
+ patch(
+ "local_deep_research.security.egress.policy.evaluate_engine",
+ return_value=Decision(True, "local_review"),
+ ),
+ pytest.raises(ValueError) as error,
+ ):
+ create_search_engine("serpapi", settings_snapshot=snapshot)
+ message = str(error.value)
+ assert message.startswith(f"Environment variable {variable} must be one of")
+ assert message.endswith("case and surrounding whitespace matter")
+ # The raw value is never echoed, control characters included.
+ assert repr(value) not in message
+ assert "\r" not in message
+ assert "\t" not in message
+
+
+def test_invalid_global_environment_pin_names_the_variable_before_any_mutation(
+ monkeypatch,
+):
+ import copy
+
+ monkeypatch.setenv("LDR_SEARCH_TIME_PERIOD", "y\r")
+ snapshot = {
+ "search.time_period": {"value": "d", "ui_element": "select"},
+ "search.engine.web.serpapi.default_params.time_period": {
+ "value": "m",
+ "ui_element": "select",
+ },
+ }
+ before = copy.deepcopy(snapshot)
+ with pytest.raises(ValueError) as error:
+ apply_time_period_override(snapshot, "w")
+ assert str(error.value) == (
+ "Environment variable LDR_SEARCH_TIME_PERIOD must be one of "
+ "d, w, m, y, all; case and surrounding whitespace matter"
+ )
+ assert snapshot == before
+
+
+ "bad_value", ["typo-private-marker", "inherit", "", None, 1, True, ["w"]]
+)
+def test_invalid_request_does_not_mutate_snapshot(monkeypatch, bad_value):
+ import copy
+
+ monkeypatch.delenv("LDR_SEARCH_TIME_PERIOD", raising=False)
+ snapshot = {
+ "search.time_period": {"value": "d", "ui_element": "select"},
+ "search.engine.web.serpapi.default_params.time_period": {
+ "value": "m",
+ "ui_element": "select",
+ },
+ }
+ before = copy.deepcopy(snapshot)
+ with pytest.raises(ValueError, match="time_period must be one of"):
+ apply_time_period_override(snapshot, bad_value)
+ assert snapshot == before
+
+
[email protected]("engine", ["brave", "serpapi", "tavily"])
+ ("pinned", "expected"),
+ [
+ pytest.param("w", "w", id="environment-pin-wins"),
+ pytest.param(None, "d", id="control-no-pin-follows-global"),
+ ],
+)
+def test_environment_pinned_per_engine_period_outranks_global(
+ monkeypatch, engine, pinned, expected
+):
+ """The changelog says an environment-pinned per-engine period is a
+ deliberate override. Before the inherit semantics the global setting
+ shadowed it for SerpAPI and Tavily, so it now takes effect for them."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ env_name = (
+ f"LDR_SEARCH_ENGINE_WEB_{engine.upper()}_DEFAULT_PARAMS_TIME_PERIOD"
+ )
+ monkeypatch.delenv("LDR_SEARCH_TIME_PERIOD", raising=False)
+ monkeypatch.delenv(env_name, raising=False)
+ if pinned is not None:
+ monkeypatch.setenv(env_name, pinned)
+ snapshot = {
+ "search.time_period": "d",
+ f"search.engine.web.{engine}.default_params.time_period": "inherit",
+ "search.engine.library.enabled": False,
+ }
+ with (
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.retriever_registry",
+ SimpleNamespace(get=lambda *a, **k: None),
+ ),
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.get_safe_module_class",
+ return_value=CapturingEngine,
+ ),
+ patch(
+ "local_deep_research.security.egress.policy.evaluate_engine",
+ return_value=Decision(True, "local_review"),
+ ),
+ ):
+ built = create_search_engine(engine, settings_snapshot=snapshot)
+ assert built is not None
+ assert built.time_period == expected
+
+
[email protected]("locked", [False, True])
+def test_request_period_replaces_saved_choice_whether_or_not_settings_locked(
+ monkeypatch, locked
+):
+ """The research start snapshot is taken with SettingsManager.get_all_settings,
+ which marks every database-backed entry non-editable while app.lock_settings
+ is on. That marker is not an environment pin, so a per-request period must
+ replace an explicit per-engine choice on a locked installation too."""
+ from sqlalchemy import create_engine as create_db_engine
+ from sqlalchemy.orm import Session
+
+ from local_deep_research.database.models.settings import (
+ Setting,
+ SettingType,
+ )
+ from local_deep_research.settings.manager import SettingsManager
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ for name in (
+ "LDR_SEARCH_TIME_PERIOD",
+ "LDR_APP_LOCK_SETTINGS",
+ "LDR_SEARCH_ENGINE_WEB_SERPAPI_DEFAULT_PARAMS_TIME_PERIOD",
+ ):
+ monkeypatch.delenv(name, raising=False)
+ serpapi_key = "search.engine.web.serpapi.default_params.time_period"
+ options = [
+ {"label": code, "value": code}
+ for code in ("inherit", "d", "w", "m", "y", "all")
+ ]
+ rows = [
+ ("app.lock_settings", locked, SettingType.APP, "checkbox", None),
+ (
+ "search.time_period",
+ "all",
+ SettingType.SEARCH,
+ "select",
+ options[1:],
+ ),
+ (serpapi_key, "y", SettingType.SEARCH, "select", options),
+ ]
+ database = create_db_engine("sqlite://")
+ Setting.__table__.create(database)
+ try:
+ with Session(database) as session:
+ for key, value, kind, ui_element, choices in rows:
+ session.add(
+ Setting(
+ key=key,
+ value=value,
+ type=kind,
+ name=key,
+ ui_element=ui_element,
+ options=choices,
+ visible=True,
+ editable=True,
+ )
+ )
+ session.commit()
+ snapshot = SettingsManager(
+ session, seed_defaults=False
+ ).get_all_settings(
+ # Research uses effective metadata. Stored-value exports
+ # deliberately leave editable unchanged, even when locked.
+ bypass_cache=True,
+ include_environment_overrides=True,
+ )
+ finally:
+ database.dispose()
+ snapshot["search.engine.library.enabled"] = False
+ snapshot["search.engine.web.serpapi.api_key"] = {"value": "sk-" + "x" * 20}
+ # The premise: the saved choice is marked non-editable exactly when locked.
+ assert snapshot[serpapi_key]["editable"] is (not locked)
+
+ apply_time_period_override(snapshot, "w")
+
+ assert snapshot[serpapi_key]["value"] == "inherit"
+ assert snapshot["search.time_period"]["value"] == "w"
+ with (
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.retriever_registry",
+ SimpleNamespace(get=lambda *a, **k: None),
+ ),
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.get_safe_module_class",
+ return_value=CapturingEngine,
+ ),
+ patch(
+ "local_deep_research.security.egress.policy.evaluate_engine",
+ return_value=Decision(True, "local_review"),
+ ),
+ ):
+ built = create_search_engine("serpapi", settings_snapshot=snapshot)
+ assert built is not None
+ assert built.time_period == "w"
+
+
[email protected]("engine", ["brave", "serpapi", "tavily"])
+def test_wrapped_null_global_period_falls_back_to_all(monkeypatch, engine):
+ """A stored global row with no value (what a database-backed snapshot
+ holds for a cleared setting) resolves to the documented "all" default,
+ as it did before inherit semantics, instead of failing every search."""
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ monkeypatch.delenv("LDR_SEARCH_TIME_PERIOD", raising=False)
+ monkeypatch.delenv(
+ f"LDR_SEARCH_ENGINE_WEB_{engine.upper()}_DEFAULT_PARAMS_TIME_PERIOD",
+ raising=False,
+ )
+ snapshot = {
+ "search.time_period": {"value": None, "ui_element": "select"},
+ f"search.engine.web.{engine}.default_params.time_period": "inherit",
+ "search.engine.library.enabled": False,
+ }
+ with (
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.retriever_registry",
+ SimpleNamespace(get=lambda *a, **k: None),
+ ),
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.get_safe_module_class",
+ return_value=CapturingEngine,
+ ),
+ patch(
+ "local_deep_research.security.egress.policy.evaluate_engine",
+ return_value=Decision(True, "local_review"),
+ ),
+ ):
+ built = create_search_engine(engine, settings_snapshot=snapshot)
+ assert built is not None
+ assert built.time_period == "all"
+
+
[email protected]("engine", ["brave", "serpapi", "tavily", "wikinews"])
[email protected]("stored", ["json-null", "sql-null"])
+def test_stored_null_global_period_in_an_unwrapped_snapshot_means_all(
+ monkeypatch, engine, stored
+):
+ """SettingsManager.get_settings_snapshot() (REST /api/v1, scheduled news
+ runs, news/api) unwraps every entry, so a stored null search.time_period
+ arrives as a bare None. As on main, that means "not set" and every engine
+ that takes the shared period searches unfiltered instead of raising."""
+ from sqlalchemy import create_engine as create_db_engine
+ from sqlalchemy import null
+ from sqlalchemy.orm import Session
+
+ from local_deep_research.database.models.settings import (
+ Setting,
+ SettingType,
+ )
+ from local_deep_research.settings.manager import SettingsManager
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ monkeypatch.delenv("LDR_SEARCH_TIME_PERIOD", raising=False)
+ monkeypatch.delenv(
+ f"LDR_SEARCH_ENGINE_WEB_{engine.upper()}_DEFAULT_PARAMS_TIME_PERIOD",
+ raising=False,
+ )
+ database = create_db_engine("sqlite://")
+ Setting.__table__.create(database)
+ try:
+ with Session(database) as session:
+ session.add(
+ Setting(
+ key="search.time_period",
+ value=None if stored == "json-null" else null(),
+ type=SettingType.SEARCH,
+ name="Time Period",
+ ui_element="select",
+ options=[
+ {"label": code, "value": code}
+ for code in ("d", "w", "m", "y", "all")
+ ],
+ visible=True,
+ editable=True,
+ )
+ )
+ session.commit()
+ snapshot = SettingsManager(
+ session, seed_defaults=False
+ ).get_settings_snapshot()
+ finally:
+ database.dispose()
+ # The premise: the stored null really is a bare None in this shape.
+ assert snapshot["search.time_period"] is None
+ snapshot["search.engine.library.enabled"] = False
+ snapshot[f"search.engine.web.{engine}.api_key"] = "sk-" + "x" * 20
+
+ with (
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.retriever_registry",
+ SimpleNamespace(get=lambda *a, **k: None),
+ ),
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.get_safe_module_class",
+ return_value=CapturingEngine,
+ ),
+ patch(
+ "local_deep_research.security.egress.policy.evaluate_engine",
+ return_value=Decision(True, "local_review"),
+ ),
+ ):
+ built = create_search_engine(engine, settings_snapshot=snapshot)
+ assert built is not None
+ assert built.time_period == "all"
+
+
+def _resolved_period(monkeypatch, engine="serpapi", **levels):
+ """Period an engine receives with the given levels set to a value.
+
+ Levels, highest first: explicit (kwarg), engine_env, global_env, request,
+ engine_saved, global_saved. The snapshot has the shape dispatch gives it.
+ """
+ engine_env = (
+ f"LDR_SEARCH_ENGINE_WEB_{engine.upper()}_DEFAULT_PARAMS_TIME_PERIOD"
+ )
+ per_engine_key = f"search.engine.web.{engine}.default_params.time_period"
+ for name in ("LDR_SEARCH_TIME_PERIOD", engine_env):
+ monkeypatch.delenv(name, raising=False)
+ if "engine_env" in levels:
+ monkeypatch.setenv(engine_env, levels["engine_env"])
+ if "global_env" in levels:
+ monkeypatch.setenv("LDR_SEARCH_TIME_PERIOD", levels["global_env"])
+ snapshot = {
+ "search.engine.library.enabled": False,
+ per_engine_key: {
+ "value": levels.get("engine_saved", "inherit"),
+ "ui_element": "select",
+ "editable": True,
+ },
+ }
+ if "global_saved" in levels:
+ snapshot["search.time_period"] = {
+ "value": levels["global_saved"],
+ "ui_element": "select",
+ "editable": True,
+ }
+ if "request" in levels:
+ apply_time_period_override(snapshot, levels["request"])
+ kwargs = {"time_period": levels["explicit"]} if "explicit" in levels else {}
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ create_search_engine,
+ )
+
+ with (
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.retriever_registry",
+ SimpleNamespace(get=lambda *a, **k: None),
+ ),
+ patch(
+ "local_deep_research.web_search_engines.search_engine_factory.get_safe_module_class",
+ return_value=CapturingEngine,
+ ),
+ patch(
+ "local_deep_research.security.egress.policy.evaluate_engine",
+ return_value=Decision(True, "local_review"),
+ ),
+ ):
+ built = create_search_engine(
+ engine, settings_snapshot=snapshot, **kwargs
+ )
+ assert built is not None
+ return built.time_period
+
+
[email protected]("engine", ["brave", "serpapi", "tavily"])
+ ("higher", "lower"),
+ [
+ pytest.param("explicit", "engine_env", id="code-over-engine-pin"),
+ pytest.param("explicit", "global_env", id="code-over-global-pin"),
+ pytest.param(
+ "engine_env", "global_env", id="engine-pin-over-global-pin"
+ ),
+ pytest.param("engine_env", "engine_saved", id="engine-pin-over-saved"),
+ pytest.param("global_env", "request", id="global-pin-over-request"),
+ pytest.param("global_env", "engine_saved", id="global-pin-over-saved"),
+ pytest.param("request", "engine_saved", id="request-over-saved"),
+ pytest.param("request", "global_saved", id="request-over-saved-global"),
+ pytest.param(
+ "engine_saved", "global_saved", id="saved-engine-over-global"
+ ),
+ ],
+)
+def test_time_period_precedence_is_one_order_on_every_path(
+ monkeypatch, engine, higher, lower
+):
+ """explicit > engine env > LDR_SEARCH_TIME_PERIOD > request > saved
+ per-engine choice > saved global setting, for every pair that meets."""
+ assert (
+ _resolved_period(monkeypatch, engine, **{higher: "d", lower: "w"})
+ == "d"
+ )
+ # Control: the lower level alone is honoured, so the pair above really
+ # tests which of the two wins.
+ assert _resolved_period(monkeypatch, engine, **{lower: "w"}) == "w"
+
+
+def test_time_period_defaults_to_all_without_any_level(monkeypatch):
+ assert _resolved_period(monkeypatch) == "all"
+
+
+ ("levels", "expected"),
+ [
+ pytest.param({}, "d", id="follows-saved-global"),
+ pytest.param({"global_env": "m"}, "m", id="follows-global-pin"),
+ ],
+)
+def test_engine_environment_inherit_hides_the_saved_per_engine_choice(
+ monkeypatch, levels, expected
+):
+ """LDR_SEARCH_ENGINE_WEB_<ENGINE>_DEFAULT_PARAMS_TIME_PERIOD=inherit is an
+ operator pin to the global level: a choice saved for the engine in
+ Settings does not apply."""
+ assert (
+ _resolved_period(
+ monkeypatch,
+ engine_env="inherit",
+ engine_saved="w",
+ global_saved="d",
+ **levels,
+ )
+ == expected
+ )