返回 last30days-skill
reddit_hydrate.py
根目录 / skills / last30days / scripts / lib / reddit_hydrate.py
1 """Turn discovered Reddit thread refs into Reddit items, one chain for every path.
2
3 Each discovery path (web search, a host's thread list, a logged-in session)
4 hands over :class:`reddit_refs.ThreadRef` values. :func:`hydrate` fills them
5 in best-first:
6
7 1. An injected session hydrator, when the caller has one. It returns
8 Reddit's live data for the refs it could read.
9 2. Arctic Shift ``/posts/ids`` for the rest, in batches of at most 100 ids,
10 one request at a time through the shared keyless limiter. A post under
11 ``reddit_refs.PENDING_SECONDS`` old has no settled archive score yet, so
12 its score is withheld (``None``) and labeled ``arctic-pending``.
13 3. A ref nothing filled keeps the search result's title, URL and date with an
14 unknown score, so an archive outage leaves Reddit thin, not empty.
15
16 Comments for the most-discussed kept threads come from Arctic Shift
17 ``/comments/tree`` within the lane's comment budget, each with its ``depth``
18 (0 for a top-level comment); a fresh archive comment is pending like a fresh
19 post. When the caller passes a ScrapeCreators fetch (it has a key) and fewer
20 threads than the floor are on topic, the fetch runs and its threads merge in
21 by thread id. A pending thread counts as on topic when its title names the
22 topic.
23
24 The items have the shape the Reddit lane hands the pipeline (title, url,
25 subreddit, date, engagement, top_comments, metadata.post_id), plus
26 ``engagement_source`` and ``comments_source`` naming where the score and the
27 comments came from, and ``provenance``, the discovery paths that found the
28 thread. ``normalize`` carries both labels into ``SourceItem.metadata``.
29 Never raises.
30 """
31
32 from __future__ import annotations
33
34 import sys
35 import time
36 from dataclasses import dataclass
37 from typing import Any, Callable, Iterable, Mapping, Optional
38
39 from . import env, reddit_arctic, reddit_shreddit
40 from .reddit_refs import (
41 ARCTIC,
42 ARCTIC_PENDING,
43 LIVE,
44 PENDING_SECONDS,
45 UNKNOWN,
46 ThreadRef,
47 canonical_thread,
48 score_rank,
49 union_comments,
50 )
51
52 SessionHydrator = Callable[[list[ThreadRef]], Mapping[str, dict]]
53
54 COMMENTS_PER_THREAD = 10
55 # Order the served-path detail names its paths in.
56 _PATH_ORDER = ("session", "host", "web", "listing", "arctic", "sc")
57
58
59 @dataclass
60 class Hydration:
61 """What :func:`hydrate` produced.
62
63 ``arctic_state`` is ``"ok"``, ``"throttled"``, ``"down"``, or ``"unused"``
64 when no ref needed the archive. ``detail`` is a short served-path note
65 such as ``web+arctic served 14`` or ``web served 3; arctic down``.
66 """
67
68 items: list[dict]
69 detail: str
70 arctic_state: str
71 # Archive comment-tree requests this call: trees attached, and requests
72 # that failed (an empty tree is neither).
73 comment_fills: int = 0
74 comment_failures: int = 0
75 comment_throttles: int = 0 # failures that were a 422/429 slow-down
76
77
78 def _log(msg: str) -> None:
79 sys.stderr.write(f"[RedditHydrate] {msg}\n")
80 sys.stderr.flush()
81
82
83 def _is_number(value: Any) -> bool:
84 return isinstance(value, (int, float)) and not isinstance(value, bool)
85
86
87 def _age_seconds(created_utc: Any, now: float) -> Optional[float]:
88 try:
89 return now - float(created_utc)
90 except (TypeError, ValueError):
91 return None
92
93
94 def _fresh(created_utc: Any, now: float) -> bool:
95 age = _age_seconds(created_utc, now)
96 return age is not None and age < PENDING_SECONDS
97
98
99 def _merge_refs(refs: Iterable[ThreadRef]) -> dict[str, ThreadRef]:
100 """One ref per thread id, in first-seen order, provenance unioned."""
101 by_id: dict[str, ThreadRef] = {}
102 for ref in refs:
103 if not isinstance(ref, ThreadRef) or not ref.post_id:
104 continue
105 current = by_id.get(ref.post_id)
106 if current is None:
107 by_id[ref.post_id] = ThreadRef(
108 post_id=ref.post_id, url=ref.url, subreddit=ref.subreddit,
109 provenance=set(ref.provenance), matched_comment=ref.matched_comment,
110 title=ref.title, date=ref.date,
111 matched_comment_verified=ref.matched_comment_verified,
112 )
113 continue
114 current.provenance |= ref.provenance
115 current.subreddit = current.subreddit or ref.subreddit
116 current.title = current.title or ref.title
117 current.date = current.date or ref.date
118 if current.matched_comment is None and ref.matched_comment is not None:
119 current.matched_comment = ref.matched_comment
120 current.matched_comment_verified = ref.matched_comment_verified
121 elif current.matched_comment is not None and ref.matched_comment is not None:
122 current.matched_comment_verified = (
123 current.matched_comment_verified or ref.matched_comment_verified
124 )
125 if ref.subreddit and "/r/" not in current.url:
126 current.url = ref.url
127 return by_id
128
129
130 def label_archive_post(post: dict, now: float) -> None:
131 """Label an archive row's score: pending under 36 h old, else archive."""
132 if _fresh(post.get("created_utc"), now):
133 post["score"] = None
134 post.setdefault("engagement", {})["score"] = None
135 post["engagement_source"] = ARCTIC_PENDING
136 else:
137 post["engagement_source"] = ARCTIC
138
139
140 def _from_search_result(ref: ThreadRef) -> dict:
141 return {
142 "id": "",
143 "title": ref.title,
144 "url": ref.url,
145 "score": None,
146 "num_comments": None,
147 "subreddit": ref.subreddit,
148 "created_utc": None,
149 "author": "",
150 "selftext": "",
151 "date": ref.date,
152 "engagement": {"score": None, "num_comments": None, "upvote_ratio": None},
153 "relevance": 0.0,
154 "why_relevant": "Reddit thread (search result)",
155 "metadata": {"post_id": ref.post_id},
156 "engagement_source": UNKNOWN,
157 }
158
159
160 def _stamp_depth(comments: Any) -> list[dict]:
161 """Comments with an int ``depth``; a path that reports none lists top-level comments."""
162 out: list[dict] = []
163 for comment in comments or []:
164 if not isinstance(comment, dict):
165 continue
166 try:
167 comment["depth"] = int(comment.get("depth") or 0)
168 except (TypeError, ValueError):
169 comment["depth"] = 0
170 out.append(comment)
171 return out
172
173
174 def _stamp_uploader(post: dict) -> None:
175 """Mark the original poster's own comments so they never quote as community.
176
177 Set while the post author is still on the item; the normalized item drops it.
178 """
179 author = str(post.get("author") or "").strip().lower().removeprefix("/").removeprefix("u/")
180 if not author or author in ("[deleted]", "[removed]"):
181 return
182 for comment in post.get("top_comments") or []:
183 if isinstance(comment, dict) and not isinstance(comment.get("is_uploader"), bool):
184 name = str(comment.get("author") or "").strip().lower().removeprefix("/").removeprefix("u/")
185 if name and name not in ("[deleted]", "[removed]"):
186 comment["is_uploader"] = name == author
187
188
189 def _finish(post: dict, ref: ThreadRef, topic: str) -> dict:
190 """Canonical URL, subreddit, provenance and topic relevance on one item."""
191 # The subreddit Reddit or the archive reported is authoritative; a ref's
192 # URL (a host-supplied one included) can name the wrong community.
193 subreddit = str(post.get("subreddit") or "") or ref.subreddit
194 canon = canonical_thread(
195 f"https://www.reddit.com/r/{subreddit}/comments/{ref.post_id}/" if subreddit else ref.post_id
196 )
197 post["url"] = canon.url if canon else ref.url
198 post["subreddit"] = subreddit
199 post.setdefault("metadata", {})["post_id"] = ref.post_id
200 post["provenance"] = sorted(ref.provenance)
201 matched = ref.matched_comment
202 engagement_source = post.get("engagement_source")
203 is_archive_or_unhydrated = engagement_source in (ARCTIC, ARCTIC_PENDING, UNKNOWN)
204 allow_matched = ref.matched_comment_verified or (
205 not is_archive_or_unhydrated and "session" not in ref.provenance
206 )
207 if matched is not None and matched.created_utc and allow_matched:
208 from . import dates
209
210 post["matched_comment"] = {
211 "id": matched.comment_id,
212 "date": dates.timestamp_to_date(matched.created_utc),
213 "url": matched.permalink,
214 }
215 engagement = post.setdefault("engagement", {})
216 engagement.setdefault("score", post.get("score"))
217 engagement.setdefault("num_comments", post.get("num_comments"))
218 post.setdefault("engagement_source", LIVE)
219 if post.get("top_comments"):
220 post["top_comments"] = _stamp_depth(post["top_comments"])
221 _stamp_uploader(post)
222 if topic and post.get("title"):
223 from .relevance import token_overlap_relevance
224
225 post["relevance"] = round(token_overlap_relevance(topic, post["title"]), 3)
226 return post
227
228
229 def _day_in_window(day: Optional[str], from_date: Optional[str], to_date: Optional[str]) -> bool:
230 return bool(day) and (not from_date or day >= from_date) and (not to_date or day <= to_date)
231
232
233 def _in_window(item: dict, from_date: Optional[str], to_date: Optional[str]) -> bool:
234 """A thread is in the window by its own date, or by the date of the
235 comment a comment search matched in it (an older thread with a fresh
236 matched comment stays)."""
237 day = item.get("date")
238 if not day:
239 return True
240 if _day_in_window(day, from_date, to_date):
241 return True
242 matched = item.get("matched_comment") or {}
243 return _day_in_window(matched.get("date"), from_date, to_date)
244
245
246 def _discussion(item: dict) -> float:
247 engagement = item.get("engagement") or {}
248 return sum(
249 float(engagement.get(key)) for key in ("num_comments", "score")
250 if _is_number(engagement.get(key))
251 )
252
253
254 def _attach_comments(
255 items: list[dict], depth: str, deadline: Optional[float], now: float,
256 ) -> tuple[int, int, int]:
257 """Archive comment trees for the most-discussed hydrated threads that lack
258 comments, within the lane's comment budget. Returns (filled, failed,
259 throttled), where throttled counts the failures that were the archive
260 asking to slow down."""
261 from . import reddit_keyless
262
263 limit = reddit_shreddit.ENRICH_LIMITS.get(depth, reddit_shreddit.ENRICH_LIMITS["default"])
264 targets = sorted(
265 (
266 item for item in items
267 if item.get("engagement_source") != UNKNOWN
268 and not item.get("top_comments")
269 and (item.get("engagement") or {}).get("num_comments") != 0
270 ),
271 key=_discussion, reverse=True,
272 )[:limit]
273 if not targets:
274 return 0, 0, 0
275 end = time.monotonic() + reddit_keyless.FINAL_ENRICH_BUDGET
276 if deadline is not None:
277 end = min(end, deadline)
278 filled = failed = throttled = 0
279 for item in targets:
280 if end - time.monotonic() < 1:
281 _log("comment budget spent; remaining threads keep no comments")
282 break
283 pid = item["metadata"]["post_id"]
284 if reddit_arctic.fetch_comment_tree is getattr(reddit_arctic, "_ORIG_FETCH_COMMENT_TREE", None):
285 rows, was_throttled = reddit_arctic._fetch_comment_tree_with_status(pid, deadline=end)
286 else:
287 if "last_tree_throttled" not in vars(reddit_arctic):
288 reddit_arctic._set_thread_tree_throttled(False)
289 rows = reddit_arctic.fetch_comment_tree(pid, deadline=end)
290 was_throttled = bool(getattr(reddit_arctic, "last_tree_throttled", False))
291 if rows is None:
292 failed += 1
293 throttled += bool(was_throttled)
294 if failed >= 2 and not filled:
295 _log("archive comments failing; remaining threads keep no comments")
296 break
297 continue
298 for row in rows:
299 if _fresh(row.get("created_utc"), now):
300 row["score"] = None
301 row["score_pending"] = True
302 kept = union_comments([], rows)[:COMMENTS_PER_THREAD]
303 if kept:
304 item["top_comments"] = kept
305 item["comments_source"] = ARCTIC
306 _stamp_uploader(item)
307 filled += 1
308 return filled, failed, throttled
309
310
311 def in_window(item: dict, from_date: Optional[str], to_date: Optional[str]) -> bool:
312 """Whether a hydrated thread is in the window (see ``_in_window``)."""
313 return _in_window(item, from_date, to_date)
314
315
316 def attach_comments(
317 items: list[dict], depth: str = "default", deadline: Optional[float] = None,
318 now: Optional[float] = None,
319 ) -> int:
320 """Archive comments for ``items`` hydrated with ``comments=False``, within
321 the lane's comment budget. Returns how many threads gained comments."""
322 filled, _failed, _throttled = _attach_comments(items, depth, deadline, time.time() if now is None else now)
323 return filled
324
325
326 def on_topic_count(items: Iterable[dict], topic: str) -> int:
327 """Threads whose title names the topic. A pending score does not matter."""
328 items = list(items)
329 if not topic:
330 return len(items)
331 from .reddit_discover import names_topic
332
333 return sum(names_topic(str(item.get("title") or ""), topic) for item in items)
334
335
336 def _effective_score_rank(post: dict) -> int:
337 """Rank a post's score trustworthiness.
338
339 An explicit ``engagement_source`` (including ``LIVE`` with a measured 0)
340 uses ``score_rank``. An unlabeled dict with a placeholder 0/None score
341 ranks as ``UNKNOWN`` so missing votes never overwrite measured scores.
342 """
343 source = post.get("engagement_source")
344 if source:
345 return score_rank(source)
346 engagement = post.get("engagement") or {}
347 score = engagement.get("score") if engagement.get("score") is not None else post.get("score")
348 if _is_number(score) and score != 0:
349 return score_rank(LIVE)
350 return score_rank(UNKNOWN)
351
352
353 def merge_post(existing: dict, incoming: dict) -> None:
354 """Fold another layer's copy of a thread into ``existing``, field by field."""
355 mine = existing.setdefault("engagement", {})
356 theirs = incoming.get("engagement") or {}
357 if _effective_score_rank(incoming) > _effective_score_rank(existing):
358 mine["score"] = theirs.get("score")
359 existing["score"] = theirs.get("score")
360 existing["engagement_source"] = incoming.get("engagement_source") or LIVE
361 count = theirs.get("num_comments")
362 if _is_number(count) and not (_is_number(mine.get("num_comments")) and mine["num_comments"] >= count):
363 mine["num_comments"] = count
364 existing["num_comments"] = count
365 if incoming.get("top_comments"):
366 sources = {existing.get("comments_source"), incoming.get("comments_source")} - {None}
367 existing["top_comments"] = union_comments(
368 existing.get("top_comments") or [], incoming["top_comments"],
369 )[:COMMENTS_PER_THREAD]
370 existing["comments_source"] = "+".join(sorted(sources)) or LIVE
371 for key in ("title", "date", "selftext", "author", "matched_comment"):
372 if not existing.get(key) and incoming.get(key):
373 existing[key] = incoming[key]
374 existing["provenance"] = sorted(set(existing.get("provenance") or []) | set(incoming.get("provenance") or []))
375
376
377 def _merge_sc(
378 items: list[dict], sc_items: Iterable[dict], topic: str,
379 from_date: Optional[str], to_date: Optional[str],
380 ) -> int:
381 by_id = {item["metadata"]["post_id"]: item for item in items}
382 added = 0
383 for raw in sc_items or []:
384 if not isinstance(raw, dict):
385 continue
386 ref = canonical_thread(str(raw.get("url") or ""))
387 if ref is None:
388 continue
389 ref.provenance.add("sc")
390 post = dict(raw)
391 post.setdefault("engagement_source", LIVE)
392 if post.get("top_comments"):
393 post.setdefault("comments_source", "sc")
394 post = _finish(post, ref, topic)
395 if not _in_window(post, from_date, to_date):
396 continue
397 if ref.post_id in by_id:
398 merge_post(by_id[ref.post_id], post)
399 else:
400 by_id[ref.post_id] = post
401 items.append(post)
402 added += 1
403 return added
404
405
406 def _detail(items: list[dict], served: set[str], arctic_state: str) -> str:
407 paths = set(served)
408 for item in items:
409 paths.update(p for p in item.get("provenance") or [] if p in _PATH_ORDER)
410 named = "+".join(p for p in _PATH_ORDER if p in paths) or "reddit"
411 detail = f"{named} served {len(items)}"
412 if arctic_state in ("down", "throttled"):
413 detail += f"; arctic {arctic_state}"
414 return detail
415
416
417 def hydrate(
418 refs: Iterable[ThreadRef],
419 *,
420 topic: str = "",
421 depth: str = "default",
422 from_date: Optional[str] = None,
423 to_date: Optional[str] = None,
424 comments: bool = True,
425 session_hydrator: Optional[SessionHydrator] = None,
426 sc_fetch: Optional[Callable[[], Iterable[dict]]] = None,
427 sc_min_items: int = env.REDDIT_SC_MIN_ITEMS_DEFAULT,
428 deadline: Optional[float] = None,
429 now: Optional[float] = None,
430 ) -> Hydration:
431 """Hydrate ``refs`` through the chain described in the module docstring.
432
433 ``from_date``/``to_date`` (YYYY-MM-DD) keep threads whose post date is in
434 the window; a thread with no known date stays. ``sc_fetch`` is passed only
435 by a caller that holds a ScrapeCreators key, and returns Reddit lane items.
436 ``deadline`` is a ``time.monotonic()`` bound; ``now`` is the epoch clock
437 used for the pending-score age.
438 """
439 now = time.time() if now is None else now
440 by_id = _merge_refs(refs)
441 posts: dict[str, dict] = {}
442 served: set[str] = set()
443 dropped = 0
444
445 if session_hydrator is not None and by_id:
446 try:
447 got = session_hydrator(list(by_id.values())) or {}
448 except Exception as exc: # a session failure must not stop the free chain
449 _log(f"session hydration failed: {type(exc).__name__}: {exc}")
450 got = {}
451 for pid, post in got.items():
452 if pid in by_id and isinstance(post, dict) and post.get("_drop"):
453 # The session's privacy rules or a thread 403 exclude it:
454 # no other hydrator may bring it back.
455 del by_id[pid]
456 dropped += 1
457 continue
458 if pid in by_id and isinstance(post, dict):
459 post = dict(post)
460 post.setdefault("engagement_source", LIVE)
461 if post.get("top_comments"):
462 post.setdefault("comments_source", "session")
463 posts[pid] = post
464 if posts:
465 served.add("session")
466
467 missing = [pid for pid in by_id if pid not in posts]
468 arctic_state = "unused"
469 # An archive already throttled or down this run is not asked again.
470 from . import reddit_health
471
472 skipped = reddit_health.skip_reason("arctic") if missing else None
473 if skipped:
474 arctic_state = "throttled" if skipped == reddit_health.THROTTLED else "down"
475 _log(f"arctic skipped ({skipped}); {len(missing)} threads keep search-result data")
476 elif missing:
477 found, arctic_state = reddit_arctic.fetch_posts_by_ids(missing, deadline=deadline)
478 for pid, post in found.items():
479 if pid in by_id:
480 label_archive_post(post, now)
481 ref = by_id[pid]
482 actual_sub = str(post.get("subreddit") or "").strip().lower()
483 ref_sub = str(ref.subreddit or "").strip().lower()
484 if ref.matched_comment is not None and (not actual_sub or actual_sub != ref_sub):
485 ref.matched_comment_verified = False
486 ref.matched_comment = None
487 posts[pid] = post
488 if found:
489 served.add("arctic")
490 unfilled = len(missing) - len(found)
491 if unfilled:
492 _log(f"{unfilled} of {len(missing)} threads kept search-result data only (arctic {arctic_state})")
493
494 # A thread only the logged-in session found, that neither the session's
495 # thread JSON nor the public archive filled, may be from a community a
496 # logged-out reader cannot see: it is not shown on search-result data.
497 session_only = [
498 pid for pid, ref in by_id.items() if pid not in posts and ref.provenance == {"session"}
499 ]
500 for pid in session_only:
501 del by_id[pid]
502 if session_only:
503 _log(f"{len(session_only)} session-only threads had no public copy; left out")
504 if dropped:
505 _log(f"{dropped} threads left out by the session's privacy rules or a thread refusal")
506 items = [
507 _finish(posts.get(pid) or _from_search_result(ref), ref, topic)
508 for pid, ref in by_id.items()
509 ]
510 items = [item for item in items if _in_window(item, from_date, to_date)]
511
512 filled = failed = throttled = 0
513 if comments and items and not skipped and arctic_state not in ("down", "throttled"):
514 filled, failed, throttled = _attach_comments(items, depth, deadline, now)
515 if filled:
516 served.add("arctic")
517
518 if sc_fetch is not None:
519 on_topic = on_topic_count(items, topic)
520 if on_topic < max(sc_min_items, 1):
521 try:
522 sc_items = list(sc_fetch() or [])
523 except Exception as exc: # the backup must never break the free result
524 _log(f"ScrapeCreators backup failed: {type(exc).__name__}: {exc}")
525 sc_items = []
526 if _merge_sc(items, sc_items, topic, from_date, to_date):
527 served.add("sc")
528
529 return Hydration(
530 items=items, detail=_detail(items, served, arctic_state), arctic_state=arctic_state,
531 comment_fills=filled, comment_failures=failed, comment_throttles=throttled,
532 )
533
533 lines PYTHON