Files
2026-11-10 22:13:40 +03:00

328 lines
19 KiB
Python

#!/usr/bin/env python3
"""Real Redis Streams/S3/PostgreSQL fault tests; only the isolated lab5 stack."""
import hashlib
import datetime as dt
import io
import json
import os
from pathlib import Path
import subprocess
import sys
import time
import uuid
from helpers import Client, Probe, ROOT, STACK, check, containers, docker, png, oversized_dimensions, sql, upload
sys.path.insert(0, str(ROOT/'tests'))
from client import Failure
from image_probe import jpeg_size
STREAM = 'attachments:jobs:v1'
GROUP = 'image-workers-v1'
RESULT = {'stack': STACK, 'cases': {}, 'started_at': time.time()}
if '--tail-only' in sys.argv:
previous=ROOT/'evidence/lab5-faults.json'
check(previous.is_file(),'tail-only needs previously saved successful fault cases')
RESULT=json.loads(previous.read_text())
RESULT.setdefault('resumed_at',[]).append(time.time())
def save():
(ROOT/'evidence/lab5-faults.json').write_text(json.dumps(RESULT, indent=2)+'\n')
def until(operation, predicate=bool, timeout=90):
deadline = time.monotonic()+timeout
last = None
while time.monotonic() < deadline:
try:
last = operation()
if predicate(last):
return last
except (AssertionError, subprocess.CalledProcessError, KeyError, IndexError):
pass
time.sleep(.2)
raise AssertionError('condition deadline exceeded; last='+str(last))
def tasks(service):
ids = docker('service','ps','--filter','desired-state=running','-q',STACK+'_'+service).stdout.decode().split()
if not ids:
return []
return json.loads(docker('inspect',*ids).stdout)
def settled(service, count):
stable = [None, None]
def ready():
spec=json.loads(docker('service','inspect',STACK+'_'+service).stdout)[0]
check(spec.get('UpdateStatus',{}).get('State','completed')=='completed','service update not completed')
ts = tasks(service)
check(len(ts)==count, 'wrong task count')
if not count:
live=docker('ps','--filter','label=com.docker.swarm.service.name='+STACK+'_'+service,'-q').stdout.strip()
check(not live,'old worker container still running')
return True
check(all(t['Status']['State']=='running' for t in ts), 'task not running')
states = json.loads(docker('inspect',*[t['Status']['ContainerStatus']['ContainerID'] for t in ts]).stdout)
check(all(s['State'].get('Health',{}).get('Status','healthy')=='healthy' for s in states), 'unhealthy container')
if service=='api':
Client(timeout=2).call('GET','/health/ready',schema='Health')
ids = frozenset(t['ID'] for t in ts)
if ids != stable[0]:
stable[:] = [ids,time.monotonic()]
return time.monotonic()-stable[1]>=4
def observe():
try:
return ready()
except (AssertionError,subprocess.CalledProcessError,KeyError,IndexError):
stable[:]=[None,None]
raise
until(observe, timeout=120)
def control(service, values=None, replicas=None, force=False):
args = ['service','update','--detach']
for key,value in (values or {}).items():
args += ['--env-rm',key] if value is None else ['--env-add',key+'='+str(value)]
if replicas is not None:
args += ['--replicas',str(replicas)]
if force:
args += ['--force']
docker(*args,STACK+'_'+service)
if replicas is None:
spec = json.loads(docker('service','inspect',STACK+'_'+service).stdout)[0]
replicas = spec['Spec']['Mode']['Replicated']['Replicas']
settled(service,replicas)
def redis(*args):
return json.loads(docker('exec',containers('redis')[0],'redis-cli','--json',*args).stdout)
def job(att):
return json.loads(sql("SELECT row_to_json(j) FROM attachment_jobs j WHERE attachment_id='"+att['id']+"';"))
def wait_state(att, state, timeout=90):
return until(lambda: job(att), lambda j: j['state']==state, timeout)
def variant_check(c, actor, att, original, expected_thumb=(256,160)):
ready = c.wait_ready(actor,att)
check(ready['error_code'] is None, 'ready has error')
check(c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=actor)['bytes']==original,'original changed')
variants = {v['name']:v for v in ready['variants']}
check(set(variants)=={'thumbnail','crop','optimized'},'incomplete variants')
check((variants['thumbnail']['width'],variants['thumbnail']['height'])==expected_thumb,'thumbnail geometry')
check((variants['crop']['width'],variants['crop']['height'])==(128,128),'crop geometry')
for name,v in variants.items():
response = c.call('GET','/api/v1/attachments/'+att['id']+'/content?variant='+name,actor=actor)
body = response['bytes']
check(len(body)==v['size_bytes'] and hashlib.sha256(body).hexdigest()==v['sha256'],'variant checksum')
check(response['headers'].get_content_type()==v['content_type'],'variant MIME')
if name=='optimized':
check(body[:4]==b'RIFF' and body[8:12]==b'WEBP','not WebP')
else:
check(jpeg_size(body)==(v['width'],v['height']),'JPEG actual geometry')
return ready
def replay(j, expected=True):
result = docker('exec',containers('worker')[0],'/usr/local/bin/worker','--replay',j['id'],
'--operator','synthetic-fault-test','--reason','restore synthetic fixture',check_result=False)
check((result.returncode==0)==expected,'unexpected replay result')
def main():
check(STACK!='mtusi-lab4','refuse source stack')
c = Client(timeout=55)
alice,bob,eve,chat = c.bootstrap()
data = png()
# Inherited lab4 obligations remain public: input validation and access control.
negatives=[]
for name,body,mime,filename,status in (
('oversized',b'x'*(10485760+1),'image/png','large.png',413),
('damaged',data[:45],'image/png','broken.png',415),
('pixel_budget',oversized_dimensions(),'image/png','huge.png',413),
('mime_spoof',data,'image/jpeg','fake.jpg',415),
('filename',data,'image/png','../evil.png',400),
('unsupported',data,'application/octet-stream','file.png',415)):
upload(c,alice,chat,body,filename,mime,status)
negatives.append({'name':name,'status':status})
att = upload(c,alice,chat,data)['json']
variant_check(c,bob,att,data)
c.message(alice,chat,'',attachments=[att['id']])
c.call('GET','/api/v1/attachments/'+att['id'],404,actor=eve)
c.call('GET','/api/v1/attachments/'+att['id']+'/content',401)
upload(c,eve,chat,data,expected=404)
RESULT['cases']['input_and_acl'] = negatives
# Real small image, alpha and EXIF orientation exercise the actual renderer.
from PIL import Image
for name,im,exif,shape in (
('small.png',Image.new('RGBA',(12,8),(255,0,0,0)),None,(12,8)),
('oriented.jpg',Image.new('RGB',(320,200),(40,120,200)),6,(160,256)),
('oriented.png',Image.new('RGB',(320,200),(40,120,200)),6,(160,256))):
out=io.BytesIO();kwargs={}
if exif:
tags=Image.Exif();tags[274]=exif;kwargs['exif']=tags
is_jpeg=name.endswith('.jpg')
im.save(out,format='JPEG' if is_jpeg else 'PNG',**kwargs)
body=out.getvalue();item=upload(c,alice,chat,body,name,'image/jpeg' if is_jpeg else 'image/png')['json']
variant_check(c,bob,item,body,shape)
if name=='small.png':
raw=c.call('GET','/api/v1/attachments/'+item['id']+'/content?variant=thumbnail',actor=bob)['bytes']
pixel=Image.open(io.BytesIO(raw)).getpixel((0,0));check(min(pixel)>250,'alpha was not white')
RESULT['cases']['small_alpha_exif']='PASS'
print('PASS: input/ACL, three actual formats, geometry, EXIF, alpha',flush=True)
with Probe() as probe:
key=sql("SELECT object_key FROM attachments WHERE id='"+att['id']+"';")
anonymous=docker('exec',containers('minio')[0],'wget','-S','-O','/dev/null','http://127.0.0.1:9000/attachments/'+key,check_result=False)
check(b'403' in anonymous.stderr,'bucket public')
probe.mc('pipe','local/attachments/outside-prefix',data=b'x',expected=1)
RESULT['cases']['private_s3']={'anonymous_get':403,'outside_prefix_denied':True}
# A stage PUT without metadata COMMIT must never produce a 202 or a job.
until(lambda:sql("SELECT count(*) FROM attachments WHERE status='ready' AND staging_key IS NOT NULL;")=='0',timeout=45)
def stage_keys():
lines=probe.mc('ls','--recursive','--json','local/attachments/staging/').stdout.decode().splitlines()
return {json.loads(line)['key'] for line in lines if json.loads(line).get('type')=='file'}
old=stage_keys()
filename='db-fault-'+uuid.uuid4().hex+'.png'
sql("CREATE FUNCTION lab5_reject_metadata() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.filename='"+filename+"' THEN RAISE EXCEPTION 'synthetic metadata failure'; END IF; RETURN NEW; END; $$; CREATE TRIGGER lab5_reject_metadata BEFORE INSERT ON attachments FOR EACH ROW EXECUTE FUNCTION lab5_reject_metadata();")
try:
upload(c,alice,chat,data,filename=filename,expected=503)
finally:
sql('DROP TRIGGER lab5_reject_metadata ON attachments; DROP FUNCTION lab5_reject_metadata();')
unconfirmed=stage_keys()-old
check(len(unconfirmed)==1,'expected one unconfirmed stage')
check(sql("SELECT count(*) FROM attachments WHERE filename='"+filename+"';")=='0','failed upload published metadata')
orphan=next(iter(unconfirmed))
time.sleep(6)
check(orphan in stage_keys(),'fresh unconfirmed stage deleted before grace')
RESULT['cases']['stage_before_commit']={'upload_status':503,'metadata':0,'fresh_orphan_preserved':True}
if '--tail-only' not in sys.argv:
# COMMIT without publish, then API and broker restart with worker absent.
control('worker',replicas=0)
control('api',{'PIPELINE_PAUSE_PUBLISH':'1'})
item=upload(c,alice,chat,data)['json']
c.message(alice,chat,'',attachments=[item['id']])
c.call('GET','/api/v1/attachments/'+item['id']+'/content',409,actor=bob)
j=job(item)
check(sql("SELECT published_at IS NULL FROM attachment_outbox WHERE job_id='"+j['id']+"';")=='t','publish not paused')
control('api',force=True)
control('redis',force=True)
settled('api',2)
control('api',{'PIPELINE_PAUSE_PUBLISH':None})
until(lambda:sql("SELECT published_at IS NOT NULL FROM attachment_outbox WHERE job_id='"+j['id']+"';")=='t')
before=redis('XRANGE',STREAM,'-','+')
check(any(json.loads(row[1][1])['job_id']==j['id'] for row in before),'job not in stream')
control('redis',force=True)
settled('api',2)
check(any(json.loads(row[1][1])['job_id']==j['id'] for row in redis('XRANGE',STREAM,'-','+')),'broker lost durable job')
control('worker',replicas=1)
variant_check(c,bob,item,data)
RESULT['cases']['commit_publish_and_restarts']={'job_id':j['id'],'api_restart':True,'broker_restarts':2,'link_queued':True}
save();print('PASS: COMMIT/publish gap, queued link, API/broker restarts, worker recovery',flush=True)
# A killed worker leaves deterministic objects before metadata COMMIT/ack.
control('worker',{'WORKER_TIMEOUT_SECONDS':'5','WORKER_LEASE_SECONDS':'12','PIPELINE_FAILPOINT':'after_objects'})
item=upload(c,alice,chat,data)['json']
until(lambda:job(item)['state']=='processing')
until(lambda:probe.mc('stat','local/attachments/original/'+item['id']+'/v1/optimized').returncode==0)
control('worker',{'PIPELINE_FAILPOINT':None})
variant_check(c,bob,item,data)
j=job(item);check(j['attempts']>=2,'expired processing was not retried')
objects=probe.mc('ls','--recursive','--json','local/attachments/original/'+item['id']+'/').stdout.decode().splitlines()
check(sum(json.loads(x).get('type')=='file' for x in objects)==4,'duplicate objects created')
RESULT['cases']['crash_after_objects']={'attempts':j['attempts'],'objects':4,'fence':j['fence']}
save();print('PASS: crash after objects, expired lease/fencing, same four keys',flush=True)
# Ready COMMIT before ack: redelivery must leave metadata unchanged.
control('worker',{'PIPELINE_FAILPOINT':'after_commit'})
item=upload(c,alice,chat,data)['json'];wait_state(item,'ready')
snapshot=c.call('GET','/api/v1/attachments/'+item['id'],actor=bob,schema='Attachment')['json']
check(redis('XPENDING',STREAM,GROUP)[0]>0,'ack happened before crash')
control('worker',{'PIPELINE_FAILPOINT':None})
until(lambda:redis('XPENDING',STREAM,GROUP)[0]==0,timeout=30)
check(c.call('GET','/api/v1/attachments/'+item['id'],actor=bob,schema='Attachment')['json']==snapshot,'ready replay changed metadata')
j=job(item)
envelope={'schema_version':1,'job_id':j['id'],'type':'attachment.process.v1','attachment_id':item['id'],'pipeline_version':1,'attempt':1,'created_at':j['created_at']}
redis('XADD',STREAM,'*','job',json.dumps(envelope))
until(lambda:redis('XLEN',STREAM)==0,timeout=30)
check(c.call('GET','/api/v1/attachments/'+item['id'],actor=bob,schema='Attachment')['json']==snapshot,'duplicate changed ready')
replay(j,False)
RESULT['cases']['commit_before_ack_and_duplicate']={'ready_unchanged':True,'ready_replay_rejected':True}
save();print('PASS: COMMIT before ack, duplicate no-op and ready replay rejection',flush=True)
# Temporary storage error, bounded attempts/backoff, failed registry and audit replay.
control('api',{'WORKER_MAX_ATTEMPTS':'2'})
control('worker',{'PIPELINE_FAILPOINT':'transient'})
item=upload(c,alice,chat,data)['json']
retry=until(lambda:job(item),lambda j:j['state']=='queued' and j['attempts']==1)
delay=(dt.datetime.fromisoformat(retry['available_at'].replace('Z','+00:00'))-dt.datetime.fromisoformat(retry['updated_at'].replace('Z','+00:00'))).total_seconds()
check(1.5<=delay<=2.6,'retry backoff/jitter outside configured range')
failed=wait_state(item,'failed',timeout=30)
check(failed['attempts']==2,'retry limit')
meta=c.call('GET','/api/v1/attachments/'+item['id'],actor=bob,schema='Attachment')['json']
check(meta['error_code']=='retry_exhausted','unsafe final code')
c.call('GET','/api/v1/attachments/'+item['id']+'/content',409,actor=bob)
c.call('POST','/api/v1/chats/'+chat['id']+'/messages',409,actor=alice,body={'text':'','attachment_ids':[item['id']]},headers={'Idempotency-Key':uuid.uuid4().hex})
registry=json.loads(docker('exec',containers('worker')[0],'/usr/local/bin/worker','--failed').stdout)
check(any(row['job_id']==failed['id'] for row in registry),'failed registry missing')
control('worker',{'PIPELINE_FAILPOINT':None})
replay(failed)
variant_check(c,bob,item,data)
check(sql("SELECT count(*) FROM attachment_replays WHERE job_id='"+failed['id']+"';")=='1','replay audit missing')
RESULT['cases']['bounded_retry_replay']={'max_attempts':2,'retry_available_at':retry['available_at'],'first_backoff_seconds':round(delay,3),'failed_attempts':failed['attempts'],'audits':1}
save();print('PASS: bounded retry/backoff, failed registry, safe audited replay',flush=True)
# A permanently corrupted durable stage is not retried endlessly.
control('worker',replicas=0)
item=upload(c,alice,chat,data)['json']
probe.mc('pipe','local/attachments/staging/'+item['id'],data=b'damaged synthetic stage')
control('worker',replicas=1)
failed=wait_state(item,'failed')
check(failed['attempts']==1,'permanent error retried')
check(c.call('GET','/api/v1/attachments/'+item['id'],actor=bob,schema='Attachment')['json']['error_code']=='invalid_image','permanent classification')
RESULT['cases']['permanent_stage_error']={'attempts':1,'error_code':'invalid_image'}
permanent_att=item
permanent_job=failed
# Deadline kills the renderer AND its real cwebp child blocked on a FIFO.
control('api',{'WORKER_MAX_ATTEMPTS':'1'})
control('worker',{'WORKER_TIMEOUT_SECONDS':'2','WORKER_LEASE_SECONDS':'7','PIPELINE_FAILPOINT':'renderer_timeout'})
item=upload(c,alice,chat,data)['json'];started=time.monotonic()
seen=until(lambda:docker('exec',containers('worker')[0],'ps','-o','pid,args').stdout.decode(),lambda text:'cwebp -quiet' in text,timeout=10)
wait_state(item,'failed',timeout=15)
elapsed=time.monotonic()-started
processes=docker('exec',containers('worker')[0],'ps','-o','pid,args').stdout.decode()
check('cwebp -quiet' not in processes and '/worker render' not in processes,'renderer descendant survived timeout')
RESULT['cases']['renderer_process_group_timeout']={'deadline_seconds':2,'elapsed_seconds':round(elapsed,3),'cwebp_observed':True,'descendants_after_failure':0}
control('worker',{'PIPELINE_FAILPOINT':None,'WORKER_TIMEOUT_SECONDS':'25','WORKER_LEASE_SECONDS':'40'})
control('api',{'WORKER_MAX_ATTEMPTS':None})
# Every ready stage is eventually collected; linked final objects remain.
until(lambda:sql("SELECT count(*) FROM attachments WHERE status='ready' AND staging_key IS NOT NULL;")=='0',timeout=45)
check(c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=bob)['bytes']==data,'cleanup removed ready original')
sql("UPDATE attachments SET created_at=created_at-interval '8 days',updated_at=clock_timestamp()-interval '8 days' WHERE id='"+permanent_att['id']+"';")
until(lambda:sql("SELECT storage_cleaned_at IS NOT NULL AND staging_key IS NULL FROM attachments WHERE id='"+permanent_att['id']+"';")=='t',timeout=45)
replay(permanent_job,False)
until(lambda:orphan not in stage_keys(),timeout=100)
RESULT['cases']['staging_cleanup']={'ready_stages_remaining':0,'linked_original_preserved':True,'failed_retention_days':7,'expired_failed_stage_removed':True,'expired_replay_rejected':True,'unconfirmed_orphan_removed':True}
required={'input_and_acl','small_alpha_exif','private_s3','stage_before_commit','commit_publish_and_restarts','crash_after_objects','commit_before_ack_and_duplicate','bounded_retry_replay','permanent_stage_error','renderer_process_group_timeout','staging_cleanup'}
check(required.issubset(RESULT['cases']),'incomplete fault evidence')
RESULT['finished_at']=time.time();save()
print('PASS: all lab5 fault, retry, replay, durability, rendering and cleanup checks',flush=True)
if __name__=='__main__':
try:
main()
finally:
# Restore ordinary service configuration even if an assertion fails.
try:
control('worker',{'PIPELINE_FAILPOINT':None,'WORKER_TIMEOUT_SECONDS':'25','WORKER_LEASE_SECONDS':'40'},replicas=1)
control('api',{'WORKER_MAX_ATTEMPTS':None,'PIPELINE_PAUSE_PUBLISH':None})
finally:
save()