Files
mtusi2026lab3-fork/student-tests/storage.py

87 lines
4.3 KiB
Python

#!/usr/bin/env python3
"""Run inside API image: real SQL rollback, idempotency atomicity and index evidence."""
from pathlib import Path
import sys
import uuid
sys.path.insert(0, '/app/src')
from messenger.cache import SessionCache
from messenger.config import Config
from messenger.db import Database
from messenger.errors import InvalidRequest
from messenger.security import hash_password
from messenger.store import Store
def main():
config = Config.from_env()
db = Database(config)
db.open()
store = Store(config, db, SessionCache(config))
suffix = uuid.uuid4().hex[:10]
actor = store.create_user('sql_' + suffix, 'SQL synthetic', hash_password('test-password-123'))
try:
with db.cursor() as cur:
cur.execute('SELECT count(*) AS n FROM chats')
before = cur.fetchone()['n']
try:
store.create_chat('Must rollback', [actor['id'], str(uuid.uuid4())])
raise AssertionError('unknown member was accepted')
except InvalidRequest:
pass
with db.cursor() as cur:
cur.execute('SELECT count(*) AS n FROM chats')
assert cur.fetchone()['n'] == before, 'partial chat survived rollback'
print('PASS: actual multi-statement chat transaction rollback')
chat = store.create_chat('SQL test', [actor['id']])
function = 'test_reject_' + suffix
key = 'rollback-' + suffix
# Simulate failure between message INSERT and idempotency result INSERT.
# Unique function/key isolate this synthetic test from every other request.
with db.cursor() as cur:
cur.execute("CREATE FUNCTION " + function + "() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN "
"IF NEW.key = '" + key + "' THEN RAISE EXCEPTION 'synthetic rollback'; END IF; RETURN NEW; END $$")
cur.execute('CREATE TRIGGER ' + function + ' BEFORE INSERT ON message_idempotency '
'FOR EACH ROW EXECUTE FUNCTION ' + function + '()')
try:
try:
store.add_message(chat['id'], actor['id'], 'must rollback', key)
raise AssertionError('injected failure did not occur')
except Exception as exc:
assert 'synthetic rollback' in str(exc), type(exc).__name__
with db.cursor() as cur:
cur.execute('SELECT count(*) AS n FROM messages WHERE chat_id=%s', (chat['id'],))
assert cur.fetchone()['n'] == 0, 'message committed without replay record'
finally:
with db.cursor() as cur:
cur.execute('DROP TRIGGER ' + function + ' ON message_idempotency')
cur.execute('DROP FUNCTION ' + function + '()')
message = store.add_message(chat['id'], actor['id'], 'must rollback', key)
assert store.add_message(chat['id'], actor['id'], 'must rollback', key) == message
print('PASS: message/result atomic rollback; same key usable after transient failure')
with db.cursor() as cur:
cur.execute('INSERT INTO messages(id,chat_id,sender_id,text,created_at) '
"SELECT gen_random_uuid(),%s,%s,'index-'||g, '2026-01-01'::timestamptz+g*interval '1 second' "
'FROM generate_series(1,10000) AS g', (chat['id'], actor['id']))
cur.execute('ANALYZE messages')
cur.execute('EXPLAIN (ANALYZE, BUFFERS) SELECT id,chat_id,sender_id,text,created_at '
'FROM messages WHERE chat_id=%s ORDER BY created_at,id LIMIT 51', (chat['id'],))
plan = '\n'.join(row['QUERY PLAN'] for row in cur.fetchall())
assert 'idx_messages_chat_created_id' in plan and 'Index Scan' in plan, plan
print(plan)
print('PASS: history index on at least 10000 messages')
db.run_migrations()
db.run_migrations()
with db.cursor() as cur:
cur.execute('SELECT name FROM schema_migrations ORDER BY name')
assert [r['name'] for r in cur.fetchall()] == ['0001_init.sql', '0002_idempotency.sql']
cur.execute('SELECT count(*) AS n FROM messages WHERE chat_id=%s', (chat['id'],))
assert cur.fetchone()['n'] == 10001
print('PASS: repeated versioned migrations preserved existing messages')
finally:
db.close()
if __name__ == '__main__':
main()