Files
mtusi2026lab2/bench/analyze_track2.py
T

192 lines
6.5 KiB
Python

"""Расчёты трека 2 из неизменённых файлов стенда; результат — JSON в stdout.
uv run python bench/analyze_track2.py
Шум CPU оценивается в своей метрике, по протоколу REPORT.md,
зафиксированному до прогонов. Скрипт не меняет результаты и не запускает
нагрузку. Числа в отчёте можно проверить этой же командой.
"""
import argparse
import csv
import json
import statistics
from pathlib import Path
import compare
ROOT = Path(__file__).resolve().parents[1]
METRICS = (
"rps",
"p50_ms",
"p95_ms",
"p99_ms",
"cpu_us_per_req",
"db_cpu_us_per_req",
"app_cpu_cores",
"db_cpu_cores",
)
def stats(rows: list[dict]) -> dict:
grouped: dict[tuple, list] = {}
for row in rows:
key = (row["scenario"], row.get("chat_class", ""), int(row["clients"]))
grouped.setdefault(key, []).append(row)
return {
key: {
metric: (
statistics.median(values),
min(values),
max(values),
)
for metric in METRICS
if (values := [float(row[metric]) for row in group])
}
for key, group in grouped.items()
}
def load(label: str) -> dict:
data = compare.load(label)
meta = data["meta"]
if (
meta.get("aborted")
or meta.get("host_warnings")
or meta["code"].get("git_dirty")
or any(row["flags"] or int(row["errors"]) for row in data["rows"])
):
raise SystemExit(f"analyze: label {label} is not a clean completed run")
profile = meta["profile"]
if profile["name"] != "skew":
raise SystemExit(f"analyze: expected skew, got {profile['name']}")
expected = {
(scenario, chat_class, clients, repeat)
for scenario, chat_class in [
*(("read", name) for name, _, _ in profile["classes"]),
("write", ""),
]
for clients in profile["clients"]
for repeat in range(1, profile["repeats"] + 1)
}
actual = {
(r["scenario"], r["chat_class"], int(r["clients"]), int(r["repeat"]))
for r in data["rows"]
}
if actual != expected or len(data["rows"]) != len(expected):
raise SystemExit(f"analyze: label {label} has an incomplete matrix")
data["stats"] = stats(data["rows"])
return data
def restore(label: str) -> dict:
data = json.loads(
(ROOT / "evidence" / "restore" / label / "restore.json").read_text()
)
if (
data.get("aborted")
or not data["checks"]
or not all(row["ok"] for row in data["checks"])
):
raise SystemExit(f"analyze: restore {label} did not pass all checks")
return {
"label": label,
"counts": data["before"]["counts"],
"timings": data["timings"],
"dump_bytes": data["backup"]["dump_bytes"],
"lost_messages": data["after_backup"]["messages_in_source"]
- data["restored"]["counts"]["messages"],
"checks": data["checks"],
}
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
for option, default in (
("keyset", "t2-keyset"),
("aa", "t2-keyset-2"),
("chat-only", "t2-chat-only"),
("no-index", "t2-no-index"),
("restore", "restore"),
("restore-repeat", "restore-2"),
):
parser.add_argument(f"--{option}", default=default)
args = parser.parse_args()
labels = [args.keyset, args.aa, args.chat_only, args.no_index]
runs = [load(label) for label in labels]
base, aa, chat_only, no_index = runs
methodology = compare.methodology(base["meta"])
for data in runs[1:]:
if compare.methodology(data["meta"]) != methodology:
raise SystemExit("analyze: experiment methodology differs")
for section, keys in (
("host", compare.HOST_KEYS),
("docker", compare.DOCKER_KEYS),
):
if any(
data["meta"][section].get(key) != base["meta"][section].get(key)
for key in keys
):
raise SystemExit(f"analyze: {section} differs between labels")
if data["meta"]["code"]["src_sha256"] != base["meta"]["code"]["src_sha256"]:
raise SystemExit("analyze: application code differs")
if [data["meta"]["variant"] for data in runs] != [
"keyset",
"keyset",
"chat-only",
"no-index",
]:
raise SystemExit("analyze: unexpected index variants")
cpu_metric = "db_cpu_us_per_req"
cpu_noise = max(
abs(compare.delta(base["stats"][key][cpu_metric][0], value[cpu_metric][0]))
for key, value in aa["stats"].items()
if key[0] == "write"
)
result = {
"rps_noise_percent": compare.noise_levels(
compare.cell_stats(base["rows"]), compare.cell_stats(aa["rows"])
),
"write_db_cpu_noise_percent": cpu_noise,
"variants": {},
"write_db_cpu_comparisons": [],
"restores": [restore(args.restore), restore(args.restore_repeat)],
}
for data in runs:
memory = next(iter(data["memory"].values()))
result["variants"][data["label"]] = {
"duration_s": data["meta"]["duration_s"],
"cells": [
{"scenario": key[0], "chat_class": key[1], "clients": key[2], **value}
for key, value in sorted(data["stats"].items())
],
"plans": data["meta"]["plans"],
"memory": memory,
"fill": list(
csv.DictReader(
(ROOT / "evidence" / "bench" / data["label"] / "fill.csv").open()
)
),
}
for before, after in ((base, chat_only), (chat_only, no_index), (base, no_index)):
for key in sorted(base["stats"]):
if key[0] != "write":
continue
b, a = before["stats"][key][cpu_metric], after["stats"][key][cpu_metric]
result["write_db_cpu_comparisons"].append(
{
"before": before["label"],
"after": after["label"],
"clients": key[2],
"before_us": b,
"after_us": a,
"delta_percent": compare.delta(b[0], a[0]),
"verdict": compare.verdict(b, a, cpu_noise),
}
)
print(json.dumps(result, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()