Files
mtusi2026lab4/student_tests/track2_experiment.py
T

170 lines
8.9 KiB
Python

#!/usr/bin/env python3
"""Трек 2: reconciler. python3 student_tests/track2_experiment.py --seed 1000 5000 | tee evidence/track2-experiment.txt
Меняет только синтетические данные; кроме них удаляет лишь aged-сирот, найденные базовым запуском."""
import argparse
import hashlib
import json
import subprocess
import sys
import time
import uuid
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from test_attachments_level4 import ROOT, SAMPLE, http_call, jcall, new_chat, new_user, psql, upload # noqa: E402
GRACE = 30
FAILS = []
def check(ok, text):
print(("PASS " if ok else "FAIL ") + text, flush=True)
if not ok:
FAILS.append(text)
def api_exec(code, *args, stdin=b""):
r = subprocess.run(["docker", "compose", "--env-file", ".env", "exec", "-T", "api", "python", "-c", code, *args],
cwd=ROOT, input=stdin, capture_output=True, check=True)
return r.stdout.decode().strip()
PUT = "import sys; from src import storage, config; storage.client().put_object(Bucket=config.S3_BUCKET, Key=sys.argv[1], Body=sys.stdin.buffer.read())"
DEL = "import sys; from src import storage; storage.delete_object(sys.argv[1])"
HEAD = """import sys
from botocore.exceptions import ClientError
from src import storage, config
try:
storage.client().head_object(Bucket=config.S3_BUCKET, Key=sys.argv[1]); print(1)
except ClientError:
print(0)"""
SEED = """import sys, uuid
from concurrent.futures import ThreadPoolExecutor
from src import storage, config
c = storage.client()
def put(i): c.put_object(Bucket=config.S3_BUCKET, Key="attachments/seed-" + uuid.uuid4().hex, Body=b"seed")
with ThreadPoolExecutor(16) as ex: list(ex.map(put, range(int(sys.argv[1]))))"""
def put(key, data=b"orphan"): api_exec(PUT, key, stdin=data)
def delete(key): api_exec(DEL, key)
def exists(key): return api_exec(HEAD, key) == "1"
def new_key(): return "attachments/" + str(uuid.uuid4())
def reconcile(*extra):
r = subprocess.run(["docker", "compose", "--env-file", ".env", "run", "--rm", "--no-deps", "-T", "reconciler",
"python", "-m", "src.reconciler", "--grace", str(GRACE), *extra],
cwd=ROOT, capture_output=True, text=True)
line = [l for l in r.stdout.splitlines() if l.startswith("{")][-1]
print(" reconciler", " ".join(extra) or "(dry-run)", "->", line, f"[exit {r.returncode}]", flush=True)
return json.loads(line), r.returncode
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--seed", type=int, nargs="*", default=[1000])
args = ap.parse_args()
user, auth = new_user()
chat = new_chat(auth, [user["id"]])
def up():
st, _, raw = upload(auth, chat, SAMPLE)
assert st == 201, st
return json.loads(raw)
def attach(att):
st, _ = jcall("POST", f"/api/v1/chats/{chat}/messages", {"text": "", "attachment_ids": [att["id"]]},
{**auth, "Idempotency-Key": uuid.uuid4().hex})
assert st == 201, st
def content(att): return http_call("GET", f"/api/v1/attachments/{att['id']}/content", headers=auth)
def key_of(att): return psql(f"SELECT object_key FROM attachments WHERE id = '{att['id']}'")
def state_of(att): return psql(f"SELECT storage_state FROM attachments WHERE id = '{att['id']}'")
print("== 0. Базовая очистка (чтобы счётчики ниже были точными)")
time.sleep(GRACE + 1)
reconcile("--apply")
print("== 1. Данные: используемые и неиспользуемые вложения")
used = up(); attach(used)
unlinked = up()
lost_used = up(); attach(lost_used)
lost_unused = up()
fresh_lost = None
print("== 2. Внедрение ошибок. S3-сторона: 3 объекта без метаданных; БД-сторона: у 2 записей объект удалён")
orphans = [new_key() for _ in range(3)]
for k in orphans:
put(k)
lost_used_key, lost_unused_key = key_of(lost_used), key_of(lost_unused)
delete(lost_used_key)
delete(lost_unused_key)
time.sleep(GRACE + 2)
fresh_orphan = new_key()
put(fresh_orphan)
fresh_lost = up()
delete(key_of(fresh_lost))
print("== 3. DRY-RUN: обнаруживает, но ничего не меняет")
r, _ = reconcile()
check(r["dry_run"] and r["orphans_found"] == 3 and r["missing_found"] == 2, "dry-run нашёл 3 сирот и 2 потерянных объекта")
check(r["orphans_fresh_skipped"] == 1 and r["missing_fresh_skipped"] == 1, "свежие сирота и запись (моложе grace) пропущены")
check(r["orphans_deleted"] == 0 and r["missing_marked"] == 0, "dry-run ничего не изменил в счётчиках")
check(all(exists(k) for k in orphans), "после dry-run все сироты ещё в S3")
check(state_of(lost_used) == "ok" and state_of(lost_unused) == "ok", "после dry-run состояния записей не изменены")
print("== 4. APPLY и сразу повторный APPLY (идемпотентность)")
r, _ = reconcile("--apply")
r2, _ = reconcile("--apply")
check(r["orphans_deleted"] == 3 and r["missing_marked"] == 2, "удалены 3 сироты, помечены 2 потерянных объекта")
check(r2["orphans_found"] == 0 and r2["missing_found"] == 0 and r2["orphans_deleted"] == 0 and r2["missing_marked"] == 0,
"повторный apply ничего не находит и не меняет")
check(exists(fresh_orphan), "свежая сирота НЕ удалена (grace period)")
check(state_of(fresh_lost) == "ok", "свежая запись без объекта НЕ помечена (grace period)")
check(not any(exists(k) for k in orphans), "старые сироты удалены из S3")
for name, att in (("используемое", used), ("неиспользуемое, но с метаданными", unlinked)):
st, _, raw = content(att)
check(st == 200 and hashlib.sha256(raw).hexdigest() == att["sha256"], f"{name} вложение старше grace цело и скачивается")
check(content(lost_used)[0] == 409 and content(lost_unused)[0] == 409, "потерянные вложения: скачивание 409, а не 500")
check(http_call("GET", f"/api/v1/attachments/{lost_used['id']}", headers=auth)[0] == 200, "метаданные потерянного вложения остаются (запись не удалена)")
st, _ = jcall("POST", f"/api/v1/chats/{chat}/messages", {"text": "", "attachment_ids": [lost_unused["id"]]},
{**auth, "Idempotency-Key": uuid.uuid4().hex})
check(st == 409, "потерянное вложение нельзя прикрепить к новому сообщению (409)")
print("== 6. Восстановление: объект вернули на то же место")
put(lost_used_key, SAMPLE)
r, _ = reconcile("--apply")
check(r["restored"] == 1 and state_of(lost_used) == "ok", "запись снова ok после проверки размера и SHA-256")
st, _, raw = content(lost_used)
check(st == 200 and hashlib.sha256(raw).hexdigest() == lost_used["sha256"], "восстановленное вложение скачивается")
print("== 7. Прошёл grace: бывшие свежие объекты теперь обрабатываются")
time.sleep(GRACE + 2)
r, _ = reconcile("--apply")
check(r["orphans_deleted"] == 1 and r["missing_marked"] == 1, "теперь удалена вторая сирота и помечена вторая потеря")
print("== 8. Стоимость обхода и предохранитель")
for n in args.seed:
print(f"-- seed {n} объектов-сирот")
api_exec(SEED, str(n))
time.sleep(GRACE + 2)
t0 = time.time()
r, _ = reconcile()
print(f" dry-run N={n}: reconciler elapsed={r['elapsed_s']}s s3_list={r['s3_list_s']}s pages={r['s3_list_pages']} "
f"db_rows={r['db_rows']} peak_rss={r['peak_rss_mib']}MiB (с запуском контейнера {time.time() - t0:.1f}s)")
check(r["orphans_found"] >= n, f"dry-run видит {n} сирот")
if n > 1000:
r, code = reconcile("--apply")
check(code == 3 and r.get("error") == "too_many_actions" and r["orphans_deleted"] == 0,
"предохранитель: массовое удаление выше --max-actions отклонено, ничего не удалено")
r, _ = reconcile("--apply", "--max-actions", str(n + 100))
check(r["orphans_deleted"] >= n, f"очистка {n} сирот выполнена")
print("\nИТОГ:", "FAIL" if FAILS else "PASS")
sys.exit(1 if FAILS else 0)
if __name__ == "__main__":
main()