| 1 | """The keyless Reddit web floor: thread refs from web search, and the topic bar. |
| 2 | |
| 3 | :func:`web_refs` finds recent Reddit threads with no key and no consent. It |
| 4 | runs ``site:reddit.com <topic>`` through the keyless web ladder |
| 5 | (:mod:`web_search_keyless`: Brave HTML, then DuckDuckGo, then Startpage), |
| 6 | filtered to the run's recent period, and turns every thread link into a |
| 7 | canonical :class:`reddit_refs.ThreadRef`. Profile pages, wiki pages, |
| 8 | subreddit listings, share links and other hosts are not threads and are |
| 9 | dropped. Each ref keeps the result's title and date, which stand in only when |
| 10 | no hydrator can fill the thread. |
| 11 | |
| 12 | An entity gets at most :data:`MAX_QUERIES_PER_ENTITY` distinct web queries per run: |
| 13 | the topic, and the topic with the top resolved subreddit as a hint. Repeat |
| 14 | calls for the same topic (one per subquery, or per comparison entity) reuse |
| 15 | the answers already fetched instead of asking again. |
| 16 | |
| 17 | :func:`apply_bar` is the topic bar for threads that web search, a host, or a |
| 18 | listing found: a thread stays when its title names the topic, or when it sits |
| 19 | in a subreddit the plan resolved or the user named as dedicated and its body |
| 20 | names the topic. Never raises. |
| 21 | """ |
| 22 | |
| 23 | from __future__ import annotations |
| 24 | |
| 25 | import re |
| 26 | import sys |
| 27 | import threading |
| 28 | import time |
| 29 | from dataclasses import dataclass, field |
| 30 | from datetime import date, datetime, timezone |
| 31 | from functools import partial |
| 32 | from typing import Any, Callable, Iterable, Mapping, Optional |
| 33 | |
| 34 | from . import env, health, http, web_search_keyless |
| 35 | from .reddit_refs import ThreadRef, canonical_thread |
| 36 | |
| 37 | MAX_QUERIES_PER_ENTITY = 2 |
| 38 | RESULTS_PER_QUERY = 20 |
| 39 | |
| 40 | # Brave titles a Reddit hit "r/<sub> on Reddit: <title>"; DuckDuckGo and |
| 41 | # Startpage show "<title> : r/<sub>" with an optional " - Reddit". |
| 42 | _TITLE_PREFIX = re.compile(r"^r/[A-Za-z0-9_]+ on Reddit:\s*", re.IGNORECASE) |
| 43 | _TITLE_SUFFIX = re.compile(r"(?:\s*:\s*r/[A-Za-z0-9_]+)?(?:\s+-\s+Reddit)?\s*$", re.IGNORECASE) |
| 44 | |
| 45 | SearchFn = Callable[..., tuple[list[dict], dict]] |
| 46 | |
| 47 | |
| 48 | # The only SearXNG states that become a note. Anything else is ignored. |
| 49 | _SEARXNG_FAILURE_STATES = ( |
| 50 | web_search_keyless.BLOCKED, web_search_keyless.THROTTLED, |
| 51 | web_search_keyless.ERROR, health.TIMEOUT, |
| 52 | ) |
| 53 | |
| 54 | |
| 55 | @dataclass |
| 56 | class WebFloor: |
| 57 | """What :func:`web_refs` found: refs, the queries behind them, and the |
| 58 | state each web rung reached this run.""" |
| 59 | |
| 60 | refs: list[ThreadRef] = field(default_factory=list) |
| 61 | queries: list[str] = field(default_factory=list) |
| 62 | rungs: dict[str, str] = field(default_factory=dict) |
| 63 | timed_out: bool = False |
| 64 | # Failures the optional SearXNG fallback showed on any query, in order, once each. The |
| 65 | # rung map keeps only its latest state, so a later clean query would otherwise hide them. |
| 66 | searxng_failures: list[str] = field(default_factory=list) |
| 67 | _lock: threading.Lock = field( |
| 68 | default_factory=threading.Lock, init=False, repr=False, compare=False, |
| 69 | ) |
| 70 | |
| 71 | def record_query( |
| 72 | self, |
| 73 | query: str, |
| 74 | rungs: Optional[dict[str, str]] = None, |
| 75 | refs: Optional[Iterable[ThreadRef]] = None, |
| 76 | *, |
| 77 | timed_out: bool = False, |
| 78 | searxng: Optional[str] = None, |
| 79 | ) -> None: |
| 80 | """Atomically record a completed web query, its rung states, and refs.""" |
| 81 | with self._lock: |
| 82 | self.queries.append(query) |
| 83 | self.timed_out = self.timed_out or timed_out |
| 84 | if searxng in _SEARXNG_FAILURE_STATES and searxng not in self.searxng_failures: |
| 85 | self.searxng_failures.append(searxng) |
| 86 | for rung, state in (rungs or {}).items(): |
| 87 | # A rung skipped on a later query keeps the state that took it out. |
| 88 | if state != web_search_keyless.SKIPPED or rung not in self.rungs: |
| 89 | self.rungs[rung] = state |
| 90 | if refs is not None: |
| 91 | self.refs = list(refs) |
| 92 | |
| 93 | def mark_timed_out(self) -> None: |
| 94 | with self._lock: |
| 95 | self.timed_out = True |
| 96 | |
| 97 | def record_rung(self, rung: str, state: str) -> None: |
| 98 | """Record one rung state under the floor lock.""" |
| 99 | with self._lock: |
| 100 | if state != web_search_keyless.SKIPPED or rung not in self.rungs: |
| 101 | self.rungs[rung] = state |
| 102 | |
| 103 | def add_refs(self, refs: Iterable[ThreadRef]) -> None: |
| 104 | """Merge thread refs under the floor lock, preserving first-seen order.""" |
| 105 | with self._lock: |
| 106 | seen = {ref.post_id for ref in self.refs} |
| 107 | for ref in refs: |
| 108 | if ref.post_id not in seen: |
| 109 | seen.add(ref.post_id) |
| 110 | self.refs.append(ref) |
| 111 | |
| 112 | def snapshot(self) -> WebFloor: |
| 113 | """Return a detached, thread-safe copy of this floor's current state.""" |
| 114 | with self._lock: |
| 115 | return WebFloor( |
| 116 | refs=list(self.refs), |
| 117 | queries=list(self.queries), |
| 118 | rungs=dict(self.rungs), |
| 119 | timed_out=self.timed_out, |
| 120 | searxng_failures=list(self.searxng_failures), |
| 121 | ) |
| 122 | |
| 123 | |
| 124 | @dataclass |
| 125 | class BarResult: |
| 126 | kept: list[dict] |
| 127 | dropped: list[dict] |
| 128 | |
| 129 | def note(self, label: str) -> Optional[str]: |
| 130 | """``"N of M threads dropped for not naming the topic (<label>)"``, or None.""" |
| 131 | if not self.dropped: |
| 132 | return None |
| 133 | total = len(self.kept) + len(self.dropped) |
| 134 | return f"{len(self.dropped)} of {total} threads dropped for not naming the topic ({label})" |
| 135 | |
| 136 | |
| 137 | @dataclass |
| 138 | class _QueryAttempt: |
| 139 | done: threading.Event = field(default_factory=threading.Event) |
| 140 | items: list[dict] = field(default_factory=list) |
| 141 | timed_out: bool = False |
| 142 | |
| 143 | |
| 144 | # Per-run memo: topic key -> {query: attempt or None for a retryable miss}. |
| 145 | # Waiters keep the attempt they joined, even if the slot becomes retryable. |
| 146 | # Direct callers that omit ``config`` read the approved SearXNG URL once per run. |
| 147 | _LOCK = threading.Lock() |
| 148 | # Held while the standalone config is read. Each run gets its own, so a read that is still |
| 149 | # blocked when a run is reset can neither stall the next run nor seed it. |
| 150 | _CONFIG_LOAD_LOCK = threading.Lock() |
| 151 | _ASKED: dict[str, dict[str, Optional[_QueryAttempt]]] = {} |
| 152 | _SEARXNG_URL: Optional[str] = None |
| 153 | _RUN_GENERATION = 0 |
| 154 | _WAIT_SECONDS = 30.0 |
| 155 | |
| 156 | |
| 157 | def reset_run_state() -> None: |
| 158 | """Forget the queries and SearXNG setting this run asked (call between runs in one process).""" |
| 159 | global _SEARXNG_URL, _RUN_GENERATION, _CONFIG_LOAD_LOCK |
| 160 | with _LOCK: |
| 161 | _ASKED.clear() |
| 162 | _SEARXNG_URL = None |
| 163 | _CONFIG_LOAD_LOCK = threading.Lock() |
| 164 | _RUN_GENERATION += 1 |
| 165 | |
| 166 | |
| 167 | def _normalize_searxng_url(config: Optional[Mapping[str, Any]]) -> str: |
| 168 | """Extract trimmed LAST30DAYS_SEARXNG_URL or '' when absent/unsubstituted.""" |
| 169 | if not isinstance(config, Mapping): |
| 170 | return "" |
| 171 | raw = config.get("LAST30DAYS_SEARXNG_URL") |
| 172 | if not isinstance(raw, str) or env.is_unsubstituted_template(raw): |
| 173 | return "" |
| 174 | return raw.strip() |
| 175 | |
| 176 | |
| 177 | def _standalone_searxng_url(generation: int, deadline: Optional[float] = None) -> Optional[str]: |
| 178 | """Load the approved URL. The answer is '' if absent and None if unavailable. |
| 179 | |
| 180 | ``deadline`` (``time.monotonic()``) bounds the wait for another caller's load of the same |
| 181 | run. Out of time the answer is None, exactly as for a config that could not be read, and |
| 182 | nothing is cached, so the caller's query stays retryable. |
| 183 | """ |
| 184 | global _SEARXNG_URL |
| 185 | with _LOCK: |
| 186 | if generation != _RUN_GENERATION: |
| 187 | return None |
| 188 | if _SEARXNG_URL is not None: |
| 189 | return _SEARXNG_URL |
| 190 | load_lock = _CONFIG_LOAD_LOCK |
| 191 | wait = -1 if deadline is None else max(0.0, deadline - time.monotonic()) |
| 192 | if not load_lock.acquire(timeout=wait): |
| 193 | _log("config load wait ran out") |
| 194 | return None |
| 195 | try: |
| 196 | with _LOCK: |
| 197 | if generation != _RUN_GENERATION: |
| 198 | return None |
| 199 | if _SEARXNG_URL is not None: |
| 200 | return _SEARXNG_URL |
| 201 | try: |
| 202 | url = (env.resolve_searxng_url() or "").strip() |
| 203 | except Exception as exc: |
| 204 | _log(f"config load failed: {type(exc).__name__}") |
| 205 | return None |
| 206 | with _LOCK: |
| 207 | if generation != _RUN_GENERATION: |
| 208 | return None |
| 209 | _SEARXNG_URL = url |
| 210 | return url |
| 211 | finally: |
| 212 | load_lock.release() |
| 213 | |
| 214 | |
| 215 | def _log(msg: str) -> None: |
| 216 | sys.stderr.write(f"[RedditWeb] {msg}\n") |
| 217 | sys.stderr.flush() |
| 218 | |
| 219 | |
| 220 | def _today() -> str: |
| 221 | return datetime.now(timezone.utc).date().isoformat() |
| 222 | |
| 223 | |
| 224 | def _freshness(from_date: Optional[str], to_date: Optional[str]) -> Optional[str]: |
| 225 | """The search engines' recency filter that covers the window, or None. |
| 226 | |
| 227 | A window that ends before today cannot be expressed as "past month", so |
| 228 | it runs unfiltered and the hydrated post dates do the windowing. |
| 229 | """ |
| 230 | if not from_date or not to_date or to_date < _today(): |
| 231 | return None |
| 232 | try: |
| 233 | days = (date.fromisoformat(_today()) - date.fromisoformat(from_date)).days |
| 234 | except ValueError: |
| 235 | return None |
| 236 | if days <= 7: |
| 237 | return "week" |
| 238 | if days <= 31: |
| 239 | return "month" |
| 240 | if days <= 366: |
| 241 | return "year" |
| 242 | return None |
| 243 | |
| 244 | |
| 245 | def _queries(topic: str, subreddits: Optional[list[str]]) -> list[str]: |
| 246 | queries = [f"site:reddit.com {topic}"] |
| 247 | hint = next((s.strip().removeprefix("r/") for s in subreddits or [] if s and s.strip()), "") |
| 248 | if hint: |
| 249 | queries.append(f"site:reddit.com r/{hint} {topic}") |
| 250 | return queries[:MAX_QUERIES_PER_ENTITY] |
| 251 | |
| 252 | |
| 253 | def _clean_title(title: str) -> str: |
| 254 | return _TITLE_SUFFIX.sub("", _TITLE_PREFIX.sub("", (title or "").strip())).strip() |
| 255 | |
| 256 | |
| 257 | def _ask( |
| 258 | generation: int, topic_key: str, query: str, search: SearchFn, date_range: tuple[str, str], |
| 259 | freshness: Optional[str], config: Optional[Mapping[str, Any]] = None, |
| 260 | deadline: Optional[float] = None, |
| 261 | ) -> tuple[Optional[list[dict]], dict, bool]: |
| 262 | """One web query, memoized per run and capped per entity. |
| 263 | |
| 264 | An absent item list means the entity's query slots were spent or the run ended. |
| 265 | """ |
| 266 | with _LOCK: |
| 267 | if generation != _RUN_GENERATION: |
| 268 | return None, {}, False |
| 269 | asked = _ASKED.setdefault(topic_key, {}) |
| 270 | attempt = asked.get(query) |
| 271 | owner = attempt is None |
| 272 | if owner: |
| 273 | if query not in asked and len(asked) >= MAX_QUERIES_PER_ENTITY: |
| 274 | return None, {}, False |
| 275 | attempt = asked[query] = _QueryAttempt() |
| 276 | if not owner: |
| 277 | wait = _WAIT_SECONDS |
| 278 | if deadline is not None: |
| 279 | wait = min(wait, max(0.0, deadline - time.monotonic())) |
| 280 | completed = attempt.done.wait(wait) |
| 281 | with _LOCK: |
| 282 | if generation != _RUN_GENERATION: |
| 283 | return None, {}, False |
| 284 | if not completed: |
| 285 | return [], {}, True |
| 286 | return list(attempt.items), {}, attempt.timed_out |
| 287 | items: list[dict] = [] |
| 288 | artifact: dict = {} |
| 289 | url: Optional[str] = "" |
| 290 | try: |
| 291 | url = ( |
| 292 | _standalone_searxng_url(generation, deadline) |
| 293 | if config is None else _normalize_searxng_url(config) |
| 294 | ) |
| 295 | with _LOCK: |
| 296 | if generation != _RUN_GENERATION: |
| 297 | return None, {}, False |
| 298 | search_config = {"LAST30DAYS_SEARXNG_URL": url} if url else {} |
| 299 | extra = {"deadline_monotonic": deadline} if deadline is not None else {} |
| 300 | # The web rungs' failures are the floor's own health, not the Reddit |
| 301 | # source's: keep them out of the stream's failure sink. |
| 302 | with http.capture_failures(): |
| 303 | items, artifact = search( |
| 304 | query, date_range, search_config, |
| 305 | count=RESULTS_PER_QUERY, freshness=freshness, **extra, |
| 306 | ) |
| 307 | except Exception as exc: # the floor must never break the lane |
| 308 | _log(f"web search failed: {type(exc).__name__}: {exc}") |
| 309 | finally: |
| 310 | timed_out = ((artifact or {}).get("_source_outcome") or {}).get("state") == health.TIMEOUT |
| 311 | with _LOCK: |
| 312 | if generation == _RUN_GENERATION: |
| 313 | attempt.items = list(items or []) |
| 314 | attempt.timed_out = timed_out |
| 315 | if not items and (url is None or timed_out): |
| 316 | # Let this query try again without freeing its slot for a new hint. |
| 317 | asked[query] = None |
| 318 | attempt.done.set() |
| 319 | return list(items or []), artifact or {}, timed_out |
| 320 | |
| 321 | |
| 322 | def web_refs( |
| 323 | topic: str, |
| 324 | *, |
| 325 | subreddits: Optional[list[str]] = None, |
| 326 | from_date: Optional[str] = None, |
| 327 | to_date: Optional[str] = None, |
| 328 | search: Optional[SearchFn] = None, |
| 329 | deadline: Optional[float] = None, |
| 330 | floor: Optional[WebFloor] = None, |
| 331 | config: Optional[Mapping[str, Any]] = None, |
| 332 | ) -> WebFloor: |
| 333 | """Thread refs for ``topic`` from keyless web search. Never raises. |
| 334 | |
| 335 | ``subreddits`` are the plan's resolved subreddits, best first; the first |
| 336 | one is the second query's hint. ``search`` replaces |
| 337 | :func:`web_search_keyless.keyless_search` (tests). No query starts after |
| 338 | ``deadline`` (``time.monotonic()``). ``floor`` is filled in place after |
| 339 | each query, so a caller that stops waiting keeps the threads found so far. |
| 340 | """ |
| 341 | with _LOCK: |
| 342 | generation = _RUN_GENERATION |
| 343 | floor = floor if floor is not None else WebFloor() |
| 344 | topic = " ".join(str(topic or "").split()) |
| 345 | if not topic: |
| 346 | return floor |
| 347 | search = search or partial( |
| 348 | web_search_keyless.keyless_search, |
| 349 | accept_result=lambda item: canonical_thread(str(item.get("url") or "")) is not None, |
| 350 | ) |
| 351 | date_range = (from_date or "", to_date or _today()) |
| 352 | freshness = _freshness(from_date, to_date) |
| 353 | by_id: dict[str, ThreadRef] = {} |
| 354 | skipped_links = 0 |
| 355 | for query in _queries(topic, subreddits): |
| 356 | if deadline is not None and time.monotonic() >= deadline: |
| 357 | floor.mark_timed_out() |
| 358 | _log("web floor stopped at its deadline; later queries skipped") |
| 359 | break |
| 360 | items, artifact, timed_out = _ask( |
| 361 | generation, topic.lower(), query, search, date_range, freshness, |
| 362 | config=config, deadline=deadline, |
| 363 | ) |
| 364 | if items is None: |
| 365 | continue |
| 366 | for item in items: |
| 367 | ref = canonical_thread(str(item.get("url") or "")) |
| 368 | if ref is None: |
| 369 | skipped_links += 1 |
| 370 | continue |
| 371 | if ref.post_id in by_id: |
| 372 | continue |
| 373 | ref.provenance.add("web") |
| 374 | ref.title = _clean_title(str(item.get("title") or "")) |
| 375 | ref.date = item.get("date") or None |
| 376 | by_id[ref.post_id] = ref |
| 377 | query_rungs = dict(artifact.get("keyless_rungs") or {}) |
| 378 | if artifact.get("keyless_searxng"): |
| 379 | query_rungs["searxng"] = artifact["keyless_searxng"] |
| 380 | floor.record_query( |
| 381 | query, query_rungs, by_id.values(), timed_out=timed_out, |
| 382 | searxng=artifact.get("keyless_searxng"), |
| 383 | ) |
| 384 | snap = floor.snapshot() |
| 385 | if snap.queries: |
| 386 | rungs = ", ".join(f"{rung} {state}" for rung, state in snap.rungs.items()) or "no rung" |
| 387 | _log( |
| 388 | f"{len(snap.refs)} threads from {len(snap.queries)} web queries " |
| 389 | f"({rungs}; {skipped_links} non-thread links skipped)" |
| 390 | ) |
| 391 | return floor |
| 392 | |
| 393 | |
| 394 | def names_topic(text: str, topic: str) -> bool: |
| 395 | """Whether ``text`` names ``topic``: the entity check rerank uses, or token |
| 396 | overlap for a topic with no usable entity.""" |
| 397 | from . import relevance, rerank |
| 398 | |
| 399 | entity = rerank._primary_entity(topic).lower() |
| 400 | if entity: |
| 401 | return rerank._entity_grounded(text or "", entity) |
| 402 | return relevance.token_overlap_relevance(topic, text or "") >= relevance.RELEVANCE_FLOOR |
| 403 | |
| 404 | |
| 405 | def _sub_key(name: Any) -> str: |
| 406 | return str(name or "").strip().removeprefix("r/").lower() |
| 407 | |
| 408 | |
| 409 | def apply_bar( |
| 410 | topic: str, |
| 411 | items: Iterable[dict], |
| 412 | *, |
| 413 | subreddits: Optional[Iterable[str]] = None, |
| 414 | dedicated: Optional[Iterable[str]] = None, |
| 415 | ) -> BarResult: |
| 416 | """Split threads into those that name ``topic`` and those that do not. |
| 417 | |
| 418 | A title that names the topic passes. A thread in one of ``subreddits`` |
| 419 | (resolved by the plan) or ``dedicated`` (named by the user) also passes |
| 420 | when its body names the topic. Order is kept. |
| 421 | """ |
| 422 | items = [item for item in items or [] if isinstance(item, dict)] |
| 423 | if not topic: |
| 424 | return BarResult(kept=items, dropped=[]) |
| 425 | home = {_sub_key(s) for s in [*(subreddits or []), *(dedicated or [])]} - {""} |
| 426 | result = BarResult(kept=[], dropped=[]) |
| 427 | for item in items: |
| 428 | passed = names_topic(str(item.get("title") or ""), topic) or ( |
| 429 | _sub_key(item.get("subreddit")) in home |
| 430 | and names_topic(str(item.get("selftext") or ""), topic) |
| 431 | ) |
| 432 | (result.kept if passed else result.dropped).append(item) |
| 433 | return result |
| 434 |