Files
mtusi2026lab6/student-tests/pipeline_checks.py
T

189 lines
11 KiB
Python

"""Real DB/S3/Redis fault injection. Stop production worker/dispatcher first."""
import concurrent.futures
import hashlib
import io
import json
import os
from pathlib import Path
import subprocess
import sys
import time
import uuid
sys.path[:0]=['/app/src',str(Path.cwd()/'tests')]
from PIL import Image
from client import Client
from pipeline import STREAM,GROUP,broker,connect,event,dispatch_once,process,ack
from objects import Objects
from postgres import setting
from admin import replay,version,cleanup
def main():
c=Client();alice,bob,eve,chat=c.bootstrap()
bus=broker(); objects=Objects(setting)
report={'invariants':{},'faults':[]}
def fetch(aid):
with connect() as conn:
a=conn.execute('SELECT * FROM attachments WHERE 1=1 AND id = %s',(aid,)).fetchone()
j=conn.execute('SELECT * FROM attachment_jobs WHERE 1=1 AND id = %s',(a['current_job_id'],)).fetchone()
return a,j
def upload(raw=None,mime='image/png'):
if raw is None: a,_=c.attachment(alice,chat)
else:a=c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=research.png',202,actor=alice,raw=raw,headers={'Content-Type':mime},schema='Attachment')['json']
return a,fetch(a['id'])[1]
def run_once(fault=None):
args=[sys.executable,'/app/src/pipeline.py','work','--once']
if fault:args+=['--fault-point',fault]
return subprocess.run(args,capture_output=True,timeout=30).returncode
def drain():
for _ in range(200):
batch=bus.xreadgroup(GROUP,'research-drain',{STREAM:'>'},count=1)
if not batch:break
for mid,data in batch[0][1]:process(json.loads(data['event']));ack(bus,mid)
def expire(job):
with connect() as conn:
conn.execute("UPDATE attachment_jobs SET lease_until = clock_timestamp() - INTERVAL '1 second' WHERE 1=1 AND id = %s",(job['id'],))
def recover(aid):
until=time.monotonic()+20
while time.monotonic()<until:
dispatch_once(bus);drain()
a,j=fetch(aid)
if a['state']=='ready':return a,j
time.sleep(.1)
raise AssertionError('not recovered')
for mid,data in bus.xautoclaim(STREAM,GROUP,'initial-recovery',min_idle_time=0,start_id='0-0',count=100)[1]:
process(json.loads(data['event']));ack(bus,mid)
# COMMIT -> no publisher yet: one queued row, no Redis message, then automatic outbox pass.
a,j=upload()
assert fetch(a['id'])[0]['state']=='queued'
assert c.call('GET','/api/v1/attachments/'+a['id']+'/content',409,actor=bob)
c.message(bob,chat,'queued is linkable',attachments=[a['id']])
dispatch_once(bus);drain();assert fetch(a['id'])[0]['state']=='ready'
report['invariants']['commit_before_publish_recovered']=True
# Broker accepted XADD but publisher died before marking outbox: true exit(77).
a,j=upload()
code=subprocess.run([sys.executable,'/app/src/pipeline.py','dispatch','--once','--fault-point','after_publish'],capture_output=True,timeout=10).returncode
assert code==77
dispatch_once(bus);drain()
assert fetch(a['id'])[0]['state']=='ready'
report['invariants']['publish_before_marker_duplicate_safe']=True
for point in ['before_side_effect','after_original','after_objects','after_commit']:
a,j=upload();dispatch_once(bus)
code=run_once(point);assert code==77,(point,code)
before,job=fetch(a['id'])
if point not in ('after_commit','before_side_effect'):expire(job)
result,job=recover(a['id'])
assert c.call('GET','/api/v1/attachments/'+a['id']+'/content',actor=bob)['bytes']==(Path.cwd()/'tests/fixtures/sample.png').read_bytes()
reclaimed=bus.xautoclaim(STREAM,GROUP,'post-crash-redelivery',min_idle_time=0,start_id='0-0',count=100)[1]
for mid,data in reclaimed:
process(json.loads(data['event']));ack(bus,mid)
assert bus.xpending(STREAM,GROUP)['pending']==0
keys=objects.client.list_objects_v2(Bucket=objects.bucket,Prefix='results/'+a['id']+'/v1/').get('Contents',[])
assert len(keys)==4,(point,len(keys))
report['faults'].append({'point':point,'exit_code':code,'state_at_crash':before['state'],'recovered':result['state'],'attempts':job['attempt'],'result_objects':len(keys)})
report['invariants']['crashes_before_after_side_effect_and_commit']=True
bus.xadd(STREAM,{'event':json.dumps({'not':'a job'})})
assert run_once()==0
assert bus.xlen('rejected-jobs')>=1
report['invariants']['invalid_envelope_observable_dlq']=True
# Duplicate/reorder through broker on a completed job: no extra attempt/effect.
a,j=upload();dispatch_once(bus);drain();before,done=fetch(a['id'])
old=event(j)
for attempt in [2,1,3,1,1]:bus.xadd(STREAM,{'event':json.dumps(dict(old,attempt=attempt))})
drain();after,done2=fetch(a['id'])
assert before['variants']==after['variants'] and done2['attempt']==done['attempt']
report['invariants']['duplicate_and_reorder_no_second_effect']=True
# Race two consumers with the SAME logical job, not just one serial duplicate.
a,j=upload();e=event(j)
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: results=list(pool.map(lambda _:process(e),range(2)))
assert fetch(a['id'])[0]['state']=='ready' and sorted(results)==['noop','ready']
report['invariants']['concurrent_duplicate_single_claim']=True
# Pause actual old process after all immutable side effects, advance version and finish v2.
a,j=upload();e=event(j)
directory=Path('/tmp')/('fence-'+uuid.uuid4().hex);directory.mkdir();marker=directory/'paused';release=directory/'release'
code="import sys,json,time;from pathlib import Path;sys.path.insert(0,'/app/src');from pipeline import process\ndef hook(point,job):\n if point=='after_objects':\n Path(sys.argv[2]).write_text('paused')\n while not Path(sys.argv[3]).exists():time.sleep(.05)\nprint(process(json.loads(sys.argv[1]),hook))"
child=subprocess.Popen([sys.executable,'-c',code,json.dumps(e),str(marker),str(release)],stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True)
try:
deadline=time.monotonic()+20
while not marker.exists():
assert child.poll() is None
assert time.monotonic()<deadline;time.sleep(.05)
new=version(uuid.UUID(a['id']),2);newrow,newjob=fetch(a['id'])
assert process(event(newjob))=='ready'
current,finished=fetch(a['id']);signature=current['variants']
release.write_text('go');stdout,stderr=child.communicate(timeout=10)
assert child.returncode==0 and stdout.strip()=='fenced',(stdout,stderr)
bus.xadd(STREAM,{'event':json.dumps(e)});drain()
final,finished=fetch(a['id'])
assert final['pipeline_version']==2 and final['variants']==signature and final['state']=='ready'
assert all('/v2/' in v['object_key'] for v in final['variants'])
report['invariants']['stale_running_version_fenced']=True
report['invariants']['old_delivery_after_new_ready_no_overwrite']=True
finally:
release.write_text('go')
if child.poll() is None:child.kill();child.wait()
# Transient failures consume a finite budget; failed registry and explicit replay.
a,j=upload()
with connect() as conn:conn.execute('UPDATE attachment_jobs SET max_attempts = 2 WHERE 1=1 AND id = %s',(j['id'],))
# Exact staging copy saved externally; missing source is permanent and observable.
raw=(Path.cwd()/'tests/fixtures/sample.png').read_bytes();objects.delete(j['source_key'])
process(event(j));failed,fj=fetch(a['id']);assert failed['state']=='failed' and failed['error_code']=='source_missing'
objects.put(j['source_key'],io.BytesIO(raw),len(raw),'image/png',hashlib.sha256(raw).hexdigest())
replay(j['id']);fresh,fj=fetch(a['id']);assert process(event(fj))=='ready'
try:replay(j['id']);raise AssertionError('replayed ready')
except ValueError:pass
report['invariants']['failed_registry_explicit_replay_and_ready_refusal']=True
# Real S3 signature failures are transient, with two attempts and measured backoff.
a,j=upload()
with connect() as conn:conn.execute('UPDATE attachment_jobs SET max_attempts = 2 WHERE 1=1 AND id = %s',(j['id'],))
wrong=Path('/tmp/wrong-secret');wrong.write_text('synthetic-invalid-key-not-a-real-secret')
env=dict(os.environ,S3_SECRET_ACCESS_KEY_FILE=str(wrong))
transitions=[];started=time.monotonic()
for _ in range(2):
row,j=fetch(a['id'])
delay=max(0,(j['next_attempt_at']-__import__('datetime').datetime.now(__import__('datetime').timezone.utc)).total_seconds())
time.sleep(delay+.01)
code="import sys,json;sys.path.insert(0,'/app/src');from pipeline import process;print(process(json.loads(sys.argv[1])))"
run=subprocess.run([sys.executable,'-c',code,json.dumps(event(j))],env=env,capture_output=True,timeout=10)
assert run.returncode==0
row,j=fetch(a['id']);transitions.append({'state':j['state'],'attempt':j['attempt'],'error_code':j['error_code']})
assert row['state']=='failed' and row['error_code']=='retry_exhausted' and j['attempt']==2
replay(j['id']);row,j=fetch(a['id']);assert process(event(j))=='ready'
report['retry']={'transitions':transitions,'seconds':round(time.monotonic()-started,3),'replayed_attempt':fetch(a['id'])[1]['attempt']}
report['invariants']['transient_backoff_exhaustion_then_replay']=True
# Real corrupted JPEG whose header is valid: heavy decoder fails safely in worker.
jpg=io.BytesIO();Image.new('RGB',(320,200),'blue').save(jpg,format='JPEG');truncated=jpg.getvalue()[:-100]
a,j=upload(truncated,'image/jpeg');process(event(j));bad,_=fetch(a['id'])
assert bad['state']=='failed' and bad['error_code']=='invalid_image'
report['invariants']['invalid_decode_permanent_failed']=True
# EXIF, alpha, small image and all on-disk variants checked by the real decoder.
transforms=[]
for kind in ['alpha','exif','small']:
out=io.BytesIO()
if kind=='alpha':
Image.new('RGBA',(20,10),(255,0,0,0)).save(out,format='PNG');mime='image/png'
elif kind=='exif':
image=Image.new('RGB',(200,320),'green');exif=Image.Exif();exif[274]=6;image.save(out,format='JPEG',exif=exif);mime='image/jpeg'
else:Image.new('RGB',(5,3),'yellow').save(out,format='PNG');mime='image/png'
a,j=upload(out.getvalue(),mime);assert process(event(j))=='ready'
r=c.call('GET','/api/v1/attachments/'+a['id']+'/content?variant=thumbnail',actor=bob)
with Image.open(io.BytesIO(r['bytes'])) as thumb:
expected=(20,10) if kind=='alpha' else (256,160) if kind=='exif' else (5,3)
assert thumb.size==expected
assert not thumb.getexif()
if kind=='alpha':assert min(thumb.getpixel((0,0)))>=250
transforms.append({'kind':kind,'size':thumb.size,'exif_removed':not bool(thumb.getexif())})
report['transforms']=transforms
pending,pending_job=upload()
dry=cleanup(False);fixed=cleanup(True);repeat=cleanup(True)
assert fetch(pending['id'])[0]['state']=='queued' and objects.head(pending_job['source_key']) is not None
report['invariants']['cleanup_preserves_current_and_fresh_failed']=True
assert repeat['counts']['ready_staging']==0
report['invariants']['ready_staging_cleanup_idempotent']=True
report['cleanup']=[dry,fixed,repeat]
print(json.dumps(report,indent=2))
if __name__=='__main__': main()