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(library): preserve canonical documents and PDF snapshots on retry (#7202)

LearningCircuit44e7bfdd17d4
diff --git a/changelog.d/7163.bugfix.md b/changelog.d/7163.bugfix.md
new file mode 100644
index 0000000000..687593762d
--- /dev/null
+++ b/changelog.d/7163.bugfix.md
@@ -0,0 +1 @@
+Reuse existing content when a failed library download retry would collide with another document's hash. PDF and text retries preserve canonical content and storage, copy collection membership without copying index state, and retain the failed record's history and unrelated references. Retries restore missing stored PDFs and preserve indexed text even when a previous extraction failed. Recovered text is reused without skipping extraction of uploaded PDFs that have no extraction provenance.
diff --git a/changelog.d/7231.bugfix.md b/changelog.d/7231.bugfix.md
new file mode 100644
index 0000000000..b207d9fe6c
--- /dev/null
+++ b/changelog.d/7231.bugfix.md
@@ -0,0 +1 @@
+Download retries preserve shared PDF snapshots and keep changed content under its own document identity. Extracted text stays with its saved PDF even when downloads overlap, and retries release cached reads before network requests. Newly written filesystem PDFs include a content hash in their filenames; existing saved paths remain usable.
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 77b2f8f129..703e1fec9c 100644
--- a/src/local_deep_research/research_library/services/download_service.py
+++ b/src/local_deep_research/research_library/services/download_service.py
@@ -143,6 +143,49 @@ def _arxiv_text_provenance(source: ArxivTextSource) -> tuple[str, str]:
assert_never(unreachable)
+def _link_retry_to_canonical(
+ session: Session,
+ resource: ResearchResource,
+ failed: Document,
+ canonical: Document,
+) -> None:
+ """Reuse content without cascading away the failed record's history.
+
+ A FAILED record can still have annotations, stored content or other
+ resource references. Only redirect the resource whose retry established
+ the content match; retain the original record and its dependents.
+ Collection membership is copied, never its stale indexing state.
+ """
+ resource.document_id = canonical.id
+ collection_ids = {link.collection_id for link in failed.collections}
+ library = session.query(Collection).filter_by(name="Library").first()
+ if library:
+ collection_ids.add(library.id)
+ for collection_id in collection_ids:
+ ensure_in_collection(session, canonical.id, collection_id)
+
+
+def _has_reusable_text(document: Document) -> bool:
+ """Reuse successful text, including recovered failed-attempt provenance.
+
+ An upload with no extraction method still needs its stored PDF extracted.
+ """
+ return bool(
+ document.text_content
+ and (
+ (
+ document.extraction_method
+ and document.extraction_method != "failed"
+ )
+ or (
+ document.extraction_method == "failed"
+ and document.status == DocumentStatus.COMPLETED
+ and document.error_message is None
+ )
+ )
+ )
+
+
# Single source of truth for caller-safe skip-reason tokens lives in
# ``security.client_safe_errors`` (PR #6564 review: the services and HTML
# downloader copies drifted). Aliases below preserve the historic import
@@ -982,7 +1025,28 @@ class DownloadService:
skip_reason = None
status_code = None
+ if resource.document_id:
+ # A duplicate resource points to another resource's saved
+ # snapshot. Reuse its bytes while still repairing this
+ # resource's tracker, collection membership and queue state.
+ # Missing storage falls through to the normal retry path.
+ cache_session_cm = (
+ nullcontext(session)
+ if session is not None
+ else get_user_db_session(self.username, self.password)
+ )
+ with cache_session_cm as cache_session:
+ cached_pdf = self._load_cached_pdf(cache_session, resource)
+ if session is None:
+ # This read belongs to the download. Release it even
+ # when an outer route still owns a session scope.
+ cache_session.rollback()
+ if cached_pdf is not None:
+ pdf_content = cached_pdf[0]
+
for downloader in self.downloaders:
+ if pdf_content is not None:
+ break
if downloader.can_handle(url):
logger.info(
f"Using {downloader.__class__.__name__} for {redact_url_for_log(url)}"
@@ -1007,7 +1071,7 @@ class DownloadService:
):
break
- if selected_downloader is None:
+ if selected_downloader is None and pdf_content is None:
logger.error(
f"No downloader found for {redact_url_for_log(url)}"
)
@@ -1191,8 +1255,59 @@ class DownloadService:
# Check if library document already exists
existing_doc = get_document_for_resource(sess, target_resource)
+ canonical_retry = False
+ # Older placeholder recovery could leave a nonempty PDF
+ # labelled "unknown"; that content still needs preservation.
+ if (
+ existing_doc
+ and existing_doc.document_hash != file_hash_val
+ and (
+ existing_doc.status == DocumentStatus.COMPLETED
+ or (
+ existing_doc.file_type in ("pdf", "unknown")
+ and existing_doc.file_size > 0
+ )
+ or pdf_storage_manager.has_pdf(existing_doc, sess)
+ )
+ ):
+ # Preserve a saved snapshot even if later extraction
+ # failed, or the link appeared while the download was in
+ # flight. Resolve changed bytes by hash without rewriting
+ # the document used by other resources.
+ existing_doc = None
+ canonical_retry = True
+ if (
+ existing_doc
+ and existing_doc.status == DocumentStatus.FAILED
+ ):
+ # A retry can discover bytes already owned by another
+ # document. Resolve that owner BEFORE replacing the failed
+ # hash, otherwise the next autoflush violates uniqueness.
+ owner = (
+ sess.query(Document)
+ .filter_by(document_hash=file_hash_val)
+ .first()
+ )
+ if owner and owner.id != existing_doc.id:
+ _link_retry_to_canonical(
+ sess, target_resource, existing_doc, owner
+ )
+ existing_doc = None
+ canonical_retry = True
+ if (
+ existing_doc
+ and existing_doc.resource_id != target_resource.id
+ and existing_doc.document_hash == file_hash_val
+ ):
+ # A repeated retry now resolves through document_id.
+ # It may itself be FAILED after another extraction attempt.
+ # Use the dedup storage path again so a none-mode retry
+ # cannot downgrade the canonical PDF's stored bytes.
+ existing_doc = None
+ canonical_retry = True
if existing_doc:
+ pdf_document_id = existing_doc.id
# Update existing document. Only replace document_hash when
# transitioning from FAILED — that's the placeholder hash from
# _record_failed_text_extraction. For any other prior state
@@ -1201,6 +1316,7 @@ class DownloadService:
was_failed = existing_doc.status == DocumentStatus.FAILED
if was_failed:
existing_doc.document_hash = target_tracker.file_hash
+ existing_doc.error_message = None
existing_doc.file_size = len(pdf_content)
existing_doc.status = DocumentStatus.COMPLETED
existing_doc.processed_at = datetime.now(UTC)
@@ -1240,7 +1356,29 @@ class DownloadService:
.first()
)
if existing_by_hash:
+ pdf_document_id = existing_by_hash.id
target_resource.document_id = existing_by_hash.id
+ if canonical_retry:
+ if (
+ existing_by_hash.status
+ in (
+ DocumentStatus.COMPLETED,
+ DocumentStatus.FAILED,
+ )
+ and existing_by_hash.text_content
+ ):
+ # Preserve the canonical extraction and its
+ # indexed chunks even when a later extraction
+ # failed. FAILED does not mean text is absent.
+ text_details = None
+ if existing_by_hash.status == DocumentStatus.FAILED:
+ existing_by_hash.status = (
+ DocumentStatus.COMPLETED
+ )
+ existing_by_hash.error_message = None
+ existing_by_hash.processed_at = datetime.now(
+ UTC
+ )
try:
dedup_collection_id = (
collection_id
@@ -1272,8 +1410,17 @@ class DownloadService:
# downgrade): when the canonical already stores the PDF,
# mirror its location onto this tracker for consistency.
try:
+ missing_pdf = canonical_retry and not (
+ pdf_storage_manager.has_pdf(
+ existing_by_hash, sess
+ )
+ )
+ previous_paths = {existing_by_hash.file_path}
+ if existing_by_hash.storage_mode == "database":
+ previous_paths.add("database")
needs_upgrade = (
existing_by_hash.storage_mode in (None, "none")
+ or missing_pdf
) and (
pdf_storage_mode in ("database", "filesystem")
)
@@ -1313,7 +1460,11 @@ class DownloadService:
.all()
)
for sibling in siblings:
- if not sibling.file_path:
+ if not sibling.file_path or (
+ missing_pdf
+ and sibling.file_path
+ in previous_paths
+ ):
sibling.file_path = (
target_tracker.file_path
)
@@ -1325,6 +1476,13 @@ class DownloadService:
"Failed to sync sibling trackers after storage upgrade",
exc,
)
+ if canonical_retry:
+ raise
+ elif missing_pdf:
+ # none-mode retries may recover text without
+ # storing bytes. Do not advertise a lost file.
+ target_tracker.file_path = None
+ target_tracker.file_name = None
elif existing_by_hash.storage_mode == "database":
target_tracker.file_path = "database"
target_tracker.file_name = None
@@ -1365,6 +1523,8 @@ class DownloadService:
"Failed to reuse/upgrade deduped PDF storage",
exc,
)
+ if canonical_retry:
+ raise
if hasattr(tracker, "file_path"):
tracker.file_path = target_tracker.file_path
tracker.file_name = target_tracker.file_name
@@ -1396,6 +1556,7 @@ class DownloadService:
# Create new unified document entry
doc_id = str(uuid.uuid4())
+ pdf_document_id = doc_id
doc = Document(
id=doc_id,
source_type_id=source_type_id,
@@ -1413,6 +1574,7 @@ class DownloadService:
)
sess.add(doc)
sess.flush() # Ensure doc.id is available for blob storage
+ target_resource.document_id = doc.id
# Save PDF using storage manager (updates storage_mode and file_path)
file_path_result, _ = pdf_storage_manager.save_pdf(
pdf_content=pdf_content,
@@ -1477,10 +1639,28 @@ class DownloadService:
)
try:
with text_session_cm as text_sess:
- pdf_doc = get_document_for_resource(
- text_sess, target_resource
+ # The resource link can change after the PDF commit.
+ # Claim the exact stored snapshot before saving its
+ # extracted text; a no-op write also prevents deletion
+ # or hash replacement until this transaction ends.
+ claimed = (
+ text_sess.query(Document)
+ .filter_by(
+ id=pdf_document_id,
+ document_hash=file_hash_val,
+ )
+ .update(
+ {Document.id: pdf_document_id},
+ synchronize_session=False,
+ )
)
- pdf_document_id = pdf_doc.id if pdf_doc else None
+ if claimed != 1:
+ if session is None:
+ text_sess.rollback()
+ logger.info(
+ "Skipping text because its PDF snapshot changed"
+ )
+ return True, None, status_code
# Save text to encrypted database
self._save_text_with_db(
@@ -1894,11 +2074,7 @@ class DownloadService:
return False, f"Library document {doc_id} not found in database"
# 3. If text already exists and extraction succeeded, return success
- if (
- doc.text_content
- and doc.extraction_method
- and doc.extraction_method != "failed"
- ):
+ if _has_reusable_text(doc):
logger.info(f"Library document {doc_id} already has text content")
resource.document_id = doc.id
session.commit()
@@ -1970,19 +2146,20 @@ class DownloadService:
self, session, resource_id: int
) -> Optional[Tuple[bool, Optional[str]]]:
"""Check if text already exists in database (in Document.text_content)."""
+ resource = session.get(ResearchResource, resource_id)
existing_doc = (
- session.query(Document).filter_by(resource_id=resource_id).first()
+ get_document_for_resource(session, resource)
+ if resource is not None
+ else session.query(Document)
+ .filter_by(resource_id=resource_id)
+ .first()
)
if not existing_doc:
return None
# Check if text content exists and extraction was successful
- if (
- existing_doc.text_content
- and existing_doc.extraction_method
- and existing_doc.extraction_method != "failed"
- ):
+ if _has_reusable_text(existing_doc):
logger.info(
f"Text content already exists in Document for resource_id={resource_id}, extraction_method={existing_doc.extraction_method}"
)
@@ -2159,6 +2336,11 @@ class DownloadService:
def _load_cached_arxiv_pdf(
self, session: Session, resource
+ ) -> Tuple[bytes, str] | None:
+ return self._load_cached_pdf(session, resource)
+
+ def _load_cached_pdf(
+ self, session: Session, resource
) -> Tuple[bytes, str] | None:
"""Return (pdf_bytes, document_id) for a stored completed PDF."""
pdf_document = get_document_for_resource(session, resource)
@@ -2871,6 +3053,40 @@ class DownloadService:
else:
doc = get_document_for_resource(session, resource)
+ if doc and (
+ doc.status == DocumentStatus.FAILED
+ or doc.resource_id != resource.id
+ ):
+ text_hash = hashlib.sha256(text.encode()).hexdigest()
+ if (
+ doc.status == DocumentStatus.FAILED
+ and pdf_document_id is None
+ ):
+ # Text-only retries can resolve a different hash owner;
+ # an explicit PDF target must keep its snapshot identity.
+ owner = (
+ session.query(Document)
+ .filter_by(document_hash=text_hash)
+ .first()
+ )
+ if owner and owner.id != doc.id:
+ _link_retry_to_canonical(session, resource, doc, owner)
+ doc = owner
+ if (
+ doc.document_hash == text_hash
+ and doc.status
+ in (DocumentStatus.COMPLETED, DocumentStatus.FAILED)
+ and doc.text_content
+ ):
+ # The hash can identify original bytes, not extracted
+ # text. Reusing those bytes must preserve the owner's
+ # extraction, provenance and existing collection indexes.
+ if doc.status == DocumentStatus.FAILED:
+ doc.status = DocumentStatus.COMPLETED
+ doc.error_message = None
+ doc.processed_at = datetime.now(UTC)
+ return None
+
if doc:
old_text = doc.text_content or ""
if old_text.strip():
diff --git a/src/local_deep_research/research_library/services/pdf_storage_manager.py b/src/local_deep_research/research_library/services/pdf_storage_manager.py
index 5e68cc640c..4666d9605c 100644
--- a/src/local_deep_research/research_library/services/pdf_storage_manager.py
+++ b/src/local_deep_research/research_library/services/pdf_storage_manager.py
@@ -82,8 +82,8 @@ def resolve_pdf_storage_mode(mode):
return mode
-# `extract_arxiv_id` keeps the version (`2401.12345v2`); the stored filename
-# has never carried one, and two versions of one paper share a resource.
+# Keep the historical paper-derived basename; filesystem writes add the
+# content hash so different versions cannot overwrite one another.
_ARXIV_VERSION_SUFFIX = re.compile(r"v\d+$")
@@ -325,6 +325,17 @@ class PDFStorageManager:
if url:
filename = self._generate_filename(url, resource_id, filename)
+ # Different snapshots can share a resource or paper-derived name.
+ # New writes include their content identity so saving a later version
+ # cannot replace bytes still referenced by an older document. Existing
+ # stored paths remain readable and are not moved.
+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: this only constructs a filename; validate_safe_path checks the final path and PDF extension inside library_root before write_file_verified below
+ path = Path(filename)
+ content_hash = hashlib.sha256(pdf_content).hexdigest()
+ filename = str(
+ path.with_name(f"{path.stem}_{content_hash}{path.suffix}")
+ )
+
# Create simple flat directory structure - all PDFs in one folder
from ...security.directory_creation import create_directory
@@ -440,8 +451,8 @@ class PDFStorageManager:
# Two shapes the previous `\d{4}\.\d{4,5}` search did not produce:
# old-style identifiers carry a slash (`cs.AI/0701001`), which is a
# path separator, and every identifier may carry a version. The
- # version is dropped so the stored name stays what it has always
- # been for the same paper.
+ # version is dropped from the historical basename. New filesystem
+ # writes append a content hash to distinguish saved snapshots.
bare = _ARXIV_VERSION_SUFFIX.sub("", arxiv_id)
return f"arxiv_{bare.replace('/', '_')}.pdf"
diff --git a/tests/research_library/services/test_download_service_3827_fix.py b/tests/research_library/services/test_download_service_3827_fix.py
index bf85c5285a..edc5646091 100644
--- a/tests/research_library/services/test_download_service_3827_fix.py
+++ b/tests/research_library/services/test_download_service_3827_fix.py
@@ -1239,8 +1239,11 @@ def test_pdf_path_still_inserts_for_distinct_bytes(
assert session.query(Document).count() == 2
session.refresh(res_a)
session.refresh(res_b)
- assert res_a.document_id is None
- assert res_b.document_id is None
+ doc_a = session.get(Document, res_a.document_id)
+ doc_b = session.get(Document, res_b.document_id)
+ assert doc_a.id != doc_b.id
+ assert doc_a.document_hash == hashlib.sha256(pdf_a).hexdigest()
+ assert doc_b.document_hash == hashlib.sha256(pdf_b).hexdigest()
# ---------------------------------------------------------------------------
@@ -1782,7 +1785,7 @@ def test_same_url_updated_bytes_creates_new_document(
.one()
)
assert first_doc.id != second_doc.id
- assert res_b.document_id is None
+ assert res_b.document_id == second_doc.id
# ---------------------------------------------------------------------------
diff --git a/tests/research_library/services/test_download_service_arxiv_provenance.py b/tests/research_library/services/test_download_service_arxiv_provenance.py
index 6dff2e3f6b..0df0c9fc11 100644
--- a/tests/research_library/services/test_download_service_arxiv_provenance.py
+++ b/tests/research_library/services/test_download_service_arxiv_provenance.py
@@ -1,3 +1,4 @@
+import hashlib
from pathlib import Path
from unittest.mock import MagicMock, patch
@@ -69,11 +70,13 @@ def _make_ctx(session):
("source", "expected_method", "expected_origin"),
PROVENANCE_ROUTING_CASES,
)
[email protected]("snapshot_current", [True, False])
def test_pdf_download_path_persists_typed_arxiv_origin(
service,
source,
expected_method,
expected_origin,
+ snapshot_current,
):
# Given downloaded PDF bytes and a typed arXiv text result
pdf_content = b"%PDF-exact-reused-content"
@@ -82,6 +85,7 @@ def test_pdf_download_path_persists_typed_arxiv_origin(
resource.url = "https://arxiv.org/abs/2301.12345v2"
resource.title = "Typed provenance"
resource.research_id = "research-1"
+ resource.document_id = None
tracker = MagicMock()
tracker.url_hash = "typed-provenance"
tracker.download_attempts.count.return_value = 0
@@ -91,6 +95,9 @@ def test_pdf_download_path_persists_typed_arxiv_origin(
# take the dedup-link branch and skip save_pdf; force a miss so this
# test exercises the new-document path it intends.
session.query.return_value.filter_by.return_value.first.return_value = None
+ session.query.return_value.filter_by.return_value.update.return_value = int(
+ snapshot_current
+ )
arxiv = MagicMock(spec=ArxivDownloader)
arxiv.can_handle.return_value = True
@@ -104,14 +111,13 @@ def test_pdf_download_path_persists_typed_arxiv_origin(
)
service.downloaders = [arxiv]
- stored_pdf_document = MagicMock(id="pdf-document-id")
storage_manager = MagicMock()
storage_manager.save_pdf.return_value = (None, None)
with (
patch(
f"{MODULE}.get_document_for_resource",
- side_effect=[None, stored_pdf_document],
+ return_value=None,
),
patch(f"{MODULE}.get_source_type_id", return_value="source-type"),
patch(f"{MODULE}.get_default_library_id", return_value="library-id"),
@@ -137,13 +143,20 @@ def test_pdf_download_path_persists_typed_arxiv_origin(
resource.url,
pdf_content=pdf_content,
)
+ session.query.return_value.filter_by.assert_any_call(
+ id="new-document-id",
+ document_hash=hashlib.sha256(pdf_content).hexdigest(),
+ )
+ if not snapshot_current:
+ save_text.assert_not_called()
+ return
save_text.assert_called_once_with(
resource=resource,
text="typed arXiv text",
session=session,
extraction_method=expected_method,
extraction_source=expected_origin,
- pdf_document_id="pdf-document-id",
+ pdf_document_id="new-document-id",
)
diff --git a/tests/research_library/services/test_download_service_deep_coverage.py b/tests/research_library/services/test_download_service_deep_coverage.py
index e872b2249d..3d96269fec 100644
--- a/tests/research_library/services/test_download_service_deep_coverage.py
+++ b/tests/research_library/services/test_download_service_deep_coverage.py
@@ -10,6 +10,8 @@ Focuses on:
- _save_text_with_db: pdf_extraction (non-pdfplumber) quality branch
"""
+import hashlib
+
import pytest
@@ -318,6 +320,7 @@ class TestDownloadPdfDeep:
resource.url = "https://arxiv.org/abs/1234"
resource.title = "New Paper Title Here"
resource.research_id = "res-11"
+ resource.document_id = None
tracker = self._make_tracker()
@@ -354,13 +357,18 @@ class TestDownloadPdfDeep:
events.append("pdf_stored") or "database",
None,
)
- stored_pdf_doc = MagicMock()
- stored_pdf_doc.id = "new-doc-id"
- document_lookups = iter([None, stored_pdf_doc])
def get_document_for_resource(_session, _resource):
events.append("document_lookup")
- return next(document_lookups)
+ return
+
+ def claim_snapshot(*_args, **_kwargs):
+ events.append("pdf_snapshot_claimed")
+ return 1
+
+ session.query.return_value.filter_by.return_value.update.side_effect = (
+ claim_snapshot
+ )
session.flush.side_effect = lambda: events.append("session_flush")
session.commit.side_effect = lambda: events.append("session_commit")
@@ -406,16 +414,20 @@ class TestDownloadPdfDeep:
)
# Text production precedes every persistence step: the Document
# lookup, the flush that opens the write transaction, the PDF save
- # and the commit that closes it. The trailing lookup runs after that
- # commit and resolves the stored PDF's id for the text row.
+ # and the commit that closes it. Text persistence then claims the
+ # committed PDF's identity without resolving the resource link again.
assert events == [
"text_produced",
"document_lookup",
"session_flush",
"pdf_stored",
"session_commit",
- "document_lookup",
+ "pdf_snapshot_claimed",
]
+ session.query.return_value.filter_by.assert_any_call(
+ id="new-doc-id",
+ document_hash=hashlib.sha256(pdf_content).hexdigest(),
+ )
local_pdf_extract.assert_not_called()
save_text.assert_called_once_with(
resource=resource,
@@ -536,6 +548,7 @@ class TestDownloadPdfDeep:
resource.url = "https://arxiv.org/abs/2301.12345"
resource.title = "A Title Here"
resource.research_id = "res-15"
+ resource.document_id = None
tracker = self._make_tracker()
existing_doc = MagicMock()
@@ -550,6 +563,8 @@ class TestDownloadPdfDeep:
result_obj = MagicMock()
result_obj.is_success = True
pdf_content = b"%PDF-1.4 ok"
+ existing_doc.document_hash = hashlib.sha256(pdf_content).hexdigest()
+ existing_doc.resource_id = resource.id
result_obj.content = pdf_content
result_obj.skip_reason = None
result_obj.status_code = None
diff --git a/tests/research_library/services/test_download_service_strategy_coverage.py b/tests/research_library/services/test_download_service_strategy_coverage.py
index cff6e71b7d..84f0db4b6b 100644
--- a/tests/research_library/services/test_download_service_strategy_coverage.py
+++ b/tests/research_library/services/test_download_service_strategy_coverage.py
@@ -12,6 +12,7 @@ focused tests for:
6. __enter__ / __exit__ context manager
"""
+import hashlib
from unittest.mock import MagicMock, patch
import pytest
@@ -430,6 +431,7 @@ class TestDownloadResourceGenericFallback:
resource.id = 4
resource.title = "Generic Fallback Paper"
resource.research_id = "res-generic"
+ resource.document_id = None
tracker = MagicMock()
tracker.url_hash = "hash_gen2"
@@ -445,14 +447,13 @@ class TestDownloadResourceGenericFallback:
None
)
mock_psm = MagicMock()
+ session.query.return_value.filter_by.return_value.update.return_value = 1
mock_psm.save_pdf.return_value = (None, None)
- stored_pdf_doc = MagicMock()
- stored_pdf_doc.id = "generic-pdf-id"
with (
patch(
f"{MODULE}.get_document_for_resource",
- side_effect=[None, stored_pdf_doc],
+ return_value=None,
),
patch(f"{MODULE}.get_source_type_id", return_value="src-1"),
patch(f"{MODULE}.get_default_library_id", return_value="lib-1"),
@@ -482,7 +483,11 @@ class TestDownloadResourceGenericFallback:
session=session,
extraction_method="pdf_extraction",
extraction_source="local_pdf",
- pdf_document_id="generic-pdf-id",
+ pdf_document_id="new-uuid",
+ )
+ session.query.return_value.filter_by.assert_any_call(
+ id="new-uuid",
+ document_hash=hashlib.sha256(pdf_content).hexdigest(),
)
diff --git a/tests/research_library/services/test_failed_placeholder_dedup.py b/tests/research_library/services/test_failed_placeholder_dedup.py
new file mode 100644
index 0000000000..be31028cec
--- /dev/null
+++ b/tests/research_library/services/test_failed_placeholder_dedup.py
@@ -0,0 +1,1429 @@
+"""Retry collisions use canonical content without deleting failed history."""
+
+import hashlib
+from copy import copy
+from types import SimpleNamespace
+from unittest.mock import Mock
+
+import pytest
+from sqlalchemy import create_engine, event, text
+from sqlalchemy.orm import sessionmaker
+
+from local_deep_research.database import encrypted_db, thread_local_session
+from local_deep_research.database.models import Base
+from local_deep_research.database.models.download_tracker import DownloadTracker
+from local_deep_research.database.models.library import (
+ Collection,
+ Document,
+ DocumentBlob,
+ DocumentChunk,
+ DocumentCollection,
+ DocumentStatus,
+ DownloadQueue,
+ EmbeddingProvider,
+ RAGIndex,
+ RagDocumentStatus,
+ SourceType,
+)
+from local_deep_research.database.models.research import (
+ ResearchHistory,
+ ResearchResource,
+)
+from local_deep_research.database.session_context import get_user_db_session
+from local_deep_research.library.download_management import RetryManager
+from local_deep_research.research_library.services import download_service
+from local_deep_research.research_library.services.library_rag_service import (
+ LibraryRAGService,
+)
+from local_deep_research.research_library.services.pdf_storage_manager import (
+ PDFStorageManager,
+)
+from local_deep_research.web.routers import rag
+
+
+PDF = b"%PDF-1.4 canonical PDF bytes"
+PDF_HASH = hashlib.sha256(PDF).hexdigest()
+CHANGED_PDF = b"%PDF-1.4 a different saved PDF snapshot"
+CHANGED_PDF_HASH = hashlib.sha256(CHANGED_PDF).hexdigest()
+CANONICAL_TEXT = "Complete native text with useful detail."
+TEXT_HASH = hashlib.sha256(CANONICAL_TEXT.encode()).hexdigest()
+
+
+def library(tmp_path, monkeypatch):
+ engine = create_engine(f"sqlite:///{tmp_path / 'retry.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)
+ monkeypatch.setattr(
+ encrypted_db.db_manager, "open_user_database", lambda *args: engine
+ )
+ service = download_service.DownloadService.__new__(
+ download_service.DownloadService
+ )
+ service.username = "retry-user"
+ service.password = "test-password"
+ service.library_root = tmp_path / "library"
+ service.legacy_library_root = None
+ service._closed = False
+ settings = {"research_library.pdf_storage_mode": "none"}
+ service.settings = SimpleNamespace(get_setting=settings.get)
+ service.retry_manager = RetryManager(service.username, service.password)
+ service.downloaders = [
+ SimpleNamespace(
+ can_handle=lambda url: True,
+ download_with_result=lambda *args, **kwargs: SimpleNamespace(
+ is_success=True, content=PDF, status_code=200, skip_reason=None
+ ),
+ )
+ ]
+ monkeypatch.setattr(
+ service, "_extract_text_from_pdf", lambda content: "Short PDF text."
+ )
+ monkeypatch.setattr(
+ download_service, "get_source_type_id", lambda *args: "source"
+ )
+ monkeypatch.setattr(
+ download_service, "get_default_library_id", lambda *args: "library"
+ )
+ from local_deep_research.database import library_init
+
+ monkeypatch.setattr(
+ library_init, "get_default_library_id", lambda *args: "library"
+ )
+ index = Mock()
+ monkeypatch.setattr(rag, "trigger_auto_index", index)
+ with sessions() as shared:
+ monkeypatch.setattr(
+ thread_local_session, "get_metrics_session", lambda *args: shared
+ )
+ yield SimpleNamespace(
+ sessions=sessions, service=service, settings=settings, index=index
+ )
+ shared.rollback()
+ engine.dispose()
+
+
+def seed_retry(library, *, canonical_hash, stored=False, empty_text=False):
+ with library.sessions() as session:
+ session.add_all(
+ [
+ SourceType(
+ id="source",
+ name="research_download",
+ display_name="Research",
+ ),
+ ResearchHistory(
+ id="research",
+ query="retry",
+ mode="quick",
+ status="completed",
+ created_at="2026-10-06T00:00:00",
+ ),
+ Collection(id="library", name="Library", is_default=True),
+ Collection(id="selected", name="Selected"),
+ ]
+ )
+ session.flush()
+ resources = [
+ ResearchResource(
+ research_id="research",
+ title="Paper",
+ url=url,
+ source_type="academic",
+ created_at="2026-10-06T00:00:00",
+ )
+ for url in (
+ "https://example.org/canonical.pdf",
+ "https://mirror.example.org/retry.pdf",
+ "https://other.example.org/untouched.pdf",
+ )
+ ]
+ session.add_all(resources)
+ session.flush()
+ failed_hash = hashlib.sha256(
+ f"failed:{resources[1].url}:{resources[1].id}".encode()
+ ).hexdigest()
+ placeholder = Document(
+ id="failed",
+ source_type_id="source",
+ resource_id=resources[1].id,
+ research_id="research",
+ original_url=resources[1].url,
+ document_hash=failed_hash,
+ file_type="unknown",
+ file_size=0,
+ status=DocumentStatus.FAILED,
+ storage_mode="none",
+ error_message="Earlier extraction failed",
+ tags=["keep-me"],
+ )
+ session.add(placeholder)
+ if canonical_hash:
+ canonical = Document(
+ id="canonical",
+ source_type_id="source",
+ resource_id=resources[0].id,
+ research_id="research",
+ original_url=resources[0].url,
+ document_hash=canonical_hash,
+ file_type="pdf",
+ file_size=len(PDF),
+ status=DocumentStatus.COMPLETED,
+ storage_mode="database" if stored else "none",
+ file_path="database" if stored else None,
+ text_content=None if empty_text else CANONICAL_TEXT,
+ character_count=0 if empty_text else len(CANONICAL_TEXT),
+ word_count=0 if empty_text else len(CANONICAL_TEXT.split()),
+ extraction_method="native_api",
+ extraction_source="arxiv",
+ extraction_quality="high",
+ )
+ session.add(canonical)
+ session.flush()
+ resources[1].document_id = placeholder.id
+ resources[2].document_id = placeholder.id
+ session.add_all(
+ [
+ DocumentCollection(
+ document_id="failed", collection_id="library"
+ ),
+ DocumentCollection(
+ document_id="failed", collection_id="selected"
+ ),
+ DownloadQueue(
+ resource_id=resources[1].id,
+ research_id="research",
+ collection_id="selected",
+ status=DocumentStatus.FAILED,
+ ),
+ ]
+ )
+ if canonical_hash:
+ session.add(
+ DocumentCollection(
+ document_id="canonical",
+ collection_id="library",
+ indexed=True,
+ chunk_count=3,
+ )
+ )
+ if stored:
+ session.add(
+ DocumentBlob(
+ document_id="canonical",
+ pdf_binary=PDF,
+ blob_hash=PDF_HASH,
+ )
+ )
+ resource_ids = [r.id for r in resources]
+ session.commit()
+ return resource_ids, failed_hash
+
+
[email protected]("file_type", ["pdf", "unknown"])
+def test_failed_snapshot_without_storage_keeps_original_content_identity(
+ library, monkeypatch, file_type
+):
+ resource_ids, _ = seed_retry(library, canonical_hash=PDF_HASH)
+ with library.sessions() as session:
+ original = session.get(Document, "canonical")
+ original.status = DocumentStatus.FAILED
+ # Legacy placeholder recovery could leave the file type unchanged.
+ original.file_type = file_type
+ session.get(ResearchResource, resource_ids[1]).document_id = original.id
+ session.get(ResearchResource, resource_ids[2]).document_id = original.id
+ session.commit()
+ library.settings["research_library.pdf_storage_mode"] = "database"
+ monkeypatch.setattr(
+ library.service, "_check_url_against_policy", lambda _url: (True, None)
+ )
+ library.service.downloaders[0].download_with_result = (
+ lambda *args, **kwargs: SimpleNamespace(
+ is_success=True,
+ content=CHANGED_PDF,
+ status_code=200,
+ skip_reason=None,
+ )
+ )
+
+ assert library.service.download_resource(resource_ids[1]) == (True, None)
+ with library.sessions() as session:
+ original = session.get(Document, "canonical")
+ assert original.document_hash == PDF_HASH
+ assert original.text_content == CANONICAL_TEXT
+ assert (
+ session.get(ResearchResource, resource_ids[2]).document_id
+ == original.id
+ )
+ refreshed = session.get(
+ Document, session.get(ResearchResource, resource_ids[1]).document_id
+ )
+ assert refreshed.id != original.id
+ assert refreshed.document_hash == CHANGED_PDF_HASH
+ assert (
+ PDFStorageManager(
+ library.service.library_root, "database"
+ ).load_pdf(refreshed, session)
+ == CHANGED_PDF
+ )
+ assert session.execute(text("PRAGMA foreign_key_check")).all() == []
+
+
+def assert_preserved_retry(library, resource_ids, failed_hash):
+ with library.sessions() as session:
+ assert (
+ session.get(ResearchResource, resource_ids[1]).document_id
+ == "canonical"
+ )
+ # A failed record can own annotations and other resource references.
+ # Retrying one URL must not delete it or rewrite unrelated resources.
+ failed = session.get(Document, "failed")
+ assert failed.document_hash == failed_hash
+ assert failed.status == DocumentStatus.FAILED
+ assert failed.tags == ["keep-me"]
+ assert (
+ session.get(ResearchResource, resource_ids[2]).document_id
+ == "failed"
+ )
+ canonical = session.get(Document, "canonical")
+ assert canonical.text_content == CANONICAL_TEXT
+ assert canonical.character_count == len(CANONICAL_TEXT)
+ assert canonical.word_count == len(CANONICAL_TEXT.split())
+ assert (
+ canonical.extraction_method,
+ canonical.extraction_source,
+ canonical.extraction_quality,
+ ) == ("native_api", "arxiv", "high")
+ links = (
+ session.query(DocumentCollection)
+ .filter_by(document_id="canonical")
+ .all()
+ )
+ assert {link.collection_id for link in links} == {"library", "selected"}
+ assert len(links) == 2
+ by_collection = {link.collection_id: link for link in links}
+ assert by_collection["library"].indexed is True
+ assert by_collection["library"].chunk_count == 3
+ assert by_collection["selected"].indexed is False
+ assert session.execute(text("PRAGMA foreign_key_check")).all() == []
+
+
+def seed_snapshot_resources(library, *, arxiv_versions=False):
+ """Three distinct URLs, initially without any saved document."""
+ urls = [f"https://paper-{letter}.example/paper.pdf" for letter in "abc"]
+ if arxiv_versions:
+ urls[:2] = [
+ "https://arxiv.org/pdf/2401.12345v1",
+ "https://arxiv.org/pdf/2401.12345v2",
+ ]
+ with library.sessions() as session:
+ session.add_all(
+ [
+ SourceType(
+ id="source",
+ name="research_download",
+ display_name="Research",
+ ),
+ ResearchHistory(
+ id="research",
+ query="snapshots",
+ mode="quick",
+ status="completed",
+ created_at="2026-10-07T00:00:00",
+ ),
+ Collection(id="library", name="Library", is_default=True),
+ ]
+ )
+ session.flush()
+ resources = [
+ ResearchResource(
+ research_id="research",
+ title=f"Paper {index}",
+ url=url,
+ source_type="academic",
+ created_at="2026-10-07T00:00:00",
+ )
+ for index, url in enumerate(urls)
+ ]
+ session.add_all(resources)
+ session.flush()
+ resource_ids = [resource.id for resource in resources]
+ session.commit()
+ return resource_ids, urls
+
+
+def install_snapshot_downloads(library, monkeypatch, urls, mode, callback=None):
+ library.settings["research_library.pdf_storage_mode"] = mode
+ monkeypatch.setenv(
+ "LDR_RESEARCH_LIBRARY_ALLOW_FILESYSTEM_PDF_STORAGE", "true"
+ )
+ monkeypatch.setattr(
+ library.service, "_check_url_against_policy", lambda _url: (True, None)
+ )
+ # Keep this regression about PDF identity rather than extraction quality.
+ monkeypatch.setattr(
+ library.service, "_extract_text_from_pdf", lambda _content: None
+ )
+ content = dict.fromkeys(urls, PDF)
+ requests = []
+
+ def download(url, *_args, **_kwargs):
+ requests.append(url)
+ if callback is not None:
+ callback(url)
+ return SimpleNamespace(
+ is_success=True,
+ content=content[url],
+ status_code=200,
+ skip_reason=None,
+ )
+
+ library.service.downloaders = [
+ SimpleNamespace(
+ can_handle=lambda _url: True, download_with_result=download
+ )
+ ]
+ return content, requests
+
+
[email protected]("mode", ["database", "filesystem"])
[email protected]("changed", [False, True])
+def test_completed_linked_retry_preserves_original_pdf_snapshot(
+ library, monkeypatch, mode, changed
+):
+ resource_ids, urls = seed_snapshot_resources(library)
+ content, requests = install_snapshot_downloads(
+ library, monkeypatch, urls, mode
+ )
+ for resource_id in resource_ids[:2]:
+ assert library.service.download_resource(resource_id) == (True, None)
+ if changed:
+ content[urls[1]] = CHANGED_PDF
+ assert library.service.download_resource(resource_ids[1]) == (True, None)
+ assert library.service.download_resource(resource_ids[2]) == (True, None)
+
+ with library.sessions() as session:
+ canonical = session.query(Document).one()
+ manager = PDFStorageManager(library.service.library_root, mode)
+ assert manager.load_pdf(canonical, session) == PDF
+ assert canonical.document_hash == PDF_HASH
+ for resource_id in resource_ids[1:]:
+ assert (
+ session.get(ResearchResource, resource_id).document_id
+ == canonical.id
+ )
+ for tracker in session.query(DownloadTracker):
+ assert tracker.file_hash == PDF_HASH
+ assert tracker.file_size == len(PDF)
+ if mode == "database":
+ assert session.query(DocumentBlob).one().blob_hash == PDF_HASH
+ assert session.execute(text("PRAGMA foreign_key_check")).all() == []
+ # The repeat can repair bookkeeping from the saved bytes without re-fetching.
+ assert requests.count(urls[1]) == 1
+
+
[email protected]("mode", ["database", "filesystem"])
+ "target_status", [None, DocumentStatus.COMPLETED, DocumentStatus.FAILED]
+)
+def test_late_completed_link_resolves_changed_bytes_to_a_separate_snapshot(
+ library, monkeypatch, mode, target_status
+):
+ resource_ids, urls = seed_snapshot_resources(library, arxiv_versions=True)
+ canonical_id = None
+
+ def link_while_downloading(url):
+ if url == urls[1]:
+ # An independent writer completes the link after the initial check,
+ # while this request is fetching different bytes outside its session.
+ with library.sessions() as session:
+ session.get(
+ ResearchResource, resource_ids[1]
+ ).document_id = canonical_id
+ session.commit()
+
+ content, requests = install_snapshot_downloads(
+ library, monkeypatch, urls, mode, link_while_downloading
+ )
+ content[urls[1]] = CHANGED_PDF
+ content[urls[2]] = CHANGED_PDF
+ assert library.service.download_resource(resource_ids[0]) == (True, None)
+ with library.sessions() as session:
+ canonical = session.query(Document).one()
+ canonical_id = canonical.id
+ old_path = canonical.file_path
+ if target_status is not None:
+ assert library.service.download_resource(resource_ids[2]) == (
+ True,
+ None,
+ )
+ if target_status == DocumentStatus.FAILED:
+ with library.sessions() as session:
+ target = (
+ session.query(Document)
+ .filter_by(document_hash=CHANGED_PDF_HASH)
+ .one()
+ )
+ target.status = DocumentStatus.FAILED
+ target.error_message = "Previous extraction failed"
+ if mode == "database":
+ session.delete(session.get(DocumentBlob, target.id))
+ else:
+ (library.service.library_root / target.file_path).unlink()
+ session.commit()
+ assert library.service.download_resource(resource_ids[1]) == (True, None)
+
+ with library.sessions() as session:
+ original = session.get(Document, canonical_id)
+ refreshed = (
+ session.query(Document)
+ .filter_by(document_hash=CHANGED_PDF_HASH)
+ .one()
+ )
+ assert session.query(Document).count() == 2
+ assert original.file_path == old_path
+ assert original.document_hash == PDF_HASH
+ assert refreshed.status == DocumentStatus.COMPLETED
+ assert refreshed.error_message is None
+ assert (
+ session.get(ResearchResource, resource_ids[1]).document_id
+ == refreshed.id
+ )
+ if target_status is not None:
+ third = session.get(ResearchResource, resource_ids[2])
+ assert (
+ download_service.get_document_for_resource(session, third).id
+ == refreshed.id
+ )
+ manager = PDFStorageManager(library.service.library_root, mode)
+ assert manager.load_pdf(original, session) == PDF
+ assert manager.load_pdf(refreshed, session) == CHANGED_PDF
+ if mode == "filesystem":
+ assert original.file_path != refreshed.file_path
+ trackers = {
+ tracker.url: tracker for tracker in session.query(DownloadTracker)
+ }
+ assert trackers[urls[0]].file_hash == PDF_HASH
+ assert trackers[urls[1]].file_hash == CHANGED_PDF_HASH
+ assert trackers[urls[1]].file_path == (
+ "database" if mode == "database" else refreshed.file_path
+ )
+ assert session.execute(text("PRAGMA foreign_key_check")).all() == []
+ assert requests.count(urls[1]) == 1
+
+
[email protected]("mode", ["database", "filesystem"])
+def test_changed_snapshot_storage_failure_preserves_completed_link(
+ library, monkeypatch, mode
+):
+ resource_ids, urls = seed_snapshot_resources(library, arxiv_versions=True)
+ canonical_id = None
+
+ def link_while_downloading(url):
+ if url == urls[1]:
+ with library.sessions() as session:
+ session.get(
+ ResearchResource, resource_ids[1]
+ ).document_id = canonical_id
+ session.commit()
+
+ content, _ = install_snapshot_downloads(
+ library, monkeypatch, urls, mode, link_while_downloading
+ )
+ assert library.service.download_resource(resource_ids[0]) == (True, None)
+ with library.sessions() as session:
+ canonical = session.query(Document).one()
+ canonical_id = canonical.id
+ original_path = canonical.file_path
+
+ content[urls[1]] = CHANGED_PDF
+ save_pdf = PDFStorageManager.save_pdf
+
+ def fail_after_save(self, *args, **kwargs):
+ save_pdf(self, *args, **kwargs)
+ kwargs["session"].flush()
+ raise RuntimeError("Controlled storage failure after flushing")
+
+ monkeypatch.setattr(PDFStorageManager, "save_pdf", fail_after_save)
+ assert library.service.download_resource(resource_ids[1])[0] is False
+
+ with library.sessions() as session:
+ canonical = session.query(Document).one()
+ assert canonical.id == canonical_id
+ assert canonical.document_hash == PDF_HASH
+ assert canonical.file_path == original_path
+ assert (
+ session.get(ResearchResource, resource_ids[1]).document_id
+ == canonical_id
+ )
+ manager = PDFStorageManager(library.service.library_root, mode)
+ assert manager.load_pdf(canonical, session) == PDF
+ tracker = session.query(DownloadTracker).filter_by(url=urls[1]).one()
+ assert tracker.is_downloaded is False
+ assert session.execute(text("PRAGMA foreign_key_check")).all() == []
+
+
+ "first_mode,retry_mode",
+ [
+ ("none", "none"),
+ ("none", "database"),
+ ("database", "none"),
+ ("database", "database"),
+ ],
+)
+def test_pdf_retry_collision_preserves_canonical_and_can_repeat(
+ library,
+ first_mode,
+ retry_mode,
+):
+ resource_ids, failed_hash = seed_retry(
+ library, canonical_hash=PDF_HASH, stored=first_mode == "database"
+ )
+ library.settings["research_library.pdf_storage_mode"] = retry_mode
+ for _ in range(2):
+ # Real download_resource, short production sessions, storage and retry manager.
+ assert library.service.download_resource(resource_ids[1]) == (
+ True,
+ None,
+ )
+ assert_preserved_retry(library, resource_ids, failed_hash)
+ with library.sessions() as session:
+ canonical = session.get(Document, "canonical")
+ assert canonical.document_hash == PDF_HASH
+ stored = "database" in (first_mode, retry_mode)
+ assert canonical.storage_mode == ("database" if stored else "none")
+ blob = session.get(DocumentBlob, "canonical")
+ assert (blob.pdf_binary if blob else None) == (
+ PDF if stored else None
+ )
+ tracker = session.query(DownloadTracker).one()
+ assert tracker.is_downloaded
+ assert tracker.file_hash == PDF_HASH
+ assert tracker.file_path == ("database" if stored else None)
+ assert (
+ session.query(DownloadQueue).one().status
+ == DocumentStatus.COMPLETED
+ )
+ assert library.index.call_count == 2
+ assert library.index.call_args.args[:2] == (["canonical"], "selected")
+
+
+def save_text(library, resource_id, content=CANONICAL_TEXT):
+ with get_user_db_session(
+ library.service.username, library.service.password
+ ) as session:
+ resource = session.get(ResearchResource, resource_id)
+ library.service._save_text_with_db(
+ resource, content, session, "pdf_extraction", "local_pdf"
+ )
+ session.commit()
+ assert session.execute(text("SELECT 1")).scalar_one() == 1
+
+
+def test_text_retry_collision_preserves_canonical_and_can_repeat(library):
+ resource_ids, failed_hash = seed_retry(library, canonical_hash=TEXT_HASH)
+ for _ in range(2):
+ save_text(library, resource_ids[1])
+ assert_preserved_retry(library, resource_ids, failed_hash)
+
+
+def test_text_retry_preserves_a_hash_owners_different_extraction(library):
+ # Document hashes can identify original bytes rather than extracted text.
+ # A text retry with those bytes must not replace the owner's extraction.
+ resource_ids, _ = seed_retry(library, canonical_hash=TEXT_HASH)
+ with library.sessions() as session:
+ canonical = session.get(Document, "canonical")
+ canonical.text_content = "Existing native extraction."
+ canonical.character_count = len(canonical.text_content)
+ canonical.word_count = len(canonical.text_content.split())
+ session.commit()
+ for _ in range(2):
+ save_text(library, resource_ids[1])
+ with library.sessions() as session:
+ canonical = session.get(Document, "canonical")
+ assert canonical.text_content == "Existing native extraction."
+ assert canonical.extraction_quality == "high"
+
+
[email protected]("mode", ["none", "database"])
+def test_pdf_retry_without_collision_recovers_same_record(library, mode):
+ resource_ids, _ = seed_retry(library, canonical_hash=None)
+ library.settings["research_library.pdf_storage_mode"] = mode
+ assert library.service.download_resource(resource_ids[1]) == (True, None)
+ with library.sessions() as session:
+ recovered = session.query(Document).one()
+ assert recovered.id == "failed"
+ assert recovered.document_hash == PDF_HASH
+ assert recovered.status == DocumentStatus.COMPLETED
+ assert recovered.error_message is None
+ assert recovered.text_content == "Short PDF text."
+
+
+def test_text_retry_without_collision_recovers_same_record(library):
+ resource_ids, _ = seed_retry(library, canonical_hash=None)
+ save_text(library, resource_ids[1])
+ with library.sessions() as session:
+ recovered = session.query(Document).one()
+ assert recovered.id == "failed"
+ assert recovered.document_hash == TEXT_HASH
+ assert recovered.status == DocumentStatus.COMPLETED
+ assert recovered.error_message is None
+ assert recovered.text_content == CANONICAL_TEXT
+
+
+ "from_pdf,existing_text_owner",
+ [(False, False), (True, False), (True, True)],
+ ids=["text", "stored-pdf", "stored-pdf-existing-text-owner"],
+)
+def test_recovered_text_clears_failure_and_keeps_content_identity(
+ library, from_pdf, existing_text_owner
+):
+ resource_ids, _ = seed_retry(
+ library,
+ canonical_hash=PDF_HASH if from_pdf else None,
+ stored=from_pdf,
+ empty_text=True,
+ )
+ document_id = "canonical" if from_pdf else "failed"
+ resource_id = resource_ids[0] if from_pdf else resource_ids[1]
+ with library.sessions() as session:
+ document = session.get(Document, document_id)
+ document.status = DocumentStatus.FAILED
+ document.error_message = "Previous extraction failed"
+ resource = session.get(ResearchResource, resource_id)
+ original_link = resource.document_id
+ if existing_text_owner:
+ session.add(
+ Document(
+ id="text-owner",
+ source_type_id="source",
+ resource_id=resource_ids[2],
+ research_id="research",
+ document_hash=TEXT_HASH,
+ file_type="text",
+ file_size=len(CANONICAL_TEXT),
+ status=DocumentStatus.COMPLETED,
+ storage_mode="none",
+ text_content=CANONICAL_TEXT,
+ )
+ )
+ library.service._save_text_with_db(
+ resource,
+ CANONICAL_TEXT,
+ session,
+ "pdf_extraction",
+ "local_pdf",
+ pdf_document_id=document_id if from_pdf else None,
+ )
+ session.commit()
+
+ with library.sessions() as session:
+ recovered = session.get(Document, document_id)
+ assert recovered.status == DocumentStatus.COMPLETED
+ assert recovered.error_message is None
+ assert recovered.document_hash == (PDF_HASH if from_pdf else TEXT_HASH)
+ assert recovered.text_content == CANONICAL_TEXT
+ assert (
+ session.get(ResearchResource, resource_id).document_id
+ == original_link
+ )
+ if from_pdf:
+ assert session.get(DocumentBlob, document_id).pdf_binary == PDF
+ assert session.execute(text("PRAGMA foreign_key_check")).all() == []
+
+
+def test_pdf_retry_fills_empty_canonical_text(library):
+ resource_ids, _ = seed_retry(
+ library, canonical_hash=PDF_HASH, empty_text=True
+ )
+ assert library.service.download_resource(resource_ids[1]) == (True, None)
+ with library.sessions() as session:
+ assert (
+ session.get(ResearchResource, resource_ids[1]).document_id
+ == "canonical"
+ )
+ assert (
+ session.get(Document, "canonical").text_content == "Short PDF text."
+ )
+
+
+def test_retry_network_releases_cache_read_inside_outer_session(
+ library, monkeypatch
+):
+ resource_ids, _ = seed_retry(library, canonical_hash=None)
+ monkeypatch.setattr(
+ library.service, "_check_url_against_policy", lambda url: (True, None)
+ )
+ observations = []
+ download = library.service.downloaders[0].download_with_result
+ with get_user_db_session(
+ library.service.username, library.service.password
+ ) as outer:
+
+ def observe_download(*args, **kwargs):
+ observations.append(
+ (outer.in_transaction(), outer.bind.pool.checkedout())
+ )
+ return download(*args, **kwargs)
+
+ library.service.downloaders[0].download_with_result = observe_download
+ assert library.service.download_resource(resource_ids[1]) == (
+ True,
+ None,
+ )
+ assert observations == [(False, 0)]
+
+
[email protected]("mode", ["database", "filesystem"])
+def test_inflight_downloads_keep_text_with_their_own_pdf(
+ library, monkeypatch, mode
+):
+ resource_ids, urls = seed_snapshot_resources(library)
+ install_snapshot_downloads(library, monkeypatch, urls, mode)
+ original_text = "Original snapshot complete extraction. " * 4
+ changed_text = "Changed snapshot extraction."
+ monkeypatch.setattr(
+ library.service, "_extract_text_from_pdf", lambda _pdf: original_text
+ )
+ url_hash = library.service._get_url_hash(urls[0])
+ with library.sessions() as session:
+ session.add(
+ DownloadTracker(
+ url=urls[0],
+ url_hash=url_hash,
+ first_resource_id=resource_ids[0],
+ is_downloaded=False,
+ )
+ )
+ session.commit()
+
+ contender = copy(library.service)
+ contender._closed = True # The original service owns shared cleanup.
+ contender.downloaders = [
+ SimpleNamespace(
+ can_handle=lambda _url: True,
+ download_with_result=lambda *args, **kwargs: SimpleNamespace(
+ is_success=True,
+ content=CHANGED_PDF,
+ status_code=200,
+ skip_reason=None,
+ ),
+ )
+ ]
+ contender._extract_text_from_pdf = lambda _pdf: changed_text
+ completed_competing_download = False
+ with library.sessions() as other:
+ # Both downloads observed the resource before either committed a PDF.
+ early_resource = other.get(ResearchResource, resource_ids[0])
+ early_tracker = (
+ other.query(DownloadTracker).filter_by(url_hash=url_hash).one()
+ )
+ assert early_resource.document_id is None
+ with get_user_db_session(
+ library.service.username, library.service.password
+ ) as shared:
+
+ def complete_competing_download(_session):
+ nonlocal completed_competing_download
+ if completed_competing_download:
+ return
+ with library.sessions() as check:
+ original = (
+ check.query(Document)
+ .filter_by(document_hash=PDF_HASH)
+ .first()
+ )
+ if original is None:
+ return
+ completed_competing_download = True
+ assert contender._download_pdf(
+ early_resource, early_tracker, other
+ ) == (True, None, 200)
+ other.commit()
+
+ event.listen(shared, "after_commit", complete_competing_download)
+ try:
+ assert library.service.download_resource(resource_ids[0]) == (
+ True,
+ None,
+ )
+ finally:
+ event.remove(
+ shared, "after_commit", complete_competing_download
+ )
+
+ assert completed_competing_download
+ with library.sessions() as session:
+ resource = session.get(ResearchResource, resource_ids[0])
+ latest = session.get(Document, resource.document_id)
+ original = (
+ session.query(Document).filter_by(document_hash=PDF_HASH).one()
+ )
+ manager = PDFStorageManager(library.service.library_root, mode)
+ assert latest.id != original.id
+ assert latest.document_hash == CHANGED_PDF_HASH
+ assert manager.load_pdf(latest, session) == CHANGED_PDF
+ assert latest.text_content == changed_text
+ assert manager.load_pdf(original, session) == PDF
+ assert original.text_content == original_text
+ assert session.execute(text("PRAGMA foreign_key_check")).all() == []
+
+
[email protected]("kind", ["pdf", "text"])
+def test_retry_recovers_hash_owner_that_is_also_failed(library, kind):
+ content_hash = PDF_HASH if kind == "pdf" else TEXT_HASH
+ resource_ids, _ = seed_retry(library, canonical_hash=content_hash)
+ with library.sessions() as session:
+ canonical = session.get(Document, "canonical")
+ canonical.status = DocumentStatus.FAILED
+ canonical.error_message = "Previous extraction error"
+ canonical.text_content = None
+ session.commit()
+ if kind == "pdf":
+ assert library.service.download_resource(resource_ids[1]) == (
+ True,
+ None,
+ )
+ else:
+ save_text(library, resource_ids[1])
+ with library.sessions() as session:
+ canonical = session.get(Document, "canonical")
+ assert canonical.document_hash == content_hash
+ assert canonical.status == DocumentStatus.COMPLETED
+ assert canonical.error_message is None
+ assert canonical.text_content == (
+ "Short PDF text." if kind == "pdf" else CANONICAL_TEXT
+ )
+ assert (
+ session.get(ResearchResource, resource_ids[1]).document_id
+ == "canonical"
+ )
+
+
[email protected]("kind", ["pdf", "text"])
+def test_failed_collection_write_rolls_back_link_and_allows_retry(
+ library, monkeypatch, kind
+):
+ content_hash = PDF_HASH if kind == "pdf" else TEXT_HASH
+ resource_ids, failed_hash = seed_retry(library, canonical_hash=content_hash)
+ ensure = download_service.ensure_in_collection
+
+ def fail_after_flush(session, document_id, collection_id):
+ ensure(session, document_id, collection_id)
+ session.flush()
+ raise RuntimeError("Controlled collection write failure")
+
+ with monkeypatch.context() as failure:
+ failure.setattr(
+ download_service, "ensure_in_collection", fail_after_flush
+ )
+ if kind == "pdf":
+ assert (
+ library.service.download_resource(resource_ids[1])[0] is False
+ )
+ else:
+ with pytest.raises(RuntimeError, match="Controlled collection"):
+ save_text(library, resource_ids[1])
+ with library.sessions() as session:
+ assert (
+ session.get(ResearchResource, resource_ids[1]).document_id
+ == "failed"
+ )
+ assert session.get(Document, "failed").document_hash == failed_hash
+ assert session.get(Document, "canonical").text_content == CANONICAL_TEXT
+ links = (
+ session.query(DocumentCollection)
+ .filter_by(document_id="canonical")
+ .all()
+ )
+ assert [link.collection_id for link in links] == ["library"]
+ assert session.execute(text("PRAGMA foreign_key_check")).all() == []
+ if kind == "pdf":
+ assert library.service.download_resource(resource_ids[1]) == (
+ True,
+ None,
+ )
+ else:
+ save_text(library, resource_ids[1])
+ assert_preserved_retry(library, resource_ids, failed_hash)
+
+
+ "backend", ["database", "filesystem", "database_with_file_path"]
+)
[email protected]("already_linked", [False, True])
[email protected]("requested_mode", ["database", "none"])
+def test_retry_recovers_missing_pdf_without_advertising_lost_storage(
+ library, backend, already_linked, requested_mode
+):
+ resource_ids, _ = seed_retry(library, canonical_hash=PDF_HASH)
+ with library.sessions() as session:
+ canonical = session.get(Document, "canonical")
+ canonical.storage_mode = (
+ "filesystem" if backend == "filesystem" else "database"
+ )
+ canonical.file_path = (
+ "database" if backend == "database" else "pdfs/lost.pdf"
+ )
+ if already_linked:
+ session.get(
+ ResearchResource, resource_ids[1]
+ ).document_id = "canonical"
+ # Sibling trackers pointing to the missing canonical file must follow
+ # its repair; a different stored path must not be changed blindly.
+ for resource_id, path in (
+ (resource_ids[0], canonical.file_path),
+ (resource_ids[2], "pdfs/independent.pdf"),
+ ):
+ resource = session.get(ResearchResource, resource_id)
+ session.add(
+ DownloadTracker(
+ url=resource.url,
+ url_hash=library.service._get_url_hash(resource.url),
+ first_resource_id=resource.id,
+ file_hash=PDF_HASH,
+ file_path=path,
+ is_downloaded=True,
+ )
+ )
+ manager = PDFStorageManager(library.service.library_root, "database")
+ assert manager.load_pdf(canonical, session) is None
+ session.commit()
+ library.settings["research_library.pdf_storage_mode"] = requested_mode
+
+ for _ in range(2):
+ assert library.service.download_resource(resource_ids[1]) == (
+ True,
+ None,
+ )
+ with library.sessions() as session:
+ canonical = session.get(Document, "canonical")
+ stored = requested_mode == "database"
+ assert manager.load_pdf(canonical, session) == (
+ PDF if stored else None
+ )
+ assert canonical.text_content == CANONICAL_TEXT
+ tracker = (
+ session.query(DownloadTracker)
+ .filter_by(first_resource_id=resource_ids[1])
+ .one()
+ )
+ assert tracker.file_path == ("database" if stored else None)
+ if stored:
+ sibling = (
+ session.query(DownloadTracker)
+ .filter_by(first_resource_id=resource_ids[0])
+ .one()
+ )
+ assert sibling.file_path == "database"
+ unrelated = (
+ session.query(DownloadTracker)
+ .filter_by(first_resource_id=resource_ids[2])
+ .one()
+ )
+ assert unrelated.file_path == "pdfs/independent.pdf"
+ assert session.execute(text("PRAGMA foreign_key_check")).all() == []
+
+
[email protected]("kind", ["pdf", "text"])
[email protected]("already_linked", [False, True])
+def test_failed_hash_owner_preserves_nonempty_text_and_real_index(
+ library, kind, already_linked
+):
+ resource_ids, _ = seed_retry(
+ library, canonical_hash=PDF_HASH if kind == "pdf" else TEXT_HASH
+ )
+ previous_text = "Existing complete extraction already indexed by the user."
+ with library.sessions() as session:
+ canonical = session.get(Document, "canonical")
+ canonical.text_content = previous_text
+ canonical.character_count = len(previous_text)
+ canonical.word_count = len(previous_text.split())
+ if already_linked:
+ session.get(
+ ResearchResource, resource_ids[1]
+ ).document_id = "canonical"
+ index = RAGIndex(
+ collection_name="collection_library",
+ embedding_model="controlled-embedding",
+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,
+ embedding_dimension=3,
+ index_path=str(library.service.library_root / "controlled.faiss"),
+ index_hash="controlled-index",
+ chunk_size=500,
+ chunk_overlap=50,
+ )
+ session.add(index)
+ session.flush()
+ link = (
+ session.query(DocumentCollection)
+ .filter_by(document_id="canonical", collection_id="library")
+ .one()
+ )
+ link.chunk_count = 1
+ session.add_all(
+ [
+ RagDocumentStatus(
+ document_id="canonical",
+ collection_id="library",
+ rag_index_id=index.id,
+ chunk_count=1,
+ ),
+ DocumentChunk(
+ chunk_hash=hashlib.sha256(
+ previous_text.encode()
+ ).hexdigest(),
+ source_type="document",
+ source_id="canonical",
+ collection_name="collection_library",
+ chunk_text=previous_text,
+ chunk_index=0,
+ start_char=0,
+ end_char=len(previous_text),
+ word_count=len(previous_text.split()),
+ embedding_id="controlled-vector",
+ embedding_model="controlled-embedding",
+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,
+ embedding_dimension=3,
+ ),
+ ]
+ )
+ library.service._record_failed_text_extraction(
+ session,
+ session.get(ResearchResource, resource_ids[0]),
+ "Controlled later extraction failure",
+ )
+ provenance = (
+ canonical.extraction_method,
+ canonical.extraction_source,
+ canonical.extraction_quality,
+ )
+ session.commit()
+
+ for _ in range(2):
+ if kind == "pdf":
+ assert library.service.download_resource(resource_ids[1]) == (
+ True,
+ None,
+ )
+ else:
+ library.service.downloaders[0].download_with_result = (
+ lambda *args, **kwargs: SimpleNamespace(
+ is_success=True,
+ content=CANONICAL_TEXT,
+ status_code=200,
+ skip_reason=None,
+ )
+ )
+ assert library.service.download_as_text(resource_ids[1]) == (
+ True,
+ None,
+ )
+ with library.sessions() as session:
+ canonical = session.get(Document, "canonical")
+ assert canonical.text_content == previous_text
+ assert canonical.character_count == len(previous_text)
+ assert canonical.word_count == len(previous_text.split())
+ assert (
+ canonical.extraction_method,
+ canonical.extraction_source,
+ canonical.extraction_quality,
+ ) == provenance
+ assert canonical.status == DocumentStatus.COMPLETED
+ assert canonical.error_message is None
+ assert (
+ session.query(DocumentChunk).one().chunk_text == previous_text
+ )
+ assert (
+ session.get(RagDocumentStatus, ("canonical", "library"))
+ is not None
+ )
+ preparation = LibraryRAGService._prepare_document(
+ SimpleNamespace(
+ username=library.service.username,
+ db_password=library.service.password,
+ ),
+ "canonical",
+ "library",
+ force_reindex=False,
+ )
+ assert preparation == {
+ "status": "skipped",
+ "message": "Document already indexed for this collection",
+ "chunk_count": 1,
+ }
+
+
[email protected]("failure_point", ["probe", "save"])
+def test_retry_storage_failure_rolls_back_and_can_recover(
+ library, monkeypatch, failure_point
+):
+ resource_ids, failed_hash = seed_retry(library, canonical_hash=PDF_HASH)
+ library.settings["research_library.pdf_storage_mode"] = "database"
+ save_pdf = PDFStorageManager.save_pdf
+
+ def fail_probe(*args, **kwargs):
+ raise RuntimeError("Controlled availability failure")
+
+ def fail_save(self, *args, **kwargs):
+ save_pdf(self, *args, **kwargs)
+ kwargs["session"].flush()
+ raise RuntimeError("Controlled storage failure")
+
+ with monkeypatch.context() as failure:
+ failure.setattr(
+ PDFStorageManager,
+ "has_pdf" if failure_point == "probe" else "save_pdf",
+ fail_probe if failure_point == "probe" else fail_save,
+ )
+ assert library.service.download_resource(resource_ids[1])[0] is False
+ with library.sessions() as session:
+ assert (
+ session.get(ResearchResource, resource_ids[1]).document_id
+ == "failed"
+ )
+ assert session.get(Document, "failed").document_hash == failed_hash
+ assert session.get(DocumentBlob, "canonical") is None
+ assert (
+ session.query(DownloadQueue).one().status == DocumentStatus.FAILED
+ )
+ assert session.query(DownloadTracker).one().is_downloaded is False
+ assert library.service.download_resource(resource_ids[1]) == (True, None)
+ assert_preserved_retry(library, resource_ids, failed_hash)
+ with library.sessions() as session:
+ assert session.get(DocumentBlob, "canonical").pdf_binary == PDF
+
+
[email protected]("requested_mode", ["database", "none"])
+def test_retry_preserves_existing_filesystem_pdf(
+ library, monkeypatch, requested_mode
+):
+ resource_ids, failed_hash = seed_retry(library, canonical_hash=PDF_HASH)
+ root = library.service.library_root
+ path = root / "pdfs" / "existing.pdf"
+ path.parent.mkdir(parents=True)
+ path.write_bytes(PDF)
+ with library.sessions() as session:
+ canonical = session.get(Document, "canonical")
+ canonical.storage_mode = "filesystem"
+ canonical.file_path = "pdfs/existing.pdf"
+ session.get(ResearchResource, resource_ids[1]).document_id = "canonical"
+ session.commit()
+ library.settings["research_library.pdf_storage_mode"] = requested_mode
+ save = Mock(side_effect=AssertionError("Existing PDF must be reused"))
+ monkeypatch.setattr(PDFStorageManager, "save_pdf", save)
+
+ assert library.service.download_resource(resource_ids[1]) == (True, None)
+ save.assert_not_called()
+ assert path.read_bytes() == PDF
+ assert_preserved_retry(library, resource_ids, failed_hash)
+ with library.sessions() as session:
+ canonical = session.get(Document, "canonical")
+ assert canonical.storage_mode == "filesystem"
+ assert canonical.file_path == "pdfs/existing.pdf"
+ assert session.get(DocumentBlob, "canonical") is None
+ assert (
+ session.query(DownloadTracker).one().file_path
+ == "pdfs/existing.pdf"
+ )
+
+
[email protected]("requested_mode", ["database", "filesystem", "none"])
+def test_retry_refetches_own_pdf_instead_of_reusing_shared_legacy_file(
+ library, monkeypatch, tmp_path, requested_mode
+):
+ resource_ids, failed_hash = seed_retry(library, canonical_hash=PDF_HASH)
+ legacy_root = tmp_path / "legacy"
+ legacy_pdf = legacy_root / "pdfs" / "existing.pdf"
+ legacy_pdf.parent.mkdir(parents=True)
+ legacy_pdf.write_bytes(CHANGED_PDF)
+ library.service.library_root = legacy_root / library.service.username
+ # Model an older service's saved configuration. The new implementation
+ # must not consume this shared root, even with the retired flag set.
+ library.service.legacy_library_root = legacy_root
+ library.settings["research_library.storage_path"] = str(legacy_root)
+ library.settings["research_library.pdf_storage_mode"] = requested_mode
+ monkeypatch.setenv(
+ "LDR_RESEARCH_LIBRARY_ALLOW_LEGACY_READ_FALLBACK", "true"
+ )
+ monkeypatch.setenv(
+ "LDR_RESEARCH_LIBRARY_ALLOW_FILESYSTEM_PDF_STORAGE", "true"
+ )
+ monkeypatch.setattr(
+ library.service, "_check_url_against_policy", lambda _url: (True, None)
+ )
+ with library.sessions() as session:
+ canonical = session.get(Document, "canonical")
+ canonical.storage_mode = "filesystem"
+ canonical.file_path = "pdfs/existing.pdf"
+ session.get(ResearchResource, resource_ids[1]).document_id = "canonical"
+ session.commit()
+ original_download = library.service.downloaders[0].download_with_result
+ download = Mock(side_effect=original_download)
+ library.service.downloaders[0].download_with_result = download
+
+ assert library.service.download_resource(resource_ids[1]) == (True, None)
+ download.assert_called_once()
+ assert download.call_args.args[0] == "https://mirror.example.org/retry.pdf"
+ assert legacy_pdf.read_bytes() == CHANGED_PDF
+ assert_preserved_retry(library, resource_ids, failed_hash)
+ with library.sessions() as session:
+ canonical = session.get(Document, "canonical")
+ assert canonical.document_hash == PDF_HASH
+ manager = PDFStorageManager(
+ library.service.library_root, requested_mode
+ )
+ assert manager.load_pdf(canonical, session) == (
+ None if requested_mode == "none" else PDF
+ )
+ tracker = session.query(DownloadTracker).one()
+ assert tracker.file_hash == PDF_HASH
+ if requested_mode == "none":
+ assert tracker.file_path is None
+ elif requested_mode == "database":
+ assert tracker.file_path == "database"
+ else:
+ assert tracker.file_path == canonical.file_path
+ assert tracker.file_path != "pdfs/existing.pdf"
+ saved_pdf = library.service.library_root / tracker.file_path
+ assert saved_pdf.read_bytes() == PDF
+
+
[email protected]("resource_index", [0, 1, 2])
+def test_recovered_canonical_text_is_reused_without_network(
+ library, resource_index
+):
+ resource_ids, _ = seed_retry(library, canonical_hash=TEXT_HASH)
+ with library.sessions() as session:
+ library.service._record_failed_text_extraction(
+ session,
+ session.get(ResearchResource, resource_ids[0]),
+ "Earlier extraction failed",
+ )
+ session.commit()
+ save_text(library, resource_ids[1])
+ if resource_index == 2:
+ with library.sessions() as session:
+ resource = session.get(ResearchResource, resource_ids[2])
+ resource.source_type = "library"
+ resource.url = "/library/document/canonical"
+ resource.document_id = "canonical"
+ session.commit()
+ download = Mock(
+ side_effect=AssertionError("Completed text is already available")
+ )
+ library.service.downloaders[0].download_with_result = download
+
+ assert library.service.download_as_text(resource_ids[resource_index]) == (
+ True,
+ None,
+ )
+ download.assert_not_called()
+ with library.sessions() as session:
+ canonical = session.get(Document, "canonical")
+ assert canonical.text_content == CANONICAL_TEXT
+ assert canonical.status == DocumentStatus.COMPLETED
+
+
[email protected]("method", [None, "", "failed", "pdf_extraction"])
+def test_uploaded_pdf_without_extraction_provenance_is_extracted(
+ library, monkeypatch, method
+):
+ resource_ids, _ = seed_retry(library, canonical_hash=PDF_HASH, stored=True)
+ with library.sessions() as session:
+ uploaded = session.get(Document, "canonical")
+ uploaded.resource_id = None
+ uploaded.original_url = None
+ uploaded.extraction_method = method
+ uploaded.extraction_source = None
+ uploaded.extraction_quality = None
+ resource = session.get(ResearchResource, resource_ids[0])
+ resource.source_type = "library"
+ resource.url = "/library/document/canonical"
+ resource.document_id = uploaded.id
+ session.commit()
+ extracted = "Text extracted from the stored upload."
+ extract = Mock(return_value=extracted)
+ monkeypatch.setattr(library.service, "_extract_text_from_pdf", extract)
+ download = Mock(side_effect=AssertionError("Uploads use stored PDF bytes"))
+ library.service.downloaders[0].download_with_result = download
+
+ assert library.service.download_as_text(resource_ids[0]) == (True, None)
+ download.assert_not_called()
+ with library.sessions() as session:
+ uploaded = session.get(Document, "canonical")
+ assert uploaded.document_hash == PDF_HASH
+ assert session.get(DocumentBlob, uploaded.id).pdf_binary == PDF
+ if method in (None, ""):
+ extract.assert_called_once_with(PDF)
+ assert uploaded.text_content == extracted
+ assert uploaded.character_count == len(extracted)
+ assert uploaded.word_count == len(extracted.split())
+ assert uploaded.extraction_method == "pdf_extraction"
+ assert uploaded.extraction_source == "pdfplumber"
+ else:
+ # Successfully recovered failed provenance and established
+ # extractions still reuse their saved text without extraction.
+ extract.assert_not_called()
+ assert uploaded.text_content == CANONICAL_TEXT
+ assert uploaded.extraction_method == method
+
+
[email protected]("change", ["delete", "replace_bytes"])
+def test_text_save_does_not_recreate_or_reuse_a_lost_pdf_snapshot(
+ library, monkeypatch, change
+):
+ ids, urls = seed_snapshot_resources(library)
+ install_snapshot_downloads(library, monkeypatch, urls, "database")
+ monkeypatch.setattr(
+ library.service, "_extract_text_from_pdf", lambda pdf: CANONICAL_TEXT
+ )
+ changed = []
+ with get_user_db_session(
+ library.service.username, library.service.password
+ ) as shared:
+
+ def change_committed_snapshot(_session):
+ if changed:
+ return
+ with library.sessions() as other:
+ doc = (
+ other.query(Document)
+ .filter_by(document_hash=PDF_HASH)
+ .first()
+ )
+ if doc is None:
+ return
+ changed.append(doc.id)
+ if change == "delete":
+ other.get(ResearchResource, ids[0]).document_id = None
+ other.flush()
+ other.delete(doc)
+ else:
+ doc.document_hash = CHANGED_PDF_HASH
+ blob = other.get(DocumentBlob, doc.id)
+ blob.pdf_binary = CHANGED_PDF
+ blob.blob_hash = CHANGED_PDF_HASH
+ other.commit()
+
+ event.listen(shared, "after_commit", change_committed_snapshot)
+ try:
+ assert library.service.download_resource(ids[0]) == (True, None)
+ finally:
+ event.remove(shared, "after_commit", change_committed_snapshot)
+ assert len(changed) == 1
+ with library.sessions() as check:
+ if change == "delete":
+ assert check.query(Document).count() == 0
+ else:
+ doc = check.get(Document, changed[0])
+ assert doc.document_hash == CHANGED_PDF_HASH
+ assert not doc.text_content
+ assert check.get(DocumentBlob, doc.id).pdf_binary == CHANGED_PDF
diff --git a/tests/research_library/services/test_pdf_storage_manager.py b/tests/research_library/services/test_pdf_storage_manager.py
index 983e900726..9dfdbc072d 100644
--- a/tests/research_library/services/test_pdf_storage_manager.py
+++ b/tests/research_library/services/test_pdf_storage_manager.py
@@ -1,5 +1,6 @@
"""Tests for PDF Storage Manager."""
+import hashlib
import os
from unittest.mock import MagicMock, patch
@@ -515,7 +516,8 @@ class TestPDFStorageManagerFilesystemWrite:
pdf_dir.mkdir(parents=True)
outside_pdf = tmp_path / "outside.pdf"
outside_pdf.write_bytes(b"ORIGINAL")
- symlink = pdf_dir / "evil.pdf"
+ content_hash = hashlib.sha256(mock_pdf_content).hexdigest()
+ symlink = pdf_dir / f"evil_{content_hash}.pdf"
try:
symlink.symlink_to(outside_pdf)
except (OSError, NotImplementedError):
diff --git a/tests/research_library/services/test_per_user_library_root.py b/tests/research_library/services/test_per_user_library_root.py
index adb88f147c..7b359014c9 100644
--- a/tests/research_library/services/test_per_user_library_root.py
+++ b/tests/research_library/services/test_per_user_library_root.py
@@ -1,5 +1,6 @@
"""Per-user library isolation and refusal of ambiguous legacy PDF reads."""
+import hashlib
from unittest.mock import MagicMock
import pytest
@@ -149,15 +150,17 @@ class TestDownloadWritesToPerUserPath:
mock_pdf_content, doc, MagicMock(), "5.pdf"
)
- assert rel_path == "pdfs/5.pdf"
- written = base / "alice" / "pdfs" / "5.pdf"
+ expected_name = f"5_{hashlib.sha256(mock_pdf_content).hexdigest()}.pdf"
+ assert rel_path == f"pdfs/{expected_name}"
+ written = base / "alice" / rel_path
assert written.is_file()
assert written.read_bytes() == mock_pdf_content
# Nothing was written to the shared base directly.
- assert not (base / "pdfs" / "5.pdf").exists()
+ assert not (base / "pdfs").exists()
+ @pytest.mark.parametrize("same_content", [False, True])
def test_two_users_same_resource_id_do_not_collide(
- self, tmp_path, mock_pdf_content
+ self, tmp_path, mock_pdf_content, same_content
):
base = tmp_path
alice_mgr = PDFStorageManager(
@@ -167,7 +170,7 @@ class TestDownloadWritesToPerUserPath:
apply_user_subdir(base, "bob", False), "filesystem"
)
alice_bytes = mock_pdf_content + b"-alice"
- bob_bytes = mock_pdf_content + b"-bob"
+ bob_bytes = alice_bytes if same_content else mock_pdf_content + b"-bob"
a_rel, _ = alice_mgr.save_pdf(
alice_bytes, MagicMock(id="a"), MagicMock(), "5.pdf"
@@ -176,13 +179,17 @@ class TestDownloadWritesToPerUserPath:
bob_bytes, MagicMock(id="b"), MagicMock(), "5.pdf"
)
- # Same RELATIVE path (per-user autoincrement collides at id 5)...
- assert a_rel == b_rel == "pdfs/5.pdf"
- # ...but distinct absolute files with each user's own bytes.
- a_file = base / "alice" / "pdfs" / "5.pdf"
- b_file = base / "bob" / "pdfs" / "5.pdf"
+ assert a_rel == f"pdfs/5_{hashlib.sha256(alice_bytes).hexdigest()}.pdf"
+ assert b_rel == f"pdfs/5_{hashlib.sha256(bob_bytes).hexdigest()}.pdf"
+ # Equal bytes produce equal snapshot names, so content hashes alone
+ # cannot provide per-user isolation.
+ assert (a_rel == b_rel) is same_content
+ a_file = base / "alice" / a_rel
+ b_file = base / "bob" / b_rel
+ assert a_file != b_file
assert a_file.read_bytes() == alice_bytes
assert b_file.read_bytes() == bob_bytes
+ assert not (base / "pdfs").exists()
class TestNoLegacyReadFallback:
diff --git a/tests/research_library/test_download_service_contracts.py b/tests/research_library/test_download_service_contracts.py
index f4c475b124..25723ecd3f 100644
--- a/tests/research_library/test_download_service_contracts.py
+++ b/tests/research_library/test_download_service_contracts.py
@@ -485,13 +485,13 @@ def filesystem_mode(monkeypatch):
(
"https://evil.example.com/a/../../../../etc/cron.d/pwn.pdf"
"?filename=../../../../outside/pwn.pdf",
- "{resource_id}.pdf",
+ "{resource_id}_{content_hash}.pdf",
),
# arXiv takes the regex-extracted id branch; the hostile query is
# not part of the name.
(
"https://arxiv.org/pdf/2401.12345v1?f=../../../outside/pwn.pdf",
- "arxiv_2401.12345.pdf",
+ "arxiv_2401.12345_{content_hash}.pdf",
),
],
)
@@ -520,7 +520,10 @@ def test_storage_path_comes_from_server_side_values_only(
db.session.commit()
assert success is True, reason
- expected = expected_name.format(resource_id=fixture.resource.id)
+ expected = expected_name.format(
+ resource_id=fixture.resource.id,
+ content_hash=hashlib.sha256(PDF_BYTES).hexdigest(),
+ )
written = store.root / "pdfs" / expected
# The exact whole-sandbox diff: one new file, at the expected path.