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.

36.2 KB
Raw Blame
"""Tests for PDF Storage Manager."""

import errno
import hashlib
import os
from pathlib import Path
from unittest.mock import MagicMock, patch

import pytest

from local_deep_research.constants import (
    FILE_PATH_METADATA_ONLY,
)
from local_deep_research.database.models.library import DocumentBlob
from local_deep_research.research_library.services.pdf_storage_manager import (
    PDFStorageManager,
)


class TestPDFStorageManagerInit:
    """Tests for PDFStorageManager initialization."""

    def test_initializes_with_defaults(self, tmp_path):
        """Should initialize with default settings (3 GB)."""
        manager = PDFStorageManager(tmp_path, "database")
        assert manager.library_root == tmp_path.resolve()
        assert manager.storage_mode == "database"
        assert manager.max_pdf_size_bytes == 3072 * 1024 * 1024

    def test_initializes_with_custom_max_size(self, tmp_path):
        """Should use custom max PDF size."""
        manager = PDFStorageManager(tmp_path, "database", max_pdf_size_mb=50)
        assert manager.max_pdf_size_bytes == 50 * 1024 * 1024

    def test_accepts_valid_storage_modes(self, tmp_path):
        """Should accept all valid storage modes."""
        for mode in ("none", "filesystem", "database"):
            manager = PDFStorageManager(tmp_path, mode)
            assert manager.storage_mode == mode

    def test_defaults_to_none_for_invalid_mode(self, tmp_path):
        """Should default to 'none' for invalid storage mode."""
        manager = PDFStorageManager(tmp_path, "invalid_mode")
        assert manager.storage_mode == "none"


class TestPDFStorageManagerSavePdf:
    """Tests for save_pdf method."""

    def test_returns_none_for_none_mode(self, tmp_path, mock_pdf_content):
        """Should return None when storage mode is 'none'."""
        manager = PDFStorageManager(tmp_path, "none")
        mock_doc = MagicMock()
        mock_session = MagicMock()

        result, size = manager.save_pdf(
            mock_pdf_content, mock_doc, mock_session, "test.pdf"
        )

        assert result is None
        assert size == len(mock_pdf_content)

    def test_saves_to_database(self, tmp_path, mock_pdf_content):
        """Should save PDF to database when mode is 'database'."""
        manager = PDFStorageManager(tmp_path, "database")
        mock_doc = MagicMock()
        mock_doc.id = "doc-123"
        mock_session = MagicMock()
        mock_session.query.return_value.filter_by.return_value.first.return_value = None

        result, size = manager.save_pdf(
            mock_pdf_content, mock_doc, mock_session, "test.pdf"
        )

        assert result == "database"
        assert mock_doc.storage_mode == "database"
        assert mock_session.add.called

    def test_saves_to_filesystem(self, tmp_path, mock_pdf_content):
        """Should save PDF to filesystem when mode is 'filesystem'."""
        manager = PDFStorageManager(tmp_path, "filesystem")
        mock_doc = MagicMock()
        mock_doc.id = "doc-123"
        mock_session = MagicMock()

        # Mock the internal method to avoid file system operations
        with patch.object(
            manager,
            "_save_to_filesystem",
            return_value=tmp_path / "pdfs" / "test.pdf",
        ):
            result, size = manager.save_pdf(
                mock_pdf_content, mock_doc, mock_session, "test.pdf"
            )

        assert result is not None
        assert mock_doc.storage_mode == "filesystem"

    def test_rejects_oversized_pdf(self, tmp_path):
        """Should reject PDF that exceeds size limit."""
        manager = PDFStorageManager(tmp_path, "database", max_pdf_size_mb=1)
        mock_doc = MagicMock()
        mock_session = MagicMock()

        # Create content larger than 1MB
        large_content = b"x" * (2 * 1024 * 1024)

        result, size = manager.save_pdf(
            large_content, mock_doc, mock_session, "test.pdf"
        )

        assert result is None
        assert size == len(large_content)


class TestPDFStorageManagerLoadPdf:
    """Tests for load_pdf method."""

    def test_loads_from_database_first(self, tmp_path, mock_pdf_content):
        """Should try database first when loading."""
        manager = PDFStorageManager(tmp_path, "database")
        mock_doc = MagicMock()
        mock_doc.id = "doc-123"
        mock_session = MagicMock()

        # Mock database blob
        mock_blob = MagicMock()
        mock_blob.pdf_binary = mock_pdf_content
        mock_session.query.return_value.filter_by.return_value.first.return_value = mock_blob

        result = manager.load_pdf(mock_doc, mock_session)

        assert result == mock_pdf_content

    def test_falls_back_to_filesystem(self, tmp_path, mock_pdf_content):
        """Should fall back to filesystem if not in database."""
        manager = PDFStorageManager(tmp_path, "filesystem")
        mock_doc = MagicMock()
        mock_doc.id = "doc-123"
        mock_doc.file_path = "pdfs/test.pdf"
        mock_session = MagicMock()

        # No blob in database
        mock_session.query.return_value.filter_by.return_value.first.return_value = None

        # Create file on disk
        pdf_path = tmp_path / "pdfs"
        pdf_path.mkdir(parents=True, exist_ok=True)
        (pdf_path / "test.pdf").write_bytes(mock_pdf_content)

        result = manager.load_pdf(mock_doc, mock_session)

        assert result == mock_pdf_content

    def test_returns_none_when_not_found(self, tmp_path):
        """Should return None when PDF not found anywhere."""
        manager = PDFStorageManager(tmp_path, "database")
        mock_doc = MagicMock()
        mock_doc.id = "doc-123"
        mock_doc.file_path = None
        mock_session = MagicMock()

        mock_session.query.return_value.filter_by.return_value.first.return_value = None

        result = manager.load_pdf(mock_doc, mock_session)

        assert result is None


class TestPDFStorageManagerHasPdf:
    """Tests for has_pdf method."""

    def test_returns_false_for_non_pdf_file_type(self, tmp_path):
        """Should return False for non-PDF documents."""
        manager = PDFStorageManager(tmp_path, "database")
        mock_doc = MagicMock()
        mock_doc.file_type = "txt"
        mock_session = MagicMock()

        result = manager.has_pdf(mock_doc, mock_session)

        assert result is False

    def test_has_pdf_checks_database_first(self, tmp_path):
        """Should check database for blob existence."""
        manager = PDFStorageManager(tmp_path, "database")
        mock_doc = MagicMock()
        mock_doc.id = "doc-123"
        mock_doc.file_type = "pdf"
        mock_doc.file_path = None
        mock_session = MagicMock()

        # Mock session returns a truthy row, so the DB path should succeed
        # and the filesystem fallback should never be reached.
        mock_first = mock_session.query.return_value.filter_by.return_value
        mock_first.first.return_value = MagicMock()

        with patch.object(manager, "_get_safe_file_path") as mock_get_path:
            assert manager.has_pdf(mock_doc, mock_session) is True
            mock_session.query.assert_called_once_with(DocumentBlob.document_id)
            mock_session.query.return_value.filter_by.assert_called_once_with(
                document_id="doc-123"
            )
            mock_get_path.assert_not_called()

    def test_has_pdf_falls_back_to_filesystem_when_not_in_db(self, tmp_path):
        """Should fall back to checking filesystem if not found in database."""
        manager = PDFStorageManager(tmp_path, "database")
        mock_doc = MagicMock()
        mock_doc.id = "doc-123"
        mock_doc.file_type = "pdf"
        mock_doc.file_path = "pdfs/test.pdf"
        mock_session = MagicMock()

        mock_first = mock_session.query.return_value.filter_by.return_value
        mock_first.first.return_value = None

        with patch.object(manager, "_get_safe_file_path") as mock_get_path:
            mock_file_path = MagicMock()
            mock_file_path.is_file.return_value = True
            mock_get_path.return_value = mock_file_path

            assert manager.has_pdf(mock_doc, mock_session) is True
            mock_session.query.assert_called_once_with(DocumentBlob.document_id)
            mock_session.query.return_value.filter_by.assert_called_once_with(
                document_id="doc-123"
            )
            mock_get_path.assert_called_once_with("pdfs/test.pdf")

    def test_has_pdf_returns_false_when_not_in_db_and_not_on_filesystem(
        self, tmp_path
    ):
        """Should return False when PDF is in neither database nor filesystem."""
        manager = PDFStorageManager(tmp_path, "database")
        mock_doc = MagicMock()
        mock_doc.id = "doc-123"
        mock_doc.file_type = "pdf"
        mock_doc.file_path = "pdfs/missing.pdf"
        mock_session = MagicMock()

        mock_first = mock_session.query.return_value.filter_by.return_value
        mock_first.first.return_value = None

        with patch.object(manager, "_get_safe_file_path") as mock_get_path:
            mock_file_path = MagicMock()
            mock_file_path.is_file.return_value = False
            mock_get_path.return_value = mock_file_path

            assert manager.has_pdf(mock_doc, mock_session) is False
            mock_session.query.assert_called_once_with(DocumentBlob.document_id)
            mock_session.query.return_value.filter_by.assert_called_once_with(
                document_id="doc-123"
            )
            mock_get_path.assert_called_once_with("pdfs/missing.pdf")

    def test_has_pdf_returns_false_when_no_blob_and_file_path_none(
        self, tmp_path
    ):
        """Should return False when PDF is not in DB and document.file_path is None."""
        manager = PDFStorageManager(tmp_path, "database")
        mock_doc = MagicMock()
        mock_doc.id = "doc-123"
        mock_doc.file_type = "pdf"
        mock_doc.file_path = None
        mock_session = MagicMock()

        mock_first = mock_session.query.return_value.filter_by.return_value
        mock_first.first.return_value = None

        assert manager.has_pdf(mock_doc, mock_session) is False
        mock_session.query.assert_called_once_with(DocumentBlob.document_id)
        mock_session.query.return_value.filter_by.assert_called_once_with(
            document_id="doc-123"
        )

    def test_has_pdf_returns_false_when_path_traversal_blocked(self, tmp_path):
        """Should return False when path traversal protection rejects the file path."""
        manager = PDFStorageManager(tmp_path, "database")
        mock_doc = MagicMock()
        mock_doc.id = "doc-123"
        mock_doc.file_type = "pdf"
        mock_doc.file_path = "../../etc/passwd"
        mock_session = MagicMock()

        mock_first = mock_session.query.return_value.filter_by.return_value
        mock_first.first.return_value = None

        # Explicitly tie the False result to the traversal guard firing:
        # patch _get_safe_file_path so we can assert it was consulted with
        # the traversal string and returned None (the reject signal), rather
        # than merely inferring rejection from the boolean result.
        with patch.object(
            manager, "_get_safe_file_path", return_value=None
        ) as mock_get_path:
            assert manager.has_pdf(mock_doc, mock_session) is False
            mock_get_path.assert_called_once_with("../../etc/passwd")

        mock_session.query.assert_called_once_with(DocumentBlob.document_id)
        mock_session.query.return_value.filter_by.assert_called_once_with(
            document_id="doc-123"
        )


class TestPDFStorageManagerPdfExists:
    """Tests for pdf_exists classmethod."""

    def test_returns_false_for_non_pdf(self, tmp_path):
        """Should return False for non-PDF documents without requiring a storage mode."""
        mock_doc = MagicMock()
        mock_doc.file_type = "txt"
        mock_session = MagicMock()

        result = PDFStorageManager.pdf_exists(tmp_path, mock_doc, mock_session)

        assert result is False

    def test_returns_true_when_blob_exists(self, tmp_path):
        """Should find PDF in database via classmethod."""
        mock_doc = MagicMock()
        mock_doc.id = "doc-123"
        mock_doc.file_type = "pdf"
        mock_doc.file_path = None
        mock_session = MagicMock()

        # Simulate DocumentBlob found in database
        mock_session.query.return_value.filter_by.return_value.first.return_value = MagicMock()

        result = PDFStorageManager.pdf_exists(tmp_path, mock_doc, mock_session)

        assert result is True
        mock_session.query.assert_called_once_with(DocumentBlob.document_id)
        mock_session.query.return_value.filter_by.assert_called_once_with(
            document_id="doc-123"
        )

    def test_returns_true_when_file_exists(self, tmp_path):
        """Should find PDF on filesystem via classmethod."""
        pdf_dir = tmp_path / "pdfs"
        pdf_dir.mkdir()
        (pdf_dir / "test.pdf").write_bytes(b"%PDF-1.4 test")

        mock_doc = MagicMock()
        mock_doc.id = "doc-456"
        mock_doc.file_type = "pdf"
        mock_doc.file_path = "pdfs/test.pdf"
        mock_session = MagicMock()

        # No blob in database
        mock_session.query.return_value.filter_by.return_value.first.return_value = None

        result = PDFStorageManager.pdf_exists(tmp_path, mock_doc, mock_session)

        assert result is True
        mock_session.query.assert_called_once_with(DocumentBlob.document_id)
        mock_session.query.return_value.filter_by.assert_called_once_with(
            document_id="doc-456"
        )

    def test_returns_false_on_db_miss_and_filesystem_miss(self, tmp_path):
        """Direct negative case: no blob in the DB AND no file on disk must
        yield False. Pins the both-backends-miss path end-to-end through the
        classmethod (not just the non-PDF short-circuit)."""
        mock_doc = MagicMock()
        mock_doc.id = "doc-789"
        mock_doc.file_type = "pdf"
        # Points at a file that does not exist under library_root.
        mock_doc.file_path = "pdfs/missing.pdf"
        mock_session = MagicMock()

        # No blob in database.
        mock_session.query.return_value.filter_by.return_value.first.return_value = None

        result = PDFStorageManager.pdf_exists(tmp_path, mock_doc, mock_session)

        assert result is False
        mock_session.query.assert_called_once_with(DocumentBlob.document_id)
        mock_session.query.return_value.filter_by.assert_called_once_with(
            document_id="doc-789"
        )

    def test_propagates_query_failure(self, tmp_path):
        """A DB error while probing for the blob must NOT be swallowed and
        misreported as "no PDF": ``has_pdf``/``pdf_exists`` deliberately have
        no try/except around ``session.query(...)``, so a genuine backend
        failure surfaces to the caller instead of masquerading as absence.
        This locks that contract so a future refactor can't quietly turn DB
        outages into false "PDF missing" results."""
        mock_doc = MagicMock()
        mock_doc.id = "doc-err"
        mock_doc.file_type = "pdf"
        mock_doc.file_path = None
        mock_session = MagicMock()
        mock_session.query.side_effect = RuntimeError("db connection lost")

        with pytest.raises(RuntimeError, match="db connection lost"):
            PDFStorageManager.pdf_exists(tmp_path, mock_doc, mock_session)


class TestPDFStorageManagerDeletePdf:
    """Tests for delete_pdf method."""

    def test_deletes_database_blob(self, tmp_path):
        """Should delete blob from database."""
        manager = PDFStorageManager(tmp_path, "database")
        mock_doc = MagicMock()
        mock_doc.id = "doc-123"
        mock_doc.storage_mode = "database"
        mock_session = MagicMock()

        mock_blob = MagicMock()
        mock_session.query.return_value.filter_by.return_value.first.return_value = mock_blob

        result = manager.delete_pdf(mock_doc, mock_session)

        assert result is True
        mock_session.delete.assert_called_with(mock_blob)
        assert mock_doc.storage_mode == "none"

    def test_deletes_filesystem_file(self, tmp_path, mock_pdf_content):
        """Should delete file from filesystem."""
        # A user context is required for destructive filesystem ops (delete
        # fails closed without one; see delete_pdf).
        manager = PDFStorageManager(tmp_path, "filesystem", username="alice")
        mock_doc = MagicMock()
        mock_doc.id = "doc-123"
        mock_doc.storage_mode = "filesystem"
        mock_doc.file_path = "pdfs/test.pdf"
        mock_session = MagicMock()

        # Create file on disk
        pdf_path = tmp_path / "pdfs"
        pdf_path.mkdir(parents=True, exist_ok=True)
        file_path = pdf_path / "test.pdf"
        file_path.write_bytes(mock_pdf_content)

        result = manager.delete_pdf(mock_doc, mock_session)

        assert result is True
        assert not file_path.exists()
        assert mock_doc.storage_mode == "none"

    def test_returns_true_for_none_mode(self, tmp_path):
        """Should return True when nothing to delete."""
        manager = PDFStorageManager(tmp_path, "none")
        mock_doc = MagicMock()
        mock_doc.storage_mode = "none"
        mock_session = MagicMock()

        result = manager.delete_pdf(mock_doc, mock_session)

        assert result is True


class TestPDFStorageManagerUpgradeToPdf:
    """Tests for upgrade_to_pdf method."""

    def test_upgrades_text_only_document(self, tmp_path, mock_pdf_content):
        """Should add PDF to text-only document."""
        manager = PDFStorageManager(tmp_path, "database")
        mock_doc = MagicMock()
        mock_doc.id = "doc-123"
        mock_doc.storage_mode = "none"
        mock_session = MagicMock()

        mock_session.query.return_value.filter_by.return_value.first.return_value = None

        result = manager.upgrade_to_pdf(
            mock_doc, mock_pdf_content, mock_session
        )

        assert result is True
        assert mock_doc.storage_mode == "database"
        mock_session.add.assert_called()

    def test_skips_if_already_has_pdf(self, tmp_path, mock_pdf_content):
        """Should skip if document already has PDF storage."""
        manager = PDFStorageManager(tmp_path, "database")
        mock_doc = MagicMock()
        mock_doc.id = "doc-123"
        mock_doc.storage_mode = "database"
        mock_session = MagicMock()

        result = manager.upgrade_to_pdf(
            mock_doc, mock_pdf_content, mock_session
        )

        assert result is False

    def test_rejects_oversized_pdf(self, tmp_path):
        """Should reject PDF that exceeds size limit."""
        manager = PDFStorageManager(tmp_path, "database", max_pdf_size_mb=1)
        mock_doc = MagicMock()
        mock_doc.id = "doc-123"
        mock_doc.storage_mode = "none"
        mock_session = MagicMock()

        mock_session.query.return_value.filter_by.return_value.first.return_value = None

        large_content = b"x" * (2 * 1024 * 1024)

        result = manager.upgrade_to_pdf(mock_doc, large_content, mock_session)

        assert result is False


class TestPDFStorageManagerFilesystemWrite:
    """Tests for actual filesystem write operations."""

    @pytest.mark.skipif(
        not hasattr(os, "O_NOFOLLOW"), reason="O_NOFOLLOW unavailable"
    )
    def test_refuses_preplanted_pdf_leaf_symlink(
        self, tmp_path, mock_pdf_content
    ):
        """A PDF filename must not overwrite a symlink target outside the library."""
        library_root = tmp_path / "library"
        pdf_dir = library_root / "pdfs"
        pdf_dir.mkdir(parents=True)
        outside_pdf = tmp_path / "outside.pdf"
        outside_pdf.write_bytes(b"ORIGINAL")
        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):
            pytest.skip("Cannot create symlinks in this environment")

        manager = PDFStorageManager(library_root, "filesystem")
        with pytest.raises((OSError, ValueError)):
            manager._save_to_filesystem(mock_pdf_content, "evil.pdf")

        assert symlink.is_symlink()
        assert outside_pdf.read_bytes() == b"ORIGINAL"

    def test_saves_to_filesystem_without_encoding_error(
        self, tmp_path, mock_pdf_content
    ):
        """Should save binary PDF to filesystem without encoding errors.

        Regression test for bug where write_file_verified passed encoding
        argument to binary mode open(), causing ValueError.
        """
        manager = PDFStorageManager(tmp_path, "filesystem")

        # Actually call _save_to_filesystem (not mocked)
        result_path = manager._save_to_filesystem(
            mock_pdf_content,
            "test_document.pdf",
            url="https://example.com/paper.pdf",
            resource_id=123,
        )

        # Verify file was created
        assert result_path.exists()
        assert result_path.suffix == ".pdf"

        # Verify content matches
        saved_content = result_path.read_bytes()
        assert saved_content == mock_pdf_content

    def test_filesystem_write_uses_settings_snapshot(
        self, tmp_path, mock_pdf_content
    ):
        """Should pass settings_snapshot to write_file_verified.

        Regression test for bug where settings couldn't be found because
        no settings_snapshot was passed to write_file_verified.
        """
        # Create manager with filesystem mode
        manager = PDFStorageManager(tmp_path, "filesystem")

        # This should work without raising FileWriteSecurityError
        # because the settings_snapshot is now passed correctly
        result_path = manager._save_to_filesystem(
            mock_pdf_content,
            "snapshot_test.pdf",
        )

        assert result_path.exists()

    def test_saves_to_symlinked_pdfs_directory(
        self, tmp_path, mock_pdf_content
    ):
        """Should save PDFs when ``<library_root>/pdfs`` is a symlink.

        Regression test: a common deployment layout symlinks
        ``<library_root>/pdfs`` onto a larger disk. The directory-creation
        call for this trusted, hard-coded "pdfs" leaf must not pass a
        containment ``root=``, since ``create_directory`` resolves symlinks
        before checking containment and would otherwise reject this legitimate
        layout with a ``DirectoryCreationSecurityError``.
        """
        library_root = tmp_path / "library"
        library_root.mkdir()
        big_disk_pdfs = tmp_path / "big_disk_pdfs"
        big_disk_pdfs.mkdir()
        try:
            (library_root / "pdfs").symlink_to(
                big_disk_pdfs, target_is_directory=True
            )
        except (OSError, NotImplementedError):
            pytest.skip("Cannot create directory symlinks in this environment")

        manager = PDFStorageManager(library_root, "filesystem")

        result_path = manager._save_to_filesystem(
            mock_pdf_content,
            "symlinked_test.pdf",
        )

        assert result_path.exists()
        assert result_path.read_bytes() == mock_pdf_content
        # The file actually landed on the symlink target, not a directory
        # newly created under library_root.
        assert big_disk_pdfs in result_path.resolve().parents

    def test_resolves_stored_path_from_symlinked_pdfs_directory(
        self, tmp_path, mock_pdf_content
    ):
        """Should resolve a stored ``pdfs/<name>`` path when
        ``<library_root>/pdfs`` is a symlink.

        Load-side parity with test_saves_to_symlinked_pdfs_directory:
        the trusted-leaf carve-out now lives in the shared
        ``research_library.utils._resolve_within_root`` implementation
        that ``_safe_path_in_root`` delegates to, so a PDF saved into
        the sanctioned layout must also resolve back (not return None)
        through the storage manager.
        """
        library_root = tmp_path / "library"
        library_root.mkdir()
        big_disk_pdfs = tmp_path / "big_disk_pdfs"
        big_disk_pdfs.mkdir()
        try:
            (library_root / "pdfs").symlink_to(
                big_disk_pdfs, target_is_directory=True
            )
        except (OSError, NotImplementedError):
            pytest.skip("Cannot create directory symlinks in this environment")
        stored = big_disk_pdfs / "symlinked_test.pdf"
        stored.write_bytes(mock_pdf_content)

        manager = PDFStorageManager(library_root, "filesystem")

        result_path = manager._get_safe_file_path("pdfs/symlinked_test.pdf")

        assert result_path is not None
        assert result_path.is_file()
        assert result_path == stored.resolve()
        assert result_path.read_bytes() == mock_pdf_content

    def test_refuses_outside_pdf_leaf_without_nofollow(
        self, tmp_path, monkeypatch, mock_pdf_content
    ):
        """Realpath validation protects writes when O_NOFOLLOW is unavailable."""
        from local_deep_research.security import file_write_verifier

        library_root = tmp_path / "library"
        pdf_dir = library_root / "pdfs"
        pdf_dir.mkdir(parents=True)
        outside_pdf = tmp_path / "outside.pdf"
        outside_pdf.write_bytes(b"ORIGINAL")
        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):
            pytest.skip("Cannot create symlinks in this environment")

        # Simulate platforms where the verified writer cannot use O_NOFOLLOW.
        # The filesystem-level path check must still reject the planted leaf.
        monkeypatch.setattr(file_write_verifier, "_O_NOFOLLOW", 0)
        manager = PDFStorageManager(library_root, "filesystem")

        with pytest.raises(ValueError, match="escapes base directory"):
            manager._save_to_filesystem(mock_pdf_content, "evil.pdf")

        assert symlink.is_symlink()
        assert outside_pdf.read_bytes() == b"ORIGINAL"

    def test_save_pdf_round_trips_through_symlinked_pdfs_layout(
        self, tmp_path, mock_pdf_content
    ):
        """save_pdf stores ``pdfs/<name>`` relative to the library root
        when ``<library_root>/pdfs`` is a symlink onto a larger disk, and
        load_pdf reads the bytes back through that stored path.

        validate_safe_path returns the name joined onto the RESOLVED pdfs
        directory; _save_to_filesystem re-expresses it on the lexical
        ``pdfs`` path. Without that step save_pdf's
        ``relative_to(self.library_root)`` raises in this layout.
        """
        library_root = tmp_path / "library"
        library_root.mkdir()
        big_disk_pdfs = tmp_path / "big_disk_pdfs"
        big_disk_pdfs.mkdir()
        try:
            (library_root / "pdfs").symlink_to(
                big_disk_pdfs, target_is_directory=True
            )
        except (OSError, NotImplementedError):
            pytest.skip("Cannot create directory symlinks in this environment")
        manager = PDFStorageManager(library_root, "filesystem")
        document = MagicMock()
        document.id = "doc-123"
        document.file_type = "pdf"
        session = MagicMock()
        # No blob, so load_pdf has to read the file.
        session.query.return_value.filter_by.return_value.first.return_value = (
            None
        )

        stored_path, size = manager.save_pdf(
            mock_pdf_content, document, session, "paper.pdf"
        )

        name = f"paper_{hashlib.sha256(mock_pdf_content).hexdigest()}.pdf"
        assert stored_path == f"pdfs/{name}"
        assert size == len(mock_pdf_content)
        assert document.file_path == stored_path
        assert document.storage_mode == "filesystem"
        # The bytes landed on the larger disk, not in a new library dir.
        assert (big_disk_pdfs / name).read_bytes() == mock_pdf_content
        assert manager.load_pdf(document, session) == mock_pdf_content

    def test_save_pdf_keeps_an_absolute_looking_name_inside_the_store(
        self, tmp_path, mock_pdf_content
    ):
        """An absolute-looking filename is stored under ``pdfs/``, as the
        old ``"pdfs/" + filename`` join stored it, instead of being
        rejected: _save_to_filesystem strips the leading slash before
        validating the name against the pdfs directory."""
        manager = PDFStorageManager(tmp_path, "filesystem")
        document = MagicMock()
        session = MagicMock()

        stored_path, _ = manager.save_pdf(
            mock_pdf_content, document, session, "/evil.pdf"
        )

        name = f"evil_{hashlib.sha256(mock_pdf_content).hexdigest()}.pdf"
        assert stored_path == f"pdfs/{name}"
        assert (tmp_path / "pdfs" / name).read_bytes() == mock_pdf_content
        # Nothing was written anywhere else.
        assert [p.name for p in tmp_path.iterdir()] == ["pdfs"]
        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."""

    def test_generates_arxiv_filename(self, tmp_path):
        """Should generate proper filename for arXiv URLs."""
        manager = PDFStorageManager(tmp_path, "filesystem")
        filename = manager._generate_filename(
            "https://arxiv.org/pdf/2401.12345.pdf", None, "fallback.pdf"
        )
        assert "arxiv" in filename.lower()
        assert "2401.12345" in filename

    def test_generates_pmc_filename(self, tmp_path):
        """Should generate proper filename for PMC URLs."""
        manager = PDFStorageManager(tmp_path, "filesystem")
        filename = manager._generate_filename(
            "https://ncbi.nlm.nih.gov/pmc/articles/PMC1234567/pdf/",
            None,
            "fallback.pdf",
        )
        assert "pmc" in filename.lower() or "pubmed" in filename.lower()

    def test_uses_fallback_for_unknown_urls(self, tmp_path):
        """Should use fallback filename for unknown URLs."""
        manager = PDFStorageManager(tmp_path, "filesystem")
        filename = manager._generate_filename(
            "https://example.com/paper.pdf", None, "my_paper.pdf"
        )
        assert filename == "my_paper.pdf"


class TestPDFStorageManagerInferStorageMode:
    """Tests for _infer_storage_mode method."""

    def test_infers_database_from_blob(self, tmp_path):
        """Should infer database mode when blob exists."""
        manager = PDFStorageManager(tmp_path, "database")
        mock_doc = MagicMock()
        mock_doc.blob = MagicMock()
        mock_doc.file_path = None

        result = manager._infer_storage_mode(mock_doc)

        assert result == "database"

    def test_infers_filesystem_from_file_path(self, tmp_path):
        """Should infer filesystem mode when file_path exists."""
        manager = PDFStorageManager(tmp_path, "filesystem")
        mock_doc = MagicMock(spec=["file_path"])
        mock_doc.file_path = "pdfs/test.pdf"

        result = manager._infer_storage_mode(mock_doc)

        assert result == "filesystem"

    def test_infers_none_for_metadata_only(self, tmp_path):
        """Should infer none mode for metadata_only documents."""
        manager = PDFStorageManager(tmp_path, "database")
        mock_doc = MagicMock(spec=["file_path"])
        mock_doc.file_path = FILE_PATH_METADATA_ONLY

        result = manager._infer_storage_mode(mock_doc)

        assert result == "none"