Files
mtusi2026lab4/student-tests/research.py

124 lines
7.3 KiB
Python

"""Track 2 fault injection and measured traversal; use only synthetic lab4 data."""
import concurrent.futures
import datetime as dt
import hashlib
import io
import json
from pathlib import Path
import sys
import time
import uuid
import psycopg
from psycopg.rows import dict_row
sys.path[:0] = [str(Path.cwd() / 'tests'), '/app/src']
from client import Client
from objects import Objects
from postgres import setting, Store
from reconcile import reconcile
def main():
c = Client()
alice, bob, eve, chat = c.bootstrap()
good, content = c.attachment(alice, chat)
message = c.message(alice, chat, '', attachments=[good['id']])['json']
sha = hashlib.sha256(content).hexdigest()
objects = Objects(setting)
report = {'method': 'real S3 and PostgreSQL, per-run fixed cutoff, synthetic data, 2s test grace; production >=3600s', 'checks': {}, 'passes': []}
with psycopg.connect(setting('DATABASE_URL'), autocommit=True, row_factory=dict_row) as conn:
def row(attachment_id):
return conn.execute('SELECT * FROM attachments WHERE 1=1 AND id = %s', (attachment_id,)).fetchone()
def aged(attachment_id):
conn.execute("UPDATE attachments SET updated_at = clock_timestamp() - INTERVAL '2 hours' WHERE 1=1 AND id = %s", (attachment_id,))
def intent(state='uploading'):
aid = uuid.uuid4()
conn.execute('''
INSERT INTO attachments (id, chat_id, owner_id, filename, object_key, content_type, size_bytes, sha256, state, updated_at)
VALUES (%s, %s, %s, 'research.png', %s, 'image/png', %s, %s, %s, clock_timestamp() - INTERVAL '2 hours')
''', (aid, chat['id'], alice['id'], 'originals/' + str(aid), len(content), sha, state))
return str(aid)
# Fail precisely after successful S3 PUT, before the ready UPDATE/COMMIT.
broken_name = 'fault_' + uuid.uuid4().hex + '.png'
trigger = 'research_' + uuid.uuid4().hex
try:
from psycopg import sql
conn.execute(sql.SQL('''CREATE FUNCTION {}() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF NEW.state = 'ready' AND NEW.filename = '{}' THEN
RAISE EXCEPTION 'synthetic research failure';
END IF;
RETURN NEW;
END $$''').format(sql.Identifier(trigger), sql.SQL(broken_name)))
conn.execute(sql.SQL('CREATE TRIGGER {} BEFORE UPDATE ON attachments FOR EACH ROW EXECUTE FUNCTION {}()').format(sql.Identifier(trigger), sql.Identifier(trigger)))
c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=' + broken_name, 503, actor=alice, raw=content, headers={'Content-Type': 'image/png'})
failed = conn.execute('SELECT id, state, object_key FROM attachments WHERE 1=1 AND filename = %s', (broken_name,)).fetchone()
assert failed['state'] == 'uploading' and objects.head(failed['object_key']) is not None
aged(failed['id'])
finally:
conn.execute(sql.SQL('DROP TRIGGER IF EXISTS {} ON attachments').format(sql.Identifier(trigger)))
conn.execute(sql.SQL('DROP FUNCTION IF EXISTS {}()').format(sql.Identifier(trigger)))
absent = intent() # DB intent exists, S3 PUT never happened (process died first).
missing, _ = c.attachment(alice, chat)
c.message(alice, chat, 'keep missing reference', attachments=[missing['id']])
missing_key = 'originals/' + missing['id']
objects.delete(missing_key) # S3-side loss; referenced metadata must never be erased.
aged(missing['id'])
orphan_key = 'originals/' + str(uuid.uuid4())
objects.put(orphan_key, io.BytesIO(content), len(content), 'image/png', sha) # no DB row
aged(good['id'])
# Wait real object age; don't forge LastModified or replace the S3 clock.
time.sleep(3)
fresh_key = 'originals/' + str(uuid.uuid4())
objects.put(fresh_key, io.BytesIO(content), len(content), 'image/png', sha)
fresh_intent = intent()
conn.execute('UPDATE attachments SET updated_at = clock_timestamp() WHERE 1=1 AND id = %s', (fresh_intent,))
locked = intent()
# Hold the same lock as a live uploader while reconciliation runs.
with psycopg.connect(setting('DATABASE_URL')) as uploading:
uploading.execute('SELECT id FROM attachments WHERE 1=1 AND id = %s FOR UPDATE', (locked,))
dry = reconcile(False, 2)
assert row(failed['id']) and row(absent) and row(missing['id'])['state'] == 'ready'
assert objects.head(orphan_key) is not None
report['checks']['dry_run_mutates_nothing'] = True
fixed = reconcile(True, 2)
assert row(failed['id']) is None and row(absent) is None
assert objects.head(failed['object_key']) is None and objects.head(orphan_key) is None
assert row(missing['id'])['state'] == 'storage_missing'
assert row(locked) is not None and fixed['counts']['skipped_locked'] >= 1
assert row(fresh_intent) is not None and objects.head(fresh_key) is not None
assert row(good['id'])['state'] == 'ready' and objects.head('originals/' + good['id']) is not None
report['checks'].update(stale_intents_and_orphans_cleaned=True, fresh_and_locked_retained=True, used_ready_retained=True, missing_reference_retained=True)
repeat = reconcile(True, 2)
assert repeat['counts']['deleted_objects'] == 0 and repeat['counts']['marked_missing'] == 0
report['checks']['apply_repeat_idempotent'] = True
c.call('GET', '/api/v1/attachments/' + missing['id'] + '/content', 503, actor=bob)
# Restore exact original from the test's external copy; reconciler can't invent lost bytes.
objects.put(missing_key, io.BytesIO(content), len(content), 'image/png', sha)
aged(missing['id'])
recovered = reconcile(True, 2)
assert row(missing['id'])['state'] == 'ready'
assert c.call('GET', '/api/v1/attachments/' + missing['id'] + '/content', actor=bob)['bytes'] == content
report['checks']['restore_after_sha256_verification'] = True
# Verify metadata FK and existing message survive every repair.
assert conn.execute('SELECT 1 FROM message_attachments WHERE 1=1 AND message_id = %s AND attachment_id = %s', (message['id'], good['id'])).fetchone()
report['passes'] = [dict(name=n, **v) for n, v in [('dry_run', dry), ('apply', fixed), ('repeat', repeat), ('recover', recovered)]]
# Clean up only new unattached diagnostic keys/intents; confirmed files remain.
objects.delete(fresh_key)
for aid in [fresh_intent, locked]:
conn.execute("DELETE FROM attachments WHERE 1=1 AND id = %s AND state = 'uploading'", (aid,))
# Measure bounded scans at three populations; 3 repeats, no writes during scan.
report['scan_cost'] = []
for extra in [0, 100, 400]:
for _ in range(extra):
aid = intent('ready')
objects.put('originals/' + aid, io.BytesIO(content), len(content), 'image/png', sha)
for repetition in range(3):
scan = reconcile(False, 2)
report['scan_cost'].append({'repetition': repetition + 1, **scan})
print(json.dumps(report, indent=2))
if __name__ == '__main__':
main()