~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): record PDF downloads as completed only after the file is saved (#7856)
LearningCircuit6bdfc13920ae
diff --git a/changelog.d/5868.bugfix.md b/changelog.d/5868.bugfix.mdnew file mode 100644index 0000000000..8220014ce6--- /dev/null+++ b/changelog.d/5868.bugfix.md@@ -0,0 +1 @@+A PDF download whose write to filesystem PDF storage fails partway, for example on a full disk, no longer leaves a truncated PDF file in the library folder. The PDF is written to a temporary file beside its final name and moved into place only once it is complete, so a failed write leaves neither a partial file nor a damaged copy of a PDF already stored under that name. This protects against a write that fails, not against a power loss: the file is not flushed to disk before the move. The download is recorded as failed, with no document marked completed for it, and the next download stores the PDF, except when the download also creates the default Library collection: creating it commits the bookkeeping already staged, so the success rows stay even if the write fails. This now also holds for a download whose PDF matches a library document that has no stored PDF, for example one downloaded with PDF storage off: when storing the PDF in that document failed, the download was recorded as completed and linked to it, and the PDF was not downloaded again.diff --git a/src/local_deep_research/research_library/services/download_service.py b/src/local_deep_research/research_library/services/download_service.pyindex b3794ef8fe..8c1b368a78 100644--- a/src/local_deep_research/research_library/services/download_service.py+++ b/src/local_deep_research/research_library/services/download_service.py@@ -2915,6 +2915,7 @@ class DownloadService:# the second tracker claims success. Only upgrade (never# downgrade): when the canonical already stores the PDF,# mirror its location onto this tracker for consistency.+ upgrade_write_failed = Falsetry:missing_pdf = canonical_retry and not (pdf_storage_manager.has_pdf(@@ -2931,16 +2932,30 @@ class DownloadService:pdf_storage_mode in ("database", "filesystem"))if needs_upgrade:- file_path_result, _ = (- pdf_storage_manager.save_pdf(- pdf_content=pdf_content,- document=existing_by_hash,- session=sess,- filename=f"{target_resource.id}.pdf",- url=url,- resource_id=target_resource.id,+ try:+ file_path_result, _ = (+ pdf_storage_manager.save_pdf(+ pdf_content=pdf_content,+ document=existing_by_hash,+ session=sess,+ filename=f"{target_resource.id}.pdf",+ url=url,+ resource_id=target_resource.id,+ ))- )+ except Exception:+ # A write that fails, for example on a+ # full disk, fails the download also+ # without a canonical retry (issue+ # #5868). Linking would record a+ # success with no PDF stored and leave+ # the resource counted as downloaded,+ # so nothing would fetch it again. The+ # rollback keeps the canonical document+ # as it was, and the next download+ # links it and stores the PDF.+ upgrade_write_failed = True+ raiseif _pdf_storage_refused(file_path_result,pdf_storage_manager.storage_mode,@@ -3065,7 +3080,7 @@ class DownloadService:"Failed to reuse/upgrade deduped PDF storage",exc,)- if canonical_retry:+ if canonical_retry or upgrade_write_failed:raiseif hasattr(tracker, "file_path"):tracker.file_path = target_tracker.file_pathdiff --git a/src/local_deep_research/research_library/services/pdf_storage_manager.py b/src/local_deep_research/research_library/services/pdf_storage_manager.pyindex 80e6b79e74..230fc1cdae 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@@ -7,8 +7,11 @@ Handles PDF storage across three modes:- database: Store PDFs encrypted in SQLCipher database (secure, portable)"""+import errnoimport hashlib+import osimport re+import uuidfrom datetime import datetime, UTCfrom pathlib import Pathfrom typing import Optional, Tuple@@ -391,17 +394,45 @@ class PDFStorageManager:# Pass current storage_mode as snapshot since we already validated itfrom ...security.file_write_verifier import write_file_verified- write_file_verified(- validated_path,- pdf_content,- "research_library.pdf_storage_mode",- "filesystem",- "library PDF storage",- mode="wb",- settings_snapshot={- "research_library.pdf_storage_mode": self.storage_mode- },+ # Write the bytes to a staged file beside the destination and move+ # it into place only once every byte is written (issue #5868). A+ # write that fails partway, for example on a full disk, then leaves+ # no truncated PDF under the stored name, and does not truncate a+ # complete PDF already stored there. The move stays in one+ # directory, so it replaces the destination in a single step. The+ # ".tmp" suffix keeps a staged file from passing for a stored PDF.+ if validated_path.is_symlink():+ # The in-place write refused a symlinked leaf (O_NOFOLLOW);+ # refuse it here too instead of replacing the link. The OS+ # message for ELOOP, with no path, keeps the reason a download+ # reports a client-safe "filesystem_error:" one, as the+ # O_NOFOLLOW refusal was.+ raise OSError(errno.ELOOP, os.strerror(errno.ELOOP))+ staged_path = validated_path.with_name(+ f".ldr-pdf-{uuid.uuid4().hex}.tmp")+ try:+ write_file_verified(+ staged_path,+ pdf_content,+ "research_library.pdf_storage_mode",+ "filesystem",+ "library PDF storage",+ mode="wb",+ settings_snapshot={+ "research_library.pdf_storage_mode": self.storage_mode+ },+ )+ staged_path.replace(validated_path)+ finally:+ # After a successful move there is nothing left to remove.+ try:+ staged_path.unlink(missing_ok=True)+ except OSError as exc:+ logger.warning(+ "Could not remove a staged PDF file ({error_type})",+ error_type=type(exc).__name__,+ )return Path(validated_path)diff --git a/tests/research_library/services/test_pdf_storage_manager.py b/tests/research_library/services/test_pdf_storage_manager.pyindex ceca01550e..d8e303108b 100644--- a/tests/research_library/services/test_pdf_storage_manager.py+++ b/tests/research_library/services/test_pdf_storage_manager.py@@ -1,7 +1,9 @@"""Tests for PDF Storage Manager."""+import errnoimport hashlibimport os+from pathlib import Pathfrom unittest.mock import MagicMock, patchimport pytest@@ -744,6 +746,135 @@ class TestPDFStorageManagerFilesystemWrite:assert [p.name for p in (tmp_path / "pdfs").iterdir()] == [name]+def _write_half_then_fail(path, content, *args, **kwargs):+ """Write half the bytes, then fail the way a full disk does."""+ Path(path).write_bytes(content[: len(content) // 2])+ raise OSError(errno.ENOSPC, "No space left on device")+++class TestPDFStorageManagerFailedWrite:+ """A filesystem write that fails partway leaves no partial PDF (#5868).++ ``_save_to_filesystem`` stages the bytes beside the destination and+ moves them into place only once the write completed. The in-place+ write it replaced left a truncated PDF under the stored name, and+ truncated a complete PDF already stored there.+ """++ @staticmethod+ def _stored_name(content):+ return f"paper_{hashlib.sha256(content).hexdigest()}.pdf"++ def test_a_failed_write_leaves_no_partial_file(+ self, tmp_path, mock_pdf_content, monkeypatch+ ):+ from local_deep_research.security import file_write_verifier++ manager = PDFStorageManager(tmp_path, "filesystem")+ document = MagicMock()+ document.storage_mode = "none"+ document.file_path = None+ # _save_to_filesystem imports write_file_verified inside the+ # function, so the source module is where a patch takes effect.+ monkeypatch.setattr(+ file_write_verifier, "write_file_verified", _write_half_then_fail+ )++ with pytest.raises(OSError, match="No space left on device"):+ manager.save_pdf(+ mock_pdf_content, document, MagicMock(), "paper.pdf"+ )++ assert list((tmp_path / "pdfs").iterdir()) == []+ # The document is not labelled as storing the PDF.+ assert document.storage_mode == "none"+ assert document.file_path is None++ def test_a_failed_rewrite_keeps_the_complete_stored_pdf(+ self, tmp_path, mock_pdf_content, monkeypatch+ ):+ from local_deep_research.security import file_write_verifier++ manager = PDFStorageManager(tmp_path, "filesystem")+ stored = manager._save_to_filesystem(mock_pdf_content, "paper.pdf")+ assert stored.name == self._stored_name(mock_pdf_content)+ monkeypatch.setattr(+ file_write_verifier, "write_file_verified", _write_half_then_fail+ )++ with pytest.raises(OSError, match="No space left on device"):+ manager._save_to_filesystem(mock_pdf_content, "paper.pdf")++ assert stored.read_bytes() == mock_pdf_content+ assert [p.name for p in (tmp_path / "pdfs").iterdir()] == [stored.name]++ def test_a_successful_write_leaves_only_the_stored_pdf(+ self, tmp_path, mock_pdf_content+ ):+ manager = PDFStorageManager(tmp_path, "filesystem")+ document = MagicMock()+ name = self._stored_name(mock_pdf_content)++ for _ in range(2):+ stored_path, size = manager.save_pdf(+ mock_pdf_content, document, MagicMock(), "paper.pdf"+ )++ assert (stored_path, size) == (+ f"pdfs/{name}",+ len(mock_pdf_content),+ )+ assert document.storage_mode == "filesystem"+ assert document.file_path == stored_path+ # No staged file is left beside the stored PDF, also after+ # the same PDF is written again over it.+ assert [p.name for p in (tmp_path / "pdfs").iterdir()] == [name]+ assert (tmp_path / "pdfs" / name).read_bytes() == mock_pdf_content++ def test_a_symlinked_destination_inside_the_store_is_refused(+ self, tmp_path, mock_pdf_content+ ):+ """A symlinked destination present when the write begins is refused.++ The in-place write refused it with ELOOP through O_NOFOLLOW, and+ the staged write keeps that refusal from its own is_symlink()+ check: the link and its target stay as they were. The refusal+ carries the OS message for ELOOP, so a download still reports it+ as a client-safe filesystem error. This protects against a link+ present at the check, not against one planted after it: the move+ then replaces the link itself and the download records success,+ but it never writes through a link, so the link's target is never+ touched.+ """+ from local_deep_research.security.client_safe_errors import (+ client_safe_download_message,+ )++ pdf_dir = tmp_path / "pdfs"+ pdf_dir.mkdir()+ other = pdf_dir / "other.pdf"+ other.write_bytes(b"OTHER")+ link = pdf_dir / self._stored_name(mock_pdf_content)+ try:+ link.symlink_to(other)+ except (OSError, NotImplementedError):+ pytest.skip("Cannot create symlinks in this environment")+ manager = PDFStorageManager(tmp_path, "filesystem")++ with pytest.raises(OSError) as excinfo:+ manager._save_to_filesystem(mock_pdf_content, "paper.pdf")++ assert excinfo.value.errno == errno.ELOOP+ assert client_safe_download_message(excinfo.value) == (+ f"filesystem_error:{os.strerror(errno.ELOOP)}"+ )+ assert link.is_symlink()+ assert other.read_bytes() == b"OTHER"+ assert sorted(p.name for p in pdf_dir.iterdir()) == sorted(+ [link.name, other.name]+ )++class TestPDFStorageManagerGenerateFilename:"""Tests for _generate_filename method."""diff --git a/tests/research_library/test_download_service_contracts.py b/tests/research_library/test_download_service_contracts.pyindex 20d13f5f76..d8e95bacb4 100644--- a/tests/research_library/test_download_service_contracts.py+++ b/tests/research_library/test_download_service_contracts.py@@ -56,8 +56,13 @@ Covered:resulting Document is labelled ``file_type="pdf"`` /``mime_type="application/pdf"`` regardless of its bytes (DEFECT --xfail);- * a write that fails part-way leaves no COMPLETED row (holds) but does- leave the truncated file behind (DEFECT -- xfail);+ * a write that fails part-way leaves no COMPLETED row and no truncated+ file behind (issue #5868), whether it retries a failed document,+ creates a new one, refills a document awaiting its PDF, stores the+ PDF in a matching document that has none (content-hash dedup, also+ without a canonical retry) or persists a PDF at fetch time, and the+ next download stores the PDF; a failed rewrite keeps a PDF already+ stored under the same name;* retrying a failed resource updates in place -- one Document, oneblob, one attempt row per attempt;* HTML-only responses are distinguished from actual access failures in@@ -1575,21 +1580,16 @@ def test_a_write_that_fails_partway_leaves_no_completed_row(assert attempts[0].succeeded is False- strict=True,- reason=(- "DEFECT: _save_to_filesystem writes in place via "- "write_file_verified(mode='wb') with no temp-file-and-rename and "- "no cleanup on failure, so a write that dies partway leaves a "- "truncated .pdf in the store. The DB rolls back and forgets it, "- "making it an orphan that load_pdf/has_pdf will still find and "- "serve."- ),-)def test_a_write_that_fails_partway_leaves_no_half_written_file(db, store, seeded, filesystem_mode, monkeypatch):- """CONTRACT: a failed download leaves nothing behind on disk."""+ """CONTRACT: a failed download leaves nothing behind on disk.++ Issue #5868: ``_save_to_filesystem`` wrote in place, so a write that+ died partway left a truncated .pdf in the store that the rolled-back+ database no longer knew about. It now stages the bytes and moves them+ into place only once the write completed.+ """fixture = seeded("https://evil.example.com/paper.pdf")before = _tree(store.sandbox)# _save_to_filesystem imports write_file_verified INSIDE the function,@@ -1608,6 +1608,530 @@ def test_a_write_that_fails_partway_leaves_no_half_written_file(assert _tree(store.sandbox) == before+def _stored_pdf(store, resource_id, content):+ """The sandbox-relative path ``_save_to_filesystem`` stores ``content`` at+ for a generic URL, and its ``file_path`` relative to the library root."""+ name = f"{resource_id}_{hashlib.sha256(content).hexdigest()}.pdf"+ stored = store.root / "pdfs" / name+ return stored.relative_to(store.sandbox).as_posix(), f"pdfs/{name}"+++def test_a_new_document_write_that_fails_partway_is_not_recorded(+ db, store, seeded, filesystem_mode, monkeypatch+):+ """A new document whose PDF write fails partway is not kept (#5868).++ ``_save_pdf_document_record`` adds the document as COMPLETED before+ ``save_pdf`` writes the file. The failed write rolls the document back,+ leaves no truncated file, and records a failed attempt; the next+ download, with the disk writable again, creates the document COMPLETED+ with the stored PDF.+ """+ from local_deep_research.database.models.library import Collection+ from local_deep_research.research_library.services import download_service++ fixture = seeded("https://example.com/new-document.pdf")+ resource_id = fixture.resource.id+ tracker_id = fixture.tracker.id+ url_hash = fixture.tracker.url_hash+ # Without the seeded FAILED document the download takes the+ # new-document branch. The source type and default library lookups+ # open their own user-database sessions, so they answer from the seed.+ db.session.add(Collection(id="new-library", name="New library"))+ db.session.delete(fixture.document)+ db.session.commit()+ monkeypatch.setattr(+ download_service,+ "get_source_type_id",+ lambda *a: fixture.source_type.id,+ )+ monkeypatch.setattr(+ download_service, "get_default_library_id", lambda *a: "new-library"+ )+ write_file = file_write_verifier.write_file_verified+ monkeypatch.setattr(+ file_write_verifier, "write_file_verified", _explode_mid_write+ )+ downloader = StubDownloader(+ DownloadResult(content=PDF_BYTES, is_success=True, status_code=200)+ )+ service = make_service(store, downloader, storage_mode="filesystem")+ service._extract_text_from_pdf = lambda content: None++ success, _reason, _ = service._download_pdf(+ fixture.resource, fixture.tracker, db.session, None+ )+ db.session.commit()++ assert success is False+ with db.fresh() as other:+ assert (+ other.query(Document).filter_by(resource_id=resource_id).count()+ == 0+ )+ assert other.query(DocumentBlob).count() == 0+ tracker = other.get(DownloadTracker, tracker_id)+ assert (tracker.is_downloaded, tracker.file_path) == (False, None)+ attempts = (+ other.query(DownloadAttempt).filter_by(url_hash=url_hash).all()+ )+ assert [attempt.succeeded for attempt in attempts] == [False]+ assert _tree(store.sandbox) == set()++ monkeypatch.setattr(file_write_verifier, "write_file_verified", write_file)+ success, reason, _ = service._download_pdf(+ fixture.resource, fixture.tracker, db.session, None+ )+ db.session.commit()++ assert success is True, reason+ stored, file_path = _stored_pdf(store, resource_id, PDF_BYTES)+ with db.fresh() as other:+ doc = other.query(Document).filter_by(resource_id=resource_id).one()+ assert doc.status is DocumentStatus.COMPLETED+ assert (doc.storage_mode, doc.file_path) == ("filesystem", file_path)+ attempts = (+ other.query(DownloadAttempt)+ .filter_by(url_hash=url_hash)+ .order_by(DownloadAttempt.id)+ .all()+ )+ assert [attempt.succeeded for attempt in attempts] == [False, True]+ assert _tree(store.sandbox) == {stored}++[email protected]("site", ["own-document", "linked-canonical"])+def test_a_refill_write_that_fails_partway_keeps_the_document_awaiting_its_pdf(+ db, store, seeded, filesystem_mode, monkeypatch, site+):+ """A refill whose PDF write fails partway still awaits its PDF (#5868).++ A refill of a document that "Sync library" left awaiting its PDF sets+ it COMPLETED and gives it the new bytes' hash before ``save_pdf``+ writes the file. The failed write rolls that back: the document keeps+ its text and still awaits its PDF, so the Download Manager offers it+ again, and no truncated file is left. ``own-document`` takes the+ existing-document branch, ``linked-canonical`` the content-hash dedup+ branch. The next refill stores the PDF in the same document.+ """+ from local_deep_research.constants import FILE_PATH_TEXT_ONLY+ from local_deep_research.research_library.utils import document_awaits_pdf++ awaiting_id, refill = _document_awaiting_its_pdf(db, seeded, site)+ tracker_id = refill.tracker.id+ url_hash = refill.tracker.url_hash+ write_file = file_write_verifier.write_file_verified+ monkeypatch.setattr(+ file_write_verifier, "write_file_verified", _explode_mid_write+ )+ # The linked-canonical document carries OVERSIZED_PDF's hash; the+ # default limit of make_service stores it.+ downloader = StubDownloader(+ DownloadResult(content=OVERSIZED_PDF, is_success=True, status_code=200)+ )+ service = make_service(store, downloader, storage_mode="filesystem")+ service._extract_text_from_pdf = lambda content: None++ success, _reason, _ = service._download_pdf(+ refill.resource, refill.tracker, db.session, "refill-collection"+ )+ db.session.commit()++ assert success is False+ with db.fresh() as other:+ doc = other.get(Document, awaiting_id)+ assert other.query(Document).count() == 1+ assert document_awaits_pdf(doc)+ assert (doc.storage_mode, doc.file_path) == (+ "none",+ FILE_PATH_TEXT_ONLY,+ )+ assert doc.text_content == "text kept by the sync"+ assert other.query(DocumentBlob).count() == 0+ tracker = other.get(DownloadTracker, tracker_id)+ assert (tracker.is_downloaded, tracker.file_path) == (False, None)+ attempts = (+ other.query(DownloadAttempt).filter_by(url_hash=url_hash).all()+ )+ assert [attempt.succeeded for attempt in attempts] == [False]+ assert _tree(store.sandbox) == set()++ monkeypatch.setattr(file_write_verifier, "write_file_verified", write_file)+ success, reason, _ = service._download_pdf(+ refill.resource, refill.tracker, db.session, "refill-collection"+ )+ db.session.commit()++ assert success is True, reason+ with db.fresh() as other:+ doc = other.get(Document, awaiting_id)+ assert other.query(Document).count() == 1+ assert doc.status is DocumentStatus.COMPLETED+ assert not document_awaits_pdf(doc)+ assert doc.storage_mode == "filesystem"+ assert doc.text_content == "text kept by the sync"+ manager = PDFStorageManager(+ library_root=store.root, storage_mode="filesystem"+ )+ assert manager.load_pdf(doc, other) == OVERSIZED_PDF+ assert len(_tree(store.sandbox)) == 1+++def _rolling_back_download_session(db, monkeypatch):+ """Give the download service one reused session, rolled back on error.++ Like ``_one_download_session``, but a scope that raises rolls the+ session back before the error propagates, as ``get_user_db_session``+ does, so a failed write is judged by what production keeps rather+ than by pending changes a bare ``nullcontext`` would leave behind.+ """+ from local_deep_research.research_library.services import download_service++ @contextmanager+ def scope(*args, **kwargs):+ try:+ yield db.download_session+ except Exception:+ db.download_session.rollback()+ raise++ monkeypatch.setattr(download_service, "get_user_db_session", scope)+++def test_a_fetch_time_write_that_fails_partway_is_not_recorded(+ db, store, seeded, filesystem_mode, monkeypatch+):+ """Fetch-time persistence whose PDF write fails partway keeps nothing.++ ``_do_persist_downloaded_pdf_on_the_spot`` (a research's own fetch,+ with auto-persistence on) adds the document as COMPLETED before+ ``save_pdf`` writes the file (#5868). The failed write rolls it back+ and leaves no truncated file; the next fetch persists the document+ COMPLETED with the stored PDF and its text.+ """+ from local_deep_research.database.models.library import Collection+ from local_deep_research.research_library.services import download_service++ fixture = seeded("https://example.com/fetched.pdf")+ resource_id = fixture.resource.id+ url = fixture.resource.url+ db.session.add(Collection(id="fetch-library", name="Fetch library"))+ db.session.delete(fixture.document)+ db.session.commit()+ monkeypatch.setattr(+ download_service,+ "get_source_type_id",+ lambda *a: fixture.source_type.id,+ )+ _rolling_back_download_session(db, monkeypatch)+ write_file = file_write_verifier.write_file_verified+ monkeypatch.setattr(+ file_write_verifier, "write_file_verified", _explode_mid_write+ )++ def persist():+ return download_service._do_persist_downloaded_pdf_on_the_spot(+ url=url,+ pdf_content=PDF_BYTES,+ text=SEARCHABLE_TEXT,+ title="Fetched paper",+ username=USERNAME,+ settings_snapshot={+ "document_scheduler.download_pdfs": True,+ "research_library.pdf_storage_mode": "filesystem",+ "research_library.max_pdf_size_mb": 3072,+ },+ library_root=store.root,+ collection_id="fetch-library",+ resource_id=resource_id,+ )++ assert persist() is None+ with db.fresh() as other:+ assert other.query(Document).count() == 0+ assert other.query(DocumentBlob).count() == 0+ assert _tree(store.sandbox) == set()++ monkeypatch.setattr(file_write_verifier, "write_file_verified", write_file)+ doc_id = persist()++ assert doc_id is not None+ stored, file_path = _stored_pdf(store, resource_id, PDF_BYTES)+ with db.fresh() as other:+ doc = other.get(Document, doc_id)+ assert doc.status is DocumentStatus.COMPLETED+ assert (doc.storage_mode, doc.file_path) == ("filesystem", file_path)+ assert doc.text_content == SEARCHABLE_TEXT+ assert _tree(store.sandbox) == {stored}+++def test_a_dedup_upgrade_write_that_fails_partway_is_not_recorded(+ db, store, seeded, filesystem_mode, monkeypatch+):+ """A duplicate whose PDF write into the matching document fails (#5868).++ The duplicate's bytes match a document that a download with PDF+ storage off kept without its PDF. The content-hash dedup links the+ duplicate to it and stores the PDF there, with no canonical retry+ involved. A write that fails partway used to be logged as best-effort+ and the download recorded as a success, with the duplicate linked,+ its tracker downloaded and nothing stored, so nothing fetched it+ again. Now the download is recorded as failed and rolled back, and+ the next download links the duplicate and stores the PDF in the+ matching document.+ """+ from local_deep_research.database.models.library import (+ Collection,+ DocumentCollection,+ )++ canonical = seeded("https://example.com/canonical.pdf")+ duplicate = seeded("https://example.com/duplicate.pdf")+ canonical_id = canonical.document.id+ canonical_tracker_id = canonical.tracker.id+ duplicate_resource_id = duplicate.resource.id+ duplicate_tracker_id = duplicate.tracker.id+ duplicate_url_hash = duplicate.tracker.url_hash+ file_hash = hashlib.sha256(PDF_BYTES).hexdigest()+ # The shape a download with PDF storage "none" leaves: COMPLETED, the+ # content hash, the text, and no stored PDF.+ document = canonical.document+ document.status = DocumentStatus.COMPLETED+ document.document_hash = file_hash+ document.file_size = len(PDF_BYTES)+ document.text_content = "text of the canonical download"+ canonical.tracker.file_hash = file_hash+ canonical.tracker.is_downloaded = True+ db.session.delete(duplicate.document)+ db.session.add(Collection(id="dedup-collection", name="Dedup"))+ db.session.commit()+ write_file = file_write_verifier.write_file_verified+ monkeypatch.setattr(+ file_write_verifier, "write_file_verified", _explode_mid_write+ )+ downloader = StubDownloader(+ DownloadResult(content=PDF_BYTES, is_success=True, status_code=200)+ )+ service = make_service(store, downloader, storage_mode="filesystem")+ service._extract_text_from_pdf = lambda content: None++ success, _reason, _ = service._download_pdf(+ duplicate.resource, duplicate.tracker, db.session, "dedup-collection"+ )+ db.session.commit()++ assert success is False+ with db.fresh() as other:+ assert other.query(Document).count() == 1+ doc = other.get(Document, canonical_id)+ assert doc.status is DocumentStatus.COMPLETED+ assert (doc.storage_mode, doc.file_path) == ("none", None)+ assert doc.text_content == "text of the canonical download"+ assert other.query(DocumentBlob).count() == 0+ assert other.query(DocumentCollection).count() == 0+ assert (+ other.get(ResearchResource, duplicate_resource_id).document_id+ is None+ )+ tracker = other.get(DownloadTracker, duplicate_tracker_id)+ assert (tracker.is_downloaded, tracker.file_path) == (False, None)+ assert (+ other.get(DownloadTracker, canonical_tracker_id).file_path is None+ )+ attempts = (+ other.query(DownloadAttempt)+ .filter_by(url_hash=duplicate_url_hash)+ .all()+ )+ assert [attempt.succeeded for attempt in attempts] == [False]+ assert _tree(store.sandbox) == set()++ monkeypatch.setattr(file_write_verifier, "write_file_verified", write_file)+ success, reason, _ = service._download_pdf(+ duplicate.resource, duplicate.tracker, db.session, "dedup-collection"+ )+ db.session.commit()++ assert success is True, reason+ stored, file_path = _stored_pdf(store, duplicate_resource_id, PDF_BYTES)+ with db.fresh() as other:+ assert other.query(Document).count() == 1+ doc = other.get(Document, canonical_id)+ assert doc.status is DocumentStatus.COMPLETED+ assert (doc.storage_mode, doc.file_path) == ("filesystem", file_path)+ assert doc.text_content == "text of the canonical download"+ manager = PDFStorageManager(+ library_root=store.root, storage_mode="filesystem"+ )+ assert manager.load_pdf(doc, other) == PDF_BYTES+ assert (+ other.get(ResearchResource, duplicate_resource_id).document_id+ == canonical_id+ )+ assert {+ row.collection_id for row in other.query(DocumentCollection).all()+ } == {"dedup-collection"}+ tracker = other.get(DownloadTracker, duplicate_tracker_id)+ assert (tracker.is_downloaded, tracker.file_path) == (True, file_path)+ assert (+ other.get(DownloadTracker, canonical_tracker_id).file_path+ == file_path+ )+ attempts = (+ other.query(DownloadAttempt)+ .filter_by(url_hash=duplicate_url_hash)+ .order_by(DownloadAttempt.id)+ .all()+ )+ assert [attempt.succeeded for attempt in attempts] == [False, True]+ assert _tree(store.sandbox) == {stored}+++def test_a_fetch_time_write_into_a_matching_document_that_fails_keeps_it(+ db, store, seeded, filesystem_mode, monkeypatch+):+ """Fetch-time persistence into a document with the same bytes (#5868).++ ``_save_pdf_document_record`` reuses the document whose hash matches+ the fetched bytes. Here it stores no PDF (a download with PDF storage+ off, which found no text), so persistence gives it the text and then+ writes the PDF. A write that fails partway leaves no truncated file+ and leaves the document as it was; the next fetch stores the PDF and+ the text in that same document.+ """+ from local_deep_research.database.models.library import Collection+ from local_deep_research.research_library.services import download_service++ fixture = seeded("https://example.com/fetched-again.pdf")+ resource_id = fixture.resource.id+ document_id = fixture.document.id+ tracker_id = fixture.tracker.id+ url = fixture.resource.url+ document = fixture.document+ document.status = DocumentStatus.COMPLETED+ document.document_hash = hashlib.sha256(PDF_BYTES).hexdigest()+ document.file_size = len(PDF_BYTES)+ db.session.add(Collection(id="fetch-library", name="Fetch library"))+ db.session.commit()+ _rolling_back_download_session(db, monkeypatch)+ write_file = file_write_verifier.write_file_verified+ monkeypatch.setattr(+ file_write_verifier, "write_file_verified", _explode_mid_write+ )++ def persist():+ return download_service._do_persist_downloaded_pdf_on_the_spot(+ url=url,+ pdf_content=PDF_BYTES,+ text=SEARCHABLE_TEXT,+ title="Fetched paper",+ username=USERNAME,+ settings_snapshot={+ "document_scheduler.download_pdfs": True,+ "research_library.pdf_storage_mode": "filesystem",+ "research_library.max_pdf_size_mb": 3072,+ },+ library_root=store.root,+ collection_id="fetch-library",+ resource_id=resource_id,+ )++ assert persist() is None+ with db.fresh() as other:+ assert other.query(Document).count() == 1+ doc = other.get(Document, document_id)+ assert doc.status is DocumentStatus.COMPLETED+ assert (doc.storage_mode, doc.file_path) == ("none", None)+ assert doc.text_content is None+ assert other.query(DocumentBlob).count() == 0+ tracker = other.get(DownloadTracker, tracker_id)+ assert (tracker.is_downloaded, tracker.file_path) == (False, None)+ assert _tree(store.sandbox) == set()++ monkeypatch.setattr(file_write_verifier, "write_file_verified", write_file)++ assert persist() == document_id+ stored, file_path = _stored_pdf(store, resource_id, PDF_BYTES)+ with db.fresh() as other:+ assert other.query(Document).count() == 1+ doc = other.get(Document, document_id)+ assert (doc.storage_mode, doc.file_path) == ("filesystem", file_path)+ assert doc.text_content == SEARCHABLE_TEXT+ tracker = other.get(DownloadTracker, tracker_id)+ assert (tracker.is_downloaded, tracker.file_path) == (True, file_path)+ assert _tree(store.sandbox) == {stored}+++def test_a_failed_rewrite_keeps_the_pdf_a_document_already_stores(+ db, store, seeded, filesystem_mode, monkeypatch+):+ """A retry whose rewrite of a stored PDF fails partway keeps it (#5868).++ A document whose PDF is stored is FAILED when a later text extraction+ fails, and still names its file. Its retry downloads the same bytes and+ writes them under the same file name. The in-place write truncated+ that stored PDF when it failed partway; the staged write leaves it+ whole, and the document still loads it. The next retry completes the+ document with the same file.+ """+ fixture = seeded("https://example.com/stored.pdf")+ resource_id = fixture.resource.id+ document_id = fixture.document.id+ url_hash = fixture.tracker.url_hash+ stored, file_path = _stored_pdf(store, resource_id, PDF_BYTES)+ (store.sandbox / stored).write_bytes(PDF_BYTES)+ document = fixture.document+ document.document_hash = hashlib.sha256(PDF_BYTES).hexdigest()+ document.file_size = len(PDF_BYTES)+ document.storage_mode = "filesystem"+ document.file_path = file_path+ db.session.commit()+ write_file = file_write_verifier.write_file_verified+ monkeypatch.setattr(+ file_write_verifier, "write_file_verified", _explode_mid_write+ )+ downloader = StubDownloader(+ DownloadResult(content=PDF_BYTES, is_success=True, status_code=200)+ )+ service = make_service(store, downloader, storage_mode="filesystem")+ service._extract_text_from_pdf = lambda content: None+ manager = PDFStorageManager(+ library_root=store.root, storage_mode="filesystem"+ )++ success, _reason, _ = service._download_pdf(+ fixture.resource, fixture.tracker, db.session, None+ )+ db.session.commit()++ assert success is False+ assert (store.sandbox / stored).read_bytes() == PDF_BYTES+ assert _tree(store.sandbox) == {stored}+ with db.fresh() as other:+ doc = other.get(Document, document_id)+ assert doc.status is DocumentStatus.FAILED+ assert (doc.storage_mode, doc.file_path) == ("filesystem", file_path)+ assert manager.load_pdf(doc, other) == PDF_BYTES+ attempts = (+ other.query(DownloadAttempt).filter_by(url_hash=url_hash).all()+ )+ assert [attempt.succeeded for attempt in attempts] == [False]++ monkeypatch.setattr(file_write_verifier, "write_file_verified", write_file)+ success, reason, _ = service._download_pdf(+ fixture.resource, fixture.tracker, db.session, None+ )+ db.session.commit()++ assert success is True, reason+ assert _tree(store.sandbox) == {stored}+ with db.fresh() as other:+ doc = other.get(Document, document_id)+ assert doc.status is DocumentStatus.COMPLETED+ assert (doc.storage_mode, doc.file_path) == ("filesystem", file_path)+ assert manager.load_pdf(doc, other) == PDF_BYTES++def test_retrying_a_failed_resource_does_not_duplicate_rows(db, store, seeded):"""Attempt 1 fails, attempt 2 succeeds: one Document, one blob.diff --git a/tests/security/test_remote_filename_writes.py b/tests/security/test_remote_filename_writes.pyindex 905e5ade59..879e10f68c 100644--- a/tests/security/test_remote_filename_writes.py+++ b/tests/security/test_remote_filename_writes.py@@ -30,7 +30,6 @@ Run with: .venv/bin/python -m pytest tests/security/test_remote_filename_writes.from __future__ import annotations-import osfrom pathlib import Pathfrom typing import Optional@@ -232,15 +231,16 @@ class TestURLDerivedFilename:class TestSymlinkWriteEscape:"""A symlink planted at the intended PDF filename must not redirect writes.- The verified writer refuses the link where O_NOFOLLOW is available.- The outside canary must survive, and legitimate in-root saves remain- covered by the positive controls."""+ ``_save_to_filesystem`` writes the bytes to a staged file and refuses a+ symlinked destination present when the write begins with ELOOP (its+ ``is_symlink()`` check) before moving that file into place, on every+ platform; the verified writer's O_NOFOLLOW never sees the destination.+ This protects against a link present at the check, not against one+ planted after it: the move then replaces the link itself and the+ download records success, but it never writes through a link, so the+ link's target is never touched. The outside canary must survive, and+ legitimate in-root saves remain covered by the positive controls."""- @pytest.mark.xfail(- not getattr(os, "O_NOFOLLOW", 0),- strict=True,- reason="The verified writer cannot refuse leaf symlinks without O_NOFOLLOW",- )def test_symlink_inside_pdf_subdir_does_not_let_write_escape(self,fs_storage,diff --git a/tests/security/test_verified_write_symlink_refusal.py b/tests/security/test_verified_write_symlink_refusal.pyindex 91b90d18d7..894b20cdb3 100644--- a/tests/security/test_verified_write_symlink_refusal.py+++ b/tests/security/test_verified_write_symlink_refusal.py@@ -1,7 +1,11 @@"""Regression tests: write_file_verified refuses to follow a symlink leaf.-The verified-write helper is the single chokepoint the library PDF write path-and the config/report writers use. Previously it opened the destination with a+The verified-write helper is the chokepoint the config/report writers use.+The library PDF write path also writes through it, but into a freshly named+staged file that it then moves into place, so its refusal of a symlinked+destination comes from its own ``is_symlink()`` check+(``PDFStorageManager._save_to_filesystem``), not from these.+Previously the helper opened the destination with aplain ``open(path, mode)``, so a symlink pre-planted at the target leaf wasfollowed and the write landed on the link's target -- potentially a fileoutside the intended directory. The read path already refused symlinks; these