| 1 | #!/usr/bin/env python3 |
| 2 | """Live canary for the keyless Reddit floor and the Arctic Shift hydrator. |
| 3 | |
| 4 | Dev and CI tool, not part of the skill runtime. The scheduled workflow |
| 5 | ``.github/workflows/reddit-canary.yml`` runs it daily; it never gates a pull |
| 6 | request. It runs with no logged-in session, no ScrapeCreators key and no |
| 7 | config file, so it measures exactly the path every free user gets. |
| 8 | |
| 9 | Each run: |
| 10 | |
| 11 | 1. Asks every keyless web rung (Brave, DuckDuckGo, Startpage) the floor's own |
| 12 | month-filtered ``site:reddit.com <topic>`` query for each of |
| 13 | :data:`TOPICS`, one rung at a time (no fall-through), and parses the page |
| 14 | with the engine's own parser. |
| 15 | 2. Hydrates each topic's discovered threads through the engine's hydration |
| 16 | chain (Arctic Shift, no session, no ScrapeCreators). |
| 17 | 3. Looks up :data:`KNOWN_THREAD_IDS` on Arctic Shift ``/posts/ids``, so the |
| 18 | hydrator is checked even on a day every web rung is challenged. |
| 19 | |
| 20 | Every check is classified as one of: |
| 21 | |
| 22 | - ``ok``: it returned parseable results. |
| 23 | - ``challenged``: a 202 or 429 answer, an archive "slow down" (422), or a |
| 24 | known challenge/captcha page. GitHub runners are datacenter IPs and get |
| 25 | challenged more often than users do. |
| 26 | - ``parser-broke``: a 200 answer the engine's parser finds no results in, |
| 27 | and that is not the rung's own "no results" page. |
| 28 | - ``down``: no answer, a 403, a 5xx, another error status, or a page the |
| 29 | parser read that holds no Reddit thread (the rung serves the floor nothing). |
| 30 | |
| 31 | The run fails (exit 1) when any check is ``parser-broke``, Arctic hydration is |
| 32 | ``down``, every discovery rung check is ``down``, or every rung was kept from |
| 33 | serving (challenged, or challenged and down) two days running: a streak of |
| 34 | runs with no rung ``ok``, each within :data:`CONSECUTIVE_WINDOW_HOURS` of the |
| 35 | last, that began at least :data:`STREAK_FAIL_HOURS` ago. The streak start is |
| 36 | read from and written to ``--state-file``; the workflow carries that file |
| 37 | between runs through the Actions cache. |
| 38 | |
| 39 | Run locally (direct CLI; there is no slash-command form for this dev tool):: |
| 40 | |
| 41 | python3 skills/last30days/scripts/reddit_canary.py --state-file tmp/reddit-canary/state.json |
| 42 | """ |
| 43 | |
| 44 | from __future__ import annotations |
| 45 | |
| 46 | import argparse |
| 47 | import json |
| 48 | import os |
| 49 | import sys |
| 50 | import time |
| 51 | import urllib.error |
| 52 | import urllib.request |
| 53 | from dataclasses import asdict, dataclass, field |
| 54 | from datetime import datetime, timedelta, timezone |
| 55 | from pathlib import Path |
| 56 | from typing import Any, Callable, Iterable, Optional |
| 57 | |
| 58 | sys.path.insert(0, str(Path(__file__).resolve().parent)) |
| 59 | |
| 60 | from lib import env, http, reddit_arctic, reddit_discover, reddit_health, reddit_hydrate, web_search_keyless # noqa: E402 |
| 61 | from lib.reddit_refs import ARCTIC, ARCTIC_PENDING, ThreadRef, canonical_thread # noqa: E402 |
| 62 | |
| 63 | # The canary measures the free floor only: no config file (so no saved key, |
| 64 | # Reddit consent or browser setting), no Keychain key, no session, no SC key. |
| 65 | CLEAN_ENV = { |
| 66 | "LAST30DAYS_CONFIG_DIR": "", |
| 67 | "LAST30DAYS_SKIP_KEYCHAIN": "1", |
| 68 | "REDDIT_BROWSER_CONSENT": "false", |
| 69 | "FROM_BROWSER": "off", |
| 70 | } |
| 71 | DROPPED_ENV = ("SCRAPECREATORS_API_KEY", env.REDDIT_SESSION_COOKIE_VAR) |
| 72 | |
| 73 | |
| 74 | def clean_environment() -> None: |
| 75 | """Point this process at the free floor only (see :data:`CLEAN_ENV`).""" |
| 76 | os.environ.update(CLEAN_ENV) |
| 77 | for key in DROPPED_ENV: |
| 78 | os.environ.pop(key, None) |
| 79 | # env resolved its config dir at import; no config file from here on, so |
| 80 | # the path-health cache is not read or written either. |
| 81 | env.CONFIG_DIR = None |
| 82 | env.CONFIG_FILE = None |
| 83 | |
| 84 | TOPICS = ("Claude Code", "Steam Deck") |
| 85 | # Settled threads the archive has held for a long time. A lookup that finds |
| 86 | # none of them means the archive or its answer shape changed. |
| 87 | KNOWN_THREAD_IDS = (reddit_health.PROBE_THREAD_ID, "1j1y38t", "1j1w6ar", "1j1oqnu") |
| 88 | RUNGS = web_search_keyless.RUNGS |
| 89 | RESULTS_PER_PAGE = reddit_discover.RESULTS_PER_QUERY |
| 90 | FRESHNESS = "month" |
| 91 | # A run more than this long after the previous one starts a fresh streak. |
| 92 | CONSECUTIVE_WINDOW_HOURS = 48 |
| 93 | # A no-rung-served streak this old spans two daily runs: the canary fails. |
| 94 | # Same-day reruns (workflow_dispatch) never reach it. |
| 95 | STREAK_FAIL_HOURS = 20 |
| 96 | REQUEST_TIMEOUT = 20 |
| 97 | PAUSE_SECONDS = 2.0 |
| 98 | |
| 99 | OK = "ok" |
| 100 | CHALLENGED = "challenged" |
| 101 | PARSER_BROKE = "parser-broke" |
| 102 | DOWN = "down" |
| 103 | |
| 104 | # Generic captcha wording a results page has only when it is a challenge. The |
| 105 | # engine's per-rung challenge markers are checked first. |
| 106 | _GENERIC_CHALLENGE_MARKERS = ("captcha",) |
| 107 | # A rung's own "nothing found" page: parsed fine, just no results. DuckDuckGo |
| 108 | # serves it for many month-filtered site: queries. |
| 109 | _NO_RESULTS_MARKERS = {"ddg": ("no-results__message",)} |
| 110 | |
| 111 | Fetch = Callable[[str, str], tuple[Optional[int], str]] |
| 112 | HydrateFn = Callable[..., Any] |
| 113 | |
| 114 | |
| 115 | @dataclass |
| 116 | class Check: |
| 117 | name: str |
| 118 | kind: str # "rung", "hydrate" or "arctic" |
| 119 | state: str |
| 120 | status: Optional[int] = None |
| 121 | results: int = 0 |
| 122 | note: str = "" |
| 123 | refs: list[ThreadRef] = field(default_factory=list, repr=False) |
| 124 | |
| 125 | def to_dict(self) -> dict[str, Any]: |
| 126 | out = asdict(self) |
| 127 | out.pop("refs", None) |
| 128 | return out |
| 129 | |
| 130 | |
| 131 | def http_fetch(url: str, accept: str = "text/html") -> tuple[Optional[int], str]: |
| 132 | """One GET with the engine's browser headers: ``(status, body)``. |
| 133 | |
| 134 | ``status`` is None when no HTTP answer came back. Never raises. |
| 135 | """ |
| 136 | request = urllib.request.Request(url, headers={ |
| 137 | "User-Agent": http.BROWSER_USER_AGENT, |
| 138 | "Accept": accept, |
| 139 | "Accept-Language": "en-US,en;q=0.9", |
| 140 | }) |
| 141 | try: |
| 142 | with urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT) as response: |
| 143 | return response.status, response.read().decode("utf-8", errors="replace") |
| 144 | except urllib.error.HTTPError as exc: |
| 145 | try: |
| 146 | body = exc.read().decode("utf-8", errors="replace") |
| 147 | except Exception: |
| 148 | body = "" |
| 149 | return exc.code, body |
| 150 | except Exception: |
| 151 | return None, "" |
| 152 | |
| 153 | |
| 154 | def _is_challenge(rung: str, text: str) -> bool: |
| 155 | if web_search_keyless.is_challenge_page(rung, text): |
| 156 | return True |
| 157 | lowered = (text or "").lower() |
| 158 | return any(marker in lowered for marker in _GENERIC_CHALLENGE_MARKERS) |
| 159 | |
| 160 | |
| 161 | def _recognized_empty(rung: str, text: str) -> bool: |
| 162 | return any(marker in (text or "") for marker in _NO_RESULTS_MARKERS.get(rung, ())) |
| 163 | |
| 164 | |
| 165 | def classify_page( |
| 166 | rung: str, status: Optional[int], text: str, threads: int, parsed: int = 0, |
| 167 | ) -> str: |
| 168 | """The canary state of one results page (see the module docstring). |
| 169 | |
| 170 | ``threads`` is the Reddit threads found on the page, ``parsed`` every |
| 171 | result the parser read. A page the parser read (other results, or the |
| 172 | engine's own "no results" page) but with no Reddit thread is ``down`` |
| 173 | for the floor, not a parser break. |
| 174 | """ |
| 175 | if status is None: |
| 176 | return DOWN |
| 177 | if 200 <= status < 300 and threads > 0: |
| 178 | return OK |
| 179 | if status in (202, 429): |
| 180 | return CHALLENGED |
| 181 | if 200 <= status < 300 and _is_challenge(rung, text): |
| 182 | return CHALLENGED |
| 183 | if status == 200 and (parsed > 0 or _recognized_empty(rung, text)): |
| 184 | return DOWN |
| 185 | if status == 200: |
| 186 | return PARSER_BROKE |
| 187 | return DOWN |
| 188 | |
| 189 | |
| 190 | def check_rung(rung: str, topic: str, fetch: Fetch) -> Check: |
| 191 | query = reddit_discover._queries(topic, None)[0] |
| 192 | status, text = fetch(web_search_keyless.rung_url(rung, query, FRESHNESS), "text/html") |
| 193 | items: list[dict] = [] |
| 194 | if status is not None and 200 <= status < 300: |
| 195 | try: |
| 196 | items = web_search_keyless.parse_rung(rung, text, RESULTS_PER_PAGE) |
| 197 | except Exception as exc: # a parser crash is a parser break |
| 198 | return Check(f"{rung}: {topic}", "rung", PARSER_BROKE, status, 0, f"parser raised {type(exc).__name__}") |
| 199 | refs: dict[str, ThreadRef] = {} |
| 200 | for item in items: |
| 201 | ref = canonical_thread(str(item.get("url") or "")) |
| 202 | if ref is None or ref.post_id in refs: |
| 203 | continue |
| 204 | ref.provenance.add("web") |
| 205 | ref.title = reddit_discover._clean_title(str(item.get("title") or "")) |
| 206 | ref.date = item.get("date") or None |
| 207 | refs[ref.post_id] = ref |
| 208 | state = classify_page(rung, status, text, len(refs), len(items)) |
| 209 | note = f"{len(items)} results, {len(refs)} reddit threads" |
| 210 | if status is None: |
| 211 | note = "no answer" |
| 212 | elif state == DOWN and status == 200: |
| 213 | note += " (results page parsed)" |
| 214 | return Check(f"{rung}: {topic}", "rung", state, status, len(refs), note, list(refs.values())) |
| 215 | |
| 216 | |
| 217 | def check_hydration(topic: str, refs: list[ThreadRef], hydrate: HydrateFn) -> Optional[Check]: |
| 218 | """The engine's hydration chain on the topic's discovered threads, or None |
| 219 | when discovery found none to hydrate.""" |
| 220 | if not refs: |
| 221 | return None |
| 222 | result = hydrate(refs, topic=topic, depth="quick", comments=True) |
| 223 | filled = sum( |
| 224 | 1 for item in result.items if item.get("engagement_source") in (ARCTIC, ARCTIC_PENDING) |
| 225 | ) |
| 226 | comments = sum(len(item.get("top_comments") or []) for item in result.items) |
| 227 | state = {"ok": OK, "unused": OK, "throttled": CHALLENGED}.get(result.arctic_state, DOWN) |
| 228 | failures = getattr(result, "comment_failures", 0) |
| 229 | throttles = getattr(result, "comment_throttles", 0) |
| 230 | if state == OK and failures and not getattr(result, "comment_fills", 0): |
| 231 | # Post lookups worked but every comment-tree request failed. All of |
| 232 | # them slow-downs is a challenge; any other failure means the comments |
| 233 | # endpoint is out. An empty tree is not a failure. |
| 234 | state = CHALLENGED if throttles >= failures else DOWN |
| 235 | if state == OK and filled == 0: |
| 236 | # Discovery found recent threads but Arctic Shift hydrated none of |
| 237 | # them (e.g. an ingestion stall returning empty data while old |
| 238 | # KNOWN_THREAD_IDS still resolve). Treat total recent miss as down. |
| 239 | state = DOWN |
| 240 | note = f"{filled} of {len(refs)} threads from arctic, {comments} comments" |
| 241 | if failures: |
| 242 | note += f", {failures} comment requests failed ({throttles} throttled)" |
| 243 | note += f"; {result.detail}" |
| 244 | return Check(f"hydrate: {topic}", "hydrate", state, None, filled, note) |
| 245 | |
| 246 | |
| 247 | def check_known_ids(fetch: Fetch, ids: Iterable[str] = KNOWN_THREAD_IDS) -> Check: |
| 248 | ids = list(ids) |
| 249 | status, text = fetch(f"{reddit_arctic.API}?ids={','.join(ids)}", "application/json") |
| 250 | name = "arctic: known ids" |
| 251 | if status is None: |
| 252 | return Check(name, "arctic", DOWN, None, 0, "no answer") |
| 253 | if status in (422, 429): |
| 254 | return Check(name, "arctic", CHALLENGED, status, 0, "archive asked to slow down") |
| 255 | if status != 200: |
| 256 | return Check(name, "arctic", DOWN, status, 0, f"HTTP {status}") |
| 257 | try: |
| 258 | data = json.loads(text or "") |
| 259 | except ValueError: |
| 260 | return Check(name, "arctic", PARSER_BROKE, status, 0, "not JSON") |
| 261 | rows = data.get("data") if isinstance(data, dict) else None |
| 262 | if not isinstance(rows, list): |
| 263 | if isinstance(data, dict) and "slow down" in str(data.get("error") or "").lower(): |
| 264 | return Check(name, "arctic", CHALLENGED, status, 0, "archive asked to slow down") |
| 265 | return Check(name, "arctic", PARSER_BROKE, status, 0, "no data list in the answer") |
| 266 | found = { |
| 267 | str(row.get("id")) for row in rows |
| 268 | if isinstance(row, dict) and row.get("id") in ids and row.get("title") |
| 269 | } |
| 270 | if not found: |
| 271 | return Check(name, "arctic", PARSER_BROKE, status, 0, f"0 of {len(ids)} known threads in the answer") |
| 272 | return Check(name, "arctic", OK, status, len(found), f"{len(found)} of {len(ids)} known threads") |
| 273 | |
| 274 | |
| 275 | def read_state(path: Optional[Path]) -> Optional[dict[str, Any]]: |
| 276 | if path is None or not path.exists(): |
| 277 | return None |
| 278 | try: |
| 279 | data = json.loads(path.read_text(encoding="utf-8")) |
| 280 | except (OSError, ValueError): |
| 281 | return None |
| 282 | return data if isinstance(data, dict) else None |
| 283 | |
| 284 | |
| 285 | def write_state(path: Optional[Path], state: dict[str, Any]) -> None: |
| 286 | if path is None: |
| 287 | return |
| 288 | path.parent.mkdir(parents=True, exist_ok=True) |
| 289 | tmp = path.with_suffix(path.suffix + ".tmp") |
| 290 | tmp.write_text(json.dumps(state, indent=2) + "\n", encoding="utf-8") |
| 291 | os.replace(tmp, path) |
| 292 | |
| 293 | |
| 294 | def _parse_at(value: Any) -> Optional[datetime]: |
| 295 | try: |
| 296 | at = datetime.fromisoformat(str(value)) |
| 297 | except ValueError: |
| 298 | return None |
| 299 | return at if at.tzinfo is not None else at.replace(tzinfo=timezone.utc) |
| 300 | |
| 301 | |
| 302 | def _streak_start(previous: Optional[dict[str, Any]], now: datetime) -> Optional[datetime]: |
| 303 | """When the no-rung-served streak the previous run was in began, or None |
| 304 | when the previous run served (or is missing, unreadable or too old).""" |
| 305 | if not previous or not previous.get("no_rung_served"): |
| 306 | return None |
| 307 | at = _parse_at(previous.get("at")) |
| 308 | if at is None or not timedelta(0) <= now - at <= timedelta(hours=CONSECUTIVE_WINDOW_HOURS): |
| 309 | return None |
| 310 | return _parse_at(previous.get("no_serve_since")) or at |
| 311 | |
| 312 | |
| 313 | def evaluate( |
| 314 | checks: list[Check], previous: Optional[dict[str, Any]], now: datetime, |
| 315 | ) -> tuple[list[str], Optional[datetime]]: |
| 316 | """``(failure reasons, start of the no-rung-served streak or None)``.""" |
| 317 | failures: list[str] = [] |
| 318 | for check in checks: |
| 319 | if check.state == PARSER_BROKE: |
| 320 | failures.append(f"{check.name} is parser-broke ({check.note})") |
| 321 | elif check.kind in ("arctic", "hydrate") and check.state == DOWN: |
| 322 | failures.append(f"{check.name}: Arctic hydration is down ({check.note})") |
| 323 | rungs = [check for check in checks if check.kind == "rung"] |
| 324 | no_rung_served = bool(rungs) and not any(check.state == OK for check in rungs) |
| 325 | since = (_streak_start(previous, now) or now) if no_rung_served else None |
| 326 | if rungs and all(check.state == DOWN for check in rungs): |
| 327 | failures.append("every discovery rung is down") |
| 328 | elif ( |
| 329 | since is not None |
| 330 | and any(check.state == CHALLENGED for check in rungs) |
| 331 | and now - since >= timedelta(hours=STREAK_FAIL_HOURS) |
| 332 | ): |
| 333 | failures.append( |
| 334 | f"no discovery rung served since {since.isoformat(timespec='minutes')} " |
| 335 | "(challenged two days running)" |
| 336 | ) |
| 337 | return failures, since |
| 338 | |
| 339 | |
| 340 | def run( |
| 341 | *, |
| 342 | fetch: Fetch = http_fetch, |
| 343 | hydrate: HydrateFn = reddit_hydrate.hydrate, |
| 344 | topics: Iterable[str] = TOPICS, |
| 345 | state_file: Optional[Path] = None, |
| 346 | now: Optional[datetime] = None, |
| 347 | sleep: Callable[[float], None] = time.sleep, |
| 348 | pause: float = PAUSE_SECONDS, |
| 349 | ) -> tuple[int, dict[str, Any]]: |
| 350 | """Run every check; returns ``(exit code, report)``.""" |
| 351 | now = now or datetime.now(timezone.utc) |
| 352 | previous = read_state(state_file) |
| 353 | reddit_health.reset_run_state() |
| 354 | web_search_keyless.reset_rung_health() |
| 355 | checks: list[Check] = [] |
| 356 | for topic in topics: |
| 357 | refs: dict[str, ThreadRef] = {} |
| 358 | for rung in RUNGS: |
| 359 | check = check_rung(rung, topic, fetch) |
| 360 | checks.append(check) |
| 361 | for ref in check.refs: |
| 362 | refs.setdefault(ref.post_id, ref) |
| 363 | sleep(pause) |
| 364 | hydration = check_hydration(topic, list(refs.values()), hydrate) |
| 365 | if hydration is not None: |
| 366 | checks.append(hydration) |
| 367 | checks.append(check_known_ids(fetch)) |
| 368 | failures, since = evaluate(checks, previous, now) |
| 369 | report = { |
| 370 | "at": now.isoformat(timespec="seconds"), |
| 371 | "no_rung_served": since is not None, |
| 372 | "no_serve_since": since.isoformat(timespec="seconds") if since else None, |
| 373 | "failures": failures, |
| 374 | "checks": [check.to_dict() for check in checks], |
| 375 | } |
| 376 | write_state(state_file, report) |
| 377 | return (1 if failures else 0), report |
| 378 | |
| 379 | |
| 380 | def render(report: dict[str, Any]) -> str: |
| 381 | lines = [ |
| 382 | f"Reddit canary {report['at']}", |
| 383 | "", |
| 384 | "| Check | State | HTTP | Results | Note |", |
| 385 | "|---|---|---:|---:|---|", |
| 386 | ] |
| 387 | for check in report["checks"]: |
| 388 | status = check["status"] if check["status"] is not None else "-" |
| 389 | lines.append(f"| {check['name']} | {check['state']} | {status} | {check['results']} | {check['note']} |") |
| 390 | lines.append("") |
| 391 | if report["failures"]: |
| 392 | lines.append("FAIL") |
| 393 | lines.extend(f"- {reason}" for reason in report["failures"]) |
| 394 | else: |
| 395 | lines.append("PASS") |
| 396 | return "\n".join(lines) + "\n" |
| 397 | |
| 398 | |
| 399 | def main(argv: Optional[list[str]] = None) -> int: |
| 400 | parser = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0]) |
| 401 | parser.add_argument("--state-file", help="previous-run state, read then rewritten (JSON)") |
| 402 | parser.add_argument("--report", help="also write the full report as JSON here") |
| 403 | args = parser.parse_args(argv) |
| 404 | clean_environment() |
| 405 | state_file = Path(args.state_file) if args.state_file else None |
| 406 | code, report = run(state_file=state_file) |
| 407 | text = render(report) |
| 408 | sys.stdout.write(text) |
| 409 | if args.report: |
| 410 | Path(args.report).parent.mkdir(parents=True, exist_ok=True) |
| 411 | Path(args.report).write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") |
| 412 | summary = os.environ.get("GITHUB_STEP_SUMMARY") |
| 413 | if summary: |
| 414 | with open(summary, "a", encoding="utf-8") as handle: |
| 415 | handle.write(text) |
| 416 | return code |
| 417 | |
| 418 | |
| 419 | if __name__ == "__main__": |
| 420 | raise SystemExit(main()) |
| 421 |