mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-12-03 21:29:59 -05:00
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>
This commit is contained in:
parent
ffba963639
commit
a61d528832
5 changed files with 889 additions and 39 deletions
|
|
@ -8,7 +8,7 @@ page, for example, is rendered from `POST /api/videos/search`).
|
|||
|
||||
Usage examples:
|
||||
|
||||
# Hot only (no SSH needed), 3 passes, against a host profile from scripts/api_perf_hosts.json
|
||||
# Hot only (no SSH needed), 3 passes, against a host profile from <data dir>/hosts.json
|
||||
# (copy scripts/api_perf_hosts.example.json to create it).
|
||||
python3 scripts/api_perf.py --host docker
|
||||
|
||||
|
|
@ -21,8 +21,14 @@ Usage examples:
|
|||
# Ad-hoc host.
|
||||
python3 scripts/api_perf.py --url https://192.0.2.10:8443
|
||||
|
||||
Results are written as CSV to ./perf_results/<host>_<timestamp>.csv, one row per request, and a
|
||||
summary table is printed at the end. Only the standard library is used so this runs anywhere.
|
||||
# Record the run in the history and report endpoints that got slower than their own baseline
|
||||
# (see scripts/api_perf_history.py).
|
||||
python3 scripts/api_perf.py --host docker --record
|
||||
|
||||
Results are written as CSV to <data dir>/runs/<host>_<timestamp>.csv, one row per request, and a
|
||||
summary table is printed at the end. The data dir is outside the repository so results are never
|
||||
committed: --data-dir, $WROLPI_BENCH_DIR, or ~/.local/share/wrolpi-bench. Only the standard library is
|
||||
used so this runs anywhere.
|
||||
"""
|
||||
import argparse
|
||||
import csv
|
||||
|
|
@ -40,18 +46,23 @@ import urllib.request
|
|||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
import api_perf_history
|
||||
|
||||
# ----------------------------------------------------------------------------------------------
|
||||
# Hosts
|
||||
# ----------------------------------------------------------------------------------------------
|
||||
|
||||
HOSTS_FILE = Path(__file__).with_name('api_perf_hosts.json') # gitignored; see api_perf_hosts.example.json
|
||||
# Host profiles hold LAN addresses and usernames, so they are never committed. The first of these that
|
||||
# exists is used: <data dir>/hosts.json (works from any checkout or worktree), then scripts/api_perf_hosts.json
|
||||
# (gitignored). See api_perf_hosts.example.json for the format.
|
||||
HOSTS_FILES = [api_perf_history.data_dir() / 'hosts.json', Path(__file__).with_name('api_perf_hosts.json')]
|
||||
HOSTS_FILE = next((p for p in HOSTS_FILES if p.exists()), HOSTS_FILES[0])
|
||||
|
||||
|
||||
def load_hosts() -> dict:
|
||||
"""Host profiles live in a gitignored JSON file so LAN addresses/usernames stay out of the repo.
|
||||
|
||||
Each profile: url, ssh (user@host or null), ssh_opts (list), restart (shell command run over
|
||||
ssh), drop_caches (shell command or null when the ssh user cannot do it)."""
|
||||
"""Each profile: url, ssh (user@host or null), ssh_opts (list), restart (shell command run over
|
||||
ssh), drop_caches (shell command or null when the ssh user cannot do it), and optionally
|
||||
production (true: --cold also needs --restart-production)."""
|
||||
if not HOSTS_FILE.exists():
|
||||
return {}
|
||||
return json.loads(HOSTS_FILE.read_text())
|
||||
|
|
@ -66,11 +77,39 @@ HOSTS = load_hosts()
|
|||
# load; used for grouping and for --cold-each), optional `needs` (an id discovered at runtime,
|
||||
# substituted into the path as {video_id}, etc.).
|
||||
#
|
||||
# Deliberately excluded (read-only but not useful to time, or slow by design):
|
||||
# GET /api/events/feed (long-poll), GET /api/files/zip/download (streams a zip),
|
||||
# GET /api/extensions/<filename> (static file), GET /api/upgrade/check (network),
|
||||
# GET /api/ai/services/<name>/logs, GET /api/ai/files/read, GET /api/ai/help/<slug>,
|
||||
# GET /api/echo (used as the readiness probe instead).
|
||||
# Every read-only route must be in CATALOG or in EXCLUDED; wrolpi/test/test_api_perf.py fails when a new GET
|
||||
# route is in neither, so new endpoints get timed (or a reason not to).
|
||||
|
||||
EXCLUDED = {
|
||||
'/api': 'not part of the API',
|
||||
'/api/echo': 'readiness probe',
|
||||
'/api/events/feed': 'long-poll',
|
||||
'/api/extensions/<filename:str>': 'static file',
|
||||
'/api/files/zip/download': 'streams a zip',
|
||||
'/api/repos/<repo_id:int>/archive.zip': 'streams a zip',
|
||||
'/api/map/export/<export_id:str>/pdf': 'per-export file',
|
||||
'/api/torrents/<hash_:str>/torrent': 'per-torrent file',
|
||||
'/api/archive/upload': 'upload endpoint',
|
||||
'/api/upgrade/check': 'contacts the git remote',
|
||||
'/api/sync/test': 'contacts the primary WROLPi',
|
||||
'/api/speedtest/download': 'throughput test, slow by design',
|
||||
'/api/speedtest/ping': 'latency test',
|
||||
'/api/db/schema': 'opt-in, forbidden by default',
|
||||
'/api/jobs/<job_id:str>': 'per-job status',
|
||||
'/api/files/jobs/<job_id:str>': 'per-job status',
|
||||
'/api/collections/<collection_id:int>/reorganize/status/<job_id:str>': 'per-job status',
|
||||
'/api/collections/reorganize/batch/status/<batch_job_id:str>': 'per-job status',
|
||||
'/api/collections/<collection_id:int>/reorganize/preview': 'plans a reorganize, user-initiated',
|
||||
'/api/collections/<collection_id:int>/reorganize/conflicts': 'plans a reorganize, user-initiated',
|
||||
'/api/inventory/<slug:str>/backups': 'needs an inventory slug',
|
||||
'/api/zim/<zim_id:[0-9]+>/entry/<zim_path:[ -~/]*>': 'proxies a Zim article',
|
||||
'/api/map/quad': 'needs a bounding box',
|
||||
'/api/map/species/here': 'needs coordinates',
|
||||
'/api/map/species/<taxon_id:int>': 'needs a taxon id',
|
||||
'/api/map/species/<taxon_id:int>/range': 'needs a taxon id',
|
||||
'/api/map/fallout/climatology': 'static data file',
|
||||
'/api/map/fallout/climatology/<month:int>': 'static data file',
|
||||
}
|
||||
|
||||
CATALOG = [
|
||||
# --- root ---
|
||||
|
|
@ -92,7 +131,7 @@ CATALOG = [
|
|||
|
||||
# --- config ---
|
||||
dict(name='config', method='GET', path='/api/config/'),
|
||||
dict(name='config/backups', method='GET', path='/api/config/backups'),
|
||||
dict(name='config/backups', method='GET', path='/api/config/backups?file_name=tags.yaml'),
|
||||
|
||||
# --- files ---
|
||||
dict(name='files/worker_status', method='GET', path='/api/files/worker_status'),
|
||||
|
|
@ -146,6 +185,7 @@ CATALOG = [
|
|||
dict(name='videos/<id>/comments', method='GET', path='/api/videos/{video_id}/comments', needs='video_id',
|
||||
page='video'),
|
||||
dict(name='videos/<id>/captions', method='GET', path='/api/videos/{video_id}/captions', needs='video_id'),
|
||||
dict(name='videos/<id>/description', method='GET', path='/api/videos/{video_id}/description', needs='video_id'),
|
||||
|
||||
# --- archive ---
|
||||
dict(name='archive/statistics', method='GET', path='/api/archive/statistics', page='archives-stats'),
|
||||
|
|
@ -180,6 +220,11 @@ CATALOG = [
|
|||
dict(name='map/search', method='GET', path='/api/map/search?q={q}&limit=20&offset=0'),
|
||||
dict(name='map/search/estimate', method='GET', path='/api/map/search/estimate?q={q}'),
|
||||
dict(name='map/search/status', method='GET', path='/api/map/search/status'),
|
||||
dict(name='map/weather', method='GET', path='/api/map/weather', page='map'),
|
||||
dict(name='map/nuclear/targets', method='GET', path='/api/map/nuclear/targets'),
|
||||
dict(name='map/fallout/winds/latest', method='GET', path='/api/map/fallout/winds/latest'),
|
||||
dict(name='map/species/subscribe', method='GET', path='/api/map/species/subscribe'),
|
||||
dict(name='map/species (query)', method='GET', path='/api/map/species?q={q}'),
|
||||
|
||||
# --- inventory ---
|
||||
dict(name='inventory', method='GET', path='/api/inventory/', page='inventory'),
|
||||
|
|
@ -189,23 +234,20 @@ CATALOG = [
|
|||
dict(name='flasher/configs', method='GET', path='/api/flasher/configs'),
|
||||
dict(name='flasher/search', method='POST', path='/api/flasher/search', body={}),
|
||||
|
||||
# --- ai (MCP-facing read endpoints) ---
|
||||
dict(name='ai/status', method='GET', path='/api/ai/status'),
|
||||
dict(name='ai/services', method='GET', path='/api/ai/services'),
|
||||
dict(name='ai/disks', method='GET', path='/api/ai/disks'),
|
||||
dict(name='ai/manage/catalog', method='GET', path='/api/ai/manage/catalog'),
|
||||
dict(name='ai/collections', method='GET', path='/api/ai/collections'),
|
||||
dict(name='ai/inventories', method='GET', path='/api/ai/inventories'),
|
||||
dict(name='ai/zims', method='GET', path='/api/ai/zims'),
|
||||
dict(name='ai/search', method='POST', path='/api/ai/search', body={'search_str': '{q}', 'limit': 5}),
|
||||
dict(name='ai/videos/search', method='POST', path='/api/ai/videos/search', body={'search_str': '{q}', 'limit': 5}),
|
||||
dict(name='ai/archives/search', method='POST', path='/api/ai/archives/search',
|
||||
body={'search_str': '{q}', 'limit': 5}),
|
||||
dict(name='ai/docs/search', method='POST', path='/api/ai/docs/search', body={'search_str': '{q}', 'limit': 5}),
|
||||
dict(name='ai/zims/search', method='POST', path='/api/ai/zims/search', body={'search_str': '{q}', 'limit': 5}),
|
||||
dict(name='ai/videos/<id>', method='GET', path='/api/ai/videos/{video_id}', needs='video_id'),
|
||||
dict(name='ai/archives/<id>', method='GET', path='/api/ai/archives/{archive_id}', needs='archive_id'),
|
||||
dict(name='chat/modes', method='GET', path='/api/chat/modes'),
|
||||
# --- repos ---
|
||||
dict(name='repos', method='GET', path='/api/repos/', page='repos'),
|
||||
dict(name='repos/search', method='POST', path='/api/repos/search', body={'search_str': '{q}'}),
|
||||
dict(name='repos/<id>', method='GET', path='/api/repos/{repo_id}', needs='repo_id', page='repo'),
|
||||
dict(name='repos/<id>/tree', method='GET', path='/api/repos/{repo_id}/tree', needs='repo_id', page='repo'),
|
||||
dict(name='repos/<id>/log', method='GET', path='/api/repos/{repo_id}/log', needs='repo_id'),
|
||||
|
||||
# --- misc ---
|
||||
dict(name='bookmarks', method='GET', path='/api/bookmarks/', page='app'),
|
||||
dict(name='jobs', method='GET', path='/api/jobs/'),
|
||||
dict(name='torrents', method='GET', path='/api/torrents/', page='torrents'),
|
||||
dict(name='sync/info', method='GET', path='/api/sync/info'),
|
||||
dict(name='sync/status', method='GET', path='/api/sync/status'),
|
||||
dict(name='speedtest/info', method='GET', path='/api/speedtest/info'),
|
||||
]
|
||||
|
||||
# Endpoints that get their own restart when --cold-each is used: what a user hits when they open
|
||||
|
|
@ -275,6 +317,18 @@ def request(base_url: str, method: str, path: str, body=None, timeout: float = 1
|
|||
return dict(ms=round(elapsed * 1000, 1), status=status, bytes=size, error=error, payload=payload)
|
||||
|
||||
|
||||
def get_json(base_url: str, path: str) -> Optional[dict]:
|
||||
"""GET a JSON object, or None if the request fails (context for the history is best-effort)."""
|
||||
r = request(base_url, 'GET', path, timeout=60)
|
||||
if r['status'] != 200:
|
||||
return None
|
||||
try:
|
||||
data = json.loads(r['payload'])
|
||||
except ValueError:
|
||||
return None
|
||||
return data if isinstance(data, dict) else None
|
||||
|
||||
|
||||
def wait_ready(base_url: str, timeout: float = 300.0) -> float:
|
||||
"""Poll /api/echo until it answers 200. Returns seconds waited."""
|
||||
start = time.perf_counter()
|
||||
|
|
@ -352,6 +406,7 @@ def discover_ids(base_url: str, log) -> dict:
|
|||
probe('doc_id', 'POST', '/api/docs/search', {'limit': 1}, 'file_groups')
|
||||
probe('channel_id', 'GET', '/api/videos/channels', None, 'channels')
|
||||
probe('collection_id', 'GET', '/api/collections/', None, 'collections')
|
||||
probe('repo_id', 'GET', '/api/repos/', None, 'repos')
|
||||
log(f' discovered ids: {ids}')
|
||||
return ids
|
||||
|
||||
|
|
@ -383,7 +438,7 @@ def resolve(entry: dict, ids: dict) -> Optional[dict]:
|
|||
def main():
|
||||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
g = ap.add_mutually_exclusive_group(required=True)
|
||||
g.add_argument('--host', choices=sorted(HOSTS), help=f'A host profile from {HOSTS_FILE.name}.')
|
||||
g.add_argument('--host', choices=sorted(HOSTS), help=f'A host profile from {HOSTS_FILE}.')
|
||||
g.add_argument('--url', help='Ad-hoc base URL, e.g. https://192.0.2.10:8443 (hot only unless --ssh given).')
|
||||
ap.add_argument('--cold', action='store_true', help='Restart the API over SSH, run one cold pass first.')
|
||||
ap.add_argument('--cold-each', action='store_true',
|
||||
|
|
@ -393,7 +448,14 @@ def main():
|
|||
help='Search term substituted for {q} in the catalog (default "solar"; "the" rows are fixed worst-case).')
|
||||
ap.add_argument('--only', help='Substring filter on endpoint names.')
|
||||
ap.add_argument('--timeout', type=float, default=180.0, help='Per-request timeout in seconds.')
|
||||
ap.add_argument('--out-dir', default='perf_results')
|
||||
ap.add_argument('--restart-production', action='store_true',
|
||||
help='Allow --cold on a host profile marked "production": true (it restarts the API users rely on).')
|
||||
ap.add_argument('--record', action='store_true',
|
||||
help='Save the run to the history and report regressions against earlier runs of this host.')
|
||||
ap.add_argument('--recheck', type=int, default=5,
|
||||
help='With --record, re-time each hot regression this many times before reporting it (default 5).')
|
||||
ap.add_argument('--data-dir', help='History and run output (default $WROLPI_BENCH_DIR or'
|
||||
' ~/.local/share/wrolpi-bench). Keep this outside the repository.')
|
||||
args = ap.parse_args()
|
||||
|
||||
if args.host:
|
||||
|
|
@ -403,11 +465,15 @@ def main():
|
|||
ssh=None, ssh_opts=[], restart=None, drop_caches=None)
|
||||
if args.cold and not host.get('ssh'):
|
||||
ap.error('--cold requires a --host profile with SSH access')
|
||||
if args.cold and host.get('production') and not args.restart_production:
|
||||
ap.error(f'{host["name"]} is a production host; --cold restarts its API. Add --restart-production to do it anyway.')
|
||||
host.setdefault('ssh_opts', [])
|
||||
|
||||
base = host['url']
|
||||
stamp = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
|
||||
out_dir = Path(args.out_dir)
|
||||
started = datetime.datetime.now()
|
||||
stamp = started.strftime('%Y%m%d_%H%M%S')
|
||||
data_dir = api_perf_history.data_dir(args.data_dir)
|
||||
out_dir = data_dir / 'runs'
|
||||
out_dir.mkdir(exist_ok=True)
|
||||
out_csv = out_dir / f'{host["name"]}_{stamp}.csv'
|
||||
log_path = out_dir / f'{host["name"]}_{stamp}.log'
|
||||
|
|
@ -421,6 +487,11 @@ def main():
|
|||
log(f'== WROLPi API perf: {host["name"]} ({base}) at {stamp}')
|
||||
ready = wait_ready(base, timeout=30)
|
||||
log(f' reachable (echo answered after {ready}s)')
|
||||
# Taken before the passes: load caused by this benchmark must not mark the host busy.
|
||||
# /api/statistics is fetched after the passes so it cannot warm anything a cold pass measures.
|
||||
status = get_json(base, '/api/status')
|
||||
load = get_json(base, '/controller/api/stats/load')
|
||||
cpu = get_json(base, '/controller/api/stats/cpu')
|
||||
|
||||
ids = discover_ids(base, log)
|
||||
ids['q'] = args.query
|
||||
|
|
@ -522,6 +593,32 @@ def main():
|
|||
cold_txt = f'cold max {max(cd):7.0f} sum {sum(cd):7.0f}' if cd else ''
|
||||
log(f' {page:16} {hot_txt} {cold_txt} ({len(names)} calls)')
|
||||
|
||||
if args.record:
|
||||
stats = get_json(base, '/api/statistics')
|
||||
context = api_perf_history.context_from_api(status, stats, load, cpu)
|
||||
api_perf_history.mark_unavailable(context, rows)
|
||||
conn = api_perf_history.connect(data_dir / 'history.db')
|
||||
run_id = api_perf_history.record_run(
|
||||
conn, host['name'], started.isoformat(timespec='seconds'), rows, context, cold=args.cold,
|
||||
query=args.query, extra_context=dict(hot_passes=args.hot_passes, only=args.only,
|
||||
cold_each=args.cold_each, csv=out_csv.name))
|
||||
by_name = {e['name']: e for e in catalog}
|
||||
suspects = api_perf_history.needs_recheck(api_perf_history.evaluate(conn, run_id))
|
||||
if suspects and args.recheck > 0:
|
||||
log(f'\n-- rechecking {len(suspects)} possible regressions ({args.recheck} requests each)')
|
||||
for finding in suspects:
|
||||
e = by_name[finding['name']]
|
||||
times = []
|
||||
for _ in range(args.recheck):
|
||||
r = request(base, e['method'], e['path'], e.get('body'), timeout=args.timeout)
|
||||
if r['status'] == 200:
|
||||
times.append(r['ms'])
|
||||
recheck_ms = statistics.median(times) if times else None
|
||||
api_perf_history.set_recheck(conn, run_id, finding['name'], 'hot', recheck_ms)
|
||||
log(f' {finding["name"]}: run median {finding["ms"]:.0f} ms, recheck median '
|
||||
f'{"failed" if recheck_ms is None else f"{recheck_ms:.0f} ms"}')
|
||||
log('\n' + api_perf_history.report(conn, run_id, Path(__file__).resolve().parent.parent))
|
||||
|
||||
log(f'\nrows: {out_csv}\nlog: {log_path}')
|
||||
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue