lab5 done

This commit is contained in:
Khakimov Dmitrij
2026-11-10 22:13:40 +03:00
parent b2bd7501d3
commit cbe9d8748c
63 changed files with 8907 additions and 307 deletions
+17 -17
View File
@@ -1,20 +1,20 @@
# Собственные проверки lab4
# Проверки lab5
`make test-lab4` проверяет реальные PNG/JPEG, лимиты, MIME, повреждения, права, приватность bucket и отказы.
Тест останавливает именно API-реплику, которая приняла файл, и проверяет скачивание через другую.
`make measure-uploads` запускает десять клиентов на двух размерах PNG и сохраняет замеры cgroup memory.
`make test-reconcile` внедряет ошибки S3/БД и проверяет grace, блокировки, dry-run, повторное исправление и стоимость обхода.
Эти сценарии используют реальный MinIO. Запускайте их последовательно на учебном Swarm-стенде.
`make test` запускает неизменённый публичный smoke lab5.
`make test-own` запускает Go-тесты с race detector.
`make test-integration` проверяет реальные миграции, транзакции, гонки, пагинацию, fencing и версии.
`make test-lab5` проверяет реальные Redis Streams, MinIO и PostgreSQL.
Сценарий проверяет границы staging/COMMIT/publish/objects/COMMIT/ack и восстановление после остановки компонентов.
Он проверяет retry, failed registry, audit replay, process timeout и cleanup.
Проверки JPEG/WebP, EXIF, alpha и малых изображений используют Pillow из `requirements-research.txt`.
Сценарии изменяют только свой стек и синтетические данные.
Запускайте проверки отказов последовательно.
Результаты находятся в `evidence/lab4-*`. Подробная методика приведена в [REPORT.md](../../REPORT.md).
`make test-lab4` и `make test-reconcile` оставлены как совместимые имена для полного `test-lab5`.
Старые `reconcile.py` и `grade4.py` сохраняют исторические сценарии; напрямую их не запускайте.
`make test-persistence` проверяет общий restart; `make test-failover` проверяет остановку одной API-реплики.
Публичные tests/*.py и обязательный контракт сохранены.
- `make test-own`: Go tests с race detector. Без INTEGRATION_TESTS=1 PostgreSQL-сценарий пропускается.
- `make test-integration`: отдельный Swarm job, Go 1.26.4 и goose. Временная схема, миграции с нуля/повторно/legacy/reset/up, регистрационная гонка, rollback, 10 000 сообщений с одинаковыми timestamps, EXPLAIN и 16 конкурентных запросов одного ключа.
- `make test-grade4`: `swarm_grade4.py`, ровно две API tasks. Проверяет общий ключ через LB, одинаковый результат, 409, границы ключа, область пользователя/чата, права и logout. По очереди останавливает обе исходные tasks с восстановлением, затем выполняет rolling update под нагрузкой. Проверяет историю, отсутствие дублей и повтор исходного ключа после воздействия. Сохраняет `evidence/swarm-grade4.json`.
- `make test-persistence`: перезапуск всех API, PostgreSQL, Redis, MinIO и LB; volumes/secrets сохраняются.
- `make test-failover ACTION_SCRIPT=scripts/stop-one.sh`: публичный сценарий отказа; `make wait` дожидается восстановления двух реплик.
- `make measure-load`: 3s прогрева + 30s, concurrency 4, метрики и Docker stats в `evidence/swarm-*`.
Сценарии отказов, persistence и rolling update выполняйте **последовательно**, на локальном учебном стенде. Все данные синтетические; пароль и токены в результаты не записываются. Старый `grade4.py` относится к Compose-стенду lab2 и не является entrypoint текущей работы.
`make benchmark` измеряет очередь под перегрузкой для трёх настроек и двух размеров изображений.
`make plot-research` строит графики по фактическому JSON.
Методика и результаты находятся в [RESEARCH.md](../../RESEARCH.md).
Новые доказательства используют имена `evidence/lab5-*`; исходные lab4 evidence считаются историческими.
+21 -8
View File
@@ -14,7 +14,7 @@ ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, check
STACK = os.environ.get('STACK_NAME', 'mtusi-lab4')
STACK = os.environ.get('STACK_NAME', 'mtusi-lab5')
MC = os.environ.get('S3_CLIENT_IMAGE', 'mtusi-mc:RELEASE.2025-08-13T08-35-41Z')
@@ -43,11 +43,11 @@ def reconcile(apply=False, grace='90s'):
return json.loads(docker(*args).stdout)
def upload(c, actor, chat, content, filename='sample.png', mime='image/png', expected=201):
def upload(c, actor, chat, content, filename='sample.png', mime='image/png', expected=202):
from urllib.parse import quote
return c.call('POST', '/api/v1/chats/'+chat['id']+'/attachments?filename='+quote(filename, safe=''),
expected, actor=actor, raw=content, headers={'Content-Type': mime},
schema='Attachment' if expected == 201 else None)
schema='Attachment' if expected == 202 else None)
def png(width=320, height=200, noisy=False):
@@ -72,13 +72,26 @@ def save(name, result):
def wait_ready(timeout=90):
deadline = time.monotonic()+timeout
stable_since = None
previous = None
while time.monotonic() < deadline:
try:
Client(timeout=2).call('GET', '/health/ready', schema='Health')
return
except AssertionError:
time.sleep(.5)
raise AssertionError('readiness did not recover')
ids=docker('service','ps','--filter','desired-state=running','-q',STACK+'_api').stdout.decode().split()
wanted=json.loads(docker('service','inspect',STACK+'_api').stdout)[0]['Spec']['Mode']['Replicated']['Replicas']
check(wanted>0 and len(ids)==wanted,'API count')
ts=json.loads(docker('inspect',*ids).stdout)
check(all(t['Status']['State']=='running' for t in ts),'API task state')
cs=json.loads(docker('inspect',*[t['Status']['ContainerStatus']['ContainerID'] for t in ts]).stdout)
check(all(c['State'].get('Health',{}).get('Status')=='healthy' for c in cs),'API health')
Client(timeout=2).call('GET','/health/ready',schema='Health')
current=frozenset(ids)
if current!=previous: stable_since=time.monotonic()
previous=current
if stable_since is not None and time.monotonic()-stable_since>=5:return
except (AssertionError,subprocess.CalledProcessError,KeyError):
stable_since=None;previous=None
time.sleep(.5)
raise AssertionError('all API replicas and LB did not stabilize')
class Probe:
-154
View File
@@ -1,154 +0,0 @@
#!/usr/bin/env python3
"""Real S3/API negative cases and failures; only synthetic lab data."""
import hashlib
import http.client
import json
import os
from pathlib import Path
import subprocess
import time
import uuid
from urllib.parse import urlsplit
from helpers import Client, Probe, ROOT, STACK, check, containers, docker, png, oversized_dimensions, save, sql, upload, wait_ready
def main():
c = Client(timeout=55)
alice, bob, eve, chat = c.bootstrap()
data = png()
result = {'negative_cases': [], 'failures': {}, 'checksums': {}}
for name, body, mime, filename, status in (
('oversized_bytes', b'x'*(10*1024*1024+1), 'image/png', 'large.png', 413),
('damaged_png', data[:50], 'image/png', 'broken.png', 415),
('corrupt_crc', data[:-16]+b'\xff'*16, 'image/png', 'crc.png', 415),
('mime_spoof', data, 'image/jpeg', 'fake.jpg', 415),
('not_image', b'plain text', 'image/png', 'fake.png', 415),
('unsupported_mime', data, 'application/octet-stream', 'file.png', 415),
('pixel_budget', oversized_dimensions(), 'image/png', 'large-dimensions.png', 413),
('unsafe_slash', data, 'image/png', '../file.png', 400),
('unsafe_backslash', data, 'image/png', 'x\\y.png', 400),
('unsafe_control', data, 'image/png', 'x\x00.png', 400),
('empty_filename', data, 'image/png', '', 400),
):
upload(c, alice, chat, body, filename, mime, status)
result['negative_cases'].append({'case': name, 'status': status})
for content, filename, mime in ((data, 'изображение.png', 'image/png'),
((ROOT/'tests/own/fixtures/sample.jpg').read_bytes(), 'photo.jpg', 'image/jpeg')):
att = upload(c, alice, chat, content, filename, mime)['json']
downloaded = c.call('GET', '/api/v1/attachments/'+att['id']+'/content', actor=bob)
check(downloaded['bytes'] == content, 'original bytes changed')
check(att['sha256'] == hashlib.sha256(content).hexdigest(), 'incorrect SHA256')
check(downloaded['headers'].get_content_type() == mime, 'incorrect content MIME')
result['checksums'][mime] = att['sha256']
att = upload(c, alice, chat, data)['json']
for suffix in ('', '/content'):
c.call('GET', '/api/v1/attachments/'+att['id']+suffix, 404, actor=eve)
c.call('GET', '/api/v1/attachments/'+str(uuid.uuid4())+suffix, 404, actor=alice)
c.call('GET', '/api/v1/attachments/'+att['id']+suffix, 401)
upload(c, eve, chat, data, expected=404)
c.call('GET', '/api/v1/attachments/'+att['id']+'/content?variant=thumbnail', 404, actor=bob)
other = c.call('POST', '/api/v1/chats', 201, actor=alice,
body={'title':'other chat', 'member_ids':[alice['id'], bob['id']]}, schema='Chat')['json']
path = '/api/v1/chats/'+other['id']+'/messages'
for ids, status in (([att['id']], 404), ([str(uuid.uuid4())], 404), ([att['id'],att['id']], 400)):
c.call('POST', path, status, actor=alice, body={'text':'', 'attachment_ids':ids},
headers={'Idempotency-Key':uuid.uuid4().hex})
result['negative_cases'] += [{'case': x, 'status': s} for x,s in (
('foreign_attachment',404), ('foreign_chat_link',404), ('unknown_attachment',404),
('duplicate_ids',400), ('missing_authentication',401), ('unknown_variant',404))]
# The proxy must stop oversized chunked bodies even without Content-Length.
address = urlsplit(c.base)
conn = http.client.HTTPConnection(address.hostname, address.port, timeout=55)
conn.request('POST', '/api/v1/chats/'+chat['id']+'/attachments?filename=chunked.png',
body=iter([b'x'*65536]*161), encode_chunked=True,
headers={'Authorization':'Bearer '+alice['token'], 'Content-Type':'image/png'})
response = conn.getresponse()
check(response.status == 413, 'chunked upload bypassed byte limit')
response.read(); conn.close()
result['negative_cases'].append({'case':'chunked_oversized', 'status':413})
# Disconnect halfway through the declared body. No object/metadata can be published.
before = int(sql('SELECT count(*) FROM attachments;'))
conn = http.client.HTTPConnection(address.hostname, address.port, timeout=5)
conn.putrequest('POST', '/api/v1/chats/'+chat['id']+'/attachments?filename=aborted.png')
conn.putheader('Authorization', 'Bearer '+alice['token'])
conn.putheader('Content-Type', 'image/png')
conn.putheader('Content-Length', str(len(data)+10000))
conn.endheaders(); conn.send(data[:40]); conn.close()
time.sleep(1)
check(int(sql('SELECT count(*) FROM attachments;')) == before, 'aborted upload published metadata')
leftovers = [docker('exec', container, 'find', '/tmp', '-maxdepth', '1', '-name', 'messenger-upload-*').stdout.decode()
for container in containers('api')]
check(not any(leftovers), 'aborted upload left spool files')
result['failures']['client_disconnect'] = {'metadata_added':0, 'spool_files_remaining':0}
with Probe() as probe:
key = sql("SELECT object_key FROM attachments WHERE id='"+att['id']+"';")
raw = docker('exec', containers('minio')[0], 'wget', '-S', '-O', '/dev/null',
'http://127.0.0.1:9000/attachments/'+key, check_result=False)
check(b'403' in raw.stderr, 'unauthenticated direct S3 GET was not forbidden')
probe.mc('stat', 'local/attachments/'+key)
probe.mc('mb', 'local/forbidden-'+uuid.uuid4().hex[:8], expected=1)
probe.mc('pipe', 'local/attachments/outside-prefix', data=b'x', expected=1)
result['bucket_security'] = {'anonymous_get_status':403, 'create_bucket_denied':True,
'write_outside_prefix_denied':True, 'console_published':False}
service = json.loads(docker('service', 'inspect', STACK+'_minio').stdout)[0]
check(not service['Spec'].get('EndpointSpec', {}).get('Ports'), 'MinIO publishes an external port')
for _ in range(2):
subprocess.run(['python3', str(ROOT/'scripts/swarm.py'), 'bootstrap-s3'], check=True,
stdout=subprocess.DEVNULL)
check(c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=bob)['bytes']==data,
'repeated bucket bootstrap changed data')
result['bucket_security']['bootstrap_repeats'] = 2
# Stop the replica that accepted THIS upload, then read through another one.
accepted = upload(c,alice,chat,data)
source = accepted['headers']['X-Instance-Id']
env = dict(os.environ, TARGET_INSTANCE_ID=source)
started = time.monotonic()
subprocess.run(['python3',str(ROOT/'scripts/swarm.py'),'stop-one'],env=env,check=True,
stdout=subprocess.DEVNULL)
deadline = time.monotonic()+10
while True:
try:
downloaded = Client(timeout=2).call('GET','/api/v1/attachments/'+accepted['json']['id']+'/content',actor=bob)
check(downloaded['headers']['X-Instance-Id']!=source,'stopped upload replica still serves bytes')
check(downloaded['bytes']==data,'cross-replica original changed')
break
except AssertionError:
check(time.monotonic()<deadline,'cross-replica download did not recover in10s')
time.sleep(.2)
result['failures']['upload_replica_failure'] = {'upload_instance':source,
'download_instance':downloaded['headers']['X-Instance-Id'],
'recovery_seconds':round(time.monotonic()-started,3), 'sha256':hashlib.sha256(data).hexdigest()}
subprocess.run(['python3',str(ROOT/'scripts/swarm.py'),'wait'],check=True,stdout=subprocess.DEVNULL)
# Stop only this stack's S3; /live still works, direct /ready reports503.
started = time.monotonic()
try:
docker('service','scale','--detach',STACK+'_minio=0')
deadline = time.monotonic()+30
while time.monotonic()<deadline:
stopped = docker('ps','--filter','label=com.docker.swarm.service.name='+STACK+'_minio','-q').stdout.strip()
if not stopped:
break
time.sleep(.3)
live = docker('exec',containers('api')[0],'wget','-q','-O','-','http://127.0.0.1:8080/health/live')
check(json.loads(live.stdout)['status']=='ok','S3 outage broke liveness')
ready = docker('exec',containers('api')[0],'wget','-S','-O','-','http://127.0.0.1:8080/health/ready',check_result=False)
check(b'503' in ready.stderr,'readiness ignored S3 outage')
result['failures']['s3_outage'] = {'liveness':200, 'readiness':503}
finally:
docker('service','scale','--detach',STACK+'_minio=1')
wait_ready()
check(c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=bob)['bytes']==data,
'S3 outage lost original')
result['failures']['s3_outage']['recovery_seconds'] = round(time.monotonic()-started,3)
save('lab4-acceptance.json', result)
print('PASS: PNG/JPEG, bounded uploads, MIME/damage/ACL/link errors, disconnect, private S3, repeat bootstrap, S3 outage.')
if __name__ == '__main__':
main()
+327
View File
@@ -0,0 +1,327 @@
#!/usr/bin/env python3
"""Real Redis Streams/S3/PostgreSQL fault tests; only the isolated lab5 stack."""
import hashlib
import datetime as dt
import io
import json
import os
from pathlib import Path
import subprocess
import sys
import time
import uuid
from helpers import Client, Probe, ROOT, STACK, check, containers, docker, png, oversized_dimensions, sql, upload
sys.path.insert(0, str(ROOT/'tests'))
from client import Failure
from image_probe import jpeg_size
STREAM = 'attachments:jobs:v1'
GROUP = 'image-workers-v1'
RESULT = {'stack': STACK, 'cases': {}, 'started_at': time.time()}
if '--tail-only' in sys.argv:
previous=ROOT/'evidence/lab5-faults.json'
check(previous.is_file(),'tail-only needs previously saved successful fault cases')
RESULT=json.loads(previous.read_text())
RESULT.setdefault('resumed_at',[]).append(time.time())
def save():
(ROOT/'evidence/lab5-faults.json').write_text(json.dumps(RESULT, indent=2)+'\n')
def until(operation, predicate=bool, timeout=90):
deadline = time.monotonic()+timeout
last = None
while time.monotonic() < deadline:
try:
last = operation()
if predicate(last):
return last
except (AssertionError, subprocess.CalledProcessError, KeyError, IndexError):
pass
time.sleep(.2)
raise AssertionError('condition deadline exceeded; last='+str(last))
def tasks(service):
ids = docker('service','ps','--filter','desired-state=running','-q',STACK+'_'+service).stdout.decode().split()
if not ids:
return []
return json.loads(docker('inspect',*ids).stdout)
def settled(service, count):
stable = [None, None]
def ready():
spec=json.loads(docker('service','inspect',STACK+'_'+service).stdout)[0]
check(spec.get('UpdateStatus',{}).get('State','completed')=='completed','service update not completed')
ts = tasks(service)
check(len(ts)==count, 'wrong task count')
if not count:
live=docker('ps','--filter','label=com.docker.swarm.service.name='+STACK+'_'+service,'-q').stdout.strip()
check(not live,'old worker container still running')
return True
check(all(t['Status']['State']=='running' for t in ts), 'task not running')
states = json.loads(docker('inspect',*[t['Status']['ContainerStatus']['ContainerID'] for t in ts]).stdout)
check(all(s['State'].get('Health',{}).get('Status','healthy')=='healthy' for s in states), 'unhealthy container')
if service=='api':
Client(timeout=2).call('GET','/health/ready',schema='Health')
ids = frozenset(t['ID'] for t in ts)
if ids != stable[0]:
stable[:] = [ids,time.monotonic()]
return time.monotonic()-stable[1]>=4
def observe():
try:
return ready()
except (AssertionError,subprocess.CalledProcessError,KeyError,IndexError):
stable[:]=[None,None]
raise
until(observe, timeout=120)
def control(service, values=None, replicas=None, force=False):
args = ['service','update','--detach']
for key,value in (values or {}).items():
args += ['--env-rm',key] if value is None else ['--env-add',key+'='+str(value)]
if replicas is not None:
args += ['--replicas',str(replicas)]
if force:
args += ['--force']
docker(*args,STACK+'_'+service)
if replicas is None:
spec = json.loads(docker('service','inspect',STACK+'_'+service).stdout)[0]
replicas = spec['Spec']['Mode']['Replicated']['Replicas']
settled(service,replicas)
def redis(*args):
return json.loads(docker('exec',containers('redis')[0],'redis-cli','--json',*args).stdout)
def job(att):
return json.loads(sql("SELECT row_to_json(j) FROM attachment_jobs j WHERE attachment_id='"+att['id']+"';"))
def wait_state(att, state, timeout=90):
return until(lambda: job(att), lambda j: j['state']==state, timeout)
def variant_check(c, actor, att, original, expected_thumb=(256,160)):
ready = c.wait_ready(actor,att)
check(ready['error_code'] is None, 'ready has error')
check(c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=actor)['bytes']==original,'original changed')
variants = {v['name']:v for v in ready['variants']}
check(set(variants)=={'thumbnail','crop','optimized'},'incomplete variants')
check((variants['thumbnail']['width'],variants['thumbnail']['height'])==expected_thumb,'thumbnail geometry')
check((variants['crop']['width'],variants['crop']['height'])==(128,128),'crop geometry')
for name,v in variants.items():
response = c.call('GET','/api/v1/attachments/'+att['id']+'/content?variant='+name,actor=actor)
body = response['bytes']
check(len(body)==v['size_bytes'] and hashlib.sha256(body).hexdigest()==v['sha256'],'variant checksum')
check(response['headers'].get_content_type()==v['content_type'],'variant MIME')
if name=='optimized':
check(body[:4]==b'RIFF' and body[8:12]==b'WEBP','not WebP')
else:
check(jpeg_size(body)==(v['width'],v['height']),'JPEG actual geometry')
return ready
def replay(j, expected=True):
result = docker('exec',containers('worker')[0],'/usr/local/bin/worker','--replay',j['id'],
'--operator','synthetic-fault-test','--reason','restore synthetic fixture',check_result=False)
check((result.returncode==0)==expected,'unexpected replay result')
def main():
check(STACK!='mtusi-lab4','refuse source stack')
c = Client(timeout=55)
alice,bob,eve,chat = c.bootstrap()
data = png()
# Inherited lab4 obligations remain public: input validation and access control.
negatives=[]
for name,body,mime,filename,status in (
('oversized',b'x'*(10485760+1),'image/png','large.png',413),
('damaged',data[:45],'image/png','broken.png',415),
('pixel_budget',oversized_dimensions(),'image/png','huge.png',413),
('mime_spoof',data,'image/jpeg','fake.jpg',415),
('filename',data,'image/png','../evil.png',400),
('unsupported',data,'application/octet-stream','file.png',415)):
upload(c,alice,chat,body,filename,mime,status)
negatives.append({'name':name,'status':status})
att = upload(c,alice,chat,data)['json']
variant_check(c,bob,att,data)
c.message(alice,chat,'',attachments=[att['id']])
c.call('GET','/api/v1/attachments/'+att['id'],404,actor=eve)
c.call('GET','/api/v1/attachments/'+att['id']+'/content',401)
upload(c,eve,chat,data,expected=404)
RESULT['cases']['input_and_acl'] = negatives
# Real small image, alpha and EXIF orientation exercise the actual renderer.
from PIL import Image
for name,im,exif,shape in (
('small.png',Image.new('RGBA',(12,8),(255,0,0,0)),None,(12,8)),
('oriented.jpg',Image.new('RGB',(320,200),(40,120,200)),6,(160,256)),
('oriented.png',Image.new('RGB',(320,200),(40,120,200)),6,(160,256))):
out=io.BytesIO();kwargs={}
if exif:
tags=Image.Exif();tags[274]=exif;kwargs['exif']=tags
is_jpeg=name.endswith('.jpg')
im.save(out,format='JPEG' if is_jpeg else 'PNG',**kwargs)
body=out.getvalue();item=upload(c,alice,chat,body,name,'image/jpeg' if is_jpeg else 'image/png')['json']
variant_check(c,bob,item,body,shape)
if name=='small.png':
raw=c.call('GET','/api/v1/attachments/'+item['id']+'/content?variant=thumbnail',actor=bob)['bytes']
pixel=Image.open(io.BytesIO(raw)).getpixel((0,0));check(min(pixel)>250,'alpha was not white')
RESULT['cases']['small_alpha_exif']='PASS'
print('PASS: input/ACL, three actual formats, geometry, EXIF, alpha',flush=True)
with Probe() as probe:
key=sql("SELECT object_key FROM attachments WHERE id='"+att['id']+"';")
anonymous=docker('exec',containers('minio')[0],'wget','-S','-O','/dev/null','http://127.0.0.1:9000/attachments/'+key,check_result=False)
check(b'403' in anonymous.stderr,'bucket public')
probe.mc('pipe','local/attachments/outside-prefix',data=b'x',expected=1)
RESULT['cases']['private_s3']={'anonymous_get':403,'outside_prefix_denied':True}
# A stage PUT without metadata COMMIT must never produce a 202 or a job.
until(lambda:sql("SELECT count(*) FROM attachments WHERE status='ready' AND staging_key IS NOT NULL;")=='0',timeout=45)
def stage_keys():
lines=probe.mc('ls','--recursive','--json','local/attachments/staging/').stdout.decode().splitlines()
return {json.loads(line)['key'] for line in lines if json.loads(line).get('type')=='file'}
old=stage_keys()
filename='db-fault-'+uuid.uuid4().hex+'.png'
sql("CREATE FUNCTION lab5_reject_metadata() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.filename='"+filename+"' THEN RAISE EXCEPTION 'synthetic metadata failure'; END IF; RETURN NEW; END; $$; CREATE TRIGGER lab5_reject_metadata BEFORE INSERT ON attachments FOR EACH ROW EXECUTE FUNCTION lab5_reject_metadata();")
try:
upload(c,alice,chat,data,filename=filename,expected=503)
finally:
sql('DROP TRIGGER lab5_reject_metadata ON attachments; DROP FUNCTION lab5_reject_metadata();')
unconfirmed=stage_keys()-old
check(len(unconfirmed)==1,'expected one unconfirmed stage')
check(sql("SELECT count(*) FROM attachments WHERE filename='"+filename+"';")=='0','failed upload published metadata')
orphan=next(iter(unconfirmed))
time.sleep(6)
check(orphan in stage_keys(),'fresh unconfirmed stage deleted before grace')
RESULT['cases']['stage_before_commit']={'upload_status':503,'metadata':0,'fresh_orphan_preserved':True}
if '--tail-only' not in sys.argv:
# COMMIT without publish, then API and broker restart with worker absent.
control('worker',replicas=0)
control('api',{'PIPELINE_PAUSE_PUBLISH':'1'})
item=upload(c,alice,chat,data)['json']
c.message(alice,chat,'',attachments=[item['id']])
c.call('GET','/api/v1/attachments/'+item['id']+'/content',409,actor=bob)
j=job(item)
check(sql("SELECT published_at IS NULL FROM attachment_outbox WHERE job_id='"+j['id']+"';")=='t','publish not paused')
control('api',force=True)
control('redis',force=True)
settled('api',2)
control('api',{'PIPELINE_PAUSE_PUBLISH':None})
until(lambda:sql("SELECT published_at IS NOT NULL FROM attachment_outbox WHERE job_id='"+j['id']+"';")=='t')
before=redis('XRANGE',STREAM,'-','+')
check(any(json.loads(row[1][1])['job_id']==j['id'] for row in before),'job not in stream')
control('redis',force=True)
settled('api',2)
check(any(json.loads(row[1][1])['job_id']==j['id'] for row in redis('XRANGE',STREAM,'-','+')),'broker lost durable job')
control('worker',replicas=1)
variant_check(c,bob,item,data)
RESULT['cases']['commit_publish_and_restarts']={'job_id':j['id'],'api_restart':True,'broker_restarts':2,'link_queued':True}
save();print('PASS: COMMIT/publish gap, queued link, API/broker restarts, worker recovery',flush=True)
# A killed worker leaves deterministic objects before metadata COMMIT/ack.
control('worker',{'WORKER_TIMEOUT_SECONDS':'5','WORKER_LEASE_SECONDS':'12','PIPELINE_FAILPOINT':'after_objects'})
item=upload(c,alice,chat,data)['json']
until(lambda:job(item)['state']=='processing')
until(lambda:probe.mc('stat','local/attachments/original/'+item['id']+'/v1/optimized').returncode==0)
control('worker',{'PIPELINE_FAILPOINT':None})
variant_check(c,bob,item,data)
j=job(item);check(j['attempts']>=2,'expired processing was not retried')
objects=probe.mc('ls','--recursive','--json','local/attachments/original/'+item['id']+'/').stdout.decode().splitlines()
check(sum(json.loads(x).get('type')=='file' for x in objects)==4,'duplicate objects created')
RESULT['cases']['crash_after_objects']={'attempts':j['attempts'],'objects':4,'fence':j['fence']}
save();print('PASS: crash after objects, expired lease/fencing, same four keys',flush=True)
# Ready COMMIT before ack: redelivery must leave metadata unchanged.
control('worker',{'PIPELINE_FAILPOINT':'after_commit'})
item=upload(c,alice,chat,data)['json'];wait_state(item,'ready')
snapshot=c.call('GET','/api/v1/attachments/'+item['id'],actor=bob,schema='Attachment')['json']
check(redis('XPENDING',STREAM,GROUP)[0]>0,'ack happened before crash')
control('worker',{'PIPELINE_FAILPOINT':None})
until(lambda:redis('XPENDING',STREAM,GROUP)[0]==0,timeout=30)
check(c.call('GET','/api/v1/attachments/'+item['id'],actor=bob,schema='Attachment')['json']==snapshot,'ready replay changed metadata')
j=job(item)
envelope={'schema_version':1,'job_id':j['id'],'type':'attachment.process.v1','attachment_id':item['id'],'pipeline_version':1,'attempt':1,'created_at':j['created_at']}
redis('XADD',STREAM,'*','job',json.dumps(envelope))
until(lambda:redis('XLEN',STREAM)==0,timeout=30)
check(c.call('GET','/api/v1/attachments/'+item['id'],actor=bob,schema='Attachment')['json']==snapshot,'duplicate changed ready')
replay(j,False)
RESULT['cases']['commit_before_ack_and_duplicate']={'ready_unchanged':True,'ready_replay_rejected':True}
save();print('PASS: COMMIT before ack, duplicate no-op and ready replay rejection',flush=True)
# Temporary storage error, bounded attempts/backoff, failed registry and audit replay.
control('api',{'WORKER_MAX_ATTEMPTS':'2'})
control('worker',{'PIPELINE_FAILPOINT':'transient'})
item=upload(c,alice,chat,data)['json']
retry=until(lambda:job(item),lambda j:j['state']=='queued' and j['attempts']==1)
delay=(dt.datetime.fromisoformat(retry['available_at'].replace('Z','+00:00'))-dt.datetime.fromisoformat(retry['updated_at'].replace('Z','+00:00'))).total_seconds()
check(1.5<=delay<=2.6,'retry backoff/jitter outside configured range')
failed=wait_state(item,'failed',timeout=30)
check(failed['attempts']==2,'retry limit')
meta=c.call('GET','/api/v1/attachments/'+item['id'],actor=bob,schema='Attachment')['json']
check(meta['error_code']=='retry_exhausted','unsafe final code')
c.call('GET','/api/v1/attachments/'+item['id']+'/content',409,actor=bob)
c.call('POST','/api/v1/chats/'+chat['id']+'/messages',409,actor=alice,body={'text':'','attachment_ids':[item['id']]},headers={'Idempotency-Key':uuid.uuid4().hex})
registry=json.loads(docker('exec',containers('worker')[0],'/usr/local/bin/worker','--failed').stdout)
check(any(row['job_id']==failed['id'] for row in registry),'failed registry missing')
control('worker',{'PIPELINE_FAILPOINT':None})
replay(failed)
variant_check(c,bob,item,data)
check(sql("SELECT count(*) FROM attachment_replays WHERE job_id='"+failed['id']+"';")=='1','replay audit missing')
RESULT['cases']['bounded_retry_replay']={'max_attempts':2,'retry_available_at':retry['available_at'],'first_backoff_seconds':round(delay,3),'failed_attempts':failed['attempts'],'audits':1}
save();print('PASS: bounded retry/backoff, failed registry, safe audited replay',flush=True)
# A permanently corrupted durable stage is not retried endlessly.
control('worker',replicas=0)
item=upload(c,alice,chat,data)['json']
probe.mc('pipe','local/attachments/staging/'+item['id'],data=b'damaged synthetic stage')
control('worker',replicas=1)
failed=wait_state(item,'failed')
check(failed['attempts']==1,'permanent error retried')
check(c.call('GET','/api/v1/attachments/'+item['id'],actor=bob,schema='Attachment')['json']['error_code']=='invalid_image','permanent classification')
RESULT['cases']['permanent_stage_error']={'attempts':1,'error_code':'invalid_image'}
permanent_att=item
permanent_job=failed
# Deadline kills the renderer AND its real cwebp child blocked on a FIFO.
control('api',{'WORKER_MAX_ATTEMPTS':'1'})
control('worker',{'WORKER_TIMEOUT_SECONDS':'2','WORKER_LEASE_SECONDS':'7','PIPELINE_FAILPOINT':'renderer_timeout'})
item=upload(c,alice,chat,data)['json'];started=time.monotonic()
seen=until(lambda:docker('exec',containers('worker')[0],'ps','-o','pid,args').stdout.decode(),lambda text:'cwebp -quiet' in text,timeout=10)
wait_state(item,'failed',timeout=15)
elapsed=time.monotonic()-started
processes=docker('exec',containers('worker')[0],'ps','-o','pid,args').stdout.decode()
check('cwebp -quiet' not in processes and '/worker render' not in processes,'renderer descendant survived timeout')
RESULT['cases']['renderer_process_group_timeout']={'deadline_seconds':2,'elapsed_seconds':round(elapsed,3),'cwebp_observed':True,'descendants_after_failure':0}
control('worker',{'PIPELINE_FAILPOINT':None,'WORKER_TIMEOUT_SECONDS':'25','WORKER_LEASE_SECONDS':'40'})
control('api',{'WORKER_MAX_ATTEMPTS':None})
# Every ready stage is eventually collected; linked final objects remain.
until(lambda:sql("SELECT count(*) FROM attachments WHERE status='ready' AND staging_key IS NOT NULL;")=='0',timeout=45)
check(c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=bob)['bytes']==data,'cleanup removed ready original')
sql("UPDATE attachments SET created_at=created_at-interval '8 days',updated_at=clock_timestamp()-interval '8 days' WHERE id='"+permanent_att['id']+"';")
until(lambda:sql("SELECT storage_cleaned_at IS NOT NULL AND staging_key IS NULL FROM attachments WHERE id='"+permanent_att['id']+"';")=='t',timeout=45)
replay(permanent_job,False)
until(lambda:orphan not in stage_keys(),timeout=100)
RESULT['cases']['staging_cleanup']={'ready_stages_remaining':0,'linked_original_preserved':True,'failed_retention_days':7,'expired_failed_stage_removed':True,'expired_replay_rejected':True,'unconfirmed_orphan_removed':True}
required={'input_and_acl','small_alpha_exif','private_s3','stage_before_commit','commit_publish_and_restarts','crash_after_objects','commit_before_ack_and_duplicate','bounded_retry_replay','permanent_stage_error','renderer_process_group_timeout','staging_cleanup'}
check(required.issubset(RESULT['cases']),'incomplete fault evidence')
RESULT['finished_at']=time.time();save()
print('PASS: all lab5 fault, retry, replay, durability, rendering and cleanup checks',flush=True)
if __name__=='__main__':
try:
main()
finally:
# Restore ordinary service configuration even if an assertion fails.
try:
control('worker',{'PIPELINE_FAILPOINT':None,'WORKER_TIMEOUT_SECONDS':'25','WORKER_LEASE_SECONDS':'40'},replicas=1)
control('api',{'WORKER_MAX_ATTEMPTS':None,'PIPELINE_PAUSE_PUBLISH':None})
finally:
save()
+1 -1
View File
@@ -15,7 +15,7 @@ sys.path.insert(0, str(ROOT/'tests'))
from client import Client, Failure, check, run
from resilience import history
STACK = os.environ.get('STACK_NAME', 'mtusi-lab4')
STACK = os.environ.get('STACK_NAME', 'mtusi-lab5')
def docker_json(*args):