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
+20 -3
View File
@@ -1,6 +1,8 @@
"""Два прогона подряд: «до» и «после» одного изменения, в одной сессии.
Запуск — `make bench_ab BEFORE=<метка> AFTER=<метка> REAPPLY=<commit>`.
Запуск — `make bench_ab BEFORE=<метка> AFTER=<метка> REAPPLY=<commit>
[SERIES=<серия>]`; с `SERIES` вместо полной матрицы снимается серия трека 1
(`make bench_scaling`).
В рабочем дереве должен лежать код «до», а изменение — быть
закоммиченным и откаченным отдельным commit; `REAPPLY` — commit отката.
Скрипт снимает стенд «до», коммитит его результаты, возвращает изменение
@@ -51,13 +53,26 @@ def problems(args: argparse.Namespace) -> list[str]:
return found
def run_step(args: argparse.Namespace, label: str) -> list[str]:
"""Прогон стенда: полная матрица или серия трека 1 (`--series`,
решение 11 design change `scaling-bench`)."""
if args.series:
return [
"make",
"bench_scaling",
f"SERIES={args.series}",
f"SCALING_LABEL={label}",
]
return ["make", "bench", f"BENCH_LABEL={label}"]
def steps(args: argparse.Namespace) -> list[list[str]]:
return [
["make", "bench", f"BENCH_LABEL={args.before}"],
run_step(args, args.before),
["git", "add", f"evidence/bench/{args.before}"],
["git", "commit", "-m", f"docs: add {args.before} bench evidence"],
["git", "revert", "--no-edit", args.reapply],
["make", "bench", f"BENCH_LABEL={args.after}"],
run_step(args, args.after),
]
@@ -67,6 +82,8 @@ def main(argv: list[str]) -> int:
parser.add_argument("--after", default="")
parser.add_argument("--reapply", default="")
parser.add_argument("--dry-run", action="store_true")
# серия трека 1 вместо полной матрицы: a, b, pool, ab, quick
parser.add_argument("--series", default="")
args = parser.parse_args(argv)
if not (args.before and args.after and args.reapply):
print(
+9 -2
View File
@@ -15,8 +15,15 @@ services:
# упавший контейнер не поднимается сам: прогон помечается stand_down
restart: "no"
# auto_explain загружен, но выключен (log_min_duration = -1): run.py
# включает его только на этапе плана, между прогонами
command: ["postgres", "-c", "shared_preload_libraries=auto_explain"]
# включает его только на этапе плана, между прогонами. max_connections
# — конфигурация серии трека 1 (граница пула), у прочих профилей 100,
# как у образа (решение 1 design change scaling-bench)
command:
- postgres
- -c
- shared_preload_libraries=auto_explain
- -c
- max_connections=${BENCH_DB_MAX_CONNECTIONS:?run make bench}
ports: !reset []
deploy:
resources:
+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
+217
View File
@@ -0,0 +1,217 @@
// Ступень серии трека 1 (решения 2–3 design change scaling-bench):
// открытая модель, три сценария ramping-arrival-rate с долями смеси —
// страница истории читаемого чата, отправка с новым Idempotency-Key в один
// из чатов записи, GET /users/me. Ступень — подъём от START до LEVEL за
// WARMUP_S (в замер не входит) и окно MEASURE_S с постоянной
// интенсивностью. Каждый запрос получает тег window (warm / hold) по
// времени отправки от начала сценария; итог содержит подметрики окна.
// Время setup (t0) — часы ВМ Docker: по нему run.py режет отсчёты
// сэмплера. Вход по Basic — в prepare.js, до ступеней.
import exec from "k6/execution";
import http from "k6/http";
import { check } from "k6";
import { SharedArray } from "k6/data";
import { Counter } from "k6/metrics";
import {
API,
PAGE_LIMIT,
SUMMARY_TREND_STATS,
WORK_DIR,
authHeaders,
messageHeaders,
mulberry32,
summaryFiles,
syntheticText,
} from "./lib.js";
const fixture = JSON.parse(open(`${WORK_DIR}/fixture.json`));
const cursors = new SharedArray(
"cursors",
() => JSON.parse(open(`${WORK_DIR}/cursors.json`)).cursors,
);
const LEVEL = Number(__ENV.LEVEL);
const START = Number(__ENV.START || 0);
// «read:0.7,write:0.2,me:0.1» — Profile.mix
const MIX = (__ENV.MIX || "read:0.7,write:0.2,me:0.1")
.split(",")
.map((item) => item.split(":"))
.map(([name, share]) => [name, Number(share)]);
const WARMUP_S = Number(__ENV.WARMUP_S);
const MEASURE_S = Number(__ENV.MEASURE_S);
const WARMUP_MS = WARMUP_S * 1000;
// больше timeout server LB (10 с): клиент видит ответ LB, а не свой таймаут
const TIMEOUT_S = Number(__ENV.TIMEOUT || 15);
const PRE_VUS_PER_RPS = Number(__ENV.PRE_VUS_PER_RPS || 0.05);
const MAX_VUS_PER_RPS = Number(__ENV.MAX_VUS_PER_RPS || 0.2);
const SEED = Number(__ENV.SEED || 0);
const STEP = Number(__ENV.STEP || 0);
// короткие ID реплик: подметрики распределения по X-Instance-Id
const INSTANCES = (__ENV.INSTANCES || "").split(",").filter((x) => x);
const ABORT_ERRORS = Number(__ENV.ABORT_ERRORS || 0.5);
const ABORT_P95_MS = Number(__ENV.ABORT_P95_MS || 2000);
// коды неуспешных ответов окна (bench/scaling.py, ERROR_STATUSES)
const ERROR_STATUSES = [0, 400, 401, 403, 404, 409, 422, 429, 500, 502, 503, 504];
const READ_URL = `${API}/chats/${fixture.readChatId}/messages`;
const READ_HEADERS = authHeaders(fixture.tokens[fixture.readerId]);
const USERS = [fixture.readerId, ...fixture.memberIds];
const WRITE_CHATS = fixture.writeChatIds || [fixture.writeChatId];
const shortPages = new Counter("short_pages");
const instanceOk = new Counter("instance_ok");
function scenario(name, share) {
const target = Math.round(LEVEL * share);
const start = Math.round(START * share);
return {
executor: "ramping-arrival-rate",
exec: name,
startRate: start,
timeUnit: "1s",
preAllocatedVUs: Math.ceil(target * PRE_VUS_PER_RPS) + 10,
maxVUs: Math.ceil(target * MAX_VUS_PER_RPS) + 20,
stages: [
{ target, duration: `${WARMUP_S}s` },
{ target, duration: `${MEASURE_S}s` },
],
// запрос, начатый в конце окна, успевает дождаться ответа или таймаута
gracefulStop: `${TIMEOUT_S + 1}s`,
};
}
const HOLD = "window:hold";
const thresholds = {
// досрочный выход по подметрикам окна (код k6 99): перегрузка не тянется
// до конца ступени
[`http_req_duration{${HOLD},expected_response:true}`]: [
"max>=0",
{
threshold: `p(95)<${ABORT_P95_MS}`,
abortOnFail: true,
delayAbortEval: `${WARMUP_S + 5}s`,
},
],
[`http_req_failed{${HOLD}}`]: [
"rate>=0",
{
threshold: `rate<=${ABORT_ERRORS}`,
abortOnFail: true,
delayAbortEval: `${WARMUP_S + 5}s`,
},
],
[`short_pages{${HOLD}}`]: ["count>=0"],
[`checks{${HOLD}}`]: ["rate>=0"],
};
// остальные пороги всегда выполняются: они нужны, чтобы подметрики попали
// в итог
for (const [name] of MIX) {
thresholds[`http_reqs{${HOLD},scenario:${name}}`] = ["count>=0"];
thresholds[`http_req_failed{${HOLD},scenario:${name}}`] = ["rate>=0"];
thresholds[
`http_req_duration{${HOLD},expected_response:true,scenario:${name}}`
] = ["max>=0"];
thresholds[`http_reqs{scenario:${name}}`] = ["count>=0"];
thresholds[`http_req_failed{scenario:${name}}`] = ["rate>=0"];
}
for (const id of [...INSTANCES, "-"]) {
thresholds[`instance_ok{${HOLD},instance:${id}}`] = ["count>=0"];
}
for (const status of ERROR_STATUSES) {
thresholds[`http_reqs{${HOLD},status:${status}}`] = ["count>=0"];
}
export const options = {
scenarios: Object.fromEntries(
MIX.map(([name, share]) => [name, scenario(name, share)]),
),
summaryTrendStats: SUMMARY_TREND_STATS,
thresholds,
};
export function setup() {
return { t0: Date.now() };
}
// тег окна по времени отправки от начала сценария
function windowTag() {
return Date.now() - exec.scenario.startTime < WARMUP_MS ? "warm" : "hold";
}
function counted(res, ok, window) {
if (ok) {
instanceOk.add(1, {
window,
instance: res.headers["X-Instance-Id"] || "-",
});
}
}
let random = null;
export function read() {
if (random === null) {
random = mulberry32(SEED + exec.vu.idInTest);
}
const window = windowTag();
const cursor = encodeURIComponent(
cursors[Math.floor(random() * cursors.length)],
);
const res = http.get(`${READ_URL}?limit=${PAGE_LIMIT}&cursor=${cursor}`, {
headers: READ_HEADERS,
timeout: `${TIMEOUT_S}s`,
tags: { window },
responseCallback: http.expectedStatuses(200),
});
const full = res.status === 200 && res.json("items.#") === PAGE_LIMIT;
if (res.status === 200 && !full) {
// неполная страница при 200: отдельный счётчик, без двойного учёта
shortPages.add(1, { window });
}
check(res, { "read 200 full page": () => full }, { window });
counted(res, full, window);
}
export function write() {
const n = exec.scenario.iterationInTest;
const sender = fixture.memberIds[n % fixture.memberIds.length];
const chat = WRITE_CHATS[
Math.floor(n / fixture.memberIds.length) % WRITE_CHATS.length
];
const window = windowTag();
const res = http.post(
`${API}/chats/${chat}/messages`,
JSON.stringify({ text: syntheticText(`s${STEP}`, n) }),
{
// ключ — новый на каждую отправку (lib.js); стенд не повторяет
headers: messageHeaders(fixture.tokens[sender]),
responseType: "none",
timeout: `${TIMEOUT_S}s`,
tags: { window },
responseCallback: http.expectedStatuses(201),
},
);
const ok = res.status === 201;
check(res, { "write 201": () => ok }, { window });
counted(res, ok, window);
}
export function me() {
const n = exec.scenario.iterationInTest;
const user = USERS[n % USERS.length];
const window = windowTag();
const res = http.get(`${API}/users/me`, {
headers: authHeaders(fixture.tokens[user]),
responseType: "none",
timeout: `${TIMEOUT_S}s`,
tags: { window },
responseCallback: http.expectedStatuses(200),
});
const ok = res.status === 200;
check(res, { "me 200": () => ok }, { window });
counted(res, ok, window);
}
export function handleSummary(data) {
return summaryFiles(data);
}
+14 -2
View File
@@ -6,6 +6,8 @@
import { WORK_DIR, createChat, register } from "./lib.js";
const MEMBERS = Number(__ENV.MEMBERS || 10);
// чатов записи (Profile.write_chats): у прежних профилей один
const WRITE_CHATS = Math.max(1, Number(__ENV.WRITE_CHATS || 1));
// уровни фоновых чатов: «10x5000,100x400» — число чатов x сообщений в чате
const BACKGROUND = (__ENV.BACKGROUND || "")
.split(",")
@@ -40,12 +42,22 @@ export function setup() {
bgChats.push({ id: createChat(reader.token, title, everyone), size });
}
}
const readChatId = createChat(reader.token, "bench read", everyone);
// чаты записи со всеми пользователями: серии трека 1 делят вставки на
// WRITE_CHATS правых краёв индекса истории (решение 2 design change
// scaling-bench); прежние сценарии пишут в первый — writeChatId
const writeChatIds = [];
for (let i = 0; i < WRITE_CHATS; i++) {
const title = i === 0 ? "bench write" : `bench write #${i}`;
writeChatIds.push(createChat(reader.token, title, everyone));
}
return {
readerId: reader.id,
memberIds,
tokens,
readChatId: createChat(reader.token, "bench read", everyone),
writeChatId: createChat(reader.token, "bench write", everyone),
readChatId,
writeChatId: writeChatIds[0],
writeChatIds,
bgChats,
};
}
+953
View File
@@ -0,0 +1,953 @@
"""Графики серий трека 1: SVG текстом, только stdlib.
Запуск — `make bench_plots LABELS="scaling-a scaling-b" [PLOTS=scaling]`,
результат — `evidence/plots/<PLOTS>/`: `rstar-by-replicas.svg`,
`p95-by-rate-<серия>.svg`, `cpu-by-component.svg` и `summary.md` (R*,
эффективность роста, R*(1 × 4) / R*(1 × 1), точка насыщения и признаки на
k_sat ± 1). Серия при завершении строит свои `p95-by-rate.svg` и
`cpu-by-component.svg` в каталоге метки (`render_series`). Данные —
`meta.json`, `searches.csv`, `runs.csv` меток; графики выводятся из
неизменяемых меток и пересоздаются той же командой. Решение 13 design
change `scaling-bench`; палитра — категориальные слоты по порядку,
проверенные валидатором на CVD, у каждой метки — `<title>` с числами.
"""
import argparse
import json
import math
import shutil
import sys
from pathlib import Path
from typing import Any
from xml.sax.saxutils import escape
import scaling
ROOT = Path(__file__).resolve().parents[1]
BENCH_DIR = ROOT / "evidence" / "bench"
OUT_DIR = ROOT / "evidence" / "plots"
# категориальные слоты в фиксированном порядке (проверены на CVD для
# соседних пар): конфигурации и компоненты получают цвет по позиции
SERIES = (
"#2a78d6",
"#eb6834",
"#1baf7a",
"#eda100",
"#e87ba4",
"#008300",
"#6250d6",
"#e34948",
)
SURFACE = "#fcfcfb"
INK = "#0b0b0b"
INK_2 = "#52514e"
MUTED = "#898781"
GRID = "#e1e0d9"
AXIS = "#c3c2b7"
FONT = 'system-ui, -apple-system, "Segoe UI", sans-serif'
COMPONENTS = (
("app_cpu_cores", "реплики API"),
("db_cpu_cores", "PostgreSQL"),
("lb_cpu_cores", "HAProxy"),
("cache_cpu_cores", "Valkey"),
("generator_cpu_cores", "k6"),
("vm_rest", "остальное в ВМ"),
)
class Svg:
"""Минимальный построитель SVG: элементы — строки."""
def __init__(self, width: int, height: int, title: str) -> None:
self.width = width
self.height = height
self.parts = [
f'<rect x="0" y="0" width="{width}" height="{height}" '
f'fill="{SURFACE}"/>',
self.text_el(24, 30, title, size=16, weight=600),
]
@staticmethod
def text_el(
x: float,
y: float,
text: str,
*,
size: int = 12,
color: str = INK_2,
anchor: str = "start",
weight: int = 400,
rotate: bool = False,
) -> str:
transform = (
f' transform="rotate(-90 {x:.1f} {y:.1f})"' if rotate else ""
)
return (
f'<text x="{x:.1f}" y="{y:.1f}" font-size="{size}" '
f'font-weight="{weight}" fill="{color}" text-anchor="{anchor}"'
f"{transform}>{escape(text)}</text>"
)
def text(self, *args: Any, **kwargs: Any) -> None:
self.parts.append(self.text_el(*args, **kwargs))
def line(
self,
x1: float,
y1: float,
x2: float,
y2: float,
*,
color: str = GRID,
width: float = 1,
dash: str = "",
) -> None:
extra = f' stroke-dasharray="{dash}"' if dash else ""
self.parts.append(
f'<line x1="{x1:.1f}" y1="{y1:.1f}" x2="{x2:.1f}" y2="{y2:.1f}" '
f'stroke="{color}" stroke-width="{width}"{extra}/>',
)
def polyline(self, points: list[tuple[float, float]], color: str) -> None:
if len(points) < 2:
return
coords = " ".join(f"{x:.1f},{y:.1f}" for x, y in points)
self.parts.append(
f'<polyline points="{coords}" fill="none" stroke="{color}" '
'stroke-width="2" stroke-linejoin="round" '
'stroke-linecap="round"/>',
)
def dot(
self,
x: float,
y: float,
color: str,
tip: str,
*,
hollow: bool = False,
) -> None:
fill = SURFACE if hollow else color
self.parts.append(
f'<g><title>{escape(tip)}</title>'
f'<circle cx="{x:.1f}" cy="{y:.1f}" r="7" fill="transparent"/>'
f'<circle cx="{x:.1f}" cy="{y:.1f}" r="4.5" fill="{fill}" '
f'stroke="{color if hollow else SURFACE}" '
f'stroke-width="2"/></g>',
)
def bar(
self,
x: float,
y: float,
width: float,
height: float,
color: str,
tip: str,
*,
top: bool,
) -> None:
"""Сегмент столбика; верхний — со скруглённым концом 4 px."""
if height <= 0:
return
if top and height > 4:
r = 4
path = (
f"M{x:.1f},{y + height:.1f} L{x:.1f},{y + r:.1f} "
f"Q{x:.1f},{y:.1f} {x + r:.1f},{y:.1f} "
f"L{x + width - r:.1f},{y:.1f} "
f"Q{x + width:.1f},{y:.1f} {x + width:.1f},{y + r:.1f} "
f"L{x + width:.1f},{y + height:.1f} Z"
)
shape = f'<path d="{path}" fill="{color}"/>'
else:
shape = (
f'<rect x="{x:.1f}" y="{y:.1f}" width="{width:.1f}" '
f'height="{height:.1f}" fill="{color}"/>'
)
self.parts.append(f"<g><title>{escape(tip)}</title>{shape}</g>")
def legend(
self,
items: list[tuple[str, str, str]],
x: float,
y: float,
width: float,
) -> float:
"""Легенда строками: (цвет, подпись, вид — line, dot, box, dash)."""
cx, cy = x, y
for color, label, kind in items:
item_w = 34 + 7 * len(label)
if cx + item_w > x + width:
cx, cy = x, cy + 20
if kind == "box":
self.parts.append(
f'<rect x="{cx:.1f}" y="{cy - 9:.1f}" width="12" '
f'height="12" rx="2" fill="{color}"/>',
)
elif kind == "dot":
self.parts.append(
f'<circle cx="{cx + 6:.1f}" cy="{cy - 3:.1f}" r="4.5" '
f'fill="{color}"/>',
)
else:
self.line(
cx,
cy - 3,
cx + 16,
cy - 3,
color=color,
width=2,
dash="5 4" if kind == "dash" else "",
)
self.text(cx + 22, cy + 1, label, color=INK_2)
cx += item_w
return cy
def render(self) -> str:
body = "\n".join(self.parts)
return (
'<svg xmlns="http://www.w3.org/2000/svg" '
f'viewBox="0 0 {self.width} {self.height}" '
f'width="{self.width}" height="{self.height}" '
f'font-family=\'{FONT}\'>\n{body}\n</svg>\n'
)
def nice_ticks(high: float, count: int = 5) -> list[float]:
"""Круглые деления оси от 0 до ≥ high."""
if high <= 0:
return [0, 1]
raw = high / count
power = 10 ** math.floor(math.log10(raw))
step = next(m * power for m in (1, 2, 2.5, 5, 10) if m * power >= raw)
ticks = [0.0]
while ticks[-1] < high:
ticks.append(round(ticks[-1] + step, 6))
return ticks
def log_ticks(low: float, high: float) -> list[float]:
ticks = []
exp = math.floor(math.log10(low))
while 10**exp <= high * 1.0001:
for m in (1, 2, 5):
value = m * 10**exp
if low * 0.9999 <= value <= high * 1.0001:
ticks.append(value)
exp += 1
return ticks
def compact(value: float) -> str:
if value >= 1000:
text = f"{value / 1000:.1f}".rstrip("0").rstrip(".")
return f"{text}K"
if value == int(value):
return str(int(value))
return f"{value:g}"
# ------------------------------------------------------------- данные
def load(label_dir: Path) -> dict[str, Any]:
meta = json.loads((label_dir / "meta.json").read_text(encoding="utf-8"))
runs = scaling.read_csv(label_dir / "runs.csv")
searches = scaling.read_csv(label_dir / "searches.csv")
return {
"name": label_dir.name,
"meta": meta,
"runs": runs,
"searches": searches,
"series": meta["profile"].get("series"),
"stats": scaling.config_stats(meta, runs, searches),
"chosen": scaling.chosen_steps(runs, searches),
}
def p95_points(
label: dict[str, Any],
config: str,
) -> tuple[list[tuple[float, float, int]], list[tuple[float, float, int]]]:
"""Медиана p95 по повторам на каждом уровне: ступени лестницы и
фиксированные — линия, деления — отдельные точки."""
line: dict[float, list[float]] = {}
split: dict[float, list[float]] = {}
for search in label["searches"]:
if search["config"] != config:
continue
for step in label["chosen"].get(search["cell"], []):
level = scaling.num(step.get("level"))
p95 = scaling.num(step.get("p95_ms"))
if level is None or p95 is None or p95 <= 0:
continue
target = split if step.get("step_kind") == "bisect" else line
target.setdefault(level, []).append(p95)
def medians(
data: dict[float, list[float]],
) -> list[tuple[float, float, int]]:
return [
(level, scaling.median(values) or 0, len(values))
for level, values in sorted(data.items())
]
return medians(line), medians(split)
def component_values(
label: dict[str, Any],
config: str,
) -> dict[str, float | None]:
"""CPU по компонентам на ступени R*: медиана по ячейкам."""
rows = []
for search in label["searches"]:
if search["config"] != config or search["status"] != "complete":
continue
row = scaling.step_at(
label["chosen"].get(search["cell"], []),
scaling.num(search["r_star_rps"]),
)
if row is not None:
rows.append(row)
values: dict[str, float | None] = {}
for key, _ in COMPONENTS[:-1]:
values[key] = scaling.median(scaling.num(r.get(key)) for r in rows)
stand = sum(v or 0 for v in values.values())
vm = scaling.median(scaling.num(r.get("vm_busy_cores")) for r in rows)
values["vm_rest"] = None if vm is None else max(0.0, vm - stand)
values["vm_busy_cores"] = vm
return values
# ------------------------------------------------------------ графики
def plot_p95(label: dict[str, Any], title: str) -> str:
stats = label["stats"]
width, height = 860, 520
left, right, top, bottom = 76, 24, 96, 64
svg = Svg(width, height, title)
svg.text(
24,
52,
f"Метка {label['name']}: медиана p95 успешных запросов по повторам "
"на каждом уровне; полые точки — ступени деления",
color=INK_2,
)
data = {c["config"]: p95_points(label, c["config"]) for c in stats}
levels = [p[0] for line, split in data.values() for p in line + split]
values = [p[1] for line, split in data.values() for p in line + split]
if not levels:
svg.text(left, top + 40, "Нет данных", color=MUTED)
return svg.render()
x_ticks = nice_ticks(max(levels) * 1.05)
low = 10 ** math.floor(math.log10(max(min(values), 0.5)))
high = 10 ** math.ceil(math.log10(max(max(values), 250)))
y_ticks = log_ticks(low, high)
plot_w = width - left - right
plot_h = height - top - bottom
def sx(value: float) -> float:
return left + value / x_ticks[-1] * plot_w
def sy(value: float) -> float:
span = math.log10(high) - math.log10(low)
return (
top
+ plot_h
- (math.log10(value) - math.log10(low)) / span * plot_h
)
for tick in y_ticks:
svg.line(left, sy(tick), left + plot_w, sy(tick))
svg.text(
left - 8,
sy(tick) + 4,
compact(tick),
color=MUTED,
anchor="end",
)
for tick in x_ticks:
svg.text(
sx(tick),
top + plot_h + 18,
compact(tick),
color=MUTED,
anchor="middle",
)
svg.line(left, top + plot_h, left + plot_w, top + plot_h, color=AXIS)
slo = label["meta"]["profile"].get("slo_p95_ms", 200)
svg.line(
left,
sy(slo),
left + plot_w,
sy(slo),
color=INK_2,
width=1.5,
dash="6 4",
)
svg.text(
left + plot_w - 4,
sy(slo) - 6,
f"SLO p95 {slo:g} мс",
color=INK_2,
anchor="end",
)
svg.text(
left + plot_w / 2,
height - 18,
"Интенсивность, запросов/с",
anchor="middle",
)
svg.text(
20,
top + plot_h / 2,
"p95, мс (логарифмическая шкала)",
anchor="middle",
rotate=True,
)
legend = []
for index, c in enumerate(stats):
color = SERIES[index % len(SERIES)]
line, split = data[c["config"]]
svg.polyline([(sx(x), sy(y)) for x, y, _ in line], color)
for x, y, n in line:
svg.dot(
sx(x),
sy(y),
color,
f"{c['config']}: {x:.0f} запросов/с, p95 {y:.1f} мс (повторов {n})",
)
for x, y, n in split:
svg.dot(
sx(x),
sy(y),
color,
f"{c['config']}: деление {x:.0f} запросов/с, p95 {y:.1f} мс (повторов {n})",
hollow=True,
)
legend.append((color, c["config"], "line"))
svg.legend(legend, left, 76, plot_w)
return svg.render()
def plot_cpu(labels: list[dict[str, Any]], title: str) -> str:
bars = []
for label in labels:
prefix = f"{label['series']}: " if len(labels) > 1 else ""
for c in label["stats"]:
bars.append(
(
f"{prefix}{c['config']}",
component_values(label, c["config"]),
c,
),
)
vm_cpus = labels[0]["meta"].get("docker", {}).get("vm_cpus") or 12
perf = labels[0]["meta"].get("host", {}).get("performance_cores")
width = max(720, 120 + 78 * len(bars))
height = 560
left, right, top, bottom = 64, 24, 130, 84
svg = Svg(width, height, title)
svg.text(
24,
52,
"Медиана занятых ядер по ячейкам на ступени R*;",
color=INK_2,
)
svg.text(
24,
70,
"«остальное в ВМ» — загрузка ВМ сверх контейнеров стенда",
color=INK_2,
)
plot_w = width - left - right
plot_h = height - top - bottom
y_ticks = nice_ticks(max(vm_cpus, 1) * 1.05)
def sy(value: float) -> float:
return top + plot_h - value / y_ticks[-1] * plot_h
for tick in y_ticks:
svg.line(left, sy(tick), left + plot_w, sy(tick))
svg.text(
left - 8,
sy(tick) + 4,
compact(tick),
color=MUTED,
anchor="end",
)
svg.line(left, sy(0), left + plot_w, sy(0), color=AXIS)
svg.line(
left,
sy(vm_cpus),
left + plot_w,
sy(vm_cpus),
color=INK_2,
width=1.5,
dash="6 4",
)
svg.text(
left + plot_w - 4,
sy(vm_cpus) - 6,
f"{vm_cpus} vCPU ВМ",
color=INK_2,
anchor="end",
)
if perf:
svg.line(
left,
sy(perf),
left + plot_w,
sy(perf),
color=MUTED,
width=1.5,
dash="2 4",
)
svg.text(
left + plot_w - 4,
sy(perf) - 6,
f"{perf} производительных ядер хоста",
color=INK_2,
anchor="end",
)
slot = plot_w / max(1, len(bars))
bar_w = min(24.0, slot * 0.6)
for index, (name, values, c) in enumerate(bars):
x = left + slot * index + (slot - bar_w) / 2
base = 0.0
present = [(k, lbl) for k, lbl in COMPONENTS if values.get(k)]
for number, (key, label_text) in enumerate(COMPONENTS):
value = values.get(key) or 0
if value <= 0:
continue
y_top = sy(base + value)
h = sy(base) - y_top
# 2 px поверхности между сегментами
gap = 2 if base > 0 else 0
svg.bar(
x,
y_top,
bar_w,
max(0.0, h - gap),
SERIES[number],
f"{name}: {label_text} {value:.2f} ядра (R* {c['r_star'] or 0:.0f} запросов/с)",
top=key == present[-1][0],
)
base += value
svg.text(
x + bar_w / 2,
sy(base) - 6,
f"{base:.1f}",
color=INK,
anchor="middle",
)
svg.text(
x + bar_w / 2,
top + plot_h + 18,
name,
color=MUTED,
anchor="middle",
)
svg.text(
x + bar_w / 2,
top + plot_h + 34,
f"R* {c['r_star'] or 0:.0f}",
color=MUTED,
anchor="middle",
)
svg.text(
16,
top + plot_h / 2,
"Занятые ядра",
anchor="middle",
rotate=True,
)
svg.legend(
[(SERIES[i], text, "box") for i, (_, text) in enumerate(COMPONENTS)],
left,
98,
plot_w,
)
return svg.render()
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)
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",
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"]]
max_k = max(
[
*by_k.keys(),
4,
*(c["replicas"] for c in (budget or {}).get("stats", [])),
],
)
if base:
values.append(base * max_k)
y_ticks = nice_ticks(max(values or [1]) * 1.05)
plot_w = width - left - right
plot_h = height - top - bottom
def sx(k: float) -> float:
return left + (k - 0.5) / max_k * plot_w
def sy(value: float) -> float:
return top + plot_h - value / y_ticks[-1] * plot_h
for tick in y_ticks:
svg.line(left, sy(tick), left + plot_w, sy(tick))
svg.text(
left - 8,
sy(tick) + 4,
compact(tick),
color=MUTED,
anchor="end",
)
for k in range(1, max_k + 1):
svg.text(
sx(k),
top + plot_h + 18,
str(k),
color=MUTED,
anchor="middle",
)
svg.line(left, sy(0), left + plot_w, sy(0), color=AXIS)
svg.text(
left + plot_w / 2,
height - 18,
"Число реплик API",
anchor="middle",
)
svg.text(
20,
top + plot_h / 2,
"R*, запросов/с",
anchor="middle",
rotate=True,
)
legend = []
if base:
svg.line(
sx(1),
sy(base),
sx(max_k),
sy(base * max_k),
color=MUTED,
width=1.5,
dash="6 4",
)
legend.append((MUTED, "линейный рост от 1 × 1", "dash"))
if by_k:
color = SERIES[0]
points = []
for k, c in sorted(by_k.items()):
if c["r_star"] is None:
continue
lo, hi = min(c["r_stars"]), max(c["r_stars"])
svg.line(sx(k), sy(lo), sx(k), sy(hi), color=color, width=1.5)
svg.line(
sx(k) - 5,
sy(lo),
sx(k) + 5,
sy(lo),
color=color,
width=1.5,
)
svg.line(
sx(k) - 5,
sy(hi),
sx(k) + 5,
sy(hi),
color=color,
width=1.5,
)
points.append((k, c))
svg.polyline([(sx(k), sy(c["r_star"])) for k, c in points], color)
for k, c in points:
eff = sat["efficiency"].get(k) if sat else None
svg.dot(
sx(k),
sy(c["r_star"]),
color,
f"серия b, {k} × 1: R* {scaling.spread(c['r_stars'])} запросов/с"
+ (f", эффективность {eff:.2f}" if eff is not None else ""),
)
if points:
k, c = points[-1]
svg.text(
sx(k) + 10,
sy(c["r_star"]) + 4,
f"{c['r_star']:.0f}",
color=INK,
)
legend.append((color, "серия b: k × 1 CPU", "line"))
if sat and sat["k_sat"]:
k = sat["k_sat"]
svg.line(
sx(k),
top,
sx(k),
top + plot_h,
color=INK_2,
width=1,
dash="2 4",
)
svg.text(sx(k) + 6, top + 14, f"k_sat = {k}", color=INK_2)
if budget:
color = SERIES[1]
for c in budget["stats"]:
if c["r_star"] is None:
continue
k = c["replicas"]
lo, hi = min(c["r_stars"]), max(c["r_stars"])
svg.line(
sx(k) + 14,
sy(lo),
sx(k) + 14,
sy(hi),
color=color,
width=1.5,
)
svg.dot(
sx(k) + 14,
sy(c["r_star"]),
color,
f"серия a, {k} × {c['replica_cpus']}: R* {scaling.spread(c['r_stars'])} запросов/с",
)
svg.text(
sx(k) + 24,
sy(c["r_star"]) + 4,
f"{k} × {c['replica_cpus']}",
color=INK_2,
)
legend.append((color, "серия a: бюджет 4 CPU", "dot"))
svg.legend(legend, left, 76, plot_w)
return svg.render()
# ------------------------------------------------------------ сводка
def render_combined_summary(labels: list[dict[str, Any]], command: str) -> str:
growth = next((x for x in labels if x["series"] == "b"), None)
sat = scaling.saturation(growth["stats"]) if growth else None
base = None
if sat and 1 in sat["by_k"]:
base = sat["by_k"][1]
# host_cost всех серий — против 1 × 1 серии b (в серии a её нет)
for label in labels:
for c in label["stats"]:
scaling.apply_host_cost(c, base["app_us_marginal"])
lines = [
"# Цена масштабирования: сводка серий",
"",
f"- Команда: `{command}`",
"- Метки: "
+ ", ".join(
f"`{x['name']}` (серия `{x['series']}`, commit "
f"`{x['meta']['git']['commit']}`, {x['meta']['status']})"
for x in 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* по конфигурациям",
"",
"| Серия | Конфигурация | R*, запросов/с | Эффективность | p95 на "
"250 / 500, мс | p99 на 250 / 500, мс | CPU реплик на запрос на 500, "
"мкс | Предельный CPU на запрос, мкс | host_cost | Признаки на R* | "
"Признаки на первой нарушившей |",
"|---|---|---|---|---|---|---|---|---|---|---|",
]
for label in labels:
for c in label["stats"]:
k = c["replicas"]
eff = (
c["r_star"] / (k * base["r_star"])
if base and base["r_star"] and c["r_star"] is not None
else None
)
f250 = c["fixed"].get(250) or {}
f500 = c["fixed"].get(500) or {}
us = f500.get("app_us")
cost = c.get("host_cost")
signs_r = list(c["signs_r"])
signs_f = list(c["signs_f"])
lines.append(
f"| {label['series']} | {c['config']} | "
f"{scaling.spread(c['r_stars'])} | {scaling.fmt(eff, 2)} | "
f"{scaling.fmt(f250.get('p95'), 1)} / "
f"{scaling.fmt(f500.get('p95'), 1)} | "
f"{scaling.fmt(f250.get('p99'), 1)} / "
f"{scaling.fmt(f500.get('p99'), 1)} | {scaling.fmt(us, 0)} | "
f"{scaling.fmt(c.get('app_us_marginal'), 0)} | "
f"{scaling.fmt(cost, 2)} | {' '.join(signs_r) or '—'} | "
f"{' '.join(signs_f) or '—'} |",
)
lines.append("")
budget = next((x for x in labels if x["series"] == "a"), None)
if budget and base and base["r_star"]:
one = next((c for c in budget["stats"] if c["replicas"] == 1), None)
if one and one["r_star"] is not None:
lines += [
"## Фиксированный бюджет",
"",
f"R*(1 × {one['replica_cpus']}) / R*(1 × 1) = "
f"{one['r_star']:.0f} / {base['r_star']:.0f} = "
f"**{one['r_star'] / base['r_star']:.2f}** (H1: 0,9–1,15). "
"Посекундный максимум CPU реплики 1 × "
f"{one['replica_cpus']} за серию: "
f"{scaling.fmt(one['app_cpu_second_max'], 2)} ядра.",
"",
]
if sat:
lines += [
"## Точка насыщения (серия `b`)",
"",
f"Правило: наименьшее k ≤ 5, при котором медиана R*(k + 1) < "
f"{scaling.THRESHOLDS['k_sat_gain']} × R*(k).",
"",
"| k | R*, запросов/с | Прирост к k − 1 | Эффективность | "
"CPU реплики на R*, ядер на реплику | CPU PostgreSQL на R*, "
"ядер | Признаки на R* | Признаки на первой нарушившей |",
"|---|---|---|---|---|---|---|---|",
]
previous = None
for k, c in sorted(sat["by_k"].items()):
gain = (
c["r_star"] / previous - 1
if previous and c["r_star"] is not None
else None
)
per = c["app_cpu_r"] / k if c["app_cpu_r"] is not None else None
lines.append(
f"| {k} | {scaling.spread(c['r_stars'])} | "
+ (f"{gain * 100:+.0f} %" if gain is not None else "—")
+ f" | {scaling.fmt(sat['efficiency'].get(k), 2)} | "
f"{scaling.fmt(per, 2)} | {scaling.fmt(c['db_cpu_r'], 2)} | "
f"{' '.join(c['signs_r']) or '—'} | "
f"{' '.join(c['signs_f']) or '—'} |",
)
previous = c["r_star"]
k_sat = sat["k_sat"]
lines += [
"",
"k_sat: "
+ (
f"**{k_sat}** — признаки на k_sat − 1, k_sat и k_sat + 1 — "
"строки таблицы выше"
if k_sat
else "нет: в пределах серии каждая реплика добавляет не "
"меньше 10 %"
),
"",
]
return "\n".join(lines)
def render_series(label_dir: Path) -> None:
"""Графики серии в каталоге метки: p95 от интенсивности и CPU по
компонентам на R*."""
try:
label = load(label_dir)
except (OSError, ValueError, KeyError):
return
if not label["searches"]:
return
series = label["series"]
(label_dir / "p95-by-rate.svg").write_text(
plot_p95(label, f"Серия {series}: p95 от интенсивности"),
encoding="utf-8",
)
(label_dir / "cpu-by-component.svg").write_text(
plot_cpu([label], f"Серия {series}: CPU по компонентам на R*"),
encoding="utf-8",
)
def render_combined(names: list[str], out_name: str, command: str) -> Path:
labels = [load(BENCH_DIR / name) for name in names]
out = OUT_DIR / out_name
if out.exists():
shutil.rmtree(out)
out.mkdir(parents=True)
(out / "rstar-by-replicas.svg").write_text(
plot_rstar(labels, "R* от числа реплик API"),
encoding="utf-8",
)
for label in labels:
(out / f"p95-by-rate-{label['series']}.svg").write_text(
plot_p95(label, f"Серия {label['series']}: p95 от интенсивности"),
encoding="utf-8",
)
(out / "cpu-by-component.svg").write_text(
plot_cpu(labels, "CPU по компонентам на R*"),
encoding="utf-8",
)
(out / "summary.md").write_text(
render_combined_summary(labels, command),
encoding="utf-8",
)
return out
def main(argv: list[str]) -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--labels", default="")
parser.add_argument("--out", default="scaling")
args = parser.parse_args(argv)
names = args.labels.split()
if not names:
print(
'labels are required: make bench_plots LABELS="<label> …" '
"[PLOTS=<dir>]",
flush=True,
)
return 2
missing = [n for n in names if not (BENCH_DIR / n / "meta.json").is_file()]
if missing:
print(f"labels not found: {', '.join(missing)}", flush=True)
return 1
not_series = [
n
for n in names
if not json.loads(
(BENCH_DIR / n / "meta.json").read_text(encoding="utf-8"),
)["profile"].get("series")
]
if not_series:
print(
f"not track 1 series labels: {', '.join(not_series)}",
flush=True,
)
return 1
command = f'make bench_plots LABELS="{" ".join(names)}" PLOTS={args.out}'
out = render_combined(names, args.out, command)
print((out / "summary.md").read_text(encoding="utf-8"), flush=True)
print(f"saved to {out.relative_to(ROOT)}", flush=True)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
+1230 -47
View File
File diff suppressed because it is too large Load Diff
+112
View File
@@ -0,0 +1,112 @@
#!/usr/bin/env bash
# Сэмплер стенда трека 1 (решение 7 design change scaling-bench). Работает
# только внутри контейнера mtusi-bench-sampler (образ PostgreSQL стенда,
# --cgroupns host, сеть mtusi-bench), не на хосте: его запускает
# bench/run.py (Stand.start_sampler). Раз в интервал пишет в
# /work/samples.log строки с отметкой часов ВМ в наносекундах:
# cg <нс> <роль> <id12> <usage_usec> <nr_periods> <nr_throttled>
# <throttled_usec> <memory.current> <cpu.pressure some total>
# cg <нс> <роль> <id12> missing — нет каталога cgroup
# vm <нс> <занято jiffies> <всего jiffies> <PSI CPU some total, мкс>
# lb <нс> # <заголовок CSV статистики HAProxy> / lb <нс> api,<строка>
# lb <нс> missing — статистика недоступна
# В фоне psql с \watch пишет /work/pg-samples.log (одно соединение на всю
# ячейку): act, db, wal, io — разбор в bench/scaling.py (parse_samples).
# Аргументы: <интервал, с> <роль>=<полный id контейнера>…
set -u
interval=$1
shift
roles=()
ids=()
for arg in "$@"; do
roles+=("${arg%%=*}")
ids+=("${arg#*=}")
done
export PGPASSWORD="$POSTGRES_PASSWORD"
psql "host=postgres user=$POSTGRES_USER dbname=$POSTGRES_DB \
application_name=bench-sampler" -XAtq -F '|' >/work/pg-samples.log 2>&1 <<SQL &
WITH t AS (
SELECT (extract(epoch FROM clock_timestamp()) * 1000)::bigint AS ts
)
SELECT 'act', (SELECT ts FROM t), coalesce(host(client_addr), '-'),
coalesce(state, '-'), coalesce(wait_event_type, 'CPU'),
coalesce(wait_event, '-'), count(*)
FROM pg_stat_activity
WHERE backend_type = 'client backend' AND pid <> pg_backend_pid()
GROUP BY 3, 4, 5, 6
UNION ALL
SELECT 'db', (SELECT ts FROM t), xact_commit::text, xact_rollback::text,
sessions::text, sessions_fatal::text, numbackends::bigint
FROM pg_stat_database WHERE datname = current_database()
UNION ALL
SELECT 'wal', (SELECT ts FROM t), wal_records::text, wal_fpi::text,
wal_bytes::text, NULL, NULL
FROM pg_stat_wal
UNION ALL
SELECT 'io', (SELECT ts FROM t), coalesce(sum(writes), 0)::text,
coalesce(sum(fsyncs), 0)::text, NULL, NULL, NULL
FROM pg_stat_io WHERE object = 'wal'
\watch $interval
SQL
exec 4>>/work/samples.log
cg_line() {
local role=$1 id=$2 dir=/sys/fs/cgroup/docker/$2
local key val usage=0 periods=0 throttled=0 thr_usec=0 mem=0 psi=0 rest
if [[ ! -r $dir/cpu.stat ]]; then
printf 'cg %s %s %s missing\n' "$ns" "$role" "${id:0:12}" >&4
return
fi
while read -r key val; do
case $key in
usage_usec) usage=$val ;;
nr_periods) periods=$val ;;
nr_throttled) throttled=$val ;;
throttled_usec) thr_usec=$val ;;
esac
done <"$dir/cpu.stat"
read -r mem <"$dir/memory.current"
read -r _ _ _ _ rest <"$dir/cpu.pressure"
psi=${rest#total=}
printf 'cg %s %s %s %s %s %s %s %s %s\n' "$ns" "$role" "${id:0:12}" \
"$usage" "$periods" "$throttled" "$thr_usec" "$mem" "$psi" >&4
}
vm_line() {
local _cpu user nice system idle iowait irq softirq steal rest total
read -r _cpu user nice system idle iowait irq softirq steal rest </proc/stat
total=$((user + nice + system + idle + iowait + irq + softirq + steal))
read -r _ _ _ _ rest </proc/pressure/cpu
printf 'vm %s %s %s %s\n' "$ns" "$((total - idle - iowait))" "$total" \
"${rest#total=}" >&4
}
lb_lines() {
local line
if ! exec 3<>/dev/tcp/haproxy/8404 2>/dev/null; then
printf 'lb %s missing\n' "$ns" >&4
return
fi
printf 'GET /stats;csv HTTP/1.0\r\n\r\n' >&3
while IFS= read -r line; do
line=${line%$'\r'}
case $line in
"# "* | api,*) printf 'lb %s %s\n' "$ns" "$line" >&4 ;;
esac
done <&3
exec 3<&-
}
while :; do
# EPOCHREALTIME bash 5 — часы ВМ без запуска date
ns=${EPOCHREALTIME/./}000
for i in "${!ids[@]}"; do
cg_line "${roles[$i]}" "${ids[$i]}"
done
vm_line
lb_lines
sleep "$interval"
done
+1689
View File
File diff suppressed because it is too large Load Diff