"""Model uptime history: stores real probe results, never probes by itself. Stdlib-only SQLite store fed by the existing ``_ms_loop`` probe results in ``webapp/server.py`` (``_MS["data"]`` dict ``model -> probe``). Probe schema: ``{"up": 1|0|None, "status": "up"|"down"|"busy"|"unknown", "ms": int?, "http_status": int?, "checked_at": int}``. Semantics: * only terminal ``up``/``down`` observations count towards uptime; * ``busy`` (429/5xx after retry) is *degraded*, not down; * ``unknown`` (timeouts, empty answers) and missing hours are ``no_data``; * nothing before the first real observation is invented (``observed_since``). """ from __future__ import annotations import sqlite3 import math import time from typing import Any, Iterable, Mapping RETENTION_DAYS = 30 WINDOW_HOURS = 24 BUCKET_SECONDS = 3600 MAX_ROWS = 200_000 # hard storage bound on top of retention MAX_MODELS = 500 # per batch / per history call MAX_MODEL_LEN = 128 MAX_LATENCY_MS = 600_000 FUTURE_SKEW = 300 # tolerated clock skew for checked_at, seconds STATUSES = ("up", "down", "busy", "unknown") _SCHEMA = ( "CREATE TABLE IF NOT EXISTS model_probe (" " ts INTEGER NOT NULL, model TEXT NOT NULL, status TEXT NOT NULL," " latency_ms INTEGER, http_status INTEGER, PRIMARY KEY (model, ts))", "CREATE INDEX IF NOT EXISTS model_probe_ts ON model_probe (ts)", ) def _connect(db_path: str) -> sqlite3.Connection: con = sqlite3.connect(db_path, timeout=15, isolation_level=None) con.execute("PRAGMA busy_timeout=15000") return con def init(db_path: str) -> None: """Create schema (idempotent) and switch the file to WAL for concurrent readers.""" con = _connect(db_path) try: try: con.execute("PRAGMA journal_mode=WAL") except sqlite3.OperationalError: pass # e.g. locked by another writer; DELETE journal still works for stmt in _SCHEMA: con.execute(stmt) finally: con.close() def _int_or_none(value: Any, lo: int, hi: int) -> int | None: if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value): return None value = int(value) return value if lo <= value <= hi else None def _normalize(model: Any, probe: Any, now: int, cutoff: int) -> tuple | None: if not isinstance(model, str) or not model or len(model) > MAX_MODEL_LEN: return None if not isinstance(probe, Mapping): return None status = probe.get("status") if status not in STATUSES: up = probe.get("up") status = ("unknown" if isinstance(up, bool) or up is None else "up" if up == 1 else "down" if up == 0 else "unknown") ts = _int_or_none(probe.get("checked_at"), 1, now + FUTURE_SKEW) ts = min(ts, now) if ts is not None else now if ts < cutoff: return None latency = _int_or_none(probe.get("ms"), 0, MAX_LATENCY_MS) if status == "up" else None http_status = _int_or_none(probe.get("http_status"), 100, 599) return ts, model, status, latency, http_status def record_batch(db_path: str, status_dict: Mapping[str, Any], now: float | None = None, retention_days: int = RETENTION_DAYS) -> int: now_i = int(time.time() if now is None else now) cutoff = now_i - int(retention_days) * 86400 rows = [] if isinstance(status_dict, Mapping): for model, probe in list(status_dict.items())[:MAX_MODELS]: row = _normalize(model, probe, now_i, cutoff) if row: rows.append(row) init(db_path) con = _connect(db_path) try: con.execute("BEGIN IMMEDIATE") try: before = con.total_changes con.executemany("INSERT OR IGNORE INTO model_probe (ts, model, status, latency_ms, http_status)" " VALUES (?,?,?,?,?)", rows) inserted = con.total_changes - before con.execute("DELETE FROM model_probe WHERE ts < ?", (cutoff,)) excess = con.execute("SELECT COUNT(*) FROM model_probe").fetchone()[0] - MAX_ROWS if excess > 0: con.execute("DELETE FROM model_probe WHERE rowid IN" " (SELECT rowid FROM model_probe ORDER BY ts LIMIT ?)", (excess,)) con.execute("COMMIT") except BaseException: con.execute("ROLLBACK") raise finally: con.close() return inserted def _bucket_state(c: Mapping[str, int]) -> str: if c["up"] and c["down"]: return "partial" if c["down"]: return "down" if c["up"] and not c["busy"]: return "up" if c["up"] or c["busy"]: return "degraded" return "no_data" # only unknown samples or nothing at all def _empty_model(buckets: list[dict]) -> dict: return {"data_state": "no_data", "uptime_pct": None, "sample_count": 0, "observed_count": 0, "counts": dict.fromkeys(STATUSES, 0), "observed_since": None, "last_checked": None, "last_status": None, "latency_ms": None, "latency_avg_ms": None, "coverage_pct": 0.0, "buckets": [dict(b, state="no_data", samples=0, **dict.fromkeys(STATUSES, 0)) for b in buckets]} def history(db_path: str, models: Iterable[str], now: float | None = None, hours: int = WINDOW_HOURS) -> dict: """Per-model timeline of the last ``hours`` one-hour buckets (hour-aligned, UTC). The last bucket is the current, still running hour. ``uptime_pct`` is ``up / (up + down)`` over the window or ``None`` without terminal samples. ``data_state``: ``no_data`` (no samples in window), ``partial`` (history starts inside the window or hours are missing) or ``complete``. """ now_i = int(time.time() if now is None else now) hours = max(1, min(int(hours), 24 * RETENTION_DAYS)) end = (now_i // BUCKET_SECONDS + 1) * BUCKET_SECONDS start = end - hours * BUCKET_SECONDS frame = [{"start": start + i * BUCKET_SECONDS, "end": start + (i + 1) * BUCKET_SECONDS} for i in range(hours)] names = [m for m in dict.fromkeys(models) if isinstance(m, str) and m][:MAX_MODELS] out = {m: _empty_model(frame) for m in names} meta = {"generated_at": now_i, "window_start": start, "window_end": end, "hours": hours, "bucket_seconds": BUCKET_SECONDS, "retention_days": RETENTION_DAYS, "uptime_basis": "up/(up+down); busy=degraded; unknown/no probe=no_data"} if not names: return {**meta, "models": out} init(db_path) con = _connect(db_path) try: marks = ",".join("?" * len(names)) firsts = dict(con.execute(f"SELECT model, MIN(ts) FROM model_probe WHERE model IN ({marks})" " GROUP BY model", names).fetchall()) lasts = {m: (ts, st, lat) for m, ts, st, lat in con.execute( f"SELECT model, ts, status, latency_ms FROM model_probe p WHERE model IN ({marks})" " AND ts = (SELECT MAX(ts) FROM model_probe WHERE model = p.model)", names)} rows = con.execute(f"SELECT model, ts, status, latency_ms FROM model_probe" f" WHERE model IN ({marks}) AND ts >= ? AND ts < ?", (*names, start, end)).fetchall() finally: con.close() lat_sum: dict[str, list[int]] = {} for model, ts, status, latency in rows: if status not in STATUSES: continue item = out[model] bucket = item["buckets"][(ts - start) // BUCKET_SECONDS] bucket[status] += 1 bucket["samples"] += 1 item["counts"][status] += 1 item["sample_count"] += 1 if status == "up" and latency is not None: lat_sum.setdefault(model, []).append(latency) for model, item in out.items(): for bucket in item["buckets"]: bucket["state"] = _bucket_state(bucket) c = item["counts"] terminal = c["up"] + c["down"] item["observed_count"] = terminal item["uptime_pct"] = round(100.0 * c["up"] / terminal, 2) if terminal else None item["observed_since"] = firsts.get(model) if model in lasts: ts, status, latency = lasts[model] item["last_checked"], item["last_status"] = ts, status item["latency_ms"] = latency if status == "up" else None if model in lat_sum: item["latency_avg_ms"] = round(sum(lat_sum[model]) / len(lat_sum[model])) covered = sum(1 for b in item["buckets"] if b["state"] != "no_data") # the running hour may simply not have been probed yet (loop sleeps 30 min) due = hours if item["buckets"][-1]["state"] != "no_data" else hours - 1 item["coverage_pct"] = round(100.0 * covered / max(due, 1), 1) if item["sample_count"] == 0: item["data_state"] = "no_data" elif item["observed_since"] > start or covered < due: item["data_state"] = "partial" else: item["data_state"] = "complete" return {**meta, "models": out}