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
+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*."""