Files
gabrielvidalandClaude Opus 5.5 a1dc1d8c88 perf(hub): cheap conversation widgets — cached + delta /calls, stale-while-revalidate rollups, perf reads beside writes
- /api/perf/conversation/{sid}/calls: per-call view cache on (updated, len(data)),
  ?since= delta with a cursor (client polls since = cursor - 30), marks memo,
  (sid, updated) index. 260 calls: ~1 s → 3.7 ms cached, 0.7 ms per empty poll.
- _Memo: max_stale (soft key = summaries_version) + slots; project costs and
  the related index use it (151 cost rebuilds x ~10 s in 40 min on prod).
- PerfStore: per-thread read-only connections, so a slow ingest no longer
  parks pool threads (14 seen in query) and starves conversation reads.

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

320 lines
15 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.
"""SQLite tables for the Performance dashboard — what every runner's ``/procs``
said, kept at three grains (its own ``perf.db`` next to ai-agent.db, so the
5-s writes never queue behind the indexer's):
- ``perf_samples`` — every poll, per agent run and per machine (``sid = ''``):
CPU %, RSS, process count. Kept ``SAMPLES_KEEP_S`` (48 h).
- ``perf_minutes`` — those rolled up per minute (avg + max). ``MINUTES_KEEP_S``
(30 days).
- ``perf_runs`` — one row per agent process (a run, each resume): cumulative
CPU seconds and the peaks. Forever; a conversation's totals are its rows
summed.
- ``perf_procs`` — one row per process seen in a run's tree or left over from
one: its label (``npm run build``, ``vite``), CPU, peak RSS, and the
leftover bookkeeping (since when, kept, killed). Bash-tool shells
(``kind = 'tool'``) are kept only while that bookkeeping needs them
(``TOOL_ROWS_KEEP_S``): what a call cost is the call probe's (calls.py);
the small rest is pruned after 30 days.
CPU is in % of one core (``cpu``) or CPU seconds; memory in bytes."""
from __future__ import annotations
import os
import sqlite3
import threading
import time
from .calls import SCHEMA as CALLS_SCHEMA
from .storage import SCHEMA as STORAGE_SCHEMA
SAMPLES_KEEP_S = 48 * 3600
MINUTES_KEEP_S = 30 * 86400
PROCS_KEEP_S = 30 * 86400
# A sampled Bash-tool shell: only the leftover auto-kill reads it (the call
# probe has the call's exact cost), so it goes once it is gone a day.
TOOL_ROWS_KEEP_S = 86400
# Page cache of each thread's read connection (KiB): up to one per pool thread.
READ_CACHE_KIB = 2048
_SCHEMA = """
CREATE TABLE IF NOT EXISTS perf_samples (
t REAL NOT NULL,
runner TEXT NOT NULL, -- 'lab' | a worker id
sid TEXT NOT NULL, -- '' = the machine itself
cpu REAL, -- % of one core
rss INTEGER, -- bytes (the machine: memory in use)
procs INTEGER
);
CREATE INDEX IF NOT EXISTS perf_samples_t ON perf_samples (t);
CREATE INDEX IF NOT EXISTS perf_samples_sid ON perf_samples (sid, t);
CREATE TABLE IF NOT EXISTS perf_minutes (
t INTEGER NOT NULL, -- minute start, epoch s
runner TEXT NOT NULL,
sid TEXT NOT NULL,
cpu REAL, cpu_max REAL,
rss INTEGER, rss_max INTEGER,
procs INTEGER,
PRIMARY KEY (runner, sid, t)
);
CREATE INDEX IF NOT EXISTS perf_minutes_t ON perf_minutes (t);
CREATE TABLE IF NOT EXISTS perf_runs (
runner TEXT NOT NULL,
sid TEXT NOT NULL,
root_pid INTEGER NOT NULL,
root_start REAL NOT NULL, -- the process's start, epoch s
harness TEXT, source TEXT, -- source: hub | terminal
first_seen REAL, last_seen REAL,
cpu_seconds REAL DEFAULT 0, -- the tree's, reaped children included
peak_cpu REAL DEFAULT 0,
peak_rss INTEGER DEFAULT 0,
peak_procs INTEGER DEFAULT 0,
PRIMARY KEY (runner, sid, root_pid, root_start)
);
CREATE INDEX IF NOT EXISTS perf_runs_last ON perf_runs (last_seen);
CREATE TABLE IF NOT EXISTS perf_procs (
runner TEXT NOT NULL,
pid INTEGER NOT NULL,
started REAL NOT NULL, -- epoch s
sid TEXT NOT NULL,
kind TEXT, -- 'tool' = a Bash-tool shell
label TEXT NOT NULL,
cmd TEXT,
first_seen REAL, last_seen REAL,
cpu_seconds REAL DEFAULT 0, -- its own
tree_cpu REAL DEFAULT 0, -- it + everything under it
peak_rss INTEGER DEFAULT 0,
peak_tree_rss INTEGER DEFAULT 0,
leftover_since REAL, -- first poll that saw its run ended
kept INTEGER DEFAULT 0, -- never auto-killed
killed_at REAL, kill_reason TEXT,
PRIMARY KEY (runner, pid, started)
);
CREATE INDEX IF NOT EXISTS perf_procs_sid ON perf_procs (sid);
CREATE INDEX IF NOT EXISTS perf_procs_last ON perf_procs (last_seen);
"""
_UPSERT_RUN = """
INSERT INTO perf_runs VALUES (?,?,?,?,?,?,?,?,?,?,?,?)
ON CONFLICT (runner, sid, root_pid, root_start) DO UPDATE SET
last_seen = excluded.last_seen,
cpu_seconds = MAX(cpu_seconds, excluded.cpu_seconds),
peak_cpu = MAX(peak_cpu, excluded.peak_cpu),
peak_rss = MAX(peak_rss, excluded.peak_rss),
peak_procs = MAX(peak_procs, excluded.peak_procs)
"""
_UPSERT_PROC = """
INSERT INTO perf_procs (runner, pid, started, sid, kind, label, cmd, first_seen,
last_seen, cpu_seconds, tree_cpu, peak_rss, peak_tree_rss, leftover_since, in_tool)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
ON CONFLICT (runner, pid, started) DO UPDATE SET
last_seen = excluded.last_seen, in_tool = MAX(in_tool, excluded.in_tool),
label = excluded.label, cmd = excluded.cmd,
cpu_seconds = MAX(cpu_seconds, excluded.cpu_seconds),
tree_cpu = MAX(tree_cpu, excluded.tree_cpu),
peak_rss = MAX(peak_rss, excluded.peak_rss),
peak_tree_rss = MAX(peak_tree_rss, excluded.peak_tree_rss),
leftover_since = CASE WHEN excluded.leftover_since IS NULL THEN NULL
ELSE COALESCE(leftover_since, excluded.leftover_since) END
"""
def _start(row: dict) -> float:
return round(float(row.get("startedAt") or 0), 0)
class PerfStore:
"""Writes go through one connection under ``_lock``; reads (``query``,
``proc_state``) through a read-only connection per thread, so they run
beside a write instead of queueing behind it — WAL readers never wait on
the writer. On prod a slow ingest (an ``executemany`` on the 689 MB
perf.db, the box swapping) held the lock while 14 pool threads sat in
``query`` and conversation reads waited 60–90 s for a free thread. A
store that isn't WAL (``:memory:``, a filesystem without it) keeps
reading through the writer's connection, under the lock."""
def __init__(self, path: str):
self._path = path
self._lock = threading.Lock()
self._local = threading.local()
self._db = sqlite3.connect(path, check_same_thread=False)
self._db.execute("PRAGMA auto_vacuum=INCREMENTAL")
mode = self._db.execute("PRAGMA journal_mode=WAL").fetchone()
self._wal = bool(mode) and str(mode[0]).lower() == "wal"
self._db.execute("PRAGMA synchronous=NORMAL")
self._db.execute("PRAGMA busy_timeout=5000")
self._db.execute("PRAGMA journal_size_limit=16777216")
self._db.executescript(_SCHEMA)
self._db.executescript(CALLS_SCHEMA) # the call probe's records (calls.py)
self._db.executescript(STORAGE_SCHEMA) # what sessions keep on disk (storage.py)
# in_tool: the process ran inside a Bash call (procstats ``inTool``) —
# the call probe has it exactly, so the program ranking skips it
cols = {r[1] for r in self._db.execute("PRAGMA table_info(perf_procs)").fetchall()}
if "in_tool" not in cols:
self._db.execute("ALTER TABLE perf_procs ADD COLUMN in_tool INTEGER DEFAULT 0")
self._db.commit()
# disk_net: what the call left on disk, net (agent-probe's / claude-probe >= 0.3's
# `files`: exact per write) — the Biggest writers ranking
cols = {r[1] for r in self._db.execute("PRAGMA table_info(perf_calls)").fetchall()}
if "disk_net" not in cols:
self._db.execute("ALTER TABLE perf_calls ADD COLUMN disk_net INTEGER")
self._db.execute("CREATE INDEX IF NOT EXISTS perf_calls_disk ON perf_calls (disk_net)")
self._db.commit()
self._rolled = 0 # the last minute rolled up
def wal_checkpoint(self, mode: str = "TRUNCATE") -> None:
if mode not in ("PASSIVE", "FULL", "RESTART", "TRUNCATE"):
mode = "TRUNCATE"
with self._lock:
self._db.execute(f"PRAGMA wal_checkpoint({mode})").fetchall()
def incremental_vacuum(self, pages: int = 1000) -> None:
with self._lock:
self._db.execute(f"PRAGMA incremental_vacuum({int(pages)})").fetchall()
@classmethod
def beside(cls, db_path: str) -> "PerfStore":
return cls(os.path.join(os.path.dirname(db_path) or ".", "perf.db"))
# ---- writes ---------------------------------------------------------------
def record(self, runner: str, snap: dict) -> None:
"""One ``/procs`` snapshot: a sample per run and for the machine, the
run totals, every process's row."""
t = float(snap.get("at") or time.time())
host = snap.get("host") or {}
samples, runs, procs = [], [], []
used = None
if host.get("memTotal") and host.get("memAvailable") is not None:
used = int(host["memTotal"] - host["memAvailable"])
samples.append((t, runner, "", host.get("cpu"), used, None))
for s in snap.get("sessions") or []:
sid = s["sessionId"]
samples.append((t, runner, sid, s.get("cpu"), s.get("rss"), s.get("procs")))
runs.append((runner, sid, s["rootPid"], _start(s), s.get("harness"),
s.get("source"), t, t, s.get("cpuSeconds") or 0,
s.get("cpu") or 0, s.get("rss") or 0, s.get("procs") or 0))
procs += [_proc_row(runner, sid, r, t, None) for r in s.get("processes") or []]
for g in snap.get("leftovers") or []:
procs += [_proc_row(runner, g["sessionId"], r, t, t)
for r in g.get("processes") or []]
with self._lock:
self._db.executemany("INSERT INTO perf_samples VALUES (?,?,?,?,?,?)", samples)
self._db.executemany(_UPSERT_RUN, runs)
self._db.executemany(_UPSERT_PROC, procs)
self._db.commit()
def rollup(self, now: float | None = None) -> int:
"""Fold every finished minute's samples into ``perf_minutes``."""
upto = int((now or time.time()) // 60 * 60)
with self._lock:
since = self._rolled or int(self._db.execute(
"SELECT COALESCE(MAX(t) + 60, 0) FROM perf_minutes").fetchone()[0])
if since == 0:
first = self._db.execute("SELECT MIN(t) FROM perf_samples").fetchone()[0]
since = int(first // 60 * 60) if first else upto
if since >= upto:
return 0
cur = self._db.execute(
"INSERT OR REPLACE INTO perf_minutes SELECT CAST(t / 60 AS INT) * 60,"
" runner, sid, AVG(cpu), MAX(cpu), CAST(AVG(rss) AS INT), MAX(rss),"
" MAX(procs) FROM perf_samples WHERE t >= ? AND t < ?"
" GROUP BY 1, runner, sid", (since, upto))
self._db.commit()
self._rolled = upto
return cur.rowcount
def prune(self, now: float | None = None) -> None:
now = now or time.time()
with self._lock:
self._db.execute("DELETE FROM perf_samples WHERE t < ?", (now - SAMPLES_KEEP_S,))
self._db.execute("DELETE FROM perf_minutes WHERE t < ?", (now - MINUTES_KEEP_S,))
self._db.execute(
"DELETE FROM perf_procs WHERE last_seen < ? AND kind IS NULL"
" AND tree_cpu < 5 AND peak_tree_rss < 200000000", (now - PROCS_KEEP_S,))
self._db.execute("DELETE FROM perf_procs WHERE kind = 'tool' AND last_seen < ?"
" AND kept = 0", (now - TOOL_ROWS_KEEP_S,))
self._db.commit()
from . import storage # noqa: PLC0415
storage.prune(self, now)
def mark_killed(self, runner: str, rows: list[tuple[int, float]], reason: str) -> None:
now = time.time()
with self._lock:
self._db.executemany(
"UPDATE perf_procs SET killed_at = ?, kill_reason = ?"
" WHERE runner = ? AND pid = ? AND ABS(started - ?) < 2",
[(now, reason, runner, pid, st) for pid, st in rows])
self._db.commit()
def set_kept(self, runner: str, pid: int, started: float, kept: bool) -> bool:
with self._lock:
cur = self._db.execute(
"UPDATE perf_procs SET kept = ? WHERE runner = ? AND pid = ?"
" AND ABS(started - ?) < 2", (1 if kept else 0, runner, pid, started))
self._db.commit()
return cur.rowcount > 0
def write(self, statements: list[tuple[str, list[tuple]]]) -> None:
"""Several ``executemany``s in one transaction (calls.py)."""
with self._lock:
for sql, rows in statements:
if rows:
self._db.executemany(sql, rows)
self._db.commit()
def insert_once(self, sql: str, args: tuple) -> bool:
"""One INSERT OR IGNORE: whether this call is the one that inserted."""
with self._lock:
cur = self._db.execute(sql, args)
self._db.commit()
return cur.rowcount > 0
def script(self, sql: str) -> None:
with self._lock:
self._db.executescript(sql)
# ---- reads ----------------------------------------------------------------
def _reader(self) -> sqlite3.Connection | None:
"""This thread's read-only connection (None: read under the lock).
Each read is one autocommit statement, so it sees every committed
write — a ``write`` then a ``query`` on any thread reads what it wrote."""
if not self._wal:
return None
conn = getattr(self._local, "db", None)
if conn is None:
conn = sqlite3.connect(self._path, check_same_thread=True)
conn.execute("PRAGMA query_only=1")
conn.execute("PRAGMA busy_timeout=5000")
conn.execute(f"PRAGMA cache_size=-{int(READ_CACHE_KIB)}")
self._local.db = conn # closed with its thread
return conn
def query(self, sql: str, args: tuple = ()) -> list[tuple]:
conn = self._reader()
if conn is None:
with self._lock:
return self._db.execute(sql, args).fetchall()
return conn.execute(sql, args).fetchall()
def proc_state(self, runner: str, rows: list[dict]) -> dict[tuple[int, float], tuple]:
"""(pid, started) → (leftover_since, kept, killed_at) for these rows."""
if not rows:
return {}
sql = ("SELECT leftover_since, kept, killed_at FROM perf_procs WHERE runner = ?"
" AND pid = ? AND ABS(started - ?) < 2")
out = {}
for r in rows:
hit = self.query(sql, (runner, r["pid"], _start(r)))
if hit:
out[(r["pid"], _start(r))] = hit[0]
return out
def _proc_row(runner: str, sid: str, r: dict, t: float, leftover: float | None) -> tuple:
return (runner, r["pid"], _start(r), sid, r.get("kind"), r.get("label") or "?",
r.get("cmd"), t, t, r.get("cpuSeconds") or 0, r.get("treeCpuSeconds") or 0,
r.get("rss") or 0, r.get("treeRss") or 0, leftover, 1 if r.get("inTool") else 0)