feat: draw series db in R* plot and summarize PostgreSQL saturation

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-11 12:22:32 +03:00
co-authored by Claude Opus 5.5
parent 48d10dad37
commit 9fbe2ea503
+135 -9
View File
@@ -655,27 +655,32 @@ def plot_cpu(labels: list[dict[str, Any]], title: str) -> str:
def plot_rstar(labels: list[dict[str, Any]], title: str) -> str:
growth = next((x for x in labels if x["series"] == "b"), None)
budget = next((x for x in labels if x["series"] == "a"), None)
db = next((x for x in labels if x["series"] == "db"), None)
width, height = 860, 520
left, right, top, bottom = 76, 24, 96, 64
svg = Svg(width, height, title)
svg.text(
24,
52,
"Медиана R* по повторам, усы — min–max; пунктир — линейный рост "
"k × R*(1 × 1) серии b",
"Медиана R* по повторам, усы — min–max"
+ (
"; пунктир — линейный рост k × R*(1 × 1) серии b" if growth else ""
),
color=INK_2,
)
sat = scaling.saturation(growth["stats"]) if growth else None
by_k = sat["by_k"] if sat else {}
base = by_k[1]["r_star"] if 1 in by_k else None
values = [max(c["r_stars"] or [0]) for c in by_k.values()]
if budget:
values += [max(c["r_stars"] or [0]) for c in budget["stats"]]
for extra in (budget, db):
if extra:
values += [max(c["r_stars"] or [0]) for c in extra["stats"]]
max_k = max(
[
*by_k.keys(),
4,
*(c["replicas"] for c in (budget or {}).get("stats", [])),
*(c["replicas"] for c in (db or {}).get("stats", [])),
],
)
if base:
@@ -819,6 +824,53 @@ def plot_rstar(labels: list[dict[str, Any]], title: str) -> str:
color=INK_2,
)
legend.append((color, "серия a: бюджет 4 CPU", "dot"))
if db:
# серия db: линия по k на каждый лимит CPU PostgreSQL
groups: dict[str, list[dict[str, Any]]] = {}
for c in db["stats"]:
if c["r_star"] is not None:
groups.setdefault(c.get("db_cpus") or "", []).append(c)
for index, (limit, items) in enumerate(
sorted(groups.items(), key=lambda kv: float(kv[0] or 0)),
):
color = SERIES[2 + index]
items.sort(key=lambda c: c["replicas"])
for c in items:
k = c["replicas"]
svg.line(
sx(k),
sy(min(c["r_stars"])),
sx(k),
sy(max(c["r_stars"])),
color=color,
width=1.5,
)
if len(items) > 1:
svg.polyline(
[(sx(c["replicas"]), sy(c["r_star"])) for c in items],
color,
)
for c in items:
svg.dot(
sx(c["replicas"]),
sy(c["r_star"]),
color,
f"серия db, {c['config']}: R* "
f"{scaling.spread(c['r_stars'])} запросов/с",
)
svg.text(
sx(c["replicas"]) + 8,
sy(c["r_star"]) - 8,
f"{c['r_star']:.0f}",
color=INK,
)
legend.append(
(
color,
f"серия db: PostgreSQL {limit} CPU",
"line" if len(items) > 1 else "dot",
),
)
svg.legend(legend, left, 76, plot_w)
return svg.render()
@@ -847,11 +899,19 @@ def render_combined_summary(labels: list[dict[str, Any]], command: str) -> str:
for x in labels
),
*passport_lines(labels),
"- R* — медиана (min–max) по повторам; эффективность — R* / (k × "
"R*(1 × 1)), опора — 1 × 1 серии `b`; предельный CPU на запрос — "
"наклон CPU реплик от успешных запросов/с по ступеням, прошедшим "
"SLO; host_cost — он же против 1 × 1 серии `b` (порог "
f"{scaling.THRESHOLDS['host_cost']})",
(
"- R* — медиана (min–max) по повторам; эффективность — R* / "
"(k × R*(1 × 1)), опора — 1 × 1 серии `b`; предельный CPU на "
"запрос — наклон CPU реплик от успешных запросов/с по ступеням, "
"прошедшим SLO; host_cost — он же против 1 × 1 серии `b` (порог "
f"{scaling.THRESHOLDS['host_cost']})"
if base
else "- R* — медиана (min–max) по повторам; предельный CPU на "
"запрос — наклон CPU реплик от успешных запросов/с по ступеням, "
"прошедшим SLO; host_cost — он же против 1 × 1 своей метки "
f"(порог {scaling.THRESHOLDS['host_cost']}); эффективность — "
"только вместе с серией `b`"
),
"",
"## R* по конфигурациям",
"",
@@ -948,10 +1008,76 @@ def render_combined_summary(labels: list[dict[str, Any]], command: str) -> str:
"",
*cost_lines(growth, sat["by_k"]),
]
db = next((x for x in labels if x["series"] == "db"), None)
if db:
lines += db_lines(db)
lines += memory_lines(labels)
return "\n".join(lines)
def db_lines(label: dict[str, Any]) -> list[str]:
"""Серия db: PostgreSQL на ступени R* и на первой нарушившей —
медианы по повторам (насыщение БД управляемым опытом)."""
lines = [
"## Насыщение PostgreSQL (серия `db`)",
"",
"Медианы по повторам. Доля лимита — CPU PostgreSQL / его лимит; "
"троттлинг — доля периодов CFS контейнера PostgreSQL; CPU "
"PostgreSQL на запрос — `db_us_per_request`; доля WAL — от всех "
"активных соединений; признак `db_cpu` — CPU ≥ "
f"{scaling.THRESHOLDS['db_cpu_share'] * 100:.0f} % лимита или "
f"троттлинг ≥ {scaling.THRESHOLDS['throttled_ratio'] * 100:.0f} %.",
"",
"| Конфигурация | Лимит CPU PostgreSQL | Ступень | Уровень, "
"запросов/с | CPU PostgreSQL, ядер | Доля лимита | Троттлинг "
"PostgreSQL | CPU PostgreSQL на запрос, мкс | Ожидания WAL, доля "
"активных | Соединений | p95, мс | Признаки |",
"|---|---|---|---|---|---|---|---|---|---|---|---|",
]
for c in label["stats"]:
limit = scaling.num(c.get("db_cpus"))
steps = {"R*": [], "первая нарушившая": []}
for search in label["searches"]:
if (
search["config"] != c["config"]
or search["status"] != "complete"
):
continue
chosen = label["chosen"].get(search["cell"], [])
r_star = scaling.num(search["r_star_rps"]) or 0
for name, row in (
("R*", scaling.step_at(chosen, r_star)),
("первая нарушившая", scaling.fail_step(chosen, r_star)),
):
if row is not None:
steps[name].append(row)
for name, rows in steps.items():
if not rows:
continue
def med(column: str, rows: list[dict[str, str]] = rows) -> Any:
return scaling.median(scaling.num(r.get(column)) for r in rows)
cpu = med("db_cpu_cores")
share = cpu / limit if cpu is not None and limit else None
wal = scaling.median(wal_share(r) for r in rows)
signs = scaling.majority(
[(r.get("signs") or "").split() for r in rows],
)
lines.append(
f"| {c['config']} | {c.get('db_cpus') or '—'} | {name} | "
f"{scaling.spread([scaling.num(r.get('level')) for r in rows])}"
f" | {scaling.fmt(cpu, 2)} | {scaling.fmt(share, 2)} | "
f"{scaling.fmt(med('db_throttled_ratio'), 3)} | "
f"{scaling.fmt(med('db_us_per_request'), 0)} | "
f"{scaling.fmt(None if wal is None else wal * 100, 0)} % | "
f"{scaling.fmt(med('db_conn_max'), 0)} | "
f"{scaling.fmt(med('p95_ms'), 1)} | "
f"{' '.join(signs) or '—'} |",
)
return [*lines, ""]
def passport_lines(labels: list[dict[str, Any]]) -> list[str]:
"""Шапка evidence: спек, change, даты меток и хост из паспортов."""
hosts = []