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(benchmark): record LDR version + redacted settings snapshot at benchmark start (#3844)

LearningCircuit374d075f1b14
diff --git a/changelog.d/3844.bugfix.md b/changelog.d/3844.bugfix.md
new file mode 100644
index 0000000000..c29ef47e58
--- /dev/null
+++ b/changelog.d/3844.bugfix.md
@@ -0,0 +1 @@
+Wikipedia search no longer floods the log with per-title tracebacks when the MediaWiki API rate-limits a query — the engine now detects the JSON-decode error pattern, logs a single warning, and bails out of the batch with whatever previews it collected. Fetched pages that come back empty (paywalls, JS-only SPAs, blank 200s) and LLM extractions that return an empty summary now short-circuit to `NOT RELEVANT` without locking the URL into the citation collector, so the agent is free to re-fetch it later under a different focus.
diff --git a/changelog.d/3844.feature.md b/changelog.d/3844.feature.md
new file mode 100644
index 0000000000..a06eb585ea
--- /dev/null
+++ b/changelog.d/3844.feature.md
@@ -0,0 +1 @@
+**Benchmark YAML downloads now show the LDR version and `date_tested` from when the benchmark *ran*, not at download time.** Previously a v1.6.5 run downloaded on v1.6.7 incorrectly stamped v1.6.7 — making cross-run comparison impossible. The full per-key settings snapshot active at the run (API keys redacted) is now captured at run time and is available **opt-in** via the new **Export → "Include settings snapshot"** checkbox; by default the YAML contains only the summary configuration, so it's safe to share without exposing internal URLs or local paths. Benchmarks created before this release show `ldr_version: unknown (pre-0014 run)` and, when settings are requested, `settings: null` — no backfill, but no breakage either.
diff --git a/changelog.d/3947.bugfix.md b/changelog.d/3947.bugfix.md
new file mode 100644
index 0000000000..74f26a35eb
--- /dev/null
+++ b/changelog.d/3947.bugfix.md
@@ -0,0 +1 @@
+`SettingsManager.get_all_settings()` no longer crashes when the DB contains a row whose `type` column holds an enum value no longer in `SettingType` (e.g. legacy `'CHAT'`-typed rows from a removed feature). The handler now catches `LookupError` alongside `SQLAlchemyError` and falls back to defaults-only — strictly safer than crashing every caller (`/settings/api`, benchmark start, research start, MCP).
diff --git a/changelog.d/3947.security.md b/changelog.d/3947.security.md
new file mode 100644
index 0000000000..3c7a05a7af
--- /dev/null
+++ b/changelog.d/3947.security.md
@@ -0,0 +1 @@
+**`/settings/api` no longer leaks env-overridden API keys to authenticated users.** The bulk settings JSON endpoint now redacts password-typed values (`llm.openai.api_key`, search-engine API keys, etc.) so they come back as `[REDACTED]` instead of plaintext. Metadata is preserved so the UI still renders correctly. Note: the settings form template still pre-fills password inputs server-side — that's a separate UX issue and not addressed here.
diff --git a/src/local_deep_research/advanced_search_system/tools/fetch/__init__.py b/src/local_deep_research/advanced_search_system/tools/fetch/__init__.py
index df422efa01..483c19b634 100644
--- a/src/local_deep_research/advanced_search_system/tools/fetch/__init__.py
+++ b/src/local_deep_research/advanced_search_system/tools/fetch/__init__.py
@@ -183,8 +183,24 @@ def _make_summary_fetch_tool(
if result.get("status") != "success":
return f"Failed to fetch {url}: {result.get('error', 'unknown error')}"
- title = result.get("title", "")
- content = result.get("content", "")
+ title = result.get("title") or ""
+ content = result.get("content") or ""
+
+ # Guard 1 — empty page content (paywalls, JS-only SPAs that
+ # static fetch can't render, deleted pages with HTTP 200).
+ # Skipping the LLM call here means we don't pay the round-trip
+ # to summarise nothing, AND we don't register an empty
+ # citation in the collector — `_register_in_collector` caches
+ # by URL, so an empty snippet would lock the URL in as
+ # "already fetched, nothing here" and the agent would never
+ # retry it under a different focus.
+ if not content.strip():
+ logger.info(
+ f"[FETCH] mode={mode_label} url={url} — "
+ "empty page content, returning NOT RELEVANT without "
+ "LLM call or collector registration"
+ )
+ return f"NOT RELEVANT (no extractable content at {url})"
fmt_kwargs = {
"focus": focus,
@@ -226,8 +242,17 @@ def _make_summary_fetch_tool(
)
logger.info("\n".join(log_lines))
+ # Guard 2 — empty LLM summary. The model decided nothing on
+ # the page answers the focus (or it returned a malformed/empty
+ # response). Treat as NOT RELEVANT and skip collector
+ # registration: the agent should be free to re-fetch the URL
+ # later with a different focus instead of seeing it as
+ # already-cached with an empty body.
+ if not summary:
+ return f"NOT RELEVANT (no spans matched focus at {url})"
+
cite_idx = _register_in_collector(
- collector, url, title, summary or content
+ collector, url, title, summary
)
return f"[{cite_idx}] Title: {title}\nURL: {url}\n\n{summary}"
except PolicyDeniedError:
diff --git a/src/local_deep_research/benchmarks/web_api/benchmark_routes.py b/src/local_deep_research/benchmarks/web_api/benchmark_routes.py
index 8740bbc5b3..a68a7d233e 100644
--- a/src/local_deep_research/benchmarks/web_api/benchmark_routes.py
+++ b/src/local_deep_research/benchmarks/web_api/benchmark_routes.py
@@ -445,6 +445,21 @@ def get_benchmark_history():
"id": run.id,
"run_name": run.run_name or f"Benchmark #{run.id}",
"created_at": run.created_at.isoformat(),
+ # `start_time` is the wall-clock instant work began
+ # (status flipped to IN_PROGRESS); used by the YAML
+ # download for `date_tested` instead of the (broken)
+ # download-time stamp. NULL on rows that never started.
+ "start_time": run.start_time.isoformat()
+ if run.start_time
+ else None,
+ # `ldr_version` is captured by start_benchmark; NULL
+ # on rows created before migration 0014. The YAML
+ # download substitutes "unknown (pre-0014 run)".
+ # `settings_snapshot` is intentionally NOT included
+ # here — it's ~184KB per run and would balloon the
+ # history list response. Loaded on-demand from
+ # /api/results/<id>/export when YAML is downloaded.
+ "ldr_version": run.ldr_version,
"total_examples": run.total_examples,
"completed_examples": run.completed_examples,
"overall_accuracy": run.overall_accuracy,
@@ -597,21 +612,57 @@ def get_benchmark_results(benchmark_run_id: int):
)
@login_required
def export_benchmark_results(benchmark_run_id: int):
- """Get lightweight results for YAML export (no full_response/sources/grader_response)."""
+ """Get lightweight results for YAML export plus run-level provenance.
+
+ Returns a `metadata` block alongside the per-result rows so the YAML
+ download path can stamp the version/settings that ran the benchmark
+ instead of falling back to download-time values. Pre-0014 rows return
+ NULL for the new metadata fields. The `success: True` envelope is
+ preserved so the existing JS contract (5 callsites in
+ benchmark_results.html) keeps working.
+ """
try:
from sqlalchemy.orm import load_only
- from ...database.models.benchmark import BenchmarkResult
+ from ...database.models.benchmark import (
+ BenchmarkResult,
+ BenchmarkRun,
+ )
from ...database.session_context import get_user_db_session
- from flask import session as flask_session
+ from flask import request, session as flask_session
username = flask_session["username"]
+ # The ~184KB settings snapshot is only loaded/returned when the
+ # client opts in (Export -> "Include settings snapshot"); the
+ # default summary download skips it to avoid transferring a blob it
+ # would discard.
+ include_settings = request.args.get("include_settings", "").lower() in (
+ "1",
+ "true",
+ )
logger.info(
"Exporting benchmark results for run {} by user {}",
benchmark_run_id,
username,
)
with get_user_db_session(username) as session:
+ # Fetch only the provenance columns we need from BenchmarkRun.
+ # `load_only` keeps us off the heavy JSON config blobs (and the
+ # settings_snapshot blob unless it was requested).
+ run_columns = [
+ BenchmarkRun.ldr_version,
+ BenchmarkRun.start_time,
+ BenchmarkRun.created_at,
+ ]
+ if include_settings:
+ run_columns.append(BenchmarkRun.settings_snapshot)
+ run = (
+ session.query(BenchmarkRun)
+ .options(load_only(*run_columns))
+ .filter(BenchmarkRun.id == benchmark_run_id)
+ .one_or_none()
+ )
+
results = (
session.query(BenchmarkResult)
.options(
@@ -650,12 +701,43 @@ def export_benchmark_results(benchmark_run_id: int):
}
)
+ # Build metadata block. Each field is independently null-checked
+ # so a pre-0014 row, or an in-flight run with no start_time,
+ # serializes cleanly as JSON null.
+ if run is not None:
+ started_at = (
+ run.start_time.isoformat()
+ if run.start_time
+ else (
+ run.created_at.isoformat() if run.created_at else None
+ )
+ )
+ metadata = {
+ "ldr_version": run.ldr_version,
+ "started_at": started_at,
+ "settings_snapshot": (
+ run.settings_snapshot if include_settings else None
+ ),
+ }
+ else:
+ metadata = {
+ "ldr_version": None,
+ "started_at": None,
+ "settings_snapshot": None,
+ }
+
logger.info(
"Exported {} results for benchmark run {}",
len(formatted),
benchmark_run_id,
)
- return jsonify({"success": True, "results": formatted})
+ return jsonify(
+ {
+ "success": True,
+ "metadata": metadata,
+ "results": formatted,
+ }
+ )
except Exception:
logger.exception("Error exporting benchmark results")
diff --git a/src/local_deep_research/benchmarks/web_api/benchmark_service.py b/src/local_deep_research/benchmarks/web_api/benchmark_service.py
index bd11115208..4e7950e8d5 100644
--- a/src/local_deep_research/benchmarks/web_api/benchmark_service.py
+++ b/src/local_deep_research/benchmarks/web_api/benchmark_service.py
@@ -9,6 +9,7 @@ from enum import Enum
from typing import Any, Dict, List, Optional
from loguru import logger
+from sqlalchemy.exc import SQLAlchemyError
from ...api.research_functions import quick_summary
from ...settings.manager import SnapshotSettingsContext
@@ -243,11 +244,34 @@ class BenchmarkService:
f"Benchmark run {benchmark_run_id} not found"
)
- # Create settings snapshot for thread safety
+ # Create settings snapshot for thread safety + provenance.
+ # The settings snapshot is BEST-EFFORT provenance, not a
+ # critical path: a recoverable read failure must not break
+ # the user's ability to start a benchmark. We catch only the
+ # failures that can legitimately escape get_all_settings:
+ # SQLAlchemyError (transient DB issues) and LookupError /
+ # ValueError (a stale enum-typed settings row, e.g. a legacy
+ # 'CHAT' value that fails enum coercion). Those degrade to an
+ # empty snapshot — ldr_version is still recorded. Anything
+ # else (a genuine programming error) is deliberately NOT
+ # swallowed here: it propagates to the outer handler, which
+ # logs a full traceback and marks the run FAILED — the right
+ # outcome, since a settings subsystem that breaks unexpectedly
+ # would also corrupt the benchmark's own config reads.
from local_deep_research.settings import SettingsManager
settings_manager = SettingsManager(session)
- settings_snapshot = settings_manager.get_all_settings()
+ try:
+ settings_snapshot = settings_manager.get_all_settings()
+ except (SQLAlchemyError, LookupError, ValueError):
+ # Use logger.exception so the traceback goes to stderr
+ # without splatting `repr(exc)` into the message body —
+ # exception details may include user data.
+ logger.exception(
+ "Failed to capture settings snapshot for benchmark "
+ f"{benchmark_run_id}; running with empty snapshot."
+ )
+ settings_snapshot = {}
# Get user password for metrics tracking in background thread
from flask import session as flask_session
@@ -278,7 +302,21 @@ class BenchmarkService:
"settings_snapshot": settings_snapshot, # Add settings snapshot
}
- # Update status in database
+ # Update status in database. Persist provenance (ldr_version
+ # + redacted settings_snapshot) BEFORE the commit so the
+ # YAML download can later reproduce the run; the snapshot
+ # already exists in memory from line 306, we just store the
+ # redacted form so secrets don't sit in the DB even though
+ # SQLCipher protects at rest.
+ from local_deep_research import __version__
+ from local_deep_research.security.data_sanitizer import (
+ DataSanitizer,
+ )
+
+ benchmark_run.ldr_version = __version__
+ benchmark_run.settings_snapshot = (
+ DataSanitizer.redact_settings_snapshot(settings_snapshot)
+ )
benchmark_run.status = BenchmarkStatus.IN_PROGRESS
benchmark_run.start_time = datetime.now(UTC)
session.commit()
diff --git a/src/local_deep_research/database/migrations/versions/0014_benchmark_run_version_and_snapshot.py b/src/local_deep_research/database/migrations/versions/0014_benchmark_run_version_and_snapshot.py
new file mode 100644
index 0000000000..1f71cb5301
--- /dev/null
+++ b/src/local_deep_research/database/migrations/versions/0014_benchmark_run_version_and_snapshot.py
@@ -0,0 +1,94 @@
+"""Add ldr_version and settings_snapshot columns to benchmark_runs.
+
+Background
+==========
+The YAML downloaded from a benchmark run is currently stamped with the
+*current* app version and *current* date at download time, not the values
+that were active when the benchmark actually ran (see
+``benchmark_results.html:593-596`` — ``new Date()`` and the
+``meta[name="app-version"]`` tag). A v1.6.5 run downloaded on v1.6.7
+incorrectly shows v1.6.7. Reproducibility breaks because cross-run
+comparisons can't trust the stamped version. Additionally, only ~3
+settings (temperature, context_window, max_tokens) make it into the
+YAML — the ~30-50 other settings that affect benchmark behaviour
+(``search.iterations``, ``search.questions_per_iteration``,
+``search.fetch.mode``, etc.) are lost.
+
+This migration adds two nullable columns to ``benchmark_runs``:
+
+- ``ldr_version`` (String(32)) — the LDR version active when the
+ benchmark started, captured at ``start_benchmark`` time.
+- ``settings_snapshot`` (JSON) — the redacted full settings snapshot
+ (``DataSanitizer.redact_settings_snapshot`` strips API keys),
+ preserving the per-key metadata so downstream consumers can render
+ human-readable diffs.
+
+Existing rows
+=============
+Both columns are nullable. Pre-0014 rows get ``NULL`` and the YAML
+download path treats this as "pre-0014 run" (UI shows
+``ldr_version: unknown (pre-0014 run)`` and a ``# settings: not
+recorded`` comment). No backfill — there's no source of truth for what
+those rows actually ran with.
+
+Idempotent
+==========
+The upgrade and downgrade both inspect the table and column state before
+mutating, so re-running the migration after a partial failure is safe.
+
+Revision ID: 0014
+Revises: 0013
+Create Date: 2026-05-03
+"""
+
+from __future__ import annotations
+
+import sqlalchemy as sa
+from alembic import op
+from loguru import logger
+from sqlalchemy import inspect
+
+revision = "0014"
+down_revision = "0013"
+branch_labels = None
+depends_on = None
+
+
+def _column_exists(table: str, column: str) -> bool:
+ """Check whether ``column`` exists on ``table`` in the current DB."""
+ insp = inspect(op.get_bind())
+ if not insp.has_table(table):
+ return False
+ return column in {c["name"] for c in insp.get_columns(table)}
+
+
+def upgrade() -> None:
+ if not inspect(op.get_bind()).has_table("benchmark_runs"):
+ return
+
+ added: list[str] = []
+ with op.batch_alter_table("benchmark_runs") as batch_op:
+ if not _column_exists("benchmark_runs", "ldr_version"):
+ batch_op.add_column(
+ sa.Column("ldr_version", sa.String(32), nullable=True)
+ )
+ added.append("ldr_version")
+ if not _column_exists("benchmark_runs", "settings_snapshot"):
+ batch_op.add_column(
+ sa.Column("settings_snapshot", sa.JSON, nullable=True)
+ )
+ added.append("settings_snapshot")
+
+ if added:
+ logger.info("0014: added benchmark_runs columns: {}", ", ".join(added))
+
+
+def downgrade() -> None:
+ if not inspect(op.get_bind()).has_table("benchmark_runs"):
+ return
+
+ with op.batch_alter_table("benchmark_runs") as batch_op:
+ if _column_exists("benchmark_runs", "settings_snapshot"):
+ batch_op.drop_column("settings_snapshot")
+ if _column_exists("benchmark_runs", "ldr_version"):
+ batch_op.drop_column("ldr_version")
diff --git a/src/local_deep_research/database/models/benchmark.py b/src/local_deep_research/database/models/benchmark.py
index 8122f73752..eb695963a0 100644
--- a/src/local_deep_research/database/models/benchmark.py
+++ b/src/local_deep_research/database/models/benchmark.py
@@ -79,6 +79,12 @@ class BenchmarkRun(Base):
start_time = Column(UtcDateTime, nullable=True)
end_time = Column(UtcDateTime, nullable=True)
+ # Provenance — captured at start_benchmark time so the YAML download
+ # reflects the version/settings that ran the benchmark, not the version
+ # at download time. NULL on rows created before migration 0014.
+ ldr_version = Column(String(32), nullable=True)
+ settings_snapshot = Column(JSON, nullable=True)
+
# Progress tracking
total_examples = Column(Integer, default=0, nullable=False)
completed_examples = Column(Integer, default=0, nullable=False)
diff --git a/src/local_deep_research/security/data_sanitizer.py b/src/local_deep_research/security/data_sanitizer.py
index fc75ac346b..073f228764 100644
--- a/src/local_deep_research/security/data_sanitizer.py
+++ b/src/local_deep_research/security/data_sanitizer.py
@@ -121,6 +121,76 @@ class DataSanitizer:
# Return primitives unchanged
return data
+ @staticmethod
+ def redact_settings_snapshot(
+ snapshot: Any,
+ sensitive_keys: Set[str] | None = None,
+ redaction_text: str = "[REDACTED]",
+ ) -> Any:
+ """Redact secret values in a settings snapshot while preserving metadata.
+
+ A settings snapshot from ``SettingsManager.get_all_settings()`` has the
+ nested-with-metadata shape ``{dotted_key: {"value": ..., "ui_element":
+ ..., "type": ..., ...}}``. The ordinary ``redact()`` method does not
+ catch secrets in this shape: the outer dotted key (e.g.
+ ``"llm.openai.api_key"``) is not in the sensitive-name set (only the
+ suffix ``"api_key"`` is), and the inner key ``"value"`` is not
+ sensitive — so the secret survives unredacted.
+ ``redact_settings_snapshot`` handles the shape correctly:
+
+ - Replaces ``entry["value"]`` with ``redaction_text`` when the entry
+ is sensitive (``ui_element == "password"`` OR the last dotted
+ segment of the outer key matches a sensitive name).
+ - Preserves all metadata (``ui_element``, ``type``, ``description``,
+ etc.) so YAML diffs can still show "this key existed."
+ - Leaves empty values (``None``, ``""``, ``[]``, ``{}``) unredacted
+ so diffs of "unset" settings stay readable.
+ - Pure function: does not mutate the input.
+
+ Entries that don't have the metadata-wrapper shape (e.g. mixed
+ snapshots that contain bare values) are passed through untouched —
+ this is intentional so the helper is safe to call on any dict
+ without crashing.
+
+ Args:
+ snapshot: A settings snapshot dict.
+ sensitive_keys: Override the default set of sensitive name
+ suffixes. Defaults to ``DataSanitizer.DEFAULT_SENSITIVE_KEYS``.
+ redaction_text: Replacement string for redacted values.
+
+ Returns:
+ New dict with secret values replaced.
+
+ Example:
+ >>> snap = {"llm.openai.api_key": {"value": "sk-x", "ui_element": "password"}}
+ >>> DataSanitizer.redact_settings_snapshot(snap)
+ {'llm.openai.api_key': {'value': '[REDACTED]', 'ui_element': 'password'}}
+ """
+ if not isinstance(snapshot, dict):
+ return snapshot
+
+ sensitive_lower = {
+ k.lower()
+ for k in (sensitive_keys or DataSanitizer.DEFAULT_SENSITIVE_KEYS)
+ }
+ out: dict = {}
+ for key, entry in snapshot.items():
+ if not isinstance(entry, dict) or "value" not in entry:
+ out[key] = entry
+ continue
+ new_entry = dict(entry) # shallow copy preserves metadata
+ suffix = key.rsplit(".", 1)[-1].lower()
+ is_secret = (
+ entry.get("ui_element") == "password"
+ or suffix in sensitive_lower
+ )
+ value = entry.get("value")
+ # Only redact non-empty values — leave empty fields readable.
+ if is_secret and value not in (None, "", [], {}):
+ new_entry["value"] = redaction_text
+ out[key] = new_entry
+ return out
+
# Convenience functions for direct use
def sanitize_data(data: Any, sensitive_keys: Set[str] | None = None) -> Any:
diff --git a/src/local_deep_research/settings/manager.py b/src/local_deep_research/settings/manager.py
index 52256cfeaa..03e14a6a67 100644
--- a/src/local_deep_research/settings/manager.py
+++ b/src/local_deep_research/settings/manager.py
@@ -859,7 +859,15 @@ class SettingsManager(ISettingsManager):
# Override with database settings
try:
db_settings = self.__query_settings()
- except SQLAlchemyError:
+ except (SQLAlchemyError, LookupError):
+ # LookupError fires when a row's `type` column holds an enum
+ # value that's no longer in `SettingType` (e.g. legacy 'CHAT'-
+ # typed rows from removed features). The previous handler only
+ # caught SQLAlchemyError, so a single stale row would crash the
+ # whole snapshot — and every caller of get_all_settings (the
+ # /settings/api endpoint, benchmark start, research start, MCP
+ # entry points, …) downstream of it. Falling back to defaults-
+ # only is strictly safer than crashing.
logger.exception(
"Error querying settings from database in get_all_settings"
)
diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.py
index 4044e7cb18..4011ee937b 100644
--- a/src/local_deep_research/web/routes/settings_routes.py
+++ b/src/local_deep_research/web/routes/settings_routes.py
@@ -848,12 +848,30 @@ def save_settings(db_session=None, settings_manager=None):
@login_required
@with_user_session()
def api_get_all_settings(db_session=None, settings_manager=None):
- """Get all settings"""
+ """Get all settings.
+
+ The response is redacted via ``DataSanitizer.redact_settings_snapshot``
+ so password-typed values (API keys, OAuth tokens, etc.) come back as
+ ``"[REDACTED]"`` instead of plaintext. The previous implementation
+ leaked env-overridden API keys to anyone who could authenticate as a
+ user — even though the values render unmasked into the server-side
+ settings form too (a separate template-level concern), the JSON API
+ is its own surface area: it gets cached by clients, logged by
+ proxies, and copy/pasted into bug reports. Redaction here is
+ defense-in-depth.
+
+ No JS caller round-trips this endpoint's values back into a form
+ (the settings form is server-rendered from the template, which uses
+ the model directly), so redacting the response does not break the UI.
+ """
try:
+ from ...security.data_sanitizer import DataSanitizer
+
# Get query parameters
category = request.args.get("category")
- # Get settings
+ # Get settings (nested-with-metadata shape:
+ # {key: {value, ui_element, type, ...}})
settings = settings_manager.get_all_settings()
# Filter by category if requested
@@ -871,6 +889,8 @@ def api_get_all_settings(db_session=None, settings_manager=None):
if key in category_keys
}
+ settings = DataSanitizer.redact_settings_snapshot(settings)
+
return jsonify({"status": "success", "settings": settings})
except Exception:
logger.exception("Error getting settings")
diff --git a/src/local_deep_research/web/templates/pages/benchmark_results.html b/src/local_deep_research/web/templates/pages/benchmark_results.html
index 36d4bbe2aa..a6e5ab3483 100644
--- a/src/local_deep_research/web/templates/pages/benchmark_results.html
+++ b/src/local_deep_research/web/templates/pages/benchmark_results.html
@@ -266,12 +266,25 @@ function createRunCard(run) {
<div class="ldr-summary-item">
<div style="display: flex; gap: 8px; flex-wrap: wrap; justify-content: center;">
${status === 'completed' ?
- `<button class="btn ldr-btn-outline btn-sm ldr-download-btn" onclick="event.stopPropagation(); downloadBenchmarkYAML(${run.id}, false)" title="Summary only">
- <i aria-hidden="true" class="fas fa-download"></i> YAML
- </button>
- <button class="btn ldr-btn-outline btn-sm ldr-download-btn" onclick="event.stopPropagation(); downloadBenchmarkYAML(${run.id}, true)" title="Summary + individual questions &amp; answers">
- <i aria-hidden="true" class="fas fa-download"></i> + Examples
- </button>` : ''
+ `<div class="dropdown d-inline-block" onclick="event.stopPropagation()">
+ <button class="btn ldr-btn-outline btn-sm ldr-download-btn dropdown-toggle" type="button" id="export-dropdown-${run.id}" data-bs-toggle="dropdown" aria-expanded="false" title="Export benchmark YAML">
+ <i aria-hidden="true" class="fas fa-download"></i> Export
+ </button>
+ <ul class="dropdown-menu" aria-labelledby="export-dropdown-${run.id}">
+ <li><a class="dropdown-item" href="#" onclick="event.preventDefault(); event.stopPropagation(); downloadBenchmarkYAML(${run.id}, false, document.getElementById('include-settings-${run.id}').checked)">
+ <i aria-hidden="true" class="fas fa-download"></i> Download YAML (summary)
+ </a></li>
+ <li><a class="dropdown-item" href="#" onclick="event.preventDefault(); event.stopPropagation(); downloadBenchmarkYAML(${run.id}, true, document.getElementById('include-settings-${run.id}').checked)">
+ <i aria-hidden="true" class="fas fa-download"></i> Download YAML + examples
+ </a></li>
+ <li><hr class="dropdown-divider"></li>
+ <li class="dropdown-item" onclick="event.stopPropagation()">
+ <label style="display:flex; align-items:center; gap:6px; margin:0; cursor:pointer;">
+ <input type="checkbox" id="include-settings-${run.id}" onclick="event.stopPropagation()"> Include settings snapshot
+ </label>
+ </li>
+ </ul>
+ </div>` : ''
}
${status === 'in_progress' ?
`<button class="btn ldr-btn-outline btn-sm ldr-delete-btn" onclick="event.stopPropagation(); cancelAndDeleteBenchmarkRun(${run.id})">
@@ -580,7 +593,55 @@ function yamlEscape(str) {
.replace(/\t/g, '\\t');
}
-async function downloadBenchmarkYAML(runId, includeExamples = false) {
+// Format a single setting value as a YAML scalar / flow node.
+// Booleans/numbers emit bare; null as `null`; arrays/objects as inline JSON
+// (valid YAML 1.2 flow syntax — JSON is a YAML 1.2 superset). Strings are
+// always double-quoted via yamlEscape so colons, hashes, leading dashes,
+// and YAML reserved words (true/no/null/~) are unambiguous.
+function formatSettingValue(value) {
+ if (value === null || value === undefined) return 'null';
+ if (typeof value === 'boolean') return value ? 'true' : 'false';
+ if (typeof value === 'number') {
+ if (!Number.isFinite(value)) return 'null';
+ return String(value);
+ }
+ if (Array.isArray(value) || typeof value === 'object') {
+ try {
+ return JSON.stringify(value);
+ } catch (e) {
+ // Defensive: circular references etc. Fall back to null.
+ return 'null';
+ }
+ }
+ return `"${yamlEscape(value)}"`;
+}
+
+// Build a `settings:` YAML block from a redacted settings snapshot dict.
+// Snapshot is the {key: {value, ui_element, type, ...}} nested-with-metadata
+// shape produced by SettingsManager.get_all_settings(). Tolerates flat
+// snapshots and missing `value` keys without crashing.
+function formatSettingsSnapshot(snapshot) {
+ if (snapshot == null) {
+ return 'settings: null # snapshot not captured for this run\n';
+ }
+ const keys = Object.keys(snapshot).sort();
+ if (keys.length === 0) return 'settings: {}\n';
+ let out = 'settings:\n';
+ for (const key of keys) {
+ const entry = snapshot[key];
+ const raw = (entry && typeof entry === 'object' && 'value' in entry)
+ ? entry.value
+ : (entry && typeof entry === 'object' ? null : entry);
+ // Quote keys containing YAML-significant chars. Plain dotted keys
+ // (e.g. `llm.model`) are valid plain scalars — no quoting needed.
+ const needsQuote = /[:#\s\[\]\{\},&*!|>'"%@`]/.test(key) || /^[-?]/.test(key);
+ const formattedKey = needsQuote ? `"${yamlEscape(key)}"` : key;
+ out += ` ${formattedKey}: ${formatSettingValue(raw)}\n`;
+ }
+ return out;
+}
+
+async function downloadBenchmarkYAML(runId, includeExamples = false, includeSettings = false) {
try {
// Find the run in our local data
const run = benchmarkRuns.find(r => r.id === runId);
@@ -589,11 +650,45 @@ async function downloadBenchmarkYAML(runId, includeExamples = false) {
return;
}
- // Get current date for filename
- const date = new Date().toISOString().split('T')[0];
-
- // Get app version from meta tag
- const appVersion = document.querySelector('meta[name="app-version"]')?.content || 'Could not fetch version';
+ // Always fetch /export to stamp the YAML with the LDR version + the
+ // date the benchmark RAN — not the current app version / current date
+ // the user happens to download on. The full settings snapshot is only
+ // requested when the user opts in (it's ~184KB and exposes the full
+ // config), so the default summary download stays lean and shareable.
+ // Pre-0014 rows return null fields and the YAML falls back to
+ // "unknown (pre-0014 run)" gracefully.
+ let exportData = { metadata: {}, results: [] };
+ try {
+ const exportUrl = `/benchmark/api/results/${runId}/export${includeSettings ? '?include_settings=1' : ''}`;
+ const exportResponse = await fetch(exportUrl);
+ exportData = await exportResponse.json();
+ } catch (e) {
+ console.error('Error fetching benchmark export:', e);
+ // Continue with cached run data only — YAML will lack settings_snapshot
+ }
+ const meta = exportData.metadata || {};
+
+ // Filename uses today's date for sortability — we want the file to
+ // sort by when YOU downloaded it, not when the benchmark ran.
+ const fileDate = new Date().toISOString().split('T')[0];
+
+ // YAML's `date_tested` field MUST come from the benchmark's actual
+ // start_time (or created_at as fallback). External parsers — most
+ // importantly /home/coder1/code/ldr-benchmarks/scripts/build_leaderboards.py
+ // — read this field for the public HuggingFace leaderboard. Pulling
+ // from new Date() (the old behaviour) silently corrupted that history.
+ const startedAt = meta.started_at || run.start_time || run.created_at;
+ const dateTested = startedAt
+ ? String(startedAt).split('T')[0]
+ : fileDate;
+
+ // Same story for ldr_version: prefer the value that was active at
+ // benchmark START, then the cached run field, then a clear sentinel
+ // for pre-0014 rows so users can tell the YAML predates this feature.
+ // Do NOT fall back to the current app version — stamping today's
+ // version onto a historical run is the exact bug this feature fixes
+ // (a v1.6.5 run downloaded on v1.6.7 must not read 1.6.7).
+ const ldrVersion = meta.ldr_version || run.ldr_version || 'unknown (pre-0014 run)';
// Extract model name and clean it for filename
const modelName = run.search_config?.model_name || 'unknown-model';
@@ -648,39 +743,41 @@ ${avgSearchResults !== 'N/A' ? `average_results_per_query: ${avgSearchResults}\n
configuration:
temperature: ${run.search_config?.temperature ?? 'N/A'}
${isLocalProvider && localContextWindow != null ? ` context_window: ${localContextWindow} # captured at benchmark start\n` : ''}${!isLocalProvider && contextWindowUnrestricted != null ? ` context_window_unrestricted: ${contextWindowUnrestricted ? 'yes' : 'no'} # captured at benchmark start\n` : ''}${!isLocalProvider && !contextWindowUnrestricted && cloudContextWindow != null ? ` context_window: ${cloudContextWindow} # captured at benchmark start\n` : ''}${maxTokens != null ? ` max_tokens: ${maxTokens} # captured at benchmark start\n` : ''}${evaluatorYaml}versions:
- ldr_version: ${appVersion}
-date_tested: ${date}
+ ldr_version: ${ldrVersion}
+date_tested: ${dateTested}
`;
- // Optionally append individual examples
+ // Optionally append the full (redacted) settings snapshot. Opt-in
+ // only: the default download stays a shareable summary and never
+ // ships internal URLs / local paths. formatSettingsSnapshot handles
+ // a null snapshot (pre-0014 rows) as "settings: null # ...".
+ if (includeSettings) {
+ yamlContent += formatSettingsSnapshot(meta.settings_snapshot);
+ }
+
+ // Optionally append individual examples (already fetched in exportData)
if (includeExamples) {
- try {
- const exportResponse = await fetch(`/benchmark/api/results/${runId}/export`);
- const exportData = await exportResponse.json();
-
- if (exportData.success && exportData.results.length > 0) {
- yamlContent += `examples:\n`;
-
- for (const ex of exportData.results) {
- const result = ex.is_correct === true ? 'correct'
- : ex.is_correct === false ? 'incorrect'
- : 'not_graded';
- const time = ex.processing_time != null
- ? Number(ex.processing_time).toFixed(1)
- : null;
-
- yamlContent += ` - question: "${yamlEscape(ex.question)}"\n`;
- yamlContent += ` correct_answer: "${yamlEscape(ex.correct_answer)}"\n`;
- yamlContent += ` model_answer: "${yamlEscape(ex.model_answer)}"\n`;
- yamlContent += ` result: ${result}\n`;
- yamlContent += ` dataset: ${ex.dataset_type || 'unknown'}\n`;
- if (time !== null) {
- yamlContent += ` processing_time_seconds: ${time}\n`;
- }
+ if (exportData.success && exportData.results && exportData.results.length > 0) {
+ yamlContent += `examples:\n`;
+
+ for (const ex of exportData.results) {
+ const result = ex.is_correct === true ? 'correct'
+ : ex.is_correct === false ? 'incorrect'
+ : 'not_graded';
+ const time = ex.processing_time != null
+ ? Number(ex.processing_time).toFixed(1)
+ : null;
+
+ yamlContent += ` - question: "${yamlEscape(ex.question)}"\n`;
+ yamlContent += ` correct_answer: "${yamlEscape(ex.correct_answer)}"\n`;
+ yamlContent += ` model_answer: "${yamlEscape(ex.model_answer)}"\n`;
+ yamlContent += ` result: ${result}\n`;
+ yamlContent += ` dataset: ${ex.dataset_type || 'unknown'}\n`;
+ if (time !== null) {
+ yamlContent += ` processing_time_seconds: ${time}\n`;
}
}
- } catch (e) {
- console.error('Error fetching examples for export:', e);
+ } else if (!exportData.success) {
showAlert('Could not fetch individual examples, downloading without them.', 'warning');
}
}
@@ -691,7 +788,7 @@ date_tested: ${date}
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
- a.download = `${cleanModelName}_${date}.yaml`;
+ a.download = `${cleanModelName}_${fileDate}.yaml`;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_wikipedia.py b/src/local_deep_research/web_search_engines/engines/search_engine_wikipedia.py
index ffb6e785ee..ce6d055232 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_wikipedia.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_wikipedia.py
@@ -1,5 +1,7 @@
+import json
from typing import Any, Dict, List, Optional
+import requests
import wikipedia
from langchain_core.language_models import BaseLLM
from loguru import logger
@@ -8,6 +10,19 @@ from ...config import search_config
from ..search_engine_base import BaseSearchEngine
+# Wikipedia / MediaWiki returns a non-JSON HTML body with HTTP 429 when a
+# client is rate-limited. The `wikipedia` PyPI library calls
+# ``Response.json()`` unconditionally, so the symptom we observe is a
+# ``JSONDecodeError`` on every subsequent ``wikipedia.summary()`` call.
+# Catch that family explicitly so we can short-circuit instead of
+# emitting a full traceback per title (the original behaviour spammed
+# the log with 14+ stack traces for a single rate-limited query).
+_TRANSIENT_DECODE_ERRORS: tuple = (
+ json.JSONDecodeError,
+ requests.exceptions.JSONDecodeError,
+)
+
+
class WikipediaSearchEngine(BaseSearchEngine):
"""Wikipedia search engine implementation with two-phase approach"""
@@ -147,6 +162,18 @@ class WikipediaSearchEngine(BaseSearchEngine):
# Skip pages with errors
logger.warning(f"Error getting summary for '{title}'")
continue
+ except _TRANSIENT_DECODE_ERRORS:
+ # MediaWiki almost certainly returned a 429 (or other
+ # non-JSON page) — every remaining title in this batch
+ # will hit the same throttle. Bail out with one warning
+ # instead of a per-title traceback storm.
+ logger.warning(
+ "Wikipedia rate-limited (non-JSON response while "
+ "fetching '{}'); returning {} previews collected so far",
+ title,
+ len(previews),
+ )
+ break
except Exception:
logger.exception(f"Unexpected error for '{title}'")
continue
@@ -156,6 +183,15 @@ class WikipediaSearchEngine(BaseSearchEngine):
)
return previews
+ except _TRANSIENT_DECODE_ERRORS:
+ # Same 429-style failure on the outer wikipedia.search() call —
+ # log once at warning level and return an empty list.
+ logger.warning(
+ "Wikipedia rate-limited on search for query '{}'; "
+ "returning no previews",
+ query,
+ )
+ return []
except Exception:
logger.exception("Error getting Wikipedia previews")
return []
diff --git a/tests/benchmarks/test_benchmark_service_snapshot.py b/tests/benchmarks/test_benchmark_service_snapshot.py
new file mode 100644
index 0000000000..cf9771e99f
--- /dev/null
+++ b/tests/benchmarks/test_benchmark_service_snapshot.py
@@ -0,0 +1,156 @@
+"""Tests for benchmark service persistence of ldr_version + settings_snapshot.
+
+Pins the contract added by the migration-0014 PR:
+- start_benchmark writes ldr_version (== current __version__) on the row.
+- start_benchmark writes a redacted settings_snapshot.
+- A LookupError raised by SettingsManager.get_all_settings (as happens with
+ legacy CHAT-typed enum rows) is swallowed; benchmark proceeds with empty
+ snapshot and ldr_version still recorded.
+
+Patterned after test_benchmark_service.test_start_benchmark_creates_thread.
+The thread is stubbed so we only exercise the synchronous prelude where the
+new fields are written.
+"""
+
+from unittest.mock import Mock, patch
+
+
+def _make_run(**overrides):
+ mock_run = Mock()
+ mock_run.id = 1
+ mock_run.config_hash = "abc12345"
+ mock_run.datasets_config = {"simpleqa": {"count": 1}}
+ mock_run.search_config = {}
+ mock_run.evaluation_config = {}
+ # Start with no provenance set; assertions read the post-call value.
+ mock_run.ldr_version = None
+ mock_run.settings_snapshot = None
+ for k, v in overrides.items():
+ setattr(mock_run, k, v)
+ return mock_run
+
+
+def _patched_start_benchmark(service, mock_run, snapshot):
+ """Run service.start_benchmark with all collaborators stubbed."""
+ with patch(
+ "local_deep_research.database.session_context.get_user_db_session"
+ ) as mock_get_session:
+ mock_session = Mock()
+ mock_session.__enter__ = Mock(return_value=mock_session)
+ mock_session.__exit__ = Mock(return_value=False)
+ mock_get_session.return_value = mock_session
+ mock_session.query.return_value.filter.return_value.first.return_value = mock_run
+
+ with patch(
+ "local_deep_research.settings.SettingsManager"
+ ) as mock_settings_mgr:
+ if isinstance(snapshot, Exception):
+ mock_settings_mgr.return_value.get_all_settings.side_effect = (
+ snapshot
+ )
+ else:
+ mock_settings_mgr.return_value.get_all_settings.return_value = (
+ snapshot
+ )
+
+ with patch("flask.session", {"session_id": "s"}):
+ with patch(
+ "local_deep_research.database.session_passwords.session_password_store"
+ ):
+ with patch.object(
+ service, "_run_benchmark_thread", return_value=None
+ ):
+ return service.start_benchmark(
+ mock_run.id, username="testuser"
+ )
+
+
+def test_start_benchmark_persists_ldr_version():
+ from local_deep_research import __version__
+ from local_deep_research.benchmarks.web_api.benchmark_service import (
+ BenchmarkService,
+ )
+
+ service = BenchmarkService(socket_service=Mock())
+ mock_run = _make_run()
+ result = _patched_start_benchmark(service, mock_run, snapshot={})
+ assert result is True
+ assert mock_run.ldr_version == __version__
+
+
+def test_start_benchmark_persists_redacted_snapshot():
+ """The persisted snapshot must redact secrets via DataSanitizer.redact_settings_snapshot."""
+ from local_deep_research.benchmarks.web_api.benchmark_service import (
+ BenchmarkService,
+ )
+
+ service = BenchmarkService(socket_service=Mock())
+ mock_run = _make_run()
+ snapshot = {
+ "llm.openai.api_key": {
+ "value": "sk-real-secret",
+ "ui_element": "password",
+ "type": "LLM",
+ },
+ "search.fetch.mode": {
+ "value": "summary_focus_query",
+ "ui_element": "select",
+ "type": "SEARCH",
+ },
+ }
+ _patched_start_benchmark(service, mock_run, snapshot=snapshot)
+
+ persisted = mock_run.settings_snapshot
+ assert isinstance(persisted, dict)
+ # Secret value redacted, metadata intact.
+ assert persisted["llm.openai.api_key"]["value"] == "[REDACTED]"
+ assert persisted["llm.openai.api_key"]["ui_element"] == "password"
+ # Non-secret values pass through.
+ assert persisted["search.fetch.mode"]["value"] == "summary_focus_query"
+
+
+def test_start_benchmark_does_not_mutate_in_memory_snapshot():
+ """The unredacted snapshot the background thread uses to authenticate
+ against providers must NOT be mutated by the redaction step."""
+ from local_deep_research.benchmarks.web_api.benchmark_service import (
+ BenchmarkService,
+ )
+
+ service = BenchmarkService(socket_service=Mock())
+ mock_run = _make_run()
+ snapshot = {
+ "llm.openai.api_key": {
+ "value": "sk-real-secret",
+ "ui_element": "password",
+ }
+ }
+ _patched_start_benchmark(service, mock_run, snapshot=snapshot)
+ # Original dict still has the real secret.
+ assert snapshot["llm.openai.api_key"]["value"] == "sk-real-secret"
+ # The active_runs in-memory copy keeps the unredacted snapshot for the
+ # background thread (which needs the real keys to call providers).
+ assert (
+ service.active_runs[1]["data"]["settings_snapshot"][
+ "llm.openai.api_key"
+ ]["value"]
+ == "sk-real-secret"
+ )
+
+
+def test_start_benchmark_survives_settings_lookup_error():
+ """A LookupError from get_all_settings (e.g. stale CHAT enum row) must
+ not crash benchmark start. Snapshot becomes empty; ldr_version is still
+ recorded so users can tell which version produced the empty snapshot."""
+ from local_deep_research import __version__
+ from local_deep_research.benchmarks.web_api.benchmark_service import (
+ BenchmarkService,
+ )
+
+ service = BenchmarkService(socket_service=Mock())
+ mock_run = _make_run()
+ err = LookupError("'CHAT' is not among the defined enum values")
+ result = _patched_start_benchmark(service, mock_run, snapshot=err)
+
+ assert result is True
+ assert mock_run.ldr_version == __version__
+ assert mock_run.settings_snapshot == {}
diff --git a/tests/benchmarks/web_api/test_benchmark_export_metadata.py b/tests/benchmarks/web_api/test_benchmark_export_metadata.py
new file mode 100644
index 0000000000..6ac644e147
--- /dev/null
+++ b/tests/benchmarks/web_api/test_benchmark_export_metadata.py
@@ -0,0 +1,195 @@
+"""Tests for the metadata block added to /api/results/<id>/export.
+
+Pins the contract introduced by the migration-0014 PR:
+- Response includes a top-level ``metadata`` dict with ``ldr_version``,
+ ``started_at`` (ISO-8601), and ``settings_snapshot``.
+- Pre-0014 rows return null for the new fields without crashing the JS.
+- ``success: True`` envelope is preserved (5 JS callsites depend on it —
+ see benchmark_results.html lines 95, 348, 556, 661, 722).
+- ``started_at`` falls back to ``created_at`` when ``start_time`` is null
+ (e.g. a run that was created but never reached IN_PROGRESS).
+- ``settings_snapshot`` round-trips as a JSON object — secrets are
+ expected to already be redacted at insert time, but this endpoint
+ doesn't re-redact, so we assert the round-trip preserves the dict.
+"""
+# allow: no-sut-import — exercises the SUT indirectly through helpers
+# (_make_app, _make_export_query_router, _patch_auth_and_db, …) imported
+# from tests.benchmarks.web_api.test_benchmark_routes_coverage, which in
+# turn imports from local_deep_research.
+
+from datetime import datetime, UTC
+from unittest.mock import MagicMock
+
+# Import helpers from the existing coverage suite.
+from tests.benchmarks.web_api.test_benchmark_routes_coverage import (
+ _FakeDatasetType,
+ _make_app,
+ _make_export_query_router,
+ _make_run_mock,
+ _patch_auth_and_db,
+)
+
+
+def _result_row():
+ r = MagicMock()
+ r.example_id = "ex0"
+ r.dataset_type = _FakeDatasetType.SIMPLEQA
+ r.question = "Q?"
+ r.correct_answer = "A"
+ r.extracted_answer = "A"
+ r.is_correct = True
+ r.confidence = 0.9
+ r.processing_time = 5.0
+ r.completed_at = datetime(2025, 1, 1, tzinfo=UTC)
+ return r
+
+
+def test_metadata_includes_ldr_version():
+ app = _make_app()
+ with _patch_auth_and_db() as (_svc, _mgr, mock_db):
+ mock_db.query.side_effect = _make_export_query_router(
+ run=_make_run_mock(ldr_version="1.6.10"),
+ results=[_result_row()],
+ )
+ with app.test_client() as client:
+ with client.session_transaction() as sess:
+ sess["username"] = "testuser"
+ resp = client.get("/benchmark/api/results/1/export")
+ assert resp.status_code == 200
+ body = resp.get_json()
+ assert body["metadata"]["ldr_version"] == "1.6.10"
+
+
+def test_metadata_started_at_uses_start_time_when_set():
+ app = _make_app()
+ start_dt = datetime(2026, 5, 1, 12, 30, 0, tzinfo=UTC)
+ with _patch_auth_and_db() as (_svc, _mgr, mock_db):
+ mock_db.query.side_effect = _make_export_query_router(
+ run=_make_run_mock(start_time=start_dt),
+ results=[_result_row()],
+ )
+ with app.test_client() as client:
+ with client.session_transaction() as sess:
+ sess["username"] = "testuser"
+ resp = client.get("/benchmark/api/results/1/export")
+ body = resp.get_json()
+ assert body["metadata"]["started_at"] == start_dt.isoformat()
+
+
+def test_metadata_started_at_falls_back_to_created_at():
+ """If a run was created but never started, started_at falls back to
+ created_at so the YAML still has a date_tested anchor."""
+ app = _make_app()
+ run = _make_run_mock() # start_time defaults to None
+ with _patch_auth_and_db() as (_svc, _mgr, mock_db):
+ mock_db.query.side_effect = _make_export_query_router(
+ run=run, results=[_result_row()]
+ )
+ with app.test_client() as client:
+ with client.session_transaction() as sess:
+ sess["username"] = "testuser"
+ resp = client.get("/benchmark/api/results/1/export")
+ body = resp.get_json()
+ assert body["metadata"]["started_at"] == run.created_at.isoformat()
+
+
+def test_metadata_settings_snapshot_round_trip():
+ """The snapshot is returned only when opted in via ?include_settings=1."""
+ app = _make_app()
+ snapshot = {
+ "llm.model": {"value": "qwen3.6:27b", "ui_element": "select"},
+ "search.fetch.mode": {
+ "value": "summary_focus_query",
+ "ui_element": "select",
+ },
+ }
+ with _patch_auth_and_db() as (_svc, _mgr, mock_db):
+ mock_db.query.side_effect = _make_export_query_router(
+ run=_make_run_mock(settings_snapshot=snapshot),
+ results=[_result_row()],
+ )
+ with app.test_client() as client:
+ with client.session_transaction() as sess:
+ sess["username"] = "testuser"
+ resp = client.get(
+ "/benchmark/api/results/1/export?include_settings=1"
+ )
+ body = resp.get_json()
+ assert body["metadata"]["settings_snapshot"] == snapshot
+
+
+def test_metadata_settings_snapshot_omitted_by_default():
+ """Without the opt-in flag, the snapshot is NOT transferred — the
+ default summary download stays lean and doesn't ship the full config."""
+ app = _make_app()
+ snapshot = {"llm.model": {"value": "qwen3.6:27b", "ui_element": "select"}}
+ with _patch_auth_and_db() as (_svc, _mgr, mock_db):
+ mock_db.query.side_effect = _make_export_query_router(
+ run=_make_run_mock(settings_snapshot=snapshot),
+ results=[_result_row()],
+ )
+ with app.test_client() as client:
+ with client.session_transaction() as sess:
+ sess["username"] = "testuser"
+ resp = client.get("/benchmark/api/results/1/export")
+ body = resp.get_json()
+ assert body["metadata"]["settings_snapshot"] is None
+
+
+def test_pre_0014_row_returns_null_metadata_fields():
+ """A row with all new columns NULL must serialize as JSON null, not
+ crash, and not omit the metadata block."""
+ app = _make_app()
+ run = _make_run_mock() # all provenance fields default to None
+ run.created_at = None # full pre-0014 — even created_at unset
+ with _patch_auth_and_db() as (_svc, _mgr, mock_db):
+ mock_db.query.side_effect = _make_export_query_router(
+ run=run, results=[]
+ )
+ with app.test_client() as client:
+ with client.session_transaction() as sess:
+ sess["username"] = "testuser"
+ resp = client.get("/benchmark/api/results/1/export")
+ body = resp.get_json()
+ assert body["metadata"] == {
+ "ldr_version": None,
+ "started_at": None,
+ "settings_snapshot": None,
+ }
+
+
+def test_run_not_found_returns_null_metadata():
+ """Missing run still returns a metadata block (all None) so the JS
+ code path doesn't need a separate not-found branch."""
+ app = _make_app()
+ with _patch_auth_and_db() as (_svc, _mgr, mock_db):
+ mock_db.query.side_effect = _make_export_query_router(
+ run=None, results=[]
+ )
+ with app.test_client() as client:
+ with client.session_transaction() as sess:
+ sess["username"] = "testuser"
+ resp = client.get("/benchmark/api/results/1/export")
+ assert resp.status_code == 200
+ body = resp.get_json()
+ assert body["success"] is True
+ assert body["metadata"]["ldr_version"] is None
+ assert body["metadata"]["settings_snapshot"] is None
+ assert body["results"] == []
+
+
+def test_success_field_preserved_for_back_compat():
+ """5 JS callsites in benchmark_results.html check `data.success` —
+ removing it would silently break the UI."""
+ app = _make_app()
+ with _patch_auth_and_db() as (_svc, _mgr, mock_db):
+ mock_db.query.side_effect = _make_export_query_router(
+ run=_make_run_mock(ldr_version="1.6.10"),
+ results=[_result_row()],
+ )
+ with app.test_client() as client:
+ with client.session_transaction() as sess:
+ sess["username"] = "testuser"
+ resp = client.get("/benchmark/api/results/1/export")
+ body = resp.get_json()
+ assert body["success"] is True
diff --git a/tests/benchmarks/web_api/test_benchmark_routes_coverage.py b/tests/benchmarks/web_api/test_benchmark_routes_coverage.py
index 766f2e86fe..e119c06adf 100644
--- a/tests/benchmarks/web_api/test_benchmark_routes_coverage.py
+++ b/tests/benchmarks/web_api/test_benchmark_routes_coverage.py
@@ -639,6 +639,10 @@ class TestGetBenchmarkHistory:
run.id = run_id
run.run_name = run_name
run.created_at = datetime(2025, 1, 1, tzinfo=UTC)
+ # Provenance fields added in migration 0014 — None mimics a pre-0014
+ # row, so the existing history tests cover the back-compat path.
+ run.start_time = None
+ run.ldr_version = None
run.total_examples = 10
run.completed_examples = 8
run.overall_accuracy = 0.75
@@ -907,6 +911,41 @@ class TestGetBenchmarkResults:
# ---------------------------------------------------------------------------
+def _make_export_query_router(*, run=None, results=None):
+ """Side-effect for mock_db.query that routes by model class for the
+ /export endpoint.
+
+ The endpoint runs two queries:
+ 1. session.query(BenchmarkRun).options(...).filter(...).one_or_none()
+ 2. session.query(BenchmarkResult).options(...).filter(...).order_by(...).all()
+ """
+
+ def _route(model, *args):
+ chain = MagicMock()
+ chain.options.return_value = chain
+ chain.filter.return_value = chain
+ chain.order_by.return_value = chain
+ name = getattr(model, "__name__", "")
+ if "BenchmarkRun" in name:
+ chain.one_or_none.return_value = run
+ else:
+ chain.all.return_value = results or []
+ return chain
+
+ return _route
+
+
+def _make_run_mock(
+ *, ldr_version=None, start_time=None, settings_snapshot=None
+):
+ run = MagicMock()
+ run.ldr_version = ldr_version
+ run.start_time = start_time
+ run.created_at = datetime(2025, 1, 1, tzinfo=UTC)
+ run.settings_snapshot = settings_snapshot
+ return run
+
+
class TestExportBenchmarkResults:
def test_export_success(self):
app = _make_app()
@@ -922,12 +961,10 @@ class TestExportBenchmarkResults:
mock_result.completed_at = datetime(2025, 1, 1, tzinfo=UTC)
with _patch_auth_and_db() as (mock_svc, mgr, mock_db):
- mock_query = MagicMock()
- mock_db.query.return_value = mock_query
- mock_query.options.return_value = mock_query
- mock_query.filter.return_value = mock_query
- mock_query.order_by.return_value = mock_query
- mock_query.all.return_value = [mock_result]
+ mock_db.query.side_effect = _make_export_query_router(
+ run=_make_run_mock(ldr_version="1.6.10"),
+ results=[mock_result],
+ )
with app.test_client() as client:
with client.session_transaction() as sess:
@@ -953,12 +990,10 @@ class TestExportBenchmarkResults:
mock_result.completed_at = None
with _patch_auth_and_db() as (mock_svc, mgr, mock_db):
- mock_query = MagicMock()
- mock_db.query.return_value = mock_query
- mock_query.options.return_value = mock_query
- mock_query.filter.return_value = mock_query
- mock_query.order_by.return_value = mock_query
- mock_query.all.return_value = [mock_result]
+ mock_db.query.side_effect = _make_export_query_router(
+ run=_make_run_mock(),
+ results=[mock_result],
+ )
with app.test_client() as client:
with client.session_transaction() as sess:
diff --git a/tests/database/test_alembic_migrations.py b/tests/database/test_alembic_migrations.py
index 67412fdaf5..52b3eced88 100644
--- a/tests/database/test_alembic_migrations.py
+++ b/tests/database/test_alembic_migrations.py
@@ -680,6 +680,10 @@ class TestMigrationChain:
"0008_fix_research_strategy_fk.py",
"0009_default_fetch_mode_summary.py",
"0010_add_chat_tables.py",
+ "0011_add_collection_is_public.py",
+ "0012_add_collection_agent_enabled.py",
+ "0013_remove_meta_search_engines.py",
+ "0014_benchmark_run_version_and_snapshot.py",
]
for filename in expected_files:
diff --git a/tests/database/test_migration_0014_benchmark_run_version_and_snapshot.py b/tests/database/test_migration_0014_benchmark_run_version_and_snapshot.py
new file mode 100644
index 0000000000..f745f6819d
--- /dev/null
+++ b/tests/database/test_migration_0014_benchmark_run_version_and_snapshot.py
@@ -0,0 +1,215 @@
+"""Tests for migration 0014: add ldr_version + settings_snapshot to benchmark_runs.
+
+Pins the upgrade/downgrade semantics:
+- Upgrade adds both columns as nullable on existing benchmark_runs tables.
+- Existing rows survive; their new columns are NULL.
+- Downgrade drops both columns cleanly.
+- Idempotent: re-running upgrade after partial application is a no-op.
+- Missing-table guard: doesn't crash if benchmark_runs doesn't exist yet.
+
+Note on test setup
+==================
+Migration 0001 calls ``Base.metadata.create_all()``, which creates tables
+based on the CURRENT model class — so on a freshly initialised DB, the new
+columns are present even before 0014 runs. To pin "0014 is the migration
+that adds these columns" we use the same pattern as
+``test_migration_0005_resource_document_id.py``: hand-build a "legacy"
+``benchmark_runs`` table without the new columns, stamp the DB at
+``down_revision``, and run the upgrade against that.
+"""
+
+import pytest
+from alembic import command
+from sqlalchemy import create_engine, inspect, text
+
+from local_deep_research.database.alembic_runner import (
+ get_alembic_config,
+ get_head_revision,
+ stamp_database,
+)
+
+
+def _run_upgrade_to(engine, revision):
+ config = get_alembic_config(engine)
+ with engine.begin() as conn:
+ config.attributes["connection"] = conn
+ command.upgrade(config, revision)
+
+
+def _run_downgrade_to(engine, revision):
+ config = get_alembic_config(engine)
+ with engine.begin() as conn:
+ config.attributes["connection"] = conn
+ command.downgrade(config, revision)
+
+
+def _columns(engine, table):
+ insp = inspect(engine)
+ if not insp.has_table(table):
+ return set()
+ return {c["name"] for c in insp.get_columns(table)}
+
+
+def _column_info(engine, table):
+ insp = inspect(engine)
+ if not insp.has_table(table):
+ return {}
+ return {c["name"]: c for c in insp.get_columns(table)}
+
+
+def legacy_engine(tmp_path):
+ """A DB with a ``benchmark_runs`` table missing the new 0014 columns.
+
+ Simulates an installation that's been running on revisions 0001–0013
+ and never had the new ``ldr_version`` or ``settings_snapshot`` columns.
+ Stamped at 0013 so 0014's upgrade is a clean delta.
+ """
+ db_path = tmp_path / "legacy_pre_0014.db"
+ engine = create_engine(f"sqlite:///{db_path}")
+
+ with engine.begin() as conn:
+ # Build the pre-0014 benchmark_runs schema by hand. We only need
+ # the NOT-NULL columns the migration will inspect; full schema
+ # fidelity isn't required for column-add tests.
+ conn.execute(
+ text(
+ "CREATE TABLE benchmark_runs ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "run_name VARCHAR(255), "
+ "config_hash VARCHAR(16) NOT NULL, "
+ "query_hash_list TEXT NOT NULL, "
+ "search_config TEXT NOT NULL, "
+ "evaluation_config TEXT NOT NULL, "
+ "datasets_config TEXT NOT NULL, "
+ "status VARCHAR(20) NOT NULL, "
+ "created_at TEXT NOT NULL, "
+ "updated_at TEXT NOT NULL, "
+ "start_time TEXT, "
+ "end_time TEXT, "
+ "total_examples INTEGER NOT NULL DEFAULT 0, "
+ "completed_examples INTEGER NOT NULL DEFAULT 0, "
+ "failed_examples INTEGER NOT NULL DEFAULT 0, "
+ "overall_accuracy REAL, "
+ "processing_rate REAL, "
+ "error_message TEXT"
+ ")"
+ )
+ )
+
+ # Stamp at the predecessor so alembic's view of state is consistent.
+ stamp_database(engine, "0013")
+ yield engine
+ engine.dispose()
+
+
+class TestMigration0014Upgrade:
+ def test_adds_ldr_version_column(self, legacy_engine):
+ engine = legacy_engine
+ assert "ldr_version" not in _columns(engine, "benchmark_runs")
+ _run_upgrade_to(engine, "0014")
+ assert "ldr_version" in _columns(engine, "benchmark_runs")
+
+ def test_adds_settings_snapshot_column(self, legacy_engine):
+ engine = legacy_engine
+ assert "settings_snapshot" not in _columns(engine, "benchmark_runs")
+ _run_upgrade_to(engine, "0014")
+ assert "settings_snapshot" in _columns(engine, "benchmark_runs")
+
+ def test_columns_are_nullable(self, legacy_engine):
+ engine = legacy_engine
+ _run_upgrade_to(engine, "0014")
+ cols = _column_info(engine, "benchmark_runs")
+ assert cols["ldr_version"]["nullable"] is True
+ assert cols["settings_snapshot"]["nullable"] is True
+
+ def test_existing_row_survives_with_null_new_columns(self, legacy_engine):
+ engine = legacy_engine
+ with engine.begin() as conn:
+ conn.execute(
+ text(
+ "INSERT INTO benchmark_runs "
+ "(run_name, config_hash, query_hash_list, search_config, "
+ "evaluation_config, datasets_config, status, created_at, "
+ "updated_at, total_examples, completed_examples, "
+ "failed_examples) "
+ "VALUES ('pre-migration', 'h0', '[]', '{}', '{}', '{}', "
+ "'PENDING', '2026-01-01 00:00:00', '2026-01-01 00:00:00', "
+ "0, 0, 0)"
+ )
+ )
+
+ _run_upgrade_to(engine, "0014")
+
+ with engine.begin() as conn:
+ row = conn.execute(
+ text(
+ "SELECT run_name, ldr_version, settings_snapshot "
+ "FROM benchmark_runs WHERE run_name = 'pre-migration'"
+ )
+ ).fetchone()
+ assert row is not None
+ assert row[0] == "pre-migration"
+ assert row[1] is None
+ assert row[2] is None
+
+ def test_can_write_new_columns_after_upgrade(self, legacy_engine):
+ """Sanity check — the columns are usable, not just present."""
+ engine = legacy_engine
+ _run_upgrade_to(engine, "0014")
+ with engine.begin() as conn:
+ conn.execute(
+ text(
+ "INSERT INTO benchmark_runs "
+ "(run_name, config_hash, query_hash_list, search_config, "
+ "evaluation_config, datasets_config, status, created_at, "
+ "updated_at, total_examples, completed_examples, "
+ "failed_examples, ldr_version, settings_snapshot) "
+ "VALUES ('post-migration', 'h1', '[]', '{}', '{}', '{}', "
+ "'COMPLETED', '2026-05-03 00:00:00', "
+ "'2026-05-03 00:00:00', 1, 1, 0, '1.6.10', "
+ """'{"llm.model": {"value": "qwen3.6:27b"}}')"""
+ )
+ )
+ row = conn.execute(
+ text(
+ "SELECT ldr_version, settings_snapshot "
+ "FROM benchmark_runs WHERE run_name = 'post-migration'"
+ )
+ ).fetchone()
+ assert row[0] == "1.6.10"
+ # SQLite stores JSON as TEXT — values come back as strings here.
+ assert "qwen3.6:27b" in row[1]
+
+ def test_upgrade_is_idempotent(self, legacy_engine):
+ engine = legacy_engine
+ _run_upgrade_to(engine, "0014")
+ _run_upgrade_to(engine, "0014")
+ cols = _columns(engine, "benchmark_runs")
+ assert "ldr_version" in cols
+ assert "settings_snapshot" in cols
+
+ def test_missing_table_does_not_crash(self, tmp_path):
+ """If benchmark_runs doesn't exist, migration is a clean no-op."""
+ db_path = tmp_path / "no_benchmark_table.db"
+ engine = create_engine(f"sqlite:///{db_path}")
+ stamp_database(engine, "0013")
+ # Should not raise.
+ _run_upgrade_to(engine, "0014")
+ engine.dispose()
+
+
+class TestMigration0014Downgrade:
+ def test_downgrade_removes_columns(self, legacy_engine):
+ engine = legacy_engine
+ _run_upgrade_to(engine, "0014")
+ assert "ldr_version" in _columns(engine, "benchmark_runs")
+ _run_downgrade_to(engine, "0013")
+ cols = _columns(engine, "benchmark_runs")
+ assert "ldr_version" not in cols
+ assert "settings_snapshot" not in cols
+
+
+class TestMigration0014HeadAlignment:
+ def test_head_revision_is_0014(self):
+ assert get_head_revision() == "0014"
diff --git a/tests/security/test_redact_settings_snapshot.py b/tests/security/test_redact_settings_snapshot.py
new file mode 100644
index 0000000000..a45c379962
--- /dev/null
+++ b/tests/security/test_redact_settings_snapshot.py
@@ -0,0 +1,111 @@
+"""Tests for DataSanitizer.redact_settings_snapshot.
+
+The plain DataSanitizer.redact() does NOT redact secrets in nested-with-metadata
+snapshots like {"llm.openai.api_key": {"value": "sk-...", "ui_element": "password"}}
+— the outer compound key isn't in the sensitive-name set, and the inner key
+"value" isn't sensitive either. redact_settings_snapshot fixes that for the
+specific shape produced by SettingsManager.get_all_settings().
+"""
+
+from local_deep_research.security.data_sanitizer import DataSanitizer
+
+
+def test_redacts_value_when_ui_element_is_password():
+ snap = {
+ "llm.openai.api_key": {
+ "value": "sk-secret123",
+ "ui_element": "password",
+ "type": "LLM",
+ }
+ }
+ out = DataSanitizer.redact_settings_snapshot(snap)
+ assert out["llm.openai.api_key"]["value"] == "[REDACTED]"
+
+
+def test_preserves_metadata_alongside_redacted_value():
+ """ui_element/type/etc. survive so YAML diffs still show the field exists."""
+ snap = {
+ "llm.openai.api_key": {
+ "value": "sk-secret",
+ "ui_element": "password",
+ "type": "LLM",
+ "description": "OpenAI key",
+ }
+ }
+ out = DataSanitizer.redact_settings_snapshot(snap)
+ assert out["llm.openai.api_key"]["ui_element"] == "password"
+ assert out["llm.openai.api_key"]["type"] == "LLM"
+ assert out["llm.openai.api_key"]["description"] == "OpenAI key"
+
+
+def test_does_not_redact_non_secret_settings():
+ snap = {
+ "search.fetch.mode": {
+ "value": "summary_focus_query",
+ "ui_element": "select",
+ "type": "SEARCH",
+ }
+ }
+ out = DataSanitizer.redact_settings_snapshot(snap)
+ assert out["search.fetch.mode"]["value"] == "summary_focus_query"
+
+
+def test_empty_secret_value_stays_empty():
+ """An unset API key reads as "" — leaving it empty is more useful than
+ "[REDACTED]" when diffing two runs to spot which had the key set."""
+ snap = {"llm.lmstudio.api_key": {"value": "", "ui_element": "password"}}
+ out = DataSanitizer.redact_settings_snapshot(snap)
+ assert out["llm.lmstudio.api_key"]["value"] == ""
+
+
+def test_none_secret_value_stays_none():
+ snap = {"llm.lmstudio.api_key": {"value": None, "ui_element": "password"}}
+ out = DataSanitizer.redact_settings_snapshot(snap)
+ assert out["llm.lmstudio.api_key"]["value"] is None
+
+
+def test_defense_in_depth_via_key_suffix():
+ """ui_element=text + key suffix in DEFAULT_SENSITIVE_KEYS still redacts.
+
+ Catches developer error: a future plugin author who registers
+ `plugin.x.api_key` with the wrong ui_element should still have the
+ secret redacted because `api_key` is in DEFAULT_SENSITIVE_KEYS.
+ """
+ snap = {"plugin.x.api_key": {"value": "sk-leaked", "ui_element": "text"}}
+ out = DataSanitizer.redact_settings_snapshot(snap)
+ assert out["plugin.x.api_key"]["value"] == "[REDACTED]"
+
+
+def test_input_is_not_mutated():
+ """Pure-function contract — the in-memory snapshot used by the running
+ benchmark thread must remain unredacted; only the persisted copy is
+ redacted."""
+ snap = {
+ "llm.openai.api_key": {
+ "value": "sk-secret",
+ "ui_element": "password",
+ }
+ }
+ DataSanitizer.redact_settings_snapshot(snap)
+ assert snap["llm.openai.api_key"]["value"] == "sk-secret"
+
+
+def test_passes_through_non_metadata_entries():
+ """Tolerates flat-shape entries (bare key→value) so the helper is safe
+ on mixed snapshots without crashing."""
+ snap = {"flat_key": "raw_value", "no_value_key": {"ui_element": "text"}}
+ out = DataSanitizer.redact_settings_snapshot(snap)
+ assert out["flat_key"] == "raw_value"
+ assert out["no_value_key"] == {"ui_element": "text"}
+
+
+def test_passes_through_non_dict_input():
+ """Defensive — a None or list snapshot returns unchanged."""
+ assert DataSanitizer.redact_settings_snapshot(None) is None
+ assert DataSanitizer.redact_settings_snapshot([1, 2, 3]) == [1, 2, 3]
+
+
+def test_custom_redaction_text():
+ snap = {"llm.openai.api_key": {"value": "sk-x", "ui_element": "password"}}
+ out = DataSanitizer.redact_settings_snapshot(snap, redaction_text="***")
+ assert out["llm.openai.api_key"]["value"] == "***"
diff --git a/tests/ui_tests/test_benchmark_ci.js b/tests/ui_tests/test_benchmark_ci.js
index b78734459e..b99cacd955 100644
--- a/tests/ui_tests/test_benchmark_ci.js
+++ b/tests/ui_tests/test_benchmark_ci.js
@@ -366,6 +366,48 @@ const BenchmarkResultsTests = {
passed: true,
message: result.text ? `Delete button found: "${result.text}"` : 'Delete icon found'
};
+ },
+
+ async exportDropdown(page, baseUrl) {
+ // The per-run Export dropdown only renders for COMPLETED runs.
+ await navigateTo(page, `${baseUrl}/benchmark/`);
+ await delay(1500); // let the async history fetch render run cards
+
+ const result = await page.evaluate(() => {
+ const toggle = Array.from(document.querySelectorAll('.dropdown-toggle'))
+ .find(b => (b.textContent || '').toLowerCase().includes('export'));
+ if (!toggle) return { found: false };
+
+ const menu = toggle.closest('.dropdown')?.querySelector('.dropdown-menu');
+ const items = menu
+ ? Array.from(menu.querySelectorAll('.dropdown-item')).map(i => (i.textContent || '').toLowerCase())
+ : [];
+ const itemText = items.join(' | ');
+ const checkbox = menu?.querySelector('input[type="checkbox"]');
+ const checkboxLabel = (checkbox?.closest('label')?.textContent || '').toLowerCase();
+
+ return {
+ found: true,
+ hasSummary: itemText.includes('summary'),
+ hasExamples: itemText.includes('examples'),
+ hasSettingsCheckbox: !!checkbox && checkboxLabel.includes('settings'),
+ // The opt-in default must be OFF so the default download is lean.
+ checkboxDefaultOff: checkbox ? checkbox.checked === false : null,
+ };
+ });
+
+ if (!result.found) {
+ return { passed: null, skipped: true, message: 'No Export dropdown found (requires a completed benchmark run)' };
+ }
+
+ const ok = result.hasSummary && result.hasExamples
+ && result.hasSettingsCheckbox && result.checkboxDefaultOff === true;
+ return {
+ passed: ok,
+ message: ok
+ ? 'Export dropdown has summary/examples items + settings-snapshot checkbox (default off)'
+ : `Export dropdown incomplete: summary=${result.hasSummary} examples=${result.hasExamples} settingsCheckbox=${result.hasSettingsCheckbox} checkboxDefaultOff=${result.checkboxDefaultOff}`,
+ };
}
};
@@ -514,6 +556,7 @@ async function main() {
await run('Results', 'Quality Score Display', (p, u) => BenchmarkResultsTests.qualityScoreDisplay(p, u));
await run('Results', 'Cancel Benchmark Button', (p, u) => BenchmarkResultsTests.cancelBenchmarkButton(p, u));
await run('Results', 'Delete Benchmark Button', (p, u) => BenchmarkResultsTests.deleteBenchmarkButton(p, u));
+ await run('Results', 'Export Dropdown', (p, u) => BenchmarkResultsTests.exportDropdown(p, u));
// Benchmark API Tests
log.section('Benchmark APIs');
diff --git a/tests/web/routes/test_settings_routes_gaps_coverage.py b/tests/web/routes/test_settings_routes_gaps_coverage.py
index b1f5d7ba15..6f2762c87c 100644
--- a/tests/web/routes/test_settings_routes_gaps_coverage.py
+++ b/tests/web/routes/test_settings_routes_gaps_coverage.py
@@ -66,6 +66,97 @@ def _authenticated_client(app):
p.stop()
+# ===========================================================================
+# api_get_all_settings — redaction
+# ===========================================================================
+
+
+class TestApiGetAllSettingsRedaction:
+ """Tests for GET /settings/api — verifies password-typed values are
+ redacted in the JSON response so env-overridden API keys (and any other
+ ``ui_element=='password'`` field) cannot leak via the JSON endpoint.
+
+ The fix wraps the settings dict in
+ ``DataSanitizer.redact_settings_snapshot`` before ``jsonify``. No JS
+ caller round-trips this endpoint's values back into the form (the
+ settings form is server-rendered from the template), so redacting the
+ JSON response is safe.
+ """
+
+ SECRET = "sk-real-leaked-key"
+ SAFE_VALUE = "summary_focus_query"
+
+ def _snapshot_with_secret(self):
+ return {
+ "llm.openai.api_key": {
+ "value": self.SECRET,
+ "ui_element": "password",
+ "type": "LLM",
+ },
+ "search.fetch.mode": {
+ "value": self.SAFE_VALUE,
+ "ui_element": "select",
+ "type": "SEARCH",
+ },
+ }
+
+ def test_password_value_is_redacted(self):
+ """The plaintext API key MUST NOT appear in the response."""
+ app = _create_test_app()
+ mock_sm = Mock()
+ mock_sm.get_all_settings.return_value = self._snapshot_with_secret()
+
+ with _authenticated_client(app) as client:
+ with patch(
+ "local_deep_research.web.utils.route_decorators.SettingsManager",
+ return_value=mock_sm,
+ ):
+ resp = client.get("/settings/api")
+
+ assert resp.status_code == 200
+ data = resp.get_json()
+ assert data["status"] == "success"
+ assert data["settings"]["llm.openai.api_key"]["value"] == "[REDACTED]"
+ # And belt-and-braces: the raw secret string must be nowhere in
+ # the serialised payload (no encoded copies, no log echoes).
+ assert self.SECRET not in resp.get_data(as_text=True)
+
+ def test_non_secret_values_pass_through(self):
+ """Non-password settings still come back with their real values."""
+ app = _create_test_app()
+ mock_sm = Mock()
+ mock_sm.get_all_settings.return_value = self._snapshot_with_secret()
+
+ with _authenticated_client(app) as client:
+ with patch(
+ "local_deep_research.web.utils.route_decorators.SettingsManager",
+ return_value=mock_sm,
+ ):
+ resp = client.get("/settings/api")
+
+ data = resp.get_json()
+ assert data["settings"]["search.fetch.mode"]["value"] == self.SAFE_VALUE
+
+ def test_metadata_preserved_for_redacted_entry(self):
+ """ui_element/type/etc. survive so the UI can still render a
+ password input even though the value is masked."""
+ app = _create_test_app()
+ mock_sm = Mock()
+ mock_sm.get_all_settings.return_value = self._snapshot_with_secret()
+
+ with _authenticated_client(app) as client:
+ with patch(
+ "local_deep_research.web.utils.route_decorators.SettingsManager",
+ return_value=mock_sm,
+ ):
+ resp = client.get("/settings/api")
+
+ data = resp.get_json()
+ entry = data["settings"]["llm.openai.api_key"]
+ assert entry["ui_element"] == "password"
+ assert entry["type"] == "LLM"
+
+
# ===========================================================================
# get_bulk_settings
# ===========================================================================
diff --git a/tests/web_search_engines/engines/test_search_engine_wikipedia.py b/tests/web_search_engines/engines/test_search_engine_wikipedia.py
index 5aba6b07dd..a9c80c5ffb 100644
--- a/tests/web_search_engines/engines/test_search_engine_wikipedia.py
+++ b/tests/web_search_engines/engines/test_search_engine_wikipedia.py
@@ -9,7 +9,7 @@ Tests cover:
- Error handling
"""
-from unittest.mock import Mock, patch
+from unittest.mock import MagicMock, Mock, patch
class TestWikipediaSearchEngineInit:
@@ -200,6 +200,60 @@ class TestGetPreviews:
assert previews == []
+ def test_get_previews_short_circuits_on_rate_limit_decode_error(self):
+ """When MediaWiki rate-limits us, the `wikipedia` PyPI library tries
+ to ``Response.json()`` on the 429 HTML body and raises
+ ``JSONDecodeError``. We must bail out of the per-title loop on the
+ first occurrence — every subsequent call in the batch will hit the
+ same throttle, and emitting a full traceback per title floods the
+ log (we observed 14+ stack traces for a single rate-limited query).
+ """
+ import json
+
+ from local_deep_research.web_search_engines.engines.search_engine_wikipedia import (
+ WikipediaSearchEngine,
+ )
+
+ decode_error = json.JSONDecodeError("Expecting value", "<html>", 0)
+
+ with patch("wikipedia.set_lang"):
+ with patch(
+ "wikipedia.search",
+ return_value=["A", "B", "C", "D", "E"],
+ ):
+ # Title A succeeds, B trips the throttle. Titles C-E must
+ # NOT be looked up — we break on first decode error.
+ summary_mock = MagicMock(
+ side_effect=["A summary", decode_error, "C", "D", "E"]
+ )
+ with patch("wikipedia.summary", summary_mock):
+ engine = WikipediaSearchEngine()
+ previews = engine._get_previews("test")
+
+ # Got the title that succeeded before the throttle.
+ assert len(previews) == 1
+ assert previews[0]["title"] == "A"
+ # Loop short-circuited: only A and B were attempted.
+ assert summary_mock.call_count == 2
+
+ def test_get_previews_handles_outer_decode_error_on_search(self):
+ """Even the initial wikipedia.search() can be rate-limited. Should
+ return [] without spamming a traceback at exception level."""
+ import json
+
+ from local_deep_research.web_search_engines.engines.search_engine_wikipedia import (
+ WikipediaSearchEngine,
+ )
+
+ decode_error = json.JSONDecodeError("Expecting value", "<html>", 0)
+
+ with patch("wikipedia.set_lang"):
+ with patch("wikipedia.search", side_effect=decode_error):
+ engine = WikipediaSearchEngine()
+ previews = engine._get_previews("test")
+
+ assert previews == []
+
def test_get_previews_creates_correct_link(self):
"""Get previews creates correct Wikipedia link."""
from local_deep_research.web_search_engines.engines.search_engine_wikipedia import (