test: verify persistent sessions, dependency failures and rollback

This commit is contained in:
2026-11-07 08:05:15 +03:00
parent 2f0a8672be
commit 5fb1f19de1
6 changed files with 439 additions and 2 deletions
+2 -2
View File
@@ -38,8 +38,8 @@ down:
image:
docker build --build-arg VCS_REF=$$(git rev-parse HEAD) -t "$(IMAGE)" .
lint:
$(UV) run --locked ruff format src student-tests research scripts/bootstrap.py scripts/verify_*.py
$(UV) run --locked ruff check src student-tests research scripts/bootstrap.py scripts/verify_*.py
$(UV) run --locked ruff format src student-tests research scripts/bootstrap.py scripts/stand.py scripts/verify_*.py
$(UV) run --locked ruff check src student-tests research scripts/bootstrap.py scripts/stand.py scripts/verify_*.py
test-student:
BASE_URL="$(BASE_URL)" $(UV) run --locked pytest student-tests
verify:
+8
View File
@@ -0,0 +1,8 @@
{
"date": "2026-11-07",
"source_commit": "2f0a867",
"public_smoke": "PASS: lab2 public API scenario",
"student_tests": {"passed": 77, "seconds": 91.82},
"command": "NO_PROXY=localhost,127.0.0.1 make test; pytest student-tests -q -x",
"note": "HTTP checks against real PostgreSQL/Valkey/API Compose stack; credentials remain in memory."
}
+3
View File
@@ -18,6 +18,9 @@ include = ["src/**/*.py", "student-tests/**/*.py", "research/**/*.py", "scripts/
[tool.ruff.lint]
select = ["E", "F", "I", "B", "UP"]
[tool.ruff.per-file-target-version]
"scripts/*.py" = "py39"
[tool.pytest.ini_options]
testpaths = ["student-tests"]
addopts = "-ra"
View File
+137
View File
@@ -0,0 +1,137 @@
import json
import os
import subprocess
import time
from pathlib import Path
from uuid import uuid4
import httpx
ROOT = Path(__file__).resolve().parents[1]
BASE = os.environ.get("BASE_URL", "http://127.0.0.1:8082")
def command(args, *, input=None):
result = subprocess.run(
args, cwd=ROOT, input=input, capture_output=True, text=True
)
if result.returncode:
raise RuntimeError(
"Command failed: "
+ args[0]
+ "; "
+ result.stderr.replace(str(ROOT), "<repository>")
)
return result.stdout.strip()
def compose(*args):
return command(["docker", "compose", *args])
def sql(query, *, database="messenger"):
return compose(
"exec",
"-T",
"postgres",
"psql",
"-U",
"messenger",
"-d",
database,
"-A",
"-t",
"-v",
"ON_ERROR_STOP=1",
"-c",
query,
)
def cache(command_name, *args):
script = (
'export REDISCLI_AUTH="$(cat /run/secrets/cache_password)"; '
'exec valkey-cli "$@"'
)
return compose(
"exec", "-T", "cache", "sh", "-c", script, "sh", command_name, *args
)
def ready(base=BASE, *, timeout=30):
end = time.monotonic() + timeout
with httpx.Client(base_url=base, trust_env=False, timeout=6) as client:
while time.monotonic() < end:
try:
if client.get("/health/ready").status_code == 200:
return
except httpx.HTTPError:
pass
time.sleep(0.2)
raise TimeoutError("API readiness")
def actor(client):
username = "verify_" + uuid4().hex[:20]
password = "Synthetic-" + uuid4().hex + ":🌍"
result = client.post(
"/api/v1/users",
json={
"username": username,
"display_name": "Synthetic",
"password": password,
},
)
assert result.status_code == 201
user = result.json()
session = client.post(
"/api/v1/auth/sessions", auth=httpx.BasicAuth(username, password)
)
assert session.status_code == 201
return user, password, session.json()
def auth(session):
return {"Authorization": "Bearer " + session["token"]}
def extra_api(*, ttl=3600, pool_size=1):
name = "mtusi-lab2-test-" + uuid4().hex[:10]
compose(
"run",
"-d",
"--no-deps",
"--name",
name,
"-e",
"SESSION_TTL_SECONDS=" + str(ttl),
"-e",
"DB_POOL_SIZE=" + str(pool_size),
"-p",
"127.0.0.1::8080",
"api",
)
try:
info = json.loads(command(["docker", "inspect", name]))[0]
base = (
"http://127.0.0.1:"
+ info["NetworkSettings"]["Ports"]["8080/tcp"][0]["HostPort"]
)
ready(base)
return name, base
except Exception:
command(["docker", "rm", "-f", name])
raise
def instances():
data = {}
for role in ["api", "postgres", "cache"]:
cid = compose("ps", "-q", role)
info = json.loads(command(["docker", "inspect", cid]))[0]
data[role] = {
"container": cid[:12],
"pid": info["State"]["Pid"],
"started_at": info["State"]["StartedAt"],
}
return data
+289
View File
@@ -0,0 +1,289 @@
import argparse
import hashlib
import json
import time
from datetime import UTC, datetime
from pathlib import Path
from uuid import uuid4
import httpx
from scripts.stand import (
BASE,
ROOT,
actor,
auth,
cache,
command,
compose,
extra_api,
instances,
ready,
sql,
)
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--output", required=True)
args = parser.parse_args()
output = Path(args.output)
if output.exists():
raise SystemExit("Choose new output path")
receipt = {
"date": datetime.now(UTC).isoformat(),
"commit": command(["git", "rev-parse", "HEAD"]),
"command": "python -m scripts.verify_lifecycle",
}
ready()
source_hashes = {
p.name: hashlib.sha256(p.read_bytes()).hexdigest()
for p in (ROOT / "src").glob("*.py")
}
installed_hashes = json.loads(
compose(
"exec",
"-T",
"api",
"python",
"-c",
"import hashlib,json;from pathlib import Path;"
"print(json.dumps({p.name:hashlib.sha256(p.read_bytes()).hexdigest() "
"for p in Path('/app/src').glob('*.py')}))",
)
)
assert source_hashes == installed_hashes
receipt["runtime_source_hashes_match"] = True
api_info = json.loads(
command(["docker", "inspect", compose("ps", "-q", "api")])
)[0]
receipt["image_revision"] = api_info["Config"]["Labels"][
"org.opencontainers.image.revision"
]
with httpx.Client(base_url=BASE, trust_env=False, timeout=15) as client:
user, password, session = actor(client)
headers = auth(session)
chat = client.post(
"/api/v1/chats",
headers=headers,
json={"title": "Lifecycle", "member_ids": [user["id"]]},
).json()
path = "/api/v1/chats/" + chat["id"] + "/messages"
message = client.post(
path, headers=headers, json={"text": "Synthetic retained message"}
)
assert message.status_code == 201
message_id = message.json()["id"]
before = instances()
started = time.perf_counter()
command(["sh", "scripts/restart.sh"])
ready()
after = instances()
for role in before:
assert before[role]["started_at"] != after[role]["started_at"]
assert (
client.get(path, headers=headers).json()["items"][0]["id"]
== message_id
)
receipt["persistence"] = {
"same_token": True,
"same_message": True,
"before": before,
"after": after,
"seconds": time.perf_counter() - started,
}
migration_count = sql("SELECT count(*) FROM schema_migrations")
compose("run", "--rm", "--no-deps", "migrate")
assert sql("SELECT count(*) FROM schema_migrations") == migration_count
receipt["migration_repeat"] = "PASS"
files_before = {
p.name: hashlib.sha256(p.read_bytes()).hexdigest()
for p in (ROOT / "secrets").iterdir()
}
command(["python3", "scripts/bootstrap.py"])
assert files_before == {
p.name: hashlib.sha256(p.read_bytes()).hexdigest()
for p in (ROOT / "secrets").iterdir()
}
receipt["bootstrap_preserves_secrets"] = True
dump = compose(
"exec",
"-T",
"postgres",
"pg_dump",
"-U",
"messenger",
"--data-only",
"messenger",
)
assert password not in dump and session["token"] not in dump
del dump
privacy = json.loads(
sql(
"SELECT json_build_object('argon2id',"
"password_hash LIKE '$argon2id$%','digest_bytes',"
"(SELECT min(octet_length(token_digest)) FROM sessions "
"WHERE user_id=users.id)) FROM users WHERE id='"
+ user["id"]
+ "'"
)
)
assert privacy == {"argon2id": True, "digest_bytes": 32}
receipt["credential_storage"] = {
**privacy,
"raw_password_and_token_absent_in_dump": True,
}
cache("FLUSHDB")
assert (
client.get("/api/v1/users/me", headers=headers).status_code == 200
)
info_before = cache("INFO", "stats")
for _ in range(20):
assert (
client.get("/api/v1/users/me", headers=headers).status_code
== 200
)
info_after = cache("INFO", "stats")
def hits(value):
return int(
next(
line.split(":")[1]
for line in value.splitlines()
if line.startswith("keyspace_hits:")
)
)
assert hits(info_after) - hits(info_before) >= 20
receipt["cache_hits"] = hits(info_after) - hits(info_before)
compose("stop", "cache")
try:
started = time.perf_counter()
assert (
client.get("/api/v1/users/me", headers=headers).status_code
== 200
)
receipt["cache_stopped"] = {
"status": 200,
"seconds": time.perf_counter() - started,
}
finally:
compose("up", "-d", "--no-recreate", "--wait", "cache")
cache("FLUSHDB")
assert (
client.get(path, headers=headers).json()["items"][0]["id"]
== message_id
)
receipt["cache_flush_preserves_truth"] = True
for mode in ["pause", "stop"]:
compose(mode, "postgres")
try:
started = time.perf_counter()
result = client.get("/api/v1/users/me", headers=headers)
elapsed = time.perf_counter() - started
assert result.status_code == 503 and elapsed < 6
assert result.json()["error"]["code"] == "unavailable"
assert (
result.headers["x-request-id"]
== result.json()["error"]["request_id"]
)
assert client.get("/health/live").status_code == 200
receipt["postgres_" + mode] = {
"status": result.status_code,
"seconds": elapsed,
"cached_identity_not_trusted": True,
}
finally:
if mode == "pause":
compose("unpause", "postgres")
else:
compose("up", "-d", "--no-recreate", "--wait", "postgres")
ready(timeout=45)
assert (
client.get(path, headers=headers).json()["items"][0]["id"]
== message_id
)
# Отказ посередине вставки участников откатывает весь чат.
outsider, _, _ = actor(client)
title = "rollback_" + uuid4().hex
function = "rollback_" + uuid4().hex[:8]
sql(
"CREATE FUNCTION "
+ function
+ "() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN "
+ "IF NEW.user_id='"
+ outsider["id"]
+ "'::uuid THEN RAISE EXCEPTION 'synthetic member failure'; "
+ "END IF; RETURN NEW; END $$; CREATE TRIGGER "
+ function
+ " BEFORE INSERT ON members FOR EACH ROW EXECUTE FUNCTION "
+ function
+ "()"
)
try:
result = client.post(
"/api/v1/chats",
headers=headers,
json={
"title": title,
"member_ids": [user["id"], outsider["id"]],
},
)
assert result.status_code == 500
assert (
sql("SELECT count(*) FROM chats WHERE title='" + title + "'")
== "0"
)
receipt["chat_transaction_rollback"] = {
"injected_failure_status": 500,
"remaining_chat_rows": 0,
}
finally:
sql(
"DROP TRIGGER "
+ function
+ " ON members; DROP FUNCTION "
+ function
+ "()"
)
# Короткий TTL — на отдельном API; обычный smoke сохраняет TTL3600.
name, base = extra_api(ttl=2)
try:
with httpx.Client(
base_url=base, trust_env=False, timeout=15
) as short:
_, _, expiring = actor(short)
assert (
short.get(
"/api/v1/users/me", headers=auth(expiring)
).status_code
== 200
)
time.sleep(2.2)
assert (
short.get(
"/api/v1/users/me", headers=auth(expiring)
).status_code
== 401
)
receipt["expiry"] = {"ttl_seconds": 2, "status_after_expiry": 401}
finally:
command(["docker", "rm", "-f", name])
assert (
client.delete(
"/api/v1/auth/sessions/current", headers=headers
).status_code
== 204
)
assert (
client.get("/api/v1/users/me", headers=headers).status_code == 401
)
receipt["logout_after_cache_hit"] = "PASS"
receipt["result"] = "PASS"
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()