wrolpi/scripts/api_perf_history.py

502 lines
23 KiB
Python
Raw Normal View History

API benchmark: run history and regression detection (#1084) * API benchmark: run history and regression detection api_perf.py --record saves each run to a SQLite history kept outside the repository (--data-dir, $WROLPI_BENCH_DIR, or ~/.local/share/wrolpi-bench) and reports endpoints that got slower than their own baseline: the median of the last 5 trustworthy runs, flagged at 1.5x and +100 ms, with hot regressions re-timed before they are reported. Also reports slow drift, errors, slow endpoints, response growth, library growth, and the commits between the baseline and the run that touched related code. Runs on a busy host (downloads, load above core count) or during which the API was unavailable are recorded but never used as baselines. Host profiles can live in the data dir so LAN addresses stay out of every checkout; a profile marked production refuses --cold without --restart-production. The catalog drops the removed ai/chat endpoints and adds repos, bookmarks, jobs, torrents, sync, speedtest, map and video description endpoints. test_api_perf.py fails when a GET route is neither timed nor deliberately excluded, so new endpoints are not silently left out. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * API benchmark: a 5xx is an endpoint error, not an unavailable API Sanic answers 503 when a single request exceeds its response timeout; that endpoint is reported as an error and the run stays a usable baseline. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 17:16:23 -07:00
#!/usr/bin/env python3
"""
History of `scripts/api_perf.py` runs, and detection of endpoints that got slower.
Runs recorded with `api_perf.py --record` are kept in a SQLite file OUTSIDE the repository so results
(and the hosts they describe) are never committed. The location is, in order of precedence:
`--data-dir`, `$WROLPI_BENCH_DIR`, `~/.local/share/wrolpi-bench`.
# Report on the newest run of a host (regressions, slow endpoints, improvements, trends).
python3 scripts/api_perf_history.py report --host rpi
# List recorded runs.
python3 scripts/api_perf_history.py runs [--host rpi]
# Time series of one endpoint (substring match on the endpoint name).
python3 scripts/api_perf_history.py series --host rpi --name "videos/search (page 1"
# Import CSVs written by older versions of api_perf.py (host and time come from the file name).
python3 scripts/api_perf_history.py import old_results/*.csv
Only the standard library is used.
"""
import argparse
import csv
import datetime
import json
import os
import re
import sqlite3
import statistics
import subprocess
import sys
from pathlib import Path
from typing import List, Optional
# A finding is reported only when an endpoint is at least this much slower than its baseline, in BOTH
# relative and absolute terms; small endpoints jitter by large ratios, big ones by large milliseconds.
REGRESSION_RATIO = 1.5
REGRESSION_MIN_MS = 100.0
# The baseline is the median of an endpoint's medians over this many previous trustworthy runs.
BASELINE_RUNS = 5
# A hot median above this is reported as slow, history or not.
SLOW_MS = 1000.0
# Slow drift: compare the older half of the last TREND_RUNS runs with the newer half.
TREND_RUNS = 10
TREND_RATIO = 1.25
TREND_MIN_MS = 50.0
PHASES = ('hot', 'cold', 'cold-each')
SCHEMA = '''
CREATE TABLE IF NOT EXISTS run (
id INTEGER PRIMARY KEY,
host TEXT NOT NULL,
started_at TEXT NOT NULL,
source TEXT NOT NULL DEFAULT 'live',
cold INTEGER NOT NULL DEFAULT 0,
version TEXT,
git_commit TEXT,
git_branch TEXT,
query TEXT,
busy INTEGER NOT NULL DEFAULT 0,
busy_reason TEXT,
load_1 REAL,
db_size INTEGER,
file_count INTEGER,
video_count INTEGER,
archive_count INTEGER,
context_json TEXT
);
CREATE INDEX IF NOT EXISTS run_host_started ON run (host, started_at);
CREATE TABLE IF NOT EXISTS result (
run_id INTEGER NOT NULL REFERENCES run (id) ON DELETE CASCADE,
name TEXT NOT NULL,
phase TEXT NOT NULL,
method TEXT,
path TEXT,
n INTEGER NOT NULL,
median_ms REAL,
min_ms REAL,
max_ms REAL,
status TEXT,
bytes INTEGER,
errors INTEGER NOT NULL DEFAULT 0,
recheck_ms REAL,
PRIMARY KEY (run_id, name, phase)
);
'''
# Endpoint name prefix -> source paths whose commits are suspects when that endpoint regresses.
# Longest matching prefix wins. Every endpoint also gets COMMON_SUSPECT_PATHS.
SUSPECT_PATHS = {
'videos': ['modules/videos'],
'archive': ['modules/archive'],
'docs': ['modules/docs'],
'zim': ['modules/zim'],
'map': ['modules/map'],
'inventory': ['modules/inventory'],
'flasher': ['modules/flasher'],
'repos': ['modules/repos'],
'torrents': ['modules/torrents'],
'collections': ['wrolpi/collections'],
'files': ['wrolpi/files'],
'tag': ['wrolpi/tags.py'],
'statistics': ['wrolpi/root_api.py', 'wrolpi/files'],
'status': ['wrolpi/root_api.py', 'wrolpi/status.py'],
'search_': ['wrolpi/files', 'wrolpi/root_api.py'],
'sync': ['wrolpi/sync'],
'jobs': ['wrolpi/jobs.py'],
'bookmarks': ['wrolpi/bookmarks_api.py', 'wrolpi/bookmarks.py'],
}
COMMON_SUSPECT_PATHS = ['wrolpi/db.py', 'wrolpi/api_utils.py', 'alembic', 'requirements.txt']
LEGACY_CSV_NAME = re.compile(r'^(?P<host>.+)_(?P<stamp>\d{8}_\d{6})$')
# ----------------------------------------------------------------------------------------------
# Storage
# ----------------------------------------------------------------------------------------------
def data_dir(override: Optional[str] = None) -> Path:
path = Path(override or os.environ.get('WROLPI_BENCH_DIR') or Path.home() / '.local/share/wrolpi-bench')
path = path.expanduser()
path.mkdir(parents=True, exist_ok=True)
return path
def connect(path) -> sqlite3.Connection:
conn = sqlite3.connect(str(path))
conn.row_factory = sqlite3.Row
conn.execute('PRAGMA foreign_keys = ON')
conn.executescript(SCHEMA)
return conn
def _int(value) -> Optional[int]:
try:
return int(value)
except (TypeError, ValueError):
return None
def _float(value) -> Optional[float]:
try:
return float(value)
except (TypeError, ValueError):
return None
def context_from_api(status: Optional[dict], stats: Optional[dict], load: Optional[dict] = None,
cpu: Optional[dict] = None) -> dict:
"""Pull what explains a timing out of /api/status, /api/statistics and the Controller's load/cpu
stats: what code ran, how big the library is, and whether the host was busy (a busy run is recorded
but never used as a baseline)."""
status = status or {}
stats = stats or {}
file_stats = stats.get('file_statistics') or {}
load_1 = _float((load or status.get('load_stats') or {}).get('minute_1'))
cores = _int((cpu or status.get('cpu_stats') or {}).get('cores'))
downloads = status.get('downloads') or {}
reasons = []
if downloads and not downloads.get('stopped') and not downloads.get('disabled') and downloads.get('pending'):
reasons.append(f'{downloads["pending"]} downloads pending')
if load_1 is not None and cores and load_1 > cores:
reasons.append(f'load {load_1} > {cores} cores')
return dict(
version=(status.get('version') or '').strip() or None,
git_commit=status.get('current_commit'),
git_branch=status.get('git_branch'),
load_1=load_1,
db_size=_int((stats.get('global_statistics') or {}).get('db_size')),
file_count=_int(file_stats.get('total_count')),
video_count=_int(file_stats.get('video_count')),
archive_count=_int(file_stats.get('archive_count')),
busy=bool(reasons),
busy_reason='; '.join(reasons) or None,
)
def mark_unavailable(context: dict, rows: List[dict]) -> dict:
"""A run during which the API could not answer (redirected to the fallback UI, refused, no response) says
nothing about endpoint speed; mark it busy so it is never a baseline. A 5xx is the endpoint's own error
(Sanic answers 503 when one request exceeds its response timeout) and is reported as such."""
down = [r for r in rows if str(r['status']) in ('301', '302', 'HTML', 'None', '')]
if down:
reasons = [context['busy_reason']] if context.get('busy_reason') else []
reasons.append(f'API unavailable for {len(down)} of {len(rows)} requests')
context.update(busy=True, busy_reason='; '.join(reasons))
return context
def summarize_rows(rows: List[dict]) -> List[dict]:
"""Collapse per-request rows (as written to the CSV) into one result per (endpoint, phase)."""
grouped = {}
for row in rows:
grouped.setdefault((row['name'], row['phase']), []).append(row)
results = []
for (name, phase), group in grouped.items():
ok = [float(r['ms']) for r in group if str(r['status']) == '200']
statuses = sorted({str(r['status']) for r in group})
results.append(dict(
name=name, phase=phase, method=group[0].get('method'), path=group[0].get('path'), n=len(group),
median_ms=statistics.median(ok) if ok else None, min_ms=min(ok) if ok else None,
max_ms=max(ok) if ok else None, status=','.join(statuses),
bytes=max((_int(r['bytes']) or 0 for r in group), default=0),
errors=len(group) - len(ok),
))
return results
def record_run(conn, host: str, started_at: str, rows: List[dict], context: Optional[dict] = None,
cold: bool = False, query: Optional[str] = None, source: str = 'live',
extra_context: Optional[dict] = None) -> int:
context = context or {}
cur = conn.execute(
'INSERT INTO run (host, started_at, source, cold, version, git_commit, git_branch, query, busy, busy_reason,'
' load_1, db_size, file_count, video_count, archive_count, context_json)'
' VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)',
(host, started_at, source, int(cold), context.get('version'), context.get('git_commit'),
context.get('git_branch'), query, int(bool(context.get('busy'))), context.get('busy_reason'),
context.get('load_1'), context.get('db_size'), context.get('file_count'), context.get('video_count'),
context.get('archive_count'), json.dumps(extra_context) if extra_context else None))
run_id = cur.lastrowid
for r in summarize_rows(rows):
conn.execute(
'INSERT INTO result (run_id, name, phase, method, path, n, median_ms, min_ms, max_ms, status, bytes,'
' errors) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)',
(run_id, r['name'], r['phase'], r['method'], r['path'], r['n'], r['median_ms'], r['min_ms'],
r['max_ms'], r['status'], r['bytes'], r['errors']))
conn.commit()
return run_id
def set_recheck(conn, run_id: int, name: str, phase: str, recheck_ms: Optional[float]):
conn.execute('UPDATE result SET recheck_ms = ? WHERE run_id = ? AND name = ? AND phase = ?',
(recheck_ms, run_id, name, phase))
conn.commit()
def import_csv(conn, path: Path) -> Optional[int]:
"""Import one CSV written by api_perf.py. Returns the new run id, or None when the file is not an
api_perf CSV or was already imported."""
match = LEGACY_CSV_NAME.match(path.stem)
if not match:
return None
with open(path, newline='') as fh:
reader = csv.DictReader(fh)
if not reader.fieldnames or not {'phase', 'name', 'ms', 'status'} <= set(reader.fieldnames):
return None
rows = list(reader)
if not rows:
return None
host = match['host']
started_at = datetime.datetime.strptime(match['stamp'], '%Y%m%d_%H%M%S').isoformat()
exists = conn.execute('SELECT 1 FROM run WHERE host = ? AND started_at = ?', (host, started_at)).fetchone()
if exists:
return None
cold = any(r['phase'] in ('cold', 'cold-each') for r in rows)
return record_run(conn, host, started_at, rows, cold=cold, source='import',
extra_context=dict(file=path.name))
# ----------------------------------------------------------------------------------------------
# Analysis
# ----------------------------------------------------------------------------------------------
def effective_ms(row) -> Optional[float]:
"""A recheck replaces the run's median: a slowdown that did not survive the recheck was noise."""
if row['recheck_ms'] is not None:
return row['recheck_ms']
return row['median_ms']
def previous_values(conn, run, name: str, phase: str, limit: int) -> List[sqlite3.Row]:
"""The endpoint's results from earlier trustworthy runs of the same host, newest first."""
return conn.execute(
'SELECT result.*, run.git_commit, run.started_at FROM result JOIN run ON run.id = result.run_id'
' WHERE run.host = ? AND run.started_at < ? AND run.busy = 0 AND result.name = ? AND result.phase = ?'
' AND result.median_ms IS NOT NULL AND result.errors = 0'
' ORDER BY run.started_at DESC LIMIT ?',
(run['host'], run['started_at'], name, phase, limit)).fetchall()
def is_regression(current_ms: float, baseline_ms: float) -> bool:
return current_ms >= baseline_ms * REGRESSION_RATIO and current_ms - baseline_ms >= REGRESSION_MIN_MS
def is_improvement(current_ms: float, baseline_ms: float) -> bool:
return baseline_ms >= current_ms * REGRESSION_RATIO and baseline_ms - current_ms >= REGRESSION_MIN_MS
def evaluate(conn, run_id: int) -> List[dict]:
"""Compare one run against its host's history. Returns findings, each a dict with `kind` one of
regression, improvement, trend, slow, error, new."""
run = conn.execute('SELECT * FROM run WHERE id = ?', (run_id,)).fetchone()
if run is None:
raise ValueError(f'No run {run_id}')
findings = []
for row in conn.execute('SELECT * FROM result WHERE run_id = ? ORDER BY name, phase', (run_id,)):
name, phase = row['name'], row['phase']
base = dict(name=name, phase=phase, path=row['path'], bytes=row['bytes'])
current = effective_ms(row)
if row['errors'] or current is None:
findings.append(dict(base, kind='error', status=row['status'], errors=row['errors'], n=row['n']))
continue
previous = previous_values(conn, run, name, phase, max(BASELINE_RUNS, TREND_RUNS - 1))
if not previous:
findings.append(dict(base, kind='new', ms=current))
else:
window = previous[:BASELINE_RUNS]
baseline = statistics.median(effective_ms(p) for p in window)
prev_bytes = statistics.median(p['bytes'] or 0 for p in window)
info = dict(base, ms=current, baseline_ms=baseline, baseline_runs=len(window),
baseline_commit=window[0]['git_commit'], baseline_bytes=prev_bytes,
rechecked=row['recheck_ms'] is not None, run_ms=row['median_ms'])
if is_regression(current, baseline):
findings.append(dict(info, kind='regression'))
elif is_improvement(current, baseline):
findings.append(dict(info, kind='improvement'))
elif len(previous) + 1 >= TREND_RUNS:
# Newest first: [current, previous...]; compare the older half with the newer half.
values = [current] + [effective_ms(p) for p in previous[:TREND_RUNS - 1]]
newer = statistics.median(values[:TREND_RUNS // 2])
older = statistics.median(values[TREND_RUNS // 2:])
if newer >= older * TREND_RATIO and newer - older >= TREND_MIN_MS:
findings.append(dict(info, kind='trend', older_ms=older, newer_ms=newer))
if phase == 'hot' and current >= SLOW_MS:
findings.append(dict(base, kind='slow', ms=current))
return findings
def needs_recheck(findings: List[dict]) -> List[dict]:
"""Hot regressions measured from a single run's median; re-time them before believing them. Cold
regressions cannot be rechecked without another restart, so they are reported as single samples."""
return [f for f in findings if f['kind'] == 'regression' and f['phase'] == 'hot' and not f.get('rechecked')]
def suspect_paths(name: str) -> List[str]:
best = ''
for prefix in SUSPECT_PATHS:
if name.startswith(prefix) and len(prefix) > len(best):
best = prefix
return SUSPECT_PATHS.get(best, []) + COMMON_SUSPECT_PATHS
def suspect_commits(repo: Path, old: Optional[str], new: Optional[str], name: str) -> Optional[List[str]]:
"""Commits between the baseline's and this run's commit touching code related to the endpoint.
None when the range is unknown (no commits recorded, or the commits are not in the local clone)."""
if not old or not new or old == new:
return None
try:
proc = subprocess.run(
['git', '-C', str(repo), 'log', '--oneline', '--no-decorate', f'{old}..{new}', '--',
*suspect_paths(name)], capture_output=True, text=True, timeout=30)
except (OSError, subprocess.TimeoutExpired):
return None
if proc.returncode != 0:
return None
return [line for line in proc.stdout.splitlines() if line.strip()]
# ----------------------------------------------------------------------------------------------
# Reports
# ----------------------------------------------------------------------------------------------
def fmt_ms(value: Optional[float]) -> str:
return '-' if value is None else f'{value:,.0f} ms'
def fmt_bytes(value) -> str:
value = value or 0
for unit in ('B', 'KB', 'MB', 'GB'):
if value < 1024 or unit == 'GB':
return f'{value:,.0f} {unit}'
value /= 1024
def report(conn, run_id: int, repo: Optional[Path] = None) -> str:
run = conn.execute('SELECT * FROM run WHERE id = ?', (run_id,)).fetchone()
findings = evaluate(conn, run_id)
lines = [f'== {run["host"]} run {run_id} {run["started_at"]} {"cold" if run["cold"] else "hot"}'
f' version {run["version"] or "?"} commit {run["git_commit"] or "?"}']
if run['busy']:
lines.append(f' ! host was busy ({run["busy_reason"]}): this run is not used as a baseline')
previous = conn.execute('SELECT * FROM run WHERE host = ? AND started_at < ? AND busy = 0'
' ORDER BY started_at DESC LIMIT 1', (run['host'], run['started_at'])).fetchone()
if previous:
growth = []
for key in ('db_size', 'file_count', 'video_count', 'archive_count'):
if previous[key] and run[key] and previous[key] != run[key]:
growth.append(f'{key} {previous[key]:,} -> {run[key]:,}')
if growth:
lines.append(' library changed since the previous run: ' + ', '.join(growth))
def section(kind, title, render):
items = [f for f in findings if f['kind'] == kind]
if items:
lines.append(f'\n-- {title} ({len(items)})')
lines.extend(render(f) for f in items)
def render_change(f):
ratio = f['ms'] / f['baseline_ms'] if f['baseline_ms'] else 0
text = (f' {f["name"]} [{f["phase"]}] {fmt_ms(f["baseline_ms"])} -> {fmt_ms(f["ms"])}'
f' ({ratio:.1f}x, baseline of {f["baseline_runs"]} runs)')
if f.get('rechecked'):
text += f' confirmed by recheck (run median {fmt_ms(f["run_ms"])})'
elif f['kind'] == 'regression' and f['phase'] != 'hot':
text += ' single cold sample, re-run cold to confirm'
if f['baseline_bytes'] and f['bytes'] and f['bytes'] > f['baseline_bytes'] * 1.5:
text += f' response grew {fmt_bytes(f["baseline_bytes"])} -> {fmt_bytes(f["bytes"])}'
if f['kind'] == 'regression' and repo:
commits = suspect_commits(repo, f['baseline_commit'], run['git_commit'], f['name'])
if commits:
text += '\n' + '\n'.join(f' suspect {c}' for c in commits[:10])
if len(commits) > 10:
text += f'\n ... {len(commits) - 10} more'
elif commits is None and f['baseline_commit'] and f['baseline_commit'] != run['git_commit']:
text += f'\n commits {f["baseline_commit"]}..{run["git_commit"]} (not in the local clone?)'
elif not f['baseline_commit'] or not run['git_commit']:
text += '\n no commit recorded for the baseline or this run (imported history?)'
elif f['baseline_commit'] == run['git_commit']:
text += '\n same commit as baseline: data growth, host load, or environment'
return text
section('regression', 'REGRESSIONS', render_change)
section('trend', 'slow drift', lambda f: f' {f["name"]} [{f["phase"]}] older half {fmt_ms(f["older_ms"])}'
f' -> newer half {fmt_ms(f["newer_ms"])} over {TREND_RUNS} runs')
errors = [f for f in findings if f['kind'] == 'error']
if len(errors) > 10:
statuses = sorted({s for f in errors for s in f['status'].split(',')})
lines.append(f'\n-- errors ({len(errors)} endpoints, statuses {",".join(statuses)}); first few:')
lines.extend(f' {f["name"]} [{f["phase"]}] status {f["status"]}' for f in errors[:5])
else:
section('error', 'errors', lambda f: f' {f["name"]} [{f["phase"]}] status {f["status"]}'
f' ({f["errors"]}/{f["n"]} failed)')
section('slow', f'slow (hot >= {fmt_ms(SLOW_MS)})', lambda f: f' {f["name"]} {fmt_ms(f["ms"])}')
section('improvement', 'improvements', render_change)
new = [f for f in findings if f['kind'] == 'new']
if new:
lines.append(f'\n-- {len(new)} endpoint/phase pairs have no history yet')
if not any(f['kind'] in ('regression', 'trend', 'error', 'slow') for f in findings):
lines.append('\n-- no regressions')
return '\n'.join(lines)
def latest_run_id(conn, host: str) -> Optional[int]:
row = conn.execute('SELECT id FROM run WHERE host = ? ORDER BY started_at DESC LIMIT 1', (host,)).fetchone()
return row['id'] if row else None
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument('--data-dir', help='Where history.db lives (default $WROLPI_BENCH_DIR or'
' ~/.local/share/wrolpi-bench).')
sub = ap.add_subparsers(dest='command', required=True)
p = sub.add_parser('report', help='Findings for a run (default: newest run of --host).')
p.add_argument('--host')
p.add_argument('--run', type=int)
sub.add_parser('runs', help='List recorded runs.').add_argument('--host')
p = sub.add_parser('series', help='Time series of endpoints matching --name.')
p.add_argument('--host', required=True)
p.add_argument('--name', required=True)
p.add_argument('--phase', default='hot', choices=PHASES)
sub.add_parser('import', help='Import api_perf.py CSVs.').add_argument('csv', nargs='+', type=Path)
args = ap.parse_args()
conn = connect(data_dir(args.data_dir) / 'history.db')
repo = Path(__file__).resolve().parent.parent
if args.command == 'report':
run_id = args.run or (latest_run_id(conn, args.host) if args.host else None)
if not run_id:
ap.error('give --run, or a --host that has recorded runs')
print(report(conn, run_id, repo))
elif args.command == 'runs':
query = 'SELECT * FROM run' + (' WHERE host = ?' if args.host else '') + ' ORDER BY host, started_at'
for r in conn.execute(query, (args.host,) if args.host else ()):
print(f'{r["id"]:5} {r["host"]:10} {r["started_at"]:20} {r["source"]:6} {"cold" if r["cold"] else "hot ":4}'
f' {r["git_commit"] or "-":10} {r["version"] or "-":14} {"BUSY " + r["busy_reason"] if r["busy"] else ""}')
elif args.command == 'series':
rows = conn.execute(
'SELECT run.started_at, run.git_commit, run.busy, result.* FROM result JOIN run ON run.id = result.run_id'
' WHERE run.host = ? AND result.phase = ? AND result.name LIKE ? ORDER BY result.name, run.started_at',
(args.host, args.phase, f'%{args.name}%'))
for r in rows:
print(f'{r["name"]:42} {r["started_at"]:20} {r["git_commit"] or "-":10} {fmt_ms(effective_ms(r)):>12}'
f' {fmt_bytes(r["bytes"]):>10} {r["status"]:>5}{" busy" if r["busy"] else ""}')
elif args.command == 'import':
imported = 0
for path in sorted(args.csv):
run_id = import_csv(conn, path)
if run_id:
imported += 1
print(f'imported {path.name} as run {run_id}')
print(f'{imported} runs imported')
if __name__ == '__main__':
sys.exit(main())