test_news_mcp.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911
  1. from __future__ import annotations
  2. from contextlib import contextmanager
  3. import tempfile
  4. from pathlib import Path
  5. from datetime import datetime, timezone
  6. from news_mcp.dedup.cluster import dedup_and_cluster_articles
  7. from news_mcp.storage.sqlite_store import SQLiteClusterStore
  8. from news_mcp.enrichment.importance import compute_importance
  9. from news_mcp.enrichment.llm_enrich import _filter_entities, _matches_blacklist
  10. from news_mcp.entity_normalize import normalize_query, normalize_entities
  11. from news_mcp.llm import build_extraction_prompt, call_llm, load_prompt
  12. from news_mcp.trends_resolution import resolve_entity_via_trends
  13. from news_mcp.mcp_server_fastmcp import _sort_clusters_by_recency
  14. def _article(title: str, url: str = None, source: str = "Src", ts: str = "Mon, 30 Mar 2026 12:00:00 GMT"):
  15. if url is None:
  16. import hashlib
  17. url = f"https.example.com/{hashlib.md5(title.encode()).hexdigest()[:10]}"
  18. return {
  19. "title": title,
  20. "url": url,
  21. "source": source,
  22. "timestamp": ts,
  23. "summary": "summary text",
  24. }
  25. def test_dedup_merges_similar_titles():
  26. articles = [
  27. _article("Trump warns Iran war could spread"),
  28. _article("Trump warns Iran conflict could spread"),
  29. _article("Unrelated sports result"),
  30. ]
  31. clustered = dedup_and_cluster_articles(articles, similarity_threshold=0.75)
  32. # We expect the Trump/Iran items to be merged into one cluster in the same topic bucket.
  33. total_clusters = sum(len(v) for v in clustered.values())
  34. assert total_clusters == 2
  35. def test_sqlite_feed_hash_roundtrip():
  36. with tempfile.TemporaryDirectory() as td:
  37. db = Path(td) / "news.sqlite"
  38. store = SQLiteClusterStore(db)
  39. assert store.get_feed_hash("breakingthenews") is None
  40. store.set_feed_hash("breakingthenews", "abc123")
  41. assert store.get_feed_hash("breakingthenews") == "abc123"
  42. def test_sqlite_summary_cache_roundtrip():
  43. with tempfile.TemporaryDirectory() as td:
  44. db = Path(td) / "news.sqlite"
  45. store = SQLiteClusterStore(db)
  46. # Upsert a base cluster first.
  47. store.upsert_clusters([
  48. {
  49. "cluster_id": "cid1",
  50. "headline": "Headline",
  51. "summary": "Summary",
  52. "entities": ["Iran"],
  53. "sentiment": "negative",
  54. "importance": 0.5,
  55. "sources": ["BreakingTheNews"],
  56. "timestamp": "Mon, 30 Mar 2026 12:00:00 GMT",
  57. "articles": [],
  58. "first_seen": "Mon, 30 Mar 2026 12:00:00 GMT",
  59. "last_updated": "Mon, 30 Mar 2026 12:00:00 GMT",
  60. }
  61. ], topic="other")
  62. store.upsert_cluster_summary(
  63. "cid1",
  64. {
  65. "headline": "Headline",
  66. "mergedSummary": "Merged summary",
  67. "keyFacts": ["Fact 1"],
  68. "sources": ["BreakingTheNews"],
  69. },
  70. )
  71. cached = store.get_cluster_summary("cid1", ttl_hours=24)
  72. assert cached is not None
  73. assert cached["mergedSummary"] == "Merged summary"
  74. assert cached["keyFacts"] == ["Fact 1"]
  75. def test_sqlite_summary_cache_does_not_create_placeholder_row():
  76. with tempfile.TemporaryDirectory() as td:
  77. db = Path(td) / "news.sqlite"
  78. store = SQLiteClusterStore(db)
  79. store.upsert_cluster_summary(
  80. "missing",
  81. {
  82. "headline": "Missing",
  83. "mergedSummary": "Summary",
  84. "keyFacts": [],
  85. "sources": [],
  86. },
  87. )
  88. assert store.get_cluster_by_id("missing") is None
  89. assert store.get_cluster_summary("missing", ttl_hours=24) is None
  90. def test_prune_clusters_deletes_rows_older_than_retention():
  91. with tempfile.TemporaryDirectory() as td:
  92. db = Path(td) / "news.sqlite"
  93. store = SQLiteClusterStore(db)
  94. store.upsert_clusters([
  95. {
  96. "cluster_id": "fresh",
  97. "headline": "Fresh",
  98. "summary": "Fresh summary",
  99. "entities": ["Bitcoin"],
  100. "timestamp": "Wed, 01 Apr 2026 12:00:00 GMT",
  101. "articles": [],
  102. },
  103. {
  104. "cluster_id": "stale",
  105. "headline": "Stale",
  106. "summary": "Stale summary",
  107. "entities": ["Iran"],
  108. "timestamp": "Wed, 01 Apr 2026 11:00:00 GMT",
  109. "articles": [],
  110. },
  111. ], topic="other")
  112. with store._conn() as conn:
  113. conn.execute(
  114. "UPDATE clusters SET updated_at=? WHERE cluster_id=?",
  115. ("2025-01-01T00:00:00+00:00", "stale"),
  116. )
  117. deleted = store.prune_clusters(retention_days=30)
  118. assert deleted == 1
  119. assert store.get_cluster_by_id("stale") is None
  120. assert store.get_cluster_by_id("fresh") is not None
  121. assert store.get_prune_state(pruning_enabled=True, retention_days=30, interval_hours=24)["last_prune_at"] is not None
  122. def test_prune_if_due_skips_deletes_when_pruning_disabled():
  123. with tempfile.TemporaryDirectory() as td:
  124. db = Path(td) / "news.sqlite"
  125. store = SQLiteClusterStore(db)
  126. store.upsert_clusters([
  127. {
  128. "cluster_id": "stale",
  129. "headline": "Stale",
  130. "summary": "Stale summary",
  131. "entities": ["Iran"],
  132. "timestamp": "Wed, 01 Apr 2026 11:00:00 GMT",
  133. "articles": [],
  134. }
  135. ], topic="other")
  136. with store._conn() as conn:
  137. conn.execute(
  138. "UPDATE clusters SET updated_at=? WHERE cluster_id=?",
  139. ("2025-01-01T00:00:00+00:00", "stale"),
  140. )
  141. result = store.prune_if_due(pruning_enabled=False, retention_days=30, interval_hours=24)
  142. assert result["enabled"] is False
  143. assert result["deleted"] == 0
  144. assert store.get_cluster_by_id("stale") is not None
  145. def test_get_latest_clusters_orders_by_updated_at_before_limit():
  146. with tempfile.TemporaryDirectory() as td:
  147. db = Path(td) / "news.sqlite"
  148. store = SQLiteClusterStore(db)
  149. store.upsert_clusters(
  150. [
  151. {
  152. "cluster_id": "old",
  153. "headline": "Old",
  154. "summary": "Old summary",
  155. "entities": ["Iran"],
  156. "timestamp": "Wed, 01 Apr 2026 09:00:00 GMT",
  157. "articles": [],
  158. },
  159. {
  160. "cluster_id": "new",
  161. "headline": "New",
  162. "summary": "New summary",
  163. "entities": ["Bitcoin"],
  164. "timestamp": "Wed, 01 Apr 2026 11:00:00 GMT",
  165. "articles": [],
  166. },
  167. ],
  168. topic="crypto",
  169. )
  170. with store._conn() as conn:
  171. conn.execute("UPDATE clusters SET updated_at=? WHERE cluster_id=?", ("2025-01-01T00:00:00+00:00", "new"))
  172. conn.execute("UPDATE clusters SET updated_at=? WHERE cluster_id=?", ("2026-01-01T00:00:00+00:00", "old"))
  173. latest = store.get_latest_clusters(topic="crypto", ttl_hours=24 * 365, limit=1)
  174. assert len(latest) == 1
  175. assert latest[0]["cluster_id"] == "new"
  176. def test_get_entity_metadata_prefers_mid_scoped_row():
  177. with tempfile.TemporaryDirectory() as td:
  178. db = Path(td) / "news.sqlite"
  179. store = SQLiteClusterStore(db)
  180. store.upsert_entity_metadata("Bitcoin", canonical_label="Bitcoin", mid=None, sources=["local"])
  181. store.upsert_entity_metadata("Bitcoin", canonical_label="Bitcoin", mid="/m/Bitcoin", sources=["trends"])
  182. store.record_entity_request("Bitcoin", mid="/m/Bitcoin")
  183. meta = store.get_entity_metadata("Bitcoin")
  184. assert meta is not None
  185. assert meta["mid"] == "/m/Bitcoin"
  186. def test_blacklist_filters_entities_case_insensitively():
  187. entities = ["Bloomberg", "Reuters", "bloomberg", "CoinDesk"]
  188. filtered = _filter_entities(entities, blacklist=["bloomberg"])
  189. assert filtered == ["Reuters", "CoinDesk"]
  190. def test_blacklist_supports_wildcards():
  191. assert _matches_blacklist("Bloomberg Economics", blacklist=["bloomberg*"])
  192. assert _matches_blacklist("bloomberg", blacklist=["*berg"])
  193. assert not _matches_blacklist("Reuters", blacklist=["bloomberg*"])
  194. def test_query_normalization_keeps_common_shorthand_working():
  195. assert normalize_query("btc") == "Bitcoin"
  196. assert normalize_query("Trump") == "Donald Trump"
  197. assert normalize_query("nvidia") == "nvidia"
  198. def test_entity_normalization_deduplicates_aliases():
  199. assert normalize_entities(["btc", "Bitcoin", "BTC", "Ethereum"]) == ["Bitcoin", "Ethereum"]
  200. def test_load_prompt_reads_prompt_files():
  201. text = load_prompt("extract_entities.prompt")
  202. assert "Return STRICT JSON" in text
  203. def test_resolve_entity_falls_back_cleanly_when_provider_unavailable(monkeypatch):
  204. import news_mcp.trends_resolution as trends_resolution
  205. trends_resolution.resolve_entity_via_trends.cache_clear()
  206. trends_resolution._provider.cache_clear()
  207. monkeypatch.setattr(trends_resolution, "_provider", lambda: None)
  208. resolved = resolve_entity_via_trends("btc")
  209. assert resolved["normalized"] == "Bitcoin"
  210. assert resolved["canonical_label"] == "Bitcoin"
  211. assert resolved["mid"] is None
  212. assert resolved["candidates"] == []
  213. assert resolved["source"] == "fallback"
  214. trends_resolution.resolve_entity_via_trends.cache_clear()
  215. def test_sort_clusters_by_recency_prefers_newer_timestamp_over_importance():
  216. clusters = [
  217. {"headline": "older", "timestamp": "Wed, 01 Apr 2026 10:00:00 GMT", "importance": 0.9},
  218. {"headline": "newer", "timestamp": "Wed, 01 Apr 2026 11:00:00 GMT", "importance": 0.1},
  219. ]
  220. sorted_clusters = _sort_clusters_by_recency(clusters)
  221. assert [c["headline"] for c in sorted_clusters] == ["newer", "older"]
  222. def test_build_extraction_prompt_is_stable_without_blacklist():
  223. cluster = {
  224. "headline": "Bloomberg reports Bitcoin rallies after US rate comments",
  225. "summary": "A report from Bloomberg says Bitcoin moved higher after comments from the Fed.",
  226. "articles": [],
  227. }
  228. prompt = build_extraction_prompt(cluster)
  229. assert "Bloomberg reports Bitcoin rallies" in prompt
  230. assert "Do NOT return empty entities" in prompt
  231. assert "Bloomberg" in prompt # present in the input, not filtered here
  232. def test_call_llm_dispatches_to_selected_provider(monkeypatch):
  233. async def fake_groq(model, messages, response_json=True):
  234. return '{"ok": true, "provider": "groq"}'
  235. async def fake_openai(model, messages, response_json=True):
  236. return '{"ok": true, "provider": "openai"}'
  237. monkeypatch.setattr("news_mcp.llm._call_groq", fake_groq)
  238. monkeypatch.setattr("news_mcp.llm._call_openai", fake_openai)
  239. import asyncio
  240. groq = asyncio.run(call_llm("groq", "x", "sys", "user"))
  241. openai = asyncio.run(call_llm("openai", "x", "sys", "user"))
  242. assert '"provider": "groq"' in groq
  243. assert '"provider": "openai"' in openai
  244. def test_refresh_skips_reprocessing_when_feed_hash_is_unchanged(monkeypatch):
  245. import news_mcp.jobs.poller as poller
  246. import hashlib
  247. from news_mcp.config import NEWS_FEED_URL, NEWS_FEED_URLS
  248. calls = {"fetch": 0, "cluster": 0, "enrich": 0, "classify": 0}
  249. rss_urls = [u.strip() for u in NEWS_FEED_URLS.split(",") if u.strip()] or [NEWS_FEED_URL]
  250. material = "\n".join(
  251. [
  252. "Bitcoin rallies|https://example.com/a|Wed, 01 Apr 2026 12:00:00 GMT",
  253. ]
  254. )
  255. expected_hash = hashlib.sha1(material.encode("utf-8")).hexdigest()
  256. async def fake_to_thread(fn, limit):
  257. calls["fetch"] += 1
  258. return [
  259. {
  260. "title": "Bitcoin rallies",
  261. "url": "https://example.com/a",
  262. "source": "Src",
  263. "timestamp": "Wed, 01 Apr 2026 12:00:00 GMT",
  264. "summary": "summary",
  265. }
  266. ]
  267. def fake_cluster(articles):
  268. calls["cluster"] += 1
  269. return {
  270. "crypto": [
  271. {
  272. "cluster_id": "cid",
  273. "headline": "Bitcoin rallies",
  274. "summary": "summary",
  275. "entities": [],
  276. "sentiment": "neutral",
  277. "importance": 0.0,
  278. "sources": ["Src"],
  279. "timestamp": "Wed, 01 Apr 2026 12:00:00 GMT",
  280. "articles": [],
  281. }
  282. ]
  283. }
  284. def fake_enrich(cluster):
  285. calls["enrich"] += 1
  286. return cluster
  287. async def fake_classify(cluster):
  288. calls["classify"] += 1
  289. return cluster
  290. class DummyStore:
  291. def __init__(self, *args, **kwargs):
  292. self.meta = {}
  293. self.feed_hash = expected_hash
  294. @contextmanager
  295. def _conn(self):
  296. class _Conn:
  297. def execute(self, *args, **kwargs):
  298. return None
  299. yield _Conn()
  300. def get_feed_hash(self, feed_key):
  301. return self.feed_hash
  302. def set_feed_hash(self, feed_key, last_hash):
  303. self.feed_hash = last_hash
  304. def set_feed_state(self, feed_key, last_hash, item_count):
  305. self.feed_hash = last_hash
  306. def get_enabled_feed_urls(self, feed_urls):
  307. return feed_urls
  308. def get_cluster_by_id(self, cluster_id):
  309. return None
  310. def upsert_clusters(self, clusters, topic):
  311. self.meta["upserted"] = (len(clusters), topic)
  312. def prune_if_due(self, **kwargs):
  313. self.meta["prune"] = kwargs
  314. return {"deleted": 0}
  315. def get_latest_clusters_all_topics(self, ttl_hours=24, limit=500):
  316. return []
  317. def set_meta(self, key, value):
  318. self.meta[key] = value
  319. monkeypatch.setattr(poller, "SQLiteClusterStore", DummyStore)
  320. async def _mock_fetch(limit, url_list=None):
  321. calls["fetch"] += 1
  322. return [{"title": "Bitcoin rallies", "url": "https://example.com/a", "timestamp": "Wed, 01 Apr 2026 12:00:00 GMT"}]
  323. monkeypatch.setattr(poller, "fetch_news_articles", _mock_fetch)
  324. monkeypatch.setattr(poller.asyncio, "to_thread", fake_to_thread)
  325. monkeypatch.setattr(poller, "dedup_and_cluster_articles", fake_cluster)
  326. monkeypatch.setattr(poller, "enrich_cluster", fake_enrich)
  327. monkeypatch.setattr(poller, "classify_cluster_llm", fake_classify)
  328. poller.store = None
  329. async def run_once():
  330. await poller.refresh_clusters(topic=None, limit=80)
  331. import asyncio
  332. asyncio.run(run_once())
  333. assert calls["fetch"] == 1
  334. assert calls["cluster"] == 0
  335. assert calls["enrich"] == 0
  336. assert calls["classify"] == 0
  337. def test_importance_prefers_llm_signal():
  338. # Two clusters with same coverage but different sentiment magnitude.
  339. base = {
  340. "sources": ["A", "B"],
  341. "articles": [{}, {}],
  342. "sentiment": "neutral",
  343. "sentimentScore": 0.0,
  344. }
  345. pos = dict(base, sentimentScore=0.9)
  346. neg = dict(base, sentimentScore=-0.8)
  347. imp_base = compute_importance(base)
  348. imp_pos = compute_importance(pos)
  349. imp_neg = compute_importance(neg)
  350. assert imp_pos >= imp_base
  351. assert imp_neg >= imp_base
  352. # ---------------------------------------------------------------------------
  353. # Regression tests for the May 2026 correctness pass
  354. # ---------------------------------------------------------------------------
  355. def test_classify_cluster_llm_uses_llm_topic_and_drops_invalid_ones(monkeypatch):
  356. """The LLM-extracted topic must propagate to the returned cluster, but
  357. free-form / hallucinated topic strings must be coerced into the allowed
  358. set so they never reach the SQL row column verbatim."""
  359. import asyncio
  360. from news_mcp.enrichment import llm_enrich
  361. async def fake_extraction(cluster):
  362. return {
  363. "topic": "regulation",
  364. "entities": ["SEC"],
  365. "sentiment": "neutral",
  366. "sentimentScore": 0.0,
  367. "keywords": ["enforcement"],
  368. }
  369. monkeypatch.setattr(llm_enrich, "call_extraction", fake_extraction)
  370. monkeypatch.setattr(llm_enrich, "resolve_entity_via_trends", lambda e: {"normalized": e, "canonical_label": e, "mid": None})
  371. cluster = {"cluster_id": "x", "headline": "SEC fines firm", "summary": "...", "topic": "other"}
  372. out = asyncio.run(llm_enrich.classify_cluster_llm(cluster))
  373. assert out["topic"] == "regulation"
  374. # Hallucinated topic is rejected; we fall back to the input cluster's
  375. # heuristic topic when it is one of the allowed ones.
  376. async def fake_extraction_garbage(cluster):
  377. return {
  378. "topic": "geopolitics-and-stuff",
  379. "entities": ["NATO"],
  380. "sentiment": "neutral",
  381. "sentimentScore": 0.0,
  382. "keywords": [],
  383. }
  384. monkeypatch.setattr(llm_enrich, "call_extraction", fake_extraction_garbage)
  385. cluster = {"cluster_id": "y", "headline": "NATO meets", "summary": "...", "topic": "macro"}
  386. out = asyncio.run(llm_enrich.classify_cluster_llm(cluster))
  387. assert out["topic"] == "macro" # heuristic fallback
  388. # When neither the LLM nor the heuristic gives a valid label -> "other".
  389. cluster = {"cluster_id": "z", "headline": "...", "summary": "...", "topic": "geopolitics-bucket"}
  390. out = asyncio.run(llm_enrich.classify_cluster_llm(cluster))
  391. assert out["topic"] == "other"
  392. def test_classify_cluster_llm_normalizes_aliases_before_blacklist(monkeypatch):
  393. """Regression: previously ``_filter_entities`` ran before
  394. ``normalize_entities``, so blacklisting "bitcoin" missed entries the LLM
  395. returned as the alias "btc". Order is now normalize -> blacklist."""
  396. import asyncio
  397. from news_mcp.enrichment import llm_enrich
  398. async def fake_extraction(cluster):
  399. return {
  400. "topic": "crypto",
  401. "entities": ["btc", "Reuters"],
  402. "sentiment": "neutral",
  403. "sentimentScore": 0.0,
  404. "keywords": ["btc rally", "Reuters"],
  405. }
  406. monkeypatch.setattr(llm_enrich, "call_extraction", fake_extraction)
  407. monkeypatch.setattr(llm_enrich, "resolve_entity_via_trends", lambda e: {"normalized": e, "canonical_label": e, "mid": None})
  408. monkeypatch.setattr(llm_enrich, "NEWS_ENTITY_BLACKLIST", ["bitcoin"])
  409. cluster = {"cluster_id": "x", "headline": "BTC up", "summary": "...", "topic": "crypto"}
  410. out = asyncio.run(llm_enrich.classify_cluster_llm(cluster))
  411. # "btc" became "Bitcoin" via aliasing, then was filtered out by the
  412. # blacklist. "Reuters" survives (not blacklisted in this test).
  413. assert "Bitcoin" not in out["entities"]
  414. assert "btc" not in [e.lower() for e in out["entities"]]
  415. assert "Reuters" in out["entities"]
  416. def test_dedup_uses_jaccard_when_titles_diverge():
  417. """Composite similarity: even with embeddings off, two articles whose
  418. titles share only some tokens should still merge if their content (token
  419. overlap) is high enough."""
  420. from news_mcp.dedup import cluster as dc
  421. # Titles differ heavily; bodies overlap heavily -> Jaccard should catch.
  422. articles = [
  423. {
  424. "title": "Iran tension rises",
  425. "url": "https://example.com/a",
  426. "source": "A",
  427. "timestamp": "Mon, 30 Mar 2026 12:00:00 GMT",
  428. "summary": "Trump warns Iran war could spread across the Middle East amid rising tensions.",
  429. },
  430. {
  431. "title": "Trump issues stark warning over Tehran",
  432. "url": "https://example.com/b",
  433. "source": "B",
  434. "timestamp": "Mon, 30 Mar 2026 12:00:00 GMT",
  435. "summary": "Trump warns Iran war could spread across the Middle East amid rising tensions.",
  436. },
  437. ]
  438. clustered = dc.dedup_and_cluster_articles(articles)
  439. total = sum(len(v) for v in clustered.values())
  440. assert total == 1, f"Expected 1 merged cluster via Jaccard signal, got {total}"
  441. def test_dedup_does_not_merge_unrelated_articles():
  442. """Negative control: cluster is robust against false-positives even with
  443. the more permissive multi-signal merging."""
  444. from news_mcp.dedup import cluster as dc
  445. articles = [
  446. {
  447. "title": "Bitcoin hits new high",
  448. "url": "https://example.com/a",
  449. "source": "A",
  450. "timestamp": "Mon, 30 Mar 2026 12:00:00 GMT",
  451. "summary": "Bitcoin reached a record high amid rising demand.",
  452. },
  453. {
  454. "title": "Local sports team wins",
  455. "url": "https://example.com/b",
  456. "source": "B",
  457. "timestamp": "Mon, 30 Mar 2026 12:00:00 GMT",
  458. "summary": "The local team won the regional championship.",
  459. },
  460. ]
  461. clustered = dc.dedup_and_cluster_articles(articles)
  462. total = sum(len(v) for v in clustered.values())
  463. assert total == 2
  464. def test_get_all_feed_states_returns_all_rows():
  465. """Health endpoint regression: the writer keys feed state with a hashed
  466. multi-feed key, so the old hardcoded ``get_feed_state("breakingthenews")``
  467. always returned None. Verify the bulk getter works."""
  468. import tempfile
  469. from pathlib import Path
  470. with tempfile.TemporaryDirectory() as td:
  471. db = Path(td) / "news.sqlite"
  472. store = SQLiteClusterStore(db)
  473. store.set_feed_hash("newsfeeds:abc123", "hash1")
  474. store.set_feed_hash("newsfeeds:def456", "hash2")
  475. all_states = store.get_all_feed_states()
  476. assert len(all_states) == 2
  477. keys = {s["feed_key"] for s in all_states}
  478. assert keys == {"newsfeeds:abc123", "newsfeeds:def456"}
  479. def test_poller_persists_clusters_under_post_enrichment_topic(monkeypatch):
  480. """Regression: the SQL row-column ``topic`` previously locked in the
  481. headline-heuristic value (which is ``other`` for most stories) and ignored
  482. the LLM's classification stored in the payload. Verify the upsert now uses
  483. the post-enrichment topic so SQL filtering and dashboard groupings see the
  484. real classification."""
  485. import asyncio
  486. import news_mcp.jobs.poller as poller
  487. captured = {"upserts": []}
  488. class DummyStore:
  489. def __init__(self, *args, **kwargs):
  490. pass
  491. @contextmanager
  492. def _conn(self):
  493. class _Conn:
  494. def execute(self, *args, **kwargs):
  495. return None
  496. yield _Conn()
  497. def get_feed_hash(self, feed_key):
  498. return None
  499. def set_feed_hash(self, feed_key, last_hash):
  500. pass
  501. def set_feed_state(self, feed_key, last_hash, item_count):
  502. pass
  503. def get_enabled_feed_urls(self, feed_urls):
  504. return feed_urls
  505. def get_cluster_by_id(self, cluster_id):
  506. return None
  507. def upsert_clusters(self, clusters, topic):
  508. # Capture the topic the poller chose for each cluster.
  509. for c in clusters:
  510. captured["upserts"].append({"row_topic": topic, "payload_topic": c.get("topic"), "cluster_id": c.get("cluster_id")})
  511. def prune_if_due(self, **kwargs):
  512. return {"deleted": 0}
  513. def get_failed_enrichment_clusters(self, max_retries=3):
  514. return []
  515. def get_latest_clusters_all_topics(self, ttl_hours=24, limit=500):
  516. return []
  517. def set_meta(self, key, value):
  518. pass
  519. def set_feed_state(self, feed_key, last_hash, item_count):
  520. pass
  521. def fake_cluster(articles, similarity_threshold=None, existing_clusters=None, max_age_hours=0):
  522. # Heuristic put it in "other" (no crypto/macro/regulation/ai keywords
  523. # in the title for the heuristic matcher — title above does have
  524. # "law"-adjacent words but not the specific tokens it matches).
  525. return {
  526. "other": [
  527. {
  528. "cluster_id": "cid",
  529. "headline": "SEC fines firm",
  530. "summary": "...",
  531. "topic": "other",
  532. "entities": [],
  533. "sentiment": "neutral",
  534. "importance": 0.0,
  535. "sources": ["S"],
  536. "timestamp": "Wed, 01 Apr 2026 12:00:00 GMT",
  537. "articles": [],
  538. }
  539. ]
  540. }
  541. def fake_enrich(cluster):
  542. return cluster
  543. async def fake_classify(cluster):
  544. # The LLM thinks it's regulation -> the SQL row column must reflect that.
  545. out = dict(cluster)
  546. out["topic"] = "regulation"
  547. out["entities"] = ["SEC"]
  548. out["entityResolutions"] = []
  549. out["sentiment"] = "neutral"
  550. out["sentimentScore"] = 0.0
  551. out["keywords"] = []
  552. return out
  553. monkeypatch.setattr(poller, "SQLiteClusterStore", DummyStore)
  554. async def _mock_fetch2(limit, url_list=None):
  555. return [
  556. {"title": "SEC fines firm", "url": "https://example.com/a", "source": "S",
  557. "timestamp": "Wed, 01 Apr 2026 12:00:00 GMT", "summary": "..."},
  558. ]
  559. monkeypatch.setattr(poller, "fetch_news_articles", _mock_fetch2)
  560. monkeypatch.setattr(poller, "dedup_and_cluster_articles", fake_cluster)
  561. monkeypatch.setattr(poller, "enrich_cluster", fake_enrich)
  562. monkeypatch.setattr(poller, "classify_cluster_llm", fake_classify)
  563. asyncio.run(poller.refresh_clusters(topic=None, limit=10))
  564. assert captured["upserts"], "Expected at least one upsert call"
  565. # The poller first stores raw clusters (topic=heuristic), then enriched
  566. # clusters (topic=post-LLM). The enriched upsert is the one whose row_topic
  567. # reflects the LLM classification.
  568. enriched_upserts = [u for u in captured["upserts"] if u["row_topic"] == "regulation"]
  569. assert enriched_upserts, (
  570. f"Expected at least one upsert with row_topic='regulation', "
  571. f"got topics: {[u['row_topic'] for u in captured['upserts']]}"
  572. )
  573. upsert = enriched_upserts[0]
  574. assert upsert["row_topic"] == "regulation", (
  575. f"Expected SQL row topic to follow the LLM's classification 'regulation', got {upsert['row_topic']!r}"
  576. )
  577. assert upsert["payload_topic"] == "regulation"
  578. # ---------------------------------------------------------------------------
  579. # v1.3 — Stable cluster IDs, orphan merge, temporal gating
  580. # ---------------------------------------------------------------------------
  581. def test_stable_cluster_id_is_order_independent():
  582. """Two articles about the same event should always get the same cluster_id,
  583. regardless of which article is processed first."""
  584. from news_mcp.dedup import cluster as dc
  585. art_a = {
  586. "title": "Bitcoin Surges Past $100K",
  587. "url": "https://example.com/btc-100k",
  588. "source": "Reuters",
  589. "timestamp": "Mon, 30 Mar 2026 12:00:00 GMT",
  590. "summary": "Bitcoin reached $100,000 for the first time.",
  591. }
  592. art_b = {
  593. "title": "BTC Breaks $100,000 Barrier",
  594. "url": "https://example.com/btc-100k",
  595. "source": "Bloomberg",
  596. "timestamp": "Mon, 30 Mar 2026 12:05:00 GMT",
  597. "summary": "Bitcoin topped the $100,000 level.",
  598. }
  599. # Process A first
  600. clustered_ab = dc.dedup_and_cluster_articles([art_a, art_b])
  601. # Process B first
  602. clustered_ba = dc.dedup_and_cluster_articles([art_b, art_a])
  603. # Both orderings must produce the same cluster_id(s)
  604. ids_ab = sorted(c["cluster_id"] for clusters in clustered_ab.values() for c in clusters)
  605. ids_ba = sorted(c["cluster_id"] for clusters in clustered_ba.values() for c in clusters)
  606. assert ids_ab == ids_ba, f"Cluster IDs depend on order: {ids_ab} vs {ids_ba}"
  607. def test_orphan_merge_deduplicates_shared_articles():
  608. """When two clusters end up with overlapping article sets (e.g. because
  609. embeddings were temporarily unavailable), the post-clustering merge pass
  610. should combine them into one."""
  611. from news_mcp.dedup.cluster import _merge_orphan_clusters
  612. clusters = [
  613. {
  614. "cluster_id": "aaa",
  615. "topic": "crypto",
  616. "headline": "Bitcoin surges",
  617. "articles": [
  618. {"title": "Bitcoin surges", "url": "https://example.com/btc", "source": "A"},
  619. ],
  620. "sources": ["A"],
  621. "first_seen": "T1",
  622. "last_updated": "T1",
  623. },
  624. {
  625. "cluster_id": "bbb",
  626. "topic": "crypto",
  627. "headline": "BTC up",
  628. "articles": [
  629. {"title": "BTC up", "url": "https://example.com/btc", "source": "B"},
  630. ],
  631. "sources": ["B"],
  632. "first_seen": "T2",
  633. "last_updated": "T2",
  634. },
  635. ]
  636. merged = _merge_orphan_clusters(clusters)
  637. assert len(merged) == 1, f"Expected 1 merged cluster, got {len(merged)}"
  638. assert set(merged[0]["sources"]) == {"A", "B"}
  639. def test_orphan_merge_preserves_distinct_clusters():
  640. """Clusters with no shared articles must remain independent."""
  641. from news_mcp.dedup.cluster import _merge_orphan_clusters
  642. clusters = [
  643. {
  644. "cluster_id": "aaa",
  645. "topic": "crypto",
  646. "headline": "Bitcoin surges",
  647. "articles": [
  648. {"title": "Bitcoin surges", "url": "https://example.com/btc", "source": "A"},
  649. ],
  650. "sources": ["A"],
  651. "first_seen": "T1",
  652. "last_updated": "T1",
  653. },
  654. {
  655. "cluster_id": "bbb",
  656. "topic": "crypto",
  657. "headline": "Ethereum merge",
  658. "articles": [
  659. {"title": "Ethereum merge", "url": "https://example.com/eth", "source": "B"},
  660. ],
  661. "sources": ["B"],
  662. "first_seen": "T2",
  663. "last_updated": "T2",
  664. },
  665. ]
  666. merged = _merge_orphan_clusters(clusters)
  667. assert len(merged) == 2
  668. def test_stable_id_same_for_different_titles_same_url():
  669. """Two articles with the same URL but different titles (e.g. corrected
  670. headline) must produce the same cluster_id."""
  671. from news_mcp.dedup.cluster import _stable_cluster_id
  672. arts_a = [
  673. {"title": "Fed Raises Rates", "url": "https://example.com/fed-rates"},
  674. ]
  675. arts_b = [
  676. {"title": "Federal Reserve Increases Interest Rates", "url": "https://example.com/fed-rates"},
  677. ]
  678. id_a = _stable_cluster_id("macro", arts_a)
  679. id_b = _stable_cluster_id("macro", arts_b)
  680. assert id_a == id_b, f"Same URL must give same cluster_id: {id_a} vs {id_b}"
  681. def test_temporal_gate_excludes_stale_clusters():
  682. """Clusters older than max_age_hours should not be candidates for merging."""
  683. from news_mcp.dedup.cluster import _cluster_is_within_age_window
  684. old_cluster = {
  685. "cluster_id": "old",
  686. "topic": "crypto",
  687. "last_updated": "2025-01-01T00:00:00+00:00",
  688. "articles": [],
  689. }
  690. assert not _cluster_is_within_age_window(old_cluster, max_age_hours=4)
  691. recent_cluster = {
  692. "cluster_id": "recent",
  693. "topic": "crypto",
  694. "last_updated": datetime.now(timezone.utc).isoformat(),
  695. "articles": [],
  696. }
  697. assert _cluster_is_within_age_window(recent_cluster, max_age_hours=4)
  698. # max_age_hours=0 means no limit
  699. assert _cluster_is_within_age_window(old_cluster, max_age_hours=0)
  700. def test_preseed_merge_into_existing_cluster():
  701. """When existing_clusters is provided, a new article that matches should
  702. merge into the existing cluster instead of creating a new one."""
  703. from news_mcp.dedup import cluster as dc
  704. existing = [{
  705. "cluster_id": "existing-1",
  706. "topic": "other",
  707. "headline": "Trump warns Iran war could spread across Middle East",
  708. "summary": "Trump warns Iran war could spread across the Middle East amid rising tensions.",
  709. "sources": ["Reuters"],
  710. "timestamp": "Mon, 30 Mar 2026 12:00:00 GMT",
  711. "last_updated": datetime.now(timezone.utc).isoformat(),
  712. "first_seen": "Mon, 30 Mar 2026 12:00:00 GMT",
  713. "articles": [
  714. {
  715. "title": "Trump warns Iran war could spread across Middle East",
  716. "url": "https://example.com/trump-iran",
  717. "source": "Reuters",
  718. "timestamp": "Mon, 30 Mar 2026 12:00:00 GMT",
  719. "summary": "Trump warns Iran war could spread across the Middle East amid rising tensions.",
  720. }
  721. ],
  722. "entities": [],
  723. "sentiment": "neutral",
  724. "importance": 0.0,
  725. }]
  726. new_article = {
  727. "title": "Trump warns Iran conflict could spread across Middle East",
  728. "url": "https://example.com/trump-iran-2",
  729. "source": "Bloomberg",
  730. "timestamp": "Mon, 30 Mar 2026 13:00:00 GMT",
  731. "summary": "Trump warns Iran war could spread across the Middle East amid rising tensions.",
  732. }
  733. # Use a low title threshold so Jaccard can catch the merge
  734. clustered = dc.dedup_and_cluster_articles(
  735. [new_article],
  736. similarity_threshold=0.75,
  737. existing_clusters=existing,
  738. max_age_hours=4,
  739. )
  740. all_clusters = [c for clusters in clustered.values() for c in clusters]
  741. # Should have exactly 1 cluster (the existing one, now with 2 articles)
  742. assert len(all_clusters) == 1, f"Expected 1 cluster, got {len(all_clusters)}: {[c['headline'] for c in all_clusters]}"
  743. assert len(all_clusters[0]["articles"]) == 2