Coverage for notifications/postgres_telegram.py: 100%
35 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""PostgreSQL I/O layer for Telegram alerting (V2-19).
3Mirrors performance/postgres_triggers.py's design: embedded DDL (no
4Alembic, no migration files), ensure_schema() idempotent at startup. This
5module does NOT reimplement trigger fetching — notifications/telegram_worker.py
6imports fetch_triggers_since() directly from performance.postgres_triggers,
7since that table is already the durable system of record for triggers.
8This module only owns: the watermark table shared by both alert channels,
9and a defensive read of experience_events (owned by
10experience/postgres_worker.py) for session_summary events.
11"""
13from __future__ import annotations
15import json
16import logging
17from datetime import datetime, timezone
19logger = logging.getLogger(__name__)
21# ---------------------------------------------------------------------------
22# Schema DDL — embedded constant, no migration files
23# ---------------------------------------------------------------------------
25_CREATE_WATERMARK_TABLE_SQL = """
26CREATE TABLE IF NOT EXISTS telegram_alert_watermark (
27 channel VARCHAR(30) PRIMARY KEY,
28 last_created_at TIMESTAMPTZ
29);
30"""
33def ensure_schema(conn) -> None:
34 """Create telegram_alert_watermark if missing. Idempotent."""
35 with conn.cursor() as cur:
36 cur.execute(_CREATE_WATERMARK_TABLE_SQL)
37 conn.commit()
38 logger.info("ensure_schema: telegram_alert_watermark ready.")
41# ---------------------------------------------------------------------------
42# Watermark bookkeeping — one row per channel ("triggers", "session_summary")
43# ---------------------------------------------------------------------------
46def get_watermark(conn, channel: str) -> datetime | None:
47 with conn.cursor() as cur:
48 cur.execute(
49 "SELECT last_created_at FROM telegram_alert_watermark WHERE channel = %(channel)s;",
50 {"channel": channel},
51 )
52 row = cur.fetchone()
53 return row[0] if row else None
56def set_watermark(conn, channel: str, last_created_at) -> None:
57 with conn.cursor() as cur:
58 cur.execute(
59 "INSERT INTO telegram_alert_watermark (channel, last_created_at) VALUES (%(channel)s, %(ts)s) "
60 "ON CONFLICT (channel) DO UPDATE SET last_created_at = EXCLUDED.last_created_at;",
61 {"channel": channel, "ts": last_created_at},
62 )
63 conn.commit()
66# ---------------------------------------------------------------------------
67# Reading experience_events (owned by experience/postgres_worker.py)
68# ---------------------------------------------------------------------------
71def fetch_session_summaries_since(conn, since: datetime | None, limit: int = 500) -> list[dict]:
72 """Fetch session_summary experience events newer than `since`, oldest first.
74 Never raises — experience_events may be unavailable in a
75 telegram-worker-only deployment (experience/postgres_worker.py owns that
76 table's schema, not this module), mirroring
77 performance/postgres_triggers.py::fetch_last_retraining_at()'s
78 defensiveness for cross-package reads.
79 """
80 if since is None:
81 since = datetime.fromtimestamp(0, tz=timezone.utc)
83 try:
84 with conn.cursor() as cur:
85 cur.execute(
86 "SELECT payload FROM experience_events "
87 "WHERE payload->>'event_type' = 'session_summary' AND created_at > %(since)s "
88 "ORDER BY created_at ASC LIMIT %(limit)s;",
89 {"since": since, "limit": limit},
90 )
91 rows = cur.fetchall()
92 return [json.loads(row[0]) if isinstance(row[0], str) else row[0] for row in rows]
93 except Exception:
94 logger.debug("fetch_session_summaries_since: experience_events unavailable, returning [].")
95 try:
96 conn.rollback()
97 except Exception:
98 pass
99 return []