poller.py 14 KB

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