#!/usr/bin/env python3 """Create 10 000 synthetic messages and record EXPLAIN (ANALYZE, BUFFERS). Run inside the API container (psycopg is installed there): docker compose exec -T api python student-tests/explain_history.py \ --output /app/evidence/explain_history.txt The evidence directory is mounted read-only in the container, so the example below is normally executed with a writable bind mount or copied out. """ from __future__ import annotations import argparse import os import uuid from datetime import datetime, timezone from pathlib import Path import psycopg MESSAGES = 10_000 def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--database-url", default=os.environ.get("DATABASE_URL")) parser.add_argument("--output", default="evidence/explain_history.txt") parser.add_argument("--messages", type=int, default=MESSAGES) args = parser.parse_args() if not args.database_url: raise SystemExit("DATABASE_URL is required") tag = uuid.uuid4().hex[:10] user_id = uuid.uuid4() chat_id = uuid.uuid4() with psycopg.connect(args.database_url) as conn: conn.execute( "INSERT INTO users (id, username, display_name, password_hash) VALUES (%s, %s, %s, %s)", (user_id, "perf_" + tag, "Performance synthetic", "not-a-real-password-hash"), ) conn.execute("INSERT INTO chats (id, title) VALUES (%s, %s)", (chat_id, "perf-" + tag)) conn.execute( "INSERT INTO chat_members (chat_id, user_id) VALUES (%s, %s)", (chat_id, user_id) ) conn.execute( """ INSERT INTO messages (id, chat_id, sender_id, text, created_at) SELECT gen_random_uuid(), %s, %s, 'synthetic message ' || g, timestamptz '2026-01-01 00:00:00+00' + (g || ' milliseconds')::interval FROM generate_series(1, %s) AS g """, (chat_id, user_id, args.messages), ) total = conn.execute( "SELECT count(*) FROM messages WHERE chat_id = %s", (chat_id,) ).fetchone()[0] conn.execute("ANALYZE messages") cursor = conn.execute( """ SELECT created_at, id FROM messages WHERE chat_id = %s ORDER BY created_at, id OFFSET %s LIMIT 1 """, (chat_id, max(0, args.messages - 500)), ).fetchone() plan_rows = conn.execute( """ EXPLAIN (ANALYZE, BUFFERS) SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = %s AND (created_at, id) > (%s, %s) ORDER BY created_at, id LIMIT 51 """, (chat_id, cursor[0], cursor[1]), ).fetchall() conn.commit() plan = "\n".join(row[0] for row in plan_rows) if "messages_chat_created_at_id_idx" not in plan: raise AssertionError("history query did not use the keyset index:\n" + plan) if "Seq Scan" in plan: raise AssertionError("history query performed a sequential scan:\n" + plan) header = ( "# EXPLAIN (ANALYZE, BUFFERS) for keyset history pagination\n" f"generated_at_utc: {datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z')}\n" f"messages_in_chat: {total}\n" f"chat_id: {chat_id}\n" "query: WHERE chat_id = ? AND (created_at, id) > (?, ?) " "ORDER BY created_at, id LIMIT 51\n\n" ) output = Path(args.output) output.parent.mkdir(parents=True, exist_ok=True) output.write_text(header + plan + "\n", encoding="utf-8") print(header + plan) print(f"PASS: index used on {total} messages; evidence written to {output}") if __name__ == "__main__": main()