~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(arxiv): follow-ups to #5617 — offline text, math tiers, HTML-first search full text (#6691)
LearningCircuitae423bc9e631
diff --git a/.github/scripts/check-file-writes.sh b/.github/scripts/check-file-writes.shindex e6a41f818c..faad230652 100755--- a/.github/scripts/check-file-writes.sh+++ b/.github/scripts/check-file-writes.sh@@ -253,40 +253,10 @@ if [ -n "$ALL_MATCHES" ]; then# ``.idmap.json`` migration sidecar (plain position->uuid JSON map,# no chunk text; see the module docstring / `_ID_RE`)# web_search_engines/engines/search_engine_arxiv.py is NOT listed here:- # its one write (the downloaded PDF of a public arXiv paper) carries an- # inline `# Safe: ...` marker on the write line itself instead of a- # blanket file-level exemption -- that marker is intended as the- # belt-and-suspenders exemption for whichever SUSPICIOUS_PATTERNS entry- # fires on that line. CORRECTION (this comment previously claimed the- # marker is what currently satisfies the check for this file -- false):- # as written today (`tmp_path.open("wb") # Safe: public PDF`), the- # marker is never actually consulted for this line. SAFE_USAGE_PATTERNS- # contains the bare identifier `tmp_path`, and that loop runs BEFORE- # the `# Safe:` marker check below -- `tmp_path` matches this line's- # variable name first, so skip_line is already 1 by the time the- # marker check would run. This is weaker than "any other write later- # added to that file still gets flagged" for two independent reasons,- # not one: first, the bare `tmp_path` entry exempts ANY line in src/- # mentioning that identifier, whatever it does, not just this write;- # second, the SUSPICIOUS_PATTERNS loop above runs `grep` in POSIX- # basic-regex mode (no `-E`), where most of these patterns' trailing- # `\(` opens an unterminated group and errors out (silently swallowed- # by `2>/dev/null`), so patterns like `\.write\(`,- # `Path.*\.write_bytes\(`, and `with.*open\(...` never fire at all.- # Only patterns with a *balanced* `\(...\)` pair, e.g.- # `open\(.*['"]wb['"].*\)`, actually match under this grep call -- and- # it is `tmp_path`, not the marker, that currently exempts that match.- # A write shape that only matches one of the dead patterns (a bare- # `.write(`, `Path(...).write_bytes(...)`, etc.) added elsewhere in- # this file would NOT be caught, marker or no marker. Treat this as a- # per-line exemption for the one pattern that does fire, not a- # file-wide guarantee, and not evidence that the `# Safe:` marker- # mechanism is actually wired up for this file today. Whether the bare- # `tmp_path` entry in SAFE_USAGE_PATTERNS is sound at all (it exempts- # by variable name, not by review) is out of scope for this comment- # fix and tracked instead in #6208, alongside the ~26 other- # SAFE_USAGE_PATTERNS/dead-pattern violations tightening it would- # surface.+ # it no longer writes files (its full text now comes from the in-memory+ # ArxivDownloader path). The dead-pattern and bare `tmp_path`+ # SAFE_USAGE_PATTERNS problems this comment used to describe are+ # tracked in #6208.# If you add an entry here, document WHY the file's writes are safe# (public data, not user-specific, not encrypted at rest by design).if [ "$skip_line" -eq 0 ]; thendiff --git a/changelog.d/5807.security.md b/changelog.d/5807.security.mdindex 25d0faf72b..233330cf0f 100644--- a/changelog.d/5807.security.md+++ b/changelog.d/5807.security.md@@ -1,54 +1,6 @@-arXiv PDF downloads now go through a SSRF-validated `SafeSession`-(with SSRF pre-validation and DNS pinning) instead of the arxiv-library's built-in download path (`urllib.request.urlretrieve`).-This is narrower than "the same session as the rest of the arXiv-integration": this engine's metadata queries (`arxiv.Client()`) still-use the `arxiv` package's own bare `requests.Session()`, unvalidated-and untimed -- only the PDF fetch is gated here.-The fetch continues to go to export.arxiv.org -- that host did not-change; the `arxiv` library (2.4.1) already defaulted-`download_domain="export.arxiv.org"`, the same host already used for-the metadata API.-The request URL no longer appends a `.pdf` suffix (arxiv 2.4.1's own-`pdf_url` has none), which also removes a 301 redirect hop that-`export.arxiv.org` was adding for the suffixed form -- a redirect-response's body was being drained by `requests`' internal redirect-handling before it ever reached the size check below, undermining that-check for exactly the request this change makes.-This fetch now passes `stream=True` and writes the body to disk in-bounded chunks (instead of buffering the whole response via-`.content`) with `Accept-Encoding: identity`: `requests` sends-`Accept-Encoding: gzip` by default where the old `urllib`-based path-did not, and a valid, under-cap `Content-Length` installs no body-guard in `SafeSession` at all, so a small compressed response could-otherwise decompress far past that check.-Since this change, `download_dir` -- reachable through per-user web-settings, e.g. `search.engine.web.arxiv.default_params.download_dir`--- is created (including any missing parent directories) rather than-raising if it does not already exist. Two behavior changes from that-were not previously called out: a `download_dir` containing a `..`-traversal segment now raises (caught, so the result silently has no-`pdf_path` rather than an actionable error), and a `download_dir`-starting with `~` is not expanded by this code, so it is treated as a-literal `~` path segment rather than the user's home directory.-A follow-up now additionally contains directory creation to a-dedicated subtree of the local-deep-research data directory, since-`download_dir` is user-influenced input rather than a trusted-constant -- as of that follow-up, an unexpanded `~`-prefixed-`download_dir` resolves relative to the process's working directory-and (outside the unusual case of that directory being the contained-subtree itself) is now rejected by that containment check rather than-silently creating a literal `~` directory.-The saved filename also changed, from `<id>.<sanitized title>.pdf` to-`<id>.pdf`.-When `Content-Length` is absent, `SafeSession`'s guard correctly-bounds memory for a connection-close-delimited body, but not for one-sent with `Transfer-Encoding: chunked` (the common case for a CDN of-unknown length) -- `urllib3` reads chunked bodies through a path that-bypasses the guard, which is why this fetch enforces its own running-byte cap while streaming rather than relying on that guard alone. The-`urllib3` gap itself lives in SafeSession's response-size cap-(`_check_response_size`/`_install_body_guard` in `safe_requests.py`),-affects every `SafeSession` caller that already streams, and needs-its own follow-up; it is not the same issue as #6172, which tracks-callers that don't set `stream=True` at all.+arXiv PDF downloads made by the arXiv search engine no longer go through the+arxiv library's built-in download path (`urllib.request.urlretrieve`), which+had no SSRF validation; they are fetched through the SSRF-validated+`SafeSession` (pre-validation and DNS pinning) from `export.arxiv.org`, the+host the library already defaulted to. How the engine fetches full text,+and the fact that it no longer saves PDFs to disk, is described under #6691.diff --git a/changelog.d/6199.security.md b/changelog.d/6199.security.mdindex 2c9422c3ee..6fa6e2920d 100644--- a/changelog.d/6199.security.md+++ b/changelog.d/6199.security.md@@ -1,18 +1,6 @@-Follow-up to #5807's arXiv PDF egress hardening. arXiv PDF downloads no-longer append a `.pdf` suffix to the request URL, which removed a 301-redirect hop whose body was being drained by `requests` before-`SafeSession`'s response-size check ever ran on it. The body is now-streamed to disk in bounded chunks with its own running byte cap (instead-of being read whole via `.content`) and `Accept-Encoding: identity` is-sent as a best-effort measure, though the running byte cap over the-already-decoded stream is what actually bounds a decompression bomb-regardless of what encoding the origin sends. Directory creation for-the (per-user-settable) `download_dir` is now contained to a dedicated-`arxiv_downloads` subtree of the local-deep-research data directory,-rather than the data directory itself, which also holds secrets and-per-user encrypted databases.-Also fixed: three unit tests that were making live HTTPS requests to-export.arxiv.org in CI (`test_pdf_download_pypdf2_empty_falls_back_to_summary`,-`test_pypdf2_fails_pdfplumber_succeeds`, `test_both_pdf_extractors_fail`),-and a fourth (`test_pdf_limit_reached`) whose ids never exercised the-branch it named.+Follow-up to #5807's arXiv PDF egress hardening. The response body of the+arXiv search engine's PDF fetch is now bounded by a running cap on the+decoded bytes, so neither an oversized nor a small compressed final+response can exceed the response-size limit (this cap now lives in the+shared downloader; see #6691). Bodies of redirect responses followed on+the way are not covered by this cap (#6813).diff --git a/changelog.d/6691.bugfix.md b/changelog.d/6691.bugfix.mdnew file mode 100644index 0000000000..65090a9355--- /dev/null+++ b/changelog.d/6691.bugfix.md@@ -0,0 +1,13 @@+arXiv text extraction for the research library recovers text in more cases.+When the egress policy or the per-resource retry budget refuses network+access for an arXiv paper whose PDF is already stored (in the database or+on disk), text is now extracted from that stored PDF locally instead of the+request ending without text; with no usable stored PDF the denial stands as+before. Equations in arXiv HTML renditions are now also read from an+`<annotation encoding="application/x-tex+html">` child, and an equation with+no TeX annotation and no `alttext` keeps its visible MathML text (annotation+contents excluded), so a partially annotated rendition is kept instead of+falling back to the PDF; only an equation with no text at all still sends+the page to the PDF. Citation metadata now takes the arXiv ID from a link+written without a scheme on an arXiv-family host (`arxiv.org/abs/...`,+`www.arxiv.org/...`, `export.arxiv.org/...`, `ar5iv.org/...`).diff --git a/changelog.d/6691.removal.md b/changelog.d/6691.removal.mdnew file mode 100644index 0000000000..1d4f4f0b56--- /dev/null+++ b/changelog.d/6691.removal.md@@ -0,0 +1,22 @@+The arXiv search engine no longer writes PDFs to disk. With+`include_full_text` on, the engine's `download_dir` parameter now only+switches the full-text fetch on: its value is not used, no directory is created and no+file is written, and results no longer carry a `pdf_path` key. Full text is+kept in memory: the paper's official arXiv HTML rendition when one exists+(with its equations kept as TeX), otherwise text extracted from the PDF,+both fetched from `export.arxiv.org` through the shared arXiv downloader.+PDF text on this path is now extracted by the shared downloader's extractor,+so the page, character and CPU ceilings from #6459 apply to it.+The `pdf_url` field of arXiv search results (and of `get_paper_details`) is+now `https://arxiv.org/pdf/<id>` built from the paper's validated arXiv ID,+or `None` when the ID does not validate, instead of the `pdf_url` value the+arxiv library returned.+The engine's PDF request is made once and is not retried. When a full-text+request fails instead of being answered (HTTP 429 or 503 on the PDF, a+timeout, a connection error, a failed DNS lookup, a 5xx on either the HTML+or the PDF request),+no further full-text fetches are made for the remaining papers of that+search, which keep their summaries, and the failure is logged as a warning.+Only a paper arXiv answered has no full text (no HTML rendition, and its PDF+answered 404/410 or with a response that is not a PDF) gives its+`max_full_text` slot to a later paper.diff --git a/changelog.d/6691.security.md b/changelog.d/6691.security.mdnew file mode 100644index 0000000000..7cfc1f433c--- /dev/null+++ b/changelog.d/6691.security.md@@ -0,0 +1,8 @@+The research-library downloaders' shared PDF fetch and HTML page fetch now+stream the response and bound the decoded body of the final response at the+response-size limit, including a compressed body sent with a small, valid+`Content-Length`, which `SafeSession` alone left unbounded. An oversized+body is abandoned without a retry and the fetch returns no content. Both+fetches still follow redirects, and the body of an intermediate redirect+response is read by `requests` before this bound applies; that gap is+tracked in #6813.diff --git a/src/local_deep_research/research_library/downloaders/arxiv.py b/src/local_deep_research/research_library/downloaders/arxiv.pyindex 4c39c9c622..c147c3c422 100644--- a/src/local_deep_research/research_library/downloaders/arxiv.py+++ b/src/local_deep_research/research_library/downloaders/arxiv.py@@ -5,10 +5,10 @@ arXiv PDF and Text Downloaderimport refrom dataclasses import dataclassfrom enum import StrEnum-from typing import Dict, Final, Optional+from typing import Callable, Dict, Final, Iterator, Optionalfrom urllib.parse import urlparse-from bs4 import BeautifulSoup, NavigableString, Tag+from bs4 import BeautifulSoup, NavigableString, PageElement, Tagfrom loguru import loggerfrom ...constants import USER_AGENT@@ -34,6 +34,65 @@ class ArxivTextResult:source: ArxivTextSource+def attribute_arxiv_text(text: str, arxiv_id: str) -> str:+ """Append the ``Source: https://arxiv.org/abs/<id>`` attribution line.++ Applied to PDF and API metadata text (not to the HTML rendition), by+ the downloader and by ``DownloadService`` for text it extracts from a+ stored PDF, so text saved with the same provenance labels reads the+ same whichever path produced it.+ """+ return f"{text.rstrip()}\n\nSource: https://arxiv.org/abs/{arxiv_id}"+++class ArxivFullTextStatus(StrEnum):+ """How a full-text-only fetch (``download_full_text``) ended."""++ # Full text was produced (``ArxivFullTextOutcome.result`` holds it).+ TEXT = "text"+ # The PDF was downloaded but extraction produced no text: an+ # image-only scan, or the extraction ceilings hit before any text.+ # The download and the extraction were both paid for.+ PDF_WITHOUT_TEXT = "pdf_without_text"+ # No full text and no PDF bytes, and arXiv answered every request:+ # the HTML leg found no usable rendition (404/410, a non-HTML answer,+ # or a page that is not a rendition) and the PDF request was answered+ # 404/410 or with something that is not a PDF. The paper has no full+ # text to fetch, so a caller budgeting fetches can refund this one.+ NOT_FETCHED = "not_fetched"+ # No full text and no PDF bytes because a request failed rather than+ # being answered: a timeout, a connection error, a 5xx (other than a+ # PDF 503) or other unexpected status, or the decoded-body cap, on+ # either leg. Nothing says the paper lacks full text; the host is+ # failing, so a caller fetching several papers should stop sending it+ # requests instead of paying a timeout per paper.+ FETCH_FAILED = "fetch_failed"+ # As FETCH_FAILED, but arXiv answered the PDF request with HTTP 429 or+ # 503: the host is rate limiting or unavailable, so a caller fetching+ # several papers should stop sending it requests. The PDF leg of+ # ``download_full_text`` makes a single attempt and does not retry+ # into the rate limit.+ RATE_LIMITED = "rate_limited"+++@dataclass(frozen=True, slots=True)+class ArxivFullTextOutcome:+ """Result of ``download_full_text``: the text, and how the fetch ended."""++ status: ArxivFullTextStatus+ result: ArxivTextResult | None = None+++# arXiv asks harvesters to use this host, which carries an up-to-date copy+# of the corpus and is "specifically set aside for programmatic access"+# (https://info.arxiv.org/help/bulk_data.html), rather than arxiv.org,+# whose capacity is kept for interactive readers. It serves the same+# /html/{id} and /pdf/{id} paths. Automated callers (the search engine's+# full-text step) fetch from it; user-initiated library downloads keep+# arxiv.org.+ARXIV_EXPORT_HOST: Final = "export.arxiv.org"++# HTML must be at least this fraction of the PDF text already in hand before it# is allowed to replace it. arXiv answers /html/{id} with a stub for papers that# have no HTML rendition, and such a stub clears the extraction pipeline's 50@@ -55,7 +114,8 @@ MIN_STANDALONE_HTML_TEXT_LENGTH = 2000# Upper bound on the number of <math> elements a rendition may carry before# the TeX rewrite is abandoned in favour of the PDF. The rewrite itself is-# linear (see _rewrite_math_to_tex), so this is not a complexity guard: it+# linear, nested <math> included (see _rewrite_math_to_tex, which rewrites+# only outermost elements), so this is not a complexity guard: it# caps the work the rewrite can be made to do, and nothing more. It does not# bound the BeautifulSoup parse that precedes it, whose cost scales with the# page's total element count rather than its equation count and which every@@ -80,12 +140,41 @@ _MATHML_LOCAL_NAME: Final = re.compile(r"(?:^|:)math$", re.IGNORECASE)_TEX_ANNOTATION_LOCAL_NAME: Final = re.compile(r"(?:^|:)annotation$", re.IGNORECASE)+# The visible-text tier of the ladder below must not read annotation+# markup: <annotation> children of other encodings (application/x-asy, ...)+# and <annotation-xml> (Content MathML) carry hidden machine-readable+# state, not rendered characters. Anchored and suffixed so a literal+# "annotation" matches, "annotation-xml" matches, and nothing longer does.+_HIDDEN_ANNOTATION_LOCAL_NAME: Final = re.compile(+ r"(?:^|:)annotation(?:-xml)?$", re.IGNORECASE+)class ArxivDownloader(HTMLDownloader):"""Download arXiv PDFs and produce text from canonical arXiv sources."""- def __init__(self, timeout: int = 30, language: str = "English"):+ # Set per instance by __init__; the class default covers instances+ # built without it (test doubles, ``__new__``).+ _fetch_host: str = "arxiv.org"++ def __init__(+ self,+ timeout: int = 30,+ language: str = "English",+ *,+ fetch_host: str = "arxiv.org",+ ):+ """``fetch_host`` is the host the HTML and PDF legs request from.++ It is ``arxiv.org`` or ``ARXIV_EXPORT_HOST``; any other value is+ rejected. Attribution (``Source: https://arxiv.org/abs/...``) and+ the response checks are independent of it: both hosts sit inside+ the ``.arxiv.org`` trust boundary ``_is_matching_arxiv_paper_url``+ applies.+ """+ if fetch_host not in ("arxiv.org", ARXIV_EXPORT_HOST):+ raise ValueError("fetch_host must be arxiv.org or export.arxiv.org")+ self._fetch_host = fetch_hostsuper().__init__(timeout=timeout, language=language)session = self.sessionif session is not None:@@ -133,7 +222,7 @@ class ArxivDownloader(HTMLDownloader):skip_reason=f"Could not retrieve full text for arXiv:{arxiv_id}")# Download PDF- pdf_url = f"https://arxiv.org/pdf/{arxiv_id}.pdf"+ pdf_url = self._pdf_url(arxiv_id)logger.info(f"Downloading arXiv PDF: {arxiv_id}")pdf_content = super()._download_pdf(pdf_url)@@ -144,9 +233,19 @@ class ArxivDownloader(HTMLDownloader):)def _download_pdf(- self, url: str, headers: Optional[Dict[str, str]] = None+ self,+ url: str,+ headers: Optional[Dict[str, str]] = None,+ *,+ max_attempts: int = 3,+ on_rate_limited: Optional[Callable[[], None]] = None,+ on_transport_failure: Optional[Callable[[], None]] = None,) -> Optional[bytes]:- """Download PDF from arXiv."""+ """Download PDF from arXiv.++ ``max_attempts``, ``on_rate_limited`` and ``on_transport_failure``+ are passed through to ``BaseDownloader._download_pdf``.+ """# Extract arXiv IDarxiv_id = self._extract_arxiv_id(url)if not arxiv_id:@@ -154,7 +253,7 @@ class ArxivDownloader(HTMLDownloader):return None# Construct PDF URL- pdf_url = f"https://arxiv.org/pdf/{arxiv_id}.pdf"+ pdf_url = self._pdf_url(arxiv_id)logger.info(f"Downloading arXiv PDF: {arxiv_id}")@@ -167,7 +266,13 @@ class ArxivDownloader(HTMLDownloader):"Connection": "keep-alive",}- return super()._download_pdf(pdf_url, headers=enhanced_headers)+ return super()._download_pdf(+ pdf_url,+ headers=enhanced_headers,+ max_attempts=max_attempts,+ on_rate_limited=on_rate_limited,+ on_transport_failure=on_transport_failure,+ )def download_text(self, url: str, pdf_content: bytes | None = None@@ -181,16 +286,121 @@ class ArxivDownloader(HTMLDownloader):result = self.download_text_with_source(url, pdf_content=pdf_content)return result.text if result is not None else None+ def _pdf_url(self, arxiv_id: str) -> str:+ """The PDF URL on ``fetch_host``.++ ``export.arxiv.org`` answers ``/pdf/{id}.pdf`` with a 301 to the+ suffix-less path, and ``requests`` drains a redirect response's body+ in ``resolve_redirects`` before ``SafeSession`` can size-check it,+ so on that host the suffix is left off and the redirect never+ happens. ``arxiv.org`` keeps the URL it has always been sent.+ """+ if self._fetch_host == ARXIV_EXPORT_HOST:+ return f"https://{ARXIV_EXPORT_HOST}/pdf/{arxiv_id}"+ return f"https://arxiv.org/pdf/{arxiv_id}.pdf"+def download_text_with_source(self, url: str, pdf_content: bytes | None = None) -> ArxivTextResult | None:- """Return arXiv text with the exact source that produced it."""+ """Return arXiv text with the exact source that produced it.++ Transport failures on every leg are handled here, not raised: a+ paper whose HTML and PDF legs both fail yields the API metadata+ (``ArxivTextSource.ARXIV_API``) or ``None``.+ """arxiv_id = self._extract_arxiv_id(url)if not arxiv_id:return None- canonical_url = f"https://arxiv.org/abs/{arxiv_id}"+ result, _ = self._html_then_pdf_text(url, arxiv_id, pdf_content)+ if result is not None:+ return result++ api_text = self._fetch_from_arxiv_api(arxiv_id)+ if api_text:+ return ArxivTextResult(+ attribute_arxiv_text(api_text, arxiv_id),+ ArxivTextSource.ARXIV_API,+ )+ return None+ def download_full_text(self, url: str) -> ArxivFullTextOutcome:+ """Return full text only (HTML rendition, then PDF), and how it ended.++ For callers that already hold the abstract: the API metadata leg is+ never requested, because it yields only the abstract. The status+ tells the ways a fetch can end without text apart, so a caller+ budgeting fetches can refund only a paper that has no full text:+ ``NOT_FETCHED`` when arXiv answered that there is none (no+ rendition, and a PDF request answered 404/410 or with no PDF),+ ``FETCH_FAILED`` when a request failed instead of being answered+ (timeout, connection error, a failed DNS lookup or other refusal by+ the URL validator, 5xx, the decoded-body cap, any other request+ error, on either leg), ``RATE_LIMITED`` for a PDF answered 429/503, and+ ``PDF_WITHOUT_TEXT`` for a PDF that downloaded but yielded no text+ (the download and extraction were paid for). A URL naming no paper+ is ``NOT_FETCHED``.++ The PDF leg makes a single attempt: it is not retried on HTTP+ 429/503, timeouts or connection errors, so a fetch costs at most+ two requests (HTML, then PDF). ``FETCH_FAILED`` and+ ``RATE_LIMITED`` tell a caller fetching several papers to stop+ instead of sending a failing host a request (and a timeout) per+ paper. Those give-ups are logged as warnings, not errors.+ """+ arxiv_id = self._extract_arxiv_id(url)+ if not arxiv_id:+ return ArxivFullTextOutcome(ArxivFullTextStatus.NOT_FETCHED)+ rate_limited = False+ transport_failed = False++ def _note_rate_limited() -> None:+ nonlocal rate_limited+ rate_limited = True++ def _note_transport_failure() -> None:+ nonlocal transport_failed+ transport_failed = True++ result, pdf_in_hand = self._html_then_pdf_text(+ url,+ arxiv_id,+ None,+ pdf_max_attempts=1,+ on_pdf_rate_limited=_note_rate_limited,+ on_transport_failure=_note_transport_failure,+ )+ if result is not None:+ return ArxivFullTextOutcome(ArxivFullTextStatus.TEXT, result)+ if pdf_in_hand:+ return ArxivFullTextOutcome(ArxivFullTextStatus.PDF_WITHOUT_TEXT)+ if rate_limited:+ return ArxivFullTextOutcome(ArxivFullTextStatus.RATE_LIMITED)+ if transport_failed:+ return ArxivFullTextOutcome(ArxivFullTextStatus.FETCH_FAILED)+ return ArxivFullTextOutcome(ArxivFullTextStatus.NOT_FETCHED)++ def _html_then_pdf_text(+ self,+ url: str,+ arxiv_id: str,+ pdf_content: bytes | None,+ *,+ pdf_max_attempts: int | None = None,+ on_pdf_rate_limited: Callable[[], None] | None = None,+ on_transport_failure: Callable[[], None] | None = None,+ ) -> tuple[ArxivTextResult | None, bool]:+ """Produce text from the HTML rendition, then the PDF.++ Returns the text (or ``None``) and whether PDF bytes were in hand,+ supplied or downloaded, whether or not they yielded any text.++ ``pdf_max_attempts`` and ``on_pdf_rate_limited`` are forwarded to+ ``_download_pdf`` when the PDF is downloaded; left unset, the PDF+ download keeps its default retries. ``on_transport_failure`` is+ forwarded to the HTML fetch and, with ``pdf_max_attempts``, to the+ PDF download.+ """# PDF bytes already in hand set the quality floor for HTML, so their# text is extracted before HTML is considered.pdf_text = (@@ -198,38 +408,70 @@ class ArxivDownloader(HTMLDownloader):if pdf_content is not Noneelse None)+ pdf_in_hand = pdf_content is not None# HTML is fetched even when PDF bytes are already in hand: preferring# the official HTML rendition is the point of this path, and the PDF# text above is what sets the quality floor it has to clear# (_html_text_beats_pdf_text). That costs one request the PDF-only# path did not make; the caller's retry budget is what bounds it.- html_text = self._download_html_text(arxiv_id)+ if on_transport_failure is None:+ html_text = self._download_html_text(arxiv_id)+ else:+ html_text = self._download_html_text(+ arxiv_id, on_transport_failure=on_transport_failure+ )if html_text and self._html_text_beats_pdf_text(html_text, pdf_text, arxiv_id):- return ArxivTextResult(html_text, ArxivTextSource.ARXIV_HTML)+ return (+ ArxivTextResult(html_text, ArxivTextSource.ARXIV_HTML),+ pdf_in_hand,+ )if pdf_content is None:logger.info(f"Downloading arXiv PDF for full text: {arxiv_id}")- downloaded_pdf = self._download_pdf(url)+ if pdf_max_attempts is None:+ downloaded_pdf = self._download_pdf(url)+ else:+ downloaded_pdf = self._download_pdf(+ url,+ max_attempts=pdf_max_attempts,+ on_rate_limited=on_pdf_rate_limited,+ on_transport_failure=on_transport_failure,+ )if downloaded_pdf is not None:+ pdf_in_hand = Truepdf_text = self.extract_text_from_pdf(downloaded_pdf)if pdf_text:- attributed_text = f"{pdf_text.rstrip()}\n\nSource: {canonical_url}"- return ArxivTextResult(attributed_text, ArxivTextSource.LOCAL_PDF)+ return (+ ArxivTextResult(+ attribute_arxiv_text(pdf_text, arxiv_id),+ ArxivTextSource.LOCAL_PDF,+ ),+ pdf_in_hand,+ )+ return None, pdf_in_hand- api_text = self._fetch_from_arxiv_api(arxiv_id)- if api_text:- attributed_text = f"{api_text.rstrip()}\n\nSource: {canonical_url}"- return ArxivTextResult(attributed_text, ArxivTextSource.ARXIV_API)- return None+ def _download_html_text(+ self,+ arxiv_id: str,+ *,+ on_transport_failure: Callable[[], None] | None = None,+ ) -> str | None:+ """Extract normalized text from official arXiv HTML when usable.- def _download_html_text(self, arxiv_id: str) -> str | None:- """Extract normalized text from official arXiv HTML when usable."""- html_url = f"https://arxiv.org/html/{arxiv_id}"- html, final_url = self._fetch_html_with_final_url(html_url)+ ``on_transport_failure`` is forwarded to the HTML fetch (see+ ``HTMLDownloader._fetch_html_with_final_url``).+ """+ html_url = f"https://{self._fetch_host}/html/{arxiv_id}"+ if on_transport_failure is None:+ html, final_url = self._fetch_html_with_final_url(html_url)+ else:+ html, final_url = self._fetch_html_with_final_url(+ html_url, on_transport_failure=on_transport_failure+ )if not html:return Noneif not self._stayed_on_arxiv_html(final_url, arxiv_id):@@ -261,27 +503,106 @@ class ArxivDownloader(HTMLDownloader):def _tex_for_math_element(math: Tag) -> str:"""The TeX one <math> element carries, or ``""`` when it carries none.- Two sources, annotation first because it is the explicit one: an- ``<annotation encoding="application/x-tex">`` child, then the- ``alttext`` attribute LaTeXML always writes onto the element itself.- An empty annotation falls through rather than abandoning the page --- an element can carry an empty annotation and a usable one beside it, or- an empty annotation and a usable attribute, and there is no reason to- prefer the empty one. Every x-tex annotation is examined for that- reason, not just the first descendant.+ Four sources, each a strictly weaker guarantee than the one before.+ An ``<annotation encoding="application/x-tex">`` child first because+ it is the explicit one; then an+ ``<annotation encoding="application/x-tex+html">`` child, the same+ TeX with the HTML LaTeXML kept around it; then the ``alttext``+ attribute LaTeXML always writes onto the element itself; and finally+ the element's visible MathML text, read with the annotation+ subtrees skipped so annotation state is never mistaken for rendered+ characters, so a bare unannotated equation+ still yields its rendered characters instead of its annotation state+ (#4783). Only annotations are removed: presentation elements that+ lay out without drawing, such as ``<mphantom>``, keep their text in+ this tier. An empty source falls through rather than abandoning the+ page -- an element can carry an empty annotation and a usable one+ beside it, or an empty annotation and a usable attribute, and there+ is no reason to prefer the empty one. Every annotation of each+ encoding is examined for that reason, not just the first descendant+ -- but only the outermost of a nested run: an annotation nested in a+ same-encoding annotation contributes a subset of its ancestor's+ text, so once the ancestor reads as empty every annotation inside it+ does too. Reading only outermost matches keeps their subtrees+ disjoint, so each encoding's search, text extraction included, is+ one linear pass over the element; re-reading every level of a+ nested chain would be quadratic in its depth, and this HTML is+ author-controlled.``<annotation-xml>`` is deliberately not a source: it holds a- different encoding, and the anchored matcher already excludes it.+ different encoding, the anchored matcher above already excludes it,+ and the visible-text tier skips it — along with every other+ non-TeX ``<annotation>`` — in the text it reads, so its hidden+ text can neither supply an empty equation nor pollute a rendered+ one. A node whose only text is annotation text reads as empty and+ takes the PDF exit."""- for annotation in math.find_all(- _TEX_ANNOTATION_LOCAL_NAME,- attrs={"encoding": "application/x-tex"},- ):- tex = annotation.get_text().strip()- if tex:- return tex+ for encoding in ("application/x-tex", "application/x-tex+html"):+ for annotation in ArxivDownloader._outermost_tex_annotations(+ math, encoding+ ):+ tex = annotation.get_text().strip()+ if tex:+ return texalttext = math.get("alttext")- return alttext.strip() if isinstance(alttext, str) else ""+ if isinstance(alttext, str) and alttext.strip():+ return alttext.strip()+ return ArxivDownloader._visible_math_text(math)++ @staticmethod+ def _outermost_tex_annotations(math: Tag, encoding: str) -> Iterator[Tag]:+ """``<annotation encoding=...>`` descendants with no such ancestor.++ Yielded lazily in document order. One iterative walk that does not+ descend into a match, so every node is visited at most once and the+ yielded subtrees are disjoint -- reading each one's text is linear+ in the element's size in total, however deeply matches nest.+ """+ stack: list[Tag] = [+ child for child in reversed(math.contents) if isinstance(child, Tag)+ ]+ while stack:+ node = stack.pop()+ if (+ _TEX_ANNOTATION_LOCAL_NAME.search(node.name or "")+ and node.get("encoding") == encoding+ ):+ yield node+ continue+ stack.extend(+ child+ for child in reversed(node.contents)+ if isinstance(child, Tag)+ )++ @staticmethod+ def _visible_math_text(math: Tag) -> str:+ """``math.get_text(" ", strip=True)`` minus annotation subtrees.++ Hidden machine-readable state -- Content MathML inside+ ``<annotation-xml>``, other encodings inside ``<annotation>`` -- is+ never emitted as the equation's rendered characters. One iterative+ walk that skips those subtrees, so each node is visited once and the+ tree is left untouched. (A ``copy.deepcopy`` of the element with the+ annotations decomposed gives the same text, but bs4's deepcopy+ re-walks the copy on every insert, which is quadratic in the depth+ of nested markup.) Strings are filtered by the same types+ ``get_text`` keeps, so comments and the like stay out.+ """+ types = math.interesting_string_types or Tag.MAIN_CONTENT_STRING_TYPES+ parts: list[str] = []+ stack: list[PageElement] = list(reversed(math.contents))+ while stack:+ node = stack.pop()+ if isinstance(node, Tag):+ if _HIDDEN_ANNOTATION_LOCAL_NAME.search(node.name or ""):+ continue+ stack.extend(reversed(node.contents))+ elif isinstance(node, NavigableString) and type(node) in types:+ stripped = node.strip()+ if stripped:+ parts.append(stripped)+ return " ".join(parts)@staticmethoddef _rewrite_math_to_tex(soup: BeautifulSoup, arxiv_id: str) -> bool:@@ -292,12 +613,18 @@ class ArxivDownloader(HTMLDownloader):a report: the page carries more than MAX_MATH_ELEMENTS equations, or a<math> offers no TeX at all.- "No TeX at all" is narrower than it used to be. The annotation child is- not the only place LaTeXML writes the TeX -- it always writes it into- the ``alttext`` attribute as well, while the parallel <annotation>- markup depends on how arXiv invokes it, so a rendition carrying only- ``alttext`` used to take the PDF exit with its TeX sitting right there- on the element (#6414). Both sources are read now, annotation first.+ "No TeX at all" is narrower than it used to be. The annotation child+ is not the only place LaTeXML writes the TeX -- it always writes it+ into the ``alttext`` attribute as well, while the parallel+ <annotation> markup depends on how arXiv invokes it, so a rendition+ carrying only ``alttext`` used to take the PDF exit with its TeX+ sitting right there on the element (#6414). Both sources are read+ now, annotation first. Partially annotated renditions go further and+ mix TeX-annotated equations with bare MathML (#4783): the recovery+ ladder reads x-tex annotations, then x-tex+html ones, then+ ``alttext``, then the element's visible MathML text, so a node kills+ the page only when it is genuinely empty -- no annotation, no+ attribute, and no rendered characters to keep.Each element is rewritten in place -- renamed to an inline <span>holding the TeX -- rather than with ``Tag.replace_with``. replace_with@@ -306,6 +633,16 @@ class ArxivDownloader(HTMLDownloader):renders this HTML from author-submitted LaTeX, and it is reached onthe search path. Rewriting in place is linear and keeps bs4's ownescaping on serialization.++ Only outermost <math> elements are rewritten. Each one's TeX comes+ from its own subtree (the annotation search, and the visible-text+ tier's walk), so a <math> nested inside another is covered by its+ ancestor and is discarded with the ancestor's children. Visiting+ the nested ones as well would re-read every level of a nested+ chain, making the rewrite quadratic in the nesting depth (nested+ <math> is not valid MathML, but this HTML is author-controlled).+ Outermost elements have disjoint subtrees, so the total work is+ linear in the page size."""math_elements = soup.find_all(_MATHML_LOCAL_NAME)if len(math_elements) > MAX_MATH_ELEMENTS:@@ -318,13 +655,14 @@ class ArxivDownloader(HTMLDownloader):)return False- for math in math_elements:+ for math in ArxivDownloader._outermost_math_elements(soup):tex = ArxivDownloader._tex_for_math_element(math)if not tex:logger.debug(- "arXiv HTML for {} has a <math> element carrying neither a "- 'non-empty <annotation encoding="application/x-tex"> child '- "nor a non-empty alttext attribute; falling back to the PDF",+ "arXiv HTML for {} has a <math> element carrying no "+ "annotation of either TeX encoding, no alttext "+ "attribute, and no visible MathML text; falling back "+ "to the PDF",arxiv_id,)return False@@ -334,6 +672,30 @@ class ArxivDownloader(HTMLDownloader):math.append(NavigableString(tex))return True+ @staticmethod+ def _outermost_math_elements(soup: BeautifulSoup) -> list[Tag]:+ """<math> elements with no <math> ancestor, in document order.++ One iterative walk that does not descend into a matched element,+ so every node is visited at most once.+ """+ outermost: list[Tag] = []+ # Children are pushed in reverse so they pop in document order.+ stack: list[Tag] = [+ child for child in reversed(soup.contents) if isinstance(child, Tag)+ ]+ while stack:+ node = stack.pop()+ if _MATHML_LOCAL_NAME.search(node.name or ""):+ outermost.append(node)+ continue+ stack.extend(+ child+ for child in reversed(node.contents)+ if isinstance(child, Tag)+ )+ return outermost+@staticmethoddef _is_matching_arxiv_paper_url(response_url: str | None, arxiv_id: strdiff --git a/src/local_deep_research/research_library/downloaders/base.py b/src/local_deep_research/research_library/downloaders/base.pyindex 347d96cef8..69a3bdaa64 100644--- a/src/local_deep_research/research_library/downloaders/base.py+++ b/src/local_deep_research/research_library/downloaders/base.py@@ -3,7 +3,7 @@ Base Academic Content Downloader Abstract Class"""from abc import ABC, abstractmethod-from typing import Optional, Dict, Any, NamedTuple+from typing import Any, Callable, Dict, NamedTuple, Optionalfrom enum import Enumimport timeimport requests@@ -14,7 +14,7 @@ from loguru import loggerfrom ...web_search_engines.rate_limiting import (AdaptiveRateLimitTracker,)-from ...security import SafeSession+from ...security import SafeSession, safe_requestsfrom ...utilities.pdf_extraction_limits import (MAX_PDF_EXTRACTED_CHARS,MAX_PDF_EXTRACTION_CPU_SECONDS,@@ -23,6 +23,7 @@ from ...utilities.pdf_extraction_limits import (from ...utilities.pdf_stream_release import PypdfWalkReleaserfrom ...security.log_sanitizer import scrub_errorfrom ...security.ssrf_validator import redact_url_for_log+from ...utilities.resource_utils import safe_close# Import centralized User-Agent from constantsfrom ...constants import USER_AGENT # noqa: F401 - re-exported for backward compatibility@@ -85,6 +86,25 @@ class DownloadResult(NamedTuple):status_code: Optional[int] = None+class _ResponseBodyTooLarge(Exception):+ """A response body exceeded the size cap while being decoded.++ Internal to this module: it separates the body-cap abort (raised by+ ``safe_requests._install_body_guard``'s bounded reader during+ ``response.content``/``response.text`` access) from the+ ``ValueError``s ``SafeSession`` raises for SSRF validation, so the+ retry loop below can label it precisely instead of mislabeling an+ SSRF rejection as a size problem (or vice versa).+ """+++# HTTP statuses that answer "no such document" rather than signalling a+# failing host: a fetch ending on one of these is not reported through the+# ``on_transport_failure`` callbacks of ``_download_pdf`` and+# ``HTMLDownloader._fetch_html_with_final_url``.+_DOCUMENT_ABSENT_STATUSES: frozenset[int] = frozenset({404, 410})++class BaseDownloader(ABC):"""Abstract base class for academic content downloaders."""@@ -252,8 +272,71 @@ class BaseDownloader(ABC):return False+ def _ensure_decoded_body_cap(self, response: requests.Response) -> None:+ """Install the running decoded-byte body guard when SafeSession+ would not have.++ ``SafeSession.send`` installs ``_install_body_guard`` (which+ bounds ``raw.read()``/``read_chunked()`` at+ ``MAX_RESPONSE_SIZE``, counting already-decoded bytes) only when+ ``Content-Length`` is absent or unparseable; a *valid, under-cap*+ ``Content-Length`` gets no body guard at all, so a gzip response+ with a small header can transparently decode past the cap while+ ``response.content`` / ``response.text`` is read. Install the same+ guard for exactly that gap so the decoded body of *this* response+ is bounded regardless of framing.++ This only bounds the body of the final response that callers of+ this method go on to read (``response.content`` in+ ``_download_pdf``, the streamed body in+ ``_fetch_html_with_final_url``). With ``allow_redirects=True``,+ any intermediate redirect responses have their bodies already+ read by ``requests.Session.resolve_redirects`` before this guard+ is installed on the final response, and are not bounded here (see+ #6813).++ The request must have been made with ``stream=True`` for this to+ matter: with ``stream=False``, ``requests.Session.send`` consumes+ the body before returning, i.e. before this guard could wrap+ anything.+ """+ if getattr(response, "raw", None) is None:+ # No raw stream to wrap (the body is already materialised, e.g.+ # a Response built in memory): nothing left to bound here.+ return+ content_length = response.headers.get("Content-Length")+ if not content_length:+ # Absent/empty: SafeSession.send already installed the guard.+ return+ try:+ parts = [+ p.strip() for p in str(content_length).split(",") if p.strip()+ ]+ sizes = {int(p) for p in parts}+ except ValueError:+ # Unparseable: _check_response_size treated it as absent and+ # already installed the guard (differing duplicate values were+ # rejected inside SafeSession.send before we got here).+ return+ if (+ len(sizes) == 1+ and next(iter(sizes)) <= safe_requests.MAX_RESPONSE_SIZE+ ):+ # The one case SafeSession leaves unguarded: a single valid+ # Content-Length within the cap, where the decoded body can+ # still exceed the header (e.g. gzip). Installing the guard on+ # top of an existing one (negative or duplicate CL corner+ # cases) is harmless — both counters share the same threshold.+ safe_requests._install_body_guard(response)+def _download_pdf(- self, url: str, headers: Optional[Dict[str, str]] = None+ self,+ url: str,+ headers: Optional[Dict[str, str]] = None,+ *,+ max_attempts: int = 3,+ on_rate_limited: Optional[Callable[[], None]] = None,+ on_transport_failure: Optional[Callable[[], None]] = None,) -> Optional[bytes]:"""Helper method to download PDF with error handling and retry logic.@@ -262,14 +345,28 @@ class BaseDownloader(ABC):Args:url: The URL to downloadheaders: Optional additional headers+ max_attempts: Attempts made before giving up on HTTP 429/503,+ timeouts and connection errors (default 3). A caller that+ must not retry into a rate-limited host passes 1.+ on_rate_limited: Called once when the download gives up on+ HTTP 429/503, so a caller can stop sending further+ requests to that host. When given, that give-up is logged+ as a warning rather than an error: the caller handles it.+ on_transport_failure: Called once when the download fails+ without the host answering "no such document" (HTTP 404+ or 410) or "not a PDF", and without a 429/503 give-up:+ timeouts and connection errors after the last attempt,+ any other request error, any other non-200 status, the+ decoded-body cap, or an unexpected error. A caller fetching+ several documents uses it to stop instead of paying a+ timeout per document. When given, every one of these+ failures is logged as a warning rather than an error.Returns:PDF content as bytes, or None if download failed"""engine_type = f"pdf_download_{rate_limit_authority(url)}"- max_attempts = 3-logger.debug(f"Downloading PDF from {redact_url_for_log(url)} with adaptive "f"rate limiting (max {max_attempts} attempts)"@@ -287,51 +384,97 @@ class BaseDownloader(ABC):else:request_headers = dict(self.session.headers)- # Make the request+ # Make the request. stream=True is load-bearing: with+ # stream=False, requests.Session.send consumes the body+ # before returning, before _ensure_decoded_body_cap could+ # wrap the reads, so a small-Content-Length gzip body would+ # decode whole and unbounded. Streamed, the guard installed+ # below is what bounds the decoded read of+ # response.content at MAX_RESPONSE_SIZE. That covers the+ # final response only; intermediate redirect bodies are+ # read by requests before the guard exists (#6813).response = self.session.get(url,headers=request_headers,timeout=self.timeout,allow_redirects=True,+ stream=True,)- # Check response- if response.status_code == 200:- if self._is_pdf_content(response):- logger.debug(- f"Successfully downloaded PDF from "- f"{redact_url_for_log(url)} on attempt {attempt}"+ try:+ # Check response+ if response.status_code == 200:+ self._ensure_decoded_body_cap(response)+ try:+ body = response.content+ except ValueError as e:+ raise _ResponseBodyTooLarge(str(e)) from e+ if self._is_pdf_content(response):+ logger.debug(+ f"Successfully downloaded PDF from "+ f"{redact_url_for_log(url)} on attempt {attempt}"+ )+ # Record successful outcome+ self.rate_tracker.record_outcome(+ engine_type=engine_type,+ wait_time=wait_time,+ success=True,+ retry_count=attempt,+ search_result_count=1, # We got the PDF+ )+ return body+ logger.warning(+ f"Response is not a PDF: {response.headers.get('content-type', 'unknown')}")- # Record successful outcome+ # Record failure but don't retry for wrong content typeself.rate_tracker.record_outcome(engine_type=engine_type,wait_time=wait_time,- success=True,+ success=False,retry_count=attempt,- search_result_count=1, # We got the PDF+ error_type="NotPDF",)- return response.content- logger.warning(- f"Response is not a PDF: {response.headers.get('content-type', 'unknown')}"- )- # Record failure but don't retry for wrong content type- self.rate_tracker.record_outcome(- engine_type=engine_type,- wait_time=wait_time,- success=False,- retry_count=attempt,- error_type="NotPDF",- )- return None- if response.status_code in [- 429,- 503,- ]: # Rate limit or service unavailable+ return None+ if response.status_code in [+ 429,+ 503,+ ]: # Rate limit or service unavailable+ logger.warning(+ f"Attempt {attempt}/{max_attempts} - HTTP "+ f"{response.status_code} from {redact_url_for_log(url)}"+ )+ # Record rate limit failure+ self.rate_tracker.record_outcome(+ engine_type=engine_type,+ wait_time=wait_time,+ success=False,+ retry_count=attempt,+ error_type=f"HTTP_{response.status_code}",+ )+ if attempt == max_attempts:+ # A caller that passed on_rate_limited handles+ # the give-up itself (the arXiv full-text step+ # stops and keeps summaries), so it is not an+ # error here; ERROR records also reach the+ # user's browser via frontend_progress_sink.+ give_up = (+ f"Failed to download from "+ f"{redact_url_for_log(url)}: HTTP "+ f"{response.status_code} after {max_attempts} attempts"+ )+ if on_rate_limited is not None:+ logger.warning(give_up)+ on_rate_limited()+ else:+ logger.error(give_up)+ return None+ # Continue retry loop with adaptive wait+ continuelogger.warning(- f"Attempt {attempt}/{max_attempts} - HTTP "- f"{response.status_code} from {redact_url_for_log(url)}"+ f"Failed to download from {redact_url_for_log(url)}: "+ f"HTTP {response.status_code}")- # Record rate limit failure+ # Record failure but don't retry for other status codesself.rate_tracker.record_outcome(engine_type=engine_type,wait_time=wait_time,@@ -339,28 +482,19 @@ class BaseDownloader(ABC):retry_count=attempt,error_type=f"HTTP_{response.status_code}",)- if attempt == max_attempts:- logger.error(- f"Failed to download from "- f"{redact_url_for_log(url)}: HTTP "- f"{response.status_code} after {max_attempts} attempts"- )- return None- # Continue retry loop with adaptive wait- continue- logger.warning(- f"Failed to download from {redact_url_for_log(url)}: "- f"HTTP {response.status_code}"- )- # Record failure but don't retry for other status codes- self.rate_tracker.record_outcome(- engine_type=engine_type,- wait_time=wait_time,- success=False,- retry_count=attempt,- error_type=f"HTTP_{response.status_code}",- )- return None+ if (+ on_transport_failure is not None+ and response.status_code+ not in _DOCUMENT_ABSENT_STATUSES+ ):+ on_transport_failure()+ return None+ finally:+ # stream=True leaves the connection unreleased until the+ # body is consumed or the response is closed; close on+ # every path so non-200/NotPDF responses return their+ # connection to the pool instead of leaking it.+ safe_close(response, "downloader response")except (requests.exceptions.Timeout,@@ -375,10 +509,17 @@ class BaseDownloader(ABC):error_type=type(e).__name__,)if attempt == max_attempts:- logger.opt(exception=False).error(+ give_up = (f"{type(e).__name__} downloading from "f"{redact_url_for_log(url)} after {max_attempts} attempts")+ if on_transport_failure is not None:+ # The caller handles the give-up (see+ # on_transport_failure), so it is not an error here.+ logger.warning(give_up)+ on_transport_failure()+ else:+ logger.opt(exception=False).error(give_up)return Nonelogger.warning(f"Attempt {attempt}/{max_attempts} - {type(e).__name__} "@@ -386,9 +527,13 @@ class BaseDownloader(ABC):)continue # Retry with adaptive waitexcept requests.exceptions.RequestException as e:- logger.opt(exception=False).error(+ request_error = (f"Request error downloading from {redact_url_for_log(url)}")+ if on_transport_failure is not None:+ logger.warning(request_error)+ else:+ logger.opt(exception=False).error(request_error)# Record failure but don't retryself.rate_tracker.record_outcome(engine_type=engine_type,@@ -397,11 +542,41 @@ class BaseDownloader(ABC):retry_count=attempt,error_type=type(e).__name__,)+ if on_transport_failure is not None:+ on_transport_failure()return None- except Exception:- logger.opt(exception=False).error(- f"Unexpected error downloading from {redact_url_for_log(url)}"+ except _ResponseBodyTooLarge:+ # The decoded body passed MAX_RESPONSE_SIZE mid-read (guard+ # installed by _ensure_decoded_body_cap). Not retryable: the+ # body is oversized regardless of attempt count. The+ # exception carries only the byte counts; its detail is+ # kept out of the log line per the sensitive-logging hook.+ logger.warning(+ f"Response body exceeded size cap downloading from "+ f"{redact_url_for_log(url)}")+ self.rate_tracker.record_outcome(+ engine_type=engine_type,+ wait_time=wait_time,+ success=False,+ retry_count=attempt,+ error_type="ResponseBodyTooLarge",+ )+ if on_transport_failure is not None:+ on_transport_failure()+ return None+ except Exception:+ # Includes the ValueError SafeSession raises when the URL+ # fails validation, which is also how a failed DNS lookup+ # surfaces, so an offline machine lands here. A caller that+ # passed on_transport_failure handles it (see the docstring),+ # so it is not an error here; ERROR records reach the+ # user's browser via frontend_progress_sink.+ unexpected_error = f"Unexpected error downloading from {redact_url_for_log(url)}"+ if on_transport_failure is not None:+ logger.warning(unexpected_error)+ else:+ logger.opt(exception=False).error(unexpected_error)# Record failure but don't retryself.rate_tracker.record_outcome(engine_type=engine_type,@@ -410,6 +585,8 @@ class BaseDownloader(ABC):retry_count=attempt,error_type="UnexpectedError",)+ if on_transport_failure is not None:+ on_transport_failure()return Nonereturn Nonediff --git a/src/local_deep_research/research_library/downloaders/html.py b/src/local_deep_research/research_library/downloaders/html.pyindex 0ded4b31ec..bc5d42d970 100644--- a/src/local_deep_research/research_library/downloaders/html.py+++ b/src/local_deep_research/research_library/downloaders/html.py@@ -5,12 +5,13 @@ Downloads and extracts clean text content from HTML web pages.Extraction is handled by the shared pipeline in extraction/pipeline.py."""-from typing import Optional, Dict, Any+from typing import Any, Callable, Dict, Optionalfrom urllib.parse import urlparsefrom loguru import loggerfrom bs4 import BeautifulSoupfrom .base import (+ _DOCUMENT_ABSENT_STATUSES,BaseDownloader,ContentType,DownloadResult,@@ -20,6 +21,7 @@ from .extraction.pipeline import extract_content_with_metadatafrom ...constants import BROWSER_USER_AGENTfrom ...security import sanitize_error_for_clientfrom ...security.ssrf_validator import redact_url_for_log+from ...utilities.resource_utils import safe_closedef _as_markdown_text(value: str) -> str:@@ -159,13 +161,23 @@ class HTMLDownloader(BaseDownloader):return self._fetch_html_with_final_url(url)[0]def _fetch_html_with_final_url(- self, url: str+ self,+ url: str,+ *,+ on_transport_failure: Optional[Callable[[], None]] = None,) -> tuple[Optional[str], Optional[str]]:"""Fetch raw HTML together with the URL that finally served it.Redirects are followed, so the final URL can differ from ``url``.Callers that require the response to stay on a specific path mustcompare the returned URL themselves.++ ``on_transport_failure`` is called once when the fetch fails+ without 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+ as a warning rather than an error, since the caller handles it."""logger.debug("html.fetch_started url={url}",@@ -176,55 +188,88 @@ class HTMLDownloader(BaseDownloader):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, requests reads each+ # intermediate redirect body before the guard exists (#6813).response = self.session.get(url,timeout=self.timeout,allow_redirects=True,+ stream=True,)- if response.status_code == 200:- content_type = response.headers.get("content-type", "").lower()- if (- "text/html" in content_type- or "application/xhtml" in content_type- ):- self.rate_tracker.record_outcome(- engine_type=engine_type,- wait_time=wait_time,- success=True,- retry_count=1,- search_result_count=1,- )- logger.debug(- "html.fetch_succeeded url={url}",+ try:+ if response.status_code == 200:+ content_type = response.headers.get(+ "content-type", ""+ ).lower()+ if (+ "text/html" in content_type+ or "application/xhtml" in content_type+ ):+ self._ensure_decoded_body_cap(response)+ # Read (capped) before recording the outcome, so a+ # body that aborts mid-read is not also counted as+ # a success.+ text = response.text+ self.rate_tracker.record_outcome(+ engine_type=engine_type,+ wait_time=wait_time,+ success=True,+ retry_count=1,+ search_result_count=1,+ )+ logger.debug(+ "html.fetch_succeeded url={url}",+ url=redact_url_for_log(url),+ )+ return text, response.url+ logger.warning(+ "html.fetch_unexpected_content_type url={url} status={status}",url=redact_url_for_log(url),+ status=response.status_code,)- return response.text, response.url+ return None, Nonelogger.warning(- "html.fetch_unexpected_content_type url={url} status={status}",+ "html.fetch_failed url={url} status={status}",url=redact_url_for_log(url),status=response.status_code,)+ 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}",+ )+ if (+ on_transport_failure is not None+ and response.status_code not in _DOCUMENT_ABSENT_STATUSES+ ):+ on_transport_failure()return None, None- logger.warning(- "html.fetch_failed url={url} status={status}",- url=redact_url_for_log(url),- status=response.status_code,- )- 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}",- )- return None, None+ finally:+ # stream=True leaves the connection unreleased until the+ # body is consumed or the response is closed.+ safe_close(response, "HTML download response")except Exception as e:- logger.opt(exception=False).error(- "html.fetch_error url={url}",- url=redact_url_for_log(url),- )+ 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}",+ url=redact_url_for_log(url),+ )+ else:+ logger.opt(exception=False).error(+ "html.fetch_error url={url}",+ url=redact_url_for_log(url),+ )self.rate_tracker.record_outcome(engine_type=engine_type,wait_time=wait_time,@@ -232,6 +277,8 @@ class HTMLDownloader(BaseDownloader):retry_count=1,error_type=type(e).__name__,)+ if on_transport_failure is not None:+ on_transport_failure()return None, Nonedef _extract_content(self, html: str, url: str) -> Optional[Dict[str, Any]]:diff --git a/src/local_deep_research/research_library/services/download_service.py b/src/local_deep_research/research_library/services/download_service.pyindex af42b01ad8..fde7c5559a 100644--- a/src/local_deep_research/research_library/services/download_service.py+++ b/src/local_deep_research/research_library/services/download_service.py@@ -24,7 +24,7 @@ from sqlalchemy.orm import Sessionimport pdfplumberfrom pypdf import PdfReader-from ...utilities.arxiv import is_arxiv_paper_url+from ...utilities.arxiv import extract_arxiv_id, is_arxiv_paper_urlfrom ...utilities.type_utils import unwrap_settingfrom ...constants import FILE_PATH_SENTINELS, FILE_PATH_TEXT_ONLYfrom ...database.models.download_tracker import (@@ -77,7 +77,7 @@ from ..downloaders import (OpenAlexDownloader,GenericDownloader,)-from ..downloaders.arxiv import ArxivTextSource+from ..downloaders.arxiv import ArxivTextSource, attribute_arxiv_textfrom ..extraction_catalog import (ExtractionMethodExtra,ExtractionSourceExtra,@@ -874,6 +874,54 @@ class DownloadService:logger.info(f"Download failed with reason: {error_msg}")return False, error_msg, status_code+ # Produce the canonical text BEFORE the persistence block.+ # download_text_with_source may issue a network (HTML) request,+ # and holding an uncommitted write transaction (Document row ++ # save_pdf blob) open across that round-trip extends the write+ # lock for the full network latency. Producing text first keeps+ # the PDF persistence a short transaction that commits before+ # the best-effort text save opens. Text production and+ # persistence both stay best-effort: a failure in either must+ # not fail the PDF download itself (see the commit and the+ # guard around _save_text_with_db below).+ text_details: tuple[str, str, str] | None = None+ try:+ if isinstance(selected_downloader, ArxivDownloader):+ logger.info(+ f"Producing canonical arXiv text for: {resource.title[:50]}"+ )+ arxiv_text = selected_downloader.download_text_with_source(+ url,+ pdf_content=pdf_content,+ )+ if arxiv_text is not None:+ extraction_method, extraction_source = (+ _arxiv_text_provenance(arxiv_text.source)+ )+ text_details = (+ arxiv_text.text,+ extraction_method,+ extraction_source,+ )+ else:+ logger.info(+ f"Extracting text from downloaded PDF for: {resource.title[:50]}"+ )+ text = self._extract_text_from_pdf(pdf_content)+ if text:+ text_details = (text, "pdf_extraction", "local_pdf")++ if text_details is None:+ logger.warning(+ f"Text production returned empty text for: {resource.title[:50]}"+ )+ except Exception:+ logger.exception(+ "Failed to produce text after PDF download, "+ "but PDF download succeeded"+ )+ text_details = None+# Get PDF storage mode setting. Resolve through the operator gate# BEFORE any PDF is written: a stored value or an# LDR_RESEARCH_LIBRARY_PDF_STORAGE_MODE env override could still@@ -1012,51 +1060,36 @@ class DownloadService:# Link document to default Library collectionensure_in_collection(session, doc_id, library_collection_id)- # Update attempt- attempt.succeeded = True- attempt.bytes_downloaded = len(pdf_content)-- if pdf_storage_mode == "database":- logger.info(- f"Successfully stored PDF in database: {resource.url}"- )- elif pdf_storage_mode == "filesystem":- logger.info(f"Successfully downloaded: {tracker.file_path}")- else:- logger.info(f"Successfully extracted text from: {resource.url}")-- # Produce and save text only after the PDF has been stored.- try:- text_details: tuple[str, str, str] | None- if isinstance(selected_downloader, ArxivDownloader):- logger.info(- f"Producing canonical arXiv text for: {resource.title[:50]}"- )- arxiv_text = selected_downloader.download_text_with_source(- url,- pdf_content=pdf_content,- )- if arxiv_text is None:- text_details = None- else:- extraction_method, extraction_source = (- _arxiv_text_provenance(arxiv_text.source)- )- text_details = (- arxiv_text.text,- extraction_method,- extraction_source,- )- else:- logger.info(- f"Extracting text from downloaded PDF for: {resource.title[:50]}"- )- text = self._extract_text_from_pdf(pdf_content)- text_details = (- (text, "pdf_extraction", "local_pdf") if text else None- )+ # Commit the PDF persistence as its own transaction BEFORE the+ # best-effort text save below. Until this point the attempt+ # row, the Document row, the PDF blob, and the collection+ # link are all uncommitted — the only commit used to be the+ # caller's, at the end of download_resource. _save_text_with_db+ # rolls the whole session back before re-raising (issue+ # #3827), so a DB error in the text save would have discarded+ # every one of those writes while the caller went on to mark+ # the queue COMPLETED and record a retry success — the user is+ # told success and the database keeps nothing. Committing here+ # bounds that rollback to the text changes. download_resource's+ # later commit stays correct: it simply opens a fresh+ # transaction and persists the retry/queue bookkeeping that+ # follows this call.+ session.commit()- if text_details is not None:+ if text_details is not None:+ # Text persistence stays best-effort, mirroring the+ # production step above. _save_text_with_db re-raises+ # after its own full-session rollback (issue #3827); with+ # the PDF transaction already committed above, that+ # rollback can no longer discard the PDF persistence. The+ # re-raised DB error (IntegrityError on autoflush,+ # OperationalError, ...) is still a local text-save+ # problem that must not fail an already-successful PDF+ # download, which is what the outer except would do: flip+ # tracker.is_accessible to a false 404 signal and consume+ # the retry budget. Catch, log, and keep the successful+ # PDF outcome; the text is re-extracted on a later pass.+ try:text, extraction_method, extraction_source = text_details# Get the document ID we just created/updatedpdf_doc = get_document_for_resource(session, resource)@@ -1074,15 +1107,24 @@ class DownloadService:logger.info(f"Successfully produced and saved text for: {resource.title[:50]}")- else:- logger.warning(- f"Text production returned empty text for: {resource.title[:50]}"+ except Exception:+ logger.exception(+ "Failed to save text after PDF download, "+ "but PDF download succeeded")- except Exception:- logger.exception(- "Failed to produce text after PDF download, but PDF download succeeded"++ # Update attempt+ attempt.succeeded = True+ attempt.bytes_downloaded = len(pdf_content)++ if pdf_storage_mode == "database":+ logger.info(+ f"Successfully stored PDF in database: {resource.url}")- # Text production is best-effort after a successful PDF download.+ elif pdf_storage_mode == "filesystem":+ logger.info(f"Successfully downloaded: {tracker.file_path}")+ else:+ logger.info(f"Successfully extracted text from: {resource.url}")return True, None, status_code@@ -1337,8 +1379,8 @@ class DownloadService:# Canonical arXiv sources, HTML first. This is network-bearing,# so it applies the retry gate itself; when that denies it, it- # returns None rather than a verdict so the local-only strategies- # below still run.+ # only reads the stored PDF and otherwise returns None rather+ # than a verdict, so the local-only strategies below still run.result = self._try_arxiv_text_extraction(session, resource)if result is not None:self._record_retry_attempt(resource, result, session)@@ -1482,10 +1524,11 @@ class DownloadService:# is saved: the three ``_save_text_with_db`` calls fed by it (in# ``_download_pdf``, ``_try_existing_pdf_extraction`` and# ``_fallback_pdf_extraction``), plus the ``_save_text_with_db``- # calls in ``_try_arxiv_text_extraction`` and- # ``_try_api_text_extraction`` for downloader text (arXiv PDF text- # among it) that ``BaseDownloader.extract_text_from_pdf`` bounds- # the same way.+ # calls in ``_try_arxiv_text_extraction``,+ # ``_text_from_cached_pdf`` (the stored-PDF read on a retry or+ # egress denial) and ``_try_api_text_extraction`` for downloader+ # text (arXiv PDF text among it) that+ # ``BaseDownloader.extract_text_from_pdf`` bounds the same way.resource.document_id = doc.idsession.commit()@@ -1556,17 +1599,31 @@ class DownloadService:None means "this path does not apply", never "this resource has notext": the caller must go on to the local-only strategies. A URL that- names no paper and an exhausted retry budget both return None, the- latter because this path is the only network-bearing one that runs- ahead of _try_existing_pdf_extraction. Deciding the whole call here- would have denied a resource with a stored PDF the pure filesystem- read it used to get (download_as_text applies the same gate itself,- after that read, so the budget still holds).+ names no paper returns None. So does an exhausted retry budget once+ the stored PDF has been tried, because this path is the only+ network-bearing one that runs ahead of _try_existing_pdf_extraction.+ Deciding the whole call here would have denied a resource with a+ stored PDF the local read it used to get (download_as_text applies+ the same gate itself, after that read, so the budget still holds).++ Both network denials read the stored PDF first, entirely locally,+ through _text_from_cached_pdf. That reader loads the PDF through+ PDFStorageManager, so it covers the default database storage, where+ the document has no file path and _try_existing_pdf_extraction+ finds nothing. Text produced that way satisfies the call. Otherwise+ (no stored PDF, no text, or a failed read or save) a retry denial+ returns None and an egress denial stands with its own reason."""url = resource.url or ""if not is_arxiv_paper_url(url):return None+ # Retry gate before any network access. A denial still reads the+ # stored PDF, which makes no network request and so is outside what+ # the retry gate limits. Only a success is returned from here;+ # anything else returns None rather than a verdict, so the+ # local-only strategies below still run and download_as_text's own+ # gate, after them, returns the denial (so the budget still holds).if self.retry_manager:decision = self.retry_manager.should_retry_resource(resource.id)if not decision.can_retry:@@ -1575,6 +1632,16 @@ class DownloadService:resource.id,decision.reason,)+ try:+ cached_outcome = self._text_from_cached_pdf(+ session, resource+ )+ except Exception:+ safe_rollback(session, "_try_arxiv_text_extraction")+ logger.exception("Stored arXiv PDF text extraction failed")+ return None+ if cached_outcome is not None and cached_outcome[0]:+ return cached_outcomereturn Nonetry:@@ -1584,33 +1651,28 @@ class DownloadService:allowed, reason = self._check_url_against_policy(url)if not allowed:+ # Egress policy refuses the network, but a stored PDF can+ # still produce text entirely locally before the denial+ # stands. Only a success replaces the denial: a failed+ # read or save must not bury the egress_policy_denied+ # reason the caller records.+ try:+ cached_outcome = self._text_from_cached_pdf(+ session, resource+ )+ except Exception:+ safe_rollback(session, "_try_arxiv_text_extraction")+ logger.exception("Stored arXiv PDF text extraction failed")+ cached_outcome = None+ if cached_outcome is not None and cached_outcome[0]:+ return cached_outcomereturn False, f"egress_policy_denied:{reason}"pdf_content: bytes | None = Nonepdf_document_id: str | None = None- pdf_document = get_document_for_resource(session, resource)- if (- pdf_document is not None- and getattr(pdf_document, "status", None)- in {DocumentStatus.COMPLETED, DocumentStatus.COMPLETED.value}- and getattr(pdf_document, "file_type", None) == "pdf"- ):- settings = self.settings- if settings is None:- return False, "Download settings unavailable"- pdf_storage_mode = resolve_pdf_storage_mode(- settings.get_setting(- "research_library.pdf_storage_mode", "none"- )- )- pdf_manager = PDFStorageManager(- library_root=Path(self.library_root),- storage_mode=pdf_storage_mode,- legacy_root=Path(self.legacy_library_root),- )- pdf_content = pdf_manager.load_pdf(pdf_document, session)- if pdf_content is not None:- pdf_document_id = getattr(pdf_document, "id")+ cached_pdf = self._load_cached_arxiv_pdf(session, resource)+ if cached_pdf is not None:+ pdf_content, pdf_document_id = cached_pdfif pdf_content is None:arxiv_text = downloader.download_text_with_source(url)@@ -1653,6 +1715,76 @@ class DownloadService:return True, None+ def _load_cached_arxiv_pdf(+ self, session: Session, resource+ ) -> Tuple[bytes, str] | None:+ """Return (pdf_bytes, document_id) for a stored completed PDF."""+ pdf_document = get_document_for_resource(session, resource)+ if (+ pdf_document is None+ or getattr(pdf_document, "status", None)+ not in {DocumentStatus.COMPLETED, DocumentStatus.COMPLETED.value}+ or getattr(pdf_document, "file_type", None) != "pdf"+ ):+ return None+ settings = self.settings+ if settings is None:+ return None+ pdf_storage_mode = resolve_pdf_storage_mode(+ settings.get_setting("research_library.pdf_storage_mode", "none")+ )+ pdf_manager = PDFStorageManager(+ library_root=Path(self.library_root),+ storage_mode=pdf_storage_mode,+ legacy_root=Path(self.legacy_library_root),+ )+ pdf_content = pdf_manager.load_pdf(pdf_document, session)+ if pdf_content is None:+ return None+ return pdf_content, getattr(pdf_document, "id")++ def _text_from_cached_pdf(+ self, session: Session, resource+ ) -> Optional[Tuple[bool, Optional[str]]]:+ """Produce text from the stored PDF without any network access.++ Used when the egress policy or the retry gate denies the network+ but the PDF downloaded by an earlier attempt is still on hand. Returns None when there is+ no usable stored PDF or it yields no text, so the caller's verdict+ stands; a completed extraction returns (True, None).+ """+ cached_pdf = self._load_cached_arxiv_pdf(session, resource)+ if cached_pdf is None:+ return None+ pdf_content, pdf_document_id = cached_pdf+ text = ArxivDownloader.extract_text_from_pdf(pdf_content)+ if not text:+ return None+ # Same attribution download_text_with_source gives PDF text saved+ # with these labels. Callers only reach here for an arXiv paper+ # URL, so the id is always present.+ arxiv_id = extract_arxiv_id(resource.url or "")+ if arxiv_id:+ text = attribute_arxiv_text(text, arxiv_id)+ try:+ _ = self._save_text_with_db(+ resource,+ text,+ session,+ extraction_method="pdf_extraction",+ extraction_source="local_pdf",+ pdf_document_id=pdf_document_id,+ )+ session.commit()+ except Exception as exc:+ safe_rollback(session, "_try_arxiv_text_extraction")+ logger.exception("Failed to save local arXiv PDF text")+ safe_error = sanitize_error_for_client(+ f"Failed to extract arXiv text: {exc}"+ )+ return False, safe_error+ return True, None+def _try_existing_pdf_extraction(self, session, resource, resource_id: int) -> Optional[Tuple[bool, Optional[str]]]:diff --git a/src/local_deep_research/utilities/arxiv_api.py b/src/local_deep_research/utilities/arxiv_api.pyindex c49486f76d..91206123f1 100644--- a/src/local_deep_research/utilities/arxiv_api.py+++ b/src/local_deep_research/utilities/arxiv_api.py@@ -25,6 +25,7 @@ from typing import ()import arxiv+import requestsfrom requests import PreparedRequestfrom ..security import SafeSession@@ -95,15 +96,6 @@ class ArxivPaper(Protocol):@propertydef authors(self) -> Sequence[ArxivAuthor]: ...- @property- def pdf_url(self) -> str | None: ...-- def download_pdf(- self,- dirpath: str = "./",- filename: str = "",- ) -> str: ...-_SORT_CRITERIA: Final = {ArxivSortCriterion.RELEVANCE: arxiv.SortCriterion.Relevance,@@ -205,25 +197,55 @@ def _policy_arxiv_client("""Yield an ``arxiv.Client`` adapted to the shared arXiv API policy.The client is constructed through the ``arxiv.Client`` module attribute- with ``delay_seconds=0`` because the shared gate owns spacing. Its- discarded default session is closed, and a gated- :class:`_GatedArxivSession` is pinned onto the client. The adapted+ with ``delay_seconds=0`` because the shared gate owns spacing.+ :func:`_install_gated_session` then closes the discarded default+ session and pins a gated :class:`_GatedArxivSession` onto the+ client, raising ``ImportError`` if the client's private ``_session``+ attribute is missing or not a ``requests.Session``. The adaptedsession is closed on exit for both normal and exceptional scopes."""constructor_kwargs: dict[str, int] = {"delay_seconds": 0}if page_size is not None:constructor_kwargs["page_size"] = page_sizeclient = arxiv.Client(**constructor_kwargs)- discarded_session = client._session- safe_close(discarded_session, "discarded arXiv client session")- adapted_session = _GatedArxivSession()- client._session = adapted_session+ adapted_session = _install_gated_session(client)try:yield clientfinally:safe_close(adapted_session, "adapted arXiv client session")+def _install_gated_session(client: arxiv.Client) -> _GatedArxivSession:+ """Install the gate-enforcing session on ``client`` or fail loudly.++ ``arxiv.Client`` keeps its HTTP transport on the private ``_session``+ attribute (a ``requests.Session`` in arxiv 2.4.0, 2.4.1 and 4.0.1;+ pyproject.toml does not pin the version for this guard's sake, since+ the guard fails closed). A future release renaming or retyping that+ attribute would leave the client's default session in place and+ silently bypass the shared rate-limit gate, so the mutation is+ guarded: anything other than a ``requests.Session`` at ``_session``+ raises ``ImportError`` with maintainer guidance instead of shipping+ an ungated client. The discarded default session is closed, a+ :class:`_GatedArxivSession` is installed in its place, and it is+ returned so the caller can close it on scope exit.+ """+ discarded_session = getattr(client, "_session", None)+ if not isinstance(discarded_session, requests.Session):+ raise ImportError(+ "arxiv.Client no longer exposes a requests.Session at "+ "_session, so the shared arXiv rate-limit gate cannot be "+ "installed. The installed arxiv release changed the client "+ "internals; adapt utilities/arxiv_api.py to them, or constrain "+ "arxiv to a release that keeps a requests.Session at _session "+ "(2.4.0, 2.4.1 and 4.0.1 do).",+ )+ safe_close(discarded_session, "discarded arXiv client session")+ adapted_session = _GatedArxivSession()+ client._session = adapted_session+ return adapted_session++def fetch_arxiv_results(request: ArxivRequest) -> list[ArxivPaper]:"""Fetch and materialize one typed arXiv request under shared policy."""match request:diff --git a/src/local_deep_research/utilities/citation_normalizer.py b/src/local_deep_research/utilities/citation_normalizer.pyindex f5476d728c..75a1df295a 100644--- a/src/local_deep_research/utilities/citation_normalizer.py+++ b/src/local_deep_research/utilities/citation_normalizer.py@@ -8,8 +8,10 @@ Each engine has its own dict shape; this module handles the differences.import refrom datetime import datefrom typing import Any, Optional+from urllib.parse import urlparsefrom .arxiv import extract_arxiv_id as extract_arxiv_id_from_url+from .arxiv import is_arxiv_family_url__all__ = [@@ -194,6 +196,48 @@ def _parse_date(source: dict) -> tuple[Optional[date], Optional[int]]:return None, year+_HOST_LABEL = r"[a-z0-9](?:[a-z0-9-]*[a-z0-9])?"+_PLAIN_HOST_RE = re.compile(rf"{_HOST_LABEL}(?:\.{_HOST_LABEL})*")+++def _with_scheme_for_arxiv_host(url: str) -> str:+ """Prefix ``https://`` onto a scheme-less arXiv-family link.++ The leading segment (up to the first ``/``, lower-cased, trailing dots+ dropped) must be a plain DNS name -- dot-separated labels of ASCII+ letters, digits and inner hyphens -- on an arXiv-family host as the+ strict parser defines it (:func:`is_arxiv_family_url`): ``arxiv.org``,+ ``ar5iv.org`` or a subdomain of either (``www.``, ``export.``,+ ``ar5iv.labs.``). Only then does the link get a scheme; any other+ scheme-less string is returned unchanged. So is any string containing+ ``://`` anywhere (even only in its query) or one ``urlparse`` reads as+ having a scheme (``arxiv.org:443/...``), so such links yield no id.+ The strict parser applied afterwards still decides whether the result+ is an arXiv paper. A string ``urlparse`` rejects outright (an+ unbalanced ``[`` or ``]`` in the netloc, or a netloc NFKC folds into a+ delimiter) is returned unchanged too, rather than raising out of+ :func:`normalize_citation`; the strict parser rejects it in turn.+ """+ if "://" in url:+ return url+ try:+ has_scheme = bool(urlparse(url).scheme)+ except ValueError:+ return url+ if has_scheme:+ return url+ host = url.split("/", 1)[0].lower().rstrip(".")+ # A plain DNS-name host only: a backslash, "@", ":", an empty or+ # hyphen-edged label, or any other delimiter in the leading segment+ # could make the parsed host differ from what a browser would open, so+ # such input is left as it is.+ if not _PLAIN_HOST_RE.fullmatch(host):+ return url+ if is_arxiv_family_url(f"https://{host}/"):+ return f"https://{url}"+ return url++def _extract_arxiv_id(source: dict) -> Optional[str]:"""Extract arXiv ID from URL or explicit field."""arxiv_id = source.get("arxiv_id")@@ -201,7 +245,11 @@ def _extract_arxiv_id(source: dict) -> Optional[str]:return arxiv_idurl = source.get("link", "") or source.get("url", "")- return extract_arxiv_id_from_url(url) if isinstance(url, str) else None+ return (+ extract_arxiv_id_from_url(_with_scheme_for_arxiv_host(url))+ if isinstance(url, str)+ else None+ )def _extract_doi(source: dict) -> Optional[str]:diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py b/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.pyindex f2c9ab6124..76092f7ce2 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py@@ -1,20 +1,10 @@-import osimport re-import uuid-from pathlib import Pathfrom typing import Any, Dict, List, Optionalfrom langchain_core.language_models import BaseLLMfrom requests.exceptions import RequestException-from ...config.paths import get_data_directoryfrom ...constants import SNIPPET_LENGTH_SHORT-from ...security import SafeSession-from ...security.directory_creation import (- DirectoryCreationSecurityError,- create_directory,-)-from ...security.safe_requests import DEFAULT_TIMEOUT, MAX_RESPONSE_SIZEfrom ...security.secure_logging import loggerfrom ...utilities.arxiv_api import (ArxivIdRequest,@@ -37,6 +27,37 @@ _ARXIV_ID_RE = re.compile()+class FullTextNotExtractedError(Exception):+ """The paper's PDF was downloaded but produced no text.++ Raised by ``ArXivSearchEngine._fetch_full_text`` so the caller can tell+ it apart from a failed fetch (``None``): the download and the+ extraction were paid for, so the full-text budget stays spent.+ """+++class FullTextFetchFailedError(Exception):+ """A full-text request to arXiv failed instead of being answered.++ Raised by ``ArXivSearchEngine._fetch_full_text`` when the paper's HTML+ or PDF request timed out, could not connect, got a 5xx or other+ unexpected status, or hit the decoded-body cap, and no text arrived.+ Nothing says the paper lacks full text: the host is failing, so+ ``_get_full_content`` makes no further full-text fetches for the rest+ of that call instead of paying a request (and a timeout) per paper.+ """+++class FullTextRateLimitedError(FullTextFetchFailedError):+ """arXiv answered the paper's PDF request with HTTP 429 or 503.++ Raised by ``ArXivSearchEngine._fetch_full_text``. The host is rate+ limiting or unavailable: as for any ``FullTextFetchFailedError``,+ ``_get_full_content`` makes no further full-text fetches for the rest+ of that call instead of sending a request per paper.+ """++class ArXivSearchEngine(BaseSearchEngine):"""arXiv search engine implementation with two-phase approach"""@@ -71,8 +92,21 @@ class ArXivSearchEngine(BaseSearchEngine):sort_by: Sorting criteria ('relevance', 'lastUpdatedDate', or 'submittedDate')sort_order: Sort order ('ascending' or 'descending')include_full_text: Whether to include full paper content in results (downloads PDF)- download_dir: Directory to download PDFs to (if include_full_text is True)- max_full_text: Maximum number of PDFs to download and process (default: 1)+ download_dir: Gates full-text fetching -- full text is only+ attempted when include_full_text is True and this is set.+ The value itself is not used: _fetch_full_text routes+ through the shared HTML-first ArxivDownloader (issue #4783),+ which keeps the text in memory and writes nothing to disk.+ max_full_text: Maximum number of papers whose full text is+ fetched (default: 1). A paper counts once full text or its+ PDF arrived, even if the PDF yielded no text. A paper arXiv+ answered has no full text (no rendition, and its PDF answered+ 404/410 or with no PDF) does not count, so a later paper+ still gets the attempt. A request that failed instead of+ being answered (timeout, connection error, 5xx, HTTP+ 429/503) counts, and stops full-text fetching for the+ remaining papers of that search, so a failing host costs+ one paper's requests rather than one per paper.llm: Language model for relevance filteringmax_filtered_results: Maximum number of results to keep after filteringsettings_snapshot: Settings snapshot for thread context@@ -162,262 +196,130 @@ class ArXivSearchEngine(BaseSearchEngine):return candidatereturn None- @staticmethod- def _enforce_response_size_cap(written: int) -> None:- """Raise if a streamed PDF body has grown past ``MAX_RESPONSE_SIZE``.-- Split out from ``_download_pdf_safely``'s streaming loop so the- ``raise`` isn't directly inside that loop's own cleanup- ``try``/``except`` block.- """- if written > MAX_RESPONSE_SIZE:- raise ValueError(- f"arXiv PDF body exceeded {MAX_RESPONSE_SIZE} bytes "- "while streaming"- )-- def _download_pdf_safely(self, paper: Any, dirpath: str) -> str:- """Download a paper PDF through the SSRF-validated ``SafeSession``.-- Invariant: every arXiv PDF fetch made *by this engine*- (``ArXivSearchEngine``) goes through this gate. ``SafeSession``- applies SSRF pre-validation and DNS pinning to this fetch. This- replaces ``arxiv.Result.download_pdf``, which fetches via- ``urllib.request.urlretrieve`` and therefore bypasses all of those- controls. Metadata queries use ``fetch_arxiv_results`` from- ``utilities.arxiv_api``, which supplies its own ``SafeSession``- with a fixed timeout and the shared API request pacing gate.-- It is also narrower than "every arXiv PDF fetch in this codebase":- ``research_library/downloaders/arxiv.py``'s ``ArxivDownloader``- (via ``BaseDownloader._download_pdf``) independently fetches- ``https://arxiv.org/pdf/{id}.pdf`` — the public host, with the- ``.pdf`` suffix this module omits specifically to dodge the- redirect-drain gap described below. It does use ``SafeSession``,- but sends ``Accept-Encoding: gzip, deflate, br`` and reads- ``response.content`` with no ``stream=True``, so it has neither- this call site's running-byte-count cap nor its identity-encoding- best-effort measure. That is a separate, untouched call site —- fixing it is out of scope here.-- The filename changes from the old path's ``<id>.<sanitized- title>.pdf`` (``arxiv.Result._get_default_filename``) to- ``<id>.pdf`` here — a behavior change worth knowing about even- though nothing in this codebase parses the filename back apart.-- No ``.pdf`` suffix is appended to the request URL: arxiv 2.4.1's- own Atom ``pdf_url`` (what ``arxiv.Result.download_pdf`` fetches)- has none either, e.g. ``"http://arxiv.org/pdf/2101.00001v1"``.- Appending ``.pdf`` makes ``export.arxiv.org`` answer with a 301 to- the suffix-less path, and that redirect response's own body is- drained by ``requests.Session.send()``'s internal- ``resolve_redirects()`` (``resp.content # Consume socket``)- *before* it is ever handed to ``SafeSession.send()`` for a size- check — so an oversized redirect body would be read into memory- unchecked. Omitting the suffix removes that hop entirely, which is- the minimal fix; it is not a fix to ``SafeSession`` itself (every- redirect hop has this gap, not just this call site). This- redirect-drain gap in ``SafeSession.send()`` has no tracking issue- filed for it yet — it is untracked, and distinct from the- chunked-body gap discussed below (which does have one, #6180).-- This call passes ``stream=True`` and writes the body to- ``target_path`` in bounded chunks via ``iter_content`` rather than- reading ``response.content`` — unlike what an earlier version of- this comment claimed, ``stream=True`` alone does not bound memory;- `research_library/downloaders/generic.py`'s ``stream=True`` usage- is not a precedent for this pattern, since it never reads the body- at all (a status-code-only diagnostic probe). The running byte- count enforced while streaming is also the actual guard against a- gzip/deflate decompression bomb here: for a valid, under-cap- ``Content-Length``, ``SafeSession._check_response_size`` installs- no body guard at all (see ``safe_requests.py``), and ``requests``- (unlike the old ``urllib``-based path) sends- ``Accept-Encoding: gzip`` by default, so a small compressed- response could otherwise decompress far past any header-level- check. This fetch instead sends ``Accept-Encoding: identity`` —- matching what the old ``urlretrieve``-based path effectively did- (``urllib`` does not request compression) — as a best-effort- signal, since a PDF is already-compressed binary and gains- nothing from gzip transfer. This does not remove the- decompression-bomb vector outright: ``urllib3`` decodes based on- the *response*'s ``Content-Encoding`` header, not the request's- ``Accept-Encoding`` one, so a server that ignores the request- header and gzips the body anyway would still be transparently- decoded by ``iter_content`` here. What actually bounds a- decompression bomb, with or without gzip, is the running byte- count enforced while streaming above — it is computed over the- already-decoded chunks ``iter_content`` yields, so it caps the- decompressed size regardless of what encoding the origin used.-- Connection release: if ``SafeSession``'s response-size cap rejects- an over-limit ``Content-Length`` response, that ``ValueError`` is- raised *inside* ``SafeSession.send()`` — i.e. inside the- ``session.get(...)`` call itself, before the ``with ... as- response:`` statement below ever binds. So on that path the- connection is released by ``_check_response_size`` calling- ``response.close()`` internally, not by this function's context- manager; the context manager only covers releasing the connection- for responses that *do* make it past that check (including this- function's own errors raised while streaming the body).-- The ``Content-Length``-absent case is covered since #6180. The cap- installs a guard on ``response.raw.read()``- (``_install_body_guard``), which used to run only when the- connection was delimited by the socket closing: a- ``Transfer-Encoding: chunked`` body, the common case for a CDN- serving a PDF of unknown length, is read through ``urllib3``'s- ``HTTPResponse.read_chunked()`` instead, which pulls bytes off the- socket via ``self._fp._safe_read()`` and never calls the patched- ``read()``. That generator is wrapped against the same counter now,- so both framings are bounded. #6172, about callers that never set- ``stream=True`` at all, is a separate issue (this call does set it).-- This function's own running byte count during streaming is still- what bounds the *decoded* size, which is what a decompression bomb- turns on; the cap counts what it is handed.+ def _fetch_full_text(self, paper: Any) -> Optional[str]:+ """Fetch a paper's full text through the shared HTML-first downloader.++ This routes ``ArXivSearchEngine``'s full-text step through+ ``ArxivDownloader.download_full_text`` (issue #4783): the+ equation-preserving official arXiv HTML rendition when one exists,+ then the arXiv PDF, and never the API metadata leg that+ ``download_text_with_source`` would add. That replaces the pypdf+ extraction this engine used to inline.++ The downloader is imported lazily: importing+ ``research_library.downloaders.arxiv`` at module scope would+ pull the whole download stack into every engine import, and+ its base module imports back into+ ``web_search_engines.rate_limiting``.++ The downloader fetches from ``export.arxiv.org``, the host arXiv+ sets aside for programmatic access, rather than ``arxiv.org``.++ Returns the text only when it is full text: the HTML rendition or+ text extracted from the PDF. Returns ``None`` when arXiv answered+ that the paper has no full text (no usable rendition, and no PDF+ bytes). The downloader handles its own transport errors on every+ leg (HTTP errors, 429s, connection failures and the decoded-body+ cap all come back as a status, not as an exception), which this+ method turns into the exceptions below. The API metadata leg is+ never requested (``download_full_text``): it yields the abstract,+ which the engine already holds as the paper summary, so it would+ add an arXiv API request without adding text.++ Raises ``FullTextNotExtractedError`` when the PDF arrived but+ produced no text (an image-only scan, or the extraction ceilings+ hit first), ``FullTextRateLimitedError`` when arXiv answered the+ PDF request with HTTP 429 or 503 (the PDF leg makes one attempt+ and does not retry), ``FullTextFetchFailedError`` when a request+ failed instead of being answered (timeout, connection error, 5xx,+ the decoded-body cap), and ``ValueError`` when the paper carries+ no valid arXiv id."""arxiv_id = self._validated_arxiv_id(paper)if not arxiv_id:- raise ValueError(- "Could not derive a valid arXiv id for PDF download"- )+ raise ValueError("Could not derive a valid arXiv id for full text")++ from ...research_library.downloaders.arxiv import (+ ARXIV_EXPORT_HOST,+ ArxivDownloader,+ ArxivFullTextStatus,+ ArxivTextSource,+ )- # Build the download URL from the validated id rather than trusting- # an arbitrary attribute value; SafeSession re-validates it anyway.- # No ".pdf" suffix -- see the docstring note above for why.- # Use export.arxiv.org (not the public arxiv.org CDN-fronted host)- # to match arxiv.Result.download_pdf's default `download_domain`- # (see the installed `arxiv` package, ~v2.4) and the host- # `arxiv.Client`/`arxiv.Search` already use for the metadata API- # (`query_url_format = "https://export.arxiv.org/api/query?..."`).- # export.arxiv.org is arXiv's designated host for automated/scripted- # access; the public arxiv.org host is rate-limited and- # bot-challenged for that traffic.- pdf_url = f"https://export.arxiv.org/pdf/{arxiv_id}"-- directory = Path(dirpath)- # `dirpath` (== self.download_dir) is reachable from per-user web- # settings ("search." is an allowed settings prefix; the factory- # splats `search.engine.web.arxiv.default_params.download_dir`- # straight into this engine's constructor kwargs) as well as- # `LDR_SEARCH_ENGINE_WEB_ARXIV_DEFAULT_PARAMS_DOWNLOAD_DIR`, so it- # is untrusted/user-influenced input, not a trusted constant --- # containment is required per directory_creation.py's own- # opt-in-root guidance. Contain it to a dedicated subtree of the- # LDR-managed data directory rather than the data directory- # itself: the data directory root also holds `.secret_key`- # (fastapi_app.py), `encrypted_databases/` (per-user encrypted DB- # files + `.salt`), and backups, and `create_directory` is called- # with `parents=True, exist_ok=True` -- with the bare data- # directory as root, an authenticated user could `mkdir` any- # not-yet-existing path under it, including pre-occupying the- # (computable) encrypted-DB path of a username that has not- # registered yet. Scoping the root to a download-only subtree- # keeps the blast radius of that primitive to the download area.- arxiv_downloads_root = get_data_directory() / "arxiv_downloads"- create_directory(- directory,- context="arXiv PDF download directory",- root=arxiv_downloads_root,+ downloader = getattr(self, "_arxiv_text_downloader", None)+ if downloader is None:+ downloader = ArxivDownloader(fetch_host=ARXIV_EXPORT_HOST)+ self._arxiv_text_downloader = downloader+ outcome = downloader.download_full_text(+ f"https://arxiv.org/abs/{arxiv_id}")- target_path = directory / f"{arxiv_id.replace('/', '_')}.pdf"-- with SafeSession() as session:- # stream=True is intentional here — DO NOT remove it: it lets- # the body be written to disk in bounded chunks below instead- # of buffered whole in memory (see the docstring note above).- # Accept-Encoding: identity mirrors what the old- # urlretrieve-based path effectively sent -- a best-effort- # signal only; it does NOT rule out a decompression bomb on- # its own (a server that ignores this header and gzips the- # body anyway is still transparently decoded downstream). The- # running byte count enforced while streaming below, over the- # already-decoded chunks, is what actually bounds that (see- # the docstring note above).- with session.get(- pdf_url,- timeout=DEFAULT_TIMEOUT,- allow_redirects=True,- stream=True,- headers={"Accept-Encoding": "identity"},- ) as response:- response.raise_for_status()- self._stream_response_to_file(response, target_path)-- return str(target_path)-- def _stream_response_to_file(- self, response: Any, target_path: Path+ if outcome.status == ArxivFullTextStatus.PDF_WITHOUT_TEXT:+ raise FullTextNotExtractedError(+ f"arXiv PDF for {arxiv_id} yielded no text"+ )+ if outcome.status == ArxivFullTextStatus.RATE_LIMITED:+ raise FullTextRateLimitedError(+ f"arXiv rate limited the PDF request for {arxiv_id}"+ )+ if outcome.status == ArxivFullTextStatus.FETCH_FAILED:+ raise FullTextFetchFailedError(+ f"arXiv full-text request failed for {arxiv_id}"+ )+ result = outcome.result+ if result is None or result.source not in (+ ArxivTextSource.ARXIV_HTML,+ ArxivTextSource.LOCAL_PDF,+ ):+ return None+ return result.text++ def close(self) -> None:+ """Close the lazily-created full-text downloader, then the base+ engine's own resources.++ ``_fetch_full_text`` caches an ``ArxivDownloader`` (which owns an+ HTTP session) on ``self._arxiv_text_downloader`` the first time+ full text is fetched; it is only ever created there, so nothing+ else in this engine would release it. The attribute is cleared after+ closing, so reuse after close() starts from a fresh downloader.+ """+ from ...utilities.resource_utils import safe_close++ downloader = getattr(self, "_arxiv_text_downloader", None)+ if downloader is not None:+ safe_close(downloader, "arXiv text downloader")+ # Drop the closed instance so a later full-text fetch builds a+ # fresh downloader instead of reusing one without a session.+ del self._arxiv_text_downloader+ super().close()++ def _log_full_text_error(+ self, error: Exception, title: Optional[str] = None) -> None:- """Write ``response``'s body to ``target_path`` in bounded chunks.-- Streams via ``iter_content`` rather than reading ``response.content``- (which would materialise the whole body in memory) -- see- ``_download_pdf_safely``'s docstring. ``written`` is an independent- running cap: it is what actually bounds this fetch's memory/disk- use, not the ``Content-Length`` check in ``SafeSession`` (see that- docstring for why the check alone is not enough here).-- The body is streamed to a per-call-unique ``<target- name>.<uuid4 hex>.part`` sibling and only ``os.replace()``d onto- ``target_path`` after a full, under-cap, *non-empty* write -- never- streamed directly into ``target_path``. Two concurrent downloads of- the same arXiv id into the same directory each get their own- ``.part`` file, so one failing (e.g. tripping the size cap) can- only ever remove *its own* partial file, never a sibling- download's already-completed ``target_path``.-- A response body that streams zero bytes (e.g. a ``200`` with an- empty body) is rejected before ``os.replace()`` runs, specifically- so it can never silently overwrite an already-completed- ``target_path`` from an earlier download of the same id with a- 0-byte file while still reporting success.-- Cleanup runs in a ``finally``, not an ``except Exception`` --- ``except Exception`` does not catch ``KeyboardInterrupt`` /- ``SystemExit`` (or a raw thread-kill), which would otherwise leave- an unpredictably-named, up-to-``MAX_RESPONSE_SIZE``-byte ``.part``- file orphaned in this shared root with no sweeper to reclaim it.- On success ``os.replace()`` has already moved ``tmp_path`` onto- ``target_path`` by the time ``finally`` runs, so the same- unconditional ``unlink(missing_ok=True)`` call is a no-op then;- on any failure -- including the cap being exceeded, an empty body,- or an interrupt -- it removes that call's own ``.part`` file. The- unlink itself is best-effort and never allowed to replace (mask)- whatever exception is already propagating.+ """Log an error raised by the full-text step without leaking paths.++ An ``OSError`` message can carry a local filesystem path, which+ ``_scrub_error`` does not remove, and ``logger.exception`` output+ reaches the research owner's browser via ``frontend_progress_sink``.+ So an ``OSError`` is logged by its type name only (which is+ path-free and still tells an operator what kind of failure it+ was). ``requests``' ``RequestException`` subclasses ``OSError`` but+ carries no local path, so it keeps the scrubbed message, as does+ every other exception."""- written = 0- tmp_path = target_path.with_name(- f"{target_path.name}.{uuid.uuid4().hex}.part"+ paper = f"paper {title} " if title is not None else "paper "+ if isinstance(error, OSError) and not isinstance(+ error, RequestException+ ):+ logger.exception(+ f"Error downloading {paper}({type(error).__name__}): "+ "a filesystem error occurred"+ )+ return+ safe_msg = self._scrub_error(error)+ logger.exception(+ f"Error downloading {paper}({type(error).__name__}): {safe_msg}")- try:- # Public arXiv PDF (a published paper, no PII/secrets) fetched- # through the SSRF-validated SafeSession and written into the- # caller-provided, containment-checked download dir.- with tmp_path.open("wb") as pdf_file: # Safe: public PDF- for chunk in response.iter_content(chunk_size=1024 * 1024):- if not chunk:- continue- written += len(chunk)- self._enforce_response_size_cap(written)- pdf_file.write(chunk)- if written == 0:- raise ValueError(- "arXiv PDF body was empty; refusing to write a "- "0-byte file over any existing download at the "- "target path"- )- os.replace(tmp_path, target_path)- finally:- try:- tmp_path.unlink(missing_ok=True)- except OSError:- # Never let a failure to clean up the partial file mask- # whatever exception (if any) is already propagating.- logger.debug(- f"Failed to remove partial download file {tmp_path.name}"- )def _get_previews(self, query: str) -> List[Dict[str, Any]]:"""@@ -498,8 +400,11 @@ class ArXivSearchEngine(BaseSearchEngine):) -> List[Dict[str, Any]]:"""Get full content for the relevant arXiv papers.- Downloads PDFs and extracts text when include_full_text is True.- Limits the number of PDFs processed to max_full_text.+ Fetches full text through the shared HTML-first arXiv downloader+ when include_full_text is True. At most max_full_text papers+ have their full text fetched; a paper arXiv answered has no full+ text is refunded, and a failed request stops further fetches (see+ the constructor's max_full_text).Args:relevant_items: List of relevant preview dictionaries@@ -510,7 +415,15 @@ class ArXivSearchEngine(BaseSearchEngine):logger.info("Getting full content for relevant arXiv papers")results = []- pdf_count = 0 # Track number of PDFs processed+ # Papers whose full-text fetch counts against max_full_text: full+ # text or the PDF arrived (text or not), or a request failed. Only+ # a paper arXiv answered has no full text is refunded below.+ pdf_count = 0+ # Set once a full-text request fails instead of being answered+ # (timeout, connection error, 5xx, 429/503): no further full-text+ # fetches are made in this call, so a failing host is not sent a+ # request (and a timeout) per remaining paper.+ host_failing = Falsefor item in relevant_items:# Start with the preview data@@ -525,10 +438,15 @@ class ArXivSearchEngine(BaseSearchEngine):paper = self._papers[paper_id]if paper:+ arxiv_id = self._validated_arxiv_id(paper)# Add complete paper informationresult.update({- "pdf_url": paper.pdf_url,+ "pdf_url": (+ f"https://arxiv.org/pdf/{arxiv_id}"+ if arxiv_id+ else None+ ),"authors": [author.name for author in paper.authors], # All authors@@ -555,145 +473,78 @@ class ArXivSearchEngine(BaseSearchEngine):result["content"] = paper.summaryresult["full_content"] = paper.summary- # Download PDF and extract text if requested and within limit+ # Fetch full text through the shared HTML-first arXiv+ # downloader (official HTML rendition with a PDF+ # fallback, issue #4783) when requested and within limitif (self.include_full_textand self.download_dirand pdf_count < self.max_full_text+ and not host_failing):+ pdf_count += 1 # Count the fetch before attempting it+ full_text = None+ fetched = Falsetry:- # Download the paper- pdf_count += (- 1 # Increment counter before attempting download- )- # Apply rate limiting before PDF download+ # Apply rate limiting before the full-text fetchself.rate_tracker.apply_rate_limit(self.engine_type)- paper_path = self._download_pdf_safely(- paper, self.download_dir+ full_text = self._fetch_full_text(paper)+ fetched = full_text is not None+ except FullTextNotExtractedError:+ # The PDF arrived but yielded no text: the download+ # and extraction were paid for, so the fetch counts.+ fetched = True+ logger.info(+ "arXiv PDF yielded no text; keeping the summary")- result["pdf_path"] = str(paper_path)-- # Extract text from PDF- try:- # Try pypdf first- try:- from pypdf import PdfReader-- with open(paper_path, "rb") as pdf_file:- pdf_reader = PdfReader(pdf_file)- pdf_text = ""- for page in pdf_reader.pages:- pdf_text += page.extract_text() + "\n\n"-- if (- pdf_text.strip()- ): # Only use if we got meaningful text- result["content"] = pdf_text- result["full_content"] = pdf_text- logger.info(- "Successfully extracted text from PDF using pypdf"- )- except (ImportError, Exception) as e1:- # Fall back to pdfplumber- try:- import pdfplumber-- with pdfplumber.open(paper_path) as pdf:- pdf_text = ""- for plumber_page in pdf.pages:- pdf_text += (- plumber_page.extract_text()- + "\n\n"- )-- if (- pdf_text.strip()- ): # Only use if we got meaningful text- result["content"] = pdf_text- result["full_content"] = pdf_text- logger.info(- "Successfully extracted text from PDF using pdfplumber"- )- except (ImportError, Exception) as e2:- safe_e1 = self._scrub_error(e1)- safe_e2 = self._scrub_error(e2)- logger.exception(- f"PDF text extraction failed ({type(e1).__name__}, then {type(e2).__name__}): {safe_e1}, then {safe_e2}"- )- logger.info(- "Using paper summary as content instead"- )- except Exception as e:- safe_msg = self._scrub_error(e)- logger.exception(- f"Error extracting text from PDF ({type(e).__name__}): {safe_msg}"+ except FullTextFetchFailedError as e:+ # The host is failing (429/503, timeout, connection+ # error, 5xx): the fetch counts against the budget+ # and no further full text is fetched in this call.+ fetched = True+ host_failing = True+ if isinstance(e, FullTextRateLimitedError):+ logger.warning(+ "arXiv rate limited the full-text fetch; "+ "using summaries for the remaining papers")- logger.info(- "Using paper summary as content instead"+ else:+ logger.warning(+ "arXiv full-text fetch failed; using "+ "summaries for the remaining papers")- except RequestException as e:- # ORDER MATTERS: this clause must precede the- # (DirectoryCreationSecurityError, OSError)- # clause below. requests' RequestException- # subclasses IOError, which *is* OSError, so a- # bare OSError catch would otherwise swallow- # every ConnectionError/Timeout/HTTPError and- # relabel a routine network failure as a- # containment error. Network errors carry no- # local path, so the normal scrubbed message is- # both safe and far more useful here.- safe_msg = self._scrub_error(e)- logger.exception(- f"Error downloading paper {paper.title} ({type(e).__name__}): {safe_msg}"- )- result["pdf_path"] = None- pdf_count -= 1 # Decrement counter if download fails- except (DirectoryCreationSecurityError, OSError) as e:- # Never interpolate either exception's message or- # any path -- only its type name, which is- # path-free and safe to include (unlike str(e)).- # DirectoryCreationSecurityError embeds the- # resolved data-directory path- # (directory_creation.py). OSError (e.g.- # FileExistsError/NotADirectoryError) is what- # create_directory's own `p.mkdir()` raises- # uncaught -- with the *same* resolved, absolute- # path in its message -- when download_dir- # collides with an existing file or has one as a- # parent component; a filesystem error surfacing- # from the streaming write below (e.g. a disk-full- # OSError) can carry a path too. logger.exception- # here reaches the research owner's browser via- # frontend_progress_sink -- _scrub_error does not- # scrub filesystem paths, so a static, path-free- # message is used for this whole exception family- # instead; the type name alone lets an operator- # tell a containment rejection apart from e.g. a- # disk-full OSError (a cert_verify OSError from a- # missing REQUESTS_CA_BUNDLE, say).- logger.exception(- f"Error downloading paper {paper.title} "- f"({type(e).__name__}): a filesystem or "- "directory-containment error occurred"- )- result["pdf_path"] = None- pdf_count -= 1 # Decrement counter if download failsexcept Exception as e:- safe_msg = self._scrub_error(e)- logger.exception(- f"Error downloading paper {paper.title} ({type(e).__name__}): {safe_msg}"+ # The downloader handles its own transport errors+ # (see _fetch_full_text; a failed request comes+ # back as FullTextFetchFailedError, handled+ # above), so only errors outside+ # the transport reach this point: an invalid arXiv+ # id, the rate limiter, or a bug. None of them+ # fetched anything.+ self._log_full_text_error(e, paper.title)+ if full_text and full_text.strip():+ result["content"] = full_text+ result["full_content"] = full_text+ logger.info(+ "Retrieved full text via the HTML-first arXiv downloader")- result["pdf_path"] = None- pdf_count -= 1 # Decrement counter if download fails+ else:+ if not fetched:+ # arXiv answered that the paper has no full+ # text, or an error stopped the fetch before+ # any request: refund the budget so a later+ # paper still gets a full-text attempt.+ pdf_count -= 1+ logger.info("Using paper summary as content instead")elif (self.include_full_textand self.download_dirand pdf_count >= self.max_full_text):- # Reached PDF limit+ # Reached full-text fetch limitlogger.info(- f"Maximum number of PDFs ({self.max_full_text}) reached. Skipping remaining PDFs."+ f"Maximum number of full-text fetches ({self.max_full_text}) reached. Skipping remaining papers.")result["content"] = paper.summaryresult["full_content"] = paper.summary@@ -763,9 +614,14 @@ class ArXivSearchEngine(BaseSearchEngine):"journal_ref": paper.journal_ref,}+ canonical_id = self._validated_arxiv_id(paper)result.update({- "pdf_url": paper.pdf_url,+ "pdf_url": (+ f"https://arxiv.org/pdf/{canonical_id}"+ if canonical_id+ else None+ ),"authors": [author.name for author in paper.authors], # All authors@@ -788,63 +644,47 @@ class ArXivSearchEngine(BaseSearchEngine):})- # Download PDF if requested+ # Fetch full text through the shared HTML-first downloader+ # (official HTML rendition with a PDF fallback, #4783)+ # if requestedif self.include_full_text and self.download_dir:try:- # Apply rate limiting before PDF download+ # Apply rate limiting before the full-text fetchself.rate_tracker.apply_rate_limit(self.engine_type)- # Download the paper through the SSRF-validated session- paper_path = self._download_pdf_safely(- paper, self.download_dir+ full_text = self._fetch_full_text(paper)+ if full_text and full_text.strip():+ result["content"] = full_text+ result["full_content"] = full_text+ logger.info(+ "Retrieved full text via the HTML-first arXiv downloader"+ )+ except FullTextNotExtractedError:+ logger.info(+ "arXiv PDF yielded no text; keeping the summary")- result["pdf_path"] = str(paper_path)- except RequestException as e:- # ORDER MATTERS: this clause must precede the- # (DirectoryCreationSecurityError, OSError)- # clause below. requests' RequestException- # subclasses IOError, which *is* OSError, so a- # bare OSError catch would otherwise swallow- # every ConnectionError/Timeout/HTTPError and- # relabel a routine network failure as a- # containment error. Network errors carry no- # local path, so the normal scrubbed message is- # both safe and far more useful here.- safe_msg = self._scrub_error(e)- logger.exception(- f"Error downloading paper ({type(e).__name__}): {safe_msg}"+ except FullTextRateLimitedError:+ # arXiv answered the PDF request with 429/503: nothing+ # arrived, so keep the summary. Not an error in this+ # code, so no traceback.+ logger.warning(+ "arXiv rate limited the full-text fetch; keeping "+ "the summary")- except (DirectoryCreationSecurityError, OSError) as e:- # Never interpolate either exception's message or any- # path -- only its type name, which is path-free and- # safe to include (unlike str(e)).- # DirectoryCreationSecurityError embeds the resolved- # data-directory path (directory_creation.py). OSError- # (e.g. FileExistsError/NotADirectoryError) is what- # create_directory's own `p.mkdir()` raises uncaught- # -- with the *same* resolved, absolute path in its- # message -- when download_dir collides with an- # existing file or has one as a parent component; a- # filesystem error surfacing from the streaming write- # below (e.g. a disk-full OSError) can carry a path- # too. logger.exception here reaches the research- # owner's browser via frontend_progress_sink --- # _scrub_error does not scrub filesystem paths, so a- # static, path-free message is used for this whole- # exception family instead; the type name alone lets- # an operator tell a containment rejection apart from- # e.g. a disk-full OSError (a cert_verify OSError from- # a missing REQUESTS_CA_BUNDLE, say).- logger.exception(- f"Error downloading paper ({type(e).__name__}): "- "a filesystem or directory-containment error "- "occurred"+ except FullTextFetchFailedError:+ # A request timed out, could not connect or got a 5xx:+ # nothing arrived, so keep the summary. Logged by the+ # downloader as a warning; not an error here either.+ logger.warning(+ "arXiv full-text fetch failed; keeping the summary")except Exception as e:- safe_msg = self._scrub_error(e)- logger.exception(- f"Error downloading paper ({type(e).__name__}): {safe_msg}"- )+ # Failed requests (429/503, timeouts, connection+ # errors, 5xx) are handled above (see+ # _fetch_full_text), so only errors outside+ # the transport reach this point: an invalid arXiv id,+ # the rate limiter, or a bug.+ self._log_full_text_error(e)return resultdiff --git a/tests/content_fetcher/test_url_classifier.py b/tests/content_fetcher/test_url_classifier.pyindex 76fd8c3a41..aacb2ad4a9 100644--- a/tests/content_fetcher/test_url_classifier.py+++ b/tests/content_fetcher/test_url_classifier.py@@ -106,6 +106,35 @@ class TestURLClassifier:@pytest.mark.parametrize("url",(+ "https://arxiv.org/about",+ "https://arxiv.org/help",+ "https://arxiv.org/list/cs.AI",+ "https://arxiv.org/blog",+ ),+ )+ def test_classify_arxiv_non_paper_pages_as_html(self, url):+ assert URLClassifier.classify(url) == URLType.HTML++ @pytest.mark.parametrize(+ "url",+ (+ "https://arxiv.org/abs/2301.12345",+ "https://arxiv.org/pdf/2301.12345.pdf",+ "https://arxiv.org/html/2301.12345",+ "https://ar5iv.org/2301.12345",+ "https://ar5iv.org/abs/2301.12345",+ ),+ )+ def test_classify_paper_shaped_arxiv_urls_as_arxiv(self, url):+ # Routing follows the paper identifier, not the host: only URLs+ # that name one paper are terminal arXiv (main's merged policy).+ assert URLClassifier.classify(url) == URLType.ARXIV++ @pytest.mark.parametrize(+ "url",+ (+ "https://arxiv.org/aboutness",+ "https://ar5iv.org/about","https://AR5IV.ORG./not-an-arxiv-id","https://ARXIV.ORG./not-an-arxiv-id","https://EXPORT.ARXIV.ORG./not-an-arxiv-id",diff --git a/tests/research_library/downloaders/test_arxiv_html_text.py b/tests/research_library/downloaders/test_arxiv_html_text.pyindex e01944b176..9d61e80aa1 100644--- a/tests/research_library/downloaders/test_arxiv_html_text.py+++ b/tests/research_library/downloaders/test_arxiv_html_text.py@@ -121,18 +121,29 @@ def test_pdf_path_does_not_touch_api_gate(downloader, mocker):],ids=["missing-tex-annotation", "empty-tex-annotation"],)-def test_text_falls_back_when_any_math_lacks_usable_tex(+def test_text_preserves_document_when_any_math_lacks_usable_tex(downloader, mocker, unusable_math):- # Given HTML with one valid formula and one unusable formula+ # Given HTML whose prose is long enough to stand alone and one formula+ # without a usable TeX annotation -- the partially annotated renditions+ # at the heart of issue #4783. The prose length matters because+ # text-first callers have no PDF text to compare against, so+ # MIN_STANDALONE_HTML_TEXT_LENGTH decides whether HTML can stand alone.+ body_prose = (+ "This paper develops a detailed mathematical argument with enough "+ "explanatory prose for the shared extraction pipeline to retain the "+ "article body. The derivation is repeated across several examples so "+ "readers can follow every step and understand the surrounding context. "+ ) * 8html = (- "<html><body><article><p>"- "A sufficiently detailed article introduces "- '<math><semantics><mi>y</mi><annotation encoding="application/x-tex">'- "y^2</annotation></semantics></math> before a second expression "- f"{unusable_math}. The surrounding discussion is intentionally long "- "enough that content extraction would otherwise succeed, and it "- "continues with assumptions, results, limitations, and conclusions."+ "<html><head><title>Partially Annotated Paper</title></head>"+ "<body><article><p>"+ + body_prose+ + "A fully annotated formula <math><semantics><mi>y</mi>"+ + '<annotation encoding="application/x-tex">'+ + "y^2</annotation></semantics></math> sits beside an unusable one "+ + f"{unusable_math}. The surrounding discussion continues with "+ "assumptions, results, limitations, and conclusions.""</p></article></body></html>")fetch_html = mocker.patch.object(@@ -140,11 +151,8 @@ def test_text_falls_back_when_any_math_lacks_usable_tex("_fetch_html_with_final_url",return_value=(html, "https://arxiv.org/html/math.AG/0601001v3"),)- mocker.patch.object(downloader, "_download_pdf", return_value=b"%PDF-test")- mocker.patch.object(- downloader, "extract_text_from_pdf", return_value="PDF fallback text"- )- mocker.patch.object(downloader, "_fetch_from_arxiv_api", return_value=None)+ pdf_download = mocker.patch.object(downloader, "_download_pdf")+ api_fetch = mocker.patch.object(downloader, "_fetch_from_arxiv_api")# When text is requested for a versioned legacy identifierresult = downloader.download_with_result(@@ -152,14 +160,81 @@ def test_text_falls_back_when_any_math_lacks_usable_tex(ContentType.TEXT,)- # Then the entire HTML document is rejected and the existing PDF path wins+ # Then the document survives: the annotated formula keeps its TeX and+ # the unusable one degrades to visible MathML text instead of rejecting+ # the whole HTML renditionassert result.is_success is True- assert result.content == (- b"PDF fallback text\n\nSource: https://arxiv.org/abs/math.AG/0601001v3"- )+ content = result.content.decode("utf-8")+ assert "y^2" in content+ assert "<math" not in content+ assert "Source: https://arxiv.org/abs/math.AG/0601001v3" in contentfetch_html.assert_called_once_with("https://arxiv.org/html/math.AG/0601001v3")+ pdf_download.assert_not_called()+ api_fetch.assert_not_called()+++def test_math_nodes_convert_through_every_fallback_tier(downloader, mocker):+ # Given a LaTeXML-style rendition exercising every conversion tier: a+ # whitespace-first TeX annotation pair, a TeX annotation that exists+ # only as x-tex+html, an alttext attribute over visible MathML, and+ # bare visible MathML. A genuinely empty node is deliberately absent+ # here: it still takes the whole-page PDF exit by design, which+ # test_neither_source_still_falls_back_to_the_pdf pins.+ body_prose = (+ "This paper develops a detailed mathematical argument with enough "+ "explanatory prose for the shared extraction pipeline to retain the "+ "article body. The derivation is repeated across several examples so "+ "readers can follow every step and understand the surrounding context. "+ ) * 8+ html = (+ "<html><head><title>Partly Annotated LaTeXML Paper</title></head>"+ "<body><article><p>"+ + body_prose+ + "Equations arrive in every state of annotation: "+ + "<math><semantics><mfrac><mi>a</mi><mi>b</mi></mfrac>"+ + '<annotation encoding="application/x-tex"> </annotation>'+ + '<annotation encoding="application/x-tex">'+ + "\\frac{a}{b}</annotation></semantics></math>, "+ + "<math><semantics><mi>z</mi>"+ + '<annotation encoding="application/x-tex"> </annotation>'+ + '<annotation encoding="application/x-tex+html">'+ + "\\sqrt{z}</annotation></semantics></math>, "+ + '<math alttext="\\alpha"><mi>α</mi></math>, '+ + "<math><mrow><mi>p</mi><mo>+</mo><mi>q</mi></mrow></math>. "+ + "The discussion continues with assumptions, results, limitations, "+ + "and conclusions so nothing is lost."+ "</p></article></body></html>"+ )+ fetch_html = mocker.patch.object(+ downloader,+ "_fetch_html_with_final_url",+ return_value=(html, "https://arxiv.org/html/2501.12345v2"),+ )+ pdf_download = mocker.patch.object(downloader, "_download_pdf")+ api_fetch = mocker.patch.object(downloader, "_fetch_from_arxiv_api")++ # When text is produced without PDF bytes in hand+ result = downloader.download_text_with_source(+ "https://arxiv.org/abs/2501.12345v2"+ )++ # Then each node converted by its best available tier and none of them+ # rejected the document+ assert result is not None+ assert result.source is ArxivTextSource.ARXIV_HTML+ text = result.text+ assert "\\frac{a}{b}" in text+ assert "\\sqrt{z}" in text+ assert "\\alpha" in text+ assert "p + q" in text+ assert "α" not in text+ assert "<math" not in text+ assert "application/x-tex" not in text+ fetch_html.assert_called_once_with("https://arxiv.org/html/2501.12345v2")+ pdf_download.assert_not_called()+ api_fetch.assert_not_called()def _math_page(count: int) -> str:@@ -942,11 +1017,15 @@ def test_the_annotation_still_wins_over_alttext(downloader):def test_neither_source_still_falls_back_to_the_pdf(downloader):- # The exit is narrower now, not gone: a <math> with no annotation and no- # alttext carries no TeX, and the MathML must not be left in the text.+ # The exit is narrower now, not gone: a <math> with no annotation, no+ # alttext, and no visible MathML text carries nothing at all, and the+ # MathML must not be left in the text. A node with rendered characters+ # no longer takes this exit -- it converts through the visible-text+ # tier -- which test_math_nodes_convert_through_every_fallback_tier+ # pins from the other side.from bs4 import BeautifulSoup- soup = BeautifulSoup(_page_with("<math><mi>x</mi></math>"), "lxml")+ soup = BeautifulSoup(_page_with("<math></math>"), "lxml")rewritten = downloader._rewrite_math_to_tex(soup, "2501.12345v2")@@ -982,10 +1061,15 @@ def test_an_empty_alttext_is_not_a_tex_source(downloader):from bs4 import BeautifulSoupsoup = BeautifulSoup(- _page_with('<math alttext=" "><mi>x</mi></math>'), "lxml"+ _page_with('<math alttext=" "><mi>QVAR</mi></math>'), "lxml")- assert downloader._rewrite_math_to_tex(soup, "2501.12345v2") is False+ # The whitespace alttext is skipped and the visible MathML text is used+ # instead, so the element converts rather than taking the PDF exit --+ # but through "QVAR", never through the empty attribute. The token is+ # absent from the page prose, so the check can fail.+ assert downloader._rewrite_math_to_tex(soup, "2501.12345v2") is True+ assert "QVAR" in soup.get_text()def test_the_local_name_matchers_are_anchored(downloader):@@ -1016,3 +1100,459 @@ def test_the_local_name_matchers_are_anchored(downloader):# `<annotation-xml>` is not a TeX annotation: alttext supplied the TeX.assert "real" in soup.get_text()assert "NOT_TEX" not in soup.get_text()+++def test_visible_text_tier_excludes_hidden_annotation_text(downloader):+ # A node with rendered MathML beside an annotation-xml: no TeX+ # annotation of either encoding and no alttext, so the visible-text+ # tier runs. It must yield only the rendered characters -- the hidden+ # Content MathML inside <annotation-xml> (and inside a plain+ # <annotation> of another encoding) must never surface in the+ # equation. Red under reverting the decompose: the hidden text is+ # glued onto the visible symbol ("XVAR HIDDEN_CI").+ from bs4 import BeautifulSoup++ soup = BeautifulSoup(+ _page_with(+ "<math><semantics><mrow><mi>XVAR</mi></mrow>"+ '<annotation-xml encoding="MathML-Content"><ci>HIDDEN_CI'+ "</ci></annotation-xml></semantics></math>"+ "<m:math><m:semantics><m:mi>YVAR</m:mi>"+ '<m:annotation-xml encoding="MathML-Content"><m:ci>PREFIXED_HIDDEN'+ "</m:annotation-xml></m:semantics></m:math>"+ "<math><semantics><mrow><mi>ZVAR</mi></mrow>"+ '<annotation encoding="application/x-asy">ASY_HIDDEN'+ "</annotation></semantics></math>"+ ),+ "lxml",+ )++ assert downloader._rewrite_math_to_tex(soup, "2501.12345v2") is True+ text = soup.get_text()+ # Tokens absent from the page prose, so each check can fail.+ assert "XVAR" in text and "YVAR" in text and "ZVAR" in text+ assert "HIDDEN_CI" not in text+ assert "PREFIXED_HIDDEN" not in text+ assert "ASY_HIDDEN" not in text+++def test_hidden_annotation_only_text_takes_the_pdf_exit(downloader):+ # A node whose ONLY text lives inside annotation-xml carries no+ # rendered characters. The visible-text tier must read it as empty+ # (the annotation is decomposed out of the copy first) so the node is+ # genuinely empty and the rewrite takes the PDF exit, instead of+ # emitting the hidden Content MathML text as the equation and keeping+ # the page. Red under reverting the decompose: the hidden text+ # converts the element and stays in the page.+ from bs4 import BeautifulSoup++ soup = BeautifulSoup(+ _page_with(+ "<math><semantics>"+ '<annotation-xml encoding="MathML-Content"><ci>ONLY_HIDDEN'+ "</ci></annotation-xml></semantics></math>"+ ),+ "lxml",+ )++ assert downloader._rewrite_math_to_tex(soup, "2501.12345v2") is False+++def test_nested_math_is_rewritten_once_per_outermost_element(+ downloader, mocker+):+ # Given a chain of nested <math> elements with no TeX anywhere, so every+ # level would fall to the visible-text tier. Visiting each level re-reads+ # the whole chain below it, which is quadratic in the depth; only the+ # outermost element is rewritten, and its text covers the chain. Red+ # under iterating every find_all match: the ladder runs once per level.+ from bs4 import BeautifulSoup++ depth = 50+ soup = BeautifulSoup(+ _page_with(+ "<math><mrow><mi>NVAR</mi>" * depth + "</mrow></math>" * depth+ ),+ "lxml",+ )+ ladder = mocker.spy(ArxivDownloader, "_tex_for_math_element")++ assert downloader._rewrite_math_to_tex(soup, "2501.12345v2") is True+ assert ladder.call_count == 1+ assert soup.find_all("math") == []+ assert soup.get_text().count("NVAR") == depth+++def test_nested_math_without_tex_is_covered_by_its_ancestor(downloader):+ # An inner <math> carrying nothing sits inside an outer one whose+ # alttext supplies the TeX: the outer element's TeX stands for the+ # whole subtree, so the page is kept rather than sent to the PDF.+ from bs4 import BeautifulSoup++ soup = BeautifulSoup(+ _page_with(+ '<math alttext="OUTER_TEX"><mrow><math></math></mrow></math>'+ ),+ "lxml",+ )++ assert downloader._rewrite_math_to_tex(soup, "2501.12345v2") is True+ assert "OUTER_TEX" in soup.get_text()+ assert soup.find_all("math") == []+++ "encoding", ("application/x-tex", "application/x-tex+html")+)+def test_nested_tex_annotations_are_read_once_per_outermost_match(+ downloader, mocker, encoding+):+ # Given a chain of nested, empty same-encoding annotations: reading the+ # text of every level re-reads the whole chain below it, quadratic in+ # the depth. An inner annotation's text is a subset of its ancestor's,+ # so only the outermost match is read, and the empty chain falls+ # through to alttext. Red under iterating every find_all match: the+ # text is read once per level.+ from bs4 import BeautifulSoup+ from bs4.element import Tag++ depth = 200+ soup = BeautifulSoup(+ _page_with(+ '<math alttext="ALT_TEX"><semantics><mi>v</mi>'+ + f'<annotation encoding="{encoding}">' * depth+ + "</annotation>" * depth+ + "</semantics></math>"+ ),+ "lxml",+ )+ assert len(soup.find_all("annotation")) == depth+ get_text = mocker.spy(Tag, "get_text")++ assert downloader._rewrite_math_to_tex(soup, "2501.12345v2") is True+ assert get_text.call_count == 1+ assert "ALT_TEX" in soup.get_text()+++def test_tex_annotation_after_an_empty_nested_run_is_still_read(downloader):+ # Outermost-only reading still examines every disjoint match in+ # document order: an empty nested run does not hide a usable sibling.+ from bs4 import BeautifulSoup++ soup = BeautifulSoup(+ _page_with(+ '<math alttext="ALT_TEX"><semantics>'+ '<annotation encoding="application/x-tex">'+ '<annotation encoding="application/x-tex"> </annotation>'+ "</annotation>"+ '<annotation encoding="application/x-tex">SIBLING_TEX</annotation>'+ "</semantics></math>"+ ),+ "lxml",+ )++ assert downloader._rewrite_math_to_tex(soup, "2501.12345v2") is True+ text = soup.get_text()+ assert "SIBLING_TEX" in text+ assert "ALT_TEX" not in text+++def test_visible_text_tier_does_not_deepcopy(downloader, mocker):+ # bs4's Tag.__deepcopy__ re-walks the copy on every insert, quadratic+ # in the depth of nested markup; the visible-text tier walks the+ # element in place instead, skipping annotation subtrees, and leaves+ # the tree untouched until the rewrite itself.+ from bs4 import BeautifulSoup+ from bs4.element import Tag++ soup = BeautifulSoup(+ _page_with(+ "<math><semantics><mrow><mi>WVAR</mi><!-- CMT_HIDDEN --></mrow>"+ '<annotation-xml encoding="MathML-Content"><ci>XML_HIDDEN</ci>'+ "</annotation-xml></semantics></math>"+ ),+ "lxml",+ )+ deepcopy = mocker.spy(Tag, "__deepcopy__")++ assert downloader._rewrite_math_to_tex(soup, "2501.12345v2") is True+ deepcopy.assert_not_called()+ text = soup.get_text()+ assert "WVAR" in text+ assert "XML_HIDDEN" not in text+ assert "CMT_HIDDEN" not in text+++def test_download_full_text_reports_html_text(downloader, mocker):+ from local_deep_research.research_library.downloaders.arxiv import (+ ArxivFullTextOutcome,+ ArxivFullTextStatus,+ )++ mocker.patch.object(+ downloader, "_download_html_text", return_value="H" * 3000+ )+ pdf_download = mocker.patch.object(downloader, "_download_pdf")+ api_fetch = mocker.patch.object(downloader, "_fetch_from_arxiv_api")++ outcome = downloader.download_full_text("https://arxiv.org/abs/2301.12345")++ assert outcome == ArxivFullTextOutcome(+ ArxivFullTextStatus.TEXT,+ ArxivTextResult("H" * 3000, ArxivTextSource.ARXIV_HTML),+ )+ pdf_download.assert_not_called()+ api_fetch.assert_not_called()+++ ("pdf_bytes", "pdf_text", "expected_status", "extracted"),+ (+ pytest.param(+ b"%PDF-scan", None, "PDF_WITHOUT_TEXT", True, id="pdf_no_text"+ ),+ pytest.param(+ b"%PDF-scan", "", "PDF_WITHOUT_TEXT", True, id="pdf_empty_text"+ ),+ pytest.param(None, "unused", "NOT_FETCHED", False, id="pdf_failed"),+ ),+)+def test_download_full_text_tells_no_text_from_a_failed_fetch(+ downloader, mocker, pdf_bytes, pdf_text, expected_status, extracted+):+ # A PDF that arrived but yielded no text is PDF_WITHOUT_TEXT; no PDF+ # bytes, with no failed request reported, is NOT_FETCHED. The API leg+ # is never asked either way.+ from local_deep_research.research_library.downloaders.arxiv import (+ ArxivFullTextOutcome,+ ArxivFullTextStatus,+ )++ mocker.patch.object(downloader, "_download_html_text", return_value=None)+ mocker.patch.object(downloader, "_download_pdf", return_value=pdf_bytes)+ extract = mocker.patch.object(+ downloader, "extract_text_from_pdf", return_value=pdf_text+ )+ api_fetch = mocker.patch.object(downloader, "_fetch_from_arxiv_api")++ outcome = downloader.download_full_text("https://arxiv.org/abs/2301.12345")++ assert outcome == ArxivFullTextOutcome(ArxivFullTextStatus[expected_status])+ assert extract.called is extracted+ api_fetch.assert_not_called()+++def test_download_full_text_rejects_a_url_naming_no_paper(downloader, mocker):+ from local_deep_research.research_library.downloaders.arxiv import (+ ArxivFullTextStatus,+ )++ html = mocker.patch.object(downloader, "_download_html_text")++ outcome = downloader.download_full_text("https://example.org/nothing")++ assert outcome.status is ArxivFullTextStatus.NOT_FETCHED+ assert outcome.result is None+ html.assert_not_called()++[email protected]("status_code", (429, 503))+def test_download_full_text_makes_one_pdf_attempt_when_rate_limited(+ mocker, status_code+):+ # Under arXiv rate limiting the full-text fetch must not retry the PDF+ # into the limit: one HTML request, one PDF request, then RATE_LIMITED+ # so a caller fetching several papers can stop.+ from unittest.mock import Mock++ from local_deep_research.research_library.downloaders.arxiv import (+ ARXIV_EXPORT_HOST,+ ArxivFullTextStatus,+ )++ export = ArxivDownloader(fetch_host=ARXIV_EXPORT_HOST)+ export.rate_tracker = Mock()+ export.rate_tracker.apply_rate_limit.return_value = 0+ requested = []++ def fake_get(url, **kwargs):+ requested.append(url)+ return Mock(status_code=status_code, headers={})++ mocker.patch.object(export.session, "get", side_effect=fake_get)+ api_fetch = mocker.patch.object(export, "_fetch_from_arxiv_api")++ outcome = export.download_full_text("https://arxiv.org/abs/2301.12345")++ assert outcome.status is ArxivFullTextStatus.RATE_LIMITED+ assert outcome.result is None+ assert requested == [+ "https://export.arxiv.org/html/2301.12345",+ "https://export.arxiv.org/pdf/2301.12345",+ ]+ api_fetch.assert_not_called()+ export.close()+++def _requests_error(kind):+ import requests++ return {+ "timeout": requests.exceptions.Timeout("export.arxiv.org hung"),+ "connection": requests.exceptions.ConnectionError("unreachable"),+ # SafeSession's refusal shape, also raised on a failed DNS lookup+ "refused": ValueError(+ "URL failed security validation (possible SSRF): "+ "https://export.arxiv.org/pdf/2301.12345"+ ),+ "unexpected": RuntimeError("boom"),+ }[kind]+++ ("html_answer", "pdf_answer", "expected_status"),+ (+ pytest.param("timeout", "timeout", "FETCH_FAILED", id="host_hung"),+ pytest.param(+ "connection", "connection", "FETCH_FAILED", id="host_unreachable"+ ),+ pytest.param(500, 502, "FETCH_FAILED", id="both_5xx"),+ pytest.param(504, 404, "FETCH_FAILED", id="html_5xx_pdf_404"),+ pytest.param("timeout", 404, "FETCH_FAILED", id="html_hung_pdf_404"),+ pytest.param(404, 500, "FETCH_FAILED", id="html_404_pdf_5xx"),+ pytest.param("refused", "refused", "FETCH_FAILED", id="dns_failure"),+ pytest.param(404, "refused", "FETCH_FAILED", id="html_404_pdf_dns"),+ pytest.param(+ 404, "unexpected", "FETCH_FAILED", id="html_404_pdf_unexpected"+ ),+ pytest.param(404, 404, "NOT_FETCHED", id="both_absent"),+ pytest.param(410, 410, "NOT_FETCHED", id="both_gone"),+ pytest.param(404, "not_pdf", "NOT_FETCHED", id="pdf_not_a_pdf"),+ ),+)+def test_download_full_text_tells_a_failed_request_from_an_answer(+ mocker, html_answer, pdf_answer, expected_status, loguru_caplog+):+ # NOT_FETCHED (refundable) only when arXiv answered both legs; any leg+ # that failed instead of being answered is FETCH_FAILED, so a caller+ # fetching several papers stops rather than paying a timeout per+ # paper. Red under reporting every no-bytes ending as NOT_FETCHED.+ from unittest.mock import Mock++ from local_deep_research.research_library.downloaders.arxiv import (+ ARXIV_EXPORT_HOST,+ ArxivFullTextStatus,+ )++ export = ArxivDownloader(fetch_host=ARXIV_EXPORT_HOST)+ export.rate_tracker = Mock()+ export.rate_tracker.apply_rate_limit.return_value = 0+ requested = []++ def answer(spec):+ if isinstance(spec, str) and spec != "not_pdf":+ raise _requests_error(spec)+ if spec == "not_pdf":+ return Mock(+ status_code=200,+ headers={"content-type": "text/html"},+ content=b"<html>no pdf here</html>",+ raw=None,+ )+ return Mock(status_code=spec, headers={})++ def fake_get(url, **kwargs):+ requested.append(url)+ return answer(html_answer if "/html/" in url else pdf_answer)++ mocker.patch.object(export.session, "get", side_effect=fake_get)+ api_fetch = mocker.patch.object(export, "_fetch_from_arxiv_api")++ with loguru_caplog.at_level("DEBUG"):+ outcome = export.download_full_text("https://arxiv.org/abs/2301.12345")++ assert outcome.status is ArxivFullTextStatus[expected_status]+ assert outcome.result is None+ # One HTML and one (unretried) PDF request, whatever the ending+ assert requested == [+ "https://export.arxiv.org/html/2301.12345",+ "https://export.arxiv.org/pdf/2301.12345",+ ]+ api_fetch.assert_not_called()+ # The caller handles every ending, so none is logged at ERROR (ERROR+ # records reach the user's browser via frontend_progress_sink).+ assert not [r for r in loguru_caplog.records if r.levelno >= 40]+ export.close()+++def test_library_text_path_keeps_pdf_retries_when_rate_limited(mocker):+ # The single-attempt PDF leg is specific to download_full_text; the+ # library's text path keeps BaseDownloader's three attempts.+ from unittest.mock import Mock++ downloader = ArxivDownloader()+ downloader.rate_tracker = Mock()+ downloader.rate_tracker.apply_rate_limit.return_value = 0+ requested = []++ def fake_get(url, **kwargs):+ requested.append(url)+ return Mock(status_code=429, headers={})++ mocker.patch.object(downloader.session, "get", side_effect=fake_get)+ mocker.patch.object(downloader, "_fetch_from_arxiv_api", return_value=None)++ assert (+ downloader.download_text_with_source("https://arxiv.org/abs/2301.12345")+ is None+ )+ pdf_requests = [url for url in requested if "/pdf/" in url]+ assert pdf_requests == ["https://arxiv.org/pdf/2301.12345.pdf"] * 3+ downloader.close()+++def test_export_host_downloader_fetches_html_and_pdf_from_export(mocker):+ # arXiv asks programmatic clients to use export.arxiv.org. Its PDF URL+ # carries no ".pdf" suffix, which that host would answer with a 301+ # whose body requests drains before SafeSession can size-check it.+ from unittest.mock import Mock++ from local_deep_research.research_library.downloaders.arxiv import (+ ARXIV_EXPORT_HOST,+ )++ export = ArxivDownloader(fetch_host=ARXIV_EXPORT_HOST)+ export.rate_tracker = Mock()+ requested = []++ def fake_get(url, **kwargs):+ requested.append(url)+ return Mock(status_code=404, headers={})++ mocker.patch.object(export.session, "get", side_effect=fake_get)+ mocker.patch.object(export, "_fetch_from_arxiv_api")++ export.download_full_text("https://arxiv.org/abs/2301.12345v2")++ assert requested[0] == "https://export.arxiv.org/html/2301.12345v2"+ assert requested[1:] and all(+ url == "https://export.arxiv.org/pdf/2301.12345v2"+ for url in requested[1:]+ )+ export.close()+++def test_default_downloader_keeps_arxiv_org_urls():+ downloader = ArxivDownloader()+ try:+ assert (+ downloader._pdf_url("2301.12345")+ == "https://arxiv.org/pdf/2301.12345.pdf"+ )+ finally:+ downloader.close()+++def test_fetch_host_outside_arxiv_is_rejected():+ with pytest.raises(ValueError):+ ArxivDownloader(fetch_host="evil.example")diff --git a/tests/research_library/downloaders/test_base_downloader.py b/tests/research_library/downloaders/test_base_downloader.pyindex a08f860c05..751d16cefa 100644--- a/tests/research_library/downloaders/test_base_downloader.py+++ b/tests/research_library/downloaders/test_base_downloader.py@@ -2,11 +2,17 @@Tests for BaseDownloader abstract class and utility methods."""+import pytest+import requests+from local_deep_research.research_library.downloaders.base import (BaseDownloader,ContentType,DownloadResult,)+from local_deep_research.research_library.downloaders.html import (+ HTMLDownloader,+)class ConcreteDownloader(BaseDownloader):@@ -281,6 +287,680 @@ class TestDownloadPdfHelper:content = downloader._download_pdf("https://example.com/paper.pdf")assert content is None+ def _rate_limited_downloader(self, mocker, status_code):+ downloader = ConcreteDownloader()+ response = mocker.Mock()+ response.status_code = status_code+ response.content = b""+ response.headers = {}+ get = mocker.patch.object(+ downloader.session, "get", return_value=response+ )+ mocker.patch.object(+ downloader.rate_tracker, "apply_rate_limit", return_value=0+ )+ mocker.patch.object(downloader.rate_tracker, "record_outcome")+ return downloader, get++ def test_rate_limited_retries_by_default_and_reports_once(self, mocker):+ """Library downloads keep three attempts on 429; the callback+ fires once, when the download gives up."""+ downloader, get = self._rate_limited_downloader(mocker, 429)+ on_rate_limited = mocker.Mock()++ content = downloader._download_pdf(+ "https://example.com/paper.pdf", on_rate_limited=on_rate_limited+ )++ assert content is None+ assert get.call_count == 3+ on_rate_limited.assert_called_once_with()++ def test_single_attempt_does_not_retry_a_rate_limited_host(self, mocker):+ """max_attempts=1 sends one request on 429/503 and reports it."""+ for status_code in (429, 503):+ downloader, get = self._rate_limited_downloader(mocker, status_code)+ on_rate_limited = mocker.Mock()++ content = downloader._download_pdf(+ "https://example.com/paper.pdf",+ max_attempts=1,+ on_rate_limited=on_rate_limited,+ )++ assert content is None+ assert get.call_count == 1+ on_rate_limited.assert_called_once_with()++ def test_rate_limit_callback_not_called_for_other_failures(self, mocker):+ """A 404 is not rate limiting, so the callback stays silent."""+ downloader, get = self._rate_limited_downloader(mocker, 404)+ on_rate_limited = mocker.Mock()++ content = downloader._download_pdf(+ "https://example.com/paper.pdf",+ max_attempts=1,+ on_rate_limited=on_rate_limited,+ )++ assert content is None+ assert get.call_count == 1+ on_rate_limited.assert_not_called()++ def test_handled_rate_limit_give_up_logs_no_error(+ self, mocker, loguru_caplog+ ):+ """With on_rate_limited, the 429 give-up is a warning, not an error.++ ERROR records reach the user's browser via frontend_progress_sink,+ and a caller passing the callback handles the give-up itself. Red+ when the give-up keeps logging at ERROR regardless of the callback.+ """+ downloader, _ = self._rate_limited_downloader(mocker, 429)++ with loguru_caplog.at_level("DEBUG"):+ downloader._download_pdf(+ "https://example.com/paper.pdf",+ max_attempts=1,+ on_rate_limited=mocker.Mock(),+ )++ give_ups = [+ r for r in loguru_caplog.records if "after 1 attempts" in r.message+ ]+ assert [r.levelname for r in give_ups] == ["WARNING"]+ assert not [r for r in loguru_caplog.records if r.levelno >= 40]++ def test_unhandled_rate_limit_give_up_still_logs_an_error(+ self, mocker, loguru_caplog+ ):+ """Without a callback nobody handles the give-up: it stays ERROR."""+ downloader, _ = self._rate_limited_downloader(mocker, 429)++ with loguru_caplog.at_level("DEBUG"):+ downloader._download_pdf(+ "https://example.com/paper.pdf", max_attempts=1+ )++ assert any(+ r.levelname == "ERROR" and "after 1 attempts" in r.message+ for r in loguru_caplog.records+ )+++class TestDownloadPdfTransportFailureCallback:+ """on_transport_failure fires for failed requests, not for answers."""++ def _downloader(self, mocker, **get_kwargs):+ downloader = ConcreteDownloader()+ get = mocker.patch.object(downloader.session, "get", **get_kwargs)+ mocker.patch.object(+ downloader.rate_tracker, "apply_rate_limit", return_value=0+ )+ mocker.patch.object(downloader.rate_tracker, "record_outcome")+ return downloader, get++ def _status_response(self, mocker, status_code):+ response = mocker.Mock()+ response.status_code = status_code+ response.headers = {}+ return response++ def test_timeout_and_connection_error_report_once_as_warning(+ self, mocker, loguru_caplog+ ):+ for error in (+ requests.exceptions.Timeout("slow"),+ requests.exceptions.ConnectionError("down"),+ ):+ downloader, get = self._downloader(mocker, side_effect=error)+ on_failure = mocker.Mock()+ loguru_caplog.clear()++ with loguru_caplog.at_level("DEBUG"):+ content = downloader._download_pdf(+ "https://example.com/paper.pdf",+ max_attempts=1,+ on_transport_failure=on_failure,+ )++ assert content is None+ assert get.call_count == 1+ on_failure.assert_called_once_with()+ assert not [r for r in loguru_caplog.records if r.levelno >= 40]++ def test_unexpected_error_is_a_warning_only_with_a_callback(+ self, mocker, loguru_caplog+ ):+ # SafeSession raises ValueError when validate_url refuses the URL,+ # which is also how a failed DNS lookup surfaces; any other+ # exception takes the same catch-all branch. With a callback the+ # caller handles it (WARNING); without one it stays an ERROR.+ for error in (+ ValueError("URL failed security validation (possible SSRF)"),+ RuntimeError("boom"),+ ):+ for with_callback in (True, False):+ downloader, get = self._downloader(mocker, side_effect=error)+ on_failure = mocker.Mock() if with_callback else None+ loguru_caplog.clear()++ with loguru_caplog.at_level("DEBUG"):+ content = downloader._download_pdf(+ "https://example.com/paper.pdf",+ max_attempts=1,+ on_transport_failure=on_failure,+ )++ assert content is None+ assert get.call_count == 1+ errors = [+ r+ for r in loguru_caplog.records+ if r.levelno >= 40+ and "Unexpected error downloading" in r.message+ ]+ if with_callback:+ on_failure.assert_called_once_with()+ assert not [+ r for r in loguru_caplog.records if r.levelno >= 40+ ]+ assert any(+ r.levelname == "WARNING"+ and "Unexpected error downloading" in r.message+ for r in loguru_caplog.records+ )+ else:+ assert len(errors) == 1++ def test_server_errors_report_a_failure(self, mocker):+ for status_code in (500, 502, 504, 403):+ downloader, _ = self._downloader(+ mocker,+ return_value=self._status_response(mocker, status_code),+ )+ on_failure = mocker.Mock()++ downloader._download_pdf(+ "https://example.com/paper.pdf",+ max_attempts=1,+ on_transport_failure=on_failure,+ )++ on_failure.assert_called_once_with()++ def test_document_absent_answers_do_not_report_a_failure(self, mocker):+ for status_code in (404, 410):+ downloader, _ = self._downloader(+ mocker,+ return_value=self._status_response(mocker, status_code),+ )+ on_failure = mocker.Mock()++ downloader._download_pdf(+ "https://example.com/paper.pdf",+ max_attempts=1,+ on_transport_failure=on_failure,+ )++ on_failure.assert_not_called()++ def test_rate_limit_goes_to_its_own_callback(self, mocker):+ downloader, _ = self._downloader(+ mocker, return_value=self._status_response(mocker, 503)+ )+ on_rate_limited = mocker.Mock()+ on_failure = mocker.Mock()++ downloader._download_pdf(+ "https://example.com/paper.pdf",+ max_attempts=1,+ on_rate_limited=on_rate_limited,+ on_transport_failure=on_failure,+ )++ on_rate_limited.assert_called_once_with()+ on_failure.assert_not_called()++ def test_html_fetch_reports_failures_but_not_answers(+ self, mocker, loguru_caplog+ ):+ downloader = HTMLDownloader()+ mocker.patch.object(+ downloader.rate_tracker, "apply_rate_limit", return_value=0+ )+ mocker.patch.object(downloader.rate_tracker, "record_outcome")+ cases = [+ (requests.exceptions.Timeout("slow"), True),+ (self._status_response(mocker, 500), True),+ (self._status_response(mocker, 404), False),+ ]+ for outcome, reported in cases:+ get_kwargs = (+ {"side_effect": outcome}+ if isinstance(outcome, Exception)+ else {"return_value": outcome}+ )+ mocker.patch.object(downloader.session, "get", **get_kwargs)+ on_failure = mocker.Mock()+ loguru_caplog.clear()++ with loguru_caplog.at_level("DEBUG"):+ result = downloader._fetch_html_with_final_url(+ "https://example.com/page",+ on_transport_failure=on_failure,+ )++ assert result == (None, None)+ assert on_failure.called is reported+ assert not [r for r in loguru_caplog.records if r.levelno >= 40]+++class _FiniteBombRaw:+ """A raw HTTP body that yields a fixed number of 1 MiB decoded chunks.++ Mimics urllib3's ``HTTPResponse`` surface just enough for+ ``requests.Response.content``: ``stream`` routes through ``read`` (so+ a guard wrapping ``read`` sees every chunk) and both connection+ hooks are no-ops. The body is deliberately finite so a missing guard+ terminates instead of looping forever.+ """++ CHUNK = b"x" * (1024 * 1024)++ def __init__(self, chunks: int):+ self.remaining = chunks+ self.read_calls = 0++ def read(self, amt=None, decode_content=False):+ self.read_calls += 1+ if self.remaining <= 0:+ return b""+ self.remaining -= 1+ return self.CHUNK++ def stream(self, amt=None, decode_content=None):+ while True:+ data = self.read(amt, decode_content)+ if not data:+ break+ yield data++ def close(self):+ pass++ def release_conn(self):+ pass+++class TestDownloadPdfBodyCap:+ """The PDF transport must bound the decoded body size while reading."""++ def _bomb_response(self, chunks: int) -> requests.Response:+ response = requests.Response()+ response.status_code = 200+ response.headers["Content-Type"] = "application/pdf"+ # A valid, under-cap Content-Length is exactly the case+ # SafeSession leaves unguarded (see+ # security.safe_requests._check_response_size): the abort can+ # only come from BaseDownloader's own guard install.+ response.headers["Content-Length"] = "100"+ response.raw = _FiniteBombRaw(chunks)+ return response++ def test_oversized_decoded_body_aborts_download(self, mocker, monkeypatch):+ """A body decoding past MAX_RESPONSE_SIZE aborts, unretried.++ Red under reverting the _ensure_decoded_body_cap call: without+ the guard install the whole finite bomb (4 MiB against a 2 MiB+ cap) is read, passes the content-type PDF check, and is returned+ as a successful download.+ """+ from local_deep_research.security import safe_requests++ monkeypatch.setattr(safe_requests, "MAX_RESPONSE_SIZE", 2 * 1024 * 1024)++ downloader = ConcreteDownloader()+ mocker.patch.object(+ downloader.rate_tracker, "apply_rate_limit", return_value=0+ )+ record = mocker.patch.object(downloader.rate_tracker, "record_outcome")++ response = self._bomb_response(chunks=4)+ mocker.patch.object(downloader.session, "get", return_value=response)++ content = downloader._download_pdf("https://example.com/paper.pdf")++ assert content is None+ # One non-retried failure, labelled as the size cap+ assert record.call_count == 1+ assert record.call_args.kwargs["error_type"] == "ResponseBodyTooLarge"+ # The read stopped at the cap (1 + 1 MiB fit, the 3rd crosses it),+ # not at the whole bomb+ assert response.raw.read_calls == 3++ def test_under_cap_body_passes_through(self, mocker, monkeypatch):+ """A body under the cap still downloads normally through the guard."""+ from local_deep_research.security import safe_requests++ monkeypatch.setattr(safe_requests, "MAX_RESPONSE_SIZE", 2 * 1024 * 1024)++ downloader = ConcreteDownloader()+ mocker.patch.object(+ downloader.rate_tracker, "apply_rate_limit", return_value=0+ )+ record = mocker.patch.object(downloader.rate_tracker, "record_outcome")++ response = self._bomb_response(chunks=1)+ mocker.patch.object(downloader.session, "get", return_value=response)++ content = downloader._download_pdf("https://example.com/paper.pdf")++ assert content == _FiniteBombRaw.CHUNK+ assert record.call_args.kwargs["success"] is True+ # stream=True is load-bearing: without it Session.send consumes+ # the body before the guard could wrap the reads+ assert downloader.session.get.call_args.kwargs["stream"] is True+++class TestFetchHtmlBodyCap:+ """The HTML transport must bound the decoded body size while reading.++ Twin of TestDownloadPdfBodyCap above for the HTMLDownloader leg+ (``_fetch_html_with_final_url``): the same finite bomb, the same valid+ under-cap Content-Length SafeSession leaves unguarded, and the same+ abort contract.+ """++ def _bomb_response(self, chunks: int) -> requests.Response:+ response = requests.Response()+ response.status_code = 200+ response.headers["Content-Type"] = "text/html; charset=utf-8"+ # A valid, under-cap Content-Length is exactly the case+ # SafeSession leaves unguarded (see+ # security.safe_requests._check_response_size): the abort can+ # only come from BaseDownloader's own guard install.+ response.headers["Content-Length"] = "100"+ response.url = "https://example.com/page"+ # Pin the codec so .text never runs charset detection on the bomb+ response.encoding = "utf-8"+ response.raw = _FiniteBombRaw(chunks)+ return response++ def test_oversized_decoded_body_aborts_html_fetch(+ self, mocker, monkeypatch+ ):+ """A body decoding past MAX_RESPONSE_SIZE aborts the HTML fetch.++ Red under reverting the _ensure_decoded_body_cap call (or the+ stream=True it depends on) in html.py's _fetch_html_with_final_url:+ without the guard install the whole finite bomb (4 MiB against a+ 2 MiB cap) is decoded and returned as the page text with a success+ outcome recorded.+ """+ from local_deep_research.security import safe_requests++ monkeypatch.setattr(safe_requests, "MAX_RESPONSE_SIZE", 2 * 1024 * 1024)++ downloader = HTMLDownloader()+ mocker.patch.object(+ downloader.rate_tracker, "apply_rate_limit", return_value=0+ )+ record = mocker.patch.object(downloader.rate_tracker, "record_outcome")++ response = self._bomb_response(chunks=4)+ mocker.patch.object(downloader.session, "get", return_value=response)++ result = downloader._fetch_html_with_final_url(+ "https://example.com/page"+ )++ assert result == (None, None)+ # No success outcome recorded: exactly one failure, from the outer+ # except after the body guard raised mid-read+ assert record.call_count == 1+ assert record.call_args.kwargs["success"] is False+ # The read stopped at the cap (1 + 1 MiB fit, the 3rd crosses it),+ # not at the whole bomb+ assert response.raw.read_calls == 3+ # stream=True is load-bearing: without it Session.send consumes+ # the body before the guard could wrap the reads+ assert downloader.session.get.call_args.kwargs["stream"] is True+++class TestDecodedBodyCapOnTheWire:+ """Gzip bodies served over a real socket, so urllib3 picks the reader.++ The fakes above route ``stream`` through ``read``. A real+ ``Transfer-Encoding: chunked`` response never calls ``raw.read``:+ urllib3's ``stream`` hands it to ``read_chunked``. These serve each+ framing from a local socket (127.0.0.1 only) through a real+ ``SafeSession`` and check both downloader legs stop at the cap on the+ *decoded* bytes. Red when the ``read_chunked`` wrap in+ ``safe_requests._install_body_guard`` is removed (chunked cases), or+ when ``_ensure_decoded_body_cap`` is not called (the small+ ``Content-Length`` cases).+ """++ CAP = 64 * 1024+ # ~4 MiB of zeros compresses to a few KiB: far past the cap once+ # decoded, far under it on the wire.+ DECODED = b"%PDF" + b"\0" * (4 * 1024 * 1024)++ @classmethod+ def _serve(cls, sock, framing, content_type, body):+ conn, _ = sock.accept()+ try:+ conn.recv(65536)+ head = (+ b"HTTP/1.1 200 OK\r\n"+ b"Content-Type: " + content_type + b"\r\n"+ b"Content-Encoding: gzip\r\n"+ )+ if framing == "chunked":+ conn.sendall(head + b"Transfer-Encoding: chunked\r\n\r\n")+ for i in range(0, len(body), 1024):+ part = body[i : i + 1024]+ conn.sendall(b"%x\r\n" % len(part) + part + b"\r\n")+ conn.sendall(b"0\r\n\r\n")+ else:+ conn.sendall(+ head + b"Content-Length: %d\r\n\r\n" % len(body) + body+ )+ except OSError:+ pass # the guard closes the connection mid-body when over cap+ finally:+ conn.close()+ sock.close()++ def _url(self, framing, content_type, decoded):+ import gzip+ import socket+ import threading++ sock = socket.socket()+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)+ sock.bind(("127.0.0.1", 0))+ sock.listen(1)+ threading.Thread(+ target=self._serve,+ args=(sock, framing, content_type, gzip.compress(decoded)),+ daemon=True,+ ).start()+ return f"http://127.0.0.1:{sock.getsockname()[1]}/doc"++ @staticmethod+ def _local(downloader, mocker):+ from local_deep_research.security.safe_requests import SafeSession++ downloader.session.close()+ downloader.session = SafeSession(allow_localhost=True)+ mocker.patch.object(+ downloader.rate_tracker, "apply_rate_limit", return_value=0+ )+ return mocker.patch.object(downloader.rate_tracker, "record_outcome")++ @pytest.fixture(autouse=True)+ def _small_cap(self, monkeypatch):+ from local_deep_research.security import safe_requests++ monkeypatch.setattr(safe_requests, "MAX_RESPONSE_SIZE", self.CAP)++ @pytest.mark.parametrize("framing", ["chunked", "content-length"])+ def test_pdf_gzip_bomb_is_refused_at_the_cap(self, mocker, framing):+ downloader = ConcreteDownloader()+ record = self._local(downloader, mocker)+ url = self._url(framing, b"application/pdf", self.DECODED)++ assert downloader._download_pdf(url, max_attempts=1) is None+ assert record.call_args.kwargs["error_type"] == "ResponseBodyTooLarge"+ downloader.close()++ @pytest.mark.parametrize("framing", ["chunked", "content-length"])+ def test_html_gzip_bomb_is_refused_at_the_cap(self, mocker, framing):+ downloader = HTMLDownloader()+ record = self._local(downloader, mocker)+ url = self._url(framing, b"text/html; charset=utf-8", self.DECODED)++ assert downloader._fetch_html_with_final_url(url) == (None, None)+ assert record.call_args.kwargs["success"] is False+ assert record.call_args.kwargs["error_type"] == "ValueError"+ downloader.close()++ @pytest.mark.parametrize("framing", ["chunked", "content-length"])+ def test_under_cap_gzip_bodies_pass(self, mocker, framing):+ body = b"%PDF-1.4 " + b"a" * 4096+ downloader = ConcreteDownloader()+ self._local(downloader, mocker)+ assert (+ downloader._download_pdf(+ self._url(framing, b"application/pdf", body), max_attempts=1+ )+ == body+ )+ downloader.close()++ page = b"<html><body>" + b"b" * 4096 + b"</body></html>"+ html = HTMLDownloader()+ self._local(html, mocker)+ text, _ = html._fetch_html_with_final_url(+ self._url(framing, b"text/html; charset=utf-8", page)+ )+ assert text == page.decode()+ html.close()+++class TestDownloadPdfConnectionReleased:+ """_download_pdf must release the response's connection on every path.++ ``finally: safe_close(response, "downloader response")`` (base.py) is+ what calls ``response.close()`` for a ``stream=True`` request; nothing+ else in the method does. Red under deleting that finally line: neither+ test below observes ``response.close()`` being called.+ """++ def test_closed_on_success(self, mocker, mock_pdf_content):+ """The connection is released after a successful download."""+ downloader = ConcreteDownloader()++ mock_response = mocker.Mock()+ mock_response.status_code = 200+ mock_response.content = mock_pdf_content+ mock_response.headers = {"content-type": "application/pdf"}++ mocker.patch.object(+ downloader.session, "get", return_value=mock_response+ )+ mocker.patch.object(+ downloader.rate_tracker, "apply_rate_limit", return_value=0+ )+ mocker.patch.object(downloader.rate_tracker, "record_outcome")++ content = downloader._download_pdf("https://example.com/paper.pdf")++ assert content == mock_pdf_content+ mock_response.close.assert_called_once()++ def test_closed_on_abort(self, mocker):+ """The connection is released on a non-retried failure (HTTP 404)."""+ downloader = ConcreteDownloader()++ mock_response = mocker.Mock()+ mock_response.status_code = 404+ mock_response.content = b""+ mock_response.headers = {}++ mocker.patch.object(+ downloader.session, "get", return_value=mock_response+ )+ mocker.patch.object(+ downloader.rate_tracker, "apply_rate_limit", return_value=0+ )+ mocker.patch.object(downloader.rate_tracker, "record_outcome")++ content = downloader._download_pdf("https://example.com/paper.pdf")++ assert content is None+ mock_response.close.assert_called_once()+++class TestFetchHtmlConnectionReleased:+ """_fetch_html_with_final_url must release the connection on every path.++ ``finally: safe_close(response, "HTML download response")`` (html.py)+ is what calls ``response.close()`` for a ``stream=True`` request; red+ under deleting that finally line for the same reason as+ TestDownloadPdfConnectionReleased above.+ """++ def test_closed_on_success(self, mocker):+ """The connection is released after a successful fetch."""+ downloader = HTMLDownloader()++ mock_response = mocker.Mock()+ mock_response.status_code = 200+ mock_response.text = "<html><body>hi</body></html>"+ mock_response.headers = {"content-type": "text/html; charset=utf-8"}+ mock_response.url = "https://example.com/page"++ mocker.patch.object(+ downloader.session, "get", return_value=mock_response+ )+ mocker.patch.object(+ downloader.rate_tracker, "apply_rate_limit", return_value=0+ )+ mocker.patch.object(downloader.rate_tracker, "record_outcome")++ result = downloader._fetch_html_with_final_url(+ "https://example.com/page"+ )++ assert result == (mock_response.text, mock_response.url)+ mock_response.close.assert_called_once()++ def test_closed_on_abort(self, mocker):+ """The connection is released on a failed fetch (HTTP 404)."""+ downloader = HTMLDownloader()++ mock_response = mocker.Mock()+ mock_response.status_code = 404+ mock_response.headers = {}++ mocker.patch.object(+ downloader.session, "get", return_value=mock_response+ )+ mocker.patch.object(+ downloader.rate_tracker, "apply_rate_limit", return_value=0+ )+ mocker.patch.object(downloader.rate_tracker, "record_outcome")++ result = downloader._fetch_html_with_final_url(+ "https://example.com/page"+ )++ assert result == (None, None)+ mock_response.close.assert_called_once()+class TestExtractTextFromPdf:"""Tests for extract_text_from_pdf static method."""diff --git a/tests/research_library/downloaders/test_extraction_pipeline.py b/tests/research_library/downloaders/test_extraction_pipeline.pyindex 8ad5c9f3b5..58e9b6cc1c 100644--- a/tests/research_library/downloaders/test_extraction_pipeline.py+++ b/tests/research_library/downloaders/test_extraction_pipeline.py@@ -450,6 +450,21 @@ class TestTrySpecializedDownloader:assert result.content is Noneassert result.fallback_allowed is True+ @pytest.mark.parametrize(+ "url",+ (+ "https://arxiv.org/about",+ "https://arxiv.org/help",+ "https://arxiv.org/list/cs.AI",+ "https://arxiv.org/blog",+ ),+ )+ def test_arxiv_non_paper_pages_allow_generic_fallback(self, url):+ result = pipeline._try_specialized_downloader(url)++ assert result.content is None+ assert result.fallback_allowed is True+@pytest.mark.parametrize("url",(diff --git a/tests/research_library/services/test_download_service_arxiv_provenance.py b/tests/research_library/services/test_download_service_arxiv_provenance.pyindex e4807793f9..d439ec6d11 100644--- a/tests/research_library/services/test_download_service_arxiv_provenance.py+++ b/tests/research_library/services/test_download_service_arxiv_provenance.py@@ -249,7 +249,8 @@ def test_family_url_without_an_identifier_falls_through(service, url):def test_exhausted_retry_budget_falls_through_to_the_stored_pdf(service):- # Given an arXiv paper whose retry budget is spent+ # Given an arXiv paper whose retry budget is spent and which has no+ # stored PDF the storage manager can loadresource = MagicMock()resource.id = 25resource.url = "https://arxiv.org/abs/2301.12345"@@ -260,7 +261,9 @@ def test_exhausted_retry_budget_falls_through_to_the_stored_pdf(service):service.retry_manager.should_retry_resource.return_value = deniedwith (- patch(f"{MODULE}.get_document_for_resource") as get_document,+ patch(+ f"{MODULE}.get_document_for_resource", return_value=None+ ) as get_document,patch(f"{MODULE}.PDFStorageManager") as storage_manager,patch.object(service, "_get_downloader") as get_downloader,patch.object(service, "_check_url_against_policy") as policy_check,@@ -272,7 +275,7 @@ def test_exhausted_retry_budget_falls_through_to_the_stored_pdf(service):# download_as_text still reaches _try_existing_pdf_extraction -- a pure# filesystem read that produced text before this path existedassert result is None- get_document.assert_not_called()+ get_document.assert_called_once_with(session, resource)storage_manager.assert_not_called()get_downloader.assert_not_called()policy_check.assert_not_called()@@ -396,6 +399,10 @@ def test_arxiv_retry_denial_skips_work_and_retry_record(service):patch(f"{MODULE}.get_user_db_session", return_value=_make_ctx(session)),patch.object(service, "_try_existing_text", return_value=None),patch.object(service, "_try_legacy_text_file", return_value=None),+ # No stored document, so the denial path's local read finds+ # nothing and it declines without a verdict; the filesystem+ # strategy is mocked out here.+ patch(f"{MODULE}.get_document_for_resource", return_value=None),patch(f"{MODULE}.PDFStorageManager") as storage_manager,patch.object(service, "_get_downloader") as get_downloader,patch.object(service, "_check_url_against_policy") as policy_check,@@ -420,6 +427,289 @@ def test_arxiv_retry_denial_skips_work_and_retry_record(service):service.retry_manager.record_attempt.assert_not_called()+def test_arxiv_retry_denial_reads_a_database_stored_pdf(service):+ """A retry-denied resource whose PDF is stored in the database gets text.++ The default storage mode keeps the PDF as a database blob and leaves+ ``file_path`` unset, so the filesystem strategy+ (``_try_existing_pdf_extraction``, run for real here) finds nothing.+ The retry gate denies the network, but the canonical path still reads+ the stored blob through the storage manager, entirely locally, the way+ the egress-denied path does. No network-bearing step runs.+ """+ resource = MagicMock()+ resource.id = 29+ resource.url = "https://arxiv.org/abs/2301.12345"+ resource.source_type = "web"+ resource.title = "Database-stored PDF"+ session = MagicMock()+ document = MagicMock()+ document.id = "database-pdf-document"+ # The string form satisfies both stored-PDF readers' status checks, so+ # the filesystem strategy is stopped by the missing file_path alone.+ document.status = "completed"+ document.file_type = "pdf"+ document.file_path = None+ # First lookup is the resource; any later one is its stored document.+ session.query.return_value.filter_by.return_value.first.side_effect = [+ resource+ ] + [document] * 5+ decision = service.retry_manager.should_retry_resource.return_value+ decision.can_retry = False+ decision.reason = "retry denied"+ storage_manager = MagicMock()+ storage_manager.load_pdf.return_value = b"%PDF-database-blob"++ with (+ patch(f"{MODULE}.get_user_db_session", return_value=_make_ctx(session)),+ patch.object(service, "_try_existing_text", return_value=None),+ patch.object(service, "_try_legacy_text_file", return_value=None),+ patch(f"{MODULE}.get_document_for_resource", return_value=document),+ patch(f"{MODULE}.PDFStorageManager", return_value=storage_manager),+ patch(+ f"{MODULE}.ArxivDownloader.extract_text_from_pdf",+ return_value="text from the database blob",+ ),+ patch.object(service, "_save_text_with_db") as save_text,+ patch.object(service, "_get_downloader") as get_downloader,+ patch.object(service, "_check_url_against_policy") as policy_check,+ patch.object(service, "_try_api_text_extraction") as api_text,+ patch.object(service, "_fallback_pdf_extraction") as fallback,+ ):+ result = service.download_as_text(resource.id)++ # Then the text arrives from the stored blob and no network path ran+ assert result == (True, None)+ storage_manager.load_pdf.assert_called_once_with(document, session)+ save_text.assert_called_once_with(+ resource,+ "text from the database blob\n\n"+ "Source: https://arxiv.org/abs/2301.12345",+ session,+ extraction_method="pdf_extraction",+ extraction_source="local_pdf",+ pdf_document_id="database-pdf-document",+ )+ get_downloader.assert_not_called()+ policy_check.assert_not_called()+ api_text.assert_not_called()+ fallback.assert_not_called()+++def test_arxiv_retry_denial_ignores_a_failed_stored_pdf_save(service):+ """A failed local read under a retry denial leaves the denial to stand.++ Only a success is returned from the denial path; a save failure falls+ through, so download_as_text's own gate returns the denial and no+ failure is recorded against a resource that made no request.+ """+ resource = MagicMock()+ resource.id = 32+ resource.url = "https://arxiv.org/abs/2301.12345"+ resource.source_type = "web"+ session = MagicMock()+ session.query.return_value.filter_by.return_value.first.return_value = (+ resource+ )+ decision = service.retry_manager.should_retry_resource.return_value+ decision.can_retry = False+ decision.reason = "retry denied"++ with (+ patch(f"{MODULE}.get_user_db_session", return_value=_make_ctx(session)),+ patch.object(service, "_try_existing_text", return_value=None),+ patch.object(service, "_try_legacy_text_file", return_value=None),+ patch.object(+ service,+ "_text_from_cached_pdf",+ return_value=(False, "Failed to extract arXiv text"),+ ) as cached_read,+ patch.object(+ service, "_try_existing_pdf_extraction", return_value=None+ ) as existing_pdf,+ patch.object(service, "_get_downloader") as get_downloader,+ ):+ result = service.download_as_text(resource.id)++ assert result == (False, "retry denied")+ cached_read.assert_called_once_with(session, resource)+ existing_pdf.assert_called_once_with(session, resource, resource.id)+ get_downloader.assert_not_called()+ service.retry_manager.record_attempt.assert_not_called()+++def test_arxiv_egress_denial_with_cached_pdf_extracts_locally(service):+ """An egress-denied resource with a stored PDF still gets its text."""+ resource = MagicMock()+ resource.id = 30+ resource.url = "https://arxiv.org/abs/2301.12345"+ resource.title = "Egress denied cached PDF"+ session = MagicMock()+ arxiv = MagicMock(spec=ArxivDownloader)++ document = MagicMock()+ document.id = "cached-pdf-document-egress"+ document.status = DocumentStatus.COMPLETED+ document.file_type = "pdf"+ storage_manager = MagicMock()+ storage_manager.load_pdf.return_value = b"%PDF-cached-egress"++ with (+ patch(f"{MODULE}.get_document_for_resource", return_value=document),+ patch(f"{MODULE}.PDFStorageManager", return_value=storage_manager),+ patch.object(service, "_get_downloader", return_value=arxiv),+ patch.object(+ service,+ "_check_url_against_policy",+ return_value=(False, "blocked"),+ ),+ patch(+ f"{MODULE}.ArxivDownloader.extract_text_from_pdf",+ return_value="egress cached text",+ ),+ patch.object(service, "_save_text_with_db") as save_text,+ ):+ outcome = service._try_arxiv_text_extraction(session, resource)++ # Then the extraction succeeded entirely locally: (True, None) in the+ # plain tuple contract this method speaks on main.+ assert outcome == (True, None)+ arxiv.download_text_with_source.assert_not_called()+ save_text.assert_called_once_with(+ resource,+ "egress cached text\n\nSource: https://arxiv.org/abs/2301.12345",+ session,+ extraction_method="pdf_extraction",+ extraction_source="local_pdf",+ pdf_document_id="cached-pdf-document-egress",+ )+ session.commit.assert_called_once_with()+++def _stored_document(status=DocumentStatus.COMPLETED, file_type="pdf"):+ document = MagicMock()+ document.id = "stored-document"+ document.status = status+ document.file_type = file_type+ return document+++ ("document", "stored_bytes", "extracted_text"),+ (+ pytest.param(None, b"%PDF-stored", "stored text", id="no_document"),+ pytest.param(+ _stored_document(status=DocumentStatus.PENDING),+ b"%PDF-stored",+ "stored text",+ id="document_not_completed",+ ),+ pytest.param(+ _stored_document(file_type="html"),+ b"%PDF-stored",+ "stored text",+ id="document_not_a_pdf",+ ),+ pytest.param(+ _stored_document(), None, "stored text", id="pdf_bytes_missing"+ ),+ pytest.param(+ _stored_document(), b"%PDF-stored", "", id="pdf_yields_no_text"+ ),+ ),+)+def test_arxiv_egress_denial_without_usable_cached_pdf_returns_denial(+ service, document, stored_bytes, extracted_text+):+ """An egress-denied resource with no usable stored PDF keeps the denial.++ Each case removes one precondition of the local read. Every other+ precondition holds and the extraction stub returns text where it is+ reached, so dropping the guard for the missing one would save text+ and turn the outcome into a success.+ """+ resource = MagicMock()+ resource.id = 31+ resource.url = "https://arxiv.org/abs/2301.12345"+ resource.title = "Egress denied, no usable stored PDF"+ session = MagicMock()+ arxiv = MagicMock(spec=ArxivDownloader)+ # Were the network path reached, it would yield no text, so the+ # outcome itself (not an incidental error) shows the denial held.+ arxiv.download_text_with_source.return_value = None+ storage_manager = MagicMock()+ storage_manager.load_pdf.return_value = stored_bytes++ with (+ patch(f"{MODULE}.get_document_for_resource", return_value=document),+ patch(f"{MODULE}.PDFStorageManager", return_value=storage_manager),+ patch.object(service, "_get_downloader", return_value=arxiv),+ patch.object(+ service,+ "_check_url_against_policy",+ return_value=(False, "blocked"),+ ),+ patch(+ f"{MODULE}.ArxivDownloader.extract_text_from_pdf",+ return_value=extracted_text,+ ),+ patch.object(service, "_save_text_with_db"),+ ):+ outcome = service._try_arxiv_text_extraction(session, resource)++ # Then the denial stands and the network text path was never entered+ assert outcome == (False, "egress_policy_denied:blocked")+ arxiv.download_text_with_source.assert_not_called()+++ "cached_read",+ (+ pytest.param(+ {"return_value": (False, "Failed to extract arXiv text: boom")},+ id="stored_text_save_failed",+ ),+ pytest.param(+ {"side_effect": RuntimeError("stored PDF unreadable")},+ id="stored_read_raised",+ ),+ ),+)+def test_arxiv_egress_denial_keeps_its_reason_when_the_local_read_fails(+ service, cached_read+):+ """Only a local success replaces an egress denial.++ A failed save of the stored PDF's text, or a read that raises, must+ leave ``egress_policy_denied:<reason>`` as the outcome: that reason is+ what the caller records, and the save error would bury it. Red under+ returning any non-None local outcome, and under letting the exception+ reach the outer handler (which returns a "Failed to extract" error).+ """+ resource = MagicMock()+ resource.id = 33+ resource.url = "https://arxiv.org/abs/2301.12345"+ session = MagicMock()+ arxiv = MagicMock(spec=ArxivDownloader)++ with (+ patch.object(service, "_get_downloader", return_value=arxiv),+ patch.object(+ service,+ "_check_url_against_policy",+ return_value=(False, "blocked"),+ ),+ patch.object(+ service, "_text_from_cached_pdf", **cached_read+ ) as local_read,+ ):+ outcome = service._try_arxiv_text_extraction(session, resource)++ assert outcome == (False, "egress_policy_denied:blocked")+ local_read.assert_called_once_with(session, resource)+ arxiv.download_text_with_source.assert_not_called()++def test_arxiv_success_records_one_terminal_retry_attempt(service):resource = MagicMock()resource.id = 26diff --git a/tests/research_library/services/test_download_service_deep_coverage.py b/tests/research_library/services/test_download_service_deep_coverage.pyindex 77e3994eb1..7ed151a1f8 100644--- a/tests/research_library/services/test_download_service_deep_coverage.py+++ b/tests/research_library/services/test_download_service_deep_coverage.py@@ -349,11 +349,19 @@ class TestDownloadPdfDeep:)stored_pdf_doc = MagicMock()stored_pdf_doc.id = "new-doc-id"+ document_lookups = iter([None, stored_pdf_doc])++ def get_document_for_resource(_session, _resource):+ events.append("document_lookup")+ return next(document_lookups)++ session.flush.side_effect = lambda: events.append("session_flush")+ session.commit.side_effect = lambda: events.append("session_commit")with (patch(f"{MODULE}.get_document_for_resource",- side_effect=[None, stored_pdf_doc],+ side_effect=get_document_for_resource,),patch(f"{MODULE}.get_source_type_id", return_value="src-type-1"),patch(f"{MODULE}.get_default_library_id", return_value="lib-col-1"),@@ -374,7 +382,11 @@ class TestDownloadPdfDeep:assert success is Trueassert reason is None- # Then PDF bytes are stored first and reused by canonical text production+ # Then the exact PDF bytes are stored and reused by canonical text+ # production. Text is produced BEFORE the PDF persistence block:+ # producing canonical text may issue a network (HTML) request, and+ # doing that with the Document write transaction already open would+ # hold the write lock across the network round-trip.downloader.download_with_result.assert_called_once_with(resource.url, ContentType.PDF)@@ -385,7 +397,18 @@ class TestDownloadPdfDeep:resource.url,pdf_content=pdf_content,)- assert events == ["pdf_stored", "text_produced"]+ # Text production precedes every persistence step: the Document+ # lookup, the flush that opens the write transaction, the PDF save+ # and the commit that closes it. The trailing lookup runs after that+ # commit and resolves the stored PDF's id for the text row.+ assert events == [+ "text_produced",+ "document_lookup",+ "session_flush",+ "pdf_stored",+ "session_commit",+ "document_lookup",+ ]local_pdf_extract.assert_not_called()save_text.assert_called_once_with(resource=resource,@@ -557,6 +580,202 @@ class TestDownloadPdfDeep:local_pdf_extract.assert_not_called()save_text.assert_not_called()+ def test_arxiv_text_save_exception_does_not_fail_pdf_download(self, svc):+ """A text-save DB failure must not discard the PDF persistence.++ Replaces an earlier MagicMock-session version of this test: a mock+ session never executes _save_text_with_db's full-session rollback,+ so it certified nothing about row survival and passed verbatim on+ code where that rollback discarded every uncommitted PDF write --+ attempt row, Document row, PDF blob, collection link -- while the+ caller went on to mark the queue COMPLETED and record a retry+ success: the user is told success and the database keeps nothing.++ This version uses a real in-memory SQLite session (the idiom of+ test_download_service_3827_fix) and a text save that fails exactly+ the way the real one does -- it rolls the shared session back,+ then re-raises IntegrityError. The download must still report+ success AND the Document row, PDF blob, and attempt row must+ SURVIVE in the database. Red under surgically removing the+ session.commit() that makes PDF persistence its own transaction+ before the best-effort text save: the rollback then wipes every+ row.+ """+ import uuid as _uuid++ from sqlalchemy import create_engine+ from sqlalchemy.exc import IntegrityError+ from sqlalchemy.orm import sessionmaker++ from local_deep_research.database.models import Base+ from local_deep_research.database.models.download_tracker import (+ DownloadAttempt,+ DownloadTracker,+ )+ from local_deep_research.database.models.library import (+ Collection,+ Document,+ DocumentBlob,+ DocumentCollection,+ DocumentStatus,+ SourceType,+ )+ from local_deep_research.database.models.research import (+ ResearchHistory,+ ResearchResource,+ )+ from local_deep_research.research_library.downloaders import (+ ArxivDownloader,+ )+ from local_deep_research.research_library.downloaders.arxiv import (+ ArxivTextResult,+ ArxivTextSource,+ )+ from local_deep_research.research_library.utils import get_url_hash++ engine = create_engine("sqlite:///:memory:")+ Base.metadata.create_all(engine)+ session = sessionmaker(bind=engine)()++ try:+ # Seed: source type, default Library collection, a research+ # history row (ResearchResource FK), a resource, and a tracker+ # committed the way download_resource commits it before+ # calling _download_pdf.+ source_type = SourceType(+ id=str(_uuid.uuid4()),+ name="research_download",+ display_name="Research Download",+ )+ library = Collection(+ id=str(_uuid.uuid4()),+ name="Library",+ is_default=True,+ collection_type="default_library",+ )+ research = ResearchHistory(+ id=str(_uuid.uuid4()),+ query="test query",+ mode="quick",+ status="completed",+ created_at="2026-05-09T00:00:00",+ )+ session.add_all([source_type, library, research])+ session.commit()++ resource = ResearchResource(+ research_id=research.id,+ title="Text Save Failure Paper",+ url="https://arxiv.org/abs/2301.12345",+ source_type="academic",+ created_at="2026-05-09T00:00:00",+ )+ session.add(resource)+ session.flush()++ url_hash = get_url_hash(resource.url)+ tracker = DownloadTracker(+ url=resource.url,+ url_hash=url_hash,+ first_resource_id=resource.id,+ is_downloaded=False,+ )+ session.add(tracker)+ session.commit()++ svc.settings.get_setting.side_effect = lambda key, default=None: {+ "research_library.pdf_storage_mode": "database",+ "research_library.max_pdf_size_mb": 100,+ }.get(key, default)++ downloader = MagicMock(spec=ArxivDownloader)+ result_obj = MagicMock()+ result_obj.is_success = True+ pdf_content = b"%PDF-1.4 ok"+ result_obj.content = pdf_content+ result_obj.skip_reason = None+ result_obj.status_code = None+ downloader.can_handle.return_value = True+ downloader.download_with_result.return_value = result_obj+ downloader.download_text_with_source.return_value = ArxivTextResult(+ text="Official HTML text",+ source=ArxivTextSource.ARXIV_HTML,+ )+ svc.downloaders = [downloader]++ def _text_save_fails_like_the_real_one(*args, **kwargs):+ # The real _save_text_with_db rolls the shared session+ # back, then re-raises (issue #3827). Mirror that exactly:+ # the rollback is the mechanism that used to discard the+ # uncommitted PDF persistence.+ session.rollback()+ raise IntegrityError(+ "UPDATE documents",+ {},+ Exception("UNIQUE constraint failed"),+ )++ with (+ patch(+ f"{MODULE}.get_source_type_id",+ return_value=source_type.id,+ ),+ patch(+ f"{MODULE}.get_default_library_id",+ return_value=library.id,+ ),+ patch.object(+ svc,+ "_save_text_with_db",+ side_effect=_text_save_fails_like_the_real_one,+ ) as save_text,+ ):+ # When the PDF download workflow completes+ success, reason, _status_code = svc._download_pdf(+ resource, tracker, session+ )+ assert success is True # text-save failure does not fail it+ assert reason is None++ save_text.assert_called_once()+ # No false inaccessibility signal was recorded for the local+ # DB error (the outer except would have set is_accessible=False)+ assert tracker.is_accessible is True++ # Then the PDF persistence survived the text-save rollback in+ # the database, not just in the session's memory.+ session.expire_all()+ doc = (+ session.query(Document)+ .filter_by(resource_id=resource.id)+ .one_or_none()+ )+ assert doc is not None, "Document row must survive"+ assert doc.status == DocumentStatus.COMPLETED+ blob = (+ session.query(DocumentBlob)+ .filter_by(document_id=doc.id)+ .one_or_none()+ )+ assert blob is not None, "PDF blob must survive"+ assert blob.pdf_binary == pdf_content+ link = (+ session.query(DocumentCollection)+ .filter_by(document_id=doc.id)+ .one_or_none()+ )+ assert link is not None, "Collection link must survive"+ attempts = (+ session.query(DownloadAttempt)+ .filter_by(url_hash=url_hash)+ .all()+ )+ assert len(attempts) == 1, "Attempt row must survive"+ assert attempts[0].succeeded is True+ finally:+ session.close()+ engine.dispose()+def test_outer_exception_caught_and_sanitized(self, svc):"""Exceptions inside the try block are caught and sanitized via sanitize_error_for_client."""session = MagicMock()diff --git a/tests/research_library/services/test_download_service_strategy_coverage.py b/tests/research_library/services/test_download_service_strategy_coverage.pyindex f8bcbfd20a..5429ba97e6 100644--- a/tests/research_library/services/test_download_service_strategy_coverage.py+++ b/tests/research_library/services/test_download_service_strategy_coverage.py@@ -677,6 +677,13 @@ class TestDownloadAsTextSuccess:),patch.object(svc, "_try_existing_text", return_value=None),patch.object(svc, "_try_legacy_text_file", return_value=None),+ # The storage-manager read the denial path tries first finds+ # nothing it can load (covered in+ # test_download_service_arxiv_provenance.py), so the call+ # reaches the filesystem strategy this test is about.+ patch.object(+ svc, "_text_from_cached_pdf", return_value=None+ ) as cached_read,patch.object(svc, "_get_downloader") as get_downloader,patch(f"{MODULE}.get_absolute_path_from_settings",@@ -695,6 +702,7 @@ class TestDownloadAsTextSuccess:# Then the spent budget stops only the network-bearing arXiv path; the# pure filesystem read still runs and returns the text the user hadassert (success, error) == (True, None)+ cached_read.assert_called_once_with(session, resource)get_downloader.assert_not_called()save_text.assert_called_once_with(resource,diff --git a/tests/security/test_ssrf_egress_policy.py b/tests/security/test_ssrf_egress_policy.pyindex 166de8f199..e49d2fed1c 100644--- a/tests/security/test_ssrf_egress_policy.py+++ b/tests/security/test_ssrf_egress_policy.py@@ -216,7 +216,7 @@ def test_scanner_ignores_wrapper_backed_calls():assert _scan_source(_GATED_PROBE) == []-# The only two modules in the package allowed to touch a raw HTTP client.+# The only modules in the package allowed to touch a raw HTTP client.# Anything else appearing here is a new ungated egress path._REVIEWED_RAW_EGRESS = {# The SSRF wrapper itself: validates + DNS-pins, then calls requests.diff --git a/tests/utilities/test_arxiv_policy_client.py b/tests/utilities/test_arxiv_policy_client.pyindex 5cc464f7a7..b1623aa7c8 100644--- a/tests/utilities/test_arxiv_policy_client.py+++ b/tests/utilities/test_arxiv_policy_client.py@@ -9,20 +9,25 @@ that constructs ``arxiv.Client`` through the ``arxiv`` module attributewith ``delay_seconds=0``, closes the discarded default session, pins agated ``SafeSession`` whose wire call forces ``timeout=10`` and``allow_redirects=False``, yields the client, and closes the adapted-session in ``finally``.--Deterministic seams mirror the downloader gate naming so existing test-patches retarget cleanly: ``_arxiv_api_request_lock``,-``_last_request_started_at``, ``_monotonic``, ``_sleep``.+session in ``finally``. Session installation goes through+``_install_gated_session``, which raises ``ImportError`` unless the+client exposes a real ``requests.Session`` at its private ``_session``+attribute, so an ``arxiv`` release changing that internals shape fails+loudly instead of silently bypassing the gate. Deterministic seams+mirror the downloader gate naming so existing test patches retarget+cleanly: ``_arxiv_api_request_lock``, ``_last_request_started_at``,+``_monotonic``, ``_sleep``."""from collections.abc import Iteratorfrom dataclasses import dataclass+from types import SimpleNamespacefrom typing import Protocolfrom unittest.mock import MagicMockimport arxivimport pytest+import requestsfrom pytest_mock import MockerFixturefrom local_deep_research.security import SafeSession@@ -61,7 +66,7 @@ class StubbedClientFactory:constructed: list[StubClientConstruction]instances: list[StubArxivClient]- default_sessions: list[MagicMock]+ default_sessions: list[requests.Session]@pytest.fixture(autouse=True)@@ -92,8 +97,13 @@ def stub_arxiv_client(mocker: MockerFixture) -> Iterator[StubbedClientFactory]:self.delay_seconds: float = delay_secondsself.num_retries: int = num_retriesself._last_request_dt: float | None = None- default_session = MagicMock(name="default_session")- self._session: MagicMock = default_session+ # The policy adapter guards on _session being a real+ # requests.Session (see _install_gated_session), so the+ # double must pin one; its close is spied so tests can+ # still assert the discarded session was closed.+ default_session = requests.Session()+ default_session.close = MagicMock(wraps=default_session.close)+ self._session: requests.Session = default_sessionconstructed.append(StubClientConstruction(page_size=page_size,@@ -314,5 +324,106 @@ class TestPolicyArxivClient:call = request.call_argsassert call is not Noneassert call.kwargs.get("timeout") == 10- assert call.kwargs.get("allow_redirects") is Falseassert call.kwargs.get("headers") == {"User-Agent": "LDR-test"}+++class TestInstallGatedSession:+ """Guard tests for the private ``client._session`` mutation."""++ def test_raises_import_error_when_session_attribute_missing(self) -> None:+ # Given a client double without the private _session attribute+ stub = SimpleNamespace()++ # When the gated session would be installed+ with pytest.raises(ImportError, match="rate-limit gate"):+ arxiv_api_module._install_gated_session(stub)++ def test_raises_import_error_for_non_requests_session(self) -> None:+ # Given a client whose _session is not a requests.Session+ stub = SimpleNamespace(_session=object())++ # When the gated session would be installed+ with pytest.raises(ImportError, match="requests.Session at _session"):+ arxiv_api_module._install_gated_session(stub)++ def test_non_session_attribute_is_not_closed(self) -> None:+ # Given an unusable _session that records close calls+ not_a_session = MagicMock(name="not_a_session")+ stub = SimpleNamespace(_session=not_a_session)++ # When installation is refused+ with pytest.raises(ImportError):+ arxiv_api_module._install_gated_session(stub)++ # Then the rejected value was never closed+ not_a_session.close.assert_not_called()+++_ATOM_FEED = b"""<?xml version="1.0" encoding="UTF-8"?>+<feed xmlns="http://www.w3.org/2005/Atom">+ <link href="http://arxiv.org/api/query?search_query%3Did_list:2101.12345" rel="self" type="application/atom+xml"/>+ <title type="html">ArXiv Query: search_query=id_list:2101.12345</title>+ <id>http://arxiv.org/api/query</id>+ <updated>2021-01-01T00:00:00-00:00</updated>+ <opensearch:totalResults xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/">1</opensearch:totalResults>+ <opensearch:startIndex xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/">0</opensearch:startIndex>+ <opensearch:itemsPerPage xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/">1</opensearch:itemsPerPage>+ <entry>+ <id>http://arxiv.org/abs/2101.12345v1</id>+ <updated>2021-01-02T00:00:00-00:00</updated>+ <published>2021-01-01T00:00:00-00:00</published>+ <title>Paper Title Here</title>+ <summary>The summary text.</summary>+ <author><name>A. Author</name></author>+ <link title="pdf" href="http://arxiv.org/pdf/2101.12345v1" rel="related" type="application/pdf"/>+ <arxiv:primary_category xmlns:arxiv="http://arxiv.org/schemas/atom" term="cs.AI"/>+ <category term="cs.AI"/>+ </entry>+</feed>"""+++def _atom_response() -> requests.Response:+ """A 200 Atom-feed response the real arxiv client can parse."""+ response = requests.Response()+ response.status_code = 200+ response._content = _ATOM_FEED+ response.headers["content-type"] = "application/atom+xml; charset=utf-8"+ response.url = "https://export.arxiv.org/api/query"+ return response+++class TestRealClientGating:+ """A real ``arxiv.Client`` (no stubs) receives the gated session."""++ def test_gated_session_installed_on_real_client(self) -> None:+ with arxiv_api_module._policy_arxiv_client() as client:+ assert isinstance(+ client._session, arxiv_api_module._GatedArxivSession+ )+ assert isinstance(client._session, SafeSession)++ def test_real_client_wire_call_travels_gated_session(+ self, mocker: MockerFixture+ ) -> None:+ # Given the transport funnel mocked with a parseable Atom feed+ request = mocker.patch.object(+ SafeSession, "request", return_value=_atom_response()+ )++ # When a real (unstubbed) client fetches one paper by id+ papers = arxiv_api_module.fetch_arxiv_results(+ arxiv_api_module.ArxivIdRequest(arxiv_id="2101.12345")+ )++ # Then the wire call went through _GatedArxivSession.get's+ # policy funnel: forced timeout, disabled redirects, and the+ # export.arxiv.org query URL the client built+ assert len(papers) == 1+ assert papers[0].entry_id == "http://arxiv.org/abs/2101.12345v1"+ request.assert_called_once()+ call = request.call_args+ assert call is not None+ assert call.args[0] == "GET"+ assert "export.arxiv.org/api/query" in call.args[1]+ assert call.kwargs.get("timeout") == 10+ assert call.kwargs.get("allow_redirects") is Falsediff --git a/tests/utilities/test_citation_normalizer.py b/tests/utilities/test_citation_normalizer.pyindex 760d0b74e2..d0e8b6fef0 100644--- a/tests/utilities/test_citation_normalizer.py+++ b/tests/utilities/test_citation_normalizer.py@@ -1,5 +1,7 @@"""Tests for citation_normalizer — engine-specific dict → CSL-JSON metadata."""+import pytest+from local_deep_research.utilities.citation_normalizer import (detect_engine,normalize_citation,@@ -7,6 +9,7 @@ from local_deep_research.utilities.citation_normalizer import (_parse_authors_list,_parse_name,_extract_doi,+ _with_scheme_for_arxiv_host,_extract_arxiv_id,)@@ -307,6 +310,120 @@ class TestExtractArxivId:# Then no arXiv ID is inferred from the untrusted path textassert result is None+ def test_schemeless_arxiv_url(self):+ assert (+ _extract_arxiv_id({"link": "arxiv.org/abs/2401.12345"})+ == "2401.12345"+ )++ def test_schemeless_ar5iv_url(self):+ assert (+ _extract_arxiv_id({"link": "ar5iv.org/2401.12345"}) == "2401.12345"+ )++ def test_mixed_case_schemeless_arxiv_url(self):+ assert (+ _extract_arxiv_id({"link": "ArXiV.OrG/abs/2401.12345"})+ == "2401.12345"+ )++ @pytest.mark.parametrize(+ "url",+ (+ "https://arxiv.org/abs/2401.12345",+ "http://arxiv.org/abs/2401.12345",+ ),+ )+ def test_fully_qualified_arxiv_url_regression(self, url):+ assert _extract_arxiv_id({"link": url}) == "2401.12345"++ @pytest.mark.parametrize(+ "url",+ (+ "example.com/abs/2401.12345",+ "arxiv.org.evil.com/abs/2401.12345",+ ),+ )+ def test_schemeless_non_arxiv_host_is_rejected(self, url):+ assert _extract_arxiv_id({"link": url}) is None++ @pytest.mark.parametrize(+ ("url", "expected"),+ (+ ("www.arxiv.org/abs/2401.12345", "2401.12345"),+ ("export.arxiv.org/abs/2401.12345", "2401.12345"),+ ("ar5iv.labs.arxiv.org/html/2401.12345", "2401.12345"),+ ("www.ar5iv.org/abs/2401.12345", "2401.12345"),+ ("arxiv.org./abs/2401.12345", "2401.12345"),+ ),+ )+ def test_schemeless_arxiv_subdomain_url(self, url, expected):+ assert _extract_arxiv_id({"link": url}) == expected+++class TestWithSchemeForArxivHost:+ """The helper itself: only arXiv-family hosts gain a scheme.++ The end-to-end rejection cases above hold even without the helper's+ host check, because the strict parser rejects the prefixed lookalike+ too; these cases pin the check directly.+ """++ @pytest.mark.parametrize(+ "url",+ (+ "arxiv.org/abs/2401.12345",+ "ArXiV.OrG/abs/2401.12345",+ "ar5iv.org/2401.12345",+ "www.arxiv.org/abs/2401.12345",+ "export.arxiv.org/abs/2401.12345",+ "www.ar5iv.org/abs/2401.12345",+ # A trailing-dot (fully qualified) host is the same host.+ "arxiv.org./abs/2401.12345",+ ),+ )+ def test_arxiv_family_host_gains_a_scheme(self, url):+ assert _with_scheme_for_arxiv_host(url) == f"https://{url}"++ @pytest.mark.parametrize(+ "url",+ (+ "example.com/abs/2401.12345",+ "arxiv.org.evil.com/abs/2401.12345",+ "evilarxiv.org/abs/2401.12345",+ "[email protected]/abs/2401.12345",+ "evil.com\\.arxiv.org/abs/2401.12345",+ "[email protected]/abs/2401.12345", # email-domains: allow+ "https://arxiv.org/abs/2401.12345",+ "/abs/2401.12345",+ # Empty and hyphen-edged labels are not plain DNS names.+ ".arxiv.org/abs/2401.12345",+ "a..arxiv.org/abs/2401.12345",+ "-.arxiv.org/abs/2401.12345",+ ),+ )+ def test_other_input_is_returned_unchanged(self, url):+ assert _with_scheme_for_arxiv_host(url) == url++ @pytest.mark.parametrize(+ "url",+ (+ # urlparse raises ValueError on each of these: an unbalanced+ # bracket in the netloc, and a netloc NFKC folds into "/".+ "//[arxiv.org/abs/2101.00001",+ "//arxiv.org]/abs/2101.00001",+ "//ar\uff0fxiv.org/abs/2101.00001",+ ),+ )+ def test_input_urlparse_rejects_is_returned_unchanged(self, url):+ assert _with_scheme_for_arxiv_host(url) == url+ assert _extract_arxiv_id({"link": url}) is None+ result = normalize_citation(+ {"title": "T", "link": url, "source": "arXiv"}+ )+ assert result is not None+ assert result.get("arxiv_id") is None+class TestNormalizeCitation:def test_arxiv_result(self):diff --git a/tests/web_search_engines/engines/test_arxiv_coverage.py b/tests/web_search_engines/engines/test_arxiv_coverage.pyindex 990ffbd015..327d9d18a5 100644--- a/tests/web_search_engines/engines/test_arxiv_coverage.py+++ b/tests/web_search_engines/engines/test_arxiv_coverage.py@@ -5,16 +5,18 @@ Targets uncovered paths in search_engine_arxiv.py including:- __init__ with/without journal filter- _get_search_results with various sort options- _get_previews success and error paths (rate limit patterns)-- _get_full_content: snippets-only mode, cache hit/miss, PDF download+extraction,- PDF limit reached, download failure, pypdf extraction, pdfplumber fallback,- both-fail path, empty PDF text+- _get_full_content: snippets-only mode, cache hit/miss, HTML-first+ full-text fetch, fetch failure, limit reached, empty-text fallback,+ _fetch_full_text downloader routing- run() cleanup of _papers-- get_paper_details: found/not-found, snippet-only mode, full mode, PDF download+- get_paper_details: found/not-found, snippet-only mode, full mode, full-text fetch- search_by_author / search_by_category with/without custom max_results"""from datetime import datetime-from unittest.mock import MagicMock, Mock, PropertyMock, patch, mock_open+from unittest.mock import Mock, PropertyMock, patch++import requestsimport pytest@@ -415,7 +417,7 @@ class TestGetFullContent:items = [{"id": paper.entry_id, "title": paper.title}]result = engine._get_full_content(items)assert result[0]["content"] == paper.summary- assert result[0]["pdf_url"] == paper.pdf_url+ assert result[0]["pdf_url"] == "https://arxiv.org/pdf/2101.00001"assert result[0]["categories"] == ["cs.AI"]assert result[0]["journal_ref"] == journal_ref_value@@ -428,172 +430,458 @@ class TestGetFullContent:assert result[0]["published"] is Noneassert result[0]["updated"] is None- def test_pdf_download_and_pypdf2_extraction(self, engine_with_pdf):- """PDF download + pypdf text extraction succeeds."""+ def test_full_text_via_downloader_succeeds(self, engine_with_pdf):+ """Full-text fetch through the HTML-first downloader populates content."""paper = _make_mock_paper()engine_with_pdf._papers = {paper.entry_id: paper}items = [{"id": paper.entry_id, "title": "T"}]- mock_page = Mock()- mock_page.extract_text.return_value = "Extracted text"- mock_reader = Mock()- mock_reader.pages = [mock_page]+ with patch.object(+ engine_with_pdf,+ "_fetch_full_text",+ return_value="Full text from downloader",+ ) as mock_fetch:+ result = engine_with_pdf._get_full_content(items)- with (- patch("builtins.open", mock_open()),- patch.dict("sys.modules", {"pypdf": MagicMock()}),- patch.object(- engine_with_pdf,- "_download_pdf_safely",- return_value="/tmp/paper.pdf",- ),- ):- # We need to mock pypdf inside the method- import sys+ mock_fetch.assert_called_once_with(paper)+ assert result[0]["content"] == "Full text from downloader"+ assert result[0]["full_content"] == "Full text from downloader"+ assert "pdf_path" not in result[0]+ paper.download_pdf.assert_not_called()- mock_pypdf2 = MagicMock()- mock_pypdf2.PdfReader.return_value = mock_reader- sys.modules["pypdf"] = mock_pypdf2+ def test_full_text_none_falls_back_to_summary(self, engine_with_pdf):+ """Downloader yielding no text leaves the summary as content."""+ paper = _make_mock_paper()+ engine_with_pdf._papers = {paper.entry_id: paper}+ items = [{"id": paper.entry_id, "title": "T"}]- try:- result = engine_with_pdf._get_full_content(items)- assert result[0]["pdf_path"] == "/tmp/paper.pdf"- assert result[0]["content"] == "Extracted text\n\n"- finally:- del sys.modules["pypdf"]+ with patch.object(+ engine_with_pdf, "_fetch_full_text", return_value=None+ ):+ result = engine_with_pdf._get_full_content(items)- def test_pdf_download_pypdf2_empty_falls_back_to_summary(- self, engine_with_pdf- ):- """pypdf extracts empty text -> content stays as summary."""+ assert result[0]["content"] == paper.summary+ assert result[0]["full_content"] == paper.summary+ assert "pdf_path" not in result[0]++ def test_full_text_whitespace_falls_back_to_summary(self, engine_with_pdf):+ """Whitespace-only downloader text is treated as no text."""paper = _make_mock_paper()engine_with_pdf._papers = {paper.entry_id: paper}items = [{"id": paper.entry_id, "title": "T"}]- mock_page = Mock()- mock_page.extract_text.return_value = ""- mock_reader = Mock()- mock_reader.pages = [mock_page]-- with (- patch("builtins.open", mock_open()),- patch.object(- engine_with_pdf,- "_download_pdf_safely",- return_value="/tmp/paper.pdf",- ),+ with patch.object(+ engine_with_pdf, "_fetch_full_text", return_value=" \n "):- import sys+ result = engine_with_pdf._get_full_content(items)++ assert result[0]["content"] == paper.summary- mock_pypdf2 = MagicMock()- mock_pypdf2.PdfReader.return_value = mock_reader- sys.modules["pypdf"] = mock_pypdf2+ def test_fetch_full_text_uses_downloader_with_canonical_url(+ self, engine_with_pdf+ ):+ """_fetch_full_text routes through ArxivDownloader.download_full_text.- try:- result = engine_with_pdf._get_full_content(items)- # Content should be the summary since extracted text is empty- assert result[0]["content"] == paper.summary- finally:- del sys.modules["pypdf"]+ The downloader is built for export.arxiv.org, the host arXiv sets+ aside for programmatic access.+ """+ from local_deep_research.research_library.downloaders.arxiv import (+ ArxivFullTextOutcome,+ ArxivFullTextStatus,+ ArxivTextResult,+ ArxivTextSource,+ )- def test_pypdf2_fails_pdfplumber_succeeds(self, engine_with_pdf):- """pypdf import fails, pdfplumber works."""paper = _make_mock_paper()- engine_with_pdf._papers = {paper.entry_id: paper}- items = [{"id": paper.entry_id, "title": "T"}]+ text_result = ArxivTextResult(+ "equation-preserving text", ArxivTextSource.ARXIV_HTML+ )+ with patch(+ "local_deep_research.research_library.downloaders.arxiv."+ "ArxivDownloader"+ ) as downloader_cls:+ instance = downloader_cls.return_value+ instance.download_full_text.return_value = ArxivFullTextOutcome(+ ArxivFullTextStatus.TEXT, text_result+ )- mock_pdf_page = Mock()- mock_pdf_page.extract_text.return_value = "Plumber text"- mock_pdf = Mock()- mock_pdf.pages = [mock_pdf_page]- mock_pdf.__enter__ = Mock(return_value=mock_pdf)- mock_pdf.__exit__ = Mock(return_value=False)+ text = engine_with_pdf._fetch_full_text(paper)- with (- patch("builtins.open", mock_open()),- patch.object(- engine_with_pdf,- "_download_pdf_safely",- return_value="/tmp/paper.pdf",+ downloader_cls.assert_called_once_with(+ fetch_host="export.arxiv.org"+ )+ instance.download_full_text.assert_called_once_with(+ "https://arxiv.org/abs/2101.00001"+ )+ assert text == "equation-preserving text"+ # Downloader is cached on the engine for reuse across papers+ assert engine_with_pdf._arxiv_text_downloader is instance++ def test_fetch_full_text_invalid_id_raises(self, engine_with_pdf):+ """A paper whose entry_id yields no valid arXiv id raises."""+ paper = _make_mock_paper(entry_id="https://example.org/not-arxiv")++ with pytest.raises(ValueError):+ engine_with_pdf._fetch_full_text(paper)++ def test_paper_without_full_text_does_not_consume_budget(+ self, engine_with_pdf+ ):+ """A paper arXiv answered has no full text refunds the budget.++ Drives the real ``_fetch_full_text`` -> ``ArxivDownloader`` chain+ and fakes only the downloader's HTTP session. Both of the first+ paper's requests are answered 404 (no rendition, no PDF), which the+ downloader turns into ``None`` rather than an exception, so the+ refund must come from the "no full text" outcome and not from an+ ``except`` clause. With ``max_full_text=1``, a fetch that kept the+ budget would leave the second paper on its summary without ever+ requesting it.+ """+ from local_deep_research.research_library.downloaders.arxiv import (+ ArxivDownloader,+ )++ engine_with_pdf.max_full_text = 1+ engine_with_pdf.rate_tracker = Mock()+ paper1 = _make_mock_paper(entry_id="http://arxiv.org/abs/2101.00001")+ paper2 = _make_mock_paper(entry_id="http://arxiv.org/abs/2101.00002")+ engine_with_pdf._papers = {+ paper1.entry_id: paper1,+ paper2.entry_id: paper2,+ }+ items = [+ {"id": paper1.entry_id, "title": "P1"},+ {"id": paper2.entry_id, "title": "P2"},+ ]++ prose = " ".join(+ ["The second paper has a readable official HTML rendition."] * 8+ )+ rendition = (+ "<html><head><title>Paper two</title></head><body><article>"+ "<h1>Paper two</h1>"+ + "".join(f"<p>{prose} Paragraph {k}.</p>" for k in range(6))+ + "</article></body></html>"+ )+ html_url = "https://arxiv.org/html/2101.00002"++ def html_response():+ response = requests.Response()+ response.status_code = 200+ response.headers["Content-Type"] = "text/html; charset=utf-8"+ response.encoding = "utf-8"+ response._content = rendition.encode()+ response.url = html_url+ return response++ requested = []++ def fake_get(url, **kwargs):+ requested.append(url)+ if url == html_url:+ return html_response()+ return Mock(status_code=404, headers={})++ downloader = ArxivDownloader()+ downloader.rate_tracker = Mock()+ engine_with_pdf._arxiv_text_downloader = downloader+ with patch.object(downloader.session, "get", side_effect=fake_get):+ result = engine_with_pdf._get_full_content(items)++ # Both of the first paper's requests were answered 404; it kept+ # its summary+ assert [url for url in requested if "2101.00001" in url] == [+ "https://arxiv.org/html/2101.00001",+ "https://arxiv.org/pdf/2101.00001.pdf",+ ]+ assert result[0]["content"] == paper1.summary+ # The second paper still got its full-text attempt, and its text+ assert html_url in requested+ assert result[1]["content"] != paper2.summary+ assert "Paper two" in result[1]["content"]+ # The API leg would only return the abstract, so it is never asked+ assert not any("api/query" in url for url in requested)++ @pytest.mark.parametrize(+ "failure",+ [+ pytest.param(requests.exceptions.Timeout("hung"), id="timeout"),+ pytest.param(+ requests.exceptions.ConnectionError("down"), id="connection"),- ):- import sys-- # pypdf fails with ImportError- mock_pypdf2 = MagicMock()- mock_pypdf2.PdfReader.side_effect = ImportError("no pypdf")- sys.modules["pypdf"] = mock_pypdf2-- mock_pdfplumber = MagicMock()- mock_pdfplumber.open.return_value = mock_pdf- sys.modules["pdfplumber"] = mock_pdfplumber-- try:- result = engine_with_pdf._get_full_content(items)- assert result[0]["content"] == "Plumber text\n\n"- finally:- del sys.modules["pypdf"]- del sys.modules["pdfplumber"]-- def test_both_pdf_extractors_fail(self, engine_with_pdf):- """Both pypdf and pdfplumber fail -> summary used."""- paper = _make_mock_paper()- engine_with_pdf._papers = {paper.entry_id: paper}- items = [{"id": paper.entry_id, "title": "T"}]+ pytest.param(500, id="http_500"),+ pytest.param(502, id="http_502"),+ pytest.param(504, id="http_504"),+ # SafeSession raises ValueError when validate_url refuses the+ # URL, which is also how a failed DNS lookup (offline machine)+ # surfaces; it lands in _download_pdf's catch-all branch.+ pytest.param(+ ValueError(+ "URL failed security validation (possible SSRF): "+ "https://arxiv.org/pdf/2101.00001.pdf"+ ),+ id="dns_failure_validator_refusal",+ ),+ pytest.param(RuntimeError("boom"), id="unexpected_error"),+ ],+ )+ def test_failing_host_stops_further_fetches(+ self, engine_with_pdf, failure, loguru_caplog+ ):+ """A hung or failing arXiv costs one paper's requests, not one per paper.++ Drives the real ``_fetch_full_text`` -> ``ArxivDownloader`` chain+ with every request failing (a timeout, a connection error, or a+ 5xx). The first paper costs one HTML and one unretried PDF request;+ the remaining papers are not requested at all, keep their+ summaries, and nothing is logged at ERROR (it would reach the+ user's browser). Red under refunding a failed request: every paper+ is then requested (six requests here, ~25 HTML+PDF pairs with 30 s+ timeouts for a real search).+ """+ from local_deep_research.research_library.downloaders.arxiv import (+ ArxivDownloader,+ )++ engine_with_pdf.max_full_text = 3+ engine_with_pdf.rate_tracker = Mock()+ papers = [+ _make_mock_paper(entry_id=f"http://arxiv.org/abs/2101.0000{n}")+ for n in (1, 2, 3)+ ]+ engine_with_pdf._papers = {p.entry_id: p for p in papers}+ items = [{"id": p.entry_id, "title": "P"} for p in papers]++ requested = []+ def fake_get(url, **kwargs):+ requested.append(url)+ if isinstance(failure, Exception):+ raise failure+ return Mock(status_code=failure, headers={})++ downloader = ArxivDownloader()+ downloader.rate_tracker = Mock()+ downloader.rate_tracker.apply_rate_limit.return_value = 0+ engine_with_pdf._arxiv_text_downloader = downloaderwith (- patch("builtins.open", mock_open()),- patch.object(- engine_with_pdf,- "_download_pdf_safely",- return_value="/tmp/paper.pdf",- ),+ loguru_caplog.at_level("DEBUG"),+ patch.object(downloader.session, "get", side_effect=fake_get),):- import sys-- mock_pypdf2 = MagicMock()- mock_pypdf2.PdfReader.side_effect = Exception("pypdf broken")- sys.modules["pypdf"] = mock_pypdf2-- mock_pdfplumber = MagicMock()- mock_pdfplumber.open.side_effect = Exception("pdfplumber broken")- sys.modules["pdfplumber"] = mock_pdfplumber-- try:- result = engine_with_pdf._get_full_content(items)- # Falls back to summary- assert result[0]["content"] == paper.summary- finally:- del sys.modules["pypdf"]- del sys.modules["pdfplumber"]-- def test_pdf_download_fails(self, engine_with_pdf):- """Download failure sets pdf_path to None and decrements counter."""- paper = _make_mock_paper()- engine_with_pdf._papers = {paper.entry_id: paper}- items = [{"id": paper.entry_id, "title": "T"}]+ result = engine_with_pdf._get_full_content(items)- with patch.object(- engine_with_pdf,- "_download_pdf_safely",- side_effect=Exception("Network error"),+ assert requested == [+ "https://arxiv.org/html/2101.00001",+ "https://arxiv.org/pdf/2101.00001.pdf",+ ]+ assert [r["content"] for r in result] == [p.summary for p in papers]+ assert "arXiv full-text fetch failed" in loguru_caplog.text+ assert not [r for r in loguru_caplog.records if r.levelno >= 40]++ def test_rate_limited_full_text_stops_further_fetches(+ self, engine_with_pdf+ ):+ """Under persistent 429 the engine stops after the first paper.++ Drives the real ``_fetch_full_text`` -> ``ArxivDownloader`` chain+ with every request answered 429. The first paper costs one HTML+ and one PDF request (the PDF is not retried into the rate limit);+ the remaining papers are not requested at all and keep their+ summaries.+ """+ from local_deep_research.research_library.downloaders.arxiv import (+ ArxivDownloader,+ )++ engine_with_pdf.max_full_text = 3+ engine_with_pdf.rate_tracker = Mock()+ papers = [+ _make_mock_paper(entry_id=f"http://arxiv.org/abs/2101.0000{n}")+ for n in (1, 2, 3)+ ]+ engine_with_pdf._papers = {p.entry_id: p for p in papers}+ items = [{"id": p.entry_id, "title": "P"} for p in papers]++ requested = []++ def fake_get(url, **kwargs):+ requested.append(url)+ return Mock(status_code=429, headers={})++ downloader = ArxivDownloader()+ downloader.rate_tracker = Mock()+ downloader.rate_tracker.apply_rate_limit.return_value = 0+ engine_with_pdf._arxiv_text_downloader = downloader+ with patch.object(downloader.session, "get", side_effect=fake_get):+ result = engine_with_pdf._get_full_content(items)++ assert len(requested) == 2+ assert all("2101.00001" in url for url in requested)+ assert [r["content"] for r in result] == [p.summary for p in papers]++ def test_fetch_full_text_raises_when_a_request_failed(+ self, engine_with_pdf+ ):+ """A FETCH_FAILED outcome raises FullTextFetchFailedError."""+ from local_deep_research.research_library.downloaders.arxiv import (+ ArxivFullTextOutcome,+ ArxivFullTextStatus,+ )+ from local_deep_research.web_search_engines.engines.search_engine_arxiv import (+ FullTextFetchFailedError,+ FullTextRateLimitedError,+ )++ downloader = Mock()+ downloader.download_full_text.return_value = ArxivFullTextOutcome(+ ArxivFullTextStatus.FETCH_FAILED+ )+ engine_with_pdf._arxiv_text_downloader = downloader++ with pytest.raises(FullTextFetchFailedError) as raised:+ engine_with_pdf._fetch_full_text(_make_mock_paper())+ assert not isinstance(raised.value, FullTextRateLimitedError)++ def test_fetch_full_text_raises_when_rate_limited(self, engine_with_pdf):+ """A RATE_LIMITED outcome raises FullTextRateLimitedError."""+ from local_deep_research.research_library.downloaders.arxiv import (+ ArxivFullTextOutcome,+ ArxivFullTextStatus,+ )+ from local_deep_research.web_search_engines.engines.search_engine_arxiv import (+ FullTextRateLimitedError,+ )++ downloader = Mock()+ downloader.download_full_text.return_value = ArxivFullTextOutcome(+ ArxivFullTextStatus.RATE_LIMITED+ )+ engine_with_pdf._arxiv_text_downloader = downloader++ with pytest.raises(FullTextRateLimitedError):+ engine_with_pdf._fetch_full_text(_make_mock_paper())++ def test_pdf_that_yields_no_text_consumes_the_budget(self, engine_with_pdf):+ """A PDF that downloaded but produced no text is not refunded.++ Only a transport failure is refunded. Here the first paper's PDF+ arrives (an image-only scan, say) and extraction yields nothing:+ the download and the extraction were paid for, so with+ ``max_full_text=1`` the second paper must keep its summary without+ a single request. Red under refunding every no-text result: the+ second paper's HTML and PDF are then requested too.+ """+ from local_deep_research.research_library.downloaders.arxiv import (+ ArxivDownloader,+ )++ engine_with_pdf.max_full_text = 1+ engine_with_pdf.rate_tracker = Mock()+ paper1 = _make_mock_paper(entry_id="http://arxiv.org/abs/2101.00001")+ paper2 = _make_mock_paper(entry_id="http://arxiv.org/abs/2101.00002")+ engine_with_pdf._papers = {+ paper1.entry_id: paper1,+ paper2.entry_id: paper2,+ }+ items = [+ {"id": paper1.entry_id, "title": "P1"},+ {"id": paper2.entry_id, "title": "P2"},+ ]++ requested = []++ def fake_get(url, **kwargs):+ requested.append(url)+ return Mock(status_code=404, headers={})++ downloader = ArxivDownloader()+ downloader.rate_tracker = Mock()+ engine_with_pdf._arxiv_text_downloader = downloader+ with (+ patch.object(downloader.session, "get", side_effect=fake_get),+ patch.object(+ downloader, "_download_pdf", return_value=b"%PDF-scan"+ ) as download_pdf,+ patch.object(+ downloader, "extract_text_from_pdf", return_value=None+ ) as extract,):result = engine_with_pdf._get_full_content(items)- assert result[0]["pdf_path"] is None- def test_pdf_limit_reached(self, engine_with_pdf):- """Once max_full_text PDFs processed, remaining use summary.+ # The first paper's PDF arrived and was extracted, to no text+ download_pdf.assert_called_once()+ extract.assert_called_once_with(b"%PDF-scan")+ assert result[0]["content"] == paper1.summary+ # The budget stayed spent: nothing was requested for the second+ assert not any("2101.00002" in url for url in requested)+ assert result[1]["content"] == paper2.summary++ def test_fetch_full_text_raises_when_the_pdf_yields_no_text(+ self, engine_with_pdf+ ):+ """PDF_WITHOUT_TEXT raises; NOT_FETCHED reads as None (refundable)."""+ from local_deep_research.research_library.downloaders.arxiv import (+ ArxivFullTextOutcome,+ ArxivFullTextStatus,+ )+ from local_deep_research.web_search_engines.engines.search_engine_arxiv import (+ FullTextNotExtractedError,+ )++ downloader = Mock()+ engine_with_pdf._arxiv_text_downloader = downloader++ downloader.download_full_text.return_value = ArxivFullTextOutcome(+ ArxivFullTextStatus.PDF_WITHOUT_TEXT+ )+ with pytest.raises(FullTextNotExtractedError):+ engine_with_pdf._fetch_full_text(_make_mock_paper())++ downloader.download_full_text.return_value = ArxivFullTextOutcome(+ ArxivFullTextStatus.NOT_FETCHED+ )+ assert engine_with_pdf._fetch_full_text(_make_mock_paper()) is None++ @pytest.mark.parametrize(+ ("source_name", "expected"),+ [+ ("ARXIV_HTML", "downloader text"),+ ("LOCAL_PDF", "downloader text"),+ ("ARXIV_API", None),+ ],+ )+ def test_fetch_full_text_returns_only_full_text_sources(+ self, engine_with_pdf, source_name, expected+ ):+ """API metadata is the abstract, not full text, so it reads as None.- Uses valid arXiv ids (unlike the ``abs/1``/``abs/2`` ids this test- used to use) so the first download actually succeeds and+ The engine already holds the abstract as the paper summary; counting+ it as full text would spend the budget on no new text.+ """+ from local_deep_research.research_library.downloaders.arxiv import (+ ArxivFullTextOutcome,+ ArxivFullTextStatus,+ ArxivTextResult,+ ArxivTextSource,+ )++ downloader = Mock()+ downloader.download_full_text.return_value = ArxivFullTextOutcome(+ ArxivFullTextStatus.TEXT,+ ArxivTextResult("downloader text", ArxivTextSource[source_name]),+ )+ engine_with_pdf._arxiv_text_downloader = downloader++ assert engine_with_pdf._fetch_full_text(_make_mock_paper()) == expected++ def test_full_text_limit_reached(self, engine_with_pdf):+ """Once max_full_text fetches succeed, remaining papers use the summary.++ Uses valid arXiv ids so the first fetch actually succeeds and``pdf_count`` reaches ``max_full_text`` for real, exercising the- "Reached PDF limit" ``elif`` branch in- ``_get_full_content``. With invalid ids ``_download_pdf_safely``- raised before that branch could ever be reached: the except-path- decrements ``pdf_count`` right back down, so the second paper- re-entered the *download* branch instead of the limit branch, and- the branch this test names went uncovered while the test stayed- green.+ "Reached full-text fetch limit" ``elif`` branch in+ ``_get_full_content``.The elif's own body (``result["content"] = paper.summary`` /``result["full_content"] = paper.summary``) re-assigns the exact@@ -617,12 +905,7 @@ class TestGetFullContent:share a class: ``NonCallableMock.__new__`` gives every ``Mock()``instance its own freshly-created subclass, so ``type(paper1) istype(paper2)`` is ``False`` and this patch cannot bleed onto- ``paper1.summary`` reads. (An earlier version of this docstring- claimed the opposite -- that ``paper1``/``paper2`` "share the- same ``Mock`` class" and a ``type(paper2)`` patch would therefore- leak onto ``paper1`` -- which is false; verified directly by- patching ``type(paper2).summary`` via ``PropertyMock`` and- observing ``paper1.summary`` unaffected.)+ ``paper1.summary`` reads."""engine_with_pdf.max_full_text = 1paper1 = _make_mock_paper(entry_id="http://arxiv.org/abs/2101.00001")@@ -636,11 +919,6 @@ class TestGetFullContent:{"id": paper2.entry_id, "title": "P2"},]- mock_page = Mock()- mock_page.extract_text.return_value = "text"- mock_reader = Mock()- mock_reader.pages = [mock_page]-summary_reads = ["summary-read-1-field","summary-read-2-default-content",@@ -650,12 +928,11 @@ class TestGetFullContent:]with (- patch("builtins.open", mock_open()),patch.object(engine_with_pdf,- "_download_pdf_safely",- return_value="/tmp/paper1.pdf",- ) as mock_download,+ "_fetch_full_text",+ return_value="paper1 full text",+ ) as mock_fetch,patch.object(type(paper2),"summary",@@ -664,33 +941,25 @@ class TestGetFullContent:) as paper2_summary,):paper2_summary.side_effect = summary_reads- import sys-- mock_pypdf2 = MagicMock()- mock_pypdf2.PdfReader.return_value = mock_reader- sys.modules["pypdf"] = mock_pypdf2-- try:- result = engine_with_pdf._get_full_content(items)- # Only the first paper triggers a download; the second- # must hit the "limit reached" branch and fall back to- # the summary without calling the download helper again- # (and therefore without ever touching the network).- mock_download.assert_called_once()- assert result[0]["pdf_path"] == "/tmp/paper1.pdf"- assert "pdf_path" not in result[1]- # These can only hold if the elif body's own reassignment- # ran: deleting those two lines would leave- # result[1]["content"]/["full_content"] at the 2nd/3rd- # (default-assignment) read instead of the 4th/5th.- assert result[1]["content"] == "summary-read-4-elif-content"- assert (- result[1]["full_content"]- == "summary-read-5-elif-full-content"- )- assert paper2_summary.call_count == 5- finally:- del sys.modules["pypdf"]+ result = engine_with_pdf._get_full_content(items)+ # Only the first paper triggers a fetch; the second+ # must hit the "limit reached" branch and fall back to+ # the summary without calling the fetch helper again+ # (and therefore without ever touching the network).+ mock_fetch.assert_called_once()+ assert result[0]["content"] == "paper1 full text"+ assert result[0]["full_content"] == "paper1 full text"+ assert "pdf_path" not in result[0]+ assert "pdf_path" not in result[1]+ # These can only hold if the elif body's own reassignment+ # ran: deleting those two lines would leave+ # result[1]["content"]/["full_content"] at the 2nd/3rd+ # (default-assignment) read instead of the 4th/5th.+ assert result[1]["content"] == "summary-read-4-elif-content"+ assert (+ result[1]["full_content"] == "summary-read-5-elif-full-content"+ )+ assert paper2_summary.call_count == 5# ===========================================================================@@ -753,42 +1022,127 @@ class TestGetPaperDetails:assert result["title"] == "Test Paper"assert result["snippet"].endswith("...")- def test_paper_details_with_pdf_download(self, engine_with_pdf):- """PDF download happens in get_paper_details when configured."""+ def test_paper_details_full_text_fetch(self, engine_with_pdf):+ """Full text is fetched in get_paper_details when configured."""paper = _make_mock_paper()with (patch(FETCH_SEAM, return_value=[paper]),patch.object(engine_with_pdf,- "_download_pdf_safely",- return_value="/tmp/paper.pdf",- ) as mock_download,+ "_fetch_full_text",+ return_value="Full text body",+ ) as mock_fetch,):result = engine_with_pdf.get_paper_details("2101.00001")- assert result["pdf_path"] == "/tmp/paper.pdf"- mock_download.assert_called_once_with(- paper, engine_with_pdf.download_dir- )+ assert result["content"] == "Full text body"+ assert result["full_content"] == "Full text body"+ mock_fetch.assert_called_once_with(paper)paper.download_pdf.assert_not_called()+ assert "pdf_path" not in result++ def test_paper_details_pdf_without_text_keeps_summary(+ self, engine_with_pdf, log_sink+ ):+ """A PDF that yielded no text leaves the summary, logged as info."""+ from local_deep_research.web_search_engines.engines.search_engine_arxiv import (+ FullTextNotExtractedError,+ )++ paper = _make_mock_paper()+ with (+ patch(FETCH_SEAM, return_value=[paper]),+ patch.object(+ engine_with_pdf,+ "_fetch_full_text",+ side_effect=FullTextNotExtractedError("no text"),+ ),+ ):+ result = engine_with_pdf.get_paper_details("2101.00001")++ assert result["title"] == "Test Paper"+ assert result["content"] == paper.summary+ rendered = "\n".join(str(m) for m in log_sink)+ assert "yielded no text" in rendered+ assert "Error downloading" not in rendered++ @pytest.mark.parametrize(+ ("failure", "expected_log"),+ [+ pytest.param(429, "rate limited the full-text fetch", id="429"),+ pytest.param(503, "rate limited the full-text fetch", id="503"),+ pytest.param(+ requests.exceptions.Timeout("hung"),+ "full-text fetch failed",+ id="timeout",+ ),+ pytest.param(500, "full-text fetch failed", id="500"),+ ],+ )+ def test_paper_details_failed_fetch_keeps_summary_without_error(+ self, engine_with_pdf, log_sink, failure, expected_log+ ):+ """A 429/503, timeout or 5xx keeps the summary and logs no error.++ Drives the real ``_fetch_full_text`` -> ``ArxivDownloader`` ->+ ``BaseDownloader._download_pdf`` / ``_fetch_html_with_final_url``+ chain with only the HTTP session stubbed (no network), so the+ downloader's own give-up logging is part of what is checked. Red+ when any of it logs at ERROR -- the PDF leg's "HTTP 429 after 1+ attempts" give-up, the HTML leg's fetch error, or+ ``get_paper_details`` letting the exception fall into+ ``_log_full_text_error`` -- since ERROR records reach the user's+ browser through ``frontend_progress_sink``.+ """+ from local_deep_research.research_library.downloaders.arxiv import (+ ArxivDownloader,+ )++ def fake_get(url, **kwargs):+ if isinstance(failure, Exception):+ raise failure+ return Mock(status_code=failure, headers={})++ paper = _make_mock_paper()+ downloader = ArxivDownloader()+ downloader.rate_tracker = Mock()+ downloader.rate_tracker.apply_rate_limit.return_value = 0+ engine_with_pdf._arxiv_text_downloader = downloader+ engine_with_pdf.rate_tracker = Mock()+ with (+ patch(FETCH_SEAM, return_value=[paper]),+ patch.object(+ downloader.session, "get", side_effect=fake_get+ ) as get,+ ):+ result = engine_with_pdf.get_paper_details("2101.00001")- def test_paper_details_pdf_download_fails(self, engine_with_pdf):- """PDF download failure in get_paper_details is handled gracefully."""+ # One HTML and one unretried PDF request+ assert get.call_count == 2+ assert result["title"] == "Test Paper"+ assert result["content"] == paper.summary+ assert result["full_content"] == paper.summary+ rendered = "\n".join(str(m) for m in log_sink)+ assert expected_log in rendered+ assert "Error downloading" not in rendered+ assert not any(m.startswith("ERROR") for m in log_sink)++ def test_paper_details_full_text_fetch_fails(self, engine_with_pdf):+ """Full-text fetch failure in get_paper_details is handled gracefully."""paper = _make_mock_paper()with (patch(FETCH_SEAM, return_value=[paper]),patch.object(engine_with_pdf,- "_download_pdf_safely",+ "_fetch_full_text",side_effect=Exception("download error"),- ) as mock_download,+ ) as mock_fetch,):result = engine_with_pdf.get_paper_details("2101.00001")assert result["title"] == "Test Paper"- assert "pdf_path" not in result- mock_download.assert_called_once_with(- paper, engine_with_pdf.download_dir- )+ assert result["content"] == paper.summary+ mock_fetch.assert_called_once_with(paper)paper.download_pdf.assert_not_called()+ assert "pdf_path" not in result# ===========================================================================@@ -797,73 +1151,26 @@ class TestGetPaperDetails:class TestDownloadErrorLoggingOmitsPaths:- """The path-free logging invariant for the two containment/OSError- handlers -- ``except (DirectoryCreationSecurityError, OSError)`` in- both ``_get_full_content``'s download branch and- ``get_paper_details``.-- Both handlers catch that pair and log a static, path-free message- instead of interpolating the exception, because either exception- type can carry the resolved, absolute download path in its own- ``str()``: ``DirectoryCreationSecurityError`` embeds it directly,- and an ``OSError`` such as ``FileExistsError`` (what- ``create_directory``'s own ``p.mkdir()`` raises uncaught on a- collision) embeds it via ``strerror``/``filename`` too. The message- does interpolate ``type(e).__name__`` -- that alone is path-free, and- lets an operator tell a containment rejection apart from e.g. a- disk-full ``OSError``. Deleting either handler (letting the generic- ``except Exception`` below it catch instead, which interpolates- ``str(e)`` in full) produces the exact same ``pdf_path``/``pdf_count``- end state -- nothing but the rendered log text itself tells the two- apart, so that's what these tests inspect: each asserts both that the- static "filesystem or directory-containment error" text (plus the- type name) is present, and that the path is absent -- a sink that- silently swallowed the record would fail the first assertion instead- of passing vacuously.+ """The path-free logging invariant for errors raised by the full-text+ step, in both ``_get_full_content`` and ``get_paper_details``.++ ``_log_full_text_error`` logs an ``OSError`` by its type name only,+ because an ``OSError`` can carry a local filesystem path in its own+ ``str()`` (``strerror``/``filename``) and ``_scrub_error`` does not+ remove paths. Letting it fall through to the scrubbed-message branch+ produces the same result dicts; only the rendered log text tells the+ two apart, so that's what these tests inspect: each asserts both that+ the static "a filesystem error occurred" text (plus the type name) is+ present, and that the path is absent -- a sink that silently+ swallowed the record would fail the first assertion instead of+ passing vacuously."""- def test_get_full_content_containment_error_log_omits_path(- self, engine_with_pdf, log_sink- ):- """Catches deleting the ``(DirectoryCreationSecurityError,- OSError)`` handler in ``_get_full_content``'s download branch: with- only the generic ``except Exception`` left, the log line would- interpolate ``str(e)``, which for ``DirectoryCreationSecurityError``- embeds the resolved path."""- from local_deep_research.security.directory_creation import (- DirectoryCreationSecurityError,- )-- paper = _make_mock_paper()- engine_with_pdf._papers = {paper.entry_id: paper}- items = [{"id": paper.entry_id, "title": "T"}]-- secret_path = "/home/researcher/.secret_key_dir/zzqleak4711"- with patch.object(- engine_with_pdf,- "_download_pdf_safely",- side_effect=DirectoryCreationSecurityError(- f"Path {secret_path} escapes the containment root"- ),- ):- result = engine_with_pdf._get_full_content(items)-- assert result[0]["pdf_path"] is None- rendered = "\n".join(str(m) for m in log_sink)- # Positive: the static log line was actually emitted (a sink that- # captured nothing would fail here instead of passing vacuously),- # and it names the exception type.- assert "a filesystem or directory-containment error" in rendered- assert "DirectoryCreationSecurityError" in rendered- # Negative: but never the path it carries.- assert secret_path not in rendered-def test_get_full_content_oserror_log_omits_path(self, engine_with_pdf, log_sink):- """Same property, ``OSError`` branch -- e.g. ``create_directory``'s- own ``p.mkdir()`` raising ``FileExistsError`` uncaught, whose- message also embeds the same resolved path."""+ """Catches dropping the ``OSError`` branch of+ ``_log_full_text_error`` for ``_get_full_content``."""paper = _make_mock_paper()engine_with_pdf._papers = {paper.entry_id: paper}items = [{"id": paper.entry_id, "title": "T"}]@@ -871,31 +1178,26 @@ class TestDownloadErrorLoggingOmitsPaths:secret_path = "/home/researcher/.secret_key_dir/zzqleak8822"with patch.object(engine_with_pdf,- "_download_pdf_safely",+ "_fetch_full_text",side_effect=FileExistsError(17, f"File exists: '{secret_path}'"),):result = engine_with_pdf._get_full_content(items)- assert result[0]["pdf_path"] is None+ assert "pdf_path" not in result[0]rendered = "\n".join(str(m) for m in log_sink)# Positive: the static log line was actually emitted, and it# names the exception type.- assert "a filesystem or directory-containment error" in rendered+ assert "a filesystem error occurred" in renderedassert "FileExistsError" in rendered# Negative: but never the path it carries.assert secret_path not in rendered- def test_get_paper_details_containment_error_log_omits_path(+ def test_get_paper_details_oserror_log_omits_path(self, engine_with_pdf, log_sink):- """Catches deleting the ``(DirectoryCreationSecurityError,- OSError)`` handler in ``get_paper_details``."""+ """Same property for ``get_paper_details``."""import arxiv- from local_deep_research.security.directory_creation import (- DirectoryCreationSecurityError,- )-paper = _make_mock_paper()secret_path = "/home/researcher/.secret_key_dir/zzqleak9933"with (@@ -903,13 +1205,16 @@ class TestDownloadErrorLoggingOmitsPaths:patch.object(arxiv, "Search"),patch.object(engine_with_pdf,- "_download_pdf_safely",- side_effect=DirectoryCreationSecurityError(- f"Path {secret_path} escapes the containment root"+ "_fetch_full_text",+ side_effect=FileExistsError(+ 17, f"File exists: '{secret_path}'"),),):+ # arxiv_api._install_gated_session requires a real+ # requests.Session at _session; the guard closes it.mock_client = Mock()+ mock_client._session = requests.Session()mock_client.results.return_value = [paper]mock_client_cls.return_value = mock_client@@ -919,22 +1224,20 @@ class TestDownloadErrorLoggingOmitsPaths:rendered = "\n".join(str(m) for m in log_sink)# Positive: the static log line was actually emitted, and it# names the exception type.- assert "a filesystem or directory-containment error" in rendered- assert "DirectoryCreationSecurityError" in rendered+ assert "a filesystem error occurred" in rendered+ assert "FileExistsError" in rendered# Negative: but never the path it carries.assert secret_path not in rendered-class TestRequestExceptionOrderingBeforeContainmentHandler:- """``RequestException`` must be caught -- and produce the scrubbed- diagnostic message -- before ``(DirectoryCreationSecurityError,- OSError)``. ``requests``' ``RequestException`` subclasses ``IOError``,- which *is* ``OSError``, so reordering the two ``except`` clauses (or- merging them) would silently swallow every- ``ConnectionError``/``Timeout``/``HTTPError`` under the static,- path-free containment message instead of the normal scrubbed network- diagnostic -- exactly the regression the ``# ORDER MATTERS`` comments- at both call sites warn about.+class TestRequestExceptionKeepsScrubbedMessage:+ """``RequestException`` must keep the scrubbed diagnostic message and+ not take ``_log_full_text_error``'s path-free ``OSError`` branch.+ ``requests``' ``RequestException`` subclasses ``IOError``, which *is*+ ``OSError``, so dropping the ``RequestException`` exclusion from that+ branch would log every ``ConnectionError``/``Timeout``/``HTTPError``+ under the static filesystem message instead of the scrubbed network+ diagnostic."""def test_connection_error_in_get_full_content_produces_scrubbed_message(@@ -950,15 +1253,15 @@ class TestRequestExceptionOrderingBeforeContainmentHandler:with patch.object(engine_with_pdf,- "_download_pdf_safely",+ "_fetch_full_text",side_effect=RequestsConnectionError("zzqnetfail1234"),):result = engine_with_pdf._get_full_content(items)- assert result[0]["pdf_path"] is None+ assert "pdf_path" not in result[0]rendered = "\n".join(str(m) for m in log_sink)assert "zzqnetfail1234" in rendered- assert "filesystem or directory-containment error" not in rendered+ assert "a filesystem error occurred" not in rendereddef test_connection_error_in_get_paper_details_produces_scrubbed_message(self, engine_with_pdf, log_sink@@ -974,11 +1277,12 @@ class TestRequestExceptionOrderingBeforeContainmentHandler:patch.object(arxiv, "Search"),patch.object(engine_with_pdf,- "_download_pdf_safely",+ "_fetch_full_text",side_effect=RequestsConnectionError("zzqnetfail5678"),),):mock_client = Mock()+ mock_client._session = requests.Session()mock_client.results.return_value = [paper]mock_client_cls.return_value = mock_client@@ -987,7 +1291,7 @@ class TestRequestExceptionOrderingBeforeContainmentHandler:assert "pdf_path" not in resultrendered = "\n".join(str(m) for m in log_sink)assert "zzqnetfail5678" in rendered- assert "filesystem or directory-containment error" not in rendered+ assert "a filesystem error occurred" not in rendered# ===========================================================================@@ -1056,6 +1360,96 @@ class TestSearchByCategory:# ===========================================================================+class TestClose:+ """close() releases the lazily cached full-text downloader."""++ def test_close_releases_cached_downloader_and_is_idempotent(self, engine):+ from local_deep_research.research_library.downloaders.arxiv import (+ ArxivDownloader,+ )+ from local_deep_research.web_search_engines.search_engine_base import (+ BaseSearchEngine,+ )++ # Given an engine holding the downloader _fetch_full_text caches+ downloader = ArxivDownloader()+ session = downloader.session+ engine._arxiv_text_downloader = downloader++ with (+ patch.object(+ session, "close", wraps=session.close+ ) as session_close,+ patch.object(+ BaseSearchEngine, "close", autospec=True+ ) as base_close,+ ):+ # When the engine is closed twice+ engine.close()+ engine.close()++ # Then the downloader's HTTP session was closed exactly once, the+ # engine dropped the closed downloader, the second close was a+ # no-op, and the base engine's close ran each time+ session_close.assert_called_once_with()+ assert downloader.session is None+ assert getattr(engine, "_arxiv_text_downloader", None) is None+ assert base_close.call_count == 2++ def test_full_text_after_close_builds_a_fresh_downloader(self, engine):+ from local_deep_research.research_library.downloaders.arxiv import (+ ArxivFullTextOutcome,+ ArxivFullTextStatus,+ ArxivTextResult,+ ArxivTextSource,+ )+ from local_deep_research.web_search_engines.search_engine_base import (+ BaseSearchEngine,+ )++ # Given an engine whose cached downloader has been closed+ closed = Mock()+ engine._arxiv_text_downloader = closed+ with patch.object(BaseSearchEngine, "close", autospec=True):+ engine.close()+ closed.close.assert_called_once_with()++ # When full text is fetched again (downloader construction stubbed,+ # so no network seam is opened)+ with patch(+ "local_deep_research.research_library.downloaders.arxiv."+ "ArxivDownloader"+ ) as downloader_cls:+ fresh = downloader_cls.return_value+ fresh.download_full_text.return_value = ArxivFullTextOutcome(+ ArxivFullTextStatus.TEXT,+ ArxivTextResult("fresh text", ArxivTextSource.ARXIV_HTML),+ )+ text = engine._fetch_full_text(_make_mock_paper())++ # Then a new downloader was built and used; the closed one was not+ downloader_cls.assert_called_once_with(fetch_host="export.arxiv.org")+ closed.download_full_text.assert_not_called()+ assert text == "fresh text"+ assert engine._arxiv_text_downloader is fresh++ def test_close_without_cached_downloader(self, engine):+ from local_deep_research.web_search_engines.search_engine_base import (+ BaseSearchEngine,+ )++ # Given an engine that never fetched full text+ assert getattr(engine, "_arxiv_text_downloader", None) is None++ with patch.object(+ BaseSearchEngine, "close", autospec=True+ ) as base_close:+ engine.close()++ # Then only the base engine's resources are released+ base_close.assert_called_once_with(engine)++class TestClassAttributes:def test_is_public(self):from local_deep_research.web_search_engines.engines.search_engine_arxiv import (diff --git a/tests/web_search_engines/engines/test_arxiv_pdf_egress_gating.py b/tests/web_search_engines/engines/test_arxiv_pdf_egress_gating.pyindex f84c59a4ac..3e27fe5776 100644--- a/tests/web_search_engines/engines/test_arxiv_pdf_egress_gating.py+++ b/tests/web_search_engines/engines/test_arxiv_pdf_egress_gating.py@@ -1,60 +1,25 @@"""-Regression tests for the arXiv PDF download egress-gating hardening.--Invariant under test: every arXiv PDF fetch is routed through the project's-SSRF-validated ``SafeSession`` (SSRF pre-validation and DNS pinning) rather-than ``arxiv.Result.download_pdf``, which fetches via-``urllib.request.urlretrieve`` and bypasses all of those controls. The-fetch targets ``export.arxiv.org`` (arXiv's designated host for automated-access — the same default ``arxiv.Result.download_pdf`` uses and the host-already used for the metadata API), not the public ``arxiv.org`` host.+Regression tests for the arXiv engine's gated full-text path.++Invariant under test: the engine's full-text step never fetches through+``arxiv.Result.download_pdf`` (which uses ``urllib.request.urlretrieve``+and bypasses the project's SSRF controls). It goes through+``ArxivDownloader.download_full_text`` instead, whose HTML and PDF+legs use ``SafeSession`` (SSRF pre-validation and DNS pinning), request+with ``stream=True`` and install the running decoded-byte guard before+reading the body. The id used to build any egress URL is validated first.Metadata queries separately use the typed ``utilities.arxiv_api``boundary, with its own ``SafeSession``, fixed timeout, and request pacing.-This suite covers the engine's PDF download path.--The request URL carries no ``.pdf`` suffix (arxiv 2.4.1's own ``pdf_url``-has none either) — appending one makes ``export.arxiv.org`` answer with a-301 whose body is drained by ``requests``' internal redirect handling-before any size check runs, so the suffix-less form is load-bearing, not-cosmetic.--Note: this fetch passes ``stream=True`` and writes the body to disk in-bounded chunks via ``iter_content`` (never ``.content``, which would-buffer the whole body in memory) with ``Accept-Encoding: identity``. A-running byte count enforced while streaming — not ``SafeSession``'s-``Content-Length`` check alone — is what bounds this fetch: for a valid,-under-cap ``Content-Length`` header, ``_check_response_size`` installs no-body guard at all. The no-``Content-Length`` case is bounded for both-framings since #6180 (``_install_body_guard`` wraps ``read_chunked()`` as-well as ``read()``), and is unrelated to #6172 (which tracks callers that-never set ``stream=True`` at all; this one now does).--``download_dir`` is reachable from per-user web settings, so directory-creation is contained to a dedicated ``arxiv_downloads`` subtree of the-local-deep-research data directory (see ``get_data_directory``) rather-than the data directory itself -- the data directory root also holds-``.secret_key``, the per-user encrypted databases, and backups, and-``download_dir`` is untrusted input, so containing it to a-download-only subtree keeps the blast radius of an accepted-``download_dir`` to that subtree. These tests patch ``get_data_directory``-to return ``tmp_path`` so the real, platform-specific data directory is-never touched.--These tests mock ``SafeSession`` wholesale, so they don't exercise-``_check_response_size`` — they only pin that the call site asks for-``stream=True``/``Accept-Encoding: identity`` and handles the response as-a context manager.++The engine used to download PDFs to disk itself (``_download_pdf_safely``);+that helper had no callers once full text moved to the shared downloader+and was removed together with its tests."""-from pathlib import Pathfrom unittest.mock import MagicMock, Mock, patchimport pytest-ENGINE_MODULE = (- "local_deep_research.web_search_engines.engines.search_engine_arxiv"-)-def _make_engine(**kwargs):from local_deep_research.web_search_engines.engines.search_engine_arxiv import (@@ -70,82 +35,9 @@ def _make_engine(**kwargs):@pytest.fixture-def data_dir(tmp_path):- """Patch get_data_directory() to tmp_path for the duration of a test.-- ``_download_pdf_safely`` contains directory creation to a dedicated- ``arxiv_downloads`` subtree of ``get_data_directory()`` (not the data- directory root itself) because ``download_dir`` is reachable from- per-user web settings. Patching it to ``tmp_path`` keeps these tests- off the real, platform-specific data directory while still exercising- the real containment check (a ``download_dir`` outside the patched- root, or inside it but outside the ``arxiv_downloads`` subtree, is- still rejected -- see- ``test_download_dir_outside_data_directory_is_rejected`` and- ``test_download_dir_inside_data_dir_but_outside_subtree_is_rejected``).- """- with patch(f"{ENGINE_MODULE}.get_data_directory", return_value=tmp_path):- yield tmp_path---def download_dir(data_dir):- """The accepted download directory: inside the contained subtree.-- ``_download_pdf_safely`` requires ``download_dir`` to resolve inside- ``get_data_directory() / "arxiv_downloads"``; the bare data directory- itself (what these tests used to pass directly) is now outside that- root and would be rejected -- see ``download_dir`` usages below.- """- return data_dir / "arxiv_downloads"---def _mock_safe_session(pdf_bytes=b"%PDF-1.4 test"):- """Return (SafeSession class mock, session instance mock, response mock).-- ``response`` (what a correct call site sees via- ``with session.get(...) as response:``) is deliberately a *different*- object from ``session.get.return_value`` (what a buggy call site would- see if it dropped the ``with`` and just did- ``response = session.get(...)``). Only entering the context manager- yields ``response``, whose ``raise_for_status``/``iter_content`` are- configured below; the bare return value's methods are unconfigured- ``MagicMock`` attributes. Iterating an unconfigured ``MagicMock`` does- *not* raise -- ``MagicMock`` pre-configures ``__iter__`` with a- default of ``iter([])``, so a call site that dropped the ``with`` and- iterated the bare return value's ``iter_content()`` result would get- zero chunks back from that call rather than erroring there. What- actually pins the "DO NOT remove the ``with``" invariant the call- site's own comment relies on is that ``response`` and ``get_result``- are different objects: a dropped ``with`` calls methods on- ``get_result``, never on ``response``, and streaming zero chunks- trips ``_stream_response_to_file``'s own empty-body check (``if- written == 0: raise ValueError(...)``) -- so the call to- ``_download_pdf_safely`` itself raises before any of the assertions- below run. It is *not* the ``response.raise_for_status``/- ``response.iter_content`` assertions (e.g. ``assert_called_once()``)- that catch a dropped ``with``: those never execute on that path,- because the ``ValueError`` propagates out of the call first. With the- old version of this helper, ``response.__enter__.return_value =- response`` made the two forms indistinguishable, so dropping the- ``with`` (or dropping ``raise_for_status()``) still passed every- assertion below.- """- response = MagicMock()- response.raise_for_status = Mock()- response.iter_content = Mock(return_value=[pdf_bytes])-- get_result = MagicMock(name="bare_get_result_not_a_context_manager")- get_result.__enter__.return_value = response- get_result.__exit__.return_value = False-- session = MagicMock()- session.get.return_value = get_result-- session_cls = MagicMock()- session_cls.return_value.__enter__.return_value = session- session_cls.return_value.__exit__.return_value = False- return session_cls, session, response+def download_dir(tmp_path):+ """A download directory: only gates full text, nothing is written."""+ return tmp_path / "arxiv_downloads"class TestValidatedArxivId:@@ -191,372 +83,133 @@ class TestValidatedArxivId:assert ArXivSearchEngine._validated_arxiv_id(paper) is None-class TestDownloadPdfSafely:- """The download helper must use SafeSession and never download_pdf."""-- def test_routes_through_safe_session(self, download_dir):- engine = _make_engine()- paper = Mock()- paper.entry_id = "https://arxiv.org/abs/2101.12345"-- session_cls, session, response = _mock_safe_session(b"%PDF-1.4 payload")-- with patch(f"{ENGINE_MODULE}.SafeSession", session_cls):- path = engine._download_pdf_safely(paper, str(download_dir))-- # SafeSession was constructed and used as the fetch transport.- assert session_cls.called- session.get.assert_called_once()- called_url = session.get.call_args.args[0]- # No ".pdf" suffix -- see the module docstring for why that matters.- assert called_url == "https://export.arxiv.org/pdf/2101.12345"-- # The response was consumed via the context manager, not the bare- # session.get() return value (see _mock_safe_session's docstring).- response.raise_for_status.assert_called_once()- response.iter_content.assert_called_once()-- # arxiv.Result.download_pdf (the ungated urlretrieve path) is never used.- assert not paper.download_pdf.called-- # Bytes were written to the returned path inside dirpath, and no- # ".part" temp sibling is left behind after a successful download.- assert Path(path).parent == download_dir- assert Path(path).is_file()- assert Path(path).name == "2101.12345.pdf"- assert list(download_dir.iterdir()) == [Path(path)]- with open(path, "rb") as fh:- assert fh.read() == b"%PDF-1.4 payload"-- def test_uses_streaming_get_with_identity_encoding(self, download_dir):- """stream=True lets the body be written to disk in bounded chunks- instead of buffered whole via `.content` — see the module- docstring. Accept-Encoding: identity is a best-effort measure- against a gzip/deflate decompression bomb on this fetch; the- running byte cap over the decoded stream is the actual backstop- (see the module docstring for why identity alone isn't enough)."""- engine = _make_engine()- paper = Mock()- paper.entry_id = "https://arxiv.org/abs/2101.12345"-- session_cls, session, _ = _mock_safe_session()- with patch(f"{ENGINE_MODULE}.SafeSession", session_cls):- engine._download_pdf_safely(paper, str(download_dir))-- assert session.get.call_args.kwargs["stream"] is True- assert (- session.get.call_args.kwargs["headers"]["Accept-Encoding"]- == "identity"- )-- def test_url_is_built_from_validated_id(self, download_dir):- engine = _make_engine()- paper = Mock()- paper.entry_id = "http://arxiv.org/abs/2301.12345v3"-- session_cls, session, _ = _mock_safe_session()- with patch(f"{ENGINE_MODULE}.SafeSession", session_cls):- engine._download_pdf_safely(paper, str(download_dir))-- assert (- session.get.call_args.args[0]- == "https://export.arxiv.org/pdf/2301.12345v3"- )-- def test_raises_and_makes_no_request_for_bad_id(self, download_dir):- engine = _make_engine()- paper = Mock()- paper.entry_id = "https://evil.example.com/abs/2101.12345"-- session_cls, session, _ = _mock_safe_session()- with patch(f"{ENGINE_MODULE}.SafeSession", session_cls):- with pytest.raises(ValueError):- engine._download_pdf_safely(paper, str(download_dir))-- # No egress attempted for an id that fails validation.- assert not session.get.called- assert not session_cls.called+class TestFullContentUsesGatedPath:+ """The higher-level full-content path must ride the capped downloader+ transport (SafeSession + running decoded-byte guard) and never the+ deprecated ``paper.download_pdf``."""- def test_oversized_streamed_body_is_rejected_and_not_left_on_disk(+ def test_get_full_content_routes_full_text_through_shared_downloader(self, download_dir):- """A body that grows past MAX_RESPONSE_SIZE while being streamed- must be rejected, and no partial file left behind -- this is the- guard that actually bounds a decompressed/chunked body, since- SafeSession's own Content-Length check installs no guard at all- for a valid, under-cap header (see the module docstring).-- The body is streamed to a unique ``.part`` sibling and only- ``os.replace()``d onto the final path on success (see- ``_stream_response_to_file``'s docstring), so a rejected download- must leave that ``.part`` file removed too, not just the final- ``<id>.pdf`` path absent.-- Patches the module's ``MAX_RESPONSE_SIZE`` down to a few bytes- instead of allocating a real ~1GB chunk, which would needlessly- pressure memory for a check that only cares about the comparison,- not the actual cap value.- """- engine = _make_engine()- paper = Mock()- paper.entry_id = "https://arxiv.org/abs/2101.12345"-- oversized_chunk = b"x" * 32- session_cls, session, response = _mock_safe_session()- response.iter_content = Mock(return_value=[oversized_chunk])-- with (- patch(f"{ENGINE_MODULE}.SafeSession", session_cls),- patch(f"{ENGINE_MODULE}.MAX_RESPONSE_SIZE", 8),- ):- with pytest.raises(ValueError):- engine._download_pdf_safely(paper, str(download_dir))-- # No leftover partial PDF (nor its ".part" temp sibling) for a- # rejected download.- assert list(download_dir.iterdir()) == []-- def test_download_dir_outside_data_directory_is_rejected(- self, data_dir, tmp_path_factory- ):- """download_dir is untrusted (reachable from per-user settings), so- directory creation must stay contained to the arxiv_downloads- subtree of get_data_directory() -- a sibling directory entirely- outside the data directory must be rejected rather than silently- created."""- from local_deep_research.security.directory_creation import (- DirectoryCreationSecurityError,+ engine = _make_engine(+ include_full_text=True,+ download_dir=str(download_dir),+ max_full_text=1,)- engine = _make_engine()paper = Mock()paper.entry_id = "https://arxiv.org/abs/2101.12345"+ paper.pdf_url = "https://arxiv.org/pdf/2101.12345"+ paper.authors = []+ paper.published = None+ paper.updated = None+ paper.categories = ["cs.AI"]+ paper.summary = "Summary text"+ paper.comment = None+ paper.doi = None+ paper.journal_ref = None+ engine._papers = {"https://arxiv.org/abs/2101.12345": paper}- outside_dir = tmp_path_factory.mktemp("outside_data_dir")- session_cls, session, _ = _mock_safe_session()-- with patch(f"{ENGINE_MODULE}.SafeSession", session_cls):- with pytest.raises(DirectoryCreationSecurityError):- engine._download_pdf_safely(paper, str(outside_dir))-- # Rejected before any egress was attempted.- assert not session.get.called+ item = {"id": "https://arxiv.org/abs/2101.12345"}- def test_download_dir_inside_data_dir_but_outside_subtree_is_rejected(- self, data_dir- ):- """A download_dir that resolves inside get_data_directory() but- outside its arxiv_downloads subtree must still be rejected --- this is the containment-root-too-broad regression this subtree- exists to close. Before the subtree narrowing, any path under the- bare data directory (including e.g. a not-yet-existing per-user- encrypted-DB path, since the username hash is computable) was- accepted; now only paths under arxiv_downloads are."""- from local_deep_research.security.directory_creation import (- DirectoryCreationSecurityError,+ from local_deep_research.research_library.downloaders.arxiv import (+ ArxivFullTextOutcome,+ ArxivFullTextStatus,+ ArxivTextResult,+ ArxivTextSource,)- engine = _make_engine()- paper = Mock()- paper.entry_id = "https://arxiv.org/abs/2101.12345"+ downloader = MagicMock()+ downloader.download_full_text.return_value = ArxivFullTextOutcome(+ ArxivFullTextStatus.TEXT,+ ArxivTextResult(+ text="HTML rendition text", source=ArxivTextSource.ARXIV_HTML+ ),+ )+ # The engine imports ArxivDownloader lazily inside _fetch_full_text,+ # so patching the class at its source module intercepts the seam.+ with patch(+ "local_deep_research.research_library.downloaders.arxiv."+ "ArxivDownloader",+ return_value=downloader,+ ):+ results = engine._get_full_content([item])- # A sibling of arxiv_downloads, still inside data_dir.- sibling_dir = data_dir / "encrypted_databases"- session_cls, session, _ = _mock_safe_session()-- with patch(f"{ENGINE_MODULE}.SafeSession", session_cls):- with pytest.raises(DirectoryCreationSecurityError):- engine._download_pdf_safely(paper, str(sibling_dir))-- # Rejected before any egress was attempted, and nothing was created.- assert not session.get.called- assert not sibling_dir.exists()---class TestStreamResponseToFileIntermediateState:- """The body must never be visible at ``target_path`` until the fetch- fully completes -- it is streamed to a per-call ``.part`` sibling and- only ``os.replace()``d onto ``target_path`` afterwards (see- ``_stream_response_to_file``'s docstring).-- Both existing assertions in ``TestDownloadPdfSafely`` only inspect the- directory listing *after* ``_download_pdf_safely`` has already- returned -- ``test_routes_through_safe_session``'s- ``list(download_dir.iterdir()) == [Path(path)]`` and the- oversized-body test's ``== []`` -- so a revert straight back to- streaming directly into ``target_path`` (dropping the ``.part`` +- ``os.replace()`` indirection entirely) still satisfies both of them:- the *final* directory state is identical either way (one completed- file, or none). These tests instead inspect the state *while the body- is still streaming*, which is the only place that revert actually- differs.- """-- def test_target_path_does_not_exist_mid_stream(self, download_dir):- """Catches a revert of ``_stream_response_to_file`` to opening- ``target_path`` itself for writing (no ``.part`` sibling, no- rename): on that revert, ``target_path`` would already exist- (partially written) by the time a later chunk is requested, and- no ``.part``-suffixed file would exist at all.- """- engine = _make_engine()- paper = Mock()- paper.entry_id = "https://arxiv.org/abs/2101.12345"- target_name = "2101.12345.pdf"- observed = {}-- def chunks():- yield b"first-chunk-bytes"- # Mid-stream: the first chunk has already been written to- # disk, but the response body has not finished streaming.- observed["target_exists"] = (download_dir / target_name).exists()- observed["part_files"] = [- p.name- for p in download_dir.iterdir()- if p.name.startswith(target_name + ".")- and p.name.endswith(".part")- ]- yield b"second-chunk-bytes"-- session_cls, session, response = _mock_safe_session()- response.iter_content = Mock(return_value=chunks())-- with patch(f"{ENGINE_MODULE}.SafeSession", session_cls):- engine._download_pdf_safely(paper, str(download_dir))-- assert observed["target_exists"] is False- assert len(observed["part_files"]) == 1-- def test_part_suffix_is_unique_per_call(self, download_dir):- """Catches unpinning the ``uuid4().hex`` component of the- ``.part`` filename (reverting ``_stream_response_to_file`` to a- fixed ``<target_name>.part`` sibling with no per-call-unique- suffix). ``test_target_path_does_not_exist_mid_stream`` above only- checks that *a* name matching ``startswith(name + ".") and- endswith(".part")`` exists mid-stream -- a fixed ``<name>.part``- satisfies that filter just as well as a uuid-suffixed one, so it- can't tell the two apart. The whole point of the per-call-unique- suffix, per the function's docstring, is that two concurrent- downloads of the same arXiv id can only ever remove *their own*- partial file; this test drives the streaming write twice for the- same id and captures the generated ``.part`` name each time --- under a fixed-suffix revert both calls would produce the- identical name.- """- engine = _make_engine()- target_name = "2101.12345.pdf"- observed_names = []-- def make_chunks():- def chunks():- yield b"first-chunk-bytes"- names = [- p.name- for p in download_dir.iterdir()- if p.name.startswith(target_name + ".")- and p.name.endswith(".part")- ]- assert len(names) == 1- observed_names.append(names[0])- yield b"second-chunk-bytes"-- return chunks()-- for _ in range(2):- paper = Mock()- paper.entry_id = "https://arxiv.org/abs/2101.12345"- session_cls, session, response = _mock_safe_session()- response.iter_content = Mock(return_value=make_chunks())-- with patch(f"{ENGINE_MODULE}.SafeSession", session_cls):- engine._download_pdf_safely(paper, str(download_dir))-- assert len(observed_names) == 2- assert observed_names[0] != observed_names[1]- assert observed_names[0] != f"{target_name}.part"- assert observed_names[1] != f"{target_name}.part"-- def test_keyboard_interrupt_mid_stream_cleans_up_part_file(- self, download_dir- ):- """Catches rewriting ``_stream_response_to_file``'s cleanup from a- ``finally`` block to ``except Exception: unlink(...); raise``.- Every other test in this module only ever raises ``Exception``- subclasses (``ValueError``, an oversized-chunk rejection, etc.),- so an ``except Exception``-based rewrite would pass all of them- too. ``KeyboardInterrupt`` does not subclass ``Exception`` (it- subclasses ``BaseException`` directly), so that rewrite would let- it propagate straight past the cleanup, orphaning the ``.part``- file -- up to ``MAX_RESPONSE_SIZE`` bytes -- in the shared- ``arxiv_downloads`` root with no sweeper to reclaim it. This test- must let the ``KeyboardInterrupt`` propagate out of- ``_download_pdf_safely`` and catch it explicitly (a bare- ``except Exception`` in the test itself would just as wrongly- swallow it).+ # The HTML-first gated downloader performed the fetch through the+ # SafeSession-based download stack; the deprecated paper.download_pdf+ # was never called.+ downloader.download_full_text.assert_called_once_with(+ "https://arxiv.org/abs/2101.12345"+ )+ assert not paper.download_pdf.called+ assert results[0]["content"] == "HTML rendition text"++ def test_get_full_content_pdf_transport_is_byte_capped(self, download_dir):+ """The engine's full-text PDF fallback leg bounds the decoded body.++ Drives the real downloader chain from ``_get_full_content``: the+ HTML leg answers 404, so ``download_full_text`` falls back+ to ``BaseDownloader._download_pdf``, whose response is a crafted+ body decoding past ``MAX_RESPONSE_SIZE`` while claiming a valid,+ under-cap ``Content-Length`` — the exact framing SafeSession+ leaves unguarded. The abort can only come from+ ``BaseDownloader._ensure_decoded_body_cap``'s guard install;+ reverting it lets the finite bomb through as a "successful"+ download and the ResponseBodyTooLarge outcome is never recorded."""- engine = _make_engine()- paper = Mock()- paper.entry_id = "https://arxiv.org/abs/2101.12345"+ import contextlib- def chunks():- yield b"first-chunk-bytes"- raise KeyboardInterrupt()+ import requests as requests_lib- session_cls, session, response = _mock_safe_session()- response.iter_content = Mock(return_value=chunks())+ from local_deep_research.research_library.downloaders.arxiv import (+ ArxivDownloader,+ )+ from local_deep_research.security import safe_requests- with patch(f"{ENGINE_MODULE}.SafeSession", session_cls):- with pytest.raises(KeyboardInterrupt):- engine._download_pdf_safely(paper, str(download_dir))+ chunk = b"x" * (1024 * 1024)- # `finally` (not `except Exception`) ran the cleanup: no orphaned- # `.part` file -- or anything else -- is left behind.- assert list(download_dir.iterdir()) == []+ class BombRaw:+ def __init__(self, chunks):+ self.remaining = chunks+ self.read_calls = 0- def test_empty_body_does_not_replace_existing_complete_download(- self, download_dir- ):- """A ``200`` with a zero-byte body must be rejected before- ``os.replace()`` runs, and must never overwrite an- already-completed ``target_path`` left by an earlier, separate- download of the same id.-- Catches dropping (or reordering after ``os.replace()``) the- ``written == 0`` check in ``_stream_response_to_file``: on that- revert this test's pre-seeded, already-complete ``target_path``- would be silently replaced by a 0-byte file while the call still- reported success (no exception raised).- """- engine = _make_engine()- paper = Mock()- paper.entry_id = "https://arxiv.org/abs/2101.12345"+ def read(self, amt=None, decode_content=False):+ self.read_calls += 1+ if self.remaining <= 0:+ return b""+ self.remaining -= 1+ return chunk- download_dir.mkdir(parents=True, exist_ok=True)- target_path = download_dir / "2101.12345.pdf"- target_path.write_bytes(b"%PDF-1.4 already complete")+ def stream(self, amt=None, decode_content=None):+ while True:+ data = self.read(amt, decode_content)+ if not data:+ break+ yield data- session_cls, session, response = _mock_safe_session()- response.iter_content = Mock(return_value=[]) # zero bytes streamed+ def close(self):+ pass- with patch(f"{ENGINE_MODULE}.SafeSession", session_cls):- with pytest.raises(ValueError):- engine._download_pdf_safely(paper, str(download_dir))+ def release_conn(self):+ pass- assert target_path.read_bytes() == b"%PDF-1.4 already complete"- # No leftover ".part" sibling either.- assert list(download_dir.iterdir()) == [target_path]+ def not_found():+ return Mock(status_code=404, headers={})+ bomb = requests_lib.Response()+ bomb.status_code = 200+ bomb.headers["Content-Type"] = "application/pdf"+ bomb.headers["Content-Length"] = "100"+ bomb.raw = BombRaw(chunks=4)-class TestFullContentUsesGatedPath:- """The higher-level full-content path must also avoid download_pdf."""+ downloader = ArxivDownloader()+ downloader.rate_tracker = MagicMock()- def test_get_full_content_uses_safe_session(self, download_dir):engine = _make_engine(include_full_text=True,download_dir=str(download_dir),max_full_text=1,)-paper = Mock()paper.entry_id = "https://arxiv.org/abs/2101.12345"paper.pdf_url = "https://arxiv.org/pdf/2101.12345"@@ -569,19 +222,36 @@ class TestFullContentUsesGatedPath:paper.doi = Nonepaper.journal_ref = Noneengine._papers = {"https://arxiv.org/abs/2101.12345": paper}+ # Pre-seed the engine's downloader cache with our instrumented one+ engine._arxiv_text_downloader = downloaderitem = {"id": "https://arxiv.org/abs/2101.12345"}- session_cls, session, _ = _mock_safe_session(b"%PDF-1.4 body")- # Neutralise the PDF text extractors so the test stays focused on- # the egress transport rather than parsing.with (- patch(f"{ENGINE_MODULE}.SafeSession", session_cls),- patch("pypdf.PdfReader", side_effect=Exception("skip")),+ patch.object(+ downloader.session,+ "get",+ side_effect=[not_found(), bomb],+ ),+ patch(+ "local_deep_research.research_library.downloaders.arxiv."+ "arxiv_api_request_gate",+ contextlib.nullcontext,+ ),+ patch.object(safe_requests, "MAX_RESPONSE_SIZE", 2 * 1024 * 1024),):results = engine._get_full_content([item])- # The gated session performed the fetch; download_pdf was never called.- assert session.get.called- assert not paper.download_pdf.called- assert results[0]["pdf_path"] is not None+ # The PDF fetch aborted at the cap: exactly one outcome carries the+ # size-cap label (the HTML leg carries HTTP_404; the engine skips+ # the API leg)+ cap_calls = [+ call+ for call in downloader.rate_tracker.record_outcome.call_args_list+ if call.kwargs.get("error_type") == "ResponseBodyTooLarge"+ ]+ assert len(cap_calls) == 1+ # The full-text fetch yielded nothing, so the summary stands+ assert results[0]["content"] == "Summary text"+ # The read stopped at the cap (1 + 1 MiB fit; the 3rd crosses)+ assert bomb.raw.read_calls == 3diff --git a/tests/web_search_engines/engines/test_search_engine_arxiv.py b/tests/web_search_engines/engines/test_search_engine_arxiv.pyindex 9767cdc25a..b105f2ea4e 100644--- a/tests/web_search_engines/engines/test_search_engine_arxiv.py+++ b/tests/web_search_engines/engines/test_search_engine_arxiv.py@@ -415,6 +415,7 @@ class TestGetFullContent:)mock_paper = Mock()+ mock_paper.entry_id = "https://arxiv.org/abs/2101.12345"mock_paper.pdf_url = "https://arxiv.org/pdf/2101.12345.pdf"mock_paper.authors = [Mock(name="Author 1")]mock_paper.published = datetime(2021, 1, 15)@@ -435,9 +436,7 @@ class TestGetFullContent:results = engine._get_full_content(items)assert len(results) == 1- assert (- results[0]["pdf_url"] == "https://arxiv.org/pdf/2101.12345.pdf"- )+ assert results[0]["pdf_url"] == "https://arxiv.org/pdf/2101.12345"assert results[0]["summary"] == "Full summary"assert results[0]["content"] == "Full summary"