~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(library): render distinct chunk citation lines in bibliography without inflating source counts (#6149)
S7bdc3e307be8
diff --git a/changelog.d/+distinct-chunk-citation-lines.bugfix.md b/changelog.d/+distinct-chunk-citation-lines.bugfix.mdnew file mode 100644index 0000000000..3db11878e5--- /dev/null+++ b/changelog.d/+distinct-chunk-citation-lines.bugfix.md@@ -0,0 +1 @@+Distinct cited chunks of a library document now render separate bibliography lines in `## Sources` each linking to its respective chunk anchor (completing #5894 so N cited passages produce N lines linking to their own passage rather than mis-linking to chunk 0), while document-level source counting and parser compatibility are preserved.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.pyindex 3810cba126..ea684f2581 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@@ -124,15 +124,14 @@ def _scrub_tool_error(message: str) -> str:def _citation_dedup_key(link: Any) -> str:"""Canonical key a citation link is deduplicated on.- This MUST be the same key ``format_links_to_markdown`` groups the- rendered bibliography by, or the two disagree about how many sources- a report has. Since #5381 ``canonical_url_key`` collapses- ``/library/document/<id>``, its ``/pdf`` view and its- ``/chunks#chunk-<n>`` views onto one key — three views of one- document render as ONE ``## Sources`` line, so keying the collector- on the raw link handed back three entries, three citation indices and- a ``sources_count`` of 3 for a report that displays 1 (MCP's- ``sources`` payload and the news impact score both read that count).+ This matches the document-level key :func:`count_distinct_sources` counts+ sources by, and forms the first half of the ``(canon, display)`` grouping key+ used by ``format_links_to_markdown`` to render chunk-specific bibliography lines.+ ``canonical_url_key`` collapses ``/library/document/<id>``, its ``/pdf`` view,+ and its ``/chunks#chunk-<n>`` views onto one key — keeping document identity,+ MCP's ``sources`` payload, and news impact scoring stable (count of 1 for one+ document cited across multiple chunks), while the renderer displays each distinct+ chunk anchor on its own line.Returns ``""`` for anything that cannot be a dict/set key — anon-string ``link`` (an engine handing back a list) would otherwisediff --git a/src/local_deep_research/utilities/search_utilities.py b/src/local_deep_research/utilities/search_utilities.pyindex 35570320dd..6472af734b 100644--- a/src/local_deep_research/utilities/search_utilities.py+++ b/src/local_deep_research/utilities/search_utilities.py@@ -280,16 +280,13 @@ def _owned_chunk_display(recorded: object, canon: str) -> str | None:def source_url_field(link: Dict) -> object:"""The field a source's identity is read from: ``link`` first.- ``SearchResultsCollector`` keys every citation on- ``_citation_dedup_key(result["link"])``, and- :func:`_citation_dedup_key`'s docstring requires that key to be the- one this module groups the rendered bibliography by. While the- collector kept at most one entry per source the disagreement was- invisible — with a single entry there is nothing to group. Now that a- source can own several entries (one per distinct snippet), a result- carrying BOTH fields with different values would land in a render- group of its own and give one source two ``## Sources`` lines under- different numbers.+ ``SearchResultsCollector`` keys citations on+ ``_citation_dedup_key(result["link"])``, and records the authoritative+ chunk anchor or normalized URL in ``link``. A result carrying BOTH+ fields with divergent values (e.g. ``link`` carrying the collector's+ rebuilt anchor while ``url`` retains an anchor-less engine string) must+ consistently read ``link`` so the entry groups under its intended chunk+ anchor rather than fanning out into an unintended second group.``link`` wins because it is what the collector keys on, what``_format_results`` shows the agent next to the ``[N]`` marker, and@@ -302,19 +299,19 @@ def source_url_field(link: Dict) -> object:def count_distinct_sources(all_links: List[Dict]) -> int:- """How many sources :func:`format_links_to_markdown` will render.+ """How many distinct sources a report cites (document-level count).``len(all_links_of_system)`` counts OCCURRENCES, not sources: theLangGraph collector stores one entry per ``(url, snippet)`` pair, and``source_based`` / ``focused_iteration`` / ``topic_organization``extend the list with raw engine dicts and no URL dedup at all. Bothshapes put one source in the list several times, so every "N sources"- number must group the way the bibliography does rather than take a- length.+ number must group at the document level rather than take a length.- Grouped with the same expression and the same canonical key the- renderer uses, so the count and the number of rendered lines cannot- drift.+ Counts by canonical URL key, so distinct library documents are counted+ once regardless of how many distinct chunks or views are cited.+ The relation across reporting layers is:+ distinct sources <= bibliography lines <= citation indices."""seen: set[str] = set()for link in all_links or []:@@ -340,21 +337,22 @@ def format_links_to_markdown(all_links: List[Dict]) -> str:# section stays clean — no utm_*/fbclid clutter, no embedded# credentials, no scheme/host casing noise. Click-through is# unaffected (tracking params carry no content).- url_to_indices: dict[str, list] = {}- canon_to_title: dict[str, str] = {}- canon_to_quality: dict[str, int] = {}- # Track the RAG/library collection name per canonical URL so the- # citation formatter's source-tagged mode can surface it as the- # citation tag (e.g. `[mypapers-7]`) instead of falling back to- # the generic `local` label.- canon_to_collection: dict[str, str] = {}- # Library routes key per-document (so a document's /pdf and- # /chunks#chunk-N views share one entry) but must DISPLAY the first- # URL seen, anchor included — the canonical key drops #chunk-<n>,- # and that anchor is what makes a citation scroll to the cited- # chunk. Non-library sources keep displaying the canonical form so- # utm_*/fbclid clutter and credentials stay out of the report.- canon_to_display: dict[str, str] = {}+ # Group links by (canonical URL, chunk display URL).+ # Canonical key remains per-document so count_distinct_sources,+ # MCP sources, and news metrics do not inflate, while grouping on+ # chunk anchor ensures distinct cited chunks (/chunks#chunk-N) each+ # render their own Sources entry with their own anchor. Unanchored+ # views of the same document (e.g. /pdf and base route) merge together;+ # an unanchored /pdf view deliberately renders on its own line when+ # cited alongside chunks (reversing #5685's collapse so anchorless+ # indices honestly link to /pdf rather than mis-pointing at an arbitrary chunk).+ # Non-library sources display their canonical URL, so tracking params+ # and credentials stay out of the report.+ url_to_indices: dict[tuple[str, str], list] = {}+ group_to_title: dict[tuple[str, str], str] = {}+ group_to_quality: dict[tuple[str, str], int] = {}+ group_to_collection: dict[tuple[str, str], str] = {}+ group_to_display: dict[tuple[str, str], str] = {}for link in all_links:raw = source_url_field(link)# Skipped, not coerced. These dicts reach here straight from@@ -370,76 +368,55 @@ def format_links_to_markdown(all_links: List[Dict]) -> str:canon = canonical_url_key(raw)if not canon:continue- # An anchored spelling recorded by the collector wins: after- # canonical-key dedup only one entry per document survives, so- # the anchor may live on that entry rather than in its ``url``.- # Validate the recorded anchor rather than trusting it. It is- # preferred over the entry's own url, so an unvalidated read- # would let whatever set the key choose the rendered AND the- # persisted URL — and the key rides in a dict built with- # ``dict(raw)`` from engine output, so "only the collector- # writes it" is a coincidence, not a control.- # The entry's OWN anchored spelling wins, ahead of anything- # recorded alongside it. ``_prefer_anchored_link`` refuses to- # record over a collector-built anchor for exactly this reason- # — a different chunk of the same document points the reader at- # text the snippet did not come from — and the reader has to- # apply the same rule or the two disagree. The recorded key- # only fills the gap where the entry has no anchor of its own.- display = (- preferred_chunk_display(raw)- or _owned_chunk_display(link.get(CHUNK_DISPLAY_KEY), canon)- or library_display_url(raw)+ chunk_disp = preferred_chunk_display(raw) or _owned_chunk_display(+ link.get(CHUNK_DISPLAY_KEY), canon)- if display:- # Prefer a URL that carries a #chunk-<n> anchor over one- # that doesn't. Views of a document key together, so- # first-seen alone would show `/library/document/<id>/pdf`- # — losing the anchor — whenever a chunk-less hit happened- # to be registered first.- #- # The test is for ``#chunk-`` specifically, not for any- # ``#``: an empty fragment (``/library/document/9#``) or an- # unrelated one (``#section-intro``) would otherwise count- # as "anchored", win the preference, and permanently lock- # out the real chunk anchor that arrives later.- current = canon_to_display.get(canon)- if current is None or (- "#chunk-" not in current and "#chunk-" in display- ):- canon_to_display[canon] = display- url_to_indices.setdefault(canon, []).append(link.get("index", ""))- canon_to_title.setdefault(canon, link.get("title", "Untitled"))- # Track journal quality per canonical URL (first non-None wins)- if canon not in canon_to_quality and link.get("journal_quality"):- canon_to_quality[canon] = link["journal_quality"]+ if chunk_disp:+ key = (canon, chunk_disp)+ disp = chunk_disp+ else:+ key = (canon, "")+ disp = library_display_url(raw) or canon++ url_to_indices.setdefault(key, []).append(link.get("index", ""))+ group_to_title.setdefault(key, link.get("title", "Untitled"))+ # Prefer /pdf over bare /library/document/<id> for unanchored display+ curr_disp = group_to_display.get(key)+ if curr_disp is None or (+ curr_disp.endswith(canon) and "/pdf" in disp+ ):+ group_to_display[key] = disp++ # Track journal quality per group (first non-None wins)+ if key not in group_to_quality and link.get("journal_quality"):+ group_to_quality[key] = link["journal_quality"]# First non-empty collection name wins (mirrors title/quality).- if canon not in canon_to_collection:+ # Note: per-group collection tracking is display-only today and+ # anticipates #5722 encoding collection identity into chunk anchors.+ if key not in group_to_collection:metadata = link.get("metadata") or {}if not isinstance(metadata, dict):metadata = {}collection = metadata.get("collection_name")if collection:- canon_to_collection[canon] = str(collection)+ group_to_collection[key] = str(collection)# Emit each unique source once, in first-seen order.- seen: set[str] = set()+ seen: set[tuple[str, str]] = set()for link in all_links:raw = source_url_field(link)- # Skipped, not coerced. These dicts reach here straight from- # engine output on the non-LangGraph strategies, and- # canonical_url_key raises on a non-str. Stringifying instead- # renders a Python repr as a clickable URL and can merge two- # distinct sources onto one citation — and it would disagree- # with ``_citation_dedup_key``, which refuses a non-str link- # outright and whose docstring requires the two to group- # identically.if not isinstance(raw, str):continuecanon = canonical_url_key(raw)- if not canon or canon in seen:+ if not canon:+ continue+ chunk_disp = preferred_chunk_display(raw) or _owned_chunk_display(+ link.get(CHUNK_DISPLAY_KEY), canon+ )+ key = (canon, chunk_disp) if chunk_disp else (canon, "")+ if key in seen:continue- title = canon_to_title[canon]+ title = group_to_title[key]# Coerced for the same reason the url is skipped: it comes# from the same engine dict, and ``.replace`` below raises on# a non-str, taking the whole Sources block with it.@@ -453,7 +430,7 @@ def format_links_to_markdown(all_links: List[Dict]) -> str:# _build_sources_markdown's fallback). Coerce so dedup collapses# 1 and "1", and sorted() doesn't TypeError on mixed types.indices = sorted(- {str(i) for i in url_to_indices[canon]},+ {str(i) for i in url_to_indices[key]},# ``isdigit()`` is True for non-ASCII digit characters that# ``int()`` rejects — e.g. the superscript "\u00b9" — so it# alone would raise ValueError here and crash the whole@@ -477,8 +454,8 @@ def format_links_to_markdown(all_links: List[Dict]) -> str:# that ``repr()`` without sanitising here instead.indices = [_sanitize_sources_field(i) for i in indices]indices_str = f"[{', '.join(indices)}]"- quality_tag = _format_quality_tag(canon_to_quality.get(canon))- collection = canon_to_collection.get(canon, "")+ quality_tag = _format_quality_tag(group_to_quality.get(key))+ collection = group_to_collection.get(key, "")if collection:collection = _sanitize_sources_field(collection.replace(LDR_APPENDED_SOURCES_SENTINEL, "")@@ -486,14 +463,15 @@ def format_links_to_markdown(all_links: List[Dict]) -> str:collection_line = (f" Collection: {collection}\n" if collection else "")+ display = group_to_display[key]parts.append(f"{indices_str} {title}{quality_tag} "f"(source nr: {', '.join(map(str, indices))})\n"- f" URL: {_sanitize_sources_field(canon_to_display.get(canon, canon))}\n"+ f" URL: {_sanitize_sources_field(display)}\n"f"{collection_line}"f"\n")- seen.add(canon)+ seen.add(key)parts.append("\n")diff --git a/tests/strategies/test_langgraph_agent_strategy.py b/tests/strategies/test_langgraph_agent_strategy.pyindex eef2a068e0..52c51fdc9f 100644--- a/tests/strategies/test_langgraph_agent_strategy.py+++ b/tests/strategies/test_langgraph_agent_strategy.py@@ -5930,11 +5930,12 @@ class TestPairDedup:# One source for this subsection, not two.assert collector.sources == ["https://ex.test/p"]- def test_library_chunks_of_one_document_stay_one_source(self):- """Two chunks of one library document are two excerpts of ONE- source: two citations, one ## Sources line, each citation keeping- its own ``#chunk-<n>`` anchor so the reader lands on the text the- excerpt came from.+ def test_library_chunks_of_one_document_each_get_their_own_entry(self):+ """Two chunks of one library document are distinct cited chunk anchors:+ two citations, two ## Sources lines, each citation keeping its own+ ``#chunk-<n>`` anchor so the reader lands on the text the excerpt came from.+ ``count_distinct_sources`` remains per-document so "N sources" metrics+ do not inflate.A repeat of the SAME chunk with the same excerpt still collapses."""@@ -5964,11 +5965,15 @@ class TestPairDedup:assert len(all_links) == 2assert all_links[0]["link"].endswith("#chunk-0")assert all_links[1]["link"].endswith("#chunk-3")- # ...but one document, one bibliography line, both numbers on it.+ # Distinct sources count remains per-document:assert count_distinct_sources(all_links) == 1+ # But each distinct chunk anchor renders its own bibliography line:rendered = format_links_to_markdown(all_links)- assert rendered.count("URL:") == 1- assert "[1, 2]" in rendered+ assert rendered.count("URL:") == 2+ assert "[1] Doc" in rendered+ assert "[2] Doc" in rendered+ assert "#chunk-0" in rendered+ assert "#chunk-3" in rendereddef test_agent_facing_block_is_unchanged(self):"""``_format_results`` is not touched by this change: for a givendiff --git a/tests/utilities/test_search_utilities_formatting.py b/tests/utilities/test_search_utilities_formatting.pyindex 4b3356bd5d..3fa197a4f7 100644--- a/tests/utilities/test_search_utilities_formatting.py+++ b/tests/utilities/test_search_utilities_formatting.py@@ -875,21 +875,16 @@ class TestFormatLinksToMarkdownCollections:)-def test_format_links_collapses_library_chunk_anchors_to_one_entry():- """Regression for the #5381 follow-up: eight cited chunks of one library- document must render as ONE Sources line carrying all eight indices, not- eight near-identical lines. ``canonical_url_key`` only stripped fragments- from absolute URLs, so root-relative chunk anchors each became their own- group."""+def test_format_links_preserves_distinct_library_chunks_as_separate_entries():+ """Distinct cited chunks of a library document render as separate bibliography+ entries, each with its own citation index and chunk URL. Duplicate citations+ of the SAME chunk merge under that chunk's entry."""from local_deep_research.utilities.search_utilities import (format_links_to_markdown,)from local_deep_research.utilities.url_utils import canonical_url_keycanonical_url_key.cache_clear()- # Distinct per-chunk titles and a SECOND document: without both, the- # test would pass even if grouping were keyed on title rather than on- # the canonical URL, which is the thing actually under test.links = [{"title": f"My Paper (chunk {i})",@@ -898,6 +893,14 @@ def test_format_links_collapses_library_chunk_anchors_to_one_entry():}for i in range(8)]+ # Repeat citation of chunk 0+ links.append(+ {+ "title": "My Paper (chunk 0)",+ "url": "/library/document/doc1/chunks#chunk-0",+ "index": 10,+ }+ )links.append({"title": "Other Paper",@@ -908,23 +911,18 @@ def test_format_links_collapses_library_chunk_anchors_to_one_entry():out = format_links_to_markdown(links)- # doc1's eight chunks collapse to one entry carrying all eight indices,- # keyed by document despite the eight different titles.- assert "[1, 2, 3, 4, 5, 6, 7, 8]" in out- assert out.count("/library/document/doc1") == 1- # ...and the entry keeps a usable anchor: collapsing must not strip the- # #chunk-<n> that makes the citation scroll to the cited chunk.- assert "/library/document/doc1/chunks#chunk-0" in out- # doc2 is a genuinely different document and must NOT be merged into it.- assert "/library/document/doc2/chunks#chunk-0" in out+ # doc1's 8 distinct chunks each get their own entry; chunk 0 merges indices 1 and 10+ assert "[1, 10]" in out+ assert "[2]" in out+ assert "[8]" in outassert "[9]" in out+ assert out.count("/library/document/doc1/chunks#chunk-") == 8+ assert "/library/document/doc2/chunks#chunk-0" in out-def test_format_links_collapses_pdf_and_chunks_views_of_one_document():- """A document whose chunks have mixed metadata yields both a- ``/chunks#chunk-N`` and a ``/pdf`` citation URL (``_get_document_url``- falls back to ``/pdf`` when ``chunk_index`` is missing). Those are one- source and must not occupy two bibliography entries."""+def test_format_links_keeps_pdf_and_chunk_view_distinct_and_merges_same_chunk():+ """A document cited with a chunk anchor and an unanchored whole-document /pdf+ are distinct citation entries. Citations to the same chunk merge together."""from local_deep_research.utilities.search_utilities import (format_links_to_markdown,)@@ -943,37 +941,34 @@ def test_format_links_collapses_pdf_and_chunks_views_of_one_document():"url": "/library/document/doc1/pdf","index": 2,},+ {+ "title": "My Paper",+ "url": "/library/document/doc1/chunks#chunk-0",+ "index": 3,+ },])- assert "[1, 2]" in out- assert out.count("My Paper") == 1- # The merged entry must still carry the anchor, not degrade to the- # anchor-less /pdf view.+ assert "[1, 3]" in outassert "/library/document/doc1/chunks#chunk-0" in out+ assert "[2]" in out+ assert "/library/document/doc1/pdf" in outdef test_format_links_merges_absolute_library_alias_with_relative_route():- """A document cited once by the RAG engine (relative route) and once via- fetch_content on the absolute alias is ONE source. The fetch resolver- registers the agent's original alias string verbatim, so without alias- normalization this fans out into two entries and the alias one loses its- anchor."""+ """A chunk cited once by the RAG engine (relative route) and once via+ fetch_content on the absolute alias is ONE source and merges indices."""from local_deep_research.utilities.search_utilities import (format_links_to_markdown,)from local_deep_research.utilities.url_utils import canonical_url_keycanonical_url_key.cache_clear()- # The ANCHOR-LESS view is registered first on purpose. With the- # anchored relative hit first, the anchor-preference rule would supply- # the anchor regardless, and a broken alias path in- # ``library_display_url`` would go undetected.out = format_links_to_markdown([{"title": "My Paper",- "url": "/library/document/abc123/pdf",+ "url": "/library/document/abc123/chunks#chunk-7","index": 1,},{@@ -986,15 +981,13 @@ def test_format_links_merges_absolute_library_alias_with_relative_route():assert "[1, 2]" in outassert out.count("My Paper") == 1- # The anchor can only have come from the alias, via normalization.assert "/library/document/abc123/chunks#chunk-7" in outassert "https://library.document" not in out-def test_format_links_prefers_anchored_url_regardless_of_order():- """The anchor must survive even when a chunk-less view of the document- is registered FIRST — views key together, so plain first-seen ordering- would display `/pdf` and silently drop the scroll-to-chunk target."""+def test_format_links_merges_unanchored_views_and_keeps_chunks_distinct():+ """Unanchored views (/pdf and base) share one canonical key and merge,+ while anchored chunks remain distinct."""from local_deep_research.utilities.search_utilities import (format_links_to_markdown,)@@ -1010,18 +1003,24 @@ def test_format_links_prefers_anchored_url_regardless_of_order():},{"title": "My Paper",- "url": "/library/document/doc1/chunks#chunk-4",+ "url": "/library/document/doc1","index": 2,},+ {+ "title": "My Paper",+ "url": "/library/document/doc1/chunks#chunk-4",+ "index": 3,+ },])assert "[1, 2]" in out+ assert "[3]" in outassert "/library/document/doc1/chunks#chunk-4" in outdef test_format_links_survives_non_ascii_digit_index():- """``"²".isdigit()`` is True while ``int("²")`` raises, which took down+ """``\"²\".isdigit()`` is True while ``int(\"²\")`` raises, which took downthe whole bibliography. The repo's Hypothesis fuzzer only finds thisfrom a cached example database, so pin it deterministically."""from local_deep_research.utilities.search_utilities import (@@ -1040,7 +1039,7 @@ def test_format_links_survives_non_ascii_digit_index():def test_format_links_prefers_the_chunk_anchor_over_any_other_fragment():"""The display preference tested for ``"#" in display`` rather than``"#chunk-" in display``, so an empty or unrelated fragment counted as- "anchored", won, and permanently locked out the real chunk anchor."""+ \"anchored\", won, and permanently locked out the real chunk anchor."""from local_deep_research.utilities.search_utilities import (format_links_to_markdown,)@@ -1058,15 +1057,14 @@ def test_format_links_prefers_the_chunk_anchor_over_any_other_fragment():},])- assert "[1, 2]" in out, decoy+ assert "[1]" in out, decoy+ assert "[2]" in out, decoyassert "/library/document/9/chunks#chunk-4" in out, decoydef test_format_links_merges_lib_abbreviation_and_encoded_id():"""``/lib/document/<id>`` and ``/library/document/<id>`` are the same- document to the fetch resolver, and ``a%2Db`` resolves to ``a-b`` — so- citing one document three ways must not produce three entries (one of- which links to ``/lib/...``, not a registered route)."""+ document to the fetch resolver, and ``a%2Db`` resolves to ``a-b``."""from local_deep_research.utilities.search_utilities import (format_links_to_markdown,)@@ -1082,11 +1080,16 @@ def test_format_links_merges_lib_abbreviation_and_encoded_id():"url": "/library/document/a%2Db/chunks#chunk-2","index": 3,},+ {+ "title": "Doc",+ "url": "/lib/document/a-b/chunks#chunk-2",+ "index": 4,+ },])- assert "[1, 2, 3]" in out- assert out.count(" URL: ") == 1+ assert "[1, 2]" in out+ assert "[3, 4]" in outassert "/library/document/a-b/chunks#chunk-2" in outassert "/lib/document" not in out