~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): preserve canonical text on duplicate downloads (#7229)
LearningCircuit8f786a225a68
diff --git a/changelog.d/7161.bugfix.md b/changelog.d/7161.bugfix.mdnew file mode 100644index 0000000000..73fd83602c--- /dev/null+++ b/changelog.d/7161.bugfix.md@@ -0,0 +1 @@+Duplicate paper downloads preserve better existing text and its extraction provenance. Accepted improvements mark every affected collection for reindexing without changing the PDF's content identity or double-counting documents and chunks in index totals.diff --git a/src/local_deep_research/research_library/services/download_service.py b/src/local_deep_research/research_library/services/download_service.pyindex 184d456349..28e23cfa23 100644--- a/src/local_deep_research/research_library/services/download_service.py+++ b/src/local_deep_research/research_library/services/download_service.py@@ -22,6 +22,7 @@ from urllib.parse import urlparseimport requestsfrom loguru import loggerfrom ...security import redact_url_for_log+from sqlalchemy import funcfrom sqlalchemy.orm import Sessionimport pdfplumberfrom pypdf import PdfReader@@ -55,8 +56,11 @@ from ...security.secure_logging import log_exception_typefrom ...database.models.library import (Collection,Document as Document,+ DocumentCollection,DocumentStatus,DownloadQueue as LibraryDownloadQueue,+ RAGIndex,+ RagDocumentStatus,)from .pdf_storage_manager import (DEFAULT_MAX_PDF_SIZE_MB,@@ -106,6 +110,24 @@ from ...utilities.pdf_extraction_limits import ()+def _text_extraction_quality(method: str | None, source: str | None) -> str:+ if method in {"native_api", "html_extraction"}:+ return "high"+ if method == "pdfplumber" or (+ method == "pdf_extraction" and source == "pdfplumber"+ ):+ return "medium"+ return "low"+++def _text_extraction_rank(quality: str, method: str, source: str) -> int:+ # The arXiv API fallback is explicitly metadata/abstract only. Its historic+ # "high" quality label describes the API, not full-paper coverage.+ if method == "native_api" and source == "arxiv_api":+ return -1+ return {"low": 0, "medium": 1, "high": 2}[quality]++def _arxiv_text_provenance(source: ArxivTextSource) -> tuple[str, str]:match source:case ArxivTextSource.ARXIV_HTML:@@ -2823,18 +2845,15 @@ class DownloadService:None (previously returned text file path, now removed)"""try:+ if not text.strip():+ return None+# Calculate text metadata for databaseword_count = len(text.split())character_count = len(text)- if extraction_method in {"native_api", "html_extraction"}:- extraction_quality = "high"- elif extraction_method == "pdfplumber" or (- extraction_method == "pdf_extraction"- and extraction_source == "pdfplumber"- ):- extraction_quality = "medium"- else:- extraction_quality = "low"+ extraction_quality = _text_extraction_quality(+ extraction_method, extraction_source+ )# Find the document by pdf_document_id or resource_id. Both reads# touch scalar columns (`document_id`, `id`) that are eagerly@@ -2852,11 +2871,103 @@ class DownloadService:doc = get_document_for_resource(session, resource)if doc:+ old_text = doc.text_content or ""+ if old_text.strip():+ # Duplicate PDFs share one extraction. Automatically replace+ # it only with nondecreasing quality AND text coverage. A+ # native API abstract must not displace a longer full paper;+ # whitespace padding is not additional coverage. Ties keep+ # the original text and provenance stable.+ ranks = {"low": 0, "medium": 1, "high": 2}+ old_quality = doc.extraction_quality+ if old_quality not in ranks:+ old_quality = _text_extraction_quality(+ doc.extraction_method, doc.extraction_source+ )+ old_rank = _text_extraction_rank(+ old_quality,+ doc.extraction_method,+ doc.extraction_source,+ )+ new_rank = _text_extraction_rank(+ extraction_quality, extraction_method, extraction_source+ )+ old_size = len("".join(old_text.split()))+ new_size = len("".join(text.split()))+ if (+ new_rank < old_rank+ or new_size < old_size+ or (new_rank == old_rank and new_size == old_size)+ ):+ if doc.status == DocumentStatus.FAILED:+ doc.status = DocumentStatus.COMPLETED+ doc.error_message = None+ return None++ # Claim the observed extraction before changing it. SQLite+ # ignores SELECT FOR UPDATE: a conditional no-op write instead+ # holds its write lock until the caller commits. If another+ # worker already changed the extraction, preserve that result.+ claimed = (+ session.query(Document)+ .filter(+ Document.id == doc.id,+ Document.text_content == doc.text_content,+ Document.extraction_quality == doc.extraction_quality,+ Document.extraction_method == doc.extraction_method,+ Document.extraction_source == doc.extraction_source,+ Document.document_hash == doc.document_hash,+ Document.status == doc.status,+ )+ .update({Document.id: doc.id}, synchronize_session=False)+ )+ if claimed == 0:+ session.expire(doc)+ return None++ if old_text != text:+ # The legacy flag and canonical per-index marker must both+ # move with the text, in this transaction. Leave chunk rows+ # available for replace-on-reindex to remove their vectors.+ affected_indexes = (+ session.query(RagDocumentStatus.rag_index_id)+ .filter_by(document_id=doc.id)+ .distinct()+ .all()+ )+ session.query(DocumentCollection).filter_by(+ document_id=doc.id+ ).update(+ {DocumentCollection.indexed: False},+ synchronize_session="fetch",+ )+ session.query(RagDocumentStatus).filter_by(+ document_id=doc.id+ ).delete(synchronize_session="fetch")+ # Reindex treats a removed status as a new contribution.+ # Remove its old contribution now, in the same transaction,+ # or each text improvement inflates the index totals.+ for (index_id,) in affected_indexes:+ chunk_count, document_count = (+ session.query(+ func.sum(RagDocumentStatus.chunk_count),+ func.count(),+ )+ .filter_by(rag_index_id=index_id)+ .one()+ )+ session.query(RAGIndex).filter_by(id=index_id).update(+ {+ RAGIndex.chunk_count: chunk_count or 0,+ RAGIndex.total_documents: document_count,+ },+ synchronize_session="fetch",+ )+# Update existing document with extracted text. Only replace- # document_hash when transitioning from FAILED — see issue- # #3827. PDF-bytes hashes set at creation must remain stable;- # text-content hashes collide far more often (identical- # extracted text from different PDFs).+ # a failed placeholder's hash on a text-only retry (#3827).+ # An explicit PDF document already has the downloaded byte+ # hash, including a failed canonical document reused by dedup.was_failed = doc.status == DocumentStatus.FAILEDdoc.text_content = textdoc.character_count = character_count@@ -2864,10 +2975,12 @@ class DownloadService:doc.extraction_method = extraction_methoddoc.extraction_source = extraction_sourcedoc.status = DocumentStatus.COMPLETED- if was_failed:+ if was_failed and pdf_document_id is None:doc.document_hash = hashlib.sha256(text.encode()).hexdigest()+ if was_failed:+ doc.error_message = Nonedoc.processed_at = datetime.now(UTC)doc.extraction_quality = extraction_qualitydiff --git a/tests/research_library/services/test_download_service_arxiv_provenance.py b/tests/research_library/services/test_download_service_arxiv_provenance.pyindex 9517b7ff92..6dff2e3f6b 100644--- a/tests/research_library/services/test_download_service_arxiv_provenance.py+++ b/tests/research_library/services/test_download_service_arxiv_provenance.py@@ -863,9 +863,10 @@ def test_existing_document_quality_uses_unified_mapping(source,expected_quality,):- # Given an existing completed document+ # Given an existing completed document without extracted textdocument = MagicMock()document.status = DocumentStatus.COMPLETED+ document.text_content = Nonesession = MagicMock()session.query.return_value.filter_by.return_value.first.return_value = (documentdiff --git a/tests/research_library/services/test_download_service_coverage.py b/tests/research_library/services/test_download_service_coverage.pyindex e6cf0fd537..68ecaa0b9c 100644--- a/tests/research_library/services/test_download_service_coverage.py+++ b/tests/research_library/services/test_download_service_coverage.py@@ -1386,6 +1386,7 @@ class TestSaveTextWithDb:def test_update_existing_doc_with_pdf_document_id(self, svc):session = MagicMock()doc = MagicMock()+ doc.text_content = Nonesession.query.return_value.filter_by.return_value.first.return_value = (doc)diff --git a/tests/research_library/services/test_download_text_quality.py b/tests/research_library/services/test_download_text_quality.pynew file mode 100644index 0000000000..3c989ebc0a--- /dev/null+++ b/tests/research_library/services/test_download_text_quality.py@@ -0,0 +1,712 @@+"""Canonical extraction selection across real PDF download transactions."""++import hashlib+from datetime import UTC, datetime+from types import SimpleNamespace+from unittest.mock import Mock++import pytest+from sqlalchemy import create_engine, event+from sqlalchemy.orm import sessionmaker++from local_deep_research.database import (+ encrypted_db,+ library_init,+ thread_local_session,+)+from local_deep_research.database.models import Base+from local_deep_research.database.models.library import (+ Collection,+ Document,+ DocumentBlob,+ DocumentChunk,+ DocumentCollection,+ DocumentStatus,+ EmbeddingProvider,+ RAGIndex,+ RagDocumentStatus,+ SourceType,+)+from local_deep_research.database.models.research import (+ ResearchHistory,+ ResearchResource,+)+from local_deep_research.library.download_management import RetryManager+from local_deep_research.research_library.downloaders.arxiv import (+ ArxivDownloader,+ ArxivTextResult,+ ArxivTextSource,+)+from local_deep_research.research_library.services import download_service+from local_deep_research.web.routers import rag+++ORIGINAL = "The original paper has full results and detailed methods."+LONGER = (+ ORIGINAL + " Additional experiments and conclusions complete the paper."+)+STAMP = datetime(2026, 10, 1, tzinfo=UTC)+TEXT_FIELDS = (+ "text_content",+ "word_count",+ "character_count",+ "extraction_method",+ "extraction_source",+ "extraction_quality",+ "processed_at",+)+++def extraction_case(tmp_path, monkeypatch):+ engine = create_engine(f"sqlite:///{tmp_path / 'quality.sqlite'}")++ @event.listens_for(engine, "connect")+ def enable_foreign_keys(connection, _record):+ connection.execute("PRAGMA foreign_keys=ON")++ Base.metadata.create_all(engine)+ sessions = sessionmaker(bind=engine)+ shared = sessions()+ monkeypatch.setattr(+ encrypted_db.db_manager, "open_user_database", lambda *args: engine+ )+ monkeypatch.setattr(+ thread_local_session, "get_metrics_session", lambda *args: shared+ )+ monkeypatch.setattr(+ download_service, "get_source_type_id", lambda *args: "source"+ )+ monkeypatch.setattr(+ download_service, "get_default_library_id", lambda *args: "library"+ )+ monkeypatch.setattr(+ library_init, "get_default_library_id", lambda *args: "library"+ )+ auto_index = Mock()+ monkeypatch.setattr(rag, "trigger_auto_index", auto_index)++ def prepare(+ text=ORIGINAL,+ quality="high",+ method="native_api",+ source="arxiv",+ incoming=LONGER,+ origin=ArxivTextSource.ARXIV_HTML,+ status=DocumentStatus.COMPLETED,+ storage="none",+ ):+ pdf = b"%PDF-1.4 identical canonical PDF content"+ pdf_hash = hashlib.sha256(pdf).hexdigest()+ with sessions() as seed:+ seed.add_all(+ [+ SourceType(+ id="source",+ name="research_download",+ display_name="Research",+ ),+ ResearchHistory(+ id="research",+ query="quality",+ mode="quick",+ status="completed",+ created_at="2026-10-01T00:00:00",+ ),+ Collection(id="library", name="Library", is_default=True),+ Collection(id="selected", name="Selected"),+ ]+ )+ seed.flush()+ resources = [+ ResearchResource(+ research_id="research",+ title="A paper",+ url=url,+ source_type="academic",+ created_at="2026-10-01T00:00:00",+ )+ for url in (+ "https://example.org/paper.pdf",+ "https://arxiv.org/abs/2601.12345",+ )+ ]+ seed.add_all(resources)+ seed.flush()+ duplicate_id = resources[1].id+ document = Document(+ id="canonical",+ source_type_id="source",+ resource_id=resources[0].id,+ research_id="research",+ document_hash=pdf_hash,+ file_type="pdf",+ file_size=len(pdf),+ storage_mode="none",+ text_content=text,+ word_count=len((text or "").split()),+ character_count=len(text or ""),+ extraction_method=method,+ extraction_source=source,+ extraction_quality=quality,+ status=status,+ processed_at=STAMP,+ )+ seed.add(document)+ seed.flush()+ # Two collections and two embedding configurations must both become+ # stale on a replacement; one auto-index target is not sufficient.+ for collection_id in ("library", "selected"):+ index = RAGIndex(+ collection_name=f"collection_{collection_id}",+ embedding_model="test",+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,+ embedding_dimension=2,+ index_path=str(tmp_path / collection_id),+ index_hash=collection_id,+ chunk_size=100,+ chunk_overlap=0,+ chunk_count=1,+ total_documents=1,+ )+ seed.add(index)+ seed.flush()+ seed.add_all(+ [+ DocumentCollection(+ document_id=document.id,+ collection_id=collection_id,+ indexed=True,+ chunk_count=1,+ last_indexed_at=STAMP,+ ),+ RagDocumentStatus(+ document_id=document.id,+ collection_id=collection_id,+ rag_index_id=index.id,+ chunk_count=1,+ indexed_at=STAMP,+ ),+ DocumentChunk(+ chunk_hash=collection_id,+ source_type="document",+ source_id=document.id,+ collection_name=f"collection_{collection_id}",+ chunk_text=text or "old text",+ chunk_index=0,+ start_char=0,+ end_char=len(text or ""),+ word_count=len((text or "").split()),+ embedding_id=collection_id,+ embedding_model="test",+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,+ ),+ ]+ )+ seed.commit()+ before = {field: getattr(document, field) for field in TEXT_FIELDS}++ service = download_service.DownloadService.__new__(+ download_service.DownloadService+ )+ service.username = "quality-user"+ service.password = "test-password"+ service.library_root = tmp_path / "library"+ service.legacy_library_root = None+ service._closed = False+ service.settings = SimpleNamespace(+ get_setting={"research_library.pdf_storage_mode": storage}.get+ )+ service.retry_manager = RetryManager(service.username, service.password)+ downloader = Mock(spec=ArxivDownloader)+ downloader.can_handle.return_value = True++ def fetch(*args, **kwargs):+ assert not shared.in_transaction()+ return SimpleNamespace(+ is_success=True, content=pdf, status_code=200, skip_reason=None+ )++ downloader.download_with_result.side_effect = fetch+ downloader.download_text_with_source.return_value = ArxivTextResult(+ text=incoming, source=origin+ )+ service.downloaders = [downloader]+ return SimpleNamespace(+ service=service,+ sessions=sessions,+ shared=shared,+ resource_id=duplicate_id,+ before=before,+ pdf=pdf,+ pdf_hash=pdf_hash,+ auto_index=auto_index,+ )++ try:+ yield prepare+ finally:+ shared.close()+ engine.dispose()++[email protected]("storage", ["none", "database"])+ "quality,method,old,incoming,origin",+ [+ (+ "high",+ "native_api",+ ORIGINAL,+ "Short extraction.",+ ArxivTextSource.LOCAL_PDF,+ ),+ ("high", "native_api", ORIGINAL, LONGER, ArxivTextSource.LOCAL_PDF),+ (+ "high",+ "html_extraction",+ ORIGINAL,+ "Short abstract.",+ ArxivTextSource.ARXIV_API,+ ),+ (+ "low",+ "pdf_extraction",+ ORIGINAL,+ "Short abstract.",+ ArxivTextSource.ARXIV_API,+ ),+ ("medium", "pdfplumber", ORIGINAL, LONGER, ArxivTextSource.LOCAL_PDF),+ (None, "native_api", ORIGINAL, LONGER, ArxivTextSource.LOCAL_PDF),+ ("high", "native_api", ORIGINAL, " \n\t", ArxivTextSource.ARXIV_HTML),+ ("low", "pdf_extraction", ORIGINAL, "", ArxivTextSource.LOCAL_PDF),+ (+ "high",+ "native_api",+ ORIGINAL,+ ORIGINAL.replace(" ", " "),+ ArxivTextSource.ARXIV_HTML,+ ),+ ],+)+def test_duplicate_preserves_better_text_and_index_state(+ extraction_case, storage, quality, method, old, incoming, origin+):+ case = extraction_case(+ text=old,+ quality=quality,+ method=method,+ incoming=incoming,+ origin=origin,+ storage=storage,+ )+ assert case.service.download_resource(case.resource_id) == (True, None)+ with case.sessions() as session:+ doc = session.query(Document).one()+ assert {+ field: getattr(doc, field) for field in TEXT_FIELDS+ } == case.before+ assert doc.document_hash == case.pdf_hash+ assert (+ session.get(ResearchResource, case.resource_id).document_id+ == doc.id+ )+ assert all(link.indexed for link in session.query(DocumentCollection))+ assert session.query(RagDocumentStatus).count() == 2+ assert session.query(DocumentChunk).count() == 2+ assert all(+ index.chunk_count == index.total_documents == 1+ for index in session.query(RAGIndex)+ )+ if storage == "database":+ assert session.get(DocumentBlob, doc.id).pdf_binary == case.pdf+ case.auto_index.assert_called_once_with(+ ["canonical"], "library", "quality-user", "test-password"+ )+ assert not case.shared.in_transaction()+++ "old,quality,incoming,origin",+ [+ (ORIGINAL, "low", LONGER, ArxivTextSource.ARXIV_HTML),+ (ORIGINAL, "high", LONGER, ArxivTextSource.ARXIV_HTML),+ (None, "high", ORIGINAL, ArxivTextSource.LOCAL_PDF),+ ("", "high", ORIGINAL, ArxivTextSource.LOCAL_PDF),+ (" \n\t", "high", ORIGINAL, ArxivTextSource.LOCAL_PDF),+ ],+)+def test_duplicate_improvement_marks_every_collection_stale(+ extraction_case, old, quality, incoming, origin+):+ case = extraction_case(+ text=old, quality=quality, incoming=incoming, origin=origin+ )+ assert case.service.download_resource(case.resource_id) == (True, None)+ with case.sessions() as session:+ doc = session.query(Document).one()+ assert doc.text_content == incoming+ assert doc.word_count == len(incoming.split())+ assert doc.character_count == len(incoming)+ assert (+ doc.extraction_method,+ doc.extraction_source,+ doc.extraction_quality,+ ) == (+ ("html_extraction", "arxiv_html", "high")+ if origin == ArxivTextSource.ARXIV_HTML+ else ("pdf_extraction", "local_pdf", "low")+ )+ assert doc.document_hash == case.pdf_hash+ assert not any(+ link.indexed for link in session.query(DocumentCollection)+ )+ assert session.query(RagDocumentStatus).count() == 0+ assert all(+ index.chunk_count == index.total_documents == 0+ for index in session.query(RAGIndex)+ )+ # Old rows identify the vectors the normal replace-on-reindex path must+ # remove. Deleting these rows here would strand the stored vectors.+ assert session.query(DocumentChunk).count() == 2+++def test_identical_text_better_provenance_does_not_invalidate_embeddings(+ extraction_case,+):+ case = extraction_case(+ quality="low",+ method="pdf_extraction",+ source="local_pdf",+ incoming=ORIGINAL,+ )+ assert case.service.download_resource(case.resource_id) == (True, None)+ with case.sessions() as session:+ doc = session.get(Document, "canonical")+ assert doc.text_content == ORIGINAL+ assert (+ doc.extraction_method,+ doc.extraction_source,+ doc.extraction_quality,+ ) == ("html_extraction", "arxiv_html", "high")+ assert all(link.indexed for link in session.query(DocumentCollection))+ assert session.query(RagDocumentStatus).count() == 2+++def test_text_and_index_flags_rollback_together(extraction_case):+ case = extraction_case(+ quality="low", method="pdf_extraction", source="local_pdf"+ )+ with case.sessions() as session:+ resource = session.get(ResearchResource, case.resource_id)+ case.service._save_text_with_db(+ resource,+ LONGER,+ session,+ "html_extraction",+ "arxiv_html",+ "canonical",+ )+ session.flush()+ assert not any(+ link.indexed for link in session.query(DocumentCollection)+ )+ assert session.query(RagDocumentStatus).count() == 0+ session.rollback()+ with case.sessions() as verification:+ doc = verification.get(Document, "canonical")+ assert {+ field: getattr(doc, field) for field in TEXT_FIELDS+ } == case.before+ assert all(+ link.indexed for link in verification.query(DocumentCollection)+ )+ assert verification.query(RagDocumentStatus).count() == 2+ assert all(+ index.chunk_count == index.total_documents == 1+ for index in verification.query(RAGIndex)+ )+++def test_failed_empty_pdf_keeps_byte_identity_when_text_recovers(+ extraction_case,+):+ case = extraction_case(text=None, status=DocumentStatus.FAILED)+ assert case.service.download_resource(case.resource_id) == (True, None)+ with case.sessions() as session:+ doc = session.get(Document, "canonical")+ assert doc.status == DocumentStatus.COMPLETED+ assert doc.text_content == LONGER+ assert doc.document_hash == case.pdf_hash+++def test_failed_document_recovers_without_replacing_better_text(+ extraction_case,+):+ case = extraction_case(+ status=DocumentStatus.FAILED,+ incoming="Short extraction.",+ origin=ArxivTextSource.LOCAL_PDF,+ )+ assert case.service.download_resource(case.resource_id) == (True, None)+ with case.sessions() as session:+ doc = session.get(Document, "canonical")+ assert doc.status == DocumentStatus.COMPLETED+ assert {+ field: getattr(doc, field) for field in TEXT_FIELDS+ } == case.before+ assert doc.document_hash == case.pdf_hash+ assert all(link.indexed for link in session.query(DocumentCollection))+ assert session.query(RagDocumentStatus).count() == 2++[email protected]("failure_point", ["status_delete", "index_totals"])+def test_failed_index_invalidation_preserves_prior_text_and_markers(+ extraction_case, failure_point+):+ case = extraction_case(+ quality="low", method="pdf_extraction", source="local_pdf"+ )++ def fail_status_delete(_conn, _cursor, statement, *_args):+ target = (+ "DELETE FROM rag_document_status"+ if failure_point == "status_delete"+ else "UPDATE rag_indices"+ )+ if statement.startswith(target):+ raise RuntimeError("controlled status write failure")++ event.listen(case.shared.bind, "before_cursor_execute", fail_status_delete)+ try:+ with case.sessions() as session:+ resource = session.get(ResearchResource, case.resource_id)+ with pytest.raises(+ RuntimeError, match="controlled status write failure"+ ):+ case.service._save_text_with_db(+ resource,+ LONGER,+ session,+ "html_extraction",+ "arxiv_html",+ "canonical",+ )+ assert not session.in_transaction()+ finally:+ event.remove(+ case.shared.bind, "before_cursor_execute", fail_status_delete+ )+ with case.sessions() as session:+ doc = session.get(Document, "canonical")+ assert {+ field: getattr(doc, field) for field in TEXT_FIELDS+ } == case.before+ assert all(link.indexed for link in session.query(DocumentCollection))+ assert session.query(RagDocumentStatus).count() == 2+ assert all(+ index.chunk_count == index.total_documents == 1+ for index in session.query(RAGIndex)+ )+++def test_concurrent_better_extraction_is_not_overwritten(extraction_case):+ case = extraction_case(+ quality="low", method="pdf_extraction", source="local_pdf"+ )+ winner = LONGER + " Further independently verified results and references."+ fired = False++ def save_winner_before_first_write(_conn, _cursor, statement, *_args):+ nonlocal fired+ if fired or not statement.startswith("UPDATE "):+ return+ fired = True+ # Another connection commits after the losing worker has selected its+ # extraction but before that worker's first write acquires SQLite's lock.+ with case.sessions() as writer:+ resource = writer.get(ResearchResource, case.resource_id)+ case.service._save_text_with_db(+ resource,+ winner,+ writer,+ "html_extraction",+ "arxiv_html",+ "canonical",+ )+ writer.commit()++ event.listen(+ case.shared.bind,+ "before_cursor_execute",+ save_winner_before_first_write,+ )+ try:+ with case.sessions() as session:+ resource = session.get(ResearchResource, case.resource_id)+ case.service._save_text_with_db(+ resource,+ LONGER,+ session,+ "html_extraction",+ "arxiv_html",+ "canonical",+ )+ session.commit()+ finally:+ event.remove(+ case.shared.bind,+ "before_cursor_execute",+ save_winner_before_first_write,+ )+ assert fired+ with case.sessions() as session:+ doc = session.get(Document, "canonical")+ assert doc.text_content == winner+ assert doc.word_count == len(winner.split())+ assert doc.character_count == len(winner)+ assert doc.document_hash == case.pdf_hash+ assert not any(+ link.indexed for link in session.query(DocumentCollection)+ )+ assert session.query(RagDocumentStatus).count() == 0+++def test_full_pdf_can_replace_arxiv_api_metadata(extraction_case):+ case = extraction_case(source="arxiv_api", origin=ArxivTextSource.LOCAL_PDF)+ assert case.service.download_resource(case.resource_id) == (True, None)+ with case.sessions() as session:+ doc = session.get(Document, "canonical")+ assert doc.text_content == LONGER+ assert doc.extraction_source == "local_pdf"+ assert doc.extraction_quality == "low"+ assert not any(+ link.indexed for link in session.query(DocumentCollection)+ )+ assert session.query(RagDocumentStatus).count() == 0+++def test_api_metadata_cannot_replace_full_text_even_if_longer(extraction_case):+ case = extraction_case(+ quality="low",+ method="pdf_extraction",+ source="local_pdf",+ incoming=LONGER,+ origin=ArxivTextSource.ARXIV_API,+ )+ assert case.service.download_resource(case.resource_id) == (True, None)+ with case.sessions() as session:+ doc = session.get(Document, "canonical")+ assert {+ field: getattr(doc, field) for field in TEXT_FIELDS+ } == case.before+ assert all(link.indexed for link in session.query(DocumentCollection))+ assert session.query(RagDocumentStatus).count() == 2+++def test_text_replacement_keeps_index_totals_correct_after_reindex(+ extraction_case,+):+ from local_deep_research.research_library.services.library_rag_service import (+ LibraryRAGService,+ )++ case = extraction_case(quality="low", incoming=LONGER)+ assert case.service.download_resource(case.resource_id) == (True, None)++ # Exercise the real prepare/persist transactions. Only the embedding and+ # vector backend are controlled: the regression concerns SQL aggregate+ # accounting after the text update invalidates its old status rows.+ vector_index = SimpleNamespace(+ index_prepared=lambda **kwargs: SimpleNamespace(added=1)+ )+ indexer = SimpleNamespace(+ username=case.service.username,+ db_password=case.service.password,+ rag_index_record=None,+ embedding_model="test",+ embedding_provider="sentence_transformers",+ text_splitter=SimpleNamespace(split_documents=lambda docs: docs),+ _embed_texts_cancellable=lambda texts, cancelled: [+ [1.0, 0.0] for _ in texts+ ],+ _get_index_hash=lambda collection, *args: collection,+ _get_index_path=lambda index_hash: (+ case.service.library_root / index_hash+ ),+ _get_vector_index=lambda *args, **kwargs: vector_index,+ )+ for collection_id in ("library", "selected"):+ with case.sessions() as session:+ index_id = (+ session.query(RAGIndex.id)+ .filter_by(collection_name=f"collection_{collection_id}")+ .scalar()+ )+ indexer.rag_index_record = SimpleNamespace(id=index_id)+ preparation = LibraryRAGService._prepare_document(+ indexer, "canonical", collection_id, force_reindex=False+ )+ assert preparation["status"] == "prepared"+ assert LibraryRAGService._write_prepared_document(+ indexer, preparation["prepared"]+ ) == {"status": "success", "chunk_count": 1}+ with case.sessions() as session:+ index = session.get(RAGIndex, index_id)+ assert index.chunk_count == 1+ assert index.total_documents == 1+++def test_text_invalidation_preserves_other_documents_index_contributions(+ extraction_case,+):+ case = extraction_case(quality="low", incoming=LONGER)+ with case.sessions() as session:+ session.add(+ Document(+ id="unrelated",+ source_type_id="source",+ document_hash="unrelated-hash",+ file_type="text",+ file_size=len("Another document's content"),+ text_content="Another document's content",+ )+ )+ session.flush()+ for index in session.query(RAGIndex):+ collection_id = index.index_hash+ session.add_all(+ [+ DocumentCollection(+ document_id="unrelated",+ collection_id=collection_id,+ indexed=True,+ chunk_count=3,+ ),+ RagDocumentStatus(+ document_id="unrelated",+ collection_id=collection_id,+ rag_index_id=index.id,+ chunk_count=3,+ ),+ ]+ )+ index.total_documents = 2+ index.chunk_count = 4+ session.commit()+ assert case.service.download_resource(case.resource_id) == (True, None)+ with case.sessions() as session:+ assert all(+ index.chunk_count == 3 and index.total_documents == 1+ for index in session.query(RAGIndex)+ )+ assert all(+ status.document_id == "unrelated" and status.chunk_count == 3+ for status in session.query(RagDocumentStatus)+ )+ assert all(+ link.indexed and link.chunk_count == 3+ for link in session.query(DocumentCollection).filter_by(+ document_id="unrelated"+ )+ )