#!/usr/bin/env python3 """Check worker scope, rotate TLS identity and Redis credential, and verify queued content.""" import argparse import math import concurrent.futures import json import subprocess from pathlib import Path import sys import time sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts")) from stand import ROOT, rotate_worker, run_compose sys.path.insert(0, str(ROOT / "tests")) from client import Client, Failure, check def snapshot(): result = run_compose("images", "--format", "json", "worker", capture_output=True, text=True) return json.loads(result.stdout)[0]["ID"] def summary(values): values = sorted(values) def pct(n): return round(values[max(0, math.ceil(len(values) * n / 100) - 1)] * 1000, 1) return {f"p{n}_ms": pct(n) for n in (50, 95, 99)} def experiment(client, count): alice, bob, _, chat = client.bootstrap() def burst(): def upload(_): c = Client(client.base, args.ca_file) started = time.monotonic() att, original = c.attachment(alice, chat) c.message(alice, chat, "lab7 worker experiment", attachments=[att["id"]]) return att, original, started, time.monotonic() - started with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool: work = list(pool.map(upload, range(count))) check(len({a["id"] for a, *_ in work}) == count, "upload IDs must be unique") return work def drain(work): def get(item): c = Client(client.base, args.ca_file) att, original, submitted, _ = item deadline = time.monotonic() + 60 retries = 0 while time.monotonic() < deadline: path = "/api/v1/attachments/" + att["id"] try: ready = c.call("GET", path, actor=bob, schema="Attachment")["json"] check(ready["status"] != "failed", "attachment processing failed") if ready["status"] == "ready": latency = time.monotonic() - submitted check(ready["id"] == att["id"] and ready["sha256"] == att["sha256"], "attachment identity changed") check(c.call("GET", path + "/content", actor=bob)["bytes"] == original, "original changed") check(len(ready["variants"]) == 3, "missing generated variants") thumbnail = c.call("GET", path + "/content?variant=thumbnail", actor=bob) check(thumbnail["bytes"].startswith(b"\xff\xd8"), "thumbnail not present") return latency, retries except Failure as error: if "received 503" not in str(error) and "connection/TLS failure" not in str(error): raise retries += 1 time.sleep(0.3) raise Failure("attachment did not become ready within 60 seconds") with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool: return list(pool.map(get, work)) def worker_usage(): worker = run_compose("ps", "-q", "worker", capture_output=True, text=True).stdout.strip() result = subprocess.check_output(["docker", "stats", "--no-stream", "--format", "{{json .}}", worker], text=True, timeout=12) sample = json.loads(result) return {"cpu": sample["CPUPerc"], "memory": sample["MemUsage"]} run_compose("run", "--rm", "--no-deps", "audit", "worker") run_compose("run", "--rm", "--no-deps", "--entrypoint", "sh", "db_grants", "/db-audit.sh") run_compose("run", "--rm", "--no-deps", "--entrypoint", "sh", "s3_bootstrap", "/s3-audit.sh") image = snapshot() with concurrent.futures.ThreadPoolExecutor(max_workers=1) as monitor: usage = monitor.submit(worker_usage) start = time.monotonic() warm = burst() warm_ready = drain(warm) warm_seconds = time.monotonic() - start resources = usage.result() run_compose("stop", "worker") paused = time.monotonic() queued = burst() time.sleep(2) for att, *_ in queued: path = "/api/v1/attachments/" + att["id"] check(client.call("GET", path, actor=bob, schema="Attachment")["json"]["status"] == "queued", "accepted attachment was not queued without worker") rotation_start = time.monotonic() try: rotate_worker() restarted = time.monotonic() post_ready = drain(queued) recovered = time.monotonic() run_compose("run", "--rm", "--no-deps", "audit", "rotation") run_compose("run", "--rm", "--no-deps", "--entrypoint", "sh", "db_grants", "/db-audit.sh", "rotated") run_compose("run", "--rm", "--no-deps", "--entrypoint", "sh", "s3_bootstrap", "/s3-audit.sh", "rotated") check(snapshot() == image, "worker image changed during rotation") time.sleep(2) path = "/api/v1/chats/" + chat["id"] + "/messages?limit=100" rows = client.call("GET", path, actor=bob, schema="MessagePage")["json"]["items"] linked = [row["attachment_ids"][0] for row in rows] expected = {att["id"] for att, *_ in (*warm, *queued)} check(set(linked) == expected and len(rows) == len(expected), "confirmed messages lost or duplicated") finally: # Retired material is kept only long enough to prove rejection. for name in ("tls.crt", "tls.key", "REDIS_PASSWORD", "POSTGRES_PASSWORD", "S3_ACCESS_KEY", "S3_SECRET_KEY"): path = ROOT / ".runtime/retired" / name if path.exists(): path.unlink() return { "worker_image_id": image, "baseline": {"jobs": count, "verified": len(warm_ready), "ready_latency": summary([latency for latency, _ in warm_ready]), "read_retries": sum(retries for _, retries in warm_ready), "worker_sample": resources, "submission_latency": summary([cost for *_, cost in warm]), "verified_per_second": round(count / warm_seconds, 2)}, "incident": {"queued": count, "verified": len(post_ready), "lost_or_duplicate": 0, "submission_latency": summary([cost for *_, cost in queued]), "ready_latency": summary([latency for latency, _ in post_ready]), "read_retries": sum(retries for _, retries in post_ready), "rotation_seconds": round(restarted - rotation_start, 2), "worker_unavailable_seconds": round(recovered - paused, 2), "drain_seconds_after_start": round(recovered - restarted, 2)}, } if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--ca-file", default=str(ROOT / ".runtime/trust/ca.crt")) parser.add_argument("--base-url", default="https://localhost:8443") parser.add_argument("--jobs", type=int, default=8, choices=range(1, 41)) parser.add_argument("--repeats", type=int, default=3, choices=range(1, 6)) parser.add_argument("--output", type=Path) args = parser.parse_args() runs = [experiment(Client(args.base_url, args.ca_file), args.jobs) for _ in range(args.repeats)] environment = subprocess.check_output( ["docker", "info", "--format", "{{.OSType}}/{{.Architecture}} {{.NCPU}} {{.MemTotal}}"], text=True, ).split() result = { "docker_platform": environment[0], "docker_vcpus": int(environment[1]), "docker_memory_bytes": int(environment[2]), "fixture_png_bytes": (ROOT / "tests/fixtures/sample.png").stat().st_size, "closed_loop_concurrency": 4, "queue_observation_seconds": 2, "runs": runs, } encoded = json.dumps(result, indent=2) + "\n" if args.output: args.output.write_text(encoded) print(encoded, end="")