#!/usr/bin/env python3 import json import math import shlex import subprocess import sys import threading import time import uuid from collections import Counter, defaultdict 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, arguments, check, run def pct(values, p): return round(1000 * values[max(0, math.ceil(p * len(values)) - 1)], 1) if values else None def docker_stats(): ids = subprocess.run(["docker", "compose", "ps", "-q"], cwd=ROOT, capture_output=True, text=True).stdout.split() out = subprocess.run(["docker", "stats", "--no-stream", "--format", "{{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}", *ids], capture_output=True, text=True) return sorted(out.stdout.splitlines()) def main(): def configure(p): p.add_argument("--duration", type=float, default=25) p.add_argument("--concurrency", type=int, default=8) p.add_argument("--action", default=None, help="command run once at --action-at seconds") p.add_argument("--action-at", type=float, default=5) p.add_argument("--output", default=None) args = arguments("Load with an operator action in the middle", configure) boot = Client(args.base_url, timeout=10) alice, bob, _eve, chat = boot.bootstrap() path = "/api/v1/chats/" + chat["id"] + "/messages" events = [] confirmed = [] lock = threading.Lock() t0 = time.monotonic() stop_at = t0 + args.duration action_info = {} def worker(wid): c = Client(args.base_url, timeout=2) key, text, n = None, None, 0 while time.monotonic() < stop_at: if key is None: key = uuid.uuid4().hex text = "chaos-%d-%d-%s" % (wid, n, key[:8]) for kind in ("write", "read"): start = time.monotonic() try: if kind == "write": r = c.call("POST", path, 201, actor=alice, body={"text": text}, headers={"Idempotency-Key": key}, schema="Message") else: r = c.call("GET", path + "?limit=20", actor=bob, schema="MessagePage") ok, inst = True, r["headers"].get("X-Instance-Id") except Failure: ok, inst = False, None end = time.monotonic() with lock: events.append((start - t0, kind, ok, end - start, inst)) if ok and kind == "write": confirmed.append(r["json"]) if kind == "write" and ok: key, n = None, n + 1 if not ok: time.sleep(0.05) def action(): time.sleep(args.action_at) action_info["started"] = time.monotonic() - t0 proc = subprocess.run(shlex.split(args.action), cwd=ROOT, capture_output=True, text=True) action_info["finished"] = time.monotonic() - t0 action_info["returncode"] = proc.returncode action_info["output_tail"] = proc.stdout.strip().splitlines()[-6:] stats_mid = [] threads = [threading.Thread(target=worker, args=(i,)) for i in range(args.concurrency)] if args.action: threads.append(threading.Thread(target=action)) for t in threads: t.start() time.sleep(min(args.duration / 2, args.action_at + 3)) stats_mid = docker_stats() for t in threads: t.join() elapsed = time.monotonic() - t0 ok_lat = sorted(e[3] for e in events if e[2]) errors = [e for e in events if not e[2]] a0 = action_info.get("started") timeline = defaultdict(lambda: [0, 0]) for e in events: timeline[int(e[0])][0 if e[2] else 1] += 1 report = { "profile": "closed loop, %d workers, each: POST message (retry same key) + GET history; client timeout 2 s" % args.concurrency, "action": args.action, "action_started_s": a0 and round(a0, 2), "action_finished_s": action_info.get("finished") and round(action_info["finished"], 2), "action_returncode": action_info.get("returncode"), "action_output": action_info.get("output_tail"), "elapsed_s": round(elapsed, 2), "requests": len(events), "successful": len(ok_lat), "errors": len(errors), "error_ratio": round(len(errors) / len(events), 5) if events else None, "successful_rps": round(len(ok_lat) / elapsed, 1), "latency_ms_success": {"p50": pct(ok_lat, .50), "p95": pct(ok_lat, .95), "p99": pct(ok_lat, .99), "max": pct(ok_lat, 1)}, "slow_over_500ms_after_action": sum(1 for e in events if e[2] and e[3] > .5 and a0 is not None and e[0] >= a0), "error_window_s": [round(errors[0][0] - (a0 or 0), 2), round(max(e[0] + e[3] for e in errors) - (a0 or 0), 2)] if errors else None, "recovery_s_after_action": None, "instances_before": dict(Counter(e[4] for e in events if e[2] and (a0 is None or e[0] < a0))), "instances_last_5s": dict(Counter(e[4] for e in events if e[2] and e[0] > elapsed - 5)), "timeline_ok_err_per_s": {k: v for k, v in sorted(timeline.items())}, "docker_stats_mid": stats_mid, } if a0 is not None: bad_ends = [e[0] + e[3] for e in events if e[0] + e[3] >= a0 and (not e[2] or e[3] > 1)] report["recovery_s_after_action"] = round(max(bad_ends) - a0, 2) if bad_ends else 0.0 items, cursor = [], None while True: q = path + "?limit=100" + ("&cursor=" + quote(cursor, safe="") if cursor else "") page = boot.call("GET", q, actor=bob, schema="MessagePage")["json"] items += page["items"] cursor = page["next_cursor"] if cursor is None: break ids = Counter(m["id"] for m in items) texts = Counter(m["text"] for m in items) stored = {m["id"]: m for m in items} report["integrity"] = { "stored_messages": len(items), "confirmed_writes": len(confirmed), "duplicate_ids": sum(1 for n in ids.values() if n > 1), "duplicate_texts": sum(1 for n in texts.values() if n > 1), "confirmed_missing": sum(1 for m in confirmed if stored.get(m["id"]) != m), } text = json.dumps(report, ensure_ascii=False, indent=1) print(text) if args.output: Path(args.output).write_text(text + "\n") check(report["integrity"]["duplicate_texts"] == 0 and report["integrity"]["confirmed_missing"] == 0, "data integrity violated") check(action_info.get("returncode", 0) == 0, "action failed") if __name__ == "__main__": run(main)