~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(fetch): retry transient HTML fetch failures, align PDF recovery page budget (#7192)
S9031266fcbe4
diff --git a/changelog.d/+html-fetch-retry-pdf500.security.md b/changelog.d/+html-fetch-retry-pdf500.security.mdnew file mode 100644index 0000000000..fb037037da--- /dev/null+++ b/changelog.d/+html-fetch-retry-pdf500.security.md@@ -0,0 +1 @@+Retry transient failures in the HTML fetcher, log status-bucket reasons on fetch failures, and align the PDF recovery page budget with the central extraction ceiling.diff --git a/src/local_deep_research/research_library/downloaders/arxiv.py b/src/local_deep_research/research_library/downloaders/arxiv.pyindex 6296881923..b2aabf2da6 100644--- a/src/local_deep_research/research_library/downloaders/arxiv.py+++ b/src/local_deep_research/research_library/downloaders/arxiv.py@@ -471,11 +471,20 @@ class ArxivDownloader(HTMLDownloader):``HTMLDownloader._fetch_html_with_final_url``)."""html_url = f"https://{self._fetch_host}/html/{arxiv_id}"+ # Single-shot HTML leg: the full-text flow implements its own+ # backoff/circuit-breaking across papers (NOT_FETCHED vs+ # FETCH_FAILED accounting), so the generic fetch must not+ # retry timeouts/429s underneath it and triple the per-paper+ # cost against a rate-limiting host.if on_transport_failure is None:- html, final_url = self._fetch_html_with_final_url(html_url)+ html, final_url = self._fetch_html_with_final_url(+ html_url, max_attempts=1+ )else:html, final_url = self._fetch_html_with_final_url(- html_url, on_transport_failure=on_transport_failure+ html_url,+ on_transport_failure=on_transport_failure,+ max_attempts=1,)if not html:return Nonediff --git a/src/local_deep_research/research_library/downloaders/html.py b/src/local_deep_research/research_library/downloaders/html.pyindex 773270b0c3..7a47daf9b1 100644--- a/src/local_deep_research/research_library/downloaders/html.py+++ b/src/local_deep_research/research_library/downloaders/html.py@@ -9,6 +9,8 @@ from typing import Any, Callable, Dict, Optionalfrom urllib.parse import urlparsefrom loguru import loggerfrom bs4 import BeautifulSoup+from requests.exceptions import ConnectionError as RequestsConnectionError+from requests.exceptions import Timeout as RequestsTimeoutfrom .base import (_DOCUMENT_ABSENT_STATUSES,@@ -24,6 +26,7 @@ from ...security.client_safe_errors import (client_safe_download_message,)from ...security.ssrf_validator import redact_url_for_log+from ...utilities.pdf_extraction_limits import MAX_PDF_EXTRACTION_PAGESfrom ...utilities.resource_utils import safe_close@@ -67,17 +70,55 @@ def _as_markdown_text(value: str) -> str:return " ".join(value.split())+def _fetch_failure_reason(status_code: int) -> str:+ """Factual HTTP-class token for ``html.fetch_failed`` log lines.++ Names the status bucket only (absent / rate-limited / forbidden /+ client / server error) — never the cause: a 403 may be a bot-wall+ or a genuinely private document, and the log cannot tell.+ """+ if status_code in _DOCUMENT_ABSENT_STATUSES:+ return "absent"+ if status_code in (429, 503):+ return "rate_limited"+ if status_code in (401, 403):+ return "forbidden"+ if status_code == 400:+ return "bad_request"+ if 500 <= status_code <= 599:+ return "server_error"+ if 400 <= status_code <= 499:+ return "client_error"+ return "unexpected_status"+++class _TerminalTransportError(Exception):+ """Internal: terminal transport failure with attempt context.++ Raised by ``_fetch_response_with_retry`` when the last attempt fails+ with a transport error, so the failure handling can record the real+ attempt count instead of a hardcoded ``retry_count=1``. Never+ escapes ``HTMLDownloader``.+ """++ def __init__(self, exc: BaseException, wait_time: float, attempt: int):+ super().__init__(exc)+ self.exc = exc+ self.wait_time = wait_time+ self.attempt = attempt++class HTMLDownloader(BaseDownloader):"""Downloader for HTML web pages - extracts clean text content."""# Bound on the PDF recovery path (see _extract_stashed_pdf_text). The- # stash is reachable from every HTML-classified URL, so an unbounded- # pypdf parse would turn any search result into unbounded CPU/memory- # work (crafted FlateDecode streams parse far beyond their byte size;- # pypdf caps each stream but not the document total). 10 MB / 50 pages- # covers ordinary papers while keeping a single ingest bounded.+ # stash is reachable from every HTML-classified URL, so the fetched+ # bytes stay capped small (MAX_RECOVERED_PDF_BYTES); the page budget+ # aliases the central MAX_PDF_EXTRACTION_PAGES ceiling so research+ # recovery and dedicated PDF paths truncate identically (one source+ # of truth in utilities.pdf_extraction_limits).MAX_RECOVERED_PDF_BYTES = 10 * 1024 * 1024- MAX_RECOVERED_PDF_PAGES = 50+ MAX_RECOVERED_PDF_PAGES = MAX_PDF_EXTRACTION_PAGESdef __init__(self,@@ -249,6 +290,7 @@ class HTMLDownloader(BaseDownloader):url: str,*,on_transport_failure: Optional[Callable[[], None]] = None,+ max_attempts: int = 3,) -> tuple[Optional[str], Optional[str]]:"""Fetch raw HTML together with the URL that finally served it.@@ -268,6 +310,14 @@ class HTMLDownloader(BaseDownloader):those bytes turns a recoverable source into a warning plus a lostcitation.+ Transient failures -- HTTP 429/503 and ``requests`` timeouts /+ connection errors -- are retried up to ``max_attempts`` with an+ adaptive wait before every attempt (mirroring+ ``BaseDownloader._download_pdf``); every other status or error+ fails fast exactly as before. ``on_transport_failure`` fires at+ most once, only on the terminal failure, preserving its+ circuit-breaker contract (see below).+``on_transport_failure`` is called once when the fetch failswithout the host answering: an exception (timeout, connectionerror, a body that aborts mid-read, the decoded-body cap) or a@@ -293,22 +343,47 @@ class HTMLDownloader(BaseDownloader):url=redact_url_for_log(url),)engine_type = f"html_download_{rate_limit_authority(url)}"+ max_attempts = max(1, int(max_attempts))- wait_time = self.rate_tracker.apply_rate_limit(engine_type)+ def _terminal_failure(+ exc: BaseException, failed_wait_time: float, failed_attempt: int+ ) -> tuple[None, None]:+ # A fetch that raised must leave no recovery state behind, even+ # if it raised after the stash was populated: the payload belongs+ # to a response the caller never received in full.+ self._recovery_kind = None+ self._recovery_payload = None+ self._recovery_url = None+ if on_transport_failure is not None:+ # The caller handles the failure, so it is not an error+ # here (ERROR records reach the user's browser).+ logger.warning(+ "html.fetch_error url={url} exc_class={exc_class}",+ url=redact_url_for_log(url),+ exc_class=type(exc).__name__,+ )+ else:+ logger.opt(exception=False).error(+ "html.fetch_error url={url} exc_class={exc_class}",+ url=redact_url_for_log(url),+ exc_class=type(exc).__name__,+ )+ self.rate_tracker.record_outcome(+ engine_type=engine_type,+ wait_time=failed_wait_time,+ success=False,+ retry_count=failed_attempt,+ error_type=type(exc).__name__,+ )+ if on_transport_failure is not None:+ on_transport_failure()+ return None, None+ wait_time = 0.0+ attempt = 1try:- # stream=True keeps requests.Session.send from consuming the- # body before _ensure_decoded_body_cap can wrap the reads, so- # the guard bounds the decoded read of response.text at- # MAX_RESPONSE_SIZE even for a valid under-cap Content-Length- # (the gap SafeSession leaves unguarded). This bounds the final- # response only: with allow_redirects=True, SafeSession discards- # each intermediate redirect body unread.- response = self.session.get(- url,- timeout=self.timeout,- allow_redirects=True,- stream=True,+ response, wait_time, attempt = self._fetch_response_with_retry(+ url, engine_type, max_attempts)try:@@ -329,7 +404,7 @@ class HTMLDownloader(BaseDownloader):engine_type=engine_type,wait_time=wait_time,success=True,- retry_count=1,+ retry_count=attempt,search_result_count=1,)logger.debug(@@ -400,21 +475,29 @@ class HTMLDownloader(BaseDownloader):status=response.status_code,)return None, None+ status = response.status_code+ # NOTE: intermediate 429/503s never reach here --+ # _fetch_response_with_retry handles (and closes) those+ # before returning. A 429/503 seen here exhausted+ # max_attempts and fails terminally below.logger.warning(- "html.fetch_failed url={url} status={status}",+ "html.fetch_failed url={url} status={status} "+ "reason={reason} attempts={attempts}",url=redact_url_for_log(url),- status=response.status_code,+ status=status,+ reason=_fetch_failure_reason(status),+ attempts=attempt,)self.rate_tracker.record_outcome(engine_type=engine_type,wait_time=wait_time,success=False,- retry_count=1,- error_type=f"HTTP_{response.status_code}",+ retry_count=attempt,+ error_type=f"HTTP_{status}",)if (on_transport_failure is not None- and response.status_code not in _DOCUMENT_ABSENT_STATUSES+ and status not in _DOCUMENT_ABSENT_STATUSES):on_transport_failure()return None, None@@ -423,37 +506,91 @@ class HTMLDownloader(BaseDownloader):# body is consumed or the response is closed.safe_close(response, "HTML download response")+ except _TerminalTransportError as terminal:+ return _terminal_failure(+ terminal.exc, terminal.wait_time, terminal.attempt+ )except Exception as e:- # A fetch that raised must leave no recovery state behind, even- # if it raised after the stash was populated: the payload belongs- # to a response the caller never received in full.- self._recovery_kind = None- self._recovery_payload = None- self._recovery_url = None- if on_transport_failure is not None:- # The caller handles the failure, so it is not an error- # here (ERROR records reach the user's browser).+ return _terminal_failure(e, wait_time, attempt)++ def _fetch_response_with_retry(+ self, url: str, engine_type: str, max_attempts: int+ ) -> tuple[Any, float, int]:+ """GET with retry on transient failures; terminal errors raise.++ Retries HTTP 429/503 and ``requests`` timeouts / connection+ errors (mirroring ``BaseDownloader._download_pdf``), with an+ adaptive wait before every attempt. Returns+ ``(response, wait_time, attempt)``. A terminal transport failure+ raises ``_TerminalTransportError`` carrying the attempt context;+ any other exception from the GET propagates unchanged. A+ retried 429/503 response is closed before continuing so pooled+ connections are released.+ """+ for attempt in range(1, max_attempts + 1):+ # Adaptive wait before every attempt (mirrors+ # BaseDownloader._download_pdf): the tracker learns per host,+ # and retrying into a rate-limited host without waiting would+ # trip the next attempt immediately.+ wait_time = self.rate_tracker.apply_rate_limit(engine_type)+ try:+ # stream=True keeps requests.Session.send from consuming the+ # body before _ensure_decoded_body_cap can wrap the reads, so+ # the guard bounds the decoded read of response.text at+ # MAX_RESPONSE_SIZE even for a valid under-cap Content-Length+ # (the gap SafeSession leaves unguarded). This bounds the final+ # response only: with allow_redirects=True, SafeSession discards+ # each intermediate redirect body unread.+ response = self.session.get(+ url,+ timeout=self.timeout,+ allow_redirects=True,+ stream=True,+ )+ except (RequestsTimeout, RequestsConnectionError) as e:+ if attempt >= max_attempts:+ raise _TerminalTransportError(e, wait_time, attempt) from elogger.warning(- "html.fetch_error url={url} exc_class={exc_class}",+ "html.fetch_attempt url={url} exc_class={exc_class} "+ "attempt={attempt}/{max_attempts}",url=redact_url_for_log(url),exc_class=type(e).__name__,+ attempt=attempt,+ max_attempts=max_attempts,)- else:- logger.opt(exception=False).error(- "html.fetch_error url={url} exc_class={exc_class}",+ self.rate_tracker.record_outcome(+ engine_type=engine_type,+ wait_time=wait_time,+ success=False,+ retry_count=attempt,+ error_type=type(e).__name__,+ )+ continue+ except Exception as e:+ raise _TerminalTransportError(e, wait_time, attempt) from e+ status = response.status_code+ if status in (429, 503) and attempt < max_attempts:+ logger.warning(+ "html.fetch_attempt url={url} status={status} "+ "attempt={attempt}/{max_attempts}",url=redact_url_for_log(url),- exc_class=type(e).__name__,+ status=status,+ attempt=attempt,+ max_attempts=max_attempts,)- self.rate_tracker.record_outcome(- engine_type=engine_type,- wait_time=wait_time,- success=False,- retry_count=1,- error_type=type(e).__name__,- )- if on_transport_failure is not None:- on_transport_failure()- return None, None+ self.rate_tracker.record_outcome(+ engine_type=engine_type,+ wait_time=wait_time,+ success=False,+ retry_count=attempt,+ error_type=f"HTTP_{status}",+ )+ safe_close(response, "HTML download response")+ continue+ return response, wait_time, attempt+ raise AssertionError( # pragma: no cover -- defensive+ "_fetch_response_with_retry: loop always returns or raises"+ )@staticmethoddef _is_recoverable_text_content(content_type: str) -> bool:diff --git a/tests/content_fetcher/test_html_downloader.py b/tests/content_fetcher/test_html_downloader.pyindex 312cf2a65d..e901b7e01f 100644--- a/tests/content_fetcher/test_html_downloader.py+++ b/tests/content_fetcher/test_html_downloader.py@@ -4,9 +4,13 @@ Tests for HTML downloader.from unittest.mock import MagicMock, PropertyMock, patch+import pytestfrom requests.exceptions import ChunkedEncodingError-from local_deep_research.research_library.downloaders.html import HTMLDownloader+from local_deep_research.research_library.downloaders.html import (+ HTMLDownloader,+ _fetch_failure_reason,+)from local_deep_research.research_library.downloaders.base import ContentType@@ -599,11 +603,13 @@ class TestHTMLDownloaderPdfRecovery:assert called == [], sizemock_session.get.assert_called_once()- def test_recovery_truncates_real_pdf_at_page_budget(self, monkeypatch):- """End-to-end: a 60-page PDF served at an HTML URL yields 50 pages.+ def test_recovery_extracts_sixty_page_pdf_fully(self, monkeypatch):+ """End-to-end: a 60-page PDF served at an HTML URL is fully read.- Uses the real extractor (no mocks), pinning both the page-budget- wiring and base.py's enumerate/break enforcement.+ The recovery page budget aliases the central+ ``MAX_PDF_EXTRACTION_PAGES`` ceiling (500), so ordinary+ multi-dozen-page documents are no longer cut at 50. Uses the+ real extractor (no mocks)."""pdf_bytes = _make_text_pdf(60)assert len(pdf_bytes) <= HTMLDownloader.MAX_RECOVERED_PDF_BYTES@@ -617,10 +623,35 @@ class TestHTMLDownloaderPdfRecovery:text = result.decode("utf-8")assert "pagetext-000" in textassert "pagetext-049" in text- assert "pagetext-050" not in text- assert "pagetext-059" not in text+ assert "pagetext-050" in text+ assert "pagetext-059" in textmock_session.get.assert_called_once()+ def test_recovery_truncation_enforced_at_configured_cap(self, monkeypatch):+ """A small configured cap still truncates (wiring check)."""+ monkeypatch.setattr(HTMLDownloader, "MAX_RECOVERED_PDF_PAGES", 7)+ pdf_bytes = _make_text_pdf(10)+ response = self._pdf_response()+ response.content = pdf_bytes+ downloader, _ = self._pdf_downloader(monkeypatch, response)++ result = downloader.download(self.PDF_URL, ContentType.TEXT)++ assert result is not None+ text = result.decode("utf-8")+ assert "pagetext-006" in text+ assert "pagetext-007" not in text++ def test_page_budget_aliases_central_ceiling(self):+ """The recovery budget cannot silently diverge again."""+ from local_deep_research.utilities.pdf_extraction_limits import (+ MAX_PDF_EXTRACTION_PAGES,+ )++ assert (+ HTMLDownloader.MAX_RECOVERED_PDF_PAGES == MAX_PDF_EXTRACTION_PAGES+ )+class TestHTMLDownloaderTextRecovery:"""Plain-text / feed responses at HTML URLs are usable as-is.@@ -850,3 +881,272 @@ class TestHTMLDownloaderBodyReadFailure:on_transport_failure.assert_called_once_with()assert tracker.record_outcome.call_count == 1assert downloader._consume_recovery(self.URL) == (None, None, None)+++class TestHTMLFetchRetry:+ """Transient failures (429/503, timeouts) are retried, rest fail fast."""++ URL = "https://example.com/unstable-page"++ def _downloader(self, monkeypatch):+ downloader = HTMLDownloader()+ mock_session = MagicMock()+ mock_session.headers = {}+ monkeypatch.setattr(downloader, "session", mock_session)+ tracker = MagicMock()+ monkeypatch.setattr(downloader, "rate_tracker", tracker)+ return downloader, mock_session, tracker++ def _status_response(self, status):+ response = MagicMock()+ response.status_code = status+ response.headers = {}+ response.url = self.URL+ return response++ def _html_response(self):+ response = self._status_response(200)+ response.headers = {"content-type": "text/html; charset=utf-8"}+ response.text = "<html><body>recovered</body></html>"+ return response++ def test_429_then_success(self, monkeypatch):+ """A 429 is retried; the eventual 200 succeeds."""+ downloader, mock_session, tracker = self._downloader(monkeypatch)+ mock_session.get.side_effect = [+ self._status_response(429),+ self._html_response(),+ ]+ on_transport_failure = MagicMock()++ html, final_url = downloader._fetch_html_with_final_url(+ self.URL, on_transport_failure=on_transport_failure+ )++ assert html == "<html><body>recovered</body></html>"+ assert final_url == self.URL+ assert mock_session.get.call_count == 2+ on_transport_failure.assert_not_called()+ assert tracker.record_outcome.call_count == 2+ failed, succeeded = tracker.record_outcome.call_args_list+ assert failed.kwargs["success"] is False+ assert failed.kwargs["error_type"] == "HTTP_429"+ assert failed.kwargs["retry_count"] == 1+ assert succeeded.kwargs["success"] is True+ assert succeeded.kwargs["retry_count"] == 2++ def test_503_exhausted_gives_up_once(self, monkeypatch):+ """Three 503s: three GETs, one callback, terminal reason logged."""+ downloader, mock_session, tracker = self._downloader(monkeypatch)+ mock_session.get.side_effect = [self._status_response(503)] * 3+ on_transport_failure = MagicMock()++ with patch(+ "local_deep_research.research_library.downloaders.html.logger"+ ) as mock_logger:+ html, final_url = downloader._fetch_html_with_final_url(+ self.URL, on_transport_failure=on_transport_failure+ )++ assert (html, final_url) == (None, None)+ assert mock_session.get.call_count == 3+ on_transport_failure.assert_called_once_with()+ assert tracker.record_outcome.call_count == 3+ failed = [+ c+ for c in mock_logger.warning.call_args_list+ if "fetch_failed" in c.args[0]+ ]+ assert len(failed) == 1+ assert failed[0].kwargs["status"] == 503+ assert failed[0].kwargs["reason"] == "rate_limited"+ assert failed[0].kwargs["attempts"] == 3++ def test_timeout_then_success(self, monkeypatch):+ """Timeouts are retried like 429/503."""+ from requests.exceptions import Timeout++ downloader, mock_session, tracker = self._downloader(monkeypatch)+ mock_session.get.side_effect = [+ Timeout("timed out"),+ Timeout("timed out"),+ self._html_response(),+ ]++ html, _ = downloader._fetch_html_with_final_url(self.URL)++ assert html == "<html><body>recovered</body></html>"+ assert mock_session.get.call_count == 3+ assert tracker.record_outcome.call_count == 3++ def test_403_fails_fast_with_reason(self, monkeypatch):+ """A 403 is not retryable; the reason names the bucket."""+ downloader, mock_session, tracker = self._downloader(monkeypatch)+ mock_session.get.return_value = self._status_response(403)+ on_transport_failure = MagicMock()++ with patch(+ "local_deep_research.research_library.downloaders.html.logger"+ ) as mock_logger:+ html, final_url = downloader._fetch_html_with_final_url(+ self.URL, on_transport_failure=on_transport_failure+ )++ assert (html, final_url) == (None, None)+ mock_session.get.assert_called_once()+ on_transport_failure.assert_called_once_with()+ failed = [+ c+ for c in mock_logger.warning.call_args_list+ if "fetch_failed" in c.args[0]+ ]+ assert len(failed) == 1+ assert failed[0].kwargs["reason"] == "forbidden"++ def test_404_fails_fast_without_callback(self, monkeypatch):+ """Absent documents are answers, not transport failures."""+ downloader, mock_session, _ = self._downloader(monkeypatch)+ mock_session.get.return_value = self._status_response(404)+ on_transport_failure = MagicMock()++ with patch(+ "local_deep_research.research_library.downloaders.html.logger"+ ) as mock_logger:+ html, final_url = downloader._fetch_html_with_final_url(+ self.URL, on_transport_failure=on_transport_failure+ )++ assert (html, final_url) == (None, None)+ mock_session.get.assert_called_once()+ on_transport_failure.assert_not_called()+ failed = [+ c+ for c in mock_logger.warning.call_args_list+ if "fetch_failed" in c.args[0]+ ]+ assert len(failed) == 1+ assert failed[0].kwargs["reason"] == "absent"++ def test_max_attempts_one_disables_retry(self, monkeypatch):+ """max_attempts=1 preserves the old single-shot behavior."""+ downloader, mock_session, _ = self._downloader(monkeypatch)+ mock_session.get.side_effect = [+ self._status_response(429),+ self._html_response(),+ ]++ html, final_url = downloader._fetch_html_with_final_url(+ self.URL, max_attempts=1+ )++ assert (html, final_url) == (None, None)+ mock_session.get.assert_called_once()++ def test_retried_response_connection_is_closed(self, monkeypatch):+ """A retried 429 response is closed before the next attempt.++ The old single-shot path also closed its (single) response in a+ ``finally``, so asserting the close alone cannot tell retry from+ no-retry. Pin the ordering: the first response must be closed+ before the second GET is issued.+ """+ downloader, mock_session, _ = self._downloader(monkeypatch)+ first = self._status_response(429)+ second = self._html_response()+ order: list[str] = []++ def _record_close(*args, **kwargs):+ order.append("close")++ first.close.side_effect = _record_close++ def _ordered_get(*args, **kwargs):+ order.append("get")+ if len([c for c in order if c == "get"]) == 1:+ return first+ return second++ mock_session.get.side_effect = _ordered_get++ downloader._fetch_html_with_final_url(self.URL)++ first.close.assert_called_once()+ assert mock_session.get.call_count == 2+ # Close must sit between the two GETs: the old single-shot+ # ``finally`` only closes after the fetch returns, i.e. after the+ # last GET (["get", "get", "close"]).+ assert order == ["get", "close", "get"]++ def test_connection_error_then_success(self, monkeypatch):+ """ConnectionErrors are retried like timeouts."""+ from requests.exceptions import ConnectionError as RequestsConnError++ downloader, mock_session, tracker = self._downloader(monkeypatch)+ mock_session.get.side_effect = [+ RequestsConnError("connection reset"),+ self._html_response(),+ ]+ on_transport_failure = MagicMock()++ html, final_url = downloader._fetch_html_with_final_url(+ self.URL, on_transport_failure=on_transport_failure+ )++ assert html == "<html><body>recovered</body></html>"+ assert final_url == self.URL+ assert mock_session.get.call_count == 2+ on_transport_failure.assert_not_called()+ assert tracker.record_outcome.call_count == 2+ failed, succeeded = tracker.record_outcome.call_args_list+ assert failed.kwargs["success"] is False+ assert failed.kwargs["error_type"] == "ConnectionError"+ assert failed.kwargs["retry_count"] == 1+ assert succeeded.kwargs["success"] is True+ assert succeeded.kwargs["retry_count"] == 2++ def test_non_retryable_exception_fails_fast_once(self, monkeypatch):+ """A non-retryable GET error: 1 GET, 1 outcome, 1 callback."""+ downloader, mock_session, tracker = self._downloader(monkeypatch)+ # SSRF rejections surface as ValueError from the session; any+ # non-timeout/connection exception must take the same path.+ mock_session.get.side_effect = ValueError("SSRF blocked")+ on_transport_failure = MagicMock()++ html, final_url = downloader._fetch_html_with_final_url(+ self.URL, on_transport_failure=on_transport_failure+ )++ assert (html, final_url) == (None, None)+ mock_session.get.assert_called_once()+ on_transport_failure.assert_called_once_with()+ assert tracker.record_outcome.call_count == 1+ outcome = tracker.record_outcome.call_args+ assert outcome.kwargs["success"] is False+ assert outcome.kwargs["retry_count"] == 1+ assert outcome.kwargs["error_type"] == "ValueError"+++ ("status", "expected"),+ [+ (404, "absent"),+ (410, "absent"),+ (429, "rate_limited"),+ (503, "rate_limited"),+ (401, "forbidden"),+ (403, "forbidden"),+ (400, "bad_request"),+ (500, "server_error"),+ (502, "server_error"),+ (599, "server_error"),+ (418, "client_error"),+ (422, "client_error"),+ (499, "client_error"),+ (302, "unexpected_status"),+ (199, "unexpected_status"),+ (600, "unexpected_status"),+ ],+)+def test_fetch_failure_reason_token_table(status, expected):+ """Every status bucket maps to its caller-safe log token."""+ assert _fetch_failure_reason(status) == expecteddiff --git a/tests/research_library/downloaders/test_arxiv_html_text.py b/tests/research_library/downloaders/test_arxiv_html_text.pyindex 6d6acd2837..093b44af61 100644--- a/tests/research_library/downloaders/test_arxiv_html_text.py+++ b/tests/research_library/downloaders/test_arxiv_html_text.py@@ -72,7 +72,9 @@ def test_text_uses_official_html_and_preserves_tex(downloader, mocker):assert "Source: https://arxiv.org/abs/2501.12345v2" in textassert "<math" not in textassert "application/x-tex" not in text- fetch_html.assert_called_once_with("https://arxiv.org/html/2501.12345v2")+ fetch_html.assert_called_once_with(+ "https://arxiv.org/html/2501.12345v2", max_attempts=1+ )pdf_download.assert_not_called()api_fetch.assert_not_called()hard_clock.assert_not_called()@@ -169,7 +171,7 @@ def test_text_preserves_document_when_any_math_lacks_usable_tex(assert "<math" not in contentassert "Source: https://arxiv.org/abs/math.AG/0601001v3" in contentfetch_html.assert_called_once_with(- "https://arxiv.org/html/math.AG/0601001v3"+ "https://arxiv.org/html/math.AG/0601001v3", max_attempts=1)pdf_download.assert_not_called()api_fetch.assert_not_called()@@ -232,7 +234,9 @@ def test_math_nodes_convert_through_every_fallback_tier(downloader, mocker):assert "α" not in textassert "<math" not in textassert "application/x-tex" not in text- fetch_html.assert_called_once_with("https://arxiv.org/html/2501.12345v2")+ fetch_html.assert_called_once_with(+ "https://arxiv.org/html/2501.12345v2", max_attempts=1+ )pdf_download.assert_not_called()api_fetch.assert_not_called()@@ -721,7 +725,9 @@ def test_text_keeps_pdf_when_html_is_a_degenerate_stub(downloader, mocker):assert result.text == (f"{FULL_PDF_TEXT.rstrip()}\n\nSource: https://arxiv.org/abs/2301.12345")- fetch_html.assert_called_once_with("https://arxiv.org/html/2301.12345")+ fetch_html.assert_called_once_with(+ "https://arxiv.org/html/2301.12345", max_attempts=1+ )pdf_download.assert_not_called()api_fetch.assert_not_called()diff --git a/tests/research_library/downloaders/test_html_logging_sinks.py b/tests/research_library/downloaders/test_html_logging_sinks.pyindex f5fbbc08c0..88b3e33895 100644--- a/tests/research_library/downloaders/test_html_logging_sinks.py+++ b/tests/research_library/downloaders/test_html_logging_sinks.py@@ -78,7 +78,7 @@ def _html_downloader(response=None, error=None):@pytest.mark.parametrize(- ("response", "error", "event"),+ ("response", "error", "event", "rate_limit_calls"),[(SimpleNamespace(@@ -88,6 +88,7 @@ def _html_downloader(response=None, error=None):),None,"html.fetch_succeeded",+ 1,),(SimpleNamespace(@@ -99,6 +100,7 @@ def _html_downloader(response=None, error=None):),None,"html.fetch_pdf_recovery",+ 1,),(SimpleNamespace(@@ -110,6 +112,7 @@ def _html_downloader(response=None, error=None):),None,"html.fetch_text_recovery",+ 1,),(SimpleNamespace(@@ -121,24 +124,32 @@ def _html_downloader(response=None, error=None):),None,"html.fetch_unexpected_content_type",+ 1,),(SimpleNamespace(status_code=503, headers={}, text=""),None,"html.fetch_failed",+ 3,+ ),+ (+ None,+ RuntimeError(f"{_EXCEPTION_TEXT}: {_URL}"),+ "html.fetch_error",+ 1,),- (None, RuntimeError(f"{_EXCEPTION_TEXT}: {_URL}"), "html.fetch_error"),],)def test_static_fetch_branches_render_one_safe_origin(- rendered_log, response, error, event+ rendered_log, response, error, event, rate_limit_calls):downloader, rate_tracker = _html_downloader(response=response, error=error)with downloader:downloader._fetch_html(_URL)- rate_tracker.apply_rate_limit.assert_called_once_with(+ assert rate_tracker.apply_rate_limit.call_count == rate_limit_calls+ rate_tracker.apply_rate_limit.assert_called_with("html_download_origin.example:8443")_assert_safe_event(rendered_log, event)@@ -416,8 +427,14 @@ def _drive_html(url, _monkeypatch):# Same (url, monkeypatch) signature as the two browser drivers so the# parametrisation below can treat all three uniformly; the static path# needs no module stubbing, so its monkeypatch argument goes unused.+ # A 200 HTML response: these tests pin the engine-key derivation, not+ # the fetch retry loop (a 503 here would apply rate limiting 3 times).downloader, rate_tracker = _html_downloader(- response=SimpleNamespace(status_code=503, headers={}, text="")+ response=SimpleNamespace(+ status_code=200,+ headers={"content-type": "text/html"},+ text="<html>ok</html>",+ ))with downloader:downloader._fetch_html(url)