Files
mtusi2026lab6/student-tests/slo_research.py
T

123 lines
6.7 KiB
Python

"""Track 2. Real short/long incidents, twice for each domain, with control periods."""
import argparse
from concurrent.futures import ThreadPoolExecutor
import json
import math
import threading
import time
from common import *
def percentile(values,q):
values=sorted(values)
return values[min(len(values)-1, math.ceil(len(values)*q)-1)] if values else None
def run_case(domain, repeat):
c=Client(BASE);alice,bob,eve,chat=c.bootstrap()
stop=threading.Event();lock=threading.Lock()
rows=[];uploads=[];samples=[];phases=[]
phase='warmup'
db_fault=DBLock()
started=time.time()
def messages(index):
time.sleep(index*.5)
while not stop.is_set():
start=time.monotonic()
label=phase
try:
r=c.call('POST','/api/v1/chats/'+chat['id']+'/messages',[201,503],actor=alice,
body={'text':'synthetic SLO control'},headers={'Idempotency-Key':str(time.time_ns())},schema='Message')
row={'time':time.time(),'phase':label,'kind':'message','status':r['status'],
'elapsed':r['elapsed'],'trace_id':r['headers'].get('X-Trace-Id')}
except Exception as exc:
row={'time':time.time(),'phase':label,'kind':'message','status':0,'error':type(exc).__name__,'elapsed':time.monotonic()-start}
with lock:rows.append(row)
stop.wait(max(0,3-(time.monotonic()-start)))
def images():
while not stop.is_set():
start=time.monotonic();label=phase
try:
r=c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=slo.png',[202,503],
actor=alice,raw=(ROOT/'tests/fixtures/sample.png').read_bytes(),headers={'Content-Type':'image/png'},schema='Attachment')
with lock:
rows.append({'time':time.time(),'phase':label,'kind':'upload','status':r['status'],'elapsed':r['elapsed']})
if r['status']==202:uploads.append(r['json'])
except Exception as exc:
with lock:rows.append({'time':time.time(),'phase':label,'kind':'upload','status':0,'error':type(exc).__name__,'elapsed':time.monotonic()-start})
stop.wait(max(0,2-(time.monotonic()-start)))
def sampler():
counter=0
while not stop.is_set():
try:
record={'time':time.time(),'phase':phase,'alerts':query('prometheus','/api/v1/alerts')['data']['alerts'],
'queue_age':prom('messenger_queue_oldest_seconds'),'queue_depth':prom('messenger_queue_depth'),
'ready_bad':prom('messenger_ready_window_bad'),'ready_total':prom('messenger_ready_window_total')}
if counter%3==0:record['stats']=dc('stats','--no-stream','--format','json')
samples.append(record)
counter+=1
except Exception as exc:samples.append({'time':time.time(),'query_error':type(exc).__name__})
stop.wait(3)
def wait(label,seconds):
nonlocal phase
phase=label;phases.append({'name':label,'time':time.time(),'duration_planned':seconds})
print(domain,repeat,label,seconds,flush=True)
until=time.monotonic()+seconds
while time.monotonic()<until:time.sleep(min(1,until-time.monotonic()))
def fault(on):
if domain=='worker':dc('stop' if on else 'start',*(['-t','2'] if on else []),'worker')
else:
db_fault.start() if on else db_fault.stop()
before=snapshot()
with ThreadPoolExecutor(max_workers=8) as pool:
tasks=[pool.submit(messages,i) for i in range(6)]+[pool.submit(sampler)]
if domain=='worker':tasks.append(pool.submit(images))
try:
wait('warmup',35)
fault(True)
try:wait('brief',4)
finally:fault(False)
wait('brief_recovery',40)
fault(True)
try:wait('sustained',75)
finally:fault(False)
wait('recovery',100)
finally:
stop.set()
for task in tasks:task.result()
for att in uploads:c.wait_ready(alice,att,wait_seconds=60)
report={'domain':domain,'repeat':repeat,'started':started,'ended':time.time(),'before':before,'after':snapshot(),
'phases':phases,'samples':samples,'requests':rows,'accepted_uploads':len(uploads),'all_accepted_ready':True}
prefix='API' if domain=='db' else 'Ready'
sustained=next(p['time'] for p in phases if p['name']=='sustained')
restored=next(p['time'] for p in phases if p['name']=='recovery')
brief_end=next(p['time'] for p in phases if p['name']=='brief_recovery')+50
for speed in ('Fast','Slow'):
name=prefix+'Burn'+speed
def firing(sample):return any(a['labels']['alertname']==name and a['state']=='firing' for a in sample.get('alerts',[]))
fired=[s['time'] for s in samples if sustained<=s['time']<restored and firing(s)]
false=[s['time'] for s in samples if s.get('phase') in ('warmup','brief','brief_recovery') and firing(s)]
resolved=next((s['time'] for s in samples if s['time']>=restored and not firing(s) and fired),None)
report.setdefault('alerts',{})[name]={'detected_seconds':min(fired)-sustained if fired else None,
'resolved_seconds_after_restore':resolved-restored if resolved else None,'control_firing_samples':len(false)}
report['summaries']={}
for label in ['warmup','brief','brief_recovery','sustained','recovery']:
selected=[r for r in rows if r['phase']==label and r['kind']=='message']
good=[r['elapsed'] for r in selected if r['status']==201]
duration=next(p['duration_planned'] for p in phases if p['name']==label)
report['summaries'][label]={'requests':len(selected),'successes':len(good),'errors':len(selected)-len(good),
'successful_rps':len(good)/duration,'p50_success_s':percentile(good,.5),
'p95_success_s':percentile(good,.95),'p99_success_s':percentile(good,.99)}
save(f'slo-{domain}-{repeat}.json',report)
check(all(x['detected_seconds'] is not None for x in report['alerts'].values()),'burn alert not detected')
check(all(x['resolved_seconds_after_restore'] is not None for x in report['alerts'].values()),'burn alert not resolved')
check(all(x['control_firing_samples']==0 for x in report['alerts'].values()),'control/brief fired burn alert')
print('PASS',domain,repeat,json.dumps(report['alerts']),flush=True)
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('--domain',choices=['db','worker','both'],default='both');p.add_argument('--repeats',type=int,default=2)
args=p.parse_args()
for domain in (['db','worker'] if args.domain=='both' else [args.domain]):
for repeat in range(1,args.repeats+1):run_case(domain,repeat)