Instrument durable messenger with OTel, provision Grafana and prove SLO incident detection

This commit is contained in:
2026-11-21 00:58:18 +03:00
parent 470d9d6f1e
commit bd2c7f7b37
89 changed files with 15839 additions and 25 deletions
+31
View File
@@ -0,0 +1,31 @@
#!/usr/bin/env python3
"""Run committed solution from a real local clone, new credentials and volumes."""
import json,os,socket,subprocess,tempfile,uuid
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
lab=json.loads((ROOT/'lab.json').read_text())['number']
project='verify-lab'+str(lab)+'-'+uuid.uuid4().hex[:10]
with socket.socket() as sock:sock.bind(('127.0.0.1',0));port=sock.getsockname()[1]
with tempfile.TemporaryDirectory(prefix=project+'-') as directory:
clone=Path(directory)/'repo';subprocess.run(['git','clone','--no-hardlinks',str(ROOT),str(clone)],check=True)
env=dict(os.environ,COMPOSE_PROJECT_NAME=project,APP_PORT=str(port),API_REPLICAS='2',SESSION_TTL_SECONDS='3600',GRAFANA_PORT='0',PROMETHEUS_PORT='0',LOKI_PORT='0',TEMPO_PORT='0')
def run(*args):subprocess.run(args,cwd=clone,env=env,check=True)
def snapshots():
ids=subprocess.check_output(['docker','compose','ps','-q'],cwd=clone,env=env,text=True).splitlines()
result={}
for id in ids:
item=json.loads(subprocess.check_output(['docker','inspect',id],text=True))[0]
service=item['Config']['Labels']['com.docker.compose.service']
if service in ['api','postgres','valkey','s3','broker','worker','dispatcher','prometheus','loki','tempo','grafana','collector']:result[item['Name']]={'service':service,'started_at':item['State']['StartedAt'],'image_id':item['Image'],'user':item['Config'].get('User',''),'pid1':item['Path']}
return result
try:
run('make','up');run('make','check');run('make','test','BASE_URL=http://localhost:'+str(port))
before=snapshots();run('make','test-persistence','ACTION_SCRIPT=scripts/restart.sh','BASE_URL=http://localhost:'+str(port));after=snapshots()
for name,item in before.items():assert after[name]['started_at']!=item['started_at'],name+' was not restarted'
for item in after.values():
if item['service']=='api':assert item['user']=='10001:10001' and item['pid1']=='/usr/local/bin/messenger'
(ROOT/'evidence/persistence-processes.json').write_text(json.dumps({'scope':'disposable real clean clone','before':before,'after':after},indent=2)+'\n')
print('PASS: real clean clone, fresh secrets/volumes, smoke, same-session persistence, actual store/API restart, non-root PID1')
finally:
# Only this unique synthetic project, never the working lab volumes.
run('docker','compose','down','-v','--remove-orphans')
+16
View File
@@ -0,0 +1,16 @@
#!/usr/bin/env python3
"""Prove the SLI also observes a 503 generated by HAProxy, outside API SDKs."""
import json,time,urllib.request,urllib.error
from observability import ROOT,BASE,Client,check,dc,scalar,wait_for
c=Client(BASE);a,b,e,chat=c.bootstrap();before=scalar('sum(haproxy_backend_http_responses_total{proxy="replicas",code="5xx"})') or 0
try:
dc('stop','api');time.sleep(2)
req=urllib.request.Request(BASE+'/api/v1/users/me',headers={'Authorization':'Bearer '+a['token']})
try:response=urllib.request.urlopen(req,timeout=4)
except urllib.error.HTTPError as error:response=error
with response:check(response.code==503,'expected LB 503');status=response.code
after,delay=wait_for(lambda: (lambda n:n if n is not None and n>before else None)(scalar('sum(haproxy_backend_http_responses_total{proxy="replicas",code="5xx"})')),15)
result={'client_status':status,'api_processes_stopped':True,'ingress_5xx_before':before,'ingress_5xx_after':after,'observation_seconds':delay,'lb_generated_error_counted':True}
(ROOT/'evidence/ingress-guard.json').write_text(json.dumps(result,indent=2)+'\n');print('PASS: LB-generated 503 included in business ingress SLI')
finally:dc('up','-d','--no-deps','--wait','api')
c.call('GET','/api/v1/users/me',actor=a,schema='User')
+160
View File
@@ -0,0 +1,160 @@
#!/usr/bin/env python3
"""Saved telemetry evidence and bounded incidents, all using synthetic traffic."""
import concurrent.futures,datetime,json,os,subprocess,sys,threading,time,urllib.parse,urllib.request,uuid
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'tests'))
from client import Client,Failure,check
BASE=os.environ.get('BASE_URL','http://localhost:8086');PROM=os.environ.get('PROMETHEUS_URL','http://localhost:9096');TEMPO=os.environ.get('TEMPO_URL','http://localhost:3206');LOKI=os.environ.get('LOKI_URL','http://localhost:3106')
RESULT={'started_at':datetime.datetime.now(datetime.timezone.utc).isoformat(),'slo':{'window':'10m rolling (local exercise)','api':'99% non-5xx of business requests','ready':'95% job versions ready within 5s; cohorts mature at 5s, unfinished count bad'},'incidents':[]}
def get(url):
with urllib.request.urlopen(urllib.request.Request(url,headers={'Accept':'application/json'}),timeout=8) as r:return json.load(r)
def dc(*args):return subprocess.check_output(['docker','compose',*args],cwd=ROOT,text=True,stderr=subprocess.DEVNULL).strip()
def query(expr):return get(PROM+'/api/v1/query?'+urllib.parse.urlencode({'query':expr}))['data']['result']
def scalar(expr):
values=query(expr);return float(values[0]['value'][1]) if values else None
def alerts():return [{'name':x['labels']['alertname'],'state':x['state'],'active_at':x.get('activeAt')} for x in get(PROM+'/api/v1/alerts')['data']['alerts']]
def wait_for(fn,timeout=60):
start=time.monotonic()
while time.monotonic()-start<timeout:
try:
value=fn()
if value:return value,round(time.monotonic()-start,3)
except (OSError,KeyError,ValueError):pass
time.sleep(1)
raise AssertionError('timeout waiting telemetry')
def norm_spans(trace):
spans=[]
for b in trace.get('batches',trace.get('resourceSpans',[])):
attrs={x['key']:x['value'].get('stringValue') for x in b.get('resource',{}).get('attributes',[])}
for scope in b.get('scopeSpans',b.get('instrumentationLibrarySpans',[])):
for s in scope.get('spans',[]):
spans.append({'service':attrs.get('service.name'),'name':s['name'],'id':s.get('spanId'),'parent_id':s.get('parentSpanId'),'kind':s.get('kind'),'status':s.get('status',{}),'duration_ms':(int(s.get('endTimeUnixNano',0))-int(s.get('startTimeUnixNano',0)))/1e6})
return spans
def trace_chain(c,a,chat,retry=False,artifact="trace-chain.json"):
if retry:dc("stop","worker")
traceid=uuid.uuid4().hex;parent=uuid.uuid4().hex[:16];raw=(ROOT/'tests/fixtures/sample.png').read_bytes()
headers={'Content-Type':'image/png'}
if retry:headers.update({'traceparent':'00-'+traceid+'-'+parent+'-01','tracestate':'lab=defense'})
res=c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=trace.png',202,actor=a,raw=raw,headers=headers,schema='Attachment')
if retry:check(res['headers'].get('X-Trace-Id')==traceid,'incoming W3C trace context lost')
else:traceid=res['headers'].get('X-Trace-Id');check(traceid and len(traceid)==32,'missing real root trace')
if retry:
dc('stop','s3');dc('up','-d','--no-deps','worker')
try:
def errored():
value=dc('exec','-T','postgres','psql','-U','messenger','-d','messenger','-Atc',"SELECT count(*) FROM pipeline_audit WHERE job_id=(SELECT job_id FROM pipeline_jobs WHERE attachment_id='"+res['json']['id']+"') AND event='processing_error'")
return int(value)>0
wait_for(errored,20)
finally:dc('up','-d','--no-deps','--wait','s3')
wait_for(lambda:get(BASE+'/health/ready'),20)
att=c.wait_ready(a,res['json'])
def complete_trace():
t=get(TEMPO+'/api/traces/'+traceid)
serialized=json.dumps(t)
check(a['token'] not in serialized and a['registration']['password'] not in serialized,'credential leaked to traces')
spans=norm_spans(t)
names={s['name'] for s in spans};return spans if {'queue.publish','queue.consume','image.transform','s3.request'}.issubset(names) and (not retry or sum(x['name']=='queue.consume' for x in spans)>=2) else None
spans,delay=wait_for(complete_trace)
check({'messenger-api','messenger-worker','messenger-dispatcher'}.issubset({s['service'] for s in spans}),'missing service in trace')
for s in spans:
if s['name']=='queue.consume':check(s['parent_id'] in {x['id'] for x in spans if x['name']=='queue.publish'},'consumer not child of producer')
params={'query':'{service_name=~"messenger-(api|worker|dispatcher)"} | trace_id="'+traceid+'"','limit':'100','start':str(int((time.time()-180)*1e9)),'end':str(int(time.time()*1e9))}
logs,_=wait_for(lambda:get(LOKI+'/loki/api/v1/query_range?'+urllib.parse.urlencode(params))['data']['result'])
serialized=json.dumps(logs)
check(a['token'] not in serialized and a['registration']['password'] not in serialized,'credential leaked to logs')
services={item['stream']['service_name'] for item in logs};check({'messenger-api','messenger-worker'}.issubset(services),'correlated service logs missing')
result={'trace_id':traceid,'attachment_id':att['id'],'ingest_wait_seconds':delay,'spans':spans,'log_services':sorted(services),'log_lines':sum(len(x['values']) for x in logs)}
(ROOT/'evidence'/artifact).write_text(json.dumps(result,indent=2)+'\n');print('PASS: real W3C API → outbox → producer → consumer → S3/DB trace and correlated logs',flush=True)
return result
class Traffic:
def __init__(self,actor,chat,threads=4):self.actor=actor;self.chat=chat;self.stop=threading.Event();self.results=[];self.pool=concurrent.futures.ThreadPoolExecutor(threads);self.tasks=[self.pool.submit(self.run) for _ in range(threads)]
def run(self):
c=Client(BASE,timeout=4)
while not self.stop.is_set():
start=time.monotonic()
try:r=c.message(self.actor,self.chat,'synthetic incident probe');self.results.append({'ok':True,'seconds':time.monotonic()-start,'trace_id':r['headers'].get('X-Trace-Id')})
except Failure:self.results.append({'ok':False,'seconds':time.monotonic()-start})
time.sleep(.2)
def close(self):self.stop.set();self.pool.shutdown(wait=True)
def timeline(seconds,step=1):
start=time.monotonic();points=[]
while time.monotonic()-start<seconds:
points.append({'elapsed':round(time.monotonic()-start,3),'time':time.time(),'alerts':alerts(),'queue_depth':scalar('max(messenger_queue_depth)'),'oldest_seconds':scalar('max(messenger_queue_oldest_age_seconds)'),'api_error_ratio':scalar('sum(rate(haproxy_backend_http_responses_total{proxy="replicas",code="5xx"}[10s])) / clamp_min(sum(rate(haproxy_backend_http_responses_total{proxy="replicas"}[10s])),.001)')});time.sleep(step)
return points
def worker_incident(c,a,chat):
timeline(15)
dc('stop','worker');start=time.monotonic();points=[];accepted=[]
try:
for _ in range(32):
att,data=c.attachment(a,chat);accepted.append((att,data));points+=timeline(1)
firing=[p for p in points if any(x['name']=='QueueLag' and x['state']=='firing' for x in p['alerts'])];check(firing,'QueueLag never fired')
burn=[p for p in points if any(x['name']=='ReadyBudgetFastBurn' and x['state']=='firing' for x in p['alerts'])];check(burn,'ready burn alert never fired')
finally:dc('up','-d','--no-deps','worker')
restored=time.monotonic()
for att,data in accepted:
ready=c.wait_ready(a,att)
response=c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=a);check(response['bytes']==data,'accepted job lost')
recovery=timeline(22);check(not any(x['state']=='firing' and x['name'] in ['QueueLag','ReadyBudgetFastBurn'] for x in alerts()),'queue alerts did not resolve')
result={'name':'worker_stopped','accepted_jobs':len(accepted),'all_ready_and_identical':True,'detection_seconds':firing[0]['time']-(time.time()-(time.monotonic()-start)),'burn_detection_seconds':burn[0]['time']-(time.time()-(time.monotonic()-start)),'recovery_observation_seconds':round(time.monotonic()-restored,3),'timeline':points+recovery};RESULT['incidents'].append(result);print('PASS: stopped worker, lag/ready budget firing then resolved, all accepted originals preserved',flush=True)
def lock_db(seconds):
return subprocess.Popen(['docker','compose','exec','-T','postgres','psql','-U','messenger','-d','messenger','-v','ON_ERROR_STOP=1','-c',f'BEGIN; LOCK TABLE chats IN ACCESS EXCLUSIVE MODE; SELECT pg_sleep({seconds}); ROLLBACK;'],cwd=ROOT,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
def db_incident(c,a,chat):
traffic=Traffic(a,chat);timeline(20)
try:
# A 3s bounded spike should not page the multi-window burn alert.
spike_begin=len(traffic.results);proc=lock_db(3);spike=timeline(18);spike_results=traffic.results[spike_begin:];proc.wait(timeout=8)
false=[p for p in spike if any(x['name']=='APIBudgetFastBurn' and x['state']=='firing' for x in p['alerts'])]
# Collect spans of an actual 5xx while the 2s SQL timeout fires.
proc=lock_db(45);start=time.monotonic();sustained=[];traceid=None
deadline=time.monotonic()+44
while time.monotonic()<deadline:
r=c.call('POST','/api/v1/chats/'+chat['id']+'/messages',[201,503],actor=a,body={'text':'DB lock probe'},headers={'Idempotency-Key':uuid.uuid4().hex})
if r['status']==503:traceid=r['headers'].get('X-Trace-Id')
sustained+=timeline(1)
proc.wait(timeout=8);restored=time.monotonic();recovery=timeline(32)
check(any(x['name']=='APIBudgetFastBurn' and x['state']=='firing' for p in sustained for x in p['alerts']),'sustained API burn never fired')
check(any(x['name']=='APIBudgetSlowBurn' and x['state']=='firing' for p in sustained for x in p['alerts']),'slow API burn never fired')
check(any(x['name']=='APIHighErrorRate' and x['state']=='firing' for p in sustained for x in p['alerts']),'high-error rule never fired')
check(not any(x['name']=='APIBudgetFastBurn' and x['state']=='firing' for x in alerts()),'API burn did not resolve')
trace,_=wait_for(lambda:norm_spans(get(TEMPO+'/api/traces/'+traceid)))
db=[s for s in trace if s['name'].startswith('db.')];check(any(s['duration_ms']>1000 for s in db),'DB trace does not show blocked query')
firing=[p for p in sustained if any(x['name']=='APIBudgetFastBurn' and x['state']=='firing' for x in p['alerts'])]
RESULT['incidents'].append({'name':'postgres_chat_table_lock','short_spike_seconds':3,'spike_http_errors':sum(not r['ok'] for r in spike_results),'spike_requests':len(spike_results),'false_fast_burn_firings':len(false),'sustained_lock_seconds':45,'detection_seconds':round(firing[0]['time']-(time.time()-(time.monotonic()-start)),3),'trace_id':traceid,'slow_db_spans':db,'timeline':spike+sustained+recovery})
print('PASS: DB lock distinguished by real spans, multi-window alert firing/resolved; spike false firings='+str(len(false)),flush=True)
finally:traffic.close()
def backend_incident(c,a,chat):
before=scalar('sum(otelcol_exporter_send_failed_spans_total)') or 0;traffic=Traffic(a,chat,threads=6);samples=[];dc('stop','tempo','loki')
try:
for _ in range(22):
samples.append(dc('stats','--no-stream','--format','{{.Name}} {{.MemUsage}}','collector'));time.sleep(1)
c.message(a,chat,'confirmed while telemetry backends unavailable')
finally:dc('up','-d','--no-deps','tempo','loki');traffic.close()
time.sleep(5);after=scalar('sum(otelcol_exporter_send_failed_spans_total)') or 0
check(all(r['ok'] for r in traffic.results),'telemetry outage broke business requests');check(after>before,'telemetry loss counter did not increase')
RESULT['incidents'].append({'name':'telemetry_backends_stopped','successful_messages':len(traffic.results),'business_errors':sum(not r['ok'] for r in traffic.results),'failed_span_exports_delta':after-before,'collector_memory_samples':samples,'queue_bound_batches':64,'export_retry_budget_seconds':15})
print('PASS: telemetry backend outage, business messages continue; bounded buffering and counted loss',flush=True)
def labels_check():
series=get(PROM+'/api/v1/series?'+urllib.parse.urlencode({'match[]':'{__name__=~"http_server.*|messenger.*"}'}))['data']
forbidden={'user_id','chat_id','message_id','attachment_id','request_id','job_id','trace_id','span_id','filename','raw_url','url'}
check(series,'no application metric series')
for item in series:check(not forbidden.intersection(item),'high cardinality labels')
(ROOT/'evidence/metric-labels.json').write_text(json.dumps({'series_count':len(series),'label_keys':sorted(set().union(*(set(s) for s in series))),'forbidden_labels_absent':True},indent=2)+'\n')
print('PASS: live application metric series use bounded labels',flush=True)
def main():
global RESULT
phase=sys.argv[1] if len(sys.argv)>1 else 'all'
if phase!='all' and (ROOT/'evidence/incidents.json').exists():RESULT=json.loads((ROOT/'evidence/incidents.json').read_text())
c=Client(BASE);a,b,e,chat=c.bootstrap();wait_for(lambda:scalar('sum(http_server_requests_total)'))
if phase in ['all','trace']:
trace_chain(c,a,chat)
trace_chain(c,a,chat,retry=True,artifact='trace-chain-retry.json')
if phase in ['all','worker']:worker_incident(c,a,chat)
if phase in ['all','db']:db_incident(c,a,chat)
if phase in ['all','backend']:
backend_incident(c,a,chat)
trace_chain(c,a,chat,artifact='trace-chain-recovered.json')
labels_check()
RESULT['finished_at']=datetime.datetime.now(datetime.timezone.utc).isoformat()
if __name__=='__main__':
try:main()
finally:(ROOT/'evidence/incidents.json').write_text(json.dumps(RESULT,indent=2)+'\n')
+61
View File
@@ -0,0 +1,61 @@
#!/usr/bin/env python3
"""Stop each real container, then replace them in sequence under writes."""
import json,os,subprocess,sys,threading,time,uuid
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'tests'))
from client import Client,Failure,check
BASE=os.environ.get('BASE_URL','http://localhost:8086')
def dc(*args):return subprocess.check_output(['docker','compose',*args],cwd=ROOT,text=True,stderr=subprocess.DEVNULL).strip()
def inspect(id):return json.loads(subprocess.check_output(['docker','inspect',id],text=True))[0]
def ready():
deadline=time.monotonic()+45
while time.monotonic()<deadline:
try:
dc('up','-d','--no-deps','--wait','api');time.sleep(2);return
except subprocess.CalledProcessError:time.sleep(1)
raise AssertionError('API did not recover')
def run_phase(c,actor,chat,action,seconds=7):
results=[];failed=0;stop=threading.Event();events=[];seen=set()
def write():
nonlocal failed
client=Client(BASE,timeout=2);key=uuid.uuid4().hex
while not stop.is_set():
try:
response=client.message(actor,chat,'operation probe '+key,key=key)
results.append((time.monotonic(),response['json']['id']))
seen.add(response['headers']['X-Instance-Id']);key=uuid.uuid4().hex
except Failure:failed+=1
time.sleep(.02)
worker=threading.Thread(target=write);worker.start();time.sleep(1)
started=time.monotonic();action();action_done=time.monotonic();time.sleep(seconds);stop.set();worker.join()
history=[];path='/api/v1/chats/'+chat['id']+'/messages?limit=100'
from urllib.parse import quote
while True:
page=c.call('GET',path,actor=actor,schema='MessagePage')['json'];history+=page['items']
if page['next_cursor'] is None:break
path='/api/v1/chats/'+chat['id']+'/messages?limit=100&cursor='+quote(page['next_cursor'],safe='')
ids=[m['id'] for m in history];check(len(ids)==len(set(ids)),'duplicate IDs')
check({i for _,i in results}.issubset(set(ids)),'lost confirmed message')
successes_after=[t for t,_ in results if t>=action_done]
check(successes_after,'no successful write after action')
recovery=successes_after[0]-started
return {'successful_writes':len(results),'errors':failed,'successful_rps':len(results)/(time.monotonic()-started+1),'first_recovery_seconds':round(recovery,3),'action_seconds':round(action_done-started,3),'instances':sorted(seen),'confirmed_preserved':True}
def main():
ready();c=Client(BASE);a,b,e,chat=c.bootstrap();results={'failures':[]}
ids=dc('ps','-q','api').splitlines();check(len(ids)==2,'requires two API containers')
for id in ids:
alias=inspect(id)['Config']['Hostname']
env=dict(os.environ,TARGET_INSTANCE_ID=alias)
def action():subprocess.run([str(ROOT/'scripts/stop-one.sh')],env=env,check=True,stdout=subprocess.DEVNULL)
try:
result=run_phase(c,a,chat,action);result['stopped_alias']=alias
check(not inspect(id)['State']['Running'],'target is still running')
check(result['first_recovery_seconds']<10,'recovery >10s')
results['failures'].append(result)
finally:ready()
results['rolling']=run_phase(c,a,chat,lambda:subprocess.run([str(ROOT/'scripts/rolling.sh')],check=True,stdout=subprocess.DEVNULL),seconds=2)
check(len(dc('ps','-q','api').splitlines())==2,'rolling lost replicas')
(ROOT/'evidence/operations.json').write_text(json.dumps(results,indent=2)+'\n')
print('PASS: each API stopped and rolling replacement completed; confirmed writes preserved')
if __name__=='__main__':main()
+81
View File
@@ -0,0 +1,81 @@
#!/usr/bin/env python3
"""Black-box fault experiment. Mutates only this synthetic Compose project."""
import hashlib,json,os,subprocess,sys,time,uuid
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'tests'))
from client import Client,check,Failure
BASE=os.environ.get('BASE_URL','http://localhost:8086');C=Client(BASE)
RESULT={'method':'real process/container faults; no forged timestamps','cases':[]}
def dc(*args):return subprocess.check_output(['docker','compose',*args],cwd=ROOT,text=True,stderr=subprocess.DEVNULL).strip()
def sql(query):return dc('exec','-T','postgres','psql','-U','messenger','-d','messenger','-Atc',query)
def record(name,**kwargs):RESULT['cases'].append(dict(name=name,**kwargs));print('PASS:',name,flush=True)
def meta(a,id):return C.call('GET','/api/v1/attachments/'+id,actor=a,schema='Attachment')['json']
def wait_status(a,id,status,timeout=130):
start=time.monotonic()
while time.monotonic()-start<timeout:
try:item=meta(a,id)
except Failure:time.sleep(.25);continue
if item['status']==status:return item,round(time.monotonic()-start,3)
time.sleep(.25)
raise AssertionError('timeout waiting '+status+' last='+item['status'])
def job(id,version=1):return json.loads(sql("SELECT row_to_json(x) FROM (SELECT 1 schema_version,job_id,'attachment.process.v1' type,attachment_id,pipeline_version,1 attempt,to_char(created_at AT TIME ZONE 'UTC','YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"') created_at FROM pipeline_jobs WHERE attachment_id='"+id+"' AND pipeline_version="+str(version)+") x"))
def publish(payload):
# The URL is read inside the container; credentials never enter output/argv.
script='valkey-cli -u "$(cat /run/secrets/broker_url)" --no-auth-warning XADD attachment.jobs.v1 "*" payload "$1" >/dev/null'
return dc('exec','-T','broker','sh','-c',script,'sh',json.dumps(payload))
def content(a,id,variant='original'):return C.call('GET','/api/v1/attachments/'+id+'/content?variant='+variant,actor=a)['bytes']
def upload(a,chat):return C.attachment(a,chat)
def start_worker():dc('up','-d','--no-deps','worker')
def fault(a,chat,point):
dc('stop','worker');att,data=upload(a,chat);name='lab-fault-'+uuid.uuid4().hex[:10]
dc('run','-d','--no-deps','--name',name,'-e','LAB_FAULT_POINT='+point,'worker')
try:
deadline=time.monotonic()+45
while time.monotonic()<deadline:
if subprocess.run(['docker','exec',name,'test','-f','/tmp/fault-reached'],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL).returncode==0:break
time.sleep(.2)
else:raise AssertionError('fault boundary never reached '+point)
status=meta(a,att['id'])['status'];check(status==('ready' if point=='after_commit' else 'processing'),'wrong crash boundary')
subprocess.run(['docker','kill',name],check=True,stdout=subprocess.DEVNULL)
start_worker();ready,recovery=wait_status(a,att['id'],'ready');check(content(a,att['id'])==data,'original changed after crash')
time.sleep(2)
check(int(sql("SELECT count(*) FROM pipeline_jobs WHERE attachment_id='"+att['id']+"'"))==1,'extra logical job')
record('crash_'+point,attachment_id=att['id'],status_at_crash=status,recovery_seconds=recovery,versions=len(ready['variants']))
return att,data
finally:subprocess.run(['docker','rm','-f',name],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL);start_worker()
def main():
a,b,e,chat=C.bootstrap()
dc('stop','worker','dispatcher');att,data=upload(a,chat)
C.call('GET','/api/v1/attachments/'+att['id']+'/content',409,actor=a)
C.message(a,chat,'',attachments=[att['id']]);C.message(a,chat,'text while worker is down')
check(sql("SELECT published_at IS NULL FROM pipeline_jobs WHERE attachment_id='"+att['id']+"'")=='t','expected committed unpublished outbox')
dc('restart','api','broker');dc('up','-d','--no-deps','dispatcher','worker');ready,recovery=wait_status(a,att['id'],'ready')
check(content(a,att['id'])==data,'durable stage lost');check({v['name'] for v in ready['variants']}=={'thumbnail','crop','optimized'},'missing variants')
for v in ready['variants']:check(hashlib.sha256(content(a,att['id'],v['name'])).hexdigest()==v['sha256'],'variant checksum')
C.call('GET','/api/v1/attachments/'+att['id'],404,actor=e)
record('commit_before_publish_api_broker_restart',attachment_id=att['id'],recovery_seconds=recovery,original_identical=True)
# No ACK occurred for these real crashes. Lease + stream reclaim recover them.
for point in ['before_objects','after_objects','after_commit']:fault(a,chat,point)
before=meta(a,att['id']);p=job(att['id'])
for _ in range(5):publish(p)
time.sleep(2);check(meta(a,att['id'])==before,'ready duplicate changed metadata');record('five_duplicate_deliveries',unchanged=True)
dc('run','--rm','--no-deps','worker','reprocess',att['id']);v2,_=wait_status(a,att['id'],'ready');check(sql("SELECT pipeline_version FROM attachments WHERE id='"+att['id']+"'")=='2','version not incremented')
v2bytes={v['name']:content(a,att['id'],v['name']) for v in v2['variants']}
# Old version redelivery is reordered behind a fully committed new version.
for _ in range(3):publish(p)
time.sleep(2);check(meta(a,att['id'])==v2,'old version changed metadata');check(all(content(a,att['id'],k)==v for k,v in v2bytes.items()),'old version overwrote bytes')
record('reordered_v1_after_v2',metadata_unchanged=True,checksums_unchanged=True)
# A permanent checksum mismatch is observable and cannot be attached. Restore
# the expected digest and explicitly replay; the source itself stays durable.
dc('stop','worker');bad,data=upload(a,chat);original=bad['sha256'];sql("UPDATE attachments SET sha256=repeat('0',64) WHERE id='"+bad['id']+"'");start_worker();failed,_=wait_status(a,bad['id'],'failed')
check(failed['error_code']=='invalid_image','permanent error code')
C.call('POST','/api/v1/chats/'+chat['id']+'/messages',409,actor=a,body={'text':'','attachment_ids':[bad['id']]},headers={'Idempotency-Key':uuid.uuid4().hex})
sql("UPDATE attachments SET sha256='"+original+"' WHERE id='"+bad['id']+"'");dc('run','--rm','--no-deps','worker','replay',bad['id']);replayed,_=wait_status(a,bad['id'],'ready')
check(content(a,bad['id'])==data,'replay lost original');check(int(sql("SELECT count(*) FROM pipeline_audit WHERE job_id=(SELECT job_id FROM pipeline_jobs WHERE attachment_id='"+bad['id']+"') AND event='operator_replay'"))==1,'missing replay audit')
record('failed_registry_explicit_audited_replay',error_code=failed['error_code'],ready=True)
print('PASS: versioned at-least-once pipeline invariants; NOT exactly-once delivery')
if __name__=='__main__':
try:main()
finally:
dc('up','-d','--no-deps','worker','dispatcher')
(ROOT/'evidence/pipeline.json').write_text(json.dumps(RESULT,indent=2)+'\n')
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env python3
"""Controlled transient failures, finite retries, admission bound, hard API kill."""
import json,time,uuid
from pipeline import ROOT,C,dc,sql,check,meta,wait_status,content,upload,start_worker
def main():
a,b,e,chat=C.bootstrap();result={}
dc('stop','worker','dispatcher');att,data=upload(a,chat)
dc('kill','-s','SIGKILL','api');dc('restart','broker');dc('up','-d','--no-deps','--wait','api','dispatcher','worker')
ready,recovery=wait_status(a,att['id'],'ready');check(content(a,att['id'])==data,'SIGKILL lost accepted original');result['sigkill_after_commit_before_publish']={'ready':True,'seconds':recovery}
# Hold S3 down while retry worker runs. Read metadata via SQL because S3 is
# intentionally a readiness dependency; no fake app success during this outage.
dc('stop','worker');bad,data=upload(a,chat);dc('stop','s3');start_worker();start=time.monotonic()
try:
deadline=time.monotonic()+130
while time.monotonic()<deadline:
status=sql("SELECT status FROM attachments WHERE id='"+bad['id']+"'")
if status=='failed':break
time.sleep(.5)
else:raise AssertionError('retries did not terminate')
attempts=int(sql("SELECT attempt FROM pipeline_jobs WHERE attachment_id='"+bad['id']+"'"));check(attempts==5,'wrong retry budget')
code=sql("SELECT error_code FROM attachments WHERE id='"+bad['id']+"'");check(code=='retry_exhausted','wrong terminal code')
events=json.loads(sql("SELECT json_agg(x) FROM (SELECT event,attempt,created_at FROM pipeline_audit WHERE job_id=(SELECT job_id FROM pipeline_jobs WHERE attachment_id='"+bad['id']+"') ORDER BY id) x"))
result['retry_exhaustion']={'attempts':attempts,'error_code':code,'seconds':round(time.monotonic()-start,3),'audit':events}
finally:dc('up','-d','--no-deps','--wait','s3');time.sleep(2)
dc('run','--rm','--no-deps','worker','replay',bad['id']);wait_status(a,bad['id'],'ready');check(content(a,bad['id'])==data,'replay after transient failure lost source')
# Fill the durable admission ledger with synthetic test-only entries in this
# test's own chat; delete them transactionally at the end (no API/user data).
dc('stop','worker','dispatcher');testid=uuid.uuid4().hex
try:
sql("INSERT INTO pipeline_jobs(job_id,attachment_id,pipeline_version) SELECT gen_random_uuid(),'"+att['id']+"',n FROM generate_series(100,1099)n")
C.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=backpressure.png',429,actor=a,raw=data,headers={'Content-Type':'image/png'})
check(sql("SELECT count(*) FROM pipeline_jobs WHERE pipeline_version BETWEEN 100 AND 1099 AND attachment_id='"+att['id']+"'")=='1000','fixture mutated')
result['admission_bound']={'unfinished_cap':1000,'response':429,'confirmed_work_retained':True}
finally:
sql("DELETE FROM pipeline_jobs WHERE pipeline_version BETWEEN 100 AND 1099 AND attachment_id='"+att['id']+"'");dc('up','-d','--no-deps','worker','dispatcher')
(ROOT/'evidence/retry-backpressure.json').write_text(json.dumps(result,indent=2)+'\n');print('PASS: SIGKILL, finite durable retry/backoff/replay, atomic admission limit')
if __name__=='__main__':main()
+13
View File
@@ -0,0 +1,13 @@
#!/usr/bin/env python3
"""Small sanitized runtime manifest; no environment, passwords or tokens."""
import json,platform,subprocess
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
ids=subprocess.check_output(['docker','compose','ps','-q'],cwd=ROOT,text=True).splitlines()
result={'platform':platform.platform(),'containers':[]}
for id in ids:
item=json.loads(subprocess.check_output(['docker','inspect',id],text=True))[0]
result['containers'].append({'service':item['Config']['Labels']['com.docker.compose.service'],'name':item['Name'],'alias':item['Config']['Hostname'],'image':item['Config']['Image'],'image_id':item['Image'],'user':item['Config']['User'],'pid1_path':item['Path'],'started_at':item['State']['StartedAt'],'memory_limit_bytes':item['HostConfig']['Memory'],'nano_cpus_limit':item['HostConfig']['NanoCpus'],'published_ports':item['NetworkSettings']['Ports'],'health':item['State'].get('Health',{}).get('Status'),'mount_targets':[m['Destination'] for m in item['Mounts']]})
result['postgres_durability']=subprocess.check_output(['docker','compose','exec','-T','postgres','psql','-U','messenger','-d','messenger','-Atqc',"SELECT name||'='||setting FROM pg_settings WHERE name IN ('fsync','synchronous_commit','full_page_writes','max_connections') ORDER BY name"],cwd=ROOT,text=True).splitlines()
(ROOT/'evidence/runtime.json').write_text(json.dumps(result,indent=2)+'\n')
print('Saved sanitized runtime manifest: resources, images, PID1, ports, durability')
+29
View File
@@ -0,0 +1,29 @@
#!/usr/bin/env python3
"""Release an actually stale v1 process after v2 commits, rather than mocking SQL."""
import hashlib,json,subprocess,time,uuid
from pipeline import ROOT,C,dc,sql,check,meta,wait_status,content,upload,start_worker
def main():
a,b,e,chat=C.bootstrap();dc('stop','worker');att,data=upload(a,chat);name='lab-stale-'+uuid.uuid4().hex[:10]
dc('run','-d','--no-deps','--name',name,'-e','LAB_FAULT_POINT=before_write','worker')
try:
deadline=time.monotonic()+45
while time.monotonic()<deadline:
if subprocess.run(['docker','exec',name,'test','-f','/tmp/fault-reached'],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL).returncode==0:break
time.sleep(.2)
else:raise AssertionError('v1 did not reach pre-write boundary')
check(meta(a,att['id'])['status']=='processing','v1 not processing')
dc('run','--rm','--no-deps','worker','reprocess',att['id']);start_worker();v2,recovery=wait_status(a,att['id'],'ready')
versions=sql("SELECT pipeline_version FROM attachments WHERE id='"+att['id']+"'");check(versions=='2','new version missing')
before={v['name']:content(a,att['id'],v['name']) for v in v2['variants']}
subprocess.run(['docker','exec',name,'touch','/tmp/fault-release'],check=True)
time.sleep(3)
after=meta(a,att['id']);check(after==v2,'stale process overwrote v2 metadata')
check(all(content(a,att['id'],k)==v for k,v in before.items()),'stale process overwrote v2 variants')
check(content(a,att['id'])==data,'original changed')
check(sql("SELECT count(*) FROM pipeline_jobs WHERE attachment_id='"+att['id']+"' AND finished_at IS NULL")=='0','obsolete version still pending')
result={'case':'live stale v1 resumed S3 writes and SQL finalization after v2 ready','attachment_id':att['id'],'new_version':2,'v2_recovery_seconds':recovery,'metadata_unchanged':True,'sha256_unchanged':True,'unfinished_jobs':0,'variant_checksums':{v['name']:v['sha256'] for v in v2['variants']}}
(ROOT/'evidence/version-fence.json').write_text(json.dumps(result,indent=2)+'\n');print('PASS: live stale v1 cannot overwrite v2 objects or fenced SQL result')
finally:
subprocess.run(['docker','rm','-f',name],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL);start_worker()
if __name__=='__main__':main()
+20
View File
@@ -0,0 +1,20 @@
#!/usr/bin/env python3
"""Short reproducible message workload + container resources, not capacity proof."""
import json,subprocess,time,sys,urllib.request,urllib.parse
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
def dc(*args):return subprocess.check_output(['docker','compose',*args],cwd=ROOT,text=True,stderr=subprocess.DEVNULL).strip()
def counts():return dc('exec','-T','postgres','psql','-U','messenger','-d','messenger','-Atc','SELECT json_build_object(\'users\',(SELECT count(*) FROM users),\'chats\',(SELECT count(*) FROM chats),\'messages\',(SELECT count(*) FROM messages),\'attachments\',(SELECT count(*) FROM attachments))')
start=time.monotonic();before=json.loads(counts());samples=[]
process=subprocess.Popen([sys.executable,'tests/load.py','--base-url','http://localhost:8086','--duration','15','--concurrency','4','--output','evidence/load.json'],cwd=ROOT)
while process.poll() is None:
row={'elapsed_seconds':round(time.monotonic()-start,3)}
for name,expr in [('container_cpu_cores','rate(container_cpu_time_seconds_total[10s])'),('container_memory_bytes','container_memory_usage_bytes')]:
try:
with urllib.request.urlopen('http://localhost:9096/api/v1/query?'+urllib.parse.urlencode({'query':expr}),timeout=3) as response:row[name]=json.load(response)['data']['result']
except OSError:row[name]=None
samples.append(row);time.sleep(1)
load=json.loads((ROOT/'evidence/load.json').read_text())
assert process.returncode in [0,1] and 'successful_requests' in load,'load did not produce a complete measurement'
result={'scope':'local synthetic closed-loop, includes auth/ACL/idempotency/SQL commit and enabled telemetry','requested_duration_seconds':15,'concurrency':4,'public_load_exit_code':process.returncode,'warmup_seconds':0,'elapsed_including_bootstrap_seconds':round(time.monotonic()-start,3),'before':before,'after':json.loads(counts()),'resources':samples,'limitations':['successful latency percentiles only','coordinated omission','growing dataset','shared Docker VM; not maximum capacity']}
(ROOT/'evidence/load-resources.json').write_text(json.dumps(result,indent=2)+'\n');print('MEASURED: workload, error count, exit code and container resources saved')