test: prepare isolated clean-clone verification and stronger cache checks

This commit is contained in:
2026-11-07 08:19:20 +03:00
parent 171b6de9c8
commit 7466a09178
8 changed files with 312 additions and 2 deletions
+2 -2
View File
@@ -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
+13
View File
@@ -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"
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

+31
View File
@@ -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
1 messages position variant repeats median_sql_ms min_sql_ms max_sql_ms median_buffers
2 10 head chat_only 3 0.011 0.011 0.015 3
3 10 head keyset 3 0.006 0.006 0.008 4
4 10 middle chat_only 3 0.01 0.008 0.013 3
5 10 middle keyset 3 0.005 0.005 0.007 4
6 10 tail chat_only 3 0.011 0.01 0.011 3
7 10 tail keyset 3 0.006 0.006 0.007 4
8 100 head chat_only 3 0.038 0.034 0.039 6
9 100 head keyset 3 0.016 0.016 0.018 7
10 100 middle chat_only 3 0.03 0.026 0.034 6
11 100 middle keyset 3 0.015 0.014 0.015 5
12 100 tail chat_only 3 0.028 0.027 0.031 6
13 100 tail keyset 3 0.016 0.015 0.016 6
14 1000 head chat_only 3 0.197 0.195 0.205 25
15 1000 head keyset 3 0.018 0.016 0.02 5
16 1000 middle chat_only 3 0.152 0.136 0.158 25
17 1000 middle keyset 3 0.026 0.017 0.032 6
18 1000 tail chat_only 3 0.092 0.08 0.106 25
19 1000 tail keyset 3 0.016 0.015 0.019 6
20 10000 head chat_only 3 1.801 1.755 1.845 224
21 10000 head keyset 3 0.019 0.018 0.019 6
22 10000 middle chat_only 3 1.187 1.17 1.198 224
23 10000 middle keyset 3 0.016 0.016 0.018 5
24 10000 tail chat_only 3 0.624 0.603 0.878 224
25 10000 tail keyset 3 0.016 0.016 0.017 6
26 90000 head chat_only 3 16.501 9.887 22.44 2209
27 90000 head keyset 3 0.02 0.019 0.021 5
28 90000 middle chat_only 3 7.237 7.082 8.505 2209
29 90000 middle keyset 3 0.017 0.016 0.018 5
30 90000 tail chat_only 3 4.287 4.282 4.674 2194
31 90000 tail keyset 3 0.016 0.016 0.018 5
+20
View File
@@ -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 быстрее:
гипотеза роста именно времени записи не подтвердилась. Причина механизма
такого различия отдельно не профилировалась.
+13
View File
@@ -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 при этом не менялся.
+212
View File
@@ -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), "<clean-clone>")
.replace(str(ROOT), "<repository>")
.replace(str(Path.home()), "<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()
+21
View File
@@ -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,