sqlite_store.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. from __future__ import annotations
  2. import json
  3. import sqlite3
  4. from dataclasses import dataclass
  5. from datetime import datetime, timezone, timedelta
  6. from pathlib import Path
  7. from typing import Any
  8. from urllib.parse import urlparse
  9. from email.utils import parsedate_to_datetime
  10. from news_mcp.entity_normalize import normalize_entities
  11. from news_mcp.trends_resolution import resolve_entity_via_trends
  12. @dataclass
  13. class ClusterRow:
  14. cluster_id: str
  15. topic: str
  16. payload: dict
  17. updated_at: datetime
  18. META_LAST_PRUNE_AT = "last_prune_at"
  19. def _article_key(article: dict[str, Any]) -> str:
  20. url = str(article.get("url") or "").strip()
  21. if not url:
  22. return str(article.get("title") or "")
  23. try:
  24. parsed = urlparse(url)
  25. parts = [p for p in parsed.path.split("/") if p]
  26. if parts:
  27. return parts[-1]
  28. except Exception:
  29. pass
  30. return url
  31. def _dedup_articles(articles: list[dict[str, Any]]) -> list[dict[str, Any]]:
  32. seen: set[str] = set()
  33. out: list[dict[str, Any]] = []
  34. for article in articles:
  35. key = _article_key(article)
  36. if key in seen:
  37. continue
  38. seen.add(key)
  39. out.append(article)
  40. return out
  41. def _has_valid_entity_resolutions(resolutions: Any, entities: list[str]) -> bool:
  42. if not isinstance(resolutions, list):
  43. return False
  44. if len(resolutions) != len(entities):
  45. return False
  46. for res in resolutions:
  47. if not isinstance(res, dict):
  48. return False
  49. if not res.get("normalized") or not res.get("canonical_label"):
  50. return False
  51. return True
  52. def sanitize_cluster_payload(cluster: dict[str, Any], *, include_resolutions: bool = True) -> dict[str, Any]:
  53. """Normalize cluster payload so every stored payload is internally consistent."""
  54. out = dict(cluster)
  55. raw_articles = out.get("articles", []) or []
  56. articles = [a for a in raw_articles if isinstance(a, dict)]
  57. out["articles"] = _dedup_articles(articles)
  58. raw_entities = out.get("entities", []) or []
  59. entities = normalize_entities(raw_entities)
  60. out["entities"] = entities
  61. if not include_resolutions:
  62. return out
  63. resolutions = out.get("entityResolutions", None)
  64. if entities:
  65. if not _has_valid_entity_resolutions(resolutions, entities):
  66. out["entityResolutions"] = [resolve_entity_via_trends(e) for e in entities]
  67. else:
  68. # Keep the empty case explicit and stable.
  69. out["entityResolutions"] = []
  70. return out
  71. class SQLiteClusterStore:
  72. def __init__(self, db_path: str | Path):
  73. self.db_path = str(db_path)
  74. self._init_db()
  75. def _conn(self) -> sqlite3.Connection:
  76. return sqlite3.connect(self.db_path)
  77. def _init_db(self) -> None:
  78. Path(self.db_path).parent.mkdir(parents=True, exist_ok=True)
  79. with self._conn() as conn:
  80. conn.execute("PRAGMA journal_mode=WAL")
  81. conn.execute("PRAGMA synchronous=NORMAL")
  82. conn.execute("PRAGMA busy_timeout=5000")
  83. conn.execute(
  84. """
  85. CREATE TABLE IF NOT EXISTS clusters (
  86. cluster_id TEXT PRIMARY KEY,
  87. topic TEXT NOT NULL,
  88. payload TEXT NOT NULL,
  89. updated_at TEXT NOT NULL,
  90. summary_payload TEXT,
  91. summary_updated_at TEXT
  92. )
  93. """
  94. )
  95. # If the table already exists without the summary columns,
  96. # add them (SQLite-friendly incremental migrations).
  97. for col_def in [
  98. "summary_payload TEXT",
  99. "summary_updated_at TEXT",
  100. ]:
  101. col = col_def.split()[0]
  102. try:
  103. conn.execute(f"ALTER TABLE clusters ADD COLUMN {col_def}")
  104. except sqlite3.OperationalError:
  105. pass
  106. conn.execute(
  107. "CREATE INDEX IF NOT EXISTS idx_clusters_topic ON clusters(topic)"
  108. )
  109. conn.execute(
  110. "CREATE INDEX IF NOT EXISTS idx_clusters_updated_at ON clusters(updated_at)"
  111. )
  112. conn.execute(
  113. """
  114. CREATE TABLE IF NOT EXISTS feed_state (
  115. feed_key TEXT PRIMARY KEY,
  116. last_hash TEXT NOT NULL,
  117. updated_at TEXT NOT NULL
  118. )
  119. """
  120. )
  121. conn.execute(
  122. """
  123. CREATE TABLE IF NOT EXISTS meta (
  124. key TEXT PRIMARY KEY,
  125. value TEXT NOT NULL
  126. )
  127. """
  128. )
  129. def upsert_clusters(self, clusters: list[dict], topic: str) -> None:
  130. now = datetime.now(timezone.utc)
  131. with self._conn() as conn:
  132. for c in clusters:
  133. c = sanitize_cluster_payload(c)
  134. cluster_id = c["cluster_id"]
  135. payload = json.dumps(c, ensure_ascii=False)
  136. conn.execute(
  137. "INSERT INTO clusters(cluster_id, topic, payload, updated_at) VALUES(?,?,?,?) "
  138. "ON CONFLICT(cluster_id) DO UPDATE SET topic=excluded.topic, payload=excluded.payload, updated_at=excluded.updated_at",
  139. (cluster_id, topic, payload, now.isoformat()),
  140. )
  141. def upsert_cluster_summary(
  142. self,
  143. cluster_id: str,
  144. summary_payload: dict,
  145. ) -> None:
  146. now = datetime.now(timezone.utc).isoformat()
  147. with self._conn() as conn:
  148. conn.execute(
  149. "INSERT INTO clusters(cluster_id, topic, payload, updated_at, summary_payload, summary_updated_at) "
  150. "VALUES(?,?,?,?,?,?) "
  151. "ON CONFLICT(cluster_id) DO UPDATE SET "
  152. "summary_payload=excluded.summary_payload, summary_updated_at=excluded.summary_updated_at",
  153. (
  154. cluster_id,
  155. "", # topic not used for update
  156. json.dumps({}, ensure_ascii=False),
  157. now,
  158. json.dumps(summary_payload, ensure_ascii=False),
  159. now,
  160. ),
  161. )
  162. def get_cluster_summary(self, cluster_id: str, ttl_hours: float) -> dict | None:
  163. cutoff = datetime.now(timezone.utc) - timedelta(hours=ttl_hours)
  164. cutoff_iso = cutoff.isoformat()
  165. with self._conn() as conn:
  166. cur = conn.execute(
  167. "SELECT summary_payload, summary_updated_at FROM clusters "
  168. "WHERE cluster_id=? AND summary_updated_at >= ?",
  169. (cluster_id, cutoff_iso),
  170. )
  171. row = cur.fetchone()
  172. if not row or not row[0]:
  173. return None
  174. return json.loads(row[0])
  175. def get_latest_clusters(self, topic: str, ttl_hours: float, limit: int) -> list[dict]:
  176. """Return newest clusters by *their own* timestamp.
  177. Filtering/sorting by the DB row's `updated_at` can drift away from the
  178. actual event time in `payload.timestamp`.
  179. """
  180. cutoff = datetime.now(timezone.utc) - timedelta(hours=float(ttl_hours))
  181. cutoff_ts = cutoff.timestamp()
  182. def _parse_payload_ts(ts: Any) -> float | None:
  183. if not ts:
  184. return None
  185. if isinstance(ts, (int, float)):
  186. return float(ts)
  187. text = str(ts).strip()
  188. try:
  189. dt = datetime.fromisoformat(text.replace('Z', '+00:00'))
  190. if dt.tzinfo is None:
  191. dt = dt.replace(tzinfo=timezone.utc)
  192. return dt.astimezone(timezone.utc).timestamp()
  193. except Exception:
  194. pass
  195. try:
  196. dt = parsedate_to_datetime(text)
  197. if dt.tzinfo is None:
  198. dt = dt.replace(tzinfo=timezone.utc)
  199. return dt.astimezone(timezone.utc).timestamp()
  200. except Exception:
  201. return None
  202. # Pull a wider candidate set, then filter by payload.timestamp.
  203. with self._conn() as conn:
  204. cur = conn.execute(
  205. "SELECT payload FROM clusters WHERE topic=? LIMIT ?",
  206. (topic, int(max(200, limit) * 10)),
  207. )
  208. candidates = [json.loads(r[0]) for r in cur.fetchall()]
  209. filtered: list[dict] = []
  210. for c in candidates:
  211. ts = _parse_payload_ts(c.get("timestamp"))
  212. if ts is None:
  213. continue
  214. if ts >= cutoff_ts:
  215. filtered.append(c)
  216. filtered.sort(key=lambda c: _parse_payload_ts(c.get("timestamp")) or 0.0, reverse=True)
  217. return filtered[: int(limit)]
  218. def get_latest_clusters_all_topics(self, ttl_hours: float, limit: int) -> list[dict]:
  219. cutoff = datetime.now(timezone.utc) - timedelta(hours=float(ttl_hours))
  220. cutoff_ts = cutoff.timestamp()
  221. def _parse_payload_ts(ts: Any) -> float | None:
  222. if not ts:
  223. return None
  224. if isinstance(ts, (int, float)):
  225. return float(ts)
  226. text = str(ts).strip()
  227. try:
  228. dt = datetime.fromisoformat(text.replace('Z', '+00:00'))
  229. if dt.tzinfo is None:
  230. dt = dt.replace(tzinfo=timezone.utc)
  231. return dt.astimezone(timezone.utc).timestamp()
  232. except Exception:
  233. pass
  234. try:
  235. dt = parsedate_to_datetime(text)
  236. if dt.tzinfo is None:
  237. dt = dt.replace(tzinfo=timezone.utc)
  238. return dt.astimezone(timezone.utc).timestamp()
  239. except Exception:
  240. return None
  241. with self._conn() as conn:
  242. cur = conn.execute(
  243. "SELECT payload FROM clusters LIMIT ?",
  244. (int(max(500, limit) * 10),),
  245. )
  246. candidates = [json.loads(r[0]) for r in cur.fetchall()]
  247. filtered: list[dict] = []
  248. for c in candidates:
  249. ts = _parse_payload_ts(c.get("timestamp"))
  250. if ts is None:
  251. continue
  252. if ts >= cutoff_ts:
  253. filtered.append(c)
  254. filtered.sort(key=lambda c: _parse_payload_ts(c.get("timestamp")) or 0.0, reverse=True)
  255. return filtered[: int(limit)]
  256. def get_cluster_by_id(self, cluster_id: str) -> dict | None:
  257. with self._conn() as conn:
  258. cur = conn.execute(
  259. "SELECT payload FROM clusters WHERE cluster_id=?",
  260. (cluster_id,),
  261. )
  262. row = cur.fetchone()
  263. return json.loads(row[0]) if row else None
  264. def get_feed_hash(self, feed_key: str) -> str | None:
  265. with self._conn() as conn:
  266. cur = conn.execute(
  267. "SELECT last_hash FROM feed_state WHERE feed_key=?",
  268. (feed_key,),
  269. )
  270. row = cur.fetchone()
  271. return row[0] if row else None
  272. def set_feed_hash(self, feed_key: str, last_hash: str) -> None:
  273. now = datetime.now(timezone.utc).isoformat()
  274. with self._conn() as conn:
  275. conn.execute(
  276. "INSERT INTO feed_state(feed_key, last_hash, updated_at) VALUES(?,?,?) "
  277. "ON CONFLICT(feed_key) DO UPDATE SET last_hash=excluded.last_hash, updated_at=excluded.updated_at",
  278. (feed_key, last_hash, now),
  279. )
  280. def get_feed_state(self, feed_key: str) -> dict | None:
  281. with self._conn() as conn:
  282. cur = conn.execute(
  283. "SELECT last_hash, updated_at FROM feed_state WHERE feed_key=?",
  284. (feed_key,),
  285. )
  286. row = cur.fetchone()
  287. if not row:
  288. return None
  289. return {"last_hash": row[0], "updated_at": row[1]}
  290. def get_meta(self, key: str) -> str | None:
  291. with self._conn() as conn:
  292. cur = conn.execute("SELECT value FROM meta WHERE key=?", (key,))
  293. row = cur.fetchone()
  294. return row[0] if row else None
  295. def set_meta(self, key: str, value: str) -> None:
  296. with self._conn() as conn:
  297. conn.execute(
  298. "INSERT INTO meta(key, value) VALUES(?, ?) "
  299. "ON CONFLICT(key) DO UPDATE SET value=excluded.value",
  300. (key, value),
  301. )
  302. def prune_clusters(self, retention_days: float) -> int:
  303. retention_days = float(retention_days)
  304. if retention_days <= 0:
  305. return 0
  306. cutoff = datetime.now(timezone.utc) - timedelta(days=retention_days)
  307. cutoff_iso = cutoff.isoformat()
  308. pruned_at = datetime.now(timezone.utc).isoformat()
  309. with self._conn() as conn:
  310. cur = conn.execute("DELETE FROM clusters WHERE updated_at < ?", (cutoff_iso,))
  311. deleted = int(cur.rowcount or 0)
  312. conn.execute(
  313. "INSERT INTO meta(key, value) VALUES(?, ?) "
  314. "ON CONFLICT(key) DO UPDATE SET value=excluded.value",
  315. (META_LAST_PRUNE_AT, pruned_at),
  316. )
  317. return deleted
  318. def prune_if_due(self, pruning_enabled: bool, retention_days: float, interval_hours: float = 24.0) -> dict[str, Any]:
  319. retention_days = float(retention_days)
  320. interval_hours = float(interval_hours)
  321. if (not pruning_enabled) or retention_days <= 0:
  322. return {
  323. "enabled": bool(pruning_enabled),
  324. "deleted": 0,
  325. "due": False,
  326. "retention_days": retention_days,
  327. "interval_hours": interval_hours,
  328. "last_prune_at": self.get_meta(META_LAST_PRUNE_AT),
  329. }
  330. last_prune_at = self.get_meta(META_LAST_PRUNE_AT)
  331. now = datetime.now(timezone.utc)
  332. due = True
  333. if last_prune_at:
  334. try:
  335. last_dt = datetime.fromisoformat(last_prune_at)
  336. due = now - last_dt >= timedelta(hours=max(1.0, interval_hours))
  337. except Exception:
  338. due = True
  339. if not due:
  340. return {
  341. "enabled": True,
  342. "deleted": 0,
  343. "due": False,
  344. "retention_days": retention_days,
  345. "interval_hours": interval_hours,
  346. "last_prune_at": last_prune_at,
  347. }
  348. deleted = self.prune_clusters(retention_days)
  349. last_prune_at = self.get_meta(META_LAST_PRUNE_AT)
  350. return {
  351. "enabled": True,
  352. "deleted": deleted,
  353. "due": True,
  354. "retention_days": retention_days,
  355. "interval_hours": interval_hours,
  356. "last_prune_at": last_prune_at,
  357. }
  358. def get_prune_state(self, pruning_enabled: bool, retention_days: float, interval_hours: float = 24.0) -> dict[str, Any]:
  359. return {
  360. "enabled": bool(pruning_enabled),
  361. "retention_days": float(retention_days),
  362. "interval_hours": float(interval_hours),
  363. "last_prune_at": self.get_meta(META_LAST_PRUNE_AT),
  364. }