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.

34.2 KB
Raw Blame
import hashlib
from pathlib import Path
from unittest.mock import MagicMock, patch

import pytest

from local_deep_research.database.models.library import DocumentStatus
from local_deep_research.research_library.downloaders.arxiv import (
    ArxivDownloader,
    ArxivTextResult,
    ArxivTextSource,
)
from local_deep_research.research_library.downloaders.base import DownloadResult
from local_deep_research.research_library.services.download_service import (
    DownloadService,
)


MODULE = "local_deep_research.research_library.services.download_service"
PROVENANCE_CASES = (
    (ArxivTextSource.ARXIV_HTML, "html_extraction", "arxiv_html", "high"),
    (ArxivTextSource.LOCAL_PDF, "pdf_extraction", "local_pdf", "low"),
    (ArxivTextSource.ARXIV_API, "native_api", "arxiv_api", "high"),
)
PROVENANCE_ROUTING_CASES = tuple(
    (source, method, origin)
    for source, method, origin, _quality in PROVENANCE_CASES
)
QUALITY_CASES = tuple(
    (method, source, quality)
    for _text_source, method, source, quality in PROVENANCE_CASES
) + (
    ("pdf_extraction", "pdfplumber", "medium"),
    ("pdfplumber", "legacy_pdfplumber", "medium"),
    ("other", "test_source", "low"),
)


@pytest.fixture
def service():
    with patch.object(DownloadService, "__init__", lambda self, *a, **kw: None):
        instance = DownloadService.__new__(DownloadService)
        instance.username = "test_user"
        instance.password = "test_password"
        instance.library_root = "/tmp/test_library/test_user"
        instance.settings = MagicMock()
        instance.settings.get_setting.side_effect = lambda key, default=None: {
            "research_library.pdf_storage_mode": "none",
            "research_library.max_pdf_size_mb": 100,
        }.get(key, default)
        instance.downloaders = []
        instance.retry_manager = MagicMock()
        retry_decision = MagicMock()
        retry_decision.can_retry = True
        retry_decision.reason = None
        instance.retry_manager.should_retry_resource.return_value = (
            retry_decision
        )
        return instance


def _make_ctx(session):
    context = MagicMock()
    context.__enter__.return_value = session
    context.__exit__.return_value = False
    return context


@pytest.mark.parametrize(
    ("source", "expected_method", "expected_origin"),
    PROVENANCE_ROUTING_CASES,
)
@pytest.mark.parametrize("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"
    resource = MagicMock()
    resource.id = 7
    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
    session = MagicMock()
    # B1 (#6758): _download_pdf now pre-checks Document(document_hash)
    # before INSERT. Default MagicMock query chains are truthy, which would
    # 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
    arxiv.download_with_result.return_value = DownloadResult(
        content=pdf_content,
        is_success=True,
    )
    arxiv.download_text_with_source.return_value = ArxivTextResult(
        text="typed arXiv text",
        source=source,
    )
    service.downloaders = [arxiv]

    storage_manager = MagicMock()
    storage_manager.save_pdf.return_value = (None, None)

    with (
        patch(
            f"{MODULE}.get_document_for_resource",
            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"),
        patch(f"{MODULE}.ensure_in_collection"),
        patch(f"{MODULE}.PDFStorageManager", return_value=storage_manager),
        patch(f"{MODULE}.uuid.uuid4", return_value="new-document-id"),
        patch.object(service, "_save_text_with_db") as save_text,
    ):
        # When the PDF workflow produces canonical arXiv text
        success, error, _status_code = service._download_pdf(
            resource,
            tracker,
            session,
        )

    # Then the exact bytes are reused and typed provenance is persisted
    assert success is True
    assert error is None
    assert (
        storage_manager.save_pdf.call_args.kwargs["pdf_content"] is pdf_content
    )
    arxiv.download_text_with_source.assert_called_once_with(
        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="new-document-id",
    )


@pytest.mark.parametrize(
    ("source", "expected_method", "expected_origin"),
    PROVENANCE_ROUTING_CASES,
)
def test_direct_text_path_persists_typed_arxiv_origin(
    service,
    source,
    expected_method,
    expected_origin,
):
    # Given an arXiv downloader returning typed text provenance
    resource = MagicMock()
    resource.url = "https://ar5iv.org/2301.12345v3"
    resource.title = "Direct typed provenance"
    arxiv = MagicMock(spec=ArxivDownloader)
    arxiv.download_text_with_source.return_value = ArxivTextResult(
        text="direct typed text",
        source=source,
    )
    session = MagicMock()

    with (
        patch.object(service, "_get_downloader", return_value=arxiv),
        patch.object(
            service,
            "_check_url_against_policy",
            return_value=(True, "allowed"),
        ),
        patch.object(service, "_save_text_with_db") as save_text,
    ):
        # When direct text extraction runs
        result = service._try_api_text_extraction(session, resource)

    # Then the source-specific method and exact origin are stored
    assert result == (True, None)
    arxiv.download_text_with_source.assert_called_once_with(resource.url)
    arxiv.download_with_result.assert_not_called()
    save_text.assert_called_once_with(
        resource,
        "direct typed text",
        session,
        extraction_method=expected_method,
        extraction_source=expected_origin,
    )


def test_arxiv_helper_returns_none_for_trailing_dot_lookalike(service):
    resource = MagicMock()
    resource.id = 21
    resource.url = "https://ar5iv.org.example.com./2301.12345"
    session = MagicMock()

    with (
        patch(f"{MODULE}.PDFStorageManager") as storage_manager,
        patch.object(service, "_get_downloader") as get_downloader,
        patch.object(service, "_check_url_against_policy") as policy_check,
    ):
        result = service._try_arxiv_text_extraction(session, resource)

    assert result is None
    service.retry_manager.should_retry_resource.assert_not_called()
    storage_manager.assert_not_called()
    get_downloader.assert_not_called()
    policy_check.assert_not_called()


@pytest.mark.parametrize(
    "url",
    (
        "https://AR5IV.ORG./not-an-arxiv-id",
        "https://ARXIV.ORG./not-an-arxiv-id",
        "https://EXPORT.ARXIV.ORG./not-an-arxiv-id",
        "https://arxiv.org/list/cs.AI/recent",
        "https://arxiv.org/ftp/arxiv/papers/2301/2301.12345.pdf",
    ),
)
def test_family_url_without_an_identifier_falls_through(service, url):
    # Given an arXiv-family URL that names no paper
    resource = MagicMock()
    resource.id = 22
    resource.url = url
    session = MagicMock()

    with (
        patch(f"{MODULE}.get_document_for_resource") as get_document,
        patch(f"{MODULE}.PDFStorageManager") as storage_manager,
        patch.object(service, "_get_downloader") as get_downloader,
        patch.object(service, "_check_url_against_policy") as policy_check,
        patch.object(service, "_save_text_with_db") as save_text,
    ):
        result = service._try_arxiv_text_extraction(session, resource)

    # Then this path declines rather than deciding the call: the canonical
    # sources need an identifier, and a verdict here would deny the resource
    # every later strategy
    assert result is None
    service.retry_manager.should_retry_resource.assert_not_called()
    service.retry_manager.record_attempt.assert_not_called()
    get_document.assert_not_called()
    storage_manager.assert_not_called()
    get_downloader.assert_not_called()
    policy_check.assert_not_called()
    save_text.assert_not_called()


def test_exhausted_retry_budget_falls_through_to_the_stored_pdf(service):
    # Given an arXiv paper whose retry budget is spent and which has no
    # stored PDF the storage manager can load
    resource = MagicMock()
    resource.id = 25
    resource.url = "https://arxiv.org/abs/2301.12345"
    session = MagicMock()
    denied = MagicMock()
    denied.can_retry = False
    denied.reason = "Max retries exceeded"
    service.retry_manager.should_retry_resource.return_value = denied

    with (
        patch(
            f"{MODULE}.get_document_for_resource", return_value=None
        ) as get_document,
        patch(f"{MODULE}.PDFStorageManager") as storage_manager,
        patch.object(service, "_get_downloader") as get_downloader,
        patch.object(service, "_check_url_against_policy") as policy_check,
        patch.object(service, "_save_text_with_db") as save_text,
    ):
        result = service._try_arxiv_text_extraction(session, resource)

    # Then the network-bearing path declines without deciding the call, so
    # download_as_text still reaches _try_existing_pdf_extraction -- a pure
    # filesystem read that produced text before this path existed
    assert result is None
    get_document.assert_called_once_with(session, resource)
    storage_manager.assert_not_called()
    get_downloader.assert_not_called()
    policy_check.assert_not_called()
    save_text.assert_not_called()


def test_arxiv_text_reuses_database_pdf_and_document_identity(service):
    resource = MagicMock()
    resource.id = 23
    resource.url = "https://AR5IV.ORG./2301.12345v2"
    resource.title = "Stored PDF identity"
    session = MagicMock()
    document = MagicMock()
    document.id = "existing-pdf-document"
    document.status = DocumentStatus.COMPLETED
    document.file_type = "pdf"
    pdf_content = b"%PDF-database-identity"
    storage_manager = MagicMock()
    storage_manager.load_pdf.return_value = pdf_content
    arxiv = MagicMock(spec=ArxivDownloader)
    arxiv.download_text_with_source.return_value = ArxivTextResult(
        text="text from stored PDF",
        source=ArxivTextSource.LOCAL_PDF,
    )

    with (
        patch(f"{MODULE}.get_document_for_resource", return_value=document),
        patch(
            f"{MODULE}.PDFStorageManager", return_value=storage_manager
        ) as manager,
        patch.object(service, "_get_downloader", return_value=arxiv),
        patch.object(
            service,
            "_check_url_against_policy",
            return_value=(True, "allowed"),
        ),
        patch.object(service, "_save_text_with_db") as save_text,
    ):
        result = service._try_arxiv_text_extraction(session, resource)

    assert result == (True, None)
    manager.assert_called_once_with(
        library_root=Path(service.library_root),
        storage_mode="none",
    )
    storage_manager.load_pdf.assert_called_once_with(document, session)
    assert (
        arxiv.download_text_with_source.call_args.kwargs["pdf_content"]
        is pdf_content
    )
    arxiv.download_text_with_source.assert_called_once_with(
        resource.url,
        pdf_content=pdf_content,
    )
    save_text.assert_called_once_with(
        resource,
        "text from stored PDF",
        session,
        extraction_method="pdf_extraction",
        extraction_source="local_pdf",
        pdf_document_id=document.id,
    )
    session.commit.assert_called_once_with()


def test_arxiv_text_without_stored_pdf_uses_one_typed_chain(service):
    resource = MagicMock()
    resource.id = 24
    resource.url = "https://arxiv.org/abs/2301.12345"
    resource.title = "One typed chain"
    session = MagicMock()
    arxiv = MagicMock(spec=ArxivDownloader)
    arxiv.download_text_with_source.return_value = ArxivTextResult(
        text="API fallback text",
        source=ArxivTextSource.ARXIV_API,
    )

    with (
        patch(f"{MODULE}.get_document_for_resource", return_value=None),
        patch(f"{MODULE}.PDFStorageManager") as storage_manager,
        patch.object(service, "_get_downloader", return_value=arxiv),
        patch.object(
            service,
            "_check_url_against_policy",
            return_value=(True, "allowed"),
        ),
        patch.object(service, "_save_text_with_db") as save_text,
    ):
        result = service._try_arxiv_text_extraction(session, resource)

    assert result == (True, None)
    storage_manager.assert_not_called()
    arxiv.download_text_with_source.assert_called_once_with(resource.url)
    arxiv.download_with_result.assert_not_called()
    save_text.assert_called_once_with(
        resource,
        "API fallback text",
        session,
        extraction_method="native_api",
        extraction_source="arxiv_api",
        pdf_document_id=None,
    )
    session.commit.assert_called_once_with()


def test_arxiv_retry_denial_skips_work_and_retry_record(service):
    resource = MagicMock()
    resource.id = 25
    resource.url = "https://arxiv.org/abs/2301.12345"
    resource.source_type = "web"
    session = MagicMock()
    session.query.return_value.filter_by.return_value.first.return_value = (
        resource
    )
    decision = service.retry_manager.should_retry_resource.return_value
    decision.can_retry = False
    decision.reason = "retry denied"

    with (
        patch(f"{MODULE}.get_user_db_session", return_value=_make_ctx(session)),
        patch.object(service, "_try_existing_text", return_value=None),
        patch.object(service, "_try_legacy_text_file", return_value=None),
        # No stored document, so the denial path's local read finds
        # nothing and it declines without a verdict; the filesystem
        # strategy is mocked out here.
        patch(f"{MODULE}.get_document_for_resource", return_value=None),
        patch(f"{MODULE}.PDFStorageManager") as storage_manager,
        patch.object(service, "_get_downloader") as get_downloader,
        patch.object(service, "_check_url_against_policy") as policy_check,
        patch.object(
            service, "_try_existing_pdf_extraction", return_value=None
        ) as existing_pdf,
        patch.object(service, "_try_api_text_extraction") as api_text,
        patch.object(service, "_fallback_pdf_extraction") as fallback,
    ):
        result = service.download_as_text(resource.id)

    # Then the canonical arXiv path declines without a verdict, the stored
    # PDF is still read (pure filesystem, ahead of the gate), and the gate
    # then ends the call before any network-bearing step or retry record
    assert result == (False, "retry denied")
    existing_pdf.assert_called_once_with(session, resource, resource.id)
    storage_manager.assert_not_called()
    get_downloader.assert_not_called()
    policy_check.assert_not_called()
    api_text.assert_not_called()
    fallback.assert_not_called()
    service.retry_manager.record_attempt.assert_not_called()


def test_arxiv_retry_denial_reads_a_database_stored_pdf(service):
    """A retry-denied resource whose PDF is stored in the database gets text.

    The default storage mode keeps the PDF as a database blob and leaves
    ``file_path`` unset, so the filesystem strategy
    (``_try_existing_pdf_extraction``, run for real here) finds nothing.
    The retry gate denies the network, but the canonical path still reads
    the stored blob through the storage manager, entirely locally, the way
    the egress-denied path does. No network-bearing step runs.
    """
    resource = MagicMock()
    resource.id = 29
    resource.url = "https://arxiv.org/abs/2301.12345"
    resource.source_type = "web"
    resource.title = "Database-stored PDF"
    session = MagicMock()
    document = MagicMock()
    document.id = "database-pdf-document"
    # The loaded member satisfies both stored-PDF readers' status checks, so
    # the filesystem strategy is stopped by the missing file_path alone.
    document.status = DocumentStatus.COMPLETED
    document.file_type = "pdf"
    document.file_path = None
    # First lookup is the resource; any later one is its stored document.
    session.query.return_value.filter_by.return_value.first.side_effect = [
        resource
    ] + [document] * 5
    decision = service.retry_manager.should_retry_resource.return_value
    decision.can_retry = False
    decision.reason = "retry denied"
    storage_manager = MagicMock()
    storage_manager.load_pdf.return_value = b"%PDF-database-blob"

    with (
        patch(f"{MODULE}.get_user_db_session", return_value=_make_ctx(session)),
        patch.object(service, "_try_existing_text", return_value=None),
        patch.object(service, "_try_legacy_text_file", return_value=None),
        patch(f"{MODULE}.get_document_for_resource", return_value=document),
        patch(f"{MODULE}.PDFStorageManager", return_value=storage_manager),
        patch(
            f"{MODULE}.ArxivDownloader.extract_text_from_pdf",
            return_value="text from the database blob",
        ),
        patch.object(service, "_save_text_with_db") as save_text,
        patch.object(service, "_get_downloader") as get_downloader,
        patch.object(service, "_check_url_against_policy") as policy_check,
        patch.object(service, "_try_api_text_extraction") as api_text,
        patch.object(service, "_fallback_pdf_extraction") as fallback,
    ):
        result = service.download_as_text(resource.id)

    # Then the text arrives from the stored blob and no network path ran
    assert result == (True, None)
    storage_manager.load_pdf.assert_called_once_with(document, session)
    save_text.assert_called_once_with(
        resource,
        "text from the database blob\n\n"
        "Source: https://arxiv.org/abs/2301.12345",
        session,
        extraction_method="pdf_extraction",
        extraction_source="local_pdf",
        pdf_document_id="database-pdf-document",
    )
    get_downloader.assert_not_called()
    policy_check.assert_not_called()
    api_text.assert_not_called()
    fallback.assert_not_called()


def test_arxiv_retry_denial_ignores_a_failed_stored_pdf_save(service):
    """A failed local read under a retry denial leaves the denial to stand.

    Only a success is returned from the denial path; a save failure falls
    through, so download_as_text's own gate returns the denial and no
    failure is recorded against a resource that made no request.
    """
    resource = MagicMock()
    resource.id = 32
    resource.url = "https://arxiv.org/abs/2301.12345"
    resource.source_type = "web"
    session = MagicMock()
    session.query.return_value.filter_by.return_value.first.return_value = (
        resource
    )
    decision = service.retry_manager.should_retry_resource.return_value
    decision.can_retry = False
    decision.reason = "retry denied"

    with (
        patch(f"{MODULE}.get_user_db_session", return_value=_make_ctx(session)),
        patch.object(service, "_try_existing_text", return_value=None),
        patch.object(service, "_try_legacy_text_file", return_value=None),
        patch.object(
            service,
            "_text_from_cached_pdf",
            return_value=(False, "Failed to extract arXiv text"),
        ) as cached_read,
        patch.object(
            service, "_try_existing_pdf_extraction", return_value=None
        ) as existing_pdf,
        patch.object(service, "_get_downloader") as get_downloader,
    ):
        result = service.download_as_text(resource.id)

    assert result == (False, "retry denied")
    cached_read.assert_called_once_with(session, resource)
    existing_pdf.assert_called_once_with(session, resource, resource.id)
    get_downloader.assert_not_called()
    service.retry_manager.record_attempt.assert_not_called()


def test_arxiv_egress_denial_with_cached_pdf_extracts_locally(service):
    """An egress-denied resource with a stored PDF still gets its text."""
    resource = MagicMock()
    resource.id = 30
    resource.url = "https://arxiv.org/abs/2301.12345"
    resource.title = "Egress denied cached PDF"
    session = MagicMock()
    arxiv = MagicMock(spec=ArxivDownloader)

    document = MagicMock()
    document.id = "cached-pdf-document-egress"
    document.status = DocumentStatus.COMPLETED
    document.file_type = "pdf"
    storage_manager = MagicMock()
    storage_manager.load_pdf.return_value = b"%PDF-cached-egress"

    with (
        patch(f"{MODULE}.get_document_for_resource", return_value=document),
        patch(f"{MODULE}.PDFStorageManager", return_value=storage_manager),
        patch.object(service, "_get_downloader", return_value=arxiv),
        patch.object(
            service,
            "_check_url_against_policy",
            return_value=(False, "blocked"),
        ),
        patch(
            f"{MODULE}.ArxivDownloader.extract_text_from_pdf",
            return_value="egress cached text",
        ),
        patch.object(service, "_save_text_with_db") as save_text,
    ):
        outcome = service._try_arxiv_text_extraction(session, resource)

    # Then the extraction succeeded entirely locally: (True, None) in the
    # plain tuple contract this method speaks on main.
    assert outcome == (True, None)
    arxiv.download_text_with_source.assert_not_called()
    save_text.assert_called_once_with(
        resource,
        "egress cached text\n\nSource: https://arxiv.org/abs/2301.12345",
        session,
        extraction_method="pdf_extraction",
        extraction_source="local_pdf",
        pdf_document_id="cached-pdf-document-egress",
    )
    session.commit.assert_called_once_with()


def _stored_document(status=DocumentStatus.COMPLETED, file_type="pdf"):
    document = MagicMock()
    document.id = "stored-document"
    document.status = status
    document.file_type = file_type
    return document


@pytest.mark.parametrize(
    ("document", "stored_bytes", "extracted_text"),
    (
        pytest.param(None, b"%PDF-stored", "stored text", id="no_document"),
        pytest.param(
            _stored_document(status=DocumentStatus.PENDING),
            b"%PDF-stored",
            "stored text",
            id="document_not_completed",
        ),
        pytest.param(
            _stored_document(file_type="html"),
            b"%PDF-stored",
            "stored text",
            id="document_not_a_pdf",
        ),
        pytest.param(
            _stored_document(), None, "stored text", id="pdf_bytes_missing"
        ),
        pytest.param(
            _stored_document(), b"%PDF-stored", "", id="pdf_yields_no_text"
        ),
    ),
)
def test_arxiv_egress_denial_without_usable_cached_pdf_returns_denial(
    service, document, stored_bytes, extracted_text
):
    """An egress-denied resource with no usable stored PDF keeps the denial.

    Each case removes one precondition of the local read. Every other
    precondition holds and the extraction stub returns text where it is
    reached, so dropping the guard for the missing one would save text
    and turn the outcome into a success.
    """
    resource = MagicMock()
    resource.id = 31
    resource.url = "https://arxiv.org/abs/2301.12345"
    resource.title = "Egress denied, no usable stored PDF"
    session = MagicMock()
    arxiv = MagicMock(spec=ArxivDownloader)
    # Were the network path reached, it would yield no text, so the
    # outcome itself (not an incidental error) shows the denial held.
    arxiv.download_text_with_source.return_value = None
    storage_manager = MagicMock()
    storage_manager.load_pdf.return_value = stored_bytes

    with (
        patch(f"{MODULE}.get_document_for_resource", return_value=document),
        patch(f"{MODULE}.PDFStorageManager", return_value=storage_manager),
        patch.object(service, "_get_downloader", return_value=arxiv),
        patch.object(
            service,
            "_check_url_against_policy",
            return_value=(False, "blocked"),
        ),
        patch(
            f"{MODULE}.ArxivDownloader.extract_text_from_pdf",
            return_value=extracted_text,
        ),
        patch.object(service, "_save_text_with_db"),
    ):
        outcome = service._try_arxiv_text_extraction(session, resource)

    # Then the denial stands and the network text path was never entered
    assert outcome == (False, "egress_policy_denied:blocked")
    arxiv.download_text_with_source.assert_not_called()


@pytest.mark.parametrize(
    "cached_read",
    (
        pytest.param(
            {"return_value": (False, "Failed to extract arXiv text: boom")},
            id="stored_text_save_failed",
        ),
        pytest.param(
            {"side_effect": RuntimeError("stored PDF unreadable")},
            id="stored_read_raised",
        ),
    ),
)
def test_arxiv_egress_denial_keeps_its_reason_when_the_local_read_fails(
    service, cached_read
):
    """Only a local success replaces an egress denial.

    A failed save of the stored PDF's text, or a read that raises, must
    leave ``egress_policy_denied:<reason>`` as the outcome: that reason is
    what the caller records, and the save error would bury it. Red under
    returning any non-None local outcome, and under letting the exception
    reach the outer handler (which returns a "Failed to extract" error).
    """
    resource = MagicMock()
    resource.id = 33
    resource.url = "https://arxiv.org/abs/2301.12345"
    session = MagicMock()
    arxiv = MagicMock(spec=ArxivDownloader)

    with (
        patch.object(service, "_get_downloader", return_value=arxiv),
        patch.object(
            service,
            "_check_url_against_policy",
            return_value=(False, "blocked"),
        ),
        patch.object(
            service, "_text_from_cached_pdf", **cached_read
        ) as local_read,
    ):
        outcome = service._try_arxiv_text_extraction(session, resource)

    assert outcome == (False, "egress_policy_denied:blocked")
    local_read.assert_called_once_with(session, resource)
    arxiv.download_text_with_source.assert_not_called()


def test_arxiv_success_records_one_terminal_retry_attempt(service):
    resource = MagicMock()
    resource.id = 26
    resource.url = "https://arxiv.org/abs/2301.12345"
    resource.title = "Terminal success"
    resource.source_type = "web"
    session = MagicMock()
    session.query.return_value.filter_by.return_value.first.return_value = (
        resource
    )
    arxiv = MagicMock(spec=ArxivDownloader)
    arxiv.download_text_with_source.return_value = ArxivTextResult(
        text="official HTML text",
        source=ArxivTextSource.ARXIV_HTML,
    )

    with (
        patch(f"{MODULE}.get_user_db_session", return_value=_make_ctx(session)),
        patch.object(service, "_try_existing_text", return_value=None),
        patch.object(service, "_try_legacy_text_file", return_value=None),
        patch(f"{MODULE}.get_document_for_resource", return_value=None),
        patch.object(service, "_get_downloader", return_value=arxiv),
        patch.object(
            service,
            "_check_url_against_policy",
            return_value=(True, "allowed"),
        ),
        patch.object(service, "_save_text_with_db"),
        patch.object(service, "_try_existing_pdf_extraction") as existing_pdf,
        patch.object(service, "_try_api_text_extraction") as api_fallback,
        patch.object(service, "_fallback_pdf_extraction") as pdf_fallback,
    ):
        result = service.download_as_text(resource.id)

    assert result == (True, None)
    service.retry_manager.record_attempt.assert_called_once_with(
        resource_id=resource.id,
        result=result,
        url=resource.url,
        details="Successfully extracted text",
        session=session,
    )
    existing_pdf.assert_not_called()
    api_fallback.assert_not_called()
    pdf_fallback.assert_not_called()


def test_arxiv_typed_exhaustion_is_terminal_and_records_once(service):
    resource = MagicMock()
    resource.id = 27
    resource.url = "https://arxiv.org/abs/2301.12345"
    resource.title = "Terminal exhaustion"
    resource.source_type = "web"
    session = MagicMock()
    session.query.return_value.filter_by.return_value.first.return_value = (
        resource
    )
    arxiv = MagicMock(spec=ArxivDownloader)
    arxiv.download_text_with_source.return_value = None

    with (
        patch(f"{MODULE}.get_user_db_session", return_value=_make_ctx(session)),
        patch.object(service, "_try_existing_text", return_value=None),
        patch.object(service, "_try_legacy_text_file", return_value=None),
        patch(f"{MODULE}.get_document_for_resource", return_value=None),
        patch.object(service, "_get_downloader", return_value=arxiv),
        patch.object(
            service,
            "_check_url_against_policy",
            return_value=(True, "allowed"),
        ),
        patch.object(service, "_try_existing_pdf_extraction") as existing_pdf,
        patch.object(service, "_try_api_text_extraction") as api_fallback,
        patch.object(service, "_fallback_pdf_extraction") as pdf_fallback,
    ):
        result = service.download_as_text(resource.id)

    assert result == (False, "Could not retrieve arXiv text")
    service.retry_manager.record_attempt.assert_called_once_with(
        resource_id=resource.id,
        result=result,
        url=resource.url,
        details="Could not retrieve arXiv text",
        session=session,
    )
    arxiv.download_text_with_source.assert_called_once_with(resource.url)
    arxiv.download_with_result.assert_not_called()
    existing_pdf.assert_not_called()
    api_fallback.assert_not_called()
    pdf_fallback.assert_not_called()


def test_arxiv_typed_exception_is_terminal_and_records_once(service):
    resource = MagicMock()
    resource.id = 28
    resource.url = "https://arxiv.org/abs/2301.12345"
    resource.title = "Terminal exception"
    resource.source_type = "web"
    session = MagicMock()
    session.query.return_value.filter_by.return_value.first.return_value = (
        resource
    )
    arxiv = MagicMock(spec=ArxivDownloader)
    arxiv.download_text_with_source.side_effect = RuntimeError(
        "secret_token=unsafe"
    )

    with (
        patch(f"{MODULE}.get_user_db_session", return_value=_make_ctx(session)),
        patch.object(service, "_try_existing_text", return_value=None),
        patch.object(service, "_try_legacy_text_file", return_value=None),
        patch(f"{MODULE}.get_document_for_resource", return_value=None),
        patch.object(service, "_get_downloader", return_value=arxiv),
        patch.object(
            service,
            "_check_url_against_policy",
            return_value=(True, "allowed"),
        ),
        patch(f"{MODULE}.safe_rollback") as rollback,
        patch.object(service, "_try_existing_pdf_extraction") as existing_pdf,
        patch.object(service, "_try_api_text_extraction") as api_fallback,
        patch.object(service, "_fallback_pdf_extraction") as pdf_fallback,
    ):
        result = service.download_as_text(resource.id)

    # Caller-visible reason is a fixed token (PR #6564 follow-up), never
    # str(exc) — even though the exception text carries a secret shape here.
    assert result == (False, "download_error:RuntimeError")
    service.retry_manager.record_attempt.assert_called_once_with(
        resource_id=resource.id,
        result=result,
        url=resource.url,
        details="download_error:RuntimeError",
        session=session,
    )
    rollback.assert_called_once_with(session, "_try_arxiv_text_extraction")
    existing_pdf.assert_not_called()
    api_fallback.assert_not_called()
    pdf_fallback.assert_not_called()


@pytest.mark.parametrize(
    ("method", "source", "expected_quality"), QUALITY_CASES
)
def test_existing_document_quality_uses_unified_mapping(
    service,
    method,
    source,
    expected_quality,
):
    # Given an existing completed document without extracted text
    document = MagicMock()
    document.status = DocumentStatus.COMPLETED
    document.text_content = None
    session = MagicMock()
    session.query.return_value.filter_by.return_value.first.return_value = (
        document
    )
    resource = MagicMock()

    # When extracted text updates it
    service._save_text_with_db(
        resource,
        "quality text",
        session,
        extraction_method=method,
        extraction_source=source,
        pdf_document_id="existing-document",
    )

    # Then the method's exact unified quality is applied
    assert document.extraction_quality == expected_quality


@pytest.mark.parametrize(
    ("method", "source", "expected_quality"), QUALITY_CASES
)
def test_new_document_quality_uses_unified_mapping(
    service,
    method,
    source,
    expected_quality,
):
    # Given no existing resource document or duplicate content hash
    resource = MagicMock()
    resource.id = 9
    resource.research_id = "research-2"
    resource.url = "https://example.com/resource"
    resource.title = "Quality mapping"
    session = MagicMock()
    session.query.return_value.filter_by.return_value.first.side_effect = [
        None,
        None,
    ]

    with (
        patch(f"{MODULE}.get_document_for_resource", return_value=None),
        patch(f"{MODULE}.get_source_type_id", return_value="source-type"),
        patch(f"{MODULE}.uuid.uuid4", return_value="new-text-document"),
    ):
        # When extracted text creates a document
        service._save_text_with_db(
            resource,
            "new quality text",
            session,
            extraction_method=method,
            extraction_source=source,
        )

    # Then creation uses the same exact quality mapping as updates
    document = session.add.call_args.args[0]
    assert document.extraction_quality == expected_quality