"""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()=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)