poller.py 12 KB

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