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(research): deduplicate URLs in SearchResultsCollector to reuse citation indices (#5379) (#5381)

Sed599225b57f
diff --git a/changelog.d/5381.breaking.md b/changelog.d/5381.breaking.md
new file mode 100644
index 0000000000..a33d9fb6fa
--- /dev/null
+++ b/changelog.d/5381.breaking.md
@@ -0,0 +1 @@
+**`SearchResultsCollector.add_results()` now returns `tuple[int, list[dict]]` instead of `int`.** Callers that did `start = collector.add_results(results)` must migrate to `start, indexed = collector.add_results(results)` and pass `indexed` to `_format_results()` so deduped citation indices (`[N]`) stay in sync with the collector. The old `int`-only return is no longer available; this is a breaking change for external programmatic users of `SearchResultsCollector`. Internal call sites (`web_search`, `specialized_search`, `fetch_content`) have been updated.
diff --git a/changelog.d/5381.bugfix.md b/changelog.d/5381.bugfix.md
new file mode 100644
index 0000000000..8a1ec2882e
--- /dev/null
+++ b/changelog.d/5381.bugfix.md
@@ -0,0 +1,3 @@
+Fixed search result collection in `LangGraphAgentStrategy` to deduplicate URLs so repeated search hits across queries reuse their existing citation index instead of assigning duplicate numbers. Also fixes RAG chunk URI fragments for library search hits to use correct metadata keys (`source_id`/`document_id`) and adds chunk-targeted HTML anchors (`id="chunk-{{ chunk.index }}"`) so citations scroll to the cited chunk.
+
+Further hardened the chunk-anchor contract: chunk-URL fragments are now validated centrally in `src/local_deep_research/utilities/chunk_anchor.py` and reused by `CollectionSearchEngine`, `LibraryRAGSearchEngine`, and `SearchResultsCollector.add_results`. A malformed `chunk_index`/`chunk_id` (UUID, boolean, negative, etc.) cannot leak into a citation; a missing/rejected `doc_id` no longer appends `#chunk-...` to an unrelated route; and any producer-supplied unvalidated `#chunk-...` fragment is stripped rather than trusted. RAG producers also sanitise `doc_id`/`source_id` (including the primary `r.source_id` path) before URL construction. `SearchResultsCollector` now allocates citation indices past the highest seeded index so sparse seeds are not overwritten; the `_format_results` fallback warning routes the URL through `redact_url_for_log` so credentials never appear raw in logs; and the constructor skips legacy non-dict seeded entries.
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 47aa0d80be..7a7d778ffc 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
@@ -24,7 +24,13 @@ from loguru import logger
from ...citation_handler import CitationHandler
from ...security.egress import EngineClassification, classify_engine
-from ...security import sanitize_error_for_client
+from ...security import redact_url_for_log, sanitize_error_for_client
+from ...utilities.chunk_anchor import (
+ build_chunk_anchor_url,
+ extract_chunk_index,
+ extract_document_id,
+ is_library_chunk_result,
+)
from ...utilities.thread_context import get_search_context, search_context
from ...database.thread_local_session import thread_cleanup
from ..tools.fetch import FETCH_MODES, build_fetch_tool, make_library_resolver
@@ -101,6 +107,19 @@ class SearchResultsCollector:
Thread-safe: multiple subagent threads may call ``add_results``
concurrently. The ``_all_links`` reference points to the strategy's
shared ``all_links_of_system`` list and is never reassigned.
+
+ .. note::
+ ``all_links`` is **aliased**, not copied, so the collector and its
+ caller share one ``all_links_of_system`` list for the final
+ bibliography. Callers must not mutate ``all_links_of_system``
+ directly (e.g. ``all_links.append(...)``) — that bypasses
+ ``add_results`` and desyncs the O(1) ``_url_to_index`` /
+ ``_index_to_result`` maps. All inserts must go through
+ ``add_results`` under the collector's lock. ``find_by_url`` and
+ ``find_by_index`` fall back to a linear scan when a lookup misses
+ the map, so direct external appends remain *visible* but lose O(1)
+ dedup and may reuse indices incorrectly until the next
+ ``add_results`` call.
"""
def __init__(self, all_links: list | None = None) -> None:
@@ -108,6 +127,39 @@ class SearchResultsCollector:
self._sources: list[str] = []
self._lock = threading.Lock()
self._all_links = all_links if all_links is not None else []
+ # O(1) URL → citation-index and index → result lookups. Maintained
+ # under ``_lock`` alongside ``_all_links`` so the LangGraph path
+ # (the only path that mutates ``_all_links``) keeps it in sync.
+ # Seeded once at construction from any pre-existing entries the
+ # caller passed in; entries without an ``index`` are skipped to
+ # avoid storing the literal string ``"None"``.
+ self._url_to_index: dict[str, str] = {}
+ self._index_to_result: dict[str, dict] = {}
+ # Highest seeded citation index — used by ``add_results`` and
+ # ``find_or_add_result`` so newly-allocated indices never collide
+ # with sparse seeded indices.
+ # ``max(0, ...)`` defends against an empty/all-non-dict seed list.
+ max_seeded_idx = 0
+ for r in self._all_links:
+ # Skip legacy non-dict entries — ``r.get`` would raise on a
+ # bare string / None.
+ if not isinstance(r, dict):
+ continue
+ link = r.get("link") or r.get("url") or ""
+ idx = r.get("index")
+ if idx is not None:
+ idx_str = str(idx)
+ if link and link not in self._url_to_index:
+ self._url_to_index[link] = idx_str
+ if idx_str not in self._index_to_result:
+ self._index_to_result[idx_str] = r
+ try:
+ seed_idx = int(idx_str)
+ if seed_idx > max_seeded_idx:
+ max_seeded_idx = seed_idx
+ except (ValueError, TypeError):
+ pass
+ self._max_idx = max_seeded_idx
# -- public API ----------------------------------------------------------
@@ -115,36 +167,120 @@ class SearchResultsCollector:
self,
results: list[dict],
engine_name: str = "web",
- ) -> int:
+ ) -> tuple[int, list[dict]]:
"""Index *results* and append to the internal list **and** the shared
- ``all_links_of_system``. Returns the starting citation index
- (0-based) assigned to the first result in this batch.
+ ``all_links_of_system``.
+
+ .. warning::
+ Return type changed from ``int`` to ``tuple[int, list[dict]]``.
+ Old code ``start = collector.add_results(results)`` must
+ migrate to ``start, indexed = collector.add_results(results)``
+ and pass ``indexed`` to ``_format_results`` so deduped ``[N]``
+ markers stay in sync. See ``changelog.d/5381.breaking.md``.
+
+ Returns ``(start_idx, indexed_copies)``:
+
+ * ``start_idx`` — 0-based offset of the first added result, measured
+ against ``_all_links``. Used for diagnostic logging; do **not**
+ slice ``self._results[start_idx:]`` to recover "the just-added"
+ results, because duplicates are appended to ``_results`` but not
+ to ``_all_links``, so the two lists grow at different rates.
+ * ``indexed_copies`` — the indexed dicts that were appended to
+ ``_results`` in this batch (each carrying the assigned ``index``).
+ Callers formatting the batch for the LLM should pass this list
+ to ``_format_results`` so the displayed ``[N]`` markers match the
+ collector's stored citation indices — including for duplicates
+ that reuse an existing index instead of getting a new one.
The entire operation runs under a single lock acquisition so that
citation indices are never duplicated.
"""
if not results:
- return len(self._all_links)
+ return len(self._all_links), []
with self._lock:
# Use global offset (all_links) not per-call offset (results)
# so that indices are unique across sections in detailed reports.
start_idx = len(self._all_links)
- for i, raw in enumerate(results):
+ indexed: list[dict] = []
+
+ for raw in results:
if not isinstance(raw, dict):
continue
r = dict(raw) # shallow copy to avoid mutating engine output
- r["index"] = str(start_idx + i + 1)
r["source_engine"] = engine_name
# Normalise URL key — citation handler expects "link"
if "link" not in r and "url" in r:
r["link"] = r["url"]
- self._results.append(r)
link = r.get("link", "")
- if link:
- self._sources.append(link)
- self._all_links.append(r)
- return start_idx
+ metadata = (
+ r.get("metadata")
+ if isinstance(r.get("metadata"), dict)
+ else {}
+ )
+ # Centralised chunk-index validation. Always rebuild from
+ # validated metadata — never trust a producer-supplied
+ # ``#chunk-...`` fragment (UUID / bool / negative can
+ # otherwise survive when metadata fails validation but the
+ # URL already carries a fragment).
+ if is_library_chunk_result(r):
+ chunk_idx = extract_chunk_index(metadata)
+ doc_id = extract_document_id(metadata, r)
+ if chunk_idx is not None and doc_id:
+ rebuilt = build_chunk_anchor_url(
+ link, doc_id, chunk_idx
+ )
+ if rebuilt is not None:
+ link = rebuilt
+ r["link"] = link
+ r["url"] = link
+ elif isinstance(link, str) and "#chunk-" in link:
+ # Producer shipped a chunk fragment we cannot
+ # validate — strip it so a malformed anchor never
+ # reaches the bibliography. Leave non-chunk
+ # fragments alone.
+ stripped = link.split("#", 1)[0]
+ logger.debug(
+ "add_results: stripping unvalidated chunk "
+ "fragment from link={}",
+ redact_url_for_log(link),
+ )
+ link = stripped
+ r["link"] = link
+ r["url"] = link
+ if link and link in self._url_to_index:
+ # Duplicate URL — reuse the existing citation index
+ # so repeated search hits collapse to a single [N].
+ r["index"] = self._url_to_index[link]
+ logger.debug(
+ "add_results: dedup reuse url={} -> [{}]",
+ redact_url_for_log(link),
+ r["index"],
+ )
+ else:
+ # Collision-free index allocator: advance ``_max_idx``
+ # so a new entry never collides with a sparse seeded
+ # index. The seeded max is initialised in ``__init__``
+ # from any pre-existing entries.
+ self._max_idx += 1
+ new_idx = str(self._max_idx)
+ r["index"] = new_idx
+ if link:
+ self._url_to_index[link] = new_idx
+ self._index_to_result[new_idx] = r
+ self._sources.append(link)
+ else:
+ # No link — still track by index for find_by_index
+ self._index_to_result[new_idx] = r
+ self._all_links.append(r)
+ logger.debug(
+ "add_results: new citation url={} -> [{}]",
+ redact_url_for_log(link) if link else "<no link>",
+ new_idx,
+ )
+ self._results.append(r)
+ indexed.append(r)
+ return start_idx, indexed
def find_or_add_result(
self,
@@ -159,13 +295,29 @@ class SearchResultsCollector:
"""
url = result.get("link", result.get("url", ""))
with self._lock:
+ if url and url in self._url_to_index:
+ try:
+ return int(self._url_to_index[url])
+ except (ValueError, TypeError):
+ pass
+
for tracked in self._all_links:
- if tracked.get("link", tracked.get("url", "")) == url:
+ if tracked.get("link", tracked.get("url", "")) == url and url:
idx = tracked.get("index")
if idx is not None:
- return int(idx)
-
- index = len(self._all_links) + 1
+ idx_str = str(idx)
+ self._url_to_index[url] = idx_str
+ if idx_str not in self._index_to_result:
+ self._index_to_result[idx_str] = tracked
+ try:
+ return int(idx)
+ except (ValueError, TypeError):
+ pass
+
+ # Collision-free allocator (same as ``add_results``) so the
+ # fetch fast path can never overwrite a sparse seeded index.
+ self._max_idx += 1
+ index = self._max_idx
tracked = dict(result)
tracked["index"] = str(index)
tracked["source_engine"] = engine_name
@@ -174,19 +326,45 @@ class SearchResultsCollector:
self._results.append(tracked)
link = tracked.get("link", "")
if link:
+ self._url_to_index[link] = str(index)
self._sources.append(link)
+ self._index_to_result[str(index)] = tracked
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``."""
+ """Return the 1-based citation index if *url* is already tracked, else ``None``.
+
+ O(1) via ``_url_to_index`` with a linear-scan fallback for entries
+ that were appended to ``_all_links`` outside the collector (see
+ aliasing note in ``__init__``) or that carry a non-int-like index.
+ """
with self._lock:
+ idx_str = self._url_to_index.get(url)
+ if idx_str is not None:
+ try:
+ return int(idx_str)
+ except (ValueError, TypeError):
+ logger.warning(
+ "find_by_url: invalid index for url={}: {!r}",
+ redact_url_for_log(url),
+ idx_str,
+ )
+ # Fallback scan for externally-mutated or legacy entries
for r in self._all_links:
if r.get("link", r.get("url", "")) == url:
idx = r.get("index")
- if idx is not None:
+ if idx is None:
+ continue
+ try:
return int(idx)
- return None
+ except (ValueError, TypeError):
+ logger.warning(
+ "find_by_url: invalid index for url={}: {!r}",
+ redact_url_for_log(url),
+ idx,
+ )
+ continue
return None
def find_by_index(self, idx: int) -> dict | None:
@@ -198,14 +376,26 @@ class SearchResultsCollector:
call to the real URL. Thread-safe via the collector lock; uses
``_all_links`` (the shared, monotonic list) so a citation registered
by the lead agent is also resolvable by a pooled subagent.
+
+ O(1) via ``_index_to_result`` with a linear-scan fallback for
+ externally-mutated entries.
"""
if not isinstance(idx, int) or idx < 1:
return None
+ idx_str = str(idx)
with self._lock:
+ result = self._index_to_result.get(idx_str)
+ if result is not None:
+ return result
+ # Fallback scan for externally-mutated or legacy entries
for r in self._all_links:
stored = r.get("index")
- if stored is not None and int(stored) == idx:
- return r
+ if stored is not None:
+ try:
+ if int(stored) == idx:
+ return r
+ except (ValueError, TypeError):
+ continue
return None
def reset(self) -> None:
@@ -305,7 +495,22 @@ def _format_results(results: list[dict], start_idx: int) -> str:
for i, r in enumerate(results):
if not isinstance(r, dict):
continue
- idx = start_idx + i + 1
+ if "index" in r:
+ idx = r["index"]
+ else:
+ idx = start_idx + i + 1
+ # Route the URL through ``redact_url_for_log`` so credentials,
+ # tokens, and sensitive paths embedded in the URL never appear
+ # raw in logs.
+ raw_link = r.get("link", r.get("url", ""))
+ logger.warning(
+ "_format_results: result missing 'index' key (link={}); "
+ "falling back to start_idx ({}) + i ({}) + 1 = {}",
+ redact_url_for_log(raw_link),
+ start_idx,
+ i,
+ idx,
+ )
title = r.get("title", "No title")
link = r.get("link", r.get("url", ""))
snippet = r.get("snippet", r.get("body", ""))
@@ -343,10 +548,10 @@ def _make_web_search_tool(
results = engine.run(query)
if not isinstance(results, list) or not results:
return f"No results found for '{query}'. Try rephrasing."
- start = collector.add_results(
+ start, indexed = collector.add_results(
results, engine_name=search_engine_name
)
- return _format_results(results, start)
+ return _format_results(indexed, start)
except Exception as exc:
logger.exception("web_search tool error")
# Scrub credentials: a search-engine exception can embed the
@@ -394,8 +599,10 @@ def _make_specialized_search_tool(
results = engine.run(query)
if not isinstance(results, list) or not results:
return f"No results from {engine_name} for '{query}'. Try rephrasing."
- start = collector.add_results(results, engine_name=engine_name)
- return _format_results(results, start)
+ start, indexed = collector.add_results(
+ results, engine_name=engine_name
+ )
+ return _format_results(indexed, start)
except Exception as exc:
logger.exception(f"search_{engine_name} tool error")
return _scrub_tool_error(f"Search error ({engine_name}): {exc}")
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 c128a93236..2be5b78ddb 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
@@ -87,6 +87,29 @@ def _register_in_collector(
snippet = snippet_source[:200].strip()
if len(snippet_source) > 200:
snippet += "..."
+ if not hasattr(collector, "find_or_add_result"):
+ # Legacy/custom collectors without find_or_add_result fallback
+ _, indexed = collector.add_results(
+ [{"title": title, "link": url, "snippet": snippet}],
+ engine_name="fetch",
+ )
+ if indexed:
+ raw_idx = indexed[0].get("index")
+ try:
+ return int(raw_idx)
+ except (ValueError, TypeError):
+ logger.warning(
+ "Failed to parse citation index for url={}: {!r}",
+ redact_url_for_log(url),
+ raw_idx,
+ )
+ existing_idx = collector.find_by_url(url)
+ if existing_idx is not None:
+ return existing_idx
+ raise RuntimeError(
+ f"Failed to register fetched URL in collector: {redact_url_for_log(url)}"
+ )
+
return collector.find_or_add_result(
{"title": title, "link": url, "snippet": snippet},
engine_name="fetch",
diff --git a/src/local_deep_research/utilities/chunk_anchor.py b/src/local_deep_research/utilities/chunk_anchor.py
new file mode 100644
index 0000000000..dd138a4840
--- /dev/null
+++ b/src/local_deep_research/utilities/chunk_anchor.py
@@ -0,0 +1,189 @@
+"""Helpers for building chunk-targeted library/RAG citation anchors.
+
+Centralizes the validation and URL-fragment construction that RAG search
+engines and the LangGraph result collector all share. Every producer
+must route chunk metadata through :func:`extract_chunk_index` before
+interpolating it into a ``#chunk-...`` URL fragment — a UUID or boolean
+``chunk_id`` would otherwise slip into ``document_chunks.html`` as a
+fragment that points at a chunk that does not exist. This module is the
+single source of truth so producers and the collector agree on what a
+valid chunk index looks like.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Mapping, Optional
+
+
+def extract_chunk_index(metadata: Mapping[str, Any] | None) -> Optional[int]:
+ """Return a validated non-negative chunk index from a result's metadata,
+ or ``None`` if the metadata does not carry a usable value.
+
+ Reads (in order):
+
+ * ``metadata["chunk_index"]`` — preferred, always an ``int`` in the
+ production schema.
+ * ``metadata["chunk_id"]`` — legacy field that may carry either an
+ ``int`` or an int-as-string. UUIDs and other non-int-like values
+ are rejected.
+
+ Accepts:
+
+ * ``int`` (excluding ``bool``) — used as-is.
+ * ``str`` whose trimmed value parses as a non-negative integer.
+ * ``float`` whose value is a whole non-negative integer (catches
+ e.g. ``0.0`` from numpy conversion).
+
+ Rejects (returns ``None``):
+
+ * ``bool`` (avoids ``True`` being printed as ``#chunk-True``).
+ * Negative integers — zero is allowed because chunks are 0-indexed.
+ * Strings that are not pure digits (``"550e8400-..."`` UUIDs, etc).
+ * Floats with a fractional part.
+ * Anything else (``None``, dicts, lists, ...).
+ """
+ if not isinstance(metadata, Mapping):
+ return None
+
+ chunk_idx_raw: Any = None
+ if metadata.get("chunk_index") is not None:
+ chunk_idx_raw = metadata["chunk_index"]
+ elif metadata.get("chunk_id") is not None:
+ chunk_idx_raw = metadata["chunk_id"]
+ else:
+ return None
+
+ try:
+ if isinstance(chunk_idx_raw, bool):
+ # bool is a subclass of int but True/False are never chunk ids.
+ return None
+ if isinstance(chunk_idx_raw, int):
+ value = chunk_idx_raw
+ elif isinstance(chunk_idx_raw, str):
+ stripped = chunk_idx_raw.strip()
+ # Reject leading/trailing whitespace, signs, plus signs,
+ # anything that isn't a pure non-negative integer string.
+ if not stripped or not stripped.isdigit():
+ return None
+ value = int(stripped)
+ elif isinstance(chunk_idx_raw, float):
+ if not chunk_idx_raw.is_integer():
+ return None
+ value = int(chunk_idx_raw)
+ else:
+ return None
+ except (ValueError, AttributeError):
+ return None
+
+ # Negative chunk ids never match a real chunk — reject. Zero is
+ # allowed: the document_chunks.html template renders ``chunk.index``
+ # directly as the HTML anchor id, so a 0-indexed chunk anchors at
+ # ``#chunk-0``.
+ if value < 0:
+ return None
+ return value
+
+
+def extract_document_id(
+ metadata: Mapping[str, Any] | None, *top_level: Any
+) -> Optional[str]:
+ """Return a sanitised library document id from a result's metadata or
+ top-level fields, or ``None`` if no usable id is present.
+
+ Reads (in order):
+
+ * ``metadata["doc_id"]`` — legacy key.
+ * ``metadata["source_id"]`` — used by the current LibraryRAGSearchEngine.
+ * ``metadata["document_id"]`` — alternate key.
+ * ``top_level[0]``'s ``source_id`` / ``document_id`` — for results that
+ promote the id to the top-level dict instead of metadata.
+
+ Sanitisation:
+
+ * Non-strings are coerced: ``int`` → ``str``.
+ * Strings are stripped; non-empty values containing only
+ alphanumerics, dashes, and underscores pass. Anything else
+ (whitespace, path traversal, control chars, ``/``) is rejected
+ because it would be interpolated into a URL path.
+ """
+ candidates: list[Any] = []
+ if isinstance(metadata, Mapping):
+ candidates.append(metadata.get("doc_id"))
+ candidates.append(metadata.get("source_id"))
+ candidates.append(metadata.get("document_id"))
+ for obj in top_level:
+ if isinstance(obj, Mapping):
+ candidates.append(obj.get("doc_id"))
+ candidates.append(obj.get("source_id"))
+ candidates.append(obj.get("document_id"))
+
+ for raw in candidates:
+ if raw is None:
+ continue
+ if isinstance(raw, int) and not isinstance(raw, bool):
+ return str(raw)
+ if isinstance(raw, str):
+ stripped = raw.strip()
+ if not stripped:
+ continue
+ if not all(c.isalnum() or c in "-_" for c in stripped):
+ continue
+ return stripped
+ return None
+
+
+def is_library_chunk_result(result: Mapping[str, Any] | None) -> bool:
+ """Return ``True`` if *result* is a library/RAG hit that should receive
+ a chunk anchor.
+
+ Heuristic: the result's ``source`` / ``source_type`` field is
+ ``"library"`` or its link points at ``/library/document/``. Mirrors
+ the producer-side checks in
+ :class:`langgraph_agent_strategy.SearchResultsCollector` so the two
+ agree on the eligibility rule.
+ """
+ if not isinstance(result, Mapping):
+ return False
+ if result.get("source") == "library":
+ return True
+ if result.get("source_type") == "library":
+ return True
+ link = result.get("link") or result.get("url") or ""
+ return isinstance(link, str) and "/library/document/" in link
+
+
+def build_chunk_anchor_url(
+ link: str,
+ doc_id: Optional[str],
+ chunk_index: Optional[int],
+) -> Optional[str]:
+ """Build a ``/library/document/<doc_id>/chunks#chunk-<n>`` URL when
+ *doc_id* and *chunk_index* are both valid, otherwise return ``None``.
+
+ Returns ``None`` (rather than mutating *link*) when:
+
+ * the chunk index failed validation (UUID, bool, negative, string,
+ float with a fractional part, or any other non-int-like value), or
+ * the document id is missing/rejected.
+
+ Callers should leave the original *link* unchanged on ``None`` —
+ appending ``#chunk-...`` to whatever route was already in the link
+ would point the anchor at an unrelated route when the doc id failed
+ sanitisation.
+ """
+ # Re-validate ``chunk_index`` defensively. Most callers should have
+ # already passed it through :func:`extract_chunk_index`, but a
+ # future caller that passes a raw value (e.g. a producer that
+ # forgot to validate) must not be able to inject a malformed
+ # fragment. ``int`` excludes ``bool`` (which is technically an
+ # ``int`` subclass) and ``None``.
+ if doc_id is None:
+ return None
+ if (
+ chunk_index is None
+ or isinstance(chunk_index, bool)
+ or not isinstance(chunk_index, int)
+ or chunk_index < 0
+ ):
+ return None
+ return f"/library/document/{doc_id}/chunks#chunk-{chunk_index}"
diff --git a/src/local_deep_research/web/templates/pages/document_chunks.html b/src/local_deep_research/web/templates/pages/document_chunks.html
index 8f9d7b7fbc..1247037489 100644
--- a/src/local_deep_research/web/templates/pages/document_chunks.html
+++ b/src/local_deep_research/web/templates/pages/document_chunks.html
@@ -31,7 +31,7 @@
</div>
{% for chunk in collection_data.chunks %}
- <div class="ldr-chunk">
+ <div class="ldr-chunk" id="chunk-{{ chunk.index }}">
<div class="ldr-chunk-meta">
<div class="ldr-chunk-meta-item">
<strong>Chunk #{{ chunk.index + 1 }}</strong>
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_collection.py b/src/local_deep_research/web_search_engines/engines/search_engine_collection.py
index bcb5bbf7c0..e0bae65140 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_collection.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_collection.py
@@ -4,18 +4,15 @@ Collection-specific RAG Search Engine
Provides semantic search within a specific document collection using RAG.
"""
-import os
from typing import List, Dict, Any, Optional
from ...security.secure_logging import logger
from .search_engine_library import LibraryRAGSearchEngine
from ...constants import SNIPPET_LENGTH_LONG
from ...research_library.services.library_rag_service import LibraryRAGService
-from ...database.models.library import RAGIndex, Document
-from ...research_library.services.pdf_storage_manager import PDFStorageManager
+from ...database.models.library import RAGIndex
from ...database.session_context import get_user_db_session
-from ...config.thread_settings import get_setting_from_snapshot
-from ...config.paths import get_library_directory
+from ...utilities.chunk_anchor import extract_chunk_index, extract_document_id
from ...utilities.type_utils import to_bool
@@ -257,8 +254,18 @@ class CollectionSearchEngine(LibraryRAGSearchEngine):
else r.text
)
- # Generate document URL
- document_url = self._get_document_url(doc_id)
+ # Generate document URL. Validate chunk_idx and
+ # sanitise doc_id through the shared helpers so a
+ # malformed chunk index (UUID, boolean, negative) or
+ # path-traversal doc_id cannot leak into the citation.
+ chunk_idx = extract_chunk_index(metadata)
+ sanitised_doc_id = extract_document_id(
+ metadata,
+ {"source_id": doc_id} if doc_id else {},
+ )
+ document_url = self._get_document_url(
+ sanitised_doc_id, chunk_index=chunk_idx
+ )
# Add collection info to metadata
metadata["collection_id"] = self.collection_id
@@ -314,55 +321,3 @@ class CollectionSearchEngine(LibraryRAGSearchEngine):
f"Error searching collection '{self.collection_name}' ({type(e).__name__}): {safe_msg}"
)
raise
-
- def _get_document_url(self, doc_id: Optional[str]) -> str:
- """Get the URL for viewing a document."""
- if not doc_id:
- return "#"
-
- # Default to root document page (shows all options: PDF, Text, Chunks, etc.)
- document_url = f"/library/document/{doc_id}"
-
- try:
- with get_user_db_session(self.username) as session:
- document = session.query(Document).filter_by(id=doc_id).first()
- if document:
- from pathlib import Path
-
- from ...research_library.utils import apply_user_subdir
-
- library_root = get_setting_from_snapshot(
- "research_library.storage_path",
- default=str(get_library_directory()),
- settings_snapshot=self.settings_snapshot,
- )
- base_root = (
- Path(os.path.expandvars(library_root))
- .expanduser()
- .resolve()
- )
- shared_library = get_setting_from_snapshot(
- "research_library.shared_library",
- default=False,
- settings_snapshot=self.settings_snapshot,
- )
- # Per-user root with legacy-shared fallback (issue #5521).
- per_user_root = apply_user_subdir(
- base_root, self.username, shared_library
- )
- if PDFStorageManager.pdf_exists(
- per_user_root,
- document,
- session,
- legacy_root=base_root,
- ):
- document_url = f"/library/document/{doc_id}/pdf"
- except Exception as e:
- # Non-fatal: keep the default /library/document/{id} URL.
- safe_msg = self._scrub_error(e)
- logger.warning(
- f"Error getting document URL for {doc_id} "
- f"({type(e).__name__}): {safe_msg}"
- )
-
- return document_url
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_library.py b/src/local_deep_research/web_search_engines/engines/search_engine_library.py
index 4d3809a77f..73a59abacc 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_library.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_library.py
@@ -13,6 +13,10 @@ from ...constants import SNIPPET_LENGTH_LONG
from ...research_library.services.library_rag_service import LibraryRAGService
from ...research_library.services.library_service import LibraryService
from ...config.thread_settings import get_setting_from_snapshot
+from ...utilities.chunk_anchor import (
+ extract_chunk_index,
+ extract_document_id,
+)
from ...utilities.llm_utils import get_server_url
from ...utilities.type_utils import to_bool
from ...database.models.library import RAGIndex, Document
@@ -362,57 +366,20 @@ class LibraryRAGSearchEngine(BaseSearchEngine):
if len(r.text) > SNIPPET_LENGTH_LONG
else r.text
)
-
- # Generate URL to document content
- # Default to root document page (shows all options: PDF, Text, Chunks, etc.)
- document_url = f"/library/document/{doc_id}" if doc_id else "#"
-
- if doc_id:
- try:
- with get_user_db_session(self.username) as session:
- document = (
- session.query(Document)
- .filter_by(id=doc_id)
- .first()
- )
- if document:
- from pathlib import Path
- from ...research_library.utils import (
- apply_user_subdir,
- )
-
- library_root = get_setting_from_snapshot(
- "research_library.storage_path",
- default=str(get_library_directory()),
- settings_snapshot=self.settings_snapshot,
- )
- base_root = (
- Path(os.path.expandvars(library_root))
- .expanduser()
- .resolve()
- )
- shared_library = get_setting_from_snapshot(
- "research_library.shared_library",
- default=False,
- settings_snapshot=self.settings_snapshot,
- )
- # Per-user root, legacy-shared fallback (#5521).
- per_user_root = apply_user_subdir(
- base_root,
- self.username,
- shared_library,
- )
- if PDFStorageManager.pdf_exists(
- per_user_root,
- document,
- session,
- legacy_root=base_root,
- ):
- document_url = (
- f"/library/document/{doc_id}/pdf"
- )
- except Exception:
- logger.warning(f"Error querying document {doc_id}")
+ # Generate URL to document content (targeted chunk if
+ # chunk_index available). Use the shared helpers so a
+ # malformed chunk index (UUID, boolean, negative, etc.)
+ # cannot leak into the citation anchor, and so the
+ # primary ``r.source_id`` path is sanitised the same way
+ # as metadata keys.
+ chunk_idx = extract_chunk_index(metadata)
+ sanitised_doc_id = extract_document_id(
+ metadata,
+ {"source_id": doc_id} if doc_id else {},
+ )
+ document_url = self._get_document_url(
+ sanitised_doc_id, chunk_index=chunk_idx
+ )
result = {
"title": title,
@@ -513,6 +480,64 @@ class LibraryRAGSearchEngine(BaseSearchEngine):
)
return relevant_items
+ def _get_document_url(
+ self, doc_id: Optional[str], chunk_index: Optional[int] = None
+ ) -> str:
+ """Get the URL for viewing a document, targeting a specific chunk if provided."""
+ if not doc_id:
+ return "#"
+
+ if (
+ chunk_index is not None
+ and isinstance(chunk_index, int)
+ and not isinstance(chunk_index, bool)
+ and chunk_index >= 0
+ ):
+ return f"/library/document/{doc_id}/chunks#chunk-{chunk_index}"
+
+ document_url = f"/library/document/{doc_id}"
+ try:
+ with get_user_db_session(self.username) as session:
+ document = session.query(Document).filter_by(id=doc_id).first()
+ if document:
+ from pathlib import Path
+ from ...research_library.utils import apply_user_subdir
+
+ library_root = get_setting_from_snapshot(
+ "research_library.storage_path",
+ default=str(get_library_directory()),
+ settings_snapshot=self.settings_snapshot,
+ )
+ base_root = (
+ Path(os.path.expandvars(library_root))
+ .expanduser()
+ .resolve()
+ )
+ shared_library = get_setting_from_snapshot(
+ "research_library.shared_library",
+ default=False,
+ settings_snapshot=self.settings_snapshot,
+ )
+ # Per-user root with legacy-shared fallback (issue #5521).
+ per_user_root = apply_user_subdir(
+ base_root, self.username, shared_library
+ )
+ if PDFStorageManager.pdf_exists(
+ per_user_root,
+ document,
+ session,
+ legacy_root=base_root,
+ ):
+ document_url = f"/library/document/{doc_id}/pdf"
+ except Exception as e:
+ safe_msg = self._scrub_error(e)
+ logger.warning(
+ f"Error getting document URL for {doc_id} "
+ f"({type(e).__name__}): {safe_msg}"
+ )
+
+ return document_url
+
def close(self):
"""Clean up resources."""
pass
diff --git a/tests/advanced_search_system/tools/test_fetch_modes.py b/tests/advanced_search_system/tools/test_fetch_modes.py
index 26f707bde3..a8366e0c4a 100644
--- a/tests/advanced_search_system/tools/test_fetch_modes.py
+++ b/tests/advanced_search_system/tools/test_fetch_modes.py
@@ -1007,3 +1007,59 @@ def test_non_string_url_returns_none_in_try_resolve_url():
)
assert _try_resolve_url(12345, None, None) is None
+
+
+def test_register_in_collector_assigns_new_index():
+ from local_deep_research.advanced_search_system.tools.fetch import (
+ _register_in_collector,
+ )
+
+ collector = SearchResultsCollector([])
+ idx = _register_in_collector(
+ collector, "http://a.com", "A", "body text for snippet"
+ )
+ assert idx == 1
+ assert collector.find_by_url("http://a.com") == 1
+
+
+def test_register_in_collector_fast_path_reuses_without_reappend():
+ """Already-tracked URL returns existing index and does not grow _results."""
+ from local_deep_research.advanced_search_system.tools.fetch import (
+ _register_in_collector,
+ )
+
+ collector = SearchResultsCollector([])
+ collector.add_results(
+ [{"title": "A", "link": "http://a.com", "snippet": "a"}],
+ engine_name="web",
+ )
+ before = len(collector.results)
+ idx = _register_in_collector(collector, "http://a.com", "A", "fetched body")
+ assert idx == 1
+ assert len(collector.results) == before
+
+
+def test_register_in_collector_slow_path_returns_deduped_index_not_start_plus_one():
+ """Regression for Observation A: when ``find_by_url`` misses (TOCTOU /
+ race) but the URL is already in the collector, the slow path must return
+ the index from the indexed copy — not ``start + 1``, which would be one
+ past the real citation after dedup.
+ """
+ from local_deep_research.advanced_search_system.tools.fetch import (
+ _register_in_collector,
+ )
+
+ collector = SearchResultsCollector([])
+ collector.add_results(
+ [{"title": "A", "link": "http://a.com", "snippet": "a"}],
+ engine_name="web",
+ )
+ # Simulate find_by_url racing / missing while the URL is already tracked.
+ with patch.object(collector, "find_by_url", return_value=None):
+ idx = _register_in_collector(
+ collector, "http://a.com", "A again", "fetched body"
+ )
+
+ assert idx == 1
+ # start would have been 1 (len(_all_links)); start+1 == 2 is the bug.
+ assert idx != 2
diff --git a/tests/strategies/test_langgraph_agent_strategy.py b/tests/strategies/test_langgraph_agent_strategy.py
index 07b2d96de4..b0b47666d8 100644
--- a/tests/strategies/test_langgraph_agent_strategy.py
+++ b/tests/strategies/test_langgraph_agent_strategy.py
@@ -48,12 +48,27 @@ class TestSearchResultsCollector:
{"title": "A", "link": "http://a.com", "snippet": "a"},
{"title": "B", "link": "http://b.com", "snippet": "b"},
]
- start = collector.add_results(results, engine_name="test")
+ start, indexed = collector.add_results(results, engine_name="test")
assert start == 0
assert len(collector.results) == 2
assert collector.results[0]["index"] == "1"
assert collector.results[1]["index"] == "2"
+ # Indexed copies are the same objects that landed in _results.
+ assert indexed[0]["index"] == "1"
+ assert indexed[1]["index"] == "2"
+
+ def test_seeded_linkless_entry_registers_index_and_max_idx(self):
+ """Pre-seeded entries without a link (or with an empty link) must still
+ populate ``_index_to_result`` and advance ``_max_idx`` so future allocations
+ do not collide with the pre-seeded index."""
+ pre_seeded = [{"title": "No Link", "index": "5", "link": ""}]
+ collector, _ = self._make_collector(pre_seeded)
+ assert collector.find_by_index(5) == pre_seeded[0]
+ _, indexed = collector.add_results(
+ [{"title": "New", "link": "http://new.com"}], engine_name="test"
+ )
+ assert indexed[0]["index"] == "6"
def test_add_results_continues_indexing(self):
collector, _ = self._make_collector()
@@ -61,13 +76,163 @@ class TestSearchResultsCollector:
[{"title": "A", "link": "http://a.com", "snippet": "a"}],
engine_name="test",
)
- start = collector.add_results(
+ start, indexed = collector.add_results(
[{"title": "B", "link": "http://b.com", "snippet": "b"}],
engine_name="test",
)
assert start == 1
assert collector.results[1]["index"] == "2"
+ assert indexed[0]["index"] == "2"
+
+ def test_add_results_dedupes_within_single_batch(self):
+ """Two results with the same URL in one ``add_results`` call reuse
+ the first slot's index — the dedup must not only span batches."""
+ collector, all_links = self._make_collector()
+ start, indexed = collector.add_results(
+ [
+ {"title": "First", "link": "http://a.com", "snippet": "a"},
+ {
+ "title": "First dup",
+ "link": "http://a.com",
+ "snippet": "a2",
+ },
+ {"title": "Other", "link": "http://b.com", "snippet": "b"},
+ ],
+ engine_name="test",
+ )
+
+ assert start == 0
+ assert len(all_links) == 2
+ assert len(collector.results) == 3
+ assert indexed[0]["index"] == "1"
+ assert indexed[1]["index"] == "1" # dedup of indexed[0]
+ assert indexed[2]["index"] == "2"
+ # First URL registered once in sources, second URL also once.
+ assert collector.sources.count("http://a.com") == 1
+
+ def test_add_results_returns_indexed_copies_with_link_normalized(self):
+ """URL normalization (``url`` -> ``link``) and chunk-URL rewriting
+ are reflected in the returned indexed copies, not just the stored
+ list."""
+ collector, _ = self._make_collector()
+ _, indexed = collector.add_results(
+ [
+ {
+ "title": "Doc",
+ "url": "http://a.com",
+ "snippet": "a",
+ },
+ {
+ "title": "Doc",
+ "link": "/library/document/doc1",
+ "source": "library",
+ "metadata": {"doc_id": "doc1", "chunk_index": 0},
+ },
+ ],
+ engine_name="test",
+ )
+
+ assert indexed[0]["link"] == "http://a.com"
+ assert indexed[1]["link"] == "/library/document/doc1/chunks#chunk-0"
+
+ def test_add_results_deduplicates_by_url(self):
+ collector, all_links = self._make_collector()
+ collector.add_results(
+ [{"title": "A", "link": "http://a.com", "snippet": "a"}],
+ engine_name="test",
+ )
+ assert collector.results[0]["index"] == "1"
+ assert len(all_links) == 1
+
+ collector.add_results(
+ [
+ {
+ "title": "A Duplicate",
+ "link": "http://a.com",
+ "snippet": "a2",
+ },
+ {"title": "B", "link": "http://b.com", "snippet": "b"},
+ ],
+ engine_name="test",
+ )
+ assert len(all_links) == 2
+ assert collector.results[1]["index"] == "1"
+ assert collector.results[2]["index"] == "2"
+
+ def test_add_results_formats_library_chunk_url(self):
+ collector, all_links = self._make_collector()
+ results_chunk0 = [
+ {
+ "title": "Doc",
+ "link": "/library/document/doc1",
+ "source": "library",
+ "metadata": {"doc_id": "doc1", "chunk_index": 0},
+ }
+ ]
+ results_chunk1 = [
+ {
+ "title": "Doc",
+ "link": "/library/document/doc1",
+ "source": "library",
+ "metadata": {"doc_id": "doc1", "chunk_index": 1},
+ }
+ ]
+ results_chunk0_again = [
+ {
+ "title": "Doc Repeat",
+ "link": "/library/document/doc1",
+ "source": "library",
+ "metadata": {"doc_id": "doc1", "chunk_index": 0},
+ }
+ ]
+
+ collector.add_results(results_chunk0)
+ collector.add_results(results_chunk1)
+ collector.add_results(results_chunk0_again)
+
+ assert len(all_links) == 2
+ assert all_links[0]["link"] == "/library/document/doc1/chunks#chunk-0"
+ assert all_links[0]["index"] == "1"
+ assert all_links[1]["link"] == "/library/document/doc1/chunks#chunk-1"
+ assert all_links[1]["index"] == "2"
+ assert collector.results[2]["index"] == "1"
+
+ @pytest.mark.parametrize(
+ "doc_id_structure",
+ [
+ {"metadata": {"doc_id": "doc123", "chunk_index": 0}},
+ {"metadata": {"source_id": "doc123", "chunk_index": 0}},
+ {"metadata": {"document_id": "doc123", "chunk_index": 0}},
+ {"source_id": "doc123", "metadata": {"chunk_index": 0}},
+ {"document_id": "doc123", "metadata": {"chunk_id": 0}},
+ ],
+ )
+ def test_add_results_formats_library_chunk_url_production_keys(
+ self, doc_id_structure
+ ):
+ """Verify chunk-URL rewriting fires for all production document ID keys
+ (source_id, document_id in metadata or top-level) and chunk keys (chunk_index, chunk_id).
+ """
+ collector, _ = self._make_collector()
+ result = {
+ "title": "Doc",
+ "link": "/library/document/doc123",
+ "source": "library",
+ }
+ for k, v in doc_id_structure.items():
+ if k == "metadata":
+ result.setdefault("metadata", {}).update(v)
+ else:
+ result[k] = v
+
+ start, indexed = collector.add_results([result])
+
+ assert indexed[0]["link"] == "/library/document/doc123/chunks#chunk-0"
+ assert (
+ collector.results[0]["link"]
+ == "/library/document/doc123/chunks#chunk-0"
+ )
def test_add_results_normalizes_url_to_link(self):
collector, _ = self._make_collector()
@@ -107,6 +272,42 @@ class TestSearchResultsCollector:
assert len(all_links) == 1
assert all_links[0]["index"] == "1"
+ def test_preseeded_all_links_seed_url_index(self):
+ """A pre-seeded ``_all_links`` entry seeds ``_url_to_index`` so a
+ later ``add_results`` with the same URL reuses its citation index.
+
+ Entries without an ``index`` (e.g. legacy rows) are skipped to
+ avoid storing the literal string ``"None"``.
+
+ New entries get a collision-free index — one past the highest
+ seeded index, not ``len(_all_links) + 1``, so sparse seeded
+ indices can't be aliased or overwritten."""
+ all_links = [
+ {"title": "Seed", "link": "http://seed.com", "index": "7"},
+ # Legacy entry with no index — must NOT seed "None".
+ {"title": "Legacy", "link": "http://legacy.com"},
+ ]
+ collector, _ = self._make_collector(all_links)
+
+ _, indexed = collector.add_results(
+ [
+ {
+ "title": "Seed again",
+ "link": "http://seed.com",
+ "snippet": "s",
+ },
+ {"title": "New", "link": "http://new.com", "snippet": "n"},
+ ],
+ engine_name="test",
+ )
+
+ # Seed URL reuses its existing index. New URL is allocated one
+ # past the highest seeded index (7 → 8), not ``len(all_links)+1``
+ # (which would be 3 and silently overwrite the seeded index 3 if
+ # one existed in a larger seed list).
+ assert indexed[0]["index"] == "7"
+ assert indexed[1]["index"] == "8"
+
def test_reset_clears_results_but_not_all_links(self):
all_links = []
collector, _ = self._make_collector(all_links)
@@ -147,22 +348,27 @@ class TestSearchResultsCollector:
collector.add_results(
[{"title": "A", "link": "http://a.com", "snippet": "a"}]
)
- start = collector.add_results([])
+ start, indexed = collector.add_results([])
assert start == 1
+ assert indexed == []
def test_thread_safety_no_duplicate_indices(self):
"""Multiple threads adding results should never produce duplicate indices."""
collector, _ = self._make_collector()
- results_per_thread = [
- {"title": f"T{i}", "link": f"http://{i}.com", "snippet": f"s{i}"}
- for i in range(5)
- ]
errors = []
def add_batch(thread_id):
try:
+ results_per_thread = [
+ {
+ "title": f"T{thread_id}-{i}",
+ "link": f"http://t{thread_id}-{i}.com",
+ "snippet": f"s{i}",
+ }
+ for i in range(5)
+ ]
collector.add_results(
- [dict(r) for r in results_per_thread],
+ results_per_thread,
engine_name=f"thread-{thread_id}",
)
except Exception as exc:
@@ -182,6 +388,80 @@ class TestSearchResultsCollector:
indices = [r["index"] for r in all_results]
assert len(indices) == len(set(indices)), "Duplicate indices found!"
+ def test_thread_safety_same_url_dedup(self):
+ """Concurrent ``add_results`` with the SAME URL must dedup to one index.
+
+ Regression for F3: the original thread-safety test used unique URLs
+ per thread, so it never exercised the dedup path under concurrency.
+ """
+ collector, all_links = self._make_collector()
+ errors: list[Exception] = []
+
+ def add_same_url():
+ try:
+ collector.add_results(
+ [
+ {
+ "title": "Same",
+ "link": "http://same.com",
+ "snippet": "s",
+ }
+ ],
+ engine_name="test",
+ )
+ except Exception as exc: # pragma: no cover
+ errors.append(exc)
+
+ threads = [threading.Thread(target=add_same_url) for _ in range(8)]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join()
+
+ assert not errors
+ # All 8 calls appended to _results, but only one unique URL in _all_links
+ assert len(collector.results) == 8
+ assert len(all_links) == 1
+ indices = [r["index"] for r in collector.results]
+ assert len(set(indices)) == 1
+ assert indices[0] == "1"
+ assert collector.find_by_url("http://same.com") == 1
+ # find_by_index O(1) path
+ assert collector.find_by_index(1)["link"] == "http://same.com"
+
+ def test_chunk_index_boolean_rejected(self):
+ """Boolean chunk_index (e.g. True) must not format as '#chunk-True'."""
+ collector, _ = self._make_collector()
+ collector.add_results(
+ [
+ {
+ "title": "A",
+ "link": "http://a.com/doc",
+ "source": "library",
+ "metadata": {"chunk_index": True, "doc_id": "doc123"},
+ }
+ ]
+ )
+ assert collector.results[0]["link"] == "http://a.com/doc"
+
+ def test_doc_id_integer_coerced(self):
+ """Integer doc_id (e.g. 123) is coerced to string and properly formatted."""
+ collector, _ = self._make_collector()
+ collector.add_results(
+ [
+ {
+ "title": "A",
+ "link": "http://a.com/doc",
+ "source": "library",
+ "metadata": {"chunk_index": 2, "doc_id": 123},
+ }
+ ]
+ )
+ assert (
+ collector.results[0]["link"]
+ == "/library/document/123/chunks#chunk-2"
+ )
+
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()
@@ -216,6 +496,15 @@ class TestSearchResultsCollector:
assert len(all_links) == 1
assert collector.sources == ["https://example.com/shared"]
+ def test_find_by_url_fallback_scans_past_unindexed_entries(self):
+ """find_by_url fallback scan continues past unindexed matching entries."""
+ all_links = [
+ {"link": "http://a.com"}, # missing "index"
+ {"link": "http://a.com", "index": "2"},
+ ]
+ collector, _ = self._make_collector(all_links)
+ assert collector.find_by_url("http://a.com") == 2
+
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
@@ -261,6 +550,339 @@ class TestSearchResultsCollector:
assert result is not None
assert result["link"] == "http://a.com"
+ def test_find_or_add_result_updates_dedup_maps_and_prevents_add_results_duplicates(
+ self,
+ ):
+ """Registering a URL via find_or_add_result (fetch path) updates
+ _url_to_index and _index_to_result so a subsequent add_results call
+ (search path) reuses the citation index without duplicating _all_links.
+ """
+ collector, all_links = self._make_collector()
+ index = collector.find_or_add_result(
+ {
+ "title": "Fetch first",
+ "link": "http://fetch.com",
+ "snippet": "f",
+ },
+ engine_name="fetch",
+ )
+ assert index == 1
+ assert collector._url_to_index.get("http://fetch.com") == "1"
+ assert collector._index_to_result.get("1")["link"] == "http://fetch.com"
+
+ # Subsequent search returns the same URL
+ start, indexed = collector.add_results(
+ [
+ {
+ "title": "Search second",
+ "link": "http://fetch.com",
+ "snippet": "s",
+ }
+ ],
+ engine_name="web",
+ )
+ assert len(all_links) == 1
+ assert indexed[0]["index"] == "1"
+ assert collector.find_by_url("http://fetch.com") == 1
+ assert collector.find_by_index(1)["title"] == "Fetch first"
+
+ def test_add_results_rejects_malicious_doc_id_path_traversal(self):
+ """Malicious doc_id containing path traversal (e.g. ../../etc/passwd)
+ is rejected — and the original link is left unchanged rather than
+ receiving an anchor against the wrong route."""
+ collector, all_links = self._make_collector()
+ collector.add_results(
+ [
+ {
+ "title": "Malicious Doc",
+ "link": "/library/document/doc1",
+ "source": "library",
+ "metadata": {
+ "doc_id": "../../etc/passwd",
+ "chunk_index": 0,
+ },
+ }
+ ]
+ )
+ # No sanitizable doc_id → link stays exactly as the producer
+ # supplied it, no ``#chunk-...`` fragment appended.
+ assert collector.results[0]["link"] == "/library/document/doc1"
+
+ def test_add_results_rejects_uuid_or_non_int_chunk_id(self):
+ """UUID string chunk_id is rejected and does not append #chunk-<uuid>."""
+ collector, _ = self._make_collector()
+ collector.add_results(
+ [
+ {
+ "title": "UUID chunk",
+ "link": "http://a.com/doc",
+ "source": "library",
+ "metadata": {
+ "chunk_id": "550e8400-e29b-41d4-a716-446655440000",
+ "doc_id": "doc123",
+ },
+ }
+ ]
+ )
+ assert collector.results[0]["link"] == "http://a.com/doc"
+
+ def test_add_results_idempotent_when_chunk_already_in_link(self):
+ """Link already containing a *validated* #chunk- marker is rebuilt
+ to the same canonical URL (idempotent under valid metadata)."""
+ collector, _ = self._make_collector()
+ collector.add_results(
+ [
+ {
+ "title": "Already chunked",
+ "link": "/library/document/doc1/chunks#chunk-0",
+ "source": "library",
+ "metadata": {"doc_id": "doc1", "chunk_index": 0},
+ }
+ ]
+ )
+ assert (
+ collector.results[0]["link"]
+ == "/library/document/doc1/chunks#chunk-0"
+ )
+
+ def test_add_results_strips_unvalidated_producer_chunk_fragment(self):
+ """A producer-supplied ``#chunk-<uuid>`` (or other malformed fragment)
+ with no valid metadata must be stripped — never trusted as-is."""
+ collector, _ = self._make_collector()
+ collector.add_results(
+ [
+ {
+ "title": "Bad producer fragment",
+ "link": (
+ "/library/document/doc1/chunks"
+ "#chunk-550e8400-e29b-41d4-a716-446655440000"
+ ),
+ "source": "library",
+ "metadata": {
+ "doc_id": "doc1",
+ "chunk_id": "550e8400-e29b-41d4-a716-446655440000",
+ },
+ }
+ ]
+ )
+ link = collector.results[0]["link"]
+ assert "#chunk-" not in link
+ assert link == "/library/document/doc1/chunks"
+
+ def test_constructor_skips_non_dict_seeded_entries(self):
+ """Non-dict legacy entries (``None``, bare strings) in ``all_links``
+ must not crash ``__init__``."""
+ all_links = [
+ None, # legacy malformed
+ "raw string", # legacy malformed
+ {"title": "OK", "link": "http://ok.com", "index": "1"},
+ 42, # legacy malformed
+ ]
+ # Should not raise.
+ collector, _ = self._make_collector(all_links)
+ assert "http://ok.com" in collector._url_to_index
+ assert collector._url_to_index["http://ok.com"] == "1"
+
+ def test_add_results_skips_non_dict_inputs(self):
+ """Non-dict entries in the input list are skipped silently (they
+ cannot carry an index anyway)."""
+ collector, _ = self._make_collector()
+ start, indexed = collector.add_results(
+ [
+ None,
+ "raw string",
+ {"title": "OK", "link": "http://ok.com", "snippet": "ok"},
+ 42,
+ ]
+ )
+ assert start == 0
+ assert len(indexed) == 1
+ assert indexed[0]["link"] == "http://ok.com"
+
+ def test_seed_collision_uses_max_plus_one(self):
+ """Appending to a pre-seeded list whose highest index is far above
+ ``len(_all_links)`` must allocate one past the max, never collide
+ with a sparse seeded index."""
+ all_links = [
+ {"title": "Sparse", "link": "http://sparse.com", "index": "42"},
+ {"title": "Sparse 2", "link": "http://sparse2.com", "index": "99"},
+ ]
+ collector, _ = self._make_collector(all_links)
+ _, indexed = collector.add_results(
+ [{"title": "Fresh", "link": "http://fresh.com", "snippet": "f"}]
+ )
+ # The sparse seed has max index 99; the fresh entry must NOT
+ # collide with 3 (``len+1``) or any other seeded index.
+ assert indexed[0]["index"] == "100"
+ # The seed entries are still resolvable via their own indices.
+ assert collector.find_by_index(42)["link"] == "http://sparse.com"
+ assert collector.find_by_index(99)["link"] == "http://sparse2.com"
+ assert collector.find_by_index(100)["link"] == "http://fresh.com"
+
+ def test_find_or_add_result_seed_collision_uses_max_plus_one(self):
+ """``find_or_add_result`` must use the same collision-free allocator
+ as ``add_results``."""
+ all_links = [
+ {"title": "Sparse", "link": "http://sparse.com", "index": "42"},
+ ]
+ collector, _ = self._make_collector(all_links)
+ index = collector.find_or_add_result(
+ {"title": "Fetch", "link": "http://fetch.com", "snippet": "f"},
+ engine_name="fetch",
+ )
+ assert index == 43
+ # The seeded index 42 is still resolvable.
+ assert collector.find_by_index(42)["link"] == "http://sparse.com"
+ assert collector.find_by_index(43)["link"] == "http://fetch.com"
+
+ def test_find_by_url_fallback_after_external_append(self):
+ """When a URL is appended to ``_all_links`` outside the collector
+ (legacy direct-append code paths), ``find_by_url`` must still
+ resolve it via the linear fallback."""
+ all_links = [
+ {"title": "External", "link": "http://external.com", "index": "5"},
+ ]
+ collector, _ = self._make_collector(all_links)
+ # Externally append WITHOUT going through add_results /
+ # find_or_add_result — the maps must not know about this URL.
+ collector._all_links.append(
+ {"title": "Also external", "link": "http://also.com", "index": "6"}
+ )
+ assert "http://external.com" in collector._url_to_index
+ assert "http://also.com" not in collector._url_to_index
+ # The fallback linear scan still resolves both.
+ assert collector.find_by_url("http://external.com") == 5
+ assert collector.find_by_url("http://also.com") == 6
+
+ def test_find_by_index_fallback_after_external_append(self):
+ """Linear fallback for ``find_by_index`` must work when an entry is
+ appended to ``_all_links`` outside the collector."""
+ all_links = [
+ {"title": "Seeded", "link": "http://seeded.com", "index": "5"},
+ ]
+ collector, _ = self._make_collector(all_links)
+ # Externally append — map should be unaware.
+ collector._all_links.append(
+ {"title": "Ghost", "link": "http://ghost.com", "index": "9"}
+ )
+ assert "9" not in collector._index_to_result
+ assert collector.find_by_index(5)["link"] == "http://seeded.com"
+ assert collector.find_by_index(9)["link"] == "http://ghost.com"
+
+ def test_find_by_url_continues_past_unindexed_collision(self):
+ """If a legacy entry with a matching link but no ``index`` precedes
+ a real indexed entry, ``find_by_url`` must continue scanning to
+ find the real index."""
+ all_links = [
+ {"title": "Ghost", "link": "http://a.com"}, # no index
+ {"title": "Real", "link": "http://a.com", "index": "11"},
+ ]
+ collector, _ = self._make_collector(all_links)
+ # The first matching entry has no index; the fallback must
+ # continue and return the real one (11), not ``None``.
+ assert collector.find_by_url("http://a.com") == 11
+
+ def test_add_results_negative_chunk_index_rejected(self):
+ """Negative chunk_index is not a valid anchor target — the link is
+ left unchanged."""
+ collector, _ = self._make_collector()
+ collector.add_results(
+ [
+ {
+ "title": "Neg",
+ "link": "/library/document/doc1",
+ "source": "library",
+ "metadata": {"doc_id": "doc1", "chunk_index": -1},
+ }
+ ]
+ )
+ assert collector.results[0]["link"] == "/library/document/doc1"
+
+ def test_add_results_missing_doc_id_leaves_link_unchanged(self):
+ """chunk_index present but no sanitisable doc_id (metadata empty,
+ top-level empty) leaves the link unchanged — must NOT append a
+ ``#chunk-...`` fragment to whatever the producer happened to set
+ the link to."""
+ collector, _ = self._make_collector()
+ collector.add_results(
+ [
+ {
+ "title": "No doc id",
+ "link": "/some/other/route",
+ "source": "library",
+ "metadata": {"chunk_index": 5}, # no doc_id/source_id
+ }
+ ]
+ )
+ # Link unchanged — no fragment appended to a non-library route.
+ assert collector.results[0]["link"] == "/some/other/route"
+
+
+class TestSearchToolMakers:
+ """Direct tests for _make_web_search_tool and _make_specialized_search_tool."""
+
+ def test_make_web_search_tool_executes_and_unpacks_add_results(self):
+ from unittest.mock import MagicMock, patch
+ from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (
+ SearchResultsCollector,
+ _make_web_search_tool,
+ )
+
+ mock_engine = MagicMock()
+ mock_engine.run.return_value = [
+ {"title": "Result 1", "link": "http://a.com", "snippet": "s1"}
+ ]
+
+ collector = SearchResultsCollector()
+ with patch(
+ "local_deep_research.web_search_engines.search_engine_factory.create_search_engine",
+ return_value=mock_engine,
+ ):
+ tool_fn = _make_web_search_tool(
+ search_engine_name="duckduckgo",
+ model=MagicMock(),
+ settings_snapshot={},
+ collector=collector,
+ )
+ result_str = tool_fn.invoke({"query": "test query"})
+
+ assert "[1] Result 1 (http://a.com)" in result_str
+ assert len(collector.results) == 1
+ assert collector.results[0]["index"] == "1"
+
+ def test_make_specialized_search_tool_executes_and_unpacks_add_results(
+ self,
+ ):
+ from unittest.mock import MagicMock, patch
+ from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (
+ SearchResultsCollector,
+ _make_specialized_search_tool,
+ )
+
+ mock_engine = MagicMock()
+ mock_engine.run.return_value = [
+ {"title": "Arxiv 1", "link": "http://arxiv.org/1", "snippet": "ax1"}
+ ]
+
+ collector = SearchResultsCollector()
+ with patch(
+ "local_deep_research.web_search_engines.search_engine_factory.create_search_engine",
+ return_value=mock_engine,
+ ):
+ tool_fn = _make_specialized_search_tool(
+ engine_name="arxiv",
+ description="Arxiv search",
+ model=MagicMock(),
+ settings_snapshot={},
+ collector=collector,
+ )
+ result_str = tool_fn.invoke({"query": "physics"})
+
+ assert "[1] Arxiv 1 (http://arxiv.org/1)" in result_str
+ assert len(collector.results) == 1
+ assert collector.results[0]["index"] == "1"
+ assert collector.results[0]["source_engine"] == "arxiv"
+
# ---------------------------------------------------------------------------
# Format results helper
@@ -304,6 +926,105 @@ class TestFormatResults:
assert _format_results([], 0) == "No results."
+ def test_format_results_honours_assigned_index_from_collector(self):
+ """Regression for the dedup integration: ``_format_results`` must
+ use the ``index`` the collector assigned, not fall through to the
+ ``start_idx + i + 1`` fallback. Otherwise deduped citations render
+ as dangling ``[N]`` markers the agent can't fetch.
+ """
+ from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (
+ SearchResultsCollector,
+ _format_results,
+ )
+
+ collector = SearchResultsCollector([])
+ collector.add_results(
+ [{"title": "A", "link": "http://a.com", "snippet": "a"}],
+ engine_name="test",
+ )
+ start, indexed = collector.add_results(
+ [
+ {
+ "title": "A again",
+ "link": "http://a.com",
+ "snippet": "a2",
+ },
+ {"title": "B", "link": "http://b.com", "snippet": "b"},
+ ],
+ engine_name="test",
+ )
+
+ output = _format_results(indexed, start)
+
+ # The duplicate collapses to [1]; only the new URL is [2].
+ assert "[1]" in output
+ assert "[2]" in output
+ assert "[3]" not in output # start + i + 1 fallback would emit this
+ # The dedup entry kept the original URL so the [1] in this batch
+ # is a real, fetchable link (not a dangling marker).
+ assert "(http://a.com)" in output
+ assert "(http://b.com)" in output
+
+ def test_format_results_missing_index_logs_warning(self):
+ """When a result dict lacks the 'index' key, _format_results falls back
+ to start_idx + i + 1 and logs a warning.
+ """
+ from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (
+ _format_results,
+ )
+ from loguru import logger
+
+ logs = []
+ handler_id = logger.add(
+ lambda msg: logs.append(str(msg)), level="WARNING", diagnose=False
+ )
+ logger.enable("local_deep_research")
+ try:
+ results = [{"title": "No Index", "link": "http://no-index.com"}]
+ output = _format_results(results, start_idx=0)
+ assert "[1]" in output
+ assert any("result missing 'index' key" in log for log in logs)
+ finally:
+ logger.remove(handler_id)
+
+ def test_format_results_warning_redacts_url(self):
+ """The fallback warning must route the URL through
+ ``redact_url_for_log`` so the path / query / fragment never appear
+ raw."""
+ from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (
+ _format_results,
+ )
+ from loguru import logger
+
+ logs = []
+ # Use the default sink interface (``message`` is a string after
+ # the format string is applied) — matches the existing
+ # ``test_format_results_missing_index_logs_warning`` style.
+ handler_id = logger.add(
+ lambda msg: logs.append(str(msg)), level="WARNING", diagnose=False
+ )
+ logger.enable("local_deep_research")
+ try:
+ # URL carries sensitive path/query that must not appear raw.
+ results = [
+ {
+ "title": "Token Leak Risk",
+ "link": "https://api.example.com/secret?token=abc123",
+ }
+ ]
+ _format_results(results, start_idx=0)
+ warning_lines = [line for line in logs if "result missing" in line]
+ assert warning_lines, "expected a fallback warning"
+ for line in warning_lines:
+ assert "token=abc123" not in line, (
+ f"raw query leaked into warning: {line!r}"
+ )
+ assert "/secret" not in line, (
+ f"raw path leaked into warning: {line!r}"
+ )
+ finally:
+ logger.remove(handler_id)
+
# ---------------------------------------------------------------------------
# Strategy instantiation and configuration
diff --git a/tests/utilities/test_chunk_anchor.py b/tests/utilities/test_chunk_anchor.py
new file mode 100644
index 0000000000..6a6c017715
--- /dev/null
+++ b/tests/utilities/test_chunk_anchor.py
@@ -0,0 +1,327 @@
+"""Tests for the centralised chunk-anchor helpers.
+
+These tests exercise the single source of truth that the LangGraph
+result collector and the RAG producer search engines all share for
+deciding whether a ``chunk_index`` / ``chunk_id`` metadata value is a
+safe anchor target. They pin the contract so a producer cannot
+interpolate a malformed value into a citation and the collector cannot
+skip validation whenever ``#chunk-`` is already present in the URL.
+"""
+
+import pytest
+
+from local_deep_research.utilities.chunk_anchor import (
+ build_chunk_anchor_url,
+ extract_chunk_index,
+ extract_document_id,
+ is_library_chunk_result,
+)
+
+
+class TestExtractChunkIndex:
+ """``extract_chunk_index`` must reject any value that cannot be safely
+ interpolated into a ``#chunk-<n>`` URL fragment."""
+
+ @pytest.mark.parametrize(
+ "raw,expected",
+ [
+ (0, 0),
+ (1, 1),
+ (42, 42),
+ (999, 999),
+ ],
+ )
+ def test_accepts_non_negative_int(self, raw, expected):
+ assert extract_chunk_index({"chunk_index": raw}) == expected
+
+ @pytest.mark.parametrize(
+ "raw",
+ [True, False],
+ )
+ def test_rejects_bool_even_though_bool_subclasses_int(self, raw):
+ # True / False are technically ``int`` in Python but never valid
+ # chunk indices — previously slipped through as ``#chunk-True``.
+ assert extract_chunk_index({"chunk_index": raw}) is None
+
+ @pytest.mark.parametrize(
+ "raw",
+ [-1, -42],
+ )
+ def test_rejects_negative_int(self, raw):
+ assert extract_chunk_index({"chunk_index": raw}) is None
+
+ @pytest.mark.parametrize(
+ "raw,expected",
+ [
+ ("0", 0),
+ ("1", 1),
+ ("42", 42),
+ ],
+ )
+ def test_accepts_int_like_string(self, raw, expected):
+ assert extract_chunk_index({"chunk_id": raw}) == expected
+
+ @pytest.mark.parametrize(
+ "raw",
+ [
+ "550e8400-e29b-41d4-a716-446655440000", # UUID
+ "abc", # non-numeric
+ "1.5", # not int-like
+ " ", # whitespace-only
+ "1abc", # mixed
+ ],
+ )
+ def test_rejects_non_int_like_string(self, raw):
+ assert extract_chunk_index({"chunk_id": raw}) is None
+
+ def test_chunk_index_takes_precedence_over_chunk_id(self):
+ # chunk_index wins when both are present; chunk_id is ignored.
+ assert extract_chunk_index({"chunk_index": 5, "chunk_id": "999"}) == 5
+
+ def test_falls_back_to_chunk_id_when_chunk_index_absent(self):
+ assert extract_chunk_index({"chunk_id": 7}) == 7
+
+ def test_returns_none_when_neither_key_present(self):
+ assert extract_chunk_index({}) is None
+ assert extract_chunk_index({"other": 1}) is None
+
+ def test_returns_none_for_non_mapping_metadata(self):
+ assert extract_chunk_index(None) is None
+ assert extract_chunk_index("not a mapping") is None
+ assert extract_chunk_index([1, 2, 3]) is None
+
+ def test_float_with_integer_value_accepted(self):
+ assert extract_chunk_index({"chunk_index": 5.0}) == 5
+
+ def test_float_with_fractional_value_rejected(self):
+ assert extract_chunk_index({"chunk_index": 5.5}) is None
+
+ def test_negative_float_rejected(self):
+ assert extract_chunk_index({"chunk_index": -5.0}) is None
+
+ def test_none_chunk_index_falls_back_to_chunk_id(self):
+ # ``chunk_index: None`` should NOT shadow ``chunk_id``.
+ assert extract_chunk_index({"chunk_index": None, "chunk_id": 7}) == 7
+
+ @pytest.mark.parametrize("value", [{}, [], object(), set()])
+ def test_rejects_arbitrary_non_numeric_types(self, value):
+ assert extract_chunk_index({"chunk_index": value}) is None
+
+
+class TestExtractDocumentId:
+ """``extract_document_id`` must sanitise for safe URL interpolation."""
+
+ @pytest.mark.parametrize(
+ "metadata,expected",
+ [
+ ({"doc_id": "doc1"}, "doc1"),
+ ({"source_id": "doc1"}, "doc1"),
+ ({"document_id": "doc1"}, "doc1"),
+ ({"doc_id": "abc-123_xyz"}, "abc-123_xyz"), # UUID-like
+ ({"doc_id": 123}, "123"), # int coerced to str
+ ],
+ )
+ def test_accepts_valid_ids(self, metadata, expected):
+ assert extract_document_id(metadata) == expected
+
+ def test_doc_id_takes_precedence(self):
+ # doc_id is the legacy key, checked first.
+ assert (
+ extract_document_id({"doc_id": "first", "source_id": "second"})
+ == "first"
+ )
+
+ def test_top_level_fallback(self):
+ # When metadata doesn't carry the id, check the top-level result.
+ top = {"source_id": "top-level"}
+ assert extract_document_id({}, top) == "top-level"
+
+ def test_top_level_document_id_fallback(self):
+ top = {"document_id": "top-doc-id"}
+ assert extract_document_id({}, top) == "top-doc-id"
+
+ def test_top_level_doc_id_fallback(self):
+ top = {"doc_id": "top-doc-id"}
+ assert extract_document_id({}, top) == "top-doc-id"
+
+ @pytest.mark.parametrize(
+ "bad_id",
+ [
+ "../../etc/passwd",
+ "/etc/passwd",
+ "doc with space",
+ "doc\nnewline",
+ "doc;injected",
+ ],
+ )
+ def test_rejects_unsafe_strings(self, bad_id):
+ # Path traversal / control chars must NOT make it through.
+ assert extract_document_id({"doc_id": bad_id}) is None
+
+ def test_returns_none_when_no_candidates(self):
+ assert extract_document_id({}) is None
+
+ def test_returns_none_for_empty_string(self):
+ assert extract_document_id({"doc_id": ""}) is None
+ assert extract_document_id({"doc_id": " "}) is None # strip → empty
+
+ def test_none_metadata_returns_none(self):
+ assert extract_document_id(None) is None
+
+ def test_bool_rejected(self):
+ # bool subclasses int but is never a valid doc id.
+ assert extract_document_id({"doc_id": True}) is None
+
+ def test_metadata_with_non_mapping_top_level_safe(self):
+ # The top-level fallback is type-checked — non-mapping values
+ # don't crash and don't leak raw content into the doc id.
+ assert extract_document_id({}, "raw string", None, 42) is None
+
+
+class TestIsLibraryChunkResult:
+ """``is_library_chunk_result`` must agree with the collector's
+ eligibility check for chunk URL rewriting."""
+
+ def test_source_library_true(self):
+ assert is_library_chunk_result({"source": "library"}) is True
+
+ def test_source_type_library_true(self):
+ assert is_library_chunk_result({"source_type": "library"}) is True
+
+ def test_link_to_library_document_true(self):
+ assert (
+ is_library_chunk_result(
+ {"link": "/library/document/doc1/chunks#chunk-5"}
+ )
+ is True
+ )
+
+ def test_unrelated_result_false(self):
+ assert is_library_chunk_result({"link": "http://example.com"}) is False
+ assert is_library_chunk_result({}) is False
+
+ def test_non_mapping_returns_false(self):
+ assert is_library_chunk_result(None) is False
+ assert is_library_chunk_result("string") is False
+ assert is_library_chunk_result([1, 2]) is False
+
+
+class TestBuildChunkAnchorUrl:
+ """``build_chunk_anchor_url`` must return ``None`` rather than
+ mutate the input when its arguments aren't safe."""
+
+ def test_valid_inputs_produce_url(self):
+ assert (
+ build_chunk_anchor_url("http://x.com", "doc1", 5)
+ == "/library/document/doc1/chunks#chunk-5"
+ )
+
+ def test_missing_doc_id_returns_none(self):
+ # Missing doc_id → ``None``, caller leaves link unchanged.
+ assert build_chunk_anchor_url("http://x.com", None, 5) is None
+
+ def test_missing_chunk_index_returns_none(self):
+ assert build_chunk_anchor_url("http://x.com", "doc1", None) is None
+
+ @pytest.mark.parametrize("bad_chunk", [-1, True, False, "1.5", "uuid"])
+ def test_invalid_chunk_index_returns_none(self, bad_chunk):
+ assert build_chunk_anchor_url("http://x.com", "doc1", bad_chunk) is None
+
+ def test_zero_chunk_index_accepted(self):
+ # 0 is a valid 0-indexed chunk anchor.
+ assert (
+ build_chunk_anchor_url("http://x.com", "doc1", 0)
+ == "/library/document/doc1/chunks#chunk-0"
+ )
+
+
+class TestProducerCollectorTemplateContract:
+ """Shared CI contract test for the producer→collector→template path.
+
+ A single assertion sweep that covers malformed-chunk, missing-doc-id,
+ and wrong-route cases. If a producer ships a malformed chunk anchor,
+ the collector must NOT propagate it into the citation that the
+ template will render.
+ """
+
+ @pytest.fixture
+ def collector(self):
+ from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (
+ SearchResultsCollector,
+ )
+
+ return SearchResultsCollector([])
+
+ @pytest.mark.parametrize(
+ "metadata",
+ [
+ # UUID chunk_id → must not produce #chunk-<uuid>
+ {
+ "chunk_id": "550e8400-e29b-41d4-a716-446655440000",
+ "doc_id": "doc1",
+ },
+ # Boolean chunk_index → must not produce #chunk-True
+ {"chunk_index": True, "doc_id": "doc1"},
+ # Negative chunk_index → must not produce #chunk--1
+ {"chunk_index": -1, "doc_id": "doc1"},
+ # String chunk_index that isn't pure digits
+ {"chunk_index": "abc", "doc_id": "doc1"},
+ # Missing doc_id but valid chunk_index
+ {"chunk_index": 5},
+ ],
+ )
+ def test_malformed_inputs_do_not_produce_fragment(
+ self, collector, metadata
+ ):
+ """For every malformed input the URL fragment must NOT appear in
+ the citation — the collector must defend against a producer
+ interpolating a bad value verbatim."""
+ result = {
+ "title": "Doc",
+ "link": "/library/document/doc1",
+ "source": "library",
+ "metadata": metadata,
+ }
+ collector.add_results([result])
+ link = collector.results[0]["link"]
+ assert "#chunk-" not in link, (
+ f"malformed chunk anchor leaked into citation: {link!r}"
+ )
+
+ def test_valid_inputs_round_trip_to_template_anchor(self, collector):
+ """Valid inputs must produce the exact anchor id the template
+ renders, so a citation click scrolls to a real chunk."""
+ collector.add_results(
+ [
+ {
+ "title": "Doc",
+ "link": "/library/document/doc1",
+ "source": "library",
+ "metadata": {"chunk_index": 5, "doc_id": "doc1"},
+ }
+ ]
+ )
+ link = collector.results[0]["link"]
+ assert link == "/library/document/doc1/chunks#chunk-5"
+ # The fragment is exactly what document_chunks.html renders as
+ # ``id="chunk-{{ chunk.index }}"`` for the matching chunk row.
+ assert link.endswith("#chunk-5")
+
+ def test_producer_prebuilt_malformed_fragment_is_stripped(self, collector):
+ """Even when the producer already interpolated a bad fragment into
+ the URL, the collector must strip it rather than trust it."""
+ collector.add_results(
+ [
+ {
+ "title": "Doc",
+ "link": "/library/document/doc1/chunks#chunk-True",
+ "source": "library",
+ # Metadata has no usable chunk_index — only the
+ # prebuilt fragment. The collector must strip it.
+ "metadata": {"doc_id": "doc1"},
+ }
+ ]
+ )
+ link = collector.results[0]["link"]
+ assert "#chunk-" not in link
+ assert link == "/library/document/doc1/chunks"
diff --git a/tests/web_search_engines/engines/test_search_engine_collection.py b/tests/web_search_engines/engines/test_search_engine_collection.py
index 4234170427..385c8e5b97 100644
--- a/tests/web_search_engines/engines/test_search_engine_collection.py
+++ b/tests/web_search_engines/engines/test_search_engine_collection.py
@@ -544,6 +544,67 @@ class TestGetDocumentUrl:
assert url == "#"
+ def test_get_document_url_with_valid_chunk_index(self):
+ """Valid non-negative chunk_index produces a chunk-targeted URL."""
+ from local_deep_research.web_search_engines.engines.search_engine_collection import (
+ CollectionSearchEngine,
+ )
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_library.get_setting_from_snapshot",
+ return_value=None,
+ ):
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_library.get_server_url",
+ return_value="http://localhost:5000",
+ ):
+ with patch.object(
+ CollectionSearchEngine,
+ "_load_collection_embedding_settings",
+ ):
+ engine = CollectionSearchEngine(
+ collection_id="abc123",
+ collection_name="Test Collection",
+ )
+ url = engine._get_document_url("doc123", chunk_index=5)
+ assert url == "/library/document/doc123/chunks#chunk-5"
+
+ def test_get_document_url_rejects_malformed_chunk_index(self):
+ """Boolean / negative / non-int chunk_index must not produce a fragment."""
+ from local_deep_research.web_search_engines.engines.search_engine_collection import (
+ CollectionSearchEngine,
+ )
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_library.get_setting_from_snapshot",
+ return_value=None,
+ ):
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_library.get_server_url",
+ return_value="http://localhost:5000",
+ ):
+ with patch.object(
+ CollectionSearchEngine,
+ "_load_collection_embedding_settings",
+ ):
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_collection.get_user_db_session"
+ ) as mock_session:
+ mock_session.return_value.__enter__.return_value.query.return_value.filter_by.return_value.first.return_value = None
+ engine = CollectionSearchEngine(
+ collection_id="abc123",
+ collection_name="Test Collection",
+ settings_snapshot={"_username": "testuser"},
+ )
+ for bad in (True, False, -1, "uuid", 1.5):
+ url = engine._get_document_url(
+ "doc123", chunk_index=bad
+ )
+ assert "#chunk-" not in url, (
+ f"malformed chunk_index={bad!r} leaked: {url}"
+ )
+ assert url == "/library/document/doc123"
+
def test_get_document_url_default(self):
"""Get document URL returns default library URL."""
from local_deep_research.web_search_engines.engines.search_engine_collection import (
@@ -594,29 +655,28 @@ class TestGetDocumentUrl:
return_value="http://localhost:5000",
):
with patch(
- "local_deep_research.web_search_engines.engines.search_engine_collection.get_user_db_session"
+ "local_deep_research.web_search_engines.engines.search_engine_library.get_user_db_session"
) as mock_session:
# First call during init returns None for RAG index
# Subsequent calls for document lookup return the document
mock_query = Mock()
- mock_query.filter_by.return_value.first.side_effect = [
- None, # RAG index query
- mock_document, # Document query
- ]
+ mock_query.filter_by.return_value.first.return_value = (
+ mock_document
+ )
mock_session.return_value.__enter__.return_value.query.return_value = mock_query
with patch(
- "local_deep_research.web_search_engines.engines.search_engine_collection.get_setting_from_snapshot",
+ "local_deep_research.web_search_engines.engines.search_engine_library.get_setting_from_snapshot",
return_value="/path/to/library",
):
with patch(
- "local_deep_research.web_search_engines.engines.search_engine_collection.get_library_directory",
+ "local_deep_research.web_search_engines.engines.search_engine_library.get_library_directory",
return_value="/default/library",
):
with patch(
- "local_deep_research.web_search_engines.engines.search_engine_collection.PDFStorageManager"
+ "local_deep_research.web_search_engines.engines.search_engine_library.PDFStorageManager"
) as mock_pdf_manager:
- mock_pdf_manager.return_value.has_pdf.return_value = True
+ mock_pdf_manager.pdf_exists.return_value = True
engine = CollectionSearchEngine(
collection_id="abc123",
@@ -644,13 +704,13 @@ class TestGetDocumentUrl:
return_value="http://localhost:5000",
):
with patch(
- "local_deep_research.web_search_engines.engines.search_engine_collection.get_user_db_session",
+ "local_deep_research.web_search_engines.engines.search_engine_library.get_user_db_session",
side_effect=Exception(
"DB lookup failure: Bearer secret-token-12345"
),
):
with patch(
- "local_deep_research.web_search_engines.engines.search_engine_collection.logger"
+ "local_deep_research.web_search_engines.engines.search_engine_library.logger"
) as mock_logger:
engine = CollectionSearchEngine(
collection_id="abc123",