feat: add cost and memory tables, passports and sampler limits to track 1 outputs

plots.py summary gains per-request CPU by component, PostgreSQL waits and
pool, H1b throttling and memory peaks; compare.py and plots.py headers
name the spec, change and host; errors logs match 5xx by status field and
keep the exception tail; series labels record sampler limits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-11 07:26:36 +03:00
co-authored by Claude Opus 5.5
parent 68edc66742
commit dcea85942a
4 changed files with 332 additions and 20 deletions
+17
View File
@@ -310,6 +310,20 @@ def passport_rows(labels: list[Label]) -> list[str]:
found = meta.get("app_image", {}).get("versions", {})
return ", ".join(f"{name} {ver}" for name, ver in found.items())
def machine(meta: dict[str, Any]) -> str:
found, docker = meta.get("host", {}), meta.get("docker", {})
cores = (
f" ({found['performance_cores']} P + "
f"{found['efficiency_cores']} E)"
if found.get("performance_cores") is not None
else ""
)
return (
f"{found.get('machine')}{cores}, ВМ {docker.get('vm_cpus')} vCPU "
f"/ {docker.get('vm_memory_gib')} GiB, Docker "
f"{docker.get('server')}"
)
return [
"| | " + " | ".join(f"`{x.name}`" for x in labels) + " |",
"|---|" + "---|" * len(labels),
@@ -317,6 +331,7 @@ def passport_rows(labels: list[Label]) -> list[str]:
field("Начало прогона", lambda m: str(m.get("started_at"))),
field("Статус", lambda m: str(m.get("status"))),
field("Версии в образе", versions),
field("Машина", machine),
field("Хост в начале", host),
]
@@ -599,6 +614,8 @@ def render_series(
f"# Сравнение серий: `{before.name}` → `{after.name}`",
"",
f"- Команда: `{command}`",
"- Спек: `load-benchmark` (сравнение меток), change `scaling-bench`; "
"даты, commit и хост — таблица «Метки»",
"- Метки серий трека 1 сравниваются по общим конфигурациям. R* — "
"медиана повторов, в скобках min–max; Δ R* — отношение медиан "
"минус единица. Ячейки с браком генератора не входят.",
+271 -5
View File
@@ -53,6 +53,8 @@ COMPONENTS = (
("generator_cpu_cores", "k6"),
("vm_rest", "остальное в ВМ"),
)
# классы ожидания активных соединений PostgreSQL (`db_aas_*`, решение 8)
AAS = ("cpu", "wal", "lock", "lwlock", "io", "other")
class Svg:
@@ -296,11 +298,8 @@ def p95_points(
return medians(line), medians(split)
def component_values(
label: dict[str, Any],
config: str,
) -> dict[str, float | None]:
"""CPU по компонентам на ступени R*: медиана по ячейкам."""
def r_star_rows(label: dict[str, Any], config: str) -> list[dict[str, str]]:
"""Строки `runs.csv` на ступени R* завершённых ячеек конфигурации."""
rows = []
for search in label["searches"]:
if search["config"] != config or search["status"] != "complete":
@@ -311,6 +310,91 @@ def component_values(
)
if row is not None:
rows.append(row)
return rows
def config_rows(label: dict[str, Any], config: str) -> list[dict[str, str]]:
"""Все ступени выбранных попыток ячеек конфигурации."""
return [
row
for search in label["searches"]
if search["config"] == config
for row in label["chosen"].get(search["cell"], [])
]
def per_request(row: dict[str, str], cores: str) -> float | None:
"""CPU компонента на успешный запрос ступени, мкс."""
return scaling.per_request(
scaling.num(row.get(cores)),
scaling.num(row.get("rps")),
)
def wal_share(row: dict[str, str]) -> float | None:
"""Доля ожиданий WAL среди активных соединений PostgreSQL."""
active = sum(scaling.num(row.get(f"db_aas_{name}")) or 0 for name in AAS)
wal = scaling.num(row.get("db_aas_wal"))
return wal / active if active and wal is not None else None
def at_r_star(label: dict[str, Any], config: str) -> dict[str, float | None]:
"""Цена запроса и занятость ресурсов на ступени R*: медианы по
ячейкам (числа таблицы точки насыщения в `REPORT.md`)."""
rows = r_star_rows(label, config)
replicas = int(config.split("x", 1)[0])
def med(value: Any) -> float | None:
return scaling.median(value(row) for row in rows)
def col(name: str) -> Any:
return lambda row: scaling.num(row.get(name))
return {
"app_cores_replica": med(
lambda row: (
(scaling.num(row.get("app_cpu_cores")) or 0) / replicas
),
),
"app_us": med(col("app_us_per_request")),
"db_us": med(col("db_us_per_request")),
"lb_us": med(lambda row: per_request(row, "lb_cpu_cores")),
"k6_us": med(lambda row: per_request(row, "generator_cpu_cores")),
"vm_busy": med(col("vm_busy_cores")),
"vm_psi": med(col("vm_cpu_pressure")),
"db_cores": med(col("db_cpu_cores")),
"db_conn": med(col("db_conn_max")),
"db_conn_replica": med(col("db_conn_replica_max")),
"wal_share": med(wal_share),
"aas_other": med(col("db_aas_other")),
"sessions_new": med(col("db_sessions_new")),
"pool_busy": med(col("pool_busy_share")),
"lb_cores": med(col("lb_cpu_cores")),
}
def peaks(label: dict[str, Any], config: str) -> dict[str, float | None]:
"""Пики памяти за серию по всем ступеням конфигурации, МиБ."""
rows = config_rows(label, config)
def top(name: str) -> float | None:
values = [scaling.num(row.get(name)) for row in rows]
return max((v for v in values if v is not None), default=None)
return {
"rss": top("rss_max_mib"),
"app": top("app_mem_peak_mib"),
"db": top("db_mem_peak_mib"),
"k6": top("generator_mem_peak_mib"),
}
def component_values(
label: dict[str, Any],
config: str,
) -> dict[str, float | None]:
"""CPU по компонентам на ступени R*: медиана по ячейкам."""
rows = r_star_rows(label, config)
values: dict[str, float | None] = {}
for key, _ in COMPONENTS[:-1]:
values[key] = scaling.median(scaling.num(r.get(key)) for r in rows)
@@ -762,6 +846,7 @@ def render_combined_summary(labels: list[dict[str, Any]], command: str) -> str:
f"`{x['meta']['git']['commit']}`, {x['meta']['status']})"
for x in labels
),
*passport_lines(labels),
"- R* — медиана (min–max) по повторам; эффективность — R* / (k × "
"R*(1 × 1)), опора — 1 × 1 серии `b`; предельный CPU на запрос — "
"наклон CPU реплик от успешных запросов/с по ступеням, прошедшим "
@@ -816,6 +901,9 @@ def render_combined_summary(labels: list[dict[str, Any]], command: str) -> str:
f"{one['replica_cpus']} за серию: "
f"{scaling.fmt(one['app_cpu_second_max'], 2)} ядра.",
"",
*throttling_lines(
[(growth, base), (budget, one)] if growth else [],
),
]
if sat:
lines += [
@@ -858,10 +946,188 @@ def render_combined_summary(labels: list[dict[str, Any]], command: str) -> str:
"меньше 10 %"
),
"",
*cost_lines(growth, sat["by_k"]),
]
lines += memory_lines(labels)
return "\n".join(lines)
def passport_lines(labels: list[dict[str, Any]]) -> list[str]:
"""Шапка evidence: спек, change, даты меток и хост из паспортов."""
hosts = []
for x in labels:
host, docker = x["meta"].get("host", {}), x["meta"].get("docker", {})
text = (
f"{host.get('machine')} ({host.get('performance_cores')} P + "
f"{host.get('efficiency_cores')} E ядер, "
f"{host.get('memory_gib')} ГиБ), {host.get('os')}; ВМ Docker "
f"{docker.get('vm_cpus')} vCPU / {docker.get('vm_memory_gib')} "
f"GiB, Docker {docker.get('server')}"
)
if text not in hosts:
hosts.append(text)
return [
"- Спек: `load-benchmark`, change `scaling-bench`",
"- Даты меток (UTC): "
+ ", ".join(
f"`{x['name']}` {x['meta'].get('started_at')} — "
f"{x['meta'].get('finished_at')}"
for x in labels
),
"- Хост (паспорт `meta.json`): " + "; ".join(hosts),
]
def percent(values: list[float | None]) -> str:
"""Доли в процентах: медиана (min–max)."""
return scaling.spread(
[None if v is None else v * 100 for v in values],
1,
)
def throttling_lines(
pairs: list[tuple[dict[str, Any] | None, dict[str, Any]]],
) -> list[str]:
"""H1б: троттлинг CFS и p99 одной реплики 1 × 1 и 1 × 4 на 500/с, на
R* и на нарушивших ступенях."""
lines = [
"Троттлинг CFS одной реплики (H1б; доля периодов, медиана (min–max) "
"по повторам; нарушившие — наибольшее по ступеням выше R*):",
"",
"| Конфигурация | Троттлинг на 500/с, % | p99 на 500/с, мс | "
"Троттлинг на R*, % | p99 на R*, мс | Троттлинг на нарушивших, "
"max % |",
"|---|---|---|---|---|---|",
]
for label, c in pairs:
if label is None:
continue
f500 = c["fixed"].get(500) or {}
rows = r_star_rows(label, c["config"])
failed = [
scaling.num(row.get("app_throttled_ratio"))
for row in config_rows(label, c["config"])
if row.get("slo_pass") == "False"
]
top = max((v for v in failed if v is not None), default=None)
at_r = [scaling.num(r.get("app_throttled_ratio")) for r in rows]
p99_r = [scaling.num(r.get("p99_ms")) for r in rows]
lines.append(
f"| {label['series']} {c['config']} | "
f"{percent(f500.get('throttled_all') or [])} | "
f"{scaling.spread(f500.get('p99_all') or [], 1)} | "
f"{percent(at_r)} | {scaling.spread(p99_r, 1)} | "
f"{scaling.fmt(None if top is None else top * 100, 1)} |",
)
return [*lines, ""]
def cost_lines(
label: dict[str, Any] | None,
by_k: dict[int, dict[str, Any]],
) -> list[str]:
"""Цена успешного запроса в CPU по компонентам и занятость общих
ресурсов на ступени R* серии роста; рост — к k = 1."""
if label is None or not by_k:
return []
values = {k: at_r_star(label, c["config"]) for k, c in by_k.items()}
base = values.get(1, {})
keys = ("app_us", "db_us", "lb_us", "k6_us")
def growth(v: dict[str, float | None], key: str) -> str:
own, ref = v.get(key), base.get(key)
return f"×{own / ref:.2f}" if own and ref else "—"
lines = [
"## Цена запроса и общие ресурсы на R* (серия `b`)",
"",
"Медианы по повторам на ступени R*. CPU на успешный запрос — CPU "
"компонента × 10⁶ / успешные в секунду (у HAProxy и k6 — по "
"`lb_cpu_cores` и `generator_cpu_cores`); рост — к k = 1. PSI — доля "
"времени, когда задачи ВМ ждали CPU.",
"",
"| k | CPU реплики, ядер на реплику | CPU на запрос, мкс: реплики / "
"PostgreSQL / HAProxy / k6 | Рост к k = 1 | Занято ядер ВМ | PSI CPU "
"ВМ, % | CPU PostgreSQL, ядер | CPU HAProxy, ядер |",
"|---|---|---|---|---|---|---|---|",
]
for k, v in sorted(values.items()):
psi = v["vm_psi"]
lines.append(
f"| {k} | {scaling.fmt(v['app_cores_replica'], 2)} | "
+ " / ".join(scaling.fmt(v[key], 0) for key in keys)
+ " | "
+ " / ".join(growth(v, key) for key in keys)
+ f" | {scaling.fmt(v['vm_busy'], 1)} | "
f"{scaling.fmt(None if psi is None else psi * 100, 1)} | "
f"{scaling.fmt(v['db_cores'], 2)} | "
f"{scaling.fmt(v['lb_cores'], 2)} |",
)
lines += [
"",
"PostgreSQL и пул на R* (`db_aas_*` — среднее число активных "
"соединений по классу ожидания; доля WAL — от всех активных, "
"порог признака `db_wal` — "
f"{scaling.THRESHOLDS['wait_share'] * 100:.0f} % при среднем не "
f"меньше {scaling.THRESHOLDS['db_active_min']:.0f} активного; "
"`pool_busy_share` — доля отсчётов, когда у реплики не было "
"свободного соединения):",
"",
"| k | Соединений, всего | Соединений реплики, max | Ожидания "
"WAL, доля активных | Прочие ожидания, соединений | Новых сессий за "
"окно | pool_busy_share |",
"|---|---|---|---|---|---|---|",
]
for k, v in sorted(values.items()):
share = v["wal_share"]
lines.append(
f"| {k} | {scaling.fmt(v['db_conn'], 0)} | "
f"{scaling.fmt(v['db_conn_replica'], 0)} | "
f"{scaling.fmt(None if share is None else share * 100, 0)} % | "
f"{scaling.fmt(v['aas_other'], 2)} | "
f"{scaling.fmt(v['sessions_new'], 0)} | "
f"{scaling.fmt(v['pool_busy'], 2)} |",
)
return [*lines, ""]
def memory_lines(labels: list[dict[str, Any]]) -> list[str]:
"""Пики памяти за серию: память нигде не была узким местом."""
lines = [
"## Память: пики за серию",
"",
"Наибольшее по всем ступеням конфигурации, МиБ. RSS — сумма RSS "
"процессов реплик (`rss_max_mib`) и она же на реплику; cgroup — "
"сумма пиков `memory.current` реплик (`app_mem_peak_mib`). Лимит "
"PostgreSQL и k6 — 1 ГиБ.",
"",
"| Серия | Конфигурация | Лимит реплики | RSS реплик, сумма | RSS "
"на реплику | cgroup реплик, сумма | PostgreSQL | k6 |",
"|---|---|---|---|---|---|---|---|",
]
for label in labels:
for c in label["stats"]:
p = peaks(label, c["config"])
k = c["replicas"]
limit = next(
(
s["replica_memory"]
for s in label["searches"]
if s["config"] == c["config"]
),
"",
)
lines.append(
f"| {label['series']} | {c['config']} | {limit or '—'} | "
f"{scaling.fmt(p['rss'], 0)} | "
f"{scaling.fmt(None if p['rss'] is None else p['rss'] / k)} | "
f"{scaling.fmt(p['app'], 0)} | "
f"{scaling.fmt(p['db'], 0)} | {scaling.fmt(p['k6'], 0)} |",
)
return [*lines, ""]
def render_series(label_dir: Path) -> None:
"""Графики серии в каталоге метки: p95 от интенсивности и CPU по
компонентам на R*."""
+42 -14
View File
@@ -65,6 +65,16 @@ SAMPLER = "mtusi-bench-sampler"
SAMPLER_SCRIPT = ROOT / "bench" / "sampler.sh"
# один прогон стенда любого профиля: flock держится до выхода процесса
LOCK_FILE = ROOT / "bench" / ".bench.lock"
# строки журналов окна с 5xx и отказами (`raw/<ступень>-errors.log`):
# PostgreSQL — отказ и FATAL; API — ответ 5xx или запись error; HAProxy —
# поле статуса 5xx или ответ без сервера. Подстроки «53300» и « 5»
# ловили метки времени и request_id (verify S4)
ERRORS_PG_RE = re.compile(r"too many clients|FATAL")
ERRORS_API_RE = re.compile(r'"status": 5\d\d\b|"level": "error"')
ERRORS_LB_RE = re.compile(r"\s5\d\d\s|<NOSRV>")
# длинная строка журнала: начало и конец (класс исключения — в конце)
ERRORS_HEAD = 300
ERRORS_TAIL = 300
# второе хранилище этапа восстановления: контейнер, volume и имя в сети
# стенда (по нему API переключается на восстановленную базу)
RESTORE_DB = "mtusi-bench-postgres-restore"
@@ -2235,6 +2245,13 @@ class Measured:
return self.cores("db_usec")
def shorten(line: str) -> str:
"""Строка журнала в файл ошибок: длинная — начало, «…» и конец."""
if len(line) <= ERRORS_HEAD + ERRORS_TAIL:
return line
return f"{line[:ERRORS_HEAD]} … {line[-ERRORS_TAIL:]}"
def k6_failure(script: str, proc: subprocess.CompletedProcess[str]) -> str:
tail = (proc.stdout + proc.stderr)[-3000:]
return f"k6 {script} failed ({proc.returncode}):\n{tail}"
@@ -3879,12 +3896,18 @@ class Bench:
# max_connections — в лимитах конфигурации, не в паспорте
known = self.results.meta.setdefault("limits", {})
config = self.cell["config"]
if config in known and known[config] != limits:
# лимиты сэмплера добавляет run_cell после его запуска
earlier = known.get(config, {})
sampler = earlier.get("sampler")
stand_only = {k: v for k, v in earlier.items() if k != "sampler"}
if config in known and stand_only != limits:
raise BenchError(
f"{config}: limits differ from the earlier repeat: "
f"{limits}",
)
known[config] = limits
known[config] = (
limits if sampler is None else {**limits, "sampler": sampler}
)
if "stand" not in self.results.meta:
passport = stand.passport()
passport["postgres"]["settings"].pop("max_connections", None)
@@ -4545,6 +4568,15 @@ class Bench:
size = p.sizes[0]
stand.start_sampler()
self.say(f"{tag}: sampler started")
# лимиты сэмплера — тоже у запущенного контейнера, в лимитах
# конфигурации (спек «Лимиты конфигурации серии», verify S11)
sampler = stand.container_limits(SAMPLER)
known = self.results.meta["limits"][cell["config"]]
if known.setdefault("sampler", sampler) != sampler:
raise BenchError(
f"{cell['config']}: sampler limits differ from the earlier "
f"repeat: {sampler}",
)
replicas = stand.replicas()
instances = [stand.full_id(name)[:12] for name in replicas]
addresses = {
@@ -4952,14 +4984,14 @@ class Bench:
) -> None:
"""Доказательства 5xx и отказов «too many clients» ступени (H3):
строки PostgreSQL, API и LB окна, без секретов — строки со словом
`password` отбрасываются, длина строки ограничена."""
`password` отбрасываются. Длинная строка (traceback) сокращается
до начала и конца: класс исключения — в конце (verify S4)."""
def pick(text: str, needles: tuple[str, ...], limit: int) -> list[str]:
def pick(text: str, pattern: re.Pattern[str], limit: int) -> list[str]:
lines = [
line[:600]
shorten(line)
for line in text.splitlines()
if any(n in line for n in needles)
and "password" not in line.lower()
if pattern.search(line) and "password" not in line.lower()
]
return lines[:limit]
@@ -4967,20 +4999,16 @@ class Bench:
f"# {name}: коды ошибок окна k6 — {codes or 'нет'}",
"",
"## PostgreSQL",
*pick(pg_log, (scaling.TOO_MANY_CLIENTS, "FATAL"), 10),
*pick(pg_log, ERRORS_PG_RE, 10),
"",
"## API",
]
for replica in self.stand.replicas():
out += pick(
self.window_log(replica, w0, w1),
('"status": 5', '"level": "error"', "53300", "too many"),
10,
)
out += pick(self.window_log(replica, w0, w1), ERRORS_API_RE, 10)
out += [
"",
"## HAProxy",
*pick(self.window_log(LB, w0, w1), (" 5", "<NOSRV>", "sD"), 10),
*pick(self.window_log(LB, w0, w1), ERRORS_LB_RE, 10),
]
path = self.results.dir / "raw" / f"{name}-errors.log"
path.write_text("\n".join(out) + "\n", encoding="utf-8")
+2 -1
View File
@@ -176,7 +176,8 @@ THRESHOLDS: dict[str, float] = {
# хост: занятые ядра ВМ — доля её CPU, PSI CPU — доля времени
"vm_busy_share": 0.9,
"vm_cpu_pressure": 0.20,
# CPU реплики на запрос на 500/с против 1 × 1 той же серии
# предельный CPU реплик на запрос (наклон по ступеням, прошедшим SLO)
# против 1 × 1 серии роста (marginal_us, найдено в apply)
"host_cost": 1.2,
# генератор: троттлинг и недосланные при CPU k6 не меньше доли лимита
"generator_throttled": 0.10,