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(rag): keep library citations tied to the indexed chunk (#7997)

creedc546ad0d6c20
diff --git a/changelog.d/7811.bugfix.md b/changelog.d/7811.bugfix.md
new file mode 100644
index 0000000000..611313a38b
--- /dev/null
+++ b/changelog.d/7811.bugfix.md
@@ -0,0 +1 @@
+Keep library search and fetch results tied to the exact indexed chunk, preventing stale text when multiple index versions share a chunk number.
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 4463e1f024..fb97112cd2 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
@@ -622,7 +622,10 @@ class SearchResultsCollector:
doc_id = extract_document_id(authoritative, metadata, r)
if chunk_idx is not None and doc_id:
rebuilt = build_chunk_anchor_url(
- link, doc_id, chunk_idx
+ link,
+ doc_id,
+ chunk_idx,
+ document_chunk_id=metadata.get("document_chunk_id"),
)
if rebuilt is not None:
link = rebuilt
diff --git a/src/local_deep_research/advanced_search_system/tools/fetch/library_resolver.py b/src/local_deep_research/advanced_search_system/tools/fetch/library_resolver.py
index 18e188f4ac..23eda8c96b 100644
--- a/src/local_deep_research/advanced_search_system/tools/fetch/library_resolver.py
+++ b/src/local_deep_research/advanced_search_system/tools/fetch/library_resolver.py
@@ -96,6 +96,7 @@ class _LibraryReference:
#: dead link. Callers re-emit the canonical route instead.
bracketed: bool = False
chunk_index: Optional[int] = None
+ document_chunk_id: Optional[int] = None
def _decode_segment(value: str) -> str | None:
@@ -142,26 +143,43 @@ def _parse_library_reference(url: str) -> _LibraryReference | None:
if not candidate:
return None
+ query = ""
+ has_query = "?" in candidate
if "://" in candidate:
parsed = urlsplit(candidate)
- # No ``parsed.fragment`` check: the fragment was stripped above, so
- # it can never reach here. A query still disqualifies — it can carry
- # server-meaningful state, unlike a client-side anchor.
- if (
- parsed.scheme != "https"
- or parsed.netloc != "library.document"
- or parsed.query
- ):
+ # The fragment was stripped above. Only the bounded chunk-row query
+ # parameter below is accepted; arbitrary server-side state is not.
+ if parsed.scheme != "https" or parsed.netloc != "library.document":
return None
+ query = parsed.query
candidate = f"/library/document{parsed.path}"
+ elif "?" in candidate:
+ candidate, query = candidate.split("?", 1)
+
+ document_chunk_id = None
+ if has_query:
+ match = re.fullmatch(r"document_chunk_id=([1-9][0-9]{0,18})", query)
+ if match is None or chunk_index is None:
+ return None
+ document_chunk_id = int(match.group(1))
+ if document_chunk_id > (1 << 63) - 1:
+ return None
path_match = _LIBRARY_PATH_RE.match(candidate)
if path_match:
+ if (
+ document_chunk_id is not None
+ and path_match.group("suffix") != "chunks"
+ ):
+ return None
doc_id = _decode_segment(path_match.group("doc_id"))
if doc_id is None:
return None
return _LibraryReference(
- doc_id, path_match.group("suffix"), chunk_index=chunk_index
+ doc_id,
+ path_match.group("suffix"),
+ chunk_index=chunk_index,
+ document_chunk_id=document_chunk_id,
)
bracket_match = _BRACKETED_DOCUMENT_RE.match(candidate)
@@ -170,6 +188,7 @@ def _parse_library_reference(url: str) -> _LibraryReference | None:
bracket_match.group("doc_id"),
bracketed=True,
chunk_index=chunk_index,
+ document_chunk_id=document_chunk_id,
)
return None
@@ -279,6 +298,7 @@ def resolve_library_document(
}
lookup_value = reference.value
chunk_index = reference.chunk_index
+ document_chunk_id = reference.document_chunk_id
if not username:
# No user context → no library. Caller falls through to the
@@ -288,9 +308,12 @@ def resolve_library_document(
# Lazy imports: avoid pulling SQLAlchemy / user-DB modules into the
# module-load path for the (common) no-library case.
try:
+ from sqlalchemy import exists
+
from local_deep_research.database.models.library import (
Document,
DocumentChunk,
+ RAGIndex,
)
from local_deep_research.database.session_context import (
get_user_db_session,
@@ -319,15 +342,87 @@ def resolve_library_document(
chunk = None
if chunk_index is not None:
- chunk = (
- session.query(DocumentChunk)
- .filter(
- DocumentChunk.source_id == document.id,
- DocumentChunk.chunk_index == chunk_index,
+ filters = [
+ DocumentChunk.source_id == document.id,
+ DocumentChunk.chunk_index == chunk_index,
+ ]
+ if document_chunk_id is not None:
+ chunk = (
+ session.query(DocumentChunk)
+ .filter(*filters, DocumentChunk.id == document_chunk_id)
+ .first()
)
- .order_by(DocumentChunk.collection_name, DocumentChunk.id)
- .first()
- )
+ if chunk is None:
+ # A rebuild replaces row IDs. Old citations and URLs
+ # without an ID may resolve to the current generation,
+ # but never to an arbitrary older same-ordinal row.
+ chunk = (
+ session.query(DocumentChunk)
+ .filter(
+ *filters,
+ exists().where(
+ RAGIndex.index_hash
+ == DocumentChunk.vector_index_key,
+ RAGIndex.collection_name
+ == DocumentChunk.collection_name,
+ RAGIndex.is_current.is_(True),
+ ),
+ )
+ .order_by(
+ DocumentChunk.collection_name, DocumentChunk.id
+ )
+ .first()
+ )
+ if chunk is None:
+ # Migration 0042 leaves legacy ownership NULL when more
+ # than one index matches. Keep those stored citations
+ # readable, but only after trying a current owned row and
+ # only for a matching collection/model/provider.
+ chunk = (
+ session.query(DocumentChunk)
+ .filter(
+ *filters,
+ DocumentChunk.vector_index_key.is_(None),
+ exists().where(
+ RAGIndex.collection_name
+ == DocumentChunk.collection_name,
+ RAGIndex.embedding_model
+ == DocumentChunk.embedding_model,
+ RAGIndex.embedding_model_type
+ == DocumentChunk.embedding_model_type,
+ ),
+ )
+ .order_by(
+ DocumentChunk.collection_name, DocumentChunk.id
+ )
+ .first()
+ )
+ if chunk is None:
+ # A document may have only a row owned by a retired
+ # index after a settings change. Recover it only when
+ # that identity is valid and the document/ordinal has a
+ # single candidate; multiple generations are ambiguous.
+ older = (
+ session.query(DocumentChunk)
+ .filter(
+ *filters,
+ DocumentChunk.vector_index_key.is_not(None),
+ exists().where(
+ RAGIndex.index_hash
+ == DocumentChunk.vector_index_key,
+ RAGIndex.collection_name
+ == DocumentChunk.collection_name,
+ RAGIndex.embedding_model
+ == DocumentChunk.embedding_model,
+ RAGIndex.embedding_model_type
+ == DocumentChunk.embedding_model_type,
+ ),
+ )
+ .limit(2)
+ .all()
+ )
+ if len(older) == 1:
+ chunk = older[0]
if chunk is not None:
text = chunk.chunk_text or ""
else:
diff --git a/src/local_deep_research/utilities/chunk_anchor.py b/src/local_deep_research/utilities/chunk_anchor.py
index 6497570b97..fd5caf7cde 100644
--- a/src/local_deep_research/utilities/chunk_anchor.py
+++ b/src/local_deep_research/utilities/chunk_anchor.py
@@ -276,6 +276,8 @@ def build_chunk_anchor_url(
link: str,
doc_id: Optional[str],
chunk_index: Optional[int],
+ *,
+ document_chunk_id: Optional[int] = None,
) -> Optional[str]:
"""Build a ``/library/document/<doc_id>/chunks#chunk-<n>`` URL when
*doc_id* and *chunk_index* are both valid, otherwise return ``None``.
@@ -326,4 +328,10 @@ def build_chunk_anchor_url(
or chunk_index > MAX_CHUNK_INDEX
):
return None
- return f"/library/document/{safe_doc_id}/chunks#chunk-{chunk_index}"
+ query = (
+ f"?document_chunk_id={document_chunk_id}"
+ if type(document_chunk_id) is int
+ and 0 < document_chunk_id <= (1 << 63) - 1
+ else ""
+ )
+ return f"/library/document/{safe_doc_id}/chunks{query}#chunk-{chunk_index}"
diff --git a/src/local_deep_research/utilities/url_utils.py b/src/local_deep_research/utilities/url_utils.py
index 779f489ae5..f299e0658f 100644
--- a/src/local_deep_research/utilities/url_utils.py
+++ b/src/local_deep_research/utilities/url_utils.py
@@ -172,8 +172,8 @@ def _normalize_library_alias(url: str) -> str | None:
Two deliberate differences from the resolver, both narrowing or
identity-preserving rather than widening:
- * A query disqualifies (as in the resolver) — it can carry
- server-meaningful state, unlike a client-side anchor.
+ * Only the resolver's bounded ``document_chunk_id`` query is accepted
+ on a chunk URL; arbitrary server-meaningful state still disqualifies.
* Host comparison uses ``hostname``/``port``, so ``LIBRARY.DOCUMENT``,
``:443`` and userinfo forms name the same document rather than
fanning out into separate bibliography entries. The resolver rejects
@@ -200,7 +200,6 @@ def _normalize_library_alias(url: str) -> str | None:
return None
if (
parsed.scheme != _LIBRARY_ALIAS_SCHEME
- or parsed.query
or (parsed.hostname or "") != _LIBRARY_ALIAS_HOST
):
return None
@@ -219,6 +218,17 @@ def _normalize_library_alias(url: str) -> str | None:
if not is_safe_document_id(doc_id):
return None
suffix = path_match.group("suffix")
+ if parsed.query:
+ match = re.fullmatch(
+ r"document_chunk_id=([1-9][0-9]{0,18})", parsed.query
+ )
+ if (
+ suffix != "chunks"
+ or not is_valid_chunk_fragment(parsed.fragment)
+ or match is None
+ or int(match.group(1)) > (1 << 63) - 1
+ ):
+ return None
rel = f"/library/document/{doc_id}"
if suffix:
rel = f"{rel}/{suffix}"
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 9a177564a6..b5ca7205e4 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
@@ -20,7 +20,11 @@ from ...constants import (
from ...research_library.services.library_rag_service import LibraryRAGService
from ...database.models.library import Collection
from ...database.session_context import get_user_db_session
-from ...utilities.chunk_anchor import extract_chunk_index, extract_document_id
+from ...utilities.chunk_anchor import (
+ build_chunk_anchor_url,
+ extract_chunk_index,
+ extract_document_id,
+)
from ...utilities.type_utils import to_bool
@@ -303,6 +307,7 @@ class CollectionSearchEngine(LibraryRAGSearchEngine):
results = []
for r in search_results:
metadata = dict(r.metadata or {})
+ metadata["document_chunk_id"] = r.chunk_id
# Get document ID
doc_id = (
@@ -345,6 +350,16 @@ class CollectionSearchEngine(LibraryRAGSearchEngine):
document_url = self._get_document_url(
sanitised_doc_id, chunk_index=chunk_idx
)
+ if chunk_idx is not None:
+ document_url = (
+ build_chunk_anchor_url(
+ document_url,
+ sanitised_doc_id,
+ chunk_idx,
+ document_chunk_id=r.chunk_id,
+ )
+ or document_url
+ )
# Add collection info to metadata
metadata["collection_id"] = self.collection_id
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 ef97eab781..9239e31e43 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
@@ -453,6 +453,10 @@ class LibraryRAGSearchEngine(BaseSearchEngine):
results = []
for r, relevance, coll_id in top_results:
metadata = dict(r.metadata or {})
+ # The vector hit was rehydrated by this exact DB chunk row.
+ # Keep its identity for the later full-content lookup: old
+ # index configurations may share the same chunk ordinal.
+ metadata["document_chunk_id"] = r.chunk_id
metadata["collection_id"] = coll_id
metadata["collection_name"] = (
collection_names.get(coll_id) or "Unknown"
@@ -499,6 +503,16 @@ class LibraryRAGSearchEngine(BaseSearchEngine):
document_url = self._get_document_url(
sanitised_doc_id, chunk_index=chunk_idx
)
+ if chunk_idx is not None:
+ document_url = (
+ build_chunk_anchor_url(
+ document_url,
+ sanitised_doc_id,
+ chunk_idx,
+ document_chunk_id=r.chunk_id,
+ )
+ or document_url
+ )
result = {
"title": title,
@@ -566,7 +580,13 @@ class LibraryRAGSearchEngine(BaseSearchEngine):
return relevant_items
try:
- from ...database.models.library import Document, DocumentChunk
+ from sqlalchemy import exists
+
+ from ...database.models.library import (
+ Document,
+ DocumentChunk,
+ RAGIndex,
+ )
from ...database.session_context import get_user_db_session
# Retrieve content for each document or targeted chunk
@@ -589,6 +609,7 @@ class LibraryRAGSearchEngine(BaseSearchEngine):
DocumentChunk.source_id == doc_id,
DocumentChunk.chunk_index == chunk_idx,
)
+ chunk_id = metadata.get("document_chunk_id")
coll_id = metadata.get("collection_id") or item.get(
"collection_id"
)
@@ -609,9 +630,76 @@ class LibraryRAGSearchEngine(BaseSearchEngine):
== metadata.get("collection_name")
)
- chunk = query.order_by(
- DocumentChunk.collection_name, DocumentChunk.id
- ).first()
+ chunk = None
+ if type(chunk_id) is int and chunk_id > 0:
+ chunk = query.filter(
+ DocumentChunk.id == chunk_id
+ ).first()
+ if chunk is None:
+ # A force reindex replaces row IDs. Prefer the
+ # collection's current owned row for an old hit
+ # or metadata without an exact row ID.
+ chunk = (
+ query.filter(
+ exists().where(
+ RAGIndex.index_hash
+ == DocumentChunk.vector_index_key,
+ RAGIndex.collection_name
+ == DocumentChunk.collection_name,
+ RAGIndex.is_current.is_(True),
+ )
+ )
+ .order_by(
+ DocumentChunk.collection_name,
+ DocumentChunk.id,
+ )
+ .first()
+ )
+ if chunk is None:
+ # Historical rows can lack an owner after
+ # migration 0042. Use one only after the current
+ # owned lookup fails and its embedding identity
+ # matches an index in the same collection.
+ chunk = (
+ query.filter(
+ DocumentChunk.vector_index_key.is_(None),
+ exists().where(
+ RAGIndex.collection_name
+ == DocumentChunk.collection_name,
+ RAGIndex.embedding_model
+ == DocumentChunk.embedding_model,
+ RAGIndex.embedding_model_type
+ == DocumentChunk.embedding_model_type,
+ ),
+ )
+ .order_by(
+ DocumentChunk.collection_name,
+ DocumentChunk.id,
+ )
+ .first()
+ )
+ if chunk is None:
+ # Recover a sole row owned by a retired index,
+ # but leave multiple old generations unresolved.
+ older = (
+ query.filter(
+ DocumentChunk.vector_index_key.is_not(None),
+ exists().where(
+ RAGIndex.index_hash
+ == DocumentChunk.vector_index_key,
+ RAGIndex.collection_name
+ == DocumentChunk.collection_name,
+ RAGIndex.embedding_model
+ == DocumentChunk.embedding_model,
+ RAGIndex.embedding_model_type
+ == DocumentChunk.embedding_model_type,
+ ),
+ )
+ .limit(2)
+ .all()
+ )
+ if len(older) == 1:
+ chunk = older[0]
if chunk is not None:
text = chunk.chunk_text or ""
diff --git a/tests/advanced_search_system/tools/test_library_resolver.py b/tests/advanced_search_system/tools/test_library_resolver.py
index 6f0eb5e419..340207dab2 100644
--- a/tests/advanced_search_system/tools/test_library_resolver.py
+++ b/tests/advanced_search_system/tools/test_library_resolver.py
@@ -13,6 +13,8 @@ from __future__ import annotations
from unittest.mock import MagicMock, call, patch
+import pytest
+
# ---------------------------------------------------------------------------
# Pure parsing
@@ -115,6 +117,40 @@ def test_parse_library_url_absolute_alias_with_chunk_anchor():
) == ("123e4567-e89b-12d3-a456-426614174000", "chunks")
+ "suffix",
+ [
+ "?",
+ "?document_chunk_id=0#chunk-0",
+ "?document_chunk_id=-1#chunk-0",
+ "?document_chunk_id=9223372036854775808#chunk-0",
+ "?document_chunk_id=1&other=2#chunk-0",
+ "?document_chunk_id=1",
+ "?document_chunk_id=1#invalid",
+ "?document_chunk_id=" + "9" * 5000 + "#chunk-0",
+ ],
+ ids=[
+ "empty",
+ "zero",
+ "negative",
+ "over_int64",
+ "extra_parameter",
+ "missing_fragment",
+ "bad_fragment",
+ "very_long_id",
+ ],
+)
+def test_parse_library_url_rejects_invalid_chunk_id_query(suffix):
+ from local_deep_research.advanced_search_system.tools.fetch.library_resolver import (
+ parse_library_url,
+ )
+
+ doc_id = "123e4567-e89b-12d3-a456-426614174000"
+ assert (
+ parse_library_url(f"/library/document/{doc_id}/chunks{suffix}") is None
+ )
+
+
def test_parse_library_url_fragment_containing_scheme_not_misrouted():
"""A relative path whose fragment contains ``://`` must not be pushed
into the absolute branch by the ``\"://\" in candidate`` test."""
@@ -201,6 +237,219 @@ def test_resolve_library_document_fetches_chunk_content_when_present():
)
+def test_resolve_library_document_uses_exact_hit_chunk_across_index_versions():
+ """A citation with a row id fetches its hit, not an older ordinal twin."""
+ from contextlib import contextmanager
+
+ from sqlalchemy import create_engine
+ from sqlalchemy.orm import sessionmaker
+
+ from local_deep_research.advanced_search_system.tools.fetch.library_resolver import (
+ resolve_library_document,
+ )
+ from local_deep_research.database.models.library import (
+ Base,
+ Document,
+ DocumentChunk,
+ DocumentStatus,
+ RAGIndex,
+ SourceType,
+ )
+
+ doc_id = "123e4567-e89b-12d3-a456-426614174000"
+ engine = create_engine("sqlite:///:memory:")
+ Base.metadata.create_all(engine)
+ Session = sessionmaker(bind=engine)
+ with Session() as session:
+ session.add(
+ SourceType(id="source", name="document", display_name="Document")
+ )
+ session.add(
+ Document(
+ id=doc_id,
+ source_type_id="source",
+ title="Paper",
+ text_content="document body",
+ document_hash="hash",
+ file_size=13,
+ file_type="txt",
+ status=DocumentStatus.COMPLETED,
+ )
+ )
+ for owner, text in (
+ ("old-index", "old text"),
+ ("new-index", "new text"),
+ ):
+ session.add(
+ DocumentChunk(
+ chunk_hash=owner,
+ source_type="document",
+ source_id=doc_id,
+ collection_name="collection_one",
+ chunk_text=text,
+ chunk_index=0,
+ start_char=0,
+ end_char=len(text),
+ word_count=2,
+ embedding_id=owner,
+ embedding_model="model",
+ embedding_model_type="openai",
+ vector_index_key=owner,
+ )
+ )
+ session.add(
+ RAGIndex(
+ collection_name="collection_one",
+ embedding_model="model",
+ embedding_model_type="openai",
+ embedding_dimension=2,
+ index_path=f"/{owner}.faiss",
+ index_hash=owner,
+ chunk_size=500,
+ chunk_overlap=50,
+ is_current=owner == "new-index",
+ )
+ )
+ session.commit()
+ current_id = (
+ session.query(DocumentChunk.id)
+ .filter_by(vector_index_key="new-index")
+ .scalar()
+ )
+ old_id = (
+ session.query(DocumentChunk.id)
+ .filter_by(vector_index_key="old-index")
+ .scalar()
+ )
+
+ @contextmanager
+ def user_session(username):
+ assert username == "alice"
+ with Session() as session:
+ yield session
+
+ url = f"/library/document/{doc_id}/chunks?document_chunk_id={current_id}#chunk-0"
+ with patch(
+ "local_deep_research.database.session_context.get_user_db_session",
+ side_effect=user_session,
+ ):
+ result = resolve_library_document(url, "alice")
+ legacy_result = resolve_library_document(
+ f"/library/document/{doc_id}/chunks#chunk-0", "alice"
+ )
+ old_result = resolve_library_document(
+ f"/library/document/{doc_id}/chunks?document_chunk_id={old_id}#chunk-0",
+ "alice",
+ )
+ rebuilt_result = resolve_library_document(
+ f"/library/document/{doc_id}/chunks?document_chunk_id={current_id + 1000}#chunk-0",
+ "alice",
+ )
+
+ assert result is not None
+ assert result["content"] == "new text"
+ assert result["url"] == url
+ assert legacy_result is not None
+ assert legacy_result["content"] == "new text"
+ assert old_result is not None
+ assert old_result["content"] == "old text"
+ assert rebuilt_result is not None
+ assert rebuilt_result["content"] == "new text"
+ # Migration 0042 cannot identify an owner when several index rows match.
+ # A stored, ID-less citation must still resolve a legacy NULL-key row.
+ with Session() as session:
+ session.query(DocumentChunk).delete()
+ session.query(RAGIndex).update({"is_current": False})
+ session.add(
+ DocumentChunk(
+ chunk_hash="legacy-null",
+ source_type="document",
+ source_id=doc_id,
+ collection_name="collection_one",
+ chunk_text="legacy text",
+ chunk_index=0,
+ start_char=0,
+ end_char=11,
+ word_count=2,
+ embedding_id="legacy-null",
+ embedding_model="model",
+ embedding_model_type="openai",
+ vector_index_key=None,
+ )
+ )
+ session.commit()
+ with patch(
+ "local_deep_research.database.session_context.get_user_db_session",
+ side_effect=user_session,
+ ):
+ null_key_result = resolve_library_document(
+ f"/library/document/{doc_id}/chunks#chunk-0", "alice"
+ )
+ assert null_key_result is not None
+ assert null_key_result["content"] == "legacy text"
+ with Session() as session:
+ session.query(DocumentChunk).update({"embedding_model": "unrelated"})
+ session.commit()
+ with patch(
+ "local_deep_research.database.session_context.get_user_db_session",
+ side_effect=user_session,
+ ):
+ unrelated_result = resolve_library_document(
+ f"/library/document/{doc_id}/chunks#chunk-0", "alice"
+ )
+ assert unrelated_result is not None
+ assert (
+ unrelated_result["content"]
+ == f"Chunk 0 not found for document {doc_id}."
+ )
+ with Session() as session:
+ session.query(DocumentChunk).update(
+ {"embedding_model": "model", "vector_index_key": "old-index"}
+ )
+ session.commit()
+ with patch(
+ "local_deep_research.database.session_context.get_user_db_session",
+ side_effect=user_session,
+ ):
+ retired_result = resolve_library_document(
+ f"/library/document/{doc_id}/chunks#chunk-0", "alice"
+ )
+ assert retired_result is not None
+ assert retired_result["content"] == "legacy text"
+ with Session() as session:
+ session.add(
+ DocumentChunk(
+ chunk_hash="second-retired",
+ source_type="document",
+ source_id=doc_id,
+ collection_name="collection_one",
+ chunk_text="ambiguous text",
+ chunk_index=0,
+ start_char=0,
+ end_char=14,
+ word_count=2,
+ embedding_id="second-retired",
+ embedding_model="model",
+ embedding_model_type="openai",
+ vector_index_key="new-index",
+ )
+ )
+ session.commit()
+ with patch(
+ "local_deep_research.database.session_context.get_user_db_session",
+ side_effect=user_session,
+ ):
+ ambiguous_result = resolve_library_document(
+ f"/library/document/{doc_id}/chunks#chunk-0", "alice"
+ )
+ assert ambiguous_result is not None
+ assert (
+ ambiguous_result["content"]
+ == f"Chunk 0 not found for document {doc_id}."
+ )
+ engine.dispose()
+
+
def test_resolve_library_document_reports_missing_chunk_when_chunk_missing():
"""When a chunk anchor is present but the DocumentChunk row is missing,
it reports that the chunk was not found instead of silently falling back
diff --git a/tests/strategies/test_langgraph_agent_strategy.py b/tests/strategies/test_langgraph_agent_strategy.py
index 14f7e603ea..6a7e9062ab 100644
--- a/tests/strategies/test_langgraph_agent_strategy.py
+++ b/tests/strategies/test_langgraph_agent_strategy.py
@@ -251,6 +251,27 @@ class TestSearchResultsCollector:
assert collector.results[2]["index"] == "1"
assert collector.sources == ["/library/document/doc1/chunks#chunk-0"]
+ def test_add_results_keeps_exact_chunk_identity_in_citation_url(self):
+ collector, _ = self._make_collector()
+ collector.add_results(
+ [
+ {
+ "title": "Doc",
+ "link": "/library/document/doc1/chunks#chunk-0",
+ "source": "library",
+ "source_id": "doc1",
+ "metadata": {
+ "chunk_index": 0,
+ "document_chunk_id": 42,
+ },
+ }
+ ]
+ )
+ assert (
+ collector.results[0]["link"]
+ == "/library/document/doc1/chunks?document_chunk_id=42#chunk-0"
+ )
+
@pytest.mark.parametrize(
"doc_id_structure",
[
diff --git a/tests/utilities/test_chunk_anchor.py b/tests/utilities/test_chunk_anchor.py
index f9d3539668..cb11de33e2 100644
--- a/tests/utilities/test_chunk_anchor.py
+++ b/tests/utilities/test_chunk_anchor.py
@@ -234,6 +234,12 @@ class TestBuildChunkAnchorUrl:
== "/library/document/doc1/chunks#chunk-0"
)
+ def test_document_chunk_id_preserves_ui_anchor(self):
+ assert (
+ build_chunk_anchor_url("", "doc1", 0, document_chunk_id=42)
+ == "/library/document/doc1/chunks?document_chunk_id=42#chunk-0"
+ )
+
class TestProducerCollectorTemplateContract:
"""Shared CI contract test for the producer→collector→template path.
diff --git a/tests/utilities/test_research_cache_completeness.py b/tests/utilities/test_research_cache_completeness.py
index ead9099820..b245e624b6 100644
--- a/tests/utilities/test_research_cache_completeness.py
+++ b/tests/utilities/test_research_cache_completeness.py
@@ -316,9 +316,11 @@ def test_missing_library_chunk_can_be_retried():
query = session.query.return_value
query.filter.return_value = query
query.order_by.return_value.first.side_effect = [
+ None,
None,
SimpleNamespace(chunk_text=BODY),
]
+ query.limit.return_value.all.return_value = []
def search():
return engine._get_full_content_cached(
diff --git a/tests/utilities/test_url_utils.py b/tests/utilities/test_url_utils.py
index a41bd0f344..50d7eac293 100644
--- a/tests/utilities/test_url_utils.py
+++ b/tests/utilities/test_url_utils.py
@@ -351,6 +351,18 @@ class TestCanonicalUrlKey:
"/library/document/abc123/chunks#chunk-0"
) == canonical_url_key("https://library.document/abc123/chunks#chunk-7")
+ def test_chunk_id_alias_still_keys_and_displays_as_library_route(self):
+ from local_deep_research.utilities.url_utils import (
+ canonical_url_key,
+ library_display_url,
+ )
+
+ alias = "https://library.document/abc123/chunks?document_chunk_id=42#chunk-3"
+ assert canonical_url_key(alias) == "/library/document/abc123"
+ assert library_display_url(alias) == (
+ "/library/document/abc123/chunks#chunk-3"
+ )
+
def test_absolute_library_alias_rejects_lookalikes(self):
"""Only the exact https://library.document host normalizes."""
from local_deep_research.utilities.url_utils import (
@@ -371,6 +383,9 @@ class TestCanonicalUrlKey:
"https://library.document/abc/../../../admin/api/delete-all",
"https://library.document/abc/xyz/extra",
"https://library.document/abc?evil=1",
+ "https://library.document/abc/chunks?document_chunk_id=0#chunk-3",
+ "https://library.document/abc/chunks?document_chunk_id=1#invalid",
+ "https://library.document/abc/pdf?document_chunk_id=1#chunk-3",
"https://library.document/https://a.test/page",
):
# Assert the invariant, not inequality with one literal: a
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 2b22303666..7edcc3e5f0 100644
--- a/tests/web_search_engines/engines/test_search_engine_collection.py
+++ b/tests/web_search_engines/engines/test_search_engine_collection.py
@@ -456,6 +456,7 @@ class TestSearch:
mock_doc.metadata = {
"source_id": "123",
"document_title": "Test Document",
+ "chunk_index": 0,
}
with patch(
@@ -514,7 +515,9 @@ class TestSearch:
assert results[0]["title"] == "Test Document"
assert results[0]["source"] == "library"
assert results[0]["source_type"] == "library"
- assert results[0]["url"] == "/library/document/123"
+ assert results[0]["url"] == (
+ "/library/document/123/chunks?document_chunk_id=1#chunk-0"
+ )
def test_search_forwards_all_rag_parameters(self):
"""Search forwards chunk_overlap=0, splitter_type, text_separators, distance_metric, index_type."""
diff --git a/tests/web_search_engines/engines/test_search_engine_library.py b/tests/web_search_engines/engines/test_search_engine_library.py
index c08fe02677..245fb86ff0 100644
--- a/tests/web_search_engines/engines/test_search_engine_library.py
+++ b/tests/web_search_engines/engines/test_search_engine_library.py
@@ -169,6 +169,7 @@ class TestSearch:
mock_doc.metadata = {
"source_id": "123",
"document_title": "Test Document",
+ "chunk_index": 0,
}
with patch(
@@ -243,7 +244,12 @@ class TestSearch:
assert results[0]["title"] == "Test Document"
assert results[0]["source"] == "library"
assert results[0]["source_type"] == "library"
- assert "/library/document/123" in results[0]["url"]
+ assert (
+ results[0]["metadata"]["document_chunk_id"] == 1
+ )
+ assert results[0]["url"] == (
+ "/library/document/123/chunks?document_chunk_id=1#chunk-0"
+ )
def test_search_forwards_zero_overlap_and_splitter_settings(self):
"""Search forwards chunk_overlap=0, splitter_type, and text_separators to LibraryRAGService."""
@@ -498,6 +504,164 @@ class TestGetPreviews:
class TestGetFullContent:
"""Tests for _get_full_content method."""
+ def test_get_full_content_uses_hit_chunk_id_across_index_versions(self):
+ """A current-index hit must not hydrate an older same-ordinal chunk."""
+ from contextlib import contextmanager
+
+ from sqlalchemy import create_engine
+ from sqlalchemy.orm import sessionmaker
+
+ from local_deep_research.database.models.library import (
+ Base,
+ DocumentChunk,
+ RAGIndex,
+ )
+ from local_deep_research.web_search_engines.engines.search_engine_library import (
+ LibraryRAGSearchEngine,
+ )
+
+ db_engine = create_engine("sqlite:///:memory:")
+ Base.metadata.create_all(
+ db_engine, tables=[DocumentChunk.__table__, RAGIndex.__table__]
+ )
+ Session = sessionmaker(bind=db_engine)
+ with Session() as session:
+ for owner, text in (
+ ("old-index", "old text"),
+ ("new-index", "new text"),
+ ):
+ session.add(
+ DocumentChunk(
+ chunk_hash=owner,
+ source_type="document",
+ source_id="doc123",
+ collection_name="collection_coll-A",
+ chunk_text=text,
+ chunk_index=0,
+ start_char=0,
+ end_char=len(text),
+ word_count=2,
+ embedding_id=owner,
+ embedding_model="model",
+ embedding_model_type="openai",
+ vector_index_key=owner,
+ )
+ )
+ session.add(
+ RAGIndex(
+ collection_name="collection_coll-A",
+ embedding_model="model",
+ embedding_model_type="openai",
+ embedding_dimension=2,
+ index_path=f"/{owner}.faiss",
+ index_hash=owner,
+ chunk_size=500,
+ chunk_overlap=50,
+ is_current=owner == "new-index",
+ )
+ )
+ session.commit()
+ current_id = (
+ session.query(DocumentChunk.id)
+ .filter_by(vector_index_key="new-index")
+ .scalar()
+ )
+ old_id = (
+ session.query(DocumentChunk.id)
+ .filter_by(vector_index_key="old-index")
+ .scalar()
+ )
+
+ @contextmanager
+ def user_session(username):
+ assert username == "testuser"
+ with Session() as session:
+ yield session
+
+ engine = LibraryRAGSearchEngine(
+ settings_snapshot={"_username": "testuser"}
+ )
+ item = {
+ "source_id": "doc123",
+ "metadata": {
+ "chunk_index": 0,
+ "collection_id": "coll-A",
+ "document_chunk_id": current_id,
+ },
+ "snippet": "new text",
+ }
+ with patch(
+ "local_deep_research.database.session_context.get_user_db_session",
+ side_effect=user_session,
+ ):
+ result = engine._get_full_content([item])
+ old_item = {
+ **item,
+ "metadata": {**item["metadata"], "document_chunk_id": old_id},
+ }
+ old_result = engine._get_full_content([old_item])
+ rebuilt_item = {
+ **item,
+ "metadata": {
+ **item["metadata"],
+ "document_chunk_id": current_id + 1000,
+ },
+ }
+ rebuilt_result = engine._get_full_content([rebuilt_item])
+ legacy_item = {
+ **item,
+ "metadata": {
+ key: value
+ for key, value in item["metadata"].items()
+ if key != "document_chunk_id"
+ },
+ }
+ legacy_result = engine._get_full_content([legacy_item])
+
+ assert result[0]["full_content"] == "new text"
+ assert old_result[0]["full_content"] == "old text"
+ assert rebuilt_result[0]["full_content"] == "new text"
+ assert legacy_result[0]["full_content"] == "new text"
+ with Session() as session:
+ session.query(DocumentChunk).delete()
+ session.query(RAGIndex).update({"is_current": False})
+ session.add(
+ DocumentChunk(
+ chunk_hash="legacy-null",
+ source_type="document",
+ source_id="doc123",
+ collection_name="collection_coll-A",
+ chunk_text="legacy text",
+ chunk_index=0,
+ start_char=0,
+ end_char=11,
+ word_count=2,
+ embedding_id="legacy-null",
+ embedding_model="model",
+ embedding_model_type="openai",
+ vector_index_key=None,
+ )
+ )
+ session.commit()
+ with patch(
+ "local_deep_research.database.session_context.get_user_db_session",
+ side_effect=user_session,
+ ):
+ null_key_result = engine._get_full_content([legacy_item.copy()])
+ assert null_key_result[0]["full_content"] == "legacy text"
+ with Session() as session:
+ session.query(DocumentChunk).update(
+ {"vector_index_key": "old-index"}
+ )
+ session.commit()
+ with patch(
+ "local_deep_research.database.session_context.get_user_db_session",
+ side_effect=user_session,
+ ):
+ retired_result = engine._get_full_content([legacy_item.copy()])
+ assert retired_result[0]["full_content"] == "legacy text"
+ db_engine.dispose()
+
def test_get_full_content_retrieves_chunk_when_indexed(self):
"""When chunk metadata exists, chunk text is retrieved instead of full document."""
from local_deep_research.web_search_engines.engines.search_engine_library import (
@@ -627,6 +791,7 @@ class TestGetFullContent:
from local_deep_research.database.models.library import (
Base,
DocumentChunk,
+ RAGIndex,
)
from local_deep_research.web_search_engines.engines.search_engine_library import (
LibraryRAGSearchEngine,
@@ -634,7 +799,8 @@ class TestGetFullContent:
test_db_engine = create_engine("sqlite:///:memory:")
Base.metadata.create_all(
- test_db_engine, tables=[DocumentChunk.__table__]
+ test_db_engine,
+ tables=[DocumentChunk.__table__, RAGIndex.__table__],
)
Session = sessionmaker(bind=test_db_engine)
db_session = Session()
@@ -654,6 +820,7 @@ class TestGetFullContent:
embedding_id="e1",
embedding_model="model",
embedding_model_type="openai",
+ vector_index_key="index-a",
)
)
db_session.add(
@@ -670,8 +837,26 @@ class TestGetFullContent:
embedding_id="e2",
embedding_model="model",
embedding_model_type="openai",
+ vector_index_key="index-b",
)
)
+ for collection_name, index_hash in (
+ ("collection_coll-A", "index-a"),
+ ("collection_coll-B", "index-b"),
+ ):
+ db_session.add(
+ RAGIndex(
+ collection_name=collection_name,
+ embedding_model="model",
+ embedding_model_type="openai",
+ embedding_dimension=2,
+ index_path=f"/{index_hash}.faiss",
+ index_hash=index_hash,
+ chunk_size=500,
+ chunk_overlap=50,
+ is_current=True,
+ )
+ )
db_session.commit()
@contextmanager
@@ -735,6 +920,7 @@ class TestGetFullContent:
query_mock.filter.return_value = query_mock
query_mock.order_by.return_value = query_mock
query_mock.first.return_value = None
+ query_mock.limit.return_value.all.return_value = []
mock_session_cm.return_value.__enter__.return_value = mock_session
items = [
diff --git a/tests/web_search_engines/test_engine_success_path.py b/tests/web_search_engines/test_engine_success_path.py
index 35cc63c2cb..40759e05ab 100644
--- a/tests/web_search_engines/test_engine_success_path.py
+++ b/tests/web_search_engines/test_engine_success_path.py
@@ -1543,6 +1543,7 @@ def _drive_zenodo(tracker):
def _fake_rag_hit():
"""One ``SearchResult`` as ``LibraryRAGService.search`` returns them."""
return SimpleNamespace(
+ chunk_id=1,
source_id="41",
document_title="Attention Is All You Need (local copy)",
text="The Transformer architecture dispenses with recurrence.",
@@ -1900,14 +1901,14 @@ CASES = [
"library",
_drive_library,
"Attention Is All You Need (local copy)",
- "/library/document/41/chunks#chunk-3",
+ "/library/document/41/chunks?document_chunk_id=1#chunk-3",
"dispenses with recurrence",
),
Case(
"collection",
_drive_collection,
"Attention Is All You Need (local copy)",
- "/library/document/41/chunks#chunk-3",
+ "/library/document/41/chunks?document_chunk_id=1#chunk-3",
"dispenses with recurrence",
),
]