124 lines
7.6 KiB
Python
124 lines
7.6 KiB
Python
#!/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()<end:
|
|
result=predicate()
|
|
if result: return result
|
|
time.sleep(.2)
|
|
raise AssertionError('Condition timed out')
|
|
|
|
|
|
def ready(c,actor,att):
|
|
return c.wait_ready(actor,att)
|
|
|
|
|
|
def main():
|
|
c=Client();alice,bob,_,chat=c.bootstrap()
|
|
evidence={'result':'INCOMPLETE'}
|
|
trigger=False
|
|
try:
|
|
# Durable acceptance while both relay and worker are absent: real COMMIT/publish gap.
|
|
compose('stop','worker','relay')
|
|
att,raw=c.attachment(alice,chat)
|
|
c.message(alice,chat,'',attachments=[att['id']])
|
|
c.call('GET','/api/v1/attachments/'+att['id']+'/content',409,actor=bob)
|
|
before=state(att['id']);check(before['dispatched_at'] is None,'outbox already published')
|
|
compose('restart','api','broker')
|
|
wait_for(lambda: subprocess.run(['python3','scripts/cluster.py','wait'],cwd=ROOT,capture_output=True).returncode==0)
|
|
c.call('GET','/api/v1/users/me',actor=alice)
|
|
compose('start','relay','worker')
|
|
meta=ready(c,bob,att)
|
|
check(c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=bob)['bytes']==raw,'original changed')
|
|
evidence['commit_publish_gap']={'accepted_status':202,'outbox_unpublished':True,'api_broker_restarted':True,'same_job_ready':state(att['id'])['job_id']==before['job_id']}
|
|
# Publisher has already confirmed acceptance, broker restart preserves unread work.
|
|
compose('stop','worker')
|
|
att2,_=c.attachment(alice,chat)
|
|
wait_for(lambda: state(att2['id'])['dispatched_at'])
|
|
compose('restart','broker')
|
|
compose('start','worker')
|
|
ready(c,bob,att2)
|
|
evidence['broker_persistence']={'unread_job_survived_restart':True}
|
|
# Delay ready COMMIT in real PostgreSQL AFTER all S3 PUTs, kill before ack.
|
|
compose('stop','worker')
|
|
target,_=c.attachment(alice,chat)
|
|
inside("with db.pool.connection() as c:\n c.execute(\"CREATE OR REPLACE FUNCTION lab5_pause_ready() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.id='\"+v['aid']+\"'::uuid AND NEW.status='ready' THEN PERFORM pg_sleep(2); END IF; RETURN NEW; END $$\")\n c.execute('CREATE TRIGGER lab5_pause BEFORE UPDATE ON attachments FOR EACH ROW EXECUTE FUNCTION lab5_pause_ready()')\nresult=True",aid=target['id'])
|
|
trigger=True
|
|
compose('start','worker')
|
|
def at_commit():
|
|
return inside("with db.pool.connection() as c:\n result=bool(c.execute(\"SELECT 1 FROM pg_stat_activity WHERE wait_event='PgSleep' AND query LIKE 'UPDATE attachments SET status=%'\").fetchone())")
|
|
wait_for(at_commit)
|
|
observed=inside("with db.pool.connection() as c:\n row=c.execute('SELECT object_key FROM attachments WHERE id=%s',(v['aid'],)).fetchone()\nobj=store.get(row['object_key']);result={'s3_effect_written':obj.length>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()
|