Files
mtusi2026lab2/student-tests/history_bench.py
T
zemilesandClaude Opus 5.5 ffb98242ff ЛР 2: PostgreSQL, Bearer-сессии и кэш сессий в Valkey (на 4)
- Перенесён минимум lab1; переход 1 → 2: password при регистрации,
  Basic только на POST /auth/sessions, Bearer вместо X-User-Id, logout.
- PostgreSQL — источник истины: users, chats, chat_members, messages,
  sessions; миграции с PK/FK/UNIQUE/CHECK и индексами, атомарное
  создание чата, scrypt для паролей, SHA-256 токенов в БД.
- Valkey — кэш проверенных сессий с TTL, tombstone при logout,
  обход кэша и окно недоверия при отказе.
- Ограниченные пулы и таймауты PostgreSQL/Valkey, 503 при отказе БД.
- compose.yaml с Docker secrets и именованным томом, restart hook,
  собственные тесты, EXPLAIN на 110 тыс. сообщений, замер пользы кэша,
  заполненный REPORT.md и evidence/.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 02:15:02 +03:00

157 lines
8.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Обоснование индекса истории: EXPLAIN (ANALYZE, BUFFERS) на большом объёме + замер пагинации через API.
python3 student-tests/history_bench.py [--big 100000] [--small-chats 20] [--small-size 500]
1. Через API создаёт двух синтетических пользователей, большой чат и N маленьких чатов.
2. Через psql (docker compose exec postgres) заливает сообщения: generate_series, одна транзакция.
Неравномерно: один чат на --big сообщений, остальные по --small-size.
3. Печатает EXPLAIN (ANALYZE, BUFFERS) ровно того SQL, который выполняет приложение:
первая страница, «глубокая» страница по keyset-курсору, та же глубина через OFFSET;
затем те же запросы БЕЗ индекса messages_chat_order_idx (DROP INDEX внутри BEGIN … ROLLBACK).
4. Проходит всю историю большого чата через API (limit=100) и сравнивает задержку первых и
последних страниц: при keyset-пагинации она не растёт с номером страницы.
Каждый запуск добавляет синтетические данные в учебную БД (API курса не удаляет сообщения).
"""
import argparse
import base64
import json
import statistics
import subprocess
import time
import urllib.parse
import urllib.request
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://localhost:8080")
parser.add_argument("--big", type=int, default=100_000)
parser.add_argument("--small-chats", type=int, default=20)
parser.add_argument("--small-size", type=int, default=500)
args = parser.parse_args()
BASE = args.base_url.rstrip("/")
def api(method, path, body=None, headers=None):
h = dict(headers or {})
data = None
if body is not None:
data = json.dumps(body).encode()
h["Content-Type"] = "application/json"
req = urllib.request.Request(BASE + path, data=data, headers=h, method=method)
with urllib.request.urlopen(req, timeout=30) as r:
raw = r.read()
return json.loads(raw) if raw else None
def psql(sql, tuples_only=False):
cmd = ["docker", "compose", "--env-file", str(ROOT / ".env"), "exec", "-T", "postgres",
"psql", "-U", "messenger", "-d", "messenger", "-X", "-q", "-v", "ON_ERROR_STOP=1"]
if tuples_only:
cmd += ["-A", "-t"]
out = subprocess.run(cmd, input=sql, cwd=ROOT, check=True, capture_output=True, text=True)
return out.stdout.strip()
def user(label):
name = "bench_%s_%s" % (label, uuid.uuid4().hex[:8])
pw = "T3st-" + uuid.uuid4().hex
u = api("POST", "/api/v1/users", {"username": name, "display_name": "Bench " + label, "password": pw})
cred = base64.b64encode((name + ":" + pw).encode()).decode()
s = api("POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + cred})
return u, {"Authorization": "Bearer " + s["token"]}
def section(title):
print("\n" + "=" * 100 + "\n" + title + "\n" + "=" * 100)
# ---------- 1. данные ----------
a, ha = user("a")
b, _ = user("b")
big = api("POST", "/api/v1/chats", {"title": "Большой чат", "member_ids": [a["id"], b["id"]]}, ha)
small = [api("POST", "/api/v1/chats", {"title": "Малый %d" % i, "member_ids": [a["id"], b["id"]]}, ha)
for i in range(args.small_chats)]
section("1. Заливка данных")
started = time.monotonic()
values = ",".join("('%s'::uuid)" % c["id"] for c in small) # UUID получены от нашего API
psql("""
BEGIN;
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT gen_random_uuid(), '{big}'::uuid,
CASE WHEN n % 2 = 0 THEN '{a}'::uuid ELSE '{b}'::uuid END,
'synthetic message #' || n || ' ' || repeat('x', (n * 7919) % 200),
timestamptz '2026-01-01 00:00:00+00' + n * interval '1 millisecond'
FROM generate_series(1, {big_n}) AS n;
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT gen_random_uuid(), c.id, '{a}'::uuid, 'small chat message #' || n,
timestamptz '2026-01-01 00:00:00+00' + n * interval '1 millisecond'
FROM (VALUES {values}) AS c(id), generate_series(1, {small_n}) AS n;
COMMIT;
ANALYZE messages;
""".format(big=big["id"], a=a["id"], b=b["id"], big_n=args.big, small_n=args.small_size, values=values))
print("залито за %.1f с" % (time.monotonic() - started))
print(psql("""SELECT count(*) AS messages_total,
count(DISTINCT chat_id) AS chats_with_messages,
(SELECT count(*) FROM messages WHERE chat_id = '{big}') AS in_big_chat,
pg_size_pretty(pg_relation_size('messages')) AS table_size,
pg_size_pretty(pg_relation_size('messages_chat_order_idx')) AS index_size
FROM messages""".format(big=big["id"])))
# ---------- 2. EXPLAIN ----------
deep_offset = int(args.big * 0.9)
cur_ts, cur_id = psql("""SELECT created_at, id FROM messages WHERE chat_id = '{big}'
ORDER BY created_at, id OFFSET {off} LIMIT 1""".format(
big=big["id"], off=deep_offset - 1), tuples_only=True).split("|")
COLS = "SELECT id, chat_id, sender_id, text, created_at FROM messages"
Q_FIRST = COLS + " WHERE chat_id = '{c}' ORDER BY created_at, id LIMIT 51".format(c=big["id"])
Q_KEYSET = (COLS + " WHERE chat_id = '{c}' AND (created_at, id) > ('{t}', '{i}'::uuid)"
" ORDER BY created_at, id LIMIT 51").format(c=big["id"], t=cur_ts, i=cur_id)
Q_OFFSET = (COLS + " WHERE chat_id = '{c}' ORDER BY created_at, id OFFSET {o} LIMIT 51").format(
c=big["id"], o=deep_offset)
EXPLAIN = "EXPLAIN (ANALYZE, BUFFERS, COSTS OFF) "
for title, q in [
("2a. С индексом: первая страница (как в приложении, limit=50 → LIMIT 51)", Q_FIRST),
("2b. С индексом: страница после %d-го сообщения, keyset-курсор (как в приложении)" % deep_offset, Q_KEYSET),
("2c. Для сравнения: та же глубина через OFFSET %d (так приложение НЕ делает)" % deep_offset, Q_OFFSET)]:
section(title)
print(q)
print(psql(EXPLAIN + q))
section("2d. БЕЗ индекса messages_chat_order_idx (DROP INDEX внутри BEGIN … ROLLBACK, данные не меняются)")
print(psql("BEGIN;\nDROP INDEX messages_chat_order_idx;\n"
"\\echo '--- первая страница без индекса'\n" + EXPLAIN + Q_FIRST + ";\n"
"\\echo '--- keyset-страница без индекса'\n" + EXPLAIN + Q_KEYSET + ";\nROLLBACK;"))
print(psql("SELECT indexname FROM pg_indexes WHERE tablename = 'messages' ORDER BY 1"))
# ---------- 3. пагинация через API ----------
section("3. Полный обход истории большого чата через API (limit=100)")
path = "/api/v1/chats/%s/messages?limit=100" % big["id"]
latencies, total, cursor = [], 0, None
while True:
url = path + ("&cursor=" + urllib.parse.quote(cursor, safe="") if cursor else "")
t0 = time.perf_counter()
page = api("GET", url, headers=ha)
latencies.append((time.perf_counter() - t0) * 1000)
total += len(page["items"])
cursor = page["next_cursor"]
if not cursor:
break
first, last = latencies[1:21], latencies[-20:] # первая страница — прогрев
print(json.dumps({
"pages": len(latencies), "messages_read": total, "expected": args.big,
"first_20_pages_median_ms": round(statistics.median(first), 2),
"last_20_pages_median_ms": round(statistics.median(last), 2),
"all_pages_p50_ms": round(statistics.median(latencies), 2),
"all_pages_p95_ms": round(sorted(latencies)[int(len(latencies) * 0.95) - 1], 2),
"all_pages_max_ms": round(max(latencies), 2),
}, ensure_ascii=False, indent=1))
assert total == args.big, "пагинация потеряла или задублировала сообщения"
print("PASS: все %d сообщений прочитаны без потерь и повторов" % total)