| 1 | """Keyless web search (floor tier for engine-side general web). |
| 2 | |
| 3 | Returns ranked web results for a query with no API key. This is strictly the |
| 4 | FLOOR of the search-source ladder: |
| 5 | |
| 6 | host-native search > paid engine backend > keyless engine search |
| 7 | |
| 8 | It must never run on a host that has native search (the model does it better |
| 9 | there) or preempt a configured paid backend. The pipeline/grounding layer owns |
| 10 | that gating; this module just performs the search when asked. |
| 11 | |
| 12 | Vendor-neutral rungs, all stdlib-only via :mod:`http`: |
| 13 | 0. Brave Search HTML results, tried first for ``site:reddit.com`` queries |
| 14 | only (the Reddit web floor): it serves dated Reddit thread links to a |
| 15 | plain GET where DuckDuckGo throttles. |
| 16 | 1. DuckDuckGo HTML endpoint (no key, no instance to maintain). |
| 17 | 2. Startpage HTML results, tried when DuckDuckGo yields nothing — notably |
| 18 | when DuckDuckGo anomaly-blocks a datacenter IP with a 202 challenge page. |
| 19 | 3. A configurable SearXNG instance returning JSON (``LAST30DAYS_SEARXNG_URL``), |
| 20 | tried when the HTML rungs yield nothing. |
| 21 | |
| 22 | Each HTML rung keeps a health state for the run (:class:`RungHealth`). A 403 |
| 23 | marks a rung ``blocked`` and a 429 that survived its one retry (or a known |
| 24 | challenge page) marks it ``throttled``; either way the rung is skipped for the |
| 25 | rest of the run and the next rung answers. One failed page of any other kind |
| 26 | (``error``) or a page with no results (``empty``) skips nothing. |
| 27 | :func:`seed_rung_health` lets a caller start a run with rungs it already |
| 28 | knows are down. |
| 29 | |
| 30 | Never raises. Returns results in the same dict shape as the paid backends in |
| 31 | :mod:`grounding` so they flow through normalize/score/dedupe unchanged. On total |
| 32 | failure returns ``([], artifact)`` with a degraded reason in the artifact, so the |
| 33 | source-health layer can report it. |
| 34 | """ |
| 35 | |
| 36 | from __future__ import annotations |
| 37 | |
| 38 | import html |
| 39 | import ipaddress |
| 40 | import re |
| 41 | import threading |
| 42 | import time |
| 43 | from datetime import datetime, timedelta, timezone |
| 44 | from html.parser import HTMLParser |
| 45 | from typing import Any, Callable, Mapping, Optional |
| 46 | from urllib.parse import parse_qs, urlencode, urlparse, urlsplit, urlunsplit |
| 47 | |
| 48 | from . import health, http, log, public_host |
| 49 | |
| 50 | KEYLESS_BACKEND = "keyless" |
| 51 | |
| 52 | _DDG_HTML_URL = "https://html.duckduckgo.com/html/" |
| 53 | |
| 54 | # Floor-tier relevance: below the paid backends' 0.8 so fusion prefers paid/native |
| 55 | # results when both are present. |
| 56 | _KEYLESS_RELEVANCE = 0.6 |
| 57 | |
| 58 | _MAX_SERP_BYTES = 2 * 1024 * 1024 |
| 59 | _MAX_SEARXNG_BYTES = 2 * 1024 * 1024 |
| 60 | # With a result filter, how many rows are looked at before giving up. |
| 61 | _MAX_SEARXNG_SCANNED = 100 |
| 62 | |
| 63 | _BLOCKED_SEARXNG_HOSTS = frozenset({ |
| 64 | "metadata.google.internal", |
| 65 | "metadata.goog", |
| 66 | "instance-data", |
| 67 | }) |
| 68 | _AWS_IPV6_IMDS = ipaddress.IPv6Address("fd00:ec2::254") |
| 69 | _ALIBABA_IMDS = ipaddress.IPv4Address("100.100.100.200") |
| 70 | |
| 71 | # Single-character-class opening-tag and attribute patterns: [^<>]* never |
| 72 | # crosses a tag boundary, keeping all SERP scans linear even on malformed HTML. |
| 73 | _A_TAG_RE = re.compile(r"<a\b[^<>]*>", re.IGNORECASE) |
| 74 | _DIV_TAG_RE = re.compile(r"<div\b[^<>]*>", re.IGNORECASE) |
| 75 | _H2_TAG_RE = re.compile(r"<h2\b[^<>]*>", re.IGNORECASE) |
| 76 | _P_TAG_RE = re.compile(r"<p\b[^<>]*>", re.IGNORECASE) |
| 77 | _CLOSE_A_RE = re.compile(r"</a\s*>", re.IGNORECASE) |
| 78 | _CLOSE_DIV_RE = re.compile(r"</div\s*>", re.IGNORECASE) |
| 79 | _CLOSE_H2_RE = re.compile(r"</h2\s*>", re.IGNORECASE) |
| 80 | _CLOSE_P_RE = re.compile(r"</p\s*>", re.IGNORECASE) |
| 81 | _CLASS_ATTR_RE = re.compile(r'\bclass="(?P<cls>[^"]*)"', re.IGNORECASE) |
| 82 | _HREF_ATTR_RE = re.compile(r'\bhref="(?P<href>[^"]+)"', re.IGNORECASE) |
| 83 | _HTTP_HREF_ATTR_RE = re.compile(r'\bhref="(?P<href>https?://[^"]+)"', re.IGNORECASE) |
| 84 | _DATA_TYPE_WEB_RE = re.compile(r'\bdata-type="web"', re.IGNORECASE) |
| 85 | _BRAVE_SNIPPET_CLASS_RE = re.compile(r"^(?:content|inline-qa-question)\b", re.IGNORECASE) |
| 86 | |
| 87 | _STARTPAGE_HTML_URL = "https://www.startpage.com/sp/search" |
| 88 | _BRAVE_HTML_URL = "https://search.brave.com/search" |
| 89 | |
| 90 | # Bounded character class with no overlapping whitespace quantifiers: |
| 91 | # _brave_date strips surrounding whitespace and trailing dashes in Python. |
| 92 | _BRAVE_AGE_RE = re.compile( |
| 93 | r'<span class="t-secondary">(?P<age>[^<]{1,120})</span>', re.IGNORECASE, |
| 94 | ) |
| 95 | _RELATIVE_AGE_RE = re.compile( |
| 96 | r"^(?P<n>\d+)\s+(?P<unit>minute|hour|day|week|month|year)s?\s+ago", re.IGNORECASE, |
| 97 | ) |
| 98 | _UNIT_DAYS = {"minute": 0, "hour": 0, "day": 1, "week": 7, "month": 30, "year": 365} |
| 99 | _ABSOLUTE_DATE_FORMATS = ("%b %d, %Y", "%B %d, %Y") |
| 100 | |
| 101 | # Freshness filters per rung: Brave ``tf``, DuckDuckGo ``df``, Startpage ``with_date``. |
| 102 | _FRESHNESS = { |
| 103 | "day": ("pd", "d", "d"), |
| 104 | "week": ("pw", "w", "w"), |
| 105 | "month": ("pm", "m", "m"), |
| 106 | "year": ("py", "y", "y"), |
| 107 | } |
| 108 | |
| 109 | # A DuckDuckGo anomaly page answers 202 with no results; it is a throttle. |
| 110 | _CHALLENGE_MARKERS = { |
| 111 | "ddg": ("anomaly-modal",), |
| 112 | # Startpage answers a refused client with a proof-of-work challenge page. |
| 113 | "startpage": ('"challenge":{"issuedAt"',), |
| 114 | } |
| 115 | |
| 116 | RUNGS = ("brave", "ddg", "startpage") |
| 117 | OK = "ok" |
| 118 | EMPTY = "empty" |
| 119 | ERROR = "error" |
| 120 | THROTTLED = "throttled" |
| 121 | BLOCKED = "blocked" |
| 122 | SKIPPED = "skipped" |
| 123 | # States that take a rung out of the run. |
| 124 | _DOWN = frozenset({THROTTLED, BLOCKED}) |
| 125 | |
| 126 | |
| 127 | class RungHealth: |
| 128 | """Per-run health of the HTML rungs, shared by every thread of a run.""" |
| 129 | |
| 130 | def __init__(self) -> None: |
| 131 | self._lock = threading.Lock() |
| 132 | self._states: dict[str, str] = {} |
| 133 | self._seeded: set[str] = set() |
| 134 | |
| 135 | def usable(self, rung: str) -> bool: |
| 136 | with self._lock: |
| 137 | return rung not in self._seeded and self._states.get(rung) not in _DOWN |
| 138 | |
| 139 | def record(self, rung: str, state: str) -> None: |
| 140 | with self._lock: |
| 141 | # A rung already down stays down for the run. |
| 142 | if self._states.get(rung) not in _DOWN: |
| 143 | self._states[rung] = state |
| 144 | |
| 145 | def seed(self, states: Mapping[str, str]) -> None: |
| 146 | """Start the run with rungs already known down (``blocked``/``throttled``).""" |
| 147 | with self._lock: |
| 148 | for rung, state in (states or {}).items(): |
| 149 | if rung in RUNGS and state in _DOWN: |
| 150 | self._seeded.add(rung) |
| 151 | self._states[rung] = state |
| 152 | |
| 153 | def snapshot(self) -> dict[str, str]: |
| 154 | """Each rung's state this run; a seeded rung that never ran reads ``skipped``.""" |
| 155 | with self._lock: |
| 156 | out = dict(self._states) |
| 157 | for rung in self._seeded: |
| 158 | out[rung] = SKIPPED |
| 159 | return out |
| 160 | |
| 161 | def reset(self) -> None: |
| 162 | with self._lock: |
| 163 | self._states.clear() |
| 164 | self._seeded.clear() |
| 165 | |
| 166 | |
| 167 | RUNG_HEALTH = RungHealth() |
| 168 | |
| 169 | |
| 170 | def rung_health() -> dict[str, str]: |
| 171 | """The HTML rungs' states this run (see :class:`RungHealth`).""" |
| 172 | return RUNG_HEALTH.snapshot() |
| 173 | |
| 174 | |
| 175 | def seed_rung_health(states: Mapping[str, str]) -> None: |
| 176 | """Skip the given down rungs for this run without asking them.""" |
| 177 | RUNG_HEALTH.seed(states) |
| 178 | |
| 179 | |
| 180 | def reset_rung_health() -> None: |
| 181 | """Forget every rung's state (call between runs in one process).""" |
| 182 | RUNG_HEALTH.reset() |
| 183 | |
| 184 | |
| 185 | def _domain(url: str) -> str: |
| 186 | # Normalize identically to grounding._domain (strip + lowercase) so keyless |
| 187 | # and paid results dedupe/group consistently by source_domain. |
| 188 | try: |
| 189 | return urlparse(url).netloc.strip().lower() |
| 190 | except (ValueError, AttributeError): |
| 191 | return "" |
| 192 | |
| 193 | |
| 194 | class _TextStripper(HTMLParser): |
| 195 | """Single-pass O(N) HTML-to-text stripper that drops <style>/<script> contents.""" |
| 196 | |
| 197 | def __init__(self) -> None: |
| 198 | super().__init__(convert_charrefs=True) |
| 199 | self._skip_depths = {"style": 0, "script": 0} |
| 200 | self._skip_active = 0 |
| 201 | self._parts: list[str] = [] |
| 202 | |
| 203 | def handle_starttag(self, tag: str, attrs: list[tuple[str, Optional[str]]]) -> None: |
| 204 | tag_lower = tag.lower() |
| 205 | if tag_lower in self._skip_depths: |
| 206 | self._skip_depths[tag_lower] += 1 |
| 207 | self._skip_active += 1 |
| 208 | |
| 209 | def handle_endtag(self, tag: str) -> None: |
| 210 | tag_lower = tag.lower() |
| 211 | if tag_lower in self._skip_depths and self._skip_depths[tag_lower] > 0: |
| 212 | self._skip_depths[tag_lower] -= 1 |
| 213 | self._skip_active -= 1 |
| 214 | |
| 215 | def handle_data(self, data: str) -> None: |
| 216 | if self._skip_active == 0: |
| 217 | self._parts.append(data) |
| 218 | |
| 219 | def text(self) -> str: |
| 220 | return "".join(self._parts).strip() |
| 221 | |
| 222 | |
| 223 | def _strip_html(fragment: str) -> str: |
| 224 | if not fragment: |
| 225 | return "" |
| 226 | parser = _TextStripper() |
| 227 | parser.feed(fragment) |
| 228 | parser.close() |
| 229 | return parser.text() |
| 230 | |
| 231 | |
| 232 | def _is_blocked_searxng_ip(addr: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool: |
| 233 | """Reject link-local/cloud-metadata, unspecified, and multicast IP addresses. |
| 234 | |
| 235 | Loopback (127.0.0.0/8, ::1) and RFC1918 private LAN addresses are allowed |
| 236 | so self-hosted local/Docker/homelab SearXNG instances continue to work. |
| 237 | """ |
| 238 | if addr.is_link_local or addr.is_unspecified or addr.is_multicast: |
| 239 | return True |
| 240 | if addr == _AWS_IPV6_IMDS or addr == _ALIBABA_IMDS: |
| 241 | return True |
| 242 | if isinstance(addr, ipaddress.IPv6Address): |
| 243 | for embedded in ( |
| 244 | addr.ipv4_mapped, |
| 245 | addr.sixtofour, |
| 246 | addr.teredo[1] if addr.teredo else None, |
| 247 | ): |
| 248 | if embedded is not None and _is_blocked_searxng_ip(embedded): |
| 249 | return True |
| 250 | if addr in public_host._NAT64_WELL_KNOWN or addr in public_host._NAT64_LOCAL: |
| 251 | embedded = ipaddress.IPv4Address(int(addr) & 0xFFFFFFFF) |
| 252 | if _is_blocked_searxng_ip(embedded): |
| 253 | return True |
| 254 | return False |
| 255 | |
| 256 | |
| 257 | def _is_allowed_searxng_ip(addr: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool: |
| 258 | return not _is_blocked_searxng_ip(addr) |
| 259 | |
| 260 | |
| 261 | def _normalize_searxng_host(host: str) -> str: |
| 262 | """Normalize a SearXNG hostname via IDNA to canonical ASCII, or '' if invalid.""" |
| 263 | raw = (host or "").strip() |
| 264 | if not raw or "%" in raw: |
| 265 | return "" |
| 266 | if any(ch.isspace() or ord(ch) < 0x20 or ord(ch) == 0x7F for ch in raw): |
| 267 | return "" |
| 268 | if raw.startswith("[") and raw.endswith("]"): |
| 269 | raw = raw[1:-1] |
| 270 | if ":" in raw: |
| 271 | return raw.lower().rstrip(".") if raw.isascii() else "" |
| 272 | try: |
| 273 | normalized = raw.encode("idna").decode("ascii").lower().rstrip(".") |
| 274 | except UnicodeError: |
| 275 | return "" |
| 276 | if not normalized or any(ch.isspace() or ord(ch) < 0x20 or ord(ch) == 0x7F for ch in normalized): |
| 277 | return "" |
| 278 | return normalized |
| 279 | |
| 280 | |
| 281 | def _is_blocked_searxng_host(host: str) -> bool: |
| 282 | normalized = _normalize_searxng_host(host) |
| 283 | if not normalized: |
| 284 | return True |
| 285 | if ( |
| 286 | normalized in _BLOCKED_SEARXNG_HOSTS |
| 287 | or normalized.endswith(".metadata.google.internal") |
| 288 | or normalized.endswith(".metadata.goog") |
| 289 | ): |
| 290 | return True |
| 291 | ip = public_host._parse_ip_literal(normalized) |
| 292 | if ip is not None: |
| 293 | return _is_blocked_searxng_ip(ip) |
| 294 | return False |
| 295 | |
| 296 | |
| 297 | def _validate_searxng_url(instance_url: str) -> Optional[tuple[str, tuple[str, str, int]]]: |
| 298 | """Validate LAST30DAYS_SEARXNG_URL and return ``(normalized_base, origin)`` or None.""" |
| 299 | if not isinstance(instance_url, str): |
| 300 | return None |
| 301 | text = instance_url.strip() |
| 302 | if not text or "\\" in text or any(ch.isspace() or ord(ch) < 0x20 or ord(ch) == 0x7F for ch in text): |
| 303 | return None |
| 304 | try: |
| 305 | parts = urlsplit(text) |
| 306 | port = parts.port |
| 307 | except ValueError: |
| 308 | return None |
| 309 | scheme = parts.scheme.lower() |
| 310 | if scheme not in ("http", "https"): |
| 311 | return None |
| 312 | if parts.username is not None or parts.password is not None: |
| 313 | return None |
| 314 | if "%" in parts.netloc: |
| 315 | return None |
| 316 | if parts.query or parts.fragment: |
| 317 | return None |
| 318 | host = _normalize_searxng_host(parts.hostname or "") |
| 319 | if not host or _is_blocked_searxng_host(host): |
| 320 | return None |
| 321 | effective_port = port if port is not None else (443 if scheme == "https" else 80) |
| 322 | origin = (scheme, host, effective_port) |
| 323 | base_path = parts.path.rstrip("/") |
| 324 | netloc_host = f"[{host}]" if ":" in host else host |
| 325 | netloc = f"{netloc_host}:{port}" if port is not None else netloc_host |
| 326 | normalized = urlunsplit((scheme, netloc, base_path, "", "")) |
| 327 | return normalized, origin |
| 328 | |
| 329 | |
| 330 | def _rung_redirect_guard(url: str): |
| 331 | """Allow redirects only over HTTPS to the same public search rung host.""" |
| 332 | expected_host = (urlsplit(url).hostname or "").strip().lower().rstrip(".") |
| 333 | |
| 334 | def _guard(target: str) -> bool: |
| 335 | if not isinstance(target, str) or not target or target != target.strip(): |
| 336 | return False |
| 337 | if "\\" in target or any(ch.isspace() or ord(ch) < 0x20 or ord(ch) == 0x7F for ch in target): |
| 338 | return False |
| 339 | if not public_host.is_public_address_syntax(target): |
| 340 | return False |
| 341 | try: |
| 342 | parts = urlsplit(target) |
| 343 | port = parts.port |
| 344 | except ValueError: |
| 345 | return False |
| 346 | if parts.scheme.lower() != "https": |
| 347 | return False |
| 348 | if parts.username is not None or parts.password is not None: |
| 349 | return False |
| 350 | if port not in (None, 443): |
| 351 | return False |
| 352 | host = (parts.hostname or "").strip().lower().rstrip(".") |
| 353 | return bool(expected_host) and host == expected_host |
| 354 | |
| 355 | return _guard |
| 356 | |
| 357 | |
| 358 | def _searxng_redirect_guard(origin: tuple[str, str, int]): |
| 359 | """Allow SearXNG redirects only within the exact configured origin.""" |
| 360 | def _guard(target: str) -> bool: |
| 361 | if not isinstance(target, str) or not target or target != target.strip(): |
| 362 | return False |
| 363 | if "\\" in target or any(ch.isspace() or ord(ch) < 0x20 or ord(ch) == 0x7F for ch in target): |
| 364 | return False |
| 365 | try: |
| 366 | parts = urlsplit(target) |
| 367 | port = parts.port |
| 368 | except ValueError: |
| 369 | return False |
| 370 | scheme = parts.scheme.lower() |
| 371 | if scheme not in ("http", "https"): |
| 372 | return False |
| 373 | if parts.username is not None or parts.password is not None: |
| 374 | return False |
| 375 | if "%" in parts.netloc: |
| 376 | return False |
| 377 | host = _normalize_searxng_host(parts.hostname or "") |
| 378 | if not host or _is_blocked_searxng_host(host): |
| 379 | return False |
| 380 | effective_port = port if port is not None else (443 if scheme == "https" else 80) |
| 381 | return (scheme, host, effective_port) == origin |
| 382 | |
| 383 | return _guard |
| 384 | |
| 385 | |
| 386 | def _unwrap_ddg_redirect(href: str) -> str: |
| 387 | """DuckDuckGo wraps result links as //duckduckgo.com/l/?uddg=<encoded>.""" |
| 388 | if "uddg=" not in href: |
| 389 | return href if href.startswith("http") else f"https:{href}" if href.startswith("//") else href |
| 390 | try: |
| 391 | query = urlparse(href if href.startswith("http") else f"https:{href}").query |
| 392 | target = parse_qs(query).get("uddg", [""])[0] |
| 393 | return target or href |
| 394 | except (ValueError, AttributeError): |
| 395 | return href |
| 396 | |
| 397 | |
| 398 | def _is_reddit_query(query: str) -> bool: |
| 399 | return "site:reddit.com" in (query or "").lower() |
| 400 | |
| 401 | |
| 402 | def keyless_search( |
| 403 | query: str, |
| 404 | date_range: tuple[str, str], |
| 405 | config: dict, |
| 406 | count: int = 5, |
| 407 | *, |
| 408 | freshness: Optional[str] = None, |
| 409 | deadline_monotonic: Optional[float] = None, |
| 410 | cancel: Optional[threading.Event] = None, |
| 411 | accept_result: Optional[Callable[[dict], bool]] = None, |
| 412 | ) -> tuple[list[dict], dict]: |
| 413 | """Run keyless web search; returns (items, artifact). Never raises. |
| 414 | |
| 415 | ``deadline_monotonic`` bounds every page fetch, and no further rung starts |
| 416 | once it passes or ``cancel`` is set. |
| 417 | ``accept_result`` filters each rung before deciding whether it served. |
| 418 | |
| 419 | ``freshness`` (``day``/``week``/``month``/``year``) asks each HTML rung for |
| 420 | results from that recent period only. The artifact's ``keyless_rungs`` |
| 421 | names the state each HTML rung reached for this query (``skipped`` for a |
| 422 | rung down earlier in the run). |
| 423 | """ |
| 424 | tried: dict[str, str] = {} |
| 425 | items: list[dict] = [] |
| 426 | used = "ddg" |
| 427 | ladder = (("brave", _brave_rung),) if _is_reddit_query(query) else () |
| 428 | ladder += (("ddg", _ddg_rung), ("startpage", _startpage_rung)) |
| 429 | bound: dict[str, Any] = {} |
| 430 | if deadline_monotonic is not None: |
| 431 | bound["deadline_monotonic"] = deadline_monotonic |
| 432 | if cancel is not None: |
| 433 | bound["cancel"] = cancel |
| 434 | |
| 435 | def stopped() -> bool: |
| 436 | if cancel is not None and cancel.is_set(): |
| 437 | return True |
| 438 | return deadline_monotonic is not None and time.monotonic() >= deadline_monotonic |
| 439 | |
| 440 | searxng_attempted = False |
| 441 | searxng_state: Optional[str] = None |
| 442 | with http.tee_failures() as run_failures: |
| 443 | for rung, search in ladder: |
| 444 | if stopped(): |
| 445 | tried[rung] = SKIPPED |
| 446 | continue |
| 447 | if not RUNG_HEALTH.usable(rung): |
| 448 | tried[rung] = SKIPPED |
| 449 | continue |
| 450 | # A DuckDuckGo anomaly block (202 challenge page on a datacenter IP) |
| 451 | # falls through to Startpage, which still serves organic results there. |
| 452 | items, state = search(query, count, freshness, **bound) |
| 453 | if accept_result is not None and items: |
| 454 | items = [item for item in items if accept_result(item)] |
| 455 | if not items and state == OK: |
| 456 | state = EMPTY |
| 457 | tried[rung] = state |
| 458 | RUNG_HEALTH.record(rung, state) |
| 459 | used = rung |
| 460 | if items: |
| 461 | break |
| 462 | if not items: |
| 463 | searxng_url = (config.get("LAST30DAYS_SEARXNG_URL") or "").strip() |
| 464 | if searxng_url and not stopped(): |
| 465 | searxng_attempted = True |
| 466 | searxng_outcome: dict[str, str] = {} |
| 467 | items = _search_searxng( |
| 468 | query, count, searxng_url, accept_result=accept_result, |
| 469 | outcome=searxng_outcome, **bound, |
| 470 | ) |
| 471 | # Reported on its own key so that ``keyless_rungs`` and the shared rung |
| 472 | # health stay the HTML rungs only. |
| 473 | searxng_state = searxng_outcome.get("state") |
| 474 | used = "searxng" |
| 475 | # These backends never return a publish date, so normalize's grounding |
| 476 | # require_date would drop every result. Keep undated links only when the |
| 477 | # window reaches today; a historical window can't vouch for them. |
| 478 | if date_range[1] >= datetime.now(timezone.utc).date().isoformat(): |
| 479 | for item in items: |
| 480 | item["metadata"] = {"date_window_basis": "keyless_current"} |
| 481 | artifact = { |
| 482 | "label": "keyless", |
| 483 | "webSearchQueries": [query], |
| 484 | "resultCount": len(items), |
| 485 | "keyless_backend": used, |
| 486 | "keyless_rungs": tried, |
| 487 | } |
| 488 | if searxng_state: |
| 489 | artifact["keyless_searxng"] = searxng_state |
| 490 | if not items: |
| 491 | budget_exhausted = stopped() or any( |
| 492 | isinstance(failure, http.DeadlineExceeded) for failure in run_failures |
| 493 | ) |
| 494 | if budget_exhausted: |
| 495 | artifact["reason"] = "keyless-search-timeout" |
| 496 | artifact["_source_outcome"] = { |
| 497 | "state": health.TIMEOUT, |
| 498 | "detail": "Keyless web search cancelled or timed out", |
| 499 | "attempted": searxng_attempted or any(state != SKIPPED for state in tried.values()), |
| 500 | } |
| 501 | else: |
| 502 | artifact["reason"] = "keyless-search-unavailable" |
| 503 | return items, artifact |
| 504 | |
| 505 | |
| 506 | def _fetch_page( |
| 507 | rung: str, |
| 508 | url: str, |
| 509 | deadline_monotonic: Optional[float] = None, |
| 510 | cancel: Optional[threading.Event] = None, |
| 511 | ) -> tuple[Optional[str], str]: |
| 512 | """One rung's results page: ``(text, "")`` or ``(None, failure state)``. |
| 513 | |
| 514 | The transport swallows the status; the failures it records are read back |
| 515 | here and still forwarded to the caller's failure sink. |
| 516 | """ |
| 517 | extra: dict[str, Any] = {} |
| 518 | if cancel is not None: |
| 519 | extra["cancel"] = cancel |
| 520 | with http.tee_failures() as failures: |
| 521 | try: |
| 522 | text = http.get_text( |
| 523 | url, |
| 524 | accept="text/html", |
| 525 | retries=2, |
| 526 | deadline_monotonic=deadline_monotonic, |
| 527 | public_only=True, |
| 528 | redirect_guard=_rung_redirect_guard(url), |
| 529 | max_bytes=_MAX_SERP_BYTES, |
| 530 | decode_errors="replace", |
| 531 | **extra, |
| 532 | ) |
| 533 | except (UnicodeDecodeError, ValueError): |
| 534 | return None, ERROR |
| 535 | if is_challenge_page(rung, text or ""): |
| 536 | return None, THROTTLED |
| 537 | if text: |
| 538 | return text, "" |
| 539 | statuses = [f.status_code for f in failures if f.status_code] |
| 540 | if 403 in statuses: |
| 541 | return None, BLOCKED |
| 542 | if 429 in statuses: |
| 543 | return None, THROTTLED |
| 544 | return None, ERROR if text is None else EMPTY |
| 545 | |
| 546 | |
| 547 | def _freshness_param(freshness: Optional[str], index: int) -> Optional[str]: |
| 548 | values = _FRESHNESS.get((freshness or "").lower()) |
| 549 | return values[index] if values else None |
| 550 | |
| 551 | |
| 552 | |
| 553 | def _brave_url(query: str, freshness: Optional[str] = None) -> str: |
| 554 | params = {"q": query, "source": "web"} |
| 555 | tf = _freshness_param(freshness, 0) |
| 556 | if tf: |
| 557 | params["tf"] = tf |
| 558 | return f"{_BRAVE_HTML_URL}?{urlencode(params)}" |
| 559 | |
| 560 | |
| 561 | def _brave_rung( |
| 562 | query: str, count: int, freshness: Optional[str] = None, |
| 563 | deadline_monotonic: Optional[float] = None, |
| 564 | cancel: Optional[threading.Event] = None, |
| 565 | ) -> tuple[list[dict], str]: |
| 566 | """Rung 0 (Reddit queries): Brave Search's HTML results page, with its state.""" |
| 567 | text, failed = _fetch_page( |
| 568 | "brave", _brave_url(query, freshness), deadline_monotonic, cancel=cancel, |
| 569 | ) |
| 570 | if text is None: |
| 571 | return [], failed |
| 572 | items = parse_brave(text, count) |
| 573 | return items, OK if items else EMPTY |
| 574 | |
| 575 | |
| 576 | def _brave_date(age: str, now: datetime) -> Optional[str]: |
| 577 | """``"2 weeks ago"`` or ``"Nov 3, 2026"`` as YYYY-MM-DD, else None.""" |
| 578 | age = (age or "").strip().rstrip("-").strip() |
| 579 | match = _RELATIVE_AGE_RE.match(age) |
| 580 | if match: |
| 581 | days = int(match.group("n")) * _UNIT_DAYS[match.group("unit").lower()] |
| 582 | return (now - timedelta(days=days)).date().isoformat() |
| 583 | for fmt in _ABSOLUTE_DATE_FORMATS: |
| 584 | try: |
| 585 | return datetime.strptime(age, fmt).date().isoformat() |
| 586 | except ValueError: |
| 587 | continue |
| 588 | return None |
| 589 | |
| 590 | |
| 591 | def _tag_class(tag: str) -> str: |
| 592 | match = _CLASS_ATTR_RE.search(tag) |
| 593 | return match.group("cls") if match else "" |
| 594 | |
| 595 | |
| 596 | def _brave_block_starts(text: str) -> list[int]: |
| 597 | starts: list[int] = [] |
| 598 | for match in _DIV_TAG_RE.finditer(text): |
| 599 | tag = match.group(0) |
| 600 | if not _DATA_TYPE_WEB_RE.search(tag): |
| 601 | continue |
| 602 | cls = _tag_class(tag) |
| 603 | if cls and re.match(r"^snippet\b", cls, re.IGNORECASE): |
| 604 | starts.append(match.start()) |
| 605 | return starts |
| 606 | |
| 607 | |
| 608 | def parse_brave(text: str, count: int, now: Optional[datetime] = None) -> list[dict]: |
| 609 | """Organic results from a Brave Search HTML page, each with its date when shown.""" |
| 610 | now = now or datetime.now(timezone.utc) |
| 611 | text = text or "" |
| 612 | starts = _brave_block_starts(text) |
| 613 | items: list[dict] = [] |
| 614 | seen: set[str] = set() |
| 615 | for idx, start in enumerate(starts): |
| 616 | if len(items) >= count: |
| 617 | break |
| 618 | block = text[start:starts[idx + 1] if idx + 1 < len(starts) else len(text)] |
| 619 | target = "" |
| 620 | for a_match in _A_TAG_RE.finditer(block): |
| 621 | href_match = _HTTP_HREF_ATTR_RE.search(a_match.group(0)) |
| 622 | if href_match: |
| 623 | target = html.unescape(href_match.group("href")) |
| 624 | break |
| 625 | if not target or target in seen: |
| 626 | continue |
| 627 | title = "" |
| 628 | snippet = "" |
| 629 | tried_title = False |
| 630 | tried_snippet = False |
| 631 | div_pos = 0 |
| 632 | while div_pos < len(block) and not (tried_title and tried_snippet): |
| 633 | div_match = _DIV_TAG_RE.search(block, div_pos) |
| 634 | if div_match is None: |
| 635 | break |
| 636 | div_pos = div_match.end() |
| 637 | cls = _tag_class(div_match.group(0)) |
| 638 | if not cls: |
| 639 | continue |
| 640 | cls_lower = cls.lower() |
| 641 | if not tried_title and "search-snippet-title" in cls_lower: |
| 642 | tried_title = True |
| 643 | close = _CLOSE_DIV_RE.search(block, div_match.end()) |
| 644 | if close is None: |
| 645 | break |
| 646 | title = _strip_html(block[div_match.end():close.start()]) |
| 647 | div_pos = close.end() |
| 648 | elif not tried_snippet and _BRAVE_SNIPPET_CLASS_RE.match(cls): |
| 649 | tried_snippet = True |
| 650 | close = _CLOSE_DIV_RE.search(block, div_match.end()) |
| 651 | if close is None: |
| 652 | break |
| 653 | raw_snippet = block[div_match.end():close.start()] |
| 654 | snippet = " ".join(_strip_html( |
| 655 | _BRAVE_AGE_RE.sub("", raw_snippet, count=1) |
| 656 | ).split()) |
| 657 | div_pos = close.end() |
| 658 | if not title: |
| 659 | continue |
| 660 | age = _BRAVE_AGE_RE.search(block) |
| 661 | seen.add(target) |
| 662 | item = _to_item(len(items), title, target, snippet) |
| 663 | item["date"] = _brave_date(age.group("age"), now) if age else None |
| 664 | items.append(item) |
| 665 | return items |
| 666 | |
| 667 | |
| 668 | def _search_ddg(query: str, count: int, freshness: Optional[str] = None) -> list[dict]: |
| 669 | return _ddg_rung(query, count, freshness)[0] |
| 670 | |
| 671 | |
| 672 | def _ddg_url(query: str, freshness: Optional[str] = None) -> str: |
| 673 | params = {"q": query} |
| 674 | df = _freshness_param(freshness, 1) |
| 675 | if df: |
| 676 | params["df"] = df |
| 677 | return f"{_DDG_HTML_URL}?{urlencode(params)}" |
| 678 | |
| 679 | |
| 680 | def _ddg_rung( |
| 681 | query: str, count: int, freshness: Optional[str] = None, |
| 682 | deadline_monotonic: Optional[float] = None, |
| 683 | cancel: Optional[threading.Event] = None, |
| 684 | ) -> tuple[list[dict], str]: |
| 685 | text, failed = _fetch_page( |
| 686 | "ddg", _ddg_url(query, freshness), deadline_monotonic, cancel=cancel, |
| 687 | ) |
| 688 | if text is None: |
| 689 | return [], failed |
| 690 | items = parse_ddg(text, count) |
| 691 | return items, OK if items else EMPTY |
| 692 | |
| 693 | |
| 694 | def parse_ddg(text: str, count: int) -> list[dict]: |
| 695 | """Organic results from a DuckDuckGo HTML results page.""" |
| 696 | text = text or "" |
| 697 | items: list[dict] = [] |
| 698 | # Associate each result's snippet by position, not by a parallel index: |
| 699 | # some result anchors (video/news modules) have no snippet, so a global |
| 700 | # zip would shift every later snippet onto the wrong result. Take the first |
| 701 | # snippet that falls between this anchor and the next one. |
| 702 | anchors: list[tuple[int, int, str, str]] = [] |
| 703 | pos = 0 |
| 704 | while pos < len(text): |
| 705 | match = _A_TAG_RE.search(text, pos) |
| 706 | if match is None: |
| 707 | break |
| 708 | pos = match.end() |
| 709 | tag = match.group(0) |
| 710 | if "result__a" not in tag.lower(): |
| 711 | continue |
| 712 | cls = _tag_class(tag) |
| 713 | if "result__a" not in cls.lower().split(): |
| 714 | continue |
| 715 | href_match = _HREF_ATTR_RE.search(tag) |
| 716 | if not href_match: |
| 717 | continue |
| 718 | close = _CLOSE_A_RE.search(text, match.end()) |
| 719 | if close is None: |
| 720 | break |
| 721 | anchors.append((match.start(), close.end(), href_match.group("href"), text[match.end():close.start()])) |
| 722 | pos = close.end() |
| 723 | for idx, (_start, end, raw_href, raw_title) in enumerate(anchors): |
| 724 | if len(items) >= count: |
| 725 | break |
| 726 | target = _unwrap_ddg_redirect(raw_href) |
| 727 | if not target.startswith("http"): |
| 728 | continue |
| 729 | next_start = anchors[idx + 1][0] if idx + 1 < len(anchors) else len(text) |
| 730 | snippet = "" |
| 731 | for s_match in _A_TAG_RE.finditer(text, end, next_start): |
| 732 | s_tag = s_match.group(0) |
| 733 | if "result__snippet" not in s_tag.lower(): |
| 734 | continue |
| 735 | s_cls = _tag_class(s_tag) |
| 736 | if "result__snippet" not in s_cls.lower().split(): |
| 737 | continue |
| 738 | s_close = _CLOSE_A_RE.search(text, s_match.end(), next_start) |
| 739 | if s_close is not None: |
| 740 | snippet = _strip_html(text[s_match.end():s_close.start()]) |
| 741 | break |
| 742 | title = _strip_html(raw_title) |
| 743 | items.append(_to_item(len(items), title, target, snippet)) |
| 744 | return items |
| 745 | |
| 746 | |
| 747 | def _search_startpage(query: str, count: int, freshness: Optional[str] = None) -> list[dict]: |
| 748 | return _startpage_rung(query, count, freshness)[0] |
| 749 | |
| 750 | |
| 751 | def _startpage_rung( |
| 752 | query: str, count: int, freshness: Optional[str] = None, |
| 753 | deadline_monotonic: Optional[float] = None, |
| 754 | cancel: Optional[threading.Event] = None, |
| 755 | ) -> tuple[list[dict], str]: |
| 756 | """Keyless rung 2: Startpage's HTML results page. Unlike DuckDuckGo's HTML |
| 757 | endpoint (which anomaly-blocks datacenter IPs with a 202 challenge page), |
| 758 | Startpage returns organic results to a plain browser-UA GET, making it the |
| 759 | working floor on hosts DuckDuckGo refuses. Never raises.""" |
| 760 | text, failed = _fetch_page( |
| 761 | "startpage", _startpage_url(query, freshness), deadline_monotonic, cancel=cancel, |
| 762 | ) |
| 763 | if text is None: |
| 764 | return [], failed |
| 765 | items = parse_startpage(text, count) |
| 766 | return items, OK if items else EMPTY |
| 767 | |
| 768 | |
| 769 | def _startpage_url(query: str, freshness: Optional[str] = None) -> str: |
| 770 | params = {"query": query} |
| 771 | with_date = _freshness_param(freshness, 2) |
| 772 | if with_date: |
| 773 | params["with_date"] = with_date |
| 774 | return f"{_STARTPAGE_HTML_URL}?{urlencode(params)}" |
| 775 | |
| 776 | |
| 777 | def parse_startpage(text: str, count: int) -> list[dict]: |
| 778 | """Organic results from a Startpage HTML results page.""" |
| 779 | text = text or "" |
| 780 | items: list[dict] = [] |
| 781 | results: list[tuple[int, int, str, str]] = [] |
| 782 | pos = 0 |
| 783 | while pos < len(text): |
| 784 | match = _A_TAG_RE.search(text, pos) |
| 785 | if match is None: |
| 786 | break |
| 787 | pos = match.end() |
| 788 | tag = match.group(0) |
| 789 | if "result-title" not in tag.lower(): |
| 790 | continue |
| 791 | cls = _tag_class(tag) |
| 792 | if "result-title" not in cls.lower(): |
| 793 | continue |
| 794 | href_match = _HTTP_HREF_ATTR_RE.search(tag) |
| 795 | if not href_match: |
| 796 | continue |
| 797 | close = _CLOSE_A_RE.search(text, match.end()) |
| 798 | if close is None: |
| 799 | break |
| 800 | results.append((match.start(), close.end(), href_match.group("href"), text[match.end():close.start()])) |
| 801 | pos = close.end() |
| 802 | for idx, (_start, end, raw_href, inner) in enumerate(results): |
| 803 | if len(items) >= count: |
| 804 | break |
| 805 | target = html.unescape(raw_href) |
| 806 | if not target.startswith("http"): |
| 807 | continue |
| 808 | h2_open = _H2_TAG_RE.search(inner) |
| 809 | if h2_open is not None: |
| 810 | h2_close = _CLOSE_H2_RE.search(inner, h2_open.end()) |
| 811 | raw_title = inner[h2_open.end():h2_close.start()] if h2_close is not None else inner |
| 812 | else: |
| 813 | raw_title = inner |
| 814 | title = _strip_html(raw_title) |
| 815 | if not title: |
| 816 | continue |
| 817 | next_start = results[idx + 1][0] if idx + 1 < len(results) else len(text) |
| 818 | snippet = "" |
| 819 | for p_match in _P_TAG_RE.finditer(text, end, next_start): |
| 820 | p_tag = p_match.group(0) |
| 821 | if "description" not in p_tag.lower(): |
| 822 | continue |
| 823 | p_cls = _tag_class(p_tag) |
| 824 | if "description" not in p_cls.lower(): |
| 825 | continue |
| 826 | p_close = _CLOSE_P_RE.search(text, p_match.end(), next_start) |
| 827 | if p_close is not None: |
| 828 | snippet = _strip_html(text[p_match.end():p_close.start()]) |
| 829 | break |
| 830 | items.append(_to_item(len(items), title, target, snippet)) |
| 831 | return items |
| 832 | |
| 833 | |
| 834 | def rung_url(rung: str, query: str, freshness: Optional[str] = None) -> str: |
| 835 | """The results-page address one HTML rung asks for ``query``.""" |
| 836 | return {"brave": _brave_url, "ddg": _ddg_url, "startpage": _startpage_url}[rung](query, freshness) |
| 837 | |
| 838 | |
| 839 | def parse_rung(rung: str, text: str, count: int) -> list[dict]: |
| 840 | """One HTML rung's parser applied to a results page it served.""" |
| 841 | if rung == "brave": |
| 842 | return parse_brave(text, count) |
| 843 | return {"ddg": parse_ddg, "startpage": parse_startpage}[rung](text, count) |
| 844 | |
| 845 | |
| 846 | def is_challenge_page(rung: str, text: str) -> bool: |
| 847 | """Whether ``text`` is a known challenge/anomaly page for ``rung``.""" |
| 848 | return bool(text) and any(marker in text for marker in _CHALLENGE_MARKERS.get(rung, ())) |
| 849 | |
| 850 | |
| 851 | def _searxng_failure_state(exc: http.HTTPError) -> str: |
| 852 | """The rung state for a failed SearXNG request (a refusal, a throttle, a timeout or other). |
| 853 | |
| 854 | A refusal status wins. Any other error the transport normalized to a timeout counts as one, |
| 855 | including the shared deadline. Only the shared deadline ends a run, which is decided elsewhere. |
| 856 | """ |
| 857 | if exc.status_code == 403: |
| 858 | return BLOCKED |
| 859 | if exc.status_code == 429: |
| 860 | return THROTTLED |
| 861 | if exc.outcome_state == health.TIMEOUT: |
| 862 | return health.TIMEOUT |
| 863 | return ERROR |
| 864 | |
| 865 | |
| 866 | def _search_searxng( |
| 867 | query: str, count: int, instance_url: str, time_range: str | None = None, |
| 868 | deadline_monotonic: float | None = None, |
| 869 | cancel: Optional[threading.Event] = None, |
| 870 | accept_result: Optional[Callable[[dict], bool]] = None, |
| 871 | outcome: Optional[dict[str, str]] = None, |
| 872 | ) -> list[dict]: |
| 873 | """SearXNG results, up to ``count`` that ``accept_result`` keeps. |
| 874 | |
| 875 | The filter runs before the count, over at most ``_MAX_SEARXNG_SCANNED`` rows. |
| 876 | ``outcome``, when given, receives ``state``: ok, empty, blocked (403), |
| 877 | throttled (429), timeout or error. The URL and response text stay out of it. |
| 878 | """ |
| 879 | def record(state: str) -> None: |
| 880 | if outcome is not None: |
| 881 | outcome["state"] = state |
| 882 | |
| 883 | validated = _validate_searxng_url(instance_url) |
| 884 | if validated is None: |
| 885 | log.source_log( |
| 886 | "Web", |
| 887 | "Ignoring invalid or blocked LAST30DAYS_SEARXNG_URL", |
| 888 | tty_only=False, |
| 889 | ) |
| 890 | return [] |
| 891 | base, origin = validated |
| 892 | params = {'q': query, 'format': 'json'} |
| 893 | if time_range: |
| 894 | params['time_range'] = time_range |
| 895 | url = f"{base}/search?{urlencode(params)}" |
| 896 | extra: dict[str, Any] = {} |
| 897 | if cancel is not None: |
| 898 | extra["cancel"] = cancel |
| 899 | try: |
| 900 | data = http.get( |
| 901 | url, |
| 902 | headers={"Accept": "application/json"}, |
| 903 | timeout=15, |
| 904 | retries=2, |
| 905 | deadline_monotonic=deadline_monotonic, |
| 906 | redirect_guard=_searxng_redirect_guard(origin), |
| 907 | ip_validator=_is_allowed_searxng_ip, |
| 908 | max_bytes=_MAX_SEARXNG_BYTES, |
| 909 | decode_errors="replace", |
| 910 | **extra, |
| 911 | ) |
| 912 | except http.HTTPError as exc: |
| 913 | record(_searxng_failure_state(exc)) |
| 914 | return [] |
| 915 | except (UnicodeDecodeError, ValueError): |
| 916 | record(ERROR) |
| 917 | return [] |
| 918 | if not isinstance(data, dict): |
| 919 | record(ERROR) |
| 920 | return [] |
| 921 | raw_results = data.get("results") |
| 922 | if not isinstance(raw_results, list): |
| 923 | record(ERROR) |
| 924 | return [] |
| 925 | if accept_result is not None: |
| 926 | raw_results = raw_results[:_MAX_SEARXNG_SCANNED] |
| 927 | items: list[dict] = [] |
| 928 | for i, r in enumerate(raw_results): |
| 929 | if len(items) >= count: |
| 930 | break |
| 931 | if not isinstance(r, dict): |
| 932 | continue |
| 933 | target = r.get("url") |
| 934 | if not isinstance(target, str) or not target.startswith(("http://", "https://")): |
| 935 | continue |
| 936 | title = r.get("title") |
| 937 | content = r.get("content") |
| 938 | item = _to_item( |
| 939 | i, |
| 940 | title if isinstance(title, str) else str(title or ""), |
| 941 | target, |
| 942 | content if isinstance(content, str) else str(content or ""), |
| 943 | ) |
| 944 | if accept_result is not None and not accept_result(item): |
| 945 | continue |
| 946 | items.append(item) |
| 947 | record(OK if items else EMPTY) |
| 948 | return items |
| 949 | |
| 950 | |
| 951 | def _to_item(index: int, title: str, url: str, snippet: str) -> dict: |
| 952 | return { |
| 953 | "id": f"WK{index + 1}", |
| 954 | "title": title, |
| 955 | "url": url, |
| 956 | "source_domain": _domain(url), |
| 957 | "snippet": (snippet or "")[:500], |
| 958 | "date": None, |
| 959 | "relevance": _KEYLESS_RELEVANCE, |
| 960 | "why_relevant": "Keyless web search", |
| 961 | } |
| 962 |