ЛР 5 — БВТ2301 — Курлова — на 5

RabbitMQ + transactional outbox, отдельный worker (thumbnail/crop/WebP), lease и heartbeat, retry с backoff+jitter, DLQ и replay, admission control; тесты отказов, трек 1 и отчёт.
This commit is contained in:
alenchha
2026-11-06 12:10:16 +03:00
parent 276dbdad8a
commit 633fb96920
57 changed files with 5194 additions and 22 deletions
+250
View File
@@ -0,0 +1,250 @@
#!/usr/bin/env python3
"""Track 1: the queue under load. Open-loop upload arrivals against the running stack, metrics from the DB.
Each run:
1. (re)creates the worker service with WORKER_REPLICAS / WORKER_CONCURRENCY / WORKER_PREFETCH
2. sends uploads at a FIXED arrival rate (open loop: the schedule does not wait for responses)
3. samples worker container memory (docker stats) and accepted-but-unfinished jobs once per second
4. waits until every accepted upload is ready/failed and computes from attachment_jobs:
queue lag = first_started_at - created_at (time a job waited for a worker)
time to ready = finished_at - attachment.created_at
throughput = finished jobs / (last finish - first arrival)
Rejections (503 queue_full from admission control) are counted, not retried.
python3 student-tests/queue_load.py run --size medium --rate 4 --duration 30 --concurrency 2 --prefetch 2
python3 student-tests/queue_load.py overload --max-pending 30 --size medium --rate 12 --duration 30
Results are appended as JSON lines to evidence/track1/results.jsonl.
"""
import argparse
import json
import os
import statistics
import subprocess
import threading
import time
import uuid
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from urllib.parse import quote
from stand import ROOT, Client, Failure, compose, log, sql, wait_http_ready
OUT = ROOT / "evidence/track1"
SIZES = {"small": (640, 400, "JPEG"), "medium": (4000, 3000, "JPEG"), "large": (6000, 4000, "PNG")}
GEN = r'''
import io, random, sys
from PIL import Image, ImageChops, ImageDraw
w, h, fmt = int(sys.argv[1]), int(sys.argv[2]), sys.argv[3]
if fmt == "JPEG": # photo-like noise: realistic JPEG sizes
chan = [Image.effect_noise((max(8, w // 24), max(8, h // 24)), 90).resize((w, h), Image.Resampling.BICUBIC) for _ in range(3)]
grain = Image.effect_noise((w, h), 12)
img = Image.merge("RGB", [ImageChops.add(c, grain, 1.0, -6) for c in chan])
else: # graphics-like PNG: compresses well (stays under 10 MiB) but must be fully decoded (no DCT scaling)
img = Image.linear_gradient("L").resize((w, h)).convert("RGB")
draw, rnd = ImageDraw.Draw(img), random.Random(1)
for _ in range(400):
x, y, r = rnd.randrange(w), rnd.randrange(h), rnd.randrange(20, 300)
draw.ellipse((x, y, x + r, y + r), fill=(rnd.randrange(256), rnd.randrange(256), rnd.randrange(256)))
buf = io.BytesIO()
img.save(buf, fmt, **({"quality": 90} if fmt == "JPEG" else {"compress_level": 6}))
sys.stdout.buffer.write(buf.getvalue())
'''
def image(size):
w, h, fmt = SIZES[size]
cache = OUT / ("fixture-%s.%s" % (size, fmt.lower()))
if not cache.exists():
OUT.mkdir(parents=True, exist_ok=True)
data = subprocess.run(["docker", "compose", "exec", "-T", "api-1", "python", "-c", GEN, str(w), str(h), fmt],
cwd=ROOT, capture_output=True, check=True).stdout
cache.write_bytes(data)
return cache.read_bytes(), "image/png" if fmt == "PNG" else "image/jpeg"
def set_worker(replicas, concurrency, prefetch, cpus="2.00"):
env = dict(os.environ, WORKER_REPLICAS=str(replicas), WORKER_CONCURRENCY=str(concurrency),
WORKER_PREFETCH=str(prefetch), WORKER_CPUS=cpus)
subprocess.run(["docker", "compose", "--env-file", ".env", "up", "-d", "--no-deps", "--wait", "worker"],
cwd=ROOT, env=env, check=True, capture_output=True, timeout=180)
def set_admission(max_pending):
env = dict(os.environ, MAX_PENDING_JOBS=str(max_pending))
subprocess.run(["docker", "compose", "--env-file", ".env", "up", "-d", "--no-deps", "--wait", "api-1", "api-2"],
cwd=ROOT, env=env, check=True, capture_output=True, timeout=180)
def parse_mem(text):
value = text.split("/")[0].strip()
for unit, mult in (("GiB", 1024), ("MiB", 1), ("KiB", 1 / 1024), ("B", 1 / 1048576)):
if value.endswith(unit):
return float(value[: -len(unit)]) * mult
return 0.0
class Sampler(threading.Thread):
def __init__(self, tag):
super().__init__(daemon=True)
self.tag = tag
self.stop = threading.Event()
self.rss, self.pending, self.cpu = [], [], []
def run(self):
while not self.stop.is_set():
ids = compose("ps", "-q", "worker", check_rc=False).split()
if ids:
out = subprocess.run(["docker", "stats", "--no-stream", "--format", "{{.MemUsage}}|{{.CPUPerc}}", *ids],
capture_output=True, text=True).stdout
rows = [line.split("|") for line in out.splitlines() if "|" in line]
self.rss.append(sum(parse_mem(r[0]) for r in rows))
self.cpu.append(sum(float(r[1].rstrip("%") or 0) for r in rows))
try:
self.pending.append(int(sql("SELECT count(*) FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id"
" WHERE a.filename LIKE 'load-%s-%%' AND j.state IN ('queued','processing')"
% self.tag)[0][0]))
except Exception:
pass
self.stop.wait(1.0)
def pct(values, q):
if not values:
return None
values = sorted(values)
return round(values[min(len(values) - 1, int(round(q * (len(values) - 1))))], 3)
def drive(c, actor, chat, body, ctype, rate, duration, tag):
"""Open-loop: request i is sent at t0 + i/rate regardless of earlier responses."""
total = int(rate * duration)
results = {"accepted": 0, "rejected_503": 0, "other_errors": 0}
lock = threading.Lock()
def one(i):
path = "/api/v1/chats/%s/attachments?filename=%s" % (chat["id"], quote("load-%s-%05d.img" % (tag, i)))
try:
r = c.call("POST", path, [202, 503], actor=actor, raw=body, headers={"Content-Type": ctype})
key = "accepted" if r["status"] == 202 else "rejected_503"
except Exception: # connection errors, timeouts: counted, never retried
key = "other_errors"
with lock:
results[key] += 1
t0 = time.monotonic()
with ThreadPoolExecutor(max_workers=64) as pool:
for i in range(total):
delay = t0 + i / rate - time.monotonic()
if delay > 0:
time.sleep(delay)
pool.submit(one, i)
results["send_seconds"] = round(time.monotonic() - t0, 2)
results["offered"] = total
return results
def wait_drained(tag, seconds):
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
left = int(sql("SELECT count(*) FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id"
" WHERE a.filename LIKE 'load-%s-%%' AND j.state IN ('queued','processing')" % tag)[0][0])
if left == 0:
return True
time.sleep(1)
return False
def job_metrics(tag):
rows = sql(
"SELECT extract(epoch FROM a.created_at), extract(epoch FROM j.first_started_at), extract(epoch FROM j.finished_at),"
" j.state, j.attempt FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id"
" WHERE a.filename LIKE 'load-%s-%%'" % tag)
done = [(float(a), float(s), float(f)) for a, s, f, st, _ in rows if st == "succeeded"]
lag = [s - a for a, s, f in done]
ttr = [f - a for a, s, f in done]
span = (max(f for _, _, f in done) - min(a for a, _, _ in done)) if done else 0
return {
"succeeded": len(done), "failed": sum(1 for r in rows if r[3] == "failed"),
"retries": sum(int(r[4]) - 1 for r in rows),
"throughput_jobs_s": round(len(done) / span, 3) if span else None,
"lag_p50_s": pct(lag, 0.5), "lag_p95_s": pct(lag, 0.95), "lag_max_s": pct(lag, 1.0),
"ttr_p50_s": pct(ttr, 0.5), "ttr_p95_s": pct(ttr, 0.95), "ttr_max_s": pct(ttr, 1.0),
}
def record(summary):
OUT.mkdir(parents=True, exist_ok=True)
with open(OUT / "results.jsonl", "a") as handle:
handle.write(json.dumps(summary, ensure_ascii=False) + "\n")
log(json.dumps(summary, ensure_ascii=False))
def experiment(args, label, max_pending=None):
c = Client(timeout=60)
wait_http_ready(c)
alice = c.user("load")
chat = c.call("POST", "/api/v1/chats", 201, actor=alice, body={"title": "load", "member_ids": [alice["id"]]},
schema="Chat")["json"]
body, ctype = image(args.size)
set_worker(args.replicas, args.concurrency, args.prefetch)
time.sleep(2)
tag = uuid.uuid4().hex[:8]
sampler = Sampler(tag)
sampler.start()
log("run %s tag=%s size=%s (%d KiB) rate=%s/s duration=%ss workers=%dx(c=%d,p=%d)" % (
label, tag, args.size, len(body) >> 10, args.rate, args.duration, args.replicas, args.concurrency, args.prefetch))
sent = drive(c, alice, chat, body, ctype, args.rate, args.duration, tag)
load_end = time.monotonic()
drained = wait_drained(tag, args.drain_timeout)
drain_seconds = round(time.monotonic() - load_end, 2)
sampler.stop.set()
sampler.join()
summary = {"label": label, "tag": tag, "size": args.size, "file_kib": len(body) >> 10, "rate": args.rate,
"duration": args.duration, "replicas": args.replicas, "concurrency": args.concurrency,
"prefetch": args.prefetch, "max_pending": max_pending, **sent, "drained": drained,
"drain_after_load_s": drain_seconds, **job_metrics(tag),
"pending_max": max(sampler.pending or [0]),
"worker_mem_peak_mib": round(max(sampler.rss or [0]), 1),
"worker_mem_median_mib": round(statistics.median(sampler.rss), 1) if sampler.rss else None,
"worker_cpu_peak_pct": round(max(sampler.cpu or [0]), 1),
"at": time.strftime("%Y-%m-%dT%H:%M:%S")}
return summary, c, alice, chat
def main():
parser = argparse.ArgumentParser()
parser.add_argument("mode", choices=["run", "overload"])
parser.add_argument("--size", choices=sorted(SIZES), default="medium")
parser.add_argument("--rate", type=float, default=4)
parser.add_argument("--duration", type=float, default=30)
parser.add_argument("--replicas", type=int, default=1)
parser.add_argument("--concurrency", type=int, default=2)
parser.add_argument("--prefetch", type=int, default=2)
parser.add_argument("--max-pending", type=int, default=30)
parser.add_argument("--drain-timeout", type=float, default=600)
parser.add_argument("--label", default="")
args = parser.parse_args()
if args.mode == "run":
summary, *_ = experiment(args, args.label or "c%d-p%d" % (args.concurrency, args.prefetch))
record(summary)
return
# Overload: admission limit on, offered rate far above capacity, then recovery.
set_admission(args.max_pending)
try:
summary, c, alice, chat = experiment(args, args.label or "overload", args.max_pending)
# Recovery probe: after the backlog drained, a fresh upload must be ready quickly again.
body, ctype = image("small")
t = time.monotonic()
att = c.call("POST", "/api/v1/chats/%s/attachments?filename=probe.png" % chat["id"], 202, actor=alice, raw=body,
headers={"Content-Type": ctype}, schema="Attachment")["json"]
while c.call("GET", "/api/v1/attachments/" + att["id"], actor=alice, schema="Attachment")["json"]["status"] != "ready":
time.sleep(0.2)
summary["recovery_probe_ready_s"] = round(time.monotonic() - t, 2)
record(summary)
finally:
set_admission(200)
if __name__ == "__main__":
main()
+132
View File
@@ -0,0 +1,132 @@
"""Helpers for student resilience tests: the public HTTP client plus docker compose / psql / mc access.
Standard library only (Python 3.9+). Images that need Pillow are generated inside the API container.
Never prints tokens or secrets.
"""
import json
import subprocess
import sys
import time
import uuid
from pathlib import Path
from urllib.parse import quote
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check, run # noqa: E402,F401
SAMPLE = (ROOT / "tests/fixtures/sample.png").read_bytes()
def log(*parts):
print(time.strftime("%H:%M:%S"), *parts, flush=True)
def compose(*args, check_rc=True, capture=True, timeout=180):
done = subprocess.run(["docker", "compose", *args], cwd=ROOT, capture_output=capture, text=True, timeout=timeout)
if check_rc and done.returncode != 0:
raise Failure("docker compose %s failed: %s" % (" ".join(args[:2]), (done.stderr or "")[-300:]))
return done.stdout if capture else ""
def started_at(*services):
"""Container name -> State.StartedAt, proof that a restart really happened."""
ids = compose("ps", "-q", *services).split()
out = subprocess.run(["docker", "inspect", "-f", "{{.Name}} {{.State.StartedAt}}", *ids],
capture_output=True, text=True).stdout
return "; ".join(line.strip("/")[:60] for line in out.splitlines())
def sql(query):
"""Run a read query in postgres; returns rows as lists of strings (tab separated)."""
out = compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-At", "-F", "\t", "-c", query)
return [line.split("\t") for line in out.splitlines() if line]
def s3_keys(prefix):
"""Object keys starting with prefix, listed with the root credentials inside a throwaway minio-init container."""
wanted, prefix = prefix, prefix[:prefix.rfind("/") + 1]
script = ('mc alias set l http://minio:9000 "$(cat /run/secrets/minio_root_user)" '
'"$(cat /run/secrets/minio_root_password)" >/dev/null && '
'mc ls --recursive --json l/messenger-attachments/%s || true' % prefix)
out = compose("run", "--rm", "--no-deps", "-T", "--entrypoint", "sh", "minio-init", "-c", script)
keys = []
for line in out.splitlines():
try:
item = json.loads(line)
except ValueError:
continue
if item.get("key"):
keys.append(prefix + item["key"])
return sorted(k for k in keys if k.startswith(wanted))
def queue_depth(queue="attachments.process"):
out = compose("exec", "-T", "rabbitmq", "rabbitmqctl", "-q", "--vhost", "messenger", "list_queues",
"name", "messages", "messages_ready", "messages_unacknowledged")
for line in out.splitlines():
parts = line.split()
if parts and parts[0] == queue:
return {"messages": int(parts[1]), "ready": int(parts[2]), "unacked": int(parts[3])}
return None
def wait_queue(min_ready=1, seconds=30):
"""Quorum queue counters are refreshed by the stats emitter (~5 s), so poll."""
deadline = time.monotonic() + seconds
depth = None
while time.monotonic() < deadline:
depth = queue_depth()
if depth and depth["ready"] >= min_ready:
return depth
time.sleep(1)
return depth
def jobs_cli(*args):
done = subprocess.run(["docker", "compose", "exec", "-T", "api-1", "python", "scripts/jobs.py", *args],
cwd=ROOT, capture_output=True, text=True, timeout=60)
return done.returncode, json.loads(done.stdout) if done.stdout.strip() else None
def wait_http_ready(c, seconds=120):
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
try:
c.call("GET", "/health/ready", 200)
return
except Failure:
time.sleep(1)
raise Failure("API not ready after %ds" % seconds)
def upload(c, actor, chat, body=SAMPLE, filename="sample.png", ctype="image/png", expected=202):
path = "/api/v1/chats/%s/attachments?filename=%s" % (chat["id"], quote(filename, safe=""))
schema = "Attachment" if expected == 202 else None
return c.call("POST", path, expected, actor=actor, raw=body, headers={"Content-Type": ctype}, schema=schema)["json"]
def get(c, actor, att_id):
return c.call("GET", "/api/v1/attachments/" + att_id, actor=actor, schema="Attachment")["json"]
def wait_status(c, actor, att_id, statuses, seconds=120):
deadline = time.monotonic() + seconds
seen = []
while time.monotonic() < deadline:
att = get(c, actor, att_id)
if not seen or seen[-1] != att["status"]:
seen.append(att["status"])
if att["status"] in statuses:
return att, seen
time.sleep(0.5)
raise Failure("attachment %s did not reach %s in %ds (seen %s)" % (att_id, statuses, seconds, seen))
def objects_of(att_id):
return s3_keys("attachments/%s/" % att_id) + s3_keys("staging/%s" % att_id)
def unique_name(fault=None):
tag = uuid.uuid4().hex[:8]
return ("fault-%s-%s.png" % (fault, tag)) if fault else ("plain-%s.png" % tag)
+194
View File
@@ -0,0 +1,194 @@
#!/usr/bin/env python3
"""Grade 4 fault-injection suite (needs FAULT_INJECTION=1 on the stand, see REPORT.md).
Each scenario uploads a file whose display name selects an injected fault (app/faults.py) and checks the
recovery through the public API plus DB/S3/broker state:
A api_crash_after_commit crash between COMMIT(job+outbox) and publish -> another replica's relay publishes
B worker_crash_after_put crash after S3 writes, before result COMMIT -> lease expiry -> same keys, one result
C worker_crash_after_commit crash after COMMIT, before ack -> redelivery is a no-op
D transient3 3 transient errors -> retries with growing jittered backoff -> ready
E permanent permanent error -> failed at attempt 1, no retry, content/attach 409
F transient6 attempts exhausted -> failed/retry_exhausted -> registry -> explicit replay -> ready;
replay of a ready job is refused
G worker_hang hung worker (no heartbeats) -> other worker takes over, hung one is fenced
H poison message invalid broker message -> DLQ, not retried forever
I broker down RabbitMQ stopped: upload still 202 (job waits in outbox) -> broker back -> ready
usage: python3 student-tests/test_failure_windows.py [A B C ...]
"""
import sys
import time
from stand import (Client, Failure, check, compose, get, jobs_cli, log, objects_of, queue_depth, run, sql, upload,
unique_name, wait_http_ready, wait_status)
def audit(att_id):
return sql("SELECT action, actor, attempt, coalesce(detail->>'error_code',''), coalesce(detail->>'delay_seconds','')"
" FROM job_audit WHERE attachment_id='%s' ORDER BY id" % att_id)
def show_audit(att_id):
for action, actor, attempt, code, delay in audit(att_id):
log(" audit attempt=%s %-16s %-28s %s %s" % (attempt, action, actor[:28], code, ("delay=%ss" % delay) if delay else ""))
def one_result(att_id):
variants = sql("SELECT count(*) FROM attachment_variants WHERE attachment_id='%s'" % att_id)[0][0]
succeeded = sql("SELECT count(*) FROM job_audit WHERE attachment_id='%s' AND action='succeeded'" % att_id)[0][0]
keys = objects_of(att_id)
check(variants == "3", "exactly one set of 3 variant rows, got %s" % variants)
check(succeeded == "1", "exactly one committed success, got %s" % succeeded)
check(len(keys) == 4 and not any(k.startswith("staging/") for k in keys),
"original + 3 variants, staging cleaned: %s" % keys)
def ready_and_single(c, actor, att_id, seconds=120):
att, seen = wait_status(c, actor, att_id, ("ready", "failed"), seconds)
check(att["status"] == "ready", "expected ready, got %s/%s" % (att["status"], att["error_code"]))
log(" statuses:", " -> ".join(seen))
show_audit(att_id)
one_result(att_id)
return att
def scenario_a(c, alice, bob, chat):
name = unique_name("api_crash_after_commit")
try:
upload(c, alice, chat, filename=name, expected=[202, 500, 502, 503])
except Failure as exc:
log(" client saw:", exc)
wait_http_ready(c)
rows = sql("SELECT id FROM attachments WHERE filename='%s'" % name)
check(len(rows) == 1, "committed attachment must exist after API crash")
att_id = rows[0][0]
log(" committed attachment %s survived the API crash" % att_id)
ready_and_single(c, bob, att_id)
pub = sql("SELECT count(*) FROM outbox o JOIN attachment_jobs j ON j.id=o.job_id"
" WHERE j.attachment_id='%s' AND o.published_at IS NOT NULL" % att_id)[0][0]
check(pub == "1", "outbox row published exactly once by the relay")
def scenario_b(c, alice, bob, chat):
att = upload(c, alice, chat, filename=unique_name("worker_crash_after_put"))
ready_and_single(c, bob, att["id"])
actions = [r[0] for r in audit(att["id"])]
check("retry_scheduled" in actions, "lease expiry must schedule a new attempt")
def scenario_c(c, alice, bob, chat):
att = upload(c, alice, chat, filename=unique_name("worker_crash_after_commit"))
ready_and_single(c, bob, att["id"])
time.sleep(8)
logs = compose("logs", "--since", "60s", "worker")
check("decision=done" in logs, "redelivered message after crash must be a no-op")
one_result(att["id"])
def scenario_d(c, alice, bob, chat):
att = upload(c, alice, chat, filename=unique_name("transient3"))
ready_and_single(c, bob, att["id"])
delays = [float(r[4]) for r in audit(att["id"]) if r[0] == "retry_scheduled"]
check(len(delays) == 3, "three retries expected, got %s" % delays)
bounds = [(1, 2), (2, 4), (4, 8)]
check(all(lo <= d <= hi for d, (lo, hi) in zip(delays, bounds)), "equal-jitter backoff bounds %s" % delays)
log(" backoff delays:", delays)
def scenario_e(c, alice, bob, chat):
att = upload(c, alice, chat, filename=unique_name("permanent"))
failed, _ = wait_status(c, bob, att["id"], ("failed", "ready"), 60)
check(failed["status"] == "failed" and failed["error_code"] == "invalid_image", "permanent -> failed/invalid_image")
check(failed["variants"] == [], "failed attachment has no variants")
show_audit(att["id"])
check([r[0] for r in audit(att["id"])].count("claimed") == 1, "permanent errors are not retried")
c.call("GET", "/api/v1/attachments/%s/content" % att["id"], 409, actor=bob)
c.call("POST", "/api/v1/chats/%s/messages" % chat["id"], 409, actor=alice,
body={"text": "", "attachment_ids": [att["id"]]}, headers={"Idempotency-Key": "k-" + att["id"]})
def scenario_f(c, alice, bob, chat):
att = upload(c, alice, chat, filename=unique_name("transient6"))
failed, _ = wait_status(c, bob, att["id"], ("failed", "ready"), 120)
check(failed["status"] == "failed" and failed["error_code"] == "retry_exhausted", "exhausted -> retry_exhausted")
attempts = sql("SELECT attempt, max_attempts FROM attachment_jobs WHERE attachment_id='%s'" % att["id"])[0]
check(attempts == ["5", "5"], "bounded: stopped at attempt 5 of 5, got %s" % attempts)
rc, registry = jobs_cli("failed")
check(any(r["attachment_id"] == att["id"] for r in registry), "failed job listed in operator registry")
log(" failed registry contains the job; replay")
rc, result = jobs_cli("replay", att["id"], "--actor", "test-suite")
check(rc == 0 and result["result"] == "queued", "replay must queue: %s" % result)
ready_and_single(c, bob, att["id"], 120)
rc, result = jobs_cli("replay", att["id"], "--actor", "test-suite")
check(rc == 3 and result["result"] == "refused", "replay of a ready job must be refused: %s" % result)
log(" second replay refused:", result["reason"])
one_result(att["id"])
def scenario_g(c, alice, bob, chat):
att = upload(c, alice, chat, filename=unique_name("worker_hang"))
ready_and_single(c, bob, att["id"], 150)
rows = audit(att["id"])
check(any(r[0] == "retry_scheduled" and r[3] == "lease_expired" for r in rows), "lease expiry detected")
time.sleep(30) # the hung worker wakes up and must be fenced
logs = compose("logs", "--since", "180s", "worker")
check("lease lost" in logs or "result not committed" in logs, "hung worker must be fenced by the lease")
one_result(att["id"])
POISON = ("import asyncio, aio_pika\n"
"from app import config, broker\n"
"async def m():\n"
" conn = await broker.connect(); ch = await conn.channel(publisher_confirms=True)\n"
" ex, _ = await broker.declare(ch)\n"
" await ex.publish(aio_pika.Message(b'{not json', delivery_mode=2), routing_key=broker.ROUTING_KEY)\n"
" await conn.close()\n"
"asyncio.run(m())\n")
def scenario_h(c, alice, bob, chat):
before = (queue_depth("attachments.dlq") or {}).get("messages", 0)
compose("exec", "-T", "api-1", "python", "-c", POISON)
deadline = time.monotonic() + 30
after = before
while time.monotonic() < deadline and after <= before:
time.sleep(1)
after = (queue_depth("attachments.dlq") or {}).get("messages", 0)
check(after == before + 1, "poison message must land in attachments.dlq (%s -> %s)" % (before, after))
log(" DLQ depth %s -> %s" % (before, after))
def scenario_i(c, alice, bob, chat):
compose("stop", "-t", "10", "rabbitmq")
try:
att = upload(c, alice, chat, filename=unique_name())
check(att["status"] == "queued", "upload accepted while broker is down")
c.message(alice, chat, "", attachments=[att["id"]])
time.sleep(3)
pending = sql("SELECT count(*) FROM outbox o JOIN attachment_jobs j ON j.id=o.job_id"
" WHERE j.attachment_id='%s' AND o.published_at IS NULL" % att["id"])[0][0]
check(pending == "1", "job must wait in the outbox, got %s" % pending)
check(get(c, bob, att["id"])["status"] == "queued", "still queued while broker is down")
log(" broker down: upload 202, outbox holds 1 unpublished job")
finally:
compose("start", "rabbitmq")
ready_and_single(c, bob, att["id"], 120)
SCENARIOS = {"A": scenario_a, "B": scenario_b, "C": scenario_c, "D": scenario_d, "E": scenario_e,
"F": scenario_f, "G": scenario_g, "H": scenario_h, "I": scenario_i}
def main():
c = Client(timeout=30)
alice, bob, eve, chat = c.bootstrap()
picked = sys.argv[1:] or list(SCENARIOS)
for key in picked:
log("scenario %s: %s" % (key, SCENARIOS[key].__name__))
started = time.monotonic()
SCENARIOS[key](c, alice, bob, chat)
log("scenario %s PASS (%.1fs)" % (key, time.monotonic() - started))
print("PASS: failure windows %s" % " ".join(picked))
if __name__ == "__main__":
run(main)
+84
View File
@@ -0,0 +1,84 @@
#!/usr/bin/env python3
"""Grade 3 demo: worker stopped -> upload 202 -> message with attachment -> restart API + broker (volumes kept)
-> worker started -> ready + thumbnail. Then an explicit duplicate delivery of the finished job is a no-op.
python3 student-tests/test_worker_down.py (stack from REPORT.md must be running)
"""
import hashlib
import time
from stand import (Client, check, compose, started_at, get, log, objects_of, wait_queue, run, sql, upload, wait_http_ready,
wait_status, unique_name, SAMPLE)
def main():
c = Client()
alice, bob, eve, chat = c.bootstrap()
log("stop all workers")
compose("stop", "-t", "20", "worker")
try:
att = upload(c, alice, chat, filename=unique_name())
check(att["status"] == "queued" and att["variants"] == [] and att["error_code"] is None, "upload must be 202 queued")
log("upload 202 queued id=%s" % att["id"])
msg = c.message(alice, chat, "", attachments=[att["id"]])["json"]
check(msg["attachment_ids"] == [att["id"]], "message must reference the queued attachment")
log("message %s created with queued attachment" % msg["id"])
c.call("GET", "/api/v1/attachments/%s/content" % att["id"], 409, actor=bob)
c.call("GET", "/api/v1/attachments/%s/content?variant=thumbnail" % att["id"], 409, actor=bob)
c.message(bob, chat, "другие сообщения работают")
depth = wait_queue()
log("broker queue while worker is down:", depth)
check(depth and depth["ready"] >= 1, "job must be waiting in the broker")
unpublished = sql("SELECT count(*) FROM outbox o JOIN attachment_jobs j ON j.id=o.job_id"
" WHERE j.attachment_id='%s' AND o.published_at IS NULL" % att["id"])[0][0]
check(unpublished == "0", "outbox row must be published with confirm")
log("restart api-1 api-2 rabbitmq (volumes kept)")
before = started_at("api-1", "api-2", "rabbitmq")
compose("restart", "-t", "10", "rabbitmq", "api-1", "api-2")
wait_http_ready(c)
after = started_at("api-1", "api-2", "rabbitmq")
log("started before:", before)
log("started after: ", after)
check(before != after, "containers must really restart")
check(get(c, bob, att["id"])["status"] == "queued", "still queued after restart, nothing lost")
depth = wait_queue()
log("broker queue after broker restart:", depth)
check(depth and depth["ready"] >= 1, "durable message must survive broker restart")
finally:
log("start workers")
compose("start", "worker")
ready, seen = wait_status(c, bob, att["id"], ("ready", "failed"), 90)
check(ready["status"] == "ready", "expected ready, got %s" % ready["status"])
log("status sequence observed:", " -> ".join(seen))
names = sorted(v["name"] for v in ready["variants"])
check(names == ["crop", "optimized", "thumbnail"], "expected thumbnail+crop+optimized, got %s" % names)
thumb = [v for v in ready["variants"] if v["name"] == "thumbnail"][0]
check((thumb["width"], thumb["height"]) == (256, 160), "thumbnail 256x160")
body = c.call("GET", "/api/v1/attachments/%s/content?variant=thumbnail" % att["id"], actor=bob)["bytes"]
check(hashlib.sha256(body).hexdigest() == thumb["sha256"], "thumbnail checksum")
orig = c.call("GET", "/api/v1/attachments/%s/content" % att["id"], actor=bob)["bytes"]
check(orig == SAMPLE, "original unchanged byte for byte")
keys = objects_of(att["id"])
log("objects:", keys)
check(len(keys) == 4 and not any(k.startswith("staging/") for k in keys), "original + 3 variants, staging removed")
log("redelivery: republish the finished job through the outbox (duplicate message)")
sql("INSERT INTO outbox (job_id, payload, available_at, created_at) SELECT o.job_id, o.payload, now(), now()"
" FROM outbox o JOIN attachment_jobs j ON j.id=o.job_id WHERE j.attachment_id='%s' ORDER BY o.id LIMIT 1"
% att["id"])
time.sleep(5)
again = get(c, bob, att["id"])
check(again["status"] == "ready" and again["variants"] == ready["variants"], "duplicate must not change the result")
rows = sql("SELECT count(*) FROM attachment_variants WHERE attachment_id='%s'" % att["id"])[0][0]
succeeded = sql("SELECT count(*) FROM job_audit WHERE attachment_id='%s' AND action='succeeded'" % att["id"])[0][0]
check(rows == "3" and succeeded == "1", "one set of variants and one success (rows=%s succeeded=%s)" % (rows, succeeded))
check(len(objects_of(att["id"])) == 4, "no new objects after duplicate")
noop = compose("logs", "--since", "30s", "worker")
check("decision=done" in noop, "worker must log the duplicate as no-op")
log("duplicate acked as no-op: variants=%s successes=%s" % (rows, succeeded))
print("PASS: worker down / API+broker restart / redelivery no-op")
if __name__ == "__main__":
run(main)
+23
View File
@@ -0,0 +1,23 @@
#!/bin/sh
# Track 1 matrix: 3 sizes x 4 worker settings x REPEATS, then the overload/recovery scenario.
# One worker replica with a 2-CPU limit; offered rates are fixed per size (open loop, 30 s each).
set -eu
cd "$(dirname "$0")/.."
REPEATS="${REPEATS:-2}"
for rep in $(seq 1 "$REPEATS"); do
for spec in "small 10" "medium 5" "large 3"; do
set -- $spec
for cp in "1 1" "2 2" "4 4" "2 16"; do
c=${cp% *}; p=${cp#* }
python3 student-tests/queue_load.py run --size "$1" --rate "$2" --duration 30 \
--concurrency "$c" --prefetch "$p" --label "c$c-p$p-r$rep" | tail -1
done
done
done
for rep in $(seq 1 "$REPEATS"); do
python3 student-tests/queue_load.py overload --max-pending 30 --size large --rate 8 --duration 30 \
--concurrency 2 --prefetch 2 --label "overload-r$rep" | tail -1
done
# back to the default topology
WORKER_REPLICAS=2 docker compose --env-file .env up -d --no-deps --wait worker >/dev/null
echo MATRIX_DONE
+48
View File
@@ -0,0 +1,48 @@
#!/usr/bin/env python3
"""Aggregate evidence/track1/results.jsonl into evidence/track1/summary.md (mean over repeats, min..max shown)."""
import json
from collections import defaultdict
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
rows = [json.loads(line) for line in (ROOT / "evidence/track1/results.jsonl").read_text().splitlines() if line.strip()]
groups = defaultdict(list)
for r in rows:
if r["label"].startswith("calib"):
continue
key = ("overload" if r["label"].startswith("overload") else "run", r["size"], r["concurrency"], r["prefetch"])
groups[key].append(r)
def agg(items, field, digits=2):
values = [i[field] for i in items if i.get(field) is not None]
if not values:
return "—"
mean = sum(values) / len(values)
if len(values) == 1 or max(values) == min(values):
return ("%." + str(digits) + "f") % mean
return ("%." + str(digits) + "f (%." + str(digits) + "f–%." + str(digits) + "f)") % (mean, min(values), max(values))
order = {"small": 0, "medium": 1, "large": 2}
lines = ["| size | rate/s | c/p | n | accepted | throughput jobs/s | lag p95 s | ttr p50 s | ttr p95 s | pending max |"
" worker mem peak MiB | cpu peak % |",
"| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |"]
for key in sorted((k for k in groups if k[0] == "run"), key=lambda k: (order[k[1]], k[2], k[3])):
items = groups[key]
lines.append("| %s | %s | %d/%d | %d | %s | %s | %s | %s | %s | %s | %s | %s |" % (
key[1], items[0]["rate"], key[2], key[3], len(items), agg(items, "accepted", 0), agg(items, "throughput_jobs_s"),
agg(items, "lag_p95_s"), agg(items, "ttr_p50_s"), agg(items, "ttr_p95_s"), agg(items, "pending_max", 0),
agg(items, "worker_mem_peak_mib", 0), agg(items, "worker_cpu_peak_pct", 0)))
over = [r for k, v in groups.items() if k[0] == "overload" for r in v]
if over:
lines += ["", "| overload run | offered | accepted | rejected 503 | other errors | pending max (limit) | throughput |"
" ttr p95 s | drain after load s | recovery probe ready s |",
"| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |"]
for r in over:
lines.append("| %s | %d @ %s/s | %d | %d | %d | %d (%d) | %.2f | %s | %s | %s |" % (
r["label"], r["offered"], r["rate"], r["accepted"], r["rejected_503"], r["other_errors"], r["pending_max"],
r["max_pending"], r["throughput_jobs_s"] or 0, r["ttr_p95_s"], r["drain_after_load_s"],
r.get("recovery_probe_ready_s")))
(ROOT / "evidence/track1/summary.md").write_text("\n".join(lines) + "\n")
print("\n".join(lines))
+126
View File
@@ -0,0 +1,126 @@
"""Variant rules and worker resource limits. Runs INSIDE the worker container (Pillow + app code):
docker compose exec -T --index 1 worker python - < student-tests/variants_check.py
"""
import io
import json
import os
import resource
import subprocess
import sys
import tempfile
import time
from PIL import Image
sys.path.insert(0, "/app")
from app import config # noqa: E402
FAILS = []
def check(cond, msg):
print(("ok " if cond else "FAIL ") + msg, flush=True)
if not cond:
FAILS.append(msg)
def run_child(path, mem_mb=config.WORKER_CHILD_MEMORY_MB, cpu=config.JOB_TIMEOUT_SECONDS, max_pixels=config.MAX_IMAGE_PIXELS):
out = tempfile.mkdtemp()
def limits():
resource.setrlimit(resource.RLIMIT_AS, (mem_mb << 20, mem_mb << 20))
resource.setrlimit(resource.RLIMIT_CPU, (cpu, cpu + 5))
start = time.monotonic()
done = subprocess.run([sys.executable, "-m", "app.imageproc", path, out, str(max_pixels)], capture_output=True,
preexec_fn=limits, timeout=120, env={"PATH": os.environ["PATH"], "MALLOC_ARENA_MAX": "2"})
usage = resource.getrusage(resource.RUSAGE_CHILDREN)
produced = {v["name"]: v for v in json.loads(done.stdout)} if done.returncode == 0 else {}
return done.returncode, produced, time.monotonic() - start, usage.ru_maxrss / 1024
def save(img, fmt, **kw):
path = tempfile.mktemp(suffix="." + fmt.lower())
img.save(path, fmt, **kw)
return path
def dims(v):
return v["width"], v["height"]
def real(v):
with Image.open(v["file"]) as im:
return im.format, im.size, "exif" in im.info, im
# 1. fixture 320x200 -> 256x160, crop 128, optimized not upscaled
rc, p, _, _ = run_child("/app/tests/fixtures/sample.png" if os.path.exists("/app/tests/fixtures/sample.png") else
save(Image.new("RGB", (320, 200), "red"), "PNG"))
check(rc == 0 and dims(p["thumbnail"]) == (256, 160), "320x200 -> thumbnail 256x160")
check(dims(p["crop"]) == (128, 128), "crop 128x128")
check(dims(p["optimized"]) == (320, 200) and real(p["optimized"])[0] == "WEBP", "optimized WebP 320x200, no upscale")
check(real(p["thumbnail"])[0] == "JPEG" and real(p["crop"])[0] == "JPEG", "thumbnail/crop are JPEG")
# 2. small source: no upscale for thumbnail, upscale allowed for crop
rc, p, _, _ = run_child(save(Image.new("RGB", (40, 10), "blue"), "PNG"))
check(dims(p["thumbnail"]) == (40, 10) and dims(p["crop"]) == (128, 128), "40x10: thumbnail 40x10, crop 128x128")
# 3. extreme aspect ratio: floor rounding, minimum 1 px
rc, p, _, _ = run_child(save(Image.new("RGB", (3000, 2), "blue"), "PNG"))
check(dims(p["thumbnail"]) == (256, 1) and dims(p["optimized"]) == (1280, 1), "3000x2 -> 256x1 / 1280x1 (min 1px)")
rc, p, _, _ = run_child(save(Image.new("RGB", (1001, 999), "blue"), "PNG"))
check(dims(p["thumbnail"]) == (256, 255), "1001x999 -> 256x255 (floor)")
# 4. EXIF orientation 6 (rotate 90): stored 400x200 -> upright 200x400 -> thumbnail 128x256; EXIF stripped
exif = Image.Exif()
exif[0x0112] = 6
img = Image.new("RGB", (400, 200), "white")
img.paste((255, 0, 0), (0, 0, 200, 200)) # left half red
rc, p, _, _ = run_child(save(img, "JPEG", exif=exif.tobytes(), quality=95))
fmt, size, has_exif, im = real(p["thumbnail"])
check(size == (128, 256), "EXIF orientation applied: 400x200 (o=6) -> 128x256")
with Image.open(p["thumbnail"]["file"]) as t:
top = t.convert("RGB").getpixel((64, 20))
check(top[0] > 200 and top[1] < 80, "rotated content: red half on top after orientation 6")
check(not has_exif and "exif" not in Image.open(p["optimized"]["file"]).info, "EXIF removed from thumbnail/optimized")
# 5. alpha composited on white for JPEG, kept for WebP
rgba = Image.new("RGBA", (100, 100), (0, 0, 0, 0))
rc, p, _, _ = run_child(save(rgba, "PNG"))
with Image.open(p["thumbnail"]["file"]) as t:
px = t.convert("RGB").getpixel((50, 50))
check(min(px) >= 250, "transparent PNG -> white JPEG thumbnail")
check(Image.open(p["optimized"]["file"]).mode == "RGBA", "WebP optimized keeps alpha")
# 6. 16-bit grayscale PNG, CMYK JPEG, palette PNG
rc16, _, _, _ = run_child(save(Image.new("I;16", (300, 300), 40000), "PNG"))
rcc, _, _, _ = run_child(save(Image.new("CMYK", (300, 300), (0, 255, 0, 0)), "JPEG"))
rcp, _, _, _ = run_child(save(Image.new("P", (300, 300), 3), "PNG", transparency=3))
check(rc16 == 0 and rcc == 0 and rcp == 0, "16-bit PNG, CMYK JPEG, palette+transparency PNG are processed")
# 7. limits: pixels (exit 4), not an image (exit 3), memory (exit 5), CPU (SIGXCPU)
rc, _, _, _ = run_child(save(Image.new("RGB", (100, 100)), "PNG"), max_pixels=5000)
check(rc == 4, "pixel limit enforced before decode -> image_too_large (exit 4)")
junk = tempfile.mktemp()
open(junk, "wb").write(b"\x89PNG\r\n\x1a\n" + os.urandom(2000))
rc, _, _, _ = run_child(junk)
check(rc == 3, "corrupted PNG -> invalid_image (exit 3)")
big = save(Image.new("RGB", (6000, 6000), "green"), "PNG")
rc, _, _, _ = run_child(big, mem_mb=160)
check(rc == 5, "36 Mpx PNG with 160 MiB address-space limit -> image_too_complex (exit 5), got %s" % rc)
# 8. largest allowed inputs under the real limits: time and child peak RSS
for name, w, h, fmt in (("png", 7900, 5000, "PNG"), ("jpeg", 7900, 5000, "JPEG")):
noise = Image.effect_noise((w // 10, h // 10), 60).convert("RGB").resize((w, h))
path = save(noise, fmt, **({"quality": 90} if fmt == "JPEG" else {"compress_level": 1}))
rc, p, secs, rss = run_child(path)
check(rc == 0 and dims(p["thumbnail"]) == (256, 162), "%.1f Mpx %s (%d MB file) ok in %.1fs, peak child RSS %.0f MiB"
% (w * h / 1e6, name.upper(), os.path.getsize(path) >> 20, secs, rss))
if fmt == "PNG":
rc, _, _, _ = run_child(path, cpu=0)
check(rc == -24, "CPU limit exhausted -> SIGXCPU (worker: permanent image_too_complex), got %s" % rc)
print("RESULT:", "PASS" if not FAILS else "FAIL %s" % FAILS)
sys.exit(1 if FAILS else 0)