feat: add track 1 scaling series to the bench stand

Series a/b/pool/ab/quick in bench/run.py: per-cell fresh stand with the
configuration's replicas and max_connections, open-model mixed profile
(k6/mixed.js), fixed levels and R* search by SLO, a sampler container
for cgroup, VM, HAProxy and PostgreSQL metrics, resume and a stand
lock. Pure helpers in bench/scaling.py, SVG plots in bench/plots.py,
series mode for bench_compare and bench_ab. Hypotheses H1-H3 go to
REPORT.md before the first series.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-11 03:28:36 +03:00
co-authored by Claude Opus 5.5
parent 525ace7c9b
commit 02fd3d8a36
16 changed files with 4848 additions and 122 deletions
+273 -16
View File
@@ -18,6 +18,8 @@ from dataclasses import dataclass
from pathlib import Path
from typing import Any
import scaling
ROOT = Path(__file__).resolve().parents[1]
BENCH_DIR = ROOT / "evidence" / "bench"
OUT_DIR = ROOT / "evidence" / "compare"
@@ -103,19 +105,36 @@ def flatten(prefix: str, value: Any, into: dict[str, Any]) -> None:
into[prefix] = value
def methodology(label: Label) -> dict[str, Any]:
def is_series(label: Label) -> bool:
"""Метка серии трека 1 (design change `scaling-bench`, решение 11)."""
return bool(label.meta.get("profile", {}).get("series"))
def methodology(
label: Label,
configs: set[str] | None = None,
) -> dict[str, Any]:
"""Параметры, которые у сравнимых меток обязаны совпадать.
Профиль, лимиты всех контейнеров стенда, образ генератора, образы и
настройки PostgreSQL и Valkey, окружение приложения (решение 8 design
change `bench-postgres`). У Valkey настройки — `maxmemory*` из
`valkey.conf`: правку конфигурации образ не покажет.
`valkey.conf`: правку конфигурации образ не покажет. У серий трека 1
имя, серия и состав конфигураций к методике не относятся, лимиты — по
общим конфигурациям `configs` (решение 11 design change
`scaling-bench`).
"""
meta = label.meta
stand = meta.get("stand", {})
flat: dict[str, Any] = {}
flatten("profile", meta.get("profile", {}), flat)
flatten("limits", meta.get("limits", {}), flat)
profile = dict(meta.get("profile", {}))
limits = meta.get("limits", {})
if configs is not None:
for key in ("name", "series", "configs"):
profile.pop(key, None)
limits = {key: limits[key] for key in configs if key in limits}
flatten("profile", profile, flat)
flatten("limits", limits, flat)
for name, value in (
("generator.image", meta.get("generator", {}).get("image")),
("stand.postgres.image", stand.get("postgres", {}).get("image")),
@@ -135,9 +154,22 @@ def methodology(label: Label) -> dict[str, Any]:
return flat
def check_methodology(first: Label, second: Label) -> list[str]:
"""Отказ при различии; возвращает параметры, записанные в одной метке."""
a, b = methodology(first), methodology(second)
def check_methodology(
first: Label,
second: Label,
configs: set[str] | None = None,
) -> list[str]:
"""Отказ при различии; возвращает параметры, записанные в одной метке.
`configs` — общие конфигурации серий трека 1; None — матрица."""
if is_series(first) != is_series(second):
series = first if is_series(first) else second
raise CompareError(
"different methodology: track 1 series "
f"{series.name} and matrix "
f"{(second if series is first else first).name}",
)
a, b = methodology(first, configs), methodology(second, configs)
# с change graceful-failover в пути запроса стоит HAProxy, и паспорт
# пишет число реплик; метка без него снята мимо LB — другая методика
# (решение 6 design change graceful-failover), а не «параметр
@@ -145,7 +177,7 @@ def check_methodology(first: Label, second: Label) -> list[str]:
without_lb = [
label.name
for label, flat in ((first, a), (second, b))
if "limits.api_replicas" not in flat
if configs is None and "limits.api_replicas" not in flat
]
if len(without_lb) == 1:
raise CompareError(
@@ -261,8 +293,18 @@ def passport_rows(labels: list[Label]) -> list[str]:
)
def host(meta: dict[str, Any]) -> str:
start = meta.get("host_state", {}).get("start", {})
return f"swap {start.get('swap_used_mib')} МиБ, {start.get('power')}"
# занятый swap — не помеха; помеха — выгрузка за прогон (решение 12
# design change scaling-bench)
state = meta.get("host_state", {})
start = state.get("start", {})
before = start.get("swapouts")
after = state.get("end", {}).get("swapouts")
swapped = (
f"выгрузок в swap за прогон {after - before}"
if before is not None and after is not None
else f"swap {start.get('swap_used_mib')} МиБ"
)
return f"{swapped}, {start.get('power')}"
def versions(meta: dict[str, Any]) -> str:
found = meta.get("app_image", {}).get("versions", {})
@@ -431,6 +473,218 @@ def render(
return "\n".join(lines) + "\n"
@dataclass(frozen=True)
class SeriesRow:
"""Общая конфигурация двух меток серий: R* повторов и числа сводки."""
config: str
before: dict[str, Any]
after: dict[str, Any]
@property
def delta(self) -> float:
return (self.after["r_star"] / self.before["r_star"] - 1) * 100
@property
def overlap(self) -> bool:
a, b = self.before["r_stars"], self.after["r_stars"]
return min(a) <= max(b) and min(b) <= max(a)
def series_stats(label: Label) -> dict[str, dict[str, Any]]:
"""Сводка конфигураций серии (`scaling.config_stats`) с R* полных
ячеек; ячейки с браком генератора в сравнение не входят."""
directory = BENCH_DIR / label.name
searches = scaling.read_csv(directory / "searches.csv")
return {
c["config"]: c
for c in scaling.config_stats(label.meta, label.runs, searches)
}
def series_notes(label: Label, stats: dict[str, dict[str, Any]]) -> list[str]:
"""Что мешает считать метку серии чистым замером: прочее — как у
матрицы, но нарушения SLO на ступенях поиска — норма, а не пометка."""
meta = label.meta
found = []
if meta.get("status") != "complete":
found.append(f"статус {meta.get('status')}: {meta.get('reason')}")
if meta.get("git", {}).get("dirty"):
found.append("незакоммиченные изменения (`dirty: true`)")
if meta.get("overrides"):
found.append(f"отладочные переопределения {meta['overrides']}")
found += [f"хост: {text}" for text in meta.get("host_warnings", [])]
bound = [cell for c in stats.values() for cell in c["generator_bound"]]
if bound:
found.append(
"брак генератора, ячейки не сравниваются: " + ", ".join(bound),
)
marked = sorted(
{
run["cell"]
for run in label.runs
if {"oom", "app_down", "stand_down", "host_swap"}
& set((run.get("flags") or "").split())
},
)
if marked:
found.append(
"ячейки с отказом стенда или выгрузкой: " + ", ".join(marked),
)
return [f"`{label.name}`: {text}" for text in found]
def series_noise(aa: Label, before: Label) -> tuple[float, str]:
"""Шум A/A серий: наибольшее по общим конфигурациям |Δ медианы R*|."""
first, second = series_stats(aa), series_stats(before)
common = [
SeriesRow(config=key, before=first[key], after=second[key])
for key in first
if key in second
and first[key]["r_stars"]
and second[key]["r_stars"]
and first[key]["r_star"]
]
if not common:
raise CompareError(
f"labels {aa.name} and {before.name} have no common configs",
)
worst = max(common, key=lambda row: abs(row.delta))
return abs(worst.delta), worst.config
def render_series(
before: Label,
after: Label,
aa: Label | None,
command: str,
) -> str:
"""Сравнение меток серий трека 1 по общим конфигурациям (решение 11
design change `scaling-bench`)."""
first, second = series_stats(before), series_stats(after)
common = [key for key in first if key in second]
if not common:
raise CompareError("labels have no common track 1 configs")
unverified = check_methodology(before, after, set(common))
labels = [before, after]
floor = None
if aa is not None:
aa_stats = series_stats(aa)
unverified += check_methodology(
aa,
before,
{key for key in aa_stats if key in first},
)
floor = series_noise(aa, before)
labels.append(aa)
remarks = list(unverified)
remarks += series_notes(before, first) + series_notes(after, second)
if aa is not None:
remarks += series_notes(aa, series_stats(aa))
remarks += [
f"конфигурация {key} есть только в `{label.name}`: не сравнивается"
for key, label in [
*((k, before) for k in first if k not in second),
*((k, after) for k in second if k not in first),
]
]
rows = [
SeriesRow(config=key, before=first[key], after=second[key])
for key in common
if first[key]["r_stars"]
and second[key]["r_stars"]
and first[key]["r_star"]
]
lines = [
f"# Сравнение серий: `{before.name}` → `{after.name}`",
"",
f"- Команда: `{command}`",
"- Метки серий трека 1 сравниваются по общим конфигурациям. R* — "
"медиана повторов, в скобках min–max; Δ R* — отношение медиан "
"минус единица. Ячейки с браком генератора не входят.",
"- Задержки — медианы по повторам на фиксированных уровнях, «до → "
"после»; CPU на запрос — CPU реплик на успешный запрос на втором "
"фиксированном уровне; CPU PostgreSQL — на ступени R*.",
]
if floor is None:
lines.append(
"- Уровень шума не задан (`AA`): вывод говорит только, "
"пересекаются ли разбросы повторов.",
)
else:
lines += [
f"- Уровень шума — наибольшее по общим конфигурациям изменение "
f"медианы R* между `{aa.name if aa else ''}` и `{before.name}`: "
f"{floor[0]:.1f}% ({floor[1]}). Он имеет смысл, только если код "
"приложения в этих метках одинаков; это проверяется по git.",
"- «Эффект» — разбросы повторов не пересекаются и изменение "
"медианы больше уровня шума; иначе «в пределах шума».",
]
lines += [
"",
"## Метки",
"",
*passport_rows(labels),
"",
"## Замечания",
"",
]
lines += [f"- {text}" for text in dict.fromkeys(remarks)] or ["Нет."]
fixed = before.meta["profile"].get("fixed_rps") or []
second_level = (
fixed[1] if len(fixed) > 1 else (fixed[0] if fixed else None)
)
lines += [
"",
"## R* по общим конфигурациям",
"",
"| Конфигурация | R* до | R* после | Δ R* | Вывод | "
+ " | ".join(f"p95 / p99 на {lvl}, мс" for lvl in fixed)
+ f" | CPU на запрос на {second_level}, мкс | CPU PostgreSQL на R*, "
"ядер |",
"|---|---|---|---|---|" + "---|" * len(fixed) + "---|---|",
]
for row in rows:
a, b = row.before, row.after
if floor is None:
verdict = (
"разбросы пересекаются"
if row.overlap
else "разбросы не пересекаются"
)
elif not row.overlap and abs(row.delta) > floor[0]:
verdict = "эффект"
else:
verdict = "в пределах шума"
latency = []
for lvl in fixed:
fa, fb = a["fixed"].get(lvl) or {}, b["fixed"].get(lvl) or {}
latency.append(
f"{scaling.fmt(fa.get('p95'), 1)} → "
f"{scaling.fmt(fb.get('p95'), 1)} / "
f"{scaling.fmt(fa.get('p99'), 1)} → "
f"{scaling.fmt(fb.get('p99'), 1)}",
)
us_a = (a["fixed"].get(second_level) or {}).get("app_us")
us_b = (b["fixed"].get(second_level) or {}).get("app_us")
lines.append(
f"| {row.config} | {scaling.spread(a['r_stars'])} | "
f"{scaling.spread(b['r_stars'])} | {row.delta:+.1f}% | "
f"{verdict} | "
+ " | ".join(latency)
+ f" | {scaling.fmt(us_a, 0)} → {scaling.fmt(us_b, 0)} | "
f"{scaling.fmt(a['db_cpu_r'], 2)} → {scaling.fmt(b['db_cpu_r'], 2)} |",
)
if rows:
deltas = [row.delta for row in rows]
lines += [
"",
f"Δ R* по конфигурациям: от {min(deltas):+.1f}% до "
f"{max(deltas):+.1f}%.",
]
return "\n".join(lines) + "\n"
def main(argv: list[str]) -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--before", default="")
@@ -448,12 +702,15 @@ def main(argv: list[str]) -> int:
if args.aa:
command += f" AA={args.aa}"
try:
text = render(
load(args.before),
load(args.after),
load(args.aa) if args.aa else None,
command,
)
before, after = load(args.before), load(args.after)
aa = load(args.aa) if args.aa else None
if any(is_series(x) for x in (before, after, aa) if x is not None):
for other in (after, aa):
if other is not None:
check_methodology(before, other, set())
text = render_series(before, after, aa, command)
else:
text = render(before, after, aa, command)
except CompareError as exc:
print(f"compare failed: {exc}", flush=True)
return 1