Files
mtusi2026lab2/src/explain_history.py
T
samsikandCursor ae4d626ce6 Add PostgreSQL storage and Valkey sessions for lab2.
Messages survive restart in Postgres, and bearer sessions persist in Valkey with AOF.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-09 01:21:39 +03:00

84 lines
2.9 KiB
Python

#!/usr/bin/env python3
"""EXPLAIN (ANALYZE, BUFFERS) keyset-страницы на >= 10000 сообщениях одного чата."""
from __future__ import annotations
import os
import sys
import uuid
from datetime import datetime, timedelta, timezone
import psycopg
START = datetime(2020, 1, 1, tzinfo=timezone.utc)
def main() -> None:
url = os.environ.get("DATABASE_URL", "").strip()
if not url:
sys.stderr.write("DATABASE_URL is not set\n")
raise SystemExit(2)
with psycopg.connect(url, connect_timeout=5, autocommit=False) as conn:
user_id = uuid.uuid5(uuid.NAMESPACE_URL, "lab2-explain-user")
chat_id = uuid.uuid5(uuid.NAMESPACE_URL, "lab2-explain-chat")
with conn.transaction():
conn.execute(
"""
INSERT INTO users (id, username, display_name, password_hash, created_at)
VALUES (%s, %s, %s, %s, %s)
ON CONFLICT (username) DO NOTHING
""",
(user_id, "explain_hist", "explain", "not-a-login-hash", START),
)
conn.execute(
"""
INSERT INTO chats (id, title, created_at)
VALUES (%s, %s, %s)
ON CONFLICT (id) DO NOTHING
""",
(chat_id, "explain", START),
)
conn.execute(
"""
INSERT INTO chat_members (chat_id, user_id, position)
VALUES (%s, %s, 0)
ON CONFLICT (chat_id, user_id) DO NOTHING
""",
(chat_id, user_id),
)
count = conn.execute(
"SELECT count(*) FROM messages WHERE chat_id = %s",
(chat_id,),
).fetchone()[0]
missing = 10000 - count
if missing > 0:
conn.execute(
"""
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT gen_random_uuid(), %s, %s, 'm', %s + (g || ' seconds')::interval
FROM generate_series(%s, %s) AS g
""",
(chat_id, user_id, START, count + 1, 10000),
)
midpoint = START + timedelta(seconds=5000)
plan = conn.execute(
"""
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, created_at
FROM messages
WHERE chat_id = %s
AND (created_at, id) > (%s, %s)
ORDER BY created_at, id
LIMIT 50
""",
(chat_id, midpoint, uuid.UUID(int=0)),
).fetchall()
text = "\n".join(row[0] for row in plan)
sys.stdout.write(text + "\n")
if "Index" not in text or "Seq Scan" in text:
sys.stderr.write("expected an index range scan, not a sequential scan\n")
raise SystemExit(1)
if __name__ == "__main__":
main()