AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary
Python ai-promptsai-skillblueskyclaudeclaude-codeclawhubdeep-researchhackernewsinstagramopenclawpolymarketrecencyredditresearchsocial-mediatiktoktrendstwitterweb-searchyoutube
fix(fusion): keep duplicate HN submissions of one URL apart (#1262)
Matt Van Horn9e459fea7329
diff --git a/changelog.d/+hn-duplicate-submissions.fixed.md b/changelog.d/+hn-duplicate-submissions.fixed.mdnew file mode 100644index 00000000..556f2a12--- /dev/null+++ b/changelog.d/+hn-duplicate-submissions.fixed.md@@ -0,0 +1 @@+Hacker News: when the same article was submitted to HN more than once, the engine merged the submissions and showed one story's id with another story's comment count and comments. Each HN submission now keeps its own points, comment count, discussion link, and comments, and a ranked card's evidence text comes from the same submission whose numbers it shows; submissions of the same article still cluster together.diff --git a/skills/last30days/scripts/lib/fusion.py b/skills/last30days/scripts/lib/fusion.pyindex 617ecdd6..13b55b54 100644--- a/skills/last30days/scripts/lib/fusion.py+++ b/skills/last30days/scripts/lib/fusion.py@@ -47,6 +47,22 @@ def candidate_key(item: schema.SourceItem) -> str:return f"{item.source}:{item.item_id}"+def source_item_key(item: schema.SourceItem) -> tuple[str, str]:+ """Identity of one source item, for same-source de-duplication.++ Usually the normalized URL (see :func:`candidate_key`). A Hacker News+ item's ``url`` is the linked article, and one article can be submitted+ several times as distinct stories with their own points and comments, so+ HN identity is the discussion URL. ``candidate_key`` still clusters those+ submissions (and other sources linking the article) into one candidate.+ """+ if item.source == "hackernews":+ hn_url = item.metadata.get("hn_url")+ if hn_url:+ return (item.source, _normalize_url(str(hn_url)))+ return (item.source, candidate_key(item))++# Enrichment that one copy of a thread may carry and another may lack. When# the same URL arrives from two subquery streams (each stream enriches its own# top-N), the copy that won a comment slot must survive de-duplication.@@ -92,13 +108,14 @@ def collapse_duplicate_urls(items: list[schema.SourceItem]) -> list[schema.Sourc"""Collapse same-source, same-URL copies, keeping order and merging enrichment.Per-stream item ids (``R1``, ``X1``) collide across subqueries, so identity- is the normalized URL, not the id. The first occurrence stays in place and+ is :func:`source_item_key` (the normalized URL, or the HN discussion URL),+ not the id. The first occurrence stays in place andabsorbs later copies via :func:`merge_source_items`."""first_by_key: dict[tuple[str, str], schema.SourceItem] = {}kept: list[schema.SourceItem] = []for item in items:- key = (item.source, candidate_key(item))+ key = source_item_key(item)existing = first_by_key.get(key)if existing is None:first_by_key[key] = item@@ -327,6 +344,27 @@ def _diversify_pool(return pool[:pool_limit]+def _pin_snippet_to_primary_submission(candidate: schema.Candidate) -> None:+ """Keep a card's Evidence on the item whose metrics it shows.++ The card renders :func:`schema.candidate_primary_item`'s metrics beside+ ``candidate.snippet``. When the candidate also holds a distinct+ same-source sibling (two HN submissions of one article), the longest- or+ best-snippet rule above can pick the sibling's text, so one story's+ numbers would sit beside another story's words. Other candidates keep+ their snippet unchanged.+ """+ primary = schema.candidate_primary_item(candidate)+ if primary is None:+ return+ primary_key = source_item_key(primary)+ if any(+ item.source == primary.source and source_item_key(item) != primary_key+ for item in candidate.source_items+ ):+ candidate.snippet = primary.snippet or ""++def weighted_rrf(streams: dict[tuple[str, str], list[schema.SourceItem]],plan: schema.QueryPlan,@@ -348,7 +386,8 @@ def weighted_rrf(subqueries = {subquery.label: subquery for subquery in plan.subqueries}candidates: dict[str, schema.Candidate] = {}# Track source items already attached to each candidate, keyed by- # (source, normalized URL): per-stream ids collide across subqueries, and+ # source_item_key (source + normalized URL, or the HN discussion URL):+ # per-stream ids collide across subqueries, and# a repeat copy may carry enrichment the first one lacks.seen_source_items: dict[str, dict[tuple[str, str], schema.SourceItem]] = {}@@ -394,7 +433,7 @@ def weighted_rrf(source_items=[item],metadata=candidate_metadata,)- seen_source_items[key] = {(item.source, candidate_key(item)): item}+ seen_source_items[key] = {source_item_key(item): item}continuecandidate = candidates[key]@@ -420,10 +459,10 @@ def weighted_rrf(candidate.subquery_labels.append(label)if item.source not in candidate.sources:candidate.sources.append(item.source)- source_item_key = (item.source, candidate_key(item))- existing_item = seen_source_items[key].get(source_item_key)+ item_key = source_item_key(item)+ existing_item = seen_source_items[key].get(item_key)if existing_item is None:- seen_source_items[key][source_item_key] = item+ seen_source_items[key][item_key] = itemcandidate.source_items.append(item)else:merge_source_items(existing_item, item)@@ -443,6 +482,9 @@ def weighted_rrf(if len(candidate.snippet.split()) < len(item.snippet.split()):candidate.snippet = item.snippet+ for candidate in candidates.values():+ _pin_snippet_to_primary_submission(candidate)+fused = sorted(candidates.values(), key=_candidate_sort_key)fused = _apply_per_author_cap(fused, first_party_handles=first_party_handles)from . import rerankdiff --git a/tests/test_fusion_v3.py b/tests/test_fusion_v3.pyindex 4cefe41d..27741b59 100644--- a/tests/test_fusion_v3.py+++ b/tests/test_fusion_v3.py@@ -1,6 +1,6 @@import unittest-from lib import fusion, schema+from lib import fusion, render, schemadef make_item(item_id: str, source: str, url: str, title: str, rank_score: float) -> schema.SourceItem:@@ -623,3 +623,118 @@ class FusionEnrichedCopyTests(unittest.TestCase):self.assertIs(out[0], bare)self.assertEqual(3, len(out[0].metadata["top_comments"]))self.assertIs(out[1], other)+++def _hn_story(story_id: str, author: str, points: int, comments: list[dict], rank: float) -> schema.SourceItem:+ item = make_item(story_id, "hackernews", "https://sqlite.org/releaselog/3_54_0.html", "SQLite 3.54.0 Released", rank)+ item.author = author+ item.engagement = {"points": points, "comments": len(comments)}+ item.metadata["hn_url"] = f"https://news.ycombinator.com/item?id={story_id}"+ item.metadata["top_comments"] = comments+ return item+++class HackerNewsDuplicateSubmissionTests(unittest.TestCase):+ """Two HN submissions of one article URL are two stories, not two copies:+ each keeps its own points, comment count, discussion link, and comments."""++ def _plan(self):+ return schema.QueryPlan(+ intent="breaking_news",+ freshness_mode="strict_recent",+ cluster_mode="story",+ raw_topic="sqlite",+ subqueries=[+ schema.SubQuery(label="primary", search_query="sqlite", ranking_query="sqlite", sources=["hackernews", "reddit"], weight=1.0),+ schema.SubQuery(label="release", search_query="sqlite release", ranking_query="sqlite release", sources=["hackernews"], weight=0.8),+ ],+ source_weights={},+ )++ def _stories(self):+ comment = {"score": 0, "author": "ciupicri", "excerpt": "How nice of them to support Windows XP until now."}+ first = _hn_story("50040360", "thunderbong", 11, [], 0.6)+ second = _hn_story("50032781", "lawrencejgd", 6, [comment], 0.5)+ return first, second++ def _assert_unmerged(self, items):+ hn = {item.item_id: item for item in items if item.source == "hackernews"}+ self.assertEqual({"50040360", "50032781"}, set(hn))+ self.assertEqual({"points": 11, "comments": 0}, hn["50040360"].engagement)+ self.assertEqual([], hn["50040360"].metadata["top_comments"])+ self.assertEqual("https://news.ycombinator.com/item?id=50040360", hn["50040360"].metadata["hn_url"])+ self.assertEqual({"points": 6, "comments": 1}, hn["50032781"].engagement)+ self.assertEqual("ciupicri", hn["50032781"].metadata["top_comments"][0]["author"])++ def test_weighted_rrf_keeps_each_submission_engagement(self):+ first, second = self._stories()+ streams = {("primary", "hackernews"): [first], ("release", "hackernews"): [second]}++ candidates = fusion.weighted_rrf(streams, self._plan(), pool_limit=10)++ # Same article URL still clusters into one candidate.+ self.assertEqual(1, len(candidates))+ self._assert_unmerged(candidates[0].source_items)++ def test_same_submission_from_two_streams_still_merges(self):+ bare = _hn_story("50032781", "lawrencejgd", 6, [], 0.6)+ rich = _hn_story("50032781", "lawrencejgd", 6, [{"score": 0, "author": "ciupicri", "excerpt": "x"}], 0.4)+ streams = {("primary", "hackernews"): [bare], ("release", "hackernews"): [rich]}++ candidates = fusion.weighted_rrf(streams, self._plan(), pool_limit=10)++ self.assertEqual(1, len(candidates[0].source_items))+ self.assertEqual("ciupicri", candidates[0].source_items[0].metadata["top_comments"][0]["author"])++ def test_hn_and_reddit_of_same_article_share_a_candidate(self):+ first, _ = self._stories()+ reddit = make_item("R1", "reddit", "https://sqlite.org/releaselog/3_54_0.html", "SQLite 3.54.0 released", 0.5)+ streams = {("primary", "hackernews"): [first], ("primary", "reddit"): [reddit]}++ candidates = fusion.weighted_rrf(streams, self._plan(), pool_limit=10)++ self.assertEqual(1, len(candidates))+ self.assertEqual(["hackernews", "reddit"], sorted(item.source for item in candidates[0].source_items))++ def _evidence_line(self, candidate):+ lines = render._render_candidate(candidate, "1.")+ evidence = [line for line in lines if "Evidence:" in line]+ self.assertEqual(1, len(evidence), lines)+ return evidence[0]++ def test_card_evidence_comes_from_primary_submission(self):+ # The sibling submission has the longer snippet; the card shows the+ # primary story's metrics, so its Evidence must be the primary's text.+ first, second = self._stories()+ second.snippet = "How nice of them to support Windows XP until now, says ciupicri in a long comment."+ streams = {("primary", "hackernews"): [first], ("release", "hackernews"): [second]}++ candidate = fusion.weighted_rrf(streams, self._plan(), pool_limit=10)[0]+ primary = schema.candidate_primary_item(candidate)++ self.assertEqual("50040360", primary.item_id)+ self.assertEqual(primary.snippet, candidate.snippet)+ evidence = self._evidence_line(candidate)+ self.assertIn("SQLite 3.54.0 Released", evidence)+ self.assertNotIn("ciupicri", evidence)++ def test_card_evidence_matches_primary_when_sibling_scores_higher(self):+ # A later sibling that wins the primary-score comparison must not put+ # its text beside the first-attached submission's metrics either.+ first, second = self._stories()+ first.metadata["local_relevance"] = 0.3+ second.snippet = "How nice of them to support Windows XP until now, says ciupicri."+ streams = {("primary", "hackernews"): [first], ("release", "hackernews"): [second]}++ candidate = fusion.weighted_rrf(streams, self._plan(), pool_limit=10)[0]+ primary = schema.candidate_primary_item(candidate)++ self.assertEqual(primary.snippet, candidate.snippet)+ self.assertIn(primary.snippet, self._evidence_line(candidate))++ def test_collapse_duplicate_urls_keeps_distinct_submissions(self):+ first, second = self._stories()++ out = fusion.collapse_duplicate_urls([first, second])++ self._assert_unmerged(out)diff --git a/tests/test_pipeline_finalize.py b/tests/test_pipeline_finalize.pyindex ea22485d..0b696c65 100644--- a/tests/test_pipeline_finalize.py+++ b/tests/test_pipeline_finalize.py@@ -26,3 +26,33 @@ def test_finalize_merges_same_url_copies_and_keeps_comments():items = finalized["reddit"]assert len(items) == 1assert items[0].metadata["top_comments"][0]["score"] == 3293+++def _hn(story_id, points, comments, rank):+ item = schema.SourceItem(+ item_id=story_id,+ source="hackernews",+ title="SQLite 3.54.0 Released",+ body="SQLite 3.54.0 Released",+ url="https://sqlite.org/releaselog/3_54_0.html",+ engagement={"points": points, "comments": len(comments)},+ metadata={"hn_url": f"https://news.ycombinator.com/item?id={story_id}", "top_comments": comments},+ )+ item.local_rank_score = rank+ return item+++def test_finalize_keeps_two_hn_submissions_of_one_url_apart():+ comment = {"score": 0, "author": "ciupicri", "excerpt": "How nice of them to support Windows XP until now."}+ first = _hn("50040360", 11, [], 0.9)+ second = _hn("50032781", 6, [comment], 0.8)++ finalized = pipeline._finalize_items_by_source({"hackernews": [first, second]}, topic="sqlite", mock=True)++ # Text dedupe may drop the near-identical second story, but no story may+ # carry another story's comment count or comments.+ for item in finalized["hackernews"]:+ assert item.metadata["hn_url"].endswith(item.item_id)+ assert item.engagement["comments"] == len(item.metadata["top_comments"])+ by_id = {item.item_id: item for item in finalized["hackernews"]}+ assert by_id["50040360"].engagement == {"points": 11, "comments": 0}