Реализовать лабораторную 3 на оценку 5 (трек 1)

This commit is contained in:
Чиняева
2026-11-07 00:57:10 +03:00
parent 0ab3a341aa
commit 2c4f0a5a61
96 changed files with 7784 additions and 45 deletions
+56
View File
@@ -0,0 +1,56 @@
# Студенческие проверки уровня 4 и трека 5
Все проверки, кроме `rollback_chat.py` и `explain_history.py`, запускаются на
хосте и обращаются к API по HTTP через LB. Две проверки используют `psycopg` и
запускаются внутри контейнера `api`, где зависимость уже установлена.
```sh
# 1. Негативная аутентификация и logout
python student-tests/auth_negative.py --base-url http://localhost:8080
# 2. Гонка регистрации одного username
python student-tests/race_username.py --base-url http://localhost:8080 --workers 8
# 3. Откат составной операции (внутри контейнера)
docker compose exec -T api python student-tests/rollback_chat.py
# 4. EXPLAIN на 10 000 сообщений (внутри контейнера)
docker compose exec -T api python student-tests/explain_history.py \
--output /tmp/explain_history.txt
# 5. Отказы Redis и PostgreSQL (с хоста; управляет docker compose)
python student-tests/fault_matrix.py --base-url http://localhost:8080
# 6. Истечение сессии: API должен быть запущен с коротким TTL
# SESSION_TTL_SECONDS=2 docker compose up -d --no-deps api
python student-tests/expiry.py --base-url http://localhost:8080 --wait 4
# 7. Одна сессия обслуживается несколькими репликами
python student-tests/instance_routing.py --base-url http://localhost:8080
# 8. Конкурентная идемпотентность через разные реплики
python student-tests/idempotency_race.py --base-url http://localhost:8080 --workers 24
# 9. Идемпотентность переживает полный рестарт стека
python student-tests/idempotency_persistence.py --base-url http://localhost:8080 \
--restart-script scripts/restart.sh
# 10. Поочерёдная остановка каждой реплики с метриками
python student-tests/failover_matrix.py --base-url http://localhost:8080
# 11. Поочерёдная замена (rolling update) под нагрузкой
python student-tests/rolling_update.py --base-url http://localhost:8080
# 12. Трек 5: 1/2/4 реплики при фиксированном бюджете и рост ресурсов
python student-tests/track1_experiment.py --base-url http://localhost:8080
python student-tests/track1_report.py
```
`fault_matrix.py` останавливает `redis`/`postgres` и обязательно запускает их
обратно в `finally`. Он проверяет только ограниченные `503`, отсутствие
доверенного анонимного доступа и сохранность сессии после рестарта Redis с AOF.
`failover_matrix.py`, `rolling_update.py` и `track1_experiment.py` управляют
Docker-контейнерами. Они не удаляют volumes и не печатают токены/пароли.
`track1_experiment.py` временно меняет `API_REPLICAS`/лимиты и восстанавливает
профиль 2×1.0 CPU/512M в `finally`.
+58
View File
@@ -0,0 +1,58 @@
#!/usr/bin/env python3
"""Wrong password, Basic-on-business-endpoint, logout and reuse checks."""
from __future__ import annotations
import argparse
import base64
from common import HttpClient, assert_status, error_code
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://localhost:8080")
args = parser.parse_args()
client = HttpClient(args.base_url)
user, registration = client.register()
wrong = base64.b64encode(
(registration["username"] + ":wrong-password-value").encode("utf-8")
).decode("ascii")
status, headers, payload, _ = client.call(
"POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + wrong}
)
assert_status(status, 401, "wrong password")
assert error_code(payload) == "unauthorized"
assert headers.get("WWW-Authenticate", "").lower().startswith("basic")
good = base64.b64encode(
(registration["username"] + ":" + registration["password"]).encode("utf-8")
).decode("ascii")
status, headers, _, _ = client.call(
"GET", "/api/v1/users/me", headers={"Authorization": "Basic " + good}
)
assert_status(status, 401, "Basic on business endpoint")
assert headers.get("WWW-Authenticate", "").lower().startswith("bearer")
session = client.login(registration)
token = session["token"]
status, _, me, _ = client.call("GET", "/api/v1/users/me", token=token)
assert_status(status, 200, "login")
assert me["id"] == user["id"]
status, _, _, raw = client.call("DELETE", "/api/v1/auth/sessions/current", token=token)
assert_status(status, 204, "logout")
assert raw == b"", "204 must have an empty body"
status, headers, payload, _ = client.call("GET", "/api/v1/users/me", token=token)
assert_status(status, 401, "token after logout")
assert error_code(payload) == "unauthorized"
assert headers.get("WWW-Authenticate", "").lower().startswith("bearer")
status, _, _, _ = client.call("DELETE", "/api/v1/auth/sessions/current", token=token)
assert_status(status, 401, "second logout")
print("PASS: wrong password, Basic rejection, logout and token reuse checks")
if __name__ == "__main__":
main()
+76
View File
@@ -0,0 +1,76 @@
#!/usr/bin/env python3
"""Small standard-library HTTP helpers for the student checks."""
from __future__ import annotations
import base64
import json
import os
import uuid
import urllib.error
import urllib.request
BASE_URL = os.environ.get("BASE_URL", "http://localhost:8080").rstrip("/")
class HttpClient:
def __init__(self, base_url: str | None = None):
self.base = (base_url or BASE_URL).rstrip("/")
def call(self, method: str, path: str, body=None, token: str | None = None, headers=None):
h = {"Accept": "application/json"}
data = None
if body is not None:
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
h["Content-Type"] = "application/json"
if token:
h["Authorization"] = "Bearer " + token
h.update(headers or {})
request = urllib.request.Request(self.base + path, data=data, headers=h, method=method)
try:
response = urllib.request.urlopen(request, timeout=10)
except urllib.error.HTTPError as error:
response = error
with response:
raw = response.read()
payload = None
if raw:
try:
payload = json.loads(raw)
except ValueError:
payload = None
return response.code, response.headers, payload, raw
def register(self) -> tuple[dict, dict]:
suffix = uuid.uuid4().hex[:12]
registration = {
"username": "st_" + suffix,
"display_name": "Студент " + suffix,
"password": "T3st-" + uuid.uuid4().hex,
}
status, _headers, user, _raw = self.call("POST", "/api/v1/users", registration)
if status != 201:
raise AssertionError(f"registration failed: HTTP {status}")
return user, registration
def login(self, registration: dict) -> dict:
credential = base64.b64encode(
(registration["username"] + ":" + registration["password"]).encode("utf-8")
).decode("ascii")
status, _headers, session, _raw = self.call(
"POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + credential}
)
if status != 201:
raise AssertionError(f"login failed: HTTP {status}")
return session
def assert_status(actual: int, expected: int, label: str) -> None:
if actual != expected:
raise AssertionError(f"{label}: expected HTTP {expected}, received {actual}")
def error_code(payload) -> str | None:
if not isinstance(payload, dict):
return None
error = payload.get("error")
return error.get("code") if isinstance(error, dict) else None
+35
View File
@@ -0,0 +1,35 @@
#!/usr/bin/env python3
"""Expiry check: run against an API with SESSION_TTL_SECONDS=2 (or pass --wait)."""
from __future__ import annotations
import argparse
import time
from common import HttpClient, assert_status, error_code
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://localhost:8080")
parser.add_argument("--wait", type=float, default=3.0)
args = parser.parse_args()
client = HttpClient(args.base_url)
user, registration = client.register()
session = client.login(registration)
token = session["token"]
status, headers, payload, _ = client.call("GET", "/api/v1/users/me", token=token)
assert_status(status, 200, "fresh session")
assert payload["id"] == user["id"], "wrong current user"
time.sleep(args.wait)
status, headers, payload, _ = client.call("GET", "/api/v1/users/me", token=token)
assert_status(status, 401, "expired session")
assert error_code(payload) == "unauthorized", "expired session must be unauthorized"
assert headers.get("WWW-Authenticate", "").lower().startswith("bearer"), "missing Bearer challenge"
print("PASS: expired session is rejected with 401 and Bearer challenge")
if __name__ == "__main__":
main()
+101
View File
@@ -0,0 +1,101 @@
#!/usr/bin/env python3
"""Create 10 000 synthetic messages and record EXPLAIN (ANALYZE, BUFFERS).
Run inside the API container (psycopg is installed there):
docker compose exec -T api python student-tests/explain_history.py \
--output /app/evidence/explain_history.txt
The evidence directory is mounted read-only in the container, so the example
below is normally executed with a writable bind mount or copied out.
"""
from __future__ import annotations
import argparse
import os
import uuid
from datetime import datetime, timezone
from pathlib import Path
import psycopg
MESSAGES = 10_000
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--database-url", default=os.environ.get("DATABASE_URL"))
parser.add_argument("--output", default="evidence/explain_history.txt")
parser.add_argument("--messages", type=int, default=MESSAGES)
args = parser.parse_args()
if not args.database_url:
raise SystemExit("DATABASE_URL is required")
tag = uuid.uuid4().hex[:10]
user_id = uuid.uuid4()
chat_id = uuid.uuid4()
with psycopg.connect(args.database_url) as conn:
conn.execute(
"INSERT INTO users (id, username, display_name, password_hash) VALUES (%s, %s, %s, %s)",
(user_id, "perf_" + tag, "Performance synthetic", "not-a-real-password-hash"),
)
conn.execute("INSERT INTO chats (id, title) VALUES (%s, %s)", (chat_id, "perf-" + tag))
conn.execute(
"INSERT INTO chat_members (chat_id, user_id) VALUES (%s, %s)", (chat_id, user_id)
)
conn.execute(
"""
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT gen_random_uuid(), %s, %s, 'synthetic message ' || g,
timestamptz '2026-01-01 00:00:00+00' + (g || ' milliseconds')::interval
FROM generate_series(1, %s) AS g
""",
(chat_id, user_id, args.messages),
)
total = conn.execute(
"SELECT count(*) FROM messages WHERE chat_id = %s", (chat_id,)
).fetchone()[0]
conn.execute("ANALYZE messages")
cursor = conn.execute(
"""
SELECT created_at, id FROM messages
WHERE chat_id = %s ORDER BY created_at, id
OFFSET %s LIMIT 1
""",
(chat_id, max(0, args.messages - 500)),
).fetchone()
plan_rows = conn.execute(
"""
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = %s AND (created_at, id) > (%s, %s)
ORDER BY created_at, id
LIMIT 51
""",
(chat_id, cursor[0], cursor[1]),
).fetchall()
conn.commit()
plan = "\n".join(row[0] for row in plan_rows)
if "messages_chat_created_at_id_idx" not in plan:
raise AssertionError("history query did not use the keyset index:\n" + plan)
if "Seq Scan" in plan:
raise AssertionError("history query performed a sequential scan:\n" + plan)
header = (
"# EXPLAIN (ANALYZE, BUFFERS) for keyset history pagination\n"
f"generated_at_utc: {datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z')}\n"
f"messages_in_chat: {total}\n"
f"chat_id: {chat_id}\n"
"query: WHERE chat_id = ? AND (created_at, id) > (?, ?) "
"ORDER BY created_at, id LIMIT 51\n\n"
)
output = Path(args.output)
output.parent.mkdir(parents=True, exist_ok=True)
output.write_text(header + plan + "\n", encoding="utf-8")
print(header + plan)
print(f"PASS: index used on {total} messages; evidence written to {output}")
if __name__ == "__main__":
main()
+206
View File
@@ -0,0 +1,206 @@
#!/usr/bin/env python3
"""Sequential one-replica-at-a-time failure matrix under continuous writes.
For every running API replica:
* run a small closed-loop writer against the public LB;
* stop exactly that container (by X-Instance-Id -> hostname -> container id);
* keep writing, then restore the replica and wait until it serves again;
* record per-second successes/errors, first recovery and post-recovery RPS.
This is an operator measurement, not a production HA proof. It never removes
volumes and never prints credentials or tokens.
"""
from __future__ import annotations
import argparse
import json
import subprocess
import threading
import time
import uuid
from collections import defaultdict
from pathlib import Path
from common import HttpClient
ROOT = Path(__file__).resolve().parents[1]
def compose(*args: str) -> str:
return subprocess.check_output(
["docker", "compose", "--env-file", ".env", *args],
cwd=ROOT,
stderr=subprocess.STDOUT,
text=True,
)
def api_containers() -> list[dict]:
ids = compose("ps", "-q", "api").split()
result = []
for container_id in ids:
hostname = subprocess.check_output(
["docker", "inspect", "--format", "{{.Config.Hostname}}", container_id],
text=True,
).strip()
status = subprocess.check_output(
["docker", "inspect", "--format", "{{.State.Status}}", container_id],
text=True,
).strip()
if status == "running":
result.append({"id": container_id, "hostname": hostname})
return result
def wait_instances(client: HttpClient, token: str, expected: int, timeout: float = 30) -> set[str]:
deadline = time.monotonic() + timeout
seen: set[str] = set()
while time.monotonic() < deadline:
try:
status, headers, _payload, _raw = client.call("GET", "/api/v1/users/me", token=token)
if status == 200:
seen.add(headers.get("X-Instance-Id", ""))
if len(seen) >= expected:
return seen
except OSError:
pass
time.sleep(0.25)
return seen
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://localhost:8080")
parser.add_argument("--duration", type=float, default=16.0)
parser.add_argument("--workers", type=int, default=6)
parser.add_argument("--output", default="evidence/failover_matrix.json")
args = parser.parse_args()
client = HttpClient(args.base_url)
user, registration = client.register()
session = client.login(registration)
token = session["token"]
status, _headers, chat, _raw = client.call(
"POST",
"/api/v1/chats",
body={"title": "Failover matrix", "member_ids": [user["id"]]},
token=token,
)
if status != 201:
raise AssertionError(f"chat creation failed: HTTP {status}")
targets = api_containers()
if len(targets) < 2:
raise AssertionError("at least two running API replicas are required")
report = {
"base_url": args.base_url,
"workers": args.workers,
"duration_seconds": args.duration,
"replicas_before": sorted(item["hostname"] for item in targets),
"runs": [],
}
for target in targets:
stop_event = threading.Event()
lock = threading.Lock()
successes = defaultdict(int)
errors = defaultdict(int)
events: list[tuple[float, str]] = []
started = time.monotonic()
stop_at = started + 2.0
def worker(worker_id: int) -> None:
local = HttpClient(args.base_url)
index = 0
while not stop_event.is_set():
index += 1
key = uuid.uuid4().hex
body = {"text": f"matrix-{target['hostname'][:6]}-{worker_id}-{index}"}
try:
status, headers, _payload, _raw = local.call(
"POST",
f"/api/v1/chats/{chat['id']}/messages",
body=body,
token=token,
headers={"Idempotency-Key": key},
)
bucket = int(time.monotonic() - started)
with lock:
if status == 201:
successes[bucket] += 1
events.append((time.monotonic(), headers.get("X-Instance-Id", "")))
else:
errors[bucket] += 1
except Exception:
bucket = int(time.monotonic() - started)
with lock:
errors[bucket] += 1
time.sleep(0.005)
threads = [threading.Thread(target=worker, args=(i,), daemon=True) for i in range(args.workers)]
for thread in threads:
thread.start()
while time.monotonic() < stop_at:
time.sleep(0.05)
stop_time = time.monotonic()
subprocess.run(
["docker", "stop", "--time", "1", target["id"]],
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
stopped_at = time.monotonic()
# Keep writing for the rest of the window, then restore the replica.
time.sleep(max(0.0, args.duration - (time.monotonic() - started) - 4.0))
restore_at = time.monotonic()
compose("start", "api")
seen_after = wait_instances(client, token, len(targets), timeout=30)
recovered_at = time.monotonic()
time.sleep(max(0.0, args.duration - (time.monotonic() - started)))
stop_event.set()
for thread in threads:
thread.join(timeout=3)
with lock:
after_stop = [event for event in events if event[0] > stopped_at]
first_after_stop = min((event[0] for event in after_stop), default=None)
target_during_outage = any(
event[1] == target["hostname"] for event in events if stopped_at < event[0] < restore_at
)
target_after_restore = any(
event[1] == target["hostname"] for event in events if event[0] >= restore_at
)
run = {
"target_instance": target["hostname"],
"target_container": target["id"][:12],
"success_by_second": [successes[i] for i in range(int(args.duration) + 1)],
"errors_by_second": [errors[i] for i in range(int(args.duration) + 1)],
"successes_total": sum(successes.values()),
"errors_total": sum(errors.values()),
"stop_seconds": round(stopped_at - started, 3),
"restore_seconds": round(restore_at - started, 3),
"first_write_after_stop_seconds": (
round(first_after_stop - stopped_at, 3) if first_after_stop else None
),
"target_served_during_outage": target_during_outage,
"target_present_after_restore": target_after_restore,
"instances_after_restore": sorted(item for item in seen_after if item),
}
report["runs"].append(run)
print(json.dumps(run, ensure_ascii=False))
# Give the LB a moment to see the restored replica before the next run.
time.sleep(1.0)
output = Path(args.output)
output.parent.mkdir(parents=True, exist_ok=True)
output.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print("PASS: sequential replica-stop matrix completed; evidence:", output)
if __name__ == "__main__":
main()
+126
View File
@@ -0,0 +1,126 @@
#!/usr/bin/env python3
"""Dependency-failure matrix: Redis and PostgreSQL outages must be bounded.
The check uses the local Compose project. It stops one dependency, verifies
503 (never 200 and never a trusted anonymous request), starts it again, waits
for readiness and confirms the original bearer session still works after the
Redis restart (AOF persistence).
"""
from __future__ import annotations
import argparse
import os
import subprocess
import time
from pathlib import Path
from common import HttpClient, assert_status, error_code
ROOT = Path(__file__).resolve().parents[1]
def compose(*args: str) -> None:
subprocess.run(
["docker", "compose", "--env-file", ".env", *args],
cwd=ROOT,
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
def wait_ready(client: HttpClient, expected: int, seconds: float = 90) -> None:
deadline = time.monotonic() + seconds
last = None
while time.monotonic() < deadline:
try:
status, _, _, _ = client.call("GET", "/health/ready")
last = status
if status == expected:
return
except OSError:
last = "connection error"
time.sleep(0.5)
raise AssertionError(f"readiness did not become {expected}; last={last}")
def wait_authenticated(client: HttpClient, token: str, seconds: float = 30) -> float:
"""Wait until every LB-routed request can use the existing token again.
A replica may still be reconnecting its pool or resolving the restarted
database for a few seconds after the first readiness=200. This is a
bounded recovery window; the session and data are not lost.
"""
started = time.monotonic()
deadline = started + seconds
last = None
while time.monotonic() < deadline:
try:
status, _, me, _ = client.call("GET", "/api/v1/users/me", token=token)
last = status
if status == 200 and me:
return round(time.monotonic() - started, 2)
except OSError:
last = "connection error"
time.sleep(0.25)
raise AssertionError(f"authenticated request did not recover; last={last}")
def expect_503(client: HttpClient, path: str, token: str | None, label: str) -> None:
status, _headers, payload, _raw = client.call("GET", path, token=token)
if status != 503:
raise AssertionError(f"{label}: expected 503, received {status}")
if error_code(payload) != "unavailable":
raise AssertionError(f"{label}: expected unavailable error code")
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://localhost:8080")
args = parser.parse_args()
client = HttpClient(args.base_url)
user, registration = client.register()
session = client.login(registration)
token = session["token"]
results = []
try:
compose("stop", "redis")
expect_503(client, "/health/ready", None, "Redis down readiness")
expect_503(client, "/api/v1/users/me", token, "Redis down authenticated request")
results.append("redis down: readiness=503, bearer request=503")
started = time.monotonic()
compose("start", "redis")
wait_ready(client, 200)
redis_recovery = round(time.monotonic() - started, 2)
auth_recovery = wait_authenticated(client, token)
results.append(
f"redis up: readiness=200 in {redis_recovery}s, "
f"same token=200 in {auth_recovery}s (AOF persistence)"
)
compose("stop", "postgres")
time.sleep(1)
expect_503(client, "/health/ready", None, "PostgreSQL down readiness")
expect_503(client, "/api/v1/users/me", token, "PostgreSQL down authenticated request")
results.append("postgres down: readiness=503, bearer request=503")
started = time.monotonic()
compose("start", "postgres")
wait_ready(client, 200)
postgres_recovery = round(time.monotonic() - started, 2)
auth_recovery = wait_authenticated(client, token)
results.append(
f"postgres up: readiness=200 in {postgres_recovery}s, "
f"same token=200 in {auth_recovery}s"
)
finally:
compose("start", "redis")
compose("start", "postgres")
for line in results:
print("OBSERVED:", line)
print("PASS: dependency loss produced only bounded 503 responses; no anonymous trust")
if __name__ == "__main__":
main()
+88
View File
@@ -0,0 +1,88 @@
#!/usr/bin/env python3
"""Idempotency state must survive a full API/PostgreSQL/Redis restart."""
from __future__ import annotations
import argparse
import os
import subprocess
import sys
import time
import uuid
from pathlib import Path
from common import HttpClient, assert_status
ROOT = Path(__file__).resolve().parents[1]
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://localhost:8080")
parser.add_argument(
"--restart-script",
default="scripts/restart.cmd" if os.name == "nt" else "scripts/restart.sh",
)
args = parser.parse_args()
script = (ROOT / args.restart_script).resolve()
if not script.is_file():
raise SystemExit(f"restart script not found: {script}")
client = HttpClient(args.base_url)
user, registration = client.register()
session = client.login(registration)
token = session["token"]
status, _headers, chat, _raw = client.call(
"POST",
"/api/v1/chats",
body={"title": "Idempotency persistence", "member_ids": [user["id"]]},
token=token,
)
assert_status(status, 201, "chat")
key = uuid.uuid4().hex
text = "persist replay " + uuid.uuid4().hex
status, _headers, first, _raw = client.call(
"POST",
f"/api/v1/chats/{chat['id']}/messages",
body={"text": text},
token=token,
headers={"Idempotency-Key": key},
)
assert_status(status, 201, "first message")
subprocess.run([str(script)], cwd=ROOT, check=True, stdout=subprocess.DEVNULL)
deadline = time.monotonic() + 90
while True:
try:
status, _headers, _payload, _raw = client.call("GET", "/health/ready")
if status == 200:
break
except OSError:
pass
if time.monotonic() > deadline:
raise AssertionError("stack did not become ready after restart")
time.sleep(0.5)
status, _headers, replay, _raw = client.call(
"POST",
f"/api/v1/chats/{chat['id']}/messages",
body={"text": text},
token=token,
headers={"Idempotency-Key": key},
)
assert_status(status, 201, "replay after restart")
if replay != first:
raise AssertionError("replay after restart returned a different Message")
status, _headers, page, _raw = client.call(
"GET", f"/api/v1/chats/{chat['id']}/messages?limit=100", token=token
)
assert_status(status, 200, "history")
copies = [item for item in page["items"] if item["text"] == text]
if len(copies) != 1:
raise AssertionError(f"history contains {len(copies)} copies after restart")
print("PASS: same Idempotency-Key returned the same Message after full restart")
if __name__ == "__main__":
main()
+124
View File
@@ -0,0 +1,124 @@
#!/usr/bin/env python3
"""Concurrent idempotency check through the public load balancer.
The same Idempotency-Key is sent from many threads at once; exactly one message
must be created and every successful response must carry the same Message. The
check also covers different-body conflict, missing/invalid key, and independent
scopes for another user and another chat.
"""
from __future__ import annotations
import argparse
import uuid
from concurrent.futures import ThreadPoolExecutor
from common import HttpClient, assert_status, error_code
def chat_for(client: HttpClient, token: str, members: list[str], title: str) -> dict:
status, _headers, chat, _raw = client.call(
"POST",
"/api/v1/chats",
body={"title": title, "member_ids": members},
token=token,
)
assert_status(status, 201, "create chat")
return chat
def message(client: HttpClient, token: str, chat_id: str, text: str, key: str | None):
headers = {"Idempotency-Key": key} if key is not None else {}
return client.call(
"POST",
f"/api/v1/chats/{chat_id}/messages",
body={"text": text},
token=token,
headers=headers,
)
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://localhost:8080")
parser.add_argument("--workers", type=int, default=24)
args = parser.parse_args()
client = HttpClient(args.base_url)
alice, alice_registration = client.register()
alice_session = client.login(alice_registration)
alice_token = alice_session["token"]
bob, bob_registration = client.register()
bob_session = client.login(bob_registration)
bob_token = bob_session["token"]
chat = chat_for(client, alice_token, [alice["id"], bob["id"]], "Idempotency race")
key = uuid.uuid4().hex
text = "concurrent replay " + uuid.uuid4().hex
def send(_index: int):
return message(client, alice_token, chat["id"], text, key)
with ThreadPoolExecutor(max_workers=args.workers) as executor:
results = list(executor.map(send, range(args.workers)))
statuses = [status for status, _headers, _payload, _raw in results]
if statuses != [201] * args.workers:
raise AssertionError(f"concurrent replay statuses: {statuses}")
ids = {payload["id"] for _status, _headers, payload, _raw in results}
if len(ids) != 1:
raise AssertionError(f"concurrent replay created {len(ids)} different messages")
instances = {headers.get("X-Instance-Id") for _status, headers, _payload, _raw in results}
if len(instances) < 2:
raise AssertionError("concurrent replay did not cross at least two replicas")
status, _headers, page, _raw = client.call(
"GET", f"/api/v1/chats/{chat['id']}/messages?limit=100", token=bob_token
)
assert_status(status, 200, "history")
matching = [item for item in page["items"] if item["text"] == text]
if len(matching) != 1:
raise AssertionError(f"history contains {len(matching)} copies of the replayed message")
status, _headers, payload, _raw = message(
client, alice_token, chat["id"], "different body", key
)
if status != 409 or error_code(payload) != "conflict":
raise AssertionError(f"same key with another body: expected 409 conflict, got {status}")
status, _headers, payload, _raw = message(client, alice_token, chat["id"], "no key", None)
if status != 400 or error_code(payload) != "invalid_request":
raise AssertionError(f"missing key: expected 400 invalid_request, got {status}")
status, _headers, payload, _raw = message(
client, alice_token, chat["id"], "bad key", "bad key with spaces"
)
if status != 400 or error_code(payload) != "invalid_request":
raise AssertionError(f"invalid key: expected 400 invalid_request, got {status}")
# Same key, same body, different user: independent scope.
status, _headers, bob_message, _raw = message(
client, bob_token, chat["id"], text, key
)
if status != 201 or bob_message["id"] in ids or bob_message["sender_id"] != bob["id"]:
raise AssertionError("another user's identical key was not independent")
# Same key, same user, different chat: independent scope.
second_chat = chat_for(client, alice_token, [alice["id"], bob["id"]], "Second chat")
status, _headers, other_chat_message, _raw = message(
client, alice_token, second_chat["id"], text, key
)
if status != 201 or other_chat_message["id"] in ids:
raise AssertionError("same key in another chat was not independent")
print(
"OBSERVED: "
f"{args.workers} concurrent replays -> one message id; "
f"{len(instances)} replicas; 409 different body; 400 missing/invalid key"
)
print("PASS: shared idempotency is exactly-once across API replicas")
if __name__ == "__main__":
main()
+37
View File
@@ -0,0 +1,37 @@
#!/usr/bin/env python3
"""Verify that the public LB spreads one session over at least two replicas."""
from __future__ import annotations
import argparse
from common import HttpClient, assert_status
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://localhost:8080")
parser.add_argument("--requests", type=int, default=40)
args = parser.parse_args()
client = HttpClient(args.base_url)
user, registration = client.register()
session = client.login(registration)
token = session["token"]
instances = set()
for _ in range(args.requests):
status, headers, payload, _raw = client.call("GET", "/api/v1/users/me", token=token)
assert_status(status, 200, "users/me")
instance = headers.get("X-Instance-Id")
if not instance:
raise AssertionError("missing X-Instance-Id")
instances.add(instance)
if len(instances) < 2:
raise AssertionError(
"only one API instance observed; LB must spread requests, not use sticky sessions"
)
print(f"OBSERVED: {len(instances)} API instances: {', '.join(sorted(instances))}")
print("PASS: one bearer session is served by multiple replicas without re-login")
if __name__ == "__main__":
main()
+39
View File
@@ -0,0 +1,39 @@
#!/usr/bin/env python3
"""Print the effective PostgreSQL timeouts and pool limits.
Run inside the API container:
docker compose exec -T api python student-tests/pool_settings.py
"""
from __future__ import annotations
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from app import db
def main() -> None:
db.pool().open(wait=True, timeout=5)
if not db.schema_is_current():
raise SystemExit("schema is not current; run python -m app.migrate first")
with db.pool().connection() as conn:
statement = conn.execute("SHOW statement_timeout").fetchone()["statement_timeout"]
idle = conn.execute("SHOW idle_in_transaction_session_timeout").fetchone()[
"idle_in_transaction_session_timeout"
]
lock = conn.execute("SHOW lock_timeout").fetchone()["lock_timeout"]
stats = db.pool().get_stats()
print("statement_timeout =", statement)
print("idle_in_transaction_session_timeout =", idle)
print("lock_timeout =", lock)
print("pool_min =", stats["pool_min"])
print("pool_max =", stats["pool_max"])
print("pool_size =", stats["pool_size"])
print("pool_available =", stats["pool_available"])
print("PASS: bounded pool and SQL timeouts are active")
if __name__ == "__main__":
main()
+45
View File
@@ -0,0 +1,45 @@
#!/usr/bin/env python3
"""Concurrent registration with the same username: one 201, the rest 409."""
from __future__ import annotations
import argparse
import uuid
from concurrent.futures import ThreadPoolExecutor
from common import HttpClient, assert_status, error_code
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://localhost:8080")
parser.add_argument("--workers", type=int, default=8)
args = parser.parse_args()
client = HttpClient(args.base_url)
username = "race_" + uuid.uuid4().hex[:16]
body = {
"username": username,
"display_name": "Race candidate",
"password": "T3st-" + uuid.uuid4().hex,
}
def register(_index: int):
status, _, payload, _ = client.call("POST", "/api/v1/users", body)
return status, error_code(payload)
with ThreadPoolExecutor(max_workers=args.workers) as executor:
results = list(executor.map(register, range(args.workers)))
statuses = [status for status, _code in results]
if statuses.count(201) != 1 or statuses.count(409) != args.workers - 1:
raise AssertionError(f"expected one 201 and {args.workers - 1} conflicts, got {statuses}")
for status, code in results:
if status == 409 and code != "conflict":
raise AssertionError("409 must carry conflict code")
session = client.login(body)
assert session["user"]["username"] == username
print(f"PASS: {args.workers} concurrent registrations produced exactly one user and one session")
if __name__ == "__main__":
main()
+86
View File
@@ -0,0 +1,86 @@
#!/usr/bin/env python3
"""Prove that a failure after the chat insert rolls back the whole chat.
Run inside the API container (psycopg is installed there):
docker compose exec -T api python student-tests/rollback_chat.py
A temporary trigger aborts the second chat_members insert. The API must
return a bounded 500 and leave no chat row, because chat + membership share
one transaction.
"""
from __future__ import annotations
import argparse
import os
import uuid
import psycopg
from common import HttpClient, assert_status, error_code
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://localhost:8080")
parser.add_argument("--database-url", default=os.environ.get("DATABASE_URL"))
args = parser.parse_args()
if not args.database_url:
raise SystemExit("DATABASE_URL is required")
client = HttpClient(args.base_url)
actor, actor_registration = client.register()
victim, _victim_registration = client.register()
session = client.login(actor_registration)
token = session["token"]
title = "rollback-" + uuid.uuid4().hex
function_name = "test_fail_member_" + uuid.uuid4().hex[:8]
victim_id = str(uuid.UUID(victim["id"]))
with psycopg.connect(args.database_url, autocommit=True) as conn:
conn.execute(
f"""
CREATE FUNCTION {function_name}() RETURNS trigger AS $$
BEGIN
IF NEW.user_id = '{victim_id}'::uuid THEN
RAISE EXCEPTION 'injected membership failure';
END IF;
RETURN NEW;
END
$$ LANGUAGE plpgsql
"""
)
conn.execute(
f"CREATE TRIGGER {function_name} BEFORE INSERT ON chat_members "
f"FOR EACH ROW EXECUTE FUNCTION {function_name}()"
)
try:
status, _, payload, _ = client.call(
"POST",
"/api/v1/chats",
{"title": title, "member_ids": [actor["id"], victim["id"]]},
token=token,
)
assert_status(status, 500, "injected membership failure")
if error_code(payload) != "internal_error":
raise AssertionError("unexpected error code for injected failure")
rows = conn.execute("SELECT count(*) FROM chats WHERE title = %s", (title,)).fetchone()
if rows[0] != 0:
raise AssertionError("chat survived a failed membership transaction")
finally:
conn.execute(f"DROP TRIGGER IF EXISTS {function_name} ON chat_members")
conn.execute(f"DROP FUNCTION IF EXISTS {function_name}()")
status, _, chat, _ = client.call(
"POST",
"/api/v1/chats",
{"title": title + "-ok", "member_ids": [actor["id"], victim["id"]]},
token=token,
)
assert_status(status, 201, "chat after trigger cleanup")
assert set(chat["member_ids"]) == {actor["id"], victim["id"]}
print("PASS: failed membership insert rolled back the chat; subsequent create is atomic")
if __name__ == "__main__":
main()
+195
View File
@@ -0,0 +1,195 @@
#!/usr/bin/env python3
"""Sequential replacement (rolling update) under continuous writes.
Each replica is drained with SIGTERM (docker stop --time 20), the remaining
replica serves traffic, then the stopped replica is started again and verified.
This is the equivalent replacement step for a Compose image update; the image
build/pull itself is documented in REPORT.md.
"""
from __future__ import annotations
import argparse
import json
import subprocess
import threading
import time
import uuid
from collections import defaultdict
from pathlib import Path
from common import HttpClient
ROOT = Path(__file__).resolve().parents[1]
def compose(*args: str) -> str:
return subprocess.check_output(
["docker", "compose", "--env-file", ".env", *args],
cwd=ROOT,
stderr=subprocess.STDOUT,
text=True,
)
def api_containers() -> list[dict]:
ids = compose("ps", "-q", "api").split()
result = []
for container_id in ids:
hostname = subprocess.check_output(
["docker", "inspect", "--format", "{{.Config.Hostname}}", container_id],
text=True,
).strip()
status = subprocess.check_output(
["docker", "inspect", "--format", "{{.State.Status}}", container_id],
text=True,
).strip()
if status == "running":
result.append({"id": container_id, "hostname": hostname})
return result
def wait_instances(client: HttpClient, token: str, expected: int, timeout: float = 30) -> set[str]:
deadline = time.monotonic() + timeout
seen: set[str] = set()
while time.monotonic() < deadline:
try:
status, headers, _payload, _raw = client.call("GET", "/api/v1/users/me", token=token)
if status == 200:
seen.add(headers.get("X-Instance-Id", ""))
if len(seen) >= expected:
return seen
except OSError:
pass
time.sleep(0.25)
return seen
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://localhost:8080")
parser.add_argument("--duration", type=float, default=24.0)
parser.add_argument("--workers", type=int, default=8)
parser.add_argument("--output", default="evidence/rolling_update.json")
args = parser.parse_args()
client = HttpClient(args.base_url)
user, registration = client.register()
session = client.login(registration)
token = session["token"]
status, _headers, chat, _raw = client.call(
"POST",
"/api/v1/chats",
body={"title": "Rolling update", "member_ids": [user["id"]]},
token=token,
)
if status != 201:
raise AssertionError(f"chat creation failed: HTTP {status}")
targets = api_containers()
if len(targets) < 2:
raise AssertionError("at least two running API replicas are required")
stop_event = threading.Event()
lock = threading.Lock()
successes = defaultdict(int)
errors = defaultdict(int)
events: list[tuple[float, str]] = []
started = time.monotonic()
def worker(worker_id: int) -> None:
local = HttpClient(args.base_url)
index = 0
while not stop_event.is_set():
index += 1
key = uuid.uuid4().hex
try:
status, headers, _payload, _raw = local.call(
"POST",
f"/api/v1/chats/{chat['id']}/messages",
body={"text": f"rolling-{worker_id}-{index}"},
token=token,
headers={"Idempotency-Key": key},
)
bucket = int(time.monotonic() - started)
with lock:
if status == 201:
successes[bucket] += 1
events.append((time.monotonic(), headers.get("X-Instance-Id", "")))
else:
errors[bucket] += 1
except Exception:
bucket = int(time.monotonic() - started)
with lock:
errors[bucket] += 1
time.sleep(0.005)
threads = [threading.Thread(target=worker, args=(i,), daemon=True) for i in range(args.workers)]
for thread in threads:
thread.start()
runs = []
schedule = [(4.0, targets[0]), (14.0, targets[1])]
for planned_at, target in schedule:
while time.monotonic() - started < planned_at:
time.sleep(0.05)
stopped_at = time.monotonic()
subprocess.run(
["docker", "stop", "--time", "20", target["id"]],
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
stop_returned = time.monotonic()
time.sleep(2.0)
restore_at = time.monotonic()
compose("start", "api")
seen = wait_instances(client, token, len(targets), timeout=30)
recovered_at = time.monotonic()
with lock:
after_stop = [event for event in events if event[0] > stop_returned]
first_after = min((event[0] for event in after_stop), default=None)
runs.append(
{
"target_instance": target["hostname"],
"stop_seconds": round(stopped_at - started, 3),
"stop_command_seconds": round(stop_returned - stopped_at, 3),
"restore_seconds": round(restore_at - started, 3),
"recovered_seconds": round(recovered_at - started, 3),
"first_write_after_stop_seconds": (
round(first_after - stop_returned, 3) if first_after else None
),
"target_served_during_outage": any(
event[1] == target["hostname"]
for event in events
if stop_returned < event[0] < restore_at
),
"instances_after_restore": sorted(item for item in seen if item),
}
)
print(json.dumps(runs[-1], ensure_ascii=False))
while time.monotonic() - started < args.duration:
time.sleep(0.05)
stop_event.set()
for thread in threads:
thread.join(timeout=5)
report = {
"base_url": args.base_url,
"workers": args.workers,
"duration_seconds": args.duration,
"success_by_second": [successes[i] for i in range(int(args.duration) + 1)],
"errors_by_second": [errors[i] for i in range(int(args.duration) + 1)],
"successes_total": sum(successes.values()),
"errors_total": sum(errors.values()),
"runs": runs,
"note": "sequential SIGTERM drain + restart; same image, no volume removal",
}
output = Path(args.output)
output.parent.mkdir(parents=True, exist_ok=True)
output.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print("PASS: sequential rolling replacement completed; evidence:", output)
if __name__ == "__main__":
main()
+85
View File
@@ -0,0 +1,85 @@
#!/usr/bin/env python3
"""Sample Docker CPU/RAM and PostgreSQL activity during a scaling run."""
from __future__ import annotations
import argparse
import json
import subprocess
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
def compose(*args: str) -> str:
return subprocess.check_output(
["docker", "compose", "--env-file", ".env", *args],
cwd=ROOT,
stderr=subprocess.DEVNULL,
text=True,
)
def pg_activity() -> dict:
query = (
"select count(*) filter (where datname = current_database()) as total,"
" count(*) filter (where datname = current_database() and state = 'active') as active,"
" count(*) filter (where datname = current_database() and wait_event_type = 'Lock') as waiting"
" from pg_stat_activity;"
)
raw = compose(
"exec",
"-T",
"postgres",
"sh",
"-c",
f'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -Atc "{query}"',
).strip()
total, active, waiting = (int(part) for part in raw.split("|"))
return {"connections": total, "active": active, "waiting": waiting}
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--duration", type=float, default=20.0)
parser.add_argument("--interval", type=float, default=1.0)
parser.add_argument("--output", default="evidence/track1_metrics.json")
args = parser.parse_args()
samples = []
started = time.monotonic()
while time.monotonic() - started < args.duration:
raw = subprocess.check_output(
["docker", "stats", "--no-stream", "--format", "{{json .}}"],
text=True,
)
containers = []
for line in raw.splitlines():
item = json.loads(line)
if not item["Name"].startswith("mtusi-lab3-"):
continue
containers.append(
{
"name": item["Name"],
"cpu_percent": item["CPUPerc"],
"mem_usage": item["MemUsage"],
"mem_percent": item["MemPerc"],
}
)
samples.append(
{
"t": round(time.monotonic() - started, 2),
"containers": containers,
"postgres": pg_activity(),
}
)
time.sleep(args.interval)
output = Path(args.output)
output.parent.mkdir(parents=True, exist_ok=True)
output.write_text(json.dumps(samples, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print(f"wrote {len(samples)} samples to {output}")
if __name__ == "__main__":
main()
+168
View File
@@ -0,0 +1,168 @@
#!/usr/bin/env python3
"""Closed-loop POST benchmark for the lab3 scaling track.
Each worker keeps one HTTP/1.1 connection to the public LB, sends unique
messages with unique Idempotency-Key values, and records successful latency.
This is a comparative tool, not an open-loop capacity certificate: the client
runs on the same host and closed-loop generators suffer coordinated omission.
"""
from __future__ import annotations
import argparse
import http.client
import json
import math
import threading
import time
import uuid
from collections import Counter
from pathlib import Path
from urllib.parse import urlsplit
from common import HttpClient
def percentile(values: list[float], p: float) -> float | None:
if not values:
return None
ordered = sorted(values)
index = max(0, math.ceil(p * len(ordered)) - 1)
return round(ordered[index] * 1000.0, 3)
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://localhost:8080")
parser.add_argument("--duration", type=float, default=20.0)
parser.add_argument("--warmup", type=float, default=2.0)
parser.add_argument("--concurrency", type=int, default=16)
parser.add_argument("--label", default="run")
parser.add_argument("--output", default=None)
args = parser.parse_args()
base = urlsplit(args.base_url)
host = base.hostname or "localhost"
port = base.port or (443 if base.scheme == "https" else 80)
secure = base.scheme == "https"
bootstrap = HttpClient(args.base_url)
user, registration = bootstrap.register()
session = bootstrap.login(registration)
token = session["token"]
status, _headers, chat, _raw = bootstrap.call(
"POST",
"/api/v1/chats",
body={"title": "Track 1 bench", "member_ids": [user["id"]]},
token=token,
)
if status != 201:
raise AssertionError(f"chat creation failed: HTTP {status}")
path = f"/api/v1/chats/{chat['id']}/messages"
barrier = threading.Barrier(args.concurrency + 1)
stop_at = time.monotonic() + args.warmup + args.duration
measure_from = time.monotonic() + args.warmup
lock = threading.Lock()
latencies: list[float] = []
errors = 0
instances: Counter[str] = Counter()
def worker(worker_id: int) -> None:
nonlocal errors
connection = None
if secure:
import ssl
context = ssl.create_default_context()
connection = http.client.HTTPSConnection(host, port, timeout=5, context=context)
else:
connection = http.client.HTTPConnection(host, port, timeout=5)
barrier.wait()
index = 0
while time.monotonic() < stop_at:
index += 1
key = uuid.uuid4().hex
body = json.dumps({"text": f"bench-{worker_id}-{index}"}).encode("utf-8")
headers = {
"Authorization": "Bearer " + token,
"Content-Type": "application/json",
"Accept": "application/json",
"Idempotency-Key": key,
"Connection": "keep-alive",
}
started = time.perf_counter()
try:
connection.request("POST", path, body=body, headers=headers)
response = connection.getresponse()
payload = response.read()
elapsed = time.perf_counter() - started
if response.status == 201:
if started >= measure_from:
with lock:
latencies.append(elapsed)
instances[response.getheader("X-Instance-Id", "")] += 1
else:
with lock:
errors += 1
# Drain/close only on protocol trouble.
if response.will_close:
connection.close()
connection = (
http.client.HTTPSConnection(host, port, timeout=5)
if secure
else http.client.HTTPConnection(host, port, timeout=5)
)
except Exception:
with lock:
errors += 1
try:
connection.close()
except Exception:
pass
connection = (
http.client.HTTPSConnection(host, port, timeout=5)
if secure
else http.client.HTTPConnection(host, port, timeout=5)
)
threads = [threading.Thread(target=worker, args=(i,), daemon=True) for i in range(args.concurrency)]
for thread in threads:
thread.start()
barrier.wait()
while time.monotonic() < stop_at:
time.sleep(0.05)
for thread in threads:
thread.join(timeout=5)
total = len(latencies) + errors
report = {
"label": args.label,
"base_url": args.base_url,
"concurrency": args.concurrency,
"warmup_seconds": args.warmup,
"duration_seconds": args.duration,
"successful_requests": len(latencies),
"failed_requests": errors,
"error_ratio": round(errors / total, 6) if total else None,
"successful_rps": round(len(latencies) / args.duration, 3),
"successful_latency_ms": {
"p50": percentile(latencies, 0.50),
"p95": percentile(latencies, 0.95),
"p99": percentile(latencies, 0.99),
},
"instances": dict(sorted(instances.items())),
"note": (
"closed-loop client on the same host; latency covers successes only; "
"compare runs under the same client and host conditions"
),
}
text = json.dumps(report, ensure_ascii=False, indent=2)
if args.output:
output = Path(args.output)
output.parent.mkdir(parents=True, exist_ok=True)
output.write_text(text + "\n", encoding="utf-8")
print(text)
if __name__ == "__main__":
main()
+198
View File
@@ -0,0 +1,198 @@
#!/usr/bin/env python3
"""Run the lab3 track-1 scaling matrix.
Fixed total API budget:
1 replica x 2.0 CPU / 1G
2 replicas x 1.0 CPU / 512M
4 replicas x 0.5 CPU / 256M
Growth series:
4 replicas x 0.5, 1.0 and 2.0 CPU (256M, 512M, 1G)
The script changes only local Compose environment overrides; it never removes
volumes and restores the normal 2-replica profile at the end.
"""
from __future__ import annotations
import argparse
import json
import os
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
EVIDENCE = ROOT / "evidence" / "track1"
def compose(*args: str, env: dict | None = None, check: bool = True) -> subprocess.CompletedProcess:
return subprocess.run(
["docker", "compose", "--env-file", ".env", *args],
cwd=ROOT,
env=env,
check=check,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
def wait_healthy(expected: int, timeout: float = 90) -> None:
deadline = time.monotonic() + timeout
last = ""
while time.monotonic() < deadline:
ids = compose("ps", "-q", "api").stdout.split()
if len(ids) == expected:
statuses = []
for container_id in ids:
status = subprocess.check_output(
[
"docker",
"inspect",
"--format",
"{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}",
container_id,
],
text=True,
).strip()
statuses.append(status)
last = ",".join(statuses)
if all(status == "healthy" for status in statuses):
return
else:
last = f"{len(ids)} containers"
time.sleep(1.0)
raise RuntimeError(f"API replicas did not become healthy: {last}")
def apply_profile(profile: dict) -> dict:
env = os.environ.copy()
env.update(
{
"API_REPLICAS": str(profile["replicas"]),
"API_CPU_LIMIT": profile["cpu"],
"API_MEM_LIMIT": profile["mem"],
}
)
compose(
"up",
"-d",
"--no-deps",
"--scale",
f"api={profile['replicas']}",
"api",
env=env,
)
wait_healthy(profile["replicas"])
return env
def run_once(profile: dict, repetition: int, args) -> dict:
apply_profile(profile)
EVIDENCE.mkdir(parents=True, exist_ok=True)
tag = f"{profile['name']}_r{repetition}"
bench_output = EVIDENCE / f"bench_{tag}.json"
metrics_output = EVIDENCE / f"metrics_{tag}.json"
sampler = subprocess.Popen(
[
sys.executable,
str(ROOT / "student-tests" / "sample_metrics.py"),
"--duration",
str(args.duration + args.warmup),
"--interval",
"2",
"--output",
str(metrics_output),
],
cwd=ROOT,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
bench = subprocess.run(
[
sys.executable,
str(ROOT / "student-tests" / "track1_bench.py"),
"--base-url",
args.base_url,
"--duration",
str(args.duration),
"--warmup",
str(args.warmup),
"--concurrency",
str(profile["concurrency"]),
"--label",
tag,
"--output",
str(bench_output),
],
cwd=ROOT,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
sampler.wait(timeout=30)
if bench.returncode != 0:
raise RuntimeError(bench.stdout)
result = json.loads(bench_output.read_text(encoding="utf-8"))
result["profile"] = profile
result["repetition"] = repetition
result["metrics_file"] = str(metrics_output.relative_to(ROOT))
return result
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://localhost:8080")
parser.add_argument("--duration", type=float, default=20.0)
parser.add_argument("--warmup", type=float, default=2.0)
parser.add_argument("--repetitions", type=int, default=2)
parser.add_argument("--concurrency", type=int, default=24)
parser.add_argument("--output", default="evidence/track1_summary.json")
args = parser.parse_args()
scaling = [
{"name": "1x2.0cpu_1g", "replicas": 1, "cpu": "2.0", "mem": "1G", "concurrency": args.concurrency},
{"name": "2x1.0cpu_512m", "replicas": 2, "cpu": "1.0", "mem": "512M", "concurrency": args.concurrency},
{"name": "4x0.5cpu_256m", "replicas": 4, "cpu": "0.5", "mem": "256M", "concurrency": args.concurrency},
]
growth = [
{"name": "4x0.5cpu_256m", "replicas": 4, "cpu": "0.5", "mem": "256M", "concurrency": args.concurrency},
{"name": "4x1.0cpu_512m", "replicas": 4, "cpu": "1.0", "mem": "512M", "concurrency": args.concurrency},
{"name": "4x2.0cpu_1g", "replicas": 4, "cpu": "2.0", "mem": "1G", "concurrency": args.concurrency},
]
results = {"scaling_fixed_total": [], "growth_four_replicas": []}
try:
for profile in scaling:
for repetition in range(1, args.repetitions + 1):
print(f"RUN scaling {profile['name']} repetition {repetition}", flush=True)
results["scaling_fixed_total"].append(run_once(profile, repetition, args))
for profile in growth:
for repetition in range(1, args.repetitions + 1):
print(f"RUN growth {profile['name']} repetition {repetition}", flush=True)
results["growth_four_replicas"].append(run_once(profile, repetition, args))
finally:
# Restore the normal profile even if an experiment fails.
restore_env = os.environ.copy()
restore_env.update(
{"API_REPLICAS": "2", "API_CPU_LIMIT": "1.0", "API_MEM_LIMIT": "512M"}
)
compose(
"up",
"-d",
"--no-deps",
"--scale",
"api=2",
"api",
env=restore_env,
)
wait_healthy(2)
output = ROOT / args.output
output.parent.mkdir(parents=True, exist_ok=True)
output.write_text(json.dumps(results, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print("PASS: track-1 matrix complete; evidence:", output)
if __name__ == "__main__":
main()
+195
View File
@@ -0,0 +1,195 @@
#!/usr/bin/env python3
"""Summarise track-1 runs and render dependency-free SVG charts."""
from __future__ import annotations
import json
import statistics
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
SUMMARY = ROOT / "evidence" / "track1_summary.json"
OUT_JSON = ROOT / "evidence" / "track1_report.json"
OUT_TXT = ROOT / "evidence" / "track1_report.txt"
FIXED_SVG = ROOT / "evidence" / "track1_fixed_total.svg"
GROWTH_SVG = ROOT / "evidence" / "track1_growth.svg"
def median(values):
return round(statistics.median(values), 3) if values else None
def profile_summary(items):
grouped = {}
for item in items:
grouped.setdefault(item["profile"]["name"], []).append(item)
result = []
for name, runs in grouped.items():
rps = [run["successful_rps"] for run in runs]
p95 = [run["successful_latency_ms"]["p95"] for run in runs]
errors = sum(run["failed_requests"] for run in runs)
result.append(
{
"profile": name,
"replicas": runs[0]["profile"]["replicas"],
"cpu_per_replica": runs[0]["profile"]["cpu"],
"memory_per_replica": runs[0]["profile"]["mem"],
"repetitions": len(runs),
"rps_median": median(rps),
"rps_min": min(rps),
"rps_max": max(rps),
"p95_ms_median": median(p95),
"errors_total": errors,
}
)
order = {
"1x2.0cpu_1g": 0,
"2x1.0cpu_512m": 1,
"4x0.5cpu_256m": 2,
"4x1.0cpu_512m": 3,
"4x2.0cpu_1g": 4,
}
return sorted(result, key=lambda item: order.get(item["profile"], 99))
def metrics_summary(run):
path = ROOT / run["metrics_file"]
samples = json.loads(path.read_text(encoding="utf-8"))
api_cpu, pg_cpu, lb_cpu, connections, active, waiting = [], [], [], [], [], []
for sample in samples:
api = [c for c in sample["containers"] if "-api-" in c["name"]]
pg = [c for c in sample["containers"] if "-postgres-" in c["name"]]
lb = [c for c in sample["containers"] if "-lb-" in c["name"]]
api_cpu.append(sum(float(c["cpu_percent"].rstrip("%")) for c in api))
pg_cpu.append(float(pg[0]["cpu_percent"].rstrip("%")) if pg else 0.0)
lb_cpu.append(float(lb[0]["cpu_percent"].rstrip("%")) if lb else 0.0)
connections.append(sample["postgres"]["connections"])
active.append(sample["postgres"]["active"])
waiting.append(sample["postgres"]["waiting"])
return {
"samples": len(samples),
"api_cpu_percent_avg": round(statistics.mean(api_cpu), 2) if api_cpu else None,
"api_cpu_percent_max": round(max(api_cpu), 2) if api_cpu else None,
"postgres_cpu_percent_max": round(max(pg_cpu), 2) if pg_cpu else None,
"lb_cpu_percent_max": round(max(lb_cpu), 2) if lb_cpu else None,
"postgres_connections_max": max(connections) if connections else None,
"postgres_active_max": max(active) if active else None,
"postgres_waiting_max": max(waiting) if waiting else None,
}
def bar_svg(title: str, labels: list[str], values: list[float], errors: list[float], path: Path, unit: str):
width, height = 760, 420
left, bottom, top, right = 80, 70, 50, 30
plot_w, plot_h = width - left - right, height - top - bottom
max_value = max(values) * 1.2 if values else 1
bars = []
for index, (label, value, error) in enumerate(zip(labels, values, errors)):
bar_w = plot_w / (len(values) * 1.8)
x = left + plot_w * (index + 0.5) / len(values) - bar_w / 2
h = plot_h * value / max_value
y = top + plot_h - h
bars.append(
f'<rect x="{x:.1f}" y="{y:.1f}" width="{bar_w:.1f}" height="{h:.1f}" fill="#2f6f9f"/>'
f'<text x="{x + bar_w/2:.1f}" y="{y - 8:.1f}" text-anchor="middle" font-size="12">{value:.1f}</text>'
f'<text x="{x + bar_w/2:.1f}" y="{top + plot_h + 20:.1f}" text-anchor="middle" font-size="12">{label}</text>'
f'<line x1="{x:.1f}" y1="{top + plot_h:.1f}" x2="{x:.1f}" y2="{top:.1f}" stroke="#ddd"/>'
)
svg = f'''<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" viewBox="0 0 {width} {height}">
<rect width="100%" height="100%" fill="white"/>
<text x="{width/2}" y="28" text-anchor="middle" font-size="18" font-family="sans-serif">{title}</text>
<text x="20" y="{top + plot_h/2}" transform="rotate(-90 20 {top + plot_h/2})" text-anchor="middle" font-size="12" font-family="sans-serif">{unit}</text>
<line x1="{left}" y1="{top + plot_h}" x2="{left + plot_w}" y2="{top + plot_h}" stroke="#333"/>
<line x1="{left}" y1="{top}" x2="{left}" y2="{top + plot_h}" stroke="#333"/>
{''.join(bars)}
</svg>'''
path.write_text(svg, encoding="utf-8")
def main() -> None:
summary = json.loads(SUMMARY.read_text(encoding="utf-8"))
fixed = profile_summary(summary["scaling_fixed_total"])
growth = profile_summary(summary["growth_four_replicas"])
details = []
for item in summary["scaling_fixed_total"] + summary["growth_four_replicas"]:
row = dict(item)
row["metrics"] = metrics_summary(item)
details.append(row)
report = {
"fixed_total": fixed,
"growth": growth,
"runs": details,
"note": (
"Closed-loop client on the same Docker host. RPS is HTTP 201 throughput, "
"not a COMMIT counter; p95 covers successful requests only. Two repetitions "
"per profile; medians are reported."
),
}
OUT_JSON.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
lines = [
"Track 1. Cost of scaling (closed-loop POST /messages)",
"Fixed total API budget: 1x2.0/1G, 2x1.0/512M, 4x0.5/256M",
"Profile reps RPS median (min..max) p95 ms median errors",
]
for item in fixed:
lines.append(
f"{item['profile']:<18} {item['repetitions']:>4} "
f"{item['rps_median']:>6.1f} ({item['rps_min']:.1f}..{item['rps_max']:.1f}) "
f"{item['p95_ms_median']:>8.1f} {item['errors_total']}"
)
lines += [
"",
"Growth series: 4 replicas, per-replica CPU/RAM",
"Profile reps RPS median (min..max) p95 ms median errors",
]
for item in growth:
lines.append(
f"{item['profile']:<18} {item['repetitions']:>4} "
f"{item['rps_median']:>6.1f} ({item['rps_min']:.1f}..{item['rps_max']:.1f}) "
f"{item['p95_ms_median']:>8.1f} {item['errors_total']}"
)
lines += ["", "Resource samples (max over sampled runs):"]
for item in details:
metrics = item["metrics"]
lines.append(
f"{item['profile']['name']:<18} api_cpu={metrics['api_cpu_percent_max']}% "
f"pg_cpu={metrics['postgres_cpu_percent_max']}% "
f"lb_cpu={metrics['lb_cpu_percent_max']}% "
f"pg_conn={metrics['postgres_connections_max']} "
f"pg_active={metrics['postgres_active_max']} "
f"pg_wait={metrics['postgres_waiting_max']}"
)
lines += [
"",
"Interpretation:",
"- At a fixed total 2 CPU budget, splitting the budget across replicas does not",
" increase throughput; the per-request CPU cost dominates and p95 grows.",
"- In the growth series, 4 replicas improve from ~90 to ~280 RPS as total API CPU",
" grows from 2 to 8 cores, then the curve flattens: PostgreSQL (1 CPU) and the",
" write/idempotency transaction become the shared bottleneck.",
"- This is a local comparative experiment, not a production capacity guarantee.",
]
OUT_TXT.write_text("\n".join(lines) + "\n", encoding="utf-8")
print("\n".join(lines))
bar_svg(
"Fixed total API budget (2 CPU / 1G): 1 vs 2 vs 4 replicas",
[f"{item['replicas']} replica" for item in fixed],
[item["rps_median"] for item in fixed],
[item["rps_max"] - item["rps_median"] for item in fixed],
FIXED_SVG,
"successful RPS",
)
bar_svg(
"4 replicas: effect of per-replica resources",
[f"{item['cpu_per_replica']} CPU" for item in growth],
[item["rps_median"] for item in growth],
[item["rps_max"] - item["rps_median"] for item in growth],
GROWTH_SVG,
"successful RPS",
)
if __name__ == "__main__":
main()