feat: add 5 experiment
This commit is contained in:
@@ -0,0 +1,68 @@
|
||||
# Эксперимент: цена масштабирования
|
||||
|
||||
Проверяем, помогает ли увеличение числа API-реплик при прежнем и растущем бюджете ресурсов. Затем проверяем одну настройку Go — `GOMAXPROCS=1`.
|
||||
|
||||
Читать по порядку:
|
||||
|
||||
1. [Методика](docs/method.md): гипотезы, конфигурации и нагрузка.
|
||||
2. [Настройка Go](docs/runtime-tuning.md): почему выбрали её и зачем провели три проверки.
|
||||
3. [Результаты](../../evidence/grade5/RESULTS.md): числа, графики и выводы.
|
||||
4. [Каталог доказательств](../../evidence/grade5/README.md): исходные данные каждой серии.
|
||||
|
||||
## Содержимое папки
|
||||
|
||||
| Файл или папка | Назначение |
|
||||
|---|---|
|
||||
| `docs/` | Объяснение исследования |
|
||||
| `protocols/` | JSON с параметрами запусков; внутри `pilots/` — пробные запуски |
|
||||
| `run.sh` | Запуск серии из WSL и восстановление обычного приложения |
|
||||
| `run.py` | Подготовка стенда, порядок прогонов, фиксация версий и результатов |
|
||||
| `load.py` | HTTP-нагрузка и сбор метрик |
|
||||
| `common.py` | Настройки конфигураций, Docker, восстановление данных |
|
||||
| `fixture.sql` | 200 пользователей, 100 чатов, 10000 сообщений |
|
||||
| `compose.yml`, `haproxy.cfg` | Отдельный экспериментальный стенд |
|
||||
| `requirements-lock.txt` | Точные версии Python-зависимостей |
|
||||
| `analyze.py` | CSV, сводные показатели и графики |
|
||||
| `postprocess/` | Проверка сохранённых данных и расчёт решений по гипотезам |
|
||||
|
||||
## Новые измерения
|
||||
|
||||
Команды выполняются из корня репозитория в WSL. Скрипт останавливает обычное приложение и затем восстанавливает его. У эксперимента отдельные БД, Redis и volumes. Основная серия занимает несколько часов. Другую нагрузку одновременно запускать нельзя.
|
||||
|
||||
```sh
|
||||
bash experiments/lab3-scale/run.sh pilot pilot-my-run
|
||||
bash experiments/lab3-scale/run.sh baseline baseline-my-run
|
||||
|
||||
# Три проверки одной настройки; запускать последовательно.
|
||||
bash experiments/lab3-scale/run.sh runtime-400 runtime-400-my-run
|
||||
bash experiments/lab3-scale/run.sh runtime-capacity runtime-capacity-my-run
|
||||
bash experiments/lab3-scale/run.sh runtime-latency runtime-latency-my-run
|
||||
```
|
||||
|
||||
Каждой серии задавайте новое имя. Незавершённые прогоны сохраняются для разбора, перезаписывать их нельзя. При продолжении серии совпадающий протокол позволяет пропустить завершённые точки.
|
||||
|
||||
Ручное восстановление приложения:
|
||||
|
||||
```sh
|
||||
.memory/bench-env/bin/python experiments/lab3-scale/run.py restore
|
||||
```
|
||||
|
||||
## Анализ имеющихся данных
|
||||
|
||||
Эти команды читают измерения и обновляют сводки в `evidence`, без HTTP-нагрузки и изменения контейнеров. Нужен Python с зависимостями из `requirements-lock.txt`; после запуска `run.sh` он есть в `.memory/bench-env`.
|
||||
|
||||
```sh
|
||||
.memory/bench-env/bin/python experiments/lab3-scale/analyze.py baseline-01
|
||||
.memory/bench-env/bin/python experiments/lab3-scale/analyze.py latency-improvement-01
|
||||
.memory/bench-env/bin/python experiments/lab3-scale/postprocess/decisions.py audit baseline-01
|
||||
.memory/bench-env/bin/python experiments/lab3-scale/postprocess/decisions.py hi improvement-01
|
||||
.memory/bench-env/bin/python experiments/lab3-scale/postprocess/decisions.py hc capacity-improvement-01
|
||||
.memory/bench-env/bin/python experiments/lab3-scale/postprocess/decisions.py hl latency-improvement-01
|
||||
.memory/bench-env/bin/python experiments/lab3-scale/postprocess/plot_latency.py latency-improvement-01
|
||||
```
|
||||
|
||||
## Повторение исходного опыта
|
||||
|
||||
В каждой завершённой серии сохранены `protocol.json`, его SHA-256, порядок и `source.tar.gz`. Архив содержит фактический код, инструменты и первоначальное описание гипотез до измерений. Для повторения именно того опыта распакуйте архив в отдельную копию проекта и используйте протокол той же серии.
|
||||
|
||||
Тексты в `docs/` — пояснения для чтения. Текущие JSON в `protocols/` обновлены под структуру проекта после уборки; гипотезы, пороги и нагрузка сохранены. Старые протоколы и измерения в `evidence` не изменены. Перед запуском проверяются хеши кода и инструментов; при следующих изменениях сначала фиксируйте новую версию протокола. На другом компьютере числа могут отличаться.
|
||||
@@ -0,0 +1,391 @@
|
||||
import argparse
|
||||
import csv
|
||||
import gzip
|
||||
import json
|
||||
import statistics
|
||||
from collections import defaultdict
|
||||
from datetime import datetime
|
||||
|
||||
from common import EVIDENCE, write_json
|
||||
|
||||
|
||||
def seconds(value):
|
||||
return datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp()
|
||||
|
||||
|
||||
def diagnostics(directory, manifest):
|
||||
samples = []
|
||||
with gzip.open(directory / "telemetry.jsonl.gz", "rt") as file:
|
||||
samples = [json.loads(line) for line in file]
|
||||
limits = {row["instance"]: row["cpu"] / 1e9 for row in manifest["containers"]}
|
||||
previous, cpu, throttled, memory = (
|
||||
{},
|
||||
defaultdict(list),
|
||||
defaultdict(list),
|
||||
defaultdict(list),
|
||||
)
|
||||
queue, active, waits = [], [], defaultdict(int)
|
||||
for sample in samples:
|
||||
if "error" in sample:
|
||||
continue
|
||||
queue.append(
|
||||
sum(
|
||||
int(row["qcur"] or 0)
|
||||
for row in sample["haproxy"]
|
||||
if row["svname"].startswith("api")
|
||||
)
|
||||
)
|
||||
active.append(sample["postgres"]["active"])
|
||||
for row in sample["postgres"]["waits"]:
|
||||
waits[str(row["event_type"]) + ":" + str(row["event"])] += row["count"]
|
||||
for resource in sample["resources"]:
|
||||
name = resource["instance"]
|
||||
stats = resource["cpu_stats"] or {}
|
||||
old = previous.get(name)
|
||||
if old and "system_cpu_usage" in stats and "system_cpu_usage" in old:
|
||||
system_delta = stats["system_cpu_usage"] - old["system_cpu_usage"]
|
||||
if system_delta > 0:
|
||||
delta = (
|
||||
stats["cpu_usage"]["total_usage"]
|
||||
- old["cpu_usage"]["total_usage"]
|
||||
)
|
||||
cores = delta / system_delta * stats.get("online_cpus", 16)
|
||||
if delta >= 0:
|
||||
cpu[resource["service"]].append(cores / limits[name])
|
||||
current_throttle, old_throttle = (
|
||||
stats.get("throttling_data", {}),
|
||||
old.get("throttling_data", {}),
|
||||
)
|
||||
periods = current_throttle.get("periods", 0) - old_throttle.get(
|
||||
"periods", 0
|
||||
)
|
||||
if periods > 0:
|
||||
throttled[resource["service"]].append(
|
||||
(
|
||||
current_throttle.get("throttled_periods", 0)
|
||||
- old_throttle.get("throttled_periods", 0)
|
||||
)
|
||||
/ periods
|
||||
)
|
||||
previous[name] = stats
|
||||
memory[resource["service"]].append(
|
||||
(resource["memory_stats"] or {}).get("usage", 0) / 1048576
|
||||
)
|
||||
pools = defaultdict(list)
|
||||
for row in json.loads(directory.joinpath("pool.json").read_text()):
|
||||
pools[row["instance"]].append(row)
|
||||
acquires = duration_ns = empties = 0
|
||||
for values in pools.values():
|
||||
if len(values) >= 2:
|
||||
acquires += values[-1]["acquire_count"] - values[0]["acquire_count"]
|
||||
duration_ns += (
|
||||
values[-1]["acquire_duration_ns"] - values[0]["acquire_duration_ns"]
|
||||
)
|
||||
empties += (
|
||||
values[-1]["empty_acquire_count"] - values[0]["empty_acquire_count"]
|
||||
)
|
||||
return {
|
||||
"cpu_fraction_of_limit_mean": {
|
||||
name: round(statistics.mean(values), 4) for name, values in cpu.items()
|
||||
},
|
||||
"throttled_period_fraction_mean": {
|
||||
name: round(statistics.mean(values), 4)
|
||||
for name, values in throttled.items()
|
||||
},
|
||||
"memory_max_mib": {
|
||||
name: round(max(values), 3) for name, values in memory.items()
|
||||
},
|
||||
"haproxy_max_queue": max(queue, default=0),
|
||||
"postgres_max_active": max(active, default=0),
|
||||
"postgres_wait_sample_counts": dict(waits),
|
||||
"pool_acquire_mean_ms": round(duration_ns / max(acquires, 1) / 1e6, 4),
|
||||
"pool_empty_acquire_fraction": round(empties / max(acquires, 1), 4),
|
||||
}
|
||||
|
||||
|
||||
def analyze(series):
|
||||
directory = EVIDENCE / series
|
||||
reports, groups = [], defaultdict(list)
|
||||
for path in sorted(directory.glob("*/summary.json")):
|
||||
manifest = json.loads(path.with_name("manifest.json").read_text())
|
||||
summary = json.loads(path.read_text())
|
||||
diagnostic = diagnostics(path.parent, manifest)
|
||||
report = {
|
||||
"run": manifest["run_id"],
|
||||
"config": manifest["config_name"],
|
||||
"repeat": manifest["repeat"],
|
||||
"rate": manifest["rate"],
|
||||
**summary,
|
||||
"diagnostics": diagnostic,
|
||||
}
|
||||
reports.append(report)
|
||||
groups[(report["config"], report["repeat"])].append(report)
|
||||
capacities = []
|
||||
for (config, repeat), values in sorted(groups.items()):
|
||||
values.sort(key=lambda row: row["rate"])
|
||||
passed, failures, invalid = [], [], []
|
||||
stopped = False
|
||||
for row in values:
|
||||
if not row["valid"]:
|
||||
invalid.append(row["rate"])
|
||||
if row["slo_pass"] and not stopped:
|
||||
passed.append(row["rate"])
|
||||
else:
|
||||
stopped = True
|
||||
failures.append(row["rate"])
|
||||
capacities.append(
|
||||
{
|
||||
"config": config,
|
||||
"repeat": repeat,
|
||||
"capacity_lower": max(passed, default=0),
|
||||
"capacity_upper": min(failures) if failures else None,
|
||||
"invalid_rates": invalid,
|
||||
"nonmonotonic": any(
|
||||
row["slo_pass"] and row["rate"] > min(failures) for row in values
|
||||
)
|
||||
if failures
|
||||
else False,
|
||||
}
|
||||
)
|
||||
write_json(directory / "analysis.json", {"runs": reports, "capacities": capacities})
|
||||
if all(
|
||||
name in {row["config"] for row in capacities}
|
||||
for name in ("A1", "A4", "B1", "B4")
|
||||
):
|
||||
write_json(directory / "hypotheses.json", hypothesis_decisions(capacities))
|
||||
with directory.joinpath("summary.csv").open("w", newline="") as file:
|
||||
fields = [
|
||||
"config",
|
||||
"repeat",
|
||||
"rate",
|
||||
"goodput_rps",
|
||||
"success_ratio",
|
||||
"p95_ms",
|
||||
"p99_ms",
|
||||
"dispatch_p95_ms",
|
||||
"generator_cpu_cores",
|
||||
"valid",
|
||||
"slo_pass",
|
||||
]
|
||||
writer = csv.DictWriter(file, fieldnames=fields)
|
||||
writer.writeheader()
|
||||
for row in reports:
|
||||
writer.writerow({key: row.get(key) for key in fields})
|
||||
print(json.dumps(capacities, indent=2))
|
||||
if reports:
|
||||
plots(directory, reports, capacities)
|
||||
return reports, capacities
|
||||
|
||||
|
||||
def plots(directory, reports, capacities):
|
||||
import matplotlib
|
||||
|
||||
matplotlib.use("Agg")
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
colors = {
|
||||
"A1": "#0072B2",
|
||||
"A2": "#009E73",
|
||||
"A4": "#D55E00",
|
||||
"B1": "#CC79A7",
|
||||
"B2": "#56B4E9",
|
||||
"B4": "#E69F00",
|
||||
}
|
||||
if not any(row["config"].startswith(("A", "B")) for row in reports):
|
||||
figure, axes = plt.subplots(1, 3, figsize=(14, 4), layout="constrained")
|
||||
for ax, metric, label in zip(
|
||||
axes,
|
||||
("window_goodput_rps", "p95_ms", "success_ratio"),
|
||||
(
|
||||
"Successful responses / s",
|
||||
"p95 full latency (ms)",
|
||||
"Successful / scheduled",
|
||||
),
|
||||
):
|
||||
for config in sorted({row["config"] for row in reports}):
|
||||
grouped = defaultdict(list)
|
||||
for row in reports:
|
||||
if row["config"] == config and row.get(metric) is not None:
|
||||
grouped[row["rate"]].append(row[metric])
|
||||
rates = sorted(grouped)
|
||||
ax.plot(
|
||||
rates,
|
||||
[statistics.median(grouped[rate]) for rate in rates],
|
||||
"o-",
|
||||
label=config,
|
||||
)
|
||||
ax.fill_between(
|
||||
rates,
|
||||
[min(grouped[rate]) for rate in rates],
|
||||
[max(grouped[rate]) for rate in rates],
|
||||
alpha=0.15,
|
||||
)
|
||||
ax.set_xlabel("Offered requests / s")
|
||||
ax.set_ylabel(label)
|
||||
ax.grid(alpha=0.25)
|
||||
ax.legend()
|
||||
figure.savefig(directory / "improvement.png", dpi=160)
|
||||
plt.close(figure)
|
||||
return
|
||||
for metric, label, name in (
|
||||
(
|
||||
"window_goodput_rps",
|
||||
"Successful responses / s (measurement window)",
|
||||
"throughput",
|
||||
),
|
||||
("p95_ms", "p95 full response latency (ms)", "latency"),
|
||||
("success_ratio", "Successful / scheduled", "success"),
|
||||
):
|
||||
figure, axes = plt.subplots(1, 2, figsize=(11, 4), layout="constrained")
|
||||
for ax, prefix in zip(axes, ("A", "B")):
|
||||
for config in sorted(
|
||||
{row["config"] for row in reports if row["config"].startswith(prefix)}
|
||||
):
|
||||
grouped = defaultdict(list)
|
||||
for row in reports:
|
||||
if row["config"] == config and row.get(metric) is not None:
|
||||
grouped[row["rate"]].append(row[metric])
|
||||
rates = sorted(grouped)
|
||||
median = [statistics.median(grouped[rate]) for rate in rates]
|
||||
ax.plot(rates, median, "o-", color=colors.get(config), label=config)
|
||||
ax.fill_between(
|
||||
rates,
|
||||
[min(grouped[rate]) for rate in rates],
|
||||
[max(grouped[rate]) for rate in rates],
|
||||
alpha=0.15,
|
||||
color=colors.get(config),
|
||||
)
|
||||
ax.set_title(
|
||||
"Fixed total API resources"
|
||||
if prefix == "A"
|
||||
else "Resources increase with replicas"
|
||||
)
|
||||
ax.set_xlabel("Offered requests / s")
|
||||
ax.set_ylabel(label)
|
||||
ax.grid(alpha=0.25)
|
||||
ax.legend()
|
||||
if metric == "p95_ms":
|
||||
ax.axhline(500, color="black", linestyle="--", linewidth=0.8)
|
||||
if metric == "success_ratio":
|
||||
ax.axhline(0.99, color="black", linestyle="--", linewidth=0.8)
|
||||
figure.savefig(directory / (name + ".png"), dpi=160)
|
||||
plt.close(figure)
|
||||
figure, ax = plt.subplots(figsize=(9, 4), layout="constrained")
|
||||
configs = sorted({row["config"] for row in capacities})
|
||||
for index, config in enumerate(configs):
|
||||
values = [
|
||||
row["capacity_lower"] for row in capacities if row["config"] == config
|
||||
]
|
||||
ax.bar(index, statistics.median(values), color=colors.get(config), alpha=0.7)
|
||||
ax.scatter([index] * len(values), values, color="black", s=22, zorder=3)
|
||||
ax.set_xticks(range(len(configs)), configs)
|
||||
ax.set_ylabel("Last contiguous SLO-passing offered rate (req/s)")
|
||||
ax.set_title("Capacity: medians and all repetitions; finite rate grid")
|
||||
ax.grid(axis="y", alpha=0.25)
|
||||
figure.savefig(directory / "capacity.png", dpi=160)
|
||||
plt.close(figure)
|
||||
figure, axes = plt.subplots(1, 2, figsize=(11, 4), layout="constrained")
|
||||
for ax, prefix in zip(axes, ("A", "B")):
|
||||
for config in sorted(
|
||||
{row["config"] for row in reports if row["config"].startswith(prefix)}
|
||||
):
|
||||
grouped = defaultdict(list)
|
||||
for row in reports:
|
||||
if row["config"] == config:
|
||||
value = row["diagnostics"]["cpu_fraction_of_limit_mean"].get("api")
|
||||
if value is not None:
|
||||
grouped[row["rate"]].append(value)
|
||||
rates = sorted(grouped)
|
||||
ax.plot(
|
||||
rates,
|
||||
[statistics.median(grouped[rate]) for rate in rates],
|
||||
"o-",
|
||||
color=colors.get(config),
|
||||
label=config,
|
||||
)
|
||||
ax.axhline(1, color="black", linestyle="--", linewidth=0.8)
|
||||
ax.set_title("API CPU relative to per-container limit: " + prefix)
|
||||
ax.set_xlabel("Offered requests / s")
|
||||
ax.set_ylabel("Mean CPU / configured CPU limit")
|
||||
ax.grid(alpha=0.25)
|
||||
ax.legend()
|
||||
figure.savefig(directory / "api-cpu.png", dpi=160)
|
||||
plt.close(figure)
|
||||
|
||||
|
||||
def hypothesis_decisions(capacities):
|
||||
decisions = {}
|
||||
lookup = {(row["config"], row["repeat"]): row for row in capacities}
|
||||
for name, prefix, threshold, less in (
|
||||
("H1", "A", 1.2, True),
|
||||
("H2", "B", 1.5, False),
|
||||
):
|
||||
blocks = []
|
||||
for repeat in sorted({row["repeat"] for row in capacities}):
|
||||
one, four = (
|
||||
lookup.get((prefix + "1", repeat)),
|
||||
lookup.get((prefix + "4", repeat)),
|
||||
)
|
||||
if one is None or four is None:
|
||||
continue
|
||||
lower_ratio = (
|
||||
four["capacity_lower"] / one["capacity_lower"]
|
||||
if one["capacity_lower"]
|
||||
else None
|
||||
)
|
||||
lower_bound = (
|
||||
four["capacity_lower"] / one["capacity_upper"]
|
||||
if one["capacity_upper"]
|
||||
else None
|
||||
)
|
||||
upper_bound = (
|
||||
four["capacity_upper"] / one["capacity_lower"]
|
||||
if four["capacity_upper"] and one["capacity_lower"]
|
||||
else None
|
||||
)
|
||||
valid = not (
|
||||
one["invalid_rates"]
|
||||
or four["invalid_rates"]
|
||||
or one["nonmonotonic"]
|
||||
or four["nonmonotonic"]
|
||||
)
|
||||
decision = "inconclusive"
|
||||
if valid and lower_bound is not None and upper_bound is not None:
|
||||
if less:
|
||||
if upper_bound < threshold:
|
||||
decision = "supported"
|
||||
elif lower_bound >= threshold:
|
||||
decision = "refuted"
|
||||
else:
|
||||
if lower_bound >= threshold:
|
||||
decision = "supported"
|
||||
elif upper_bound < threshold:
|
||||
decision = "refuted"
|
||||
blocks.append(
|
||||
{
|
||||
"repeat": repeat,
|
||||
"ratio_of_grid_capacities": lower_ratio,
|
||||
"ratio_lower_bound": lower_bound,
|
||||
"ratio_upper_bound": upper_bound,
|
||||
"decision": decision,
|
||||
}
|
||||
)
|
||||
outcomes = [row["decision"] for row in blocks]
|
||||
result = (
|
||||
outcomes[0]
|
||||
if len(outcomes) == 3 and len(set(outcomes)) == 1
|
||||
else "inconclusive"
|
||||
)
|
||||
decisions[name] = {
|
||||
"threshold": threshold,
|
||||
"result": result,
|
||||
"blocks": blocks,
|
||||
"note": "Conservative bounds from finite offered-rate grid; not a confidence interval.",
|
||||
}
|
||||
return decisions
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(__doc__)
|
||||
parser.add_argument("series")
|
||||
analyze(parser.parse_args().series)
|
||||
@@ -0,0 +1,218 @@
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import subprocess
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
ROOT = HERE.parents[1]
|
||||
PRIVATE = ROOT / ".memory/benchmark"
|
||||
EVIDENCE = ROOT / "evidence/grade5"
|
||||
PROJECT = "highload-lab3-bench"
|
||||
BASE = "http://127.0.0.1:18080"
|
||||
STATS = "http://127.0.0.1:18404/stats;csv"
|
||||
CONFIGS = {
|
||||
"A1": {"replicas": 1, "cpu": 1, "memory": "256m", "pool": 12},
|
||||
"A2": {"replicas": 2, "cpu": 0.5, "memory": "128m", "pool": 6},
|
||||
"A4": {"replicas": 4, "cpu": 0.25, "memory": "64m", "pool": 3},
|
||||
"B1": {"replicas": 1, "cpu": 0.5, "memory": "128m", "pool": 12},
|
||||
"B2": {"replicas": 2, "cpu": 0.5, "memory": "128m", "pool": 6},
|
||||
"B4": {"replicas": 4, "cpu": 0.5, "memory": "128m", "pool": 3},
|
||||
}
|
||||
|
||||
|
||||
def shell(args, *, input=None):
|
||||
result = subprocess.run(
|
||||
args,
|
||||
check=False,
|
||||
cwd=ROOT,
|
||||
input=input,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
)
|
||||
if result.returncode:
|
||||
# Do not expose command/environment/stdin containing credentials.
|
||||
raise RuntimeError(
|
||||
f"Command {args[0]} failed (exit {result.returncode}); inspect local setup logs"
|
||||
)
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def prepare_private():
|
||||
PRIVATE.mkdir(parents=True, exist_ok=True)
|
||||
path = PRIVATE / "environment"
|
||||
if not path.exists():
|
||||
path.write_text("BENCH_PASSWORD=" + secrets.token_hex(24) + "\n")
|
||||
path.chmod(0o600)
|
||||
|
||||
|
||||
def compose(args, config=None):
|
||||
env = os.environ.copy()
|
||||
env.update(
|
||||
{
|
||||
"BENCH_CPU": ".5",
|
||||
"BENCH_MEMORY": "128m",
|
||||
"BENCH_REPLICAS": "2",
|
||||
"BENCH_POOL": "6",
|
||||
"BENCH_GOMAXPROCS": "",
|
||||
}
|
||||
)
|
||||
if config:
|
||||
env.update(
|
||||
{
|
||||
"BENCH_CPU": str(config["cpu"]),
|
||||
"BENCH_MEMORY": config["memory"],
|
||||
"BENCH_REPLICAS": str(config["replicas"]),
|
||||
"BENCH_POOL": str(config["pool"]),
|
||||
"BENCH_IMAGE": config.get("image", "highload-lab3-bench-api:baseline"),
|
||||
}
|
||||
)
|
||||
env["BENCH_GOMAXPROCS"] = str(config.get("gomaxprocs", ""))
|
||||
result = subprocess.run(
|
||||
[
|
||||
"docker",
|
||||
"compose",
|
||||
"--project-name",
|
||||
PROJECT,
|
||||
"--project-directory",
|
||||
str(ROOT),
|
||||
"--env-file",
|
||||
str(PRIVATE / "environment"),
|
||||
"-f",
|
||||
str(HERE / "compose.yml"),
|
||||
*args,
|
||||
],
|
||||
check=False,
|
||||
cwd=ROOT,
|
||||
env=env,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
)
|
||||
if result.returncode:
|
||||
PRIVATE.joinpath("last-compose-error.log").write_text(result.stderr)
|
||||
raise RuntimeError(
|
||||
"Benchmark Compose failed; see private last-compose-error.log"
|
||||
)
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def sql(query):
|
||||
return compose_psql(query)
|
||||
|
||||
|
||||
def compose_psql(query):
|
||||
db = compose(["ps", "-q", "db"])
|
||||
return shell(
|
||||
[
|
||||
"docker",
|
||||
"exec",
|
||||
"-i",
|
||||
db,
|
||||
"psql",
|
||||
"-X",
|
||||
"-q",
|
||||
"-t",
|
||||
"-A",
|
||||
"-v",
|
||||
"ON_ERROR_STOP=1",
|
||||
"-U",
|
||||
"benchmark",
|
||||
"-d",
|
||||
"benchmark",
|
||||
],
|
||||
input=query,
|
||||
)
|
||||
|
||||
|
||||
def md5uuid(value):
|
||||
return str(uuid.UUID(hashlib.md5(value.encode()).hexdigest()))
|
||||
|
||||
|
||||
def restore_fixture():
|
||||
sql(HERE.joinpath("fixture.sql").read_text())
|
||||
if sql("SELECT count(*) FROM messages;") != "10000":
|
||||
raise RuntimeError("Fixture restoration did not produce 10000 initial messages")
|
||||
redis = compose(["ps", "-q", "redis"])
|
||||
# Only the benchmark project's Redis is eligible for clearing sessions.
|
||||
shell(["docker", "exec", redis, "redis-cli", "FLUSHDB"])
|
||||
actors = []
|
||||
protocol = bytearray()
|
||||
for i in range(200):
|
||||
token = secrets.token_hex(32)
|
||||
user_id = md5uuid("bench-user-" + str(i))
|
||||
key = "messenger:session:" + hashlib.sha256(token.encode()).hexdigest()
|
||||
parts = ["SET", key, user_id, "EX", "86400"]
|
||||
protocol.extend(f"*{len(parts)}\r\n".encode())
|
||||
for part in parts:
|
||||
data = part.encode()
|
||||
protocol.extend(f"${len(data)}\r\n".encode() + data + b"\r\n")
|
||||
actors.append({"id": user_id, "token": token})
|
||||
result = subprocess.run(
|
||||
["docker", "exec", "-i", redis, "redis-cli", "--pipe"],
|
||||
check=False,
|
||||
input=bytes(protocol),
|
||||
capture_output=True,
|
||||
)
|
||||
if result.returncode or b"errors: 0" not in result.stdout:
|
||||
raise RuntimeError("Session fixture failed")
|
||||
return actors
|
||||
|
||||
|
||||
def inspect_public(container):
|
||||
return json.loads(
|
||||
shell(
|
||||
[
|
||||
"docker",
|
||||
"inspect",
|
||||
"--format",
|
||||
'{"id":{{json .Id}},"instance":{{json .Config.Hostname}},"image":{{json .Image}},"cpu":{{.HostConfig.NanoCpus}},"memory":{{.HostConfig.Memory}},"state":{{json .State.Status}},"oom":{{.State.OOMKilled}},"restarts":{{.RestartCount}},"ports":{{json .HostConfig.PortBindings}}}',
|
||||
container,
|
||||
]
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def current_containers():
|
||||
result = []
|
||||
for service in ("api", "db", "redis", "haproxy"):
|
||||
for container in compose(["ps", "-q", service]).split():
|
||||
info = inspect_public(container)
|
||||
info["service"] = service
|
||||
result.append(info)
|
||||
return result
|
||||
|
||||
|
||||
def code_hash():
|
||||
digest = hashlib.sha256()
|
||||
paths = list(ROOT.joinpath("src/backend").rglob("*"))
|
||||
paths.extend(
|
||||
ROOT / relative for relative in ("src/go.mod", "src/go.sum", "src/Dockerfile")
|
||||
)
|
||||
for path in sorted(paths):
|
||||
if path.is_file():
|
||||
digest.update(str(path.relative_to(ROOT)).encode())
|
||||
digest.update(path.read_bytes())
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def instrument_hash():
|
||||
digest = hashlib.sha256()
|
||||
for path in sorted(HERE.iterdir()):
|
||||
if path.is_file() and path.suffix in (
|
||||
".py",
|
||||
".sql",
|
||||
".cfg",
|
||||
".yml",
|
||||
".txt",
|
||||
".sh",
|
||||
):
|
||||
digest.update(path.name.encode())
|
||||
digest.update(path.read_bytes())
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def write_json(path, value):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n")
|
||||
@@ -0,0 +1,81 @@
|
||||
name: highload-lab3-bench
|
||||
services:
|
||||
db:
|
||||
image: postgres:16.10-bookworm
|
||||
cpus: 1.0
|
||||
mem_limit: 512m
|
||||
environment:
|
||||
POSTGRES_DB: benchmark
|
||||
POSTGRES_USER: benchmark
|
||||
POSTGRES_PASSWORD: ${BENCH_PASSWORD:?prepare the private environment first}
|
||||
volumes: [bench_db:/var/lib/postgresql/data]
|
||||
networks: [data]
|
||||
healthcheck:
|
||||
test: [CMD-SHELL, 'pg_isready -U benchmark -d benchmark']
|
||||
interval: 1s
|
||||
timeout: 3s
|
||||
retries: 60
|
||||
redis:
|
||||
image: redis:7.4.11-bookworm
|
||||
cpus: 0.25
|
||||
mem_limit: 128m
|
||||
command: [redis-server, --appendonly, 'yes', --appendfsync, everysec, --dir, /data]
|
||||
volumes: [bench_redis:/data]
|
||||
networks: [data]
|
||||
healthcheck:
|
||||
test: [CMD, redis-cli, ping]
|
||||
interval: 1s
|
||||
timeout: 3s
|
||||
retries: 60
|
||||
migrate:
|
||||
image: highload-lab3-bench-api:baseline
|
||||
cpus: 0.5
|
||||
mem_limit: 128m
|
||||
networks: [data]
|
||||
environment:
|
||||
DATABASE_URL: postgres://benchmark:${BENCH_PASSWORD}@db:5432/benchmark?sslmode=disable
|
||||
command: [./messenger, migrate, up]
|
||||
depends_on:
|
||||
db: {condition: service_healthy}
|
||||
api:
|
||||
image: ${BENCH_IMAGE:-highload-lab3-bench-api:baseline}
|
||||
cpus: ${BENCH_CPU:-0.5}
|
||||
mem_limit: ${BENCH_MEMORY:-128m}
|
||||
deploy:
|
||||
replicas: ${BENCH_REPLICAS:-2}
|
||||
stop_grace_period: 15s
|
||||
networks: [proxy, data]
|
||||
environment:
|
||||
DATABASE_URL: postgres://benchmark:${BENCH_PASSWORD}@db:5432/benchmark?sslmode=disable
|
||||
DATABASE_MAX_CONNS: ${BENCH_POOL:-6}
|
||||
BENCH_POOL_STATS: '1'
|
||||
GOMAXPROCS: ${BENCH_GOMAXPROCS:-}
|
||||
REDIS_ADDR: redis:6379
|
||||
SESSION_TTL_SECONDS: 86400
|
||||
APP_PORT: 8080
|
||||
APP_HOST: 0.0.0.0
|
||||
healthcheck:
|
||||
test: [CMD, ./messenger, healthcheck]
|
||||
interval: 1s
|
||||
timeout: 3s
|
||||
retries: 60
|
||||
depends_on:
|
||||
migrate: {condition: service_completed_successfully}
|
||||
redis: {condition: service_healthy}
|
||||
haproxy:
|
||||
image: haproxy:3.2.25-alpine
|
||||
cpus: 0.5
|
||||
mem_limit: 128m
|
||||
ports: ['127.0.0.1:18080:8080', '127.0.0.1:18404:8404']
|
||||
networks: [edge, proxy]
|
||||
volumes:
|
||||
- ./experiments/lab3-scale/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||
depends_on:
|
||||
api: {condition: service_healthy}
|
||||
volumes:
|
||||
bench_db:
|
||||
bench_redis:
|
||||
networks:
|
||||
edge:
|
||||
proxy: {internal: true}
|
||||
data: {internal: true}
|
||||
@@ -0,0 +1,54 @@
|
||||
# Методика проверки масштабирования
|
||||
|
||||
## Что проверяем
|
||||
|
||||
**H1.** Если разделить прежние 1 CPU и 256 MiB между четырьмя API вместо одной, прирост предельной нагрузки будет меньше 20%: `C4 / C1 < 1.20`.
|
||||
|
||||
**H2.** Если каждой API дать по 0.5 CPU и 128 MiB, четыре реплики выдержат хотя бы в 1.5 раза больше запросов, чем одна: `C4 / C1 >= 1.50`.
|
||||
|
||||
**C** — последняя подряд проходящая ступень нагрузки. Ступень проходит, когда успешны не менее 99% запланированных запросов, p95 успешных ответов не превышает 500 мс, генератор успевает отправлять нагрузку и все подтверждённые записи найдены в БД.
|
||||
|
||||
Если 300 запросов/с проходят, а 400 уже нет, предел находится между 300 и 400. Это интервал сетки, а не точное значение и не доверительный интервал. Для H1 верхняя граница отношения должна быть ниже 1.20; для H2 нижняя — не меньше 1.50. Обратные границы доказывают опровержение. Если интервал пересекает порог, данных недостаточно. Для общего вывода решения всех трёх повторов должны совпасть. Немонотонность, неверные условия или ненайденная граница дают неопределённый результат.
|
||||
|
||||
## Конфигурации
|
||||
|
||||
| Условие | Реплики | CPU / RAM каждой | CPU / RAM всех API | Соединения БД: каждой / всего |
|
||||
|---|---:|---|---|---|
|
||||
| A1 | 1 | 1 / 256 MiB | 1 / 256 MiB | 12 / 12 |
|
||||
| A2 | 2 | 0.5 / 128 MiB | 1 / 256 MiB | 6 / 12 |
|
||||
| A4 | 4 | 0.25 / 64 MiB | 1 / 256 MiB | 3 / 12 |
|
||||
| B1 | 1 | 0.5 / 128 MiB | 0.5 / 128 MiB | 12 / 12 |
|
||||
| B2 | 2 | 0.5 / 128 MiB | 1 / 256 MiB | 6 / 12 |
|
||||
| B4 | 4 | 0.5 / 128 MiB | 2 / 512 MiB | 3 / 12 |
|
||||
|
||||
PostgreSQL получает 1 CPU / 512 MiB, Redis — 0.25 CPU / 128 MiB, HAProxy — 0.5 CPU / 128 MiB во всех условиях. Общий пул БД ограничен 12 соединениями, чтобы добавление API не увеличивало его автоматически. A2 и B2 одинаковы по настройкам, но измерены отдельно.
|
||||
|
||||
Образ приложения один, Go 1.22.2; на исходной машине фактический `GOMAXPROCS=16`. HAProxy использует roundrobin без повторной отправки неудачного запроса. Проверки готовности идут раз в секунду; для переключения нужны две успешные или неуспешные проверки.
|
||||
|
||||
## Один прогон
|
||||
|
||||
1. Пересоздаём API и восстанавливаем 200 пользователей, 100 чатов, 10000 сообщений. Подготавливаем сессии Redis. PostgreSQL и Redis продолжают работать; файловый кэш ОС не сбрасываем.
|
||||
2. Прогреваем приложение 15 секунд при 25 запросах/с.
|
||||
3. Отправляем заданную нагрузку 30 секунд: 80% POST сообщений и 20% GET первой страницы истории, `limit=50`. Каждый POST имеет новый ключ идемпотентности и текст 128 байт. Вход по паролю не измеряется.
|
||||
4. Ждём ответы на начатые запросы, сопоставляем каждую подтверждённую запись с сообщением и ключом идемпотентности в БД.
|
||||
5. Сохраняем результаты и выдерживаем паузу 10 секунд.
|
||||
|
||||
Генератор отправляет запросы по расписанию, не ожидая предыдущего ответа. Если сервер не успевает, появляется очередь и растёт задержка. Таймаут — 5 секунд, повторов нет. Задержка отсчитывается от запланированной отправки и включает отставание генератора.
|
||||
|
||||
Нагрузки: **100, 200, 250, 300, 400, 500, 800 запросов/с**. Три повтора, всего `6 × 7 × 3 = 126` прогонов. Конфигурации перемешиваются, ступени внутри них возрастают. Seed нагрузки — 230300, seeds порядка — 230301, 230302, 230303. Лимит одновременно выполняющихся запросов — 8192.
|
||||
|
||||
## Метрики и пригодность данных
|
||||
|
||||
Сохраняем ответы и ошибки, p50/p95/p99, CPU/RAM и ограничения CPU контейнеров, ожидание соединений pgx, подключения и ожидания PostgreSQL, состояния и очередь HAProxy, CPU и отставание генератора. Целевая частота наблюдения — раз в секунду; фактическое время есть в данных.
|
||||
|
||||
На графике пропускной способности считаем успешные ответы внутри 30-секундного окна. Поздние ответы сохраняем отдельно. p95 относится только к успешным ответам, поэтому его нужно читать вместе с долей успехов: массовые таймауты могут оставить небольшой p95 у остальных ответов.
|
||||
|
||||
Прогон непригоден при ошибке сборщика ресурсов/БД, неверном коде, данных или лимитах, посторонней нагрузке либо ограничении генератора. Последнее означает: больше 1% запросов не отправлены из-за локального лимита, или p95 отставания больше 100 мс при среднем CPU процесса не ниже 0.85 ядра. Необъяснённое отставание обсуждается как ограничение. Недоступная статистика перегруженного HAProxy сохраняется как наблюдение. Ошибки API, OOM и плохая производительность не служат причиной удалить результат.
|
||||
|
||||
## Повторяемость и ограничения
|
||||
|
||||
У стенда отдельные volumes, одинаковые начальные данные и фиксированные ресурсы. Сохраняются seeds, образы, хеши, протокол, порядок и архив исходников. Пилоты отделены от основной серии. [Проверки настройки](runtime-tuning.md) используют новые прогоны.
|
||||
|
||||
Все повторы сделаны на одном компьютере. Они показывают разброс, но не подтверждают тот же эффект на другом оборудовании. Генератор делит хост с Docker; наблюдение и healthchecks тоже потребляют ресурсы.
|
||||
|
||||
[Параметры нового запуска](../protocols/baseline.json), [исходный протокол](../../../evidence/grade5/baseline-01/protocol.json), [результаты](../../../evidence/grade5/RESULTS.md).
|
||||
@@ -0,0 +1,37 @@
|
||||
# Одна настройка Go, три проверки
|
||||
|
||||
В основной серии четыре маленьких API почти полностью использовали CPU-квоту, а ограничение CPU срабатывало в 93–94% периодов. Go разрешал выполнять код параллельно на 16 потоках при квоте 0.25 CPU на API. Поэтому проверили **`GOMAXPROCS=1` вместо 16**.
|
||||
|
||||
Параметр ограничивает число потоков, одновременно выполняющих Go-код. Сетевые запросы и ожидание БД по-прежнему могут выполняться конкурентно. Используемый Go 1.22 не определяет этот параметр по квоте контейнера; см. [документацию Go](https://go.dev/doc/go1.25#container-aware-gomaxprocs).
|
||||
|
||||
I0 — контроль с 16, I1 — настройка с 1. Обе конфигурации: четыре API по 0.25 CPU / 64 MiB и по три соединения БД. Образ, данные, ресурсы зависимостей и профиль запросов одинаковы. Меняется только `GOMAXPROCS`.
|
||||
|
||||
## Почему не одна проверка
|
||||
|
||||
Первый опыт показал снижение задержки, но один повтор не уложился в 500 мс. Второй проверял рост предельной нагрузки на 15%; выбранные ступени не позволили доказать его во всех повторах. Третий проверял более узкий эффект: снижение задержки при одной устойчивой нагрузке.
|
||||
|
||||
Это три вопроса к одной настройке. Цель и пороги следующей проверки фиксировались до её новых измерений. Старые результаты не подменялись и не объединялись с новыми.
|
||||
|
||||
| Проверка | Вопрос | Прогонов | Итог |
|
||||
|---|---|---:|---|
|
||||
| HI, 400 запросов/с | Снижается ли p95 хотя бы на 15% с выполнением SLO во всех парах? | 6 | В одной паре p95 = 871 мс; общего подтверждения нет |
|
||||
| HC, 325 и 375 запросов/с | Вырастет ли предельная нагрузка C хотя бы на 15%? | 12 | Во втором блоке интервал слишком широк; данных недостаточно |
|
||||
| HL, 325 запросов/с | Снижается ли p95 хотя бы на 15% при фиксированной нагрузке? | 6 | Все пары прошли; снижение на 60–68% |
|
||||
|
||||
## Условия и критерии
|
||||
|
||||
**HI.** Три пары при 400 запросах/с. В каждой `p95(I1) / p95(I0) <= 0.85`, у I1 не менее 99% успехов и не меньше, чем у контроля, p95 не выше 500 мс, подтверждённые записи сохранены. Seeds порядка: 230401, 230402, 230403. [Настройки](../protocols/runtime-400.json), [исходный протокол](../../../evidence/grade5/improvement-01/protocol.json).
|
||||
|
||||
**HC.** Ступени 325 и 375 запросов/с для обеих конфигураций в трёх блоках. Нижняя граница `C(I1) / C(I0)` должна быть не меньше 1.15 во всех блоках. Например, контроль не проходит 325, а настройка проходит 375: отношение больше `375 / 325 = 1.154`, этого достаточно. Если контроль проходит 325, но не 375, обе реальные границы могут быть почти равны 375 — доказать 15% нельзя. Отсутствие проходящей точки контроля не означает нулевую реальную мощность. Seeds: 230501, 230502, 230503. [Настройки](../protocols/runtime-capacity.json), [исходный протокол](../../../evidence/grade5/capacity-improvement-01/protocol.json).
|
||||
|
||||
**HL.** Условия HI при 325 запросах/с; все шесть прогонов новые. Seeds: 230601, 230602, 230603. [Настройки](../protocols/runtime-latency.json), [исходный протокол](../../../evidence/grade5/latency-improvement-01/protocol.json).
|
||||
|
||||
В HI и HL подтверждение требует всех трёх пригодных пар с выполнением каждого условия. Если все три пригодные пары не выполняют условия — опровержение. Смешанный результат или непригодные данные — неопределённость. В HC подтверждение требует нижнюю границу отношения не меньше 1.15 во всех блоках, опровержение — верхнюю меньше 1.15 во всех. Немонотонность или нарушение сохранности также не позволяют подтвердить гипотезу.
|
||||
|
||||
Перед каждым прогоном восстанавливаются данные и пересоздаются API. Прогрев 15 с, измерение 30 с, пауза 10 с, timeout 5 с, seed нагрузки 230300, лимит запросов 8192. Правила пригодности — из [общей методики](method.md). Все запланированные прогоны выполняются независимо от первых результатов.
|
||||
|
||||
## Что подтверждено
|
||||
|
||||
Подтверждено снижение задержки при 325 запросах/с в проверенных условиях. Рост максимальной мощности на 15% остался недоказанным. В обычный Compose добавлен `API_GOMAXPROCS`, по умолчанию 1. Обычный стенд имеет две API по 0.5 CPU; переносить на него 60–68% без отдельного измерения нельзя.
|
||||
|
||||
[Таблицы и графики](../../../evidence/grade5/RESULTS.md).
|
||||
@@ -0,0 +1,23 @@
|
||||
-- Applies only to the isolated benchmark database. Never use on the main DB.
|
||||
BEGIN;
|
||||
TRUNCATE message_idempotency, messages, chat_members, chats, users;
|
||||
INSERT INTO users
|
||||
SELECT md5('bench-user-' || i)::uuid, 'bench_user_' || i, 'Benchmark ' || i,
|
||||
decode('00','hex'), '2020-01-01T00:00:00Z'::timestamptz
|
||||
FROM generate_series(0,199) AS i;
|
||||
-- Password login is outside the workload; valid sessions are seeded in Redis.
|
||||
-- These synthetic users deliberately cannot password-login.
|
||||
INSERT INTO chats
|
||||
SELECT md5('bench-chat-' || i)::uuid, 'Benchmark chat ' || i,
|
||||
'2020-01-01T00:00:00Z'::timestamptz
|
||||
FROM generate_series(0,99) AS i;
|
||||
INSERT INTO chat_members
|
||||
SELECT md5('bench-chat-' || i)::uuid, md5('bench-user-' || (2*i+j))::uuid
|
||||
FROM generate_series(0,99) AS i CROSS JOIN generate_series(0,1) AS j;
|
||||
INSERT INTO messages
|
||||
SELECT md5('bench-message-' || i || '-' || j)::uuid,
|
||||
md5('bench-chat-' || i)::uuid, md5('bench-user-' || (2*i))::uuid,
|
||||
repeat('x',128), '2020-01-01T00:00:00Z'::timestamptz + j * interval '1 second'
|
||||
FROM generate_series(0,99) AS i CROSS JOIN generate_series(0,99) AS j;
|
||||
COMMIT;
|
||||
ANALYZE;
|
||||
@@ -0,0 +1,38 @@
|
||||
global
|
||||
log stdout format raw local0
|
||||
maxconn 1024
|
||||
defaults
|
||||
log global
|
||||
mode http
|
||||
option httplog
|
||||
timeout connect 1s
|
||||
timeout client 15s
|
||||
timeout server 12s
|
||||
timeout check 1s
|
||||
retries 0
|
||||
resolvers docker
|
||||
nameserver docker_dns 127.0.0.11:53
|
||||
accepted_payload_size 8192
|
||||
resolve_retries 3
|
||||
timeout resolve 1s
|
||||
timeout retry 1s
|
||||
hold valid 1s
|
||||
hold obsolete 1s
|
||||
hold nx 1s
|
||||
hold timeout 1s
|
||||
hold refused 1s
|
||||
hold other 1s
|
||||
frontend api_entry
|
||||
bind :8080
|
||||
default_backend api_replicas
|
||||
backend api_replicas
|
||||
balance roundrobin
|
||||
option httpchk GET /health/ready
|
||||
http-check expect status 200
|
||||
server-template api 4 api:8080 check inter 1s fall 2 rise 2 resolvers docker resolve-prefer ipv4 init-addr libc,none
|
||||
listen statistics
|
||||
bind :8404
|
||||
stats enable
|
||||
stats show-legends
|
||||
stats uri /stats
|
||||
stats refresh 2s
|
||||
@@ -0,0 +1,421 @@
|
||||
"""Open-loop HTTP experiment and concurrent one-second telemetry collection."""
|
||||
|
||||
import asyncio
|
||||
import csv
|
||||
import gzip
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import math
|
||||
import random
|
||||
import time
|
||||
from collections import Counter
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import aiohttp
|
||||
from common import (
|
||||
BASE,
|
||||
STATS,
|
||||
current_containers,
|
||||
inspect_public,
|
||||
md5uuid,
|
||||
sql,
|
||||
write_json,
|
||||
)
|
||||
|
||||
|
||||
def percentile(values, quantile):
|
||||
ordered = sorted(values)
|
||||
return (
|
||||
round(ordered[max(0, math.ceil(len(ordered) * quantile) - 1)], 3)
|
||||
if ordered
|
||||
else None
|
||||
)
|
||||
|
||||
|
||||
async def wait_ready(replicas):
|
||||
async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=3)) as session:
|
||||
for _ in range(100):
|
||||
try:
|
||||
async with session.get(STATS) as response:
|
||||
rows = csv.DictReader(
|
||||
io.StringIO((await response.text()).removeprefix("# "))
|
||||
)
|
||||
count = sum(
|
||||
row["pxname"] == "api_replicas"
|
||||
and row["svname"].startswith("api")
|
||||
and row["status"].startswith("UP")
|
||||
for row in rows
|
||||
)
|
||||
if count == replicas:
|
||||
return
|
||||
except (aiohttp.ClientError, TimeoutError):
|
||||
pass
|
||||
await asyncio.sleep(0.1)
|
||||
raise RuntimeError("Not all expected replicas are ready in HAProxy")
|
||||
|
||||
|
||||
async def load(actors, *, rate, duration, seed, prefix, limit=512):
|
||||
rows, pending = [], set()
|
||||
rng = random.Random(seed)
|
||||
timeout = aiohttp.ClientTimeout(total=5, ceil_threshold=10)
|
||||
connector = aiohttp.TCPConnector(limit=limit, limit_per_host=limit)
|
||||
started = time.monotonic() + 0.05
|
||||
cpu_started = time.process_time()
|
||||
wall_started = time.time()
|
||||
|
||||
async with aiohttp.ClientSession(connector=connector, timeout=timeout) as session:
|
||||
|
||||
async def request(index, scheduled, chat_index, user_index):
|
||||
begin = time.monotonic()
|
||||
kind = "read" if index % 5 == 4 else "write"
|
||||
chat_id = md5uuid("bench-chat-" + str(chat_index))
|
||||
actor = actors[2 * chat_index + user_index]
|
||||
key = hashlib.sha256(f"{prefix}:{index}".encode()).hexdigest()
|
||||
text = key + "x" * 64
|
||||
row = {
|
||||
"index": index,
|
||||
"kind": kind,
|
||||
"scheduled_s": round(scheduled - started, 6),
|
||||
"start_s": round(begin - started, 6),
|
||||
"chat_id": chat_id,
|
||||
"sender_id": actor["id"],
|
||||
"key": key if kind == "write" else None,
|
||||
}
|
||||
try:
|
||||
kwargs = {"headers": {"Authorization": "Bearer " + actor["token"]}}
|
||||
method = "GET"
|
||||
path = f"/api/v1/chats/{chat_id}/messages?limit=50"
|
||||
if kind == "write":
|
||||
method, path = "POST", path.split("?")[0]
|
||||
kwargs["headers"]["Idempotency-Key"] = key
|
||||
kwargs["json"] = {"text": text}
|
||||
async with session.request(method, BASE + path, **kwargs) as response:
|
||||
body = await response.read()
|
||||
row.update(
|
||||
status=response.status,
|
||||
instance=response.headers.get("X-Instance-Id"),
|
||||
)
|
||||
expected = 201 if kind == "write" else 200
|
||||
row["success"] = response.status == expected
|
||||
if row["success"]:
|
||||
payload = json.loads(body)
|
||||
valid = bool(
|
||||
row["instance"] and response.headers.get("X-Request-Id")
|
||||
)
|
||||
if kind == "write":
|
||||
valid = (
|
||||
valid
|
||||
and payload.get("chat_id") == chat_id
|
||||
and payload.get("sender_id") == actor["id"]
|
||||
and payload.get("text") == text
|
||||
)
|
||||
row["message_id"] = payload.get("id")
|
||||
valid = valid and bool(row["message_id"])
|
||||
else:
|
||||
valid = (
|
||||
valid
|
||||
and isinstance(payload.get("items"), list)
|
||||
and len(payload["items"]) <= 50
|
||||
)
|
||||
if not valid:
|
||||
row.update(success=False, error="invalid_response")
|
||||
except (aiohttp.ClientError, TimeoutError, ValueError) as error:
|
||||
row.update(success=False, error=type(error).__name__)
|
||||
end = time.monotonic()
|
||||
row.update(
|
||||
end_s=round(end - started, 6),
|
||||
latency_ms=1000 * (end - scheduled),
|
||||
http_ms=1000 * (end - begin),
|
||||
dispatch_lag_ms=1000 * (begin - scheduled),
|
||||
)
|
||||
rows.append(row)
|
||||
|
||||
for index in range(round(rate * duration)):
|
||||
scheduled = started + index / rate
|
||||
delay = scheduled - time.monotonic()
|
||||
if delay > 0:
|
||||
await asyncio.sleep(delay)
|
||||
elif index % 50 == 0:
|
||||
await asyncio.sleep(0)
|
||||
chat_index, user_index = rng.randrange(100), rng.randrange(2)
|
||||
if len(pending) >= limit:
|
||||
rows.append(
|
||||
{
|
||||
"index": index,
|
||||
"kind": "read" if index % 5 == 4 else "write",
|
||||
"scheduled_s": index / rate,
|
||||
"success": False,
|
||||
"error": "generator_inflight_limit",
|
||||
}
|
||||
)
|
||||
continue
|
||||
task = asyncio.create_task(
|
||||
request(index, scheduled, chat_index, user_index)
|
||||
)
|
||||
pending.add(task)
|
||||
task.add_done_callback(pending.discard)
|
||||
if pending:
|
||||
await asyncio.gather(*pending)
|
||||
elapsed = time.monotonic() - started
|
||||
successes = [row for row in rows if row["success"]]
|
||||
sent = [row for row in rows if "start_s" in row]
|
||||
summary = {
|
||||
"scheduled": len(rows),
|
||||
"sent": len(sent),
|
||||
"successes": len(successes),
|
||||
"errors": len(rows) - len(successes),
|
||||
"success_ratio": len(successes) / len(rows),
|
||||
"requested_rps": rate,
|
||||
"duration_s": duration,
|
||||
"completion_elapsed_s": elapsed,
|
||||
"goodput_rps": len(successes) / duration,
|
||||
"window_goodput_rps": sum(row["end_s"] <= duration for row in successes)
|
||||
/ duration,
|
||||
"completion_goodput_rps": len(successes) / max(0.001, elapsed),
|
||||
"achieved_send_rps": len(sent) / duration,
|
||||
"p50_ms": percentile([row["latency_ms"] for row in successes], 0.5),
|
||||
"p95_ms": percentile([row["latency_ms"] for row in successes], 0.95),
|
||||
"p99_ms": percentile([row["latency_ms"] for row in successes], 0.99),
|
||||
"dispatch_p95_ms": percentile([row["dispatch_lag_ms"] for row in sent], 0.95),
|
||||
"http_p95_ms": percentile([row["http_ms"] for row in successes], 0.95),
|
||||
"generator_dropped": len(rows) - len(sent),
|
||||
"errors_by_type": dict(
|
||||
Counter(
|
||||
str(row.get("status", row.get("error")))
|
||||
for row in rows
|
||||
if not row["success"]
|
||||
)
|
||||
),
|
||||
"instances": dict(Counter(row["instance"] for row in successes)),
|
||||
"generator_cpu_cores": (time.process_time() - cpu_started)
|
||||
/ max(0.001, elapsed),
|
||||
"started_utc": datetime.fromtimestamp(wall_started, timezone.utc).isoformat(),
|
||||
}
|
||||
return rows, summary
|
||||
|
||||
|
||||
DB_SAMPLE = """SELECT json_build_object(
|
||||
'active', (SELECT count(*) FROM pg_stat_activity WHERE datname='benchmark' AND state='active' AND pid<>pg_backend_pid()),
|
||||
'waits', (SELECT coalesce(json_agg(json_build_object('event_type',wait_event_type,'event',wait_event,'count',n)), '[]'::json)
|
||||
FROM (SELECT wait_event_type,wait_event,count(*) n FROM pg_stat_activity WHERE datname='benchmark' AND pid<>pg_backend_pid() GROUP BY 1,2) t),
|
||||
'database', (SELECT row_to_json(d) FROM (SELECT xact_commit,xact_rollback,blks_read,blks_hit,tup_returned,tup_fetched,tup_inserted,deadlocks FROM pg_stat_database WHERE datname='benchmark') d)
|
||||
);"""
|
||||
|
||||
|
||||
async def sample_db(container):
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
"docker",
|
||||
"exec",
|
||||
"-i",
|
||||
container,
|
||||
"psql",
|
||||
"-X",
|
||||
"-q",
|
||||
"-t",
|
||||
"-A",
|
||||
"-v",
|
||||
"ON_ERROR_STOP=1",
|
||||
"-U",
|
||||
"benchmark",
|
||||
"-d",
|
||||
"benchmark",
|
||||
stdin=asyncio.subprocess.PIPE,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
stdout, _ = await proc.communicate(DB_SAMPLE.encode())
|
||||
if proc.returncode:
|
||||
raise RuntimeError("DB telemetry unavailable")
|
||||
return json.loads(stdout)
|
||||
|
||||
|
||||
async def collect(stop, containers, rows):
|
||||
db = next(row["id"] for row in containers if row["service"] == "db")
|
||||
connector = aiohttp.UnixConnector(path="/var/run/docker.sock")
|
||||
async with (
|
||||
aiohttp.ClientSession(
|
||||
connector=connector, timeout=aiohttp.ClientTimeout(total=4)
|
||||
) as engine,
|
||||
aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=4)) as http,
|
||||
):
|
||||
|
||||
async def container_stats(container):
|
||||
async with engine.get(
|
||||
f"http://docker/v1.47/containers/{container['id']}/stats?stream=false&one-shot=true"
|
||||
) as response:
|
||||
data = await response.json()
|
||||
return {
|
||||
"service": container["service"],
|
||||
"instance": container["instance"],
|
||||
"cpu_stats": data.get("cpu_stats"),
|
||||
"memory_stats": data.get("memory_stats"),
|
||||
"blkio_stats": data.get("blkio_stats"),
|
||||
}
|
||||
|
||||
while not stop.is_set():
|
||||
begin = time.monotonic()
|
||||
try:
|
||||
resources, database = await asyncio.gather(
|
||||
asyncio.gather(
|
||||
*(container_stats(container) for container in containers)
|
||||
),
|
||||
sample_db(db),
|
||||
)
|
||||
haproxy, stats_error = [], None
|
||||
try:
|
||||
async with http.get(STATS) as response:
|
||||
entries = csv.DictReader(
|
||||
io.StringIO((await response.text()).removeprefix("# "))
|
||||
)
|
||||
haproxy = [
|
||||
{
|
||||
key: row.get(key)
|
||||
for key in (
|
||||
"pxname",
|
||||
"svname",
|
||||
"status",
|
||||
"scur",
|
||||
"qcur",
|
||||
"qmax",
|
||||
"econ",
|
||||
"eresp",
|
||||
"stot",
|
||||
"addr",
|
||||
"check_duration",
|
||||
)
|
||||
}
|
||||
for row in entries
|
||||
if row["pxname"] in ("api_replicas", "api_entry")
|
||||
]
|
||||
except (aiohttp.ClientError, TimeoutError) as error:
|
||||
# Target stats may be unavailable under overload: that is a
|
||||
# system observation, not grounds to discard poor throughput.
|
||||
stats_error = type(error).__name__
|
||||
# /proc/stat and process_time are raw inputs for CPU diagnostics.
|
||||
with open("/proc/stat") as file:
|
||||
host_cpu = file.readline().strip()
|
||||
rows.append(
|
||||
{
|
||||
"time": datetime.now(timezone.utc).isoformat(),
|
||||
"resources": resources,
|
||||
"postgres": database,
|
||||
"haproxy": haproxy,
|
||||
"host_cpu": host_cpu,
|
||||
"haproxy_stats_error": stats_error,
|
||||
"generator_cpu_seconds": time.process_time(),
|
||||
"collection_seconds": time.monotonic() - begin,
|
||||
}
|
||||
)
|
||||
except Exception as error:
|
||||
rows.append(
|
||||
{
|
||||
"time": datetime.now(timezone.utc).isoformat(),
|
||||
"error": type(error).__name__,
|
||||
}
|
||||
)
|
||||
try:
|
||||
await asyncio.wait_for(
|
||||
stop.wait(), timeout=max(0.01, 1 - (time.monotonic() - begin))
|
||||
)
|
||||
except TimeoutError:
|
||||
pass
|
||||
|
||||
|
||||
def verify_confirmed(rows):
|
||||
successful = [row for row in rows if row["kind"] == "write" and row["success"]]
|
||||
statement = "CREATE TEMP TABLE expected(id uuid,chat_id uuid,sender_id uuid,key text);\nCOPY expected FROM STDIN;\n"
|
||||
statement += "".join(
|
||||
"\t".join((row["message_id"], row["chat_id"], row["sender_id"], row["key"]))
|
||||
+ "\n"
|
||||
for row in successful
|
||||
)
|
||||
statement += "\\.\nSELECT json_build_object('expected',count(*),'matched',count(m.id),'linked',count(i.message_id)) FROM expected e LEFT JOIN messages m ON m.id=e.id AND m.chat_id=e.chat_id AND m.sender_id=e.sender_id AND m.text=e.key || repeat('x',64) LEFT JOIN message_idempotency i ON i.message_id=e.id AND i.sender_id=e.sender_id AND i.chat_id=e.chat_id AND i.key=e.key;"
|
||||
check = json.loads(sql(statement))
|
||||
check["passed"] = check["expected"] == check["matched"] == check["linked"]
|
||||
return check
|
||||
|
||||
|
||||
async def measure(
|
||||
actors, directory, config, *, rate, duration, seed, prefix, warmup=15, limit=512
|
||||
):
|
||||
await wait_ready(config["replicas"])
|
||||
warm_rows, warm_summary = await load(
|
||||
actors,
|
||||
rate=25,
|
||||
duration=warmup,
|
||||
seed=seed,
|
||||
prefix=prefix + "-warm",
|
||||
limit=limit,
|
||||
)
|
||||
write_json(directory / "warmup.json", warm_summary)
|
||||
with gzip.open(
|
||||
directory / "warmup-requests.jsonl.gz", "wt", encoding="utf-8"
|
||||
) as file:
|
||||
for row in warm_rows:
|
||||
file.write(json.dumps(row, separators=(",", ":")) + "\n")
|
||||
containers = current_containers()
|
||||
stop, samples = asyncio.Event(), []
|
||||
collection = asyncio.create_task(collect(stop, containers, samples))
|
||||
started_utc = datetime.now(timezone.utc).isoformat()
|
||||
try:
|
||||
rows, summary = await load(
|
||||
actors, rate=rate, duration=duration, seed=seed, prefix=prefix, limit=limit
|
||||
)
|
||||
finally:
|
||||
stop.set()
|
||||
await collection
|
||||
for name, values in (("requests", rows), ("telemetry", samples)):
|
||||
with gzip.open(
|
||||
directory / (name + ".jsonl.gz"), "wt", encoding="utf-8"
|
||||
) as file:
|
||||
for row in values:
|
||||
file.write(json.dumps(row, separators=(",", ":")) + "\n")
|
||||
pools = []
|
||||
for container in containers:
|
||||
if container["service"] == "api":
|
||||
# Go log output uses stderr; gather both without exposing other env.
|
||||
import subprocess
|
||||
|
||||
result = subprocess.run(
|
||||
["docker", "logs", "--since", started_utc, container["id"]],
|
||||
check=False,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
)
|
||||
for line in (result.stdout + result.stderr).splitlines():
|
||||
if "benchmark_pool " in line:
|
||||
value = json.loads(line.split("benchmark_pool ", 1)[1])
|
||||
value["instance"] = container["instance"]
|
||||
pools.append(value)
|
||||
write_json(directory / "pool.json", pools)
|
||||
summary["pool_max_by_instance"] = {row["instance"]: row["max"] for row in pools}
|
||||
summary["gomaxprocs_by_instance"] = {
|
||||
row["instance"]: row.get("gomaxprocs") for row in pools
|
||||
}
|
||||
summary["correctness"] = verify_confirmed(rows)
|
||||
summary["telemetry_samples"] = len(samples)
|
||||
summary["telemetry_errors"] = sum("error" in row for row in samples)
|
||||
summary["haproxy_stats_errors"] = sum(
|
||||
bool(row.get("haproxy_stats_error")) for row in samples
|
||||
)
|
||||
summary["containers_after"] = [
|
||||
dict(inspect_public(container["id"]), service=container["service"])
|
||||
for container in containers
|
||||
]
|
||||
cpu_limited = summary["generator_cpu_cores"] >= 0.85
|
||||
summary["generator_limited"] = summary["generator_dropped"] / summary[
|
||||
"scheduled"
|
||||
] > 0.01 or (summary["dispatch_p95_ms"] > 100 and cpu_limited)
|
||||
summary["valid"] = (
|
||||
summary["telemetry_errors"] == 0 and not summary["generator_limited"]
|
||||
)
|
||||
summary["slo_pass"] = (
|
||||
summary["valid"]
|
||||
and summary["correctness"]["passed"]
|
||||
and summary["success_ratio"] >= 0.99
|
||||
and summary["p95_ms"] is not None
|
||||
and summary["p95_ms"] <= 500
|
||||
)
|
||||
write_json(directory / "summary.json", summary)
|
||||
return summary
|
||||
@@ -0,0 +1,160 @@
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
root = Path(__file__).resolve().parents[3]
|
||||
ev = root / "evidence/grade5"
|
||||
|
||||
|
||||
def save(path, data):
|
||||
path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n")
|
||||
|
||||
|
||||
def data(series):
|
||||
return json.loads((ev / series / "analysis.json").read_text())
|
||||
|
||||
|
||||
def decide_hi(series="improvement-01", hypothesis="HI"):
|
||||
a = data(series)
|
||||
pairs = []
|
||||
for repeat in (1, 2, 3):
|
||||
rows = {r["config"]: r for r in a["runs"] if r["repeat"] == repeat}
|
||||
c, t = rows["I0"], rows["I1"]
|
||||
valid = all(r["valid"] and r["correctness"]["passed"] for r in (c, t))
|
||||
ratio = t["p95_ms"] / c["p95_ms"]
|
||||
passed = (
|
||||
valid
|
||||
and ratio <= 0.85
|
||||
and t["success_ratio"] >= max(0.99, c["success_ratio"])
|
||||
and t["p95_ms"] <= 500
|
||||
)
|
||||
pairs.append(
|
||||
{
|
||||
"repeat": repeat,
|
||||
"control_p95_ms": c["p95_ms"],
|
||||
"tuned_p95_ms": t["p95_ms"],
|
||||
"p95_reduction_percent": 100 * (1 - ratio),
|
||||
"control_success_ratio": c["success_ratio"],
|
||||
"tuned_success_ratio": t["success_ratio"],
|
||||
"valid": valid,
|
||||
"criteria_met": passed,
|
||||
}
|
||||
)
|
||||
result = (
|
||||
"supported"
|
||||
if all(p["criteria_met"] for p in pairs)
|
||||
else (
|
||||
"refuted"
|
||||
if all(p["valid"] and not p["criteria_met"] for p in pairs)
|
||||
else "inconclusive"
|
||||
)
|
||||
)
|
||||
save(
|
||||
ev / series / "decision.json",
|
||||
{"hypothesis": hypothesis, "result": result, "pairs": pairs},
|
||||
)
|
||||
|
||||
|
||||
def decide_hc(series="capacity-improvement-01"):
|
||||
a = data(series)
|
||||
assert len(a["runs"]) == 12
|
||||
pairs = []
|
||||
for repeat in (1, 2, 3):
|
||||
caps = {r["config"]: r for r in a["capacities"] if r["repeat"] == repeat}
|
||||
c, t = caps["I0"], caps["I1"]
|
||||
rows = [r for r in a["runs"] if r["repeat"] == repeat]
|
||||
valid = all(
|
||||
r["valid"] and r["correctness"]["passed"] for r in rows
|
||||
) and not any(r["nonmonotonic"] for r in (c, t))
|
||||
lower = (
|
||||
t["capacity_lower"] / c["capacity_upper"] if c["capacity_upper"] else None
|
||||
)
|
||||
upper = (
|
||||
t["capacity_upper"] / c["capacity_lower"]
|
||||
if t["capacity_upper"] and c["capacity_lower"]
|
||||
else None
|
||||
)
|
||||
outcome = "inconclusive"
|
||||
if valid and lower is not None and lower >= 1.15:
|
||||
outcome = "supported"
|
||||
elif valid and upper is not None and upper < 1.15:
|
||||
outcome = "refuted"
|
||||
pairs.append(
|
||||
{
|
||||
"repeat": repeat,
|
||||
"control": c,
|
||||
"tuned": t,
|
||||
"ratio_lower_bound": lower,
|
||||
"ratio_upper_bound": upper,
|
||||
"valid": valid,
|
||||
"decision": outcome,
|
||||
}
|
||||
)
|
||||
outcomes = [p["decision"] for p in pairs]
|
||||
result = outcomes[0] if len(set(outcomes)) == 1 else "inconclusive"
|
||||
save(
|
||||
ev / series / "decision.json",
|
||||
{
|
||||
"hypothesis": "HC",
|
||||
"result": result,
|
||||
"blocks": pairs,
|
||||
"note": "Finite-grid bounds, not confidence intervals.",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def audit(series):
|
||||
directory = ev / series
|
||||
protocol = json.loads((directory / "protocol.json").read_text())
|
||||
summaries = list(directory.glob("*/summary.json"))
|
||||
expected = (
|
||||
len(protocol["configs"]) * len(protocol["rates"]) * len(protocol["order_seeds"])
|
||||
)
|
||||
assert len(summaries) == expected
|
||||
s = [json.loads(p.read_text()) for p in summaries]
|
||||
protocol_sha = hashlib.sha256(
|
||||
(directory / "protocol.json").read_bytes()
|
||||
).hexdigest()
|
||||
assert protocol_sha == (directory / "protocol.sha256").read_text().split()[0]
|
||||
for p in summaries:
|
||||
m = json.loads(p.with_name("manifest.json").read_text())
|
||||
assert m["protocol_sha256"] == protocol_sha
|
||||
assert m["code_sha256"] == protocol["code_sha256"]
|
||||
assert m["instrument_sha256"] == protocol["instrument_sha256"]
|
||||
save(
|
||||
directory / "audit.json",
|
||||
{
|
||||
"planned_runs": expected,
|
||||
"completed_runs": len(s),
|
||||
"valid_runs": sum(r["valid"] for r in s),
|
||||
"slo_passing_runs": sum(r["slo_pass"] for r in s),
|
||||
"confirmed_writes_checked": sum(r["correctness"]["expected"] for r in s),
|
||||
"all_confirmed_writes_preserved": all(
|
||||
r["correctness"]["passed"] for r in s
|
||||
),
|
||||
"generator_dropped": sum(r["generator_dropped"] for r in s),
|
||||
"oom_container_observations": sum(
|
||||
c["oom"] for r in s for c in r["containers_after"]
|
||||
),
|
||||
"protocol_sha256": protocol_sha,
|
||||
"source_archive_sha256": hashlib.sha256(
|
||||
(directory / "source.tar.gz").read_bytes()
|
||||
).hexdigest(),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import argparse
|
||||
|
||||
parser = argparse.ArgumentParser(
|
||||
"Audit saved runs and apply preregistered decision rules"
|
||||
)
|
||||
parser.add_argument("mode", choices=("audit", "hi", "hc", "hl"))
|
||||
parser.add_argument("series")
|
||||
args = parser.parse_args()
|
||||
if args.mode in ("hi", "hl"):
|
||||
decide_hi(args.series, args.mode.upper())
|
||||
elif args.mode == "hc":
|
||||
decide_hc(args.series)
|
||||
audit(args.series)
|
||||
@@ -0,0 +1,45 @@
|
||||
import argparse
|
||||
import json
|
||||
import statistics
|
||||
from pathlib import Path
|
||||
|
||||
import matplotlib
|
||||
|
||||
matplotlib.use("Agg")
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
parser = argparse.ArgumentParser(__doc__)
|
||||
parser.add_argument("series")
|
||||
args = parser.parse_args()
|
||||
directory = Path(__file__).resolve().parents[3] / "evidence/grade5" / args.series
|
||||
runs = json.loads(directory.joinpath("analysis.json").read_text())["runs"]
|
||||
assert len({r["rate"] for r in runs}) == 1, "Use a fixed-rate study"
|
||||
figure, ax = plt.subplots(figsize=(8, 4.5), layout="constrained")
|
||||
groups = [[r["p95_ms"] for r in runs if r["config"] == c] for c in ("I0", "I1")]
|
||||
ax.bar(
|
||||
[0, 1],
|
||||
[statistics.median(g) for g in groups],
|
||||
color=["#0072B2", "#D55E00"],
|
||||
alpha=0.25,
|
||||
width=0.5,
|
||||
)
|
||||
for repeat, color in zip(
|
||||
sorted({r["repeat"] for r in runs}), ("#0072B2", "#009E73", "#CC79A7")
|
||||
):
|
||||
pair = {r["config"]: r for r in runs if r["repeat"] == repeat}
|
||||
ax.plot(
|
||||
[0, 1],
|
||||
[pair[c]["p95_ms"] for c in ("I0", "I1")],
|
||||
"o-",
|
||||
color=color,
|
||||
label=f"Repeat {repeat}",
|
||||
)
|
||||
ax.set_xticks([0, 1], ["Control: GOMAXPROCS=16", "Tuned: GOMAXPROCS=1"])
|
||||
ax.set_ylim(bottom=0)
|
||||
ax.set_ylabel("p95 full latency of successful responses (ms)")
|
||||
rate = runs[0]["rate"]
|
||||
ax.set_title(f"Paired repetitions at {rate} requests/s; bars show medians")
|
||||
ax.grid(axis="y", alpha=0.25)
|
||||
ax.legend()
|
||||
figure.savefig(directory / "latency-pairs.png", dpi=160)
|
||||
plt.close(figure)
|
||||
@@ -0,0 +1,51 @@
|
||||
{
|
||||
"version": "1.1",
|
||||
"hypotheses": {
|
||||
"H1": "fixed-budget C4/C1 < 1.20",
|
||||
"H2": "growing-budget C4/C1 >= 1.50"
|
||||
},
|
||||
"configs": [
|
||||
"A1",
|
||||
"A2",
|
||||
"A4",
|
||||
"B1",
|
||||
"B2",
|
||||
"B4"
|
||||
],
|
||||
"rates": [
|
||||
100,
|
||||
200,
|
||||
250,
|
||||
300,
|
||||
400,
|
||||
500,
|
||||
800
|
||||
],
|
||||
"duration_s": 30,
|
||||
"warmup_s": 15,
|
||||
"cooldown_s": 10,
|
||||
"inflight_limit": 8192,
|
||||
"workload_seed": 230300,
|
||||
"order_seeds": [
|
||||
230301,
|
||||
230302,
|
||||
230303
|
||||
],
|
||||
"success_min": 0.99,
|
||||
"p95_max_ms": 500,
|
||||
"cpu_db": 1,
|
||||
"cpu_redis": 0.25,
|
||||
"cpu_haproxy": 0.5,
|
||||
"pool_total": 12,
|
||||
"api_reset_each_point": true,
|
||||
"code_sha256": "0248ad2dcc718997f00304e14d34ae0819630fce68e298549a13667e022e9be2",
|
||||
"instrument_sha256": "f70c75276e0f2b1880fec9afbae460fd6ac38f8d9a5aea6804b921092c57a944",
|
||||
"human_protocol_sha256": "e38b98e6cc44b603ce4a446665146695a9fa85c9090e0a7f2ded3160af9385ed",
|
||||
"pilot_exclusion": [
|
||||
"pilot-01",
|
||||
"pilot-02",
|
||||
"pilot-03"
|
||||
],
|
||||
"source_series": "baseline-01",
|
||||
"revision_reason": "Directory cleanup and removal of unused helpers; hypotheses, thresholds, workload and order unchanged."
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"version": "pilot-0.1",
|
||||
"configs": [
|
||||
"A1",
|
||||
"A4",
|
||||
"B1",
|
||||
"B4"
|
||||
],
|
||||
"rates": [
|
||||
100,
|
||||
400,
|
||||
800,
|
||||
1600
|
||||
],
|
||||
"duration_s": 10,
|
||||
"warmup_s": 15,
|
||||
"cooldown_s": 5,
|
||||
"inflight_limit": 512,
|
||||
"workload_seed": 230300,
|
||||
"order_seeds": [
|
||||
230301
|
||||
],
|
||||
"note": "Exploratory pilot only; excluded from hypothesis confirmation. Main duration remains 30s pending instrument checks."
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"version": "pilot-0.2",
|
||||
"configs": [
|
||||
"A1",
|
||||
"A4",
|
||||
"B1",
|
||||
"B4"
|
||||
],
|
||||
"rates": [
|
||||
250,
|
||||
500,
|
||||
1000
|
||||
],
|
||||
"duration_s": 10,
|
||||
"warmup_s": 15,
|
||||
"cooldown_s": 5,
|
||||
"inflight_limit": 8192,
|
||||
"workload_seed": 230300,
|
||||
"order_seeds": [
|
||||
230301
|
||||
],
|
||||
"note": "Validate larger client inflight budget without changing H1/H2 or SLO. Retain pilot-01 separately. Main runs remain 30 seconds."
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"version": "pilot-0.3",
|
||||
"configs": [
|
||||
"A4"
|
||||
],
|
||||
"rates": [
|
||||
800
|
||||
],
|
||||
"duration_s": 30,
|
||||
"warmup_s": 15,
|
||||
"cooldown_s": 0,
|
||||
"inflight_limit": 8192,
|
||||
"workload_seed": 230300,
|
||||
"order_seeds": [
|
||||
230301
|
||||
],
|
||||
"note": "Final measurement-instrument validation at the proposed main upper rate and full duration; excluded from H1/H2."
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
{
|
||||
"version": "improvement-1.1",
|
||||
"hypotheses": {
|
||||
"HI": "At 400 req/s p95(I1)/p95(I0) <= 0.85 in all 3 pairs; I1 success >= 0.99 and >= I0; I1 p95 <= 500 ms; confirmed writes preserved"
|
||||
},
|
||||
"configs": [
|
||||
"I0",
|
||||
"I1"
|
||||
],
|
||||
"rates": [
|
||||
400
|
||||
],
|
||||
"duration_s": 30,
|
||||
"warmup_s": 15,
|
||||
"cooldown_s": 10,
|
||||
"inflight_limit": 8192,
|
||||
"workload_seed": 230300,
|
||||
"order_seeds": [
|
||||
230401,
|
||||
230402,
|
||||
230403
|
||||
],
|
||||
"success_min": 0.99,
|
||||
"p95_max_ms": 500,
|
||||
"cpu_db": 1,
|
||||
"cpu_redis": 0.25,
|
||||
"cpu_haproxy": 0.5,
|
||||
"pool_total": 12,
|
||||
"api_reset_each_point": true,
|
||||
"code_sha256": "0248ad2dcc718997f00304e14d34ae0819630fce68e298549a13667e022e9be2",
|
||||
"instrument_sha256": "f70c75276e0f2b1880fec9afbae460fd6ac38f8d9a5aea6804b921092c57a944",
|
||||
"pilot_exclusion": [
|
||||
"pilot-01",
|
||||
"pilot-02",
|
||||
"pilot-03"
|
||||
],
|
||||
"config_bases": {
|
||||
"I0": "A4",
|
||||
"I1": "A4"
|
||||
},
|
||||
"config_overrides": {
|
||||
"I1": {
|
||||
"gomaxprocs": 1
|
||||
}
|
||||
},
|
||||
"human_protocol_sha256": "fddbc8da79990294069b7f6006709bfa4ccbfca9a3c71ff876807606459bfddb",
|
||||
"source_series": "improvement-01",
|
||||
"revision_reason": "Directory cleanup and removal of unused helpers; hypotheses, thresholds, workload and order unchanged."
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
{
|
||||
"version": "capacity-improvement-1.1",
|
||||
"hypotheses": {
|
||||
"HC": "C(I1)/C(I0) >=1.15, conservative lower grid bound in all 3 new blocks"
|
||||
},
|
||||
"configs": [
|
||||
"I0",
|
||||
"I1"
|
||||
],
|
||||
"rates": [
|
||||
325,
|
||||
375
|
||||
],
|
||||
"duration_s": 30,
|
||||
"warmup_s": 15,
|
||||
"cooldown_s": 10,
|
||||
"inflight_limit": 8192,
|
||||
"workload_seed": 230300,
|
||||
"order_seeds": [
|
||||
230501,
|
||||
230502,
|
||||
230503
|
||||
],
|
||||
"success_min": 0.99,
|
||||
"p95_max_ms": 500,
|
||||
"cpu_db": 1,
|
||||
"cpu_redis": 0.25,
|
||||
"cpu_haproxy": 0.5,
|
||||
"pool_total": 12,
|
||||
"api_reset_each_point": true,
|
||||
"code_sha256": "0248ad2dcc718997f00304e14d34ae0819630fce68e298549a13667e022e9be2",
|
||||
"instrument_sha256": "f70c75276e0f2b1880fec9afbae460fd6ac38f8d9a5aea6804b921092c57a944",
|
||||
"pilot_exclusion": [
|
||||
"pilot-01",
|
||||
"pilot-02",
|
||||
"pilot-03"
|
||||
],
|
||||
"config_bases": {
|
||||
"I0": "A4",
|
||||
"I1": "A4"
|
||||
},
|
||||
"config_overrides": {
|
||||
"I1": {
|
||||
"gomaxprocs": 1
|
||||
}
|
||||
},
|
||||
"human_protocol_sha256": "fddbc8da79990294069b7f6006709bfa4ccbfca9a3c71ff876807606459bfddb",
|
||||
"source_series": "capacity-improvement-01",
|
||||
"revision_reason": "Directory cleanup and removal of unused helpers; hypotheses, thresholds, workload and order unchanged."
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
{
|
||||
"version": "latency-improvement-1.1",
|
||||
"hypotheses": {
|
||||
"HL": "At 325 req/s p95(I1)/p95(I0) <=0.85 in all 3 new pairs, I1 success>=0.99 and >=I0, p95<=500 ms, confirmed writes preserved"
|
||||
},
|
||||
"configs": [
|
||||
"I0",
|
||||
"I1"
|
||||
],
|
||||
"rates": [
|
||||
325
|
||||
],
|
||||
"duration_s": 30,
|
||||
"warmup_s": 15,
|
||||
"cooldown_s": 10,
|
||||
"inflight_limit": 8192,
|
||||
"workload_seed": 230300,
|
||||
"order_seeds": [
|
||||
230601,
|
||||
230602,
|
||||
230603
|
||||
],
|
||||
"success_min": 0.99,
|
||||
"p95_max_ms": 500,
|
||||
"cpu_db": 1,
|
||||
"cpu_redis": 0.25,
|
||||
"cpu_haproxy": 0.5,
|
||||
"pool_total": 12,
|
||||
"api_reset_each_point": true,
|
||||
"code_sha256": "0248ad2dcc718997f00304e14d34ae0819630fce68e298549a13667e022e9be2",
|
||||
"instrument_sha256": "f70c75276e0f2b1880fec9afbae460fd6ac38f8d9a5aea6804b921092c57a944",
|
||||
"pilot_exclusion": [
|
||||
"pilot-01",
|
||||
"pilot-02",
|
||||
"pilot-03"
|
||||
],
|
||||
"config_bases": {
|
||||
"I0": "A4",
|
||||
"I1": "A4"
|
||||
},
|
||||
"config_overrides": {
|
||||
"I1": {
|
||||
"gomaxprocs": 1
|
||||
}
|
||||
},
|
||||
"human_protocol_sha256": "fddbc8da79990294069b7f6006709bfa4ccbfca9a3c71ff876807606459bfddb",
|
||||
"source_series": "latency-improvement-01",
|
||||
"revision_reason": "Directory cleanup and removal of unused helpers; hypotheses, thresholds, workload and order unchanged."
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
aiohappyeyeballs==2.7.1
|
||||
aiohttp==3.12.15
|
||||
aiosignal==1.4.0
|
||||
attrs==26.1.0
|
||||
contourpy==1.3.3
|
||||
cycler==0.12.1
|
||||
fonttools==4.66.1
|
||||
frozenlist==1.8.0
|
||||
idna==3.20
|
||||
kiwisolver==1.5.1
|
||||
matplotlib==3.9.2
|
||||
multidict==6.9.1
|
||||
numpy==1.26.4
|
||||
packaging==26.3
|
||||
pillow==12.3.0
|
||||
propcache==0.5.4
|
||||
pyparsing==3.3.3
|
||||
python-dateutil==2.9.0.post0
|
||||
six==1.17.0
|
||||
typing_extensions==4.16.0
|
||||
yarl==1.25.1
|
||||
@@ -0,0 +1,254 @@
|
||||
import argparse
|
||||
import asyncio
|
||||
import fcntl
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import random
|
||||
import sys
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from common import (
|
||||
CONFIGS,
|
||||
EVIDENCE,
|
||||
HERE,
|
||||
PRIVATE,
|
||||
ROOT,
|
||||
code_hash,
|
||||
compose,
|
||||
current_containers,
|
||||
instrument_hash,
|
||||
prepare_private,
|
||||
restore_fixture,
|
||||
shell,
|
||||
write_json,
|
||||
)
|
||||
from load import measure
|
||||
|
||||
|
||||
def protocol_hash(protocol):
|
||||
return hashlib.sha256(
|
||||
(json.dumps(protocol, ensure_ascii=False, indent=2) + "\n").encode()
|
||||
).hexdigest()
|
||||
|
||||
|
||||
def main_compose(args):
|
||||
return shell(
|
||||
[
|
||||
"docker",
|
||||
"compose",
|
||||
"--project-name",
|
||||
"highload-lab3",
|
||||
"--env-file",
|
||||
".env",
|
||||
"-f",
|
||||
"compose.yml",
|
||||
*args,
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def setup():
|
||||
prepare_private()
|
||||
main_ids = main_compose(["ps", "-q"]).split()
|
||||
# Preserve the original state so completion/error restores only our main app.
|
||||
if not PRIVATE.joinpath("original-state.json").exists():
|
||||
write_json(PRIVATE / "original-state.json", {"was_running": bool(main_ids)})
|
||||
main_compose(["stop"])
|
||||
compose(["up", "-d", "--wait"])
|
||||
write_json(
|
||||
EVIDENCE / "environment.json",
|
||||
{
|
||||
"time": datetime.now(timezone.utc).isoformat(),
|
||||
"platform": platform.platform(),
|
||||
"python": sys.version,
|
||||
"cpu_count_wsl": os.cpu_count(),
|
||||
"docker": shell(["docker", "version", "--format", "{{json .Server}}"]),
|
||||
"docker_resources": shell(
|
||||
["docker", "info", "--format", "{{.NCPU}} {{.MemTotal}}"]
|
||||
),
|
||||
"compose": shell(["docker", "compose", "version"]),
|
||||
"git_commit": shell(["git", "rev-parse", "HEAD"]),
|
||||
"code_sha256": code_hash(),
|
||||
"fixture_sha256": hashlib.sha256(
|
||||
HERE.joinpath("fixture.sql").read_bytes()
|
||||
).hexdigest(),
|
||||
"dependencies": shell([sys.executable, "-m", "pip", "freeze"]),
|
||||
"main_app_stopped_with_volumes_preserved": True,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def restore_main():
|
||||
compose(["stop"])
|
||||
path = PRIVATE / "original-state.json"
|
||||
if path.exists() and json.loads(path.read_text())["was_running"]:
|
||||
main_compose(["up", "-d", "--wait"])
|
||||
print("Restored original application state; benchmark volumes retained", flush=True)
|
||||
|
||||
|
||||
def run_one(series, config_name, rate, repeat, protocol, *, pilot=False):
|
||||
config = dict(
|
||||
CONFIGS[protocol.get("config_bases", {}).get(config_name, config_name)]
|
||||
)
|
||||
if "config_overrides" in protocol:
|
||||
config.update(protocol["config_overrides"].get(config_name, {}))
|
||||
# Reset Go heap, goroutines, prepared-statement caches and connection pools
|
||||
# before EVERY point, including adjacent rates of the same configuration.
|
||||
compose(["up", "-d", "--no-deps", "--force-recreate", "--wait", "api"], config)
|
||||
actors = restore_fixture()
|
||||
run_id = f"{config_name}-r{repeat}-rate{rate}"
|
||||
directory = EVIDENCE / series / run_id
|
||||
if directory.exists():
|
||||
if directory.joinpath("summary.json").exists():
|
||||
saved = json.loads(directory.joinpath("summary.json").read_text())
|
||||
manifest = json.loads(directory.joinpath("manifest.json").read_text())
|
||||
if manifest["protocol_sha256"] != protocol_hash(protocol):
|
||||
raise RuntimeError("Cannot reuse a run from a different protocol")
|
||||
print("Already completed " + run_id, flush=True)
|
||||
return saved
|
||||
raise RuntimeError(
|
||||
"Incomplete run exists; retain it and choose a new series name"
|
||||
)
|
||||
directory.mkdir(parents=True)
|
||||
actual = current_containers()
|
||||
apis = [row for row in actual if row["service"] == "api"]
|
||||
if len(apis) != config["replicas"] or any(
|
||||
row["cpu"] != config["cpu"] * 1e9
|
||||
or row["memory"] != int(config["memory"].removesuffix("m")) * 1048576
|
||||
or row["ports"]
|
||||
for row in apis
|
||||
):
|
||||
raise RuntimeError(
|
||||
"Effective API resources/ports differ from the planned configuration"
|
||||
)
|
||||
write_json(
|
||||
directory / "manifest.json",
|
||||
{
|
||||
"run_id": run_id,
|
||||
"series": series,
|
||||
"pilot": pilot,
|
||||
"config_name": config_name,
|
||||
"config": config,
|
||||
"rate": rate,
|
||||
"repeat": repeat,
|
||||
"workload_seed": protocol["workload_seed"],
|
||||
"protocol_sha256": protocol_hash(protocol),
|
||||
"code_sha256": code_hash(),
|
||||
"containers": actual,
|
||||
"instrument_sha256": instrument_hash(),
|
||||
"started_utc": datetime.now(timezone.utc).isoformat(),
|
||||
"fixture_users": 200,
|
||||
"fixture_chats": 100,
|
||||
"fixture_messages": 10000,
|
||||
},
|
||||
)
|
||||
summary = asyncio.run(
|
||||
measure(
|
||||
actors,
|
||||
directory,
|
||||
config,
|
||||
rate=rate,
|
||||
duration=protocol["duration_s"],
|
||||
warmup=protocol["warmup_s"],
|
||||
seed=protocol["workload_seed"],
|
||||
prefix=series + ":" + run_id,
|
||||
limit=protocol["inflight_limit"],
|
||||
)
|
||||
)
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"run": run_id,
|
||||
"success_ratio": round(summary["success_ratio"], 4),
|
||||
"p95_ms": summary["p95_ms"],
|
||||
"goodput_rps": round(summary["goodput_rps"], 2),
|
||||
"generator_cpu": round(summary["generator_cpu_cores"], 3),
|
||||
"dispatch_p95_ms": summary["dispatch_p95_ms"],
|
||||
"valid": summary["valid"],
|
||||
"slo_pass": summary["slo_pass"],
|
||||
}
|
||||
),
|
||||
flush=True,
|
||||
)
|
||||
return summary
|
||||
|
||||
|
||||
def run_series(series, protocol, pilot=False):
|
||||
if not pilot:
|
||||
expected = protocol["code_sha256"]
|
||||
if code_hash() != expected:
|
||||
raise RuntimeError("Baseline code differs from the frozen protocol")
|
||||
if instrument_hash() != protocol["instrument_sha256"]:
|
||||
raise RuntimeError("Instruments differ from the frozen protocol")
|
||||
order = []
|
||||
for repeat, seed in enumerate(protocol["order_seeds"], 1):
|
||||
names = list(protocol["configs"])
|
||||
random.Random(seed).shuffle(names)
|
||||
for name in names:
|
||||
for rate in protocol["rates"]:
|
||||
order.append({"config": name, "rate": rate, "repeat": repeat})
|
||||
directory = EVIDENCE / series
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
frozen = directory / "protocol.json"
|
||||
if frozen.exists() and json.loads(frozen.read_text()) != protocol:
|
||||
raise RuntimeError("Series protocol already exists and differs")
|
||||
write_json(frozen, protocol)
|
||||
directory.joinpath("protocol.sha256").write_text(
|
||||
hashlib.sha256(frozen.read_bytes()).hexdigest() + " protocol.json\n"
|
||||
)
|
||||
# Capture the complete non-secret implementation, including uncommitted files.
|
||||
import tarfile
|
||||
|
||||
archive = directory / "source.tar.gz"
|
||||
if not archive.exists():
|
||||
with tarfile.open(archive, "w:gz") as tar:
|
||||
for base in (ROOT / "src/backend", HERE):
|
||||
for path in sorted(base.rglob("*")):
|
||||
if path.is_file() and "__pycache__" not in path.parts:
|
||||
tar.add(path, arcname=str(path.relative_to(ROOT)))
|
||||
for path in (
|
||||
ROOT / "src/go.mod",
|
||||
ROOT / "src/go.sum",
|
||||
ROOT / "src/Dockerfile",
|
||||
):
|
||||
tar.add(path, arcname=str(path.relative_to(ROOT)))
|
||||
write_json(directory / "order.json", order)
|
||||
print(f"Starting {series}: {len(order)} runs, pilot={pilot}", flush=True)
|
||||
for index, item in enumerate(order, 1):
|
||||
print(f"Progress {index}/{len(order)}", flush=True)
|
||||
run_one(
|
||||
series, item["config"], item["rate"], item["repeat"], protocol, pilot=pilot
|
||||
)
|
||||
time.sleep(protocol["cooldown_s"])
|
||||
print("SERIES COMPLETE: " + series, flush=True)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(__doc__)
|
||||
parser.add_argument("action", choices=("prepare", "pilot", "series", "restore"))
|
||||
parser.add_argument("--protocol", default=None)
|
||||
parser.add_argument("--series", default=None)
|
||||
args = parser.parse_args()
|
||||
prepare_private()
|
||||
with PRIVATE.joinpath("experiment.lock").open("w") as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
if args.action == "prepare":
|
||||
setup()
|
||||
elif args.action == "restore":
|
||||
restore_main()
|
||||
else:
|
||||
if not args.protocol or not args.series:
|
||||
parser.error("pilot/series require --protocol and --series")
|
||||
protocol = json.loads(ROOT.joinpath(args.protocol).read_text())
|
||||
try:
|
||||
run_series(args.series, protocol, pilot=args.action == "pilot")
|
||||
except BaseException:
|
||||
restore_main()
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,31 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/../.."
|
||||
phase=${1:-baseline}
|
||||
series=${2:-"${phase}-$(date -u +%Y%m%dT%H%M%SZ)"}
|
||||
case "$series" in
|
||||
''|*[!A-Za-z0-9_-]*) printf 'Use letters, digits, _ or - in series name\n' >&2; exit 2 ;;
|
||||
esac
|
||||
action=series
|
||||
case "$phase" in
|
||||
pilot) protocol=pilots/pilot-02; action=pilot; series="pilots/$series" ;;
|
||||
baseline|runtime-400|runtime-capacity|runtime-latency) protocol=$phase ;;
|
||||
*) printf 'Unknown phase: %s\n' "$phase" >&2; exit 2 ;;
|
||||
esac
|
||||
python3 -m venv .memory/bench-env
|
||||
.memory/bench-env/bin/pip install -r experiments/lab3-scale/requirements-lock.txt
|
||||
docker build -t highload-lab3-bench-api:baseline src
|
||||
runner=.memory/bench-env/bin/python
|
||||
trap '$runner experiments/lab3-scale/run.py restore' EXIT
|
||||
$runner experiments/lab3-scale/run.py prepare
|
||||
$runner experiments/lab3-scale/run.py "$action" --protocol "experiments/lab3-scale/protocols/$protocol.json" --series "$series"
|
||||
$runner experiments/lab3-scale/analyze.py "$series"
|
||||
case "$phase" in
|
||||
baseline) $runner experiments/lab3-scale/postprocess/decisions.py audit "$series" ;;
|
||||
runtime-400) $runner experiments/lab3-scale/postprocess/decisions.py hi "$series" ;;
|
||||
runtime-capacity) $runner experiments/lab3-scale/postprocess/decisions.py hc "$series" ;;
|
||||
runtime-latency)
|
||||
$runner experiments/lab3-scale/postprocess/decisions.py hl "$series"
|
||||
$runner experiments/lab3-scale/postprocess/plot_latency.py "$series"
|
||||
;;
|
||||
esac
|
||||
Reference in New Issue
Block a user