poller.py 12 KB

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