Files
mtusi2026lab5/tests/track1_benchmark.py
T

421 lines
11 KiB
Python

"""Track 1 benchmark: image processing throughput, latency and memory."""
import csv
from concurrent.futures import ThreadPoolExecutor, as_completed
import datetime as dt
import json
import re
import subprocess
import threading
import time
from pathlib import Path
from tests.client import Client, Failure, arguments, check, run
ROOT = Path(__file__).resolve().parents[1]
FIXTURES = ROOT / "tests" / "fixtures"
IMAGE_SIZES = ("small", "medium", "large")
COMPLETION_RE = re.compile(
r"Image processing completed: attachment=(\S+) "
r"attempt=(\d+) queue_lag_ms=([\d.]+) "
r"processing_elapsed_ms=([\d.]+)"
)
def percentile(values, percentile_value):
"""Nearest-rank percentile."""
if not values:
return None
ordered = sorted(values)
index = max(
0,
min(
len(ordered) - 1,
int((percentile_value / 100) * len(ordered) + 0.999999) - 1,
),
)
return ordered[index]
def memory_to_mib(value):
match = re.match(r"([\d.]+)\s*(B|KiB|MiB|GiB|KB|MB|GB)", value)
if not match:
return None
number = float(match.group(1))
unit = match.group(2)
factors = {
"B": 1 / (1024 * 1024),
"KiB": 1 / 1024,
"MiB": 1,
"GiB": 1024,
"KB": 1000 / (1024 * 1024),
"MB": 1000 * 1000 / (1024 * 1024),
"GB": 1000 * 1000 * 1000 / (1024 * 1024),
}
return number * factors[unit]
class MemorySampler:
"""Samples aggregate worker container memory using docker stats."""
def __init__(self, container_name):
self.container_name = container_name
self.peak_mib = 0.0
self.error = None
self.stop_event = threading.Event()
self.thread = threading.Thread(target=self._sample, daemon=True)
def start(self):
self.thread.start()
def _sample(self):
while not self.stop_event.is_set():
try:
result = subprocess.run(
[
"docker",
"stats",
"--no-stream",
"--format",
"{{.MemUsage}}",
self.container_name,
],
capture_output=True,
text=True,
timeout=10,
check=True,
)
usage = result.stdout.strip().split("/")[0].strip()
value = memory_to_mib(usage)
if value is not None:
self.peak_mib = max(self.peak_mib, value)
except Exception as exc:
self.error = type(exc).__name__
self.stop_event.wait(0.5)
def stop(self):
self.stop_event.set()
self.thread.join(timeout=12)
def read_worker_metrics(since):
"""Read queue lag and processing duration from worker logs."""
result = subprocess.run(
[
"docker",
"compose",
"--env-file",
".env",
"logs",
"--since",
since,
"worker",
],
capture_output=True,
text=True,
timeout=30,
)
if result.returncode != 0:
raise Failure("could not read worker logs")
metrics = {}
for line in result.stdout.splitlines():
match = COMPLETION_RE.search(line)
if not match:
continue
attachment_id, attempt, queue_lag, processing_elapsed = (
match.groups()
)
metrics[attachment_id] = {
"attempt": int(attempt),
"queue_lag_ms": float(queue_lag),
"processing_elapsed_ms": float(processing_elapsed),
}
return metrics
def upload_and_wait(
size_name,
image_bytes,
actor,
chat,
base_url,
ca_file,
wait_seconds,
):
client = Client(base_url=base_url, ca_file=ca_file)
filename = f"{size_name}.jpg"
path = (
f"/api/v1/chats/{chat['id']}/attachments"
f"?filename={filename}"
)
started = time.monotonic()
upload_attempts = 0
while True:
upload_attempts += 1
response = client.call(
"POST",
path,
expected=[202, 429],
actor=actor,
raw=image_bytes,
headers={"Content-Type": "image/jpeg"},
schema="Attachment",
)
if response["status"] == 202:
attachment = response["json"]
break
retry_after = response["headers"].get("Retry-After", "1")
try:
delay = max(1.0, float(retry_after))
except ValueError:
delay = 1.0
time.sleep(min(delay, 10.0))
check(
attachment["status"] == "queued",
"upload did not return queued attachment",
)
ready = client.wait_ready(
actor,
attachment,
wait_seconds=wait_seconds,
)
elapsed = time.monotonic() - started
return {
"size": size_name,
"attachment_id": attachment["id"],
"time_to_ready_s": elapsed,
"upload_attempts": upload_attempts,
"final_status": ready["status"],
}
def main():
def configure(parser):
parser.add_argument("--config", required=True, choices=["A", "B", "C"])
parser.add_argument("--per-size", type=int, default=6)
parser.add_argument("--upload-concurrency", type=int, default=4)
parser.add_argument("--wait-seconds", type=int, default=180)
parser.add_argument(
"--worker-container",
default="mtusi2026lab5-worker-1",
)
parser.add_argument("--output", default=None)
args = arguments(
"Track 1 image processing benchmark",
configure,
)
check(args.per_size >= 1, "--per-size must be positive")
check(
args.upload_concurrency >= 1,
"--upload-concurrency must be positive",
)
images = {
name: (FIXTURES / f"{name}.jpg").read_bytes()
for name in IMAGE_SIZES
}
for name, content in images.items():
check(bool(content), f"{name}.jpg is empty")
bootstrap_client = Client(
base_url=args.base_url,
ca_file=args.ca_file,
)
alice, _, _, chat = bootstrap_client.bootstrap()
tasks = [
(name, images[name])
for name in IMAGE_SIZES
for _ in range(args.per_size)
]
log_since = (
dt.datetime.now(dt.timezone.utc)
- dt.timedelta(seconds=2)
).isoformat()
sampler = MemorySampler(args.worker_container)
sampler.start()
benchmark_started = time.monotonic()
results = []
try:
with ThreadPoolExecutor(
max_workers=args.upload_concurrency
) as executor:
futures = [
executor.submit(
upload_and_wait,
name,
content,
alice,
chat,
args.base_url,
args.ca_file,
args.wait_seconds,
)
for name, content in tasks
]
for future in as_completed(futures):
results.append(future.result())
finally:
benchmark_elapsed = time.monotonic() - benchmark_started
sampler.stop()
worker_metrics = read_worker_metrics(log_since)
for result in results:
result.update(
worker_metrics.get(
result["attachment_id"],
{},
)
)
completed = [
item for item in results
if item["final_status"] == "ready"
]
check(
len(completed) == len(tasks),
"not all benchmark images reached ready",
)
ready_times = [
item["time_to_ready_s"] for item in completed
]
throughput = len(completed) / benchmark_elapsed
p95_ready = percentile(ready_times, 95)
queue_lags = [
item["queue_lag_ms"]
for item in completed
if "queue_lag_ms" in item
]
processing_times = [
item["processing_elapsed_ms"]
for item in completed
if "processing_elapsed_ms" in item
]
output = args.output or f"evidence/track1_{args.config}.csv"
output_path = ROOT / output
output_path.parent.mkdir(parents=True, exist_ok=True)
fields = [
"config",
"size",
"attachment_id",
"time_to_ready_s",
"queue_lag_ms",
"processing_elapsed_ms",
"upload_attempts",
"throughput_rps",
"p95_time_to_ready_s",
"peak_container_memory_mib",
]
with output_path.open(
"w",
newline="",
encoding="utf-8-sig",
) as file:
writer = csv.DictWriter(file, fieldnames=fields)
writer.writeheader()
for item in results:
writer.writerow(
{
"config": args.config,
"size": item["size"],
"attachment_id": item["attachment_id"],
"time_to_ready_s": round(
item["time_to_ready_s"], 4
),
"queue_lag_ms": item.get("queue_lag_ms", ""),
"processing_elapsed_ms": item.get(
"processing_elapsed_ms", ""
),
"upload_attempts": item["upload_attempts"],
"throughput_rps": round(throughput, 4),
"p95_time_to_ready_s": round(p95_ready, 4),
"peak_container_memory_mib": round(
sampler.peak_mib, 2
),
}
)
print()
print(f"Configuration: {args.config}")
print(f"Completed: {len(completed)}/{len(tasks)}")
print(f"Duration: {benchmark_elapsed:.2f} s")
print(f"Throughput: {throughput:.3f} images/s")
print(f"p95 time-to-ready: {p95_ready:.3f} s")
print(
"Average queue lag: "
+ (
f"{sum(queue_lags) / len(queue_lags):.2f} ms"
if queue_lags else "not available"
)
)
print(
"Average processing time: "
+ (
f"{sum(processing_times) / len(processing_times):.2f} ms"
if processing_times else "not available"
)
)
print(
f"Peak worker container memory: {sampler.peak_mib:.2f} MiB"
)
if sampler.error:
print(f"Memory sampler warning: {sampler.error}")
missing_metrics = len(completed) - len(queue_lags)
if missing_metrics:
print(f"WARNING: metrics missing for {missing_metrics} jobs")
print(f"CSV: {output_path}")
if __name__ == "__main__":
run(main)