Files
mtusi2026lab2/student-tests/explain_history.py
T

82 lines
4.6 KiB
Python

"""Reproduce the actual keyset history query on >=10,000 synthetic messages."""
import argparse
import base64
import json
import uuid
from datetime import datetime, timezone
from compose_helpers import ROOT, sql
from client import Client, check, run
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://localhost:8080")
args = parser.parse_args()
client = Client(args.base_url)
actor = client.user("explain")
chat = client.call("POST", "/api/v1/chats", 201, actor=actor,
body={"title": "EXPLAIN 10000 " + uuid.uuid4().hex,
"member_ids": [actor["id"]]}, schema="Chat")["json"]
chat_id, user_id = chat["id"], actor["id"]
# One fixed timeline and deterministic unique UUIDs; each run uses its own chat.
sql(f"""
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT md5('{chat_id}:' || n::text)::uuid, '{chat_id}'::uuid, '{user_id}'::uuid,
repeat('message-' || n::text || ' ', 8),
'2026-01-01T00:00:00Z'::timestamptz + n * interval '1 millisecond'
FROM generate_series(1, 10000) AS fixture(n);
ANALYZE messages;
""")
count = int(sql(f"SELECT count(*) FROM messages WHERE chat_id = '{chat_id}';"))
check(count == 10000, "fixture must contain exactly 10000 messages")
anchor = json.loads(sql(f"""
SELECT json_build_object('id', id, 'created_at', to_char(created_at AT TIME ZONE 'UTC',
'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"'))
FROM messages WHERE chat_id = '{chat_id}' ORDER BY created_at, id OFFSET 8999 LIMIT 1;
"""))
# OFFSET is used only once to choose the benchmark anchor, never by the API query.
first_query = f"SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = '{chat_id}' ORDER BY created_at, id LIMIT 51"
next_query = f"SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = '{chat_id}' AND (created_at, id) > ('{anchor['created_at']}'::timestamptz, '{anchor['id']}'::uuid) ORDER BY created_at, id LIMIT 51"
plans = {}
for name, query in [("first_page", first_query), ("after_message_9000", next_query)]:
plan = json.loads(sql("EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) " + query + ";"))[0]
nodes = list(walk(plan["Plan"]))
check(any(node.get("Index Name") == "messages_chat_created_id_idx" for node in nodes),
name + " did not use the history index")
check(not any(node["Node Type"] == "Seq Scan" for node in nodes), name + " scanned the entire message table")
check(plan["Plan"]["Actual Rows"] == 51, "plan returned an unexpected page size")
plans[name] = {"query": query, "explain_analyze_buffers": plan}
encoded = base64.urlsafe_b64encode(json.dumps({"Scope": "chat:" + chat_id,
"CreatedAt": anchor["created_at"], "Id": anchor["id"]}).encode()).decode().rstrip("=")
first = client.call("GET", f"/api/v1/chats/{chat_id}/messages?limit=50", actor=actor, schema="MessagePage")["json"]
deep = client.call("GET", f"/api/v1/chats/{chat_id}/messages?limit=50&cursor={encoded}",
actor=actor, schema="MessagePage")["json"]
check(len(first["items"]) == len(deep["items"]) == 50 and deep["next_cursor"] is not None,
"API did not return the expected keyset pages")
next_page = client.call("GET", f"/api/v1/chats/{chat_id}/messages?limit=50&cursor={deep['next_cursor']}",
actor=actor, schema="MessagePage")["json"]
check(not set(item["id"] for item in deep["items"]) & set(item["id"] for item in next_page["items"]),
"keyset continuation repeated messages")
evidence = {"verified_at": datetime.now(timezone.utc).isoformat(), "message_count_in_chat": count,
"fixture": "synthetic data; no tokens or passwords in evidence", "plans": plans,
"api_pages": {"first": 50, "deep": 50, "continuation": len(next_page["items"]), "duplicates": 0}}
destination = ROOT / "evidence" / "history-explain.json"
destination.parent.mkdir(exist_ok=True)
destination.write_text(json.dumps(evidence, ensure_ascii=False, indent=2) + "\n")
for name, value in plans.items():
plan = value["explain_analyze_buffers"]
print(f"PASS: {name}: history index, 51 SQL rows, execution {plan['Execution Time']} ms")
print("PASS: 10000 messages, deep API pagination without repeats; evidence/history-explain.json")
def walk(node):
yield node
for child in node.get("Plans", []):
yield from walk(child)
if __name__ == "__main__":
run(main)