poller.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. from __future__ import annotations
  2. import asyncio
  3. import hashlib
  4. import logging
  5. import sys
  6. from collections import defaultdict
  7. from dataclasses import dataclass, field
  8. from datetime import datetime, timezone, timedelta
  9. from typing import Any, Dict
  10. from news_mcp.config import (
  11. DEFAULT_TOPICS,
  12. DB_PATH,
  13. ENRICH_OTHER_TOPICS_ONLY,
  14. NEWS_EXTRACT_PROVIDER,
  15. NEWS_FEED_URL,
  16. NEWS_FEED_URLS,
  17. NEWS_PRUNE_INTERVAL_HOURS,
  18. NEWS_PRUNING_ENABLED,
  19. NEWS_RETENTION_DAYS,
  20. NEWS_CLUSTER_MAX_AGE_HOURS,
  21. llm_concurrency,
  22. llm_rate_limit,
  23. )
  24. from news_mcp.dedup.cluster import dedup_and_cluster_articles, _cluster_is_within_age_window, _parse_ts
  25. from news_mcp.enrichment.enrich import enrich_cluster
  26. from news_mcp.enrichment.llm_enrich import classify_cluster_llm
  27. from news_mcp.sources.news_feeds import fetch_news_articles
  28. from news_mcp.storage.sqlite_store import SQLiteClusterStore
  29. # --------------------------------------------------------------------------- #
  30. # Per-feed + per-cycle statistics
  31. # --------------------------------------------------------------------------- #
  32. @dataclass
  33. class FeedStats:
  34. """Per-feed statistics for one polling cycle."""
  35. feed_url: str
  36. fetched: int = 0 # total items fetched from the feed
  37. duplicate: int = 0 # unchanged hash → skipped entirely
  38. stale: int = 0 # older than retention window (dropped)
  39. ingested: int = 0 # passed dedup + retention, entered clustering
  40. enriched: int = 0 # newly LLM-enriched this cycle
  41. already_enriched: int = 0 # cache hit — already had entities+keywords
  42. failed: int = 0 # LLM enrichment failed after retries
  43. @dataclass
  44. class PollStats:
  45. """Aggregated statistics for one polling cycle."""
  46. started_at: str = ""
  47. feeds: list[FeedStats] = field(default_factory=list)
  48. total_clusters: int = 0
  49. total_newly_enriched: int = 0
  50. total_already_enriched: int = 0
  51. total_failed: int = 0
  52. def summary(self) -> dict:
  53. return {
  54. "started_at": self.started_at,
  55. "feeds": [
  56. {
  57. "feed_url": f.feed_url,
  58. "fetched": f.fetched,
  59. "duplicate": f.duplicate,
  60. "stale": f.stale,
  61. "ingested": f.ingested,
  62. }
  63. for f in self.feeds
  64. ],
  65. "total_clusters": self.total_clusters,
  66. "total_newly_enriched": self.total_newly_enriched,
  67. "total_already_enriched": self.total_already_enriched,
  68. "total_failed": self.total_failed,
  69. }
  70. # --------------------------------------------------------------------------- #
  71. # Poller
  72. # --------------------------------------------------------------------------- #
  73. class ClusterPoller:
  74. """One polling cycle: fetch → dedup → cluster → enrich-once → store."""
  75. MAX_ENRICHMENT_RETRIES = 3
  76. def __init__(
  77. self,
  78. store: SQLiteClusterStore,
  79. logger: logging.Logger | None = None,
  80. ):
  81. self.store = store
  82. self.logger = logger or logging.getLogger("news_mcp.refresh")
  83. self.stats = PollStats()
  84. # ------------------------------------------------------------------ #
  85. # Public entry point
  86. # ------------------------------------------------------------------ #
  87. async def poll(self, topic_filter: str | None = None) -> PollStats:
  88. """Run one full polling cycle. Returns statistics."""
  89. self.stats = PollStats(started_at=datetime.now(timezone.utc).isoformat())
  90. # 1. Load enabled feed URLs
  91. configured_urls = self._load_feed_urls()
  92. enabled_urls = self.store.get_enabled_feed_urls(configured_urls)
  93. self.logger.info("poll start: enabled_feeds=%d configured=%d", len(enabled_urls), len(configured_urls))
  94. # 2. Fetch articles from all enabled feeds, per-feed dedup
  95. feed_map, feed_stats = await self._fetch_feeds(enabled_urls)
  96. # Flatten all fresh articles (stats already tracked per-feed in feed_stats)
  97. all_fresh = [a for articles in feed_map.values() for a in articles]
  98. if not all_fresh:
  99. self.logger.info("poll: no fresh articles from any feed")
  100. self.stats.feeds = feed_stats
  101. self._save_feed_stats(feed_stats)
  102. self._prune_and_finalize(enabled_urls, feed_map)
  103. return self.stats
  104. # 3. Retention filter
  105. articles = self._apply_retention(all_fresh, feed_map)
  106. if not articles:
  107. self.logger.info("poll: all %d fresh articles dropped by retention", len(all_fresh))
  108. self.stats.feeds = feed_stats
  109. self._save_feed_stats(feed_stats)
  110. self._prune_and_finalize(enabled_urls, feed_map)
  111. return self.stats
  112. # 4. Pre-seed existing clusters for cross-cycle merging
  113. existing_clusters = self._preseed_clusters()
  114. # 5. Cluster (sync, may do concurrent embeddings internally)
  115. clustered_by_topic = await self._cluster(articles, existing_clusters)
  116. # 6. Enrich every cluster that needs it, store immediately
  117. await self._enrich_all(clustered_by_topic)
  118. # 7. Retry previously failed enrichments
  119. await self._retry_failed()
  120. # 8. Persist feed stats + prune
  121. self.stats.feeds = feed_stats
  122. self._save_feed_stats(feed_stats)
  123. self._prune_and_finalize(enabled_urls, feed_map)
  124. self.logger.info(
  125. "poll complete: clusters=%d newly_enriched=%d already_enriched=%d failed=%d",
  126. self.stats.total_clusters,
  127. self.stats.total_newly_enriched,
  128. self.stats.total_already_enriched,
  129. self.stats.total_failed,
  130. )
  131. return self.stats
  132. # ------------------------------------------------------------------ #
  133. # Phase 1: Load feed URLs
  134. # ------------------------------------------------------------------ #
  135. @staticmethod
  136. def _load_feed_urls() -> list[str]:
  137. urls = [u.strip() for u in NEWS_FEED_URLS.split(",") if u.strip()]
  138. if not urls:
  139. urls = [NEWS_FEED_URL]
  140. return urls
  141. # ------------------------------------------------------------------ #
  142. # Phase 2: Fetch + per-feed dedup
  143. # ------------------------------------------------------------------ #
  144. async def _fetch_feeds(
  145. self, feed_urls: list[str],
  146. ) -> tuple[dict[str, list[dict]], list[FeedStats]]:
  147. """Fetch all feeds concurrently. Returns {feed_url: fresh_articles}
  148. and per-feed stats. Unchanged feeds (same content hash) are dropped."""
  149. articles = await fetch_news_articles(limit=9999, url_list=feed_urls)
  150. # limit=9999 effectively means no per-feed cap — fetches everything
  151. # the feed gives us. fetch_news_articles applies max(1, limit).
  152. # Group by feed URL
  153. per_feed: dict[str, list[dict]] = defaultdict(list)
  154. for a in articles:
  155. fu = str(a.get("feed_url") or NEWS_FEED_URL).strip() or NEWS_FEED_URL
  156. per_feed[fu].append(a)
  157. # Per-feed content hash dedup
  158. feed_map: dict[str, list[dict]] = {}
  159. feed_stats_list: list[FeedStats] = []
  160. for feed_url in feed_urls:
  161. feed_articles = per_feed.get(feed_url, [])
  162. stats = FeedStats(feed_url=feed_url, fetched=len(feed_articles))
  163. if not feed_articles:
  164. self.logger.info("feed empty: feed_url=%s", feed_url)
  165. feed_stats_list.append(stats)
  166. continue
  167. material = "\n".join(
  168. f"{a.get('title','')}|{a.get('url','')}|{a.get('timestamp','')}"
  169. for a in feed_articles
  170. )
  171. content_hash = hashlib.sha1(material.encode("utf-8")).hexdigest()
  172. prev_hash = self.store.get_feed_hash(feed_url)
  173. if prev_hash == content_hash:
  174. stats.duplicate = len(feed_articles)
  175. self.logger.info("feed unchanged: feed_url=%s items=%d", feed_url, len(feed_articles))
  176. feed_stats_list.append(stats)
  177. continue
  178. feed_map[feed_url] = feed_articles
  179. self.logger.info(
  180. "feed changed: feed_url=%s items=%d hash_prev=%s hash_now=%s",
  181. feed_url, len(feed_articles),
  182. (prev_hash or "-")[:12], content_hash[:12],
  183. )
  184. feed_stats_list.append(stats)
  185. return feed_map, feed_stats_list
  186. # ------------------------------------------------------------------ #
  187. # Phase 3: Retention filter
  188. # ------------------------------------------------------------------ #
  189. def _apply_retention(
  190. self, articles: list[dict], feed_map: dict[str, list[dict]],
  191. ) -> list[dict]:
  192. """Drop articles older than NEWS_RETENTION_DAYS. Updates FeedStats."""
  193. if NEWS_RETENTION_DAYS <= 0:
  194. return articles
  195. cutoff = datetime.now(timezone.utc) - timedelta(days=NEWS_RETENTION_DAYS)
  196. # Build a lookup: article_url → feed_url for stats
  197. article_feed: dict[str, str] = {}
  198. for fu, arts in feed_map.items():
  199. for a in arts:
  200. article_feed[a.get("url", "")] = fu
  201. fresh = []
  202. dropped = 0
  203. for a in articles:
  204. ts_str = a.get("timestamp", "")
  205. if not ts_str:
  206. fresh.append(a)
  207. continue
  208. dt = _parse_ts(ts_str)
  209. if dt is None or dt >= cutoff:
  210. fresh.append(a)
  211. else:
  212. dropped += 1
  213. fu = article_feed.get(a.get("url", ""), "")
  214. if fu:
  215. # Find matching FeedStats and increment stale
  216. for fs in self.stats.feeds:
  217. if fs.feed_url == fu:
  218. fs.stale += 1
  219. break
  220. if dropped:
  221. self.logger.info("retention: dropped=%d remaining=%d retention_days=%.0f", dropped, len(fresh), NEWS_RETENTION_DAYS)
  222. return fresh
  223. # ------------------------------------------------------------------ #
  224. # Phase 4: Pre-seed existing clusters
  225. # ------------------------------------------------------------------ #
  226. def _preseed_clusters(self) -> list[dict]:
  227. """Load recent clusters from DB for cross-cycle article merging."""
  228. max_age = NEWS_CLUSTER_MAX_AGE_HOURS
  229. if max_age == 0:
  230. return []
  231. lookback = max_age if max_age > 0 else 72
  232. all_recent = self.store.get_latest_clusters_all_topics(ttl_hours=lookback, limit=500)
  233. recent = [c for c in all_recent if _cluster_is_within_age_window(c, max_age_hours=max_age)]
  234. self.logger.info("pre-seeded: existing_clusters=%d max_age_h=%.1f", len(recent), max_age)
  235. return recent
  236. # ------------------------------------------------------------------ #
  237. # Phase 5: Clustering
  238. # ------------------------------------------------------------------ #
  239. async def _cluster(
  240. self, articles: list[dict], existing_clusters: list[dict],
  241. ) -> dict[str, list[dict]]:
  242. """Run dedup_and_cluster_articles. Returns {topic: [clusters]}."""
  243. self.logger.info("clustering: articles=%d existing_clusters=%d", len(articles), len(existing_clusters))
  244. clustered = await asyncio.to_thread(
  245. dedup_and_cluster_articles,
  246. articles,
  247. None, # default similarity_threshold
  248. existing_clusters=existing_clusters if existing_clusters else None,
  249. max_age_hours=NEWS_CLUSTER_MAX_AGE_HOURS,
  250. )
  251. self.logger.info("clustered: topics=%s", list(clustered.keys()))
  252. return clustered
  253. # ------------------------------------------------------------------ #
  254. # Phase 6: Enrich + store
  255. # ------------------------------------------------------------------ #
  256. async def _enrich_all(self, clustered_by_topic: dict[str, list[dict]]) -> None:
  257. """Enrich every cluster that needs it and store immediately."""
  258. semaphore = asyncio.Semaphore(llm_concurrency(NEWS_EXTRACT_PROVIDER))
  259. rate = llm_rate_limit(NEWS_EXTRACT_PROVIDER)
  260. self.logger.info(
  261. "enrich: semaphore_limit=%d rate_limit=%s/s provider=%s",
  262. llm_concurrency(NEWS_EXTRACT_PROVIDER), rate, NEWS_EXTRACT_PROVIDER,
  263. )
  264. # Flatten all clusters into one list with their topics
  265. all_targets: list[tuple[str, dict]] = []
  266. for topic, clusters in clustered_by_topic.items():
  267. for c in clusters:
  268. all_targets.append((topic, c))
  269. if not all_targets:
  270. return
  271. # Enrich concurrently
  272. tasks = [
  273. self._enrich_one(c, topic, semaphore, rate)
  274. for topic, c in all_targets
  275. ]
  276. results = await asyncio.gather(*tasks, return_exceptions=False)
  277. # Store each cluster individually, grouped by final topic
  278. by_final_topic: dict[str, list[dict]] = defaultdict(list)
  279. for c2, was_new in results:
  280. final_topic = str(c2.get("topic") or "other").strip().lower()
  281. if final_topic not in {t.lower() for t in DEFAULT_TOPICS}:
  282. final_topic = "other"
  283. by_final_topic[final_topic].append(c2)
  284. self.stats.total_clusters += 1
  285. if was_new:
  286. self.stats.total_newly_enriched += 1
  287. else:
  288. self.stats.total_already_enriched += 1
  289. for final_topic, group in by_final_topic.items():
  290. self.store.upsert_clusters(group, topic=final_topic)
  291. self.logger.info("stored: topic=%s clusters=%d", final_topic, len(group))
  292. async def _enrich_one(
  293. self,
  294. cluster: dict,
  295. topic: str,
  296. semaphore: asyncio.Semaphore,
  297. rate: float,
  298. ) -> tuple[dict, bool]:
  299. """Enrich a single cluster. Returns (cluster, was_newly_enriched).
  300. If the cluster already has entities AND keywords, skip LLM entirely.
  301. The data on the dict IS the cache — no timestamp or DB lookup needed.
  302. """
  303. c2 = enrich_cluster(cluster)
  304. c2.setdefault("topic", topic)
  305. llm_enabled = (not ENRICH_OTHER_TOPICS_ONLY) or (topic == "other")
  306. cluster_id = c2.get("cluster_id")
  307. if not llm_enabled or not cluster_id:
  308. return c2, False
  309. # Cache check: entities + keywords already present → skip
  310. if (c2.get("entities") or []) and (c2.get("keywords") or []):
  311. self.logger.debug("enrich skip (cached): cluster=%s topic=%s", cluster_id, topic)
  312. return c2, False
  313. # Actually call the LLM
  314. last_err = ""
  315. for attempt in range(1 + self.MAX_ENRICHMENT_RETRIES):
  316. if attempt > 0:
  317. backoff = 2 ** attempt
  318. self.logger.info("retry: cluster=%s attempt=%d backoff=%.0fs", cluster_id, attempt, backoff)
  319. await asyncio.sleep(backoff)
  320. try:
  321. async with semaphore:
  322. c2 = await classify_cluster_llm(dict(c2))
  323. c2["enriched_at"] = datetime.now(timezone.utc).isoformat()
  324. return c2, True
  325. except Exception:
  326. last_err = str(sys.exc_info()[1])[:200] if sys.exc_info()[1] else "unknown"
  327. self.logger.warning(
  328. "enrich failed: cluster=%s attempt=%d err=%s",
  329. cluster_id, attempt, last_err,
  330. )
  331. # All retries exhausted
  332. prev_count = c2.get("enrichment_retry_count", 0)
  333. c2["enrichment_failed_at"] = datetime.now(timezone.utc).isoformat()
  334. c2["enrichment_retry_count"] = prev_count + 1
  335. self.logger.error("enrich exhausted: cluster=%s after %d retries", cluster_id, self.MAX_ENRICHMENT_RETRIES)
  336. self.stats.total_failed += 1
  337. return c2, True # was "newly" enriched (attempted), but failed
  338. # ------------------------------------------------------------------ #
  339. # Phase 7: Retry failed enrichments
  340. # ------------------------------------------------------------------ #
  341. async def _retry_failed(self) -> None:
  342. """Retry clusters whose previous enrichment failed."""
  343. failed = self.store.get_failed_enrichment_clusters(max_retries=3)
  344. if not failed:
  345. return
  346. self.logger.info("retry: failed_clusters=%d", len(failed))
  347. semaphore = asyncio.Semaphore(llm_concurrency(NEWS_EXTRACT_PROVIDER))
  348. rate = llm_rate_limit(NEWS_EXTRACT_PROVIDER)
  349. tasks = [
  350. self._enrich_one(c, str(c.get("topic") or "other"), semaphore, rate)
  351. for c in failed
  352. ]
  353. results = await asyncio.gather(*tasks, return_exceptions=False)
  354. by_topic: dict[str, list[dict]] = defaultdict(list)
  355. attempted = 0
  356. now_success = 0
  357. still_failed = 0
  358. for c2, was_new in results:
  359. if not was_new:
  360. continue
  361. attempted += 1
  362. # Clear failure marker on success
  363. if c2.get("enriched_at") and not c2.get("enrichment_failed_at"):
  364. c2.pop("enrichment_failed_at", None)
  365. c2.pop("enrichment_retry_count", None)
  366. now_success += 1
  367. else:
  368. still_failed += 1
  369. t = str(c2.get("topic") or "other").strip().lower()
  370. if t not in {x.lower() for x in DEFAULT_TOPICS}:
  371. t = "other"
  372. by_topic[t].append(c2)
  373. for t, group in by_topic.items():
  374. self.store.upsert_clusters(group, topic=t)
  375. self.logger.info("retry stored: topic=%s clusters=%d", t, len(group))
  376. if attempted:
  377. self.logger.info("retry done: attempted=%d recovered=%d still_failed=%d", attempted, now_success, still_failed)
  378. # ------------------------------------------------------------------ #
  379. # Phase 8: Feed stats + prune
  380. # ------------------------------------------------------------------ #
  381. def _save_feed_stats(self, feed_stats: list[FeedStats]) -> None:
  382. """Log per-feed statistics. ingested = fetched - duplicate - stale."""
  383. for fs in feed_stats:
  384. fs.ingested = max(0, fs.fetched - fs.duplicate - fs.stale)
  385. self.logger.info(
  386. "feed stats: feed_url=%s fetched=%d duplicate=%d stale=%d ingested=%d",
  387. fs.feed_url, fs.fetched, fs.duplicate, fs.stale, fs.ingested,
  388. )
  389. def _prune_and_finalize(
  390. self,
  391. enabled_urls: list[str],
  392. feed_map: dict[str, list[dict]],
  393. ) -> None:
  394. """Run pruning and update feed_state hashes + timestamps."""
  395. prune_result = self.store.prune_if_due(
  396. pruning_enabled=NEWS_PRUNING_ENABLED,
  397. retention_days=NEWS_RETENTION_DAYS,
  398. interval_hours=NEWS_PRUNE_INTERVAL_HOURS,
  399. )
  400. # Update feed_state: hash + item_count for feeds that had changes
  401. for feed_url, feed_articles in feed_map.items():
  402. material = "\n".join(
  403. f"{a.get('title','')}|{a.get('url','')}|{a.get('timestamp','')}"
  404. for a in feed_articles
  405. )
  406. content_hash = hashlib.sha1(material.encode("utf-8")).hexdigest()
  407. self.store.set_feed_state(feed_url, content_hash, len(feed_articles))
  408. # Drop legacy aggregate feed-state rows
  409. with self.store._conn() as conn:
  410. conn.execute("DELETE FROM feed_state WHERE feed_key LIKE 'newsfeeds:%'")
  411. self.store.set_meta("last_refresh_at", datetime.now(timezone.utc).isoformat())
  412. self.logger.info("prune: %s", prune_result)
  413. # --------------------------------------------------------------------------- #
  414. # Compatibility wrapper (used by background loop + tests)
  415. # --------------------------------------------------------------------------- #
  416. async def refresh_clusters(topic: str | None = None, limit: int = 80) -> None:
  417. """Backward-compatible entry point. Delegates to ClusterPoller."""
  418. store = SQLiteClusterStore(DB_PATH)
  419. poller = ClusterPoller(store)
  420. await poller.poll(topic_filter=topic)