"""Persistent, gap-sensitive health observations; no scheduler or signing key here.""" from datetime import datetime, timedelta, timezone import sqlite3 from .release_operations import revision class HealthObserver: def __init__(self, database, *, max_gap_seconds=90): if not 1 <= max_gap_seconds <= 90: raise ValueError('health gap must be at most 90 seconds') self.database, self.max_gap = database, timedelta(seconds=max_gap_seconds) with self.connect() as db: db.execute('CREATE TABLE IF NOT EXISTS observations (at TEXT PRIMARY KEY, revision TEXT NOT NULL, healthy INTEGER NOT NULL, since TEXT)') db.execute('CREATE TABLE IF NOT EXISTS observer_guard (singleton INTEGER PRIMARY KEY, invalidated INTEGER NOT NULL)') db.execute('INSERT OR IGNORE INTO observer_guard VALUES (1,0)') def connect(self): db=sqlite3.connect(self.database,timeout=5,isolation_level=None) db.execute('PRAGMA synchronous=FULL') return db def observe(self, commit, healthy, now=None): """Called by a trusted sampler after exact-revision readiness/invariant checks. Failed/unavailable probes must be recorded False. A missed sample, clock regression or revision change resets the interval; no timestamp backfill. """ revision(commit) if type(healthy) is not bool:raise ValueError('explicit boolean health required') now=now or datetime.now(timezone.utc) if now.tzinfo is None:raise ValueError('timezone required') db=self.connect() try: db.execute('BEGIN IMMEDIATE') prior=db.execute('SELECT at,revision,healthy,since FROM observations ORDER BY rowid DESC LIMIT 1').fetchone() invalidated=db.execute('SELECT invalidated FROM observer_guard WHERE singleton=1').fetchone()[0] since=now.isoformat() if healthy else None if prior: last=datetime.fromisoformat(prior[0]) if now<=last: db.execute('UPDATE observer_guard SET invalidated=1 WHERE singleton=1') db.commit() raise ValueError('non-increasing observation time') if not invalidated and healthy and prior[2] and prior[1]==commit and now-last<=self.max_gap: since=prior[3] db.execute('INSERT INTO observations VALUES (?,?,?,?)',(now.isoformat(),commit,int(healthy),since)) db.execute('UPDATE observer_guard SET invalidated=0 WHERE singleton=1') db.commit() return since except Exception: db.rollback();raise finally:db.close() def attestation(self, commit, now=None): """Return facts for a trusted health issuer, never fabricate a signature.""" revision(commit);now=now or datetime.now(timezone.utc) db=self.connect() try: row=db.execute('SELECT at,revision,healthy,since FROM observations ORDER BY rowid DESC LIMIT 1').fetchone() if db.execute('SELECT invalidated FROM observer_guard WHERE singleton=1').fetchone()[0]: raise ValueError('observation interval invalidated by clock regression') finally:db.close() if not row or row[1]!=commit or not row[2] or not row[3]:raise ValueError('no healthy revision interval') measured=datetime.fromisoformat(row[0]);since=datetime.fromisoformat(row[3]) if not timedelta(0)<=now-measured<=self.max_gap:raise ValueError('health observations stale or clock regressed') if measured-since