"""Замечание к MR: уборщик S3 не удаляет текущую работу — воспроизведение на стенде с «барьерами». make cleanup-race (= python student-tests/cleanup_race.py) Порядок событий закрепляют точки-паузы (src/messenger/faults.py): процесс один раз ждёт несколько секунд в опасном месте, а тест в это время делает следующий шаг. Grace period = 0, чтобы уборщик рассматривал даже свежие объекты (так же, как в воспроизведении из замечания). Настоящие PostgreSQL, S3, CLI уборщика, replay, API и worker. A. Как в замечании. failed-вложение с истёкшим retention (состояние и возраст заданы через updated_at, как в замечании). Уборщик прочитал ссылки и остановился (cleanup_pause) -> оператор делает replay (queued) -> уборщик продолжает. Было: staging удалён, worker -> failed / source_missing. Стало: уборщик перепроверяет состояние под блокировкой и staging не трогает; после запуска worker вложение становится ready. B. Обратный порядок. Уборщик под блокировкой уже решил удалить staging истёкшего failed и пометил его удалённым, COMMIT ещё нет (cleanup_pause_locked) -> replay ждёт блокировку и безопасно отказывает (source_missing), задание остаётся failed, в журнале — запись уборщика и отказ replay; сам объект уборщик удаляет после COMMIT. C. Загрузка между PUT в staging и COMMIT строки вложения (api_pause_after_staging): уборщик пропускает это вложение (занято), загрузка заканчивается 202 -> ready. D. Worker записал оригинал и варианты в S3, COMMIT ещё нет (worker_pause_after_objects): уборщик ничего не удаляет (задание в processing), worker коммитит -> ready, файлы на месте. """ import hashlib import threading import time import ops from filegen import SAMPLE_PNG, png, wait_status from helpers import Client, check, run # Секунд в точке-паузе: столько длится «окно» гонки. С запасом: на Windows каждый docker exec — около секунды. PAUSE = {"cleanup_pause": "10", "cleanup_pause_locked": "8", "api_pause_after_staging": "10", "worker_pause_after_objects": "12"} def background(fn, *args): result = {} def target(): try: result["value"] = fn(*args) except BaseException as exc: # noqa: BLE001 — передаём в основной поток result["error"] = exc thread = threading.Thread(target=target, daemon=True) thread.start() return thread, result def finish(step, seconds=60): thread, result = step thread.join(seconds) check(not thread.is_alive(), "a background step did not finish") if "error" in result: raise result["error"] return result["value"] def wait_paused(container, point, seconds=40): """Точка-пауза сработала (процесс удалил её файл и ждёт) — можно делать следующий шаг.""" deadline = time.monotonic() + seconds while ops.armed(container, point): check(time.monotonic() < deadline, f"{point} did not fire") time.sleep(0.2) def janitor(container, attachment_id): return ops.cli_in(container, "messenger.cleanup", "--grace-seconds", "0", "--attachment", attachment_id) def mark_failed_long_ago(attachment_id): ops.psql(f"""UPDATE attachment_jobs SET status = 'failed', finished_at = now(), last_error_code = 'storage_unavailable', last_error = 'cleanup-race' WHERE attachment_id = '{attachment_id}'; UPDATE attachments SET status = 'failed', error_code = 'retry_exhausted', updated_at = now() - interval '2 days' WHERE id = '{attachment_id}'""") def staging_exists(attachment_id): return ops.objects(f"staging/{attachment_id}") == [f"staging/{attachment_id}"] def upload(api, actor, chat, data, name): return api.call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename={name}", 202, actor=actor, raw=data, headers={"Content-Type": "image/png"}, schema="Attachment")["json"] def main(): api = Client(timeout=30) alice, bob, _eve, chat = api.bootstrap() container = ops.containers("api")[0] # здесь запускается уборщик и включаются его паузы # ---------- A и B: подготовка двух failed-вложений с истёкшим retention ---------- ops.stop("worker") try: a = upload(api, alice, chat, SAMPLE_PNG, "race-a.png") b = upload(api, alice, chat, png(40, 30), "race-b.png") for att in (a, b): mark_failed_long_ago(att["id"]) # ---------- A ---------- ops.arm("api", "cleanup_pause", PAUSE["cleanup_pause"], container=container) cleanup = background(janitor, container, a["id"]) wait_paused(container, "cleanup_pause") print(f"A. failed {a['id']} (retention expired); the janitor read the references and stopped") replayed = ops.replay(a["id"]) check(replayed.get("result") == "queued", f"replay: {replayed}") print(f" operator replay while the janitor waits -> {replayed}") out = finish(cleanup) check(out["deleted"] == 0 and out["kept_after_recheck"] == {"current_work": 1}, f"janitor: {out}") check(staging_exists(a["id"]), "the staging of the replayed job was deleted") print(f" janitor continued: deleted {out['deleted']}, re-checked under the lock -> kept " f"{out['kept_after_recheck']}; staging/{a['id'][:8]}... is still in S3") # ---------- B ---------- ops.arm("api", "cleanup_pause_locked", PAUSE["cleanup_pause_locked"], container=container) cleanup = background(janitor, container, b["id"]) wait_paused(container, "cleanup_pause_locked") print(f"B. failed {b['id']} (retention expired); the janitor holds the lock: staging marked deleted, " f"no COMMIT yet") started = time.monotonic() refused = ops.replay(b["id"]) waited = time.monotonic() - started out = finish(cleanup) check(refused.get("result") == "refused" and refused.get("reason") == "source_missing", f"replay: {refused}") check(out["deleted"] == 1 and out["to_delete"]["staging_failed_expired"] == 1, f"janitor: {out}") job = ops.job(b["id"]) events = [e["event"] for e in job["events"] if e["event"] in ("staging_expired", "replay_refused")] check(job["job"]["status"] == "failed" and events == ["staging_expired", "replay_refused"], f"{job}") check(not staging_exists(b["id"]), "the expired staging must be deleted") print(f" replay waited {waited:.1f} s for the lock -> {refused['result']} ({refused['reason']}); " f"job stays failed; journal: {' -> '.join(events)}") finally: ops.start("worker") ops.wait_healthy("worker", 1) ready = wait_status(api, bob, a["id"], ("ready", "failed"), seconds=90) check(ready["status"] == "ready", f"A must become ready, got {ready['status']} / {ready['error_code']}") print(f" A: worker started -> ready with {[v['name'] for v in ready['variants']]} (before the fix: " f"failed / source_missing)") # ---------- C ---------- before = set(ops.objects("staging/")) ops.arm("api", "api_pause_after_staging", PAUSE["api_pause_after_staging"]) try: sending = background(upload, api, alice, chat, png(48, 36), "race-c.png") deadline = time.monotonic() + 30 while True: new = sorted(set(ops.objects("staging/")) - before) if new: break check(time.monotonic() < deadline, "the upload did not reach staging") time.sleep(0.2) c_id = new[0].split("/", 1)[1] rows = ops.psql(f"SELECT count(*) FROM attachments WHERE id = '{c_id}'") check(rows == "0", "the row must not be committed yet") print(f"C. upload {c_id}: staging written, no row in the database yet (API paused before COMMIT)") out = janitor(container, c_id) check(out["deleted"] == 0 and out["skipped_busy"] == 1, f"janitor: {out}") print(f" janitor (grace 0): skipped_busy {out['skipped_busy']}, deleted {out['deleted']} — " f"the upload holds the attachment lock") att = finish(sending) check(att["id"] == c_id, "unexpected attachment id") finally: ops.disarm("api", "api_pause_after_staging") meta = wait_status(api, bob, c_id, seconds=60) print(f" upload -> 202, then {meta['status']} with {len(meta['variants'])} variants") # ---------- D ---------- ops.arm("worker", "worker_pause_after_objects", PAUSE["worker_pause_after_objects"]) try: d = upload(api, alice, chat, SAMPLE_PNG, "race-d.png") deadline = time.monotonic() + 60 while len(ops.objects(f"variants/{d['id']}/")) < 3 or not ops.objects(f"originals/{d['id']}"): check(time.monotonic() < deadline, "the worker did not write the objects") time.sleep(0.2) status = ops.job(d["id"])["attachment_status"] check(status == "processing", f"expected processing, got {status}") print(f"D. {d['id']}: worker wrote the original and 3 variants, COMMIT not yet (status {status})") out = janitor(container, d["id"]) # По снимку ссылок оригинал и 3 варианта — ничьи (на них ещё нет COMMIT), staging — нужен. check(out["deleted"] == 0 and out["kept_after_recheck"].get("current_work", 0) == 4, f"janitor: {out}") print(f" janitor (grace 0): the snapshot marked the original and 3 variants as unreferenced; re-checked " f"under the lock -> kept {out['kept_after_recheck']}, deleted {out['deleted']}") finally: ops.disarm("worker", "worker_pause_after_objects") meta = wait_status(api, bob, d["id"], seconds=60) body = api.call("GET", f"/api/v1/attachments/{d['id']}/content", 200, actor=bob)["bytes"] check(hashlib.sha256(body).hexdigest() == d["sha256"], "the original changed") for variant in meta["variants"]: got = api.call("GET", f"/api/v1/attachments/{d['id']}/content?variant={variant['name']}", 200, actor=bob) check(hashlib.sha256(got["bytes"]).hexdigest() == variant["sha256"], "variant bytes differ") print(f" worker committed -> {meta['status']}; the original and all variants download with the same SHA-256") print("PASS: the janitor re-checks the state under the attachment lock before deleting: a replay accepted " "after its snapshot keeps the staging (A), a replay after the janitor's decision is refused safely (B), " "an upload in progress (C) and objects of a job in processing (D) are not deleted") if __name__ == "__main__": run(main)