Implement durable versioned image pipeline with outbox, fencing and fault experiments

This commit is contained in:
2026-11-20 21:38:54 +03:00
parent 276dbdad8a
commit 33e02d0ef9
58 changed files with 4293 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']: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')
+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:8085')
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:8085');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()