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): add Federal Register search engine (#5153)

LearningCircuit9abef5b77c91
diff --git a/changelog.d/+federal-register-search.feature.md b/changelog.d/+federal-register-search.feature.md
new file mode 100644
index 0000000000..4fa69df7da
--- /dev/null
+++ b/changelog.d/+federal-register-search.feature.md
@@ -0,0 +1 @@
+Federal Register is now available as a search engine for finding and retrieving U.S. government documents. Concurrent searches keep independent full-content budgets, cached results, and failure outcomes.
diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md
index 0ab8957c15..0f62b0a819 100644
--- a/docs/CONFIGURATION.md
+++ b/docs/CONFIGURATION.md
@@ -290,6 +290,17 @@ They are not available in the Web UI because they are needed to start the applic
| `search.engine.web.exa.supports_full_search` | `LDR_SEARCH_ENGINE_WEB_EXA_SUPPORTS_FULL_SEARCH` | `true` | Indicates this engine can fetch full page content after initial search, not just snippets. | SEARCH |
| `search.engine.web.exa.use_in_auto_search` | `LDR_SEARCH_ENGINE_WEB_EXA_USE_IN_AUTO_SEARCH` | `false` | Include Exa in auto search mode | SEARCH |
| `search.engine.web.exa.weaknesses` | `LDR_SEARCH_ENGINE_WEB_EXA_WEAKNESSES` | ``["requires API key with usage limits", "newer service still evolving", "costs scale with usage"]`` | Limitations: Requires paid API key with usage limits, newer service with evolving features. | SEARCH |
+| `search.engine.web.federal_register.agent_enabled` | `LDR_SEARCH_ENGINE_WEB_FEDERAL_REGISTER_AGENT_ENABLED` | `true` | Include Federal Register as a specialized tool for the langgraph research agent. The engine selected as `search.tool` always keeps its generic web_search tool — this flag only controls additional specialized tools. Independent of egress; the per-collection 'available to the research agent' toggle still wins for collections. | SEARCH |
+| `search.engine.web.federal_register.default_params.document_types` | `LDR_SEARCH_ENGINE_WEB_FEDERAL_REGISTER_DEFAULT_PARAMS_DOCUMENT_TYPES` | ``[]`` | Federal Register document types to include in search results. Valid values: RULE (final rules), PRORULE (proposed rules), NOTICE (notices), PRESDOCU (presidential documents), CORRECT (corrections), UNKNOWN (uncategorized documents), SUNSHINE (Sunshine Act documents, a legacy type); case-insensitive. Leave empty to search all types. Any other value is ignored with a warning. | SEARCH |
+| `search.engine.web.federal_register.description` | `LDR_SEARCH_ENGINE_WEB_FEDERAL_REGISTER_DESCRIPTION` | `FederalRegister.gov informational edition search for rules, proposed rules, notices, and presidential documents; not the official legal edition. Verify against GovInfo for legal reliance.` | Human-readable description of the search engine. | SEARCH |
+| `search.engine.web.federal_register.display_name` | `LDR_SEARCH_ENGINE_WEB_FEDERAL_REGISTER_DISPLAY_NAME` | `Federal Register` | Display name to use in the U.I. for this search engine. | SEARCH |
+| `search.engine.web.federal_register.reliability` | `LDR_SEARCH_ENGINE_WEB_FEDERAL_REGISTER_RELIABILITY` | `0.95` | Reliability of the Federal Register search engine. | SEARCH |
+| `search.engine.web.federal_register.requires_api_key` | `LDR_SEARCH_ENGINE_WEB_FEDERAL_REGISTER_REQUIRES_API_KEY` | `false` | Whether this search engine requires an API key. | SEARCH |
+| `search.engine.web.federal_register.requires_llm` | `LDR_SEARCH_ENGINE_WEB_FEDERAL_REGISTER_REQUIRES_LLM` | `false` | Whether this search engine requires an LLM. | SEARCH |
+| `search.engine.web.federal_register.strengths` | `LDR_SEARCH_ENGINE_WEB_FEDERAL_REGISTER_STRENGTHS` | ``["FederalRegister.gov informational edition, not the official legal edition", "Searches rules, proposed rules, notices, and presidential documents", "Verify against GovInfo for legal reliance", "No API key required"]`` | Strengths of this search engine. | SEARCH |
+| `search.engine.web.federal_register.supports_full_search` | `LDR_SEARCH_ENGINE_WEB_FEDERAL_REGISTER_SUPPORTS_FULL_SEARCH` | `false` | Whether this search engine supports generic full document search. | SEARCH |
+| `search.engine.web.federal_register.use_in_auto_search` | `LDR_SEARCH_ENGINE_WEB_FEDERAL_REGISTER_USE_IN_AUTO_SEARCH` | `false` | Include Federal Register in auto search mode. | SEARCH |
+| `search.engine.web.federal_register.weaknesses` | `LDR_SEARCH_ENGINE_WEB_FEDERAL_REGISTER_WEAKNESSES` | ``["Focused on Federal Register documents", "API requests are limited to 20 results by the adapter"]`` | Weaknesses of this search engine. | SEARCH |
| `search.engine.web.github.agent_enabled` | `LDR_SEARCH_ENGINE_WEB_GITHUB_AGENT_ENABLED` | `false` | Include GitHub as a specialized tool for the langgraph research agent. The engine selected as `search.tool` always keeps its generic web_search tool — this flag only controls additional specialized tools. Independent of egress; the per-collection 'available to the research agent' toggle still wins for collections. | SEARCH |
| `search.engine.web.github.api_key` | `LDR_SEARCH_ENGINE_WEB_GITHUB_API_KEY` | `` | GitHub Personal Access Token for API authentication. Without this, you're limited to 10 requests/minute for search API. With authentication, you get 30 requests/minute for search API. | SEARCH |
| `search.engine.web.github.default_params.include_issues` | `LDR_SEARCH_ENGINE_WEB_GITHUB_DEFAULT_PARAMS_INCLUDE_ISSUES` | `false` | Include recent GitHub issues in repository search results. | SEARCH |
diff --git a/src/local_deep_research/defaults/settings/search_engines/federal_register.json b/src/local_deep_research/defaults/settings/search_engines/federal_register.json
new file mode 100644
index 0000000000..30673b65ef
--- /dev/null
+++ b/src/local_deep_research/defaults/settings/search_engines/federal_register.json
@@ -0,0 +1,172 @@
+{
+ "search.engine.web.federal_register.display_name": {
+ "category": "federal_register",
+ "description": "Display name to use in the U.I. for this search engine.",
+ "editable": false,
+ "max_value": null,
+ "min_value": null,
+ "name": "Display Name",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "text",
+ "value": "Federal Register",
+ "visible": false
+ },
+ "search.engine.web.federal_register.description": {
+ "category": "federal_register",
+ "description": "Human-readable description of the search engine.",
+ "editable": false,
+ "max_value": null,
+ "min_value": null,
+ "name": "Description",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "text",
+ "value": "FederalRegister.gov informational edition search for rules, proposed rules, notices, and presidential documents; not the official legal edition. Verify against GovInfo for legal reliance.",
+ "visible": false
+ },
+ "search.engine.web.federal_register.default_params.document_types": {
+ "category": "federal_register",
+ "description": "Federal Register document types to include in search results. Valid values: RULE (final rules), PRORULE (proposed rules), NOTICE (notices), PRESDOCU (presidential documents), CORRECT (corrections), UNKNOWN (uncategorized documents), SUNSHINE (Sunshine Act documents, a legacy type); case-insensitive. Leave empty to search all types. Any other value is ignored with a warning.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Document Types",
+ "options": [
+ "RULE",
+ "PRORULE",
+ "NOTICE",
+ "PRESDOCU",
+ "CORRECT",
+ "UNKNOWN",
+ "SUNSHINE"
+ ],
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "multiselect",
+ "value": [],
+ "visible": true
+ },
+ "search.engine.web.federal_register.reliability": {
+ "category": "federal_register",
+ "description": "Reliability of the Federal Register search engine.",
+ "editable": true,
+ "max_value": 1.0,
+ "min_value": 0.0,
+ "name": "Reliability",
+ "options": null,
+ "step": 0.05,
+ "type": "SEARCH",
+ "ui_element": "range",
+ "value": 0.95,
+ "visible": true
+ },
+ "search.engine.web.federal_register.requires_api_key": {
+ "category": "federal_register",
+ "description": "Whether this search engine requires an API key.",
+ "editable": false,
+ "max_value": null,
+ "min_value": null,
+ "name": "Requires Api Key",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "checkbox",
+ "value": false,
+ "visible": false
+ },
+ "search.engine.web.federal_register.requires_llm": {
+ "category": "federal_register",
+ "description": "Whether this search engine requires an LLM.",
+ "editable": false,
+ "max_value": null,
+ "min_value": null,
+ "name": "Requires LLM",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "checkbox",
+ "value": false,
+ "visible": false
+ },
+ "search.engine.web.federal_register.supports_full_search": {
+ "category": "federal_register",
+ "description": "Whether this search engine supports generic full document search.",
+ "editable": false,
+ "max_value": null,
+ "min_value": null,
+ "name": "Supports Full Search",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "checkbox",
+ "value": false,
+ "visible": false
+ },
+ "search.engine.web.federal_register.strengths": {
+ "category": "federal_register",
+ "description": "Strengths of this search engine.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Strengths",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "json",
+ "value": [
+ "FederalRegister.gov informational edition, not the official legal edition",
+ "Searches rules, proposed rules, notices, and presidential documents",
+ "Verify against GovInfo for legal reliance",
+ "No API key required"
+ ],
+ "visible": false
+ },
+ "search.engine.web.federal_register.weaknesses": {
+ "category": "federal_register",
+ "description": "Weaknesses of this search engine.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Weaknesses",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "json",
+ "value": [
+ "Focused on Federal Register documents",
+ "API requests are limited to 20 results by the adapter"
+ ],
+ "visible": false
+ },
+ "search.engine.web.federal_register.use_in_auto_search": {
+ "category": "federal_register",
+ "description": "Include Federal Register in auto search mode.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Include in Auto Search",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "checkbox",
+ "value": false,
+ "visible": true
+ },
+ "search.engine.web.federal_register.agent_enabled": {
+ "category": "federal_register",
+ "description": "Include Federal Register as a specialized tool for the langgraph research agent. The engine selected as `search.tool` always keeps its generic web_search tool — this flag only controls additional specialized tools. Independent of egress; the per-collection 'available to the research agent' toggle still wins for collections.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Available to Research Agent",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "checkbox",
+ "value": true,
+ "visible": true
+ }
+}
diff --git a/src/local_deep_research/security/module_whitelist.py b/src/local_deep_research/security/module_whitelist.py
index 7620168199..c1489889e5 100644
--- a/src/local_deep_research/security/module_whitelist.py
+++ b/src/local_deep_research/security/module_whitelist.py
@@ -34,6 +34,7 @@ ALLOWED_MODULE_PATHS: frozenset[str] = frozenset(
".engines.search_engine_ddg",
".engines.search_engine_elasticsearch",
".engines.search_engine_exa",
+ ".engines.search_engine_federal_register",
".engines.search_engine_github",
".engines.search_engine_google_pse",
".engines.search_engine_guardian",
@@ -83,6 +84,7 @@ ALLOWED_CLASS_NAMES: frozenset[str] = frozenset(
"ElasticsearchSearchEngine",
"GutenbergSearchEngine",
"ExaSearchEngine",
+ "FederalRegisterSearchEngine",
"FullSearchResults",
"GitHubSearchEngine",
"GooglePSESearchEngine",
diff --git a/src/local_deep_research/web_search_engines/engine_registry.py b/src/local_deep_research/web_search_engines/engine_registry.py
index 9eb8fb6e34..68ffde9294 100644
--- a/src/local_deep_research/web_search_engines/engine_registry.py
+++ b/src/local_deep_research/web_search_engines/engine_registry.py
@@ -40,6 +40,10 @@ ENGINE_REGISTRY: Dict[str, EngineEntry] = {
module_path=".engines.search_engine_exa",
class_name="ExaSearchEngine",
),
+ "federal_register": EngineEntry(
+ module_path=".engines.search_engine_federal_register",
+ class_name="FederalRegisterSearchEngine",
+ ),
"github": EngineEntry(
module_path=".engines.search_engine_github",
class_name="GitHubSearchEngine",
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_federal_register.py b/src/local_deep_research/web_search_engines/engines/search_engine_federal_register.py
new file mode 100644
index 0000000000..5561d3ad18
--- /dev/null
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_federal_register.py
@@ -0,0 +1,562 @@
+import time
+from dataclasses import dataclass, field
+from typing import Any, Dict, Final, List, Optional, cast
+from urllib.parse import quote
+
+import requests
+from langchain_core.language_models import BaseLLM
+from urllib3.exceptions import LocationParseError
+from urllib3.util import parse_url
+
+from ...security.safe_requests import safe_get
+from ...security.secure_logging import logger
+from ...security.ssrf_validator import RFC_FORBIDDEN_URL_CHARS_RE
+from ..engine_availability import retry_after_from_error
+from ..rate_limiting import RateLimitError
+from ..search_engine_base import (
+ BaseSearchEngine,
+ Exposure,
+ Sensitivity,
+ _SearchRunState,
+)
+
+
+FULL_CONTENT_DEADLINE_SECONDS: Final = 120
+FULL_CONTENT_MAX_CHARS: Final = 50000
+
+
+class _FullContentDeadlineReached(Exception):
+ """Internal signal that the full-content budget ran out mid-item.
+
+ Raised by ``_request_timeout`` and caught by ``_get_full_content``, so
+ every way of running out of time unwinds through a single path that
+ still returns one result per input item.
+ """
+
+
+class _UnexpectedResponseHost(Exception):
+ """A list response whose redirect chain ended off Federal Register."""
+
+
+@dataclass
+class _FederalRegisterRunState(_SearchRunState):
+ full_content_deadline: float | None = None
+ full_content_fetch_cache: dict[str, tuple[str | None, str | None]] = field(
+ default_factory=dict
+ )
+
+
+class FederalRegisterSearchEngine(BaseSearchEngine):
+ """Search rules, proposed rules, notices, and presidential documents."""
+
+ is_public = True
+ is_generic = False
+ is_scientific = False
+ is_lexical = True
+ needs_llm_relevance_filter = True
+ egress_sensitivity = Sensitivity.NON_SENSITIVE
+ egress_exposure = Exposure.EXPOSING
+
+ LIST_URL = "https://www.federalregister.gov/api/v1/documents.json"
+ DETAIL_URL = "https://www.federalregister.gov/api/v1/documents"
+ MAX_QUERY_LENGTH = 400
+ MAX_RESULTS = 20
+ REQUEST_TIMEOUT = 30
+ RAW_TEXT_HOSTS = frozenset(
+ {"www.federalregister.gov", "federalregister.gov"}
+ )
+ # The values the API's ``conditions[type][]`` filter accepts: the four
+ # the ``/documents/facets/type`` endpoint lists, plus CORRECT
+ # ("Correction"), UNKNOWN ("Uncategorized Document") and SUNSHINE
+ # ("Sunshine Act Document"), which the filter also recognises (its
+ # reply names the type) though the facet omits them. SUNSHINE is a
+ # legacy type that currently matches no documents. The API answers
+ # any other value (``"rule"``, ``"Rule"``, ``"RULES"``) with HTTP 200
+ # ``{"description": "Documents of type ", "count": 0}`` —
+ # indistinguishable from a query that matched nothing — so an unknown
+ # type must never be sent.
+ VALID_DOCUMENT_TYPES: Final = (
+ "RULE",
+ "PRORULE",
+ "NOTICE",
+ "PRESDOCU",
+ "CORRECT",
+ "UNKNOWN",
+ "SUNSHINE",
+ )
+
+ def __init__(
+ self,
+ max_results: int = 10,
+ document_types: Optional[List[str]] = None,
+ llm: Optional[BaseLLM] = None,
+ max_filtered_results: Optional[int] = None,
+ settings_snapshot: Optional[Dict[str, Any]] = None,
+ search_snippets_only: bool = True,
+ max_content_chars: int = FULL_CONTENT_MAX_CHARS,
+ **kwargs,
+ ):
+ super().__init__(
+ llm=llm,
+ max_filtered_results=max_filtered_results,
+ max_results=max_results,
+ settings_snapshot=settings_snapshot,
+ search_snippets_only=search_snippets_only,
+ **kwargs,
+ )
+ self.document_types = self._normalize_document_types(document_types)
+ self.max_content_chars = max_content_chars
+
+ def _new_search_run_state(self) -> _FederalRegisterRunState:
+ return _FederalRegisterRunState()
+
+ def _get_previews(self, query: str) -> List[Dict[str, Any]]:
+ result_limit = min(self.max_results, self.MAX_RESULTS)
+
+ try:
+ params: Dict[str, Any] = {
+ "conditions[term]": query[: self.MAX_QUERY_LENGTH],
+ "per_page": result_limit,
+ "order": "newest",
+ }
+ if self.document_types:
+ params["conditions[type][]"] = self.document_types
+ self._last_wait_time = self.rate_tracker.apply_rate_limit(
+ self.engine_type
+ )
+ response = safe_get(
+ self.LIST_URL,
+ params=params,
+ timeout=self.REQUEST_TIMEOUT,
+ )
+ # Checked before the 429: a rate limit (and Retry-After) from
+ # an off-host redirect target says nothing about Federal
+ # Register's own limit, and its body is not a Federal Register
+ # answer either.
+ self._raise_if_list_ended_off_host(response)
+ self._raise_if_rate_limited(response)
+ response.raise_for_status()
+ data = response.json()
+ except RateLimitError:
+ raise
+ except _UnexpectedResponseHost as error:
+ self._search_failed = True
+ self._record_search_failure(error)
+ logger.warning(
+ "Federal Register request ended on an unexpected host"
+ )
+ return []
+ except requests.exceptions.RequestException as error:
+ self._search_failed = True
+ self._record_search_failure(error)
+ status_code = getattr(
+ getattr(error, "response", None), "status_code", None
+ )
+ logger.warning(
+ "Federal Register request failed "
+ f"(status={status_code if status_code is not None else 'unknown'})"
+ )
+ return []
+ except (AttributeError, KeyError, TypeError, ValueError) as error:
+ self._search_failed = True
+ self._record_search_failure(error)
+ logger.warning("Federal Register response parsing failed")
+ return []
+
+ if not isinstance(data, dict):
+ self._search_failed = True
+ self._record_search_failure(
+ ValueError("Federal Register response was not an object")
+ )
+ logger.warning(
+ "Federal Register response did not contain an object"
+ )
+ return []
+ documents = data.get("results")
+ if documents is None and self._is_zero_match(data):
+ # FederalRegister.gov answers a query that matched nothing
+ # with ``{"description": ..., "count": 0}`` and no
+ # ``results`` key. That is a valid empty result, not a
+ # provider failure: it must neither fail the search in
+ # metrics nor cool the engine down for the rest of the run.
+ return []
+ if not isinstance(documents, list):
+ self._search_failed = True
+ self._record_search_failure(
+ ValueError("Federal Register response had no results list")
+ )
+ logger.warning("Federal Register response did not contain results")
+ return []
+
+ previews = []
+ for document in documents[:result_limit]:
+ if not isinstance(document, dict):
+ continue
+ document_number = document.get("document_number")
+ if not isinstance(document_number, str) or not document_number:
+ continue
+ previews.append(
+ {
+ "id": document_number,
+ "title": document.get("title") or "Untitled",
+ "link": document.get("html_url") or "",
+ "snippet": document.get("abstract")
+ or document.get("excerpts")
+ or "",
+ "type": document.get("type") or "",
+ "agencies": document.get("agencies") or [],
+ "publication_date": document.get("publication_date") or "",
+ "pdf_url": document.get("pdf_url") or "",
+ }
+ )
+ return previews
+
+ def _get_full_content(
+ self, relevant_items: List[Dict[str, Any]]
+ ) -> List[Dict[str, Any]]:
+ state = cast(_FederalRegisterRunState, self._get_search_run_state())
+ deadline = state.full_content_deadline
+ if deadline is None:
+ deadline = time.monotonic() + FULL_CONTENT_DEADLINE_SECONDS
+ state.full_content_deadline = deadline
+
+ fetch_cache = state.full_content_fetch_cache
+
+ pending = list(relevant_items)
+ results: List[Dict[str, Any]] = []
+ for position, item in enumerate(pending):
+ result = self._preview_fields(item)
+ document_number = result.get("id")
+ if not isinstance(document_number, str) or not document_number:
+ results.append(result)
+ continue
+
+ cached_fetch = fetch_cache.get(document_number)
+ if cached_fetch is not None and cached_fetch[1] is not None:
+ cached_content = cached_fetch[1]
+ result["full_content"] = cached_content
+ results.append(result)
+ continue
+
+ if time.monotonic() > deadline:
+ results.append(result)
+ results.extend(
+ self._drain_without_fetching(
+ pending[position + 1 :], fetch_cache
+ )
+ )
+ return results
+
+ try:
+ if cached_fetch is None:
+ self._last_wait_time = self.rate_tracker.apply_rate_limit(
+ self.engine_type
+ )
+ detail_response = safe_get(
+ f"{self.DETAIL_URL}/{quote(document_number, safe='')}.json",
+ timeout=self._request_timeout(deadline),
+ )
+ if self._ended_off_host(detail_response):
+ # Same reasoning as the list request: neither a 429
+ # nor a body from another host is Federal
+ # Register's.
+ logger.warning(
+ "Federal Register detail request ended on an "
+ "unexpected host"
+ )
+ fetch_cache[document_number] = (None, None)
+ results.append(result)
+ continue
+ self._raise_if_rate_limited(detail_response)
+ detail_response.raise_for_status()
+ detail = detail_response.json()
+ if not isinstance(detail, dict):
+ logger.warning(
+ "Federal Register detail response did not contain an object"
+ )
+ fetch_cache[document_number] = (None, None)
+ results.append(result)
+ continue
+
+ raw_text_url = detail.get("raw_text_url")
+ if not isinstance(raw_text_url, str) or not raw_text_url:
+ fetch_cache[document_number] = (None, None)
+ results.append(result)
+ continue
+ if not self._is_allowed_raw_text_url(raw_text_url):
+ logger.warning(
+ "Federal Register raw-text URL had an unexpected host"
+ )
+ fetch_cache[document_number] = (None, None)
+ results.append(result)
+ continue
+ fetch_cache[document_number] = (raw_text_url, None)
+ else:
+ raw_text_url = cached_fetch[0]
+
+ if raw_text_url is None:
+ results.append(result)
+ continue
+
+ self._last_wait_time = self.rate_tracker.apply_rate_limit(
+ self.engine_type
+ )
+ try:
+ text_response = safe_get(
+ raw_text_url,
+ timeout=self._request_timeout(deadline),
+ require_https=True,
+ )
+ except ValueError as refusal:
+ # safe_get refuses (rather than fails) with ValueError:
+ # a redirect hop to cleartext, SSRF validation, or an
+ # oversized body. Log that as a refusal, not a parse
+ # failure, and never echo the URL (its query string can
+ # carry tokens). The result keeps its preview fields.
+ if "downgrade to cleartext" in str(refusal):
+ logger.warning(
+ "Federal Register raw-text fetch refused: "
+ "redirect to non-https"
+ )
+ else:
+ logger.warning(
+ "Federal Register raw-text fetch refused by the "
+ "request guard"
+ )
+ fetch_cache[document_number] = (None, None)
+ results.append(result)
+ continue
+ # Host check first: a 429 (and its Retry-After) from an
+ # off-host redirect target says nothing about Federal
+ # Register's own rate limit.
+ if not self._is_allowed_raw_text_url(
+ getattr(text_response, "url", None)
+ ):
+ logger.warning(
+ "Federal Register raw-text fetch ended on an "
+ "unexpected host"
+ )
+ fetch_cache[document_number] = (None, None)
+ results.append(result)
+ continue
+ self._raise_if_rate_limited(text_response)
+ text_response.raise_for_status()
+ full_content = self._truncate_full_content(text_response.text)
+ result["full_content"] = full_content
+ fetch_cache[document_number] = (raw_text_url, full_content)
+ except RateLimitError:
+ # The previews are already paid for. Re-raising would make
+ # ``BaseSearchEngine.run()`` retry the whole search and,
+ # once retries ran out, return [] — losing every preview
+ # over an optional enrichment. So a 429 here only stops
+ # further full-content fetches, exactly like the deadline.
+ # The availability cooldown is not recorded: usable results
+ # supersede a failure signal, and the next search's preview
+ # request raises its own RateLimitError if the limit holds.
+ # The adaptive rate limiter must still learn of the 429,
+ # though, or a sustained limit is re-hit by every search
+ # without the wait ever growing: the flag makes ``run()``
+ # record this attempt as a rate-limit failure instead of a
+ # success.
+ self._rate_limited_after_previews = True
+ results.append(result)
+ results.extend(
+ self._drain_without_fetching(
+ pending[position + 1 :],
+ fetch_cache,
+ reason="was rate limited (HTTP 429)",
+ )
+ )
+ return results
+ except _FullContentDeadlineReached:
+ results.append(result)
+ results.extend(
+ self._drain_without_fetching(
+ pending[position + 1 :], fetch_cache
+ )
+ )
+ return results
+ except requests.exceptions.RequestException as error:
+ status_code = getattr(
+ getattr(error, "response", None), "status_code", None
+ )
+ logger.warning(
+ "Federal Register full-content request failed "
+ f"(status={status_code if status_code is not None else 'unknown'})"
+ )
+ except (AttributeError, KeyError, TypeError, ValueError):
+ logger.warning("Federal Register full-content parsing failed")
+ results.append(result)
+ return results
+
+ @classmethod
+ def _normalize_document_types(cls, document_types: Any) -> List[str]:
+ """Strip, uppercase, de-duplicate and validate *document_types*.
+
+ Values outside ``VALID_DOCUMENT_TYPES`` are dropped with a warning
+ rather than sent: the API turns an unknown type into an empty
+ result, so one typo would otherwise make every search return
+ nothing. If every configured value is invalid the filter is
+ removed, i.e. all document types are searched.
+ """
+ normalized: List[str] = []
+ invalid_count = 0
+ for value in cls._ensure_list(document_types):
+ candidate = value.strip().upper() if isinstance(value, str) else ""
+ if candidate not in cls.VALID_DOCUMENT_TYPES:
+ invalid_count += 1
+ elif candidate not in normalized:
+ normalized.append(candidate)
+ if invalid_count:
+ logger.warning(
+ f"Ignoring {invalid_count} invalid Federal Register document "
+ f"type(s); valid values are {', '.join(cls.VALID_DOCUMENT_TYPES)}"
+ + ("" if normalized else ". Searching all document types.")
+ )
+ return normalized
+
+ @staticmethod
+ def _is_zero_match(data: Dict[str, Any]) -> bool:
+ """True for the API's no-match reply: an integer ``count`` of 0."""
+ count = data.get("count")
+ return (
+ isinstance(count, int)
+ and not isinstance(count, bool)
+ and (count == 0)
+ )
+
+ @staticmethod
+ def _raise_if_rate_limited(response: Any) -> None:
+ """Raise ``RateLimitError`` when *response* is an HTTP 429.
+
+ Decided by the status code alone. The base class's
+ ``_raise_if_rate_limit`` also matches phrases such as "throttl" or
+ "ratelimit" in an exception's text, and a ``requests`` exception's
+ text carries the request URL — here, the user's query — so a 400,
+ 5xx or connection error on a query like "FCC throttling rules"
+ would be misread as a rate limit (retries, a 300-second cooldown).
+ A 429's ``Retry-After`` is kept on the error; for the preview
+ request engine availability uses it as the cooldown (in the
+ full-content phase ``_get_full_content`` catches the error and only
+ stops fetching). (A 503 is not a rate limit here:
+ ``_record_search_failure`` classifies it as provider-unavailable.)
+ """
+ if getattr(response, "status_code", None) != 429:
+ return
+ raise RateLimitError(
+ "Federal Register rate limit reached (HTTP 429)",
+ retry_after=retry_after_from_error(
+ requests.HTTPError(response=response)
+ ),
+ )
+
+ def _raise_if_list_ended_off_host(self, response: Any) -> None:
+ """Raise ``_UnexpectedResponseHost`` for an off-host list response."""
+ if self._ended_off_host(response):
+ raise _UnexpectedResponseHost(
+ "Federal Register list request ended on an unexpected host"
+ )
+
+ def _ended_off_host(self, response: Any) -> bool:
+ """True when *response*'s final URL is not on a Federal Register host.
+
+ ``safe_get`` follows redirects, so a response can come from
+ wherever the last hop pointed. A response whose ``url`` is not a
+ string (a test double that never set one) is taken to come from
+ the requested Federal Register URL; ``requests`` always sets it.
+ """
+ final_url = getattr(response, "url", None)
+ return isinstance(final_url, str) and not self._is_allowed_raw_text_url(
+ final_url
+ )
+
+ @staticmethod
+ def _preview_fields(item: Dict[str, Any]) -> Dict[str, Any]:
+ """Copy an item's public fields, dropping internal ``_`` keys."""
+ return {
+ key: value for key, value in item.items() if not key.startswith("_")
+ }
+
+ def _drain_without_fetching(
+ self,
+ items: List[Dict[str, Any]],
+ fetch_cache: dict[str, tuple[str | None, str | None]],
+ reason: str = "exceeded its deadline",
+ ) -> List[Dict[str, Any]]:
+ """Return the items an expired deadline or a 429 stops us fetching.
+
+ ``BaseSearchEngine._get_full_content`` returns one result per input
+ item, and ``run()`` records the returned count as the search's
+ result count, so running out of time may only cost the
+ ``full_content`` key — never the title/link/snippet/agencies the
+ preview phase already paid for. Text already in ``fetch_cache``
+ costs nothing to hand back, so it still travels.
+ """
+ logger.info(
+ f"Full-content phase {reason}, returning the remaining "
+ "items without full content"
+ )
+ drained = []
+ for item in items:
+ result = self._preview_fields(item)
+ document_number = result.get("id")
+ cached_fetch = (
+ fetch_cache.get(document_number)
+ if isinstance(document_number, str)
+ else None
+ )
+ if cached_fetch is not None and cached_fetch[1] is not None:
+ result["full_content"] = cached_fetch[1]
+ drained.append(result)
+ return drained
+
+ def _request_timeout(self, deadline: float) -> int:
+ """Seconds to allow the next request, bounded by *deadline*.
+
+ Raises ``_FullContentDeadlineReached`` once the budget is spent.
+ The one-second floor keeps a sub-second remainder from truncating
+ to ``0``: ``int(0.4)`` is ``0``, and a zero timeout is not "no
+ limit" but an immediate failure, so the item burned its turn for
+ nothing.
+ """
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ raise _FullContentDeadlineReached
+ return min(self.REQUEST_TIMEOUT, max(1, int(remaining)))
+
+ def _is_allowed_raw_text_url(self, url: Any) -> bool:
+ """True when *url* is an ``https`` URL on a Federal Register host.
+
+ Parsed with ``urllib3.util.parse_url`` — the parser ``requests``
+ resolves the destination with — because ``urlparse`` disagrees
+ with it on backslash authorities (GHSA-g23j-2vwm-5c25), the same
+ reason ``security/ssrf_validator.py`` validates against urllib3:
+ ``https://evil.example\\@www.federalregister.gov/x`` has host
+ ``www.federalregister.gov`` to ``urlparse`` but connects to
+ ``evil.example``. The scheme and the RFC 3986 character class are
+ checked here too — the same rule ``validate_url`` applies — so
+ ``file://``, ``ftp://`` and every parser-differential payload are
+ refused by this guard alone rather than by a downstream layer.
+ """
+ if not isinstance(url, str) or not url:
+ return False
+ if RFC_FORBIDDEN_URL_CHARS_RE.search(url):
+ return False
+ try:
+ parsed = parse_url(url)
+ except LocationParseError:
+ return False
+ if (parsed.scheme or "").lower() != "https":
+ return False
+ return (parsed.host or "").lower() in self.RAW_TEXT_HOSTS
+
+ def _truncate_full_content(self, text: str) -> str:
+ """Bound one document's text before it reaches an LLM prompt.
+
+ Mirrors ``search_engine_gutenberg.py``'s ``max_content_chars``:
+ the raw-text endpoint serves whole rules, and the string is
+ inlined verbatim into the citation prompt.
+ """
+ if len(text) > self.max_content_chars:
+ return text[: self.max_content_chars] + "\n\n[... truncated ...]"
+ return text
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.py
index ee6e2303b4..026aee9bde 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
@@ -1,6 +1,8 @@
import json
import time
from abc import ABC, abstractmethod
+from contextvars import ContextVar
+from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Set, Union
from urllib.parse import urlparse
@@ -106,6 +108,14 @@ def _is_api_key_placeholder(api_key: Optional[str]) -> bool:
return False
+@dataclass
+class _SearchRunState:
+ """Outcomes belonging to one search invocation, including its retries."""
+
+ search_failed: bool = False
+ rate_limited_after_previews: bool = False
+
+
class AdaptiveWait(wait_base):
"""Custom wait strategy that uses adaptive rate limiting."""
@@ -272,6 +282,49 @@ class BaseSearchEngine(ABC):
# (see ``_secret_attrs``) after the live attribute is cleared.
_rejected_api_key: Optional[str] = None
+ def _new_search_run_state(self) -> _SearchRunState:
+ """Allow adapters to keep additional retry state in the same scope."""
+ return _SearchRunState()
+
+ def _search_run_state_var(self) -> ContextVar[Optional[_SearchRunState]]:
+ # Normally initialized in __init__; retain support for bare instances
+ # used to call individual adapter helpers without constructing an engine.
+ state_var: ContextVar[Optional[_SearchRunState]] | None = getattr(
+ self, "_search_run_state", None
+ )
+ if state_var is None:
+ state_var = ContextVar("search_run_state", default=None)
+ self._search_run_state = state_var
+ return state_var
+
+ def _get_search_run_state(self) -> _SearchRunState:
+ state_var = self._search_run_state_var()
+ state = state_var.get()
+ if state is None:
+ # Direct calls to private adapter helpers can share retry state in
+ # this context. Public run() always starts a fresh invocation.
+ state = self._new_search_run_state()
+ state_var.set(state)
+ return state
+
+ @property
+ def _search_failed(self) -> bool:
+ """An absorbed preview failure in the current search attempt."""
+ return self._get_search_run_state().search_failed
+
+ @_search_failed.setter
+ def _search_failed(self, value: bool) -> None:
+ self._get_search_run_state().search_failed = value
+
+ @property
+ def _rate_limited_after_previews(self) -> bool:
+ """An absorbed full-content HTTP 429 in the current search attempt."""
+ return self._get_search_run_state().rate_limited_after_previews
+
+ @_rate_limited_after_previews.setter
+ def _rate_limited_after_previews(self, value: bool) -> None:
+ self._get_search_run_state().rate_limited_after_previews = value
+
def _note_openalex_key_rejected(
self, api_key: Optional[str] = None
) -> None:
@@ -426,6 +479,7 @@ class BaseSearchEngine(ABC):
(pipeline-strategy fetch progress, #7193).
**kwargs: Additional engine-specific parameters
"""
+ self._search_run_state = ContextVar("search_run_state", default=None)
if max_filtered_results is None:
max_filtered_results = DEFAULT_MAX_FILTERED_RESULTS
if max_results is None:
@@ -735,6 +789,19 @@ class BaseSearchEngine(ABC):
Returns:
List of search results with full content (if available)
"""
+ state_var = self._search_run_state_var()
+ token = state_var.set(self._new_search_run_state())
+ try:
+ return self._run_search(query, research_context)
+ finally:
+ # Reset also restores the outer state for a nested run(), and
+ # cannot clear another thread's in-flight cache or outcome flags.
+ state_var.reset(token)
+
+ def _run_search(
+ self, query: str, research_context: Dict[str, Any] | None = None
+ ) -> List[Dict[str, Any]]:
+ """Execute and record one search inside its invocation state."""
logger.info(f"---Execute a search using {self.__class__.__name__}---")
# Runtime egress scope backstop: verify this engine is allowed
@@ -789,8 +856,13 @@ class BaseSearchEngine(ABC):
previews_received = False
try:
# Step 1: Get preview information for items
+ self._search_failed = False
+ self._rate_limited_after_previews = False
self.last_search_failure = None
previews = self._get_previews(query)
+ if self._search_failed:
+ success = False
+ error_message = "Preview retrieval failed"
if not previews:
logger.info(
f"Search engine {self.__class__.__name__} returned no preview results"
@@ -865,7 +937,25 @@ class BaseSearchEngine(ABC):
self._last_results_count = results_count
# Record success if we get here and rate limiting is enabled
- if self.rate_tracker.enabled:
+ if (
+ self.rate_tracker.enabled
+ and self._rate_limited_after_previews
+ ):
+ # The results are usable, but the provider answered a
+ # later request with HTTP 429: tell the limiter, as
+ # ``_record_retry_outcome`` does for a raised 429.
+ logger.info(
+ f"Recording rate-limited search for {self.engine_type}: wait_time={self._last_wait_time}s, results={results_count}"
+ )
+ self.rate_tracker.record_outcome(
+ self.engine_type,
+ self._last_wait_time or 0,
+ success=False,
+ retry_count=1,
+ error_type="RateLimitError",
+ search_result_count=results_count,
+ )
+ elif self.rate_tracker.enabled:
logger.info(
f"Recording successful search for {self.engine_type}: wait_time={self._last_wait_time}s, results={results_count}"
)
diff --git a/tests/security/test_egress_policy.py b/tests/security/test_egress_policy.py
index bc3c45b7c2..c4b285fb60 100644
--- a/tests/security/test_egress_policy.py
+++ b/tests/security/test_egress_policy.py
@@ -436,6 +436,7 @@ _PUBLIC_ENGINES = [
"brave",
"ddg",
"exa",
+ "federal_register",
"github",
"google_pse",
"guardian",
diff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.json
index 31263308ca..311a990e08 100644
--- a/tests/settings/golden_master_settings.json
+++ b/tests/settings/golden_master_settings.json
@@ -3761,6 +3761,176 @@
],
"visible": true
},
+ "search.engine.web.federal_register.agent_enabled": {
+ "category": "federal_register",
+ "description": "Include Federal Register as a specialized tool for the langgraph research agent. The engine selected as `search.tool` always keeps its generic web_search tool — this flag only controls additional specialized tools. Independent of egress; the per-collection 'available to the research agent' toggle still wins for collections.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Available to Research Agent",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "checkbox",
+ "value": true,
+ "visible": true
+ },
+ "search.engine.web.federal_register.default_params.document_types": {
+ "category": "federal_register",
+ "description": "Federal Register document types to include in search results. Valid values: RULE (final rules), PRORULE (proposed rules), NOTICE (notices), PRESDOCU (presidential documents), CORRECT (corrections), UNKNOWN (uncategorized documents), SUNSHINE (Sunshine Act documents, a legacy type); case-insensitive. Leave empty to search all types. Any other value is ignored with a warning.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Document Types",
+ "options": [
+ "RULE",
+ "PRORULE",
+ "NOTICE",
+ "PRESDOCU",
+ "CORRECT",
+ "UNKNOWN",
+ "SUNSHINE"
+ ],
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "multiselect",
+ "value": [],
+ "visible": true
+ },
+ "search.engine.web.federal_register.description": {
+ "category": "federal_register",
+ "description": "Human-readable description of the search engine.",
+ "editable": false,
+ "max_value": null,
+ "min_value": null,
+ "name": "Description",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "text",
+ "value": "FederalRegister.gov informational edition search for rules, proposed rules, notices, and presidential documents; not the official legal edition. Verify against GovInfo for legal reliance.",
+ "visible": false
+ },
+ "search.engine.web.federal_register.display_name": {
+ "category": "federal_register",
+ "description": "Display name to use in the U.I. for this search engine.",
+ "editable": false,
+ "max_value": null,
+ "min_value": null,
+ "name": "Display Name",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "text",
+ "value": "Federal Register",
+ "visible": false
+ },
+ "search.engine.web.federal_register.reliability": {
+ "category": "federal_register",
+ "description": "Reliability of the Federal Register search engine.",
+ "editable": true,
+ "max_value": 1.0,
+ "min_value": 0.0,
+ "name": "Reliability",
+ "options": null,
+ "step": 0.05,
+ "type": "SEARCH",
+ "ui_element": "range",
+ "value": 0.95,
+ "visible": true
+ },
+ "search.engine.web.federal_register.requires_api_key": {
+ "category": "federal_register",
+ "description": "Whether this search engine requires an API key.",
+ "editable": false,
+ "max_value": null,
+ "min_value": null,
+ "name": "Requires Api Key",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "checkbox",
+ "value": false,
+ "visible": false
+ },
+ "search.engine.web.federal_register.requires_llm": {
+ "category": "federal_register",
+ "description": "Whether this search engine requires an LLM.",
+ "editable": false,
+ "max_value": null,
+ "min_value": null,
+ "name": "Requires LLM",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "checkbox",
+ "value": false,
+ "visible": false
+ },
+ "search.engine.web.federal_register.strengths": {
+ "category": "federal_register",
+ "description": "Strengths of this search engine.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Strengths",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "json",
+ "value": [
+ "FederalRegister.gov informational edition, not the official legal edition",
+ "Searches rules, proposed rules, notices, and presidential documents",
+ "Verify against GovInfo for legal reliance",
+ "No API key required"
+ ],
+ "visible": false
+ },
+ "search.engine.web.federal_register.supports_full_search": {
+ "category": "federal_register",
+ "description": "Whether this search engine supports generic full document search.",
+ "editable": false,
+ "max_value": null,
+ "min_value": null,
+ "name": "Supports Full Search",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "checkbox",
+ "value": false,
+ "visible": false
+ },
+ "search.engine.web.federal_register.use_in_auto_search": {
+ "category": "federal_register",
+ "description": "Include Federal Register in auto search mode.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Include in Auto Search",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "checkbox",
+ "value": false,
+ "visible": true
+ },
+ "search.engine.web.federal_register.weaknesses": {
+ "category": "federal_register",
+ "description": "Weaknesses of this search engine.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Weaknesses",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "json",
+ "value": [
+ "Focused on Federal Register documents",
+ "API requests are limited to 20 results by the adapter"
+ ],
+ "visible": false
+ },
"search.engine.web.github.agent_enabled": {
"category": "github",
"description": "Include GitHub as a specialized tool for the langgraph research agent. The engine selected as `search.tool` always keeps its generic web_search tool — this flag only controls additional specialized tools. Independent of egress; the per-collection 'available to the research agent' toggle still wins for collections.",
diff --git a/tests/web_search_engines/engines/test_search_engine_federal_register.py b/tests/web_search_engines/engines/test_search_engine_federal_register.py
new file mode 100644
index 0000000000..25fb8f2800
--- /dev/null
+++ b/tests/web_search_engines/engines/test_search_engine_federal_register.py
@@ -0,0 +1,939 @@
+from unittest.mock import Mock, call, patch
+
+import pytest
+import requests
+
+
+MODULE = "local_deep_research.web_search_engines.engines.search_engine_federal_register"
+LIST_URL = "https://www.federalregister.gov/api/v1/documents.json"
+RAW_TEXT_URL = (
+ "https://www.federalregister.gov/documents/full_text/text/2026/12345.txt"
+)
+
+
+def _make_engine(**kwargs):
+ from local_deep_research.web_search_engines.engines.search_engine_federal_register import (
+ FederalRegisterSearchEngine,
+ )
+
+ kwargs.setdefault("programmatic_mode", True)
+ return FederalRegisterSearchEngine(**kwargs)
+
+
+def _document(**changes):
+ return {
+ "document_number": "2026-12345",
+ "title": "Clean Air Standards",
+ "html_url": "https://www.federalregister.gov/documents/2026/12345",
+ "abstract": "The agency updates emissions standards.",
+ "excerpts": "Standards excerpt.",
+ "type": "Rule",
+ "agencies": [{"name": "Environmental Protection Agency"}],
+ "publication_date": "2026-01-15",
+ "pdf_url": "https://www.federalregister.gov/documents/2026/12345.pdf",
+ } | changes
+
+
+def _response(json_data=None, text="", url=RAW_TEXT_URL):
+ response = Mock()
+ response.status_code = 200
+ response.json.return_value = {} if json_data is None else json_data
+ response.text = text
+ response.url = url
+ return response
+
+
+def _parse_failure_response():
+ response = _response()
+ response.json.side_effect = ValueError("not json")
+ return response
+
+
+def _non_dict_body_response():
+ return _response([{"document_number": "2026-12345"}])
+
+
+def _missing_results_key_response():
+ return _response({"description": "Documents matching 'clean air'"})
+
+
+def _nonzero_count_without_results_response():
+ return _response({"count": 3})
+
+
+def _string_count_without_results_response():
+ return _response({"count": "0"})
+
+
+def _zero_match_response():
+ # The live API's reply to a query that matched nothing: no
+ # ``results`` key at all.
+ return _response(
+ {"description": "Documents matching 'clean air'", "count": 0}
+ )
+
+
+class TestFederalRegisterSearchEngine:
+ def test_init_forwards_settings_snapshot_and_programmatic_mode(self):
+ snapshot = {
+ "search.engine.web.federal_register.default_params.document_types": [
+ "RULE"
+ ]
+ }
+
+ engine = _make_engine(
+ settings_snapshot=snapshot,
+ programmatic_mode=True,
+ )
+
+ assert engine.settings_snapshot is snapshot
+ assert engine.programmatic_mode is True
+
+ def test_classification_is_public_specialized_and_exposing(self):
+ from local_deep_research.security.egress.classification import (
+ Exposure,
+ Sensitivity,
+ )
+ from local_deep_research.web_search_engines.engines.search_engine_federal_register import (
+ FederalRegisterSearchEngine,
+ )
+
+ assert FederalRegisterSearchEngine.is_public is True
+ assert FederalRegisterSearchEngine.is_generic is False
+ assert FederalRegisterSearchEngine.is_scientific is False
+ assert FederalRegisterSearchEngine.is_lexical is True
+ assert FederalRegisterSearchEngine.needs_llm_relevance_filter is True
+ assert (
+ FederalRegisterSearchEngine.egress_sensitivity
+ is Sensitivity.NON_SENSITIVE
+ )
+ assert FederalRegisterSearchEngine.egress_exposure is Exposure.EXPOSING
+
+ def test_get_previews_normalizes_documents_and_uses_list_contract(self):
+ long_query = "q" * 401
+ fallback_document = _document(
+ document_number="2026-54321",
+ abstract=None,
+ excerpts="Excerpt fallback.",
+ )
+ response = _response({"results": [_document(), fallback_document]})
+ engine = _make_engine(
+ max_results=99,
+ document_types=["RULE", "NOTICE"],
+ )
+ engine.rate_tracker = Mock()
+ engine.rate_tracker.apply_rate_limit.return_value = 0.0
+
+ with patch(f"{MODULE}.safe_get", return_value=response) as mock_get:
+ previews = engine._get_previews(long_query)
+
+ preview = previews[0]
+ assert preview["id"] == "2026-12345"
+ assert preview["title"] == "Clean Air Standards"
+ assert preview["link"] == _document()["html_url"]
+ assert preview["snippet"] == _document()["abstract"]
+ assert preview["type"] == "Rule"
+ assert preview["agencies"] == _document()["agencies"]
+ assert preview["publication_date"] == "2026-01-15"
+ assert preview["pdf_url"] == _document()["pdf_url"]
+ assert previews[1]["snippet"] == "Excerpt fallback."
+ assert mock_get.call_args.args[0] == LIST_URL
+ assert mock_get.call_args.kwargs["params"] == {
+ "conditions[term]": "q" * 400,
+ "conditions[type][]": ["RULE", "NOTICE"],
+ "order": "newest",
+ "per_page": 20,
+ }
+ engine.rate_tracker.apply_rate_limit.assert_called_once_with(
+ engine.engine_type
+ )
+
+ def test_get_previews_caps_overdelivered_documents_to_twenty(self):
+ documents = [
+ _document(document_number=f"2026-{index:05d}")
+ for index in range(25)
+ ]
+ engine = _make_engine(max_results=99)
+ engine.rate_tracker = Mock()
+ engine.rate_tracker.apply_rate_limit.return_value = 0.0
+
+ with patch(
+ f"{MODULE}.safe_get",
+ return_value=_response({"results": documents}),
+ ) as mock_get:
+ previews = engine._get_previews("clean air")
+
+ assert mock_get.call_args.kwargs["params"]["per_page"] == 20
+ assert len(previews) == 20
+
+ def test_run_snippets_only_makes_only_the_list_request(self):
+ response = _response({"results": [_document()]})
+ engine = _make_engine(search_snippets_only=True)
+
+ with patch(f"{MODULE}.safe_get", return_value=response) as mock_get:
+ results = engine.run("clean air")
+
+ assert mock_get.call_count == 1
+ assert mock_get.call_args.args[0] == LIST_URL
+ assert results[0]["id"] == "2026-12345"
+ assert "full_content" not in results[0]
+
+ def test_run_full_content_fetches_detail_and_server_text(self):
+ detail_url = f"{LIST_URL.removesuffix('.json')}/2026-12345.json"
+ list_response = _response({"results": [_document()]})
+ detail_response = _response({"raw_text_url": RAW_TEXT_URL})
+ text_response = _response(text="Full Federal Register document text.")
+ engine = _make_engine(
+ include_full_content=True,
+ search_snippets_only=False,
+ )
+ engine.rate_tracker = Mock()
+ engine.rate_tracker.enabled = False
+ request_events = Mock()
+ request_events.attach_mock(
+ engine.rate_tracker.apply_rate_limit,
+ "rate_limit",
+ )
+
+ with patch(
+ f"{MODULE}.safe_get",
+ side_effect=[list_response, detail_response, text_response],
+ ) as mock_get:
+ request_events.attach_mock(mock_get, "safe_get")
+ results = engine.run("clean air")
+
+ assert [event[0] for event in request_events.mock_calls] == [
+ "rate_limit",
+ "safe_get",
+ "rate_limit",
+ "safe_get",
+ "rate_limit",
+ "safe_get",
+ ]
+ assert engine.rate_tracker.apply_rate_limit.call_args_list == [
+ call(engine.engine_type),
+ call(engine.engine_type),
+ call(engine.engine_type),
+ ]
+ assert [call.args[0] for call in mock_get.call_args_list] == [
+ LIST_URL,
+ detail_url,
+ RAW_TEXT_URL,
+ ]
+ assert mock_get.call_args_list[2].kwargs["require_https"] is True
+ result = results[0]
+ assert result["title"] == "Clean Air Standards"
+ assert result["link"] == _document()["html_url"]
+ assert result["snippet"] == _document()["abstract"]
+ assert result["type"] == "Rule"
+ assert result["agencies"] == _document()["agencies"]
+ assert result["publication_date"] == "2026-01-15"
+ assert result["pdf_url"] == _document()["pdf_url"]
+ assert result["full_content"] == "Full Federal Register document text."
+
+ def test_get_previews_handles_request_failure_without_logging_query_url(
+ self,
+ ):
+ secret_query = "private-clean-air-query"
+ error_url = f"{LIST_URL}?conditions%5Bterm%5D={secret_query}"
+ error = requests.exceptions.RequestException(
+ f"request failed: {error_url}"
+ )
+ engine = _make_engine(programmatic_mode=False)
+
+ # search_engine_base.py binds its own module-level ``logger``
+ # (base.py:8, engine :9 — separate names for the same object), so
+ # patching only the engine module leaves the base class's
+ # "returned no preview results" line going to the real logger.
+ # Both are captured here: reverting that line to interpolate the
+ # query must fail this test, not slip through the engine patch.
+ with (
+ patch(f"{MODULE}.safe_get", side_effect=error),
+ patch(f"{MODULE}.logger") as mock_logger,
+ patch(
+ "local_deep_research.web_search_engines.search_engine_base.logger"
+ ) as mock_base_logger,
+ patch(
+ "local_deep_research.metrics.search_tracker.SearchTracker.record_search"
+ ) as record_search,
+ ):
+ previews = engine.run(secret_query)
+
+ logged = " ".join(
+ str(argument)
+ for call in mock_logger.mock_calls
+ for argument in call.args
+ )
+ base_logged = " ".join(
+ str(argument)
+ for call in mock_base_logger.mock_calls
+ for argument in call.args
+ )
+ assert previews == []
+ assert secret_query not in logged
+ assert error_url not in logged
+ assert secret_query not in base_logged
+ assert error_url not in base_logged
+ # Not vacuous: the redacted line really did run.
+ # The base line itself is redacted on main (no query, no length);
+ # its exact text is pinned by
+ # tests/web_search_engines/test_search_engine_base_query_logging.py.
+ assert "returned no preview results" in base_logged
+ assert record_search.call_args.kwargs["success"] is False
+ mock_logger.exception.assert_not_called()
+
+ def test_get_previews_raises_rate_limit_error_for_429(self):
+ from local_deep_research.web_search_engines.rate_limiting import (
+ RateLimitError,
+ )
+
+ response = _response()
+ response.status_code = 429
+ engine = _make_engine()
+
+ with patch(f"{MODULE}.safe_get", return_value=response):
+ with pytest.raises(RateLimitError):
+ engine._get_previews("clean air")
+
+ def test_get_previews_429_carries_retry_after(self):
+ from local_deep_research.web_search_engines.rate_limiting import (
+ RateLimitError,
+ )
+
+ response = _response()
+ response.status_code = 429
+ response.headers = {"Retry-After": "120"}
+ engine = _make_engine()
+
+ with patch(f"{MODULE}.safe_get", return_value=response):
+ with pytest.raises(RateLimitError) as raised:
+ engine._get_previews("clean air")
+
+ assert raised.value.retry_after == 120
+
+ def test_get_previews_request_failure_records_engine_failure(self):
+ engine = _make_engine()
+
+ with patch(
+ f"{MODULE}.safe_get",
+ side_effect=requests.exceptions.ConnectionError("offline"),
+ ):
+ assert engine._get_previews("clean air") == []
+
+ assert engine._search_failed is True
+ assert engine.last_search_failure is not None
+
+ @pytest.mark.parametrize(
+ "requests_after_list",
+ [
+ (requests.exceptions.RequestException("detail private-marker"),),
+ (
+ _response({"raw_text_url": RAW_TEXT_URL}),
+ requests.exceptions.RequestException("text private-marker"),
+ ),
+ (_response({"raw_text_url": "https://example.com/document.txt"}),),
+ (
+ _response(
+ {
+ "raw_text_url": "https://evil.example\\@www.federalregister.gov/x.txt"
+ }
+ ),
+ ),
+ ],
+ ids=[
+ "detail",
+ "raw-text",
+ "external-raw-text-host",
+ "backslash-authority-raw-text-host",
+ ],
+ )
+ def test_run_preserves_metadata_when_full_content_unavailable(
+ self, requests_after_list
+ ):
+ list_response = _response({"results": [_document()]})
+ engine = _make_engine(search_snippets_only=False)
+
+ with patch(
+ f"{MODULE}.safe_get",
+ side_effect=[list_response, *requests_after_list],
+ ):
+ results = engine.run("clean air")
+
+ result = results[0]
+ assert result["id"] == "2026-12345"
+ assert result["title"] == "Clean Air Standards"
+ assert result["link"] == _document()["html_url"]
+ assert result["snippet"] == _document()["abstract"]
+ assert result["type"] == "Rule"
+ assert result["agencies"] == _document()["agencies"]
+ assert result["publication_date"] == "2026-01-15"
+ assert result["pdf_url"] == _document()["pdf_url"]
+ assert all(not key.startswith("_") for key in result)
+ assert "private-marker" not in str(result)
+
+ @pytest.mark.parametrize(
+ "raw_text_url",
+ [
+ "https://evil.example\\@www.federalregister.gov/x.txt",
+ "https://www.federalregister.gov\\@evil.example/x.txt",
+ "file://www.federalregister.gov/etc/passwd",
+ "file:///etc/passwd",
+ "ftp://www.federalregister.gov/document.txt",
+ "http://www.federalregister.gov/document.txt",
+ "https://www.federalregister.gov.evil.example/document.txt",
+ "//www.federalregister.gov/document.txt",
+ "",
+ ],
+ ids=[
+ "backslash-authority",
+ "backslash-path-delimiter",
+ "file-with-host",
+ "file-no-host",
+ "ftp",
+ "http",
+ "suffix-host",
+ "scheme-relative",
+ "empty",
+ ],
+ )
+ def test_raw_text_guard_refuses_non_https_and_off_host_urls(
+ self, raw_text_url
+ ):
+ """The engine's own guard refuses these, with no downstream help.
+
+ ``urlparse`` reads the backslash-authority URL as
+ ``www.federalregister.gov`` while ``requests``/urllib3 connect to
+ ``evil.example`` (GHSA-g23j-2vwm-5c25), so the guard parses with
+ urllib3 exactly like ``security/ssrf_validator.py`` does, and
+ checks the scheme itself rather than relying on ``safe_get``.
+ """
+ engine = _make_engine()
+
+ assert engine._is_allowed_raw_text_url(raw_text_url) is False
+
+ @pytest.mark.parametrize(
+ "raw_text_url",
+ [
+ RAW_TEXT_URL,
+ "https://federalregister.gov/documents/full_text/text/1.txt",
+ "https://WWW.FEDERALREGISTER.GOV/documents/full_text/text/1.txt",
+ ],
+ ids=["www", "apex", "uppercase-host"],
+ )
+ def test_raw_text_guard_allows_https_federal_register_urls(
+ self, raw_text_url
+ ):
+ engine = _make_engine()
+
+ assert engine._is_allowed_raw_text_url(raw_text_url) is True
+
+ def test_run_discards_full_content_when_the_fetch_ends_off_host(self):
+ """A redirect off federalregister.gov must not become document text.
+
+ ``safe_requests`` re-validates each redirect hop against the SSRF
+ rules, but not against this engine's host allow-list, so the
+ allow-list has to be re-checked against the response's final URL.
+ """
+ list_response = _response({"results": [_document()]})
+ detail_response = _response({"raw_text_url": RAW_TEXT_URL})
+ text_response = _response(
+ text="attacker supplied body",
+ url="https://evil.example/redirected.txt",
+ )
+ engine = _make_engine(search_snippets_only=False)
+
+ with patch(
+ f"{MODULE}.safe_get",
+ side_effect=[list_response, detail_response, text_response],
+ ):
+ results = engine.run("clean air")
+
+ result = results[0]
+ assert "full_content" not in result
+ assert "attacker supplied body" not in str(result)
+ assert result["id"] == "2026-12345"
+ assert result["title"] == "Clean Air Standards"
+ assert result["snippet"] == _document()["abstract"]
+
+ def test_run_logs_a_refused_https_downgrade_distinctly_without_the_url(
+ self,
+ ):
+ """A raw-text redirect to cleartext is a refusal, not a parse error.
+
+ ``safe_get(require_https=True)`` raises ``ValueError`` naming the
+ redirect target; the engine must log it as a refusal without that
+ URL (its query string can carry tokens) and keep the preview result.
+ """
+ downgrade_url = "http://www.federalregister.gov/x.txt?token=secret"
+ list_response = _response({"results": [_document()]})
+ detail_response = _response({"raw_text_url": RAW_TEXT_URL})
+ engine = _make_engine(search_snippets_only=False)
+
+ with (
+ patch(
+ f"{MODULE}.safe_get",
+ side_effect=[
+ list_response,
+ detail_response,
+ ValueError(
+ f"Redirect would downgrade to cleartext: {downgrade_url}"
+ ),
+ ],
+ ),
+ patch(f"{MODULE}.logger") as mock_logger,
+ ):
+ results = engine.run("clean air")
+
+ logged = " ".join(
+ str(argument)
+ for call in mock_logger.mock_calls
+ for argument in call.args
+ )
+ assert "raw-text fetch refused: redirect to non-https" in logged
+ assert "parsing failed" not in logged
+ assert "token=secret" not in logged
+ assert downgrade_url not in logged
+ result = results[0]
+ assert "full_content" not in result
+ assert result["id"] == "2026-12345"
+ assert result["snippet"] == _document()["abstract"]
+
+ def test_run_truncates_full_content_to_max_content_chars(self):
+ list_response = _response({"results": [_document()]})
+ detail_response = _response({"raw_text_url": RAW_TEXT_URL})
+ text_response = _response(text="x" * 5000, url=RAW_TEXT_URL)
+ engine = _make_engine(
+ search_snippets_only=False,
+ max_content_chars=100,
+ )
+
+ with patch(
+ f"{MODULE}.safe_get",
+ side_effect=[list_response, detail_response, text_response],
+ ):
+ results = engine.run("clean air")
+
+ assert (
+ results[0]["full_content"] == "x" * 100 + "\n\n[... truncated ...]"
+ )
+
+ def test_full_content_cap_defaults_to_fifty_thousand_characters(self):
+ engine = _make_engine()
+
+ assert engine.max_content_chars == 50000
+ assert engine._truncate_full_content("x" * 50000) == "x" * 50000
+ assert (
+ engine._truncate_full_content("x" * 50001)
+ == "x" * 50000 + "\n\n[... truncated ...]"
+ )
+
+ @pytest.mark.parametrize(
+ "response_factory",
+ [
+ _parse_failure_response,
+ _non_dict_body_response,
+ _missing_results_key_response,
+ _nonzero_count_without_results_response,
+ _string_count_without_results_response,
+ ],
+ ids=[
+ "parse-failure",
+ "non-dict-body",
+ "missing-results-key",
+ "nonzero-count-without-results",
+ "string-count-without-results",
+ ],
+ )
+ def test_get_previews_latches_search_failed_on_unusable_payloads(
+ self, response_factory
+ ):
+ """An unusable payload is a failed search, not an empty one."""
+ engine = _make_engine()
+ assert engine._search_failed is False
+
+ with patch(f"{MODULE}.safe_get", return_value=response_factory()):
+ previews = engine._get_previews("clean air")
+
+ assert previews == []
+ assert engine._search_failed is True
+ # The engine-availability signal is set too, so a research run can
+ # tell a failing provider from a query that matched nothing.
+ assert engine.last_search_failure is not None
+
+ def test_get_previews_leaves_search_failed_unset_on_an_empty_result(self):
+ engine = _make_engine()
+
+ with patch(
+ f"{MODULE}.safe_get", return_value=_response({"results": []})
+ ):
+ previews = engine._get_previews("clean air")
+
+ assert previews == []
+ assert engine._search_failed is False
+ assert engine.last_search_failure is None
+
+ def test_get_previews_treats_the_zero_match_reply_as_an_empty_result(
+ self,
+ ):
+ """``{"count": 0}`` with no ``results`` key is "matched nothing".
+
+ Treating it as a payload failure would fail the search in metrics
+ and cool the engine down for the rest of a research run after a
+ few queries with no hits.
+ """
+ engine = _make_engine()
+
+ with patch(f"{MODULE}.safe_get", return_value=_zero_match_response()):
+ previews = engine._get_previews("clean air")
+
+ assert previews == []
+ assert engine._search_failed is False
+ assert engine.last_search_failure is None
+
+ def test_run_records_a_zero_match_query_as_a_successful_search(self):
+ engine = _make_engine(programmatic_mode=False)
+
+ with (
+ patch(f"{MODULE}.safe_get", return_value=_zero_match_response()),
+ patch(
+ "local_deep_research.metrics.search_tracker.SearchTracker.record_search"
+ ) as record_search,
+ ):
+ assert engine.run("clean air") == []
+
+ assert record_search.call_args.kwargs["success"] is True
+ assert engine.last_search_failure is None
+
+ @pytest.mark.parametrize(
+ "error",
+ [
+ requests.exceptions.ConnectionError(
+ f"{LIST_URL}?conditions%5Bterm%5D=FCC+throttling+rules offline"
+ ),
+ requests.exceptions.HTTPError(
+ f"500 Server Error for url: {LIST_URL}"
+ "?conditions%5Bterm%5D=ratelimit+rules"
+ ),
+ ],
+ ids=["connection-error-throttling-query", "http-500-ratelimit-query"],
+ )
+ def test_get_previews_does_not_read_a_rate_limit_from_the_query_text(
+ self, error
+ ):
+ """Rate limiting is decided by HTTP 429, never by exception text.
+
+ A ``requests`` exception's text carries the request URL, i.e. the
+ user's query; matching "throttl"/"ratelimit" in it would turn an
+ ordinary failure into retries and a 300-second cooldown.
+ """
+ engine = _make_engine()
+
+ with patch(f"{MODULE}.safe_get", side_effect=error):
+ assert engine._get_previews("FCC throttling rules") == []
+
+ assert engine._search_failed is True
+ assert engine.last_search_failure is not None
+ assert engine.last_search_failure.reason != "Rate limit reached"
+
+ def test_get_previews_400_on_a_throttle_query_is_not_a_rate_limit(self):
+ response = _response()
+ response.status_code = 400
+ response.raise_for_status.side_effect = requests.exceptions.HTTPError(
+ f"400 Client Error: Bad Request for url: {LIST_URL}"
+ "?conditions%5Bterm%5D=throttle+ratelimit",
+ response=response,
+ )
+ engine = _make_engine()
+
+ with patch(f"{MODULE}.safe_get", return_value=response):
+ assert engine._get_previews("throttle ratelimit") == []
+
+ # A rejected query is not reported to engine availability.
+ assert engine.last_search_failure is None
+
+ @pytest.mark.parametrize("phase", ["detail", "raw-text"])
+ def test_full_content_429_stops_fetching_and_keeps_every_preview(
+ self, phase
+ ):
+ """A 429 after the previews costs only ``full_content``.
+
+ Re-raising it would make ``run()`` retry the whole search and end
+ in ``[]``; instead the remaining items are drained unfetched.
+ """
+ limited = _response()
+ limited.status_code = 429
+ limited.headers = {"Retry-After": "90"}
+ responses = (
+ [limited]
+ if phase == "detail"
+ else [_response({"raw_text_url": RAW_TEXT_URL}), limited]
+ )
+ items = [
+ {"id": "2026-12345", "title": "One"},
+ {"id": "2026-54321", "title": "Two"},
+ ]
+ engine = _make_engine()
+ engine.rate_tracker = Mock()
+ engine.rate_tracker.apply_rate_limit.return_value = 0.0
+
+ with patch(f"{MODULE}.safe_get", side_effect=responses) as mock_get:
+ results = engine._get_full_content(items)
+
+ assert results == items
+ # Nothing is fetched for the second item after the 429.
+ assert mock_get.call_count == len(responses)
+
+ @pytest.mark.parametrize("phase", ["detail", "raw-text"])
+ def test_run_returns_previews_when_full_content_is_rate_limited(
+ self, phase
+ ):
+ """End to end: a full-content 429 must not cost the previews."""
+ documents = [
+ _document(),
+ _document(document_number="2026-54321", title="Second Rule"),
+ ]
+ limited = _response()
+ limited.status_code = 429
+ limited.headers = {"Retry-After": "90"}
+ responses = [_response({"results": documents})] + (
+ [limited]
+ if phase == "detail"
+ else [_response({"raw_text_url": RAW_TEXT_URL}), limited]
+ )
+ engine = _make_engine(search_snippets_only=False)
+ engine.rate_tracker = Mock()
+ engine.rate_tracker.enabled = True
+ engine.rate_tracker.apply_rate_limit.return_value = 0.0
+
+ with (
+ patch(f"{MODULE}.safe_get", side_effect=responses) as mock_get,
+ patch.object(engine, "_get_adaptive_wait", return_value=0.0),
+ ):
+ results = engine.run("clean air")
+
+ assert [result["id"] for result in results] == [
+ "2026-12345",
+ "2026-54321",
+ ]
+ assert results[1]["title"] == "Second Rule"
+ assert all("full_content" not in result for result in results)
+ # The search was not retried: one list request only.
+ assert mock_get.call_count == len(responses)
+ assert engine.last_search_failure is None
+
+ @pytest.mark.parametrize("phase", ["detail", "raw-text"])
+ def test_run_records_a_full_content_429_with_the_rate_limiter(self, phase):
+ """The absorbed 429 still reaches the adaptive rate limiter.
+
+ Recording the search as a success instead would let a sustained
+ limit be re-hit by every search without the wait ever growing.
+ """
+ from local_deep_research.web_search_engines.rate_limiting.tracker import (
+ AdaptiveRateLimitTracker,
+ )
+
+ limited = _response()
+ limited.status_code = 429
+ responses = [
+ _response({"results": [_document()]}),
+ *(
+ [limited]
+ if phase == "detail"
+ else [_response({"raw_text_url": RAW_TEXT_URL}), limited]
+ ),
+ # The next search's full-content fetch succeeds.
+ _response({"results": [_document()]}),
+ _response({"raw_text_url": RAW_TEXT_URL}),
+ _response(text="full text"),
+ ]
+ engine = _make_engine(search_snippets_only=False)
+ engine.rate_tracker = Mock(spec=AdaptiveRateLimitTracker)
+ engine.rate_tracker.enabled = True
+ engine.rate_tracker.apply_rate_limit.return_value = 0.25
+
+ with (
+ patch(f"{MODULE}.safe_get", side_effect=responses),
+ patch.object(engine, "_get_adaptive_wait", return_value=0.0),
+ ):
+ first = engine.run("clean air")
+ second = engine.run("clean air")
+
+ assert [result["id"] for result in first] == ["2026-12345"]
+ assert second[0]["full_content"] == "full text"
+ assert engine.rate_tracker.record_outcome.call_args_list == [
+ call(
+ engine.engine_type,
+ 0.25,
+ success=False,
+ retry_count=1,
+ error_type="RateLimitError",
+ search_result_count=1,
+ ),
+ # The flag does not leak into the next search.
+ call(
+ engine.engine_type,
+ 0.25,
+ success=True,
+ retry_count=1,
+ search_result_count=1,
+ ),
+ ]
+
+ def test_off_host_list_429_is_not_a_federal_register_rate_limit(self):
+ """A list request redirected off-host is refused before the 429.
+
+ Neither ``RateLimitError`` nor the foreign ``Retry-After`` may
+ reach the limiter or the availability cooldown.
+ """
+ off_host_limited = _response(url="https://evil.example/limited.json")
+ off_host_limited.status_code = 429
+ off_host_limited.headers = {"Retry-After": "86400"}
+ engine = _make_engine()
+ engine.rate_tracker = Mock()
+ engine.rate_tracker.apply_rate_limit.return_value = 0.0
+
+ with patch(f"{MODULE}.safe_get", return_value=off_host_limited):
+ assert engine._get_previews("clean air") == []
+
+ off_host_limited.json.assert_not_called()
+ assert engine._search_failed is True
+ assert engine.last_search_failure is not None
+ assert engine.last_search_failure.cooldown_seconds != 86400
+ assert "rate limit" not in engine.last_search_failure.reason.lower()
+
+ def test_off_host_list_response_is_not_parsed(self):
+ off_host = _response(
+ {"results": [_document()]}, url="https://evil.example/list.json"
+ )
+ engine = _make_engine()
+ engine.rate_tracker = Mock()
+ engine.rate_tracker.apply_rate_limit.return_value = 0.0
+
+ with patch(f"{MODULE}.safe_get", return_value=off_host):
+ assert engine._get_previews("clean air") == []
+
+ off_host.json.assert_not_called()
+
+ def test_off_host_detail_429_does_not_stop_the_full_content_phase(self):
+ off_host_limited = _response(url="https://evil.example/detail.json")
+ off_host_limited.status_code = 429
+ off_host_limited.headers = {"Retry-After": "86400"}
+ engine = _make_engine()
+ engine.rate_tracker = Mock()
+ engine.rate_tracker.apply_rate_limit.return_value = 0.0
+
+ with patch(
+ f"{MODULE}.safe_get",
+ side_effect=[
+ off_host_limited,
+ _response({"raw_text_url": RAW_TEXT_URL}),
+ _response(text="second text"),
+ ],
+ ):
+ results = engine._get_full_content(
+ [{"id": "2026-12345"}, {"id": "2026-54321"}]
+ )
+
+ assert results == [
+ {"id": "2026-12345"},
+ {"id": "2026-54321", "full_content": "second text"},
+ ]
+ assert engine._rate_limited_after_previews is False
+
+ def test_off_host_429_does_not_count_as_a_federal_register_rate_limit(
+ self,
+ ):
+ """An off-host redirect target's 429 is refused by the host check.
+
+ It must neither raise ``RateLimitError`` nor stop the remaining
+ items from being fetched.
+ """
+ off_host_limited = _response(url="https://evil.example/limited.txt")
+ off_host_limited.status_code = 429
+ off_host_limited.headers = {"Retry-After": "86400"}
+ engine = _make_engine()
+ engine.rate_tracker = Mock()
+ engine.rate_tracker.apply_rate_limit.return_value = 0.0
+
+ with patch(
+ f"{MODULE}.safe_get",
+ side_effect=[
+ _response({"raw_text_url": RAW_TEXT_URL}),
+ off_host_limited,
+ _response({"raw_text_url": RAW_TEXT_URL}),
+ _response(text="second text"),
+ ],
+ ):
+ results = engine._get_full_content(
+ [{"id": "2026-12345"}, {"id": "2026-54321"}]
+ )
+
+ assert results == [
+ {"id": "2026-12345"},
+ {"id": "2026-54321", "full_content": "second text"},
+ ]
+
+ @pytest.mark.parametrize(
+ ("configured", "expected"),
+ [
+ (["rule", " Notice ", "PRESDOCU"], ["RULE", "NOTICE", "PRESDOCU"]),
+ (
+ ["correct", "Unknown", " SUNSHINE "],
+ ["CORRECT", "UNKNOWN", "SUNSHINE"],
+ ),
+ ("prorule, rule", ["PRORULE", "RULE"]),
+ ('["notice", "NOTICE"]', ["NOTICE"]),
+ (["RULE", "Rules", "final", 7, None], ["RULE"]),
+ (["rules", "bogus"], []),
+ ([], []),
+ (None, []),
+ ],
+ ids=[
+ "case-and-whitespace",
+ "unfaceted-api-types",
+ "comma-string",
+ "json-string-dedup",
+ "drops-invalid-keeps-valid",
+ "all-invalid-means-all-types",
+ "empty",
+ "none",
+ ],
+ )
+ def test_document_types_are_normalised_and_validated(
+ self, configured, expected
+ ):
+ engine = _make_engine(document_types=configured)
+
+ assert engine.document_types == expected
+
+ def test_get_previews_never_sends_an_invalid_document_type(self):
+ """The API answers an unknown type with ``{"count": 0}``.
+
+ That reply is accepted as "matched nothing", so an invalid type
+ reaching the request would silently empty every search.
+ """
+ engine = _make_engine(document_types=["rules", "bogus"])
+ engine.rate_tracker = Mock()
+ engine.rate_tracker.apply_rate_limit.return_value = 0.0
+
+ with patch(
+ f"{MODULE}.safe_get",
+ return_value=_response({"results": [_document()]}),
+ ) as mock_get:
+ engine._get_previews("clean air")
+
+ assert "conditions[type][]" not in mock_get.call_args.kwargs["params"]
+
+ def test_invalid_document_types_log_a_warning_with_the_valid_values(
+ self,
+ ):
+ with patch(f"{MODULE}.logger") as mock_logger:
+ engine = _make_engine(document_types=["rule", "final"])
+
+ assert engine.document_types == ["RULE"]
+ message = mock_logger.warning.call_args.args[0]
+ assert "1 invalid" in message
+ assert (
+ "RULE, PRORULE, NOTICE, PRESDOCU, CORRECT, UNKNOWN, SUNSHINE"
+ in message
+ )
diff --git a/tests/web_search_engines/engines/test_search_engine_federal_register_concurrency.py b/tests/web_search_engines/engines/test_search_engine_federal_register_concurrency.py
new file mode 100644
index 0000000000..7de1ebec4c
--- /dev/null
+++ b/tests/web_search_engines/engines/test_search_engine_federal_register_concurrency.py
@@ -0,0 +1,423 @@
+"""Per-invocation results and outcomes when searches share an engine."""
+
+import json
+from concurrent.futures import ThreadPoolExecutor
+from threading import Event
+from unittest.mock import Mock, patch
+
+import requests
+import pytest
+
+from local_deep_research.web_search_engines.rate_limiting import RateLimitError
+from local_deep_research.web_search_engines.engines import (
+ search_engine_federal_register as module,
+)
+
+
+def response(
+ payload=None, *, status=200, url=module.FederalRegisterSearchEngine.LIST_URL
+):
+ result = requests.Response()
+ result.status_code = status
+ result.url = url
+ result.encoding = "utf-8"
+ result._content = (
+ json.dumps(payload).encode()
+ if payload is not None
+ else b"Full document text"
+ )
+ return result
+
+
+def document(number):
+ return {
+ "document_number": number,
+ "title": number,
+ "abstract": "Preview " + number,
+ "html_url": "https://www.federalregister.gov/documents/" + number,
+ }
+
+
+def make_engine(*, snippets=False):
+ engine = module.FederalRegisterSearchEngine(
+ programmatic_mode=True, search_snippets_only=snippets
+ )
+ engine.rate_tracker = Mock()
+ engine.rate_tracker.enabled = True
+ engine.rate_tracker.apply_rate_limit.return_value = 0.1
+ engine.rate_tracker.get_wait_time.return_value = 0.0
+ return engine
+
+
+ "shared", [True, False], ids=["shared", "separate_engines"]
+)
+def test_preview_failure_metrics_are_per_call(shared):
+ """Known #6610: a healthy call resets a failed call's metrics flag."""
+ engine = make_engine(snippets=True)
+ engine.programmatic_mode = False
+ second_engine = engine if shared else make_engine(snippets=True)
+ second_engine.programmatic_mode = False
+ failed = Event()
+ release = Event()
+ original_previews = engine._get_previews
+
+ def fake_get(url, **kwargs):
+ query = kwargs["params"]["conditions[term]"]
+ return (
+ response(status=503)
+ if query == "failed"
+ else response({"results": [document("healthy")]})
+ )
+
+ def paused_previews(query):
+ results = original_previews(query)
+ if query == "failed":
+ failed.set()
+ assert release.wait(15)
+ return results
+
+ with (
+ patch.object(module, "safe_get", side_effect=fake_get),
+ patch.object(engine, "_get_previews", side_effect=paused_previews),
+ patch(
+ "local_deep_research.metrics.search_tracker.SearchTracker.record_search"
+ ) as metrics,
+ ThreadPoolExecutor(max_workers=2) as pool,
+ ):
+ future = pool.submit(engine.run, "failed")
+ try:
+ assert failed.wait(15)
+ healthy = second_engine.run("healthy")
+ finally:
+ release.set()
+ assert future.result(timeout=15) == []
+ assert healthy[0]["id"] == "healthy"
+ outcomes = {
+ call.kwargs["query"]: call.kwargs["success"]
+ for call in metrics.call_args_list
+ }
+ assert outcomes == {"healthy": True, "failed": False}, outcomes
+
+
+ "shared", [True, False], ids=["shared", "separate_engines"]
+)
+def test_full_content_429_is_not_erased_by_another_call(shared):
+ """A success must not turn an overlapping real HTTP 429 into a success."""
+ engine = make_engine()
+ second_engine = engine if shared else make_engine()
+ limited = Event()
+ release = Event()
+ original_full_content = engine._get_full_content
+
+ def fake_get(url, **kwargs):
+ if url == engine.LIST_URL:
+ query = kwargs["params"]["conditions[term]"]
+ return response({"results": [document(query)]})
+ if url == engine.DETAIL_URL + "/limited.json":
+ return response(status=429, url=url)
+ if url == engine.DETAIL_URL + "/healthy.json":
+ return response(
+ {"raw_text_url": "https://www.federalregister.gov/healthy.txt"},
+ url=url,
+ )
+ return response(url=url)
+
+ def paused_full_content(items):
+ results = original_full_content(items)
+ if items[0]["id"] == "limited":
+ limited.set()
+ assert release.wait(15)
+ return results
+
+ with (
+ patch.object(module, "safe_get", side_effect=fake_get),
+ patch.object(
+ engine, "_get_full_content", side_effect=paused_full_content
+ ),
+ ThreadPoolExecutor(max_workers=2) as pool,
+ ):
+ future = pool.submit(engine.run, "limited")
+ try:
+ assert limited.wait(15)
+ healthy = second_engine.run("healthy")
+ finally:
+ release.set()
+ first = future.result(timeout=15)
+ assert first[0]["id"] == "limited"
+ assert healthy[0]["full_content"] == "Full document text"
+ trackers = (
+ [engine.rate_tracker]
+ if shared
+ else [engine.rate_tracker, second_engine.rate_tracker]
+ )
+ outcomes = [
+ call.kwargs["success"]
+ for tracker in trackers
+ for call in tracker.record_outcome.call_args_list
+ ]
+ assert outcomes.count(False) == 1, outcomes
+
+
+ "shared", [True, False], ids=["shared", "separate_engines"]
+)
+def test_each_parallel_run_receives_its_own_full_content_budget(shared):
+ """An expired older call must not exhaust a new call's 120-second budget."""
+ engine = make_engine()
+ second_engine = engine if shared else make_engine()
+ older_enriched = Event()
+ release = Event()
+ clock = Mock()
+ elapsed = [0.0]
+ clock.monotonic.side_effect = lambda: elapsed[0]
+ original_full_content = engine._get_full_content
+ calls = []
+
+ def fake_get(url, **kwargs):
+ calls.append((url, kwargs.get("timeout")))
+ if url == engine.LIST_URL:
+ query = kwargs["params"]["conditions[term]"]
+ numbers = (
+ ["older-1", "older-2", "older-3"]
+ if query == "older"
+ else ["fresh"]
+ )
+ return response({"results": [document(n) for n in numbers]})
+ if "older" in url:
+ # Six sequential requests, last one finishes just beyond the
+ # best-effort deadline (socket timeouts are not total deadlines).
+ elapsed[0] += 21 if url.endswith("older-3.txt") else 20
+ if url.endswith(".json"):
+ number = url.rsplit("/", 1)[-1].removesuffix(".json")
+ return response(
+ {
+ "raw_text_url": "https://www.federalregister.gov/"
+ + number
+ + ".txt"
+ },
+ url=url,
+ )
+ return response(url=url)
+
+ def paused_full_content(items):
+ results = original_full_content(items)
+ if items[0]["id"] == "older-1":
+ older_enriched.set()
+ assert release.wait(15)
+ return results
+
+ with (
+ patch.object(module, "time", clock),
+ patch.object(module, "safe_get", side_effect=fake_get),
+ patch.object(
+ engine, "_get_full_content", side_effect=paused_full_content
+ ),
+ ThreadPoolExecutor(max_workers=2) as pool,
+ ):
+ future = pool.submit(engine.run, "older")
+ try:
+ assert older_enriched.wait(15)
+ fresh = second_engine.run("fresh")
+ finally:
+ release.set()
+ older = future.result(timeout=15)
+ assert len(older) == 3
+ assert elapsed[0] == 121
+ assert fresh[0].get("full_content") == "Full document text", {
+ "results": fresh,
+ "requests": calls,
+ }
+
+
+def test_overlapping_searches_do_not_reuse_each_others_cached_content():
+ engine = make_engine()
+ older_enriched = Event()
+ release = Event()
+ original_full_content = engine._get_full_content
+ text_versions = iter([b"older content", b"fresh content"])
+
+ def fake_get(url, **kwargs):
+ if url == engine.LIST_URL:
+ item = document("same-document")
+ item["title"] = kwargs["params"]["conditions[term]"]
+ return response({"results": [item]})
+ if url.endswith(".json"):
+ return response(
+ {"raw_text_url": "https://www.federalregister.gov/same.txt"},
+ url=url,
+ )
+ result = response(url=url)
+ result._content = next(text_versions)
+ return result
+
+ def paused_full_content(items):
+ results = original_full_content(items)
+ if items[0]["title"] == "older":
+ older_enriched.set()
+ assert release.wait(15)
+ return results
+
+ with (
+ patch.object(module, "safe_get", side_effect=fake_get) as get,
+ patch.object(
+ engine, "_get_full_content", side_effect=paused_full_content
+ ),
+ ThreadPoolExecutor(max_workers=2) as pool,
+ ):
+ first = pool.submit(engine.run, "older")
+ try:
+ assert older_enriched.wait(15)
+ fresh = engine.run("fresh")
+ finally:
+ release.set()
+ older = first.result(timeout=15)
+
+ assert older[0]["full_content"] == "older content"
+ assert fresh[0]["full_content"] == "fresh content"
+ assert get.call_count == 6
+
+
+def test_nested_search_restores_the_outer_failure_outcome():
+ engine = make_engine(snippets=True)
+ engine.programmatic_mode = False
+ original_previews = engine._get_previews
+
+ def fake_get(url, **kwargs):
+ query = kwargs["params"]["conditions[term]"]
+ return (
+ response(status=503)
+ if query == "failed"
+ else response({"results": [document("healthy")]})
+ )
+
+ def nested_previews(query):
+ results = original_previews(query)
+ if query == "failed":
+ assert engine.run("healthy")[0]["id"] == "healthy"
+ return results
+
+ with (
+ patch.object(module, "safe_get", side_effect=fake_get),
+ patch.object(engine, "_get_previews", side_effect=nested_previews),
+ patch(
+ "local_deep_research.metrics.search_tracker.SearchTracker.record_search"
+ ) as metrics,
+ ):
+ assert engine.run("failed") == []
+
+ assert {
+ call.kwargs["query"]: call.kwargs["success"]
+ for call in metrics.call_args_list
+ } == {"healthy": True, "failed": False}
+
+
+def test_public_run_keeps_completed_fetches_across_its_own_retry():
+ engine = make_engine()
+ content_filter = Mock()
+ attempts = 0
+
+ def filter_results(results, query):
+ nonlocal attempts
+ attempts += 1
+ if attempts == 1:
+ raise RateLimitError("Retry the filter")
+ return results
+
+ content_filter.filter_results.side_effect = filter_results
+ engine._content_filters = [content_filter]
+
+ def fake_get(url, **kwargs):
+ if url == engine.LIST_URL:
+ return response({"results": [document("one")]})
+ if url.endswith(".json"):
+ return response(
+ {"raw_text_url": "https://www.federalregister.gov/one.txt"},
+ url=url,
+ )
+ return response(url=url)
+
+ with patch.object(module, "safe_get", side_effect=fake_get) as get:
+ results = engine.run("query")
+
+ assert results[0]["full_content"] == "Full document text"
+ assert attempts == 2
+ requested = [call.args[0] for call in get.call_args_list]
+ assert requested.count(engine.LIST_URL) == 2
+ assert requested.count(engine.DETAIL_URL + "/one.json") == 1
+ assert requested.count("https://www.federalregister.gov/one.txt") == 1
+
+
+def test_retry_keeps_its_deadline_but_the_next_search_gets_a_new_budget():
+ engine = make_engine()
+ elapsed = [0.0]
+ content_filter = Mock()
+ documents = iter(["one", "two", "three"])
+ attempts = 0
+
+ def filter_results(results, query):
+ nonlocal attempts
+ attempts += 1
+ if attempts == 1:
+ elapsed[0] = 121.0
+ raise RateLimitError("Retry after the full-content budget expired")
+ return results
+
+ content_filter.filter_results.side_effect = filter_results
+ engine._content_filters = [content_filter]
+
+ def fake_get(url, **kwargs):
+ if url == engine.LIST_URL:
+ return response({"results": [document(next(documents))]})
+ if url.endswith(".json"):
+ return response(
+ {"raw_text_url": "https://www.federalregister.gov/text.txt"},
+ url=url,
+ )
+ return response(url=url)
+
+ with (
+ patch.object(module, "safe_get", side_effect=fake_get) as get,
+ patch.object(
+ module, "time", Mock(monotonic=Mock(side_effect=lambda: elapsed[0]))
+ ),
+ ):
+ retried = engine.run("retry")
+ fresh = engine.run("fresh")
+
+ assert retried[0]["id"] == "two"
+ assert "full_content" not in retried[0]
+ assert fresh[0]["id"] == "three"
+ assert fresh[0]["full_content"] == "Full document text"
+ assert engine.DETAIL_URL + "/two.json" not in [
+ call.args[0] for call in get.call_args_list
+ ]
+
+
[email protected]("metrics_fail", [False, True])
+def test_completed_search_releases_state_even_when_recording_fails(
+ metrics_fail,
+):
+ engine = make_engine()
+ engine.programmatic_mode = False
+ metrics_error = (
+ RuntimeError("Metrics unavailable") if metrics_fail else None
+ )
+
+ with (
+ patch.object(module, "safe_get", return_value=response({"count": 0})),
+ patch(
+ "local_deep_research.metrics.search_tracker.SearchTracker.record_search",
+ side_effect=metrics_error,
+ ),
+ ):
+ if metrics_fail:
+ with pytest.raises(RuntimeError, match="Metrics unavailable"):
+ engine.run("query")
+ else:
+ assert engine.run("query") == []
+
+ # Retained state could keep full document text alive in a reused worker
+ # context after a run has finished or an exception has escaped.
+ assert engine._search_run_state.get() is None
diff --git a/tests/web_search_engines/engines/test_search_engine_federal_register_latency.py b/tests/web_search_engines/engines/test_search_engine_federal_register_latency.py
new file mode 100644
index 0000000000..1d0ce2033b
--- /dev/null
+++ b/tests/web_search_engines/engines/test_search_engine_federal_register_latency.py
@@ -0,0 +1,203 @@
+from unittest.mock import Mock, patch
+
+from local_deep_research.web_search_engines.rate_limiting import RateLimitError
+
+
+MODULE = "local_deep_research.web_search_engines.engines.search_engine_federal_register"
+TEXT_BASE_URL = "https://www.federalregister.gov/full-text"
+
+
+def _response(json_data=None, text="", url=f"{TEXT_BASE_URL}/final.txt"):
+ response = Mock()
+ response.status_code = 200
+ response.json.return_value = {} if json_data is None else json_data
+ response.text = text
+ response.url = url
+ return response
+
+
+def _item(number):
+ return {
+ "id": number,
+ "title": f"Document {number}",
+ "link": f"https://www.federalregister.gov/documents/{number}",
+ "snippet": f"Abstract for {number}",
+ }
+
+
+def _engine():
+ from local_deep_research.web_search_engines.engines.search_engine_federal_register import (
+ FederalRegisterSearchEngine,
+ )
+
+ engine = FederalRegisterSearchEngine(programmatic_mode=True)
+ engine.rate_tracker = Mock()
+ engine.rate_tracker.apply_rate_limit.return_value = 0.0
+ return engine
+
+
+def test_full_content_returns_every_item_when_deadline_expires():
+ """An expired deadline costs full_content, never the preview fields.
+
+ ``BaseSearchEngine._get_full_content`` returns one result per input
+ item; dropping the unfetched items would delete their title, link and
+ snippet and shrink the result count ``run()`` records.
+ """
+ items = [_item("one"), _item("two"), _item("three")]
+ engine = _engine()
+
+ with (
+ patch(
+ f"{MODULE}.time",
+ Mock(monotonic=Mock(side_effect=[0.0, 0.0, 0.0, 0.0, 121.0])),
+ create=True,
+ ),
+ patch(
+ f"{MODULE}.safe_get",
+ side_effect=[
+ _response({"raw_text_url": f"{TEXT_BASE_URL}/one.txt"}),
+ _response(text="one text", url=f"{TEXT_BASE_URL}/one.txt"),
+ ],
+ ) as mock_get,
+ ):
+ results = engine._get_full_content(items)
+
+ assert [mock_call.args[0] for mock_call in mock_get.call_args_list] == [
+ f"{engine.DETAIL_URL}/one.json",
+ f"{TEXT_BASE_URL}/one.txt",
+ ]
+ assert results == [
+ {**_item("one"), "full_content": "one text"},
+ _item("two"),
+ _item("three"),
+ ]
+
+
+def test_full_content_returns_every_item_when_deadline_expires_mid_item():
+ """The deadline can also expire between an item's two requests."""
+ items = [_item("one"), _item("two"), _item("three")]
+ engine = _engine()
+
+ with (
+ patch(
+ f"{MODULE}.time",
+ Mock(
+ monotonic=Mock(
+ side_effect=[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 121.0]
+ )
+ ),
+ create=True,
+ ),
+ patch(
+ f"{MODULE}.safe_get",
+ side_effect=[
+ _response({"raw_text_url": f"{TEXT_BASE_URL}/one.txt"}),
+ _response(text="one text", url=f"{TEXT_BASE_URL}/one.txt"),
+ _response({"raw_text_url": f"{TEXT_BASE_URL}/two.txt"}),
+ ],
+ ) as mock_get,
+ ):
+ results = engine._get_full_content(items)
+
+ assert [mock_call.args[0] for mock_call in mock_get.call_args_list] == [
+ f"{engine.DETAIL_URL}/one.json",
+ f"{TEXT_BASE_URL}/one.txt",
+ f"{engine.DETAIL_URL}/two.json",
+ ]
+ assert results == [
+ {**_item("one"), "full_content": "one text"},
+ _item("two"),
+ _item("three"),
+ ]
+
+
+def test_full_content_floors_a_fractional_remaining_budget_at_one_second():
+ """0.4 s left must still buy a request, not truncate to ``timeout=0``.
+
+ ``int(0.4)`` is ``0``, and ``timeout=0`` is an immediate failure
+ rather than "no limit", so the sub-second window used to cost the
+ item its content for nothing.
+ """
+ items = [_item("one")]
+ engine = _engine()
+
+ with (
+ patch(
+ f"{MODULE}.time",
+ Mock(monotonic=Mock(side_effect=[0.0, 0.0, 119.6, 119.6])),
+ create=True,
+ ),
+ patch(
+ f"{MODULE}.safe_get",
+ side_effect=[
+ _response({"raw_text_url": f"{TEXT_BASE_URL}/one.txt"}),
+ _response(text="one text", url=f"{TEXT_BASE_URL}/one.txt"),
+ ],
+ ) as mock_get,
+ ):
+ results = engine._get_full_content(items)
+
+ assert [
+ mock_call.kwargs["timeout"] for mock_call in mock_get.call_args_list
+ ] == [1, 1]
+ assert results == [{**_item("one"), "full_content": "one text"}]
+
+
+def test_full_content_caps_each_request_timeout_to_remaining_budget():
+ items = [{"id": "one"}]
+ engine = _engine()
+
+ with (
+ patch(
+ f"{MODULE}.time",
+ Mock(monotonic=Mock(side_effect=[0.0, 0.0, 100.0, 115.0])),
+ create=True,
+ ),
+ patch(
+ f"{MODULE}.safe_get",
+ side_effect=[
+ _response({"raw_text_url": f"{TEXT_BASE_URL}/one.txt"}),
+ _response(text="one text", url=f"{TEXT_BASE_URL}/one.txt"),
+ ],
+ ) as mock_get,
+ ):
+ results = engine._get_full_content(items)
+
+ assert [
+ mock_call.kwargs["timeout"] for mock_call in mock_get.call_args_list
+ ] == [20, 5]
+ assert results == [{"id": "one", "full_content": "one text"}]
+
+
+def test_full_content_retry_reuses_completed_detail_and_text_fetches():
+ items = [{"id": "one"}, {"id": "two"}]
+ engine = _engine()
+
+ with patch(
+ f"{MODULE}.safe_get",
+ side_effect=[
+ _response({"raw_text_url": f"{TEXT_BASE_URL}/one.txt"}),
+ _response(text="one text", url=f"{TEXT_BASE_URL}/one.txt"),
+ RateLimitError("retry"),
+ ],
+ ):
+ # A rate limit only stops fetching: item two comes back unfetched.
+ assert engine._get_full_content(items) == [
+ {"id": "one", "full_content": "one text"},
+ {"id": "two"},
+ ]
+
+ with patch(
+ f"{MODULE}.safe_get",
+ side_effect=[
+ _response({"raw_text_url": f"{TEXT_BASE_URL}/two.txt"}),
+ _response(text="two text", url=f"{TEXT_BASE_URL}/two.txt"),
+ ],
+ ) as retry_get:
+ results = engine._get_full_content(items)
+
+ assert results == [
+ {"id": "one", "full_content": "one text"},
+ {"id": "two", "full_content": "two text"},
+ ]
+ assert retry_get.call_count == 2
diff --git a/tests/web_search_engines/test_engine_success_path.py b/tests/web_search_engines/test_engine_success_path.py
index 4d7313bad2..24c9ec3577 100644
--- a/tests/web_search_engines/test_engine_success_path.py
+++ b/tests/web_search_engines/test_engine_success_path.py
@@ -86,6 +86,9 @@ from local_deep_research.web_search_engines.engines import (
from local_deep_research.web_search_engines.engines import (
search_engine_exa as exa_engine,
)
+from local_deep_research.web_search_engines.engines import (
+ search_engine_federal_register as federal_register_engine,
+)
from local_deep_research.web_search_engines.engines import (
search_engine_github as github_engine,
)
@@ -373,6 +376,28 @@ EXA_PAYLOAD = {
],
}
+FEDERAL_REGISTER_PAYLOAD = {
+ "count": 1,
+ "results": [
+ {
+ "document_number": "2024-00001",
+ "title": "Transformer Safety Standards",
+ "html_url": (
+ "https://www.federalregister.gov/documents/2024/01/01/"
+ "2024-00001/transformer-safety-standards"
+ ),
+ "abstract": "New transformer safety standards for the electrical grid.",
+ "type": "Rule",
+ "agencies": [{"name": "Department of Energy"}],
+ "publication_date": "2024-01-01",
+ "pdf_url": (
+ "https://www.federalregister.gov/documents/2024/01/01/"
+ "2024-00001.pdf"
+ ),
+ }
+ ],
+}
+
GITHUB_REPO_PAYLOAD = {
"total_count": 1,
"incomplete_results": False,
@@ -999,6 +1024,23 @@ def _drive_exa(tracker):
return engine._get_previews(QUERY)
+def _drive_federal_register(tracker):
+ engine = _wire(
+ federal_register_engine.FederalRegisterSearchEngine(
+ max_results=3,
+ llm=None,
+ settings_snapshot=SNAPSHOT,
+ ),
+ tracker,
+ )
+ with patch.object(
+ federal_register_engine,
+ "safe_get",
+ const_response(payload=FEDERAL_REGISTER_PAYLOAD),
+ ):
+ return engine._get_previews(QUERY)
+
+
def _github_engine(tracker, search_type="repositories"):
return _wire(
github_engine.GitHubSearchEngine(
@@ -1597,6 +1639,16 @@ CASES = [
"https://arxiv.org/abs/1706.03762",
"based solely on attention",
),
+ Case(
+ "federal_register",
+ _drive_federal_register,
+ "Transformer Safety Standards",
+ (
+ "https://www.federalregister.gov/documents/2024/01/01/"
+ "2024-00001/transformer-safety-standards"
+ ),
+ "transformer safety standards",
+ ),
Case(
"github",
_drive_github,
diff --git a/tests/web_search_engines/test_federal_register_factory_integration.py b/tests/web_search_engines/test_federal_register_factory_integration.py
new file mode 100644
index 0000000000..58aa6581e7
--- /dev/null
+++ b/tests/web_search_engines/test_federal_register_factory_integration.py
@@ -0,0 +1,67 @@
+from unittest.mock import Mock, patch
+
+
+MODULE = "local_deep_research.web_search_engines.engines.search_engine_federal_register"
+LIST_URL = "https://www.federalregister.gov/api/v1/documents.json"
+RAW_TEXT_URL = (
+ "https://www.federalregister.gov/documents/full_text/text/2026/12345.txt"
+)
+
+
+def _response(json_data=None, text="", url=RAW_TEXT_URL):
+ response = Mock()
+ response.status_code = 200
+ response.json.return_value = {} if json_data is None else json_data
+ response.text = text
+ # The engine re-checks the response's final URL against its host
+ # allow-list, so a stubbed response has to carry one.
+ response.url = url
+ return response
+
+
+def test_get_search_fetches_federal_register_full_content_when_snippets_disabled():
+ from local_deep_research.web_search_engines.search_engine_factory import (
+ get_search,
+ )
+
+ settings_snapshot = {
+ "search.engine.web": {"federal_register": {"default_params": {}}},
+ "rate_limiting.enabled": False,
+ }
+ document = {
+ "document_number": "2026-12345",
+ "title": "Clean Air Standards",
+ "html_url": "https://www.federalregister.gov/documents/2026/12345",
+ "abstract": "The agency updates emissions standards.",
+ "type": "Rule",
+ "agencies": [],
+ "publication_date": "2026-01-15",
+ "pdf_url": "https://www.federalregister.gov/documents/2026/12345.pdf",
+ }
+ detail_url = f"{LIST_URL.removesuffix('.json')}/2026-12345.json"
+
+ with patch(
+ f"{MODULE}.safe_get",
+ side_effect=[
+ _response({"results": [document]}),
+ _response({"raw_text_url": RAW_TEXT_URL}),
+ _response(text="Full Federal Register document text."),
+ ],
+ ) as mock_get:
+ engine = get_search(
+ search_tool="federal_register",
+ llm_instance=None,
+ max_results=1,
+ search_snippets_only=False,
+ settings_snapshot=settings_snapshot,
+ programmatic_mode=True,
+ )
+ assert engine.rate_tracker.enabled is False
+ results = engine.run("clean air")
+
+ assert [call.args[0] for call in mock_get.call_args_list] == [
+ LIST_URL,
+ detail_url,
+ RAW_TEXT_URL,
+ ]
+ assert results[0]["full_content"] == "Full Federal Register document text."