From 465224dd15bd3a8a7aa32ba1ff7294964b2abbd9 Mon Sep 17 00:00:00 2001 From: GordonYuanyc Date: Thu, 3 Dec 2026 05:59:18 +0000 Subject: [PATCH] System leaderboard: compare within a query set, declared by the data; open local results The leaderboard now compares systems only inside a query set: one-shot or periodic, then a set of queries (ClickBench hits, each use case, a PromQL spec), then its participants. What is compared with what comes from the data, not from rules in the page or the converter. - Each result directory carries leaderboard.json: display names, and per query set its queries, the truth, and each participant's mode (exact or approximate), the participant it is compared with, and any measurements awaiting a rerun. one-shot-workload.sh and run_use_case_on_systems.py write it; scripts/leaderboard_catalog.py writes it for saved results and marks pending measurements. - system-leaderboard-data.py takes each record's mode and reference from its query set, leaves pending measurements out, reads --spec summaries, per-query latency, the CPU split and per-query one-shot CPU, and writes catalog.json beside the records. - The page: query sets by kind; per query set the participants, exact participants on the queries all of them answered, each approximate participant against its reference, an error-against-time chart, any two participants on the queries both answered, and a per-query table. The cross-query-set pages are gone. - Open local results reads records and catalog files in the browser only, so results that must stay private can be shown without publishing them. Co-Authored-By: Claude Opus 5.5 --- scripts/leaderboard-catalog-clickbench.json | 33 + scripts/leaderboard-catalog.json | 53 ++ scripts/leaderboard-data.sh | 43 +- scripts/leaderboard_catalog.py | 343 ++++++++++ scripts/one-shot-clickbench.sh | 1 + scripts/one-shot-workload.sh | 17 + scripts/system-leaderboard-data.py | 357 ++++++++-- scripts/test_system_leaderboard_data.py | 263 +++++++ scripts/use_cases/run_use_case_on_systems.py | 21 +- .../use_cases/test_run_use_case_on_systems.py | 8 +- system-leaderboard/src/App.jsx | 14 +- .../src/components/BaselineLink.jsx | 12 +- .../src/components/DataHealthGate.jsx | 19 +- .../src/components/ErrorVsTime.jsx | 207 ++++++ system-leaderboard/src/components/Navbar.jsx | 74 +- .../src/components/PairComparison.jsx | 318 +++++++++ .../src/components/QuerySetCells.jsx | 33 + .../src/components/RecordName.jsx | 57 ++ .../src/components/SourcesBar.jsx | 89 +++ .../src/context/BenchmarkDataContext.jsx | 97 ++- .../src/pages/AccuracyVsCost.css | 90 --- .../src/pages/AccuracyVsCost.jsx | 454 ------------- .../src/pages/DecisionSupport.jsx | 471 ------------- system-leaderboard/src/pages/Home.jsx | 68 +- system-leaderboard/src/pages/QuerySet.css | 148 ++++ system-leaderboard/src/pages/QuerySet.jsx | 641 ++++++++++++++++++ .../src/pages/ResultDetails.jsx | 291 +++++--- system-leaderboard/src/pages/ResultTable.css | 18 + system-leaderboard/src/pages/ResultTable.jsx | 142 ---- system-leaderboard/src/pages/Throughput.jsx | 235 ------- .../src/pages/Visualization.jsx | 402 ----------- .../src/utils/benchmarkRecord.js | 64 +- system-leaderboard/src/utils/catalog.js | 106 +++ system-leaderboard/src/utils/compare.js | 158 +++++ system-leaderboard/src/utils/loadJson.js | 83 ++- system-leaderboard/src/utils/metrics.js | 73 +- system-leaderboard/src/utils/querySets.js | 117 ++++ system-leaderboard/src/utils/schema.json | 21 +- 38 files changed, 3569 insertions(+), 2072 deletions(-) create mode 100644 scripts/leaderboard-catalog-clickbench.json create mode 100644 scripts/leaderboard-catalog.json create mode 100644 scripts/leaderboard_catalog.py create mode 100644 scripts/test_system_leaderboard_data.py create mode 100644 system-leaderboard/src/components/ErrorVsTime.jsx create mode 100644 system-leaderboard/src/components/PairComparison.jsx create mode 100644 system-leaderboard/src/components/QuerySetCells.jsx create mode 100644 system-leaderboard/src/components/RecordName.jsx create mode 100644 system-leaderboard/src/components/SourcesBar.jsx delete mode 100644 system-leaderboard/src/pages/AccuracyVsCost.css delete mode 100644 system-leaderboard/src/pages/AccuracyVsCost.jsx delete mode 100644 system-leaderboard/src/pages/DecisionSupport.jsx create mode 100644 system-leaderboard/src/pages/QuerySet.css create mode 100644 system-leaderboard/src/pages/QuerySet.jsx delete mode 100644 system-leaderboard/src/pages/ResultTable.jsx delete mode 100644 system-leaderboard/src/pages/Throughput.jsx delete mode 100644 system-leaderboard/src/pages/Visualization.jsx create mode 100644 system-leaderboard/src/utils/catalog.js create mode 100644 system-leaderboard/src/utils/compare.js create mode 100644 system-leaderboard/src/utils/querySets.js diff --git a/scripts/leaderboard-catalog-clickbench.json b/scripts/leaderboard-catalog-clickbench.json new file mode 100644 index 00000000..c2c5d83f --- /dev/null +++ b/scripts/leaderboard-catalog-clickbench.json @@ -0,0 +1,33 @@ +{ + "catalog_version": 1, + "systems": { + "postgresql": { + "name": "TimescaleDB", + "description": "PostgreSQL with the timescaledb extension, set up as ClickBench's timescaledb entry: hits is a compressed hypertable; timescaledb_toolkit is installed." + } + }, + "configurations": { + "clickhouse/exact": { + "name": "Exact", + "description": "ClickBench's ClickHouse queries, as written; exact answers." + }, + "duckdb/exact": { + "name": "Exact", + "description": "ClickBench's DuckDB queries, as written; exact answers." + }, + "postgresql/exact": { + "name": "Exact", + "description": "ClickBench's timescaledb queries, as written; exact answers." + }, + "postgresql/approximate": { + "name": "approx_count_distinct rewrite", + "description": "ASAPBench's rewrite, not part of ClickBench: each query with COUNT(DISTINCT x) uses timescaledb_toolkit's distinct_count(approx_count_distinct(x)) instead (HyperLogLog++ at the toolkit's default size), computed from the stored rows at every query. Queries without COUNT(DISTINCT) are not run." + } + }, + "workloads": { + "clickbench-hits": { + "name": "ClickBench hits", + "description": "ClickBench's 43 queries over its hits table of web analytics events, each system in its own dialect from the ClickBench repository." + } + } +} diff --git a/scripts/leaderboard-catalog.json b/scripts/leaderboard-catalog.json new file mode 100644 index 00000000..1af66cdd --- /dev/null +++ b/scripts/leaderboard-catalog.json @@ -0,0 +1,53 @@ +{ + "catalog_version": 1, + "benchmarks": { + "one-shot": { + "name": "One-shot SQL", + "description": "Each query runs on its own over a loaded table; hot runs are timed and answers are compared with the truth configuration." + }, + "periodic": { + "name": "Periodic PromQL", + "description": "Samples are written as time series and every query is evaluated again at each step of its interval, as dashboards and alerts do." + } + }, + "systems": { + "clickhouse": { "name": "ClickHouse", "description": "ClickHouse server, queried over HTTP." }, + "duckdb": { "name": "DuckDB", "description": "DuckDB command line on a database file." }, + "postgresql": { "name": "PostgreSQL", "description": "PostgreSQL, queried with psql." }, + "druid": { "name": "Apache Druid", "description": "Apache Druid, queried with Druid SQL over HTTP." }, + "pilotdb": { + "name": "PilotDB", + "description": "PilotDB on DuckDB: sampling-based approximate query processing with an error guarantee set before the query runs." + }, + "VictoriaMetrics": { + "name": "VictoriaMetrics", + "description": "VictoriaMetrics single node: stores every raw sample and answers each query at query time." + }, + "ASAPQuery-backend": { + "name": "ASAPQuery-backend", + "description": "ASAPQuery's control plane plans the queries with ASAPPlanner; its data plane keeps what the plan needs (summaries, materialized views, raw samples when allowed) and answers from it." + } + }, + "configurations": { + "*/exact": { "name": "Exact", "description": "Every query as written; exact answers." }, + "druid/exact": { + "name": "Exact", + "description": "useApproximateCountDistinct and useApproximateTopN off: COUNT(DISTINCT) and TopN answered exactly." + }, + "druid/defaults": { + "name": "Druid defaults", + "description": "Druid's default query context, which answers COUNT(DISTINCT) approximately (useApproximateCountDistinct) and uses approximate TopN (useApproximateTopN)." + }, + "pilotdb/*": { + "name": "PilotDB, relative error {relative_error}", + "description": "Target relative error {relative_error} with failure probability {failure_probability}; only the queries PilotDB's paper runs." + } + }, + "workloads": { + "ddos_syn_flood": { "name": "DDoS SYN flood", "description": "Use case 1: SYN flood alerts from distinct source IPs and their entropy over short windows." }, + "k8s_autoscaling": { "name": "Kubernetes autoscaling", "description": "Use case 2: scale-out, scale-in and resize decisions from CPU and memory percentiles of containers." }, + "video_experience": { "name": "Video experience", "description": "Use case 3: video quality alerts from buffering, bitrate and start time." }, + "canary_release": { "name": "Canary release", "description": "Use case 4: promote or roll back a canary from its latency percentiles." }, + "top_clients": { "name": "Top clients", "description": "Use case 5: rate limiting of the top clients by request count." } + } +} diff --git a/scripts/leaderboard-data.sh b/scripts/leaderboard-data.sh index 0e049c27..97689359 100755 --- a/scripts/leaderboard-data.sh +++ b/scripts/leaderboard-data.sh @@ -7,7 +7,7 @@ Pack saved benchmark results into one archive, and show an archive as the system or as Grafana dashboards, without running any system again. scripts/leaderboard-data.sh pack [--one-shot ]... - [--use-cases ] + [--use-cases ] [--spec ]... scripts/leaderboard-data.sh web [] scripts/leaderboard-data.sh grafana @@ -15,17 +15,22 @@ pack --one-shot a run directory of scripts/one-shot-workload.sh after one its reports, results/ and workloads/ are kept, a DuckDB database is not --use-cases the runs/ directory scripts/use_cases/run_use_case_on_systems.py writes under its --data, holding index.json -web unpacks the archive under target/leaderboard-data/, writes - system-leaderboard/public/data/all.jsonl from it and starts the leaderboard - [port 5173]; needs python3 and node 20.19 or later + --spec an -summary.json of run_use_case_on_systems.py --spec, kept with + the leaderboard.json of its directory +web unpacks the archive under target/leaderboard-data/, writes all.jsonl, catalog.json + and sources.json into system-leaderboard/public/data/ from it and starts the + leaderboard [port 5173]; needs python3 and node 20.19 or later. Results that must + not be published are opened in the page itself (Open local results), not packed. grafana unpacks the archive under target/leaderboard-data/, writes leaderboard/records.json in it and starts tools/grafana/run.sh on it: the five use cases on systems and the one-shot query dashboards An archive holds one directory: manifest.json when, from which ASAPBench commit, on which machine - one-shot// one-shot-summary.csv, one-shot-tables.csv, results/, workloads/ + one-shot// one-shot-summary.csv, one-shot-tables.csv, results/, workloads/, + leaderboard.json phase3/runs/ index.json and one directory per use-case run + spec// -summary.json files and leaderboard.json EOF } @@ -64,15 +69,16 @@ case $action in [ $# -ge 1 ] || { usage >&2; exit 2; } archive=$(realpath -m "$1"); shift case $archive in *.tar.xz) ;; *) echo "the archive name ends in .tar.xz" >&2; exit 2 ;; esac - one_shot=(); use_cases="" + one_shot=(); use_cases=""; spec=() while [ $# -gt 0 ]; do case $1 in --one-shot) one_shot+=("$(realpath "$2")"); shift 2 ;; --use-cases) use_cases=$(realpath "$2"); shift 2 ;; + --spec) spec+=("$(realpath "$2")"); shift 2 ;; *) usage >&2; exit 2 ;; esac done - [ ${#one_shot[@]} -gt 0 ] || [ -n "$use_cases" ] || { echo "nothing to pack" >&2; exit 2; } + [ ${#one_shot[@]} -gt 0 ] || [ -n "$use_cases" ] || [ ${#spec[@]} -gt 0 ] || { echo "nothing to pack" >&2; exit 2; } name=$(basename "$archive" .tar.xz) staging=$(mktemp -d) trap 'rm -rf "$staging"' EXIT @@ -81,7 +87,7 @@ case $action in [ -f "$run/one-shot-summary.csv" ] || { echo "$run has no one-shot-summary.csv; run one-shot-report first" >&2; exit 1; } target=$staging/$name/one-shot/$(basename "$run") mkdir -p "$target" - for item in one-shot-summary.csv one-shot-summary.md one-shot-tables.csv results workloads; do + for item in one-shot-summary.csv one-shot-summary.md one-shot-tables.csv results workloads leaderboard.json; do [ -e "$run/$item" ] && cp -a "$run/$item" "$target/" done done @@ -90,6 +96,15 @@ case $action in mkdir -p "$staging/$name/phase3" cp -a "$use_cases" "$staging/$name/phase3/runs" fi + for summary in ${spec[@]+"${spec[@]}"}; do + case $summary in *-summary.json) ;; *) echo "$summary is not an -summary.json" >&2; exit 1 ;; esac + [ -f "$summary" ] || { echo "no $summary" >&2; exit 1; } + source_directory=$(dirname "$summary") + target=$staging/$name/spec/$(basename "$source_directory") + mkdir -p "$target" + cp -a "$summary" "$target/" + [ -f "$source_directory/leaderboard.json" ] && cp -a "$source_directory/leaderboard.json" "$target/" + done python3 - "$staging/$name" "$repo" <<'PY' import datetime, glob, json, os, subprocess, sys root, repo = sys.argv[1:] @@ -106,6 +121,7 @@ manifest = { "machines": [json.loads(m) for m in sorted(machines)], "one_shot_runs": sorted(os.listdir(os.path.join(root, "one-shot"))) if os.path.isdir(os.path.join(root, "one-shot")) else [], "use_case_runs": os.path.isdir(os.path.join(root, "phase3", "runs")), + "spec_directories": sorted(os.listdir(os.path.join(root, "spec"))) if os.path.isdir(os.path.join(root, "spec")) else [], } with open(os.path.join(root, "manifest.json"), "w") as file: json.dump(manifest, file, indent=2) @@ -117,8 +133,15 @@ PY web) [ $# -ge 1 ] || { usage >&2; exit 2; } data=$(data_directory "$1"); port=${2:-5173} - python3 "$repo/scripts/system-leaderboard-data.py" --data "$data" \ - --output "$repo/system-leaderboard/public/data/all.jsonl" + public=$repo/system-leaderboard/public/data + python3 "$repo/scripts/system-leaderboard-data.py" --data "$data" --output "$public/all.jsonl" + python3 - "$public/sources.json" "$(basename "$data")" <<'PY' +import json, sys +path, name = sys.argv[1:] +with open(path, "w") as file: + json.dump({"title": "System Leaderboard", + "sources": [{"name": name, "records": "all.jsonl", "catalog": "catalog.json"}]}, file, indent=1) +PY command -v npm >/dev/null || { echo "needs node 20.19 or later and npm" >&2; exit 1; } cd "$repo/system-leaderboard" [ -d node_modules ] || npm ci --no-audit --no-fund diff --git a/scripts/leaderboard_catalog.py b/scripts/leaderboard_catalog.py new file mode 100644 index 00000000..0f988668 --- /dev/null +++ b/scripts/leaderboard_catalog.py @@ -0,0 +1,343 @@ +#!/usr/bin/env python3 +import argparse +import glob +import json +import os +import re +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +TEXTS = os.path.join(HERE, "leaderboard-catalog.json") +SIDECAR = "leaderboard.json" +CATALOG_VERSION = 2 +SECTIONS = ("benchmarks", "systems", "configurations", "workloads") +MEASUREMENTS = ("time", "cpu", "memory", "accuracy", "decision") +MODES = ("exact", "approximate") + +DESCRIPTION = ("Write leaderboard.json beside saved results: what each query set compares, and the display names " + "and descriptions.") + +EPILOG = """\ +leaderboard.json holds + catalog {"benchmarks"|"systems"|"workloads": {id: {"name", "description"}}, + "configurations": {"/": {"name", "description"}}} + query_sets {"/": { + "benchmark": "one-shot" | "periodic", "workload": id, + "queries": [query id, ...], + "truth": "/" or another id, "truth_description": text, + "participants": {"/": { + "mode": "exact" | "approximate", + "reference": "/" this one is compared with, or null, + "pending": measurements not to show, of time, cpu, memory, accuracy, decision}}, + "pending_reason": text}} +The names and descriptions come from scripts/leaderboard-catalog.json and the --texts files; +an existing leaderboard.json is merged, later entries winning, participant by participant. + +one-shot a run directory of scripts/one-shot-workload.sh: results//*.one-shot.json; + exact is the configuration named exact, every other one is approximate and compared + with its own system's exact, or with --truth when its system has none +use-cases the runs/ directory scripts/use_cases/run_use_case_on_systems.py writes, holding index.json +spec a directory holding -summary.json files of run_use_case_on_systems.py --spec +pending mark measurements of participants as not to be shown, with --query-set, --participant, + --measurements and --reason +""" + + +def empty_catalog(): + return {"catalog_version": CATALOG_VERSION, **{section: {} for section in SECTIONS}} + + +def read_json(path): + with open(path) as file: + return json.load(file) + + +def merge_catalogs(base, extra): + for section in SECTIONS: + base.setdefault(section, {}).update((extra or {}).get(section) or {}) + return base + + +def merge_query_sets(base, extra): + for key, declared in (extra or {}).items(): + current = base.setdefault(key, {}) + participants = {**(current.get("participants") or {})} + for name, participant in (declared.get("participants") or {}).items(): + participants[name] = {**participants.get(name, {}), **participant} + current.update({k: v for k, v in declared.items() if k != "participants" and v is not None}) + current["participants"] = participants + return base + + +def load_texts(extra_paths=()): + texts = empty_catalog() + for path in (TEXTS, *extra_paths): + merge_catalogs(texts, read_json(path)) + return texts + + +class Options(dict): + def __missing__(self, key): + return "{" + key + "}" + + +def entry(texts, section, key, options=None): + found = texts.get(section, {}) + candidates = [key] + if section == "configurations" and "/" in key: + system, configuration = key.split("/", 1) + candidates += [f"{system}/*", f"*/{configuration}"] + for candidate in candidates: + if candidate in found: + values = Options({k: v for k, v in (options or {}).items() if not isinstance(v, (dict, list))}) + return {field: text.format_map(values) for field, text in found[candidate].items()} + return None + + +def put(catalog, texts, section, key, options=None): + found = entry(texts, section, key, options) + if found: + catalog[section][key] = found + + +def percent(value): + return f"{value * 100:g}%" + + +def arm_entry(arm, details): + details = details or {} + parts = [] + if details.get("raw_data_retained"): + store = details.get("raw_store") + parts.append("keeps raw samples" + (f" in a raw store ({store})" if store else "")) + else: + parts.append("keeps no raw samples") + if details.get("max_error") is not None: + target = f"relative error at most {percent(details['max_error'])}" + if details.get("failure_probability") is not None: + target += f" with failure probability {percent(details['failure_probability'])}" + parts.append(target) + if details.get("ignore_guarantees"): + parts.append("plans without an accuracy guarantee accepted") + text = "; ".join(parts) + return {"name": arm, "description": text[0].upper() + text[1:] + "."} + + +def read_sidecar(directory): + path = os.path.join(directory, SIDECAR) + return read_json(path) if os.path.isfile(path) else {} + + +def write_sidecar(directory, catalog=None, query_sets=None): + current = read_sidecar(directory) + out = { + "catalog": merge_catalogs(merge_catalogs(empty_catalog(), current.get("catalog")), catalog), + "query_sets": merge_query_sets(merge_query_sets({}, current.get("query_sets")), query_sets), + } + path = os.path.join(directory, SIDECAR) + with open(path + ".partial", "w") as file: + json.dump(out, file, indent=1, sort_keys=True) + os.replace(path + ".partial", path) + return path + + +def query_set_key(benchmark, workload): + return f"{benchmark}/{workload}" + + +def query_set(benchmark, workload, queries, truth, truth_description, participants): + return {query_set_key(benchmark, workload): { + "benchmark": benchmark, + "workload": workload, + "queries": queries, + "truth": truth, + "truth_description": truth_description, + "participants": participants, + }} + + +def one_shot_catalog(run_directory, truth, texts): + catalog = empty_catalog() + put(catalog, texts, "benchmarks", "one-shot") + by_workload = {} + for path in sorted(glob.glob(os.path.join(run_directory, "results", "*", "*.one-shot.json"))): + result = read_json(path) + system = result["engine"]["id"] + key = f"{system}/{result['configuration']}" + workload = result.get("workload") or "" + found = by_workload.setdefault(workload, {"configurations": [], "queries": []}) + found["configurations"].append(key) + for query in result.get("queries") or []: + if query.get("id") not in found["queries"]: + found["queries"].append(query.get("id")) + put(catalog, texts, "systems", system) + put(catalog, texts, "configurations", key, result.get("configuration_options")) + put(catalog, texts, "workloads", workload) + query_sets = {} + for workload, found in by_workload.items(): + configurations = found["configurations"] + participants = {} + for key in configurations: + if key.endswith("/exact"): + participants[key] = {"mode": "exact", "reference": None} + else: + own = key.split("/", 1)[0] + "/exact" + participants[key] = {"mode": "approximate", "reference": own if own in configurations else truth} + query_sets.update(query_set("one-shot", workload, found["queries"], truth, + f"{truth}'s answers" if truth else None, participants)) + return catalog, query_sets + + +PLANEVAL_TRUTH = "planeval" +PLANEVAL_TRUTH_DESCRIPTION = ("planeval's exact answers over the same samples, or the reference system's where " + "planeval has none") + + +def use_case_catalog(index_path, texts): + catalog = empty_catalog() + put(catalog, texts, "benchmarks", "periodic") + query_sets = {} + for run in read_json(index_path): + details = run.get("details") or {} + use_case = run.get("use_case") or "" + put(catalog, texts, "workloads", use_case) + reference, candidate = periodic_roles(details) + for system in details.get("systems") or {}: + put(catalog, texts, "systems", system) + participants = {} + if reference: + put(catalog, texts, "configurations", f"{reference}/exact") + participants[f"{reference}/exact"] = {"mode": "exact", "reference": None} + if candidate: + arm = arm_name(run) + catalog["configurations"][f"{candidate}/{arm}"] = arm_entry(arm, details.get("arm")) + participants[f"{candidate}/{arm}"] = { + "mode": "approximate", "reference": f"{reference}/exact" if reference else None} + merge_query_sets(query_sets, query_set("periodic", use_case, list(details.get("promql") or {}), + PLANEVAL_TRUTH, PLANEVAL_TRUTH_DESCRIPTION, participants)) + return catalog, query_sets + + +def spec_catalog(summary_paths, texts): + catalog = empty_catalog() + put(catalog, texts, "benchmarks", "periodic") + query_sets = {} + for path in summary_paths: + summary = read_json(path) + reference, candidate = summary_roles(summary) + workload = spec_workload(summary) + for system in summary.get("systems") or {}: + put(catalog, texts, "systems", system) + put(catalog, texts, "workloads", workload) + put(catalog, texts, "configurations", f"{reference}/exact") + arm = summary_arm(path, summary) + deployment = summary.get(f"{candidate} deployment") or {} + requirement = deployment.get("accuracy requirement") or {} + details = {"raw_data_retained": deployment.get("raw_data_retained"), "raw_store": deployment.get("raw store"), + "max_error": requirement.get("max_error"), + "failure_probability": requirement.get("failure_probability"), + "ignore_guarantees": "ignore" in arm.split("-")} + catalog["configurations"][f"{candidate}/{arm}"] = arm_entry(arm, details) + participants = {f"{reference}/exact": {"mode": "exact", "reference": None}, + f"{candidate}/{arm}": {"mode": "approximate", "reference": f"{reference}/exact"}} + merge_query_sets(query_sets, query_set("periodic", workload, list(summary.get("per query") or {}), + f"{reference}/exact", f"{reference}'s answers", participants)) + return catalog, query_sets + + +def mark_pending(directory, key, participants, measurements, reason): + unknown = sorted(set(measurements) - set(MEASUREMENTS)) + if unknown: + sys.exit(f"unknown measurements {', '.join(unknown)}; known: {', '.join(MEASUREMENTS)}") + declared = (read_sidecar(directory).get("query_sets") or {}).get(key) + if not declared: + sys.exit(f"{os.path.join(directory, SIDECAR)} declares no query set {key}") + missing = [p for p in participants if p not in (declared.get("participants") or {})] + if missing: + sys.exit(f"query set {key} has no participant {', '.join(missing)}") + update = {key: {"pending_reason": reason, "participants": { + p: {"pending": sorted(set(declared["participants"][p].get("pending") or []) | set(measurements))} + for p in participants}}} + return write_sidecar(directory, None, update) + + +RUN_ARM = re.compile(r"-systems-(?:bulk|speed[^-]*)-(?P.+?)(?:-trial\d+)?$") + + +def arm_name(run): + details = run.get("details") or {} + if details.get("arm_name"): + return details["arm_name"] + match = RUN_ARM.search(run["run_id"]) + return match.group("arm") if match else run["run_id"] + + +REFERENCE_OF_RUNS_WITHOUT_ONE = "VictoriaMetrics" + + +def periodic_roles(details): + systems = list(details.get("systems") or {}) + reference = details.get("reference") or ( + REFERENCE_OF_RUNS_WITHOUT_ONE if REFERENCE_OF_RUNS_WITHOUT_ONE in systems else (systems[0] if systems else None)) + candidate = details.get("candidate") or next((s for s in systems if s != reference), None) + return reference, candidate + + +def summary_roles(summary): + systems = list(summary.get("systems") or {}) + reference = summary.get("reference") or (systems[0] if systems else None) + candidate = summary.get("candidate") or next((s for s in systems if s != reference), None) + return reference, candidate + + +def summary_arm(path, summary): + if summary.get("arm"): + return summary["arm"] + name = os.path.basename(path) + return name[: -len("-summary.json")] if name.endswith("-summary.json") else name + + +def spec_workload(summary): + if summary.get("workload"): + return summary["workload"] + return os.path.splitext(os.path.basename(summary.get("spec") or ""))[0] or summary.get("use_case") or "spec" + + +def main(): + parser = argparse.ArgumentParser(description=DESCRIPTION, epilog=EPILOG, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("kind", choices=("one-shot", "use-cases", "spec", "pending")) + parser.add_argument("directory") + parser.add_argument("--truth", help="one-shot: the configuration answers are compared with [none]") + parser.add_argument("--texts", action="append", default=[], metavar="CATALOG_JSON", + help="repeatable; more names and descriptions, over scripts/leaderboard-catalog.json") + parser.add_argument("--query-set", metavar="BENCHMARK/WORKLOAD", help="pending: the query set") + parser.add_argument("--participant", action="append", default=[], metavar="SYSTEM/CONFIGURATION", + help="pending: repeatable") + parser.add_argument("--measurements", default="", help=f"pending: comma-separated, of {', '.join(MEASUREMENTS)}") + parser.add_argument("--reason", help="pending: why the measurements are not shown") + args = parser.parse_args() + if args.kind == "pending": + if not args.query_set or not args.participant or not args.measurements: + sys.exit("pending needs --query-set, --participant and --measurements") + print(mark_pending(args.directory, args.query_set, args.participant, + [m for m in args.measurements.split(",") if m], args.reason)) + return + texts = load_texts(args.texts) + if args.kind == "one-shot": + catalog, query_sets = one_shot_catalog(args.directory, args.truth, texts) + elif args.kind == "use-cases": + index = os.path.join(args.directory, "index.json") + if not os.path.isfile(index): + sys.exit(f"no {index}") + catalog, query_sets = use_case_catalog(index, texts) + else: + summaries = sorted(glob.glob(os.path.join(args.directory, "*-summary.json"))) + if not summaries: + sys.exit(f"no *-summary.json in {args.directory}") + catalog, query_sets = spec_catalog(summaries, texts) + print(write_sidecar(args.directory, catalog, query_sets)) + + +if __name__ == "__main__": + main() diff --git a/scripts/one-shot-clickbench.sh b/scripts/one-shot-clickbench.sh index 4a0c9de7..df4cad22 100755 --- a/scripts/one-shot-clickbench.sh +++ b/scripts/one-shot-clickbench.sh @@ -179,4 +179,5 @@ PY DUCKDB=$duckdb DUCKDB_DATABASE=${DUCKDB_DATABASE:-$run/hits.duckdb} \ APPROXIMATE_QUERIES=${APPROXIMATE_QUERIES:-1 2 3 4 8 21 30} \ + LEADERBOARD_TEXTS="$(dirname "$0")/leaderboard-catalog-clickbench.json${LEADERBOARD_TEXTS:+ $LEADERBOARD_TEXTS}" \ "$(dirname "$0")/one-shot-workload.sh" "$workload" "$data" "$run" diff --git a/scripts/one-shot-workload.sh b/scripts/one-shot-workload.sh index c578fbe1..a315aca6 100755 --- a/scripts/one-shot-workload.sh +++ b/scripts/one-shot-workload.sh @@ -98,6 +98,8 @@ Environment (defaults in brackets): RUNS runs per query of every configuration but PilotDB's [3, as ClickBench] PILOTDB_RUNS runs per query of PilotDB [20, as PilotDB's accuracy experiments] + LEADERBOARD_TEXTS space-separated catalog files of names and descriptions for the + run's leaderboard.json, over scripts/leaderboard-catalog.json [none] THREADS DuckDB threads and ClickHouse max_threads [engine default] ENGINE_CPUS a taskset CPU list for approxbench and the DuckDB, psql and PilotDB processes it starts; pin the servers to the same CPUs @@ -331,6 +333,15 @@ chown_run_and_databases() { fi } +write_leaderboard_catalog() { + local texts=() file + for file in ${LEADERBOARD_TEXTS:-}; do + texts+=(--texts "$file") + done + python3 "$(dirname "$0")/leaderboard_catalog.py" one-shot "$run" ${1:+--truth "$1"} \ + ${texts[@]+"${texts[@]}"} >/dev/null +} + one_shot() { local result=$run/results/$1/${name}__$2.one-shot.json if [ -f "$result" ]; then @@ -435,8 +446,13 @@ PY "${words[@]:4}" || status=$? fi done + truth="" + for ((i = 0; i + 1 < ${#report[@]}; i++)); do + [ "${report[i]}" = --truth ] && truth=${report[i + 1]} + done chown_run_and_databases ${databases[@]+"${databases[@]}"} [ "$status" -eq 0 ] || exit "$status" + write_leaderboard_catalog "$truth" "$approxbench" benchmark-external one-shot-report --run-directory "$run" ${report[@]+"${report[@]}"} exit 0 fi @@ -528,6 +544,7 @@ if [ "$status" -eq 0 ] && [ -n "$pilotdb_python" ]; then fi chown_run_and_databases "$database" [ "$status" -eq 0 ] || exit "$status" +write_leaderboard_catalog duckdb/exact "$approxbench" benchmark-external one-shot-report --run-directory "$run" \ --truth duckdb/exact "${baselines[@]}" diff --git a/scripts/system-leaderboard-data.py b/scripts/system-leaderboard-data.py index 48ab836b..c5ca0bfc 100755 --- a/scripts/system-leaderboard-data.py +++ b/scripts/system-leaderboard-data.py @@ -5,26 +5,35 @@ import json import math import os +import re import statistics import sys -SCHEMA_VERSION = 2 +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import leaderboard_catalog # noqa: E402 -DESCRIPTION = "Write the system leaderboard's data file from saved approxbench benchmark-external outputs." +SCHEMA_VERSION = 3 + +DESCRIPTION = "Write the system leaderboard's data files from saved approxbench benchmark-external outputs." EPILOG = """\ ---data a data directory as scripts/leaderboard-data.sh packs it: one-shot// for each - one-shot run directory and phase3/runs/index.json for the use cases on systems ---one-shot a run directory of scripts/one-shot-workload.sh after one-shot-report: its - one-shot-summary.csv, one-shot-tables.csv and results//*.one-shot.json ---periodic the runs/index.json scripts/use_cases/run_use_case_on_systems.py writes - -Every line of the output is one record: one system in one configuration on one workload, with -its per-query results under "queries". Nothing is rerun; only saved results are read. +--data a data directory as scripts/leaderboard-data.sh packs it: one-shot// for each + one-shot run directory, phase3/runs/index.json for the use cases on systems and + spec// for each directory of --spec summaries +--one-shot a run directory of scripts/one-shot-workload.sh after one-shot-report: its + one-shot-summary.csv, one-shot-tables.csv and results//*.one-shot.json +--periodic the runs/index.json scripts/use_cases/run_use_case_on_systems.py writes +--spec-summary an -summary.json run_use_case_on_systems.py --spec writes + +Every line of the records file is one record: one system in one configuration on one workload, +with its per-query results under "queries". The catalog file beside it holds the query sets (what +is compared with what, which answers are the truth, which measurements are pending) and the +display names and descriptions, merged from the leaderboard.json each result directory carries +(scripts/leaderboard_catalog.py), or made from scripts/leaderboard-catalog.json for a directory +without one. A record takes its mode and its reference from its query set; a measurement its +query set marks pending is left out. Nothing is rerun; only saved results are read. """ -EXACT_PERIODIC_SYSTEMS = {"VictoriaMetrics"} - def number(value): if value is None or value == "": @@ -58,6 +67,11 @@ def median(values): return statistics.median(values) if values else None +def largest(values): + values = finite(values) + return max(values) if values else None + + def machine_text(machine): if not machine: return None @@ -71,15 +85,20 @@ def query_seconds(row, which): return number(query) if query is not None else number(row[f"{which}_wall_seconds"]) -def one_shot_baseline(system, configuration, configurations): - if configuration == "exact": +def answers_of(reference): + return f"{reference} answers" if reference else None + + +def summary_truth(run_directory): + path = os.path.join(run_directory, "one-shot-summary.md") + if not os.path.isfile(path): return None - if (system, "exact") in configurations: - return f"{system}/exact" - return "duckdb/exact" if ("duckdb", "exact") in configurations else None + with open(path) as file: + match = re.search(r"^Accuracy against (\S+?)\.?(?:\s|$)", file.read(), re.MULTILINE) + return match.group(1) if match else None -def one_shot(run_directory): +def one_shot(run_directory, query_sets): summary = os.path.join(run_directory, "one-shot-summary.csv") tables = os.path.join(run_directory, "one-shot-tables.csv") for path in (summary, tables): @@ -101,10 +120,14 @@ def one_shot(run_directory): hot = {key: {r["query"]: query_seconds(r, "hot_min") for r in group if r["status"] == "ok"} for key, group in rows.items()} for (system, configuration), group in rows.items(): + key = f"{system}/{configuration}" + declared = query_sets.get(f"one-shot/{group[0]['workload']}") or {} + participant = (declared.get("participants") or {}).get(key) or {} + exact = participant.get("mode", "exact" if configuration == "exact" else "approximate") == "exact" + baseline = None if exact else participant.get("reference") result = results.get((system, configuration), {}) texts = {q["id"]: q.get("sql") for q in result.get("queries", [])} - baseline = one_shot_baseline(system, configuration, rows) - baseline_key = tuple(baseline.split("/")) if baseline else None + baseline_key = tuple(baseline.split("/", 1)) if baseline else None queries = [] for r in group: answered = r["status"] == "ok" @@ -125,6 +148,8 @@ def one_shot(run_directory): "differing_text_cells": count(r["differing_text_cells"]), "truth_stable": r["truth_runs_agree"] != "false", "peak_memory_bytes": number(r["hot_median_peak_memory_bytes"]), + "cpu_seconds": number(r.get("hot_median_harness_cpu_seconds")) + if r.get("cpu_and_memory_source") else None, }) ok = [q for q in queries if q["status"] == "ok"] compared = [q for q in ok if q["truth_stable"]] @@ -136,8 +161,9 @@ def one_shot(run_directory): "workload": r["workload"], "system": system, "configuration": configuration, - "mode": "exact" if configuration == "exact" else "approximate", + "mode": "exact" if exact else "approximate", "baseline": baseline, + "error_reference": truth_text(declared) or answers_of(summary_truth(run_directory)), "version": (result.get("engine") or {}).get("version"), "build_profile": (result.get("engine") or {}).get("build_profile"), "options": {k: v for k, v in (result.get("configuration_options") or {}).items() @@ -145,6 +171,7 @@ def one_shot(run_directory): "machine": machine_text(result.get("machine")), "harness_version": result.get("harness_version"), "trials": 1, + "instances": 1, "runs_per_query": max((count(q["runs"]) or 0) for q in group), "query_count": len(queries), "answered_count": len(ok), @@ -159,6 +186,7 @@ def one_shot(run_directory): "max_relative_error": largest_error([q["max_relative_error"] for q in compared]), "median_relative_error": median([q["max_relative_error"] for q in compared]), "peak_memory_bytes": largest_error([q["peak_memory_bytes"] for q in ok]), + "largest_instance_peak_memory_bytes": None, "data_size_bytes": sum(count(t["data_size_bytes"]) or 0 for t in load) or None, "load_seconds": sum(load_seconds) if load_seconds else None, "ingest_samples_per_second": None, @@ -186,11 +214,12 @@ def instance_totals(measured): "ingest_samples_per_second": min(rates) if rates else None, "disk_bytes": sum(disks) if disks else None, "peak_memory_bytes": sum(peaks) if peaks else None, + "largest_instance_peak_memory_bytes": max(peaks) if peaks else None, } def comparable(trials): - flags = [(d.get("cost comparison") or {}).get("cpu and memory comparable") for _, d, _, _ in trials] + flags = [(d.get("cost comparison") or {}).get("cpu and memory comparable") for _, d, _, _, _ in trials] return None if None in flags else all(flags) @@ -198,28 +227,66 @@ def names(value): return sorted(value) if isinstance(value, dict) else list(value or []) -def periodic(index_path): +def truth_text(declared): + return declared.get("truth_description") or declared.get("truth") + + +def participant_of(query_sets, benchmark, workload, key): + declared = query_sets.get(f"{benchmark}/{workload}") or {} + return declared, (declared.get("participants") or {}).get(key) or {} + + +def latency(measured, field): + common = measured.get("latency over the queries both systems asked") or {} + return common.get(field, measured.get(field)) + + +def query_latencies(runs_directory, run_id): + path = os.path.join(runs_directory, run_id, "low_level.json") + if not os.path.isfile(path): + return {} + with open(path) as file: + rows = json.load(file) + out = {} + for row in rows: + if row.get("metric") == "query_latency" and row.get("unit") == "s": + labels = row.get("labels") or {} + out.setdefault((labels.get("arm"), labels.get("query")), []).append(row["value"] * 1000) + return out + + +def periodic(index_path, query_sets): + runs_directory = os.path.dirname(index_path) with open(index_path) as file: runs = json.load(file) groups = {} for run in runs: details = run["details"] - arm = run["run_id"].split("-systems-bulk-", 1)[-1].split("-trial")[0] + reference, _ = leaderboard_catalog.periodic_roles(details) + arm = leaderboard_catalog.arm_name(run) for system, measured in (details.get("systems") or {}).items(): - exact = system in EXACT_PERIODIC_SYSTEMS + exact = system == reference key = (run["use_case"], system, "exact" if exact else arm) - groups.setdefault(key, []).append((run, details, measured, exact)) + groups.setdefault(key, []).append((run, details, measured, exact, reference)) for (use_case, system, configuration), trials in groups.items(): - run, details, _, exact = trials[0] + run, details, _, exact, reference = trials[0] + declared, participant = participant_of(query_sets, "periodic", use_case, f"{system}/{configuration}") + exact = participant.get("mode", "exact" if exact else "approximate") == "exact" + baseline = None if exact else participant.get("reference", f"{reference}/exact") reasons = {} if exact else (details.get("unsupported") or {}) - totals = [instance_totals(m) for _, _, m, _ in trials] + totals = [instance_totals(m) for _, _, m, _, _ in trials] errors = {} - for _, d, _, ex in trials: - source = {q: (v or {}).get("max relative error") for q, v in (d.get("victoriametrics_vs_truth") or {}).items()} \ + latencies = {} + for r, d, _, ex, _ in trials: + source = {q: (v or {}).get("max relative error") + for q, v in (d.get("reference_vs_truth") or d.get("victoriametrics_vs_truth") or {}).items()} \ if ex else (d.get("max_relative_error") or {}) for query, value in source.items(): errors.setdefault(query, []).append(value) - unsupported = sorted({n for _, _, m, _ in trials for n in names(m.get("unsupported"))}) + for (role, query), values in query_latencies(runs_directory, r["run_id"]).items(): + if role == ("exact" if ex else "approx"): + latencies.setdefault(query, []).extend(values) + unsupported = sorted({n for _, _, m, _, _ in trials for n in names(m.get("unsupported"))}) plans = (details.get("exact_plans") if exact else details.get("plans")) or {} queries = [{ "query": query, @@ -228,10 +295,11 @@ def periodic(index_path): "reason": reasons.get(query) if query in unsupported else None, "plan": plans.get(query), "max_relative_error": largest_error(errors.get(query, [])), + "median_query_ms": median(latencies.get(query, [])), } for query, text in (details.get("promql") or {}).items()] agreement = {} if not exact: - for _, d, _, _ in trials: + for _, d, _, _, _ in trials: for rule, values in (d.get("fidelity") or {}).items(): agreement.setdefault(rule, []).append(values.get("agreement")) yield { @@ -241,12 +309,13 @@ def periodic(index_path): "system": system, "configuration": configuration, "mode": "exact" if exact else "approximate", - "baseline": None if exact else "VictoriaMetrics/exact", + "baseline": baseline, + "error_reference": truth_text(declared), "version": None if exact else details.get("backend_rev"), "build_profile": details.get("write mode"), "options": {} if exact else (details.get("arm") or {}), - "machine": None, - "harness_version": None, + "machine": machine_text(details.get("machine")), + "harness_version": details.get("harness_version"), "trials": len(trials), "instances": max(t["instances"] for t in totals), "runs_per_query": None, @@ -260,17 +329,18 @@ def periodic(index_path): "max_relative_error": largest_error([q["max_relative_error"] for q in queries]), "median_relative_error": median([q["max_relative_error"] for q in queries]), "peak_memory_bytes": median([t["peak_memory_bytes"] for t in totals]), + "largest_instance_peak_memory_bytes": median([t["largest_instance_peak_memory_bytes"] for t in totals]), "data_size_bytes": None, "load_seconds": None, "ingest_samples_per_second": median([t["ingest_samples_per_second"] for t in totals]), - "median_query_ms": median([m.get("median query ms") for _, _, m, _ in trials]), - "p99_query_ms": median([m.get("p99 query ms") for _, _, m, _ in trials]), - "cpu_seconds": median([m.get("cpu seconds") for _, _, m, _ in trials]), - "query_cpu_seconds": median([m.get("query cpu seconds") for _, _, m, _ in trials]), - "ingest_cpu_seconds": median([m.get("ingest cpu seconds") for _, _, m, _ in trials]), + "median_query_ms": median([latency(m, "median query ms") for _, _, m, _, _ in trials]), + "p99_query_ms": median([latency(m, "p99 query ms") for _, _, m, _, _ in trials]), + "cpu_seconds": median([m.get("cpu seconds") for _, _, m, _, _ in trials]), + "query_cpu_seconds": median([m.get("query cpu seconds") for _, _, m, _, _ in trials]), + "ingest_cpu_seconds": median([m.get("ingest cpu seconds") for _, _, m, _, _ in trials]), "ingest_cpu_seconds_one_instance": median([m.get("largest instance ingest cpu seconds", m.get("ingest cpu seconds")) - for _, _, m, _ in trials]), + for _, _, m, _, _ in trials]), "cpu_and_memory_comparable": comparable(trials), "query_time": None, "disk_bytes": median([t["disk_bytes"] for t in totals]), @@ -279,15 +349,174 @@ def periodic(index_path): } +def instance_query_ms(measured): + out = {} + for instance in measured.get("per instance") or []: + asked = instance.get("queries") or [] + if len(asked) == 1: + out[asked[0]] = instance.get("median query ms") + return out + + +def spec(summary_paths, query_sets): + groups = {} + for path in summary_paths: + with open(path) as file: + summary = json.load(file) + reference, candidate = leaderboard_catalog.summary_roles(summary) + arm = leaderboard_catalog.summary_arm(path, summary) + workload = leaderboard_catalog.spec_workload(summary) + for system in (reference, candidate): + exact = system == reference + key = (workload, system, "exact" if exact else arm) + groups.setdefault(key, []).append((summary, exact, reference, candidate)) + for (workload, system, configuration), trials in groups.items(): + summary, exact, reference, candidate = trials[0] + declared, participant = participant_of(query_sets, "periodic", workload, f"{system}/{configuration}") + exact = participant.get("mode", "exact" if exact else "approximate") == "exact" + baseline = None if exact else participant.get("reference", f"{reference}/exact") + measured = [(s.get("systems") or {}).get(system) or {} for s, _, _, _ in trials] + totals = [instance_totals(m) for m in measured] + errors, latencies, status, reasons, plans = {}, {}, {}, {}, {} + for s, m in zip((t[0] for t in trials), measured): + fallback_ms = instance_query_ms(m) + for query, row in (s.get("per query") or {}).items(): + own = row.get(system) or {} + if exact: + supported = "unsupported" not in own + else: + supported = bool(own.get("supported")) + agreement = own.get(f"answers against {reference}") or {} + errors.setdefault(query, []).append(agreement.get("max relative error")) + if own.get("plan"): + plans[query] = own["plan"] + if not supported: + status[query] = "unsupported" + reasons[query] = own.get("reason") or own.get("unsupported") + elif own.get("failed"): + status.setdefault(query, "failed") + reasons.setdefault(query, str(own["failed"])) + else: + status.setdefault(query, "ok") + value = own.get("median query ms", fallback_ms.get(query)) + if value is not None: + latencies.setdefault(query, []).append(value) + queries = [{ + "query": query, + "text": row.get("promql"), + "status": status.get(query, "ok"), + "reason": reasons.get(query), + "plan": plans.get(query), + "max_relative_error": None if exact else largest_error(errors.get(query, [])), + "median_query_ms": median(latencies.get(query, [])), + } for query, row in (summary.get("per query") or {}).items()] + deployment = summary.get(f"{candidate} deployment") or {} + yield { + "schema_version": SCHEMA_VERSION, + "benchmark": "periodic", + "workload": workload, + "system": system, + "configuration": configuration, + "mode": "exact" if exact else "approximate", + "baseline": baseline, + "error_reference": truth_text(declared) or answers_of(reference), + "version": None if exact else summary.get("backend_rev"), + "build_profile": summary.get("write mode"), + "options": {} if exact else deployment, + "machine": machine_text(summary.get("machine")), + "harness_version": summary.get("harness_version"), + "trials": len(trials), + "instances": max(t["instances"] for t in totals), + "runs_per_query": None, + "query_count": len(queries), + "answered_count": sum(1 for q in queries if q["status"] == "ok"), + "matching_truth_count": None, + "compared_count": None, + "total_hot_seconds": None, + "geomean_hot_seconds": None, + "speedup_over_baseline": None, + "max_relative_error": None if exact else largest_error([q["max_relative_error"] for q in queries]), + "median_relative_error": None if exact else median([q["max_relative_error"] for q in queries]), + "peak_memory_bytes": median([t["peak_memory_bytes"] for t in totals]), + "largest_instance_peak_memory_bytes": median([t["largest_instance_peak_memory_bytes"] for t in totals]), + "data_size_bytes": None, + "load_seconds": None, + "ingest_samples_per_second": median([t["ingest_samples_per_second"] for t in totals]), + "median_query_ms": median([latency(m, "median query ms") for m in measured]), + "p99_query_ms": median([latency(m, "p99 query ms") for m in measured]), + "cpu_seconds": median([m.get("cpu seconds") for m in measured]), + "query_cpu_seconds": median([m.get("query cpu seconds") for m in measured]), + "ingest_cpu_seconds": median([m.get("ingest cpu seconds") for m in measured]), + "ingest_cpu_seconds_one_instance": median([m.get("largest instance ingest cpu seconds", + m.get("ingest cpu seconds")) for m in measured]), + "cpu_and_memory_comparable": (lambda flags: None if None in flags else all(flags))( + [(s.get("cost comparison") or {}).get("cpu and memory comparable") for s, _, _, _ in trials]), + "query_time": None, + "disk_bytes": median([t["disk_bytes"] for t in totals]), + "decision_agreement": {}, + "queries": queries, + } + + +PENDING_FIELDS = { + "time": ("total_hot_seconds", "geomean_hot_seconds", "speedup_over_baseline", "median_query_ms", + "p99_query_ms"), + "cpu": ("cpu_seconds", "query_cpu_seconds", "ingest_cpu_seconds", "ingest_cpu_seconds_one_instance"), + "memory": ("peak_memory_bytes", "largest_instance_peak_memory_bytes"), + "accuracy": ("max_relative_error", "median_relative_error", "matching_truth_count", "compared_count"), + "decision": ("decision_agreement",), +} +PENDING_QUERY_FIELDS = { + "time": ("first_run_seconds", "hot_min_seconds", "hot_median_seconds", "hot_min_engine_seconds", + "speedup_over_baseline", "median_query_ms"), + "cpu": ("cpu_seconds",), + "memory": ("peak_memory_bytes",), + "accuracy": ("max_relative_error", "missing_groups", "extra_groups", "differing_text_cells"), +} + + +def withhold_pending(records, query_sets): + pending = {} + for record in records: + _, participant = participant_of(query_sets, record["benchmark"], record["workload"], + f"{record['system']}/{record['configuration']}") + record["pending"] = sorted(participant.get("pending") or []) + pending[(record["benchmark"], record["workload"], f"{record['system']}/{record['configuration']}")] = \ + set(record["pending"]) + for record in records: + own = set(record["pending"]) + reference = pending.get((record["benchmark"], record["workload"], record["baseline"]), set()) + for measurement in own: + for field in PENDING_FIELDS.get(measurement, ()): + record[field] = {} if field == "decision_agreement" else None + for query in record["queries"]: + for field in PENDING_QUERY_FIELDS.get(measurement, ()): + if field in query: + query[field] = None + if "time" in reference: + record["speedup_over_baseline"] = None + for query in record["queries"]: + if "speedup_over_baseline" in query: + query["speedup_over_baseline"] = None + + def periodic_speedups(records): - exact = {(r["workload"]): r for r in records if r["benchmark"] == "periodic" and r["mode"] == "exact"} + exact = {(r["workload"], f"{r['system']}/{r['configuration']}"): r + for r in records if r["benchmark"] == "periodic" and r["mode"] == "exact"} for record in records: if record["benchmark"] == "periodic" and record["mode"] == "approximate": - reference = exact.get(record["workload"]) + reference = exact.get((record["workload"], record["baseline"])) if reference and reference["median_query_ms"] and record["median_query_ms"]: record["speedup_over_baseline"] = reference["median_query_ms"] / record["median_query_ms"] +def directory_catalog(directory, make): + sidecar = leaderboard_catalog.read_sidecar(directory) + if sidecar.get("query_sets"): + return sidecar.get("catalog") or {}, sidecar["query_sets"] + return make() + + def main(): parser = argparse.ArgumentParser( description=DESCRIPTION, epilog=EPILOG, formatter_class=argparse.RawDescriptionHelpFormatter @@ -295,26 +524,55 @@ def main(): parser.add_argument("--data", action="append", default=[], metavar="DATA_DIRECTORY") parser.add_argument("--one-shot", action="append", default=[], metavar="RUN_DIRECTORY") parser.add_argument("--periodic", action="append", default=[], metavar="INDEX_JSON") + parser.add_argument("--spec-summary", action="append", default=[], metavar="SUMMARY_JSON") parser.add_argument("--output", default="system-leaderboard/public/data/all.jsonl") + parser.add_argument("--catalog-output", metavar="CATALOG_JSON", + help="where to write the merged catalog [catalog.json beside --output]") + parser.add_argument("--texts", action="append", default=[], metavar="CATALOG_JSON", + help="repeatable; more names and descriptions for result directories without " + "leaderboard.json, over scripts/leaderboard-catalog.json") parser.add_argument("--format", choices=("jsonl", "json"), default="jsonl", help="jsonl: one record per line, as the web leaderboard reads; json: one array, as " "the Grafana dashboards read [jsonl]") args = parser.parse_args() one_shot_runs = list(args.one_shot) periodic_indexes = list(args.periodic) + spec_summaries = list(args.spec_summary) for data in args.data: one_shot_runs += sorted(os.path.dirname(p) for p in glob.glob(os.path.join(data, "one-shot", "*", "one-shot-summary.csv"))) index = os.path.join(data, "phase3", "runs", "index.json") if os.path.isfile(index): periodic_indexes.append(index) - if not one_shot_runs and not periodic_indexes: - sys.exit("no results found; give --data, --one-shot or --periodic") + spec_summaries += sorted(glob.glob(os.path.join(data, "spec", "*", "*-summary.json"))) + if not one_shot_runs and not periodic_indexes and not spec_summaries: + sys.exit("no results found; give --data, --one-shot, --periodic or --spec-summary") + texts = leaderboard_catalog.load_texts(args.texts) + catalog = leaderboard_catalog.empty_catalog() + query_sets = {} + + def declare(found): + leaderboard_catalog.merge_catalogs(catalog, found[0]) + leaderboard_catalog.merge_query_sets(query_sets, found[1]) + return found[1] + records = [] for run_directory in one_shot_runs: - records.extend(one_shot(run_directory)) + declared = declare(directory_catalog(run_directory, lambda: leaderboard_catalog.one_shot_catalog( + run_directory, summary_truth(run_directory), texts))) + records.extend(one_shot(run_directory, declared)) for index in periodic_indexes: - records.extend(periodic(index)) + declared = declare(directory_catalog( + os.path.dirname(index), lambda: leaderboard_catalog.use_case_catalog(index, texts))) + records.extend(periodic(index, declared)) + by_directory = {} + for path in spec_summaries: + by_directory.setdefault(os.path.dirname(os.path.abspath(path)), []).append(path) + for directory, paths in by_directory.items(): + declared = declare(directory_catalog(directory, lambda: leaderboard_catalog.spec_catalog(paths, texts))) + records.extend(spec(paths, declared)) + withhold_pending(records, query_sets) periodic_speedups(records) + catalog["query_sets"] = query_sets records.sort(key=lambda r: (r["benchmark"], r["workload"], r["mode"] != "exact", r["system"], r["configuration"])) os.makedirs(os.path.dirname(os.path.abspath(args.output)), exist_ok=True) with open(args.output, "w") as file: @@ -324,7 +582,10 @@ def main(): for record in records: file.write(json.dumps(record, sort_keys=True)) file.write("\n") - print(f"{len(records)} records to {args.output}") + catalog_output = args.catalog_output or os.path.join(os.path.dirname(os.path.abspath(args.output)), "catalog.json") + with open(catalog_output, "w") as file: + json.dump(catalog, file, indent=1, sort_keys=True) + print(f"{len(records)} records to {args.output}; catalog to {catalog_output}") if __name__ == "__main__": diff --git a/scripts/test_system_leaderboard_data.py b/scripts/test_system_leaderboard_data.py new file mode 100644 index 00000000..22c4f0d7 --- /dev/null +++ b/scripts/test_system_leaderboard_data.py @@ -0,0 +1,263 @@ +import contextlib +import csv +import importlib.util +import io +import json +import os +import sys +import tempfile +import unittest +from unittest import mock + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import leaderboard_catalog # noqa: E402 + +spec = importlib.util.spec_from_file_location("system_leaderboard_data", + os.path.join(HERE, "system-leaderboard-data.py")) +converter = importlib.util.module_from_spec(spec) +spec.loader.exec_module(converter) + +SUMMARY_FIELDS = ["workload", "engine", "configuration", "query", "status", "runs", "first_run_wall_seconds", + "hot_min_wall_seconds", "hot_median_wall_seconds", "hot_min_engine_seconds", + "max_relative_error", "max_missing_groups", "max_extra_groups", "differing_text_cells", + "truth_runs_agree", "hot_median_peak_memory_bytes", "cpu_and_memory_source", + "hot_median_harness_cpu_seconds"] + + +def write_json(path, value): + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "w") as file: + json.dump(value, file) + + +def one_shot_run(directory, rows, results, summary_md=None): + with open(os.path.join(directory, "one-shot-summary.csv"), "w", newline="") as file: + writer = csv.DictWriter(file, SUMMARY_FIELDS) + writer.writeheader() + for row in rows: + writer.writerow({field: row.get(field, "") for field in SUMMARY_FIELDS}) + with open(os.path.join(directory, "one-shot-tables.csv"), "w", newline="") as file: + writer = csv.DictWriter(file, ["engine", "configuration", "load_seconds", "data_size_bytes"]) + writer.writeheader() + for system, configuration, options in results: + write_json(os.path.join(directory, "results", system, f"w__{configuration}.one-shot.json"), + {"engine": {"id": system}, "configuration": configuration, "workload": "w", + "configuration_options": options, "queries": []}) + if summary_md: + with open(os.path.join(directory, "one-shot-summary.md"), "w") as file: + file.write(summary_md) + + +def row(system, configuration, query, seconds, status="ok", error="0"): + return {"workload": "w", "engine": system, "configuration": configuration, "query": query, + "status": status, "runs": "3", "hot_min_wall_seconds": seconds if status == "ok" else "", + "max_relative_error": error, "truth_runs_agree": "true"} + + +def declared(truth, participants, benchmark="one-shot", workload="w"): + return {f"{benchmark}/{workload}": {"benchmark": benchmark, "workload": workload, "truth": truth, + "truth_description": f"{truth}'s answers", "participants": participants}} + + +class OneShotTest(unittest.TestCase): + def test_mode_reference_and_truth_come_from_the_query_set(self): + with tempfile.TemporaryDirectory() as run: + one_shot_run(run, [row("a", "exact", "1", "2"), row("b", "exact", "1", "1"), + row("b", "fast", "1", "0.5", error="0.1")], + [("a", "exact", {}), ("b", "exact", {}), ("b", "fast", {})]) + query_sets = declared("a/exact", {"a/exact": {"mode": "exact"}, "b/exact": {"mode": "exact"}, + "b/fast": {"mode": "approximate", "reference": "a/exact"}}) + records = {r["system"] + "/" + r["configuration"]: r for r in converter.one_shot(run, query_sets)} + self.assertEqual(records["b/fast"]["baseline"], "a/exact") + self.assertEqual(records["b/fast"]["mode"], "approximate") + self.assertEqual(records["b/fast"]["error_reference"], "a/exact's answers") + self.assertAlmostEqual(records["b/fast"]["speedup_over_baseline"], 4.0) + self.assertIsNone(records["a/exact"]["baseline"]) + + def test_the_generated_query_set_compares_with_the_own_exact_else_the_truth(self): + with tempfile.TemporaryDirectory() as run: + one_shot_run(run, [row("duckdb", "exact", "1", "1"), row("pilotdb", "p", "1", "0.5"), + row("druid", "exact", "1", "1"), row("druid", "defaults", "1", "1")], + [("duckdb", "exact", {}), ("pilotdb", "p", {}), ("druid", "exact", {}), + ("druid", "defaults", {})]) + _, query_sets = leaderboard_catalog.one_shot_catalog(run, "duckdb/exact", leaderboard_catalog.load_texts()) + participants = query_sets["one-shot/w"]["participants"] + self.assertEqual(participants["pilotdb/p"], {"mode": "approximate", "reference": "duckdb/exact"}) + self.assertEqual(participants["druid/defaults"], {"mode": "approximate", "reference": "druid/exact"}) + self.assertEqual(participants["druid/exact"]["mode"], "exact") + self.assertEqual(query_sets["one-shot/w"]["truth"], "duckdb/exact") + + def test_the_truth_is_read_from_a_report_without_a_declaration(self): + for line in ("Accuracy against duckdb/exact.", + "Accuracy against duckdb/exact. The rows of a query without group columns are matched."): + with tempfile.TemporaryDirectory() as run: + with open(os.path.join(run, "one-shot-summary.md"), "w") as file: + file.write(f"# Report\n\n{line}\n") + self.assertEqual(converter.summary_truth(run), "duckdb/exact") + + def test_cpu_per_query_only_where_the_harness_measured_the_engine_s_process(self): + with tempfile.TemporaryDirectory() as run: + measured = {**row("duckdb", "exact", "1", "1"), "cpu_and_memory_source": "the engine's process", + "hot_median_harness_cpu_seconds": "0.25"} + server = {**row("clickhouse", "exact", "1", "1"), "hot_median_harness_cpu_seconds": "0.01"} + one_shot_run(run, [measured, server], [("duckdb", "exact", {}), ("clickhouse", "exact", {})]) + records = {r["system"]: r for r in converter.one_shot(run, {})} + self.assertAlmostEqual(records["duckdb"]["queries"][0]["cpu_seconds"], 0.25) + self.assertIsNone(records["clickhouse"]["queries"][0]["cpu_seconds"]) + + def test_pending_measurements_are_left_out_and_so_is_a_speedup_over_a_pending_reference(self): + with tempfile.TemporaryDirectory() as run: + one_shot_run(run, [row("duckdb", "exact", "1", "1"), row("pilotdb", "p", "1", "0.5", error="0.2")], + [("duckdb", "exact", {}), ("pilotdb", "p", {})]) + query_sets = declared("duckdb/exact", { + "duckdb/exact": {"mode": "exact", "pending": ["time"]}, + "pilotdb/p": {"mode": "approximate", "reference": "duckdb/exact"}}) + records = {r["system"]: r for r in converter.one_shot(run, query_sets)} + converter.withhold_pending(list(records.values()), query_sets) + self.assertEqual(records["duckdb"]["pending"], ["time"]) + self.assertIsNone(records["duckdb"]["geomean_hot_seconds"]) + self.assertIsNone(records["duckdb"]["queries"][0]["hot_min_seconds"]) + self.assertIsNone(records["pilotdb"]["speedup_over_baseline"]) + self.assertAlmostEqual(records["pilotdb"]["geomean_hot_seconds"], 0.5) + self.assertAlmostEqual(records["pilotdb"]["max_relative_error"], 0.2) + + +def periodic_run(run_id, use_case, details): + return {"run_id": run_id, "use_case": use_case, "start": 0, "end": 1, "details": details} + + +def system(median_ms, peaks, cpu=1.0): + return {"median query ms": median_ms, "p99 query ms": median_ms * 2, "cpu seconds": cpu, + "per instance": [{"peak resident bytes": p, "insert samples per second": 10.0, "disk bytes": 5} + for p in peaks]} + + +class PeriodicTest(unittest.TestCase): + def test_reference_and_arm_come_from_the_run_and_latency_per_query_from_its_rows(self): + details = {"reference": "Ref", "candidate": "Cand", "arm_name": "raw-x", + "systems": {"Ref": system(2.0, [100]), "Cand": system(1.0, [30, 50])}, + "promql": {"q1": "sum(x)", "q2": "max(x)"}, "unsupported": {}, + "max_relative_error": {"q1": 0.1}, "reference_vs_truth": {"q1": {"max relative error": 0.0}}, + "fidelity": {"rule": {"agreement": 0.9}}} + with tempfile.TemporaryDirectory() as runs: + write_json(os.path.join(runs, "index.json"), [periodic_run("uc-systems-speed2-whatever-trial2", "uc", + details)]) + write_json(os.path.join(runs, "uc-systems-speed2-whatever-trial2", "low_level.json"), [ + {"metric": "query_latency", "unit": "s", "value": 0.004, "labels": {"arm": "approx", "query": "q1"}}, + {"metric": "query_latency", "unit": "s", "value": 0.002, "labels": {"arm": "approx", "query": "q1"}}, + {"metric": "query_latency", "unit": "s", "value": 0.010, "labels": {"arm": "exact", "query": "q1"}}, + ]) + index = os.path.join(runs, "index.json") + _, query_sets = leaderboard_catalog.use_case_catalog(index, leaderboard_catalog.load_texts()) + records = {r["system"]: r for r in converter.periodic(index, query_sets)} + self.assertEqual(records["Ref"]["configuration"], "exact") + self.assertEqual(records["Ref"]["mode"], "exact") + self.assertEqual(records["Cand"]["configuration"], "raw-x") + self.assertEqual(records["Cand"]["baseline"], "Ref/exact") + self.assertEqual(records["Cand"]["peak_memory_bytes"], 80) + self.assertEqual(records["Cand"]["largest_instance_peak_memory_bytes"], 50) + self.assertEqual(records["Cand"]["instances"], 2) + by_query = {q["query"]: q for q in records["Cand"]["queries"]} + self.assertAlmostEqual(by_query["q1"]["median_query_ms"], 3.0) + self.assertIsNone(by_query["q2"]["median_query_ms"]) + self.assertAlmostEqual({q["query"]: q for q in records["Ref"]["queries"]}["q1"]["median_query_ms"], 10.0) + self.assertEqual(records["Cand"]["decision_agreement"], {"rule": 0.9}) + self.assertEqual(query_sets["periodic/uc"]["queries"], ["q1", "q2"]) + self.assertEqual(query_sets["periodic/uc"]["truth"], "planeval") + + def test_an_older_run_names_its_arm_in_the_run_id(self): + run = periodic_run("uc4-systems-speed1.5-noraw-eps0.01-trial2", "uc", {}) + self.assertEqual(leaderboard_catalog.arm_name(run), "noraw-eps0.01") + run = periodic_run("uc4-systems-bulk-noraw-ignore-eps0.01", "uc", {}) + self.assertEqual(leaderboard_catalog.arm_name(run), "noraw-ignore-eps0.01") + + +def spec_summary(arm, per_query, candidate_instances): + return { + "spec": "/x/js_one.json", "use_case": "promql_workload", "machine": None, "write mode": "bulk", + "ASAPQuery-backend deployment": {"raw_data_retained": True, "raw store": "VictoriaMetrics v1", + "accuracy requirement": {"max_error": 0.01, "failure_probability": 0.01}}, + "systems": {"VictoriaMetrics": {"median query ms": 1.0, "cpu seconds": 5.0, "peak resident bytes": 9}, + "ASAPQuery-backend": {"median query ms": 2.0, "cpu seconds": 50.0, + "per instance": candidate_instances}}, + "per query": per_query, + } + + +class SpecTest(unittest.TestCase): + def test_both_systems_become_records_with_errors_against_the_reference(self): + per_query = { + "q1": {"promql": "sum(x)", "VictoriaMetrics": {"evaluations": 3}, + "ASAPQuery-backend": {"supported": True, "plan": "exact", + "answers against VictoriaMetrics": {"max relative error": 0.25}}}, + "q2": {"promql": "y", "VictoriaMetrics": {"evaluations": 3}, + "ASAPQuery-backend": {"supported": False, "reason": "no valid candidate"}}, + } + instances = [{"queries": ["q1"], "median query ms": 4.0, "peak resident bytes": 7}] + with tempfile.TemporaryDirectory() as directory: + path = os.path.join(directory, "raw-eps0.01-summary.json") + write_json(path, spec_summary("raw-eps0.01", per_query, instances)) + catalog, query_sets = leaderboard_catalog.spec_catalog([path], leaderboard_catalog.load_texts()) + records = {r["system"]: r for r in converter.spec([path], query_sets)} + backend, reference = records["ASAPQuery-backend"], records["VictoriaMetrics"] + self.assertEqual(backend["workload"], "js_one") + self.assertEqual(backend["configuration"], "raw-eps0.01") + self.assertEqual(backend["baseline"], "VictoriaMetrics/exact") + self.assertEqual(backend["error_reference"], "VictoriaMetrics's answers") + self.assertEqual(query_sets["periodic/js_one"]["participants"]["ASAPQuery-backend/raw-eps0.01"], + {"mode": "approximate", "reference": "VictoriaMetrics/exact"}) + self.assertEqual(backend["answered_count"], 1) + by_query = {q["query"]: q for q in backend["queries"]} + self.assertEqual(by_query["q1"]["max_relative_error"], 0.25) + self.assertEqual(by_query["q1"]["median_query_ms"], 4.0) + self.assertEqual(by_query["q2"]["status"], "unsupported") + self.assertEqual(reference["mode"], "exact") + self.assertIsNone(reference["max_relative_error"]) + self.assertIn("raw store (VictoriaMetrics v1)", + catalog["configurations"]["ASAPQuery-backend/raw-eps0.01"]["description"]) + + +class CatalogTest(unittest.TestCase): + def test_wildcards_fill_in_the_options(self): + texts = {"configurations": {"pilotdb/*": {"name": "e {relative_error}", "description": "{missing}"}}} + self.assertEqual(leaderboard_catalog.entry(texts, "configurations", "pilotdb/x", {"relative_error": 0.05}), + {"name": "e 0.05", "description": "{missing}"}) + + def test_a_sidecar_is_merged_participant_by_participant(self): + with tempfile.TemporaryDirectory() as directory: + leaderboard_catalog.write_sidecar(directory, {"systems": {"a": {"name": "A"}}}, + declared("a/exact", {"a/exact": {"mode": "exact"}})) + leaderboard_catalog.write_sidecar(directory, {"systems": {"b": {"name": "B"}}}, + declared("a/exact", {"b/x": {"mode": "approximate", + "reference": "a/exact"}})) + leaderboard_catalog.mark_pending(directory, "one-shot/w", ["b/x"], ["cpu"], "old run") + sidecar = leaderboard_catalog.read_sidecar(directory) + self.assertEqual(set(sidecar["catalog"]["systems"]), {"a", "b"}) + participants = sidecar["query_sets"]["one-shot/w"]["participants"] + self.assertEqual(set(participants), {"a/exact", "b/x"}) + self.assertEqual(participants["b/x"], {"mode": "approximate", "reference": "a/exact", "pending": ["cpu"]}) + self.assertEqual(sidecar["query_sets"]["one-shot/w"]["pending_reason"], "old run") + + def test_the_converter_writes_the_merged_catalog_beside_the_records(self): + with tempfile.TemporaryDirectory() as data, tempfile.TemporaryDirectory() as out: + directory = os.path.join(data, "spec", "js") + os.makedirs(directory) + write_json(os.path.join(directory, "noraw-summary.json"), spec_summary("noraw", {}, [])) + leaderboard_catalog.write_sidecar(directory, *leaderboard_catalog.spec_catalog( + [os.path.join(directory, "noraw-summary.json")], leaderboard_catalog.load_texts())) + leaderboard_catalog.write_sidecar(directory, {"workloads": {"js_one": {"name": "Private"}}}) + argv = ["x", "--data", data, "--output", os.path.join(out, "all.jsonl")] + with mock.patch.object(sys, "argv", argv), contextlib.redirect_stdout(io.StringIO()): + converter.main() + with open(os.path.join(out, "catalog.json")) as file: + catalog = json.load(file) + with open(os.path.join(out, "all.jsonl")) as file: + records = [json.loads(line) for line in file] + self.assertEqual(catalog["workloads"]["js_one"]["name"], "Private") + self.assertEqual({r["configuration"] for r in records}, {"exact", "noraw"}) + self.assertIn("periodic/js_one", catalog["query_sets"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/use_cases/run_use_case_on_systems.py b/scripts/use_cases/run_use_case_on_systems.py index f0d04490..682d284d 100644 --- a/scripts/use_cases/run_use_case_on_systems.py +++ b/scripts/use_cases/run_use_case_on_systems.py @@ -17,10 +17,12 @@ import urllib.request sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "dataset_tools")) +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import bounds import cases import data_root +import leaderboard_catalog import run_use_case as in_process import scenario from approx_rows import row, write_run @@ -1004,10 +1006,13 @@ def returned_by_time(query): def evaluation_counts(query): - returned = [c.get("series_returned") for c in query.get("costs", [])] + costs = query.get("costs", []) + returned = [c.get("series_returned") for c in costs] + seconds = [c["query_seconds"] for c in costs if isinstance(c.get("query_seconds"), (int, float))] return {"evaluations": query.get("evaluations", len(returned)), "failed evaluations": query.get("failed_evaluations", 0), - "empty evaluations": sum(r == 0 for r in returned)} + "empty evaluations": sum(r == 0 for r in returned), + "median query ms": statistics.median(seconds) * 1000 if seconds else None} def plan_text(plans, query): @@ -1111,6 +1116,10 @@ def run_spec_trial(args, spec_path, spec, name, workdir): report = { "spec": spec_path, "use_case": use_case_label(spec), + "workload": name, + "reference": names[0], + "candidate": names[1], + "arm": arm, "start_ms": spec["start_ms"], "duration_ms": spec["duration_ms"], "queries": len(spec["queries"]), @@ -1137,6 +1146,8 @@ def run_spec_trial(args, spec_path, spec, name, workdir): json.dump(report, f, indent=1) print(f"{name} {arm}: {report[f'supported by {names[1]}']} of {len(spec['queries'])} queries supported by " f"{names[1]} in {len(groups)} instances; {out}", file=sys.stderr) + leaderboard_catalog.write_sidecar(workdir, *leaderboard_catalog.spec_catalog( + [out], leaderboard_catalog.load_texts())) def main(argv=None): @@ -1253,6 +1264,9 @@ def run_case_trial(args, case, arms, spec_path, spec, run_prefix, workdir, truth continue details = { "arm": arm_details(args, arm), + "arm_name": arm, + "reference": names[0], + "candidate": names[1], "trial": trial, "plans": {q["id"]: plan_text(plans, q) for q in spec["queries"] if q["id"] not in unsupported}, "unsupported": {q: f"not supported by {names[1]}: {reason}" for q, reason in unsupported.items()}, @@ -1278,6 +1292,9 @@ def run_case_trial(args, case, arms, spec_path, spec, run_prefix, workdir, truth details["rules"] = {name: rule["description"] for name, rule in case["rules"].items()} details["signal_dashboards"] = {name: "rules" for name in case["rules"]} write_arm(args.data, case, run_id, exact, approx, unsupported, details, spec, names[1]) + runs = os.path.join(args.data, "runs") + leaderboard_catalog.write_sidecar(runs, *leaderboard_catalog.use_case_catalog( + os.path.join(runs, "index.json"), leaderboard_catalog.load_texts())) if __name__ == "__main__": diff --git a/scripts/use_cases/test_run_use_case_on_systems.py b/scripts/use_cases/test_run_use_case_on_systems.py index f2d6638a..c4e89025 100644 --- a/scripts/use_cases/test_run_use_case_on_systems.py +++ b/scripts/use_cases/test_run_use_case_on_systems.py @@ -321,7 +321,13 @@ def test_empty_and_failed_evaluations(self): query = {"evaluations": 3, "failed_evaluations": 1, "costs": [{"series_returned": 0}, {"series_returned": 2}, {"series_returned": None}]} self.assertEqual(evaluation_counts(query), - {"evaluations": 3, "failed evaluations": 1, "empty evaluations": 1}) + {"evaluations": 3, "failed evaluations": 1, "empty evaluations": 1, + "median query ms": None}) + + def test_median_query_time_of_the_evaluations_that_were_timed(self): + query = {"costs": [{"query_seconds": 0.001}, {"query_seconds": 0.003}, {"query_seconds": 0.002}, + {"series_returned": 1}]} + self.assertAlmostEqual(evaluation_counts(query)["median query ms"], 2.0) class BenchmarkExternalTest(unittest.TestCase): diff --git a/system-leaderboard/src/App.jsx b/system-leaderboard/src/App.jsx index 6c897e6e..077e870d 100644 --- a/system-leaderboard/src/App.jsx +++ b/system-leaderboard/src/App.jsx @@ -1,12 +1,9 @@ import { Routes, Route } from "react-router-dom"; import Navbar from "./components/Navbar"; import Home from "./pages/Home"; -import ResultTable from "./pages/ResultTable"; -import AccuracyVsCost from "./pages/AccuracyVsCost"; +import QuerySet from "./pages/QuerySet"; import ResultDetails from "./pages/ResultDetails"; -import Throughput from "./pages/Throughput"; -import Visualization from "./pages/Visualization"; -import DecisionSupport from "./pages/DecisionSupport"; +import SourcesBar from "./components/SourcesBar"; import { BenchmarkDataProvider } from "./context/BenchmarkDataContext"; import DataHealthGate from "./components/DataHealthGate"; @@ -14,16 +11,13 @@ function App() { return ( + } /> - } /> + } /> } /> - } /> - } /> - } /> - } /> diff --git a/system-leaderboard/src/components/BaselineLink.jsx b/system-leaderboard/src/components/BaselineLink.jsx index e4d2e12c..273c7676 100644 --- a/system-leaderboard/src/components/BaselineLink.jsx +++ b/system-leaderboard/src/components/BaselineLink.jsx @@ -1,14 +1,22 @@ import { Link } from "react-router-dom"; +import { useBenchmarkData } from "../hooks/useBenchmarkData"; import { baselineIndex } from "../utils/metrics"; +import { referenceName } from "../utils/catalog"; function BaselineLink({ records, item }) { + const { catalog } = useBenchmarkData(); if (item.mode === "exact") { return reference; } if (!item.baseline) return -; + const label = referenceName(catalog, item.workload, item.baseline); const index = baselineIndex(records, item); - if (index < 0) return {item.baseline}; - return {item.baseline}; + if (index < 0) return {label}; + return ( + + {label} + + ); } export default BaselineLink; diff --git a/system-leaderboard/src/components/DataHealthGate.jsx b/system-leaderboard/src/components/DataHealthGate.jsx index 1e3311ef..5448c5ea 100644 --- a/system-leaderboard/src/components/DataHealthGate.jsx +++ b/system-leaderboard/src/components/DataHealthGate.jsx @@ -4,7 +4,7 @@ import "./DataHealthGate.css"; function group(problems) { const byKind = new Map(); for (const p of problems) { - const key = `${p.field}::${p.message}`; + const key = `${p.source ?? ""}::${p.field}::${p.message}`; const seen = byKind.get(key); if (seen) { seen.count += 1; @@ -20,13 +20,16 @@ function ProblemList({ items }) { return (
    {items.map((p) => ( -
  • +
  • {p.field} {p.message} - {p.count > 1 - ? `${p.count} records, first at line ${p.firstLine}` - : `line ${p.firstLine}`} + {p.source ? `${p.source}: ` : ""} + {p.firstLine == null + ? `${p.count} records` + : p.count > 1 + ? `${p.count} records, first at line ${p.firstLine}` + : `line ${p.firstLine}`}
  • ))} @@ -52,7 +55,7 @@ function FailurePanel({ error }) {

    {versionOnly ? ( <> - data/all.jsonl was written by a different version of{" "} + The published records were written by a different version of{" "} scripts/system-leaderboard-data.py. Nothing is damaged — the file simply predates the schema this app reads. Regenerate it with scripts/leaderboard-data.sh web or{" "} @@ -61,10 +64,10 @@ function FailurePanel({ error }) { ) : ( <> - data/all.jsonl is not what{" "} + The published records are not what{" "} scripts/system-leaderboard-data.py wrote. Rather than rank on values that may be wrong, the pages are held back until the - file is replaced. + files are replaced. )}

    diff --git a/system-leaderboard/src/components/ErrorVsTime.jsx b/system-leaderboard/src/components/ErrorVsTime.jsx new file mode 100644 index 00000000..d1781493 --- /dev/null +++ b/system-leaderboard/src/components/ErrorVsTime.jsx @@ -0,0 +1,207 @@ +import { useState } from "react"; +import { + CartesianGrid, + ReferenceLine, + ResponsiveContainer, + Scatter, + ScatterChart, + Tooltip, + XAxis, + YAxis, +} from "recharts"; +import { useBenchmarkData } from "../hooks/useBenchmarkData"; +import { recordName } from "../utils/catalog"; +import { isPending } from "../utils/querySets"; +import { compareRecords, queryTimeBasis } from "../utils/compare"; +import { fmtError, fmtRatio, fmtSpeed, finiteNumber } from "../utils/metrics"; + +const COLORS = [ + "#1f77b4", + "#ff7f0e", + "#2ca02c", + "#d62728", + "#9467bd", + "#8c564b", + "#e377c2", + "#17becf", +]; + +const ERRORS = { median: "Median error", max: "Max error" }; + +function pointsOf(set, catalog, which) { + const points = []; + const skipped = []; + for (const p of set.approximate) { + const name = recordName(catalog, { ...p, workload: set.workload }); + const reference = set.participants.find((o) => o.key === p.reference); + if (!p.record || !reference?.record) { + skipped.push([name, "no results of it or of what it is compared with"]); + continue; + } + if (isPending(p, "time") || isPending(reference, "time")) { + skipped.push([name, "time awaiting rerun"]); + continue; + } + if (isPending(p, "accuracy")) { + skipped.push([name, "accuracy awaiting rerun"]); + continue; + } + const c = compareRecords(reference.record, p.record, set.queries.length); + const ratio = c.timeRatio ?? c.latencyRatio; + const error = c.toError[which]; + if (ratio == null) { + skipped.push([name, "no time on the queries both answered"]); + continue; + } + if (error === "inf") { + skipped.push([name, `infinite ${which} error`]); + continue; + } + if (finiteNumber(error) == null) { + skipped.push([name, "no error recorded"]); + continue; + } + points.push({ + name, + reference: recordName(catalog, { ...reference, workload: set.workload }), + x: ratio, + y: error * 100, + common: c.common, + total: c.total, + perQuery: c.timeRatio != null, + }); + } + return { points, skipped }; +} + +function logTicks(points) { + const xs = points.map((p) => p.x); + const low = Math.floor(Math.log10(Math.min(...xs, 1) / 1.5)); + const high = Math.ceil(Math.log10(Math.max(...xs, 1) * 1.5)); + const ticks = []; + for (let e = low; e <= high; e++) ticks.push(10 ** e); + return ticks; +} + +function ErrorVsTime({ set }) { + const { catalog } = useBenchmarkData(); + const [which, setWhich] = useState("median"); + const { points, skipped } = pointsOf(set, catalog, which); + + return ( + <> +

    + One point per approximate participant: across, its query time over the + time of what it is compared with (below 1 is faster;{" "} + {queryTimeBasis(set.benchmark) ?? "query time"}, geometric mean of the + per-query ratios); up, its error against the truth on the same queries. +

    +
    + {Object.entries(ERRORS).map(([key, label]) => ( + + ))} +
    + {points.length > 0 ? ( +
    + + + + Math.min(min, 1) / 1.5, + (max) => Math.max(max, 1) * 1.5, + ]} + ticks={logTicks(points)} + allowDataOverflow + tickFormatter={(v) => `${v}×`} + label={{ + value: "Query time over what it is compared with", + position: "insideBottom", + offset: -15, + }} + /> + `${v}%`} + label={{ + value: `${ERRORS[which]} (%)`, + angle: -90, + position: "insideLeft", + }} + /> + + { + if (!active || !payload?.length) return null; + const point = payload[0].payload; + return ( +
    + {point.name} +
    compared with {point.reference}
    +
    + {fmtSpeed(point.x)} ({fmtRatio(point.x)}) + {!point.perQuery && ", whole-run median latencies"} +
    +
    + {ERRORS[which]}: {fmtError(point.y / 100)} +
    +
    + {point.common} of {point.total} queries both answered +
    +
    + ); + }} + /> + {points.map((point, i) => ( + + ))} +
    +
    +
    + ) : ( +

    Nothing to plot yet.

    + )} + {points.length > 0 && ( +
      + {points.map((point, i) => ( +
    • + + {point.name}: {fmtSpeed(point.x)}, {ERRORS[which].toLowerCase()}{" "} + {fmtError(point.y / 100)} +
    • + ))} +
    + )} + {skipped.length > 0 && ( +

    + Not plotted:{" "} + {skipped.map(([name, why]) => `${name} (${why})`).join("; ")}. +

    + )} + + ); +} + +export default ErrorVsTime; diff --git a/system-leaderboard/src/components/Navbar.jsx b/system-leaderboard/src/components/Navbar.jsx index 81450f32..c25a6bcc 100644 --- a/system-leaderboard/src/components/Navbar.jsx +++ b/system-leaderboard/src/components/Navbar.jsx @@ -1,44 +1,62 @@ +import { useRef } from "react"; import { Link } from "react-router-dom"; +import { useBenchmarkData } from "../hooks/useBenchmarkData"; + +const linkStyle = { color: "white", textDecoration: "none" }; + +const PAGES = [["/", "Query sets"]]; function Navbar() { + const { title, addLocalFiles } = useBenchmarkData(); + const input = useRef(null); + return ( ); } diff --git a/system-leaderboard/src/components/PairComparison.jsx b/system-leaderboard/src/components/PairComparison.jsx new file mode 100644 index 00000000..82695559 --- /dev/null +++ b/system-leaderboard/src/components/PairComparison.jsx @@ -0,0 +1,318 @@ +import { useState } from "react"; +import { isPending } from "../utils/querySets"; +import { + answered, + compareRecords, + queryTime, + queryTimeBasis, +} from "../utils/compare"; +import { + fmtCount, + fmtCpu, + fmtError, + fmtMemory, + fmtRatio, + fmtSeconds, + fmtSpeed, +} from "../utils/metrics"; +import { useBenchmarkData } from "../hooks/useBenchmarkData"; +import { nameOf } from "../utils/catalog"; +import { Measured, ParticipantName, Pending, Sub } from "./QuerySetCells"; + +function defaults(choices) { + const to = choices.find((p) => p.mode !== "exact") ?? choices[1]; + const from = + choices.find((p) => p.key === to?.reference) ?? + choices.find((p) => p !== to); + return [from?.key ?? "", to?.key ?? ""]; +} + +function Picker({ label, value, onChange, choices, workload }) { + const { catalog } = useBenchmarkData(); + return ( + + ); +} + +function RatioCell({ pending, ratio, from, to, format }) { + if (pending) return ; + return ( + <> + {fmtRatio(ratio)} + {(from != null || to != null) && ( + + {format(to)} vs {format(from)} + + )} + + ); +} + +function PairComparison({ set }) { + const choices = set.participants.filter((p) => p.record); + const [initialFrom, initialTo] = defaults(choices); + const [fromKey, setFromKey] = useState(initialFrom); + const [toKey, setToKey] = useState(initialTo); + const from = choices.find((p) => p.key === fromKey); + const to = choices.find((p) => p.key === toKey); + + if (choices.length < 2) { + return

    Fewer than two participants loaded.

    ; + } + + const controls = ( +
    + + + +
    + ); + + if (!from || !to || from === to) { + return ( + <> + {controls} +

    Pick two different participants.

    + + ); + } + + const c = compareRecords(from.record, to.record, set.queries.length); + const either = (m) => isPending(from, m) || isPending(to, m); + const periodic = set.benchmark === "periodic"; + const perQuery = c.timeRatio != null; + const timeRatio = perQuery ? c.timeRatio : c.latencyRatio; + const fromAnswered = answered(from.record); + const toAnswered = answered(to.record); + const common = set.queries.filter( + (q) => fromAnswered.has(q) && toAnswered.has(q), + ); + const ownReference = to.reference === from.key; + + return ( + <> + {controls} +

    + What changes when the queries move from the first to the second, over + the queries both answered. Time is the geometric mean of the per-query + ratios ({queryTimeBasis(set.benchmark) ?? "query time"}); memory and CPU + are ratios of the whole runs. A ratio is the second over the first. +

    + + + + + + + {!periodic && } + {periodic && ( + <> + + + + )} + + + {periodic && ownReference && } + + + + + + + + {!periodic && ( + + )} + {periodic && ( + <> + + + + )} + + + {periodic && ownReference && ( + + )} + + +
    Both answeredQuery timePeak memoryCPUQuery CPUIngest CPUError against truth, firstError against truth, secondDecision agreement
    + {fmtCount(c.common, c.total)} + + first answered {c.fromAnswered}, second {c.toAnswered} + + + + {fmtSpeed(timeRatio)} + + {perQuery + ? `over ${c.timed} queries` + : timeRatio != null + ? "whole-run median latencies; no per-query times recorded" + : "no time recorded"} + + + + + + + {fmtRatio(c.perQueryCpuRatio)} + {c.cpuTimed > 0 && over {c.cpuTimed} queries} + + + + + + + + {fmtError(c.fromError.median)} + max {fmtError(c.fromError.max)} + + + + {fmtError(c.toError.median)} + max {fmtError(c.toError.max)} + + + + {c.agreement + ? Object.entries(c.agreement).map(([rule, value]) => ( +
    + {rule}:{" "} + {value != null ? `${(value * 100).toFixed(1)}%` : "—"} +
    + )) + : "—"} +
    +
    + +
    + The {common.length} queries both answered + + + + + + + + + + + + + {common.map((query) => { + const a = fromAnswered.get(query); + const b = toAnswered.get(query); + const ta = queryTime(set.benchmark, a); + const tb = queryTime(set.benchmark, b); + return ( + + + + + + + + + ); + })} + +
    Query + Time,{" "} + + + Time,{" "} + + Second / firstError, firstError, second
    + {query} + + + {fmtSeconds(ta)} + + + + {fmtSeconds(tb)} + + + + {ta && tb ? fmtRatio(tb / ta) : "—"} + + + + {fmtError(a.max_relative_error)} + + + + {fmtError(b.max_relative_error)} + +
    +
    + + ); +} + +export default PairComparison; diff --git a/system-leaderboard/src/components/QuerySetCells.jsx b/system-leaderboard/src/components/QuerySetCells.jsx new file mode 100644 index 00000000..eab94446 --- /dev/null +++ b/system-leaderboard/src/components/QuerySetCells.jsx @@ -0,0 +1,33 @@ +import { useBenchmarkData } from "../hooks/useBenchmarkData"; +import { descriptionOf, nameOf } from "../utils/catalog"; + +export function Pending() { + return awaiting rerun; +} + +export function Measured({ pending, children }) { + return pending ? : children; +} + +export function Sub({ children }) { + return
    {children}
    ; +} + +export function ParticipantName({ participant, workload, showId = true }) { + const { catalog } = useBenchmarkData(); + const item = { ...participant, workload }; + const system = nameOf(catalog, "system", item); + const configuration = nameOf(catalog, "configuration", item); + const description = [ + descriptionOf(catalog, "system", item), + descriptionOf(catalog, "configuration", item), + ] + .filter(Boolean) + .join("\n\n"); + return ( + + {system} · {configuration} + {showId &&
    {participant.key}
    } +
    + ); +} diff --git a/system-leaderboard/src/components/RecordName.jsx b/system-leaderboard/src/components/RecordName.jsx new file mode 100644 index 00000000..c6028a2b --- /dev/null +++ b/system-leaderboard/src/components/RecordName.jsx @@ -0,0 +1,57 @@ +import { useBenchmarkData } from "../hooks/useBenchmarkData"; +import { descriptionOf, nameOf } from "../utils/catalog"; + +const idStyle = { color: "#888", fontSize: "0.8em" }; + +export function CatalogName({ kind, item, showId = true }) { + const { catalog } = useBenchmarkData(); + const name = nameOf(catalog, kind, item); + const id = + kind === "system" + ? item.system + : kind === "configuration" + ? item.configuration + : kind === "workload" + ? item.workload + : item.benchmark; + const description = descriptionOf(catalog, kind, item); + return ( + + {name} + {showId && id && id !== name &&
    {id}
    } +
    + ); +} + +export function SourceTag({ item }) { + const { localSources } = useBenchmarkData(); + if (!localSources.has(item.source)) return null; + return ( + + local + + ); +} + +export function InstancesWarning({ item }) { + if (!(item.instances > 1)) return null; + return ( +
    + ⚠ {item.instances} instances +
    + ); +} diff --git a/system-leaderboard/src/components/SourcesBar.jsx b/system-leaderboard/src/components/SourcesBar.jsx new file mode 100644 index 00000000..7c8e6fdc --- /dev/null +++ b/system-leaderboard/src/components/SourcesBar.jsx @@ -0,0 +1,89 @@ +import { useBenchmarkData } from "../hooks/useBenchmarkData"; + +const chip = { + display: "inline-flex", + alignItems: "center", + gap: "6px", + border: "1px solid #ddd", + borderRadius: "999px", + padding: "2px 10px", + fontSize: "0.85em", + background: "#fafafa", +}; + +function SourcesBar() { + const { sources, localSources, rejected, removeLocal } = useBenchmarkData(); + if (sources.length === 0 && rejected.length === 0) return null; + + return ( +
    + Results from: + {sources.map((s) => { + const local = localSources.has(s.name); + return ( + + {local && local} + {s.name} + + {s.records.length > 0 + ? `${s.records.length} records` + : "names and descriptions"} + + {local && ( + + )} + + ); + })} + {rejected.map((s) => ( + p.severity === "error") + .slice(0, 5) + .map((p) => `line ${p.line ?? "—"}: ${p.field} — ${p.message}`) + .join("\n")} + > + not opened: {s.name} ( + {s.problems.filter((p) => p.severity === "error").length} errors) + + ))} +
    + ); +} + +export default SourcesBar; diff --git a/system-leaderboard/src/context/BenchmarkDataContext.jsx b/system-leaderboard/src/context/BenchmarkDataContext.jsx index a0795b33..4ab5971c 100644 --- a/system-leaderboard/src/context/BenchmarkDataContext.jsx +++ b/system-leaderboard/src/context/BenchmarkDataContext.jsx @@ -1,21 +1,34 @@ -import { useEffect, useState } from "react"; -import { loadBenchmarkData } from "../utils/loadJson"; +import { useCallback, useEffect, useMemo, useState } from "react"; +import { loadPublishedSources, readLocalFile } from "../utils/loadJson"; +import { SchemaViolation, baselineProblems } from "../utils/benchmarkRecord"; +import { mergeCatalogs } from "../utils/catalog"; import { BenchmarkDataContext } from "./benchmarkDataContextValue"; +const hasErrors = (source) => + source.problems.some((p) => p.severity === "error"); + export function BenchmarkDataProvider({ children }) { - const [records, setRecords] = useState([]); - const [problems, setProblems] = useState([]); + const [published, setPublished] = useState([]); + const [local, setLocal] = useState([]); + const [rejected, setRejected] = useState([]); + const [title, setTitle] = useState(null); + const [description, setDescription] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { let cancelled = false; - loadBenchmarkData() + loadPublishedSources() .then((data) => { if (cancelled) return; - setRecords(data.records); - setProblems(data.problems); + const problems = data.sources.flatMap((s) => s.problems); + if (data.sources.some(hasErrors)) { + throw new SchemaViolation(problems); + } + setPublished(data.sources); + setTitle(data.title); + setDescription(data.description); }) .catch((err) => { if (!cancelled) setError(err); @@ -29,10 +42,74 @@ export function BenchmarkDataProvider({ children }) { }; }, []); + const addLocalFiles = useCallback(async (files) => { + const read = []; + const refused = []; + for (const file of files) { + try { + const source = await readLocalFile(file); + if (hasErrors(source)) refused.push(source); + else read.push(source); + } catch (err) { + refused.push({ + name: file.name, + problems: [ + { + line: null, + field: "(file)", + severity: "error", + message: err.message, + }, + ], + }); + } + } + setLocal((current) => [ + ...current.filter((s) => !read.some((r) => r.name === s.name)), + ...read, + ]); + setRejected(refused); + }, []); + + const removeLocal = useCallback((name) => { + setLocal((current) => current.filter((s) => s.name !== name)); + }, []); + + const value = useMemo(() => { + const sources = [...published, ...local]; + const records = sources.flatMap((s) => s.records); + const problems = [ + ...sources.flatMap((s) => s.problems), + ...baselineProblems(records), + ]; + return { + records, + problems, + catalog: mergeCatalogs(sources.map((s) => s.catalog)), + sources, + localSources: new Set(local.map((s) => s.name)), + rejected, + title, + description, + loading, + error, + addLocalFiles, + removeLocal, + }; + }, [ + published, + local, + rejected, + title, + description, + loading, + error, + addLocalFiles, + removeLocal, + ]); + return ( - + {children} ); diff --git a/system-leaderboard/src/pages/AccuracyVsCost.css b/system-leaderboard/src/pages/AccuracyVsCost.css deleted file mode 100644 index 5ddc50e3..00000000 --- a/system-leaderboard/src/pages/AccuracyVsCost.css +++ /dev/null @@ -1,90 +0,0 @@ -.workload-filter { - display: flex; - align-items: center; - gap: 18px; - flex-wrap: wrap; -} - -.workload-filter strong { - margin-right: 6px; -} - -.checkbox-label { - display: flex; - align-items: center; - gap: 6px; - padding: 6px 10px; - border: 1px solid #dcdcdc; - border-radius: 6px; - background: #fff; - cursor: pointer; - transition: all 0.2s ease; - user-select: none; -} - -.checkbox-label:hover { - background: #f5f5f5; - border-color: #1976d2; -} - -.checkbox-label input[type="checkbox"] { - width: 16px; - height: 16px; - cursor: pointer; -} - -.warning-message { - margin: 12px 0; - padding: 10px 14px; - border: 1px solid #ffeeba; - border-radius: 6px; - background-color: #fff3cd; - color: #856404; - font-size: 14px; -} - -.accuracy-container { - padding: 20px; -} - -.page-description { - margin-bottom: 20px; - color: #555; -} - -.control-panel { - margin: 20px 0; - display: flex; - align-items: center; - gap: 12px; -} - -.metric-select { - padding: 6px 10px; - font-size: 14px; - border: 1px solid #ccc; - border-radius: 4px; - background-color: white; - cursor: pointer; -} - -.chart-container { - height: 500px; - border: 2px dashed #bbb; - border-radius: 8px; - padding: 20px; - background-color: #fafafa; - margin: 20px 0; -} - -.summary-section { - margin-top: 20px; -} - -.summary-section h3 { - margin-bottom: 10px; -} - -.summary-section p { - margin: 6px 0; -} diff --git a/system-leaderboard/src/pages/AccuracyVsCost.jsx b/system-leaderboard/src/pages/AccuracyVsCost.jsx deleted file mode 100644 index f85efb52..00000000 --- a/system-leaderboard/src/pages/AccuracyVsCost.jsx +++ /dev/null @@ -1,454 +0,0 @@ -import { useState } from "react"; -import { useBenchmarkData } from "../hooks/useBenchmarkData"; -import { - workloadsOf, - finiteNumber, - isInfinite, - queryLatencySeconds, - fmtSeconds, -} from "../utils/metrics"; - -import { - ScatterChart, - Scatter, - CartesianGrid, - XAxis, - YAxis, - Tooltip, - ResponsiveContainer, - Legend, -} from "recharts"; - -import "./AccuracyVsCost.css"; - -const SYSTEM_COLORS = [ - "#1f77b4", - "#ff7f0e", - "#2ca02c", - "#d62728", - "#9467bd", - "#8c564b", - "#e377c2", - "#7f7f7f", - "#bcbd22", - "#17becf", -]; - -function AccuracyVsCost() { - const { records: results } = useBenchmarkData(); - const [selectedMetric, setSelectedMetric] = useState("time"); - const [errorMetric, setErrorMetric] = useState("median"); - const [chosenWorkloads, setSelectedWorkloads] = useState(null); - const [xAxisScale, setXAxisScale] = useState("log"); - const [message, setMessage] = useState(""); - - const workloads = workloadsOf(results); - const selectedWorkloads = - chosenWorkloads ?? (workloads.length > 0 ? [workloads[0]] : []); - - const benchmarkOf = (workload) => - results.find((r) => r.workload === workload)?.benchmark; - - const selectedBenchmark = - selectedWorkloads.length > 0 ? benchmarkOf(selectedWorkloads[0]) : null; - - function getCostValue(item, metric) { - switch (metric) { - case "memory": - return finiteNumber(item.peak_memory_bytes); - - case "time": - return queryLatencySeconds(item); - - case "cpu": - return finiteNumber(item.cpu_seconds); - - default: - return null; - } - } - - function generateLogTicks(min, max) { - if (min <= 0 || max <= 0) return []; - - const ticks = []; - - let tick = 2 ** Math.floor(Math.log2(min)); - - while (tick <= max) { - if (tick >= min) { - ticks.push(tick); - } - - tick *= 2; - } - - return ticks; - } - - function getXAxisLabel(metric) { - switch (metric) { - case "memory": - return "Peak Memory"; - - case "time": - return selectedBenchmark === "periodic" - ? "Median Query Latency" - : "Geomean Query Time"; - - case "cpu": - return "CPU Time"; - - default: - return ""; - } - } - - const yLabel = - errorMetric === "max" - ? "Max Relative Error (%)" - : "Median Relative Error (%)"; - - function getErrorValue(item) { - return errorMetric === "max" - ? item.max_relative_error - : item.median_relative_error; - } - - const allPoints = results - .filter((item) => selectedWorkloads.includes(item.workload)) - .map((item) => ({ - x: getCostValue(item, selectedMetric), - error: getErrorValue(item), - system: item.system, - configuration: item.configuration, - mode: item.mode, - baseline: item.baseline, - workload: item.workload, - })); - - const skippedPoints = allPoints - .map((point) => { - if (isInfinite(point.error) || point.error === "nan") - return { ...point, reason: "infinite error" }; - if (point.error == null) return { ...point, reason: "no error value" }; - if (point.x == null) - return { - ...point, - reason: `no ${getXAxisLabel(selectedMetric).toLowerCase()} measured`, - }; - if (xAxisScale === "log" && point.x <= 0) - return { ...point, reason: "zero cost on a log scale" }; - return null; - }) - .filter(Boolean); - - const plottedData = allPoints - .filter( - (point) => - typeof point.error === "number" && - point.x != null && - (xAxisScale !== "log" || point.x > 0), - ) - .map((point) => ({ ...point, y: point.error * 100 })); - - const positiveXValues = plottedData - .map((item) => item.x) - .filter((value) => value > 0); - - const logTicks = - selectedMetric === "memory" && - xAxisScale === "log" && - positiveXValues.length > 0 - ? generateLogTicks( - Math.min(...positiveXValues), - Math.max(...positiveXValues), - ) - : undefined; - - const systems = [...new Set(results.map((item) => item.system))]; - const systemColor = (system) => - SYSTEM_COLORS[systems.indexOf(system) % SYSTEM_COLORS.length]; - - const groupedData = {}; - plottedData.forEach((item) => { - const series = `${item.system} (${item.mode})`; - if (!groupedData[series]) { - groupedData[series] = { system: item.system, mode: item.mode, data: [] }; - } - - groupedData[series].data.push(item); - }); - - function toggleWorkload(workload) { - if (selectedWorkloads.includes(workload)) { - setSelectedWorkloads(selectedWorkloads.filter((w) => w !== workload)); - return; - } - - if (selectedWorkloads.length === 0) { - setSelectedWorkloads([workload]); - return; - } - - if (benchmarkOf(workload) === selectedBenchmark) { - setSelectedWorkloads([...selectedWorkloads, workload]); - } else { - setMessage( - "These workloads come from different benchmarks (one-shot and periodic) and their costs cannot be compared together.", - ); - - setTimeout(() => { - setMessage(""); - }, 3000); - } - } - - function formatMemory(value) { - if (value >= 1024 ** 3) { - return `${(value / 1024 ** 3).toFixed(2)} GB`; - } - - if (value >= 1024 ** 2) { - return `${(value / 1024 ** 2).toFixed(2)} MB`; - } - - if (value >= 1024) { - return `${(value / 1024).toFixed(2)} KB`; - } - - return `${value} B`; - } - - const formatX = (value) => - selectedMetric === "memory" ? formatMemory(value) : fmtSeconds(value); - - return ( -
    -

    Accuracy vs Cost Tradeoff

    - -

    - Compare the tradeoff between system accuracy and different cost metrics. - Diamonds are exact systems, the reference; circles are approximate - systems, each compared with the exact system named in its tooltip. -

    - -
    - -
    - - - - - - - - - - - -
    - -
    - Workloads: - - {workloads.map((workload) => ( - - ))} -
    - - {message &&
    {message}
    } -
    - -
    - - - - - min / 1.5, (max) => max * 1.5] - : ["auto", "auto"] - } - ticks={xAxisScale === "log" ? logTicks : undefined} - allowDataOverflow={xAxisScale === "log"} - label={{ - value: getXAxisLabel(selectedMetric), - position: "insideBottom", - offset: -10, - }} - tickFormatter={formatX} - /> - - - - { - if (!active || !payload || payload.length === 0) return null; - - const point = payload[0].payload; - - return ( -
    - {point.system} - -
    - - {point.configuration} - -
    - - {point.workload} - -
    - - {point.mode === "exact" - ? "Exact (reference)" - : `Approximate, compared with ${point.baseline ?? "—"}`} - -
    - -
    - {getXAxisLabel(selectedMetric)}:{" "} - {formatX(point.x)} -
    - -
    - {yLabel}: {point.y.toFixed(4)} -
    -
    - ); - }} - /> - - - - {Object.entries(groupedData).map(([series, group]) => ( - - ))} -
    -
    -
    - - {skippedPoints.length > 0 && ( -
    - - Skipped data points ({skippedPoints.length}) — infinite errors and - missing costs are not plotted - - -
    - {skippedPoints.map((point, index) => ( -
    - {point.system} - {" — "} - {point.configuration} - {" — "} - {point.workload} - {" — "} - {point.reason} -
    - ))} -
    -
    - )} - -
    - -
    -

    Dataset Summary

    - -

    Total Records Loaded: {results.length}

    - -

    Points Plotted: {plottedData.length}

    - -

    Skipped Points: {skippedPoints.length}

    - -

    Current Cost Metric: {getXAxisLabel(selectedMetric)}

    - -

    - Selected Workloads:{" "} - {selectedWorkloads.length === 0 - ? "None" - : selectedWorkloads.join(", ")} -

    -
    -
    - ); -} - -export default AccuracyVsCost; diff --git a/system-leaderboard/src/pages/DecisionSupport.jsx b/system-leaderboard/src/pages/DecisionSupport.jsx deleted file mode 100644 index b8a43db6..00000000 --- a/system-leaderboard/src/pages/DecisionSupport.jsx +++ /dev/null @@ -1,471 +0,0 @@ -import { useMemo, useState } from "react"; -import { useBenchmarkData } from "../hooks/useBenchmarkData"; -import ModeBadge from "../components/ModeBadge"; -import BaselineLink from "../components/BaselineLink"; -import { - workloadsOf, - finiteNumber, - isInfinite, - queryThroughput, - fmtMemory, -} from "../utils/metrics"; -import "./ResultTable.css"; - -function errorPct(item) { - const v = item.median_relative_error; - if (isInfinite(v) || v === "nan") return Infinity; - const n = finiteNumber(v); - return n != null ? +(n * 100).toFixed(3) : null; -} - -function toBytes(value, unit) { - if (unit === "GB") return value * 1024 ** 3; - if (unit === "MB") return value * 1024 ** 2; - return value * 1024; -} - -function PrioritySlider({ label, value, onChange }) { - return ( -
    - {label} - Low - onChange(+e.target.value)} - style={{ width: "160px", cursor: "pointer" }} - /> - High - = 4 ? "#4f86c6" : value <= 2 ? "#aaa" : "#555", - }} - > - {value} - -
    - ); -} - -function ScoreBar({ score }) { - const pct = +(score * 100).toFixed(0); - const color = score > 0.66 ? "#42b883" : score > 0.33 ? "#e5c07b" : "#e06c75"; - return ( -
    -
    -
    -
    - - {pct} - -
    - ); -} - -function DecisionSupport() { - const { records } = useBenchmarkData(); - const [workloadFilter, setWorkloadFilter] = useState("any"); - - const [maxMemory, setMaxMemory] = useState(""); - const [maxMemoryUnit, setMaxMemoryUnit] = useState("MB"); - const [maxError, setMaxError] = useState(""); - const [minThroughput, setMinThroughput] = useState(""); - - const [speedPri, setSpeedPri] = useState(3); - const [memoryPri, setMemoryPri] = useState(3); - const [accuracyPri, setAccuracyPri] = useState(3); - - function reset() { - setWorkloadFilter("any"); - setMaxMemory(""); - setMaxMemoryUnit("MB"); - setMaxError(""); - setMinThroughput(""); - setSpeedPri(3); - setMemoryPri(3); - setAccuracyPri(3); - } - - const workloads = useMemo(() => workloadsOf(records), [records]); - - const candidates = useMemo(() => { - const src = - workloadFilter === "any" - ? records - : records.filter((r) => r.workload === workloadFilter); - - return src.map((r) => { - const q = queryThroughput(r); - return { - record: r, - workload: r.workload, - system: r.system, - config: r.configuration, - query: q != null ? +q.toFixed(3) : null, - memoryBytes: finiteNumber(r.peak_memory_bytes), - error: errorPct(r), - }; - }); - }, [records, workloadFilter]); - - const maxMemoryBytes = - maxMemory !== "" ? toBytes(parseFloat(maxMemory), maxMemoryUnit) : null; - - const passing = useMemo(() => { - return candidates.filter((c) => { - if ( - maxMemoryBytes !== null && - c.memoryBytes != null && - c.memoryBytes > maxMemoryBytes - ) - return false; - if (maxError !== "" && c.error != null && c.error > parseFloat(maxError)) - return false; - if ( - minThroughput !== "" && - c.query != null && - c.query < parseFloat(minThroughput) - ) - return false; - return true; - }); - }, [candidates, maxMemoryBytes, maxError, minThroughput]); - - const ranked = useMemo(() => { - if (passing.length === 0) return []; - - const range = (workload, pick) => { - const values = passing - .filter((c) => c.workload === workload) - .map(pick) - .filter((v) => v != null && Number.isFinite(v)); - return values.length - ? [Math.min(...values), Math.max(...values)] - : [0, 1]; - }; - - const norm = (v, lo, hi) => (hi === lo ? 1 : (v - lo) / (hi - lo)); - const total = speedPri + memoryPri + accuracyPri || 1; - - return [...passing] - .map((c) => { - const [minQ, maxQ] = range(c.workload, (x) => x.query); - const [minM, maxM] = range(c.workload, (x) => x.memoryBytes); - const [minE, maxE] = range(c.workload, (x) => x.error); - const missing = []; - const sSpeed = - c.query != null - ? norm(c.query, minQ, maxQ) - : (missing.push("throughput"), 0); - const sMem = - c.memoryBytes != null - ? 1 - norm(c.memoryBytes, minM, maxM) - : (missing.push("memory"), 0); - const sAcc = - c.error == null - ? (missing.push("error"), 0) - : Number.isFinite(c.error) - ? 1 - norm(c.error, minE, maxE) - : 0; - if (missing.length > 0) - console.warn( - `[DecisionSupport] ${c.workload}/${c.system}/${c.config}: missing ${missing.join(", ")} — scored as 0`, - ); - const score = - (speedPri * sSpeed + memoryPri * sMem + accuracyPri * sAcc) / total; - return { ...c, score }; - }) - .sort((a, b) => b.score - a.score); - }, [passing, speedPri, memoryPri, accuracyPri]); - - const filteredOut = candidates.length - passing.length; - - return ( -
    -
    -

    Decision Support

    - -
    -

    - Set constraints and priorities to find the best system configuration for - your use case. Scores are relative within each workload. -

    - -
    - {["any", ...workloads].map((w) => ( - - ))} -
    - -
    -
    -

    Constraints

    -

    - Leave blank to skip a constraint. -

    - -
    -
    - - Max memory - - setMaxMemory(e.target.value)} - style={{ - width: "80px", - padding: "6px 8px", - border: "1px solid #ccc", - borderRadius: "4px", - }} - /> - -
    - -
    - - Max median error - - setMaxError(e.target.value)} - style={{ - width: "80px", - padding: "6px 8px", - border: "1px solid #ccc", - borderRadius: "4px", - }} - /> - % -
    - -
    - - Min throughput - - setMinThroughput(e.target.value)} - style={{ - width: "80px", - padding: "6px 8px", - border: "1px solid #ccc", - borderRadius: "4px", - }} - /> - queries/s -
    -
    -
    - -
    -

    Priorities

    -

    - Weight each metric in the final ranking. -

    - - - -
    -
    - -
    -

    - {ranked.length === 0 && candidates.length > 0 - ? "No system configurations match your constraints." - : `${ranked.length} result${ranked.length === 1 ? "" : "s"} ranked by priority`} - {filteredOut > 0 && ( - - ({filteredOut} filtered out by constraints) - - )} -

    - - {ranked.length > 0 && ( - - - - - - - - - - - - - - - - - {ranked.map((r, i) => ( - - - - - - - - - - - - - ))} - -
    #WorkloadSystemConfigModeCompared withMemoryThroughputMedian ErrorScore
    - {i + 1} - - {r.workload} - {r.system} - {r.config} - - - - - - {r.memoryBytes != null ? fmtMemory(r.memoryBytes) : "NA"} - {r.query != null ? `${r.query} q/s` : "NA"} - {r.error == null - ? "NA" - : Number.isFinite(r.error) - ? `${r.error}%` - : "∞"} - - -
    - )} -
    -
    - ); -} - -export default DecisionSupport; diff --git a/system-leaderboard/src/pages/Home.jsx b/system-leaderboard/src/pages/Home.jsx index 33ff2411..87fb6b11 100644 --- a/system-leaderboard/src/pages/Home.jsx +++ b/system-leaderboard/src/pages/Home.jsx @@ -1,13 +1,67 @@ +import { useMemo } from "react"; +import { Link } from "react-router-dom"; +import { useBenchmarkData } from "../hooks/useBenchmarkData"; +import { descriptionOf, nameOf } from "../utils/catalog"; +import { querySetsOf } from "../utils/querySets"; +import "./QuerySet.css"; + function Home() { - return ( -
    -

    System Leaderboard

    + const { records, catalog, title, description, localSources } = + useBenchmarkData(); + const sets = useMemo(() => querySetsOf(records, catalog), [records, catalog]); + const benchmarks = [...new Set(sets.map((s) => s.benchmark))]; -

    - Welcome to the System Benchmark Leaderboard. Each result is one system - in one configuration on one workload; approximate results are compared - with the exact result they replace. + return ( +

    +

    {title ?? "System Leaderboard"}

    +

    + {description ?? + "Each query set is compared on its own: the systems and configurations that ran its queries, which of them are exact and which approximate, and what each approximate one is compared with. Nothing is ranked across query sets."}

    +

    + Open local results (top right) reads result files in + this browser only, beside the published ones: nothing is uploaded or + kept after a reload. +

    + + {benchmarks.map((benchmark) => ( +
    +

    {nameOf(catalog, "benchmark", { benchmark })}

    + {descriptionOf(catalog, "benchmark", { benchmark }) && ( +

    + {descriptionOf(catalog, "benchmark", { benchmark })} +

    + )} +
      + {sets + .filter((s) => s.benchmark === benchmark) + .map((s) => { + const local = s.sources.some((name) => localSources.has(name)); + return ( +
    • +

      + + {nameOf(catalog, "workload", s)} + + {local && (local)} +

      +
      + {s.queries.length} queries · {s.exact.length} exact ·{" "} + {s.approximate.length} approximate +
      + {descriptionOf(catalog, "workload", s) && ( +

      + {descriptionOf(catalog, "workload", s)} +

      + )} +
    • + ); + })} +
    +
    + ))}
    ); } diff --git a/system-leaderboard/src/pages/QuerySet.css b/system-leaderboard/src/pages/QuerySet.css new file mode 100644 index 00000000..1020836f --- /dev/null +++ b/system-leaderboard/src/pages/QuerySet.css @@ -0,0 +1,148 @@ +.page { + padding: 20px; + max-width: 1400px; +} + +.kind { + color: #555; + margin-top: -8px; +} + +.facts { + display: grid; + grid-template-columns: max-content 1fr; + gap: 4px 16px; + margin: 16px 0; +} + +.facts dt { + font-weight: bold; +} + +.facts dd { + margin: 0; +} + +.section-note { + color: #555; + max-width: 900px; +} + +.name-cell { + text-align: left !important; +} + +.cell-id { + color: #888; + font-size: 0.8em; +} + +.cell-sub { + color: #777; + font-size: 0.8em; +} + +.pending { + color: #888; + font-style: italic; + font-size: 0.9em; +} + +.pending-banner { + background: #f6f6f6; + border: 1px solid #ddd; + border-radius: 6px; + padding: 10px 14px; + margin: 16px 0; +} + +.pending-banner ul { + margin: 6px 0 0; +} + +.rules-cell { + text-align: left !important; + font-size: 0.85em; +} + +.wide-table { + overflow-x: auto; +} + +.results-table.compact th, +.results-table.compact td { + padding: 6px 8px; + font-size: 0.85em; +} + +.query-cell { + text-align: left !important; + max-width: 360px; +} + +.query-text { + font-family: monospace; + font-size: 0.8em; + color: #666; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.cell-none { + color: #aaa; +} + +.cell-bad { + color: #a33; +} + +.set-list { + list-style: none; + padding: 0; + display: grid; + grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); + gap: 12px; +} + +.set-card { + border: 1px solid #ddd; + border-radius: 8px; + padding: 12px 14px; +} + +.set-card h3 { + margin: 0 0 6px; +} + +.chart-box { + width: 100%; + max-width: 900px; + height: 420px; +} + +.chart-tip { + background: white; + border: 1px solid #ccc; + border-radius: 6px; + padding: 8px 10px; + font-size: 0.9em; +} + +.chart-legend { + list-style: none; + padding: 0; + font-size: 0.9em; +} + +.chart-swatch { + display: inline-block; + width: 10px; + height: 10px; + border-radius: 50%; + margin-right: 6px; +} + +.pair-queries { + margin-top: 12px; +} diff --git a/system-leaderboard/src/pages/QuerySet.jsx b/system-leaderboard/src/pages/QuerySet.jsx new file mode 100644 index 00000000..40a87c0d --- /dev/null +++ b/system-leaderboard/src/pages/QuerySet.jsx @@ -0,0 +1,641 @@ +import { useMemo, useState } from "react"; +import { Link, useParams } from "react-router-dom"; +import { useBenchmarkData } from "../hooks/useBenchmarkData"; +import ModeBadge from "../components/ModeBadge"; +import { SourceTag } from "../components/RecordName"; +import { descriptionOf, nameOf } from "../utils/catalog"; +import { findQuerySet, isPending, querySetsOf } from "../utils/querySets"; +import { + compareRecords, + exactComparison, + queryCpu, + queryTime, + queryTimeBasis, +} from "../utils/compare"; +import { + fmtCount, + fmtCpu, + fmtError, + fmtMemory, + fmtMs, + fmtRate, + fmtRatio, + fmtSeconds, + fmtSpeed, + finiteNumber, +} from "../utils/metrics"; +import { + Measured, + ParticipantName, + Pending, + Sub, +} from "../components/QuerySetCells"; +import PairComparison from "../components/PairComparison"; +import ErrorVsTime from "../components/ErrorVsTime"; +import "./ResultTable.css"; +import "./QuerySet.css"; + +function notAnswered(record, total) { + const counts = {}; + const notRun = total - (record?.queries ?? []).length; + if (record && notRun > 0) counts["not run"] = notRun; + for (const q of record?.queries ?? []) { + if (q.status === "ok") continue; + const kind = q.status.startsWith("failed") ? "failed" : q.status; + counts[kind] = (counts[kind] ?? 0) + 1; + } + return Object.entries(counts) + .map(([kind, n]) => `${n} ${kind}`) + .join(", "); +} + +function Participants({ set }) { + return ( + + + + + + + + + + + + + + {set.participants.map((p) => { + const reference = set.participants.find((o) => o.key === p.reference); + return ( + + + + + + + + + + ); + })} + +
    ParticipantModeCompared withAnsweredNot answeredPendingDetails
    + + {p.record && } + + + + {p.mode === "exact" ? ( + "—" + ) : reference ? ( + + ) : ( + (p.reference ?? "—") + )} + + {p.record + ? fmtCount(p.record.answered_count, set.queries.length) + : "no results loaded"} + {notAnswered(p.record, set.queries.length) || "—"}{p.pending.length ? p.pending.join(", ") : "—"} + {p.record ? ( + Details + ) : ( + "—" + )} +
    + ); +} + +function ExactTable({ set }) { + const { common, rows } = exactComparison(set.benchmark, set.exact); + const oneShot = set.benchmark === "one-shot"; + return ( + <> +

    + {common.length} of {set.queries.length} queries are answered by every + exact participant; time, CPU and error below are over those queries only + ({queryTimeBasis(set.benchmark) ?? "query time"}, geometric mean). +

    + + + + + + + + {oneShot && } + + + {oneShot ? ( + <> + + + + + ) : ( + <> + + + + + + + )} + + + + {rows.map( + ({ + participant: p, + answered, + time, + relative, + firstRun, + cpu, + error, + }) => { + const r = p.record; + const timePending = isPending(p, "time"); + return ( + + + + + + {oneShot && ( + + )} + + + {oneShot ? ( + <> + + + + + ) : ( + <> + + + + + + + )} + + ); + }, + )} + +
    Exact participantAnsweredQuery timeRelative to fastestFirst runError against truthPeak memoryCPU per queryLoad timeData sizeMedian / p99 latencyQuery CPUIngest CPUDiskInsert rate
    + + + {fmtCount(answered, set.queries.length)} + + {fmtSeconds(time)} + + + + {fmtRatio(relative)} + + + + {fmtSeconds(firstRun)} + + + + {fmtError(error.median)} + max {fmtError(error.max)} + + + + {fmtMemory(r.peak_memory_bytes)} + {r.instances > 1 && ( + + {r.instances} instances; largest{" "} + {fmtMemory(r.largest_instance_peak_memory_bytes)} + + )} + + + + {fmtSeconds(cpu)} + + {fmtSeconds(finiteNumber(r.load_seconds))}{fmtMemory(r.data_size_bytes)} + + {fmtMs(r.median_query_ms)} + p99 {fmtMs(r.p99_query_ms)} + + + + {fmtCpu(r.query_cpu_seconds)} + + + + {fmtCpu(r.ingest_cpu_seconds)} + + {fmtMemory(r.disk_bytes)} + {fmtRate(finiteNumber(r.ingest_samples_per_second))} +
    + + ); +} + +function Ratio({ pending, value, from, to, format }) { + if (pending) return ; + return ( + <> + {fmtRatio(value)} + {(from != null || to != null) && ( + + {format(to)} vs {format(from)} + + )} + + ); +} + +function ApproximateTable({ set }) { + const periodic = set.benchmark === "periodic"; + return ( + <> +

    + Each approximate participant against the participant it is compared + with, over the queries both answered. Time is the geometric mean of the + per-query ratios ({queryTimeBasis(set.benchmark) ?? "query time"}); + {set.benchmark === "one-shot" + ? " CPU is the same per query, where both recorded it; memory is the ratio of the largest query's peak." + : " memory and CPU are ratios of the whole runs."} +

    + + + + + + + + + + {!periodic && } + {periodic && ( + <> + + + + + )} + + + + {set.approximate.map((p) => { + const reference = set.participants.find( + (o) => o.key === p.reference, + ); + if (!p.record || !reference?.record) { + return ( + + + + + ); + } + const c = compareRecords( + reference.record, + p.record, + set.queries.length, + ); + const either = (m) => isPending(p, m) || isPending(reference, m); + const perQuery = c.timeRatio != null; + const timeRatio = perQuery ? c.timeRatio : c.latencyRatio; + return ( + + + + + + + + {!periodic && ( + + )} + {periodic && ( + <> + + + + + )} + + ); + })} + +
    Approximate participantCompared withBoth answeredQuery timeError against truthPeak memoryCPUQuery CPUIngest CPUDecision agreement
    + + + {!p.record + ? "no results loaded" + : `no results of ${p.reference ?? "a reference"} loaded`} +
    + + + + + + {fmtCount(c.common, c.total)} + + answered here {c.toAnswered}, there {c.fromAnswered} + + + + {fmtSpeed(timeRatio)} + + {perQuery + ? `over ${c.timed} queries` + : timeRatio != null + ? "whole-run median latencies; no per-query times recorded" + : "no time recorded"} + + + + + {fmtError(c.toError.median)} + max {fmtError(c.toError.max)} + + + + + + {fmtRatio(c.perQueryCpuRatio)} + {c.cpuTimed > 0 && over {c.cpuTimed} queries} + + + + + + + + {c.agreement + ? Object.entries(c.agreement).map(([rule, value]) => ( +
    + {rule}:{" "} + {value != null + ? `${(value * 100).toFixed(1)}%` + : "—"} +
    + )) + : "—"} +
    +
    + + ); +} + +const VIEWS = { + status: "Status", + time: "Query time", + cpu: "CPU", + error: "Error against truth", +}; + +function cellFor(view, set, participant, q) { + if (!q) return { text: "not run", className: "cell-none" }; + if (q.status !== "ok") { + const short = q.status.startsWith("failed") ? "failed" : q.status; + return { text: short, title: q.reason ?? q.status, className: "cell-bad" }; + } + if (view === "status") return { text: "ok", title: q.plan ?? undefined }; + if (view === "time") { + if (isPending(participant, "time")) return { pending: true }; + return { text: fmtSeconds(queryTime(set.benchmark, q)) }; + } + if (view === "cpu") { + if (isPending(participant, "cpu")) return { pending: true }; + return { text: fmtSeconds(queryCpu(set.benchmark, q)) }; + } + if (isPending(participant, "accuracy")) return { pending: true }; + const differs = + (q.missing_groups ?? 0) + + (q.extra_groups ?? 0) + + (q.differing_text_cells ?? 0); + return { + text: fmtError(q.max_relative_error), + title: differs + ? `${q.missing_groups ?? 0} missing groups, ${q.extra_groups ?? 0} extra groups, ${q.differing_text_cells ?? 0} differing text cells` + : q.truth_stable === false + ? "the truth's own runs disagree: no accuracy" + : undefined, + }; +} + +function PerQuery({ set }) { + const [view, setView] = useState("status"); + const byParticipant = useMemo( + () => + set.participants.map((p) => [ + p, + new Map((p.record?.queries ?? []).map((q) => [q.query, q])), + ]), + [set], + ); + return ( + <> +
    + {Object.entries(VIEWS) + .filter(([key]) => key !== "cpu" || set.benchmark === "one-shot") + .map(([key, label]) => ( + + ))} +
    +
    + + + + + {byParticipant.map(([p]) => ( + + ))} + + + + {set.queries.map((query) => ( + + + {byParticipant.map(([p, queries]) => { + const cell = cellFor(view, set, p, queries.get(query)); + return ( + + ); + })} + + ))} + +
    Query + +
    + +
    +
    + {query} + {set.texts[query] && ( +
    {set.texts[query]}
    + )} +
    + {cell.pending ? : cell.text} +
    +
    + + ); +} + +function QuerySet() { + const { benchmark, workload } = useParams(); + const { records, catalog } = useBenchmarkData(); + const set = useMemo( + () => findQuerySet(querySetsOf(records, catalog), benchmark, workload), + [records, catalog, benchmark, workload], + ); + + if (!set) { + return ( +
    +

    + No query set {benchmark}/{workload} in the loaded results.{" "} + All query sets +

    +
    + ); + } + + const pendingParticipants = set.participants.filter((p) => p.pending.length); + const truth = set.participants.find((p) => p.key === set.truth); + + return ( +
    + ← All query sets +

    {nameOf(catalog, "workload", { workload })}

    +

    {nameOf(catalog, "benchmark", { benchmark })}

    + {descriptionOf(catalog, "workload", { workload }) && ( +

    {descriptionOf(catalog, "workload", { workload })}

    + )} +
    +
    Queries
    +
    {set.queries.length}
    +
    Truth
    +
    + {truth ? ( + + ) : ( + (set.truthDescription ?? set.truth ?? "not declared") + )} + {truth && set.truthDescription && ( + — {set.truthDescription} + )} +
    +
    Participants
    +
    + {set.exact.length} exact, {set.approximate.length} approximate +
    +
    + + {pendingParticipants.length > 0 && ( +
    + Measurements awaiting a rerun are not shown.{" "} + {set.pendingReason} +
      + {pendingParticipants.map((p) => ( +
    • + + : {p.pending.join(", ")} +
    • + ))} +
    +
    + )} + +

    Participants

    + + + {set.exact.length > 0 && ( + <> +

    Exact participants, on the queries all of them answered

    + + + )} + + {set.approximate.length > 0 && ( + <> +

    + Approximate participants, each against what it is compared with +

    + + + )} + + {set.approximate.length > 0 && ( + <> +

    Error against time, approximate participants

    + + + )} + +

    Any two participants

    + + +

    Per query

    + +
    + ); +} + +export default QuerySet; diff --git a/system-leaderboard/src/pages/ResultDetails.jsx b/system-leaderboard/src/pages/ResultDetails.jsx index b03fc7ce..5b858912 100644 --- a/system-leaderboard/src/pages/ResultDetails.jsx +++ b/system-leaderboard/src/pages/ResultDetails.jsx @@ -2,10 +2,14 @@ import { Link, useParams } from "react-router-dom"; import { useBenchmarkData } from "../hooks/useBenchmarkData"; import ModeBadge from "../components/ModeBadge"; import BaselineLink from "../components/BaselineLink"; +import { SourceTag } from "../components/RecordName"; +import { descriptionOf, nameOf } from "../utils/catalog"; import { benchmarkLabel, insertThroughput, - queryThroughput, + answeredPerHotSecond, + inverseMedianLatency, + instancesNote, fmtMemory, fmtRate, fmtSeconds, @@ -112,6 +116,7 @@ function PeriodicQueries({ queries }) { PromQL Status Plan + Median latency Max Error (%) @@ -122,6 +127,7 @@ function PeriodicQueries({ queries }) { {q.text ?? "-"} {q.status} {q.reason ?? q.plan ?? "-"} + {fmtMs(q.median_query_ms)} {fmtError(q.max_relative_error)} ))} @@ -130,9 +136,41 @@ function PeriodicQueries({ queries }) { ); } +function cellText(value) { + if (value == null) return "—"; + if (typeof value === "object") return JSON.stringify(value); + return String(value); +} + +function GenericQueries({ queries }) { + const keys = [...new Set(queries.flatMap((q) => Object.keys(q)))]; + return ( + + + + {keys.map((k) => ( + + ))} + + + + {queries.map((q, i) => ( + + {keys.map((k) => ( + + ))} + + ))} + +
    {k}
    + {cellText(q[k])} +
    + ); +} + function ResultDetails() { const { index } = useParams(); - const { records, loading } = useBenchmarkData(); + const { records, loading, catalog } = useBenchmarkData(); if (loading) { return
    Loading…
    ; @@ -143,123 +181,198 @@ function ResultDetails() { return (

    Run not found.

    - - ← Back to Results + + ← All query sets
    ); } const oneShot = item.benchmark === "one-shot"; + const periodic = item.benchmark === "periodic"; const insert = insertThroughput(item); - const query = queryThroughput(item); const accs = accuracyRows(item); const queries = item.queries ?? []; + const instances = instancesNote(item); + const descriptions = [ + ["System", descriptionOf(catalog, "system", item)], + ["Configuration", descriptionOf(catalog, "configuration", item)], + ["Workload", descriptionOf(catalog, "workload", item)], + ].filter(([, text]) => text); return (
    - - ← Back to Results + + ← {nameOf(catalog, "workload", item)}

    - {item.system} · {item.configuration} + {nameOf(catalog, "system", item)} ·{" "} + {nameOf(catalog, "configuration", item)} +

    - {item.workload} - {benchmarkLabel(item.benchmark)} + {nameOf(catalog, "workload", item)} + + {benchmarkLabel(item.benchmark, catalog)} + {item.mode === "approximate" && ( compared with )} + from {item.source ?? "—"}
    + {descriptions.map(([label, text]) => ( +

    + {label}: {text} +

    + ))} + {instances && ( +

    ⚠ {instances}

    + )} + {item.pending?.length > 0 && ( +

    + Awaiting a rerun, so left out: {item.pending.join(", ")}. +

    + )}
    - - - {!oneShot && ( - - )} - - + {!oneShot && !periodic && ( +
    +

    Measurements

    +
    + {Object.entries(item) + .filter( + ([k, v]) => + k !== "queries" && (v == null || typeof v !== "object"), + ) + .map(([k, v]) => ( + + ))} +
    +
    + )} - - {oneShot ? ( - <> - + {(oneShot || periodic) && ( + <> + + {!oneShot && ( + + )} - - ) : ( - <> - - + + + + {oneShot ? ( + <> + + + + + ) : ( + <> + + + + + + + )} + + + - - )} - - - - - {oneShot ? ( - - ) : ( - - )} - + {periodic && ( + + )} + {oneShot ? ( + + ) : ( + + )} + + + )} {accs.map((a) => ( @@ -269,7 +382,9 @@ function ResultDetails() { - + + + Queries ({queries.length}) {oneShot ? ( - ) : ( + ) : periodic ? ( + ) : ( + )} diff --git a/system-leaderboard/src/pages/ResultTable.css b/system-leaderboard/src/pages/ResultTable.css index bb8d93a1..06610a57 100644 --- a/system-leaderboard/src/pages/ResultTable.css +++ b/system-leaderboard/src/pages/ResultTable.css @@ -23,3 +23,21 @@ .results-table tr:hover { background-color: #f1f1f1; } + +.table-controls { + display: flex; + flex-wrap: wrap; + gap: 16px; + align-items: center; + margin: 12px 0; +} + +.column-chooser { + margin: 8px 0; +} + +.column-chooser label { + display: inline-block; + margin: 4px 14px 4px 0; + font-size: 0.9em; +} diff --git a/system-leaderboard/src/pages/ResultTable.jsx b/system-leaderboard/src/pages/ResultTable.jsx deleted file mode 100644 index 8c0d5a53..00000000 --- a/system-leaderboard/src/pages/ResultTable.jsx +++ /dev/null @@ -1,142 +0,0 @@ -import { useState } from "react"; -import { Link } from "react-router-dom"; -import { useBenchmarkData } from "../hooks/useBenchmarkData"; -import ModeBadge from "../components/ModeBadge"; -import BaselineLink from "../components/BaselineLink"; -import { - workloadsOf, - benchmarkLabel, - queryThroughput, - insertThroughput, - fmtRate, - fmtError, - fmtMemory, - fmtSpeedup, -} from "../utils/metrics"; -import "./ResultTable.css"; - -function ResultTable() { - const { records: results } = useBenchmarkData(); - const [workloadFilter, setWorkloadFilter] = useState("all"); - - const workloads = workloadsOf(results); - const shown = results - .map((item, index) => ({ item, index })) - .filter( - ({ item }) => - workloadFilter === "all" || item.workload === workloadFilter, - ); - - return ( -
    -

    Benchmark Results

    - -
    - -
    - -

    - Showing {shown.length} of {results.length} records. Exact rows are the - reference; each approximate row is compared with the exact row named in - “Compared with”, and its speedup and error are measured against it. -

    - -
    - - - - - - - - - - - - - - - - - - - {shown.map(({ item, index }) => ( - - - - - - - - - - - - - - - - - - - - - - - - ))} - -
    SystemConfigurationModeCompared withWorkloadQuery ThroughputInsert ThroughputSpeedup - Error (%) -
    - max / median -
    -
    MemoryDetails
    {item.system}{item.configuration} - - - - - {item.workload} -
    - {benchmarkLabel(item.benchmark)} · {item.answered_count}/ - {item.query_count} answered -
    -
    {fmtRate(queryThroughput(item))} - {insertThroughput(item) != null - ? fmtRate(insertThroughput(item)) - : "-"} - - {item.speedup_over_baseline != null - ? fmtSpeedup(item.speedup_over_baseline) - : "-"} - - {fmtError(item.max_relative_error)} -
    - {fmtError(item.median_relative_error)} -
    -
    - {item.peak_memory_bytes != null - ? fmtMemory(item.peak_memory_bytes) - : "-"} - - View -
    -
    -
    - ); -} - -export default ResultTable; diff --git a/system-leaderboard/src/pages/Throughput.jsx b/system-leaderboard/src/pages/Throughput.jsx deleted file mode 100644 index f4575fd7..00000000 --- a/system-leaderboard/src/pages/Throughput.jsx +++ /dev/null @@ -1,235 +0,0 @@ -import { useMemo, useState } from "react"; -import { useBenchmarkData } from "../hooks/useBenchmarkData"; -import ModeBadge from "../components/ModeBadge"; -import BaselineLink from "../components/BaselineLink"; -import { - workloadsOf, - benchmarkLabel, - insertThroughput, - queryThroughput, - fmtRate, -} from "../utils/metrics"; -import "./ResultTable.css"; - -function ThroughputBar({ value, max, color, logScale }) { - let pct = 0; - if (max > 0 && value != null) { - if (logScale && value > 0 && max > 1) { - pct = Math.max(2, (Math.log(value) / Math.log(max)) * 100); - } else { - pct = Math.max(2, (value / max) * 100); - } - } - return ( -
    -
    -
    -
    - - {value != null ? fmtRate(value) : "-"} - -
    - ); -} - -function Throughput() { - const { records } = useBenchmarkData(); - const [selectedWorkload, setSelectedWorkload] = useState(""); - const [selectedConfig, setSelectedConfig] = useState("all"); - const [logScale, setLogScale] = useState(false); - - const workloads = useMemo(() => workloadsOf(records), [records]); - const workload = selectedWorkload || workloads[0] || ""; - const benchmark = records.find((r) => r.workload === workload)?.benchmark; - const periodic = benchmark === "periodic"; - - const configs = useMemo( - () => [ - ...new Set( - records - .filter((r) => r.workload === workload) - .map((r) => r.configuration), - ), - ], - [records, workload], - ); - const config = - selectedConfig !== "all" && configs.includes(selectedConfig) - ? selectedConfig - : "all"; - - const rows = useMemo( - () => - records - .filter( - (r) => - r.workload === workload && - (config === "all" || r.configuration === config), - ) - .map((r) => ({ - record: r, - insert: insertThroughput(r), - query: queryThroughput(r), - })), - [records, workload, config], - ); - - const maxInsert = Math.max(1, ...rows.map((r) => r.insert ?? 0)); - const maxQuery = Math.max(1, ...rows.map((r) => r.query ?? 0)); - - return ( -
    -

    Throughput

    -

    - Insertion and query throughput for a given workload and configuration. - Insert throughput is samples per second while data arrives (periodic - workloads only); query throughput is 1000 / median query latency for - periodic workloads and answered queries / total hot time for one-shot - workloads. -

    - -
    - {workloads.map((w) => ( - - ))} -
    - - {configs.length > 0 && ( - - )} - -
    -

    - {workload ? workload.toUpperCase() : ""} - {benchmark ? ` · ${benchmarkLabel(benchmark)}` : ""} - {config !== "all" ? ` · ${config}` : ""} — {rows.length} run - {rows.length === 1 ? "" : "s"} -

    - -
    - - - - - - - - - {periodic && } - - - - - - {rows.map((r, index) => ( - - - - - - {periodic && ( - - )} - - - ))} - -
    SystemConfigurationModeCompared withInsert Throughput (samples/s)Query Throughput (queries/s)
    {r.record.system}{r.record.configuration} - - - - - - - -
    -
    - ); -} - -export default Throughput; diff --git a/system-leaderboard/src/pages/Visualization.jsx b/system-leaderboard/src/pages/Visualization.jsx deleted file mode 100644 index cb22317f..00000000 --- a/system-leaderboard/src/pages/Visualization.jsx +++ /dev/null @@ -1,402 +0,0 @@ -import { useMemo, useState } from "react"; -import { - BarChart, - Bar, - XAxis, - YAxis, - CartesianGrid, - Tooltip, - Legend, - ResponsiveContainer, -} from "recharts"; -import { useBenchmarkData } from "../hooks/useBenchmarkData"; -import { - workloadsOf, - benchmarkLabel, - runLabel, - finiteNumber, - insertThroughput, - queryThroughput, -} from "../utils/metrics"; -import "./ResultTable.css"; - -function memoryUnit(maxBytes) { - if (maxBytes >= 1024 ** 3) return "GB"; - if (maxBytes >= 1024 ** 2) return "MB"; - return "KB"; -} - -function memoryDivisor(unit) { - if (unit === "GB") return 1024 ** 3; - if (unit === "MB") return 1024 ** 2; - return 1024; -} - -function round(v, digits) { - return v != null ? +v.toFixed(digits) : null; -} - -function errorPct(v) { - const n = finiteNumber(v); - return n != null ? +(n * 100).toFixed(4) : null; -} - -const IMPL_COLORS = [ - "#4f86c6", - "#42b883", - "#e06c75", - "#e5c07b", - "#c678dd", - "#56b6c2", - "#98c379", - "#d19a66", - "#be5046", - "#61afef", -]; - -function StackedChart({ - title, - data, - dataKeys, - yLabel, - lowerIsBetter, - logScale, -}) { - const scale = logScale ? "log" : "auto"; - const domain = logScale ? ["auto", "auto"] : [0, "auto"]; - - return ( -
    -

    - {title} - {lowerIsBetter && ( - - {" "} - (lower is better) - - )} -

    - - - - - - [v != null ? v : "—", name]} - contentStyle={{ fontSize: "13px" }} - /> - {dataKeys.length > 1 && ( - - )} - {dataKeys.map(({ key, color, name }, i) => ( - - ))} - - -
    - ); -} - -function Visualization() { - const { records } = useBenchmarkData(); - const [selectedWorkload, setSelectedWorkload] = useState(""); - const [selectedMode, setSelectedMode] = useState("all"); - const [selectedMetric, setSelectedMetric] = useState("all"); - const [logScale, setLogScale] = useState(false); - - const workloads = useMemo(() => workloadsOf(records), [records]); - const workload = selectedWorkload || workloads[0] || ""; - const benchmark = records.find((r) => r.workload === workload)?.benchmark; - const periodic = benchmark === "periodic"; - - const filtered = useMemo( - () => - records.filter( - (r) => - r.workload === workload && - (selectedMode === "all" || r.mode === selectedMode), - ), - [records, workload, selectedMode], - ); - - const byRun = useMemo( - () => - filtered.map((r) => ({ - run: `${runLabel(r)}${r.mode === "exact" ? " (exact)" : ""}`, - insert: - insertThroughput(r) != null - ? round(insertThroughput(r) / 1e6, 3) - : null, - query: round(queryThroughput(r), 3), - geomean: round(finiteNumber(r.geomean_hot_seconds), 4), - total: round(finiteNumber(r.total_hot_seconds), 3), - median: round(finiteNumber(r.median_query_ms), 3), - p99: round(finiteNumber(r.p99_query_ms), 3), - cpu: round(finiteNumber(r.cpu_seconds), 3), - memoryBytes: finiteNumber(r.peak_memory_bytes), - maxError: errorPct(r.max_relative_error), - medianError: errorPct(r.median_relative_error), - infinite: r.max_relative_error === "inf", - })), - [filtered], - ); - - const unit = useMemo(() => { - const maxBytes = Math.max(0, ...byRun.map((r) => r.memoryBytes ?? 0)); - return memoryUnit(maxBytes); - }, [byRun]); - - const memoryData = useMemo(() => { - const div = memoryDivisor(unit); - return byRun.map((r) => ({ - ...r, - memory: r.memoryBytes != null ? +(r.memoryBytes / div).toFixed(3) : null, - })); - }, [byRun, unit]); - - const hasMemory = byRun.some((r) => r.memoryBytes != null); - const hasAccuracy = byRun.some( - (r) => r.maxError != null || r.medianError != null, - ); - const infiniteRuns = byRun.filter((r) => r.infinite).map((r) => r.run); - const show = (metric) => - selectedMetric === "all" || selectedMetric === metric; - - return ( -
    -

    Visualization

    -

    Multi-metric comparison across systems and configurations.

    - -
    - {workloads.map((w) => ( - - ))} -
    - -
    - - - -
    - -

    - {workload.toUpperCase()} - {benchmark ? ` · ${benchmarkLabel(benchmark)}` : ""} - {selectedMode !== "all" ? ` · ${selectedMode}` : ""} — {byRun.length}{" "} - system configuration{byRun.length === 1 ? "" : "s"} -

    - - {byRun.length === 0 ? ( -

    No data for this selection.

    - ) : ( -
    - {show("throughput") && ( - - )} - {show("throughput") && periodic && ( - - )} - {show("time") && periodic && ( - - )} - {show("time") && !periodic && ( - - )} - {show("cpu") && periodic && ( - - )} - {show("memory") && hasMemory && ( - - )} - {show("error") && hasAccuracy && ( - - )} - {show("error") && infiniteRuns.length > 0 && ( -
    - Infinite error -

    - Max error not drawn for {infiniteRuns.join(", ")}: at least one - query's relative error is infinite. -

    -
    - )} -
    - )} -
    - ); -} - -export default Visualization; diff --git a/system-leaderboard/src/utils/benchmarkRecord.js b/system-leaderboard/src/utils/benchmarkRecord.js index 32ef201d..fd63cb5f 100644 --- a/system-leaderboard/src/utils/benchmarkRecord.js +++ b/system-leaderboard/src/utils/benchmarkRecord.js @@ -4,6 +4,12 @@ import schema from "./schema.json" with { type: "json" }; export const SCHEMA_VERSION = schema["x-schema-version"]; +export const READABLE_SCHEMA_VERSIONS = Object.freeze( + schema.properties.schema_version.enum, +); + +export const KNOWN_BENCHMARKS = Object.freeze(["one-shot", "periodic"]); + export const RECORD_KEYS = Object.freeze(Object.keys(schema.properties)); const KNOWN_KEYS = new Set(RECORD_KEYS); @@ -137,13 +143,13 @@ export function validateRecord(raw, line) { ]; } - if (raw.schema_version !== SCHEMA_VERSION) { + if (!READABLE_SCHEMA_VERSIONS.includes(raw.schema_version)) { return [ problem( line, "schema_version", "error", - `expected ${SCHEMA_VERSION}, got ${JSON.stringify(raw.schema_version)} — ` + + `expected one of ${READABLE_SCHEMA_VERSIONS.join(", ")}, got ${JSON.stringify(raw.schema_version)} — ` + `this file was written by a different version of system-leaderboard-data.py, not damaged`, ), ]; @@ -274,6 +280,17 @@ export function validateRecord(raw, line) { ); } + if (!KNOWN_BENCHMARKS.includes(benchmark)) { + problems.push( + problem( + line, + "benchmark", + "warning", + `benchmark ${JSON.stringify(benchmark)} is shown in the tables only, without its own charts`, + ), + ); + } + const otherFields = benchmark === "one-shot" ? PERIODIC_ONLY @@ -305,7 +322,7 @@ export class SchemaViolation extends Error { .join("\n"); const more = errors.length > 5 ? `\n …and ${errors.length - 5} more` : ""; super( - `all.jsonl failed validation with ${errors.length} error(s):\n${shown}${more}`, + `the records failed validation with ${errors.length} error(s):\n${shown}${more}`, ); this.name = "SchemaViolation"; this.problems = problems; @@ -315,7 +332,6 @@ export class SchemaViolation extends Error { export function parseBenchmarkJsonl(text) { const records = []; const problems = []; - const lineOf = new Map(); const lines = text.split(/\r?\n/); @@ -338,28 +354,9 @@ export function parseBenchmarkJsonl(text) { problems.push(...found); if (!found.some((p) => p.severity === "error")) { records.push(parsed); - lineOf.set(parsed, line); } }); - const exact = new Set( - records - .filter((r) => r.mode === "exact") - .map((r) => `${r.workload}::${r.system}/${r.configuration}`), - ); - for (const r of records) { - if (r.baseline != null && !exact.has(`${r.workload}::${r.baseline}`)) { - problems.push( - problem( - lineOf.get(r), - "baseline", - "warning", - `no exact record ${r.baseline} on ${r.workload} in this file`, - ), - ); - } - } - if (records.length === 0 && problems.length === 0) { problems.push( problem(0, "(file)", "error", "no records found — file is empty"), @@ -368,3 +365,24 @@ export function parseBenchmarkJsonl(text) { return { records, problems }; } + +export function baselineProblems(records) { + const exact = new Set( + records + .filter((r) => r.mode === "exact") + .map((r) => `${r.workload}::${r.system}/${r.configuration}`), + ); + return records + .filter( + (r) => r.baseline != null && !exact.has(`${r.workload}::${r.baseline}`), + ) + .map((r) => ({ + ...problem( + null, + "baseline", + "warning", + `no exact record ${r.baseline} on ${r.workload} in the loaded results`, + ), + source: r.source, + })); +} diff --git a/system-leaderboard/src/utils/catalog.js b/system-leaderboard/src/utils/catalog.js new file mode 100644 index 00000000..b34cff35 --- /dev/null +++ b/system-leaderboard/src/utils/catalog.js @@ -0,0 +1,106 @@ +const SECTIONS = ["benchmarks", "systems", "configurations", "workloads"]; + +export function emptyCatalog() { + return { + ...Object.fromEntries(SECTIONS.map((s) => [s, {}])), + query_sets: {}, + }; +} + +export function isCatalog(value) { + if (typeof value !== "object" || value === null) return false; + if ("catalog_version" in value || "query_sets" in value) return true; + return typeof value.catalog === "object" && value.catalog !== null; +} + +function mergeQuerySets(base, extra) { + for (const [key, declared] of Object.entries(extra ?? {})) { + const current = base[key] ?? {}; + const participants = { ...(current.participants ?? {}) }; + for (const [name, participant] of Object.entries( + declared?.participants ?? {}, + )) { + participants[name] = { ...(participants[name] ?? {}), ...participant }; + } + const fields = Object.fromEntries( + Object.entries(declared ?? {}).filter( + ([k, v]) => k !== "participants" && v != null, + ), + ); + base[key] = { ...current, ...fields, participants }; + } + return base; +} + +export function catalogOf(value) { + const source = value?.catalog ?? value ?? {}; + const out = emptyCatalog(); + for (const section of SECTIONS) { + Object.assign(out[section], source[section] ?? {}); + } + mergeQuerySets(out.query_sets, value?.query_sets ?? source.query_sets); + return out; +} + +export function mergeCatalogs(catalogs) { + const out = emptyCatalog(); + for (const catalog of catalogs) { + for (const section of SECTIONS) { + Object.assign(out[section], catalog?.[section] ?? {}); + } + mergeQuerySets(out.query_sets, catalog?.query_sets); + } + return out; +} + +function configurationEntry(catalog, system, configuration) { + const found = catalog?.configurations ?? {}; + return ( + found[`${system}/${configuration}`] ?? + found[`${system}/*`] ?? + found[`*/${configuration}`] ?? + null + ); +} + +export function entryOf(catalog, kind, item) { + switch (kind) { + case "system": + return catalog?.systems?.[item.system] ?? null; + case "configuration": + return configurationEntry(catalog, item.system, item.configuration); + case "workload": + return catalog?.workloads?.[item.workload] ?? null; + case "benchmark": + return catalog?.benchmarks?.[item.benchmark] ?? null; + default: + return null; + } +} + +export function nameOf(catalog, kind, item) { + const id = + kind === "system" + ? item.system + : kind === "configuration" + ? item.configuration + : kind === "workload" + ? item.workload + : item.benchmark; + return entryOf(catalog, kind, item)?.name ?? id ?? "—"; +} + +export function descriptionOf(catalog, kind, item) { + return entryOf(catalog, kind, item)?.description ?? null; +} + +export function recordName(catalog, item) { + return `${nameOf(catalog, "system", item)} · ${nameOf(catalog, "configuration", item)}`; +} + +export function referenceName(catalog, workload, key) { + if (!key) return null; + const [system, ...rest] = key.split("/"); + const configuration = rest.join("/"); + return recordName(catalog, { system, configuration, workload }); +} diff --git a/system-leaderboard/src/utils/compare.js b/system-leaderboard/src/utils/compare.js new file mode 100644 index 00000000..0ade035a --- /dev/null +++ b/system-leaderboard/src/utils/compare.js @@ -0,0 +1,158 @@ +import { finiteNumber, isInfinite } from "./metrics"; + +export const recordKey = (r) => `${r.system}/${r.configuration}`; + +export function queryTime(benchmark, q) { + if (benchmark === "one-shot") return finiteNumber(q.hot_min_seconds); + if (benchmark === "periodic") { + const ms = finiteNumber(q.median_query_ms); + return ms != null ? ms / 1000 : null; + } + return null; +} + +export function queryCpu(benchmark, q) { + return benchmark === "one-shot" ? finiteNumber(q.cpu_seconds) : null; +} + +export const queryTimeBasis = (benchmark) => + benchmark === "one-shot" + ? "hot query time per query" + : benchmark === "periodic" + ? "median latency per query" + : null; + +export function answered(record) { + return new Map( + (record?.queries ?? []) + .filter((q) => q.status === "ok") + .map((q) => [q.query, q]), + ); +} + +export function geomean(values) { + const positive = values.filter((v) => Number.isFinite(v) && v > 0); + if (positive.length === 0) return null; + return Math.exp( + positive.reduce((s, v) => s + Math.log(v), 0) / positive.length, + ); +} + +function median(values) { + const finite = values.filter((v) => Number.isFinite(v)).sort((a, b) => a - b); + if (finite.length === 0) return null; + const mid = Math.floor(finite.length / 2); + return finite.length % 2 ? finite[mid] : (finite[mid - 1] + finite[mid]) / 2; +} + +export function errorSummary(queries) { + const values = queries.map((q) => q.max_relative_error); + if (values.some((v) => isInfinite(v))) { + return { median: median(values.map(finiteNumber)), max: "inf" }; + } + const finite = values.map(finiteNumber).filter((v) => v != null); + if (finite.length === 0) return { median: null, max: null }; + return { median: median(finite), max: Math.max(...finite) }; +} + +function ratio(numerator, denominator) { + const n = finiteNumber(numerator); + const d = finiteNumber(denominator); + return n != null && d != null && d > 0 ? n / d : null; +} + +export function compareRecords(from, to, total) { + const fromAnswered = answered(from); + const toAnswered = answered(to); + const common = [...toAnswered.keys()].filter((q) => fromAnswered.has(q)); + const timed = common.filter( + (q) => + queryTime(from.benchmark, fromAnswered.get(q)) != null && + queryTime(to.benchmark, toAnswered.get(q)) != null, + ); + const timeRatio = + from.benchmark === to.benchmark && timed.length > 0 + ? geomean( + timed.map( + (q) => + queryTime(to.benchmark, toAnswered.get(q)) / + queryTime(from.benchmark, fromAnswered.get(q)), + ), + ) + : null; + const cpuTimed = common.filter( + (q) => + queryCpu(from.benchmark, fromAnswered.get(q)) != null && + queryCpu(to.benchmark, toAnswered.get(q)) != null, + ); + return { + cpuTimed: cpuTimed.length, + perQueryCpuRatio: + from.benchmark === to.benchmark && cpuTimed.length > 0 + ? geomean( + cpuTimed.map( + (q) => + queryCpu(to.benchmark, toAnswered.get(q)) / + queryCpu(from.benchmark, fromAnswered.get(q)), + ), + ) + : null, + total: + total ?? + Math.max( + from.query_count ?? (from.queries ?? []).length, + to.query_count ?? (to.queries ?? []).length, + ), + fromAnswered: fromAnswered.size, + toAnswered: toAnswered.size, + common: common.length, + timed: timed.length, + timeRatio, + latencyRatio: ratio(to.median_query_ms, from.median_query_ms), + memoryRatio: ratio(to.peak_memory_bytes, from.peak_memory_bytes), + cpuRatio: ratio(to.cpu_seconds, from.cpu_seconds), + queryCpuRatio: ratio(to.query_cpu_seconds, from.query_cpu_seconds), + ingestCpuRatio: ratio(to.ingest_cpu_seconds, from.ingest_cpu_seconds), + toError: errorSummary(common.map((q) => toAnswered.get(q))), + fromError: errorSummary(common.map((q) => fromAnswered.get(q))), + agreement: + Object.keys(to.decision_agreement ?? {}).length > 0 + ? to.decision_agreement + : null, + }; +} + +export function exactComparison(benchmark, participants) { + const withRecords = participants.filter((p) => p.record); + const sets = withRecords.map((p) => answered(p.record)); + const common = + sets.length === 0 + ? [] + : [...sets[0].keys()].filter((q) => sets.every((s) => s.has(q))); + const rows = withRecords.map((p, i) => { + const own = sets[i]; + const times = common.map((q) => queryTime(benchmark, own.get(q))); + const complete = times.every((t) => t != null) && times.length > 0; + const cpus = common.map((q) => queryCpu(benchmark, own.get(q))); + return { + participant: p, + answered: own.size, + time: complete ? geomean(times) : null, + firstRun: + benchmark === "one-shot" && complete + ? geomean( + common.map((q) => finiteNumber(own.get(q).first_run_seconds)), + ) + : null, + cpu: + cpus.length > 0 && cpus.every((v) => v != null) ? geomean(cpus) : null, + error: errorSummary(common.map((q) => own.get(q))), + }; + }); + const fastest = Math.min(...rows.map((r) => r.time).filter((t) => t != null)); + for (const row of rows) { + row.relative = + row.time != null && Number.isFinite(fastest) ? row.time / fastest : null; + } + return { common, rows }; +} diff --git a/system-leaderboard/src/utils/loadJson.js b/system-leaderboard/src/utils/loadJson.js index c456cd84..83e9fdbf 100644 --- a/system-leaderboard/src/utils/loadJson.js +++ b/system-leaderboard/src/utils/loadJson.js @@ -1,20 +1,85 @@ -import { parseBenchmarkJsonl, SchemaViolation } from "./benchmarkRecord"; +import { parseBenchmarkJsonl } from "./benchmarkRecord"; +import { emptyCatalog, isCatalog, catalogOf } from "./catalog"; -export async function loadBenchmarkData() { - const response = await fetch(`${import.meta.env.BASE_URL}data/all.jsonl`); +const DATA = `${import.meta.env.BASE_URL}data/`; +async function fetchText(path, optional) { + const response = await fetch(`${DATA}${path}`); if (!response.ok) { + if (optional && response.status === 404) return null; throw new Error( - `could not load data/all.jsonl: ${response.status} ${response.statusText}`, + `could not load data/${path}: ${response.status} ${response.statusText}`, ); } - const text = await response.text(); - const { records, problems } = parseBenchmarkJsonl(text); + if (optional && text.trimStart().startsWith("<")) return null; + return text; +} + +function withSource(parsed, name) { + return { + records: parsed.records.map((r) => ({ ...r, source: r.source ?? name })), + problems: parsed.problems.map((p) => ({ ...p, source: name })), + }; +} - if (problems.some((p) => p.severity === "error")) { - throw new SchemaViolation(problems); +export async function loadPublishedSources() { + const listing = await fetchText("sources.json", true); + const manifest = listing + ? JSON.parse(listing) + : { + sources: [ + { name: "all.jsonl", records: "all.jsonl", catalog: "catalog.json" }, + ], + }; + const sources = []; + for (const entry of manifest.sources ?? []) { + const name = entry.name ?? entry.records; + const text = await fetchText(entry.records, false); + const parsed = withSource(parseBenchmarkJsonl(text), name); + const catalogText = entry.catalog + ? await fetchText(entry.catalog, true) + : null; + sources.push({ + name, + local: false, + ...parsed, + catalog: catalogText + ? catalogOf(JSON.parse(catalogText)) + : emptyCatalog(), + }); } + return { + title: manifest.title ?? null, + description: manifest.description ?? null, + sources, + }; +} - return { records, problems }; +export async function readLocalFile(file) { + const text = await file.text(); + const trimmed = text.trimStart(); + if (trimmed.startsWith("{") && !trimmed.includes("\n{")) { + let parsed; + try { + parsed = JSON.parse(text); + } catch { + parsed = null; + } + if (parsed && isCatalog(parsed)) { + return { + name: file.name, + local: true, + records: [], + problems: [], + catalog: catalogOf(parsed), + }; + } + } + return { + name: file.name, + local: true, + ...withSource(parseBenchmarkJsonl(text), file.name), + catalog: emptyCatalog(), + }; } diff --git a/system-leaderboard/src/utils/metrics.js b/system-leaderboard/src/utils/metrics.js index fa397c2f..acf5d3de 100644 --- a/system-leaderboard/src/utils/metrics.js +++ b/system-leaderboard/src/utils/metrics.js @@ -1,19 +1,9 @@ -export function formatConfig(item) { - return item.configuration ?? "—"; -} - export function runLabel(item) { return `${item.system}/${item.configuration}`; } -export function workloadsOf(records) { - return [...new Set(records.map((r) => r.workload))]; -} - -export function benchmarkLabel(benchmark) { - if (benchmark === "one-shot") return "One-shot SQL"; - if (benchmark === "periodic") return "Periodic PromQL"; - return benchmark ?? "—"; +export function benchmarkLabel(benchmark, catalog) { + return catalog?.benchmarks?.[benchmark]?.name ?? benchmark ?? "—"; } export function finiteNumber(v) { @@ -39,29 +29,24 @@ export function insertThroughput(item) { return finiteNumber(item.ingest_samples_per_second); } -export function queryThroughput(item) { - if (item.benchmark === "periodic") { - const ms = finiteNumber(item.median_query_ms); - return ms ? 1000 / ms : null; - } +export function answeredPerHotSecond(item) { + if (item.benchmark !== "one-shot") return null; const total = finiteNumber(item.total_hot_seconds); return total ? item.answered_count / total : null; } -export function queryLatencySeconds(item) { - if (item.benchmark === "periodic") { - const ms = finiteNumber(item.median_query_ms); - return ms != null ? ms / 1000 : null; - } - return finiteNumber(item.geomean_hot_seconds); +export function inverseMedianLatency(item) { + if (item.benchmark !== "periodic") return null; + const ms = finiteNumber(item.median_query_ms); + return ms ? 1000 / ms : null; } export function fmtMemory(bytes) { if (isInfinite(bytes)) return "∞"; if (bytes == null) return "—"; - if (bytes >= 1024 ** 3) return `${(bytes / 1024 ** 3).toFixed(1)} GB`; - if (bytes >= 1048576) return `${(bytes / 1048576).toFixed(1)} MB`; - if (bytes >= 1024) return `${(bytes / 1024).toFixed(1)} KB`; + if (bytes >= 1024 ** 3) return `${(bytes / 1024 ** 3).toFixed(1)} GiB`; + if (bytes >= 1048576) return `${(bytes / 1048576).toFixed(1)} MiB`; + if (bytes >= 1024) return `${(bytes / 1024).toFixed(1)} KiB`; return `${Math.round(bytes)} B`; } @@ -91,17 +76,28 @@ export function fmtSpeedup(v) { return `${v.toFixed(2)}×`; } +export function fmtRatio(v) { + if (v == null || !Number.isFinite(v)) return "—"; + return `${v >= 10 ? v.toFixed(1) : v.toFixed(2)}×`; +} + +export function instancesNote(item) { + if (!(item.instances > 1)) return null; + return `${item.instances} instances, each written all the data: cost totals are not comparable with a single instance`; +} + export function accuracyRows(item) { + const reference = item.error_reference ?? "not recorded"; const rows = [ { label: "Max relative error", value: fmtError(item.max_relative_error), - sub: "worst query", + sub: `worst query, against ${reference}`, }, { label: "Median relative error", value: fmtError(item.median_relative_error), - sub: "middle query", + sub: `middle query, against ${reference}`, }, ]; if (item.compared_count != null) { @@ -120,3 +116,24 @@ export function accuracyRows(item) { } return rows; } + +export function fmtSpeed(ratio) { + if (ratio == null || !Number.isFinite(ratio)) return "—"; + if (ratio < 1) return `${fmtRatio(1 / ratio)} faster`; + if (ratio > 1) return `${fmtRatio(ratio)} slower`; + return "same"; +} + +export function fmtCount(answered, total) { + return `${answered ?? "—"} / ${total ?? "—"}`; +} + +export function fmtMs(v) { + const n = finiteNumber(v); + return n == null ? "—" : `${n.toFixed(2)} ms`; +} + +export function fmtCpu(v) { + const n = finiteNumber(v); + return n == null ? "—" : `${n.toFixed(1)} s`; +} diff --git a/system-leaderboard/src/utils/querySets.js b/system-leaderboard/src/utils/querySets.js new file mode 100644 index 00000000..1f3f484f --- /dev/null +++ b/system-leaderboard/src/utils/querySets.js @@ -0,0 +1,117 @@ +export const querySetKey = (benchmark, workload) => `${benchmark}/${workload}`; + +const participantKey = (r) => `${r.system}/${r.configuration}`; + +function splitKey(key) { + const [system, ...rest] = key.split("/"); + return { system, configuration: rest.join("/") }; +} + +function emptySet(benchmark, workload) { + return { + key: querySetKey(benchmark, workload), + benchmark, + workload, + declaredQueries: null, + truth: null, + truthDescription: null, + pendingReason: null, + participants: new Map(), + }; +} + +function participantOf(set, key) { + if (!set.participants.has(key)) { + set.participants.set(key, { + key, + ...splitKey(key), + mode: null, + reference: null, + pending: [], + record: null, + index: -1, + }); + } + return set.participants.get(key); +} + +export function querySetsOf(records, catalog) { + const sets = new Map(); + const setOf = (benchmark, workload) => { + const key = querySetKey(benchmark, workload); + if (!sets.has(key)) sets.set(key, emptySet(benchmark, workload)); + return sets.get(key); + }; + + for (const [key, declared] of Object.entries(catalog?.query_sets ?? {})) { + const benchmark = declared.benchmark ?? key.split("/")[0]; + const workload = declared.workload ?? key.split("/").slice(1).join("/"); + const set = setOf(benchmark, workload); + set.declaredQueries = Array.isArray(declared.queries) + ? declared.queries + : null; + set.truth = declared.truth ?? null; + set.truthDescription = declared.truth_description ?? null; + set.pendingReason = declared.pending_reason ?? null; + for (const [name, p] of Object.entries(declared.participants ?? {})) { + const participant = participantOf(set, name); + participant.mode = p.mode ?? null; + participant.reference = p.reference ?? null; + participant.pending = p.pending ?? []; + } + } + + records.forEach((record, index) => { + const set = setOf(record.benchmark, record.workload); + const participant = participantOf(set, participantKey(record)); + participant.record = record; + participant.index = index; + participant.mode = participant.mode ?? record.mode; + participant.reference = participant.reference ?? record.baseline ?? null; + if (record.pending?.length) { + participant.pending = [ + ...new Set([...participant.pending, ...record.pending]), + ]; + } + set.truthDescription = set.truthDescription ?? record.error_reference; + }); + + return [...sets.values()].map((set) => { + const participants = [...set.participants.values()].sort( + (a, b) => + (a.mode === "exact" ? 0 : 1) - (b.mode === "exact" ? 0 : 1) || + a.key.localeCompare(b.key), + ); + const seen = []; + for (const p of participants) { + for (const q of p.record?.queries ?? []) { + if (!seen.includes(q.query)) seen.push(q.query); + } + } + const queries = set.declaredQueries ?? seen; + const texts = {}; + for (const p of participants) { + for (const q of p.record?.queries ?? []) { + if (q.text && !texts[q.query]) texts[q.query] = q.text; + } + } + return { + ...set, + queries, + texts, + participants, + exact: participants.filter((p) => p.mode === "exact"), + approximate: participants.filter((p) => p.mode !== "exact"), + sources: [ + ...new Set(participants.map((p) => p.record?.source).filter(Boolean)), + ], + }; + }); +} + +export function findQuerySet(sets, benchmark, workload) { + return sets.find((s) => s.benchmark === benchmark && s.workload === workload); +} + +export const isPending = (participant, measurement) => + (participant?.pending ?? []).includes(measurement); diff --git a/system-leaderboard/src/utils/schema.json b/system-leaderboard/src/utils/schema.json index fa7abdb0..d140c64f 100644 --- a/system-leaderboard/src/utils/schema.json +++ b/system-leaderboard/src/utils/schema.json @@ -1,17 +1,18 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", "title": "SystemRecord", - "description": "One line of all.jsonl as scripts/system-leaderboard-data.py writes it: one system in one configuration on one workload, with its per-query results under queries.", - "x-schema-version": 2, + "description": "One line of a records file (all.jsonl) as scripts/system-leaderboard-data.py writes it: one system in one configuration on one workload, with its per-query results under queries. Display names live in the catalog file, not here.", + "x-schema-version": 3, "type": "object", "properties": { - "schema_version": { "const": 2 }, - "benchmark": { "enum": ["one-shot", "periodic"] }, + "schema_version": { "enum": [2, 3] }, + "benchmark": { "type": "string", "minLength": 1 }, "workload": { "type": "string", "minLength": 1 }, "system": { "type": "string", "minLength": 1 }, "configuration": { "type": "string", "minLength": 1 }, "mode": { "enum": ["exact", "approximate"] }, "baseline": { "type": ["string", "null"] }, + "error_reference": { "type": ["string", "null"] }, "version": { "type": ["string", "null"] }, "build_profile": { "type": ["string", "null"] }, "options": { "type": "object" }, @@ -29,6 +30,7 @@ "load_seconds": { "$ref": "#/$defs/Measurement" }, "data_size_bytes": { "$ref": "#/$defs/Measurement" }, "peak_memory_bytes": { "$ref": "#/$defs/Measurement" }, + "largest_instance_peak_memory_bytes": { "$ref": "#/$defs/Measurement" }, "ingest_samples_per_second": { "$ref": "#/$defs/Measurement" }, "median_query_ms": { "$ref": "#/$defs/Measurement" }, "p99_query_ms": { "$ref": "#/$defs/Measurement" }, @@ -53,6 +55,13 @@ "queries": { "type": "array", "items": { "$ref": "#/$defs/Query" } + }, + "source": { "type": "string" }, + "pending": { + "type": "array", + "items": { + "enum": ["time", "cpu", "memory", "accuracy", "decision"] + } } }, "required": [ @@ -123,7 +132,9 @@ "extra_groups": { "type": ["integer", "null"], "minimum": 0 }, "differing_text_cells": { "type": ["integer", "null"], "minimum": 0 }, "truth_stable": { "type": "boolean" }, - "peak_memory_bytes": { "$ref": "#/$defs/Measurement" } + "peak_memory_bytes": { "$ref": "#/$defs/Measurement" }, + "cpu_seconds": { "$ref": "#/$defs/Measurement" }, + "median_query_ms": { "$ref": "#/$defs/Measurement" } }, "required": ["query", "text", "status", "max_relative_error"] }