Files
mtusi2026lab2/student-tests/db_checks.py
T
2026-09-30 12:13:29 +03:00

314 lines
10 KiB
Python

"""Direct PostgreSQL checks for lab2 level 4.
Run inside the compose network (no DB port is published):
docker compose --profile tools run --rm db_checks
1. Rollback of the composite "create chat + members" operation, using the
application's own repository code.
2. EXPLAIN (ANALYZE, BUFFERS) of the message history page on a chat with
>= 10 000 messages: first page, deep keyset page, OFFSET for comparison
and the keyset page with the index dropped inside a rolled back
transaction.
Only synthetic data is created (user "explain_bench").
"""
from __future__ import annotations
import asyncio
import os
import re
import sys
from pathlib import Path
from uuid import uuid4
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
os.environ.setdefault("SESSION_STORE", "postgres")
from sqlalchemy import text # noqa: E402
from app import repositories # noqa: E402
from app.db import SessionLocal, engine # noqa: E402
BENCH_USERNAME = "explain_bench"
BENCH_CHATS = 5
MESSAGES_PER_CHAT = 10_000
PAGE = 50
DEEP_POSITION = 9_000
failures: list[str] = []
def check(condition: bool, message: str) -> None:
print(("PASS: " if condition else "FAIL: ") + message)
if not condition:
failures.append(message)
async def check_chat_rollback() -> None:
print("== rollback of composite chat creation")
title = f"rollback-{uuid4().hex}"
async with SessionLocal() as db:
user_id = (
await db.execute(text("SELECT id FROM users LIMIT 1"))
).scalar_one_or_none()
if user_id is None:
user_id = uuid4()
await db.execute(
text(
"INSERT INTO users (id, username, display_name, password_hash) "
"VALUES (:id, :u, 'Rollback', 'not-a-login-hash')"
),
{"id": user_id, "u": f"rb_{uuid4().hex[:20]}"},
)
await db.commit()
missing_member = uuid4()
failed = False
try:
# Chat INSERT succeeds, the second member violates the FK.
await repositories.create_chat_with_members(
db,
title=title,
member_ids=[user_id, missing_member],
)
except Exception as exc: # noqa: BLE001
failed = True
print(f"expected failure: {type(exc).__name__}")
check(failed, "create_chat_with_members fails on a missing member")
async with SessionLocal() as db:
chats = (
await db.execute(
text("SELECT count(*) FROM chats WHERE title = :title"),
{"title": title},
)
).scalar_one()
orphans = (
await db.execute(
text(
"SELECT count(*) FROM chats c "
"WHERE NOT EXISTS (SELECT 1 FROM chat_members m "
"WHERE m.chat_id = c.id)"
)
)
).scalar_one()
check(chats == 0, "chat row was rolled back together with members")
check(orphans == 0, "no chats without members exist in the database")
async def seed_history() -> str:
async with SessionLocal() as db:
user_id = (
await db.execute(
text("SELECT id FROM users WHERE username = :u"),
{"u": BENCH_USERNAME},
)
).scalar_one_or_none()
if user_id is None:
user_id = uuid4()
await db.execute(
text(
"INSERT INTO users (id, username, display_name, password_hash) "
"VALUES (:id, :u, 'Explain Bench', 'not-a-login-hash')"
),
{"id": user_id, "u": BENCH_USERNAME},
)
chat_ids = list(
(
await db.execute(
text(
"SELECT c.id FROM chats c JOIN chat_members m "
"ON m.chat_id = c.id WHERE m.user_id = :u "
"AND c.title LIKE 'explain-bench-%' ORDER BY c.title"
),
{"u": user_id},
)
).scalars()
)
for index in range(len(chat_ids), BENCH_CHATS):
chat_id = uuid4()
await db.execute(
text("INSERT INTO chats (id, title) VALUES (:id, :t)"),
{"id": chat_id, "t": f"explain-bench-{index}"},
)
await db.execute(
text(
"INSERT INTO chat_members (chat_id, user_id) "
"VALUES (:c, :u)"
),
{"c": chat_id, "u": user_id},
)
chat_ids.append(chat_id)
for chat_id in chat_ids:
existing = (
await db.execute(
text("SELECT count(*) FROM messages WHERE chat_id = :c"),
{"c": chat_id},
)
).scalar_one()
missing = MESSAGES_PER_CHAT - existing
if missing > 0:
# Several messages share one timestamp to exercise the
# (created_at, id) tie-breaker.
await db.execute(
text(
"""
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT gen_random_uuid(), :c, :u,
'synthetic message ' || g,
now() - interval '1 day' + (g / 3) * interval '1 second'
FROM generate_series(1, :n) AS g
"""
),
{"c": chat_id, "u": user_id, "n": missing},
)
await db.commit()
async with engine.connect() as connection:
await connection.execute(text("ANALYZE messages"))
await connection.commit()
return str(chat_ids[0])
async def explain(connection, title: str, sql: str, params: dict) -> str:
rows = await connection.execute(
text("EXPLAIN (ANALYZE, BUFFERS, COSTS OFF) " + sql),
params,
)
plan = "\n".join(row[0] for row in rows)
print(f"\n-- {title}\n{plan}")
return plan
def shared_buffers(plan: str) -> int:
first = re.search(r"Buffers: shared ([^\n]+)", plan)
if not first:
return 0
return sum(int(value) for value in re.findall(r"=(\d+)", first.group(1)))
async def check_history_plan() -> None:
print("\n== EXPLAIN for message history pagination")
chat_id = await seed_history()
async with engine.connect() as connection:
total = (
await connection.execute(text("SELECT count(*) FROM messages"))
).scalar_one()
in_chat = (
await connection.execute(
text("SELECT count(*) FROM messages WHERE chat_id = :c"),
{"c": chat_id},
)
).scalar_one()
print(f"messages total: {total}; in explained chat: {in_chat}")
check(in_chat >= 10_000, "explained chat has >= 10 000 messages")
cursor = (
await connection.execute(
text(
"SELECT created_at, id FROM messages WHERE chat_id = :c "
"ORDER BY created_at, id OFFSET :o LIMIT 1"
),
{"c": chat_id, "o": DEEP_POSITION},
)
).one()
params = {
"c": chat_id,
"ca": cursor.created_at,
"ci": cursor.id,
"l": PAGE + 1,
}
# Same SQL as repositories.list_messages_keyset.
first_sql = (
"SELECT id, chat_id, sender_id, text, created_at FROM messages "
"WHERE chat_id = :c ORDER BY created_at ASC, id ASC LIMIT :l"
)
keyset_sql = (
"SELECT id, chat_id, sender_id, text, created_at FROM messages "
"WHERE chat_id = :c AND (created_at, id) > (:ca, :ci) "
"ORDER BY created_at ASC, id ASC LIMIT :l"
)
offset_sql = (
"SELECT id, chat_id, sender_id, text, created_at FROM messages "
"WHERE chat_id = :c ORDER BY created_at ASC, id ASC "
f"OFFSET {DEEP_POSITION} LIMIT :l"
)
first = await explain(connection, "first page", first_sql, params)
keyset = await explain(
connection, f"keyset page after position {DEEP_POSITION}",
keyset_sql, params,
)
offset = await explain(
connection, f"OFFSET {DEEP_POSITION} (not used by the API)",
offset_sql, params,
)
# Close the autobegun read transaction, then drop the index only
# inside a transaction that is always rolled back.
await connection.rollback()
transaction = await connection.begin()
await connection.execute(text("SET LOCAL lock_timeout = '2s'"))
await connection.execute(text("DROP INDEX messages_keyset_idx"))
no_index = await explain(
connection, "keyset page WITHOUT messages_keyset_idx (rolled back)",
keyset_sql, params,
)
await transaction.rollback()
check(
"Index Scan using messages_keyset_idx" in first
and "Sort" not in first,
"first page reads the index in order, no Sort",
)
check(
"Index Scan using messages_keyset_idx" in keyset
and re.search(r"Index Cond: .*created_at", keyset) is not None
and "Sort" not in keyset,
"keyset cursor is an Index Cond, not a filter over the history",
)
check(
shared_buffers(keyset) < shared_buffers(offset),
f"keyset deep page touches fewer buffers than OFFSET "
f"({shared_buffers(keyset)} < {shared_buffers(offset)})",
)
check(
shared_buffers(keyset) < shared_buffers(no_index),
f"index reduces buffers for the deep page "
f"({shared_buffers(keyset)} < {shared_buffers(no_index)})",
)
async def main() -> int:
try:
await check_chat_rollback()
await check_history_plan()
finally:
await engine.dispose()
if failures:
print(f"\nFAIL: {len(failures)} check(s) failed")
return 1
print("\nPASS: db checks")
return 0
if __name__ == "__main__":
sys.exit(asyncio.run(main()))