返回 last30days-skill
reddit_keyless.py
根目录 / skills / last30days / scripts / lib / reddit_keyless.py
1 """Keyless Reddit pipeline: free discovery + comment enrichment.
2
3 ``search.json`` is permanently 403/429 keyless, so it is not used. Discovery
4 runs on the surfaces that still serve data without a key, then enrichment runs
5 on whatever was discovered:
6
7 Host threads thread URLs or ids the host found with its own web search
8 (``--reddit-threads``, reddit_envelope): hydrated once per
9 run through the same chain, held to the window and the
10 topic bar, and routed to the subquery they match best.
11 Session with the user's consent, their logged-in reddit.com
12 session (reddit_session): post, comment and community
13 search, and thread JSON as the first hydrator for every
14 layer. Runs first; keyless site search is skipped when it
15 served, and the web floor runs only when it found fewer
16 on-topic threads than the ScrapeCreators floor.
17 Dedicated lane entity-home subreddits (e.g. r/Kanye) pulled in full via the
18 shreddit listing partials (top+hot+new, real scores), kept
19 whole (floor-exempt) because the sub IS the topic.
20 Search lane Reddit's site search fragment (reddit_search): global keyword
21 search plus per-sub search for targeted subreddits. Results
22 arrive dated and scored. Relevance-floored.
23 Web floor keyless web search for recent ``site:reddit.com`` threads
24 (reddit_discover), hydrated through reddit_hydrate (Arctic
25 Shift, else the search result itself). Threads whose title,
26 or whose body in a resolved or dedicated subreddit, does
27 not name the topic are dropped before any merge.
28 Listings the last discovery rung: targeted runs merge the
29 subreddits' listing partials; dedicated subs are pulled in
30 full.
31 Enrichment shreddit comment + count enrichment (reddit_shreddit) for the
32 top-ranked posts (author + score + text + permalink).
33
34 Each path has a health state (``reddit_health``): a site search or web rung
35 refused with a 403 or a challenge page is skipped for 6 h across runs, a 429
36 for the rest of the run. Site search failures stay out of the stream's
37 failure sink: one refused path is a detail note, never the source's outcome.
38 A caller that opens ``lane_paths()`` gets each path's state for the call,
39 which the pipeline turns into the served-path detail.
40
41 Returns ``[]`` (never raises) so ``pipeline.py`` can fall through to the
42 ScrapeCreators backup when every keyless lane comes up empty.
43 """
44
45 import concurrent.futures
46 import contextlib
47 import contextvars
48 import math
49 import sys
50 import time
51 from concurrent.futures import ThreadPoolExecutor
52 from typing import Any, Dict, List, Mapping, Optional
53
54 from . import health, http
55 from . import reddit_search, reddit_shreddit, reddit_listing, reddit_arctic
56 from . import reddit_discover, reddit_envelope, reddit_health, reddit_hydrate, reddit_refs, reddit_session, web_search_keyless
57 # High-upvote posts from targeted-sub listings can bury on-topic search hits
58 # under an engagement-first final sort. A relevance floor + relevance-first
59 # final ranking keeps the section on-topic. Thresholds are shared with the
60 # keyed path (reddit.py) via relevance.py.
61 from .relevance import RELEVANCE_FLOOR, MIN_ON_TOPIC
62
63 ENRICH_LIMITS = reddit_shreddit.ENRICH_LIMITS
64 ENRICH_BUDGET = 45 # seconds total across all enrichment threads
65 MAX_ENRICH_WORKERS = 4
66 # Dedicated subreddits (the entity's home, e.g. r/Kanye for "Kanye West") are
67 # wholly on-topic, so pull top+hot+new — the top-of-month listing alone misses
68 # fresh threads — and keep every item (floor-exempt).
69 DEDICATED_SORTS = ["top", "hot", "new"]
70 # The lane's stages each carry their own budget (listing archive 45s twice,
71 # site search, enrichment 45s plus the shared bucket's queue), and on a busy
72 # run their sum passes the pipeline's wait for the source, which then reports
73 # a timeout and keeps none of the threads already found. The caller's
74 # deadline bounds the whole lane: a stage that no longer fits is skipped and
75 # the lane returns what it has.
76 MIN_STAGE_SECONDS = 2.0
77 _lane_deadline: contextvars.ContextVar[Optional[float]] = contextvars.ContextVar(
78 "last30days_reddit_lane_deadline", default=None,
79 )
80
81
82 @contextlib.contextmanager
83 def lane_deadline(deadline: Optional[float]):
84 """Bound search_and_enrich calls in this context by a ``time.monotonic()`` deadline."""
85 token = _lane_deadline.set(deadline)
86 try:
87 yield
88 finally:
89 _lane_deadline.reset(token)
90
91
92 # Notes the lane wants on the Reddit source's detail line (such as how many
93 # web-floor threads the topic bar dropped). The caller opens a sink with
94 # lane_notes(); with none open, a note is only logged.
95 _lane_notes: contextvars.ContextVar[Optional[List[str]]] = contextvars.ContextVar(
96 "last30days_reddit_lane_notes", default=None,
97 )
98
99
100 @contextlib.contextmanager
101 def lane_notes():
102 """Collect the lane's detail notes made in this context; yields the list."""
103 notes: List[str] = []
104 token = _lane_notes.set(notes)
105 try:
106 yield notes
107 finally:
108 _lane_notes.reset(token)
109
110
111 # Each Reddit path's state for one lane call (``search``, the web rungs,
112 # ``listing``, ``arctic``), in reddit_health's vocabulary. The caller opens a
113 # sink with lane_paths() and turns it into the served-path detail.
114 _lane_paths: contextvars.ContextVar[Optional[Dict[str, str]]] = contextvars.ContextVar(
115 "last30days_reddit_lane_paths", default=None,
116 )
117
118
119 @contextlib.contextmanager
120 def lane_paths():
121 """Collect each Reddit path's state for lane calls in this context; yields the dict."""
122 paths: Dict[str, str] = {}
123 token = _lane_paths.set(paths)
124 try:
125 yield paths
126 finally:
127 _lane_paths.reset(token)
128
129
130 def _mark(path: str, state: Optional[str]) -> None:
131 sink = _lane_paths.get()
132 if sink is not None and state:
133 sink[path] = state
134
135
136 def _note(msg: Optional[str]) -> None:
137 if not msg:
138 return
139 _log(msg)
140 sink = _lane_notes.get()
141 if sink is not None and msg not in sink:
142 sink.append(msg)
143
144
145 def _out_of_time(deadline: Optional[float]) -> bool:
146 return deadline is not None and deadline - time.monotonic() < MIN_STAGE_SECONDS
147
148
149 # A stage is told to finish this long before the lane stops waiting for it,
150 # so it has time to assemble and hand back what it fetched. With one shared
151 # deadline the stage reached it mid-request, and the wait gave up at the same
152 # moment and put an empty result in place of the threads already fetched.
153 STAGE_RETURN_MARGIN_SECONDS = 3.0
154
155
156 def _stage_deadline(deadline: Optional[float], name: str = "deadline") -> Dict[str, float]:
157 """The keyword that gives a stage its own, earlier deadline; ``{}`` with none."""
158 if deadline is None:
159 return {}
160 return {name: deadline - STAGE_RETURN_MARGIN_SECONDS}
161
162
163 def _within(wait_until: Optional[float], stage: str, default: Any, call, /, *args, **kwargs) -> Any:
164 """Run one discovery call and stop waiting for it at the lane deadline.
165
166 The search, listing and score calls wait for their own workers on their
167 own timeouts, so a call started with seconds left could run past the
168 pipeline's wait for the source and take the threads already found with
169 it. Under a deadline the call runs on a worker that is abandoned when the
170 deadline passes, and ``default`` stands in for its result. With no
171 deadline the call runs inline, as before.
172 """
173 if wait_until is None:
174 return call(*args, **kwargs)
175 executor = ThreadPoolExecutor(max_workers=1)
176 try:
177 future = http.submit_with_context(executor, call, *args, **kwargs)
178 try:
179 return future.result(timeout=max(0.0, wait_until - time.monotonic()))
180 except concurrent.futures.TimeoutError:
181 _log(f"{stage} still running at the lane deadline; returning without it")
182 return default
183 finally:
184 executor.shutdown(wait=False, cancel_futures=True)
185
186
187 def _relevance_rank_key(post: Dict[str, Any]) -> float:
188 """Rank by relevance first, with a bounded engagement bonus as tiebreaker.
189
190 Mirrors reddit.py: the log-scaled bonus (capped at 0.25) orders
191 similarly-relevant posts by discussion volume but is too small to lift an
192 off-topic post (relevance ~0) above an on-topic one.
193 """
194 eng = post.get("engagement", {})
195 total = (eng.get("score", 0) or 0) + (eng.get("num_comments", 0) or 0)
196 return (post.get("relevance") or 0.0) + min(0.25, math.log10(max(0, total) + 1) / 20.0)
197
198
199 def _log(msg: str) -> None:
200 sys.stderr.write(f"[RedditKeyless] {msg}\n")
201 sys.stderr.flush()
202
203
204 _TIMED_OUT = object()
205
206
207 def _apply_scores(post: Dict[str, Any], scored: Dict[str, Any]) -> None:
208 engagement = post.setdefault("engagement", {})
209 existing_source = post.get("engagement_source")
210 incoming_source = scored.get("engagement_source")
211 existing_rank = reddit_hydrate._effective_score_rank(post)
212 incoming_rank = (
213 reddit_refs.score_rank(incoming_source)
214 if incoming_source is not None
215 else reddit_refs.score_rank(reddit_refs.LIVE)
216 )
217 if incoming_rank >= existing_rank:
218 post["score"] = scored["score"]
219 engagement["score"] = scored["score"]
220 if incoming_source and (
221 not existing_source or incoming_rank > existing_rank
222 ):
223 post["engagement_source"] = incoming_source
224 counts = [
225 v for v in (
226 post.get("num_comments"),
227 engagement.get("num_comments"),
228 scored.get("num_comments"),
229 )
230 if isinstance(v, (int, float)) and not isinstance(v, bool)
231 ]
232 num_comments = int(max(counts)) if counts else 0
233 post["num_comments"] = num_comments
234 engagement["num_comments"] = num_comments
235
236
237 def _needs_score_backfill(post: Dict[str, Any]) -> bool:
238 """True when ``post`` lacks a measured score and has not already tried Arctic Shift."""
239 if post.get("engagement", {}).get("score"):
240 return False
241 source = post.get("engagement_source")
242 if not source:
243 return True
244 if source == reddit_refs.UNKNOWN:
245 prov = set(post.get("provenance") or [])
246 return not (prov & {"web", "host", "session"})
247 return False
248
249
250 def _listing_timeframe(from_date: Optional[str], to_date: Optional[str]) -> str:
251 from .reddit import _window_to_time_filter
252 return _window_to_time_filter(from_date or "", to_date or "")
253
254
255 def _is_listing_block_failure(failure: Any) -> bool:
256 if getattr(failure, "status_code", None) == 403:
257 return True
258 msg = str(failure).lower()
259 return "reddit listing interstitial" in msg or "blocked by network security" in msg
260
261
262 def _classify_listing_state(
263 posts: List[Dict[str, Any]],
264 failures: List[Any],
265 *,
266 timed_out: bool = False,
267 failed: bool = False,
268 ) -> str:
269 if posts:
270 return reddit_health.OK
271 snapshot = list(failures)
272 if any(_is_listing_block_failure(f) for f in snapshot):
273 return reddit_health.BLOCKED
274 if (
275 snapshot
276 and not timed_out
277 and not failed
278 and all(getattr(f, "status_code", None) == 429 for f in snapshot)
279 ):
280 return reddit_health.THROTTLED
281 if snapshot or timed_out or failed:
282 return reddit_health.ERROR
283 return reddit_health.EMPTY
284
285
286 def _combine_listing_states(states: List[str], has_posts: bool) -> str:
287 if has_posts or reddit_health.OK in states:
288 return reddit_health.OK
289 if reddit_health.EMPTY in states:
290 return reddit_health.EMPTY
291 if states and all(s == reddit_health.THROTTLED for s in states):
292 return reddit_health.THROTTLED
293 if reddit_health.BLOCKED in states:
294 return reddit_health.BLOCKED
295 return reddit_health.ERROR
296
297
298 def _scored_listings_with_state(
299 subreddits: List[str],
300 depth: str = "default",
301 query: str = "",
302 sorts: Optional[List[str]] = None,
303 from_date: Optional[str] = None,
304 to_date: Optional[str] = None,
305 deadline: Optional[float] = None,
306 ) -> tuple[List[Dict[str, Any]], str]:
307 """Scored subreddit listings plus health state: shreddit partials, arctic-shift supplement.
308
309 The shreddit ``community-more-posts`` partials 403 from datacenter IPs
310 (and any host Reddit decides to block). Shreddit is tried first; arctic-
311 shift supplements with any posts shreddit missed. Individual sort lanes
312 can fail silently (shreddit's ``fetch_listings`` flattens results without
313 exposing per-sort status), so arctic is called for all requested subreddits
314 and merged via deduplication. Both calls run inside
315 ``http.capture_failures()`` so listing HTTP failures stay isolated from the
316 outer stream sink while still classifying listing health accurately. Never
317 raises.
318 """
319 timeframe = _listing_timeframe(from_date, to_date)
320 posts: List[Dict[str, Any]] = []
321 timed_out = False
322 failed = False
323 with http.capture_failures() as failures:
324 try:
325 shreddit_res = _within(
326 deadline, "subreddit listing", _TIMED_OUT,
327 reddit_listing.fetch_listings, subreddits, depth=depth, query=query, sorts=sorts,
328 timeframe=timeframe,
329 **_stage_deadline(deadline),
330 )
331 except Exception as exc: # defensive: listings must never break the pipeline
332 _log(f"shreddit listing fetch failed: {exc}")
333 failed = True
334 else:
335 if shreddit_res is _TIMED_OUT:
336 timed_out = True
337 elif shreddit_res:
338 posts = list(shreddit_res)
339
340 arctic_posts: List[Dict[str, Any]] = []
341
342 # Supplement with arctic for all requested subreddits. Shreddit's per-sort
343 # success/failure is opaque, so arctic provides coverage for any failed
344 # sort lanes (e.g., hot/new failing while top succeeded). Deduplication
345 # ensures no redundant posts when shreddit fully succeeded.
346 if subreddits and _out_of_time(deadline):
347 _log("arctic-shift supplement skipped: lane budget spent")
348 elif subreddits:
349 try:
350 arctic_res = _within(
351 deadline, "arctic-shift supplement", _TIMED_OUT,
352 reddit_arctic.fetch_listings,
353 subreddits, depth=depth, query=query, sorts=sorts,
354 from_date=from_date, to_date=to_date,
355 **_stage_deadline(deadline, "lane_deadline"),
356 )
357 except Exception as exc: # the fallback must never break the pipeline
358 _log(f"arctic-shift listing supplement failed: {exc}")
359 failed = True
360 else:
361 if arctic_res is _TIMED_OUT:
362 timed_out = True
363 elif arctic_res:
364 arctic_posts = list(arctic_res)
365 if arctic_posts:
366 # An archive count on a fresh post is not a settled score yet.
367 now = time.time()
368 for p in arctic_posts:
369 reddit_hydrate.label_archive_post(p, now)
370 # Merge and dedupe by thread key (fallback URL) — shreddit posts take priority.
371 seen_urls = {p["url"] for p in posts}
372 seen_keys = {
373 k for p in posts if (k := reddit_refs.thread_key(p.get("url", "")))
374 }
375 added = 0
376 for p in arctic_posts:
377 key = reddit_refs.thread_key(p.get("url", ""))
378 if p["url"] in seen_urls or (key and key in seen_keys):
379 continue
380 seen_urls.add(p["url"])
381 if key:
382 seen_keys.add(key)
383 posts.append(p)
384 added += 1
385 if added:
386 _log(f"arctic-shift supplement: {added} new posts from {len(arctic_posts)} arctic results")
387
388 state = _classify_listing_state(posts, failures, timed_out=timed_out, failed=failed)
389 return posts, state
390
391
392 def _scored_listings(
393 subreddits: List[str],
394 depth: str = "default",
395 query: str = "",
396 sorts: Optional[List[str]] = None,
397 from_date: Optional[str] = None,
398 to_date: Optional[str] = None,
399 deadline: Optional[float] = None,
400 ) -> List[Dict[str, Any]]:
401 """Scored subreddit listings: shreddit partials, arctic-shift supplement. Never raises."""
402 posts, _state = _scored_listings_with_state(
403 subreddits, depth=depth, query=query, sorts=sorts,
404 from_date=from_date, to_date=to_date, deadline=deadline,
405 )
406 return posts
407
408
409 # Reserve up to 8s (capped at 40% of remaining budget) before the lane deadline
410 # so a slow second web query leaves room to hydrate query one's refs without
411 # starving the first query when only a few seconds remain.
412 _WEB_HYDRATION_RESERVE_SECONDS = 8.0
413 _WEB_HYDRATION_MIN_SECONDS = 0.5
414
415
416 def _web_discover_deadline(
417 deadline: Optional[float], now: Optional[float] = None,
418 ) -> Optional[float]:
419 if deadline is None:
420 return None
421 current = time.monotonic() if now is None else now
422 remaining = deadline - current
423 if remaining <= _WEB_HYDRATION_MIN_SECONDS:
424 return deadline
425 reserve = min(_WEB_HYDRATION_RESERVE_SECONDS, remaining * 0.4)
426 return deadline - reserve
427
428
429 def _hydrate_stage_deadline(deadline: Optional[float]) -> Dict[str, float]:
430 if deadline is None:
431 return {}
432 remaining = max(0.0, deadline - time.monotonic())
433 margin = min(STAGE_RETURN_MARGIN_SECONDS, remaining * 0.25)
434 return {"deadline": deadline - margin}
435
436
437 def _web_floor(
438 topic: str,
439 depth: str,
440 subreddits: Optional[List[str]],
441 dedicated_subreddits: Optional[List[str]],
442 from_date: Optional[str],
443 to_date: Optional[str],
444 deadline: Optional[float],
445 config: Optional[Mapping[str, Any]] = None,
446 ) -> List[Dict[str, Any]]:
447 """Web-search thread refs, hydrated and held to the topic bar. Never raises."""
448 reddit_health.seed_web_rungs()
449 try:
450 # Filled in place, so a floor still running at its cutoff hands back
451 # the threads its earlier queries found with time left to hydrate them.
452 partial = reddit_discover.WebFloor()
453 discover_cutoff = _web_discover_deadline(deadline)
454 discover_kw = {"deadline": discover_cutoff} if discover_cutoff is not None else {}
455 found = _within(
456 discover_cutoff, "web floor", None,
457 reddit_discover.web_refs,
458 topic, subreddits=subreddits, from_date=from_date, to_date=to_date,
459 floor=partial, **discover_kw,
460 **({"config": config} if config is not None else {}),
461 )
462 wait_expired = found is None
463 if wait_expired:
464 found = partial
465 floor = (
466 found.snapshot()
467 if hasattr(found, "snapshot")
468 else reddit_discover.WebFloor(
469 refs=list(found.refs), queries=list(found.queries), rungs=dict(found.rungs),
470 )
471 )
472 _record_web_rungs(floor)
473 _note_searxng_rung(floor)
474 if wait_expired or floor.timed_out:
475 _mark("web", health.TIMEOUT)
476 if not floor.refs:
477 return []
478 if deadline is not None and deadline - time.monotonic() < _WEB_HYDRATION_MIN_SECONDS:
479 _log("web floor hydration skipped: lane budget spent")
480 return []
481 hydrate_kw = _hydrate_stage_deadline(deadline)
482 hydrate_deadline = hydrate_kw.get("deadline", deadline)
483 session = reddit_session.current()
484 extra: Dict[str, Any] = {}
485 if session is not None and session.alive:
486 extra["session_hydrator"] = reddit_session.hydrator(
487 session, depth=depth, deadline=hydrate_deadline,
488 )
489 hydrated = _within(
490 deadline, "web floor hydration", None,
491 reddit_hydrate.hydrate,
492 floor.refs, topic=topic, depth=depth, from_date=from_date, to_date=to_date,
493 **extra, **hydrate_kw,
494 )
495 except Exception as exc: # the floor must never break the lane
496 _log(f"web floor failed: {type(exc).__name__}: {exc}")
497 return []
498 if hydrated is None:
499 return []
500 _record_arctic(hydrated.arctic_state)
501 _log(f"web floor: {hydrated.detail}")
502 bar = reddit_discover.apply_bar(
503 topic, hydrated.items, subreddits=subreddits, dedicated=dedicated_subreddits,
504 )
505 _note(bar.note("web search"))
506 for post in bar.kept:
507 post["topic_bar"] = True
508 return bar.kept
509
510
511 # What the optional SearXNG fallback answered when it failed. This is a note on the
512 # fallback itself. Its refusals say nothing about reddit.com, so they never become
513 # a Reddit path state or touch the shared rung health. The wording avoids every phrase
514 # that http.classify_failure reads, so a note can never change how a detail is classified.
515 _SEARXNG_NOTES = {
516 web_search_keyless.BLOCKED: "refused (403)",
517 web_search_keyless.THROTTLED: "throttled (429)",
518 health.TIMEOUT: "ran out of time",
519 web_search_keyless.ERROR: "failed",
520 }
521
522
523 def searxng_note_texts() -> frozenset[str]:
524 """Every note the SearXNG fallback can produce. Nothing else is ever shown as one."""
525 return frozenset(f"SearXNG fallback {note}" for note in _SEARXNG_NOTES.values())
526
527
528 def _note_searxng_rung(floor: "reddit_discover.WebFloor") -> None:
529 for state in floor.searxng_failures:
530 note = _SEARXNG_NOTES.get(state)
531 if note:
532 _note(f"SearXNG fallback {note}")
533
534
535 _RUNG_STATES = {
536 web_search_keyless.OK: reddit_health.OK,
537 web_search_keyless.EMPTY: reddit_health.EMPTY,
538 web_search_keyless.ERROR: reddit_health.ERROR,
539 web_search_keyless.THROTTLED: reddit_health.THROTTLED,
540 web_search_keyless.BLOCKED: reddit_health.BLOCKED,
541 }
542
543
544 def _record_web_rungs(floor: "reddit_discover.WebFloor") -> None:
545 """Persist what each web rung answered and mark the lane's web paths.
546
547 Only the call that asked a query sees its rung states; a later subquery
548 served from the run memo reads the run's rung health instead."""
549 if not floor.queries:
550 return
551 for rung, state in floor.rungs.items():
552 mapped = _RUNG_STATES.get(state)
553 if rung in reddit_health.WEB_RUNGS and mapped:
554 reddit_health.record(rung, mapped, f"web search {state}")
555 for rung, state in web_search_keyless.rung_health().items():
556 if rung not in reddit_health.WEB_RUNGS:
557 continue
558 if state == web_search_keyless.SKIPPED:
559 _mark(rung, reddit_health.SKIPPED_CACHED)
560 else:
561 _mark(rung, _RUNG_STATES.get(state))
562 _mark("web", reddit_health.OK if floor.refs else reddit_health.EMPTY)
563
564
565 def _record_arctic(state: str) -> None:
566 mapped = {
567 "ok": reddit_health.OK,
568 "throttled": reddit_health.THROTTLED,
569 "down": reddit_health.ERROR,
570 }.get(state)
571 if mapped:
572 reddit_health.record("arctic", mapped, f"posts/ids {state}")
573 _mark("arctic", mapped)
574
575
576 def _host_layer(
577 topic: str,
578 depth: str,
579 subreddits: Optional[List[str]],
580 dedicated_subreddits: Optional[List[str]],
581 from_date: Optional[str],
582 to_date: Optional[str],
583 deadline: Optional[float],
584 ) -> List[Dict[str, Any]]:
585 """The host's thread refs routed to this subquery: ``[]`` without an
586 envelope. Hydrated through the session first when one is open. Never raises."""
587 opened = reddit_envelope.current()
588 if opened is None:
589 return []
590 envelope, label = opened
591
592 def session_hydrator():
593 session = reddit_session.current()
594 if session is not None and session.alive:
595 return reddit_session.hydrator(session, depth=depth, deadline=deadline)
596 return None
597
598 try:
599 served = envelope.serve(
600 label, depth=depth, from_date=from_date, to_date=to_date,
601 subreddits=subreddits, dedicated=dedicated_subreddits,
602 session_hydrator=session_hydrator, deadline=deadline,
603 )
604 except Exception as exc: # the host lane must never break the Reddit lane
605 _log(f"host threads failed: {type(exc).__name__}")
606 return []
607 if served.arctic_state:
608 _record_arctic(served.arctic_state)
609 _note(served.note)
610 return served.items
611
612
613 def _session_layer(
614 topic: str,
615 depth: str,
616 from_date: Optional[str],
617 to_date: Optional[str],
618 deadline: Optional[float],
619 ) -> List[Dict[str, Any]]:
620 """The consented logged-in session: search, then hydrate through thread
621 JSON first. ``[]`` when no session is open for this lane call. Never raises."""
622 session = reddit_session.current()
623 if session is None:
624 return []
625 if not session.alive:
626 _mark("session", session.state)
627 if session.state == reddit_session.EXPIRED:
628 _note(f"session-expired: {reddit_session.relogin_hint(session)}")
629 return []
630 try:
631 found = _within(
632 deadline, "session search", None,
633 reddit_session.discover, session, topic, depth=depth,
634 from_date=from_date, to_date=to_date,
635 **_stage_deadline(deadline),
636 )
637 if found is None:
638 _mark("session", reddit_health.ERROR)
639 return []
640 if found.state == reddit_session.EXPIRED:
641 _mark("session", reddit_session.EXPIRED)
642 _note(f"session-expired: {reddit_session.relogin_hint(session)}")
643 return []
644 if not found.refs:
645 _mark("session", found.state or reddit_health.EMPTY)
646 return []
647 hydrated = _within(
648 deadline, "session hydration", None,
649 reddit_hydrate.hydrate,
650 found.refs, topic=topic, depth=depth, from_date=from_date, to_date=to_date,
651 session_hydrator=reddit_session.hydrator(session, found, depth=depth, deadline=deadline),
652 **_stage_deadline(deadline),
653 )
654 except Exception as exc: # the session must never break the lane
655 _log(f"session layer failed: {type(exc).__name__}")
656 _mark("session", reddit_health.ERROR)
657 return []
658 if hydrated is None:
659 _mark("session", reddit_health.ERROR)
660 return []
661 _record_arctic(hydrated.arctic_state)
662 kept = reddit_session.topic_bar(topic, hydrated.items)
663 if session.state == reddit_session.EXPIRED:
664 _mark("session", reddit_session.EXPIRED)
665 _note(f"session-expired: {reddit_session.relogin_hint(session)}")
666 else:
667 _mark("session", reddit_health.OK if kept else reddit_health.EMPTY)
668 for post in kept:
669 post["topic_bar"] = True
670 _log(f"session: {len(kept)} threads ({session.requests} session requests this run)")
671 return kept
672
673
674 def _site_search(
675 topic: str,
676 depth: str,
677 subreddits: Optional[List[str]],
678 from_date: Optional[str],
679 to_date: Optional[str],
680 deadline: Optional[float],
681 ) -> List[Dict[str, Any]]:
682 """Reddit's site search, gated and judged by its path health.
683
684 A search skipped earlier this run, or within a persisted skip, sends no
685 request. Its HTTP failures stay out of the stream's failure sink: a
686 refused site search is one path failing while the others still run, so
687 it is a detail note, never the Reddit source's outcome.
688 """
689 skip = reddit_health.skip_reason("search")
690 if skip:
691 _log(f"site search skipped ({skip})")
692 _mark("search", skip)
693 return []
694 with http.capture_failures() as failures:
695 posts = _within(
696 deadline, "site search", [],
697 reddit_search.search,
698 topic, depth=depth, subreddits=subreddits, from_date=from_date, to_date=to_date,
699 **_stage_deadline(deadline),
700 )
701 blocked = reddit_search._blocked_reason
702 statuses = {getattr(f, "status_code", None) for f in list(failures)}
703 if blocked:
704 state = reddit_health.BLOCKED
705 elif posts:
706 state = reddit_health.OK
707 elif 429 in statuses:
708 state = reddit_health.THROTTLED
709 elif failures:
710 state = reddit_health.ERROR
711 else:
712 state = reddit_health.EMPTY
713 reddit_health.record("search", state, blocked or "")
714 _mark("search", state)
715 for post in posts or []:
716 post.setdefault("provenance", ["search"])
717 return posts or []
718
719
720 def _discover(
721 topic: str,
722 depth: str,
723 subreddits: Optional[List[str]],
724 dedicated_subreddits: Optional[List[str]] = None,
725 from_date: Optional[str] = None,
726 to_date: Optional[str] = None,
727 deadline: Optional[float] = None,
728 config: Optional[Mapping[str, Any]] = None,
729 ) -> List[Dict[str, Any]]:
730 # The host's own thread refs come first (best-first, KTD12): they cost
731 # only hydration, and every other layer merges into them by thread id.
732 host_posts = (
733 [] if _out_of_time(deadline)
734 else _host_layer(
735 topic, depth, subreddits, dedicated_subreddits, from_date, to_date, deadline,
736 )
737 )
738 # The consented logged-in session runs next (best-first, KTD12): it
739 # searches the same site search logged in, so the keyless site search is
740 # skipped once it served.
741 session_posts = (
742 [] if _out_of_time(deadline)
743 else _session_layer(topic, depth, from_date, to_date, deadline)
744 )
745 session = reddit_session.current()
746 session_floor = session.sc_floor if session is not None else 0
747 session_on_topic = reddit_hydrate.on_topic_count(session_posts, topic)
748
749 # search.json is permanently 403/429 keyless (no Tier 0). Discovery is
750 # Reddit's site search: global, plus per-sub for targeted subreddits. The
751 # dedicated subs keep their full-listing lane below and are not searched.
752 if session_posts:
753 _log("site search skipped: the session served")
754 search_posts = []
755 elif _out_of_time(deadline):
756 _log("site search skipped: lane budget spent")
757 search_posts = []
758 else:
759 search_posts = _site_search(topic, depth, subreddits, from_date, to_date, deadline)
760
761 # Web floor: recent threads from keyless web search, hydrated and held to
762 # the topic bar. Runs before the listings, which stay the last rung. With
763 # a session that already found enough on-topic threads it is not needed.
764 if session_posts and session_on_topic >= max(session_floor, 1):
765 _log(f"web floor skipped: the session found {session_on_topic} on-topic threads")
766 web_posts: List[Dict[str, Any]] = []
767 elif _out_of_time(deadline):
768 _log("web floor skipped: lane budget spent")
769 web_posts = []
770 else:
771 web_posts = _web_floor(
772 topic, depth, subreddits, dedicated_subreddits, from_date, to_date, deadline,
773 **({"config": config} if config is not None else {}),
774 )
775
776 # Dedicated lane: the entity's home subs are wholly on-topic. Pull
777 # top+hot+new (real scores from the listing) and mark them floor-exempt so
778 # an on-topic post whose title lacks the entity name is never dropped.
779 listing_states: List[str] = []
780 dedicated_posts: List[Dict[str, Any]] = []
781 if dedicated_subreddits:
782 dedicated_posts, dedicated_state = _scored_listings_with_state(
783 dedicated_subreddits, depth=depth, query=topic, sorts=DEDICATED_SORTS,
784 from_date=from_date, to_date=to_date, deadline=deadline,
785 )
786 listing_states.append(dedicated_state)
787 for p in dedicated_posts:
788 p["dedicated"] = True
789 p.setdefault("provenance", ["listing"])
790 _log(f"Dedicated lane: {len(dedicated_posts)} posts from {dedicated_subreddits}")
791
792 # Targeted run: the caller chose these subreddits, so their listing cards
793 # are on-topic; include them as scored discovery. A bare run fetches no
794 # listings, so high-upvote off-topic posts cannot flood the results.
795 listing_posts: List[Dict[str, Any]] = []
796 if subreddits and not _out_of_time(deadline):
797 listing_posts, targeted_state = _scored_listings_with_state(
798 subreddits, depth=depth, query=topic, from_date=from_date, to_date=to_date,
799 deadline=deadline,
800 )
801 listing_states.append(targeted_state)
802 for p in listing_posts:
803 p.setdefault("provenance", ["listing"])
804 if listing_states:
805 _mark(
806 "listing",
807 _combine_listing_states(listing_states, bool(listing_posts or dedicated_posts)),
808 )
809 _log(
810 f"Tier 1 (site search) {len(search_posts)} posts; host {len(host_posts)}; "
811 f"web floor {len(web_posts)}; "
812 f"{'listing discovery ' + str(len(listing_posts)) if subreddits else 'no listings'}"
813 )
814
815 # Score lookup by post id, from the scored listing cards, carrying
816 # engagement_source so live scores are never overwritten by archive snapshots
817 # and unmeasured listing placeholders never enter the score map.
818 score_map: Dict[str, Dict[str, Any]] = {}
819 for p in listing_posts:
820 pid = p.get("metadata", {}).get("post_id", "")
821 if not pid or reddit_refs.score_pending(p):
822 continue
823 rank = reddit_hydrate._effective_score_rank(p)
824 if rank <= reddit_refs.score_rank(reddit_refs.UNKNOWN):
825 continue
826 src = p.get("engagement_source") or reddit_refs.LIVE
827 prev = score_map.get(pid)
828 if prev is not None and reddit_refs.score_rank(src) < reddit_refs.score_rank(prev.get("engagement_source")):
829 continue
830 score_map[pid] = {
831 "score": p["score"],
832 "num_comments": p["num_comments"],
833 "engagement_source": src,
834 }
835
836 # Merge: dedicated-sub posts first (floor-exempt), then scored listing posts
837 # (targeted only), then search results, merging copies of the same thread by
838 # canonical thread id so slugless search URLs and full listing URLs collapse
839 # into one item while preserving live scores over archive snapshots.
840 merged: List[Dict[str, Any]] = []
841 seen: set = set()
842 merged_by_thread: Dict[str, Dict[str, Any]] = {}
843 for p in dedicated_posts + listing_posts:
844 key = reddit_refs.thread_key(p.get("url", ""))
845 if key and key in merged_by_thread:
846 reddit_hydrate.merge_post(merged_by_thread[key], p)
847 continue
848 if p["url"] in seen:
849 continue
850 seen.add(p["url"])
851 if key:
852 merged_by_thread[key] = p
853 merged.append(p)
854 # Session threads merge by thread id, so a listing copy gains the
855 # session's comments and a thread found both ways stays one item.
856 for p in session_posts:
857 key = reddit_refs.thread_key(p.get("url", ""))
858 if key and key in merged_by_thread:
859 reddit_hydrate.merge_post(merged_by_thread[key], p)
860 merged_by_thread[key]["topic_bar"] = True
861 continue
862 if key:
863 merged_by_thread[key] = p
864 seen.add(p["url"])
865 merged.append(p)
866 for p in search_posts:
867 key = reddit_refs.thread_key(p.get("url", ""))
868 if key and key in merged_by_thread:
869 reddit_hydrate.merge_post(merged_by_thread[key], p)
870 continue
871 if p["url"] in seen:
872 continue
873 pid = reddit_listing._post_id(p["url"])
874 if pid in score_map:
875 _apply_scores(p, score_map[pid])
876 seen.add(p["url"])
877 if key:
878 merged_by_thread[key] = p
879 merged.append(p)
880 # Host and web-floor threads merge by thread id: a copy another rung
881 # already holds keeps that copy's live score and gains their comments,
882 # and the provenance of every path that found it.
883 by_thread = {}
884 for p in merged:
885 key = reddit_refs.thread_key(p.get("url", ""))
886 if key:
887 by_thread.setdefault(key, p)
888 for p in host_posts + web_posts:
889 key = reddit_refs.thread_key(p.get("url", ""))
890 if key in by_thread:
891 reddit_hydrate.merge_post(by_thread[key], p)
892 by_thread[key]["topic_bar"] = True
893 continue
894 if key:
895 by_thread[key] = p
896 merged.append(p)
897
898 # Backfill posts still at score 0 from the free arctic-shift archive. Posts
899 # already scored by search or a listing keep that live score; arctic only
900 # fills the gap, and is best-effort (never raises).
901 # Hydrated web-floor threads carry their own labeled score (a pending
902 # archive score stays pending) and are not looked up again.
903 need = [pid for p in merged
904 if _needs_score_backfill(p)
905 for pid in [reddit_listing._post_id(p["url"])] if pid]
906 if need and not _out_of_time(deadline):
907 scores = _within(
908 deadline, "score lookup", {}, reddit_arctic.fetch_scores, need,
909 **_stage_deadline(deadline),
910 )
911 filled = 0
912 now = time.time()
913 for p in merged:
914 if not _needs_score_backfill(p):
915 continue
916 pid = reddit_listing._post_id(p["url"])
917 if pid in scores:
918 _apply_scores(p, scores[pid])
919 reddit_hydrate.label_archive_post(p, now)
920 filled += 1
921 if filled:
922 _log(f"arctic-shift backfilled {filled} post scores")
923 return merged
924
925
926 def _fetch_enrichment(
927 url: str,
928 deadline: Optional[float] = None,
929 post_author: Optional[str] = None,
930 ) -> Dict[str, Any]:
931 """Fetch shreddit comments for ``url`` without touching any post dict. Never raises."""
932 try:
933 data = reddit_shreddit.fetch_comments(
934 url, deadline=deadline, post_author=post_author,
935 )
936 return data if isinstance(data, dict) else {}
937 except Exception:
938 return {}
939
940
941 def _apply_enrichment(post: Dict[str, Any], data: Optional[Dict[str, Any]]) -> None:
942 """Apply fetched comment data to ``post`` on the calling thread."""
943 if not isinstance(data, dict):
944 return
945 if data.get("top_comments"):
946 post["top_comments"] = data["top_comments"]
947 reddit_hydrate._stamp_uploader(post)
948 if data.get("comment_insights"):
949 post["comment_insights"] = data["comment_insights"]
950 num = data.get("num_comments")
951 if num is not None:
952 post["num_comments"] = num
953 post.setdefault("engagement", {})["num_comments"] = num
954
955
956 def _enrich_one(post: Dict[str, Any], deadline: Optional[float] = None) -> Dict[str, Any]:
957 """Fetch shreddit comments + real comment count without mutating ``post``. Never raises.
958
959 A thread that already has comments (the web floor's archive comments)
960 is left as it is and returns ``{}``."""
961 if post.get("top_comments"):
962 return {}
963 return _fetch_enrichment(
964 str(post.get("url") or ""),
965 deadline=deadline,
966 post_author=post.get("author"),
967 )
968
969
970 @contextlib.contextmanager
971 def _enrich_executor(max_workers: int, lane_deadline: Optional[float]):
972 """The enrichment pool. Under a lane deadline its exit does not join a
973 worker still queued in the shared bucket, so the lane returns on time
974 with the comments fetched so far."""
975 executor = ThreadPoolExecutor(max_workers=max_workers)
976 try:
977 yield executor
978 finally:
979 executor.shutdown(wait=lane_deadline is None, cancel_futures=lane_deadline is not None)
980
981
982 def _enrich(
983 posts: List[Dict[str, Any]], depth: str, lane_deadline: Optional[float] = None,
984 ) -> List[Dict[str, Any]]:
985 """Enrich the top N posts with comments under a total time budget."""
986 limit = ENRICH_LIMITS.get(depth, ENRICH_LIMITS["default"])
987 to_enrich = posts[:limit]
988 rest = posts[limit:]
989 if not to_enrich:
990 return posts
991 if _out_of_time(lane_deadline):
992 _log("comment enrichment skipped: lane budget spent")
993 return posts
994
995 # Leaving the executor joins running workers, so the archive fallback
996 # must stop by the same budget the wait below enforces.
997 budget = ENRICH_BUDGET
998 wait_timeout = ENRICH_BUDGET + http.reddit_keyless_wait_allowance(len(to_enrich))
999 if lane_deadline is not None:
1000 lane_left = lane_deadline - time.monotonic()
1001 budget = min(budget, lane_left)
1002 wait_timeout = min(wait_timeout, lane_left)
1003 deadline = time.monotonic() + budget
1004 try:
1005 with _enrich_executor(min(limit, MAX_ENRICH_WORKERS), lane_deadline) as executor:
1006 futures = {}
1007 for i, post in enumerate(to_enrich):
1008 if post.get("top_comments"):
1009 continue
1010 # Snapshot immutable values before submitting so an abandoned
1011 # worker never reads or mutates the returned post dict.
1012 url = str(post.get("url") or "")
1013 author = post.get("author")
1014 futures[http.submit_with_context(
1015 executor, _fetch_enrichment, url, deadline, author,
1016 )] = i
1017 if futures:
1018 # The budget covers the fetches; the allowance covers the shared
1019 # bucket's queue (other lanes, other entities in compare mode).
1020 done, not_done = concurrent.futures.wait(futures, timeout=max(0.0, wait_timeout))
1021 for future in done:
1022 idx = futures[future]
1023 try:
1024 data = future.result(timeout=0)
1025 except Exception:
1026 data = None
1027 _apply_enrichment(to_enrich[idx], data)
1028 for future in not_done:
1029 future.cancel()
1030 enriched = list(to_enrich)
1031 except Exception:
1032 enriched = to_enrich
1033
1034 return enriched + rest
1035
1036
1037 def _by_comments(posts: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
1038 """Stable-sort posts by comment count descending for enrichment slots.
1039
1040 Ties (equal counts, including unknown counts treated as 0) preserve the
1041 incoming order, which search_and_enrich's provisional score-first sort
1042 establishes. Mirrors _relevance_rank_key's `or 0` guard so a present-but-
1043 None count is treated as 0 rather than raising.
1044 """
1045 def _comment_count(post: Dict[str, Any]) -> int:
1046 eng = post.get("engagement") or {}
1047 return eng.get("num_comments") or post.get("num_comments") or 0
1048
1049 return sorted(posts, key=_comment_count, reverse=True)
1050
1051
1052 def _slot_priority(topic: str, posts: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
1053 """Order posts for enrichment slots: entity-matching posts first.
1054
1055 Comment slots (ENRICH_LIMITS) are scarce; spending them on high-upvote
1056 posts that rerank later demotes as entity misses starves the on-topic
1057 posts the user actually sees (2026-06-06 "OpenClaw vs Hermes" run:
1058 2,000+ upvote Gemma/GPU threads took every slot, then were demoted to
1059 zero). Mirror rerank's demotion signal via the shared `_entity_grounded`
1060 check (head token of the topic's stripped primary entity present in the
1061 post text) so slots go to posts likely to survive final ranking — keying
1062 on the same head token keeps the two paths from diverging. Falls back to
1063 token-overlap relevance when the topic yields no usable primary entity.
1064 Within each tier posts are ordered by comment count descending (stable:
1065 equal or unknown counts preserve the incoming score-first order), so the
1066 scarce slots go to the threads with the most discussion rather than to
1067 near-empty threads that merely ranked higher by score. Never raises; on
1068 any failure the incoming order is returned unchanged.
1069 """
1070 try:
1071 from . import relevance, rerank
1072
1073 def _post_text(post: Dict[str, Any]) -> str:
1074 return f"{post.get('title') or ''} {post.get('selftext') or ''}"
1075
1076 entity = rerank._primary_entity(topic).lower()
1077 if entity:
1078 def _matches(post: Dict[str, Any]) -> bool:
1079 return rerank._entity_grounded(_post_text(post), entity)
1080 else:
1081 prepared = relevance.PreparedQuery(topic)
1082
1083 def _matches(post: Dict[str, Any]) -> bool:
1084 return relevance.token_overlap_relevance(prepared, _post_text(post)) > 0.24
1085
1086 matches: List[Dict[str, Any]] = []
1087 misses: List[Dict[str, Any]] = []
1088 for post in posts:
1089 (matches if _matches(post) else misses).append(post)
1090 return _by_comments(matches) + _by_comments(misses)
1091 except Exception:
1092 return posts
1093
1094
1095 def search_and_enrich(
1096 topic: str,
1097 from_date: str,
1098 to_date: str,
1099 depth: str = "default",
1100 subreddits: Optional[List[str]] = None,
1101 dedicated_subreddits: Optional[List[str]] = None,
1102 config: Optional[Mapping[str, Any]] = None,
1103 ) -> List[Dict[str, Any]]:
1104 """Full keyless Reddit pipeline: discover then enrich.
1105
1106 Args:
1107 topic: Search topic
1108 from_date: Start date (YYYY-MM-DD)
1109 to_date: End date (YYYY-MM-DD)
1110 depth: 'quick', 'default', or 'deep'
1111 subreddits: Optional pre-resolved broad/category subreddit names (no r/)
1112 dedicated_subreddits: Optional entity-home subreddit names (no r/) pulled
1113 in full (top+hot+new) and exempt from the relevance floor.
1114 config: Optional pre-loaded per-run config mapping.
1115
1116 Returns:
1117 List of normalized item dicts matching the reddit_public output shape,
1118 with top_comments/comment_insights attached on enriched posts.
1119 Empty list when all keyless tiers fail (so SC backup can engage).
1120 """
1121 deadline = _lane_deadline.get()
1122 posts = _discover(
1123 topic, depth, subreddits, dedicated_subreddits, from_date=from_date, to_date=to_date,
1124 **({"deadline": deadline} if deadline is not None else {}),
1125 **({"config": config} if config is not None else {}),
1126 )
1127 if not posts:
1128 return []
1129
1130 # Date filter: keep posts in range or with unknown dates (mirrors reddit_public).
1131 posts = [
1132 p for p in posts
1133 if p.get("date") is None or (from_date <= p["date"] <= to_date)
1134 or from_date <= ((p.get("matched_comment") or {}).get("date") or "") <= to_date
1135 ]
1136
1137 # Relevance floor: strip zero-overlap posts (relevance exactly 0 = no
1138 # title/body token match at all) when anything relevant remains, so
1139 # high-upvote listing posts can't bury on-topic search
1140 # hits. Keep all only when nothing scored above zero.
1141 before = len(posts)
1142 # Dedicated-sub posts are floor-exempt: their whole subreddit is the topic,
1143 # so an on-topic post whose title lacks the entity name must not be dropped.
1144 # Web-floor threads already passed the topic bar, which is the stricter
1145 # judge of whether a thread names the topic.
1146 on_topic = [p for p in posts if p.get("dedicated") or p.get("topic_bar")
1147 or (p.get("relevance") or 0) >= RELEVANCE_FLOOR]
1148 if len(on_topic) >= MIN_ON_TOPIC:
1149 posts = on_topic
1150 else:
1151 nonzero = [p for p in posts if p.get("dedicated") or p.get("topic_bar")
1152 or (p.get("relevance") or 0) > 0]
1153 if nonzero:
1154 posts = nonzero
1155 if len(posts) < before:
1156 _log(f"Relevance floor dropped {before - len(posts)} off-topic posts")
1157
1158 # Provisional score-first order so enrichment-slot selection has a stable
1159 # within-tier tiebreak order to preserve: within each entity tier, slots go
1160 # to the most-commented threads first, and equal counts keep score order.
1161 posts.sort(
1162 key=lambda p: (
1163 p.get("engagement", {}).get("score", 0) or 0,
1164 p.get("relevance", 0) or 0,
1165 p.get("date") or "",
1166 ),
1167 reverse=True,
1168 )
1169
1170 # Enrichment slot selection is comment-aware within entity tiers:
1171 # entity-matching posts claim the scarce comment slots first, and within
1172 # each tier the most-commented threads get slots first (score order is the
1173 # stable tiebreak for equal counts).
1174 posts = _enrich(
1175 _slot_priority(topic, posts), depth,
1176 **({"lane_deadline": deadline} if deadline is not None else {}),
1177 )
1178
1179 # Final display order ranks relevance-first with a bounded engagement bonus,
1180 # so an off-topic high-upvote post can't outrank an on-topic one in what the
1181 # user sees. Enrichment above may have backfilled real comment counts.
1182 posts.sort(key=_relevance_rank_key, reverse=True)
1183
1184 for i, post in enumerate(posts):
1185 post["id"] = f"R{i + 1}"
1186
1187 return posts
1188
1189
1190 # Comments for the threads the report keeps. Lane-time enrichment above picks
1191 # its slots before the pipeline's own relevance prune and ranking, so most of
1192 # the threads that survive arrived without comments (3 to 5 of 12 in the
1193 # 2026-11-10 runs), and a thread's top comment is usually its best quote.
1194 # This pass runs from ``_finalize_items_by_source`` on the survivors, highest
1195 # ranked first. Threads the lane already enriched cost nothing, and repeat
1196 # URLs are served from the run memo.
1197 FINAL_ENRICH_LIMITS = {"quick": 6, "default": 12, "deep": 16}
1198 FINAL_ENRICH_BUDGET = 30 # seconds, at the shared 1 req/s pacing
1199
1200
1201 def enrich_source_items(
1202 items: List[Any],
1203 depth: str = "default",
1204 deadline: Optional[float] = None,
1205 ) -> List[Any]:
1206 """Attach top comments to the kept Reddit SourceItems that lack them.
1207
1208 Considers the first ``FINAL_ENRICH_LIMITS[depth]`` items (they arrive
1209 ranked), skips threads that have comments already or report none, and
1210 fetches the rest through the same paced, memoized comment fetch as the
1211 lane, under ``FINAL_ENRICH_BUDGET`` and the caller's ``deadline``. Each
1212 comment carries author, score and its own permalink. Never raises and
1213 never waits for a straggler: a thread whose fetch did not finish stays as
1214 it was.
1215 """
1216 limit = FINAL_ENRICH_LIMITS.get(depth, FINAL_ENRICH_LIMITS["default"])
1217 kept = [item for item in items if getattr(item, "source", None) == "reddit"][:limit]
1218 targets = [
1219 item for item in kept
1220 if item.url
1221 and not (item.metadata or {}).get("top_comments")
1222 and (item.engagement or {}).get("num_comments") != 0
1223 ]
1224 if not targets:
1225 return items
1226 budget = float(FINAL_ENRICH_BUDGET)
1227 if deadline is not None:
1228 budget = min(budget, deadline - time.monotonic())
1229 if budget < MIN_STAGE_SECONDS:
1230 _log("comments for kept threads skipped: no time left")
1231 return items
1232 end = time.monotonic() + budget
1233 executor = ThreadPoolExecutor(max_workers=min(len(targets), MAX_ENRICH_WORKERS))
1234 try:
1235 futures = {
1236 http.submit_with_context(
1237 executor,
1238 _fetch_enrichment,
1239 item.url,
1240 end,
1241 (item.metadata or {}).get("post_author") or item.author,
1242 ): item
1243 for item in targets
1244 }
1245 done, _not_done = concurrent.futures.wait(futures, timeout=budget)
1246 for future in done:
1247 item = futures[future]
1248 try:
1249 data = future.result(timeout=0) or {}
1250 except Exception:
1251 continue
1252 if data.get("top_comments"):
1253 item.metadata["top_comments"] = data["top_comments"]
1254 post_author = (item.metadata or {}).get("post_author") or item.author
1255 if post_author:
1256 reddit_hydrate._stamp_uploader({
1257 "author": post_author,
1258 "top_comments": item.metadata["top_comments"],
1259 })
1260 item.metadata["comment_insights"] = data.get("comment_insights") or []
1261 if data.get("num_comments") is not None:
1262 item.engagement["num_comments"] = data["num_comments"]
1263 except Exception as exc:
1264 _log(f"comments for kept threads failed: {exc}")
1265 finally:
1266 executor.shutdown(wait=False, cancel_futures=True)
1267 have = sum(1 for item in kept if (item.metadata or {}).get("top_comments"))
1268 _log(f"comments on {have} of {len(kept)} kept threads ({len(targets)} fetched after ranking)")
1269 return items
1270
1270 lines PYTHON