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.

fix(deps): enforce patched v2 package and toolchain versions (#7131)

LearningCircuitc708c6146dd1
diff --git a/changelog.d/+arxiv-requests-compatibility.security.md b/changelog.d/+arxiv-requests-compatibility.security.md
new file mode 100644
index 0000000000..7633b3ac34
--- /dev/null
+++ b/changelog.d/+arxiv-requests-compatibility.security.md
@@ -0,0 +1 @@
+Require a patched Requests version for pip installations and update the ArXiv client to a compatible release, removing the conflicting development-only dependency override.
diff --git a/changelog.d/+datasets-security.security.md b/changelog.d/+datasets-security.security.md
new file mode 100644
index 0000000000..d5e6481c68
--- /dev/null
+++ b/changelog.d/+datasets-security.security.md
@@ -0,0 +1 @@
+Require datasets 5.0.1 or newer, the release carrying the upstream fix for CVE-2026-66007 (folder-metadata path traversal).
diff --git a/changelog.d/+fsspec-security.security.md b/changelog.d/+fsspec-security.security.md
new file mode 100644
index 0000000000..ee67470e8d
--- /dev/null
+++ b/changelog.d/+fsspec-security.security.md
@@ -0,0 +1 @@
+Require fsspec 2026.6.0 or newer, alongside the compatible datasets upgrade, to address CVE-2026-104851 in reference-filesystem template handling.
diff --git a/pdm.lock b/pdm.lock
index ad65cae44b..e03a2a0311 100644
--- a/pdm.lock
+++ b/pdm.lock
@@ -5,7 +5,7 @@
groups = ["default", "dev", "mcp"]
strategy = ["inherit_metadata"]
lock_version = "4.5.0"
-content_hash = "sha256:2ddf256726a5df80ca27c2fcaf9cd73cba92bd21a5b73990896fede0fecb176d"
+content_hash = "sha256:4fead3891d3376d1334013c74a30c63d9f084aa68bdba90cd7e80765a5cb768f"
[[metadata.targets]]
requires_python = ">=3.12,<3.15"
@@ -309,18 +309,18 @@ files = [
[[package]]
name = "arxiv"
-version = "2.4.1"
-requires_python = ">=3.9"
+version = "4.0.1"
+requires_python = ">=3.10"
summary = "Python wrapper for the arXiv API"
groups = ["default"]
dependencies = [
- "feedparser~=6.0.10",
- "requests~=2.32.0",
+ "lxml<7.0,>=6.1.0",
+ "requests<2.35,>=2.32",
"typing-extensions>=4.0.0; python_version < \"3.11\"",
]
files = [
- {file = "arxiv-2.4.1-py3-none-any.whl", hash = "sha256:060d678410ffc224ada01089f877b7676f250e37f96c140bad6c287afadb15d8"},
- {file = "arxiv-2.4.1.tar.gz", hash = "sha256:691606c1069bcca8316fcb082f5d15e65f1f24a021b0b87f01b9fa56347f63c8"},
+ {file = "arxiv-4.0.1-py3-none-any.whl", hash = "sha256:72a79d22a83fec14c3a23966791692e2400399c218ad4e5416ce84af817a9cc9"},
+ {file = "arxiv-4.0.1.tar.gz", hash = "sha256:304e91a9f869fa4cc362a0a6f38ecb956eec11b83619465172ab24b9453e3d51"},
]
[[package]]
@@ -1167,14 +1167,14 @@ files = [
[[package]]
name = "datasets"
-version = "4.8.5"
+version = "5.0.1"
requires_python = ">=3.10.0"
summary = "HuggingFace community-driven open-source library of datasets"
groups = ["default"]
dependencies = [
"dill<0.4.2,>=0.3.0",
"filelock",
- "fsspec[http]<=2026.2.0,>=2023.1.0",
+ "fsspec[http]<=2026.6.0,>=2023.1.0",
"httpx<1.0.0",
"huggingface-hub<2.0,>=0.25.0",
"multiprocess<0.70.20",
@@ -1188,8 +1188,8 @@ dependencies = [
"xxhash",
]
files = [
- {file = "datasets-4.8.5-py3-none-any.whl", hash = "sha256:5079900781719c0e063a8efdd2cd95a31ad0c63209178669cd23cf1b926149ff"},
- {file = "datasets-4.8.5.tar.gz", hash = "sha256:0f0c1c3d56ffff2c93b2f4c63c95bac94f3d7e8621aea2a2a576275233bba772"},
+ {file = "datasets-5.0.1-py3-none-any.whl", hash = "sha256:9fbf73688f8c18f7529b4fe592abd04015f81d1e58001e4bac73ffb2b39d7cc4"},
+ {file = "datasets-5.0.1.tar.gz", hash = "sha256:ce22bb851efd7494f08aad33b940803784434f6e77763d00679a0dc45fcf686a"},
]
[[package]]
@@ -1738,29 +1738,29 @@ files = [
[[package]]
name = "fsspec"
-version = "2026.2.0"
+version = "2026.6.0"
requires_python = ">=3.10"
summary = "File-system specification"
groups = ["default"]
files = [
- {file = "fsspec-2026.2.0-py3-none-any.whl", hash = "sha256:98de475b5cb3bd66bedd5c4679e87b4fdfe1a3bf4d707b151b3c07e58c9a2437"},
- {file = "fsspec-2026.2.0.tar.gz", hash = "sha256:6544e34b16869f5aacd5b90bdf1a71acb37792ea3ddf6125ee69a22a53fb8bff"},
+ {file = "fsspec-2026.6.0-py3-none-any.whl", hash = "sha256:02e0b71817df9b2169dc30a16832045764def1191b43dcff5bb85bdee212d2a1"},
+ {file = "fsspec-2026.6.0.tar.gz", hash = "sha256:f5bac145310fe30e16e1471bd6840b2d990d609e872251d7e674241822abf01a"},
]
[[package]]
name = "fsspec"
-version = "2026.2.0"
+version = "2026.6.0"
extras = ["http"]
requires_python = ">=3.10"
summary = "File-system specification"
groups = ["default"]
dependencies = [
"aiohttp!=4.0.0a0,!=4.0.0a1",
- "fsspec==2026.2.0",
+ "fsspec==2026.6.0",
]
files = [
- {file = "fsspec-2026.2.0-py3-none-any.whl", hash = "sha256:98de475b5cb3bd66bedd5c4679e87b4fdfe1a3bf4d707b151b3c07e58c9a2437"},
- {file = "fsspec-2026.2.0.tar.gz", hash = "sha256:6544e34b16869f5aacd5b90bdf1a71acb37792ea3ddf6125ee69a22a53fb8bff"},
+ {file = "fsspec-2026.6.0-py3-none-any.whl", hash = "sha256:02e0b71817df9b2169dc30a16832045764def1191b43dcff5bb85bdee212d2a1"},
+ {file = "fsspec-2026.6.0.tar.gz", hash = "sha256:f5bac145310fe30e16e1471bd6840b2d990d609e872251d7e674241822abf01a"},
]
[[package]]
diff --git a/pyproject.toml b/pyproject.toml
index a7df50b63c..06e9cfd3a0 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -52,8 +52,8 @@ dependencies = [
"sqlalchemy>=2.0,<2.1", # #6876: fresh 2.1.1 installs reported a research-time segfault; stay on the tested 2.0 series pending upstream resolution
"sqlalchemy-utc~=0.14",
"wikipedia~=1.4",
- "arxiv~=2.4",
- "pypdf>=6.19,<7", # GHSA-fp3h-c4fm-7vvf, GHSA-g9cg-prrw-2r8q, GHSA-jw7q-gvrg-4vj3 (fixed 6.18.1), GHSA-php9-fj8v-98fj, GHSA-v247-6f48-mgcj, GHSA-w23x-9jrw-r45c (fixed 6.19.0), CVE-2026-33123, CVE-2026-31826, GHSA-9m86-7pmv-2852, CVE-2026-27888, CVE-2026-27024, CVE-2026-0777, CVE-2025-55197, GHSA-3crg-w4f6-42mx, GHSA-248m-82v9-q6g6, GHSA-cj93-chg6-vgv8, GHSA-jm82-fx9c-mx94, CVE-2026-71852, CVE-2026-71870 fixes
+ "arxiv>=4.0.1,<5",
+ "pypdf~=6.19", # GHSA-fp3h-c4fm-7vvf, GHSA-g9cg-prrw-2r8q, GHSA-jw7q-gvrg-4vj3 (fixed 6.18.1), GHSA-php9-fj8v-98fj, GHSA-v247-6f48-mgcj, GHSA-w23x-9jrw-r45c (fixed 6.19.0), CVE-2026-33123, CVE-2026-31826, GHSA-9m86-7pmv-2852, CVE-2026-27888, CVE-2026-27024, CVE-2026-0777, CVE-2025-55197, GHSA-3crg-w4f6-42mx, GHSA-248m-82v9-q6g6, GHSA-cj93-chg6-vgv8, GHSA-jm82-fx9c-mx94, CVE-2026-71852, CVE-2026-71870, CVE-2026-102999 fixes
"sentence-transformers~=5.2",
"faiss-cpu~=1.13.0", # 1.14.x wheels SIGILL on CPUs without AVX2 (#4480); unpin criteria tracked in #4499
"pydantic~=2.12",
@@ -61,8 +61,8 @@ dependencies = [
"toml~=0.10",
"platformdirs~=4.5",
"dynaconf~=3.2",
- "requests>=2.32", # CVE-2026-25645 patched in 2.33; PDM override ensures 2.33+ in dev
- "urllib3>=2.8,<3", # CVE-2026-44431 CVE-2026-44432 fix; 2.8.0 fixes GHSA-8988-9cw3-xx77, GHSA-gh4c-6fx4-qh6g, GHSA-vxq7-64xx-v4gw
+ "requests>=2.33,<3", # CVE-2026-25645: enforce the patched floor in published packages too
+ "urllib3~=2.8", # CVE-2026-44431 CVE-2026-44432 fix; 2.8.0 fixes GHSA-8988-9cw3-xx77, GHSA-gh4c-6fx4-qh6g, GHSA-vxq7-64xx-v4gw
"tiktoken~=0.12",
"xmltodict~=1.0",
"lxml>=5.3", # >=5.3 to satisfy crawl4ai; PDM override ensures >=6.0 in dev
@@ -114,7 +114,8 @@ dependencies = [
"oauthlib>=4,<5", # Apprise -> requests-oauthlib; 4.0.0 fixes GHSA-hj66-6f7g-4r5v and GHSA-xpv3-w29h-x7cv
"markdown~=3.10",
"pypandoc-binary~=1.16",
- "datasets~=4.5",
+ "datasets>=5.0.1,<6", # CVE-2026-66007: release carrying the upstream fix
+ "fsspec>=2026.6.0", # CVE-2026-104851: sandbox reference-filesystem templates
"pyarrow~=23.0",
"langchain-experimental~=0.4",
# Pinned to the 0.136.x line: fastapi 0.138 breaks app.include_router
@@ -254,8 +255,6 @@ name = "torch"
include_packages = ["torch", "torch*"]
[tool.pdm.resolution.overrides]
-# arxiv pins requests~=2.32.0, but 2.32.x has CVE-2026-25645
-requests = ">=2.33"
# newspaper4k and crawl4ai pin lxml<6.0 but work fine with 6.x
# (tested). Override to get Python 3.14 pre-built wheels.
lxml = ">=6.0"
diff --git a/src/local_deep_research/utilities/arxiv_api.py b/src/local_deep_research/utilities/arxiv_api.py
index 91206123f1..1a325c12ed 100644
--- a/src/local_deep_research/utilities/arxiv_api.py
+++ b/src/local_deep_research/utilities/arxiv_api.py
@@ -96,6 +96,9 @@ class ArxivPaper(Protocol):
@property
def authors(self) -> Sequence[ArxivAuthor]: ...
+ @property
+ def pdf_url(self) -> str | None: ...
+
_SORT_CRITERIA: Final = {
ArxivSortCriterion.RELEVANCE: arxiv.SortCriterion.Relevance,
@@ -246,8 +249,41 @@ def _install_gated_session(client: arxiv.Client) -> _GatedArxivSession:
return adapted_session
+def _strip_optional(text: str | None) -> str | None:
+ return None if text is None else text.strip()
+
+
+def _strip_feed_text(paper: arxiv.Result) -> arxiv.Result:
+ """Strip surrounding whitespace from the text fields LDR reads.
+
+ arxiv 2.x parsed the Atom feed with feedparser, which strips the
+ leading and trailing whitespace of each of these fields. arxiv 4.x
+ parses it with its own lxml parser and keeps the raw element text,
+ and the arXiv API returns some of it with surrounding whitespace
+ (some abstracts start with two spaces). The id, title, abstract,
+ comment, journal reference, DOI and author names are stripped in
+ place with ``str.strip()``, as feedparser stripped them, so snippets,
+ content and author lists carry none of the whitespace 2.x removed.
+ The SDK already collapses each whitespace run in the title to one
+ space, which leaves at most one space at each end to strip.
+ """
+ paper.entry_id = paper.entry_id.strip()
+ paper.title = paper.title.strip()
+ paper.summary = paper.summary.strip()
+ paper.comment = _strip_optional(paper.comment)
+ paper.journal_ref = _strip_optional(paper.journal_ref)
+ paper.doi = _strip_optional(paper.doi)
+ for author in paper.authors:
+ author.name = author.name.strip()
+ return paper
+
+
def fetch_arxiv_results(request: ArxivRequest) -> list[ArxivPaper]:
- """Fetch and materialize one typed arXiv request under shared policy."""
+ """Fetch and materialize one typed arXiv request under shared policy.
+
+ The text fields LDR reads from each result are stripped of
+ surrounding whitespace (``_strip_feed_text``).
+ """
match request:
case ArxivQueryRequest():
search = arxiv.Search(
@@ -257,10 +293,14 @@ def fetch_arxiv_results(request: ArxivRequest) -> list[ArxivPaper]:
sort_order=_SORT_ORDERS[request.sort_order],
)
with _policy_arxiv_client(page_size=request.max_results) as client:
- return list[ArxivPaper](client.results(search))
+ return list[ArxivPaper](
+ map(_strip_feed_text, 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))
+ return list[ArxivPaper](
+ map(_strip_feed_text, client.results(search))
+ )
case unreachable:
assert_never(unreachable)
diff --git a/tests/ci/test_dependency_floors.py b/tests/ci/test_dependency_floors.py
new file mode 100644
index 0000000000..78463898db
--- /dev/null
+++ b/tests/ci/test_dependency_floors.py
@@ -0,0 +1,188 @@
+"""Revert-catching tests for the patched-v2 dependency floors.
+
+Why these exist: the security floors in ``pyproject.toml`` ship in the
+published wheel metadata, but nothing downstream re-asserts them — pip only
+checks resolvability (2.32.x still resolves), and OSV scans ``pdm.lock``,
+which already held patched versions before the floors existed via dev
+overrides. Lowering or deleting a floor is therefore a silently revertible
+change. Each test fails loudly when its floor moves, and names the
+advisories the floor remediates so a future re-baseline must justify itself
+here rather than in a diff nobody reads.
+"""
+
+# allow: no-sut-import — asserts on repository metadata (pyproject.toml),
+# not on the package under test.
+
+from __future__ import annotations
+
+import tomllib
+from pathlib import Path
+
+import pytest
+from packaging.requirements import Requirement
+from packaging.version import Version
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+PYPROJECT = REPO_ROOT / "pyproject.toml"
+
+
+def _requirements(section: str, key: str) -> dict[str, Requirement]:
+ with PYPROJECT.open("rb") as fh:
+ data = tomllib.load(fh)
+ raw = data[section][key]
+ parsed = {Requirement(r).name: Requirement(r) for r in raw}
+ assert parsed, f"{section}.{key} in {PYPROJECT} is empty — floors vanished"
+ return parsed
+
+
+def _project_dependencies() -> dict[str, Requirement]:
+ return _requirements("project", "dependencies")
+
+
+def _dev_group() -> dict[str, Requirement]:
+ return _requirements("dependency-groups", "dev")
+
+
+def _assert_floor(req: Requirement, *, floor_excluded: str, floor: str) -> None:
+ """Require an unconditional floor at ``floor``.
+
+ The specifier must admit ``floor`` and no version below it, which
+ includes ``floor_excluded`` and every prerelease of ``floor``.
+ """
+ # An environment marker makes the floor conditional: pip skips this
+ # requirement where the marker is false (for example on Python 3.13+
+ # under ``python_version < '3.13'``), while every check below would
+ # still pass.
+ assert req.marker is None, (
+ f"{req.name} floor applies only where {req.marker} holds: a "
+ f"security floor must be unconditional (requirement: {req})"
+ )
+ spec = req.specifier
+ # The highest lower bound must reach the floor. A probe version cannot
+ # catch every partial downgrade: datasets>=5.0.1rc1 rejects 5.0.1.dev0
+ # yet admits 5.0.1rc1, which is below the patched 5.0.1.
+ lower_bounds = [
+ Version(clause.version)
+ for clause in spec
+ if clause.operator in {">=", ">", "~=", "=="}
+ and not clause.version.endswith(".*")
+ ]
+ assert lower_bounds and max(lower_bounds) >= Version(floor), (
+ f"{req.name} admits versions below {floor}: the patched floor was "
+ f"lowered (current specifier: {spec})"
+ )
+ assert not spec.contains(floor_excluded, prereleases=True), (
+ f"{req.name} accepts {floor_excluded}: the patched floor was lowered "
+ f"(current specifier: {spec})"
+ )
+ # A historical bad version alone misses a partial downgrade, such as
+ # datasets>=5.0.0 when the patched floor is 5.0.1. Explicitly considering
+ # prereleases tests the lower boundary even if no adjacent release exists.
+ assert not spec.contains(f"{floor}.dev0", prereleases=True), (
+ f"{req.name} accepts a version below {floor}: the patched floor was "
+ f"lowered (current specifier: {spec})"
+ )
+ assert spec.contains(floor, prereleases=True), (
+ f"{req.name} rejects {floor}: the patched floor moved above it "
+ f"(current specifier: {spec})"
+ )
+
+
+def _assert_window(
+ req: Requirement, *, floor_excluded: str, floor: str, cap: str
+) -> None:
+ """Accept the patched floor while preserving the compatibility cap."""
+ _assert_floor(req, floor_excluded=floor_excluded, floor=floor)
+ spec = req.specifier
+ assert not spec.contains(cap, prereleases=True), (
+ f"{req.name} accepts {cap}: the compat cap was dropped "
+ f"(current specifier: {spec})"
+ )
+
+
+def test_requests_floor_is_patched_in_published_metadata():
+ """requests>=2.33,<3 — CVE-2026-25645 (2.32.x ships the vulnerable path).
+
+ Published metadata must enforce the floor; the pre-floor policy relied on
+ a dev-only PDM override, so release wheels could resolve 2.32.x.
+ """
+ req = _project_dependencies()["requests"]
+ _assert_window(req, floor_excluded="2.32.5", floor="2.33.0", cap="3.0.0")
+
+
+def test_arxiv_floor_requires_the_4x_api_port():
+ """arxiv>=4.0.1,<5 — the 2.4 line caps requests~=2.32.0 (CVE-2026-25645
+ exposure) and uses the removed feedparser/download_pdf stack this PR
+ ports away from.
+ """
+ req = _project_dependencies()["arxiv"]
+ _assert_window(req, floor_excluded="2.4.1", floor="4.0.1", cap="5.0.0")
+
+
+def test_pypdf_floor_covers_2026_advisory_batch():
+ """pypdf~=6.19 — GHSA-jw7q-gvrg-4vj3 et al. fixed in 6.18.1/6.19.0
+ (incl. CVE-2026-102999); 6.18.x must not resolve.
+ """
+ req = _project_dependencies()["pypdf"]
+ _assert_window(req, floor_excluded="6.18.1", floor="6.19.0", cap="7.0.0")
+
+
+def test_urllib3_floor_covers_2026_advisory_batch():
+ """urllib3~=2.8 — CVE-2026-44431/CVE-2026-44432; 2.8.0 also fixes
+ GHSA-8988-9cw3-xx77, GHSA-gh4c-6fx4-qh6g, GHSA-vxq7-64xx-v4gw.
+ """
+ req = _project_dependencies()["urllib3"]
+ _assert_window(req, floor_excluded="2.7.0", floor="2.8.0", cap="3.0.0")
+
+
+def test_fsspec_floor_covers_reference_template_cve():
+ """fsspec>=2026.6.0 — CVE-2026-104851 (reference-filesystem template
+ handling); 2026.2.0 must not resolve.
+ """
+ req = _project_dependencies()["fsspec"]
+ _assert_floor(req, floor_excluded="2026.2.0", floor="2026.6.0")
+
+
+def test_datasets_floor_caps_folder_metadata_traversal():
+ """datasets>=5.0.1,<6 — CVE-2026-66007 folder-metadata path containment."""
+ req = _project_dependencies()["datasets"]
+ _assert_window(req, floor_excluded="4.8.5", floor="5.0.1", cap="6.0.0")
+
+
+def test_dev_virtualenv_floor_covers_activation_advisories():
+ """dev virtualenv>=21.7.13,<22 — GHSA-9h9j-4vrj-gf7g (21.7.11),
+ GHSA-94p9-xgh2-xp45 / GHSA-x78j-v8h9-3j2q (21.7.12),
+ GHSA-p58f-9548-mpm2 (21.7.13).
+ """
+ req = _dev_group()["virtualenv"]
+ _assert_window(req, floor_excluded="21.7.12", floor="21.7.13", cap="22.0.0")
+
+
+ "name", ["requests", "arxiv", "pypdf", "urllib3", "fsspec", "datasets"]
+)
+def test_floored_packages_are_declared_dependencies(name: str) -> None:
+ """Keep the patched packages in the published dependency set."""
+ assert name in _project_dependencies(), (
+ f"{name} no longer declared in [project.dependencies] — floor removed"
+ )
+
+
+ "line",
+ [
+ "datasets>=5.0.1,<6; python_version < '3.13'",
+ "datasets>=5.0.1rc1,<6",
+ ],
+ ids=["environment-marker", "prerelease-floor"],
+)
+def test_floor_guard_rejects_weakened_floors(line: str) -> None:
+ """The guard itself rejects a conditional floor and a floor lowered to
+ a prerelease of the patched release."""
+ with pytest.raises(AssertionError):
+ _assert_window(
+ Requirement(line),
+ floor_excluded="4.8.5",
+ floor="5.0.1",
+ cap="6.0.0",
+ )
diff --git a/tests/download_stuff_for_local.py b/tests/download_stuff_for_local.py
index dcca4ee77c..08b13052db 100644
--- a/tests/download_stuff_for_local.py
+++ b/tests/download_stuff_for_local.py
@@ -1,41 +1,74 @@
-import os
import sys
from pathlib import Path
-from datasets import load_dataset
-
PROJECT_ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(PROJECT_ROOT / "src"))
+from local_deep_research.research_library.downloaders.arxiv import ( # noqa: E402
+ ArxivDownloader,
+)
from local_deep_research.utilities.arxiv_api import ( # noqa: E402
ArxivQueryRequest,
fetch_arxiv_results,
)
-max_results = 50
-papers = fetch_arxiv_results(
- ArxivQueryRequest(query="machine learning", max_results=max_results)
-)
+MAX_RESULTS = 50
+PAPER_DIR = Path("./../local_search_files/research_papers")
+WIKI_DIR = Path("./../local_search_files/wiki_sample")
+
+
+def download_papers(papers, paper_dir, downloader) -> list[str]:
+ """Download each paper's PDF through the application transport.
+
+ ``ArxivDownloader.download`` returns ``None`` instead of raising
+ whenever no PDF arrives, for example when arXiv has none to serve, the
+ response is not a PDF, or the request failed (an HTTP error, rate
+ limiting, a timeout or connection error, or another error while
+ requesting or reading the response; the downloader logs each). Those
+ papers are returned as failures. This function catches nothing itself,
+ so an error the downloader does raise, or a failure writing a file,
+ propagates.
+ """
+ paper_dir.mkdir(parents=True, exist_ok=True)
+ failures: list[str] = []
+ for i, paper in enumerate(papers):
+ pdf = downloader.download(paper.entry_id)
+ if not pdf:
+ failures.append(paper.title)
+ print(f"No PDF downloaded for {paper.title} ({paper.entry_id})")
+ continue
+ (paper_dir / f"paper_{i}.pdf").write_bytes(pdf)
+ print(f"Downloaded {i + 1} / {len(papers)}: {paper.title}")
+ return failures
+
+
+def main() -> int:
+ from datasets import load_dataset
+
+ papers = fetch_arxiv_results(
+ ArxivQueryRequest(query="machine learning", max_results=MAX_RESULTS)
+ )
+ with ArxivDownloader() as downloader:
+ failures = download_papers(papers, PAPER_DIR, downloader)
+
+ wiki = load_dataset(
+ "wikipedia",
+ "20220301.en",
+ split=f"train[:{MAX_RESULTS}]",
+ trust_remote_code=True,
+ )
+
+ WIKI_DIR.mkdir(parents=True, exist_ok=True)
+ for i, article in enumerate(wiki):
+ (WIKI_DIR / f"article_{i}.txt").write_text(
+ article["title"] + "\n\n" + article["text"]
+ )
+
+ if failures:
+ print(f"{len(failures)} paper(s) could not be downloaded")
+ return 1
+ return 0
-# Download papers
-os.makedirs("./../local_search_files/research_papers", exist_ok=True)
-for i, result in enumerate(papers):
- try:
- filename = f"./../local_search_files/research_papers/paper_{i}.pdf"
- result.download_pdf(filename=filename)
- print(f"Downloaded {i + 1} / {max_results}: {result.title}")
- except Exception as e:
- print(f"Error downloading {result.title}: {e}")
-
-
-wiki = load_dataset(
- "wikipedia",
- "20220301.en",
- split=f"train[:{max_results}]",
- trust_remote_code=True,
-)
-os.makedirs("./../local_search_files/wiki_sample", exist_ok=True)
-for i, article in enumerate(wiki):
- with open(f"./../local_search_files/wiki_sample/article_{i}.txt", "w") as f:
- f.write(article["title"] + "\n\n" + article["text"])
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tests/utilities/test_arxiv_fetch_api.py b/tests/utilities/test_arxiv_fetch_api.py
index 1e24308584..a8fed41729 100644
--- a/tests/utilities/test_arxiv_fetch_api.py
+++ b/tests/utilities/test_arxiv_fetch_api.py
@@ -21,6 +21,12 @@ def _stub_policy_client(
return policy, context, client
+def _paper(
+ entry_id: str = "https://arxiv.org/abs/2101.12345v1",
+) -> arxiv.Result:
+ return arxiv.Result(entry_id=entry_id)
+
+
def test_request_types_expose_stable_defaults_and_values() -> None:
request = arxiv_api_module.ArxivQueryRequest(query="q", max_results=10)
@@ -42,7 +48,7 @@ def test_query_request_maps_search_enums_and_materializes_inside_context(
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")]
+ papers = [_paper()]
def results(_search: Mock):
assert context.__exit__.call_count == 0
@@ -77,7 +83,7 @@ def test_id_request_uses_id_search_and_default_client_page_size(
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")
+ paper = _paper()
client.results.return_value = iter([paper])
fetched = arxiv_api_module.fetch_arxiv_results(
@@ -89,6 +95,60 @@ def test_id_request_uses_id_search_and_default_client_page_size(
policy.assert_called_once_with()
+ "fetch_request",
+ [
+ arxiv_api_module.ArxivQueryRequest(query="graph models", max_results=2),
+ arxiv_api_module.ArxivIdRequest(arxiv_id="2101.12345v1"),
+ ],
+ ids=["query", "identifier"],
+)
+def test_result_text_is_stripped_as_feedparser_stripped_it(
+ mocker: MockerFixture,
+ fetch_request: arxiv_api_module.ArxivRequest,
+) -> None:
+ # arxiv 4.x keeps the surrounding whitespace feedparser stripped in
+ # 2.x. str.strip() is what feedparser used, so Unicode whitespace
+ # (U+00A0, U+3000) goes too; inner whitespace and absent fields stay.
+ _, _, client = _stub_policy_client(mocker)
+ mocker.patch.object(arxiv, "Search", return_value=Mock())
+ padded = arxiv.Result(
+ entry_id="\n https://arxiv.org/abs/2101.12345v1\n",
+ title=" Graph models ",
+ authors=[
+ arxiv.Result.Author("\n Example Author\n"),
+ arxiv.Result.Author("Second Author"),
+ ],
+ summary=" Research abstract.\n Second line.\n",
+ comment=" Two figures\n",
+ journal_ref=" Example Journal ",
+ doi="\t10.1234/example ",
+ )
+ bare = arxiv.Result(
+ entry_id="https://arxiv.org/abs/2101.54321v1",
+ comment=None,
+ journal_ref=None,
+ doi=None,
+ )
+ client.results.return_value = iter([padded, bare])
+
+ fetched = arxiv_api_module.fetch_arxiv_results(fetch_request)
+
+ assert fetched[0] is padded
+ assert fetched[1] is bare
+ assert padded.entry_id == "https://arxiv.org/abs/2101.12345v1"
+ assert padded.title == "Graph models"
+ assert padded.summary == "Research abstract.\n Second line."
+ assert padded.comment == "Two figures"
+ assert padded.journal_ref == "Example Journal"
+ assert padded.doi == "10.1234/example"
+ assert [author.name for author in padded.authors] == [
+ "Example Author",
+ "Second Author",
+ ]
+ assert (bare.comment, bare.journal_ref, bare.doi) == (None, None, None)
+
+
def test_iteration_error_propagates_after_context_cleanup(
mocker: MockerFixture,
) -> None:
diff --git a/tests/utilities/test_arxiv_sdk_compatibility.py b/tests/utilities/test_arxiv_sdk_compatibility.py
new file mode 100644
index 0000000000..e3ac4d33ac
--- /dev/null
+++ b/tests/utilities/test_arxiv_sdk_compatibility.py
@@ -0,0 +1,182 @@
+"""Exercise the installed SDK and Atom parser through LDR's transport adapter."""
+
+from datetime import UTC, datetime
+from itertools import count
+from pathlib import Path
+from urllib.parse import parse_qs, urlsplit
+
+import arxiv
+import pytest
+import requests
+from pytest_mock import MockerFixture
+
+from local_deep_research.utilities import arxiv_api
+
+
+# The text fields carry surrounding whitespace, as the arXiv API sends for
+# some of them (some abstracts start with two spaces). arxiv 2.x's
+# feedparser stripped it and arxiv 4.x's lxml parser keeps it, so
+# fetch_arxiv_results strips it, as 2.x did.
+ENTRY = """<entry>
+ <id>
+ https://arxiv.org/abs/2101.12345v2
+ </id>
+ <updated>2021-02-15T12:00:00Z</updated>
+ <published>2021-01-15T12:00:00Z</published>
+ <title>
+ Graph\n models &amp; search
+ </title>
+ <summary> Research abstract.
+ </summary>
+ <author><name>
+ Example Author
+ </name></author>
+ <category term="cs.AI"/>
+ <category term="cs.IR"/>
+ <arxiv:primary_category term="cs.AI"/>
+ <arxiv:comment> Two figures
+ </arxiv:comment>
+ <arxiv:journal_ref> Example Journal </arxiv:journal_ref>
+ <arxiv:doi>
+ 10.1234/example
+ </arxiv:doi>
+ <link href="https://arxiv.org/abs/2101.12345v2" rel="alternate"/>
+ <link href="https://arxiv.org/pdf/2101.12345v2"
+ rel="related" title="pdf" type="application/pdf"/>
+</entry>"""
+
+
+def _feed(entry: str = ENTRY) -> bytes:
+ total = 1 if entry else 0
+ return f"""<feed xmlns="http://www.w3.org/2005/Atom"
+ xmlns:arxiv="http://arxiv.org/schemas/atom"
+ xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/">
+ <opensearch:totalResults>{total}</opensearch:totalResults>
+ <opensearch:startIndex>0</opensearch:startIndex>
+ <opensearch:itemsPerPage>{total}</opensearch:itemsPerPage>
+ {entry}
+ </feed>""".encode()
+
+
+def transport(mocker: MockerFixture):
+ # Only the wire response is replaced: Client, Search, Result, the Atom
+ # parser, and LDR's session/gate/cleanup all execute their real code.
+ response = requests.Response()
+ response.status_code = 200
+ response._content = _feed()
+ wire = mocker.patch.object(
+ arxiv_api.SafeSession, "request", autospec=True, return_value=response
+ )
+ close = mocker.spy(arxiv_api, "safe_close")
+ mocker.patch.object(arxiv_api, "_last_request_started_at", None)
+ mocker.patch.object(arxiv_api, "_monotonic", side_effect=count(step=4))
+ return response, wire, close
+
+
+ ("fetch_request", "expected_query"),
+ [
+ (
+ arxiv_api.ArxivQueryRequest(
+ query="graph models",
+ max_results=2,
+ sort_by=arxiv_api.ArxivSortCriterion.LAST_UPDATED_DATE,
+ sort_order=arxiv_api.ArxivSortOrder.ASCENDING,
+ ),
+ {
+ "search_query": ["graph models"],
+ "max_results": ["2"],
+ "sortBy": ["lastUpdatedDate"],
+ "sortOrder": ["ascending"],
+ },
+ ),
+ (
+ arxiv_api.ArxivIdRequest(arxiv_id="2101.12345v2"),
+ {"id_list": ["2101.12345v2"]},
+ ),
+ ],
+ ids=["query", "identifier"],
+)
+def test_real_sdk_returns_paper_metadata_through_policy_transport(
+ fetch_request, expected_query, transport
+):
+ _, wire, close = transport
+
+ papers = arxiv_api.fetch_arxiv_results(fetch_request)
+
+ assert len(papers) == 1
+ paper = papers[0]
+ assert isinstance(paper, arxiv.Result)
+ assert paper.entry_id == "https://arxiv.org/abs/2101.12345v2"
+ assert paper.title == "Graph models & search"
+ assert paper.summary == "Research abstract."
+ assert [author.name for author in paper.authors] == ["Example Author"]
+ assert paper.published == datetime(2021, 1, 15, 12, tzinfo=UTC)
+ assert paper.updated == datetime(2021, 2, 15, 12, tzinfo=UTC)
+ assert paper.categories == ["cs.AI", "cs.IR"]
+ assert paper.comment == "Two figures"
+ assert paper.journal_ref == "Example Journal"
+ assert paper.doi == "10.1234/example"
+ assert paper.pdf_url == "https://arxiv.org/pdf/2101.12345v2"
+
+ wire.assert_called_once()
+ session, method, url = wire.call_args.args
+ assert isinstance(session, arxiv_api.SafeSession)
+ assert method == "GET"
+ assert urlsplit(url).netloc == "export.arxiv.org"
+ query = parse_qs(urlsplit(url).query)
+ for key, value in expected_query.items():
+ assert query[key] == value
+ assert wire.call_args.kwargs["timeout"] == 10
+ assert wire.call_args.kwargs["allow_redirects"] is False
+ assert close.call_count == 2
+ assert close.call_args.args[0] is session
+
+
+def test_real_sdk_empty_feed_returns_no_papers(transport):
+ response, wire, close = transport
+ response._content = _feed("")
+
+ assert (
+ arxiv_api.fetch_arxiv_results(arxiv_api.ArxivIdRequest("missing")) == []
+ )
+
+ wire.assert_called_once()
+ assert close.call_count == 2
+
+
+def test_real_sdk_parser_does_not_expand_external_entities(
+ transport, tmp_path: Path
+):
+ response, _, _ = transport
+ sentinel = tmp_path / "external-entity.txt"
+ sentinel.write_text("arxiv-external-entity-sentinel")
+ declaration = (
+ f'<!DOCTYPE feed [<!ENTITY external SYSTEM "{sentinel.as_uri()}">]>'
+ ).encode()
+ response._content = declaration + _feed(
+ ENTRY.replace("Research abstract.", "&external;")
+ )
+
+ papers = arxiv_api.fetch_arxiv_results(
+ arxiv_api.ArxivIdRequest("2101.12345")
+ )
+
+ assert len(papers) == 1
+ assert "arxiv-external-entity-sentinel" not in papers[0].summary
+
+
+def test_real_sdk_rejects_redirect_and_closes_transport(transport):
+ response, wire, close = transport
+ response.status_code = 302
+ response.headers["Location"] = "https://example.com/redirect-target"
+
+ with pytest.raises(arxiv.HTTPError):
+ arxiv_api.fetch_arxiv_results(arxiv_api.ArxivIdRequest("2101.12345"))
+
+ assert wire.call_count > 0
+ for call in wire.call_args_list:
+ assert urlsplit(call.args[2]).netloc == "export.arxiv.org"
+ assert call.kwargs["allow_redirects"] is False
+ assert close.call_count == 2
diff --git a/tests/utilities/test_download_stuff_for_local.py b/tests/utilities/test_download_stuff_for_local.py
new file mode 100644
index 0000000000..92a0144222
--- /dev/null
+++ b/tests/utilities/test_download_stuff_for_local.py
@@ -0,0 +1,50 @@
+"""The local-data helper script must download via the 4.x-safe transport."""
+# allow: no-sut-import — exercises the runnable helper script under tests/
+
+import importlib.util
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+_SCRIPT = Path(__file__).resolve().parents[1] / "download_stuff_for_local.py"
+
+
+def _load_script():
+ spec = importlib.util.spec_from_file_location("_dl_local", _SCRIPT)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+class _Downloader:
+ def __init__(self, pdfs):
+ self.pdfs = pdfs
+
+ def download(self, url):
+ return self.pdfs[url]
+
+
+def _paper(n):
+ return SimpleNamespace(title=f"t{n}", entry_id=f"http://arxiv.org/abs/{n}")
+
+
+def test_writes_pdfs_and_reports_missing(tmp_path):
+ script = _load_script()
+ papers = [_paper(1), _paper(2)]
+ dl = _Downloader({papers[0].entry_id: b"%PDF-1", papers[1].entry_id: None})
+ failures = script.download_papers(papers, tmp_path / "out", dl)
+ assert failures == ["t2"]
+ assert (tmp_path / "out" / "paper_0.pdf").read_bytes() == b"%PDF-1"
+ assert not (tmp_path / "out" / "paper_1.pdf").exists()
+
+
+def test_unexpected_errors_propagate(tmp_path):
+ script = _load_script()
+ papers = [_paper(1)]
+ with pytest.raises(KeyError):
+ script.download_papers(papers, tmp_path, _Downloader({}))
+
+
+def test_script_does_not_use_removed_sdk_download():
+ assert ".download_pdf(" not in _SCRIPT.read_text()
diff --git a/tests/web/routes/test_available_search_engines_scope.py b/tests/web/routes/test_available_search_engines_scope.py
index 6c938d12dd..c40bb2671b 100644
--- a/tests/web/routes/test_available_search_engines_scope.py
+++ b/tests/web/routes/test_available_search_engines_scope.py
@@ -11,7 +11,7 @@ The tests below stub the engine-class flag lookups inside
``policy`` (``_get_engine_class`` and ``_engine_flags``) so they
exercise the helper's wiring (scope mapping,
fail-closed under bad input) without depending on third-party
-engines like ``arxiv`` that require ``feedparser`` to import. The
+engines like ``arxiv`` that require the ``arxiv`` SDK to import. The
*real* ``evaluate_engine`` runs the rest of its usual logic on top
of the mocked flags, so this still exercises the full helper path.
"""
@@ -54,8 +54,8 @@ def _snap(scope="adaptive", primary="arxiv"):
# policy module's _get_engine_class to return a fake class with
# the matching (is_public, is_local) tuple so the real evaluate_engine
# flow runs on top of deterministic per-engine classification without
-# needing the engines' third-party deps installed (feedparser for
-# arxiv, etc.). ``library`` and ``collection_x`` are intentionally
+# needing the engines' third-party deps installed (the ``arxiv`` SDK
+# for arxiv, etc.). ``library`` and ``collection_x`` are intentionally
# NOT in this map so they keep their real per-collection resolution.
_FLAGS = {
"arxiv": (True, False), # public web engine