"""Explicit fault injection against this lab's disposable Compose project.""" import asyncio import hashlib from io import BytesIO import json from pathlib import Path import subprocess import sys import time from uuid import UUID sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests')) from client import Client from PIL import Image import psycopg from psycopg.rows import dict_row from app.pipeline import broker from app.attachments import client as s3client ROOT=Path(__file__).resolve().parents[1] results=[] def dc(*args): subprocess.run(['docker','compose','--env-file','.env',*args],cwd=ROOT,check=True,stdout=subprocess.DEVNULL) def sql(query,params=(),one=True): with psycopg.connect(Path('/run/secrets/database_url').read_text().strip(),row_factory=dict_row) as conn: cur=conn.execute(query,params) return cur.fetchone() if cur.description and one else cur.fetchall() if cur.description else None def record(name,**data): results.append(dict(test=name,result='PASS',**data)) (ROOT/'evidence/pipeline.json').write_text(json.dumps(results,indent=2)) print('PASS:',name,flush=True) c=Client(); a,b,e,chat=c.bootstrap(); s3=s3client() def meta(att):return c.call('GET','/api/v1/attachments/'+att['id'],actor=a,schema='Attachment')['json'] def upload():return c.attachment(a,chat) def job(att):return sql('SELECT * FROM jobs WHERE attachment_id=%s',(UUID(att['id']),)) def wait_state(att,state,seconds=120): end=time.monotonic()+seconds while time.monotonic()0 dc('restart','api','broker') dc('start','worker') ready=variants(att) assert c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=b)['bytes']==original record('stopped worker and API broker restart',attachment_id=att['id'],queued_messages=before) dc('stop','publisher') att,_=upload() assert job(att)['last_published'] is None # API is killed after queued+job COMMIT, before any publisher can execute. dc('kill','api'); dc('start','api'); dc('start','publisher') variants(att) record('crash between COMMIT and publish',attachment_id=att['id']) dc('stop','worker') # Start worker with one-shot marker inserted while it is running, before upload. dc('start','worker');dc('exec','-T','worker','touch','/tmp/crash_after_object') att,_=upload() ready=variants(att) assert job(att)['attempts']>=2 original_attempts=job(att)['attempts'] payload=dict(schema_version=1,job_id=str(job(att)['id']),type='attachment.process.v1',attachment_id=att['id'],pipeline_version=1,attempt=1,created_at=att['created_at']) async def duplicate(): q=broker() for _ in range(3):await q.xadd('images.v1',{'payload':json.dumps(payload)}) await q.aclose() asyncio.run(duplicate());time.sleep(3) assert meta(att)['variants']==ready['variants'] and job(att)['attempts']==original_attempts listing=s3.list_objects_v2(Bucket='attachments',Prefix='variants/'+UUID(att['id']).hex+'/v1/') assert listing['KeyCount']==3 record('crash after S3 write and duplicate delivery',attachment_id=att['id'],attempts=original_attempts,variant_objects=3) dc('stop','worker'); att,_=upload() # Trusted-storage corruption emulates permanent input failure after acceptance. s3.put_object(Bucket='attachments',Key='staging/'+UUID(att['id']).hex,Body=b'broken') dc('start','worker');failed=wait_state(att,'failed') assert failed['error_code']=='invalid_image' c.call('GET','/api/v1/attachments/'+att['id']+'/content',409,actor=a) s3.put_object(Bucket='attachments',Key='staging/'+UUID(att['id']).hex,Body=original,ContentType='image/png') dc('exec','-T','worker','python','-m','app.pipeline','replay',str(job(att)['id']),'restored staging for lab fault test') variants(att) assert sql('SELECT count(*) AS n FROM replay_audit WHERE job_id=%s',(job(att)['id'],))['n']==1 record('permanent failure registry and audited replay',attachment_id=att['id']) dc('stop','worker'); att,_=upload() worker_id=subprocess.check_output(['docker','compose','ps','-aq','worker'],cwd=ROOT,text=True).strip() dc('stop','minio') # docker start intentionally avoids Compose restarting the stopped dependency. subprocess.run(['docker','start',worker_id],check=True,stdout=subprocess.DEVNULL) # S3 outage intentionally makes API readiness fail, so HAProxy may return 503. # Observe the durable job directly until storage and routing are restored. deadline=time.monotonic()+150 while job(att)['state']!='failed' and time.monotonic()