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): register fetched URLs atomically (#5363)

Ziyang Guoa683b89fcb80
diff --git a/changelog.d/+atomic-fetch-citations.bugfix.md b/changelog.d/+atomic-fetch-citations.bugfix.md
new file mode 100644
index 0000000000..8b3cb99e02
--- /dev/null
+++ b/changelog.d/+atomic-fetch-citations.bugfix.md
@@ -0,0 +1 @@
+Concurrent page fetches now reuse one citation index for the same URL, and deep acyclic citation chains report a distinct depth-limit error instead of being mislabeled as circular.
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 1306045017..9863e2c474 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
@@ -146,6 +146,38 @@ class SearchResultsCollector:
self._all_links.append(r)
return start_idx
+ def find_or_add_result(
+ self,
+ result: dict,
+ engine_name: str = "web",
+ ) -> int:
+ """Atomically reuse or register one result and return its 1-based index.
+
+ Fetch tools can run concurrently in pooled subagents. Keeping the URL
+ lookup and append under one lock prevents two fetches of the same URL
+ from allocating separate citation indices.
+ """
+ url = result.get("link", result.get("url", ""))
+ with self._lock:
+ for tracked in self._all_links:
+ if tracked.get("link", tracked.get("url", "")) == url:
+ idx = tracked.get("index")
+ if idx is not None:
+ return int(idx)
+
+ index = len(self._all_links) + 1
+ tracked = dict(result)
+ tracked["index"] = str(index)
+ tracked["source_engine"] = engine_name
+ if "link" not in tracked and "url" in tracked:
+ tracked["link"] = tracked["url"]
+ self._results.append(tracked)
+ link = tracked.get("link", "")
+ if link:
+ self._sources.append(link)
+ self._all_links.append(tracked)
+ return index
+
def find_by_url(self, url: str) -> int | None:
"""Return the 1-based citation index if *url* is already tracked, else ``None``."""
with self._lock:
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 e27180317e..c128a93236 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
@@ -84,17 +84,13 @@ def _register_in_collector(
If the URL was already tracked (via a prior search hit) the existing
index is reused so the agent sees a stable citation per URL.
"""
- existing_idx = collector.find_by_url(url)
- if existing_idx is not None:
- return existing_idx
snippet = snippet_source[:200].strip()
if len(snippet_source) > 200:
snippet += "..."
- start = collector.add_results(
- [{"title": title, "link": url, "snippet": snippet}],
+ return collector.find_or_add_result(
+ {"title": title, "link": url, "snippet": snippet},
engine_name="fetch",
)
- return start + 1
def _enforce_url_policy(url: str, egress_context: Any) -> None:
@@ -186,11 +182,16 @@ def _try_resolve_url(
if _visited is None:
_visited = set()
- if url in _visited or len(_visited) >= 5:
+ if url in _visited:
return (
_KIND_ERROR,
f"Circular citation reference detected for '{url}'.",
)
+ if len(_visited) >= 5:
+ return (
+ _KIND_ERROR,
+ f"Citation resolution depth limit exceeded for '{url}'.",
+ )
_visited.add(url)
# 1. Citation marker [N] → resolve to citation's URL.
diff --git a/tests/advanced_search_system/tools/test_fetch_modes.py b/tests/advanced_search_system/tools/test_fetch_modes.py
index 94218819dc..26f707bde3 100644
--- a/tests/advanced_search_system/tools/test_fetch_modes.py
+++ b/tests/advanced_search_system/tools/test_fetch_modes.py
@@ -769,6 +769,48 @@ def test_circular_citation_marker_prevents_unbounded_recursion():
assert "Circular citation reference detected" in out
+def test_multi_node_citation_cycle_reports_circular_reference():
+ """A [1] -> [2] -> [1] cycle is detected before the depth cap."""
+ collector = SearchResultsCollector([])
+ collector.add_results(
+ [{"title": "First", "link": "[2]", "snippet": "points to 2"}],
+ engine_name="fetch",
+ )
+ collector.add_results(
+ [{"title": "Second", "link": "[1]", "snippet": "points to 1"}],
+ engine_name="fetch",
+ )
+ tool = build_fetch_tool("full", collector)
+
+ out = tool.invoke({"url": "[1]"})
+
+ assert "Circular citation reference detected for '[1]'" in out
+ assert "depth limit exceeded" not in out
+
+
+def test_deep_acyclic_citation_chain_reports_depth_limit():
+ """A six-hop acyclic chain gets a precise depth-limit error."""
+ collector = SearchResultsCollector([])
+ for index in range(1, 7):
+ link = f"[{index + 1}]" if index < 6 else "https://example.com/final"
+ collector.add_results(
+ [
+ {
+ "title": f"Citation {index}",
+ "link": link,
+ "snippet": f"points to {link}",
+ }
+ ],
+ engine_name="fetch",
+ )
+ tool = build_fetch_tool("full", collector)
+
+ out = tool.invoke({"url": "[1]"})
+
+ assert "Citation resolution depth limit exceeded for '[6]'" in out
+ assert "Circular citation reference detected" not in out
+
+
def test_citation_marker_rewrite_denied_by_egress_policy_names_resolved_url():
"""When a citation marker [N] rewrites to an external URL and that resolved URL is
denied by policy, the denial message names the resolved URL, not the marker."""
diff --git a/tests/strategies/test_langgraph_agent_strategy.py b/tests/strategies/test_langgraph_agent_strategy.py
index b6761baa38..4a5fd90e55 100644
--- a/tests/strategies/test_langgraph_agent_strategy.py
+++ b/tests/strategies/test_langgraph_agent_strategy.py
@@ -182,6 +182,40 @@ class TestSearchResultsCollector:
indices = [r["index"] for r in all_results]
assert len(indices) == len(set(indices)), "Duplicate indices found!"
+ def test_find_or_add_result_is_atomic_for_same_url(self):
+ """Concurrent fetch registration reuses one citation index."""
+ collector, all_links = self._make_collector()
+ barrier = threading.Barrier(8)
+ indices = []
+ errors = []
+
+ def register():
+ try:
+ barrier.wait()
+ index = collector.find_or_add_result(
+ {
+ "title": "Fetched page",
+ "link": "https://example.com/shared",
+ "snippet": "shared",
+ },
+ engine_name="fetch",
+ )
+ indices.append(index)
+ except Exception as exc:
+ errors.append(exc)
+
+ threads = [threading.Thread(target=register) for _ in range(8)]
+ for thread in threads:
+ thread.start()
+ for thread in threads:
+ thread.join()
+
+ assert not errors
+ assert indices == [1] * 8
+ assert len(collector.results) == 1
+ assert len(all_links) == 1
+ assert collector.sources == ["https://example.com/shared"]
+
def test_find_by_index_returns_result_dict_when_present(self):
"""``find_by_index(N)`` returns the dict stored at citation N so the
fetch tool can resolve a bare ``[N]`` marker to its source URL