~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(search): honor search.time_period in Tavily; default to "all" (#4936) (#4978)
LearningCircuit1340381c8255
diff --git a/changelog.d/4936.bugfix.md b/changelog.d/4936.bugfix.mdnew file mode 100644index 0000000000..ea9dcde3fd--- /dev/null+++ b/changelog.d/4936.bugfix.md@@ -0,0 +1 @@+The Tavily search engine now honors the configured time period. When a specific period (Past 24 hours / week / month / year) is selected under Settings → Search, it is forwarded to the Tavily API as `time_range`, so that selection actually narrows results instead of being silently ignored. The default is "All time" (no filter) — select a narrower period if you want time-restricted results. The setting now reaches engines on every search path, including the default `langgraph-agent` strategy and the MCP server, which previously bypassed it.diff --git a/changelog.d/4978.breaking.md b/changelog.d/4978.breaking.mdnew file mode 100644index 0000000000..1638d99322--- /dev/null+++ b/changelog.d/4978.breaking.md@@ -0,0 +1 @@+**`search.time_period` default changed from "Past year" to "All time".** Default searches are no longer silently restricted to the last year. Migration 0030 updates every stored "Past year" value to "All time" — including deliberately selected ones, since they are indistinguishable from the old default; if you want year-restricted results, re-select **Past year** in Settings after upgrading (choices of Past 24 hours / week / month are preserved). The global setting now reaches Tavily, serpapi, and Wikinews on every search path — `get_search()`-based flows (including news subscriptions) as well as direct `create_search_engine()` callers such as the default `langgraph-agent` strategy and the MCP server — and takes precedence over the per-engine `search.engine.web.<engine>.default_params.time_period` settings, which apply only when the global setting is absent (rare, programmatic snapshots). Brave is not covered by the global setting and remains governed by its own per-engine setting. Wikinews changes: its built-in default is now "All time" (previously an implicit one-year window), and unrecognized values apply no filter instead of silently falling back to one year — much older articles can appear unless a narrower period is explicitly selected.diff --git a/src/local_deep_research/database/migrations/versions/0030_default_time_period_all.py b/src/local_deep_research/database/migrations/versions/0030_default_time_period_all.pynew file mode 100644index 0000000000..47d24ba138--- /dev/null+++ b/src/local_deep_research/database/migrations/versions/0030_default_time_period_all.py@@ -0,0 +1,107 @@+"""Switch default search.time_period from 'y' to 'all'.++Background+==========+``search.time_period`` shipped with a default of ``"y"`` (Past year). With+issue #4936 the Tavily engine learned to honor this setting (forwarding it+to the Tavily ``time_range`` param), which exposed a long-standing problem:+the same default also drove the already-wired ``serpapi`` and ``wikinews``+engines, silently filtering every default search to the last year. For+research and news that is sometimes desirable, but as an *immutable* default+it quietly hides older (often more authoritative) sources, and most users+inherited it without choosing it.++The new default ``"all"`` disables the time filter unless the user opts in+(Past 24 hours / week / month / year), matching the intuitive meaning of+"search the web".++What this migration does+========================+Updates rows where ``key = 'search.time_period'`` AND the stored value is+exactly ``"y"``. Users who explicitly chose ``d``, ``w``, ``m``, or ``all``+are left untouched. Users who deliberately picked ``y`` will find their+preference flipped — they can re-select ``Past year`` from the settings UI;+this is the intentional cost of fixing a poor default that almost everyone+inherited without choosing it.++Storage note: the ``value`` column uses SQLAlchemy's ``JSON`` type, which+serializes Python strings via ``json.dumps`` and stores them as TEXT. The+on-disk representation of the string ``y`` is the 3-character literal+``"y"`` (with the surrounding quotes), so the WHERE clause matches on that+exact form.++Revision ID: 0030+Revises: 0029+Create Date: 2026-07-05+"""++from __future__ import annotations++import sqlalchemy as sa+from alembic import op+from loguru import logger+from sqlalchemy import inspect++revision = "0030"+down_revision = "0029"+branch_labels = None+depends_on = None++SETTING_KEY = "search.time_period"+OLD_VALUE_JSON = '"y"'+NEW_VALUE_JSON = '"all"'+++def upgrade() -> None:+ conn = op.get_bind()++ inspector = inspect(conn)+ if not inspector.has_table("settings"):+ return++ result = conn.execute(+ sa.text(+ "UPDATE settings SET value = :new_value "+ "WHERE key = :key AND value = :old_value"+ ),+ {+ "new_value": NEW_VALUE_JSON,+ "key": SETTING_KEY,+ "old_value": OLD_VALUE_JSON,+ },+ )++ if result.rowcount:+ logger.info(+ "Migrated {} setting(s) {!r} from 'y' to 'all'.",+ result.rowcount,+ SETTING_KEY,+ )+++def downgrade() -> None:+ """Revert previously-migrated rows back to 'y'.++ Only rows whose value is currently ``"all"`` are reverted — leaves any+ user choice of ``d``, ``w``, or ``m`` alone. Rows that already held+ ``all`` before the upgrade are indistinguishable from migrated rows; the+ downgrade conservatively reverts them as well, since the pre-upgrade+ state stored ``"y"`` as the default.+ """+ conn = op.get_bind()++ inspector = inspect(conn)+ if not inspector.has_table("settings"):+ return++ conn.execute(+ sa.text(+ "UPDATE settings SET value = :old_value "+ "WHERE key = :key AND value = :new_value"+ ),+ {+ "old_value": OLD_VALUE_JSON,+ "key": SETTING_KEY,+ "new_value": NEW_VALUE_JSON,+ },+ )diff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.jsonindex 0f250239c4..0d0526fe03 100644--- a/src/local_deep_research/defaults/default_settings.json+++ b/src/local_deep_research/defaults/default_settings.json@@ -1483,7 +1483,7 @@"step": null,"type": "SEARCH","ui_element": "select",- "value": "y",+ "value": "all","visible": true},"search.tool": {@@ -2937,7 +2937,7 @@},"search.engine.web.serpapi.default_params.time_period": {"category": "serpapi",- "description": "Time filter for results: 'd' (day), 'w' (week), 'm' (month), 'y' (year), or empty for all time.",+ "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.","editable": true,"max_value": null,"min_value": null,@@ -3861,6 +3861,41 @@"value": true,"visible": true},+ "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.",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Time Period",+ "options": [+ {+ "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": "select",+ "value": "all",+ "visible": true+ },"search.engine.web.tavily.requires_api_key": {"category": "tavily","description": "Indicates this engine requires a Tavily API key. Get one at tavily.com.",diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_brave.py b/src/local_deep_research/web_search_engines/engines/search_engine_brave.pyindex 77c6c62a16..6d64fd261e 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_brave.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_brave.py@@ -6,7 +6,12 @@ from langchain_core.language_models import BaseLLMfrom ...security.secure_logging import loggerfrom ..rate_limiting import RateLimitError-from ..search_engine_base import BaseSearchEngine, Exposure, Sensitivity+from ..search_engine_base import (+ VALID_TIME_PERIODS,+ BaseSearchEngine,+ Exposure,+ Sensitivity,+)class BraveSearchEngine(BaseSearchEngine):@@ -42,7 +47,9 @@ class BraveSearchEngine(BaseSearchEngine):Args:max_results: Maximum number of search resultsregion: Region code for search results- time_period: Time period for search results+ time_period: Time period filter (d/w/m/y); forwarded to Brave's+ ``freshness`` param as p{d,w,m,y}. ``all`` (or any+ unrecognized value) omits the filter.safe_search: Whether to enable safe searchsearch_language: Language for search resultsapi_key: Brave Search API key (can also be set via LDR_SEARCH_ENGINE_WEB_BRAVE_API_KEY env var or in UI settings)@@ -80,22 +87,27 @@ class BraveSearchEngine(BaseSearchEngine):# Get language codelanguage_code = language_code_mapping.get(search_language.lower(), "en")- # Convert time period format to Brave's format- brave_time_period = f"p{time_period}"-# Convert safe search to Brave's formatbrave_safe_search = "moderate" if safe_search else "off"# Initialize Brave Search+ search_kwargs = {+ "count": min(20, max_results),+ "country": region.upper(),+ "search_lang": language_code,+ "safesearch": brave_safe_search,+ }+ # Brave's freshness param prefixes time_period with "p" (pd/pw/pm/py).+ # Only forward recognized codes; "all", any unrecognized value+ # (typo, None, "") and non-string types omit freshness entirely so+ # the search is unfiltered rather than sending an invalid value+ # like "pall" (the isinstance guard also keeps unhashable values+ # from raising on the frozenset lookup).+ if isinstance(time_period, str) and time_period in VALID_TIME_PERIODS:+ search_kwargs["freshness"] = f"p{time_period}"self.engine = BraveSearch.from_api_key(api_key=brave_api_key,- search_kwargs={- "count": min(20, max_results),- "country": region.upper(),- "search_lang": language_code,- "safesearch": brave_safe_search,- "freshness": brave_time_period,- },+ search_kwargs=search_kwargs,)# User agent is not needed for Brave Search APIdiff --git a/src/local_deep_research/web_search_engines/engines/search_engine_serpapi.py b/src/local_deep_research/web_search_engines/engines/search_engine_serpapi.pyindex 1d1206d826..3dcbc168f1 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_serpapi.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_serpapi.py@@ -5,7 +5,12 @@ from langchain_community.utilities import SerpAPIWrapperfrom langchain_core.language_models import BaseLLMfrom ..rate_limiting import RateLimitError-from ..search_engine_base import BaseSearchEngine, Exposure, Sensitivity+from ..search_engine_base import (+ VALID_TIME_PERIODS,+ BaseSearchEngine,+ Exposure,+ Sensitivity,+)class SerpAPISearchEngine(BaseSearchEngine):@@ -39,7 +44,9 @@ class SerpAPISearchEngine(BaseSearchEngine):Args:max_results: Maximum number of search resultsregion: Region code for search results- time_period: Time period for search results+ time_period: Time period filter (d/w/m/y); forwarded to Google's+ ``tbs`` param as qdr:{d,w,m,y}. ``all`` (or any unrecognized+ value) omits the filter.safe_search: Whether to enable safe searchsearch_language: Language for search resultsapi_key: SerpAPI API key (can also be set via LDR_SEARCH_ENGINE_WEB_SERPAPI_API_KEY env var or in UI settings)@@ -82,20 +89,28 @@ class SerpAPISearchEngine(BaseSearchEngine):language_code = language_code_mapping.get(search_language.lower(), "en")# Initialize SerpAPI wrapper+ params = {+ "engine": "google",+ "hl": language_code,+ "gl": region,+ "safe": "active" if safe_search else "off",+ # Google's "num" tops out at 100 results per request; cap so a+ # large user-supplied max_results can't request an unbounded page.+ # Use the base-class-normalized self.max_results (positive int)+ # rather than the raw arg, which could be None/str.+ "num": min(self.max_results, 100),+ }+ # Google's tbs validator accepts qdr:d/w/m/y (h is not one of LDR's+ # canonical time_period codes). Only forward recognized codes; "all",+ # any unrecognized value (typo, None, "") and non-string types omit+ # the param entirely so the search is unfiltered rather than+ # silently malformed (e.g. "qdr:all") — the isinstance guard also+ # keeps unhashable values from raising on the frozenset lookup.+ if isinstance(time_period, str) and time_period in VALID_TIME_PERIODS:+ params["tbs"] = f"qdr:{time_period}"self.engine = SerpAPIWrapper(serpapi_api_key=serpapi_api_key,- params={- "engine": "google",- "hl": language_code,- "gl": region,- "safe": "active" if safe_search else "off",- "tbs": f"qdr:{time_period}",- # Google's "num" tops out at 100 results per request; cap so a- # large user-supplied max_results can't request an unbounded page.- # Use the base-class-normalized self.max_results (positive int)- # rather than the raw arg, which could be None/str.- "num": min(self.max_results, 100),- },+ params=params,)# If full content is requested, initialize FullSearchResultsdiff --git a/src/local_deep_research/web_search_engines/engines/search_engine_tavily.py b/src/local_deep_research/web_search_engines/engines/search_engine_tavily.pyindex 2c54a77cb4..d4a136d9db 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_tavily.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_tavily.py@@ -8,6 +8,15 @@ from ...security.safe_requests import safe_postfrom ..rate_limiting import RateLimitErrorfrom ..search_engine_base import BaseSearchEngine, Exposure, Sensitivity+# Map LDR time_period codes to Tavily API time_range values.+# "all" and any unrecognized value (None, "", wrong case, whitespace,+# unknown strings) omit time_range so no filter is applied. The settings+# UI only emits the canonical d/w/m/y/all codes; programmatic callers+# must match exactly — we deliberately do NOT .lower()/strip() so a+# mistyped value fails visibly as "unfiltered" rather than silently+# being coerced.+_TIME_RANGE_MAP = {"d": "day", "w": "week", "m": "month", "y": "year"}+class TavilySearchEngine(BaseSearchEngine):"""Tavily search engine implementation with two-phase approach"""@@ -23,7 +32,7 @@ class TavilySearchEngine(BaseSearchEngine):self,max_results: int = 10,region: str = "US",- time_period: str = "y",+ time_period: str = "all",safe_search: bool = True,search_language: str = "English",api_key: Optional[str] = None,@@ -42,7 +51,9 @@ class TavilySearchEngine(BaseSearchEngine):Args:max_results: Maximum number of search resultsregion: Region code for search results (not used by Tavily currently)- time_period: Time period for search results (not used by Tavily currently)+ time_period: Time period filter (d/w/m/y/all); forwarded to the+ Tavily ``time_range`` param as day/week/month/year. ``all``+ (or any unrecognized value) omits the filter.safe_search: Whether to enable safe search (not used by Tavily currently)search_language: Language for search results (not used by Tavily currently)api_key: Tavily API key (can also be set via LDR_SEARCH_ENGINE_WEB_TAVILY_API_KEY env var or in UI settings)@@ -64,6 +75,7 @@ class TavilySearchEngine(BaseSearchEngine):settings_snapshot=settings_snapshot,)self.search_depth = search_depth+ self.time_period = time_periodself.include_domains = include_domains or []self.exclude_domains = exclude_domains or []@@ -129,6 +141,18 @@ class TavilySearchEngine(BaseSearchEngine):if self.exclude_domains:payload["exclude_domains"] = self.exclude_domains+ # Apply time-period filter (Tavily time_range). "all" / unknown+ # map to None and are omitted so no filter is applied. Non-string+ # values (possible via programmatic construction) are treated as+ # "no filter" rather than raising on the unhashable dict lookup.+ time_range = (+ _TIME_RANGE_MAP.get(self.time_period)+ if isinstance(self.time_period, str)+ else None+ )+ if time_range:+ payload["time_range"] = time_range+# Apply rate limiting before requestself._last_wait_time = self.rate_tracker.apply_rate_limit(self.engine_typediff --git a/src/local_deep_research/web_search_engines/engines/search_engine_wikinews.py b/src/local_deep_research/web_search_engines/engines/search_engine_wikinews.pyindex 4bd5994227..7a2b9a83fa 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_wikinews.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_wikinews.py@@ -59,7 +59,7 @@ class WikinewsSearchEngine(BaseSearchEngine):self,search_language: str = "english",adaptive_search: bool = True,- time_period: str = "y",+ time_period: str = "all",llm: Optional[BaseLLM] = None,max_filtered_results: Optional[int] = None,max_results: int = 10,@@ -74,6 +74,7 @@ class WikinewsSearchEngine(BaseSearchEngine):search_language (str): Language for Wikinews search (e.g. "english").adaptive_search (bool): Whether to expand or shrink date ranges based on query.time_period (str): Defines the look-back window used to filter search results ("all", "y", "m", "w", "d").+ "all" (or any unrecognized value) applies no lower date bound.llm (Optional[BaseLLM]): Language model used for query optimization and classification.max_filtered_results (Optional[int]): Maximum number of results to keep after filtering.max_results (int): Maximum number of search results to return.@@ -108,7 +109,14 @@ class WikinewsSearchEngine(BaseSearchEngine):# Date range initializationnow = datetime.now(UTC)- delta = TIME_PERIOD_DELTAS.get(time_period, timedelta(days=365))+ # Unrecognized values fall back to "all" (no lower bound), matching+ # the tavily/serpapi/brave convention of unfiltered-on-unknown rather+ # than silently imposing a year window.+ delta = (+ TIME_PERIOD_DELTAS.get(time_period)+ if isinstance(time_period, str)+ else None+ )self.from_date: datetime = (now - delta if delta else datetime.min.replace(tzinfo=UTC))diff --git a/src/local_deep_research/web_search_engines/search_engine_base.py b/src/local_deep_research/web_search_engines/search_engine_base.pyindex 63f8cf4ba3..a9e7b84a74 100644--- a/src/local_deep_research/web_search_engines/search_engine_base.py+++ b/src/local_deep_research/web_search_engines/search_engine_base.py@@ -49,6 +49,13 @@ API_KEY_PLACEHOLDERS = frozenset(})+# Canonical short codes for time-restricted search (the global+# ``search.time_period`` setting minus "all", which means "no filter" and is+# expressed by omitting the engine's recency param entirely). Engines that+# forward a recency filter to their API (brave, serpapi, tavily) validate+# against this shared set so the accepted codes can't drift apart.+VALID_TIME_PERIODS = frozenset({"d", "w", "m", "y"})+def _is_api_key_placeholder(api_key: Optional[str]) -> bool:"""Return True if ``api_key`` looks like a placeholder, not a real key.diff --git a/src/local_deep_research/web_search_engines/search_engine_factory.py b/src/local_deep_research/web_search_engines/search_engine_factory.pyindex f9ca929e9c..3ed49583a4 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@@ -9,6 +9,12 @@ from .retriever_registry import retriever_registryfrom .search_engine_base import BaseSearchEnginefrom .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")+def create_search_engine(engine_name: str,@@ -268,6 +274,26 @@ def create_search_engine(max_results = 20kwargs["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 = settings_snapshot["search.time_period"]+ kwargs["time_period"] = (+ raw_time_period.get("value", "all")+ if isinstance(raw_time_period, dict)+ else raw_time_period+ )+# Check for API key requirementsrequires_api_key = engine_config.get("requires_api_key", False)@@ -638,7 +664,7 @@ def get_search(llm_instance,max_results: int = 10,region: str = "us",- time_period: str = "y",+ time_period: str = "all",safe_search: bool = True,search_snippets_only: bool = False,search_language: str = "English",@@ -711,7 +737,7 @@ def get_search(.get("value", True))- if search_tool in ["serpapi", "wikinews"]:+ if search_tool in TIME_PERIOD_ENGINES:params["time_period"] = time_period# Create and return the search enginediff --git a/tests/database/test_migration_0030_default_time_period_all.py b/tests/database/test_migration_0030_default_time_period_all.pynew file mode 100644index 0000000000..ae70b2f81e--- /dev/null+++ b/tests/database/test_migration_0030_default_time_period_all.py@@ -0,0 +1,288 @@+"""Tests for migration 0030: default search.time_period 'y' → 'all'.++Pins the upgrade/downgrade semantics:+- Rows with the legacy default ``"y"`` get flipped.+- Rows users explicitly chose (``d``, ``w``, ``m``, ``all``) are left+ untouched.+- Other settings keys with value ``"y"`` are not affected.+- Idempotency: a second upgrade is a no-op once values are migrated.++The on-disk encoding is JSON-text (``"y"`` with the surrounding quotes), so+the test inserts through SQLAlchemy's JSON column type to match production+storage exactly.+"""++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,+)+++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):+ """Insert a setting matching production's JSON-text storage.++ SQLAlchemy's JSON column writes ``json.dumps(value)``; we mirror that+ explicitly so raw SQL produces the same on-disk bytes the migration+ expects to match in its WHERE clause.+ """+ with engine.begin() as conn:+ conn.execute(+ text(+ "INSERT INTO settings "+ "(key, value, type, name, ui_element, visible, editable) "+ "VALUES (:key, :value, 'search', :name, 'select', 1, 1)"+ ),+ {"key": key, "value": json.dumps(value), "name": key},+ )+++def _read_setting(engine, key):+ with engine.begin() as conn:+ row = conn.execute(+ text("SELECT value FROM settings WHERE key = :key"),+ {"key": key},+ ).fetchone()+ if row is None:+ return None+ raw = row[0]+ # JSON column round-trips through json.loads on read, but raw text()+ # bypasses the column type — so decode manually.+ return json.loads(raw) if isinstance(raw, str) else raw++[email protected](scope="module")+def _migrated_to_0029_template(tmp_path_factory):+ """Template DB fully migrated through 0029, built once per module.++ Rebuilding the full 0001->0029 Alembic chain is the expensive part of+ this file (dominates its runtime across ~16 tests); building it once+ and letting each test start from a copy keeps per-test isolation while+ paying the migration cost only once.+ """+ template_dir = tmp_path_factory.mktemp("migration_0030_template")+ db_path = template_dir / "template_0029.db"+ engine = create_engine(f"sqlite:///{db_path}")+ _run_upgrade_to(engine, "0029")+ engine.dispose()+ return db_path+++def migrated_to_0029_engine(tmp_path, _migrated_to_0029_template):+ """Database fully migrated through 0029 (the revision before 0030).++ Copies the module-scoped template built by ``_migrated_to_0029_template``+ into a fresh per-test file, so every test still gets its own isolated+ database without re-running the Alembic chain from scratch.+ """+ db_path = tmp_path / "test_0030.db"+ shutil.copy2(_migrated_to_0029_template, db_path)+ engine = create_engine(f"sqlite:///{db_path}")+ yield engine+ engine.dispose()+++class TestMigration0030Upgrade:+ def test_y_value_is_migrated_to_all(self, migrated_to_0029_engine):+ engine = migrated_to_0029_engine++ with engine.begin() as conn:+ conn.execute(+ text("DELETE FROM settings WHERE key = 'search.time_period'")+ )+ _seed_setting(engine, "search.time_period", "y")++ _run_upgrade_to(engine, "0030")++ assert _read_setting(engine, "search.time_period") == "all"++ @pytest.mark.parametrize("explicit_value", ["d", "w", "m", "all"])+ def test_explicit_non_y_choices_are_preserved(+ self, migrated_to_0029_engine, explicit_value+ ):+ engine = migrated_to_0029_engine++ with engine.begin() as conn:+ conn.execute(+ text("DELETE FROM settings WHERE key = 'search.time_period'")+ )+ _seed_setting(engine, "search.time_period", explicit_value)++ _run_upgrade_to(engine, "0030")++ assert _read_setting(engine, "search.time_period") == explicit_value++ def test_other_keys_with_y_value_are_not_touched(+ self, migrated_to_0029_engine+ ):+ engine = migrated_to_0029_engine++ # An unrelated key that happens to hold 'y' must not be flipped.+ _seed_setting(engine, "test.unrelated.period", "y")++ _run_upgrade_to(engine, "0030")++ assert _read_setting(engine, "test.unrelated.period") == "y"++ def test_upgrade_is_idempotent(self, migrated_to_0029_engine):+ """Running the upgrade a second time is a no-op (already at head)."""+ engine = migrated_to_0029_engine++ with engine.begin() as conn:+ conn.execute(+ text("DELETE FROM settings WHERE key = 'search.time_period'")+ )+ _seed_setting(engine, "search.time_period", "y")++ _run_upgrade_to(engine, "0030")+ # Second invocation: nothing left to do; alembic short-circuits.+ _run_upgrade_to(engine, "0030")++ assert _read_setting(engine, "search.time_period") == "all"++ def test_no_settings_row_does_not_error(self, migrated_to_0029_engine):+ """If the row never existed, the migration is a clean no-op."""+ engine = migrated_to_0029_engine++ with engine.begin() as conn:+ conn.execute(+ text("DELETE FROM settings WHERE key = 'search.time_period'")+ )++ _run_upgrade_to(engine, "0030")++ assert _read_setting(engine, "search.time_period") is None++ @pytest.mark.parametrize(+ "raw_value",+ [+ "y", # bare unquoted — legacy bug / hand-edited DB+ '"y', # truncated JSON+ 'y"', # truncated JSON the other way+ json.dumps(json.dumps("y")), # double-encoded+ ],+ )+ def test_malformed_legacy_y_value_is_left_alone(+ self, migrated_to_0029_engine, raw_value+ ):+ """If the on-disk bytes don't exactly match the JSON-encoded '"y"'+ the migration docstring worries about, the WHERE clause must NOT+ match — leaving the row alone rather than corrupting it. Safe-no-op+ failure mode: future hand-edit or migration bug that writes bare+ 'y' will not be silently rewritten.++ Parametrized over the legacy forms the docstring calls out as+ potential on-disk shapes from older code paths.+ """+ engine = migrated_to_0029_engine++ with engine.begin() as conn:+ conn.execute(+ text("DELETE FROM settings WHERE key = 'search.time_period'")+ )+ # Insert the raw bytes verbatim — bypassing json.dumps so we+ # control exactly what's on disk.+ conn.execute(+ text(+ "INSERT INTO settings "+ "(key, value, type, name, ui_element, visible, editable) "+ "VALUES ('search.time_period', :value, "+ "'search', 'period', 'select', 1, 1)"+ ),+ {"value": raw_value},+ )++ _run_upgrade_to(engine, "0030")++ with engine.begin() as conn:+ row = conn.execute(+ text(+ "SELECT value FROM settings "+ "WHERE key = 'search.time_period'"+ )+ ).fetchone()+ # The malformed value is left exactly as-is on disk.+ assert row[0] == raw_value+++class TestMigration0030Downgrade:+ def test_downgrade_reverts_all_to_y(self, migrated_to_0029_engine):+ engine = migrated_to_0029_engine++ with engine.begin() as conn:+ conn.execute(+ text("DELETE FROM settings WHERE key = 'search.time_period'")+ )+ _seed_setting(engine, "search.time_period", "y")++ _run_upgrade_to(engine, "0030")+ _run_downgrade_to(engine, "0029")++ assert _read_setting(engine, "search.time_period") == "y"++ @pytest.mark.parametrize("preserved_value", ["d", "w", "m"])+ def test_downgrade_preserves_other_explicit_choices(+ self, migrated_to_0029_engine, preserved_value+ ):+ engine = migrated_to_0029_engine++ with engine.begin() as conn:+ conn.execute(+ text("DELETE FROM settings WHERE key = 'search.time_period'")+ )+ _seed_setting(engine, "search.time_period", preserved_value)++ _run_upgrade_to(engine, "0030")+ _run_downgrade_to(engine, "0029")++ assert _read_setting(engine, "search.time_period") == preserved_value+++class TestMigration0030HeadAlignment:+ """Head-alignment guard.++ Deliberately does NOT pin ``get_head_revision() == "0030"``: this repo+ was burned once already (see test_migration_0009_default_fetch_mode.py)+ by a literal head pin that broke the moment a later migration chained+ on top. The substantive invariant — that 0030 is correctly anchored+ in the chain — is covered by asserting ``down_revision`` instead.+ Global head-uniqueness / "head matches latest migration file" coverage+ lives in the dynamic checks in+ tests/database/test_migration_0022_note_references.py, which need no+ update when a new migration (like this one) lands on top.+ """++ def test_0030_chains_correctly_to_0029(self):+ """0030 (default_time_period_all) chains directly off 0029."""+ 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_0030 = script.get_revision("0030")+ assert rev_0030.down_revision == "0029"diff --git a/tests/security/test_api_key_leakage.py b/tests/security/test_api_key_leakage.pyindex fc2c518df0..99651fb0b8 100644--- a/tests/security/test_api_key_leakage.py+++ b/tests/security/test_api_key_leakage.py@@ -509,6 +509,7 @@ class TestSearchEngineKeyLeakage:setattr(engine, api_attr, _LEAKED_KEY)engine.max_results = 10engine.search_depth = "basic"+ engine.time_period = "all"engine.include_full_content = Falseengine.include_domains = []engine.exclude_domains = []diff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.jsonindex 1508e748d8..038f121f8a 100644--- a/tests/settings/golden_master_settings.json+++ b/tests/settings/golden_master_settings.json@@ -6578,7 +6578,7 @@},"search.engine.web.serpapi.default_params.time_period": {"category": "serpapi",- "description": "Time filter for results: 'd' (day), 'w' (week), 'm' (month), 'y' (year), or empty for all time.",+ "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.","editable": true,"max_value": null,"min_value": null,@@ -7360,6 +7360,41 @@"value": "basic","visible": true},+ "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.",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Time Period",+ "options": [+ {+ "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": "select",+ "value": "all",+ "visible": true+ },"search.engine.web.tavily.description": {"category": "tavily","description": "Human-readable description of the search engine.",@@ -8748,7 +8783,7 @@"step": null,"type": "SEARCH","ui_element": "select",- "value": "y",+ "value": "all","visible": true},"search.tool": {diff --git a/tests/web_search_engines/engines/test_search_engine_brave.py b/tests/web_search_engines/engines/test_search_engine_brave.pyindex d3fd9de662..592990af0d 100644--- a/tests/web_search_engines/engines/test_search_engine_brave.py+++ b/tests/web_search_engines/engines/test_search_engine_brave.py@@ -140,6 +140,59 @@ class TestBraveSearchEngineInit:call_kwargs = mock_brave.from_api_key.call_args[1]assert call_kwargs["search_kwargs"]["freshness"] == "pd"+ def test_init_with_time_period_all_omits_freshness(self):+ """time_period='all' must omit freshness entirely — Brave's freshness+ prefixes time_period with 'p' (pd/pw/pm/py) and 'pall' is invalid.+ Pre-existing latent bug made user-visible by the new global 'all'+ default.+ """+ from local_deep_research.web_search_engines.engines.search_engine_brave import (+ BraveSearchEngine,+ )++ with patch(+ "local_deep_research.web_search_engines.engines.search_engine_brave.BraveSearch"+ ) as mock_brave:+ mock_brave.from_api_key.return_value = Mock()+ BraveSearchEngine(api_key="test-key", time_period="all")++ call_kwargs = mock_brave.from_api_key.call_args[1]+ assert "freshness" not in call_kwargs["search_kwargs"], (+ "time_period='all' must omit freshness (pall is invalid for "+ f"Brave); got search_kwargs={call_kwargs['search_kwargs']!r}"+ )++ @pytest.mark.parametrize(+ "bad_value",+ ["garbage", "year", "D", "", None, {"a": 1}, ["y"], 7, True],+ )+ def test_init_with_unrecognized_time_period_omits_freshness(+ self, bad_value+ ):+ """Unrecognized or non-string time_period values omit freshness.++ Only the canonical d/w/m/y codes are forwarded; anything else+ (typo, wrong case, empty string, None, or a non-string type) must+ not be interpolated into freshness=p{...}, which would send an+ invalid value to the Brave API. Unhashable values (dict/list) must+ not raise on the allow-list membership check either.+ """+ from local_deep_research.web_search_engines.engines.search_engine_brave import (+ BraveSearchEngine,+ )++ with patch(+ "local_deep_research.web_search_engines.engines.search_engine_brave.BraveSearch"+ ) as mock_brave:+ mock_brave.from_api_key.return_value = Mock()+ BraveSearchEngine(api_key="test-key", time_period=bad_value)++ call_kwargs = mock_brave.from_api_key.call_args[1]+ assert "freshness" not in call_kwargs["search_kwargs"], (+ f"time_period={bad_value!r} should omit freshness, got "+ f"search_kwargs={call_kwargs['search_kwargs']!r}"+ )+def test_init_without_api_key_raises(self):"""Initialize without API key raises ValueError."""from local_deep_research.web_search_engines.engines.search_engine_brave import (diff --git a/tests/web_search_engines/engines/test_search_engine_serpapi.py b/tests/web_search_engines/engines/test_search_engine_serpapi.pyindex 83f630d462..bbf879ce20 100644--- a/tests/web_search_engines/engines/test_search_engine_serpapi.py+++ b/tests/web_search_engines/engines/test_search_engine_serpapi.py@@ -72,6 +72,54 @@ class TestSerpAPISearchEngineInit:call_kwargs = mock_wrapper.call_args[1]assert call_kwargs["params"]["tbs"] == "qdr:m"+ def test_init_with_time_period_all_omits_tbs(self):+ """time_period='all' must omit tbs entirely — Google's tbs validator+ accepts qdr:d/w/m/y/h but rejects qdr:all. Pre-existing latent bug+ made user-visible by the new global 'all' default.+ """+ from local_deep_research.web_search_engines.engines.search_engine_serpapi import (+ SerpAPISearchEngine,+ )++ with patch(+ "local_deep_research.web_search_engines.engines.search_engine_serpapi.SerpAPIWrapper"+ ) as mock_wrapper:+ SerpAPISearchEngine(api_key="test-key", time_period="all")++ call_kwargs = mock_wrapper.call_args[1]+ assert "tbs" not in call_kwargs["params"], (+ "time_period='all' must omit tbs (qdr:all is invalid for "+ f"Google); got params={call_kwargs['params']!r}"+ )++ @pytest.mark.parametrize(+ "bad_value",+ ["garbage", "year", "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).++ Only the canonical d/w/m/y codes are forwarded; anything else+ (typo, wrong case, empty string, None, or a non-string type) must+ not be interpolated into tbs=qdr:{...}, which would send an invalid+ value to Google. Unhashable values (dict/list) must not raise on+ the allow-list membership check either.+ """+ from local_deep_research.web_search_engines.engines.search_engine_serpapi import (+ SerpAPISearchEngine,+ )++ with patch(+ "local_deep_research.web_search_engines.engines.search_engine_serpapi.SerpAPIWrapper"+ ) as mock_wrapper:+ SerpAPISearchEngine(api_key="test-key", time_period=bad_value)++ call_kwargs = mock_wrapper.call_args[1]+ assert "tbs" not in call_kwargs["params"], (+ f"time_period={bad_value!r} should omit tbs, got "+ f"params={call_kwargs['params']!r}"+ )+def test_init_with_safe_search_disabled(self):"""Initialize with safe_search disabled."""from local_deep_research.web_search_engines.engines.search_engine_serpapi import (diff --git a/tests/web_search_engines/engines/test_search_engine_tavily.py b/tests/web_search_engines/engines/test_search_engine_tavily.pyindex d6ba7a65db..4c7c4d80bd 100644--- a/tests/web_search_engines/engines/test_search_engine_tavily.py+++ b/tests/web_search_engines/engines/test_search_engine_tavily.py@@ -449,3 +449,235 @@ class TestClassAttributes:)assert TavilySearchEngine.is_generic is True+++class TestTimePeriod:+ """Tests for time_period handling (forwarded to Tavily time_range)."""++ def test_init_stores_time_period(self):+ """Constructor stores time_period on self.time_period."""+ from local_deep_research.web_search_engines.engines.search_engine_tavily import (+ TavilySearchEngine,+ )++ engine = TavilySearchEngine(api_key="test-key", time_period="w")+ assert engine.time_period == "w"++ def test_init_default_time_period(self):+ """Constructor default time_period is 'all' (unfiltered)."""+ from local_deep_research.web_search_engines.engines.search_engine_tavily import (+ TavilySearchEngine,+ )++ engine = TavilySearchEngine(api_key="test-key")+ assert engine.time_period == "all"++ def test_get_previews_sends_time_range_day(self):+ """time_period='d' maps to Tavily time_range='day'."""+ from local_deep_research.web_search_engines.engines.search_engine_tavily import (+ TavilySearchEngine,+ )++ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json.return_value = {"results": []}++ with patch(+ "local_deep_research.web_search_engines.engines.search_engine_tavily.safe_post",+ return_value=mock_response,+ ) as mock_post:+ engine = TavilySearchEngine(api_key="test-key", time_period="d")+ engine._get_previews("test query")++ payload = mock_post.call_args[1]["json"]+ assert payload["time_range"] == "day"++ def test_get_previews_sends_time_range_month(self):+ """time_period='m' maps to Tavily time_range='month'."""+ from local_deep_research.web_search_engines.engines.search_engine_tavily import (+ TavilySearchEngine,+ )++ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json.return_value = {"results": []}++ with patch(+ "local_deep_research.web_search_engines.engines.search_engine_tavily.safe_post",+ return_value=mock_response,+ ) as mock_post:+ engine = TavilySearchEngine(api_key="test-key", time_period="m")+ engine._get_previews("test query")++ payload = mock_post.call_args[1]["json"]+ assert payload["time_range"] == "month"++ def test_get_previews_sends_time_range_year(self):+ """time_period='y' maps to Tavily time_range='year'."""+ from local_deep_research.web_search_engines.engines.search_engine_tavily import (+ TavilySearchEngine,+ )++ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json.return_value = {"results": []}++ with patch(+ "local_deep_research.web_search_engines.engines.search_engine_tavily.safe_post",+ return_value=mock_response,+ ) as mock_post:+ engine = TavilySearchEngine(api_key="test-key", time_period="y")+ engine._get_previews("test query")++ payload = mock_post.call_args[1]["json"]+ assert payload["time_range"] == "year"++ def test_get_previews_default_omits_time_range(self):+ """Default constructor (time_period='all') omits time_range."""+ from local_deep_research.web_search_engines.engines.search_engine_tavily import (+ TavilySearchEngine,+ )++ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json.return_value = {"results": []}++ with patch(+ "local_deep_research.web_search_engines.engines.search_engine_tavily.safe_post",+ return_value=mock_response,+ ) as mock_post:+ engine = TavilySearchEngine(api_key="test-key")+ engine._get_previews("test query")++ payload = mock_post.call_args[1]["json"]+ assert "time_range" not in payload++ def test_get_previews_omits_time_range_for_all(self):+ """time_period='all' omits time_range from the payload."""+ from local_deep_research.web_search_engines.engines.search_engine_tavily import (+ TavilySearchEngine,+ )++ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json.return_value = {"results": []}++ with patch(+ "local_deep_research.web_search_engines.engines.search_engine_tavily.safe_post",+ return_value=mock_response,+ ) as mock_post:+ engine = TavilySearchEngine(api_key="test-key", time_period="all")+ engine._get_previews("test query")++ payload = mock_post.call_args[1]["json"]+ assert "time_range" not in payload++ def test_time_range_map_matches_shared_valid_time_periods(self):+ """Drift guard: tavily's map covers exactly the shared canonical+ codes. VALID_TIME_PERIODS deliberately excludes "all" — that means+ "no filter" and is expressed by omitting time_range."""+ from local_deep_research.web_search_engines.engines.search_engine_tavily import (+ _TIME_RANGE_MAP,+ )+ from local_deep_research.web_search_engines.search_engine_base import (+ VALID_TIME_PERIODS,+ )++ assert set(_TIME_RANGE_MAP) == set(VALID_TIME_PERIODS)++ @pytest.mark.parametrize("bad_value", [{"a": 1}, ["y"], 7, True])+ def test_get_previews_non_string_time_period_omits_time_range(+ self, bad_value+ ):+ """Non-string time_period values (possible via programmatic+ construction) mean "no filter" — the request still goes out instead+ of dying on an unhashable dict lookup and returning empty results."""+ from local_deep_research.web_search_engines.engines.search_engine_tavily import (+ TavilySearchEngine,+ )++ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json.return_value = {"results": []}++ with patch(+ "local_deep_research.web_search_engines.engines.search_engine_tavily.safe_post",+ return_value=mock_response,+ ) as mock_post:+ engine = TavilySearchEngine(+ api_key="test-key", time_period=bad_value+ )+ engine._get_previews("test query")++ assert mock_post.called, (+ f"time_period={bad_value!r} must not prevent the API call"+ )+ payload = mock_post.call_args[1]["json"]+ assert "time_range" not in payload++ @pytest.mark.parametrize(+ "bad_value", [None, "", "garbage", "D", "Year", "y ", " y"]+ )+ def test_get_previews_unrecognized_time_period_omits_time_range(+ self, bad_value+ ):+ """Unrecognized time_period values omit time_range (no filter).++ The settings UI only emits the canonical d/w/m/y/all codes, so this+ is mostly a contract for programmatic callers. We deliberately do+ NOT .lower()/strip() — a mistyped value should fail visibly as+ "unfiltered" rather than being silently coerced.+ """+ from local_deep_research.web_search_engines.engines.search_engine_tavily import (+ TavilySearchEngine,+ )++ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json.return_value = {"results": []}++ with patch(+ "local_deep_research.web_search_engines.engines.search_engine_tavily.safe_post",+ return_value=mock_response,+ ) as mock_post:+ engine = TavilySearchEngine(+ api_key="test-key", time_period=bad_value+ )+ engine._get_previews("test query")++ payload = mock_post.call_args[1]["json"]+ assert "time_range" not in payload, (+ f"time_period={bad_value!r} should omit time_range, "+ f"got payload={payload!r}"+ )++ def test_get_previews_time_range_coexists_with_domain_filters(self):+ """time_range, include_domains, and exclude_domains all land in the+ same payload when set together. Regression guard against a future+ refactor that mutates the payload dict in the wrong order and+ silently drops one of the three.+ """+ from local_deep_research.web_search_engines.engines.search_engine_tavily import (+ TavilySearchEngine,+ )++ mock_response = Mock()+ mock_response.status_code = 200+ mock_response.json.return_value = {"results": []}++ with patch(+ "local_deep_research.web_search_engines.engines.search_engine_tavily.safe_post",+ return_value=mock_response,+ ) as mock_post:+ engine = TavilySearchEngine(+ api_key="test-key",+ time_period="d",+ include_domains=["example.com"],+ exclude_domains=["spam.example"],+ )+ engine._get_previews("test query")++ payload = mock_post.call_args[1]["json"]+ assert payload["time_range"] == "day"+ assert payload["include_domains"] == ["example.com"]+ assert payload["exclude_domains"] == ["spam.example"]diff --git a/tests/web_search_engines/engines/test_search_engine_wikinews_coverage.py b/tests/web_search_engines/engines/test_search_engine_wikinews_coverage.pyindex f7fc13836c..eb3cae07a1 100644--- a/tests/web_search_engines/engines/test_search_engine_wikinews_coverage.py+++ b/tests/web_search_engines/engines/test_search_engine_wikinews_coverage.py@@ -3,8 +3,9 @@ Coverage tests for WikinewsSearchEngine targeting statements not hit bythe existing test_search_engine_wikinews.py.Covers:-- __init__: time_period="all" (from_date = datetime.min); unknown time_period- falls back to 1-year delta; language not in WIKINEWS_LANGUAGES warning + default+- __init__: time_period="all" (from_date = datetime.min); unknown/non-string+ time_period applies no lower bound; language not in WIKINEWS_LANGUAGES+ warning + default- _adapt_date_range_for_query: UNCLEAR branch; LLM raises (exception handler);adaptive_search=True but no LLM returns early- _optimize_query_for_wikinews: empty 'query' field raises ValueError; TypeError/@@ -62,11 +63,24 @@ class TestInitExtra:engine = _engine(time_period="all")assert engine.from_date.year == 1- def test_unknown_time_period_falls_back_to_one_year(self):+ def test_unknown_time_period_applies_no_lower_bound(self):+ """Unrecognized values mean "no filter", matching the+ tavily/serpapi/brave unfiltered-on-unknown convention (#4936) —+ previously this silently imposed a 1-year window."""engine = _engine(time_period="UNKNOWN_PERIOD")- expected = datetime.now(UTC) - timedelta(days=365)- delta = abs((engine.from_date - expected).total_seconds())- assert delta < 60+ assert engine.from_date.year == 1++ def test_default_time_period_is_all(self):+ """The constructor default is "all" (no lower bound), aligned with+ the global search.time_period default."""+ engine = _engine()+ assert engine.from_date.year == 1++ def test_non_string_time_period_applies_no_lower_bound(self):+ """Non-string values (possible via programmatic construction) are+ treated as "no filter" instead of raising on the dict lookup."""+ engine = _engine(time_period={"bogus": True})+ assert engine.from_date.year == 1def test_language_not_in_wikinews_defaults_to_english(self):"""A language code that maps OK but is absent from WIKINEWS_LANGUAGES → 'en'."""diff --git a/tests/web_search_engines/test_search_engine_factory_coverage.py b/tests/web_search_engines/test_search_engine_factory_coverage.pyindex 743dfdc224..f036734491 100644--- a/tests/web_search_engines/test_search_engine_factory_coverage.py+++ b/tests/web_search_engines/test_search_engine_factory_coverage.py@@ -423,6 +423,126 @@ class TestMaxResultsDefaults:assert EngCls._call_kwargs["max_results"] == 5+class TestTimePeriodSnapshotFallback:+ """create_search_engine() pulls search.time_period from the snapshot.++ Direct callers (langgraph-agent strategy tools, the MCP server) build+ engines via create_search_engine() without a time_period kwarg; the+ snapshot fallback is what makes the user's Settings → Search → Time+ Period choice reach them (#4936).+ """++ def test_time_period_from_snapshot_dict_value(self):+ """search.time_period as {value: ...} reaches a forwarding engine."""+ 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)++ assert EngCls._call_kwargs["time_period"] == "d"++ def test_time_period_from_snapshot_bare_value(self):+ """Bare snapshot values are honored too — run_research_process's+ per-request override writes the raw string, not a {value: ...} dict."""+ 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": "m"}++ with _patches(+ config_return={"tavily": _engine_config()},+ class_return=EngCls,+ ):+ create_search_engine("tavily", settings_snapshot=snapshot)++ assert EngCls._call_kwargs["time_period"] == "m"++ def test_explicit_time_period_kwarg_beats_snapshot(self):+ """An explicit kwarg (e.g. from get_search) is never overridden."""+ 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="w"+ )++ 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."""+ 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": "all"})+ },+ class_return=EngCls,+ ):+ create_search_engine("tavily", settings_snapshot=snapshot)++ 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."""+ 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={"brave": _engine_config()},+ class_return=EngCls,+ ):+ create_search_engine("brave", 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."""+ 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()},+ class_return=EngCls,+ ):+ create_search_engine("tavily", settings_snapshot=snapshot)++ assert "time_period" not in EngCls._call_kwargs++# ---------------------------------------------------------------------------# Tests: Display label fallback (end-to-end)# ---------------------------------------------------------------------------@@ -946,6 +1066,51 @@ class TestGetSearchParameterRouting:assert call_kwargs["search_language"] == "French"assert call_kwargs["adaptive_search"] is False+ def test_get_search_tavily_forwards_time_period(self):+ """Tavily gets time_period forwarded (regression guard for #4936)."""+ from local_deep_research.web_search_engines.search_engine_factory import (+ get_search,+ )++ with patch(+ "local_deep_research.web_search_engines.search_engine_factory.create_search_engine"+ ) as mock_create:+ mock_create.return_value = Mock(run=Mock())++ get_search(+ search_tool="tavily",+ llm_instance=Mock(),+ time_period="w",+ settings_snapshot={},+ )++ 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.+ """+ from local_deep_research.web_search_engines.search_engine_factory import (+ get_search,+ )++ with patch(+ "local_deep_research.web_search_engines.search_engine_factory.create_search_engine"+ ) as mock_create:+ mock_create.return_value = Mock(run=Mock())++ get_search(+ search_tool="tavily",+ llm_instance=Mock(),+ settings_snapshot={},+ )++ call_kwargs = mock_create.call_args[1]+ assert call_kwargs["time_period"] == "all"+def test_get_search_sofya_params(self):"""Sofya gets search_snippets_only forwarded: it derives its requestdepth from it (paid 'basic' depth only when content is consumed)."""