Skip to content

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

fix(api): load user context for REST research endpoints (and remove /quick_summary_test) (#3661)

LearningCircuitc6e667af262e
diff --git a/changelog.d/3661.bugfix.md b/changelog.d/3661.bugfix.md
new file mode 100644
index 0000000000..06401e2ff7
--- /dev/null
+++ b/changelog.d/3661.bugfix.md
@@ -0,0 +1 @@
+REST `/api/v1/generate_report` and `/api/v1/analyze_documents` now load the authenticated user's encrypted-DB settings (API keys, model preference, search tool) instead of silently falling back to application defaults plus `LDR_*` env vars. Like `/quick_summary`, both endpoints now fail closed (HTTP 503) when the settings snapshot cannot be loaded, with `allow_default_settings: true` as the explicit opt-out.
diff --git a/changelog.d/3661.removal.md b/changelog.d/3661.removal.md
new file mode 100644
index 0000000000..b570bb63fe
--- /dev/null
+++ b/changelog.d/3661.removal.md
@@ -0,0 +1 @@
+Removed the `/api/v1/quick_summary_test` REST endpoint. It was a near-duplicate of `/quick_summary` with hardcoded test defaults; call `/quick_summary` with `search_tool`, `iterations`, and `temperature` set explicitly instead.
diff --git a/src/local_deep_research/api/research_functions.py b/src/local_deep_research/api/research_functions.py
index 429b544483..89cb43d926 100644
--- a/src/local_deep_research/api/research_functions.py
+++ b/src/local_deep_research/api/research_functions.py
@@ -625,7 +625,10 @@ def analyze_documents(
temperature: float = 0.7,
force_reindex: bool = False,
output_file: str | None = None,
- **kwargs: Any,
+ *,
+ username: str | None = None,
+ settings_snapshot: dict[str, Any] | None = None,
+ programmatic_mode: bool = True,
) -> dict[str, Any]:
"""
Search and analyze documents in a specific local collection.
@@ -637,17 +640,23 @@ def analyze_documents(
temperature: LLM temperature for summary generation
force_reindex: Whether to force reindexing the collection
output_file: Optional path to save analysis results to a file
- **kwargs: Pass settings_snapshot (via create_settings_snapshot()) to
- configure provider, API keys, embedding model, etc.
+ username: Optional username for thread context. REST callers pass the
+ authenticated user; programmatic SDK callers can omit.
+ settings_snapshot: Settings snapshot for the user's stored configuration
+ (LLM provider/model, embedding model, etc.). REST callers pass the
+ snapshot from the user's encrypted DB; SDK callers can omit to use
+ JSON defaults + LDR_* env vars.
+ programmatic_mode: If True (default for SDK callers), disables DB-backed
+ metrics. REST callers pass False so per-user rate-limit estimates
+ persist across requests.
Returns:
Dictionary containing:
- 'summary': Summary of the findings
- 'documents': List of matching documents with content and metadata
"""
- if "settings_snapshot" not in kwargs:
- kwargs["settings_snapshot"] = create_settings_snapshot()
- settings_snapshot = kwargs["settings_snapshot"]
+ if settings_snapshot is None:
+ settings_snapshot = create_settings_snapshot()
logger.info(
f"Analyzing documents in collection '{collection_name}' for query: {query}"
@@ -665,7 +674,9 @@ def analyze_documents(
search = get_search(
collection_name,
llm_instance=llm,
+ username=username,
settings_snapshot=settings_snapshot,
+ programmatic_mode=programmatic_mode,
)
if not search:
diff --git a/src/local_deep_research/web/api.py b/src/local_deep_research/web/api.py
index 82a1467861..59fec3bf56 100644
--- a/src/local_deep_research/web/api.py
+++ b/src/local_deep_research/web/api.py
@@ -5,7 +5,7 @@ Provides HTTP access to programmatic search and research capabilities.
import time
from functools import wraps
-from typing import Dict, Any
+from typing import Dict, Any, Optional, Tuple
from flask import Blueprint, jsonify, request, Response
from loguru import logger
@@ -24,6 +24,113 @@ from ..security.rate_limiter import (
api_blueprint = Blueprint("api_v1", __name__, url_prefix="/api/v1")
+# Contract enforced by the test_user_context_loaded /
+# test_settings_snapshot_loaded tests in tests/web/test_api_coverage.py.
+# Each authed REST endpoint that calls a research function must invoke
+# this helper. Each endpoint's contract test must assert that username,
+# settings_snapshot (with the tracer key from _mock_access_control), and
+# programmatic_mode=False reach the underlying research function.
+def _load_user_context_into_params(
+ params: Dict[str, Any],
+ username: str | None,
+ allow_default_settings: bool = False,
+) -> Optional[Tuple[Response, int]]:
+ """Mutate ``params`` in place to thread the authenticated user's context
+ down to the research-function call.
+
+ All authenticated REST endpoints share the same shape: the user has an
+ encrypted DB whose settings snapshot must be loaded and passed through,
+ so calls honor the user's stored API keys, model preference, search
+ tool, and other config — not just the application defaults plus
+ ``LDR_*`` env vars that the programmatic-API fallback would produce.
+
+ Sets ``username``, ``settings_snapshot``, and (for authenticated
+ requests) ``programmatic_mode=False`` so DB-backed rate-limit
+ estimates persist across requests. Uses ``setdefault`` for
+ ``programmatic_mode`` so an explicit override in the request body
+ is respected.
+
+ Returns ``None`` on success. If the settings snapshot cannot be loaded,
+ fails CLOSED: returns a ``(response, 503)`` tuple the endpoint must
+ return to the caller. Continuing with an empty snapshot would resolve
+ to the permissive default egress scope, silently downgrading a
+ configured PRIVATE_ONLY / require-local user — bypassing the very
+ boundary they configured. ``allow_default_settings=True`` is the
+ caller's CONSCIOUS opt-in to proceed with defaults (empty snapshot,
+ no egress policy) instead; it is logged loudly so it is never silent.
+ """
+ if not username:
+ logger.debug("No username in session, skipping settings snapshot")
+ params["settings_snapshot"] = {}
+ return None
+
+ params["username"] = username
+ params.setdefault("programmatic_mode", False)
+ try:
+ with get_user_db_session(username) as db_session:
+ if db_session is None:
+ logger.warning(f"No database session for user: {username}")
+ params["settings_snapshot"] = {}
+ return None
+ settings_manager = get_settings_manager(db_session, username)
+ all_settings = settings_manager.get_all_settings()
+ snapshot: Dict[str, Any] = {}
+ for key, setting in all_settings.items():
+ if isinstance(setting, dict) and "value" in setting:
+ snapshot[key] = setting["value"]
+ else:
+ snapshot[key] = setting
+ params["settings_snapshot"] = snapshot
+ logger.debug(
+ f"Loaded settings snapshot for user '{username}' "
+ f"with {len(snapshot)} settings"
+ )
+ return None
+ except Exception:
+ # logger.exception captures the traceback so the root cause
+ # (e.g. SQLCipher decrypt failure, settings table corruption,
+ # missing column after a migration) is visible. Without this
+ # the downstream error misleads — looks like "no provider",
+ # really was "couldn't read user settings".
+ logger.exception("Failed to load user settings snapshot")
+ if allow_default_settings:
+ # Caller explicitly opted in to run without their settings.
+ # Proceed with defaults (empty snapshot → permissive scope).
+ # Logged loudly so it's never a silent downgrade.
+ logger.bind(policy_audit=True).warning(
+ "Settings snapshot failed to load; proceeding with "
+ "DEFAULT settings because allow_default_settings=true "
+ "— this run is NOT bound by the user's egress policy",
+ user=username,
+ )
+ params["settings_snapshot"] = {}
+ return None
+ return (
+ jsonify(
+ {
+ "error": (
+ "Your settings could not be loaded, so the "
+ "research was REFUSED to avoid silently "
+ "running without your privacy/egress policy "
+ "(which could send your data to the cloud "
+ "when you meant to keep it local)."
+ ),
+ "how_to_fix": (
+ "This is usually transient — try again. If "
+ "it persists, your encrypted settings "
+ "database may be unavailable (e.g. a session "
+ "/ password issue), so re-authenticate. To "
+ "deliberately run with default settings and "
+ "NO egress policy, resend the request with "
+ '"allow_default_settings": true.'
+ ),
+ "reason": "settings_unavailable",
+ }
+ ),
+ 503,
+ )
+
+
def api_access_control(f):
"""
Decorator to enforce API access control:
@@ -122,45 +229,6 @@ def health_check():
)
-@api_blueprint.route("/quick_summary_test", methods=["POST"])
-@api_access_control
-@api_rate_limit
-@require_json_body(error_message="Query parameter is required")
-def api_quick_summary_test():
- """Test endpoint using programmatic access with minimal parameters for fast testing."""
- data = request.json
- if "query" not in data:
- return jsonify({"error": "Query parameter is required"}), 400
-
- query = data.get("query")
-
- try:
- # Import here to avoid circular imports
- from ..api.research_functions import quick_summary
-
- logger.info(f"Processing quick_summary_test request: query='{query}'")
-
- # Use minimal parameters for faster testing
- result = quick_summary(
- query=query,
- search_tool="wikipedia", # Use fast Wikipedia search for testing
- iterations=1, # Single iteration for speed
- temperature=0.7,
- )
-
- return jsonify(result)
- except Exception:
- logger.exception("Error in quick_summary_test API")
- return (
- jsonify(
- {
- "error": "An internal error has occurred. Please try again later."
- }
- ),
- 500,
- )
-
-
def _serialize_results(results: Dict[str, Any]) -> Response:
"""
Converts the results dictionary into a JSON string.
@@ -231,8 +299,6 @@ def api_quick_summary():
)
username = get_current_username()
- if username:
- params["username"] = username
try:
# Import here to avoid circular imports. NOTE: get_user_db_session and
@@ -254,91 +320,11 @@ def api_quick_summary():
params.setdefault("search_tool", "auto")
params.setdefault("iterations", 1)
- # Get settings snapshot for the user
- if username:
- try:
- logger.debug(f"Getting settings snapshot for user: {username}")
- with get_user_db_session(username) as db_session:
- if db_session:
- try:
- settings_manager = get_settings_manager(
- db_session, username
- )
- all_settings = settings_manager.get_all_settings()
- # Extract just the values for the settings snapshot
- settings_snapshot = {}
- for key, setting in all_settings.items():
- if (
- isinstance(setting, dict)
- and "value" in setting
- ):
- settings_snapshot[key] = setting["value"]
- else:
- settings_snapshot[key] = setting
- params["settings_snapshot"] = settings_snapshot
- logger.debug(
- f"Got settings snapshot with {len(settings_snapshot)} settings"
- )
- except AttributeError as ae:
- logger.exception(
- f"SettingsManager attribute error: {ae}. "
- f"Type: {type(settings_manager) if 'settings_manager' in locals() else 'Unknown'}"
- )
- raise
- else:
- logger.warning(
- f"No database session for user: {username}"
- )
- except Exception:
- if allow_default_settings:
- # Caller explicitly opted in to run without their settings.
- # Proceed with defaults (empty snapshot → permissive scope).
- # Logged loudly so it's never a silent downgrade.
- logger.bind(policy_audit=True).warning(
- "Settings snapshot failed to load; proceeding with "
- "DEFAULT settings because allow_default_settings=true "
- "— this run is NOT bound by the user's egress policy",
- user=username,
- )
- params["settings_snapshot"] = {}
- else:
- # Fail CLOSED: if the user's settings can't be loaded we
- # can't read their egress policy (PRIVATE_ONLY, require-
- # local, …), and continuing with an empty snapshot would
- # silently downgrade them to the permissive BOTH scope —
- # bypassing the very boundary they configured. Refuse the
- # run with a clear, actionable message.
- logger.exception(
- "Failed to load settings snapshot; refusing research to "
- "avoid running without the user's egress policy"
- )
- return (
- jsonify(
- {
- "error": (
- "Your settings could not be loaded, so the "
- "research was REFUSED to avoid silently "
- "running without your privacy/egress policy "
- "(which could send your data to the cloud "
- "when you meant to keep it local)."
- ),
- "how_to_fix": (
- "This is usually transient — try again. If "
- "it persists, your encrypted settings "
- "database may be unavailable (e.g. a session "
- "/ password issue), so re-authenticate. To "
- "deliberately run with default settings and "
- "NO egress policy, resend the request with "
- '"allow_default_settings": true.'
- ),
- "reason": "settings_unavailable",
- }
- ),
- 503,
- )
- else:
- logger.debug("No username in session, skipping settings snapshot")
- params["settings_snapshot"] = {}
+ error = _load_user_context_into_params(
+ params, username, allow_default_settings
+ )
+ if error is not None:
+ return error
# Call the actual research function
result = quick_summary(query, **params)
@@ -388,7 +374,16 @@ def api_generate_report():
return jsonify({"error": "Query parameter is required"}), 400
query = data.get("query")
- params = {k: v for k, v in data.items() if k != "query"}
+ # See api_quick_summary for the allow_default_settings semantics
+ # (opt-in escape hatch, strict ``is True``, excluded from params).
+ allow_default_settings = data.get("allow_default_settings") is True
+ params = {
+ k: v
+ for k, v in data.items()
+ if k not in ("query", "allow_default_settings")
+ }
+
+ username = get_current_username()
try:
# Import here to avoid circular imports
@@ -398,8 +393,14 @@ def api_generate_report():
params.setdefault("searches_per_section", 1)
params.setdefault("temperature", 0.7)
+ error = _load_user_context_into_params(
+ params, username, allow_default_settings
+ )
+ if error is not None:
+ return error
+
logger.info(
- f"Processing generate_report request: query='{query}', params={params}"
+ f"Processing generate_report request: query='{query}' for user='{username}'"
)
result = generate_report(query, **params)
@@ -471,11 +472,23 @@ def api_analyze_documents():
query = data.get("query")
collection_name = data.get("collection_name")
+ # See api_quick_summary for the allow_default_settings semantics
+ # (opt-in escape hatch, strict ``is True``, excluded from params).
+ allow_default_settings = data.get("allow_default_settings") is True
params = {
- k: v for k, v in data.items() if k not in ["query", "collection_name"]
+ k: v
+ for k, v in data.items()
+ if k not in ("query", "collection_name", "allow_default_settings")
}
+ username = get_current_username()
+
try:
+ error = _load_user_context_into_params(
+ params, username, allow_default_settings
+ )
+ if error is not None:
+ return error
result = analyze_documents(query, collection_name, **params)
return jsonify(result)
except Exception:
diff --git a/src/local_deep_research/web/routes/route_registry.py b/src/local_deep_research/web/routes/route_registry.py
index 4d423869f4..fe403e0ffb 100644
--- a/src/local_deep_research/web/routes/route_registry.py
+++ b/src/local_deep_research/web/routes/route_registry.py
@@ -100,12 +100,6 @@ ROUTE_REGISTRY: dict[str, Any] = {
"api_quick_summary",
"Quick LLM summary",
),
- (
- "POST",
- "/quick_summary_test",
- "api_quick_summary_test",
- "Test quick summary",
- ),
(
"POST",
"/generate_report",
diff --git a/tests/api_tests/test_all_endpoints.py b/tests/api_tests/test_all_endpoints.py
index fc5b7be143..2feecb5303 100644
--- a/tests/api_tests/test_all_endpoints.py
+++ b/tests/api_tests/test_all_endpoints.py
@@ -358,19 +358,8 @@ class TestAllEndpoints:
response = authenticated_client.get("/api/v1/")
assert response.status_code == 200, f"API docs failed: {response.data}"
- # Quick summary test
- summary_data = {"query": "What is machine learning?", "max_tokens": 100}
- response = authenticated_client.post(
- "/api/v1/quick_summary_test",
- json=summary_data,
- content_type="application/json",
- )
- # This endpoint might not be fully implemented
- assert response.status_code in [200, 404, 500], (
- f"Quick summary test status: {response.status_code}"
- )
-
# Quick summary
+ summary_data = {"query": "What is machine learning?", "max_tokens": 100}
response = authenticated_client.post(
"/api/v1/quick_summary",
json=summary_data,
diff --git a/tests/api_tests/test_rest_api.py b/tests/api_tests/test_rest_api.py
index 914ca72e80..62c6f55bb5 100644
--- a/tests/api_tests/test_rest_api.py
+++ b/tests/api_tests/test_rest_api.py
@@ -66,30 +66,6 @@ class TestRestAPI:
f"✅ Quick summary passed - got {len(data['summary'])} chars of summary"
)
- @pytest.mark.requires_llm
- def test_quick_summary_test_endpoint(self, authenticated_client):
- """Test the quick summary test endpoint with minimal query."""
- payload = {"query": "AI"}
-
- response = authenticated_client.post(
- "/api/v1/quick_summary_test",
- json=payload,
- content_type="application/json",
- )
-
- assert response.status_code == 200
- data = json.loads(response.data)
-
- # Verify response structure
- assert "query" in data
- assert "summary" in data
- assert data["query"] == "AI"
- assert len(data["summary"]) > 10
-
- print(
- f"✅ Quick summary test passed - got {len(data['summary'])} chars"
- )
-
def test_quick_summary_validation(self, authenticated_client):
"""Test quick summary endpoint validation."""
# Test missing query
diff --git a/tests/api_tests/test_rest_api_simple.py b/tests/api_tests/test_rest_api_simple.py
index 59b12596c1..97a73ebdea 100644
--- a/tests/api_tests/test_rest_api_simple.py
+++ b/tests/api_tests/test_rest_api_simple.py
@@ -101,38 +101,6 @@ class TestRestAPISimple:
)
print(f" Response: {response.data[:200]}")
- @pytest.mark.requires_llm
- def test_quick_summary_test_minimal(self, authenticated_client):
- """Test the test endpoint with minimal query."""
- print("🔍 Testing quick summary test endpoint...")
-
- payload = {"query": "dog"} # Another simple, common word
-
- print("Making request...")
- response = authenticated_client.post(
- "/api/v1/quick_summary_test",
- json=payload,
- content_type="application/json",
- )
-
- if response.status_code == 200:
- data = json.loads(response.data)
-
- # Basic structure validation
- assert "query" in data
- assert "summary" in data
- assert data["query"] == "dog"
- assert len(data["summary"]) > 0
-
- print(
- f"✅ Quick summary test passed - got {len(data['summary'])} chars of summary"
- )
- else:
- pytest.fail(
- f"Quick summary test failed with status {response.status_code}"
- )
- print(f" Response: {response.data[:200]}")
-
@pytest.mark.requires_llm
def test_analyze_documents_minimal(self, authenticated_client):
"""Test analyze documents with minimal input."""
diff --git a/tests/utilities/test_search_utilities_formatting.py b/tests/utilities/test_search_utilities_formatting.py
index f345bb0007..bf9bd91c4e 100644
--- a/tests/utilities/test_search_utilities_formatting.py
+++ b/tests/utilities/test_search_utilities_formatting.py
@@ -571,6 +571,163 @@ class TestFormatLinksDedupCanonical:
assert "[1, 2]" not in result
+# ---------------------------------------------------------------------------
+# format_findings — exact character-by-character output
+# ---------------------------------------------------------------------------
+
+
+class TestFormatFindingsExactOutput:
+ """Character-by-character tests of the markdown produced by
+ ``format_findings`` for predetermined inputs. Locks in the exact
+ layout (indentation, blank lines, ``[1]`` citation markers, the
+ 80-char ``_`` separator) so a renderer regression — even a single
+ extra newline or a moved citation — fails loudly.
+ """
+
+ def test_exact_output_minimal_findings(self):
+ """One finding, one source, one iteration, one question."""
+ from local_deep_research.utilities.search_utilities import (
+ format_findings,
+ )
+
+ findings_list = [
+ {
+ "phase": "Initial",
+ "content": "Qubits enable quantum computing [1].",
+ "search_results": [
+ {
+ "title": "Qubit Basics",
+ "link": "https://example.com/q",
+ "index": "1",
+ },
+ ],
+ },
+ ]
+ synthesized_content = "Quantum computing uses qubits [1]."
+ questions_by_iteration = {1: ["What is a qubit?"]}
+
+ # Expected output is the verbatim string format_findings produces
+ # for the inputs above. Anchored to today's exact layout — any
+ # change (added blank line, moved citation, renamed section
+ # header) will fail this test, which is the point.
+ expected = (
+ "Quantum computing uses qubits [1].\n"
+ "\n"
+ "[1] Qubit Basics (source nr: 1)\n"
+ " URL: https://example.com/q\n"
+ "\n"
+ "\n"
+ "\n"
+ "\n"
+ "## SEARCH QUESTIONS BY ITERATION\n"
+ "\n"
+ "\n"
+ " #### Iteration 1:\n"
+ "1. What is a qubit?\n"
+ "\n"
+ "\n"
+ "\n"
+ "## DETAILED FINDINGS\n"
+ "\n"
+ "\n"
+ "### Initial\n"
+ "\n"
+ "\n"
+ "\n"
+ "\n"
+ "Qubits enable quantum computing [1].\n"
+ "\n"
+ "### SOURCES USED IN THIS SECTION:\n"
+ "[1] Qubit Basics (source nr: 1)\n"
+ " URL: https://example.com/q\n"
+ "\n"
+ "\n"
+ "\n"
+ "\n" + ("_" * 80) + "\n"
+ "\n"
+ "## ALL SOURCES:\n"
+ "[1] Qubit Basics (source nr: 1)\n"
+ " URL: https://example.com/q\n"
+ "\n"
+ "\n"
+ )
+
+ actual = format_findings(
+ findings_list, synthesized_content, questions_by_iteration
+ )
+ assert actual == expected, (
+ f"format_findings output drifted from the locked-in layout.\n"
+ f"--- expected ---\n{expected!r}\n"
+ f"--- actual ---\n{actual!r}"
+ )
+
+ def test_citations_in_synthesized_content_preserved(self):
+ """``[1]`` and ``[2]`` markers in the synthesized content reach
+ the final output unchanged. Independent narrower assertion to
+ catch citation-handling regressions even when the broader exact-
+ match test is in flux for unrelated layout reasons."""
+ from local_deep_research.utilities.search_utilities import (
+ format_findings,
+ )
+
+ synthesized = "First fact [1]. Second fact [2]. Third fact [1]."
+ result = format_findings(
+ findings_list=[],
+ synthesized_content=synthesized,
+ questions_by_iteration={},
+ )
+ # The synthesized content is the very first thing written.
+ assert result.startswith(synthesized + "\n\n"), (
+ f"Synthesized content (with citations) was rewritten or "
+ f"prefixed by format_findings: result starts with "
+ f"{result[: len(synthesized) + 20]!r}"
+ )
+ assert result.count("[1]") == 2
+ assert result.count("[2]") == 1
+
+ def test_source_indices_match_citation_markers(self):
+ """When a finding's search_results have indices ``"1"`` and
+ ``"2"``, format_links_to_markdown emits ``[1]`` and ``[2]`` —
+ these should align with the citation markers in the synthesized
+ content. Tests the citation→source alignment that makes the
+ markdown navigable."""
+ from local_deep_research.utilities.search_utilities import (
+ format_findings,
+ )
+
+ findings_list = [
+ {
+ "phase": "Initial",
+ "content": "Body referencing [1] and [2].",
+ "search_results": [
+ {
+ "title": "Source One",
+ "link": "https://example.com/one",
+ "index": "1",
+ },
+ {
+ "title": "Source Two",
+ "link": "https://example.com/two",
+ "index": "2",
+ },
+ ],
+ },
+ ]
+ result = format_findings(
+ findings_list,
+ synthesized_content="See [1] and [2].",
+ questions_by_iteration={},
+ )
+ # Both [1] and [2] appear in source listings, attached to the
+ # right titles and URLs.
+ assert "[1] Source One" in result
+ assert "https://example.com/one" in result
+ assert "[2] Source Two" in result
+ assert "https://example.com/two" in result
+ # And the synthesized [1]/[2] citations at the top survive.
+ assert result.startswith("See [1] and [2].\n\n")
+
+
class TestFormatLinksToMarkdownCollections:
"""Tests for the optional ``Collection:`` line surfaced for
RAG / library results so the source-tagged citation mode can read
diff --git a/tests/web/test_api.py b/tests/web/test_api.py
index 43507dcd06..d205733089 100644
--- a/tests/web/test_api.py
+++ b/tests/web/test_api.py
@@ -245,65 +245,3 @@ class TestQuickSummaryQueryTypeValidation:
"""None/null query returns 400."""
response = self._make_request(authenticated_client, {"query": None})
assert response.status_code == 400
-
-
-class TestQuickSummaryTestEndpoint:
- """Tests for /api/v1/quick_summary_test endpoint."""
-
- def test_requires_query_parameter(self, authenticated_client):
- """Should require query parameter."""
- with patch(
- "local_deep_research.web.api.get_user_db_session"
- ) as mock_session_ctx:
- mock_session = MagicMock()
- mock_session_ctx.return_value.__enter__ = MagicMock(
- return_value=mock_session
- )
- mock_session_ctx.return_value.__exit__ = MagicMock(
- return_value=None
- )
-
- with patch(
- "local_deep_research.web.api.get_settings_manager"
- ) as mock_settings:
- mock_manager = MagicMock()
- mock_manager.get_setting.side_effect = lambda key, default: {
- "app.enable_api": True,
- }.get(key, default)
- mock_settings.return_value = mock_manager
-
- response = authenticated_client.post(
- "/api/v1/quick_summary_test",
- json={}, # No query parameter
- )
- assert response.status_code == 400
- data = response.get_json()
- assert "query" in data["error"].lower()
-
- def test_returns_400_for_empty_body(self, authenticated_client):
- """Should return 400 for empty body."""
- with patch(
- "local_deep_research.web.api.get_user_db_session"
- ) as mock_session_ctx:
- mock_session = MagicMock()
- mock_session_ctx.return_value.__enter__ = MagicMock(
- return_value=mock_session
- )
- mock_session_ctx.return_value.__exit__ = MagicMock(
- return_value=None
- )
-
- with patch(
- "local_deep_research.web.api.get_settings_manager"
- ) as mock_settings:
- mock_manager = MagicMock()
- mock_manager.get_setting.side_effect = lambda key, default: {
- "app.enable_api": True,
- }.get(key, default)
- mock_settings.return_value = mock_manager
-
- response = authenticated_client.post(
- "/api/v1/quick_summary_test",
- content_type="application/json",
- )
- assert response.status_code == 400
diff --git a/tests/web/test_api_coverage.py b/tests/web/test_api_coverage.py
index 63a4220cdf..2a791b6127 100644
--- a/tests/web/test_api_coverage.py
+++ b/tests/web/test_api_coverage.py
@@ -53,6 +53,13 @@ def _mock_access_control(*, api_enabled=True, rate_limit=60):
"app.enable_api": api_enabled,
"app.api_rate_limit": rate_limit,
}.get(key, default)
+ # Tracer setting so contract tests can verify the user's
+ # snapshot reaches the underlying research function.
+ # `_ldr_test_tracer` is reserved for tests; no production
+ # code reads this key.
+ mock_manager.get_all_settings.return_value = {
+ "_ldr_test_tracer": {"value": "tracer-value"}
+ }
mock_sm.return_value = mock_manager
yield mock_ctx, mock_sm
@@ -303,77 +310,6 @@ class TestApiAccessControl:
assert resp.status_code == 200
-# ===================================================================
-# /api/v1/quick_summary_test
-# ===================================================================
-
-
-class TestQuickSummaryTest:
- """POST /api/v1/quick_summary_test"""
-
- def test_unauthenticated_returns_401(self, client):
- resp = client.post("/api/v1/quick_summary_test", json={"query": "hi"})
- assert resp.status_code == 401
-
- def test_no_json_body_returns_400(self, authed_client):
- with _mock_access_control():
- resp = authed_client.post(
- "/api/v1/quick_summary_test",
- content_type="application/json",
- )
- assert resp.status_code == 400
-
- def test_missing_query_returns_400(self, authed_client):
- with _mock_access_control():
- resp = authed_client.post(
- "/api/v1/quick_summary_test", json={"not_query": "x"}
- )
- assert resp.status_code == 400
- assert "query" in resp.get_json()["error"].lower()
-
- def test_empty_dict_body_returns_400(self, authed_client):
- with _mock_access_control():
- resp = authed_client.post("/api/v1/quick_summary_test", json={})
- assert resp.status_code == 400
-
- def test_successful_summary(self, authed_client):
- mock_result = {"summary": "test summary", "sources": []}
- with _mock_access_control():
- with patch(
- "local_deep_research.api.research_functions.quick_summary",
- return_value=mock_result,
- ):
- resp = authed_client.post(
- "/api/v1/quick_summary_test",
- json={"query": "test query"},
- )
- assert resp.status_code == 200
- assert resp.get_json() == mock_result
-
- def test_internal_error_returns_500(self, authed_client):
- with _mock_access_control():
- with patch(
- "local_deep_research.api.research_functions.quick_summary",
- side_effect=RuntimeError("boom"),
- ):
- resp = authed_client.post(
- "/api/v1/quick_summary_test",
- json={"query": "test query"},
- )
- assert resp.status_code == 500
- assert "internal error" in resp.get_json()["error"].lower()
-
- def test_non_dict_body_returns_400(self, authed_client):
- """Sending a JSON list should trigger require_json_body guard."""
- with _mock_access_control():
- resp = authed_client.post(
- "/api/v1/quick_summary_test",
- data="[1,2,3]",
- content_type="application/json",
- )
- assert resp.status_code == 400
-
-
# ===================================================================
# /api/v1/quick_summary
# ===================================================================
@@ -559,9 +495,14 @@ class TestQuickSummary:
),
patch(
"local_deep_research.api.research_functions.quick_summary",
- return_value={"findings": []},
+ # autospec=True catches param renames on existing named
+ # args (e.g. username → user). quick_summary has **kwargs
+ # so unknown kwarg names are NOT rejected — for that
+ # bug class see TestResearchFunctionSignatures.
+ autospec=True,
) as mock_qs,
):
+ mock_qs.return_value = {"findings": []}
mock_db = MagicMock()
mock_ctx.return_value.__enter__ = MagicMock(return_value=mock_db)
mock_ctx.return_value.__exit__ = MagicMock(return_value=None)
@@ -571,10 +512,15 @@ class TestQuickSummary:
json={"query": "test"},
)
assert resp.status_code == 200
- snapshot = mock_qs.call_args[1].get("settings_snapshot")
+ snapshot = mock_qs.call_args.kwargs.get("settings_snapshot")
assert snapshot is not None
assert snapshot["some.key"] == 42
assert snapshot["another.key"] == "raw_value"
+ # Contract: username + programmatic_mode=False also reach
+ # the research function. See _load_user_context_into_params
+ # in src/local_deep_research/web/api.py.
+ assert mock_qs.call_args.kwargs.get("username") == "testuser"
+ assert mock_qs.call_args.kwargs.get("programmatic_mode") is False
def test_settings_load_failure_fails_closed(self, authed_client):
"""If loading the settings snapshot fails, the request is REFUSED
@@ -585,9 +531,10 @@ class TestQuickSummary:
endpoint fails closed and the research function is never called.
We fail the endpoint's full-snapshot load (``get_all_settings``) on the
shared settings-manager mock, so the auth decorator's ``get_setting``
- calls keep working — only the snapshot build inside the endpoint's try
- is broken. (Both get_user_db_session and get_settings_manager are
- bound at module level, so they share one patch surface.)
+ calls keep working — only the snapshot build inside
+ ``_load_user_context_into_params`` is broken. (Both
+ get_user_db_session and get_settings_manager are bound at module
+ level, so they share one patch surface.)
"""
with _mock_access_control() as (_ctx, mock_sm):
mock_sm.return_value.get_all_settings.side_effect = RuntimeError(
@@ -849,6 +796,100 @@ class TestGenerateReport:
assert resp.status_code == 200
assert resp.get_json()["content"] is None
+ def test_user_context_loaded(self, authed_client):
+ """Authenticated requests must thread username + settings_snapshot
+ + programmatic_mode=False down to generate_report. Pre-fix this
+ endpoint silently dropped user context, so users' encrypted-DB
+ API keys / model preferences / search tool config never reached
+ the research function."""
+ mock_all_settings = {
+ "llm.provider": {"value": "openai"},
+ "search.tool": "tavily",
+ }
+ mock_sm_instance = MagicMock()
+ mock_sm_instance.get_all_settings.return_value = mock_all_settings
+ mock_sm_instance.get_setting.side_effect = lambda key, default: {
+ "app.enable_api": True,
+ }.get(key, default)
+
+ with (
+ patch(
+ "local_deep_research.web.api.get_user_db_session"
+ ) as mock_ctx,
+ patch(
+ "local_deep_research.web.api.get_settings_manager",
+ return_value=mock_sm_instance,
+ ),
+ patch(
+ "local_deep_research.api.research_functions.generate_report",
+ # autospec=True catches param renames on existing named
+ # args. generate_report has **kwargs so unknown kwarg
+ # names are NOT rejected — TestResearchFunctionSignatures
+ # covers that bug class via sig.bind_partial.
+ autospec=True,
+ ) as mock_gr,
+ ):
+ mock_gr.return_value = {"content": "ok"}
+ mock_ctx.return_value.__enter__ = MagicMock(
+ return_value=MagicMock()
+ )
+ mock_ctx.return_value.__exit__ = MagicMock(return_value=None)
+
+ resp = authed_client.post(
+ "/api/v1/generate_report", json={"query": "test"}
+ )
+ assert resp.status_code == 200
+ kw = mock_gr.call_args.kwargs
+ assert kw.get("username") == "testuser"
+ assert kw.get("programmatic_mode") is False
+ snapshot = kw.get("settings_snapshot")
+ assert snapshot is not None
+ assert snapshot["llm.provider"] == "openai"
+ assert snapshot["search.tool"] == "tavily"
+
+ def test_settings_load_failure_fails_closed(self, authed_client):
+ """Like /quick_summary, /generate_report refuses (503) when the
+ settings snapshot can't be loaded, instead of silently running
+ with defaults — same egress-policy boundary, same helper."""
+ with _mock_access_control() as (_ctx, mock_sm):
+ mock_sm.return_value.get_all_settings.side_effect = RuntimeError(
+ "settings fail"
+ )
+ with patch(
+ "local_deep_research.api.research_functions.generate_report",
+ return_value={"content": "ok"},
+ ) as mock_gr:
+ resp = authed_client.post(
+ "/api/v1/generate_report",
+ json={"query": "test"},
+ )
+ assert resp.status_code == 503
+ mock_gr.assert_not_called()
+ assert "how_to_fix" in resp.get_json()
+
+ def test_settings_load_failure_opt_in_continues_with_defaults(
+ self, authed_client
+ ):
+ """allow_default_settings=true opts in to run with an empty
+ snapshot when settings can't load; the flag itself must not be
+ forwarded to generate_report."""
+ with _mock_access_control() as (_ctx, mock_sm):
+ mock_sm.return_value.get_all_settings.side_effect = RuntimeError(
+ "settings fail"
+ )
+ with patch(
+ "local_deep_research.api.research_functions.generate_report",
+ return_value={"content": "ok"},
+ ) as mock_gr:
+ resp = authed_client.post(
+ "/api/v1/generate_report",
+ json={"query": "test", "allow_default_settings": True},
+ )
+ assert resp.status_code == 200
+ mock_gr.assert_called_once()
+ assert mock_gr.call_args.kwargs["settings_snapshot"] == {}
+ assert "allow_default_settings" not in mock_gr.call_args.kwargs
+
# ===================================================================
# /api/v1/analyze_documents
@@ -952,6 +993,453 @@ class TestAnalyzeDocuments:
)
assert resp.status_code == 400
+ def test_user_context_loaded(self, authed_client):
+ """Authenticated requests must thread username + settings_snapshot
+ + programmatic_mode=False down to analyze_documents. Pre-fix this
+ endpoint silently dropped user context, so users' encrypted-DB
+ embedding model / collection settings never reached the research
+ function."""
+ mock_all_settings = {
+ "rag.embedding_model": {"value": "BAAI/bge-base"},
+ }
+ mock_sm_instance = MagicMock()
+ mock_sm_instance.get_all_settings.return_value = mock_all_settings
+ mock_sm_instance.get_setting.side_effect = lambda key, default: {
+ "app.enable_api": True,
+ }.get(key, default)
+
+ with (
+ patch(
+ "local_deep_research.web.api.get_user_db_session"
+ ) as mock_ctx,
+ patch(
+ "local_deep_research.web.api.get_settings_manager",
+ return_value=mock_sm_instance,
+ ),
+ patch(
+ "local_deep_research.web.api.analyze_documents",
+ # autospec=True so the mock mirrors the real function's
+ # signature; if the endpoint passes kwargs the function
+ # doesn't accept, the mock raises TypeError just like
+ # the real call would. Caught the original /analyze_documents
+ # bug where MagicMock(return_value={}) silently swallowed
+ # incompatible kwargs.
+ autospec=True,
+ ) as mock_ad,
+ ):
+ mock_ad.return_value = {}
+ mock_ctx.return_value.__enter__ = MagicMock(
+ return_value=MagicMock()
+ )
+ mock_ctx.return_value.__exit__ = MagicMock(return_value=None)
+
+ resp = authed_client.post(
+ "/api/v1/analyze_documents",
+ json={"query": "q", "collection_name": "c"},
+ )
+ assert resp.status_code == 200
+ kw = mock_ad.call_args.kwargs
+ assert kw.get("username") == "testuser"
+ assert kw.get("programmatic_mode") is False
+ snapshot = kw.get("settings_snapshot")
+ assert snapshot is not None
+ assert snapshot["rag.embedding_model"] == "BAAI/bge-base"
+
+ def test_settings_load_failure_fails_closed(self, authed_client):
+ """Like /quick_summary, /analyze_documents refuses (503) when the
+ settings snapshot can't be loaded, instead of silently running
+ with defaults — same egress-policy boundary, same helper."""
+ with _mock_access_control() as (_ctx, mock_sm):
+ mock_sm.return_value.get_all_settings.side_effect = RuntimeError(
+ "settings fail"
+ )
+ with patch(
+ "local_deep_research.web.api.analyze_documents",
+ return_value={},
+ ) as mock_ad:
+ resp = authed_client.post(
+ "/api/v1/analyze_documents",
+ json={"query": "q", "collection_name": "c"},
+ )
+ assert resp.status_code == 503
+ mock_ad.assert_not_called()
+ assert "how_to_fix" in resp.get_json()
+
+ def test_settings_load_failure_opt_in_continues_with_defaults(
+ self, authed_client
+ ):
+ """allow_default_settings=true opts in to run with an empty
+ snapshot when settings can't load; the flag itself must not be
+ forwarded to analyze_documents."""
+ with _mock_access_control() as (_ctx, mock_sm):
+ mock_sm.return_value.get_all_settings.side_effect = RuntimeError(
+ "settings fail"
+ )
+ with patch(
+ "local_deep_research.web.api.analyze_documents",
+ return_value={},
+ ) as mock_ad:
+ resp = authed_client.post(
+ "/api/v1/analyze_documents",
+ json={
+ "query": "q",
+ "collection_name": "c",
+ "allow_default_settings": True,
+ },
+ )
+ assert resp.status_code == 200
+ mock_ad.assert_called_once()
+ assert mock_ad.call_args.kwargs["settings_snapshot"] == {}
+ assert "allow_default_settings" not in mock_ad.call_args.kwargs
+
+
+# ===================================================================
+# End-to-end REST → research-function call path
+# ===================================================================
+
+
+class TestRestToResearchFunctionCallPath:
+ """Real-path tests that DO NOT mock the research functions themselves.
+ Instead they mock the LLM and search-engine factories one layer down,
+ so the actual REST handler → research function → signature-unpack
+ → function-body chain runs.
+
+ Catches the bug class where the REST handler passes kwargs the
+ research function does not accept. Mock-based tests at the
+ web.api.<research_fn> boundary use MagicMock which silently
+ swallows any kwargs and never raises TypeError. The end-to-end
+ path test in tests/api_tests/test_rest_api.py is marked
+ @requires_llm and therefore auto-skipped in CI (which runs with
+ LDR_TESTING_WITH_MOCKS=true), so until now no test verified the
+ REST endpoint could actually invoke the research function with
+ the kwargs it passes.
+ """
+
+ def test_analyze_documents_full_call_path(self, authed_client):
+ """Fires a real /api/v1/analyze_documents request. Does NOT
+ mock analyze_documents itself — only get_llm and get_search.
+ The real analyze_documents() body executes; if the REST
+ endpoint passes kwargs it does not accept, this surfaces as
+ a 500 (caught by the handler's broad except), not a silent
+ green test."""
+ mock_llm = MagicMock()
+ mock_response = MagicMock()
+ mock_response.content = "stub summary"
+ mock_llm.invoke.return_value = mock_response
+
+ mock_search = MagicMock()
+ mock_search.run.return_value = [
+ {"content": "stub document content", "title": "Stub Doc"}
+ ]
+
+ with _mock_access_control():
+ with (
+ patch(
+ "local_deep_research.api.research_functions.get_llm",
+ return_value=mock_llm,
+ ),
+ patch(
+ "local_deep_research.api.research_functions.get_search",
+ return_value=mock_search,
+ ),
+ ):
+ resp = authed_client.post(
+ "/api/v1/analyze_documents",
+ json={"query": "q", "collection_name": "c"},
+ )
+ assert resp.status_code == 200, (
+ f"REST endpoint failed to invoke analyze_documents() "
+ f"with the kwargs it passes. Response: {resp.get_data(as_text=True)}"
+ )
+ data = resp.get_json()
+ assert "summary" in data
+
+ # ---------------------------------------------------------------
+ # Stub data shared across the per-output assertions below. The
+ # LLM content includes [1]/[2] citations so the test also covers
+ # the "summary preserves citation markers" passthrough — if a
+ # future refactor adds citation normalization to analyze_documents,
+ # the citation-passthrough test below will flag it for review.
+ # ---------------------------------------------------------------
+ _QUERY = "What is quantum computing?"
+ _COLLECTION = "physics_papers"
+ _STUB_LLM_SUMMARY = "Qubits [1] enable superposition and entanglement [2]."
+ _STUB_DOCUMENTS = [
+ {
+ "content": "Qubits are quantum bits.",
+ "title": "Qubit Basics",
+ "link": "https://example.com/qubit",
+ },
+ {
+ "content": "Superposition allows simultaneous states.",
+ "title": "Superposition",
+ "link": "https://example.com/super",
+ },
+ ]
+
+ def _post_analyze_documents(self, authed_client):
+ """Fire a real /api/v1/analyze_documents request with the
+ stub LLM + stub search above. Returns (response, mock_llm,
+ mock_search) so individual tests can assert on whichever
+ slice they care about."""
+ mock_llm = MagicMock()
+ mock_llm_response = MagicMock()
+ mock_llm_response.content = self._STUB_LLM_SUMMARY
+ mock_llm.invoke.return_value = mock_llm_response
+
+ mock_search = MagicMock()
+ mock_search.run.return_value = self._STUB_DOCUMENTS
+
+ with _mock_access_control():
+ with (
+ patch(
+ "local_deep_research.api.research_functions.get_llm",
+ return_value=mock_llm,
+ ),
+ patch(
+ "local_deep_research.api.research_functions.get_search",
+ return_value=mock_search,
+ ),
+ ):
+ resp = authed_client.post(
+ "/api/v1/analyze_documents",
+ json={
+ "query": self._QUERY,
+ "collection_name": self._COLLECTION,
+ },
+ )
+ return resp, mock_llm, mock_search
+
+ # --- Per-output assertions (one test per response field) -------
+
+ def test_analyze_documents_response_shape_exact(self, authed_client):
+ """The full response equals an exact predetermined dict — no
+ unexpected keys, no missing keys. Catches new fields silently
+ added or existing fields silently removed."""
+ resp, _, _ = self._post_analyze_documents(authed_client)
+ assert resp.status_code == 200
+ assert resp.get_json() == {
+ "summary": self._STUB_LLM_SUMMARY,
+ "documents": self._STUB_DOCUMENTS,
+ "collection": self._COLLECTION,
+ "document_count": len(self._STUB_DOCUMENTS),
+ }
+
+ def test_analyze_documents_summary_equals_llm_content(self, authed_client):
+ """The ``summary`` field must equal the LLM's ``.content``
+ verbatim (modulo the no-op ``remove_think_tags`` transform —
+ our stub content has no <think> tags)."""
+ resp, _, _ = self._post_analyze_documents(authed_client)
+ assert resp.status_code == 200
+ assert resp.get_json()["summary"] == self._STUB_LLM_SUMMARY
+
+ def test_analyze_documents_summary_preserves_citations(self, authed_client):
+ """``[1]``/``[2]`` citation markers in the LLM response must
+ reach the client unchanged. analyze_documents() must not strip
+ or rewrite them. If a future refactor adds citation processing
+ here, this test will flag the behavior change."""
+ resp, _, _ = self._post_analyze_documents(authed_client)
+ assert resp.status_code == 200
+ summary = resp.get_json()["summary"]
+ assert "[1]" in summary, (
+ f"Citation [1] was stripped from summary: {summary!r}"
+ )
+ assert "[2]" in summary, (
+ f"Citation [2] was stripped from summary: {summary!r}"
+ )
+
+ def test_analyze_documents_documents_field_passes_through(
+ self, authed_client
+ ):
+ """The ``documents`` field equals the search engine's output
+ verbatim — analyze_documents() does not filter, reorder, or
+ mutate it."""
+ resp, _, _ = self._post_analyze_documents(authed_client)
+ assert resp.status_code == 200
+ assert resp.get_json()["documents"] == self._STUB_DOCUMENTS
+
+ def test_analyze_documents_collection_echoed(self, authed_client):
+ """The ``collection`` field equals the collection name the
+ client requested."""
+ resp, _, _ = self._post_analyze_documents(authed_client)
+ assert resp.status_code == 200
+ assert resp.get_json()["collection"] == self._COLLECTION
+
+ def test_analyze_documents_document_count_matches(self, authed_client):
+ """The ``document_count`` field equals ``len(documents)``."""
+ resp, _, _ = self._post_analyze_documents(authed_client)
+ assert resp.status_code == 200
+ assert resp.get_json()["document_count"] == len(self._STUB_DOCUMENTS)
+
+ # --- Inputs flowed to LLM/search assertions --------------------
+
+ def test_analyze_documents_search_called_with_query(self, authed_client):
+ """The search engine receives the user's query verbatim."""
+ resp, _, mock_search = self._post_analyze_documents(authed_client)
+ assert resp.status_code == 200
+ mock_search.run.assert_called_once_with(self._QUERY)
+
+ def test_analyze_documents_llm_prompt_includes_query(self, authed_client):
+ """The LLM's summarisation prompt embeds the user's query."""
+ resp, mock_llm, _ = self._post_analyze_documents(authed_client)
+ assert resp.status_code == 200
+ prompt = mock_llm.invoke.call_args[0][0]
+ assert self._QUERY in prompt
+
+ def test_analyze_documents_llm_prompt_includes_documents(
+ self, authed_client
+ ):
+ """The LLM's prompt embeds each stub document's content."""
+ resp, mock_llm, _ = self._post_analyze_documents(authed_client)
+ assert resp.status_code == 200
+ prompt = mock_llm.invoke.call_args[0][0]
+ for doc in self._STUB_DOCUMENTS:
+ assert doc["content"] in prompt, (
+ f"Document content missing from LLM prompt: {doc['content']!r}"
+ )
+
+ def test_analyze_documents_output_file_branch_passes_snapshot(
+ self, authed_client
+ ):
+ """When ``output_file`` is in the request body, ``analyze_documents``
+ calls ``write_file_verified`` to enforce the user's
+ ``api.allow_file_output`` setting. Verify the user's
+ ``settings_snapshot`` reaches ``write_file_verified`` so the
+ setting check uses user config, not JSON defaults / env vars.
+
+ This is the file-write branch of ``analyze_documents`` that the
+ other end-to-end tests skip because they don't pass
+ ``output_file``. Locks in the third of the four coordinated
+ threadings (signature → get_llm → get_search → write_file_verified)
+ — without this, a future revert of the ``settings_snapshot=None``
+ line at ``research_functions.py`` would silently regress the
+ file-output gate to ignore the user's setting.
+ """
+ write_call = {}
+
+ def _capture_write(*args, **kwargs):
+ write_call["args"] = args
+ write_call["kwargs"] = kwargs
+ # Return None — the real write_file_verified returns
+ # nothing on the no-op path, and analyze_documents only
+ # uses the side effect (file write).
+ return
+
+ mock_llm = MagicMock()
+ mock_llm_response = MagicMock()
+ mock_llm_response.content = self._STUB_LLM_SUMMARY
+ mock_llm.invoke.return_value = mock_llm_response
+
+ mock_search = MagicMock()
+ mock_search.run.return_value = self._STUB_DOCUMENTS
+
+ with _mock_access_control():
+ with (
+ patch(
+ "local_deep_research.api.research_functions.get_llm",
+ return_value=mock_llm,
+ ),
+ patch(
+ "local_deep_research.api.research_functions.get_search",
+ return_value=mock_search,
+ ),
+ patch(
+ "local_deep_research.security.file_write_verifier.write_file_verified",
+ side_effect=_capture_write,
+ ),
+ ):
+ resp = authed_client.post(
+ "/api/v1/analyze_documents",
+ json={
+ "query": self._QUERY,
+ "collection_name": self._COLLECTION,
+ "output_file": "/tmp/ldr_test_output.md",
+ },
+ )
+
+ assert resp.status_code == 200
+ assert write_call, (
+ "write_file_verified was not called — analyze_documents may "
+ "have skipped the output_file branch entirely."
+ )
+ snapshot = write_call["kwargs"].get("settings_snapshot")
+ assert snapshot is not None, (
+ "write_file_verified got settings_snapshot=None — user's "
+ "api.allow_file_output setting is ignored on the file-write "
+ "branch."
+ )
+ assert snapshot.get("_ldr_test_tracer") == "tracer-value", (
+ f"settings_snapshot reaching write_file_verified does not "
+ f"match the user's snapshot. Got: {snapshot!r}"
+ )
+ # The setting key write_file_verified is asked to enforce.
+ # Pinning it ensures the file-output gate isn't accidentally
+ # rerouted to a different (or no) setting.
+ assert "api.allow_file_output" in write_call["args"], (
+ f"write_file_verified called without 'api.allow_file_output' "
+ f"setting key. args: {write_call['args']!r}"
+ )
+
+
+# ===================================================================
+# Research-function signature compatibility
+# ===================================================================
+
+
+class TestResearchFunctionSignatures:
+ """Static checks that the programmatic-API research functions accept
+ the kwargs that authed REST endpoints pass through
+ ``_load_user_context_into_params``. No mocking — operates purely on
+ ``inspect.signature``. Catches the bug class where an endpoint passes
+ ``**params`` to a research function whose signature doesn't accept the
+ keys, which would TypeError at runtime but pass mock-based tests
+ (``MagicMock(return_value=...)`` swallows arbitrary kwargs).
+ """
+
+ @pytest.mark.parametrize(
+ "fn_name,extra_required",
+ [
+ ("quick_summary", {}),
+ ("generate_report", {}),
+ ("analyze_documents", {"collection_name": "c"}),
+ ],
+ )
+ def test_endpoint_call_binds_to_function_signature(
+ self, fn_name, extra_required
+ ):
+ """Reproduce the exact call shape REST endpoints use:
+ ``fn(query=..., **params)`` where params contains the keys
+ ``_load_user_context_into_params`` writes. ``sig.bind_partial``
+ raises TypeError if any kwarg is rejected by the signature —
+ catches the bug class for all three functions, including ones
+ with ``**kwargs`` where a plain "is the kwarg accepted" check
+ would short-circuit on ``has_var_keyword=True`` and never
+ actually validate.
+ """
+ import inspect
+
+ from local_deep_research.api import research_functions
+
+ fn = getattr(research_functions, fn_name)
+ sig = inspect.signature(fn)
+
+ endpoint_call_kwargs = {
+ "query": "q",
+ "username": "u",
+ "settings_snapshot": {},
+ "programmatic_mode": False,
+ **extra_required,
+ }
+ try:
+ sig.bind_partial(**endpoint_call_kwargs)
+ except TypeError as exc:
+ pytest.fail(
+ f"REST endpoint cannot call {fn_name}{sig}: {exc}. "
+ f"This bug class — endpoint passes kwargs the function "
+ f"rejects — caused the original /analyze_documents "
+ f"runtime TypeError that mock-based tests missed."
+ )
+
# ===================================================================
# _serialize_results helper
@@ -1047,7 +1535,3 @@ class TestHttpMethods:
def test_analyze_documents_rejects_get(self, authed_client):
resp = authed_client.get("/api/v1/analyze_documents")
assert resp.status_code == 405
-
- def test_quick_summary_test_rejects_get(self, authed_client):
- resp = authed_client.get("/api/v1/quick_summary_test")
- assert resp.status_code == 405