Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
286 lines
20 KiB
Python
286 lines
20 KiB
Python
#!/usr/bin/env python3
|
||
"""Сквозная проверка pipeline lab5 (уровни 3–4) и эксперимент трека 2 «доказанная идемпотентность».
|
||
|
||
Гипотеза: при at-least-once доставке, дублях, перестановке сообщений, падениях до/после побочного
|
||
эффекта и устаревшей job после новой версии ни одна принятая (202) работа не теряется, на ключ эффекта
|
||
(attachment_id, pipeline_version, variant) приходится ровно один результат, а указатель версии не откатывается.
|
||
|
||
Сценарии (FAULT_INJECTION=1 включает точки сбоя по префиксу имени файла fault-<point>, каждая — один раз):
|
||
A worker остановлен → upload 202, content 409, сообщение с вложением 201 → рестарт API и брокера → worker → ready;
|
||
B падения: relay до publish (разрыв COMMIT/publish), relay после publish до удаления outbox (дубль),
|
||
worker после захвата (до эффекта), после записи в S3 до COMMIT, после COMMIT до ack; временная ошибка до
|
||
исчерпания попыток (backoff+jitter → failed) и replay; постоянная ошибка (arithmetic JPEG);
|
||
C устаревшая job: v1 медленная (40 с перед COMMIT), v2 (jobctl reprocess) фиксируется раньше; дубли v1 во время и после обработки;
|
||
затем инварианты по БД, S3 и API.
|
||
|
||
Запуск из корня репозитория при работающем стенде (docker compose из этого каталога; для другого проекта —
|
||
COMPOSE_PROJECT_NAME/COMPOSE_FILE):
|
||
python3 tests/pipeline_experiment.py --output evidence/pipeline_experiment.json
|
||
Скрипт пересоздаёт api-1, api-2 и worker с FAULT_INJECTION=1 и арендой 6 с, в конце возвращает обычный режим.
|
||
"""
|
||
import hashlib
|
||
import json
|
||
import os
|
||
import re
|
||
import struct
|
||
import subprocess
|
||
import time
|
||
from pathlib import Path
|
||
from client import ROOT, Client, arguments, check, run
|
||
from image_probe import jpeg_size
|
||
|
||
PNG = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||
BUCKET = 'messenger-attachments'
|
||
LEASE = 6
|
||
FAULT_ENV = {'FAULT_INJECTION': '1', 'JOB_LEASE_SECONDS': str(LEASE)}
|
||
CRASHES = ['crash-before-publish', 'crash-after-publish', 'crash-after-claim', 'crash-after-s3', 'crash-after-commit']
|
||
|
||
|
||
def compose(*args, env=None, stdin=None):
|
||
p = subprocess.run(['docker', 'compose', *args], cwd=ROOT, input=stdin, capture_output=True, text=True, env={**os.environ, **(env or {})})
|
||
check(p.returncode == 0, 'docker compose %s failed: %s' % (' '.join(args[:2]), p.stderr[-400:]))
|
||
return p.stdout
|
||
|
||
|
||
def sql(query):
|
||
return compose('exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-At', '-F', '|', '-c', query).strip()
|
||
|
||
|
||
def rows(query):
|
||
out = sql(query)
|
||
return [line.split('|') for line in out.split('\n')] if out else []
|
||
|
||
|
||
def queue():
|
||
out = compose('exec', '-T', 'rabbitmq', 'rabbitmqctl', '-q', 'list_queues', 'name', 'messages')
|
||
return {k: int(v) for k, v in (line.split('\t') for line in out.strip().split('\n') if '\t' in line and not line.startswith('name'))}
|
||
|
||
|
||
def s3(commands):
|
||
# Подписанные запросы ключами API из контейнера s3-probe; ключи передаются curl через stdin.
|
||
script = ('sign() { printf \'user = "%s:%s"\\n\' "$(cat /run/secrets/s3.access-key)" "$(cat /run/secrets/s3.secret-key)"; }\n'
|
||
'url=http://s3:8333/' + BUCKET + '\n' + '\n'.join(commands) + '\n')
|
||
return compose('run', '--rm', '-T', 's3-probe', stdin=script)
|
||
|
||
|
||
def s3_keys(prefix):
|
||
return re.findall(r'<Key>([^<]+)</Key>', s3(['sign | curl -K - -s --aws-sigv4 aws:amz:us-east-1:s3 "$url?list-type=2&prefix=%s"' % prefix]))
|
||
|
||
|
||
def s3_sha256(keys):
|
||
out = s3(['echo "%s $(sign | curl -K - -s --aws-sigv4 aws:amz:us-east-1:s3 "$url/%s" | sha256sum | cut -d" " -f1)"' % (k, k) for k in keys])
|
||
return dict(line.split(' ') for line in out.strip().split('\n') if line)
|
||
|
||
|
||
def jobctl(*args):
|
||
out = compose('run', '--rm', '-T', 'jobctl', *args)
|
||
return json.loads(out[out.index('{'):])
|
||
|
||
|
||
def arithmetic_jpeg():
|
||
# Структурно корректный JPEG (SOF9, arithmetic coding): API принимает, ImageIO декодировать не умеет.
|
||
seg = lambda marker, body: b'\xff' + bytes([marker]) + struct.pack('>H', len(body) + 2) + body
|
||
return (b'\xff\xd8' + seg(0xC9, struct.pack('>BHHB', 8, 16, 16, 1) + b'\x01\x11\x00')
|
||
+ seg(0xDA, b'\x01\x01\x00\x00\x3f\x00') + b'\x00' * 32 + b'\xff\xd9')
|
||
|
||
|
||
def wait_until(what, condition, timeout):
|
||
deadline = time.monotonic() + timeout
|
||
while time.monotonic() < deadline:
|
||
try:
|
||
value = condition()
|
||
if value:
|
||
return value
|
||
except Exception:
|
||
pass # API-реплика или брокер перезапускаются после внедрённого падения
|
||
time.sleep(0.5)
|
||
check(False, 'timeout waiting for ' + what)
|
||
|
||
|
||
def events(job):
|
||
return [(int(a), e, d) for a, e, d in rows("select attempt,event,coalesce(detail,'') from job_audit where job_id='%s' order by id" % job)]
|
||
|
||
|
||
def invariants(ids, invalid_id):
|
||
in_list = ','.join("'%s'" % i for i in ids)
|
||
jobs_of = 'select job_id from jobs where attachment_id in (%s)' % in_list
|
||
states = dict(rows('select id,state from attachments where id in (%s)' % in_list))
|
||
check(all(states[i] == 'ready' for i in ids if i != invalid_id) and states[invalid_id] == 'failed', 'I1: accepted work lost or stuck: %s' % states)
|
||
effects = rows('select attachment_id,pipeline_version,count(*) from attachment_variants where attachment_id in (%s) group by 1,2' % in_list)
|
||
check(all(int(n) == 3 for _, _, n in effects), 'I2: effect key has not exactly 3 variants')
|
||
db_sha = dict(rows('select object_key,sha256 from attachment_variants where attachment_id in (%s)' % in_list))
|
||
s3_variants = sorted(k for i in ids for k in s3_keys('variants/' + i + '/'))
|
||
check(s3_variants == sorted(db_sha), 'I2: S3 variant objects differ from DB rows')
|
||
s3_sha = s3_sha256(sorted(db_sha))
|
||
check(s3_sha == db_sha, 'I3: S3 bytes differ from committed checksums')
|
||
# I4: каждое done-задание зафиксировано ровно один раз, failed — ни разу; после done захватов нет.
|
||
commits = rows("select j.state,count(a.*) filter (where a.event='done') from jobs j left join job_audit a on a.job_id=j.job_id where j.job_id in (%s) group by j.job_id,j.state" % jobs_of)
|
||
check(all(int(n) == (1 if s == 'done' else 0) for s, n in commits), 'I4: a job was committed more than once (or failed job committed): %s' % commits)
|
||
after_done = sql("select count(*) from job_audit a join job_audit d on d.job_id=a.job_id and d.event='done' and a.event='claimed' and a.id>d.id where a.job_id in (%s)" % jobs_of)
|
||
check(after_done == '0', 'I4: a done job was claimed again')
|
||
# I5: staging ready-вложений удалён (сразу после COMMIT или sweepStaging), failed хранится до retention.
|
||
ready_ids = {i for i in ids if states[i] == 'ready'}
|
||
staging = wait_until('staging cleanup', lambda: (lambda left: {'staging_left_for_run': sorted(left & set(ids))} if not left & ready_ids else None)(
|
||
{k.split('/')[1] for k in s3_keys('staging/')}), 90)
|
||
duplicates = dict(rows("select event,count(*) from job_audit where event in ('duplicate_done','duplicate_in_progress','stale_attempt') and job_id in (%s) group by 1" % jobs_of))
|
||
result = {'I1_no_lost_accepted_work': states, 'I2_variants_per_effect_key': {'%s/v%s' % (a, v): int(n) for a, v, n in effects},
|
||
'I2_s3_variant_objects': len(s3_variants), 'I3_checksums_equal': len(s3_sha),
|
||
'I4_commits_per_job': sorted(int(n) for _, n in commits), 'I5_staging': staging,
|
||
'duplicates_dropped': {k: int(v) for k, v in duplicates.items()}, 'result': 'PASS'}
|
||
print('PASS invariants: %d attachments final, %d variant objects = DB rows, checksums equal, every done job committed once, dropped %s'
|
||
% (len(ids), len(s3_variants), result['duplicates_dropped']))
|
||
return result
|
||
|
||
|
||
def main():
|
||
def configure(p):
|
||
p.add_argument('--output', default=None)
|
||
args = arguments('Lab5 pipeline end-to-end checks and track-2 idempotency experiment', configure)
|
||
c = Client(args.base_url, args.ca_file, timeout=20)
|
||
started = time.monotonic()
|
||
compose('up', '-d', '--wait', 'api-1', 'api-2', 'worker', env=FAULT_ENV)
|
||
alice, bob, eve, chat = c.bootstrap()
|
||
report = {'experiment': 'lab5 pipeline: grade 3/4 scenarios and track 2 idempotency', 'lease_seconds': LEASE, 'scenarios': {}}
|
||
|
||
def upload(name, data=PNG, ctype='image/png'):
|
||
att = c.call('POST', '/api/v1/chats/%s/attachments?filename=%s' % (chat['id'], name), 202, actor=alice, raw=data,
|
||
headers={'Content-Type': ctype}, schema='Attachment')['json']
|
||
check(att['status'] == 'queued' and att['variants'] == [] and att['error_code'] is None, 'upload must return a queued snapshot')
|
||
return att
|
||
|
||
def meta(att):
|
||
return c.call('GET', '/api/v1/attachments/' + att['id'], actor=bob, schema='Attachment')['json']
|
||
|
||
def final(att, timeout=120):
|
||
return wait_until('final state of ' + att['filename'], lambda: (lambda m: m if m['status'] in ('ready', 'failed') else None)(meta(att)), timeout)
|
||
|
||
def job_of(att, version=1):
|
||
return sql("select job_id from jobs where attachment_id='%s' and pipeline_version=%d" % (att['id'], version))
|
||
|
||
# A. Worker остановлен: приём не зависит от worker, задание переживает рестарт API и брокера.
|
||
t0 = time.monotonic()
|
||
# Сначала очередь пуста (worker разобрал прежнее); счётчик list_queues у quorum-очереди обновляется
|
||
# с задержкой до ~5 с, поэтому пустоту подтверждаем двумя чтениями с паузой.
|
||
empty = lambda: queue().get('attachments.process', 1) == 0
|
||
wait_until('queue drained', lambda: empty() and (time.sleep(6) or empty()), 120)
|
||
compose('stop', 'worker')
|
||
demo = upload('demo.png')
|
||
for suffix in ('/content', '/content?variant=thumbnail'):
|
||
c.call('GET', '/api/v1/attachments/%s%s' % (demo['id'], suffix), 409, actor=bob)
|
||
linked = c.message(alice, chat, '', attachments=[demo['id']])['json']
|
||
c.message(bob, chat, 'worker остановлен, текст идёт')
|
||
depth = lambda least: (lambda q: q if q.get('attachments.process', 0) >= least else None)(queue())
|
||
depth_before = wait_until('job message in broker', lambda: depth(1), 30)
|
||
compose('restart', 'api-1', 'api-2', 'rabbitmq')
|
||
# После рестарта quorum-очередь сначала выбирает лидера; ждём, пока она снова покажет сообщение.
|
||
depth_after = wait_until('queued job after broker restart', lambda: depth(1), 90)
|
||
wait_until('API after restart', lambda: c.call('GET', '/health/ready', schema='Health'), 90)
|
||
check(meta(demo)['status'] == 'queued', 'attachment must stay queued while worker is down')
|
||
compose('start', 'worker')
|
||
ready = final(demo)
|
||
check(ready['status'] == 'ready' and ready['error_code'] is None, 'demo attachment did not become ready')
|
||
got = {v: c.call('GET', '/api/v1/attachments/%s/content?variant=%s' % (demo['id'], v), actor=bob) for v in ('original', 'thumbnail', 'crop', 'optimized')}
|
||
check(got['original']['bytes'] == PNG, 'original changed')
|
||
variants = {v['name']: v for v in ready['variants']}
|
||
check(sorted(variants) == ['crop', 'optimized', 'thumbnail'], 'expected thumbnail, crop, optimized')
|
||
check(jpeg_size(got['thumbnail']['bytes']) == (256, 160) and jpeg_size(got['crop']['bytes']) == (128, 128), 'JPEG variant dimensions')
|
||
check(got['optimized']['bytes'][:4] == b'RIFF' and got['optimized']['bytes'][8:12] == b'WEBP', 'optimized is not WebP')
|
||
check((variants['optimized']['width'], variants['optimized']['height']) == (320, 200), 'optimized must not upscale 320x200')
|
||
for v in ('thumbnail', 'crop', 'optimized'):
|
||
check(hashlib.sha256(got[v]['bytes']).hexdigest() == variants[v]['sha256'], 'variant checksum mismatch: ' + v)
|
||
report['scenarios']['A_worker_down_restart'] = {
|
||
'attachment_id': demo['id'], 'job_id': job_of(demo), 'message_id': linked['id'],
|
||
'queue_before_restart': depth_before, 'queue_after_restart': depth_after,
|
||
'content_while_queued': 409, 'seconds': round(time.monotonic() - t0, 1), 'result': 'PASS'}
|
||
print('PASS A: worker down -> 202/409/message 201 -> API+broker restart keeps job -> worker -> ready')
|
||
|
||
# B. Падения в окнах отказа, временная и постоянная ошибки. Relay работает и в API-репликах:
|
||
# его падение роняет реплику, поэтому эти два сценария идут по одному, остальные — параллельно.
|
||
t0 = time.monotonic()
|
||
crash = {}
|
||
for p in CRASHES[:2]:
|
||
crash[p] = upload('fault-%s.png' % p)
|
||
final(crash[p], 180)
|
||
wait_until('API after relay crash', lambda: c.call('GET', '/health/ready', schema='Health'), 90)
|
||
crash.update({p: upload('fault-%s.png' % p) for p in CRASHES[2:]})
|
||
transient = upload('fault-transient.png')
|
||
invalid = upload('arith.jpg', arithmetic_jpeg(), 'image/jpeg')
|
||
# Перестановка: устаревшее сообщение attempt=1, когда задание уже на attempt≥2.
|
||
tjob = job_of(transient)
|
||
wait_until('transient job retry', lambda: int(sql("select attempt from jobs where job_id='%s'" % tjob)) >= 2, 240)
|
||
sql("insert into outbox(job_id,attempt) values('%s',1)" % tjob)
|
||
results = {p: final(a, 300) for p, a in crash.items()}
|
||
bad = final(invalid)
|
||
exhausted = final(transient, 300)
|
||
check(all(r['status'] == 'ready' for r in results.values()), 'crash scenario did not reach ready: %s' % {p: r['status'] for p, r in results.items()})
|
||
check(bad['status'] == 'failed' and bad['error_code'] == 'invalid_image', 'arithmetic JPEG must fail with invalid_image')
|
||
check(exhausted['status'] == 'failed' and exhausted['error_code'] == 'retry_exhausted', 'transient job must end with retry_exhausted')
|
||
c.call('GET', '/api/v1/attachments/%s/content' % bad['id'], 409, actor=bob)
|
||
c.call('POST', '/api/v1/chats/%s/messages' % chat['id'], 409, actor=alice, body={'text': '', 'attachment_ids': [bad['id']]},
|
||
headers={'Idempotency-Key': 'failed-' + bad['id']})
|
||
fired = sorted(r[0] for r in rows('select point from fault_marks'))
|
||
check(all(p in fired for p in CRASHES), 'not all crash points fired: %s' % fired)
|
||
per = {p: events(job_of(a)) for p, a in crash.items()}
|
||
check(any(e == 'lease_expired' for _, e, _ in per['crash-after-claim']), 'crash before effect: lease did not expire')
|
||
check(any(e == 'lease_expired' for _, e, _ in per['crash-after-s3']), 'crash after S3 write: lease did not expire')
|
||
check([a for a, e, _ in per['crash-after-commit'] if e == 'done'] == [1] and any(e == 'duplicate_done' for _, e, _ in per['crash-after-commit']),
|
||
'crash after commit: redelivery must be a no-op')
|
||
check(any(e.startswith('duplicate') or e == 'stale_attempt' for _, e, _ in per['crash-after-publish']), 'duplicate publish not observed')
|
||
tev = events(tjob)
|
||
delays = [int(re.search(r'delay_ms=(\d+)', d).group(1)) for _, e, d in tev if e == 'retry_scheduled']
|
||
check(len(delays) == 4 and [a for a, e, _ in tev if e == 'claimed'] == [1, 2, 3, 4, 5], 'transient job: expected 5 attempts, 4 backoffs')
|
||
check(any(e == 'stale_attempt' for _, e, _ in tev), 'stale attempt=1 message was not dropped')
|
||
check(sum(e == 'failed' for _, e, _ in events(job_of(invalid))) == 1 and not any(e == 'retry_scheduled' for _, e, _ in events(job_of(invalid))),
|
||
'permanent error must not be retried')
|
||
# Replay: failed → queued (новая попытка того же job_id); повтор replay и replay done-задания — no-op.
|
||
replay = jobctl('replay', tjob, job_of(crash['crash-after-commit']))
|
||
replayed = final(transient, 60)
|
||
check(replayed['status'] == 'ready', 'replayed job did not become ready')
|
||
again = jobctl('replay', tjob)
|
||
check(again[tjob].startswith('skipped') and replay[job_of(crash['crash-after-commit'])].startswith('skipped'), 'replay of done job must be skipped')
|
||
report['scenarios']['B_faults'] = {
|
||
'fired_points': fired,
|
||
'audit': {p: [list(e) for e in v] for p, v in per.items()},
|
||
'transient': {'job_id': tjob, 'backoff_delays_ms': delays, 'audit': [list(e) for e in events(tjob)], 'replay': replay, 'replay_again': again},
|
||
'invalid_image': {'job_id': job_of(invalid), 'audit': [list(e) for e in events(job_of(invalid))]},
|
||
'seconds': round(time.monotonic() - t0, 1), 'result': 'PASS'}
|
||
print('PASS B: crash windows recovered, duplicates dropped, backoff %s ms -> retry_exhausted -> replay -> ready, invalid_image not retried' % delays)
|
||
|
||
# C. Устаревшая job после новой версии + дубли во время и после обработки.
|
||
t0 = time.monotonic()
|
||
slow = upload('fault-slow.png')
|
||
v1 = job_of(slow)
|
||
wait_until('v1 claimed', lambda: sql("select state from jobs where job_id='%s'" % v1) == 'processing', 30)
|
||
created = jobctl('reprocess', '--pipeline-version=2', slow['id'])
|
||
for _ in range(3):
|
||
sql("insert into outbox(job_id,attempt) values('%s',1)" % v1)
|
||
wait_until('v1 done', lambda: sql("select state from jobs where job_id='%s'" % v1) == 'done', 90)
|
||
for _ in range(2):
|
||
sql("insert into outbox(job_id,attempt) values('%s',1)" % v1)
|
||
time.sleep(3)
|
||
m = meta(slow)
|
||
v2 = job_of(slow, 2)
|
||
v1_events, v2_events = events(v1), events(v2)
|
||
check(sql("select pipeline_version from attachments where id='%s'" % slow['id']) == '2', 'stale v1 job rolled back the version pointer')
|
||
check(('superseded' in [d for _, e, d in v1_events if e == 'done']), 'v1 must be committed as superseded after v2')
|
||
v2_rows = {r[0]: r[1] for r in rows("select name,sha256 from attachment_variants where attachment_id='%s' and pipeline_version=2" % slow['id'])}
|
||
check({v['name']: v['sha256'] for v in m['variants']} == v2_rows and len(v2_rows) == 3, 'API must serve v2 variants')
|
||
check(sum(e == 'duplicate_in_progress' for _, e, _ in v1_events) >= 1 and sum(e == 'duplicate_done' for _, e, _ in v1_events) >= 2, 'duplicates of v1 were not dropped')
|
||
report['scenarios']['C_stale_version'] = {'attachment_id': slow['id'], 'v1_job': v1, 'v2_job': v2, 'reprocess': created,
|
||
'v1_audit': [list(e) for e in v1_events], 'v2_audit': [list(e) for e in v2_events],
|
||
'pointer': 2, 'seconds': round(time.monotonic() - t0, 1), 'result': 'PASS'}
|
||
print('PASS C: v2 committed first, late v1 committed as superseded, pointer stays 2, duplicates dropped')
|
||
|
||
# Инварианты по всем вложениям прогона.
|
||
ids = [demo['id'], slow['id'], transient['id'], invalid['id']] + [a['id'] for a in crash.values()]
|
||
report['invariants'] = invariants(ids, invalid['id'])
|
||
report['seconds_total'] = round(time.monotonic() - started, 1)
|
||
compose('up', '-d', '--wait', 'api-1', 'api-2', 'worker')
|
||
if args.output:
|
||
Path(args.output).parent.mkdir(parents=True, exist_ok=True)
|
||
Path(args.output).write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n')
|
||
|
||
|
||
if __name__ == '__main__':
|
||
run(main)
|