返回 last30days-skill
test_reddit_hydrate.py
根目录 / tests / test_reddit_hydrate.py
1 """The Reddit hydration chain: refs in, Reddit items out, through Arctic Shift
2 batched post lookups and comment trees, with fresh archive scores labeled
3 pending and a search-result fallback when nothing hydrates a ref."""
4
5 from urllib.parse import parse_qs, urlsplit
6
7 import pytest
8
9 from lib import http, normalize, reddit_arctic, reddit_hydrate, reddit_refs, render, schema
10
11 NOW = 1_800_000_000 # fixed clock for age math
12 HOUR = 3600
13 DAY = 24 * HOUR
14
15
16 class CountingLimiter:
17 def __init__(self):
18 self.calls = 0
19
20 def acquire(self):
21 self.calls += 1
22
23
24 @pytest.fixture(autouse=True)
25 def _quiet(monkeypatch):
26 """No real sleeps, a counting limiter, and a clean archive memo."""
27 sleeps = []
28 monkeypatch.setattr(reddit_arctic.time, "sleep", lambda s: sleeps.append(s))
29 limiter = CountingLimiter()
30 monkeypatch.setattr(http, "REDDIT_KEYLESS_LIMITER", limiter)
31 reddit_arctic.reset_memo()
32 yield {"sleeps": sleeps, "limiter": limiter}
33 reddit_arctic.reset_memo()
34
35
36 def _post(pid, *, title="ghostty terminal release", score=50, num_comments=10,
37 age=5 * DAY, sub="ghostty"):
38 return {
39 "id": pid, "title": title, "score": score, "num_comments": num_comments,
40 "created_utc": NOW - age, "subreddit": sub,
41 "permalink": f"/r/{sub}/comments/{pid}/slug/", "author": "op", "selftext": "body",
42 }
43
44
45 def _comment(cid, pid, *, score=5, age=3 * DAY, depth=0, body="ghostty is fast now", replies=None):
46 return {"kind": "t1", "data": {
47 "id": cid, "score": score, "created_utc": NOW - age, "depth": depth,
48 "author": f"user_{cid}", "body": body, "link_id": f"t3_{pid}",
49 "permalink": f"/r/ghostty/comments/{pid}/slug/{cid}/",
50 "replies": {"kind": "Listing", "data": {"children": replies or []}} if replies else "",
51 }}
52
53
54 class FakeArctic:
55 """Routes the archive's two endpoints to canned answers and records calls."""
56
57 def __init__(self, posts=None, trees=None, ids_answers=None):
58 self.posts = {p["id"]: p for p in (posts or [])}
59 self.trees = trees or {}
60 self.ids_answers = list(ids_answers or [])
61 self.calls = []
62
63 def __call__(self, url, headers=None, **_kwargs):
64 self.calls.append(url)
65 query = parse_qs(urlsplit(url).query)
66 if "/posts/ids" in url:
67 if self.ids_answers:
68 answer = self.ids_answers.pop(0)
69 if isinstance(answer, BaseException):
70 raise answer
71 return answer
72 ids = query["ids"][0].split(",")
73 return {"data": [self.posts[i] for i in ids if i in self.posts]}
74 if "/comments/tree" in url:
75 pid = query["link_id"][0].removeprefix("t3_")
76 return {"data": self.trees.get(pid, [])}
77 raise AssertionError(f"unexpected URL {url}")
78
79 def ids_calls(self):
80 return [u for u in self.calls if "/posts/ids" in u]
81
82
83 def _ref(pid, **kwargs):
84 ref = reddit_refs.canonical_thread(f"https://www.reddit.com/r/ghostty/comments/{pid}/slug/")
85 ref.provenance.add("web")
86 for key, value in kwargs.items():
87 setattr(ref, key, value)
88 return ref
89
90
91 def _hydrate(fake, refs, monkeypatch, **kwargs):
92 monkeypatch.setattr(reddit_arctic.http, "get", fake)
93 kwargs.setdefault("now", NOW)
94 kwargs.setdefault("topic", "ghostty")
95 return reddit_hydrate.hydrate(refs, **kwargs)
96
97
98 def _http_error(status):
99 return http.HTTPError(f"HTTP {status}", status_code=status)
100
101
102 class TestBatching:
103 def test_250_refs_make_three_serial_batches_of_at_most_100(self, monkeypatch, _quiet):
104 pids = [f"a{i:04d}" for i in range(250)]
105 fake = FakeArctic(posts=[_post(p) for p in pids])
106 result = _hydrate(fake, [_ref(p) for p in pids], monkeypatch, comments=False)
107 batches = [parse_qs(urlsplit(u).query)["ids"][0].split(",") for u in fake.ids_calls()]
108 assert [len(b) for b in batches] == [100, 100, 50]
109 assert sorted(sum(batches, [])) == sorted(pids)
110 assert _quiet["limiter"].calls >= 3
111 assert len(result.items) == 250
112
113
114 class TestPendingScores:
115 def test_fresh_low_score_is_pending_and_older_scores_stay(self, monkeypatch):
116 fake = FakeArctic(posts=[
117 _post("fresh1", score=1, age=10 * HOUR),
118 _post("old840", score=840, age=5 * DAY),
119 _post("old1", score=1, age=4 * DAY),
120 ])
121 result = _hydrate(fake, [_ref("fresh1"), _ref("old840"), _ref("old1")], monkeypatch,
122 comments=False)
123 by_id = {i["metadata"]["post_id"]: i for i in result.items}
124 assert by_id["fresh1"]["score"] is None
125 assert by_id["fresh1"]["engagement"]["score"] is None
126 assert by_id["fresh1"]["engagement_source"] == reddit_refs.ARCTIC_PENDING
127 assert by_id["old840"]["engagement"]["score"] == 840
128 assert by_id["old840"]["engagement_source"] == reddit_refs.ARCTIC
129 assert by_id["old1"]["engagement"]["score"] == 1
130 assert by_id["old1"]["engagement_source"] == reddit_refs.ARCTIC
131
132 def test_pending_score_renders_as_score_pending(self, monkeypatch):
133 fake = FakeArctic(posts=[_post("fresh1", score=1, num_comments=4, age=10 * HOUR)])
134 result = _hydrate(fake, [_ref("fresh1")], monkeypatch, comments=False)
135 [item] = normalize.normalize_source_items(
136 "reddit", result.items, "2027-01-01", "2027-02-01",
137 )
138 assert item.metadata["engagement_source"] == reddit_refs.ARCTIC_PENDING
139 shown = render._format_engagement(item)
140 assert "score pending" in shown
141 assert "pts" not in shown
142 assert "score pending" in render._format_item_engagement(item)
143
144
145 class TestComments:
146 def test_every_stored_comment_carries_depth(self, monkeypatch):
147 reply = _comment("c2", "p1", depth=1, score=3)
148 tree = [_comment("c1", "p1", score=12, replies=[reply]), _comment("c3", "p1", score=7)]
149 fake = FakeArctic(posts=[_post("p1")], trees={"p1": tree})
150 result = _hydrate(fake, [_ref("p1")], monkeypatch)
151 comments = result.items[0]["top_comments"]
152 assert {c["id"] for c in comments} == {"c1", "c2", "c3"}
153 assert all(isinstance(c["depth"], int) for c in comments)
154 assert {c["id"]: c["depth"] for c in comments} == {"c1": 0, "c2": 1, "c3": 0}
155 assert [c["id"] for c in comments] == ["c1", "c3", "c2"] # by score
156 assert result.items[0]["comments_source"] == reddit_refs.ARCTIC
157
158 def test_original_posters_comments_are_marked_uploader(self, monkeypatch):
159 own = _comment("c1", "p1", score=12)
160 own["data"]["author"] = "op"
161 tree = [own, _comment("c2", "p1", score=7)]
162 fake = FakeArctic(posts=[_post("p1")], trees={"p1": tree})
163 result = _hydrate(fake, [_ref("p1")], monkeypatch)
164 marks = {c["id"]: c["is_uploader"] for c in result.items[0]["top_comments"]}
165 assert marks == {"c1": True, "c2": False}
166 [item] = normalize.normalize_source_items(
167 "reddit", result.items, "2027-01-01", "2027-02-01",
168 )
169 quotable = [c for c in item.metadata["top_comments"]
170 if render._is_community_comment(item, c, c.get("excerpt", ""))]
171 assert [c["id"] for c in quotable] == ["c2"]
172
173 def test_fresh_arctic_comments_have_no_vote_count(self, monkeypatch):
174 tree = [_comment("c1", "p1", score=1, age=5 * HOUR), _comment("c2", "p1", score=2, age=8 * HOUR)]
175 fake = FakeArctic(posts=[_post("p1")], trees={"p1": tree})
176 result = _hydrate(fake, [_ref("p1")], monkeypatch)
177 comments = result.items[0]["top_comments"]
178 assert len(comments) == 2
179 assert all(c["score"] is None and c["score_pending"] for c in comments)
180
181 def test_attach_comments_after_hydrating_without_them(self, monkeypatch):
182 # Regression for #1546: the public wrapper unpacked two of three results.
183 fake = FakeArctic(posts=[_post("p1")], trees={"p1": [_comment("c1", "p1")]})
184 result = _hydrate(fake, [_ref("p1")], monkeypatch, comments=False)
185 assert not result.items[0].get("top_comments")
186 assert reddit_hydrate.attach_comments(result.items, "quick", now=NOW) == 1
187 assert [c["id"] for c in result.items[0]["top_comments"]] == ["c1"]
188 assert result.items[0]["comments_source"] == reddit_refs.ARCTIC
189
190 def test_comments_only_for_top_threads_within_budget(self, monkeypatch):
191 pids = [f"t{i}" for i in range(12)]
192 fake = FakeArctic(
193 posts=[_post(p, num_comments=100 - i) for i, p in enumerate(pids)],
194 trees={p: [_comment(f"c{p}", p)] for p in pids},
195 )
196 _hydrate(fake, [_ref(p) for p in pids], monkeypatch, depth="quick")
197 tree_calls = [u for u in fake.calls if "/comments/tree" in u]
198 assert len(tree_calls) == 4 # the quick-depth comment budget
199 assert all("link_id=t3_t" in u for u in tree_calls)
200 assert "link_id=t3_t0" in tree_calls[0] # most-discussed first
201
202
203 class TestArcticRetries:
204 def test_422_then_200_retries_once(self, monkeypatch, _quiet):
205 fake = FakeArctic(ids_answers=[_http_error(422), {"data": [_post("p1")]}])
206 result = _hydrate(fake, [_ref("p1")], monkeypatch, comments=False)
207 assert len(fake.ids_calls()) == 2
208 assert _quiet["sleeps"] # paused before the retry, through the patchable clock
209 assert result.items[0]["engagement"]["score"] == 50
210 assert result.arctic_state == "ok"
211
212 def test_two_422s_return_nothing_and_record_throttled(self, monkeypatch):
213 fake = FakeArctic(ids_answers=[_http_error(422), _http_error(422)])
214 monkeypatch.setattr(reddit_arctic.http, "get", fake)
215 posts, state = reddit_arctic.fetch_posts_by_ids(["p1"])
216 assert posts == {}
217 assert state == "throttled"
218 assert len(fake.ids_calls()) == 2
219
220
221 class TestLastRung:
222 def test_arctic_down_keeps_search_result_data(self, monkeypatch):
223 fake = FakeArctic(ids_answers=[_http_error(503)] * 10)
224 refs = [
225 _ref("p1", title="Ghostty 2.0 is out", date="2026-11-14"),
226 _ref("p2", title="Ghostty vs kitty", date="2026-11-10"),
227 ]
228 result = _hydrate(fake, refs, monkeypatch, from_date="2026-10-16", to_date="2026-11-15")
229 assert [i["title"] for i in result.items] == ["Ghostty 2.0 is out", "Ghostty vs kitty"]
230 for item in result.items:
231 assert item["engagement"]["score"] is None
232 assert item["engagement_source"] == reddit_refs.UNKNOWN
233 assert item["date"] in ("2026-11-14", "2026-11-10")
234 assert item["url"].startswith("https://www.reddit.com/r/ghostty/comments/")
235 assert result.arctic_state == "down"
236 assert "arctic down" in result.detail
237 assert "web served 2" in result.detail
238 assert not [u for u in fake.calls if "/comments/tree" in u]
239
240
241 class TestWindow:
242 def test_window_judged_on_post_created_utc(self, monkeypatch):
243 fake = FakeArctic(posts=[_post("in1", age=2 * DAY), _post("old1", age=90 * DAY)])
244 today = "2027-01-15" # NOW is 2027-01-15 UTC
245 result = _hydrate(fake, [_ref("in1"), _ref("old1")], monkeypatch, comments=False,
246 from_date="2026-12-16", to_date=today)
247 assert [i["metadata"]["post_id"] for i in result.items] == ["in1"]
248
249
250 class TestScrapeCreatorsRung:
251 def _sc_item(self, pid):
252 return {
253 "url": f"https://www.reddit.com/r/ghostty/comments/{pid}/x/",
254 "title": f"ghostty sc {pid}", "date": "2027-01-14",
255 "engagement": {"score": 77, "num_comments": 9},
256 "top_comments": [{"score": 20, "excerpt": "ghostty from sc", "url": ""}],
257 }
258
259 def test_thin_free_layers_call_sc(self, monkeypatch):
260 fake = FakeArctic(posts=[_post("p1"), _post("p2"), _post("p3", title="unrelated cats")])
261 calls = []
262
263 def sc():
264 calls.append(1)
265 return [self._sc_item("s1")]
266
267 result = _hydrate(fake, [_ref("p1"), _ref("p2"), _ref("p3")], monkeypatch,
268 comments=False, sc_fetch=sc, sc_min_items=5)
269 assert calls == [1]
270 sc_item = next(i for i in result.items if i["metadata"]["post_id"] == "s1")
271 assert sc_item["engagement_source"] == reddit_refs.LIVE
272 assert all(isinstance(c["depth"], int) for c in sc_item["top_comments"])
273 assert "sc" in result.detail
274
275 def test_pending_on_topic_threads_count_toward_the_floor(self, monkeypatch):
276 posts = [_post(f"f{i}", score=1, age=6 * HOUR) for i in range(4)] + [_post("s1", score=90)]
277 fake = FakeArctic(posts=posts)
278 calls = []
279 result = _hydrate(fake, [_ref(p["id"]) for p in posts], monkeypatch, comments=False,
280 sc_fetch=lambda: calls.append(1) or [], sc_min_items=5)
281 assert calls == []
282 assert reddit_hydrate.on_topic_count(result.items, "ghostty") == 5
283
284
285 class TestSessionHook:
286 def test_session_hydrated_refs_skip_arctic(self, monkeypatch):
287 fake = FakeArctic(posts=[_post("p2")])
288
289 def session(refs):
290 return {"p1": reddit_arctic._normalize_listing_row(_post("p1", score=300))}
291
292 result = _hydrate(fake, [_ref("p1"), _ref("p2")], monkeypatch, comments=False,
293 session_hydrator=session)
294 ids_requested = parse_qs(urlsplit(fake.ids_calls()[0]).query)["ids"][0]
295 assert ids_requested == "p2"
296 by_id = {i["metadata"]["post_id"]: i for i in result.items}
297 assert by_id["p1"]["engagement_source"] == reddit_refs.LIVE
298
299
300 def _reddit_item(url, *, score, source_label, comments, item_id="R1"):
301 return schema.SourceItem(
302 item_id=item_id, source="reddit", title="ghostty 2.0", body="ghostty 2.0",
303 url=url, engagement={"score": score, "num_comments": 12},
304 metadata={"top_comments": comments, "engagement_source": source_label,
305 "local_relevance": 0.8, "freshness": 80, "source_quality": 0.7},
306 )
307
308
309 class TestMergeKeepsMatchedComment:
310 def test_listing_copy_gains_the_session_copys_matched_comment(self):
311 listing = {"url": "u", "engagement": {"score": 5}, "engagement_source": reddit_refs.LIVE}
312 session_copy = {"url": "u", "engagement": {"score": 5},
313 "matched_comment": {"date": "2026-11-10", "url": "c"}}
314 reddit_hydrate.merge_post(listing, session_copy)
315 assert listing["matched_comment"] == {"date": "2026-11-10", "url": "c"}
316
317
318 class TestMergeAcrossForms:
319 def test_three_forms_of_one_thread_merge_with_live_score_and_all_comments(self):
320 from lib import fusion
321
322 plan = schema.QueryPlan(
323 intent="breaking_news", freshness_mode="strict_recent", cluster_mode="story",
324 raw_topic="ghostty",
325 subqueries=[
326 schema.SubQuery(label=label, search_query="ghostty", ranking_query="ghostty",
327 sources=["reddit"], weight=1.0)
328 for label in ("a", "b", "c")
329 ],
330 source_weights={"reddit": 1.0},
331 )
332 session = _reddit_item(
333 "https://www.reddit.com/r/ghostty/comments/1abc2de/ghostty_20/", score=412,
334 source_label=reddit_refs.LIVE,
335 comments=[{"id": "c1", "score": 50, "excerpt": "session comment", "depth": 0}],
336 )
337 brave = _reddit_item(
338 "https://old.reddit.com/r/ghostty/comments/1abc2de/ghostty_20/k9z8y7x/", score=None,
339 source_label=reddit_refs.ARCTIC_PENDING,
340 comments=[{"id": "c1", "score": None, "score_pending": True, "excerpt": "session comment", "depth": 0},
341 {"id": "c2", "score": None, "score_pending": True, "excerpt": "arctic comment", "depth": 1}],
342 )
343 host = _reddit_item(
344 "https://redd.it/1abc2de", score=900, source_label=reddit_refs.ARCTIC,
345 comments=[{"id": "c3", "score": 8, "excerpt": "host comment", "depth": 0}],
346 )
347 streams = {("a", "reddit"): [brave], ("b", "reddit"): [session], ("c", "reddit"): [host]}
348 candidates = fusion.weighted_rrf(streams, plan, pool_limit=10)
349 assert len(candidates) == 1
350 [item] = candidates[0].source_items
351 assert item.engagement["score"] == 412
352 assert item.metadata["engagement_source"] == reddit_refs.LIVE
353 ids = [c["id"] for c in item.metadata["top_comments"]]
354 assert sorted(ids) == ["c1", "c2", "c3"]
355 assert ids[-1] == "c2" # pending after scored
356
357
358 class TestRankingSkipsPendingScores:
359 def _candidate(self, item, engagement):
360 return schema.Candidate(
361 candidate_id=item.url, item_id=item.item_id, source="reddit", title=item.title,
362 url=item.url, snippet="", subquery_labels=["a"], native_ranks={"a:reddit": 1},
363 local_relevance=0.8, freshness=80, engagement=engagement, source_quality=0.7,
364 rrf_score=0.02, sources=["reddit"], source_items=[item], rerank_score=60.0,
365 )
366
367 def test_pending_engagement_is_unknown_not_zero(self):
368 from lib import rerank
369
370 pending = _reddit_item("https://www.reddit.com/r/g/comments/aaa/", score=None,
371 source_label=reddit_refs.ARCTIC_PENDING, comments=[])
372 zero = _reddit_item("https://www.reddit.com/r/g/comments/bbb/", score=0,
373 source_label=reddit_refs.ARCTIC, comments=[])
374 assert rerank._final_score(self._candidate(pending, None)) > rerank._final_score(
375 self._candidate(zero, None)
376 )
377
378 def test_engagement_reservation_skips_pending_scores(self):
379 from lib import fusion
380
381 pending = _reddit_item("https://www.reddit.com/r/g/comments/aaa/", score=None,
382 source_label=reddit_refs.ARCTIC_PENDING, comments=[])
383 pending.engagement["num_comments"] = 500
384 pending.local_relevance = 0.8
385 scored = _reddit_item("https://www.reddit.com/r/g/comments/bbb/", score=40,
386 source_label=reddit_refs.LIVE, comments=[])
387 scored.local_relevance = 0.8
388 fused = [self._candidate(pending, None), self._candidate(scored, None)]
389 reserved = fusion._reddit_engagement_reservation(fused, 2, "ghostty")
390 assert [c.url for c in reserved] == [scored.url]
391
392
393 class TestPendingCommentsInQuotes:
394 def _report(self, candidates):
395 return schema.Report(
396 topic="ghostty", range_from="2027-01-01", range_to="2027-01-15",
397 generated_at="2027-01-15T00:00:00Z", provider_runtime=schema.ProviderRuntime(
398 reasoning_provider="mock", planner_model="mock", rerank_model="mock"),
399 query_plan=schema.QueryPlan(intent="concept", freshness_mode="balanced_recent",
400 cluster_mode="none", raw_topic="ghostty",
401 subqueries=[], source_weights={}),
402 clusters=[], ranked_candidates=candidates, items_by_source={}, errors_by_source={},
403 )
404
405 def _cand(self, item):
406 return schema.Candidate(
407 candidate_id=item.url, item_id=item.item_id, source=item.source, title=item.title,
408 url=item.url, snippet="", subquery_labels=["a"], native_ranks={"a": 1},
409 local_relevance=0.9, freshness=80, engagement=10, source_quality=0.7,
410 rrf_score=0.02, sources=[item.source], source_items=[item], final_score=50.0,
411 )
412
413 def test_pending_quotes_have_no_count_and_follow_scored_ones(self):
414 reddit = _reddit_item(
415 "https://www.reddit.com/r/ghostty/comments/aaa/", score=None,
416 source_label=reddit_refs.ARCTIC_PENDING,
417 comments=[{"id": "c1", "score": None, "score_pending": True, "depth": 0,
418 "author": "fresh_user", "excerpt": "ghostty pending comment text"}],
419 )
420 youtube = schema.SourceItem(
421 item_id="YT1", source="youtube", title="ghostty video", body="ghostty video",
422 url="https://www.youtube.com/watch?v=abc", author="channel",
423 engagement={"views": 1000},
424 metadata={"top_comments": [{"score": 30, "author": "yt_user",
425 "excerpt": "ghostty scored youtube comment"}]},
426 )
427 lines = render._render_top_comments(
428 self._report([self._cand(reddit), self._cand(youtube)]), limit=10,
429 )
430 pending = next(line for line in lines if "pending comment" in line)
431 scored = next(line for line in lines if "scored youtube" in line)
432 assert "upvotes" not in pending
433 assert lines.index(scored) < lines.index(pending)
434
435 def test_cluster_comment_lines_show_pending_without_votes(self):
436 reddit = _reddit_item(
437 "https://www.reddit.com/r/ghostty/comments/aaa/", score=None,
438 source_label=reddit_refs.ARCTIC_PENDING,
439 comments=[{"id": "c1", "score": None, "score_pending": True, "depth": 0,
440 "author": "fresh_user", "excerpt": "ghostty pending comment text"}],
441 )
442 shown = render._top_comments_list(reddit)
443 assert [c["id"] for c in shown] == ["c1"]
444
445
446 class TestArcticRunHealth:
447 def test_arctic_throttled_earlier_this_run_is_not_asked_again(self, monkeypatch, _quiet):
448 from lib import reddit_health
449
450 reddit_health.record("arctic", reddit_health.THROTTLED, "posts/ids 429")
451 fake = FakeArctic(posts=[_post("a0001")])
452 result = _hydrate(fake, [_ref("a0001")], monkeypatch, comments=False)
453 assert fake.ids_calls() == []
454 assert result.arctic_state == "throttled"
455 assert len(result.items) == 1
456
457 def test_skipped_archive_fetches_no_comment_trees(self, monkeypatch, _quiet):
458 from lib import reddit_health
459
460 reddit_health.record("arctic", reddit_health.THROTTLED, "posts/ids 429")
461 fake = FakeArctic(posts=[_post("a0002")])
462 _hydrate(fake, [_ref("a0002")], monkeypatch, comments=True)
463 assert fake.calls == []
464
465
466 class TestCommentThrottleCounts:
467 def test_slow_down_tree_failures_are_counted_as_throttles(self, monkeypatch):
468 fake = FakeArctic(posts=[_post("p1"), _post("p2")])
469
470 def tree_422(url, headers=None, **_kwargs):
471 if "/comments/tree" in url:
472 raise _http_error(422)
473 return fake(url, headers=headers)
474
475 monkeypatch.setattr(reddit_arctic.http, "get", tree_422)
476 result = reddit_hydrate.hydrate([_ref("p1"), _ref("p2")], now=NOW, topic="ghostty")
477 assert result.comment_fills == 0
478 assert result.comment_failures >= 1
479 assert result.comment_throttles == result.comment_failures
480
480 lines PYTHON