#!/usr/bin/env python3 """Sequential one-replica-at-a-time failure matrix under continuous writes. For every running API replica: * run a small closed-loop writer against the public LB; * stop exactly that container (by X-Instance-Id -> hostname -> container id); * keep writing, then restore the replica and wait until it serves again; * record per-second successes/errors, first recovery and post-recovery RPS. This is an operator measurement, not a production HA proof. It never removes volumes and never prints credentials or tokens. """ from __future__ import annotations import argparse import json import subprocess import threading import time import uuid from collections import defaultdict from pathlib import Path from common import HttpClient ROOT = Path(__file__).resolve().parents[1] def compose(*args: str) -> str: return subprocess.check_output( ["docker", "compose", "--env-file", ".env", *args], cwd=ROOT, stderr=subprocess.STDOUT, text=True, ) def api_containers() -> list[dict]: ids = compose("ps", "-q", "api").split() result = [] for container_id in ids: hostname = subprocess.check_output( ["docker", "inspect", "--format", "{{.Config.Hostname}}", container_id], text=True, ).strip() status = subprocess.check_output( ["docker", "inspect", "--format", "{{.State.Status}}", container_id], text=True, ).strip() if status == "running": result.append({"id": container_id, "hostname": hostname}) return result def wait_instances(client: HttpClient, token: str, expected: int, timeout: float = 30) -> set[str]: deadline = time.monotonic() + timeout seen: set[str] = set() while time.monotonic() < deadline: try: status, headers, _payload, _raw = client.call("GET", "/api/v1/users/me", token=token) if status == 200: seen.add(headers.get("X-Instance-Id", "")) if len(seen) >= expected: return seen except OSError: pass time.sleep(0.25) return seen def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--base-url", default="http://localhost:8080") parser.add_argument("--duration", type=float, default=16.0) parser.add_argument("--workers", type=int, default=6) parser.add_argument("--output", default="evidence/failover_matrix.json") args = parser.parse_args() client = HttpClient(args.base_url) user, registration = client.register() session = client.login(registration) token = session["token"] status, _headers, chat, _raw = client.call( "POST", "/api/v1/chats", body={"title": "Failover matrix", "member_ids": [user["id"]]}, token=token, ) if status != 201: raise AssertionError(f"chat creation failed: HTTP {status}") targets = api_containers() if len(targets) < 2: raise AssertionError("at least two running API replicas are required") report = { "base_url": args.base_url, "workers": args.workers, "duration_seconds": args.duration, "replicas_before": sorted(item["hostname"] for item in targets), "runs": [], } for target in targets: stop_event = threading.Event() lock = threading.Lock() successes = defaultdict(int) errors = defaultdict(int) events: list[tuple[float, str]] = [] started = time.monotonic() stop_at = started + 2.0 def worker(worker_id: int) -> None: local = HttpClient(args.base_url) index = 0 while not stop_event.is_set(): index += 1 key = uuid.uuid4().hex body = {"text": f"matrix-{target['hostname'][:6]}-{worker_id}-{index}"} try: status, headers, _payload, _raw = local.call( "POST", f"/api/v1/chats/{chat['id']}/messages", body=body, token=token, headers={"Idempotency-Key": key}, ) bucket = int(time.monotonic() - started) with lock: if status == 201: successes[bucket] += 1 events.append((time.monotonic(), headers.get("X-Instance-Id", ""))) else: errors[bucket] += 1 except Exception: bucket = int(time.monotonic() - started) with lock: errors[bucket] += 1 time.sleep(0.005) threads = [threading.Thread(target=worker, args=(i,), daemon=True) for i in range(args.workers)] for thread in threads: thread.start() while time.monotonic() < stop_at: time.sleep(0.05) stop_time = time.monotonic() subprocess.run( ["docker", "stop", "--time", "1", target["id"]], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) stopped_at = time.monotonic() # Keep writing for the rest of the window, then restore the replica. time.sleep(max(0.0, args.duration - (time.monotonic() - started) - 4.0)) restore_at = time.monotonic() compose("start", "api") seen_after = wait_instances(client, token, len(targets), timeout=30) recovered_at = time.monotonic() time.sleep(max(0.0, args.duration - (time.monotonic() - started))) stop_event.set() for thread in threads: thread.join(timeout=3) with lock: after_stop = [event for event in events if event[0] > stopped_at] first_after_stop = min((event[0] for event in after_stop), default=None) target_during_outage = any( event[1] == target["hostname"] for event in events if stopped_at < event[0] < restore_at ) target_after_restore = any( event[1] == target["hostname"] for event in events if event[0] >= restore_at ) run = { "target_instance": target["hostname"], "target_container": target["id"][:12], "success_by_second": [successes[i] for i in range(int(args.duration) + 1)], "errors_by_second": [errors[i] for i in range(int(args.duration) + 1)], "successes_total": sum(successes.values()), "errors_total": sum(errors.values()), "stop_seconds": round(stopped_at - started, 3), "restore_seconds": round(restore_at - started, 3), "first_write_after_stop_seconds": ( round(first_after_stop - stopped_at, 3) if first_after_stop else None ), "target_served_during_outage": target_during_outage, "target_present_after_restore": target_after_restore, "instances_after_restore": sorted(item for item in seen_after if item), } report["runs"].append(run) print(json.dumps(run, ensure_ascii=False)) # Give the LB a moment to see the restored replica before the next run. time.sleep(1.0) output = Path(args.output) output.parent.mkdir(parents=True, exist_ok=True) output.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") print("PASS: sequential replica-stop matrix completed; evidence:", output) if __name__ == "__main__": main()