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(benchmark): handle recorded grading and terminal research failures (#7591)

LearningCircuitcc71f953b0e9
diff --git a/.gitignore b/.gitignore
index b5a073c83f..732f2f77b1 100644
--- a/.gitignore
+++ b/.gitignore
@@ -388,6 +388,10 @@ tests/**/*.md
# To whitelist specific test MD files, add them explicitly like:
# !tests/specific-file-to-include.md
+# Security contract registry (seam -> test file -> PR); see the
+# security-hardening loop's duplicate gate.
+!tests/security/INDEX.md
+
# Whitelist Playwright test infrastructure
!tests/ui_tests/playwright/
!tests/ui_tests/playwright/package.json
diff --git a/changelog.d/7591.security.md b/changelog.d/7591.security.md
new file mode 100644
index 0000000000..506e55f0a1
--- /dev/null
+++ b/changelog.d/7591.security.md
@@ -0,0 +1 @@
+Benchmark results use the standard message for recorded grading failures. Research tasks with a terminal error finding now finish with a research error before answer extraction or grading. Ordinary answer and grading rationale text is preserved.
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 8be4cc4010..6b4bd14246 100644
--- a/src/local_deep_research/benchmarks/web_api/benchmark_service.py
+++ b/src/local_deep_research/benchmarks/web_api/benchmark_service.py
@@ -39,6 +39,9 @@ _GENERIC_BENCHMARK_ERROR = (
"Benchmark run failed due to an internal error. "
"Check the server logs for details."
)
+_GENERIC_BENCHMARK_RESEARCH_ERROR = (
+ "Research failed. Check the server logs for details."
+)
_RESULT_PERSISTENCE_ERROR = {
"code": "database_write_failed",
"message": (
@@ -981,6 +984,19 @@ class BenchmarkService:
# Extract answer
response = search_result.get("summary", "")
+ findings = search_result.get("findings")
+ if isinstance(findings, list) and findings:
+ final_finding = findings[-1]
+ if (
+ isinstance(final_finding, dict)
+ and final_finding.get("phase") == "Error"
+ and final_finding.get("content") == response
+ ):
+ return {
+ **task,
+ "research_error": _GENERIC_BENCHMARK_RESEARCH_ERROR,
+ "completed_at": datetime.now(UTC),
+ }
logger.info(
f"Task {task['example_id']} response length: {len(response)} chars"
)
diff --git a/src/local_deep_research/web/routers/benchmark.py b/src/local_deep_research/web/routers/benchmark.py
index a3a8a9e138..5e1f1b850d 100644
--- a/src/local_deep_research/web/routers/benchmark.py
+++ b/src/local_deep_research/web/routers/benchmark.py
@@ -38,6 +38,60 @@ _benchmark_start_limit = limiter.shared_limit(
_BENCHMARK_START_RATE_LIMIT, scope="benchmark_start"
)
+# The grading/evaluation failure prefixes the benchmark producers attach
+# to BenchmarkResult.grader_response when they store raw ``str(e)`` of the
+# LLM call (benchmark_service.py ``"Evaluation failed: ..."`` / graders.py
+# ``_grading_error_result`` ``"Grading failed: ..."``). The raw text can
+# carry server-level LLM endpoints / hosts / filesystem paths, so it must
+# not cross the HTTP boundary (CWE-209) — the same rationale as the
+# run-level ``_GENERIC_BENCHMARK_ERROR`` (#4843). Full detail stays in the
+# ``logger.exception`` records at the producer sites.
+_GRADER_FAILURE_PREFIXES = ("Evaluation failed:", "Grading failed:")
+_GENERIC_GRADER_FAILURE_DETAIL = "internal error (details in server logs)"
+
+# Left-edge decoration in front of the failure prefix on rows written by
+# earlier producer eras (a94af439f7..9a8b36c19b, 2025-06..08): the
+# missing-API-key wrapper prefixed the failure text with a literal key
+# emoji — ``🔑 Evaluation failed: {raw}. Set llm.openai_endpoint...`` —
+# and rows can also carry incidental leading whitespace or a zero-width
+# space (U+200B, which is *not* whitespace to ``str.strip``).
+_GRADER_FAILURE_DECORATION = "\u200b\U0001f511"
+
+
+def _safe_grader_response(grader_response):
+ """Genericize raw grader failure detail at the HTTP boundary.
+
+ Failure-prefixed values keep their prefix (the payload still reads as
+ a grading/evaluation failure) but lose the raw exception detail.
+ Everything else — ordinary grading rationale, NULL/empty values from
+ pre-existing rows — passes through unchanged. Producer payloads are
+ deliberately raw and stay raw (pinned by
+ tests/benchmarks/web_api/test_benchmark_service_coverage.py); this is
+ the read-side enforcement point, mirroring how
+ ``get_benchmark_status`` genericizes ``BenchmarkRun.error_message``.
+
+ Rows from the decorated producer eras carry the key-emoji / whitespace
+ decoration in front of the failure prefix, which defeats a plain
+ ``startswith`` match — so the decoration is stripped from the left
+ before matching (equivalent to
+ ``^[\\s\\u200b\\U0001f511]*(Evaluation failed|Grading failed):``),
+ and the surfaced payload drops it, keeping the bare failure prefix.
+ """
+ if not isinstance(grader_response, str):
+ return grader_response
+ # Scan the left-edge decoration once, without copying each remaining
+ # suffix. Keep the original value intact for ordinary grading rationale.
+ start = 0
+ for char in grader_response:
+ if not (char.isspace() or char in _GRADER_FAILURE_DECORATION):
+ break
+ start += 1
+ for prefix in _GRADER_FAILURE_PREFIXES:
+ if grader_response.startswith(prefix, start):
+ return f"{prefix} {_GENERIC_GRADER_FAILURE_DETAIL}"
+ return grader_response
+
+
# Create the router for benchmark routes
router = APIRouter(prefix="/benchmark", tags=["benchmark"])
@@ -725,7 +779,9 @@ def get_benchmark_results(
"full_response": result.response,
"is_correct": result.is_correct,
"confidence": result.confidence,
- "grader_response": result.grader_response,
+ "grader_response": _safe_grader_response(
+ result.grader_response
+ ),
"processing_time": result.processing_time,
"search_result_count": search_result_count,
"sources": result.sources,
diff --git a/tests/benchmarks/web_api/test_benchmark_service_coverage.py b/tests/benchmarks/web_api/test_benchmark_service_coverage.py
index 2d3c292c9d..f7980a9469 100644
--- a/tests/benchmarks/web_api/test_benchmark_service_coverage.py
+++ b/tests/benchmarks/web_api/test_benchmark_service_coverage.py
@@ -466,6 +466,75 @@ class TestProcessBenchmarkTask:
task.update(overrides)
return task
+ @pytest.mark.parametrize(
+ ("findings", "is_failure"),
+ [
+ ([{"phase": "Error", "content": "Error: synthesis detail"}], True),
+ (
+ [
+ {
+ "phase": "Final synthesis",
+ "content": "Error: synthesis detail",
+ }
+ ],
+ False,
+ ),
+ (
+ [
+ {"phase": "Error", "content": "earlier step"},
+ {
+ "phase": "Final synthesis",
+ "content": "Error: synthesis detail",
+ },
+ ],
+ False,
+ ),
+ ([{"phase": "Error", "content": "different content"}], False),
+ (None, False),
+ ],
+ )
+ @patch(f"{MODULE}.grade_single_result")
+ @patch(f"{MODULE}.extract_answer_from_response")
+ @patch(f"{MODULE}.quick_summary")
+ @patch(f"{MODULE}.format_query")
+ def test_terminal_research_finding_controls_result_state(
+ self,
+ mock_format,
+ mock_summary,
+ mock_extract,
+ mock_grade,
+ findings,
+ is_failure,
+ ):
+ svc = _make_service()
+ mock_format.return_value = "q"
+ summary = "Error: synthesis detail"
+ mock_summary.return_value = {
+ "summary": summary,
+ "findings": findings,
+ "sources": [],
+ }
+ mock_extract.return_value = {"extracted_answer": "answer"}
+ mock_grade.return_value = {"is_correct": True}
+ context = MagicMock()
+ context.snapshot = {}
+ with patch(
+ f"{SETTINGS_CTX_MODULE}.get_settings_context", return_value=context
+ ):
+ result = svc._process_benchmark_task(self._make_task(), {}, {})
+ if is_failure:
+ assert result["research_error"] == (
+ "Research failed. Check the server logs for details."
+ )
+ assert "response" not in result
+ assert "extracted_answer" not in result
+ mock_extract.assert_not_called()
+ mock_grade.assert_not_called()
+ else:
+ assert result["response"] == summary
+ mock_extract.assert_called_once()
+ mock_grade.assert_called_once()
+
@patch(f"{MODULE}.grade_single_result")
@patch(f"{MODULE}.extract_answer_from_response")
@patch(f"{MODULE}.quick_summary")
diff --git a/tests/security/INDEX.md b/tests/security/INDEX.md
new file mode 100644
index 0000000000..12e44622e8
--- /dev/null
+++ b/tests/security/INDEX.md
@@ -0,0 +1,5 @@
+# Security contract registry — seam → test file → PR #
+
+| Seam | Contract test | PR |
+|---|---|---|
+| `GET /benchmark/api/results` `grader_response` CWE-209 boundary (failure-prefixed raw exception detail genericized, including the historical 🔑-decorated prefix; normal/NULL pass through) | `tests/web/routers/test_benchmark_results_grader_response_boundary.py` | #7591 |
diff --git a/tests/web/routers/test_benchmark_results_grader_response_boundary.py b/tests/web/routers/test_benchmark_results_grader_response_boundary.py
new file mode 100644
index 0000000000..70427e4f2b
--- /dev/null
+++ b/tests/web/routers/test_benchmark_results_grader_response_boundary.py
@@ -0,0 +1,295 @@
+"""Boundary contract: ``GET /benchmark/api/results/<id>`` must not echo
+raw grader exception internals (CWE-209).
+
+The producers attach raw ``str(exc)`` of the LLM/grading call to
+``BenchmarkResult.grader_response`` under two well-known prefixes:
+
+* ``benchmarks/web_api/benchmark_service.py`` —
+ ``f"Evaluation failed: {error_msg}"`` / ``f"Evaluation failed: {e!s}"``
+* ``benchmarks/graders.py`` ``_grading_error_result`` —
+ ``f"Grading failed: {exc!s}"``
+
+Earlier producer eras (a94af439f7..9a8b36c19b, 2025-06..08) decorated
+the prefix — ``🔑 Evaluation failed: {raw}. Set llm.openai_endpoint...`` —
+and the boundary strips that left-edge decoration (key emoji, whitespace,
+zero-width space) before the prefix match, so historical rows genericize
+too.
+
+Those producer payloads are deliberately raw and stay raw: full detail is
+pinned for the in-memory result dict by
+``tests/benchmarks/web_api/test_benchmark_service_coverage.py``
+(``test_grading_error_in_result`` / ``test_grading_returns_none`` /
+``test_grading_exception``) and belongs in the server-side
+``logger.exception`` record. The raw text can carry server-level LLM
+endpoints / hosts / filesystem paths, so it must not cross the HTTP
+boundary — the same CWE-209 rationale the run-level genericization
+(``_GENERIC_BENCHMARK_ERROR`` for ``/benchmark/api/status``, #4843)
+already applies to ``BenchmarkRun.error_message``.
+
+These tests pin the boundary behavior:
+
+* failure-prefixed ``grader_response`` values keep their failure prefix
+ but lose the raw detail (fail-closed: the boundary cannot distinguish
+ inert constants from raw ``str(e)`` inside the failure branches);
+* normal grading rationale passes through verbatim;
+* NULL/empty values pass through unchanged (pre-existing rows).
+"""
+
+from contextlib import contextmanager
+from datetime import UTC, datetime
+from types import SimpleNamespace
+from unittest.mock import MagicMock, patch
+
+import pytest
+from fastapi.testclient import TestClient
+
+# Inert marker shapes representing the internal-endpoint / internal-path
+# classes of detail that live in raw LLM exception strings (the ``.example``
+# TLD is reserved; nothing here resembles a credential).
+MARKER_HOST = "internal-llm-gateway.corp.example"
+MARKER_URL = "https://internal-llm-gateway.corp.example:8443/v1/chat"
+MARKER_PATH = "/srv/ldr/evaluation/runner-state.toml"
+GRADING_FAILURE_RAW = (
+ "Grading failed: APIConnectionError: Connection error to "
+ f"{MARKER_URL} (read {MARKER_PATH})"
+)
+EVALUATION_FAILURE_RAW = (
+ "Evaluation failed: HTTPSConnectionPool(host='internal-llm-gateway"
+ ".corp.example', port=8443): Max retries exceeded with: /srv/ldr/"
+ "evaluation/runner-state.toml"
+)
+# Exact historical producer shape (a94af439f7..9a8b36c19b, 2025-06..08):
+# the missing-API-key wrapper prefixed the failure prefix with a literal
+# key emoji and appended setup boilerplate. The leading "🔑 " defeats a
+# plain startswith match, so without decoration-stripping these rows echo
+# the raw exception detail verbatim across the boundary.
+KEY_EMOJI_EVALUATION_FAILURE_RAW = (
+ "\U0001f511 Evaluation failed: APIConnectionError: Connection error "
+ f"to {MARKER_URL} (read {MARKER_PATH}). Set llm.openai_endpoint"
+ ".api_key in database settings to use Claude 3.7 Sonnet via "
+ "OpenRouter."
+)
+NORMAL_GRADER_RESPONSE = "The model's answer matches the reference answer."
+
+MARKERS = (MARKER_HOST, MARKER_URL, MARKER_PATH)
+
+
+def _make_app():
+ """Return the real FastAPI app with ``require_auth`` overridden so the
+ route body executes as ``testuser`` without a real login/DB."""
+ from local_deep_research.web.fastapi_app import app
+ from local_deep_research.web.dependencies.auth import require_auth
+
+ app.dependency_overrides[require_auth] = lambda: "testuser"
+ return app
+
+
+@contextmanager
+def _patch_auth_and_db():
+ """Patch ``get_user_db_session`` and the ``benchmark_service``
+ singleton, mirroring the idiom of
+ ``tests/benchmarks/web_api/test_benchmark_results_persistence_error.py``.
+ """
+ mock_db = MagicMock()
+ mock_svc = MagicMock()
+ mock_svc.get_result_persistence_error.return_value = None
+
+ @contextmanager
+ def _session_ctx(username, *args, **kwargs):
+ yield mock_db
+
+ with (
+ patch(
+ "local_deep_research.database.session_context.get_user_db_session",
+ side_effect=_session_ctx,
+ ),
+ patch(
+ "local_deep_research.web.routers.benchmark.benchmark_service",
+ mock_svc,
+ ),
+ ):
+ yield mock_svc, mock_db
+
+
+def _make_results_query_router(*, results=None):
+ """Side-effect for ``mock_db.query`` routing by model class (same
+ idiom as the persistence-error suite)."""
+
+ def _route(model, *args):
+ chain = MagicMock()
+ chain.filter.return_value = chain
+ chain.order_by.return_value = chain
+ chain.limit.return_value = chain
+ name = getattr(model, "__name__", "")
+ if "SearchCall" in name:
+ chain.all.return_value = []
+ else:
+ chain.all.return_value = results or []
+ return chain
+
+ return _route
+
+
+def _make_result(grader_response):
+ return SimpleNamespace(
+ example_id="ex-1",
+ dataset_type=SimpleNamespace(value="simpleqa"),
+ question="What is 2+2?",
+ correct_answer="4",
+ extracted_answer="4",
+ response="The answer is 4.",
+ is_correct=None,
+ confidence=0.0,
+ grader_response=grader_response,
+ processing_time=1.5,
+ sources=None,
+ completed_at=datetime(2025, 1, 1, tzinfo=UTC),
+ research_id=None,
+ )
+
+
[email protected](autouse=True)
+def _clear_overrides():
+ """Ensure the ``require_auth`` override doesn't leak into other tests
+ sharing the module-level FastAPI app."""
+ yield
+ from local_deep_research.web.fastapi_app import app
+ from local_deep_research.web.dependencies.auth import require_auth
+
+ app.dependency_overrides.pop(require_auth, None)
+
+
+def _client(app):
+ return TestClient(app, raise_server_exceptions=False)
+
+
+def _get_first_grader_response(grader_response):
+ app = _make_app()
+ row = _make_result(grader_response)
+
+ with _patch_auth_and_db() as (_svc, mock_db):
+ mock_db.query.side_effect = _make_results_query_router(results=[row])
+ resp = _client(app).get("/benchmark/api/results/1")
+
+ assert resp.status_code == 200, resp.text
+ body = resp.json()
+ assert body["success"] is True
+ assert len(body["results"]) == 1
+ return body["results"][0]["grader_response"]
+
+
+class TestGraderResponseBoundary:
+ def test_grading_failure_detail_genericized(self):
+ """'Grading failed:' rows keep the failure prefix but never carry
+ the raw exception detail to the client."""
+ surfaced = _get_first_grader_response(GRADING_FAILURE_RAW)
+
+ for marker in MARKERS:
+ assert marker not in surfaced, (
+ f"raw internal detail {marker!r} reached the client"
+ )
+ assert surfaced.startswith("Grading failed"), surfaced
+ assert surfaced != GRADING_FAILURE_RAW
+
+ def test_evaluation_failure_detail_genericized(self):
+ """'Evaluation failed:' rows keep the failure prefix but never
+ carry the raw exception detail to the client."""
+ surfaced = _get_first_grader_response(EVALUATION_FAILURE_RAW)
+
+ for marker in MARKERS:
+ assert marker not in surfaced, (
+ f"raw internal detail {marker!r} reached the client"
+ )
+ assert surfaced.startswith("Evaluation failed"), surfaced
+ assert surfaced != EVALUATION_FAILURE_RAW
+
+ def test_normal_grader_response_passes_through(self):
+ """Ordinary grading rationale about the user's own run is not
+ redacted — the boundary keys on the producer failure prefixes,
+ not on the field itself."""
+ surfaced = _get_first_grader_response(NORMAL_GRADER_RESPONSE)
+ assert surfaced == NORMAL_GRADER_RESPONSE
+
+ def test_null_and_empty_pass_through(self):
+ """Pre-existing rows with NULL/empty grader_response surface
+ unchanged (no crash, no invented failure text)."""
+ assert _get_first_grader_response(None) is None
+ assert _get_first_grader_response("") == ""
+
+ def test_historical_key_emoji_failure_genericized(self):
+ """Rows from the 🔑 producer era (a94af439f7..9a8b36c19b,
+ 2025-06..08) use the exact historical literal: a key emoji in
+ front of the failure prefix plus trailing setup boilerplate.
+ Decoration-stripping must genericize them — raw exception detail
+ and boilerplate never reach the client."""
+ from local_deep_research.web.routers.benchmark import (
+ _GENERIC_GRADER_FAILURE_DETAIL,
+ )
+
+ surfaced = _get_first_grader_response(KEY_EMOJI_EVALUATION_FAILURE_RAW)
+
+ for marker in MARKERS:
+ assert marker not in surfaced, (
+ f"raw internal detail {marker!r} reached the client"
+ )
+ assert "Set llm.openai_endpoint" not in surfaced, surfaced
+ assert "OpenRouter" not in surfaced, surfaced
+ assert "\U0001f511" not in surfaced, surfaced
+ assert surfaced == (
+ f"Evaluation failed: {_GENERIC_GRADER_FAILURE_DETAIL}"
+ ), surfaced
+
+ def test_leading_whitespace_failure_genericized(self):
+ """A failure prefix behind leading whitespace still matches after
+ left-edge normalization."""
+ from local_deep_research.web.routers.benchmark import (
+ _GENERIC_GRADER_FAILURE_DETAIL,
+ )
+
+ surfaced = _get_first_grader_response(
+ f" \n\tEvaluation failed: connection to {MARKER_URL} failed"
+ )
+
+ for marker in MARKERS:
+ assert marker not in surfaced, (
+ f"raw internal detail {marker!r} reached the client"
+ )
+ assert surfaced == (
+ f"Evaluation failed: {_GENERIC_GRADER_FAILURE_DETAIL}"
+ ), surfaced
+
+ def test_interleaved_decoration_failure_genericized(self):
+ """Zero-width spaces, whitespace, and the key emoji interleaved
+ in front of the prefix all strip (the normalization runs to a
+ fixpoint, not a single pass)."""
+ from local_deep_research.web.routers.benchmark import (
+ _GENERIC_GRADER_FAILURE_DETAIL,
+ )
+
+ surfaced = _get_first_grader_response(
+ f"\u200b \U0001f511 \u200b\n Grading failed: read {MARKER_PATH}"
+ )
+
+ for marker in MARKERS:
+ assert marker not in surfaced, (
+ f"raw internal detail {marker!r} reached the client"
+ )
+ assert surfaced == (
+ f"Grading failed: {_GENERIC_GRADER_FAILURE_DETAIL}"
+ ), surfaced
+
+ def test_non_string_value_passes_through(self):
+ """Non-str values (defensive: the column is Text) pass through
+ untouched — the isinstance guard must not be 'simplified' into
+ a crash or a stringification."""
+ assert _get_first_grader_response(12345) == 12345
+
+ def test_long_failure_retains_the_standard_message(self):
+ value = " \u200b" * 4096 + "Evaluation failed: " + "detail " * 1000
+ assert _get_first_grader_response(value) == (
+ "Evaluation failed: internal error (details in server logs)"
+ )
+
+ def test_long_rationale_passes_through_unchanged(self):
+ value = " \u200b" * 4096 + NORMAL_GRADER_RESPONSE * 200
+ assert _get_first_grader_response(value) == value