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(benchmarks): skip malformed persistence results (#5376)

Ziyang Guod42971a9e4ed
diff --git a/changelog.d/4861.bugfix.md b/changelog.d/4861.bugfix.md
new file mode 100644
index 0000000000..7a5e3be95f
--- /dev/null
+++ b/changelog.d/4861.bugfix.md
@@ -0,0 +1 @@
+Skip malformed benchmark result payloads without rolling back the rest of the pending persistence batch.
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 7cc02dd8fb..739bb57fa4 100644
--- a/src/local_deep_research/benchmarks/web_api/benchmark_service.py
+++ b/src/local_deep_research/benchmarks/web_api/benchmark_service.py
@@ -47,6 +47,24 @@ _RESULT_PERSISTENCE_ERROR = {
}
+def _required_persistence_fields(
+ result: Any,
+) -> tuple[Any, str, DatasetType, Any, Any]:
+ """Extract required fields or raise a data-shape error."""
+ if not isinstance(result, dict):
+ raise TypeError("result must be a mapping")
+ query_hash = result["query_hash"]
+ if not isinstance(query_hash, str) or not query_hash:
+ raise ValueError("query_hash must be a non-empty string")
+ return (
+ result["example_id"],
+ query_hash,
+ DatasetType(result["dataset_type"]),
+ result["question"],
+ result["correct_answer"],
+ )
+
+
class BenchmarkTaskStatus(Enum):
"""Status values for benchmark tasks in the queue tracker."""
@@ -923,11 +941,13 @@ class BenchmarkService:
Idempotent and rollback-safe. A result is skipped when its index is
already known-saved (``saved_indices``), its ``query_hash`` is already
committed for this run, or it repeats a ``query_hash`` staged earlier
- in this same batch. Since ``query_hash`` covers ``example_id`` as well
- as the question text (#5080), a repeat no longer means "a dataset
- legitimately repeats a question": it is the same result entry reaching
- this method twice, so the skip is logged at WARNING rather than passed
- over in silence (#4860).
+ in this same batch. Malformed result entries are also skipped so one
+ bad payload cannot make every later valid result roll back (#4861).
+ Since ``query_hash`` covers ``example_id`` as well as the question text
+ (#5080), a repeat no longer means "a dataset legitimately repeats a
+ question": it is the same result entry reaching this method twice, so
+ the skip is logged at WARNING rather than passed over in silence
+ (#4860).
Dedup correctness rests on the DB-backed ``seen_hashes``, which
survives a rollback (the next sync re-reads it), NOT on any in-memory
flag.
@@ -960,23 +980,47 @@ class BenchmarkService:
for idx, result in enumerate(results):
if idx in saved_indices:
continue
- query_hash = result["query_hash"]
+ try:
+ (
+ example_id,
+ query_hash,
+ dataset_type,
+ question,
+ correct_answer,
+ ) = _required_persistence_fields(result)
+ except (KeyError, TypeError, ValueError) as exc:
+ example_id = (
+ result.get("example_id")
+ if isinstance(result, dict)
+ else None
+ )
+ task_index = (
+ result.get("task_index")
+ if isinstance(result, dict)
+ else None
+ )
+ logger.warning(
+ f"Benchmark run {benchmark_run_id}: skipping malformed "
+ f"result index {idx} (example_id={example_id!r}, "
+ f"task_index={task_index!r}): {type(exc).__name__}"
+ )
+ continue
if query_hash in seen_hashes:
logger.warning(
f"Benchmark run {benchmark_run_id}: skipping result index "
- f"{idx} (example_id={result['example_id']!r}), its "
+ f"{idx} (example_id={example_id!r}), its "
f"query_hash is already persisted or staged for this run"
)
continue
session.add(
BenchmarkResult(
benchmark_run_id=benchmark_run_id,
- example_id=result["example_id"],
+ example_id=example_id,
query_hash=query_hash,
- dataset_type=DatasetType(result["dataset_type"]),
+ dataset_type=dataset_type,
research_id=result.get("research_id"),
- question=result["question"],
- correct_answer=result["correct_answer"],
+ question=question,
+ correct_answer=correct_answer,
response=result.get("response"),
extracted_answer=result.get("extracted_answer"),
confidence=result.get("confidence"),
diff --git a/tests/benchmarks/web_api/test_benchmark_result_dedup.py b/tests/benchmarks/web_api/test_benchmark_result_dedup.py
index 1c8a9523b7..03b8c1a1f4 100644
--- a/tests/benchmarks/web_api/test_benchmark_result_dedup.py
+++ b/tests/benchmarks/web_api/test_benchmark_result_dedup.py
@@ -164,6 +164,51 @@ def test_repeated_sync_does_not_double_insert():
assert _count(session) == 1
+def test_malformed_results_do_not_abort_valid_batch(duplicate_warnings):
+ """Bad result payloads are logged and skipped without blocking later rows."""
+ missing_question = _result("bad-missing", "bad-missing-hash")
+ missing_question["task_index"] = 1
+ missing_question.pop("question")
+ invalid_dataset = _result("bad-dataset", "bad-dataset-hash")
+ invalid_dataset["task_index"] = 2
+ invalid_dataset["dataset_type"] = "not-a-dataset"
+
+ svc = BenchmarkService(socket_service=MagicMock())
+ session = _make_session()
+ run_data = {
+ "results": [
+ _result("valid-before", "valid-before-hash"),
+ missing_question,
+ invalid_dataset,
+ _result("valid-after", "valid-after-hash"),
+ ]
+ }
+
+ staged = svc._persist_unsaved_results(session, 1, run_data)
+ session.commit()
+
+ assert staged == [0, 3]
+ assert _count(session) == 2
+ persisted_ids = {
+ row.example_id
+ for row in session.query(BenchmarkResult)
+ .filter_by(benchmark_run_id=1)
+ .all()
+ }
+ assert persisted_ids == {"valid-before", "valid-after"}
+
+ messages = [record["message"] for record in duplicate_warnings]
+ assert len(messages) == 2
+ assert "index 1" in messages[0]
+ assert "example_id='bad-missing'" in messages[0]
+ assert "task_index=1" in messages[0]
+ assert "KeyError" in messages[0]
+ assert "index 2" in messages[1]
+ assert "example_id='bad-dataset'" in messages[1]
+ assert "task_index=2" in messages[1]
+ assert "ValueError" in messages[1]
+
+
def test_duplicate_within_batch_is_logged(duplicate_warnings):
"""The within-batch skip names the run and the dropped example (#4860).