poller.py 23 KB

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