Plot track 1 series and tabulate the ceilings

tools/plot_track1.py reads any set of summary.csv files and draws, per
series, successful RPS, p95 and p99 against the offered rate and CPU
per component against its limit, plus two cross-series charts: peak
successful RPS against total API CPU with the linear growth line, and
the utilisation of API, PostgreSQL, balancer and the share of the pool
waiting on a lock at each config's peak. A point is the median of the
repeats, the whiskers are min and max. capacity.csv and capacity.md
hold the SLO capacity, the peak and the resource figures at the peak.

Colours follow the config across charts, every line also has its own
marker and a direct label. matplotlib comes through uv run --with, so
the tool lives in tools/ and stays out of the 3.9 scripts; make plots
runs it, make lint covers it.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Artyom
2026-10-28 20:35:05 +03:00
co-authored by Claude Opus 5.5
parent 8ea1996063
commit e8804b05d0
4 changed files with 309 additions and 7 deletions
+8 -4
View File
@@ -10,7 +10,7 @@ COMPOSE ?= docker compose
RATE ?= 100
API_IMAGE ?= mtusi-messenger:lab3
FROM_REV ?=
SCRIPTS_PY = scripts/probe.py scripts/limits.py scripts/scaling.py
SCRIPTS_PY = scripts/probe.py scripts/limits.py scripts/scaling.py tools
TRACK1 = evidence/track1
SCALING = $(PYTHON) scripts/scaling.py --fresh-db --start-per-cpu 150
PSQL = $(COMPOSE) exec -T postgres psql -U messenger -d messenger -X -q
@@ -20,7 +20,7 @@ PSQL = $(COMPOSE) exec -T postgres psql -U messenger -d messenger -X -q
secrets up down reset-data migrate ps logs restore lb-check failover-evidence stack-evidence \
persistence-evidence storage-evidence cache-evidence test-faults seed explain \
limits detection failover-each rolling-update level4 \
track1 track1-host track1-a track1-b
track1 track1-host track1-a track1-b plots
help:
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
@@ -28,7 +28,7 @@ help:
@echo "secrets/up/down/migrate/ps/logs: стенд Docker Compose; reset-data: намеренное удаление volumes"
@echo "restore: вернуть остановленные реплики; lb-check: реплики на одном токене и 20 гонок одного ключа"
@echo "level4 = limits, lb-check, detection, failover-each, rolling-update [FROM_REV=<коммит>]; RATE=$(RATE) rps"
@echo "track1 = track1-host, track1-a (1x4/2x2/4x1), track1-b (1x1/2x1/8x1) → $(TRACK1)"
@echo "track1 = track1-host, track1-a (1x4/2x2/4x1), track1-b (1x1/2x1/8x1), plots → $(TRACK1)"
check:
$(PYTHON) scripts/check_contract.py
@@ -118,7 +118,7 @@ endif
level4: limits lb-check detection failover-each rolling-update
track1: track1-host track1-a track1-b
track1: track1-host track1-a track1-b plots
track1-host:
sh scripts/host-snapshot.sh $(TRACK1)/host.txt
@@ -129,6 +129,10 @@ track1-a:
track1-b:
$(SCALING) --out $(TRACK1)/series-b --configs 1x1,2x1,8x1 --api-memory 512
plots:
MPLBACKEND=Agg $(UV) run --no-project --python 3.14 --with 'matplotlib==3.11.2' \
python tools/plot_track1.py --out $(TRACK1)/plots $(wildcard $(TRACK1)/*/summary.csv)
failover-evidence:
sh scripts/failover-evidence.sh "$(BASE_URL)"
@@ -6,9 +6,9 @@
## 2. Сэмплеры и оркестратор
- [x] 2.1 `scripts/docker-stats.sh`, `scripts/lb-stats.sh`, `scripts/pg-stats.sh` (activity, statements, reset, размер базы)
- [x] 2.2 `scripts/scaling.py`: конфигурация `RxC` с воркерами, пулом, очередью LB на реплику и закреплением CPU; поиск колена с повторами; `summary.csv` и сырьё шага; `probe.py` — ожидание реплик в LB
- [x] 2.2 `scripts/scaling.py`: конфигурация `RxC` с воркерами, пулом, очередью LB на реплику и закреплением CPU; ожидание ровно R реплик в LB; поиск колена с повторами; варианты «до/после» с чередованием; `summary.csv` и сырьё шага
- [ ] 2.3 `tools/plot_track1.py` и `make plots`; цели `make track1-a`, `track1-b`, `track1-compare`, `track1`
- [ ] 2.4 Проверка группы: `make lint`, `make check`, пробный шаг `scaling.py` на одной интенсивности
- [x] 2.4 Проверка группы: `make lint`, `make check`, пробный шаг `scaling.py` на одной интенсивности
## 3. Серии
+2 -1
View File
@@ -37,7 +37,7 @@ packages = ["src/messenger"]
[tool.ruff]
line-length = 100
target-version = "py314"
src = ["src", "student-tests"]
src = ["src", "student-tests", "tools"]
extend-exclude = ["tests", "scripts/check_contract.py", "scripts/validate_openapi.py"]
per-file-target-version = { "scripts/*.py" = "py39" }
@@ -79,6 +79,7 @@ ignore = [
[tool.ruff.lint.per-file-ignores]
"student-tests/**" = ["S101", "S105", "S106", "S603", "S607", "PLR2004", "ARG001", "T20", "TID251"]
"scripts/*.py" = ["T20", "S603", "S607", "S310", "PLR2004", "TID251", "SIM905"]
"tools/*.py" = ["T20", "SIM905"]
"src/messenger/*/infrastructure/**" = ["TID251", "ARG002"]
"src/messenger/*/domain/errors.py" = ["N818"]
"src/messenger/*/application/errors.py" = ["N818"]
+297
View File
@@ -0,0 +1,297 @@
import argparse
import collections
import csv
import statistics
from pathlib import Path
import matplotlib.pyplot as plt
ORDER = ("1x1", "2x1", "4x1", "8x1", "2x2", "1x4")
PALETTE = ("#2a78d6", "#eb6834", "#1baf7a", "#eda100", "#e87ba4", "#008300", "#6250d6", "#e34948")
MARKERS = ("o", "s", "^", "D", "v", "P", "X", "*")
COMPONENTS = (("api", "API"), ("postgres", "PostgreSQL"), ("lb", "HAProxy"), ("k6", "k6"))
INK, MUTED, GRID, SURFACE = "#0b0b0b", "#52514e", "#e4e3df", "#fcfcfb"
SUMMARY = (
"series variant config rates capacity_rate capacity_ok_rps capacity_p95_ms capacity_p99_ms "
"peak_rate peak_ok_rps peak_ok_min peak_ok_max peak_p95_ms peak_failed_ratio peak_dropped "
"cpu_api cpu_api_limit cpu_postgres cpu_lb cpu_k6 pg_active_avg pg_lock_avg pg_idle_tx_avg "
"pg_idle_avg pool_total pg_backends_max lb_qcur_max"
).split()
plt.rcParams.update(
{
"figure.facecolor": SURFACE,
"axes.facecolor": SURFACE,
"axes.edgecolor": MUTED,
"axes.labelcolor": MUTED,
"axes.titlecolor": INK,
"axes.titleweight": "bold",
"axes.grid": True,
"grid.color": GRID,
"grid.linewidth": 0.8,
"axes.spines.top": False,
"axes.spines.right": False,
"xtick.color": MUTED,
"ytick.color": MUTED,
"legend.frameon": False,
"lines.linewidth": 2,
"lines.markersize": 7,
"font.size": 10,
}
)
VARIANTS = {
"before": {"color": MUTED, "marker": "o"},
"after": {"color": PALETTE[0], "marker": "s"},
}
def style(name):
index = ORDER.index(name) if name in ORDER else len(ORDER)
return {"color": PALETTE[index], "marker": MARKERS[index]}
def load(paths):
groups = collections.defaultdict(lambda: collections.defaultdict(list))
for path in paths:
with Path(path).open() as handle:
for row in csv.DictReader(handle):
key = (Path(path).parent.name, row["variant"], row["config"])
groups[key][int(row["rate"])].append(row)
return groups
def med(rows, field):
values = [float(r[field]) for r in rows]
middle = statistics.median(values)
return middle, middle - min(values), max(values) - middle
def label(key):
return key[2] if key[1] == "base" else f"{key[2]} {key[1]}"
def summarize(key, rates):
series, variant, config = key
sat = {rate: any(r["saturated"] == "True" for r in rows) for rate, rows in rates.items()}
capacity = max((rate for rate, bad in sat.items() if not bad), default=None)
peak = max(rates, key=lambda rate: med(rates[rate], "ok_rps")[0])
top, first = rates[peak], rates[peak][0]
replicas, workers, pool = (int(first[f]) for f in ("replicas", "workers", "pool"))
row = {
"series": series,
"variant": variant,
"config": config,
"rates": " ".join(str(r) for r in sorted(rates)),
"peak_rate": peak,
"peak_ok_rps": med(top, "ok_rps")[0],
"peak_ok_min": min(float(r["ok_rps"]) for r in top),
"peak_ok_max": max(float(r["ok_rps"]) for r in top),
"peak_p95_ms": med(top, "p95_ms")[0],
"peak_failed_ratio": med(top, "failed_ratio")[0],
"peak_dropped": med(top, "dropped_iterations")[0],
"cpu_api_limit": round(replicas * float(first["cpus"]) * 100),
"pool_total": replicas * workers * pool,
}
for field in (
"cpu_api cpu_postgres cpu_lb cpu_k6 pg_active_avg pg_lock_avg pg_idle_tx_avg "
"pg_idle_avg pg_backends_max lb_qcur_max"
).split():
row[field] = round(med(top, field)[0], 2)
if capacity is not None:
for field, name in (("ok_rps", "ok_rps"), ("p95_ms", "p95_ms"), ("p99_ms", "p99_ms")):
row[f"capacity_{name}"] = med(rates[capacity], field)[0]
row["capacity_rate"] = capacity
return row
def direct_label(axis, x, y, text):
axis.annotate(
text, (x, y), xytext=(6, 0), textcoords="offset points", va="center", color=INK, fontsize=9
)
def lines(axis, keys, groups, field):
for key in keys:
rates = sorted(groups[key])
values = [med(groups[key][rate], field) for rate in rates]
look = VARIANTS.get(key[1]) or style(key[2])
axis.errorbar(
rates,
[v[0] for v in values],
yerr=[[v[1] for v in values], [v[2] for v in values]],
capsize=3,
label=label(key),
markeredgecolor=SURFACE,
markeredgewidth=1.5,
**look,
)
direct_label(axis, rates[-1], values[-1][0], label(key))
def throughput(series, keys, groups, out):
figure, axes = plt.subplots(1, 3, figsize=(17, 4.8))
top = max(rate for key in keys for rate in groups[key])
axes[0].plot(
[0, top], [0, top], color=MUTED, linestyle="--", linewidth=1, label="RPS = нагрузка"
)
lines(axes[0], keys, groups, "ok_rps")
axes[0].set_title("Успешные RPS")
for axis, field, title in ((axes[1], "p95_ms", "p95, мс"), (axes[2], "p99_ms", "p99, мс")):
lines(axis, keys, groups, field)
axis.set_yscale("log")
axis.set_title(title)
for axis in axes:
axis.set_xlabel("Предложенная нагрузка, запросов/с")
axis.legend(loc="upper left", fontsize=9)
figure.suptitle(f"{series}: медиана 3 повторов, усы — min–max", color=INK)
figure.tight_layout()
figure.savefig(out / f"{series}-throughput.png", dpi=150)
plt.close(figure)
def cpu(series, keys, groups, out):
figure, axes = plt.subplots(1, len(keys), figsize=(5 * len(keys), 4.2), squeeze=False)
for axis, key in zip(axes[0], keys, strict=True):
rates = sorted(groups[key])
first = groups[key][rates[0]][0]
limit = int(first["replicas"]) * float(first["cpus"]) * 100
for index, (field, name) in enumerate(COMPONENTS):
values = [med(groups[key][rate], f"cpu_{field}")[0] for rate in rates]
axis.plot(rates, values, color=PALETTE[index], marker=MARKERS[index], label=name)
axis.axhline(limit, color=PALETTE[0], linestyle=":", linewidth=1.2, label="лимит API")
axis.axhline(200, color=PALETTE[1], linestyle=":", linewidth=1.2, label="лимит PostgreSQL")
axis.set_title(f"CPU, % ядра — {label(key)}")
axis.set_xlabel("Предложенная нагрузка, запросов/с")
axis.legend(fontsize=8, loc="upper left")
figure.tight_layout()
figure.savefig(out / f"{series}-cpu.png", dpi=150)
plt.close(figure)
def scaling(rows, out):
by = {(r["series"], r["config"]): r for r in rows if r["variant"] == "base"}
growth = [
by.get(("series-b", c)) or by.get(("series-a", c)) for c in ("1x1", "2x1", "4x1", "8x1")
]
growth = [r for r in growth if r]
if not growth:
return
figure, axis = plt.subplots(figsize=(7.5, 4.8))
cpus = [r["cpu_api_limit"] / 100 for r in growth]
unit = growth[0]["peak_ok_rps"] / cpus[0]
axis.plot(cpus, [unit * c for c in cpus], color=MUTED, linestyle="--", linewidth=1)
axis.annotate("линейный рост", (cpus[-1], unit * cpus[-1]), color=MUTED, fontsize=9)
axis.errorbar(
cpus,
[r["peak_ok_rps"] for r in growth],
yerr=[
[r["peak_ok_rps"] - r["peak_ok_min"] for r in growth],
[r["peak_ok_max"] - r["peak_ok_rps"] for r in growth],
],
color=PALETTE[0],
marker="o",
capsize=3,
label="серия B: N × 1 CPU",
)
for r, c in zip(growth, cpus, strict=True):
direct_label(axis, c, r["peak_ok_rps"], r["config"])
for config in ("2x2", "1x4"):
r = by.get(("series-a", config))
if r:
look = style(config)
axis.plot(4, r["peak_ok_rps"], linestyle="none", label=f"серия A: {config}", **look)
axis.set_xlabel("Суммарный CPU реплик API")
axis.set_ylabel("Пик успешных RPS")
axis.set_title("Пропускная способность от ресурсов API")
axis.set_xticks(cpus)
axis.legend(loc="upper left", fontsize=9)
figure.tight_layout()
figure.savefig(out / "scaling.png", dpi=150)
plt.close(figure)
def utilisation(rows, out):
picked = [r for r in rows if r["variant"] == "base" and r["series"] != "compare"]
seen, ordered = set(), []
for config in ORDER:
for r in picked:
if r["config"] == config and config not in seen:
seen.add(config)
ordered.append(r)
if not ordered:
return
metrics = (
("CPU API, % лимита", lambda r: 100 * r["cpu_api"] / r["cpu_api_limit"]),
("CPU PostgreSQL, % лимита", lambda r: r["cpu_postgres"] / 2),
("CPU HAProxy, % лимита", lambda r: r["cpu_lb"]),
("ждут блокировку, % пула", lambda r: 100 * r["pg_lock_avg"] / r["pool_total"]),
)
figure, axis = plt.subplots(figsize=(10, 4.8))
width = 0.8 / len(metrics)
for index, (name, value) in enumerate(metrics):
xs = [i + (index - 1.5) * width for i in range(len(ordered))]
axis.bar(
xs,
[value(r) for r in ordered],
width=width - 0.02,
color=PALETTE[index],
label=name,
edgecolor=SURFACE,
)
axis.set_xticks(range(len(ordered)), [r["config"] for r in ordered])
axis.axhline(100, color=MUTED, linestyle=":", linewidth=1)
axis.set_ylabel("%")
axis.set_ylim(0, 115)
axis.set_title("Загрузка звеньев в точке пика успешных RPS", pad=34)
axis.legend(fontsize=9, ncols=4, loc="lower left", bbox_to_anchor=(0, 1.0))
figure.tight_layout()
figure.savefig(out / "utilisation.png", dpi=150)
plt.close(figure)
def write(rows, out):
with (out / "capacity.csv").open("w", newline="") as handle:
writer = csv.DictWriter(handle, fieldnames=SUMMARY, extrasaction="ignore")
writer.writeheader()
writer.writerows(rows)
head = (
"| серия | вариант | конфигурация | потолок по SLO, rps | p95 там, мс | пик успешных RPS "
"[min–max] | при нагрузке | CPU API / лимит | CPU PG | CPU LB | ждут блокировку / пул |"
)
lines_ = [head, "|" + " --- |" * 11]
for r in rows:
lines_.append(
f"| {r['series']} | {r['variant']} | {r['config']} | {r.get('capacity_rate', '—')} | "
f"{r.get('capacity_p95_ms', '—')} | {r['peak_ok_rps']:.0f} "
f"[{r['peak_ok_min']:.0f}–{r['peak_ok_max']:.0f}] | {r['peak_rate']} | "
f"{r['cpu_api']:.0f} / {r['cpu_api_limit']} | {r['cpu_postgres']:.0f} | "
f"{r['cpu_lb']:.0f} | {r['pg_lock_avg']:.1f} / {r['pool_total']} |"
)
(out / "capacity.md").write_text("\n".join(lines_) + "\n")
print("\n".join(lines_))
def main():
parser = argparse.ArgumentParser(description="Графики и сводка трека 1 из summary.csv")
parser.add_argument("summaries", nargs="+")
parser.add_argument("--out", required=True)
args = parser.parse_args()
out = Path(args.out)
out.mkdir(parents=True, exist_ok=True)
groups = load(args.summaries)
rank = {name: index for index, name in enumerate(ORDER)}
keys = sorted(groups, key=lambda k: (k[0], k[1] != "before", rank.get(k[2], 99)))
rows = [summarize(key, groups[key]) for key in keys]
for series in dict.fromkeys(k[0] for k in keys):
chosen = [k for k in keys if k[0] == series]
throughput(series, chosen, groups, out)
cpu(series, chosen, groups, out)
scaling(rows, out)
utilisation(rows, out)
write(rows, out)
if __name__ == "__main__":
main()