47 lines
2.8 KiB
Python
47 lines
2.8 KiB
Python
#!/usr/bin/env python3
|
|
"""Repeatable grade-4 index experiment: SQL plans on 10000 fresh synthetic messages."""
|
|
import json
|
|
from uuid import uuid4
|
|
import psycopg
|
|
from psycopg.rows import dict_row
|
|
from messenger.db import setting
|
|
from messenger.security import HASHER
|
|
|
|
|
|
def main():
|
|
uid, cid = uuid4(), uuid4()
|
|
with psycopg.connect(setting('DATABASE_URL'), row_factory=dict_row) as conn:
|
|
conn.execute('INSERT INTO users(id,username,display_name,password_hash) VALUES (%s,%s,%s,%s)',
|
|
(uid, 'plan_' + uuid4().hex[:24], 'Synthetic plan user', HASHER.hash(str(uuid4()))))
|
|
conn.execute('INSERT INTO chats(id,title) VALUES (%s,%s)', (cid, 'Synthetic 10000-message index experiment'))
|
|
conn.execute('INSERT INTO chat_members(chat_id,user_id) VALUES (%s,%s)', (cid, uid))
|
|
conn.execute("INSERT INTO messages(id,chat_id,sender_id,text,created_at) SELECT gen_random_uuid(),%s,%s, 'Synthetic message '||n, timestamptz '2026-01-01T00:00:00Z' + n * interval '1 millisecond' FROM generate_series(1,10000) AS n", (cid, uid))
|
|
with psycopg.connect(setting('DATABASE_URL'), row_factory=dict_row, autocommit=True) as conn:
|
|
conn.execute('ANALYZE messages')
|
|
# OFFSET is used only to choose an experimental pivot, never by the application pagination.
|
|
pivot = conn.execute('SELECT created_at,id FROM messages WHERE chat_id=%s ORDER BY created_at,id OFFSET 9000 LIMIT 1', (cid,)).fetchone()
|
|
result = {'messages_in_chat': 10000, 'limit_plus_one': 51,
|
|
'index': 'messages_history_idx (chat_id, created_at, id)',
|
|
'first_sql': 'SELECT id,chat_id,sender_id,text,created_at FROM messages WHERE chat_id=$1 ORDER BY created_at,id LIMIT 51',
|
|
'deep_sql': 'SELECT id,chat_id,sender_id,text,created_at FROM messages WHERE chat_id=$1 AND (created_at,id)>($2,$3) ORDER BY created_at,id LIMIT 51',
|
|
'first': None, 'deep_after_9001': None}
|
|
for key, condition, params in [
|
|
('first', '', (cid,)),
|
|
('deep_after_9001', ' AND (created_at,id) > (%s,%s)', (cid, pivot['created_at'], pivot['id']))
|
|
]:
|
|
plan = conn.execute('EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) SELECT id,chat_id,sender_id,text,created_at FROM messages WHERE chat_id=%s'+condition+' ORDER BY created_at,id LIMIT 51', params).fetchone()['QUERY PLAN'][0]
|
|
result[key] = plan
|
|
nodes = [plan['Plan']]
|
|
index_found = False
|
|
while nodes:
|
|
node = nodes.pop()
|
|
index_found |= node.get('Index Name') == 'messages_history_idx'
|
|
nodes.extend(node.get('Plans', []))
|
|
if not index_found:
|
|
raise RuntimeError('Planner did not use history index: ' + key)
|
|
print(json.dumps(result, indent=2, default=str))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|