#!/usr/bin/env python3 """MessengerWorkerSaturated: capacity is lowered (2 workers x 1 slot, 0.25 CPU each), uploads exceed it for longer than `for: 5m`; the alert must fire, and resolve after the normal configuration is restored and the backlog drains. python3 student-tests/test_worker_saturation.py (stack running; ~10 min). Restores WORKER_* defaults at the end. """ import json import os import subprocess import threading import time from pathlib import Path import obs from openloop import Load from stand import check, log, run from test_incidents import wait_alert ROOT = Path(__file__).resolve().parents[1] ALERT = "MessengerWorkerSaturated" def worker(env): done = subprocess.run(["docker", "compose", "--env-file", ".env", "up", "-d", "--wait", "--no-deps", "--force-recreate", "worker"], cwd=ROOT, env={**os.environ, **env}, capture_output=True, text=True, timeout=240) check(done.returncode == 0, "worker recreate failed: %s" % done.stderr[-300:]) def main(): result = {} log("lower capacity: WORKER_CONCURRENCY=1 WORKER_PREFETCH=1 WORKER_CPUS=0.25, 2 replicas") worker({"WORKER_CONCURRENCY": "1", "WORKER_PREFETCH": "1", "WORKER_CPUS": "0.25"}) load = Load("https://localhost:8443", users=2, threads=32) stop = threading.Event() summary = {} thread = threading.Thread(target=lambda: summary.update(load.run(0, 900, upload_rate=4, stop_event=stop)), daemon=True) t0 = time.time() thread.start() log("uploads: 4/s open-loop (sample.png)") try: time.sleep(60) capacity = obs.prom_scalar("sum(messenger_worker_capacity and (time() - timestamp(messenger_worker_capacity) < 30))") log("fresh capacity=%.0f slots (stale series of recreated containers are excluded)" % capacity) check(capacity == 2, "expected 2 slots, got %s" % capacity) firing, pending = wait_alert(ALERT, "firing", 480, t0) ratio = obs.prom_scalar("messenger:worker_saturation:ratio") depth = obs.prom_scalar('max(messenger_queue_depth{queue="attachments.process",state="queued"})') age = obs.prom_scalar('max(messenger_queue_oldest_age_seconds{queue="attachments.process"})') rate = obs.prom_scalar('sum(rate(messenger_jobs_processed_total{outcome="succeeded"}[2m]))') p95 = obs.prom_scalar('histogram_quantile(0.95, sum by (le) (rate(messenger_job_duration_seconds_bucket{outcome="succeeded"}[5m])))') others = obs.alerts() log("at firing: saturation=%.2f, queued=%.0f, oldest age=%.0f s, succeeded=%.2f jobs/s, job p95=%.2f s, alerts=%s" % (ratio, depth, age, rate, p95, others)) check(ratio > 0.9, "saturation must be above the threshold") finally: stop.set() thread.join(60) log("restore default worker configuration") t1 = time.time() worker({}) resolved, _ = wait_alert(ALERT, "resolved", 240, t1) drained = obs.wait_for(lambda: obs.prom_scalar('max(messenger_queue_depth{queue="attachments.process",state="queued"})', default=-1) == 0, 240, 5) log("backlog drained: %s (+%.0f s after restore)" % (bool(drained), time.time() - t1)) check(drained, "backlog must drain") result.update({"alert_pending_s": pending, "alert_firing_s": round(firing), "saturation_at_firing": round(ratio, 3), "queued_at_firing": depth, "oldest_age_s": round(age), "jobs_per_s": round(rate, 2), "job_p95_s": round(p95, 2), "alerts_at_firing": others, "resolved_after_restore_s": round(resolved), "drained_after_restore_s": round(time.time() - t1), "uploads": summary.get("status_counts")}) (ROOT / "evidence/worker_saturation.json").write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n") print("PASS: MessengerWorkerSaturated fired under saturation and resolved after recovery") if __name__ == "__main__": run(main)