#!/usr/bin/env python3 """Отказы pipeline (уровни 3–4): окна отказа из contracts/attachment-states.md и восстановление. ВНИМАНИЕ: останавливает/запускает worker, брокер (nats) и реплики API, поднимает профиль fault (api-fault, :8082), внедряет падения worker хуками по имени файла (нужен FAULT_HOOKS=lab у worker). Volumes не удаляются. Сценарии: 1 защита: worker остановлен → 202 → 409 → сообщение создано → рестарт API и брокера → worker → ready 2 broker недоступен: upload всё равно 202 (задание в outbox PostgreSQL), после старта брокера — ready 3 разрыв COMMIT → publish (api-fault падает сразу после COMMIT): relay другой реплики публикует 4 разрыв publish ack → отметка outbox: повторная публикация, брокер отбрасывает дубль по Nats-Msg-Id 5 worker падает после claim до побочного эффекта / после записи S3 до COMMIT / после COMMIT до ack 6 зависший worker (event loop заблокирован) против долгой, но живой обработки (heartbeat) 7 временные ошибки: backoff с jitter; исчерпание попыток → failed retry_exhausted → replay → ready 8 processing с истёкшим lease и потерянным сообщением → reaper возвращает работу в очередь 9 ограниченная конкуренция: одновременно в обработке не больше replicas × WORKER_CONCURRENCY 10 staging удаляется после ready; у failed — после retention, после чего replay честно отказывает """ import os import shlex import subprocess import time import uuid from common import (BASE_URL, DC, ROOT, Client, Failure, Suite, check, events, jobs_cli, login, make_png, new_user, s3_admin, sh, sql, upload, wait_status, wait_until) FAULT_URL = os.environ.get("FAULT_BASE_URL", "http://127.0.0.1:8082") WORKERS = int(os.environ.get("WORKER_REPLICAS", "2")) CONCURRENCY = int(os.environ.get("WORKER_CONCURRENCY", "2")) LEASE = float(os.environ.get("JOB_LEASE_SECONDS", "20")) c = Client(BASE_URL, timeout=30) s = Suite("pipeline failures (" + BASE_URL + ")") alice = new_user(c, "fa"); login(c, alice) bob = new_user(c, "fb"); login(c, bob) chat = c.call("POST", "/api/v1/chats", 201, actor=alice, schema="Chat", body={"title": "failures", "member_ids": [alice["id"], bob["id"]]})["json"] def dc(*args, env=None, timeout=180): subprocess.run(shlex.split(DC) + list(args), cwd=ROOT, check=True, timeout=timeout, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=dict(os.environ, **(env or {}))) def wait_healthy(service, timeout=120): def ok(): ids = subprocess.run(shlex.split(DC) + ["ps", "-q", service], cwd=ROOT, capture_output=True, text=True).stdout.split() return ids and all(subprocess.run(["docker", "inspect", "-f", "{{.State.Health.Status}}", i], capture_output=True, text=True).stdout.strip() == "healthy" for i in ids) wait_until(ok, timeout=timeout, interval=1) def ev(att_id): return [(e["event"], e["lease_token"], e["worker"], e["detail"]) for e in events(att_id)] def names(att_id): return [e[0] for e in ev(att_id)] def message(text, att_ids=()): return c.call("POST", "/api/v1/chats/%s/messages" % chat["id"], 201, actor=alice, schema="Message", body={"text": text, "attachment_ids": list(att_ids)}, headers={"Idempotency-Key": uuid.uuid4().hex}) def broker_messages(): out = subprocess.run(shlex.split(DC) + ["exec", "-T", "api", "python", "-m", "messenger", "stats"], cwd=ROOT, capture_output=True, text=True, timeout=30) import json return (json.loads(out.stdout).get("broker") or {}).get("stream_messages") @s.case("defense: worker stopped → 202 → 409 → message ok → restart API+broker (volumes kept) → worker → ready") def _(): sh("stop_worker", timeout=120) try: att, data = upload(c, alice, chat, make_png(120, 90), filename="defense.png") meta = c.call("GET", "/api/v1/attachments/" + att["id"], actor=bob, schema="Attachment")["json"] check(meta["status"] == "queued", "expected queued, got " + meta["status"]) c.call("GET", "/api/v1/attachments/%s/content" % att["id"], 409, actor=bob) message("со вложением", [att["id"]]) message("обычное сообщение работает без worker") wait_until(lambda: "published" in names(att["id"]), timeout=30) in_stream = broker_messages() sh("restart_broker", timeout=120) wait_healthy("nats") sh("restart_api", timeout=180) wait_healthy("api") after = broker_messages() check(after is not None and after >= 1, "job message lost on broker restart (stream has %s)" % after) check(wait_status(c, bob, att["id"], ("queued",), timeout=10)["status"] == "queued", "not queued") finally: sh("start_worker", timeout=120) t = time.monotonic() ready = wait_status(c, bob, att["id"], ("ready", "failed"), timeout=60) check(ready["status"] == "ready", "not ready") check(c.call("GET", "/api/v1/attachments/%s/content" % att["id"], actor=bob)["bytes"] == data, "original") c.call("GET", "/api/v1/attachments/%s/content?variant=thumbnail" % att["id"], actor=bob) return "attachment %s: stream held %s→%s msgs across restart; ready %.1fs after worker start" % ( att["id"][:8], in_stream, after, time.monotonic() - t) @s.case("broker down: upload still 202 (job durable in outbox), ready after broker returns") def _(): dc("stop", "nats") try: att, _ = upload(c, alice, chat, make_png(60, 60), filename="nobroker.png") time.sleep(2) check("published" not in names(att["id"]), "published without broker?!") check(c.call("GET", "/api/v1/attachments/" + att["id"], actor=alice, schema="Attachment")["json"]["status"] == "queued", "not queued") finally: dc("start", "nats") wait_healthy("nats") ready = wait_status(c, alice, att["id"], ("ready", "failed"), timeout=60) check(ready["status"] == "ready", "not ready") return "202 with broker stopped; events %s" % names(att["id"])[:3] def fault_upload(mode, filename): """Загрузка через api-fault с заданной точкой отказа; процесс api-fault после неё умирает.""" dc("--profile", "fault", "up", "-d", "--no-deps", "--force-recreate", "api-fault", env={"API_FAULT_INJECT": mode}) fc = Client(FAULT_URL, timeout=15) wait_until(lambda: fc.call("GET", "/health/ready", [200, 502, 503])["status"] == 200, timeout=90) fault_instance = fc.call("GET", "/health/live")["headers"].get("X-Instance-Id") marker = sql("SELECT clock_timestamp()")[0] try: upload(fc, alice, chat, make_png(70, 70), filename=filename) except Failure: pass # 202 могло не дойти: процесс умер — это и проверяем rows = sql("SELECT id FROM attachments WHERE chat_id = '%s' AND filename = '%s' AND created_at >= '%s'" % (chat["id"], filename, marker)) check(len(rows) == 1, "accepted attachment not found (%s)" % rows) return rows[0], fault_instance @s.case("crash between COMMIT and publish: relay of another process publishes, job reaches ready") def _(): try: aid, fault_instance = fault_upload("crash_after_commit_before_publish", "gap-commit-publish.png") ready = wait_status(c, alice, aid, ("ready", "failed"), timeout=60) check(ready["status"] == "ready", "not ready") e = ev(aid) seq = [x[0] for x in e] pub = [x for x in e if x[0] == "published"] # Порядок published/claimed в журнале — порядок COMMIT: worker может получить сообщение и # зафиксировать claim раньше, чем relay зафиксирует отметку outbox (это и есть at-least-once). check(seq[0] == "enqueued" and len(pub) == 1 and seq.count("committed") == 1, "events %s" % seq) relay = pub[0][3].get("relay", "") check(fault_instance and fault_instance not in relay, "published by the crashed process?! %s" % relay) finally: dc("--profile", "fault", "stop", "api-fault") return "api-fault (%s) died after COMMIT; published by relay %s; events %s" % (fault_instance, relay, seq) @s.case("crash between publish ack and outbox mark: duplicate publish dropped by Nats-Msg-Id") def _(): seen = None try: for _ in range(3): # relay другой реплики может успеть первым — тогда повтор aid, _ = fault_upload("crash_after_publish_before_mark", "gap-publish-mark.png") wait_status(c, alice, aid, ("ready", "failed"), timeout=60) pub = [x for x in ev(aid) if x[0] == "published"] check(len(pub) == 1, "published events %s" % pub) if pub[0][3].get("duplicate"): seen = pub[0][3] break finally: dc("--profile", "fault", "stop", "api-fault") check(seen is not None, "crash window not hit in 3 tries (another relay always won)") e = names(aid) check(e.count("claimed") == 1 and e.count("committed") == 1, "processed more than once: %s" % e) return "second publish: duplicate=true, stream_seq=%s; processed once" % seen["stream_seq"] def crash_case(hook, expect_takeover): att, _ = upload(c, alice, chat, make_png(90, 70), filename="fault-%s.png" % hook) t = time.monotonic() ready = wait_status(c, alice, att["id"], ("ready", "failed"), timeout=LEASE * 3 + 30) check(ready["status"] == "ready", "not ready") e = ev(att["id"]) seq = [x[0] for x in e] committed = [x for x in e if x[0] == "committed"] check(len(committed) == 1, "committed %d times" % len(committed)) if expect_takeover: check("lease_takeover" in seq, "no takeover: %s" % seq) tok = [x[1] for x in e if x[0] in ("claimed", "lease_takeover")] check(committed[0][1] == tok[-1] and tok[0] != tok[-1], "commit token %s, claims %s" % (committed[0][1], tok)) check(sql("SELECT count(*) FROM attachment_variants WHERE attachment_id = '%s'" % att["id"]) == ["3"], "variants") wait_healthy("worker") return att["id"], seq, time.monotonic() - t @s.case("worker crash after claim, before any side effect → lease takeover → ready") def _(): aid, seq, took = crash_case("crash-before-s3", True) return "%s in %.1fs" % (seq, took) @s.case("worker crash after S3 writes, before COMMIT → takeover rewrites the same keys, one result") def _(): aid, seq, took = crash_case("crash-after-s3", True) keys = sql("SELECT object_key FROM attachment_variants WHERE attachment_id = '%s' ORDER BY name" % aid) check(len(keys) == 3 and all("/v1/" in k for k in keys), "keys %s" % keys) return "%s in %.1fs; keys deterministic: %s" % (seq, took, [k.split("/")[-1] for k in keys]) @s.case("worker crash after COMMIT, before ack → redelivery is a no-op (duplicate_ignored)") def _(): aid, seq, took = crash_case("crash-after-commit", False) wait_until(lambda: "duplicate_ignored" in names(aid), timeout=LEASE * 3 + 20, interval=1) seq = names(aid) check(seq.count("committed") == 1 and seq.count("claimed") == 1, "unexpected: %s" % seq) return "%s" % seq @s.case("hung worker (event loop blocked 45 s) loses lease; takeover commits; zombie commit is fenced") def _(): att, _ = upload(c, alice, chat, make_png(90, 90), filename="fault-hang-45.png") ready = wait_status(c, alice, att["id"], ("ready", "failed"), timeout=120) check(ready["status"] == "ready", "not ready") wait_until(lambda: "lease_lost" in names(att["id"]), timeout=60, interval=1) e = ev(att["id"]) claims = [x for x in e if x[0] in ("claimed", "lease_takeover")] commit = [x for x in e if x[0] == "committed"] lost = [x for x in e if x[0] == "lease_lost"] check(len(commit) == 1 and commit[0][1] == claims[-1][1] and lost[0][1] == claims[0][1], "tokens: claims %s commit %s lost %s" % ([x[1] for x in claims], commit[0][1], lost[0][1])) check(claims[0][2] != claims[-1][2], "takeover by the same worker?") wait_healthy("worker", timeout=90) return "claimed t%s → takeover t%s → committed t%s; zombie (t%s) → lease_lost" % ( claims[0][1], claims[-1][1], commit[0][1], lost[0][1]) @s.case("long but alive job (35 s > lease 20 s): heartbeat keeps the lease, no takeover, no duplicate") def _(): att, _ = upload(c, alice, chat, make_png(60, 40), filename="fault-slow-35.png") t = time.monotonic() ready = wait_status(c, alice, att["id"], ("ready", "failed"), timeout=120) check(ready["status"] == "ready", "not ready") seq = names(att["id"]) check(seq.count("claimed") == 1 and "lease_takeover" not in seq and seq.count("committed") == 1, "%s" % seq) return "ready after %.1fs, %s" % (time.monotonic() - t, seq) @s.case("transient errors: retry with backoff + jitter (2 failures), then ready") def _(): att, _ = upload(c, alice, chat, make_png(50, 50), filename="fault-transient-2.png") ready = wait_status(c, alice, att["id"], ("ready", "failed"), timeout=60) check(ready["status"] == "ready", "not ready") e = events(att["id"]) retries = [x for x in e if x["event"] == "retry_scheduled"] check(len(retries) == 2, "retries %d" % len(retries)) d1, d2 = retries[0]["detail"]["delay_seconds"], retries[1]["detail"]["delay_seconds"] check(1.0 <= d1 <= 2.0 and 2.0 <= d2 <= 4.0, "backoff windows: %s, %s" % (d1, d2)) claims = [x for x in e if x["event"] == "claimed"] gaps = [] for r, nxt in zip(retries, claims[1:]): import datetime as dt g = (dt.datetime.fromisoformat(nxt["created_at"]) - dt.datetime.fromisoformat(r["created_at"])).total_seconds() gaps.append(round(g, 2)) check(g >= r["detail"]["delay_seconds"] - 0.05, "retried earlier than scheduled") return "delays %.2fs, %.2fs (windows [1,2], [2,4]); actual gaps %s; attempts %s" % ( d1, d2, gaps, [x["attempt"] for x in claims]) @s.case("retries exhausted → failed retry_exhausted (in registry) → operator replay → ready") def _(): att, _ = upload(c, alice, chat, make_png(40, 40), filename="fault-transient-5.png") failed = wait_status(c, alice, att["id"], ("ready", "failed"), timeout=90) check(failed["status"] == "failed" and failed["error_code"] == "retry_exhausted", "got %s" % failed["status"]) seq = names(att["id"]) check(seq.count("claimed") == 5 and seq.count("retry_scheduled") == 4, "attempts: %s" % seq) reg = jobs_cli("failed", "--limit", "500")["failed"] check(any(r["attachment_id"] == att["id"] and r["replayable"] for r in reg), "not in registry") r = jobs_cli("replay", "--attachment", att["id"], "--reason", "fixed dependency", "--operator", "student") check(r["result"] == "replayed" and r["attempt"] == 6, "%s" % r) ready = wait_status(c, alice, att["id"], ("ready", "failed"), timeout=60) check(ready["status"] == "ready" and ready["error_code"] is None, "replay did not finish") return "5 attempts → retry_exhausted; replay (attempt 6) → ready" @s.case("processing with expired lease and LOST message → reaper requeues → ready") def _(): sh("stop_worker", timeout=120) try: att, _ = upload(c, alice, chat, make_png(55, 55), filename="reaper.png") wait_until(lambda: "published" in names(att["id"]), timeout=30) purged = jobs_cli("purge-stream")["purged"] # имитация: worker захватил работу и умер, а его сообщение брокер уже не вернёт (потеряно) sql("UPDATE attachment_jobs SET status = 'processing', claims = 1, lease_token = nextval('job_lease_token_seq')," " lease_owner = 'dead-worker', lease_until = clock_timestamp() - interval '2 minutes'" " WHERE attachment_id = '%s'" % att["id"]) sql("UPDATE attachments SET status = 'processing' WHERE id = '%s'" % att["id"]) finally: sh("start_worker", timeout=120) ready = wait_status(c, alice, att["id"], ("ready", "failed"), timeout=60) check(ready["status"] == "ready", "not ready") seq = names(att["id"]) check("requeued_expired_lease" in seq, "reaper did not act: %s" % seq) return "purged %s stream msgs; %s" % (purged, seq[-4:]) @s.case("bounded concurrency: never more than replicas × WORKER_CONCURRENCY jobs in processing") def _(): ids = [upload(c, alice, chat, make_png(30 + i, 30), filename="fault-slow-4-n%d.png" % i)[0]["id"] for i in range(8)] import datetime as dt for a in ids: wait_status(c, alice, a, ("ready", "failed"), timeout=120) spans = [] for a in ids: e = events(a) start = [x["created_at"] for x in e if x["event"] == "claimed"][0] end = [x["created_at"] for x in e if x["event"] == "committed"][0] spans.append((dt.datetime.fromisoformat(start), dt.datetime.fromisoformat(end))) points = sorted([(s0, 1) for s0, _ in spans] + [(e0, -1) for _, e0 in spans]) cur = peak = 0 for _, d in points: cur += d peak = max(peak, cur) limit = WORKERS * CONCURRENCY check(peak <= limit, "peak %d > %d" % (peak, limit)) total = (max(e0 for _, e0 in spans) - min(s0 for s0, _ in spans)).total_seconds() return "8 jobs × ~4 s: peak concurrency %d (limit %d), wall %.1fs" % (peak, limit, total) @s.case("staging removed after ready; failed staging kept until retention, then replay refuses honestly") def _(): att, _ = upload(c, alice, chat, make_png(33, 33), filename="staging.png") wait_status(c, alice, att["id"], "ready") hexid = att["id"].replace("-", "") wait_until(lambda: s3_admin("ls", "staging/" + hexid) == "", timeout=30) check(s3_admin("ls", "originals/" + hexid) != "", "original not published") bad, _ = upload(c, alice, chat, open(os.path.join(os.path.dirname(__file__), "fixtures", "sof5.jpg"), "rb").read(), "image/jpeg", "sof5-retention.jpg") wait_status(c, alice, bad["id"], "failed") bhex = bad["id"].replace("-", "") check(s3_admin("ls", "staging/" + bhex) != "", "failed staging must be kept for replay") sql("UPDATE attachments SET updated_at = clock_timestamp() - interval '2 days' WHERE id = '%s'" % bad["id"]) wait_until(lambda: s3_admin("ls", "staging/" + bhex) == "", timeout=30) r = jobs_cli("replay", "--attachment", bad["id"], "--reason", "too late") check(r["result"] == "refused", "replay after retention: %s" % r) return "ready: staging gone, originals/ present; failed: staging kept, removed after retention; replay %s" % r["result"] s.run()