From a61d528832ac951c33c5f255cf9489ba62a4d7c3 Mon Sep 17 00:00:00 2001 From: lrnselfreliance <33263708+lrnselfreliance@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:16:23 -0700 Subject: [PATCH] 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 * 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 --------- Co-authored-by: Claude Opus 5.5 --- scripts/api_perf.py | 167 ++++++++-- scripts/api_perf_compare.py | 6 +- scripts/api_perf_history.py | 501 ++++++++++++++++++++++++++++ scripts/api_perf_hosts.example.json | 3 +- wrolpi/test/test_api_perf.py | 251 ++++++++++++++ 5 files changed, 889 insertions(+), 39 deletions(-) create mode 100644 scripts/api_perf_history.py create mode 100644 wrolpi/test/test_api_perf.py diff --git a/scripts/api_perf.py b/scripts/api_perf.py index 67c74431..ae0f1a7e 100644 --- a/scripts/api_perf.py +++ b/scripts/api_perf.py @@ -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 /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/_.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 /runs/_.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: /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/ (static file), GET /api/upgrade/check (network), -# GET /api/ai/services//logs, GET /api/ai/files/read, GET /api/ai/help/, -# 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/': 'static file', + '/api/files/zip/download': 'streams a zip', + '/api/repos//archive.zip': 'streams a zip', + '/api/map/export//pdf': 'per-export file', + '/api/torrents//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/': 'per-job status', + '/api/files/jobs/': 'per-job status', + '/api/collections//reorganize/status/': 'per-job status', + '/api/collections/reorganize/batch/status/': 'per-job status', + '/api/collections//reorganize/preview': 'plans a reorganize, user-initiated', + '/api/collections//reorganize/conflicts': 'plans a reorganize, user-initiated', + '/api/inventory//backups': 'needs an inventory slug', + '/api/zim//entry/': 'proxies a Zim article', + '/api/map/quad': 'needs a bounding box', + '/api/map/species/here': 'needs coordinates', + '/api/map/species/': 'needs a taxon id', + '/api/map/species//range': 'needs a taxon id', + '/api/map/fallout/climatology': 'static data file', + '/api/map/fallout/climatology/': '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//comments', method='GET', path='/api/videos/{video_id}/comments', needs='video_id', page='video'), dict(name='videos//captions', method='GET', path='/api/videos/{video_id}/captions', needs='video_id'), + dict(name='videos//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/', method='GET', path='/api/ai/videos/{video_id}', needs='video_id'), - dict(name='ai/archives/', 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/', method='GET', path='/api/repos/{repo_id}', needs='repo_id', page='repo'), + dict(name='repos//tree', method='GET', path='/api/repos/{repo_id}/tree', needs='repo_id', page='repo'), + dict(name='repos//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}') diff --git a/scripts/api_perf_compare.py b/scripts/api_perf_compare.py index 411b66a9..c1452f71 100644 --- a/scripts/api_perf_compare.py +++ b/scripts/api_perf_compare.py @@ -2,9 +2,9 @@ """ Merge the CSVs written by scripts/api_perf.py into one cross-host table. - python3 scripts/api_perf_compare.py perf_results/*.csv - python3 scripts/api_perf_compare.py perf_results/*.csv --sort hot --top 25 - python3 scripts/api_perf_compare.py perf_results/*.csv --markdown > perf_results/summary.md + python3 scripts/api_perf_compare.py ~/.local/share/wrolpi-bench/runs/*.csv + python3 scripts/api_perf_compare.py ~/.local/share/wrolpi-bench/runs/*.csv --sort hot --top 25 + python3 scripts/api_perf_compare.py ~/.local/share/wrolpi-bench/runs/*.csv --markdown > summary.md For each endpoint and host prints cold (ms, first request after an API restart) and hot median (ms, over the hot passes). When several CSVs exist for the same host the newest one wins. diff --git a/scripts/api_perf_history.py b/scripts/api_perf_history.py new file mode 100644 index 00000000..f660199c --- /dev/null +++ b/scripts/api_perf_history.py @@ -0,0 +1,501 @@ +#!/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.+)_(?P\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()) diff --git a/scripts/api_perf_hosts.example.json b/scripts/api_perf_hosts.example.json index 81b70328..5713b9a1 100644 --- a/scripts/api_perf_hosts.example.json +++ b/scripts/api_perf_hosts.example.json @@ -24,6 +24,7 @@ "IdentitiesOnly=yes" ], "restart": "sudo -n systemctl stop wrolpi-api.service && sudo -n systemctl start wrolpi-api.service", - "drop_caches": null + "drop_caches": null, + "production": true } } diff --git a/wrolpi/test/test_api_perf.py b/wrolpi/test/test_api_perf.py new file mode 100644 index 00000000..c27a062b --- /dev/null +++ b/wrolpi/test/test_api_perf.py @@ -0,0 +1,251 @@ +"""Tests for the API benchmark scripts: scripts/api_perf.py (endpoint catalog) and scripts/api_perf_history.py +(history and regression detection). No requests are made; history is synthetic.""" +import importlib +import re +import sys + +import pytest + +from wrolpi.api_utils import api_app +from wrolpi.vars import PROJECT_DIR + +sys.path.insert(0, str(PROJECT_DIR / 'scripts')) +api_perf = importlib.import_module('api_perf') +api_perf_history = importlib.import_module('api_perf_history') + +PARAM = re.compile(r'<[^>]+>|{[^}]+}') + + +def shape(path: str) -> str: + """'/api/videos/{video_id}?x=1' and 'api/videos/' both become '/api/videos/*'.""" + path = path.split('?', 1)[0] + path = PARAM.sub('*', path) + return '/' + path.strip('/') + + +def routes(): + """(method, shape) of every /api route. Others (sanic-ext's /docs, registered once the app has started in + an earlier test) are not part of what the benchmark covers.""" + found = set() + for route in api_app.router.routes: + path = shape(route.path) + if path != '/api' and not path.startswith('/api/'): + continue + for method in route.methods: + found.add((method, path)) + return found + + +def test_catalog_covers_get_routes(): + """Every GET route is timed or deliberately excluded, so new endpoints are not silently left out.""" + covered = {shape(e['path']) for e in api_perf.CATALOG if e['method'] == 'GET'} + covered |= {shape(p) for p in api_perf.EXCLUDED} + missing = sorted(path for method, path in routes() if method == 'GET' and path not in covered) + assert not missing, f'Add these GET routes to CATALOG or EXCLUDED in scripts/api_perf.py: {missing}' + + +def test_catalog_entries_exist(): + """Every catalog entry and exclusion names a route the API still serves.""" + served = routes() + stale = [(e['method'], e['path']) for e in api_perf.CATALOG if (e['method'], shape(e['path'])) not in served] + assert not stale, f'CATALOG entries for routes that no longer exist: {stale}' + served_paths = {path for _, path in served} + stale = [p for p in api_perf.EXCLUDED if shape(p) not in served_paths] + assert not stale, f'EXCLUDED entries for routes that no longer exist: {stale}' + + +def test_catalog_needs_are_discovered(): + """Every id a catalog entry needs is discovered at runtime (or the entry would always be skipped).""" + source = (PROJECT_DIR / 'scripts/api_perf.py').read_text() + discovered = set(re.findall(r"probe\('(\w+)'", source)) + needs = {e['needs'] for e in api_perf.CATALOG if e.get('needs')} + assert needs <= discovered, f'Not discovered: {needs - discovered}' + + +# ---------------------------------------------------------------------------------------------- +# History +# ---------------------------------------------------------------------------------------------- + +@pytest.fixture +def history(tmp_path): + conn = api_perf_history.connect(tmp_path / 'history.db') + yield conn + conn.close() + + +def rows_for(timings: dict, phase='hot', passes=3, status=200, size=1000): + """CSV-like rows: every endpoint answers in the given ms on every pass.""" + rows = [] + for name, ms in timings.items(): + for i in range(passes): + rows.append(dict(name=name, phase=phase, method='GET', path=f'/api/{name}', ms=ms, status=status, + bytes=size, **{'pass': i + 1})) + return rows + + +def record(conn, day: int, timings: dict, commit='aaaa', busy=False, **kwargs) -> int: + context = dict(git_commit=commit, busy=busy, busy_reason='downloads' if busy else None) + return api_perf_history.record_run(conn, 'host', f'2026-01-{day:02d}T00:00:00', rows_for(timings, **kwargs), + context) + + +def kinds(conn, run_id, name='a'): + return {f['kind'] for f in api_perf_history.evaluate(conn, run_id) if f['name'] == name} + + +def test_first_run_has_no_baseline(history): + run_id = record(history, 1, {'a': 50}) + assert kinds(history, run_id) == {'new'} + + +def test_regression_needs_ratio_and_absolute_increase(history): + for day in range(1, 6): + record(history, day, {'a': 200, 'b': 10}) + # a: 200 -> 300 is +100 ms and 1.5x; b: 10 -> 90 is 9x but only +80 ms. + run_id = record(history, 6, {'a': 300, 'b': 90}) + assert kinds(history, run_id, 'a') == {'regression'} + assert kinds(history, run_id, 'b') == set() + + +def test_below_ratio_is_not_a_regression(history): + for day in range(1, 6): + record(history, day, {'a': 1000}) + run_id = record(history, 6, {'a': 1400}) # +400 ms but only 1.4x + assert 'regression' not in kinds(history, run_id) + + +def test_improvement(history): + for day in range(1, 6): + record(history, day, {'a': 900}) + run_id = record(history, 6, {'a': 300}) + assert kinds(history, run_id) == {'improvement'} + + +def test_baseline_is_median_of_recent_runs(history): + """One noisy earlier run does not move the baseline; runs older than BASELINE_RUNS are ignored.""" + record(history, 1, {'a': 5000}) # older than the baseline window + for day, ms in zip(range(2, 7), [200, 200, 2000, 200, 200]): + record(history, day, {'a': ms}) + run_id = record(history, 7, {'a': 320}) + [finding] = [f for f in api_perf_history.evaluate(history, run_id) if f['kind'] == 'regression'] + assert finding['baseline_ms'] == 200 + assert finding['baseline_runs'] == api_perf_history.BASELINE_RUNS + + +def test_busy_runs_are_not_baselines(history): + for day in range(1, 6): + record(history, day, {'a': 200}) + record(history, 6, {'a': 5000}, busy=True) + run_id = record(history, 7, {'a': 210}) + assert kinds(history, run_id) == set() + + +def test_phases_have_separate_baselines(history): + """A cold request is compared with earlier cold requests, never with hot ones.""" + for day in range(1, 6): + record(history, day, {'a': 100}) + run_id = record(history, 6, {'a': 3000}, phase='cold', passes=1) + assert kinds(history, run_id) == {'new'} + + +def test_errors_are_reported_and_not_baselines(history): + for day in range(1, 6): + record(history, day, {'a': 200}) + run_id = record(history, 6, {'a': 30}, status=500) + assert kinds(history, run_id) == {'error'} + run_id = record(history, 7, {'a': 210}) + assert kinds(history, run_id) == set() + + +def test_recheck_overrides_run_median(history): + """A hot regression that does not survive the recheck is not reported.""" + for day in range(1, 6): + record(history, day, {'a': 200}) + run_id = record(history, 6, {'a': 900}) + findings = api_perf_history.evaluate(history, run_id) + assert [f['name'] for f in api_perf_history.needs_recheck(findings)] == ['a'] + + api_perf_history.set_recheck(history, run_id, 'a', 'hot', 210) + assert kinds(history, run_id) == set() + + api_perf_history.set_recheck(history, run_id, 'a', 'hot', 800) + [finding] = api_perf_history.evaluate(history, run_id) + assert finding['kind'] == 'regression' and finding['rechecked'] + assert not api_perf_history.needs_recheck([finding]) + + +def test_cold_regressions_are_not_rechecked(history): + for day in range(1, 6): + record(history, day, {'a': 200}, phase='cold', passes=1) + run_id = record(history, 6, {'a': 900}, phase='cold', passes=1) + findings = api_perf_history.evaluate(history, run_id) + assert [f['kind'] for f in findings] == ['regression'] + assert api_perf_history.needs_recheck(findings) == [] + + +def test_slow_drift_is_reported_as_trend(history): + """Each run is only a little slower than the last, so no single run regresses, but the drift shows.""" + for day, ms in enumerate([200, 205, 210, 215, 220, 260, 270, 280, 290], start=1): + record(history, day, {'a': ms}) + run_id = record(history, 10, {'a': 300}) + assert kinds(history, run_id) == {'trend'} + + +def test_slow_endpoint_without_history(history): + run_id = record(history, 1, {'a': api_perf_history.SLOW_MS + 1}) + assert kinds(history, run_id) == {'new', 'slow'} + + +def test_context_from_api_marks_busy(): + status = dict(version='1.0\n', current_commit='abc', downloads=dict(pending=3, stopped=False, disabled=False)) + stats = dict(file_statistics=dict(total_count=10, video_count=2), global_statistics=dict(db_size=4096)) + context = api_perf_history.context_from_api(status, stats, load=dict(minute_1='0.5'), cpu=dict(cores=4)) + assert context['version'] == '1.0' and context['git_commit'] == 'abc' + assert context['busy'] and 'downloads' in context['busy_reason'] + assert (context['file_count'], context['video_count'], context['db_size']) == (10, 2, 4096) + + status['downloads']['stopped'] = True + context = api_perf_history.context_from_api(status, stats, load=dict(minute_1='9.5'), cpu=dict(cores=4)) + assert context['busy'] and 'load' in context['busy_reason'] + + context = api_perf_history.context_from_api(status, None, load=None, cpu=None) + assert not context['busy'] and context['file_count'] is None + + +def test_unavailable_api_marks_run_busy(history): + """Requests redirected to the fallback UI (the API was down) make the run untrustworthy.""" + rows = rows_for({'a': 10, 'b': 10}) + assert not api_perf_history.mark_unavailable({}, rows).get('busy') + rows[0]['status'] = 503 # one endpoint timed out; the API was up + assert not api_perf_history.mark_unavailable({}, rows).get('busy') + rows[-1]['status'] = 302 + context = api_perf_history.mark_unavailable(dict(busy=True, busy_reason='load 9 > 4 cores'), rows) + assert context['busy'] and context['busy_reason'] == 'load 9 > 4 cores; API unavailable for 1 of 6 requests' + + +def test_import_csv(history, tmp_path): + csv_path = tmp_path / 'somehost_20260101_120000.csv' + csv_path.write_text( + 'host,phase,pass,name,method,path,ms,status,bytes,error,dropped_caches,ready_seconds\n' + 'somehost,cold,0,a,GET,/api/a,900.0,200,10,,False,5\n' + 'somehost,hot,1,a,GET,/api/a,100.0,200,10,,,\n' + 'somehost,hot,2,a,GET,/api/a,120.0,200,10,,,\n' + 'somehost,hot,3,a,GET,/api/a,110.0,HTML,10,non-JSON 200,,\n' + ) + run_id = api_perf_history.import_csv(history, csv_path) + run = history.execute('SELECT * FROM run WHERE id = ?', (run_id,)).fetchone() + assert (run['host'], run['started_at'], run['cold'], run['source']) == \ + ('somehost', '2026-01-01T12:00:00', 1, 'import') + hot = history.execute("SELECT * FROM result WHERE run_id = ? AND phase = 'hot'", (run_id,)).fetchone() + assert (hot['n'], hot['median_ms'], hot['errors']) == (3, 110.0, 1) + + assert api_perf_history.import_csv(history, csv_path) is None, 'imported twice' + other = tmp_path / 'notes.csv' + other.write_text('a,b\n1,2\n') + assert api_perf_history.import_csv(history, other) is None + + +def test_suspect_paths(): + assert 'modules/videos' in api_perf_history.suspect_paths('videos/search (page 1, newest)') + assert 'wrolpi/files' in api_perf_history.suspect_paths('files/search (query)') + assert 'wrolpi/db.py' in api_perf_history.suspect_paths('unknown')