Files
mtusi2026lab2/scripts/track2_experiment.py

177 lines
6.0 KiB
Python

#!/usr/bin/env python3
"""Reproducible index and write-cost experiment over a skewed 100k-row dataset."""
import hashlib
import json
import os
import statistics
import time
import psycopg
from psycopg.rows import dict_row
DATABASE_URL = os.environ["DATABASE_URL"]
ROWS = int(os.environ.get("TRACK2_ROWS", "100000"))
HOT_CHAT = "md5('hot-chat')::uuid"
def plan_summary(plan):
root = plan[0]["Plan"]
nodes = []
def visit(node):
nodes.append(
{
"node": node.get("Node Type"),
"index": node.get("Index Name"),
"actual_rows": node.get("Actual Rows"),
"actual_ms": node.get("Actual Total Time"),
"shared_hit_blocks": node.get("Shared Hit Blocks", 0),
"shared_read_blocks": node.get("Shared Read Blocks", 0),
"sort_method": node.get("Sort Method"),
}
)
for child in node.get("Plans", []):
visit(child)
visit(root)
return nodes
def insert_dataset(conn, table):
started = time.perf_counter()
conn.execute(
"""
INSERT INTO {} (id, chat_id, created_at, body)
SELECT i,
CASE WHEN i <= %s * 0.8
THEN md5('hot-chat')::uuid
ELSE md5('chat-' || (i %% 20)::text)::uuid
END,
TIMESTAMPTZ '2025-01-01 00:00:00+00' + make_interval(secs => i::double precision),
repeat('x', 64 + (i %% 449))
FROM generate_series(1, %s) AS i
""".format(table),
(ROWS, ROWS),
)
conn.commit()
return round(time.perf_counter() - started, 4)
def table_sample(conn, table):
return conn.execute(
"SELECT id, chat_id::text AS chat_id, created_at::text AS created_at, body "
"FROM {} WHERE id = ANY(%s) ORDER BY id".format(table),
([1, ROWS // 2, ROWS],),
).fetchall()
def main():
if ROWS < 100000:
raise SystemExit("TRACK2_ROWS must be at least 100000")
with psycopg.connect(DATABASE_URL, row_factory=dict_row) as conn:
conn.execute("DROP SCHEMA IF EXISTS track2_lab CASCADE")
conn.execute("CREATE SCHEMA track2_lab")
for table in ("messages_chat_only", "messages_composite"):
conn.execute(
"""
CREATE TABLE track2_lab.{} (
id BIGINT PRIMARY KEY,
chat_id UUID NOT NULL,
created_at TIMESTAMPTZ NOT NULL,
body TEXT NOT NULL
)
""".format(table)
)
conn.execute(
"CREATE INDEX messages_chat_only_idx ON track2_lab.messages_chat_only(chat_id)"
)
conn.execute(
"CREATE INDEX messages_composite_idx "
"ON track2_lab.messages_composite(chat_id, created_at, id)"
)
conn.commit()
write_seconds = {}
for table in ("messages_chat_only", "messages_composite"):
write_seconds[table] = insert_dataset(conn, "track2_lab." + table)
conn.execute("ANALYZE track2_lab.messages_chat_only")
conn.execute("ANALYZE track2_lab.messages_composite")
conn.commit()
plans = {}
for table in ("messages_chat_only", "messages_composite"):
result = conn.execute(
"""
EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)
SELECT id, created_at, body
FROM track2_lab.{}
WHERE chat_id = {}
ORDER BY created_at, id
LIMIT 50
""".format(table, HOT_CHAT)
).fetchone()
plan_json = result["QUERY PLAN"]
if isinstance(plan_json, str):
plan_json = json.loads(plan_json)
plans[table] = plan_summary(plan_json)
manifest_rows = []
samples = {}
for table in ("messages_chat_only", "messages_composite"):
rows = table_sample(conn, "track2_lab." + table)
encoded = json.dumps(rows, sort_keys=True, default=str).encode("utf-8")
digest = hashlib.sha256(encoded).hexdigest()
samples[table] = {
"sample_ids": [1, ROWS // 2, ROWS],
"sha256": digest,
}
count = conn.execute(
"SELECT count(*) AS count FROM track2_lab.{}".format(table)
).fetchone()["count"]
index_size = conn.execute(
"SELECT pg_relation_size('track2_lab.{}') AS bytes".format(
"messages_chat_only_idx"
if table == "messages_chat_only"
else "messages_composite_idx"
)
).fetchone()["bytes"]
manifest_rows.append((table, count, samples[table]["sample_ids"], digest))
samples[table]["index_bytes"] = index_size
conn.execute(
"""
CREATE TABLE track2_lab.manifest (
table_name TEXT PRIMARY KEY,
row_count BIGINT NOT NULL,
sample_ids BIGINT[] NOT NULL,
sample_sha256 TEXT NOT NULL
)
"""
)
with conn.cursor() as cur:
cur.executemany(
"INSERT INTO track2_lab.manifest VALUES (%s, %s, %s, %s)",
manifest_rows,
)
conn.commit()
result = {
"dataset_rows_per_variant": ROWS,
"distribution": "80% in one hot chat; remaining 20% split across 20 chats",
"body_size_bytes": "64..512, deterministic",
"write_seconds_single_bulk_insert_with_index": write_seconds,
"explain_analyze_buffers": plans,
"index_size_and_restore_manifest": samples,
"limits": [
"single local Docker host and one trial per variant",
"EXPLAIN ANALYZE executes the query and is not a production latency guarantee",
"write times include local cache and container scheduling noise",
],
}
print(json.dumps(result, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()