| 1 | """Weighted reciprocal rank fusion for per-(subquery, source) streams.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import copy |
| 6 | import dataclasses |
| 7 | import math |
| 8 | import re |
| 9 | from collections.abc import Iterable |
| 10 | from datetime import date, datetime, timezone |
| 11 | |
| 12 | from urllib.parse import parse_qs, urlencode, urlparse, urlunparse |
| 13 | |
| 14 | from . import entity_extract, reddit_refs, schema |
| 15 | |
| 16 | # Standard RRF smoothing constant (Cormack et al. 2009) |
| 17 | RRF_K = 60 |
| 18 | |
| 19 | |
| 20 | def _candidate_sort_key(c: schema.Candidate) -> tuple: |
| 21 | # Out-of-window evidence sorts strictly below anything in the window. A |
| 22 | # "last 30 days" brief that ranks a nine-month-old video at #1 breaks its |
| 23 | # own contract, however relevant that video is; it still appears, just |
| 24 | # never above in-window evidence. |
| 25 | return ( |
| 26 | 1 if schema.candidate_out_of_window(c) else 0, |
| 27 | -c.rrf_score, |
| 28 | -c.local_relevance, |
| 29 | -c.freshness, |
| 30 | schema.candidate_source_label(c), |
| 31 | c.title, |
| 32 | ) |
| 33 | |
| 34 | |
| 35 | def _normalize_url(url: str) -> str: |
| 36 | """Normalize URL for dedup: lowercase scheme/host, strip www/old/m prefixes, |
| 37 | drop fragments and utm_* params, and sort remaining query parameters.""" |
| 38 | cleaned = url.strip() |
| 39 | try: |
| 40 | parsed = urlparse(cleaned) |
| 41 | except ValueError: |
| 42 | return cleaned |
| 43 | netloc = parsed.netloc.lower() |
| 44 | changed = True |
| 45 | while changed: |
| 46 | changed = False |
| 47 | for prefix in ("www.", "old.", "m."): |
| 48 | if netloc.startswith(prefix): |
| 49 | netloc = netloc[len(prefix):] |
| 50 | changed = True |
| 51 | # Strip tracking params and canonicalize parameter name order while |
| 52 | # preserving value order for repeated parameter names. |
| 53 | params = parse_qs(parsed.query, keep_blank_values=True) |
| 54 | clean_params = sorted( |
| 55 | ( |
| 56 | (k, v) |
| 57 | for k, v in params.items() |
| 58 | if not k.lower().startswith("utm_") |
| 59 | ), |
| 60 | key=lambda kv: kv[0], |
| 61 | ) |
| 62 | query = urlencode(clean_params, doseq=True) |
| 63 | return urlunparse((parsed.scheme.lower(), netloc, parsed.path.rstrip("/"), "", query, "")) |
| 64 | |
| 65 | |
| 66 | def candidate_key( |
| 67 | item: schema.SourceItem, |
| 68 | *, |
| 69 | polymarket_eids_by_url: dict[str, set[str]] | None = None, |
| 70 | ) -> str: |
| 71 | if item.url: |
| 72 | if item.source == "polymarket" and polymarket_eids_by_url: |
| 73 | poly_key = polymarket_url_key(item, polymarket_eids_by_url) |
| 74 | if poly_key is not None: |
| 75 | return poly_key |
| 76 | # Every URL form of one Reddit thread (old., redd.it, a comment |
| 77 | # permalink) is one candidate, keyed by the thread id. |
| 78 | return reddit_refs.thread_key(item.url) or _normalize_url(item.url) |
| 79 | return f"{item.source}:{item.item_id}" |
| 80 | |
| 81 | |
| 82 | def source_item_key( |
| 83 | item: schema.SourceItem, |
| 84 | *, |
| 85 | polymarket_eids_by_url: dict[str, set[str]] | None = None, |
| 86 | ) -> tuple[str, str]: |
| 87 | """Identity of one source item, for same-source de-duplication. |
| 88 | |
| 89 | Usually the normalized URL (see :func:`candidate_key`). A Hacker News |
| 90 | item's ``url`` is the linked article, and one article can be submitted |
| 91 | several times as distinct stories with their own points and comments, so |
| 92 | HN identity is the discussion URL. ``candidate_key`` still clusters those |
| 93 | submissions (and other sources linking the article) into one candidate. |
| 94 | """ |
| 95 | if item.source == "hackernews": |
| 96 | hn_url = item.metadata.get("hn_url") |
| 97 | if hn_url: |
| 98 | return (item.source, _normalize_url(str(hn_url))) |
| 99 | return (item.source, candidate_key(item, polymarket_eids_by_url=polymarket_eids_by_url)) |
| 100 | |
| 101 | |
| 102 | # Enrichment that one copy of a thread may carry and another may lack. When |
| 103 | # the same URL arrives from two subquery streams (each stream enriches its own |
| 104 | # top-N), the copy that won a comment slot must survive de-duplication. |
| 105 | _ENRICHMENT_KEYS = ( |
| 106 | "top_comments", |
| 107 | "comment_insights", |
| 108 | "transcript_highlights", |
| 109 | "transcript_snippet", |
| 110 | "transcript", |
| 111 | ) |
| 112 | |
| 113 | |
| 114 | def _clone_source_item(item: schema.SourceItem) -> schema.SourceItem: |
| 115 | """Shallow-copy a SourceItem and its mutable engagement/metadata containers.""" |
| 116 | metadata = { |
| 117 | k: ( |
| 118 | [dict(e) if isinstance(e, dict) else e for e in v] |
| 119 | if isinstance(v, list) |
| 120 | else dict(v) |
| 121 | if isinstance(v, dict) |
| 122 | else v |
| 123 | ) |
| 124 | for k, v in (item.metadata or {}).items() |
| 125 | } |
| 126 | return dataclasses.replace( |
| 127 | item, |
| 128 | engagement=dict(item.engagement or {}), |
| 129 | metadata=metadata, |
| 130 | ) |
| 131 | |
| 132 | |
| 133 | def _item_engagement_score(item: schema.SourceItem) -> int | float | None: |
| 134 | if item.engagement_score is not None: |
| 135 | return item.engagement_score |
| 136 | return (item.metadata or {}).get("engagement_score") |
| 137 | |
| 138 | |
| 139 | def _candidate_engagement_from_items(source_items: list[schema.SourceItem]) -> int | float | None: |
| 140 | scores = [ |
| 141 | val |
| 142 | for si in source_items |
| 143 | if (val := _item_engagement_score(si)) is not None |
| 144 | ] |
| 145 | return max(scores) if scores else None |
| 146 | |
| 147 | |
| 148 | def _primary_score(local_relevance: float, freshness: int, source_quality: float) -> float: |
| 149 | return (local_relevance * 100.0) + freshness + (source_quality * 10.0) |
| 150 | |
| 151 | |
| 152 | def _parse_iso_day(value: str | None) -> str | None: |
| 153 | text = str(value or "").strip() |
| 154 | if not text: |
| 155 | return None |
| 156 | try: |
| 157 | if len(text) == 10: |
| 158 | return date.fromisoformat(text).isoformat() |
| 159 | dt = datetime.fromisoformat(text.replace("Z", "+00:00")) |
| 160 | return (dt.astimezone(timezone.utc) if dt.tzinfo else dt).date().isoformat() |
| 161 | except ValueError: |
| 162 | return None |
| 163 | |
| 164 | |
| 165 | def _matched_date_in_window( |
| 166 | date_str: str, |
| 167 | range_from: str | None, |
| 168 | range_to: str | None, |
| 169 | ) -> bool: |
| 170 | text = str(date_str or "").strip() |
| 171 | if not text: |
| 172 | return False |
| 173 | if not range_from and not range_to: |
| 174 | return True |
| 175 | iso = _parse_iso_day(text) |
| 176 | if not iso: |
| 177 | return False |
| 178 | start = _parse_iso_day(range_from) if range_from else None |
| 179 | end = _parse_iso_day(range_to) if range_to else None |
| 180 | if start and iso < start: |
| 181 | return False |
| 182 | if end and iso > end: |
| 183 | return False |
| 184 | return True |
| 185 | |
| 186 | |
| 187 | def _sanitize_reddit_matched_comment( |
| 188 | item: schema.SourceItem, |
| 189 | range_from: str | None, |
| 190 | range_to: str | None, |
| 191 | ) -> None: |
| 192 | if item.source != "reddit" or not isinstance(item.metadata, dict): |
| 193 | return |
| 194 | if not range_from and not range_to: |
| 195 | return |
| 196 | matched_date = str(item.metadata.get("matched_comment_date") or "").strip() |
| 197 | if matched_date and not _matched_date_in_window(matched_date, range_from, range_to): |
| 198 | item.metadata.pop("matched_comment_date", None) |
| 199 | item.metadata.pop("matched_comment_url", None) |
| 200 | |
| 201 | |
| 202 | # Polymarket display and ranking fields that belong to a matched-market verdict |
| 203 | # and must move together so a merged item never mixes one market's price with |
| 204 | # another market's question/odds/close date or loses its selection ranking. |
| 205 | _POLYMARKET_MATCH_BUNDLE_KEYS = ( |
| 206 | "matched_market", |
| 207 | "odds", |
| 208 | "headline", |
| 209 | "end_date", |
| 210 | "question", |
| 211 | "outcome_prices", |
| 212 | "outcome_questions", |
| 213 | "outcome_market_ids", |
| 214 | "outcomes_remaining", |
| 215 | "price_movement", |
| 216 | "selection_score", |
| 217 | "selection_tier", |
| 218 | ) |
| 219 | |
| 220 | |
| 221 | def _polymarket_event_id(item: schema.SourceItem) -> str: |
| 222 | if item.source != "polymarket": |
| 223 | return "" |
| 224 | return str((item.metadata or {}).get("event_id") or "").strip() |
| 225 | |
| 226 | |
| 227 | def _polymarket_event_ids_conflict( |
| 228 | a: schema.SourceItem, |
| 229 | b: schema.SourceItem, |
| 230 | ) -> bool: |
| 231 | """True when two Polymarket items carry distinct known Gamma event IDs.""" |
| 232 | id_a = _polymarket_event_id(a) |
| 233 | id_b = _polymarket_event_id(b) |
| 234 | return bool(id_a and id_b and id_a != id_b) |
| 235 | |
| 236 | |
| 237 | def polymarket_event_ids_by_url( |
| 238 | items: Iterable[schema.SourceItem], |
| 239 | ) -> dict[str, set[str]]: |
| 240 | """Map each normalized Polymarket URL to all distinct non-empty event IDs seen.""" |
| 241 | by_url: dict[str, set[str]] = {} |
| 242 | for item in items: |
| 243 | if item.source != "polymarket": |
| 244 | continue |
| 245 | url = (item.url or "").strip() |
| 246 | if not url: |
| 247 | continue |
| 248 | eid = _polymarket_event_id(item) |
| 249 | if eid: |
| 250 | by_url.setdefault(_normalize_url(url), set()).add(eid) |
| 251 | return by_url |
| 252 | |
| 253 | |
| 254 | def polymarket_url_key( |
| 255 | item: schema.SourceItem, |
| 256 | eids_by_url: dict[str, set[str]] | None = None, |
| 257 | ) -> str | None: |
| 258 | """Collision-safe URL key for a Polymarket item, or None if not Polymarket/URL-less. |
| 259 | |
| 260 | When multiple distinct ``event_id`` values share one reused slug URL: |
| 261 | - items with a known ``event_id`` key under ``"{norm_url}\\x1fevent={eid}"`` |
| 262 | - ID-less items key under ``"{norm_url}\\x1fidless"`` so they never merge |
| 263 | with or bridge conflicting events. |
| 264 | When zero or one ``event_id`` exists at ``norm_url``, every copy shares |
| 265 | ``norm_url`` so ID-less copies merge cleanly and inherit the sole ``event_id``. |
| 266 | """ |
| 267 | if item.source != "polymarket": |
| 268 | return None |
| 269 | url = (item.url or "").strip() |
| 270 | if not url: |
| 271 | return None |
| 272 | norm = _normalize_url(url) |
| 273 | eids = (eids_by_url or {}).get(norm) |
| 274 | if eids and len(eids) > 1: |
| 275 | eid = _polymarket_event_id(item) |
| 276 | return f"{norm}\x1fevent={eid}" if eid else f"{norm}\x1fidless" |
| 277 | return norm |
| 278 | |
| 279 | |
| 280 | def _merge_polymarket_match_bundle( |
| 281 | existing: schema.SourceItem, |
| 282 | incoming: schema.SourceItem, |
| 283 | ) -> bool: |
| 284 | """Keep Polymarket's display and ranking fields coherent across copies. |
| 285 | |
| 286 | Returns True for any non-conflicting Polymarket pair so the caller keeps |
| 287 | the winning copy's ``body`` and ``snippet`` (including an empty |
| 288 | ``price_movement`` snippet when a fresh fetch reported no move) paired |
| 289 | with its own odds, headline, and close date. |
| 290 | """ |
| 291 | if existing.source != "polymarket" or incoming.source != "polymarket": |
| 292 | return False |
| 293 | if _polymarket_event_ids_conflict(existing, incoming): |
| 294 | return False |
| 295 | in_meta = incoming.metadata or {} |
| 296 | mine_matched = bool(existing.metadata.get("matched_market")) |
| 297 | theirs_matched = bool(in_meta.get("matched_market")) |
| 298 | if not mine_matched and theirs_matched: |
| 299 | for key in _POLYMARKET_MATCH_BUNDLE_KEYS: |
| 300 | if key in in_meta and in_meta[key] is not None: |
| 301 | existing.metadata[key] = copy.deepcopy(in_meta[key]) |
| 302 | else: |
| 303 | existing.metadata.pop(key, None) |
| 304 | if in_meta.get("event_id") and not existing.metadata.get("event_id"): |
| 305 | existing.metadata["event_id"] = in_meta["event_id"] |
| 306 | if incoming.title: |
| 307 | existing.title = incoming.title |
| 308 | if incoming.body: |
| 309 | existing.body = incoming.body |
| 310 | existing.snippet = incoming.snippet |
| 311 | return True |
| 312 | |
| 313 | |
| 314 | def _keep_github_repo_snapshot(existing: schema.SourceItem, incoming: schema.SourceItem) -> schema.SourceItem | None: |
| 315 | """Keep one inventory reading and return the other copy for independent enrichment.""" |
| 316 | if existing.source != "github" or incoming.source != "github": |
| 317 | return None |
| 318 | mine = schema.GITHUB_REPO_COUNTERS.intersection(existing.engagement or {}) |
| 319 | theirs = schema.GITHUB_REPO_COUNTERS.intersection(incoming.engagement or {}) |
| 320 | if not mine and not theirs: |
| 321 | return None |
| 322 | |
| 323 | if not mine or not theirs: |
| 324 | # A failed enrichment on another repo card cannot replace a reading. |
| 325 | unmeasured = incoming if mine else existing |
| 326 | if not schema.github_repo_counter_fields(unmeasured): |
| 327 | return None |
| 328 | prefer_incoming = bool(theirs) |
| 329 | else: |
| 330 | before = schema.github_repo_count_time(existing) |
| 331 | after = schema.github_repo_count_time(incoming) |
| 332 | if before == after: |
| 333 | prefer_incoming = len(theirs) > len(mine) |
| 334 | else: |
| 335 | prefer_incoming = after is not None and (before is None or after > before) |
| 336 | if not prefer_incoming: |
| 337 | return incoming |
| 338 | |
| 339 | # Keep the attachment identity used by the stream. The prose, release/event |
| 340 | # date and inventory belong to the selected card, including an observed zero. |
| 341 | previous = _clone_source_item(existing) |
| 342 | existing.title = incoming.title |
| 343 | existing.body = incoming.body |
| 344 | existing.snippet = incoming.snippet |
| 345 | existing.author = incoming.author |
| 346 | existing.container = incoming.container |
| 347 | existing.published_at = incoming.published_at |
| 348 | existing.date_confidence = incoming.date_confidence |
| 349 | existing.why_relevant = incoming.why_relevant |
| 350 | existing.metadata = copy.deepcopy(incoming.metadata or {}) |
| 351 | existing.engagement = dict(incoming.engagement or {}) |
| 352 | return previous |
| 353 | |
| 354 | |
| 355 | def merge_source_items( |
| 356 | existing: schema.SourceItem, |
| 357 | incoming: schema.SourceItem, |
| 358 | *, |
| 359 | range_from: str | None = None, |
| 360 | range_to: str | None = None, |
| 361 | ) -> schema.SourceItem: |
| 362 | """Fold ``incoming``'s enrichment and counts into ``existing`` (same thread). |
| 363 | |
| 364 | Keeps the richer value per field: an enrichment list the existing copy |
| 365 | lacks (or a longer one), a longer enrichment string, the larger numeric |
| 366 | engagement counters, and the longer body/snippet. Reddit copies merge per |
| 367 | field by provenance: the score from the most trusted source wins (a live |
| 368 | score beats an archive snapshot, which beats a pending one) and comments |
| 369 | are unioned by comment id. Recomputes ``existing.engagement_score`` when |
| 370 | engagement or top comments change. Mutates and returns ``existing``. |
| 371 | """ |
| 372 | if existing.engagement is None: |
| 373 | existing.engagement = {} |
| 374 | if existing.metadata is None: |
| 375 | existing.metadata = {} |
| 376 | if _polymarket_event_ids_conflict(existing, incoming): |
| 377 | return existing |
| 378 | eng_before = dict(existing.engagement) |
| 379 | eng_src_before = existing.metadata.get("engagement_source") |
| 380 | comments_before = existing.metadata.get("top_comments") |
| 381 | |
| 382 | other_repo_snapshot = _keep_github_repo_snapshot(existing, incoming) |
| 383 | if other_repo_snapshot is not None: |
| 384 | incoming = other_repo_snapshot |
| 385 | |
| 386 | reddit = existing.source == "reddit" and incoming.source == "reddit" |
| 387 | if reddit: |
| 388 | _merge_reddit_fields( |
| 389 | existing, incoming, range_from=range_from, range_to=range_to, |
| 390 | ) |
| 391 | polymarket_match_preserved = _merge_polymarket_match_bundle(existing, incoming) |
| 392 | in_meta = incoming.metadata or {} |
| 393 | if existing.source == "polymarket" and incoming.source == "polymarket": |
| 394 | incoming_eid = _polymarket_event_id(incoming) |
| 395 | if incoming_eid and not _polymarket_event_id(existing): |
| 396 | existing.metadata["event_id"] = incoming_eid |
| 397 | for meta_key in ("enriched_via", "reddit_subreddit"): |
| 398 | val = in_meta.get(meta_key) |
| 399 | if val and not existing.metadata.get(meta_key): |
| 400 | existing.metadata[meta_key] = val |
| 401 | theirs_rts = in_meta.get("reddit_thread_score") |
| 402 | if ( |
| 403 | isinstance(theirs_rts, (int, float)) |
| 404 | and not isinstance(theirs_rts, bool) |
| 405 | and math.isfinite(theirs_rts) |
| 406 | ): |
| 407 | mine_rts = existing.metadata.get("reddit_thread_score") |
| 408 | if ( |
| 409 | not isinstance(mine_rts, (int, float)) |
| 410 | or isinstance(mine_rts, bool) |
| 411 | or not math.isfinite(mine_rts) |
| 412 | or theirs_rts > mine_rts |
| 413 | ): |
| 414 | existing.metadata["reddit_thread_score"] = theirs_rts |
| 415 | for key in _ENRICHMENT_KEYS: |
| 416 | if reddit and key == "top_comments": |
| 417 | continue |
| 418 | theirs = incoming.metadata.get(key) |
| 419 | if not theirs or (isinstance(theirs, str) and not theirs.strip()): |
| 420 | continue |
| 421 | mine = existing.metadata.get(key) |
| 422 | mine_empty = not mine or (isinstance(mine, str) and not mine.strip()) |
| 423 | if ( |
| 424 | mine_empty |
| 425 | or (isinstance(theirs, list) and isinstance(mine, list) and len(theirs) > len(mine)) |
| 426 | or (isinstance(theirs, str) and isinstance(mine, str) and len(theirs.strip()) > len(mine.strip())) |
| 427 | ): |
| 428 | existing.metadata[key] = ( |
| 429 | [dict(e) if isinstance(e, dict) else e for e in theirs] |
| 430 | if isinstance(theirs, list) |
| 431 | else theirs |
| 432 | ) |
| 433 | for field_name, value in (incoming.engagement or {}).items(): |
| 434 | if other_repo_snapshot is not None and field_name in schema.GITHUB_REPO_COUNTERS: |
| 435 | continue |
| 436 | if reddit and field_name == "score": |
| 437 | continue |
| 438 | if isinstance(value, bool) or not isinstance(value, (int, float)): |
| 439 | if existing.engagement.get(field_name) is None and value is not None: |
| 440 | existing.engagement[field_name] = value |
| 441 | continue |
| 442 | current = existing.engagement.get(field_name) |
| 443 | if not isinstance(current, (int, float)) or isinstance(current, bool) or value > current: |
| 444 | existing.engagement[field_name] = value |
| 445 | if ( |
| 446 | existing.engagement != eng_before |
| 447 | or existing.metadata.get("engagement_source") != eng_src_before |
| 448 | or existing.metadata.get("top_comments") != comments_before |
| 449 | ): |
| 450 | from . import signals |
| 451 | |
| 452 | existing.engagement_score = signals.engagement_score(existing) |
| 453 | if not polymarket_match_preserved and other_repo_snapshot is None: |
| 454 | if len(incoming.body or "") > len(existing.body or ""): |
| 455 | existing.body = incoming.body |
| 456 | # A reel or TikTok fetched twice can come back once with its spoken |
| 457 | # transcript and once with only its written description. `spoken_caption` |
| 458 | # says which one the snippet is, so the two move together: the transcript |
| 459 | # wins whatever its length, and a longer written description never takes |
| 460 | # its place. |
| 461 | theirs_spoken = bool(incoming.metadata.get("spoken_caption")) |
| 462 | mine_spoken = bool(existing.metadata.get("spoken_caption")) |
| 463 | if theirs_spoken != mine_spoken: |
| 464 | if theirs_spoken and (incoming.snippet or "").strip(): |
| 465 | existing.snippet = incoming.snippet |
| 466 | existing.metadata["spoken_caption"] = True |
| 467 | elif len(incoming.snippet or "") > len(existing.snippet or ""): |
| 468 | existing.snippet = incoming.snippet |
| 469 | return existing |
| 470 | |
| 471 | |
| 472 | def _reddit_score_key(score: object, source: str | None) -> tuple[int, float]: |
| 473 | """Order-independent rank for a Reddit copy's ``(score, engagement_source)``. |
| 474 | |
| 475 | Higher wins regardless of merge order: |
| 476 | 3 — measured live score (explicit ``LIVE`` with any finite number, |
| 477 | including measured ``0``; or unlabeled copy with a non-zero number) |
| 478 | 2 — measured archive score (``ARCTIC`` with any finite number) |
| 479 | 1 — explicitly withheld fresh archive score (``ARCTIC_PENDING``) |
| 480 | 0 — unmeasured / ``UNKNOWN`` / placeholder ``0`` or ``None`` |
| 481 | """ |
| 482 | numeric = ( |
| 483 | isinstance(score, (int, float)) |
| 484 | and not isinstance(score, bool) |
| 485 | and math.isfinite(score) |
| 486 | ) |
| 487 | if source == reddit_refs.ARCTIC_PENDING: |
| 488 | return (1, 0.0) |
| 489 | if source == reddit_refs.UNKNOWN: |
| 490 | return (0, 0.0) |
| 491 | if source == reddit_refs.ARCTIC: |
| 492 | return (2, float(score)) if numeric else (0, 0.0) |
| 493 | if source == reddit_refs.LIVE: |
| 494 | return (3, float(score)) if numeric else (0, 0.0) |
| 495 | if not source: |
| 496 | # Unlabeled copy: a non-zero number is treated as live (matching |
| 497 | # reddit_hydrate._effective_score_rank); placeholder 0 or None is unmeasured. |
| 498 | return (3, float(score)) if (numeric and score != 0) else (0, 0.0) |
| 499 | return (reddit_refs.score_rank(source), float(score)) if numeric else (0, 0.0) |
| 500 | |
| 501 | |
| 502 | def _merge_reddit_fields( |
| 503 | existing: schema.SourceItem, |
| 504 | incoming: schema.SourceItem, |
| 505 | *, |
| 506 | range_from: str | None = None, |
| 507 | range_to: str | None = None, |
| 508 | ) -> None: |
| 509 | """The Reddit fields whose winner depends on where each copy got them.""" |
| 510 | mine_source = existing.metadata.get("engagement_source") |
| 511 | theirs_source = incoming.metadata.get("engagement_source") |
| 512 | mine_score = existing.engagement.get("score") |
| 513 | theirs_score = (incoming.engagement or {}).get("score") |
| 514 | if _reddit_score_key(theirs_score, theirs_source) > _reddit_score_key(mine_score, mine_source): |
| 515 | existing.engagement["score"] = theirs_score |
| 516 | if theirs_source: |
| 517 | existing.metadata["engagement_source"] = theirs_source |
| 518 | else: |
| 519 | existing.metadata.pop("engagement_source", None) |
| 520 | theirs_comments = incoming.metadata.get("top_comments") or [] |
| 521 | if theirs_comments: |
| 522 | existing.metadata["top_comments"] = [ |
| 523 | dict(c) if isinstance(c, dict) else c |
| 524 | for c in reddit_refs.union_comments( |
| 525 | existing.metadata.get("top_comments") or [], theirs_comments, |
| 526 | ) |
| 527 | ] |
| 528 | sources = { |
| 529 | existing.metadata.get("comments_source"), incoming.metadata.get("comments_source"), |
| 530 | } - {None, ""} |
| 531 | if sources: |
| 532 | existing.metadata["comments_source"] = "+".join(sorted(sources)) |
| 533 | in_meta = incoming.metadata if isinstance(incoming.metadata, dict) else {} |
| 534 | mine_date = str(existing.metadata.get("matched_comment_date") or "").strip() |
| 535 | theirs_date = str(in_meta.get("matched_comment_date") or "").strip() |
| 536 | mine_url = str(existing.metadata.get("matched_comment_url") or "").strip() |
| 537 | theirs_url = str(in_meta.get("matched_comment_url") or "").strip() |
| 538 | if mine_date and not _matched_date_in_window(mine_date, range_from, range_to): |
| 539 | existing.metadata.pop("matched_comment_date", None) |
| 540 | existing.metadata.pop("matched_comment_url", None) |
| 541 | mine_date = "" |
| 542 | mine_url = "" |
| 543 | theirs_in_window = _matched_date_in_window(theirs_date, range_from, range_to) |
| 544 | mine_cmp = _parse_iso_day(mine_date) or mine_date |
| 545 | theirs_cmp = _parse_iso_day(theirs_date) or theirs_date |
| 546 | if theirs_in_window and ( |
| 547 | not mine_date |
| 548 | or theirs_cmp > mine_cmp |
| 549 | or (theirs_cmp == mine_cmp and not mine_url and theirs_url) |
| 550 | ): |
| 551 | existing.metadata["matched_comment_date"] = theirs_date |
| 552 | if theirs_url: |
| 553 | existing.metadata["matched_comment_url"] = theirs_url |
| 554 | else: |
| 555 | existing.metadata.pop("matched_comment_url", None) |
| 556 | |
| 557 | |
| 558 | def collapse_duplicate_urls(items: list[schema.SourceItem]) -> list[schema.SourceItem]: |
| 559 | """Collapse same-source, same-URL copies, keeping order and merging enrichment. |
| 560 | |
| 561 | Per-stream item ids (``R1``, ``X1``) collide across subqueries, so identity |
| 562 | is :func:`source_item_key` (the normalized URL, or the HN discussion URL), |
| 563 | not the id. The first occurrence stays in place and absorbs later copies |
| 564 | via :func:`merge_source_items`. Reused Polymarket slug URLs carrying |
| 565 | distinct known ``event_id`` values (and ID-less copies at those URLs) are |
| 566 | kept separate so conflicting events never merge or bridge. |
| 567 | """ |
| 568 | poly_eids = polymarket_event_ids_by_url(items) |
| 569 | first_by_key: dict[tuple[str, str], schema.SourceItem] = {} |
| 570 | kept: list[schema.SourceItem] = [] |
| 571 | for item in items: |
| 572 | key = source_item_key(item, polymarket_eids_by_url=poly_eids) |
| 573 | existing = first_by_key.get(key) |
| 574 | if existing is None: |
| 575 | first_by_key[key] = item |
| 576 | kept.append(item) |
| 577 | else: |
| 578 | merge_source_items(existing, item) |
| 579 | return kept |
| 580 | |
| 581 | |
| 582 | _DIVERSITY_RELEVANCE_THRESHOLD = 0.25 |
| 583 | |
| 584 | # Reddit engagement reservation: pool slots held for the highest-engagement |
| 585 | # entity-grounded in-window Reddit candidates, scaled by pool size (quick 15 |
| 586 | # -> 2, default 40 -> 3, deep 60 -> 4). The fused order is RRF-first and each |
| 587 | # stream is relevance-first, so the month's most-discussed on-topic thread can |
| 588 | # otherwise lose its slot to a one-upvote post with better title overlap. |
| 589 | _REDDIT_RESERVE_BY_POOL = ((15, 2), (40, 3)) |
| 590 | _REDDIT_RESERVE_MAX = 4 |
| 591 | |
| 592 | |
| 593 | # Capability reservation: on an enablement plan ("X control my computer"), |
| 594 | # pool slots held for the best results of the searches for the capability |
| 595 | # alone ("computer use MCP server"). Posts naming the host match several |
| 596 | # searches and outrank them on RRF, so the tools that answer the question |
| 597 | # would otherwise never reach the reranker. |
| 598 | _CAPABILITY_RESERVE = 6 |
| 599 | _CAPABILITY_RESERVE_PER_SOURCE = 3 |
| 600 | ENABLEMENT_HOST_NOTE = "enablement-host:" # planner.ENABLEMENT_HOST_NOTE |
| 601 | |
| 602 | |
| 603 | def enablement_host(plan: schema.QueryPlan) -> str: |
| 604 | """The host an enablement plan names ("grok"), or "" for any other plan.""" |
| 605 | for note in plan.notes: |
| 606 | if note.startswith(ENABLEMENT_HOST_NOTE): |
| 607 | return note[len(ENABLEMENT_HOST_NOTE):] |
| 608 | return "" |
| 609 | |
| 610 | |
| 611 | def _names(text: str, host: str) -> bool: |
| 612 | return bool(re.search(rf"\b{re.escape(host)}", text, re.IGNORECASE)) |
| 613 | |
| 614 | |
| 615 | def capability_labels(plan: schema.QueryPlan) -> set[str]: |
| 616 | """Labels of an enablement plan's subqueries that leave out the host.""" |
| 617 | host = enablement_host(plan) |
| 618 | if not host: |
| 619 | return set() |
| 620 | return {subquery.label for subquery in plan.subqueries if not _names(subquery.search_query, host)} |
| 621 | |
| 622 | |
| 623 | def is_capability_result(candidate: schema.Candidate, labels: set[str], host: str) -> bool: |
| 624 | """A result of a capability-only search that does not itself name the host. |
| 625 | |
| 626 | Some sources search the raw topic whatever the subquery says, so a |
| 627 | capability label alone also tags posts about the host; those need no help. |
| 628 | """ |
| 629 | if not labels.intersection(candidate.subquery_labels): |
| 630 | return False |
| 631 | return not _names(f"{candidate.title} {candidate.snippet}", host) |
| 632 | |
| 633 | |
| 634 | def _capability_reservation(results: list[schema.Candidate]) -> list[schema.Candidate]: |
| 635 | """Up to _CAPABILITY_RESERVE results, taken round-robin across sources. |
| 636 | |
| 637 | Tool pages (Web, GitHub) rank below social posts on fused rank, so a plain |
| 638 | top-N went entirely to Reddit and TikTok posts about the capability. |
| 639 | """ |
| 640 | by_source: dict[str, list[schema.Candidate]] = {} |
| 641 | for candidate in results: |
| 642 | by_source.setdefault(candidate.source, []).append(candidate) |
| 643 | chosen: list[schema.Candidate] = [] |
| 644 | for rank in range(_CAPABILITY_RESERVE_PER_SOURCE): |
| 645 | for queue in by_source.values(): |
| 646 | if rank < len(queue) and len(chosen) < _CAPABILITY_RESERVE: |
| 647 | chosen.append(queue[rank]) |
| 648 | return chosen |
| 649 | |
| 650 | |
| 651 | def _reddit_reserve_for(pool_limit: int) -> int: |
| 652 | for ceiling, reserve in _REDDIT_RESERVE_BY_POOL: |
| 653 | if pool_limit <= ceiling: |
| 654 | return reserve |
| 655 | return _REDDIT_RESERVE_MAX |
| 656 | |
| 657 | |
| 658 | def relevance_floor_for_entity(entity: str) -> float: |
| 659 | """Relevance a Reddit thread must clear to earn a reservation or keeper slot. |
| 660 | |
| 661 | Grounding keys on the entity's head token (see ``rerank._entity_grounded``). |
| 662 | A generic head ("ai", "x", "new") matches almost anything, so the floor |
| 663 | rises to the diversity threshold; a distinctive head keeps the shared |
| 664 | ``RELEVANCE_FLOOR``. |
| 665 | """ |
| 666 | from . import relevance |
| 667 | |
| 668 | head = (entity or "").lower().split()[:1] |
| 669 | if not head: |
| 670 | return relevance.RELEVANCE_FLOOR |
| 671 | token = head[0] |
| 672 | generic = ( |
| 673 | len(token) <= 2 |
| 674 | or token in relevance.STOPWORDS |
| 675 | or token in relevance.LOW_SIGNAL_QUERY_TOKENS |
| 676 | ) |
| 677 | return _DIVERSITY_RELEVANCE_THRESHOLD if generic else relevance.RELEVANCE_FLOOR |
| 678 | |
| 679 | |
| 680 | def raw_engagement(item: schema.SourceItem) -> float: |
| 681 | """Upvotes plus comments as a plain number, for engagement-first ordering.""" |
| 682 | eng = item.engagement or {} |
| 683 | total = 0.0 |
| 684 | for key in ("score", "num_comments"): |
| 685 | value = eng.get(key) |
| 686 | if isinstance(value, (int, float)) and not isinstance(value, bool): |
| 687 | total += float(value) |
| 688 | return total |
| 689 | |
| 690 | |
| 691 | def reddit_thread_qualifies( |
| 692 | item: schema.SourceItem, |
| 693 | entity: str, |
| 694 | floor: float, |
| 695 | relevance: float | None = None, |
| 696 | ) -> bool: |
| 697 | """On-topic enough for an engagement slot: clears the floor and names the entity. |
| 698 | |
| 699 | ``relevance`` overrides the item's own ``local_relevance`` (a fused |
| 700 | candidate carries the max across its copies). |
| 701 | """ |
| 702 | from . import rerank |
| 703 | |
| 704 | score = relevance if relevance is not None else (item.local_relevance or 0.0) |
| 705 | if score < floor: |
| 706 | return False |
| 707 | if raw_engagement(item) <= 0: |
| 708 | return False |
| 709 | if not entity: |
| 710 | return True |
| 711 | return rerank._entity_grounded(f"{item.title or ''} {item.body or ''}", entity) |
| 712 | |
| 713 | # Per-author cap: no single author/handle should dominate the pool. |
| 714 | _MAX_ITEMS_PER_AUTHOR = 3 |
| 715 | |
| 716 | # Raised cap for the subject of the topic (a handle in the run's |
| 717 | # resolved_handles). On a person or company topic the subject is what the user |
| 718 | # asked about, so the flat cap discards exactly the evidence the run worked |
| 719 | # hardest to retrieve -- the measured 'Peter Steinberger steipete' baseline |
| 720 | # recovered 8 subject-authored posts and would have kept 3. Still bounded: a |
| 721 | # prolific subject must not crowd out commentary about them, which is the other |
| 722 | # half of the answer a user wants. |
| 723 | _MAX_ITEMS_PER_FIRST_PARTY_AUTHOR = 8 |
| 724 | |
| 725 | |
| 726 | def _extract_author(candidate: schema.Candidate) -> str | None: |
| 727 | """Return a normalized author key from a candidate's source items.""" |
| 728 | for item in candidate.source_items: |
| 729 | # Jobs use the ATS provider as author, not an individual contributor. |
| 730 | if item.source != "jobs" and item.author: |
| 731 | return item.author.strip().lower() |
| 732 | return None |
| 733 | |
| 734 | |
| 735 | def _apply_per_author_cap( |
| 736 | candidates: list[schema.Candidate], |
| 737 | max_per_author: int = _MAX_ITEMS_PER_AUTHOR, |
| 738 | first_party_handles: Iterable[str] | None = None, |
| 739 | max_per_first_party_author: int = _MAX_ITEMS_PER_FIRST_PARTY_AUTHOR, |
| 740 | ) -> list[schema.Candidate]: |
| 741 | """Keep at most *max_per_author* items from any single author. |
| 742 | |
| 743 | Authors named in *first_party_handles* -- the subject of the topic -- get |
| 744 | the higher *max_per_first_party_author* allowance instead, because their |
| 745 | own posts are the point of the query rather than one voice among many. |
| 746 | |
| 747 | Candidates are assumed to already be sorted by quality (rrf_score etc.), |
| 748 | so the first N encountered per author are the best ones. |
| 749 | """ |
| 750 | first_party = { |
| 751 | h.strip().lstrip("@").lower() |
| 752 | for h in (first_party_handles or ()) |
| 753 | if h and h.strip() |
| 754 | } |
| 755 | author_counts: dict[str, int] = {} |
| 756 | result: list[schema.Candidate] = [] |
| 757 | for c in candidates: |
| 758 | author = _extract_author(c) |
| 759 | if author is None: |
| 760 | result.append(c) |
| 761 | continue |
| 762 | limit = ( |
| 763 | max_per_first_party_author |
| 764 | if author.strip().lstrip("@").lower() in first_party |
| 765 | else max_per_author |
| 766 | ) |
| 767 | count = author_counts.get(author, 0) |
| 768 | if count < limit: |
| 769 | result.append(c) |
| 770 | author_counts[author] = count + 1 |
| 771 | return result |
| 772 | |
| 773 | |
| 774 | def _reddit_engagement_reservation( |
| 775 | fused: list[schema.Candidate], |
| 776 | reserve: int, |
| 777 | entity: str, |
| 778 | ) -> list[schema.Candidate]: |
| 779 | """The *reserve* highest-engagement Reddit candidates that are in-window |
| 780 | and on-topic, in engagement order. A copy whose score is pending has no |
| 781 | engagement to rank by yet and is passed over.""" |
| 782 | if reserve <= 0: |
| 783 | return [] |
| 784 | floor = relevance_floor_for_entity(entity) |
| 785 | eligible = [] |
| 786 | for c in fused: |
| 787 | if c.source != "reddit" or schema.candidate_out_of_window(c): |
| 788 | continue |
| 789 | reddit_items = [ |
| 790 | it for it in c.source_items |
| 791 | if it.source == "reddit" and not reddit_refs.score_pending(it.metadata) |
| 792 | ] |
| 793 | if not reddit_items: |
| 794 | continue |
| 795 | best = max(reddit_items, key=raw_engagement) |
| 796 | relevance = max(c.local_relevance or 0.0, best.local_relevance or 0.0) |
| 797 | if not reddit_thread_qualifies(best, entity, floor, relevance=relevance): |
| 798 | continue |
| 799 | eligible.append((raw_engagement(best), c)) |
| 800 | eligible.sort(key=lambda pair: -pair[0]) |
| 801 | return [c for _, c in eligible[:reserve]] |
| 802 | |
| 803 | |
| 804 | def _diversify_pool( |
| 805 | fused: list[schema.Candidate], |
| 806 | pool_limit: int, |
| 807 | min_per_source: int = 2, |
| 808 | entity: str = "", |
| 809 | capability: set[str] | None = None, |
| 810 | host: str = "", |
| 811 | ) -> list[schema.Candidate]: |
| 812 | """Ensure at least *min_per_source* items per qualifying source survive truncation. |
| 813 | |
| 814 | Sources only qualify for reserved slots if their best item exceeds |
| 815 | the relevance threshold. Low-relevance sources compete on merit only. |
| 816 | Reddit additionally gets an engagement reservation (see |
| 817 | ``_reddit_reserve_for``) for its most-discussed on-topic threads. |
| 818 | """ |
| 819 | max_relevance: dict[str, float] = {} |
| 820 | for c in fused: |
| 821 | current = max_relevance.get(c.source, 0.0) |
| 822 | if c.local_relevance > current: |
| 823 | max_relevance[c.source] = c.local_relevance |
| 824 | |
| 825 | protected = _reddit_engagement_reservation(fused, _reddit_reserve_for(pool_limit), entity) |
| 826 | if capability: |
| 827 | reserved_ids = {c.candidate_id for c in protected} |
| 828 | protected += _capability_reservation( |
| 829 | [ |
| 830 | c |
| 831 | for c in fused |
| 832 | if c.candidate_id not in reserved_ids |
| 833 | and not schema.candidate_out_of_window(c) |
| 834 | and is_capability_result(c, capability, host) |
| 835 | ] |
| 836 | ) |
| 837 | protected_ids = {c.candidate_id for c in protected} |
| 838 | pool: list[schema.Candidate] = list(protected) |
| 839 | seen = set(protected_ids) |
| 840 | reserved: dict[str, list[schema.Candidate]] = {} |
| 841 | remainder: list[schema.Candidate] = [] |
| 842 | for c in fused: |
| 843 | if c.candidate_id in seen: |
| 844 | continue |
| 845 | qualifies = max_relevance.get(c.source, 0.0) >= _DIVERSITY_RELEVANCE_THRESHOLD |
| 846 | bucket = reserved.setdefault(c.source, []) |
| 847 | if qualifies and len(bucket) < min_per_source: |
| 848 | bucket.append(c) |
| 849 | else: |
| 850 | remainder.append(c) |
| 851 | pool.extend(c for per_source in reserved.values() for c in per_source) |
| 852 | seen = {c.candidate_id for c in pool} |
| 853 | for c in remainder: |
| 854 | if len(pool) >= pool_limit: |
| 855 | break |
| 856 | if c.candidate_id not in seen: |
| 857 | pool.append(c) |
| 858 | pool.sort(key=_candidate_sort_key) |
| 859 | if len(pool) > pool_limit: |
| 860 | # The per-source buckets can overfill a small pool. The Reddit |
| 861 | # reservation is low-RRF by construction, so a plain slice would cut |
| 862 | # exactly the threads it exists to keep: trim unprotected candidates |
| 863 | # from the sorted tail instead. |
| 864 | keep_unprotected = pool_limit - len(protected_ids) |
| 865 | trimmed: list[schema.Candidate] = [] |
| 866 | for c in pool: |
| 867 | if c.candidate_id in protected_ids: |
| 868 | trimmed.append(c) |
| 869 | elif keep_unprotected > 0: |
| 870 | trimmed.append(c) |
| 871 | keep_unprotected -= 1 |
| 872 | pool = trimmed |
| 873 | return pool[:pool_limit] |
| 874 | |
| 875 | |
| 876 | def _pin_snippet_to_primary_submission(candidate: schema.Candidate) -> None: |
| 877 | """Keep a card's Evidence on the item whose metrics it shows. |
| 878 | |
| 879 | The card renders :func:`schema.candidate_primary_item`'s metrics beside |
| 880 | ``candidate.snippet``. A longer description or a spoken caption can come |
| 881 | from a different submission of the same URL, on the same or another |
| 882 | source. Copies of one submission have already merged their enrichment. |
| 883 | """ |
| 884 | primary = schema.candidate_primary_item(candidate) |
| 885 | if primary is None: |
| 886 | return |
| 887 | if primary.source == "github" and schema.GITHUB_REPO_COUNTERS.intersection(primary.engagement or {}): |
| 888 | candidate.title = primary.title |
| 889 | candidate.snippet = primary.snippet or "" |
| 890 | return |
| 891 | primary_key = source_item_key(primary) |
| 892 | if any( |
| 893 | source_item_key(item) != primary_key |
| 894 | for item in candidate.source_items |
| 895 | ): |
| 896 | candidate.snippet = primary.snippet or "" |
| 897 | |
| 898 | |
| 899 | def weighted_rrf( |
| 900 | streams: dict[tuple[str, str], list[schema.SourceItem]], |
| 901 | plan: schema.QueryPlan, |
| 902 | *, |
| 903 | pool_limit: int, |
| 904 | range_from: str | None = None, |
| 905 | range_to: str | None = None, |
| 906 | first_party_handles: Iterable[str] | None = None, |
| 907 | primary_handle: str | None = None, |
| 908 | ) -> list[schema.Candidate]: |
| 909 | """Fuse ranked lists into a single candidate pool. |
| 910 | |
| 911 | When ``range_from`` and ``range_to`` are provided, they are stored in each |
| 912 | candidate's metadata so ``candidate_out_of_window`` can compare the actual |
| 913 | date against the run window (instead of relying solely on adapter-provided |
| 914 | ``date_confidence``). ``first_party_handles`` raises the per-author cap |
| 915 | for the topic's subject so their own posts are not flattened to the |
| 916 | incidental-account allowance. |
| 917 | """ |
| 918 | subqueries = {subquery.label: subquery for subquery in plan.subqueries} |
| 919 | candidates: dict[str, schema.Candidate] = {} |
| 920 | primary_scores: dict[str, float] = {} |
| 921 | candidate_spoken: dict[str, bool] = {} |
| 922 | # Track source items already attached to each candidate, keyed by |
| 923 | # source_item_key (source + normalized URL, or the HN discussion URL): |
| 924 | # per-stream ids collide across subqueries, and |
| 925 | # a repeat copy may carry enrichment the first one lacks. |
| 926 | seen_source_items: dict[str, dict[tuple[str, str], schema.SourceItem]] = {} |
| 927 | poly_eids = polymarket_event_ids_by_url( |
| 928 | item |
| 929 | for items in streams.values() |
| 930 | for item in items |
| 931 | if item.source == "polymarket" |
| 932 | and entity_extract.matches_person_identity( |
| 933 | item, plan.person_identity_anchors, primary_handle, |
| 934 | person_run=getattr(plan, "person_run", False), |
| 935 | ) |
| 936 | ) |
| 937 | |
| 938 | for (label, source), items in streams.items(): |
| 939 | subquery = subqueries[label] |
| 940 | weight = subquery.weight * plan.source_weights.get(source, 1.0) |
| 941 | for rank, item in enumerate(items, start=1): |
| 942 | # Reject only the unqualified copy before combining its text, |
| 943 | # provenance, or votes with qualified evidence at the same URL. |
| 944 | if not entity_extract.matches_person_identity( |
| 945 | item, plan.person_identity_anchors, primary_handle, |
| 946 | person_run=getattr(plan, "person_run", False), |
| 947 | ): |
| 948 | continue |
| 949 | key = candidate_key(item, polymarket_eids_by_url=poly_eids) |
| 950 | score = weight / (RRF_K + rank) |
| 951 | item_local_relevance = item.local_relevance if item.local_relevance is not None else float(item.metadata.get("local_relevance", item.relevance_hint)) |
| 952 | item_freshness = item.freshness if item.freshness is not None else int(item.metadata.get("freshness", 0)) |
| 953 | item_source_quality = item.source_quality if item.source_quality is not None else float(item.metadata.get("source_quality", 0.6)) |
| 954 | incoming_primary_score = _primary_score(item_local_relevance, item_freshness, item_source_quality) |
| 955 | incoming_spoken = bool((item.metadata or {}).get("spoken_caption")) and bool((item.snippet or "").strip()) |
| 956 | if key not in candidates: |
| 957 | attached = _clone_source_item(item) |
| 958 | _sanitize_reddit_matched_comment(attached, range_from, range_to) |
| 959 | candidate_metadata: dict = { |
| 960 | "provenance": [ |
| 961 | { |
| 962 | "source": source, |
| 963 | "subquery_label": label, |
| 964 | "native_rank": rank, |
| 965 | "item_id": item.item_id, |
| 966 | } |
| 967 | ] |
| 968 | } |
| 969 | if range_from: |
| 970 | candidate_metadata["range_from"] = range_from |
| 971 | if range_to: |
| 972 | candidate_metadata["range_to"] = range_to |
| 973 | candidates[key] = schema.Candidate( |
| 974 | candidate_id=key, |
| 975 | item_id=item.item_id, |
| 976 | source=item.source, |
| 977 | title=item.title, |
| 978 | url=item.url, |
| 979 | snippet=item.snippet, |
| 980 | subquery_labels=[label], |
| 981 | native_ranks={f"{label}:{source}": rank}, |
| 982 | local_relevance=item_local_relevance, |
| 983 | freshness=item_freshness, |
| 984 | engagement=_item_engagement_score(attached), |
| 985 | source_quality=item_source_quality, |
| 986 | rrf_score=score, |
| 987 | sources=[item.source], |
| 988 | source_items=[attached], |
| 989 | metadata=candidate_metadata, |
| 990 | ) |
| 991 | primary_scores[key] = incoming_primary_score |
| 992 | candidate_spoken[key] = incoming_spoken |
| 993 | seen_source_items[key] = { |
| 994 | source_item_key(attached, polymarket_eids_by_url=poly_eids): attached, |
| 995 | } |
| 996 | continue |
| 997 | |
| 998 | candidate = candidates[key] |
| 999 | rank_key = f"{label}:{source}" |
| 1000 | if rank_key not in candidate.native_ranks: |
| 1001 | candidate.rrf_score += score |
| 1002 | candidate.native_ranks[rank_key] = rank |
| 1003 | else: |
| 1004 | candidate.native_ranks[rank_key] = min(candidate.native_ranks[rank_key], rank) |
| 1005 | candidate.local_relevance = max( |
| 1006 | candidate.local_relevance, |
| 1007 | item_local_relevance, |
| 1008 | ) |
| 1009 | candidate.freshness = max(candidate.freshness, item_freshness) |
| 1010 | candidate.source_quality = max( |
| 1011 | candidate.source_quality, |
| 1012 | item_source_quality, |
| 1013 | ) |
| 1014 | if label not in candidate.subquery_labels: |
| 1015 | candidate.subquery_labels.append(label) |
| 1016 | if item.source not in candidate.sources: |
| 1017 | candidate.sources.append(item.source) |
| 1018 | promoted = incoming_primary_score > primary_scores[key] |
| 1019 | item_key = source_item_key(item, polymarket_eids_by_url=poly_eids) |
| 1020 | existing_item = seen_source_items[key].get(item_key) |
| 1021 | if existing_item is None: |
| 1022 | attached = _clone_source_item(item) |
| 1023 | _sanitize_reddit_matched_comment(attached, range_from, range_to) |
| 1024 | seen_source_items[key][item_key] = attached |
| 1025 | candidate.source_items.append(attached) |
| 1026 | elif promoted: |
| 1027 | new_primary = _clone_source_item(item) |
| 1028 | merge_source_items( |
| 1029 | new_primary, existing_item, |
| 1030 | range_from=range_from, range_to=range_to, |
| 1031 | ) |
| 1032 | idx = candidate.source_items.index(existing_item) |
| 1033 | candidate.source_items[idx] = new_primary |
| 1034 | seen_source_items[key][item_key] = new_primary |
| 1035 | attached = new_primary |
| 1036 | else: |
| 1037 | merge_source_items( |
| 1038 | existing_item, _clone_source_item(item), |
| 1039 | range_from=range_from, range_to=range_to, |
| 1040 | ) |
| 1041 | attached = existing_item |
| 1042 | candidate.engagement = _candidate_engagement_from_items(candidate.source_items) |
| 1043 | candidate.metadata.setdefault("provenance", []).append( |
| 1044 | { |
| 1045 | "source": source, |
| 1046 | "subquery_label": label, |
| 1047 | "native_rank": rank, |
| 1048 | "item_id": item.item_id, |
| 1049 | } |
| 1050 | ) |
| 1051 | if promoted: |
| 1052 | primary_scores[key] = incoming_primary_score |
| 1053 | candidate.item_id = attached.item_id |
| 1054 | candidate.source = attached.source |
| 1055 | candidate.title = attached.title |
| 1056 | candidate.url = attached.url |
| 1057 | if candidate.source_items and candidate.source_items[0] is not attached: |
| 1058 | candidate.source_items.remove(attached) |
| 1059 | candidate.source_items.insert(0, attached) |
| 1060 | elif ( |
| 1061 | attached.source == "polymarket" |
| 1062 | and candidate.source == "polymarket" |
| 1063 | and (attached.metadata or {}).get("matched_market") |
| 1064 | ): |
| 1065 | candidate.title = attached.title |
| 1066 | if incoming_spoken and not candidate_spoken[key]: |
| 1067 | candidate.snippet = item.snippet |
| 1068 | candidate_spoken[key] = True |
| 1069 | elif incoming_spoken == candidate_spoken[key]: |
| 1070 | if promoted or ( |
| 1071 | attached.source == "polymarket" |
| 1072 | and candidate.source == "polymarket" |
| 1073 | ): |
| 1074 | candidate.snippet = attached.snippet |
| 1075 | elif len((candidate.snippet or "").split()) < len((item.snippet or "").split()): |
| 1076 | candidate.snippet = item.snippet |
| 1077 | |
| 1078 | for candidate in candidates.values(): |
| 1079 | _pin_snippet_to_primary_submission(candidate) |
| 1080 | |
| 1081 | fused = sorted(candidates.values(), key=_candidate_sort_key) |
| 1082 | fused = _apply_per_author_cap(fused, first_party_handles=first_party_handles) |
| 1083 | from . import rerank |
| 1084 | |
| 1085 | entity = rerank._primary_entity(plan.raw_topic or "") if plan.raw_topic else "" |
| 1086 | return _diversify_pool( |
| 1087 | fused, pool_limit, entity=entity, capability=capability_labels(plan), host=enablement_host(plan) |
| 1088 | ) |
| 1089 |