Files
mtusi2026lab2/student-tests/research_worker.py
T
2026-11-05 01:43:30 +03:00

86 lines
6.5 KiB
Python

"""Executed inside API container by research.py, only in fresh research databases."""
import hashlib,json,os,statistics,sys,time,uuid
from pathlib import Path
import psycopg
from psycopg.conninfo import make_conninfo
from psycopg.rows import dict_row
mode,dbname=sys.argv[1:3]
if not dbname.startswith('lab2_study_') or not dbname.replace('_','').isalnum():
raise ValueError('Expected isolated study database name')
base=Path(os.environ['DATABASE_URL_FILE']).read_text().strip()
dsn=make_conninfo(base,dbname=dbname, **({"host":sys.argv[3]} if len(sys.argv)>3 else {}))
def fingerprint(conn):
counts={t:conn.execute('SELECT count(*) AS n FROM '+t).fetchone()['n'] for t in ['users','chats','members','messages','sessions','schema_migrations']}
digest=hashlib.sha256()
with conn.cursor(name='verify_messages') as cur:
cur.execute('SELECT id,chat_id,sender_id,text,created_at FROM messages ORDER BY id')
for row in cur:
digest.update(json.dumps(row,sort_keys=True,default=str,ensure_ascii=False).encode()+b'\n')
samples=conn.execute("SELECT id,chat_id,sender_id,text,created_at FROM messages WHERE id IN (md5('message-1')::uuid,md5('message-100000')::uuid,md5('message-120000')::uuid) ORDER BY id").fetchall()
return {'counts':counts,'messages_sha256':digest.hexdigest(),'samples':samples}
if mode=='prepare':
with psycopg.connect(base,autocommit=True) as admin:
from psycopg import sql
admin.execute(sql.SQL('CREATE DATABASE {}').format(sql.Identifier(dbname)))
with psycopg.connect(dsn,row_factory=dict_row) as conn:
conn.execute('CREATE TABLE schema_migrations(version text PRIMARY KEY,applied_at timestamptz NOT NULL DEFAULT clock_timestamp())')
for path in sorted(Path('/app/migrations').glob('*.sql')):
conn.execute(path.read_text());conn.execute('INSERT INTO schema_migrations(version) VALUES(%s)',(path.name,))
conn.execute("INSERT INTO users(id,username,display_name,password_hash) VALUES(md5('research-user')::uuid,'research_user','Synthetic benchmark user','not-a-login-account')")
conn.execute("INSERT INTO chats(id,title) SELECT md5('chat-'||n)::uuid,'Synthetic chat '||n FROM generate_series(0,101) n")
conn.execute("INSERT INTO members(chat_id,user_id) SELECT id,md5('research-user')::uuid FROM chats")
conn.execute("""INSERT INTO messages(id,chat_id,sender_id,text,created_at)
SELECT md5('message-'||n)::uuid,
md5('chat-'||(CASE WHEN n<=100000 THEN 0 WHEN n<=119000 THEN 1 ELSE 2+(n-119001)%100 END))::uuid,
md5('research-user')::uuid,'synthetic-'||n||'-'||repeat('x',64+n%512),
timestamptz '2026-01-01 00:00:00+00'+ n * interval '1 microsecond'
FROM generate_series(1,120000) n""")
conn.execute('ANALYZE messages')
print(json.dumps({'created':dbname,'messages':120000,'distribution':'100000 + 19000 + 100*10','synthetic_only':True}))
elif mode=='benchmark':
query='SELECT * FROM messages WHERE chat_id=%s AND (created_at,id)>(%s,%s) ORDER BY created_at,id LIMIT 51'
specs=[('hot-middle',0,'2026-01-01T00:00:00.050000Z'),('medium-first',1,'2026-01-01T00:00:00Z'),('tiny-first',101,'2026-01-01T00:00:00Z')]
output={'messages':120000,'warmup':3,'measured_reads':20,'rounds':3,'write_batch':5000,'results':[],'query':query}
with psycopg.connect(dsn,row_factory=dict_row) as conn:
for round_no in range(3):
# Alternate order to reduce systematic warmup/order bias.
variants=['global','chat_first'] if round_no%2==0 else ['chat_first','global']
for variant in variants:
conn.execute('DROP INDEX IF EXISTS messages_history');conn.execute('DROP INDEX IF EXISTS messages_global')
definition=('CREATE INDEX messages_history ON messages(chat_id,created_at,id)' if variant=='chat_first' else 'CREATE INDEX messages_global ON messages(created_at,id)')
start=time.perf_counter();conn.execute(definition);conn.commit();build_ms=(time.perf_counter()-start)*1000
conn.execute('ANALYZE messages');conn.commit()
record={'round':round_no+1,'variant':variant,'definition':definition,'index_build_ms':build_ms,'queries':[]}
for name,chat_no,stamp in specs:
args=(str(uuid.UUID(hashlib.md5(('chat-'+str(chat_no)).encode()).hexdigest())),stamp,str(uuid.UUID(int=0)))
for _ in range(3):conn.execute(query,args).fetchall()
times=[]
for _ in range(20):
start=time.perf_counter();rows=conn.execute(query,args).fetchall();times.append((time.perf_counter()-start)*1000)
plan=conn.execute('EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) '+query,args).fetchone()['QUERY PLAN'][0]
record['queries'].append({'scenario':name,'rows':len(rows),'median_ms':statistics.median(times),'p95_ms':sorted(times)[18],'raw_ms':times,'explain':plan})
conn.commit()
# Real inserts, full constraints/index maintenance, then rollback to keep all variants at 120k rows.
start=time.perf_counter()
conn.execute("""INSERT INTO messages(id,chat_id,sender_id,text,created_at)
SELECT md5('write-cost-'||n)::uuid,md5('chat-0')::uuid,md5('research-user')::uuid,
'synthetic-write-'||n,timestamptz '2026-01-02 00:00:00+00'+n*interval '1 microsecond'
FROM generate_series(1,5000) n""")
record['insert_5000_ms']=(time.perf_counter()-start)*1000
conn.rollback()
# Clean up dead tuples from rollback, without changing measured data volume.
with psycopg.connect(dsn,autocommit=True) as vacuum: vacuum.execute('VACUUM ANALYZE messages')
record['index_bytes']=conn.execute("SELECT pg_relation_size(%s) AS bytes",('messages_history' if variant=='chat_first' else 'messages_global',)).fetchone()['bytes']
conn.commit();output['results'].append(record)
conn.execute('DROP INDEX IF EXISTS messages_global');conn.execute('DROP INDEX IF EXISTS messages_history')
conn.execute('CREATE INDEX messages_history ON messages(chat_id,created_at,id)');conn.commit()
output['fingerprint']=fingerprint(conn)
print(json.dumps(output,default=str,ensure_ascii=False))
elif mode=='verify':
with psycopg.connect(dsn,row_factory=dict_row) as conn:
print(json.dumps(fingerprint(conn),default=str,ensure_ascii=False))
else: raise ValueError('Unknown study mode')