Реализация на 5

This commit is contained in:
Grbisba
2026-11-17 13:08:13 +03:00
parent 470d9d6f1e
commit 60f48c0337
229 changed files with 74928 additions and 47 deletions
+10
View File
@@ -0,0 +1,10 @@
# Перенесённые проверки pipeline
Существующие проверки перенесены из собственной lab5 и используют только изолированный Compose-проект lab6, URL http://localhost:18086 и его volumes. Новые unit/integration-тесты для ЛР №6 не добавлялись. Новые воспроизводимые сценарии наблюдаемости находятся в `scripts/`.
- `make test-images`: форматы, геометрия, EXIF, alpha, checksums, ACL и отрицательные входы.
- `make test-staging`: защита активного source, cleanup, terminal error, retention, restore/replay.
- `make test-broker-persistence`: замена контейнера брокера с сохранённым volume при остановленном потребителе.
- `python3 student-tests/pipeline.py --repeats 1 --output evidence/pipeline.json`: 13 сценариев crash/retry/lease/version/idempotency. Профиль ограничивает job timeout/lease; в finally восстанавливается стандартная конфигурация.
Все изменяющие состояние проверки запускать последовательно на синтетическом стенде. Нельзя выполнять их параллельно с исследованием SLO. Токены не печатаются и не сохраняются.
+47
View File
@@ -0,0 +1,47 @@
#!/usr/bin/env python3
"""Prove a confirmed queued message survives broker container replacement, not only restart."""
from pathlib import Path
import json
import subprocess
import sys
import time
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'tests'))
from client import Client,check
def compose(*args):
r=subprocess.run([str(ROOT/'scripts/compose.sh'),*args],stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True,timeout=150)
check(r.returncode==0,'broker persistence infrastructure command failed: '+args[0]);return r.stdout.strip()
def queued():
r=subprocess.run([str(ROOT/'scripts/compose.sh'),'exec','-T','broker','rabbitmqctl','-q','list_queues','name','messages'],stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True,timeout=30)
if r.returncode:return 0
out=r.stdout
for line in out.splitlines():
fields=line.split()
if len(fields)==2 and fields[0]=='attachments.v1':return int(fields[1])
return 0
def main():
c=Client('http://localhost:18086');alice,bob,eve,chat=c.bootstrap()
try:
compose('stop','worker');att,data=c.attachment(alice,chat)
deadline=time.monotonic()+20
while queued()<1 and time.monotonic()<deadline:time.sleep(.2)
check(queued()>=1,'message not durably queued before replacement')
published=compose('exec','-T','postgres','psql','-U','messenger','-d','messenger','-At','-c',"SELECT bool_and(status='published') FROM outbox WHERE job_id=(SELECT id FROM attachment_jobs WHERE attachment_id='%s')"%att['id'])
check(published=='t','outbox not marked published before replacement')
compose('stop','dispatcher')
old=compose('ps','-q','broker')
compose('up','-d','--no-deps','--force-recreate','--wait','--wait-timeout','120','broker')
new=compose('ps','-q','broker');check(new!=old,'broker container was not replaced')
deadline=time.monotonic()+30
while queued()<1 and time.monotonic()<deadline:time.sleep(.3)
check(queued()>=1,'confirmed queue message lost after replacement')
compose('start','worker');c.wait_ready(bob,att)
check(c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=bob)['bytes']==data,'original changed after broker replacement')
result={'result':'PASS','attachment_id':att['id'],'broker_hostname':'broker','old_container_id':old,'new_container_id':new,'message_present_before_and_after':True,'outbox_published_before_replacement':True,'dispatcher_stopped_during_replacement':True}
(ROOT/'evidence/broker-persistence.json').write_text(json.dumps(result,indent=2)+'\n')
print('PASS: confirmed message survived broker container replacement with the same volume and stable node identity')
finally:compose('start','worker','dispatcher')
if __name__=='__main__':main()
+53
View File
@@ -0,0 +1,53 @@
#!/usr/bin/env python3
"""Image contract checks using synthetic fixtures and real decoding in ImageMagick."""
import hashlib
import json
from pathlib import Path
import struct
import subprocess
import sys
import urllib.parse
import zlib
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'tests'))
from client import Client,check
from image_probe import jpeg_size
def magick(args,data=None):
r=subprocess.run([str(ROOT/'scripts/compose.sh'),'run','--rm','--no-deps','-T','--entrypoint','magick','operator']+args,input=data,stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=30)
check(r.returncode==0,'fixture decoder failed')
return r.stdout
def png(w,h,rgba):
def chunk(t,b):return struct.pack('>I',len(b))+t+b+struct.pack('>I',zlib.crc32(t+b))
return b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('>IIBBBBB',w,h,8,6,0,0,0))+chunk(b'IDAT',zlib.compress(b''.join(b'\0'+b''.join(bytes(rgba(x,y)) for x in range(w)) for y in range(h)) if callable(rgba) else (b'\0'+bytes(rgba)*w)*h))+chunk(b'IEND',b'')
def main():
c=Client('http://localhost:18086');alice,bob,eve,chat=c.bootstrap();results=[]
jpeg=magick(['png:-','jpeg:-'],png(300,150,(255,0,0,255)))
# EXIF TIFF orientation 6: display rotates the stored 300x150 pixels clockwise.
tiff=b'II'+struct.pack('<HI',42,8)+struct.pack('<H',1)+struct.pack('<HHI',0x112,3,1)+struct.pack('<H',6)+b'\0\0'+struct.pack('<I',0)
exif=b'Exif\0\0'+tiff;oriented=jpeg[:2]+b'\xff\xe1'+struct.pack('>H',len(exif)+2)+exif+jpeg[2:]
for name,data,mime,dimensions in [('small',png(16,8,(255,0,0,255)),'image/png',(16,8)),('floor',png(333,100,(255,0,0,255)),'image/png',(256,76)),('alpha',png(40,20,(0,0,0,0)),'image/png',(40,20)),('orientation',oriented,'image/jpeg',(128,256)),('thin',png(1,300,(0,0,0,255)),'image/png',(1,256)),('center_crop',png(300,100,lambda x,y:(255,0,0,255) if 100<=x<200 else (0,0,255,255)),'image/png',(256,85))]:
att=c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename='+name,202,actor=alice,raw=data,headers={'Content-Type':mime},schema='Attachment')['json'];ready=c.wait_ready(bob,att)
original=c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=bob)['bytes'];check(original==data,'original changed')
for v in ready['variants']:
b=c.call('GET','/api/v1/attachments/'+att['id']+'/content?variant='+v['name'],actor=bob)['bytes'];check(hashlib.sha256(b).hexdigest()==v['sha256'],'checksum mismatch')
actual=tuple(map(int,magick(['identify','-format','%w %h','-'],b).split()))
check(actual==(v['width'],v['height']),'actual dimensions differ')
if v['name']=='thumbnail':
check(jpeg_size(b)==dimensions,'thumbnail geometry differs')
if name=='alpha':check(magick(['identify','-format','%[pixel:p{0,0}]','jpeg:-'],b).strip() in (b'gray(255)',b'srgb(255,255,255)'),'alpha was not composited on white')
if v['name']=='crop':
check(actual==(128,128),'crop geometry differs')
if name=='center_crop':
import re
color=tuple(map(int,re.findall(rb'\d+',magick(['identify','-format','%[pixel:p{0,0}]','jpeg:-'],b))))
check(len(color)==3 and color[0]>=250 and color[1]<=5 and color[2]<=5,'crop is not centered')
check(b'Exif\0\0' not in b,'EXIF retained in derivative')
c.call('GET','/api/v1/attachments/'+att['id']+'/content',404,actor=eve)
results.append({'case':name,'result':'PASS','thumbnail':dimensions})
for data,mime,status in [(b'not image','image/png',415),(png(2,2,(0,0,0,255)),'image/jpeg',415),(png(2,2,(0,0,0,255))[:40],'image/png',415),(b'x'*10485761,'image/png',413)]:
c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=bad',status,actor=alice,raw=data,headers={'Content-Type':mime})
(ROOT/'evidence/images.json').write_text(json.dumps({'results':results,'negative_cases':4},indent=2)+'\n');print('PASS: image geometry, EXIF, alpha, real formats, checksums, ACL and negative inputs')
if __name__=='__main__':main()
+179
View File
@@ -0,0 +1,179 @@
#!/usr/bin/env python3
"""Repeatable lab5 experiment on the local synthetic Compose stand. Never prints tokens."""
import argparse
import concurrent.futures
import datetime
import hashlib
import json
import os
from pathlib import Path
import subprocess
import sys
import time
import uuid
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'tests'))
from client import Client, Failure, check
from image_probe import jpeg_size
FAULTS=ROOT/'.lab6-faults'
COMPOSE=[str(ROOT/'scripts/compose.sh'),'-f',str(ROOT/'compose.yaml'),'-f',str(ROOT/'compose.faults.yaml')]
RESULTS=[]
SELECTED=set()
def compose(*args, allow_failure=False):
p=subprocess.run(COMPOSE+list(args),cwd=ROOT,stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True,timeout=180)
if p.returncode and not allow_failure:
# Infrastructure logs may contain settings; report only action and exit status.
raise Failure('Compose '+args[0]+' failed, exit '+str(p.returncode))
return p
def sql(query):
return compose('exec','-T','postgres','psql','-U','messenger','-d','messenger','-At','-v','ON_ERROR_STOP=1','-c',query).stdout.strip()
def uid(value):
return str(uuid.UUID(value))
def job(att,version=1):
return sql("SELECT id FROM attachment_jobs WHERE attachment_id='%s' AND pipeline_version=%d"%(uid(att['id']),version))
def operator(action,id=None,version=None, allow_failure=False):
args=['run','--rm','--no-deps','-T','operator','jobs',action]
if id: args+=['--id',uid(id)]
if version:args+=['--pipeline-version',str(version)]
return compose(*args,allow_failure=allow_failure)
def wait(predicate,timeout=65):
deadline=time.monotonic()+timeout
while time.monotonic()<deadline:
v=predicate()
if v:return v
time.sleep(.1)
raise Failure('experiment condition timed out')
def directive(point,id,action):
p=FAULTS/(point+'.'+id)
Path(str(p)+'.hit').unlink(missing_ok=True)
p.write_text(action);p.chmod(0o666)
return p
def hit(p,timeout=65):
wait(lambda:Path(str(p)+'.hit').exists(),timeout)
return Path(str(p)+'.hit').read_text().strip()
def metadata(c,actor,att):
return c.call('GET','/api/v1/attachments/'+att['id'],actor=actor,schema='Attachment')['json']
def state(c,actor,att,value,timeout=65):
return wait(lambda:(a if (a:=metadata(c,actor,att))['status']==value else None),timeout)
def ready(c,actor,att,content):
a=c.wait_ready(actor,att)
check(a['error_code'] is None,'ready has error')
original=c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=actor)['bytes']
check(original==content,'original changed')
variants={v['name']:v for v in a['variants']}
check(set(variants)=={'thumbnail','crop','optimized'},'variant set differs')
for name,v in variants.items():
r=c.call('GET','/api/v1/attachments/'+att['id']+'/content?variant='+name,actor=actor)
check(hashlib.sha256(r['bytes']).hexdigest()==v['sha256'] and len(r['bytes'])==v['size_bytes'],'variant checksum mismatch')
if name!='optimized':check(jpeg_size(r['bytes'])==(v['width'],v['height']),'JPEG dimensions differ')
else:check(r['bytes'][:4]==b'RIFF' and r['bytes'][8:12]==b'WEBP','optimized is not WebP')
rows=int(sql("SELECT count(*) FROM attachment_variants WHERE attachment_id='%s'"%uid(att['id'])))
check(rows in (4,8),'manifest has duplicate/missing logical variants')
return a
def record(name,run,fn):
if SELECTED and name not in SELECTED:return
start=time.monotonic();detail=fn() or {}
r={'scenario':name,'run':run,'result':'PASS','seconds':round(time.monotonic()-start,3),**detail}
RESULTS.append(r);print(json.dumps(r),flush=True)
def main():
p=argparse.ArgumentParser();p.add_argument('--repeats',type=int,default=3);p.add_argument('--base-url',default='http://localhost:18086');p.add_argument('--output',default='evidence/pipeline.json');p.add_argument('--scenario',action='append',default=[]);args=p.parse_args()
SELECTED.update(args.scenario)
FAULTS.mkdir(exist_ok=True);FAULTS.chmod(0o777)
for f in FAULTS.iterdir():f.unlink()
compose('up','-d','--build','--wait','--wait-timeout','180')
c=Client(args.base_url,timeout=15);alice,bob,eve,chat=c.bootstrap()
def upload_stopped():
compose('stop','worker');att,content=c.attachment(alice,chat);return att,content,job(att)
try:
for run in range(1,args.repeats+1):
def recovery():
att,data,jid=upload_stopped();c.message(alice,chat,'',attachments=[att['id']]);c.call('GET','/api/v1/attachments/'+att['id']+'/content',409,actor=bob)
before=sql('SELECT pg_postmaster_start_time()')
compose('restart','api','postgres','redis','s3','broker')
wait(lambda:health(c),90);compose('run','--rm','--no-deps','-T','s3-init');compose('start','worker');ready(c,bob,att,data)
check(sql('SELECT pg_postmaster_start_time()')!=before,'PostgreSQL was not restarted')
return {'attachment_id':att['id'],'job_id':jid,'postgres_restarted':True}
record('worker_down_and_store_restart',run,recovery)
for point in ('before_objects','after_original_put','after_objects','after_result_commit','before_ack'):
def crash(point=point):
att,data,jid=upload_stopped();marker=directive(point,jid,'crash');compose('start','worker');hit(marker);ready(c,bob,att,data)
return {'job_id':jid,'manifest_rows':int(sql("SELECT count(*) FROM attachment_variants WHERE attachment_id='%s'"%uid(att['id'])))}
record('crash_'+point,run,crash)
def duplicates():
att,data=c.attachment(alice,chat);first=ready(c,bob,att,data);jid=job(att)
for _ in range(3):operator('redeliver',jid)
time.sleep(.5);check(metadata(c,bob,att)==first,'ready changed after duplicate')
return {'job_id':jid,'copies':3}
record('ready_redelivery',run,duplicates)
def publish_crash():
att,data,jid=upload_stopped();compose('stop','dispatcher');marker=directive('after_publish',jid,'crash')
# Existing publish may have completed before stop. Add a second durable notification.
sql("UPDATE outbox SET status='pending',next_attempt_at=clock_timestamp() WHERE job_id='%s'"%uid(jid))
compose('start','dispatcher');hit(marker);compose('start','worker');ready(c,bob,att,data)
wait(lambda:sql("SELECT count(*) FROM outbox WHERE job_id='%s' AND status='published'"%uid(jid))!='0',45)
return {'job_id':jid}
record('crash_confirm_before_outbox_mark',run,publish_crash)
def version_fence():
att,data,jid=upload_stopped();marker=directive('after_objects',jid,'pause');compose('start','worker');hit(marker)
# Recovery expires the real 8s lease; a newer attempt finishes on the second worker slot.
first=ready(c,bob,att,data);check(int(sql("SELECT attempt FROM attachment_jobs WHERE id='%s'"%uid(jid)))>=2,'lease not recovered')
operator('reprocess',att['id'],2);second=ready(c,bob,att,data)
check(first['variants']!=second['variants'],'pipeline versions are indistinguishable')
operator('redeliver',jid);marker.unlink();time.sleep(1)
check(metadata(c,bob,att)==second,'stale worker/job overwrote version 2')
check(sql("SELECT pipeline_version FROM attachments WHERE id='%s'"%uid(att['id']))=='2','version rolled back')
ready(c,bob,att,data)
return {'attachment_id':att['id'],'old_job_id':jid,'pipeline_version':2,'manifest_rows':8}
record('lease_reorder_and_stale_version',run,version_fence)
def retries():
att,data,jid=upload_stopped();marker=directive('before_objects',jid,'temporary');compose('start','worker');failed=state(c,bob,att,'failed',65)
check(failed['error_code']=='retry_exhausted','wrong terminal code');check(sql("SELECT attempt FROM attachment_jobs WHERE id='%s'"%uid(jid))=='5','attempt limit not honored')
c.call('POST','/api/v1/chats/'+chat['id']+'/messages',409,actor=alice,body={'text':'','attachment_ids':[att['id']]},headers={'Idempotency-Key':uuid.uuid4().hex})
marker.unlink();operator('replay',jid);ready(c,bob,att,data);check(operator('replay',jid,allow_failure=True).returncode!=0,'successful job replay allowed')
return {'job_id':jid,'failed_attempt':5,'replayed_attempt':6}
record('bounded_retry_and_explicit_replay',run,retries)
def permanent():
att,data,jid=upload_stopped();marker=directive('before_objects',jid,'permanent');compose('start','worker');failed=state(c,bob,att,'failed');check(failed['error_code']=='invalid_image','wrong permanent code');check(sql("SELECT attempt FROM attachment_jobs WHERE id='%s'"%uid(jid))=='1','permanent error was retried');marker.unlink();operator('replay',jid);ready(c,bob,att,data);return {'job_id':jid}
record('permanent_error',run,permanent)
for point in ('after_staging','after_upload_commit'):
def api_crash(point=point):
if point=='after_upload_commit':compose('stop','dispatcher')
marker=directive(point,'all','crash')
try:c.attachment(alice,chat)
except Failure:pass
aid=hit(marker);att={'id':aid}
if point=='after_staging':check(sql("SELECT count(*) FROM attachments WHERE id='%s'"%uid(aid))=='0','precommit row exists')
else:
check(sql("SELECT status FROM outbox WHERE job_id=(SELECT id FROM attachment_jobs WHERE attachment_id='%s')"%uid(aid))=='pending','COMMIT/publish window not reached')
compose('start','dispatcher');ready(c,bob,att,(ROOT/'tests/fixtures/sample.png').read_bytes())
wait(lambda:health(c));return {'attachment_id':aid,'accepted_commit':point=='after_upload_commit'}
record('api_crash_'+point,run,api_crash)
payload={'date_utc':datetime.datetime.now(datetime.timezone.utc).isoformat(),'commit':subprocess.check_output(['git','rev-parse','HEAD'],cwd=ROOT,text=True).strip(),'working_tree':'implementation changes uncommitted','repeats':args.repeats,'worker':{'concurrency':2,'prefetch':2,'timeout_seconds':5,'lease_seconds':8,'memory':'1GiB','cpus':1},'results':RESULTS}
check(bool(RESULTS),'no scenarios selected')
payload['image_id']=subprocess.check_output(['docker','image','inspect','mtusi-messenger:lab6','--format','{{.Id}}'],text=True).strip()
(ROOT/args.output).write_text(json.dumps(payload,ensure_ascii=False,indent=2)+'\n')
finally:
for f in FAULTS.iterdir():f.unlink()
compose('stop','worker','dispatcher',allow_failure=True)
# Restore standard configuration, disabling fault injection and short experiment leases.
subprocess.run([str(ROOT/'scripts/compose.sh'),'up','-d','--wait','--wait-timeout','120'],cwd=ROOT,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,timeout=180)
def health(c):
try:c.call('GET','/health/ready',schema='Health');return True
except Failure:return False
if __name__=='__main__':main()
+62
View File
@@ -0,0 +1,62 @@
#!/usr/bin/env python3
"""Staging protection, retirement, retention and explicit restoration on synthetic data."""
import json
from pathlib import Path
import sys
import time
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'tests'))
from client import Client,check
BASE=[str(ROOT/'scripts/compose.sh')]
import subprocess
def command(*args,fail=False):
r=subprocess.run(BASE+list(args),stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True,timeout=120)
if not fail:check(r.returncode==0,'storage scenario infrastructure command failed: '+args[0])
return r
def sql(q):return command('exec','-T','postgres','psql','-U','messenger','-d','messenger','-At','-v','ON_ERROR_STOP=1','-c',q).stdout.strip()
def op(*args,fail=False):return command('run','--rm','--no-deps','-T','operator',*args,fail=fail)
def wait(fn):
deadline=time.monotonic()+20
while time.monotonic()<deadline:
if fn():return
time.sleep(.1)
raise AssertionError('storage condition timed out')
def exists(key):return json.loads(op('storage','object-check','--key',key).stdout)['exists']
def main():
c=Client('http://localhost:18086');alice,bob,eve,chat=c.bootstrap();results=[]
try:
command('stop','worker')
att,data=c.attachment(alice,chat);key='staging/'+att['id']
check(exists(key),'accepted source missing')
result=json.loads(op('storage','reconcile','--apply').stdout)
check(result['referenced_objects']>0 and exists(key),'reconciliation removed active source')
results.append({'scenario':'queued_staging_protected','result':'PASS','attachment_id':att['id']})
command('start','worker');c.wait_ready(bob,att)
wait(lambda:sql("SELECT staging_key FROM attachments WHERE id='%s'"%att['id'])=='')
check(not exists(key),'ready source staging not retired')
results.append({'scenario':'staging_deleted_after_ready','result':'PASS','attachment_id':att['id']})
command('stop','worker')
failed,data=c.attachment(alice,chat);key='staging/'+failed['id'];jid=sql("SELECT id FROM attachment_jobs WHERE attachment_id='%s'"%failed['id'])
op('storage','remove-object','--id',failed['id']);command('start','worker')
def is_failed():return c.call('GET','/api/v1/attachments/'+failed['id'],actor=bob,schema='Attachment')['json']['status']=='failed'
wait(is_failed)
check(sql("SELECT error_code FROM attachment_jobs WHERE id='%s'"%jid)=='source_missing','missing source not permanent')
check(op('jobs','replay','--id',jid,fail=True).returncode!=0,'replay accepted missing source')
op('storage','restore','--id',failed['id'],'--source','/fixtures/sample.png')
check(exists(key),'restored source missing')
# Advance only the synthetic record's age; do not wait a real day or change production retention.
sql("UPDATE attachments SET updated_at=clock_timestamp()-interval '25 hours' WHERE id='%s'"%failed['id'])
wait(lambda:sql("SELECT staging_key FROM attachments WHERE id='%s'"%failed['id'])=='')
check(not exists(key),'expired failed source not retired')
check(op('jobs','replay','--id',jid,fail=True).returncode!=0,'replay accepted retired source')
results.append({'scenario':'failed_retention_and_missing_source_replay','result':'PASS','age_simulated_hours':25})
op('storage','restore','--id',failed['id'],'--source','/fixtures/sample.png');op('jobs','replay','--id',jid);c.wait_ready(bob,failed)
check(c.call('GET','/api/v1/attachments/'+failed['id']+'/content',actor=bob)['bytes']==data,'restored original changed')
results.append({'scenario':'verified_restore_then_replay','result':'PASS','job_id':jid})
(ROOT/'evidence/storage.json').write_text(json.dumps({'results':results},indent=2)+'\n')
print('PASS: active source protected, ready staging removed, failed retention enforced, restore/replay verified')
finally:command('start','worker')
if __name__=='__main__':main()