#!/usr/bin/env python3 """Track2: actual DB/S3 failures, grace, locking, repeat repairs and scan cost.""" import json import subprocess import time import uuid from helpers import Client, Probe, ROOT, STACK, check, containers, docker, png, reconcile, save, sql, upload, wait_ready def objects(probe): raw = probe.mc('ls','--recursive','--json','local/attachments',admin=True).stdout.decode() return {json.loads(line)['key'] for line in raw.splitlines() if json.loads(line).get('type')=='file'} def main(): c = Client(timeout=55) alice,bob,_,chat = c.bootstrap() data = png() experiment = uuid.uuid4().hex result = {'hypothesis':'fixed grace plus per-object transaction lock permits repeatable repair without deleting fresh or linked data', 'grace_seconds':90, 'faults':{}, 'cost':[]} with Probe() as probe: # Inject a failure exactly between successful S3 PUT and PostgreSQL INSERT. before = objects(probe) filename = 'db-fault-'+experiment+'.png' sql("CREATE FUNCTION lab4_inject_failure() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.filename='"+filename+"' THEN RAISE EXCEPTION 'lab4 injected DB failure'; END IF; RETURN NEW; END; $$; CREATE TRIGGER lab4_inject_failure BEFORE INSERT ON attachments FOR EACH ROW EXECUTE FUNCTION lab4_inject_failure();") try: upload(c,alice,chat,data,filename=filename,expected=503) finally: sql('DROP TRIGGER lab4_inject_failure ON attachments; DROP FUNCTION lab4_inject_failure();') orphans = objects(probe)-before check(len(orphans)==1,'DB failure did not leave the expected one unconfirmed S3 object') orphan = next(iter(orphans)) check(sql("SELECT count(*) FROM attachments WHERE filename='"+filename+"';")=='0','failed metadata INSERT published a row') born = time.monotonic() result['faults']['s3_put_db_insert_failure'] = {'upload_status':503, 'objects_without_metadata':1} fresh = reconcile(apply=True) check(orphan in objects(probe),'fresh orphan removed before grace') result['fresh_orphan_preserved'] = fresh['fresh_skipped']>0 # Keep one old linked object and remove a second original behind PostgreSQL. live = upload(c,alice,chat,data)['json'] c.message(alice,chat,'keep live original',attachments=[live['id']]) missing = upload(c,alice,chat,data)['json'] message = c.message(alice,chat,'keep missing reference',attachments=[missing['id']])['json'] missing_key = sql("SELECT object_key FROM attachments WHERE id='"+missing['id']+"';") probe.mc('rm','local/attachments/'+missing_key,admin=True) current = reconcile(apply=True) check(sql("SELECT status FROM attachments WHERE id='"+missing['id']+"';")=='ready','fresh metadata changed before grace') result['fresh_metadata_preserved'] = current['fresh_skipped']>0 # Measure a real scan at two bucket sizes, crossing an S3 page boundary. cost_prefix = 'original/cost-'+experiment+'/' try: for group,count,total in (('small',100,100),('extra',1000,1100)): script = ('mkdir -p /tmp/cost/"$1"; i=1; while [ "$i" -le "$2" ]; do ' 'printf x > /tmp/cost/"$1"/"$i"; i=$((i+1)); done') docker('exec',probe.container,'/bin/sh','-c',script,'sh',group,str(count)) probe.mc('mirror','--quiet','/tmp/cost/'+group,'local/attachments/'+cost_prefix+group,admin=True) summary = reconcile() check(summary['objects_scanned']>=total,'scan skipped S3 objects') result['cost'].append({'phase':'fresh', 'synthetic_objects':total, **summary}) print('Fresh scan cost:',json.dumps({k:summary[k] for k in ('objects_scanned','metadata_scanned','list_requests_estimate','stat_requests','db_queries','duration_ms')}),flush=True) print('Waiting92s for actual S3 timestamps: measuring aged-object locking, DB and HEAD cost next.',flush=True) time.sleep(92) for total in (1100,100): summary = reconcile() check(summary['orphans']>=total,'aged scan did not inspect all orphan fixtures') result['cost'].append({'phase':'aged', 'synthetic_objects':total, **summary}) print('Aged scan cost:',json.dumps({k:summary[k] for k in ('objects_scanned','metadata_scanned','list_requests_estimate','stat_requests','db_queries','duration_ms')}),flush=True) if total==1100: probe.mc('rm','--recursive','--force','local/attachments/'+cost_prefix+'extra/',admin=True) finally: probe.mc('rm','--recursive','--force','local/attachments/'+cost_prefix,admin=True) # S3/DB unavailability must stop reconciliation without destructive guesses. for service in ('minio','postgres'): try: docker('service','scale','--detach',STACK+'_'+service+'=0') deadline=time.monotonic()+30 while time.monotonic()0: print('Waiting for actual S3 object age to exceed90s grace:',round(remaining,1),'seconds',flush=True) time.sleep(remaining) sql("UPDATE attachments SET created_at=clock_timestamp()-interval '10 minutes' WHERE id IN ('"+live['id']+"','"+missing['id']+"');") # A second process holds the upload lock: even an old orphan is protected. lock_script = "BEGIN; SELECT pg_advisory_xact_lock(hashtextextended('"+orphan+"',0));\n" lock = subprocess.Popen(['docker','exec','-i',containers('postgres')[0],'psql','-U','messenger','-d','messenger','-At','-v','ON_ERROR_STOP=1'],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE) lock.stdin.write(lock_script.encode()); lock.stdin.flush() try: deadline = time.monotonic()+10 while sql("SELECT pg_try_advisory_xact_lock(hashtextextended('"+orphan+"',0));") != 'f': check(time.monotonic()=1 and orphan in objects(probe),'upload lock did not protect orphan') finally: lock.stdin.write(b'ROLLBACK;\n'); lock.stdin.close() lock.wait(timeout=15) result['locked_candidate_preserved'] = True # The apply above may mark the aged missing row; restore only its internal state # to compare the following dry-run with an unchanged, well-defined fixture. sql("UPDATE attachments SET status='ready',error_code=NULL WHERE id='"+missing['id']+"';") dry = reconcile() check(dry['orphans']>=1 and dry['missing']>=1,'dry-run did not detect injected inconsistencies') check(orphan in objects(probe),'dry-run deleted an object') check(sql("SELECT status FROM attachments WHERE id='"+missing['id']+"';")=='ready','dry-run modified metadata') applied = reconcile(apply=True) check(orphan not in objects(probe),'apply did not delete old orphan') check(sql("SELECT status FROM attachments WHERE id='"+missing['id']+"';")=='failed','missing original not marked failed') check(sql("SELECT count(*) FROM messages WHERE id='"+message['id']+"' AND '"+missing['id']+"'::uuid=ANY(attachment_ids);")=='1','repair deleted linked metadata or reference') c.call('GET','/api/v1/attachments/'+missing['id'],409,actor=alice) check(c.call('GET','/api/v1/attachments/'+live['id']+'/content',actor=bob)['bytes']==data,'repair deleted a live linked original') repeated = reconcile(apply=True) check(repeated['deleted']==0 and repeated['marked_failed']==0,'repeat apply was not idempotent') result.update({'dry_run':dry, 'apply':applied, 'repeat_apply':repeated, 'live_linked_preserved':True, 'missing_linked_reference_preserved':True}) save('lab4-reconciliation.json',result) print('PASS: real two-store faults, grace, lock, dry-run/apply/repeat, linked data preserved and paginated scan cost.') if __name__=='__main__': main()