bench: трек 2 — планы запросов, стоимость записи, backup/restore со сверкой

plans.py: 121 120 сообщений (60k/15k/2k/80), 3 индекса x keyset/OFFSET x 3 размера
чата, pgbench в отдельном контейнере; WAL на вставку детерминированно.
backup_restore.py: pg_dump живой БД во время записи через API, восстановление в
новый контейнер и volume, сверка MD5 по чатам, API на восстановленной БД.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alexey Bodanyuk
2026-10-12 20:08:13 +03:00
co-authored by Claude Opus 5.5
parent a8c6af8c7d
commit eb92e8e91e
21 changed files with 1256 additions and 0 deletions
+281
View File
@@ -0,0 +1,281 @@
#!/usr/bin/env python3
"""Track 2, part 2: backup -> restore into NEW storage -> reconciliation, with RPO/RTO.
python bench/track2/backup_restore.py --repeats 3 # stand must be running
1. The live stand database gets (once) >= 100 000 synthetic messages with uneven chat sizes.
2. A writer sends messages through the real API (POST /messages) the whole time.
3. `pg_dump -Fc` of the live database (one consistent MVCC snapshot) to ./backups (git-ignored).
4. Restore into NEW storage: a fresh PostgreSQL container with a NEW volume (`pg_restore -j 2`).
5. Reconciliation source vs restored: row counts, per-chat MD5 of every message
(id, created_at, text), the first/last 50 messages of the biggest chat, schema_migrations.
Writer messages: the restored ones must be an exact PREFIX of the confirmed ones
(consistent snapshot, no torn state); the rest is the data-loss window (RPO).
6. The app itself is started against the restored database and reads the writer's chat
with a fresh login.
Results: evidence/track2/backup.json. No passwords or tokens are written.
"""
from __future__ import annotations
import argparse
import base64
import datetime as dt
import json
import secrets
import subprocess
import sys
import threading
import time
import uuid
from pathlib import Path
import httpx2 as httpx
ROOT = Path(__file__).resolve().parents[2]
IMAGE = "postgres:18.6-bookworm@sha256:afc7e2d441324c0388fa80c3d24f733b4194a4eb7f47dd8ee2b08eb1a24a647c"
APP_IMAGE = "mtusi-messenger:lab2"
RESTORE_PG, RESTORE_API, RESTORE_NET, RESTORE_VOL = "mtusi-restore-pg", "mtusi-restore-api", "mtusi-restore-net", "mtusi-restore-pgdata"
BASE = "http://127.0.0.1:8080"
SEED_USER = "00000000-0000-4000-8000-0000000c0001"
SEED_LIVE = f"""
\\set ON_ERROR_STOP on
BEGIN;
INSERT INTO users (id, username, display_name, password_hash)
VALUES ('{SEED_USER}', 'track2_live', convert_to('Track 2 live', 'UTF8'), 'not-a-login') ON CONFLICT DO NOTHING;
CREATE TEMP TABLE sizes AS
SELECT n, CASE WHEN n = 1 THEN 60000 WHEN n <= 3 THEN 15000 WHEN n <= 11 THEN 2000 ELSE 80 END AS size,
md5('track2-live-chat-' || n)::uuid AS chat_id
FROM generate_series(1::int, 200::int) AS n;
INSERT INTO chats (id, title, created_by, created_at)
SELECT chat_id, convert_to('track2 live ' || n, 'UTF8'), '{SEED_USER}', timestamptz '2026-02-01 00:00:00+00'
FROM sizes ON CONFLICT DO NOTHING;
INSERT INTO chat_members (chat_id, user_id, position, chat_created_at)
SELECT chat_id, '{SEED_USER}', 0, timestamptz '2026-02-01 00:00:00+00' FROM sizes ON CONFLICT DO NOTHING;
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT gen_random_uuid(), s.chat_id, '{SEED_USER}',
convert_to(left(repeat('сообщение ', 40), 5 + (random() * 195)::int), 'UTF8'),
timestamptz '2026-02-01 00:00:00+00' + g * interval '1 second'
FROM sizes s CROSS JOIN LATERAL generate_series(1::int, s.size) AS g
WHERE NOT EXISTS (SELECT 1 FROM messages m WHERE m.chat_id = s.chat_id);
UPDATE chats c SET last_message_at = m.mx FROM (SELECT chat_id, max(created_at) mx FROM messages GROUP BY chat_id) m
WHERE m.chat_id = c.id AND c.created_by = '{SEED_USER}';
COMMIT;
"""
RECONCILE_SQL = """
\\pset footer off
SELECT 'count:' || t || ':' || n FROM (
SELECT 'users' t, count(*) n FROM users UNION ALL SELECT 'chats', count(*) FROM chats
UNION ALL SELECT 'chat_members', count(*) FROM chat_members UNION ALL SELECT 'messages', count(*) FROM messages
UNION ALL SELECT 'schema_migrations', count(*) FROM schema_migrations) x ORDER BY t;
SELECT 'chat:' || chat_id || ':' || count(*) || ':' ||
md5(string_agg(id::text || '|' || created_at::text || '|' || encode(text, 'hex'), ',' ORDER BY created_at, id))
FROM messages WHERE chat_id <> '{writer_chat}' GROUP BY chat_id ORDER BY chat_id;
SELECT 'big:' || md5(string_agg(x, ',')) FROM (
(SELECT id::text || '|' || encode(text, 'hex') AS x FROM messages WHERE chat_id = md5('track2-live-chat-1')::uuid
ORDER BY created_at, id LIMIT 50)
UNION ALL
(SELECT * FROM (SELECT id::text || '|' || encode(text, 'hex') FROM messages WHERE chat_id = md5('track2-live-chat-1')::uuid
ORDER BY created_at DESC, id DESC LIMIT 50) y)) z;
SELECT 'mig:' || string_agg(version || '=' || checksum, ',' ORDER BY version) FROM schema_migrations;
SELECT 'idx:' || string_agg(indexname, ',' ORDER BY indexname) FROM pg_indexes WHERE schemaname = 'public';
SELECT 'writer:' || string_agg(id::text, ',' ORDER BY created_at, id) FROM messages WHERE chat_id = '{writer_chat}';
"""
def sh(args, *, input_bytes: bytes | None = None, check: bool = True, timeout: float = 600) -> subprocess.CompletedProcess:
result = subprocess.run(args, input=input_bytes, capture_output=True, timeout=timeout, cwd=ROOT)
if check and result.returncode != 0:
raise RuntimeError(f"{' '.join(map(str, args[:5]))}: {result.stderr.decode(errors='replace')[-1500:]}")
return result
def live_psql(sql: str) -> str:
return sh(["docker", "compose", "exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger",
"-X", "-q", "-At", "-f", "-"], input_bytes=sql.encode()).stdout.decode().strip()
def restored_psql(sql: str) -> str:
return sh(["docker", "exec", "-i", RESTORE_PG, "psql", "-U", "messenger", "-d", "messenger",
"-X", "-q", "-At", "-f", "-"], input_bytes=sql.encode()).stdout.decode().strip()
def parse(text: str) -> dict:
out: dict = {"count": {}, "chat": {}}
for line in text.splitlines():
kind, _, rest = line.partition(":")
if kind == "count":
name, _, value = rest.partition(":")
out["count"][name] = int(value)
elif kind == "chat":
chat, _, digest = rest.partition(":")
out["chat"][chat] = digest
else:
out[kind] = rest
return out
class Writer(threading.Thread):
"""Real API traffic during the backup: one message every ~10 ms, confirmations recorded."""
def __init__(self):
super().__init__(daemon=True)
self.client = httpx.Client(base_url=BASE, timeout=10)
self.username = "writer_" + uuid.uuid4().hex[:10]
self.password = secrets.token_urlsafe(16)
user = self.client.post("/api/v1/users", json={"username": self.username, "display_name": "Writer",
"password": self.password}).json()
auth = base64.b64encode(f"{self.username}:{self.password}".encode()).decode()
token = self.client.post("/api/v1/auth/sessions", headers={"Authorization": "Basic " + auth}).json()["token"]
self.headers = {"Authorization": "Bearer " + token}
self.chat = self.client.post("/api/v1/chats", headers=self.headers,
json={"title": "writer", "member_ids": [user["id"]]}).json()["id"]
self.confirmed: list[tuple[str, str]] = []
self.errors = 0
self.stop = threading.Event()
def run(self) -> None:
n = 0
while not self.stop.is_set():
r = self.client.post(f"/api/v1/chats/{self.chat}/messages", headers=self.headers, json={"text": f"w{n}"})
if r.status_code == 201:
self.confirmed.append((r.json()["id"], r.json()["created_at"]))
else:
self.errors += 1
n += 1
time.sleep(0.01)
def new_storage() -> str:
for cmd in (["docker", "rm", "-f", "-v", RESTORE_API, RESTORE_PG], ["docker", "volume", "rm", "-f", RESTORE_VOL],
["docker", "network", "rm", RESTORE_NET]):
sh(cmd, check=False)
sh(["docker", "network", "create", RESTORE_NET])
password = secrets.token_urlsafe(18)
sh(["docker", "run", "-d", "--name", RESTORE_PG, "--network", RESTORE_NET, "--cpus", "2", "--memory", "2g",
"-e", f"POSTGRES_PASSWORD={password}", "-e", "POSTGRES_USER=messenger", "-e", "POSTGRES_DB=messenger",
"-v", f"{RESTORE_VOL}:/var/lib/postgresql", IMAGE])
for _ in range(120):
if sh(["docker", "exec", RESTORE_PG, "pg_isready", "-U", "messenger", "-d", "messenger", "-q"], check=False).returncode == 0:
time.sleep(1)
return password
time.sleep(0.5)
raise RuntimeError("restore PostgreSQL did not start")
def app_on_restored(password: str, writer: Writer, expected_ids: list[str]) -> dict:
"""Run our API image against the restored DB (sessions in PostgreSQL) and read the writer chat."""
url = f"postgresql://messenger:{password}@{RESTORE_PG}:5432/messenger"
sh(["docker", "run", "-d", "--name", RESTORE_API, "--network", RESTORE_NET, "-p", "127.0.0.1:18090:8080",
"-e", "SESSION_STORE=postgres", "-e", f"DATABASE_URL={url}", "-e", "DATABASE_URL_FILE=", APP_IMAGE])
client = httpx.Client(base_url="http://127.0.0.1:18090", timeout=10)
for _ in range(60):
try:
if client.get("/health/ready").status_code == 200:
break
except httpx.HTTPError:
pass
time.sleep(0.5)
auth = base64.b64encode(f"{writer.username}:{writer.password}".encode()).decode()
token = client.post("/api/v1/auth/sessions", headers={"Authorization": "Basic " + auth}).json()["token"]
seen, cursor = [], None
while True:
q = "?limit=100" + (f"&cursor={cursor}" if cursor else "")
page = client.get(f"/api/v1/chats/{writer.chat}/messages{q}", headers={"Authorization": "Bearer " + token}).json()
seen += [m["id"] for m in page["items"]]
cursor = page["next_cursor"]
if not cursor:
break
sh(["docker", "rm", "-f", RESTORE_API], check=False)
return {"login_ok": True, "history_via_api_equals_restored": seen == expected_ids, "messages_read": len(seen)}
def one_round(round_no: int, backups: Path) -> dict:
writer = Writer()
writer.start()
time.sleep(2) # writer is in steady state before the backup starts
dump_file = backups / f"messenger-round{round_no}.dump"
started_wall = dt.datetime.now(dt.timezone.utc)
started = time.monotonic()
with dump_file.open("wb") as f:
proc = subprocess.run(["docker", "compose", "exec", "-T", "postgres", "pg_dump", "-U", "messenger", "-d", "messenger",
"-Fc", "-Z", "6"], stdout=f, stderr=subprocess.PIPE, cwd=ROOT, timeout=600)
if proc.returncode != 0:
raise RuntimeError(proc.stderr.decode()[-1000:])
dump_s = time.monotonic() - started
time.sleep(2) # keep writing after the dump: these confirmed messages are not in the backup
writer.stop.set()
writer.join()
source = parse(live_psql(RECONCILE_SQL.format(writer_chat=writer.chat)))
password = new_storage()
started = time.monotonic()
sh(["docker", "exec", "-i", RESTORE_PG, "sh", "-c", "cat > /tmp/backup.dump"], input_bytes=dump_file.read_bytes())
sh(["docker", "exec", RESTORE_PG, "pg_restore", "-U", "messenger", "-d", "messenger", "--no-owner", "-j", "2",
"--exit-on-error", "/tmp/backup.dump"])
restore_s = time.monotonic() - started
started = time.monotonic()
restored_psql("ANALYZE;")
analyze_s = time.monotonic() - started
restored = parse(restored_psql(RECONCILE_SQL.format(writer_chat=writer.chat)))
confirmed_ids = [m[0] for m in writer.confirmed]
restored_writer = restored.get("writer", "").split(",") if restored.get("writer") else []
prefix_ok = restored_writer == confirmed_ids[:len(restored_writer)]
lost = confirmed_ids[len(restored_writer):]
last_in_backup = writer.confirmed[len(restored_writer) - 1][1] if restored_writer else None
first_lost = writer.confirmed[len(restored_writer)][1] if lost else None
other_counts_equal = {k: source["count"][k] == restored["count"][k] for k in source["count"] if k != "messages"}
api_check = app_on_restored(password, writer, restored_writer)
result = {
"round": round_no, "backup_started_utc": started_wall.isoformat(timespec="seconds"),
"dump_seconds": round(dump_s, 2), "dump_bytes": dump_file.stat().st_size,
"restore_seconds": round(restore_s, 2), "analyze_seconds": round(analyze_s, 2),
"rto_seconds_restore_plus_analyze": round(restore_s + analyze_s, 2),
"source_counts_after_writer_stopped": source["count"], "restored_counts": restored["count"],
"messages_in_restored": restored["count"]["messages"],
"per_chat_md5_equal": source["chat"] == restored["chat"], "chats_compared": len(source["chat"]),
"big_chat_first_last_50_equal": source["big"] == restored["big"],
"schema_migrations_equal": source["mig"] == restored["mig"], "indexes_equal": source["idx"] == restored["idx"],
"other_table_counts_equal": other_counts_equal,
"writer": {"confirmed": len(confirmed_ids), "errors": writer.errors, "in_backup": len(restored_writer),
"restored_is_exact_prefix": prefix_ok, "lost_confirmed_after_snapshot": len(lost),
"last_message_in_backup_at": last_in_backup, "first_lost_message_at": first_lost},
"app_on_restored_db": api_check,
}
result["reconciled"] = bool(result["per_chat_md5_equal"] and result["big_chat_first_last_50_equal"]
and result["schema_migrations_equal"] and result["indexes_equal"]
and all(other_counts_equal.values()) and prefix_ok
and api_check["history_via_api_equals_restored"])
return result
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--repeats", type=int, default=3)
parser.add_argument("--out", default=str(ROOT / "evidence/track2/backup.json"))
args = parser.parse_args()
backups = ROOT / "backups"
backups.mkdir(exist_ok=True)
live_psql(SEED_LIVE)
rounds = []
try:
for i in range(1, args.repeats + 1):
r = one_round(i, backups)
rounds.append(r)
print(json.dumps({k: r[k] for k in ("round", "dump_seconds", "dump_bytes", "restore_seconds", "messages_in_restored",
"reconciled")} | {"writer": r["writer"]}, ensure_ascii=False), flush=True)
finally:
for cmd in (["docker", "rm", "-f", "-v", RESTORE_API, RESTORE_PG], ["docker", "volume", "rm", "-f", RESTORE_VOL],
["docker", "network", "rm", RESTORE_NET]):
sh(cmd, check=False)
Path(args.out).parent.mkdir(parents=True, exist_ok=True)
Path(args.out).write_text(json.dumps({"image": IMAGE, "rounds": rounds}, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8", newline="\n")
print("done:", args.out)
return 0 if all(r["reconciled"] for r in rounds) else 1
if __name__ == "__main__":
sys.exit(main())
+286
View File
@@ -0,0 +1,286 @@
#!/usr/bin/env python3
"""Track 2, part 1: query plans and write cost on >= 100 000 messages with uneven chat sizes.
python bench/track2/plans.py # ~20 min, results in evidence/track2/
An ISOLATED PostgreSQL container (same pinned image as compose.yaml, --cpus 2 --memory 2g,
no published ports) gets the schema from migrations/*.sql and a deterministic synthetic
dataset: 1 chat x 60 000, 2 x 15 000, 8 x 2 000, 189 x 80 messages = 121 120 messages,
texts of 10..400 bytes. The live stand is not touched: indexes are dropped and created
here freely.
For every index variant the script runs pgbench (prepared statements, like the driver):
* reads — one history page (LIMIT 51) after a RANDOM position of a big/medium/small chat,
keyset query (the app's SQL) vs OFFSET; 4 clients;
* writes — the app's message transaction (UPDATE chats ... RETURNING + INSERT); 8 clients;
and records TPS, p50/p95/p99 latency, WAL bytes per insert, index/table sizes, EXPLAIN.
"""
from __future__ import annotations
import argparse
import csv
import json
import math
import platform
import secrets
import statistics
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "src"))
from messenger.repo import HISTORY_AFTER # noqa: E402 (the app's real statement)
IMAGE = "postgres:18.6-bookworm@sha256:afc7e2d441324c0388fa80c3d24f733b4194a4eb7f47dd8ee2b08eb1a24a647c"
NAME = "mtusi-track2-pg"
CLIENT = "mtusi-track2-client" # pgbench runs here: it must not eat the server's CPU quota
PASSWORD = secrets.token_urlsafe(16) # throwaway, never printed
USER_ID = "00000000-0000-4000-8000-0000000b0001"
VARIANTS = {
# name: (DDL of secondary indexes on messages, description)
"keyset_index": (["CREATE INDEX messages_chat_keyset ON messages (chat_id, created_at, id)"],
"(chat_id, created_at, id) — used by the app"),
"chat_id_index": (["CREATE INDEX messages_chat_only ON messages (chat_id)"],
"(chat_id) only"),
"no_index": ([], "primary key only"),
"keyset_plus_sender": (["CREATE INDEX messages_chat_keyset ON messages (chat_id, created_at, id)",
"CREATE INDEX messages_sender_time ON messages (sender_id, created_at)"],
"app index + a second index (sender_id, created_at)"),
}
READ_VARIANTS = ["keyset_index", "chat_id_index", "no_index"]
WRITE_VARIANTS = ["no_index", "keyset_index", "keyset_plus_sender"]
KINDS = {"big": 60_000, "medium": 15_000, "small": 80}
def sh(args: list[str], input_text: str | None = None, check: bool = True) -> str:
result = subprocess.run(args, input=input_text, capture_output=True, text=True, encoding="utf-8")
if check and result.returncode != 0:
raise RuntimeError(f"{' '.join(args[:4])}: {result.stderr.strip()[-1500:]}")
return result.stdout
def psql(sql: str) -> str:
return sh(["docker", "exec", "-i", NAME, "psql", "-U", "postgres", "-d", "bench", "-X", "-q", "-At",
"-v", "ON_ERROR_STOP=1", "-f", "-"], input_text=sql).strip()
def put(path: str, content: str) -> None:
sh(["docker", "exec", "-i", CLIENT, "sh", "-c", f"cat > {path}"], input_text=content)
def start_container(cpus: str, memory: str) -> None:
sh(["docker", "rm", "-f", "-v", CLIENT, NAME], check=False)
sh(["docker", "run", "-d", "--name", NAME, "--cpus", cpus, "--memory", memory,
"-e", f"POSTGRES_PASSWORD={PASSWORD}", "-e", "POSTGRES_DB=bench", IMAGE])
# Load generator: separate container (own CPU quota) sharing the server's network namespace.
sh(["docker", "run", "-d", "--name", CLIENT, "--network", f"container:{NAME}", "--cpus", "2",
"-e", f"PGPASSWORD={PASSWORD}", "--entrypoint", "sleep", IMAGE, "infinity"])
for _ in range(120):
if subprocess.run(["docker", "exec", NAME, "pg_isready", "-U", "postgres", "-d", "bench", "-q"]).returncode == 0:
time.sleep(1)
return
time.sleep(0.5)
raise RuntimeError("experiment PostgreSQL did not start")
SEED = f"""
SELECT setseed(0.42);
INSERT INTO users (id, username, display_name, password_hash)
VALUES ('{USER_ID}', 'track2_bench', convert_to('Track 2', 'UTF8'), 'not-a-login');
CREATE TABLE bench_sizes AS
SELECT n, CASE WHEN n = 1 THEN 60000 WHEN n <= 3 THEN 15000 WHEN n <= 11 THEN 2000 ELSE 80 END AS size,
md5('track2-chat-' || n)::uuid AS chat_id
FROM generate_series(1::int, 200::int) AS n;
INSERT INTO chats (id, title, created_by, created_at)
SELECT chat_id, convert_to('chat ' || n, 'UTF8'), '{USER_ID}', timestamptz '2026-01-01 00:00:00+00' FROM bench_sizes;
INSERT INTO chat_members (chat_id, user_id, position, chat_created_at)
SELECT chat_id, '{USER_ID}', 0, timestamptz '2026-01-01 00:00:00+00' FROM bench_sizes;
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT gen_random_uuid(), s.chat_id, '{USER_ID}',
convert_to(left(repeat('сообщение ', 40), 5 + (random() * 195)::int), 'UTF8'),
timestamptz '2026-01-01 00:00:00+00' + g * interval '1 second'
FROM bench_sizes s CROSS JOIN LATERAL generate_series(1::int, s.size) AS g;
UPDATE chats c SET last_message_at = m.mx FROM (SELECT chat_id, max(created_at) mx FROM messages GROUP BY chat_id) m
WHERE m.chat_id = c.id;
CREATE TABLE bench_chats AS SELECT n, chat_id AS id FROM bench_sizes;
CREATE TABLE bench_cursors AS
SELECT kind, row_number() OVER (PARTITION BY kind ORDER BY rn)::int AS n, created_at AS ts, id AS mid, rn::int AS off
FROM (SELECT CASE s.n WHEN 1 THEN 'big' WHEN 2 THEN 'medium' ELSE 'small' END AS kind, m.created_at, m.id,
row_number() OVER (PARTITION BY m.chat_id ORDER BY m.created_at, m.id) AS rn, s.size
FROM messages m JOIN bench_sizes s ON s.chat_id = m.chat_id WHERE s.n IN (1, 2, 12)) x
WHERE rn % greatest(1, size / 200) = 0 AND rn < size;
CREATE INDEX ON bench_cursors (kind, n);
VACUUM ANALYZE;
"""
def pg_param(sql: str) -> str:
"""psycopg %s placeholders -> pgbench :variables (passed as parameters in prepared mode)."""
names = iter([":chat", ":cts", ":cid", "51"])
out = sql
while "%s" in out:
out = out.replace("%s", next(names), 1)
return out
READ_SCRIPTS = {
"keyset": "\\set k random(1, :ncur)\n"
"SELECT ts AS cts, mid AS cid FROM bench_cursors WHERE kind = :kind AND n = :k \\gset\n"
+ pg_param(HISTORY_AFTER) + ";\n",
"offset": "\\set k random(1, :ncur)\n"
"SELECT off FROM bench_cursors WHERE kind = :kind AND n = :k \\gset\n"
"SELECT id, sender_id, text, created_at FROM messages WHERE chat_id = :chat "
"ORDER BY created_at, id OFFSET :off LIMIT 51;\n",
}
WRITE_SCRIPT = (
"\\set c random(1, 200)\n"
"SELECT id AS chat FROM bench_chats WHERE n = :c \\gset\n"
"BEGIN;\n"
"UPDATE chats SET last_message_at = greatest(clock_timestamp(), last_message_at + interval '1 microsecond') "
"WHERE id = :chat RETURNING last_message_at AS ts \\gset\n"
f"INSERT INTO messages (id, chat_id, sender_id, text, created_at) VALUES "
f"(gen_random_uuid(), :chat, '{USER_ID}', convert_to(repeat('w', 120), 'UTF8'), :ts);\n"
"END;\n"
)
def pgbench(script_path: str, clients: int, seconds: int, defines: dict[str, str]) -> dict:
"""Run pgbench with per-transaction logging; return TPS and latency percentiles (ms)."""
sh(["docker", "exec", CLIENT, "sh", "-c", "rm -f /tmp/pgblog*"])
args = ["docker", "exec", CLIENT, "sh", "-c",
"cd /tmp && pgbench -h 127.0.0.1 -U postgres -n -M prepared -c {c} -j {c} -T {t} -l --log-prefix=pgblog {d} -f {f} bench".format(
c=clients, t=seconds, f=script_path, d=" ".join(f"-D {k}={v}" for k, v in defines.items()))]
out = sh(args)
tps = float(next(l for l in out.splitlines() if l.startswith("tps = ")).split()[2])
failed = next((l for l in out.splitlines() if "number of failed transactions" in l), "0").split(":")[-1].split()[0]
lat = sorted(int(line.split()[2]) / 1000 for line in sh(["docker", "exec", CLIENT, "sh", "-c", "cat /tmp/pgblog*"]).splitlines())
def pct(p: float) -> float:
return round(lat[max(0, math.ceil(p * len(lat)) - 1)], 3)
return {"tps": round(tps, 1), "transactions": len(lat), "failed": int(failed),
"p50_ms": pct(.50), "p95_ms": pct(.95), "p99_ms": pct(.99), "mean_ms": round(statistics.mean(lat), 3)}
def use_variant(name: str) -> dict:
psql("DROP INDEX IF EXISTS messages_chat_keyset; DROP INDEX IF EXISTS messages_chat_only; "
"DROP INDEX IF EXISTS messages_sender_time;")
started = time.monotonic()
for ddl in VARIANTS[name][0]:
psql(ddl + ";")
build_s = round(time.monotonic() - started, 2)
psql("VACUUM ANALYZE messages;")
sizes = psql("SELECT indexrelname || '=' || pg_relation_size(indexrelid) FROM pg_stat_user_indexes "
"WHERE relname = 'messages' ORDER BY 1;").split()
return {"index_build_s": build_s, "index_bytes": dict(s.split("=") for s in sizes),
"table_bytes": int(psql("SELECT pg_relation_size('messages');"))}
def explain_late(kind: str) -> str:
chat = psql(f"SELECT chat_id FROM bench_sizes WHERE n = {dict(big=1, medium=2, small=12)[kind]};")
return psql(f"""
SET plan_cache_mode = force_generic_plan;
PREPARE p(uuid, timestamptz, uuid, int) AS {HISTORY_AFTER.replace('%s', '$1', 1).replace('%s', '$2', 1).replace('%s', '$3', 1).replace('%s', '$4', 1)};
SELECT ts, mid FROM bench_cursors WHERE kind = '{kind}' ORDER BY n DESC LIMIT 1 \\gset
EXPLAIN (ANALYZE, BUFFERS) EXECUTE p('{chat}', :'ts', :'mid', 51);
""")
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--seconds", type=int, default=10)
parser.add_argument("--warmup", type=int, default=3)
parser.add_argument("--repeats", type=int, default=3)
parser.add_argument("--out", default=str(ROOT / "evidence/track2"))
parser.add_argument("--writes-only", action="store_true", help="re-measure writes, keep reads.csv")
parser.add_argument("--write-repeats", type=int, default=5)
args = parser.parse_args()
out = Path(args.out)
(out / "explain").mkdir(parents=True, exist_ok=True)
start_container("2", "2g")
schema = "".join(p.read_text(encoding="utf-8") for p in sorted((ROOT / "migrations").glob("*.sql")))
psql(schema)
seed_started = time.monotonic()
psql(SEED)
seed_s = round(time.monotonic() - seed_started, 1)
stats = psql("SELECT count(*), count(DISTINCT chat_id), min(octet_length(text)), max(octet_length(text)) FROM messages;")
sizes = psql("SELECT size || 'x' || count(*) FROM bench_sizes GROUP BY size ORDER BY size DESC;").split()
for name, script in READ_SCRIPTS.items():
put(f"/tmp/read_{name}.sql", script)
put("/tmp/write.sql", WRITE_SCRIPT)
chats = {k: psql(f"SELECT chat_id FROM bench_sizes WHERE n = {dict(big=1, medium=2, small=12)[k]};") for k in KINDS}
ncur = {k: int(psql(f"SELECT count(*) FROM bench_cursors WHERE kind = '{k}';")) for k in KINDS}
meta = {"image": IMAGE, "limits": {"server_cpus": 2, "server_memory": "2g", "pgbench_client_cpus": 2}, "pg_settings": "image defaults",
"dataset": {"messages_chats_minbytes_maxbytes": stats, "chat_sizes": sizes, "seed_seconds": seed_s},
"pgbench": {"mode": "prepared", "seconds": args.seconds, "warmup": args.warmup, "repeats": args.repeats,
"read_clients": 4, "write_clients": 8, "page": "LIMIT 51 after a random position"},
"host": {"platform": platform.platform(), "docker": sh(["docker", "version", "-f", "{{.Server.Version}}"]).strip()},
"variants": {k: v[1] for k, v in VARIANTS.items()}, "sizes": {}}
print("dataset:", stats, sizes, flush=True)
reads, writes = [], []
if args.writes_only:
old = json.loads((out / "plans-meta.json").read_text(encoding="utf-8"))
meta["sizes"] = old.get("sizes", {})
for variant in ([] if args.writes_only else READ_VARIANTS):
meta["sizes"][variant] = use_variant(variant)
for kind in KINDS:
(out / "explain" / f"{variant}-{kind}-late-page.txt").write_text(explain_late(kind), encoding="utf-8", newline="\n")
for rep in range(1, args.repeats + 1):
for query in READ_SCRIPTS:
for kind in KINDS:
defines = {"chat": chats[kind], "kind": kind, "ncur": str(ncur[kind])}
pgbench(f"/tmp/read_{query}.sql", 4, args.warmup, defines) # warm-up, discarded
row = {"variant": variant, "query": query, "chat": kind, "chat_size": KINDS[kind], "repeat": rep,
**pgbench(f"/tmp/read_{query}.sql", 4, args.seconds, defines)}
reads.append(row)
print("read ", row, flush=True)
wal_rows = []
for variant in WRITE_VARIANTS:
meta["sizes"][variant] = use_variant(variant)
# (a) throughput/latency under concurrency: 8 clients, time-based, autovacuum as in production
for rep in range(1, args.write_repeats + 1):
pgbench("/tmp/write.sql", 8, args.warmup, {})
row = {"variant": variant, "repeat": rep, **pgbench("/tmp/write.sql", 8, args.seconds, {})}
writes.append(row)
print("write", row, flush=True)
# (b) WAL volume per insert, deterministic: the same 5 000 app transactions (1 client),
# autovacuum off for the table and a CHECKPOINT right before, so every run starts from
# the same state and only the index set differs.
psql("ALTER TABLE messages SET (autovacuum_enabled = off);")
for rep in range(1, 4):
psql("CHECKPOINT;")
lsn0 = psql("SELECT pg_current_wal_lsn();")
sh(["docker", "exec", CLIENT, "pgbench", "-h", "127.0.0.1", "-U", "postgres", "-n", "-M", "prepared",
"-c", "1", "-t", "5000", "-f", "/tmp/write.sql", "bench"])
wal = int(psql(f"SELECT pg_current_wal_lsn() - '{lsn0}'::pg_lsn;"))
wal_row = {"variant": variant, "repeat": rep, "inserts": 5000, "wal_bytes": wal,
"wal_bytes_per_insert": round(wal / 5000)}
wal_rows.append(wal_row)
print("wal ", wal_row, flush=True)
psql("ALTER TABLE messages RESET (autovacuum_enabled);")
sh(["docker", "rm", "-f", "-v", CLIENT, NAME], check=False)
with (out / "wal.csv").open("w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=list(wal_rows[0]))
writer.writeheader()
writer.writerows(wal_rows)
meta["pgbench"]["write_repeats"] = args.write_repeats
meta["pgbench"]["wal_method"] = "5000 app transactions, 1 client, autovacuum off, CHECKPOINT before; 3 repeats"
for name, rows in (("reads", reads), ("writes", writes)):
if not rows:
continue
with (out / f"{name}.csv").open("w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=list(rows[0]))
writer.writeheader()
writer.writerows(rows)
(out / "plans-meta.json").write_text(json.dumps(meta, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print("done:", out)
return 0
if __name__ == "__main__":
sys.exit(main())
+110
View File
@@ -0,0 +1,110 @@
#!/usr/bin/env python3
"""Aggregate track 2 raw data into tables (summary.md) and charts (plans.png).
python bench/track2/summarize.py # matplotlib from requirements-bench.txt for the chart
"""
from __future__ import annotations
import csv
import json
import statistics
import sys
from collections import defaultdict
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
OUT = ROOT / "evidence/track2"
SIZE_ORDER = {"big": 0, "medium": 1, "small": 2}
def load(name: str) -> list[dict]:
with (OUT / name).open(encoding="utf-8") as f:
return list(csv.DictReader(f))
def agg(rows: list[dict], keys: tuple[str, ...], fields: tuple[str, ...]) -> dict:
groups: dict = defaultdict(list)
for r in rows:
groups[tuple(r[k] for k in keys)].append(r)
out = {}
for k, g in groups.items():
out[k] = {f: statistics.median(float(r[f]) for r in g) for f in fields}
out[k]["tps_min"] = min(float(r["tps"]) for r in g)
out[k]["tps_max"] = max(float(r["tps"]) for r in g)
out[k]["n"] = len(g)
return out
def fmt(x: float) -> str:
return f"{x:,.0f}".replace(",", " ") if x >= 100 else (f"{x:.1f}" if x >= 10 else f"{x:.2f}")
def main() -> int:
sys.stdout.reconfigure(encoding="utf-8")
reads, writes, wal = load("reads.csv"), load("writes.csv"), load("wal.csv")
meta = json.loads((OUT / "plans-meta.json").read_text(encoding="utf-8"))
r = agg(reads, ("variant", "query", "chat"), ("tps", "p50_ms", "p95_ms", "p99_ms"))
w = agg(writes, ("variant",), ("tps", "p50_ms", "p95_ms", "p99_ms"))
wal_by = {v: [int(r["wal_bytes_per_insert"]) for r in wal if r["variant"] == v] for v in {r["variant"] for r in wal}}
for v, values in wal_by.items():
w[(v,)]["wal_bytes_per_insert"] = statistics.median(values)
w[(v,)]["wal_min"], w[(v,)]["wal_max"] = min(values), max(values)
sizes = {"big": 60000, "medium": 15000, "small": 80}
md = ["## Чтение: одна страница (LIMIT 51) со случайной позиции чата", "",
"Медиана 3 повторов по 10 с, 4 клиента pgbench, prepared statements. TPS min–max — разброс повторов.", "",
"| Индекс | Запрос | Чат (сообщений) | TPS (min–max) | p50, мс | p95, мс | p99, мс |",
"| --- | --- | ---: | ---: | ---: | ---: | ---: |"]
for (variant, query, chat), v in sorted(r.items(), key=lambda kv: (kv[0][0] != "keyset_index", kv[0][0], kv[0][1], SIZE_ORDER[kv[0][2]])):
md.append(f"| {variant} | {query} | {chat} ({sizes[chat]:,}) | {fmt(v['tps'])} ({fmt(v['tps_min'])}–{fmt(v['tps_max'])}) "
f"| {fmt(v['p50_ms'])} | {fmt(v['p95_ms'])} | {fmt(v['p99_ms'])} |".replace(",", " ", 1))
md += ["", "## Запись: транзакция сообщения приложения (UPDATE chats … RETURNING + INSERT)", "",
"TPS и задержка — медиана 5 повторов по 10 с, 8 клиентов. WAL — медиана 3 детерминированных прогонов: "
"5 000 транзакций, 1 клиент, autovacuum выключен, CHECKPOINT перед прогоном.", "",
"| Индексы messages | TPS (min–max) | p50, мс | p95, мс | p99, мс | WAL, байт/вставку (min–max) | Размер индексов, МиБ |",
"| --- | ---: | ---: | ---: | ---: | ---: | ---: |"]
for variant in ("no_index", "keyset_index", "keyset_plus_sender"):
v = w[(variant,)]
idx = meta["sizes"][variant]["index_bytes"]
idx_mib = sum(int(b) for b in idx.values()) / 2**20
md.append(f"| {variant} | {fmt(v['tps'])} ({fmt(v['tps_min'])}–{fmt(v['tps_max'])}) | {fmt(v['p50_ms'])} | {fmt(v['p95_ms'])} "
f"| {fmt(v['p99_ms'])} | {v['wal_bytes_per_insert']:.0f} ({v['wal_min']}–{v['wal_max']}) | {idx_mib:.1f} |")
(OUT / "summary.md").write_text("\n".join(md) + "\n", encoding="utf-8", newline="\n")
print("\n".join(md))
try:
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
except ImportError:
print("matplotlib is not installed: skipping plans.png")
return 0
fig, axes = plt.subplots(1, 2, figsize=(15, 5))
chats = ["small", "medium", "big"]
x = [sizes[c] for c in chats]
styles = {("keyset_index", "keyset"): ("#12a150", "-o"), ("keyset_index", "offset"): ("#12a150", "--s"),
("chat_id_index", "keyset"): ("#e07b00", "-o"), ("chat_id_index", "offset"): ("#e07b00", "--s"),
("no_index", "keyset"): ("#b03060", "-o"), ("no_index", "offset"): ("#b03060", "--s")}
for (variant, query), (color, style) in styles.items():
axes[0].plot(x, [r[(variant, query, c)]["p95_ms"] for c in chats], style, color=color, label=f"{variant}, {query}")
axes[0].set_xscale("log")
axes[0].set_yscale("log")
axes[0].set_xlabel("messages in the chat")
axes[0].set_ylabel("p95 latency of one page, ms (log)")
axes[0].set_title("Read: random page of a chat")
axes[0].grid(True, which="both", alpha=0.3)
axes[0].legend(fontsize=8)
names = ["no_index", "keyset_index", "keyset_plus_sender"]
axes[1].bar([n.replace("_", "\n") for n in names], [w[(n,)]["wal_bytes_per_insert"] for n in names], color="#2a6fdb")
for i, n in enumerate(names):
axes[1].text(i, w[(n,)]["wal_bytes_per_insert"], f"{w[(n,)]['tps']:.0f} TPS", ha="center", va="bottom")
axes[1].set_ylabel("WAL bytes per inserted message")
axes[1].set_title("Write cost of indexes (WAL: 5000 inserts; TPS: 8 clients)")
fig.suptitle("Track 2: 121 120 messages, chats of 60 000 / 15 000 / 2 000 / 80; PostgreSQL 18.6, 2 CPU / 2 GiB")
fig.tight_layout()
fig.savefig(OUT / "plans.png", dpi=120)
print("chart:", OUT / "plans.png")
return 0
if __name__ == "__main__":
sys.exit(main())