Files
mtusi2026lab3/student-tests/lab3/run.py
T

952 lines
50 KiB
Python

#!/usr/bin/env python3
"""Lab 3 black-box checks. All traffic uses the configured public LB URL."""
import argparse
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timezone
import http.client
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import os
from pathlib import Path
import socket
import ssl
import subprocess
import sys
import threading
import time
from urllib.parse import quote, urlsplit
import uuid
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check # noqa: E402
class Pending(Exception):
pass
class Evidence:
def __init__(self, directory):
self.directory = Path(directory).resolve()
self.directory.mkdir(parents=True, exist_ok=True)
self.path = self.directory / "events.jsonl"
self.summary = {}
def record(self, event, **fields):
now = datetime.now(timezone.utc)
item = {"time_utc": now.strftime("%Y-%m-%dT%H:%M:%SZ"),
"time_utc_ms": now.isoformat(timespec="milliseconds"),
"event": event, **fields}
with self.path.open("a", encoding="utf-8") as stream:
stream.write(json.dumps(item, ensure_ascii=False, sort_keys=True) + "\n")
def case(self, name, fn):
start = time.monotonic()
try:
fn()
status, detail = "PASS", ""
except Pending as exc:
status, detail = "PENDING_INFRA", str(exc)
except (Failure, AssertionError, ValueError, OSError, subprocess.SubprocessError) as exc:
status, detail = "FAIL", str(exc)
except Exception as exc:
status, detail = "FAIL", "unexpected " + type(exc).__name__
self.summary[name] = {"status": status, "detail": detail,
"elapsed_seconds": round(time.monotonic() - start, 3)}
self.record("case", name=name, **self.summary[name])
print(status + " " + name + (": " + detail if detail else ""), flush=True)
def finish(self):
path = self.directory / "summary.json"
path.write_text(json.dumps(self.summary, ensure_ascii=False, indent=2, sort_keys=True) + "\n",
encoding="utf-8")
print("Evidence:", path)
return 0 if self.summary and all(x["status"] == "PASS" for x in self.summary.values()) else 1
def message_path(chat):
return "/api/v1/chats/" + chat["id"] + "/messages"
def history(client, actor, chat):
path = message_path(chat) + "?limit=100"
result, cursors = [], set()
for _ in range(1000):
page = client.call("GET", path, actor=actor, schema="MessagePage")["json"]
result.extend(page["items"])
cursor = page["next_cursor"]
if cursor is None:
return result
check(cursor not in cursors, "history cursor cycle")
cursors.add(cursor)
path = message_path(chat) + "?limit=100&cursor=" + quote(cursor, safe="")
raise Failure("history exceeded pagination safety bound")
def occurrences(client, actor, chat, text):
return [m for m in history(client, actor, chat) if m["text"] == text]
def post(client, actor, chat, body, key, expected=201):
headers = {} if key is None else {"Idempotency-Key": key}
response = client.call("POST", message_path(chat), expected, actor=actor,
body=body, headers=headers, schema="Message" if expected == 201 else None)
if expected in (400, 401, 404, 409):
code = {400: "invalid_request", 401: "unauthorized", 404: "not_found", 409: "conflict"}[expected]
check(response["json"]["error"]["code"] == code, "wrong error code for %d" % expected)
return response
def hook(config, name, evidence, target=None, timeout=45):
argv = config.get("hooks", {}).get(name)
if not isinstance(argv, list) or not argv or not all(isinstance(x, str) and x for x in argv):
raise Pending("configure hooks.%s as an executable argv array" % name)
env = dict(os.environ)
if target:
env["TARGET_INSTANCE_ID"] = target
env.update(config.get("hook_context", {}))
start = time.monotonic()
try:
result = subprocess.run(argv, cwd=ROOT, env=env, capture_output=True,
timeout=timeout, check=False)
except (OSError, subprocess.TimeoutExpired) as exc:
raise Failure("hook %s unavailable or timed out (%s)" % (name, type(exc).__name__)) from None
elapsed = round(time.monotonic() - start, 3)
evidence.record("hook", name=name, target_instance=target, elapsed_seconds=elapsed,
exit_code=result.returncode)
check(result.returncode == 0, "hook %s exited %d; inspect it locally" % (name, result.returncode))
if name in ("revoke_access", "restore_access"):
try:
detail = json.loads(result.stdout)
except ValueError:
raise Failure("access hook must return validated fixture JSON") from None
check(detail.get("action") == name and detail.get("validated_exact_message") is True,
"access hook did not confirm exact fixture mutation")
evidence.record("access_sql", **detail)
return elapsed
def probe(config, evidence, name, target):
argv = config.get("hooks", {}).get(name)
if not isinstance(argv, list) or not argv:
raise Pending("configure hooks.%s to probe the selected private replica" % name)
env = dict(os.environ)
env["TARGET_INSTANCE_ID"] = target
proc = subprocess.run(argv, cwd=ROOT, env=env, capture_output=True, timeout=10, check=False)
check(proc.returncode == 0, "probe hook failed")
try:
value = json.loads(proc.stdout)
except ValueError:
raise Failure("probe hook must return JSON") from None
check(isinstance(value, dict), "probe hook must return a JSON object")
evidence.record("replica_probe", name=name, target_instance=target,
live_status=value.get("live_status"), ready_status=value.get("ready_status"),
accepting=value.get("accepting"))
return value
def client_for(config, timeout=None):
url = config.get("base_url")
if not isinstance(url, str) or not url.startswith(("http://", "https://")):
raise Pending("configure base_url to the PUBLIC LB address")
return Client(url, config.get("ca_file"), timeout=timeout or config.get("request_timeout_seconds", 3))
def docker_output(argv, timeout=15):
try:
proc = subprocess.run(argv, cwd=ROOT, capture_output=True, timeout=timeout, check=False)
except (OSError, subprocess.TimeoutExpired) as exc:
raise Pending("Docker inspection unavailable (%s)" % type(exc).__name__) from None
if proc.returncode:
raise Pending("Docker inspection failed; check daemon/project selection")
return proc.stdout.decode("utf-8")
def compose_ids(config, service, all_containers=False):
base = config.get("compose_base_argv", ["docker", "compose"])
flag = "-aq" if all_containers else "-q"
return docker_output(base + ["ps", flag, service]).split()
def inspect_container(identifier):
value = json.loads(docker_output(["docker", "inspect", identifier]))
check(isinstance(value, list) and len(value) == 1, "Docker inspect returned no unique container")
return value[0]
def api_by_alias(config):
result = {}
for identifier in compose_ids(config, "api", all_containers=True):
raw = inspect_container(identifier)
alias = raw["Config"]["Hostname"]
check(alias not in result, "duplicate API hostname/instance alias")
result[alias] = raw
return result
def volume_names(raw):
return sorted(m["Name"] for m in raw.get("Mounts", []) if m.get("Type") == "volume")
def public_ready(config):
client = client_for(config)
try:
client.call("GET", "/health/ready", schema="Health")
except Failure as exc:
if "connection/TLS failure" in str(exc):
raise Pending("PUBLIC LB address is not reachable") from None
raise
return client
def bootstrap(config):
client = public_ready(config)
alice, bob, eve, chat = client.bootstrap()
other_chat = client.call("POST", "/api/v1/chats", 201, actor=alice,
body={"title": "Lab3 independent scope", "member_ids": [alice["id"], bob["id"]]},
schema="Chat")["json"]
return client, alice, bob, eve, chat, other_chat
def idempotency(config, evidence, only=None):
client, alice, bob, eve, chat, other_chat = bootstrap(config)
prefix = "lab3-" + uuid.uuid4().hex
executed = []
def unique(label):
return prefix + ":" + label
def case(name, fn):
if only is None or name == only:
evidence.case(name, fn)
executed.append(name)
def invalid_keys():
for key in [None, "", " ", "bad/key", "é", "a" * 129, "a\tb"]:
post(client, alice, chat, {"text": unique("invalid")}, key, 400)
check(not occurrences(client, alice, chat, unique("invalid")), "invalid key created a message")
for key in ["a", "A._:-09", "x" * 128]:
text = unique("valid-" + str(len(key))) + key[:2]
first = post(client, alice, chat, {"text": text}, key)
check(first["json"]["text"] == text, "valid boundary key rejected")
case("idempotency_key_boundaries", invalid_keys)
def replay_conflict():
key, text = unique("key"), unique("original")
first = post(client, alice, chat, {"text": text}, key)
second = post(client, alice, chat, {"text": text}, key)
check(first["status"] == second["status"] == 201 and first["json"] == second["json"],
"replay did not return original 201 and Message")
raw = b'{ "text" : ' + json.dumps(text, ensure_ascii=False).encode("utf-8") + b' }'
equivalent = client.call("POST", message_path(chat), 201, actor=alice, raw=raw,
headers={"Idempotency-Key": key, "Content-Type": "application/json"},
schema="Message")
check(equivalent["json"] == first["json"], "equivalent JSON replay changed Message")
post(client, alice, chat, {"text": unique("changed")}, key, 409)
check(len(occurrences(client, alice, chat, text)) == 1, "replay created duplicate")
check(not occurrences(client, alice, chat, unique("changed")), "conflict wrote new message")
case("idempotency_replay_and_conflict", replay_conflict)
def replay_across_replica():
aliases = observe_instances(client, alice)
key, text = unique("replica-key"), unique("replica")
first = post(client, alice, chat, {"text": text}, key)
first_alias = first["headers"].get("X-Instance-Id")
check(first_alias in aliases, "initial response came from unknown instance")
for _ in range(100):
repeated = post(client, alice, chat, {"text": text}, key)
check(repeated["json"] == first["json"], "cross-replica replay changed Message")
if repeated["headers"].get("X-Instance-Id") != first_alias:
check(len(occurrences(client, alice, chat, text)) == 1,
"cross-replica replay created duplicate")
return
raise Failure("LB never routed replay to another instance")
case("idempotency_replay_across_replica", replay_across_replica)
def independent_scope():
key, text = unique("scope-key"), unique("scope")
a = post(client, alice, chat, {"text": text + " A"}, key)["json"]
b = post(client, bob, chat, {"text": text + " B"}, key)["json"]
c = post(client, alice, other_chat, {"text": text + " C"}, key)["json"]
check(len({a["id"], b["id"], c["id"]}) == 3, "key scope collided across user/chat")
for actor, target, body, original in [(alice, chat, text + " A", a),
(bob, chat, text + " B", b),
(alice, other_chat, text + " C", c)]:
check(post(client, actor, target, {"text": body}, key)["json"] == original,
"scoped replay changed original")
case("idempotency_user_chat_scope", independent_scope)
def concurrent():
key, text = unique("concurrent-key"), unique("concurrent")
workers = int(config.get("concurrency", 12))
check(2 <= workers <= 64, "concurrency must be 2..64")
gate = threading.Barrier(workers)
def one(_):
gate.wait(timeout=10)
return post(client_for(config), alice, chat, {"text": text}, key)
with ThreadPoolExecutor(max_workers=workers) as pool:
responses = list(pool.map(one, range(workers)))
check(all(r["status"] == 201 and r["json"] == responses[0]["json"] for r in responses),
"concurrent replay returned different status/Message")
check(len(occurrences(client, alice, chat, text)) == 1, "concurrent requests made duplicate")
ids = {r["headers"].get("X-Instance-Id") for r in responses}
evidence.record("concurrent_idempotency", attempts=workers, observed_instances=sorted(ids))
check(len(ids) >= 2, "concurrent requests did not traverse two LB backends")
case("idempotency_concurrent_cross_replica", concurrent)
def auth_rechecked():
key, text = unique("auth-key"), unique("auth")
post(client, alice, chat, {"text": text}, key)
client.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=alice)
post(client, alice, chat, {"text": text}, key, 401)
post(client, eve, chat, {"text": text}, key, 404)
check(len(occurrences(client, bob, chat, text)) == 1, "auth retry modified message")
case("idempotency_session_and_foreign_access", auth_rechecked)
# The fixture owns one message in this chat. The isolated adapter temporarily
# assigns it to the other member so the FK permits removing the original sender.
def access_rechecked():
if not all(config.get("hooks", {}).get(name) for name in ("revoke_access", "restore_access")):
raise Pending("configure isolated hooks.revoke_access/restore_access for synthetic fixture")
client2, owner, member, outsider, target, _ = bootstrap(config)
key, text = unique("acl-key"), unique("acl")
first = post(client2, owner, target, {"text": text}, key)["json"]
evidence.record("access_hook_target", chat_id=target["id"], user_id=owner["id"],
replacement_user_id=member["id"], message_id=first["id"])
env = config.setdefault("hook_context", {})
env.update({"TEST_CHAT_ID": target["id"], "TEST_USER_ID": owner["id"],
"TEST_REPLACEMENT_USER_ID": member["id"], "TEST_MESSAGE_ID": first["id"],
"TEST_IDEMPOTENCY_KEY": key})
try:
hook(config, "revoke_access", evidence)
post(client2, owner, target, {"text": text}, key, 404)
finally:
hook(config, "restore_access", evidence)
check(post(client2, owner, target, {"text": text}, key)["json"] == first,
"replay after access restoration returned a different Message")
check(len(occurrences(client2, member, target, text)) == 1,
"access restoration left duplicate message")
case("idempotency_access_rechecked_after_membership_change", access_rechecked)
def replay_after_restart():
client3, owner, member, outsider, target, _ = bootstrap(config)
key, text = unique("restart-key"), unique("restart")
first = post(client3, owner, target, {"text": text}, key)["json"]
hook(config, "restart", evidence, timeout=90)
deadline = time.monotonic() + 90
while True:
try:
client3.call("GET", "/health/ready", schema="Health")
break
except Failure:
check(time.monotonic() < deadline, "LB did not recover after restart")
time.sleep(.2)
check(post(client3, owner, target, {"text": text}, key)["json"] == first,
"idempotency result changed after restart")
check(len(occurrences(client3, member, target, text)) == 1,
"restart retry created duplicate")
case("idempotency_survives_restart", replay_after_restart)
def uncertain_replay():
client4, owner, member, outsider, target, _ = bootstrap(config)
key, text = unique("uncertain-key"), unique("uncertain")
url = urlsplit(client4.base)
check(url.scheme in ("http", "https") and url.hostname, "invalid LB URL")
path = message_path(target)
body = json.dumps({"text": text}, ensure_ascii=False).encode("utf-8")
request = ("POST " + path + " HTTP/1.1\r\nHost: " + url.netloc +
"\r\nConnection: close\r\nAuthorization: Bearer " + owner["token"] +
"\r\nIdempotency-Key: " + key +
"\r\nContent-Type: application/json\r\nContent-Length: " + str(len(body)) +
"\r\n\r\n").encode("ascii") + body
sock = socket.create_connection((url.hostname, url.port or (443 if url.scheme == "https" else 80)), 3)
try:
if url.scheme == "https":
context = ssl.create_default_context(cafile=config.get("ca_file"))
sock = context.wrap_socket(sock, server_hostname=url.hostname)
sock.sendall(request)
# Deliberately discard the response. The first request may or may not commit.
finally:
sock.close()
result = post(client4, owner, target, {"text": text}, key)["json"]
check(len(occurrences(client4, member, target, text)) == 1, "uncertain retry duplicated message")
check(result["text"] == text, "uncertain retry returned wrong message")
case("idempotency_after_disconnected_client", uncertain_replay)
def timed_out_replay():
client5, owner, member, outsider, target, _ = bootstrap(config)
key, text = unique("timeout-key"), unique("timeout")
upstream = urlsplit(client5.base)
forwarded = threading.Event()
release = threading.Event()
upstream_result = {}
class DelayedResponse(BaseHTTPRequestHandler):
def log_message(self, *_):
pass
def do_POST(self):
connection = None
try:
length = int(self.headers["Content-Length"])
body = self.rfile.read(length)
connection_type = (http.client.HTTPSConnection if upstream.scheme == "https"
else http.client.HTTPConnection)
options = {"timeout": 5}
if upstream.scheme == "https":
options["context"] = ssl.create_default_context(cafile=config.get("ca_file"))
connection = connection_type(upstream.hostname, upstream.port or
(443 if upstream.scheme == "https" else 80), **options)
headers = {k: v for k, v in self.headers.items()
if k.lower() not in ("host", "connection", "content-length")}
headers["Content-Length"] = str(len(body))
connection.request("POST", self.path, body=body, headers=headers)
response = connection.getresponse()
payload = response.read()
upstream_result["status"] = response.status
upstream_result["body"] = payload
except Exception as exc:
upstream_result["error"] = type(exc).__name__
finally:
forwarded.set()
release.wait(5)
if connection:
connection.close()
try:
self.send_response(upstream_result.get("status", 502))
self.end_headers()
self.wfile.write(upstream_result.get("body", b""))
except OSError:
pass
proxy = ThreadingHTTPServer(("127.0.0.1", 0), DelayedResponse)
proxy.daemon_threads = True
server_thread = threading.Thread(target=proxy.serve_forever, daemon=True)
server_thread.start()
try:
short = Client("http://127.0.0.1:%d" % proxy.server_port, timeout=0.01)
try:
post(short, owner, target, {"text": text}, key)
except Failure as exc:
check("connection/TLS failure" in str(exc), "delayed request failed for a reason other than timeout")
else:
raise Failure("delayed response did not produce a client timeout")
check(forwarded.wait(5), "test proxy did not forward the timed-out POST")
check(upstream_result.get("status") == 201,
"timed-out POST did not commit through public LB: " +
str(upstream_result.get("error", upstream_result.get("status"))))
finally:
release.set()
proxy.shutdown()
proxy.server_close()
server_thread.join(timeout=5)
committed = occurrences(client5, member, target, text)
check(len(committed) == 1, "timed-out first request was not committed before retry")
result = post(client5, owner, target, {"text": text}, key)["json"]
check(result == committed[0] and len(occurrences(client5, member, target, text)) == 1,
"retry after timeout did not resolve to exactly one message")
case("idempotency_after_client_timeout", timed_out_replay)
failed = [name for name in executed if evidence.summary[name]["status"] == "FAIL"]
pending = [name for name in executed if evidence.summary[name]["status"] == "PENDING_INFRA"]
check(not failed, "idempotency cases failed: " + ", ".join(failed))
if pending:
raise Pending("idempotency cases awaiting infrastructure: " + ", ".join(pending))
def observe_instances(client, actor, count=60):
ids = set()
for _ in range(count):
response = client.call("GET", "/api/v1/users/me", actor=actor, schema="User")
ids.add(response["headers"].get("X-Instance-Id"))
check(len(ids) >= 2, "public LB exposed fewer than two X-Instance-Id values")
return sorted(ids)
def wait_instances(client, actor, timeout=10):
deadline = time.monotonic() + timeout
while True:
try:
return observe_instances(client, actor, count=24)
except Failure:
if time.monotonic() >= deadline:
raise
time.sleep(.25)
def load_window(config, evidence, client, actor, chat, seconds, label, expected_instance=None):
start, successes, failures, reads, latencies, observed = time.monotonic(), 0, 0, 0, [], set()
started_at_utc = datetime.now(timezone.utc).isoformat(timespec="milliseconds")
error_events = []
first_good, first_read = None, None
pending_key = uuid.uuid4().hex
pending_text = "lab3-" + uuid.uuid4().hex
attempted_texts, confirmed_texts = set(), set()
while time.monotonic() - start < seconds:
attempted_texts.add(pending_text)
request_started_at_utc = datetime.now(timezone.utc).isoformat(timespec="milliseconds")
try:
response = post(client, actor, chat, {"text": pending_text}, pending_key)
successes += 1
confirmed_texts.add(pending_text)
latencies.append(response["elapsed"])
observed.add(response["headers"].get("X-Instance-Id"))
if first_good is None:
first_good = time.monotonic() - start
pending_key, pending_text = uuid.uuid4().hex, "lab3-" + uuid.uuid4().hex
except Failure as exc:
failures += 1
error_events.append({"seconds": round(time.monotonic() - start, 3),
"operation": "POST", "detail": str(exc)[:160],
"request_started_at_utc": request_started_at_utc,
"failed_at_utc": datetime.now(timezone.utc).isoformat(timespec="milliseconds")})
request_started_at_utc = datetime.now(timezone.utc).isoformat(timespec="milliseconds")
try:
response = client.call("GET", message_path(chat) + "?limit=1", actor=actor, schema="MessagePage")
reads += 1
if first_read is None:
first_read = time.monotonic() - start
observed.add(response["headers"].get("X-Instance-Id"))
except Failure as exc:
failures += 1
error_events.append({"seconds": round(time.monotonic() - start, 3),
"operation": "GET", "detail": str(exc)[:160],
"request_started_at_utc": request_started_at_utc,
"failed_at_utc": datetime.now(timezone.utc).isoformat(timespec="milliseconds")})
elapsed = time.monotonic() - start
summary = {"label": label, "duration_seconds": round(elapsed, 3),
"started_at_utc": started_at_utc,
"ended_at_utc": datetime.now(timezone.utc).isoformat(timespec="milliseconds"),
"successful_write_rps": round(successes / elapsed, 3),
"successful_writes": successes, "successful_reads": reads,
"errors": failures, "first_success_seconds": first_good,
"first_read_seconds": first_read,
"observed_instances": sorted(observed), "latency_seconds": latencies,
"error_events": error_events}
evidence.record("load_window", **summary)
check(successes > 0 and reads > 0, label + ": no successful reads/writes")
if expected_instance:
check(expected_instance not in observed, label + ": stopped/unready backend still served traffic")
summary["_attempted_texts"] = attempted_texts
summary["_confirmed_texts"] = confirmed_texts
return summary
def failover(config, evidence):
client, alice, bob, eve, chat, _ = bootstrap(config)
aliases = observe_instances(client, alice)
evidence.record("lb_instances", aliases=aliases)
for target in aliases:
def one():
before_docker = api_by_alias(config)
check(target in before_docker and len(before_docker) >= 2 and
all(item["State"]["Running"] for item in before_docker.values()),
"target alias does not map to one of two running API containers")
old = before_docker[target]
stable_key = uuid.uuid4().hex
stable_text = "lab3-before-" + uuid.uuid4().hex
before = post(client, alice, chat, {"text": stable_text}, stable_key)["json"]
stop_start = time.monotonic()
hook(config, "stop_one", evidence, target=target, timeout=10)
hook_elapsed = time.monotonic() - stop_start
stopped = api_by_alias(config)
check(target in stopped and stopped[target]["Id"] == old["Id"] and
not stopped[target]["State"]["Running"] and
any(item["State"]["Running"] for alias, item in stopped.items() if alias != target),
"stop hook did not stop exactly the selected API container")
try:
result = load_window(config, evidence, client_for(config, timeout=1), alice,
chat, float(config.get("failover_window_seconds", 15)),
"stop_" + target, expected_instance=target)
write_recovery = hook_elapsed + result["first_success_seconds"]
read_recovery = hook_elapsed + result["first_read_seconds"]
evidence.record("failover_recovery", target_instance=target,
write_seconds=round(write_recovery, 3), read_seconds=round(read_recovery, 3))
check(write_recovery <= 10 and read_recovery <= 10,
"read/write did not recover within 10 seconds from stop start")
check(before in history(client, bob, chat), "confirmed message lost after stop")
check(post(client, alice, chat, {"text": stable_text}, stable_key)["json"] == before,
"replay after replica stop returned different Message")
actual_texts = [m["text"] for m in history(client, bob, chat)
if m["text"] in result["_attempted_texts"]]
check(len(actual_texts) == len(set(actual_texts)),
"uncertain failover retry created duplicate")
check(result["_confirmed_texts"].issubset(set(actual_texts)),
"confirmed write disappeared during failover")
finally:
hook(config, "start_one", evidence, target=target, timeout=60)
restarted = api_by_alias(config)
check(target in restarted and restarted[target]["Id"] == old["Id"] and
restarted[target]["State"]["Running"] and
restarted[target]["State"]["StartedAt"] != old["State"]["StartedAt"] and
volume_names(restarted[target]) == volume_names(old),
"selected API container did not restart with same ID/volumes")
evidence.record("failover_docker", target_instance=target,
container_id=old["Id"],
started_at_before=old["State"]["StartedAt"],
started_at_after=restarted[target]["State"]["StartedAt"],
volumes=volume_names(old))
deadline = time.monotonic() + 30
while True:
try:
observed = observe_instances(client, alice)
if len(observed) >= 2:
break
except Failure:
pass
check(time.monotonic() < deadline, "second replica did not return through LB")
time.sleep(.25)
evidence.case("failover_" + target, one)
failed = [alias for alias in aliases if evidence.summary["failover_" + alias]["status"] != "PASS"]
check(not failed, "replica failover failed: " + ", ".join(failed))
def grade4(config, evidence, only=None):
def case(name, fn):
if only is None or name in ("rolling_update_under_load", "rolling_update_zero_http_errors_quality"):
evidence.case(name, fn)
def health():
client = public_ready(config)
client.call("GET", "/health/live", schema="Health")
client.call("GET", "/health/ready", schema="Health")
evidence.record("health", live=200, ready=200)
case("health_live_ready", health)
def topology():
argv = config.get("compose_config_argv", ["docker", "compose", "config", "--format", "json"])
try:
proc = subprocess.run(argv, cwd=ROOT, capture_output=True, timeout=15, check=False)
except (OSError, subprocess.TimeoutExpired):
raise Pending("Docker Compose config unavailable") from None
if proc.returncode:
raise Pending("Docker Compose config unavailable; provide .env/secrets and compose_config_argv")
try:
services = json.loads(proc.stdout)["services"]
except (ValueError, KeyError):
raise Failure("Compose config did not return services JSON") from None
apis = config.get("api_services") or [name for name in services if name == "api" or name.startswith("api-")]
lbs = config.get("lb_services") or [name for name in services if name in ("lb", "proxy", "nginx", "haproxy", "traefik")]
issues = []
if not lbs or not all(name in services for name in lbs):
issues.append("no configured LB service")
if not apis or not all(name in services for name in apis):
issues.append("no configured API service")
runtime = {}
project = None
for name, service in services.items():
deploy = service.get("deploy", {})
limits = deploy.get("resources", {}).get("limits", {})
if not ((limits.get("cpus") or service.get("cpus")) and
(limits.get("memory") or service.get("mem_limit"))):
issues.append(name + " lacks CPU/RAM limits")
ids = compose_ids(config, name, all_containers=True)
if not ids:
issues.append(name + " has no Docker container")
runtime[name] = []
for identifier in ids:
raw = inspect_container(identifier)
labels = raw.get("Config", {}).get("Labels", {})
observed_project = labels.get("com.docker.compose.project")
if project is None:
project = observed_project
if not observed_project or observed_project != project or labels.get("com.docker.compose.service") != name:
issues.append(name + " container has wrong Compose ownership")
host = raw.get("HostConfig", {})
cpu = host.get("NanoCpus", 0)
memory = host.get("Memory", 0)
if not (isinstance(cpu, int) and cpu > 0 and isinstance(memory, int) and memory > 0):
issues.append(name + " lacks enforced Docker CPU/RAM limits")
runtime[name].append({"id": raw["Id"], "running": raw["State"]["Running"],
"exit_code": raw["State"].get("ExitCode"),
"nano_cpus": cpu, "memory_bytes": memory,
"healthcheck": bool(raw.get("Config", {}).get("Healthcheck")),
"port_bindings": host.get("PortBindings") or {}})
for name in apis:
if name not in services:
continue
service = services[name]
if service.get("ports"):
issues.append(name + " publishes an API port around the LB")
if service.get("container_name"):
issues.append(name + " has a scaling-blocking container_name")
if not service.get("healthcheck") and not all(x["healthcheck"] for x in runtime[name]):
issues.append(name + " has no healthcheck")
if not service.get("stop_grace_period"):
issues.append(name + " has no stop_grace_period")
replicas = sum(int(services[name].get("deploy", {}).get("replicas",
services[name].get("scale", 1))) for name in apis if name in services)
if replicas < 2:
issues.append("fewer than two API replicas declared")
if sum(x["running"] for name in apis for x in runtime.get(name, [])) < 2:
issues.append("fewer than two running API containers")
for name in apis:
if any(x["port_bindings"] for x in runtime.get(name, [])):
issues.append(name + " has a direct Docker host port binding")
migrate = services.get("migrate")
if not migrate:
issues.append("migration service missing")
evidence.record("compose_topology", api_services=apis, declared_replicas=replicas,
lb_services=lbs, migration_service="migrate" if migrate else None,
project=project, runtime=runtime, issues=issues)
check(not issues, "; ".join(issues))
case("compose_lb_limits_ports_migration_layout", topology)
def readiness_exclusion():
client, alice, bob, eve, chat, _ = bootstrap(config)
aliases = observe_instances(client, alice)
target = aliases[0]
unready_start = time.monotonic()
hook(config, "make_unready", evidence, target=target)
try:
direct = probe(config, evidence, "probe_health", target)
check(direct.get("live_status") == 200 and direct.get("ready_status") == 503,
"unready replica must remain live and return ready=503")
deadline = unready_start + 10
while True:
try:
observed = [client.call("GET", "/api/v1/users/me", actor=alice, schema="User")
["headers"]["X-Instance-Id"] for _ in range(12)]
if target not in observed:
break
except Failure:
pass
check(time.monotonic() < deadline, "LB did not exclude unready replica within 10 seconds")
time.sleep(.2)
evidence.record("readiness_exclusion", target_instance=target,
elapsed_seconds=round(time.monotonic() - unready_start, 3))
result = load_window(config, evidence, client, alice, chat, 3, "unready", expected_instance=target)
check(result["errors"] == 0, "LB still sent requests to unready backend")
finally:
hook(config, "restore_ready", evidence, target=target)
wait_instances(client, alice, timeout=10)
case("lb_excludes_unready_replica", readiness_exclusion)
def lb_timing():
argv = config.get("hooks", {}).get("lb_timing_evidence")
if not isinstance(argv, list) or not argv:
raise Pending("configure hooks.lb_timing_evidence for LB health interval/timeout")
proc = subprocess.run(argv, cwd=ROOT, capture_output=True, timeout=10, check=False)
check(proc.returncode == 0, "LB timing evidence hook failed")
try:
value = json.loads(proc.stdout)
except ValueError:
raise Failure("LB timing evidence hook must return JSON") from None
interval = value.get("health_interval_seconds")
timeout = value.get("health_timeout_seconds")
detection = value.get("configured_max_detection_seconds")
check(all(isinstance(x, (int, float)) and not isinstance(x, bool) and x > 0
for x in (interval, timeout, detection)), "LB timing values must be positive numbers")
check(detection <= 10, "configured LB detection exceeds 10 seconds")
evidence.record("lb_timing", health_interval_seconds=interval,
health_timeout_seconds=timeout,
configured_max_detection_seconds=detection)
case("lb_health_timing", lb_timing)
def sigterm():
client, alice, bob, eve, chat, _ = bootstrap(config)
target = wait_instances(client, alice)[0]
hook(config, "sigterm_one", evidence, target=target, timeout=10)
try:
direct = probe(config, evidence, "probe_stopped", target)
check(direct.get("accepting") is False, "terminated replica still accepts requests")
load_window(config, evidence, client, alice, chat, 10, "sigterm", expected_instance=target)
finally:
hook(config, "start_one", evidence, target=target, timeout=60)
case("sigterm_drains_and_stops_accepting", sigterm)
rolling_result = {}
def rolling():
client, alice, bob, eve, chat, _ = bootstrap(config)
before = wait_instances(client, alice)
old_containers = [inspect_container(identifier) for identifier in compose_ids(config, "api")]
old_ids = {item["Id"] for item in old_containers}
check(len(old_ids) == 2 and all(item["State"]["Running"] for item in old_containers),
"rolling update requires two running API containers")
argv = config.get("hooks", {}).get("rolling_update")
if not isinstance(argv, list) or not argv:
raise Pending("configure hooks.rolling_update for sequential replacement under load")
telemetry = bool(config.get("rolling_telemetry"))
captures = []
since = str(int(time.time()))
telemetry_dir = evidence.directory / "rolling-telemetry"
if telemetry:
telemetry_dir.mkdir(exist_ok=True)
project = old_containers[0]["Config"]["Labels"]["com.docker.compose.project"]
lb_ids = compose_ids(config, "lb")
check(len(lb_ids) == 1, "rolling telemetry needs one LB container")
def capture(name, command):
output = (telemetry_dir / (name + ".log")).open("wb")
errors = (telemetry_dir / (name + ".stderr.log")).open("wb")
watcher = subprocess.Popen(command, cwd=ROOT, stdout=output, stderr=errors)
captures.append((watcher, output, errors))
capture("docker-events", ["docker", "events", "--filter", "type=container",
"--filter", "label=com.docker.compose.project=" + project,
"--format", "{{json .}}"])
capture("haproxy", ["docker", "logs", "--follow", "--timestamps", "--since", since, lb_ids[0]])
for identifier in sorted(old_ids):
capture("api-old-" + identifier[:12],
["docker", "logs", "--follow", "--timestamps", "--since", since, identifier])
time.sleep(.2)
rolling_env = dict(os.environ)
if telemetry:
rolling_env["HL_ROLLING_TRACE_ACTIVE"] = "1"
process = subprocess.Popen(argv, cwd=ROOT, env=rolling_env, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, start_new_session=True)
try:
result = load_window(config, evidence, client_for(config, timeout=1), alice, chat,
float(config.get("rolling_window_seconds", 20)), "rolling")
output, errors = process.communicate(timeout=90)
if telemetry:
(telemetry_dir / "rolling-script.stdout.log").write_bytes(output)
(telemetry_dir / "rolling-script.stderr.log").write_bytes(errors)
check(process.returncode == 0, "rolling update hook failed")
try:
lifecycle = json.loads(output)
except ValueError:
raise Failure("rolling hook must return lifecycle JSON") from None
check(lifecycle.get("replaced_processes", 0) >= 2 and
lifecycle.get("min_ready_during_update", 0) >= 1,
"rolling hook did not prove sequential replacement and a ready backend")
after = observe_instances(client, alice)
new_containers = [inspect_container(identifier) for identifier in compose_ids(config, "api")]
new_ids = {item["Id"] for item in new_containers}
check(len(new_ids) == 2 and not old_ids.intersection(new_ids) and
all(item["State"]["Running"] for item in new_containers),
"rolling update did not replace both real API containers")
evidence.record("rolling_update", before=before, after=after,
old_container_ids=sorted(old_ids), new_container_ids=sorted(new_ids),
replaced_processes=lifecycle["replaced_processes"],
min_ready_during_update=lifecycle["min_ready_during_update"],
errors=result["errors"], successful_write_rps=result["successful_write_rps"])
rolling_result.update(result)
finally:
if process.poll() is None:
process.terminate()
process.wait(timeout=5)
if telemetry:
for watcher, output_stream, error_stream in captures:
if watcher.poll() is None:
watcher.terminate()
watcher.wait(timeout=5)
output_stream.close()
error_stream.close()
try:
for identifier in compose_ids(config, "api"):
if identifier not in old_ids:
proc = subprocess.run(["docker", "logs", "--timestamps", "--since", since,
identifier], cwd=ROOT, capture_output=True, timeout=10)
(telemetry_dir / ("api-new-" + identifier[:12] + ".log")).write_bytes(
proc.stdout + proc.stderr)
except (OSError, subprocess.SubprocessError, Pending):
evidence.record("rolling_telemetry_incomplete", reason="new API logs unavailable")
case("rolling_update_under_load", rolling)
def rolling_quality():
if not rolling_result:
raise Pending("rolling update did not complete; inspect rolling_update_under_load")
check(rolling_result["errors"] == 0, "rolling update had %d HTTP errors" % rolling_result["errors"])
case("rolling_update_zero_http_errors_quality", rolling_quality)
def migration_once():
# A one-time historical fact requires lifecycle evidence, not just a current
# Compose snapshot. An adapter must count actual migration starts for this run.
argv = config.get("hooks", {}).get("migration_evidence")
if not isinstance(argv, list) or not argv:
raise Pending("configure hooks.migration_evidence to count actual migration starts")
proc = subprocess.run(argv, cwd=ROOT, capture_output=True, timeout=20, check=False)
check(proc.returncode == 0, "migration evidence hook failed")
try:
value = json.loads(proc.stdout)
except ValueError:
raise Failure("migration evidence hook must return JSON") from None
check(value.get("migration_starts") == 1 and value.get("migration_exit_code") == 0,
"migrations did not start exactly once and exit successfully")
check(value.get("api_started_before_migration_complete") is False,
"API started before migration completed")
evidence.record("migration_once", migration_starts=1, migration_exit_code=0,
api_started_before_migration_complete=False)
case("migrations_started_once", migration_once)
def public_checks(config, evidence):
def run_make(target, action=None, label=None):
public_ready(config)
argv = ["make", target, "BASE_URL=" + config["base_url"]]
if config.get("ca_file"):
argv.append("CA_FILE=" + config["ca_file"])
if action:
script = config.get("hooks", {}).get(action)
if not isinstance(script, list) or len(script) != 1:
raise Pending("public %s requires hooks.%s with one executable script path" % (target, action))
path = Path(script[0])
if not path.is_absolute():
path = ROOT / path
if not path.is_file() or not os.access(path, os.X_OK):
raise Pending("public %s action script is missing or not executable" % target)
argv.append("ACTION_SCRIPT=" + str(path))
started = time.monotonic()
try:
proc = subprocess.run(argv, cwd=ROOT, capture_output=True, timeout=180, check=False)
except (OSError, subprocess.TimeoutExpired) as exc:
raise Failure("%s failed to launch or timed out (%s)" % (target, type(exc).__name__)) from None
stem = label or target
(evidence.directory / (stem + ".stdout.log")).write_bytes(proc.stdout)
(evidence.directory / (stem + ".stderr.log")).write_bytes(proc.stderr)
evidence.record("public_make", target=target, label=stem, exit_code=proc.returncode,
elapsed_seconds=round(time.monotonic() - started, 3))
check(proc.returncode == 0, target + " failed; inspect its saved stdout/stderr")
evidence.case("public_make_test", lambda: run_make("test"))
evidence.case("public_make_test_persistence", lambda: run_make("test-persistence", "restart"))
def both_failovers():
if not config.get("hooks", {}).get("recover_all"):
raise Pending("configure hooks.recover_all before public failover")
stopped_aliases = set()
for attempt in range(1, 5):
before = api_by_alias(config)
check(len(before) == 2 and all(item["State"]["Running"] for item in before.values()),
"public failover requires two running API containers")
try:
run_make("test-failover", "stop_one", label="test-failover-%d" % attempt)
after = api_by_alias(config)
stopped = [alias for alias, item in after.items() if not item["State"]["Running"]]
check(len(stopped) == 1 and stopped[0] in before and
after[stopped[0]]["Id"] == before[stopped[0]]["Id"],
"public failover did not leave exactly its selected replica stopped")
stopped_aliases.add(stopped[0])
evidence.record("public_failover_target", attempt=attempt,
target_instance=stopped[0], container_id=after[stopped[0]]["Id"])
finally:
hook(config, "recover_all", evidence, timeout=60)
if len(stopped_aliases) == 2:
break
check(len(stopped_aliases) == 2,
"public make test-failover did not exercise both API replicas in four attempts")
evidence.case("public_make_test_failover_both_replicas", both_failovers)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--config", required=True, help="JSON config with PUBLIC LB address and optional hooks")
parser.add_argument("--output", required=True, help="directory for raw, token-free results")
parser.add_argument("--scenario", choices=["idempotency", "restart", "failover", "grade4", "rolling", "public", "all"], default="all")
args = parser.parse_args()
evidence = Evidence(args.output)
try:
config = json.loads(Path(args.config).read_text(encoding="utf-8"))
except (OSError, ValueError) as exc:
evidence.case("configuration", lambda: (_ for _ in ()).throw(Failure(str(exc))))
return evidence.finish()
if args.scenario in ("idempotency", "restart", "all"):
only = "idempotency_survives_restart" if args.scenario == "restart" else None
evidence.case("idempotency_setup_and_suite", lambda: idempotency(config, evidence, only))
if args.scenario in ("failover", "all"):
evidence.case("public_lb_failover", lambda: failover(config, evidence))
if args.scenario in ("grade4", "all"):
grade4(config, evidence)
if args.scenario == "rolling":
grade4(config, evidence, only="rolling")
if args.scenario in ("public", "all"):
public_checks(config, evidence)
return evidence.finish()
if __name__ == "__main__":
raise SystemExit(main())