~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): stop reporting a paywall for unrelated download failures (#6415)
Lukas Buckda90762fed79
diff --git a/changelog.d/6412.bugfix.md b/changelog.d/6412.bugfix.mdnew file mode 100644index 0000000000..3f19c8fa3c--- /dev/null+++ b/changelog.d/6412.bugfix.md@@ -0,0 +1,18 @@+Stopped reporting a paywall for PubMed/PMC text extractions that failed for+other reasons. `PubMedDownloader.download_with_result` returned+"Full text not available - may require subscription" whenever+`_download_text` gave up — which it also does for an unparseable URL, a+Europe PMC API error, an unreachable PDF, or a PDF whose text could not be+extracted. The reason is user-visible through the content fetcher and, as+failure `details`, the word "subscription" alone makes+`FailureClassifier` declare a permanent `paywall_or_login` failure. A+genuine paywall is still reported from the PDF path, where Europe PMC's+`isOpenAccess` flag provides the evidence.++Fixed the download retry-filter status counters always reporting zero.+`RetryManager._get_resource_status` matched `"permanently failed"` and+`"cooldown"` case-sensitively, while every reason+`ResourceStatusTracker.can_retry` produces is capitalized, so every+non-retryable resource was bucketed as "unavailable" and+`permanently_failed_count` / `temporarily_failed_count` stayed at 0 however+many resources were in either state.diff --git a/src/local_deep_research/library/download_management/retry_manager.py b/src/local_deep_research/library/download_management/retry_manager.pyindex 6947c0a355..0c2a721d89 100644--- a/src/local_deep_research/library/download_management/retry_manager.py+++ b/src/local_deep_research/library/download_management/retry_manager.py@@ -225,9 +225,18 @@ class RetryManager:) -> str:"""Get status string based on retry decision"""if not can_retry:- if reason and "permanently failed" in reason:+ # Every reason `ResourceStatusTracker.can_retry` produces starts+ # with a capital ("Permanently failed: ...", "Cooldown active,+ # ..."), so these must match case-insensitively — as the cooldown+ # wait estimate in `filter_resources` already does. Matching+ # lowercase only sent all of them to "unavailable", leaving+ # `FilterSummary.permanently_failed_count` and+ # `temporarily_failed_count` at zero however many resources were+ # in either state.+ reason_lower = (reason or "").lower()+ if "permanently failed" in reason_lower:return "permanently_failed"- if reason and "cooldown" in reason:+ if "cooldown" in reason_lower:return "temporarily_failed"return "unavailable"return "available"diff --git a/src/local_deep_research/research_library/downloaders/pubmed.py b/src/local_deep_research/research_library/downloaders/pubmed.pyindex a35d100e2a..55fa37730f 100644--- a/src/local_deep_research/research_library/downloaders/pubmed.py+++ b/src/local_deep_research/research_library/downloaders/pubmed.py@@ -76,8 +76,16 @@ class PubMedDownloader(BaseDownloader):content = self._download_text(url)if content:return DownloadResult(content=content, is_success=True)+ # `_download_text` collapses every failure into None: an+ # unparseable URL, a Europe PMC API error, an unreachable PDF, a+ # PDF whose text could not be extracted. Naming a subscription+ # here asserts a paywall for all of them, and the word alone is+ # what `FailureClassifier.classify_failure` matches on to declare+ # a permanent `paywall_or_login` failure. A genuine paywall is+ # established by Europe PMC's `isOpenAccess` flag, which the PDF+ # path checks and reports on its own.return DownloadResult(- skip_reason="Full text not available - may require subscription"+ skip_reason="Full text not available from the PubMed/PMC APIs")# Try to download PDF with detailed trackingreturn self._download_pdf_with_result(url)diff --git a/tests/library/download_management/test_retry_status_reason_agreement.py b/tests/library/download_management/test_retry_status_reason_agreement.pynew file mode 100644index 0000000000..af90af74c4--- /dev/null+++ b/tests/library/download_management/test_retry_status_reason_agreement.py@@ -0,0 +1,149 @@+"""The retry status buckets must agree with the reasons can_retry produces.++``RetryManager._get_resource_status`` classifies a resource by substring-matching+the reason string that ``ResourceStatusTracker.can_retry`` returned. The two+sides drifted: every reason ``can_retry`` builds is capitalized, and the match+was lowercase-only, so every non-retryable resource fell through to+``"unavailable"`` and ``FilterSummary.permanently_failed_count`` /+``temporarily_failed_count`` stayed at zero regardless of state (#6412).++The reason strings here are not written out by hand — they are taken from+``can_retry`` itself, driven through each state, so a reworded reason on either+side fails this test instead of silently emptying a counter again.+"""++from datetime import datetime, timedelta, UTC+from unittest.mock import MagicMock, patch++import pytest++from local_deep_research.library.download_management.retry_manager import (+ RetryManager,+)+from local_deep_research.library.download_management.status_tracker import (+ MAX_TOTAL_RETRIES,+ ResourceStatusTracker,+)+++def _status_record(**fields):+ """A ResourceDownloadStatus stand-in with retry-neutral defaults."""+ record = MagicMock()+ record.status = "failed"+ record.failure_message = None+ record.failure_type = None+ record.retry_after_timestamp = None+ record.today_retry_count = 0+ record.total_retry_count = 0+ record.last_attempt_at = datetime.now(UTC)+ for name, value in fields.items():+ setattr(record, name, value)+ return record+++def _reason_for(status_record):+ """Return the reason a real can_retry() produces for this stored state."""+ with (+ patch(+ "local_deep_research.database.encrypted_db.db_manager"+ ) as mock_db_manager,+ patch("local_deep_research.library.download_management.models.Base"),+ ):+ mock_db_manager.open_user_database.return_value = MagicMock()+ tracker = ResourceStatusTracker("test_user")++ session = MagicMock()+ session.__enter__ = MagicMock(return_value=session)+ session.__exit__ = MagicMock(return_value=False)+ session.query.return_value.filter_by.return_value.first.return_value = (+ status_record+ )++ with patch.object(tracker, "_get_session", return_value=session):+ can_retry, reason = tracker.can_retry(1)++ assert can_retry is False, (+ f"the fixture must describe a non-retryable resource, got {reason!r}"+ )+ return reason+++# Each case: the stored state, and the bucket its reason has to land in.+CASES = [+ pytest.param(+ {"status": "permanently_failed", "failure_message": "File not found"},+ "permanently_failed",+ id="permanent-failure",+ ),+ pytest.param(+ {+ "status": "temporarily_failed",+ "retry_after_timestamp": datetime.now(UTC) + timedelta(hours=2),+ },+ "temporarily_failed",+ id="cooldown-active",+ ),+ pytest.param(+ {"total_retry_count": MAX_TOTAL_RETRIES},+ "permanently_failed",+ id="total-retry-limit",+ ),+ pytest.param(+ {"today_retry_count": 3},+ "unavailable",+ id="daily-retry-limit",+ ),+]+++def _manager():+ with (+ patch(+ "local_deep_research.library.download_management.retry_manager.ResourceStatusTracker"+ ) as tracker_cls,+ patch(+ "local_deep_research.library.download_management.retry_manager.FailureClassifier"+ ),+ ):+ tracker_cls.return_value = MagicMock()+ return RetryManager("test_user")++[email protected]("stored,expected_status", CASES)+def test_status_matches_the_reason_can_retry_actually_returns(+ stored, expected_status+):+ reason = _reason_for(_status_record(**stored))++ assert _manager()._get_resource_status(False, reason) == expected_status, (+ f"can_retry returned {reason!r}"+ )++[email protected]("stored,expected_status", CASES)+def test_summary_counts_the_state_the_resource_is_really_in(+ stored, expected_status+):+ """The counters the queue-all response reports must follow the same reason."""+ reason = _reason_for(_status_record(**stored))+ manager = _manager()+ manager.status_tracker.can_retry.return_value = (False, reason)++ results = manager.filter_resources([MagicMock(id=1)])+ summary = manager.get_filter_summary(results)++ counts = {+ "permanently_failed": summary.permanently_failed_count,+ "temporarily_failed": summary.temporarily_failed_count,+ "unavailable": summary.available_count,+ }+ assert summary.total_count == 1+ assert summary.downloadable_count == 0+ assert counts.pop(expected_status) == 1, (+ f"{expected_status} was not counted for reason {reason!r}"+ )+ assert set(counts.values()) == {0}, f"double-counted: {counts}"+++def test_a_retryable_resource_is_still_available():+ assert _manager()._get_resource_status(True, None) == "available"diff --git a/tests/research_library/downloaders/test_pubmed.py b/tests/research_library/downloaders/test_pubmed.pyindex 183ee61da3..b87214f784 100644--- a/tests/research_library/downloaders/test_pubmed.py+++ b/tests/research_library/downloaders/test_pubmed.py@@ -285,7 +285,13 @@ class TestDownloadWithResult:def test_download_text_with_result_failure(self, mock_download_text, mock_rate_limit):- """Test failed text download returns skip reason."""+ """Test failed text download returns a skip reason.++ The reason must not name a paywall: `_download_text` returns None for+ unrelated failures too, and the word "subscription" alone makes+ `FailureClassifier` declare a permanent failure (#6412). See+ test_pubmed_text_skip_reason.py.+ """from local_deep_research.research_library.downloaders.pubmed import (PubMedDownloader,)@@ -301,7 +307,9 @@ class TestDownloadWithResult:)assert result.is_success is False- assert "subscription" in result.skip_reason.lower()+ assert result.skip_reason == (+ "Full text not available from the PubMed/PMC APIs"+ )class TestApplyRateLimit:diff --git a/tests/research_library/downloaders/test_pubmed_coverage.py b/tests/research_library/downloaders/test_pubmed_coverage.pyindex a4acb1b7b3..900899bd44 100644--- a/tests/research_library/downloaders/test_pubmed_coverage.py+++ b/tests/research_library/downloaders/test_pubmed_coverage.py@@ -558,12 +558,16 @@ class TestDownloadWithResult:assert result.content == b"some text"def test_text_failure(self, downloader):+ # No paywall is claimed: `_download_text` returns None for unrelated+ # failures too (#6412). See test_pubmed_text_skip_reason.py.with patch.object(downloader, "_download_text", return_value=None):result = downloader.download_with_result("https://pubmed.ncbi.nlm.nih.gov/123/", ContentType.TEXT)assert result.is_success is False- assert "subscription" in result.skip_reason.lower()+ assert result.skip_reason == (+ "Full text not available from the PubMed/PMC APIs"+ )def test_pdf_delegates_to_download_pdf_with_result(self, downloader):expected = DownloadResult(content=b"%PDF", is_success=True)diff --git a/tests/research_library/downloaders/test_pubmed_text_skip_reason.py b/tests/research_library/downloaders/test_pubmed_text_skip_reason.pynew file mode 100644index 0000000000..170ed737bb--- /dev/null+++ b/tests/research_library/downloaders/test_pubmed_text_skip_reason.py@@ -0,0 +1,144 @@+"""A failed PubMed text extraction must not claim a paywall it never saw.++``PubMedDownloader._download_text`` returns ``None`` for an unparseable URL, a+Europe PMC API error, an unreachable PDF and a PDF whose text could not be+extracted alike. Reporting all of them as "may require subscription" states a+paywall as fact for failures that have nothing to do with access, and the word+"subscription" is exactly what ``FailureClassifier.classify_failure`` matches to+declare a permanent ``paywall_or_login`` failure (#6412).++The genuine paywall signal is unaffected: it comes from Europe PMC's+``isOpenAccess`` flag on the PDF path, asserted in+``test_pubmed_coverage.py::TestDownloadPdfWithResult``.+"""++from unittest.mock import MagicMock, patch++import pytest++from local_deep_research.library.download_management.failure_classifier import (+ PermanentFailure,+)+from local_deep_research.research_library.downloaders.base import ContentType+from local_deep_research.research_library.downloaders.pubmed import (+ PubMedDownloader,+)++PAYWALL_WORDS = (+ "subscription",+ "paywall",+ "requires login",+ "requires authentication",+)++# The wording this fix replaced, kept as a control: the assertions below are+# about the reason being classifiable, not about phrasing taste.+PREVIOUS_REASON = "Full text not available - may require subscription"+++def downloader():+ dl = PubMedDownloader(rate_limit_delay=0.0)+ dl.last_request_time = 0+ return dl+++# Failures with no access evidence behind them, covering each way+# `_download_text` can give up.+NON_PAYWALL_FAILURES = [+ pytest.param(+ "https://pubmed.ncbi.nlm.nih.gov/12345678/",+ id="api-and-pdf-both-failed",+ ),+ pytest.param(+ "https://europepmc.org/article/MED/12345678", id="no-id-in-url"+ ),+ pytest.param(+ "https://ncbi.nlm.nih.gov/pmc/articles/PMC12345/",+ id="pmc-text-unavailable",+ ),+]++[email protected]("url", NON_PAYWALL_FAILURES)+def test_text_failure_does_not_assert_a_paywall(downloader, url):+ with patch.object(downloader, "_download_text", return_value=None):+ result = downloader.download_with_result(url, ContentType.TEXT)++ assert result.is_success is False+ assert result.skip_reason, (+ "a skipped text download must still say something"+ )+ named = [+ word for word in PAYWALL_WORDS if word in result.skip_reason.lower()+ ]+ assert not named, f"{result.skip_reason!r} asserts {named} without evidence"+++def test_text_failure_reason_is_not_classified_as_a_permanent_paywall(+ downloader,+):+ """The reason travels to the classifier as the failure `details`.++ ``RetryManager.record_attempt`` passes the skip reason straight through as+ ``details``, so the wording decides whether the resource is blacklisted.+ """+ from local_deep_research.library.download_management.failure_classifier import (+ FailureClassifier,+ )++ with patch.object(downloader, "_download_text", return_value=None):+ reason = downloader.download_with_result(+ "https://pubmed.ncbi.nlm.nih.gov/12345678/", ContentType.TEXT+ ).skip_reason++ classifier = FailureClassifier()+ failure = classifier.classify_failure(+ error_type="unknown",+ details=reason,+ url="https://pubmed.ncbi.nlm.nih.gov/12345678/",+ )+ assert not (+ isinstance(failure, PermanentFailure)+ and failure.error_type == "paywall_or_login"+ ), f"{reason!r} is still read as a paywall: {failure.error_type}"++ # Control: the previous wording is, so the change is load-bearing.+ previous = classifier.classify_failure(+ error_type="unknown",+ details=PREVIOUS_REASON,+ url="https://pubmed.ncbi.nlm.nih.gov/12345678/",+ )+ assert isinstance(previous, PermanentFailure)+ assert previous.error_type == "paywall_or_login"+++def test_successful_text_extraction_is_untouched(downloader):+ with patch.object(downloader, "_download_text", return_value=b"full text"):+ result = downloader.download_with_result(+ "https://pubmed.ncbi.nlm.nih.gov/12345678/", ContentType.TEXT+ )++ assert result.is_success is True+ assert result.content == b"full text"+ assert result.skip_reason is None+++def test_a_real_paywall_is_still_reported_on_the_pdf_path(downloader):+ """Europe PMC's open-access flag is evidence, and it must keep speaking."""+ response = MagicMock()+ response.status_code = 200+ response.json.return_value = {+ "resultList": {+ "result": [{"isOpenAccess": "N", "journalTitle": "Nature Medicine"}]+ }+ }++ with patch.object(downloader.session, "get", return_value=response):+ result = downloader.download_with_result(+ "https://pubmed.ncbi.nlm.nih.gov/12345678/", ContentType.PDF+ )++ assert result.is_success is False+ assert "subscription" in result.skip_reason.lower()+ assert "Nature Medicine" in result.skip_reason