forked from mtusi2026/mtusi2026lab5
Complete Lab 5: implementation, fault scenarios, and Track 1 report
This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Hold worker, prove queue admission cap, then recover accepted work."""
|
||||
import hashlib, json, os, subprocess, time
|
||||
from pathlib import Path
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
def compose(*args,capacity=None):
|
||||
env=os.environ.copy()
|
||||
if capacity is not None: env['MAX_QUEUED_JOBS']=str(capacity)
|
||||
subprocess.run(['docker','compose',*args],cwd=ROOT,env=env,check=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
|
||||
|
||||
def main():
|
||||
a=arguments('Queue admission backpressure under worker outage')
|
||||
compose('up','-d','--force-recreate','--scale','api=2','api',capacity=1)
|
||||
compose('stop','worker')
|
||||
try:
|
||||
c=Client(a.base_url,a.ca_file); alice,bob,_,chat=c.bootstrap(); raw=(ROOT/'tests/fixtures/sample.png').read_bytes(); path='/api/v1/chats/'+chat['id']+'/attachments?filename=backpressure.png'
|
||||
first=c.call('POST',path,202,actor=alice,raw=raw,headers={'Content-Type':'image/png'},schema='Attachment')['json']
|
||||
started=time.monotonic()
|
||||
c.call('POST',path,503,actor=alice,raw=raw,headers={'Content-Type':'image/png'})
|
||||
compose('up','-d','--force-recreate','worker')
|
||||
ready=c.wait_ready(bob,first,wait_seconds=90)
|
||||
compose('up','-d','--force-recreate','--scale','api=2','api')
|
||||
result={'queue_limit':1,'worker_stopped':True,'first_upload_status':202,'next_upload_status':503,'accepted_attachment_id':first['id'],'final_status':ready['status'],'original_sha256_matches':ready['sha256']==hashlib.sha256(raw).hexdigest(),'recovery_seconds':round(time.monotonic()-started,3),'note':'503 admission refusal leaves the already accepted job intact.'}
|
||||
dest=ROOT/'evidence/backpressure.json'; dest.write_text(json.dumps(result,indent=2)+'\n'); print(json.dumps(result,indent=2))
|
||||
finally:
|
||||
compose('up','-d','--force-recreate','worker')
|
||||
compose('up','-d','--force-recreate','--scale','api=2','api')
|
||||
|
||||
if __name__=='__main__': run(main)
|
||||
@@ -0,0 +1,37 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Publish a queued job into Redis Streams, restart broker with AOF volume, then consume."""
|
||||
import hashlib, json, os, subprocess, time
|
||||
from pathlib import Path
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
def compose(*args,pause=None,output=False):
|
||||
env=os.environ.copy()
|
||||
if pause is not None: env['WORKER_PAUSE_CONSUME']=str(pause)
|
||||
cmd=['docker','compose',*args]
|
||||
return subprocess.check_output(cmd,cwd=ROOT,env=env,text=True) if output else subprocess.run(cmd,cwd=ROOT,env=env,check=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
|
||||
|
||||
def stream_len(): return int(compose('exec','-T','broker','redis-cli','XLEN','attachment-jobs',output=True).strip())
|
||||
|
||||
def main():
|
||||
a=arguments('Broker volume restart with one published, unconsumed job')
|
||||
compose('up','-d','--force-recreate','worker',pause=1)
|
||||
try:
|
||||
c=Client(a.base_url,a.ca_file); alice,bob,_,chat=c.bootstrap(); before=stream_len(); raw=(ROOT/'tests/fixtures/sample.png').read_bytes()
|
||||
path='/api/v1/chats/'+chat['id']+'/attachments?filename=broker-restart.png'
|
||||
att=c.call('POST',path,202,actor=alice,raw=raw,headers={'Content-Type':'image/png'},schema='Attachment')['json']
|
||||
deadline=time.monotonic()+20
|
||||
while stream_len()<=before and time.monotonic()<deadline: time.sleep(.1)
|
||||
published=stream_len(); check(published>before,'outbox relay did not publish the queued job')
|
||||
status=c.call('GET','/api/v1/attachments/'+att['id'],actor=bob,schema='Attachment')['json']['status']
|
||||
check(status=='queued','paused worker unexpectedly consumed the job')
|
||||
time.sleep(1.2); compose('stop','worker'); compose('restart','broker')
|
||||
after=stream_len(); check(after>=published,'Redis AOF volume lost the published stream entry')
|
||||
compose('up','-d','--force-recreate','worker',pause=0)
|
||||
ready=c.wait_ready(bob,att,wait_seconds=90)
|
||||
check(ready['status']=='ready' and ready['sha256']==hashlib.sha256(raw).hexdigest(),'job did not finish after broker restart')
|
||||
result={'attachment_id':att['id'],'status_before_broker_restart':status,'stream_length_before_restart':published,'stream_length_after_restart':after,'final_status':ready['status'],'original_sha256_matches':True,'result':'PASS'}
|
||||
(ROOT/'evidence/broker-restart.json').write_text(json.dumps(result,indent=2)+'\n'); print(json.dumps(result,indent=2))
|
||||
finally: compose('up','-d','--force-recreate','worker',pause=0)
|
||||
|
||||
if __name__=='__main__': run(main)
|
||||
@@ -0,0 +1,18 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Requires worker recreated with FAULT_AFTER_S3_WRITE_ONCE=1 and timeout=5s."""
|
||||
import json, subprocess, time
|
||||
from pathlib import Path
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
def main():
|
||||
a=arguments('Crash after deterministic S3 side effect, then verify redelivery')
|
||||
c=Client(a.base_url,a.ca_file); alice,bob,_,chat=c.bootstrap()
|
||||
before=int(subprocess.check_output(['docker','inspect','-f','{{.RestartCount}}','mtusi_lab5_solution-worker-1'],text=True).strip())
|
||||
att,raw=c.attachment(alice,chat); started=time.monotonic(); ready=c.wait_ready(bob,att,wait_seconds=90)
|
||||
after=int(subprocess.check_output(['docker','inspect','-f','{{.RestartCount}}','mtusi_lab5_solution-worker-1'],text=True).strip())
|
||||
check(after>before,'fault injection did not restart the worker')
|
||||
check(ready['status']=='ready' and len(ready['variants'])==3,'redelivery did not preserve one complete variant set')
|
||||
result={'scenario':'crash after original+variant S3 writes, before PostgreSQL ready commit and consumer ack','attachment_id':att['id'],'worker_restart_count_before':before,'worker_restart_count_after':after,'status':'ready','variants':[v['name'] for v in ready['variants']],'original_sha256_matches':ready['sha256']==__import__('hashlib').sha256(raw).hexdigest(),'recovery_seconds':round(time.monotonic()-started,3),'delivery':'Redis Streams at-least-once; deterministic object keys; DB ready commit precedes ack'}
|
||||
dest=Path('evidence/fault-redelivery.json'); dest.write_text(json.dumps(result,indent=2)+'\n'); print(json.dumps(result,indent=2))
|
||||
|
||||
if __name__=='__main__': run(main)
|
||||
@@ -0,0 +1,68 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Closed-loop image pipeline experiment; call once per WORKER_CONCURRENCY setting."""
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
import hashlib, io, json, math, os, random, subprocess, threading, time
|
||||
from pathlib import Path
|
||||
from client import Client, arguments, check, run
|
||||
from PIL import Image
|
||||
|
||||
def main():
|
||||
def configure(p):
|
||||
p.add_argument('--count',type=int,default=24)
|
||||
p.add_argument('--profile',choices=['small','mixed','large'],default='mixed')
|
||||
p.add_argument('--upload-concurrency',type=int,default=8)
|
||||
p.add_argument('--worker-concurrency',type=int,required=True)
|
||||
p.add_argument('--output',required=True)
|
||||
a=arguments('Synthetic image pipeline throughput, queue wait, ready latency and worker RSS',configure)
|
||||
check(1<=a.count<=500 and 1<=a.upload_concurrency<=64,'invalid experiment bounds')
|
||||
c=Client(a.base_url,a.ca_file,timeout=30); alice,bob,_,chat=c.bootstrap()
|
||||
profiles={'small':[(320,200)],'mixed':[(320,200),(1024,768),(2048,1536)],'large':[(2048,1536)]}
|
||||
dimensions=profiles[a.profile]
|
||||
random.seed(20261106)
|
||||
def image_bytes(index):
|
||||
w,h=dimensions[index%len(dimensions)]; rng=random.Random(index+700)
|
||||
im=Image.frombytes('RGB',(w,h),rng.randbytes(w*h*3))
|
||||
buf=io.BytesIO(); im.save(buf,format='PNG',compress_level=1); return buf.getvalue(),(w,h)
|
||||
barrier=threading.Barrier(a.upload_concurrency)
|
||||
def upload(i):
|
||||
raw,size=image_bytes(i); local=Client(a.base_url,a.ca_file,timeout=60); barrier.wait()
|
||||
t=time.monotonic()
|
||||
res=local.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=bench-%s.png'%i,202,actor=alice,raw=raw,headers={'Content-Type':'image/png'},schema='Attachment')
|
||||
return {'id':res['json']['id'],'accepted':time.monotonic(),'upload_seconds':time.monotonic()-t,'size_bytes':len(raw),'source_size':size}
|
||||
rss=[]; stop=threading.Event()
|
||||
def sample_rss():
|
||||
while not stop.is_set():
|
||||
try:
|
||||
out=subprocess.check_output(['docker','stats','--no-stream','--format','{{.MemUsage}}','mtusi_lab5_solution-worker-1'],stderr=subprocess.DEVNULL,text=True,timeout=3).strip()
|
||||
used=out.split('/')[0].strip(); rss.append(used)
|
||||
except Exception: pass
|
||||
stop.wait(.25)
|
||||
sampler=threading.Thread(target=sample_rss,daemon=True); sampler.start()
|
||||
started=time.monotonic()
|
||||
with ThreadPoolExecutor(max_workers=a.upload_concurrency) as pool: jobs=list(pool.map(upload,range(a.count)))
|
||||
upload_done=time.monotonic(); pending={x['id']:x for x in jobs}; ready_ms=[]; queue_wait_ms=[]; deadline=time.monotonic()+180
|
||||
while pending and time.monotonic()<deadline:
|
||||
for aid,item in list(pending.items()):
|
||||
status=c.call('GET','/api/v1/attachments/'+aid,actor=alice,schema='Attachment')['json']
|
||||
now=time.monotonic()
|
||||
if status['status']=='failed': raise RuntimeError('pipeline job failed')
|
||||
if status['status']=='processing' and 'first_processing' not in item: item['first_processing']=now
|
||||
if status['status']=='ready':
|
||||
ready_ms.append((now-item['accepted'])*1000)
|
||||
queue_wait_ms.append(((item.get('first_processing',now))-item['accepted'])*1000)
|
||||
del pending[aid]
|
||||
if pending: time.sleep(.1)
|
||||
stop.set(); sampler.join(timeout=2)
|
||||
check(not pending,'ready timeout for %s attachments'%len(pending))
|
||||
elapsed=time.monotonic()-started
|
||||
def pct(xs,p): return round(sorted(xs)[max(0,math.ceil(p*len(xs))-1)],2) if xs else None
|
||||
def mib(v):
|
||||
try:
|
||||
token=v.split()[0]; n=float(token[:-3]); unit=token[-3:]
|
||||
return n*(1024 if unit=='GiB' else 1)
|
||||
except Exception:return -1
|
||||
peak=max(rss,key=mib) if rss else None
|
||||
result={'track':'queue-overload','profile':a.profile,'worker_concurrency':a.worker_concurrency,'upload_concurrency':a.upload_concurrency,'accepted':len(jobs),'failed':0,'elapsed_seconds':round(elapsed,3),'throughput_ready_per_second':round(len(jobs)/elapsed,3),'ready_latency_ms':{'p50':pct(ready_ms,.5),'p95':pct(ready_ms,.95),'p99':pct(ready_ms,.99)},'estimated_queue_wait_ms':{'p50':pct(queue_wait_ms,.5),'p95':pct(queue_wait_ms,.95)},'worker_rss_samples':rss,'worker_rss_peak_sample':peak,'total_upload_bytes':sum(x['size_bytes'] for x in jobs),'limitation':'Closed-loop synthetic workload; queue wait is bounded by 100 ms status polling and can miss short processing states. Docker RSS sampling is 250 ms.'}
|
||||
dest=Path(a.output); dest.parent.mkdir(parents=True,exist_ok=True); dest.write_text(json.dumps(result,indent=2)+'\n'); print(json.dumps(result,indent=2))
|
||||
|
||||
if __name__=='__main__': run(main)
|
||||
@@ -0,0 +1,41 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Induce transient missing-stage errors, observe bounded DLQ, restore and explicitly replay."""
|
||||
import hashlib, json, subprocess, time, uuid
|
||||
from pathlib import Path
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
def compose(*args,output=False):
|
||||
return subprocess.check_output(['docker','compose',*args],cwd=ROOT,text=True) if output else subprocess.run(['docker','compose',*args],cwd=ROOT,check=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
|
||||
def main():
|
||||
a=arguments('Bounded retry, DLQ, and explicit failed-job replay')
|
||||
compose('stop','worker')
|
||||
try:
|
||||
c=Client(a.base_url,a.ca_file); alice,bob,_,chat=c.bootstrap(); raw=(ROOT/'tests/fixtures/sample.png').read_bytes()
|
||||
path='/api/v1/chats/'+chat['id']+'/attachments?filename=retry.png'
|
||||
att=c.call('POST',path,202,actor=alice,raw=raw,headers={'Content-Type':'image/png'},schema='Attachment')['json']
|
||||
aid=str(uuid.UUID(att['id'])); chatid=str(uuid.UUID(chat['id']))
|
||||
sql="UPDATE attachments SET staging_key='staging/%s/%s/missing' WHERE id='%s'::uuid"%(chatid,aid,aid)
|
||||
compose('exec','-T','postgres','psql','-U','messenger','-d','messenger','-Atc',sql)
|
||||
compose('up','-d','--force-recreate','worker')
|
||||
started=time.monotonic(); deadline=started+120; state=None
|
||||
while time.monotonic()<deadline:
|
||||
state=c.call('GET','/api/v1/attachments/'+aid,actor=bob,schema='Attachment')['json']
|
||||
if state['status']=='failed': break
|
||||
time.sleep(.5)
|
||||
check(state and state['status']=='failed' and state['error_code']=='retry_exhausted','job did not reach bounded retry_exhausted state')
|
||||
dlq=int(compose('exec','-T','broker','redis-cli','XLEN','attachment-jobs-dlq',output=True).strip())
|
||||
check(dlq>=1,'terminal failure was not recorded in DLQ')
|
||||
restore="UPDATE attachments SET staging_key='staging/%s/%s' WHERE id='%s'::uuid"%(chatid,aid,aid)
|
||||
compose('exec','-T','postgres','psql','-U','messenger','-d','messenger','-Atc',restore)
|
||||
compose('run','--rm','--no-deps','worker','python','scripts/replay_failed.py',aid)
|
||||
ready=c.wait_ready(bob,att,wait_seconds=90)
|
||||
check(ready['status']=='ready' and ready['sha256']==hashlib.sha256(raw).hexdigest(),'explicit replay did not complete original attachment')
|
||||
# A successful logical job cannot be force-run through the failed-only operator command.
|
||||
refused=subprocess.run(['docker','compose','run','--rm','--no-deps','worker','python','scripts/replay_failed.py',aid],cwd=ROOT,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
|
||||
check(refused.returncode!=0,'replay command accepted a ready job')
|
||||
result={'attachment_id':aid,'induced_fault':'staging key temporarily pointed to missing object','terminal_error_code':'retry_exhausted','attempt_limit':5,'dlq_length_after_failure':dlq,'explicit_replay':'ready','ready_sha256_matches':True,'replay_of_ready_job':'refused','elapsed_seconds':round(time.monotonic()-started,3)}
|
||||
(ROOT/'evidence/retry-replay.json').write_text(json.dumps(result,indent=2)+'\n'); print(json.dumps(result,indent=2))
|
||||
finally: compose('up','-d','--force-recreate','worker')
|
||||
|
||||
if __name__=='__main__': run(main)
|
||||
@@ -0,0 +1,30 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Worker outage: accept durable upload, restart API, then process same job."""
|
||||
import json, subprocess, time
|
||||
from pathlib import Path
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
def compose(*args): subprocess.run(['docker','compose',*args],check=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
|
||||
|
||||
def main():
|
||||
a=arguments('Stop worker, accept upload, restart API, restore worker')
|
||||
c=Client(a.base_url,a.ca_file); alice,bob,_,chat=c.bootstrap(); started=time.monotonic(); compose('stop','worker')
|
||||
try:
|
||||
att,raw=c.attachment(alice,chat)
|
||||
check(att['status']=='queued','upload was not queued while worker stopped')
|
||||
compose('restart','api')
|
||||
deadline=time.monotonic()+45
|
||||
while time.monotonic()<deadline:
|
||||
try: c.call('GET','/health/ready',schema='Health'); break
|
||||
except Exception: time.sleep(.4)
|
||||
after=c.call('GET','/api/v1/attachments/'+att['id'],actor=bob,schema='Attachment')['json']
|
||||
check(after['status'] in ('queued','processing'),'accepted job did not survive API restart')
|
||||
compose('up','-d','--force-recreate','worker')
|
||||
ready=c.wait_ready(bob,att,wait_seconds=90)
|
||||
check(ready['status']=='ready','job was lost after worker restart')
|
||||
result={'attachment_id':att['id'],'upload_status':202,'status_without_worker_after_api_restart':after['status'],'final_status':ready['status'],'original_sha256_matches':ready['sha256']==__import__('hashlib').sha256(raw).hexdigest(),'variants':[v['name'] for v in ready['variants']],'recovery_seconds':round(time.monotonic()-started,3)}
|
||||
dest=Path('evidence/worker-outage.json'); dest.write_text(json.dumps(result,indent=2)+'\n'); print(json.dumps(result,indent=2))
|
||||
finally:
|
||||
compose('up','-d','--force-recreate','worker')
|
||||
|
||||
if __name__=='__main__': run(main)
|
||||
Reference in New Issue
Block a user