Coverage for performance/postgres_triggers.py: 100%
99 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 performance triggers (V2-16).
3Mirrors experience/postgres_worker.py's design: embedded DDL (no Alembic,
4no migration files), ensure_schema() idempotent at startup, ON CONFLICT DO
5NOTHING for safe idempotent re-delivery. Separate from performance/triggers.py
6so the pure evaluation logic stays importable with zero DB dependency.
7"""
9from __future__ import annotations
11import json
12import logging
13from datetime import datetime, timezone
14from typing import Any
16logger = logging.getLogger(__name__)
18# ---------------------------------------------------------------------------
19# Schema DDL — embedded constants, no migration files
20# ---------------------------------------------------------------------------
22_CREATE_TRIGGERS_TABLE_SQL = """
23CREATE TABLE IF NOT EXISTS performance_triggers (
24 id BIGSERIAL PRIMARY KEY,
25 trigger_id UUID UNIQUE NOT NULL,
26 created_at TIMESTAMPTZ NOT NULL,
27 ingested_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
28 trigger_type VARCHAR(40) NOT NULL,
29 severity VARCHAR(10) NOT NULL,
30 mode VARCHAR(20) NOT NULL,
31 scope VARCHAR(100) NOT NULL,
32 metric_value DOUBLE PRECISION,
33 threshold DOUBLE PRECISION,
34 message TEXT NOT NULL,
35 recommended_action VARCHAR(40) NOT NULL,
36 retrain_candidate BOOLEAN NOT NULL DEFAULT FALSE,
37 details JSONB NOT NULL DEFAULT '{}'::jsonb
38);
39"""
41_CREATE_TRIGGERS_INDEXES_SQL = [
42 "CREATE INDEX IF NOT EXISTS ix_trig_created_at ON performance_triggers (created_at);",
43 "CREATE INDEX IF NOT EXISTS ix_trig_type ON performance_triggers (trigger_type);",
44 "CREATE INDEX IF NOT EXISTS ix_trig_severity ON performance_triggers (severity);",
45 "CREATE INDEX IF NOT EXISTS ix_trig_retrain_candidate ON performance_triggers (retrain_candidate);",
46 "CREATE INDEX IF NOT EXISTS ix_trig_scope ON performance_triggers (scope);",
47 "CREATE INDEX IF NOT EXISTS ix_trig_details ON performance_triggers USING GIN (details);",
48]
50_CREATE_WATERMARK_TABLE_SQL = """
51CREATE TABLE IF NOT EXISTS performance_trigger_watermark (
52 id INT PRIMARY KEY DEFAULT 1,
53 last_created_at TIMESTAMPTZ
54);
55"""
57_INSERT_TRIGGER_SQL = """
58INSERT INTO performance_triggers
59 (trigger_id, created_at, trigger_type, severity, mode, scope,
60 metric_value, threshold, message, recommended_action, retrain_candidate, details)
61VALUES
62 (%(trigger_id)s, %(created_at)s, %(trigger_type)s, %(severity)s, %(mode)s, %(scope)s,
63 %(metric_value)s, %(threshold)s, %(message)s, %(recommended_action)s,
64 %(retrain_candidate)s, %(details)s)
65ON CONFLICT (trigger_id) DO NOTHING;
66"""
68_SUPPRESSION_CHECK_SQL = """
69SELECT 1 FROM performance_triggers
70WHERE trigger_type = %(trigger_type)s AND scope = %(scope)s
71 AND created_at > NOW() - (%(suppression_minutes)s || ' minutes')::interval
72LIMIT 1;
73"""
75# ---------------------------------------------------------------------------
76# Pure transformation — testable without any I/O
77# ---------------------------------------------------------------------------
80def trigger_to_row(trigger: dict) -> dict[str, Any]:
81 """Extract scalar columns + serialised trigger dict for _INSERT_TRIGGER_SQL."""
82 return {
83 "trigger_id": trigger["trigger_id"],
84 "created_at": trigger["created_at"],
85 "trigger_type": trigger["trigger_type"],
86 "severity": trigger["severity"],
87 "mode": trigger["mode"],
88 "scope": trigger["scope"],
89 "metric_value": trigger.get("metric_value"),
90 "threshold": trigger.get("threshold"),
91 "message": trigger["message"],
92 "recommended_action": trigger["recommended_action"],
93 "retrain_candidate": trigger["retrain_candidate"],
94 "details": json.dumps(trigger),
95 }
98# ---------------------------------------------------------------------------
99# Schema helper
100# ---------------------------------------------------------------------------
103def ensure_schema(conn) -> None:
104 """Create performance_triggers/watermark tables and indexes if missing.
106 Idempotent — safe to call on every worker startup.
107 """
108 with conn.cursor() as cur:
109 cur.execute(_CREATE_TRIGGERS_TABLE_SQL)
110 for idx_sql in _CREATE_TRIGGERS_INDEXES_SQL:
111 cur.execute(idx_sql)
112 cur.execute(_CREATE_WATERMARK_TABLE_SQL)
113 conn.commit()
114 logger.info("ensure_schema: performance_triggers ready.")
117# ---------------------------------------------------------------------------
118# Reading experience_events
119# ---------------------------------------------------------------------------
122def fetch_events_since(conn, since: datetime | None, limit: int = 10_000) -> list[dict]:
123 """Fetch experience_events payloads newer than `since`, oldest first.
125 `since=None` pulls from the epoch (first-ever run). psycopg3 decodes
126 JSONB columns to plain Python dicts by default; the json.loads fallback
127 guards against a str being returned by an older/differently-configured
128 driver.
129 """
130 if since is None:
131 since = datetime.fromtimestamp(0, tz=timezone.utc)
133 with conn.cursor() as cur:
134 cur.execute(
135 "SELECT payload FROM experience_events WHERE created_at > %(since)s "
136 "ORDER BY created_at ASC LIMIT %(limit)s;",
137 {"since": since, "limit": limit},
138 )
139 rows = cur.fetchall()
141 return [json.loads(row[0]) if isinstance(row[0], str) else row[0] for row in rows]
144def fetch_recent_events(conn, limit: int = 500, since: datetime | None = None) -> list[dict]:
145 """Fetch the most recent experience_events payloads, oldest first.
147 Added for V2-17.5 — distinct from fetch_events_since(), which returns
148 everything newer than a *watermark* (an incremental "what's new since I
149 last looked" cursor unbounded in count). This is a true rolling-window
150 read: newest `limit` rows (optionally also bounded by `since`), so
151 trigger evaluation can run over "last N observations" / "last 30 days"
152 instead of only whatever arrived since the last poll.
153 """
154 with conn.cursor() as cur:
155 if since is None:
156 cur.execute(
157 "SELECT payload FROM experience_events ORDER BY created_at DESC LIMIT %(limit)s;",
158 {"limit": limit},
159 )
160 else:
161 cur.execute(
162 "SELECT payload FROM experience_events WHERE created_at > %(since)s "
163 "ORDER BY created_at DESC LIMIT %(limit)s;",
164 {"since": since, "limit": limit},
165 )
166 rows = cur.fetchall()
168 payloads = [json.loads(row[0]) if isinstance(row[0], str) else row[0] for row in rows]
169 payloads.reverse()
170 return payloads
173def fetch_triggers_since(conn, since: datetime, limit: int = 10_000) -> list[dict]:
174 """Fetch trigger rows newer than `since`, oldest first — feeds
175 trigger_frequency_spike()'s baseline-rate calculation."""
176 with conn.cursor() as cur:
177 cur.execute(
178 "SELECT trigger_id, created_at, trigger_type, severity, mode, scope, "
179 "metric_value, threshold, message, recommended_action, retrain_candidate "
180 "FROM performance_triggers WHERE created_at > %(since)s ORDER BY created_at ASC LIMIT %(limit)s;",
181 {"since": since, "limit": limit},
182 )
183 rows = cur.fetchall()
185 columns = (
186 "trigger_id",
187 "created_at",
188 "trigger_type",
189 "severity",
190 "mode",
191 "scope",
192 "metric_value",
193 "threshold",
194 "message",
195 "recommended_action",
196 "retrain_candidate",
197 )
198 return [dict(zip(columns, row, strict=False)) for row in rows]
201def fetch_last_retraining_at(conn) -> datetime | None:
202 """Best-effort lookup of the most recent promoted/validated retraining
203 event, used to widen the trigger-evaluation window back to "since last
204 retrain" when that's more recent than the default lookback. Never
205 raises — retraining_events may not exist yet in a trigger-worker-only
206 deployment (retraining/postgres_registry.py owns that table's schema,
207 not this module), so any failure here just means "no known retrain"."""
208 try:
209 with conn.cursor() as cur:
210 cur.execute("SELECT MAX(created_at) FROM retraining_events WHERE status IN ('promoted', 'validated');")
211 row = cur.fetchone()
212 return row[0] if row else None
213 except Exception:
214 logger.debug("fetch_last_retraining_at: retraining_events unavailable, treating as no prior retrain.")
215 try:
216 conn.rollback()
217 except Exception:
218 pass
219 return None
222# ---------------------------------------------------------------------------
223# Watermark bookkeeping
224# ---------------------------------------------------------------------------
227def get_watermark(conn) -> datetime | None:
228 with conn.cursor() as cur:
229 cur.execute("SELECT last_created_at FROM performance_trigger_watermark WHERE id = 1;")
230 row = cur.fetchone()
231 return row[0] if row else None
234def set_watermark(conn, last_created_at: datetime) -> None:
235 with conn.cursor() as cur:
236 cur.execute(
237 "INSERT INTO performance_trigger_watermark (id, last_created_at) VALUES (1, %(ts)s) "
238 "ON CONFLICT (id) DO UPDATE SET last_created_at = EXCLUDED.last_created_at;",
239 {"ts": last_created_at},
240 )
241 conn.commit()
244# ---------------------------------------------------------------------------
245# Writing trigger dicts — suppression-window dedup + insert
246# ---------------------------------------------------------------------------
249def _is_suppressed(conn, trigger: dict, suppression_minutes: int) -> bool:
250 with conn.cursor() as cur:
251 cur.execute(
252 _SUPPRESSION_CHECK_SQL,
253 {
254 "trigger_type": trigger["trigger_type"],
255 "scope": trigger["scope"],
256 "suppression_minutes": suppression_minutes,
257 },
258 )
259 return cur.fetchone() is not None
262def insert_triggers(conn, triggers: list[dict], suppression_minutes: int = 60) -> int:
263 """Insert new trigger rows, skipping any within an active suppression window.
265 Row-by-row (not executemany) since each insert needs its own suppression
266 check — trigger volume per poll cycle is small enough that this is fine,
267 unlike experience_events' high-volume batch insert.
268 """
269 inserted = 0
270 for trigger in triggers:
271 if _is_suppressed(conn, trigger, suppression_minutes):
272 continue
273 with conn.cursor() as cur:
274 cur.execute(_INSERT_TRIGGER_SQL, trigger_to_row(trigger))
275 conn.commit()
276 inserted += 1
277 return inserted
280def fetch_candidate_triggers(conn, limit: int = 50) -> list[dict]:
281 """Fetch the newest retrain_candidate=true triggers, newest first.
283 Added for V2-17 (retraining/planning.py) — Phase 16 only ever wrote this
284 flag, it never read it back. Reuses the same connection/table this module
285 already owns rather than duplicating a query in retraining/.
286 """
287 with conn.cursor() as cur:
288 cur.execute(
289 "SELECT trigger_id, created_at, trigger_type, severity, mode, scope, "
290 "metric_value, threshold, message, recommended_action, retrain_candidate, details "
291 "FROM performance_triggers WHERE retrain_candidate = TRUE "
292 "ORDER BY created_at DESC LIMIT %(limit)s;",
293 {"limit": limit},
294 )
295 rows = cur.fetchall()
297 columns = (
298 "trigger_id",
299 "created_at",
300 "trigger_type",
301 "severity",
302 "mode",
303 "scope",
304 "metric_value",
305 "threshold",
306 "message",
307 "recommended_action",
308 "retrain_candidate",
309 "details",
310 )
311 results = []
312 for row in rows:
313 record = dict(zip(columns, row, strict=False))
314 details = record.pop("details")
315 record["details"] = json.loads(details) if isinstance(details, str) else (details or {})
316 results.append(record)
317 return results
320def fetch_latest_trigger(conn) -> dict | None:
321 with conn.cursor() as cur:
322 cur.execute(
323 "SELECT trigger_id, created_at, trigger_type, severity, mode, scope, "
324 "metric_value, threshold, message, recommended_action, retrain_candidate "
325 "FROM performance_triggers ORDER BY created_at DESC LIMIT 1;"
326 )
327 row = cur.fetchone()
329 if row is None:
330 return None
332 columns = (
333 "trigger_id",
334 "created_at",
335 "trigger_type",
336 "severity",
337 "mode",
338 "scope",
339 "metric_value",
340 "threshold",
341 "message",
342 "recommended_action",
343 "retrain_candidate",
344 )
345 return dict(zip(columns, row, strict=False))