#!/usr/bin/env python3 """Explicit real fault injection; emits IDs/results, never session tokens.""" import json from pathlib import Path import subprocess import sys import time import uuid ROOT=Path(__file__).resolve().parents[1] sys.path.insert(0,str(ROOT/'tests')) from client import Client,check def compose(*args): if args and args[0]=='start': args=('up','-d','--no-deps',*args[1:]) result=subprocess.run(['docker','compose',*args],cwd=ROOT,capture_output=True,text=True,timeout=120) if result.returncode: raise RuntimeError(result.stderr) return result.stdout def inside(body,**values): script="import json,io,time\nfrom uuid import UUID\nfrom messenger.db import Database\nfrom messenger.object_store import ObjectStore\nfrom messenger.jobs import work,replay,broker_client,STREAM\nfrom psycopg.types.json import Jsonb\ndb=Database();db.open();store=ObjectStore()\nv="+repr(values)+'\n'+body+'\nprint(json.dumps(result,default=str))\nstore.close();db.close()' proc=subprocess.run(['docker','compose','exec','-T','api','python','-'],cwd=ROOT,input=script,capture_output=True,text=True,timeout=120) if proc.returncode: raise RuntimeError(proc.stderr) return json.loads(proc.stdout) def state(aid): return inside("with db.pool.connection() as c:\n result=c.execute('SELECT a.status,a.staging_key,j.id AS job_id,j.attempt,j.lease_until,o.dispatched_at FROM attachments a JOIN attachment_jobs j ON j.attachment_id=a.id JOIN job_outbox o ON o.job_id=j.id WHERE a.id=%s',(v[\"aid\"],)).fetchone()",aid=aid) def wait_for(predicate,seconds=30): end=time.monotonic()+seconds while time.monotonic()0};obj.close()",aid=target['id']) compose('kill','-s','SIGKILL','worker') # unless-stopped can restart a killed worker; stop it to retain the fault boundary. compose('stop','worker') inside("with db.pool.connection() as c:\n c.execute('DROP TRIGGER lab5_pause ON attachments');c.execute('DROP FUNCTION lab5_pause_ready()')\nresult=True") trigger=False crashed=state(target['id']);check(crashed['attempt']==1,'expected first leased attempt') print('Waiting for real 90s lease expiry after killed worker.',flush=True) started=time.monotonic() wait_for(lambda: state(target['id'])['status']=='queued',110) compose('start','worker') ready(c,bob,target) after=state(target['id']) evidence['after_put_before_ack']={**observed,'lease_recovery_seconds':round(time.monotonic()-started,3),'attempt_after_recovery':after['attempt'],'same_job':after['job_id']==crashed['job_id']} # Re-deliver the completed original job. Ready metadata is immutable. original_meta=c.call('GET','/api/v1/attachments/'+target['id'],actor=alice,schema='Attachment')['json'] duplicate=inside("result=work(db,store,v['job'],1)",job=after['job_id']) check(duplicate and c.call('GET','/api/v1/attachments/'+target['id'],actor=alice,schema='Attachment')['json']==original_meta,'duplicate changed ready result') evidence['duplicate']={'ready_noop':True} # Retry exhaustion with real missing staging (transient storage failure), explicit replay. compose('stop','worker','relay') failed,failed_raw=c.attachment(alice,chat) st=state(failed['id']) inside("store.delete(v['key']);result=True",key=st['staging_key']) for attempt in range(5): inside("with db.pool.connection() as c:\n c.execute('UPDATE attachment_jobs SET next_at=clock_timestamp() WHERE id=%s',(v['job'],))\nresult=work(db,store,v['job'])",job=st['job_id']) failure=c.call('GET','/api/v1/attachments/'+failed['id'],actor=alice,schema='Attachment')['json'] check(failure['status']=='failed' and failure['error_code']=='retry_exhausted','retry did not terminate') c.call('POST','/api/v1/chats/'+chat['id']+'/messages',409,actor=alice,body={'text':'','attachment_ids':[failed['id']]},headers={'Idempotency-Key':uuid.uuid4().hex}) inside("store.put(v['key'],io.BytesIO(bytes.fromhex(v['raw'])),v['length'],'image/png')\nreplay(db,v['job'],'restore synthetic staging and retry')\nresult=True",key=st['staging_key'],raw=failed_raw.hex(),length=len(failed_raw),job=st['job_id']) compose('start','relay','worker') ready(c,bob,failed) evidence['retry_replay']={'failed_after':5,'code':'retry_exhausted','explicit_replay_ready':True,'failed_attachment_binding':409} evidence['result']='PASS' (ROOT/'evidence/jobs-faults.json').write_text(json.dumps(evidence,indent=2)+'\n') print('PASS: jobs-faults.json') finally: if trigger: inside("with db.pool.connection() as c:\n c.execute('DROP TRIGGER IF EXISTS lab5_pause ON attachments');c.execute('DROP FUNCTION IF EXISTS lab5_pause_ready()')\nresult=True") compose('start','relay','worker') if __name__=='__main__': main()