Implement observable messenger, SLO alerts and measured incident scenarios

This commit is contained in:
2026-10-23 13:09:22 +03:00
parent 470d9d6f1e
commit b7540190c1
66 changed files with 96519 additions and 39 deletions
+39
View File
@@ -0,0 +1,39 @@
"""Create local, separate API/worker/storage-admin credentials; never print values."""
import json
from pathlib import Path
import secrets
root=Path(__file__).resolve().parents[1]
required=['.env.api','.env.worker','.env.storage-admin','secrets/s3.json','secrets/broker.conf','secrets/grafana-password']
if (root/'.env').exists():
if not all((root/p).exists() for p in required):
raise SystemExit('Incomplete local configuration; preserve and restore missing files')
print('Existing local configuration preserved')
else:
password=secrets.token_hex(24)
broker_password=secrets.token_hex(24)
keys={role:(secrets.token_hex(12),secrets.token_hex(32)) for role in ('admin','api','worker')}
common=f'DATABASE_URL=postgresql://messenger:{password}@db:5432/messenger\nREDIS_URL=redis://cache:6379/0\nCURSOR_SECRET={secrets.token_hex(32)}\nSESSION_TTL_SECONDS=3600\n'
def storage(role):
key,secret=keys[role]
return f'S3_ENDPOINT=http://s3:8333\nS3_BUCKET=messenger\nS3_ACCESS_KEY={key}\nS3_SECRET_KEY={secret}\n'
common+='OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318\nTELEMETRY_ENABLED=1\nTRACE_SAMPLE_RATIO=1\n'
files={'.env':f'POSTGRES_PASSWORD={password}\n',
'secrets/grafana-password':secrets.token_urlsafe(24)+'\n',
'.env.api':common+storage('api'),
'.env.worker':common+storage('worker')+f'BROKER_URL=redis://:{broker_password}@broker:6379/0\n',
'.env.storage-admin':storage('admin'),
'secrets/broker.conf':f'bind 0.0.0.0\nprotected-mode yes\nrequirepass {broker_password}\nappendonly yes\nappendfsync always\ndir /data\nsave ""\nmaxmemory 64mb\nmaxmemory-policy noeviction\nauto-aof-rewrite-min-size 16mb\n',
'secrets/s3.json':json.dumps({'identities':[
{'name':role,'credentials':[{'accessKey':keys[role][0],'secretKey':keys[role][1]}], 'actions':actions}
for role,actions in [
('admin',['Admin','Read','Write','List','Tagging']),
('api',['Read:messenger/originals/*','Read:messenger/variants/*','Write:messenger/staging/*']),
('worker',['Read:messenger/*','Write:messenger/originals/*','Write:messenger/variants/*','Write:messenger/staging/*','List:messenger'])]
]},indent=2)+'\n'}
(root/'secrets').mkdir(exist_ok=True)
for name,content in files.items():
with (root/name).open('x',encoding='utf-8',newline='\n') as file: file.write(content)
try: (root/name).chmod(0o600)
except OSError: pass
print('Created separate local API, worker and admin configuration; values not displayed')
+37
View File
@@ -0,0 +1,37 @@
"""Generate the committed, provisioned dashboard from explicit PromQL."""
import json
from pathlib import Path
panels=[]
def panel(title,queries,unit='short'):
i=len(panels)
panels.append({'id':i+1,'type':'timeseries','title':title,'datasource':{'type':'prometheus','uid':'prometheus'},
'gridPos':{'x':(i%2)*12,'y':(i//2)*8,'w':12,'h':8},
'targets':[{'refId':chr(65+j),'expr':expr,'legendFormat':label} for j,(label,expr) in enumerate(queries)],
'fieldConfig':{'defaults':{'unit':unit,'min':0},'overrides':[]},'options':{'legend':{'displayMode':'list','placement':'bottom'}}})
panel('API requests / second',[('{{method}} {{route}}','sum by(method,route)(rate(http_server_requests_total[1m]))')],'reqps')
panel('API 5xx / all business requests',[('5xx fraction','(sum(rate(http_server_requests_total{status_class="5xx"}[1m])) or vector(0)) / clamp_min(sum(rate(http_server_requests_total[1m])),0.001)')],'percentunit')
panel('API latency: aggregate buckets across replicas',[(f'p{p}',f'histogram_quantile({p/100},sum by(le)(rate(http_server_duration_seconds_bucket[1m])))') for p in (50,95,99)],'s')
panel('Jobs / second by outcome',[('{{outcome}}','sum by(outcome)(rate(jobs_processed_total[1m]))')],'ops')
panel('Worker processing latency',[(f'p{p}',f'histogram_quantile({p/100},sum by(le)(rate(job_processing_duration_seconds_bucket[1m])))') for p in (50,95,99)],'s')
panel('Acceptance to ready latency',[(f'p{p}',f'histogram_quantile({p/100},sum by(le)(rate(attachment_time_to_ready_seconds_bucket[5m])))') for p in (50,95,99)],'s')
panel('Unfinished durable jobs',[('queue depth','sum(queue_depth)')])
panel('Oldest unfinished job age',[('oldest','max(queue_oldest_age_seconds)')],'s')
panel('DB pool',[('used {{process_instance}}','db_pool_used'),('waiting {{process_instance}}','db_pool_waiting')])
panel('Worker saturation',[('busy / capacity','sum(worker_busy) / clamp_min(sum(worker_capacity),1)')],'percentunit')
panel('Current process RSS',[('{{service}} {{process_instance}}','process_rss_bytes')],'bytes')
panel('Process CPU seconds / wall second',[('{{service}} {{process_instance}}','clamp_min(deriv(process_cpu_time_seconds[1m]),0)')],'percentunit')
panel('API availability burn rate; budget 0.5%',[(f'{w}s',f'(sum(rate(http_server_requests_total{{status_class="5xx"}}[{w}s])) or vector(0)) / clamp_min(sum(rate(http_server_requests_total[{w}s])),0.001) / 0.005') for w in (20,60)])
panel('Ready <=30s burn rate; budget 1%',[(f'{w}s eligible cohort',f'sum(attachment_slo_bad{{window="{w}"}}) / clamp_min(sum(attachment_slo_eligible{{window="{w}"}}),1) / 0.01') for w in (60,300)])
panel('Collector exporter queue / capacity',[('{{exporter}} size','otelcol_exporter_queue_size'),('{{exporter}} capacity','otelcol_exporter_queue_capacity')])
panel('Collector failed exports',[('{{exporter}} spans','rate(otelcol_exporter_send_failed_spans_total[1m])'),('{{exporter}} logs','rate(otelcol_exporter_send_failed_log_records_total[1m])')],'ops')
panels.append({'id':99,'type':'logs','title':'Structured application logs; TraceID links to Tempo','datasource':{'type':'loki','uid':'loki'},
'gridPos':{'x':0,'y':64,'w':24,'h':10},'targets':[{'refId':'A','expr':'{service_name=~"messenger-(api|worker|dispatcher)"}'}],
'options':{'showTime':True,'showLabels':False,'wrapLogMessage':True,'sortOrder':'Descending'}})
doc={'uid':'mtusi-messenger','title':'MTUSI Messenger - signals and SLO','schemaVersion':39,'version':1,
'editable':False,'timezone':'browser','time':{'from':'now-15m','to':'now'},'refresh':'15s','tags':['mtusi','lab6'],
'panels':panels,'annotations':{'list':[]},'templating':{'list':[]}}
path=Path(__file__).resolve().parents[1]/'infra/grafana/dashboards/messenger.json'
path.parent.mkdir(parents=True,exist_ok=True)
path.write_text(json.dumps(doc,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
+160
View File
@@ -0,0 +1,160 @@
"""Bounded, repeatable SLO and telemetry-backend fault experiments (local stack only)."""
import concurrent.futures
import json
import math
import subprocess
import threading
import time
import uuid
import httpx
from stack import ROOT,docker,ready
from verify_telemetry import bootstrap,upload,wait_ready,query,sql,trace_spans
OUT=ROOT/'evidence/incidents'; OUT.mkdir(parents=True,exist_ok=True)
stop=threading.Event(); requests=[]; lock=threading.Lock(); results={'phases':[]}
def traffic(headers,chat):
with httpx.Client(base_url='http://127.0.0.1:8080',timeout=10) as client:
while not stop.is_set():
trace=uuid.uuid4().hex; start=time.time()
try:
r=client.post(f'/api/v1/chats/{chat}/messages',headers={**headers,'Idempotency-Key':uuid.uuid4().hex,
'traceparent':f'00-{trace}-{uuid.uuid4().hex[:16]}-01'},json={'text':'synthetic SLO probe'})
status=r.status_code
except httpx.HTTPError: status=0
with lock: requests.append({'at':start,'seconds':time.time()-start,'status':status,'trace_id':trace})
stop.wait(.2)
def alerts():
r=httpx.get('http://127.0.0.1:9090/api/v1/alerts',timeout=10); r.raise_for_status()
return {a['labels']['alertname']:a['state'] for a in r.json()['data']['alerts']}
def phase(name,duration):
print('Phase '+name,flush=True)
start=time.time(); phase={'name':name,'start':start,'samples':[]}
results['phases'].append(phase)
until=time.monotonic()+duration
while True:
sample={'at':time.time(),'alerts':alerts()}
for label,expr in {
'queue_depth':'sum(queue_depth)','queue_age':'max(queue_oldest_age_seconds)',
'api_error_ratio':'(sum(rate(http_server_requests_total{status_class="5xx"}[20s])) or vector(0)) / clamp_min(sum(rate(http_server_requests_total[20s])),0.001)',
'api_p95':'histogram_quantile(0.95,sum by(le)(rate(http_server_duration_seconds_bucket[1m])))',
'db_pool_used':'sum(db_pool_used)','db_pool_waiting':'sum(db_pool_waiting)',
'worker_busy':'sum(worker_busy)','collector_queue':'otelcol_exporter_queue_size',
'collector_capacity':'otelcol_exporter_queue_capacity',
'collector_failed_spans':'otelcol_exporter_send_failed_spans_total',
'collector_failed_logs':'otelcol_exporter_send_failed_log_records_total',
'collector_enqueue_failed_spans':'otelcol_exporter_enqueue_failed_spans_total',
'collector_enqueue_failed_logs':'otelcol_exporter_enqueue_failed_log_records_total',
'collector_refused_spans':'otelcol_receiver_refused_spans_total',
'collector_refused_logs':'otelcol_receiver_refused_log_records_total',
'collector_received_spans':'otelcol_receiver_accepted_spans_total',
'collector_sent_spans':'otelcol_exporter_sent_spans_total',
'collector_received_logs':'otelcol_receiver_accepted_log_records_total',
'collector_sent_logs':'otelcol_exporter_sent_log_records_total',
'collector_rss':'otelcol_process_memory_rss_bytes','api_worker_rss':'process_rss_bytes'}.items():
sample[label]=query(expr)
phase['samples'].append(sample)
if time.monotonic()>=until: break
time.sleep(min(5,max(0,until-time.monotonic())))
phase['end']=time.time()
with lock: rows=[r for r in requests if start<=r['at']<phase['end']]
latencies=sorted(r['seconds'] for r in rows if r['status']==201)
phase['requests']={'total':len(rows),'success':len(latencies),'errors':len(rows)-len(latencies),
'successful_rps':len(latencies)/(phase['end']-start),
'successful_latency_ms':{f'p{p}':1000*latencies[max(0,math.ceil(p/100*len(latencies))-1)] if latencies else None for p in (50,95,99)}}
(OUT/'timeline.json').write_text(json.dumps(results,indent=2)+'\n',encoding='utf-8')
return phase
def fired(phase,name): return [s['at']-phase['start'] for s in phase['samples'] if s['alerts'].get(name)=='firing']
def db_lock(seconds):
proc=subprocess.Popen(['docker','compose','exec','-T','db','psql','-U','messenger','-d','messenger','-v','ON_ERROR_STOP=1','-c',
f'BEGIN; LOCK TABLE sessions IN ACCESS EXCLUSIVE MODE; SELECT pg_sleep({int(seconds)}); COMMIT;'],cwd=ROOT,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
deadline=time.monotonic()+10
while time.monotonic()<deadline:
if sql("SELECT count(*) FROM pg_locks l JOIN pg_class c ON c.oid=l.relation WHERE c.relname='sessions' AND l.mode='AccessExclusiveLock' AND l.granted")=='1': return proc
time.sleep(.2)
raise AssertionError('DB fault did not acquire lock')
def main():
with httpx.Client(base_url='http://127.0.0.1:8080',timeout=35) as c:
ready(c); headers,chat,_=bootstrap(c)
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool:
futures=[pool.submit(traffic,headers,chat) for _ in range(4)]
try:
quiet=phase('preflight_settle',120)
assert not any(s=='firing' for s in quiet['samples'][-1]['alerts'].values()),'Prior incident has not cleared'
phase('baseline',45)
proc=db_lock(5)
short=phase('db_burst_5s',45); proc.wait(timeout=10)
assert not fired(short,'APIAvailabilityBurn'),'Short spike generated false alert'
phase('settle',35)
proc=db_lock(70)
sustained=phase('db_sustained_70s',75); proc.wait(timeout=10)
assert fired(sustained,'APIAvailabilityBurn'),'Sustained DB failure not detected'
recovered=phase('db_recovery',70)
assert recovered['samples'][-1]['alerts'].get('APIAvailabilityBurn')!='firing'
errors=[r for r in requests if sustained['start']<=r['at']<sustained['end'] and r['status']==503]
assert errors,'No injected DB error was observed'
trace_id=errors[len(errors)//2]['trace_id']
response=httpx.get('http://127.0.0.1:3200/api/traces/'+trace_id,headers={'Accept':'application/json'},timeout=15)
response.raise_for_status(); trace=response.json()
db_spans=[s for s in trace_spans(trace) if s['name']=='db.session.authenticate']
assert db_spans and any(s.get('status',{}).get('code') in (2,'STATUS_CODE_ERROR') for s in db_spans)
(OUT/'db-error-trace.json').write_text(json.dumps(trace,indent=2)+'\n',encoding='utf-8')
docker('compose','stop','worker')
try:
aids=[upload(c,headers,chat).json()['id'] for _ in range(8)]
queued=phase('worker_stopped',85)
assert fired(queued,'QueueLag') and fired(queued,'AttachmentReadyBurn')
finally: docker('compose','start','worker')
started=time.time()
for aid in aids: wait_ready(c,headers,aid)
results['queue_seconds_to_drain']=time.time()-started
queue_recovered=phase('worker_recovery',110)
assert not {'QueueLag','AttachmentReadyBurn'} & {n for n,s in queue_recovered['samples'][-1]['alerts'].items() if s=='firing'}
docker('compose','stop','-t','3','loki','tempo')
try:
backend=phase('telemetry_backends_stopped',80)
assert backend['requests']['success']>0 and backend['requests']['errors']==0
finally: docker('compose','start','loki','tempo')
phase('telemetry_recovery',45)
lines=[line for line in docker('compose','logs','--no-color','otel-collector').splitlines()
if 'Exporting failed. Dropping data.' in line or 'sending_queue is full' in line]
(OUT/'collector-drops.txt').write_text('\n'.join(lines)+'\n',encoding='utf-8')
dropped={}
for line in lines:
if '"dropped_items"' in line:
entry=json.loads(line[line.index('{'):]); signal=entry['otelcol.signal']
dropped[signal]=dropped.get(signal,0)+entry['dropped_items']
results['collector_explicit_retry_drops']=dropped
for sample in backend['samples']:
caps={row['metric'].get('exporter'):float(row['value'][1]) for row in sample['collector_capacity']}
for row in sample['collector_queue']:
assert float(row['value'][1])<=caps[row['metric'].get('exporter')]
results['summary']={'short_burst_false_firings':len(fired(short,'APIAvailabilityBurn')),
'api_detection_seconds':fired(sustained,'APIAvailabilityBurn')[0],
'queue_lag_detection_seconds':fired(queued,'QueueLag')[0],
'ready_slo_detection_seconds':fired(queued,'AttachmentReadyBurn')[0],
'db_error_trace_id':trace_id,'backend_outage_business_requests':backend['requests'],'passed':True}
results['passed']=True
finally:
stop.set()
for f in futures: f.result(timeout=15)
(OUT/'timeline.json').write_text(json.dumps(results,indent=2)+'\n',encoding='utf-8')
(OUT/'requests.json').write_text(json.dumps(requests,indent=2)+'\n',encoding='utf-8')
# After traffic stops, allow SDK/batch/scrape to flush. There are no health
# spans. Compare record counters after exporter queues have drained.
time.sleep(15)
def total(expr): return sum(float(r['value'][1]) for r in query(expr))
assert total('otelcol_exporter_queue_size')==0
results['quiescent_collector']={}
for signal in ('spans','log_records'):
accepted=total('otelcol_receiver_accepted_'+signal+'_total')
sent=total('otelcol_exporter_sent_'+signal+'_total')
results['quiescent_collector'][signal]={'accepted':accepted,'sent':sent,'not_exported':accepted-sent}
(OUT/'timeline.json').write_text(json.dumps(results,indent=2)+'\n',encoding='utf-8')
print(json.dumps(results['summary'],indent=2),flush=True)
if __name__=='__main__': main()
+43
View File
@@ -0,0 +1,43 @@
"""Publication artifacts from saved observations only, never synthetic result values."""
import json
import math
from pathlib import Path
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
root=Path(__file__).resolve().parents[1]
data=json.loads((root/'evidence/incidents/timeline.json').read_text(encoding='utf-8'))
phases=data['phases']; origin=phases[0]['start']
fig,axes=plt.subplots(4,1,figsize=(11,10),sharex=True,layout='constrained')
seen=set()
def metric(sample,key,aggregate=max):
values=[float(row['value'][1]) for row in sample.get(key,[]) if math.isfinite(float(row['value'][1]))]
return aggregate(values) if values else float('nan')
for phase in phases:
samples=phase['samples'];x=[(s['at']-origin)/60 for s in samples]
axes[0].plot(x,[metric(s,'api_error_ratio')*100 for s in samples],color='#C13E44')
axes[1].plot(x,[metric(s,'queue_age') for s in samples],color='#9163CB')
axes[2].plot(x,[metric(s,'collector_queue') for s in samples],color='#287AB1')
axes[3].plot(x,[metric(s,'collector_rss')/2**20 for s in samples],color='#15946A')
for ax in axes:
if phase['name'] in ('db_burst_5s','db_sustained_70s','worker_stopped','telemetry_backends_stopped'):
ax.axvspan((phase['start']-origin)/60,(phase['end']-origin)/60,color='#E1E6EC',alpha=.7,zorder=-1)
for name,idx in [('APIAvailabilityBurn',0),('QueueLag',1),('AttachmentReadyBurn',1)]:
xs=[(s['at']-origin)/60 for s in samples if s['alerts'].get(name)=='firing']
if xs:
axes[idx].scatter(xs,[104 if idx==0 else 115 if name=='QueueLag' else 125]*len(xs),s=12,marker='|',
color={'APIAvailabilityBurn':'#C13E44','QueueLag':'#287AB1','AttachmentReadyBurn':'#D38529'}[name],label=name if name not in seen else None)
seen.add(name)
axes[0].set_ylabel('API 5xx (%)');axes[1].set_ylabel('Oldest job (s)')
axes[2].set_ylabel('Collector queue\nmax batches');axes[3].set_ylabel('Collector RSS (MiB)')
axes[2].axhline(32,color='#C13E44',linestyle='--',label='Queue capacity32')
axes[3].axhline(256,color='#C13E44',linestyle='--',label='Container limit256MiB')
axes[3].set_xlabel('Minutes since experiment start')
for ax in axes:
ax.grid(alpha=.2);ax.set_ylim(bottom=0)
handles,labels=ax.get_legend_handles_labels()
if handles: ax.legend(loc='upper left',fontsize=8)
fig.suptitle('Measured SLO incidents and bounded telemetry buffers\nShading: fault observation windows; markers: firing alerts',fontsize=13)
fig.savefig(root/'evidence/incidents/timeline.png',dpi=160)
fig.savefig(root/'evidence/incidents/timeline.svg')
+13
View File
@@ -0,0 +1,13 @@
"""Restart every running replica and dependency, preserving durable volumes."""
import json
from stack import ROOT, docker, state
before = state()
docker('compose', 'restart', 'api', 'db', 'cache', 'lb', 's3', 'reconciler', 'broker', 'worker', 'dispatcher')
after = state()
assert set(before) == set(after)
assert all(before[c]['state']['StartedAt'] != after[c]['state']['StartedAt'] for c in before)
(ROOT / 'evidence').mkdir(exist_ok=True)
(ROOT / 'evidence/restart-processes.json').write_text(
json.dumps({'before': before, 'after': after, 'volumes_removed': False}, indent=2) + '\n',
encoding='utf-8')
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
python3 scripts/restart.py
+35
View File
@@ -0,0 +1,35 @@
"""Shared bounded Docker helpers for reproducible, scoped failure experiments."""
import json
from pathlib import Path
import subprocess
import time
ROOT=Path(__file__).resolve().parents[1]
def docker(*args):
return subprocess.check_output(['docker',*args],cwd=ROOT,text=True,encoding='utf-8',stderr=subprocess.PIPE).strip()
def replicas(): return docker('compose','ps','-q','api').splitlines()
def ready_replicas(count=2,timeout=60):
deadline=time.monotonic()+timeout
while time.monotonic()<deadline:
ids=replicas()
if len(ids)==count:
states=[json.loads(docker('inspect','--format','{{json .State}}',cid)) for cid in ids]
if all(s['Running'] and s.get('Health',{}).get('Status')=='healthy' for s in states): return
time.sleep(.5)
raise AssertionError('Actual replica health did not recover within timeout')
def instance(cid):
return docker('exec',cid,'python','-c',"import urllib.request; print(urllib.request.urlopen('http://127.0.0.1:8080/health/live',timeout=2).headers['X-Instance-Id'])")
def state():
result={}
for service in ('api','db','cache','lb','s3','reconciler','broker','worker','dispatcher'):
for cid in docker('compose','ps','-q',service).splitlines():
result[cid]={'service':service,'state':json.loads(docker('inspect','--format','{{json .State}}',cid))}
return result
def ready(client,timeout=60):
deadline=time.monotonic()+timeout
while time.monotonic()<deadline:
try:
if client.get('/health/ready').status_code==200: return
except Exception: pass
time.sleep(.2)
raise AssertionError('Readiness timeout')
+12
View File
@@ -0,0 +1,12 @@
"""Stop the real process selected by X-Instance-Id; do not stop any dependency."""
import json
import os
from stack import ROOT, docker, instance, replicas
target=os.environ['TARGET_INSTANCE_ID']
matches=[cid for cid in replicas() if instance(cid)==target]
assert len(matches)==1,'Target does not uniquely identify a running API'
before=replicas()
docker('stop','--time','5',matches[0])
assert docker('inspect','--format','{{.State.Running}}',matches[0])=='false'
(ROOT/'evidence').mkdir(exist_ok=True)
(ROOT/'evidence/stop-one.json').write_text(json.dumps({'target_instance':target,'stopped_container':matches[0],'before_containers':before,'after_running_containers':replicas()},indent=2)+'\n',encoding='utf-8')
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
exec python3 scripts/stop-one.py
+189
View File
@@ -0,0 +1,189 @@
"""Real durable queue, crash, retry, duplicate and version-reordering experiments."""
import hashlib
import atexit
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import time
import uuid
import httpx
from stack import ROOT, docker, ready, ready_replicas, replicas, instance
OUT=ROOT/'evidence'; OUT.mkdir(exist_ok=True)
result={}
atexit.register(lambda: (OUT/('integration.json' if result.get('passed') else 'interrupted-integration.json')).write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n',encoding='utf-8'))
def sql(query):
return docker('compose','exec','-T','db','psql','-U','messenger','-d','messenger','-Atc',query)
def inside(code):
return subprocess.check_output(['docker','compose','exec','-T','dispatcher','python','-'],
input=code,cwd=ROOT,text=True,encoding='utf-8',stderr=subprocess.PIPE).strip()
def job(aid):
return json.loads(sql("SELECT row_to_json(j) FROM jobs j WHERE attachment_id='"+aid+"' ORDER BY pipeline_version DESC LIMIT 1"))
def objects(aid):
return json.loads(inside("from src.storage import Storage\nimport json\ns=Storage(); print(json.dumps(sorted(o['Key'] for prefix in ('originals/','variants/') for p in s.client.get_paginator('list_objects_v2').paginate(Bucket=s.bucket,Prefix=prefix+"+repr(aid)+") for o in p.get('Contents',[]))))"))
def emit_job(identifier):
inside("from src.jobs import database,payload\nfrom src.broker import connect,publish\nwith database() as db, connect() as c:\n j=db.execute('SELECT * FROM jobs WHERE id=%s',("+repr(identifier)+",)).fetchone(); print(publish(c,payload(j)))")
def operator(*args):
return json.loads(docker('compose','exec','-T','dispatcher','python','-m','src.operator',*args))
def restore(c):
docker('compose','up','-d','--no-deps','--scale','api=2','api')
ready_replicas(); ready(c)
def public(mode):
name='restart' if mode=='persistence' else 'stop-one'
with tempfile.TemporaryDirectory() as tmp:
if os.name=='nt':
hook=Path(tmp)/(name+'.cmd')
hook.write_text('@echo off\n"'+sys.executable+'" "'+str(ROOT/('scripts/'+name+'.py'))+'"\n',encoding='utf-8')
else: hook=ROOT/('scripts/'+name+'.sh')
proc=subprocess.run([sys.executable,'-X','utf8','tests/resilience.py','--mode',mode,'--action-script',str(hook)],cwd=ROOT,capture_output=True,text=True,encoding='utf-8')
assert proc.returncode==0,proc.stdout+proc.stderr
return proc.stdout.strip()
with httpx.Client(base_url='http://127.0.0.1:8080',timeout=35) as c:
ready(c)
result['public_smoke']=subprocess.check_output([sys.executable,'-X','utf8','tests/smoke.py'],cwd=ROOT,text=True).strip()
name='jobs_'+uuid.uuid4().hex[:20]; password='synthetic-jobs-password'
r=c.post('/api/v1/users',json={'username':name,'display_name':'Queue research','password':password}); assert r.status_code==201,r.text
uid=r.json()['id']
r=c.post('/api/v1/auth/sessions',auth=(name,password)); assert r.status_code==201
h={'Authorization':'Bearer '+r.json()['token']}
r=c.post('/api/v1/chats',headers=h,json={'title':'Jobs','member_ids':[uid]}); assert r.status_code==201
chat=r.json()['id']; data=(ROOT/'tests/fixtures/sample.png').read_bytes()
def upload():
r=c.post(f'/api/v1/chats/{chat}/attachments',params={'filename':'fixture.png'},headers={**h,'Content-Type':'image/png'},content=data)
assert r.status_code==202,r.text
assert r.json()['status']=='queued' and r.json()['variants']==[]
return r
def wait(aid,status='ready',timeout=140):
deadline=time.monotonic()+timeout
while time.monotonic()<deadline:
r=c.get('/api/v1/attachments/'+aid,headers=h)
if r.status_code==200:
row=r.json()
if row['status']==status: return row
if row['status']=='failed' and status!='failed': raise AssertionError(row)
time.sleep(.3)
raise AssertionError('Job did not reach '+status+': '+str(job(aid)))
def verify_bytes(aid):
row=wait(aid)
assert {v['name'] for v in row['variants']}=={'thumbnail','crop','optimized'}
assert c.get('/api/v1/attachments/'+aid+'/content',headers=h).content==data
for variant in row['variants']:
r=c.get('/api/v1/attachments/'+aid+'/content',headers=h,params={'variant':variant['name']})
assert r.status_code==200 and hashlib.sha256(r.content).hexdigest()==variant['sha256']
assert len(r.content)==variant['size_bytes']
dims={v['name']:(v['width'],v['height'],v['content_type']) for v in row['variants']}
assert dims['thumbnail']==(256,160,'image/jpeg')
assert dims['crop']==(128,128,'image/jpeg')
assert dims['optimized']==(320,200,'image/webp')
return row
# Hold publication, durably accept, then kill the accepting API before publish.
docker('compose','stop','worker','dispatcher')
try:
r=upload(); aid=r.json()['id']; serving=r.headers['X-Instance-Id']; j=job(aid)
assert sql("SELECT published_at IS NULL FROM outbox WHERE job_id='"+j['id']+"'")=='t'
assert c.get('/api/v1/attachments/'+aid+'/content',headers=h).status_code==409
message=c.post(f'/api/v1/chats/{chat}/messages',headers={**h,'Idempotency-Key':uuid.uuid4().hex},json={'text':'','attachment_ids':[aid]})
assert message.status_code==201,message.text
target=next(cid for cid in replicas() if instance(cid)==serving)
docker('kill',target)
docker('compose','restart','broker')
restore(c)
assert c.get('/api/v1/attachments/'+aid,headers=h).json()['status']=='queued'
finally:
docker('compose','start','dispatcher','worker')
accepted=verify_bytes(aid)
result['commit_before_publish']={'attachment_id':aid,'job_id':j['id'],'killed_api':target,
'broker_restarted':True,'queued_message_accepted':True,'original_and_variants_verified':True}
result['public_persistence']=public('persistence'); restore(c)
result['public_failover']=public('failover'); restore(c)
# Terminal duplicate is a no-op. Do not create a new logical job/effect set.
before=verify_bytes(aid); keys=objects(aid)
for _ in range(3): emit_job(j['id'])
time.sleep(2)
assert verify_bytes(aid)==before and objects(aid)==keys and len(keys)==4
result['terminal_duplicates']={'deliveries':3,'effect_objects':4,'metadata_unchanged':True}
result['crashes']=[]
for point in ('before_effect','after_effect','after_commit'):
docker('compose','stop','worker')
try:
aid=upload().json()['id']; j=job(aid)
sql("INSERT INTO job_faults(job_id,point,remaining) VALUES ('"+j['id']+"','"+point+"',1)")
before_restart=int(docker('inspect','--format','{{.RestartCount}}',docker('compose','ps','-aq','worker')))
finally: docker('compose','start','worker')
started=time.monotonic(); row=verify_bytes(aid)
# Force one extra delivery after ready to exercise the done guard.
emit_job(j['id']); time.sleep(1)
assert verify_bytes(aid)==row and len(objects(aid))==4
current=job(aid)
crash_lines=[line[line.index('{'):] for line in docker('compose','logs','--no-color','worker').splitlines()
if '"event": "injected_crash"' in line and j['id'] in line]
assert len(crash_lines)==1,crash_lines
audit_rows=json.loads(sql("SELECT coalesce(json_agg(x),'[]') FROM (SELECT event,details FROM job_audit WHERE job_id='"+j['id']+"' ORDER BY id) x"))
result['crashes'].append({'point':point,'seconds_to_ready':round(time.monotonic()-started,3),
'attempts':current['attempts'],'effect_objects':4,'audit':audit_rows,'crash_event':json.loads(crash_lines[0]),
'restart_count_before':before_restart,'restart_count_after':int(docker('inspect','--format','{{.RestartCount}}',docker('compose','ps','-q','worker')))})
result['retries']=[]
for point,count,expected in [('transient',2,'ready'),('permanent',1,'failed'),('transient',5,'failed')]:
docker('compose','stop','worker')
try:
aid=upload().json()['id']; j=job(aid)
sql(f"INSERT INTO job_faults(job_id,point,remaining) VALUES ('{j['id']}','{point}',{count})")
finally: docker('compose','start','worker')
row=wait(aid,expected)
failed=job(aid)
assert failed['attempts']==(3 if expected=='ready' else count),failed
if expected=='failed':
assert c.get('/api/v1/attachments/'+aid+'/content',headers=h).status_code==409
r=c.post(f'/api/v1/chats/{chat}/messages',headers={**h,'Idempotency-Key':uuid.uuid4().hex},json={'text':'','attachment_ids':[aid]})
assert r.status_code==409
operator('replay',j['id']); verify_bytes(aid)
result['retries'].append({'fault':point,'injected':count,'terminal_status':row['status'],
'error_code':row['error_code'],'attempts':failed['attempts'],'replay_ready':expected=='failed'})
# Explicit reorder: enqueue version 2 before version 1, then deliver stale v1 again.
docker('compose','stop','worker','dispatcher')
try:
aid=upload().json()['id']; old=job(aid)
# Operator runs in a one-shot container while dispatcher is stopped.
newer=json.loads(docker('compose','run','--rm','--no-deps','dispatcher','python','-m','src.operator','upgrade',aid,'2'))
order_code="from src.jobs import database,payload\nfrom src.broker import connect,publish\nwith database() as db, connect() as client:\n for identifier in "+repr([newer['job_id'],old['id']])+":\n row=db.execute('SELECT * FROM jobs WHERE id=%s',(identifier,)).fetchone(); publish(client,payload(row))"
docker('compose','run','--rm','--no-deps','dispatcher','python','-c',order_code)
finally: docker('compose','start','dispatcher','worker')
row=verify_bytes(aid); keys=objects(aid)
assert all('/v2' in key for key in keys) and len(keys)==4
emit_job(old['id']); time.sleep(2)
assert verify_bytes(aid)==row and objects(aid)==keys
result['version_reorder']={'old_job_id':old['id'],'new_job_id':newer['job_id'],
'final_pipeline_version':job(aid)['pipeline_version'],'keys':keys,'stale_delivery_did_not_change_result':True}
result['passed']=True
(OUT/'integration.json').write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
print(json.dumps(result,ensure_ascii=False,indent=2))
+126
View File
@@ -0,0 +1,126 @@
"""Real OTLP metrics/logs and a W3C upload -> retry -> ready trace."""
import json
import atexit
from pathlib import Path
import subprocess
import time
import uuid
import httpx
from stack import ROOT,docker,ready
OUT=ROOT/'evidence'; OUT.mkdir(exist_ok=True)
PROM=httpx.Client(base_url='http://127.0.0.1:9090',timeout=10)
atexit.register(PROM.close)
def sql(query): return docker('compose','exec','-T','db','psql','-U','messenger','-d','messenger','-Atc',query)
def query(expression):
r=PROM.get('/api/v1/query',params={'query':expression})
r.raise_for_status(); data=r.json(); assert data['status']=='success',data
return data['data']['result']
def bootstrap(c):
username='otel_'+uuid.uuid4().hex[:20]; password='synthetic-otel-password'
r=c.post('/api/v1/users',json={'username':username,'display_name':'Telemetry fixture','password':password}); assert r.status_code==201,r.text
uid=r.json()['id']; r=c.post('/api/v1/auth/sessions',auth=(username,password)); assert r.status_code==201
token=r.json()['token']; headers={'Authorization':'Bearer '+token}
r=c.post('/api/v1/chats',headers=headers,json={'title':'Telemetry fixture','member_ids':[uid]}); assert r.status_code==201
return headers,r.json()['id'],token
def upload(c,headers,chat,extra=None):
r=c.post(f'/api/v1/chats/{chat}/attachments',params={'filename':'fixture.png'},headers={**headers,'Content-Type':'image/png',**(extra or {})},content=(ROOT/'tests/fixtures/sample.png').read_bytes())
assert r.status_code==202,r.text
return r
def wait_ready(c,headers,aid,timeout=140):
until=time.monotonic()+timeout
while time.monotonic()<until:
r=c.get('/api/v1/attachments/'+aid,headers=headers)
if r.status_code==200 and r.json()['status']=='ready': return r.json()
if r.status_code==200 and r.json()['status']=='failed': raise AssertionError(r.text)
time.sleep(.5)
raise AssertionError('Attachment not ready')
def trace_spans(data):
return [span for batch in data.get('batches',data.get('resourceSpans',[]))
for scope in batch.get('scopeSpans',batch.get('instrumentationLibrarySpans',[])) for span in scope.get('spans',[])]
def main():
result={}
with httpx.Client(base_url='http://127.0.0.1:8080',timeout=35) as c:
ready(c); headers,chat,token=bootstrap(c)
trace_id=uuid.uuid4().hex; parent=uuid.uuid4().hex[:16]
docker('compose','stop','worker')
try:
r=upload(c,headers,chat,{'traceparent':f'00-{trace_id}-{parent}-01','tracestate':'research=mtusi'})
aid=r.json()['id']; request_id=r.headers['X-Request-Id']
job=json.loads(sql("SELECT row_to_json(j) FROM jobs j WHERE attachment_id='"+aid+"'"))
assert job['traceparent'].split('-')[1]==trace_id and job['tracestate']=='research=mtusi'
sql("INSERT INTO job_faults(job_id,point,remaining) VALUES ('"+job['id']+"','transient',1)")
finally: docker('compose','start','worker')
row=wait_ready(c,headers,aid)
assert len(row['variants'])==3
assert sql("SELECT staging_key IS NULL FROM attachments WHERE id='"+aid+"'")=='t'
deadline=time.monotonic()+90
while time.monotonic()<deadline:
response=httpx.get('http://127.0.0.1:3200/api/traces/'+trace_id,headers={'Accept':'application/json'},timeout=15)
if response.status_code==200:
trace_data=response.json(); spans=trace_spans(trace_data)
if sum(s['name']=='attachment.consume' for s in spans)>=2 and any(s['name']=='db.attachment.commit' for s in spans): break
time.sleep(2)
else: raise AssertionError('Upload/retry/ready trace not found in Tempo')
names=[s['name'] for s in spans]
assert names.count('POST /api/v1/chats/{chat_id}/attachments')==1,'Duplicate framework server spans'
for name in ('POST /api/v1/chats/{chat_id}/attachments','attachment.durable_accept','attachment.publish','attachment.consume','image.render','s3.put','db.attachment.commit'):
assert name in names,(name,names)
by_id={s['spanId']:s for s in spans}
consumers=[s for s in spans if s['name']=='attachment.consume']
assert all(by_id[s['parentSpanId']]['name']=='attachment.publish' for s in consumers)
assert all(s.get('traceState')=='research=mtusi' for s in consumers)
result['trace']={'trace_id':trace_id,'request_id':request_id,'attachment_id':aid,'job_id':job['id'],
'spans':len(spans),'consumer_attempts':len(consumers),'names':names,'tracestate_preserved':True,'staging_removed':True}
deadline=time.monotonic()+60
while time.monotonic()<deadline:
response=httpx.get('http://127.0.0.1:3100/loki/api/v1/query_range',params={
'query':'{service_name=~"messenger-(api|worker|dispatcher)"} |= "'+trace_id+'"',
'start':str(int((time.time()-600)*1e9)),'end':str(int(time.time()*1e9)),'limit':'1000'},timeout=15)
response.raise_for_status(); logs=response.json()
lines=[json.loads(line) for stream in logs['data']['result'] for _,line in stream['values']]
outcomes={line.get('outcome') for line in lines if line.get('event')=='job_finished'}
if {'retry','ready'}<=outcomes and any(line.get('request_id')==request_id for line in lines): break
time.sleep(2)
else: raise AssertionError('Correlated request/retry/ready logs not found in Loki')
raw=json.dumps([trace_data,logs])
assert token not in raw and 'synthetic-otel-password' not in raw
result['logs']={'count':len(lines),'outcomes':sorted(x for x in outcomes if x),'request_id_correlated':True,'secret_values_absent':True}
(OUT/'upload-trace.json').write_text(json.dumps(trace_data,indent=2)+'\n',encoding='utf-8')
(OUT/'upload-logs.json').write_text(json.dumps(logs,indent=2)+'\n',encoding='utf-8')
required=['http_server_requests_total','http_server_duration_seconds_bucket','jobs_processed_total',
'job_processing_duration_seconds_bucket','attachment_time_to_ready_seconds_bucket',
'queue_depth','queue_oldest_age_seconds','db_pool_used','db_pool_waiting','worker_busy','worker_capacity',
'process_rss_bytes','process_cpu_time_seconds','attachment_slo_eligible','attachment_slo_bad']
deadline=time.monotonic()+30
while True:
values={metric:query(metric) for metric in required}
if all(values.values()): break
assert time.monotonic()<deadline,[metric for metric,rows in values.items() if not rows]
time.sleep(2)
for metric,rows in values.items():
for sample in rows:
assert not {'user_id','chat_id','message_id','attachment_id','request_id','filename','url'} & sample['metric'].keys()
if 'route' in sample['metric']: assert aid not in sample['metric']['route'] and chat not in sample['metric']['route']
(OUT/'metric-samples.json').write_text(json.dumps(values,indent=2)+'\n',encoding='utf-8')
result['metrics']={'present':required,'forbidden_labels_absent':True}
with httpx.Client(base_url='http://127.0.0.1:3000',auth=('admin',(ROOT/'secrets/grafana-password').read_text().strip()),timeout=20) as grafana:
dashboard=grafana.get('/api/dashboards/uid/mtusi-messenger'); dashboard.raise_for_status()
panels=dashboard.json()['dashboard']['panels']; assert len(panels)==17
sources=grafana.get('/api/datasources'); sources.raise_for_status()
health={}
for source in sources.json():
response=grafana.get('/api/datasources/uid/'+source['uid']+'/health'); response.raise_for_status()
health[source['uid']]=response.json()['status']; assert health[source['uid']]=='OK'
result['grafana']={'provisioned_panels':len(panels),'datasource_health':health}
result['passed']=True
(OUT/'telemetry.json').write_text(json.dumps(result,indent=2)+'\n',encoding='utf-8')
print(json.dumps(result,indent=2))
if __name__=='__main__': main()