#!/usr/bin/env python3 """Render portable SVG graphs and a Markdown summary from grade-4 results.""" import argparse from collections import defaultdict import html import json from pathlib import Path STYLE = """ text { font-family: Inter, Segoe UI, sans-serif; fill: #eceef0; } .title { font-size: 26px; font-weight: 650; } .label { font-size: 14px; fill: #c8cbd0; } .small { font-size: 12px; fill: #a2a5aa; } .grid { stroke: #34373d; stroke-width: 1; } .bar { fill: #cfd2d6; } .bar2 { fill: #73777f; } .line { fill: none; stroke: #f4f5f6; stroke-width: 3; } .error { fill: #8f949c; stroke: #f4f5f6; stroke-width: 1; } .event { stroke: #a2a5aa; stroke-width: 2; stroke-dasharray: 6 5; } """ def svg(title, body, width=1100, height=560): return f""" {html.escape(title)} {body} """ def grid(maximum, left, top, width, height): parts = [] for step in range(6): value = maximum * step / 5 y = top + height - height * step / 5 parts.append(f'') parts.append(f'{value:.0f}') return parts def throughput(phases, output): left, top, width, height = 80, 90, 960, 360 maximum = max((phase["successful_rps"] for phase in phases), default=1) or 1 parts = grid(maximum, left, top, width, height) slot = width / max(1, len(phases)) for index, phase in enumerate(phases): bar_width = min(120, slot * 0.5) x = left + slot * index + (slot - bar_width) / 2 bar_height = height * phase["successful_rps"] / maximum y = top + height - bar_height parts.append(f'') parts.append(f'{phase["successful_rps"]:.1f} RPS') parts.append(f'{html.escape(phase["name"])}') parts.append(f'errors {phase["error_ratio"]*100:.2f}%') parts.append(f'Successful requests per second') output.write_text(svg("Grade 4: throughput and errors", "\n".join(parts))) def latency(phases, output): left, top, width, height = 80, 90, 960, 360 values = [value for phase in phases for value in phase["successful_latency_ms"].values() if value is not None] maximum = max(values, default=1) or 1 parts = grid(maximum, left, top, width, height) slot = width / max(1, len(phases)) for phase_index, phase in enumerate(phases): group_x = left + slot * phase_index bar_width = min(42, slot / 5) for metric_index, metric in enumerate(("p50", "p95", "p99")): value = phase["successful_latency_ms"][metric] or 0 bar_height = height * value / maximum x = group_x + slot * 0.2 + metric_index * (bar_width + 8) y = top + height - bar_height css = "bar" if metric_index == 0 else "bar2" parts.append(f'') parts.append(f'{value:.0f}') parts.append(f'{metric}') parts.append(f'{html.escape(phase["name"])}') parts.append(f'Successful latency, ms') output.write_text(svg("Grade 4: successful latency percentiles", "\n".join(parts))) def timeline(phases, output): left, top, width, height = 70, 90, 980, 390 rows, events, offset = [], [], 0 for phase in phases: buckets = phase["per_second"] for second, counts in sorted(buckets.items(), key=lambda item: int(item[0])): rows.append((offset + int(second), counts)) if phase.get("action"): events.append((offset + phase["action"]["started_at"], phase["name"])) offset += max([int(key) for key in buckets] or [0]) + 2 maximum = max((counts["successful"] for _, counts in rows), default=1) or 1 max_x = max((second for second, _ in rows), default=1) or 1 parts, points = grid(maximum, left, top, width, height), [] for second, counts in rows: x = left + width * second / max_x y = top + height - height * counts["successful"] / maximum points.append(f"{x:.1f},{y:.1f}") if counts["failed"]: radius = min(12, 3 + counts["failed"]) parts.append(f'') parts.append(f'') for second, label in events: x = left + width * second / max_x parts.append(f'') parts.append(f'{html.escape(label)} action') parts.append(f'One-second buckets; circles mark failed requests') output.write_text(svg("Grade 4: request timeline", "\n".join(parts), height=600)) def resources(phases, output): combined = defaultdict(lambda: {"cpu": [], "memory": []}) for phase in phases: for name, values in phase["resources"].items(): combined[name]["cpu"].append(values["cpu_percent_max"]) combined[name]["memory"].append(values["memory_mib_max"]) names, parts = sorted(combined), [] panels = [ ("Peak CPU, %", "cpu", 80, 90, 420, 360), ("Peak memory, MiB", "memory", 600, 90, 420, 360), ] for title, metric, left, top, width, height in panels: maximum = max((max(combined[name][metric]) for name in names), default=1) or 1 parts.append(f'{title}') slot = width / max(1, len(names)) for index, name in enumerate(names): value = max(combined[name][metric]) bar_width = min(70, slot * 0.55) x = left + slot * index + (slot - bar_width) / 2 bar_height = height * value / maximum y = top + height - bar_height parts.append(f'') parts.append(f'{value:.1f}') parts.append(f'{html.escape(name)}') output.write_text(svg("Grade 4: peak container resources", "\n".join(parts), height=600)) def summary(report, output): method = report["methodology"] lines = [ "# Lab 3 grade-4 experiment", "", f"Generated: {report['environment']['utc_started_at']}.", "", "## Method", "", f"- concurrency: {method['concurrency']};", f"- baseline duration: {method['baseline_seconds']} s;", "- load: closed-loop POST messages through the public HAProxy gateway;", "- failover: both original API containers stopped and restored in turn;", "- rolling update: one surge replica, old replicas replaced one by one;", "- percentiles cover successful responses; failures are separate.", "", "## Results", "", "| Phase | RPS | Errors | p50 ms | p95 ms | p99 ms | Recovery s |", "| --- | ---: | ---: | ---: | ---: | ---: | ---: |", ] for phase in report["phases"]: lat = phase["successful_latency_ms"] recovery = phase["recovery_seconds"] lines.append( f"| {phase['name']} | {phase['successful_rps']} | " f"{phase['failed_requests']} ({phase['error_ratio']*100:.3f}%) | " f"{lat['p50']} | {lat['p95']} | {lat['p99']} | " f"{recovery if recovery is not None else 'n/a'} |" ) idem = report["idempotency"] lines += [ "", "## Parallel idempotency", "", f"{idem['parallel_requests']} requests produced " f"{idem['unique_message_ids']} unique message ID across " f"{len(idem['observed_instances'])} API instances.", "", "## Graphs", "", "![Throughput and errors](throughput-errors.svg)", "", "![Latency](latency.svg)", "", "![Timeline](timeline.svg)", "", "![Resources](resources.svg)", "", "## Scope", "", "Single-host process failure and rolling replacement only. PostgreSQL " "and HAProxy remain single points of failure.", "", ] output.write_text("\n".join(lines)) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("results", nargs="?", default="evidence/grade4/results.json") args = parser.parse_args() source = Path(args.results) report = json.loads(source.read_text()) destination = source.parent phases = report["phases"] throughput(phases, destination / "throughput-errors.svg") latency(phases, destination / "latency.svg") timeline(phases, destination / "timeline.svg") resources(phases, destination / "resources.svg") summary(report, destination / "README.md") print(f"rendered grade-4 evidence in {destination}") if __name__ == "__main__": main()