Files
mtusi2026lab2/student-tests/explain-history.py
T
Daria0w0 c0ca56f208
Application checks / application (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
Complete lab2 grade 4 implementation and report
2026-10-10 00:28:43 +03:00

102 lines
5.9 KiB
Python

import datetime
import json
from pathlib import Path
import statistics
import subprocess
import uuid
from sessions import request, basic
ROOT = Path(__file__).resolve().parents[1]
def command(args, input_text=None):
result = subprocess.run(args, cwd=ROOT, input=input_text, text=True, encoding="utf-8", capture_output=True, timeout=90)
if result.returncode:
raise RuntimeError("Command failed: " + " ".join(args[:4]) + ": " + result.stderr[:1000])
return result.stdout.strip()
def sql(statement):
return command(["docker", "compose", "exec", "-T", "postgres", "psql", "-X", "-qAt", "-v", "ON_ERROR_STOP=1", "-U", "messenger", "-d", "messenger"], statement)
def nodes(plan):
yield plan
for child in plan.get("Plans", []):
yield from nodes(child)
def main():
username = "explain_" + uuid.uuid4().hex[:20]
password = "учебный:пароль:explain"
user = request("POST", "/users", 201, {"username": username, "display_name": "EXPLAIN", "password": password})
session = request("POST", "/auth/sessions", 201, headers=basic(username, password))
headers = {"Authorization": "Bearer " + session["token"]}
chat = request("POST", "/chats", 201, {"title": "History index experiment", "member_ids": [user["id"]]}, headers)
# Validate identifiers before inserting them into this standalone experiment SQL.
chat_id, user_id = str(uuid.UUID(chat["id"])), str(uuid.UUID(user["id"]))
sql(f"""BEGIN;
SET LOCAL statement_timeout='60s';
INSERT INTO messages(id,chat_id,sender_id,text,created_at)
SELECT gen_random_uuid(), '{chat_id}'::uuid, '{user_id}'::uuid,
'synthetic message ' || n,
CURRENT_TIMESTAMP - INTERVAL '1 day' + n * INTERVAL '1 millisecond'
FROM generate_series(1,12000) AS n;
COMMIT;
ANALYZE messages;
""")
count = int(sql(f"SELECT count(*) FROM messages WHERE chat_id='{chat_id}'::uuid;"))
assert count == 12000
# OFFSET is used once to choose a fixture cursor, never in the measured page query.
cursor = json.loads(sql(f"""SELECT row_to_json(p) FROM (
SELECT created_at, id FROM messages WHERE chat_id='{chat_id}'::uuid
ORDER BY created_at,id OFFSET 5999 LIMIT 1) p;"""))
cursor_id = str(uuid.UUID(cursor["id"]))
cursor_time = datetime.datetime.fromisoformat(cursor["created_at"]).isoformat()
columns = "id::text,chat_id::text,sender_id::text,text,created_at"
first = f"SELECT {columns} FROM messages WHERE chat_id=$1 ORDER BY messages.created_at,messages.id LIMIT $2"
following = f"SELECT {columns} FROM messages WHERE chat_id=$1 AND (created_at,id)>($3,$4::uuid) ORDER BY messages.created_at,messages.id LIMIT $2"
cases = {
"first_page": (f"PREPARE history(uuid,integer) AS {first};", f"EXECUTE history('{chat_id}',51)"),
"after_6000": (f"PREPARE history(uuid,integer,timestamptz,uuid) AS {following};", f"EXECUTE history('{chat_id}',51,'{cursor_time}','{cursor_id}')"),
}
metadata = {
"date": "2026-10-09", "messages_in_chat": count, "chat_id": chat_id,
"page_size": 50, "sql_limit": 51, "concurrency": 1, "warmups": 1, "repeats": 3,
"postgres_version": sql("SHOW server_version;"),
"docker_cpus_memory_bytes": command(["docker", "info", "--format", "{{.NCPU}} {{.MemTotal}}"]),
"postgres_cpu_memory_limits": command(["docker", "inspect", "--format", "{{.HostConfig.NanoCpus}} {{.HostConfig.Memory}}", command(["docker", "compose", "ps", "-q", "postgres"])]),
"method": "SQL-generated fixture; ANALYZE; prepared query; one warmup and three serial measurements; no concurrent writers",
"limitations": "warm cache, one synthetic chat; not HTTP latency or throughput; no crash-durability measurement",
"cases": {},
}
text_plans = []
for name, (prepare, execute) in cases.items():
sql(prepare + "\nEXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) " + execute + ";")
plans = [json.loads(sql(prepare + "\nEXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) " + execute + ";"))[0] for _ in range(3)]
for result in plans:
tree = list(nodes(result["Plan"]))
assert any(node.get("Index Name") == "messages_chat_history_idx" for node in tree), "history index not used"
assert not any(node["Node Type"] == "Seq Scan" and node.get("Relation Name") == "messages" for node in tree), "full history scan"
assert result["Plan"]["Actual Rows"] == 51
scanned = [node for node in tree if node.get("Relation Name") == "messages"]
assert all(node["Actual Rows"] <= 51 and node.get("Rows Removed by Filter", 0) == 0 for node in scanned), "page reads extra history"
metadata["cases"][name] = {"prepare": prepare, "execute": execute, "plans": plans}
text_plans.append(name + "\n" + prepare + "\n" + sql(prepare + "\nEXPLAIN (ANALYZE, BUFFERS) " + execute + ";"))
median = statistics.median(plan["Execution Time"] for plan in plans)
print(f"PASS: {name}: history index, 51 rows, no full scan; median SQL execution {median:.3f} ms")
# Exercise the real HTTP cursor at the same position, not only SQL plans.
import base64
from urllib.parse import quote
encoded = base64.urlsafe_b64encode(json.dumps({"scope": "messages:" + chat_id, "after": cursor}).encode()).decode().rstrip("=")
page = request("GET", f"/chats/{chat_id}/messages?limit=50&cursor=" + quote(encoded), 200, headers=headers)
assert len(page["items"]) == 50 and page["items"][0]["text"] == "synthetic message 6001"
request("DELETE", "/auth/sessions/current", 204, headers=headers)
(ROOT / "evidence/history-explain.json").write_text(json.dumps(metadata, ensure_ascii=False, indent=2), encoding="utf-8")
(ROOT / "evidence/history-explain.txt").write_text("Date: 2026-10-09\nCommand: py student-tests/explain-history.py\nMessages: 12000\n\n" + "\n\n".join(text_plans) + "\n", encoding="utf-8")
print("PASS: 12000 messages; HTTP cursor after 6000 returns message 6001; plans saved in evidence")
if __name__ == "__main__":
main()