test_news_mcp.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981
  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 filter_already_seen(self, articles):
  305. return articles, []
  306. def set_meta(self, key, value):
  307. self.meta[key] = value
  308. monkeypatch.setattr(poller, "SQLiteClusterStore", DummyStore)
  309. async def _mock_fetch(limit, url_list=None):
  310. calls["fetch"] += 1
  311. return [{"title": "Bitcoin rallies", "url": "https://example.com/a", "timestamp": "Wed, 01 Apr 2026 12:00:00 GMT"}]
  312. monkeypatch.setattr(poller, "fetch_news_articles", _mock_fetch)
  313. monkeypatch.setattr(poller.asyncio, "to_thread", fake_to_thread)
  314. monkeypatch.setattr(poller, "dedup_and_cluster_articles", fake_cluster)
  315. monkeypatch.setattr(poller, "enrich_cluster", fake_enrich)
  316. monkeypatch.setattr(poller, "classify_cluster_llm", fake_classify)
  317. poller.store = None
  318. async def run_once():
  319. await poller.refresh_clusters(topic=None, limit=80)
  320. import asyncio
  321. asyncio.run(run_once())
  322. assert calls["fetch"] == 1
  323. assert calls["cluster"] == 0
  324. assert calls["enrich"] == 0
  325. assert calls["classify"] == 0
  326. def test_importance_prefers_llm_signal():
  327. # Two clusters with same coverage but different sentiment magnitude.
  328. base = {
  329. "sources": ["A", "B"],
  330. "articles": [{}, {}],
  331. "sentiment": "neutral",
  332. "sentimentScore": 0.0,
  333. }
  334. pos = dict(base, sentimentScore=0.9)
  335. neg = dict(base, sentimentScore=-0.8)
  336. imp_base = compute_importance(base)
  337. imp_pos = compute_importance(pos)
  338. imp_neg = compute_importance(neg)
  339. assert imp_pos >= imp_base
  340. assert imp_neg >= imp_base
  341. # ---------------------------------------------------------------------------
  342. # Regression tests for the May 2026 correctness pass
  343. # ---------------------------------------------------------------------------
  344. def test_classify_cluster_llm_uses_llm_topic_and_drops_invalid_ones(monkeypatch):
  345. """The LLM-extracted topic must propagate to the returned cluster, but
  346. free-form / hallucinated topic strings must be coerced into the allowed
  347. set so they never reach the SQL row column verbatim."""
  348. import asyncio
  349. from news_mcp.enrichment import llm_enrich
  350. async def fake_extraction(cluster):
  351. return {
  352. "topic": "regulation",
  353. "entities": ["SEC"],
  354. "sentiment": "neutral",
  355. "sentimentScore": 0.0,
  356. "keywords": ["enforcement"],
  357. }
  358. monkeypatch.setattr(llm_enrich, "call_extraction", fake_extraction)
  359. monkeypatch.setattr(llm_enrich, "resolve_entity_via_trends", lambda e: {"normalized": e, "canonical_label": e, "mid": None})
  360. cluster = {"cluster_id": "x", "headline": "SEC fines firm", "summary": "...", "topic": "other"}
  361. out = asyncio.run(llm_enrich.classify_cluster_llm(cluster))
  362. assert out["topic"] == "regulation"
  363. # Hallucinated topic is rejected; we fall back to the input cluster's
  364. # heuristic topic when it is one of the allowed ones.
  365. async def fake_extraction_garbage(cluster):
  366. return {
  367. "topic": "geopolitics-and-stuff",
  368. "entities": ["NATO"],
  369. "sentiment": "neutral",
  370. "sentimentScore": 0.0,
  371. "keywords": [],
  372. }
  373. monkeypatch.setattr(llm_enrich, "call_extraction", fake_extraction_garbage)
  374. cluster = {"cluster_id": "y", "headline": "NATO meets", "summary": "...", "topic": "macro"}
  375. out = asyncio.run(llm_enrich.classify_cluster_llm(cluster))
  376. assert out["topic"] == "macro" # heuristic fallback
  377. # When neither the LLM nor the heuristic gives a valid label -> "other".
  378. cluster = {"cluster_id": "z", "headline": "...", "summary": "...", "topic": "geopolitics-bucket"}
  379. out = asyncio.run(llm_enrich.classify_cluster_llm(cluster))
  380. assert out["topic"] == "other"
  381. def test_classify_cluster_llm_normalizes_aliases_before_blacklist(monkeypatch):
  382. """Regression: previously ``_filter_entities`` ran before
  383. ``normalize_entities``, so blacklisting "bitcoin" missed entries the LLM
  384. returned as the alias "btc". Order is now normalize -> blacklist."""
  385. import asyncio
  386. from news_mcp.enrichment import llm_enrich
  387. async def fake_extraction(cluster):
  388. return {
  389. "topic": "crypto",
  390. "entities": ["btc", "Reuters"],
  391. "sentiment": "neutral",
  392. "sentimentScore": 0.0,
  393. "keywords": ["btc rally", "Reuters"],
  394. }
  395. monkeypatch.setattr(llm_enrich, "call_extraction", fake_extraction)
  396. monkeypatch.setattr(llm_enrich, "resolve_entity_via_trends", lambda e: {"normalized": e, "canonical_label": e, "mid": None})
  397. monkeypatch.setattr(llm_enrich, "NEWS_ENTITY_BLACKLIST", ["bitcoin"])
  398. cluster = {"cluster_id": "x", "headline": "BTC up", "summary": "...", "topic": "crypto"}
  399. out = asyncio.run(llm_enrich.classify_cluster_llm(cluster))
  400. # "btc" became "Bitcoin" via aliasing, then was filtered out by the
  401. # blacklist. "Reuters" survives (not blacklisted in this test).
  402. assert "Bitcoin" not in out["entities"]
  403. assert "btc" not in [e.lower() for e in out["entities"]]
  404. assert "Reuters" in out["entities"]
  405. def test_dedup_uses_jaccard_when_titles_diverge():
  406. """Composite similarity: even with embeddings off, two articles whose
  407. titles share only some tokens should still merge if their content (token
  408. overlap) is high enough."""
  409. from news_mcp.dedup import cluster as dc
  410. # Titles differ heavily; bodies overlap heavily -> Jaccard should catch.
  411. articles = [
  412. {
  413. "title": "Iran tension rises",
  414. "url": "https://example.com/a",
  415. "source": "A",
  416. "timestamp": "Mon, 30 Mar 2026 12:00:00 GMT",
  417. "summary": "Trump warns Iran war could spread across the Middle East amid rising tensions.",
  418. },
  419. {
  420. "title": "Trump issues stark warning over Tehran",
  421. "url": "https://example.com/b",
  422. "source": "B",
  423. "timestamp": "Mon, 30 Mar 2026 12:00:00 GMT",
  424. "summary": "Trump warns Iran war could spread across the Middle East amid rising tensions.",
  425. },
  426. ]
  427. clustered = dc.dedup_and_cluster_articles(articles)
  428. total = sum(len(v) for v in clustered.values())
  429. assert total == 1, f"Expected 1 merged cluster via Jaccard signal, got {total}"
  430. def test_dedup_does_not_merge_unrelated_articles():
  431. """Negative control: cluster is robust against false-positives even with
  432. the more permissive multi-signal merging."""
  433. from news_mcp.dedup import cluster as dc
  434. articles = [
  435. {
  436. "title": "Bitcoin hits new high",
  437. "url": "https://example.com/a",
  438. "source": "A",
  439. "timestamp": "Mon, 30 Mar 2026 12:00:00 GMT",
  440. "summary": "Bitcoin reached a record high amid rising demand.",
  441. },
  442. {
  443. "title": "Local sports team wins",
  444. "url": "https://example.com/b",
  445. "source": "B",
  446. "timestamp": "Mon, 30 Mar 2026 12:00:00 GMT",
  447. "summary": "The local team won the regional championship.",
  448. },
  449. ]
  450. clustered = dc.dedup_and_cluster_articles(articles)
  451. total = sum(len(v) for v in clustered.values())
  452. assert total == 2
  453. def test_get_all_feed_states_returns_all_rows():
  454. """Health endpoint regression: the writer keys feed state with a hashed
  455. multi-feed key, so the old hardcoded ``get_feed_state("breakingthenews")``
  456. always returned None. Verify the bulk getter works."""
  457. import tempfile
  458. from pathlib import Path
  459. with tempfile.TemporaryDirectory() as td:
  460. db = Path(td) / "news.sqlite"
  461. store = SQLiteClusterStore(db)
  462. store.set_feed_hash("newsfeeds:abc123", "hash1")
  463. store.set_feed_hash("newsfeeds:def456", "hash2")
  464. all_states = store.get_all_feed_states()
  465. assert len(all_states) == 2
  466. keys = {s["feed_key"] for s in all_states}
  467. assert keys == {"newsfeeds:abc123", "newsfeeds:def456"}
  468. def test_poller_persists_clusters_under_post_enrichment_topic(monkeypatch):
  469. """Regression: the SQL row-column ``topic`` previously locked in the
  470. headline-heuristic value (which is ``other`` for most stories) and ignored
  471. the LLM's classification stored in the payload. Verify the upsert now uses
  472. the post-enrichment topic so SQL filtering and dashboard groupings see the
  473. real classification."""
  474. import asyncio
  475. from datetime import datetime, timezone
  476. import news_mcp.jobs.poller as poller
  477. _now_str = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S+00:00")
  478. captured = {"upserts": []}
  479. class DummyStore:
  480. def __init__(self, *args, **kwargs):
  481. pass
  482. @contextmanager
  483. def _conn(self):
  484. class _Conn:
  485. def execute(self, *args, **kwargs):
  486. return None
  487. yield _Conn()
  488. def get_feed_hash(self, feed_key):
  489. return None
  490. def set_feed_hash(self, feed_key, last_hash):
  491. pass
  492. def set_feed_state(self, feed_key, last_hash, item_count):
  493. pass
  494. def get_enabled_feed_urls(self, feed_urls):
  495. return feed_urls
  496. def get_cluster_by_id(self, cluster_id):
  497. return None
  498. def upsert_clusters(self, clusters, topic):
  499. # Capture the topic the poller chose for each cluster.
  500. for c in clusters:
  501. captured["upserts"].append({"row_topic": topic, "payload_topic": c.get("topic"), "cluster_id": c.get("cluster_id")})
  502. def prune_if_due(self, **kwargs):
  503. return {"deleted": 0}
  504. def get_failed_enrichment_clusters(self, max_retries=3):
  505. return []
  506. def get_latest_clusters_all_topics(self, ttl_hours=24, limit=500):
  507. return []
  508. def filter_already_seen(self, articles):
  509. return articles, []
  510. def set_meta(self, key, value):
  511. pass
  512. def set_feed_state(self, feed_key, last_hash, item_count):
  513. pass
  514. def fake_cluster(articles, similarity_threshold=None, existing_clusters=None, max_age_hours=0):
  515. # Heuristic put it in "other" (no crypto/macro/regulation/ai keywords
  516. # in the title for the heuristic matcher — title above does have
  517. # "law"-adjacent words but not the specific tokens it matches).
  518. return {
  519. "other": [
  520. {
  521. "cluster_id": "cid",
  522. "headline": "SEC fines firm",
  523. "summary": "...",
  524. "topic": "other",
  525. "entities": [],
  526. "sentiment": "neutral",
  527. "importance": 0.0,
  528. "sources": ["S"],
  529. "timestamp": _now_str,
  530. "articles": [],
  531. }
  532. ]
  533. }
  534. def fake_enrich(cluster):
  535. return cluster
  536. async def fake_classify(cluster):
  537. # The LLM thinks it's regulation -> the SQL row column must reflect that.
  538. out = dict(cluster)
  539. out["topic"] = "regulation"
  540. out["entities"] = ["SEC"]
  541. out["entityResolutions"] = []
  542. out["sentiment"] = "neutral"
  543. out["sentimentScore"] = 0.0
  544. out["keywords"] = []
  545. return out
  546. monkeypatch.setattr(poller, "SQLiteClusterStore", DummyStore)
  547. async def _mock_fetch2(limit, url_list=None):
  548. return [
  549. {"title": "SEC fines firm", "url": "https://example.com/a", "source": "S",
  550. "timestamp": _now_str, "summary": "..."},
  551. ]
  552. monkeypatch.setattr(poller, "fetch_news_articles", _mock_fetch2)
  553. monkeypatch.setattr(poller, "dedup_and_cluster_articles", fake_cluster)
  554. monkeypatch.setattr(poller, "enrich_cluster", fake_enrich)
  555. monkeypatch.setattr(poller, "classify_cluster_llm", fake_classify)
  556. asyncio.run(poller.refresh_clusters(topic=None, limit=10))
  557. assert captured["upserts"], "Expected at least one upsert call"
  558. # The poller first stores raw clusters (topic=heuristic), then enriched
  559. # clusters (topic=post-LLM). The enriched upsert is the one whose row_topic
  560. # reflects the LLM classification.
  561. enriched_upserts = [u for u in captured["upserts"] if u["row_topic"] == "regulation"]
  562. assert enriched_upserts, (
  563. f"Expected at least one upsert with row_topic='regulation', "
  564. f"got topics: {[u['row_topic'] for u in captured['upserts']]}"
  565. )
  566. upsert = enriched_upserts[0]
  567. assert upsert["row_topic"] == "regulation", (
  568. f"Expected SQL row topic to follow the LLM's classification 'regulation', got {upsert['row_topic']!r}"
  569. )
  570. assert upsert["payload_topic"] == "regulation"
  571. # ---------------------------------------------------------------------------
  572. # v1.3 — Stable cluster IDs, orphan merge, temporal gating
  573. # ---------------------------------------------------------------------------
  574. def test_stable_cluster_id_is_order_independent():
  575. """Two articles about the same event should always get the same cluster_id,
  576. regardless of which article is processed first."""
  577. from news_mcp.dedup import cluster as dc
  578. art_a = {
  579. "title": "Bitcoin Surges Past $100K",
  580. "url": "https://example.com/btc-100k",
  581. "source": "Reuters",
  582. "timestamp": "Mon, 30 Mar 2026 12:00:00 GMT",
  583. "summary": "Bitcoin reached $100,000 for the first time.",
  584. }
  585. art_b = {
  586. "title": "BTC Breaks $100,000 Barrier",
  587. "url": "https://example.com/btc-100k",
  588. "source": "Bloomberg",
  589. "timestamp": "Mon, 30 Mar 2026 12:05:00 GMT",
  590. "summary": "Bitcoin topped the $100,000 level.",
  591. }
  592. # Process A first
  593. clustered_ab = dc.dedup_and_cluster_articles([art_a, art_b])
  594. # Process B first
  595. clustered_ba = dc.dedup_and_cluster_articles([art_b, art_a])
  596. # Both orderings must produce the same cluster_id(s)
  597. ids_ab = sorted(c["cluster_id"] for clusters in clustered_ab.values() for c in clusters)
  598. ids_ba = sorted(c["cluster_id"] for clusters in clustered_ba.values() for c in clusters)
  599. assert ids_ab == ids_ba, f"Cluster IDs depend on order: {ids_ab} vs {ids_ba}"
  600. def test_orphan_merge_deduplicates_shared_articles():
  601. """When two clusters end up with overlapping article sets (e.g. because
  602. embeddings were temporarily unavailable), the post-clustering merge pass
  603. should combine them into one."""
  604. from news_mcp.dedup.cluster import _merge_orphan_clusters
  605. clusters = [
  606. {
  607. "cluster_id": "aaa",
  608. "topic": "crypto",
  609. "headline": "Bitcoin surges",
  610. "articles": [
  611. {"title": "Bitcoin surges", "url": "https://example.com/btc", "source": "A"},
  612. ],
  613. "sources": ["A"],
  614. "first_seen": "T1",
  615. "last_updated": "T1",
  616. },
  617. {
  618. "cluster_id": "bbb",
  619. "topic": "crypto",
  620. "headline": "BTC up",
  621. "articles": [
  622. {"title": "BTC up", "url": "https://example.com/btc", "source": "B"},
  623. ],
  624. "sources": ["B"],
  625. "first_seen": "T2",
  626. "last_updated": "T2",
  627. },
  628. ]
  629. merged = _merge_orphan_clusters(clusters)
  630. assert len(merged) == 1, f"Expected 1 merged cluster, got {len(merged)}"
  631. assert set(merged[0]["sources"]) == {"A", "B"}
  632. def test_orphan_merge_preserves_distinct_clusters():
  633. """Clusters with no shared articles must remain independent."""
  634. from news_mcp.dedup.cluster import _merge_orphan_clusters
  635. clusters = [
  636. {
  637. "cluster_id": "aaa",
  638. "topic": "crypto",
  639. "headline": "Bitcoin surges",
  640. "articles": [
  641. {"title": "Bitcoin surges", "url": "https://example.com/btc", "source": "A"},
  642. ],
  643. "sources": ["A"],
  644. "first_seen": "T1",
  645. "last_updated": "T1",
  646. },
  647. {
  648. "cluster_id": "bbb",
  649. "topic": "crypto",
  650. "headline": "Ethereum merge",
  651. "articles": [
  652. {"title": "Ethereum merge", "url": "https://example.com/eth", "source": "B"},
  653. ],
  654. "sources": ["B"],
  655. "first_seen": "T2",
  656. "last_updated": "T2",
  657. },
  658. ]
  659. merged = _merge_orphan_clusters(clusters)
  660. assert len(merged) == 2
  661. def test_stable_id_same_for_different_titles_same_url():
  662. """Two articles with the same URL but different titles (e.g. corrected
  663. headline) must produce the same cluster_id."""
  664. from news_mcp.dedup.cluster import _stable_cluster_id
  665. arts_a = [
  666. {"title": "Fed Raises Rates", "url": "https://example.com/fed-rates"},
  667. ]
  668. arts_b = [
  669. {"title": "Federal Reserve Increases Interest Rates", "url": "https://example.com/fed-rates"},
  670. ]
  671. id_a = _stable_cluster_id("macro", arts_a)
  672. id_b = _stable_cluster_id("macro", arts_b)
  673. assert id_a == id_b, f"Same URL must give same cluster_id: {id_a} vs {id_b}"
  674. def test_temporal_gate_excludes_stale_clusters():
  675. """Clusters older than max_age_hours should not be candidates for merging."""
  676. from news_mcp.dedup.cluster import _cluster_is_within_age_window
  677. old_cluster = {
  678. "cluster_id": "old",
  679. "topic": "crypto",
  680. "last_updated": "2025-01-01T00:00:00+00:00",
  681. "articles": [],
  682. }
  683. assert not _cluster_is_within_age_window(old_cluster, max_age_hours=4)
  684. recent_cluster = {
  685. "cluster_id": "recent",
  686. "topic": "crypto",
  687. "last_updated": datetime.now(timezone.utc).isoformat(),
  688. "articles": [],
  689. }
  690. assert _cluster_is_within_age_window(recent_cluster, max_age_hours=4)
  691. # max_age_hours=0 means no limit
  692. assert _cluster_is_within_age_window(old_cluster, max_age_hours=0)
  693. def test_preseed_merge_into_existing_cluster():
  694. """When existing_clusters is provided, a new article that matches should
  695. merge into the existing cluster instead of creating a new one."""
  696. from news_mcp.dedup import cluster as dc
  697. existing = [{
  698. "cluster_id": "existing-1",
  699. "topic": "other",
  700. "headline": "Trump warns Iran war could spread across Middle East",
  701. "summary": "Trump warns Iran war could spread across the Middle East amid rising tensions.",
  702. "sources": ["Reuters"],
  703. "timestamp": "Mon, 30 Mar 2026 12:00:00 GMT",
  704. "last_updated": datetime.now(timezone.utc).isoformat(),
  705. "first_seen": "Mon, 30 Mar 2026 12:00:00 GMT",
  706. "articles": [
  707. {
  708. "title": "Trump warns Iran war could spread across Middle East",
  709. "url": "https://example.com/trump-iran",
  710. "source": "Reuters",
  711. "timestamp": "Mon, 30 Mar 2026 12:00:00 GMT",
  712. "summary": "Trump warns Iran war could spread across the Middle East amid rising tensions.",
  713. }
  714. ],
  715. "entities": [],
  716. "sentiment": "neutral",
  717. "importance": 0.0,
  718. }]
  719. new_article = {
  720. "title": "Trump warns Iran conflict could spread across Middle East",
  721. "url": "https://example.com/trump-iran-2",
  722. "source": "Bloomberg",
  723. "timestamp": "Mon, 30 Mar 2026 13:00:00 GMT",
  724. "summary": "Trump warns Iran war could spread across the Middle East amid rising tensions.",
  725. }
  726. # Use a low title threshold so Jaccard can catch the merge
  727. clustered = dc.dedup_and_cluster_articles(
  728. [new_article],
  729. similarity_threshold=0.75,
  730. existing_clusters=existing,
  731. max_age_hours=4,
  732. )
  733. all_clusters = [c for clusters in clustered.values() for c in clusters]
  734. # Should have exactly 1 cluster (the existing one, now with 2 articles)
  735. assert len(all_clusters) == 1, f"Expected 1 cluster, got {len(all_clusters)}: {[c['headline'] for c in all_clusters]}"
  736. assert len(all_clusters[0]["articles"]) == 2
  737. def test_cross_cycle_merge_topic_mismatch():
  738. """Regression: same article arriving in two cycles must merge even when
  739. the existing cluster's enriched topic differs from the new article's
  740. heuristic topic. Previously the cluster_id included the topic in the
  741. hash AND existing clusters were bucketed by enriched topic, so a
  742. topic mismatch silently produced two rows in the DB."""
  743. from news_mcp.dedup import cluster as dc
  744. url = (
  745. "https://breakingthenews.net/Article/"
  746. "Hegseth-says-US-will-keep-pressure-on-Iran/66401647"
  747. )
  748. existing = [{
  749. "cluster_id": "old-id",
  750. # Enriched topic from a prior LLM pass — *different* from what
  751. # normalize_topic_from_title would return for the headline.
  752. "topic": "crypto",
  753. "headline": "Hegseth says US will keep pressure on Iran",
  754. "summary": "",
  755. "sources": ["Breaking The News"],
  756. "timestamp": "Sat, 30 May 2026 13:00:00 GMT",
  757. "last_updated": datetime.now(timezone.utc).isoformat(),
  758. "first_seen": "Sat, 30 May 2026 13:00:00 GMT",
  759. "articles": [{
  760. "title": "Hegseth says US will keep pressure on Iran",
  761. "url": url,
  762. "source": "Breaking The News",
  763. "timestamp": "Sat, 30 May 2026 13:00:00 GMT",
  764. "summary": "",
  765. }],
  766. "entities": ["Pete Hegseth", "Iran"],
  767. "sentiment": "negative",
  768. "sentimentScore": -0.5,
  769. "importance": 0.1,
  770. }]
  771. # The same article arrives again in the next polling cycle.
  772. # Its heuristic topic (normalize_topic_from_title) is "other" (no
  773. # keyword match), which differs from the stored "crypto" topic.
  774. new_article = {
  775. "title": "Hegseth says US will keep pressure on Iran",
  776. "url": url,
  777. "source": "Breaking The News",
  778. "timestamp": "Sat, 30 May 2026 13:00:00 GMT",
  779. "summary": "",
  780. # feed_url is used for per-feed hash tracking
  781. "feed_url": "https://breakingthenews.net/news-feed.xml",
  782. "importance": 0.11,
  783. }
  784. clustered = dc.dedup_and_cluster_articles(
  785. [new_article],
  786. existing_clusters=existing,
  787. max_age_hours=4,
  788. )
  789. all_clusters = [c for clusters in clustered.values() for c in clusters]
  790. # Must produce exactly 1 cluster — the new article merges into the
  791. # existing one. Before the fix this yielded 2 clusters with different
  792. # cluster_ids because the topic mismatch prevented matching.
  793. assert len(all_clusters) == 1, (
  794. f"Expected 1 cluster, got {len(all_clusters)}: "
  795. f"{[c['headline'] for c in all_clusters]}"
  796. )
  797. # The surviving cluster must carry the *same* cluster_id from the
  798. # pre-seeded DB cluster, even after absorbing new articles.
  799. # cluster_id is set once at creation and never recomputed, so the
  800. # enrichment cache (keyed by cluster_id) survives across cycles.
  801. assert all_clusters[0]["cluster_id"] == "old-id"
  802. # The existing article must still be in the merged cluster.
  803. article_urls = [a["url"] for a in all_clusters[0]["articles"]]
  804. assert url in article_urls