Implement lab 3 level 4 failover and idempotency

This commit is contained in:
2026-10-29 23:35:04 +03:00
parent 0ab3a341aa
commit a2cb1ad2ae
338 changed files with 37821 additions and 22 deletions
+179
View File
@@ -0,0 +1,179 @@
# Собственные проверки lab3 на оценку «4»
`run.py` создаёт только синтетические данные через **публичный адрес LB** из
`base_url`. Адрес прямой API-реплики недопустим. Нужны Python 3.9+, запущенный
стенд и действующий TTL сессии не менее 300 секунд. Тестовые пользователи,
токены и сообщения не удаляются, так как контракт не содержит delete для них.
```sh
cp student-tests/lab3/config.example.json student-tests/lab3/config.local.json
# В config.local.json указать реальный публичный адрес LB и hooks.
python3 student-tests/lab3/run.py \
--config student-tests/lab3/config.local.json \
--output student-tests/output/lab3-run-01 --scenario all
# Только повтор того же сообщения/ключа с прежним токеном после restart hook:
python3 student-tests/lab3/run.py \
--config student-tests/lab3/config.example.json \
--output student-tests/output/lab3-restart --scenario restart
# Публичный persistence + Docker StartedAt/volumes + повтор по исходному ключу:
python3 student-tests/lab3/prove_persistence.py \
--project highload-lab3 --base-url http://127.0.0.1:8080 \
--output student-tests/output/lab3-persistence
```
`config.local.json` содержит только пути/адреса, но его не нужно коммитить.
Каждый запуск пишет `events.jsonl` (сырые счётчики, длительности, ID реплик),
`summary.json` и stdout/stderr публичных make-команд в указанный каталог.
Токены и пароли в артефакты не записываются. Ненулевой exit code означает
`FAIL` **или** `PENDING_INFRA`; пропуск не становится PASS.
## Покрытие
**Обязательный уровень 3:** отрицательные/граничные ключи 1–128 ASCII,
исходный `201` и тот же Message при повторе, `409` без записи, независимость
пользователя/чата, конкурентный повтор через разные `X-Instance-Id`, повтор
через другую реплику, повтор после потерянного ответа, рестарта, отказа,
реального клиентского таймаута с управляемой задержкой,
повторную проверку отозванной сессии и доступа. Сценарий обрыва закрывает
соединение после передачи полного запроса; он проверяет безопасный повтор
независимо от того, успел ли первый запрос завершиться. Проверка доступа после
изменения членства требует `revoke_access`/`restore_access`: обязательный API
не позволяет менять участников. В одноразовом проекте собственный адаптер
временно переносит ровно одно синтетическое сообщение другому участнику того
же чата, удаляет исходного участника, а затем восстанавливает членство и
отправителя. Все операции ограничены точными UUID и проверяют затронутые
строки; вне одноразового проекта этот адаптер отказывается работать.
**Обязательный уровень 4:** два наблюдаемых процесса за LB; поочерёдная
остановка и восстановление каждой реплики с прежним токеном и данными;
успешные RPS, ошибки, время восстановления чтения и записи от начала stop;
`live=200`/`ready=503` на неготовой реплике и её исключение LB; проверка
прекращения приёма после SIGTERM; CPU/RAM-лимиты всех Compose-сервисов,
закрытые порты API, отсутствие `container_name`, healthcheck и stop grace;
поочерёдное обновление под нагрузкой; фактический однократный старт миграций.
Текущий `compose.yaml` задаёт две API-реплики за LB. Сценарии с отдельными
fault-injection/rolling adapters остаются `PENDING_INFRA`, пока не настроены
соответствующие hooks; наличие двух контейнеров само по себе их не заменяет.
**Дополнительная проверка качества:** во время rolling update требуется ноль
ошибок HTTP. Это строже буквального критерия «проверена под нагрузкой»;
она выводится отдельным `rolling_update_zero_http_errors_quality`, а смена
Docker ID и работа под нагрузкой — отдельным `rolling_update_under_load`.
Публичные `make test`, `make test-persistence ACTION_SCRIPT=...` и
`make test-failover ACTION_SCRIPT=...` входят в `--scenario all` и запускаются
также отдельно через `--scenario public`. Для второго и третьего требуются
hooks `restart`, `stop_one`; после публичного failover обязательно вызывается
`recover_all`. Собственный failover вызывает `stop_one`/`start_one` для каждого
наблюдаемого alias. Action script должен быстро вернуть 0 и оставить выбранную
реплику остановленной до `start_one`. Нельзя делать `down -v` или менять чужие
данные.
`prove_persistence.py` явно принимает имя Compose-проекта и сохраняет
`summary.json`, `lifecycle.jsonl`, stdout/stderr обоих HTTP-сценариев. Проверка
сравнивает **каждый** API-контейнер, PostgreSQL, Redis и LB по Docker ID,
`StartedAt` и именам volumes; публичный сценарий проверяет прежний токен и
сообщение, lab3-сценарий — исходный `201`/Message при повторе ключа после
перезапуска. Эти файлы можно цитировать в `REPORT.md`, без токенов и паролей.
Изолированный `student-tests/stack.py verify` создаёт отдельный Compose-проект
с собственным публичным портом LB и одной API-репликой для прежнего lab2
профиля. Только в этом одноразовом проекте loopback-порт API используется
старыми проверками dependency/TTL, которым нужен ответ самого API при
исключении всех backend из LB. Публичные и lab3-сценарии идут через LB.
Runner записывает lifecycle-снимки вокруг persistence-этапов.
Для короткой проверки именно этих этапов в одноразовом проекте:
```sh
.venv/bin/python student-tests/stack.py verify --persistence-only --pull never \
--output student-tests/output/lab3-isolated-persistence
# Полный lab3-прогон в отдельном проекте с двумя API и LB:
.venv/bin/python student-tests/stack.py verify --lab3-only --pull never \
--output student-tests/output/lab3-isolated-level4
# Только rolling и отдельный строгий порог нуля ошибок в новом проекте:
.venv/bin/python student-tests/stack.py verify --lab3-only \
--lab3-scenario rolling --pull never \
--output student-tests/output/lab3-isolated-rolling
# Только идемпотентность, включая повторную проверку доступа:
.venv/bin/python student-tests/stack.py verify --lab3-only \
--lab3-scenario idempotency --pull never \
--output student-tests/output/lab3-isolated-idempotency
# Один rolling в двухсетевой схеме полного профиля с Docker/API/LB логами:
.venv/bin/python student-tests/stack.py verify --lab3-only \
--lab3-scenario rolling-dual --pull never \
--output student-tests/output/lab3-rolling-dual-diagnostic
```
Полный изолированный профиль использует сети `front` и `state`, чтобы
отключить только доступ выбранного API к хранилищам и получить локальные
`live=200`, `ready=503`, сохранив путь LB к этой реплике. Рабочий rolling-скрипт
рассчитан на одну сеть, поэтому временный Docker CLI адаптер полного профиля
возвращает ему реальный IP сети `front` для его одного шаблона `docker inspect`;
остальные команды передаются без изменений. Целевой `--lab3-scenario rolling`
использует одну сеть, как основной Compose-проект, и запускает скрипт напрямую.
`--lab3-scenario rolling-dual` сохраняет двухсетевую схему, timeout клиента
1 с и строгий нулевой порог, а также записывает UTC миллисекунды для ошибок,
шагов Docker, Docker events и поточные логи LB/API до удаления проекта.
В `summary.json` при этом стоит `scope=persistence-only`; такой PASS не
обозначает прохождение полного `verify`.
## Формат hooks
В `hooks` задаются массивы аргументов без shell interpolation, например:
```json
{
"stop_one": ["scripts/stop-one.sh"],
"start_one": ["scripts/start-one.sh"],
"recover_all": ["scripts/recover-all.sh"],
"restart": ["scripts/restart.sh"],
"make_unready": ["scripts/test-make-unready.sh"],
"restore_ready": ["scripts/test-restore-ready.sh"],
"probe_health": ["scripts/test-probe-health.sh"],
"lb_timing_evidence": ["scripts/test-lb-timing.sh"],
"sigterm_one": ["scripts/test-sigterm-one.sh"],
"probe_stopped": ["scripts/test-probe-stopped.sh"],
"rolling_update": ["scripts/test-rolling-update.sh"],
"migration_evidence": ["scripts/test-migration-evidence.sh"],
"revoke_access": ["scripts/test-revoke-access.sh"],
"restore_access": ["scripts/test-restore-access.sh"]
}
```
Это **примеры имён адаптеров, не файлы, которые тест создаёт**. Для выбранной
Compose/Swarm схемы оператор реализует их отдельно. `TARGET_INSTANCE_ID`
передаётся в hooks выбранной реплики. Для изменения членства дополнительно
передаются `TEST_CHAT_ID` и `TEST_USER_ID` синтетической фикстуры.
Таймаут проверяется встроенным одноразовым HTTP-прокси: он пересылает запрос
на публичный LB, дожидается HTTP 201 от сервера, задерживает ответ клиенту и
подтверждает запись в истории перед повтором. Отдельный fault hook не нужен.
`probe_health` возвращает `{"live_status":200,"ready_status":503}` на выбранной частной
реплике; `probe_stopped` возвращает `{"accepting":false}` после SIGTERM.
`migration_evidence` возвращает JSON с реально записанным числом стартов
мигратора и порядком запуска:
```json
{"migration_starts":1,"migration_exit_code":0,"api_started_before_migration_complete":false}
```
`lb_timing_evidence` возвращает
`{"health_interval_seconds":1,"health_timeout_seconds":1,"configured_max_detection_seconds":5}`
по действующей конфигурации LB. `rolling_update` возвращает JSON
`{"replaced_processes":2,"min_ready_during_update":1}` после завершения
поочерёдной замены; runner параллельно измеряет HTTP-ответы через LB.
Текущего состояния `compose ps` недостаточно для доказательства числа запусков.
Метод регистрации lifecycle и совместимость миграции с работающей версией
объясняются в `REPORT.md`; тест не подменяет это доказательство. Там же нужны
версии образов, параметры LB health interval/timeout и максимальное время
обнаружения, аппаратные ресурсы и привязка alias к реальным контейнерам.
Проверка RPS использует простой последовательный closed-loop клиент. Он
показывает доступность при отказе, а не предельную пропускную способность.
Сравнение производительности для уровня 5 требует отдельного эксперимента.
+13
View File
@@ -0,0 +1,13 @@
{
"base_url": "http://127.0.0.1:8080",
"request_timeout_seconds": 3,
"concurrency": 12,
"failover_window_seconds": 15,
"rolling_window_seconds": 20,
"compose_config_argv": ["docker", "compose", "config", "--format", "json"],
"api_services": ["api"],
"lb_services": ["lb"],
"hooks": {
"restart": ["scripts/restart.sh"]
}
}
+221
View File
@@ -0,0 +1,221 @@
#!/usr/bin/env python3
"""Fault adapters restricted to a disposable lab3 Compose project."""
import argparse
import json
import os
from pathlib import Path
import re
import subprocess
import sys
import time
import uuid
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "student-tests"))
import stack # noqa: E402
def execute(argv, allow_failure=False, timeout=30):
result = subprocess.run(argv, cwd=ROOT, capture_output=True, text=True, timeout=timeout)
if result.returncode and not allow_failure:
raise RuntimeError("test Docker action failed")
return result
def owned_project():
project = os.environ.get("COMPOSE_PROJECT_NAME", "")
if not re.fullmatch(r"lab3-test-[a-f0-9]{12}", project):
raise RuntimeError("fault hooks require an isolated lab3-test-* Compose project")
if not os.environ.get("COMPOSE_FILE"):
raise RuntimeError("COMPOSE_FILE must identify the isolated project override")
return project, stack.compose_base(os.environ)
def inspect(identifier):
value = json.loads(execute(["docker", "inspect", identifier]).stdout)
if len(value) != 1:
raise RuntimeError("Docker inspect did not select one container")
return value[0]
def api_map(project, base):
ids = execute(base + ["ps", "-aq", "api"]).stdout.split()
if len(ids) != 2:
raise RuntimeError("isolated project needs exactly two API containers")
mapped = {}
for identifier in ids:
value = inspect(identifier)
labels = value["Config"]["Labels"]
if labels.get("com.docker.compose.project") != project or labels.get("com.docker.compose.service") != "api":
raise RuntimeError("API container ownership mismatch")
alias = value["Config"]["Hostname"]
if alias in mapped:
raise RuntimeError("duplicate API alias")
mapped[alias] = value
return mapped
def target(project, base):
alias = os.environ.get("TARGET_INSTANCE_ID", "")
mapped = api_map(project, base)
if alias not in mapped:
raise RuntimeError("TARGET_INSTANCE_ID is not an owned API alias")
return mapped[alias]
def wait_healthy(identifier, seconds=30):
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
state = inspect(identifier)["State"]
if state["Running"] and state.get("Health", {}).get("Status") == "healthy":
return
time.sleep(.2)
raise RuntimeError("API did not regain Docker readiness")
def state_network(project):
name = os.environ.get("HL_STATE_NETWORK", "")
if name != project + "_state":
raise RuntimeError("state network must belong to isolated project")
network = json.loads(execute(["docker", "network", "inspect", name]).stdout)[0]
if network["Labels"].get("com.docker.compose.project") != project:
raise RuntimeError("state network ownership mismatch")
return name
def http_status_inside(identifier, path):
result = execute(["docker", "exec", identifier, "wget", "-S", "-O", "/dev/null",
"http://127.0.0.1:8080" + path], allow_failure=True, timeout=5)
found = re.findall(r"HTTP/\d(?:\.\d)?\s+(\d{3})", result.stderr + result.stdout)
if not found:
raise RuntimeError("cannot read internal HTTP status")
return int(found[-1])
def lb_timing():
source = (ROOT / "infra/haproxy.cfg").read_text()
check = re.search(r"timeout check\s+(\d+)s", source)
server = re.search(r"server-template[^\n]*\binter\s+(\d+)s\s+fall\s+(\d+)", source)
if not check or not server:
raise RuntimeError("cannot derive LB health timing from HAProxy config")
timeout, interval, failures = int(check[1]), int(server[1]), int(server[2])
print(json.dumps({"health_interval_seconds": interval, "health_timeout_seconds": timeout,
"configured_max_detection_seconds": interval * failures + timeout}))
def migration_evidence(project):
path = Path(os.environ["HL_MIGRATION_EVIDENCE"])
value = json.loads(path.read_text())
if value.get("project") != project:
raise RuntimeError("migration evidence belongs to another project")
print(json.dumps(value))
def access_action(project, base, action):
chat = str(uuid.UUID(os.environ["TEST_CHAT_ID"]))
owner = str(uuid.UUID(os.environ["TEST_USER_ID"]))
replacement = str(uuid.UUID(os.environ["TEST_REPLACEMENT_USER_ID"]))
message = str(uuid.UUID(os.environ["TEST_MESSAGE_ID"]))
key = os.environ["TEST_IDEMPOTENCY_KEY"]
if owner == replacement or not re.fullmatch(r"[A-Za-z0-9._:-]{1,128}", key):
raise RuntimeError("invalid isolated access fixture")
ids = execute(base + ["ps", "-q", "postgres"]).stdout.split()
if len(ids) != 1:
raise RuntimeError("isolated project must have exactly one running PostgreSQL")
raw = inspect(ids[0])
labels = raw["Config"]["Labels"]
if labels.get("com.docker.compose.project") != project or labels.get("com.docker.compose.service") != "postgres":
raise RuntimeError("PostgreSQL container ownership mismatch")
if action == "revoke_access":
statement = f"""
DO $lab3$ DECLARE affected integer; BEGIN
IF (SELECT count(*) FROM chat_members WHERE chat_id='{chat}' AND user_id='{owner}') <> 1 OR
(SELECT count(*) FROM chat_members WHERE chat_id='{chat}' AND user_id='{replacement}') <> 1 OR
(SELECT count(*) FROM messages WHERE chat_id='{chat}' AND sender_id='{owner}') <> 1 OR
(SELECT count(*) FROM messages WHERE id='{message}' AND chat_id='{chat}' AND sender_id='{owner}') <> 1 OR
(SELECT count(*) FROM message_idempotency WHERE user_id='{owner}' AND chat_id='{chat}'
AND idempotency_key='{key}' AND message_id='{message}') <> 1 THEN
RAISE EXCEPTION 'synthetic access fixture precondition failed';
END IF;
UPDATE messages SET sender_id='{replacement}' WHERE id='{message}' AND chat_id='{chat}' AND sender_id='{owner}';
GET DIAGNOSTICS affected = ROW_COUNT;
IF affected <> 1 THEN RAISE EXCEPTION 'message reassignment was not unique'; END IF;
DELETE FROM chat_members WHERE chat_id='{chat}' AND user_id='{owner}';
GET DIAGNOSTICS affected = ROW_COUNT;
IF affected <> 1 THEN RAISE EXCEPTION 'membership deletion was not unique'; END IF;
END $lab3$;
"""
else:
statement = f"""
DO $lab3$ DECLARE affected integer; BEGIN
INSERT INTO chat_members(chat_id,user_id) VALUES('{chat}','{owner}') ON CONFLICT DO NOTHING;
UPDATE messages SET sender_id='{owner}' WHERE id='{message}' AND chat_id='{chat}' AND sender_id='{replacement}';
GET DIAGNOSTICS affected = ROW_COUNT;
IF affected > 1 OR
(SELECT count(*) FROM chat_members WHERE chat_id='{chat}' AND user_id='{owner}') <> 1 OR
(SELECT count(*) FROM messages WHERE id='{message}' AND chat_id='{chat}' AND sender_id='{owner}') <> 1 OR
(SELECT count(*) FROM message_idempotency WHERE user_id='{owner}' AND chat_id='{chat}'
AND idempotency_key='{key}' AND message_id='{message}') <> 1 THEN
RAISE EXCEPTION 'synthetic access fixture restoration failed';
END IF;
END $lab3$;
"""
execute(["docker", "exec", ids[0], "psql", "-X", "-v", "ON_ERROR_STOP=1", "-U", "messenger",
"-d", "messenger", "-c", statement])
print(json.dumps({"action": action, "project": project, "chat_id": chat,
"user_id": owner, "replacement_user_id": replacement,
"message_id": message, "validated_exact_message": True,
"membership_present_after": action == "restore_access"}))
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("action", choices=("start_one", "recover_all", "sigterm_one",
"probe_stopped", "make_unready", "restore_ready",
"probe_health",
"lb_timing_evidence", "migration_evidence",
"revoke_access", "restore_access"))
args = parser.parse_args()
project, base = owned_project()
action = args.action
if action == "lb_timing_evidence":
lb_timing()
elif action == "migration_evidence":
migration_evidence(project)
elif action in ("revoke_access", "restore_access"):
access_action(project, base, action)
elif action == "recover_all":
for value in api_map(project, base).values():
if not value["State"]["Running"]:
execute(["docker", "start", value["Id"]])
wait_healthy(value["Id"])
else:
value = target(project, base)
identifier = value["Id"]
if action == "start_one":
if not value["State"]["Running"]:
execute(["docker", "start", identifier])
wait_healthy(identifier)
elif action == "sigterm_one":
execute(["docker", "stop", "--time", "18", identifier], timeout=25)
if inspect(identifier)["State"]["Running"]:
raise RuntimeError("SIGTERM did not stop selected API")
elif action == "probe_stopped":
print(json.dumps({"accepting": bool(inspect(identifier)["State"]["Running"])}))
elif action == "make_unready":
execute(["docker", "network", "disconnect", state_network(project), identifier])
elif action == "restore_ready":
execute(["docker", "network", "connect", state_network(project), identifier])
wait_healthy(identifier)
elif action == "probe_health":
print(json.dumps({"live_status": http_status_inside(identifier, "/health/live"),
"ready_status": http_status_inside(identifier, "/health/ready")}))
return 0
if __name__ == "__main__":
try:
raise SystemExit(main())
except (OSError, ValueError, KeyError, RuntimeError, subprocess.TimeoutExpired) as exc:
print("FAIL: lab3 Docker action " + type(exc).__name__, file=sys.stderr)
raise SystemExit(1)
+87
View File
@@ -0,0 +1,87 @@
#!/usr/bin/env python3
"""Run public persistence and lab3 replay with Docker lifecycle evidence."""
import argparse
import json
import os
from pathlib import Path
import subprocess
import sys
import time
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "student-tests"))
import stack # noqa: E402
TARGETS = ["api", "postgres", "redis", "lb"]
def run_case(name, argv, base, env, output, summary):
before = stack.snapshot(base, env, TARGETS)
started = time.monotonic()
try:
process = subprocess.run(argv, cwd=ROOT, env=env, capture_output=True,
text=True, timeout=180, check=False)
(output / (name + ".stdout.log")).write_text(process.stdout)
(output / (name + ".stderr.log")).write_text(process.stderr)
exit_code = process.returncode
except subprocess.TimeoutExpired as exc:
def decoded(value):
return value.decode(errors="replace") if isinstance(value, bytes) else (value or "")
(output / (name + ".stdout.log")).write_text(decoded(exc.stdout))
(output / (name + ".stderr.log")).write_text(decoded(exc.stderr))
exit_code = -1
after = stack.snapshot(base, env, TARGETS)
proof = {"exit_code": exit_code, "seconds": round(time.monotonic() - started, 3),
"before": before, "after": after}
try:
stack.record_lifecycle(output / "lifecycle.jsonl", "restart", env["COMPOSE_PROJECT_NAME"],
before, after, source=name)
proof["docker_transition"] = "PASS"
except stack.CheckFailure as exc:
proof["docker_transition"] = "FAIL"
proof["transition_error"] = str(exc)
proof["status"] = "PASS" if exit_code == 0 and proof["docker_transition"] == "PASS" else "FAIL"
summary[name] = proof
print(proof["status"] + " " + name + " (HTTP exit " + str(exit_code) + ")", flush=True)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--project", required=True, help="explicit Compose project, e.g. highload-lab3")
parser.add_argument("--compose-file", action="append", help="Compose file(s); defaults to HighLoad/compose.yaml")
parser.add_argument("--base-url", default="http://127.0.0.1:8080", help="public LB URL")
parser.add_argument("--output", required=True)
args = parser.parse_args()
output = Path(args.output).resolve()
output.mkdir(parents=True, exist_ok=True)
env = os.environ.copy()
env["COMPOSE_PROJECT_NAME"] = args.project
env["COMPOSE_FILE"] = os.pathsep.join(args.compose_file or [str(ROOT / "compose.yaml")])
env["BASE_URL"] = args.base_url
base = stack.compose_base(env)
config = output / "lab3-restart-config.json"
config.write_text(json.dumps({"base_url": args.base_url,
"hooks": {"restart": [str(ROOT / "scripts/restart.sh")]}}))
summary = {"project": args.project, "base_url": args.base_url,
"scope": "public LB and Docker Compose service containers",
"results": {}}
try:
run_case("public-persistence",
["make", "test-persistence", "ACTION_SCRIPT=scripts/restart.sh",
"BASE_URL=" + args.base_url], base, env, output, summary["results"])
run_case("lab3-idempotency-restart",
[sys.executable, "student-tests/lab3/run.py", "--config", str(config),
"--output", str(output / "lab3-run"), "--scenario", "restart"],
base, env, output, summary["results"])
except (OSError, stack.CheckFailure, subprocess.SubprocessError) as exc:
summary["error"] = type(exc).__name__ + ": " + str(exc)
summary["status"] = "PASS" if len(summary["results"]) == 2 and all(
item["status"] == "PASS" for item in summary["results"].values()) else "FAIL"
path = output / "summary.json"
path.write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n")
print(summary["status"] + ": " + str(path), flush=True)
return 0 if summary["status"] == "PASS" else 1
if __name__ == "__main__":
raise SystemExit(main())
+951
View File
@@ -0,0 +1,951 @@
#!/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())