poller.py 20 KB

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