Files
mtusi2026lab6/student-tests/reconcile_cost.py
T

90 lines
4.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Трек 2: стоимость обхода reconciler в зависимости от числа вложений.
Для каждого N: досеиваем согласованные пары (строка в PostgreSQL + объект в S3)
под отдельным префиксом чата-стенда, затем 3 раза запускаем dry-run и берём
медиану duration_ms. Фиксируем число строк/объектов, LIST-страниц, Stat-вызовов
и heap процесса reconciler. Дополнительно — прогон с 1% внедрённых расхождений.
Объекты — 1 KiB случайных байт (размер не влияет на обход: LIST возвращает
метаданные, тела объектов не читаются).
"""
import json
import statistics
import time
import uuid
from labutil import BUCKET, compose, mc, psql
from client import Client, arguments, check, run
def reconcile_dry():
for _ in range(10):
r = compose('run', '--rm', '--no-deps', '-T', '--entrypoint', '/app/reconcile', 'reconciler',
'--grace', '1h', check=False, timeout=900)
if r.returncode == 3:
time.sleep(2)
continue
check(r.returncode in (0, 4), 'reconcile failed: ' + r.stderr[-300:])
return json.loads(r.stdout.strip().splitlines()[-1])
raise RuntimeError('lock busy')
def seed(chat_id, owner_id, start, count):
"""count согласованных пар с ключами a/<chat>/bench-<номер>."""
# Объекты: генерируем count файлов в контейнере mc и заливаем одним mirror.
mc('mkdir -p /tmp/b && head -c 1024 /dev/urandom > /tmp/one && i=%d; while [ $i -lt %d ]; do '
'cp /tmp/one /tmp/b/bench-$(printf %%07d $i); i=$((i+1)); done && '
'mc mirror -q --overwrite /tmp/b s3/%s/a/%s/ >/dev/null' % (start, start + count, BUCKET, chat_id))
psql("INSERT INTO attachments (id, chat_id, owner_id, filename, object_key, status, content_type, size_bytes, sha256) "
"SELECT gen_random_uuid(), '%s', '%s', 'b.png', 'a/%s/bench-' || lpad(g::text, 7, '0'), 'ready', "
"'image/png', 1024, repeat('a', 64) FROM generate_series(%d, %d) g"
% (chat_id, owner_id, chat_id, start, start + count - 1))
def main():
def configure(p):
p.add_argument('--sizes', default='1000,10000,30000')
p.add_argument('--output', default=None)
args = arguments('Reconciler traversal cost (lab4 track 2)', configure)
c = Client(args.base_url, args.ca_file)
alice, _, _, chat = c.bootstrap()
total_existing = int(psql('SELECT count(*) FROM attachments'))
sizes = [int(x) for x in args.sizes.split(',')]
seeded, runs = 0, []
for n in sizes:
t0 = time.time()
seed(chat['id'], alice['id'], seeded, n - seeded)
seed_s = time.time() - t0
seeded = n
reps = [reconcile_dry() for _ in range(3)]
ms = [r['duration_ms'] for r in reps]
r = reps[-1]
runs.append({'bench_pairs': n, 'rows_scanned': r['rows_scanned'], 'objects_scanned': r['objects_scanned'],
'duration_ms_runs': ms, 'duration_ms_median': statistics.median(ms),
'us_per_pair': round(1000 * statistics.median(ms) / max(1, r['rows_scanned']), 1),
'calls': r['calls'], 'heap_alloc_mb': r['heap_alloc_mb'], 'found': r['found'],
'wait_ms_runs': [x.get('wait_ms') for x in reps],
'seed_seconds': round(seed_s, 1)})
print(json.dumps(runs[-1], ensure_ascii=False))
# 1% расхождений на самом большом наборе: удалённые объекты и сироты.
k = max(1, sizes[-1] // 100)
mc('i=0; while [ $i -lt %d ]; do mc rm -q s3/%s/a/%s/bench-$(printf %%07d $((i*97 %% %d))) >/dev/null 2>&1; i=$((i+1)); done'
% (k // 2, BUCKET, chat['id'], sizes[-1]))
mc('head -c 512 /dev/urandom > /tmp/o && i=0; while [ $i -lt %d ]; do mc cp -q /tmp/o s3/%s/a/%s/zz-orphan-$i >/dev/null; i=$((i+1)); done'
% (k - k // 2, BUCKET, chat['id']))
faulty = reconcile_dry()
out = {'preexisting_rows': total_existing, 'object_size_bytes': 1024, 'runs': runs,
'with_1pct_faults': {'injected_missing': k // 2, 'injected_orphans': k - k // 2,
'duration_ms': faulty['duration_ms'], 'found': faulty['found'],
'skipped': faulty['skipped'], 'calls': faulty['calls']},
'note': 'dry-run, grace 1h: свежие сироты учитываются как skipped.fresh_object, а не удаляются'}
text = json.dumps(out, ensure_ascii=False, indent=2)
if args.output:
open(args.output, 'w', encoding='utf-8').write(text + '\n')
print(text)
print('PASS: reconciler cost measured for %s pairs' % sizes)
if __name__ == '__main__':
run(main)