~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(downloaders): resolve DOI to open-access copy before declaring paywall (#6385)
DustinEwanc0de197e848d
diff --git a/src/local_deep_research/research_library/downloaders/__init__.py b/src/local_deep_research/research_library/downloaders/__init__.pyindex 9c00fa1c59..756a441f6e 100644--- a/src/local_deep_research/research_library/downloaders/__init__.py+++ b/src/local_deep_research/research_library/downloaders/__init__.py@@ -10,6 +10,7 @@ from .biorxiv import BioRxivDownloaderfrom .direct_pdf import DirectPDFDownloaderfrom .semantic_scholar import SemanticScholarDownloaderfrom .openalex import OpenAlexDownloader+from .open_access_doi import OpenAccessDOIDownloaderfrom .generic import GenericDownloaderfrom .playwright_html import (AutoHTMLDownloader,@@ -26,6 +27,7 @@ __all__ = ["DirectPDFDownloader","SemanticScholarDownloader","OpenAlexDownloader",+ "OpenAccessDOIDownloader","GenericDownloader","PlaywrightHTMLDownloader","AutoHTMLDownloader",diff --git a/src/local_deep_research/research_library/downloaders/open_access_doi.py b/src/local_deep_research/research_library/downloaders/open_access_doi.pynew file mode 100644index 0000000000..45c5281105--- /dev/null+++ b/src/local_deep_research/research_library/downloaders/open_access_doi.py@@ -0,0 +1,214 @@+"""+Open-Access DOI Downloader++Resolves a canonical DOI (https://doi.org/... or https://dx.doi.org/...) to an+open-access copy before falling back to the publisher landing page.++Closes the gap where a DOI record was treated as a direct PDF URL: the+publisher landing page (HTML) was misclassified as a paywall and no open-access+discovery was performed first. Uses OpenAlex, which aggregates OA locations+(publisher, PMC, arXiv, author manuscripts) into ``best_oa_location`` and the+per-location ``is_oa`` flag on ``locations``.++Classification of outcomes (drives retry vs. permanent via the skip reason text,+see ``library/download_management/failure_classifier.py``):+- OA PDF found and downloaded -> success+- OA PDF found but download failed -> retryable (the copy exists)+- Confirmed not open access -> permanent paywall (genuinely no free copy)+- Could not determine -> retryable (API error / not in OpenAlex)+"""++from typing import Optional, Tuple+from urllib.parse import urlparse++import requests+from loguru import logger++from ...security.ssrf_validator import redact_url_for_log+from ...utilities.resource_utils import safe_close+from .base import BaseDownloader, ContentType, DownloadResult+++class OpenAccessDOIDownloader(BaseDownloader):+ """Resolve a DOI to an open-access PDF via OpenAlex before declaring paywall."""++ def __init__(+ self,+ timeout: int = 30,+ polite_pool_email: Optional[str] = None,+ **kwargs,+ ):+ """+ Initialize the DOI open-access downloader.++ Args:+ timeout: Request timeout in seconds+ polite_pool_email: Optional email for the OpenAlex polite pool+ """+ super().__init__(timeout, **kwargs)+ self.polite_pool_email = polite_pool_email+ self.base_api_url = "https://api.openalex.org"++ def can_handle(self, url: str) -> bool:+ """Handle canonical DOI URLs (doi.org / dx.doi.org)."""+ try:+ hostname = (urlparse(url).hostname or "").lower()+ except (ValueError, AttributeError, TypeError):+ return False+ return hostname in ("doi.org", "dx.doi.org")++ def download(+ self, url: str, content_type: ContentType = ContentType.PDF+ ) -> Optional[bytes]:+ """Download content from a DOI URL."""+ result = self.download_with_result(url, content_type)+ return result.content if result.is_success else None++ def download_with_result(+ self, url: str, content_type: ContentType = ContentType.PDF+ ) -> DownloadResult:+ """Resolve the DOI to an OA PDF and return it (or extracted text)."""+ doi = self._extract_doi(url)+ if not doi:+ return DownloadResult(skip_reason="Could not extract DOI from URL")++ pdf_url, status = self._resolve_oa_pdf(doi)++ if status == "unknown":+ # Could not determine OA status (API error / not in OpenAlex) -> retry.+ return DownloadResult(+ skip_reason="Could not resolve open access status for DOI (retry later)"+ )+ if status != "oa" or not pdf_url:+ # Confirmed not open access -> genuine paywall (permanent).+ return DownloadResult(+ skip_reason="No open access copy available (paywall)"+ )++ logger.info(+ "Downloading resolved open access PDF from {}",+ redact_url_for_log(pdf_url),+ )+ pdf_content = super()._download_pdf(pdf_url)+ if not pdf_content:+ # The OA copy exists but this download attempt failed -> retry.+ return DownloadResult(+ skip_reason="Open access PDF found but download failed"+ )++ if content_type == ContentType.PDF:+ return DownloadResult(content=pdf_content, is_success=True)++ # TEXT: extract from the OA PDF.+ text = self.extract_text_from_pdf(pdf_content)+ if text:+ return DownloadResult(content=text.encode("utf-8"), is_success=True)+ return DownloadResult(+ skip_reason="Open access PDF downloaded but text extraction failed"+ )++ @staticmethod+ def _extract_doi(url: str) -> Optional[str]:+ """Extract the DOI from a doi.org / dx.doi.org URL."""+ try:+ parsed = urlparse(url)+ except (ValueError, AttributeError, TypeError):+ return None+ hostname = (parsed.hostname or "").lower()+ if hostname not in ("doi.org", "dx.doi.org"):+ return None+ return parsed.path.lstrip("/") or None++ def _resolve_oa_pdf(self, doi: str) -> Tuple[Optional[str], str]:+ """+ Resolve a DOI to an open-access PDF URL via OpenAlex.++ Returns:+ (pdf_url, status) where status is one of:+ - "oa": an OA PDF URL was found+ - "not_oa": OpenAlex confirms the work is not open access+ - "unknown": could not determine (API error / work not in OpenAlex)+ """+ try:+ # No `select`: the full work object is needed for the OA-locations+ # scan over `locations` (catches PMC / author-manuscript PDFs that+ # `best_oa_location` misses).+ params = {"filter": f"doi:{doi}"}+ headers = {}+ if self.polite_pool_email:+ headers["User-Agent"] = f"mailto:{self.polite_pool_email}"++ response = self.session.get(+ f"{self.base_api_url}/works",+ params=params,+ headers=headers,+ timeout=self.timeout,+ )++ try:+ if response.status_code != 200:+ logger.warning(+ "OpenAlex DOI lookup failed: HTTP {}",+ response.status_code,+ )+ return None, "unknown"++ results = response.json().get("results", [])+ finally:+ safe_close(response, "OpenAlex DOI response")+ if not results:+ logger.info("DOI not found in OpenAlex")+ return None, "unknown"++ work = results[0]+ if not work.get("open_access", {}).get("is_oa", False):+ logger.info("DOI is not open access per OpenAlex")+ return None, "not_oa"++ # 1. Prefer the best OA location's direct PDF.+ best = work.get("best_oa_location") or {}+ if best.get("pdf_url"):+ return str(best["pdf_url"]), "oa"++ # 2. Scan all OA locations for a direct PDF (catches PMC, arXiv, AM).+ # OpenAlex returns `locations` (not `oa_locations`); filter by the+ # per-location `is_oa` flag.+ for loc in work.get("locations", []) or []:+ if loc and loc.get("is_oa") and loc.get("pdf_url"):+ return str(loc["pdf_url"]), "oa"++ # 3. Fall back to a landing page only if it is actually a PDF.+ landing = best.get("landing_page_url")+ if landing:+ head = None+ try:+ head = self.session.head(+ landing,+ timeout=self.timeout,+ allow_redirects=True,+ )+ if (+ "application/pdf"+ in head.headers.get("Content-Type", "").lower()+ ):+ return str(landing), "oa"+ except (+ requests.exceptions.RequestException,+ ValueError,+ ) as exc:+ logger.opt(exception=False).warning(+ "Failed to validate open access landing page ({})",+ type(exc).__name__,+ )+ finally:+ safe_close(head, "OpenAlex DOI landing response")++ # OA work but no retrievable PDF this time -> retryable (not a paywall).+ logger.info("DOI is open access but no direct PDF URL was found")+ return None, "unknown"++ except (requests.exceptions.RequestException, ValueError) as exc:+ logger.opt(exception=False).warning(+ "OpenAlex DOI lookup failed ({})", type(exc).__name__+ )+ return None, "unknown"diff --git a/src/local_deep_research/research_library/services/download_service.py b/src/local_deep_research/research_library/services/download_service.pyindex f9f2179dd1..a6012de47e 100644--- a/src/local_deep_research/research_library/services/download_service.py+++ b/src/local_deep_research/research_library/services/download_service.py@@ -88,7 +88,7 @@ from ...database.models.research import ResearchResourcefrom ...database.library_init import get_source_type_id, get_default_library_idfrom ...database.session_context import get_user_db_session, safe_rollbackfrom ...utilities.db_utils import get_settings_manager-from ...library.download_management import RetryManager+from ...library.download_management import FailureClassifier, RetryManagerfrom ...library.download_management.models import (DownloadStatus as RetryStatus,)@@ -109,13 +109,16 @@ from ..utils import (# Import our modular downloadersfrom ..downloaders import (+ BaseDownloader,ContentType,+ DownloadResult,ArxivDownloader,PubMedDownloader,BioRxivDownloader,DirectPDFDownloader,SemanticScholarDownloader,OpenAlexDownloader,+ OpenAccessDOIDownloader,GenericDownloader,)from ..downloaders.arxiv import ArxivTextSource, attribute_arxiv_text@@ -1086,6 +1089,13 @@ class DownloadService:settings_snapshot=self._settings_snapshot,enable_fetch_persistence=False,),+ OpenAccessDOIDownloader(+ timeout=30,+ username=username,+ password=password,+ settings_snapshot=self._settings_snapshot,+ enable_fetch_persistence=False,+ ),GenericDownloader(timeout=30,username=username,@@ -2451,38 +2461,14 @@ class DownloadService:if cached_pdf is not None:pdf_content = cached_pdf[0]- for downloader in self.downloaders:- if pdf_content is not None:- break- if downloader.can_handle(url):- logger.info(- f"Using {downloader.__class__.__name__} for {redact_url_for_log(url)}"- )- result = downloader.download_with_result(- url, ContentType.PDF- )- selected_downloader = downloader-- if result.is_success and result.content:- pdf_content = result.content- status_code = result.status_code- break- if result.skip_reason:- skip_reason = result.skip_reason- status_code = result.status_code- logger.info(- f"Download skipped: {failure_reason_for_log(skip_reason)}"- )- if isinstance(- downloader, (ArxivDownloader, GenericDownloader)- ):- break-- if selected_downloader is None and pdf_content is None:- logger.error(- f"No downloader found for {redact_url_for_log(url)}"+ if pdf_content is None:+ result, selected_downloader = self._download_pdf_with_fallback(+ url)- skip_reason = "No compatible downloader available"+ if result.is_success and result.content:+ pdf_content = result.content+ skip_reason = result.skip_reason+ status_code = result.status_code# When pdf_content came from the local cache, selected_downloader# stays None (as on main) so text production stays local and# never sends arXiv duplicates through a network path.@@ -4084,6 +4070,56 @@ class DownloadService:safe_rollback(session, "_try_existing_pdf_extraction")return None # Fall through to other methods+ def _download_pdf_with_fallback(+ self, url: str+ ) -> Tuple[DownloadResult, Optional[BaseDownloader]]:+ """Try matching PDF downloaders, preserving retryable failures."""+ selected_downloader = None+ best_permanent = None+ best_temporary = None+ classifier = FailureClassifier()++ for downloader in self.downloaders:+ if not downloader.can_handle(url):+ continue+ logger.info(+ "Using {} for {}",+ downloader.__class__.__name__,+ redact_url_for_log(url),+ )+ result = downloader.download_with_result(url, ContentType.PDF)+ selected_downloader = downloader+ if result.is_success and result.content:+ return result, downloader+ if result.skip_reason:+ failure = classifier.classify_failure(+ "download_failed",+ status_code=result.status_code,+ url=url,+ details=result.skip_reason,+ )+ if failure.is_permanent():+ best_permanent = result+ else:+ best_temporary = result+ logger.info(+ "Download skipped: {}",+ failure_reason_for_log(result.skip_reason),+ )+ # arXiv handles its own fallbacks; GenericDownloader is last.+ if isinstance(downloader, (ArxivDownloader, GenericDownloader)):+ break++ if selected_downloader is None:+ logger.error("No downloader found for {}", redact_url_for_log(url))+ return DownloadResult(+ skip_reason="No compatible downloader available"+ ), None+ return (+ best_temporary or best_permanent or DownloadResult(),+ selected_downloader,+ )+def _try_api_text_extraction(self, session, resource) -> Optional[Tuple[bool, Optional[str]]]:@@ -4107,6 +4143,11 @@ class DownloadService:)return False, f"egress_policy_denied:{reason}"+ if isinstance(downloader, OpenAccessDOIDownloader):+ # DOI text comes from a PDF. Resolve it once in the PDF chain so+ # an inconclusive lookup can still reach the generic fallback.+ return None+if isinstance(downloader, ArxivDownloader):arxiv_text = downloader.download_text_with_source(resource.url)if arxiv_text is None:@@ -4169,18 +4210,6 @@ class DownloadService:f"Direct text extraction unavailable; trying in-memory PDF for: {redact_url_for_log(resource.url)}")- downloader = self._get_downloader(resource.url)- if not downloader:- error_msg = "No compatible downloader found"- logger.warning(- f"✗ FAILED: {failure_reason_for_log(error_msg)} for '{resource.title[:50]}...'"- )- self._record_failed_text_extraction(- session, resource, error=error_msg- )- session.commit()- return False, error_msg-# Egress policy gate at the network-fire point.allowed, reason = self._check_url_against_policy(resource.url)if not allowed:@@ -4195,7 +4224,14 @@ class DownloadService:session.commit()return False, error_msg- result = downloader.download_with_result(resource.url, ContentType.PDF)+ result, downloader = self._download_pdf_with_fallback(resource.url)+ if downloader is None:+ error_msg = "No compatible downloader found"+ self._record_failed_text_extraction(+ session, resource, error=error_msg+ )+ session.commit()+ return False, error_msgif not result.is_success or not result.content:error_msg = result.skip_reason or "Failed to download PDF"diff --git a/tests/research_library/downloaders/test_open_access_doi_downloader.py b/tests/research_library/downloaders/test_open_access_doi_downloader.pynew file mode 100644index 0000000000..e09889ae5c--- /dev/null+++ b/tests/research_library/downloaders/test_open_access_doi_downloader.py@@ -0,0 +1,474 @@+"""Tests for OpenAccessDOIDownloader (DOI -> open-access PDF resolution)."""++from unittest.mock import Mock, patch++import pytest+import requests+from loguru import logger++from local_deep_research.research_library.downloaders.base import BaseDownloader+from local_deep_research.research_library.downloaders.open_access_doi import (+ OpenAccessDOIDownloader,+)+++def _oa_work(pdf_url=None, landing=None, locations=None, is_oa=True):+ """Build an OpenAlex /works response body for a single work.++ ``locations`` mirrors OpenAlex's real schema: a list of location objects,+ each with an ``is_oa`` flag and an optional ``pdf_url`` (OpenAlex returns+ ``locations``, not ``oa_locations``).+ """+ return {+ "results": [+ {+ "id": "W1234567890",+ "open_access": {+ "is_oa": is_oa,+ "oa_status": "gold" if is_oa else "closed",+ },+ "best_oa_location": (+ {"pdf_url": pdf_url, "landing_page_url": landing}+ if (pdf_url is not None or landing is not None)+ else None+ ),+ "locations": locations or [],+ }+ ]+ }+++def _api_response(body, status_code=200):+ r = Mock()+ r.status_code = status_code+ r.json.return_value = body+ return r+++def _pdf_response(pdf_content):+ r = Mock()+ r.status_code = 200+ r.content = pdf_content+ r.headers = {"Content-Type": "application/pdf"}+ return r+++class TestOpenAccessDOIDownloaderInit:+ def test_preserves_download_service_context(self):+ snapshot = {"research_library.auto_persist_research_sources": False}+ downloader = OpenAccessDOIDownloader(+ username="test_user",+ password="test_password",+ settings_snapshot=snapshot,+ enable_fetch_persistence=False,+ )+ try:+ assert downloader.username == "test_user"+ assert downloader.settings_snapshot is snapshot+ assert downloader.enable_fetch_persistence is False+ finally:+ downloader.close()++ def test_initializes_with_default_timeout(self):+ assert OpenAccessDOIDownloader().timeout == 30++ def test_initializes_with_custom_timeout(self):+ assert OpenAccessDOIDownloader(timeout=60).timeout == 60++ def test_creates_session(self):+ assert OpenAccessDOIDownloader().session is not None+++class TestOpenAccessDOIDownloaderCanHandle:+ def test_handles_doi_org(self):+ assert OpenAccessDOIDownloader().can_handle(+ "https://doi.org/10.3390/ma15196591"+ )++ def test_handles_dx_doi_org(self):+ assert OpenAccessDOIDownloader().can_handle(+ "https://dx.doi.org/10.3390/ma15196591"+ )++ def test_rejects_non_doi(self):+ d = OpenAccessDOIDownloader()+ assert not d.can_handle("https://www.nature.com/articles/x")+ assert not d.can_handle("https://arxiv.org/abs/1234.5678")+ assert not d.can_handle("https://openalex.org/W123")++ def test_rejects_empty(self):+ assert not OpenAccessDOIDownloader().can_handle("")+++class TestOpenAccessDOIDownloaderExtractDoi:+ def test_extracts_from_doi_org(self):+ assert (+ OpenAccessDOIDownloader()._extract_doi(+ "https://doi.org/10.3390/ma15196591"+ )+ == "10.3390/ma15196591"+ )++ def test_extracts_from_dx_doi_org(self):+ assert (+ OpenAccessDOIDownloader()._extract_doi(+ "https://dx.doi.org/10.1038/s41586-021-04301-9"+ )+ == "10.1038/s41586-021-04301-9"+ )++ def test_returns_none_for_non_doi(self):+ assert (+ OpenAccessDOIDownloader()._extract_doi("https://example.com/x")+ is None+ )++ def test_returns_none_for_empty_path(self):+ assert (+ OpenAccessDOIDownloader()._extract_doi("https://doi.org/") is None+ )+++class TestOpenAccessDOIDownloaderResolve:+ def test_best_location_pdf(self):+ d = OpenAccessDOIDownloader()+ with patch.object(+ d.session,+ "get",+ return_value=_api_response(+ _oa_work(pdf_url="https://example.com/paper.pdf")+ ),+ ):+ url, status = d._resolve_oa_pdf("10.3390/ma15196591")+ assert status == "oa"+ assert url == "https://example.com/paper.pdf"++ def test_falls_back_to_oa_locations(self):+ """best_oa_location.pdf_url is None but an OA location has a PDF.++ Verifies the documented ``locations`` schema (not the non-existent+ ``oa_locations``): the resolver scans ``locations`` and picks the one+ with ``is_oa=True`` and a ``pdf_url``, skipping non-OA locations.+ """+ d = OpenAccessDOIDownloader()+ with patch.object(+ d.session,+ "get",+ return_value=_api_response(+ _oa_work(+ pdf_url=None,+ landing="https://example.com/landing",+ locations=[+ {+ "is_oa": False,+ "pdf_url": "https://example.com/paywalled.pdf",+ },+ {+ "is_oa": True,+ "pdf_url": "https://example.com/pmc.pdf",+ },+ ],+ )+ ),+ ):+ url, status = d._resolve_oa_pdf("10.3390/ma15196591")+ assert status == "oa"+ assert url == "https://example.com/pmc.pdf"++ def test_skips_non_oa_locations(self):+ """A non-OA location with a PDF must not be used (paywall risk).++ With no ``best_oa_location`` PDF, no OA location PDF, and no landing+ page, the resolver returns ``unknown`` (retryable) — not the paywalled+ PDF.+ """+ d = OpenAccessDOIDownloader()+ with patch.object(+ d.session,+ "get",+ return_value=_api_response(+ _oa_work(+ pdf_url=None,+ locations=[+ {+ "is_oa": False,+ "pdf_url": "https://example.com/paywalled.pdf",+ },+ ],+ )+ ),+ ):+ url, status = d._resolve_oa_pdf("10.3390/ma15196591")+ assert status != "oa"+ assert url is None++ def test_not_oa(self):+ d = OpenAccessDOIDownloader()+ with patch.object(+ d.session,+ "get",+ return_value=_api_response(_oa_work(pdf_url=None, is_oa=False)),+ ):+ url, status = d._resolve_oa_pdf("10.1016/j.tice.2019.05.008")+ assert status == "not_oa"+ assert url is None++ def test_api_error_is_unknown(self):+ d = OpenAccessDOIDownloader()+ with patch.object(+ d.session, "get", return_value=_api_response({}, status_code=500)+ ):+ url, status = d._resolve_oa_pdf("10.3390/ma15196591")+ assert status == "unknown"+ assert url is None++ def test_not_found_is_unknown(self):+ d = OpenAccessDOIDownloader()+ with patch.object(+ d.session, "get", return_value=_api_response({"results": []})+ ):+ url, status = d._resolve_oa_pdf("10.9999/does-not-exist")+ assert status == "unknown"+ assert url is None++ def test_exception_is_unknown(self):+ d = OpenAccessDOIDownloader()+ with patch.object(+ d.session,+ "get",+ side_effect=requests.exceptions.ConnectionError("network down"),+ ):+ url, status = d._resolve_oa_pdf("10.3390/ma15196591")+ assert status == "unknown"+ assert url is None++ def test_landing_page_pdf_check(self):+ """No direct PDF URL, but the landing page serves application/pdf."""+ d = OpenAccessDOIDownloader()+ head = Mock()+ head.headers = {"Content-Type": "application/pdf"}+ with patch.object(+ d.session,+ "get",+ return_value=_api_response(+ _oa_work(+ pdf_url=None,+ landing="https://example.com/paper.pdf",+ )+ ),+ ):+ with patch.object(d.session, "head", return_value=head):+ url, status = d._resolve_oa_pdf("10.3390/ma15196591")+ assert status == "oa"+ assert url == "https://example.com/paper.pdf"++ def test_oa_without_any_pdf_is_unknown_not_paywall(self):+ """OA work with no retrievable PDF must be retryable, not a paywall."""+ d = OpenAccessDOIDownloader()+ head = Mock()+ head.headers = {"Content-Type": "text/html"}+ with patch.object(+ d.session,+ "get",+ return_value=_api_response(+ _oa_work(pdf_url=None, landing="https://example.com/landing")+ ),+ ):+ with patch.object(d.session, "head", return_value=head):+ url, status = d._resolve_oa_pdf("10.3390/ma15196591")+ assert status == "unknown"+ assert url is None+++class TestOpenAccessDOIDownloaderDownloadWithResult:+ def test_success(self, mock_pdf_content):+ d = OpenAccessDOIDownloader()+ with patch.object(+ d.session,+ "get",+ side_effect=[+ _api_response(+ _oa_work(pdf_url="https://example.com/paper.pdf")+ ),+ _pdf_response(mock_pdf_content),+ ],+ ):+ result = d.download_with_result(+ "https://doi.org/10.3390/ma15196591"+ )+ assert result.is_success is True+ assert result.content == mock_pdf_content++ def test_not_oa_is_permanent_paywall(self):+ d = OpenAccessDOIDownloader()+ with patch.object(+ d.session,+ "get",+ return_value=_api_response(_oa_work(pdf_url=None, is_oa=False)),+ ):+ result = d.download_with_result(+ "https://doi.org/10.1016/j.tice.2019.05.008"+ )+ assert result.is_success is False+ assert "paywall" in result.skip_reason.lower()++ def test_api_error_is_retryable_not_paywall(self):+ d = OpenAccessDOIDownloader()+ with patch.object(+ d.session, "get", return_value=_api_response({}, status_code=500)+ ):+ result = d.download_with_result(+ "https://doi.org/10.3390/ma15196591"+ )+ assert result.is_success is False+ assert "paywall" not in result.skip_reason.lower()++ def test_pdf_download_failure_is_retryable(self):+ d = OpenAccessDOIDownloader()+ with patch.object(+ d.session,+ "get",+ side_effect=[+ _api_response(+ _oa_work(pdf_url="https://example.com/paper.pdf")+ ),+ Mock(status_code=403, content=b"", headers={}),+ ],+ ):+ result = d.download_with_result(+ "https://doi.org/10.3390/ma15196591"+ )+ assert result.is_success is False+ assert "paywall" not in result.skip_reason.lower()++ def test_text_success(self, mock_pdf_content):+ d = OpenAccessDOIDownloader()+ with patch.object(+ d.session,+ "get",+ side_effect=[+ _api_response(+ _oa_work(pdf_url="https://example.com/paper.pdf")+ ),+ _pdf_response(mock_pdf_content),+ ],+ ):+ with patch.object(+ OpenAccessDOIDownloader,+ "extract_text_from_pdf",+ return_value="extracted text",+ ):+ result = d.download_with_result(+ "https://doi.org/10.3390/ma15196591",+ content_type="text",+ )+ assert result.is_success is True+ assert result.content == b"extracted text"++ def test_cannot_extract_doi(self):+ d = OpenAccessDOIDownloader()+ result = d.download_with_result("https://doi.org/")+ assert result.is_success is False+ assert result.skip_reason is not None+++def doi_logs():+ messages = []+ logger.enable("local_deep_research")+ sink = logger.add(+ messages.append, level="DEBUG", format="{message}\n{exception}"+ )+ try:+ yield messages+ finally:+ logger.remove(sink)+ logger.disable("local_deep_research")+++def test_pdf_download_logs_origin_only(doi_logs):+ downloader = OpenAccessDOIDownloader()+ downloader._resolve_oa_pdf = Mock(+ return_value=(+ "https://publisher.example/document-marker.pdf?token=private-marker",+ "oa",+ )+ )+ try:+ with patch.object(+ BaseDownloader, "_download_pdf", return_value=b"%PDF"+ ):+ assert downloader.download_with_result(+ "https://doi.org/10.1234/document-marker"+ ).is_success+ finally:+ downloader.close()++ rendered = "".join(doi_logs)+ assert "https://publisher.example" in rendered+ assert "document-marker" not in rendered+ assert "private-marker" not in rendered+ assert all(message.record["exception"] is None for message in doi_logs)+++ "body",+ [+ {"results": []},+ _oa_work(is_oa=False),+ _oa_work(landing="https://publisher.example/document-marker"),+ ],+)+def test_lookup_diagnostics_omit_document_details(body, doi_logs):+ downloader = OpenAccessDOIDownloader()+ response = _api_response(body)+ head = Mock(headers={"Content-Type": "text/html"})+ try:+ with (+ patch.object(downloader.session, "get", return_value=response),+ patch.object(downloader.session, "head", return_value=head),+ ):+ downloader._resolve_oa_pdf("10.1234/document-marker")+ response.close.assert_called_once()+ if body.get("results") and body["results"][0].get("best_oa_location"):+ head.close.assert_called_once()+ finally:+ downloader.close()++ assert "document-marker" not in "".join(doi_logs)+ assert all(message.record["exception"] is None for message in doi_logs)++[email protected]("failure_point", ["get", "json", "head"])+def test_lookup_failures_emit_controlled_diagnostics(failure_point, doi_logs):+ downloader = OpenAccessDOIDownloader()+ response = _api_response(+ _oa_work(landing="https://publisher.example/document-marker")+ )+ error = requests.RequestException("document-marker private-marker")+ if failure_point == "json":+ response.json.side_effect = ValueError("document-marker private-marker")+ try:+ with (+ patch.object(+ downloader.session,+ "get",+ side_effect=error if failure_point == "get" else None,+ return_value=response,+ ),+ patch.object(downloader.session, "head", side_effect=error),+ ):+ assert downloader._resolve_oa_pdf("10.1234/document-marker") == (+ None,+ "unknown",+ )+ if failure_point != "get":+ response.close.assert_called_once()+ finally:+ downloader.close()++ rendered = "".join(doi_logs)+ assert "ValueError" in rendered or "RequestException" in rendered+ assert "document-marker" not in rendered+ assert "private-marker" not in rendered+ assert all(message.record["exception"] is None for message in doi_logs)diff --git a/tests/research_library/services/test_download_service_coverage.py b/tests/research_library/services/test_download_service_coverage.pyindex 9dba377fbb..ff9b409791 100644--- a/tests/research_library/services/test_download_service_coverage.py+++ b/tests/research_library/services/test_download_service_coverage.py@@ -1277,7 +1277,7 @@ class TestFallbackPdfExtraction:resource.title = "Test Paper with Long Title for Slicing"with (- patch.object(svc, "_get_downloader", return_value=None),+ patch.object(svc, "downloaders", []),patch.object(svc, "_record_failed_text_extraction"),):success, msg = svc._fallback_pdf_extraction(session, resource)@@ -1298,7 +1298,7 @@ class TestFallbackPdfExtraction:downloader.download_with_result.return_value = result_objwith (- patch.object(svc, "_get_downloader", return_value=downloader),+ patch.object(svc, "downloaders", [downloader]),patch.object(svc, "_record_failed_text_extraction"),):success, msg = svc._fallback_pdf_extraction(session, resource)@@ -1317,7 +1317,7 @@ class TestFallbackPdfExtraction:downloader.download_with_result.return_value = result_objwith (- patch.object(svc, "_get_downloader", return_value=downloader),+ patch.object(svc, "downloaders", [downloader]),patch.object(svc, "_extract_text_from_pdf", return_value=None),patch.object(svc, "_record_failed_text_extraction"),):@@ -1337,7 +1337,7 @@ class TestFallbackPdfExtraction:downloader.download_with_result.return_value = result_objwith (- patch.object(svc, "_get_downloader", return_value=downloader),+ patch.object(svc, "downloaders", [downloader]),patch.object(svc, "_extract_text_from_pdf", return_value="Extracted!"),@@ -1361,7 +1361,7 @@ class TestFallbackPdfExtraction:downloader.download_with_result.return_value = result_objwith (- patch.object(svc, "_get_downloader", return_value=downloader),+ patch.object(svc, "downloaders", [downloader]),patch.object(svc, "_extract_text_from_pdf", return_value="text"),patch.object(svc, "_save_text_with_db", side_effect=RuntimeError("db")@@ -1386,7 +1386,7 @@ class TestFallbackPdfExtraction:downloader.download_with_result.return_value = result_objwith (- patch.object(svc, "_get_downloader", return_value=downloader),+ patch.object(svc, "downloaders", [downloader]),patch.object(svc, "_record_failed_text_extraction"),):success, msg = svc._fallback_pdf_extraction(session, resource)diff --git a/tests/research_library/services/test_download_service_oa_retryable_preserved.py b/tests/research_library/services/test_download_service_oa_retryable_preserved.pynew file mode 100644index 0000000000..44e067a09e--- /dev/null+++ b/tests/research_library/services/test_download_service_oa_retryable_preserved.py@@ -0,0 +1,260 @@+"""+Regression (PR #6385, issue #6210): a retryable OA outcome must not be+clobbered by a later permanent failure in the ``_download_pdf`` fallback loop.++Sequence: ``OpenAccessDOIDownloader`` finds an OA copy but its download fails+(retryable). ``GenericDownloader`` then returns a publisher 403 (permanent).+Before the fix, the 403 overwrote the retryable ``skip_reason``/``status_code``,+so ``FailureClassifier`` marked the paper as permanently paywalled. The+retryable outcome must survive so the paper is retried, not given up on.+"""++from types import SimpleNamespace+from unittest.mock import Mock++import pytest++from local_deep_research.research_library.downloaders.base import (+ BaseDownloader,+ ContentType,+ DownloadResult,+)+from local_deep_research.research_library.downloaders.generic import (+ GenericDownloader,+)+from local_deep_research.research_library.downloaders.open_access_doi import (+ OpenAccessDOIDownloader,+)+from local_deep_research.library.download_management import FailureClassifier+++def _make_service(mocker):+ mock_settings = Mock()+ mock_settings.get_setting.return_value = "/tmp/test_library"+ mocker.patch(+ "local_deep_research.research_library.services.download_service.get_settings_manager",+ return_value=mock_settings,+ )+ mocker.patch("pathlib.Path.mkdir")+ mocker.patch(+ "local_deep_research.research_library.services.download_service.RetryManager"+ )+ from local_deep_research.research_library.services.download_service import (+ DownloadService,+ )++ return DownloadService(username="test_user")+++def _result(is_success, content, skip_reason, status_code):+ r = Mock()+ r.is_success = is_success+ r.content = content+ r.skip_reason = skip_reason+ r.status_code = status_code+ return r+++def _downloader(result):+ d = Mock()+ d.can_handle.return_value = True+ d.download_with_result.return_value = result+ return d+++def _run(service, url="https://doi.org/10.3390/ma15196591"):+ service._check_url_against_policy = Mock(return_value=(True, "no_context"))+ resource = SimpleNamespace(+ id=1, url=url, title="Open-access paper", document_id=None+ )+ # No `download_attempts` attr -> the code's `hasattr` guard uses `else 1`+ # (a plain list's `.count()` needs an argument, so we avoid that branch).+ tracker = SimpleNamespace(url_hash="abc123")+ session = Mock()+ return service._download_pdf(resource, tracker, session)+++class TestOARetryablePreserved:+ def test_retryable_not_clobbered_by_later_permanent(self, mocker):+ """OA copy found but download failed (retryable) survives a later 403."""+ service = _make_service(mocker)+ service.downloaders = [+ _downloader(+ _result(+ False,+ None,+ "Open access PDF found but download failed",+ 503,+ )+ ),+ _downloader(_result(False, None, "Access forbidden (403)", 403)),+ ]+ success, skip_reason, status_code = _run(service)+ assert success is False+ assert skip_reason == "Open access PDF found but download failed"+ assert status_code == 503++ def test_permanent_used_when_no_retryable(self, mocker):+ """With no retryable outcome, the permanent one is used (control)."""+ service = _make_service(mocker)+ service.downloaders = [+ _downloader(_result(False, None, "Access forbidden (403)", 403)),+ ]+ success, skip_reason, status_code = _run(service)+ assert success is False+ assert skip_reason == "Access forbidden (403)"+ assert status_code == 403++ def test_all_permanent_last_wins(self, mocker):+ """All-permanent: the last downloader's reason wins (prior behaviour)."""+ service = _make_service(mocker)+ service.downloaders = [+ _downloader(_result(False, None, "Access forbidden (403)", 403)),+ _downloader(+ _result(+ False, None, "No open access copy available (paywall)", None+ )+ ),+ ]+ success, skip_reason, status_code = _run(service)+ assert success is False+ assert skip_reason == "No open access copy available (paywall)"+++def text_fallback(mocker):+ from local_deep_research.research_library.services.download_service import (+ DownloadService,+ )++ service = DownloadService.__new__(DownloadService)+ service.username = "test_user"+ service.password = None+ service.retry_manager = None+ service._check_url_against_policy = Mock(return_value=(True, "allowed"))+ service._record_failed_text_extraction = Mock()+ service._save_text_with_db = Mock()+ service._extract_text_from_pdf = Mock(return_value="Open access full text")+ for name in (+ "_try_existing_text",+ "_try_legacy_text_file",+ "_try_arxiv_text_extraction",+ "_try_existing_pdf_extraction",+ ):+ setattr(service, name, Mock(return_value=None))++ doi = OpenAccessDOIDownloader.__new__(OpenAccessDOIDownloader)+ doi._resolve_oa_pdf = Mock(return_value=(None, "unknown"))+ generic = GenericDownloader.__new__(GenericDownloader)+ generic.download_with_result = Mock(+ return_value=DownloadResult(content=b"%PDF-test", is_success=True)+ )+ service.downloaders = [doi, generic]+ resource = SimpleNamespace(+ id=1,+ url="https://doi.org/10.1234/example",+ title="Open access paper",+ document_id=None,+ source_type="research",+ )+ session = Mock()+ session.query.return_value.filter_by.return_value.first.return_value = (+ resource+ )+ session_cm = mocker.patch(+ "local_deep_research.research_library.services.download_service.get_user_db_session"+ )+ session_cm.return_value.__enter__.return_value = session+ return SimpleNamespace(+ service=service,+ doi=doi,+ generic=generic,+ resource=resource,+ session=session,+ )+++def test_text_extraction_reaches_generic_after_inconclusive_doi(text_fallback):+ case = text_fallback++ assert case.service.download_as_text(case.resource.id) == (True, None)++ case.doi._resolve_oa_pdf.assert_called_once_with("10.1234/example")+ case.generic.download_with_result.assert_called_once_with(+ case.resource.url, ContentType.PDF+ )+ case.service._save_text_with_db.assert_called_once_with(+ case.resource,+ "Open access full text",+ case.session,+ extraction_method="pdf_extraction",+ extraction_source="pdfplumber_fallback",+ )+++def test_text_extraction_preserves_retryable_doi_failure(text_fallback):+ case = text_fallback+ case.generic.download_with_result.return_value = DownloadResult(+ skip_reason="Access forbidden (403)", status_code=403+ )++ success, error = case.service.download_as_text(case.resource.id)++ assert success is False+ assert error == (+ "PDF extraction failed: Could not resolve open access status for DOI (retry later)"+ )+ assert (+ not FailureClassifier()+ .classify_failure(+ "download_failed", url=case.resource.url, details=error+ )+ .is_permanent()+ )+ case.doi._resolve_oa_pdf.assert_called_once()+ case.generic.download_with_result.assert_called_once()+++def test_text_extraction_policy_denial_stops_all_downloaders(text_fallback):+ case = text_fallback+ case.service._check_url_against_policy.return_value = (False, "denied")++ assert case.service.download_as_text(case.resource.id) == (+ False,+ "egress_policy_denied:denied",+ )++ case.doi._resolve_oa_pdf.assert_not_called()+ case.generic.download_with_result.assert_not_called()+++def test_successful_fallback_keeps_its_own_status(text_fallback):+ case = text_fallback+ case.generic.download_with_result.return_value = DownloadResult(+ content=b"%PDF-test", is_success=True, status_code=200+ )++ result, selected = case.service._download_pdf_with_fallback(+ case.resource.url+ )++ assert result.is_success+ assert result.status_code == 200+ assert result.skip_reason is None+ assert selected is case.generic+++def test_text_extraction_uses_resolved_doi_pdf_once(text_fallback, mocker):+ case = text_fallback+ pdf_url = "https://publisher.example/paper.pdf"+ case.doi._resolve_oa_pdf.return_value = (pdf_url, "oa")+ fetch = mocker.patch.object(+ BaseDownloader, "_download_pdf", return_value=b"%PDF-test"+ )++ assert case.service.download_as_text(case.resource.id) == (True, None)++ case.doi._resolve_oa_pdf.assert_called_once_with("10.1234/example")+ fetch.assert_called_once_with(pdf_url)+ case.generic.download_with_result.assert_not_called()+ case.service._extract_text_from_pdf.assert_called_once_with(b"%PDF-test")diff --git a/tests/research_library/services/test_download_service_pool_exhaustion_6560.py b/tests/research_library/services/test_download_service_pool_exhaustion_6560.pyindex 762eff9cdf..8865e5b6fa 100644--- a/tests/research_library/services/test_download_service_pool_exhaustion_6560.py+++ b/tests/research_library/services/test_download_service_pool_exhaustion_6560.py@@ -673,11 +673,12 @@ def test_text_extraction_save_failures_do_not_leak_sql_in_error(resource.id = 12resource.title = "Fallback PDF Paper With Long Title For Slicing"downloader = MagicMock()+ downloader.can_handle.return_value = Truedownloader.download_with_result.return_value = MagicMock(is_success=True, content=b"%PDF-1.4 bytes")+ service_stub.downloaders = [downloader]with (- patch.object(service_stub, "_get_downloader", return_value=downloader),patch.object(service_stub, "_extract_text_from_pdf", return_value="text"),