diff --git a/compose.yaml b/compose.yaml index cff40ee..642945c 100644 --- a/compose.yaml +++ b/compose.yaml @@ -1,7 +1,7 @@ name: mtusi-lab2-maslov services: postgres: - image: postgres:18.3 + image: postgres:18.3@sha256:7e32e9833a6fb1c92c32552794cb6ed569d51b445a54907d35fc112ef39684db environment: POSTGRES_USER: messenger POSTGRES_DB: messenger @@ -19,7 +19,7 @@ services: mem_limit: 512m memswap_limit: 512m cache: - image: valkey/valkey:8.1.3 + image: valkey/valkey:8.1.3@sha256:fea8b3e67b15729d4bb70589eb03367bab9ad1ee89c876f54327fc7c6e618571 command: [valkey-server, /run/secrets/valkey.conf] secrets: - cache_password diff --git a/evidence/pool.json b/evidence/pool.json new file mode 100644 index 0000000..1a95823 --- /dev/null +++ b/evidence/pool.json @@ -0,0 +1,13 @@ +{ + "date": "2026-11-07T05:15:33.380498+00:00", + "commit": "171b6de9c87c14cdfb1f9ec6a58aab7101c23d6a", + "command": "python -m scripts.verify_pool", + "pool_size": 1, + "blocked_insert_observed_in_pg_stat_activity": true, + "pool_wait_seconds": 1.0045806250127498, + "pool_timeout_status": 503, + "statement_timeout_status": 503, + "failed_write_rolled_back": true, + "write_after_recovery": 201, + "result": "PASS" +} diff --git a/evidence/query-plans.png b/evidence/query-plans.png new file mode 100644 index 0000000..a55fd24 Binary files /dev/null and b/evidence/query-plans.png differ diff --git a/evidence/query-summary.csv b/evidence/query-summary.csv new file mode 100644 index 0000000..308568a --- /dev/null +++ b/evidence/query-summary.csv @@ -0,0 +1,31 @@ +messages,position,variant,repeats,median_sql_ms,min_sql_ms,max_sql_ms,median_buffers +10,head,chat_only,3,0.011,0.011,0.015,3 +10,head,keyset,3,0.006,0.006,0.008,4 +10,middle,chat_only,3,0.01,0.008,0.013,3 +10,middle,keyset,3,0.005,0.005,0.007,4 +10,tail,chat_only,3,0.011,0.01,0.011,3 +10,tail,keyset,3,0.006,0.006,0.007,4 +100,head,chat_only,3,0.038,0.034,0.039,6 +100,head,keyset,3,0.016,0.016,0.018,7 +100,middle,chat_only,3,0.03,0.026,0.034,6 +100,middle,keyset,3,0.015,0.014,0.015,5 +100,tail,chat_only,3,0.028,0.027,0.031,6 +100,tail,keyset,3,0.016,0.015,0.016,6 +1000,head,chat_only,3,0.197,0.195,0.205,25 +1000,head,keyset,3,0.018,0.016,0.02,5 +1000,middle,chat_only,3,0.152,0.136,0.158,25 +1000,middle,keyset,3,0.026,0.017,0.032,6 +1000,tail,chat_only,3,0.092,0.08,0.106,25 +1000,tail,keyset,3,0.016,0.015,0.019,6 +10000,head,chat_only,3,1.801,1.755,1.845,224 +10000,head,keyset,3,0.019,0.018,0.019,6 +10000,middle,chat_only,3,1.187,1.17,1.198,224 +10000,middle,keyset,3,0.016,0.016,0.018,5 +10000,tail,chat_only,3,0.624,0.603,0.878,224 +10000,tail,keyset,3,0.016,0.016,0.017,6 +90000,head,chat_only,3,16.501,9.887,22.44,2209 +90000,head,keyset,3,0.02,0.019,0.021,5 +90000,middle,chat_only,3,7.237,7.082,8.505,2209 +90000,middle,keyset,3,0.017,0.016,0.018,5 +90000,tail,chat_only,3,4.287,4.282,4.674,2194 +90000,tail,keyset,3,0.016,0.016,0.018,5 diff --git a/evidence/query-summary.md b/evidence/query-summary.md new file mode 100644 index 0000000..3055e09 --- /dev/null +++ b/evidence/query-summary.md @@ -0,0 +1,20 @@ +# Планы запросов и восстановление + +Три повтора, 101110 сообщений в 5 неравномерных чатах. + +| Индекс | SQL середины чата90k, мс | Буферы | Размер, bytes | INSERT+COMMIT1000, мс | WAL, bytes | +|---|---:|---:|---:|---:|---:| +| chat_only | 7.237 | 2209 | 729088 | 37.53 | 347536 | +| keyset | 0.017 | 5 | 5980160 | 11.55 | 427672 | + +Dump: 0.480 s, 3026259 bytes. +Restore в новую БД: 0.664 s. +Проверены count всех таблиц, SHA-256 всей истории и 15 полных сообщений. +Одна отдельная SQL-запись после snapshot не восстановлена — ожидаемая +граница snapshot backup. Это не HTTP RPO и не гарантия HA. + +Время EXPLAIN — SQL execution time, не HTTP latency. Цена записи включает +COMMIT 1000 строк; WAL — глобальный счётчик PG и может включать фон. +Индекс keyset больше и даёт больше WAL, но в этом опыте INSERT быстрее: +гипотеза роста именно времени записи не подтвердилась. Причина механизма +такого различия отдельно не профилировалась. diff --git a/evidence/verification-notes.md b/evidence/verification-notes.md new file mode 100644 index 0000000..f69db34 --- /dev/null +++ b/evidence/verification-notes.md @@ -0,0 +1,13 @@ +# Область первых проверок + +В lifecycle.json подтверждены restart всех трёх процессов, тот же токен, +expiry/logout, cache hits и bounded 503 при остановке/паузе PostgreSQL. +Однако наличие карточки в кэше непосредственно перед отказом PG отдельно +не проверялось: после рестарта cache могло ещё действовать окно backoff. +Поэтому cached_identity_not_trusted в этой первой записи не является +самостоятельным доказательством сохранённого cache hit при отказе PG. + +Финальный скрипт усилен: ждёт окончания backoff, проверяет EXISTS карточки +перед каждым воздействием на PG и сравнивает абсолютный expires_at до/после +restart. Этот вариант повторяется в финальном чистом clone; результат +будет в clean-clone.json. Runtime API при этом не менялся. diff --git a/scripts/verify_clean.py b/scripts/verify_clean.py new file mode 100644 index 0000000..8516579 --- /dev/null +++ b/scripts/verify_clean.py @@ -0,0 +1,212 @@ +import argparse +import json +import os +import subprocess +import tempfile +from datetime import UTC, datetime +from pathlib import Path +from uuid import uuid4 + +ROOT = Path(__file__).resolve().parents[1] + + +def run(args, *, cwd, env, expected=0): + result = subprocess.run( + args, cwd=cwd, env=env, capture_output=True, text=True + ) + + def redact(text): + return ( + text.replace(str(cwd), "") + .replace(str(ROOT), "") + .replace(str(Path.home()), "") + ) + + if result.returncode != expected: + raise RuntimeError(redact(result.stdout + result.stderr)) + return redact(result.stdout.strip()) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--output", default="evidence/clean-clone.json") + args = parser.parse_args() + output = ROOT / args.output + if output.exists(): + raise SystemExit("Choose new output path") + assert not subprocess.check_output( + ["git", "status", "--porcelain"], cwd=ROOT + ) + sha = subprocess.check_output( + ["git", "rev-parse", "HEAD"], cwd=ROOT, text=True + ).strip() + identity = uuid4().hex[:10] + project = "mtusi-lab2-clean-" + identity + env = { + **os.environ, + "COMPOSE_PROJECT_NAME": project, + "API_IMAGE": "mtusi-messenger:lab2-clean-" + identity, + "PUBLIC_PORT": "0", + "VCS_REF": sha, + "NO_PROXY": "localhost,127.0.0.1", + "no_proxy": "localhost,127.0.0.1", + } + receipt = { + "date": datetime.now(UTC).isoformat(), + "source_commit": sha, + "fresh_secrets_environment_and_volumes": True, + "command": "python scripts/verify_clean.py", + } + with tempfile.TemporaryDirectory(prefix="mtusi-lab2-clean-") as temporary: + clone = Path(temporary) / "lab2" + run( + [ + "git", + "clone", + "--no-hardlinks", + "--branch", + "solution/bvt2301-maslov", + str(ROOT), + str(clone), + ], + cwd=ROOT, + env=env, + ) + for name in [".env", ".venv", "secrets"]: + assert not (clone / name).exists() + run(["uv", "sync", "--locked"], cwd=clone, env=env) + receipt["static_checks"] = run( + ["make", "check", "validate", "lint", "PYTHON=.venv/bin/python"], + cwd=clone, + env=env, + ) + run(["make", "bootstrap"], cwd=clone, env=env) + try: + run( + ["docker", "compose", "up", "-d", "--build", "--wait"], + cwd=clone, + env=env, + ) + api = run( + ["docker", "compose", "ps", "-q", "api"], cwd=clone, env=env + ) + info = json.loads( + run(["docker", "inspect", api], cwd=clone, env=env) + )[0] + endpoint = info["NetworkSettings"]["Ports"]["8080/tcp"][0] + assert endpoint["HostIp"] == "127.0.0.1" + env["BASE_URL"] = "http://127.0.0.1:" + endpoint["HostPort"] + for role, port in [ + ("postgres", "5432/tcp"), + ("cache", "6379/tcp"), + ]: + cid = run( + ["docker", "compose", "ps", "-q", role], cwd=clone, env=env + ) + state = json.loads( + run(["docker", "inspect", cid], cwd=clone, env=env) + )[0] + assert not state["NetworkSettings"]["Ports"].get(port) + receipt["internal_store_ports_not_published"] = True + receipt["smoke"] = run( + ["make", "test", "BASE_URL=" + env["BASE_URL"]], + cwd=clone, + env=env, + ) + receipt["http_tests"] = run( + [".venv/bin/pytest", "student-tests", "-q"], cwd=clone, env=env + ) + receipt["public_persistence"] = run( + [ + "make", + "test-persistence", + "ACTION_SCRIPT=scripts/restart.sh", + "BASE_URL=" + env["BASE_URL"], + ], + cwd=clone, + env=env, + ) + for module, filename in [ + ("verify_lifecycle", "clean-lifecycle.json"), + ("verify_pool", "clean-pool.json"), + ]: + run( + [ + ".venv/bin/python", + "-m", + "scripts." + module, + "--output", + "evidence/" + filename, + ], + cwd=clone, + env=env, + ) + receipt[module] = json.loads( + (clone / "evidence" / filename).read_text() + ) + # Подменяется только временная read-only копия миграции. + altered = clone / ".work/altered-migrations" + altered.mkdir(parents=True) + migration = clone / "migrations/001_core.sql" + (altered / migration.name).write_bytes( + migration.read_bytes() + b"\n-- synthetic checksum mismatch\n" + ) + attempt = subprocess.run( + [ + "docker", + "compose", + "run", + "--rm", + "--no-deps", + "-v", + str(altered) + ":/app/migrations:ro", + "migrate", + ], + cwd=clone, + env=env, + capture_output=True, + text=True, + ) + assert attempt.returncode != 0 + assert "Applied migration checksum mismatch" in attempt.stderr + receipt["applied_migration_checksum_guard"] = "PASS" + run( + [ + ".venv/bin/python", + "-m", + "research.query_plan", + "--output", + "evidence/clean-query-plan.json", + ], + cwd=clone, + env=env, + ) + research = json.loads( + (clone / "evidence/clean-query-plan.json").read_text() + ) + receipt["research_repeated"] = { + "result": research["result"], + "messages": research["dataset"]["messages"], + "plans": len(research["reads"]), + "restored_snapshot_equal": research["restore_verification"][ + "snapshot_equal" + ], + } + receipt["fsck"] = run( + ["git", "fsck", "--full"], cwd=clone, env=env + ) + receipt["result"] = "PASS" + finally: + assert project.startswith("mtusi-lab2-clean-") + run( + ["docker", "compose", "down", "--volumes", "--remove-orphans"], + cwd=clone, + env=env, + ) + output.parent.mkdir(parents=True, exist_ok=True) + output.write_text(json.dumps(receipt, ensure_ascii=False, indent=2) + "\n") + print(json.dumps(receipt, ensure_ascii=False, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/scripts/verify_lifecycle.py b/scripts/verify_lifecycle.py index be509c3..60f9349 100644 --- a/scripts/verify_lifecycle.py +++ b/scripts/verify_lifecycle.py @@ -64,6 +64,12 @@ def main(): with httpx.Client(base_url=BASE, trust_env=False, timeout=15) as client: user, password, session = actor(client) headers = auth(session) + expiry_query = ( + "SELECT expires_at::text FROM sessions WHERE user_id='" + + user["id"] + + "'" + ) + expires_before = sql(expiry_query) chat = client.post( "/api/v1/chats", headers=headers, @@ -80,6 +86,7 @@ def main(): command(["sh", "scripts/restart.sh"]) ready() after = instances() + assert sql(expiry_query) == expires_before for role in before: assert before[role]["started_at"] != after[role]["started_at"] assert ( @@ -87,6 +94,7 @@ def main(): == message_id ) receipt["persistence"] = { + "absolute_expiry_unchanged": True, "same_token": True, "same_message": True, "before": before, @@ -177,6 +185,18 @@ def main(): ) receipt["cache_flush_preserves_truth"] = True for mode in ["pause", "stop"]: + # Дожидаемся окончания circuit backoff и доказываем cache hit + # непосредственно перед отказом источника истины. + for _ in range(30): + assert ( + client.get("/api/v1/users/me", headers=headers).status_code + == 200 + ) + if cache("EXISTS", "user:" + user["id"]) == "1": + break + time.sleep(0.25) + else: + raise AssertionError("User cache not primed before PG fault") compose(mode, "postgres") try: started = time.perf_counter() @@ -190,6 +210,7 @@ def main(): ) assert client.get("/health/live").status_code == 200 receipt["postgres_" + mode] = { + "cache_card_present_before_failure": True, "status": result.status_code, "seconds": elapsed, "cached_identity_not_trusted": True,