ЛР6: OpenTelemetry, Collector, Prometheus/Loki/Tempo, Grafana, SLO и алерты, инциденты

This commit is contained in:
kalibr456
2026-11-01 21:25:38 +03:00
parent 470d9d6f1e
commit 79ef8807d5
156 changed files with 18393 additions and 35 deletions
+567
View File
@@ -0,0 +1,567 @@
"""Lab5: асинхронная обработка вложений — варианты, сохранность, отказы, повторы, DLQ, replay.
Нужен запущенный стенд из compose.yaml с FAULT_INJECTION=1 (по умолчанию на учебном стенде).
Тест управляет только своими синтетическими данными и сервисами через `docker compose stop|start|restart`,
volumes не удаляет. Сбои внедряются файлами в volume faults (faults.py), SQL — только чтение.
python student-tests/test_jobs.py [сценарий ...] # без аргументов — все по порядку
Сценарии: variants limits worker-down broker-down outbox-crash crash-after-put crash-after-commit
lease retry exhausted-replay permanent concurrency dlq
"""
import base64
import json
import sys
import time
import urllib.parse
from pathlib import Path
from common import (call, check, compose, compose_output, new_chat, new_user, post_message, psql, run_tests,
send, sql_value, wait_ready)
HERE = Path(__file__).resolve().parent
PROBE = (HERE / "worker_probe.py").read_text(encoding="utf-8")
FINAL_KEYS = ["v1/crop.jpg", "v1/optimized.webp", "v1/original", "v1/thumbnail.jpg"]
LEASE = 15 # JOB_LEASE_SECONDS стенда
TIMEOUT = 60 # JOB_TIMEOUT_SECONDS стенда
MAX_ATTEMPTS = 5 # JOB_MAX_ATTEMPTS стенда
STATE = {}
# ---------- инфраструктура ----------
def in_container(service, code, *args):
"""python - <args> в контейнере service, код через stdin. Последняя строка stdout — JSON.
Если service остановлен (сценарии с выключенным worker) — в одноразовом контейнере того же сервиса."""
import subprocess
from common import ROOT
running = subprocess.run(["docker", "compose", "ps", "--status", "running", "-q", service], cwd=ROOT,
capture_output=True, check=False).stdout.strip()
launch = (["exec", "-T", service, "python"] if running
else ["run", "--rm", "--no-deps", "-T", "--entrypoint", "python", service])
result = subprocess.run(["docker", "compose", *launch, "-", *map(str, args)], cwd=ROOT,
input=code.encode("utf-8"), capture_output=True, check=False)
check(result.returncode == 0, f"{service}: {result.stderr.decode('utf-8', 'replace')[-500:]}")
return json.loads(result.stdout.decode("utf-8").strip().splitlines()[-1])
def probe(*args):
return in_container("worker", PROBE, *args)
def ops(*args):
import subprocess
from common import ROOT
result = subprocess.run(["docker", "compose", "exec", "-T", "dispatcher", "python", "ops.py", *map(str, args)],
cwd=ROOT, capture_output=True, check=False)
check(result.returncode == 0, f"ops {args[0]}: {result.stderr.decode('utf-8', 'replace')[-400:]}")
return json.loads(result.stdout.decode("utf-8"))
def fault(point, times=1):
"""Взвести точку сбоя: times файлов /faults/<point>.<n> (каждое срабатывание удаляет один файл)."""
code = ("import pathlib, sys, time\n"
"for n in range(int(sys.argv[2])):\n"
" pathlib.Path('/faults', f'{sys.argv[1]}.{time.time_ns()}_{n}').touch()\n"
"print('{}')\n")
in_container("worker", code, point, times)
def clear_faults():
code = "import pathlib\nfor p in pathlib.Path('/faults').glob('*'):\n p.unlink()\nprint('{}')\n"
in_container("worker", code)
def image(kind):
return base64.b64decode(probe("make", kind)["b64"])
def user_and_chat():
if "alice" not in STATE:
STATE["alice"] = new_user("alice")
STATE["bob"] = new_user("bob")
STATE["chat"] = new_chat(STATE["alice"], STATE["bob"], title="Lab5 jobs")
return STATE["alice"], STATE["bob"], STATE["chat"]
def upload(data, content_type="image/png", filename="probe.png", expected=202):
alice, _bob, chat = user_and_chat()
query = "?filename=" + urllib.parse.quote(filename, safe="")
att = call("POST", f"/api/v1/chats/{chat['id']}/attachments{query}", expected, raw=data, token=alice["token"],
headers={"Content-Type": content_type}, timeout=60).json
if expected == 202:
check(att["status"] == "queued" and att["variants"] == [] and att["error_code"] is None,
f"202 must be a queued snapshot, got {att['status']}")
return att
def get(att_id, user=None):
user = user or STATE["alice"]
return call("GET", f"/api/v1/attachments/{att_id}", 200, token=user["token"]).json
def wait_status(att_id, statuses, seconds=60):
statuses = (statuses,) if isinstance(statuses, str) else statuses
deadline = time.monotonic() + seconds
while True:
att = get(att_id)
if att["status"] in statuses:
return att
check(time.monotonic() < deadline, f"{att_id[:8]}: still {att['status']} after {seconds} s")
time.sleep(0.3)
def content(att_id, variant="original", expected=200):
return call("GET", f"/api/v1/attachments/{att_id}/content?variant={variant}", expected,
token=STATE["bob"]["token"])
def job(att_id):
rows = sql_value(f"SELECT job_id || '|' || status || '|' || attempt || '|' || coalesce(error_code, '-') "
f"FROM attachment_jobs WHERE attachment_id = '{att_id}'")
check(rows and "\n" not in rows, f"expected exactly one job for {att_id}")
job_id, status, attempt, error = rows.split("|")
return {"job_id": job_id, "status": status, "attempt": int(attempt), "error_code": error}
def events(job_id):
out = sql_value(f"SELECT attempt || ':' || event || ':' || coalesce(detail, '') FROM job_events "
f"WHERE job_id = '{job_id}' ORDER BY id")
return out.splitlines() if out else []
def names(evs):
return [e.split(":")[1] for e in evs]
def assert_one_result(att_id, label=""):
"""Инвариант идемпотентности: ровно один набор вариантов и ровно 4 объекта под конечным prefix."""
info = probe("inspect", att_id)
check(info["state"] == "ready", f"{label}: not ready in DB")
check(info["variant_rows"] == 3, f"{label}: {info['variant_rows']} variant rows, expected 3")
check(info["final_keys"] == FINAL_KEYS, f"{label}: final objects {info['final_keys']}")
check(info["original_sha_ok"] and info["original_size_ok"], f"{label}: original differs from upload")
check(all(v["sha_ok"] and v["meta_size_ok"] for v in info["variants"].values()), f"{label}: variant mismatch")
return info
def outbox_rows(job_id):
out = sql_value(f"SELECT attempt || ':' || (published_at IS NOT NULL) FROM outbox WHERE job_id = '{job_id}' "
f"ORDER BY id")
return out.splitlines() if out else []
def queue_depth():
out = compose_output("exec", "-T", "rabbitmq", "rabbitmqctl", "-q", "list_queues", "-p", "messenger",
"name", "messages", "messages_unacknowledged")
depth = {}
for line in out.splitlines():
parts = line.split()
if len(parts) == 3 and parts[1].isdigit():
depth[parts[0]] = (int(parts[1]), int(parts[2]))
return depth
def log(text):
print(text, flush=True)
# ---------- сценарии ----------
def test_variants():
"""thumbnail/crop/optimized по контракту, EXIF orientation, alpha -> белый, без увеличения, без метаданных."""
alice, bob, chat = user_and_chat()
cases = {
"thumb320": ("image/png", {"thumbnail": [256, 160], "crop": [128, 128], "optimized": [320, 200]}),
"exif6": ("image/jpeg", {"thumbnail": [192, 256], "crop": [128, 128], "optimized": [300, 400]}),
"alpha": ("image/png", {"thumbnail": [256, 170], "crop": [128, 128], "optimized": [300, 200]}),
"tiny": ("image/png", {"thumbnail": [40, 30], "crop": [128, 128], "optimized": [40, 30]}),
"large": ("image/jpeg", {"thumbnail": [256, 170], "crop": [128, 128], "optimized": [1280, 853]}),
"strip": ("image/png", {"thumbnail": [256, 1], "crop": [128, 128], "optimized": [1280, 1]}),
}
for kind, (ctype, sizes) in cases.items():
data = image(kind)
att = upload(data, ctype, f"{kind}.{'jpg' if ctype == 'image/jpeg' else 'png'}")
ready = wait_status(att["id"], "ready")
meta = {v["name"]: v for v in ready["variants"]}
check(set(meta) == {"thumbnail", "crop", "optimized"}, f"{kind}: variants {sorted(meta)}")
for name, size in sizes.items():
check([meta[name]["width"], meta[name]["height"]] == size,
f"{kind}/{name}: {meta[name]['width']}x{meta[name]['height']}, expected {size}")
check(meta["thumbnail"]["content_type"] == "image/jpeg" and meta["crop"]["content_type"] == "image/jpeg"
and meta["optimized"]["content_type"] == "image/webp", f"{kind}: wrong variant content types")
original = content(att["id"])
check(original.data == data, f"{kind}: original is not byte-identical")
for name in ("thumbnail", "crop", "optimized"):
reply = content(att["id"], name)
check(reply.headers["content-type"] == meta[name]["content_type"], f"{kind}/{name}: Content-Type")
info = assert_one_result(att["id"], kind)
for name, v in info["variants"].items():
check(v["exif_tags"] == 0 and not v["has_xmp"], f"{kind}/{name}: metadata not stripped")
if kind == "exif6":
top = info["variants"]["thumbnail"]["pixel_top_center"]
check(top[0] > 200 and top[1] < 60, f"exif6: orientation not applied, top pixel {top}")
if kind == "alpha":
left = info["variants"]["thumbnail"]["pixel_left_center"]
right = info["variants"]["thumbnail"]["pixel_right_center"]
check(left[:3] == [255, 255, 255] and right[2] > 200, f"alpha: not composited on white {left} {right}")
check(info["variants"]["optimized"]["mode"] == "RGBA", "alpha: optimized WebP lost transparency")
log(f"{kind}: " + ", ".join(f"{n} {s[0]}x{s[1]}" for n, s in sizes.items())
+ f"; original byte-identical; EXIF/XMP in variants: 0; S3 keys {info['final_keys']}")
# Отсутствующий вариант у ready -> 404 (нет такого имени в контракте -> 400), queued -> 409 проверяется ниже.
content(att["id"], "unknown", expected=400)
log("unknown variant name -> 400; variants carry their own size/sha256, original fields describe the upload")
def test_limits():
"""Лимиты: bytes и пиксели на API; память/пиксели/время процесса обработки на worker."""
alice, _bob, chat = user_and_chat()
big = b"\x89PNG\r\n\x1a\n" + b"\0" * (10 * 1024 * 1024)
call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=big.png", 413, raw=big, token=alice["token"],
headers={"Content-Type": "image/png"}, timeout=60)
log("10 MiB + 8 bytes -> 413 before any job is created")
report = probe("imaging-limits")
at, over = report["at_limit_40mpx"], report["over_limit_max_10mpx"]
check(at["exit_code"] == 0, f"40 Mpx PNG at the limit must be processed, exit {at['exit_code']}")
check(over["exit_code"] == 4, f"worker-side pixel limit must reject (exit 4), got {over['exit_code']}")
check(at["peak_rss_mib_max_children"] < report["memory_limit_mib"],
f"peak RSS {at['peak_rss_mib_max_children']} MiB exceeds RLIMIT_AS {report['memory_limit_mib']} MiB")
log(f"imaging.py on 8000x5000 PNG: exit 0, peak RSS {at['peak_rss_mib_max_children']} MiB "
f"(RLIMIT_AS {report['memory_limit_mib']} MiB); same file with MAX_IMAGE_PIXELS=10M -> exit 4 (image_too_large)")
# Память: процесс обработки упирается в RLIMIT_AS -> MemoryError -> постоянная ошибка resource_limit.
fault("imaging_oom")
att = upload(image("thumb320"), filename="oom.png")
failed = wait_status(att["id"], ("failed", "ready"), 60)
check(failed["status"] == "failed" and failed["error_code"] == "resource_limit",
f"oom: expected failed/resource_limit, got {failed['status']}/{failed['error_code']}")
j = job(att["id"])
check(j["attempt"] == 1, "resource_limit is permanent: no retries expected")
log(f"memory bomb in the imaging process -> failed/resource_limit after attempt 1; worker itself survived")
STATE["oom_job"] = j["job_id"]
# Время: зависший процесс обработки убивается по JOB_TIMEOUT_SECONDS -> временная ошибка -> retry -> ready.
fault("imaging_hang")
att = upload(image("thumb320"), filename="hang.png")
started = time.monotonic()
ready = wait_status(att["id"], "ready", TIMEOUT + 40)
j = job(att["id"])
evs = events(j["job_id"])
check("lease_expired" not in names(evs), f"a long-running (alive) attempt must keep its lease: {evs}")
check(any("processing_timeout" in e for e in evs) and j["attempt"] == 2, f"timeout not handled as retry: {evs}")
log(f"imaging hang -> killed after {TIMEOUT} s (processing_timeout, temporary), lease renewed meanwhile "
f"(no lease_expired), attempt 2 ready after {time.monotonic() - started:.0f} s")
def test_worker_down():
"""Защита п.2-3: worker остановлен -> 202 -> сообщение с вложением -> рестарт API+broker -> worker -> ready."""
alice, bob, chat = user_and_chat()
compose("stop", "worker")
log("worker stopped")
data = image("thumb320")
att = upload(data, filename="offline.png")
log(f"upload while worker is down -> 202 queued, attachment {att['id']}")
j = job(att["id"])
source_key = sql_value(f"SELECT source_key FROM attachments WHERE id = '{att['id']}'")
check(source_key.startswith("staging/"), "source must be in the durable staging prefix")
check(probe("exists", source_key)["exists"], "staging object must exist before 202")
msg = post_message(alice, chat["id"], "photo while worker is down", [att["id"]]).json
check(msg["attachment_ids"] == [att["id"]], "message must reference the queued attachment")
content(att["id"], expected=409)
content(att["id"], "thumbnail", expected=409)
send(bob, chat["id"], "other messages keep working")
deadline = time.monotonic() + 10
while outbox_rows(j["job_id"]) != ["1:true"]:
check(time.monotonic() < deadline, "dispatcher did not publish the job")
time.sleep(0.2)
deadline = time.monotonic() + 15 # счётчики quorum-очереди в rabbitmqctl обновляются раз в несколько секунд
while (queue_depth().get("attachments.process.v1") or (0, 0))[0] < 1:
check(time.monotonic() < deadline, "published message is not visible in the queue")
time.sleep(0.5)
depth = queue_depth().get("attachments.process.v1")
log(f"message with attachment 201, content 409, other messages 201; job {j['job_id']} published, "
f"queue messages/unacked = {depth}")
compose("restart", "rabbitmq")
compose("restart", "api")
wait_ready()
depth_after = queue_depth().get("attachments.process.v1")
check(depth_after and depth_after[0] >= 1, f"message lost after broker restart: {depth_after}")
check(get(att["id"])["status"] == "queued", "job must still be queued after restarts")
log(f"rabbitmq and api restarted with volumes; queue still holds {depth_after[0]} message(s); status queued")
compose("start", "worker")
ready = wait_status(att["id"], "ready", 60)
j2 = job(att["id"])
check(j2["job_id"] == j["job_id"] and j2["status"] == "ready", "same job_id must finish")
thumb = content(att["id"], "thumbnail")
check(len(thumb.data) == {v["name"]: v for v in ready["variants"]}["thumbnail"]["size_bytes"], "thumbnail size")
info = assert_one_result(att["id"], "worker-down")
check(not info["staging_present"] and not probe("exists", source_key)["exists"],
"staging must be cleaned after the safe commit")
log(f"worker started -> same job {j['job_id']} ready, thumbnail downloadable; staging object deleted")
def test_broker_down():
"""Брокер недоступен: API принимает (outbox), dispatcher копит и публикует после восстановления."""
compose("stop", "rabbitmq")
log("rabbitmq stopped")
att = upload(image("thumb320"), filename="no-broker.png")
call("GET", "/health/ready", 200)
j = job(att["id"])
time.sleep(3)
check(outbox_rows(j["job_id"]) == ["1:false"], "outbox row must wait while the broker is down")
log(f"upload -> 202 and /health/ready 200 without broker; outbox row pending for job {j['job_id']}")
compose("start", "rabbitmq")
wait_status(att["id"], "ready", 90)
check(outbox_rows(j["job_id"]) == ["1:true"], "outbox row must be published after recovery")
assert_one_result(att["id"], "broker-down")
log("rabbitmq started -> dispatcher published the pending row -> ready")
def test_outbox_crash():
"""Разрыв COMMIT/publish: dispatcher падает после COMMIT задания до publish и после confirm до отметки."""
fault("dispatcher_crash_before_publish")
att = upload(image("thumb320"), filename="crash-before-publish.png")
ready = wait_status(att["id"], "ready", 60)
j = job(att["id"])
logs = compose_output("logs", "--tail", "400", "dispatcher")
check("FAULT INJECTION: dispatcher_crash_before_publish" in logs, "fault did not fire")
check(outbox_rows(j["job_id"]) == ["1:true"] and j["attempt"] == 1, "outbox must publish exactly the same job")
assert_one_result(att["id"], "crash-before-publish")
log(f"dispatcher killed between COMMIT and publish; restarted by policy, outbox re-published -> job "
f"{j['job_id']} ready, attempt 1, no manual action")
fault("dispatcher_crash_after_confirm")
att = upload(image("thumb320"), filename="crash-after-confirm.png")
wait_status(att["id"], "ready", 60)
j = job(att["id"])
deadline = time.monotonic() + 20
while "duplicate_ignored" not in names(events(j["job_id"])):
check(time.monotonic() < deadline, f"duplicate delivery not observed: {events(j['job_id'])}")
time.sleep(0.3)
assert_one_result(att["id"], "crash-after-confirm")
log(f"dispatcher killed after publisher confirm, before marking outbox -> message published twice; "
f"worker: {names(events(j['job_id']))} -> one result set")
def test_crash_after_put():
"""Worker падает после записи объектов в S3, до COMMIT/ack: повтор завершает тот же результат."""
fault("worker_crash_after_put")
att = upload(image("thumb320"), filename="crash-after-put.png")
wait_status(att["id"], "ready", LEASE + 40)
j = job(att["id"])
evs = events(j["job_id"])
check(names(evs).count("claimed") == 2 and "lease_expired" in names(evs), f"unexpected history {evs}")
assert_one_result(att["id"], "crash-after-put")
log(f"worker killed after S3 PUT (before COMMIT and ack): redelivery saw a live lease (no-op), lease expired "
f"after {LEASE} s, attempt {j['attempt']} rewrote the same keys -> one set; events {names(evs)}")
def test_crash_after_commit():
"""Worker падает после COMMIT результата, до ack: повторная доставка ready-задачи — no-op с ack."""
fault("worker_crash_after_commit")
att = upload(image("thumb320"), filename="crash-after-commit.png")
wait_status(att["id"], "ready", 30)
j = job(att["id"])
deadline = time.monotonic() + 30
while "duplicate_ignored" not in names(events(j["job_id"])):
check(time.monotonic() < deadline, f"redelivery not observed: {events(j['job_id'])}")
time.sleep(0.3)
evs = events(j["job_id"])
check(names(evs).count("ready") == 1 and j["attempt"] == 1, f"ready must be recorded once: {evs}")
assert_one_result(att["id"], "crash-after-commit")
deadline = time.monotonic() + 20 # счётчики quorum-очереди обновляются с задержкой
while queue_depth().get("attachments.process.v1") != (0, 0):
check(time.monotonic() < deadline, f"message left in the queue: {queue_depth()}")
time.sleep(0.5)
log(f"worker killed after COMMIT, before ack: broker redelivered, worker acked as no-op ({evs[-1]}); "
f"queue empty (0 ready, 0 unacked)")
STATE["staging_check"] = att["id"]
def test_lease():
"""Зависший worker: аренда не продлевается -> dispatcher возвращает job -> другой поток завершает;
результат зависшего отклоняется fencing-токеном, ready не откатывается."""
fault("worker_freeze")
att = upload(image("thumb320"), filename="frozen.png")
started = time.monotonic()
wait_status(att["id"], "ready", LEASE + 40)
took = time.monotonic() - started
j = job(att["id"])
deadline = time.monotonic() + 3 * LEASE + 20
while "stale_result_rejected" not in names(events(j["job_id"])):
check(time.monotonic() < deadline, f"stale result of the frozen attempt not seen: {events(j['job_id'])}")
time.sleep(0.5)
evs = events(j["job_id"])
check(get(att["id"])["status"] == "ready", "late result must not roll ready back")
check(names(evs).count("ready") == 1, f"exactly one ready: {evs}")
assert_one_result(att["id"], "lease")
log(f"frozen attempt 1 stopped renewing; lease expired, recovered by dispatcher, attempt 2 ready after "
f"{took:.0f} s; frozen attempt woke up -> stale_result_rejected; events {names(evs)}")
def test_retry():
"""Временные ошибки S3: backoff с jitter, затем ready; задержки видны в журнале."""
fault("worker_s3_error", 2)
att = upload(image("thumb320"), filename="retry.png")
wait_status(att["id"], "ready", 60)
j = job(att["id"])
evs = [e for e in events(j["job_id"]) if ":retry_scheduled:" in e]
check(len(evs) == 2 and j["attempt"] == 3, f"expected 2 retries, got {evs}")
delays = [float(e.split("delay=")[1].rstrip("s")) for e in evs]
check(1.0 <= delays[0] <= 2.0 and 2.0 <= delays[1] <= 4.0, f"backoff out of range: {delays}")
assert_one_result(att["id"], "retry")
log(f"2 x storage_unavailable -> retries after {delays[0]:.2f} s and {delays[1]:.2f} s (equal jitter: "
f"1..2 s, 2..4 s), attempt 3 ready")
def test_exhausted_replay():
"""Исчерпание попыток -> failed/retry_exhausted, реестр failed, явный replay; replay ready — отказ."""
alice, _bob, chat = user_and_chat()
fault("worker_s3_error", MAX_ATTEMPTS)
att = upload(image("thumb320"), filename="exhausted.png")
failed = wait_status(att["id"], ("failed", "ready"), 120)
check(failed["status"] == "failed" and failed["error_code"] == "retry_exhausted",
f"expected failed/retry_exhausted, got {failed['status']}/{failed['error_code']}")
j = job(att["id"])
check(j["attempt"] == MAX_ATTEMPTS, f"attempts {j['attempt']}")
content(att["id"], expected=409)
post_message(alice, chat["id"], "", [att["id"]], expected=409)
registry = {row["job_id"]: row for row in ops("failed")}
check(registry.get(j["job_id"], {}).get("replayable") is True, "failed job must be in the registry")
log(f"{MAX_ATTEMPTS} temporary errors -> failed/retry_exhausted (public error_code), content 409, "
f"attach 409, listed by ops.py failed (replayable)")
replay = ops("replay", j["job_id"], "--reason", "s3 recovered")
check("replayed" in replay, f"replay refused: {replay}")
wait_status(att["id"], "ready", 60)
assert_one_result(att["id"], "replay")
j2 = job(att["id"])
refused = ops("replay", j["job_id"])
check("refused" in refused, "replay of a ready job must be refused")
again = job(att["id"])
check(again == j2, "refused replay must not change the job")
check(names(events(j["job_id"])).count("replayed") == 1, "audit must contain the replay once")
log(f"ops replay -> same job_id {j['job_id']} attempt {j2['attempt']} ready; second replay refused: "
f"\"{refused['refused']}\"")
def test_permanent():
"""Постоянная ошибка (битое изображение в worker) -> failed сразу, без повторов."""
fault("imaging_invalid")
att = upload(image("thumb320"), filename="invalid.png")
failed = wait_status(att["id"], ("failed", "ready"), 30)
check(failed["status"] == "failed" and failed["error_code"] == "invalid_image", f"got {failed}")
j = job(att["id"])
check(j["attempt"] == 1 and "retry_scheduled" not in names(events(j["job_id"])), "no retries for permanent")
log("invalid image in the worker -> failed/invalid_image at attempt 1, no retry (permanent error)")
def test_concurrency():
"""Ограниченная конкуренция: WORKER_CONCURRENCY потребителей с prefetch=1; одновременно processing <= 2."""
out = compose_output("exec", "-T", "rabbitmq", "rabbitmqctl", "-q", "list_consumers", "-p", "messenger",
"queue_name", "prefetch_count", "ack_required")
lines = [line.split() for line in out.splitlines() if line.strip()]
header = lines[0] if lines and lines[0][0] == "queue_name" else ["queue_name", "prefetch_count", "ack_required"]
consumers = [dict(zip(header, line)) for line in lines if line[0] == "attachments.process.v1"]
check(len(consumers) == 2 and all(c["prefetch_count"] == "1" and c["ack_required"] == "true"
for c in consumers), f"consumers {out}")
# Копим очередь при остановленном worker, затем запускаем: работы больше, чем потоков.
compose("stop", "worker")
data = image("large")
ids = [upload(data, "image/jpeg", f"burst{n}.jpg")["id"] for n in range(8)]
id_list = ", ".join(f"'{i}'" for i in ids)
compose("start", "worker")
started = time.monotonic()
peak, samples = 0, 0
while True:
busy, ready = map(int, sql_value(
f"SELECT count(*) FILTER (WHERE status = 'processing') || '|' || count(*) FILTER (WHERE status = 'ready') "
f"FROM attachment_jobs WHERE attachment_id IN ({id_list})").split("|"))
peak, samples = max(peak, busy), samples + 1
if ready == len(ids):
break
check(time.monotonic() - started < 120, "burst not processed in 120 s")
time.sleep(0.05)
took = time.monotonic() - started
check(peak == 2, f"peak {peak} jobs in processing, expected exactly WORKER_CONCURRENCY=2")
log(f"2 consumers, prefetch_count 1, manual ack; 8 queued 3000x2000 JPEG drained in {took:.1f} s after "
f"worker start, peak processing {peak} of 8 ({samples} samples)")
def test_dlq():
"""Невалидные сообщения и сообщения о неизвестной job -> DLQ; dlq-replay их не исполняет."""
publish = r'''
import json, sys, uuid
import broker, pipeline
p = broker.Publisher()
p.open().basic_publish(pipeline.EXCHANGE, pipeline.ROUTING_KEY, b'{"not":"a job"}', mandatory=True)
p.publish(pipeline.build_message(uuid.uuid4(), uuid.uuid4(), 1, 1, None))
p.close()
print("{}")
'''
before = queue_depth().get("attachments.process.v1.dlq", (0, 0))[0]
in_container("dispatcher", publish)
deadline = time.monotonic() + 15
while queue_depth().get("attachments.process.v1.dlq", (0, 0))[0] < before + 2:
check(time.monotonic() < deadline, "messages did not reach the DLQ")
time.sleep(0.3)
peek = ops("dlq", "--limit", "50")
reasons = {(m["invalid"] is not None, m["dead_letter_reason"]) for m in peek}
check((True, "rejected") in reasons, f"invalid message not in DLQ: {peek}")
replayed = ops("dlq-replay", "--limit", "50")
kept = [m for m in replayed if m["action"] == "keep"]
check(len(kept) >= 2, "invalid/unknown messages must be kept, not executed")
after = queue_depth().get("attachments.process.v1.dlq", (0, 0))[0]
check(after >= before + 2, "dlq-replay must not drop messages it cannot handle")
log(f"schema-invalid message and unknown job_id -> reject -> DLQ ({after} message(s)); "
f"dlq-replay kept them: {[m['note'] for m in kept][:2]}")
def test_staging_cleanup():
"""Janitor доделывает очистку staging, если worker упал до неё (после crash-after-commit)."""
att_id = STATE.get("staging_check")
if not att_id:
log("skip: run crash-after-commit first")
return
key = sql_value(f"SELECT coalesce(source_key, '') FROM attachments WHERE id = '{att_id}'")
if key:
log(f"staging source still present after the crash (worker died before cleanup); waiting 60 s window")
time.sleep(62)
from common import janitor
report = janitor()
# фоновый janitor (проход раз в JANITOR_INTERVAL_SECONDS) мог успеть первым в окне 62 с — проверяем результат
left = sql_value(f"SELECT coalesce(source_key, '') FROM attachments WHERE id = '{att_id}'")
check(not left, f"staging source still referenced: {report}")
check(not probe("exists", key)["exists"], "staging object must be gone")
by = "this pass" if report["staging_ready_deleted"] else "the background janitor pass"
log(f"janitor removed the staging source of the ready attachment ({by}); source_key NULL, object gone")
else:
log("staging already cleaned by the worker")
SCENARIOS = {
"variants": test_variants, "limits": test_limits, "worker-down": test_worker_down,
"broker-down": test_broker_down, "outbox-crash": test_outbox_crash, "crash-after-put": test_crash_after_put,
"crash-after-commit": test_crash_after_commit, "staging": test_staging_cleanup, "lease": test_lease,
"retry": test_retry, "exhausted-replay": test_exhausted_replay, "permanent": test_permanent,
"concurrency": test_concurrency, "dlq": test_dlq,
}
def main():
chosen = sys.argv[1:] or list(SCENARIOS)
wait_ready()
clear_faults()
tests = []
for name in chosen:
def run(name=name):
log(f"--- {name}: {SCENARIOS[name].__doc__.splitlines()[0]}")
try:
SCENARIOS[name]()
finally:
compose("start", "worker") # идемпотентно: стенд остаётся рабочим даже после FAIL
compose("start", "rabbitmq")
run.__name__ = name
tests.append(run)
run_tests(tests)
if __name__ == "__main__":
main()