Завершить трек 2: burn-rate alerts, повторные эксперименты и отчёт

This commit is contained in:
2026-11-27 17:23:49 +03:00
parent 0355ba13d2
commit a5c650bcf5
50 changed files with 69318 additions and 300 deletions
+37
View File
@@ -0,0 +1,37 @@
"""HTTP boundary checks against unchanged course semantics, using synthetic bytes."""
import json
import math
import struct
import urllib.parse
import zlib
from common import *
def main():
c=Client(BASE);alice,bob,eve,chat=c.bootstrap()
payload=(ROOT/'tests/fixtures/sample.png').read_bytes()
path='/api/v1/chats/'+chat['id']+'/attachments?filename='
outcomes=[]
for filename in ['../x.png','a\\b.png','bad\x00.png']:
r=c.call('POST',path+urllib.parse.quote(filename,safe=''),400,actor=alice,raw=payload,headers={'Content-Type':'image/png'})
outcomes.append({'case':'invalid filename','status':r['status']})
oversized=(payload*math.ceil((10485760+1)/len(payload)))[:10485761]
r=c.call('POST',path+'large.png',413,actor=alice,raw=oversized,headers={'Content-Type':'image/png'})
outcomes.append({'case':'actual 10 MiB + 1 byte','status':r['status']})
huge=bytearray(payload)
struct.pack_into('>II',huge,16,40001,1001)
struct.pack_into('>I',huge,29,zlib.crc32(huge[12:29]))
r=c.call('POST',path+'pixels.png',413,actor=alice,raw=bytes(huge),headers={'Content-Type':'image/png'})
outcomes.append({'case':'40041001 declared pixels before decode','status':r['status']})
r=c.call('POST',path+'wrong.jpg',415,actor=alice,raw=payload,headers={'Content-Type':'image/jpeg'})
outcomes.append({'case':'MIME/content mismatch','status':r['status']})
key='semantic-'+str(time.time_ns())
first=c.message(alice,chat,'semantic',key=key)['json']
repeat=c.message(alice,chat,'semantic',key=key,attachments=[])['json']
check(first==repeat,'omitted/empty attachments idempotency differs')
c.call('POST','/api/v1/chats/'+chat['id']+'/messages',400,actor=alice,body={'text':'bad','sender_id':eve['id']},headers={'Idempotency-Key':'invalid-'+key})
save('bounds.json',{'checks':outcomes,'semantic_replay_equal':True,'spoofed_sender_rejected':True})
print('PASS: real byte/pixel limits, MIME, filename, semantic replay and sender spoof rejection')
if __name__=='__main__':main()
+4 -2
View File
@@ -38,10 +38,11 @@ def prom(expr):
class DBLock:
"""Bounded SQL lock in this project's DB; health reads remain usable."""
def start(self):
def start(self,table='messages'):
check(table in ('messages','attachment_variants'),'unsupported fault table')
self.process=subprocess.Popen(['docker','compose','-p',PROJECT,'exec','-T','db',
'env','PGAPPNAME=lab6-fault-lock','psql','-U','messenger','-d','messenger','-c',
'BEGIN; LOCK TABLE messages IN ACCESS EXCLUSIVE MODE; SELECT pg_sleep(180); COMMIT;'],
f'BEGIN; LOCK TABLE {table} IN ACCESS EXCLUSIVE MODE; SELECT pg_sleep(180); COMMIT;'],
cwd=ROOT,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
time.sleep(.5)
check(self.process.poll() is None,'SQL fault process failed')
@@ -57,6 +58,7 @@ def snapshot():
result=[]
for row in json.loads(subprocess.check_output(['docker','inspect',*ids],text=True)):
result.append({'id':row['Id'],'service':row['Config']['Labels']['com.docker.compose.service'],
'image_id':row['Image'],'image_name':row['Config']['Image'],
'started_at':row['State']['StartedAt'],'status':row['State']['Status'],
'oom_killed':row['State']['OOMKilled'],
'memory_limit':row['HostConfig']['Memory'],'nano_cpus':row['HostConfig']['NanoCpus']})
+2
View File
@@ -41,6 +41,8 @@ def main():
'messenger_jobs_total','messenger_job_duration_seconds_bucket','messenger_ready_duration_seconds_bucket',
'messenger_worker_capacity','messenger_db_pool_used','messenger_queue_depth']}
check(all(signals.values()),'required metric missing')
check(all(row['metric'].get('queue')=='attachment.process.v1' for row in signals['messenger_queue_depth']),
'queue name missing from backlog signal')
forbidden={'user_id','chat_id','message_id','attachment_id','request_id','filename'}
check(not any(forbidden & set(row['metric']) for rows in signals.values() for row in rows),'high cardinality metric label')
telemetry=json.dumps([doc,logs,signals])
+122
View File
@@ -0,0 +1,122 @@
"""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)
+36
View File
@@ -0,0 +1,36 @@
"""Recreate storage containers with the same volumes; verify historical signals."""
import json
import time
from common import *
def main():
evidence=json.loads((ROOT/'evidence/signals.json').read_text(encoding='utf-8'))
tid=evidence['trace_id']
stamps=[int(v[0]) for stream in evidence['logs']['data']['result'] for v in stream['values']]
params={'query':'{service_name=~"messenger-api|messenger-worker|messenger-dispatcher"} |= "'+tid+'"',
'start':str(min(stamps)-10**9),'end':str(max(stamps)+10**9),'limit':100}
historical_time=time.time()-10
def observe():
_,spans=trace_wait(tid)
logs=query('loki','/loki/api/v1/query_range',**params)
metrics=query('prometheus','/api/v1/query',query='messenger_http_requests_total',time=historical_time)
return {'span_ids':sorted(s['id'] for s in spans),
'logs':sorted(v for stream in logs['data']['result'] for v in stream['values']),
'metrics':sorted(metrics['data']['result'],key=lambda row:json.dumps(row['metric'],sort_keys=True))}
before=observe()
check(before['logs'] and before['metrics'] and before['span_ids'],'historical signals absent before test')
containers=snapshot()
dc('up','-d','--no-deps','--no-build','--force-recreate','prometheus','loki','tempo','grafana')
subprocess.check_call([sys.executable,'scripts/wait_ready.py','--project',PROJECT,'--base-url',BASE,'--telemetry'],cwd=ROOT)
after=observe()
result={'before_containers':containers,'after_containers':snapshot(),'trace_id':tid,
'historical_query_time':historical_time,'span_count':len(before['span_ids']),'log_count':len(before['logs']),
'metric_series':len(before['metrics']),'same_spans':before['span_ids']==after['span_ids'],
'same_logs':before['logs']==after['logs'],'same_metrics':before['metrics']==after['metrics']}
save('telemetry-persistence.json',result)
check(result['same_spans'] and result['same_logs'] and result['same_metrics'],'historical signals differ after recreate')
print('PASS: historical traces, logs and metrics survive storage container recreation with volumes')
if __name__=='__main__':main()
+38
View File
@@ -0,0 +1,38 @@
"""SQL failure at result publication must be retry, followed by lease recovery."""
import hashlib
import json
import time
from common import *
def main():
c=Client(BASE);alice,bob,eve,chat=c.bootstrap()
dc('stop','-t','2','worker')
response=c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=db-retry.png',202,
actor=alice,raw=(ROOT/'tests/fixtures/sample.png').read_bytes(),headers={'Content-Type':'image/png'},schema='Attachment')
tid=response['headers']['X-Trace-Id'];att=response['json']
lock=DBLock();lock.start('attachment_variants')
before=snapshot();start=time.time()
try:
dc('start','worker')
deadline=time.monotonic()+30
while time.monotonic()<deadline:
logs=query('loki','/loki/api/v1/query_range',query='{service_name="messenger-worker"} |= "'+tid+'" |= "retry"',limit=20)
if logs['data']['result']:break
time.sleep(1)
check(bool(logs['data']['result']),'SQL result failure not recorded as retry')
finally:lock.stop()
ready=c.wait_ready(alice,att,wait_seconds=120)
for variant in ['original','thumbnail','crop','optimized']:
download=c.call('GET','/api/v1/attachments/'+att['id']+'/content?variant='+variant,actor=alice)
expected=ready if variant=='original' else next(v for v in ready['variants'] if v['name']==variant)
check(hashlib.sha256(download['bytes']).hexdigest()==expected['sha256'],'bytes changed during SQL retry')
time.sleep(3)
doc,spans=trace_wait(tid)
check(any(s['status'].get('code')=='STATUS_CODE_ERROR' for s in spans if s['kind']=='SPAN_KIND_CONSUMER'),'consumer error missing')
save('worker-db-failure.json',{'trace_id':tid,'attachment_id':att['id'],'before':before,'after':snapshot(),
'duration':time.time()-start,'retry_logs':logs,'spans':spans,'result':'ready; all four checksums match'})
print('PASS: result publication SQL failure recorded as retry, lease recovery, immutable bytes')
if __name__=='__main__':main()