Apply completed lab 6 implementation

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
HellsTomato
2026-10-31 01:46:08 +03:00
co-authored by Copilot
parent 470d9d6f1e
commit f2b4d77be4
50 changed files with 7983 additions and 15 deletions
+224
View File
@@ -0,0 +1,224 @@
#!/usr/bin/env python3
"""Собственные проверки вложений (с lab4; в lab5 upload → 202 queued), только стандартная библиотека.
Покрывают: слишком большой файл, повреждённые PNG/JPEG, подмену MIME, decompression bomb,
опасные filename, чужое/неизвестное attachment_id, вложение другого чата, постороннего пользователя,
идемпотентность с вложениями. Ни одна пользовательская ошибка не должна давать 500.
--with-docker дополнительно (через docker compose из корня репозитория):
* останавливает S3: загрузка/скачивание -> 503, текстовые сообщения и /health/ready работают,
неудачная загрузка не оставляет строк в БД;
* останавливает API-реплику, принявшую загрузку, и скачивает файл через другую.
Синтетический fixture tests/fixtures/sample.jpg получен из sample.png (sips, quality 85).
"""
import json
import os
import struct
import subprocess
import time
import urllib.error
import urllib.request
import uuid
import zlib
from urllib.parse import quote
from client import ROOT, Client, arguments, check, run
PNG = (ROOT / 'tests/fixtures/sample.png').read_bytes()
JPEG = (ROOT / 'tests/fixtures/sample.jpg').read_bytes()
MIB = 1024 * 1024
def png(width, height, idat=None, depth=8, color=2):
def chunk(kind, data):
return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data))
if idat is None:
row = b'\x00' + bytes(width * 3)
idat = zlib.compress(row * height, 9)
return (b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', width, height, depth, color, 0, 0, 0))
+ chunk(b'IDAT', idat) + chunk(b'IEND', b''))
def flip(data, at):
return data[:at] + bytes([data[at] ^ 0xff]) + data[at + 1:]
def compose(*args, check_rc=True):
return subprocess.run(['docker', 'compose', *args], cwd=ROOT, check=check_rc, capture_output=True, text=True).stdout
def sql(query):
return compose('exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-At', '-c', query).strip()
def main():
def configure(p):
p.add_argument('--with-docker', action='store_true', help='also stop S3 and the uploading replica via docker compose')
args = arguments('Negative attachment checks for lab4; creates synthetic data', configure)
c = Client(args.base_url, args.ca_file, timeout=20)
alice, bob, eve, chat = c.bootstrap()
other = c.call('POST', '/api/v1/chats', 201, actor=alice, body={'title': 'Другой чат', 'member_ids': [alice['id'], eve['id']]}, schema='Chat')['json']
passed = []
def upload(data, ctype='image/png', expected=202, actor=alice, target=chat, name='file.png'):
r = c.call('POST', '/api/v1/chats/%s/attachments?filename=%s' % (target['id'], quote(name, safe='')), expected,
actor=actor, raw=data, headers={'Content-Type': ctype}, schema='Attachment' if expected == 202 else None)
if expected >= 400:
check(r['json']['error']['code'] != 'internal_error', 'user error turned into 500')
return r
def ok(name):
passed.append(name)
print('PASS', name)
# Валидные форматы и побайтовое скачивание.
att_png = c.wait_ready(bob, upload(PNG)['json'])
att_jpg = c.wait_ready(bob, upload(JPEG, 'image/jpeg', name='photo.jpg')['json'])
check(att_jpg['content_type'] == 'image/jpeg' and att_jpg['status'] == 'ready', 'jpeg metadata')
for att, data, ctype in ((att_png, PNG, 'image/png'), (att_jpg, JPEG, 'image/jpeg')):
got = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=bob)
check(got['bytes'] == data and got['headers'].get_content_type() == ctype, 'download differs')
ok('valid PNG and JPEG upload/download byte-for-byte')
# Размер: API отклоняет 10 MiB + 1 байт, nginx — всё больше 11 MiB, оба JSON 413.
upload(PNG[:8] + bytes(10 * MIB + 1 - 8), expected=413)
req = urllib.request.Request(c.base + '/api/v1/chats/%s/attachments?filename=big.png' % chat['id'], data=bytes(12 * MIB), method='POST',
headers={'Authorization': 'Bearer ' + alice['token'], 'Content-Type': 'image/png'})
try:
urllib.request.urlopen(req, timeout=20)
check(False, 'oversized body accepted')
except urllib.error.HTTPError as e:
body = json.loads(e.read())
check(e.code == 413 and body['error']['code'] == 'payload_too_large' and e.headers.get('X-Request-Id'), 'nginx 413 must be contract JSON')
# Почти 10 MiB: случайные пиксели не сжимаются; у каждой строки байт фильтра 0.
big = png(1800, 1900, idat=zlib.compress(b''.join(b'\x00' + os.urandom(1800 * 3) for _ in range(1900)), 1))
check(len(big) <= 10 * MIB, 'fixture too large')
upload(big)
ok('10 MiB + 1 byte -> 413 (API), 12 MiB -> 413 JSON (nginx), valid %.1f MiB accepted' % (len(big) / MIB))
# Повреждённые изображения.
idat_at = PNG.find(b'IDAT') + 8
for broken in (flip(PNG, idat_at), PNG[:len(PNG) // 2], PNG + b'trailing', PNG[:8] + b'garbage' * 10):
upload(broken, expected=415)
for broken in (JPEG[:len(JPEG) // 2], JPEG[:4] + b'\x00' * 100, JPEG[:2] + b'\xff\xda\x00\x02' + JPEG[2:]):
upload(broken, 'image/jpeg', expected=415)
ok('corrupted/truncated PNG and JPEG -> 415')
# Подмена MIME: проверяется содержимое, а не заголовок.
upload(PNG, 'image/jpeg', expected=415)
upload(JPEG, 'image/png', expected=415)
upload(b'GIF89a' + bytes(100), 'image/png', expected=415)
upload(b'<svg xmlns="http://www.w3.org/2000/svg"/>', 'image/png', expected=415)
upload(PNG, 'text/plain', expected=415)
upload(PNG, 'image/gif', expected=415)
ok('MIME spoofing (content vs Content-Type) -> 415')
# Decompression bomb: заголовок > 40 Мпикс -> 413 до распаковки; ложный маленький заголовок -> 415;
# честные 36 Мпикс (≈108 МБ пикселей) принимаются без декодирования в RAM.
upload(png(10000, 10000, idat=zlib.compress(bytes(1000))), expected=413)
upload(png(100, 100, idat=zlib.compress(bytes(50 * MIB), 9)), expected=415)
upload(png(6000, 6000))
ok('decompression bomb: >40 MP -> 413, lying header -> 415, honest 36 MP accepted')
# filename: только отображение; пути, NUL, управляющие символы и длина — 400.
for name in ('../evil.png', 'a/b.png', 'a\\b.png', 'a\x00b.png', 'a\x07b.png', 'line\nbreak.png', ' ', '..', 'x' * 256):
upload(PNG, name=name, expected=400)
c.call('POST', '/api/v1/chats/%s/attachments' % chat['id'], 400, actor=alice, raw=PNG, headers={'Content-Type': 'image/png'})
for name in ('фото 😀.png', '😀' * 255):
got = upload(PNG, name=name)['json']
check(got['filename'] == name, 'filename changed')
ok('dangerous filenames -> 400, Unicode up to 255 code points preserved')
# Доступ: посторонний не загружает и не читает, без сессии — 401, неизвестный id — 404.
upload(PNG, actor=eve, expected=404)
for suffix in ('', '/content'):
c.call('GET', '/api/v1/attachments/' + att_png['id'] + suffix, 404, actor=eve)
c.call('GET', '/api/v1/attachments/' + str(uuid.uuid4()) + suffix, 404, actor=alice)
c.call('GET', '/api/v1/attachments/not-a-uuid', 400, actor=alice)
c.call('POST', '/api/v1/chats/%s/attachments?filename=a.png' % chat['id'], 401, raw=PNG, headers={'Content-Type': 'image/png'})
ok('outsider/unknown attachment -> 404, no session -> 401')
# attachment_ids в сообщении.
path = '/api/v1/chats/%s/messages' % chat['id']
foreign = upload(PNG, target=other)['json']
def send(body, expected=201, key=None):
return c.call('POST', path, expected, actor=alice, body=body, headers={'Idempotency-Key': key or uuid.uuid4().hex},
schema='Message' if expected == 201 else None)
send({'text': 'чужое', 'attachment_ids': [foreign['id']]}, 404)
send({'text': 'неизвестное', 'attachment_ids': [str(uuid.uuid4())]}, 404)
send({'text': 'смесь', 'attachment_ids': [att_png['id'], foreign['id']]}, 404)
for bad in (['not-a-uuid'], [att_png['id'], att_png['id']], [str(uuid.uuid4()) for _ in range(11)], None, att_png['id'], [1]):
send({'text': 'x', 'attachment_ids': bad}, 400)
send({'text': ''}, 400)
send({'text': '', 'attachment_ids': []}, 400)
send({'text': ' ', 'attachment_ids': [att_png['id']]}, 400)
two = send({'text': '', 'attachment_ids': [att_jpg['id'], att_png['id']]})['json']
check(two['attachment_ids'] == [att_jpg['id'], att_png['id']] and two['text'] == '', 'attachment order or text changed')
history = c.call('GET', path + '?limit=100', actor=bob, schema='MessagePage')['json']['items']
check(any(m == two for m in history), 'history lost attachment_ids')
ok('foreign/unknown attachment -> 404, malformed attachment_ids -> 400, order preserved')
# Идемпотентность: отсутствующий attachment_ids == [], другой набор с тем же ключом — 409.
key = uuid.uuid4().hex
first = send({'text': 'ключ'}, key=key)['json']
check(send({'attachment_ids': [], 'text': 'ключ'}, key=key)['json'] == first, 'missing vs [] must be equal')
send({'text': 'ключ', 'attachment_ids': [att_png['id']]}, 409, key=key)
key = uuid.uuid4().hex
first = send({'text': 'с файлом', 'attachment_ids': [att_png['id']]}, key=key)['json']
check(send({'text': 'с файлом', 'attachment_ids': [att_png['id']]}, key=key)['json'] == first, 'replay with attachment differs')
send({'text': 'с файлом', 'attachment_ids': [att_jpg['id']]}, 409, key=key)
ok('idempotency with attachment_ids (missing == [], different set -> 409)')
# Варианты lab5: thumbnail/crop JPEG, optimized WebP; мусорное имя — 400.
types = {'original': 'image/png', 'thumbnail': 'image/jpeg', 'crop': 'image/jpeg', 'optimized': 'image/webp'}
for name, ctype in types.items():
got = c.call('GET', '/api/v1/attachments/%s/content?variant=%s' % (att_png['id'], name), actor=bob)
check(got['headers'].get_content_type() == ctype, 'variant %s has wrong content type' % name)
c.call('GET', '/api/v1/attachments/%s/content?variant=../../etc' % att_png['id'], 400, actor=bob)
ok('variants: original/thumbnail/crop/optimized 200 with own types, garbage 400')
if args.with_docker:
# Недоступный S3: вложения 503, текстовый путь живёт, после сбоя нет зависших строк.
compose('stop', 's3')
try:
rows_before = sql('select count(*) from attachments')
r = upload(PNG, expected=503)
check(r['json']['error']['code'] == 'unavailable', 'S3 outage must be 503 unavailable')
c.call('GET', '/api/v1/attachments/' + att_png['id'] + '/content', 503, actor=bob)
c.call('GET', '/api/v1/attachments/' + att_png['id'], actor=bob, schema='Attachment')
send({'text': 'S3 лежит, текст идёт'})
c.call('GET', '/health/ready', schema='Health')
check(sql('select count(*) from attachments') == rows_before, 'failed upload left a row')
finally:
compose('start', 's3')
deadline = time.monotonic() + 60
while True:
try:
got = c.call('GET', '/api/v1/attachments/' + att_png['id'] + '/content', actor=bob)
break
except AssertionError:
check(time.monotonic() < deadline, 'downloads did not recover after S3 start')
time.sleep(1)
check(got['bytes'] == PNG, 'download after S3 recovery differs')
ok('S3 down: attachments 503, messages/ready OK, no rows left; recovered after start')
# Остановка реплики, принявшей загрузку: другая скачивает тот же файл.
r = upload(PNG)
served = r['headers']['X-Instance-Id']
c.wait_ready(bob, r['json'])
cid = [x for x in compose('ps', '-q', 'api-1', 'api-2').split() if x.startswith(served)]
check(len(cid) == 1, 'cannot map X-Instance-Id to a container')
subprocess.run(['docker', 'stop', cid[0]], check=True, capture_output=True)
try:
for _ in range(5):
got = c.call('GET', '/api/v1/attachments/' + r['json']['id'] + '/content', actor=bob)
check(got['bytes'] == PNG and got['headers']['X-Instance-Id'] != served, 'download through other replica failed')
finally:
subprocess.run(['docker', 'start', cid[0]], check=True, capture_output=True)
ok('upload replica %s stopped: other replica serves identical bytes' % served)
print('PASS: %d attachment checks' % len(passed))
if __name__ == '__main__':
run(main)
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

+408
View File
@@ -0,0 +1,408 @@
#!/usr/bin/env python3
"""Lab6 experiments on a running stack: `slo` (track 2: burn-rate alerts vs a spike, a long degradation and
an outage) and `incidents` (level 4: worker stop, slow DB, telemetry backends down). Reads telemetry through
the Grafana datasource proxy (admin password from secrets/, never printed); drives faults with docker compose,
so run it with the same COMPOSE_PROJECT_NAME/COMPOSE_FILE as the stack. `traces` (level 3/4 trace+log correlation,
upload chain with one retry, leak check) and `slo` need FAULT_INJECTION=1."""
import argparse
import base64
import json
import subprocess
import threading
import time
import urllib.parse
import urllib.request
from client import ROOT, Client, Failure, check, run
T0 = time.monotonic()
def now():
return round(time.monotonic() - T0, 1)
class Grafana:
def __init__(self, url):
password = (ROOT / 'secrets/grafana_admin_password').read_text().strip()
self.url = url.rstrip('/')
self.auth = 'Basic ' + base64.b64encode(('admin:' + password).encode()).decode()
def get(self, path):
req = urllib.request.Request(self.url + path, headers={'Authorization': self.auth})
with urllib.request.urlopen(req, timeout=20) as r:
return json.loads(r.read())
def prom(self, query):
return self.get('/api/datasources/proxy/uid/prometheus/api/v1/query?query=' + urllib.parse.quote(query))['data']['result']
def value(self, query):
result = self.prom(query)
return round(float(result[0]['value'][1]), 4) if result else None
def alerts(self):
data = self.get('/api/datasources/proxy/uid/prometheus/api/v1/alerts')['data']['alerts']
return {a['labels']['alertname']: a['state'] for a in data}
class AlertLog(threading.Thread):
"""Polls Prometheus alert states every 2 s and keeps transitions with experiment-relative time."""
def __init__(self, grafana):
super().__init__(daemon=True)
self.grafana, self.state, self.events, self.stop = grafana, {}, [], threading.Event()
def run(self):
while not self.stop.is_set():
try:
current = self.grafana.alerts()
except OSError:
current = self.state
for name in set(current) | set(self.state):
old, new = self.state.get(name, 'inactive'), current.get(name, 'inactive')
if old != new:
self.events.append({'t': now(), 'alert': name, 'from': old, 'to': new})
self.state = current
self.stop.wait(2)
def intervals(self, name):
"""Firing intervals [start, end) of one alert; end None = still firing."""
out, start = [], None
for e in self.events:
if e['alert'] != name:
continue
if e['to'] == 'firing':
start = e['t']
elif e['from'] == 'firing' and start is not None:
out.append([start, e['t']])
start = None
if start is not None:
out.append([start, None])
return out
class Load:
"""Paced POST-message load: `rps` total; share `fault` of requests carries X-Fault-Inject: http-500."""
def __init__(self, base_url, rps, threads=5):
self.client = Client(base_url)
self.alice, _, _, self.chat = self.client.bootstrap()
self.fault, self.phase, self.stop = 0.0, 'warmup', threading.Event()
self.counts, self.lock = {}, threading.Lock()
self.interval = threads / rps
self.threads = [threading.Thread(target=self.worker, args=(Client(base_url, timeout=5),), daemon=True) for _ in range(threads)]
def start(self):
for t in self.threads:
t.start()
def worker(self, client):
due, debt, n = time.monotonic(), 0.0, 0
path = '/api/v1/chats/' + self.chat['id'] + '/messages'
while not self.stop.is_set():
debt += self.fault
inject = debt >= 1
if inject:
debt -= 1
headers = {'Idempotency-Key': 'obs-%d-%d-%f' % (id(client), n, time.time())}
if inject:
headers['X-Fault-Inject'] = 'http-500'
try:
status = client.call('POST', path, [201, 500], body={'text': 'obs %d' % n}, actor=self.alice, headers=headers)['status']
outcome = 'injected_500' if status == 500 and inject else ('ok' if status == 201 else 'unexpected_500')
except Failure:
outcome = 'failed'
with self.lock:
bucket = self.counts.setdefault(self.phase, {})
bucket[outcome] = bucket.get(outcome, 0) + 1
n += 1
due += self.interval
time.sleep(max(0.0, due - time.monotonic()))
def compose(*args, check_rc=True):
return subprocess.run(['docker', 'compose', *args], cwd=ROOT, capture_output=True, text=True, check=check_rc).stdout
def slo(args):
g = Grafana(args.grafana_url)
probe = Client(args.base_url)
a, _, _, chat = probe.bootstrap()
status = probe.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', [201, 500], body={'text': 'probe'}, actor=a,
headers={'Idempotency-Key': 'probe-%f' % time.time(), 'X-Fault-Inject': 'http-500'})['status']
check(status == 500, 'fault injection is off: start the stack with FAULT_INJECTION=1')
check(wait_alerts(g, list(g.alerts()), False, 600) is not None, 'alerts still active before the experiment')
phases = [('baseline', args.baseline, 0.0), ('spike', args.spike, 1.0), ('after_spike', args.quiet, 0.0),
('degradation', args.degradation, args.degradation_ratio), ('after_degradation', args.quiet + 30, 0.0),
('outage', args.outage, 1.0), ('after_outage', args.quiet, 0.0)]
load = Load(args.base_url, args.rps)
watcher = AlertLog(g)
load.start()
watcher.start()
timeline, samples = [], []
for name, seconds, ratio in phases:
load.phase, load.fault = name, ratio
start = now()
print('%7.1fs phase %-18s %4ds fault=%.2f' % (start, name, seconds, ratio), flush=True)
while now() - start < seconds:
time.sleep(10)
samples.append({'t': now(), 'phase': name, **{w: g.value('slo:api_errors:ratio_rate' + w) for w in ('30s', '1m', '1m30s', '2m30s', '15m')}})
timeline.append({'phase': name, 'start': start, 'end': now(), 'fault_ratio': ratio})
load.stop.set()
watcher.stop.set()
watcher.join()
alerts = {name: watcher.intervals(name) for name in ('ApiAvailabilityFastBurn', 'ApiAvailabilitySlowBurn', 'ApiHighErrorRate')}
expected = {'ApiAvailabilityFastBurn': {'outage'}, 'ApiAvailabilitySlowBurn': {'degradation', 'outage'},
'ApiHighErrorRate': {'degradation', 'outage'}} # по политике SLO: всплеск < 2 % бюджета — не повод для реакции
phase_of = lambda t: next((p['phase'] for p in timeline if p['start'] <= t < p['end']), 'end')
fault_phase = {'spike', 'degradation', 'outage'}
analysis = {}
for name, spans in alerts.items():
rows = []
for start, end in spans:
cause = phase_of(start)
cause = cause.replace('after_', '') if cause.startswith('after_') else cause
origin = next(p for p in timeline if p['phase'] == cause) if cause in fault_phase else None
fault_end = origin['end'] if origin else None
rows.append({'fired_at': start, 'resolved_at': end, 'caused_by': cause,
'detect_s': round(start - origin['start'], 1) if origin else None,
'resolve_after_fault_end_s': round(end - fault_end, 1) if origin and end else None,
'expected': cause in expected[name]})
missed = sorted(expected[name] - {r['caused_by'] for r in rows})
analysis[name] = {'firings': rows, 'false_positives': sum(not r['expected'] for r in rows), 'missed': missed}
total = {k: sum(c.get(k, 0) for c in load.counts.values()) for k in ('ok', 'injected_500', 'unexpected_500', 'failed')}
result = {'design': {'rps': args.rps, 'slo': '99% non-5xx', 'compression': 24, 'phases': timeline},
'requests': load.counts, 'totals': total, 'alerts': analysis, 'events': watcher.events, 'ratios': samples}
out = ROOT / 'evidence/slo_experiment.json'
out.write_text(json.dumps(result, ensure_ascii=False, indent=1))
for name, a in analysis.items():
print(name, 'FP=%d missed=%s' % (a['false_positives'], a['missed']),
['%s: detect %ss, resolve +%ss' % (r['caused_by'], r['detect_s'], r['resolve_after_fault_end_s']) for r in a['firings']])
print('requests', total, '->', out.relative_to(ROOT))
check(total['unexpected_500'] == 0 and total['failed'] <= 3, 'unexpected request failures: %s' % total)
def wait_alerts(g, names, firing, timeout):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
active = {k for k, v in g.alerts().items() if v == 'firing'}
if (set(names) <= active) if firing else not (set(names) & set(g.alerts())):
return now()
time.sleep(2)
return None
def incidents(args):
g = Grafana(args.grafana_url)
report = {}
load = Load(args.base_url, 5, threads=2)
uploader = Client(args.base_url, timeout=10)
owner, _, _, chat = uploader.bootstrap()
uploads = {'accepted': 0, 'failed': 0}
stop_uploads = threading.Event()
def upload_loop():
while not stop_uploads.is_set():
try:
uploader.attachment(owner, chat)
uploads['accepted'] += 1
except Failure:
uploads['failed'] += 1
stop_uploads.wait(2)
watcher = AlertLog(g)
load.start()
watcher.start()
threading.Thread(target=upload_loop, daemon=True).start()
time.sleep(40)
# 1. Worker stopped: backlog grows, QueueLagHigh/WorkerAbsent fire; after start backlog drains, alerts resolve.
load.phase = 'worker_stopped'
t_stop = now()
compose('stop', 'worker')
queue = []
while now() - t_stop < args.worker_down:
time.sleep(10)
queue.append({'t': now(), 'depth': g.value('max(messenger_queue_depth)'), 'oldest_age_s': g.value('max(messenger_queue_oldest_age_seconds)')})
load.phase = 'worker_recovering'
t_start = now()
compose('start', 'worker')
drained = None
while now() - t_start < 300:
time.sleep(5)
depth = g.value('max(messenger_queue_depth)')
queue.append({'t': now(), 'depth': depth, 'oldest_age_s': g.value('max(messenger_queue_oldest_age_seconds)')})
if drained is None and depth == 0 and now() - t_start > 20:
drained = now()
if drained and wait_alerts(g, ['QueueLagHigh', 'WorkerAbsent'], False, 1):
break
report['worker_stop'] = {'stopped_at': t_stop, 'started_at': t_start, 'backlog_drained_at': drained, 'queue': queue}
print('worker stop: drained at', drained, json.dumps({n: watcher.intervals(n) for n in ('QueueLagHigh', 'WorkerAbsent')}), flush=True)
# 2. Slow DB: an exclusive lock on messages for N s; POST /messages waits in the INSERT span, not in the handler.
load.phase = 'db_locked'
t_lock = now()
compose('exec', '-T', 'postgres', 'psql', '-q', '-U', 'messenger', '-d', 'messenger', '-c',
'begin; lock table messages in access exclusive mode; select pg_sleep(%d); commit;' % args.db_lock)
load.phase = 'db_recovered'
time.sleep(25)
end_ns, start_ns = time.time_ns(), time.time_ns() - int((now() - t_lock + 30) * 1e9)
search = g.get('/api/datasources/proxy/uid/tempo/api/search?' + urllib.parse.urlencode(
{'tags': 'service.name=messenger-api', 'minDuration': '%ds' % max(2, args.db_lock // 2), 'limit': 5,
'start': start_ns // 10**9, 'end': end_ns // 10**9}))
slow = []
for t in search.get('traces', [])[:3]:
trace = g.get('/api/datasources/proxy/uid/tempo/api/traces/' + t['traceID'])
spans = [s for b in trace.get('batches') or trace.get('resourceSpans', []) for ss in b.get('scopeSpans', []) for s in ss['spans']]
dur = lambda s: (int(s['endTimeUnixNano']) - int(s['startTimeUnixNano'])) / 1e9
server = max((s for s in spans if s.get('kind') in ('SPAN_KIND_SERVER', 2)), key=dur, default=None)
db = max((s for s in spans if s.get('kind') in ('SPAN_KIND_CLIENT', 3) and any(a['key'].startswith('db.') for a in s.get('attributes', []))), key=dur, default=None)
slow.append({'trace_id': t['traceID'], 'root': t.get('rootTraceName'), 'server_s': server and round(dur(server), 2),
'slowest_db_span': db and db['name'], 'db_s': db and round(dur(db), 2)})
report['db_lock'] = {'locked_at': t_lock, 'lock_s': args.db_lock, 'slow_traces': slow,
'p99_messages_s_2m': g.value('histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket{job="messenger-api",http_route="/api/v1/chats/{id}/messages",http_request_method="POST"}[2m])))'),
'max_pending_connections_2m': g.value('max(max_over_time(db_client_connections_pending_requests[2m]))'),
'requests': {k: load.counts.get(k) for k in ('db_locked', 'db_recovered')}}
print('db lock:', json.dumps(slow), flush=True)
# 3. Telemetry backends down: API keeps serving; Collector memory stays bounded; losses are counted.
load.phase = 'telemetry_down'
# Собственные метрики Collector 0.115 приходят без суффикса _total; счётчик появляется при первой ошибке: нет = 0.
lost = lambda k: sum(g.value('sum(otelcol_exporter_%s_%s)' % (kind, k)) or 0 for kind in ('send_failed', 'enqueue_failed'))
before = {k: lost(k) for k in ('spans', 'log_records')}
compose('stop', 'loki', 'tempo')
t_down, memory = now(), []
while now() - t_down < args.telemetry_down:
time.sleep(10)
stats = compose('stats', '--no-stream', '--format', '{{.Name}} {{.MemUsage}}', 'otel-collector', check_rc=False).strip()
memory.append({'t': now(), 'collector_mem': stats.split(' ', 1)[-1],
'queue_batches': g.value('sum(otelcol_exporter_queue_size)'),
'refused_spans': g.value('sum(otelcol_receiver_refused_spans)')})
compose('start', 'loki', 'tempo')
load.phase = 'telemetry_recovered'
time.sleep(75)
after = {k: lost(k) for k in ('spans', 'log_records')}
report['telemetry_down'] = {'down_s': args.telemetry_down, 'collector': memory, 'lost_before': before, 'lost_after': after,
'requests': {k: load.counts.get(k) for k in ('telemetry_down', 'telemetry_recovered')}}
print('telemetry down:', json.dumps(memory[-1]), 'lost', before, '->', after, flush=True)
stop_uploads.set()
load.stop.set()
watcher.stop.set()
time.sleep(2)
report['alerts'] = {n: watcher.intervals(n) for n in sorted({e['alert'] for e in watcher.events})}
report['uploads'] = uploads
report['requests'] = load.counts
report['events'] = watcher.events
out = ROOT / 'evidence/incidents.json'
out.write_text(json.dumps(report, ensure_ascii=False, indent=1))
print('requests', load.counts, 'uploads', uploads, '->', out.relative_to(ROOT))
def trace_tree(g, trace_id, wait=60):
"""Spans of one trace from Tempo (waits for ingestion): service, kind, name, parent, status, key attributes."""
deadline = time.monotonic() + wait
while True:
try:
data = g.get('/api/datasources/proxy/uid/tempo/api/traces/' + trace_id)
except OSError:
data = {}
spans = []
for b in data.get('batches') or data.get('resourceSpans', []):
service = next((a['value'].get('stringValue') for a in b['resource']['attributes'] if a['key'] == 'service.name'), '?')
for ss in b.get('scopeSpans', []):
for sp in ss['spans']:
attrs = {a['key']: next(iter(a['value'].values()), None) for a in sp.get('attributes', [])}
spans.append({'service': service, 'kind': str(sp.get('kind', '')).replace('SPAN_KIND_', ''), 'name': sp['name'],
'span_id': sp['spanId'], 'parent': sp.get('parentSpanId') or None,
'start_ns': int(sp['startTimeUnixNano']), 'ms': round((int(sp['endTimeUnixNano']) - int(sp['startTimeUnixNano'])) / 1e6, 1),
'status': sp.get('status', {}).get('code', 'UNSET'),
**{k: attrs[k] for k in ('job.attempt', 'job.outcome', 'http.response.status_code', 'messaging.destination.name') if k in attrs}})
if any(s['kind'] == 'CONSUMER' and s.get('job.outcome') == 'done' for s in spans) or time.monotonic() > deadline:
return sorted(spans, key=lambda s: s['start_ns']), json.dumps(data)
time.sleep(5)
def logs_for(g, service, trace_id):
end = time.time_ns()
q = urllib.parse.quote('{service_name="%s"} | trace_id="%s"' % (service, trace_id))
data = g.get('/api/datasources/proxy/uid/loki/loki/api/v1/query_range?query=%s&limit=50&start=%d&end=%d&direction=forward' % (q, end - 900 * 10**9, end))
return [{'ts': v[0], 'line': v[1][:160], **{k: s['stream'].get(k) for k in ('event', 'severity_text', 'trace_id', 'span_id', 'request_id', 'http_route', 'http_response_status_code')}}
for s in data['data']['result'] for v in s['values']]
def traces(args):
"""Level 3/4 evidence: a controlled request → its trace + log; one upload with one retry → one trace to S3/DB."""
import os
g = Grafana(args.grafana_url)
c = Client(args.base_url)
alice, _, _, chat = c.bootstrap()
tid = lambda: os.urandom(16).hex()
marker = 'leak-marker-' + os.urandom(6).hex()
req_trace = tid()
r = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, body={'text': marker}, actor=alice, schema='Message',
headers={'Idempotency-Key': os.urandom(8).hex(), 'traceparent': '00-%s-%s-01' % (req_trace, os.urandom(8).hex())})
request_id = r['headers'].get('X-Request-Id')
content = (ROOT / 'tests/fixtures/sample.png').read_bytes()
up_trace = tid()
att = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=fault-flaky-trace.png', 202, actor=alice, raw=content, schema='Attachment',
headers={'Content-Type': 'image/png', 'traceparent': '00-%s-%s-01' % (up_trace, os.urandom(8).hex())})['json']
ready = c.wait_ready(alice, att, 90)
time.sleep(15)
req_spans, req_raw = trace_tree(g, req_trace, 30)
up_spans, up_raw = trace_tree(g, up_trace, 90)
req_logs = logs_for(g, 'messenger-api', req_trace)
up_logs = logs_for(g, 'messenger-api', up_trace) + logs_for(g, 'messenger-worker', up_trace)
by_id = {s['span_id']: s for s in up_spans}
chain = [{'service': s['service'], 'kind': s['kind'], 'name': s['name'], 'parent': by_id[s['parent']]['name'] if s['parent'] in by_id else None,
'ms': s['ms'], 'status': s['status'], **{k: s[k] for k in ('job.attempt', 'job.outcome') if k in s}}
for s in up_spans if s['kind'] in ('SERVER', 'PRODUCER', 'CONSUMER')]
effects = sorted({s['name'] for s in up_spans if s['service'] == 'messenger-worker' and s['kind'] == 'CLIENT' and (s['name'].startswith('S3.') or s['name'].split(' ')[0] in ('UPDATE', 'INSERT'))})
token = alice['token']
leaks = {'message_text_in_logs_or_traces': sum(x.count(marker) for x in (json.dumps(req_logs), req_raw)),
'session_token_in_logs_or_traces': sum(x.count(token) for x in (json.dumps(req_logs + up_logs), req_raw, up_raw))}
lq = urllib.parse.quote('{service_name=~"messenger-api|messenger-worker"} |= "%s"' % marker)
end = time.time_ns()
leaks['message_text_in_loki_all_logs'] = len(g.get('/api/datasources/proxy/uid/loki/loki/api/v1/query_range?query=%s&limit=10&start=%d&end=%d' % (lq, end - 900 * 10**9, end))['data']['result'])
result = {'controlled_request': {'trace_id': req_trace, 'request_id': request_id, 'spans': [{k: s[k] for k in ('service', 'kind', 'name', 'ms', 'status')} for s in req_spans], 'logs': req_logs},
'upload_with_retry': {'trace_id': up_trace, 'attachment_status': ready['status'], 'chain': chain, 'worker_effect_spans': effects,
'logs': [{k: l[k] for k in ('event', 'severity_text', 'line', 'span_id')} for l in up_logs]},
'leak_check': leaks}
out = ROOT / 'evidence/trace_chain.json'
out.write_text(json.dumps(result, ensure_ascii=False, indent=1))
print(json.dumps({'request_spans': len(req_spans), 'request_logs': len(req_logs), 'chain': [(x['kind'], x['name'], x.get('job.outcome')) for x in chain],
'effects': effects, 'leaks': leaks}, ensure_ascii=False))
check(req_spans and req_logs, 'controlled request: trace or log not found')
check(any(x.get('job.outcome') == 'retry' for x in chain) and any(x.get('job.outcome') == 'done' for x in chain), 'upload trace lacks retry→done chain')
check(not any(leaks.values()), 'telemetry leak: %s' % leaks)
print('PASS: trace/log correlation and upload chain ->', out.relative_to(ROOT))
def ttr(args):
"""Baseline time to ready under light load: N uploads one per second, client-side (request start → ready, poll 0.3 s)."""
c = Client(args.base_url)
owner, _, _, chat = c.bootstrap()
seconds, lock = [], threading.Lock()
def one():
start = time.monotonic()
att, _ = c.attachment(owner, chat)
c.wait_ready(owner, att, 120)
with lock:
seconds.append(round(time.monotonic() - start, 2))
threads = []
for _ in range(args.uploads):
threads.append(threading.Thread(target=one))
threads[-1].start()
time.sleep(1)
for t in threads:
t.join()
seconds.sort()
q = lambda f: seconds[min(len(seconds) - 1, int(f * len(seconds)))]
result = {'uploads': len(seconds), 'p50_s': q(0.5), 'p95_s': q(0.95), 'max_s': seconds[-1], 'over_10s': sum(x > 10 for x in seconds), 'all_s': seconds}
out = ROOT / 'evidence/ttr_baseline.json'
out.write_text(json.dumps(result, indent=1))
print({k: v for k, v in result.items() if k != 'all_s'}, '->', out.relative_to(ROOT))
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('mode', choices=['traces', 'slo', 'incidents', 'ttr'])
p.add_argument('--base-url', default=None)
p.add_argument('--grafana-url', default='http://localhost:3000')
p.add_argument('--rps', type=float, default=10)
p.add_argument('--baseline', type=int, default=300)
p.add_argument('--spike', type=int, default=15)
p.add_argument('--quiet', type=int, default=120)
p.add_argument('--degradation', type=int, default=360)
p.add_argument('--degradation-ratio', type=float, default=0.1)
p.add_argument('--outage', type=int, default=60)
p.add_argument('--worker-down', type=int, default=150)
p.add_argument('--db-lock', type=int, default=20)
p.add_argument('--telemetry-down', type=int, default=120)
p.add_argument('--uploads', type=int, default=30)
args = p.parse_args()
{'traces': traces, 'slo': slo, 'incidents': incidents, 'ttr': ttr}[args.mode](args)
if __name__ == '__main__':
run(main)
+285
View File
@@ -0,0 +1,285 @@
#!/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)
+107
View File
@@ -0,0 +1,107 @@
#!/usr/bin/env python3
"""Эксперимент уровня 4: N одновременных загрузок ~10 MiB и пик памяти контейнеров.
Память читается из cgroup v2 внутри контейнеров (memory.current и anon из memory.stat) каждые 0.2 с
через docker compose exec, пока идут загрузки. anon — память процессов (heap JVM и native),
memory.current дополнительно включает page cache временных файлов.
Пример: python3 tests/upload_memory.py --runs 1,10,20 --output evidence/upload_memory.json
"""
import json
import os
import struct
import subprocess
import threading
import time
import zlib
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from client import ROOT, Client, Failure, arguments, check, run
SERVICES = ('api-1', 'api-2', 'nginx', 's3')
# Свой дедлайн: docker exec не завершает процесс в контейнере, когда клиент отключается.
SAMPLER = ('end=$(($(date +%s)+180)); while [ $(date +%s) -lt $end ]; do '
'echo $(cat /sys/fs/cgroup/memory.current) $(grep "^anon " /sys/fs/cgroup/memory.stat | cut -d" " -f2) || exit; sleep 0.2; done')
def big_png():
# 1800×1900 RGB из случайных байтов не сжимается: файл ≈9.8 MiB, чуть меньше лимита 10 MiB.
def chunk(kind, data):
return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data))
raw = b''.join(b'\x00' + os.urandom(1800 * 3) for _ in range(1900))
return (b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', 1800, 1900, 8, 2, 0, 0, 0))
+ chunk(b'IDAT', zlib.compress(raw, 1)) + chunk(b'IEND', b''))
class Sampler:
"""Фоновое чтение памяти одного контейнера; хранит максимум за время измерения."""
def __init__(self, service):
self.service, self.peak_current, self.peak_anon, self.base = service, 0, 0, None
self.proc = subprocess.Popen(['docker', 'compose', 'exec', '-T', service, 'sh', '-c', SAMPLER], cwd=ROOT,
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
threading.Thread(target=self.read, daemon=True).start()
def read(self):
for line in self.proc.stdout:
parts = line.split()
if len(parts) != 2:
continue
current, anon = map(int, parts)
if self.base is None:
self.base = (current, anon)
self.peak_current, self.peak_anon = max(self.peak_current, current), max(self.peak_anon, anon)
def stop(self):
self.proc.terminate()
mib = lambda v: round(v / 2**20, 1)
return {'baseline_current_mib': mib(self.base[0]), 'baseline_anon_mib': mib(self.base[1]),
'peak_current_mib': mib(self.peak_current), 'peak_anon_mib': mib(self.peak_anon)}
def main():
def configure(p):
p.add_argument('--runs', default='1,10,20', help='comma-separated concurrency levels')
p.add_argument('--output', default=None)
args = arguments('Concurrent ~10 MiB uploads with peak container memory', configure)
c = Client(args.base_url, args.ca_file, timeout=120)
alice, bob, eve, chat = c.bootstrap()
data = big_png()
check(len(data) <= 10 * 2**20, 'fixture exceeds 10 MiB')
results = []
for n in [int(x) for x in args.runs.split(',')]:
samplers = [Sampler(s) for s in SERVICES]
time.sleep(1.5)
def one(_):
local = Client(args.base_url, args.ca_file, timeout=120)
started = time.monotonic()
try:
r = local.call('POST', '/api/v1/chats/%s/attachments?filename=big.png' % chat['id'], [202, 503], actor=alice,
raw=data, headers={'Content-Type': 'image/png'})
return r['status'], time.monotonic() - started, r['headers'].get('X-Instance-Id')
except Failure as e:
return str(e), time.monotonic() - started, None
started = time.monotonic()
with ThreadPoolExecutor(max_workers=n) as pool:
done = list(pool.map(one, range(n)))
wall = time.monotonic() - started
time.sleep(1)
memory = {s.service: s.stop() for s in samplers}
statuses = {}
for status, _, _ in done:
statuses[str(status)] = statuses.get(str(status), 0) + 1
latencies = sorted(d for _, d, _ in done)
result = {'concurrent_uploads': n, 'file_mib': round(len(data) / 2**20, 2), 'statuses': statuses,
'replicas_used': len({i for _, _, i in done if i}), 'wall_seconds': round(wall, 2),
'latency_seconds': {'p50': round(latencies[len(latencies) // 2], 2), 'max': round(latencies[-1], 2)},
'memory': memory}
print(json.dumps(result, ensure_ascii=False))
results.append(result)
report = {'experiment': 'concurrent ~10 MiB PNG uploads through nginx', 'api_memory_limit': '512M per replica, JVM heap max 128 MiB',
'max_concurrent_uploads_per_replica': 8, 'results': results}
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)