lab4 done

This commit is contained in:
Khakimov Dmitrij
2026-10-28 22:41:10 +03:00
parent a7bedda183
commit dbc700fafe
75 changed files with 5611 additions and 227 deletions
+9 -4
View File
@@ -1,14 +1,19 @@
# Проверки базы из lab3
# Собственные проверки lab4
Эти проверки перенесены вместе с реализацией lab3. Они не подтверждают критерии оценки lab4.
Публичные HTTP-проверки используют текущий контракт lab4 и требуют реализации вложений.
`make test-lab4` проверяет реальные PNG/JPEG, лимиты, MIME, повреждения, права, приватность bucket и отказы.
Тест останавливает именно API-реплику, которая приняла файл, и проверяет скачивание через другую.
`make measure-uploads` запускает десять клиентов на двух размерах PNG и сохраняет замеры cgroup memory.
`make test-reconcile` внедряет ошибки S3/БД и проверяет grace, блокировки, dry-run, повторное исправление и стоимость обхода.
Эти сценарии используют реальный MinIO. Запускайте их последовательно на учебном Swarm-стенде.
Результаты находятся в `evidence/lab4-*`. Подробная методика приведена в [REPORT.md](../../REPORT.md).
Публичные 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 и LB; volumes/secrets сохраняются.
- `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-*`.
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

+116
View File
@@ -0,0 +1,116 @@
"""Local lab4 experiment helpers. Never print credentials or session tokens."""
import json
import os
from pathlib import Path
import random
import struct
import subprocess
import sys
import time
import uuid
import zlib
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')
MC = os.environ.get('S3_CLIENT_IMAGE', 'mtusi-mc:RELEASE.2025-08-13T08-35-41Z')
def docker(*args, data=None, check_result=True):
return subprocess.run(['docker', *args], input=data, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, check=check_result)
def containers(service):
ids = docker('ps', '--filter', 'label=com.docker.swarm.service.name='+STACK+'_'+service,
'--format', '{{.ID}}').stdout.decode().split()
check(bool(ids), 'no container for '+service)
return ids
def sql(statement):
result = docker('exec', '-i', containers('postgres')[0], 'psql', '-U', 'messenger',
'-d', 'messenger', '-At', '-v', 'ON_ERROR_STOP=1', data=statement.encode())
return result.stdout.decode().strip()
def reconcile(apply=False, grace='90s'):
args = ['exec', containers('api')[0], '/usr/local/bin/reconcile', '--grace='+grace]
if apply:
args.append('--apply')
return json.loads(docker(*args).stdout)
def upload(c, actor, chat, content, filename='sample.png', mime='image/png', expected=201):
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)
def png(width=320, height=200, noisy=False):
def chunk(kind, body):
return struct.pack('>I', len(body))+kind+body+struct.pack('>I', zlib.crc32(kind+body))
rng = random.Random(419)
lines = b''.join(b'\0'+(rng.randbytes(width*3) if noisy else b'\x18\x60\xc0'*width)
for _ in range(height))
return (b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR', struct.pack('>IIBBBBB', width, height, 8, 2, 0, 0, 0))
+chunk(b'IDAT', zlib.compress(lines))+chunk(b'IEND', b''))
def oversized_dimensions():
body = struct.pack('>IIBBBBB', 10000, 4001, 8, 2, 0, 0, 0)
return b'\x89PNG\r\n\x1a\n'+struct.pack('>I', len(body))+b'IHDR'+body+struct.pack('>I', zlib.crc32(b'IHDR'+body))
def save(name, result):
(ROOT / 'evidence').mkdir(exist_ok=True)
(ROOT / 'evidence' / name).write_text(json.dumps(result, indent=2, ensure_ascii=False)+'\n')
def wait_ready(timeout=90):
deadline = time.monotonic()+timeout
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')
class Probe:
"""Short-lived mc service; root secrets remain inside Docker secrets."""
def __enter__(self):
self.name = STACK+'_probe_'+uuid.uuid4().hex[:8]
args = ['service', 'create', '--detach', '--no-resolve-image', '--name', self.name, '--network', STACK+'_data',
'--restart-condition', 'none', '--limit-memory', '512m', '--limit-cpu', '0.5',
'--entrypoint', '/bin/sh']
for secret in ('s3_root_access_key', 's3_root_secret_key', 's3_access_key', 's3_secret_key'):
args += ['--secret', 'source='+STACK+'_'+secret+',target='+secret]
docker(*args, MC, '-c', 'sleep 3600')
deadline = time.monotonic()+45
while time.monotonic() < deadline:
ids = docker('ps', '--filter', 'label=com.docker.swarm.service.name='+self.name, '-q').stdout.decode().split()
if ids:
self.container = ids[0]
return self
time.sleep(.3)
docker('service', 'rm', self.name, check_result=False)
raise AssertionError('probe did not start')
def mc(self, *args, data=None, admin=False, expected=0):
access = 's3_root_access_key' if admin else 's3_access_key'
secret = 's3_root_secret_key' if admin else 's3_secret_key'
script = ('set -eu; export MC_CONFIG_DIR=/tmp/mc; '
'mc alias set local http://minio:9000 "$(cat /run/secrets/'+access+')" '
'"$(cat /run/secrets/'+secret+')" >/dev/null; exec mc "$@"')
result = docker('exec', '-i', self.container, '/bin/sh', '-c', script, 'sh', *args,
data=data, check_result=False)
check((result.returncode == 0) == (expected == 0), 'unexpected mc outcome: '+args[0])
return result
def __exit__(self, *args):
docker('service', 'rm', self.name, check_result=False)
+154
View File
@@ -0,0 +1,154 @@
#!/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()
+137
View File
@@ -0,0 +1,137 @@
#!/usr/bin/env python3
"""Track2: actual DB/S3 failures, grace, locking, repeat repairs and scan cost."""
import json
import subprocess
import time
import uuid
from helpers import Client, Probe, ROOT, STACK, check, containers, docker, png, reconcile, save, sql, upload, wait_ready
def objects(probe):
raw = probe.mc('ls','--recursive','--json','local/attachments',admin=True).stdout.decode()
return {json.loads(line)['key'] for line in raw.splitlines() if json.loads(line).get('type')=='file'}
def main():
c = Client(timeout=55)
alice,bob,_,chat = c.bootstrap()
data = png()
experiment = uuid.uuid4().hex
result = {'hypothesis':'fixed grace plus per-object transaction lock permits repeatable repair without deleting fresh or linked data',
'grace_seconds':90, 'faults':{}, 'cost':[]}
with Probe() as probe:
# Inject a failure exactly between successful S3 PUT and PostgreSQL INSERT.
before = objects(probe)
filename = 'db-fault-'+experiment+'.png'
sql("CREATE FUNCTION lab4_inject_failure() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.filename='"+filename+"' THEN RAISE EXCEPTION 'lab4 injected DB failure'; END IF; RETURN NEW; END; $$; CREATE TRIGGER lab4_inject_failure BEFORE INSERT ON attachments FOR EACH ROW EXECUTE FUNCTION lab4_inject_failure();")
try:
upload(c,alice,chat,data,filename=filename,expected=503)
finally:
sql('DROP TRIGGER lab4_inject_failure ON attachments; DROP FUNCTION lab4_inject_failure();')
orphans = objects(probe)-before
check(len(orphans)==1,'DB failure did not leave the expected one unconfirmed S3 object')
orphan = next(iter(orphans))
check(sql("SELECT count(*) FROM attachments WHERE filename='"+filename+"';")=='0','failed metadata INSERT published a row')
born = time.monotonic()
result['faults']['s3_put_db_insert_failure'] = {'upload_status':503, 'objects_without_metadata':1}
fresh = reconcile(apply=True)
check(orphan in objects(probe),'fresh orphan removed before grace')
result['fresh_orphan_preserved'] = fresh['fresh_skipped']>0
# Keep one old linked object and remove a second original behind PostgreSQL.
live = upload(c,alice,chat,data)['json']
c.message(alice,chat,'keep live original',attachments=[live['id']])
missing = upload(c,alice,chat,data)['json']
message = c.message(alice,chat,'keep missing reference',attachments=[missing['id']])['json']
missing_key = sql("SELECT object_key FROM attachments WHERE id='"+missing['id']+"';")
probe.mc('rm','local/attachments/'+missing_key,admin=True)
current = reconcile(apply=True)
check(sql("SELECT status FROM attachments WHERE id='"+missing['id']+"';")=='ready','fresh metadata changed before grace')
result['fresh_metadata_preserved'] = current['fresh_skipped']>0
# Measure a real scan at two bucket sizes, crossing an S3 page boundary.
cost_prefix = 'original/cost-'+experiment+'/'
try:
for group,count,total in (('small',100,100),('extra',1000,1100)):
script = ('mkdir -p /tmp/cost/"$1"; i=1; while [ "$i" -le "$2" ]; do '
'printf x > /tmp/cost/"$1"/"$i"; i=$((i+1)); done')
docker('exec',probe.container,'/bin/sh','-c',script,'sh',group,str(count))
probe.mc('mirror','--quiet','/tmp/cost/'+group,'local/attachments/'+cost_prefix+group,admin=True)
summary = reconcile()
check(summary['objects_scanned']>=total,'scan skipped S3 objects')
result['cost'].append({'phase':'fresh', 'synthetic_objects':total, **summary})
print('Fresh scan cost:',json.dumps({k:summary[k] for k in ('objects_scanned','metadata_scanned','list_requests_estimate','stat_requests','db_queries','duration_ms')}),flush=True)
print('Waiting92s for actual S3 timestamps: measuring aged-object locking, DB and HEAD cost next.',flush=True)
time.sleep(92)
for total in (1100,100):
summary = reconcile()
check(summary['orphans']>=total,'aged scan did not inspect all orphan fixtures')
result['cost'].append({'phase':'aged', 'synthetic_objects':total, **summary})
print('Aged scan cost:',json.dumps({k:summary[k] for k in ('objects_scanned','metadata_scanned','list_requests_estimate','stat_requests','db_queries','duration_ms')}),flush=True)
if total==1100:
probe.mc('rm','--recursive','--force','local/attachments/'+cost_prefix+'extra/',admin=True)
finally:
probe.mc('rm','--recursive','--force','local/attachments/'+cost_prefix,admin=True)
# S3/DB unavailability must stop reconciliation without destructive guesses.
for service in ('minio','postgres'):
try:
docker('service','scale','--detach',STACK+'_'+service+'=0')
deadline=time.monotonic()+30
while time.monotonic()<deadline:
if not docker('ps','--filter','label=com.docker.swarm.service.name='+STACK+'_'+service,'-q').stdout.strip():
break
time.sleep(.3)
failed = docker('exec',containers('api')[0],'/usr/local/bin/reconcile','--apply','--grace=90s','--timeout=10s',check_result=False)
check(failed.returncode!=0,'reconciler succeeded with unavailable '+service)
result['faults'][service+'_unavailable'] = {'exit_nonzero':True, 'summary':json.loads(failed.stdout)}
finally:
docker('service','scale','--detach',STACK+'_'+service+'=1')
wait_ready()
check(orphan in objects(probe),'reconciler removed orphan while a store was unavailable')
remaining=92-(time.monotonic()-born)
if remaining>0:
print('Waiting for actual S3 object age to exceed90s grace:',round(remaining,1),'seconds',flush=True)
time.sleep(remaining)
sql("UPDATE attachments SET created_at=clock_timestamp()-interval '10 minutes' WHERE id IN ('"+live['id']+"','"+missing['id']+"');")
# A second process holds the upload lock: even an old orphan is protected.
lock_script = "BEGIN; SELECT pg_advisory_xact_lock(hashtextextended('"+orphan+"',0));\n"
lock = subprocess.Popen(['docker','exec','-i',containers('postgres')[0],'psql','-U','messenger','-d','messenger','-At','-v','ON_ERROR_STOP=1'],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
lock.stdin.write(lock_script.encode()); lock.stdin.flush()
try:
deadline = time.monotonic()+10
while sql("SELECT pg_try_advisory_xact_lock(hashtextextended('"+orphan+"',0));") != 'f':
check(time.monotonic()<deadline,'lock fixture did not acquire advisory lock')
time.sleep(.1)
locked = reconcile(apply=True)
check(locked['locked_skipped']>=1 and orphan in objects(probe),'upload lock did not protect orphan')
finally:
lock.stdin.write(b'ROLLBACK;\n'); lock.stdin.close()
lock.wait(timeout=15)
result['locked_candidate_preserved'] = True
# The apply above may mark the aged missing row; restore only its internal state
# to compare the following dry-run with an unchanged, well-defined fixture.
sql("UPDATE attachments SET status='ready',error_code=NULL WHERE id='"+missing['id']+"';")
dry = reconcile()
check(dry['orphans']>=1 and dry['missing']>=1,'dry-run did not detect injected inconsistencies')
check(orphan in objects(probe),'dry-run deleted an object')
check(sql("SELECT status FROM attachments WHERE id='"+missing['id']+"';")=='ready','dry-run modified metadata')
applied = reconcile(apply=True)
check(orphan not in objects(probe),'apply did not delete old orphan')
check(sql("SELECT status FROM attachments WHERE id='"+missing['id']+"';")=='failed','missing original not marked failed')
check(sql("SELECT count(*) FROM messages WHERE id='"+message['id']+"' AND '"+missing['id']+"'::uuid=ANY(attachment_ids);")=='1','repair deleted linked metadata or reference')
c.call('GET','/api/v1/attachments/'+missing['id'],409,actor=alice)
check(c.call('GET','/api/v1/attachments/'+live['id']+'/content',actor=bob)['bytes']==data,'repair deleted a live linked original')
repeated = reconcile(apply=True)
check(repeated['deleted']==0 and repeated['marked_failed']==0,'repeat apply was not idempotent')
result.update({'dry_run':dry, 'apply':applied, 'repeat_apply':repeated,
'live_linked_preserved':True, 'missing_linked_reference_preserved':True})
save('lab4-reconciliation.json',result)
print('PASS: real two-store faults, grace, lock, dry-run/apply/repeat, linked data preserved and paginated scan cost.')
if __name__=='__main__':
main()