Skip to content

AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary

fix(reddit): relevance floor + relevance-first ranking so viral off-topic posts don't dominate (#488)

rzachmithd6a4dd0822da
diff --git a/skills/last30days/scripts/lib/reddit.py b/skills/last30days/scripts/lib/reddit.py
index bd36a6bb..9cfae9a7 100644
--- a/skills/last30days/scripts/lib/reddit.py
+++ b/skills/last30days/scripts/lib/reddit.py
@@ -7,6 +7,7 @@ Requires SCRAPECREATORS_API_KEY in config (same key as TikTok + Instagram).
API docs: https://scrapecreators.com/docs
"""
+import math
import re
import sys
import time
@@ -25,6 +26,13 @@ from . import dates, http, log
SCRAPECREATORS_BASE = "https://api.scrapecreators.com/v1/reddit"
+# Reddit's highest-upvote content (relationship drama, AITA, viral news) often
+# has near-zero topic overlap. Engagement-only ranking floats it above on-topic
+# posts, especially on bare global searches where no subreddits were resolved
+# upstream. A relevance floor + relevance-first ranking (see _relevance_rank_key
+# below and RELEVANCE_FLOOR / MIN_ON_TOPIC in relevance.py) keeps an off-topic
+# viral post from ever outranking an on-topic one.
+
# Depth configurations: how many API calls per phase
DEPTH_CONFIG = {
"quick": {
@@ -48,7 +56,7 @@ DEPTH_CONFIG = {
}
from .query import extract_core_subject as _query_extract
-from .relevance import token_overlap_relevance
+from .relevance import token_overlap_relevance, RELEVANCE_FLOOR, MIN_ON_TOPIC
# Reddit-specific noise words (preserves original smaller set)
NOISE_WORDS = frozenset({
@@ -252,6 +260,18 @@ def _total_engagement(item: Dict[str, Any]) -> int:
return score + num_comments
+def _relevance_rank_key(item: Dict[str, Any]) -> float:
+ """Rank by relevance first, with a bounded engagement bonus as tiebreaker.
+
+ The log-scaled bonus is capped at 0.25 so it orders similarly-relevant posts
+ by discussion volume but is too small to lift an off-topic post (relevance
+ ~0) above an on-topic one (relevance >= RELEVANCE_FLOOR).
+ """
+ rel = item.get("relevance") or 0.0
+ eng_bonus = min(0.25, math.log10(_total_engagement(item) + 1) / 20.0)
+ return rel + eng_bonus
+
+
def _normalize_post(post: Dict[str, Any], idx: int, source_label: str = "global", query: str = "") -> Dict[str, Any]:
"""Normalize a ScrapeCreators Reddit post to our internal format.
@@ -555,11 +575,24 @@ def search_reddit(
else:
_log(f"No posts within date range, keeping all {len(all_items)}")
- # === Phase 6: Sort by engagement (upvotes + comment count) ===
- all_items.sort(
- key=lambda x: _total_engagement(x),
- reverse=True,
- )
+ # === Phase 6: Relevance floor + relevance-weighted ranking ===
+ # Drop the off-topic tail when enough on-topic posts remain (guard mirrors
+ # the date filter: keep all if too few clear the floor). When too few clear
+ # the soft floor, still strip zero-overlap posts (relevance exactly 0 = no
+ # title/body token match at all, never on-topic) whenever anything relevant
+ # remains, so viral high-upvote junk can't fill the section. Then rank by
+ # relevance with a bounded engagement bonus (see RELEVANCE_FLOOR note above).
+ before = len(all_items)
+ on_topic = [it for it in all_items if (it.get("relevance") or 0) >= RELEVANCE_FLOOR]
+ if len(on_topic) >= MIN_ON_TOPIC:
+ all_items = on_topic
+ else:
+ nonzero = [it for it in all_items if (it.get("relevance") or 0) > 0]
+ if nonzero:
+ all_items = nonzero
+ if len(all_items) < before:
+ _log(f"Relevance floor dropped {before - len(all_items)} off-topic posts")
+ all_items.sort(key=_relevance_rank_key, reverse=True)
# Re-index IDs
for i, item in enumerate(all_items):
diff --git a/skills/last30days/scripts/lib/reddit_keyless.py b/skills/last30days/scripts/lib/reddit_keyless.py
index e6185c10..7050b165 100644
--- a/skills/last30days/scripts/lib/reddit_keyless.py
+++ b/skills/last30days/scripts/lib/reddit_keyless.py
@@ -15,6 +15,7 @@ ScrapeCreators backup when every keyless tier comes up empty.
"""
import concurrent.futures
+import math
import sys
from concurrent.futures import ThreadPoolExecutor
from typing import Any, Dict, List, Optional
@@ -22,6 +23,11 @@ from typing import Any, Dict, List, Optional
from collections import Counter
from . import reddit_rss, reddit_shreddit, reddit_listing
+# Scores are backfilled from popular derived subreddits, so an engagement-first
+# final sort buries on-topic RSS hits under viral off-topic posts. A relevance
+# floor + relevance-first final ranking keeps the section on-topic. Thresholds
+# are shared with the keyed path (reddit.py) via relevance.py.
+from .relevance import RELEVANCE_FLOOR, MIN_ON_TOPIC
ENRICH_LIMITS = reddit_shreddit.ENRICH_LIMITS
ENRICH_BUDGET = 45 # seconds total across all enrichment threads
@@ -29,6 +35,18 @@ MAX_ENRICH_WORKERS = 4
MAX_DERIVED_SUBS = 5 # subreddits derived from RSS results for score backfill
+def _relevance_rank_key(post: Dict[str, Any]) -> float:
+ """Rank by relevance first, with a bounded engagement bonus as tiebreaker.
+
+ Mirrors reddit.py: the log-scaled bonus (capped at 0.25) orders
+ similarly-relevant posts by discussion volume but is too small to lift an
+ off-topic post (relevance ~0) above an on-topic one.
+ """
+ eng = post.get("engagement", {})
+ total = (eng.get("score", 0) or 0) + (eng.get("num_comments", 0) or 0)
+ return (post.get("relevance") or 0.0) + min(0.25, math.log10(total + 1) / 20.0)
+
+
def _log(msg: str) -> None:
sys.stderr.write(f"[RedditKeyless] {msg}\n")
sys.stderr.flush()
@@ -235,9 +253,23 @@ def search_and_enrich(
if p.get("date") is None or (from_date <= p["date"] <= to_date)
]
- # Rank by real upvote score (from listing cards / backfill), then query
- # relevance, then recency. Posts without a recovered score sort by the
- # latter two — same behavior as before scores were available.
+ # Relevance floor: strip zero-overlap posts (relevance exactly 0 = no
+ # title/body token match at all) when anything relevant remains, so
+ # backfilled high-upvote posts from popular subs can't bury on-topic RSS
+ # hits. Keep all only when nothing scored above zero.
+ before = len(posts)
+ on_topic = [p for p in posts if (p.get("relevance") or 0) >= RELEVANCE_FLOOR]
+ if len(on_topic) >= MIN_ON_TOPIC:
+ posts = on_topic
+ else:
+ nonzero = [p for p in posts if (p.get("relevance") or 0) > 0]
+ if nonzero:
+ posts = nonzero
+ if len(posts) < before:
+ _log(f"Relevance floor dropped {before - len(posts)} off-topic posts")
+
+ # Provisional score-first order so enrichment-slot selection has a stable
+ # within-tier order to preserve.
posts.sort(
key=lambda p: (
p.get("engagement", {}).get("score", 0) or 0,
@@ -249,9 +281,14 @@ def search_and_enrich(
# Enrichment slot selection is relevance-aware: entity-matching posts
# claim the scarce comment slots first (score order preserved within
- # each tier). The score-first sort above still governs within-tier order.
+ # each tier).
posts = _enrich(_slot_priority(topic, posts), depth)
+ # Final display order ranks relevance-first with a bounded engagement bonus,
+ # so an off-topic high-upvote post can't outrank an on-topic one in what the
+ # user sees. Enrichment above may have backfilled real comment counts.
+ posts.sort(key=_relevance_rank_key, reverse=True)
+
for i, post in enumerate(posts):
post["id"] = f"R{i + 1}"
diff --git a/skills/last30days/scripts/lib/relevance.py b/skills/last30days/scripts/lib/relevance.py
index 1af86956..78a7298c 100644
--- a/skills/last30days/scripts/lib/relevance.py
+++ b/skills/last30days/scripts/lib/relevance.py
@@ -20,6 +20,14 @@ STOPWORDS = frozenset({
'all', 'just', 'get', 'has', 'have', 'was', 'will',
}) | cjk.CHINESE_STOPWORDS
+# Shared relevance-ranking thresholds for the Reddit pipelines (keyed + keyless).
+# Single source of truth so both paths apply identical thresholds to the same
+# query. RELEVANCE_FLOOR: posts below this are off-topic; the zero-overlap tail is
+# dropped when anything relevant remains. MIN_ON_TOPIC: how many posts must clear
+# the soft floor before it is applied wholesale.
+RELEVANCE_FLOOR = 0.1
+MIN_ON_TOPIC = 5
+
# Synonym groups for relevance scoring (bidirectional expansion)
# Superset of all platform-specific synonym dicts
SYNONYMS = {
diff --git a/tests/test_reddit_relevance_ranking.py b/tests/test_reddit_relevance_ranking.py
new file mode 100644
index 00000000..8bf792dc
--- /dev/null
+++ b/tests/test_reddit_relevance_ranking.py
@@ -0,0 +1,106 @@
+"""Tests for relevance-floor + relevance-first ranking in the Reddit paths.
+
+Reddit's highest-upvote content (relationship drama, AITA, viral news) often
+has near-zero topic overlap. Before this change both the keyed (ScrapeCreators)
+and keyless (RSS) paths ranked the final list engagement-first, so a viral
+off-topic post outranked on-topic posts. These tests pin the new behavior:
+on-topic posts rank first and pure zero-overlap posts are dropped when anything
+relevant remains.
+"""
+
+from unittest import mock
+
+from lib import reddit, reddit_keyless
+
+
+# --------------------------------------------------------------------------- #
+# Shared ranking key
+# --------------------------------------------------------------------------- #
+
+class TestRelevanceRankKey:
+ def test_on_topic_low_upvote_beats_off_topic_viral(self):
+ on_topic = {"relevance": 0.3, "engagement": {"score": 10, "num_comments": 5}}
+ off_topic = {"relevance": 0.0, "engagement": {"score": 99999, "num_comments": 4000}}
+ assert reddit._relevance_rank_key(on_topic) > reddit._relevance_rank_key(off_topic)
+
+ def test_engagement_bonus_is_bounded(self):
+ # Even astronomical engagement adds at most 0.25, so it can never lift a
+ # relevance-0 post above a post that cleared the floor.
+ huge = {"relevance": 0.0, "engagement": {"score": 10**9, "num_comments": 10**9}}
+ assert reddit._relevance_rank_key(huge) <= 0.25 + 1e-9
+ floored = {"relevance": 0.3, "engagement": {"score": 0, "num_comments": 0}}
+ assert reddit._relevance_rank_key(floored) > reddit._relevance_rank_key(huge)
+
+ def test_keyless_key_matches_keyed_semantics(self):
+ on_topic = {"relevance": 0.3, "engagement": {"score": 10, "num_comments": 5}}
+ off_topic = {"relevance": 0.0, "engagement": {"score": 99999, "num_comments": 4000}}
+ assert reddit_keyless._relevance_rank_key(on_topic) > reddit_keyless._relevance_rank_key(off_topic)
+
+
+# --------------------------------------------------------------------------- #
+# Keyed path (reddit.search_reddit)
+# --------------------------------------------------------------------------- #
+
+def _raw(rid, title, ups, sub):
+ return {
+ "id": f"t3_{rid}",
+ "title": title,
+ "selftext": "",
+ "permalink": f"/r/{sub}/comments/{rid}/post/",
+ "subreddit": sub,
+ "created_utc": 1716000000, # 2024-05-18, kept by a wide date range
+ "ups": ups,
+ "num_comments": max(1, ups // 10),
+ }
+
+
+class TestKeyedRanking:
+ def test_on_topic_outranks_viral_and_zero_overlap_dropped(self):
+ topic = "electric vehicle home charging"
+ on_topic = _raw("aaa", "Electric vehicle home charging setup guide", 5, "electricvehicles")
+ viral = _raw("bbb", "AITA for not sharing my lottery winnings", 99999, "AmItheAsshole")
+
+ with mock.patch.object(reddit, "_global_search", return_value=[on_topic, viral]), \
+ mock.patch.object(reddit, "_subreddit_search", return_value=[]):
+ result = reddit.search_reddit(topic, "2000-01-01", "2100-01-01", depth="default", token="x")
+
+ items = result["items"]
+ urls = [it["url"] for it in items]
+ # Zero-overlap viral post is stripped because an on-topic post exists.
+ assert any("electricvehicles" in u for u in urls)
+ assert not any("AmItheAsshole" in u for u in urls)
+ # On-topic post leads.
+ assert "electricvehicles" in items[0]["url"]
+
+
+# --------------------------------------------------------------------------- #
+# Keyless path (reddit_keyless.search_and_enrich)
+# --------------------------------------------------------------------------- #
+
+def _kpost(rid, rel, score, date="2026-05-20"):
+ return {
+ "id": "", "title": f"Post {rid}", "url": f"https://www.reddit.com/r/t/comments/{rid}/p/",
+ "score": score, "num_comments": score, "subreddit": "t", "created_utc": None,
+ "author": "u", "selftext": "", "date": date,
+ "engagement": {"score": score, "num_comments": score, "upvote_ratio": None},
+ "relevance": rel, "why_relevant": "Reddit RSS", "metadata": {},
+ }
+
+
+class TestKeylessRanking:
+ def test_relevance_first_and_zero_overlap_dropped(self):
+ on_strong = _kpost("aaa", 0.5, 10)
+ on_weak = _kpost("bbb", 0.2, 5000)
+ off_viral = _kpost("ccc", 0.0, 99999)
+
+ with mock.patch.object(reddit_keyless, "_discover",
+ return_value=[off_viral, on_weak, on_strong]), \
+ mock.patch.object(reddit_keyless, "_enrich", side_effect=lambda posts, depth: posts):
+ out = reddit_keyless.search_and_enrich(
+ "some topic", "2026-05-07", "2026-06-06", depth="default")
+
+ urls = [p["url"] for p in out]
+ # Zero-overlap viral post dropped; on-topic posts kept, strongest first.
+ assert "ccc" not in "".join(urls)
+ assert out[0]["url"].endswith("/aaa/p/")
+ assert len(out) == 2