Skip to content

~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.

feat(arxiv): improve paper text with HTML extraction (#5617)

LearningCircuiteff9b09db14a
diff --git a/changelog.d/4783.feature.md b/changelog.d/4783.feature.md
new file mode 100644
index 0000000000..c089d4a3c8
--- /dev/null
+++ b/changelog.d/4783.feature.md
@@ -0,0 +1 @@
+Improve arXiv paper text extraction by preferring official HTML and preserving embedded TeX equations. Fall back to PDF text when HTML is unavailable, redirects away from a rendition, or falls below the content-quality floors, and use API metadata when full text cannot be extracted. Preserve versioned and legacy identifiers, reuse available PDF bytes, and record extraction provenance. Only URLs that name a paper are treated as arXiv; other pages on the arXiv hosts (listings, author pages, the info/blog/static subdomains, and the legacy `/ftp/` PDF layout) keep the generic HTML and direct-PDF handling they had before. Renditions carrying more than 5000 equations fall back to the PDF rather than being rewritten, and namespace-prefixed MathML (`<m:math>`) is now rewritten too, so its equations are stored as clean TeX instead of being dropped or left glued to the presentation text, depending on the page. Extraction quality for a newly stored text-only document is now derived from the extraction method for every source, not just arXiv, so a method other than a native API or pdfplumber is recorded as `low` where it was previously `medium`. Page-supplied titles and descriptions are collapsed to a single line before they are written into the stored text.
diff --git a/src/local_deep_research/content_fetcher/fetcher.py b/src/local_deep_research/content_fetcher/fetcher.py
index b7c802e7f0..56d0e22693 100644
--- a/src/local_deep_research/content_fetcher/fetcher.py
+++ b/src/local_deep_research/content_fetcher/fetcher.py
@@ -18,8 +18,26 @@ from ..utilities.resource_utils import safe_close
# Default maximum content length (500KB of text)
DEFAULT_MAX_CONTENT_LENGTH = 500_000
-# URL types where HTML fallback is pointless when the specialized downloader fails
-_NO_HTML_FALLBACK = {URLType.HTML, URLType.DOI, URLType.INVALID, URLType.PDF}
+# URL types whose selected strategy owns the terminal outcome when its
+# download fails.
+_NO_HTML_FALLBACK = {
+ URLType.ARXIV,
+ URLType.HTML,
+ URLType.DOI,
+ URLType.INVALID,
+ URLType.PDF,
+}
+
+# URL types that stay terminal even when the specialized downloader could not
+# be imported at all. Only arXiv qualifies, and only because URLType.ARXIV is
+# now reserved for URLs that name one paper (see URLClassifier.classify): for
+# those the downloader owns the canonical HTML, PDF, and API sources, and the
+# input URL (an ar5iv mirror included) is never fetched directly, so generic
+# extraction of that URL is not a valid substitute. Other arXiv-host pages --
+# listings, author pages, info./blog./static. subdomains, the legacy /ftp/
+# PDF layout -- have no canonical source and classify as HTML or PDF, so they
+# keep the generic path. Every other type keeps the import-failure fallback.
+_NO_IMPORT_FALLBACK = {URLType.ARXIV}
class ContentFetcher:
@@ -296,20 +314,20 @@ class ContentFetcher:
# Get the appropriate downloader
downloader = self._get_downloader(url_type)
- if not downloader:
+ if not downloader and url_type not in _NO_IMPORT_FALLBACK:
# Fall back to generic HTML downloader. This triggers when a
- # specialized downloader (ArXiv, SemanticScholar, etc.) failed
- # to import — playwright_html may still be available.
+ # specialized downloader failed to import — playwright_html may
+ # still be available.
# Use _get_downloader so the instance is cached and cleaned up
# by close().
downloader = self._get_downloader(URLType.HTML)
- if not downloader:
- return {
- "status": "error",
- "url": url,
- "source_type": source_name,
- "error": "No suitable downloader available",
- }
+ if not downloader:
+ return {
+ "status": "error",
+ "url": url,
+ "source_type": source_name,
+ "error": "No suitable downloader available",
+ }
# Determine content type
content_type = ContentType.TEXT if prefer_text else ContentType.PDF
@@ -318,9 +336,12 @@ class ContentFetcher:
try:
result = downloader.download_with_result(url, content_type)
- # HTML fallback: when a specialized downloader fails (e.g.
- # arXiv PDF unavailable, PubMed paywalled), try generic HTML
- # extraction — the abstract/landing page often has useful content.
+ # HTML fallback: when a fallback-eligible specialized downloader
+ # fails (for example, PubMed is paywalled), try generic extraction.
+ # A paper URL classified ARXIV is terminal here because its
+ # downloader owns canonical HTML, PDF, and API fallbacks and the
+ # input URL is never fetched; non-paper arXiv pages never reach
+ # this branch as ARXIV, so they are not denied the fallback.
if not result.is_success and url_type not in _NO_HTML_FALLBACK:
logger.debug(
f"Specialized downloader failed for {url}, "
@@ -430,10 +451,10 @@ class ContentFetcher:
def fetch_batch(self, urls: List[str]) -> Dict[str, Optional[str]]:
"""Fetch multiple URLs, routing each to the best downloader.
- Specialized downloaders (arXiv, PubMed, etc.) are tried first;
- generic HTML extraction is used as fallback. Downloaders are
- cached by URL type, so a single Playwright browser is shared
- across all HTML URLs.
+ Specialized downloaders are tried first; generic HTML extraction is
+ used only for fallback-eligible URL types. arXiv handles its own
+ canonical fallbacks. Downloaders are cached by URL type, so a single
+ Playwright browser is shared across all HTML URLs.
Returns:
Dict mapping URL → extracted text (or None if failed).
diff --git a/src/local_deep_research/content_fetcher/url_classifier.py b/src/local_deep_research/content_fetcher/url_classifier.py
index 0ba1b00dc5..09beb2090a 100644
--- a/src/local_deep_research/content_fetcher/url_classifier.py
+++ b/src/local_deep_research/content_fetcher/url_classifier.py
@@ -9,6 +9,11 @@ from enum import Enum
from typing import Optional
from urllib.parse import urlparse
+from ..utilities.arxiv import (
+ extract_arxiv_id as extract_arxiv_id_from_url,
+ is_arxiv_paper_url,
+)
+
class URLType(Enum):
"""Types of URLs we can handle."""
@@ -32,14 +37,6 @@ DANGEROUS_SCHEMES = {"javascript", "data", "file", "vbscript", "about"}
class URLClassifier:
"""Classifies URLs to determine the appropriate downloader."""
- # ArXiv patterns
- ARXIV_PATTERNS = [
- r"arxiv\.org/abs/",
- r"arxiv\.org/pdf/",
- r"arxiv\.org/html/",
- r"ar5iv\.org/",
- ]
-
# PubMed patterns
PUBMED_PATTERNS = [
r"pubmed\.ncbi\.nlm\.nih\.gov/\d+",
@@ -99,15 +96,19 @@ class URLClassifier:
except Exception:
return URLType.INVALID
- # Check for direct PDF link first
+ # Only a URL that names one paper belongs to arXiv. Other pages on
+ # the family hosts (listings, author pages, info./blog./static.
+ # subdomains, the legacy /ftp/ PDF layout) carry no identifier the
+ # arXiv downloader can act on, and ARXIV ownership is terminal for
+ # every fetch entry point, so they stay with the generic pipelines.
+ if is_arxiv_paper_url(url.strip()):
+ return URLType.ARXIV
+
+ # Check direct PDF links after arXiv-family routing
if cls._is_pdf_url(url_lower):
return URLType.PDF
# Check specific academic sources
- for pattern in cls.ARXIV_PATTERNS:
- if re.search(pattern, url_lower):
- return URLType.ARXIV
-
for pattern in cls.PMC_PATTERNS:
if re.search(pattern, url_lower):
return URLType.PMC
@@ -187,16 +188,9 @@ class URLClassifier:
url_type = cls.classify(url)
if url_type == URLType.ARXIV:
- # Extract arXiv ID (e.g., 2301.12345 or cond-mat/0501234)
- match = re.search(r"(\d{4}\.\d{4,5}(?:v\d+)?)", url)
- if match:
- return match.group(1)
- # Old format
- match = re.search(r"([a-z-]+/\d{7}(?:v\d+)?)", url)
- if match:
- return match.group(1)
+ return extract_arxiv_id_from_url(url)
- elif url_type == URLType.PUBMED:
+ if url_type == URLType.PUBMED:
# Extract PMID
match = re.search(r"/(\d+)/?", url)
if match:
diff --git a/src/local_deep_research/research_library/downloaders/arxiv.py b/src/local_deep_research/research_library/downloaders/arxiv.py
index 37b4f3e7af..cbd960d3b0 100644
--- a/src/local_deep_research/research_library/downloaders/arxiv.py
+++ b/src/local_deep_research/research_library/downloaders/arxiv.py
@@ -3,33 +3,112 @@ arXiv PDF and Text Downloader
"""
import re
-from typing import Dict, Optional
+from dataclasses import dataclass
+from enum import StrEnum
+from typing import Dict, Final, Optional
from urllib.parse import urlparse
-from loguru import logger
-
-from .base import BaseDownloader, ContentType, DownloadResult, USER_AGENT
+from bs4 import BeautifulSoup, NavigableString
+from loguru import logger
-class ArxivDownloader(BaseDownloader):
- """Downloader for arXiv papers with PDF and abstract/text support."""
+from ...constants import USER_AGENT
+from ...utilities.arxiv import extract_arxiv_id, is_arxiv_paper_url
+from ...utilities.arxiv_api import arxiv_api_request_gate
+from .base import ContentType, DownloadResult
+from .html import HTMLDownloader
+
+
+class ArxivTextSource(StrEnum):
+ """Canonical source used to produce arXiv text."""
+
+ ARXIV_HTML = "arxiv_html"
+ LOCAL_PDF = "local_pdf"
+ ARXIV_API = "arxiv_api"
+
+
+@dataclass(frozen=True, slots=True)
+class ArxivTextResult:
+ """Text paired with its exact arXiv production source."""
+
+ text: str
+ source: ArxivTextSource
+
+
+# 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
+# character floor while carrying none of the paper.
+MIN_HTML_TO_PDF_TEXT_RATIO = 0.5
+
+# Absolute floor for HTML accepted with no PDF text to compare against.
+# The ratio above only protects callers that already hold PDF bytes; the
+# text-first paths (ContentFetcher.fetch, pipeline.fetch_and_extract, and
+# download_service's first-ever text extraction) call in with none, and a
+# stub clears the extraction pipeline's 50 character floor easily. The
+# known stub extracts to ~260 characters and real LaTeXML renditions run to
+# tens of thousands, so this sits about 8x above the former and an order of
+# magnitude below the latter. It is a heuristic -- arXiv does not mark stub
+# pages distinctly -- but failing it is cheap: download_text_with_source
+# then falls through to downloading the PDF, which is exactly what these
+# paths did before HTML-first existed.
+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
+# 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
+# HTML download has always paid; the only limits there are the HTTP timeout
+# and SafeSession's 1 GiB body cap. Real arXiv papers sit orders of magnitude
+# below the bound -- a heavy mathematics paper runs to a few hundred
+# equations -- so exceeding it marks a page the PDF serves better.
+MAX_MATH_ELEMENTS = 5000
+
+# MathML reaches these pages namespace-prefixed as often as not, and lxml's
+# HTML parser keeps the prefix in the tag name (``<m:math>`` parses to a tag
+# named "m:math"). A literal "math" match therefore finds nothing on such a
+# page and the rendition is accepted with its MathML left in place. What
+# the extractors then make of the raw MathML depends on the page rather than
+# on which extractor wins the tiebreak: either one may drop the element, so
+# the equation is missing from the stored text (with no PDF fallback once
+# the text clears the standalone floor), or emit its text nodes glued to the
+# TeX ("x\\frac{1}{2}" for an equation whose visible symbol is "x").
+# Matching on the local name rewrites both spellings, so the stored text is
+# the clean TeX either way.
+_MATHML_LOCAL_NAME: Final = re.compile(r"(?:^|:)math$", re.IGNORECASE)
+_TEX_ANNOTATION_LOCAL_NAME: Final = re.compile(
+ r"(?:^|:)annotation$", re.IGNORECASE
+)
+
+
+class ArxivDownloader(HTMLDownloader):
+ """Download arXiv PDFs and produce text from canonical arXiv sources."""
+
+ def __init__(self, timeout: int = 30, language: str = "English"):
+ super().__init__(timeout=timeout, language=language)
+ session = self.session
+ if session is not None:
+ session.headers.update({"User-Agent": USER_AGENT})
def can_handle(self, url: str) -> bool:
- """Check if URL is from arXiv."""
- try:
- hostname = urlparse(url).hostname
- return bool(
- hostname
- and (hostname == "arxiv.org" or hostname.endswith(".arxiv.org"))
- )
- except Exception:
- return False
+ """Check if URL names a specific arXiv paper.
+
+ Host membership is not enough. Every entry point below needs an
+ identifier to build a canonical URL from, so a family URL without one
+ -- a listing, an author page, or the legacy ``/ftp/`` PDF layout --
+ would be claimed only to be skipped, starving the downloader that can
+ actually serve it (``DirectPDFDownloader`` for ``/ftp/`` PDFs).
+ """
+ return is_arxiv_paper_url(url)
def download(
self, url: str, content_type: ContentType = ContentType.PDF
) -> Optional[bytes]:
"""Download content from arXiv."""
if content_type == ContentType.TEXT:
- return self._download_text(url)
+ text = self.download_text(url)
+ return text.encode("utf-8", errors="ignore") if text else None
return self._download_pdf(url)
def download_with_result(
@@ -44,31 +123,12 @@ class ArxivDownloader(BaseDownloader):
)
if content_type == ContentType.TEXT:
- # ArXiv API only provides abstracts, not full text
- # We need to download the PDF and extract full text
- logger.info(
- f"Downloading arXiv PDF for full text extraction: {arxiv_id}"
- )
-
- pdf_content = self._download_pdf(url)
- if pdf_content:
- extracted_text = self.extract_text_from_pdf(pdf_content)
- if extracted_text:
- # Optionally prepend metadata from API
- metadata = self._fetch_from_arxiv_api(arxiv_id)
- if metadata:
- # Combine metadata with full text
- full_text = f"{metadata}\n\n{'=' * 80}\nFULL PAPER TEXT\n{'=' * 80}\n\n{extracted_text}"
- return DownloadResult(
- content=full_text.encode("utf-8", errors="ignore"),
- is_success=True,
- )
- # Just return the extracted text
- return DownloadResult(
- content=extracted_text.encode("utf-8", errors="ignore"),
- is_success=True,
- )
-
+ text = self.download_text(url)
+ if text:
+ return DownloadResult(
+ content=text.encode("utf-8", errors="ignore"),
+ is_success=True,
+ )
return DownloadResult(
skip_reason=f"Could not retrieve full text for arXiv:{arxiv_id}"
)
@@ -109,57 +169,281 @@ class ArxivDownloader(BaseDownloader):
return super()._download_pdf(pdf_url, headers=enhanced_headers)
- def _download_text(self, url: str) -> Optional[bytes]:
- """Get full text content from arXiv PDF (with metadata from API)."""
- # Extract arXiv ID
+ def download_text(
+ self, url: str, pdf_content: bytes | None = None
+ ) -> str | None:
+ """Return official HTML, PDF text, or API metadata for an arXiv URL.
+
+ Supplied PDF bytes are reused even when empty. When they are omitted,
+ the canonical arXiv PDF is downloaded once. ar5iv URLs are accepted
+ only for identifier normalization and are never fetched directly.
+ """
+ result = self.download_text_with_source(url, pdf_content=pdf_content)
+ return result.text if result is not None else None
+
+ 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."""
arxiv_id = self._extract_arxiv_id(url)
if not arxiv_id:
return None
- # Download PDF for full text extraction
- logger.info(f"Downloading arXiv PDF for full text: {arxiv_id}")
- pdf_content = self._download_pdf(url)
- if pdf_content:
- extracted_text = self.extract_text_from_pdf(pdf_content)
- if extracted_text:
- # Get metadata from API to prepend
- metadata = self._fetch_from_arxiv_api(arxiv_id)
- if metadata:
- # Combine metadata with full text
- full_text = f"{metadata}\n\n{'=' * 80}\nFULL PAPER TEXT\n{'=' * 80}\n\n{extracted_text}"
- return full_text.encode("utf-8", errors="ignore")
- return extracted_text.encode("utf-8", errors="ignore")
+ canonical_url = f"https://arxiv.org/abs/{arxiv_id}"
+
+ # PDF bytes already in hand set the quality floor for HTML, so their
+ # text is extracted before HTML is considered.
+ pdf_text = (
+ self.extract_text_from_pdf(pdf_content)
+ if pdf_content is not None
+ else 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 html_text and self._html_text_beats_pdf_text(
+ html_text, pdf_text, arxiv_id
+ ):
+ return ArxivTextResult(html_text, ArxivTextSource.ARXIV_HTML)
+
+ if pdf_content is None:
+ logger.info(f"Downloading arXiv PDF for full text: {arxiv_id}")
+ downloaded_pdf = self._download_pdf(url)
+ if downloaded_pdf is not None:
+ pdf_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)
+
+ 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) -> 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)
+ if not html:
+ return None
+ if not self._stayed_on_arxiv_html(final_url, arxiv_id):
+ logger.info(
+ "arXiv HTML request for {} redirected to {}; not a rendition",
+ arxiv_id,
+ final_url,
+ )
+ return None
+
+ try:
+ soup = BeautifulSoup(html, "lxml")
+ if not self._rewrite_math_to_tex(soup, arxiv_id):
+ return None
+
+ canonical_url = f"https://arxiv.org/abs/{arxiv_id}"
+ extracted = self._extract_content(str(soup), canonical_url)
+ if not extracted:
+ return None
+ text = self._format_extracted_content(extracted)
+ return text if text.strip() else None
+ except Exception:
+ logger.warning(
+ "arXiv HTML unusable; trying fallbacks: {}", arxiv_id
+ )
+ return None
+
+ @staticmethod
+ def _rewrite_math_to_tex(soup: BeautifulSoup, arxiv_id: str) -> bool:
+ """Replace every <math> element with its TeX annotation, in place.
+
+ Returns False when the rendition must be abandoned for the PDF. Three
+ distinct cases do that, each logged at debug so they are told apart
+ in a report: the page carries more than MAX_MATH_ELEMENTS equations,
+ a <math> has no ``<annotation encoding="application/x-tex">`` child,
+ or that annotation is empty. The second is not hypothetical -- LaTeXML
+ also carries the TeX in the ``alttext`` attribute and the parallel
+ <annotation> markup depends on how arXiv invokes it, so a whole class
+ of renditions may take this exit.
+
+ Each element is rewritten in place -- renamed to an inline <span>
+ holding the TeX -- rather than with ``Tag.replace_with``. replace_with
+ locates the element with a linear scan of its parent's contents, so
+ rewriting n equations that share one parent costs O(n^2); arXiv
+ renders this HTML from author-submitted LaTeX, and it is reached on
+ the search path. Rewriting in place is linear and keeps bs4's own
+ escaping on serialization.
+ """
+ math_elements = soup.find_all(_MATHML_LOCAL_NAME)
+ if len(math_elements) > MAX_MATH_ELEMENTS:
+ logger.debug(
+ "arXiv HTML for {} carries {} <math> elements, above the "
+ "{} element bound; falling back to the PDF",
+ arxiv_id,
+ len(math_elements),
+ MAX_MATH_ELEMENTS,
+ )
+ return False
+
+ for math in math_elements:
+ annotation = math.find(
+ _TEX_ANNOTATION_LOCAL_NAME,
+ attrs={"encoding": "application/x-tex"},
+ )
+ if annotation is None:
+ logger.debug(
+ "arXiv HTML for {} has a <math> element with no "
+ '<annotation encoding="application/x-tex"> child; '
+ "falling back to the PDF",
+ arxiv_id,
+ )
+ return False
+ tex = annotation.get_text().strip()
+ if not tex:
+ logger.debug(
+ "arXiv HTML for {} has a <math> element whose TeX "
+ "annotation is empty; falling back to the PDF",
+ arxiv_id,
+ )
+ return False
+ math.name = "span"
+ math.attrs.clear()
+ math.clear()
+ math.append(NavigableString(tex))
+ return True
+
+ @staticmethod
+ def _is_matching_arxiv_paper_url(
+ response_url: str | None, arxiv_id: str
+ ) -> bool:
+ """Require an official URL for the requested paper and version.
+
+ An unversioned request may resolve to a versioned rendition of the
+ same paper. An explicit version must remain exact. The host test is
+ the ``.arxiv.org`` trust boundary, so ``ar5iv.labs.arxiv.org`` -- the
+ host the real ar5iv service runs on -- is inside it and accepted,
+ while the bare ``ar5iv.org`` domain is not: it is an input identifier
+ only and is never treated as an authoritative response. That is also
+ why this does not reuse ``is_arxiv_family_url``, whose family takes
+ in ``ar5iv.org``: widening the boundary to match it would accept a
+ response from a host arXiv does not serve.
+ """
+ if not response_url:
+ return False
+ try:
+ parsed = urlparse(response_url)
+ hostname = (parsed.hostname or "").lower().rstrip(".")
+ expected_port = {"https": 443, "http": 80}.get(parsed.scheme)
+ if (
+ expected_port is None
+ or parsed.port not in {None, expected_port}
+ or parsed.username is not None
+ or parsed.password is not None
+ or not (
+ hostname == "arxiv.org" or hostname.endswith(".arxiv.org")
+ )
+ ):
+ return False
+ except ValueError:
+ return False
+ actual_id = extract_arxiv_id(response_url)
+ if actual_id is None:
+ return False
+ if re.search(r"v\d+$", arxiv_id, re.IGNORECASE):
+ return actual_id.casefold() == arxiv_id.casefold()
+ return (
+ re.sub(r"v\d+$", "", actual_id, flags=re.IGNORECASE).casefold()
+ == arxiv_id.casefold()
+ )
+
+ @classmethod
+ def _stayed_on_arxiv_html(
+ cls, final_url: str | None, arxiv_id: str
+ ) -> bool:
+ """Accept HTTPS HTML only for the requested arXiv paper/version."""
+ if not final_url or not cls._is_matching_arxiv_paper_url(
+ final_url, arxiv_id
+ ):
+ return False
+ parsed = urlparse(final_url)
+ return parsed.scheme == "https" and parsed.path.startswith("/html/")
+
+ def _html_text_beats_pdf_text(
+ self, html_text: str, pdf_text: str | None, arxiv_id: str
+ ) -> bool:
+ """Report whether HTML text may replace PDF text already extracted.
+
+ With no PDF text in hand there is nothing to compare against, so the
+ ratio cannot help; an absolute floor stands in for it. Returning True
+ unconditionally here is what let a stub win on every text-first path.
+ """
+ if not pdf_text:
+ if len(html_text) >= MIN_STANDALONE_HTML_TEXT_LENGTH:
+ return True
+ logger.warning(
+ "arXiv HTML for {} yielded only {} characters and no PDF text "
+ "is available to compare against; below the {} character floor "
+ "for standalone HTML, so falling back to the PDF",
+ arxiv_id,
+ len(html_text),
+ MIN_STANDALONE_HTML_TEXT_LENGTH,
+ )
+ return False
+ if len(html_text) >= MIN_HTML_TO_PDF_TEXT_RATIO * len(pdf_text):
+ return True
+ logger.warning(
+ "arXiv HTML for {} yielded only {} characters against {} "
+ "characters of PDF text; keeping the PDF text",
+ arxiv_id,
+ len(html_text),
+ len(pdf_text),
+ )
+ return False
+
def _extract_arxiv_id(self, url: str) -> Optional[str]:
"""Extract arXiv ID from URL."""
- # Handle different arXiv URL formats
- patterns = [
- r"arxiv\.org/abs/(\d+\.\d+)(?:v\d+)?", # New format: 2301.12345 or 2301.12345v2
- r"arxiv\.org/pdf/(\d+\.\d+)(?:v\d+)?", # PDF URL with optional version
- r"arxiv\.org/abs/([a-z-]+/\d+)(?:v\d+)?", # Old format: cond-mat/0501234
- r"arxiv\.org/pdf/([a-z-]+/\d+)(?:v\d+)?", # Old PDF URL with optional version
- ]
-
- for pattern in patterns:
- match = re.search(pattern, url)
- if match:
- return match.group(1)
+ return extract_arxiv_id(url)
- return None
+ def get_metadata(self, url: str) -> dict[str, str]:
+ """Return canonical arXiv attribution without making a request."""
+ arxiv_id = self._extract_arxiv_id(url)
+ if arxiv_id is None:
+ return {}
+ return {"url": f"https://arxiv.org/abs/{arxiv_id}"}
def _fetch_from_arxiv_api(self, arxiv_id: str) -> Optional[str]:
"""Fetch abstract and metadata from arXiv API."""
- try:
- # Clean the ID for API query
- clean_id = arxiv_id.replace("/", "")
-
- # Query arXiv API
- api_url = f"https://export.arxiv.org/api/query?id_list={clean_id}"
- response = self.session.get(api_url, timeout=10)
+ engine_type = "arxiv_api"
+ session = self.session
+ if session is None:
+ self.rate_tracker.record_outcome(
+ engine_type=engine_type,
+ wait_time=0.0,
+ success=False,
+ retry_count=1,
+ error_type="SessionUnavailable",
+ )
+ return None
- if response.status_code == 200:
+ adaptive_wait = self.rate_tracker.apply_rate_limit(engine_type)
+ api_text: str | None = None
+ error_type: str | None = None
+ try:
+ with arxiv_api_request_gate():
+ response = session.get(
+ "https://export.arxiv.org/api/query",
+ params={"id_list": arxiv_id},
+ timeout=10,
+ allow_redirects=False,
+ )
+
+ if response.status_code != 200:
+ error_type = f"HTTP_{response.status_code}"
+ else:
# Parse the Atom feed response
# Use defusedxml to prevent XXE attacks
from defusedxml import ElementTree as ET
@@ -174,23 +458,42 @@ class ArxivDownloader(BaseDownloader):
# Find the entry
entry = root.find("atom:entry", ns)
+ if entry is not None:
+ entry_id = entry.find("atom:id", ns)
+ response_url = (
+ entry_id.text.strip()
+ if entry_id is not None and entry_id.text
+ else None
+ )
+ if (
+ response_url is None
+ or not self._is_matching_arxiv_paper_url(
+ response_url, arxiv_id
+ )
+ or not urlparse(response_url).path.startswith("/abs/")
+ ):
+ entry = None
if entry is not None:
# Extract text content
- text_parts = []
+ text_parts: list[str] = []
# Title
title = entry.find("atom:title", ns)
if title is not None and title.text:
- text_parts.append(f"Title: {title.text.strip()}")
+ title_text = title.text.strip()
+ if title_text:
+ text_parts.append(f"Title: {title_text}")
# Authors
authors = entry.findall("atom:author", ns)
if authors:
- author_names = []
+ author_names: list[str] = []
for author in authors:
name = author.find("atom:name", ns)
if name is not None and name.text:
- author_names.append(name.text.strip())
+ author_name = name.text.strip()
+ if author_name:
+ author_names.append(author_name)
if author_names:
text_parts.append(
f"Authors: {', '.join(author_names)}"
@@ -199,30 +502,49 @@ class ArxivDownloader(BaseDownloader):
# Abstract
summary = entry.find("atom:summary", ns)
if summary is not None and summary.text:
- text_parts.append(
- f"\nAbstract:\n{summary.text.strip()}"
- )
+ summary_text = summary.text.strip()
+ if summary_text:
+ text_parts.append(f"\nAbstract:\n{summary_text}")
# Categories
categories = entry.findall("atom:category", ns)
if categories:
- cat_terms = [
- cat.get("term")
- for cat in categories
- if cat.get("term")
- ]
+ cat_terms: list[str] = []
+ for category in categories:
+ term = category.get("term")
+ if term and term.strip():
+ cat_terms.append(term.strip())
if cat_terms:
text_parts.append(
f"\nCategories: {', '.join(cat_terms)}"
)
if text_parts:
- logger.info(
- f"Retrieved text content from arXiv API for {arxiv_id}"
- )
- return "\n".join(text_parts)
+ api_text = "\n".join(text_parts)
+
+ if api_text is None:
+ error_type = "UnusableFeed"
except Exception as e:
logger.debug(f"Failed to fetch from arXiv API: {e}")
-
+ error_type = type(e).__name__
+
+ if api_text is not None:
+ self.rate_tracker.record_outcome(
+ engine_type=engine_type,
+ wait_time=adaptive_wait,
+ success=True,
+ retry_count=1,
+ search_result_count=1,
+ )
+ logger.info(f"Retrieved text content from arXiv API for {arxiv_id}")
+ return api_text
+
+ self.rate_tracker.record_outcome(
+ engine_type=engine_type,
+ wait_time=adaptive_wait,
+ success=False,
+ retry_count=1,
+ error_type=error_type,
+ )
return None
diff --git a/src/local_deep_research/research_library/downloaders/extraction/pipeline.py b/src/local_deep_research/research_library/downloaders/extraction/pipeline.py
index f16f20e24d..45562f25bb 100644
--- a/src/local_deep_research/research_library/downloaders/extraction/pipeline.py
+++ b/src/local_deep_research/research_library/downloaders/extraction/pipeline.py
@@ -10,14 +10,17 @@ Used by HTMLDownloader, ContentFetcher, FullSearchResults, WaybackSearchEngine,
and any other code that needs clean text from a web page.
Academic URLs (arXiv, PubMed, bioRxiv, etc.) are automatically routed to
-specialized downloaders first, with the generic HTML pipeline as fallback.
+specialized downloaders first. Generic HTML runs only when that route permits it.
"""
-from typing import Any, Dict, List, Optional
+from importlib import import_module
+from typing import Any, Dict, List, NamedTuple, Optional
from bs4 import BeautifulSoup
from loguru import logger
+from local_deep_research.utilities.arxiv import is_arxiv_paper_url
+
from .trafilatura_extractor import TrafilaturaExtractor
from .readability_extractor import ReadabilityExtractor
from .justext_extractor import JustextExtractor
@@ -322,21 +325,34 @@ def extract_content_with_metadata(
}
-def _try_specialized_downloader(url: str, timeout: int = 30) -> Optional[str]:
+class _SpecializedResult(NamedTuple):
+ content: str | None = None
+ fallback_allowed: bool = True
+
+
+def _try_specialized_downloader(
+ url: str, timeout: int = 30
+) -> _SpecializedResult:
"""Try a specialized downloader (arXiv, PubMed, etc.) for the URL.
- Returns extracted text if a specialized downloader handles this URL
- and succeeds, or None to signal "fall back to generic HTML pipeline".
+ The result carries extracted text and whether generic HTML fallback is safe.
"""
+ # Terminal ownership follows the paper identifier, not the host: a
+ # non-paper arXiv page has no canonical downloader source, so denying it
+ # the generic fallback would return nothing at all.
+ arxiv_url = is_arxiv_paper_url(url)
+ failure = _SpecializedResult(fallback_allowed=not arxiv_url)
try:
from local_deep_research.content_fetcher.url_classifier import (
URLClassifier,
URLType,
)
except ImportError:
- return None
+ return failure
url_type = URLClassifier.classify(url)
+ arxiv_terminal = arxiv_url or url_type == URLType.ARXIV
+ failure = _SpecializedResult(fallback_allowed=not arxiv_terminal)
# Only academic URL types have specialized downloaders worth trying.
# HTML, DOI, PDF, INVALID fall through to the generic pipeline.
@@ -349,15 +365,25 @@ def _try_specialized_downloader(url: str, timeout: int = 30) -> Optional[str]:
URLType.MEDRXIV,
}
if url_type not in _SPECIALIZED_TYPES:
- return None
+ return failure
+
+ from ..base import BaseDownloader, ContentType
# Map URL type to downloader class (lazy imports to avoid circular deps)
- downloader = None
+ downloader: BaseDownloader | None = None
try:
if url_type == URLType.ARXIV:
- from ..arxiv import ArxivDownloader
-
- downloader = ArxivDownloader(timeout=timeout)
+ package = __package__
+ if package is None:
+ return failure
+ downloaders_package = package.rpartition(".")[0]
+ arxiv_module = import_module(f"{downloaders_package}.arxiv")
+ downloader_type = getattr(arxiv_module, "ArxivDownloader", None)
+ if not isinstance(downloader_type, type) or not issubclass(
+ downloader_type, BaseDownloader
+ ):
+ return failure
+ downloader = downloader_type(timeout=timeout)
elif url_type in (URLType.PUBMED, URLType.PMC):
from ..pubmed import PubMedDownloader
@@ -374,14 +400,12 @@ def _try_specialized_downloader(url: str, timeout: int = 30) -> Optional[str]:
logger.debug(
f"Pipeline: specialized downloader not available for {url_type.value}"
)
- return None
+ return failure
if not downloader:
- return None
+ return failure
try:
- from ..base import ContentType
-
result = downloader.download_with_result(url, ContentType.TEXT)
if result.is_success and result.content:
text = result.content.decode("utf-8", errors="replace")
@@ -390,7 +414,10 @@ def _try_specialized_downloader(url: str, timeout: int = 30) -> Optional[str]:
f"Pipeline: specialized downloader ({url_type.value}) "
f"returned {len(text)} chars for {url}"
)
- return text
+ return _SpecializedResult(
+ content=text,
+ fallback_allowed=not arxiv_terminal,
+ )
except Exception:
logger.debug(
f"Pipeline: specialized downloader failed for {url}",
@@ -402,12 +429,12 @@ def _try_specialized_downloader(url: str, timeout: int = 30) -> Optional[str]:
except Exception: # noqa: silent-exception
pass
- # Specialized downloader didn't produce content — fall back to HTML
- logger.debug(
- f"Pipeline: specialized downloader ({url_type.value}) returned "
- f"no content for {url}, falling back to HTML pipeline"
- )
- return None
+ if failure.fallback_allowed:
+ logger.debug(
+ f"Pipeline: specialized downloader ({url_type.value}) returned "
+ f"no content for {url}, falling back to HTML pipeline"
+ )
+ return failure
def fetch_and_extract(
@@ -419,10 +446,10 @@ def fetch_and_extract(
"""Fetch a URL and extract clean text content.
Pipeline:
- 1. Specialized downloader (arXiv PDF, PubMed API, etc.) if URL matches
+ 1. Specialized downloader (arXiv canonical sources, PubMed API, etc.)
2. Static HTTP fetch → Playwright fallback (if JS needed and
- ``enable_js_rendering`` is True) → trafilatura → readability →
- justext
+ permitted and ``enable_js_rendering`` is True) → trafilatura →
+ readability → justext
Args:
url: The URL to fetch.
@@ -441,9 +468,20 @@ def fetch_and_extract(
Extracted plain text, or None if fetch or extraction failed.
"""
# Try specialized downloader first (arXiv, PubMed, etc.)
- specialized = _try_specialized_downloader(url, timeout=timeout)
- if specialized:
- return specialized
+ try:
+ specialized = _try_specialized_downloader(url, timeout=timeout)
+ except Exception:
+ logger.debug(
+ f"Pipeline: specialized downloader error for {url}",
+ exc_info=True,
+ )
+ specialized = _SpecializedResult(
+ fallback_allowed=not is_arxiv_paper_url(url)
+ )
+ if specialized.content:
+ return specialized.content
+ if not specialized.fallback_allowed:
+ return None
# Generic HTML pipeline
from ..playwright_html import AutoHTMLDownloader
@@ -481,7 +519,7 @@ def batch_fetch_and_extract(
For each URL:
1. Try specialized downloader (arXiv, PubMed, etc.) if URL matches
- 2. Fall back to generic HTML pipeline (AutoHTMLDownloader)
+ 2. Use generic HTML only when the specialized route permits fallback
Uses a single AutoHTMLDownloader (and thus a single Playwright
browser if JS fallback is triggered) for the generic HTML URLs.
@@ -511,14 +549,20 @@ def batch_fetch_and_extract(
for url in urls:
try:
specialized = _try_specialized_downloader(url, timeout=timeout)
- if specialized:
- results[url] = specialized
+ if specialized.content:
+ results[url] = specialized.content
+ continue
+ if not specialized.fallback_allowed:
+ results[url] = None
continue
except Exception:
logger.debug(
f"Pipeline: specialized downloader error for {url}",
exc_info=True,
)
+ if is_arxiv_paper_url(url):
+ results[url] = None
+ continue
html_urls.append(url)
# Generic HTML pipeline for remaining URLs
diff --git a/src/local_deep_research/research_library/downloaders/html.py b/src/local_deep_research/research_library/downloaders/html.py
index dd509ba4d8..ec241783ab 100644
--- a/src/local_deep_research/research_library/downloaders/html.py
+++ b/src/local_deep_research/research_library/downloaders/html.py
@@ -16,6 +16,30 @@ from ...constants import BROWSER_USER_AGENT
from ...security import sanitize_error_for_client
+def _as_markdown_text(value: str) -> str:
+ """Collapse page-supplied metadata to a single line.
+
+ ``_format_extracted_content`` wraps the title in ``# `` and the
+ description in ``*``. Both are third-party strings -- for arXiv they now
+ reach stored text at character 0, ahead of the paper itself -- so a
+ newline in either would end the construct and hand the rest of the value
+ the document's own syntax. Collapsing whitespace keeps the value inside
+ the construct it was meant to fill.
+
+ Metacharacters are deliberately *not* escaped. What this produces is
+ stored as ``Document.text_content``, which is not markdown to every
+ consumer: the document viewer renders it as plain text in a
+ ``white-space: pre-wrap`` element (``document_text.html``), unified
+ search matches it by substring, and the RAG and notes services feed it
+ to embeddings and prompts verbatim. Backslashes written in here would
+ show up literally in all four and would break substring matches on the
+ characters escaped. Escaping belongs at the markdown sinks, and they
+ already do it -- the one that renders this text as markdown parses it
+ inline and passes the result through DOMPurify.
+ """
+ return " ".join(value.split())
+
+
class HTMLDownloader(BaseDownloader):
"""Downloader for HTML web pages - extracts clean text content."""
@@ -116,6 +140,17 @@ class HTMLDownloader(BaseDownloader):
def _fetch_html(self, url: str) -> Optional[str]:
"""Fetch raw HTML content from URL."""
+ return self._fetch_html_with_final_url(url)[0]
+
+ def _fetch_html_with_final_url(
+ self, url: str
+ ) -> 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 must
+ compare the returned URL themselves.
+ """
logger.debug(f"Static fetch: {url}")
domain = urlparse(url).netloc
engine_type = f"html_download_{domain}"
@@ -142,11 +177,11 @@ class HTMLDownloader(BaseDownloader):
retry_count=1,
search_result_count=1,
)
- return response.text
+ return response.text, response.url
logger.warning(
f"Unexpected content type for HTML download: {content_type}"
)
- return None
+ return None, None
logger.warning(f"HTTP {response.status_code} fetching {url}")
self.rate_tracker.record_outcome(
engine_type=engine_type,
@@ -155,7 +190,7 @@ class HTMLDownloader(BaseDownloader):
retry_count=1,
error_type=f"HTTP_{response.status_code}",
)
- return None
+ return None, None
except Exception as e:
logger.exception(f"Error fetching HTML from {url}")
@@ -166,7 +201,7 @@ class HTMLDownloader(BaseDownloader):
retry_count=1,
error_type=type(e).__name__,
)
- return None
+ return None, None
def _extract_content(self, html: str, url: str) -> Optional[Dict[str, Any]]:
"""Extract clean content and metadata from HTML.
@@ -202,11 +237,13 @@ class HTMLDownloader(BaseDownloader):
parts = []
if extracted.get("title"):
- parts.append(f"# {extracted['title']}")
+ parts.append(f"# {_as_markdown_text(str(extracted['title']))}")
parts.append("")
if extracted.get("description"):
- parts.append(f"*{extracted['description']}*")
+ parts.append(
+ f"*{_as_markdown_text(str(extracted['description']))}*"
+ )
parts.append("")
if extracted.get("url"):
diff --git a/src/local_deep_research/research_library/extraction_catalog.py b/src/local_deep_research/research_library/extraction_catalog.py
new file mode 100644
index 0000000000..f3355ef7b4
--- /dev/null
+++ b/src/local_deep_research/research_library/extraction_catalog.py
@@ -0,0 +1,39 @@
+"""Catalog identifiers for arXiv HTML-extracted text provenance.
+
+``LibraryDocument.extraction_method`` and ``.extraction_source``
+(``database/models/library.py``) are plain unconstrained strings, not
+SQLAlchemy ``Enum`` columns, so adding a new catalog value never changes
+the schema Alembic ships -- see the docstring on ``ExtractionMethod`` /
+``ExtractionSource`` in that file.
+
+The ``"html_extraction"`` / ``"arxiv_html"`` values ``DownloadService``
+persists for an HTML-extracted arXiv download (see
+``_arxiv_text_provenance`` in
+``research_library/services/download_service.py``) are defined here,
+outside ``database/models/``, rather than as new members on the
+pre-existing enums in ``library.py``. That keeps every file under
+``database/models/`` byte-identical to the merge base, which two tests
+enforce:
+
+* ``test_migration_chain_integrity.py::test_every_file_behind_the_alembic_metadata_is_unchanged_since_the_fork``
+* ``test_upgrade_from_pre_migration_install.py::test_pr_changes_no_orm_model``
+
+Both treat any edit to a file backing ``Base.metadata`` (or anything
+under ``database/models/``) as presumed schema drift, regardless of
+whether the specific edit actually changes a column -- so a value that
+does not need to live there should not.
+"""
+
+import enum
+
+
+class ExtractionMethodExtra(str, enum.Enum):
+ """Extraction-method catalog values added after the merge base."""
+
+ HTML_EXTRACTION = "html_extraction"
+
+
+class ExtractionSourceExtra(str, enum.Enum):
+ """Extraction-source catalog values added after the merge base."""
+
+ ARXIV_HTML = "arxiv_html"
diff --git a/src/local_deep_research/research_library/services/download_service.py b/src/local_deep_research/research_library/services/download_service.py
index d8f213db10..60fa4aa3a0 100644
--- a/src/local_deep_research/research_library/services/download_service.py
+++ b/src/local_deep_research/research_library/services/download_service.py
@@ -15,7 +15,7 @@ import time
import uuid
from datetime import datetime, UTC
from pathlib import Path
-from typing import Any, Dict, Optional, Tuple
+from typing import Any, Dict, Optional, Tuple, assert_never
from urllib.parse import urlparse
import requests
@@ -24,6 +24,7 @@ from sqlalchemy.orm import Session
import pdfplumber
from pypdf import PdfReader
+from ...utilities.arxiv import is_arxiv_paper_url
from ...utilities.type_utils import unwrap_setting
from ...constants import FILE_PATH_SENTINELS, FILE_PATH_TEXT_ONLY
from ...database.models.download_tracker import (
@@ -76,9 +77,29 @@ from ..downloaders import (
OpenAlexDownloader,
GenericDownloader,
)
+from ..downloaders.arxiv import ArxivTextSource
+from ..extraction_catalog import (
+ ExtractionMethodExtra,
+ ExtractionSourceExtra,
+)
from ...constants import DEFAULT_SEARCH_TOOL
+def _arxiv_text_provenance(source: ArxivTextSource) -> tuple[str, str]:
+ match source:
+ case ArxivTextSource.ARXIV_HTML:
+ return (
+ ExtractionMethodExtra.HTML_EXTRACTION.value,
+ ExtractionSourceExtra.ARXIV_HTML.value,
+ )
+ case ArxivTextSource.LOCAL_PDF:
+ return "pdf_extraction", "local_pdf"
+ case ArxivTextSource.ARXIV_API:
+ return "native_api", "arxiv_api"
+ case unreachable:
+ assert_never(unreachable)
+
+
class DownloadService:
"""Service for downloading and managing research PDFs."""
@@ -185,15 +206,21 @@ class DownloadService:
self._setup_directories()
# Initialize modular downloaders
- # DirectPDFDownloader first for efficiency with direct PDF links
# Get Semantic Scholar API key from settings
semantic_scholar_api_key = self.settings.get_setting(
"search.engine.web.semantic_scholar.api_key", ""
)
+ # ArxivDownloader precedes DirectPDFDownloader: for a paper URL it
+ # builds the canonical PDF URL rather than fetching whatever the
+ # input pointed at. It can only do that for URLs that name a paper,
+ # and can_handle now says so, so arXiv's legacy /ftp/ PDF layout --
+ # which yields no identifier -- still reaches DirectPDFDownloader
+ # instead of being claimed and skipped.
self.downloaders = [
- DirectPDFDownloader(timeout=30), # Handle direct PDF links first
+ ArxivDownloader(timeout=30),
+ DirectPDFDownloader(timeout=30),
SemanticScholarDownloader(
timeout=30,
api_key=semantic_scholar_api_key
@@ -203,7 +230,6 @@ class DownloadService:
OpenAlexDownloader(
timeout=30
), # OpenAlex with API lookup (no key needed)
- ArxivDownloader(timeout=30),
PubMedDownloader(timeout=30, rate_limit_delay=1.0),
BioRxivDownloader(timeout=30),
GenericDownloader(timeout=30), # Generic should be last (fallback)
@@ -421,7 +447,7 @@ class DownloadService:
Get text content for a research resource.
This will try to:
- 1. Fetch text directly from APIs if available
+ 1. Produce text through a source-specific downloader if available
2. Extract text from downloaded PDF if exists
3. Download PDF and extract text if not yet downloaded
@@ -791,7 +817,7 @@ class DownloadService:
try:
# Use modular downloaders with detailed skip reasons
pdf_content = None
- downloader_used = None
+ selected_downloader = None
skip_reason = None
status_code = None
@@ -803,7 +829,7 @@ class DownloadService:
result = downloader.download_with_result(
url, ContentType.PDF
)
- downloader_used = downloader.__class__.__name__
+ selected_downloader = downloader
if result.is_success and result.content:
pdf_content = result.content
@@ -813,11 +839,12 @@ class DownloadService:
skip_reason = result.skip_reason
status_code = result.status_code
logger.info(f"Download skipped: {skip_reason}")
- # Keep trying other downloaders unless it's the GenericDownloader
- if isinstance(downloader, GenericDownloader):
- break
+ if isinstance(
+ downloader, (ArxivDownloader, GenericDownloader)
+ ):
+ break
- if not downloader_used:
+ if selected_downloader is None:
logger.error(f"No downloader found for {url}")
skip_reason = "No compatible downloader available"
@@ -981,14 +1008,39 @@ class DownloadService:
else:
logger.info(f"Successfully extracted text from: {resource.url}")
- # Automatically extract and save text after successful PDF download
+ # Produce and save text only after the PDF has been stored.
try:
- logger.info(
- f"Extracting text from downloaded PDF for: {resource.title[:50]}"
- )
- text = self._extract_text_from_pdf(pdf_content)
+ 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
+ )
- if text:
+ if text_details is not None:
+ text, extraction_method, extraction_source = text_details
# Get the document ID we just created/updated
pdf_doc = get_document_for_resource(session, resource)
pdf_document_id = pdf_doc.id if pdf_doc else None
@@ -998,22 +1050,22 @@ class DownloadService:
resource=resource,
text=text,
session=session,
- extraction_method="pdf_extraction",
- extraction_source="local_pdf",
+ extraction_method=extraction_method,
+ extraction_source=extraction_source,
pdf_document_id=pdf_document_id,
)
logger.info(
- f"Successfully extracted and saved text for: {resource.title[:50]}"
+ f"Successfully produced and saved text for: {resource.title[:50]}"
)
else:
logger.warning(
- f"Text extraction returned empty text for: {resource.title[:50]}"
+ f"Text production returned empty text for: {resource.title[:50]}"
)
except Exception:
logger.exception(
- "Failed to extract text from PDF, but PDF download succeeded"
+ "Failed to produce text after PDF download, but PDF download succeeded"
)
- # Don't fail the entire download if text extraction fails
+ # Text production is best-effort after a successful PDF download.
return True, None, status_code
@@ -1128,7 +1180,16 @@ class DownloadService:
if result is not None:
return result
- # Try extracting from existing PDF
+ # 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.
+ result = self._try_arxiv_text_extraction(session, resource)
+ if result is not None:
+ self._record_retry_attempt(resource, result, session)
+ return result
+
+ # Try extracting from existing PDF (pure filesystem, no network)
result = self._try_existing_pdf_extraction(
session, resource, resource_id
)
@@ -1144,7 +1205,7 @@ class DownloadService:
)
return False, decision.reason
- # Try API text extraction
+ # Try source-specific direct text extraction
result = self._try_api_text_extraction(session, resource)
if result is not None:
self._record_retry_attempt(resource, result, session)
@@ -1313,6 +1374,110 @@ class DownloadService:
session.commit()
return True, None
+ def _try_arxiv_text_extraction(
+ self, session: Session, resource
+ ) -> Optional[Tuple[bool, Optional[str]]]:
+ """Produce text from canonical arXiv sources, or None to fall through.
+
+ None means "this path does not apply", never "this resource has no
+ text": 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).
+ """
+ url = resource.url or ""
+ if not is_arxiv_paper_url(url):
+ return None
+
+ if self.retry_manager:
+ decision = self.retry_manager.should_retry_resource(resource.id)
+ if not decision.can_retry:
+ logger.info(
+ "Skipping canonical arXiv text for resource {}: {}",
+ resource.id,
+ decision.reason,
+ )
+ return None
+
+ try:
+ downloader = self._get_downloader(url)
+ if not isinstance(downloader, ArxivDownloader):
+ return False, "No arXiv downloader available"
+
+ allowed, reason = self._check_url_against_policy(url)
+ if not allowed:
+ return False, f"egress_policy_denied:{reason}"
+
+ pdf_content: bytes | None = None
+ pdf_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")
+
+ if pdf_content is None:
+ arxiv_text = downloader.download_text_with_source(url)
+ else:
+ arxiv_text = downloader.download_text_with_source(
+ url,
+ pdf_content=pdf_content,
+ )
+ except Exception as exc:
+ safe_rollback(session, "_try_arxiv_text_extraction")
+ logger.exception("Canonical arXiv text extraction failed")
+ safe_error = sanitize_error_for_client(
+ f"Failed to extract arXiv text: {exc}"
+ )
+ return False, safe_error
+
+ if arxiv_text is None:
+ return False, "Could not retrieve arXiv text"
+
+ extraction_method, extraction_source = _arxiv_text_provenance(
+ arxiv_text.source
+ )
+ try:
+ _ = self._save_text_with_db(
+ resource,
+ arxiv_text.text,
+ session,
+ extraction_method=extraction_method,
+ extraction_source=extraction_source,
+ pdf_document_id=pdf_document_id,
+ )
+ session.commit()
+ except Exception as exc:
+ safe_rollback(session, "_try_arxiv_text_extraction")
+ logger.exception("Failed to save canonical arXiv text")
+ safe_error = sanitize_error_for_client(
+ f"Failed to save 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]]]:
@@ -1384,7 +1549,7 @@ class DownloadService:
def _try_api_text_extraction(
self, session, resource
) -> Optional[Tuple[bool, Optional[str]]]:
- """Try direct API text extraction."""
+ """Try source-specific direct text extraction."""
logger.info(
f"Attempting direct API text extraction from: {resource.url}"
)
@@ -1404,36 +1569,44 @@ class DownloadService:
)
return False, f"egress_policy_denied:{reason}"
- result = downloader.download_with_result(resource.url, ContentType.TEXT)
-
- if not result.is_success or not result.content:
- return None
-
- # Decode text content
- text = (
- result.content.decode("utf-8", errors="ignore")
- if isinstance(result.content, bytes)
- else result.content
- )
-
- # Determine extraction source
- extraction_source = "unknown"
if isinstance(downloader, ArxivDownloader):
- extraction_source = "arxiv_api"
- elif isinstance(downloader, PubMedDownloader):
- extraction_source = "pubmed_api"
+ arxiv_text = downloader.download_text_with_source(resource.url)
+ if arxiv_text is None:
+ return None
+ text = arxiv_text.text
+ extraction_method, extraction_source = _arxiv_text_provenance(
+ arxiv_text.source
+ )
+ else:
+ result = downloader.download_with_result(
+ resource.url, ContentType.TEXT
+ )
+ if not result.is_success or not result.content:
+ return None
+
+ text = (
+ result.content.decode("utf-8", errors="ignore")
+ if isinstance(result.content, bytes)
+ else result.content
+ )
+ extraction_method = "native_api"
+ extraction_source = (
+ "pubmed_api"
+ if isinstance(downloader, PubMedDownloader)
+ else "unknown"
+ )
try:
self._save_text_with_db(
resource,
text,
session,
- extraction_method="native_api",
+ extraction_method=extraction_method,
extraction_source=extraction_source,
)
session.commit()
logger.info(
- f"✓ SUCCESS: Got text from {extraction_source.upper()} API for '{resource.title[:50]}...'"
+ f"✓ SUCCESS: Got text from {extraction_source.upper()} for '{resource.title[:50]}...'"
)
return True, None
except Exception as e:
@@ -1455,7 +1628,7 @@ class DownloadService:
) -> Tuple[bool, Optional[str]]:
"""Fallback: Download PDF to memory and extract text."""
logger.info(
- f"API text extraction failed, falling back to in-memory PDF download for: {resource.url}"
+ f"Direct text extraction unavailable; trying in-memory PDF for: {resource.url}"
)
downloader = self._get_downloader(resource.url)
@@ -1893,7 +2066,7 @@ class DownloadService:
session: Session,
extraction_method: str,
extraction_source: str,
- pdf_document_id: Optional[int] = None,
+ pdf_document_id: str | None = None,
) -> Optional[str]:
"""
Save extracted text to encrypted database.
@@ -1913,6 +2086,15 @@ class DownloadService:
# Calculate text metadata for database
word_count = len(text.split())
character_count = len(text)
+ if extraction_method in {"native_api", "html_extraction"}:
+ extraction_quality = "high"
+ elif extraction_method == "pdfplumber" or (
+ extraction_method == "pdf_extraction"
+ and extraction_source == "pdfplumber"
+ ):
+ extraction_quality = "medium"
+ else:
+ extraction_quality = "low"
# Find the document by pdf_document_id or resource_id
doc = None
@@ -1944,16 +2126,7 @@ class DownloadService:
).hexdigest()
doc.processed_at = datetime.now(UTC)
- # Set quality based on method
- if extraction_method == "native_api":
- doc.extraction_quality = "high"
- elif (
- extraction_method == "pdf_extraction"
- and extraction_source == "pdfplumber"
- ):
- doc.extraction_quality = "medium"
- else:
- doc.extraction_quality = "low"
+ doc.extraction_quality = extraction_quality
logger.debug(
f"Updated document {doc.id} with extracted text ({word_count} words)"
@@ -2026,9 +2199,7 @@ class DownloadService:
word_count=word_count,
extraction_method=extraction_method,
extraction_source=extraction_source,
- extraction_quality="high"
- if extraction_method == "native_api"
- else "medium",
+ extraction_quality=extraction_quality,
status=DocumentStatus.COMPLETED,
processed_at=datetime.now(UTC),
)
diff --git a/src/local_deep_research/utilities/arxiv.py b/src/local_deep_research/utilities/arxiv.py
new file mode 100644
index 0000000000..82c4f7db1b
--- /dev/null
+++ b/src/local_deep_research/utilities/arxiv.py
@@ -0,0 +1,104 @@
+"""Shared arXiv URL identifier parsing."""
+
+import re
+from typing import Final, NewType
+from urllib.parse import urlparse
+
+ArxivId = NewType("ArxivId", str)
+
+_ID_PATTERN: Final = (
+ r"(?:\d{4}\.\d{4,5}|[A-Za-z]+(?:-[A-Za-z]+)*(?:\.[A-Za-z]+)?/\d{7})"
+ r"(?:v\d+)?"
+)
+_ARXIV_PATH: Final = re.compile(
+ rf"^/(?:abs|pdf|html)/(?P<identifier>{_ID_PATTERN})(?:\.pdf)?/?$",
+ re.IGNORECASE,
+)
+_AR5IV_DIRECT_PATH: Final = re.compile(
+ rf"^/(?P<identifier>{_ID_PATTERN})(?:\.pdf)?/?$",
+ re.IGNORECASE,
+)
+_ARXIV_FAMILY_DOMAINS: Final = ("arxiv.org", "ar5iv.org")
+
+
+def _normalize_http_hostname(scheme: str, hostname: str | None) -> str | None:
+ if scheme.lower() not in {"http", "https"} or hostname is None:
+ return None
+ return hostname.lower().rstrip(".")
+
+
+def _normalized_http_hostname(url: str) -> str | None:
+ try:
+ parsed = urlparse(url)
+ _ = parsed.port
+ return _normalize_http_hostname(parsed.scheme, parsed.hostname)
+ except ValueError:
+ return None
+
+
+def _is_host_family(hostname: str, domain: str) -> bool:
+ return hostname == domain or hostname.endswith(f".{domain}")
+
+
+def is_arxiv_family_url(url: str) -> bool:
+ """Return whether an HTTP(S) URL is on an arXiv-family host.
+
+ This is host membership only, and the family includes the bare
+ ``ar5iv.org`` domain, which arXiv does not serve. That makes it the right
+ gate for deciding whether a *supplied* URL is worth parsing for an
+ identifier (:func:`extract_arxiv_id` uses it for exactly that) and the
+ wrong one for deciding whether a *response* came from arXiv: see
+ ``ArxivDownloader._is_matching_arxiv_paper_url``, which deliberately
+ tests the narrower ``.arxiv.org`` boundary so ``ar5iv.org`` can be an
+ input identifier without ever being treated as authoritative.
+ """
+ hostname = _normalized_http_hostname(url)
+ return hostname is not None and any(
+ _is_host_family(hostname, domain) for domain in _ARXIV_FAMILY_DOMAINS
+ )
+
+
+def is_ar5iv_url(url: str) -> bool:
+ """Return whether an HTTP(S) URL targets the ar5iv host family."""
+ hostname = _normalized_http_hostname(url)
+ return hostname is not None and _is_host_family(hostname, "ar5iv.org")
+
+
+def is_arxiv_paper_url(url: str) -> bool:
+ """Return whether an HTTP(S) URL identifies one specific arXiv paper.
+
+ Host membership alone (:func:`is_arxiv_family_url`) is not enough to hand
+ a URL to the arXiv downloader: ``arxiv.org/list/cs.AI/recent``,
+ ``info.arxiv.org/help/...`` and ``arxiv.org/ftp/.../2301.12345.pdf`` are
+ all on the family hosts but carry no identifier the downloader can act
+ on, so they belong to the generic pipelines. Use this predicate for every
+ routing and ownership decision. Response-URL trust is a separate and
+ narrower question, answered by
+ ``ArxivDownloader._is_matching_arxiv_paper_url`` rather than by either
+ predicate here.
+ """
+ return extract_arxiv_id(url) is not None
+
+
+def extract_arxiv_id(url: str) -> ArxivId | None:
+ """Return a version-preserving ID from a supported arXiv-family URL."""
+ try:
+ parsed = urlparse(url)
+ _ = parsed.port
+ hostname = _normalize_http_hostname(parsed.scheme, parsed.hostname)
+ except ValueError:
+ return None
+
+ if hostname is None:
+ return None
+
+ if not is_arxiv_family_url(url):
+ return None
+ is_ar5iv = is_ar5iv_url(url)
+
+ match = _ARXIV_PATH.fullmatch(parsed.path)
+ if match is None and is_ar5iv:
+ match = _AR5IV_DIRECT_PATH.fullmatch(parsed.path)
+ if match is None:
+ return None
+ return ArxivId(match.group("identifier"))
diff --git a/src/local_deep_research/utilities/arxiv_api.py b/src/local_deep_research/utilities/arxiv_api.py
new file mode 100644
index 0000000000..c49486f76d
--- /dev/null
+++ b/src/local_deep_research/utilities/arxiv_api.py
@@ -0,0 +1,244 @@
+"""Shared arXiv API transport policy (issue #4783).
+
+Sole owner of the arXiv API request policy: every legacy arXiv API query
+request must traverse one process-wide, monotonic, at least three-second
+single-flight gate and travel through a :class:`SafeSession` with a pinned
+timeout and redirects disabled.
+"""
+
+from __future__ import annotations
+
+import threading
+import time
+from collections.abc import Callable, Iterable, Sequence
+from contextlib import contextmanager
+from dataclasses import dataclass
+from datetime import datetime
+from enum import StrEnum
+from typing import (
+ TYPE_CHECKING,
+ Final,
+ Protocol,
+ TypeAlias,
+ assert_never,
+ override,
+)
+
+import arxiv
+from requests import PreparedRequest
+
+from ..security import SafeSession
+from .resource_utils import safe_close
+
+if TYPE_CHECKING:
+ from collections.abc import Generator
+
+ from requests import Response
+
+# arXiv API Terms of Use: one connection at a time, with at least three
+# seconds between request starts
+# (https://info.arxiv.org/help/api/tou.html). This gate is intentionally
+# process-local: it serializes request starts within a single LDR process
+# only and provides no machine-wide enforcement. Deployments running
+# multiple LDR processes must coordinate those processes externally.
+_ARXIV_API_REQUEST_INTERVAL_SECONDS: Final = 3.0
+_arxiv_api_request_lock = threading.Lock()
+_last_request_started_at: float | None = None
+_monotonic = time.monotonic
+_sleep = time.sleep
+
+_ARXIV_API_TIMEOUT_SECONDS: Final = 10
+
+
+class ArxivSortCriterion(StrEnum):
+ RELEVANCE = "relevance"
+ LAST_UPDATED_DATE = "lastUpdatedDate"
+ SUBMITTED_DATE = "submittedDate"
+
+
+class ArxivSortOrder(StrEnum):
+ ASCENDING = "ascending"
+ DESCENDING = "descending"
+
+
+@dataclass(frozen=True, slots=True)
+class ArxivQueryRequest:
+ query: str
+ max_results: int
+ sort_by: ArxivSortCriterion = ArxivSortCriterion.RELEVANCE
+ sort_order: ArxivSortOrder = ArxivSortOrder.DESCENDING
+
+
+@dataclass(frozen=True, slots=True)
+class ArxivIdRequest:
+ arxiv_id: str
+
+
+type ArxivRequest = ArxivQueryRequest | ArxivIdRequest
+
+
+class ArxivAuthor(Protocol):
+ name: str
+
+
+class ArxivPaper(Protocol):
+ entry_id: str
+ title: str
+ summary: str
+ published: datetime
+ updated: datetime
+ categories: list[str]
+ comment: str | None
+ doi: str | None
+ journal_ref: str | None
+
+ @property
+ def 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,
+ ArxivSortCriterion.LAST_UPDATED_DATE: arxiv.SortCriterion.LastUpdatedDate,
+ ArxivSortCriterion.SUBMITTED_DATE: arxiv.SortCriterion.SubmittedDate,
+}
+_SORT_ORDERS: Final = {
+ ArxivSortOrder.ASCENDING: arxiv.SortOrder.Ascending,
+ ArxivSortOrder.DESCENDING: arxiv.SortOrder.Descending,
+}
+
+
+class _Readable(Protocol):
+ def read(self, length: int = ..., /) -> str | bytes: ...
+
+
+class _ItemSource(Protocol):
+ def items(self) -> Iterable[tuple[_GetArgument, _GetArgument]]: ...
+
+
+_GetArgument: TypeAlias = (
+ None
+ | bool
+ | int
+ | float
+ | str
+ | bytes
+ | PreparedRequest
+ | Iterable["_GetArgument"]
+ | _Readable
+ | _ItemSource
+ | Callable[..., "_GetArgument"]
+)
+
+
+@contextmanager
+def arxiv_api_request_gate() -> Generator[None, None, None]:
+ """NOT REENTRANT -- never enter this from code that may already
+ be running under the gate. The lock is a plain threading.Lock held
+ across both the sleep and the request body, so a nested entry
+ deadlocks silently rather than raising. _GatedArxivSession.get()
+ enters it, so anything handed that session as its transport must
+ not wrap its own call in the gate.
+
+ Run one arXiv API request start under the process-wide policy gate.
+
+ Entering blocks until at least ``_ARXIV_API_REQUEST_INTERVAL_SECONDS``
+ monotonic seconds have passed since the previous start, then stamps the
+ new start while holding the single-flight lock across the whole body.
+ Failed starts still count for spacing, and the lock is always released.
+ """
+ global _last_request_started_at
+ with _arxiv_api_request_lock:
+ while _last_request_started_at is not None:
+ remaining = (
+ _last_request_started_at
+ + _ARXIV_API_REQUEST_INTERVAL_SECONDS
+ - _monotonic()
+ )
+ if remaining <= 0:
+ break
+ _sleep(remaining)
+ _last_request_started_at = _monotonic()
+ yield
+
+
+class _GatedArxivSession(SafeSession):
+ """SafeSession routing arXiv API wire calls through the shared gate."""
+
+ @override
+ def get(
+ self,
+ url: str | bytes,
+ params: _GetArgument = None,
+ **kwargs: _GetArgument,
+ ) -> Response:
+ request_kwargs: dict[str, _GetArgument] = {
+ **kwargs,
+ "timeout": _ARXIV_API_TIMEOUT_SECONDS,
+ "allow_redirects": False,
+ }
+ match url:
+ case str():
+ request_url = url
+ case bytes():
+ request_url = url.decode()
+ case unreachable:
+ assert_never(unreachable)
+ with arxiv_api_request_gate():
+ return super().request(
+ "GET", request_url, params=params, **request_kwargs
+ )
+
+
+@contextmanager
+def _policy_arxiv_client(
+ *, page_size: int | None = None
+) -> Generator[arxiv.Client, None, None]:
+ """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
+ session 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_size
+ client = arxiv.Client(**constructor_kwargs)
+ discarded_session = client._session
+ safe_close(discarded_session, "discarded arXiv client session")
+ adapted_session = _GatedArxivSession()
+ client._session = adapted_session
+ try:
+ yield client
+ finally:
+ safe_close(adapted_session, "adapted arXiv client session")
+
+
+def fetch_arxiv_results(request: ArxivRequest) -> list[ArxivPaper]:
+ """Fetch and materialize one typed arXiv request under shared policy."""
+ match request:
+ case ArxivQueryRequest():
+ search = arxiv.Search(
+ query=request.query,
+ max_results=request.max_results,
+ sort_by=_SORT_CRITERIA[request.sort_by],
+ sort_order=_SORT_ORDERS[request.sort_order],
+ )
+ with _policy_arxiv_client(page_size=request.max_results) as client:
+ return list[ArxivPaper](client.results(search))
+ case ArxivIdRequest():
+ search = arxiv.Search(id_list=[request.arxiv_id], max_results=1)
+ with _policy_arxiv_client() as client:
+ return list[ArxivPaper](client.results(search))
+ case unreachable:
+ assert_never(unreachable)
diff --git a/src/local_deep_research/utilities/citation_normalizer.py b/src/local_deep_research/utilities/citation_normalizer.py
index 3c3d6b665e..f5476d728c 100644
--- a/src/local_deep_research/utilities/citation_normalizer.py
+++ b/src/local_deep_research/utilities/citation_normalizer.py
@@ -9,6 +9,8 @@ import re
from datetime import date
from typing import Any, Optional
+from .arxiv import extract_arxiv_id as extract_arxiv_id_from_url
+
__all__ = [
"normalize_citation",
@@ -199,17 +201,7 @@ def _extract_arxiv_id(source: dict) -> Optional[str]:
return arxiv_id
url = source.get("link", "") or source.get("url", "")
- # Old-style (pre-Apr 2007): archive(.subject-class)?/YYMMNNN, e.g.
- # cond-mat/0501001, math.AG/0601001, hep-th/9802150.
- # New-style: YYMM.NNNN or YYMM.NNNNN (5-digit seq from 2015 onwards),
- # with optional vN version suffix, e.g. 2501.12345, 0704.0001v2.
- match = re.search(
- r"arxiv\.org/abs/((?:[a-z-]+(?:\.[A-Z]+)?/\d{7}|\d{4}\.\d{4,5})(?:v\d+)?)",
- url,
- )
- if match:
- return match.group(1)
- return None
+ return extract_arxiv_id_from_url(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/full_search.py b/src/local_deep_research/web_search_engines/engines/full_search.py
index aaf7f44ef9..e53c0cc23e 100644
--- a/src/local_deep_research/web_search_engines/engines/full_search.py
+++ b/src/local_deep_research/web_search_engines/engines/full_search.py
@@ -162,7 +162,10 @@ class FullSearchResults:
return filtered_results
# Fetch and extract all pages — specialized downloaders (arXiv,
- # PubMed, etc.) are tried first, with HTML crawling as fallback.
+ # PubMed, etc.) are tried first, with HTML crawling as fallback for
+ # every type but arXiv paper URLs, which their downloader owns
+ # outright: for those a failure is terminal and yields no content.
+ # Other arXiv-host pages are not owned and do crawl.
url_to_content = batch_fetch_and_extract(
safe_urls,
language=self.language,
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.py
index 06f42cff84..4cc2bd6a5b 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
@@ -4,7 +4,6 @@ import uuid
from pathlib import Path
from typing import Any, Dict, List, Optional
-import arxiv
from langchain_core.language_models import BaseLLM
from requests.exceptions import RequestException
@@ -17,6 +16,14 @@ from ...security.directory_creation import (
)
from ...security.safe_requests import DEFAULT_TIMEOUT, MAX_RESPONSE_SIZE
from ...security.secure_logging import logger
+from ...utilities.arxiv_api import (
+ ArxivIdRequest,
+ ArxivPaper,
+ ArxivQueryRequest,
+ ArxivSortCriterion,
+ ArxivSortOrder,
+ fetch_arxiv_results,
+)
from ..rate_limiting import RateLimitError
from ..search_engine_base import BaseSearchEngine, Exposure, Sensitivity
@@ -94,19 +101,18 @@ class ArXivSearchEngine(BaseSearchEngine):
self.download_dir = download_dir
self.max_full_text = max_full_text
- # Map sort parameters to arxiv package parameters
self.sort_criteria = {
- "relevance": arxiv.SortCriterion.Relevance,
- "lastUpdatedDate": arxiv.SortCriterion.LastUpdatedDate,
- "submittedDate": arxiv.SortCriterion.SubmittedDate,
+ "relevance": ArxivSortCriterion.RELEVANCE,
+ "lastUpdatedDate": ArxivSortCriterion.LAST_UPDATED_DATE,
+ "submittedDate": ArxivSortCriterion.SUBMITTED_DATE,
}
self.sort_directions = {
- "ascending": arxiv.SortOrder.Ascending,
- "descending": arxiv.SortOrder.Descending,
+ "ascending": ArxivSortOrder.ASCENDING,
+ "descending": ArxivSortOrder.DESCENDING,
}
- def _get_search_results(self, query: str) -> List[Any]:
+ def _get_search_results(self, query: str) -> list[ArxivPaper]:
"""
Helper method to get search results from arXiv API.
@@ -118,17 +124,13 @@ class ArXivSearchEngine(BaseSearchEngine):
"""
# Configure the search client
sort_criteria = self.sort_criteria.get(
- self.sort_by, arxiv.SortCriterion.Relevance
+ self.sort_by, ArxivSortCriterion.RELEVANCE
)
sort_order = self.sort_directions.get(
- self.sort_order, arxiv.SortOrder.Descending
+ self.sort_order, ArxivSortOrder.DESCENDING
)
- # Create the search client
- client = arxiv.Client(page_size=self.max_results)
-
- # Create the search query
- search = arxiv.Search(
+ request = ArxivQueryRequest(
query=query,
max_results=self.max_results,
sort_by=sort_criteria,
@@ -140,8 +142,7 @@ class ArXivSearchEngine(BaseSearchEngine):
self.engine_type
)
- # Get the search results
- return list(client.results(search))
+ return fetch_arxiv_results(request)
@staticmethod
def _validated_arxiv_id(paper: Any) -> Optional[str]:
@@ -182,12 +183,9 @@ class ArXivSearchEngine(BaseSearchEngine):
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. This is narrower than "the same session as the rest of
- the arXiv integration": the metadata queries this engine makes
- elsewhere (``arxiv.Client()`` in ``_get_search_results`` and
- ``get_paper_details``) still go through the ``arxiv`` package's own
- bare ``requests.Session()`` — unvalidated and untimed. Gating those
- too is out of scope here.
+ 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``
@@ -736,19 +734,12 @@ class ArXivSearchEngine(BaseSearchEngine):
Dictionary with paper information
"""
try:
- # Create the search client
- client = arxiv.Client()
-
- # Search for the specific paper
- search = arxiv.Search(id_list=[arxiv_id], max_results=1)
-
# Apply rate limiting before fetching paper by ID
self._last_wait_time = self.rate_tracker.apply_rate_limit(
self.engine_type
)
- # Get the paper
- papers = list(client.results(search))
+ papers = fetch_arxiv_results(ArxivIdRequest(arxiv_id=arxiv_id))
if not papers:
return {}
diff --git a/tests/benchmarks/evaluators/arxiv_optimization/benchmark_arxiv_query_optimization.py b/tests/benchmarks/evaluators/arxiv_optimization/benchmark_arxiv_query_optimization.py
index b3ec077a0e..f0211b7c4d 100644
--- a/tests/benchmarks/evaluators/arxiv_optimization/benchmark_arxiv_query_optimization.py
+++ b/tests/benchmarks/evaluators/arxiv_optimization/benchmark_arxiv_query_optimization.py
@@ -282,9 +282,9 @@ def search_arxiv(query: str, max_results: int = 5) -> list[dict[str, Any]]:
"""
Run a search against arXiv and return the top results.
- Uses the arxiv library directly (already a dependency of LDR) to avoid
- needing the full LDR settings/database context that ArXivSearchEngine
- requires when running inside the server.
+ Uses LDR's shared typed arXiv API without requiring the full
+ settings/database context needed to construct ArXivSearchEngine inside
+ the server.
Args:
query: The search query (raw or optimized)
@@ -294,17 +294,14 @@ def search_arxiv(query: str, max_results: int = 5) -> list[dict[str, Any]]:
List of dicts with title, authors, categories, and abstract snippet
"""
try:
- import arxiv
-
- client = arxiv.Client(page_size=max_results)
- search = arxiv.Search(
- query=query,
- max_results=max_results,
- sort_by=arxiv.SortCriterion.Relevance,
- sort_order=arxiv.SortOrder.Descending,
+ from local_deep_research.utilities.arxiv_api import (
+ ArxivQueryRequest,
+ fetch_arxiv_results,
)
- papers = list(client.results(search))
+ papers = fetch_arxiv_results(
+ ArxivQueryRequest(query=query, max_results=max_results)
+ )
results = []
for paper in papers[:max_results]:
diff --git a/tests/content_fetcher/test_fetcher.py b/tests/content_fetcher/test_fetcher.py
index 6ba110dbd3..7d8db47571 100644
--- a/tests/content_fetcher/test_fetcher.py
+++ b/tests/content_fetcher/test_fetcher.py
@@ -135,6 +135,71 @@ class TestContentFetcherFetch:
assert result["status"] == "error"
assert "not found" in result["error"].lower()
+ @pytest.mark.parametrize(
+ "url",
+ (
+ "https://AR5IV.ORG./2301.12345v2",
+ "https://ARXIV.ORG./abs/2301.12345",
+ "https://EXPORT.ARXIV.ORG./abs/cond-mat/0501001",
+ ),
+ )
+ def test_arxiv_paper_url_uses_terminal_downloader(self, url):
+ # Given a paper URL on an owned host and a failing specialist
+ fetcher = ContentFetcher()
+ arxiv_downloader = MagicMock()
+ arxiv_downloader.download_with_result.return_value = DownloadResult(
+ skip_reason="Invalid arXiv URL - could not extract article ID"
+ )
+
+ with (
+ patch(
+ "local_deep_research.content_fetcher.fetcher.policy_aware_validate_url",
+ return_value=True,
+ ),
+ patch.object(
+ fetcher,
+ "_get_downloader",
+ return_value=arxiv_downloader,
+ ) as get_downloader,
+ ):
+ # When content fetching routes the URL
+ result = fetcher.fetch(url)
+
+ # Then arXiv owns the failure and generic HTML is never selected
+ assert result["status"] == "error"
+ get_downloader.assert_called_once_with(URLType.ARXIV)
+ arxiv_downloader.download_with_result.assert_called_once()
+
+ @pytest.mark.parametrize(
+ "url",
+ (
+ "https://AR5IV.ORG./2301.12345v2",
+ "https://ARXIV.ORG./pdf/2301.12345v2",
+ ),
+ )
+ def test_arxiv_paper_import_failure_does_not_use_html(self, url):
+ # Given an unavailable arXiv downloader for an owned paper URL
+ fetcher = ContentFetcher()
+
+ with (
+ patch(
+ "local_deep_research.content_fetcher.fetcher.policy_aware_validate_url",
+ return_value=True,
+ ),
+ patch.object(
+ fetcher,
+ "_get_downloader",
+ return_value=None,
+ ) as get_downloader,
+ ):
+ # When content fetching attempts downloader selection
+ result = fetcher.fetch(url)
+
+ # Then failure is terminal without a generic HTML lookup
+ assert result["status"] == "error"
+ assert result["error"] == "No suitable downloader available"
+ get_downloader.assert_called_once_with(URLType.ARXIV)
+
@patch(
"local_deep_research.content_fetcher.fetcher.ContentFetcher._get_downloader"
)
@@ -255,6 +320,23 @@ class TestContentFetcherGetURLInfo:
class TestContentFetcherURLTypeRouting:
"""Test that URLs are routed to correct downloaders."""
+ @pytest.mark.parametrize(
+ ("url", "expected_type"),
+ (
+ ("https://AR5IV.ORG./2301.12345v2", "arxiv"),
+ ("https://AR5IV.ORG./not-an-arxiv-id", "html"),
+ ("https://ar5iv.org.example.com./2301.12345", "html"),
+ ),
+ )
+ def test_trailing_dot_ar5iv_routing_follows_the_paper_identifier(
+ self, url, expected_type
+ ):
+ fetcher = ContentFetcher()
+
+ info = fetcher.get_url_info(url)
+
+ assert info["url_type"] == expected_type
+
def test_arxiv_routing(self):
"""Test arXiv URLs are detected correctly."""
fetcher = ContentFetcher()
diff --git a/tests/content_fetcher/test_fetcher_coverage.py b/tests/content_fetcher/test_fetcher_coverage.py
index 770d373637..dc1f1538a4 100644
--- a/tests/content_fetcher/test_fetcher_coverage.py
+++ b/tests/content_fetcher/test_fetcher_coverage.py
@@ -806,10 +806,7 @@ class TestHtmlFallback:
return_value=True,
)
@patch("local_deep_research.content_fetcher.fetcher.URLClassifier")
- def test_specialized_fails_html_fallback_succeeds(
- self, classifier_mock, validate_mock
- ):
- """When ArXiv downloader fails, HTML fallback returns content."""
+ def test_arxiv_failure_is_terminal(self, classifier_mock, validate_mock):
classifier_mock.classify.return_value = URLType.ARXIV
classifier_mock.get_source_name.return_value = "arXiv"
@@ -830,9 +827,34 @@ class TestHtmlFallback:
fetcher._downloaders[URLType.ARXIV] = mock_arxiv
fetcher._downloaders[URLType.HTML] = mock_html
- result = fetcher.fetch("https://arxiv.org/abs/2301.12345")
- assert result["status"] == "success"
- assert "arXiv abstract content" in result["content"]
+ result = fetcher.fetch("https://ar5iv.org/2301.12345v2")
+ assert result["status"] == "error"
+ assert result["error"] == "PDF unavailable"
+ mock_html.download_with_result.assert_not_called()
+
+ @patch(
+ "local_deep_research.content_fetcher.fetcher.policy_aware_validate_url",
+ return_value=True,
+ )
+ @patch("local_deep_research.content_fetcher.fetcher.URLClassifier")
+ def test_missing_arxiv_downloader_is_terminal(
+ self, classifier_mock, validate_mock
+ ):
+ # Given an accepted ar5iv URL whose specialized downloader is unavailable
+ classifier_mock.classify.return_value = URLType.ARXIV
+ classifier_mock.get_source_name.return_value = "arXiv"
+ fetcher = ContentFetcher()
+
+ # When fetching the URL
+ with patch.object(
+ fetcher, "_get_downloader", return_value=None
+ ) as get_dl:
+ result = fetcher.fetch("https://ar5iv.org/math.AG/0601001v3")
+
+ # Then no generic HTML downloader is requested
+ assert result["status"] == "error"
+ assert result["error"] == "No suitable downloader available"
+ get_dl.assert_called_once_with(URLType.ARXIV)
@patch(
"local_deep_research.content_fetcher.fetcher.policy_aware_validate_url",
diff --git a/tests/content_fetcher/test_url_classifier.py b/tests/content_fetcher/test_url_classifier.py
index cb6fa034aa..3985b9bb8e 100644
--- a/tests/content_fetcher/test_url_classifier.py
+++ b/tests/content_fetcher/test_url_classifier.py
@@ -2,10 +2,62 @@
Tests for URL classifier.
"""
+import pytest
+
from local_deep_research.content_fetcher.url_classifier import (
URLClassifier,
URLType,
)
+from local_deep_research.utilities import arxiv as arxiv_utils
+
+
+class TestArxivFamilyURL:
+ @pytest.mark.parametrize(
+ "url",
+ (
+ "https://ARXIV.ORG./not-an-arxiv-id",
+ "http://export.ArXiV.OrG./any/path",
+ "https://AR5IV.ORG./not-an-arxiv-id",
+ "https://render.Ar5iV.OrG./any/path",
+ ),
+ )
+ def test_http_hosts_are_owned_independently_of_path(self, url):
+ # Given an HTTP(S) URL on an exact or subdomain arXiv-family host
+ # When ownership is checked
+ owned = arxiv_utils.is_arxiv_family_url(url)
+
+ # Then case, DNS trailing dots, and path grammar do not affect ownership
+ assert owned is True
+
+ @pytest.mark.parametrize(
+ "url",
+ (
+ "ftp://arxiv.org/2301.12345",
+ "https://arxiv.org.example.com/not-an-arxiv-id",
+ "https://ar5iv.org.example.com./not-an-arxiv-id",
+ "https://example.com/path/arxiv.org/not-an-arxiv-id",
+ "https:///arxiv.org/not-an-arxiv-id",
+ "https://[arxiv.org",
+ "https://arxiv.org:not-a-port/not-an-arxiv-id",
+ ),
+ )
+ def test_non_http_malformed_and_lookalike_urls_are_unowned(self, url):
+ # Given an unsupported, malformed, or lookalike URL
+ # When ownership is checked
+ owned = arxiv_utils.is_arxiv_family_url(url)
+
+ # Then it is not claimed by the arXiv-family route
+ assert owned is False
+
+ def test_malformed_port_has_no_strict_arxiv_identifier(self):
+ # Given an arXiv-looking URL with a malformed port
+ url = "https://arxiv.org:not-a-port/abs/2301.12345"
+
+ # When strict identifier extraction runs
+ identifier = arxiv_utils.extract_arxiv_id(url)
+
+ # Then malformed URL syntax is rejected
+ assert identifier is None
class TestURLClassifier:
@@ -36,6 +88,81 @@ class TestURLClassifier:
url = "https://ar5iv.org/abs/2301.12345"
assert URLClassifier.classify(url) == URLType.ARXIV
+ def test_classify_ar5iv_direct_path(self):
+ url = "https://ar5iv.org/math.AG/0601001v2"
+ assert URLClassifier.classify(url) == URLType.ARXIV
+
+ def test_classify_malformed_ar5iv_path_is_not_arxiv(self):
+ url = "https://ar5iv.org/not-an-arxiv-identifier"
+ assert URLClassifier.classify(url) == URLType.HTML
+
+ def test_trailing_dot_arxiv_family_host_is_arxiv_for_a_paper_path(self):
+ url = "https://AR5IV.ORG./2301.12345v2"
+ assert URLClassifier.classify(url) == URLType.ARXIV
+
+ @pytest.mark.parametrize(
+ "url",
+ (
+ "https://AR5IV.ORG./not-an-arxiv-id",
+ "https://ARXIV.ORG./not-an-arxiv-id",
+ "https://EXPORT.ARXIV.ORG./not-an-arxiv-id",
+ "https://arxiv.org/list/cs.AI/recent",
+ "https://arxiv.org/a/bengio_y_1",
+ "https://info.arxiv.org/help/api/tou.html",
+ "https://blog.arxiv.org/2024/01/01/something/",
+ "https://arxiv.org/",
+ "https://static.arxiv.org/js/x.js",
+ "https://arxiv.org/abs/not-an-id",
+ ),
+ )
+ def test_family_host_without_a_paper_identifier_is_not_arxiv(self, url):
+ # Given a page on an arXiv-family host that names no paper
+ # When it is classified
+ # Then it is not ARXIV: ARXIV ownership is terminal on every fetch
+ # entry point, and the arXiv downloader has no source for these, so
+ # claiming them would turn a readable page into nothing at all
+ assert URLClassifier.classify(url) == URLType.HTML
+
+ @pytest.mark.parametrize(
+ "url",
+ (
+ "https://arxiv.org/ftp/arxiv/papers/2301/2301.12345.pdf",
+ "https://arxiv.org/ftp/cond-mat/papers/0501/0501001.pdf",
+ ),
+ )
+ def test_legacy_ftp_pdf_layout_is_not_arxiv(self, url):
+ # Given arXiv's legacy PDF-only submission layout
+ # When it is classified
+ # Then it is not ARXIV. classify does not drive DownloadService's
+ # downloader loop -- can_handle does, and
+ # test_legacy_ftp_pdf_is_left_to_the_direct_pdf_downloader covers
+ # that -- but ARXIV here would make ContentFetcher and the extraction
+ # pipeline terminal on a URL no arXiv source can serve. HTML rather
+ # than PDF because _is_pdf_url declines every arxiv.org URL outright.
+ assert URLClassifier.classify(url) == URLType.HTML
+
+ def test_ar5iv_text_in_unrelated_path_is_not_arxiv(self):
+ url = "https://example.com/ar5iv.org/not-an-arxiv-identifier"
+ assert URLClassifier.classify(url) == URLType.HTML
+
+ @pytest.mark.parametrize(
+ "url",
+ (
+ "https://arxiv.org.example.com/2301.12345",
+ "https://ar5iv.org.example.com/2301.12345",
+ ),
+ )
+ def test_arxiv_family_lookalike_hostname_is_not_arxiv(self, url):
+ assert URLClassifier.classify(url) == URLType.HTML
+
+ def test_trailing_dot_ar5iv_lookalike_hostname_is_not_arxiv(self):
+ url = "https://ar5iv.org.example.com./2301.12345"
+ assert URLClassifier.classify(url) == URLType.HTML
+
+ def test_arxiv_text_in_unrelated_path_is_not_arxiv(self):
+ url = "https://example.com/arxiv.org/abs/2301.12345"
+ assert URLClassifier.classify(url) == URLType.HTML
+
def test_classify_pubmed(self):
"""Test PubMed URL classification."""
url = "https://pubmed.ncbi.nlm.nih.gov/12345678"
@@ -131,6 +258,14 @@ class TestURLClassifierExtractID:
url = "https://arxiv.org/abs/cond-mat/0501234"
assert URLClassifier.extract_id(url) == "cond-mat/0501234"
+ def test_extract_arxiv_dotted_legacy_id_from_pdf(self):
+ url = "https://export.arxiv.org/pdf/math.AG/0601001v3.pdf?q=1#page=2"
+ assert URLClassifier.extract_id(url) == "math.AG/0601001v3"
+
+ def test_extract_arxiv_id_rejects_unrelated_host(self):
+ url = "https://example.com/arxiv.org/abs/2301.12345v2"
+ assert URLClassifier.extract_id(url, URLType.ARXIV) is None
+
def test_extract_pubmed_id(self):
"""Test PubMed ID extraction."""
url = "https://pubmed.ncbi.nlm.nih.gov/12345678/"
@@ -250,6 +385,10 @@ class TestURLClassifierSecurity:
url = "ftp://ftp.example.com/file.txt"
assert URLClassifier.classify(url) == URLType.INVALID
+ def test_non_http_ar5iv_url_is_rejected(self):
+ url = "ftp://ar5iv.org/2301.12345"
+ assert URLClassifier.classify(url) == URLType.INVALID
+
def test_http_url_accepted(self):
"""Test that http: URLs are accepted."""
url = "http://example.com/page"
diff --git a/tests/content_fetcher/test_url_classifier_high_value.py b/tests/content_fetcher/test_url_classifier_high_value.py
index 155d977133..aedee6cee2 100644
--- a/tests/content_fetcher/test_url_classifier_high_value.py
+++ b/tests/content_fetcher/test_url_classifier_high_value.py
@@ -117,6 +117,19 @@ class TestClassifyAcademicURLEdgeCases:
url = "https://ar5iv.org/html/2301.12345"
assert URLClassifier.classify(url) == URLType.ARXIV
+ @pytest.mark.parametrize(
+ "url",
+ (
+ "https://EXPORT.ARXIV.ORG./not-an-arxiv-id",
+ "https://RENDER.AR5IV.ORG./not-an-arxiv-id",
+ ),
+ )
+ def test_malformed_arxiv_family_subdomain_is_not_arxiv(self, url):
+ # Host membership alone no longer claims a URL: without an extractable
+ # identifier the arXiv downloader has nothing to fetch, and ARXIV is
+ # terminal, so these keep the generic HTML path
+ assert URLClassifier.classify(url) == URLType.HTML
+
def test_pubmed_trailing_slash(self):
"""PubMed URL with trailing slash."""
url = "https://pubmed.ncbi.nlm.nih.gov/98765432/"
diff --git a/tests/database/models/test_extraction_catalogs.py b/tests/database/models/test_extraction_catalogs.py
new file mode 100644
index 0000000000..ca7f45f0d4
--- /dev/null
+++ b/tests/database/models/test_extraction_catalogs.py
@@ -0,0 +1,48 @@
+"""Focused tests for arXiv HTML provenance catalog enum values.
+
+These lock the exact string identifiers used by DownloadService when it
+persists an HTML-extracted arXiv download. The ``extraction_method`` and
+``extraction_source`` columns are unconstrained strings, so any caller
+that passes the literal ``"html_extraction"`` or ``"arxiv_html"`` will
+silently bypass the catalog. Giving the values first-class enum identity
+in ``research_library/extraction_catalog.py`` -- rather than as new
+members on ``ExtractionMethod``/``ExtractionSource`` in
+``database/models/library.py`` -- keeps that catalog available without
+touching a file ``test_migration_chain_integrity.py`` and
+``test_upgrade_from_pre_migration_install.py`` both require to stay
+byte-identical to the merge base.
+
+The expected outcomes are:
+
+* ``ExtractionMethodExtra.HTML_EXTRACTION.value == 'html_extraction'``
+* ``ExtractionSourceExtra.ARXIV_HTML.value == 'arxiv_html'``
+
+If either constant is renamed, the persisted strings in user databases
+would drift and the existing provenance would no longer parse — which is
+the regression the test guards against.
+"""
+
+from local_deep_research.research_library.extraction_catalog import (
+ ExtractionMethodExtra,
+ ExtractionSourceExtra,
+)
+
+
+class TestExtractionMethodCatalog:
+ """Exact-value assertions for ``ExtractionMethodExtra``."""
+
+ def test_html_extraction_value_is_html_extraction(self):
+ assert ExtractionMethodExtra.HTML_EXTRACTION.value == "html_extraction"
+
+ def test_html_extraction_member_exists(self):
+ assert "HTML_EXTRACTION" in ExtractionMethodExtra.__members__
+
+
+class TestExtractionSourceCatalog:
+ """Exact-value assertions for ``ExtractionSourceExtra``."""
+
+ def test_arxiv_html_value_is_arxiv_html(self):
+ assert ExtractionSourceExtra.ARXIV_HTML.value == "arxiv_html"
+
+ def test_arxiv_html_member_exists(self):
+ assert "ARXIV_HTML" in ExtractionSourceExtra.__members__
diff --git a/tests/download_stuff_for_local.py b/tests/download_stuff_for_local.py
index e1a4399db5..dcca4ee77c 100644
--- a/tests/download_stuff_for_local.py
+++ b/tests/download_stuff_for_local.py
@@ -1,16 +1,25 @@
import os
+import sys
+from pathlib import Path
-import arxiv
from datasets import load_dataset
+PROJECT_ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(PROJECT_ROOT / "src"))
+
+from local_deep_research.utilities.arxiv_api import ( # noqa: E402
+ ArxivQueryRequest,
+ fetch_arxiv_results,
+)
+
max_results = 50
-# Search for papers and limit to 400
-search = arxiv.Search(query="machine learning", max_results=50)
-client = arxiv.Client()
+papers = fetch_arxiv_results(
+ ArxivQueryRequest(query="machine learning", max_results=max_results)
+)
# Download papers
os.makedirs("./../local_search_files/research_papers", exist_ok=True)
-for i, result in enumerate(client.results(search)):
+for i, result in enumerate(papers):
try:
filename = f"./../local_search_files/research_papers/paper_{i}.pdf"
result.download_pdf(filename=filename)
diff --git a/tests/performance/relevance_filter/eval_models.py b/tests/performance/relevance_filter/eval_models.py
index 26670884be..eaa9288503 100644
--- a/tests/performance/relevance_filter/eval_models.py
+++ b/tests/performance/relevance_filter/eval_models.py
@@ -25,13 +25,16 @@ import time
from pathlib import Path
from typing import Dict, List
-import arxiv
import requests
PROJECT_ROOT = Path(__file__).resolve().parents[3]
sys.path.insert(0, str(PROJECT_ROOT / "src"))
from local_deep_research.security import safe_get # noqa: E402
+from local_deep_research.utilities.arxiv_api import ( # noqa: E402
+ ArxivQueryRequest,
+ fetch_arxiv_results,
+)
from local_deep_research.web_search_engines.relevance_filter import ( # noqa: E402
filter_previews_for_relevance,
)
@@ -59,19 +62,16 @@ QUERIES = [
def fetch_previews(query: str, max_results: int) -> List[Dict]:
- client = arxiv.Client(page_size=max_results)
- search = arxiv.Search(
- query=query,
- max_results=max_results,
- sort_by=arxiv.SortCriterion.Relevance,
+ papers = fetch_arxiv_results(
+ ArxivQueryRequest(query=query, max_results=max_results)
)
return [
{
- "title": p.title.strip(),
- "snippet": (p.summary or "").strip(),
- "url": p.entry_id,
+ "title": paper.title.strip(),
+ "snippet": (paper.summary or "").strip(),
+ "url": paper.entry_id,
}
- for p in client.results(search)
+ for paper in papers
]
diff --git a/tests/performance/relevance_filter/eval_prompt.py b/tests/performance/relevance_filter/eval_prompt.py
index b4ac30519d..6964cd155b 100644
--- a/tests/performance/relevance_filter/eval_prompt.py
+++ b/tests/performance/relevance_filter/eval_prompt.py
@@ -21,13 +21,16 @@ import sys
from pathlib import Path
from typing import Dict, List
-import arxiv
import requests
PROJECT_ROOT = Path(__file__).resolve().parents[3]
sys.path.insert(0, str(PROJECT_ROOT / "src"))
from local_deep_research.security import safe_get # noqa: E402
+from local_deep_research.utilities.arxiv_api import ( # noqa: E402
+ ArxivQueryRequest,
+ fetch_arxiv_results,
+)
from local_deep_research.web_search_engines.relevance_filter import ( # noqa: E402
filter_previews_for_relevance,
)
@@ -94,19 +97,16 @@ VARIANTS: Dict[str, str] = {
def fetch_previews(query: str, max_results: int) -> List[Dict]:
- client = arxiv.Client(page_size=max_results)
- search = arxiv.Search(
- query=query,
- max_results=max_results,
- sort_by=arxiv.SortCriterion.Relevance,
+ papers = fetch_arxiv_results(
+ ArxivQueryRequest(query=query, max_results=max_results)
)
return [
{
- "title": p.title.strip(),
- "snippet": (p.summary or "").strip(),
- "url": p.entry_id,
+ "title": paper.title.strip(),
+ "snippet": (paper.summary or "").strip(),
+ "url": paper.entry_id,
}
- for p in client.results(search)
+ for paper in papers
]
diff --git a/tests/performance/relevance_filter/test_live.py b/tests/performance/relevance_filter/test_live.py
index d5da5d9d3a..b81fb08bda 100644
--- a/tests/performance/relevance_filter/test_live.py
+++ b/tests/performance/relevance_filter/test_live.py
@@ -83,28 +83,27 @@ def ollama_llm():
def _arxiv_previews(query: str, max_results: int) -> List[Dict[str, Any]]:
"""Fetch arXiv previews in the dict shape the relevance filter expects.
- Uses the ``arxiv`` package directly (not ArXivSearchEngine) to avoid the
- rate-limiter, journal-reputation-filter, and thread-context machinery —
- we just want raw title+abstract pairs.
+ Uses the shared typed fetch API directly (not ArXivSearchEngine) to avoid the
+ engine / journal-reputation-filter / thread-context machinery — we just
+ want raw title+abstract pairs — while still routing every request through
+ the shared transport policy.
"""
- import arxiv
+ from local_deep_research.utilities.arxiv_api import (
+ ArxivQueryRequest,
+ fetch_arxiv_results,
+ )
- client = arxiv.Client(page_size=max_results)
- search = arxiv.Search(
- query=query,
- max_results=max_results,
- sort_by=arxiv.SortCriterion.Relevance,
+ papers = fetch_arxiv_results(
+ ArxivQueryRequest(query=query, max_results=max_results)
)
- previews = []
- for paper in client.results(search):
- previews.append(
- {
- "title": paper.title.strip(),
- "snippet": (paper.summary or "").strip(),
- "url": paper.entry_id,
- }
- )
- return previews
+ return [
+ {
+ "title": paper.title.strip(),
+ "snippet": (paper.summary or "").strip(),
+ "url": paper.entry_id,
+ }
+ for paper in papers
+ ]
# Queries chosen to exercise the keyword-bait failure mode. Each one has
diff --git a/tests/research_library/downloaders/test_arxiv_downloader.py b/tests/research_library/downloaders/test_arxiv_downloader.py
index 4d5f0778f9..35283e67e7 100644
--- a/tests/research_library/downloaders/test_arxiv_downloader.py
+++ b/tests/research_library/downloaders/test_arxiv_downloader.py
@@ -2,6 +2,9 @@
Tests for ArxivDownloader.
"""
+import threading
+from collections.abc import Iterator
+
import pytest
from local_deep_research.research_library.downloaders.arxiv import (
@@ -10,6 +13,20 @@ from local_deep_research.research_library.downloaders.arxiv import (
from local_deep_research.research_library.downloaders.base import (
ContentType,
)
+from local_deep_research.utilities import arxiv_api
+
+
[email protected](autouse=True)
+def fresh_arxiv_api_gate() -> Iterator[list[threading.Thread]]:
+ threads: list[threading.Thread] = []
+ with arxiv_api._arxiv_api_request_lock:
+ arxiv_api._last_request_started_at = None
+ yield threads
+ for thread in threads:
+ thread.join(timeout=1)
+ assert not thread.is_alive()
+ with arxiv_api._arxiv_api_request_lock:
+ arxiv_api._last_request_started_at = None
class TestArxivCanHandle:
@@ -50,6 +67,70 @@ class TestArxivCanHandle:
is True
)
+ def test_can_handle_ar5iv_direct_url(self, downloader):
+ assert downloader.can_handle("https://ar5iv.org/2301.12345v2") is True
+
+ @pytest.mark.parametrize(
+ "url",
+ (
+ "https://ar5iv.org/not-an-arxiv-id",
+ "https://ARXIV.ORG./not-an-arxiv-id",
+ "https://EXPORT.ARXIV.ORG./not-an-arxiv-id",
+ "https://RENDER.AR5IV.ORG./not-an-arxiv-id",
+ "https://arxiv.org/abs/not-an-id",
+ "https://arxiv.org/list/cs.AI/recent",
+ "https://info.arxiv.org/help/api/tou.html",
+ ),
+ )
+ def test_cannot_handle_family_host_without_an_identifier(
+ self, downloader, url
+ ):
+ # Given an arXiv-family host whose path names no paper
+ # When the downloader is offered it
+ # Then it declines: claiming it would only skip it, and would starve
+ # whichever downloader can actually serve the page
+ assert downloader.can_handle(url) is False
+
+ @pytest.mark.parametrize(
+ "url",
+ (
+ "https://arxiv.org/ftp/arxiv/papers/2301/2301.12345.pdf",
+ "https://arxiv.org/ftp/cond-mat/papers/0501/0501001.pdf",
+ ),
+ )
+ def test_legacy_ftp_pdf_is_left_to_the_direct_pdf_downloader(
+ self, downloader, url
+ ):
+ # Given arXiv's legacy PDF-only submission layout, which carries no
+ # identifier this downloader can build a canonical URL from
+ from local_deep_research.research_library.downloaders.direct_pdf import (
+ DirectPDFDownloader,
+ )
+
+ # When both downloaders in DownloadService's order are offered it
+ direct_pdf = DirectPDFDownloader(timeout=30)
+
+ # Then the arXiv downloader declines and the PDF downloader takes it,
+ # so the ordering in DownloadService.downloaders cannot starve it
+ assert downloader.can_handle(url) is False
+ assert direct_pdf.can_handle(url) is True
+
+ def test_cannot_handle_ar5iv_text_on_unrelated_host(self, downloader):
+ assert (
+ downloader.can_handle("https://example.com/ar5iv.org/2301.12345")
+ is False
+ )
+
+ @pytest.mark.parametrize(
+ "url",
+ (
+ "https://arxiv.org.example.com/not-an-arxiv-id",
+ "https://ar5iv.org.example.com./not-an-arxiv-id",
+ ),
+ )
+ def test_cannot_handle_arxiv_family_lookalike(self, downloader, url):
+ assert downloader.can_handle(url) is False
+
def test_cannot_handle_pubmed(self, downloader):
"""Returns False for PubMed URLs."""
assert (
@@ -83,9 +164,8 @@ class TestArxivIdExtraction:
assert downloader._extract_arxiv_id(url) == "2301.12345"
def test_extract_new_format_with_version(self, downloader):
- """Strips version from new format ID."""
url = "https://arxiv.org/abs/2301.12345v2"
- assert downloader._extract_arxiv_id(url) == "2301.12345"
+ assert downloader._extract_arxiv_id(url) == "2301.12345v2"
def test_extract_old_format(self, downloader):
"""Extracts cond-mat/0501234 format."""
@@ -93,9 +173,16 @@ class TestArxivIdExtraction:
assert downloader._extract_arxiv_id(url) == "cond-mat/0501234"
def test_extract_old_format_with_version(self, downloader):
- """Strips version from old format ID."""
url = "https://arxiv.org/abs/cond-mat/0501234v1"
- assert downloader._extract_arxiv_id(url) == "cond-mat/0501234"
+ assert downloader._extract_arxiv_id(url) == "cond-mat/0501234v1"
+
+ def test_extract_dotted_legacy_id_from_html_url(self, downloader):
+ url = "https://arxiv.org/html/math.AG/0601001v3?download=1#proof"
+ assert downloader._extract_arxiv_id(url) == "math.AG/0601001v3"
+
+ def test_extract_from_ar5iv_direct_url(self, downloader):
+ url = "https://ar5iv.org/2301.12345v4"
+ assert downloader._extract_arxiv_id(url) == "2301.12345v4"
def test_extract_from_pdf_url(self, downloader):
"""Extracts from PDF URL."""
@@ -183,6 +270,20 @@ class TestArxivDownloadWithResult:
assert result.skip_reason is not None
assert "could not extract" in result.skip_reason.lower()
+ def test_malformed_ar5iv_fails_without_request(self, downloader, mocker):
+ # Given an ar5iv-owned URL whose path has no valid identifier
+ request = mocker.patch.object(downloader.session, "get")
+
+ # When the specialist handles it
+ result = downloader.download_with_result(
+ "https://ar5iv.org/not-an-arxiv-id", ContentType.TEXT
+ )
+
+ # Then it fails before querying HTML, PDF, or API endpoints
+ assert result.is_success is False
+ assert "could not extract" in result.skip_reason.lower()
+ request.assert_not_called()
+
def test_download_with_result_pdf_success(
self, downloader, mocker, mock_pdf_content
):
@@ -247,11 +348,25 @@ class TestArxivApiIntegration:
mocker.patch.object(
downloader.session, "get", return_value=mock_response
)
+ apply_rate_limit = mocker.patch.object(
+ downloader.rate_tracker, "apply_rate_limit", return_value=0.25
+ )
+ record_outcome = mocker.patch.object(
+ downloader.rate_tracker, "record_outcome"
+ )
metadata = downloader._fetch_from_arxiv_api("2301.12345")
assert metadata is not None
assert "Test Paper" in metadata
assert "John Doe" in metadata
+ apply_rate_limit.assert_called_once_with("arxiv_api")
+ record_outcome.assert_called_once_with(
+ engine_type="arxiv_api",
+ wait_time=0.25,
+ success=True,
+ retry_count=1,
+ search_result_count=1,
+ )
def test_fetch_from_arxiv_api_failure(self, downloader, mocker):
"""Returns None on API failure."""
@@ -261,9 +376,22 @@ class TestArxivApiIntegration:
mocker.patch.object(
downloader.session, "get", return_value=mock_response
)
+ mocker.patch.object(
+ downloader.rate_tracker, "apply_rate_limit", return_value=0.25
+ )
+ record_outcome = mocker.patch.object(
+ downloader.rate_tracker, "record_outcome"
+ )
metadata = downloader._fetch_from_arxiv_api("2301.12345")
assert metadata is None
+ record_outcome.assert_called_once_with(
+ engine_type="arxiv_api",
+ wait_time=0.25,
+ success=False,
+ retry_count=1,
+ error_type="HTTP_500",
+ )
def test_fetch_from_arxiv_api_timeout(self, downloader, mocker):
"""Returns None on timeout."""
@@ -274,9 +402,316 @@ class TestArxivApiIntegration:
"get",
side_effect=requests.exceptions.Timeout("Timeout"),
)
+ mocker.patch.object(
+ downloader.rate_tracker, "apply_rate_limit", return_value=0.25
+ )
+ record_outcome = mocker.patch.object(
+ downloader.rate_tracker, "record_outcome"
+ )
metadata = downloader._fetch_from_arxiv_api("2301.12345")
assert metadata is None
+ record_outcome.assert_called_once_with(
+ engine_type="arxiv_api",
+ wait_time=0.25,
+ success=False,
+ retry_count=1,
+ error_type="Timeout",
+ )
+
+ def test_redirect_is_not_followed(self, downloader, mocker):
+ # Given an API redirect and unchanged adaptive tracker accounting
+ mock_response = mocker.Mock(status_code=302)
+ request = mocker.patch.object(
+ downloader.session, "get", return_value=mock_response
+ )
+ mocker.patch.object(
+ downloader.rate_tracker, "apply_rate_limit", return_value=0.25
+ )
+ record_outcome = mocker.patch.object(
+ downloader.rate_tracker, "record_outcome"
+ )
+
+ # When API metadata is requested
+ metadata = downloader._fetch_from_arxiv_api("2301.12345")
+
+ # Then redirects are disabled and the 3xx is the existing non-200 failure
+ assert metadata is None
+ request.assert_called_once_with(
+ "https://export.arxiv.org/api/query",
+ params={"id_list": "2301.12345"},
+ timeout=10,
+ allow_redirects=False,
+ )
+ record_outcome.assert_called_once_with(
+ engine_type="arxiv_api",
+ wait_time=0.25,
+ success=False,
+ retry_count=1,
+ error_type="HTTP_302",
+ )
+
+
+class TestArxivApiComplianceGate:
+ @pytest.fixture
+ def downloader(self, mocker):
+ instance = ArxivDownloader(timeout=30)
+ instance.rate_tracker = mocker.MagicMock()
+ return instance
+
+ def test_first_request_has_no_policy_sleep(self, downloader, mocker):
+ # Given a fresh process gate and a deterministic monotonic clock
+ response = mocker.Mock(status_code=503)
+ request = mocker.patch.object(
+ downloader.session, "get", return_value=response
+ )
+ mocker.patch.object(arxiv_api, "_monotonic", return_value=10.0)
+ hard_sleep = mocker.patch.object(arxiv_api, "_sleep")
+
+ # When the first API request starts
+ downloader._fetch_from_arxiv_api("2301.12345")
+
+ # Then the policy gate starts it immediately
+ hard_sleep.assert_not_called()
+ request.assert_called_once()
+
+ def test_independent_instances_share_start_spacing(self, mocker):
+ # Given two downloader instances and a clock advanced only by policy sleep
+ now = 100.0
+ starts: list[float] = []
+ sleeps: list[float] = []
+
+ def monotonic() -> float:
+ return now
+
+ def sleep(duration: float) -> None:
+ nonlocal now
+ sleeps.append(duration)
+ now += duration
+
+ def get_response(*_args, **_kwargs):
+ starts.append(now)
+ return mocker.Mock(status_code=503)
+
+ first = ArxivDownloader(timeout=30)
+ second = ArxivDownloader(timeout=30)
+ first.rate_tracker = mocker.MagicMock()
+ second.rate_tracker = mocker.MagicMock()
+ mocker.patch.object(first.session, "get", side_effect=get_response)
+ mocker.patch.object(second.session, "get", side_effect=get_response)
+ mocker.patch.object(arxiv_api, "_monotonic", side_effect=monotonic)
+ mocker.patch.object(arxiv_api, "_sleep", side_effect=sleep)
+
+ # When each independent instance requests API metadata
+ first._fetch_from_arxiv_api("2301.12345")
+ second._fetch_from_arxiv_api("2301.12346")
+
+ # Then their process-wide request starts are at least three seconds apart
+ assert starts == [100.0, 103.0]
+ assert sleeps == [3.0]
+
+ def test_concurrent_requests_are_single_flight(
+ self, mocker, fresh_arxiv_api_gate
+ ):
+ # Given two requests whose HTTP calls would overlap without the gate lock
+ now = 200.0
+ active_requests = 0
+ maximum_active_requests = 0
+ call_count = 0
+ activity_lock = threading.Lock()
+ first_request_entered = threading.Event()
+ second_request_waiting_for_gate = threading.Event()
+
+ gate_lock = threading.Lock()
+
+ class ObservedLock:
+ def __enter__(self):
+ if gate_lock.locked():
+ second_request_waiting_for_gate.set()
+ gate_lock.acquire()
+ return self
+
+ def __exit__(self, *_args):
+ gate_lock.release()
+
+ def monotonic() -> float:
+ return now
+
+ def sleep(duration: float) -> None:
+ nonlocal now
+ now += duration
+
+ def get_response(*_args, **_kwargs):
+ nonlocal active_requests, call_count, maximum_active_requests
+ with activity_lock:
+ call_count += 1
+ request_number = call_count
+ active_requests += 1
+ maximum_active_requests = max(
+ maximum_active_requests, active_requests
+ )
+ try:
+ if request_number == 1:
+ first_request_entered.set()
+ assert second_request_waiting_for_gate.wait(timeout=1)
+ return mocker.Mock(status_code=503)
+ finally:
+ with activity_lock:
+ active_requests -= 1
+
+ first = ArxivDownloader(timeout=30)
+ second = ArxivDownloader(timeout=30)
+ first.rate_tracker = mocker.MagicMock()
+ second.rate_tracker = mocker.MagicMock()
+ mocker.patch.object(first.session, "get", side_effect=get_response)
+ mocker.patch.object(second.session, "get", side_effect=get_response)
+ mocker.patch.object(
+ arxiv_api, "_arxiv_api_request_lock", ObservedLock()
+ )
+ mocker.patch.object(arxiv_api, "_monotonic", side_effect=monotonic)
+ mocker.patch.object(arxiv_api, "_sleep", side_effect=sleep)
+
+ first_thread = threading.Thread(
+ target=first._fetch_from_arxiv_api, args=("2301.12345",)
+ )
+ second_thread = threading.Thread(
+ target=second._fetch_from_arxiv_api, args=("2301.12346",)
+ )
+ fresh_arxiv_api_gate.extend((first_thread, second_thread))
+
+ # When both requests run concurrently
+ first_thread.start()
+ assert first_request_entered.wait(timeout=1)
+ second_thread.start()
+ first_thread.join(timeout=1)
+ second_thread.join(timeout=1)
+
+ # Then only one HTTP request is active at a time
+ assert not first_thread.is_alive()
+ assert not second_thread.is_alive()
+ assert second_request_waiting_for_gate.is_set()
+ assert maximum_active_requests == 1
+
+ def test_long_request_needs_no_extra_policy_sleep(self, mocker):
+ # Given a first request whose HTTP call consumes the full interval
+ now = 300.0
+ starts: list[float] = []
+
+ def monotonic() -> float:
+ return now
+
+ def get_response(*_args, **_kwargs):
+ nonlocal now
+ starts.append(now)
+ if len(starts) == 1:
+ now += 3.0
+ return mocker.Mock(status_code=503)
+
+ first = ArxivDownloader(timeout=30)
+ second = ArxivDownloader(timeout=30)
+ first.rate_tracker = mocker.MagicMock()
+ second.rate_tracker = mocker.MagicMock()
+ mocker.patch.object(first.session, "get", side_effect=get_response)
+ mocker.patch.object(second.session, "get", side_effect=get_response)
+ mocker.patch.object(arxiv_api, "_monotonic", side_effect=monotonic)
+ hard_sleep = mocker.patch.object(arxiv_api, "_sleep")
+
+ # When a second request follows the completed long request
+ first._fetch_from_arxiv_api("2301.12345")
+ second._fetch_from_arxiv_api("2301.12346")
+
+ # Then start-based spacing requires no additional sleep
+ assert starts == [300.0, 303.0]
+ hard_sleep.assert_not_called()
+
+ def test_failed_start_releases_lock_and_preserves_spacing(
+ self, mocker, fresh_arxiv_api_gate
+ ):
+ # Given a request start that raises and a deterministic process clock
+ import requests
+
+ now = 400.0
+ starts: list[float] = []
+ sleeps: list[float] = []
+
+ def monotonic() -> float:
+ return now
+
+ def sleep(duration: float) -> None:
+ nonlocal now
+ sleeps.append(duration)
+ now += duration
+
+ def failed_get(*_args, **_kwargs):
+ starts.append(now)
+ raise requests.exceptions.ConnectionError("connection refused")
+
+ def successful_get(*_args, **_kwargs):
+ starts.append(now)
+ return mocker.Mock(status_code=503)
+
+ first = ArxivDownloader(timeout=30)
+ second = ArxivDownloader(timeout=30)
+ first.rate_tracker = mocker.MagicMock()
+ second.rate_tracker = mocker.MagicMock()
+ mocker.patch.object(first.session, "get", side_effect=failed_get)
+ mocker.patch.object(second.session, "get", side_effect=successful_get)
+ mocker.patch.object(arxiv_api, "_monotonic", side_effect=monotonic)
+ mocker.patch.object(arxiv_api, "_sleep", side_effect=sleep)
+
+ # When the failed start is followed by another instance's request
+ first._fetch_from_arxiv_api("2301.12345")
+ next_thread = threading.Thread(
+ target=second._fetch_from_arxiv_api, args=("2301.12346",)
+ )
+ fresh_arxiv_api_gate.append(next_thread)
+ next_thread.start()
+ next_thread.join(timeout=1)
+
+ # Then the lock is released but the failed start still counts for spacing
+ assert not next_thread.is_alive()
+ assert starts == [400.0, 403.0]
+ assert sleeps == [3.0]
+
+
+class TestArxivMetadata:
+ @pytest.fixture
+ def downloader(self):
+ return ArxivDownloader(timeout=30)
+
+ def test_metadata_is_canonical_and_network_free(self, downloader, mocker):
+ # Given a versioned legacy ar5iv input and a request tripwire
+ request = mocker.patch.object(
+ downloader.session,
+ "get",
+ side_effect=AssertionError("metadata attempted a network request"),
+ )
+
+ # When metadata is requested
+ metadata = downloader.get_metadata(
+ "https://ar5iv.org/math.AG/0601001v3.pdf?download=1#page=2"
+ )
+
+ # Then only the canonical version-preserving arXiv URL is returned
+ assert metadata == {"url": "https://arxiv.org/abs/math.AG/0601001v3"}
+ request.assert_not_called()
+
+ def test_metadata_is_empty_for_invalid_url(self, downloader, mocker):
+ # Given an invalid arXiv URL and a request tripwire
+ request = mocker.patch.object(
+ downloader.session,
+ "get",
+ side_effect=AssertionError("invalid metadata attempted a request"),
+ )
+
+ # When metadata is requested
+ metadata = downloader.get_metadata(
+ "https://example.com/arxiv/2301.12345"
+ )
+
+ # Then it is rejected without network access
+ assert metadata == {}
+ request.assert_not_called()
class TestArxivTextDownload:
@@ -286,43 +721,41 @@ class TestArxivTextDownload:
def downloader(self):
return ArxivDownloader(timeout=30)
- def test_download_text_extracts_from_pdf(
+ def test_download_text_uses_api_after_html_and_pdf_text_fail(
self, downloader, mocker, mock_pdf_content
):
- """Downloads PDF and extracts text."""
- # Mock PDF download
- mock_pdf_response = mocker.Mock()
- mock_pdf_response.status_code = 200
- mock_pdf_response.content = mock_pdf_content
- mock_pdf_response.headers = {"content-type": "application/pdf"}
-
- # Mock API response
- mock_api_response = mocker.Mock()
- mock_api_response.status_code = 200
- mock_api_response.text = """<?xml version="1.0"?>
- <feed xmlns="http://www.w3.org/2005/Atom">
- <entry>
- <title>Test Paper</title>
- <summary>Test abstract</summary>
- </entry>
- </feed>"""
-
- def mock_get(url, **kwargs):
- if "export.arxiv.org/api" in url:
- return mock_api_response
- return mock_pdf_response
-
- mocker.patch.object(downloader.session, "get", side_effect=mock_get)
+ # Given source doubles that record the fallback order
+ calls = []
mocker.patch.object(
- downloader.rate_tracker, "apply_rate_limit", return_value=0
+ downloader,
+ "_download_html_text",
+ side_effect=lambda _arxiv_id: calls.append("html"),
+ )
+ mocker.patch.object(
+ downloader,
+ "_download_pdf",
+ side_effect=lambda _url: calls.append("pdf") or mock_pdf_content,
+ )
+ mocker.patch.object(
+ downloader,
+ "extract_text_from_pdf",
+ side_effect=lambda _content: calls.append("pdf_text"),
+ )
+ mocker.patch.object(
+ downloader,
+ "_fetch_from_arxiv_api",
+ side_effect=lambda _arxiv_id: (
+ calls.append("api")
+ or "Title: Test Paper\n\nAbstract:\nTest abstract"
+ ),
)
- mocker.patch.object(downloader.rate_tracker, "record_outcome")
- # Note: text extraction from minimal PDF returns None/empty
- result = downloader.download_with_result(
- "https://arxiv.org/abs/2301.12345",
- ContentType.TEXT,
+ # When text is downloaded directly
+ result = downloader.download_text("https://arxiv.org/abs/2301.12345")
+
+ # Then the API result is exact and is attempted strictly last
+ assert result == (
+ "Title: Test Paper\n\nAbstract:\nTest abstract"
+ "\n\nSource: https://arxiv.org/abs/2301.12345"
)
- # The minimal PDF has no text, so this tests the flow even if content extraction fails
- # In production with real PDFs, this would return the extracted text
- assert result is not None
+ assert calls == ["html", "pdf", "pdf_text", "api"]
diff --git a/tests/research_library/downloaders/test_arxiv_downloader_coverage.py b/tests/research_library/downloaders/test_arxiv_downloader_coverage.py
index b72b2bce8d..b6e8324acb 100644
--- a/tests/research_library/downloaders/test_arxiv_downloader_coverage.py
+++ b/tests/research_library/downloaders/test_arxiv_downloader_coverage.py
@@ -2,8 +2,8 @@
Comprehensive coverage tests for research_library/downloaders/arxiv.py
Focuses on:
-- download_with_result() TEXT path: with metadata, without metadata, no PDF, no extracted text
-- _download_text(): with/without metadata, invalid ID, no PDF, no extracted text
+- download_with_result() TEXT path: HTML/PDF/API fallbacks and failures
+- download_text(): PDF reuse, API fallback, invalid ID, and unavailable text
- _fetch_from_arxiv_api(): categories parsing, exception handling, empty entry
- PDF URL construction correctness
"""
@@ -18,6 +18,7 @@ from local_deep_research.research_library.downloaders.arxiv import (
from local_deep_research.research_library.downloaders.base import (
ContentType,
)
+from local_deep_research.utilities import arxiv_api
# ---------------------------------------------------------------------------
@@ -28,6 +29,7 @@ ARXIV_API_FULL_XML = """<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom"
xmlns:arxiv="http://arxiv.org/schemas/atom">
<entry>
+ <id>http://arxiv.org/abs/2301.12345v2</id>
<title> Deep Learning Survey </title>
<summary> We survey deep learning methods. </summary>
<author><name>Alice</name></author>
@@ -45,6 +47,18 @@ ARXIV_API_EMPTY_ENTRY_XML = """<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom"
xmlns:arxiv="http://arxiv.org/schemas/atom">
<entry>
+ <id>http://arxiv.org/abs/2301.12345v2</id>
+ </entry>
+</feed>"""
+
+ARXIV_API_WHITESPACE_ENTRY_XML = """<?xml version="1.0" encoding="UTF-8"?>
+<feed xmlns="http://www.w3.org/2005/Atom">
+ <entry>
+ <id>http://arxiv.org/abs/2301.12345v2</id>
+ <title> </title>
+ <summary> </summary>
+ <author><name> </name></author>
+ <category term=" "/>
</entry>
</feed>"""
@@ -52,6 +66,7 @@ ARXIV_API_CATEGORIES_ONLY_XML = """<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom"
xmlns:arxiv="http://arxiv.org/schemas/atom">
<entry>
+ <id>http://arxiv.org/abs/2301.12345v2</id>
<title>Cats</title>
<category term="cs.CV"/>
<category term="cs.AI"/>
@@ -60,10 +75,22 @@ ARXIV_API_CATEGORIES_ONLY_XML = """<?xml version="1.0" encoding="UTF-8"?>
</feed>"""
[email protected](autouse=True)
+def fresh_arxiv_api_gate():
+ with arxiv_api._arxiv_api_request_lock:
+ arxiv_api._last_request_started_at = None
+ yield
+ with arxiv_api._arxiv_api_request_lock:
+ arxiv_api._last_request_started_at = None
+
+
@pytest.fixture
def downloader():
"""Create an ArxivDownloader instance."""
- return ArxivDownloader(timeout=30)
+ instance = ArxivDownloader(timeout=30)
+ instance.rate_tracker = MagicMock()
+ instance.rate_tracker.apply_rate_limit.return_value = 0.25
+ return instance
@pytest.fixture
@@ -72,6 +99,13 @@ def mock_pdf_bytes():
return b"%PDF-1.4 fake pdf content for testing"
+def unavailable_arxiv_html(downloader, mocker):
+ return mocker.patch.object(
+ downloader, "_fetch_html_with_final_url", return_value=(None, None)
+ )
+
+
# ---------------------------------------------------------------------------
# download_with_result -- TEXT content type
# ---------------------------------------------------------------------------
@@ -80,16 +114,17 @@ def mock_pdf_bytes():
class TestDownloadWithResultText:
"""Tests for download_with_result when content_type is TEXT."""
- def test_text_with_metadata(self, downloader, mocker, mock_pdf_bytes):
- """When PDF is downloaded, text extracted, and metadata fetched,
- the result should contain metadata + separator + extracted text."""
+ def test_pdf_text_skips_api_metadata(
+ self, downloader, mocker, mock_pdf_bytes, unavailable_arxiv_html
+ ):
+ """Successful PDF text is returned without querying API metadata."""
mocker.patch.object(
downloader, "_download_pdf", return_value=mock_pdf_bytes
)
mocker.patch.object(
downloader, "extract_text_from_pdf", return_value="Extracted body."
)
- mocker.patch.object(
+ api_fetch = mocker.patch.object(
downloader,
"_fetch_from_arxiv_api",
return_value="Title: Some Title\nAuthors: A, B",
@@ -100,22 +135,25 @@ class TestDownloadWithResultText:
)
assert result.is_success is True
- text = result.content.decode("utf-8")
- assert "Title: Some Title" in text
- assert "FULL PAPER TEXT" in text
- assert "Extracted body." in text
-
- def test_text_without_metadata(self, downloader, mocker, mock_pdf_bytes):
- """When metadata fetch returns None, the result should contain only
- the extracted text (no separator header)."""
+ assert result.content == (
+ b"Extracted body.\n\nSource: https://arxiv.org/abs/2301.12345"
+ )
+ api_fetch.assert_not_called()
+
+ def test_api_metadata_follows_failed_pdf_text(
+ self, downloader, mocker, mock_pdf_bytes, unavailable_arxiv_html
+ ):
+ """API metadata is the final fallback after PDF extraction fails."""
mocker.patch.object(
downloader, "_download_pdf", return_value=mock_pdf_bytes
)
mocker.patch.object(
- downloader, "extract_text_from_pdf", return_value="Just the text."
+ downloader, "extract_text_from_pdf", return_value=None
)
mocker.patch.object(
- downloader, "_fetch_from_arxiv_api", return_value=None
+ downloader,
+ "_fetch_from_arxiv_api",
+ return_value="Title: API fallback",
)
result = downloader.download_with_result(
@@ -123,13 +161,16 @@ class TestDownloadWithResultText:
)
assert result.is_success is True
- text = result.content.decode("utf-8")
- assert text == "Just the text."
- assert "FULL PAPER TEXT" not in text
+ assert result.content == (
+ b"Title: API fallback\n\nSource: https://arxiv.org/abs/2301.12345"
+ )
- def test_text_no_pdf(self, downloader, mocker):
+ def test_text_no_pdf(self, downloader, mocker, unavailable_arxiv_html):
"""When PDF download fails, the result should be a skip with reason."""
mocker.patch.object(downloader, "_download_pdf", return_value=None)
+ mocker.patch.object(
+ downloader, "_fetch_from_arxiv_api", return_value=None
+ )
result = downloader.download_with_result(
"https://arxiv.org/abs/2301.12345", ContentType.TEXT
@@ -138,7 +179,9 @@ class TestDownloadWithResultText:
assert result.is_success is False
assert "Could not retrieve full text" in result.skip_reason
- def test_text_no_extracted_text(self, downloader, mocker, mock_pdf_bytes):
+ def test_text_no_extracted_text(
+ self, downloader, mocker, mock_pdf_bytes, unavailable_arxiv_html
+ ):
"""When PDF is downloaded but text extraction returns None,
the result should be a skip."""
mocker.patch.object(
@@ -147,6 +190,9 @@ class TestDownloadWithResultText:
mocker.patch.object(
downloader, "extract_text_from_pdf", return_value=None
)
+ mocker.patch.object(
+ downloader, "_fetch_from_arxiv_api", return_value=None
+ )
result = downloader.download_with_result(
"https://arxiv.org/abs/2301.12345", ContentType.TEXT
@@ -157,7 +203,11 @@ class TestDownloadWithResultText:
assert "2301.12345" in result.skip_reason
def test_text_empty_extracted_text(
- self, downloader, mocker, mock_pdf_bytes
+ self,
+ downloader,
+ mocker,
+ mock_pdf_bytes,
+ unavailable_arxiv_html,
):
"""When extract_text_from_pdf returns an empty string (falsy),
the result should still be a skip."""
@@ -167,6 +217,9 @@ class TestDownloadWithResultText:
mocker.patch.object(
downloader, "extract_text_from_pdf", return_value=""
)
+ mocker.patch.object(
+ downloader, "_fetch_from_arxiv_api", return_value=None
+ )
result = downloader.download_with_result(
"https://arxiv.org/abs/2301.12345", ContentType.TEXT
@@ -249,64 +302,72 @@ class TestDownloadWithResultPDF:
# ---------------------------------------------------------------------------
-# _download_text
+# download_text
# ---------------------------------------------------------------------------
class TestDownloadText:
- """Tests for the _download_text private method."""
+ """Tests for the public text-production seam."""
- def test_with_metadata(self, downloader, mocker, mock_pdf_bytes):
- """Returns bytes containing metadata + separator + extracted text."""
- mocker.patch.object(
- downloader, "_download_pdf", return_value=mock_pdf_bytes
- )
- mocker.patch.object(
- downloader, "extract_text_from_pdf", return_value="Paper text."
- )
+ def test_with_metadata(
+ self, downloader, mocker, mock_pdf_bytes, unavailable_arxiv_html
+ ):
+ """Returns API metadata when PDF text is unavailable."""
+ mocker.patch.object(downloader, "_download_pdf", return_value=None)
mocker.patch.object(
downloader, "_fetch_from_arxiv_api", return_value="Title: Paper"
)
- result = downloader._download_text("https://arxiv.org/abs/2301.12345")
+ result = downloader.download_text("https://arxiv.org/abs/2301.12345")
- assert result is not None
- decoded = result.decode("utf-8")
- assert "Title: Paper" in decoded
- assert "FULL PAPER TEXT" in decoded
- assert "Paper text." in decoded
+ assert result == (
+ "Title: Paper\n\nSource: https://arxiv.org/abs/2301.12345"
+ )
- def test_without_metadata(self, downloader, mocker, mock_pdf_bytes):
- """Returns only extracted text bytes when metadata is None."""
+ def test_without_metadata(
+ self, downloader, mocker, mock_pdf_bytes, unavailable_arxiv_html
+ ):
+ """Returns extracted PDF text without querying API metadata."""
mocker.patch.object(
downloader, "_download_pdf", return_value=mock_pdf_bytes
)
mocker.patch.object(
downloader, "extract_text_from_pdf", return_value="Only text."
)
- mocker.patch.object(
+ api_fetch = mocker.patch.object(
downloader, "_fetch_from_arxiv_api", return_value=None
)
- result = downloader._download_text("https://arxiv.org/abs/2301.12345")
+ result = downloader.download_text("https://arxiv.org/abs/2301.12345")
- assert result is not None
- assert result.decode("utf-8") == "Only text."
+ assert result == (
+ "Only text.\n\nSource: https://arxiv.org/abs/2301.12345"
+ )
+ api_fetch.assert_not_called()
def test_invalid_id_returns_none(self, downloader):
"""Invalid URL that yields no arXiv ID should return None."""
- result = downloader._download_text("https://example.com/nothing")
+ result = downloader.download_text("https://example.com/nothing")
assert result is None
- def test_no_pdf_returns_none(self, downloader, mocker):
+ def test_no_pdf_returns_none(
+ self, downloader, mocker, unavailable_arxiv_html
+ ):
"""When PDF download fails, returns None."""
mocker.patch.object(downloader, "_download_pdf", return_value=None)
+ mocker.patch.object(
+ downloader, "_fetch_from_arxiv_api", return_value=None
+ )
- result = downloader._download_text("https://arxiv.org/abs/2301.12345")
+ result = downloader.download_text("https://arxiv.org/abs/2301.12345")
assert result is None
def test_no_extracted_text_returns_none(
- self, downloader, mocker, mock_pdf_bytes
+ self,
+ downloader,
+ mocker,
+ mock_pdf_bytes,
+ unavailable_arxiv_html,
):
"""When text extraction returns None, returns None."""
mocker.patch.object(
@@ -315,8 +376,11 @@ class TestDownloadText:
mocker.patch.object(
downloader, "extract_text_from_pdf", return_value=None
)
+ mocker.patch.object(
+ downloader, "_fetch_from_arxiv_api", return_value=None
+ )
- result = downloader._download_text("https://arxiv.org/abs/2301.12345")
+ result = downloader.download_text("https://arxiv.org/abs/2301.12345")
assert result is None
@@ -329,7 +393,7 @@ class TestFetchFromArxivApi:
"""Tests for the _fetch_from_arxiv_api method."""
def test_full_metadata_parsed(self, downloader, mocker):
- """Title, authors, abstract, and categories should all be parsed."""
+ """A matching Atom id is required before metadata fields are parsed."""
mock_resp = MagicMock()
mock_resp.status_code = 200
mock_resp.text = ARXIV_API_FULL_XML
@@ -344,9 +408,19 @@ class TestFetchFromArxivApi:
assert "We survey deep learning methods." in metadata
assert "cs.LG" in metadata
assert "stat.ML" in metadata
+ downloader.rate_tracker.apply_rate_limit.assert_called_once_with(
+ "arxiv_api"
+ )
+ downloader.rate_tracker.record_outcome.assert_called_once_with(
+ engine_type="arxiv_api",
+ wait_time=0.25,
+ success=True,
+ retry_count=1,
+ search_result_count=1,
+ )
def test_categories_with_empty_term_skipped(self, downloader, mocker):
- """Categories with empty term attribute should be filtered out."""
+ """Filter empty categories after verifying the fixture paper identity."""
mock_resp = MagicMock()
mock_resp.status_code = 200
mock_resp.text = ARXIV_API_CATEGORIES_ONLY_XML
@@ -363,14 +437,26 @@ class TestFetchFromArxivApi:
def test_exception_returns_none(self, downloader, mocker):
"""Any exception during API fetch should return None."""
+ import requests
+
mocker.patch.object(
downloader.session,
"get",
- side_effect=Exception("connection refused"),
+ side_effect=requests.exceptions.ConnectionError(
+ "connection refused"
+ ),
)
metadata = downloader._fetch_from_arxiv_api("2301.12345")
assert metadata is None
+ downloader.session.get.assert_called_once()
+ downloader.rate_tracker.record_outcome.assert_called_once_with(
+ engine_type="arxiv_api",
+ wait_time=0.25,
+ success=False,
+ retry_count=1,
+ error_type="ConnectionError",
+ )
def test_non_200_returns_none(self, downloader, mocker):
"""Non-200 status code returns None."""
@@ -380,9 +466,16 @@ class TestFetchFromArxivApi:
metadata = downloader._fetch_from_arxiv_api("2301.12345")
assert metadata is None
+ downloader.rate_tracker.record_outcome.assert_called_once_with(
+ engine_type="arxiv_api",
+ wait_time=0.25,
+ success=False,
+ retry_count=1,
+ error_type="HTTP_503",
+ )
def test_empty_entry_returns_none(self, downloader, mocker):
- """An entry with no title/authors/summary/categories returns None."""
+ """A matching id alone does not make an otherwise empty entry usable."""
mock_resp = MagicMock()
mock_resp.status_code = 200
mock_resp.text = ARXIV_API_EMPTY_ENTRY_XML
@@ -390,6 +483,13 @@ class TestFetchFromArxivApi:
metadata = downloader._fetch_from_arxiv_api("2301.12345")
assert metadata is None
+ downloader.rate_tracker.record_outcome.assert_called_once_with(
+ engine_type="arxiv_api",
+ wait_time=0.25,
+ success=False,
+ retry_count=1,
+ error_type="UnusableFeed",
+ )
def test_no_entry_in_feed_returns_none(self, downloader, mocker):
"""Feed with no <entry> element returns None."""
@@ -400,9 +500,38 @@ class TestFetchFromArxivApi:
metadata = downloader._fetch_from_arxiv_api("2301.12345")
assert metadata is None
+ downloader.rate_tracker.record_outcome.assert_called_once_with(
+ engine_type="arxiv_api",
+ wait_time=0.25,
+ success=False,
+ retry_count=1,
+ error_type="UnusableFeed",
+ )
+
+ def test_whitespace_only_entry_is_unusable(self, downloader, mocker):
+ # Given a matching paper id whose content fields contain only whitespace
+ mock_resp = MagicMock(
+ status_code=200,
+ text=ARXIV_API_WHITESPACE_ENTRY_XML,
+ )
+ mocker.patch.object(downloader.session, "get", return_value=mock_resp)
+
+ # When API metadata is parsed
+ metadata = downloader._fetch_from_arxiv_api("2301.12345")
+
+ # Then it is rejected and exactly one failure is tracked
+ assert metadata is None
+ downloader.rate_tracker.record_outcome.assert_called_once_with(
+ engine_type="arxiv_api",
+ wait_time=0.25,
+ success=False,
+ retry_count=1,
+ error_type="UnusableFeed",
+ )
- def test_old_format_id_cleans_slash(self, downloader, mocker):
- """Old-format ID with slash should have slash removed for API query."""
+ def test_versioned_legacy_id_is_preserved_as_api_param(
+ self, downloader, mocker
+ ):
mock_resp = MagicMock()
mock_resp.status_code = 200
mock_resp.text = ARXIV_API_NO_ENTRY_XML
@@ -410,11 +539,41 @@ class TestFetchFromArxivApi:
downloader.session, "get", return_value=mock_resp
)
- downloader._fetch_from_arxiv_api("cond-mat/0501234")
+ downloader._fetch_from_arxiv_api("math.AG/0601001v3")
+
+ mock_get.assert_called_once_with(
+ "https://export.arxiv.org/api/query",
+ params={"id_list": "math.AG/0601001v3"},
+ timeout=10,
+ allow_redirects=False,
+ )
+ downloader.rate_tracker.record_outcome.assert_called_once()
+
+ def test_malformed_feed_records_one_failure(self, downloader, mocker):
+ # Given a successful HTTP response containing malformed Atom XML
+ mock_resp = MagicMock(status_code=200, text="<feed><entry>")
+ mock_get = mocker.patch.object(
+ downloader.session, "get", return_value=mock_resp
+ )
+
+ # When the feed is parsed
+ metadata = downloader._fetch_from_arxiv_api("2301.12345v2")
- called_url = mock_get.call_args[0][0]
- assert "cond-mat0501234" in called_url
- assert "/" not in called_url.split("id_list=")[1]
+ # Then the request is not retried and one failed outcome is recorded
+ assert metadata is None
+ mock_get.assert_called_once_with(
+ "https://export.arxiv.org/api/query",
+ params={"id_list": "2301.12345v2"},
+ timeout=10,
+ allow_redirects=False,
+ )
+ downloader.rate_tracker.record_outcome.assert_called_once_with(
+ engine_type="arxiv_api",
+ wait_time=0.25,
+ success=False,
+ retry_count=1,
+ error_type="ParseError",
+ )
# ---------------------------------------------------------------------------
@@ -473,3 +632,69 @@ class TestPdfUrlConstruction:
assert "User-Agent" in headers
assert "application/pdf" in headers["Accept"]
assert headers["Connection"] == "keep-alive"
+
+
+ "entry_url",
+ [
+ None,
+ "http://arxiv.org/api/errors#incorrect_id_format_for_1234.12345",
+ "http://arxiv.org/abs/9999.99999v2",
+ "http://arxiv.org/abs/2301.12345v3",
+ "https://ar5iv.org/abs/2301.12345v2",
+ "https://arxiv.org/html/2301.12345v2",
+ ],
+)
+def test_api_rejects_entries_without_requested_paper_identity(
+ downloader, mocker, entry_url
+):
+ """An HTTP 200 feed must identify the requested paper and version."""
+ identity = f"<id>{entry_url}</id>" if entry_url is not None else ""
+ xml = (
+ '<feed xmlns="http://www.w3.org/2005/Atom"><entry>'
+ f"{identity}<title>Unrelated text</title><summary>Not the paper.</summary>"
+ "</entry></feed>"
+ )
+ mocker.patch.object(
+ downloader.session,
+ "get",
+ return_value=MagicMock(status_code=200, text=xml),
+ )
+
+ assert downloader._fetch_from_arxiv_api("2301.12345v2") is None
+ downloader.rate_tracker.record_outcome.assert_called_once_with(
+ engine_type="arxiv_api",
+ wait_time=0.25,
+ success=False,
+ retry_count=1,
+ error_type="UnusableFeed",
+ )
+
+
+ ("requested_id", "returned_id"),
+ [
+ ("2301.12345", "2301.12345v3"),
+ ("2301.12345v2", "2301.12345v2"),
+ ("math.AG/0601001", "math.AG/0601001v3"),
+ ("math.AG/0601001v3", "math.AG/0601001v3"),
+ ],
+)
+def test_api_accepts_matching_paper_metadata(
+ downloader, mocker, requested_id, returned_id
+):
+ """Unversioned queries may resolve to a version of the same paper."""
+ xml = (
+ '<feed xmlns="http://www.w3.org/2005/Atom"><entry>'
+ f"<id>http://arxiv.org/abs/{returned_id}</id>"
+ "<title>Matching paper</title></entry></feed>"
+ )
+ mocker.patch.object(
+ downloader.session,
+ "get",
+ return_value=MagicMock(status_code=200, text=xml),
+ )
+ assert (
+ downloader._fetch_from_arxiv_api(requested_id)
+ == "Title: Matching paper"
+ )
diff --git a/tests/research_library/downloaders/test_arxiv_html_text.py b/tests/research_library/downloaders/test_arxiv_html_text.py
new file mode 100644
index 0000000000..1a0d7c73f6
--- /dev/null
+++ b/tests/research_library/downloaders/test_arxiv_html_text.py
@@ -0,0 +1,841 @@
+import pytest
+
+from local_deep_research.research_library.downloaders.arxiv import (
+ MAX_MATH_ELEMENTS,
+ ArxivDownloader,
+ ArxivTextResult,
+ ArxivTextSource,
+)
+from local_deep_research.research_library.downloaders.base import ContentType
+from local_deep_research.utilities import arxiv_api
+
+
+def downloader():
+ return ArxivDownloader(timeout=30)
+
+
+def test_text_uses_official_html_and_preserves_tex(downloader, mocker):
+ # Given an ar5iv URL whose official arXiv HTML contains annotated MathML.
+ # The prose is repeated to a realistic length on purpose: a real LaTeXML
+ # rendition carries a title, authors, abstract and body and runs to tens
+ # of thousands of characters, so a few hundred would be indistinguishable
+ # from the "no HTML rendition" stub that
+ # MIN_STANDALONE_HTML_TEXT_LENGTH exists to reject. Repeating the body
+ # does not weaken what this test asserts, which is that the TeX
+ # annotation survives extraction.
+ 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>Versioned Paper</title></head>"
+ "<body><article><p>"
+ + body_prose
+ + "The central ratio is <math><semantics><mfrac><mi>a</mi><mi>b</mi>"
+ '</mfrac><annotation encoding="application/x-tex">\\frac{a}{b}'
+ "</annotation></semantics></math> and the remaining discussion explains "
+ "why this expression is useful in practice. Additional conclusions "
+ "describe the assumptions, the resulting bounds, and the implications "
+ "for future experiments.</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")
+ hard_clock = mocker.patch.object(
+ arxiv_api,
+ "_monotonic",
+ side_effect=AssertionError("HTML path touched API policy clock"),
+ )
+ hard_sleep = mocker.patch.object(
+ arxiv_api,
+ "_sleep",
+ side_effect=AssertionError("HTML path touched API policy sleep"),
+ )
+
+ # When text is downloaded from an ar5iv input
+ result = downloader.download_text_with_source(
+ "https://ar5iv.org/2501.12345v2"
+ )
+
+ # Then only official versioned HTML is fetched and normalized text is returned
+ assert result is not None
+ assert result.source is ArxivTextSource.ARXIV_HTML
+ text = result.text
+ assert r"\frac{a}{b}" in text
+ assert "Source: https://arxiv.org/abs/2501.12345v2" 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()
+ hard_clock.assert_not_called()
+ hard_sleep.assert_not_called()
+
+
+def test_pdf_path_does_not_touch_api_gate(downloader, mocker):
+ # Given a direct PDF download with tripwires on the API-only policy gate
+ hard_clock = mocker.patch.object(
+ arxiv_api,
+ "_monotonic",
+ side_effect=AssertionError("PDF path touched API policy clock"),
+ )
+ hard_sleep = mocker.patch.object(
+ arxiv_api,
+ "_sleep",
+ side_effect=AssertionError("PDF path touched API policy sleep"),
+ )
+ pdf_download = mocker.patch(
+ "local_deep_research.research_library.downloaders"
+ ".base.BaseDownloader._download_pdf",
+ return_value=b"%PDF-test",
+ )
+
+ # When the PDF path is used
+ content = downloader.download(
+ "https://arxiv.org/abs/2301.12345", ContentType.PDF
+ )
+
+ # Then no hard API gate state is consulted
+ assert content == b"%PDF-test"
+ pdf_download.assert_called_once()
+ hard_clock.assert_not_called()
+ hard_sleep.assert_not_called()
+
+
+ "unusable_math",
+ [
+ "<math><mi>x</mi></math>",
+ (
+ "<math><semantics><mi>x</mi>"
+ '<annotation encoding="application/x-tex"> </annotation>'
+ "</semantics></math>"
+ ),
+ ],
+ ids=["missing-tex-annotation", "empty-tex-annotation"],
+)
+def test_text_falls_back_when_any_math_lacks_usable_tex(
+ downloader, mocker, unusable_math
+):
+ # Given HTML with one valid formula and one unusable formula
+ html = (
+ "<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."
+ "</p></article></body></html>"
+ )
+ fetch_html = mocker.patch.object(
+ downloader,
+ "_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)
+
+ # When text is requested for a versioned legacy identifier
+ result = downloader.download_with_result(
+ "https://arxiv.org/html/math.AG/0601001v3?download=1#section",
+ ContentType.TEXT,
+ )
+
+ # Then the entire HTML document is rejected and the existing PDF path wins
+ assert result.is_success is True
+ assert result.content == (
+ b"PDF fallback text\n\nSource: https://arxiv.org/abs/math.AG/0601001v3"
+ )
+ fetch_html.assert_called_once_with(
+ "https://arxiv.org/html/math.AG/0601001v3"
+ )
+
+
+def _math_page(count: int) -> str:
+ """A rendition whose <math> elements all share one parent."""
+ formula = (
+ "<math><semantics><mi>x</mi>"
+ '<annotation encoding="application/x-tex">x^2</annotation>'
+ "</semantics></math> "
+ )
+ prose = (
+ "This article carries a very large number of typeset equations and "
+ "enough surrounding prose that the shared extraction pipeline keeps "
+ "the body. Each equation is followed by discussion of the bounds it "
+ "implies and the assumptions behind them. "
+ ) * 8
+ return (
+ "<html><head><title>Equation Heavy</title></head>"
+ "<body><article><p>" + prose + formula * count + "</p></article>"
+ "</body></html>"
+ )
+
+
+def test_text_falls_back_to_pdf_above_the_math_element_bound(
+ downloader, mocker
+):
+ # Given a rendition carrying one more equation than the bound allows.
+ # arXiv renders this HTML from author-submitted LaTeX and it is reached
+ # on the search path, so the work one page can demand has to be capped.
+ mocker.patch.object(
+ downloader,
+ "_fetch_html_with_final_url",
+ return_value=(
+ _math_page(MAX_MATH_ELEMENTS + 1),
+ "https://arxiv.org/html/2501.12345v2",
+ ),
+ )
+ 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)
+
+ # When text is requested
+ result = downloader.download_text_with_source(
+ "https://arxiv.org/abs/2501.12345v2"
+ )
+
+ # Then the page is not rewritten and the PDF path wins
+ assert result is not None
+ assert result.source is ArxivTextSource.LOCAL_PDF
+ assert "x^2" not in result.text
+
+
+def test_text_still_rewrites_a_page_at_the_math_element_bound(
+ downloader, mocker
+):
+ # Given a rendition exactly at the bound -- the guard caps the work an
+ # untrusted page can demand, it is not what makes the rewrite correct,
+ # and no page at or below it may be skipped
+ mocker.patch.object(
+ downloader,
+ "_fetch_html_with_final_url",
+ return_value=(
+ _math_page(MAX_MATH_ELEMENTS),
+ "https://arxiv.org/html/2501.12345v2",
+ ),
+ )
+ pdf_download = mocker.patch.object(downloader, "_download_pdf")
+ mocker.patch.object(downloader, "_fetch_from_arxiv_api")
+
+ # When text is requested
+ result = downloader.download_text_with_source(
+ "https://arxiv.org/abs/2501.12345v2"
+ )
+
+ # Then the TeX is preserved from the HTML and no PDF is fetched
+ assert result is not None
+ assert result.source is ArxivTextSource.ARXIV_HTML
+ assert "x^2" in result.text
+ assert "<math" not in result.text
+ assert "application/x-tex" not in result.text
+ pdf_download.assert_not_called()
+
+
+def test_small_page_with_shared_parent_still_rewrites_every_formula(
+ downloader,
+):
+ # Given a handful of equations under one parent -- the shape the old
+ # replace_with loop made quadratic
+ from bs4 import BeautifulSoup
+
+ soup = BeautifulSoup(_math_page(5), "lxml")
+
+ # When the rewrite runs
+ rewritten = downloader._rewrite_math_to_tex(soup, "2501.12345v2")
+
+ # Then every formula is replaced by its TeX, in document order
+ assert rewritten is True
+ assert soup.find_all("math") == []
+ assert soup.get_text().count("x^2") == 5
+
+
+def test_math_element_bound_is_five_thousand():
+ # The two tests above build their pages from MAX_MATH_ELEMENTS, so they
+ # pass for any value of it, including one small enough to reject every
+ # real paper. Pin the number itself: changing it is a deliberate act
+ # that has to be made here as well.
+ assert MAX_MATH_ELEMENTS == 5000
+
+
+def test_rewrite_renames_in_place_and_never_calls_replace_with(
+ downloader, mocker
+):
+ # Given equations sharing one parent. Tag.replace_with locates the
+ # element by scanning that parent's contents, so using it here is what
+ # made the loop O(n^2); the bound above caps the damage but does not
+ # prevent the regression, and the rewrite's output is identical either
+ # way, so nothing else in this file can tell the two apart.
+ from bs4 import BeautifulSoup
+ from bs4.element import PageElement
+
+ soup = BeautifulSoup(_math_page(5), "lxml")
+ replace_with = mocker.spy(PageElement, "replace_with")
+
+ # When the rewrite runs
+ rewritten = downloader._rewrite_math_to_tex(soup, "2501.12345v2")
+
+ # Then it mutates each element where it stands -- renamed to a <span>
+ # holding only the TeX -- and never reaches for replace_with
+ assert rewritten is True
+ replace_with.assert_not_called()
+ spans = [
+ tag
+ for tag in soup.find_all("span")
+ if tag.get_text() == "x^2" and not tag.attrs
+ ]
+ assert len(spans) == 5
+
+
+def test_namespace_prefixed_mathml_is_rewritten_too(downloader, mocker):
+ # Given a rendition whose MathML is namespace-prefixed. lxml's HTML
+ # parser keeps the prefix in the tag name, so matching the literal tag
+ # "math" finds nothing here and the page is accepted with its MathML
+ # left in place. On this page newspaper4k's text then wins the
+ # extractor tiebreak and keeps the <m:mi> symbol glued to the TeX
+ # ("x\\frac{1}{2}"); on other pages the equation is dropped instead. The
+ # glued form is what this fixture produces without the rewrite, so the
+ # sentence arriving clean is what distinguishes the rewrite from a
+ # revert.
+ prose = (
+ "This article states a bound and then discusses the assumptions "
+ "behind it at length, so the shared extraction pipeline keeps the "
+ "article body rather than discarding it as boilerplate. "
+ ) * 40
+ page = (
+ "<html><head><title>Prefixed MathML</title></head>"
+ "<body><article><p>" + prose + "The bound is "
+ "<m:math><m:semantics><m:mi>x</m:mi>"
+ '<m:annotation encoding="application/x-tex">\\frac{1}{2}'
+ "</m:annotation></m:semantics></m:math> throughout."
+ "</p></article></body></html>"
+ )
+ mocker.patch.object(
+ downloader,
+ "_fetch_html_with_final_url",
+ return_value=(page, "https://arxiv.org/html/2501.12345v2"),
+ )
+ pdf_download = mocker.patch.object(downloader, "_download_pdf")
+ mocker.patch.object(downloader, "_fetch_from_arxiv_api")
+
+ # When text is requested
+ result = downloader.download_text_with_source(
+ "https://arxiv.org/abs/2501.12345v2"
+ )
+
+ # Then the TeX is stored clean, without the <m:mi> symbol glued to it,
+ # and no PDF is fetched
+ assert result is not None
+ assert result.source is ArxivTextSource.ARXIV_HTML
+ assert "The bound is \\frac{1}{2} throughout." in result.text
+ pdf_download.assert_not_called()
+
+
+def test_text_falls_back_when_html_extracts_no_content(downloader, mocker):
+ # Given available HTML that has no meaningful article content
+ mocker.patch.object(
+ downloader,
+ "_fetch_html_with_final_url",
+ return_value=(
+ "<html><body><p>Short.</p></body></html>",
+ "https://arxiv.org/html/2301.12345",
+ ),
+ )
+ mocker.patch.object(downloader, "_download_pdf", return_value=b"%PDF-test")
+ mocker.patch.object(
+ downloader, "extract_text_from_pdf", return_value="Recovered PDF text"
+ )
+ mocker.patch.object(downloader, "_fetch_from_arxiv_api", return_value=None)
+
+ # When text is requested
+ result = downloader.download_with_result(
+ "https://arxiv.org/abs/2301.12345", ContentType.TEXT
+ )
+
+ # Then empty HTML extraction falls back to the existing PDF path
+ assert result.is_success is True
+ assert result.content == (
+ b"Recovered PDF text\n\nSource: https://arxiv.org/abs/2301.12345"
+ )
+
+
+def test_text_falls_back_when_html_pipeline_cannot_be_used(downloader, mocker):
+ # Given HTML whose extraction pipeline unexpectedly cannot process it
+ mocker.patch.object(
+ downloader,
+ "_fetch_html_with_final_url",
+ return_value=(
+ "<html><body><article>content</article></body></html>",
+ "https://arxiv.org/html/2301.12345",
+ ),
+ )
+ mocker.patch.object(
+ downloader,
+ "_extract_content",
+ side_effect=RuntimeError("malformed HTML"),
+ )
+ mocker.patch.object(downloader, "_download_pdf", return_value=b"%PDF-test")
+ mocker.patch.object(
+ downloader,
+ "extract_text_from_pdf",
+ return_value="PDF after malformed HTML",
+ )
+ mocker.patch.object(downloader, "_fetch_from_arxiv_api", return_value=None)
+
+ # When text is requested
+ result = downloader.download_with_result(
+ "https://arxiv.org/abs/2301.12345", ContentType.TEXT
+ )
+
+ # Then the failure is contained and the existing PDF path is used
+ assert result.is_success is True
+ assert result.content == (
+ b"PDF after malformed HTML\n\nSource: https://arxiv.org/abs/2301.12345"
+ )
+
+
+def test_text_entrypoints_share_the_same_download_seam(downloader, mocker):
+ # Given a successful text behavior seam
+ text_download = mocker.patch.object(
+ downloader, "download_text", return_value="shared text"
+ )
+ mocker.patch.object(
+ downloader,
+ "_download_pdf",
+ side_effect=AssertionError("text entrypoint bypassed shared seam"),
+ )
+ url = "https://arxiv.org/abs/2301.12345v4"
+
+ # When both public text entrypoints are used
+ content = downloader.download(url, ContentType.TEXT)
+ result = downloader.download_with_result(url, ContentType.TEXT)
+
+ # Then both expose the same bytes through that one seam
+ assert content == b"shared text"
+ assert result.is_success is True
+ assert result.content == b"shared text"
+ assert text_download.call_count == 2
+
+
+def test_download_text_reuses_supplied_pdf_bytes(downloader, mocker):
+ # Given unavailable HTML and PDF bytes already downloaded by the caller
+ pdf_content = b"%PDF-already-downloaded"
+ mocker.patch.object(downloader, "_download_html_text", return_value=None)
+ pdf_download = mocker.patch.object(
+ downloader,
+ "_download_pdf",
+ side_effect=AssertionError("supplied PDF bytes were downloaded again"),
+ )
+ extract_text = mocker.patch.object(
+ downloader,
+ "extract_text_from_pdf",
+ return_value="Text from supplied PDF",
+ )
+ api_fetch = mocker.patch.object(downloader, "_fetch_from_arxiv_api")
+
+ # When the public text seam receives those bytes
+ result = downloader.download_text(
+ "https://arxiv.org/abs/2301.12345",
+ pdf_content=pdf_content,
+ )
+
+ # Then it extracts those exact bytes without another PDF or API request
+ assert result == (
+ "Text from supplied PDF\n\nSource: https://arxiv.org/abs/2301.12345"
+ )
+ extract_text.assert_called_once_with(pdf_content)
+ pdf_download.assert_not_called()
+ api_fetch.assert_not_called()
+
+
+def test_download_text_treats_empty_pdf_bytes_as_supplied(downloader, mocker):
+ # Given unavailable HTML and explicitly supplied empty PDF bytes
+ mocker.patch.object(downloader, "_download_html_text", return_value=None)
+ pdf_download = mocker.patch.object(
+ downloader,
+ "_download_pdf",
+ side_effect=AssertionError("empty supplied bytes triggered a download"),
+ )
+ extract_text = mocker.patch.object(
+ downloader,
+ "extract_text_from_pdf",
+ return_value=None,
+ )
+ api_fetch = mocker.patch.object(
+ downloader,
+ "_fetch_from_arxiv_api",
+ return_value="API metadata and abstract",
+ )
+
+ # When text production receives the empty bytes
+ result = downloader.download_text(
+ "https://ar5iv.org/2301.12345v2",
+ pdf_content=b"",
+ )
+
+ # Then no PDF is redownloaded and the final API fallback remains available
+ assert result == (
+ "API metadata and abstract\n\n"
+ "Source: https://arxiv.org/abs/2301.12345v2"
+ )
+ extract_text.assert_called_once_with(b"")
+ pdf_download.assert_not_called()
+ api_fetch.assert_called_once_with("2301.12345v2")
+
+
+def test_download_text_with_source_reports_local_pdf(downloader, mocker):
+ # Given unavailable HTML and exact PDF bytes supplied by the caller
+ pdf_content = b"%PDF-reused-exactly"
+ mocker.patch.object(downloader, "_download_html_text", return_value=None)
+ extract_text = mocker.patch.object(
+ downloader,
+ "extract_text_from_pdf",
+ return_value="PDF body with trailing whitespace\n\n",
+ )
+ api_fetch = mocker.patch.object(downloader, "_fetch_from_arxiv_api")
+
+ # When typed text production succeeds from those bytes
+ result = downloader.download_text_with_source(
+ "https://arxiv.org/abs/2301.12345v4",
+ pdf_content=pdf_content,
+ )
+
+ # Then the source is typed and canonical attribution has one blank line
+ assert result == ArxivTextResult(
+ text=(
+ "PDF body with trailing whitespace\n\n"
+ "Source: https://arxiv.org/abs/2301.12345v4"
+ ),
+ source=ArxivTextSource.LOCAL_PDF,
+ )
+ extract_text.assert_called_once_with(pdf_content)
+ api_fetch.assert_not_called()
+
+
+def test_download_text_with_source_reports_arxiv_api(downloader, mocker):
+ # Given unavailable HTML and PDF text with usable API metadata
+ mocker.patch.object(downloader, "_download_html_text", return_value=None)
+ mocker.patch.object(downloader, "_download_pdf", return_value=None)
+ mocker.patch.object(
+ downloader,
+ "_fetch_from_arxiv_api",
+ return_value="Title: API fallback",
+ )
+
+ # When typed text production reaches its final source
+ result = downloader.download_text_with_source(
+ "https://ar5iv.org/math.AG/0601001v3"
+ )
+
+ # Then the API source and version-preserving attribution are retained
+ assert result == ArxivTextResult(
+ text=(
+ "Title: API fallback\n\n"
+ "Source: https://arxiv.org/abs/math.AG/0601001v3"
+ ),
+ source=ArxivTextSource.ARXIV_API,
+ )
+
+
+def test_download_text_delegates_to_typed_result(downloader, mocker):
+ # Given a typed HTML result
+ typed_result = ArxivTextResult(
+ text="typed text",
+ source=ArxivTextSource.ARXIV_HTML,
+ )
+ typed_download = mocker.patch.object(
+ downloader,
+ "download_text_with_source",
+ return_value=typed_result,
+ )
+
+ # When the compatibility method is called
+ result = downloader.download_text(
+ "https://arxiv.org/abs/2301.12345", pdf_content=b"existing"
+ )
+
+ # Then it exposes only text while preserving the typed seam internally
+ assert result == "typed text"
+ typed_download.assert_called_once_with(
+ "https://arxiv.org/abs/2301.12345",
+ pdf_content=b"existing",
+ )
+
+
+def test_download_text_rejects_invalid_url_without_requests(downloader, mocker):
+ # Given tripwires on every text source
+ html_download = mocker.patch.object(downloader, "_download_html_text")
+ pdf_download = mocker.patch.object(downloader, "_download_pdf")
+ api_fetch = mocker.patch.object(downloader, "_fetch_from_arxiv_api")
+
+ # When an invalid identifier reaches the public text seam
+ result = downloader.download_text(
+ "https://example.com/not-arxiv",
+ pdf_content=b"ignored",
+ )
+
+ # Then it is rejected before any source is queried
+ assert result is None
+ html_download.assert_not_called()
+ pdf_download.assert_not_called()
+ api_fetch.assert_not_called()
+
+
+# arXiv answers /html/{id} with a stub page for papers that have no HTML
+# rendition. It is short, but long enough to clear the extraction pipeline's
+# minimum content length, so only a comparison against the PDF rejects it.
+DEGENERATE_ARXIV_HTML_STUB = (
+ "<html><head><title>No HTML for 2301.12345</title></head>"
+ "<body><article><p>"
+ "No HTML rendition is available for this submission. The authors did not "
+ "provide a LaTeX source that arXiv could convert, so please consult the "
+ "PDF version of the paper instead. This notice is generated automatically "
+ "for every submission without an HTML rendition."
+ "</p></article></body></html>"
+)
+
+FULL_PDF_TEXT = (
+ "This is the complete body of the paper as extracted from the PDF. "
+) * 40
+
+
+def test_text_keeps_pdf_when_html_is_a_degenerate_stub(downloader, mocker):
+ # Given a stub HTML page that extracts cleanly but carries no paper, and
+ # complete PDF text already in hand from the same call
+ fetch_html = mocker.patch.object(
+ downloader,
+ "_fetch_html_with_final_url",
+ return_value=(
+ DEGENERATE_ARXIV_HTML_STUB,
+ "https://arxiv.org/html/2301.12345",
+ ),
+ )
+ mocker.patch.object(
+ downloader,
+ "extract_text_from_pdf",
+ return_value=FULL_PDF_TEXT,
+ )
+ pdf_download = mocker.patch.object(
+ downloader,
+ "_download_pdf",
+ side_effect=AssertionError("PDF already in hand was redownloaded"),
+ )
+ api_fetch = mocker.patch.object(downloader, "_fetch_from_arxiv_api")
+
+ # When text is produced with those PDF bytes supplied
+ result = downloader.download_text_with_source(
+ "https://arxiv.org/abs/2301.12345",
+ pdf_content=b"%PDF-complete",
+ )
+
+ # Then the stub loses to the PDF text it would otherwise have replaced
+ assert result is not None
+ assert result.source is ArxivTextSource.LOCAL_PDF
+ assert result.text == (
+ f"{FULL_PDF_TEXT.rstrip()}\n\nSource: https://arxiv.org/abs/2301.12345"
+ )
+ fetch_html.assert_called_once_with("https://arxiv.org/html/2301.12345")
+ pdf_download.assert_not_called()
+ api_fetch.assert_not_called()
+
+
+def test_text_falls_back_to_pdf_when_a_stub_arrives_with_no_pdf_in_hand(
+ downloader, mocker
+):
+ """The ratio guard cannot fire when there is no PDF text to compare to.
+
+ This is the path every text-first caller takes -- ContentFetcher.fetch,
+ pipeline.fetch_and_extract, and download_service's first-ever text
+ extraction all call in with ``pdf_content=None``. Before the standalone
+ floor, ``_html_text_beats_pdf_text`` returned True immediately for those,
+ so a stub was returned as ARXIV_HTML and persisted as high quality while
+ the PDF was never fetched at all.
+ """
+ # Given the same stub, but with no PDF bytes supplied by the caller
+ mocker.patch.object(
+ downloader,
+ "_fetch_html_with_final_url",
+ return_value=(
+ DEGENERATE_ARXIV_HTML_STUB,
+ "https://arxiv.org/html/2301.12345",
+ ),
+ )
+ pdf_download = mocker.patch.object(
+ downloader, "_download_pdf", return_value=b"%PDF-complete"
+ )
+ mocker.patch.object(
+ downloader, "extract_text_from_pdf", return_value=FULL_PDF_TEXT
+ )
+ api_fetch = mocker.patch.object(downloader, "_fetch_from_arxiv_api")
+
+ # When text is produced without PDF bytes
+ result = downloader.download_text_with_source(
+ "https://arxiv.org/abs/2301.12345"
+ )
+
+ # Then the stub is refused and the PDF is fetched instead -- the
+ # behaviour these paths had before HTML-first existed.
+ assert result is not None
+ assert result.source is ArxivTextSource.LOCAL_PDF
+ assert result.text == (
+ f"{FULL_PDF_TEXT.rstrip()}\n\nSource: https://arxiv.org/abs/2301.12345"
+ )
+ pdf_download.assert_called_once()
+ api_fetch.assert_not_called()
+
+
+def test_text_rejects_html_served_from_a_redirected_url(downloader, mocker):
+ # Given a full-length HTML body that was served from the abstract page
+ # rather than from the requested HTML rendition
+ redirected_html = (
+ "<html><body><article><p>"
+ + (
+ "The abstract landing page repeats enough prose that content "
+ "extraction succeeds and returns a long document. "
+ )
+ * 20
+ + "</p></article></body></html>"
+ )
+ mocker.patch.object(
+ downloader,
+ "_fetch_html_with_final_url",
+ return_value=(redirected_html, "https://arxiv.org/abs/2301.12345"),
+ )
+ mocker.patch.object(
+ downloader, "extract_text_from_pdf", return_value="Authoritative PDF"
+ )
+ api_fetch = mocker.patch.object(downloader, "_fetch_from_arxiv_api")
+
+ # When text is produced
+ result = downloader.download_text_with_source(
+ "https://arxiv.org/abs/2301.12345",
+ pdf_content=b"%PDF-complete",
+ )
+
+ # Then the redirected body is refused regardless of its length
+ assert result is not None
+ assert result.source is ArxivTextSource.LOCAL_PDF
+ assert result.text == (
+ "Authoritative PDF\n\nSource: https://arxiv.org/abs/2301.12345"
+ )
+ api_fetch.assert_not_called()
+
+
+ "final_url",
+ [
+ "https://arxiv.org/html/9999.99999v2",
+ "https://arxiv.org/html/2301.12345v3",
+ "https://arxiv.org/html/2301.12345",
+ "https://ar5iv.org/html/2301.12345v2",
+ "https://arxiv.org/html/not-an-id",
+ "https://arxiv.org.evil.example/html/2301.12345v2",
+ "http://arxiv.org/html/2301.12345v2",
+ "https://arxiv.org:8443/html/2301.12345v2",
+ "https://[email protected]/html/2301.12345v2",
+ ],
+)
+def test_html_identity_failure_preserves_supplied_pdf(
+ downloader, mocker, final_url
+):
+ """A different source cannot replace the PDF under its citation."""
+ mocker.patch.object(
+ downloader,
+ "_fetch_html_with_final_url",
+ return_value=("<html>Unrelated paper</html>", final_url),
+ )
+ extract_html = mocker.patch.object(downloader, "_extract_content")
+ mocker.patch.object(
+ downloader, "extract_text_from_pdf", return_value="Requested PDF text"
+ )
+ pdf_download = mocker.patch.object(downloader, "_download_pdf")
+ api_fetch = mocker.patch.object(downloader, "_fetch_from_arxiv_api")
+
+ result = downloader.download_text_with_source(
+ "https://arxiv.org/abs/2301.12345v2", pdf_content=b"%PDF-existing"
+ )
+ assert result is not None
+ assert result.source is ArxivTextSource.LOCAL_PDF
+ assert result.text == (
+ "Requested PDF text\n\nSource: https://arxiv.org/abs/2301.12345v2"
+ )
+ extract_html.assert_not_called()
+ pdf_download.assert_not_called()
+ api_fetch.assert_not_called()
+
+
+ ("final_url", "accepted"),
+ [
+ ("https://ar5iv.labs.arxiv.org/html/2301.12345v2", True),
+ ("https://ar5iv.org/html/2301.12345v2", False),
+ ],
+)
+def test_ar5iv_acceptance_follows_the_arxiv_org_trust_boundary(
+ downloader, mocker, final_url, accepted
+):
+ # Given a rendition served from an ar5iv host. The boundary the identity
+ # check enforces is the ``.arxiv.org`` suffix, so the host the real ar5iv
+ # service runs on is inside it while the bare ar5iv.org domain -- an
+ # input identifier only -- is not.
+ mocker.patch.object(
+ downloader,
+ "_fetch_html_with_final_url",
+ return_value=("<html>Paper</html>", final_url),
+ )
+ extract = mocker.patch.object(
+ downloader,
+ "_extract_content",
+ return_value={"content": "rendition text"},
+ )
+
+ # When the HTML rendition is requested
+ result = downloader._download_html_text("2301.12345v2")
+
+ # Then only the in-boundary host is treated as authoritative
+ assert result == ("rendition text" if accepted else None)
+ assert extract.called is accepted
+
+
+ ("requested_id", "returned_id"),
+ [
+ ("2301.12345", "2301.12345v3"),
+ ("2301.12345v2", "2301.12345v2"),
+ ("math.AG/0601001", "math.AG/0601001v3"),
+ ("math.AG/0601001v3", "math.AG/0601001v3"),
+ ],
+)
+def test_html_accepts_matching_rendition(
+ downloader, mocker, requested_id, returned_id
+):
+ """Keep valid canonical redirects, including legacy paper identifiers."""
+ mocker.patch.object(
+ downloader,
+ "_fetch_html_with_final_url",
+ return_value=(
+ "<html>Paper</html>",
+ f"https://arxiv.org/html/{returned_id}",
+ ),
+ )
+ extract = mocker.patch.object(
+ downloader,
+ "_extract_content",
+ return_value={"content": "matching paper"},
+ )
+ assert downloader._download_html_text(requested_id) == "matching paper"
+ extract.assert_called_once_with(
+ mocker.ANY, f"https://arxiv.org/abs/{requested_id}"
+ )
diff --git a/tests/research_library/downloaders/test_extraction_pipeline.py b/tests/research_library/downloaders/test_extraction_pipeline.py
index 27bd414c50..1751d0f766 100644
--- a/tests/research_library/downloaders/test_extraction_pipeline.py
+++ b/tests/research_library/downloaders/test_extraction_pipeline.py
@@ -8,9 +8,16 @@ All extractors are monkeypatched — no network, no DB, no optional deps.
"""
from unittest.mock import Mock
+from typing import NamedTuple
+import pytest
from local_deep_research.research_library.downloaders.extraction import pipeline
+from local_deep_research.research_library.downloaders.base import (
+ BaseDownloader,
+ ContentType,
+ DownloadResult,
+)
# ---------------------------------------------------------------------------
@@ -22,6 +29,17 @@ def _html(body: str, head: str = "") -> str:
return f"<html><head>{head}</head><body>{body}</body></html>"
+class _SpecializedState(NamedTuple):
+ content: str | None
+ fallback_allowed: bool
+
+
+def _specialized(
+ content: str | None = None, fallback_allowed: bool = True
+) -> _SpecializedState:
+ return _SpecializedState(content, fallback_allowed)
+
+
LONG_TEXT = "A " * 600 # 1200 chars — above METADATA_ENRICHMENT_THRESHOLD
SHORT_TEXT = "Short content that passes min length but is under enrichment threshold okay."
TINY_TEXT = "tiny"
@@ -418,68 +436,109 @@ class TestExtractContentWithMetadata:
class TestTrySpecializedDownloader:
- def test_non_academic_url_returns_none(self):
+ def test_non_academic_url_allows_fallback(self):
result = pipeline._try_specialized_downloader(
"https://example.com/page"
)
- assert result is None
+ assert result.content is None
+ assert result.fallback_allowed is True
+
+ def test_trailing_dot_ar5iv_lookalike_allows_fallback(self):
+ result = pipeline._try_specialized_downloader(
+ "https://ar5iv.org.example.com./2301.12345"
+ )
+ assert result.content is None
+ assert result.fallback_allowed is True
+
+ @pytest.mark.parametrize(
+ "url",
+ (
+ "https://ARXIV.ORG./not-an-arxiv-id",
+ "https://EXPORT.ARXIV.ORG./not-an-arxiv-id",
+ "https://arxiv.org/abs/not-an-id",
+ "https://arxiv.org/list/cs.AI/recent",
+ "https://info.arxiv.org/help/api/tou.html",
+ "https://arxiv.org/ftp/arxiv/papers/2301/2301.12345.pdf",
+ ),
+ )
+ def test_arxiv_host_without_an_identifier_allows_fallback(self, url):
+ # Given an owned arXiv host whose path names no paper
+ # When specialization is attempted
+ result = pipeline._try_specialized_downloader(url)
+
+ # Then ownership is not claimed, because the arXiv downloader has no
+ # canonical source for these and terminal ownership would return
+ # nothing where generic extraction returns the page
+ assert result.content is None
+ assert result.fallback_allowed is True
def test_arxiv_url_routes_to_downloader(self, monkeypatch):
- mock_result = Mock()
- mock_result.is_success = True
- mock_result.content = b"Extracted arXiv paper text " * 10
+ # Given an exact dynamically imported BaseDownloader implementation
+ instances = []
- mock_downloader = Mock()
- mock_downloader.download_with_result.return_value = mock_result
+ class StubArxivDownloader(BaseDownloader):
+ def __init__(self, timeout=30):
+ self.timeout = timeout
+ self.closed = False
+ instances.append(self)
+
+ def can_handle(self, url):
+ return True
+
+ def download(self, url, content_type=ContentType.TEXT):
+ return b"Extracted arXiv paper text " * 10
+
+ def download_with_result(self, url, content_type=ContentType.TEXT):
+ return DownloadResult(
+ content=b"Extracted arXiv paper text " * 10,
+ is_success=True,
+ )
+
+ def close(self):
+ self.closed = True
- monkeypatch.setattr(
- "local_deep_research.research_library.downloaders.extraction.pipeline.ArxivDownloader",
- lambda timeout: mock_downloader,
- raising=False,
- )
- # Need to patch the import inside _try_specialized_downloader
import local_deep_research.research_library.downloaders.arxiv as arxiv_mod
- monkeypatch.setattr(
- arxiv_mod,
- "ArxivDownloader",
- lambda timeout: mock_downloader,
- raising=False,
- )
+ monkeypatch.setattr(arxiv_mod, "ArxivDownloader", StubArxivDownloader)
+ # When the arXiv specialization is requested
result = pipeline._try_specialized_downloader(
- "https://arxiv.org/abs/2301.00001"
+ "https://AR5IV.ORG./2301.00001v2"
)
- # May return None if the lazy import structure doesn't match our mock —
- # the important thing is it doesn't crash
- # If it returns content, verify it's correct
- if result is not None:
- assert "arXiv" in result or "Extracted" in result
+
+ # Then exact content is returned terminally and the downloader is closed
+ assert result.content == "Extracted arXiv paper text " * 10
+ assert result.fallback_allowed is False
+ assert len(instances) == 1
+ assert instances[0].closed is True
def test_specialized_downloader_failure_returns_none(self, monkeypatch):
- # Force the specialized downloader to report failure (no network —
- # matches the module's "all extractors are monkeypatched" contract).
- mock_result = Mock()
- mock_result.is_success = False
- mock_result.content = None
+ class FailingArxivDownloader(BaseDownloader):
+ def __init__(self, timeout=30):
+ self.timeout = timeout
- mock_downloader = Mock()
- mock_downloader.download_with_result.return_value = mock_result
+ def can_handle(self, url):
+ return True
+
+ def download(self, url, content_type=ContentType.TEXT):
+ return None
+
+ def download_with_result(self, url, content_type=ContentType.TEXT):
+ return DownloadResult(skip_reason="unavailable")
+
+ def close(self):
+ return None
import local_deep_research.research_library.downloaders.arxiv as arxiv_mod
monkeypatch.setattr(
- arxiv_mod,
- "ArxivDownloader",
- lambda timeout: mock_downloader,
- raising=False,
+ arxiv_mod, "ArxivDownloader", FailingArxivDownloader
)
-
result = pipeline._try_specialized_downloader(
- "https://arxiv.org/abs/2301.00001"
+ "https://ar5iv.org/2301.00001v2"
)
- # Should gracefully return None, never raise
- assert result is None
+ assert result.content is None
+ assert result.fallback_allowed is False
def test_import_error_returns_none(self, monkeypatch):
"""If url_classifier can't be imported, returns None."""
@@ -493,7 +552,36 @@ class TestTrySpecializedDownloader:
# This should trigger ImportError inside the function
# But since the module is already imported, we need a different approach
result = pipeline._try_specialized_downloader("https://example.com")
- assert result is None
+ assert result.content is None
+ assert result.fallback_allowed is True
+
+ @pytest.mark.parametrize(
+ ("url", "fallback_allowed"),
+ (
+ ("https://AR5IV.ORG./2301.12345v2", False),
+ ("https://ARXIV.ORG./abs/2301.12345", False),
+ ("https://AR5IV.ORG./not-an-arxiv-id", True),
+ ("https://ARXIV.ORG./not-an-arxiv-id", True),
+ ),
+ )
+ def test_import_error_keeps_arxiv_paper_terminal(
+ self, monkeypatch, url, fallback_allowed
+ ):
+ # Given the classifier import is unavailable
+ import sys
+
+ monkeypatch.setitem(
+ sys.modules,
+ "local_deep_research.content_fetcher.url_classifier",
+ None,
+ )
+
+ # When the owned host reaches specialization
+ result = pipeline._try_specialized_downloader(url)
+
+ # Then the paper identifier, not the host, decides the fallback
+ assert result.content is None
+ assert result.fallback_allowed is fallback_allowed
# ---------------------------------------------------------------------------
@@ -506,7 +594,9 @@ class TestFetchAndExtract:
monkeypatch.setattr(
pipeline,
"_try_specialized_downloader",
- lambda url, timeout=30: "Specialized content from academic source",
+ lambda url, timeout=30: _specialized(
+ "Specialized content from academic source", False
+ ),
)
result = pipeline.fetch_and_extract("https://arxiv.org/abs/1234")
assert result == "Specialized content from academic source"
@@ -515,7 +605,7 @@ class TestFetchAndExtract:
monkeypatch.setattr(
pipeline,
"_try_specialized_downloader",
- lambda url, timeout=30: None,
+ lambda url, timeout=30: _specialized(),
)
mock_downloader = Mock()
@@ -535,7 +625,7 @@ class TestFetchAndExtract:
monkeypatch.setattr(
pipeline,
"_try_specialized_downloader",
- lambda url, timeout=30: None,
+ lambda url, timeout=30: _specialized(),
)
mock_downloader = Mock()
@@ -554,7 +644,7 @@ class TestFetchAndExtract:
monkeypatch.setattr(
pipeline,
"_try_specialized_downloader",
- lambda url, timeout=30: None,
+ lambda url, timeout=30: _specialized(),
)
mock_downloader = Mock()
@@ -569,6 +659,118 @@ class TestFetchAndExtract:
result = pipeline.fetch_and_extract("https://example.com")
assert result is None
+ def test_arxiv_terminal_failure_does_not_use_html(self, monkeypatch):
+ # Given terminal specialized failure for an ar5iv input
+ monkeypatch.setattr(
+ pipeline,
+ "_try_specialized_downloader",
+ lambda url, timeout=30: _specialized(fallback_allowed=False),
+ )
+ mock_class = Mock()
+ monkeypatch.setattr(
+ "local_deep_research.research_library.downloaders.playwright_html.AutoHTMLDownloader",
+ mock_class,
+ )
+
+ # When the single-URL pipeline runs
+ result = pipeline.fetch_and_extract("https://ar5iv.org/2301.12345v2")
+
+ # Then failure is terminal without targeting the original host
+ assert result is None
+ mock_class.assert_not_called()
+
+ @pytest.mark.parametrize(
+ "url",
+ (
+ "https://ARXIV.ORG./not-an-arxiv-id",
+ "https://arxiv.org/list/cs.AI/recent",
+ ),
+ )
+ def test_arxiv_page_without_an_identifier_uses_html(self, monkeypatch, url):
+ # Given a generic HTML downloader that returns page text
+ instance = Mock()
+ instance.download.return_value = b"generic page text " * 10
+ mock_class = Mock(return_value=instance)
+ monkeypatch.setattr(
+ "local_deep_research.research_library.downloaders.playwright_html.AutoHTMLDownloader",
+ mock_class,
+ )
+
+ # When an owned arXiv URL names no paper
+ result = pipeline.fetch_and_extract(url)
+
+ # Then the generic pipeline runs: these pages had text on main, and
+ # the arXiv downloader has no source that could replace it
+ assert result == "generic page text " * 10
+ mock_class.assert_called_once()
+
+ def test_arxiv_paper_failure_does_not_use_html(self, monkeypatch):
+ # Given a real arXiv downloader that produces nothing, and a generic
+ # HTML constructor tripwire
+ class FailingArxivDownloader(BaseDownloader):
+ def __init__(self, timeout=30):
+ self.timeout = timeout
+
+ def can_handle(self, url):
+ return True
+
+ def download(self, url, content_type=ContentType.TEXT):
+ return None
+
+ def download_with_result(self, url, content_type=ContentType.TEXT):
+ return DownloadResult(
+ skip_reason="Could not retrieve full text"
+ )
+
+ def close(self):
+ return None
+
+ import local_deep_research.research_library.downloaders.arxiv as arxiv_mod
+
+ monkeypatch.setattr(
+ arxiv_mod, "ArxivDownloader", FailingArxivDownloader
+ )
+ mock_class = Mock()
+ monkeypatch.setattr(
+ "local_deep_research.research_library.downloaders.playwright_html.AutoHTMLDownloader",
+ mock_class,
+ )
+
+ # When an owned arXiv paper URL fails specialization
+ result = pipeline.fetch_and_extract("https://ar5iv.org/2301.12345v2")
+
+ # Then specialization fails terminally before generic HTML construction
+ assert result is None
+ mock_class.assert_not_called()
+
+ @pytest.mark.parametrize(
+ "url",
+ (
+ "https://ar5iv.org/2301.12345v2",
+ "https://ARXIV.ORG./abs/2301.12345",
+ ),
+ )
+ def test_arxiv_paper_exception_does_not_use_html(self, monkeypatch, url):
+ # Given the specialist raises before producing its terminal result
+ def raise_specialized_error(url, timeout=30):
+ raise RuntimeError("specialized failure")
+
+ monkeypatch.setattr(
+ pipeline, "_try_specialized_downloader", raise_specialized_error
+ )
+ mock_class = Mock()
+ monkeypatch.setattr(
+ "local_deep_research.research_library.downloaders.playwright_html.AutoHTMLDownloader",
+ mock_class,
+ )
+
+ # When the owned paper URL is processed
+ result = pipeline.fetch_and_extract(url)
+
+ # Then paper ownership keeps the exception path terminal
+ assert result is None
+ mock_class.assert_not_called()
+
# ---------------------------------------------------------------------------
# batch_fetch_and_extract
@@ -579,8 +781,8 @@ class TestBatchFetchAndExtract:
def test_routes_specialized_and_generic(self, monkeypatch):
def mock_specialized(url, timeout=30):
if "arxiv" in url:
- return "arXiv paper content"
- return None
+ return _specialized("arXiv paper content", False)
+ return _specialized()
monkeypatch.setattr(
pipeline, "_try_specialized_downloader", mock_specialized
@@ -604,7 +806,7 @@ class TestBatchFetchAndExtract:
monkeypatch.setattr(
pipeline,
"_try_specialized_downloader",
- lambda url, timeout=30: None,
+ lambda url, timeout=30: _specialized(),
)
call_count = [0]
@@ -633,7 +835,7 @@ class TestBatchFetchAndExtract:
monkeypatch.setattr(
pipeline,
"_try_specialized_downloader",
- lambda url, timeout=30: None,
+ lambda url, timeout=30: _specialized(),
)
results = pipeline.batch_fetch_and_extract([])
assert results == {}
@@ -656,6 +858,175 @@ class TestBatchFetchAndExtract:
results = pipeline.batch_fetch_and_extract(["https://example.com"])
assert results["https://example.com"] == "fallback content"
+ def test_terminal_arxiv_failure_is_excluded_from_html_batch(
+ self, monkeypatch
+ ):
+ # Given one terminal ar5iv failure and one fallback-eligible web URL
+ def specialized(url, timeout=30):
+ if "ar5iv.org" in url:
+ return _specialized(fallback_allowed=False)
+ return _specialized()
+
+ monkeypatch.setattr(
+ pipeline, "_try_specialized_downloader", specialized
+ )
+ mock_downloader = Mock()
+ mock_downloader.download.return_value = b"generic content"
+ mock_downloader.close = Mock()
+ mock_class = Mock(return_value=mock_downloader)
+ monkeypatch.setattr(
+ "local_deep_research.research_library.downloaders.playwright_html.AutoHTMLDownloader",
+ mock_class,
+ )
+ ar5iv_url = "https://ar5iv.org/2301.12345v2"
+ generic_url = "https://example.com/page"
+
+ # When the batch pipeline runs
+ results = pipeline.batch_fetch_and_extract([ar5iv_url, generic_url])
+
+ # Then only the fallback-eligible URL reaches generic HTML
+ assert results == {ar5iv_url: None, generic_url: "generic content"}
+ mock_downloader.download.assert_called_once_with(generic_url)
+
+ def test_malformed_arxiv_paper_does_not_construct_html_batch(
+ self, monkeypatch
+ ):
+ # Given an arXiv downloader that produces nothing and a generic HTML
+ # constructor tripwire. Only the downloader is stubbed: the ownership
+ # gate runs for real, and the real downloader would canonicalise the
+ # identifier and fetch the paper, so nothing may leave the test.
+ class FailingArxivDownloader(BaseDownloader):
+ def __init__(self, timeout=30):
+ self.timeout = timeout
+
+ def can_handle(self, url):
+ return True
+
+ def download(self, url, content_type=ContentType.TEXT):
+ return None
+
+ def download_with_result(self, url, content_type=ContentType.TEXT):
+ return DownloadResult(skip_reason="rendition unavailable")
+
+ def close(self):
+ return None
+
+ import local_deep_research.research_library.downloaders.arxiv as arxiv_mod
+
+ monkeypatch.setattr(
+ arxiv_mod, "ArxivDownloader", FailingArxivDownloader
+ )
+ mock_class = Mock()
+ monkeypatch.setattr(
+ "local_deep_research.research_library.downloaders.playwright_html.AutoHTMLDownloader",
+ mock_class,
+ )
+ url = "https://ARXIV.ORG./abs/2301.12345"
+
+ # When a batch contains only the owned paper URL
+ results = pipeline.batch_fetch_and_extract([url])
+
+ # Then the URL fails terminally before generic HTML construction
+ assert results == {url: None}
+ mock_class.assert_not_called()
+
+ def test_arxiv_page_without_an_identifier_joins_the_html_batch(
+ self, monkeypatch
+ ):
+ # Given a generic HTML downloader
+ mock_downloader = Mock()
+ mock_downloader.download.return_value = b"generic content"
+ mock_downloader.close = Mock()
+ mock_class = Mock(return_value=mock_downloader)
+ monkeypatch.setattr(
+ "local_deep_research.research_library.downloaders.playwright_html.AutoHTMLDownloader",
+ mock_class,
+ )
+ url = "https://arxiv.org/list/cs.AI/recent"
+
+ # When a batch contains an arXiv page that names no paper
+ results = pipeline.batch_fetch_and_extract([url])
+
+ # Then it is crawled rather than dropped: batch_fetch_and_extract is
+ # fed arbitrary search-result links, and these returned text on main
+ assert results == {url: "generic content"}
+ mock_downloader.download.assert_called_once_with(url)
+
+ @pytest.mark.parametrize(
+ "owned_url",
+ (
+ "https://ar5iv.org/2301.12345v2",
+ "https://ARXIV.ORG./abs/2301.12345",
+ ),
+ )
+ def test_arxiv_paper_exception_is_excluded_from_html_batch(
+ self, monkeypatch, owned_url
+ ):
+ # Given specialization raises only for the malformed owned URL
+ generic_url = "https://example.com/page"
+
+ def specialized(url, timeout=30):
+ if url == owned_url:
+ raise RuntimeError("specialized failure")
+ return _specialized()
+
+ monkeypatch.setattr(
+ pipeline, "_try_specialized_downloader", specialized
+ )
+ mock_downloader = Mock()
+ mock_downloader.download.return_value = b"generic content"
+ mock_downloader.close = Mock()
+ mock_class = Mock(return_value=mock_downloader)
+ monkeypatch.setattr(
+ "local_deep_research.research_library.downloaders.playwright_html.AutoHTMLDownloader",
+ mock_class,
+ )
+
+ # When both URLs are processed
+ results = pipeline.batch_fetch_and_extract([owned_url, generic_url])
+
+ # Then only the unrelated URL reaches generic HTML
+ assert results == {owned_url: None, generic_url: "generic content"}
+ mock_downloader.download.assert_called_once_with(generic_url)
+
+ @pytest.mark.parametrize(
+ "unowned_url",
+ (
+ "https://arxiv.org/list/cs.AI/recent",
+ "https://ARXIV.ORG./not-an-arxiv-id",
+ "https://arxiv.org/ftp/arxiv/papers/2301/2301.12345.pdf",
+ ),
+ )
+ def test_arxiv_host_without_a_paper_survives_a_specialized_crash(
+ self, monkeypatch, unowned_url
+ ):
+ # Given specialization raises for an arXiv-family URL that names no
+ # paper. The exception handler asks the same question the rest of the
+ # routing does -- does this URL name a paper? -- so a host-only test
+ # here would drop pages the generic pipeline can still read, on a
+ # path fed arbitrary search-result links.
+ def specialized(url, timeout=30):
+ raise RuntimeError("specialized failure")
+
+ monkeypatch.setattr(
+ pipeline, "_try_specialized_downloader", specialized
+ )
+ mock_downloader = Mock()
+ mock_downloader.download.return_value = b"generic content"
+ mock_downloader.close = Mock()
+ mock_class = Mock(return_value=mock_downloader)
+ monkeypatch.setattr(
+ "local_deep_research.research_library.downloaders.playwright_html.AutoHTMLDownloader",
+ mock_class,
+ )
+
+ # When the batch runs
+ results = pipeline.batch_fetch_and_extract([unowned_url])
+
+ # Then the crash is not terminal: the page still reaches generic HTML
+ assert results == {unowned_url: "generic content"}
+ mock_downloader.download.assert_called_once_with(unowned_url)
+
# ---------------------------------------------------------------------------
# enable_js_rendering plumbing through fetch_and_extract /
@@ -672,7 +1043,7 @@ class TestFetchAndExtractJSRenderingPlumbing:
monkeypatch.setattr(
pipeline,
"_try_specialized_downloader",
- lambda url, timeout=30: None,
+ lambda url, timeout=30: _specialized(),
)
mock_downloader = Mock()
mock_downloader.download.return_value = b"x"
diff --git a/tests/research_library/downloaders/test_html_downloader.py b/tests/research_library/downloaders/test_html_downloader.py
index 1e2f92b15e..eb9655ec53 100644
--- a/tests/research_library/downloaders/test_html_downloader.py
+++ b/tests/research_library/downloaders/test_html_downloader.py
@@ -415,6 +415,28 @@ class TestFormatExtractedContent:
)
assert "Main body text" in result
+ def test_page_metadata_stays_inside_the_construct_it_fills(self, dl):
+ # Given a page whose <title> and og:description carry newlines that
+ # would end the heading and the emphasis they are wrapped in
+ result = dl._format_extracted_content(
+ {
+ "title": "Paper <img src=x> [click](x)\n\n# Injected",
+ "description": "*bold* and\n<b>markup</b>",
+ "url": "https://example.com",
+ "content": "body",
+ }
+ )
+
+ # Then each stays on one line, so the page fills its construct in
+ # instead of writing the document around it. Metacharacters are left
+ # as the page wrote them: this string is stored as plain text and is
+ # substring-searched, so escaping it here would corrupt both.
+ assert result.splitlines()[0] == (
+ "# Paper <img src=x> [click](x) # Injected"
+ )
+ assert "*bold* and <b>markup</b>" in result
+ assert "\\" not in result
+
def test_missing_fields_omitted(self, dl):
"""Omits title, description, and source when they are None."""
result = dl._format_extracted_content(
diff --git a/tests/research_library/services/test_download_service_arxiv_provenance.py b/tests/research_library/services/test_download_service_arxiv_provenance.py
new file mode 100644
index 0000000000..e4807793f9
--- /dev/null
+++ b/tests/research_library/services/test_download_service_arxiv_provenance.py
@@ -0,0 +1,635 @@
+from pathlib import Path
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from local_deep_research.database.models.library import DocumentStatus
+from local_deep_research.research_library.downloaders.arxiv import (
+ ArxivDownloader,
+ ArxivTextResult,
+ ArxivTextSource,
+)
+from local_deep_research.research_library.downloaders.base import DownloadResult
+from local_deep_research.research_library.services.download_service import (
+ DownloadService,
+)
+
+
+MODULE = "local_deep_research.research_library.services.download_service"
+PROVENANCE_CASES = (
+ (ArxivTextSource.ARXIV_HTML, "html_extraction", "arxiv_html", "high"),
+ (ArxivTextSource.LOCAL_PDF, "pdf_extraction", "local_pdf", "low"),
+ (ArxivTextSource.ARXIV_API, "native_api", "arxiv_api", "high"),
+)
+PROVENANCE_ROUTING_CASES = tuple(
+ (source, method, origin)
+ for source, method, origin, _quality in PROVENANCE_CASES
+)
+QUALITY_CASES = tuple(
+ (method, source, quality)
+ for _text_source, method, source, quality in PROVENANCE_CASES
+) + (
+ ("pdf_extraction", "pdfplumber", "medium"),
+ ("pdfplumber", "legacy_pdfplumber", "medium"),
+ ("other", "test_source", "low"),
+)
+
+
+def service():
+ with patch.object(DownloadService, "__init__", lambda self, *a, **kw: None):
+ instance = DownloadService.__new__(DownloadService)
+ instance.username = "test_user"
+ instance.password = "test_password"
+ instance.library_root = "/tmp/test_library/test_user"
+ instance.legacy_library_root = "/tmp/test_library"
+ instance.settings = MagicMock()
+ instance.settings.get_setting.side_effect = lambda key, default=None: {
+ "research_library.pdf_storage_mode": "none",
+ "research_library.max_pdf_size_mb": 100,
+ }.get(key, default)
+ instance.downloaders = []
+ instance.retry_manager = MagicMock()
+ retry_decision = MagicMock()
+ retry_decision.can_retry = True
+ retry_decision.reason = None
+ instance.retry_manager.should_retry_resource.return_value = (
+ retry_decision
+ )
+ return instance
+
+
+def _make_ctx(session):
+ context = MagicMock()
+ context.__enter__.return_value = session
+ context.__exit__.return_value = False
+ return context
+
+
+ ("source", "expected_method", "expected_origin"),
+ PROVENANCE_ROUTING_CASES,
+)
+def test_pdf_download_path_persists_typed_arxiv_origin(
+ service,
+ source,
+ expected_method,
+ expected_origin,
+):
+ # Given downloaded PDF bytes and a typed arXiv text result
+ pdf_content = b"%PDF-exact-reused-content"
+ resource = MagicMock()
+ resource.id = 7
+ resource.url = "https://arxiv.org/abs/2301.12345v2"
+ resource.title = "Typed provenance"
+ resource.research_id = "research-1"
+ tracker = MagicMock()
+ tracker.url_hash = "typed-provenance"
+ tracker.download_attempts.count.return_value = 0
+ session = MagicMock()
+
+ arxiv = MagicMock(spec=ArxivDownloader)
+ arxiv.can_handle.return_value = True
+ arxiv.download_with_result.return_value = DownloadResult(
+ content=pdf_content,
+ is_success=True,
+ )
+ arxiv.download_text_with_source.return_value = ArxivTextResult(
+ text="typed arXiv text",
+ source=source,
+ )
+ service.downloaders = [arxiv]
+
+ stored_pdf_document = MagicMock(id="pdf-document-id")
+ storage_manager = MagicMock()
+ storage_manager.save_pdf.return_value = (None, None)
+
+ with (
+ patch(
+ f"{MODULE}.get_document_for_resource",
+ side_effect=[None, stored_pdf_document],
+ ),
+ patch(f"{MODULE}.get_source_type_id", return_value="source-type"),
+ patch(f"{MODULE}.get_default_library_id", return_value="library-id"),
+ patch(f"{MODULE}.ensure_in_collection"),
+ patch(f"{MODULE}.PDFStorageManager", return_value=storage_manager),
+ patch(f"{MODULE}.uuid.uuid4", return_value="new-document-id"),
+ patch.object(service, "_save_text_with_db") as save_text,
+ ):
+ # When the PDF workflow produces canonical arXiv text
+ success, error, _status_code = service._download_pdf(
+ resource,
+ tracker,
+ session,
+ )
+
+ # Then the exact bytes are reused and typed provenance is persisted
+ assert success is True
+ assert error is None
+ assert (
+ storage_manager.save_pdf.call_args.kwargs["pdf_content"] is pdf_content
+ )
+ arxiv.download_text_with_source.assert_called_once_with(
+ resource.url,
+ pdf_content=pdf_content,
+ )
+ save_text.assert_called_once_with(
+ resource=resource,
+ text="typed arXiv text",
+ session=session,
+ extraction_method=expected_method,
+ extraction_source=expected_origin,
+ pdf_document_id="pdf-document-id",
+ )
+
+
+ ("source", "expected_method", "expected_origin"),
+ PROVENANCE_ROUTING_CASES,
+)
+def test_direct_text_path_persists_typed_arxiv_origin(
+ service,
+ source,
+ expected_method,
+ expected_origin,
+):
+ # Given an arXiv downloader returning typed text provenance
+ resource = MagicMock()
+ resource.url = "https://ar5iv.org/2301.12345v3"
+ resource.title = "Direct typed provenance"
+ arxiv = MagicMock(spec=ArxivDownloader)
+ arxiv.download_text_with_source.return_value = ArxivTextResult(
+ text="direct typed text",
+ source=source,
+ )
+ session = MagicMock()
+
+ with (
+ patch.object(service, "_get_downloader", return_value=arxiv),
+ patch.object(
+ service,
+ "_check_url_against_policy",
+ return_value=(True, "allowed"),
+ ),
+ patch.object(service, "_save_text_with_db") as save_text,
+ ):
+ # When direct text extraction runs
+ result = service._try_api_text_extraction(session, resource)
+
+ # Then the source-specific method and exact origin are stored
+ assert result == (True, None)
+ arxiv.download_text_with_source.assert_called_once_with(resource.url)
+ arxiv.download_with_result.assert_not_called()
+ save_text.assert_called_once_with(
+ resource,
+ "direct typed text",
+ session,
+ extraction_method=expected_method,
+ extraction_source=expected_origin,
+ )
+
+
+def test_arxiv_helper_returns_none_for_trailing_dot_lookalike(service):
+ resource = MagicMock()
+ resource.id = 21
+ resource.url = "https://ar5iv.org.example.com./2301.12345"
+ session = MagicMock()
+
+ with (
+ 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,
+ ):
+ result = service._try_arxiv_text_extraction(session, resource)
+
+ assert result is None
+ service.retry_manager.should_retry_resource.assert_not_called()
+ storage_manager.assert_not_called()
+ get_downloader.assert_not_called()
+ policy_check.assert_not_called()
+
+
+ "url",
+ (
+ "https://AR5IV.ORG./not-an-arxiv-id",
+ "https://ARXIV.ORG./not-an-arxiv-id",
+ "https://EXPORT.ARXIV.ORG./not-an-arxiv-id",
+ "https://arxiv.org/list/cs.AI/recent",
+ "https://arxiv.org/ftp/arxiv/papers/2301/2301.12345.pdf",
+ ),
+)
+def test_family_url_without_an_identifier_falls_through(service, url):
+ # Given an arXiv-family URL that names no paper
+ resource = MagicMock()
+ resource.id = 22
+ resource.url = url
+ session = MagicMock()
+
+ with (
+ patch(f"{MODULE}.get_document_for_resource") 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,
+ patch.object(service, "_save_text_with_db") as save_text,
+ ):
+ result = service._try_arxiv_text_extraction(session, resource)
+
+ # Then this path declines rather than deciding the call: the canonical
+ # sources need an identifier, and a verdict here would deny the resource
+ # every later strategy
+ assert result is None
+ service.retry_manager.should_retry_resource.assert_not_called()
+ service.retry_manager.record_attempt.assert_not_called()
+ get_document.assert_not_called()
+ storage_manager.assert_not_called()
+ get_downloader.assert_not_called()
+ policy_check.assert_not_called()
+ save_text.assert_not_called()
+
+
+def test_exhausted_retry_budget_falls_through_to_the_stored_pdf(service):
+ # Given an arXiv paper whose retry budget is spent
+ resource = MagicMock()
+ resource.id = 25
+ resource.url = "https://arxiv.org/abs/2301.12345"
+ session = MagicMock()
+ denied = MagicMock()
+ denied.can_retry = False
+ denied.reason = "Max retries exceeded"
+ service.retry_manager.should_retry_resource.return_value = denied
+
+ with (
+ patch(f"{MODULE}.get_document_for_resource") 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,
+ patch.object(service, "_save_text_with_db") as save_text,
+ ):
+ result = service._try_arxiv_text_extraction(session, resource)
+
+ # Then the network-bearing path declines without deciding the call, so
+ # download_as_text still reaches _try_existing_pdf_extraction -- a pure
+ # filesystem read that produced text before this path existed
+ assert result is None
+ get_document.assert_not_called()
+ storage_manager.assert_not_called()
+ get_downloader.assert_not_called()
+ policy_check.assert_not_called()
+ save_text.assert_not_called()
+
+
+def test_arxiv_text_reuses_database_pdf_and_document_identity(service):
+ resource = MagicMock()
+ resource.id = 23
+ resource.url = "https://AR5IV.ORG./2301.12345v2"
+ resource.title = "Stored PDF identity"
+ session = MagicMock()
+ document = MagicMock()
+ document.id = "existing-pdf-document"
+ document.status = DocumentStatus.COMPLETED
+ document.file_type = "pdf"
+ pdf_content = b"%PDF-database-identity"
+ storage_manager = MagicMock()
+ storage_manager.load_pdf.return_value = pdf_content
+ arxiv = MagicMock(spec=ArxivDownloader)
+ arxiv.download_text_with_source.return_value = ArxivTextResult(
+ text="text from stored PDF",
+ source=ArxivTextSource.LOCAL_PDF,
+ )
+
+ with (
+ patch(f"{MODULE}.get_document_for_resource", return_value=document),
+ patch(
+ f"{MODULE}.PDFStorageManager", return_value=storage_manager
+ ) as manager,
+ patch.object(service, "_get_downloader", return_value=arxiv),
+ patch.object(
+ service,
+ "_check_url_against_policy",
+ return_value=(True, "allowed"),
+ ),
+ patch.object(service, "_save_text_with_db") as save_text,
+ ):
+ result = service._try_arxiv_text_extraction(session, resource)
+
+ assert result == (True, None)
+ manager.assert_called_once_with(
+ library_root=Path(service.library_root),
+ storage_mode="none",
+ legacy_root=Path(service.legacy_library_root),
+ )
+ storage_manager.load_pdf.assert_called_once_with(document, session)
+ assert (
+ arxiv.download_text_with_source.call_args.kwargs["pdf_content"]
+ is pdf_content
+ )
+ arxiv.download_text_with_source.assert_called_once_with(
+ resource.url,
+ pdf_content=pdf_content,
+ )
+ save_text.assert_called_once_with(
+ resource,
+ "text from stored PDF",
+ session,
+ extraction_method="pdf_extraction",
+ extraction_source="local_pdf",
+ pdf_document_id=document.id,
+ )
+ session.commit.assert_called_once_with()
+
+
+def test_arxiv_text_without_stored_pdf_uses_one_typed_chain(service):
+ resource = MagicMock()
+ resource.id = 24
+ resource.url = "https://arxiv.org/abs/2301.12345"
+ resource.title = "One typed chain"
+ session = MagicMock()
+ arxiv = MagicMock(spec=ArxivDownloader)
+ arxiv.download_text_with_source.return_value = ArxivTextResult(
+ text="API fallback text",
+ source=ArxivTextSource.ARXIV_API,
+ )
+
+ with (
+ patch(f"{MODULE}.get_document_for_resource", return_value=None),
+ patch(f"{MODULE}.PDFStorageManager") as storage_manager,
+ patch.object(service, "_get_downloader", return_value=arxiv),
+ patch.object(
+ service,
+ "_check_url_against_policy",
+ return_value=(True, "allowed"),
+ ),
+ patch.object(service, "_save_text_with_db") as save_text,
+ ):
+ result = service._try_arxiv_text_extraction(session, resource)
+
+ assert result == (True, None)
+ storage_manager.assert_not_called()
+ arxiv.download_text_with_source.assert_called_once_with(resource.url)
+ arxiv.download_with_result.assert_not_called()
+ save_text.assert_called_once_with(
+ resource,
+ "API fallback text",
+ session,
+ extraction_method="native_api",
+ extraction_source="arxiv_api",
+ pdf_document_id=None,
+ )
+ session.commit.assert_called_once_with()
+
+
+def test_arxiv_retry_denial_skips_work_and_retry_record(service):
+ resource = MagicMock()
+ resource.id = 25
+ 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(f"{MODULE}.PDFStorageManager") as storage_manager,
+ patch.object(service, "_get_downloader") as get_downloader,
+ patch.object(service, "_check_url_against_policy") as policy_check,
+ patch.object(
+ service, "_try_existing_pdf_extraction", return_value=None
+ ) as existing_pdf,
+ 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 canonical arXiv path declines without a verdict, the stored
+ # PDF is still read (pure filesystem, ahead of the gate), and the gate
+ # then ends the call before any network-bearing step or retry record
+ assert result == (False, "retry denied")
+ existing_pdf.assert_called_once_with(session, resource, resource.id)
+ storage_manager.assert_not_called()
+ get_downloader.assert_not_called()
+ policy_check.assert_not_called()
+ api_text.assert_not_called()
+ fallback.assert_not_called()
+ service.retry_manager.record_attempt.assert_not_called()
+
+
+def test_arxiv_success_records_one_terminal_retry_attempt(service):
+ resource = MagicMock()
+ resource.id = 26
+ resource.url = "https://arxiv.org/abs/2301.12345"
+ resource.title = "Terminal success"
+ resource.source_type = "web"
+ session = MagicMock()
+ session.query.return_value.filter_by.return_value.first.return_value = (
+ resource
+ )
+ arxiv = MagicMock(spec=ArxivDownloader)
+ arxiv.download_text_with_source.return_value = ArxivTextResult(
+ text="official HTML text",
+ source=ArxivTextSource.ARXIV_HTML,
+ )
+
+ 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=None),
+ patch.object(service, "_get_downloader", return_value=arxiv),
+ patch.object(
+ service,
+ "_check_url_against_policy",
+ return_value=(True, "allowed"),
+ ),
+ patch.object(service, "_save_text_with_db"),
+ patch.object(service, "_try_existing_pdf_extraction") as existing_pdf,
+ patch.object(service, "_try_api_text_extraction") as api_fallback,
+ patch.object(service, "_fallback_pdf_extraction") as pdf_fallback,
+ ):
+ result = service.download_as_text(resource.id)
+
+ assert result == (True, None)
+ service.retry_manager.record_attempt.assert_called_once_with(
+ resource_id=resource.id,
+ result=result,
+ url=resource.url,
+ details="Successfully extracted text",
+ session=session,
+ )
+ existing_pdf.assert_not_called()
+ api_fallback.assert_not_called()
+ pdf_fallback.assert_not_called()
+
+
+def test_arxiv_typed_exhaustion_is_terminal_and_records_once(service):
+ resource = MagicMock()
+ resource.id = 27
+ resource.url = "https://arxiv.org/abs/2301.12345"
+ resource.title = "Terminal exhaustion"
+ resource.source_type = "web"
+ session = MagicMock()
+ session.query.return_value.filter_by.return_value.first.return_value = (
+ resource
+ )
+ arxiv = MagicMock(spec=ArxivDownloader)
+ arxiv.download_text_with_source.return_value = None
+
+ 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=None),
+ patch.object(service, "_get_downloader", return_value=arxiv),
+ patch.object(
+ service,
+ "_check_url_against_policy",
+ return_value=(True, "allowed"),
+ ),
+ patch.object(service, "_try_existing_pdf_extraction") as existing_pdf,
+ patch.object(service, "_try_api_text_extraction") as api_fallback,
+ patch.object(service, "_fallback_pdf_extraction") as pdf_fallback,
+ ):
+ result = service.download_as_text(resource.id)
+
+ assert result == (False, "Could not retrieve arXiv text")
+ service.retry_manager.record_attempt.assert_called_once_with(
+ resource_id=resource.id,
+ result=result,
+ url=resource.url,
+ details="Could not retrieve arXiv text",
+ session=session,
+ )
+ arxiv.download_text_with_source.assert_called_once_with(resource.url)
+ arxiv.download_with_result.assert_not_called()
+ existing_pdf.assert_not_called()
+ api_fallback.assert_not_called()
+ pdf_fallback.assert_not_called()
+
+
+def test_arxiv_typed_exception_is_terminal_and_records_once(service):
+ resource = MagicMock()
+ resource.id = 28
+ resource.url = "https://arxiv.org/abs/2301.12345"
+ resource.title = "Terminal exception"
+ resource.source_type = "web"
+ session = MagicMock()
+ session.query.return_value.filter_by.return_value.first.return_value = (
+ resource
+ )
+ arxiv = MagicMock(spec=ArxivDownloader)
+ arxiv.download_text_with_source.side_effect = RuntimeError(
+ "secret_token=unsafe"
+ )
+
+ 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=None),
+ patch.object(service, "_get_downloader", return_value=arxiv),
+ patch.object(
+ service,
+ "_check_url_against_policy",
+ return_value=(True, "allowed"),
+ ),
+ patch(
+ f"{MODULE}.sanitize_error_for_client",
+ return_value="arXiv text extraction failed",
+ ),
+ patch(f"{MODULE}.safe_rollback") as rollback,
+ patch.object(service, "_try_existing_pdf_extraction") as existing_pdf,
+ patch.object(service, "_try_api_text_extraction") as api_fallback,
+ patch.object(service, "_fallback_pdf_extraction") as pdf_fallback,
+ ):
+ result = service.download_as_text(resource.id)
+
+ assert result == (False, "arXiv text extraction failed")
+ service.retry_manager.record_attempt.assert_called_once_with(
+ resource_id=resource.id,
+ result=result,
+ url=resource.url,
+ details="arXiv text extraction failed",
+ session=session,
+ )
+ rollback.assert_called_once_with(session, "_try_arxiv_text_extraction")
+ existing_pdf.assert_not_called()
+ api_fallback.assert_not_called()
+ pdf_fallback.assert_not_called()
+
+
+ ("method", "source", "expected_quality"), QUALITY_CASES
+)
+def test_existing_document_quality_uses_unified_mapping(
+ service,
+ method,
+ source,
+ expected_quality,
+):
+ # Given an existing completed document
+ document = MagicMock()
+ document.status = DocumentStatus.COMPLETED
+ session = MagicMock()
+ session.query.return_value.filter_by.return_value.first.return_value = (
+ document
+ )
+ resource = MagicMock()
+
+ # When extracted text updates it
+ service._save_text_with_db(
+ resource,
+ "quality text",
+ session,
+ extraction_method=method,
+ extraction_source=source,
+ pdf_document_id="existing-document",
+ )
+
+ # Then the method's exact unified quality is applied
+ assert document.extraction_quality == expected_quality
+
+
+ ("method", "source", "expected_quality"), QUALITY_CASES
+)
+def test_new_document_quality_uses_unified_mapping(
+ service,
+ method,
+ source,
+ expected_quality,
+):
+ # Given no existing resource document or duplicate content hash
+ resource = MagicMock()
+ resource.id = 9
+ resource.research_id = "research-2"
+ resource.url = "https://example.com/resource"
+ resource.title = "Quality mapping"
+ session = MagicMock()
+ session.query.return_value.filter_by.return_value.first.side_effect = [
+ None,
+ None,
+ ]
+
+ with (
+ patch(f"{MODULE}.get_document_for_resource", return_value=None),
+ patch(f"{MODULE}.get_source_type_id", return_value="source-type"),
+ patch(f"{MODULE}.uuid.uuid4", return_value="new-text-document"),
+ ):
+ # When extracted text creates a document
+ service._save_text_with_db(
+ resource,
+ "new quality text",
+ session,
+ extraction_method=method,
+ extraction_source=source,
+ )
+
+ # Then creation uses the same exact quality mapping as updates
+ document = session.add.call_args.args[0]
+ assert document.extraction_quality == expected_quality
diff --git a/tests/research_library/services/test_download_service_coverage.py b/tests/research_library/services/test_download_service_coverage.py
index 98cd8f568b..210e43332a 100644
--- a/tests/research_library/services/test_download_service_coverage.py
+++ b/tests/research_library/services/test_download_service_coverage.py
@@ -1183,27 +1183,37 @@ class TestTryApiTextExtraction:
resource.url = "https://arxiv.org/abs/1234"
resource.title = "Test Paper with Long Title for Slicing"
- from local_deep_research.research_library.downloaders import (
+ from local_deep_research.research_library.downloaders.arxiv import (
ArxivDownloader,
+ ArxivTextResult,
+ ArxivTextSource,
)
downloader = MagicMock(spec=ArxivDownloader)
- result_obj = MagicMock()
- result_obj.is_success = True
- result_obj.content = "text"
- downloader.download_with_result.return_value = result_obj
+ downloader.download_text_with_source.return_value = ArxivTextResult(
+ text="text",
+ source=ArxivTextSource.ARXIV_API,
+ )
with (
patch.object(svc, "_get_downloader", return_value=downloader),
patch.object(svc, "_save_text_with_db") as save_mock,
):
- svc._try_api_text_extraction(session, resource)
- # Check extraction_source was arxiv_api
- save_mock.assert_called_once()
- kwargs = save_mock.call_args
- assert kwargs[1].get("extraction_source") == "arxiv_api" or (
- len(kwargs[0]) > 4 and kwargs[0][4] == "arxiv_api"
- )
+ result = svc._try_api_text_extraction(session, resource)
+
+ assert result == (True, None)
+ downloader.download_text_with_source.assert_called_once_with(
+ resource.url
+ )
+ downloader.download_with_result.assert_not_called()
+ save_mock.assert_called_once_with(
+ resource,
+ "text",
+ session,
+ extraction_method="native_api",
+ extraction_source="arxiv_api",
+ )
+ session.commit.assert_called_once_with()
def test_save_raises_returns_error(self, svc):
session = MagicMock()
diff --git a/tests/research_library/services/test_download_service_deep_coverage.py b/tests/research_library/services/test_download_service_deep_coverage.py
index c419f0afac..77e3994eb1 100644
--- a/tests/research_library/services/test_download_service_deep_coverage.py
+++ b/tests/research_library/services/test_download_service_deep_coverage.py
@@ -293,8 +293,18 @@ class TestDownloadPdfDeep:
assert success is True
assert reason is None
- def test_new_doc_created_database_mode(self, svc):
- """No existing doc: new Document created with database storage mode."""
+ def test_new_arxiv_doc_reuses_pdf_bytes_for_text(self, svc):
+ """A new arXiv PDF keeps its bytes and stores HTML-first text."""
+ from local_deep_research.research_library.downloaders import (
+ ArxivDownloader,
+ ContentType,
+ )
+ from local_deep_research.research_library.downloaders.arxiv import (
+ ArxivTextResult,
+ ArxivTextSource,
+ )
+
+ # Given a fresh arXiv PDF download and observable storage/text seams
session = MagicMock()
resource = MagicMock()
resource.id = 11
@@ -309,31 +319,82 @@ class TestDownloadPdfDeep:
"research_library.max_pdf_size_mb": 50,
}.get(key, default)
- downloader = MagicMock()
+ downloader = MagicMock(spec=ArxivDownloader)
result_obj = MagicMock()
result_obj.is_success = True
- result_obj.content = b"%PDF database"
+ pdf_content = b"%PDF database"
+ 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
+ events = []
+
+ def download_text_with_source(url, pdf_content=None):
+ events.append("text_produced")
+ return ArxivTextResult(
+ text="Official HTML text",
+ source=ArxivTextSource.ARXIV_HTML,
+ )
+
+ downloader.download_text_with_source.side_effect = (
+ download_text_with_source
+ )
svc.downloaders = [downloader]
mock_storage = MagicMock()
- mock_storage.save_pdf.return_value = ("database", None)
+ mock_storage.save_pdf.side_effect = lambda **_kwargs: (
+ events.append("pdf_stored") or "database",
+ None,
+ )
+ stored_pdf_doc = MagicMock()
+ stored_pdf_doc.id = "new-doc-id"
with (
- patch(f"{MODULE}.get_document_for_resource", return_value=None),
+ patch(
+ f"{MODULE}.get_document_for_resource",
+ side_effect=[None, stored_pdf_doc],
+ ),
patch(f"{MODULE}.get_source_type_id", return_value="src-type-1"),
patch(f"{MODULE}.get_default_library_id", return_value="lib-col-1"),
patch(f"{MODULE}.PDFStorageManager", return_value=mock_storage),
patch(f"{MODULE}.uuid") as mock_uuid,
- patch.object(svc, "_extract_text_from_pdf", return_value=None),
+ patch.object(
+ svc,
+ "_extract_text_from_pdf",
+ side_effect=AssertionError("arXiv used local PDF extraction"),
+ ) as local_pdf_extract,
+ patch.object(svc, "_save_text_with_db") as save_text,
):
mock_uuid.uuid4.return_value = "new-doc-id"
+ # When the PDF download workflow completes
success, reason, _status_code = svc._download_pdf(
resource, tracker, session
)
assert success is True
+ assert reason is None
+
+ # Then PDF bytes are stored first and reused by canonical text production
+ downloader.download_with_result.assert_called_once_with(
+ resource.url, ContentType.PDF
+ )
+ assert (
+ mock_storage.save_pdf.call_args.kwargs["pdf_content"] == pdf_content
+ )
+ downloader.download_text_with_source.assert_called_once_with(
+ resource.url,
+ pdf_content=pdf_content,
+ )
+ assert events == ["pdf_stored", "text_produced"]
+ local_pdf_extract.assert_not_called()
+ save_text.assert_called_once_with(
+ resource=resource,
+ text="Official HTML text",
+ session=session,
+ extraction_method="html_extraction",
+ extraction_source="arxiv_html",
+ pdf_document_id="new-doc-id",
+ )
def test_source_type_exception_propagates(self, svc):
"""Exception from get_source_type_id is re-raised."""
@@ -427,12 +488,17 @@ class TestDownloadPdfDeep:
assert success is False
assert reason == "Not a PDF"
- def test_text_extraction_exception_swallowed(self, svc):
- """Exception during text extraction does not fail the download."""
+ def test_arxiv_text_exception_does_not_fail_pdf_download(self, svc):
+ """An arXiv text failure remains nonfatal after PDF storage."""
+ from local_deep_research.research_library.downloaders import (
+ ArxivDownloader,
+ )
+
+ # Given an arXiv PDF that stores successfully but whose text seam raises
session = MagicMock()
resource = MagicMock()
resource.id = 15
- resource.url = "https://example.com/p.pdf"
+ resource.url = "https://arxiv.org/abs/2301.12345"
resource.title = "A Title Here"
resource.research_id = "res-15"
@@ -445,13 +511,18 @@ class TestDownloadPdfDeep:
"research_library.max_pdf_size_mb": 100,
}.get(key, default)
- downloader = MagicMock()
+ downloader = MagicMock(spec=ArxivDownloader)
result_obj = MagicMock()
result_obj.is_success = True
- result_obj.content = b"%PDF-1.4 ok"
+ 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.side_effect = RuntimeError(
+ "HTML failed"
+ )
svc.downloaders = [downloader]
mock_storage = MagicMock()
@@ -465,14 +536,27 @@ class TestDownloadPdfDeep:
patch.object(
svc,
"_extract_text_from_pdf",
- side_effect=RuntimeError("corrupt PDF"),
- ),
+ side_effect=AssertionError("arXiv used local PDF extraction"),
+ ) as local_pdf_extract,
+ patch.object(svc, "_save_text_with_db") as save_text,
):
+ # When the PDF download workflow completes
success, reason, _status_code = svc._download_pdf(
resource, tracker, session
)
assert success is True # text extraction failure does not fail
+ # Then the stored PDF remains successful and no fallback text is saved
+ assert (
+ mock_storage.save_pdf.call_args.kwargs["pdf_content"] == pdf_content
+ )
+ downloader.download_text_with_source.assert_called_once_with(
+ resource.url,
+ pdf_content=pdf_content,
+ )
+ local_pdf_extract.assert_not_called()
+ save_text.assert_not_called()
+
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.py
index 6b009522d9..f8bcbfd20a 100644
--- a/tests/research_library/services/test_download_service_strategy_coverage.py
+++ b/tests/research_library/services/test_download_service_strategy_coverage.py
@@ -125,11 +125,133 @@ class TestDownloadResourceArxivStrategy:
from local_deep_research.research_library.downloaders import (
ArxivDownloader,
+ DirectPDFDownloader,
)
service = DownloadService(username="test_user")
types = [type(d) for d in service.downloaders]
assert ArxivDownloader in types
+ assert types.index(ArxivDownloader) < types.index(DirectPDFDownloader)
+
+ def test_arxiv_failure_does_not_continue_to_generic(self, svc):
+ # Given arXiv and generic downloaders that both accept an ar5iv URL
+ from local_deep_research.research_library.downloaders import (
+ ArxivDownloader,
+ GenericDownloader,
+ )
+
+ arxiv = MagicMock(spec=ArxivDownloader)
+ arxiv.can_handle.return_value = True
+ arxiv_result = MagicMock()
+ arxiv_result.is_success = False
+ arxiv_result.content = None
+ arxiv_result.skip_reason = None
+ arxiv.download_with_result.return_value = arxiv_result
+
+ generic = MagicMock(spec=GenericDownloader)
+ generic.can_handle.return_value = True
+ generic_result = MagicMock()
+ generic_result.is_success = False
+ generic_result.content = None
+ generic_result.skip_reason = "generic should not run"
+ generic.download_with_result.return_value = generic_result
+ svc.downloaders = [arxiv, generic]
+
+ resource = MagicMock()
+ resource.url = "https://ar5iv.org/2301.12345v2.pdf"
+ tracker = MagicMock()
+ tracker.url_hash = "arxiv-terminal"
+ tracker.download_attempts.count.return_value = 0
+ session = MagicMock()
+
+ # When PDF download attempts the arXiv specialist
+ success, reason, status_code = svc._download_pdf(
+ resource, tracker, session
+ )
+
+ # Then the arXiv failure is terminal even without a skip reason
+ assert success is False
+ assert reason == "Failed to download PDF content"
+ assert status_code is None
+ arxiv.download_with_result.assert_called_once()
+ generic.download_with_result.assert_not_called()
+
+ def test_family_host_without_a_paper_reaches_the_next_downloader(
+ self, svc, mocker
+ ):
+ # Given the real arXiv specialist followed by a generic fallback.
+ # An arXiv-family host whose path names no paper is not the arXiv
+ # downloader's to claim: every one of its entry points needs an
+ # identifier to build a canonical URL from, so claiming the URL would
+ # only skip it and end the selection loop, starving the downloader
+ # that can serve the page.
+ from local_deep_research.research_library.downloaders import (
+ ArxivDownloader,
+ GenericDownloader,
+ )
+
+ arxiv = ArxivDownloader(timeout=10)
+ request = mocker.patch.object(arxiv.session, "get")
+ generic = MagicMock(spec=GenericDownloader)
+ generic.can_handle.return_value = True
+ generic_result = MagicMock()
+ generic_result.is_success = False
+ generic_result.content = None
+ generic_result.skip_reason = "generic downloader ran"
+ generic_result.status_code = 404
+ generic.download_with_result.return_value = generic_result
+ svc.downloaders = [arxiv, generic]
+
+ resource = MagicMock()
+ resource.url = "https://ar5iv.org/not-an-arxiv-id"
+ tracker = MagicMock()
+ tracker.url_hash = "malformed-ar5iv-declined"
+ tracker.download_attempts.count.return_value = 0
+ session = MagicMock()
+
+ # When PDF strategy selection runs
+ success, reason, status_code = svc._download_pdf(
+ resource, tracker, session
+ )
+
+ # Then the arXiv specialist declines without making a request and the
+ # loop advances, so it is the generic downloader's verdict that comes
+ # back rather than an arXiv skip
+ assert success is False
+ assert reason == "generic downloader ran"
+ assert status_code == 404
+ request.assert_not_called()
+ generic.can_handle.assert_called_once()
+ generic.download_with_result.assert_called_once()
+
+ def test_a_claimed_url_always_yields_an_identifier(self):
+ # ArxivDownloader.can_handle and the ID extraction that every entry
+ # point starts with are the same predicate -- can_handle is
+ # `extract_arxiv_id(url) is not None` and _extract_arxiv_id delegates
+ # to that same function -- so no URL exists that the downloader
+ # claims and then rejects with "could not extract". That error
+ # surface is reachable only by calling the downloader directly, which
+ # test_malformed_ar5iv_fails_without_request covers; this test pins
+ # the equivalence so a future divergence between the two shows up
+ # here rather than as a silently unreachable skip reason.
+ from local_deep_research.research_library.downloaders import (
+ ArxivDownloader,
+ )
+
+ downloader = ArxivDownloader(timeout=10)
+ for url in (
+ "https://arxiv.org/abs/2301.12345",
+ "https://arxiv.org/abs/2301.12345v2",
+ "https://ar5iv.org/2301.12345v2",
+ "https://arxiv.org/abs/math.AG/0601001v3",
+ "https://arxiv.org/abs/not-an-id",
+ "https://arxiv.org/list/cs.AI/recent",
+ "https://ar5iv.org/not-an-arxiv-id",
+ "https://arxiv.org/ftp/arxiv/papers/2301/2301.12345.pdf",
+ ):
+ assert downloader.can_handle(url) is (
+ downloader._extract_arxiv_id(url) is not None
+ ), url
# ---------------------------------------------------------------------------
@@ -275,6 +397,7 @@ class TestDownloadResourceGenericFallback:
GenericDownloader,
)
+ # Given a generic fallback that returns PDF bytes after a specialist skips
# Specialist: handles but skips (non-fatal skip)
dl_specialist = MagicMock()
dl_specialist.can_handle.return_value = True
@@ -290,8 +413,10 @@ class TestDownloadResourceGenericFallback:
dl_generic.can_handle.return_value = True
generic_result = MagicMock()
generic_result.is_success = True
- generic_result.content = b"%PDF-1.4 generic pdf content"
+ pdf_content = b"%PDF-1.4 generic pdf content"
+ generic_result.content = pdf_content
generic_result.skip_reason = None
+ generic_result.status_code = None
dl_generic.download_with_result.return_value = generic_result
svc.downloaders = [dl_specialist, dl_generic]
@@ -314,23 +439,44 @@ class TestDownloadResourceGenericFallback:
session = MagicMock()
mock_psm = MagicMock()
mock_psm.save_pdf.return_value = (None, None)
+ stored_pdf_doc = MagicMock()
+ stored_pdf_doc.id = "generic-pdf-id"
with (
patch(
f"{MODULE}.get_document_for_resource",
- side_effect=[None, MagicMock()],
+ side_effect=[None, stored_pdf_doc],
),
patch(f"{MODULE}.get_source_type_id", return_value="src-1"),
patch(f"{MODULE}.get_default_library_id", return_value="lib-1"),
patch(f"{MODULE}.PDFStorageManager", return_value=mock_psm),
patch(f"{MODULE}.uuid.uuid4", return_value="new-uuid"),
- patch.object(svc, "_extract_text_from_pdf", return_value=None),
+ patch.object(
+ svc,
+ "_extract_text_from_pdf",
+ return_value="Generic PDF text",
+ ) as extract_text,
+ patch.object(svc, "_save_text_with_db") as save_text,
):
+ # When the PDF download workflow completes
success, reason, _status_code = svc._download_pdf(
resource, tracker, session
)
+ # Then non-arXiv extraction and provenance remain unchanged
assert success is True
+ assert reason is None
+ assert mock_psm.save_pdf.call_args.kwargs["pdf_content"] == pdf_content
+ extract_text.assert_called_once_with(pdf_content)
+ dl_generic.download_text.assert_not_called()
+ save_text.assert_called_once_with(
+ resource=resource,
+ text="Generic PDF text",
+ session=session,
+ extraction_method="pdf_extraction",
+ extraction_source="local_pdf",
+ pdf_document_id="generic-pdf-id",
+ )
# ---------------------------------------------------------------------------
@@ -475,7 +621,7 @@ class TestDownloadAsTextSuccess:
session = MagicMock()
resource = MagicMock()
resource.source_type = "web"
- resource.url = "https://arxiv.org/abs/2301.55555"
+ resource.url = "https://pubmed.ncbi.nlm.nih.gov/12345678"
session.query.return_value.filter_by.return_value.first.return_value = (
resource
)
@@ -498,6 +644,140 @@ class TestDownloadAsTextSuccess:
assert success is True
assert error is None
+ def test_exhausted_retry_budget_still_reads_a_stored_arxiv_pdf(
+ self, svc, tmp_path
+ ):
+ # Given an arXiv paper whose retry budget is spent and whose PDF is
+ # already stored on disk
+ session = MagicMock()
+ resource = MagicMock()
+ resource.id = 9
+ resource.source_type = "web"
+ resource.url = "https://arxiv.org/abs/2301.00001"
+
+ pdf_path = tmp_path / "stored.pdf"
+ pdf_path.write_bytes(b"%PDF-stored")
+ pdf_document = MagicMock()
+ pdf_document.id = "stored-pdf-document"
+ pdf_document.status = "completed"
+ pdf_document.file_path = "stored.pdf"
+ session.query.return_value.filter_by.return_value.first.side_effect = [
+ resource,
+ pdf_document,
+ ]
+
+ denied = MagicMock()
+ denied.can_retry = False
+ denied.reason = "Max retries exceeded"
+ svc.retry_manager.should_retry_resource.return_value = denied
+
+ with (
+ patch(
+ f"{MODULE}.get_user_db_session", return_value=_make_ctx(session)
+ ),
+ patch.object(svc, "_try_existing_text", return_value=None),
+ patch.object(svc, "_try_legacy_text_file", return_value=None),
+ patch.object(svc, "_get_downloader") as get_downloader,
+ patch(
+ f"{MODULE}.get_absolute_path_from_settings",
+ return_value=pdf_path,
+ ),
+ patch.object(
+ svc,
+ "_extract_text_from_pdf",
+ return_value="text from the stored PDF",
+ ),
+ patch.object(svc, "_save_text_with_db") as save_text,
+ ):
+ # When text is requested
+ success, error = svc.download_as_text(resource.id)
+
+ # Then the spent budget stops only the network-bearing arXiv path; the
+ # pure filesystem read still runs and returns the text the user had
+ assert (success, error) == (True, None)
+ get_downloader.assert_not_called()
+ save_text.assert_called_once_with(
+ resource,
+ "text from the stored PDF",
+ session,
+ extraction_method="pdf_extraction",
+ extraction_source="pdfplumber",
+ pdf_document_id="stored-pdf-document",
+ )
+
+ def test_non_arxiv_download_as_text_order_is_unchanged(self, svc):
+ session = MagicMock()
+ resource = MagicMock()
+ resource.id = 2
+ resource.source_type = "web"
+ resource.url = "https://example.com/article"
+ session.query.return_value.filter_by.return_value.first.return_value = (
+ resource
+ )
+ events = []
+ retry_decision = MagicMock()
+ retry_decision.can_retry = True
+ svc.retry_manager.should_retry_resource.side_effect = (
+ lambda _resource_id: events.append("retry") or retry_decision
+ )
+
+ with (
+ patch(
+ f"{MODULE}.get_user_db_session", return_value=_make_ctx(session)
+ ),
+ patch.object(
+ svc,
+ "_try_existing_text",
+ side_effect=lambda *_args: events.append("existing_text"),
+ ),
+ patch.object(
+ svc,
+ "_try_legacy_text_file",
+ side_effect=lambda *_args: events.append("legacy_text"),
+ ),
+ patch.object(
+ svc,
+ "_try_arxiv_text_extraction",
+ side_effect=lambda *_args: events.append("arxiv") or None,
+ ),
+ patch.object(
+ svc,
+ "_try_existing_pdf_extraction",
+ side_effect=lambda *_args: events.append("existing_pdf"),
+ ),
+ patch.object(
+ svc,
+ "_try_api_text_extraction",
+ side_effect=lambda *_args: events.append("api"),
+ ),
+ patch.object(
+ svc,
+ "_fallback_pdf_extraction",
+ side_effect=lambda *_args: (
+ events.append("pdf_fallback") or (True, None)
+ ),
+ ),
+ patch.object(
+ svc,
+ "_record_retry_attempt",
+ side_effect=lambda *_args: events.append("record"),
+ ) as record_attempt,
+ ):
+ result = svc.download_as_text(resource.id)
+
+ assert result == (True, None)
+ assert events == [
+ "existing_text",
+ "legacy_text",
+ "arxiv",
+ "existing_pdf",
+ "retry",
+ "api",
+ "pdf_fallback",
+ "record",
+ ]
+ record_attempt.assert_called_once_with(resource, result, session)
+
def test_fallback_pdf_extraction_success(self, svc):
"""download_as_text returns success via _fallback_pdf_extraction."""
session = MagicMock()
diff --git a/tests/search_engines/test_search_engine_arxiv.py b/tests/search_engines/test_search_engine_arxiv.py
index 48a678b1f2..b4bdf654bb 100644
--- a/tests/search_engines/test_search_engine_arxiv.py
+++ b/tests/search_engines/test_search_engine_arxiv.py
@@ -7,6 +7,11 @@ import pytest
from unittest.mock import Mock
from datetime import datetime
+from local_deep_research.utilities.arxiv_api import (
+ ArxivSortCriterion,
+ ArxivSortOrder,
+)
+
class TestArXivSearchEngineInit:
"""Tests for ArXiv search engine initialization."""
@@ -64,16 +69,13 @@ class TestArXivSearchEngineInit:
from local_deep_research.web_search_engines.engines.search_engine_arxiv import (
ArXivSearchEngine,
)
- import arxiv
engine = ArXivSearchEngine()
assert "relevance" in engine.sort_criteria
assert "lastUpdatedDate" in engine.sort_criteria
assert "submittedDate" in engine.sort_criteria
- assert (
- engine.sort_criteria["relevance"] == arxiv.SortCriterion.Relevance
- )
+ assert engine.sort_criteria["relevance"] == ArxivSortCriterion.RELEVANCE
class TestArXivSearchExecution:
@@ -110,12 +112,10 @@ class TestArXivSearchExecution:
mock_result.primary_category = "cs.CL"
mock_result.categories = ["cs.CL", "cs.AI"]
- # Mock the arxiv.Client and Search
- mock_client = Mock()
- mock_client.results.return_value = iter([mock_result])
-
- monkeypatch.setattr("arxiv.Client", Mock(return_value=mock_client))
- monkeypatch.setattr("arxiv.Search", Mock(return_value=Mock()))
+ monkeypatch.setattr(
+ "local_deep_research.web_search_engines.engines.search_engine_arxiv.fetch_arxiv_results",
+ Mock(return_value=[mock_result]),
+ )
results = arxiv_engine._get_search_results("deep learning")
@@ -124,11 +124,10 @@ class TestArXivSearchExecution:
def test_search_empty_results(self, arxiv_engine, monkeypatch):
"""Test ArXiv search with no results."""
- mock_client = Mock()
- mock_client.results.return_value = iter([])
-
- monkeypatch.setattr("arxiv.Client", Mock(return_value=mock_client))
- monkeypatch.setattr("arxiv.Search", Mock(return_value=Mock()))
+ monkeypatch.setattr(
+ "local_deep_research.web_search_engines.engines.search_engine_arxiv.fetch_arxiv_results",
+ Mock(return_value=[]),
+ )
results = arxiv_engine._get_search_results("nonexistent query xyz")
assert results == []
@@ -158,28 +157,21 @@ class TestArXivErrorHandling:
"""Test that network errors are handled gracefully by _get_previews."""
from urllib.error import URLError
- mock_client = Mock()
- mock_client.results.side_effect = URLError("Network unreachable")
-
- monkeypatch.setattr("arxiv.Client", Mock(return_value=mock_client))
- monkeypatch.setattr("arxiv.Search", Mock(return_value=Mock()))
+ monkeypatch.setattr(
+ "local_deep_research.web_search_engines.engines.search_engine_arxiv.fetch_arxiv_results",
+ Mock(side_effect=URLError("Network unreachable")),
+ )
# _get_previews handles exceptions and returns empty list
results = arxiv_engine._get_previews("test query")
assert results == []
- def test_search_handles_arxiv_exception(self, arxiv_engine, monkeypatch):
- """Test that arXiv-specific exceptions are handled by _get_previews."""
- import arxiv
-
- mock_client = Mock()
- mock_client.results.side_effect = arxiv.UnexpectedEmptyPageError(
- "empty", 1, "http://arxiv.org"
+ def test_search_handles_fetch_exception(self, arxiv_engine, monkeypatch):
+ monkeypatch.setattr(
+ "local_deep_research.web_search_engines.engines.search_engine_arxiv.fetch_arxiv_results",
+ Mock(side_effect=RuntimeError("empty page")),
)
- monkeypatch.setattr("arxiv.Client", Mock(return_value=mock_client))
- monkeypatch.setattr("arxiv.Search", Mock(return_value=Mock()))
-
# _get_previews handles exceptions and returns empty list
results = arxiv_engine._get_previews("test query")
assert results == []
@@ -203,12 +195,10 @@ class TestArXivErrorHandling:
)
leaked = "Bearer sk-arxivleaked0987654321"
- mock_client = Mock()
- mock_client.results.side_effect = URLError(
- f"429 Too Many Requests: {leaked}"
+ monkeypatch.setattr(
+ "local_deep_research.web_search_engines.engines.search_engine_arxiv.fetch_arxiv_results",
+ Mock(side_effect=URLError(f"429 Too Many Requests: {leaked}")),
)
- monkeypatch.setattr("arxiv.Client", Mock(return_value=mock_client))
- monkeypatch.setattr("arxiv.Search", Mock(return_value=Mock()))
with pytest.raises(RateLimitError) as exc_info:
arxiv_engine._get_previews("test query")
@@ -238,12 +228,11 @@ class TestArXivSortingOptions:
from local_deep_research.web_search_engines.engines.search_engine_arxiv import (
ArXivSearchEngine,
)
- import arxiv
engine = ArXivSearchEngine(sort_by="relevance")
assert (
engine.sort_criteria.get(engine.sort_by)
- == arxiv.SortCriterion.Relevance
+ == ArxivSortCriterion.RELEVANCE
)
def test_sort_by_date(self):
@@ -251,12 +240,11 @@ class TestArXivSortingOptions:
from local_deep_research.web_search_engines.engines.search_engine_arxiv import (
ArXivSearchEngine,
)
- import arxiv
engine = ArXivSearchEngine(sort_by="submittedDate")
assert (
engine.sort_criteria.get(engine.sort_by)
- == arxiv.SortCriterion.SubmittedDate
+ == ArxivSortCriterion.SUBMITTED_DATE
)
def test_sort_order_ascending(self):
@@ -264,12 +252,11 @@ class TestArXivSortingOptions:
from local_deep_research.web_search_engines.engines.search_engine_arxiv import (
ArXivSearchEngine,
)
- import arxiv
engine = ArXivSearchEngine(sort_order="ascending")
assert (
engine.sort_directions.get(engine.sort_order)
- == arxiv.SortOrder.Ascending
+ == ArxivSortOrder.ASCENDING
)
diff --git a/tests/text_optimization/test_citation_formatter_behavior.py b/tests/text_optimization/test_citation_formatter_behavior.py
index 5b0a918ad6..58c47043f3 100644
--- a/tests/text_optimization/test_citation_formatter_behavior.py
+++ b/tests/text_optimization/test_citation_formatter_behavior.py
@@ -1672,7 +1672,13 @@ class TestCitationFormatterApplyInlineHyperlinks:
)
content = "Per [1] and [2]."
sources = [
- {"index": "1", "title": "T", "url": "https://arxiv.org/abs/1"},
+ # A real arXiv identifier: the URLClassifier tag follows the
+ # paper identifier, so a placeholder id gets the domain label.
+ {
+ "index": "1",
+ "title": "T",
+ "url": "https://arxiv.org/abs/2301.00001",
+ },
# Library hit: collection_name in metadata should win over
# the URL-derived domain tag.
{
diff --git a/tests/text_optimization/test_citation_formatter_contracts.py b/tests/text_optimization/test_citation_formatter_contracts.py
index 68db0ba537..b21d3fc069 100644
--- a/tests/text_optimization/test_citation_formatter_contracts.py
+++ b/tests/text_optimization/test_citation_formatter_contracts.py
@@ -444,10 +444,26 @@ class TestSourceLabelFidelity:
):
assert CitationFormatter()._extract_domain(url) != impostor
+ def test_arxiv_in_the_path_does_not_earn_its_tag(self):
+ """Regression control for the arXiv half of the defect below.
+
+ ``URLClassifier.classify`` used to detect arXiv with a bare
+ ``re.search`` over the whole URL, so an attacker-controlled path
+ segment (``evil.example/arxiv.org/...``) earned the ``arxiv`` tag.
+ This PR routes arXiv detection through
+ ``utilities.arxiv.is_arxiv_paper_url``, which parses the actual
+ hostname and identifier instead of substring-matching the raw URL,
+ closing this specific case. DOI and PubMed still delegate to a bare
+ ``re.search`` and remain vulnerable -- see the xfail below.
+ """
+ label = CitationFormatter()._extract_source_label(
+ "https://evil.example/arxiv.org/abs/1234"
+ )
+ assert label != "arxiv"
+
@pytest.mark.parametrize(
"url,impostor",
[
- ("https://evil.example/arxiv.org/abs/1234", "arxiv"),
("https://evil.example/?x=doi.org/10.1", "doi"),
(
"https://evil.example/pubmed.ncbi.nlm.nih.gov/12345",
@@ -459,13 +475,15 @@ class TestSourceLabelFidelity:
strict=True,
reason=(
"SECURITY DEFECT: _extract_source_label delegates to "
- "URLClassifier.classify, whose patterns are re.search'ed "
- "against the whole URL string rather than the host, so an "
- "attacker-controlled path or query segment earns the "
- "academic-source tag. SOURCE_TAGGED mode then renders "
- "[[arxiv-1]] on a link to evil.example. Root cause lives in "
- "content_fetcher/url_classifier.py; citation_formatter "
- "consumes it without re-checking the host."
+ "URLClassifier.classify, whose DOI/PubMed patterns are "
+ "re.search'ed against the whole URL string rather than the "
+ "host, so an attacker-controlled path or query segment earns "
+ "the academic-source tag. SOURCE_TAGGED mode then renders "
+ "[[doi-1]] or [[pubmed-1]] on a link to evil.example. Root "
+ "cause lives in content_fetcher/url_classifier.py; "
+ "citation_formatter consumes it without re-checking the "
+ "host. (The arXiv case of this defect is fixed -- see "
+ "test_arxiv_in_the_path_does_not_earn_its_tag above.)"
),
)
def test_known_source_in_the_path_does_not_earn_its_tag(
@@ -482,8 +500,11 @@ class TestSourceLabelFidelity:
assert formatter._extract_domain("https://www.github.com/a") == (
"github.com"
)
+ # A real identifier: the label now follows the paper identifier, not
+ # the hostname, so a placeholder id would fall through to the domain
+ # and the control would stop controlling for anything.
assert (
- formatter._extract_source_label("https://arxiv.org/abs/2401.1")
+ formatter._extract_source_label("https://arxiv.org/abs/2401.12345")
== "arxiv"
)
diff --git a/tests/utilities/arxiv_policy_ast.py b/tests/utilities/arxiv_policy_ast.py
new file mode 100644
index 0000000000..6a868ae0f8
--- /dev/null
+++ b/tests/utilities/arxiv_policy_ast.py
@@ -0,0 +1,90 @@
+"""Import-boundary checks for the external arXiv package."""
+
+import ast
+from pathlib import Path
+from typing import Final, override
+
+_REPO_ROOT = Path(__file__).resolve().parents[2]
+SHARED_UTILITY_PATH: Final = "src/local_deep_research/utilities/arxiv_api.py"
+_SCAN_ROOTS: Final = ("src", "scripts")
+_RUNNABLE_TEST_PATHS: Final = (
+ "tests/download_stuff_for_local.py",
+ "tests/performance/relevance_filter/eval_models.py",
+ "tests/performance/relevance_filter/eval_prompt.py",
+ "tests/performance/relevance_filter/test_live.py",
+ "tests/benchmarks/evaluators/arxiv_optimization/benchmark_arxiv_query_optimization.py",
+)
+
+
+def _is_external_arxiv(module_name: str) -> bool:
+ return module_name.partition(".")[0] == "arxiv"
+
+
+class _ArxivImportVisitor(ast.NodeVisitor):
+ def __init__(self) -> None:
+ self.violation_lines: set[int] = set()
+
+ @override
+ def visit_Import(self, node: ast.Import) -> None:
+ if any(_is_external_arxiv(alias.name) for alias in node.names):
+ self.violation_lines.add(node.lineno)
+
+ @override
+ def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
+ if (
+ node.level == 0
+ and node.module is not None
+ and _is_external_arxiv(node.module)
+ ):
+ self.violation_lines.add(node.lineno)
+
+ @override
+ def visit_Call(self, node: ast.Call) -> None:
+ if node.args and isinstance(node.args[0], ast.Constant):
+ module_name = node.args[0].value
+ if isinstance(module_name, str) and _is_external_arxiv(module_name):
+ if (
+ isinstance(node.func, ast.Name)
+ and node.func.id in {"__import__", "import_module"}
+ ) or (
+ isinstance(node.func, ast.Attribute)
+ and node.func.attr == "import_module"
+ ):
+ self.violation_lines.add(node.lineno)
+ self.generic_visit(node)
+
+
+def arxiv_policy_violation_lines(source: str) -> tuple[int, ...]:
+ """Return lines that load the external ``arxiv`` package."""
+ visitor = _ArxivImportVisitor()
+ visitor.visit(ast.parse(source))
+ return tuple(sorted(visitor.violation_lines))
+
+
+def _iter_scanned_paths() -> list[Path]:
+ paths: list[Path] = []
+ for root_name in _SCAN_ROOTS:
+ root = _REPO_ROOT / root_name
+ if root.is_dir():
+ paths.extend(root.rglob("*.py"))
+ paths.extend(
+ path
+ for relative in _RUNNABLE_TEST_PATHS
+ if (path := _REPO_ROOT / relative).is_file()
+ )
+ return sorted(paths)
+
+
+def scan_repo_for_arxiv_policy_violations() -> list[str]:
+ """Return sorted ``path:line`` external-arXiv import violations."""
+ violations: list[str] = []
+ for path in _iter_scanned_paths():
+ relative = path.relative_to(_REPO_ROOT).as_posix()
+ if relative == SHARED_UTILITY_PATH:
+ continue
+ source = path.read_text(encoding="utf-8")
+ violations.extend(
+ f"{relative}:{line}"
+ for line in arxiv_policy_violation_lines(source)
+ )
+ return sorted(violations)
diff --git a/tests/utilities/test_arxiv_api_gate.py b/tests/utilities/test_arxiv_api_gate.py
new file mode 100644
index 0000000000..e00af1252c
--- /dev/null
+++ b/tests/utilities/test_arxiv_api_gate.py
@@ -0,0 +1,197 @@
+"""Contract tests for the ``arxiv_api_request_gate`` policy utility.
+
+Issue #4783: every ``export.arxiv.org`` API request must traverse one
+process-wide monotonic 3-second single-flight gate.
+
+The utility ``local_deep_research.utilities.arxiv_api`` is the sole policy
+owner and must expose ``arxiv_api_request_gate()`` as a context manager:
+entering marks a spaced start under the process-wide lock (single-flight,
+at least three monotonic seconds between starts, failed starts still count
+for spacing, lock always released).
+
+Deterministic seams mirror the downloader gate naming so existing test
+patches retarget cleanly: ``_arxiv_api_request_lock``,
+``_last_request_started_at``, ``_monotonic``, ``_sleep``.
+"""
+
+import threading
+import types
+from collections.abc import Iterator
+
+import pytest
+from pytest_mock import MockerFixture
+
+from local_deep_research.utilities import arxiv_api as arxiv_api_module
+
+
[email protected](autouse=True)
+def fresh_arxiv_api_gate() -> Iterator[None]:
+ """Reset the process-wide gate state around each test."""
+ with arxiv_api_module._arxiv_api_request_lock:
+ arxiv_api_module._last_request_started_at = None
+ yield
+ with arxiv_api_module._arxiv_api_request_lock:
+ arxiv_api_module._last_request_started_at = None
+
+
+class TestArxivApiRequestGate:
+ """Tests for the ``arxiv_api_request_gate`` context manager."""
+
+ def test_first_gated_start_begins_immediately(
+ self, mocker: MockerFixture
+ ) -> None:
+ # Given a fresh process gate and a deterministic monotonic clock
+ starts: list[float] = []
+ mocker.patch.object(arxiv_api_module, "_monotonic", return_value=10.0)
+ hard_sleep = mocker.patch.object(arxiv_api_module, "_sleep")
+
+ # When the first gated request starts
+ with arxiv_api_module.arxiv_api_request_gate():
+ starts.append(arxiv_api_module._monotonic())
+
+ # Then the policy gate starts it immediately
+ assert starts == [10.0]
+ hard_sleep.assert_not_called()
+
+ def test_starts_are_spaced_process_wide(
+ self, mocker: MockerFixture
+ ) -> None:
+ # Given a clock advanced only by policy sleep
+ now = 100.0
+ starts: list[float] = []
+ sleeps: list[float] = []
+
+ def monotonic() -> float:
+ return now
+
+ def sleep(duration: float) -> None:
+ nonlocal now
+ sleeps.append(duration)
+ now += duration
+
+ mocker.patch.object(
+ arxiv_api_module, "_monotonic", side_effect=monotonic
+ )
+ mocker.patch.object(arxiv_api_module, "_sleep", side_effect=sleep)
+
+ # When two independent gated requests start
+ with arxiv_api_module.arxiv_api_request_gate():
+ starts.append(now)
+ with arxiv_api_module.arxiv_api_request_gate():
+ starts.append(now)
+
+ # Then their starts are at least three seconds apart
+ assert starts == [100.0, 103.0]
+ assert sleeps == [3.0]
+
+ def test_concurrent_gated_starts_are_single_flight(
+ self, mocker: MockerFixture
+ ) -> None:
+ # Given two gated bodies that would overlap without the gate lock
+ now = 200.0
+ active_requests = 0
+ maximum_active_requests = 0
+ call_count = 0
+ activity_lock = threading.Lock()
+ first_request_entered = threading.Event()
+ second_request_waiting_for_gate = threading.Event()
+
+ gate_lock = threading.Lock()
+
+ class ObservedLock:
+ def __enter__(self) -> "ObservedLock":
+ if gate_lock.locked():
+ second_request_waiting_for_gate.set()
+ gate_lock.acquire()
+ return self
+
+ def __exit__(
+ self,
+ _exc_type: type[BaseException] | None,
+ _exc_val: BaseException | None,
+ _exc_tb: types.TracebackType | None,
+ ) -> None:
+ gate_lock.release()
+
+ def monotonic() -> float:
+ return now
+
+ def sleep(duration: float) -> None:
+ nonlocal now
+ now += duration
+
+ def gated_body() -> None:
+ nonlocal active_requests, call_count, maximum_active_requests
+ with arxiv_api_module.arxiv_api_request_gate():
+ with activity_lock:
+ call_count += 1
+ request_number = call_count
+ active_requests += 1
+ maximum_active_requests = max(
+ maximum_active_requests, active_requests
+ )
+ try:
+ if request_number == 1:
+ first_request_entered.set()
+ assert second_request_waiting_for_gate.wait(timeout=1)
+ finally:
+ with activity_lock:
+ active_requests -= 1
+
+ mocker.patch.object(
+ arxiv_api_module, "_arxiv_api_request_lock", ObservedLock()
+ )
+ mocker.patch.object(
+ arxiv_api_module, "_monotonic", side_effect=monotonic
+ )
+ mocker.patch.object(arxiv_api_module, "_sleep", side_effect=sleep)
+
+ first_thread = threading.Thread(target=gated_body)
+ second_thread = threading.Thread(target=gated_body)
+
+ # When both gated requests run concurrently
+ first_thread.start()
+ assert first_request_entered.wait(timeout=1)
+ second_thread.start()
+ first_thread.join(timeout=1)
+ second_thread.join(timeout=1)
+
+ # Then only one gated body is active at a time
+ assert not first_thread.is_alive()
+ assert not second_thread.is_alive()
+ assert second_request_waiting_for_gate.is_set()
+ assert maximum_active_requests == 1
+
+ def test_failed_start_still_counts_for_spacing(
+ self, mocker: MockerFixture
+ ) -> None:
+ # Given a gated start whose body raises and a deterministic clock
+ now = 400.0
+ starts: list[float] = []
+ sleeps: list[float] = []
+
+ def monotonic() -> float:
+ return now
+
+ def sleep(duration: float) -> None:
+ nonlocal now
+ sleeps.append(duration)
+ now += duration
+
+ mocker.patch.object(
+ arxiv_api_module, "_monotonic", side_effect=monotonic
+ )
+ mocker.patch.object(arxiv_api_module, "_sleep", side_effect=sleep)
+
+ # When the failed start is followed by another gated request
+ with pytest.raises(ConnectionError):
+ with arxiv_api_module.arxiv_api_request_gate():
+ starts.append(now)
+ raise ConnectionError("connection refused")
+
+ with arxiv_api_module.arxiv_api_request_gate():
+ starts.append(now)
+
+ # Then the lock is released but the failed start still counts
+ assert starts == [400.0, 403.0]
+ assert sleeps == [3.0]
diff --git a/tests/utilities/test_arxiv_client_policy_enforcement.py b/tests/utilities/test_arxiv_client_policy_enforcement.py
new file mode 100644
index 0000000000..b6f40293a9
--- /dev/null
+++ b/tests/utilities/test_arxiv_client_policy_enforcement.py
@@ -0,0 +1,92 @@
+# allow: no-sut-import — guardian; scans runnable source for external arxiv imports
+from pathlib import Path
+
+import pytest
+
+from . import arxiv_policy_ast
+from .arxiv_policy_ast import (
+ SHARED_UTILITY_PATH,
+ arxiv_policy_violation_lines,
+ scan_repo_for_arxiv_policy_violations,
+)
+
+
+ "source",
+ [
+ "import arxiv\n",
+ "import arxiv as ax\n",
+ "from arxiv import Search\n",
+ "from arxiv import *\n",
+ 'module = __import__("arxiv")\n',
+ 'module = importlib.import_module("arxiv")\n',
+ ],
+)
+def test_import_boundary_rejects_external_arxiv_loading(source: str) -> None:
+ assert arxiv_policy_violation_lines(source) == (1,)
+
+
+ "source",
+ [
+ 'from importlib import import_module\nmodule = import_module("arxiv")\n',
+ 'import importlib as il\nmodule = il.import_module("arxiv")\n',
+ ],
+)
+def test_import_boundary_rejects_literal_dynamic_import_aliases(
+ source: str,
+) -> None:
+ assert arxiv_policy_violation_lines(source) == (2,)
+
+
+ "source",
+ [
+ "# import arxiv\n",
+ '"""import arxiv"""\n',
+ 'note = "import arxiv"\n',
+ "module = __import__(module_name)\n",
+ "module = importlib.import_module(module_name)\n",
+ "from importlib import import_module\nmodule = import_module(module_name)\n",
+ "import importlib as il\nmodule = il.import_module(module_name)\n",
+ "from local_deep_research.utilities import arxiv as arxiv_utils\n",
+ ],
+)
+def test_import_boundary_ignores_non_external_static_imports(
+ source: str,
+) -> None:
+ assert arxiv_policy_violation_lines(source) == ()
+
+
+def _write_source(root: Path, relative: str, source: str) -> None:
+ path = root / relative
+ path.parent.mkdir(parents=True, exist_ok=True)
+ _ = path.write_text(source, encoding="utf-8")
+
+
+def test_repository_scanner_uses_exact_runnable_scope(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ included = (
+ "scripts/tool.py",
+ "src/package/module.py",
+ "tests/benchmarks/evaluators/arxiv_optimization/benchmark_arxiv_query_optimization.py",
+ "tests/download_stuff_for_local.py",
+ "tests/performance/relevance_filter/eval_models.py",
+ "tests/performance/relevance_filter/eval_prompt.py",
+ "tests/performance/relevance_filter/test_live.py",
+ )
+ for relative in included:
+ _write_source(tmp_path, relative, "import arxiv\n")
+ _write_source(tmp_path, SHARED_UTILITY_PATH, "import arxiv\n")
+ _write_source(tmp_path, "tests/unit/test_fixture.py", "import arxiv\n")
+ monkeypatch.setattr(arxiv_policy_ast, "_REPO_ROOT", tmp_path)
+
+ assert scan_repo_for_arxiv_policy_violations() == [
+ f"{relative}:1" for relative in sorted(included)
+ ]
+
+
+def test_repository_has_no_external_arxiv_imports() -> None:
+ assert scan_repo_for_arxiv_policy_violations() == []
diff --git a/tests/utilities/test_arxiv_fetch_api.py b/tests/utilities/test_arxiv_fetch_api.py
new file mode 100644
index 0000000000..1e24308584
--- /dev/null
+++ b/tests/utilities/test_arxiv_fetch_api.py
@@ -0,0 +1,128 @@
+from unittest.mock import MagicMock, Mock
+
+import arxiv
+import pytest
+from pytest_mock import MockerFixture
+
+from local_deep_research.utilities import arxiv_api as arxiv_api_module
+
+
+class FetchIterationError(RuntimeError):
+ pass
+
+
+def _stub_policy_client(
+ mocker: MockerFixture,
+) -> tuple[MagicMock, MagicMock, Mock]:
+ policy = mocker.patch.object(arxiv_api_module, "_policy_arxiv_client")
+ context = policy.return_value
+ context.__exit__.return_value = False
+ client = context.__enter__.return_value
+ return policy, context, client
+
+
+def test_request_types_expose_stable_defaults_and_values() -> None:
+ request = arxiv_api_module.ArxivQueryRequest(query="q", max_results=10)
+
+ assert request.sort_by is arxiv_api_module.ArxivSortCriterion.RELEVANCE
+ assert request.sort_order is arxiv_api_module.ArxivSortOrder.DESCENDING
+ assert arxiv_api_module.ArxivSortCriterion.RELEVANCE == "relevance"
+ assert (
+ arxiv_api_module.ArxivSortCriterion.LAST_UPDATED_DATE
+ == "lastUpdatedDate"
+ )
+ assert arxiv_api_module.ArxivSortCriterion.SUBMITTED_DATE == "submittedDate"
+ assert arxiv_api_module.ArxivSortOrder.ASCENDING == "ascending"
+ assert arxiv_api_module.ArxivSortOrder.DESCENDING == "descending"
+
+
+def test_query_request_maps_search_enums_and_materializes_inside_context(
+ mocker: MockerFixture,
+) -> None:
+ policy, context, client = _stub_policy_client(mocker)
+ search_value = Mock(name="search")
+ search = mocker.patch.object(arxiv, "Search", return_value=search_value)
+ papers = [Mock(name="paper")]
+
+ def results(_search: Mock):
+ assert context.__exit__.call_count == 0
+ yield from papers
+
+ client.results.side_effect = results
+ request = arxiv_api_module.ArxivQueryRequest(
+ query="graph models",
+ max_results=7,
+ sort_by=arxiv_api_module.ArxivSortCriterion.LAST_UPDATED_DATE,
+ sort_order=arxiv_api_module.ArxivSortOrder.ASCENDING,
+ )
+
+ fetched = arxiv_api_module.fetch_arxiv_results(request)
+
+ assert fetched == papers
+ assert fetched[0] is papers[0]
+ search.assert_called_once_with(
+ query="graph models",
+ max_results=7,
+ sort_by=arxiv.SortCriterion.LastUpdatedDate,
+ sort_order=arxiv.SortOrder.Ascending,
+ )
+ policy.assert_called_once_with(page_size=7)
+ client.results.assert_called_once_with(search_value)
+ context.__exit__.assert_called_once_with(None, None, None)
+
+
+def test_id_request_uses_id_search_and_default_client_page_size(
+ mocker: MockerFixture,
+) -> None:
+ policy, _, client = _stub_policy_client(mocker)
+ search_value = Mock(name="search")
+ search = mocker.patch.object(arxiv, "Search", return_value=search_value)
+ paper = Mock(name="paper")
+ client.results.return_value = iter([paper])
+
+ fetched = arxiv_api_module.fetch_arxiv_results(
+ arxiv_api_module.ArxivIdRequest(arxiv_id="2101.12345")
+ )
+
+ assert fetched == [paper]
+ search.assert_called_once_with(id_list=["2101.12345"], max_results=1)
+ policy.assert_called_once_with()
+
+
+def test_iteration_error_propagates_after_context_cleanup(
+ mocker: MockerFixture,
+) -> None:
+ _, context, client = _stub_policy_client(mocker)
+ mocker.patch.object(arxiv, "Search", return_value=Mock())
+ failure = FetchIterationError("iteration failed")
+
+ def results(_search: Mock):
+ raise failure
+ yield
+
+ client.results.side_effect = results
+
+ with pytest.raises(FetchIterationError) as exc_info:
+ arxiv_api_module.fetch_arxiv_results(
+ arxiv_api_module.ArxivIdRequest(arxiv_id="2101.12345")
+ )
+
+ assert exc_info.value is failure
+ assert context.__exit__.call_args.args[0] is FetchIterationError
+ assert context.__exit__.call_args.args[1] is failure
+
+
+def test_search_construction_error_propagates_without_opening_client(
+ mocker: MockerFixture,
+) -> None:
+ policy, _, _ = _stub_policy_client(mocker)
+ failure = FetchIterationError("search failed")
+ mocker.patch.object(arxiv, "Search", side_effect=failure)
+
+ with pytest.raises(FetchIterationError) as exc_info:
+ arxiv_api_module.fetch_arxiv_results(
+ arxiv_api_module.ArxivIdRequest(arxiv_id="2101.12345")
+ )
+
+ assert exc_info.value is failure
+ policy.assert_not_called()
diff --git a/tests/utilities/test_arxiv_policy_client.py b/tests/utilities/test_arxiv_policy_client.py
new file mode 100644
index 0000000000..5cc464f7a7
--- /dev/null
+++ b/tests/utilities/test_arxiv_policy_client.py
@@ -0,0 +1,318 @@
+"""Contract tests for the private policy arXiv client context manager.
+
+Issue #4783: every ``export.arxiv.org`` API request must traverse one
+process-wide monotonic 3-second single-flight gate and ``SafeSession``.
+
+The utility ``local_deep_research.utilities.arxiv_api`` is the sole policy
+owner and keeps ``_policy_arxiv_client(*, page_size: int | None = None)``
+that constructs ``arxiv.Client`` through the ``arxiv`` module attribute
+with ``delay_seconds=0``, closes the discarded default session, pins a
+gated ``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``.
+"""
+
+from collections.abc import Iterator
+from dataclasses import dataclass
+from typing import Protocol
+from unittest.mock import MagicMock
+
+import arxiv
+import pytest
+from pytest_mock import MockerFixture
+
+from local_deep_research.security import SafeSession
+from local_deep_research.utilities import arxiv_api as arxiv_api_module
+
+
+class ResultsIterationError(RuntimeError):
+ """Typed error raised when iterating arxiv.Client results fails.
+
+ Subclass of ``RuntimeError`` so the existing
+ ``pytest.raises(RuntimeError)`` assertion keeps catching it; the
+ narrow type lets the audit rule for typed exceptions pass.
+ """
+
+
+@dataclass(frozen=True, slots=True)
+class StubClientConstruction:
+ """Recorded arxiv.Client construction arguments."""
+
+ page_size: int
+ delay_seconds: float
+ num_retries: int
+
+
+class StubArxivClient(Protocol):
+ """Structural shape of the recording arxiv.Client double."""
+
+ page_size: int
+ delay_seconds: float
+ num_retries: int
+
+
+@dataclass(frozen=True, slots=True)
+class StubbedClientFactory:
+ """Recording doubles installed in place of ``arxiv.Client``."""
+
+ constructed: list[StubClientConstruction]
+ instances: list[StubArxivClient]
+ default_sessions: list[MagicMock]
+
+
[email protected](autouse=True)
+def fresh_arxiv_api_gate() -> Iterator[None]:
+ """Reset the process-wide gate state around each test."""
+ with arxiv_api_module._arxiv_api_request_lock:
+ arxiv_api_module._last_request_started_at = None
+ yield
+ with arxiv_api_module._arxiv_api_request_lock:
+ arxiv_api_module._last_request_started_at = None
+
+
+def stub_arxiv_client(mocker: MockerFixture) -> Iterator[StubbedClientFactory]:
+ """Replace the ``arxiv.Client`` attribute with a recording double."""
+ constructed: list[StubClientConstruction] = []
+ instances: list[StubArxivClient] = []
+ default_sessions: list[MagicMock] = []
+
+ class StubClient:
+ def __init__(
+ self,
+ page_size: int = 100,
+ delay_seconds: float = 3.0,
+ num_retries: int = 3,
+ ) -> None:
+ self.page_size: int = page_size
+ self.delay_seconds: float = delay_seconds
+ self.num_retries: int = num_retries
+ self._last_request_dt: float | None = None
+ default_session = MagicMock(name="default_session")
+ self._session: MagicMock = default_session
+ constructed.append(
+ StubClientConstruction(
+ page_size=page_size,
+ delay_seconds=delay_seconds,
+ num_retries=num_retries,
+ )
+ )
+ default_sessions.append(default_session)
+ instances.append(self)
+
+ mocker.patch.object(arxiv, "Client", StubClient)
+ yield StubbedClientFactory(
+ constructed=constructed,
+ instances=instances,
+ default_sessions=default_sessions,
+ )
+
+
+class TestPolicyArxivClient:
+ """Tests for the private policy client context manager."""
+
+ def test_client_constructed_with_zero_delay(
+ self, stub_arxiv_client: StubbedClientFactory
+ ) -> None:
+ # Given the arxiv.Client attribute replaced by a recording double
+
+ # When a policy client is opened
+ with arxiv_api_module._policy_arxiv_client() as client:
+ # Then construction went through arxiv.Client with zero delay
+ assert len(stub_arxiv_client.constructed) == 1
+ assert stub_arxiv_client.constructed[0].delay_seconds == 0
+ assert client is stub_arxiv_client.instances[0]
+ assert client.delay_seconds == 0
+
+ def test_page_size_is_passed_through(
+ self, stub_arxiv_client: StubbedClientFactory
+ ) -> None:
+ # Given a caller requesting a specific page size
+
+ # When a policy client is opened with that page size
+ with arxiv_api_module._policy_arxiv_client(page_size=25) as client:
+ assert client.page_size == 25
+
+ # Then construction received the page size with zero delay
+ assert stub_arxiv_client.constructed[0].page_size == 25
+ assert stub_arxiv_client.constructed[0].delay_seconds == 0
+
+ def test_adapter_pins_safe_session(
+ self, stub_arxiv_client: StubbedClientFactory
+ ) -> None:
+ # Given a policy-adapted client
+
+ # When the adapter installs the request session
+
+ # Then the pinned session is a SafeSession
+ with arxiv_api_module._policy_arxiv_client() as client:
+ assert isinstance(client._session, SafeSession)
+
+ def test_discarded_default_session_is_closed(
+ self, stub_arxiv_client: StubbedClientFactory
+ ) -> None:
+ # Given the default session recorded when the client is constructed
+
+ # When the policy scope runs to completion
+ with arxiv_api_module._policy_arxiv_client():
+ pass
+
+ # Then the discarded default session is closed exactly once
+ assert len(stub_arxiv_client.default_sessions) == 1
+ discarded = stub_arxiv_client.default_sessions[0]
+ discarded.close.assert_called_once()
+
+ def test_adapted_session_closed_on_success(
+ self,
+ mocker: MockerFixture,
+ stub_arxiv_client: StubbedClientFactory,
+ ) -> None:
+ # Given a policy-adapted session whose cleanup is observed
+ adapted_close: MagicMock | None = None
+ with arxiv_api_module._policy_arxiv_client() as client:
+ adapted = client._session
+ adapted_close = mocker.patch.object(adapted, "close")
+
+ # Then the adapted session is closed exactly once on normal exit
+ assert adapted_close is not None
+ adapted_close.assert_called_once()
+
+ def test_adapted_session_closed_on_exception(
+ self,
+ mocker: MockerFixture,
+ stub_arxiv_client: StubbedClientFactory,
+ ) -> None:
+ # Given a policy-adapted scope whose body raises
+ adapted_close: MagicMock | None = None
+ with pytest.raises(ResultsIterationError):
+ with arxiv_api_module._policy_arxiv_client() as client:
+ adapted = client._session
+ adapted_close = mocker.patch.object(adapted, "close")
+ raise ResultsIterationError("results iteration failed")
+
+ # Then the adapted session is still closed exactly once
+ assert adapted_close is not None
+ adapted_close.assert_called_once()
+
+ def test_adapted_close_failure_preserves_iteration_exception(
+ self,
+ mocker: MockerFixture,
+ stub_arxiv_client: StubbedClientFactory,
+ ) -> None:
+ # Given an iteration failure followed by a failing session close
+ iteration_error = ResultsIterationError("results iteration failed")
+ adapted_close: MagicMock | None = None
+
+ # When the policy scope unwinds
+ with pytest.raises(ResultsIterationError) as raised:
+ with arxiv_api_module._policy_arxiv_client() as client:
+ adapted_close = mocker.patch.object(
+ client._session,
+ "close",
+ side_effect=ResultsIterationError("session close failed"),
+ )
+ raise iteration_error
+
+ # Then cleanup runs once without replacing the iteration failure
+ assert raised.value is iteration_error
+ assert adapted_close is not None
+ adapted_close.assert_called_once()
+
+ def test_wire_call_forces_timeout_and_disables_redirects(
+ self,
+ mocker: MockerFixture,
+ stub_arxiv_client: StubbedClientFactory,
+ ) -> None:
+ # Given the SafeSession request funnel observed and a frozen clock
+ request = mocker.patch.object(SafeSession, "request")
+ mocker.patch.object(arxiv_api_module, "_monotonic", return_value=10.0)
+ mocker.patch.object(arxiv_api_module, "_sleep")
+
+ # When one API query travels the adapted session
+ with arxiv_api_module._policy_arxiv_client() as client:
+ client._session.get(
+ "https://export.arxiv.org/api/query",
+ params={"id_list": "2301.12345"},
+ )
+
+ # Then the wire call forces the policy request arguments
+ request.assert_called_once()
+ call = request.call_args
+ assert call is not None
+ assert call.kwargs.get("timeout") == 10
+ assert call.kwargs.get("allow_redirects") is False
+ assert call.kwargs.get("params") == {"id_list": "2301.12345"}
+ assert "https://export.arxiv.org/api/query" in str(call)
+
+ def test_wire_calls_share_the_process_wide_gate(
+ self,
+ mocker: MockerFixture,
+ stub_arxiv_client: StubbedClientFactory,
+ ) -> None:
+ # Given a clock advanced only by policy sleep
+ now = 100.0
+ starts: list[float] = []
+ sleeps: list[float] = []
+
+ def monotonic() -> float:
+ return now
+
+ def sleep(duration: float) -> None:
+ nonlocal now
+ sleeps.append(duration)
+ now += duration
+
+ def request(
+ _method: str,
+ _url: str,
+ *,
+ params: dict[str, str] | None = None,
+ timeout: int | float | None = None,
+ allow_redirects: bool = False,
+ ) -> None:
+ starts.append(now)
+
+ mocker.patch.object(
+ arxiv_api_module, "_monotonic", side_effect=monotonic
+ )
+ mocker.patch.object(arxiv_api_module, "_sleep", side_effect=sleep)
+ mocker.patch.object(SafeSession, "request", side_effect=request)
+
+ # When two queries travel one adapted client back to back
+ with arxiv_api_module._policy_arxiv_client() as client:
+ client._session.get("https://export.arxiv.org/api/query")
+ client._session.get("https://export.arxiv.org/api/query")
+
+ # Then their wire starts are spaced by the shared gate
+ assert starts == [100.0, 103.0]
+ assert sleeps == [3.0]
+
+ def test_adapted_client_requests_use_shared_gate(
+ self,
+ mocker: MockerFixture,
+ stub_arxiv_client: StubbedClientFactory,
+ ) -> None:
+ # Given the module gate replaced and the SafeSession funnel stubbed
+ gate = mocker.patch.object(arxiv_api_module, "arxiv_api_request_gate")
+ request = mocker.patch.object(SafeSession, "request")
+
+ # When one request travels the adapted client session
+ with arxiv_api_module._policy_arxiv_client() as client:
+ client._session.get(
+ "https://export.arxiv.org/api/query",
+ headers={"User-Agent": "LDR-test"},
+ )
+
+ # Then the wire call traversed the shared gate and the
+ # underlying SafeSession call carried the policy arguments
+ gate.assert_called_once_with()
+ request.assert_called_once()
+ call = request.call_args
+ assert call is not None
+ assert call.kwargs.get("timeout") == 10
+ assert call.kwargs.get("allow_redirects") is False
+ assert call.kwargs.get("headers") == {"User-Agent": "LDR-test"}
diff --git a/tests/utilities/test_citation_normalizer.py b/tests/utilities/test_citation_normalizer.py
index 316ea33c18..760d0b74e2 100644
--- a/tests/utilities/test_citation_normalizer.py
+++ b/tests/utilities/test_citation_normalizer.py
@@ -240,6 +240,19 @@ class TestExtractArxivId:
def test_explicit(self):
assert _extract_arxiv_id({"arxiv_id": "2401.12345"}) == "2401.12345"
+ def test_explicit_takes_precedence_over_url(self):
+ # Given an explicit ID that differs from the URL fallback
+ source = {
+ "arxiv_id": "2401.99999v2",
+ "link": "https://arxiv.org/abs/2401.12345v1",
+ }
+
+ # When the citation ID is extracted
+ result = _extract_arxiv_id(source)
+
+ # Then the explicit value wins unchanged
+ assert result == "2401.99999v2"
+
def test_old_format_hyphen_archive(self):
assert (
_extract_arxiv_id(
@@ -272,6 +285,28 @@ class TestExtractArxivId:
== "2501.12345v2"
)
+ def test_from_versioned_pdf_url(self):
+ # Given an arXiv PDF URL with query and fragment adornments
+ source = {
+ "link": "https://arxiv.org/pdf/math.AG/0601001v4.pdf?download=1#page=3"
+ }
+
+ # When the citation ID is extracted
+ result = _extract_arxiv_id(source)
+
+ # Then the legacy case and explicit version are preserved
+ assert result == "math.AG/0601001v4"
+
+ def test_url_fallback_rejects_unrelated_host(self):
+ # Given an unrelated host with an arXiv-looking path
+ source = {"link": "https://example.com/arxiv.org/abs/2501.12345v2"}
+
+ # When the citation ID is extracted
+ result = _extract_arxiv_id(source)
+
+ # Then no arXiv ID is inferred from the untrusted path text
+ assert result 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.py
index f5b6499e23..990ffbd015 100644
--- a/tests/web_search_engines/engines/test_arxiv_coverage.py
+++ b/tests/web_search_engines/engines/test_arxiv_coverage.py
@@ -18,6 +18,16 @@ from unittest.mock import MagicMock, Mock, PropertyMock, patch, mock_open
import pytest
+from local_deep_research.utilities.arxiv_api import (
+ ArxivSortCriterion,
+ ArxivSortOrder,
+)
+
+FETCH_SEAM = (
+ "local_deep_research.web_search_engines.engines."
+ "search_engine_arxiv.fetch_arxiv_results"
+)
+
# ---------------------------------------------------------------------------
# Helpers
@@ -208,42 +218,26 @@ class TestInit:
class TestGetSearchResults:
def test_search_results_default_sort(self, engine):
"""_get_search_results uses default relevance sort."""
- import arxiv
-
- with (
- patch.object(arxiv, "Client") as mock_client_cls,
- patch.object(arxiv, "Search") as mock_search_cls,
- ):
- mock_client = Mock()
- mock_client.results.return_value = [_make_mock_paper()]
- mock_client_cls.return_value = mock_client
-
+ with patch(FETCH_SEAM, return_value=[_make_mock_paper()]) as fetch:
results = engine._get_search_results("test query")
assert len(results) == 1
- mock_search_cls.assert_called_once()
+ request = fetch.call_args.args[0]
+ assert request.sort_by is ArxivSortCriterion.RELEVANCE
+ assert request.sort_order is ArxivSortOrder.DESCENDING
def test_search_results_unknown_sort_fallback(self, engine):
"""Unknown sort_by/sort_order falls back to defaults."""
- import arxiv
-
engine.sort_by = "unknown_sort"
engine.sort_order = "unknown_order"
- with (
- patch.object(arxiv, "Client") as mock_client_cls,
- patch.object(arxiv, "Search"),
- ):
- mock_client = Mock()
- mock_client.results.return_value = []
- mock_client_cls.return_value = mock_client
-
+ with patch(FETCH_SEAM, return_value=[]) as fetch:
results = engine._get_search_results("q")
- # Should not raise, falls back to defaults
assert results == []
+ request = fetch.call_args.args[0]
+ assert request.sort_by is ArxivSortCriterion.RELEVANCE
+ assert request.sort_order is ArxivSortOrder.DESCENDING
def test_search_results_submitted_date_ascending(self):
"""Sort by submittedDate ascending."""
- import arxiv
-
with patch(
"local_deep_research.advanced_search_system.filters.journal_reputation_filter.JournalReputationFilter"
) as mock_jrf:
@@ -256,17 +250,11 @@ class TestGetSearchResults:
sort_by="submittedDate", sort_order="ascending"
)
- with (
- patch.object(arxiv, "Client") as mock_client_cls,
- patch.object(arxiv, "Search") as mock_search_cls,
- ):
- mock_client = Mock()
- mock_client.results.return_value = []
- mock_client_cls.return_value = mock_client
+ with patch(FETCH_SEAM, return_value=[]) as fetch:
eng._get_search_results("q")
- call_kwargs = mock_search_cls.call_args[1]
- assert call_kwargs["sort_by"] == arxiv.SortCriterion.SubmittedDate
- assert call_kwargs["sort_order"] == arxiv.SortOrder.Ascending
+ request = fetch.call_args.args[0]
+ assert request.sort_by is ArxivSortCriterion.SUBMITTED_DATE
+ assert request.sort_order is ArxivSortOrder.ASCENDING
# ===========================================================================
@@ -738,17 +726,8 @@ class TestRun:
class TestGetPaperDetails:
def test_paper_found_full_mode(self, engine):
"""Paper found with full content."""
- import arxiv
-
paper = _make_mock_paper()
- with (
- patch.object(arxiv, "Client") as mock_client_cls,
- patch.object(arxiv, "Search"),
- ):
- mock_client = Mock()
- mock_client.results.return_value = [paper]
- mock_client_cls.return_value = mock_client
-
+ with patch(FETCH_SEAM, return_value=[paper]):
result = engine.get_paper_details("2101.00001")
assert result["title"] == "Test Paper"
assert result["content"] == paper.summary
@@ -756,120 +735,60 @@ class TestGetPaperDetails:
def test_paper_not_found(self, engine):
"""No paper found returns empty dict."""
- import arxiv
-
- with (
- patch.object(arxiv, "Client") as mock_client_cls,
- patch.object(arxiv, "Search"),
- ):
- mock_client = Mock()
- mock_client.results.return_value = []
- mock_client_cls.return_value = mock_client
-
+ with patch(FETCH_SEAM, return_value=[]):
result = engine.get_paper_details("9999.99999")
assert result == {}
def test_paper_details_exception(self, engine):
"""Exception returns empty dict."""
- import arxiv
-
- with patch.object(arxiv, "Client", side_effect=Exception("boom")):
+ with patch(FETCH_SEAM, side_effect=Exception("boom")):
result = engine.get_paper_details("2101.00001")
assert result == {}
def test_paper_long_summary_snippet_truncated(self, engine):
"""Long summary gets truncated snippet with ellipsis."""
- import arxiv
-
paper = _make_mock_paper(summary="A" * 300)
- with (
- patch.object(arxiv, "Client") as mock_client_cls,
- patch.object(arxiv, "Search"),
- ):
- mock_client = Mock()
- mock_client.results.return_value = [paper]
- mock_client_cls.return_value = mock_client
-
+ with patch(FETCH_SEAM, return_value=[paper]):
result = engine.get_paper_details("2101.00001")
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."""
- import arxiv
-
paper = _make_mock_paper()
with (
- patch.object(arxiv, "Client") as mock_client_cls,
- patch.object(arxiv, "Search"),
+ patch(FETCH_SEAM, return_value=[paper]),
patch.object(
engine_with_pdf,
"_download_pdf_safely",
return_value="/tmp/paper.pdf",
) as mock_download,
):
- mock_client = Mock()
- mock_client.results.return_value = [paper]
- mock_client_cls.return_value = mock_client
-
result = engine_with_pdf.get_paper_details("2101.00001")
assert result["pdf_path"] == "/tmp/paper.pdf"
- mock_download.assert_called_once()
+ mock_download.assert_called_once_with(
+ paper, engine_with_pdf.download_dir
+ )
+ paper.download_pdf.assert_not_called()
def test_paper_details_pdf_download_fails(self, engine_with_pdf):
"""PDF download failure in get_paper_details is handled gracefully."""
- import arxiv
-
paper = _make_mock_paper()
with (
- patch.object(arxiv, "Client") as mock_client_cls,
- patch.object(arxiv, "Search"),
+ patch(FETCH_SEAM, return_value=[paper]),
patch.object(
engine_with_pdf,
"_download_pdf_safely",
side_effect=Exception("download error"),
- ),
+ ) as mock_download,
):
- mock_client = Mock()
- mock_client.results.return_value = [paper]
- mock_client_cls.return_value = mock_client
-
result = engine_with_pdf.get_paper_details("2101.00001")
assert result["title"] == "Test Paper"
assert "pdf_path" not in result
-
- def test_paper_details_no_published_or_updated(self, engine):
- """Paper with no published/updated dates returns None for those fields."""
- import arxiv
-
- paper = _make_mock_paper(published=None, updated=None)
- with (
- patch.object(arxiv, "Client") as mock_client_cls,
- patch.object(arxiv, "Search"),
- ):
- mock_client = Mock()
- mock_client.results.return_value = [paper]
- mock_client_cls.return_value = mock_client
-
- result = engine.get_paper_details("2101.00001")
- assert result["published"] is None
- assert result["updated"] is None
-
- def test_paper_details_short_summary_no_ellipsis(self, engine):
- """Short summary in get_paper_details doesn't get truncated."""
- import arxiv
-
- paper = _make_mock_paper(summary="Short")
- with (
- patch.object(arxiv, "Client") as mock_client_cls,
- patch.object(arxiv, "Search"),
- ):
- mock_client = Mock()
- mock_client.results.return_value = [paper]
- mock_client_cls.return_value = mock_client
-
- result = engine.get_paper_details("2101.00001")
- assert result["snippet"] == "Short"
+ mock_download.assert_called_once_with(
+ paper, engine_with_pdf.download_dir
+ )
+ paper.download_pdf.assert_not_called()
# ===========================================================================
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.py
index 932e24c42b..f84c59a4ac 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
@@ -8,10 +8,9 @@ than ``arxiv.Result.download_pdf``, which fetches via
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.
-This is narrower than "the same session as the rest of the arXiv
-integration": this engine's metadata queries (``arxiv.Client()``) still go
-through the ``arxiv`` package's own bare, unvalidated ``requests.Session()``
-— only the PDF fetch is gated.
+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
diff --git a/tests/web_search_engines/engines/test_arxiv_policy_transport.py b/tests/web_search_engines/engines/test_arxiv_policy_transport.py
new file mode 100644
index 0000000000..7c98892ae5
--- /dev/null
+++ b/tests/web_search_engines/engines/test_arxiv_policy_transport.py
@@ -0,0 +1,105 @@
+from datetime import datetime
+from unittest.mock import Mock, patch
+
+import pytest
+
+from local_deep_research.utilities.arxiv_api import (
+ ArxivIdRequest,
+ ArxivQueryRequest,
+ ArxivSortCriterion,
+ ArxivSortOrder,
+)
+
+ENGINE_MODULE = (
+ "local_deep_research.web_search_engines.engines.search_engine_arxiv"
+)
+FETCH_SEAM = f"{ENGINE_MODULE}.fetch_arxiv_results"
+JOURNAL_FILTER_SEAM = (
+ "local_deep_research.advanced_search_system.filters."
+ "journal_reputation_filter."
+ "JournalReputationFilter.create_default"
+)
+
+
+def _make_engine():
+ from local_deep_research.web_search_engines.engines.search_engine_arxiv import (
+ ArXivSearchEngine,
+ )
+
+ with patch(JOURNAL_FILTER_SEAM, return_value=None):
+ engine = ArXivSearchEngine()
+ engine.rate_tracker.apply_rate_limit = Mock(return_value=0)
+ return engine
+
+
+def _make_detail_paper() -> Mock:
+ paper = Mock()
+ paper.entry_id = "https://arxiv.org/abs/2101.12345"
+ paper.title = "Test Paper"
+ paper.summary = "Short summary"
+ paper.authors = [Mock(name="Author 1")]
+ paper.published = datetime(2021, 1, 15)
+ paper.updated = datetime(2021, 2, 15)
+ paper.journal_ref = "Journal Ref"
+ paper.pdf_url = "https://arxiv.org/pdf/2101.12345.pdf"
+ paper.categories = ["cs.AI"]
+ paper.comment = "Comment"
+ paper.doi = "10.1234/test"
+ return paper
+
+
+def test_query_search_uses_typed_fetch_request() -> None:
+ engine = _make_engine()
+ paper = Mock()
+
+ with patch(FETCH_SEAM, return_value=[paper]) as fetch:
+ result = engine._get_search_results("test query")
+
+ assert result == [paper]
+ fetch.assert_called_once_with(
+ ArxivQueryRequest(
+ query="test query",
+ max_results=engine.max_results,
+ sort_by=ArxivSortCriterion.RELEVANCE,
+ sort_order=ArxivSortOrder.DESCENDING,
+ )
+ )
+
+
+def test_query_search_propagates_fetch_error() -> None:
+ engine = _make_engine()
+ failure = RuntimeError("boom")
+
+ with patch(FETCH_SEAM, side_effect=failure):
+ with pytest.raises(RuntimeError) as exc_info:
+ engine._get_search_results("test query")
+
+ assert exc_info.value is failure
+
+
+def test_paper_details_uses_id_fetch_request() -> None:
+ engine = _make_engine()
+
+ with patch(FETCH_SEAM, return_value=[_make_detail_paper()]) as fetch:
+ result = engine.get_paper_details("2101.12345")
+
+ assert result["title"] == "Test Paper"
+ fetch.assert_called_once_with(ArxivIdRequest(arxiv_id="2101.12345"))
+
+
+def test_paper_details_returns_empty_when_fetch_is_empty() -> None:
+ engine = _make_engine()
+
+ with patch(FETCH_SEAM, return_value=[]):
+ result = engine.get_paper_details("missing")
+
+ assert result == {}
+
+
+def test_paper_details_preserves_existing_fetch_error_handling() -> None:
+ engine = _make_engine()
+
+ with patch(FETCH_SEAM, side_effect=RuntimeError("boom")):
+ result = engine.get_paper_details("2101.12345")
+
+ assert result == {}
diff --git a/tests/web_search_engines/engines/test_search_engine_arxiv.py b/tests/web_search_engines/engines/test_search_engine_arxiv.py
index 0002a4de19..9767cdc25a 100644
--- a/tests/web_search_engines/engines/test_search_engine_arxiv.py
+++ b/tests/web_search_engines/engines/test_search_engine_arxiv.py
@@ -160,7 +160,7 @@ class TestArXivSearchEngineInit:
from local_deep_research.web_search_engines.engines.search_engine_arxiv import (
ArXivSearchEngine,
)
- import arxiv
+ from local_deep_research.utilities.arxiv_api import ArxivSortCriterion
with patch(
"local_deep_research.advanced_search_system.filters.journal_reputation_filter.JournalReputationFilter.create_default",
@@ -170,23 +170,22 @@ class TestArXivSearchEngineInit:
assert (
engine.sort_criteria["relevance"]
- == arxiv.SortCriterion.Relevance
+ == ArxivSortCriterion.RELEVANCE
)
assert (
engine.sort_criteria["lastUpdatedDate"]
- == arxiv.SortCriterion.LastUpdatedDate
+ == ArxivSortCriterion.LAST_UPDATED_DATE
)
assert (
engine.sort_criteria["submittedDate"]
- == arxiv.SortCriterion.SubmittedDate
+ == ArxivSortCriterion.SUBMITTED_DATE
)
class TestGetSearchResults:
"""Tests for _get_search_results method."""
- def test_get_search_results_creates_client(self):
- """Get search results creates arxiv client."""
+ def test_get_search_results_uses_fetch_boundary(self):
from local_deep_research.web_search_engines.engines.search_engine_arxiv import (
ArXivSearchEngine,
)
@@ -195,16 +194,14 @@ class TestGetSearchResults:
"local_deep_research.advanced_search_system.filters.journal_reputation_filter.JournalReputationFilter.create_default",
return_value=None,
):
- with patch("arxiv.Client") as mock_client_class:
- with patch("arxiv.Search"):
- mock_client = Mock()
- mock_client.results.return_value = iter([])
- mock_client_class.return_value = mock_client
-
- engine = ArXivSearchEngine()
- engine._get_search_results("test query")
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_arxiv.fetch_arxiv_results",
+ return_value=[],
+ ) as fetch:
+ engine = ArXivSearchEngine()
+ engine._get_search_results("test query")
- mock_client_class.assert_called_once()
+ fetch.assert_called_once()
class TestGetPreviews:
@@ -562,17 +559,15 @@ class TestGetPaperDetails:
"local_deep_research.advanced_search_system.filters.journal_reputation_filter.JournalReputationFilter.create_default",
return_value=None,
):
- with patch("arxiv.Client") as mock_client_class:
- with patch("arxiv.Search"):
- mock_client = Mock()
- mock_client.results.return_value = iter([mock_paper])
- mock_client_class.return_value = mock_client
-
- engine = ArXivSearchEngine()
- result = engine.get_paper_details("2101.12345")
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_arxiv.fetch_arxiv_results",
+ return_value=[mock_paper],
+ ):
+ engine = ArXivSearchEngine()
+ result = engine.get_paper_details("2101.12345")
- assert result["title"] == "Test Paper"
- assert result["link"] == "https://arxiv.org/abs/2101.12345"
+ assert result["title"] == "Test Paper"
+ assert result["link"] == "https://arxiv.org/abs/2101.12345"
def test_get_paper_details_not_found(self):
"""Get paper details returns empty for non-existent paper."""
@@ -584,16 +579,14 @@ class TestGetPaperDetails:
"local_deep_research.advanced_search_system.filters.journal_reputation_filter.JournalReputationFilter.create_default",
return_value=None,
):
- with patch("arxiv.Client") as mock_client_class:
- with patch("arxiv.Search"):
- mock_client = Mock()
- mock_client.results.return_value = iter([])
- mock_client_class.return_value = mock_client
-
- engine = ArXivSearchEngine()
- result = engine.get_paper_details("invalid-id")
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_arxiv.fetch_arxiv_results",
+ return_value=[],
+ ):
+ engine = ArXivSearchEngine()
+ result = engine.get_paper_details("invalid-id")
- assert result == {}
+ assert result == {}
def test_get_paper_details_handles_error(self):
"""Get paper details handles errors gracefully."""
@@ -605,7 +598,10 @@ class TestGetPaperDetails:
"local_deep_research.advanced_search_system.filters.journal_reputation_filter.JournalReputationFilter.create_default",
return_value=None,
):
- with patch("arxiv.Client", side_effect=Exception("API error")):
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_arxiv.fetch_arxiv_results",
+ side_effect=Exception("API error"),
+ ):
engine = ArXivSearchEngine()
result = engine.get_paper_details("2101.12345")
diff --git a/tests/web_search_engines/test_adapter_failure_contracts.py b/tests/web_search_engines/test_adapter_failure_contracts.py
index cfc5459bb9..c1e2c4afdd 100644
--- a/tests/web_search_engines/test_adapter_failure_contracts.py
+++ b/tests/web_search_engines/test_adapter_failure_contracts.py
@@ -233,18 +233,21 @@ def build_pubmed(inert_tracker):
def fake_arxiv_client(papers=None, error=None):
- """Return a drop-in for ``arxiv.Client`` that never touches the net."""
+ """Return a drop-in for ``fetch_arxiv_results`` that never touches the
+ net.
- class _Client:
- def __init__(self, *args, **kwargs):
- pass
+ ``ArXivSearchEngine`` is routed through the typed
+ ``utilities.arxiv_api.fetch_arxiv_results`` boundary rather than the
+ vendored ``arxiv`` SDK directly, so the seam to stub is the module-level
+ ``fetch_arxiv_results`` name imported into ``search_engine_arxiv``.
+ """
- def results(self, search):
- if error is not None:
- raise error
- return iter(papers or [])
+ def _fetch(request):
+ if error is not None:
+ raise error
+ return list(papers or [])
- return _Client
+ return _fetch
def fake_arxiv_paper(entry_id="http://arxiv.org/abs/2401.00001"):
@@ -565,7 +568,7 @@ class TestArxivDegradation:
def test_success_control(self, inert_tracker):
engine = build_arxiv(inert_tracker)
client = fake_arxiv_client(papers=[fake_arxiv_paper()])
- with patch.object(arxiv_engine.arxiv, "Client", client):
+ with patch.object(arxiv_engine, "fetch_arxiv_results", client):
previews = engine._get_previews(PROBE_QUERY)
assert len(previews) == 1
assert previews[0]["title"] == "A Stubbed Paper"
@@ -585,7 +588,7 @@ class TestArxivDegradation:
):
engine = build_arxiv(inert_tracker)
client = fake_arxiv_client(error=failure)
- with patch.object(arxiv_engine.arxiv, "Client", client):
+ with patch.object(arxiv_engine, "fetch_arxiv_results", client):
assert engine._get_previews(PROBE_QUERY) == []
@pytest.mark.parametrize(
@@ -599,7 +602,7 @@ class TestArxivDegradation:
class retries it instead of dropping the engine's results."""
engine = build_arxiv(inert_tracker)
client = fake_arxiv_client(error=Exception(message))
- with patch.object(arxiv_engine.arxiv, "Client", client):
+ with patch.object(arxiv_engine, "fetch_arxiv_results", client):
with pytest.raises(RateLimitError):
engine._get_previews(PROBE_QUERY)
@@ -732,7 +735,7 @@ def _wikipedia_previews(inert_tracker):
def _arxiv_previews(inert_tracker):
engine = build_arxiv(inert_tracker)
client = fake_arxiv_client(papers=[fake_arxiv_paper()])
- with patch.object(arxiv_engine.arxiv, "Client", client):
+ with patch.object(arxiv_engine, "fetch_arxiv_results", client):
return engine._get_previews(PROBE_QUERY)
@@ -1228,7 +1231,7 @@ def _run_pubmed_for_logs(inert_tracker):
def _run_arxiv_for_logs(inert_tracker):
engine = build_arxiv(inert_tracker)
with patch.object(
- arxiv_engine.arxiv, "Client", fake_arxiv_client(papers=[])
+ arxiv_engine, "fetch_arxiv_results", fake_arxiv_client(papers=[])
):
engine._get_previews(PROBE_QUERY)
diff --git a/tests/web_search_engines/test_engine_success_path.py b/tests/web_search_engines/test_engine_success_path.py
index 4cc6afbda9..f52d625547 100644
--- a/tests/web_search_engines/test_engine_success_path.py
+++ b/tests/web_search_engines/test_engine_success_path.py
@@ -942,14 +942,12 @@ def _drive_arxiv(tracker):
tracker,
)
- class _Client:
- def __init__(self, *a, **kw):
- pass
-
- def results(self, search):
- return iter([ARXIV_PAPER])
-
- with patch.object(arxiv_engine.arxiv, "Client", _Client):
+ # ArXivSearchEngine is routed through the typed
+ # ``utilities.arxiv_api.fetch_arxiv_results`` boundary rather than the
+ # vendored ``arxiv`` SDK directly, so that is the seam to stub.
+ with patch.object(
+ arxiv_engine, "fetch_arxiv_results", return_value=[ARXIV_PAPER]
+ ):
return engine._get_previews(QUERY)