Files
mtusi2026lab5/student-tests/pipeline_tests.py
T

102 lines
9.1 KiB
Python

#!/usr/bin/env python3
from support import *
import hashlib,concurrent.futures
from client import arguments,run
def main():
args=arguments('Pipeline durability, image variants and controlled failures');c=Client(args.base_url,args.ca_file,timeout=100)
a,b,e,chat=c.bootstrap();checks=[]
png_bytes=(ROOT/'tests/fixtures/sample.png').read_bytes()
upload(c,a,chat,b'bad',expected=415);upload(c,a,chat,png_bytes,mime='image/jpeg',expected=415)
upload(c,a,chat,b'x'*(10485760+1),expected=413)
upload(c,a,chat,png_bytes,name='../unsafe.png',expected=400)
other=c.call('POST','/api/v1/chats',201,actor=a,body={'title':'Other','member_ids':[a['id']]},schema='Chat')['json']
checks.append('HTTP size/MIME/corruption/filename validation remains compatible with Lab4')
faultenv={'PIPELINE_FAULT_FILE':'/run/faults/control.json','JOB_MAX_ATTEMPTS':'3'}
try:
compose('stop','worker','dispatcher')
att=upload(c,a,chat)['json'];id=job_id(att)
check(att['status']=='queued','upload is not a queued snapshot')
c.message(a,chat,'Queued image',attachments=[att['id']]);c.call('GET','/api/v1/attachments/'+att['id']+'/content',409,actor=b)
check(sql("SELECT published_at IS NULL FROM attachment_outbox WHERE job_id='"+id+"'")=='t','outbox not retained')
compose('restart','api');compose('restart','broker');wait_api(c)
compose('up','-d','--wait','dispatcher',env=faultenv)
wait(lambda:sql("SELECT published_at IS NOT NULL FROM attachment_outbox WHERE job_id='"+id+"'")=='t')
queue_before=compose('exec','-T','-e','RABBITMQ_CTL_ERL_ARGS=+S 1:1','broker','rabbitmqctl','list_queues','-p','messenger','name','messages_ready','--formatter=json')
compose('restart','broker');compose('up','-d','--wait','--wait-timeout','90','broker')
compose('up','-d','--no-deps','worker',env=faultenv);meta=ready(c,b,att)
check(c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=b)['bytes']==(ROOT/'tests/fixtures/sample.png').read_bytes(),'original changed')
checks.append('202 while worker stopped; durable outbox survives API restart; published queue survives broker restart; same ID becomes ready')
dimensions={v['name']:(v['width'],v['height']) for v in meta['variants']}
check(dimensions=={'thumbnail':(256,160),'crop':(128,128),'optimized':(320,200)},'wrong image dimensions')
for variant in meta['variants']:
data=c.call('GET','/api/v1/attachments/'+att['id']+'/content?variant='+variant['name'],actor=b)['bytes']
image=Image.open(io.BytesIO(data));check(image.size==dimensions[variant['name']],'encoded image dimensions differ')
check(hashlib.sha256(data).hexdigest()==variant['sha256'] and len(data)==variant['size_bytes'],'variant checksum mismatch')
check(not image.getexif(),'EXIF was retained in a variant')
for endpoint in ('','/content?variant=thumbnail'):c.call('GET','/api/v1/attachments/'+att['id']+endpoint,404,actor=e)
oriented=upload(c,a,chat,image_bytes(320,200,orientation=6),'rotated.jpg','image/jpeg')['json'];om=ready(c,a,oriented)
check(next(v for v in om['variants'] if v['name']=='thumbnail')['width']==160,'EXIF orientation ignored')
small=upload(c,a,chat,image_bytes(64,32,alpha=True),'alpha.png')['json'];sm=ready(c,a,small)
thumb=c.call('GET','/api/v1/attachments/'+small['id']+'/content?variant=thumbnail',actor=a)['bytes'];im=Image.open(io.BytesIO(thumb))
check(im.size==(64,32) and min(im.convert('RGB').getpixel((0,0)))>=250,'alpha is not white or small image upscaled')
checks.append('thumbnail/crop/WebP bytes and dimensions; no EXIF; orientation applied; transparent small image remains small with white background; private variants')
before=sql("SELECT attempts||':'||completed_at FROM attachment_jobs WHERE id='"+id+"'")
for _ in range(3):compose('exec','-T','dispatcher','dotnet','Messenger.Api.dll','--redeliver',id)
time.sleep(2);check(sql("SELECT attempts||':'||completed_at FROM attachment_jobs WHERE id='"+id+"'")==before,'ready duplicate reprocessed')
checks.append('three duplicate ready deliveries are no-op')
# Pause deterministically after all S3 writes, kill worker before result COMMIT/ack.
for point in ('after_objects','after_commit'):
compose('stop','worker')
interrupted=upload(c,a,chat,name=point+'.png')['json'];jid=job_id(interrupted);fault(point,jid)
compose('up','-d','--no-deps','--force-recreate','worker',env=faultenv);wait_fault()
compose('kill','-s','SIGKILL','worker');clear_fault()
compose('up','-d','--no-deps','worker',env=faultenv);ready(c,a,interrupted,130)
count=int(sql("SELECT count(*) FROM attachment_job_events WHERE job_id='"+jid+"' AND event='ready'"))
check(count==1,'completion was duplicated')
checks.append(point+': worker killed, same logical job recovered, one published result')
# Publish confirmed, dispatcher killed before marking the outbox.
compose('stop','dispatcher','worker');pub=upload(c,a,chat,name='publisher.png')['json'];pubid=job_id(pub);fault('after_publish',pubid)
compose('up','-d','--no-deps','--force-recreate','dispatcher',env=faultenv);wait_fault();compose('kill','-s','SIGKILL','dispatcher');clear_fault()
compose('up','-d','--no-deps','dispatcher','worker',env=faultenv);ready(c,a,pub)
check(sql("SELECT count(*) FROM attachment_job_events WHERE job_id='"+pubid+"' AND event='ready'")=='1','confirm-window duplicate effect')
checks.append('publisher confirm before outbox COMMIT crash recovers without lost task or duplicate effect')
# Permanent failure, without retrying invalid input forever.
compose('stop','worker');bad=upload(c,a,chat,name='invalid-stage.png')['json'];bid=job_id(bad)
staging=sql("SELECT staging_key FROM attachment_jobs WHERE id='"+bid+"'");s3('PUT',staging,b'broken')
compose('up','-d','--no-deps','worker',env=faultenv)
wait(lambda:sql("SELECT state FROM attachment_jobs WHERE id='"+bid+"'")=='failed')
check(sql("SELECT attempts FROM attachment_jobs WHERE id='"+bid+"'")=='1','permanent failure retried')
c.call('POST','/api/v1/chats/'+chat['id']+'/messages',409,actor=a,body={'text':'','attachment_ids':[bad['id']]},headers={'Idempotency-Key':uuid.uuid4().hex})
checks.append('invalid staging checksum becomes failed after one attempt; failed attachment cannot be linked')
compose('stop','worker');huge=upload(c,a,chat,name='worker-pixels.png')['json'];hid=job_id(huge)
import struct,zlib
payload=bytearray(png_bytes);payload[16:24]=struct.pack('>II',10000,10000);payload[29:33]=struct.pack('>I',zlib.crc32(payload[12:29]));payload=bytes(payload)
staging=sql("SELECT staging_key FROM attachment_jobs WHERE id='"+hid+"'");s3('PUT',staging,payload)
sql("UPDATE attachments SET sha256='"+hashlib.sha256(payload).hexdigest()+"',size_bytes="+str(len(payload))+" WHERE id='"+huge['id']+"'")
compose('up','-d','--no-deps','worker',env=faultenv)
wait(lambda:sql("SELECT state FROM attachment_jobs WHERE id='"+hid+"'")=='failed')
check(sql("SELECT attempts||':'||error_code FROM attachment_jobs WHERE id='"+hid+"'")=='1:invalid_image','worker pixel guard failed')
checks.append('worker independently rejects >40 million pixels before bitmap allocation')
# Transient SQL failure after object writes: bounded retries, jitter/backoff, explicit replay.
sql("CREATE FUNCTION test_pipeline_failure() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.filename='retry-me.png' AND NEW.status='ready' THEN RAISE EXCEPTION 'injected'; END IF; RETURN NEW; END $$; CREATE TRIGGER test_pipeline_failure BEFORE UPDATE ON attachments FOR EACH ROW EXECUTE FUNCTION test_pipeline_failure();")
retry=upload(c,a,chat,name='retry-me.png')['json'];rid=job_id(retry)
wait(lambda:sql("SELECT state FROM attachment_jobs WHERE id='"+rid+"'")=='failed',120)
check(sql("SELECT attempts||':'||error_code FROM attachment_jobs WHERE id='"+rid+"'")=='3:retry_exhausted','retry limit failed')
sql('DROP TRIGGER test_pipeline_failure ON attachments; DROP FUNCTION test_pipeline_failure();')
compose('exec','-T','dispatcher','dotnet','Messenger.Api.dll','--replay',rid);ready(c,a,retry)
finished=sql("SELECT completed_at FROM attachment_jobs WHERE id='"+rid+"'")
compose('exec','-T','dispatcher','dotnet','Messenger.Api.dll','--replay',rid)
check(sql("SELECT completed_at FROM attachment_jobs WHERE id='"+rid+"'")==finished,'replay reran successful job')
checks.append('transient failure retries with bounded attempts then failed; explicit replay succeeds; replay of ready is no-op')
wait(lambda:sql("SELECT staging_deleted_at IS NOT NULL FROM attachment_jobs WHERE id='"+rid+"'")=='t')
check(sql("SELECT staging_deleted_at IS NULL FROM attachment_jobs WHERE id='"+bid+"'")=='t','failed staging was cleaned too soon')
checks.append('ready staging cleaned after durable publication; failed staging retained for replay')
report={'checks':checks,'broker_queue_before_restart':queue_before,'retry_test_max_attempts':3,'default_max_attempts':5}
(ROOT/'evidence/pipeline.json').write_text(json.dumps(report,indent=2)+'\n');print('PASS: '+str(len(checks))+' pipeline scenarios')
finally:
clear_fault()
sql('DROP TRIGGER IF EXISTS test_pipeline_failure ON attachments; DROP FUNCTION IF EXISTS test_pipeline_failure();')
compose('up','-d','--no-deps','--force-recreate','dispatcher','worker')
if __name__=='__main__':run(main)