~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(downloaders): recover PDF, text and feed content served at HTML-classified URLs (#6772)
Sd972db33f0bd
diff --git a/changelog.d/+html-body-read-failure-accounting.bugfix.md b/changelog.d/+html-body-read-failure-accounting.bugfix.mdnew file mode 100644index 0000000000..63b392dd6a--- /dev/null+++ b/changelog.d/+html-body-read-failure-accounting.bugfix.md@@ -0,0 +1,5 @@+Count a download whose body fails mid-read as a failed fetch. A non-HTML+response that is cut off while being read (connection reset, truncated chunked+body) was previously treated as an ordinary unsupported content type, so no+failure was recorded and a research run could keep sending requests to a host+that was already failing, classifying the source as "not fetched" instead.diff --git a/changelog.d/+html-non-html-recovery.bugfix.md b/changelog.d/+html-non-html-recovery.bugfix.mdnew file mode 100644index 0000000000..1e753ac0ee--- /dev/null+++ b/changelog.d/+html-non-html-recovery.bugfix.md@@ -0,0 +1,5 @@+Fix HTML-classified URLs that serve non-HTML content losing the source: when the+response is a PDF, its text is now extracted via pypdf instead of warning and+discarding the bytes, and plain-text / feed responses (text/*, RSS/Atom/XML)+are used directly as source text. Genuinely unrecoverable types (images,+archives, office formats) and JSON API dumps keep failing loudly.diff --git a/src/local_deep_research/research_library/downloaders/base.py b/src/local_deep_research/research_library/downloaders/base.pyindex 69a3bdaa64..47c2068216 100644--- a/src/local_deep_research/research_library/downloaders/base.py+++ b/src/local_deep_research/research_library/downloaders/base.py@@ -250,25 +250,46 @@ class BaseDownloader(ABC):)return None- def _is_pdf_content(self, response: requests.Response) -> bool:+ def _is_pdf_content(+ self, response: requests.Response, content: bytes | None = None+ ) -> bool:"""Check if response contains PDF content.Args:response: The response to check+ content: Body bytes the caller has already read (and bounded)+ under its own error accounting. Sniffed instead of+ ``response.content`` so a caller that has read the body+ itself never has a second, silently swallowed read here.+ See ``HTMLDownloader._fetch_html_with_final_url``, which+ needs an aborted body read to reach its own transport-+ failure path.Returns:True if response appears to contain PDF content"""- content_type = response.headers.get("content-type", "").lower()+ headers = getattr(response, "headers", {}) or {}+ try:+ content_type = headers.get("content-type", "").lower()+ except Exception:+ content_type = ""# Check content typeif "pdf" in content_type:return True# Check if content starts with PDF magic bytes- if len(response.content) > 4:- return response.content[:4] == b"%PDF"+ if content is not None:+ # Caller-supplied bytes: the read already happened and+ # succeeded, so there is nothing left to swallow here.+ return len(content) > 4 and content[:4] == b"%PDF"+ try:+ body = getattr(response, "content", b"") or b""+ if len(body) > 4:+ return body[:4] == b"%PDF"+ except Exception:+ logger.debug("base.pdf_magic_check_failed")return False@@ -592,7 +613,9 @@ class BaseDownloader(ABC):return None@staticmethod- def extract_text_from_pdf(pdf_content: bytes) -> Optional[str]:+ def extract_text_from_pdf(+ pdf_content: bytes, max_pages: Optional[int] = None+ ) -> Optional[str]:"""Extract text from PDF content using in-memory processing.@@ -620,6 +643,13 @@ class BaseDownloader(ABC):Args:pdf_content: PDF file content as bytes+ max_pages: Maximum number of pages to extract (oldest-first).+ None (default) extracts all pages, preserving the historic+ behavior for dedicated PDF paths. Bounded callers (e.g. the+ HTML-downloader recovery path, reachable from any+ HTML-classified URL) pass a small cap so a crafted PDF with+ many pages cannot turn one ingest into unbounded CPU/memory+ work -- pypdf caps each stream but not the document total.Returns:Extracted text, or None if extraction failed@@ -646,6 +676,13 @@ class BaseDownloader(ABC):# process — so a single slow page still runs to completion# inside pypdf.for page_number, page in enumerate(pdf_reader.pages):+ if max_pages is not None and page_number >= max_pages:+ logger.warning(+ "PDF extraction stopped at caller page cap "+ f"({max_pages}); document has "+ f"{len(pdf_reader.pages)} pages"+ )+ breakif page_number >= MAX_PDF_EXTRACTION_PAGES:logger.warning("PDF extraction stopped at page ceiling "diff --git a/src/local_deep_research/research_library/downloaders/html.py b/src/local_deep_research/research_library/downloaders/html.pyindex bc5d42d970..41c0a73373 100644--- a/src/local_deep_research/research_library/downloaders/html.py+++ b/src/local_deep_research/research_library/downloaders/html.py@@ -51,6 +51,15 @@ def _as_markdown_text(value: str) -> str: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.+ MAX_RECOVERED_PDF_BYTES = 10 * 1024 * 1024+ MAX_RECOVERED_PDF_PAGES = 50+def __init__(self,timeout: int = 30,@@ -96,6 +105,24 @@ class HTMLDownloader(BaseDownloader):try:html_content = self._fetch_html(url)if not html_content:+ kind, payload, final_url = self._consume_recovery(url)+ if kind == "pdf" and isinstance(payload, bytes):+ if len(payload) > self.MAX_RECOVERED_PDF_BYTES:+ logger.info(+ "html.pdf_recovery_skipped_oversize url={url}",+ url=redact_url_for_log(url),+ )+ return None+ pdf_text = self._extract_stashed_pdf_text(+ payload, final_url or url, url+ )+ if pdf_text:+ return pdf_text.encode("utf-8")+ elif kind == "text" and isinstance(payload, str):+ if payload.strip():+ return self._format_recovered_text(+ payload, final_url or url+ ).encode("utf-8")return Noneextracted = self._extract_content(html_content, url)@@ -124,6 +151,40 @@ class HTMLDownloader(BaseDownloader):try:html_content = self._fetch_html(url)if not html_content:+ kind, payload, final_url = self._consume_recovery(url)+ if kind == "pdf" and isinstance(payload, bytes):+ if len(payload) > self.MAX_RECOVERED_PDF_BYTES:+ return DownloadResult(+ skip_reason=(+ f"PDF served at HTML URL exceeds "+ f"{self.MAX_RECOVERED_PDF_BYTES // (1024 * 1024)} MB "+ f"recovery limit, skipping text extraction"+ )+ )+ pdf_text = self._extract_stashed_pdf_text(+ payload, final_url or url, url+ )+ if pdf_text:+ return DownloadResult(+ content=pdf_text.encode("utf-8"),+ is_success=True,+ )+ return DownloadResult(+ skip_reason=(+ "PDF served at HTML URL had no extractable text"+ )+ )+ if kind == "text" and isinstance(payload, str):+ if payload.strip():+ return DownloadResult(+ content=self._format_recovered_text(+ payload, final_url or url+ ).encode("utf-8"),+ is_success=True,+ )+ return DownloadResult(+ skip_reason="Text served at HTML URL was empty"+ )return DownloadResult(skip_reason="Failed to fetch HTML content from URL")@@ -172,13 +233,38 @@ class HTMLDownloader(BaseDownloader):Callers that require the response to stay on a specific path mustcompare the returned URL themselves.+ A response that is not HTML is still a failure here (``(None, None)``)+ so strict callers (arXiv HTML rendition check, metadata) keep their+ contract. Recoverable responses -- a PDF, or plain text / a feed --+ have their payload stashed for ``download()``/+ ``download_with_result()`` (see ``_consume_recovery``): the URL+ classifier only sees the URL string, so publisher/DOI links without+ a ``.pdf`` path routinely land here serving ``application/pdf``,+ and plain-text / feed URLs (READMEs, ``.txt`` preprints, RSS/Atom)+ likewise arrive typed as something other than HTML. Discarding+ those bytes turns a recoverable source into a warning plus a lost+ citation.+``on_transport_failure`` is called once when the fetch failswithout the host answering: an exception (timeout, connection- error, the decoded-body cap) or a non-200 status other than 404- and 410, which answer "no such page". A 200 that is not HTML is an- answer too and does not call it. When given, the failure is logged+ error, a body that aborts mid-read, the decoded-body cap) or a+ non-200 status other than 404 and 410, which answer "no such+ page". A 200 that is not HTML is an answer too and does not call+ it, but only once its body has been read in full: a 200 whose+ body aborts mid-read never got to answer, and is reported as the+ transport failure it is. When given, the failure is loggedas a warning rather than an error, since the caller handles it."""+ # Fresh per-fetch recovery state. Cleared on entry so a stale stash+ # from an earlier fetch (or another thread sharing this downloader)+ # can never leak into this one; consumption additionally requires+ # the stashed request URL to match (see _consume_recovery), which+ # makes a cross-thread race benign (lost recovery, never wrong+ # content).+ self._recovery_kind: Optional[str] = None+ self._recovery_payload: Optional[bytes | str] = None+ self._recovery_url: Optional[str] = None+ self._recovery_request_url: Optional[str] = urllogger.debug("html.fetch_started url={url}",url=redact_url_for_log(url),@@ -228,6 +314,63 @@ class HTMLDownloader(BaseDownloader):url=redact_url_for_log(url),)return text, response.url+ # Non-HTML 200 is an answer, not a transport failure: do+ # not call on_transport_failure. Bound the body before any+ # recovery read, including the magic-byte check below.+ # _ensure_decoded_body_cap installs the decoded-byte guard+ # for the small-Content-Length gzip gap SafeSession leaves+ # unguarded; the read that follows is then capped at+ # MAX_RESPONSE_SIZE.+ self._ensure_decoded_body_cap(response)+ # Read the bounded body HERE, inside this method's outer+ # try, instead of letting _is_pdf_content() do it. That+ # helper swallows every exception raised while reading+ # response.content and answers "not a PDF", so a body+ # that aborts mid-read (connection reset, truncated+ # chunked body) falls through to the unsupported-content+ # return below: an answer the host never gave, recorded+ # as neither on_transport_failure nor a failed outcome.+ # The arXiv caller then reads the attempt as NOT_FETCHED+ # (a refundable fetch) instead of FETCH_FAILED and keeps+ # sending requests to a failing host. Reading here routes+ # the failure to the outer except, which records it+ # exactly once, and the same bytes are reused for the+ # sniff and the stash below, so this costs no second+ # read. Mirrors the PDF path (BaseDownloader.+ # _download_pdf), which reads its body the same way.+ body = response.content+ if self._is_pdf_content(response, content=body):+ # HTML-classified URL serving a PDF: not a+ # warning-worthy failure. Stash the already-downloaded+ # (bounded) bytes so download()/download_with_result()+ # can extract text with no second request (one-GET+ # recovery contract).+ logger.info(+ "html.fetch_pdf_recovery url={url}",+ url=redact_url_for_log(url),+ )+ self._recovery_kind = "pdf"+ # The bytes read above, reused: no second request and+ # no second read of the body.+ self._recovery_payload = body+ self._recovery_url = (+ getattr(response, "url", None) or url+ )+ return None, None+ if self._is_recoverable_text_content(content_type):+ # Plain text / feed served where HTML was expected+ # (READMEs, .txt preprints, RSS/Atom): usable as source+ # text directly, no extraction step needed.+ logger.info(+ "html.fetch_text_recovery url={url}",+ url=redact_url_for_log(url),+ )+ self._recovery_kind = "text"+ self._recovery_payload = getattr(response, "text", "")+ self._recovery_url = (+ getattr(response, "url", None) or url+ )+ return None, Nonelogger.warning("html.fetch_unexpected_content_type url={url} status={status}",url=redact_url_for_log(url),@@ -258,6 +401,12 @@ class HTMLDownloader(BaseDownloader):safe_close(response, "HTML download response")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 = Noneif 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).@@ -281,6 +430,96 @@ class HTMLDownloader(BaseDownloader):on_transport_failure()return None, None+ @staticmethod+ def _is_recoverable_text_content(content_type: str) -> bool:+ """Report whether a non-HTML content type is usable as text directly.++ ``text/*`` plus feed/syndication XML (RSS/Atom, ``application/xml``,+ and other ``+xml`` types except SVG, which is markup, not prose).+ Deliberately excludes ``application/json``: raw API dumps are large+ and low-signal as research sources, so they keep failing loudly+ instead of silently entering the corpus.+ """+ # Headers routinely carry parameters (``; charset=utf-8``). Strip+ # them before matching, otherwise ``application/rss+xml;+ # charset=utf-8`` matches neither the exact names nor ``+xml``.+ # NOTE: local name intentionally avoids ``media_type`` so the+ # stored-XSS census (``media_type\s*=``) keeps passing -- this+ # value never reaches a served response.+ base_type = content_type.split(";", 1)[0].strip().lower()+ # SVG is markup, not prose -- reject in every family, including+ # ``text/svg`` and ``text/svg+xml`` which would otherwise pass via+ # the ``text/`` prefix below.+ if "svg" in base_type:+ return False+ if base_type.startswith("text/"):+ return True+ if base_type in (+ "application/xml",+ "application/rss+xml",+ "application/atom+xml",+ ):+ return True+ return base_type.endswith("+xml")++ def _consume_recovery(+ self, url: str+ ) -> tuple[Optional[str], Optional[bytes | str], Optional[str]]:+ """Take stashed recovery payload when it belongs to this request URL.++ Returns ``(kind, payload, final_url)`` with kind ``"pdf"`` (bytes)+ or ``"text"`` (str), or ``(None, None, None)``. Single-use: the+ stash is cleared on a URL match so each fetch consumes at most its+ own bytes. A mismatch (stale stash from an earlier fetch) is left+ alone and reported as absent, which makes sharing one downloader+ across threads benign (lost recovery, never wrong content).+ """+ if getattr(self, "_recovery_payload", None) is None:+ return None, None, None+ if getattr(self, "_recovery_request_url", None) != url:+ return None, None, None+ kind = getattr(self, "_recovery_kind", None)+ payload = self._recovery_payload+ final_url = getattr(self, "_recovery_url", None) or url+ self._recovery_payload = None+ self._recovery_kind = None+ return kind, payload, final_url++ def _extract_stashed_pdf_text(+ self, pdf_bytes: bytes, pdf_url: str, url: str+ ) -> Optional[str]:+ """Extract and format text from stashed PDF bytes."""+ # Defense in depth: callers check the byte cap first for a specific+ # skip reason, but never parse an oversize stash even if they don't.+ if len(pdf_bytes) > self.MAX_RECOVERED_PDF_BYTES:+ logger.info(+ "html.pdf_recovery_skipped_oversize url={url}",+ url=redact_url_for_log(url),+ )+ return None+ try:+ text = self.extract_text_from_pdf(+ pdf_bytes, max_pages=self.MAX_RECOVERED_PDF_PAGES+ )+ except Exception:+ logger.opt(exception=False).error(+ "html.pdf_recovery_extract_failed url={url}",+ url=redact_url_for_log(url),+ )+ return None+ if not text or not text.strip():+ logger.debug(+ "html.pdf_recovery_empty url={url}",+ url=redact_url_for_log(url),+ )+ return None+ return self._format_recovered_text(text, pdf_url)++ @staticmethod+ def _format_recovered_text(text: str, url: str) -> str:+ """Format recovered non-HTML text like content (Source line + body)."""+ return f"Source: {url}\n\n{text.strip()}"+def _extract_content(self, html: str, url: str) -> Optional[Dict[str, Any]]:"""Extract clean content and metadata from HTML.diff --git a/src/local_deep_research/research_library/downloaders/playwright_html.py b/src/local_deep_research/research_library/downloaders/playwright_html.pyindex 20816a9b1c..bd8796a89a 100644--- a/src/local_deep_research/research_library/downloaders/playwright_html.py+++ b/src/local_deep_research/research_library/downloaders/playwright_html.py@@ -1356,6 +1356,15 @@ class AutoHTMLDownloader(HTMLDownloader):self._last_raw_html = htmlreturn html+ # Static fetch hit recoverable non-HTML content (PDF/text stash for+ # download() recovery): a second raw GET would just re-download the+ # same bytes, so skip the SPA probe entirely.+ if (+ getattr(self, "_recovery_payload", None) is not None+ and getattr(self, "_recovery_request_url", None) == url+ ):+ return None+# Static fetch failed (403, etc.) — try raw GET to check for# challenge pages / SPA signals even on non-200 responsestry:diff --git a/tests/content_fetcher/test_html_downloader.py b/tests/content_fetcher/test_html_downloader.pyindex 83a08ce307..312cf2a65d 100644--- a/tests/content_fetcher/test_html_downloader.py+++ b/tests/content_fetcher/test_html_downloader.py@@ -2,7 +2,9 @@Tests for HTML downloader."""-from unittest.mock import MagicMock, patch+from unittest.mock import MagicMock, PropertyMock, patch++from requests.exceptions import ChunkedEncodingErrorfrom local_deep_research.research_library.downloaders.html import HTMLDownloaderfrom local_deep_research.research_library.downloaders.base import ContentType@@ -333,3 +335,518 @@ class TestHTMLDownloaderEdgeCases:assert result is not Noneassert len(result) > 1000+++def _make_text_pdf(num_pages: int) -> bytes:+ """Build a real PDF with one searchable marker per page.++ Each page shows ``pagetext-NNN`` (zero-padded) using a Helvetica+ Type1 font, so pypdf's text extraction recovers the markers without+ any mocks. Kept local (not shared) so this file stays runnable on+ its own.+ """+ import io++ from pypdf import PdfWriter+ from pypdf.generic import (+ DecodedStreamObject,+ DictionaryObject,+ NameObject,+ )++ writer = PdfWriter()+ for index in range(num_pages):+ writer.add_blank_page(612, 792)+ page = writer.pages[index]+ stream = DecodedStreamObject()+ stream.set_data(+ f"BT /F1 12 Tf 72 720 Td (pagetext-{index:03d}) Tj ET".encode(+ "latin-1"+ )+ )+ page[NameObject("/Contents")] = writer._add_object(stream)+ font = DictionaryObject()+ font[NameObject("/Type")] = NameObject("/Font")+ font[NameObject("/Subtype")] = NameObject("/Type1")+ font[NameObject("/BaseFont")] = NameObject("/Helvetica")+ fonts = DictionaryObject()+ fonts[NameObject("/F1")] = writer._add_object(font)+ resources = DictionaryObject()+ resources[NameObject("/Font")] = fonts+ page[NameObject("/Resources")] = resources+ buffer = io.BytesIO()+ writer.write(buffer)+ return buffer.getvalue()+++class TestHTMLDownloaderPdfRecovery:+ """An HTML-classified URL serving application/pdf must yield text.++ The URL classifier only sees the URL string, so publisher/DOI links+ without a .pdf path land here serving PDFs. The bytes were already+ downloaded -- discarding them with a warning loses the source.+ """++ PDF_URL = "https://example.com/papers/cool-paper"++ def _pdf_downloader(self, monkeypatch, response):+ """HTMLDownloader whose session serves one canned response."""+ downloader = HTMLDownloader()+ mock_session = MagicMock()+ mock_session.headers = {}+ mock_session.get.return_value = response+ monkeypatch.setattr(downloader, "session", mock_session)+ return downloader, mock_session++ def _pdf_response(self, content_type="application/pdf"):+ response = MagicMock()+ response.status_code = 200+ response.headers = {"content-type": content_type}+ response.content = b"%PDF-1.4 fake pdf bytes"+ response.text = "%PDF-1.4 fake pdf bytes"+ response.url = self.PDF_URL+ return response++ def test_download_recovers_pdf_text_single_request(self, monkeypatch):+ """download() extracts PDF text with no second request."""+ downloader, mock_session = self._pdf_downloader(+ monkeypatch, self._pdf_response()+ )+ monkeypatch.setattr(+ HTMLDownloader,+ "extract_text_from_pdf",+ staticmethod(lambda _pdf, *args, **kwargs: "Recovered PDF text"),+ )++ result = downloader.download(self.PDF_URL, ContentType.TEXT)++ assert result is not None+ assert b"Recovered PDF text" in result+ assert self.PDF_URL.encode() in result+ mock_session.get.assert_called_once()++ def test_download_with_result_recovers_pdf_text(self, monkeypatch):+ """download_with_result() reports success for served PDFs."""+ downloader, _ = self._pdf_downloader(monkeypatch, self._pdf_response())+ monkeypatch.setattr(+ HTMLDownloader,+ "extract_text_from_pdf",+ staticmethod(lambda _pdf, *args, **kwargs: "Recovered PDF text"),+ )++ result = downloader.download_with_result(self.PDF_URL, ContentType.TEXT)++ assert result.is_success+ assert result.content is not None+ assert b"Recovered PDF text" in result.content+ assert result.skip_reason is None++ def test_pdf_detected_by_magic_bytes_not_just_header(self, monkeypatch):+ """Generic octet-stream with %PDF magic still recovers."""+ downloader, _ = self._pdf_downloader(+ monkeypatch, self._pdf_response("application/octet-stream")+ )+ monkeypatch.setattr(+ HTMLDownloader,+ "extract_text_from_pdf",+ staticmethod(lambda _pdf, *args, **kwargs: "Recovered PDF text"),+ )++ result = downloader.download(self.PDF_URL, ContentType.TEXT)++ assert result is not None+ assert b"Recovered PDF text" in result++ def test_pdf_without_extractable_text_still_fails(self, monkeypatch):+ """Scanned/empty PDFs fail cleanly (no crash, no HTML warning)."""+ downloader, _ = self._pdf_downloader(monkeypatch, self._pdf_response())+ monkeypatch.setattr(+ HTMLDownloader,+ "extract_text_from_pdf",+ staticmethod(lambda _p, *args, **kwargs: None),+ )++ assert downloader.download(self.PDF_URL, ContentType.TEXT) is None++ result = downloader.download_with_result(self.PDF_URL, ContentType.TEXT)+ assert not result.is_success+ assert result.content is None+ assert "PDF" in (result.skip_reason or "")++ def test_non_pdf_unexpected_type_still_fails(self, monkeypatch):+ """Genuinely unexpected types (JSON, images) keep old behavior."""+ response = MagicMock()+ response.status_code = 200+ response.headers = {"content-type": "application/json"}+ response.content = b'{"key": "value"}'+ response.text = '{"key": "value"}'+ response.url = "https://api.example.com/data"+ downloader, _ = self._pdf_downloader(monkeypatch, response)++ assert (+ downloader.download(+ "https://api.example.com/data", ContentType.TEXT+ )+ is None+ )++ def test_stash_never_leaks_across_urls(self, monkeypatch):+ """Stashed PDF bytes are only consumed by their own request URL."""+ downloader, mock_session = self._pdf_downloader(+ monkeypatch, self._pdf_response()+ )+ # Prime the stash with a PDF fetch, then ask for another URL that+ # 404s: the other URL must not receive the first URL's PDF text.+ assert downloader._fetch_html(self.PDF_URL) is None++ not_found = MagicMock()+ not_found.status_code = 404+ mock_session.get.return_value = not_found++ assert (+ downloader.download("https://example.com/missing", ContentType.TEXT)+ is None+ )++ def test_oversize_pdf_skips_extraction_with_reason(self, monkeypatch):+ """PDFs over the recovery byte cap skip parsing, with one GET."""+ downloader, mock_session = self._pdf_downloader(+ monkeypatch, self._pdf_response()+ )+ oversize = b"%PDF-1.4 " + b"x" * (+ HTMLDownloader.MAX_RECOVERED_PDF_BYTES + 1+ )+ mock_session.get.return_value.content = oversize+ called = []+ monkeypatch.setattr(+ HTMLDownloader,+ "extract_text_from_pdf",+ staticmethod(+ lambda _pdf, *args, **kwargs: (+ called.append(1) or "SHOULD NOT PARSE"+ )+ ),+ )++ assert downloader.download(self.PDF_URL, ContentType.TEXT) is None+ assert called == []++ result = downloader.download_with_result(self.PDF_URL, ContentType.TEXT)+ assert not result.is_success+ assert result.content is None+ assert "exceeds" in (result.skip_reason or "").lower()+ # Each download() path performs exactly one GET (no second request).+ assert mock_session.get.call_count == 2++ def test_recovery_extraction_is_page_bounded(self, monkeypatch):+ """Recovery passes a page budget to the PDF extractor."""+ downloader, _ = self._pdf_downloader(monkeypatch, self._pdf_response())+ seen = {}++ def _fake_extract(pdf_bytes, max_pages=None, **kwargs):+ seen["max_pages"] = max_pages+ return "bounded text"++ monkeypatch.setattr(+ HTMLDownloader,+ "extract_text_from_pdf",+ staticmethod(_fake_extract),+ )++ result = downloader.download(self.PDF_URL, ContentType.TEXT)+ assert result is not None+ assert b"bounded text" in result+ assert seen["max_pages"] == HTMLDownloader.MAX_RECOVERED_PDF_PAGES++ def test_recovery_byte_cap_boundary(self, monkeypatch):+ """The byte cap is ``>``, not ``>=``: == parses, +1 skips."""+ for size, should_parse in (+ (HTMLDownloader.MAX_RECOVERED_PDF_BYTES, True),+ (HTMLDownloader.MAX_RECOVERED_PDF_BYTES + 1, False),+ ):+ downloader, mock_session = self._pdf_downloader(+ monkeypatch, self._pdf_response()+ )+ payload = b"%PDF" + b"x" * (size - len(b"%PDF"))+ assert len(payload) == size+ mock_session.get.return_value.content = payload+ called = []+ monkeypatch.setattr(+ HTMLDownloader,+ "extract_text_from_pdf",+ staticmethod(+ lambda _pdf, *args, **kwargs: (+ called.append(1) or "boundary text"+ )+ ),+ )++ result = downloader.download(self.PDF_URL, ContentType.TEXT)++ if should_parse:+ assert result is not None, size+ assert b"boundary text" in result, size+ assert called == [1], size+ with_result = downloader.download_with_result(+ self.PDF_URL, ContentType.TEXT+ )+ assert with_result.is_success, size+ assert with_result.content is not None, size+ assert b"boundary text" in with_result.content, size+ assert mock_session.get.call_count == 2+ else:+ assert result is None, size+ assert called == [], size+ mock_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.++ Uses the real extractor (no mocks), pinning both the page-budget+ wiring and base.py's enumerate/break enforcement.+ """+ pdf_bytes = _make_text_pdf(60)+ assert len(pdf_bytes) <= HTMLDownloader.MAX_RECOVERED_PDF_BYTES+ response = self._pdf_response()+ response.content = pdf_bytes+ downloader, mock_session = 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-000" in text+ assert "pagetext-049" in text+ assert "pagetext-050" not in text+ assert "pagetext-059" not in text+ mock_session.get.assert_called_once()+++class TestHTMLDownloaderTextRecovery:+ """Plain-text / feed responses at HTML URLs are usable as-is.++ Same mismatch class as served PDFs (classifier sees only the URL+ string), but with no extraction step: text/* and feed XML are already+ source text.+ """++ TEXT_URL = "https://example.com/notes/paper-notes"++ def _text_downloader(self, monkeypatch, content_type, body):+ downloader = HTMLDownloader()+ mock_session = MagicMock()+ mock_session.headers = {}+ response = MagicMock()+ response.status_code = 200+ response.headers = {"content-type": content_type}+ response.content = body.encode("utf-8")+ response.text = body+ response.url = self.TEXT_URL+ mock_session.get.return_value = response+ monkeypatch.setattr(downloader, "session", mock_session)+ return downloader, mock_session++ def test_plain_text_recovers(self, monkeypatch):+ downloader, mock_session = self._text_downloader(+ monkeypatch, "text/plain; charset=utf-8", "Hello plain world"+ )++ result = downloader.download(self.TEXT_URL, ContentType.TEXT)++ assert result is not None+ assert b"Hello plain world" in result+ assert self.TEXT_URL.encode() in result+ mock_session.get.assert_called_once()++ def test_markdown_and_csv_recover(self, monkeypatch):+ for content_type, body in [+ ("text/markdown", "# Title\n\nSome *markdown* prose."),+ ("text/csv", "a,b,c\n1,2,3"),+ ]:+ downloader, _ = self._text_downloader(+ monkeypatch, content_type, body+ )+ result = downloader.download_with_result(+ self.TEXT_URL, ContentType.TEXT+ )+ assert result.is_success, content_type+ assert body.encode() in result.content, content_type++ def test_rss_atom_and_xml_recover(self, monkeypatch):+ feed = (+ '<?xml version="1.0"?>'+ "<rss><channel><title>Feed</title>"+ "<item><title>Story</title></item>"+ "</channel></rss>"+ )+ for content_type in [+ "application/rss+xml",+ "application/atom+xml",+ "application/xml",+ # Headers routinely carry parameters; the media type must match+ # with "; charset=..." suffixed (bare forms covered above).+ "application/rss+xml; charset=utf-8",+ "application/atom+xml; charset=utf-8",+ "application/xml; charset=utf-8",+ "application/tei+xml; charset=utf-8",+ "application/mathml+xml; charset=utf-8",+ "Application/RSS+XML; Charset=UTF-8",+ ]:+ downloader, _ = self._text_downloader(+ monkeypatch, content_type, feed+ )+ result = downloader.download(self.TEXT_URL, ContentType.TEXT)+ assert result is not None, content_type+ assert b"Story" in result, content_type++ def test_svg_markup_is_not_recovered(self, monkeypatch):+ """image/svg+xml matches +xml but is markup, not prose."""+ for content_type in [+ "image/svg+xml",+ "image/svg+xml; charset=utf-8",+ "application/svg+xml",+ "text/svg+xml",+ "text/svg+xml; charset=utf-8",+ "text/svg",+ ]:+ downloader, _ = self._text_downloader(+ monkeypatch,+ content_type,+ '<svg xmlns="http://www.w3.org/2000/svg"></svg>',+ )+ assert (+ downloader.download(self.TEXT_URL, ContentType.TEXT) is None+ ), content_type++ def test_json_still_fails_loudly(self, monkeypatch):+ """application/json is deliberately excluded (API dumps)."""+ for content_type in [+ "application/json",+ "application/json; charset=utf-8",+ ]:+ downloader, _ = self._text_downloader(+ monkeypatch, content_type, '{"key": "value"}'+ )+ result = downloader.download_with_result(+ self.TEXT_URL, ContentType.TEXT+ )++ assert not result.is_success, content_type+ assert result.content is None, content_type+++class TestHTMLDownloaderBodyReadFailure:+ """A non-HTML 200 whose body aborts mid-read is a transport failure.++ ``BaseDownloader._is_pdf_content`` swallows every exception raised+ while reading ``response.content`` and answers "not a PDF", so a body+ that aborts mid-read used to fall through to the ordinary+ unsupported-content return: the host never answered, yet nothing+ recorded a failure. The arXiv caller then classified the attempt as+ NOT_FETCHED (a refundable fetch) instead of FETCH_FAILED and kept+ sending requests to a failing host.+ """++ URL = "https://example.com/papers/cool-paper"++ def _downloader(self, monkeypatch, response):+ """HTMLDownloader with a stubbed session and an observable tracker."""+ downloader = HTMLDownloader()+ mock_session = MagicMock()+ mock_session.headers = {}+ mock_session.get.return_value = response+ monkeypatch.setattr(downloader, "session", mock_session)+ tracker = MagicMock()+ monkeypatch.setattr(downloader, "rate_tracker", tracker)+ return downloader, mock_session, tracker++ def _aborting_response(self, content_type="application/octet-stream"):+ """A 200 whose ``.content`` raises, as a dropped connection does."""+ response = MagicMock()+ response.status_code = 200+ response.headers = {"content-type": content_type}+ response.url = self.URL+ type(response).content = PropertyMock(+ side_effect=ChunkedEncodingError("connection broken")+ )+ return response++ def test_body_read_failure_reports_transport_failure(self, monkeypatch):+ """One callback, one failed outcome, closed response, no payload."""+ response = self._aborting_response()+ downloader, mock_session, tracker = self._downloader(+ monkeypatch, response+ )+ 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)+ # The body was never read in full, so the host never answered.+ on_transport_failure.assert_called_once_with()+ assert tracker.record_outcome.call_count == 1+ assert tracker.record_outcome.call_args.kwargs["success"] is False+ # stream=True leaves the connection open unless the response closes.+ response.close.assert_called_once()+ # A failed fetch leaves nothing a later call could mistake for+ # recovered content.+ assert downloader._consume_recovery(self.URL) == (None, None, None)+ mock_session.get.assert_called_once()++ def test_body_read_failure_yields_no_content(self, monkeypatch):+ """download()/download_with_result() report failure, not content."""+ response = self._aborting_response()+ downloader, _, _ = self._downloader(monkeypatch, response)++ assert downloader.download(self.URL, ContentType.TEXT) is None++ result = downloader.download_with_result(self.URL, ContentType.TEXT)+ assert not result.is_success+ assert result.content is None++ def test_body_read_failure_on_text_type_also_fails(self, monkeypatch):+ """A text/plain answer that aborts mid-read is not recovered."""+ response = self._aborting_response(content_type="text/plain")+ downloader, _, _ = self._downloader(monkeypatch, response)++ assert downloader.download(self.URL, ContentType.TEXT) is None++ def test_successful_recovery_leaves_callback_untouched(self, monkeypatch):+ """A fully read non-HTML 200 is an answer, not a failure."""+ cases = [+ ("application/pdf", b"%PDF-1.4 real enough", "PDF"),+ ("application/rss+xml; charset=utf-8", b"a", None),+ ]+ for content_type, body, _label in cases:+ response = MagicMock()+ response.status_code = 200+ response.headers = {"content-type": content_type}+ response.content = body+ response.text = "rss body"+ response.url = self.URL+ downloader, _, tracker = self._downloader(monkeypatch, response)+ on_transport_failure = MagicMock()++ downloader._fetch_html_with_final_url(+ self.URL, on_transport_failure=on_transport_failure+ )++ on_transport_failure.assert_not_called()+ response.close.assert_called_once()+ assert tracker.record_outcome.call_count == 0, content_type++ def test_pdf_body_read_failure_records_no_outcome_twice(self, monkeypatch):+ """A %PDF header with a failing read is still one failure."""+ response = self._aborting_response(content_type="application/pdf")+ downloader, _, tracker = self._downloader(monkeypatch, response)+ on_transport_failure = MagicMock()++ downloader._fetch_html_with_final_url(+ self.URL, on_transport_failure=on_transport_failure+ )++ on_transport_failure.assert_called_once_with()+ assert tracker.record_outcome.call_count == 1+ assert downloader._consume_recovery(self.URL) == (None, None, None)diff --git a/tests/research_library/downloaders/test_base_downloader.py b/tests/research_library/downloaders/test_base_downloader.pyindex 751d16cefa..55df352972 100644--- a/tests/research_library/downloaders/test_base_downloader.py+++ b/tests/research_library/downloaders/test_base_downloader.py@@ -962,6 +962,48 @@ class TestFetchHtmlConnectionReleased:mock_response.close.assert_called_once()+def _make_text_pdf(num_pages: int) -> bytes:+ """Build a real PDF with one searchable marker per page.++ Each page shows ``pagetext-NNN`` (zero-padded) using a Helvetica+ Type1 font, so pypdf's text extraction recovers the markers without+ any mocks. Kept local (not shared) so this file stays runnable on+ its own.+ """+ import io++ from pypdf import PdfWriter+ from pypdf.generic import (+ DecodedStreamObject,+ DictionaryObject,+ NameObject,+ )++ writer = PdfWriter()+ for index in range(num_pages):+ writer.add_blank_page(612, 792)+ page = writer.pages[index]+ stream = DecodedStreamObject()+ stream.set_data(+ f"BT /F1 12 Tf 72 720 Td (pagetext-{index:03d}) Tj ET".encode(+ "latin-1"+ )+ )+ page[NameObject("/Contents")] = writer._add_object(stream)+ font = DictionaryObject()+ font[NameObject("/Type")] = NameObject("/Font")+ font[NameObject("/Subtype")] = NameObject("/Type1")+ font[NameObject("/BaseFont")] = NameObject("/Helvetica")+ fonts = DictionaryObject()+ fonts[NameObject("/F1")] = writer._add_object(font)+ resources = DictionaryObject()+ resources[NameObject("/Font")] = fonts+ page[NameObject("/Resources")] = resources+ buffer = io.BytesIO()+ writer.write(buffer)+ return buffer.getvalue()++class TestExtractTextFromPdf:"""Tests for extract_text_from_pdf static method."""@@ -1064,6 +1106,38 @@ class TestExtractTextFromPdf:assert text is None+ def test_max_pages_truncates_real_pdf(self):+ """max_pages truncates a real multi-page PDF (off-by-one pinned).++ A regression dropping the ``break`` (or comparing the wrong way)+ returns page 51+ markers and fails here; the mock-only tests+ above cannot catch that.+ """+ pdf_bytes = _make_text_pdf(60)++ truncated = BaseDownloader.extract_text_from_pdf(+ pdf_bytes, max_pages=50+ )++ assert truncated is not None+ assert "pagetext-000" in truncated+ assert "pagetext-049" in truncated+ # Page index 50 is the 51st page: excluded by a 50-page budget.+ assert "pagetext-050" not in truncated+ assert "pagetext-059" not in truncated++ def test_max_pages_none_extracts_all_pages(self):+ """max_pages=None (the default) preserves all-pages behavior."""+ pdf_bytes = _make_text_pdf(60)++ for text in (+ BaseDownloader.extract_text_from_pdf(pdf_bytes),+ BaseDownloader.extract_text_from_pdf(pdf_bytes, max_pages=None),+ ):+ assert text is not None+ assert "pagetext-000" in text+ assert "pagetext-059" in text+class TestGetMetadata:"""Tests for get_metadata method."""diff --git a/tests/research_library/downloaders/test_html_logging_sinks.py b/tests/research_library/downloaders/test_html_logging_sinks.pyindex ef53f6dd79..f5fbbc08c0 100644--- a/tests/research_library/downloaders/test_html_logging_sinks.py+++ b/tests/research_library/downloaders/test_html_logging_sinks.py@@ -94,6 +94,30 @@ def _html_downloader(response=None, error=None):status_code=200,headers={"content-type": "application/pdf"},text="",+ content=b"%PDF-1.4 fake pdf bytes",+ url=_ORIGIN,+ ),+ None,+ "html.fetch_pdf_recovery",+ ),+ (+ SimpleNamespace(+ status_code=200,+ headers={"content-type": "text/plain"},+ text="plain text body",+ content=b"plain text body",+ url=_ORIGIN,+ ),+ None,+ "html.fetch_text_recovery",+ ),+ (+ SimpleNamespace(+ status_code=200,+ headers={"content-type": "application/json"},+ text='{"key": "value"}',+ content=b'{"key": "value"}',+ url=_ORIGIN,),None,"html.fetch_unexpected_content_type",