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: eliminate document content duplication for library resources (#2582)

LearningCircuit2b17c92d5dde
diff --git a/src/local_deep_research/database/initialize.py b/src/local_deep_research/database/initialize.py
index c3712a1a01..96bdb3c274 100644
--- a/src/local_deep_research/database/initialize.py
+++ b/src/local_deep_research/database/initialize.py
@@ -203,6 +203,11 @@ def _run_migrations(engine: Engine) -> None:
inspector = inspect(engine)
# Migration: Add progress tracking columns to task_metadata
+ if inspector.has_table("research_resources"):
+ _add_column_if_not_exists(
+ engine, "research_resources", "document_id", "TEXT"
+ )
+
if inspector.has_table("task_metadata"):
_add_column_if_not_exists(
engine, "task_metadata", "progress_current", "INTEGER", "0"
diff --git a/src/local_deep_research/database/models/library.py b/src/local_deep_research/database/models/library.py
index e63958cc62..d42a7fffa0 100644
--- a/src/local_deep_research/database/models/library.py
+++ b/src/local_deep_research/database/models/library.py
@@ -281,7 +281,11 @@ class Document(Base):
# Relationships
source_type = relationship("SourceType", backref="documents")
- resource = relationship("ResearchResource", backref="documents")
+ resource = relationship(
+ "ResearchResource",
+ foreign_keys="[Document.resource_id]",
+ backref="documents",
+ )
research = relationship("ResearchHistory", backref="documents")
collections = relationship(
"DocumentCollection",
diff --git a/src/local_deep_research/database/models/research.py b/src/local_deep_research/database/models/research.py
index 11bf54a348..a27c55c7a4 100644
--- a/src/local_deep_research/database/models/research.py
+++ b/src/local_deep_research/database/models/research.py
@@ -193,9 +193,16 @@ class ResearchResource(Base):
source_type = Column(Text)
resource_metadata = Column("metadata", JSON)
created_at = Column(String, nullable=False)
+ document_id = Column(
+ String(36),
+ ForeignKey("documents.id", ondelete="SET NULL"),
+ nullable=True,
+ index=True,
+ )
- # Relationship
+ # Relationships
research = relationship("ResearchHistory", back_populates="resources")
+ document = relationship("Document", foreign_keys=[document_id])
def __repr__(self):
return f"<ResearchResource(title='{self.title}', url='{self.url}')>"
diff --git a/src/local_deep_research/research_library/routes/library_routes.py b/src/local_deep_research/research_library/routes/library_routes.py
index 84066faccc..6c47aa9835 100644
--- a/src/local_deep_research/research_library/routes/library_routes.py
+++ b/src/local_deep_research/research_library/routes/library_routes.py
@@ -38,7 +38,7 @@ from ...library.download_management import ResourceFilter
from ..services.download_service import DownloadService
from ..services.library_service import LibraryService
from ..services.pdf_storage_manager import PDFStorageManager
-from ..utils import handle_api_error
+from ..utils import get_document_for_resource, handle_api_error
from ...utilities.db_utils import get_settings_manager
from ...config.paths import get_library_directory
from ...web.exceptions import AuthenticationRequiredError
@@ -1069,7 +1069,10 @@ def queue_all_undownloaded():
db_session.query(ResearchResource)
.outerjoin(
Document,
- (ResearchResource.id == Document.resource_id)
+ (
+ (ResearchResource.id == Document.resource_id)
+ | (ResearchResource.document_id == Document.id)
+ )
& (Document.status == "completed"),
)
.filter(Document.id.is_(None))
@@ -1212,11 +1215,7 @@ def get_research_sources(research_id):
for idx, resource in enumerate(resources, 1):
# Check if document exists
- document = (
- db_session.query(Document)
- .filter_by(resource_id=resource.id)
- .first()
- )
+ document = get_document_for_resource(db_session, resource)
# Get domain from URL
domain = ""
@@ -1285,11 +1284,7 @@ def check_downloads():
for resource in resources:
# Check if document exists
- document = (
- db_session.query(Document)
- .filter_by(resource_id=resource.id)
- .first()
- )
+ document = get_document_for_resource(db_session, resource)
if document and document.status == "completed":
download_status[resource.url] = {
@@ -1338,13 +1333,9 @@ def download_source():
return jsonify({"error": "Resource not found"}), 404
# Check if already downloaded
- existing = (
- db_session.query(Document)
- .filter_by(resource_id=resource.id)
- .first()
- )
+ existing = get_document_for_resource(db_session, resource)
- if existing and existing.download_status == "completed":
+ if existing and existing.status == "completed":
return jsonify(
{
"success": True,
diff --git a/src/local_deep_research/research_library/services/download_service.py b/src/local_deep_research/research_library/services/download_service.py
index 92465fca3f..f36398a96d 100644
--- a/src/local_deep_research/research_library/services/download_service.py
+++ b/src/local_deep_research/research_library/services/download_service.py
@@ -19,7 +19,6 @@ from urllib.parse import urlparse
import requests
from loguru import logger
-from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
import pdfplumber
from pypdf import PdfReader
@@ -44,6 +43,7 @@ from ...utilities.db_utils import get_settings_manager
from ...library.download_management import RetryManager
from ...config.paths import get_library_directory
from ..utils import (
+ get_document_for_resource,
get_url_hash,
get_absolute_path_from_settings,
)
@@ -301,6 +301,10 @@ class DownloadService:
for resource in resources:
if self._is_downloadable(resource):
+ # Library resources linked via document_id are already done
+ if resource.document_id:
+ continue
+
# Check if already queued
existing_queue = (
session.query(LibraryDownloadQueue)
@@ -875,92 +879,6 @@ class DownloadService:
# Fallback: Download PDF and extract
return self._fallback_pdf_extraction(session, resource)
- def _link_library_text_to_resource(
- self, session, resource, text, extraction_method, extraction_source
- ):
- """Ensure a Document record is linked to the ResearchResource.
-
- Downstream consumers (get_research_sources, check_downloads,
- queue_all_undownloaded, RAG indexing) look up Documents by
- resource_id. Library text extraction operates on the *original*
- Document (looked up by its UUID), so a second Document linked to
- the ResearchResource must be created for proper integration.
- """
- # Already linked?
- existing = (
- session.query(Document).filter_by(resource_id=resource.id).first()
- )
- if existing:
- if not existing.text_content:
- existing.text_content = text
- existing.extraction_method = extraction_method
- existing.extraction_source = extraction_source
- existing.extraction_quality = "high"
- existing.character_count = len(text)
- existing.word_count = len(text.split())
- return
-
- # Capture before try — rollback expires non-PK/FK attributes
- resource_url = resource.url
- resource_title = resource.title
-
- # Create new Document linked to this resource
- try:
- self._save_text_with_db(
- resource,
- text,
- session,
- extraction_method=extraction_method,
- extraction_source=extraction_source,
- )
- except IntegrityError:
- session.rollback()
- logger.warning(
- f"Duplicate document hash for resource {resource.id}, using resource-scoped hash"
- )
- # Duplicate hash (same content already stored) — create with resource-scoped hash
- text_hash = hashlib.sha256(
- f"libref:{resource.id}:{text[:100]}".encode()
- ).hexdigest()
- source_type_id = get_source_type_id(
- self.username, "research_download", self.password
- )
- new_doc = Document(
- id=str(uuid.uuid4()),
- source_type_id=source_type_id,
- resource_id=resource.id,
- research_id=resource.research_id,
- document_hash=text_hash,
- original_url=resource_url,
- file_path="text_only_not_stored",
- file_size=len(text),
- file_type="text",
- mime_type="text/plain",
- title=resource_title,
- text_content=text,
- character_count=len(text),
- word_count=len(text.split()),
- extraction_method=extraction_method,
- extraction_source=extraction_source,
- extraction_quality="high",
- status=DocumentStatus.COMPLETED,
- processed_at=datetime.now(UTC),
- )
- session.add(new_doc)
-
- # Link to Library collection
- library_collection = (
- session.query(Collection).filter_by(name="Library").first()
- )
- if library_collection:
- doc_collection = DocumentCollection(
- document_id=new_doc.id,
- collection_id=library_collection.id,
- indexed=False,
- chunk_count=0,
- )
- session.add(doc_collection)
-
def _try_library_text_extraction(
self, session, resource
) -> Tuple[bool, Optional[str]]:
@@ -1001,13 +919,7 @@ class DownloadService:
and doc.extraction_method != "failed"
):
logger.info(f"Library document {doc_id} already has text content")
- self._link_library_text_to_resource(
- session,
- resource,
- doc.text_content,
- "library_reference",
- "library_document",
- )
+ resource.document_id = doc.id
session.commit()
return True, None
@@ -1043,14 +955,7 @@ class DownloadService:
doc.extraction_source = "pdfplumber"
doc.extraction_quality = "medium"
- # Also create a Document linked to the ResearchResource
- self._link_library_text_to_resource(
- session,
- resource,
- text,
- "library_pdf_extraction",
- "pdfplumber",
- )
+ resource.document_id = doc.id
session.commit()
logger.info(
@@ -1660,11 +1565,7 @@ class DownloadService:
.first()
)
else:
- doc = (
- session.query(Document)
- .filter_by(resource_id=resource.id)
- .first()
- )
+ doc = get_document_for_resource(session, resource)
if doc:
# Update existing document with extracted text
diff --git a/src/local_deep_research/research_library/services/library_service.py b/src/local_deep_research/research_library/services/library_service.py
index eda48facf9..cd7825c705 100644
--- a/src/local_deep_research/research_library/services/library_service.py
+++ b/src/local_deep_research/research_library/services/library_service.py
@@ -13,7 +13,7 @@ from typing import Dict, List, Optional
from urllib.parse import urlparse
from loguru import logger
-from sqlalchemy import and_, or_, func, Integer, case
+from sqlalchemy import and_, or_, func, case
from ...database.models.download_tracker import DownloadTracker
from ...database.models.library import (
@@ -239,7 +239,8 @@ class LibraryService:
)
.outerjoin(
ResearchResource,
- Document.resource_id == ResearchResource.id,
+ (Document.resource_id == ResearchResource.id)
+ | (ResearchResource.document_id == Document.id),
)
.outerjoin(
ResearchHistory,
@@ -435,21 +436,30 @@ class LibraryService:
results = (
session.query(
ResearchHistory,
- func.count(ResearchResource.id).label("total_resources"),
+ func.count(func.distinct(ResearchResource.id)).label(
+ "total_resources"
+ ),
func.count(
- case(
- (Document.status == "completed", 1),
- else_=None,
+ func.distinct(
+ case(
+ (Document.status == "completed", Document.id),
+ else_=None,
+ )
)
).label("downloaded_count"),
- func.sum(
- func.cast(
- ResearchResource.url.like("%.pdf")
- | ResearchResource.url.like("%arxiv.org%")
- | ResearchResource.url.like(
- "%ncbi.nlm.nih.gov/pmc%"
- ),
- Integer,
+ func.count(
+ func.distinct(
+ case(
+ (
+ ResearchResource.url.like("%.pdf")
+ | ResearchResource.url.like("%arxiv.org%")
+ | ResearchResource.url.like(
+ "%ncbi.nlm.nih.gov/pmc%"
+ ),
+ ResearchResource.id,
+ ),
+ else_=None,
+ )
)
).label("downloadable_count"),
)
@@ -459,7 +469,8 @@ class LibraryService:
)
.outerjoin(
Document,
- ResearchResource.id == Document.resource_id,
+ (ResearchResource.id == Document.resource_id)
+ | (ResearchResource.document_id == Document.id),
)
.group_by(ResearchHistory.id)
.order_by(ResearchHistory.created_at.desc())
@@ -542,7 +553,8 @@ class LibraryService:
session.query(Document, ResearchResource, ResearchHistory)
.outerjoin(
ResearchResource,
- Document.resource_id == ResearchResource.id,
+ (Document.resource_id == ResearchResource.id)
+ | (ResearchResource.document_id == Document.id),
)
.outerjoin(
ResearchHistory,
diff --git a/src/local_deep_research/research_library/utils/__init__.py b/src/local_deep_research/research_library/utils/__init__.py
index e1d275fd06..d47109b553 100644
--- a/src/local_deep_research/research_library/utils/__init__.py
+++ b/src/local_deep_research/research_library/utils/__init__.py
@@ -10,9 +10,24 @@ from flask import jsonify
from loguru import logger
from ...config.paths import get_library_directory
+from ...database.models.library import Document
from ...security.path_validator import PathValidator
+def get_document_for_resource(session, resource):
+ """Get Document for a ResearchResource.
+
+ Checks resource.document_id first (library resources point directly
+ to existing Documents), falls back to Document.resource_id lookup
+ (web downloads create Documents with resource_id set).
+ """
+ if resource.document_id:
+ return (
+ session.query(Document).filter_by(id=resource.document_id).first()
+ )
+ return session.query(Document).filter_by(resource_id=resource.id).first()
+
+
def get_url_hash(url: str) -> str:
"""
Generate a SHA256 hash of a URL.
diff --git a/tests/research_library/services/test_download_service.py b/tests/research_library/services/test_download_service.py
index 1a9c4d0a16..46bca7b620 100644
--- a/tests/research_library/services/test_download_service.py
+++ b/tests/research_library/services/test_download_service.py
@@ -827,6 +827,62 @@ class TestDownloadServiceQueueResearchDownloads:
# Only arxiv URL should be queued (HTML page is not downloadable)
assert queued_count >= 0
+ def test_queue_skips_resources_with_document_id(self, mocker):
+ """Resources that already have document_id are skipped (not queued)."""
+ mock_settings = Mock()
+ mock_settings.get_setting.return_value = "/tmp/test_library"
+ mocker.patch(
+ "local_deep_research.research_library.services.download_service.get_settings_manager",
+ return_value=mock_settings,
+ )
+ mocker.patch("pathlib.Path.mkdir")
+ mocker.patch(
+ "local_deep_research.research_library.services.download_service.RetryManager"
+ )
+
+ # Mock session
+ mock_session = MagicMock()
+ mock_session.__enter__ = Mock(return_value=mock_session)
+ mock_session.__exit__ = Mock(return_value=False)
+
+ # Resource WITH document_id (should be skipped)
+ resource_linked = Mock()
+ resource_linked.id = 10
+ resource_linked.url = "https://arxiv.org/abs/2301.00010"
+ resource_linked.document_id = "existing-doc-uuid"
+
+ # Resource WITHOUT document_id (should be queued)
+ resource_unlinked = Mock()
+ resource_unlinked.id = 11
+ resource_unlinked.url = "https://arxiv.org/abs/2301.00011"
+ resource_unlinked.document_id = None
+
+ mock_session.query.return_value.filter_by.return_value.all.return_value = [
+ resource_linked,
+ resource_unlinked,
+ ]
+ # No existing queue entry for unlinked resource
+ mock_session.query.return_value.filter_by.return_value.first.return_value = None
+
+ mocker.patch(
+ "local_deep_research.research_library.services.download_service.get_user_db_session",
+ return_value=mock_session,
+ )
+ mocker.patch(
+ "local_deep_research.database.library_init.get_default_library_id",
+ return_value="default-lib-id",
+ )
+
+ from local_deep_research.research_library.services.download_service import (
+ DownloadService,
+ )
+
+ service = DownloadService(username="test_user")
+ queued_count = service.queue_research_downloads("research-456")
+
+ # Only unlinked resource should be queued
+ assert queued_count == 1
+
class TestDownloadServiceDownloadResource:
"""Tests for download_resource method."""
@@ -1764,6 +1820,7 @@ class TestLibraryTextExtraction:
# Mock Document with existing text
mock_doc = Mock()
+ mock_doc.id = "doc-uuid-123"
mock_doc.text_content = "Existing extracted text content"
mock_doc.extraction_method = "pdf_extraction"
@@ -1775,6 +1832,8 @@ class TestLibraryTextExtraction:
)
assert success is True
assert error is None
+ assert resource.document_id == "doc-uuid-123"
+ mock_session.commit.assert_called_once()
def test_library_resource_id_from_url_when_no_metadata(self, mocker):
"""Resource with source_type='web' but library URL is still handled."""
@@ -1831,6 +1890,7 @@ class TestLibraryTextExtraction:
# Mock Document without text
mock_doc = Mock()
+ mock_doc.id = "doc-uuid-789"
mock_doc.text_content = None
mock_doc.extraction_method = None
@@ -1862,6 +1922,7 @@ class TestLibraryTextExtraction:
assert mock_doc.text_content == "Extracted text from PDF document"
assert mock_doc.extraction_method == "pdf_extraction"
assert mock_doc.word_count == 5
+ assert resource.document_id == "doc-uuid-789"
mock_session.commit.assert_called_once()
def test_library_resource_no_doc_id(self, mocker):
@@ -1913,9 +1974,6 @@ class TestLibraryTextExtraction:
return_value="Re-extracted text",
)
- # Mock _link_library_text_to_resource to avoid DB interactions
- mocker.patch.object(service, "_link_library_text_to_resource")
-
success, error = service._try_library_text_extraction(
mock_session, resource
)
@@ -1924,6 +1982,8 @@ class TestLibraryTextExtraction:
# Verify text was updated from PDF extraction, not the old "failed" text
assert mock_doc.text_content == "Re-extracted text"
assert mock_doc.extraction_method == "pdf_extraction"
+ # Verify resource points directly to the document
+ assert resource.document_id == mock_doc.id
def test_library_resource_no_pdf_available(self, mocker):
"""Returns (False, error) when document has no text and load_pdf returns None."""
@@ -2037,7 +2097,7 @@ class TestLibraryTextExtraction:
mock_try.assert_called_once_with(mock_session, mock_resource)
def test_library_resource_creates_linked_document(self, mocker):
- """After successful extraction, _link_library_text_to_resource is called."""
+ """After successful extraction, resource.document_id is set."""
service = self._create_service(mocker)
resource = Mock()
@@ -2050,193 +2110,60 @@ class TestLibraryTextExtraction:
# Document with existing text
mock_doc = Mock()
+ mock_doc.id = "doc-uuid-link"
mock_doc.text_content = "Library document text"
mock_doc.extraction_method = "pdf_extraction"
mock_session = Mock()
mock_session.query.return_value.filter_by.return_value.first.return_value = mock_doc
- # Spy on _link_library_text_to_resource
- mock_link = mocker.patch.object(
- service, "_link_library_text_to_resource"
- )
-
success, error = service._try_library_text_extraction(
mock_session, resource
)
assert success is True
assert error is None
- mock_link.assert_called_once_with(
- mock_session,
- resource,
- "Library document text",
- "library_reference",
- "library_document",
- )
+ assert resource.document_id == "doc-uuid-link"
mock_session.commit.assert_called_once()
-class TestLinkLibraryTextToResource:
- """Tests for _link_library_text_to_resource."""
-
- MODULE = "local_deep_research.research_library.services.download_service"
+class TestGetDocumentForResource:
+ """Tests for get_document_for_resource helper."""
- def _make_service(self, mocker):
- mock_settings = Mock()
- mock_settings.get_setting.return_value = "/tmp/test_library"
- mocker.patch(
- f"{self.MODULE}.get_settings_manager", return_value=mock_settings
- )
- mocker.patch("pathlib.Path.mkdir")
- mocker.patch(f"{self.MODULE}.RetryManager", return_value=Mock())
- mocker.patch(f"{self.MODULE}.DownloadTracker", return_value=Mock())
- mocker.patch(f"{self.MODULE}.requests.Session", return_value=Mock())
-
- from local_deep_research.research_library.services.download_service import (
- DownloadService,
- )
-
- return DownloadService(username="test_user", password="test_pass")
-
- def test_link_updates_existing_document_without_text(self, mocker):
- """Existing Document with text_content=None gets updated."""
- service = self._make_service(mocker)
- session = MagicMock()
- resource = Mock(id="res-1", url="http://example.com")
-
- existing_doc = Mock(text_content=None)
- session.query.return_value.filter_by.return_value.first.return_value = (
- existing_doc
- )
-
- text = "Hello world foo bar"
- service._link_library_text_to_resource(
- session, resource, text, "library_reference", "library_document"
- )
-
- assert existing_doc.text_content == text
- assert existing_doc.extraction_method == "library_reference"
- assert existing_doc.extraction_source == "library_document"
- assert existing_doc.extraction_quality == "high"
- assert existing_doc.character_count == len(text)
- assert existing_doc.word_count == len(text.split())
-
- def test_link_skips_existing_document_with_text(self, mocker):
- """Existing Document with text already set is left unchanged."""
- service = self._make_service(mocker)
- session = MagicMock()
- resource = Mock(id="res-1", url="http://example.com")
-
- existing_doc = Mock(text_content="already has text")
- session.query.return_value.filter_by.return_value.first.return_value = (
- existing_doc
+ def test_returns_document_via_document_id(self):
+ """Library resources with document_id find the Document by ID."""
+ from local_deep_research.research_library.utils import (
+ get_document_for_resource,
)
- service._link_library_text_to_resource(
- session,
- resource,
- "new text",
- "library_reference",
- "library_document",
- )
-
- # text_content should remain unchanged
- assert existing_doc.text_content == "already has text"
- session.add.assert_not_called()
-
- def test_link_creates_new_document_via_save_text(self, mocker):
- """No existing Document → _save_text_with_db called."""
- service = self._make_service(mocker)
session = MagicMock()
- resource = Mock(id="res-1", url="http://example.com", title="Test")
+ resource = Mock(id=1, document_id="doc-uuid-123")
- # No existing document
+ mock_doc = Mock()
session.query.return_value.filter_by.return_value.first.return_value = (
- None
+ mock_doc
)
- mock_save = mocker.patch.object(service, "_save_text_with_db")
-
- service._link_library_text_to_resource(
- session,
- resource,
- "some text",
- "library_reference",
- "library_document",
+ result = get_document_for_resource(session, resource)
+ assert result is mock_doc
+ session.query.return_value.filter_by.assert_called_with(
+ id="doc-uuid-123"
)
- mock_save.assert_called_once_with(
- resource,
- "some text",
- session,
- extraction_method="library_reference",
- extraction_source="library_document",
+ def test_falls_back_to_resource_id(self):
+ """Web resources without document_id use Document.resource_id lookup."""
+ from local_deep_research.research_library.utils import (
+ get_document_for_resource,
)
- session.rollback.assert_not_called()
-
- def test_link_handles_hash_collision(self, mocker):
- """IntegrityError from _save_text_with_db triggers resource-scoped hash fallback."""
- from sqlalchemy.exc import IntegrityError
- service = self._make_service(mocker)
session = MagicMock()
- resource = Mock(
- id="res-1",
- url="http://example.com",
- title="Test Resource",
- research_id="research-1",
- )
+ resource = Mock(id=42, document_id=None)
- # No existing document
+ mock_doc = Mock()
session.query.return_value.filter_by.return_value.first.return_value = (
- None
- )
-
- # _save_text_with_db raises IntegrityError
- mocker.patch.object(
- service,
- "_save_text_with_db",
- side_effect=IntegrityError(
- "dup", {}, Exception("unique constraint")
- ),
- )
-
- mocker.patch(
- f"{self.MODULE}.get_source_type_id", return_value="src-type-1"
- )
- mocker.patch(f"{self.MODULE}.uuid.uuid4", return_value="fake-uuid-1234")
-
- MockDocument = mocker.patch(f"{self.MODULE}.Document")
- MockDocumentCollection = mocker.patch(
- f"{self.MODULE}.DocumentCollection"
- )
- mocker.patch(f"{self.MODULE}.DocumentStatus")
-
- # Set up the Library collection query for the fallback path
- mock_library_collection = Mock(id="lib-col-1", name="Library")
-
- def query_side_effect(model_class):
- chain = MagicMock()
- if (
- hasattr(model_class, "__name__")
- and model_class.__name__ == "Collection"
- ):
- chain.filter_by.return_value.first.return_value = (
- mock_library_collection
- )
- else:
- chain.filter_by.return_value.first.return_value = None
- return chain
-
- session.query.side_effect = query_side_effect
-
- text = "some library text"
- service._link_library_text_to_resource(
- session, resource, text, "library_reference", "library_document"
+ mock_doc
)
- session.rollback.assert_called_once()
- MockDocument.assert_called_once()
- assert session.add.call_count == 2
- MockDocumentCollection.assert_called_once()
+ result = get_document_for_resource(session, resource)
+ assert result is mock_doc
+ session.query.return_value.filter_by.assert_called_with(resource_id=42)