"""Отказы pipeline (лаба 5): выполняет только `make failure-checks`. Окна отказа из contracts/attachment-states.md и что в каждом ожидается: - worker остановлен — 202, ссылка 201, байты 409, текст работает; после рестарта API и брокера с volume и запуска worker — ready (уровень 3); - relay остановлен (после COMMIT до publish) — намерение лежит в outbox, запуск relay доводит до ready без нового задания; - relay убит после подтверждения брокера до отметки — дубль публикации, обработка одна, вариантов один набор; - worker убит после записи объектов до COMMIT — аренда истекает, relay возвращает задание, вторая попытка завершает тот же результат; - worker убит после COMMIT до ack — повторная доставка no-op; - временные ошибки — повторы с backoff до бюджета, затем failed `retry_exhausted`; replay с аудитом возвращает работу, повтор replay готового отказывает; - предел принятой работы — 429 с `Retry-After`, ни строки, ни объекта; - staging убирается после ready. Сроки стенда (PIPELINE_ENV в stand.py): аренда 10 + 4 с, повторы 0,5–1 с, 3 попытки, relay каждые 0,2 с. """ import os import time from collections.abc import Callable, Iterator from contextlib import contextmanager from typing import Any import httpx import pytest import images from helpers import ( SAMPLE_JPEG, SAMPLE_PNG, assert_error, attachment_content, attachment_meta, create_chat, ready_upload, register, send, settled, upload, uploaded, ) pytestmark = pytest.mark.fault type Stand = Callable[..., str] LEASE = 14.0 BACKLOG_LIMIT = int(os.environ.get("FAULT_BACKLOG_LIMIT", "3")) def wait_for(check: Callable[[], bool], timeout: float, step: float = 0.3) -> float: started = time.monotonic() while time.monotonic() - started < timeout: if check(): return time.monotonic() - started time.sleep(step) raise AssertionError(f"condition not met in {timeout:.0f}s") def job(stand: Stand, attachment_id: str) -> dict[str, Any]: state, attempt, base, published, lease, error = stand("job", attachment_id).split() return { "state": state, "attempt": int(attempt), "attempt_base": int(base), "published": published == "1", "leased": lease == "1", "last_error": error, } def status(client: httpx.Client, user: dict, attachment_id: str) -> str: return attachment_meta(client, user, attachment_id).json()["status"] @contextmanager def stopped(stand: Stand, kind: str) -> Iterator[None]: """worker или relay стенда остановлен; в `finally` — снова запущен.""" stand(f"stop-{kind}") try: yield finally: stand(f"start-{kind}") @contextmanager def faulty(stand: Stand, kind: str, fault: str) -> Iterator[str]: """Двойник с точкой сбоя вместо основного процесса.""" with stopped(stand, kind): name = stand("faulty", kind, fault) try: yield name finally: stand("remove", name) @pytest.fixture def members(client: httpx.Client) -> dict[str, Any]: alice, bob = register(client, "alice"), register(client, "bob") return {"alice": alice, "bob": bob, "chat": create_chat(client, alice, bob)} def test_worker_down_defense_flow( client: httpx.Client, stand: Stand, members: dict ) -> None: """Сценарий защиты, шаги 2–3, на стенде отказов.""" alice, bob, chat = members["alice"], members["bob"], members["chat"] with stopped(stand, "worker"): accepted = uploaded(client, alice, chat) linked = send(client, alice, chat, "", attachment_ids=[accepted["id"]]) assert linked.status_code == 201, linked.text assert_error(attachment_content(client, bob, accepted["id"]), 409, "conflict") assert send(client, bob, chat, "текст идёт").status_code == 201 # API и брокер перезапускаются с volume; задание не теряется stand("kill-api") stand("start-api") stand("stop", "rabbitmq") stand("start", "rabbitmq") wait_for(lambda: _ready(str(client.base_url)), 30) time.sleep(1) with httpx.Client(base_url=str(client.base_url), timeout=15) as fresh: assert status(fresh, bob, accepted["id"]) == "queued" with httpx.Client(base_url=str(client.base_url), timeout=15) as fresh: meta = settled(fresh, bob, accepted["id"]) assert meta["status"] == "ready" thumb = attachment_content(fresh, bob, accepted["id"], variant="thumbnail") assert images.decoded(thumb.content)[1] == (256, 160) assert attachment_content(fresh, bob, accepted["id"]).content == SAMPLE_PNG print(f"after restarts: {job(stand, accepted['id'])}") def _ready(base_url: str) -> bool: try: return httpx.get(f"{base_url}/health/ready", timeout=2).status_code == 200 except httpx.HTTPError: return False def test_broker_restart_keeps_published_job( client: httpx.Client, stand: Stand, members: dict ) -> None: """Сообщение уже в очереди (опубликовано и подтверждено), worker стоит; рестарт брокера с volume его не теряет. Доказательство — задание готово той же первой попыткой: повторной публикации не было.""" alice, chat = members["alice"], members["chat"] with stopped(stand, "worker"): accepted = uploaded(client, alice, chat) wait_for(lambda: job(stand, accepted["id"])["published"], 10) stand("stop", "rabbitmq") stand("start", "rabbitmq") # счётчики rabbitmqctl обновляются раз в ~5 с: ждём, а не читаем раз took = wait_for(lambda: int(stand("queue").split()[0]) >= 1, 15, 1) print(f"after broker restart: message visible in queue after {took:.1f}s") assert settled(client, alice, accepted["id"])["status"] == "ready" assert job(stand, accepted["id"])["attempt"] == 1 def test_relay_down_keeps_intent_in_outbox( client: httpx.Client, stand: Stand, members: dict ) -> None: """Окно «после COMMIT до publish»: relay не работает — задание в outbox, без публикации; запуск relay доводит до ready.""" alice, chat = members["alice"], members["chat"] with stopped(stand, "relay"): accepted = uploaded(client, alice, chat) time.sleep(2) state = job(stand, accepted["id"]) assert state["state"] == "queued" assert not state["published"] assert state["attempt"] == 0 assert status(client, alice, accepted["id"]) == "queued" took = wait_for(lambda: status(client, alice, accepted["id"]) == "ready", 30) print(f"relay back: ready after {took:.1f}s, {job(stand, accepted['id'])}") assert stand("variants", accepted["id"]) == "3" def test_relay_crash_after_confirm( client: httpx.Client, stand: Stand, members: dict ) -> None: """Окно «после publish confirm до отметки»: relay умирает — сообщение в брокере, задание не отмечено. Новый relay публикует ещё раз; worker делает работу один раз, вариантов — один набор.""" alice, chat = members["alice"], members["chat"] with faulty(stand, "relay", "exit_after_confirm") as name: accepted = uploaded(client, alice, chat) code = stand("wait-exit", name, "20") state = job(stand, accepted["id"]) print(f"faulty relay exit={code}, job={state}") assert code == "137" assert not state["published"] assert settled(client, alice, accepted["id"])["status"] == "ready" assert stand("variants", accepted["id"]) == "3" assert job(stand, accepted["id"])["attempt"] == 1 def test_worker_crash_after_objects_before_commit( client: httpx.Client, stand: Stand, members: dict ) -> None: """Объекты записаны, результат не зафиксирован, ack не отправлен: аренда истекает, relay отдаёт вторую попытку, та завершает тот же результат по тем же ключам.""" alice, bob, chat = members["alice"], members["bob"], members["chat"] with faulty(stand, "worker", "exit_after_objects") as name: accepted = uploaded(client, alice, chat, SAMPLE_JPEG, content_type="image/jpeg") code = stand("wait-exit", name, "30") objects = stand("objects-of", accepted["id"]).split() state = job(stand, accepted["id"]) print(f"faulty worker exit={code}, objects={objects}, job={state}") assert code == "137" assert {"original", "thumbnail", "crop", "optimized"} <= set(objects) assert state["state"] == "processing" assert status(client, bob, accepted["id"]) == "processing" assert stand("variants", accepted["id"]) == "0" took = wait_for( lambda: status(client, bob, accepted["id"]) == "ready", LEASE + 30, 0.5 ) state = job(stand, accepted["id"]) print(f"after lease: ready in {took:.1f}s, {state}") assert state["attempt"] == 2 assert stand("variants", accepted["id"]) == "3" assert attachment_content(client, bob, accepted["id"]).content == SAMPLE_JPEG def test_worker_crash_after_commit_before_ack( client: httpx.Client, stand: Stand, members: dict ) -> None: """Результат зафиксирован, ack не дошёл: брокер выдаёт сообщение снова, повтор — no-op с ack.""" alice, chat = members["alice"], members["chat"] skipped_before = int(stand("worker-log", "outcome=finished")) with faulty(stand, "worker", "exit_after_commit") as name: accepted = uploaded(client, alice, chat) code = stand("wait-exit", name, "30") assert code == "137" assert status(client, alice, accepted["id"]) == "ready" wait_for(lambda: int(stand("worker-log", "outcome=finished")) > skipped_before, 20) state = job(stand, accepted["id"]) print(f"redelivery after commit: {state}, queue={stand('queue')}") assert state["state"] == "ready" assert state["attempt"] == 1 assert stand("variants", accepted["id"]) == "3" def test_transient_errors_exhaust_then_replay( client: httpx.Client, stand: Stand, members: dict ) -> None: """S3 недоступен worker: повторы с backoff до бюджета (3), затем failed `retry_exhausted` в реестре. После возврата S3 replay с аудитом возвращает работу; повтор replay готового — отказ (код 3).""" alice, chat = members["alice"], members["chat"] with stopped(stand, "worker"): accepted = uploaded(client, alice, chat) stand("stop", "s3") try: meta = settled(client, alice, accepted["id"], timeout=60) state = job(stand, accepted["id"]) print(f"exhausted: {meta['error_code']} {state}") assert meta["status"] == "failed" assert meta["error_code"] == "retry_exhausted" assert state["attempt"] == 3 finally: stand("start", "s3") listing = stand("replay", "--attachment", accepted["id"]) assert "exit_code=0" in listing assert f"failed job attachment_id={accepted['id']}" in listing # без оператора и причины — отказ аргументов, ничего не меняется assert "exit_code=2" in stand("replay", "--attachment", accepted["id"], "--apply") done = stand( "replay", "--attachment", accepted["id"], "--apply", "--operator", "tests", "--reason", "s3 is back", ) assert "exit_code=0" in done, done[-1500:] assert stand("replays", accepted["id"]) == "1" meta = settled(client, alice, accepted["id"]) assert meta["status"] == "ready" state = job(stand, accepted["id"]) assert state["attempt_base"] == 3 again = stand( "replay", "--attachment", accepted["id"], "--apply", "--operator", "tests", "--reason", "again", ) assert "outcome=already_ready" in again assert "exit_code=3" in again assert stand("variants", accepted["id"]) == "3" def test_permanent_error_fails_at_first_attempt( client: httpx.Client, stand: Stand, members: dict ) -> None: alice, chat = members["alice"], members["chat"] data = images.jpeg_without_tables(SAMPLE_JPEG) accepted = uploaded(client, alice, chat, data, content_type="image/jpeg") meta = settled(client, alice, accepted["id"]) state = job(stand, accepted["id"]) assert meta["error_code"] == "invalid_image" assert state["state"] == "failed" assert state["attempt"] == 1 def test_backlog_limit_is_429( backlog_client: httpx.Client, stand: Stand, members: dict ) -> None: """Незавершённых заданий стенда столько, сколько разрешено: загрузка — 429 с `Retry-After: 5` до чтения тела, ни строки, ни объекта; текст работает. Worker разбирает — загрузки снова принимаются.""" alice, chat = members["alice"], members["chat"] wait_for(lambda: stand("unfinished") == "0", 60) with stopped(stand, "worker"): accepted = [uploaded(backlog_client, alice, chat) for _ in range(BACKLOG_LIMIT)] refused = upload(backlog_client, alice, chat) assert_error(refused, 429, "rate_limited") assert refused.headers["Retry-After"] == "5" assert stand("count-attachments", chat["id"]) == f"0 {BACKLOG_LIMIT}" assert send(backlog_client, alice, chat, "текст").status_code == 201 for item in accepted: assert settled(backlog_client, alice, item["id"])["status"] == "ready" wait_for(lambda: stand("unfinished") == "0", 30) assert upload(backlog_client, alice, chat).status_code == 202 def test_staging_is_removed_after_ready( client: httpx.Client, stand: Stand, members: dict ) -> None: alice, chat = members["alice"], members["chat"] meta = ready_upload(client, alice, chat) took = wait_for( lambda: "staging" not in stand("objects-of", meta["id"]).split(), 15 ) objects = stand("objects-of", meta["id"]).split() print(f"staging removed {took:.1f}s after ready; left: {objects}") assert set(objects) == {"original", "thumbnail", "crop", "optimized"} assert attachment_content(client, alice, meta["id"]).content == SAMPLE_PNG