返回 last30days-skill
test_reddit_health.py
根目录 / tests / test_reddit_health.py
1 """Reddit path health, the served-path detail, and doctor's Reddit rows (U3).
2
3 Every network seam is mocked: site search answers through a patched
4 ``http.get_text``, the web floor and Arctic hydration through patched
5 ``reddit_discover.web_refs`` / ``reddit_arctic`` calls, and doctor's probe
6 through a patched ``bounded_get.get``. The health cache lives in the test's
7 own config dir (conftest's ``_isolated_config``).
8 """
9
10 import json
11 from datetime import datetime, timedelta, timezone
12 from pathlib import Path
13 from unittest import mock
14
15 import pytest
16
17 from lib import (
18 doctor, env, health, http, pipeline, reddit_arctic, reddit_discover, reddit_health,
19 reddit_keyless, reddit_refs, reddit_search, schema, web_search_keyless,
20 )
21
22 FIXTURES = Path(__file__).resolve().parent.parent / "fixtures"
23 TODAY = datetime.now(timezone.utc).date()
24 FROM = (TODAY - timedelta(days=30)).isoformat()
25 TO = TODAY.isoformat()
26 OLD_UTC = int((datetime.now(timezone.utc) - timedelta(days=5)).timestamp())
27
28
29 def _new_run():
30 """What last30days.py does between commands in one process."""
31 reddit_search.reset_run_state()
32 reddit_discover.reset_run_state()
33 reddit_health.reset_run_state()
34 web_search_keyless.reset_rung_health()
35
36
37 class SearchAnswers:
38 """Site search through http.get_text: each call records ``status``."""
39
40 def __init__(self, status, message):
41 self.status = status
42 self.message = message
43 self.requests: list[str] = []
44
45 def __call__(self, url, **_kwargs):
46 self.requests.append(url)
47 http._record_failure(http.HTTPError(self.message, self.status))
48 return None
49
50
51 @pytest.fixture
52 def search_403():
53 fake = SearchAnswers(403, "HTTP 403: Blocked")
54 with mock.patch.object(http, "get_text", side_effect=fake), \
55 mock.patch.object(http.REDDIT_KEYLESS_LIMITER, "acquire"), \
56 mock.patch.object(http.time, "sleep"):
57 yield fake
58
59
60 @pytest.fixture
61 def search_429():
62 fake = SearchAnswers(429, "HTTP 429: Too Many Requests")
63 with mock.patch.object(http, "get_text", side_effect=fake), \
64 mock.patch.object(http.REDDIT_KEYLESS_LIMITER, "acquire"), \
65 mock.patch.object(http, "_sleep_reddit_429_retry"), \
66 mock.patch.object(http.time, "sleep"):
67 yield fake
68
69
70 def _ref(pid, title):
71 ref = reddit_refs.canonical_thread(f"https://www.reddit.com/r/elonmusk/comments/{pid}/x/")
72 ref.provenance.add("web")
73 ref.title = title
74 return ref
75
76
77 def _archived(pid, title, comments=9):
78 return reddit_arctic._normalize_listing_row({
79 "id": pid, "title": title, "score": 120, "num_comments": comments,
80 "subreddit": "elonmusk", "created_utc": OLD_UTC,
81 "permalink": f"/r/elonmusk/comments/{pid}/x/", "author": "someone",
82 })
83
84
85 def _floor(pids, rungs=None):
86 """Patch the web floor (Brave found ``pids``) and Arctic hydration."""
87 rungs = rungs or {"brave": web_search_keyless.OK}
88 refs = [_ref(pid, f"Elon Musk thread {pid}") for pid in pids]
89 rows = {pid: _archived(pid, f"Elon Musk thread {pid}") for pid in pids}
90
91 def web_refs(topic, **_kwargs):
92 for rung, state in rungs.items():
93 web_search_keyless.RUNG_HEALTH.record(rung, state)
94 return reddit_discover.WebFloor(
95 refs=[_ref(r.post_id, r.title) for r in refs],
96 queries=[f"site:reddit.com {topic}"], rungs=dict(rungs),
97 )
98
99 return (
100 mock.patch.object(reddit_keyless.reddit_discover, "web_refs", side_effect=web_refs),
101 mock.patch.object(
102 reddit_keyless.reddit_arctic, "fetch_posts_by_ids",
103 side_effect=lambda ids, **_k: ({i: dict(rows[i]) for i in ids if i in rows}, "ok"),
104 ),
105 mock.patch.object(reddit_keyless.reddit_arctic, "fetch_comment_tree", return_value=[]),
106 mock.patch.object(reddit_keyless.reddit_shreddit, "fetch_comments", return_value={}),
107 )
108
109
110 def _stream(config=None, limited=None, subreddits=None):
111 return pipeline._retrieve_stream(
112 topic="Elon Musk",
113 subquery=schema.SubQuery(
114 label="primary", search_query="Elon Musk", ranking_query="Elon Musk",
115 sources=["reddit"],
116 ),
117 source="reddit", config=dict(config or {}), depth="quick",
118 date_range=(FROM, TO), subreddits=subreddits,
119 runtime=schema.ProviderRuntime(
120 reasoning_provider="mock", planner_model="mock", rerank_model="mock",
121 ),
122 mock=False, rate_limited_sources=limited if limited is not None else set(),
123 )
124
125
126 def _set_entry_age(path, hours):
127 data = json.loads(reddit_health.cache_path().read_text())
128 at = datetime.now(timezone.utc) - timedelta(hours=hours)
129 data["paths"][path]["at"] = at.isoformat()
130 reddit_health.cache_path().write_text(json.dumps(data))
131
132
133 # --- the persisted cache -----------------------------------------------------
134
135 class TestPersistedSkips:
136 def test_search_page_403_writes_a_six_hour_skip_the_next_run_honors(self, search_403):
137 assert reddit_keyless._site_search("Elon Musk", "quick", None, FROM, TO, None) == []
138 assert len(search_403.requests) == 1
139
140 entry = reddit_health.entries()["search"]
141 assert entry["state"] == reddit_health.BLOCKED
142 assert entry["cookie_fp"] is None # schema carries it; nothing keyless writes it
143 until = reddit_health.skip_until("search")
144 assert timedelta(hours=5, minutes=59) < until - datetime.now(timezone.utc) <= timedelta(hours=6)
145
146 # Next run: skipped without a request.
147 _new_run()
148 with reddit_keyless.lane_paths() as paths:
149 assert reddit_keyless._site_search("Elon Musk", "quick", None, FROM, TO, None) == []
150 assert len(search_403.requests) == 1
151 assert paths["search"] == reddit_health.SKIPPED_CACHED
152
153 # Seven hours later the skip has lapsed and search is asked again.
154 _set_entry_age("search", 7)
155 _new_run()
156 reddit_keyless._site_search("Elon Musk", "quick", None, FROM, TO, None)
157 assert len(search_403.requests) == 2
158
159 def test_429_skips_the_path_for_this_run_only(self, search_429):
160 with reddit_keyless.lane_paths() as paths:
161 reddit_keyless._site_search("Elon Musk", "quick", None, FROM, TO, None)
162 assert paths["search"] == reddit_health.THROTTLED
163 asked = len(search_429.requests)
164 assert asked >= 1
165 assert "search" not in reddit_health.entries() # never persisted
166
167 # Same run: no further request.
168 reddit_keyless._site_search("Elon Musk", "quick", None, FROM, TO, None)
169 assert len(search_429.requests) == asked
170
171 # Next run asks again.
172 _new_run()
173 reddit_keyless._site_search("Elon Musk", "quick", None, FROM, TO, None)
174 assert len(search_429.requests) > asked
175
176 def test_a_skip_under_another_cookie_fingerprint_is_ignored(self):
177 reddit_health.record("search", reddit_health.BLOCKED, "logged out", cookie_fp="a" * 16)
178 assert reddit_health.skip_until("search", cookie_fp="a" * 16) is not None
179 assert reddit_health.skip_until("search", cookie_fp="b" * 16) is None
180 assert reddit_health.skip_until("search") is None
181
182 def test_an_ok_answer_clears_a_skip(self):
183 reddit_health.record("brave", reddit_health.BLOCKED, "HTTP 403")
184 _new_run()
185 reddit_health.record("brave", reddit_health.OK)
186 assert reddit_health.skip_until("brave") is None
187 assert reddit_health.entries()["brave"]["state"] == reddit_health.OK
188
189 def test_a_path_down_this_run_stays_down_for_it(self):
190 reddit_health.record("ddg", reddit_health.THROTTLED)
191 reddit_health.record("ddg", reddit_health.OK)
192 assert reddit_health.skip_reason("ddg") == reddit_health.THROTTLED
193
194 def test_unreadable_or_foreign_cache_reads_as_empty(self):
195 reddit_health.cache_path().write_text("{not json")
196 assert reddit_health.entries() == {}
197 reddit_health.cache_path().write_text(json.dumps({"schema": 99, "paths": {"search": {}}}))
198 assert reddit_health.entries() == {}
199
200 def test_clean_mode_keeps_health_in_memory_only(self, monkeypatch):
201 monkeypatch.setattr(env, "CONFIG_DIR", None)
202 reddit_health.record("search", reddit_health.BLOCKED, "HTTP 403")
203 assert reddit_health.entries() == {}
204 assert reddit_health.skip_reason("search") == reddit_health.BLOCKED
205
206
207 class TestWebRungSkips:
208 def test_brave_403_skip_seeds_the_next_run_straight_to_ddg(self):
209 reddit_health.record("brave", reddit_health.BLOCKED, "web search blocked")
210 _new_run()
211 assert reddit_health.seed_web_rungs() == {"brave": reddit_health.BLOCKED}
212 asked = []
213
214 def ddg(query, count, freshness=None):
215 asked.append("ddg")
216 return [], web_search_keyless.EMPTY
217
218 def brave(query, count, freshness=None):
219 asked.append("brave")
220 return [], web_search_keyless.OK
221
222 with mock.patch.object(web_search_keyless, "_brave_rung", side_effect=brave), \
223 mock.patch.object(web_search_keyless, "_ddg_rung", side_effect=ddg), \
224 mock.patch.object(web_search_keyless, "_startpage_rung",
225 return_value=([], web_search_keyless.EMPTY)):
226 _items, artifact = web_search_keyless.keyless_search(
227 "site:reddit.com Elon Musk", (FROM, TO), {},
228 )
229 assert asked == ["ddg"]
230 assert artifact["keyless_rungs"]["brave"] == web_search_keyless.SKIPPED
231 # Seeding happens once per run.
232 assert reddit_health.seed_web_rungs() == {}
233
234 def test_floor_rung_states_persist_blocked_and_ok_only(self):
235 p_web, p_ids, p_tree, p_comments = _floor(
236 ["aaa111"],
237 rungs={"brave": web_search_keyless.BLOCKED, "ddg": web_search_keyless.THROTTLED,
238 "startpage": web_search_keyless.OK},
239 )
240 with p_web, p_ids, p_tree, p_comments, reddit_keyless.lane_paths() as paths:
241 reddit_keyless._web_floor("Elon Musk", "quick", None, None, FROM, TO, None)
242 entries = reddit_health.entries()
243 assert entries["brave"]["state"] == reddit_health.BLOCKED
244 assert "ddg" not in entries
245 assert entries["startpage"]["state"] == reddit_health.OK
246 assert entries["arctic"]["state"] == reddit_health.OK
247 assert paths["brave"] == reddit_health.BLOCKED
248 assert paths["ddg"] == reddit_health.THROTTLED
249 assert paths["web"] == reddit_health.OK
250
251
252 # --- served-path detail through the stream ------------------------------------
253
254 class TestServedPathDetail:
255 def test_floor_threads_with_search_blocked_are_ok_with_a_served_detail(self, search_403):
256 pids = [f"t{i:05d}" for i in range(14)]
257 p_web, p_ids, p_tree, p_comments = _floor(pids)
258 limited: set = set()
259 with p_web, p_ids, p_tree, p_comments:
260 items, artifact = _stream(limited=limited)
261
262 assert len(items) == 14
263 assert "_source_outcome" not in artifact # ok, not partial
264 assert artifact["_source_outcome_detail"] == "web+arctic served 14; search blocked"
265 assert artifact.get("_source_outcome_detail_state") is None
266 assert "reddit" not in limited
267
268 def test_site_search_429_keeps_the_floor_running_and_reddit_unlimited(self, search_429):
269 p_web, p_ids, p_tree, p_comments = _floor(["aaa111", "bbb222"])
270 limited: set = set()
271 with p_web, p_ids, p_tree, p_comments:
272 items, artifact = _stream(limited=limited)
273
274 assert len(items) == 2
275 assert "_source_outcome" not in artifact
276 assert artifact["_source_outcome_detail"] == "web+arctic served 2; search throttled"
277 assert artifact.get("_source_outcome_detail_state") != health.RATE_LIMITED
278 assert "reddit" not in limited
279
280 def test_every_path_failing_is_a_transport_failure_not_no_results(self, search_403):
281 p_web, p_ids, p_tree, p_comments = _floor(
282 [],
283 rungs={"brave": web_search_keyless.BLOCKED, "ddg": web_search_keyless.THROTTLED,
284 "startpage": web_search_keyless.ERROR},
285 )
286 with p_web, p_ids, p_tree, p_comments:
287 items, artifact = _stream()
288
289 assert items == []
290 outcome = artifact["_source_outcome"]
291 assert outcome["state"] == health.UNREACHABLE
292 assert outcome["state"] != health.NO_RESULTS
293 assert outcome["detail"] == (
294 "no path served; search blocked; brave blocked; ddg throttled; startpage down"
295 )
296
297 def test_every_path_throttled_is_rate_limited(self, search_429):
298 p_web, p_ids, p_tree, p_comments = _floor(
299 [], rungs={"brave": web_search_keyless.THROTTLED},
300 )
301 with p_web, p_ids, p_tree, p_comments:
302 items, artifact = _stream()
303
304 assert items == []
305 outcome = artifact["_source_outcome"]
306 assert outcome["state"] == health.RATE_LIMITED
307 assert outcome["detail"] == (
308 "no path served; search throttled; brave throttled; rate-limited (HTTP 429)"
309 )
310
311 def test_every_free_path_failing_and_an_empty_backfill_is_still_a_failure(self, search_403):
312 p_web, p_ids, p_tree, p_comments = _floor(
313 [], rungs={"brave": web_search_keyless.BLOCKED, "ddg": web_search_keyless.BLOCKED,
314 "startpage": web_search_keyless.BLOCKED},
315 )
316 with p_web, p_ids, p_tree, p_comments, \
317 mock.patch("lib.reddit.search_and_enrich", return_value={}), \
318 mock.patch("lib.reddit.parse_reddit_response", return_value=[]):
319 items, artifact = _stream({"SCRAPECREATORS_API_KEY": "dummy-key"})
320
321 assert items == []
322 assert artifact["_source_outcome"]["state"] == health.UNREACHABLE
323
324 def test_an_empty_answer_is_still_no_results(self):
325 p_web, p_ids, p_tree, p_comments = _floor(
326 [], rungs={"brave": web_search_keyless.EMPTY},
327 )
328 with p_web, p_ids, p_tree, p_comments, \
329 mock.patch.object(reddit_keyless.reddit_search, "search", return_value=[]):
330 items, artifact = _stream()
331
332 assert items == []
333 assert "_source_outcome" not in (artifact or {})
334
335 def test_same_thread_from_floor_and_listing_is_one_item_with_comments(self):
336 # #1083 shape: two subqueries, one thread found by both the web floor
337 # (with archive comments) and a listing (with the live score).
338 comment = {"id": "c1", "author": "a", "body": "Elon Musk again", "score": 5, "depth": 0}
339 listing_copy = {
340 **_archived("aaa111", "Elon Musk thread aaa111"),
341 "score": 900, "engagement": {"score": 900, "num_comments": 40},
342 "why_relevant": "Reddit listing",
343 }
344 p_web, p_ids, p_tree, p_comments = _floor(["aaa111"])
345 with p_web, p_ids, p_comments, \
346 mock.patch.object(reddit_keyless.reddit_arctic, "fetch_comment_tree",
347 return_value=[dict(comment)]), \
348 mock.patch.object(reddit_keyless.reddit_listing, "fetch_listings",
349 side_effect=lambda *_a, **_k: [dict(listing_copy)]), \
350 mock.patch.object(reddit_keyless.reddit_search, "search", return_value=[]):
351 runs = [_stream(subreddits=["elonmusk"]) for _subquery in range(2)]
352
353 for items, artifact in runs:
354 assert len(items) == 1
355 thread = items[0]
356 assert thread["engagement"]["score"] == 900 # live beats the snapshot
357 assert [c["id"] for c in thread["top_comments"]] == ["c1"]
358 assert set(thread["provenance"]) == {"listing", "web"}
359 assert artifact["_source_outcome_detail"].startswith("web+listing+arctic served 1")
360
361
362 class TestDetailVocabulary:
363 def test_tokens_parse_back_for_doctor(self):
364 paths = {"search": "blocked", "brave": "skipped-cached", "ddg": "throttled",
365 "arctic": "error"}
366 items = [{"provenance": ["web"], "engagement_source": "arctic"}]
367 detail = reddit_health.served_detail(items, paths)
368 assert detail == (
369 "web+arctic served 1; search blocked; brave skipped-cached; ddg throttled; arctic down"
370 )
371 parsed = reddit_health.parse_detail(detail)
372 assert parsed == {"web": "served", "arctic": "served", "search": "blocked",
373 "brave": "skipped-cached", "ddg": "throttled"}
374
375 def test_detail_stays_short_and_plain(self):
376 paths = {p: "blocked" for p in reddit_health.PATHS}
377 items = [{"provenance": list(reddit_health.SERVED_ORDER)}] * 3
378 detail = reddit_health.served_detail(items, paths)
379 assert len(detail) <= 140
380 assert "\u2014" not in detail and "\u2013" not in detail
381
382 def test_every_path_failed_needs_an_asked_failing_path(self):
383 assert not reddit_health.every_path_failed({})
384 assert not reddit_health.every_path_failed({"search": "blocked", "brave": "empty"})
385 assert reddit_health.every_path_failed({"search": "blocked", "web": "empty",
386 "brave": "blocked"})
387
388
389 # --- doctor -------------------------------------------------------------------
390
391 class TestDoctorRows:
392 def _last_report(self, detail):
393 path = env.CONFIG_DIR / doctor.REPORT_CACHE_FILENAME
394 path.write_text(json.dumps({
395 "schema": doctor.REPORT_CACHE_SCHEMA_VERSION,
396 "timestamp": datetime.now(timezone.utc).isoformat(),
397 "topic": "Elon Musk",
398 "reports": [{"report": {"source_status": {
399 "reddit": {"state": "ok", "items_returned": 14, "detail": detail},
400 }}}],
401 }))
402
403 def test_rows_show_last_run_skip_and_action(self):
404 self._last_report("web+arctic served 14; search blocked; ddg throttled")
405 reddit_health.record("search", reddit_health.BLOCKED, "HTTP 403: Blocked")
406 report = doctor.build_report({})
407 rows = {row["path"]: row for row in report["sources"]["reddit"]["paths"]}
408
409 assert list(rows) == ["session", "search", "brave", "ddg", "startpage", "arctic"]
410 assert rows["session"]["consent"] == "unset"
411 assert rows["session"]["would_run"] is False
412 assert rows["search"]["last_run"] == "blocked"
413 assert rows["search"]["skip_until"].endswith("UTC")
414 assert rows["brave"]["last_run"] == "served"
415 assert rows["ddg"]["last_run"] == "throttled"
416 assert "one run only" in rows["ddg"]["action"]
417 assert rows["arctic"]["last_run"] == "served"
418 text = doctor.render_text(report)
419 assert "path: Reddit site search - last run blocked; skipped until" in text
420 assert "path: Arctic Shift archive - last run served - action: none" in text
421 for line in text.splitlines():
422 if "path:" in line:
423 assert "\u2014" not in line and "\u2013" not in line
424
425 def test_rows_with_no_saved_run_say_so(self):
426 report = doctor.build_report({})
427 rows = report["sources"]["reddit"]["paths"]
428 assert all(row["last_run"] is None for row in rows)
429 assert "path: Brave web search - no saved run - action: none" in doctor.render_text(report)
430
431 def test_sc_row_names_the_last_backfill(self):
432 self._last_report("web+arctic+sc served 9; ScrapeCreators backfill ran (4 free items)")
433 report = doctor.build_report({"SCRAPECREATORS_API_KEY": "dummy-key"})
434 sc = next(b for b in report["sources"]["reddit"]["backups"]
435 if b["name"] == "ScrapeCreators backfill")
436 assert sc["note"].endswith("; last run: backfill served")
437
438 def test_doctor_clears_the_cache_reprobes_and_reads_no_cookie(self, capsys):
439 reddit_health.record("search", reddit_health.BLOCKED, "HTTP 403: Blocked")
440 reddit_health.record("brave", reddit_health.BLOCKED, "HTTP 403")
441 brave_page = (FIXTURES / "brave_reddit_serp.html").read_text()
442 answers = [(200, brave_page.encode(), None), (200, b'{"data": []}', None)]
443 with mock.patch.object(doctor, "_probeable_sources", return_value=("reddit",)), \
444 mock.patch("lib.bounded_get.get", side_effect=answers) as get, \
445 mock.patch("lib.env.extract_browser_credentials") as creds, \
446 mock.patch("lib.cookie_extract.extract_cookies") as cookies, \
447 mock.patch("lib.cookie_extract.extract_cookies_with_source") as sourced:
448 assert doctor.run({}, probe=True) == 0
449
450 assert get.call_count == 2
451 urls = [call.args[0].full_url for call in get.call_args_list]
452 assert urls[0].startswith("https://search.brave.com/search?")
453 assert "/api/posts/ids?ids=" in urls[1]
454 creds.assert_not_called()
455 cookies.assert_not_called()
456 sourced.assert_not_called()
457 entries = reddit_health.entries()
458 assert "search" not in entries # cleared
459 assert entries["brave"]["state"] == reddit_health.OK # re-probed
460 assert entries["arctic"]["state"] == reddit_health.OK
461 assert reddit_health.skip_until("brave") is None
462 out = capsys.readouterr().out
463 assert "doctor cleared this skip; the next run asks this path again" in out
464
465 def test_cached_doctor_keeps_the_skips(self):
466 reddit_health.record("search", reddit_health.BLOCKED, "HTTP 403: Blocked")
467 with mock.patch.object(doctor, "_probe_sources", return_value={}):
468 doctor.run({}, cached=True)
469 assert reddit_health.skip_until("search") is not None
470
471
472 def test_served_path_detail_never_reaches_the_footer():
473 from lib import render
474
475 from tests.test_render_footer import _reddit_item, _report
476
477 detail = "web+arctic served 1; search blocked; brave throttled"
478 report = _report(
479 items_by_source={"reddit": [_reddit_item()]},
480 source_status={"reddit": schema.SourceOutcome(
481 source="reddit", state=health.OK, items_returned=1, detail=detail,
482 )},
483 )
484 text = render.render_compact(report)
485 footer = text.split("✅ All agents reported back!", 1)[1]
486 assert "served" not in footer
487 assert "search blocked" not in footer
488 assert "throttled" not in footer
489
489 lines PYTHON