forked from mtusi2026/mtusi2026lab3
feat: add new experiment to test GOMAXPROCS and DB CPU limit
This commit is contained in:
@@ -0,0 +1,210 @@
|
||||
"""Recompute v2 results from individual requests; never touch v1 evidence."""
|
||||
import csv
|
||||
import gzip
|
||||
import json
|
||||
from collections import defaultdict
|
||||
|
||||
from design import CONFIGS, bracket, pair_decision
|
||||
from runtime import digest, legacy_analysis, save, workload
|
||||
|
||||
|
||||
def read(path):
|
||||
return json.loads(path.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def jsonl(path):
|
||||
with gzip.open(path, "rt", encoding="utf-8") as stream:
|
||||
return [json.loads(line) for line in stream]
|
||||
|
||||
|
||||
def audit(directory, manifest, design):
|
||||
summary = read(directory / "summary.json")
|
||||
rows = jsonl(directory / "requests.jsonl.gz")
|
||||
successes = [row for row in rows if row["success"]]
|
||||
sent = [row for row in rows if "start_s" in row]
|
||||
duration = design["duration_s"]
|
||||
calculated = {
|
||||
"scheduled": len(rows), "sent": len(sent), "successes": len(successes),
|
||||
"errors": len(rows) - len(successes), "generator_dropped": len(rows) - len(sent),
|
||||
"success_ratio": len(successes) / max(1, len(rows)),
|
||||
"goodput_rps": len(successes) / duration,
|
||||
"window_goodput_rps": sum(row["end_s"] <= duration for row in successes) / duration,
|
||||
"p95_ms": workload.percentile([row["latency_ms"] for row in successes], .95),
|
||||
"dispatch_p95_ms": workload.percentile([row["dispatch_lag_ms"] for row in sent], .95),
|
||||
}
|
||||
mismatches = [key for key, value in calculated.items() if summary.get(key) != value]
|
||||
if len(rows) != round(manifest["rate"] * duration):
|
||||
mismatches.append("expected_request_count")
|
||||
if manifest["protocol_sha256"] != digest(design):
|
||||
mismatches.append("protocol_sha256")
|
||||
if len({row["index"] for row in rows}) != len(rows):
|
||||
mismatches.append("unique_request_index")
|
||||
valid = summary["valid"] and not mismatches
|
||||
slo = valid and summary["correctness"]["passed"] and calculated["success_ratio"] >= .99 and calculated["p95_ms"] is not None and calculated["p95_ms"] <= 500
|
||||
diagnostic = legacy_analysis.diagnostics(directory, manifest)
|
||||
return {**manifest, **summary, **calculated, "valid": valid, "slo_pass": slo,
|
||||
"audit_mismatches": mismatches, "diagnostics": diagnostic,
|
||||
"database_counters": database_counters(jsonl(directory / "telemetry.jsonl.gz"))}
|
||||
|
||||
|
||||
def database_counters(samples):
|
||||
values = [row["postgres"] for row in samples if "postgres" in row]
|
||||
if len(values) < 2:
|
||||
return {"available": False}
|
||||
first, last = values[0], values[-1]
|
||||
result = {"available": True, "note": "First-to-last sampled counters, not the full request window; waits are sample counts, not wait durations."}
|
||||
for section, keys in (("wal", ("wal_records", "wal_bytes", "wal_write", "wal_sync", "wal_write_time", "wal_sync_time")),
|
||||
("database", ("xact_commit", "xact_rollback", "blks_read", "blks_hit", "deadlocks"))):
|
||||
reset = first[section].get("stats_reset") != last[section].get("stats_reset")
|
||||
delta = {key: float(last[section][key]) - float(first[section][key]) for key in keys}
|
||||
result[section] = {"reset_detected": reset or any(value < 0 for value in delta.values()), "delta": delta}
|
||||
io = {}
|
||||
old = {(row["object"], row["context"]): row for row in first["io"]}
|
||||
for row in last["io"]:
|
||||
prior = old.get((row["object"], row["context"]))
|
||||
if prior:
|
||||
keys = ("reads", "read_time", "writes", "write_time", "extends", "extend_time", "fsyncs", "fsync_time")
|
||||
delta = {key: float(row[key] or 0) - float(prior[key] or 0) for key in keys}
|
||||
io[row["object"] + "/" + row["context"]] = {"delta": delta, "reset_detected": row.get("stats_reset") != prior.get("stats_reset") or any(v < 0 for v in delta.values())}
|
||||
result["io"] = io
|
||||
return result
|
||||
|
||||
|
||||
def capacities(runs, schedule):
|
||||
result = []
|
||||
for name in CONFIGS:
|
||||
for repeat in (1, 2, 3):
|
||||
points = [row for row in runs if row["phase"] == "scaling" and row["base"] == name and row["repeat"] == repeat]
|
||||
bound = bracket(points)
|
||||
expected = len([row for row in schedule if row["base"] == name and row["repeat"] == repeat])
|
||||
incomplete = len(points) != expected or not expected
|
||||
result.append({"config": name, "repeat": repeat, "capacity_lower": bound["lower"],
|
||||
"capacity_upper": bound["upper"], "nonmonotonic": bound["nonmonotonic"],
|
||||
"invalid_rates": [row["rate"] for row in points if not row["valid"]] + (["missing"] if incomplete else [])})
|
||||
return result
|
||||
|
||||
|
||||
def gomax_results(runs):
|
||||
result = {}
|
||||
for regime in ("low", "high"):
|
||||
pairs = []
|
||||
for repeat in range(1, 6):
|
||||
values = {row["variant"]: row for row in runs if row["phase"] == "gomax" and row["regime"] == regime and row["repeat"] == repeat}
|
||||
if "I0" not in values or "I1" not in values:
|
||||
continue
|
||||
control, tuned = values["I0"], values["I1"]
|
||||
numeric = control["p95_ms"] is not None and control["p95_ms"] > 0 and tuned["p95_ms"] is not None
|
||||
reduction = 100 * (1 - tuned["p95_ms"] / control["p95_ms"]) if numeric else None
|
||||
valid = numeric and control["valid"] and tuned["valid"] and control["rate"] == tuned["rate"] and control["correctness"]["passed"] and tuned["correctness"]["passed"]
|
||||
met = numeric and tuned["p95_ms"] <= .85 * control["p95_ms"] and tuned["p95_ms"] <= 500 and tuned["success_ratio"] >= max(.99, control["success_ratio"])
|
||||
pairs.append({"repeat": repeat, "rate": control["rate"], "control_p95_ms": control["p95_ms"], "tuned_p95_ms": tuned["p95_ms"],
|
||||
"valid": bool(valid), "criteria_met": bool(met), "reduction_percent": reduction})
|
||||
result["G_" + regime] = pair_decision(pairs)
|
||||
return result
|
||||
|
||||
|
||||
def db_results(runs, confirmation):
|
||||
bounds = confirmation.get("pilot_bounds", {}).get("B4", {})
|
||||
lower, upper = bounds.get("lower"), bounds.get("upper")
|
||||
blocks = []
|
||||
for repeat in (1, 2, 3):
|
||||
values = {(row["variant"], row["rate"]): row for row in runs if row["phase"] == "database" and row["repeat"] == repeat}
|
||||
required = [(variant, rate) for variant in ("D0", "D1") for rate in (lower, upper)]
|
||||
if not lower or not upper or any(key not in values for key in required):
|
||||
continue
|
||||
dl, du, tl, tu = (values[key] for key in (("D0", lower), ("D0", upper), ("D1", lower), ("D1", upper)))
|
||||
cpu = du["diagnostics"]["cpu_fraction_of_limit_mean"]
|
||||
eligible = cpu.get("db", -1) >= .90 and 0 <= cpu.get("api", -1) < .85 and 0 <= cpu.get("haproxy", -1) < .90
|
||||
valid = all(values[key]["valid"] and values[key]["correctness"]["passed"] for key in required)
|
||||
restored = dl["slo_pass"] and tl["slo_pass"] and not du["slo_pass"] and tu["slo_pass"]
|
||||
blocks.append({"repeat": repeat, "valid": valid, "cpu_prerequisites_met": eligible,
|
||||
"slo_restored": restored, "baseline_upper_cpu": cpu})
|
||||
supported = len(blocks) == 3 and all(row["valid"] and row["cpu_prerequisites_met"] and row["slo_restored"] for row in blocks)
|
||||
return {"result": "supported" if supported else "inconclusive", "blocks": blocks,
|
||||
"note": "Doubling CPU tests a CPU bottleneck only. No effect does not disprove a WAL, storage, lock or pool bottleneck."}
|
||||
|
||||
|
||||
def plots(directory, caps, hypotheses, runs):
|
||||
import matplotlib
|
||||
matplotlib.use("Agg")
|
||||
import matplotlib.pyplot as plt
|
||||
fig, ax = plt.subplots(figsize=(10, 4))
|
||||
for index, row in enumerate(caps):
|
||||
lower, upper = row["capacity_lower"], row["capacity_upper"]
|
||||
ax.plot(index, lower, "o", color="tab:blue")
|
||||
if upper is not None:
|
||||
ax.plot([index, index], [lower, upper], color="tab:blue")
|
||||
ax.plot(index, upper, "x", color="tab:red")
|
||||
else:
|
||||
ax.annotate("≥", (index, lower), xytext=(0, 7), textcoords="offset points", ha="center")
|
||||
ax.set_xticks(range(len(caps)), [r["config"] + "/" + str(r["repeat"]) for r in caps], rotation=60)
|
||||
ax.set(ylabel="Offered requests/s", title="Confirmation capacity brackets (not confidence intervals)")
|
||||
ax.grid(axis="y", alpha=.2)
|
||||
fig.tight_layout(); fig.savefig(directory / "capacity.png", dpi=160); plt.close(fig)
|
||||
fig, axes = plt.subplots(1, 2, figsize=(9, 4))
|
||||
for ax, regime in zip(axes, ("low", "high")):
|
||||
for pair in hypotheses["G_" + regime]["pairs"]:
|
||||
ax.plot([0, 1], [pair["control_p95_ms"], pair["tuned_p95_ms"]], "o-", label="pair " + str(pair["repeat"]))
|
||||
ax.set_xticks([0, 1], ["GOMAXPROCS=16", "GOMAXPROCS=1"])
|
||||
ax.set(title=regime, ylabel="Successful request p95, ms")
|
||||
ax.grid(alpha=.2)
|
||||
fig.tight_layout(); fig.savefig(directory / "gomax.png", dpi=160); plt.close(fig)
|
||||
points = [row for row in runs if row["phase"] == "database"]
|
||||
if points:
|
||||
fig, ax = plt.subplots(figsize=(8, 4))
|
||||
for variant in ("D0", "D1"):
|
||||
group = [row for row in points if row["variant"] == variant]
|
||||
ax.scatter([r["rate"] for r in group], [r["p95_ms"] for r in group], label=variant)
|
||||
ax.axhline(500, color="red", linestyle="--", label="p95 SLO (also success ≥99%)")
|
||||
ax.set(xlabel="Offered requests/s", ylabel="Successful request p95, ms")
|
||||
ax.legend(); fig.tight_layout(); fig.savefig(directory / "database.png", dpi=160); plt.close(fig)
|
||||
|
||||
|
||||
def analyze(directory):
|
||||
design = read(directory / "design.json")
|
||||
if digest(design) != (directory / "design.sha256").read_text().strip():
|
||||
raise ValueError("Design checksum mismatch")
|
||||
confirmation = read(directory / "confirmation.json") if (directory / "confirmation.json").exists() else {}
|
||||
if confirmation and (digest(confirmation) != (directory / "confirmation.sha256").read_text().strip() or confirmation["design_sha256"] != digest(design)):
|
||||
raise ValueError("Confirmation schedule checksum mismatch")
|
||||
runs, incomplete = [], []
|
||||
for item in read(directory / "execution-order.json") if (directory / "execution-order.json").exists() else []:
|
||||
target = directory / item["directory"]
|
||||
if not (target / "summary.json").exists():
|
||||
incomplete.append(item["directory"])
|
||||
continue
|
||||
manifest = read(target / "manifest.json")
|
||||
run = audit(target, manifest, design)
|
||||
if any(manifest.get(key) != item.get(key) for key in ("phase", "base", "rate", "repeat", "variant", "config", "sequence")):
|
||||
run.update(valid=False, slo_pass=False)
|
||||
run["audit_mismatches"].append("execution_order")
|
||||
runs.append(run)
|
||||
caps = capacities(runs, confirmation.get("scaling", []))
|
||||
hypotheses = {**legacy_analysis.hypothesis_decisions(caps), **gomax_results(runs), "DB_CPU": db_results(runs, confirmation)}
|
||||
if design["smoke_only"]:
|
||||
hypotheses = {name: {"result": "not_tested_smoke_only"} for name in hypotheses}
|
||||
result = {"series": design["series"], "smoke_only": design["smoke_only"], "status": read(directory / "status.json"),
|
||||
"incomplete_runs": incomplete, "hypotheses": hypotheses, "capacities": caps, "runs": runs}
|
||||
save(directory / "analysis.json", result)
|
||||
keys = ["phase", "base", "variant", "repeat", "rate", "scheduled", "sent", "successes", "errors", "generator_dropped",
|
||||
"success_ratio", "goodput_rps", "window_goodput_rps", "p95_ms", "dispatch_p95_ms", "valid", "slo_pass"]
|
||||
with (directory / "summary.csv").open("w", newline="", encoding="utf-8") as stream:
|
||||
writer = csv.DictWriter(stream, fieldnames=keys, extrasaction="ignore")
|
||||
writer.writeheader(); writer.writerows(runs)
|
||||
lines = ["# Результаты " + design["series"], "", "Статус: `" + result["status"]["status"] + "`. Завершённых измерений: " + str(len(runs)) + ".", ""]
|
||||
if design["smoke_only"]:
|
||||
lines += ["Короткая проверка инструментов. Эти данные не проверяют гипотезы и не входят в исследование.", ""]
|
||||
else:
|
||||
lines += ["| Гипотеза | Результат |", "| --- | --- |"] + [f"| {name} | {value['result']} |" for name, value in hypotheses.items()]
|
||||
lines += ["", "supported — критерий выполнен во всех повторах; refuted — во всех парах получен противоположный результат; inconclusive — данных недостаточно или повторы расходятся.", "",
|
||||
"[Сводная таблица](summary.csv), [полный расчёт и диагностика](analysis.json), [зафиксированная методика](design.json).",
|
||||
"", "Пилотные измерения выбирают нагрузку и не входят в подтверждающую серию. Пределы мощности — границы на проверенной сетке, а не доверительные интервалы. Если верхняя граница не найдена, известно только C ≥ нижней границы.", "",
|
||||
"GOMAXPROCS оценивается по отдельным парам. Среднее, медиана и диапазон процентов снижения p95 приведены в analysis.json; p95 разных прогонов не объединяются. Среднее не заменяет критерий пяти пар.", "",
|
||||
"Счётчики WAL/I/O отражают разницу между первым и последним образцом телеметрии. Частота наблюдения ожиданий не равна времени ожидания. Удвоение CPU БД проверяет только ограничение CPU; отсутствие эффекта не исключает ограничения диска, WAL или блокировок.", "",
|
||||
"", "", ""]
|
||||
if any(row["phase"] == "database" for row in runs):
|
||||
lines += ["", ""]
|
||||
plots(directory, caps, hypotheses, runs)
|
||||
(directory / "RESULTS.md").write_text("\n".join(lines) + "\n", encoding="utf-8")
|
||||
print("Analysis: " + str(directory / "RESULTS.md"), flush=True)
|
||||
return result
|
||||
Reference in New Issue
Block a user