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(strategies): keep the sources when the citation handler fails (#6082)

Ehsan22b772225853
diff --git a/changelog.d/6036.bugfix.md b/changelog.d/6036.bugfix.md
new file mode 100644
index 0000000000..9900f04469
--- /dev/null
+++ b/changelog.d/6036.bugfix.md
@@ -0,0 +1 @@
+The source-based and focused-iteration strategies now survive a citation-handler failure during final synthesis. The exception previously reached the strategy's outer handler, which returned an error response: the findings list came back empty and the report body was the error text. The collected sources were never lost, since the search system re-attaches `all_links_of_system` itself. The run now keeps its findings, says in the report that synthesis failed, and emits a `synthesis_error` progress event so the run is not classified as a plain success.
diff --git a/src/local_deep_research/advanced_search_system/strategies/focused_iteration_strategy.py b/src/local_deep_research/advanced_search_system/strategies/focused_iteration_strategy.py
index 11869d6cad..e38f621e62 100644
--- a/src/local_deep_research/advanced_search_system/strategies/focused_iteration_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/focused_iteration_strategy.py
@@ -24,6 +24,7 @@ from typing import Dict, List
from loguru import logger
from ...citation_handler import CitationHandler
+from ...security import scrub_error
# Model and search should be provided by AdvancedSearchSystem
from ...utilities.thread_context import (
@@ -332,17 +333,59 @@ class FocusedIterationStrategy(BaseSearchStrategy):
# Use citation handler for final synthesis
# Note: nr_of_links=total_citation_count_before_this_search ensures sequential report citations are offset correctly
- final_result = self.citation_handler.analyze_followup(
- query,
- self.all_search_results,
- previous_knowledge="",
- nr_of_links=total_citation_count_before_this_search,
- )
+ citation_failed = False
+ try:
+ final_result = self.citation_handler.analyze_followup(
+ query,
+ self.all_search_results,
+ previous_knowledge="",
+ nr_of_links=total_citation_count_before_this_search,
+ )
+ except Exception as exc:
+ # Without this the exception reaches the outer handler, which
+ # returns _create_error_response, so the findings and the
+ # report body are replaced by the error. Same guard the
+ # langgraph strategy has around this call.
+ citation_failed = True
+ final_result = None
+ logger.warning(
+ f"Citation handler failed in the focused-iteration "
+ f"strategy, keeping the sources without a synthesis "
+ f"(query '{query[:80]}')"
+ )
+ logger.debug(
+ f"Citation handler exception details: "
+ f"{type(exc).__name__}: {scrub_error(exc)}"
+ )
+ # Nothing downstream carries the "Error:" prefix any more, so
+ # without this event research_service classifies the run as a
+ # success and the reader gets no hint that synthesis failed.
+ self._update_progress(
+ "Final synthesis failed. Returning the sources found for "
+ "this query.",
+ 90,
+ {
+ "phase": "synthesis_error",
+ "error_type": "citation_handler",
+ },
+ )
- synthesized_content = final_result.get(
- "content", "No relevant results found."
- )
- documents = final_result.get("documents", [])
+ if final_result:
+ synthesized_content = final_result.get(
+ "content", "No relevant results found."
+ )
+ documents = final_result.get("documents", [])
+ elif citation_failed:
+ synthesized_content = (
+ "Final synthesis failed. The sources found for this query "
+ "are listed below."
+ )
+ documents = []
+ else:
+ # A falsy result is not a failure: it is the handler saying it
+ # found nothing, which is what it said before this guard.
+ synthesized_content = "No relevant results found."
+ documents = []
# Add final synthesis finding
final_finding = {
diff --git a/src/local_deep_research/advanced_search_system/strategies/source_based_strategy.py b/src/local_deep_research/advanced_search_system/strategies/source_based_strategy.py
index b90db33677..cb1e306521 100644
--- a/src/local_deep_research/advanced_search_system/strategies/source_based_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/source_based_strategy.py
@@ -7,6 +7,7 @@ from ...citation_handler import CitationHandler
# Removed get_db_setting import - using settings_snapshot instead
from ...security.log_sanitizer import sanitize_error_for_client
+from ...security import scrub_error
from ...utilities.thread_context import (
preserve_research_context,
get_search_context,
@@ -492,12 +493,42 @@ class SourceBasedSearchStrategy(BaseSearchStrategy):
{"phase": "synthesis", "type": "error"},
)
- final_citation_result = self.citation_handler.analyze_followup(
- query,
- final_filtered_results,
- previous_knowledge="",
- nr_of_links=total_citation_count_before_this_search,
- )
+ citation_failed = False
+ try:
+ final_citation_result = self.citation_handler.analyze_followup(
+ query,
+ final_filtered_results,
+ previous_knowledge="",
+ nr_of_links=total_citation_count_before_this_search,
+ )
+ except Exception as exc:
+ # Without this the exception reaches the outer handler, which
+ # replaces synthesized_content and formatted_findings with
+ # "Error: ...", so the report body is the error. Same guard
+ # the langgraph strategy has around this call.
+ citation_failed = True
+ final_citation_result = None
+ logger.warning(
+ f"Citation handler failed in the source-based strategy, "
+ f"keeping the sources without a synthesis "
+ f"(query '{query[:80]}')"
+ )
+ logger.debug(
+ f"Citation handler exception details: "
+ f"{type(exc).__name__}: {scrub_error(exc)}"
+ )
+ # Nothing downstream carries the "Error:" prefix any more, so
+ # without this event research_service classifies the run as a
+ # success and the reader gets no hint that synthesis failed.
+ self._update_progress(
+ "Final synthesis failed. Returning the sources found for "
+ "this query.",
+ 90,
+ {
+ "phase": "synthesis_error",
+ "error_type": "citation_handler",
+ },
+ )
# analyze_followup calls _create_documents() which sets "index" on each
# dict if not already present (via base_citation_handler.py:68-69).
# Since these are the same dict objects now in all_links_of_system,
@@ -507,6 +538,15 @@ class SourceBasedSearchStrategy(BaseSearchStrategy):
if final_citation_result:
synthesized_content = final_citation_result["content"]
documents = final_citation_result.get("documents", [])
+ elif citation_failed:
+ # Distinct from the empty-result message below: the sources are
+ # there, the synthesis step is what failed, and saying "no
+ # relevant results" would send the reader after the wrong thing.
+ synthesized_content = (
+ "Final synthesis failed. The sources found for this query "
+ "are listed below."
+ )
+ documents = []
else:
synthesized_content = (
"No relevant results found in final synthesis."
diff --git a/tests/advanced_search_system/strategies/test_citation_handler_failure_keeps_sources.py b/tests/advanced_search_system/strategies/test_citation_handler_failure_keeps_sources.py
new file mode 100644
index 0000000000..fffa51447d
--- /dev/null
+++ b/tests/advanced_search_system/strategies/test_citation_handler_failure_keeps_sources.py
@@ -0,0 +1,161 @@
+"""A failing citation handler must not throw away the run's findings.
+
+The langgraph strategy has guarded its analyze_followup call since #5904; the
+source-based and focused-iteration strategies called the same handler bare, so
+one exception there reached the strategy's outer handler, which returns an
+empty findings list and an "Error: ..." report body. The links themselves
+survive either way (``search_system`` re-attaches ``all_links_of_system``), so
+what the reader lost was the findings and the report.
+"""
+
+from unittest.mock import Mock, patch
+
+
+def _focused(**kwargs):
+ from local_deep_research.advanced_search_system.strategies.focused_iteration_strategy import (
+ FocusedIterationStrategy,
+ )
+
+ search = Mock()
+ search.run.return_value = [{"title": "T", "link": "https://example.test/a"}]
+ model = Mock()
+ model.invoke.return_value = Mock(content="Generated questions")
+ return FocusedIterationStrategy(
+ model=model,
+ search=search,
+ max_iterations=1,
+ use_browsecomp_optimization=False,
+ **kwargs,
+ )
+
+
+def _source_based():
+ from local_deep_research.advanced_search_system.strategies.source_based_strategy import (
+ SourceBasedSearchStrategy,
+ )
+
+ search = Mock()
+ search.run.return_value = [{"title": "T", "link": "https://example.test/a"}]
+ model = Mock()
+ model.invoke.return_value = Mock(content="Generated questions")
+ return SourceBasedSearchStrategy(
+ model=model, search=search, use_cross_engine_filter=False
+ )
+
+
+class TestFocusedIteration:
+ def test_a_raising_citation_handler_still_returns_the_run(self):
+ strategy = _focused()
+ with patch.object(
+ strategy.question_generator,
+ "generate_questions",
+ return_value=["Q1"],
+ ):
+ with patch.object(
+ strategy.citation_handler,
+ "analyze_followup",
+ side_effect=RuntimeError("llm timed out"),
+ ):
+ result = strategy.analyze_topic("test query")
+
+ assert "error" not in result, (
+ "the run was replaced by an error response"
+ )
+ assert result["findings"], "the findings were discarded"
+ assert "synthesis failed" in result["current_knowledge"].lower()
+
+ def test_a_working_citation_handler_is_unchanged(self):
+ strategy = _focused()
+ with patch.object(
+ strategy.question_generator,
+ "generate_questions",
+ return_value=["Q1"],
+ ):
+ with patch.object(
+ strategy.citation_handler,
+ "analyze_followup",
+ return_value={"content": "Synthesized", "documents": []},
+ ):
+ result = strategy.analyze_topic("test query")
+
+ assert result["current_knowledge"] == "Synthesized"
+
+ def test_an_empty_result_keeps_the_no_results_message(self):
+ """A falsy return is the handler finding nothing, not failing. It must
+ not be reported as a synthesis failure."""
+ strategy = _focused()
+ with patch.object(
+ strategy.question_generator,
+ "generate_questions",
+ return_value=["Q1"],
+ ):
+ with patch.object(
+ strategy.citation_handler, "analyze_followup", return_value={}
+ ):
+ result = strategy.analyze_topic("test query")
+
+ assert result["current_knowledge"] == "No relevant results found."
+
+ def test_the_failure_is_reported_as_a_progress_event(self):
+ """Nothing downstream carries the "Error:" prefix once the exception
+ is caught, so the run would otherwise read as a plain success."""
+ strategy = _focused()
+ events = []
+ strategy.progress_callback = lambda message, percent, metadata: (
+ events.append((message, percent, metadata))
+ )
+ with patch.object(
+ strategy.question_generator,
+ "generate_questions",
+ return_value=["Q1"],
+ ):
+ with patch.object(
+ strategy.citation_handler,
+ "analyze_followup",
+ side_effect=RuntimeError("llm timed out"),
+ ):
+ strategy.analyze_topic("test query")
+
+ phases = [m.get("phase") for _, _, m in events if m]
+ assert "synthesis_error" in phases, phases
+
+
+class TestSourceBased:
+ def test_a_raising_citation_handler_still_returns_the_run(self):
+ strategy = _source_based()
+ with patch.object(
+ strategy.question_generator,
+ "generate_questions",
+ return_value=["Q1"],
+ ):
+ with patch.object(
+ strategy.citation_handler,
+ "analyze_followup",
+ side_effect=RuntimeError("llm timed out"),
+ ):
+ result = strategy.analyze_topic("test query")
+
+ contents = [f.get("content", "") for f in result["findings"]]
+ assert not any(c.startswith("Error:") for c in contents), contents
+ assert any("synthesis failed" in c.lower() for c in contents), contents
+
+ def test_the_failure_is_reported_as_a_progress_event(self):
+ strategy = _source_based()
+ events = []
+ strategy.progress_callback = lambda message, percent, metadata: (
+ events.append((message, percent, metadata))
+ )
+ with patch.object(
+ strategy.question_generator,
+ "generate_questions",
+ return_value=["Q1"],
+ ):
+ with patch.object(
+ strategy.citation_handler,
+ "analyze_followup",
+ side_effect=RuntimeError("llm timed out"),
+ ):
+ strategy.analyze_topic("test query")
+
+ phases = [m.get("phase") for _, _, m in events if m]
+ assert "synthesis_error" in phases, phases