poller.py 23 KB

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