Files
mtusi2026lab3/student-tests/test_track1_scaling.py
T

373 lines
16 KiB
Python

#!/usr/bin/env python3
"""Grade 5 Track 1: Cost of Scaling experiment for Lab 3.
Measures:
- Series A: Fixed total API resource budget (2.0 CPU, 512M RAM) across 1/2/4 replicas.
- Series B: Scaling with resource growth (0.5 CPU, 256M RAM per replica) against 0.5 CPU DB to locate saturation point.
- Series C: Confirmed optimization at 4-replica saturation (WRITE_MODE=sequential, DB_MAX_CONNS=25 -> WRITE_MODE=pipeline, DB_MAX_CONNS=8).
Restores the default 2-replica stand on completion.
"""
import base64
from concurrent.futures import ThreadPoolExecutor
import datetime as dt
import http.client
import json
import math
import os
from pathlib import Path
import subprocess
import sys
import threading
import time
import urllib.parse
import uuid
ROOT = Path(__file__).resolve().parents[1]
EVIDENCE_JSON = ROOT / "evidence" / "track1_scaling.json"
EVIDENCE_SVG = ROOT / "evidence" / "track1_scaling_chart.svg"
BASE_URL = sys.argv[1] if len(sys.argv) > 1 else "http://localhost:8080"
def run_cmd(cmd, env=None):
merged_env = os.environ.copy()
if env:
merged_env.update(env)
return subprocess.run(cmd, cwd=str(ROOT), env=merged_env, text=True, capture_output=True, check=True)
def wait_ready(min_replicas=1, timeout_s=60):
parsed = urllib.parse.urlparse(BASE_URL)
host = parsed.hostname or "localhost"
port = parsed.port or 80
deadline = time.monotonic() + timeout_s
seen = set()
while time.monotonic() < deadline:
try:
conn = http.client.HTTPConnection(host, port, timeout=2)
conn.request("GET", "/health/ready")
resp = conn.getresponse()
_ = resp.read()
if resp.status == 200:
inst = resp.getheader("X-Instance-Id", "")
if inst:
seen.add(inst)
if len(seen) >= min_replicas:
conn.close()
return sorted(seen)
conn.close()
except Exception:
pass
time.sleep(0.3)
raise RuntimeError(f"Expected >= {min_replicas} ready replicas, observed {seen}")
def apply_topology(replicas, api_cpu, api_mem, db_cpu, db_mem, db_max_conns, write_mode):
env_overrides = {
"API_REPLICAS": str(replicas),
"API_CPU_LIMIT": str(api_cpu),
"API_MEM_LIMIT": str(api_mem),
"DB_CPU_LIMIT": str(db_cpu),
"DB_MEM_LIMIT": str(db_mem),
"DB_MAX_CONNS": str(db_max_conns),
"WRITE_MODE": str(write_mode),
}
run_cmd(
["docker", "compose", "--env-file", ".env", "up", "-d", "--no-deps", "--force-recreate", "--scale", f"api={replicas}", "postgres", "api"],
env=env_overrides,
)
run_cmd(["docker", "compose", "--env-file", ".env", "restart", "lb"], env=env_overrides)
time.sleep(2.0)
return wait_ready(min_replicas=replicas, timeout_s=60)
def sample_docker_stats():
out = run_cmd(["docker", "stats", "--no-stream", "--format", "{{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}"]).stdout.strip().splitlines()
stats = {}
for line in out:
parts = line.split("\t")
if len(parts) != 3:
continue
name, cpu, mem = parts
if not name.startswith("lab3-"):
continue
stats[name] = {"cpu": cpu.strip(), "mem": mem.strip()}
return stats
def percentile(sorted_vals, p):
if not sorted_vals:
return None
idx = max(0, math.ceil(p * len(sorted_vals)) - 1)
return round(sorted_vals[idx] * 1000.0, 3)
def bootstrap_actor(host, port):
conn = http.client.HTTPConnection(host, port, timeout=10)
uname = f"bench_{uuid.uuid4().hex[:10]}"
pw = f"ScaleBench-{uuid.uuid4().hex}"
body = json.dumps({"username": uname, "display_name": "Bench", "password": pw}).encode("utf-8")
conn.request("POST", "/api/v1/users", body, {"Content-Type": "application/json", "Accept": "application/json"})
r1 = conn.getresponse()
u = json.loads(r1.read().decode("utf-8"))
assert r1.status == 201
basic = base64.b64encode(f"{uname}:{pw}".encode("utf-8")).decode("ascii")
conn.request("POST", "/api/v1/auth/sessions", None, {"Authorization": f"Basic {basic}", "Accept": "application/json"})
r2 = conn.getresponse()
s = json.loads(r2.read().decode("utf-8"))
assert r2.status == 201
chat_body = json.dumps({"title": "Scale Chat", "member_ids": [u["id"]]}).encode("utf-8")
conn.request("POST", "/api/v1/chats", chat_body, {
"Authorization": f"Bearer {s['token']}",
"Content-Type": "application/json",
"Accept": "application/json",
})
r3 = conn.getresponse()
chat = json.loads(r3.read().decode("utf-8"))
assert r3.status == 201
# Seed one message so GET /messages returns data immediately
msg_body = json.dumps({"text": "Initial message"}).encode("utf-8")
conn.request("POST", f"/api/v1/chats/{chat['id']}/messages", msg_body, {
"Authorization": f"Bearer {s['token']}",
"Content-Type": "application/json",
"Idempotency-Key": f"init-{uuid.uuid4().hex}",
})
r4 = conn.getresponse()
_ = r4.read()
assert r4.status == 201
conn.close()
return {"username": uname, "basic": basic, "token": s["token"], "chat_id": chat["id"]}
def run_benchmark(label, concurrency=20, warmup_s=2.0, duration_s=10.0, login_every=20):
"""Mixed messenger workload:
- 1 in `login_every` (5%): POST /api/v1/auth/sessions (Argon2id CPU bound)
- ~75%: POST /api/v1/chats/{id}/messages (DB transactional write + Idempotency-Key + Redis INCR)
- ~20%: GET /api/v1/chats/{id}/messages?limit=20 (Redis/DB read)
"""
parsed = urllib.parse.urlparse(BASE_URL)
host = parsed.hostname or "localhost"
port = parsed.port or 80
actor = bootstrap_actor(host, port)
barrier = threading.Barrier(concurrency + 2)
stop_at = time.monotonic() + warmup_s + duration_s + 0.2
record_after = time.monotonic() + warmup_s
captured_stats = {}
stats_done = threading.Event()
def stats_sampler():
barrier.wait()
time.sleep(warmup_s + duration_s * 0.5)
try:
captured_stats.update(sample_docker_stats())
except Exception as exc:
captured_stats["error"] = str(exc)
stats_done.set()
def worker(wid):
conn = http.client.HTTPConnection(host, port, timeout=10)
latencies = []
write_latencies = []
errors = 0
insts = set()
i = 0
barrier.wait()
while time.monotonic() < stop_at:
t0 = time.monotonic()
ok = False
is_write = False
try:
if i % login_every == 0:
conn.request("POST", "/api/v1/auth/sessions", None, {
"Authorization": f"Basic {actor['basic']}",
"Accept": "application/json",
})
resp = conn.getresponse()
_ = resp.read()
ok = resp.status == 201
elif i % 5 == 1:
conn.request("GET", f"/api/v1/chats/{actor['chat_id']}/messages?limit=20", None, {
"Authorization": f"Bearer {actor['token']}",
"Accept": "application/json",
})
resp = conn.getresponse()
_ = resp.read()
ok = resp.status == 200
else:
is_write = True
payload = json.dumps({"text": f"m-{wid}-{i}"}).encode("utf-8")
conn.request("POST", f"/api/v1/chats/{actor['chat_id']}/messages", payload, {
"Authorization": f"Bearer {actor['token']}",
"Content-Type": "application/json",
"Accept": "application/json",
"Idempotency-Key": f"k-{wid}-{i}-{uuid.uuid4().hex[:8]}",
})
resp = conn.getresponse()
_ = resp.read()
ok = resp.status == 201
inst = resp.getheader("X-Instance-Id", "")
if inst:
insts.add(inst)
except Exception:
ok = False
try:
conn.close()
conn = http.client.HTTPConnection(host, port, timeout=10)
except Exception:
pass
t1 = time.monotonic()
if t0 >= record_after:
if ok:
lat = t1 - t0
latencies.append(lat)
if is_write:
write_latencies.append(lat)
else:
errors += 1
i += 1
conn.close()
return latencies, write_latencies, errors, insts
sampler_th = threading.Thread(target=stats_sampler)
sampler_th.start()
with ThreadPoolExecutor(max_workers=concurrency) as pool:
futs = [pool.submit(worker, wid) for wid in range(concurrency)]
barrier.wait()
res = [f.result() for f in futs]
sampler_th.join()
all_lat = sorted(x for lat, _, _, _ in res for x in lat)
w_lat = sorted(x for _, wl, _, _ in res for x in wl)
total_err = sum(e for _, _, e, _ in res)
all_inst = sorted({inst for _, _, _, insts in res for inst in insts})
total_ok = len(all_lat)
rps = round(total_ok / duration_s, 2)
result = {
"label": label,
"concurrency": concurrency,
"warmup_s": warmup_s,
"duration_s": duration_s,
"successful_requests": total_ok,
"failed_requests": total_err,
"error_rate": round(total_err / (total_ok + total_err), 5) if (total_ok + total_err) else 0.0,
"successful_rps": rps,
"latency_ms": {
"p50": percentile(all_lat, 0.50),
"p95": percentile(all_lat, 0.95),
"p99": percentile(all_lat, 0.99),
},
"write_latency_ms": {
"p50": percentile(w_lat, 0.50),
"p95": percentile(w_lat, 0.95),
"p99": percentile(w_lat, 0.99),
},
"observed_instances": all_inst,
"container_stats_midpoint": captured_stats,
}
print(f"[{label}] RPS={rps} ok={total_ok} err={total_err} p50={result['latency_ms']['p50']}ms p95={result['latency_ms']['p95']}ms p99={result['latency_ms']['p99']}ms instances={len(all_inst)}", flush=True)
return result
def generate_svg_chart(series_a, series_b, improvement):
# Clean SVG bar chart comparing Series A (Fixed Budget), Series B (Scaling + Saturation), Series C (Improvement)
items = (
[("A: 1x2.0c", series_a[0]["successful_rps"], "#3b82f6"),
("A: 2x1.0c", series_a[1]["successful_rps"], "#3b82f6"),
("A: 4x0.5c", series_a[2]["successful_rps"], "#3b82f6"),
("B: 1x0.5c", series_b[0]["successful_rps"], "#10b981"),
("B: 2x0.5c", series_b[1]["successful_rps"], "#10b981"),
("B: 4x0.5c", series_b[2]["successful_rps"], "#f59e0b"),
("Opt: 4x0.5c", improvement["after"]["successful_rps"], "#8b5cf6")]
)
max_rps = max(v for _, v, _ in items) or 100.0
width, height = 780, 360
pad_l, pad_b, pad_t = 70, 65, 50
chart_w = width - pad_l - 40
chart_h = height - pad_b - pad_t
bar_w = 64
gap = (chart_w - len(items) * bar_w) / (len(items) + 1)
lines = [
f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" viewBox="0 0 {width} {height}" style="background:#ffffff;font-family:sans-serif">',
' <text x="390" y="28" text-anchor="middle" font-size="16" font-weight="bold" fill="#111827">Lab 3 Track 1: Cost of Scaling &amp; Saturation Point (RPS)</text>',
f' <line x1="{pad_l}" y1="{pad_t}" x2="{pad_l}" y2="{pad_t + chart_h}" stroke="#9ca3af" stroke-width="1"/>',
f' <line x1="{pad_l}" y1="{pad_t + chart_h}" x2="{width - 30}" y2="{pad_t + chart_h}" stroke="#9ca3af" stroke-width="1"/>',
]
for i in range(5):
y = pad_t + chart_h - (chart_h * i / 4.0)
val = int(round(max_rps * i / 4.0))
lines.append(f' <line x1="{pad_l}" y1="{y:.1f}" x2="{width - 30}" y2="{y:.1f}" stroke="#e5e7eb" stroke-width="1"/>')
lines.append(f' <text x="{pad_l - 8}" y="{y + 4:.1f}" text-anchor="end" font-size="11" fill="#4b5563">{val}</text>')
for idx, (label, val, color) in enumerate(items):
x = pad_l + gap + idx * (bar_w + gap)
bh = (val / max_rps) * chart_h * 0.92
y = pad_t + chart_h - bh
lines.append(f' <rect x="{x:.1f}" y="{y:.1f}" width="{bar_w}" height="{bh:.1f}" rx="4" fill="{color}"/>')
lines.append(f' <text x="{x + bar_w / 2:.1f}" y="{y - 6:.1f}" text-anchor="middle" font-size="11" font-weight="bold" fill="#111827">{val:.1f}</text>')
lines.append(f' <text x="{x + bar_w / 2:.1f}" y="{pad_t + chart_h + 18}" text-anchor="middle" font-size="11" fill="#374151">{label}</text>')
lines.append(' <text x="390" y="346" text-anchor="middle" font-size="11" fill="#6b7280">Blue: Fixed 2.0 CPU Budget | Green: Resource Growth | Orange: DB Saturation | Purple: Batch Pipeline + Pool Tuning</text>')
lines.append("</svg>")
EVIDENCE_SVG.write_text("\n".join(lines) + "\n", encoding="utf-8")
def main():
report = {
"timestamp_utc": dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
"base_url": BASE_URL,
"series_a_fixed_budget": [],
"series_b_resource_growth": [],
"confirmed_improvement": {},
}
try:
# Series A: Fixed total API CPU=2.0, RAM=512M, DB=1.0 CPU
print("=== Series A: Fixed Total Budget (2.0 CPU, 512M RAM) ===")
for replicas, cpu, mem in [(1, "2.0", "512M"), (2, "1.0", "256M"), (4, "0.5", "128M")]:
apply_topology(replicas, cpu, mem, db_cpu="1.0", db_mem="512M", db_max_conns=12, write_mode="pipeline")
res = run_benchmark(f"A_fixed_{replicas}x{cpu}cpu", concurrency=16, warmup_s=2.0, duration_s=10.0)
res["config"] = {"replicas": replicas, "api_cpu": cpu, "api_mem": mem, "db_cpu": "1.0", "db_max_conns": 12, "write_mode": "pipeline"}
report["series_a_fixed_budget"].append(res)
# Series B: Resource growth per replica (0.5 CPU, 256M RAM each) vs DB=0.5 CPU (unoptimized sequential + pool=25)
print("=== Series B: Scaling with Resource Growth (0.5 CPU/replica vs 0.5 CPU DB) ===")
for replicas in [1, 2, 4]:
apply_topology(replicas, "0.5", "256M", db_cpu="0.5", db_mem="256M", db_max_conns=25, write_mode="sequential")
res = run_benchmark(f"B_growth_{replicas}x0.5cpu", concurrency=20, warmup_s=2.0, duration_s=10.0)
res["config"] = {"replicas": replicas, "api_cpu": "0.5", "api_mem": "256M", "db_cpu": "0.5", "db_max_conns": 25, "write_mode": "sequential"}
report["series_b_resource_growth"].append(res)
# Series C: Confirmed Improvement at 4-replica saturation point (same 4x0.5 CPU API vs 0.5 CPU DB)
print("=== Series C: Confirmed Improvement at 4-replica Saturation ===")
before = report["series_b_resource_growth"][-1]
apply_topology(4, "0.5", "256M", db_cpu="0.5", db_mem="256M", db_max_conns=8, write_mode="pipeline")
after = run_benchmark("C_optimized_4x0.5cpu", concurrency=20, warmup_s=2.0, duration_s=10.0)
after["config"] = {"replicas": 4, "api_cpu": "0.5", "api_mem": "256M", "db_cpu": "0.5", "db_max_conns": 8, "write_mode": "pipeline"}
rps_gain_pct = round(((after["successful_rps"] - before["successful_rps"]) / before["successful_rps"]) * 100.0, 2)
p95_delta_pct = round(((after["latency_ms"]["p95"] - before["latency_ms"]["p95"]) / before["latency_ms"]["p95"]) * 100.0, 2)
report["confirmed_improvement"] = {
"change": "Enabled pgx.Batch SQL pipelining in CreateMessage tx (5 RTT -> 2 RTT) and tuned DB_MAX_CONNS per replica (25 -> 8, limiting total connections from 100 to 32 against 0.5 CPU PostgreSQL)",
"before": before,
"after": after,
"rps_change_percent": rps_gain_pct,
"p95_latency_change_percent": p95_delta_pct,
}
EVIDENCE_JSON.parent.mkdir(parents=True, exist_ok=True)
EVIDENCE_JSON.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
generate_svg_chart(report["series_a_fixed_budget"], report["series_b_resource_growth"], report["confirmed_improvement"])
print(f"PASS: Track 1 scaling benchmark complete. RPS delta: {rps_gain_pct:+.2f}%, p95 delta: {p95_delta_pct:+.2f}%")
finally:
print("Restoring default 2-replica Lab 3 topology...")
apply_topology(2, "1.0", "256M", db_cpu="1.0", db_mem="512M", db_max_conns=12, write_mode="pipeline")
if __name__ == "__main__":
main()