"""Syndication dedupe: collapse wire copies before the threshold/cap runs.""" from __future__ import annotations import json import pytest import summarizer from intel import ( DEFAULT_DEDUPE_SIMILARITY, dedupe_blocks, normalize_title, select_graded, title_similarity, ) # Real titles/scores/categories/ids from summary_id=6 (the measured defect): # 21 graded articles, 9 distinct titles, 12 of them two wire stories. OBSERVED_RUN = [ (95, "www.kcci.com", "politics", 17263, "Trump, Xi and Putin plan an unprecedented joint meeting on the sidelines of APEC, White House says"), (95, "www.wyff4.com", "politics", 18546, "Trump, Xi and Putin plan an unprecedented joint meeting on the sidelines of APEC, White House says"), (95, "www.wtae.com", "politics", 18550, "Trump, Xi and Putin plan an unprecedented joint meeting on the sidelines of APEC, White House says"), (92, "www.koat.com", "politics", 17272, "Trump, Xi and Putin plan an unprecedented joint meeting on the sidelines of APEC, White House says"), (92, "www.ketv.com", "politics", 17291, "Trump, Xi and Putin plan an unprecedented joint meeting on the sidelines of APEC, White House says"), (92, "www.wlky.com", "politics", 18205, "Trump, Xi and Putin plan an unprecedented joint meeting on the sidelines of APEC, White House says"), (92, "www.wbaltv.com", "politics", 18297, "Trump, Xi and Putin plan an unprecedented joint meeting on the sidelines of APEC, White House says"), (75, "www.wlky.com", "other", 23748, "Interactive graphic shows the dramatic impact of Friday's FAA ground stop"), (75, "www.wtae.com", "other", 24029, "Interactive graphic shows the dramatic impact of Friday's FAA ground stop"), (60, "www.kcci.com", "other", 22643, "Interactive graphic shows the dramatic impact of Friday's FAA ground stop"), (60, "www.ketv.com", "other", 22664, "Interactive graphic shows the dramatic impact of Friday's FAA ground stop"), (60, "www.koat.com", "other", 22683, "Interactive graphic shows the dramatic impact of Friday's FAA ground stop"), (60, "www.wbaltv.com", "other", 23708, "Interactive graphic shows the dramatic impact of Friday's FAA ground stop"), (55, "www.wlky.com", "environment/disaster", 23943, "Wild video shows the moment a tanker struck a docked cruise ship in New Orleans"), (55, "www.wyff4.com", "other", 24087, "Interactive graphic shows the dramatic impact of Friday's FAA ground stop"), (45, "www.straitstimes.com", "other", 21227, "Over 600 personnel take part in multi-agency exercise at RTS Link Woodlands North station"), (30, "nypost.com", "crime", 16888, "Monster ex-cop sentenced to chemical castration for raping young kids: “We will take his manhood!”"), (5, "www.excelsior.com.mx", "other", 17414, ""), (5, "nypost.com", "sport", 22376, "Rangers’ Dylan Garand gets full-circle moment in return to British Columbia"), (5, "nypost.com", "sport", 22427, "Chargers get harsh reality check from edge rusher as frustration builds: ‘Walk upstairs and ask them’"), (5, "www.channelnewsasia.com", "sport", 23026, "Svitolina says daughter remains priority after split from Monfils"), ] def _blocks(rows) -> list[dict]: return [ { "position": index, "article_id": article_id, "score": score, "category": category, "domain": domain, "title": title, "text": f"Article {index + 1}:\n- Score: {score}\n- Title: {title}", } for index, (score, domain, category, article_id, title) in enumerate(rows) ] def _story(title, *, score=90, article_id=None, category="politics", domain="ex.com", position=0): return { "position": position, "article_id": article_id, "score": score, "category": category, "domain": domain, "title": title, "text": f"Article {position + 1}:\n- Score: {score}", } # ── title normalisation ─────────────────────────────────────────────────── @pytest.mark.parametrize( "title,expected", [ ("Big story - KCCI", "big story"), ("Big story | CNN", "big story"), ("Big story — AP", "big story"), ("Big story – AP", "big story"), (" Big STORY!! ", "big story"), ("Trump–Xi–Putin summit", "trump xi putin summit"), ], ) def test_normalize_title(title, expected): assert normalize_title(title) == expected @pytest.mark.parametrize("title", [None, "", " ", 12345, ["not", "a", "title"]]) def test_normalize_title_never_raises(title): assert isinstance(normalize_title(title), str) def test_serial_titles_are_not_treated_as_a_source_suffix(): assert normalize_title("Governor's Board – Part 1") != normalize_title( "Governor's Board – Part 2" ) # ── grouping ────────────────────────────────────────────────────────────── def test_exact_title_duplicates_collapse_to_the_best_scoring_copy(): blocks = _blocks( [ (70, "a.com", "politics", 1, "Storm hits the coast"), (95, "b.com", "politics", 2, "Storm hits the coast - KCCI"), (80, "c.com", "politics", 3, "Storm hits the coast"), ] ) kept, stats = dedupe_blocks(blocks) assert len(kept) == 1 assert kept[0]["article_id"] == 2 # highest score wins, not the earliest assert stats["input"] == 3 and stats["kept"] == 1 and stats["duplicates"] == 2 assert {record["article_id"] for record in stats["duplicate_blocks"]} == {1, 3} assert all( record["duplicate_of"] == 2 for record in stats["duplicate_blocks"] ) assert all( record["duplicate_of_position"] == 1 for record in stats["duplicate_blocks"] ) def test_hearst_style_syndication_set_collapses_to_one(): domains = [ "www.kcci.com", "www.wtae.com", "www.wyff4.com", "www.wbaltv.com", "www.koat.com", "www.ketv.com", "www.wlky.com", ] headline = "Flights halted at airports across US due to air traffic control problems" blocks = [ _story(headline, score=90 - i, article_id=100 + i, domain=domain, position=i) for i, domain in enumerate(domains) ] kept, stats = dedupe_blocks(blocks) assert len(kept) == 1 assert kept[0]["article_id"] == 100 assert stats["duplicates"] == 6 assert len({record["duplicate_of"] for record in stats["duplicate_blocks"]}) == 1 def test_rewrites_above_the_threshold_merge_and_below_do_not(): original = "Flights halted at airports across US due to air traffic control communications problems" u_s_variant = "Flights halted at airports across U.S. due to air traffic control communications problems" other_story = "Flights halted at airports across US as a snowstorm closes runways" assert title_similarity(normalize_title(original), normalize_title(u_s_variant)) >= 0.85 assert title_similarity(normalize_title(original), normalize_title(other_story)) < 0.85 kept, stats = dedupe_blocks( [_story(original, article_id=1), _story(u_s_variant, article_id=2, score=80)] ) assert [block["article_id"] for block in kept] == [1] assert stats["duplicates"] == 1 assert stats["duplicate_blocks"][0]["similarity"] >= 0.85 kept, stats = dedupe_blocks( [_story(original, article_id=1), _story(other_story, article_id=2, score=80)] ) assert len(kept) == 2 assert stats["duplicates"] == 0 def test_threshold_is_tunable(): left = "Storm batters the coast with heavy rain and wind" right = "Storm batters the coast with heavy rain, flooding and wind" assert len(dedupe_blocks([_story(left), _story(right, score=80)], similarity=0.75)[0]) == 1 assert len(dedupe_blocks([_story(left), _story(right, score=80)], similarity=0.99)[0]) == 2 def test_different_categories_are_never_merged(): headline = "Officials announce the election result" blocks = [ _story(headline, article_id=1, category="politics"), _story(headline, article_id=2, score=80, category="military/conflict"), _story(headline, article_id=3, score=70, category=None), ] kept, stats = dedupe_blocks(blocks) # politics != military/conflict -> kept apart; NULL category may join politics. assert [block["article_id"] for block in kept] == [1, 2] assert stats["duplicates"] == 1 assert stats["duplicate_blocks"][0]["article_id"] == 3 def test_titles_disagreeing_on_a_number_stay_separate(): blocks = [ _story("Governor's Commutation Advisory Board – Part 1", article_id=1), _story("Governor's Commutation Advisory Board – Part 2", article_id=2, score=80), _story("Quake kills 12 in the northern province", article_id=3, score=70), _story("Quake kills 21 in the northern province", article_id=4, score=60), ] kept, stats = dedupe_blocks(blocks) assert len(kept) == 4 assert stats["duplicates"] == 0 def test_ties_keep_the_earliest_position(): blocks = _blocks( [ (90, "a.com", "politics", 11, "Identical headline"), (90, "b.com", "politics", 12, "Identical headline"), ] ) kept, stats = dedupe_blocks(blocks) assert [block["article_id"] for block in kept] == [11] assert stats["duplicate_blocks"][0]["duplicate_of"] == 11 def test_kept_blocks_stay_in_original_order(): blocks = _blocks( [ (10, "a.com", "sport", 1, "Rangers beat the Chargers"), (95, "b.com", "politics", 2, "Summit announced"), (20, "c.com", "sport", 3, "Svitolina wins in straight sets"), ] ) kept, _ = dedupe_blocks(blocks) assert [block["article_id"] for block in kept] == [1, 2, 3] # ── robustness ──────────────────────────────────────────────────────────── @pytest.mark.parametrize("blocks", [[], None]) def test_empty_input_is_returned_untouched(blocks): kept, stats = dedupe_blocks(blocks) assert kept == [] assert stats["input"] == 0 and stats["kept"] == 0 and stats["duplicates"] == 0 def test_missing_and_null_titles_are_kept_and_never_merged(): blocks = [ {"position": 0, "score": 90, "text": "a"}, # no title key {"position": 1, "score": 80, "title": None, "text": "b"}, {"position": 2, "score": 70, "title": "", "text": "c"}, {"position": 3, "score": 60, "title": " ", "text": "d"}, {"position": 4, "score": 50, "title": "Real headline", "text": "e"}, ] kept, stats = dedupe_blocks(blocks) assert len(kept) == 5 assert stats["duplicates"] == 0 def test_malformed_blocks_do_not_raise(): kept, stats = dedupe_blocks( [ "not a dict", {"position": 0, "score": "high", "title": "Headline", "text": "a"}, {"position": 1, "score": None, "title": 42, "text": "b"}, ] ) assert len(kept) == 2 assert stats["input"] == 2 def test_kill_switch_bypasses_everything(): blocks = _blocks( [ (95, "a.com", "politics", 1, "Same headline"), (94, "b.com", "politics", 2, "Same headline"), ] ) kept, stats = dedupe_blocks(blocks, enabled=False) assert [block["article_id"] for block in kept] == [1, 2] assert stats["duplicates"] == 0 assert stats["kept"] == 2 def test_dedupe_config_reads_the_environment(monkeypatch): monkeypatch.delenv("SUMMARY_DEDUPE", raising=False) monkeypatch.delenv("SUMMARY_DEDUPE_SIMILARITY", raising=False) assert summarizer.dedupe_config() == (True, DEFAULT_DEDUPE_SIMILARITY) monkeypatch.setenv("SUMMARY_DEDUPE", "0") assert summarizer.dedupe_config()[0] is False monkeypatch.setenv("SUMMARY_DEDUPE", "off") assert summarizer.dedupe_config()[0] is False monkeypatch.setenv("SUMMARY_DEDUPE_SIMILARITY", "0.95") assert summarizer.dedupe_config() == (False, 0.95) monkeypatch.setenv("SUMMARY_DEDUPE_SIMILARITY", "nonsense") assert summarizer.dedupe_config()[1] == DEFAULT_DEDUPE_SIMILARITY monkeypatch.setenv("SUMMARY_DEDUPE_SIMILARITY", "7") assert summarizer.dedupe_config()[1] == 1.0 # ── replay of the measured run (summary id=6) ───────────────────────────── def test_replay_of_summary_6_collapses_21_to_9_and_selects_2(): blocks = _blocks(OBSERVED_RUN) assert len(blocks) == 21 assert len({normalize_title(block["title"]) for block in blocks}) == 9 kept, stats = dedupe_blocks(blocks) assert stats["input"] == 21 assert stats["kept"] == 9 assert stats["duplicates"] == 12 assert len(kept) == 9 selected, fallback = select_graded(kept, min_score=60, top_n=12, fallback_top=3) assert fallback is False assert [block["score"] for block in selected] == [95, 75] assert [block["article_id"] for block in selected] == [17263, 23748] # Every one of the 12 dropped copies points at one of the two survivors. survivors = {record["duplicate_of"] for record in stats["duplicate_blocks"]} assert survivors == {17263, 23748} # 11 dropped copies still score above SUMMARY_MIN_SCORE; none is selected. dropped_above = [ record for record in stats["duplicate_blocks"] if record["score"] >= 60 ] assert len(dropped_above) == 11 # ── wiring: one article_scores row per graded article ───────────────────── class _FakeCursor: def __init__(self, log: list): self.log = log self._sql = "" def execute(self, sql, params=None): self._sql = " ".join(sql.split()) self.log.append(("execute", self._sql, params)) def executemany(self, sql, rows): self.log.append(("executemany", " ".join(sql.split()), list(rows))) def fetchone(self): if "article_summaries" in self._sql: return (77,) return None def fetchall(self): return [] def close(self): pass class _FakeConn: def __init__(self, log: list): self.log = log def cursor(self): return _FakeCursor(self.log) def commit(self): pass def close(self): pass def _map_block(n: int, score: int) -> str: return "\n".join( [ f"Article {n}:", f"- Score: {score}", "- Fact bullet", "- Category: politics", "- Importance: high", ] ) def test_duplicates_are_persisted_unselected_with_duplicate_of(monkeypatch): """Full summarize_news flow: 4 graded articles, 2 of them the same story.""" summerizer_articles = [ {"id": 1, "title": "Summit announced in the region", "content": "x" * 120, "url": "https://a.com/1", "domain": "a.com"}, {"id": 2, "title": "Summit announced in the region - KCCI", "content": "x" * 120, "url": "https://b.com/2", "domain": "b.com"}, {"id": 3, "title": "Tanker strikes a docked cruise ship", "content": "x" * 120, "url": "https://c.com/3", "domain": "c.com"}, {"id": 4, "title": "Rangers win in overtime", "content": "x" * 120, "url": "https://d.com/4", "domain": "d.com"}, ] map_reply = "\n\n".join( [_map_block(1, 95), _map_block(2, 92), _map_block(3, 55), _map_block(4, 5)] ) reduce_reply = json.dumps({"summary_en": "Brief.", "ticker": [], "map_items": []}) db_log: list = [] prompts: list[str] = [] def fake_chat(prompt, *, api_key, model, base_url, json_mode=False): prompts.append(prompt) return reduce_reply if json_mode else map_reply monkeypatch.setenv("NOUS_API_KEY", "test-key") monkeypatch.setenv("SUMMARY_MODEL", "test-model") monkeypatch.delenv("SUMMARY_DEDUPE", raising=False) monkeypatch.delenv("SUMMARY_DEDUPE_SIMILARITY", raising=False) monkeypatch.setattr(summarizer, "BATCH_SIZE", 10) monkeypatch.setattr(summarizer, "call_llm", fake_chat) monkeypatch.setattr(summarizer, "get_recent_news", lambda *a, **k: summerizer_articles) monkeypatch.setattr(summarizer, "_already_summarized_this_interval", lambda: False) monkeypatch.setattr(summarizer, "ensure_tables", lambda: None) monkeypatch.setattr(summarizer.psycopg2, "connect", lambda **kwargs: _FakeConn(db_log)) summarizer.summarize_news() reduce_prompt = prompts[-1] assert "Score: 95" in reduce_prompt assert "Score: 92" not in reduce_prompt # wire copy never reaches reduce rows = [entry[2] for entry in db_log if entry[0] == "executemany"] assert rows, db_log by_article = {row[0]: row for row in rows[-1]} assert sorted(by_article) == [1, 2, 3, 4] # one row per graded article assert by_article[1][4] is True and by_article[1][6] is None assert by_article[2][4] is False and by_article[2][6] == 1 # duplicate_of assert by_article[3][4] is False and by_article[3][6] is None assert by_article[4][4] is False and by_article[4][6] is None