| 1 | """Tests for the arXiv source adapter (lib/arxiv.py). |
| 2 | |
| 3 | Covers query construction (quoted phrase + relevance sort), the recency |
| 4 | cutoff that doubles as off-topic gating, field mapping, and graceful |
| 5 | degradation when the binary is absent. |
| 6 | """ |
| 7 | |
| 8 | from __future__ import annotations |
| 9 | |
| 10 | import json |
| 11 | from datetime import datetime, timedelta, timezone |
| 12 | |
| 13 | from lib import arxiv |
| 14 | |
| 15 | |
| 16 | NOW = datetime(2026, 6, 27, tzinfo=timezone.utc) |
| 17 | DATE_CLAUSE = "submittedDate:[202506270000 TO 202606280000]" |
| 18 | |
| 19 | |
| 20 | def _entry(title, published, summary="An abstract.", authors=("Ada Lovelace",), abs_url="https://arxiv.org/abs/2606.00001v1"): |
| 21 | return { |
| 22 | "id": "http://arxiv.org/abs/2606.00001v1", |
| 23 | "title": title, |
| 24 | "summary": summary, |
| 25 | "published": published, |
| 26 | "authors": [{"name": a} for a in authors], |
| 27 | "categories": [{"term": "cs.AI"}], |
| 28 | "links": [ |
| 29 | {"rel": "alternate", "href": abs_url, "type": "text/html"}, |
| 30 | {"rel": "related", "href": "https://arxiv.org/pdf/2606.00001v1", "title": "pdf"}, |
| 31 | ], |
| 32 | } |
| 33 | |
| 34 | |
| 35 | # ---- query construction ---- |
| 36 | |
| 37 | def test_search_query_is_quoted_phrase_relevance_sorted(): |
| 38 | args = arxiv._build_search_args("AI coding agents", 10, DATE_CLAUSE) |
| 39 | assert args[args.index("--search-query") + 1] == ( |
| 40 | f'all:"AI coding agents" AND {DATE_CLAUSE}' |
| 41 | ) |
| 42 | assert args[args.index("--sort-by") + 1] == "relevance" |
| 43 | |
| 44 | |
| 45 | def test_search_query_strips_inner_quotes(): |
| 46 | q = arxiv._build_search_query('say "hello" world') |
| 47 | assert q == 'all:"say hello world"' |
| 48 | |
| 49 | |
| 50 | def test_unquoted_fallback_search_args_conjoin_terms_at_command_boundary(): |
| 51 | args = arxiv._build_search_args("AI video generation advances", 10, DATE_CLAUSE, quoted=False) |
| 52 | assert args == [ |
| 53 | "arxiv-pp-cli", |
| 54 | "query", |
| 55 | "--search-query", |
| 56 | f'all:"AI" AND all:"video" AND all:"generation" AND all:"advances" AND {DATE_CLAUSE}', |
| 57 | "--sort-by", |
| 58 | "relevance", |
| 59 | "--max-results", |
| 60 | "10", |
| 61 | "--agent", |
| 62 | ] |
| 63 | |
| 64 | |
| 65 | def test_unquoted_fallback_quotes_operator_and_colon_terms_at_command_boundary(): |
| 66 | args = arxiv._build_search_args("AI AND OR title:video", 5, DATE_CLAUSE, quoted=False) |
| 67 | assert args[args.index("--search-query") + 1] == ( |
| 68 | f'all:"AI" AND all:"AND" AND all:"OR" AND all:"title:video" AND {DATE_CLAUSE}' |
| 69 | ) |
| 70 | |
| 71 | |
| 72 | def test_current_window_covers_partial_recency_day_and_all_of_report_end(monkeypatch): |
| 73 | now = NOW.replace(hour=13, minute=42, second=30) |
| 74 | monkeypatch.setattr(arxiv, "_today", lambda: now) |
| 75 | assert arxiv._submitted_date_clause("2026-06-27") == ( |
| 76 | "submittedDate:[202506261342 TO 202606280000]" |
| 77 | ) |
| 78 | entries = [ |
| 79 | _entry("Before the exact cutoff", "2025-06-26T13:42:30Z"), |
| 80 | _entry("Inside the recency window", "2025-06-26T13:42:31Z"), |
| 81 | _entry("Later today", "2026-06-27T23:59:59Z"), |
| 82 | _entry("Tomorrow", "2026-06-28T00:00:00Z"), |
| 83 | ] |
| 84 | items = arxiv.parse_arxiv_response({"results": entries}, to_date="2026-06-27") |
| 85 | assert [item["title"] for item in items] == ["Inside the recency window", "Later today"] |
| 86 | |
| 87 | |
| 88 | def test_date_bounds_stay_within_supported_calendar(monkeypatch): |
| 89 | monkeypatch.setattr(arxiv, "_today", lambda: NOW) |
| 90 | assert arxiv._submitted_date_clause("0001-12-01") == ( |
| 91 | "submittedDate:[000101010000 TO 000112020000]" |
| 92 | ) |
| 93 | assert arxiv._submitted_date_clause("9999-12-31") == ( |
| 94 | "submittedDate:[202506260000 TO 999912312359]" |
| 95 | ) |
| 96 | |
| 97 | |
| 98 | # ---- envelope extraction ---- |
| 99 | |
| 100 | def test_extract_entries_handles_nested_results_envelope(): |
| 101 | data = {"meta": {"source": "live"}, "results": {"entries": [{"title": "X"}]}} |
| 102 | entries = arxiv._extract_entries(data) |
| 103 | assert len(entries) == 1 and entries[0]["title"] == "X" |
| 104 | |
| 105 | |
| 106 | # ---- happy path + field mapping ---- |
| 107 | |
| 108 | def test_happy_path_maps_fields(): |
| 109 | recent = (NOW - timedelta(days=10)).strftime("%Y-%m-%dT12:00:00Z") |
| 110 | resp = {"results": [_entry("Agent Memory as a Database", recent, authors=("A", "B"))]} |
| 111 | items = arxiv.parse_arxiv_response(resp, query="agent memory", today=NOW) |
| 112 | assert len(items) == 1 |
| 113 | it = items[0] |
| 114 | assert it["title"] == "Agent Memory as a Database" |
| 115 | assert it["url"] == "https://arxiv.org/abs/2606.00001v1" # alternate, not pdf |
| 116 | assert it["date"] == (NOW - timedelta(days=10)).date().isoformat() |
| 117 | assert it["authors"] == ["A", "B"] |
| 118 | assert it["author"] == "A et al." # multi-author label |
| 119 | |
| 120 | |
| 121 | def test_url_prefers_alternate_over_pdf(): |
| 122 | recent = (NOW - timedelta(days=5)).strftime("%Y-%m-%dT12:00:00Z") |
| 123 | resp = {"results": [_entry("T", recent)]} |
| 124 | items = arxiv.parse_arxiv_response(resp, query="t", today=NOW) |
| 125 | assert "/pdf/" not in items[0]["url"] |
| 126 | assert "/abs/" in items[0]["url"] |
| 127 | |
| 128 | |
| 129 | # ---- recency cutoff (also off-topic gating) ---- |
| 130 | |
| 131 | def test_recency_cutoff_drops_stale_paper(): |
| 132 | stale = (NOW - timedelta(days=arxiv.RECENCY_DAYS + 30)).strftime("%Y-%m-%dT12:00:00Z") |
| 133 | resp = {"results": [_entry("Old Paper", stale)]} |
| 134 | items = arxiv.parse_arxiv_response(resp, query="old paper", today=NOW) |
| 135 | assert items == [] |
| 136 | |
| 137 | |
| 138 | def test_off_topic_control_drops_via_recency(): |
| 139 | # The "Golden State Warriors" keyword match is a 2017 stats paper -- the |
| 140 | # recency cutoff is what keeps arXiv quiet on non-research topics. |
| 141 | old = "2017-06-12T12:00:00Z" |
| 142 | resp = {"results": [_entry("Do Steph Curry and Klay Thompson Have Hot Hands?", old)]} |
| 143 | items = arxiv.parse_arxiv_response(resp, query="Golden State Warriors", today=NOW) |
| 144 | assert items == [] |
| 145 | |
| 146 | |
| 147 | def test_unparseable_or_missing_date_is_dropped(): |
| 148 | resp = {"results": [_entry("No Date", None), _entry("Bad Date", "not-a-date")]} |
| 149 | items = arxiv.parse_arxiv_response(resp, query="x", today=NOW) |
| 150 | assert items == [] |
| 151 | |
| 152 | |
| 153 | def test_future_dated_entry_is_dropped(): |
| 154 | future = (NOW + timedelta(days=5)).strftime("%Y-%m-%dT12:00:00Z") |
| 155 | resp = {"results": [_entry("Future", future)]} |
| 156 | items = arxiv.parse_arxiv_response(resp, query="future", today=NOW) |
| 157 | assert items == [] |
| 158 | |
| 159 | |
| 160 | # ---- error / degradation paths ---- |
| 161 | |
| 162 | def test_binary_absent_returns_empty(monkeypatch): |
| 163 | monkeypatch.setattr(arxiv.shutil, "which", lambda _bin: None) |
| 164 | resp = arxiv.search_arxiv("anything", "2026-06-01", "2026-06-27") |
| 165 | assert resp["results"] == [] |
| 166 | assert "error" in resp |
| 167 | |
| 168 | |
| 169 | def test_empty_topic_returns_empty(): |
| 170 | assert arxiv.search_arxiv(" ", "2026-06-01", "2026-06-27") == {"results": []} |
| 171 | |
| 172 | |
| 173 | def test_parse_handles_non_list_results(): |
| 174 | assert arxiv.parse_arxiv_response({"results": "oops"}, query="x", today=NOW) == [] |
| 175 | assert arxiv.parse_arxiv_response({}, query="x", today=NOW) == [] |
| 176 | |
| 177 | |
| 178 | def test_quote_only_topic_returns_empty(): |
| 179 | # A topic of only quote characters cleans to an empty phrase; don't search. |
| 180 | assert arxiv.search_arxiv('"', "2026-06-01", "2026-06-27") == {"results": []} |
| 181 | |
| 182 | |
| 183 | def test_same_day_future_timestamp_is_kept(): |
| 184 | # A paper announced later the same UTC day yields age_days == -1; the |
| 185 | # one-day grace keeps it rather than dropping it as "future". |
| 186 | later_today = NOW.replace(hour=23, minute=59).strftime("%Y-%m-%dT%H:%M:00Z") |
| 187 | resp = {"results": [_entry("Fresh paper", later_today)]} |
| 188 | items = arxiv.parse_arxiv_response(resp, query="fresh paper", today=NOW.replace(hour=1)) |
| 189 | assert len(items) == 1 |
| 190 | |
| 191 | |
| 192 | def test_as_of_window_anchors_recency_and_drops_later_papers(monkeypatch): |
| 193 | # An --as-of run ends the window in the past. The adapter must judge |
| 194 | # recency from that end date, not from the real clock: a paper published |
| 195 | # after the window cannot appear, and one from just inside it must not be |
| 196 | # dropped as "older than a year" relative to today. |
| 197 | from lib import pipeline, schema |
| 198 | |
| 199 | entries = [ |
| 200 | _entry("Window paper", "2025-05-20T12:00:00Z"), |
| 201 | _entry("End day paper", "2025-06-01T23:30:00Z"), |
| 202 | _entry("Later paper", "2025-06-02T00:30:00Z"), |
| 203 | _entry("Much later paper", "2026-01-15T12:00:00Z"), |
| 204 | ] |
| 205 | monkeypatch.setattr( |
| 206 | arxiv, "search_arxiv", lambda *_args, **_kwargs: {"results": entries} |
| 207 | ) |
| 208 | subquery = schema.SubQuery( |
| 209 | label="primary", |
| 210 | search_query="paper", |
| 211 | ranking_query="paper", |
| 212 | sources=["arxiv"], |
| 213 | ) |
| 214 | |
| 215 | items, _ = pipeline._retrieve_stream_impl( |
| 216 | topic="paper", |
| 217 | subquery=subquery, |
| 218 | source="arxiv", |
| 219 | config={}, |
| 220 | depth="quick", |
| 221 | date_range=("2025-05-02", "2025-06-01"), |
| 222 | runtime=schema.ProviderRuntime( |
| 223 | reasoning_provider="none", |
| 224 | planner_model="none", |
| 225 | rerank_model="none", |
| 226 | ), |
| 227 | mock=False, |
| 228 | ) |
| 229 | |
| 230 | assert [item["title"] for item in items] == ["Window paper", "End day paper"] |
| 231 | |
| 232 | |
| 233 | def test_arxiv_retrieval_filters_before_relevance_limit(monkeypatch): |
| 234 | from lib import pipeline, schema |
| 235 | |
| 236 | topic = "graph neural networks" |
| 237 | current_entries = [ |
| 238 | _entry(f"Graph neural networks paper {i}", published) |
| 239 | for i, published in enumerate([ |
| 240 | "2025-11-25T00:00:00Z", |
| 241 | "2026-04-11T12:00:00Z", |
| 242 | "2026-10-05T12:00:00Z", |
| 243 | "2026-11-10T12:00:00Z", |
| 244 | "2026-11-25T23:59:59Z", |
| 245 | ]) |
| 246 | ] |
| 247 | ranked_entries = [ |
| 248 | _entry(f"Stale graph neural networks paper {i}", "2025-11-24T23:59:59Z") |
| 249 | for i in range(5) |
| 250 | ] + [_entry("Later graph neural networks paper", "2026-11-26T00:00:01Z")] + current_entries |
| 251 | monkeypatch.setattr(arxiv, "_today", lambda: datetime(2026, 11, 26, tzinfo=timezone.utc)) |
| 252 | monkeypatch.setattr(arxiv, "_is_available", lambda: True) |
| 253 | |
| 254 | def fake_run(cmd, timeout): |
| 255 | query = cmd[cmd.index("--search-query") + 1] |
| 256 | limit = int(cmd[cmd.index("--max-results") + 1]) |
| 257 | assert cmd[cmd.index("--sort-by") + 1] == "relevance" |
| 258 | assert limit == 5 |
| 259 | entries = ranked_entries |
| 260 | _, _, submitted_range = query.partition(" AND submittedDate:[") |
| 261 | if submitted_range: |
| 262 | start, end = submitted_range.removesuffix("]").split(" TO ") |
| 263 | lower = datetime.strptime(start, "%Y%m%d%H%M").replace(tzinfo=timezone.utc) |
| 264 | upper = datetime.strptime(end, "%Y%m%d%H%M").replace(tzinfo=timezone.utc) |
| 265 | entries = [ |
| 266 | entry for entry in entries |
| 267 | if lower <= datetime.fromisoformat(entry["published"]) <= upper |
| 268 | ] |
| 269 | return _Proc(0, json.dumps({"results": {"entries": entries[:limit]}})) |
| 270 | |
| 271 | monkeypatch.setattr(arxiv.subproc, "run_with_timeout", fake_run) |
| 272 | items, _ = pipeline._retrieve_stream_impl( |
| 273 | topic=topic, |
| 274 | subquery=schema.SubQuery( |
| 275 | label="primary", search_query=topic, ranking_query=topic, sources=["arxiv"], |
| 276 | ), |
| 277 | source="arxiv", |
| 278 | config={}, |
| 279 | depth="quick", |
| 280 | date_range=("2026-10-26", "2026-11-25"), |
| 281 | runtime=schema.ProviderRuntime( |
| 282 | reasoning_provider="none", planner_model="none", rerank_model="none", |
| 283 | ), |
| 284 | mock=False, |
| 285 | ) |
| 286 | assert [item["title"] for item in items] == [entry["title"] for entry in current_entries] |
| 287 | |
| 288 | |
| 289 | class _Proc: |
| 290 | def __init__(self, rc, out, err=""): |
| 291 | self.returncode, self.stdout, self.stderr = rc, out, err |
| 292 | |
| 293 | |
| 294 | def test_run_cli_flattens_nested_envelope(monkeypatch): |
| 295 | monkeypatch.setattr(arxiv, "_is_available", lambda: True) |
| 296 | payload = '{"meta":{},"results":{"entries":[{"title":"X"}]}}' |
| 297 | monkeypatch.setattr(arxiv.subproc, "run_with_timeout", lambda cmd, timeout: _Proc(0, payload)) |
| 298 | resp = arxiv.search_arxiv("topic", "2026-06-01", "2026-06-27") |
| 299 | assert resp["results"] == [{"title": "X"}] |
| 300 | |
| 301 | |
| 302 | def test_run_cli_nonzero_exit_returns_error(monkeypatch): |
| 303 | monkeypatch.setattr(arxiv, "_is_available", lambda: True) |
| 304 | monkeypatch.setattr(arxiv.subproc, "run_with_timeout", lambda cmd, timeout: _Proc(1, "", "boom\nmore")) |
| 305 | resp = arxiv.search_arxiv("topic", "2026-06-01", "2026-06-27") |
| 306 | assert resp["results"] == [] and "boom" in resp["error"] |
| 307 | |
| 308 | |
| 309 | def test_run_cli_bad_json_returns_error(monkeypatch): |
| 310 | monkeypatch.setattr(arxiv, "_is_available", lambda: True) |
| 311 | monkeypatch.setattr(arxiv.subproc, "run_with_timeout", lambda cmd, timeout: _Proc(0, "not json")) |
| 312 | resp = arxiv.search_arxiv("topic", "2026-06-01", "2026-06-27") |
| 313 | assert resp["results"] == [] and "error" in resp |
| 314 | |
| 315 | |
| 316 | def test_empty_stdout_returns_error_without_retry(monkeypatch): |
| 317 | monkeypatch.setattr(arxiv, "_is_available", lambda: True) |
| 318 | calls = [] |
| 319 | |
| 320 | def fake_run(cmd, timeout): |
| 321 | calls.append(cmd) |
| 322 | return _Proc(0, "") |
| 323 | |
| 324 | monkeypatch.setattr(arxiv.subproc, "run_with_timeout", fake_run) |
| 325 | resp = arxiv.search_arxiv("topic", "2026-06-01", "2026-06-27") |
| 326 | assert resp == {"results": [], "error": "empty stdout"} |
| 327 | assert len(calls) == 1 |
| 328 | |
| 329 | |
| 330 | def test_unrecognized_json_returns_error_without_retry(monkeypatch): |
| 331 | monkeypatch.setattr(arxiv, "_is_available", lambda: True) |
| 332 | calls = [] |
| 333 | |
| 334 | def fake_run(cmd, timeout): |
| 335 | calls.append(cmd) |
| 336 | return _Proc(0, '{"status":"ok"}') |
| 337 | |
| 338 | monkeypatch.setattr(arxiv.subproc, "run_with_timeout", fake_run) |
| 339 | resp = arxiv.search_arxiv("topic", "2026-06-01", "2026-06-27") |
| 340 | assert resp == {"results": [], "error": "unrecognized JSON response"} |
| 341 | assert len(calls) == 1 |
| 342 | |
| 343 | |
| 344 | def test_recognized_empty_list_retries(monkeypatch): |
| 345 | monkeypatch.setattr(arxiv, "_is_available", lambda: True) |
| 346 | calls = [] |
| 347 | |
| 348 | def fake_run(cmd, timeout): |
| 349 | calls.append(cmd) |
| 350 | return _Proc(0, "[]") |
| 351 | |
| 352 | monkeypatch.setattr(arxiv.subproc, "run_with_timeout", fake_run) |
| 353 | resp = arxiv.search_arxiv("topic", "2026-06-01", "2026-06-27") |
| 354 | assert resp == {"results": []} |
| 355 | assert len(calls) == 2 |
| 356 | |
| 357 | |
| 358 | # ---- unquoted-retry on zero results (#908) ---- |
| 359 | |
| 360 | def test_zero_result_quoted_query_retries_unquoted_and_finds_results(monkeypatch): |
| 361 | """A natural-language multi-word topic matches nothing as an exact |
| 362 | phrase, but the unquoted retry finds it -- the fix for #908.""" |
| 363 | monkeypatch.setattr(arxiv, "_is_available", lambda: True) |
| 364 | monkeypatch.setattr(arxiv, "_today", lambda: NOW + timedelta(days=1)) |
| 365 | calls = [] |
| 366 | |
| 367 | def fake_run(cmd, timeout): |
| 368 | calls.append(cmd) |
| 369 | query = cmd[cmd.index("--search-query") + 1] |
| 370 | if query == f'all:"AI video generation advances" AND {DATE_CLAUSE}': |
| 371 | return _Proc(0, '{"results":{"entries":[]}}') |
| 372 | return _Proc(0, '{"results":{"entries":[{"title":"AI video generation advances"}]}}') |
| 373 | |
| 374 | monkeypatch.setattr(arxiv.subproc, "run_with_timeout", fake_run) |
| 375 | resp = arxiv.search_arxiv("AI video generation advances", "2026-06-01", "2026-06-27") |
| 376 | assert resp["results"] == [{"title": "AI video generation advances"}] |
| 377 | assert len(calls) == 2 |
| 378 | assert f'all:"AI video generation advances" AND {DATE_CLAUSE}' in calls[0] |
| 379 | assert f'all:"AI" AND all:"video" AND all:"generation" AND all:"advances" AND {DATE_CLAUSE}' in calls[1] |
| 380 | |
| 381 | |
| 382 | def test_zero_result_quoted_query_retry_also_empty_returns_empty(monkeypatch): |
| 383 | monkeypatch.setattr(arxiv, "_is_available", lambda: True) |
| 384 | calls = [] |
| 385 | |
| 386 | def fake_run(cmd, timeout): |
| 387 | calls.append(cmd) |
| 388 | return _Proc(0, '{"results":{"entries":[]}}') |
| 389 | |
| 390 | monkeypatch.setattr(arxiv.subproc, "run_with_timeout", fake_run) |
| 391 | resp = arxiv.search_arxiv("truly obscure nonsense topic", "2026-06-01", "2026-06-27") |
| 392 | assert resp["results"] == [] |
| 393 | assert "error" not in resp |
| 394 | assert len(calls) == 2 |
| 395 | |
| 396 | |
| 397 | def test_real_cli_error_does_not_trigger_unquoted_retry(monkeypatch): |
| 398 | """A genuine failure (nonzero exit) must not retry -- only a clean |
| 399 | zero-result success should (R6).""" |
| 400 | monkeypatch.setattr(arxiv, "_is_available", lambda: True) |
| 401 | calls = [] |
| 402 | |
| 403 | def fake_run(cmd, timeout): |
| 404 | calls.append(cmd) |
| 405 | return _Proc(1, "", "boom") |
| 406 | |
| 407 | monkeypatch.setattr(arxiv.subproc, "run_with_timeout", fake_run) |
| 408 | resp = arxiv.search_arxiv("topic", "2026-06-01", "2026-06-27") |
| 409 | assert resp["results"] == [] and "boom" in resp["error"] |
| 410 | assert len(calls) == 1 |
| 411 |