Files
mtusi2026lab4/student-tests/research.py
T

105 lines
6.6 KiB
Python

"""Track 2: injected PostgreSQL/S3 faults, dry-run, repeatability and scan cost."""
import concurrent.futures
import hashlib
import json
import threading
import time
import uuid
from common import ROOT, Client, check, command, compose, mc, sql, reconcile, save
def objects():
raw=mc('mc ls --json --recursive local/messenger-attachments/original/')
# mc lists keys relative to the supplied prefix.
return {'original/'+line['key'].removeprefix('original/') for line in
(json.loads(x) for x in raw.splitlines() if x.strip()) if line.get('type')=='file'}
def main():
c=Client(timeout=40);alice,bob,eve,chat=c.bootstrap()
original=(ROOT/'tests/fixtures/sample.png').read_bytes()
path='/api/v1/chats/'+chat['id']+'/attachments?filename='
used,_=c.attachment(alice,chat)
missing,_=c.attachment(alice,chat)
c.message(alice,chat,'referenced old attachment',attachments=[used['id'],missing['id']])
baseline=objects()
marker='fault_'+uuid.uuid4().hex+'.png'
# Fault only our unique synthetic filename. No production test hooks.
sql("CREATE FUNCTION student_reject_attachment() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.filename='"+marker+"' THEN RAISE EXCEPTION 'injected metadata failure'; END IF; RETURN NEW; END $$; CREATE TRIGGER student_reject_attachment BEFORE INSERT ON attachments FOR EACH ROW EXECUTE FUNCTION student_reject_attachment()")
try:
c.call('POST',path+marker,503,actor=alice,raw=original,headers={'Content-Type':'image/png'})
finally:
sql('DROP TRIGGER IF EXISTS student_reject_attachment ON attachments; DROP FUNCTION IF EXISTS student_reject_attachment()')
orphaned=objects()-baseline
check(len(orphaned)==1,'injected commit-side failure did not leave exactly one orphan')
old_orphan=next(iter(orphaned))
check(sql("SELECT count(*) FROM attachments WHERE object_key='"+old_orphan+"'")=='0','orphan has metadata')
print('Waiting 65 seconds for the real S3 LastModified grace (no timestamp forgery).',flush=True)
deadline=time.monotonic()+65
while time.monotonic()<deadline:time.sleep(min(1,deadline-time.monotonic()))
# Fresh orphan is uploaded with admin fixture tools; private, unique key.
fresh_key='original/'+str(uuid.uuid4())
mc("printf 'fresh-uncommitted-fixture' >/tmp/fresh; mc cp /tmp/fresh local/messenger-attachments/"+fresh_key+" >/dev/null")
mc('mc rm local/messenger-attachments/original/'+missing['id']+' >/dev/null')
metadata_before=sql('SELECT count(*) FROM attachments')
before=objects()
dry=reconcile(False)
check(dry['old_orphans']>=1 and dry['missing']>=1,'dry-run did not detect both failure directions')
check(objects()==before,'dry-run changed S3')
check(sql("SELECT missing_since IS NULL FROM attachments WHERE id='"+missing['id']+"'")=='t','dry-run changed DB')
apply=reconcile(True)
after=objects()
check(old_orphan not in after,'old orphan not removed')
check(fresh_key in after,'fresh orphan was deleted')
check('original/'+used['id'] in after,'referenced object was deleted')
check(sql('SELECT count(*) FROM attachments')==metadata_before,'missing metadata was deleted')
check(sql("SELECT count(*) FROM message_attachments WHERE attachment_id='"+missing['id']+"'")=='1','message reference was lost')
c.call('GET','/api/v1/attachments/'+missing['id'],503,actor=bob)
c.call('GET','/api/v1/attachments/'+missing['id'],404,actor=eve)
repeat=reconcile(True)
check(repeat['deleted']==0 and repeat['marked_unavailable']==0,'second apply is not idempotent')
# Restore exact bytes from the fixture; only matching SHA-256 clears marker.
# Binary stdin avoids encoding files or credential-bearing process args.
import subprocess
script=('set -eu\nmc alias set local http://s3:9000 "$(cat /run/secrets/s3_root_user)" '
'"$(cat /run/secrets/s3_root_password)" >/dev/null\n'
'cat >/tmp/original; mc cp /tmp/original local/messenger-attachments/original/'+missing['id']+' >/dev/null')
subprocess.run(['docker','compose','run','--rm','--no-deps','-T','--entrypoint','/bin/sh','s3-init','-c',script],
cwd=ROOT,input=original,stdout=subprocess.DEVNULL,check=True,timeout=60)
recovered=reconcile(True)
check(recovered['recovered']==1 and recovered['cleared_unavailable']==1,'restore not verified/repaired')
check(c.call('GET','/api/v1/attachments/'+missing['id']+'/content',actor=bob)['bytes']==original,'restored bytes differ')
# Reconciler while legitimate concurrent uploads commit: no live object loss.
barrier=threading.Barrier(4)
def upload(_):
client=Client(timeout=40)
barrier.wait(timeout=90)
return client.call('POST',path+'race.png',[201,503],actor=alice,raw=original,headers={'Content-Type':'image/png'})
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool:
pending=[pool.submit(upload,i) for i in range(3)]
barrier.wait(timeout=90)
during=reconcile(True)
created=[json.loads(x['bytes']) for x in (f.result() for f in pending) if x['status']==201]
for item in created:
check(c.call('GET','/api/v1/attachments/'+item['id']+'/content',actor=bob)['bytes']==original,'concurrent upload was deleted')
# Two scan sizes with controlled synthetic orphans. None are eligible during
# measurement; their cleanup is the ordinary grace-based reconciler task.
counts=[]
for batch in (10,100):
keys=['original/'+str(uuid.uuid4()) for _ in range(batch)]
mc("printf 'scan-fixture' >/tmp/scan\n"+'\n'.join("mc cp /tmp/scan local/messenger-attachments/"+k+" >/dev/null" for k in keys))
timings=[reconcile(False) for _ in range(3)]
counts.append({'added_objects':batch,'runs':timings})
final=reconcile(False)
save('research.json',{'complete':True,'track':2,'grace_seconds':60,
'hypothesis':'Per-key locks, durable PostgreSQL rechecks and age threshold remove only old unreferenced objects; missing metadata is retained and recoverable.',
'faults':['PostgreSQL INSERT exception after successful S3 PUT','S3 object removed after acknowledged upload'],
'dry_run':dry,'apply':apply,'repeat_apply':repeat,'recovery':recovered,'concurrent':during,
'fresh_orphan_protected':fresh_key in objects(),'used_original_checksum':hashlib.sha256(original).hexdigest(),
'scan_cost':counts,'final':final})
print('PASS Track 2: both failures, dry-run, repair, repeat, fresh/used protection and measured scan cost')
if __name__=='__main__':
main()