Coverage for retraining/postgres_registry.py: 100%
128 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 the retraining job registry and model version
2registry (V2-17).
4Mirrors performance/postgres_triggers.py's design: embedded DDL (no Alembic,
5no migration files), ensure_schema() idempotent at startup, ON CONFLICT DO
6NOTHING for safe idempotent re-delivery. Both tables live in one file because
7every retraining_events row references a model_versions row and the two are
8always read/written together by the orchestrator/worker.
10Row-shaping helpers (*_to_row) and fetch helpers stay pure/thin — no
11business logic here. UUIDs (retraining_id, model_version_id) are generated
12by the caller (retraining/worker.py, retraining/orchestrator.py), not this
13module, matching performance/triggers.py's trigger_id convention.
14"""
16from __future__ import annotations
18import json
19import logging
20from datetime import datetime, timezone
21from typing import Any
23logger = logging.getLogger(__name__)
25# ---------------------------------------------------------------------------
26# Schema DDL — embedded constants, no migration files
27# ---------------------------------------------------------------------------
29_CREATE_MODEL_VERSIONS_TABLE_SQL = """
30CREATE TABLE IF NOT EXISTS model_versions (
31 id BIGSERIAL PRIMARY KEY,
32 model_version_id UUID UNIQUE NOT NULL,
33 status VARCHAR(20) NOT NULL DEFAULT 'candidate',
34 created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
35 updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
36 git_commit VARCHAR(64),
37 aether_vault_commit VARCHAR(64),
38 artifact_paths JSONB NOT NULL DEFAULT '{}'::jsonb,
39 artifact_hashes JSONB NOT NULL DEFAULT '{}'::jsonb,
40 training_window JSONB NOT NULL DEFAULT '{}'::jsonb,
41 validation_window JSONB NOT NULL DEFAULT '{}'::jsonb,
42 backtest_window JSONB NOT NULL DEFAULT '{}'::jsonb,
43 metrics JSONB NOT NULL DEFAULT '{}'::jsonb
44);
45"""
47_CREATE_MODEL_VERSIONS_INDEXES_SQL = [
48 "CREATE INDEX IF NOT EXISTS ix_model_versions_status ON model_versions (status);",
49 "CREATE INDEX IF NOT EXISTS ix_model_versions_created_at ON model_versions (created_at);",
50 "CREATE INDEX IF NOT EXISTS ix_model_versions_metrics ON model_versions USING GIN (metrics);",
51 # Enforces "exactly one active model" at the DB level.
52 "CREATE UNIQUE INDEX IF NOT EXISTS ux_model_versions_single_active "
53 "ON model_versions ((status)) WHERE status = 'active';",
54]
56_CREATE_RETRAINING_EVENTS_TABLE_SQL = """
57CREATE TABLE IF NOT EXISTS retraining_events (
58 id BIGSERIAL PRIMARY KEY,
59 retraining_id UUID UNIQUE NOT NULL,
60 source_trigger_id UUID,
61 candidate_version_id UUID,
62 created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
63 updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
64 status VARCHAR(20) NOT NULL DEFAULT 'planned',
65 reason TEXT NOT NULL,
66 metrics JSONB NOT NULL DEFAULT '{}'::jsonb,
67 notes JSONB NOT NULL DEFAULT '[]'::jsonb
68);
69"""
71_CREATE_RETRAINING_EVENTS_INDEXES_SQL = [
72 "CREATE INDEX IF NOT EXISTS ix_retraining_events_status ON retraining_events (status);",
73 "CREATE INDEX IF NOT EXISTS ix_retraining_events_created_at ON retraining_events (created_at);",
74 "CREATE INDEX IF NOT EXISTS ix_retraining_events_candidate_ver ON retraining_events (candidate_version_id);",
75 "CREATE INDEX IF NOT EXISTS ix_retraining_events_metrics ON retraining_events USING GIN (metrics);",
76]
78_INSERT_MODEL_VERSION_SQL = """
79INSERT INTO model_versions
80 (model_version_id, status, git_commit, aether_vault_commit, artifact_paths,
81 artifact_hashes, training_window, validation_window, backtest_window, metrics)
82VALUES
83 (%(model_version_id)s, %(status)s, %(git_commit)s, %(aether_vault_commit)s, %(artifact_paths)s,
84 %(artifact_hashes)s, %(training_window)s, %(validation_window)s, %(backtest_window)s, %(metrics)s)
85ON CONFLICT (model_version_id) DO NOTHING;
86"""
88_INSERT_RETRAINING_EVENT_SQL = """
89INSERT INTO retraining_events
90 (retraining_id, source_trigger_id, candidate_version_id, status, reason, metrics, notes)
91VALUES
92 (%(retraining_id)s, %(source_trigger_id)s, %(candidate_version_id)s, %(status)s,
93 %(reason)s, %(metrics)s, %(notes)s)
94ON CONFLICT (retraining_id) DO NOTHING;
95"""
97_MODEL_VERSION_COLUMNS = (
98 "model_version_id",
99 "status",
100 "created_at",
101 "updated_at",
102 "git_commit",
103 "aether_vault_commit",
104 "artifact_paths",
105 "artifact_hashes",
106 "training_window",
107 "validation_window",
108 "backtest_window",
109 "metrics",
110)
112_RETRAINING_EVENT_COLUMNS = (
113 "retraining_id",
114 "source_trigger_id",
115 "candidate_version_id",
116 "created_at",
117 "updated_at",
118 "status",
119 "reason",
120 "metrics",
121 "notes",
122)
125def _jsonb(value: Any) -> str:
126 return json.dumps(value if value is not None else {})
129def _row_to_dict(row: tuple, columns: tuple[str, ...]) -> dict:
130 return dict(zip(columns, row, strict=False))
133def model_version_to_row(version: dict) -> dict[str, Any]:
134 """Extract INSERT params for _INSERT_MODEL_VERSION_SQL from a version dict."""
135 return {
136 "model_version_id": version["model_version_id"],
137 "status": version.get("status", "candidate"),
138 "git_commit": version.get("git_commit"),
139 "aether_vault_commit": version.get("aether_vault_commit"),
140 "artifact_paths": _jsonb(version.get("artifact_paths")),
141 "artifact_hashes": _jsonb(version.get("artifact_hashes")),
142 "training_window": _jsonb(version.get("training_window")),
143 "validation_window": _jsonb(version.get("validation_window")),
144 "backtest_window": _jsonb(version.get("backtest_window")),
145 "metrics": _jsonb(version.get("metrics")),
146 }
149def retraining_event_to_row(event: dict) -> dict[str, Any]:
150 """Extract INSERT params for _INSERT_RETRAINING_EVENT_SQL from an event dict."""
151 return {
152 "retraining_id": event["retraining_id"],
153 "source_trigger_id": event.get("source_trigger_id"),
154 "candidate_version_id": event.get("candidate_version_id"),
155 "status": event.get("status", "planned"),
156 "reason": event["reason"],
157 "metrics": _jsonb(event.get("metrics")),
158 "notes": json.dumps(event.get("notes") or []),
159 }
162# ---------------------------------------------------------------------------
163# Schema helper
164# ---------------------------------------------------------------------------
167def ensure_schema(conn) -> None:
168 """Create model_versions/retraining_events tables and indexes if missing.
170 Idempotent — safe to call on every worker/orchestrator startup.
171 """
172 with conn.cursor() as cur:
173 cur.execute(_CREATE_MODEL_VERSIONS_TABLE_SQL)
174 for idx_sql in _CREATE_MODEL_VERSIONS_INDEXES_SQL:
175 cur.execute(idx_sql)
176 cur.execute(_CREATE_RETRAINING_EVENTS_TABLE_SQL)
177 for idx_sql in _CREATE_RETRAINING_EVENTS_INDEXES_SQL:
178 cur.execute(idx_sql)
179 conn.commit()
180 logger.info("ensure_schema: model_versions/retraining_events ready.")
183def count_experience_events(conn) -> int:
184 """Total experience_events row count - feeds planning.min_observations_satisfied().
186 A plain COUNT(*), not a since-watermark query: "minimum observations
187 before retraining starts" is meant as a lifetime floor (enough history
188 ever exists to trust a retrain), not a since-last-retrain count.
189 """
190 with conn.cursor() as cur:
191 cur.execute("SELECT COUNT(*) FROM experience_events;")
192 row = cur.fetchone()
193 return int(row[0]) if row else 0
196# ---------------------------------------------------------------------------
197# model_versions
198# ---------------------------------------------------------------------------
201def insert_model_version(conn, version: dict) -> None:
202 with conn.cursor() as cur:
203 cur.execute(_INSERT_MODEL_VERSION_SQL, model_version_to_row(version))
204 conn.commit()
207def update_model_version_status(conn, model_version_id: str, status: str, **fields: Any) -> None:
208 """Update status plus any of git_commit/aether_vault_commit/artifact_paths/
209 artifact_hashes/training_window/validation_window/backtest_window/metrics."""
210 assignments = ["status = %(status)s", "updated_at = NOW()"]
211 params: dict[str, Any] = {"model_version_id": model_version_id, "status": status}
213 jsonb_fields = (
214 "artifact_paths",
215 "artifact_hashes",
216 "training_window",
217 "validation_window",
218 "backtest_window",
219 "metrics",
220 )
221 scalar_fields = ("git_commit", "aether_vault_commit")
223 for key, value in fields.items():
224 if key in jsonb_fields:
225 assignments.append(f"{key} = %({key})s")
226 params[key] = _jsonb(value)
227 elif key in scalar_fields:
228 assignments.append(f"{key} = %({key})s")
229 params[key] = value
231 sql = f"UPDATE model_versions SET {', '.join(assignments)} WHERE model_version_id = %(model_version_id)s;"
232 with conn.cursor() as cur:
233 cur.execute(sql, params)
234 conn.commit()
237def fetch_model_version(conn, model_version_id: str) -> dict | None:
238 with conn.cursor() as cur:
239 cur.execute(
240 f"SELECT {', '.join(_MODEL_VERSION_COLUMNS)} FROM model_versions "
241 "WHERE model_version_id = %(model_version_id)s;",
242 {"model_version_id": model_version_id},
243 )
244 row = cur.fetchone()
245 return _row_to_dict(row, _MODEL_VERSION_COLUMNS) if row else None
248def fetch_active_model_version(conn) -> dict | None:
249 with conn.cursor() as cur:
250 cur.execute(
251 f"SELECT {', '.join(_MODEL_VERSION_COLUMNS)} FROM model_versions "
252 "WHERE status = 'active' ORDER BY updated_at DESC LIMIT 1;"
253 )
254 row = cur.fetchone()
255 return _row_to_dict(row, _MODEL_VERSION_COLUMNS) if row else None
258def fetch_latest_candidate_version(conn) -> dict | None:
259 with conn.cursor() as cur:
260 cur.execute(
261 f"SELECT {', '.join(_MODEL_VERSION_COLUMNS)} FROM model_versions "
262 "WHERE status = 'candidate' ORDER BY created_at DESC LIMIT 1;"
263 )
264 row = cur.fetchone()
265 return _row_to_dict(row, _MODEL_VERSION_COLUMNS) if row else None
268def fetch_rollback_candidates(conn, limit: int = 20) -> list[dict]:
269 """Archived/rolled_back versions, newest first — restorable via rollback()."""
270 with conn.cursor() as cur:
271 cur.execute(
272 f"SELECT {', '.join(_MODEL_VERSION_COLUMNS)} FROM model_versions "
273 "WHERE status IN ('archived', 'rolled_back') ORDER BY updated_at DESC LIMIT %(limit)s;",
274 {"limit": limit},
275 )
276 rows = cur.fetchall()
277 return [_row_to_dict(row, _MODEL_VERSION_COLUMNS) for row in rows]
280def promote_model_version(conn, old_active_id: str | None, new_active_id: str) -> None:
281 """Single transaction: old_active_id -> archived, new_active_id -> active.
283 Relies on ux_model_versions_single_active to fail loudly on races (two
284 concurrent promotions would violate the unique index and raise).
285 """
286 with conn.cursor() as cur:
287 if old_active_id:
288 cur.execute(
289 "UPDATE model_versions SET status = 'archived', updated_at = NOW() "
290 "WHERE model_version_id = %(id)s;",
291 {"id": old_active_id},
292 )
293 cur.execute(
294 "UPDATE model_versions SET status = 'active', updated_at = NOW() "
295 "WHERE model_version_id = %(id)s;",
296 {"id": new_active_id},
297 )
298 conn.commit()
301# ---------------------------------------------------------------------------
302# retraining_events
303# ---------------------------------------------------------------------------
306def insert_retraining_event(conn, event: dict) -> None:
307 with conn.cursor() as cur:
308 cur.execute(_INSERT_RETRAINING_EVENT_SQL, retraining_event_to_row(event))
309 conn.commit()
312def update_retraining_event_status(conn, retraining_id: str, status: str, **fields: Any) -> None:
313 """Update status plus any of candidate_version_id/reason/metrics/notes."""
314 assignments = ["status = %(status)s", "updated_at = NOW()"]
315 params: dict[str, Any] = {"retraining_id": retraining_id, "status": status}
317 if "candidate_version_id" in fields:
318 assignments.append("candidate_version_id = %(candidate_version_id)s")
319 params["candidate_version_id"] = fields["candidate_version_id"]
320 if "reason" in fields:
321 assignments.append("reason = %(reason)s")
322 params["reason"] = fields["reason"]
323 if "metrics" in fields:
324 assignments.append("metrics = %(metrics)s")
325 params["metrics"] = _jsonb(fields["metrics"])
326 if "notes" in fields:
327 assignments.append("notes = %(notes)s")
328 params["notes"] = json.dumps(fields["notes"] or [])
330 sql = f"UPDATE retraining_events SET {', '.join(assignments)} WHERE retraining_id = %(retraining_id)s;"
331 with conn.cursor() as cur:
332 cur.execute(sql, params)
333 conn.commit()
336def fetch_retraining_event(conn, retraining_id: str) -> dict | None:
337 with conn.cursor() as cur:
338 cur.execute(
339 f"SELECT {', '.join(_RETRAINING_EVENT_COLUMNS)} FROM retraining_events "
340 "WHERE retraining_id = %(retraining_id)s;",
341 {"retraining_id": retraining_id},
342 )
343 row = cur.fetchone()
344 return _row_to_dict(row, _RETRAINING_EVENT_COLUMNS) if row else None
347def fetch_recent_retraining_events(conn, since: datetime | None, limit: int = 100) -> list[dict]:
348 if since is None:
349 since = datetime.fromtimestamp(0, tz=timezone.utc)
350 with conn.cursor() as cur:
351 cur.execute(
352 f"SELECT {', '.join(_RETRAINING_EVENT_COLUMNS)} FROM retraining_events "
353 "WHERE created_at > %(since)s ORDER BY created_at DESC LIMIT %(limit)s;",
354 {"since": since, "limit": limit},
355 )
356 rows = cur.fetchall()
357 return [_row_to_dict(row, _RETRAINING_EVENT_COLUMNS) for row in rows]
360def fetch_latest_retraining_event(conn) -> dict | None:
361 with conn.cursor() as cur:
362 cur.execute(
363 f"SELECT {', '.join(_RETRAINING_EVENT_COLUMNS)} FROM retraining_events "
364 "ORDER BY created_at DESC LIMIT 1;"
365 )
366 row = cur.fetchone()
367 return _row_to_dict(row, _RETRAINING_EVENT_COLUMNS) if row else None
370def fetch_stale_active_events(conn, older_than_seconds: float) -> list[dict]:
371 """Rows stuck in 'planned'/'running' whose updated_at is older than the
372 given staleness window - feeds reconcile_stale_running_events() (see
373 retraining/orchestrator.py). A worker that crashed/was recreated mid-cycle
374 leaves its retraining_events row frozen at 'running' forever (nothing
375 else ever updates it again) - see development/Problems.md #48."""
376 with conn.cursor() as cur:
377 cur.execute(
378 f"SELECT {', '.join(_RETRAINING_EVENT_COLUMNS)} FROM retraining_events "
379 "WHERE status IN ('planned', 'running') "
380 "AND updated_at < NOW() - make_interval(secs => %(older_than_seconds)s) "
381 "ORDER BY created_at ASC;",
382 {"older_than_seconds": older_than_seconds},
383 )
384 rows = cur.fetchall()
385 return [_row_to_dict(row, _RETRAINING_EVENT_COLUMNS) for row in rows]