~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(library): keep transient access failures retryable (#7760)
LearningCircuit9bb1fd722393
diff --git a/changelog.d/7588.bugfix.md b/changelog.d/7588.bugfix.mdnew file mode 100644index 0000000000..a8658d20e7--- /dev/null+++ b/changelog.d/7588.bugfix.md@@ -0,0 +1,3 @@+Keep rate-limited Semantic Scholar lookups retryable, and treat a 403 judged to come from a known open-access host as a temporary access block instead of a permanent failure. The generic downloader's 403 diagnostic is judged by the host that answered after any redirects, and the failure stays recorded against the original source URL; every other 403 is judged by the original source URL. Semantic Scholar lookups no longer report a missing PDF link as proof of a subscription requirement, and the generic downloader no longer describes an HTTP 403 that way.++A Semantic Scholar paper with no open-access PDF link is no longer marked permanent on its first failure, on either the PDF or the text-extraction path; it stays retryable until the retry cap. Both paths run the full downloader chain, so the recorded failure is usually the generic downloader's temporary `html_not_pdf` diagnostic rather than the Semantic Scholar lookup's own. Resources already marked permanently failed are not reclassified. Per-host rate-limit cooldowns (arXiv, bioRxiv, PubMed, Semantic Scholar, ResearchGate) now also apply to their subdomains, matched without regard to case, an explicit port or a trailing dot, which lengthens some first-attempt cooldowns: `www.biorxiv.org` and `export.arxiv.org`, for example, go from 1 hour to 6 hours. Failure text in the forms the downloaders emit, such as "status 429", "HTTP 429", "(429)" or "rate limited", is now classified as a rate limit when no status code accompanies it, as on the text-extraction path, so hosts with their own rate-limit cooldown apply it instead of the 1-hour default; subscription or login wording, and URLs inside the text, do not count as rate-limit wording.diff --git a/src/local_deep_research/library/download_management/failure_classifier.py b/src/local_deep_research/library/download_management/failure_classifier.pyindex ded674bea5..4bcf452394 100644--- a/src/local_deep_research/library/download_management/failure_classifier.py+++ b/src/local_deep_research/library/download_management/failure_classifier.py@@ -7,7 +7,9 @@ Uses inheritance to organize different failure categories and their retry behavifrom abc import ABCfrom datetime import datetime, timedelta, UTC+import refrom typing import Optional+from urllib.parse import urlparsefrom loguru import logger@@ -82,7 +84,27 @@ class RateLimitFailure(TemporaryFailure):), # Default cooldown for unknown domains}- cooldown = domain_cooldowns.get(domain, domain_cooldowns["default"])+ # Exact authority first, then a parent-domain match: real URL+ # authorities carry subdomains ("www.semanticscholar.org"), which an+ # exact-match lookup would drop to the default cooldown. The authority+ # is normalised for the lookup only (case, an explicit port, a+ # trailing root dot); the message keeps the domain as given.+ host = (domain or "").strip().lower()+ if host.startswith("["):+ host = host.split("]", 1)[0] + "]"+ else:+ host = host.rsplit(":", 1)[0] if ":" in host else host+ host = host.rstrip(".")+ cooldown = domain_cooldowns.get(host)+ if cooldown is None:+ cooldown = next(+ (+ value+ for key, value in domain_cooldowns.items()+ if key != "default" and host.endswith("." + key)+ ),+ domain_cooldowns["default"],+ )message = f"Rate limited by {domain}"if details:message += f" - {details}"@@ -196,6 +218,69 @@ _CLIENT_SAFE_TOKEN_FAILURES: dict[str, tuple[str, str, timedelta]] = {_OPERATOR_FIXABLE_TOKENS = frozenset({"pdf_storage_size_limit"})+_OPEN_ACCESS_HOSTS = frozenset(+ {+ "arxiv.org",+ "biorxiv.org",+ "medrxiv.org",+ "mdpi.com",+ "plos.org",+ "biomedcentral.com",+ "frontiersin.org",+ "pmc.ncbi.nlm.nih.gov",+ "europepmc.org",+ # The Semantic Scholar API is bot-block-prone (Cloudflare-fronted)+ # and names no subscription of its own; a 403 there is an access+ # block, not a paywall (#7588).+ "semanticscholar.org",+ }+)++_OPEN_ACCESS_BLOCK_REASON = (+ "Open access source refused the automated download (403)"+)+_DESTINATION_FORBIDDEN_REASON = (+ "Access denied (403) - destination refused the download"+)+++def _is_open_access_source(url: str) -> bool:+ """Recognize public article hosts and their subdomains."""+ try:+ hostname = urlparse(url).hostname+ except ValueError:+ return False+ return bool(+ hostname+ and any(+ hostname == host or hostname.endswith("." + host)+ for host in _OPEN_ACCESS_HOSTS+ )+ )+++def access_denied_reason(url: str) -> str:+ """Describe the terminal response's 403 without returning its URL.++ These fixed reasons retain the destination's classification through PDF+ and text-only retry recording, whose resource URL stays canonical even+ when the request followed a redirect.+ """+ return (+ _OPEN_ACCESS_BLOCK_REASON+ if _is_open_access_source(url)+ else _DESTINATION_FORBIDDEN_REASON+ )+++_PAYWALL_PATTERNS = (+ "requires login",+ "subscription",+ "paywall",+ "requires authentication",+)++class FailureClassifier:"""Classifies download failures into appropriate types based on error patterns"""@@ -218,6 +303,52 @@ class FailureClassifier:Returns:Appropriate failure classification"""+ details_lower = (details or "").lower()+ pdf_extraction_wrapper = "pdf extraction failed: "+ unwrapped_details_lower = (+ details_lower[len(pdf_extraction_wrapper) :]+ if details_lower.startswith(pdf_extraction_wrapper)+ else details_lower+ )+ # A downloader that inspected the terminal response can classify a+ # redirect's destination more accurately than the canonical source+ # URL. Keep its fixed reason across retry-recording paths.+ if (+ status_code in (None, 403)+ and unwrapped_details_lower == _DESTINATION_FORBIDDEN_REASON.lower()+ ):+ return PermanentFailure("forbidden", "Access forbidden (403)")++ # A named anti-bot challenge (reCAPTCHA or a generic captcha wall) is+ # the deliberate 3-day cooldown — it outranks the one-hour OA-403+ # access-block rescue below, which would otherwise shorten it.+ recaptcha_detected = (+ "recaptcha" in details_lower or "captcha" in details_lower+ )+ # A public article host can refuse an automated fetch without the+ # article requiring a subscription. Text-only extraction paths retain+ # the diagnostic but do not carry the structured HTTP status.+ access_denied = "access denied" in details_lower or re.search(+ r"\b(?:http|status(?: code)?|error code)\s+403\b|\(403\)"+ r"|403\s+forbidden",+ details_lower,+ )+ if (status_code == 403 or (status_code is None and access_denied)) and (+ unwrapped_details_lower == _OPEN_ACCESS_BLOCK_REASON.lower()+ or _is_open_access_source(url)+ ):+ if recaptcha_detected:+ return TemporaryFailure(+ "recaptcha_protection",+ "Anti-bot protection active, retry after 3 days",+ timedelta(days=3),+ )+ return TemporaryFailure(+ "oa_bot_block",+ _OPEN_ACCESS_BLOCK_REASON,+ timedelta(hours=1),+ )+# HTTP Status Code classificationsif status_code:if status_code == 202:@@ -293,7 +424,29 @@ class FailureClassifier:# Error message pattern classificationserror_lower = error_type.lower()- details_lower = details.lower()+ # Rate-limit wording only stands in for a missing status code: with a+ # status present, the status branches above already decided. Any named+ # anti-bot challenge ("captcha" text, on any host) skips this check, so+ # the arXiv branch below can still apply its 3-day cooldown, and paywall+ # wording wins so a journal name such as "Journal of Rate Limiting" in+ # "Article requires subscription to ..." stays a paywall. URLs are+ # blanked first so a path or host like ".../rate-limiting-paper" is not+ # read as the diagnostic.+ is_paywall_text = any(+ pattern in details_lower for pattern in _PAYWALL_PATTERNS+ )+ if (+ status_code is None+ and not recaptcha_detected+ and not is_paywall_text+ and re.search(+ r"\b(?:http|status(?: code)?|error code)\s+429\b"+ r"|\brate[ -]limit(?:ed|ing)?\b|\(429\)",+ re.sub(r"[a-z][a-z0-9+.-]*://\S*", " ", details_lower),+ )+ ):+ domain = url_authority_without_userinfo(url) if url else "unknown"+ return RateLimitFailure(domain, details)# GenericDownloader's neutral diagnostic identifies a format mismatch;# it is not evidence that the source itself is inaccessible. Keep this@@ -303,12 +456,6 @@ class FailureClassifier:# before it reaches here, so strip that one known wrapper prefix and# still require an exact match on what's left.html_not_pdf_reason = "source is an html page, not a pdf"- pdf_extraction_wrapper = "pdf extraction failed: "- unwrapped_details_lower = (- details_lower[len(pdf_extraction_wrapper) :]- if details_lower.startswith(pdf_extraction_wrapper)- else details_lower- )if unwrapped_details_lower == html_not_pdf_reason:return TemporaryFailure("html_not_pdf",@@ -318,7 +465,7 @@ class FailureClassifier:# arXiv specific patternsif "arxiv" in error_lower or "arxiv" in details_lower:- if "recaptcha" in details_lower or "captcha" in details_lower:+ if recaptcha_detected:return TemporaryFailure("recaptcha_protection","Anti-bot protection active, retry after 3 days",@@ -338,15 +485,7 @@ class FailureClassifier:)# Login/subscription/paywall errors — these are permanent- if any(- pattern in details_lower- for pattern in [- "requires login",- "subscription",- "paywall",- "requires authentication",- ]- ):+ if is_paywall_text:return PermanentFailure("paywall_or_login","Requires login or subscription",diff --git a/src/local_deep_research/research_library/downloaders/generic.py b/src/local_deep_research/research_library/downloaders/generic.pyindex 093a3655b4..56e0fdf9eb 100644--- a/src/local_deep_research/research_library/downloaders/generic.py+++ b/src/local_deep_research/research_library/downloaders/generic.py@@ -7,6 +7,9 @@ import requestsfrom urllib.parse import urlparse, urlunparsefrom loguru import logger+from ...library.download_management.failure_classifier import (+ access_denied_reason,+)from ...security.ssrf_validator import redact_url_for_logfrom .base import BaseDownloader, ContentType, DownloadResult@@ -173,10 +176,21 @@ class GenericDownloader(BaseDownloader):status_code=404,)if response.status_code == 403:+ # ``url`` is set per instance by requests.Response, not+ # declared on the class, so a response-like object may+ # lack it; fall back to the requested URL.+ destination = getattr(response, "url", None)+ if not isinstance(destination, str) or not destination:+ destination = urlreturn DownloadResult(- skip_reason="Access denied (403) - article requires subscription or special permissions",+ skip_reason=access_denied_reason(destination),status_code=403,)+ if response.status_code == 429:+ return DownloadResult(+ skip_reason="Rate limited (429) - retry later",+ status_code=429,+ )if response.status_code == 401:return DownloadResult(skip_reason="Authentication required - please login to access this article",diff --git a/src/local_deep_research/research_library/downloaders/semantic_scholar.py b/src/local_deep_research/research_library/downloaders/semantic_scholar.pyindex 4ec7c36c82..174ae6ad21 100644--- a/src/local_deep_research/research_library/downloaders/semantic_scholar.py+++ b/src/local_deep_research/research_library/downloaders/semantic_scholar.py@@ -74,11 +74,16 @@ class SemanticScholarDownloader(BaseDownloader):logger.info(f"Looking up Semantic Scholar paper: {paper_id}")# Get paper details from API to find PDF URL- pdf_url = self._get_pdf_url(paper_id)+ pdf_url, status_code = self._get_pdf_url(paper_id)if not pdf_url:return DownloadResult(- skip_reason="Not open access - subscription required"+ skip_reason=(+ f"Semantic Scholar API lookup failed (HTTP {status_code})"+ if status_code is not None and status_code != 200+ else "Could not resolve an open access PDF URL from Semantic Scholar"+ ),+ status_code=status_code,)# Download the PDF from the open access URL@@ -115,7 +120,9 @@ class SemanticScholarDownloader(BaseDownloader):match = re.search(r"/paper/(?:[^/]+/)?([a-f0-9]{40})", path)return match.group(1) if match else None- def _get_pdf_url(self, paper_id: str) -> Optional[str]:+ def _get_pdf_url(+ self, paper_id: str+ ) -> tuple[Optional[str], Optional[int]]:"""Get open access PDF URL from Semantic Scholar API.@@ -123,7 +130,9 @@ class SemanticScholarDownloader(BaseDownloader):paper_id: Semantic Scholar paper ID (hash)Returns:- PDF URL if available, None otherwise+ PDF URL if available and the API's HTTP status. Transport and+ response-decoding failures have no status. A missing PDF URL+ alone does not establish that the paper requires a subscription."""try:# Construct API request@@ -152,22 +161,22 @@ class SemanticScholarDownloader(BaseDownloader):f"Found open access PDF for paper {paper_id}: "f"{redact_url_for_log(str(pdf_url))}")- return str(pdf_url)+ return str(pdf_url), response.status_codelogger.info(f"No open access PDF available for paper {paper_id}")- return None+ return None, response.status_codeif response.status_code == 404:logger.warning(f"Paper not found in Semantic Scholar: {paper_id}")- return None+ return None, response.status_codelogger.warning(f"Semantic Scholar API error: {response.status_code}")- return None+ return None, response.status_code# Both handlers keep the scrubbed message rather than dropping the# API error -- the ``safe_msg`` shape the sibling ``openalex``@@ -188,7 +197,7 @@ class SemanticScholarDownloader(BaseDownloader):paper_id,safe_msg,)- return None+ return None, Noneexcept ValueError as exc:# JSON decode errors are expected runtime errorssafe_msg = scrub_error(exc, self.api_key)@@ -198,6 +207,6 @@ class SemanticScholarDownloader(BaseDownloader):paper_id,safe_msg,)- return None+ return None, None# Note: KeyError and TypeError are not caught - they indicate programming# bugs that should propagate for debuggingdiff --git a/src/local_deep_research/research_library/services/download_service.py b/src/local_deep_research/research_library/services/download_service.pyindex 564efb3b2a..b3794ef8fe 100644--- a/src/local_deep_research/research_library/services/download_service.py+++ b/src/local_deep_research/research_library/services/download_service.py@@ -2434,10 +2434,17 @@ class DownloadService:return False, f"egress_policy_denied:{reason}", Noneattempted_at = datetime.now(UTC)+ # The held-aside rate-limit result is declared before the try on+ # purpose: once a 429 is held, anything later in the try can raise (a+ # fallback downloader, or the failure-recording transaction), and while+ # no PDF content has been obtained the outer except must still+ # reinstate the 429 classification rather than let the exception text+ # replace it (#7588).+ pdf_content = None+ held_rate_limit: List[DownloadResult] = []try:# Use modular downloaders with detailed skip reasons.# Download occurs outside the database session (#6560).- pdf_content = Noneselected_downloader = Noneskip_reason = Nonestatus_code = None@@ -2463,7 +2470,7 @@ class DownloadService:if pdf_content is None:result, selected_downloader = self._download_pdf_with_fallback(- url+ url, held_rate_limit=held_rate_limit)if result.is_success and result.content:pdf_content = result.content@@ -3214,7 +3221,22 @@ class DownloadService:# substitute — its docstring says it scrubs credentials only.server_error = sanitize_error_for_client(str(e))skip_reason = _client_safe_download_message(e)- tracker.is_accessible = False+ result_status = None+ rate_limit_reinstated = (+ bool(held_rate_limit) and pdf_content is None+ )+ if rate_limit_reinstated:+ # A rate-limit result was already held from earlier in the+ # chain, and no PDF content had been obtained, when this+ # exception was raised (by a later downloader or by the+ # failure-recording transaction). The exception does not+ # replace it: the 429 stays the final classification and the+ # tracker keeps its accessible state, exactly as on the+ # non-exception rate-limit path (#7588).+ skip_reason = held_rate_limit[0].skip_reason+ result_status = held_rate_limit[0].status_code+ else:+ tracker.is_accessible = Falseif session is not None:safe_rollback(session, "_download_pdf")session.add(@@ -3239,7 +3261,7 @@ class DownloadService:.filter_by(url_hash=tracker.url_hash).first())- if db_tracker:+ if db_tracker and not rate_limit_reinstated:db_tracker.is_accessible = Falseerr_sess.add(DownloadAttempt(@@ -3259,7 +3281,7 @@ class DownloadService:log_exception_type("Failed to record failed attempt in database", exc)- return False, skip_reason, None+ return False, skip_reason, result_statusdef _extract_text_from_pdf(self, pdf_content: bytes) -> Optional[str]:"""@@ -4071,12 +4093,25 @@ class DownloadService:return None # Fall through to other methodsdef _download_pdf_with_fallback(- self, url: str+ self,+ url: str,+ held_rate_limit: Optional[List[DownloadResult]] = None,) -> Tuple[DownloadResult, Optional[BaseDownloader]]:- """Try matching PDF downloaders, preserving retryable failures."""+ """Try matching PDF downloaders, preserving retryable failures.++ A 429 does not stop the chain: rate limits are transient and+ host-scoped, so a downloader for a different host can still succeed.+ The first rate-limit result is held aside instead — if the chain+ exhausts without a success it is the final classification, and a+ later fallback failure never replaces it (#7588). When the caller+ passes ``held_rate_limit``, the held result is also appended there as+ soon as it is seen, so the caller can still reinstate it if a later+ downloader raises.+ """selected_downloader = Nonebest_permanent = Nonebest_temporary = None+ rate_limited = Noneclassifier = FailureClassifier()for downloader in self.downloaders:@@ -4091,7 +4126,20 @@ class DownloadService:selected_downloader = downloaderif result.is_success and result.content:return result, downloader- if result.skip_reason:+ if result.status_code == 429:+ if rate_limited is None:+ rate_limited = DownloadResult(+ skip_reason=result.skip_reason or "Rate limited (429)",+ status_code=result.status_code,+ )+ if held_rate_limit is not None:+ held_rate_limit.append(rate_limited)+ if result.skip_reason:+ logger.info(+ "Download skipped: {}",+ failure_reason_for_log(result.skip_reason),+ )+ elif result.skip_reason:failure = classifier.classify_failure("download_failed",status_code=result.status_code,@@ -4116,7 +4164,10 @@ class DownloadService:skip_reason="No compatible downloader available"), Nonereturn (- best_temporary or best_permanent or DownloadResult(),+ rate_limited+ or best_temporary+ or best_permanent+ or DownloadResult(),selected_downloader,)diff --git a/tests/library/download_management/test_failure_classifier.py b/tests/library/download_management/test_failure_classifier.pyindex 68a5794d2c..c427789d57 100644--- a/tests/library/download_management/test_failure_classifier.py+++ b/tests/library/download_management/test_failure_classifier.py@@ -2,6 +2,8 @@from datetime import timedelta, datetime, UTC+import pytest+class TestBaseFailure:"""Tests for BaseFailure class."""@@ -170,6 +172,61 @@ class TestRateLimitFailure:failure = RateLimitFailure("unknown-domain.com")assert failure.retry_after == timedelta(hours=1)+ def test_subdomains_use_the_registered_domain_cooldown(self):+ """Subdomains match their parent's registered cooldown.++ Revert-catcher: an exact-match lookup drops www.semanticscholar.org+ to the 1h default and the 4h assertion below fails.+ """+ from local_deep_research.library.download_management.failure_classifier import (+ RateLimitFailure,+ )++ assert RateLimitFailure(+ "www.semanticscholar.org"+ ).retry_after == timedelta(hours=4)+ assert RateLimitFailure(+ "api.semanticscholar.org"+ ).retry_after == timedelta(hours=4)+ assert RateLimitFailure("export.arxiv.org").retry_after == timedelta(+ hours=6+ )+ assert RateLimitFailure("www.biorxiv.org").retry_after == timedelta(+ hours=6+ )++ def test_sibling_domains_do_not_inherit_cooldowns(self):+ """Suffix matching must not accept evil-semanticscholar.org."""+ from local_deep_research.library.download_management.failure_classifier import (+ RateLimitFailure,+ )++ failure = RateLimitFailure("evil-semanticscholar.org")+ assert failure.retry_after == timedelta(hours=1)++ @pytest.mark.parametrize(+ "domain",+ [+ "export.arxiv.org:443",+ "ArXiv.org",+ "arxiv.org.",+ "EXPORT.ARXIV.ORG.:8443",+ ],+ )+ def test_authority_is_normalised_before_the_cooldown_lookup(self, domain):+ """Case, an explicit port and a trailing root dot keep arXiv's 6h.++ Revert-catcher: matching the raw authority drops every case here to+ the 1h default. The message keeps the domain as given.+ """+ from local_deep_research.library.download_management.failure_classifier import (+ RateLimitFailure,+ )++ failure = RateLimitFailure(domain)+ assert failure.retry_after == timedelta(hours=6)+ assert failure.domain == domain+def test_includes_details_in_message(self):"""Test that details are included in message."""from local_deep_research.library.download_management.failure_classifier import (@@ -205,6 +262,99 @@ class TestFailureClassifier:assert isinstance(result, PermanentFailure)assert result.error_type == "not_found"+ def test_journal_name_with_rate_limit_wording_stays_a_paywall(self):+ """PubMed builds "Article requires subscription to {journal}" from+ the API's journal title, so a journal name must not read as a rate+ limit.++ Revert-catcher: letting the rate-limit text match run ahead of the+ paywall wording returns `rate_limited` here.+ """+ from local_deep_research.library.download_management.failure_classifier import (+ FailureClassifier,+ )++ failure = FailureClassifier().classify_failure(+ "str",+ url="https://pubmed.ncbi.nlm.nih.gov/12345678",+ details="Article requires subscription to Journal of Rate Limiting",+ )++ assert failure.error_type == "paywall_or_login"+ assert failure.is_permanent()++ def test_rate_limit_wording_inside_a_url_is_not_a_rate_limit(self):+ """Revert-catcher: matching the wording against the raw details reads+ the "rate-limiting" path segment as the diagnostic and returns+ `rate_limited` instead of the generic `download_failed`."""+ from local_deep_research.library.download_management.failure_classifier import (+ FailureClassifier,+ )++ failure = FailureClassifier().classify_failure(+ "str",+ url="https://example.org/papers/rate-limiting-in-networks.pdf",+ details=(+ "Download failed for "+ "https://example.org/papers/rate-limiting-in-networks.pdf"+ ),+ )++ assert failure.error_type == "download_failed"++ def test_rate_limit_wording_does_not_override_a_non_429_status(self):+ """Revert-catcher: without the `status_code is None` guard the text+ match turns a 500 whose body mentions rate limiting into+ `rate_limited`."""+ from local_deep_research.library.download_management.failure_classifier import (+ FailureClassifier,+ )++ failure = FailureClassifier().classify_failure(+ "download_failed",+ status_code=500,+ url="https://example.org/paper.pdf",+ details="Upstream rate limiting service unavailable",+ )++ assert failure.error_type == "unknown_error"++ def test_rate_limit_wording_without_a_status_is_still_a_rate_limit(self):+ """The text-only path carries no status code; its 429 wording still+ classifies as a rate limit with the host's cooldown."""+ from local_deep_research.library.download_management.failure_classifier import (+ FailureClassifier,+ )++ failure = FailureClassifier().classify_failure(+ "str",+ url="https://www.biorxiv.org/content/paper.pdf",+ details="PDF extraction failed: Rate limited (429) - retry later",+ )++ assert failure.error_type == "rate_limited"+ assert failure.retry_after == timedelta(hours=6)++ def test_none_details_keeps_status_code_classification(self):+ """details=None must not crash the classifier.++ Revert-catcher: hoisting details.lower() above the status-code+ branches without the (details or "") guard raises AttributeError+ here; the pre-existing behaviour is a clean not_found.+ """+ from local_deep_research.library.download_management.failure_classifier import (+ FailureClassifier,+ PermanentFailure,+ )++ classifier = FailureClassifier()+ result = classifier.classify_failure(+ "http_error", status_code=404, details=None+ )++ assert isinstance(result, PermanentFailure)+ assert result.error_type == "not_found"+def test_403_returns_permanent_failure(self):"""Test that 403 status code returns permanent failure."""from local_deep_research.library.download_management.failure_classifier import (diff --git a/tests/research_library/downloaders/test_generic_downloader_fallback_contracts.py b/tests/research_library/downloaders/test_generic_downloader_fallback_contracts.pyindex 50018eb3cb..d372f33787 100644--- a/tests/research_library/downloaders/test_generic_downloader_fallback_contracts.py+++ b/tests/research_library/downloaders/test_generic_downloader_fallback_contracts.py@@ -9,6 +9,9 @@ import requestsfrom local_deep_research.library.download_management.failure_classifier import (FailureClassifier,)+from local_deep_research.library.download_management.retry_manager import (+ RetryManager,+)from local_deep_research.research_library.downloaders import basefrom local_deep_research.research_library.downloaders.base import ContentTypefrom local_deep_research.research_library.downloaders.generic import (@@ -168,6 +171,77 @@ def test_missing_fallback_does_not_override_original_diagnostic(assert failure.is_permanent() is permanent[email protected]("text_only", [False, True])+ "source,destination,error_type,permanent",+ [+ (+ "https://doi.org/10.1234/paper",+ "https://www.mdpi.com/article.pdf",+ "oa_bot_block",+ False,+ ),+ (+ "https://www.mdpi.com/article",+ "https://www.mdpi.com/article.pdf",+ "oa_bot_block",+ False,+ ),+ (+ "https://www.mdpi.com/article",+ "https://publisher.example/article.pdf",+ "forbidden",+ True,+ ),+ (+ "https://doi.org/10.1234/paper",+ "https://publisher.example/article.pdf",+ "forbidden",+ True,+ ),+ ],+)+def test_redirected_access_failure_uses_destination_classification(+ downloader,+ http_transport,+ mocker,+ source,+ destination,+ error_type,+ permanent,+ text_only,+):+ add_response, sent = http_transport+ add_response(source, status=302, location=destination)+ add_response(destination, status=403)+ # Isolate the diagnostic request while keeping its actual SafeSession+ # redirect handling, validation, and response URL intact.+ mocker.patch.object(base.BaseDownloader, "_download_pdf", return_value=None)++ result = downloader.download_with_result(source)++ assert not result.is_success+ assert result.status_code == 403+ assert sent == [source, destination]+ assert source not in result.skip_reason+ assert destination not in result.skip_reason+ details = result.skip_reason+ if text_only:+ details = f"PDF extraction failed: {details}"+ manager = RetryManager.__new__(RetryManager)+ manager.failure_classifier = FailureClassifier()+ manager.status_tracker = mocker.Mock()+ manager.record_attempt(+ 42,+ (False, details),+ status_code=None if text_only else result.status_code,+ url=source,+ )+ failure = manager.status_tracker.mark_failure.call_args.args[1]+ assert failure.error_type == error_type+ assert failure.is_permanent() is permanent++@pytest.mark.parametrize("method", ["download", "download_with_result"])@pytest.mark.parametrize("scheme", ["https", "http"])@pytest.mark.parametrize(diff --git a/tests/research_library/downloaders/test_semantic_scholar_coverage.py b/tests/research_library/downloaders/test_semantic_scholar_coverage.pyindex 9e83b8c54a..71486a72e2 100644--- a/tests/research_library/downloaders/test_semantic_scholar_coverage.py+++ b/tests/research_library/downloaders/test_semantic_scholar_coverage.py@@ -114,7 +114,7 @@ class TestGetPdfUrl:call_kwargs = raw_downloader.session.get.call_argsassert call_kwargs.kwargs["headers"]["x-api-key"] == "my-secret-key"- assert result == "https://example.com/paper.pdf"+ assert result == ("https://example.com/paper.pdf", 200)def test_no_api_key_sends_empty_headers(self, raw_downloader):"""When api_key is None, no x-api-key header should be sent."""@@ -138,7 +138,7 @@ class TestGetPdfUrl:raw_downloader.session.get.return_value = mock_respresult = raw_downloader._get_pdf_url("someid")- assert result is None+ assert result == (None, None)def test_request_exception_returns_none(self, raw_downloader):"""requests.RequestException should be caught and return None."""@@ -147,7 +147,7 @@ class TestGetPdfUrl:)result = raw_downloader._get_pdf_url("someid")- assert result is None+ assert result == (None, None)def test_open_access_pdf_none_returns_none(self, raw_downloader):"""openAccessPdf=None in API response should return None."""@@ -157,7 +157,7 @@ class TestGetPdfUrl:raw_downloader.session.get.return_value = mock_respresult = raw_downloader._get_pdf_url("someid")- assert result is None+ assert result == (None, 200)def test_open_access_pdf_not_dict_returns_none(self, raw_downloader):"""openAccessPdf that is not a dict should return None."""@@ -167,7 +167,7 @@ class TestGetPdfUrl:raw_downloader.session.get.return_value = mock_respresult = raw_downloader._get_pdf_url("someid")- assert result is None+ assert result == (None, 200)# =====================================================================@@ -191,7 +191,7 @@ class TestDownloadWithResultPdfFailure:patch.object(raw_downloader,"_get_pdf_url",- return_value="https://example.com/paper.pdf",+ return_value=("https://example.com/paper.pdf", 200),),patch.object(SemanticScholarDownloader.__bases__[0],diff --git a/tests/research_library/downloaders/test_semantic_scholar_downloader.py b/tests/research_library/downloaders/test_semantic_scholar_downloader.pyindex c1ec29351f..01646e8d86 100644--- a/tests/research_library/downloaders/test_semantic_scholar_downloader.py+++ b/tests/research_library/downloaders/test_semantic_scholar_downloader.py@@ -83,7 +83,7 @@ class TestSemanticScholarDownloaderGetPdfUrl:):pdf_url = downloader._get_pdf_url("abc123")- assert pdf_url is None+ assert pdf_url == (None, 404)def test_handles_rate_limiting(self):"""Should handle rate limiting (429) gracefully."""@@ -100,7 +100,7 @@ class TestSemanticScholarDownloaderGetPdfUrl:):pdf_url = downloader._get_pdf_url("abc123")- assert pdf_url is None+ assert pdf_url == (None, 429)class TestSemanticScholarDownloaderDownload:@@ -110,7 +110,7 @@ class TestSemanticScholarDownloaderDownload:"""Should handle case when no PDF is available."""downloader = SemanticScholarDownloader()- with patch.object(downloader, "_get_pdf_url", return_value=None):+ with patch.object(downloader, "_get_pdf_url", return_value=(None, 200)):result = downloader.download("https://www.semanticscholar.org/paper/abc123")@@ -125,7 +125,7 @@ class TestSemanticScholarDownloaderDownloadWithResult:"""Should return skip_reason when no PDF available."""downloader = SemanticScholarDownloader()- with patch.object(downloader, "_get_pdf_url", return_value=None):+ with patch.object(downloader, "_get_pdf_url", return_value=(None, 200)):result = downloader.download_with_result("https://www.semanticscholar.org/paper/abc123")diff --git a/tests/research_library/downloaders/test_semantic_scholar_logging_sinks.py b/tests/research_library/downloaders/test_semantic_scholar_logging_sinks.pyindex 8ed8a4594e..a4826b6f4c 100644--- a/tests/research_library/downloaders/test_semantic_scholar_logging_sinks.py+++ b/tests/research_library/downloaders/test_semantic_scholar_logging_sinks.py@@ -42,13 +42,13 @@ def test_api_pdf_discovery_logs_only_origin(rendered_log):downloader = SemanticScholarDownloader()downloader.session.get = Mock(return_value=response)- assert downloader._get_pdf_url(_PAPER_ID) == _PDF_URL+ assert downloader._get_pdf_url(_PAPER_ID) == (_PDF_URL, 200)_assert_redacted(rendered_log)def test_pdf_download_start_logs_only_origin(rendered_log):downloader = SemanticScholarDownloader()- downloader._get_pdf_url = Mock(return_value=_PDF_URL)+ downloader._get_pdf_url = Mock(return_value=(_PDF_URL, 200))paper_url = f"https://www.semanticscholar.org/paper/{_PAPER_ID}"with patch.object(BaseDownloader, "_download_pdf", return_value=b"%PDF"):@@ -87,7 +87,7 @@ def test_api_request_failure_does_not_attach_exception(rendered_log):downloader.session.get = Mock(side_effect=requests.RequestException(f"failed: {_PDF_URL}"))- assert downloader._get_pdf_url(_PAPER_ID) is None+ assert downloader._get_pdf_url(_PAPER_ID) == (None, None)finally:logger.remove(record_sink_id)@@ -104,7 +104,7 @@ def test_api_parse_failure_does_not_attach_exception(rendered_log):response.json.side_effect = ValueError(f"bad json: {_PDF_URL}")downloader = SemanticScholarDownloader()downloader.session.get = Mock(return_value=response)- assert downloader._get_pdf_url(_PAPER_ID) is None+ assert downloader._get_pdf_url(_PAPER_ID) == (None, None)finally:logger.remove(record_sink_id)diff --git a/tests/research_library/downloaders/test_transient_access_failures.py b/tests/research_library/downloaders/test_transient_access_failures.pynew file mode 100644index 0000000000..48cfe41d40--- /dev/null+++ b/tests/research_library/downloaders/test_transient_access_failures.py@@ -0,0 +1,297 @@+"""Download access failures retain their meaning through retry recording."""++from datetime import timedelta+from unittest.mock import MagicMock, Mock, patch++import pytest+import requests++from local_deep_research.library.download_management.failure_classifier import (+ FailureClassifier,+)+from local_deep_research.library.download_management.retry_manager import (+ RetryManager,+)+from local_deep_research.research_library.downloaders.base import BaseDownloader+from local_deep_research.research_library.downloaders.generic import (+ GenericDownloader,+)+from local_deep_research.research_library.downloaders.semantic_scholar import (+ SemanticScholarDownloader,+)++PAPER_URL = "https://www.semanticscholar.org/paper/" + "a" * 40+++def record_failure(result, url, *, text_only=False):+ manager = RetryManager.__new__(RetryManager)+ manager.failure_classifier = FailureClassifier()+ manager.status_tracker = Mock()+ reason = result.skip_reason+ if text_only:+ reason = f"PDF extraction failed: {reason}"+ manager.record_attempt(+ 1,+ (False, reason),+ status_code=None if text_only else result.status_code,+ url=url,+ )+ return manager.status_tracker.mark_failure.call_args.args[1]++[email protected]("text_only", [False, True])+def test_semantic_scholar_rate_limit_remains_retryable(text_only):+ with SemanticScholarDownloader() as downloader:+ downloader.session.get = Mock(return_value=Mock(status_code=429))+ result = downloader.download_with_result(PAPER_URL)++ assert not result.is_success+ assert result.status_code == 429+ assert "subscription" not in result.skip_reason.lower()+ failure = record_failure(result, PAPER_URL, text_only=text_only)+ assert failure.error_type == "rate_limited"+ assert not failure.is_permanent()+ assert failure.retry_after >= timedelta(hours=1)++[email protected]("status", [200, 500, 503])+def test_missing_semantic_scholar_pdf_is_not_evidence_of_a_paywall(status):+ response = Mock(status_code=status)+ response.json.return_value = {"openAccessPdf": None}+ with SemanticScholarDownloader() as downloader:+ downloader.session.get = Mock(return_value=response)+ result = downloader.download_with_result(PAPER_URL)++ assert not result.is_success+ assert "subscription" not in result.skip_reason.lower()+ assert not record_failure(result, PAPER_URL).is_permanent()+++ "error", [requests.Timeout("timeout"), requests.ConnectionError("offline")]+)+def test_semantic_scholar_lookup_error_is_retryable(error):+ with SemanticScholarDownloader() as downloader:+ downloader.session.get = Mock(side_effect=error)+ result = downloader.download_with_result(PAPER_URL)++ assert not result.is_success+ assert "subscription" not in result.skip_reason.lower()+ assert not record_failure(result, PAPER_URL).is_permanent()++[email protected]("text_only", [False, True])+ "host",+ [+ "www.mdpi.com",+ "journals.plos.org",+ "bmcpublichealth.biomedcentral.com",+ "www.frontiersin.org",+ "arxiv.org",+ "www.biorxiv.org",+ "www.medrxiv.org",+ "pmc.ncbi.nlm.nih.gov",+ "europepmc.org",+ ],+)+def test_open_access_403_remains_retryable(host, text_only):+ url = f"https://{host}/article.pdf"+ response = MagicMock(status_code=403)+ response.__enter__.return_value = response+ with GenericDownloader() as downloader:+ downloader.session.get = Mock(return_value=response)+ with patch.object(BaseDownloader, "_download_pdf", return_value=None):+ result = downloader.download_with_result(url)++ assert not result.is_success+ assert result.status_code == 403+ assert "subscription" not in result.skip_reason.lower()+ failure = record_failure(result, url, text_only=text_only)+ assert failure.error_type == "oa_bot_block"+ assert not failure.is_permanent()+ assert failure.retry_after >= timedelta(hours=1)++[email protected]("status_code", [403, None])+def test_legacy_open_access_403_message_uses_retryable_classification(+ status_code,+):+ failure = FailureClassifier().classify_failure(+ "download_failed",+ status_code=status_code,+ url="https://www.mdpi.com/article",+ details=(+ "PDF extraction failed: Access denied (403) - article requires "+ "subscription or special permissions"+ ),+ )++ assert failure.error_type == "oa_bot_block"+ assert not failure.is_permanent()+++ "url",+ [+ "https://publisher.example/article",+ "https://mdpi.com.example.org/article",+ "https://example.org/mdpi.com/article",+ "https://[invalid/article",+ "",+ ],+)+def test_other_forbidden_sources_keep_existing_classification(url):+ failure = FailureClassifier().classify_failure(+ "download_failed", status_code=403, url=url+ )+ assert failure.error_type == "forbidden"+ assert failure.is_permanent()+++def test_confirmed_subscription_stays_permanent():+ failure = FailureClassifier().classify_failure(+ "download_failed",+ url="https://publisher.example/article",+ details="Article requires subscription",+ )+ assert failure.error_type == "paywall_or_login"+ assert failure.is_permanent()+++def test_generic_downloader_rate_limit_diagnostic_is_explicit():+ """GenericDownloader names the rate limit instead of a generic error.++ Revert-catcher: removing generic.py's 429 branch restores the+ "Unable to access article - server returned error code 429" fall-through+ and the skip_reason equality below fails.+ """+ url = "https://publisher.example/article.pdf"+ response = MagicMock(status_code=429)+ response.__enter__.return_value = response+ with GenericDownloader() as downloader:+ downloader.session.get = Mock(return_value=response)+ with patch.object(BaseDownloader, "_download_pdf", return_value=None):+ result = downloader.download_with_result(url)++ assert not result.is_success+ assert result.skip_reason == "Rate limited (429) - retry later"+ assert result.status_code == 429+ failure = record_failure(result, url)+ assert failure.error_type == "rate_limited"+ assert not failure.is_permanent()++[email protected]("text_only", [False, True])+def test_semantic_scholar_403_access_block_remains_retryable(text_only):+ """A 403 from the Semantic Scholar API is a bot block, not a paywall.++ Revert-catcher: dropping semanticscholar.org from _OPEN_ACCESS_HOSTS+ reclassifies both paths to permanent `forbidden` and the error_type+ assertion below fails.+ """+ with SemanticScholarDownloader() as downloader:+ downloader.session.get = Mock(return_value=Mock(status_code=403))+ result = downloader.download_with_result(PAPER_URL)++ assert not result.is_success+ assert result.status_code == 403+ assert "subscription" not in result.skip_reason.lower()+ failure = record_failure(result, PAPER_URL, text_only=text_only)+ assert failure.error_type == "oa_bot_block"+ assert not failure.is_permanent()+ assert failure.retry_after >= timedelta(hours=1)+++def test_fallback_403_on_semantic_scholar_host_is_an_access_block():+ """The fallback GenericDownloader's 403 on the Semantic Scholar host+ classifies as a transient access block too.++ The reason comes from the real downloader rather than a literal, so it is+ always one the code emits. Revert-catcher: without the host in+ _OPEN_ACCESS_HOSTS, access_denied_reason() returns the destination-+ forbidden reason, which classifies as permanent `forbidden`, and the+ error_type assertion below fails.+ """+ response = MagicMock(status_code=403)+ response.__enter__.return_value = response+ with GenericDownloader() as downloader:+ downloader.session.get = Mock(return_value=response)+ with patch.object(BaseDownloader, "_download_pdf", return_value=None):+ result = downloader.download_with_result(PAPER_URL)++ assert not result.is_success+ assert result.status_code == 403+ failure = record_failure(result, PAPER_URL)+ assert failure.error_type == "oa_bot_block"+ assert not failure.is_permanent()++[email protected]("status_code", [403, None])+def test_open_access_bare_403_forbidden_text_is_retryable(status_code):+ """Bare "403 Forbidden" diagnostics on public hosts are access blocks.++ Revert-catcher: without the `403 forbidden` alternative in the rescue+ regex the text-only path falls through to permanent `forbidden`.+ """+ failure = FailureClassifier().classify_failure(+ "download_failed",+ status_code=status_code,+ url="https://www.mdpi.com/article",+ details="PDF extraction failed: 403 Forbidden",+ )++ assert failure.error_type == "oa_bot_block"+ assert not failure.is_permanent()++[email protected]("status_code", [403, None])+def test_recaptcha_challenge_keeps_its_three_day_cooldown(status_code):+ """A named anti-bot challenge outranks the OA-403 access-block rescue.++ Revert-catcher: the bare "403 Forbidden" text matches the rescue regex,+ and without recaptcha precedence the rescue shortens the deliberate+ 3-day recaptcha cooldown to the 1h `oa_bot_block` window.+ """+ failure = FailureClassifier().classify_failure(+ "download_failed",+ status_code=status_code,+ url="https://arxiv.org/abs/2301.12345",+ details="arXiv 403 Forbidden: recaptcha challenge",+ )++ assert failure.error_type == "recaptcha_protection"+ assert not failure.is_permanent()+ assert failure.retry_after == timedelta(days=3)+++def test_recaptcha_wording_beats_the_access_block_rescue_on_open_access_hosts():+ """Revert-catcher: without the rescue-side recaptcha check this becomes+ the 1h `oa_bot_block` classification instead of the 3-day cooldown."""+ failure = FailureClassifier().classify_failure(+ "download_failed",+ status_code=403,+ url="https://www.mdpi.com/article",+ details="Access denied (403) - recaptcha challenge",+ )++ assert failure.error_type == "recaptcha_protection"+ assert failure.retry_after == timedelta(days=3)+++def test_recaptcha_wording_beats_rate_limit_wording_on_arxiv():+ """Rate-limit wording must not shorten arXiv's 3-day reCAPTCHA cooldown.++ Revert-catcher: without the `not recaptcha_detected` guard on the+ rate-limit text check, "rate limited" matches first and this returns+ `rate_limited` (6h for arxiv.org) before the arXiv reCAPTCHA branch is+ reached, so both assertions below fail.+ """+ failure = FailureClassifier().classify_failure(+ "str",+ url="https://arxiv.org/abs/2301.12345",+ details="arXiv rate limited: recaptcha challenge",+ )++ assert failure.error_type == "recaptcha_protection"+ assert failure.retry_after == timedelta(days=3)diff --git a/tests/research_library/services/test_download_service_strategy_coverage.py b/tests/research_library/services/test_download_service_strategy_coverage.pyindex f6e8f8bf86..fead19ece0 100644--- a/tests/research_library/services/test_download_service_strategy_coverage.py+++ b/tests/research_library/services/test_download_service_strategy_coverage.py@@ -265,6 +265,299 @@ class TestDownloadResourceArxivStrategy:# ---------------------------------------------------------------------------+def test_semantic_scholar_rate_limit_is_not_overwritten_by_fallback(svc):+ """A later fallback failure never replaces the rate-limit result.++ Revert-catcher: reinstating `if result.status_code == 429: break` in+ _download_pdf_with_fallback's loop stops the chain before the fallback+ and the `fallback.download_with_result.assert_called_once()` below+ fails. Letting the fallback's failure replace the held `rate_limited`+ result as the return value fails the status and reason assertions. The+ rate-limit result must survive the chain as the final classification+ (status_code == 429 and "HTTP 429" in reason) while the chain still runs.+ """+ from local_deep_research.research_library.downloaders.base import (+ DownloadResult,+ )+ from local_deep_research.research_library.downloaders.generic import (+ GenericDownloader,+ )+ from local_deep_research.research_library.downloaders.semantic_scholar import (+ SemanticScholarDownloader,+ )++ fallback = MagicMock(spec=GenericDownloader)+ fallback.can_handle.return_value = True+ fallback.download_with_result.return_value = DownloadResult(+ skip_reason="Access denied (403)", status_code=403+ )+ resource = MagicMock()+ resource.url = "https://www.semanticscholar.org/paper/" + "a" * 40+ resource.document_id = None+ tracker = MagicMock()+ tracker.url_hash = "rate-limited-paper"+ tracker.download_attempts.count.return_value = 0+ session = MagicMock()++ with SemanticScholarDownloader() as downloader:+ downloader.session.get = MagicMock(+ return_value=MagicMock(status_code=429)+ )+ svc.downloaders = [downloader, fallback]+ success, reason, status_code = svc._download_pdf(+ resource, tracker, session+ )++ assert success is False+ assert status_code == 429+ assert "HTTP 429" in reason+ fallback.download_with_result.assert_called_once()+ session.commit.assert_called_once()+++def test_raising_fallback_does_not_discard_the_held_rate_limit(svc):+ """A fallback downloader that RAISES must not replace the held 429.++ Revert-catcher: without the held-429 reinstatement in _download_pdf's+ except block (fed by `held_rate_limit`, which+ _download_pdf_with_fallback fills as soon as it sees the 429) the+ outer except returns ("download_error:ValueError", None) and both the+ exact-reason and `status_code == 429` assertions below fail. The held+ rate-limit result is the final classification even when the fallback's+ failure is an exception rather than a returned result.+ """+ from local_deep_research.research_library.downloaders.generic import (+ GenericDownloader,+ )+ from local_deep_research.research_library.downloaders.semantic_scholar import (+ SemanticScholarDownloader,+ )++ fallback = MagicMock(spec=GenericDownloader)+ fallback.can_handle.return_value = True+ fallback.download_with_result.side_effect = ValueError("boom")+ resource = MagicMock()+ resource.url = "https://www.semanticscholar.org/paper/" + "a" * 40+ resource.document_id = None+ tracker = MagicMock()+ tracker.url_hash = "raising-fallback"+ tracker.download_attempts.count.return_value = 0+ session = MagicMock()++ with SemanticScholarDownloader() as downloader:+ downloader.session.get = MagicMock(+ return_value=MagicMock(status_code=429)+ )+ svc.downloaders = [downloader, fallback]+ success, reason, status_code = svc._download_pdf(+ resource, tracker, session+ )++ assert success is False+ assert reason == "Semantic Scholar API lookup failed (HTTP 429)"+ assert status_code == 429+ fallback.download_with_result.assert_called_once()+++def test_success_after_a_rate_limit_is_not_discarded(svc):+ """A 429 from one downloader must not hide a later downloader's success.++ Revert-catcher: reinstating `if result.status_code == 429: break` in+ _download_pdf_with_fallback's loop means the fallback never runs; both+ `fallback.download_with_result.assert_called_once()` and `success is True`+ fail. Returning the held rate-limit result ahead of a later success+ (instead of returning the success straight from the loop) fails the+ `success is True` and `status_code == 200` assertions. The held 429 is+ reinstated only in _download_pdf's except block, and only while no PDF+ content was obtained; that `pdf_content is None` guard is pinned by+ test_persistence_error_after_a_success_is_not_relabelled_a_rate_limit.+ """+ from local_deep_research.research_library.downloaders.base import (+ DownloadResult,+ )+ from local_deep_research.research_library.downloaders.generic import (+ GenericDownloader,+ )+ from local_deep_research.research_library.downloaders.semantic_scholar import (+ SemanticScholarDownloader,+ )++ svc.settings.get_setting = lambda key, default=None: {+ "research_library.pdf_storage_mode": "none",+ "research_library.max_pdf_size_mb": 50,+ }.get(key, default)+ fallback = MagicMock(spec=GenericDownloader)+ fallback.can_handle.return_value = True+ fallback.download_with_result.return_value = DownloadResult(+ content=b"%PDF-1.4 bytes", is_success=True, status_code=200+ )+ resource = MagicMock()+ resource.url = "https://www.semanticscholar.org/paper/" + "a" * 40+ resource.document_id = None+ tracker = MagicMock()+ tracker.url_hash = "rate-limited-then-success"+ tracker.download_attempts.count.return_value = 0+ session = MagicMock()++ with SemanticScholarDownloader() as downloader:+ downloader.session.get = MagicMock(+ return_value=MagicMock(status_code=429)+ )+ svc.downloaders = [downloader, fallback]+ with patch(f"{MODULE}.get_document_for_resource", return_value=None):+ success, reason, status_code = svc._download_pdf(+ resource, tracker, session+ )++ assert success is True+ assert reason is None+ assert status_code == 200+ fallback.download_with_result.assert_called_once()+++def test_persistence_error_after_a_success_is_not_relabelled_a_rate_limit(+ svc,+):+ """A 429, then a fallback success, then a persistence error: the error+ is the failure, not the 429 held from before the success.++ Revert-catcher: dropping `and pdf_content is None` from+ `rate_limit_reinstated` in _download_pdf's except block reinstates the+ held ("Semantic Scholar API lookup failed (HTTP 429)", 429) pair and+ skips `tracker.is_accessible = False`, so the reason, status and+ tracker assertions below all fail.+ """+ from local_deep_research.research_library.downloaders.base import (+ DownloadResult,+ )+ from local_deep_research.research_library.downloaders.generic import (+ GenericDownloader,+ )+ from local_deep_research.research_library.downloaders.semantic_scholar import (+ SemanticScholarDownloader,+ )++ svc.settings.get_setting = lambda key, default=None: {+ "research_library.pdf_storage_mode": "none",+ "research_library.max_pdf_size_mb": 50,+ }.get(key, default)+ fallback = MagicMock(spec=GenericDownloader)+ fallback.can_handle.return_value = True+ fallback.download_with_result.return_value = DownloadResult(+ content=b"%PDF-1.4 bytes", is_success=True, status_code=200+ )+ resource = MagicMock()+ resource.url = "https://www.semanticscholar.org/paper/" + "a" * 40+ resource.document_id = None+ tracker = MagicMock()+ tracker.url_hash = "rate-limited-then-persistence-error"+ tracker.download_attempts.count.return_value = 0+ session = MagicMock()++ with SemanticScholarDownloader() as downloader:+ downloader.session.get = MagicMock(+ return_value=MagicMock(status_code=429)+ )+ svc.downloaders = [downloader, fallback]+ with patch(+ f"{MODULE}.get_document_for_resource",+ side_effect=RuntimeError("persistence failed"),+ ):+ success, reason, status_code = svc._download_pdf(+ resource, tracker, session+ )++ assert success is False+ assert reason == "download_error:RuntimeError"+ assert status_code is None+ assert tracker.is_accessible is False+ fallback.download_with_result.assert_called_once()+++def test_rate_limit_result_without_a_diagnostic_still_wins(svc):+ """A 429 result carrying no skip_reason must not freeze the previous+ downloader's diagnostic as the recorded failure.++ Revert-catcher: with the stale-pair leak the final pair is the earlier+ ("Access denied (403)", 403) and the `reason == "Rate limited (429)"`+ assertion fails.+ """+ from local_deep_research.research_library.downloaders.base import (+ DownloadResult,+ )++ first = MagicMock()+ first.can_handle.return_value = True+ first.download_with_result.return_value = DownloadResult(+ skip_reason="Access denied (403)", status_code=403+ )+ second = MagicMock()+ second.can_handle.return_value = True+ second.download_with_result.return_value = DownloadResult(+ skip_reason="", status_code=429+ )+ resource = MagicMock()+ resource.url = "https://www.semanticscholar.org/paper/" + "a" * 40+ resource.document_id = None+ tracker = MagicMock()+ tracker.url_hash = "rate-limit-without-diagnostic"+ tracker.download_attempts.count.return_value = 0+ session = MagicMock()++ svc.downloaders = [first, second]+ success, reason, status_code = svc._download_pdf(resource, tracker, session)++ assert success is False+ assert reason == "Rate limited (429)"+ assert status_code == 429+++def test_first_rate_limit_in_the_chain_is_the_recorded_one(svc):+ """Two 429s with distinct reasons: the first one seen is held and returned.++ Revert-catcher: switching _download_pdf_with_fallback to last-429-wins+ (dropping the `if rate_limited is None` guard, or appending every 429 to+ `held_rate_limit`) returns or holds the second reason, and the reason+ and held-list assertions below fail.+ """+ from local_deep_research.research_library.downloaders.base import (+ DownloadResult,+ )+ from local_deep_research.research_library.downloaders.generic import (+ GenericDownloader,+ )++ first = MagicMock()+ first.can_handle.return_value = True+ first.download_with_result.return_value = DownloadResult(+ skip_reason="First host rate limited (429)", status_code=429+ )+ second = MagicMock()+ second.can_handle.return_value = True+ second.download_with_result.return_value = DownloadResult(+ skip_reason="Second host rate limited (429)", status_code=429+ )+ fallback = MagicMock(spec=GenericDownloader)+ fallback.can_handle.return_value = True+ fallback.download_with_result.return_value = DownloadResult(+ skip_reason="Access denied (403)", status_code=403+ )+ held = []++ svc.downloaders = [first, second, fallback]+ result, selected = svc._download_pdf_with_fallback(+ "https://www.semanticscholar.org/paper/" + "a" * 40,+ held_rate_limit=held,+ )++ assert result.skip_reason == "First host rate limited (429)"+ assert result.status_code == 429+ assert [r.skip_reason for r in held] == ["First host rate limited (429)"]+ assert selected is fallback+ second.download_with_result.assert_called_once()+ fallback.download_with_result.assert_called_once()++class TestDownloadResourcePubmedStrategy:"""_download_pdf uses PubMedDownloader for pubmed.ncbi.nlm.nih.gov URLs."""