test_news_mcp.py 35 KB

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