| 1 | """Tests for digg.py - Digg source via digg-pp-cli.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import json |
| 6 | import os |
| 7 | import shutil |
| 8 | from datetime import datetime, timedelta, timezone |
| 9 | from unittest.mock import MagicMock, patch |
| 10 | |
| 11 | import pytest |
| 12 | |
| 13 | from lib import digg |
| 14 | from lib import subproc |
| 15 | |
| 16 | # === Helpers === |
| 17 | |
| 18 | |
| 19 | def _cluster( |
| 20 | cluster_url_id: str = "abc123xy", |
| 21 | title: str = "Sample cluster", |
| 22 | tldr: str = "A short summary of what is happening.", |
| 23 | rank: int = 1, |
| 24 | post_count: int = 5, |
| 25 | unique_authors: int = 3, |
| 26 | first_post_age: str = "5d", |
| 27 | ): |
| 28 | return { |
| 29 | "clusterUrlId": cluster_url_id, |
| 30 | "clusterId": f"uuid-{cluster_url_id}", |
| 31 | "title": title, |
| 32 | "tldr": tldr, |
| 33 | "rank": rank, |
| 34 | "postCount": post_count, |
| 35 | "uniqueAuthors": unique_authors, |
| 36 | "firstPostAge": first_post_age, |
| 37 | } |
| 38 | |
| 39 | |
| 40 | def _post( |
| 41 | username: str = "someone", |
| 42 | body: str = "Some body text about the topic.", |
| 43 | rank: int = 100, |
| 44 | category: str = "Engineer", |
| 45 | post_type: str = "tweet", |
| 46 | x_url: str | None = None, |
| 47 | ): |
| 48 | return { |
| 49 | "author": { |
| 50 | "username": username, |
| 51 | "display_name": username.title(), |
| 52 | "category": category, |
| 53 | "rank": rank, |
| 54 | }, |
| 55 | "body": body, |
| 56 | "post_type": post_type, |
| 57 | "xUrl": x_url or f"https://x.com/{username}/status/1234567890", |
| 58 | "posted_at": "2026-05-01T12:00:00+00:00", |
| 59 | } |
| 60 | |
| 61 | |
| 62 | def _stdout_for(payload: dict) -> subproc.SubprocResult: |
| 63 | return subproc.SubprocResult(returncode=0, stdout=json.dumps(payload), stderr="") |
| 64 | |
| 65 | # === _parse_first_post_age === |
| 66 | |
| 67 | |
| 68 | def test_parse_first_post_age_days(): |
| 69 | today = datetime(2026, 5, 9, tzinfo=timezone.utc) |
| 70 | assert digg._parse_first_post_age("5d", today=today) == "2026-05-04" |
| 71 | |
| 72 | |
| 73 | def test_parse_first_post_age_hours_returns_today(): |
| 74 | today = datetime(2026, 5, 9, 10, 0, tzinfo=timezone.utc) |
| 75 | assert digg._parse_first_post_age("5h", today=today) == "2026-05-09" |
| 76 | |
| 77 | |
| 78 | def test_parse_first_post_age_weeks(): |
| 79 | today = datetime(2026, 5, 9, tzinfo=timezone.utc) |
| 80 | assert digg._parse_first_post_age("2w", today=today) == "2026-04-25" |
| 81 | |
| 82 | |
| 83 | def test_parse_first_post_age_months_inside_window(): |
| 84 | today = datetime(2026, 5, 9, tzinfo=timezone.utc) |
| 85 | # 1 month = 30 days exactly, still inside the 30-day window. |
| 86 | assert digg._parse_first_post_age("1m", today=today) == (today - timedelta(days=30)).date().isoformat() |
| 87 | |
| 88 | |
| 89 | def test_parse_first_post_age_outside_30d_returns_none(): |
| 90 | today = datetime(2026, 5, 9, tzinfo=timezone.utc) |
| 91 | assert digg._parse_first_post_age("2m", today=today) is None |
| 92 | assert digg._parse_first_post_age("31d", today=today) is None |
| 93 | |
| 94 | |
| 95 | def test_parse_first_post_age_invalid(): |
| 96 | assert digg._parse_first_post_age(None) is None |
| 97 | assert digg._parse_first_post_age("") is None |
| 98 | assert digg._parse_first_post_age("garbage") is None |
| 99 | assert digg._parse_first_post_age("5x") is None |
| 100 | assert digg._parse_first_post_age("d") is None |
| 101 | assert digg._parse_first_post_age("-3d") is None |
| 102 | |
| 103 | # === parse_digg_response === |
| 104 | |
| 105 | |
| 106 | def test_parse_response_happy_path(): |
| 107 | response = { |
| 108 | "results": [ |
| 109 | _cluster(cluster_url_id="aaa", title="First", rank=1), |
| 110 | _cluster(cluster_url_id="bbb", title="Second", rank=4), |
| 111 | _cluster(cluster_url_id="ccc", title="Third", rank=12), |
| 112 | ] |
| 113 | } |
| 114 | items = digg.parse_digg_response(response) |
| 115 | assert len(items) == 3 |
| 116 | ids = [i["id"] for i in items] |
| 117 | assert ids == ["aaa", "bbb", "ccc"] |
| 118 | for item in items: |
| 119 | assert item["url"].startswith("https://digg.com/ai/") |
| 120 | assert item["engagement"]["postCount"] == 5 |
| 121 | assert item["engagement"]["uniqueAuthors"] == 3 |
| 122 | assert item["engagement"]["rank"] in (1, 4, 12) |
| 123 | assert item["posts"] == [] |
| 124 | assert item["date"] is not None |
| 125 | |
| 126 | |
| 127 | def test_parse_response_empty(): |
| 128 | assert digg.parse_digg_response({"results": []}) == [] |
| 129 | assert digg.parse_digg_response({}) == [] |
| 130 | assert digg.parse_digg_response({"results": "not-a-list"}) == [] |
| 131 | |
| 132 | |
| 133 | def test_parse_response_drops_missing_id(): |
| 134 | response = { |
| 135 | "results": [ |
| 136 | {"title": "no id", "tldr": "x", "postCount": 1, "uniqueAuthors": 1, "firstPostAge": "1d"}, |
| 137 | _cluster(cluster_url_id="ok", title="ok"), |
| 138 | ] |
| 139 | } |
| 140 | items = digg.parse_digg_response(response) |
| 141 | assert [i["id"] for i in items] == ["ok"] |
| 142 | |
| 143 | |
| 144 | def test_parse_response_drops_clusters_outside_30d(): |
| 145 | response = { |
| 146 | "results": [ |
| 147 | _cluster(cluster_url_id="recent", first_post_age="2d"), |
| 148 | _cluster(cluster_url_id="ancient", first_post_age="2m"), |
| 149 | ] |
| 150 | } |
| 151 | items = digg.parse_digg_response(response) |
| 152 | assert [i["id"] for i in items] == ["recent"] |
| 153 | |
| 154 | |
| 155 | def test_parse_response_keeps_cluster_when_age_missing(): |
| 156 | # When firstPostAge is absent or empty, we don't have evidence to drop; |
| 157 | # keep the cluster with date=None and let date-confidence downgrade it. |
| 158 | response = { |
| 159 | "results": [ |
| 160 | {**_cluster(cluster_url_id="noage"), "firstPostAge": None}, |
| 161 | ] |
| 162 | } |
| 163 | items = digg.parse_digg_response(response) |
| 164 | assert len(items) == 1 |
| 165 | assert items[0]["date"] is None |
| 166 | |
| 167 | |
| 168 | def test_parse_response_relevance_with_query(): |
| 169 | response = { |
| 170 | "results": [ |
| 171 | _cluster(cluster_url_id="match", title="OpenClaw launch", tldr="OpenClaw shipped today"), |
| 172 | _cluster(cluster_url_id="nomatch", title="Cricket scores", tldr="Mumbai vs Delhi"), |
| 173 | ] |
| 174 | } |
| 175 | items = digg.parse_digg_response(response, query="OpenClaw") |
| 176 | by_id = {i["id"]: i for i in items} |
| 177 | assert by_id["match"]["relevance"] > by_id["nomatch"]["relevance"] |
| 178 | |
| 179 | |
| 180 | def test_parse_response_engagement_rank_score(): |
| 181 | response = { |
| 182 | "results": [ |
| 183 | _cluster(cluster_url_id="top", rank=1), |
| 184 | _cluster(cluster_url_id="off-leaderboard", rank=999), |
| 185 | ] |
| 186 | } |
| 187 | items = digg.parse_digg_response(response) |
| 188 | by_id = {i["id"]: i for i in items} |
| 189 | assert by_id["top"]["engagement"]["rank_score"] == 50.0 |
| 190 | assert by_id["off-leaderboard"]["engagement"]["rank_score"] == 0.0 |
| 191 | |
| 192 | # === _parse_post === |
| 193 | |
| 194 | |
| 195 | def test_parse_post_happy(): |
| 196 | out = digg._parse_post(_post(username="adam", body="Hello world")) |
| 197 | assert out is not None |
| 198 | assert out["username"] == "adam" |
| 199 | assert out["body"] == "Hello world" |
| 200 | assert out["x_url"].startswith("https://x.com/") |
| 201 | |
| 202 | |
| 203 | def test_parse_post_drops_missing_body_or_handle_or_url(): |
| 204 | assert digg._parse_post({"author": {"username": "x"}, "body": "", "xUrl": "u"}) is None |
| 205 | assert digg._parse_post({"author": {}, "body": "txt", "xUrl": "u"}) is None |
| 206 | assert digg._parse_post({"author": {"username": "x"}, "body": "txt", "xUrl": ""}) is None |
| 207 | assert digg._parse_post(None) is None # type: ignore[arg-type] |
| 208 | |
| 209 | |
| 210 | def test_parse_post_drops_non_http_scheme_xurl(): |
| 211 | """Any non-http(s) scheme on xUrl yields no post. |
| 212 | |
| 213 | A malicious Digg API response (or compromised upstream) could set xUrl to |
| 214 | javascript:, data:text/html;..., file:, vbscript:, etc. The HTML report |
| 215 | renders the xUrl into an <a href> attribute, so any non-web scheme is a |
| 216 | stored-XSS or local-file vector when the user clicks the attribution. |
| 217 | """ |
| 218 | for bad_url in ( |
| 219 | "javascript:alert(1)", |
| 220 | "data:text/html;base64,PHNjcmlwdD5hbGVydCgxKTwvc2NyaXB0Pg==", |
| 221 | "vbscript:msgbox(1)", |
| 222 | "file:///etc/passwd", |
| 223 | "about:blank", |
| 224 | ): |
| 225 | out = digg._parse_post(_post(x_url=bad_url)) |
| 226 | assert out is None, f"expected non-http xUrl to be dropped, got: {out}" |
| 227 | |
| 228 | # http and https remain accepted. |
| 229 | assert digg._parse_post(_post(x_url="https://x.com/a/status/1")) is not None |
| 230 | assert digg._parse_post(_post(x_url="http://x.com/a/status/1")) is not None |
| 231 | |
| 232 | |
| 233 | def test_parse_post_logs_unsafe_xurl_rejection_even_in_non_tty(capsys): |
| 234 | """Security-class drops must be observable in non-interactive runs. |
| 235 | |
| 236 | The default ``log.source_log`` path is TTY-gated; without forcing |
| 237 | ``tty_only=False`` the rejection is invisible in Claude Code runs, |
| 238 | which is exactly the attack surface. Guard against silent regression. |
| 239 | """ |
| 240 | digg._parse_post(_post(x_url="javascript:alert(1)")) |
| 241 | err = capsys.readouterr().err |
| 242 | assert "[Digg] dropped post with unsafe xUrl scheme" in err |
| 243 | assert "javascript:alert(1)" in err |
| 244 | |
| 245 | |
| 246 | # === _run_cli / search_digg with stubbed subprocess === |
| 247 | |
| 248 | |
| 249 | def test_search_digg_binary_missing_returns_empty(monkeypatch): |
| 250 | monkeypatch.setattr(digg.shutil, "which", lambda _: None) |
| 251 | out = digg.search_digg("anything", "2026-04-09", "2026-05-09") |
| 252 | assert out["results"] == [] |
| 253 | assert "error" in out |
| 254 | |
| 255 | |
| 256 | def test_search_digg_passes_since_30d(monkeypatch): |
| 257 | captured: dict = {} |
| 258 | |
| 259 | def fake_run(cmd, *, timeout, env=None, on_pid=None): |
| 260 | captured["cmd"] = list(cmd) |
| 261 | return _stdout_for({"results": []}) |
| 262 | |
| 263 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 264 | monkeypatch.setattr(digg.subproc, "run_with_timeout", fake_run) |
| 265 | digg.search_digg("openclaw", "2026-04-09", "2026-05-09") |
| 266 | assert "--since" in captured["cmd"] |
| 267 | assert captured["cmd"][captured["cmd"].index("--since") + 1] == "30d" |
| 268 | assert "--agent" in captured["cmd"] |
| 269 | assert captured["cmd"][:2] == [digg.CLI_BIN, "search"] |
| 270 | assert captured["cmd"][-2:] == ["--", "openclaw"] |
| 271 | assert captured["cmd"][captured["cmd"].index("--topic") + 1] == "ai,tech" |
| 272 | |
| 273 | |
| 274 | def test_search_digg_subproc_timeout_returns_empty(monkeypatch): |
| 275 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 276 | |
| 277 | def fake_run(*_a, **_kw): |
| 278 | raise subproc.SubprocTimeout("boom") |
| 279 | |
| 280 | monkeypatch.setattr(digg.subproc, "run_with_timeout", fake_run) |
| 281 | out = digg.search_digg("openclaw", "2026-04-09", "2026-05-09") |
| 282 | assert out["results"] == [] |
| 283 | assert "error" in out |
| 284 | |
| 285 | |
| 286 | def test_search_digg_nonzero_exit_returns_empty(monkeypatch): |
| 287 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 288 | monkeypatch.setattr( |
| 289 | digg.subproc, |
| 290 | "run_with_timeout", |
| 291 | lambda *a, **k: subproc.SubprocResult(returncode=2, stdout="", stderr="cluster not found"), |
| 292 | ) |
| 293 | out = digg.search_digg("openclaw", "2026-04-09", "2026-05-09") |
| 294 | assert out["results"] == [] |
| 295 | assert "error" in out |
| 296 | |
| 297 | |
| 298 | def test_search_digg_unknown_flag_names_an_outdated_helper_and_its_upgrade(monkeypatch): |
| 299 | from lib import health, pipeline |
| 300 | |
| 301 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 302 | monkeypatch.setattr( |
| 303 | digg.subproc, |
| 304 | "run_with_timeout", |
| 305 | lambda *a, **k: subproc.SubprocResult( |
| 306 | returncode=1, stdout="", stderr="Error: unknown flag: --topic\nUsage: ..." |
| 307 | ), |
| 308 | ) |
| 309 | out = digg.search_digg("openclaw", "2026-04-09", "2026-05-09") |
| 310 | assert out["results"] == [] |
| 311 | assert out["error"] == ( |
| 312 | f"digg-pp-cli is outdated and rejected the search; upgrade: {health.helper_upgrade_cmd('digg')}" |
| 313 | ) |
| 314 | assert len(out["error"]) <= 140 |
| 315 | outcome = pipeline._result_outcome_artifact("digg", out) |
| 316 | assert outcome["_source_outcome"]["detail"] == out["error"] |
| 317 | assert outcome["_source_outcome"]["state"] != health.OK |
| 318 | |
| 319 | |
| 320 | def test_search_digg_other_nonzero_exit_keeps_its_own_error(monkeypatch): |
| 321 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 322 | monkeypatch.setattr( |
| 323 | digg.subproc, |
| 324 | "run_with_timeout", |
| 325 | lambda *a, **k: subproc.SubprocResult(returncode=2, stdout="", stderr="cluster not found"), |
| 326 | ) |
| 327 | out = digg.search_digg("openclaw", "2026-04-09", "2026-05-09") |
| 328 | assert out["error"] == "cluster not found" |
| 329 | assert digg.outdated_cli_error(out["error"]) is None |
| 330 | |
| 331 | |
| 332 | def test_search_digg_invalid_json_returns_empty(monkeypatch): |
| 333 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 334 | monkeypatch.setattr( |
| 335 | digg.subproc, |
| 336 | "run_with_timeout", |
| 337 | lambda *a, **k: subproc.SubprocResult(returncode=0, stdout="not json", stderr=""), |
| 338 | ) |
| 339 | out = digg.search_digg("openclaw", "2026-04-09", "2026-05-09") |
| 340 | assert out["results"] == [] |
| 341 | assert "error" in out |
| 342 | |
| 343 | |
| 344 | def test_search_digg_empty_query_short_circuits(monkeypatch): |
| 345 | called = MagicMock() |
| 346 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 347 | monkeypatch.setattr(digg.subproc, "run_with_timeout", called) |
| 348 | out = digg.search_digg("", "2026-04-09", "2026-05-09") |
| 349 | assert out["results"] == [] |
| 350 | called.assert_not_called() |
| 351 | |
| 352 | |
| 353 | _REAL_FALLBACK_STDERR = ( |
| 354 | "falling back to local FTS5: GET https://di.gg/api/search/stories: HTTP 404: " |
| 355 | '<!DOCTYPE html><html data-dpl-id="dpl_x" lang="en" class="font-sans">' |
| 356 | + "x" * 500 |
| 357 | + "\n" |
| 358 | ) |
| 359 | |
| 360 | |
| 361 | def _real_fallback_result() -> subproc.SubprocResult: |
| 362 | """digg-pp-cli 2026.9.1 output when the live API 404s: exit 0, no meta.reason.""" |
| 363 | return subproc.SubprocResult( |
| 364 | returncode=0, |
| 365 | stdout=json.dumps( |
| 366 | { |
| 367 | "meta": { |
| 368 | "count": 0, |
| 369 | "query": "openai", |
| 370 | "since": "30d", |
| 371 | "source": "local", |
| 372 | }, |
| 373 | "results": [], |
| 374 | } |
| 375 | ), |
| 376 | stderr=_REAL_FALLBACK_STDERR, |
| 377 | ) |
| 378 | |
| 379 | |
| 380 | def test_search_digg_real_fallback_reports_stderr_reason(monkeypatch): |
| 381 | """A live search that fell back to an empty local store is not 'no results'.""" |
| 382 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 383 | monkeypatch.setattr( |
| 384 | digg.subproc, "run_with_timeout", lambda *a, **k: _real_fallback_result() |
| 385 | ) |
| 386 | out = digg.search_digg("openai", "2026-04-09", "2026-05-09") |
| 387 | assert out["results"] == [] |
| 388 | assert out["error"] == ( |
| 389 | "live-search-unavailable: GET https://di.gg/api/search/stories: HTTP 404" |
| 390 | ) |
| 391 | |
| 392 | |
| 393 | def test_real_fallback_reason_reaches_source_outcome(monkeypatch): |
| 394 | from lib import pipeline |
| 395 | |
| 396 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 397 | monkeypatch.setattr( |
| 398 | digg.subproc, "run_with_timeout", lambda *a, **k: _real_fallback_result() |
| 399 | ) |
| 400 | out = digg.search_digg("openai", "2026-04-09", "2026-05-09") |
| 401 | outcome = pipeline._result_outcome_artifact("digg", out)["_source_outcome"] |
| 402 | assert outcome["state"] == "error" |
| 403 | assert "HTTP 404" in outcome["detail"] |
| 404 | assert "<!DOCTYPE" not in outcome["detail"] |
| 405 | |
| 406 | |
| 407 | def test_local_fallback_reason_bounds_non_http_errors(): |
| 408 | stderr = "noise\nfalling back to local FTS5: dial tcp: " + "y" * 1000 + "\n" |
| 409 | reason = digg._local_fallback_reason(stderr) |
| 410 | assert reason.startswith("dial tcp: ") |
| 411 | assert len(reason) <= digg._FALLBACK_REASON_MAX |
| 412 | |
| 413 | |
| 414 | def test_search_digg_empty_local_fallback_prefers_meta_reason(monkeypatch): |
| 415 | """meta.reason is not emitted by digg-pp-cli 2026.9.1; prefer it if a later release adds it.""" |
| 416 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 417 | monkeypatch.setattr( |
| 418 | digg.subproc, |
| 419 | "run_with_timeout", |
| 420 | lambda *a, **k: subproc.SubprocResult( |
| 421 | returncode=0, |
| 422 | stdout=json.dumps( |
| 423 | { |
| 424 | "meta": { |
| 425 | "source": "local", |
| 426 | "reason": "GET https://di.gg/api/search/stories: HTTP 404", |
| 427 | }, |
| 428 | "results": [], |
| 429 | } |
| 430 | ), |
| 431 | stderr="falling back to local FTS5: stderr reason\n", |
| 432 | ), |
| 433 | ) |
| 434 | out = digg.search_digg("openai", "2026-04-09", "2026-05-09") |
| 435 | assert out["results"] == [] |
| 436 | assert out["error"] == ( |
| 437 | "live-search-unavailable: GET https://di.gg/api/search/stories: HTTP 404" |
| 438 | ) |
| 439 | |
| 440 | |
| 441 | def test_search_digg_empty_local_fallback_without_reason_still_errors(monkeypatch): |
| 442 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 443 | monkeypatch.setattr( |
| 444 | digg.subproc, |
| 445 | "run_with_timeout", |
| 446 | lambda *a, **k: _stdout_for({"meta": {"source": "local"}, "results": []}), |
| 447 | ) |
| 448 | out = digg.search_digg("openai", "2026-04-09", "2026-05-09") |
| 449 | assert out["results"] == [] |
| 450 | assert "live-search-unavailable" in out["error"] |
| 451 | |
| 452 | |
| 453 | def test_search_digg_local_fallback_with_rows_keeps_results(monkeypatch): |
| 454 | """A user who ran `digg-pp-cli sync` still gets their local clusters.""" |
| 455 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 456 | monkeypatch.setattr( |
| 457 | digg.subproc, |
| 458 | "run_with_timeout", |
| 459 | lambda *a, **k: _stdout_for( |
| 460 | {"meta": {"source": "local"}, "results": [_cluster()]} |
| 461 | ), |
| 462 | ) |
| 463 | out = digg.search_digg("openai", "2026-04-09", "2026-05-09") |
| 464 | assert len(out["results"]) == 1 |
| 465 | assert "error" not in out |
| 466 | |
| 467 | |
| 468 | def test_search_digg_live_empty_is_still_no_results(monkeypatch): |
| 469 | """A live search that genuinely found nothing stays a clean empty.""" |
| 470 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 471 | monkeypatch.setattr( |
| 472 | digg.subproc, |
| 473 | "run_with_timeout", |
| 474 | lambda *a, **k: _stdout_for( |
| 475 | {"meta": {"source": "live", "count": 0}, "results": []} |
| 476 | ), |
| 477 | ) |
| 478 | out = digg.search_digg("openai", "2026-04-09", "2026-05-09") |
| 479 | assert out["results"] == [] |
| 480 | assert "error" not in out |
| 481 | |
| 482 | # === enrich_with_top_posts === |
| 483 | |
| 484 | |
| 485 | def test_enrich_with_top_posts_attaches_posts(monkeypatch): |
| 486 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 487 | |
| 488 | def fake_run(cmd, *, timeout, env=None, on_pid=None): |
| 489 | # cmd = ['digg-pp-cli', 'posts', '--agent', '--by', 'rank', '--limit', '3', '--', '<urlId>'] |
| 490 | cluster_url_id = cmd[-1] |
| 491 | return _stdout_for( |
| 492 | { |
| 493 | "results": [ |
| 494 | _post(username=f"u_{cluster_url_id}", body=f"body for {cluster_url_id}"), |
| 495 | _post(username=f"v_{cluster_url_id}", body=f"second for {cluster_url_id}"), |
| 496 | ] |
| 497 | } |
| 498 | ) |
| 499 | |
| 500 | monkeypatch.setattr(digg.subproc, "run_with_timeout", fake_run) |
| 501 | |
| 502 | items = [ |
| 503 | {"id": "aaa", "engagement": {"postCount": 5}, "posts": []}, |
| 504 | {"id": "bbb", "engagement": {"postCount": 3}, "posts": []}, |
| 505 | {"id": "ccc", "engagement": {"postCount": 9}, "posts": []}, |
| 506 | {"id": "ddd", "engagement": {"postCount": 1}, "posts": []}, |
| 507 | ] |
| 508 | digg.enrich_with_top_posts(items, top_k=2, posts_per=3) |
| 509 | assert len(items[0]["posts"]) == 2 |
| 510 | assert items[0]["posts"][0]["username"] == "u_aaa" |
| 511 | assert len(items[1]["posts"]) == 2 |
| 512 | assert items[2]["posts"] == [] # not enriched (top_k=2) |
| 513 | |
| 514 | |
| 515 | def test_enrich_skips_zero_postcount(monkeypatch): |
| 516 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 517 | fake = MagicMock(return_value=_stdout_for({"results": [_post()]})) |
| 518 | monkeypatch.setattr(digg.subproc, "run_with_timeout", fake) |
| 519 | |
| 520 | items = [ |
| 521 | {"id": "no-posts", "engagement": {"postCount": 0}, "posts": []}, |
| 522 | {"id": "ok", "engagement": {"postCount": 7}, "posts": []}, |
| 523 | ] |
| 524 | digg.enrich_with_top_posts(items, top_k=2, posts_per=3) |
| 525 | assert items[0]["posts"] == [] |
| 526 | assert len(items[1]["posts"]) == 1 |
| 527 | |
| 528 | |
| 529 | def test_enrich_partial_timeout_does_not_break_others(monkeypatch): |
| 530 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 531 | call_count = {"n": 0} |
| 532 | |
| 533 | def fake_run(cmd, *, timeout, env=None, on_pid=None): |
| 534 | call_count["n"] += 1 |
| 535 | if call_count["n"] == 2: |
| 536 | raise subproc.SubprocTimeout("boom") |
| 537 | return _stdout_for({"results": [_post(username=f"u{call_count['n']}")]}) |
| 538 | |
| 539 | monkeypatch.setattr(digg.subproc, "run_with_timeout", fake_run) |
| 540 | |
| 541 | items = [ |
| 542 | {"id": "a", "engagement": {"postCount": 3}, "posts": []}, |
| 543 | {"id": "b", "engagement": {"postCount": 3}, "posts": []}, |
| 544 | {"id": "c", "engagement": {"postCount": 3}, "posts": []}, |
| 545 | ] |
| 546 | digg.enrich_with_top_posts(items, top_k=3, posts_per=3) |
| 547 | assert len(items[0]["posts"]) == 1 |
| 548 | assert items[1]["posts"] == [] # timed out |
| 549 | assert len(items[2]["posts"]) == 1 |
| 550 | |
| 551 | |
| 552 | def test_enrich_top_k_zero_skips_all(monkeypatch): |
| 553 | fake = MagicMock() |
| 554 | monkeypatch.setattr(digg.subproc, "run_with_timeout", fake) |
| 555 | items = [{"id": "a", "engagement": {"postCount": 5}, "posts": []}] |
| 556 | digg.enrich_with_top_posts(items, top_k=0) |
| 557 | fake.assert_not_called() |
| 558 | |
| 559 | # === enrich_source_items (post-dedupe path) === |
| 560 | |
| 561 | |
| 562 | class _FakeSourceItem: |
| 563 | def __init__(self, source, item_id, engagement, metadata): |
| 564 | self.source = source |
| 565 | self.item_id = item_id |
| 566 | self.engagement = engagement |
| 567 | self.metadata = metadata |
| 568 | |
| 569 | |
| 570 | def test_enrich_source_items_attaches_to_survivors(monkeypatch): |
| 571 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 572 | monkeypatch.setattr( |
| 573 | digg.subproc, |
| 574 | "run_with_timeout", |
| 575 | lambda cmd, *, timeout, env=None, on_pid=None: _stdout_for( |
| 576 | {"results": [_post(username=f"u_{cmd[-1]}")]} |
| 577 | ), |
| 578 | ) |
| 579 | items = [ |
| 580 | _FakeSourceItem("digg", "ID1", {"postCount": 4}, {"clusterUrlId": "ID1", "posts": []}), |
| 581 | _FakeSourceItem("digg", "ID2", {"postCount": 6}, {"clusterUrlId": "ID2", "posts": []}), |
| 582 | _FakeSourceItem("digg", "ID3", {"postCount": 8}, {"clusterUrlId": "ID3", "posts": []}), |
| 583 | ] |
| 584 | digg.enrich_source_items(items, top_k=2) |
| 585 | assert items[0].metadata["posts"][0]["username"] == "u_ID1" |
| 586 | assert items[1].metadata["posts"][0]["username"] == "u_ID2" |
| 587 | assert items[2].metadata["posts"] == [] |
| 588 | |
| 589 | |
| 590 | def test_enrich_source_items_skips_non_digg(monkeypatch): |
| 591 | fake = MagicMock() |
| 592 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 593 | monkeypatch.setattr(digg.subproc, "run_with_timeout", fake) |
| 594 | items = [_FakeSourceItem("hackernews", "HN1", {"points": 100}, {"posts": []})] |
| 595 | digg.enrich_source_items(items, top_k=3) |
| 596 | fake.assert_not_called() |
| 597 | |
| 598 | |
| 599 | def test_enrich_source_items_falls_back_to_item_id(monkeypatch): |
| 600 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 601 | captured = {} |
| 602 | |
| 603 | def fake_run(cmd, *, timeout, env=None, on_pid=None): |
| 604 | captured["cluster_id"] = cmd[-1] |
| 605 | return _stdout_for({"results": [_post()]}) |
| 606 | |
| 607 | monkeypatch.setattr(digg.subproc, "run_with_timeout", fake_run) |
| 608 | items = [_FakeSourceItem("digg", "fallbackid", {"postCount": 3}, {"posts": []})] |
| 609 | digg.enrich_source_items(items, top_k=1) |
| 610 | assert captured["cluster_id"] == "fallbackid" |
| 611 | |
| 612 | # === Live tests (opt-in) === |
| 613 | |
| 614 | LIVE = os.environ.get("LAST30DAYS_DIGG_LIVE", "").lower() in ("1", "true", "yes") |
| 615 | HAVE_BIN = shutil.which(digg.CLI_BIN) is not None |
| 616 | |
| 617 | @pytest.mark.skipif(not (LIVE and HAVE_BIN), reason="LAST30DAYS_DIGG_LIVE not set or digg-pp-cli missing") |
| 618 | |
| 619 | |
| 620 | class TestLiveDigg: |
| 621 | def test_search_returns_clusters(self): |
| 622 | out = digg.search_digg("claude code", "2026-04-09", "2026-05-09", depth="quick") |
| 623 | assert "results" in out |
| 624 | assert isinstance(out["results"], list) |
| 625 | # Topic should produce at least 1 cluster in the last 30d. |
| 626 | assert len(out["results"]) >= 1 |
| 627 | sample = out["results"][0] |
| 628 | for key in ("clusterUrlId", "title", "firstPostAge", "postCount"): |
| 629 | assert key in sample |
| 630 | |
| 631 | def test_parse_then_enrich_roundtrip(self): |
| 632 | raw = digg.search_digg("claude code", "2026-04-09", "2026-05-09", depth="quick") |
| 633 | items = digg.parse_digg_response(raw, query="claude code") |
| 634 | assert items, "expected at least one parsed cluster" |
| 635 | digg.enrich_with_top_posts(items, top_k=1, posts_per=2) |
| 636 | # Either the top cluster was successfully enriched, or it was a 0-post |
| 637 | # cluster and posts stayed empty. Both are valid; we just want no crash. |
| 638 | assert isinstance(items[0]["posts"], list) |
| 639 | |
| 640 | def test_off_topic_returns_list(self): |
| 641 | # Digg's live search uses fuzzy/popularity fallback so an impossible |
| 642 | # token may return clusters Digg considers loosely related rather |
| 643 | # than an empty list. The contract we depend on is shape: results |
| 644 | # must always be a list. Token-overlap relevance later in the |
| 645 | # pipeline filters off-topic noise. |
| 646 | out = digg.search_digg("ksdjflksjdflkjsdf-impossible-token", "2026-04-09", "2026-05-09", depth="quick") |
| 647 | assert isinstance(out.get("results"), list) |
| 648 | |
| 649 | def test_missing_cluster_id_graceful(self): |
| 650 | posts = digg.fetch_top_posts("notarealclusterid", posts_per=2) |
| 651 | assert posts == [] |
| 652 | |
| 653 | if __name__ == "__main__": |
| 654 | pytest.main([__file__, "-v"]) |
| 655 | |
| 656 | |
| 657 | # === digg-pp-cli 2026.10.1+ envelopes (local feed copy with meta.stale) === |
| 658 | |
| 659 | |
| 660 | def _feed_envelope(*, source: str, stale: bool, results: list) -> subproc.SubprocResult: |
| 661 | return _stdout_for( |
| 662 | { |
| 663 | "meta": { |
| 664 | "count": len(results), |
| 665 | "query": "openai", |
| 666 | "since": "30d", |
| 667 | "source": source, |
| 668 | "stale": stale, |
| 669 | "topics": ["ai", "tech"], |
| 670 | }, |
| 671 | "results": results, |
| 672 | } |
| 673 | ) |
| 674 | |
| 675 | |
| 676 | def test_search_digg_fresh_local_empty_is_no_matches(monkeypatch): |
| 677 | """A synced store with nothing matching is a real empty answer, not a fallback.""" |
| 678 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 679 | monkeypatch.setattr( |
| 680 | digg.subproc, |
| 681 | "run_with_timeout", |
| 682 | lambda *a, **k: _feed_envelope(source="local", stale=False, results=[]), |
| 683 | ) |
| 684 | out = digg.search_digg("openai", "2026-04-09", "2026-05-09") |
| 685 | assert out["results"] == [] |
| 686 | assert "error" not in out |
| 687 | |
| 688 | |
| 689 | def test_search_digg_stale_result_keeps_items_and_notes_upgrade(monkeypatch): |
| 690 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 691 | monkeypatch.setattr( |
| 692 | digg.subproc, |
| 693 | "run_with_timeout", |
| 694 | lambda *a, **k: _feed_envelope( |
| 695 | source="local+live", stale=True, results=[_cluster()] |
| 696 | ), |
| 697 | ) |
| 698 | out = digg.search_digg("openai", "2026-04-09", "2026-05-09") |
| 699 | assert len(out["results"]) == 1 |
| 700 | assert digg.upgrade_note(out) == digg.UPGRADE_NOTE |
| 701 | assert "sync --topics" not in digg.UPGRADE_NOTE |
| 702 | |
| 703 | |
| 704 | def test_old_cli_search_marks_digg_partial_in_pipeline(monkeypatch): |
| 705 | from lib import health, pipeline, schema |
| 706 | |
| 707 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 708 | monkeypatch.setattr( |
| 709 | digg.subproc, |
| 710 | "run_with_timeout", |
| 711 | lambda *a, **k: _feed_envelope( |
| 712 | source="local+live", stale=True, results=[_cluster()] |
| 713 | ), |
| 714 | ) |
| 715 | subquery = schema.SubQuery( |
| 716 | label="primary", |
| 717 | search_query="openai", |
| 718 | ranking_query="openai", |
| 719 | sources=["digg"], |
| 720 | ) |
| 721 | items, artifact = pipeline._retrieve_stream_impl( |
| 722 | topic="openai", |
| 723 | subquery=subquery, |
| 724 | source="digg", |
| 725 | config={}, |
| 726 | depth="default", |
| 727 | date_range=("2026-04-09", "2026-05-09"), |
| 728 | runtime=None, |
| 729 | mock=False, |
| 730 | ) |
| 731 | assert len(items) == 1 |
| 732 | outcome = artifact["_source_outcome"] |
| 733 | assert outcome["state"] == health.PARTIAL |
| 734 | assert "upgrade" in outcome["detail"] |
| 735 | assert "AI and tech" in outcome["detail"] |
| 736 | |
| 737 | |
| 738 | def test_old_cli_partial_with_no_items_finalizes_as_no_results(): |
| 739 | """An old CLI search that matched nothing keeps its upgrade note and is not an error.""" |
| 740 | from lib import health, pipeline, schema |
| 741 | |
| 742 | outcomes = { |
| 743 | "digg": schema.SourceOutcome( |
| 744 | source="digg", |
| 745 | state=health.PARTIAL, |
| 746 | items_returned=0, |
| 747 | attempted=True, |
| 748 | detail=digg.UPGRADE_NOTE, |
| 749 | ), |
| 750 | "reddit": schema.SourceOutcome( |
| 751 | source="reddit", |
| 752 | state=health.PARTIAL, |
| 753 | items_returned=0, |
| 754 | attempted=True, |
| 755 | detail="HTTP 503 from upstream", |
| 756 | ), |
| 757 | } |
| 758 | final = pipeline._finalize_source_status(outcomes, {}) |
| 759 | assert final["digg"].state == schema.NO_RESULTS |
| 760 | assert final["digg"].detail == digg.UPGRADE_NOTE |
| 761 | assert final["reddit"].state != schema.NO_RESULTS |
| 762 | |
| 763 | |
| 764 | # === digg-pp-cli 2026.10.1 search answer, captured from the real binary === |
| 765 | |
| 766 | _CLI_2026_10_1_ANSWER = { |
| 767 | "meta": { |
| 768 | "count": 3, |
| 769 | "query": "openai", |
| 770 | "since": "30d", |
| 771 | "source": "live", |
| 772 | "stale": True, |
| 773 | "topics": ["ai", "tech"], |
| 774 | }, |
| 775 | "results": [ |
| 776 | { |
| 777 | "clusterId": "6043f14d-1717-4b75-8fb2-3a596fe44df5", |
| 778 | "clusterUrlId": "ljvbajl5", |
| 779 | "firstPostAge": "16d", |
| 780 | "postCount": 127, |
| 781 | "rank": 7, |
| 782 | "title": "OpenAI announces claimed AI proofs in math, computer science and physics", |
| 783 | "tldr": "OpenAI says its claimed refutation of the Exponential Time Hypothesis was formalized in Lean and made public.", |
| 784 | "uniqueAuthors": 96, |
| 785 | }, |
| 786 | { |
| 787 | "clusterId": "4e6ae3f7-6a4a-47c3-803c-0bbd1f6c992b", |
| 788 | "clusterUrlId": "g7fcfxf4", |
| 789 | "firstPostAge": "29d", |
| 790 | "postCount": 147, |
| 791 | "rank": 8, |
| 792 | "title": "Hidden recording device found in OpenAI office; employee fired and charged", |
| 793 | "tldr": "OpenAI says its models helped identify the employee who planted the device; the FBI made an arrest.", |
| 794 | "uniqueAuthors": 101, |
| 795 | }, |
| 796 | { |
| 797 | "clusterId": "2c90283c-21fa-47be-abaa-d93cf0609de9", |
| 798 | "clusterUrlId": "x7hzsqzf", |
| 799 | "firstPostAge": "19d", |
| 800 | "postCount": 29, |
| 801 | "rank": 70, |
| 802 | "title": "OpenAI red-team agents reportedly exchanged synthetic secrets through processor-cache timing", |
| 803 | "tldr": "OpenAI reported hardware side channels; AndrewCurran_ quoted its account of agents passing synthetic secrets between virtual machines.", |
| 804 | "uniqueAuthors": 23, |
| 805 | }, |
| 806 | ], |
| 807 | } |
| 808 | |
| 809 | _CAPTURE_DAY = datetime(2026, 11, 11, 12, 0, tzinfo=timezone.utc) |
| 810 | |
| 811 | |
| 812 | def test_cli_2026_10_1_answer_parses_to_the_same_items(monkeypatch): |
| 813 | monkeypatch.setattr(digg, "_today", lambda: _CAPTURE_DAY) |
| 814 | items = digg.parse_digg_response(_CLI_2026_10_1_ANSWER, query="openai") |
| 815 | assert items == [ |
| 816 | { |
| 817 | "id": "ljvbajl5", |
| 818 | "title": "OpenAI announces claimed AI proofs in math, computer science and physics", |
| 819 | "url": "https://digg.com/ai/ljvbajl5", |
| 820 | "tldr": "OpenAI says its claimed refutation of the Exponential Time Hypothesis was formalized in Lean and made public.", |
| 821 | "author": "", |
| 822 | "date": "2026-10-26", |
| 823 | "engagement": {"postCount": 127, "uniqueAuthors": 96, "rank": 7, "rank_score": 44.0}, |
| 824 | "first_post_age": "16d", |
| 825 | "posts": [], |
| 826 | "relevance": 1.0, |
| 827 | "why_relevant": "Digg cluster (rank 7, 127 posts, 96 authors)", |
| 828 | }, |
| 829 | { |
| 830 | "id": "g7fcfxf4", |
| 831 | "title": "Hidden recording device found in OpenAI office; employee fired and charged", |
| 832 | "url": "https://digg.com/ai/g7fcfxf4", |
| 833 | "tldr": "OpenAI says its models helped identify the employee who planted the device; the FBI made an arrest.", |
| 834 | "author": "", |
| 835 | "date": "2026-10-13", |
| 836 | "engagement": {"postCount": 147, "uniqueAuthors": 101, "rank": 8, "rank_score": 43.0}, |
| 837 | "first_post_age": "29d", |
| 838 | "posts": [], |
| 839 | "relevance": 1.0, |
| 840 | "why_relevant": "Digg cluster (rank 8, 147 posts, 101 authors)", |
| 841 | }, |
| 842 | { |
| 843 | "id": "x7hzsqzf", |
| 844 | "title": "OpenAI red-team agents reportedly exchanged synthetic secrets through processor-cache timing", |
| 845 | "url": "https://digg.com/ai/x7hzsqzf", |
| 846 | "tldr": "OpenAI reported hardware side channels; AndrewCurran_ quoted its account of agents passing synthetic secrets between virtual machines.", |
| 847 | "author": "", |
| 848 | "date": "2026-10-23", |
| 849 | "engagement": {"postCount": 29, "uniqueAuthors": 23, "rank": 70, "rank_score": 0.0}, |
| 850 | "first_post_age": "19d", |
| 851 | "posts": [], |
| 852 | "relevance": 0.88, |
| 853 | "why_relevant": "Digg cluster (rank 70, 29 posts, 23 authors)", |
| 854 | }, |
| 855 | ] |
| 856 | |
| 857 | |
| 858 | def test_cli_2026_10_1_answer_normalizes_to_the_same_source_item(monkeypatch): |
| 859 | from lib import normalize |
| 860 | |
| 861 | monkeypatch.setattr(digg, "_today", lambda: _CAPTURE_DAY) |
| 862 | item = digg.parse_digg_response(_CLI_2026_10_1_ANSWER, query="openai")[0] |
| 863 | source_item = normalize._normalize_digg("digg", item, 0, "2026-10-12", "2026-11-11") |
| 864 | assert source_item.item_id == "ljvbajl5" |
| 865 | assert source_item.url == "https://digg.com/ai/ljvbajl5" |
| 866 | assert source_item.published_at == "2026-10-26" |
| 867 | assert source_item.engagement == { |
| 868 | "postCount": 127, |
| 869 | "uniqueAuthors": 96, |
| 870 | "rank": 7, |
| 871 | "rank_score": 44.0, |
| 872 | } |
| 873 | assert source_item.metadata == { |
| 874 | "clusterUrlId": "ljvbajl5", |
| 875 | "tldr": "OpenAI says its claimed refutation of the Exponential Time Hypothesis was formalized in Lean and made public.", |
| 876 | "rank": 7, |
| 877 | "uniqueAuthors": 96, |
| 878 | "postCount": 127, |
| 879 | "firstPostAge": "16d", |
| 880 | "posts": [], |
| 881 | } |
| 882 | |
| 883 | |
| 884 | def _search_calls(calls: list) -> list: |
| 885 | return [cmd for cmd in calls if "--help" not in cmd] |
| 886 | |
| 887 | |
| 888 | def test_old_cli_gets_the_ai_and_tech_call_unchanged(monkeypatch): |
| 889 | calls: list = [] |
| 890 | |
| 891 | def fake_run(cmd, *, timeout, env=None, on_pid=None): |
| 892 | calls.append(list(cmd)) |
| 893 | return _stdout_for(_CLI_2026_10_1_ANSWER) |
| 894 | |
| 895 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 896 | monkeypatch.setattr(digg.subproc, "run_with_timeout", fake_run) |
| 897 | digg.search_digg("openai", "2026-10-12", "2026-11-11") |
| 898 | assert _search_calls(calls) == [ |
| 899 | [ |
| 900 | "digg-pp-cli", |
| 901 | "search", |
| 902 | "--topic", |
| 903 | "ai,tech", |
| 904 | "--since", |
| 905 | "30d", |
| 906 | "--agent", |
| 907 | "--limit", |
| 908 | "20", |
| 909 | "--", |
| 910 | "openai", |
| 911 | ] |
| 912 | ] |
| 913 | |
| 914 | |
| 915 | # === All-topic search (digg-pp-cli releases whose search lists --sort) === |
| 916 | |
| 917 | _NEW_SEARCH_HELP = ( |
| 918 | "Search Digg stories.\n\nFlags:\n" |
| 919 | " --limit int Max number of results\n" |
| 920 | " --since string Window start\n" |
| 921 | " --sort string relevance, score or newest (default relevance)\n" |
| 922 | " --topic strings Topics to search (default every topic)\n" |
| 923 | " --until string Window end\n" |
| 924 | ) |
| 925 | _OLD_SEARCH_HELP = ( |
| 926 | "Search Digg stories by title and summary.\n\nFlags:\n" |
| 927 | " --limit int Max number of results (default 20)\n" |
| 928 | " --since string Filter to stories that started within this window.\n" |
| 929 | " --topic strings Comma-separated Digg sections to search (default [ai])\n" |
| 930 | ) |
| 931 | |
| 932 | |
| 933 | @pytest.fixture(autouse=True) |
| 934 | def _forget_cli_capability(monkeypatch): |
| 935 | """Each test starts as a fresh run that has not yet read the CLI's help.""" |
| 936 | monkeypatch.setattr(digg, "_all_topic_search", None) |
| 937 | |
| 938 | |
| 939 | def _story( |
| 940 | short_id: str = "k3v9xq2m", |
| 941 | topic: str = "science", |
| 942 | title: str = "Webb telescope spots water on a rocky exoplanet", |
| 943 | published_at: str = "2026-11-08T15:02:00Z", |
| 944 | **overrides, |
| 945 | ): |
| 946 | story = { |
| 947 | "clusterId": f"11111111-2222-3333-4444-{short_id:0>12}", |
| 948 | "clusterUrlId": short_id, |
| 949 | "url": f"https://digg.com/{topic}/{short_id}", |
| 950 | "topic": topic, |
| 951 | "title": title, |
| 952 | "description": "Longer description of the story.", |
| 953 | "tldr": "Astronomers report water vapor in the planet's atmosphere.", |
| 954 | "diggScore": 412, |
| 955 | "sourceCount": 37, |
| 956 | "postCount": 37, |
| 957 | "uniqueAuthors": 29, |
| 958 | "publishedAt": published_at, |
| 959 | "firstSourceAt": "2026-11-08T13:48:00Z", |
| 960 | "firstPostAge": "3d", |
| 961 | } |
| 962 | story.update(overrides) |
| 963 | return story |
| 964 | |
| 965 | |
| 966 | def _live_envelope(*stories: dict) -> dict: |
| 967 | return { |
| 968 | "meta": { |
| 969 | "count": len(stories), |
| 970 | "query": "exoplanet", |
| 971 | "source": "live", |
| 972 | "stale": False, |
| 973 | "totalMatches": len(stories), |
| 974 | "window": {"since": "2026-10-12", "until": "2026-11-11"}, |
| 975 | "sort": "relevance", |
| 976 | }, |
| 977 | "results": list(stories), |
| 978 | } |
| 979 | |
| 980 | |
| 981 | def _fake_cli(help_text: str, answer: dict, calls: list): |
| 982 | def fake_run(cmd, *, timeout, **_bounds): |
| 983 | calls.append(list(cmd)) |
| 984 | if "--help" in cmd: |
| 985 | return subproc.SubprocResult(returncode=0, stdout=help_text, stderr="") |
| 986 | return _stdout_for(answer) |
| 987 | |
| 988 | return fake_run |
| 989 | |
| 990 | |
| 991 | def test_story_keeps_its_own_url_score_counts_and_publish_date(): |
| 992 | items = digg.parse_digg_response( |
| 993 | _live_envelope(_story()), query="exoplanet", from_date="2026-10-12" |
| 994 | ) |
| 995 | assert len(items) == 1 |
| 996 | item = items[0] |
| 997 | assert item["id"] == "k3v9xq2m" |
| 998 | assert item["url"] == "https://digg.com/science/k3v9xq2m" |
| 999 | assert item["date"] == "2026-11-08" |
| 1000 | assert item["engagement"] == {"postCount": 37, "uniqueAuthors": 29, "digg_score": 412} |
| 1001 | |
| 1002 | |
| 1003 | def test_story_reason_names_its_score_and_counts(): |
| 1004 | items = digg.parse_digg_response(_live_envelope(_story()), from_date="2026-10-12") |
| 1005 | assert items[0]["why_relevant"] == "Digg cluster (Digg Score 412, 37 posts, 29 authors)" |
| 1006 | |
| 1007 | |
| 1008 | def test_story_post_count_is_the_source_count(): |
| 1009 | items = digg.parse_digg_response( |
| 1010 | _live_envelope(_story(sourceCount=52, postCount=37)), from_date="2026-10-12" |
| 1011 | ) |
| 1012 | assert items[0]["engagement"]["postCount"] == 52 |
| 1013 | |
| 1014 | |
| 1015 | def test_sports_story_links_to_the_sports_section(): |
| 1016 | items = digg.parse_digg_response( |
| 1017 | _live_envelope(_story(short_id="w8n2jd4c", topic="sports", title="Cup final goes to penalties")), |
| 1018 | from_date="2026-10-12", |
| 1019 | ) |
| 1020 | assert items[0]["url"] == "https://digg.com/sports/w8n2jd4c" |
| 1021 | assert "/ai/" not in items[0]["url"] |
| 1022 | |
| 1023 | |
| 1024 | def test_story_without_a_score_keeps_counts_and_has_no_score(): |
| 1025 | story = _story() |
| 1026 | del story["diggScore"] |
| 1027 | del story["firstSourceAt"] |
| 1028 | items = digg.parse_digg_response(_live_envelope(story), from_date="2026-10-12") |
| 1029 | assert items[0]["engagement"] == {"postCount": 37, "uniqueAuthors": 29} |
| 1030 | |
| 1031 | |
| 1032 | def test_story_published_40_days_ago_is_dropped_from_a_30_day_run(monkeypatch): |
| 1033 | monkeypatch.setattr(digg, "_today", lambda: _CAPTURE_DAY) |
| 1034 | envelope = _live_envelope( |
| 1035 | _story(short_id="recent01", published_at="2026-11-08T15:02:00Z"), |
| 1036 | _story(short_id="old00001", published_at="2026-10-02T09:00:00Z", firstPostAge="5w"), |
| 1037 | ) |
| 1038 | with_window = digg.parse_digg_response(envelope, from_date="2026-10-12") |
| 1039 | assert [i["id"] for i in with_window] == ["recent01"] |
| 1040 | default_window = digg.parse_digg_response(envelope) |
| 1041 | assert [i["id"] for i in default_window] == ["recent01"] |
| 1042 | |
| 1043 | |
| 1044 | def test_story_with_a_non_web_url_is_dropped(): |
| 1045 | envelope = _live_envelope( |
| 1046 | _story(short_id="bad00001", url="javascript:alert(1)"), |
| 1047 | _story(short_id="good0001"), |
| 1048 | ) |
| 1049 | items = digg.parse_digg_response(envelope, from_date="2026-10-12") |
| 1050 | assert [i["id"] for i in items] == ["good0001"] |
| 1051 | |
| 1052 | |
| 1053 | def test_story_metadata_carries_uuid_topic_and_canonical_url(): |
| 1054 | from lib import normalize |
| 1055 | |
| 1056 | item = digg.parse_digg_response( |
| 1057 | _live_envelope(_story()), query="exoplanet", from_date="2026-10-12" |
| 1058 | )[0] |
| 1059 | source_item = normalize._normalize_digg("digg", item, 0, "2026-10-12", "2026-11-11") |
| 1060 | assert source_item.url == "https://digg.com/science/k3v9xq2m" |
| 1061 | assert source_item.published_at == "2026-11-08" |
| 1062 | assert source_item.engagement == {"postCount": 37, "uniqueAuthors": 29, "digg_score": 412} |
| 1063 | assert source_item.metadata["clusterId"] == "11111111-2222-3333-4444-0000k3v9xq2m" |
| 1064 | assert source_item.metadata["clusterUrlId"] == "k3v9xq2m" |
| 1065 | assert source_item.metadata["topic"] == "science" |
| 1066 | assert source_item.metadata["url"] == "https://digg.com/science/k3v9xq2m" |
| 1067 | |
| 1068 | |
| 1069 | def test_new_cli_search_names_no_topic_and_no_sort(monkeypatch): |
| 1070 | calls: list = [] |
| 1071 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 1072 | monkeypatch.setattr( |
| 1073 | digg.subproc, |
| 1074 | "run_with_timeout", |
| 1075 | _fake_cli(_NEW_SEARCH_HELP, _live_envelope(_story()), calls), |
| 1076 | ) |
| 1077 | out = digg.search_digg("exoplanet", "2026-10-12", "2026-11-11") |
| 1078 | assert _search_calls(calls) == [ |
| 1079 | ["digg-pp-cli", "search", "--since", "30d", "--agent", "--limit", "20", "--", "exoplanet"] |
| 1080 | ] |
| 1081 | assert len(out["results"]) == 1 |
| 1082 | assert digg.upgrade_note(out) is None |
| 1083 | |
| 1084 | |
| 1085 | def test_deep_search_asks_for_50_stories(monkeypatch): |
| 1086 | calls: list = [] |
| 1087 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 1088 | monkeypatch.setattr( |
| 1089 | digg.subproc, |
| 1090 | "run_with_timeout", |
| 1091 | _fake_cli(_NEW_SEARCH_HELP, _live_envelope(), calls), |
| 1092 | ) |
| 1093 | digg.search_digg("exoplanet", "2026-10-12", "2026-11-11", depth="deep") |
| 1094 | search = _search_calls(calls)[0] |
| 1095 | assert search[search.index("--limit") + 1] == "50" |
| 1096 | |
| 1097 | |
| 1098 | def test_search_help_is_read_once_per_run(monkeypatch): |
| 1099 | calls: list = [] |
| 1100 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 1101 | monkeypatch.setattr( |
| 1102 | digg.subproc, |
| 1103 | "run_with_timeout", |
| 1104 | _fake_cli(_OLD_SEARCH_HELP, _CLI_2026_10_1_ANSWER, calls), |
| 1105 | ) |
| 1106 | digg.search_digg("openai", "2026-10-12", "2026-11-11") |
| 1107 | digg.search_digg("anthropic", "2026-10-12", "2026-11-11") |
| 1108 | help_calls = [cmd for cmd in calls if "--help" in cmd] |
| 1109 | assert help_calls == [["digg-pp-cli", "search", "--help"]] |
| 1110 | assert [cmd[-1] for cmd in _search_calls(calls)] == ["openai", "anthropic"] |
| 1111 | assert all("--topic" in cmd for cmd in _search_calls(calls)) |
| 1112 | |
| 1113 | |
| 1114 | def test_old_cli_answer_yields_the_same_items_plus_the_upgrade_note(monkeypatch): |
| 1115 | calls: list = [] |
| 1116 | monkeypatch.setattr(digg, "_today", lambda: _CAPTURE_DAY) |
| 1117 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 1118 | monkeypatch.setattr( |
| 1119 | digg.subproc, |
| 1120 | "run_with_timeout", |
| 1121 | _fake_cli(_OLD_SEARCH_HELP, _CLI_2026_10_1_ANSWER, calls), |
| 1122 | ) |
| 1123 | out = digg.search_digg("openai", "2026-10-12", "2026-11-11") |
| 1124 | items = digg.parse_digg_response(out, query="openai", from_date="2026-10-12") |
| 1125 | assert items == digg.parse_digg_response(_CLI_2026_10_1_ANSWER, query="openai") |
| 1126 | assert [i["url"] for i in items] == [ |
| 1127 | "https://digg.com/ai/ljvbajl5", |
| 1128 | "https://digg.com/ai/g7fcfxf4", |
| 1129 | "https://digg.com/ai/x7hzsqzf", |
| 1130 | ] |
| 1131 | note = digg.upgrade_note(out) |
| 1132 | assert note is not None |
| 1133 | assert "upgrade" in note |
| 1134 | assert len(note) < 140 |
| 1135 | |
| 1136 | |
| 1137 | def test_upgrade_note_absent_for_failed_and_unmarked_answers(monkeypatch): |
| 1138 | assert digg.upgrade_note({"results": []}) is None |
| 1139 | assert digg.upgrade_note(_CLI_2026_10_1_ANSWER) is None |
| 1140 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 1141 | monkeypatch.setattr( |
| 1142 | digg.subproc, |
| 1143 | "run_with_timeout", |
| 1144 | lambda *a, **k: subproc.SubprocResult(returncode=2, stdout="", stderr="boom"), |
| 1145 | ) |
| 1146 | out = digg.search_digg("openai", "2026-10-12", "2026-11-11") |
| 1147 | assert out["error"] == "boom" |
| 1148 | assert digg.upgrade_note(out) is None |
| 1149 | |
| 1150 | |
| 1151 | def test_new_cli_stories_reach_the_pipeline_without_a_partial_note(monkeypatch): |
| 1152 | from lib import pipeline, schema |
| 1153 | |
| 1154 | monkeypatch.setattr(digg, "_today", lambda: _CAPTURE_DAY) |
| 1155 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 1156 | monkeypatch.setattr( |
| 1157 | digg.subproc, |
| 1158 | "run_with_timeout", |
| 1159 | _fake_cli( |
| 1160 | _NEW_SEARCH_HELP, |
| 1161 | _live_envelope( |
| 1162 | _story(short_id="recent01"), |
| 1163 | _story(short_id="old00001", published_at="2026-10-02T09:00:00Z"), |
| 1164 | ), |
| 1165 | [], |
| 1166 | ), |
| 1167 | ) |
| 1168 | subquery = schema.SubQuery( |
| 1169 | label="primary", |
| 1170 | search_query="exoplanet", |
| 1171 | ranking_query="exoplanet", |
| 1172 | sources=["digg"], |
| 1173 | ) |
| 1174 | items, artifact = pipeline._retrieve_stream_impl( |
| 1175 | topic="exoplanet", |
| 1176 | subquery=subquery, |
| 1177 | source="digg", |
| 1178 | config={}, |
| 1179 | depth="default", |
| 1180 | date_range=("2026-10-12", "2026-11-11"), |
| 1181 | runtime=None, |
| 1182 | mock=False, |
| 1183 | ) |
| 1184 | assert [item["id"] for item in items] == ["recent01"] |
| 1185 | assert items[0]["url"] == "https://digg.com/science/recent01" |
| 1186 | assert "_source_outcome" not in artifact |
| 1187 | |
| 1188 | |
| 1189 | # === Story sources and confirmation of matching items === |
| 1190 | |
| 1191 | |
| 1192 | def _source_row( |
| 1193 | kind: str = "x", |
| 1194 | url: str = "https://x.com/astro_ana/status/1986000000000000001", |
| 1195 | username: str = "astro_ana", |
| 1196 | body: str = "Water vapor on a rocky world. Big if it holds up.", |
| 1197 | ): |
| 1198 | author = {"display_name": username.title() if username else "Example Newsroom"} |
| 1199 | if kind == "x": |
| 1200 | author["username"] = username |
| 1201 | return { |
| 1202 | "kind": kind, |
| 1203 | "body": body, |
| 1204 | "xUrl": url, |
| 1205 | "title": "" if kind == "x" else "Webb finds water on a rocky exoplanet", |
| 1206 | "posted_at": "2026-11-08T14:00:00Z", |
| 1207 | "post_x_id": url.rsplit("/", 1)[-1] if kind == "x" else "", |
| 1208 | "author": author, |
| 1209 | } |
| 1210 | |
| 1211 | |
| 1212 | def _sources_answer(*rows: dict) -> dict: |
| 1213 | return {"meta": {"topic": "science"}, "results": list(rows)} |
| 1214 | |
| 1215 | |
| 1216 | def _story_item(short_id: str = "k3v9xq2m", digg_score: float = 412, engagement_score=80, **story): |
| 1217 | from lib import normalize |
| 1218 | |
| 1219 | [parsed] = digg.parse_digg_response( |
| 1220 | _live_envelope(_story(short_id=short_id, diggScore=digg_score, **story)), |
| 1221 | query="exoplanet", |
| 1222 | from_date="2026-10-12", |
| 1223 | ) |
| 1224 | [item] = normalize.normalize_source_items("digg", [parsed], "2026-10-12", "2026-11-11") |
| 1225 | item.engagement_score = engagement_score |
| 1226 | return item |
| 1227 | |
| 1228 | |
| 1229 | def _other_item(source: str, url: str, **metadata): |
| 1230 | from lib import schema |
| 1231 | |
| 1232 | return schema.SourceItem( |
| 1233 | item_id=f"{source}-1", source=source, title="A post", body="A post", url=url, |
| 1234 | published_at="2026-11-09", metadata=dict(metadata), |
| 1235 | ) |
| 1236 | |
| 1237 | |
| 1238 | def _candidate_for(*items): |
| 1239 | from lib import schema |
| 1240 | |
| 1241 | first = items[0] |
| 1242 | return schema.Candidate( |
| 1243 | candidate_id=first.url, item_id=first.item_id, source=first.source, |
| 1244 | title=first.title, url=first.url, snippet="", subquery_labels=["primary"], |
| 1245 | native_ranks={f"primary:{first.source}": 1}, local_relevance=0.6, freshness=70, |
| 1246 | engagement=30, source_quality=0.7, rrf_score=0.02, source_items=list(items), |
| 1247 | ) |
| 1248 | |
| 1249 | |
| 1250 | def _sources_cli(answers: dict, calls: list): |
| 1251 | """A CLI whose ``posts ... -- <uuid>`` answers come from ``answers`` by UUID.""" |
| 1252 | |
| 1253 | def fake_run(cmd, *, timeout, env=None, on_pid=None): |
| 1254 | calls.append(list(cmd)) |
| 1255 | return _stdout_for(answers.get(cmd[-1], _sources_answer())) |
| 1256 | |
| 1257 | return fake_run |
| 1258 | |
| 1259 | |
| 1260 | def _confirm(story, rows, *others, depth: str = "default", monkeypatch): |
| 1261 | """Fetch ``story``'s sources from a fake CLI and tag ``others``.""" |
| 1262 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 1263 | monkeypatch.setattr( |
| 1264 | digg.subproc, |
| 1265 | "run_with_timeout", |
| 1266 | _sources_cli({story.metadata["clusterId"]: _sources_answer(*rows)}, []), |
| 1267 | ) |
| 1268 | fetched = digg.fetch_story_sources([story], depth) |
| 1269 | stories = digg.apply_story_sources([story], fetched) |
| 1270 | candidates = [_candidate_for(item) for item in others] |
| 1271 | digg.tag_confirmed_candidates(candidates, stories) |
| 1272 | return candidates |
| 1273 | |
| 1274 | |
| 1275 | @pytest.mark.parametrize("item_url", [ |
| 1276 | "https://twitter.com/astro_ana/status/1986000000000000001", |
| 1277 | "https://x.com/Astro_Ana/status/1986000000000000001", |
| 1278 | "https://x.com/astro_ana/status/1986000000000000001?s=20&t=abcDEF", |
| 1279 | "https://x.com/i/status/1986000000000000001", |
| 1280 | ]) |
| 1281 | def test_x_item_with_a_story_sources_status_id_is_tagged(monkeypatch, item_url): |
| 1282 | story = _story_item() |
| 1283 | [candidate] = _confirm( |
| 1284 | story, [_source_row()], _other_item("x", item_url), monkeypatch=monkeypatch, |
| 1285 | ) |
| 1286 | assert candidate.metadata["digg_story"] == { |
| 1287 | "title": "Webb telescope spots water on a rocky exoplanet", |
| 1288 | "url": "https://digg.com/science/k3v9xq2m", |
| 1289 | "digg_score": 412, |
| 1290 | "source_count": 37, |
| 1291 | "engagement": 80, |
| 1292 | } |
| 1293 | |
| 1294 | |
| 1295 | def test_x_item_with_another_status_id_is_not_tagged(monkeypatch): |
| 1296 | [candidate] = _confirm( |
| 1297 | _story_item(), [_source_row()], |
| 1298 | _other_item("x", "https://x.com/astro_ana/status/1986000000000000002"), |
| 1299 | monkeypatch=monkeypatch, |
| 1300 | ) |
| 1301 | assert "digg_story" not in candidate.metadata |
| 1302 | |
| 1303 | |
| 1304 | def test_hacker_news_item_linking_a_story_source_article_is_tagged(monkeypatch): |
| 1305 | article = "https://www.example-observatory.org/news/webb-water/?utm_source=digg" |
| 1306 | [candidate] = _confirm( |
| 1307 | _story_item(), |
| 1308 | [_source_row(kind="webpage", url=article, username="")], |
| 1309 | _other_item( |
| 1310 | "hackernews", "https://example-observatory.org/news/webb-water", |
| 1311 | hn_url="https://news.ycombinator.com/item?id=45900001", |
| 1312 | ), |
| 1313 | monkeypatch=monkeypatch, |
| 1314 | ) |
| 1315 | assert candidate.metadata["digg_story"]["url"] == "https://digg.com/science/k3v9xq2m" |
| 1316 | |
| 1317 | |
| 1318 | def test_reddit_text_post_about_the_same_event_is_not_tagged(monkeypatch): |
| 1319 | [candidate] = _confirm( |
| 1320 | _story_item(), |
| 1321 | [_source_row(kind="webpage", url="https://example-observatory.org/news/webb-water", username="")], |
| 1322 | _other_item("reddit", "https://www.reddit.com/r/space/comments/1abcde/webb_finds_water/"), |
| 1323 | monkeypatch=monkeypatch, |
| 1324 | ) |
| 1325 | assert "digg_story" not in candidate.metadata |
| 1326 | |
| 1327 | |
| 1328 | def test_item_sharing_only_a_domain_with_a_source_is_not_tagged(monkeypatch): |
| 1329 | [candidate] = _confirm( |
| 1330 | _story_item(), |
| 1331 | [_source_row(kind="webpage", url="https://example-observatory.org/news/webb-water", username="")], |
| 1332 | _other_item("hackernews", "https://example-observatory.org/news/another-story"), |
| 1333 | monkeypatch=monkeypatch, |
| 1334 | ) |
| 1335 | assert "digg_story" not in candidate.metadata |
| 1336 | |
| 1337 | |
| 1338 | def test_the_digg_story_itself_is_not_tagged(monkeypatch): |
| 1339 | story = _story_item() |
| 1340 | [candidate] = _confirm( |
| 1341 | story, [_source_row(kind="webpage", url=story.url, username="")], story, |
| 1342 | monkeypatch=monkeypatch, |
| 1343 | ) |
| 1344 | assert "digg_story" not in candidate.metadata |
| 1345 | |
| 1346 | |
| 1347 | def test_story_with_40_sources_tags_the_30th_and_keeps_5_quotes(monkeypatch): |
| 1348 | rows = [ |
| 1349 | _source_row( |
| 1350 | url=f"https://x.com/voice{n}/status/19860000000000001{n:02d}", |
| 1351 | username=f"voice{n}", body=f"Take number {n}.", |
| 1352 | ) |
| 1353 | for n in range(1, 41) |
| 1354 | ] |
| 1355 | story = _story_item() |
| 1356 | [candidate] = _confirm( |
| 1357 | story, rows, _other_item("x", "https://x.com/voice30/status/1986000000000000130"), |
| 1358 | monkeypatch=monkeypatch, |
| 1359 | ) |
| 1360 | assert "digg_story" in candidate.metadata |
| 1361 | assert [post["username"] for post in story.metadata["posts"]] == [ |
| 1362 | "voice1", "voice2", "voice3", "voice4", "voice5", |
| 1363 | ] |
| 1364 | |
| 1365 | |
| 1366 | def test_item_in_two_stories_is_tagged_with_the_more_engaged_one(monkeypatch): |
| 1367 | shared = _source_row() |
| 1368 | small = _story_item(short_id="small001", digg_score=40, engagement_score=35, title="Small story") |
| 1369 | big = _story_item(short_id="big00001", digg_score=900, engagement_score=95, title="Big story") |
| 1370 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 1371 | monkeypatch.setattr( |
| 1372 | digg.subproc, "run_with_timeout", |
| 1373 | _sources_cli({ |
| 1374 | small.metadata["clusterId"]: _sources_answer(shared), |
| 1375 | big.metadata["clusterId"]: _sources_answer(shared), |
| 1376 | }, []), |
| 1377 | ) |
| 1378 | stories = digg.apply_story_sources( |
| 1379 | [small, big], digg.fetch_story_sources([small, big], "default"), |
| 1380 | ) |
| 1381 | candidate = _candidate_for(_other_item("x", shared["xUrl"])) |
| 1382 | digg.tag_confirmed_candidates([candidate], stories) |
| 1383 | assert candidate.metadata["digg_story"]["title"] == "Big story" |
| 1384 | |
| 1385 | |
| 1386 | def test_story_rejected_after_retrieval_no_longer_confirms_other_items(monkeypatch): |
| 1387 | shared = _source_row() |
| 1388 | kept = _story_item(short_id="kept0001", digg_score=40, engagement_score=35, title="Kept story") |
| 1389 | rejected = _story_item( |
| 1390 | short_id="reject01", digg_score=900, engagement_score=95, title="Rejected story", |
| 1391 | ) |
| 1392 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 1393 | monkeypatch.setattr( |
| 1394 | digg.subproc, "run_with_timeout", |
| 1395 | _sources_cli({ |
| 1396 | kept.metadata["clusterId"]: _sources_answer(_source_row( |
| 1397 | url="https://x.com/other/status/1986000000000000777", |
| 1398 | )), |
| 1399 | rejected.metadata["clusterId"]: _sources_answer(shared), |
| 1400 | }, []), |
| 1401 | ) |
| 1402 | stories = digg.apply_story_sources( |
| 1403 | [kept, rejected], digg.fetch_story_sources([kept, rejected], "default"), |
| 1404 | ) |
| 1405 | surviving = digg.surviving_stories(stories, [kept, _other_item("x", shared["xUrl"])]) |
| 1406 | |
| 1407 | assert [[story["title"] for story in citing] for citing in surviving.values()] == [ |
| 1408 | ["Kept story"], |
| 1409 | ] |
| 1410 | candidate = _candidate_for(_other_item("x", shared["xUrl"])) |
| 1411 | assert digg.tag_confirmed_candidates([candidate], surviving) == 0 |
| 1412 | assert "digg_story" not in candidate.metadata |
| 1413 | |
| 1414 | |
| 1415 | def test_shared_source_falls_back_to_the_surviving_story_when_the_top_one_is_rejected( |
| 1416 | monkeypatch, |
| 1417 | ): |
| 1418 | shared = _source_row() |
| 1419 | small = _story_item(short_id="small001", digg_score=40, engagement_score=35, title="Small story") |
| 1420 | big = _story_item(short_id="big00001", digg_score=900, engagement_score=95, title="Big story") |
| 1421 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 1422 | monkeypatch.setattr( |
| 1423 | digg.subproc, "run_with_timeout", |
| 1424 | _sources_cli({ |
| 1425 | small.metadata["clusterId"]: _sources_answer(shared), |
| 1426 | big.metadata["clusterId"]: _sources_answer(shared), |
| 1427 | }, []), |
| 1428 | ) |
| 1429 | stories = digg.apply_story_sources( |
| 1430 | [small, big], digg.fetch_story_sources([small, big], "default"), |
| 1431 | ) |
| 1432 | candidate = _candidate_for(_other_item("x", shared["xUrl"])) |
| 1433 | |
| 1434 | digg.tag_confirmed_candidates([candidate], digg.surviving_stories(stories, [small])) |
| 1435 | |
| 1436 | assert candidate.metadata["digg_story"]["title"] == "Small story" |
| 1437 | |
| 1438 | |
| 1439 | def test_merged_passes_keep_every_citing_story_highest_digg_score_first(): |
| 1440 | first = {"k": [{"url": "u1", "digg_score": 226, "engagement": 100}]} |
| 1441 | digg.merge_stories(first, { |
| 1442 | "k": [ |
| 1443 | {"url": "u2", "digg_score": 1286, "engagement": 100}, |
| 1444 | {"url": "u1", "digg_score": 226, "engagement": 100}, |
| 1445 | {"url": "u0", "digg_score": 226, "engagement": 100}, |
| 1446 | ], |
| 1447 | "other": [{"url": "u3", "engagement": 10}], |
| 1448 | }) |
| 1449 | assert [story["url"] for story in first["k"]] == ["u2", "u0", "u1"] |
| 1450 | assert [story["url"] for story in first["other"]] == ["u3"] |
| 1451 | |
| 1452 | |
| 1453 | def test_shared_source_names_the_story_with_the_higher_digg_score(monkeypatch): |
| 1454 | # Both stories read 100 on the 0 to 100 engagement scale. |
| 1455 | shared = _source_row() |
| 1456 | lower = _story_item(short_id="lower001", digg_score=226, engagement_score=100, title="226 story") |
| 1457 | higher = _story_item(short_id="higher01", digg_score=1286, engagement_score=100, title="1286 story") |
| 1458 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 1459 | monkeypatch.setattr( |
| 1460 | digg.subproc, "run_with_timeout", |
| 1461 | _sources_cli({ |
| 1462 | lower.metadata["clusterId"]: _sources_answer(shared), |
| 1463 | higher.metadata["clusterId"]: _sources_answer(shared), |
| 1464 | }, []), |
| 1465 | ) |
| 1466 | stories = digg.apply_story_sources( |
| 1467 | [lower, higher], digg.fetch_story_sources([lower, higher], "default"), |
| 1468 | ) |
| 1469 | candidate = _candidate_for(_other_item("x", shared["xUrl"])) |
| 1470 | digg.tag_confirmed_candidates([candidate], stories) |
| 1471 | assert candidate.metadata["digg_story"]["title"] == "1286 story" |
| 1472 | |
| 1473 | |
| 1474 | def test_item_citing_two_sources_names_the_story_with_the_higher_digg_score(): |
| 1475 | lower = {"title": "226 story", "url": "u1", "digg_score": 226, "engagement": 100} |
| 1476 | higher = {"title": "1286 story", "url": "u2", "digg_score": 1286, "engagement": 100} |
| 1477 | first = _other_item("x", "https://x.com/a/status/1986000000000000001") |
| 1478 | second = _other_item("hackernews", "https://example.org/news/water") |
| 1479 | candidate = _candidate_for(first, second) |
| 1480 | digg.tag_confirmed_candidates([candidate], { |
| 1481 | digg.match_key(first.url): [lower], |
| 1482 | digg.match_key(second.url): [higher], |
| 1483 | }) |
| 1484 | assert candidate.metadata["digg_story"]["title"] == "1286 story" |
| 1485 | |
| 1486 | |
| 1487 | @pytest.mark.parametrize("topic, sent", [ |
| 1488 | ("AI", "AI AI"), |
| 1489 | ("Go", "Go Go"), |
| 1490 | ("X", "X X"), |
| 1491 | (" AI ", "AI AI"), |
| 1492 | ("C++", "C++"), |
| 1493 | ("a" * 120, "a" * 120), |
| 1494 | ("a" * 121, "a" * 120), |
| 1495 | ("word " * 30, ("word " * 24).strip()), |
| 1496 | ("x" * 118 + " yz", "x" * 118), |
| 1497 | ("AI " + "u" * 130, "AI AI"), |
| 1498 | ("A " + "u" * 130, "A A"), |
| 1499 | ]) |
| 1500 | def test_all_topic_query_is_fitted_to_the_length_the_cli_accepts(topic, sent): |
| 1501 | args = digg._build_search_args(topic, 10, all_topics=True) |
| 1502 | assert args[-2:] == ["--", sent] |
| 1503 | assert digg.QUERY_MIN_CHARS <= len(args[-1]) <= digg.QUERY_MAX_CHARS |
| 1504 | |
| 1505 | |
| 1506 | def test_older_cli_query_is_sent_as_given(): |
| 1507 | assert digg._build_search_args("AI", 10, all_topics=False)[-2:] == ["--", "AI"] |
| 1508 | assert digg._build_search_args("a" * 200, 10, all_topics=False)[-2:] == ["--", "a" * 200] |
| 1509 | |
| 1510 | |
| 1511 | def _five_stories(): |
| 1512 | scores = {"s1": 150, "s2": 1286, "s3": 239, "s4": 473, "s5": 180} |
| 1513 | return [_story_item(short_id=short_id, digg_score=score) for short_id, score in scores.items()] |
| 1514 | |
| 1515 | |
| 1516 | def _stories(count: int) -> list: |
| 1517 | """``count`` stories s01, s02, ... with distinct scores in no special order.""" |
| 1518 | return [ |
| 1519 | _story_item(short_id=f"s{n:02d}", digg_score=100 + (n * 37) % 101) |
| 1520 | for n in range(1, count + 1) |
| 1521 | ] |
| 1522 | |
| 1523 | |
| 1524 | def _by_score(stories: list) -> list: |
| 1525 | """Story UUIDs, highest Digg Score first, then by UUID.""" |
| 1526 | return [ |
| 1527 | item.metadata["clusterId"] |
| 1528 | for item in sorted( |
| 1529 | stories, |
| 1530 | key=lambda item: (-item.engagement["digg_score"], item.metadata["clusterId"]), |
| 1531 | ) |
| 1532 | ] |
| 1533 | |
| 1534 | |
| 1535 | def test_default_depth_fetches_the_8_top_scored_stories_four_at_a_time(monkeypatch): |
| 1536 | import threading |
| 1537 | |
| 1538 | calls: list = [] |
| 1539 | lock = threading.Lock() |
| 1540 | running = {"now": 0, "most": 0} |
| 1541 | four_running = threading.Event() |
| 1542 | inner = _sources_cli({}, calls) |
| 1543 | |
| 1544 | def fake_run(cmd, *, timeout, env=None, on_pid=None): |
| 1545 | with lock: |
| 1546 | running["now"] += 1 |
| 1547 | running["most"] = max(running["most"], running["now"]) |
| 1548 | fourth = running["now"] == 4 and not four_running.is_set() |
| 1549 | try: |
| 1550 | assert timeout <= 15 |
| 1551 | if fourth: |
| 1552 | # Leave room for a fifth call to show up before any ends. |
| 1553 | threading.Event().wait(0.05) |
| 1554 | four_running.set() |
| 1555 | four_running.wait(0.5) |
| 1556 | return inner(cmd, timeout=timeout) |
| 1557 | finally: |
| 1558 | with lock: |
| 1559 | running["now"] -= 1 |
| 1560 | |
| 1561 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 1562 | monkeypatch.setattr(digg.subproc, "run_with_timeout", fake_run) |
| 1563 | stories = _stories(10) |
| 1564 | digg.fetch_story_sources(stories, "default") |
| 1565 | assert sorted(calls) == sorted( |
| 1566 | ["digg-pp-cli", "posts", "--agent", "--limit", "40", "--", uuid] |
| 1567 | for uuid in _by_score(stories)[:8] |
| 1568 | ) |
| 1569 | assert running["most"] == 4 |
| 1570 | |
| 1571 | |
| 1572 | def test_fetched_sources_come_back_by_score_then_id_whatever_finishes_first(monkeypatch): |
| 1573 | import threading |
| 1574 | |
| 1575 | stories = [ |
| 1576 | _story_item(short_id="tie-b", digg_score=300), |
| 1577 | _story_item(short_id="low", digg_score=120), |
| 1578 | _story_item(short_id="top", digg_score=900), |
| 1579 | _story_item(short_id="tie-a", digg_score=300), |
| 1580 | ] |
| 1581 | order = _by_score(stories) |
| 1582 | lock = threading.Lock() |
| 1583 | finished: list = [] |
| 1584 | others_done = threading.Event() |
| 1585 | |
| 1586 | def fake_run(cmd, *, timeout, env=None, on_pid=None): |
| 1587 | # The top story's call ends last, the lowest one's first. |
| 1588 | if cmd[-1] == order[0]: |
| 1589 | others_done.wait(1) |
| 1590 | with lock: |
| 1591 | finished.append(cmd[-1]) |
| 1592 | if len(finished) == len(order) - 1: |
| 1593 | others_done.set() |
| 1594 | return _stdout_for(_sources_answer(_source_row())) |
| 1595 | |
| 1596 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 1597 | monkeypatch.setattr(digg.subproc, "run_with_timeout", fake_run) |
| 1598 | fetched = digg.fetch_story_sources(stories, "default") |
| 1599 | assert finished[-1] == order[0] |
| 1600 | assert list(fetched) == order |
| 1601 | assert [uuid[-5:] for uuid in order] == ["00top", "tie-a", "tie-b", "00low"] |
| 1602 | |
| 1603 | |
| 1604 | def test_deep_depth_fetches_12_stories_and_quick_fetches_none(monkeypatch): |
| 1605 | calls: list = [] |
| 1606 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 1607 | monkeypatch.setattr(digg.subproc, "run_with_timeout", _sources_cli({}, calls)) |
| 1608 | assert digg.fetch_story_sources(_stories(15), "quick") == {} |
| 1609 | assert calls == [] |
| 1610 | digg.fetch_story_sources(_stories(15), "deep") |
| 1611 | assert len(calls) == 12 |
| 1612 | |
| 1613 | |
| 1614 | def test_story_found_by_two_searches_is_fetched_once_and_both_copies_get_quotes(monkeypatch): |
| 1615 | calls: list = [] |
| 1616 | first, second = _story_item(), _story_item() |
| 1617 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 1618 | monkeypatch.setattr( |
| 1619 | digg.subproc, "run_with_timeout", |
| 1620 | _sources_cli({first.metadata["clusterId"]: _sources_answer(_source_row())}, calls), |
| 1621 | ) |
| 1622 | fetched = digg.fetch_story_sources([first, second], "default") |
| 1623 | digg.apply_story_sources([first, second], fetched) |
| 1624 | assert len(calls) == 1 |
| 1625 | assert first.metadata["posts"][0]["username"] == "astro_ana" |
| 1626 | assert second.metadata["posts"][0]["username"] == "astro_ana" |
| 1627 | |
| 1628 | |
| 1629 | def test_sources_fetch_stops_when_the_run_is_out_of_time(monkeypatch): |
| 1630 | import threading |
| 1631 | |
| 1632 | calls: list = [] |
| 1633 | out_of_time = threading.Event() |
| 1634 | # The first four calls meet, and the run is out of time before any ends. |
| 1635 | four_running = threading.Barrier(4, action=out_of_time.set, timeout=1) |
| 1636 | inner = _sources_cli({}, calls) |
| 1637 | |
| 1638 | def fake_run(cmd, *, timeout, env=None, on_pid=None): |
| 1639 | four_running.wait() |
| 1640 | return inner(cmd, timeout=timeout) |
| 1641 | |
| 1642 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 1643 | monkeypatch.setattr(digg.subproc, "run_with_timeout", fake_run) |
| 1644 | digg.fetch_story_sources(_stories(10), "default", stopped=out_of_time.is_set) |
| 1645 | assert len(calls) == 4 |
| 1646 | |
| 1647 | |
| 1648 | def test_sources_fetch_timing_out_tags_nothing_and_leaves_the_story_intact(monkeypatch): |
| 1649 | def fake_run(*_a, **_kw): |
| 1650 | raise subproc.SubprocTimeout("posts timed out") |
| 1651 | |
| 1652 | story = _story_item() |
| 1653 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 1654 | monkeypatch.setattr(digg.subproc, "run_with_timeout", fake_run) |
| 1655 | fetched = digg.fetch_story_sources([story], "default") |
| 1656 | stories = digg.apply_story_sources([story], fetched) |
| 1657 | candidate = _candidate_for(_other_item("x", _source_row()["xUrl"])) |
| 1658 | digg.tag_confirmed_candidates([candidate], stories) |
| 1659 | assert fetched == {} and stories == {} |
| 1660 | assert "digg_story" not in candidate.metadata |
| 1661 | assert story.metadata["posts"] == [] |
| 1662 | assert story.url == "https://digg.com/science/k3v9xq2m" |
| 1663 | |
| 1664 | |
| 1665 | def test_source_with_a_non_web_url_confirms_nothing(monkeypatch): |
| 1666 | [candidate] = _confirm( |
| 1667 | _story_item(), |
| 1668 | [_source_row(kind="webpage", url="javascript:alert(1)", username="")], |
| 1669 | _other_item("hackernews", "javascript:alert(1)"), |
| 1670 | monkeypatch=monkeypatch, |
| 1671 | ) |
| 1672 | assert "digg_story" not in candidate.metadata |
| 1673 | |
| 1674 | |
| 1675 | def test_old_cli_clusters_get_no_sources_fetch(monkeypatch): |
| 1676 | from lib import normalize |
| 1677 | |
| 1678 | calls: list = [] |
| 1679 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 1680 | monkeypatch.setattr(digg.subproc, "run_with_timeout", _sources_cli({}, calls)) |
| 1681 | parsed = digg.parse_digg_response({"results": [_cluster()]}, query="sample") |
| 1682 | items = normalize.normalize_source_items("digg", parsed, "2026-01-01", "2026-12-31") |
| 1683 | assert digg.fetch_story_sources(items, "default") == {} |
| 1684 | assert calls == [] |
| 1685 | |
| 1686 | |
| 1687 | def test_ranked_post_enrichment_leaves_all_topic_stories_alone(monkeypatch): |
| 1688 | calls: list = [] |
| 1689 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 1690 | monkeypatch.setattr(digg.subproc, "run_with_timeout", _sources_cli({}, calls)) |
| 1691 | digg.enrich_source_items([_story_item()], top_k=3) |
| 1692 | assert calls == [] |
| 1693 | |
| 1694 | |
| 1695 | def test_tag_and_quotes_survive_fusion_of_two_streams(monkeypatch): |
| 1696 | from lib import fusion, schema |
| 1697 | |
| 1698 | source = _source_row() |
| 1699 | stories_a, stories_b = _story_item(), _story_item() |
| 1700 | post_a = _other_item("x", "https://x.com/astro_ana/status/1986000000000000001") |
| 1701 | post_b = _other_item("x", "https://x.com/astro_ana/status/1986000000000000001") |
| 1702 | for item in (stories_a, stories_b, post_a, post_b): |
| 1703 | item.local_relevance, item.freshness, item.source_quality = 0.7, 80, 0.7 |
| 1704 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 1705 | monkeypatch.setattr( |
| 1706 | digg.subproc, "run_with_timeout", |
| 1707 | _sources_cli({stories_a.metadata["clusterId"]: _sources_answer(source)}, []), |
| 1708 | ) |
| 1709 | digg_items = [stories_a, stories_b] |
| 1710 | confirmed = digg.apply_story_sources(digg_items, digg.fetch_story_sources(digg_items, "default")) |
| 1711 | plan = schema.QueryPlan( |
| 1712 | intent="breaking_news", freshness_mode="balanced_recent", cluster_mode="story", |
| 1713 | raw_topic="exoplanet", |
| 1714 | subqueries=[ |
| 1715 | schema.SubQuery(label=label, search_query="exoplanet", ranking_query="exoplanet", sources=["digg", "x"]) |
| 1716 | for label in ("primary", "second") |
| 1717 | ], |
| 1718 | source_weights={"digg": 1.0, "x": 1.0}, |
| 1719 | ) |
| 1720 | candidates = fusion.weighted_rrf( |
| 1721 | { |
| 1722 | ("primary", "digg"): [stories_a], ("primary", "x"): [post_a], |
| 1723 | ("second", "digg"): [stories_b], ("second", "x"): [post_b], |
| 1724 | }, |
| 1725 | plan, pool_limit=10, |
| 1726 | ) |
| 1727 | digg.tag_confirmed_candidates(candidates, confirmed) |
| 1728 | by_source = {candidate.source: candidate for candidate in candidates} |
| 1729 | assert len(candidates) == 2 |
| 1730 | assert by_source["x"].subquery_labels == ["primary", "second"] |
| 1731 | assert by_source["x"].metadata["digg_story"]["url"] == stories_a.url |
| 1732 | assert "digg_story" not in by_source["digg"].metadata |
| 1733 | assert schema.candidate_primary_item(by_source["digg"]).metadata["posts"][0]["username"] == "astro_ana" |
| 1734 | |
| 1735 | |
| 1736 | def test_confirmed_item_names_its_digg_story_in_the_report(monkeypatch): |
| 1737 | from lib import render |
| 1738 | |
| 1739 | [candidate] = _confirm( |
| 1740 | _story_item(), [_source_row()], |
| 1741 | _other_item("x", "https://x.com/astro_ana/status/1986000000000000001"), |
| 1742 | monkeypatch=monkeypatch, |
| 1743 | ) |
| 1744 | lines = render._render_candidate(candidate, "1.") |
| 1745 | assert ( |
| 1746 | " - Also in Digg story: " |
| 1747 | "[Webb telescope spots water on a rocky exoplanet](https://digg.com/science/k3v9xq2m)" |
| 1748 | " (Digg Score 412, 37 sources)" |
| 1749 | ) in lines |
| 1750 | |
| 1751 | |
| 1752 | def test_unconfirmed_item_names_no_digg_story(): |
| 1753 | from lib import render |
| 1754 | |
| 1755 | candidate = _candidate_for(_other_item("x", "https://x.com/astro_ana/status/1986000000000000001")) |
| 1756 | assert not [line for line in render._render_candidate(candidate, "1.") if "Digg story" in line] |
| 1757 | |
| 1758 | |
| 1759 | # === Top stories for global trending === |
| 1760 | |
| 1761 | # What digg-pp-cli 2026.10.1 printed for `top --agent --limit 20` against an |
| 1762 | # empty local store, captured 2026-11-11: plain text, exit 0. |
| 1763 | _CLI_2026_10_1_TOP_STDOUT = "no clusters in the local store. Run `digg-pp-cli sync` first.\n" |
| 1764 | |
| 1765 | |
| 1766 | def _top_row(index: int = 1, topic: str = "science", **overrides) -> dict: |
| 1767 | short_id = f"top{index:05d}" |
| 1768 | row = { |
| 1769 | "rank": index, |
| 1770 | "clusterId": f"11111111-2222-3333-4444-{short_id:0>12}", |
| 1771 | "clusterUrlId": short_id, |
| 1772 | "url": f"https://digg.com/{topic}/{short_id}", |
| 1773 | "topic": topic, |
| 1774 | "title": f"Top story number {index}", |
| 1775 | "description": "Longer description of the story.", |
| 1776 | "diggScore": 900 - index, |
| 1777 | "postCount": 40 + index, |
| 1778 | "uniqueAuthors": 20 + index, |
| 1779 | "publishedAt": "2026-11-11T08:30:00Z", |
| 1780 | } |
| 1781 | row.update(overrides) |
| 1782 | return row |
| 1783 | |
| 1784 | |
| 1785 | def _top_envelope(*rows: dict) -> dict: |
| 1786 | return { |
| 1787 | "meta": {"count": len(rows), "source": "live", "view": "top", "range": "24h"}, |
| 1788 | "results": list(rows), |
| 1789 | } |
| 1790 | |
| 1791 | |
| 1792 | def _top_calls(calls: list) -> list: |
| 1793 | return [cmd for cmd in calls if "--help" not in cmd] |
| 1794 | |
| 1795 | |
| 1796 | def test_top_stories_reads_every_topic_from_the_new_cli(monkeypatch): |
| 1797 | calls: list = [] |
| 1798 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 1799 | monkeypatch.setattr( |
| 1800 | digg.subproc, |
| 1801 | "run_with_timeout", |
| 1802 | _fake_cli(_NEW_SEARCH_HELP, _top_envelope(_top_row(1), _top_row(2)), calls), |
| 1803 | ) |
| 1804 | out = digg.top_stories() |
| 1805 | assert _top_calls(calls) == [["digg-pp-cli", "top", "--agent", "--limit", "20"]] |
| 1806 | assert len(out["results"]) == 2 |
| 1807 | assert "error" not in out |
| 1808 | |
| 1809 | |
| 1810 | def test_deep_top_stories_asks_for_50(monkeypatch): |
| 1811 | calls: list = [] |
| 1812 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 1813 | monkeypatch.setattr( |
| 1814 | digg.subproc, "run_with_timeout", _fake_cli(_NEW_SEARCH_HELP, _top_envelope(), calls) |
| 1815 | ) |
| 1816 | digg.top_stories(depth="deep") |
| 1817 | assert _top_calls(calls) == [["digg-pp-cli", "top", "--agent", "--limit", "50"]] |
| 1818 | |
| 1819 | |
| 1820 | def test_top_stories_from_cli_2026_10_1_are_empty_without_an_error(monkeypatch): |
| 1821 | calls: list = [] |
| 1822 | |
| 1823 | def fake_run(cmd, *, timeout, env=None, on_pid=None): |
| 1824 | calls.append(list(cmd)) |
| 1825 | if "--help" in cmd: |
| 1826 | return subproc.SubprocResult(returncode=0, stdout=_OLD_SEARCH_HELP, stderr="") |
| 1827 | return subproc.SubprocResult(returncode=0, stdout=_CLI_2026_10_1_TOP_STDOUT, stderr="") |
| 1828 | |
| 1829 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 1830 | monkeypatch.setattr(digg.subproc, "run_with_timeout", fake_run) |
| 1831 | out = digg.top_stories() |
| 1832 | assert out == {"results": []} |
| 1833 | assert digg.parse_top_response(out, from_date="2026-10-12") == [] |
| 1834 | assert _top_calls(calls) == [] |
| 1835 | |
| 1836 | |
| 1837 | def test_top_rows_parse_like_search_stories(): |
| 1838 | rows = [_top_row(i, topic="sports" if i % 2 else "science") for i in range(1, 21)] |
| 1839 | items = digg.parse_top_response(_top_envelope(*rows), from_date="2026-10-12") |
| 1840 | assert len(items) == 20 |
| 1841 | first = items[0] |
| 1842 | assert first["id"] == "top00001" |
| 1843 | assert first["cluster_id"] == "11111111-2222-3333-4444-0000top00001" |
| 1844 | assert first["topic"] == "sports" |
| 1845 | assert first["url"] == "https://digg.com/sports/top00001" |
| 1846 | assert first["title"] == "Top story number 1" |
| 1847 | assert first["date"] == "2026-11-11" |
| 1848 | assert first["engagement"] == {"postCount": 41, "uniqueAuthors": 21, "digg_score": 899} |
| 1849 | for item in items: |
| 1850 | assert set(item["engagement"]) == {"postCount", "uniqueAuthors", "digg_score"} |
| 1851 | assert item["date"] == "2026-11-11" |
| 1852 | |
| 1853 | |
| 1854 | def test_top_rows_without_a_title_yield_no_items(): |
| 1855 | untitled = _top_row(1) |
| 1856 | del untitled["title"] |
| 1857 | blank = _top_row(2, title=" ") |
| 1858 | assert digg.parse_top_response(_top_envelope(untitled, blank, {}), from_date="2026-10-12") == [] |
| 1859 | |
| 1860 | |
| 1861 | # === A failed help probe is not an older CLI === |
| 1862 | |
| 1863 | |
| 1864 | def _cli_with_failing_help(help_failure, answer: dict, calls: list): |
| 1865 | """A CLI whose ``search --help`` fails while every other call answers.""" |
| 1866 | |
| 1867 | def fake_run(cmd, *, timeout, **_kwargs): |
| 1868 | calls.append(list(cmd)) |
| 1869 | if "--help" in cmd: |
| 1870 | return help_failure() |
| 1871 | return _stdout_for(answer) |
| 1872 | |
| 1873 | return fake_run |
| 1874 | |
| 1875 | |
| 1876 | def _help_times_out(): |
| 1877 | raise subproc.SubprocTimeout("search --help timed out") |
| 1878 | |
| 1879 | |
| 1880 | def _help_exits_non_zero(): |
| 1881 | return subproc.SubprocResult(returncode=1, stdout="", stderr="config unreadable") |
| 1882 | |
| 1883 | |
| 1884 | @pytest.mark.parametrize("help_failure", [_help_times_out, _help_exits_non_zero]) |
| 1885 | def test_failed_help_probe_keeps_the_items_without_the_upgrade_note(monkeypatch, help_failure): |
| 1886 | calls: list = [] |
| 1887 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 1888 | monkeypatch.setattr( |
| 1889 | digg.subproc, |
| 1890 | "run_with_timeout", |
| 1891 | _cli_with_failing_help(help_failure, _live_envelope(_story()), calls), |
| 1892 | ) |
| 1893 | out = digg.search_digg("exoplanet", "2026-10-12", "2026-11-11") |
| 1894 | items = digg.parse_digg_response(out, query="exoplanet", from_date="2026-10-12") |
| 1895 | assert [item["url"] for item in items] == ["https://digg.com/science/k3v9xq2m"] |
| 1896 | assert "error" not in out |
| 1897 | assert digg.upgrade_note(out) is None |
| 1898 | # The call both CLIs accept. |
| 1899 | assert _search_calls(calls) == [ |
| 1900 | ["digg-pp-cli", "search", "--topic", "ai,tech", |
| 1901 | "--since", "30d", "--agent", "--limit", "20", "--", "exoplanet"] |
| 1902 | ] |
| 1903 | |
| 1904 | digg.search_digg("exoplanet", "2026-10-12", "2026-11-11") |
| 1905 | assert len([cmd for cmd in calls if "--help" in cmd]) == 2 |
| 1906 | |
| 1907 | |
| 1908 | @pytest.mark.parametrize("help_failure", [_help_times_out, _help_exits_non_zero]) |
| 1909 | def test_top_stories_after_a_failed_help_probe_are_empty_without_an_error(monkeypatch, help_failure): |
| 1910 | calls: list = [] |
| 1911 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 1912 | monkeypatch.setattr( |
| 1913 | digg.subproc, |
| 1914 | "run_with_timeout", |
| 1915 | _cli_with_failing_help(help_failure, _top_envelope(_top_row(1)), calls), |
| 1916 | ) |
| 1917 | assert digg.top_stories() == {"results": []} |
| 1918 | assert _top_calls(calls) == [] |
| 1919 | |
| 1920 | |
| 1921 | # === Missing binary === |
| 1922 | |
| 1923 | |
| 1924 | def test_search_and_top_stories_name_the_missing_binary(monkeypatch): |
| 1925 | def never_run(*_a, **_kw): |
| 1926 | raise AssertionError("ran a CLI that is not on PATH") |
| 1927 | |
| 1928 | monkeypatch.setattr(digg.shutil, "which", lambda _: None) |
| 1929 | monkeypatch.setattr(digg.subproc, "run_with_timeout", never_run) |
| 1930 | search = digg.search_digg("exoplanet", "2026-10-12", "2026-11-11") |
| 1931 | top = digg.top_stories() |
| 1932 | assert search == {"results": [], "error": "digg-pp-cli not on PATH"} |
| 1933 | assert top == {"results": [], "error": "digg-pp-cli not on PATH"} |
| 1934 | |
| 1935 | |
| 1936 | # === Stories without a usable publish date === |
| 1937 | |
| 1938 | |
| 1939 | @pytest.mark.parametrize("published_at", [None, "", "last Tuesday"]) |
| 1940 | def test_story_without_a_readable_publish_date_is_kept_undated(published_at): |
| 1941 | story = _story(published_at=published_at) |
| 1942 | if published_at is None: |
| 1943 | del story["publishedAt"] |
| 1944 | [item] = digg.parse_digg_response(_live_envelope(story), from_date="2026-10-12") |
| 1945 | assert item["url"] == "https://digg.com/science/k3v9xq2m" |
| 1946 | assert item["date"] is None |
| 1947 | |
| 1948 | |
| 1949 | # === Story sources: run deadline, cancel signal and comparison share === |
| 1950 | |
| 1951 | |
| 1952 | class _Clock: |
| 1953 | """A monotonic clock that only moves when a fake CLI call spends time.""" |
| 1954 | |
| 1955 | def __init__(self, now: float = 1000.0): |
| 1956 | self.now = now |
| 1957 | |
| 1958 | def monotonic(self) -> float: |
| 1959 | return self.now |
| 1960 | |
| 1961 | |
| 1962 | def _one_call_at_a_time(monkeypatch): |
| 1963 | """The fake clock only adds up when calls do not overlap.""" |
| 1964 | monkeypatch.setattr(digg, "SOURCES_CONCURRENCY", 1) |
| 1965 | |
| 1966 | |
| 1967 | def _slow_sources_cli(clock: _Clock, seen: list, *, times_out: bool = True): |
| 1968 | """A ``posts`` call that takes its whole timeout, then times out or |
| 1969 | answers with no sources.""" |
| 1970 | |
| 1971 | def fake_run(cmd, *, timeout, **kwargs): |
| 1972 | seen.append({"timeout": timeout, **kwargs}) |
| 1973 | clock.now += timeout |
| 1974 | if times_out: |
| 1975 | raise subproc.SubprocTimeout("posts timed out") |
| 1976 | return subproc.SubprocResult(returncode=0, stdout='{"results": []}', stderr="") |
| 1977 | |
| 1978 | return fake_run |
| 1979 | |
| 1980 | |
| 1981 | def test_sources_fetch_caps_a_call_at_the_time_left_and_stops_at_the_deadline(monkeypatch): |
| 1982 | clock, seen = _Clock(), [] |
| 1983 | _one_call_at_a_time(monkeypatch) |
| 1984 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 1985 | monkeypatch.setattr(digg, "time", clock) |
| 1986 | monkeypatch.setattr(digg.subproc, "run_with_timeout", _slow_sources_cli(clock, seen)) |
| 1987 | deadline = clock.now + 2 |
| 1988 | assert digg.fetch_story_sources(_five_stories(), "deep", deadline=deadline) == {} |
| 1989 | assert len(seen) == 1 |
| 1990 | assert 0 < seen[0]["timeout"] <= 2 |
| 1991 | assert seen[0]["deadline_monotonic"] == deadline |
| 1992 | |
| 1993 | |
| 1994 | def test_sources_fetch_makes_no_call_once_the_run_is_cancelled(monkeypatch): |
| 1995 | import threading |
| 1996 | |
| 1997 | calls: list = [] |
| 1998 | cancel = threading.Event() |
| 1999 | cancel.set() |
| 2000 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 2001 | monkeypatch.setattr(digg.subproc, "run_with_timeout", _sources_cli({}, calls)) |
| 2002 | assert digg.fetch_story_sources(_five_stories(), "deep", cancel=cancel) == {} |
| 2003 | assert calls == [] |
| 2004 | |
| 2005 | |
| 2006 | def test_cancel_during_the_fetch_stops_the_calls_not_yet_started(monkeypatch): |
| 2007 | import threading |
| 2008 | |
| 2009 | calls: list = [] |
| 2010 | cancel = threading.Event() |
| 2011 | # The first four calls meet, and the run is cancelled before any ends. |
| 2012 | four_running = threading.Barrier(4, action=cancel.set, timeout=1) |
| 2013 | inner = _sources_cli({}, calls) |
| 2014 | |
| 2015 | def fake_run(cmd, *, timeout, **kwargs): |
| 2016 | four_running.wait() |
| 2017 | return inner(cmd, timeout=timeout) |
| 2018 | |
| 2019 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 2020 | monkeypatch.setattr(digg.subproc, "run_with_timeout", fake_run) |
| 2021 | stories = _stories(10) |
| 2022 | digg.fetch_story_sources(stories, "default", cancel=cancel) |
| 2023 | assert len(calls) == 4 |
| 2024 | assert {call[-1] for call in calls} == set(_by_score(stories)[:4]) |
| 2025 | |
| 2026 | |
| 2027 | def test_deadline_two_seconds_away_caps_every_call_and_leaves_no_worker_running(monkeypatch): |
| 2028 | import threading |
| 2029 | import time |
| 2030 | |
| 2031 | lock = threading.Lock() |
| 2032 | seen: list = [] |
| 2033 | running = {"now": 0} |
| 2034 | |
| 2035 | def fake_run(cmd, *, timeout, **kwargs): |
| 2036 | with lock: |
| 2037 | running["now"] += 1 |
| 2038 | seen.append({"timeout": timeout, **kwargs}) |
| 2039 | try: |
| 2040 | return _stdout_for(_sources_answer()) |
| 2041 | finally: |
| 2042 | with lock: |
| 2043 | running["now"] -= 1 |
| 2044 | |
| 2045 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 2046 | monkeypatch.setattr(digg.subproc, "run_with_timeout", fake_run) |
| 2047 | threads_before = set(threading.enumerate()) |
| 2048 | deadline = time.monotonic() + 2 |
| 2049 | digg.fetch_story_sources(_stories(10), "default", deadline=deadline) |
| 2050 | assert len(seen) == 8 |
| 2051 | for call in seen: |
| 2052 | assert 0 < call["timeout"] <= 2 |
| 2053 | assert call["deadline_monotonic"] == deadline |
| 2054 | assert running["now"] == 0 |
| 2055 | assert [t for t in threading.enumerate() if t not in threads_before and t.is_alive()] == [] |
| 2056 | |
| 2057 | |
| 2058 | def test_sources_fetch_hands_the_cancel_signal_to_each_call(monkeypatch): |
| 2059 | import threading |
| 2060 | |
| 2061 | seen: list = [] |
| 2062 | cancel = threading.Event() |
| 2063 | |
| 2064 | def fake_run(cmd, *, timeout, **kwargs): |
| 2065 | seen.append(kwargs.get("cancel")) |
| 2066 | return _stdout_for(_sources_answer()) |
| 2067 | |
| 2068 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 2069 | monkeypatch.setattr(digg.subproc, "run_with_timeout", fake_run) |
| 2070 | digg.fetch_story_sources(_five_stories(), "default", cancel=cancel) |
| 2071 | assert seen == [cancel] * 5 |
| 2072 | |
| 2073 | |
| 2074 | def test_sources_fetch_without_a_run_deadline_spends_at_most_40_seconds(monkeypatch): |
| 2075 | clock, seen = _Clock(), [] |
| 2076 | _one_call_at_a_time(monkeypatch) |
| 2077 | started = clock.now |
| 2078 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 2079 | monkeypatch.setattr(digg, "time", clock) |
| 2080 | monkeypatch.setattr( |
| 2081 | digg.subproc, "run_with_timeout", _slow_sources_cli(clock, seen, times_out=False), |
| 2082 | ) |
| 2083 | digg.fetch_story_sources(_five_stories(), "deep") |
| 2084 | assert [call["timeout"] for call in seen] == [10, 10, 10, 10] |
| 2085 | assert clock.now - started <= 40 |
| 2086 | |
| 2087 | |
| 2088 | def test_sources_fetch_stops_starting_calls_once_one_fails(monkeypatch): |
| 2089 | # Digg stalls hit every call alike, so the rest are not left to wait |
| 2090 | # out their own timeouts. |
| 2091 | calls: list = [] |
| 2092 | |
| 2093 | def timing_out(cmd, *, timeout, **_bounds): |
| 2094 | calls.append(cmd) |
| 2095 | raise subproc.SubprocTimeout("posts timed out") |
| 2096 | |
| 2097 | _one_call_at_a_time(monkeypatch) |
| 2098 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 2099 | monkeypatch.setattr(digg.subproc, "run_with_timeout", timing_out) |
| 2100 | assert digg.fetch_story_sources(_five_stories(), "deep") == {} |
| 2101 | assert len(calls) == 1 |
| 2102 | |
| 2103 | |
| 2104 | @pytest.mark.parametrize("depth, entity_count, expected_calls", [ |
| 2105 | ("default", 1, 8), |
| 2106 | ("deep", 1, 12), |
| 2107 | ("default", 3, 3), |
| 2108 | ("deep", 3, 4), |
| 2109 | ("default", 9, 1), |
| 2110 | ("quick", 3, 0), |
| 2111 | ]) |
| 2112 | def test_comparison_run_fetches_its_share_of_the_story_budget( |
| 2113 | monkeypatch, depth, entity_count, expected_calls, |
| 2114 | ): |
| 2115 | calls: list = [] |
| 2116 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 2117 | monkeypatch.setattr(digg.subproc, "run_with_timeout", _sources_cli({}, calls)) |
| 2118 | digg.fetch_story_sources(_stories(15), depth, entity_count=entity_count) |
| 2119 | assert len(calls) == expected_calls |
| 2120 | |
| 2121 | |
| 2122 | # === Research search: most relevant stories plus the highest-scored ones === |
| 2123 | |
| 2124 | _RELEVANCE_ARGS = ["digg-pp-cli", "search", "--since", "30d", "--agent", "--limit"] |
| 2125 | |
| 2126 | |
| 2127 | def _research_cli(relevance, score, calls: list, seen: list | None = None, help_text=_NEW_SEARCH_HELP): |
| 2128 | """A CLI answering the relevance call and the ``--sort score`` call apart. |
| 2129 | |
| 2130 | An answer is an envelope, or a callable that raises or returns a result. |
| 2131 | """ |
| 2132 | |
| 2133 | def fake_run(cmd, *, timeout, **kwargs): |
| 2134 | calls.append(list(cmd)) |
| 2135 | if "--help" in cmd: |
| 2136 | return subproc.SubprocResult(returncode=0, stdout=help_text, stderr="") |
| 2137 | if seen is not None: |
| 2138 | seen.append({k: v for k, v in kwargs.items() if k != "env"}) |
| 2139 | answer = score if "--sort" in cmd else relevance |
| 2140 | return answer() if callable(answer) else _stdout_for(answer) |
| 2141 | |
| 2142 | return fake_run |
| 2143 | |
| 2144 | |
| 2145 | def _research_search(monkeypatch, fake_run, depth="default", from_date="2026-10-12", **kwargs): |
| 2146 | monkeypatch.setattr(digg, "_today", lambda: _CAPTURE_DAY) |
| 2147 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 2148 | monkeypatch.setattr(digg.subproc, "run_with_timeout", fake_run) |
| 2149 | return digg.search_digg( |
| 2150 | "exoplanet", from_date, "2026-11-11", depth=depth, include_top_scored=True, **kwargs |
| 2151 | ) |
| 2152 | |
| 2153 | |
| 2154 | def _score_call_times_out(): |
| 2155 | raise subproc.SubprocTimeout("search timed out after 30s") |
| 2156 | |
| 2157 | |
| 2158 | @pytest.mark.parametrize("depth,size", [("default", "50"), ("deep", "100")]) |
| 2159 | def test_research_search_asks_for_the_most_relevant_and_the_highest_scored(monkeypatch, depth, size): |
| 2160 | calls: list = [] |
| 2161 | answer = _live_envelope(_story()) |
| 2162 | out = _research_search(monkeypatch, _research_cli(answer, answer, calls), depth=depth) |
| 2163 | assert _search_calls(calls) == [ |
| 2164 | [*_RELEVANCE_ARGS, size, "--", "exoplanet"], |
| 2165 | [*_RELEVANCE_ARGS, size, "--sort", "score", "--", "exoplanet"], |
| 2166 | ] |
| 2167 | assert len(out["results"]) == 1 |
| 2168 | assert "error" not in out |
| 2169 | assert digg.score_pass_note(out) is None |
| 2170 | |
| 2171 | |
| 2172 | def test_quick_research_search_is_one_call_of_8_with_no_sort(monkeypatch): |
| 2173 | calls: list = [] |
| 2174 | answer = _live_envelope(_story()) |
| 2175 | _research_search(monkeypatch, _research_cli(answer, answer, calls), depth="quick", from_date="2026-11-04") |
| 2176 | assert _search_calls(calls) == [[*_RELEVANCE_ARGS, "8", "--", "exoplanet"]] |
| 2177 | |
| 2178 | |
| 2179 | def test_research_search_on_the_older_cli_is_the_one_ai_and_tech_call(monkeypatch): |
| 2180 | calls: list = [] |
| 2181 | out = _research_search( |
| 2182 | monkeypatch, |
| 2183 | _research_cli(_CLI_2026_10_1_ANSWER, _CLI_2026_10_1_ANSWER, calls, help_text=_OLD_SEARCH_HELP), |
| 2184 | from_date="2026-11-04", |
| 2185 | ) |
| 2186 | assert _search_calls(calls) == [ |
| 2187 | ["digg-pp-cli", "search", "--topic", "ai,tech", |
| 2188 | "--since", "30d", "--agent", "--limit", "20", "--", "exoplanet"] |
| 2189 | ] |
| 2190 | assert digg.upgrade_note(out) == digg.UPGRADE_NOTE |
| 2191 | |
| 2192 | |
| 2193 | @pytest.mark.parametrize("help_failure", [_help_times_out, _help_exits_non_zero]) |
| 2194 | def test_research_search_after_a_failed_help_probe_is_the_one_ai_and_tech_call(monkeypatch, help_failure): |
| 2195 | calls: list = [] |
| 2196 | _research_search( |
| 2197 | monkeypatch, _cli_with_failing_help(help_failure, _live_envelope(_story()), calls) |
| 2198 | ) |
| 2199 | assert _search_calls(calls) == [ |
| 2200 | ["digg-pp-cli", "search", "--topic", "ai,tech", |
| 2201 | "--since", "30d", "--agent", "--limit", "20", "--", "exoplanet"] |
| 2202 | ] |
| 2203 | |
| 2204 | |
| 2205 | def test_story_in_both_calls_appears_once_and_score_only_stories_follow_by_score(monkeypatch): |
| 2206 | relevance = _live_envelope( |
| 2207 | _story(short_id="rel00001", diggScore=12), |
| 2208 | _story(short_id="both0001", diggScore=500), |
| 2209 | ) |
| 2210 | score = _live_envelope( |
| 2211 | _story(short_id="both0001", diggScore=500), |
| 2212 | _story(short_id="big90bbb", diggScore=90), |
| 2213 | _story(short_id="big300aa", diggScore=300), |
| 2214 | _story(short_id="big90aaa", diggScore=90), |
| 2215 | ) |
| 2216 | out = _research_search(monkeypatch, _research_cli(relevance, score, [])) |
| 2217 | assert [story["clusterUrlId"] for story in out["results"]] == [ |
| 2218 | "rel00001", "both0001", "big300aa", "big90aaa", "big90bbb", |
| 2219 | ] |
| 2220 | |
| 2221 | |
| 2222 | def test_stories_without_a_uuid_are_matched_by_their_short_id(monkeypatch): |
| 2223 | def bare(short_id: str, score: int) -> dict: |
| 2224 | story = _story(short_id=short_id, diggScore=score) |
| 2225 | del story["clusterId"] |
| 2226 | return story |
| 2227 | |
| 2228 | out = _research_search( |
| 2229 | monkeypatch, |
| 2230 | _research_cli( |
| 2231 | _live_envelope(bare("same0001", 40)), |
| 2232 | _live_envelope(bare("same0001", 40), bare("other001", 70)), |
| 2233 | [], |
| 2234 | ), |
| 2235 | ) |
| 2236 | assert [story["clusterUrlId"] for story in out["results"]] == ["same0001", "other001"] |
| 2237 | |
| 2238 | |
| 2239 | def test_failed_score_call_keeps_the_relevance_stories_and_says_so(monkeypatch): |
| 2240 | out = _research_search( |
| 2241 | monkeypatch, |
| 2242 | _research_cli(_live_envelope(_story(short_id="rel00001")), _score_call_times_out, []), |
| 2243 | ) |
| 2244 | assert [story["clusterUrlId"] for story in out["results"]] == ["rel00001"] |
| 2245 | assert "error" not in out |
| 2246 | note = digg.score_pass_note(out) |
| 2247 | assert "highest-scored" in note |
| 2248 | assert "timed out" in note |
| 2249 | assert len(note) <= 140 |
| 2250 | |
| 2251 | |
| 2252 | def test_score_pass_note_is_absent_for_a_plain_answer(): |
| 2253 | assert digg.score_pass_note({"results": []}) is None |
| 2254 | assert digg.score_pass_note(None) is None |
| 2255 | |
| 2256 | |
| 2257 | def test_failed_score_call_is_a_detail_on_an_ok_digg_outcome(monkeypatch): |
| 2258 | from lib import health, pipeline, schema |
| 2259 | |
| 2260 | monkeypatch.setattr(digg, "_today", lambda: _CAPTURE_DAY) |
| 2261 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 2262 | monkeypatch.setattr( |
| 2263 | digg.subproc, |
| 2264 | "run_with_timeout", |
| 2265 | _research_cli(_live_envelope(_story(short_id="rel00001")), _score_call_times_out, []), |
| 2266 | ) |
| 2267 | subquery = schema.SubQuery( |
| 2268 | label="primary", |
| 2269 | search_query="exoplanet score pass", |
| 2270 | ranking_query="exoplanet", |
| 2271 | sources=["digg"], |
| 2272 | ) |
| 2273 | items, artifact = pipeline._retrieve_stream_impl( |
| 2274 | topic="exoplanet", |
| 2275 | subquery=subquery, |
| 2276 | source="digg", |
| 2277 | config={}, |
| 2278 | depth="default", |
| 2279 | date_range=("2026-10-12", "2026-11-11"), |
| 2280 | runtime=None, |
| 2281 | mock=False, |
| 2282 | ) |
| 2283 | assert [item["id"] for item in items] == ["rel00001"] |
| 2284 | assert "_source_outcome" not in artifact |
| 2285 | assert "highest-scored" in artifact["_source_outcome_detail"] |
| 2286 | |
| 2287 | bundle = schema.RetrievalBundle() |
| 2288 | bundle.record_detail("digg", artifact["_source_outcome_detail"]) |
| 2289 | bundle.add_items("primary", "digg", [object()]) |
| 2290 | assert bundle.source_status["digg"].state == health.OK |
| 2291 | assert "highest-scored" in bundle.source_status["digg"].detail |
| 2292 | |
| 2293 | |
| 2294 | def test_failed_relevance_call_is_an_error_and_makes_no_score_call(monkeypatch): |
| 2295 | calls: list = [] |
| 2296 | |
| 2297 | def relevance_fails(): |
| 2298 | return subproc.SubprocResult(returncode=2, stdout="", stderr="boom") |
| 2299 | |
| 2300 | out = _research_search( |
| 2301 | monkeypatch, _research_cli(relevance_fails, _live_envelope(_story()), calls) |
| 2302 | ) |
| 2303 | assert out == {"results": [], "error": "boom"} |
| 2304 | assert len(_search_calls(calls)) == 1 |
| 2305 | assert "--sort" not in _search_calls(calls)[0] |
| 2306 | |
| 2307 | |
| 2308 | @pytest.mark.parametrize( |
| 2309 | "from_date,since", |
| 2310 | [("2026-11-04", "8d"), ("2026-11-11", "1d"), ("2026-10-14", "29d"), ("2026-10-13", "30d"), ("2026-09-12", "30d")], |
| 2311 | ) |
| 2312 | def test_research_search_sends_a_shorter_lookback_on_both_calls(monkeypatch, from_date, since): |
| 2313 | calls: list = [] |
| 2314 | answer = _live_envelope(_story()) |
| 2315 | _research_search(monkeypatch, _research_cli(answer, answer, calls), from_date=from_date) |
| 2316 | searches = _search_calls(calls) |
| 2317 | assert len(searches) == 2 |
| 2318 | assert [cmd[cmd.index("--since") + 1] for cmd in searches] == [since, since] |
| 2319 | |
| 2320 | |
| 2321 | def test_cancelled_run_makes_no_score_call(monkeypatch): |
| 2322 | import threading |
| 2323 | |
| 2324 | calls: list = [] |
| 2325 | cancel = threading.Event() |
| 2326 | cancel.set() |
| 2327 | answer = _live_envelope(_story()) |
| 2328 | out = _research_search(monkeypatch, _research_cli(answer, answer, calls), cancel=cancel) |
| 2329 | assert len(_search_calls(calls)) == 1 |
| 2330 | assert "--sort" not in _search_calls(calls)[0] |
| 2331 | assert len(out["results"]) == 1 |
| 2332 | assert digg.score_pass_note(out) is None |
| 2333 | |
| 2334 | |
| 2335 | def test_run_past_its_deadline_makes_no_score_call(monkeypatch): |
| 2336 | calls: list = [] |
| 2337 | clock = _Clock() |
| 2338 | monkeypatch.setattr(digg, "time", clock) |
| 2339 | answer = _live_envelope(_story()) |
| 2340 | _research_search( |
| 2341 | monkeypatch, _research_cli(answer, answer, calls), deadline=clock.now - 1 |
| 2342 | ) |
| 2343 | assert len(_search_calls(calls)) == 1 |
| 2344 | assert "--sort" not in _search_calls(calls)[0] |
| 2345 | |
| 2346 | |
| 2347 | def test_research_search_hands_the_deadline_and_cancel_signal_to_both_calls(monkeypatch): |
| 2348 | import threading |
| 2349 | |
| 2350 | seen: list = [] |
| 2351 | clock = _Clock() |
| 2352 | monkeypatch.setattr(digg, "time", clock) |
| 2353 | cancel = threading.Event() |
| 2354 | deadline = clock.now + 60 |
| 2355 | answer = _live_envelope(_story()) |
| 2356 | _research_search( |
| 2357 | monkeypatch, _research_cli(answer, answer, [], seen), deadline=deadline, cancel=cancel |
| 2358 | ) |
| 2359 | # The score call's deadline is earlier, so its answer can be handed |
| 2360 | # back before the run's own deadline. |
| 2361 | assert seen == [ |
| 2362 | {"deadline_monotonic": deadline, "cancel": cancel}, |
| 2363 | { |
| 2364 | "deadline_monotonic": deadline - digg.SCORE_SEARCH_MARGIN, "cancel": cancel, |
| 2365 | "cleanup_grace": digg.SCORE_SEARCH_CLEANUP_GRACE, |
| 2366 | }, |
| 2367 | ] |
| 2368 | |
| 2369 | |
| 2370 | def test_pipeline_research_stream_makes_both_calls_with_the_runs_bounds(monkeypatch): |
| 2371 | import threading |
| 2372 | |
| 2373 | from lib import pipeline, schema |
| 2374 | |
| 2375 | import time |
| 2376 | |
| 2377 | calls: list = [] |
| 2378 | seen: list = [] |
| 2379 | cancel = threading.Event() |
| 2380 | deadline = time.monotonic() + 60 |
| 2381 | answer = _live_envelope(_story()) |
| 2382 | monkeypatch.setattr(digg, "_today", lambda: _CAPTURE_DAY) |
| 2383 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 2384 | monkeypatch.setattr(digg.subproc, "run_with_timeout", _research_cli(answer, answer, calls, seen)) |
| 2385 | subquery = schema.SubQuery( |
| 2386 | label="primary", |
| 2387 | search_query="exoplanet bounds", |
| 2388 | ranking_query="exoplanet", |
| 2389 | sources=["digg"], |
| 2390 | ) |
| 2391 | items, artifact = pipeline._retrieve_stream_impl( |
| 2392 | topic="exoplanet", |
| 2393 | subquery=subquery, |
| 2394 | source="digg", |
| 2395 | config={"_research_deadline": deadline, "_enrich_cancel": cancel}, |
| 2396 | depth="default", |
| 2397 | date_range=("2026-11-04", "2026-11-11"), |
| 2398 | runtime=None, |
| 2399 | mock=False, |
| 2400 | ) |
| 2401 | assert _search_calls(calls) == [ |
| 2402 | ["digg-pp-cli", "search", "--since", "8d", "--agent", "--limit", "50", "--", "exoplanet bounds"], |
| 2403 | ["digg-pp-cli", "search", "--since", "8d", "--agent", "--limit", "50", |
| 2404 | "--sort", "score", "--", "exoplanet bounds"], |
| 2405 | ] |
| 2406 | # The score call's deadline is earlier, so its answer can be handed |
| 2407 | # back before the run's own deadline. |
| 2408 | assert seen == [ |
| 2409 | {"deadline_monotonic": deadline, "cancel": cancel}, |
| 2410 | { |
| 2411 | "deadline_monotonic": deadline - digg.SCORE_SEARCH_MARGIN, "cancel": cancel, |
| 2412 | "cleanup_grace": digg.SCORE_SEARCH_CLEANUP_GRACE, |
| 2413 | }, |
| 2414 | ] |
| 2415 | assert len(items) == 1 |
| 2416 | assert artifact == {} |
| 2417 | |
| 2418 | |
| 2419 | def test_discovery_digg_search_stays_one_call_of_20(monkeypatch): |
| 2420 | from lib import pipeline |
| 2421 | |
| 2422 | calls: list = [] |
| 2423 | answer = _live_envelope(_story(title="Exoplanet water found by Webb")) |
| 2424 | monkeypatch.setattr(digg, "_today", lambda: _CAPTURE_DAY) |
| 2425 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/fake/path") |
| 2426 | monkeypatch.setattr(digg.subproc, "run_with_timeout", _research_cli(answer, answer, calls)) |
| 2427 | plan = MagicMock() |
| 2428 | plan.domain = "exoplanet" |
| 2429 | pipeline._fetch_discovery_source( |
| 2430 | "digg", plan, from_date="2026-11-04", to_date="2026-11-11", |
| 2431 | depth="default", mock=False, config={}, |
| 2432 | ) |
| 2433 | assert _search_calls(calls) == [[*_RELEVANCE_ARGS, "20", "--", "exoplanet"]] |
| 2434 | |
| 2435 | |
| 2436 | def test_score_call_ends_before_the_run_deadline_so_the_relevance_stories_are_kept(monkeypatch): |
| 2437 | # The relevance call has answered. The score call must be over with time |
| 2438 | # to spare, or the run abandons the whole search as timed out. |
| 2439 | score_calls: list = [] |
| 2440 | answer = _live_envelope(_story()) |
| 2441 | |
| 2442 | def fake_run(cmd, *, timeout, **kwargs): |
| 2443 | if "--help" in cmd: |
| 2444 | return subproc.SubprocResult(returncode=0, stdout=_NEW_SEARCH_HELP, stderr="") |
| 2445 | if "--sort" in cmd: |
| 2446 | score_calls.append({"timeout": timeout, **kwargs}) |
| 2447 | return _stdout_for(answer) |
| 2448 | |
| 2449 | deadline = digg.time.monotonic() + 12 |
| 2450 | _research_search(monkeypatch, fake_run, deadline=deadline) |
| 2451 | [score_call] = score_calls |
| 2452 | assert 0 < score_call["timeout"] <= 12 - digg.SCORE_SEARCH_MARGIN |
| 2453 | assert score_call["deadline_monotonic"] == deadline - digg.SCORE_SEARCH_MARGIN |
| 2454 | # Stopping a stuck call takes up to two grace periods, which have to fit |
| 2455 | # in the margin too. |
| 2456 | assert 2 * score_call["cleanup_grace"] < digg.SCORE_SEARCH_MARGIN |
| 2457 | |
| 2458 | |
| 2459 | def test_score_call_is_skipped_when_too_little_time_is_left(monkeypatch): |
| 2460 | calls: list = [] |
| 2461 | answer = _live_envelope(_story()) |
| 2462 | out = _research_search( |
| 2463 | monkeypatch, _research_cli(answer, answer, calls), |
| 2464 | deadline=digg.time.monotonic() + digg.SCORE_SEARCH_MARGIN - 1, |
| 2465 | ) |
| 2466 | assert len(_search_calls(calls)) == 1 |
| 2467 | assert len(out["results"]) == 1 |
| 2468 | assert digg.score_pass_note(out) is None |
| 2469 |