返回 last30days-skill
reddit_arctic.py
根目录 / skills / last30days / scripts / lib / reddit_arctic.py
1 """Arctic-shift score resolver — post upvote counts by id, keyless and free.
2
3 ``search.json`` and ``/comments/{id}.json`` are 403 keyless. Site search and the
4 shreddit listing partials usually carry a score, but some posts still arrive
5 unscored. For a thread that reaches the merge with score 0, the free score
6 comes from arctic-shift
7 (https://arctic-shift.photon-reddit.com), a public Reddit archive whose
8 ``/api/posts/ids`` returns the post object (score, num_comments, title) for a
9 batch of base36 post ids. Scores are point-in-time snapshots — slightly stale vs
10 live, which is fine for ranking and display.
11
12 Best-effort, never raises. On rate-limit (HTTP 422 "slow down"), error, or an
13 unreachable host it returns ``{}`` so the caller shows the thread without a point
14 count rather than failing the Reddit source.
15 """
16
17 import inspect
18 import math
19 import re
20 import sys
21 import threading
22 import time
23 from dataclasses import dataclass, field
24 from datetime import date, datetime, timezone
25 from typing import Any, Callable, Dict, List, Optional
26 from urllib.parse import urlencode
27
28 from . import http, reddit_refs
29
30 _ISO_DATE = re.compile(r"^\d{4}-\d{2}-\d{2}\Z")
31
32 API = "https://arctic-shift.photon-reddit.com/api/posts/ids"
33 SEARCH_API = "https://arctic-shift.photon-reddit.com/api/posts/search"
34 COMMENTS_TREE_API = "https://arctic-shift.photon-reddit.com/api/comments/tree"
35 BATCH = 50 # ids per request
36 IDS_BATCH = 100 # ids per hydration request; the archive documents a 500-id limit
37 TIMEOUT = 15
38 MAX_BATCHES = 3 # cap total requests per run (bounds latency + rate-limit risk)
39 PACE_SECONDS = 0.4 # gap between batches; arctic-shift answers 422 "slow down"
40 CACHE_MAX = 4096 # hard size bound so the in-run memo can never grow unbounded
41 # Listing-lane knobs. Base limits mirror reddit_listing's DEPTH_LIMITS so callers
42 # get the same per-depth volume. The supplement multiplier is applied when the
43 # caller requested multiple sorts (top/hot/new) — arctic-shift has no sort lanes
44 # (only asc/desc), so we fetch more posts to increase the chance of covering
45 # what the failed shreddit lanes would have returned. Windowed runs
46 # (from_date/to_date) instead slice the window and keep the highest-scored
47 # posts, which recovers window-top engagement without sort lanes.
48 #
49 _LISTING_DEPTH_LIMITS = {"quick": 10, "default": 25, "deep": 50}
50 _LISTING_SUPPLEMENT_MULTIPLIER = 2 # fetch 2x posts when supplementing multi-sort requests
51 # Total deadline for listing fetches to prevent unbounded stalls when many
52 # subreddits are requested and arctic is slow/unreachable.
53 _LISTING_DEADLINE_SECONDS = 45 # ~3 subs at 15s timeout each
54 # Comment tree rows read by hydration (fetch_comment_tree).
55 MAX_COMMENT_ROWS = 100
56 # Comment fallback (fetch_post_comments) rows. The archive's comment search
57 # sorts only by created_utc, so a capped search slice of a busy thread held only
58 # its newest replies and missed its most upvoted ones. The fallback reads the
59 # comment tree instead and ranks by score client-side; on a 628-reply thread a
60 # 500-row tree kept the same top replies as an uncapped one (#1467).
61 FALLBACK_COMMENT_ROWS = 500
62 # In-run memo: base36 id -> {score, num_comments}. Module-level so repeated
63 # fetch_scores calls within one `/last30days` run (e.g. across subqueries) reuse
64 # results, but capped at CACHE_MAX entries (never reached in a normal CLI run).
65 # Tests clear it via reddit_arctic._cache.clear().
66 _cache: Dict[str, Dict[str, int]] = {}
67
68
69 # Run memo for listing and comment searches. The Reddit lane runs once per
70 # subquery with the same subreddits and window, so a four-subquery run sent
71 # each search four times at once, and the archive answers all but one of a
72 # set of identical concurrent requests with HTTP 422 "Timeout. Maybe slow
73 # down a bit" (measured 2026-11-10: 4 identical requests -> 3 x 422). One
74 # request per URL per command: later callers wait for the first and reuse it.
75 # The archive also sheds load with the same 422 on requests that are neither
76 # duplicated nor fast (measured: 2 to 4 of 10 sequential searches, at 0.4s and
77 # at 1.5s spacing alike, with or without a ``fields`` selection), and a retry
78 # right after one tends to be refused again. A comment lookup retries once
79 # after a pause; a listing walk asks again for its refused slices at the end.
80 @dataclass
81 class _ScoreSlot:
82 """In-flight score batch shared between the owner and waiting callers."""
83
84 done: threading.Event = field(default_factory=threading.Event)
85 scores: Dict[str, Dict[str, int]] = field(default_factory=dict)
86 attempted: bool = False
87
88
89 MEMO_MAX = 512
90 RETRY_422_PAUSE = 1.5
91 _memo: Dict[str, Any] = {}
92 _inflight: Dict[str, threading.Event] = {}
93 _score_inflight: Dict[str, _ScoreSlot] = {}
94 _memo_lock = threading.Lock()
95 _tree_state = threading.local()
96
97
98 def _log(msg: str) -> None:
99 sys.stderr.write(f"[ArcticShift] {msg}\n")
100 sys.stderr.flush()
101
102
103 def _set_thread_tree_throttled(value: bool) -> None:
104 _tree_state.throttled = bool(value)
105
106
107 def last_tree_was_throttled() -> bool:
108 """Whether this thread's last ``fetch_comment_tree`` call was throttled (422/429)."""
109 return bool(getattr(_tree_state, "throttled", False))
110
111
112 def __getattr__(name: str) -> Any:
113 if name == "last_tree_throttled":
114 return last_tree_was_throttled()
115 raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
116
117
118 def reset_memo() -> None:
119 """Forget memoized archive responses. Called once per command, and by tests."""
120 with _memo_lock:
121 _memo.clear()
122 _inflight.clear()
123 _cache.clear()
124 _score_inflight.clear()
125 _set_thread_tree_throttled(False)
126
127
128 def _is_slow_down(error: BaseException) -> bool:
129 return getattr(error, "status_code", None) == 422
130
131
132 def _fetch_search(url: str, deadline: float, retry_422: bool = True) -> Any:
133 """One archive search, retried once after a pause when it answers 422.
134
135 With ``retry_422`` off a 422 is raised at once and kept out of the
136 pipeline's failure sink: the caller means to ask again later, and reports
137 it with ``_report_failures`` if it never does.
138 """
139 for attempt in range(2):
140 now = time.monotonic()
141 remaining = deadline - now
142 if remaining <= 0:
143 raise http.DeadlineExceeded()
144 # A 422 that the retry recovers is not a lost request, so it is kept
145 # out of the pipeline's failure sink unless the retry fails too.
146 with http.capture_failures() as failures:
147 try:
148 # DNS recovery may retry even with retries=1. Bound the whole
149 # request so those retries cannot consume other callers' time.
150 return http.get(
151 url,
152 headers={"User-Agent": http.BROWSER_USER_AGENT},
153 timeout=min(TIMEOUT, remaining),
154 retries=1,
155 deadline_monotonic=min(deadline, now + TIMEOUT),
156 )
157 except Exception as exc:
158 error = exc
159 if _is_slow_down(error) and not retry_422:
160 error.unreported_failures = list(failures) # type: ignore[attr-defined]
161 raise error
162 retryable = (
163 attempt == 0
164 and _is_slow_down(error)
165 and deadline - time.monotonic() > RETRY_422_PAUSE + 1
166 )
167 if not retryable:
168 if failures:
169 for failure in failures:
170 http._record_failure(failure)
171 else:
172 http._record_failure(
173 error if isinstance(error, http.HTTPError) else http.HTTPError(str(error))
174 )
175 raise error
176 time.sleep(RETRY_422_PAUSE)
177 raise http.DeadlineExceeded() # pragma: no cover - the loop always returns or raises
178
179
180 def _report_failures(error: BaseException) -> None:
181 """Record a deferred 422 that was never asked for again."""
182 for failure in getattr(error, "unreported_failures", ()):
183 http._record_failure(failure)
184
185
186 def _is_finite_int(value: int) -> bool:
187 try:
188 return math.isfinite(float(value))
189 except OverflowError:
190 return False
191
192
193 def _coerce_int(value: Any, default: int = 0) -> int:
194 if value is None or isinstance(value, bool):
195 return default
196 if isinstance(value, int):
197 return value if _is_finite_int(value) else default
198 if isinstance(value, float):
199 return int(value) if math.isfinite(value) else default
200 if isinstance(value, str):
201 text = value.strip()
202 if not text:
203 return default
204 try:
205 parsed = int(text)
206 except ValueError:
207 return default
208 return parsed if _is_finite_int(parsed) else default
209 return default
210
211
212 def _strict_int(value: Any) -> int:
213 if value is None:
214 return 0
215 if isinstance(value, bool):
216 raise TypeError("bool is not a valid integer")
217 if isinstance(value, int):
218 if not _is_finite_int(value):
219 raise OverflowError("integer exceeds float range")
220 return value
221 if isinstance(value, float):
222 if not math.isfinite(value):
223 raise ValueError("non-finite float")
224 return int(value)
225 if isinstance(value, str):
226 text = value.strip()
227 if not text:
228 return 0
229 parsed = int(text)
230 if not _is_finite_int(parsed):
231 raise OverflowError("integer exceeds float range")
232 return parsed
233 raise TypeError(f"unsupported numeric type: {type(value).__name__}")
234
235
236 def _coerce_timestamp(value: Any) -> Optional[float | int]:
237 if value is None or isinstance(value, bool):
238 return None
239 if isinstance(value, (int, float)):
240 try:
241 num = float(value)
242 except (TypeError, ValueError, OverflowError):
243 return None
244 if not math.isfinite(num):
245 return None
246 ts: float | int = value
247 elif isinstance(value, str):
248 text = value.strip()
249 if not text:
250 return None
251 try:
252 ts = float(text)
253 except (ValueError, OverflowError):
254 return None
255 if not math.isfinite(ts):
256 return None
257 else:
258 return None
259 try:
260 datetime.fromtimestamp(ts, tz=timezone.utc)
261 except (ValueError, TypeError, OSError, OverflowError):
262 return None
263 return ts
264
265
266 def _coerce_text(value: Any) -> str:
267 if value is None or isinstance(value, bool):
268 return ""
269 return value if isinstance(value, str) else str(value)
270
271
272 def _coerce_author(value: Any) -> str:
273 text = _coerce_text(value)
274 return text or "[deleted]"
275
276
277 def _search_once(url: str, deadline: float, retry_422: bool = True) -> Any:
278 """Archive search shared across the run: memoized, one fetch in flight per URL.
279
280 Returns the decoded response, or raises what the fetch raised. Only a
281 response that carries a ``data`` list is memoized, so a rate-limit body is
282 asked for again by the next caller.
283 """
284 for _round in range(3):
285 with _memo_lock:
286 if url in _memo:
287 return _memo[url]
288 gate = _inflight.get(url)
289 owner = gate is None
290 if owner:
291 gate = threading.Event()
292 _inflight[url] = gate
293 if owner:
294 break
295 gate.wait(timeout=max(0.0, deadline - time.monotonic()))
296 if time.monotonic() >= deadline:
297 raise http.DeadlineExceeded()
298 else:
299 raise http.HTTPError(f"Shared archive request kept failing: {url}")
300 try:
301 data = _fetch_search(url, deadline, retry_422)
302 rows = data.get("data") if isinstance(data, dict) else None
303 if isinstance(rows, list):
304 with _memo_lock:
305 if len(_memo) < MEMO_MAX:
306 _memo[url] = data
307 return data
308 finally:
309 with _memo_lock:
310 _inflight.pop(url, None)
311 gate.set()
312
313
314 def fetch_scores(
315 post_ids: List[str], deadline: Optional[float] = None,
316 ) -> Dict[str, Dict[str, int]]:
317 """Return ``{base36_post_id: {"score", "num_comments"}}`` for the given ids.
318
319 ``deadline`` is a ``time.monotonic()`` bound: no batch starts after it and
320 a running one is cut off at it, and the scores already found are returned.
321
322 Batched, paced, in-run cached, and never raises. Ids that fail or are absent
323 from the archive are simply missing from the result (caller degrades to no
324 point count for those threads).
325 """
326 out: Dict[str, Dict[str, int]] = {}
327 clean_ids = list(dict.fromkeys(
328 clean for pid in post_ids if (clean := reddit_refs.normalize_post_id(pid))
329 ))
330 if not clean_ids:
331 return out
332
333 pending: List[str] = list(clean_ids)
334 batches_fetched = 0
335 stop_fetching = False
336 wait_retries = 0
337 wait_end = (
338 deadline
339 if deadline is not None
340 else time.monotonic() + TIMEOUT * MAX_BATCHES + PACE_SECONDS * MAX_BATCHES
341 )
342
343 for _round in range(MAX_BATCHES + 3):
344 if batches_fetched > 0 and not stop_fetching:
345 if deadline is not None:
346 pace = min(PACE_SECONDS, max(0.0, deadline - time.monotonic()))
347 if pace > 0:
348 time.sleep(pace)
349 else:
350 time.sleep(PACE_SECONDS)
351
352 todo: List[str] = []
353 waiting: List[tuple[str, _ScoreSlot]] = []
354 batch: List[str] = []
355 slot: Optional[_ScoreSlot] = None
356
357 with _memo_lock:
358 for clean in pending:
359 if clean in out:
360 continue
361 if clean in _cache:
362 out[clean] = dict(_cache[clean])
363 elif clean in _score_inflight:
364 waiting.append((clean, _score_inflight[clean]))
365 else:
366 todo.append(clean)
367 if todo and not stop_fetching and batches_fetched < MAX_BATCHES:
368 if deadline is not None and time.monotonic() >= deadline:
369 _log(f"lookup stopped at its deadline; {len(todo)} ids left unscored")
370 stop_fetching = True
371 else:
372 # Claim one batch at a time so an owner that expires after
373 # batch 1 never blocks waiting callers from fetching batch 2.
374 batch = todo[:BATCH]
375 slot = _ScoreSlot()
376 for pid in batch:
377 _score_inflight[pid] = slot
378
379 remaining_todo = todo[len(batch):]
380
381 if slot is not None:
382 try:
383 bound: Dict[str, Any] = {"timeout": TIMEOUT}
384 if deadline is not None:
385 remaining = deadline - time.monotonic()
386 if remaining <= 0:
387 _log(f"lookup stopped at its deadline; {len(batch)} ids left unscored")
388 stop_fetching = True
389 else:
390 bound = {
391 "timeout": min(TIMEOUT, remaining),
392 "retries": 1,
393 "deadline_monotonic": deadline,
394 }
395 if not stop_fetching:
396 batches_fetched += 1
397 try:
398 query = urlencode({"ids": ",".join(batch)}, safe=",")
399 data = http.get(
400 f"{API}?{query}",
401 headers={"User-Agent": http.BROWSER_USER_AGENT},
402 **bound,
403 )
404 except Exception as e: # network error / non-200 — degrade, never raise
405 _log(f"lookup failed ({e}); {len(batch)} ids left unscored")
406 stop_fetching = True
407 else:
408 rows = data.get("data") if isinstance(data, dict) else None
409 if not isinstance(rows, list):
410 # arctic-shift returns {"error": "..."} on rate-limit / bad request.
411 _log(f"unexpected response (rate-limited?): {str(data)[:80]}")
412 stop_fetching = True
413 else:
414 entries: Dict[str, Dict[str, int]] = {}
415 for row in rows:
416 if not isinstance(row, dict):
417 continue
418 rid = _coerce_text(row.get("id")).removeprefix("t3_")
419 if not rid:
420 continue
421 try:
422 entries[rid] = {
423 "score": _strict_int(row.get("score")),
424 "num_comments": _strict_int(row.get("num_comments")),
425 }
426 except (TypeError, ValueError, OverflowError):
427 continue
428 with _memo_lock:
429 for rid, entry in entries.items():
430 if rid in _cache or len(_cache) < CACHE_MAX:
431 _cache[rid] = dict(entry)
432 slot.scores[rid] = dict(entry)
433 out[rid] = dict(entry)
434 slot.attempted = True
435 for pid in batch:
436 if _score_inflight.get(pid) is slot:
437 _score_inflight.pop(pid, None)
438 finally:
439 with _memo_lock:
440 for pid in batch:
441 if _score_inflight.get(pid) is slot:
442 _score_inflight.pop(pid, None)
443 slot.done.set()
444
445 if remaining_todo and not stop_fetching and batches_fetched < MAX_BATCHES:
446 pending = remaining_todo + [pid for pid, _ in waiting]
447 continue
448
449 if not waiting:
450 break
451
452 unique_slots: List[_ScoreSlot] = []
453 seen_slot_ids: set[int] = set()
454 for _pid, wslot in waiting:
455 sid = id(wslot)
456 if sid not in seen_slot_ids:
457 seen_slot_ids.add(sid)
458 unique_slots.append(wslot)
459 timed_out = False
460 for wslot in unique_slots:
461 remaining = wait_end - time.monotonic()
462 if remaining <= 0:
463 timed_out = True
464 break
465 if not wslot.done.wait(timeout=remaining):
466 timed_out = True
467 break
468
469 retry_ids: List[str] = []
470 with _memo_lock:
471 for pid, wslot in waiting:
472 if pid in wslot.scores:
473 out[pid] = dict(wslot.scores[pid])
474 elif pid in _cache:
475 out[pid] = dict(_cache[pid])
476 elif wslot.done.is_set() and not wslot.attempted:
477 retry_ids.append(pid)
478
479 if (
480 timed_out
481 or not retry_ids
482 or stop_fetching
483 or batches_fetched >= MAX_BATCHES
484 or wait_retries >= 1
485 or (deadline is not None and time.monotonic() >= deadline)
486 ):
487 break
488 wait_retries += 1
489 pending = retry_ids
490
491 return out
492
493
494 def _parse_iso_date(value: Optional[str]) -> Optional[date]:
495 if not isinstance(value, str):
496 return None
497 text = value.strip()
498 if not _ISO_DATE.match(text):
499 return None
500 try:
501 return date.fromisoformat(text)
502 except ValueError:
503 return None
504
505
506 def _epoch_to_date(value: Any) -> Optional[str]:
507 """Epoch seconds -> YYYY-MM-DD (UTC), or None on garbage."""
508 ts = _coerce_timestamp(value)
509 if ts is None:
510 return None
511 try:
512 return datetime.fromtimestamp(int(ts), tz=timezone.utc).date().isoformat()
513 except (TypeError, ValueError, OSError, OverflowError):
514 return None
515
516
517 def _normalize_listing_row(row: Dict[str, Any], query: str = "") -> Dict[str, Any]:
518 """Normalize an arctic-shift post row to reddit_listing.parse_cards shape.
519
520 Mirrors the shreddit card schema (title/url/score/num_comments/subreddit/
521 created_utc/author/selftext/date/engagement/relevance/metadata.post_id) so
522 reddit_keyless can consume either backend interchangeably.
523 """
524 from .relevance import token_overlap_relevance
525
526 pid = _coerce_text(row.get("id")).removeprefix("t3_")
527 raw_permalink = row.get("permalink")
528 permalink = raw_permalink if isinstance(raw_permalink, str) else ""
529 title = _coerce_text(row.get("title"))
530 score = _coerce_int(row.get("score"), default=0)
531 num_comments = _coerce_int(row.get("num_comments"), default=0)
532 author = _coerce_author(row.get("author"))
533 if author in ("[deleted]", "[removed]"):
534 author = "[deleted]"
535 raw_sub = row.get("subreddit")
536 subreddit = raw_sub if isinstance(raw_sub, str) else ""
537 created_utc = _coerce_timestamp(row.get("created_utc"))
538 url = f"https://www.reddit.com{permalink}" if permalink.startswith("/") else permalink
539 return {
540 "id": "",
541 "title": title,
542 "url": url,
543 "score": score,
544 "num_comments": num_comments,
545 "subreddit": subreddit,
546 "created_utc": created_utc,
547 "author": author,
548 "selftext": _coerce_text(row.get("selftext")),
549 "date": _epoch_to_date(created_utc),
550 "engagement": {"score": score, "num_comments": num_comments, "upvote_ratio": None},
551 "relevance": round(token_overlap_relevance(query, title), 3) if query else 0.0,
552 "why_relevant": "Reddit listing (arctic-shift)",
553 "metadata": {"post_id": pid},
554 }
555
556
557 def fetch_listings(
558 subreddits: List[str],
559 depth: str = "default",
560 query: str = "",
561 sorts: Optional[List[str]] = None,
562 timeframe: str = "month",
563 limit: Optional[int] = None,
564 from_date: Optional[str] = None,
565 to_date: Optional[str] = None,
566 lane_deadline: Optional[float] = None,
567 ) -> List[Dict[str, Any]]:
568 """Scored subreddit listings from the arctic-shift archive, keyless.
569
570 Drop-in fallback/supplement for ``reddit_listing.fetch_listings`` (shreddit
571 partials), which datacenter IPs get HTTP 403 on. Arctic-shift serves recent
572 posts with real score/num_comments from any IP.
573
574 Arctic-shift has no top/hot/new lanes (only asc/desc). Without a date
575 window the fetch is recency-only, and the archive freezes score at ingest,
576 so the freshest ~2-3 days read as 1-point stubs. When the caller supplies
577 ``from_date``/``to_date``, the window is sliced into ~7-day chunks queried
578 with ``after``/``before`` and the highest-scored sampled posts are kept per
579 subreddit. Slice requests rotate across subreddits under a shared deadline;
580 successful partial results survive failures. The 100-row cap per slice
581 means the sample can miss popular posts in busy subreddits. Best-effort,
582 never raises: returns ``[]`` when no requests succeed. ``lane_deadline``
583 is the Reddit lane's own ``time.monotonic()`` bound; the walk stops at
584 whichever deadline comes first.
585 """
586 if not subreddits:
587 return []
588 base = limit or _LISTING_DEPTH_LIMITS.get(depth, _LISTING_DEPTH_LIMITS["default"])
589 # When multiple sorts were requested, fetch more posts to compensate for
590 # arctic-shift's lack of sort lanes.
591 n = base * _LISTING_SUPPLEMENT_MULTIPLIER if sorts and len(sorts) > 1 else base
592 # Window + engagement sort: the archive freezes score at ingest time, so
593 # posts from the last ~2-3 days read as 1-point stubs and `before` ending
594 # today can return null data. Scope the query with after/before, slice the
595 # window into ~7-day chunks (API caps 100 rows/request, newest-first, so
596 # one request only covers the last day of a month window), and keep the
597 # highest-scored n per subreddit (sort has no top lane — only asc/desc).
598 start = _parse_iso_date(from_date)
599 parsed_to = _parse_iso_date(to_date)
600 clean_from = start.isoformat() if start else None
601 clean_to = parsed_to.isoformat() if parsed_to else None
602 window = bool(clean_from or clean_to)
603 slices: Optional[List[tuple]] = None
604 if window:
605 from datetime import timedelta as _timedelta
606 end = parsed_to if parsed_to is not None else date.today()
607 win_start = start if start is not None else end - _timedelta(days=30)
608 if win_start < end:
609 span = (end - win_start).days
610 n_slices = min(4, max(1, span // 7))
611 step = max(1, -(-span // n_slices))
612 slices = []
613 cursor = win_start
614 while cursor < end:
615 slices.append((cursor, min(cursor + _timedelta(days=step), end)))
616 cursor += _timedelta(days=step)
617 req_limit = 100 if window else n
618 posts_by_sub: Dict[str, List[Dict[str, Any]]] = {}
619 for raw_sub in subreddits:
620 sub = reddit_refs.normalize_subreddit(raw_sub, allow_all=False)
621 if sub:
622 posts_by_sub.setdefault(sub, [])
623 if not posts_by_sub:
624 return []
625 seen_by_sub = {sub: set() for sub in posts_by_sub}
626 # Give every subreddit a slice before spending the shared budget on more
627 # slices for any one subreddit.
628 # Newest slice first: when the shared deadline cuts the walk short, the
629 # week that is dropped is the oldest one, not the one the run is about.
630 requests = (
631 (sub, span_pair)
632 for span_pair in (list(reversed(slices)) if slices else [None])
633 for sub in posts_by_sub
634 )
635 deadline = time.monotonic() + _LISTING_DEADLINE_SECONDS
636 if lane_deadline is not None:
637 deadline = min(deadline, lane_deadline)
638
639 def url_for(sub: str, span_pair: Optional[tuple]) -> str:
640 params: List[tuple[str, Any]] = [
641 ("subreddit", sub),
642 ("limit", req_limit),
643 ("sort", "desc"),
644 ]
645 if span_pair:
646 params.append(("after", span_pair[0].isoformat()))
647 params.append(("before", span_pair[1].isoformat()))
648 else:
649 if clean_from:
650 params.append(("after", clean_from))
651 if clean_to:
652 params.append(("before", clean_to))
653 return f"{SEARCH_API}?{urlencode(params)}"
654
655 def keep(sub: str, data: Any) -> None:
656 rows = data.get("data") if isinstance(data, dict) else None
657 if not isinstance(rows, list):
658 _log(f"unexpected listing response for r/{sub}: {str(data)[:80]}")
659 return
660 for row in rows:
661 if not isinstance(row, dict):
662 continue
663 post = _normalize_listing_row(row, query)
664 if post["url"] and post["url"] not in seen_by_sub[sub]:
665 seen_by_sub[sub].add(post["url"])
666 posts_by_sub[sub].append(post)
667
668 # Two passes under the one deadline. The first asks for every (subreddit,
669 # slice) once and sets aside what the archive refuses with 422; the second
670 # asks for those again, so a refusal neither stalls the walk nor loses the
671 # slice while budget remains.
672 first_pass = [(sub, url_for(sub, span_pair), None) for sub, span_pair in requests]
673 refused: List[tuple] = []
674 paced = False
675 fetched_count = 0
676 out_of_time = False
677 for retrying, batch in ((False, first_pass), (True, refused)):
678 for sub, url, earlier_error in batch:
679 if out_of_time:
680 if earlier_error is not None:
681 _report_failures(earlier_error)
682 _log(f"listing search failed r/{sub}: {earlier_error}")
683 continue
684 with _memo_lock:
685 memoized = url in _memo
686 # Pace requests that reach the archive; a memoized answer costs nothing.
687 if paced and not memoized:
688 time.sleep(min(PACE_SECONDS, max(0, deadline - time.monotonic())))
689 if deadline - time.monotonic() <= 0:
690 _log(f"listing deadline reached after {fetched_count} requests; keeping partial results")
691 out_of_time = True
692 if earlier_error is not None:
693 _report_failures(earlier_error)
694 _log(f"listing search failed r/{sub}: {earlier_error}")
695 else:
696 http._record_failure(http.DeadlineExceeded())
697 continue
698 paced = paced or not memoized
699 fetched_count += 1
700 try:
701 data = _search_once(url, deadline, retry_422=False)
702 except Exception as e: # network error / non-200 — degrade, never raise
703 if not retrying and _is_slow_down(e):
704 refused.append((sub, url, e))
705 continue
706 if isinstance(e, http.DeadlineExceeded):
707 http._record_failure(e)
708 else:
709 _report_failures(e)
710 _log(f"listing search failed r/{sub}: {e}")
711 continue
712 keep(sub, data)
713
714 out: List[Dict[str, Any]] = []
715 for sub_posts in posts_by_sub.values():
716 if window:
717 sub_posts.sort(key=lambda p: -(p["score"] or 0))
718 sub_posts = sub_posts[:n]
719 out.extend(sub_posts)
720
721 seen: set = set()
722 unique: List[Dict[str, Any]] = []
723 for p in out:
724 if p["url"] not in seen:
725 seen.add(p["url"])
726 unique.append(p)
727 return unique
728
729
730 def _acquire_keyless_limiter(deadline: float) -> None:
731 limiter = http.REDDIT_KEYLESS_LIMITER
732 if isinstance(limiter, http.RateLimiter):
733 limiter.acquire(deadline_monotonic=deadline)
734 return
735 try:
736 params = inspect.signature(limiter.acquire).parameters
737 except (TypeError, ValueError):
738 params = {}
739 if "deadline_monotonic" in params or any(
740 p.kind == inspect.Parameter.VAR_KEYWORD for p in params.values()
741 ):
742 limiter.acquire(deadline_monotonic=deadline)
743 else:
744 limiter.acquire()
745
746
747 def _archive_get(url: str, deadline: float) -> Any:
748 """One serial archive request through the shared keyless Reddit limiter,
749 retried once after a pause when the archive answers 422."""
750 _acquire_keyless_limiter(deadline)
751 return _fetch_search(url, deadline, retry_422=True)
752
753
754 def fetch_posts_by_ids(
755 post_ids: List[str], deadline: Optional[float] = None,
756 ) -> tuple:
757 """Hydrate posts by base36 id: ``({id: listing-shaped post}, state)``.
758
759 Batches of ``IDS_BATCH`` ids, one request at a time through the shared
760 keyless limiter. Each post is normalized with ``_normalize_listing_row``
761 and keeps the archive's raw ``created_utc``. ``state`` is ``"ok"``,
762 ``"throttled"`` when the archive refused a batch with 422 twice (no later
763 batch is sent), or ``"down"`` when a batch failed any other way (later
764 batches are still tried). Never raises.
765 """
766 todo = list(dict.fromkeys(
767 clean for p in post_ids if (clean := reddit_refs.normalize_post_id(p))
768 ))
769 end = deadline if deadline is not None else time.monotonic() + _LISTING_DEADLINE_SECONDS
770 out: Dict[str, Dict[str, Any]] = {}
771 state = "ok"
772 for start in range(0, len(todo), IDS_BATCH):
773 batch = todo[start:start + IDS_BATCH]
774 if end - time.monotonic() <= 0:
775 _log(f"post lookup stopped at its deadline; {len(todo) - start} ids left")
776 # Unasked ids are not an archive answer: never report them as ok.
777 if state == "ok":
778 state = "down"
779 break
780 try:
781 _acquire_keyless_limiter(end)
782 except http.DeadlineExceeded:
783 _log(f"post lookup stopped at its deadline; {len(todo) - start} ids left")
784 if state == "ok":
785 state = "down"
786 break
787 try:
788 query = urlencode({"ids": ",".join(batch)}, safe=",")
789 data = _fetch_search(f"{API}?{query}", end, retry_422=True)
790 except http.DeadlineExceeded as exc:
791 if time.monotonic() >= end:
792 _log(f"post lookup stopped at its deadline; {len(todo) - start} ids left")
793 if state == "ok":
794 state = "down"
795 break
796 _log(f"post lookup batch timed out ({exc}); {len(batch)} ids left")
797 state = "down"
798 continue
799 except Exception as exc: # network error / non-200 — degrade, never raise
800 if _is_slow_down(exc):
801 _log(f"post lookup throttled (422 twice); {len(todo) - start} ids left")
802 return out, "throttled"
803 _log(f"post lookup failed ({exc}); {len(batch)} ids left")
804 state = "down"
805 continue
806 rows = data.get("data") if isinstance(data, dict) else None
807 if not isinstance(rows, list):
808 _log(f"unexpected post lookup response: {str(data)[:80]}")
809 err = data.get("error") if isinstance(data, dict) else None
810 if "slow down" in str(err or "").lower():
811 return out, "throttled"
812 state = "down"
813 continue
814 for row in rows:
815 if not isinstance(row, dict):
816 continue
817 post = _normalize_listing_row(row)
818 pid = post["metadata"]["post_id"]
819 if pid and post["url"]:
820 post["why_relevant"] = "Reddit thread (arctic-shift)"
821 out[pid] = post
822 return out, state
823
824
825 def _tree_rows(nodes: Any) -> List[Dict[str, Any]]:
826 """Every comment in an archive comment tree, parents before their replies."""
827 rows: List[Dict[str, Any]] = []
828 stack = list(reversed(nodes)) if isinstance(nodes, list) else []
829 while stack:
830 node = stack.pop()
831 if not isinstance(node, dict) or node.get("kind") != "t1":
832 continue
833 data = node.get("data")
834 if not isinstance(data, dict):
835 continue
836 rows.append(data)
837 replies = data.get("replies")
838 replies_data = replies.get("data") if isinstance(replies, dict) else None
839 children = replies_data.get("children") if isinstance(replies_data, dict) else None
840 if isinstance(children, list):
841 stack.extend(reversed(children))
842 return rows
843
844
845 def _row_depth(row: Dict[str, Any]) -> int:
846 """A tree row's depth; without one, a reply to the post itself is top-level."""
847 raw_depth = row.get("depth")
848 if raw_depth is not None and not isinstance(raw_depth, bool):
849 if not (isinstance(raw_depth, str) and not raw_depth.strip()):
850 try:
851 return _strict_int(raw_depth)
852 except (TypeError, ValueError, OverflowError):
853 pass
854 parent_id = _coerce_text(row.get("parent_id")).strip()
855 return 0 if (not parent_id or parent_id.startswith("t3_")) else 1
856
857
858 def _fetch_comment_tree_with_status(
859 post_id: str, deadline: Optional[float] = None,
860 ) -> tuple[Optional[List[Dict[str, Any]]], bool]:
861 """Fetch comments of a post from ``/comments/tree``, returning ``(rows, throttled)``.
862
863 Also updates the calling thread's ``last_tree_throttled`` state so concurrent
864 streams never overwrite each other's throttle classification.
865 """
866 _set_thread_tree_throttled(False)
867 pid = reddit_refs.normalize_post_id(post_id)
868 if not pid:
869 return None, False
870 end = deadline if deadline is not None else time.monotonic() + TIMEOUT
871 if end - time.monotonic() < 1:
872 return None, False
873 try:
874 query = urlencode({"link_id": f"t3_{pid}", "limit": MAX_COMMENT_ROWS})
875 data = _archive_get(f"{COMMENTS_TREE_API}?{query}", end)
876 except Exception as exc: # network error / non-200 — degrade, never raise
877 throttled = _is_slow_down(exc) or getattr(exc, "status_code", None) == 429
878 _set_thread_tree_throttled(throttled)
879 _log(f"comment tree failed t3_{pid}: {exc}")
880 return None, throttled
881 nodes = data.get("data") if isinstance(data, dict) else None
882 if not isinstance(nodes, list):
883 _log(f"unexpected comment tree response for t3_{pid}: {str(data)[:80]}")
884 return None, False
885
886 from .snippet import cut_quote
887
888 comments: List[Dict[str, Any]] = []
889 for row in _tree_rows(nodes):
890 author = _coerce_author(row.get("author"))
891 body = _coerce_text(row.get("body"))
892 if author in ("[deleted]", "[removed]") or body in ("[deleted]", "[removed]"):
893 continue
894 score = _coerce_int(row.get("score"), default=0)
895 depth = _row_depth(row)
896 raw_permalink = row.get("permalink")
897 permalink = raw_permalink if isinstance(raw_permalink, str) else ""
898 created_utc = _coerce_timestamp(row.get("created_utc"))
899 entry: Dict[str, Any] = {
900 "id": _coerce_text(row.get("id")).removeprefix("t1_"),
901 "score": score,
902 "author": author,
903 "body": body[:300],
904 "excerpt": cut_quote(body),
905 "permalink": permalink,
906 "date": _epoch_to_date(created_utc),
907 "created_utc": created_utc,
908 "url": f"https://reddit.com{permalink}" if permalink else "",
909 "depth": depth,
910 }
911 if isinstance(row.get("is_submitter"), bool):
912 entry["is_uploader"] = row["is_submitter"]
913 comments.append(entry)
914 return comments, False
915
916
917 def fetch_comment_tree(
918 post_id: str, deadline: Optional[float] = None,
919 ) -> Optional[List[Dict[str, Any]]]:
920 """Comments of a post from the archive's ``/comments/tree``, flattened.
921
922 Each comment carries id, score, author, body, excerpt, permalink, url,
923 date, ``created_utc`` and ``depth`` (0 for a top-level comment), plus
924 ``is_uploader`` when the archive supplies ``is_submitter``. Deleted
925 and removed comments are left out. Returns ``None`` when the request
926 failed, so a caller can tell a failure from a thread with no comments.
927 """
928 comments, _throttled = _fetch_comment_tree_with_status(post_id, deadline=deadline)
929 return comments
930
931
932 _ORIG_FETCH_COMMENT_TREE = fetch_comment_tree
933
934
935 def fetch_post_comments(
936 post_id: str,
937 limit: int = 10,
938 skip_author: Optional[Callable[[str], bool]] = None,
939 deadline: Optional[float] = None,
940 ) -> List[Dict[str, Any]]:
941 """Top comments for a post from the arctic-shift archive, keyless.
942
943 Drop-in fallback for ``reddit_shreddit.parse_comments`` output on hosts
944 where the shreddit comment partials 403 (datacenter egress). Rows carry
945 the same dict shape (score/author/body/excerpt/permalink/date/url), are
946 ranked by score desc, and capped at ``limit``. ``skip_author`` drops rows
947 before ranking (the caller's bot filter). ``deadline`` is an absolute
948 ``time.monotonic()`` bound shared with the caller's budget. Best-effort, never raises:
949 returns ``[]`` on any failure so the caller keeps whatever it had.
950 """
951 pid = reddit_refs.normalize_post_id(post_id)
952 if not pid:
953 return []
954 now = time.monotonic()
955 end = now + TIMEOUT if deadline is None else min(deadline, now + TIMEOUT)
956 if end - now < 1:
957 _log(f"comments lookup skipped t3_{pid}: enrichment budget spent")
958 return []
959 try:
960 query = urlencode({"link_id": f"t3_{pid}", "limit": FALLBACK_COMMENT_ROWS})
961 data = _search_once(f"{COMMENTS_TREE_API}?{query}", end)
962 except Exception as e: # network error / non-200 — degrade, never raise
963 _log(f"comments lookup failed t3_{pid}: {e}")
964 return []
965 rows = data.get("data") if isinstance(data, dict) else None
966 if not isinstance(rows, list):
967 _log(f"unexpected comments response for t3_{pid}: {str(data)[:80]}")
968 return []
969
970 from .snippet import cut_quote
971
972 comments: List[Dict[str, Any]] = []
973 for row in _tree_rows(rows):
974 author = _coerce_author(row.get("author"))
975 body = _coerce_text(row.get("body"))
976 if author in ("[deleted]", "[removed]") or body in ("[deleted]", "[removed]"):
977 continue
978 if skip_author and skip_author(author):
979 continue
980 score = _coerce_int(row.get("score"), default=0)
981 raw_permalink = row.get("permalink")
982 permalink = raw_permalink if isinstance(raw_permalink, str) else ""
983 entry: Dict[str, Any] = {
984 "score": score,
985 "author": author,
986 "body": body[:300],
987 "excerpt": cut_quote(body),
988 "permalink": permalink,
989 "date": _epoch_to_date(row.get("created_utc")),
990 "url": f"https://reddit.com{permalink}" if permalink else "",
991 "depth": _row_depth(row),
992 }
993 if isinstance(row.get("is_submitter"), bool):
994 entry["is_uploader"] = row["is_submitter"]
995 comments.append(entry)
996 comments.sort(key=lambda c: _coerce_int(c.get("score"), default=0), reverse=True)
997 return comments[:limit]
998
998 lines PYTHON