poller.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. from __future__ import annotations
  2. import asyncio
  3. import hashlib
  4. import logging
  5. import sys
  6. from collections import defaultdict
  7. from datetime import datetime, timezone, timedelta
  8. from typing import Any, Dict
  9. from news_mcp.config import (
  10. DEFAULT_LOOKBACK_HOURS,
  11. DEFAULT_TOPICS,
  12. DB_PATH,
  13. ENRICH_OTHER_TOPICS_ONLY,
  14. ENRICHMENT_MAX_PER_REFRESH,
  15. NEWS_EXTRACT_PROVIDER,
  16. NEWS_FEED_URL,
  17. NEWS_FEED_URLS,
  18. NEWS_PRUNE_INTERVAL_HOURS,
  19. NEWS_PRUNING_ENABLED,
  20. NEWS_RETENTION_DAYS,
  21. NEWS_CLUSTER_MAX_AGE_HOURS,
  22. llm_concurrency,
  23. )
  24. from news_mcp.dedup.cluster import dedup_and_cluster_articles
  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. from news_mcp.trends_resolution import resolve_entity_via_trends
  30. def _load_feed_urls() -> list[str]:
  31. """Return the configured feed URLs from environment (unsorted)."""
  32. urls = [u.strip() for u in NEWS_FEED_URLS.split(",") if u.strip()]
  33. if not urls:
  34. urls = [NEWS_FEED_URL]
  35. return urls
  36. MAX_ENRICHMENT_RETRIES = 3 # per-cluster retries before giving up for this cycle
  37. async def _enrich_single_cluster(
  38. c: dict,
  39. topic: str,
  40. llm_enabled: bool,
  41. semaphore: asyncio.Semaphore,
  42. store: SQLiteClusterStore,
  43. logger: logging.Logger,
  44. ) -> dict:
  45. """Enrich one cluster: heuristic + optional LLM extraction, concurrency-limited.
  46. On LLM failure the cluster is retried up to MAX_ENRICHMENT_RETRIES times
  47. with exponential backoff. If all retries are exhausted the cluster is
  48. marked with enrichment_failed_at and enrichment_retry_count so the next
  49. polling cycle can re-attempt it.
  50. """
  51. c2 = enrich_cluster(c)
  52. c2.setdefault("topic", topic)
  53. cluster_id = c2.get("cluster_id")
  54. if llm_enabled and cluster_id:
  55. # Cache: if we already have entities/sentiment for this cluster, skip LLM call.
  56. existing = store.get_cluster_by_id(cluster_id)
  57. if existing and existing.get("entities"):
  58. c2 = dict(c2)
  59. c2["entities"] = existing.get("entities", [])
  60. existing_resolutions = existing.get("entityResolutions", None)
  61. if isinstance(existing_resolutions, list) and existing_resolutions:
  62. c2["entityResolutions"] = existing_resolutions
  63. else:
  64. c2["entityResolutions"] = [resolve_entity_via_trends(e) for e in c2["entities"]]
  65. if existing.get("sentiment"):
  66. c2["sentiment"] = existing.get("sentiment")
  67. if existing.get("sentimentScore") is not None:
  68. c2["sentimentScore"] = existing.get("sentimentScore")
  69. if existing.get("keywords"):
  70. c2["keywords"] = existing.get("keywords")
  71. if existing.get("topic"):
  72. c2["topic"] = existing.get("topic")
  73. else:
  74. # Retry loop with exponential backoff | semaphore held per-attempt
  75. last_err = ""
  76. for attempt in range(1 + MAX_ENRICHMENT_RETRIES):
  77. if attempt > 0:
  78. backoff = 2 ** attempt
  79. logger.info(
  80. "retry cluster=%s topic=%s attempt=%d/%d backoff=%.0fs",
  81. cluster_id, topic, attempt, MAX_ENRICHMENT_RETRIES, backoff,
  82. )
  83. await asyncio.sleep(backoff)
  84. try:
  85. async with semaphore:
  86. c2 = await classify_cluster_llm(dict(c2))
  87. break # success
  88. except Exception:
  89. last_err = str(sys.exc_info()[1])[:200] if sys.exc_info()[1] else "unknown"
  90. logger.warning(
  91. "LLM enrichment failed cluster=%s topic=%s attempt=%d/%d err=%s",
  92. cluster_id, topic, attempt, MAX_ENRICHMENT_RETRIES, last_err,
  93. )
  94. else:
  95. # Loop completed without break = all retries exhausted
  96. prev_count = c2.get("enrichment_retry_count", 0)
  97. c2["enrichment_failed_at"] = datetime.now(timezone.utc).isoformat()
  98. c2["enrichment_retry_count"] = prev_count + 1
  99. logger.error(
  100. "LLM enrichment exhausted cluster=%s topic=%s after %d retries",
  101. cluster_id, topic, MAX_ENRICHMENT_RETRIES,
  102. )
  103. return c2
  104. async def _enrich_topic_clusters(
  105. clusters: list[dict],
  106. topic: str,
  107. semaphore: asyncio.Semaphore,
  108. store: SQLiteClusterStore,
  109. logger: logging.Logger,
  110. enrich_limit: int,
  111. ) -> list[dict]:
  112. """Enrich all clusters for a single topic concurrently."""
  113. llm_enabled = (not ENRICH_OTHER_TOPICS_ONLY) or (topic == "other")
  114. # Persist the raw clusters first so a slow enrichment pass does not
  115. # leave the first bootstrap run with nothing stored.
  116. store.upsert_clusters(clusters, topic=topic)
  117. logger.info("refresh stored raw topic=%s clusters=%s", topic, len(clusters))
  118. targets = clusters[:enrich_limit]
  119. tasks = [
  120. _enrich_single_cluster(c, topic, llm_enabled, semaphore, store, logger)
  121. for c in targets
  122. ]
  123. enriched = await asyncio.gather(*tasks, return_exceptions=False)
  124. # Any clusters beyond enrich_limit still need importance enrichment
  125. for c in clusters[enrich_limit:]:
  126. c2 = enrich_cluster(c)
  127. c2.setdefault("topic", topic)
  128. enriched.append(c2)
  129. logger.info("refresh enriched topic=%s clusters=%s", topic, len(enriched))
  130. return enriched
  131. def _cluster_age_ok(cluster: dict, max_age_hours: float) -> bool:
  132. """Check whether a cluster's last_updated is within the merge window."""
  133. if max_age_hours <= 0:
  134. return True
  135. ts_str = cluster.get("last_updated") or cluster.get("timestamp") or ""
  136. if not ts_str:
  137. return True
  138. try:
  139. s = str(ts_str).replace("Z", "+00:00")
  140. dt = datetime.fromisoformat(s)
  141. if dt.tzinfo is None:
  142. dt = dt.replace(tzinfo=timezone.utc)
  143. dt = dt.astimezone(timezone.utc)
  144. except Exception:
  145. try:
  146. from email.utils import parsedate_to_datetime
  147. dt = parsedate_to_datetime(str(ts_str))
  148. if dt.tzinfo is None:
  149. dt = dt.replace(tzinfo=timezone.utc)
  150. dt = dt.astimezone(timezone.utc)
  151. except Exception:
  152. return True
  153. cutoff = datetime.now(timezone.utc) - timedelta(hours=max_age_hours)
  154. return dt >= cutoff
  155. async def refresh_clusters(topic: str | None = None, limit: int = 80) -> None:
  156. logger = logging.getLogger("news_mcp.refresh")
  157. store = SQLiteClusterStore(DB_PATH)
  158. logger.info("refresh start topic=%s limit=%s", topic, limit)
  159. # Get enabled feed URLs from store (seeds new ones as enabled by default).
  160. configured_urls = _load_feed_urls()
  161. enabled_urls = store.get_enabled_feed_urls(configured_urls)
  162. logger.info("refresh enabled feeds=%d / configured=%d", len(enabled_urls), len(configured_urls))
  163. # fetch_news_articles is now fully async (concurrent RSS fetching)
  164. articles = await fetch_news_articles(limit, url_list=enabled_urls)
  165. logger.info("refresh fetched articles=%s", len(articles))
  166. # Drop legacy aggregate feed-state rows so the dashboard only reflects
  167. # real per-feed poll status from this point forward.
  168. with store._conn() as conn:
  169. conn.execute("DELETE FROM feed_state WHERE feed_key LIKE 'newsfeeds:%'")
  170. # Track feed freshness per RSS URL so unchanged feeds can be skipped.
  171. per_feed: dict[str, list[dict[str, Any]]] = defaultdict(list)
  172. for article in articles:
  173. feed_url = str(article.get("feed_url") or NEWS_FEED_URL).strip() or NEWS_FEED_URL
  174. per_feed[feed_url].append(article)
  175. changed_articles: list[dict[str, Any]] = []
  176. changed_feed_urls: list[str] = []
  177. for feed_url, feed_articles in per_feed.items():
  178. logger.info("refresh feed batch start feed_url=%s count=%s", feed_url, len(feed_articles))
  179. material = "\n".join(
  180. f"{a.get('title','')}|{a.get('url','')}|{a.get('timestamp','')}"
  181. for a in feed_articles
  182. )
  183. last_hash = hashlib.sha1(material.encode("utf-8")).hexdigest()
  184. feed_key = feed_url
  185. prev_hash = store.get_feed_hash(feed_key)
  186. if prev_hash == last_hash:
  187. logger.info("refresh unchanged feed_url=%s count=%s topic=%s", feed_url, len(feed_articles), topic)
  188. else:
  189. logger.info("refresh changed feed_url=%s count=%s topic=%s", feed_url, len(feed_articles), topic)
  190. changed_feed_urls.append(feed_url)
  191. changed_articles.extend(feed_articles)
  192. logger.info("refresh feed batch complete feed_url=%s changed_total=%s", feed_url, len(changed_articles))
  193. if not changed_articles:
  194. logger.info("refresh unchanged all feeds topic=%s", topic)
  195. store.set_meta("last_refresh_at", datetime.now(timezone.utc).isoformat())
  196. prune_result = store.prune_if_due(
  197. pruning_enabled=NEWS_PRUNING_ENABLED,
  198. retention_days=NEWS_RETENTION_DAYS,
  199. interval_hours=NEWS_PRUNE_INTERVAL_HOURS,
  200. )
  201. logger.info("refresh prune_result=%s", prune_result)
  202. return
  203. articles = changed_articles
  204. logger.info("refresh clustering start articles=%s topic=%s", len(articles), topic)
  205. # Pre-seed with recent clusters from the DB so new articles can merge
  206. # into existing clusters across polling cycles.
  207. max_age = NEWS_CLUSTER_MAX_AGE_HOURS
  208. recent_clusters: list[dict] = []
  209. if max_age != 0:
  210. lookback = max_age if max_age > 0 else 72
  211. all_recent = store.get_latest_clusters_all_topics(
  212. ttl_hours=lookback,
  213. limit=500,
  214. )
  215. recent_clusters = [c for c in all_recent if _cluster_age_ok(c, max_age)]
  216. logger.info(
  217. "refresh pre-seeded existing_clusters=%s max_age_h=%s",
  218. len(recent_clusters), max_age,
  219. )
  220. # Clustering is sync but may do concurrent embedding fetches internally.
  221. # Run off-thread so the event loop stays responsive for MCP tool calls.
  222. clustered_by_topic = await asyncio.to_thread(
  223. dedup_and_cluster_articles,
  224. articles,
  225. None, # use default similarity_threshold
  226. existing_clusters=recent_clusters if recent_clusters else None,
  227. max_age_hours=max_age,
  228. )
  229. logger.info("refresh clustered topics=%s", list(clustered_by_topic.keys()))
  230. # Build LLM concurrency semaphore from the extract provider's config.
  231. max_llm_concurrent = llm_concurrency(NEWS_EXTRACT_PROVIDER)
  232. llm_semaphore = asyncio.Semaphore(max_llm_concurrent)
  233. logger.info("refresh llm semaphore limit=%s provider=%s", max_llm_concurrent, NEWS_EXTRACT_PROVIDER)
  234. # Enrich each topic's clusters concurrently.
  235. topic_tasks = []
  236. for t, clusters in clustered_by_topic.items():
  237. if topic and t != topic:
  238. continue
  239. # Determine how many clusters to LLM-enrich.
  240. # ENRICHMENT_MAX_PER_REFRESH=0 means enrich every cluster (no cap).
  241. enrich_limit = ENRICHMENT_MAX_PER_REFRESH or len(clusters)
  242. topic_tasks.append(
  243. _enrich_topic_clusters(
  244. clusters=clusters,
  245. topic=t,
  246. semaphore=llm_semaphore,
  247. store=store,
  248. logger=logger,
  249. enrich_limit=enrich_limit,
  250. )
  251. )
  252. # Run all topic enrichment phases concurrently
  253. topic_results = await asyncio.gather(*topic_tasks, return_exceptions=False)
  254. # Persist enriched clusters grouped by their final topic
  255. for enriched in topic_results:
  256. by_final_topic: Dict[str, list] = {}
  257. for c2 in enriched:
  258. final_topic = str(c2.get("topic") or "other").strip().lower()
  259. if final_topic not in {x.lower() for x in DEFAULT_TOPICS}:
  260. final_topic = "other"
  261. by_final_topic.setdefault(final_topic, []).append(c2)
  262. for final_topic, group in by_final_topic.items():
  263. store.upsert_clusters(group, topic=final_topic)
  264. logger.info("refresh stored topic=%s clusters=%s", final_topic, len(group))
  265. # Retry previously failed enrichments
  266. failed_clusters = store.get_failed_enrichment_clusters(max_retries=3)
  267. if failed_clusters:
  268. logger.info("retry enrich failed clusters count=%d", len(failed_clusters))
  269. retry_tasks = [
  270. _enrich_single_cluster(
  271. c, str(c.get("topic") or "other"), True, llm_semaphore, store, logger
  272. )
  273. for c in failed_clusters
  274. ]
  275. retry_results = await asyncio.gather(*retry_tasks, return_exceptions=False)
  276. # Persist retried results
  277. by_topic_retry: Dict[str, list] = {}
  278. for c2 in retry_results:
  279. # Clear stale failure marker on success
  280. if not c2.get("enrichment_failed_at") or c2.get("entities"):
  281. c2.pop("enrichment_failed_at", None)
  282. c2.pop("enrichment_retry_count", None)
  283. t = str(c2.get("topic") or "other").strip().lower()
  284. if t not in {x.lower() for x in DEFAULT_TOPICS}:
  285. t = "other"
  286. by_topic_retry.setdefault(t, []).append(c2)
  287. for t, group in by_topic_retry.items():
  288. store.upsert_clusters(group, topic=t)
  289. logger.info("retry stored topic=%s clusters=%s", t, len(group))
  290. prune_result = store.prune_if_due(
  291. pruning_enabled=NEWS_PRUNING_ENABLED,
  292. retention_days=NEWS_RETENTION_DAYS,
  293. interval_hours=NEWS_PRUNE_INTERVAL_HOURS,
  294. )
  295. for feed_url in changed_feed_urls:
  296. feed_articles = per_feed[feed_url]
  297. material = "\n".join(
  298. f"{a.get('title','')}|{a.get('url','')}|{a.get('timestamp','')}"
  299. for a in feed_articles
  300. )
  301. last_hash = hashlib.sha1(material.encode("utf-8")).hexdigest()
  302. store.set_feed_state(feed_url, last_hash, len(feed_articles))
  303. store.set_meta("last_refresh_at", datetime.now(timezone.utc).isoformat())
  304. logger.info("refresh prune_result=%s", prune_result)