#!/usr/bin/env python3
import json
import statistics as st
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
OUT = ROOT / 'evidence' / 'track1'
RAW = OUT / 'raw'
ORDER = ['f1x2.0', 'f2x1.0', 'f4x0.5', 'g1', 'g2', 'g4', 'g8']
def load():
runs = [json.loads(p.read_text(encoding='utf-8')) for p in sorted(RAW.glob('*.json'))
if not p.name.endswith('.k6.json')]
groups = {}
for r in runs:
groups.setdefault(r['config'], []).append(r)
return groups
def summarize(runs):
def agg(vals):
return {'mean': round(st.mean(vals), 1), 'min': round(min(vals), 1), 'max': round(max(vals), 1)}
first = runs[0]
svc = lambda name, key: [r['docker_stats'].get(name, {}).get(key, 0) for r in runs]
return {
'replicas': first['replicas'], 'cpus_per_replica': first['cpus_per_replica'],
'mem_per_replica': first['mem_per_replica'], 'db_pool_per_replica': first['db_pool_per_replica'],
'extra_env': first.get('extra_env', {}), 'repeats': len(runs), 'vus': first['vus'],
'duration': first['duration'],
'rps': agg([r['rps'] for r in runs]),
'p50_ms': agg([r['latency_ms']['p(50)'] for r in runs]),
'p95_ms': agg([r['latency_ms']['p(95)'] for r in runs]),
'p99_ms': agg([r['latency_ms']['p(99)'] for r in runs]),
'error_ratio_max': max(r['error_ratio'] for r in runs),
'cpu_pct': {s: round(st.mean(svc(s, 'cpu_pct_mean')), 1) for s in ('api', 'postgres', 'lb', 'valkey')},
'api_cpu_max_one_replica_pct': round(max(svc('api', 'cpu_pct_max_one_container')), 1),
'mem_mib': {s: round(st.mean(svc(s, 'mem_mib_mean')), 1) for s in ('api', 'postgres', 'lb', 'valkey')},
'pg_active_backends': round(st.mean(r['postgres']['active_backends_mean'] for r in runs), 1),
'pg_top_waits': top_waits(runs),
}
def top_waits(runs):
acc = {}
for r in runs:
for k, v in r['postgres']['wait_events_mean'].items():
acc[k] = acc.get(k, 0) + v / len(runs)
return {k: round(v, 2) for k, v in sorted(acc.items(), key=lambda x: -x[1])[:4]}
FONT = 'font-family="system-ui,Segoe UI,Arial" font-size="12"'
C1, C2, C3, C4 = '#2563eb', '#dc2626', '#16a34a', '#9333ea'
def svg_wrap(w, h, body, title):
return ('\n'
% (w, h, w, h, FONT, w // 2, title, body))
def axis(x0, y0, x1, y1, ymax, ylabel, ticks=5, right=False, color='#333'):
b = ''
xa = x1 if right else x0
for i in range(ticks + 1):
v = ymax * i / ticks
y = y1 - (y1 - y0) * i / ticks
if not right:
b += '' % (x0, y, x1, y)
b += '%g' % (
xa + (6 if right else -6), y + 4, 'start' if right else 'end', color, round(v, 1))
b += '%s' % (
xa + (48 if right else -48), (y0 + y1) // 2, color, ylabel)
return b
def nice(v):
for e in range(0, 7):
for m in (1, 1.2, 1.5, 2, 2.5, 3, 4, 5, 6, 8):
c = m * 10 ** e
if c >= v:
return c
return v
def bar_chart(names, series, title, ylabel, path):
w, h, x0, y0, x1, y1 = 640, 380, 70, 40, 610, 300
ymax = nice(max(v[2] for _, _, vals in series for v in vals) * 1.1)
b = axis(x0, y0, x1, y1, ymax, ylabel)
gw = (x1 - x0) / len(names)
bw = gw * 0.7 / len(series)
for i, n in enumerate(names):
b += '%s' % (x0 + gw * (i + .5), y1 + 18, n)
for j, (lab, col, vals) in enumerate(series):
mean, lo, hi = vals[i]
x = x0 + gw * i + gw * 0.15 + bw * j
y = y1 - (y1 - y0) * mean / ymax
b += '' % (x, y, bw - 2, y1 - y, col)
ylo, yhi = (y1 - (y1 - y0) * v / ymax for v in (lo, hi))
cx = x + (bw - 2) / 2
b += '' % (cx, ylo, cx, yhi)
b += '%g' % (cx, y - 6 if yhi > y - 4 else yhi - 4, round(mean))
lx = x0
for lab, col, _ in series:
b += '%s' % (lx, y1 + 32, col, lx + 16, y1 + 42, lab)
lx += 20 + 8 * len(lab)
b += 'столбец = среднее, отрезок = min..max по повторам' % (x0, h - 8)
path.write_text(svg_wrap(w, h, b, title), encoding='utf-8')
def line_chart(xs, left, right, title, xlabel, ylabel_l, ylabel_r, path, rmax=None):
w, h, x0, y0, x1, y1 = 680, 380, 80, 40, 600, 300
lmax = nice(max(v for _, _, vals, _ in left for v in vals) * 1.1)
rmax = rmax or nice(max(v for _, _, vals, _ in right for v in vals) * 1.1)
b = axis(x0, y0, x1, y1, lmax, ylabel_l) + axis(x0, y0, x1, y1, rmax, ylabel_r, right=True, color='#555')
px = lambda i: x0 + (x1 - x0) * i / (len(xs) - 1)
for i, x in enumerate(xs):
b += '%s' % (px(i), y1 + 18, x)
b += '%s' % ((x0 + x1) // 2, y1 + 36, xlabel)
for group, ymax in ((left, lmax), (right, rmax)):
for lab, col, vals, dashed in group:
pts = ' '.join('%.1f,%.1f' % (px(i), y1 - (y1 - y0) * v / ymax) for i, v in enumerate(vals))
b += '' % (
pts, col, ' stroke-dasharray="6 4"' if dashed else '')
for i, v in enumerate(vals):
b += '' % (px(i), y1 - (y1 - y0) * v / ymax, col)
lx = x0
for lab, col, _, dashed in left + right:
b += '%s' % (
lx, y1 + 56, lx + 18, y1 + 56, col, ' stroke-dasharray="6 4"' if dashed else '', lx + 22, y1 + 60, lab)
lx += 34 + 7 * len(lab)
path.write_text(svg_wrap(w, h, b, title), encoding='utf-8')
def main():
groups = load()
res = {k: summarize(v) for k, v in groups.items()}
keys = [k for k in ORDER if k in res] + sorted(k for k in res if k not in ORDER)
(OUT / 'results.json').write_text(json.dumps({k: res[k] for k in keys}, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
lines = ['| Конфигурация | Реплики × CPU / RAM, пул | RPS mean (min–max) | p50 / p95 / p99, мс | ошибки | CPU% api / pg / lb | PG active, топ ожиданий |',
'| --- | --- | --- | --- | --- | --- | --- |']
for k in keys:
r = res[k]
lines.append('| %s | %d × %s / %s, %d | %g (%g–%g) | %g / %g / %g | %g | %g / %g / %g | %g; %s |' % (
k, r['replicas'], r['cpus_per_replica'], r['mem_per_replica'], r['db_pool_per_replica'],
r['rps']['mean'], r['rps']['min'], r['rps']['max'], r['p50_ms']['mean'], r['p95_ms']['mean'],
r['p99_ms']['mean'], r['error_ratio_max'], r['cpu_pct']['api'], r['cpu_pct']['postgres'],
r['cpu_pct']['lb'], r['pg_active_backends'],
', '.join('%s %g' % kv for kv in list(r['pg_top_waits'].items())[:2])))
(OUT / 'summary.md').write_text('\n'.join(lines) + '\n', encoding='utf-8')
print('\n'.join(lines))
fixed = [k for k in ('f1x2.0', 'f2x1.0', 'f4x0.5') if k in res]
if fixed:
g = lambda key: [(res[k][key]['mean'], res[k][key]['min'], res[k][key]['max']) for k in fixed]
bar_chart(['1 × 2.0 CPU', '2 × 1.0 CPU', '4 × 0.5 CPU'][:len(fixed)], [('RPS', C1, g('rps'))],
'Фиксированный бюджет API (2 CPU, 512 MiB, 20 соединений): RPS', 'успешные запросы/с', OUT / 'fixed-rps.svg')
bar_chart(['1 × 2.0 CPU', '2 × 1.0 CPU', '4 × 0.5 CPU'][:len(fixed)],
[('p50', C3, g('p50_ms')), ('p95', C1, g('p95_ms')), ('p99', C2, g('p99_ms'))],
'Фиксированный бюджет API: задержка', 'мс', OUT / 'fixed-latency.svg')
growth = [k for k in ('g1', 'g2', 'g4', 'g8') if k in res]
if len(growth) >= 2:
xs = [res[k]['replicas'] for k in growth]
line_chart(xs, [('RPS', C1, [res[k]['rps']['mean'] for k in growth], False)],
[('CPU API (сумма)', C3, [res[k]['cpu_pct']['api'] for k in growth], True),
('CPU PostgreSQL', C2, [res[k]['cpu_pct']['postgres'] for k in growth], True),
('CPU HAProxy', C4, [res[k]['cpu_pct']['lb'] for k in growth], True)],
'Рост числа реплик (по 1 CPU), PostgreSQL 2 CPU', 'API-реплик',
'успешные запросы/с', 'CPU, % ядра', OUT / 'growth.svg')
line_chart(xs, [('p95, мс', C1, [res[k]['p95_ms']['mean'] for k in growth], False),
('p99, мс', C2, [res[k]['p99_ms']['mean'] for k in growth], False)],
[('активных backend PG', C3, [res[k]['pg_active_backends'] for k in growth], True)],
'Рост числа реплик: задержка и очередь в PostgreSQL', 'API-реплик', 'мс',
'активные сессии PG', OUT / 'growth-latency.svg')
ab = [('g2-tx', 'g2-oneshot'), ('g4-tx', 'g4-oneshot')]
if all(k in res for pair in ab for k in pair):
g = lambda keys, m: [(res[k][m]['mean'], res[k][m]['min'], res[k][m]['max']) for k in keys]
bar_chart(['2 реплики', '4 реплики'], [('tx: 5 round trip', C2, g([a for a, _ in ab], 'rps')),
('oneshot: 1 запрос', C3, g([b for _, b in ab], 'rps'))],
'Улучшение: запись сообщения одним SQL-оператором', 'успешные запросы/с', OUT / 'improvement-rps.svg')
bar_chart(['2 реплики', '4 реплики'], [('tx p95', C2, g([a for a, _ in ab], 'p95_ms')),
('oneshot p95', C3, g([b for _, b in ab], 'p95_ms'))],
'Улучшение: p95 задержки', 'мс', OUT / 'improvement-p95.svg')
if __name__ == '__main__':
main()