Files
gabrielvidalandClaude Opus 5.5 72a4f84902 feat(telemetry): the hub's own metrics, a browser beacon and usage events
- GET /api/metrics: per-route latency, event-loop lag, SSE fan-out, watcher
  ticks, memo builds, delta vs full reads, runs by origin (prometheus-client,
  own registry). Owner, or Prometheus with METRICS_TOKEN (scope 'metrics').
- POST /api/telemetry: web vitals, JS errors, update lag, feature events
  from the browser, bounded and checked.
- telemetry.db: per-minute hub history, hourly per-route, usage per day
  (forever) and raw events (90 d).
- GET /api/telemetry/hub and /api/telemetry/usage for the two pages.
- /api/spawn stamps meta.origin (app | script | child | mcp | …).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 16:24:24 +01:00

294 lines
12 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""``telemetry.db`` — its own file beside ai-agent.db (like perf.db), so the
once-a-minute writes never queue behind the indexer.
- ``hub_minutes`` — the whole API per minute: requests, 5xx, latency
quantiles (and the buckets they came from, so a re-flushed minute merges),
plus the event loop's lag, the SSE subscribers, busy threads, the process's
RSS and CPU. :data:`MINUTES_KEEP_S` (30 days).
- ``hub_routes`` — the same per route template, per hour.
:data:`ROUTES_KEEP_S` (90 days).
- ``web_vitals`` — one row per measure a browser reported (LCP, INP, CLS,
FCP, TTFB, and ``update``: transcript event → the open thread showing it).
:data:`WEB_KEEP_S` (30 days).
- ``web_errors`` — uncaught JS errors, one row per message × page × day with
a count. :data:`WEB_KEEP_S`.
- ``usage_events`` — a page view or a named feature event, as it came
(``kind`` ``view`` | ``event``). :data:`EVENTS_KEEP_S` (90 days).
- ``usage_daily`` — every kind (``api`` too: the middleware's route counts)
rolled per day × person × device. Forever: it is a few thousand rows a year.
Nothing here holds a prompt, a path or an id beyond the person's: a usage row
is *who* (``owner`` or a guest's uid), *what* (a feature id or a route
template), *where* (phone / tablet / desktop / script) and *when*."""
from __future__ import annotations
import json
import os
import sqlite3
import threading
import time
from .middleware import EDGES_MS, Hist
MINUTES_KEEP_S = 30 * 86400
ROUTES_KEEP_S = 90 * 86400
WEB_KEEP_S = 30 * 86400
EVENTS_KEEP_S = 90 * 86400
_SCHEMA = """
CREATE TABLE IF NOT EXISTS hub_minutes (
t INTEGER PRIMARY KEY, -- minute start, epoch s
n INTEGER DEFAULT 0, -- /api requests answered (streams excluded)
err INTEGER DEFAULT 0, -- of which 5xx
sum_ms REAL DEFAULT 0,
p50 REAL, p95 REAL, max_ms REAL,
b TEXT, -- the latency buckets (JSON), EDGES_MS
lag_p95 REAL, lag_max REAL, -- event-loop lag, ms
sse INTEGER, -- peak subscribers in the minute
busy INTEGER, -- peak busy sync-handler threads
rss INTEGER, -- bytes
cpu REAL -- % of one core over the minute
);
CREATE TABLE IF NOT EXISTS hub_routes (
t INTEGER NOT NULL, -- hour start, epoch s
route TEXT NOT NULL, -- 'GET /api/conversations'
n INTEGER DEFAULT 0,
err INTEGER DEFAULT 0,
sum_ms REAL DEFAULT 0,
max_ms REAL,
b TEXT,
PRIMARY KEY (t, route)
);
CREATE TABLE IF NOT EXISTS web_vitals (
t REAL NOT NULL,
uid TEXT NOT NULL,
page TEXT NOT NULL,
device TEXT NOT NULL,
name TEXT NOT NULL, -- LCP | INP | CLS | FCP | TTFB | update
value REAL NOT NULL -- ms (CLS: unitless)
);
CREATE INDEX IF NOT EXISTS web_vitals_t ON web_vitals (t);
CREATE TABLE IF NOT EXISTS web_errors (
day TEXT NOT NULL,
message TEXT NOT NULL,
page TEXT NOT NULL,
source TEXT, stack TEXT,
uid TEXT, device TEXT, -- the last to hit it
n INTEGER DEFAULT 0,
first REAL, last REAL,
PRIMARY KEY (day, message, page)
);
CREATE TABLE IF NOT EXISTS usage_events (
t REAL NOT NULL,
uid TEXT NOT NULL,
device TEXT NOT NULL,
surface TEXT, -- pwa | tab
kind TEXT NOT NULL, -- view | event
name TEXT NOT NULL, -- a feature id (frontend lib/telemetry/features.ts)
props TEXT -- small JSON, never content
);
CREATE INDEX IF NOT EXISTS usage_events_t ON usage_events (t);
CREATE TABLE IF NOT EXISTS usage_daily (
day TEXT NOT NULL, -- local YYYY-MM-DD
uid TEXT NOT NULL,
kind TEXT NOT NULL, -- view | event | api
name TEXT NOT NULL,
device TEXT NOT NULL,
n INTEGER DEFAULT 0,
PRIMARY KEY (day, uid, kind, name, device)
);
CREATE INDEX IF NOT EXISTS usage_daily_name ON usage_daily (kind, name);
"""
_UPSERT_DAILY = """
INSERT INTO usage_daily VALUES (?,?,?,?,?,?)
ON CONFLICT (day, uid, kind, name, device) DO UPDATE SET n = n + excluded.n
"""
def _hist_from(row_b: str | None, n: int, err: int, sum_ms: float, max_ms: float | None) -> Hist:
h = Hist()
h.n, h.err, h.sum, h.max = n or 0, err or 0, sum_ms or 0.0, max_ms or 0.0
try:
b = json.loads(row_b) if row_b else None
except ValueError:
b = None
if isinstance(b, list) and len(b) == len(EDGES_MS) + 1:
h.b = [int(x) for x in b]
return h
def _quantile(samples: list[float], q: float) -> float | None:
if not samples:
return None
s = sorted(samples)
return round(s[min(len(s) - 1, int(q * len(s)))], 1)
class TelemetryStore:
def __init__(self, path: str):
self._path = path
self._lock = threading.Lock()
self._db = sqlite3.connect(path, check_same_thread=False)
self._db.execute("PRAGMA journal_mode=WAL")
self._db.execute("PRAGMA synchronous=NORMAL")
self._db.execute("PRAGMA busy_timeout=5000")
self._db.execute("PRAGMA journal_size_limit=8388608")
self._db.executescript(_SCHEMA)
self._cpu_at: tuple[float, float] | None = None
self._pruned = 0.0
@classmethod
def beside(cls, db_path: str) -> "TelemetryStore":
return cls(os.path.join(os.path.dirname(db_path) or ".", "telemetry.db"))
# ---- writes -------------------------------------------------------------
def _merge(self, table: str, where: str, args: tuple, h: Hist) -> Hist:
row = self._db.execute(
f"SELECT b, n, err, sum_ms, max_ms FROM {table} WHERE {where}", args).fetchone()
if row:
old = _hist_from(*row)
old.merge(h)
return old
return h
def flush(self, minutes: dict, hours: dict, usage: dict, lag_ms: list[float],
sse: int, busy: int, now: float | None = None) -> None:
"""Write what the middleware and the lag watch gathered since the last
flush (``middleware.Rollup.take`` + ``loop.WINDOW``)."""
now = now or time.time()
# The flush runs just past a minute's end: the lag gathered is the
# minute that just closed.
minute = int((now - 30) // 60 * 60)
rss, cpu = self._process()
with self._lock:
for t, h in minutes.items():
h = self._merge("hub_minutes", "t = ?", (t,), h)
self._db.execute(
"INSERT INTO hub_minutes (t, n, err, sum_ms, p50, p95, max_ms, b) "
"VALUES (?,?,?,?,?,?,?,?) ON CONFLICT (t) DO UPDATE SET "
"n=excluded.n, err=excluded.err, sum_ms=excluded.sum_ms, "
"p50=excluded.p50, p95=excluded.p95, max_ms=excluded.max_ms, b=excluded.b",
(t, h.n, h.err, h.sum, h.quantile(.5), h.quantile(.95), h.max,
json.dumps(h.b)))
if lag_ms or sse or rss:
self._db.execute(
"INSERT INTO hub_minutes (t, lag_p95, lag_max, sse, busy, rss, cpu) "
"VALUES (?,?,?,?,?,?,?) ON CONFLICT (t) DO UPDATE SET "
"lag_p95=excluded.lag_p95, lag_max=excluded.lag_max, sse=excluded.sse, "
"busy=excluded.busy, rss=excluded.rss, cpu=excluded.cpu",
(minute, _quantile(lag_ms, .95), round(max(lag_ms), 1) if lag_ms else None,
sse, busy, rss, cpu))
for (t, route), h in hours.items():
h = self._merge("hub_routes", "t = ? AND route = ?", (t, route), h)
self._db.execute(
"INSERT OR REPLACE INTO hub_routes VALUES (?,?,?,?,?,?,?)",
(t, route, h.n, h.err, h.sum, h.max, json.dumps(h.b)))
self._db.executemany(_UPSERT_DAILY, [
(day, uid, "api", name, device, n)
for (day, uid, name, device), n in usage.items()])
self._db.commit()
if now - self._pruned > 6 * 3600:
self.prune(now)
def _process(self) -> tuple[int | None, float | None]:
"""This process's RSS (bytes) and CPU % of one core since the last call."""
rss = cpu = None
try:
with open("/proc/self/statm") as f:
rss = int(f.read().split()[1]) * os.sysconf("SC_PAGE_SIZE")
except (OSError, ValueError, IndexError):
pass
t = os.times()
used, wall = t.user + t.system, time.monotonic()
if self._cpu_at:
dw = wall - self._cpu_at[1]
if dw > 0:
cpu = round(100 * (used - self._cpu_at[0]) / dw, 1)
self._cpu_at = (used, wall)
return rss, cpu
def add_vitals(self, rows: list[tuple]) -> None:
if not rows:
return
with self._lock:
self._db.executemany("INSERT INTO web_vitals VALUES (?,?,?,?,?,?)", rows)
self._db.commit()
def add_errors(self, rows: list[dict]) -> None:
if not rows:
return
with self._lock:
for r in rows:
self._db.execute(
"INSERT INTO web_errors VALUES (?,?,?,?,?,?,?,1,?,?) "
"ON CONFLICT (day, message, page) DO UPDATE SET n = n + 1, "
"last = excluded.last, uid = excluded.uid, device = excluded.device, "
"stack = COALESCE(excluded.stack, stack)",
(r["day"], r["message"], r["page"], r.get("source"), r.get("stack"),
r["uid"], r["device"], r["t"], r["t"]))
self._db.commit()
def add_events(self, rows: list[tuple]) -> None:
"""``(t, uid, device, surface, kind, name, props)`` rows, each also
counted in its day's ``usage_daily``."""
if not rows:
return
daily: dict[tuple, int] = {}
for t, uid, device, _surface, kind, name, _props in rows:
key = (time.strftime("%Y-%m-%d", time.localtime(t)), uid, kind, name, device)
daily[key] = daily.get(key, 0) + 1
with self._lock:
self._db.executemany("INSERT INTO usage_events VALUES (?,?,?,?,?,?,?)", rows)
self._db.executemany(_UPSERT_DAILY, [(*k, n) for k, n in daily.items()])
self._db.commit()
def prune(self, now: float | None = None) -> None:
now = now or time.time()
self._pruned = now
day = time.strftime("%Y-%m-%d", time.localtime(now - WEB_KEEP_S))
with self._lock:
self._db.execute("DELETE FROM hub_minutes WHERE t < ?", (now - MINUTES_KEEP_S,))
self._db.execute("DELETE FROM hub_routes WHERE t < ?", (now - ROUTES_KEEP_S,))
self._db.execute("DELETE FROM web_vitals WHERE t < ?", (now - WEB_KEEP_S,))
self._db.execute("DELETE FROM web_errors WHERE day < ?", (day,))
self._db.execute("DELETE FROM usage_events WHERE t < ?", (now - EVENTS_KEEP_S,))
self._db.commit()
# ---- reads --------------------------------------------------------------
def query(self, sql: str, args: tuple = ()) -> list[tuple]:
with self._lock:
return self._db.execute(sql, args).fetchall()
class Flusher(threading.Thread):
"""Once a minute: the middleware's rollup + the lag window → the store."""
def __init__(self, store: TelemetryStore, interval: float = 60.0):
super().__init__(daemon=True, name="telemetry-flush")
self.store = store
self.interval = interval
self._stop = threading.Event()
def stop(self) -> None:
self._stop.set()
def run(self) -> None:
while not self._stop.wait(self.interval - time.time() % self.interval + 1):
self.flush_once()
def flush_once(self) -> None:
from .loop import WINDOW
from .middleware import ROLLUP
try:
minutes, hours, usage = ROLLUP.take()
lag = WINDOW.take()
sse, busy = WINDOW.sse, WINDOW.busy
WINDOW.sse = WINDOW.busy = 0
self.store.flush(minutes, hours, usage, lag, sse, busy)
except Exception:
pass