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(fetch): resolve specific chunk content for library document citations (#6117)

Sce5e81cb1286
diff --git a/changelog.d/6117.bugfix.md b/changelog.d/6117.bugfix.md
new file mode 100644
index 0000000000..26c7939c24
--- /dev/null
+++ b/changelog.d/6117.bugfix.md
@@ -0,0 +1 @@
+Fetching a library document citation with a `#chunk-<n>` anchor now retrieves the cited chunk's text instead of truncating the entire document body. When a cited chunk is missing or empty, the fetch resolver reports the missing chunk or empty content rather than silently falling back to the full document. In the library search engine, chunk retrieval is scoped to the source collection and ordered deterministically.
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 8fac35ba4e..b92d146063 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
@@ -14,7 +14,8 @@ not know how to fetch even without a policy gate):
``web_search_engines.engines.search_engine_library.LibraryRAGSearchEngine.search``
and ``...search_engine_collection.CollectionSearchEngine._get_document_url``).
The URL points at the user's own library — a local DB read, not a
- network fetch — and resolving it via ``Document.text_content`` is what
+ network fetch — and resolving it via ``DocumentChunk.chunk_text`` (when
+ a chunk anchor is provided) or ``Document.text_content`` is what
the human user would see if they clicked the link in the UI.
2. **Bare citation markers** like ``[1062]``, ``[1084]``. The agent
@@ -49,7 +50,7 @@ from ....utilities.chunk_anchor import (
LIBRARY_ROUTE_SUFFIX_ALTERNATION,
is_safe_document_id,
)
-
+from ....utilities.url_utils import is_valid_chunk_fragment
# Canonical document IDs are 32/64-hex blobs or a UUID. The path form is
# bound to this same pattern as the bracket form (below) so a guessable
@@ -68,9 +69,7 @@ _DOCUMENT_ID_PATTERN = (
#
# ``chunks`` is accepted alongside ``pdf`` because the library/collection
# RAG engines cite chunk-targeted URLs (``/library/document/<id>/chunks``
-# plus a ``#chunk-<n>`` fragment) since #5381. Both suffixes resolve to
-# the same ``Document.text_content`` read below — the suffix only tells a
-# caller which UI route the citation pointed at.
+# plus a ``#chunk-<n>`` fragment) since #5381.
_LIBRARY_PATH_RE = re.compile(
rf"^/(?:library|lib)/document/(?P<doc_id>{_DOCUMENT_ID_PATTERN})"
rf"(?:/(?P<suffix>{LIBRARY_ROUTE_SUFFIX_ALTERNATION}))?/?$"
@@ -96,6 +95,7 @@ class _LibraryReference:
#: and ``https://library.document/<id>`` citations — and renders a
#: dead link. Callers re-emit the canonical route instead.
bracketed: bool = False
+ chunk_index: Optional[int] = None
def _decode_segment(value: str) -> str | None:
@@ -126,14 +126,19 @@ def _parse_library_reference(url: str) -> _LibraryReference | None:
if not candidate:
return None
- # Drop any ``#fragment`` first. Chunk citations carry ``#chunk-<n>``,
- # which addresses an anchor inside the rendered page and is never part
- # of the document identity. This runs BEFORE the ``://`` test so that
+ # Extract any validated ``#chunk-<n>`` fragment before splitting the path.
+ # Chunk citations carry ``#chunk-<n>``, which addresses a specific chunk.
+ # We record the index and strip the fragment before the ``://`` test so that
# (a) the ``https://library.document/<id>/chunks#chunk-3`` alias is not
# rejected by the absolute branch's no-fragment rule, and (b) a
# relative path whose fragment happens to contain ``://``
# (``/library/document/<id>#http://x``) is not misrouted into it.
- candidate = candidate.split("#", 1)[0]
+ chunk_index: Optional[int] = None
+ if "#" in candidate:
+ head, fragment = candidate.split("#", 1)
+ candidate = head
+ if is_valid_chunk_fragment(fragment):
+ chunk_index = int(fragment[len("chunk-") :])
if not candidate:
return None
@@ -155,11 +160,17 @@ def _parse_library_reference(url: str) -> _LibraryReference | 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"))
+ return _LibraryReference(
+ doc_id, path_match.group("suffix"), chunk_index=chunk_index
+ )
bracket_match = _BRACKETED_DOCUMENT_RE.match(candidate)
if bracket_match:
- return _LibraryReference(bracket_match.group("doc_id"), bracketed=True)
+ return _LibraryReference(
+ bracket_match.group("doc_id"),
+ bracketed=True,
+ chunk_index=chunk_index,
+ )
return None
@@ -200,6 +211,12 @@ def resolve_library_document(
) -> Optional[dict[str, Any]]:
"""Look up a local library document by ``/library/document/<uuid>[/pdf]`` URL.
+ When the URL includes a chunk anchor (e.g. ``/library/document/<uuid>/chunks#chunk-3``),
+ retrieves the specific chunk text from ``DocumentChunk`` rather than the whole document.
+ If no chunk anchor is present, resolves to ``Document.text_content``. If a chunk anchor
+ is present but the chunk is missing, reports that the chunk was not found rather than
+ silently falling back to the whole document.
+
Returns a dict shaped like the fetch tool's success payload (``title``,
``content``) so callers can pass it straight to ``_register_in_collector``
+ the ``[N] Title:\\nURL:\\n\\n<body>`` formatter. The ``url`` field of
@@ -225,6 +242,7 @@ def resolve_library_document(
if reference is None:
return None
lookup_value = reference.value
+ chunk_index = reference.chunk_index
if not username:
# No user context → no library. Caller falls through to the
@@ -234,7 +252,10 @@ 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 local_deep_research.database.models.library import Document
+ from local_deep_research.database.models.library import (
+ Document,
+ DocumentChunk,
+ )
from local_deep_research.database.session_context import (
get_user_db_session,
)
@@ -259,7 +280,25 @@ def resolve_library_document(
document = query.filter_by(id=canonical_id).first()
if document is None:
return None
- text = document.text_content or ""
+
+ chunk = None
+ if chunk_index is not None:
+ chunk = (
+ session.query(DocumentChunk)
+ .filter(
+ DocumentChunk.source_id == document.id,
+ DocumentChunk.chunk_index == chunk_index,
+ )
+ .order_by(DocumentChunk.collection_name, DocumentChunk.id)
+ .first()
+ )
+ if chunk is not None:
+ text = chunk.chunk_text or ""
+ else:
+ text = f"Chunk {chunk_index} not found for document {document.id}."
+ else:
+ text = document.text_content or ""
+
citation_url = url
if reference.bracketed:
# Built from the RESOLVED row's id, not from the alias
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 99050434be..6350a7bf07 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
@@ -456,41 +456,96 @@ class LibraryRAGSearchEngine(BaseSearchEngine):
self, relevant_items: List[Dict[str, Any]]
) -> List[Dict[str, Any]]:
"""
- Get full content for relevant library documents.
- Retrieves complete document text instead of just snippets.
+ Get full content for relevant library documents or chunks.
+ Retrieves chunk text if a chunk index is targeted, else complete document text.
"""
if not self.username:
logger.error("Cannot retrieve full content without username")
return relevant_items
try:
- from ...database.models.library import Document
+ from ...database.models.library import Document, DocumentChunk
from ...database.session_context import get_user_db_session
- # Retrieve full content for each document
+ # Retrieve content for each document or targeted chunk
for item in relevant_items:
- doc_id = item.get("metadata", {}).get("document_id")
+ metadata = item.get("metadata") or {}
+ doc_id = (
+ item.get("source_id")
+ or metadata.get("source_id")
+ or metadata.get("document_id")
+ )
if not doc_id:
continue
- # Get full document text from database
+ chunk_idx = extract_chunk_index(metadata)
+
+ # Get document/chunk text from database
with get_user_db_session(self.username) as db_session:
- document = (
- db_session.query(Document).filter_by(id=doc_id).first()
- )
+ if chunk_idx is not None:
+ query = db_session.query(DocumentChunk).filter(
+ DocumentChunk.source_id == doc_id,
+ DocumentChunk.chunk_index == chunk_idx,
+ )
+ coll_id = metadata.get("collection_id") or item.get(
+ "collection_id"
+ )
+ if coll_id:
+ coll_name = (
+ coll_id
+ if str(coll_id).startswith("collection_")
+ else f"collection_{coll_id}"
+ )
+ query = query.filter(
+ DocumentChunk.collection_name == coll_name
+ )
+ elif metadata.get("collection_name") and str(
+ metadata.get("collection_name")
+ ).startswith("collection_"):
+ query = query.filter(
+ DocumentChunk.collection_name
+ == metadata.get("collection_name")
+ )
+
+ chunk = query.order_by(
+ DocumentChunk.collection_name, DocumentChunk.id
+ ).first()
- if document and document.text_content:
- # Replace snippet with full content
- item["content"] = document.text_content
+ if chunk is not None:
+ text = chunk.chunk_text or ""
+ else:
+ text = f"Chunk {chunk_idx} not found for document {doc_id}."
+
+ item["content"] = text
item["snippet"] = (
- document.text_content[:SNIPPET_LENGTH_LONG] + "..."
- if len(document.text_content) > SNIPPET_LENGTH_LONG
- else document.text_content
+ text[:SNIPPET_LENGTH_LONG] + "..."
+ if len(text) > SNIPPET_LENGTH_LONG
+ else text
)
logger.debug(
- f"Retrieved full content for document {doc_id}"
+ f"Retrieved chunk {chunk_idx} content for document {doc_id}"
+ )
+ else:
+ document = (
+ db_session.query(Document)
+ .filter_by(id=doc_id)
+ .first()
)
+ if document and document.text_content:
+ # Replace snippet with full content
+ item["content"] = document.text_content
+ item["snippet"] = (
+ document.text_content[:SNIPPET_LENGTH_LONG]
+ + "..."
+ if len(document.text_content)
+ > SNIPPET_LENGTH_LONG
+ else document.text_content
+ )
+ logger.debug(
+ f"Retrieved full content for document {doc_id}"
+ )
+
return relevant_items
except Exception as e:
diff --git a/tests/advanced_search_system/tools/test_library_resolver.py b/tests/advanced_search_system/tools/test_library_resolver.py
index 2ef89d36b6..d6ebe5e074 100644
--- a/tests/advanced_search_system/tools/test_library_resolver.py
+++ b/tests/advanced_search_system/tools/test_library_resolver.py
@@ -117,7 +117,7 @@ def test_parse_library_url_absolute_alias_with_chunk_anchor():
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."""
+ into the absolute branch by the ``\"://\" in candidate`` test."""
from local_deep_research.advanced_search_system.tools.fetch.library_resolver import (
parse_library_url,
)
@@ -146,21 +146,91 @@ def test_parse_library_url_chunk_anchor_still_rejects_bad_doc_ids():
assert parse_library_url(bad) is None, bad
-def test_resolve_library_document_reads_document_for_chunk_url():
- """End-to-end on the resolver: a chunk-anchored citation resolves to the
- document's text content rather than falling through to egress."""
+def test_resolve_library_document_fetches_chunk_content_when_present():
+ """A chunk-anchored citation resolves specifically to that chunk's text content."""
from local_deep_research.advanced_search_system.tools.fetch.library_resolver import (
resolve_library_document,
)
+ from local_deep_research.database.models.library import (
+ Document,
+ DocumentChunk,
+ )
document = MagicMock()
+ document.id = "123e4567-e89b-12d3-a456-426614174000"
document.title = "My Paper"
document.text_content = "full document body"
+ chunk = MagicMock()
+ chunk.chunk_index = 3
+ chunk.chunk_text = "specific chunk 3 content"
+
session = MagicMock()
- session.query.return_value.filter_by.return_value.first.return_value = (
- document
+
+ def query_side_effect(model):
+ q = MagicMock()
+ if model == Document:
+ q.filter_by.return_value.first.return_value = document
+ elif model == DocumentChunk:
+ q.filter.return_value.order_by.return_value.first.return_value = (
+ chunk
+ )
+ return q
+
+ session.query.side_effect = query_side_effect
+ session_cm = MagicMock()
+ session_cm.__enter__.return_value = session
+ session_cm.__exit__.return_value = False
+
+ with patch(
+ "local_deep_research.database.session_context.get_user_db_session",
+ return_value=session_cm,
+ ):
+ result = resolve_library_document(
+ "/library/document/123e4567-e89b-12d3-a456-426614174000/chunks#chunk-3",
+ "alice",
+ )
+
+ assert result is not None
+ assert result["title"] == "My Paper"
+ assert result["content"] == "specific chunk 3 content"
+ assert result["snippet"] == "specific chunk 3 content"
+ assert (
+ result["url"]
+ == "/library/document/123e4567-e89b-12d3-a456-426614174000/chunks#chunk-3"
+ )
+
+
+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
+ to the full document body."""
+ from local_deep_research.advanced_search_system.tools.fetch.library_resolver import (
+ resolve_library_document,
+ )
+ from local_deep_research.database.models.library import (
+ Document,
+ DocumentChunk,
)
+
+ document = MagicMock()
+ document.id = "123e4567-e89b-12d3-a456-426614174000"
+ document.title = "My Paper"
+ document.text_content = "full document body"
+
+ session = MagicMock()
+
+ def query_side_effect(model):
+ q = MagicMock()
+ if model == Document:
+ q.filter_by.return_value.first.return_value = document
+ elif model == DocumentChunk:
+ q.filter.return_value.order_by.return_value.first.return_value = (
+ None
+ )
+ return q
+
+ session.query.side_effect = query_side_effect
session_cm = MagicMock()
session_cm.__enter__.return_value = session
session_cm.__exit__.return_value = False
@@ -176,15 +246,84 @@ def test_resolve_library_document_reads_document_for_chunk_url():
assert result is not None
assert result["title"] == "My Paper"
- assert result["content"] == "full document body"
- # The original URL (fragment included) is preserved so a downstream
- # re-citation still points at the cited chunk.
+ assert "Chunk 3 not found for document" in result["content"]
+ assert result["content"] != "full document body"
assert (
result["url"]
== "/library/document/123e4567-e89b-12d3-a456-426614174000/chunks#chunk-3"
)
+def test_resolve_library_document_returns_empty_content_when_chunk_text_empty():
+ """When a chunk is present but its chunk_text is empty, returns content=""
+ rather than falling back to the full document."""
+ from local_deep_research.advanced_search_system.tools.fetch.library_resolver import (
+ resolve_library_document,
+ )
+ from local_deep_research.database.models.library import (
+ Document,
+ DocumentChunk,
+ )
+
+ document = MagicMock()
+ document.id = "123e4567-e89b-12d3-a456-426614174000"
+ document.title = "My Paper"
+ document.text_content = "full document body"
+
+ chunk = MagicMock()
+ chunk.chunk_index = 3
+ chunk.chunk_text = ""
+
+ session = MagicMock()
+
+ def query_side_effect(model):
+ q = MagicMock()
+ if model == Document:
+ q.filter_by.return_value.first.return_value = document
+ elif model == DocumentChunk:
+ q.filter.return_value.order_by.return_value.first.return_value = (
+ chunk
+ )
+ return q
+
+ session.query.side_effect = query_side_effect
+ session_cm = MagicMock()
+ session_cm.__enter__.return_value = session
+ session_cm.__exit__.return_value = False
+
+ with patch(
+ "local_deep_research.database.session_context.get_user_db_session",
+ return_value=session_cm,
+ ):
+ result = resolve_library_document(
+ "/library/document/123e4567-e89b-12d3-a456-426614174000/chunks#chunk-3",
+ "alice",
+ )
+
+ assert result is not None
+ assert result["title"] == "My Paper"
+ assert result["content"] == ""
+ assert result["snippet"] == "My Paper"
+
+
+def test_parse_library_url_oversized_chunk_fragment_does_not_raise():
+ """Regression for digit-length guard: an oversized chunk fragment (e.g. 5000 digits)
+ must not raise ValueError during integer parsing."""
+ from local_deep_research.advanced_search_system.tools.fetch.library_resolver import (
+ parse_library_url,
+ resolve_library_document,
+ )
+
+ huge_fragment = "chunk-" + ("9" * 5000)
+ url = f"/library/document/123e4567-e89b-12d3-a456-426614174000/chunks#{huge_fragment}"
+
+ parsed = parse_library_url(url)
+ assert parsed == ("123e4567-e89b-12d3-a456-426614174000", "chunks")
+
+ res = resolve_library_document(url, username=None)
+ assert res is None
+
+
def test_parse_library_url_trailing_slash():
from local_deep_research.advanced_search_system.tools.fetch.library_resolver import (
parse_library_url,
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 9f9da0b8b8..931cc24e46 100644
--- a/tests/web_search_engines/engines/test_search_engine_library.py
+++ b/tests/web_search_engines/engines/test_search_engine_library.py
@@ -323,10 +323,246 @@ class TestGetPreviews:
)
-# Note: _get_full_content tests are skipped due to a bug in the source code
-# where `from ... import search_config` doesn't work (search_config is in
-# the config subpackage, not the root package). The method would need to
-# use `from ...config import search_config` instead.
+class TestGetFullContent:
+ """Tests for _get_full_content method."""
+
+ 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 (
+ LibraryRAGSearchEngine,
+ )
+
+ settings = {"_username": "testuser"}
+ engine = LibraryRAGSearchEngine(settings_snapshot=settings)
+
+ chunk = Mock()
+ chunk.chunk_text = "Specific chunk text content"
+
+ with patch(
+ "local_deep_research.database.session_context.get_user_db_session"
+ ) as mock_session_cm:
+ mock_session = Mock()
+ query_mock = Mock()
+ mock_session.query.return_value = query_mock
+ query_mock.filter.return_value = query_mock
+ query_mock.order_by.return_value = query_mock
+ query_mock.first.return_value = chunk
+ mock_session_cm.return_value.__enter__.return_value = mock_session
+
+ items = [
+ {
+ "source_id": "doc123",
+ "metadata": {"chunk_index": 5, "document_id": "doc123"},
+ "content": "old snippet",
+ }
+ ]
+ result = engine._get_full_content(items)
+
+ assert len(result) == 1
+ assert result[0]["content"] == "Specific chunk text content"
+ assert result[0]["snippet"] == "Specific chunk text content"
+
+ def test_get_full_content_falls_back_to_document_when_no_chunk_index(self):
+ """When no chunk index exists in metadata, full document text is retrieved."""
+ from local_deep_research.web_search_engines.engines.search_engine_library import (
+ LibraryRAGSearchEngine,
+ )
+
+ settings = {"_username": "testuser"}
+ engine = LibraryRAGSearchEngine(settings_snapshot=settings)
+
+ doc = Mock()
+ doc.text_content = "Full document body text"
+
+ with patch(
+ "local_deep_research.database.session_context.get_user_db_session"
+ ) as mock_session_cm:
+ mock_session = Mock()
+ mock_session.query.return_value.filter_by.return_value.first.return_value = doc
+ mock_session_cm.return_value.__enter__.return_value = mock_session
+
+ items = [
+ {
+ "source_id": "doc123",
+ "metadata": {"document_id": "doc123"},
+ "content": "old snippet",
+ }
+ ]
+ result = engine._get_full_content(items)
+
+ assert len(result) == 1
+ assert result[0]["content"] == "Full document body text"
+
+ def test_get_full_content_scopes_by_collection_id(self):
+ """When collection_id is present in metadata, chunk query is scoped by collection_name.
+
+ Pins the guarantee that a document indexed into two collections returns
+ the chunk text for the requested collection rather than the other's.
+ """
+ from contextlib import contextmanager
+ from sqlalchemy import create_engine
+ from sqlalchemy.orm import sessionmaker
+ from local_deep_research.database.models.library import (
+ Base,
+ DocumentChunk,
+ )
+ from local_deep_research.web_search_engines.engines.search_engine_library import (
+ LibraryRAGSearchEngine,
+ )
+
+ test_db_engine = create_engine("sqlite:///:memory:")
+ Base.metadata.create_all(
+ test_db_engine, tables=[DocumentChunk.__table__]
+ )
+ Session = sessionmaker(bind=test_db_engine)
+ db_session = Session()
+
+ # Same (source_id, chunk_index) exists in two distinct collections
+ db_session.add(
+ DocumentChunk(
+ chunk_hash="h1",
+ source_type="document",
+ source_id="doc123",
+ collection_name="collection_coll-A",
+ chunk_text="Collection A chunk text",
+ chunk_index=5,
+ start_char=0,
+ end_char=23,
+ word_count=4,
+ embedding_id="e1",
+ embedding_model="model",
+ embedding_model_type="openai",
+ )
+ )
+ db_session.add(
+ DocumentChunk(
+ chunk_hash="h2",
+ source_type="document",
+ source_id="doc123",
+ collection_name="collection_coll-B",
+ chunk_text="Collection B chunk text",
+ chunk_index=5,
+ start_char=0,
+ end_char=23,
+ word_count=4,
+ embedding_id="e2",
+ embedding_model="model",
+ embedding_model_type="openai",
+ )
+ )
+ db_session.commit()
+
+ @contextmanager
+ def mock_get_user_db_session(username):
+ yield db_session
+
+ settings = {"_username": "testuser"}
+ engine = LibraryRAGSearchEngine(settings_snapshot=settings)
+
+ with patch(
+ "local_deep_research.database.session_context.get_user_db_session",
+ side_effect=mock_get_user_db_session,
+ ):
+ # Query specifying coll-B should resolve chunk from coll-B
+ items_b = [
+ {
+ "source_id": "doc123",
+ "metadata": {
+ "chunk_index": 5,
+ "document_id": "doc123",
+ "collection_id": "coll-B",
+ },
+ "content": "old snippet",
+ }
+ ]
+ result_b = engine._get_full_content(items_b)
+ assert len(result_b) == 1
+ assert result_b[0]["content"] == "Collection B chunk text"
+
+ # Query specifying coll-A should resolve chunk from coll-A
+ items_a = [
+ {
+ "source_id": "doc123",
+ "metadata": {
+ "chunk_index": 5,
+ "document_id": "doc123",
+ "collection_id": "coll-A",
+ },
+ "content": "old snippet",
+ }
+ ]
+ result_a = engine._get_full_content(items_a)
+ assert len(result_a) == 1
+ assert result_a[0]["content"] == "Collection A chunk text"
+
+ def test_get_full_content_reports_missing_chunk_without_fallback(self):
+ """When chunk_index is targeted but chunk is missing, reports not found rather than full document."""
+ from local_deep_research.web_search_engines.engines.search_engine_library import (
+ LibraryRAGSearchEngine,
+ )
+
+ settings = {"_username": "testuser"}
+ engine = LibraryRAGSearchEngine(settings_snapshot=settings)
+
+ with patch(
+ "local_deep_research.database.session_context.get_user_db_session"
+ ) as mock_session_cm:
+ mock_session = Mock()
+ query_mock = Mock()
+ mock_session.query.return_value = query_mock
+ query_mock.filter.return_value = query_mock
+ query_mock.order_by.return_value = query_mock
+ query_mock.first.return_value = None
+ mock_session_cm.return_value.__enter__.return_value = mock_session
+
+ items = [
+ {
+ "source_id": "doc123",
+ "metadata": {"chunk_index": 5, "document_id": "doc123"},
+ "content": "old snippet",
+ }
+ ]
+ result = engine._get_full_content(items)
+
+ assert len(result) == 1
+ assert (
+ result[0]["content"] == "Chunk 5 not found for document doc123."
+ )
+
+ def test_get_full_content_returns_empty_when_chunk_text_empty(self):
+ """When chunk exists but chunk_text is empty, returns empty content."""
+ from local_deep_research.web_search_engines.engines.search_engine_library import (
+ LibraryRAGSearchEngine,
+ )
+
+ settings = {"_username": "testuser"}
+ engine = LibraryRAGSearchEngine(settings_snapshot=settings)
+
+ chunk = Mock()
+ chunk.chunk_text = ""
+
+ with patch(
+ "local_deep_research.database.session_context.get_user_db_session"
+ ) as mock_session_cm:
+ mock_session = Mock()
+ query_mock = Mock()
+ mock_session.query.return_value = query_mock
+ query_mock.filter.return_value = query_mock
+ query_mock.order_by.return_value = query_mock
+ query_mock.first.return_value = chunk
+ mock_session_cm.return_value.__enter__.return_value = mock_session
+
+ items = [
+ {
+ "source_id": "doc123",
+ "metadata": {"chunk_index": 5, "document_id": "doc123"},
+ "content": "old snippet",
+ }
+ ]
+ result = engine._get_full_content(items)
+
+ assert len(result) == 1
+ assert result[0]["content"] == ""
class TestClose: