287 lines
14 KiB
Python
287 lines
14 KiB
Python
#!/usr/bin/env python3
|
|
"""Grade 5 Track 2 Experiment:
|
|
- Query Plan & EXPLAIN (ANALYZE, BUFFERS) on >=100,000 messages with skewed chat sizes
|
|
(1 large chat with 80,000 messages, 4 medium chats with 5,000 messages each, 10 small chats with 1,000 messages each = 110,000 messages).
|
|
- Comparison of 3 query/index approaches and write cost with vs without secondary index.
|
|
- Full Backup (pg_dump) -> Restore into a fresh PostgreSQL database (pg_restore) -> Checksum & Row Count verification.
|
|
"""
|
|
import hashlib
|
|
import json
|
|
import subprocess
|
|
import time
|
|
|
|
|
|
def run_cmd(cmd):
|
|
res = subprocess.run(cmd, shell=True, capture_output=True, text=True)
|
|
if res.returncode != 0:
|
|
raise RuntimeError(f"Command failed ({cmd}): {res.stderr}")
|
|
return res.stdout.strip()
|
|
|
|
|
|
def psql(db, sql):
|
|
res = subprocess.run(
|
|
f"docker exec -i mtusi-lab2-postgres psql -v ON_ERROR_STOP=1 -U messenger -d {db} -tA",
|
|
input=sql,
|
|
shell=True,
|
|
capture_output=True,
|
|
text=True,
|
|
encoding="utf-8",
|
|
)
|
|
if res.returncode != 0:
|
|
raise RuntimeError(f"PSQL failed on {db}: {res.stderr}\nSQL: {sql[:200]}")
|
|
return res.stdout.strip()
|
|
|
|
|
|
def main():
|
|
print("[Track 2 - Step 1] Preparing 110,000 skewed messages across 15 chats...")
|
|
# Create dedicated synthetic benchmark user and 15 skewed chats
|
|
setup_sql = """
|
|
DO $$
|
|
DECLARE
|
|
u_id UUID := '11111111-1111-4111-8111-111111111111';
|
|
hot_chat UUID := '22222222-2222-4222-8222-222222222222';
|
|
c_id UUID;
|
|
i INT;
|
|
BEGIN
|
|
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
|
VALUES (u_id, 'track2_bench_user', 'Track 2 Researcher', '$argon2id$v=19$m=19456,t=1,p=2$dGVzdHNhbHQxMjM0NTY3OA$dGVzdGhhc2gxMjM0NTY3ODkwMTIzNDU2Nzg5MDEyMzQ', NOW())
|
|
ON CONFLICT (username) DO NOTHING;
|
|
|
|
SELECT id INTO u_id FROM users WHERE username = 'track2_bench_user';
|
|
|
|
-- Delete previous benchmark chats if re-running
|
|
DELETE FROM chats WHERE title LIKE 'Track2_Skewed_%';
|
|
|
|
-- 1 Hot chat (80,000 messages)
|
|
INSERT INTO chats (id, title, created_at) VALUES (hot_chat, 'Track2_Skewed_Hot_80k', NOW());
|
|
INSERT INTO chat_members (chat_id, user_id, ord) VALUES (hot_chat, u_id, 0);
|
|
|
|
-- 4 Medium chats (5,000 messages each = 20,000)
|
|
FOR i IN 1..4 LOOP
|
|
c_id := gen_random_uuid();
|
|
INSERT INTO chats (id, title, created_at) VALUES (c_id, 'Track2_Skewed_Medium_' || i, NOW());
|
|
INSERT INTO chat_members (chat_id, user_id, ord) VALUES (c_id, u_id, 0);
|
|
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
|
SELECT gen_random_uuid(), c_id, u_id, 'Medium chat message #' || g,
|
|
TIMESTAMPTZ '2026-01-01 00:00:00Z' + (g * INTERVAL '1 millisecond')
|
|
FROM generate_series(1, 5000) AS g;
|
|
END LOOP;
|
|
|
|
-- 10 Small chats (1,000 messages each = 10,000)
|
|
FOR i IN 1..10 LOOP
|
|
c_id := gen_random_uuid();
|
|
INSERT INTO chats (id, title, created_at) VALUES (c_id, 'Track2_Skewed_Small_' || i, NOW());
|
|
INSERT INTO chat_members (chat_id, user_id, ord) VALUES (c_id, u_id, 0);
|
|
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
|
SELECT gen_random_uuid(), c_id, u_id, 'Small chat message #' || g,
|
|
TIMESTAMPTZ '2026-01-01 00:00:00Z' + (g * INTERVAL '1 millisecond')
|
|
FROM generate_series(1, 1000) AS g;
|
|
END LOOP;
|
|
END $$;
|
|
"""
|
|
psql("messenger", setup_sql)
|
|
|
|
# Measure Write Cost: Inserting 40,000 rows WITHOUT composite index vs 40,000 rows WITH composite index
|
|
print("[Track 2 - Step 2] Measuring write cost with vs without composite index (80,000 messages into hot chat)...")
|
|
psql("messenger", "DROP INDEX IF EXISTS idx_messages_chat_created_id;")
|
|
t0 = time.perf_counter()
|
|
psql("messenger", """
|
|
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
|
SELECT gen_random_uuid(),
|
|
'22222222-2222-4222-8222-222222222222'::uuid,
|
|
(SELECT id FROM users WHERE username = 'track2_bench_user'),
|
|
'Hot chat message batch 1 #' || g,
|
|
TIMESTAMPTZ '2026-02-01 00:00:00Z' + (g * INTERVAL '1 millisecond')
|
|
FROM generate_series(1, 40000) AS g;
|
|
""")
|
|
write_no_index_ms = round((time.perf_counter() - t0) * 1000.0, 2)
|
|
|
|
# Recreate the composite index and measure insertion of the next 40,000 messages
|
|
psql("messenger", "CREATE INDEX idx_messages_chat_created_id ON messages (chat_id, created_at ASC, id ASC);")
|
|
t1 = time.perf_counter()
|
|
psql("messenger", """
|
|
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
|
SELECT gen_random_uuid(),
|
|
'22222222-2222-4222-8222-222222222222'::uuid,
|
|
(SELECT id FROM users WHERE username = 'track2_bench_user'),
|
|
'Hot chat message batch 2 #' || g,
|
|
TIMESTAMPTZ '2026-02-01 00:00:00Z' + ((40000 + g) * INTERVAL '1 millisecond')
|
|
FROM generate_series(1, 40000) AS g;
|
|
""")
|
|
write_with_index_ms = round((time.perf_counter() - t1) * 1000.0, 2)
|
|
|
|
psql("messenger", "ANALYZE messages;")
|
|
total_messages = int(psql("messenger", "SELECT count(*) FROM messages;"))
|
|
hot_chat_messages = int(psql("messenger", "SELECT count(*) FROM messages WHERE chat_id = '22222222-2222-4222-8222-222222222222';"))
|
|
|
|
# Find the cursor at offset 50,000 in the hot chat
|
|
cursor_row = psql("messenger", """
|
|
SELECT created_at::text || '|' || id::text
|
|
FROM messages
|
|
WHERE chat_id = '22222222-2222-4222-8222-222222222222'
|
|
ORDER BY created_at ASC, id ASC
|
|
OFFSET 50000 LIMIT 1;
|
|
""")
|
|
cursor_ts, cursor_id = cursor_row.split("|")
|
|
|
|
# Compare 3 Query Plans using EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)
|
|
print("[Track 2 - Step 3] Running EXPLAIN (ANALYZE, BUFFERS) across 3 index/query designs...")
|
|
|
|
# Plan A: Composite Index (chat_id, created_at ASC, id ASC) + Keyset Pagination at depth 50,000
|
|
plan_keyset_json = json.loads(psql("messenger", f"""
|
|
EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)
|
|
SELECT id, chat_id, sender_id, text, created_at
|
|
FROM messages
|
|
WHERE chat_id = '22222222-2222-4222-8222-222222222222'
|
|
AND (created_at, id) > ('{cursor_ts}'::timestamptz, '{cursor_id}'::uuid)
|
|
ORDER BY created_at ASC, id ASC
|
|
LIMIT 50;
|
|
"""))[0]
|
|
|
|
plan_keyset_text = psql("messenger", f"""
|
|
EXPLAIN (ANALYZE, BUFFERS)
|
|
SELECT id, chat_id, sender_id, text, created_at
|
|
FROM messages
|
|
WHERE chat_id = '22222222-2222-4222-8222-222222222222'
|
|
AND (created_at, id) > ('{cursor_ts}'::timestamptz, '{cursor_id}'::uuid)
|
|
ORDER BY created_at ASC, id ASC
|
|
LIMIT 50;
|
|
""")
|
|
|
|
# Plan B: Single-column index on (chat_id) + OFFSET 50000 LIMIT 50
|
|
psql("messenger", "DROP INDEX idx_messages_chat_created_id;")
|
|
psql("messenger", "CREATE INDEX idx_messages_chat_only ON messages (chat_id);")
|
|
psql("messenger", "ANALYZE messages;")
|
|
|
|
plan_offset_json = json.loads(psql("messenger", """
|
|
EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)
|
|
SELECT id, chat_id, sender_id, text, created_at
|
|
FROM messages
|
|
WHERE chat_id = '22222222-2222-4222-8222-222222222222'
|
|
ORDER BY created_at ASC, id ASC
|
|
OFFSET 50000 LIMIT 50;
|
|
"""))[0]
|
|
|
|
# Plan C: No index on messages (Seq Scan + Top-N Heap Sort) with Keyset filter
|
|
psql("messenger", "DROP INDEX idx_messages_chat_only;")
|
|
psql("messenger", "ANALYZE messages;")
|
|
|
|
plan_seqscan_json = json.loads(psql("messenger", f"""
|
|
EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)
|
|
SELECT id, chat_id, sender_id, text, created_at
|
|
FROM messages
|
|
WHERE chat_id = '22222222-2222-4222-8222-222222222222'
|
|
AND (created_at, id) > ('{cursor_ts}'::timestamptz, '{cursor_id}'::uuid)
|
|
ORDER BY created_at ASC, id ASC
|
|
LIMIT 50;
|
|
"""))[0]
|
|
|
|
# Restore the production composite keyset index!
|
|
psql("messenger", "CREATE INDEX idx_messages_chat_created_id ON messages (chat_id, created_at ASC, id ASC);")
|
|
psql("messenger", "ANALYZE messages;")
|
|
|
|
# Step 4: Backup -> Restore into a fresh database -> Verify row counts and sampled messages
|
|
print("[Track 2 - Step 4] Performing pg_dump backup -> pg_restore into clean DB -> checksum verification...")
|
|
sample_before = psql("messenger", """
|
|
SELECT id::text || ':' || md5(text) || ':' || created_at::text
|
|
FROM messages
|
|
WHERE chat_id = '22222222-2222-4222-8222-222222222222'
|
|
ORDER BY created_at ASC, id ASC
|
|
OFFSET 25000 LIMIT 20;
|
|
""")
|
|
digest_before = hashlib.sha256(sample_before.encode("utf-8")).hexdigest()
|
|
|
|
t_bkp = time.perf_counter()
|
|
run_cmd("docker exec mtusi-lab2-postgres pg_dump -Fc -U messenger -d messenger -f /tmp/lab2_backup.dump")
|
|
backup_ms = round((time.perf_counter() - t_bkp) * 1000.0, 2)
|
|
|
|
psql("postgres", "DROP DATABASE IF EXISTS messenger_restored;")
|
|
psql("postgres", "CREATE DATABASE messenger_restored OWNER messenger;")
|
|
|
|
t_rst = time.perf_counter()
|
|
run_cmd("docker exec mtusi-lab2-postgres pg_restore -U messenger -d messenger_restored /tmp/lab2_backup.dump")
|
|
restore_ms = round((time.perf_counter() - t_rst) * 1000.0, 2)
|
|
|
|
restored_total = int(psql("messenger_restored", "SELECT count(*) FROM messages;"))
|
|
restored_hot = int(psql("messenger_restored", "SELECT count(*) FROM messages WHERE chat_id = '22222222-2222-4222-8222-222222222222';"))
|
|
sample_after = psql("messenger_restored", """
|
|
SELECT id::text || ':' || md5(text) || ':' || created_at::text
|
|
FROM messages
|
|
WHERE chat_id = '22222222-2222-4222-8222-222222222222'
|
|
ORDER BY created_at ASC, id ASC
|
|
OFFSET 25000 LIMIT 20;
|
|
""")
|
|
digest_after = hashlib.sha256(sample_after.encode("utf-8")).hexdigest()
|
|
|
|
# Clean up temporary restored DB and dump file, and remove synthetic 110k rows so DB stays fast for other tests
|
|
psql("postgres", "DROP DATABASE messenger_restored;")
|
|
run_cmd("docker exec mtusi-lab2-postgres rm -f /tmp/lab2_backup.dump")
|
|
psql("messenger", "DELETE FROM chats WHERE title LIKE 'Track2_Skewed_%';")
|
|
|
|
if restored_total != total_messages or digest_before != digest_after:
|
|
raise AssertionError("Backup/restore verification mismatch!")
|
|
|
|
with open("evidence/explain_keyset_100k.txt", "w", encoding="utf-8") as f:
|
|
f.write(plan_keyset_text + "\n")
|
|
|
|
summary = {
|
|
"track": "Track 2: Query Plan on >=100,000 Skewed Messages and Backup/Restore Verification",
|
|
"dataset": {
|
|
"total_messages": total_messages,
|
|
"hot_chat_messages": hot_chat_messages,
|
|
"medium_chats": "4 chats x 5,000 messages = 20,000",
|
|
"small_chats": "10 chats x 1,000 messages = 10,000",
|
|
"deep_pagination_offset_tested": 50000,
|
|
},
|
|
"write_cost_40k_messages": {
|
|
"without_composite_index_ms": write_no_index_ms,
|
|
"with_composite_index_ms": write_with_index_ms,
|
|
"index_write_overhead_pct": round(((write_with_index_ms - write_no_index_ms) / max(1.0, write_no_index_ms)) * 100.0, 2),
|
|
},
|
|
"query_plans_at_depth_50000": {
|
|
"composite_keyset_index": {
|
|
"index": "idx_messages_chat_created_id (chat_id, created_at ASC, id ASC)",
|
|
"query_type": "Keyset: WHERE chat_id = $1 AND (created_at, id) > ($2, $3) ORDER BY created_at ASC, id ASC LIMIT 50",
|
|
"node_type": plan_keyset_json["Plan"]["Node Type"],
|
|
"execution_time_ms": plan_keyset_json["Execution Time"],
|
|
"shared_hit_blocks": plan_keyset_json["Plan"].get("Shared Hit Blocks", 0),
|
|
"shared_read_blocks": plan_keyset_json["Plan"].get("Shared Read Blocks", 0),
|
|
},
|
|
"single_column_index_with_offset": {
|
|
"index": "idx_messages_chat_only (chat_id)",
|
|
"query_type": "Offset: WHERE chat_id = $1 ORDER BY created_at ASC, id ASC OFFSET 50000 LIMIT 50",
|
|
"node_type": plan_offset_json["Plan"]["Node Type"],
|
|
"execution_time_ms": plan_offset_json["Execution Time"],
|
|
"shared_hit_blocks": plan_offset_json["Plan"].get("Shared Hit Blocks", 0),
|
|
"shared_read_blocks": plan_offset_json["Plan"].get("Shared Read Blocks", 0),
|
|
},
|
|
"no_index_seq_scan": {
|
|
"index": "NONE (Seq Scan + Top-N Sort)",
|
|
"query_type": "Keyset without index",
|
|
"node_type": plan_seqscan_json["Plan"]["Node Type"],
|
|
"execution_time_ms": plan_seqscan_json["Execution Time"],
|
|
"shared_hit_blocks": plan_seqscan_json["Plan"].get("Shared Hit Blocks", 0),
|
|
"shared_read_blocks": plan_seqscan_json["Plan"].get("Shared Read Blocks", 0),
|
|
},
|
|
},
|
|
"backup_and_restore": {
|
|
"tool": "pg_dump -Fc / pg_restore",
|
|
"backup_duration_ms": backup_ms,
|
|
"restore_duration_ms": restore_ms,
|
|
"source_messages_count": total_messages,
|
|
"restored_messages_count": restored_total,
|
|
"sample_sha256_before": digest_before,
|
|
"sample_sha256_after": digest_after,
|
|
"exact_match": digest_before == digest_after and total_messages == restored_total,
|
|
},
|
|
}
|
|
|
|
with open("evidence/track2_query_plan_and_backup.json", "w", encoding="utf-8") as f:
|
|
json.dump(summary, f, indent=2)
|
|
|
|
print("PASS: Track 2 experiment completed! Saved to evidence/track2_query_plan_and_backup.json")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|