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(citations): preserve failure marker diagnostics (#5904)

Faisal Hussain7889502f6eea
diff --git a/changelog.d/5904.bugfix.md b/changelog.d/5904.bugfix.md
new file mode 100644
index 0000000000..32ae16bafc
--- /dev/null
+++ b/changelog.d/5904.bugfix.md
@@ -0,0 +1 @@
+Preserve zero-citation diagnostics when citation handling fails and add regression coverage for citation-marker reporting and sanitized exception logging.
diff --git a/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py b/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py
index ea684f2581..f08938d653 100644
--- a/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py
@@ -2883,6 +2883,10 @@ class LangGraphAgentStrategy(BaseSearchStrategy):
# guarantees, and the empty-collector condition is also reachable
# from chat follow-ups. Until that is redesigned, make the skip
# loud and report whether the raw answer already contains markers.
+ CITATION_MARKER_RE = re.compile(
+ r"[\[【]\d+(?:\s*,\s*\d+)*[\]】]",
+ )
+
# Counted, not measured — see ``count_distinct_sources``. Every
# "N sources" number below is what the ## Sources block renders,
# not how many entries back it.
@@ -2892,15 +2896,15 @@ class LangGraphAgentStrategy(BaseSearchStrategy):
and self.all_links_of_system
and final_answer not in (NO_RESULTS_MESSAGE, NO_SYNTHESIS_MESSAGE)
):
- existing_markers = re.findall(
- r"[\[【]\d+(?:\s*,\s*\d+)*[\]】]", final_answer or ""
+ raw_fallback_markers = CITATION_MARKER_RE.findall(
+ final_answer or ""
)
- if existing_markers:
+ if raw_fallback_markers:
logger.warning(
f"Citation pass skipped: no new sources collected in "
f"this call although {accumulated_sources} "
f"are accumulated; the raw answer already contains "
- f"{len(existing_markers)} inline [N]/【N】 marker(s) and "
+ f"{len(raw_fallback_markers)} inline [N]/【N】 marker(s) and "
f"will be preserved as-is (query '{query[:80]}')"
)
else:
@@ -2973,32 +2977,44 @@ class LangGraphAgentStrategy(BaseSearchStrategy):
# Only the text falls back: any documents the dict
# does carry are still returned to the caller, as
# they were before this branch existed.
+ raw_fallback_markers = CITATION_MARKER_RE.findall(
+ final_answer or ""
+ )
documents = citation_result.get("documents", [])
citation_failed = True
logger.warning(
f"Citation handler returned a dict without a "
f"'content' or 'response' key; using raw agent "
- f"answer (query '{query[:80]}')"
+ f"answer ({len(raw_fallback_markers)} inline [N]/【N】 marker(s) present, "
+ f"query '{query[:80]}')"
)
else:
+ raw_fallback_markers = CITATION_MARKER_RE.findall(
+ final_answer or ""
+ )
citation_failed = True
logger.warning(
f"Citation handler returned a non-dict result "
f"({type(citation_result).__name__}); using raw "
- f"agent answer (query '{query[:80]}')"
+ f"agent answer ({len(raw_fallback_markers)} inline [N]/【N】 marker(s) present, "
+ f"query '{query[:80]}')"
)
except Exception as exc:
- citation_failed = True
- logger.warning(
- f"Citation handler failed, using raw agent answer "
- f"(query '{query[:80]}')"
+ raw_fallback_markers = CITATION_MARKER_RE.findall(
+ final_answer or ""
)
+ citation_failed = True
safe_exc = scrub_error(exc)
logger.debug(
- f"Citation handler exception details: "
- f"{type(exc).__name__}: {safe_exc}"
+ "Citation handler exception details: {}: {}",
+ type(exc).__name__,
+ safe_exc,
+ )
+ logger.warning(
+ f"Citation handler failed, using raw agent answer "
+ f"({len(raw_fallback_markers)} inline [N]/【N】 marker(s) present, "
+ f"query '{query[:80]}')"
)
-
# Suppressed when the handler failed — the raw answer is
# expected to lack markers then, and blaming "synthesis"
# would misdirect debugging. The marker pattern must accept
@@ -3008,8 +3024,8 @@ class LangGraphAgentStrategy(BaseSearchStrategy):
# (`[1, 2]`, which the formatter's comma_citation_pattern
# parses and the sibling skip-branch check above already
# matches). A bare `\[\d+\]` misses the grouped-only case.
- if not citation_failed and not re.search(
- r"[\[【]\d+(?:\s*,\s*\d+)*[\]】]", synthesized_content or ""
+ if not citation_failed and not CITATION_MARKER_RE.search(
+ synthesized_content or ""
):
logger.warning(
f"Synthesis produced no inline [N]/【N】 citation markers "
diff --git a/tests/strategies/test_langgraph_agent_strategy.py b/tests/strategies/test_langgraph_agent_strategy.py
index 52c51fdc9f..92d5896e04 100644
--- a/tests/strategies/test_langgraph_agent_strategy.py
+++ b/tests/strategies/test_langgraph_agent_strategy.py
@@ -4641,6 +4641,43 @@ class TestFinalizeCitationLogging:
for w in self._warnings(mock_logger)
)
+ def test_handler_exception_logs_nonzero_marker_census(self):
+ """When citation_handler raises, existing markers in the raw answer
+ must be counted in the failure warning."""
+ handler = MagicMock()
+ handler.analyze_followup.side_effect = RuntimeError(
+ "Rate limit exceeded"
+ )
+ strategy = self._make_strategy(all_links=[], citation_handler=handler)
+ strategy.collector.add_results(
+ [{"title": "New", "link": "https://b.example/y", "snippet": "s"}],
+ engine_name="web",
+ )
+
+ with patch(self._LOGGER_PATH) as mock_logger:
+ result = strategy._finalize(
+ "test_query",
+ "Raw answer with [1], [2, 3], and 【4】 markers.",
+ 1,
+ 0,
+ [],
+ )
+
+ assert (
+ result["current_knowledge"]
+ == "Raw answer with [1], [2, 3], and 【4】 markers."
+ )
+ warnings = self._warnings(mock_logger)
+ assert any(
+ "Citation handler failed, using raw agent answer (3 inline [N]/【N】 marker(s) present, query 'test_query')"
+ in w
+ for w in warnings
+ )
+ assert not any(
+ "Synthesis produced no inline [N]/【N】 citation markers" in w
+ for w in warnings
+ )
+
def test_milestone_skipped_for_no_results_sentinel(self):
"""NO_RESULTS_MESSAGE sentinel must suppress the progress milestone completely."""
from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (
@@ -4802,7 +4839,10 @@ class TestFinalizeCitationLogging:
to lack markers — warn about the failure, not about 'synthesis'
that never ran."""
handler = MagicMock()
- handler.analyze_followup.side_effect = RuntimeError("boom")
+ secret_key = "sk-ant-api03-abcdef1234567890abcdef"
+ handler.analyze_followup.side_effect = ValueError(
+ f"LLM timeout for Bearer {secret_key}"
+ )
strategy = self._make_strategy(all_links=[], citation_handler=handler)
strategy.collector.add_results(
[{"title": "New", "link": "https://b.example/y", "snippet": "s"}],
@@ -4813,14 +4853,30 @@ class TestFinalizeCitationLogging:
result = strategy._finalize("q", "raw uncited", 1, 0, [])
warnings = self._warnings(mock_logger)
+
assert any(
- "Citation handler failed" in w and "(query 'q')" in w
+ "Citation handler failed, using raw agent answer "
+ "(0 inline [N]/【N】 marker(s) present, query 'q')" in w
for w in warnings
)
+
+ assert not any("Synthesis produced no inline" in w for w in warnings)
+
+ assert result["current_knowledge"] == "raw uncited"
+
+ debug_calls = mock_logger.debug.call_args_list
+
+ assert any(
+ call.args[0] == "Citation handler exception details: {}: {}"
+ and call.args[1] == "ValueError"
+ and call.args[2] == "LLM timeout for Bearer [REDACTED]"
+ for call in debug_calls
+ )
+
assert not any(
- "no inline [N]/【N】 citation markers" in w for w in warnings
+ secret_key in " ".join(str(arg) for arg in call.args)
+ for call in debug_calls
)
- assert result["current_knowledge"] == "raw uncited"
def test_handler_non_dict_result_warns_distinctly(self):
"""A handler that violates its contract (non-dict return) must
@@ -4840,7 +4896,9 @@ class TestFinalizeCitationLogging:
warnings = self._warnings(mock_logger)
assert any(
- "non-dict result (str)" in w and "(query 'q')" in w
+ "non-dict result (str)" in w
+ and "0 inline [N]/【N】 marker(s) present" in w
+ and "query 'q'" in w
for w in warnings
)
assert not any(
@@ -4867,7 +4925,8 @@ class TestFinalizeCitationLogging:
warnings = self._warnings(mock_logger)
assert any(
"dict without a 'content' or 'response' key" in w
- and "(query 'q')" in w
+ and "0 inline [N]/【N】 marker(s) present" in w
+ and "query 'q'" in w
for w in warnings
)
assert not any(