Complete lab 5 asynchronous image processing

This commit is contained in:
sinveria
2026-11-10 18:51:02 +03:00
parent 276dbdad8a
commit 115223f920
69 changed files with 7706 additions and 31 deletions
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 543 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 89 KiB

+55
View File
@@ -0,0 +1,55 @@
"""Generate deterministic image fixtures for Track 1 benchmarks."""
import random
from pathlib import Path
from PIL import Image
ROOT = Path(__file__).resolve().parent / "fixtures"
SIZES = {
"small": (640, 480),
"medium": (1600, 1200),
"large": (3000, 2000),
}
def generate_image(name: str, width: int, height: int) -> None:
rng = random.Random(42)
image = Image.new("RGB", (width, height))
pixels = image.load()
for y in range(height):
for x in range(width):
noise = rng.randrange(0, 24)
pixels[x, y] = (
(x * 255 // width + noise) % 256,
(y * 255 // height + noise) % 256,
((x + y) * 255 // (width + height) + noise) % 256,
)
path = ROOT / f"{name}.jpg"
image.save(
path,
format="JPEG",
quality=85,
optimize=True,
)
print(
f"{name}: {width}x{height}, "
f"{path.stat().st_size} bytes"
)
def main() -> None:
ROOT.mkdir(parents=True, exist_ok=True)
for name, (width, height) in SIZES.items():
generate_image(name, width, height)
if __name__ == "__main__":
main()
+69
View File
@@ -0,0 +1,69 @@
#!/usr/bin/env python3
"""Verify the API admission limit while the worker is stopped."""
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, arguments, check, run
def main():
args = arguments("Backpressure admission-limit test")
client = Client(args.base_url, args.ca_file)
alice, bob, eve, chat = client.bootstrap()
content = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
upload_path = (
"/api/v1/chats/" + chat["id"]
+ "/attachments?filename=backpressure.png"
)
headers = {"Content-Type": "image/png"}
accepted = []
print("Uploading 20 attachments...")
for number in range(1, 21):
result = client.call(
"POST",
upload_path,
expected=202,
actor=alice,
raw=content,
headers=headers,
schema="Attachment",
)
attachment = result["json"]
check(
attachment["status"] == "queued",
"accepted attachment is not queued",
)
accepted.append(attachment["id"])
print(f"Accepted {number}/20: {attachment['id']}")
print("Sending the 21st attachment...")
rejected = client.call(
"POST",
upload_path,
expected=429,
actor=alice,
raw=content,
headers=headers,
)
check(rejected["status"] == 429, "expected HTTP 429")
print("PASS: 20 attachments accepted; the 21st was rejected with HTTP 429.")
print("Accepted attachment IDs:")
for attachment_id in accepted:
print(attachment_id)
if __name__ == "__main__":
run(main)
+52
View File
@@ -0,0 +1,52 @@
import io
from PIL import Image
from app.services.image_processor import (
ImageProcessingTimeout,
create_variants_with_timeout,
)
def make_test_image() -> bytes:
output = io.BytesIO()
image = Image.new("RGB", (640, 400), (120, 160, 200))
image.save(output, format="PNG")
return output.getvalue()
def main() -> None:
image_data = make_test_image()
print("Test 1: normal image processing")
variants = create_variants_with_timeout(
image_data,
timeout_seconds=30,
)
names = sorted(variant.name for variant in variants)
assert names == ["crop", "optimized", "thumbnail"], names
print(f"PASS: created variants: {names}")
print("Test 2: forced processing timeout")
try:
create_variants_with_timeout(
image_data,
timeout_seconds=0.001,
)
except ImageProcessingTimeout:
print("PASS: child process was terminated after timeout")
else:
raise AssertionError("Expected ImageProcessingTimeout")
print("ALL TESTS PASSED")
if __name__ == "__main__":
main()
+420
View File
@@ -0,0 +1,420 @@
"""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)