Files
mtusi2026lab3/scripts/plot_track1.py

193 lines
11 KiB
Python

#!/usr/bin/env python3
"""Render track-1 summary as dependency-free SVG charts.
Input: evidence/track1/summary.json produced by scripts/track1.py.
Output: evidence/track1/plots/*.svg. The charts plot medians of the recorded
runs; raw run files remain the source of truth.
"""
import json
import math
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
SUMMARY = ROOT / 'evidence/track1/summary.json'
OUT = ROOT / 'evidence/track1/plots'
COLORS = ['#1f77b4', '#d62728', '#2ca02c', '#ff7f0e', '#9467bd']
def esc(value):
return (str(value).replace('&', '&amp;').replace('<', '&lt;')
.replace('>', '&gt;').replace('"', '&quot;'))
def svg_header(width, height, title, subtitle):
return ['<?xml version="1.0" encoding="UTF-8"?>',
'<svg xmlns="http://www.w3.org/2000/svg" width="%d" height="%d" viewBox="0 0 %d %d">' % (width, height, width, height),
'<rect width="100%%" height="100%%" fill="#ffffff"/>',
'<text x="40" y="38" font-family="Helvetica,Arial,sans-serif" font-size="20" font-weight="bold" fill="#222">%s</text>' % esc(title),
'<text x="40" y="60" font-family="Helvetica,Arial,sans-serif" font-size="12" fill="#555">%s</text>' % esc(subtitle)]
def axes(width, height, xlabels, ymax, ylabel, left=90, right=40, top=90, bottom=80):
part = []
plot_w = width - left - right
plot_h = height - top - bottom
for step in range(6):
value = ymax * step / 5.0
y = top + plot_h - plot_h * step / 5.0
part.append('<line x1="%d" y1="%.1f" x2="%d" y2="%.1f" stroke="#e5e5e5" stroke-width="1"/>' % (left, y, width - right, y))
part.append('<text x="%d" y="%.1f" text-anchor="end" font-family="Helvetica,Arial,sans-serif" font-size="11" fill="#555">%.1f</text>' % (left - 8, y + 4, value))
part.append('<line x1="%d" y1="%d" x2="%d" y2="%d" stroke="#333" stroke-width="1.2"/>' % (left, top + plot_h, width - right, top + plot_h))
part.append('<line x1="%d" y1="%d" x2="%d" y2="%d" stroke="#333" stroke-width="1.2"/>' % (left, top, left, top + plot_h))
if len(xlabels) == 1:
positions = [left + plot_w / 2.0]
else:
positions = [left + plot_w * i / (len(xlabels) - 1.0) for i in range(len(xlabels))]
for label, x in zip(xlabels, positions):
part.append('<text x="%.1f" y="%d" text-anchor="middle" font-family="Helvetica,Arial,sans-serif" font-size="13" fill="#333">%s</text>' % (x, top + plot_h + 24, esc(label)))
part.append('<text x="%.1f" y="%d" text-anchor="middle" font-family="Helvetica,Arial,sans-serif" font-size="13" fill="#333">%s</text>' % (left + plot_w / 2.0, height - 22, esc(ylabel)))
part.append('<text x="%d" y="%d" text-anchor="middle" transform="rotate(-90 %d %d)" font-family="Helvetica,Arial,sans-serif" font-size="13" fill="#333">%s</text>' % (24, top + plot_h / 2, 24, top + plot_h / 2, esc(ylabel)))
return part, positions, plot_w, plot_h
def line_chart(path, title, subtitle, xlabels, series, ylabel, ymax=None, value_suffix=''):
width, height = 960, 560
top, bottom = 90, 80
all_values = [value for _, values in series for value in values if value is not None]
if ymax is None:
ymax = max(all_values) * 1.15 if all_values else 1.0
if ymax <= 0:
ymax = 1.0
# Round the axis up to a readable number.
magnitude = 10 ** math.floor(math.log10(ymax))
ymax = math.ceil(ymax / magnitude) * magnitude
part, positions, plot_w, plot_h = axes(width, height, xlabels, ymax, ylabel)
for index, (name, values) in enumerate(series):
color = COLORS[index % len(COLORS)]
points = []
for point, value in zip(positions, values):
if value is None:
continue
y = top + plot_h - (value / ymax) * plot_h
points.append((point, y, value))
if len(points) > 1:
path_data = ' '.join('%s%.1f,%.1f' % ('M' if i == 0 else 'L', x, y) for i, (x, y, _) in enumerate(points))
part.append('<path d="%s" fill="none" stroke="%s" stroke-width="2.5"/>' % (path_data, color))
for x, y, value in points:
part.append('<circle cx="%.1f" cy="%.1f" r="4" fill="%s"/>' % (x, y, color))
part.append('<text x="%.1f" y="%.1f" text-anchor="middle" font-family="Helvetica,Arial,sans-serif" font-size="11" fill="%s">%s%s</text>' % (x, y - 10, color, esc(('%.1f' % value) if isinstance(value, float) else value), value_suffix))
legend_y = height - 46
legend_x = 110 + index * 230
part.append('<line x1="%d" y1="%d" x2="%d" y2="%d" stroke="%s" stroke-width="3"/>' % (legend_x, legend_y, legend_x + 24, legend_y, color))
part.append('<text x="%d" y="%d" font-family="Helvetica,Arial,sans-serif" font-size="12" fill="#333">%s</text>' % (legend_x + 32, legend_y + 4, esc(name)))
part.append('</svg>')
Path(path).write_text('\n'.join(part) + '\n')
def bar_chart(path, title, subtitle, xlabels, series, ylabel, ymax=None, value_suffix=''):
width, height = 960, 560
top, bottom = 90, 100
all_values = [value for _, values in series for value in values if value is not None]
if ymax is None:
ymax = max(all_values) * 1.2 if all_values else 1.0
part, positions, plot_w, plot_h = axes(width, height, xlabels, ymax, ylabel)
group_width = plot_w / max(1, len(positions))
bar_width = group_width * 0.7 / max(1, len(series))
for series_index, (name, values) in enumerate(series):
color = COLORS[series_index % len(COLORS)]
for index, value in enumerate(values):
if value is None:
continue
x = positions[index] - group_width * 0.35 + series_index * bar_width
bar_h = value / ymax * plot_h
y = top + plot_h - bar_h
part.append('<rect x="%.1f" y="%.1f" width="%.1f" height="%.1f" fill="%s" opacity="0.88"/>' % (x, y, bar_width - 3, bar_h, color))
part.append('<text x="%.1f" y="%.1f" text-anchor="middle" font-family="Helvetica,Arial,sans-serif" font-size="10" fill="#222">%s%s</text>' % (x + bar_width / 2, y - 6, esc(('%.1f' % value)), value_suffix))
legend_y = height - 46
legend_x = 110 + series_index * 230
part.append('<rect x="%d" y="%d" width="16" height="12" fill="%s"/>' % (legend_x, legend_y - 9, color))
part.append('<text x="%d" y="%d" font-family="Helvetica,Arial,sans-serif" font-size="12" fill="#333">%s</text>' % (legend_x + 24, legend_y + 1, esc(name)))
part.append('</svg>')
Path(path).write_text('\n'.join(part) + '\n')
def get(group, key, field, default=None):
if key not in group:
return default
value = group[key].get(field, default)
return default if value is None else value
def main():
if not SUMMARY.exists():
raise SystemExit('missing %s; run scripts/track1.py first' % SUMMARY)
data = json.loads(SUMMARY.read_text())
OUT.mkdir(parents=True, exist_ok=True)
fixed = data['medians']['fixed_total']
growth = data['medians']['resource_growth']
improvement = data['medians']['improvement']
fixed_keys = ['1', '2', '4']
growth_keys = ['0.4', '0.7', '0.9']
revisions = sorted({run['config'].get('revision') for run in data['runs']['fixed_total']})
subtitle = 'Colima 2 vCPU / 2 GiB, one Docker host; medians of %d alternating runs; revision %s' % (
len(data['runs']['fixed_total']) // max(1, len(fixed_keys)), ', '.join(filter(None, revisions))[:12])
line_chart(OUT / 'fixed-rps.svg',
'Fixed total API CPU/RAM: 1 vs 2 vs 4 replicas',
subtitle + '; total API 0.8 vCPU / 512 MiB',
[key + ' replica' + ('' if key == '1' else 's') for key in fixed_keys],
[('successful RPS', [get(fixed, key, 'successful_rps', 0) for key in fixed_keys])],
'HTTP 2xx acknowledgements / second', value_suffix='')
line_chart(OUT / 'fixed-latency.svg',
'Latency at fixed total CPU: more replicas, same budget',
subtitle + '; successful requests only',
[key + ' replica' + ('' if key == '1' else 's') for key in fixed_keys],
[('p50 ms', [get(fixed, key, 'p50_ms', 0) for key in fixed_keys]),
('p95 ms', [get(fixed, key, 'p95_ms', 0) for key in fixed_keys]),
('p99 ms', [get(fixed, key, 'p99_ms', 0) for key in fixed_keys])],
'milliseconds', value_suffix=' ms')
bar_chart(OUT / 'saturation.svg',
'Where the fixed CPU budget goes (median utilization)',
subtitle + '; cgroup CPU usage / cgroup CPU limit',
[key + ' replica' + ('' if key == '1' else 's') for key in fixed_keys],
[('API', [100 * get(fixed, key, 'api_utilization', 0) for key in fixed_keys]),
('PostgreSQL', [100 * get(fixed, key, 'db_utilization', 0) for key in fixed_keys]),
('HAProxy', [100 * (get(fixed, key, 'lb_used_cores', 0) / 0.2) for key in fixed_keys])],
'percent of container CPU limit', ymax=110, value_suffix='%')
line_chart(OUT / 'growth-rps.svg',
'Resource-growth series at 4 replicas',
subtitle + '; shared PostgreSQL/Valkey/LB limits fixed',
['API total %.1f vCPU' % float(key) for key in growth_keys],
[('successful RPS', [get(growth, key, 'successful_rps', 0) for key in growth_keys])],
'HTTP 2xx acknowledgements / second')
bar_chart(OUT / 'growth-utilization.svg',
'Resource-growth series: utilization of the fixed shared backend',
subtitle + '; cgroup CPU usage / cgroup CPU limit',
['API total %.1f vCPU' % float(key) for key in growth_keys],
[('API', [100 * get(growth, key, 'api_utilization', 0) for key in growth_keys]),
('PostgreSQL', [100 * get(growth, key, 'db_utilization', 0) for key in growth_keys])],
'percent of container CPU limit', ymax=110, value_suffix='%')
base = get(improvement, 'baseline', 'successful_rps', 0)
opt = get(improvement, 'optimized', 'successful_rps', 0)
bar_chart(OUT / 'improvement-rps.svg',
'Confirmed improvement at 4x0.2 vCPU: one atomic statement',
'Baseline: explicit transaction + message INSERT + idempotency INSERT. Final: one data-modifying CTE. '
'Median of alternating runs; +%.1f%% RPS.' % (((opt - base) / base * 100.0) if base else 0.0),
['baseline', 'optimized'],
[('successful RPS', [base, opt])],
'HTTP 2xx acknowledgements / second')
bar_chart(OUT / 'improvement-latency.svg',
'Confirmed improvement: p95 latency at the same limit',
'Successful POST requests; lower is better; same alternating runs',
['baseline', 'optimized'],
[('p95 ms', [get(improvement, 'baseline', 'p95_ms', 0),
get(improvement, 'optimized', 'p95_ms', 0)])],
'milliseconds', value_suffix=' ms')
print('wrote', OUT)
if __name__ == '__main__':
main()