| 1 | """Regression tests for PR 34: Reddit null-safety and canary outage reporting. |
| 2 | |
| 3 | Covers: |
| 4 | - HIGH-118: Non-dict JSON payloads and non-list/non-dict nested structures across |
| 5 | all Arctic Shift functions in `lib/reddit_arctic.py`. |
| 6 | - HIGH-120: ScrapeCreators null/non-list/non-dict payloads and score/field |
| 7 | coercion in `lib/reddit.py` (and `lib/reddit_enrich.py:enrich_reddit_item_sc`). |
| 8 | - HIGH-132: Null, non-dict, non-list, non-string, bool, NaN, Inf, and huge-int |
| 9 | inputs in `lib/reddit_enrich.py` (`parse_thread_data`, `get_top_comments`, |
| 10 | `stored_top_comments`, `extract_comment_insights`) and via |
| 11 | `reddit_session.thread_post`. |
| 12 | - HIGH-135: `reddit_canary.check_hydration` fails the canary when Arctic Shift |
| 13 | hydrates 0 of N discovered threads (ingestion stall) while still passing |
| 14 | hydrated threads with genuinely empty comment trees. |
| 15 | """ |
| 16 | |
| 17 | from __future__ import annotations |
| 18 | |
| 19 | import json |
| 20 | from datetime import datetime, timezone |
| 21 | from pathlib import Path |
| 22 | from types import SimpleNamespace |
| 23 | from unittest import mock |
| 24 | |
| 25 | import pytest |
| 26 | |
| 27 | import reddit_canary as canary |
| 28 | from lib import ( |
| 29 | env, |
| 30 | health, |
| 31 | http, |
| 32 | pipeline, |
| 33 | reddit, |
| 34 | reddit_arctic, |
| 35 | reddit_enrich, |
| 36 | reddit_health, |
| 37 | reddit_hydrate, |
| 38 | reddit_session, |
| 39 | schema, |
| 40 | ) |
| 41 | from lib.reddit_refs import ARCTIC, ARCTIC_PENDING, UNKNOWN, ThreadRef, canonical_thread |
| 42 | |
| 43 | ROOT = Path(__file__).resolve().parents[1] |
| 44 | FIXTURES = ROOT / "fixtures" |
| 45 | BRAVE_PAGE = (FIXTURES / "brave_reddit_serp.html").read_text(encoding="utf-8") |
| 46 | THREAD_SAMPLE = json.loads((FIXTURES / "reddit_session_thread.json").read_text(encoding="utf-8")) |
| 47 | NOW = datetime(2026, 11, 15, 13, 30, tzinfo=timezone.utc) |
| 48 | ARCTIC_KNOWN_OK = json.dumps({"data": [ |
| 49 | { |
| 50 | "id": pid, |
| 51 | "title": f"Known thread {pid}", |
| 52 | "subreddit": "test", |
| 53 | "score": 10, |
| 54 | "num_comments": 2, |
| 55 | "created_utc": 1740800000, |
| 56 | "permalink": f"/r/test/comments/{pid}/x/", |
| 57 | } |
| 58 | for pid in canary.KNOWN_THREAD_IDS |
| 59 | ]}) |
| 60 | |
| 61 | NON_DICT_OR_BAD_DATA_PAYLOADS = [ |
| 62 | None, |
| 63 | [], |
| 64 | ["unexpected"], |
| 65 | "error string", |
| 66 | 123, |
| 67 | True, |
| 68 | {"data": None}, |
| 69 | {"data": "not-a-list"}, |
| 70 | {"data": 42}, |
| 71 | {"data": {"nested": 1}}, |
| 72 | ] |
| 73 | |
| 74 | |
| 75 | @pytest.fixture(autouse=True) |
| 76 | def _clean_arctic_and_sc_state(): |
| 77 | reddit_arctic.reset_memo() |
| 78 | reddit.reset_scrapecreators_memo() |
| 79 | reddit_health.reset_run_state() |
| 80 | yield |
| 81 | reddit_arctic.reset_memo() |
| 82 | reddit.reset_scrapecreators_memo() |
| 83 | reddit_health.reset_run_state() |
| 84 | |
| 85 | |
| 86 | @pytest.fixture(autouse=True) |
| 87 | def _no_arctic_network(): |
| 88 | """Override conftest stub so Arctic Shift functions execute directly.""" |
| 89 | yield |
| 90 | |
| 91 | |
| 92 | # --------------------------------------------------------------------------- |
| 93 | # HIGH-118: Arctic Shift non-dict / non-list / hostile-row null safety |
| 94 | # --------------------------------------------------------------------------- |
| 95 | |
| 96 | |
| 97 | class TestHigh118ArcticShiftNullSafety: |
| 98 | @pytest.mark.parametrize("payload", NON_DICT_OR_BAD_DATA_PAYLOADS) |
| 99 | def test_search_once_does_not_raise_or_memoize_bad_payloads(self, payload): |
| 100 | url = f"{reddit_arctic.SEARCH_API}?subreddit=python&limit=5&sort=desc" |
| 101 | with mock.patch.object(reddit_arctic.http, "get", return_value=payload) as get: |
| 102 | first = reddit_arctic._search_once(url, deadline=reddit_arctic.time.monotonic() + 30) |
| 103 | second = reddit_arctic._search_once(url, deadline=reddit_arctic.time.monotonic() + 30) |
| 104 | assert first == payload |
| 105 | assert second == payload |
| 106 | assert get.call_count == 2 # invalid payloads must never be memoized |
| 107 | |
| 108 | @pytest.mark.parametrize("payload", NON_DICT_OR_BAD_DATA_PAYLOADS) |
| 109 | def test_fetch_scores_never_raises_on_malformed_payload(self, payload): |
| 110 | with mock.patch.object(reddit_arctic.http, "get", return_value=payload): |
| 111 | assert reddit_arctic.fetch_scores(["abc123"]) == {} |
| 112 | |
| 113 | def test_fetch_scores_skips_hostile_rows_and_keeps_valid_ones(self): |
| 114 | rows = [ |
| 115 | None, |
| 116 | "not-a-dict", |
| 117 | 123, |
| 118 | {"id": "bool_score", "score": True, "num_comments": 1}, |
| 119 | {"id": "nan_score", "score": float("nan"), "num_comments": 1}, |
| 120 | {"id": "inf_score", "score": float("inf"), "num_comments": 1}, |
| 121 | {"id": "bad_str", "score": "nope", "num_comments": 1}, |
| 122 | {"id": "t3_good1", "score": 19, "num_comments": 4}, |
| 123 | {"id": "good2", "score": 0, "num_comments": None}, |
| 124 | {"id": "good3", "score": "42", "num_comments": "7"}, |
| 125 | ] |
| 126 | with mock.patch.object(reddit_arctic.http, "get", return_value={"data": rows}): |
| 127 | out = reddit_arctic.fetch_scores( |
| 128 | ["bool_score", "nan_score", "inf_score", "bad_str", "good1", "good2", "good3"], |
| 129 | ) |
| 130 | assert out == { |
| 131 | "good1": {"score": 19, "num_comments": 4}, |
| 132 | "good2": {"score": 0, "num_comments": 0}, |
| 133 | "good3": {"score": 42, "num_comments": 7}, |
| 134 | } |
| 135 | |
| 136 | @pytest.mark.parametrize("payload", NON_DICT_OR_BAD_DATA_PAYLOADS) |
| 137 | def test_fetch_listings_never_raises_on_malformed_payload(self, payload): |
| 138 | with mock.patch.object(reddit_arctic.http, "get", return_value=payload): |
| 139 | assert reddit_arctic.fetch_listings(["python"]) == [] |
| 140 | |
| 141 | def test_fetch_listings_handles_non_dict_rows_and_hostile_fields(self): |
| 142 | rows = [ |
| 143 | None, |
| 144 | "bad-row", |
| 145 | { |
| 146 | "id": "p1", |
| 147 | "permalink": 12345, # non-string permalink -> empty url -> skipped |
| 148 | "title": None, |
| 149 | "score": float("inf"), |
| 150 | }, |
| 151 | { |
| 152 | "id": "t3_p2", |
| 153 | "permalink": "/r/python/comments/p2/ok/", |
| 154 | "title": 999, |
| 155 | "score": True, |
| 156 | "num_comments": float("nan"), |
| 157 | "created_utc": 10**20, |
| 158 | "author": None, |
| 159 | "subreddit": 42, |
| 160 | "selftext": True, |
| 161 | }, |
| 162 | { |
| 163 | "id": "t3_p3", |
| 164 | "permalink": "/r/python/comments/p3/good/", |
| 165 | "title": "Valid Python thread", |
| 166 | "score": "55", |
| 167 | "num_comments": 8, |
| 168 | "created_utc": 1783000000, |
| 169 | "author": "alice", |
| 170 | "subreddit": "python", |
| 171 | "selftext": None, |
| 172 | }, |
| 173 | ] |
| 174 | with mock.patch.object(reddit_arctic.http, "get", return_value={"data": rows}): |
| 175 | out = reddit_arctic.fetch_listings(["python"], query="python") |
| 176 | assert [p["metadata"]["post_id"] for p in out] == ["p2", "p3"] |
| 177 | p2, p3 = out |
| 178 | assert p2["score"] == 0 |
| 179 | assert p2["num_comments"] == 0 |
| 180 | assert p2["date"] is None |
| 181 | assert p2["author"] == "[deleted]" |
| 182 | assert p2["subreddit"] == "" |
| 183 | assert p2["selftext"] == "" |
| 184 | assert p3["score"] == 55 |
| 185 | assert p3["date"] == "2026-07-02" |
| 186 | assert p3["selftext"] == "" |
| 187 | |
| 188 | @pytest.mark.parametrize("payload", [ |
| 189 | None, |
| 190 | [], |
| 191 | ["err"], |
| 192 | "slow down", # non-dict string must not crash .get("error") |
| 193 | 123, |
| 194 | True, |
| 195 | {"data": None}, |
| 196 | {"data": "bad"}, |
| 197 | {"error": 500}, |
| 198 | {"error": None}, |
| 199 | ]) |
| 200 | def test_fetch_posts_by_ids_never_raises_on_non_dict_or_bad_data(self, payload): |
| 201 | with mock.patch.object(reddit_arctic.http, "get", return_value=payload): |
| 202 | out, state = reddit_arctic.fetch_posts_by_ids(["abc123"]) |
| 203 | assert out == {} |
| 204 | assert state == "down" |
| 205 | |
| 206 | @pytest.mark.parametrize("payload", [ |
| 207 | {"error": "Timeout. Maybe slow down a bit"}, |
| 208 | {"error": {"message": "please slow down"}}, |
| 209 | ]) |
| 210 | def test_fetch_posts_by_ids_detects_slow_down_error_dict_safely(self, payload): |
| 211 | with mock.patch.object(reddit_arctic.http, "get", return_value=payload): |
| 212 | out, state = reddit_arctic.fetch_posts_by_ids(["abc123"]) |
| 213 | assert out == {} |
| 214 | assert state == "throttled" |
| 215 | |
| 216 | @pytest.mark.parametrize("payload", NON_DICT_OR_BAD_DATA_PAYLOADS) |
| 217 | def test_fetch_comment_tree_never_raises_on_malformed_payload(self, payload): |
| 218 | with mock.patch.object(reddit_arctic.http, "get", return_value=payload): |
| 219 | assert reddit_arctic.fetch_comment_tree("abc123") is None |
| 220 | |
| 221 | @pytest.mark.parametrize("payload", NON_DICT_OR_BAD_DATA_PAYLOADS) |
| 222 | def test_fetch_post_comments_never_raises_on_malformed_payload(self, payload): |
| 223 | with mock.patch.object(reddit_arctic.http, "get", return_value=payload): |
| 224 | assert reddit_arctic.fetch_post_comments("abc123") == [] |
| 225 | |
| 226 | def test_comment_tree_and_post_comments_survive_malformed_replies_and_fields(self): |
| 227 | tree_payload = { |
| 228 | "data": [ |
| 229 | None, |
| 230 | "junk", |
| 231 | {"kind": "t1", "data": None}, |
| 232 | { |
| 233 | "kind": "t1", |
| 234 | "data": { |
| 235 | "id": "t1_c1", |
| 236 | "author": None, |
| 237 | "body": "should be skipped because author defaults to deleted", |
| 238 | "score": 100, |
| 239 | "replies": {"data": "not-a-dict"}, |
| 240 | }, |
| 241 | }, |
| 242 | { |
| 243 | "kind": "t1", |
| 244 | "data": { |
| 245 | "id": "t1_c2", |
| 246 | "author": "bob", |
| 247 | "body": 12345, |
| 248 | "score": float("inf"), |
| 249 | "depth": True, |
| 250 | "parent_id": "t3_abc123", |
| 251 | "permalink": 999, |
| 252 | "created_utc": 10**20, |
| 253 | "replies": {"data": {"children": "not-a-list"}}, |
| 254 | }, |
| 255 | }, |
| 256 | { |
| 257 | "kind": "t1", |
| 258 | "data": { |
| 259 | "id": "t1_c3", |
| 260 | "author": "carol", |
| 261 | "body": "Solid benchmark result.", |
| 262 | "score": "27", |
| 263 | "depth": 0, |
| 264 | "permalink": "/r/test/comments/abc123/x/c3/", |
| 265 | "created_utc": True, |
| 266 | "replies": { |
| 267 | "data": { |
| 268 | "children": [ |
| 269 | None, |
| 270 | { |
| 271 | "kind": "t1", |
| 272 | "data": { |
| 273 | "id": "t1_c4", |
| 274 | "author": "dave", |
| 275 | "body": "Nested reply.", |
| 276 | "score": True, |
| 277 | "depth": float("nan"), |
| 278 | "parent_id": "t1_c3", |
| 279 | "permalink": "/r/test/comments/abc123/x/c4/", |
| 280 | "created_utc": 1783000000, |
| 281 | }, |
| 282 | }, |
| 283 | ], |
| 284 | }, |
| 285 | }, |
| 286 | }, |
| 287 | }, |
| 288 | ], |
| 289 | } |
| 290 | with mock.patch.object(reddit_arctic.http, "get", return_value=tree_payload): |
| 291 | tree_comments = reddit_arctic.fetch_comment_tree("abc123") |
| 292 | reddit_arctic.reset_memo() |
| 293 | post_comments = reddit_arctic.fetch_post_comments("abc123") |
| 294 | |
| 295 | assert tree_comments is not None |
| 296 | assert [c["author"] for c in tree_comments] == ["bob", "carol", "dave"] |
| 297 | assert tree_comments[0]["score"] == 0 |
| 298 | assert tree_comments[0]["depth"] == 0 |
| 299 | assert tree_comments[0]["body"] == "12345" |
| 300 | assert tree_comments[0]["url"] == "" |
| 301 | assert tree_comments[0]["date"] is None |
| 302 | assert tree_comments[1]["score"] == 27 |
| 303 | assert tree_comments[1]["date"] is None |
| 304 | assert tree_comments[2]["score"] == 0 |
| 305 | assert tree_comments[2]["depth"] == 1 # parent_id t1_c3 when depth is NaN |
| 306 | assert tree_comments[2]["date"] == "2026-07-02" |
| 307 | |
| 308 | assert [c["author"] for c in post_comments] == ["carol", "bob", "dave"] |
| 309 | assert [c["score"] for c in post_comments] == [27, 0, 0] |
| 310 | assert post_comments[1]["depth"] == 0 # parent_id t3_ |
| 311 | assert post_comments[2]["depth"] == 1 # parent_id t1_ |
| 312 | |
| 313 | @pytest.mark.parametrize("raw_depth,parent_id,expected", [ |
| 314 | (True, "t1_abc", 1), |
| 315 | (False, "t1_abc", 1), |
| 316 | ("", "t1_abc", 1), |
| 317 | (" ", "t1_abc", 1), |
| 318 | (None, "t1_abc", 1), |
| 319 | (float("nan"), "t1_abc", 1), |
| 320 | (float("inf"), "t1_abc", 1), |
| 321 | (10**400, "t1_abc", 1), |
| 322 | ("bad", "t1_abc", 1), |
| 323 | (True, "t3_post", 0), |
| 324 | ("", "t3_post", 0), |
| 325 | (" ", "t3_post", 0), |
| 326 | (0, "t1_abc", 0), |
| 327 | (2, "t3_post", 2), |
| 328 | ("3", "t3_post", 3), |
| 329 | ]) |
| 330 | def test_comment_tree_and_post_comments_infer_nested_depth_from_parent_id( |
| 331 | self, raw_depth, parent_id, expected, |
| 332 | ): |
| 333 | tree_payload = { |
| 334 | "data": [ |
| 335 | { |
| 336 | "kind": "t1", |
| 337 | "data": { |
| 338 | "id": "t1_nested", |
| 339 | "author": "alice", |
| 340 | "body": "Nested reply body.", |
| 341 | "score": 11, |
| 342 | "depth": raw_depth, |
| 343 | "parent_id": parent_id, |
| 344 | "permalink": "/r/test/comments/abc123/x/nested/", |
| 345 | "created_utc": 1783000000, |
| 346 | }, |
| 347 | }, |
| 348 | ], |
| 349 | } |
| 350 | with mock.patch.object(reddit_arctic.http, "get", return_value=tree_payload): |
| 351 | tree_comments = reddit_arctic.fetch_comment_tree("abc123") |
| 352 | reddit_arctic.reset_memo() |
| 353 | post_comments = reddit_arctic.fetch_post_comments("abc123") |
| 354 | assert tree_comments is not None and len(tree_comments) == 1 |
| 355 | assert len(post_comments) == 1 |
| 356 | assert tree_comments[0]["depth"] == expected |
| 357 | assert post_comments[0]["depth"] == expected |
| 358 | |
| 359 | def test_huge_int_created_utc_and_score_do_not_overflow_downstream_hydrate(self): |
| 360 | post_row_huge_cnt = { |
| 361 | "id": "huge01", |
| 362 | "title": "Huge int Arctic post", |
| 363 | "permalink": "/r/python/comments/huge01/huge/", |
| 364 | "subreddit": "python", |
| 365 | "score": 10**400, |
| 366 | "num_comments": 10**400, |
| 367 | "created_utc": 10**400, |
| 368 | "author": "alice", |
| 369 | } |
| 370 | post_row_with_comments = { |
| 371 | "id": "huge02", |
| 372 | "title": "Huge int Arctic post with comments", |
| 373 | "permalink": "/r/python/comments/huge02/huge/", |
| 374 | "subreddit": "python", |
| 375 | "score": 10**400, |
| 376 | "num_comments": 5, |
| 377 | "created_utc": 10**400, |
| 378 | "author": "alice", |
| 379 | } |
| 380 | comment_tree = { |
| 381 | "data": [ |
| 382 | { |
| 383 | "kind": "t1", |
| 384 | "data": { |
| 385 | "id": "t1_chuge", |
| 386 | "author": "bob", |
| 387 | "body": "Comment with overflowing int fields.", |
| 388 | "score": 10**400, |
| 389 | "depth": 0, |
| 390 | "permalink": "/r/python/comments/huge02/huge/chuge/", |
| 391 | "created_utc": 10**400, |
| 392 | }, |
| 393 | }, |
| 394 | ], |
| 395 | } |
| 396 | ref1 = canonical_thread("https://www.reddit.com/r/python/comments/huge01/huge/") |
| 397 | ref2 = canonical_thread("https://www.reddit.com/r/python/comments/huge02/huge/") |
| 398 | assert ref1 is not None and ref2 is not None |
| 399 | ref1.provenance.add("web") |
| 400 | ref2.provenance.add("web") |
| 401 | |
| 402 | def fake_get(url, **_kwargs): |
| 403 | if reddit_arctic.COMMENTS_TREE_API in url: |
| 404 | return comment_tree |
| 405 | return {"data": [post_row_huge_cnt, post_row_with_comments]} |
| 406 | |
| 407 | with mock.patch.object(reddit_arctic.http, "get", side_effect=fake_get): |
| 408 | scores = reddit_arctic.fetch_scores(["huge01"]) |
| 409 | assert scores == {} # 10**400 score rejected by _strict_int |
| 410 | |
| 411 | hydration = reddit_hydrate.hydrate([ref1, ref2], topic="python", depth="quick", comments=True) |
| 412 | |
| 413 | assert hydration.arctic_state == "ok" |
| 414 | by_id = {it["metadata"]["post_id"]: it for it in hydration.items} |
| 415 | assert set(by_id) == {"huge01", "huge02"} |
| 416 | assert by_id["huge01"]["score"] == 0 |
| 417 | assert by_id["huge01"]["num_comments"] == 0 |
| 418 | assert by_id["huge01"]["created_utc"] is None |
| 419 | assert by_id["huge01"]["date"] is None |
| 420 | assert reddit_hydrate._discussion(by_id["huge01"]) == 0.0 |
| 421 | |
| 422 | assert by_id["huge02"]["score"] == 0 |
| 423 | assert by_id["huge02"]["num_comments"] == 5 |
| 424 | assert by_id["huge02"]["created_utc"] is None |
| 425 | assert reddit_hydrate._discussion(by_id["huge02"]) == 5.0 |
| 426 | assert len(by_id["huge02"]["top_comments"]) == 1 |
| 427 | assert by_id["huge02"]["top_comments"][0]["score"] == 0 |
| 428 | assert by_id["huge02"]["top_comments"][0]["created_utc"] is None |
| 429 | assert by_id["huge02"]["top_comments"][0]["date"] is None |
| 430 | |
| 431 | |
| 432 | # --------------------------------------------------------------------------- |
| 433 | # HIGH-120: ScrapeCreators null/non-list/non-dict payloads and score coercion |
| 434 | # --------------------------------------------------------------------------- |
| 435 | |
| 436 | |
| 437 | class TestHigh120ScrapeCreatorsNullSafety: |
| 438 | @pytest.mark.parametrize("payload", [ |
| 439 | None, |
| 440 | [], |
| 441 | ["oops"], |
| 442 | "error", |
| 443 | 123, |
| 444 | True, |
| 445 | {"posts": None}, |
| 446 | {"posts": "bad"}, |
| 447 | {"posts": 42}, |
| 448 | {"posts": {"nested": 1}}, |
| 449 | {"data": None}, |
| 450 | {"data": "bad"}, |
| 451 | {"posts": None, "data": None}, |
| 452 | ]) |
| 453 | def test_global_and_subreddit_search_coerce_malformed_payloads_to_empty(self, payload): |
| 454 | with mock.patch.object(reddit.http, "get", return_value=payload): |
| 455 | with http.capture_failures() as global_failures: |
| 456 | assert reddit._global_search("python", "dummy-token") == [] |
| 457 | with http.capture_failures() as sub_failures: |
| 458 | assert reddit._subreddit_search("python", "python", "dummy-token") == [] |
| 459 | assert len(global_failures) == 1 |
| 460 | assert global_failures[0].outcome_state == health.SCHEMA_DRIFT |
| 461 | assert len(sub_failures) == 1 |
| 462 | assert sub_failures[0].outcome_state == health.SCHEMA_DRIFT |
| 463 | |
| 464 | @pytest.mark.parametrize("payload", [ |
| 465 | {"posts": []}, |
| 466 | {"success": True, "posts": []}, |
| 467 | {"data": []}, |
| 468 | {"posts": None, "data": []}, |
| 469 | {"posts": None, "data": [{"id": "a"}]}, |
| 470 | ]) |
| 471 | def test_valid_empty_or_fallback_payloads_do_not_flag_schema_drift(self, payload): |
| 472 | with mock.patch.object(reddit.http, "get", return_value=payload): |
| 473 | with http.capture_failures() as failures: |
| 474 | reddit._global_search("python", "dummy-token") |
| 475 | reddit._subreddit_search("python", "python", "dummy-token") |
| 476 | assert failures == [] |
| 477 | |
| 478 | def test_partial_malformed_payload_keeps_valid_rows_and_flags_schema_drift(self): |
| 479 | with mock.patch.object( |
| 480 | reddit.http, "get", return_value={"posts": [{"id": "good"}, "bad", None]}, |
| 481 | ): |
| 482 | with http.capture_failures() as failures: |
| 483 | got = reddit._global_search("python", "dummy-token") |
| 484 | assert got == [{"id": "good"}] |
| 485 | assert len(failures) == 1 |
| 486 | assert failures[0].outcome_state == health.SCHEMA_DRIFT |
| 487 | |
| 488 | with mock.patch.object( |
| 489 | reddit.http, "get", return_value={"posts": "oops", "data": [{"id": "from_data"}]}, |
| 490 | ): |
| 491 | with http.capture_failures() as fallback_failures: |
| 492 | got = reddit._global_search("python", "dummy-token") |
| 493 | assert got == [{"id": "from_data"}] |
| 494 | assert len(fallback_failures) == 1 |
| 495 | assert fallback_failures[0].outcome_state == health.SCHEMA_DRIFT |
| 496 | |
| 497 | def test_pinned_scrapecreators_schema_drift_not_hidden_by_public_fallback(self): |
| 498 | cfg = { |
| 499 | "SCRAPECREATORS_API_KEY": "dummy-key", |
| 500 | env.REDDIT_BACKEND_PIN_VAR: "scrapecreators", |
| 501 | } |
| 502 | subquery = schema.SubQuery( |
| 503 | label="t", search_query="python", ranking_query="python", sources=["reddit"], |
| 504 | ) |
| 505 | runtime = schema.ProviderRuntime( |
| 506 | reasoning_provider="mock", planner_model="mock", rerank_model="mock", |
| 507 | ) |
| 508 | public_item = { |
| 509 | "url": "https://www.reddit.com/r/python/comments/pub01/t/", |
| 510 | "title": "python fallback thread", |
| 511 | "engagement": {"score": 40, "num_comments": 5}, |
| 512 | } |
| 513 | |
| 514 | # Case 1: pinned SC returns {"posts": null} and public fallback returns items -> |
| 515 | # fallback items survive, AND schema-drift is surfaced as the primary failure. |
| 516 | with mock.patch("lib.http.get", return_value={"posts": None}), \ |
| 517 | mock.patch("lib.reddit_public.search_reddit_public", return_value=[public_item]): |
| 518 | items, artifact = pipeline._retrieve_stream( |
| 519 | topic="python", |
| 520 | subquery=subquery, |
| 521 | source="reddit", |
| 522 | config=cfg, |
| 523 | depth="quick", |
| 524 | date_range=("2026-10-16", "2026-11-15"), |
| 525 | runtime=runtime, |
| 526 | mock=False, |
| 527 | ) |
| 528 | assert items == [public_item] |
| 529 | outcome = artifact.get("_source_outcome") or {} |
| 530 | assert outcome.get("state") == health.SCHEMA_DRIFT |
| 531 | assert "Reddit primary failed" in (outcome.get("detail") or "") |
| 532 | |
| 533 | # Case 2: pinned SC returns {"posts": null} and public fallback is empty -> |
| 534 | # fails with SourceRunError(SCHEMA_DRIFT), never silent empty no-results. |
| 535 | reddit.reset_scrapecreators_memo() |
| 536 | with mock.patch("lib.http.get", return_value={"posts": None}), \ |
| 537 | mock.patch("lib.reddit_public.search_reddit_public", return_value=[]): |
| 538 | with pytest.raises(pipeline.SourceRunError) as exc_info: |
| 539 | pipeline._retrieve_stream( |
| 540 | topic="python", |
| 541 | subquery=subquery, |
| 542 | source="reddit", |
| 543 | config=cfg, |
| 544 | depth="quick", |
| 545 | date_range=("2026-10-16", "2026-11-15"), |
| 546 | runtime=runtime, |
| 547 | mock=False, |
| 548 | ) |
| 549 | assert exc_info.value.outcome_state == health.SCHEMA_DRIFT |
| 550 | |
| 551 | # Case 3: pinned SC returns valid empty {"posts": []} and public fallback is empty -> |
| 552 | # clean empty result with no schema-drift error. |
| 553 | reddit.reset_scrapecreators_memo() |
| 554 | with mock.patch("lib.http.get", return_value={"posts": []}), \ |
| 555 | mock.patch("lib.reddit_public.search_reddit_public", return_value=[]): |
| 556 | items, artifact = pipeline._retrieve_stream( |
| 557 | topic="python", |
| 558 | subquery=subquery, |
| 559 | source="reddit", |
| 560 | config=cfg, |
| 561 | depth="quick", |
| 562 | date_range=("2026-10-16", "2026-11-15"), |
| 563 | runtime=runtime, |
| 564 | mock=False, |
| 565 | ) |
| 566 | assert items == [] |
| 567 | assert not artifact.get("_source_outcome") |
| 568 | |
| 569 | def test_pinned_scrapecreators_429_does_not_skip_subsequent_public_fallback_subqueries(self): |
| 570 | import threading |
| 571 | |
| 572 | cfg = { |
| 573 | "SCRAPECREATORS_API_KEY": "dummy-key", |
| 574 | env.REDDIT_BACKEND_PIN_VAR: "scrapecreators", |
| 575 | } |
| 576 | runtime = schema.ProviderRuntime( |
| 577 | reasoning_provider="mock", planner_model="mock", rerank_model="mock", |
| 578 | ) |
| 579 | sq1 = schema.SubQuery( |
| 580 | label="q1", search_query="python", ranking_query="python", sources=["reddit"], |
| 581 | ) |
| 582 | sq2 = schema.SubQuery( |
| 583 | label="q2", search_query="rust", ranking_query="rust", sources=["reddit"], |
| 584 | ) |
| 585 | pub_q1 = { |
| 586 | "url": "https://www.reddit.com/r/python/comments/pub01/t/", |
| 587 | "title": "python public fallback", |
| 588 | "engagement": {"score": 40, "num_comments": 5}, |
| 589 | } |
| 590 | pub_q2 = { |
| 591 | "url": "https://www.reddit.com/r/rust/comments/pub02/t/", |
| 592 | "title": "rust public fallback", |
| 593 | "engagement": {"score": 35, "num_comments": 4}, |
| 594 | } |
| 595 | |
| 596 | def sc_http_429(*_args, **_kwargs): |
| 597 | http._raise(http.HTTPError("HTTP 429: Too Many Requests", status_code=429)) |
| 598 | |
| 599 | def fake_public(query, *_args, **_kwargs): |
| 600 | return [pub_q1] if "python" in query else [pub_q2] |
| 601 | |
| 602 | rate_limited_sources: set[str] = set() |
| 603 | rate_limit_lock = threading.Lock() |
| 604 | |
| 605 | with mock.patch("lib.http.get", side_effect=sc_http_429), \ |
| 606 | mock.patch("lib.reddit_public.search_reddit_public", side_effect=fake_public) as pub_mock: |
| 607 | items1, artifact1 = pipeline._retrieve_stream( |
| 608 | topic="python", |
| 609 | subquery=sq1, |
| 610 | source="reddit", |
| 611 | config=cfg, |
| 612 | depth="quick", |
| 613 | date_range=("2026-10-16", "2026-11-15"), |
| 614 | runtime=runtime, |
| 615 | mock=False, |
| 616 | rate_limited_sources=rate_limited_sources, |
| 617 | rate_limit_lock=rate_limit_lock, |
| 618 | ) |
| 619 | assert items1 == [pub_q1] |
| 620 | assert "reddit" not in rate_limited_sources |
| 621 | outcome1 = artifact1.get("_source_outcome") or {} |
| 622 | assert outcome1.get("state") == health.PARTIAL |
| 623 | assert "429" in (outcome1.get("detail") or "") |
| 624 | assert "Reddit primary failed" in (outcome1.get("detail") or "") |
| 625 | |
| 626 | items2, artifact2 = pipeline._retrieve_stream( |
| 627 | topic="rust", |
| 628 | subquery=sq2, |
| 629 | source="reddit", |
| 630 | config=cfg, |
| 631 | depth="quick", |
| 632 | date_range=("2026-10-16", "2026-11-15"), |
| 633 | runtime=runtime, |
| 634 | mock=False, |
| 635 | rate_limited_sources=rate_limited_sources, |
| 636 | rate_limit_lock=rate_limit_lock, |
| 637 | ) |
| 638 | |
| 639 | assert items2 == [pub_q2] |
| 640 | assert pub_mock.call_count == 2 |
| 641 | assert "reddit" not in rate_limited_sources |
| 642 | outcome2 = artifact2.get("_source_outcome") or {} |
| 643 | assert outcome2.get("state") == health.PARTIAL |
| 644 | assert "429" in (outcome2.get("detail") or "") |
| 645 | |
| 646 | # When public fallback ALSO returns nothing, total failure still classifies |
| 647 | # as RATE_LIMITED and marks the source rate-limited. |
| 648 | reddit.reset_scrapecreators_memo() |
| 649 | empty_rate_limited: set[str] = set() |
| 650 | with mock.patch("lib.http.get", side_effect=sc_http_429), \ |
| 651 | mock.patch("lib.reddit_public.search_reddit_public", return_value=[]): |
| 652 | with pytest.raises(pipeline.SourceRunError) as exc_info: |
| 653 | pipeline._retrieve_stream( |
| 654 | topic="python", |
| 655 | subquery=sq1, |
| 656 | source="reddit", |
| 657 | config=cfg, |
| 658 | depth="quick", |
| 659 | date_range=("2026-10-16", "2026-11-15"), |
| 660 | runtime=runtime, |
| 661 | mock=False, |
| 662 | rate_limited_sources=empty_rate_limited, |
| 663 | rate_limit_lock=rate_limit_lock, |
| 664 | ) |
| 665 | assert exc_info.value.outcome_state == health.RATE_LIMITED |
| 666 | assert "reddit" in empty_rate_limited |
| 667 | |
| 668 | @pytest.mark.parametrize("payload", [ |
| 669 | None, |
| 670 | [], |
| 671 | ["oops"], |
| 672 | "error", |
| 673 | 123, |
| 674 | True, |
| 675 | {"comments": None}, |
| 676 | {"comments": "bad"}, |
| 677 | {"comments": 99}, |
| 678 | {"data": None}, |
| 679 | {"data": "bad"}, |
| 680 | {"comments": None, "data": None}, |
| 681 | ]) |
| 682 | def test_fetch_post_comments_coerces_malformed_payloads_to_empty(self, payload): |
| 683 | with mock.patch.object(reddit.http, "get", return_value=payload): |
| 684 | assert reddit.fetch_post_comments("https://www.reddit.com/r/test/comments/abc/", "dummy-token") == [] |
| 685 | |
| 686 | def test_extract_payloads_filter_non_dicts_and_fallback_only_when_primary_not_list(self): |
| 687 | with mock.patch.object( |
| 688 | reddit.http, "get", return_value={"posts": None, "data": [{"id": "a"}, None, "bad", 7]}, |
| 689 | ): |
| 690 | assert reddit._global_search("python", "dummy-token") == [{"id": "a"}] |
| 691 | |
| 692 | with mock.patch.object( |
| 693 | reddit.http, "get", return_value={"posts": [], "data": [{"id": "should_not_use"}]}, |
| 694 | ): |
| 695 | assert reddit._global_search("python", "dummy-token") == [] |
| 696 | |
| 697 | with mock.patch.object( |
| 698 | reddit.http, "get", return_value={"comments": [None, {"body": "real"}, "bad", 1]}, |
| 699 | ): |
| 700 | assert reddit.fetch_post_comments("https://www.reddit.com/r/test/comments/abc/", "dummy-token") == [ |
| 701 | {"body": "real"}, |
| 702 | ] |
| 703 | |
| 704 | def test_search_reddit_survives_null_non_list_and_non_dict_entries(self): |
| 705 | good_post = { |
| 706 | "id": "t3_abc1", |
| 707 | "title": "Python 3.14 benchmarks", |
| 708 | "permalink": "/r/python/comments/abc1/benchmarks/", |
| 709 | "subreddit": "python", |
| 710 | "ups": 0, |
| 711 | "score": 99, # ups=0 must win over score=99 |
| 712 | "num_comments": None, |
| 713 | "created_utc": 1794268800, |
| 714 | "selftext": None, |
| 715 | } |
| 716 | hostile_post = { |
| 717 | "id": "t3_abc2", |
| 718 | "title": "Python release notes", |
| 719 | "permalink": None, |
| 720 | "url": 12345, |
| 721 | "subreddit": None, |
| 722 | "ups": True, |
| 723 | "score": float("nan"), |
| 724 | "votes": "14", |
| 725 | "num_comments": "bad", |
| 726 | "created_utc": 10**20, |
| 727 | "selftext": True, |
| 728 | } |
| 729 | with mock.patch.object(reddit, "_subreddit_search", side_effect=[None, "bad"]), \ |
| 730 | mock.patch.object(reddit, "_global_search", return_value=[None, "junk", good_post, hostile_post]): |
| 731 | res = reddit.search_reddit( |
| 732 | "Python", |
| 733 | "2026-10-16", |
| 734 | "2026-11-15", |
| 735 | depth="quick", |
| 736 | token="dummy-token", |
| 737 | subreddits=["python"], |
| 738 | ) |
| 739 | items = res["items"] |
| 740 | assert len(items) == 2 |
| 741 | by_rid = {it["reddit_id"]: it for it in items} |
| 742 | assert by_rid["abc1"]["engagement"]["score"] == 0 |
| 743 | assert by_rid["abc1"]["engagement"]["num_comments"] == 0 |
| 744 | assert by_rid["abc1"]["selftext"] == "" |
| 745 | assert by_rid["abc2"]["engagement"]["score"] == 14 |
| 746 | assert by_rid["abc2"]["engagement"]["num_comments"] == 0 |
| 747 | assert by_rid["abc2"]["subreddit"] == "" |
| 748 | assert by_rid["abc2"]["url"] == "" |
| 749 | assert by_rid["abc2"]["date"] is None |
| 750 | |
| 751 | def test_enrich_with_comments_coerces_scores_and_survives_malformed_comments(self): |
| 752 | items = [ |
| 753 | { |
| 754 | "id": "R1", |
| 755 | "url": "https://www.reddit.com/r/test/comments/abc1/post/", |
| 756 | "engagement": {"score": None, "num_comments": "12"}, |
| 757 | }, |
| 758 | { |
| 759 | "id": "R2", |
| 760 | "url": "https://www.reddit.com/r/test/comments/abc2/post/", |
| 761 | "engagement": None, |
| 762 | }, |
| 763 | ] |
| 764 | mixed_comments = [ |
| 765 | None, |
| 766 | "not-a-dict", |
| 767 | 123, |
| 768 | {"body": "both null scores", "ups": None, "score": None, "author": "null_user"}, |
| 769 | {"body": "zero ups must beat score 5", "ups": 0, "score": 5, "author": "zero_ups"}, |
| 770 | {"body": "fallback to score 5", "ups": None, "score": 5, "author": "fallback_score"}, |
| 771 | {"body": "bool ups must not be 1", "ups": True, "score": None, "author": "bool_ups"}, |
| 772 | {"body": "nan ups", "ups": float("nan"), "author": "nan_ups"}, |
| 773 | {"body": "inf ups", "ups": float("inf"), "author": "inf_ups"}, |
| 774 | {"body": "string int score", "ups": "25", "author": "str_int"}, |
| 775 | {"body": "bad ups falls back to score", "ups": "oops", "score": 12, "author": "bad_ups_fallback"}, |
| 776 | {"body": "negative score", "ups": -3, "author": "neg_user"}, |
| 777 | {"body": 12345, "ups": 1, "author": None, "permalink": 999, "created_utc": 10**20}, |
| 778 | ] |
| 779 | |
| 780 | def fake_fetch(url, token, **_kwargs): |
| 781 | if "abc1" in url: |
| 782 | return mixed_comments |
| 783 | return "not-a-list" |
| 784 | |
| 785 | with mock.patch.object(reddit, "fetch_post_comments", side_effect=fake_fetch): |
| 786 | out = reddit.enrich_with_comments(items, token="dummy-token", depth="quick", budget_seconds=10) |
| 787 | |
| 788 | enriched = {it["id"]: it for it in out} |
| 789 | top = enriched["R1"]["top_comments"] |
| 790 | assert len(top) == 10 |
| 791 | assert [c["score"] for c in top] == [25, 12, 5, 1, 0, 0, 0, 0, 0, -3] |
| 792 | by_author = {c["author"]: c for c in top} |
| 793 | assert by_author["zero_ups"]["score"] == 0 |
| 794 | assert by_author["fallback_score"]["score"] == 5 |
| 795 | assert by_author["bool_ups"]["score"] == 0 |
| 796 | assert by_author["nan_ups"]["score"] == 0 |
| 797 | assert by_author["inf_ups"]["score"] == 0 |
| 798 | assert by_author["str_int"]["score"] == 25 |
| 799 | assert by_author["bad_ups_fallback"]["score"] == 12 |
| 800 | assert by_author["[deleted]"]["excerpt"] == "12345" |
| 801 | assert by_author["[deleted]"]["url"] == "" |
| 802 | assert by_author["[deleted]"]["date"] is None |
| 803 | assert "top_comments" not in enriched["R2"] |
| 804 | |
| 805 | def test_enrich_reddit_item_sc_coerces_scores_and_survives_malformed_comments(self): |
| 806 | item = {"url": "https://www.reddit.com/r/test/comments/abc1/post/"} |
| 807 | raw_comments = [ |
| 808 | None, |
| 809 | "bad", |
| 810 | {"body": "null score", "ups": None, "score": None, "author": "u_null"}, |
| 811 | {"body": "zero ups", "ups": 0, "score": 9, "author": "u_zero"}, |
| 812 | {"body": "bool score", "ups": True, "score": None, "author": "u_bool"}, |
| 813 | {"body": "string score", "ups": "18", "author": "u_str", "created_utc": 10**20}, |
| 814 | {"body": 54321, "ups": 4, "author": None, "permalink": 123}, |
| 815 | ] |
| 816 | with mock.patch.object(reddit, "fetch_post_comments", return_value=raw_comments): |
| 817 | out = reddit_enrich.enrich_reddit_item_sc(item, "dummy-token") |
| 818 | scores = [(c["author"], c["score"]) for c in out["top_comments"]] |
| 819 | assert scores == [ |
| 820 | ("u_str", 18), |
| 821 | ("[deleted]", 4), |
| 822 | ("u_null", 0), |
| 823 | ("u_zero", 0), |
| 824 | ("u_bool", 0), |
| 825 | ] |
| 826 | assert out["top_comments"][0]["date"] is None |
| 827 | assert out["top_comments"][1]["url"] == "" |
| 828 | assert out["top_comments"][1]["excerpt"] == "54321" |
| 829 | |
| 830 | def test_discover_subreddits_and_extract_helpers_handle_malformed_fields(self): |
| 831 | results = [ |
| 832 | None, |
| 833 | "bad", |
| 834 | {"subreddit": None, "ups": 500}, |
| 835 | {"subreddit": "python", "ups": "500"}, |
| 836 | {"subreddit": "rust", "ups": True, "score": float("nan")}, |
| 837 | {"subreddit": {"name": "golang"}, "ups": 0, "score": 999}, |
| 838 | ] |
| 839 | subs = reddit.discover_subreddits(results, topic="python", max_subs=5) |
| 840 | assert subs[0] == "python" |
| 841 | assert "None" not in subs |
| 842 | assert reddit._extract_score({"ups": 0, "score": 5}) == 0 |
| 843 | assert reddit._extract_score({"ups": True, "score": None}) == 0 |
| 844 | assert reddit._extract_score({"ups": float("nan"), "score": float("inf")}) == 0 |
| 845 | assert reddit._extract_score({"ups": "33"}) == 33 |
| 846 | assert reddit.parse_reddit_response(None) == [] # type: ignore[arg-type] |
| 847 | assert reddit.parse_reddit_response({"items": [None, {"id": "R1"}]}) == [{"id": "R1"}] |
| 848 | |
| 849 | @pytest.mark.parametrize("bad_ratio,expected", [ |
| 850 | ("bad", None), |
| 851 | ([], None), |
| 852 | (10**400, None), |
| 853 | (float("nan"), None), |
| 854 | (float("inf"), None), |
| 855 | (True, None), |
| 856 | (0.87, 0.87), |
| 857 | ("0.92", 0.92), |
| 858 | ]) |
| 859 | def test_normalize_post_coerces_upvote_ratio_safely(self, bad_ratio, expected): |
| 860 | post = { |
| 861 | "id": "t3_ur1", |
| 862 | "title": "Python ratios", |
| 863 | "permalink": "/r/python/comments/ur1/ratios/", |
| 864 | "subreddit": "python", |
| 865 | "ups": 10, |
| 866 | "num_comments": 2, |
| 867 | "upvote_ratio": bad_ratio, |
| 868 | } |
| 869 | normalized = reddit._normalize_post(post, 1, "global", query="python") |
| 870 | assert normalized["engagement"]["upvote_ratio"] == expected |
| 871 | |
| 872 | def test_extract_subreddit_name_and_date_fallback_past_corrupt_primary_fields(self): |
| 873 | assert reddit._extract_subreddit_name({"name": True, "display_name": "python"}) == "python" |
| 874 | assert reddit._extract_subreddit_name({"name": " ", "display_name": "LocalLLM"}) == "LocalLLM" |
| 875 | assert reddit._extract_subreddit_name({"name": True, "display_name": False}) == "" |
| 876 | |
| 877 | assert reddit._extract_date({ |
| 878 | "created_utc": float("nan"), |
| 879 | "created_at": "2026-11-10T12:00:00Z", |
| 880 | }) == "2026-11-10" |
| 881 | assert reddit._extract_date({ |
| 882 | "created_utc": True, |
| 883 | "created_at": "not-a-date", |
| 884 | "created_at_iso": "2026-11-09T00:00:00Z", |
| 885 | }) == "2026-11-09" |
| 886 | assert reddit._extract_date({ |
| 887 | "created_utc": 10**20, |
| 888 | "created_at": "2026-11-08T00:00:00Z", |
| 889 | }) == "2026-11-08" |
| 890 | |
| 891 | |
| 892 | # --------------------------------------------------------------------------- |
| 893 | # HIGH-132: reddit_enrich parse_thread_data & get_top_comments null safety |
| 894 | # --------------------------------------------------------------------------- |
| 895 | |
| 896 | |
| 897 | class TestHigh132RedditEnrichNullSafety: |
| 898 | @pytest.mark.parametrize("payload", [ |
| 899 | [{"data": None}, {"data": None}], |
| 900 | [{"data": "not-a-dict"}, {"data": 123}], |
| 901 | [{"data": {"children": None}}, {"data": {"children": None}}], |
| 902 | [{"data": {"children": "not-a-list"}}, {"data": {"children": 42}}], |
| 903 | [{"data": {"children": [None]}}, {"data": {"children": [None, "junk", 123]}}], |
| 904 | [{"data": {"children": [{"data": None}]}}, {"data": {"children": [{"kind": "t1", "data": None}]}}], |
| 905 | [{"data": {"children": [{"data": "bad"}]}}, {"data": {"children": [{"kind": "t1", "data": "bad"}]}}], |
| 906 | ]) |
| 907 | def test_parse_thread_data_survives_malformed_nested_structures(self, payload): |
| 908 | parsed = reddit_enrich.parse_thread_data(payload) |
| 909 | assert parsed == {"submission": None, "comments": []} |
| 910 | |
| 911 | def test_parse_thread_data_coerces_hostile_submission_and_comment_fields(self): |
| 912 | payload = [ |
| 913 | { |
| 914 | "data": { |
| 915 | "children": [ |
| 916 | { |
| 917 | "kind": "t3", |
| 918 | "data": { |
| 919 | "score": True, |
| 920 | "num_comments": float("inf"), |
| 921 | "upvote_ratio": float("nan"), |
| 922 | "created_utc": 10**20, |
| 923 | "permalink": 123, |
| 924 | "title": None, |
| 925 | "selftext": None, |
| 926 | }, |
| 927 | }, |
| 928 | ], |
| 929 | }, |
| 930 | }, |
| 931 | { |
| 932 | "data": { |
| 933 | "children": [ |
| 934 | None, |
| 935 | "junk", |
| 936 | {"kind": "t1", "data": {"body": None, "score": 50, "author": "skip_null"}}, |
| 937 | {"kind": "t1", "data": {"body": True, "score": 50, "author": "skip_bool"}}, |
| 938 | { |
| 939 | "kind": "t1", |
| 940 | "data": { |
| 941 | "body": "Hidden score comment", |
| 942 | "score": None, |
| 943 | "author": "alice", |
| 944 | "created_utc": True, |
| 945 | "permalink": "/r/test/comments/x/t/c1/", |
| 946 | }, |
| 947 | }, |
| 948 | { |
| 949 | "kind": "t1", |
| 950 | "data": { |
| 951 | "body": 123456, |
| 952 | "score": True, |
| 953 | "author": None, |
| 954 | "created_utc": float("inf"), |
| 955 | "permalink": 999, |
| 956 | }, |
| 957 | }, |
| 958 | { |
| 959 | "kind": "t1", |
| 960 | "data": { |
| 961 | "body": "NaN score comment", |
| 962 | "score": float("nan"), |
| 963 | "author": "bob", |
| 964 | "created_utc": float("nan"), |
| 965 | }, |
| 966 | }, |
| 967 | { |
| 968 | "kind": "t1", |
| 969 | "data": { |
| 970 | "body": "Inf score comment", |
| 971 | "score": float("inf"), |
| 972 | "author": "carol", |
| 973 | "created_utc": 10**20, |
| 974 | }, |
| 975 | }, |
| 976 | { |
| 977 | "kind": "t1", |
| 978 | "data": { |
| 979 | "body": "x" * 700, |
| 980 | "score": "42", |
| 981 | "author": "dave", |
| 982 | "created_utc": 1714694957, |
| 983 | "is_submitter": True, |
| 984 | }, |
| 985 | }, |
| 986 | ], |
| 987 | }, |
| 988 | }, |
| 989 | ] |
| 990 | |
| 991 | parsed = reddit_enrich.parse_thread_data(payload) |
| 992 | sub = parsed["submission"] |
| 993 | assert sub == { |
| 994 | "score": None, |
| 995 | "num_comments": None, |
| 996 | "upvote_ratio": None, |
| 997 | "created_utc": None, |
| 998 | "permalink": None, |
| 999 | "title": None, |
| 1000 | "selftext": "", |
| 1001 | } |
| 1002 | comments = parsed["comments"] |
| 1003 | assert len(comments) == 5 |
| 1004 | assert [c["score"] for c in comments] == [0, 0, 0, 0, 42] |
| 1005 | assert comments[0]["created_utc"] is None |
| 1006 | assert comments[1]["body"] == "123456" |
| 1007 | assert comments[1]["author"] == "[deleted]" |
| 1008 | assert comments[1]["permalink"] is None |
| 1009 | assert comments[1]["created_utc"] is None |
| 1010 | assert comments[2]["created_utc"] is None |
| 1011 | assert comments[3]["created_utc"] is None |
| 1012 | assert len(comments[4]["body"]) == 600 |
| 1013 | assert comments[4]["created_utc"] == 1714694957 |
| 1014 | assert comments[4]["is_submitter"] is True |
| 1015 | |
| 1016 | top = reddit_enrich.get_top_comments(comments, limit=10) |
| 1017 | assert top[0]["author"] == "dave" |
| 1018 | assert all(c["author"] != "[deleted]" for c in top) |
| 1019 | |
| 1020 | stored = reddit_enrich.stored_top_comments(top) |
| 1021 | assert stored[0]["score"] == 42 |
| 1022 | assert stored[0]["date"] == "2024-05-03" |
| 1023 | assert stored[0]["is_uploader"] is True |
| 1024 | assert all(c["date"] is None for c in stored[1:]) |
| 1025 | |
| 1026 | def test_parse_thread_data_handles_huge_int_upvote_ratio_and_scores_without_overflow(self): |
| 1027 | payload = [ |
| 1028 | { |
| 1029 | "data": { |
| 1030 | "children": [ |
| 1031 | { |
| 1032 | "kind": "t3", |
| 1033 | "data": { |
| 1034 | "score": 10**400, |
| 1035 | "num_comments": 10**400, |
| 1036 | "upvote_ratio": 10**400, |
| 1037 | "created_utc": 10**400, |
| 1038 | "title": "Overflow test", |
| 1039 | "selftext": "ok", |
| 1040 | }, |
| 1041 | }, |
| 1042 | ], |
| 1043 | }, |
| 1044 | }, |
| 1045 | { |
| 1046 | "data": { |
| 1047 | "children": [ |
| 1048 | { |
| 1049 | "kind": "t1", |
| 1050 | "data": { |
| 1051 | "body": "Overflow comment", |
| 1052 | "score": 10**400, |
| 1053 | "author": "alice", |
| 1054 | "created_utc": 10**400, |
| 1055 | }, |
| 1056 | }, |
| 1057 | ], |
| 1058 | }, |
| 1059 | }, |
| 1060 | ] |
| 1061 | parsed = reddit_enrich.parse_thread_data(payload) |
| 1062 | assert parsed["submission"]["score"] is None |
| 1063 | assert parsed["submission"]["num_comments"] is None |
| 1064 | assert parsed["submission"]["upvote_ratio"] is None |
| 1065 | assert parsed["submission"]["created_utc"] is None |
| 1066 | assert len(parsed["comments"]) == 1 |
| 1067 | assert parsed["comments"][0]["score"] == 0 |
| 1068 | assert parsed["comments"][0]["created_utc"] is None |
| 1069 | |
| 1070 | def test_get_top_comments_stored_and_insights_handle_direct_hostile_inputs(self): |
| 1071 | assert reddit_enrich.get_top_comments(None) == [] # type: ignore[arg-type] |
| 1072 | assert reddit_enrich.stored_top_comments(None) == [] # type: ignore[arg-type] |
| 1073 | assert reddit_enrich.extract_comment_insights(None) == [] # type: ignore[arg-type] |
| 1074 | |
| 1075 | raw = [ |
| 1076 | None, |
| 1077 | "junk", |
| 1078 | {"score": None, "author": "null_s", "body": "a" * 40, "created_utc": 10**20}, |
| 1079 | {"score": True, "author": "bool_s", "body": 98765, "created_utc": True, "permalink": 42}, |
| 1080 | {"score": float("nan"), "author": "nan_s", "body": None, "created_utc": float("inf")}, |
| 1081 | {"score": float("inf"), "author": "inf_s", "body": "b" * 40}, |
| 1082 | {"score": "20", "author": "str_s", "body": "Substantive technical comment with real detail."}, |
| 1083 | {"score": 10, "author": "int_s", "body": "Another helpful technical explanation here."}, |
| 1084 | {"score": -5, "author": "neg_s", "body": "Downvoted remark."}, |
| 1085 | {"score": 999, "author": "[deleted]", "body": "Should be filtered out."}, |
| 1086 | ] |
| 1087 | top = reddit_enrich.get_top_comments(raw, limit=10) |
| 1088 | assert [c["author"] for c in top[:2]] == ["str_s", "int_s"] |
| 1089 | assert top[-1]["author"] == "neg_s" |
| 1090 | assert all(c["author"] != "[deleted]" for c in top) |
| 1091 | |
| 1092 | stored = reddit_enrich.stored_top_comments(top) |
| 1093 | assert [c["score"] for c in stored[:2]] == [20, 10] |
| 1094 | assert stored[-1]["score"] == -5 |
| 1095 | assert all(c["date"] is None for c in stored) |
| 1096 | |
| 1097 | insights = reddit_enrich.extract_comment_insights(top) |
| 1098 | assert "Substantive technical comment with real detail." in insights |
| 1099 | |
| 1100 | def test_reddit_session_thread_post_survives_null_selftext_and_hidden_comment_scores(self): |
| 1101 | data = json.loads(json.dumps(THREAD_SAMPLE)) |
| 1102 | post_data = data[0]["data"]["children"][0]["data"] |
| 1103 | post_data["selftext"] = None |
| 1104 | data[1]["data"]["children"] = [ |
| 1105 | None, |
| 1106 | { |
| 1107 | "kind": "t1", |
| 1108 | "data": { |
| 1109 | "body": "Hidden-score comment on a real thread", |
| 1110 | "score": None, |
| 1111 | "author": "hidden_user", |
| 1112 | "created_utc": 10**20, |
| 1113 | "permalink": "/r/Ghostty/comments/abc/t/c1/", |
| 1114 | }, |
| 1115 | }, |
| 1116 | { |
| 1117 | "kind": "t1", |
| 1118 | "data": { |
| 1119 | "body": 404, |
| 1120 | "score": True, |
| 1121 | "author": "weird_user", |
| 1122 | "created_utc": True, |
| 1123 | }, |
| 1124 | }, |
| 1125 | { |
| 1126 | "kind": "t1", |
| 1127 | "data": { |
| 1128 | "body": "Top scored real comment", |
| 1129 | "score": 88, |
| 1130 | "author": "real_user", |
| 1131 | "created_utc": 1794268800, |
| 1132 | "permalink": "/r/Ghostty/comments/abc/t/c2/", |
| 1133 | }, |
| 1134 | }, |
| 1135 | ] |
| 1136 | session = reddit_session.Session("dummy-pr34-cookie-0123456789", browser="chrome") |
| 1137 | post = reddit_session.thread_post(data, session) |
| 1138 | assert post is not None |
| 1139 | assert not post.get("_drop") |
| 1140 | assert post["selftext"] == "" |
| 1141 | assert [c["author"] for c in post["top_comments"]] == ["real_user", "hidden_user", "weird_user"] |
| 1142 | assert [c["score"] for c in post["top_comments"]] == [88, 0, 0] |
| 1143 | assert post["top_comments"][0]["date"] == "2026-11-10" |
| 1144 | assert post["top_comments"][1]["date"] is None |
| 1145 | assert post["top_comments"][2]["date"] is None |
| 1146 | |
| 1147 | |
| 1148 | # --------------------------------------------------------------------------- |
| 1149 | # HIGH-135: Canary check_hydration detects Arctic Shift ingestion stalls |
| 1150 | # --------------------------------------------------------------------------- |
| 1151 | |
| 1152 | |
| 1153 | def _canary_fetcher(pages: dict[str, tuple[int | None, str]]): |
| 1154 | def fetch(url: str, accept: str = "text/html"): |
| 1155 | for prefix, answer in pages.items(): |
| 1156 | if url.startswith(prefix): |
| 1157 | return answer |
| 1158 | raise AssertionError(f"unexpected fetch {url}") |
| 1159 | |
| 1160 | return fetch |
| 1161 | |
| 1162 | |
| 1163 | def _sample_refs(n: int = 3) -> list[ThreadRef]: |
| 1164 | refs: list[ThreadRef] = [] |
| 1165 | for i in range(n): |
| 1166 | ref = canonical_thread(f"https://www.reddit.com/r/ClaudeAI/comments/st{i:04d}/topic/") |
| 1167 | assert ref is not None |
| 1168 | ref.provenance.add("web") |
| 1169 | ref.title = f"Claude Code thread {i}" |
| 1170 | refs.append(ref) |
| 1171 | return refs |
| 1172 | |
| 1173 | |
| 1174 | class TestHigh135CanaryHydrationOutageDetection: |
| 1175 | def test_ingestion_stall_through_real_hydrator_fails_canary(self, tmp_path): |
| 1176 | """Arctic Shift returning 200 {"data": []} for all recent refs while old |
| 1177 | KNOWN_THREAD_IDS still resolve must fail the canary as DOWN.""" |
| 1178 | pages = { |
| 1179 | "https://search.brave.com/": (200, BRAVE_PAGE), |
| 1180 | "https://html.duckduckgo.com/": (202, ""), |
| 1181 | "https://www.startpage.com/": (429, ""), |
| 1182 | reddit_arctic.API: (200, ARCTIC_KNOWN_OK), |
| 1183 | } |
| 1184 | with mock.patch.object(reddit_arctic.http, "get", return_value={"data": []}): |
| 1185 | code, report = canary.run( |
| 1186 | fetch=_canary_fetcher(pages), |
| 1187 | hydrate=reddit_hydrate.hydrate, |
| 1188 | topics=("Claude Code",), |
| 1189 | state_file=tmp_path / "state.json", |
| 1190 | now=NOW, |
| 1191 | sleep=lambda _s: None, |
| 1192 | ) |
| 1193 | |
| 1194 | states = {c["name"]: c["state"] for c in report["checks"]} |
| 1195 | hydrate_check = next(c for c in report["checks"] if c["name"] == "hydrate: Claude Code") |
| 1196 | assert states["arctic: known ids"] == canary.OK |
| 1197 | assert states["hydrate: Claude Code"] == canary.DOWN |
| 1198 | assert hydrate_check["results"] == 0 |
| 1199 | assert "0 of " in hydrate_check["note"] |
| 1200 | assert code == 1 |
| 1201 | assert any("hydrate: Claude Code" in reason and "Arctic hydration is down" in reason for reason in report["failures"]) |
| 1202 | |
| 1203 | def test_check_hydration_zero_filled_is_down_for_ok_and_unused(self): |
| 1204 | refs = _sample_refs(3) |
| 1205 | |
| 1206 | def hydrate_unknown(_refs, **_kwargs): |
| 1207 | items = [{"engagement_source": UNKNOWN, "top_comments": []} for _ in _refs] |
| 1208 | return SimpleNamespace( |
| 1209 | items=items, |
| 1210 | arctic_state="ok", |
| 1211 | detail=f"web served {len(items)}", |
| 1212 | comment_fills=0, |
| 1213 | comment_failures=0, |
| 1214 | comment_throttles=0, |
| 1215 | ) |
| 1216 | |
| 1217 | check_ok = canary.check_hydration("Claude Code", refs, hydrate_unknown) |
| 1218 | assert check_ok is not None |
| 1219 | assert check_ok.state == canary.DOWN |
| 1220 | assert check_ok.results == 0 |
| 1221 | |
| 1222 | def hydrate_unused(_refs, **_kwargs): |
| 1223 | return SimpleNamespace( |
| 1224 | items=[], |
| 1225 | arctic_state="unused", |
| 1226 | detail="web served 0", |
| 1227 | comment_fills=0, |
| 1228 | comment_failures=0, |
| 1229 | comment_throttles=0, |
| 1230 | ) |
| 1231 | |
| 1232 | check_unused = canary.check_hydration("Claude Code", refs, hydrate_unused) |
| 1233 | assert check_unused is not None |
| 1234 | assert check_unused.state == canary.DOWN |
| 1235 | |
| 1236 | def test_check_hydration_throttled_zero_filled_stays_challenged(self): |
| 1237 | refs = _sample_refs(2) |
| 1238 | |
| 1239 | def hydrate_throttled(_refs, **_kwargs): |
| 1240 | items = [{"engagement_source": UNKNOWN, "top_comments": []} for _ in _refs] |
| 1241 | return SimpleNamespace( |
| 1242 | items=items, |
| 1243 | arctic_state="throttled", |
| 1244 | detail="web served 2; arctic throttled", |
| 1245 | comment_fills=0, |
| 1246 | comment_failures=0, |
| 1247 | comment_throttles=0, |
| 1248 | ) |
| 1249 | |
| 1250 | check = canary.check_hydration("Claude Code", refs, hydrate_throttled) |
| 1251 | assert check is not None |
| 1252 | assert check.state == canary.CHALLENGED |
| 1253 | |
| 1254 | @pytest.mark.parametrize("source", [ARCTIC, ARCTIC_PENDING]) |
| 1255 | def test_check_hydration_hydrated_threads_with_empty_comments_still_pass(self, tmp_path, source): |
| 1256 | pages = { |
| 1257 | "https://search.brave.com/": (200, BRAVE_PAGE), |
| 1258 | "https://html.duckduckgo.com/": (202, ""), |
| 1259 | "https://www.startpage.com/": (429, ""), |
| 1260 | reddit_arctic.API: (200, ARCTIC_KNOWN_OK), |
| 1261 | } |
| 1262 | |
| 1263 | def hydrate_empty_comments(refs, **_kwargs): |
| 1264 | items = [{"engagement_source": source, "top_comments": []} for _ in refs] |
| 1265 | return SimpleNamespace( |
| 1266 | items=items, |
| 1267 | arctic_state="ok", |
| 1268 | detail=f"web+arctic served {len(items)}", |
| 1269 | comment_fills=0, |
| 1270 | comment_failures=0, |
| 1271 | comment_throttles=0, |
| 1272 | ) |
| 1273 | |
| 1274 | code, report = canary.run( |
| 1275 | fetch=_canary_fetcher(pages), |
| 1276 | hydrate=hydrate_empty_comments, |
| 1277 | topics=("Claude Code",), |
| 1278 | state_file=tmp_path / "state.json", |
| 1279 | now=NOW, |
| 1280 | sleep=lambda _s: None, |
| 1281 | ) |
| 1282 | states = {c["name"]: c["state"] for c in report["checks"]} |
| 1283 | assert code == 0, report["failures"] |
| 1284 | assert states["hydrate: Claude Code"] == canary.OK |
| 1285 | |
| 1286 | def test_check_hydration_returns_none_for_empty_refs(self): |
| 1287 | called = False |
| 1288 | |
| 1289 | def hydrate_should_not_run(_refs, **_kwargs): |
| 1290 | nonlocal called |
| 1291 | called = True |
| 1292 | raise AssertionError("should not be called") |
| 1293 | |
| 1294 | assert canary.check_hydration("Claude Code", [], hydrate_should_not_run) is None |
| 1295 | assert called is False |
| 1296 |