From 95539a1883ece5a3130c55a92e186dd2f6308745 Mon Sep 17 00:00:00 2001 From: roman Date: Sun, 11 Oct 2026 11:27:30 +0300 Subject: [PATCH] feat: add track 1 series db with a tight PostgreSQL CPU limit Configs may carry a fifth element, the PostgreSQL CPU limit, which goes into the config key (-pg), the budget and the cell stand. Series db: 1, 2, 4 replicas at the tight limit and a 4 x 1 control at 2 CPU; label summaries show PostgreSQL CPU at R* against its limit and throttling. Co-Authored-By: Claude Opus 5.5 --- Makefile | 6 +- bench/run.py | 55 ++++++++-- bench/scaling.py | 100 ++++++++++++++---- .../specs/load-benchmark/spec.md | 28 +++-- 4 files changed, 152 insertions(+), 37 deletions(-) diff --git a/Makefile b/Makefile index bf3d130e..20a3588f 100644 --- a/Makefile +++ b/Makefile @@ -275,14 +275,16 @@ SCALING_LABEL ?= scaling-$(SERIES) # уровень 5, трек 1 «Цена масштабирования»: серия на стенде mtusi-bench — # SERIES=a (бюджет 4 CPU: 1 × 4, 2 × 2, 4 × 1, ~50 мин), b (1…6 реплик по # 1 CPU, ~100 мин), pool (4 реплики при max_connections 100 и 50, ~35 мин), -# ab (1 × 1 и 6 × 1 для «до/после» и A/A, ~35 мин); каждая ячейка — свежий +# ab (1 × 1 и 6 × 1 для «до/после» и A/A, ~35 мин), db (1, 2, 4 реплики при +# узком лимите CPU PostgreSQL и контроль 4 × 1 при 2 CPU, ~50 мин), db_quick +# (самопроверка серии db, ~5 мин, метка quick-*); каждая ячейка — свежий # стенд, открытая модель, поиск R* по SLO; результат — # evidence/bench/$(SCALING_LABEL)/. RESUME=1 — продолжить прерванную метку # на том же commit .PHONY: bench_scaling bench_scaling: @if [ -z "$(SERIES)" ]; then \ - echo "SERIES is required: make bench_scaling SERIES=a|b|pool|ab|quick [SCALING_LABEL=...] [RESUME=1]"; \ + echo "SERIES is required: make bench_scaling SERIES=a|b|pool|ab|db|quick|db_quick [SCALING_LABEL=...] [RESUME=1]"; \ exit 2; \ fi $(KEEP_AWAKE) uv run python bench/run.py --profile scaling_$(SERIES) --label $(SCALING_LABEL) $(if $(RESUME),--resume) diff --git a/bench/run.py b/bench/run.py index 876d2786..a6562268 100644 --- a/bench/run.py +++ b/bench/run.py @@ -318,7 +318,8 @@ class Profile: # как у образа; у ячейки серии — из конфигурации db_max_connections: int = 100 series: str = "" - configs: tuple[tuple[int, str, str, int], ...] = () + # у серии db — пятый элемент: CPU PostgreSQL конфигурации + configs: tuple[tuple[Any, ...], ...] = () write_chats: int = 1 mix: tuple[tuple[str, float], ...] = () fixed_rps: tuple[int, ...] = () @@ -527,7 +528,7 @@ PROFILES = { def scaling_profile( name: str, series: str, - configs: tuple[tuple[int, str, str, int], ...], + configs: tuple[tuple[Any, ...], ...], **fields: Any, ) -> Profile: """Профиль серии трека 1: общие поля всех серий в одном месте, чтобы @@ -570,6 +571,14 @@ def scaling_profile( B_CONFIGS = tuple((k, "1", "512m", 100) for k in range(1, 7)) +# серия db: CPU PostgreSQL у 1, 2 и 4 реплик и контроль 4 × 1 при 2 CPU +DB_CPUS_TIGHT = "0.5" +DB_CONFIGS = ( + (1, "1", "512m", 100, DB_CPUS_TIGHT), + (2, "1", "512m", 100, DB_CPUS_TIGHT), + (4, "1", "512m", 100, DB_CPUS_TIGHT), + (4, "1", "512m", 100, "2"), +) PROFILES.update( { # фиксированный бюджет приложения 4 CPU / 2 ГиБ @@ -606,18 +615,45 @@ PROFILES.update( bisect_steps=1, max_steps=6, ), + # насыщение PostgreSQL управляемым опытом (verify S2, указание + # пользователя 2026-10-11): 1, 2 и 4 реплики при узком лимите CPU + # PostgreSQL и контроль — 4 реплики при прежних 2 CPU. Пятый + # элемент конфигурации — CPU PostgreSQL; лимит — по калибровке + # (design, «Найдено в verify») + "scaling_db": scaling_profile( + "scaling_db", + "db", + DB_CONFIGS, + ), + # самопроверка серии db и калибровка лимита: 2 и 4 реплики при + # узком лимите, один повтор, короткие окна + "scaling_db_quick": scaling_profile( + "scaling_db_quick", + "db_quick", + DB_CONFIGS[1:3], + sizes=(2_000,), + repeats=1, + fixed_rps=(250,), + first_warmup_s=8, + step_warmup_s=3, + step_measure_s=8, + bisect_steps=1, + max_steps=6, + ), }, ) def cell_profile(profile: Profile, cell: dict[str, Any]) -> Profile: - """Профиль ячейки: реплики и max_connections из конфигурации.""" + """Профиль ячейки: реплики, max_connections и (серия db) CPU + PostgreSQL из конфигурации.""" return replace( profile, replicas=cell["replicas"], cpus=cell["replica_cpus"], memory=cell["replica_memory"], db_max_connections=cell["db_max_connections"], + db_cpus=cell.get("db_cpus") or profile.db_cpus, ) @@ -625,12 +661,14 @@ def budget(profile: Profile, vm_cpus: int, vm_memory: int) -> dict[str, Any]: """Сумма лимитов CPU и памяти стенда и генератора по конфигурациям серии (решение 1): реплики, PostgreSQL, LB, Valkey, k6, сэмплер.""" result = {} - for replicas, cpus, memory, max_conn in profile.configs: - key = scaling.config_key(replicas, cpus, memory, max_conn) + for config in profile.configs: + parts = scaling.unpack_config(config) + replicas, cpus, memory, _, db_cpus = parts + key = scaling.config_key(*parts) cpu = replicas * float(cpus) + sum( float(value) for value in ( - profile.db_cpus, + db_cpus or profile.db_cpus, profile.lb_cpus, profile.cache_cpus, profile.generator_cpus or "0", @@ -845,7 +883,10 @@ def vm_warnings(profile: Profile) -> list[str]: return [] replicas = [(profile.replicas, profile.memory)] if profile.is_series: - replicas = [(k, memory) for k, _, memory, _ in profile.configs] + replicas = [ + (k, memory) + for k, _, memory, *_ in map(scaling.unpack_config, profile.configs) + ] extra = ( (profile.generator_memory, profile.sampler_memory) if profile.is_series diff --git a/bench/scaling.py b/bench/scaling.py index 43887ae0..c45d98e6 100644 --- a/bench/scaling.py +++ b/bench/scaling.py @@ -227,16 +227,39 @@ def spread(values: Iterable[float | None], digits: int = 0) -> str: # ----------------------------------------------------- конфигурации -def config_key(replicas: int, cpus: str, _memory: str, max_conn: int) -> str: - """Имя конфигурации: `4x1`, у предела соединений не 100 — `4x1-c50`. +def config_key( + replicas: int, + cpus: str, + _memory: str, + max_conn: int, + db_cpus: str = "", +) -> str: + """Имя конфигурации: `4x1`, у предела соединений не 100 — `4x1-c50`, + у своего лимита CPU PostgreSQL (серия `db`) — `4x1-pg0.5`. Память реплики в имя не входит: в сериях она задана числом CPU.""" key = f"{replicas}x{cpus}" - return key if max_conn == 100 else f"{key}-c{max_conn}" + if max_conn != 100: + key = f"{key}-c{max_conn}" + return f"{key}-pg{db_cpus}" if db_cpus else key + + +def unpack_config(config: Any) -> tuple[int, str, str, int, str]: + """Конфигурация серии: (реплик, CPU и память реплики, max_connections + [, CPU PostgreSQL]). Пятый элемент — только у серии `db`; без него + лимит PostgreSQL — профиля.""" + replicas, cpus, memory, max_conn, *rest = config + return ( + int(replicas), + str(cpus), + str(memory), + int(max_conn), + str(rest[0]) if rest else "", + ) def plan_cells( - configs: list[tuple[int, str, str, int]], + configs: list[tuple[Any, ...]], repeats: int, seed: int, ) -> list[dict[str, Any]]: @@ -252,21 +275,24 @@ def plan_cells( if len(order) > 1 and order[0] == previous: order[0], order[1] = order[1], order[0] for index in order: - replicas, cpus, memory, max_conn = configs[index] - key = config_key(replicas, cpus, memory, max_conn) - plan.append( - { - "cell": f"{key}-r{round_no}", - "config": key, - "replicas": replicas, - "replica_cpus": cpus, - "replica_memory": memory, - "db_max_connections": max_conn, - "repeat": round_no, - "round": round_no, - "order": len(plan) + 1, - }, + replicas, cpus, memory, max_conn, db_cpus = unpack_config( + configs[index], ) + key = config_key(replicas, cpus, memory, max_conn, db_cpus) + cell = { + "cell": f"{key}-r{round_no}", + "config": key, + "replicas": replicas, + "replica_cpus": cpus, + "replica_memory": memory, + "db_max_connections": max_conn, + "repeat": round_no, + "round": round_no, + "order": len(plan) + 1, + } + if db_cpus: + cell["db_cpus"] = db_cpus + plan.append(cell) previous = order[-1] return plan @@ -1141,9 +1167,13 @@ def config_stats( profile = meta["profile"] fixed = profile.get("fixed_rps") or [] order = [ - config_key(int(r), str(c), str(m), int(mc)) - for r, c, m, mc in profile.get("configs", []) + config_key(*unpack_config(config)) + for config in profile.get("configs", []) ] + db_limits = { + config_key(*parts): parts[4] or str(profile.get("db_cpus", "")) + for parts in map(unpack_config, profile.get("configs", [])) + } result = [] for key in order: cells = [s for s in searches if s["config"] == key] @@ -1155,6 +1185,7 @@ def config_stats( at_f: list[list[str]] = [] reasons = [] db_at_r = [] + db_thr_at_r: list[float | None] = [] app_at_r = [] app_sec = [] marginals: list[float | None] = [] @@ -1183,6 +1214,7 @@ def config_stats( if r_row is not None: at_r.append((r_row.get("signs") or "").split()) db_at_r.append(num(r_row.get("db_cpu_cores"))) + db_thr_at_r.append(num(r_row.get("db_throttled_ratio"))) app_at_r.append(num(r_row.get("app_cpu_cores"))) if f_row is not None: at_f.append((f_row.get("signs") or "").split()) @@ -1235,6 +1267,8 @@ def config_stats( "signs_r": majority(at_r), "signs_f": majority(at_f), "db_cpu_r": median(db_at_r), + "db_throttled_r": median(db_thr_at_r), + "db_cpus": db_limits.get(key, ""), "app_cpu_r": median(app_at_r), "app_cpu_second_max": max( (v for v in app_sec if v is not None), @@ -1375,7 +1409,8 @@ def render_summary( f"{profile['repeats']}, порядок кругами (зерно " f"{profile['order_seed']})", f"- Лимиты без swap: PostgreSQL {profile['db_cpus']} CPU / " - f"{profile['db_memory']}, HAProxy {profile['lb_cpus']} / " + f"{profile['db_memory']} (у конфигураций `-pg` — свой лимит " + f"CPU), HAProxy {profile['lb_cpus']} / " f"{profile['lb_memory']}, Valkey {profile['cache_cpus']} / " f"{profile['cache_memory']}, k6 {profile['generator_cpus']} / " f"{profile['generator_memory']}, сэмплер {profile['sampler_cpus']} " @@ -1420,6 +1455,29 @@ def render_summary( f"{fmt(c['app_us_marginal'], 0)} | {fmt(c['host_cost'], 2)} |", ) lines.append("") + if any("-pg" in c["config"] for c in stats): + # серия db: насыщение PostgreSQL — CPU у лимита и троттлинг CFS + lines += [ + "## PostgreSQL на R*", + "", + "| Конфигурация | Лимит CPU PostgreSQL | CPU PostgreSQL на R*, " + "ядер | Доля лимита | Троттлинг PostgreSQL на R*, доля " + "периодов |", + "|---|---|---|---|---|", + ] + for c in stats: + limit = num(c.get("db_cpus")) + share = ( + c["db_cpu_r"] / limit + if limit and c["db_cpu_r"] is not None + else None + ) + lines.append( + f"| {c['config']} | {c.get('db_cpus') or '—'} | " + f"{fmt(c['db_cpu_r'], 2)} | {fmt(share, 2)} | " + f"{fmt(c.get('db_throttled_r'), 3)} |", + ) + lines.append("") for lvl in fixed: lines += [ f"## Фиксированный уровень {lvl} запросов/с", diff --git a/openspec/changes/scaling-bench/specs/load-benchmark/spec.md b/openspec/changes/scaling-bench/specs/load-benchmark/spec.md index 0477f918..18e871a4 100644 --- a/openspec/changes/scaling-bench/specs/load-benchmark/spec.md +++ b/openspec/changes/scaling-bench/specs/load-benchmark/spec.md @@ -395,12 +395,18 @@ CPU и памяти реплики и предел соединений PostgreS - `ab` — 1 и 6 реплик по 1 CPU / 512 МиБ, как в серии `b`: одна реплика и наибольшая конфигурация в бюджете ВМ, для замера «до/после» и уровня шума A/A; -- короткая серия самопроверки — команда `make bench_scaling_quick`, - метка `quick-…`, в git не идёт. +- `db` — насыщение PostgreSQL управляемым опытом: 1, 2 и 4 реплики по + 1 CPU / 512 МиБ при узком лимите CPU PostgreSQL (выбран калибровкой, + записан в паспорт и имя конфигурации) и контроль — 4 реплики при + прежних 2 CPU PostgreSQL. Лимит CPU PostgreSQL у этой серии — часть + конфигурации; +- короткие серии самопроверки — `make bench_scaling_quick` и `make + bench_scaling SERIES=db_quick` с меткой `quick-…`, в git не идут. -Лимиты LB, PostgreSQL, Valkey и генератора, профиль нагрузки, ступени и -SLO SHALL быть одинаковыми во всех сериях. В каждой конфигурации серий -`a`, `b`, `pool` и `ab` сумма лимитов CPU стенда и генератора MUST NOT +Лимиты LB, Valkey и генератора, профиль нагрузки, ступени и SLO SHALL +быть одинаковыми во всех сериях; лимит PostgreSQL — тоже, кроме +конфигураций серии `db`. В каждой конфигурации серий +`a`, `b`, `pool`, `ab` и `db` сумма лимитов CPU стенда и генератора MUST NOT превышать число CPU ВМ Docker: иначе команда завершается с ненулевым кодом до запуска стенда. Паспорт SHALL содержать по каждой конфигурации сумму лимитов CPU и памяти, а также CPU и память ВМ. @@ -436,12 +442,20 @@ SHALL можно продолжить той же командой с `RESUME=1` #### Scenario: Бюджет помещается в ВМ -- **WHEN** проверяющий открывает паспорт серии `a`, `b`, `pool` или - `ab` +- **WHEN** проверяющий открывает паспорт серии `a`, `b`, `pool`, `ab` + или `db` - **THEN** у каждой конфигурации сумма лимитов CPU стенда и генератора не больше числа CPU ВМ, а сумма лимитов памяти записана рядом с памятью ВМ +#### Scenario: Насыщение PostgreSQL + +- **WHEN** выполняется `make bench_scaling SERIES=db` +- **THEN** в метке все конфигурации серии × 3 повтора в перемешанном + порядке на одном коде; у каждой конфигурации в паспорте — лимит CPU + PostgreSQL, прочитанный у контейнера, а сводка показывает R*, CPU + PostgreSQL на R* относительно лимита и его троттлинг + #### Scenario: Перемешанный порядок - **WHEN** серия запущена дважды с тем же профилем