Files

1333 lines
73 KiB
Python

#!/usr/bin/env python3
"""Lab 4 inherited HA/idempotency and attachment checks. All traffic uses the configured public LB URL."""
import argparse
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timezone
import http.client
import hashlib
import math
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
def requirement(name):
if name.endswith("_quality"):
return "additional_quality"
if name in ("attachment_negative_uploads", "attachment_compensation", "attachment_parallel_memory",
"attachment_bucket_security"):
return "lab4_grade4"
if name.startswith("attachment_"):
return "lab4_grade3"
if name.startswith(("idempotency_", "public_", "health_", "lb_")):
return "inherited_contract_or_requested_check"
return "requested_operational_check"
def require_hooks(config, *names):
for name in names:
argv = config.get("hooks", {}).get(name)
if not isinstance(argv, list) or not argv or not all(isinstance(v, str) and v for v in argv):
raise Pending("configure hooks.%s before starting the fault" % name)
class Evidence:
def __init__(self, directory):
self.directory = Path(directory).resolve()
self.directory.mkdir(parents=True, exist_ok=True)
if any(self.directory.iterdir()):
raise ValueError("output directory must be empty; preserve previous raw evidence")
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),
"requirement": requirement(name)}
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 == 201:
message = response["json"]
# UUID spelling in a server response may be canonical. Preserve order
# and identity checks without requiring the input's letter case back.
returned_ids = [uuid.UUID(value) for value in message["attachment_ids"]]
submitted_ids = [uuid.UUID(value) for value in body.get("attachment_ids", [])]
check(message["chat_id"] == chat["id"] and message["sender_id"] == actor["id"] and
message["text"] == body["text"] and returned_ids == submitted_ids,
"Message does not match submitted chat, sender, text or attachments")
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")
origin = urlsplit(url)
check(origin.hostname and not origin.username and not origin.password and
origin.path in ("", "/") and not origin.query and not origin.fragment,
"base_url must be an origin without credentials, path or query")
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 api_ids(config, 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 api_ids(config, all_containers=False):
return [identifier for service in config.get("api_services", ["api"])
for identifier in compose_ids(config, service, all_containers=all_containers)]
def volume_names(raw):
return sorted(m["Name"] for m in raw.get("Mounts", []) if m.get("Type") == "volume")
def lifecycle_snapshot(config):
result = {}
for service in config.get("restart_services", ["api", "postgres", "redis", "s3", "lb", "migrate"]):
values = []
for identifier in compose_ids(config, service, all_containers=True):
raw = inspect_container(identifier)
values.append({"id": raw["Id"], "started_at": raw["State"]["StartedAt"],
"running": raw["State"]["Running"], "volumes": volume_names(raw)})
check(values, "no lifecycle evidence for service " + service)
result[service] = values
return result
def verify_restart(before, after, evidence):
evidence.record("restart_lifecycle", before=before, after=after)
check(before.keys() == after.keys(), "restart changed the set of services")
for service, values in before.items():
old = {v["id"]: v for v in values}
new = {v["id"]: v for v in after[service]}
check(old.keys() == new.keys(), service + ": restart must preserve containers")
for identifier, previous in old.items():
current = new[identifier]
check(current["volumes"] == previous["volumes"], service + ": volumes changed")
if service == "migrate":
check(current["started_at"] == previous["started_at"], "restart reran migrations")
else:
check(current["running"] and current["started_at"] != previous["started_at"],
service + ": hook did not restart the process")
def public_endpoint(config, evidence):
url = urlsplit(config["base_url"])
check(url.scheme in ("http", "https") and url.hostname and not url.username and
not url.password and url.path in ("", "/") and not url.query and not url.fragment,
"base_url must be a public LB origin without credentials, path or query")
port = url.port or (443 if url.scheme == "https" else 80)
bindings = []
for service in config.get("lb_services", ["lb"]):
for identifier in compose_ids(config, service):
raw = inspect_container(identifier)
for bound in (raw.get("NetworkSettings", {}).get("Ports") or {}).values():
bindings.extend(bound or [])
check(any(int(b["HostPort"]) == port for b in bindings),
"base_url port is not published by the selected LB")
for service in config.get("api_services", ["api"]):
for identifier in compose_ids(config, service, all_containers=True):
raw = inspect_container(identifier)
check(not any((raw.get("HostConfig", {}).get("PortBindings") or {}).values()),
"API publishes a direct port; select a topology with LB as sole entrypoint")
evidence.record("public_lb_endpoint", port=port, bindings=bindings)
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": "Lab4 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):
names = ("idempotency_key_boundaries", "idempotency_replay_and_conflict",
"idempotency_replay_across_replica", "idempotency_user_chat_scope",
"idempotency_concurrent_cross_replica", "idempotency_session_and_foreign_access",
"idempotency_access_rechecked_after_membership_change", "idempotency_survives_restart",
"idempotency_after_disconnected_client", "idempotency_after_client_timeout")
try:
client, alice, bob, eve, chat, other_chat = bootstrap(config)
except (Failure, Pending) as exc:
def unavailable():
raise exc
for name in names:
if only is None or name == only:
evidence.case(name, unavailable)
raise
prefix = "lab4-" + 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", "a+b", "a=b", "a!b", "a,b"]:
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", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._:-", "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'{ "attachment_ids": [], "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"]
before = lifecycle_snapshot(config)
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)
after = lifecycle_snapshot(config)
verify_restart(before, after, evidence)
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,
started=None, action_done=None, action_process=None):
start = time.monotonic() if started is None else started
successes, failures, reads, latencies, observed = 0, 0, 0, [], set()
after_action = 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 = "lab4-" + uuid.uuid4().hex
attempted_texts, confirmed_texts = set(), set()
maximum = float(config.get("rolling_max_seconds", 120))
while (time.monotonic() - start < seconds or
(action_process is not None and action_process.poll() is None)) and time.monotonic() - start < maximum:
settled = action_done is None or action_done.is_set()
attempted_texts.add(pending_text)
request_started_at_utc = datetime.now(timezone.utc).isoformat(timespec="milliseconds")
tick = time.monotonic()
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 settled:
after_action.add(response["headers"].get("X-Instance-Id"))
evidence.record("request", label=label, operation="POST", status=201,
seconds=round(time.monotonic() - start, 6),
elapsed_seconds=round(time.monotonic() - tick, 6),
instance=response["headers"].get("X-Instance-Id"),
message_id=response["json"]["id"], after_action=settled)
if settled and first_good is None:
first_good = time.monotonic() - start
pending_key, pending_text = uuid.uuid4().hex, "lab4-" + uuid.uuid4().hex
except Failure as exc:
failures += 1
evidence.record("request", label=label, operation="POST", status="error",
seconds=round(time.monotonic() - start, 6),
elapsed_seconds=round(time.monotonic() - tick, 6), detail=str(exc))
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")
settled = action_done is None or action_done.is_set()
tick = time.monotonic()
try:
response = client.call("GET", message_path(chat) + "?limit=1", actor=actor, schema="MessagePage")
reads += 1
if settled and first_read is None:
first_read = time.monotonic() - start
observed.add(response["headers"].get("X-Instance-Id"))
if settled:
after_action.add(response["headers"].get("X-Instance-Id"))
evidence.record("request", label=label, operation="GET", status=200,
seconds=round(time.monotonic() - start, 6),
elapsed_seconds=round(time.monotonic() - tick, 6),
instance=response["headers"].get("X-Instance-Id"), after_action=settled)
except Failure as exc:
failures += 1
evidence.record("request", label=label, operation="GET", status="error",
seconds=round(time.monotonic() - start, 6),
elapsed_seconds=round(time.monotonic() - tick, 6), detail=str(exc))
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,
"successful_read_rps": round(reads / elapsed, 3),
"error_fraction": failures / (successes + reads + failures),
"errors": failures, "first_success_seconds": first_good,
"first_read_seconds": first_read,
"observed_instances": sorted(observed), "after_action_instances": sorted(after_action),
"latency_seconds": latencies,
"p50_seconds": percentile(latencies, .50),
"p95_seconds": percentile(latencies, .95),
"p99_seconds": percentile(latencies, .99),
"error_events": error_events}
evidence.record("load_window", **summary)
if action_process is not None:
check(action_process.poll() is not None, "rolling update exceeded the load time budget")
check(successes > 0 and reads > 0, label + ": no successful reads/writes")
if expected_instance:
check(expected_instance not in after_action, label + ": stopped/unready backend still served traffic")
summary["_attempted_texts"] = attempted_texts
summary["_confirmed_texts"] = confirmed_texts
return summary
def percentile(values, fraction):
return sorted(values)[max(0, math.ceil(len(values) * fraction) - 1)] if values else None
def verify_load_history(client, actor, chat, result):
messages = history(client, actor, chat)
texts = [m["text"] for m in messages if m["text"] in result["_attempted_texts"]]
check(len(texts) == len(set(texts)), "uncertain request created duplicate message")
check(result["_confirmed_texts"].issubset(set(texts)), "confirmed write disappeared under load")
def failover(config, evidence):
client, alice, bob, eve, chat, _ = bootstrap(config)
aliases = observe_instances(client, alice)
check(set(aliases) == {alias for alias, item in api_by_alias(config).items() if item["State"]["Running"]},
"LB did not expose every running API replica with the same token")
evidence.record("lb_instances", aliases=aliases)
require_hooks(config, "stop_one", "start_one")
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 = "lab4-before-" + uuid.uuid4().hex
before = post(client, alice, chat, {"text": stable_text}, stable_key)["json"]
stop_start = time.monotonic()
stopped_event = threading.Event()
def stop():
hook(config, "stop_one", evidence, target=target, timeout=10)
stopped_event.set()
try:
with ThreadPoolExecutor(max_workers=1) as pool:
stopping = pool.submit(stop)
result = load_window(config, evidence, client_for(config, timeout=1), alice,
chat, float(config.get("failover_window_seconds", 15)),
"stop_" + target, expected_instance=target,
started=stop_start, action_done=stopped_event)
stopping.result()
stopped = api_by_alias(config)
check(target in stopped and stopped[target]["Id"] == old["Id"] and
not stopped[target]["State"]["Running"] and
all(item["State"]["Running"] for alias, item in stopped.items() if alias != target),
"stop hook did not stop exactly the selected API container")
write_recovery = result["first_success_seconds"]
read_recovery = result["first_read_seconds"]
check(write_recovery is not None and read_recovery is not None,
"no successful reads/writes after stop completed")
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")
verify_load_history(client, bob, chat, result)
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()
require_hooks(config, "make_unready", "restore_ready", "probe_health")
try:
hook(config, "make_unready", evidence, target=target)
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]
require_hooks(config, "sigterm_one", "start_one", "probe_stopped")
try:
hook(config, "sigterm_one", evidence, target=target, timeout=25)
direct = probe(config, evidence, "probe_stopped", target)
check(direct.get("accepting") is False, "terminated replica still accepts requests")
check(direct.get("signal") == "SIGTERM" and direct.get("forced_kill") is False and
direct.get("exit_code") == 0 and direct.get("connection_probe_performed") is True,
"probe must prove SIGTERM exit without SIGKILL and attempt a new connection")
result = load_window(config, evidence, client, alice, chat, 10, "sigterm", expected_instance=target)
verify_load_history(client, bob, chat, result)
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 api_ids(config)]
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.txt")).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",
action_process=process)
output, errors = process.communicate(timeout=5)
if telemetry:
(telemetry_dir / "rolling-script.stdout.txt").write_bytes(output)
(telemetry_dir / "rolling-script.stderr.txt").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 api_ids(config)]
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")
validate_rolling_steps(lifecycle, old_ids, new_ids)
verify_load_history(client, bob, chat, result)
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"],
steps=lifecycle["steps"],
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
validate_migration_events(value)
evidence.record("migration_once", **value)
case("migrations_started_once", migration_once)
def public_checks(config, evidence):
def run_make(target, action=None, label=None):
argv = ["make", target, "PYTHON=" + sys.executable, "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.txt")).write_bytes(proc.stdout)
(evidence.directory / (stem + ".stderr.txt")).write_bytes(proc.stderr)
evidence.record("public_make", target=target, label=stem, exit_code=proc.returncode,
elapsed_seconds=round(time.monotonic() - started, 3))
if proc.returncode:
public_ready(config) # An unreachable LB is PENDING_INFRA, never application PASS.
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):
try:
before = api_by_alias(config)
except Pending:
# Still attempt the explicitly requested public command and save
# its original result even when Docker cannot supply proof.
run_make("test-failover", "stop_one", label="test-failover-%d" % attempt)
raise
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 validate_rolling_steps(value, old_ids, new_ids):
steps = value.get("steps", [])
check(isinstance(steps, list) and len(steps) == len(old_ids), "rolling hook must provide each replacement step")
check({s.get("old_id") for s in steps} == old_ids and {s.get("new_id") for s in steps} == new_ids,
"rolling steps do not match real replaced containers")
last_end = 0
for step in steps:
begin, end = step.get("begin_ns"), step.get("end_ns")
check(isinstance(begin, int) and isinstance(end, int) and last_end <= begin < end,
"rolling replacements overlap or have invalid timestamps")
survivors = step.get("ready_survivor_ids", [])
check(survivors and all(identifier in old_ids | new_ids and identifier != step["old_id"]
for identifier in survivors), "rolling step had no other ready backend")
last_end = end
def validate_migration_events(value):
check(value.get("capture_started_before_stack") is True,
"migration evidence must capture lifecycle from before stack startup")
events = value.get("events", [])
check(isinstance(events, list) and events, "raw migration/API lifecycle events are required")
starts = [e for e in events if e.get("service") == "migrate" and e.get("action") == "start"]
exits = [e for e in events if e.get("service") == "migrate" and e.get("action") == "die"]
apis = [e for e in events if e.get("service") == "api" and e.get("action") == "start"]
check(len(starts) == len(exits) == 1 and len({e.get("container_id") for e in apis}) >= 2,
"expected exactly one migration start/exit and at least two real API starts")
check(all(isinstance(e.get("time_ns"), int) and e["time_ns"] > 0 and e.get("container_id")
for e in starts + exits + apis), "lifecycle events require real IDs and nanosecond timestamps")
check(starts[0]["container_id"] == exits[0]["container_id"] and
starts[0]["time_ns"] < exits[0]["time_ns"] and exits[0].get("exit_code") == 0,
"migrator did not complete successfully")
check(all(e["time_ns"] >= exits[0]["time_ns"] for e in apis),
"API started before migration completed")
def attachments(config, evidence):
"""Lab4-specific contract checks; reuse the public client and fixture."""
content = (ROOT / "tests/fixtures/sample.png").read_bytes()
def upload(client, actor, chat, data=content, mime="image/png", filename="sample.png", expected=201):
response = client.call("POST", "/api/v1/chats/" + chat["id"] +
"/attachments?filename=" + quote(filename, safe=""), expected,
actor=actor, raw=data, headers={"Content-Type": mime},
schema="Attachment" if expected == 201 else None)
if expected == 201:
att = response["json"]
check(att["status"] == "ready" and att["variants"] == [] and att["error_code"] is None,
"upload must synchronously return ready metadata without variants/error")
check(att["chat_id"] == chat["id"] and att["owner_id"] == actor["id"] and
att["sha256"] == hashlib.sha256(data).hexdigest() and att["size_bytes"] == len(data),
"attachment ownership or original checksum/size mismatch")
else:
expected_code = {400: "invalid_request", 404: "not_found", 413: "payload_too_large",
415: "unsupported_media_type"}[expected]
check(response["json"]["error"]["code"] == expected_code, "incorrect upload error code")
return response
def negative_uploads():
c, alice, bob, eve, chat, other = bootstrap(config)
# The oversized fixture is generated in memory, never committed as a huge file.
upload(c, alice, chat, data=content + b"\0" * (10 * 1024 * 1024 + 1 - len(content)), expected=413)
upload(c, alice, chat, data=b"\x89PNG\r\n\x1a\ntruncated", expected=415)
upload(c, alice, chat, data=b"not an image", expected=415)
upload(c, alice, chat, mime="image/jpeg", expected=415)
upload(c, alice, chat, mime="application/octet-stream", expected=415)
for name in ("../image.png", "a\\b.png", "a\x00b.png", "a\x1fb.png", "", "x" * 256):
upload(c, alice, chat, filename=name, expected=400)
evidence.case("attachment_negative_uploads", negative_uploads)
def acl_and_message():
c, alice, bob, eve, chat, other = bootstrap(config)
att = upload(c, alice, chat)["json"]
path = "/api/v1/attachments/" + att["id"]
for suffix in ("", "/content"):
c.call("GET", path + suffix, 404, actor=eve)
upload(c, eve, chat, expected=404)
downloaded = c.call("GET", path + "/content", actor=bob)
check(downloaded["bytes"] == content and
downloaded["headers"].get_content_type() == "image/png", "original bytes/MIME changed")
# Reuse this end-to-end case rather than creating a second attachment suite.
attachments = [att] + [upload(c, alice, chat)["json"] for _ in range(9)]
ids = sorted((item["id"] for item in attachments), reverse=True)
for count in range(11):
body = {"text": "" if count else "Legacy text without attachments", "attachment_ids": ids[:count]}
if count == 1:
body["attachment_ids"] = [ids[0].upper()]
key = uuid.uuid4().hex
first = post(c, bob, chat, body, key)["json"]
if count == 1:
before = history(c, alice, chat)
replay = post(c, bob, chat, body, key)["json"]
check(replay == first, "identical uppercase-UUID JSON replay changed the 201/Message")
check(history(c, alice, chat) == before, "identical uppercase-UUID replay changed history")
check(first in history(c, alice, chat), "history lost message or attachment order for count=%d" % count)
for target, actor, attachment_id in ((other, alice, att["id"]), (chat, eve, att["id"]),
(chat, alice, str(uuid.uuid4()))):
before = history(c, alice, target)
post(c, actor, target, {"text": "negative reference", "attachment_ids": [ids[0], attachment_id]},
uuid.uuid4().hex, 404)
check(history(c, alice, target) == before, "invalid attachment reference changed history")
key = uuid.uuid4().hex
original_body = {"text": "same", "attachment_ids": ids[:2]}
original = post(c, alice, chat, original_body, key)["json"]
before = history(c, bob, chat)
check(post(c, alice, chat, original_body, key)["json"] == original, "identical attachment replay changed Message")
check(history(c, bob, chat) == before, "identical attachment replay changed history")
other_att = upload(c, bob, chat)["json"]
for changed in (ids[:2][::-1], [ids[0], other_att["id"]], ids[:1], []):
post(c, alice, chat, {"text": "same", "attachment_ids": changed}, key, 409)
check(history(c, bob, chat) == before, "attachment list/order conflict changed history")
check(post(c, alice, chat, original_body, key)["json"] == original,
"attachment conflict changed original Message")
check(occurrences(c, bob, chat, "same") == [original], "attachment conflict wrote another message")
race_key = uuid.uuid4().hex
gate = threading.Barrier(int(config.get("concurrency", 12)))
def repeated(_):
gate.wait(timeout=10)
return post(client_for(config), bob, chat, {"text": "attachment race", "attachment_ids": ids[:3]}, race_key)
with ThreadPoolExecutor(max_workers=gate.parties) as pool:
responses = list(pool.map(repeated, range(gate.parties)))
raced = [response["json"] for response in responses]
aliases = sorted({response["headers"]["X-Instance-Id"] for response in responses})
evidence.record("concurrent_attachment_idempotency", attempts=gate.parties, observed_instances=aliases)
check(len(aliases) >= 2, "concurrent attachment retries did not reach two LB backends")
check(all(message == raced[0] for message in raced), "concurrent attachment replay changed Message")
check(occurrences(c, alice, chat, "attachment race") == [raced[0]], "concurrent attachment replay duplicated history")
evidence.case("attachment_acl_bytes_and_idempotency", acl_and_message)
# Faults and bucket policies are implementation-specific. A configured adapter
# executes the scenario and returns observations; a missing adapter is PENDING.
def operational(name):
require_hooks(config, name)
env = dict(os.environ, STUDENT_TEST_EVIDENCE_DIR=str(evidence.directory / name))
proc = subprocess.run(config["hooks"][name], cwd=ROOT, env=env, capture_output=True, timeout=180, check=False)
if name == "attachment_bucket_security" and proc.returncode == 2:
raise Pending("S3 infrastructure unavailable; inspect attachment_bucket_security/summary.json")
check(proc.returncode == 0, name + " adapter failed")
try:
value = json.loads(proc.stdout)
except ValueError:
raise Failure(name + " adapter must return sanitized observation JSON") from None
validate_attachment_observations(name, value)
evidence.record(name, **value)
for name in ("attachment_compensation", "attachment_parallel_memory", "attachment_bucket_security",
"attachment_s3_failure", "attachment_pixels_limit"):
evidence.case(name, lambda name=name: operational(name))
def validate_attachment_observations(name, value):
"""Require measurements/observations, never accept a bare {pass: true}."""
check(isinstance(value, dict), "adapter must return observation object")
if name == "attachment_compensation":
check(set(value.get("injected_faults", [])) >= {"client_disconnect", "after_s3_before_db"},
"both interrupted upload and S3/DB boundary fault must be injected")
check(value.get("grace_seconds", 0) > 0 and value.get("untracked_objects_after_grace") == 0 and
value.get("fresh_objects_preserved") is True and value.get("referenced_objects_preserved") is True,
"cleanup did not prove grace period and preservation of fresh/referenced objects")
elif name == "attachment_parallel_memory":
check(value.get("concurrent_uploads", 0) >= 10 and value.get("successful_uploads", 0) >= 10,
"need at least 10 simultaneous successful uploads")
check(value.get("body_bytes", 0) > 0 and value.get("duration_seconds", 0) > 0,
"upload load profile missing")
samples = value.get("samples", [])
check(samples and all(s.get("time_seconds", -1) >= 0 and s.get("memory_bytes", 0) > 0 and
s.get("cpu_percent", -1) >= 0 for s in samples), "raw CPU/RAM samples missing")
check(0 < max(s["memory_bytes"] for s in samples) <= value.get("memory_limit_bytes", 0),
"memory was not bounded by the configured runtime limit")
check(value.get("oom_kills") == 0, "upload experiment had OOM kills")
elif name == "attachment_bucket_security":
check(value.get("bootstrap_runs", 0) >= 2 and value.get("bucket_survived_second_bootstrap") is True,
"bucket bootstrap not repeated with existing data")
check(value.get("anonymous_get_status") in (401, 403, 404) and
value.get("anonymous_list_status") in (401, 403, 404) and
value.get("api_credentials_are_admin") is False and
value.get("api_can_administer_other_buckets") is False and
value.get("console_reachable_from_shared_network") is False,
"bucket/API policy or console isolation failed")
elif name == "attachment_s3_failure":
check(value.get("fault") == "s3_unreachable" and value.get("upload_status") == 503 and
value.get("ready_status") == 503 and value.get("live_status") == 200 and
value.get("false_ready_attachments") == 0 and value.get("restored_original_checksum_equal") is True,
"S3 failure was not reported safely or original was lost")
elif name == "attachment_pixels_limit":
check(value.get("width", 0) * value.get("height", 0) > 40000000 and
0 < value.get("encoded_bytes", 0) <= 10485760 and value.get("upload_status") == 413,
"need a valid image above pixel limit but below byte limit, rejected with 413")
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", "attachments", "all"], default="all")
args = parser.parse_args()
evidence = Evidence(args.output)
try:
config = json.loads(Path(args.config).read_text(encoding="utf-8"))
check(isinstance(config, dict), "config must be a JSON object")
client_for(config)
check(2 <= int(config.get("concurrency", 12)) <= 64, "concurrency must be 2..64")
check(11 <= float(config.get("failover_window_seconds", 15)) <= 60,
"failover_window_seconds must be 11..60 to observe the 10 second budget")
check(1 <= float(config.get("rolling_window_seconds", 20)) <= 60 and
60 <= float(config.get("rolling_max_seconds", 120)) <= 300,
"invalid rolling load time budget")
except (OSError, ValueError, Failure, Pending) as exc:
evidence.case("configuration", lambda: (_ for _ in ()).throw(Failure(str(exc))))
return evidence.finish()
evidence.record("run_profile", scenario=args.scenario, base_url=config["base_url"],
concurrency=config.get("concurrency", 12), request_timeout_seconds=config.get("request_timeout_seconds", 3),
failover_window_seconds=config.get("failover_window_seconds", 15),
rolling_window_seconds=config.get("rolling_window_seconds", 20),
load_model="sequential closed-loop POST+GET; concurrency only for duplicate POST race")
evidence.case("public_lb_endpoint", lambda: public_endpoint(config, evidence))
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 ("attachments", "all"):
attachments(config, evidence)
if args.scenario in ("public", "all"):
public_checks(config, evidence)
return evidence.finish()
if __name__ == "__main__":
raise SystemExit(main())