Files
mtusi2026lab5/src/jobs.py
T
zemiles 13bec4ab8b ЛР 5 — БПИ2303 — Лазарев — на 4
Асинхронная обработка вложений: RabbitMQ 4.1 (quorum-очереди, publisher
confirms, manual ack, DLQ), transactional outbox, отдельный worker.

- upload: оригинал в staging S3, затем одной транзакцией queued + jobs +
  outbox -> 202; API к брокеру не подключается
- relay: публикация outbox с confirm, reaper истёкших аренд, redrive
- worker: claim по строке jobs, аренда с heartbeat и fencing по
  lease_token, transform в подпроцессе с RLIMIT_AS/RLIMIT_CPU/таймаутом,
  thumbnail 256, crop 128, WebP 1280 по детерминированным ключам
- retry с backoff и jitter, постоянные/временные ошибки, реестр failed,
  ops replay (ready не повторяется), DLQ для невалидных сообщений
- janitor: очистка staging и сирот; миграция 004 с backfill вложений lab4
- тесты отказов: окна COMMIT/publish, крахи worker до/после S3 и ack,
  заморозка worker, всплеск загрузок, права брокера; evidence/ и REPORT.md
2026-11-13 16:28:18 +03:00

365 lines
22 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Задания обработки вложений: схема сообщения, переходы состояний, retry, lease, replay.
Используется API (постановка в очередь), worker, relay (reaper) и ops-CLI. Все переходы —
SQL-транзакции над строкой jobs под FOR UPDATE, поэтому решение «что делать с сообщением»
принимается по устойчивому состоянию в PostgreSQL, а не по факту доставки.
Сообщение брокера (contracts/jobs.schema.json) — только ссылка: job_id, attachment_id,
pipeline_version, attempt. Bytes, credentials, URL и ключи S3 в сообщение не попадают:
worker берёт доверенные storage metadata из БД.
Переходы (contracts/attachment-states.md):
enqueue нет -> queued API, одна транзакция с outbox
claim queued -> processing worker: attempt+1, lease_owner/token/until
heartbeat processing (продление) worker, только со своим lease_token
complete processing -> ready worker, только со своим lease_token (fencing)
retry processing -> queued временная ошибка, backoff + jitter, outbox с available_at
fail processing -> failed постоянная ошибка или исчерпаны попытки
lease expired processing -> queued reaper (relay), если аренду никто не продлил
replay failed -> queued оператор (ops.py), audit, ready не трогается
"""
import datetime as dt
import json
import random
import uuid
SCHEMA_VERSION = 1
JOB_TYPE = "attachment.process.v1"
VARIANT_NAMES = ("thumbnail", "crop", "optimized")
# Постоянные ошибки: повтор не поможет (тот же вход даст тот же результат).
PERMANENT_ERRORS = {"invalid_image", "image_too_large", "staging_corrupted", "staging_missing",
"resource_limit"}
_UUID_FIELDS = ("job_id", "attachment_id")
_ALLOWED = {"schema_version", "job_id", "type", "attachment_id", "pipeline_version", "attempt",
"created_at", "traceparent", "tracestate"}
class InvalidMessage(Exception):
"""Сообщение не соответствует jobs.schema.json -> reject в DLQ."""
def utc_now_text():
return dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def make_payload(job_id, attachment_id, pipeline_version, attempt, created_at=None):
return {
"schema_version": SCHEMA_VERSION,
"job_id": str(job_id),
"type": JOB_TYPE,
"attachment_id": str(attachment_id),
"pipeline_version": int(pipeline_version),
"attempt": int(attempt),
"created_at": created_at or utc_now_text(),
}
def parse_message(body):
"""bytes -> dict по jobs.schema.json (без внешних библиотек). Иначе InvalidMessage."""
try:
msg = json.loads(body.decode("utf-8"))
except (UnicodeDecodeError, ValueError):
raise InvalidMessage("not json")
if not isinstance(msg, dict):
raise InvalidMessage("not object")
if set(msg) - _ALLOWED:
raise InvalidMessage("extra fields")
for field in ("schema_version", "job_id", "type", "attachment_id", "pipeline_version", "attempt", "created_at"):
if field not in msg:
raise InvalidMessage("missing " + field)
if msg["schema_version"] != SCHEMA_VERSION or msg["type"] != JOB_TYPE:
raise InvalidMessage("unsupported type/version")
for field in _UUID_FIELDS:
try:
if not isinstance(msg[field], str):
raise ValueError
uuid.UUID(msg[field])
except ValueError:
raise InvalidMessage("bad " + field)
for field in ("pipeline_version", "attempt"):
v = msg[field]
if not isinstance(v, int) or isinstance(v, bool) or v < 1:
raise InvalidMessage("bad " + field)
if not isinstance(msg["created_at"], str):
raise InvalidMessage("bad created_at")
try:
dt.datetime.fromisoformat(msg["created_at"].replace("Z", "+00:00"))
except ValueError:
raise InvalidMessage("bad created_at")
return msg
def backoff_seconds(attempt, base, cap, rng=random):
"""Экспоненциальный backoff с «equal jitter»: d = min(cap, base*2^(attempt-1)),
задержка равномерно в [d/2, d]. Половина гарантирует паузу (не долбим упавший S3),
случайная половина разносит повторы многих заданий во времени (нет «стада»)."""
d = min(float(cap), float(base) * (2 ** max(0, attempt - 1)))
return d / 2 + rng.uniform(0, d / 2)
def add_event(conn, job_id, event, attempt=None, actor=None, detail=None):
conn.execute(
"INSERT INTO job_events (job_id, event, attempt, actor, detail) VALUES (%s, %s, %s, %s, %s)",
(job_id, event, attempt, actor, json.dumps(detail, ensure_ascii=False) if detail is not None else None))
def add_outbox(conn, job_id, attachment_id, pipeline_version, attempt, delay_seconds=0.0):
payload = make_payload(job_id, attachment_id, pipeline_version, attempt)
conn.execute(
"""INSERT INTO outbox (job_id, payload, available_at)
VALUES (%s, %s, now() + make_interval(secs => %s))""",
(job_id, json.dumps(payload), delay_seconds))
return payload
# ---------------------------------------------------------------------------
# API: постановка в очередь
# ---------------------------------------------------------------------------
def enqueue(conn, attachment_id, pipeline_version, max_attempts):
"""В ТЕКУЩЕЙ транзакции: pending -> queued, jobs, outbox, событие. job_id или None."""
row = conn.execute(
"""UPDATE attachments SET status = 'queued', updated_at = now()
WHERE id = %s AND status = 'pending' RETURNING id""", (attachment_id,)).fetchone()
if row is None:
return None
job_id = uuid.uuid4()
conn.execute(
"""INSERT INTO jobs (id, attachment_id, pipeline_version, status, attempt, max_attempts,
next_attempt_at, created_at, updated_at)
VALUES (%s, %s, %s, 'queued', 0, %s, now(), now(), now())""",
(job_id, attachment_id, pipeline_version, max_attempts))
add_event(conn, job_id, "enqueued", 1, "api")
add_outbox(conn, job_id, attachment_id, pipeline_version, 1)
return job_id
# ---------------------------------------------------------------------------
# Worker
# ---------------------------------------------------------------------------
JOB_COLUMNS = """j.id AS job_id, j.attachment_id, j.pipeline_version, j.status AS job_status, j.attempt,
j.max_attempts, j.next_attempt_at, j.error_code, j.lease_owner, j.lease_token, j.lease_until, j.replay_count,
j.lease_until > now() AS lease_alive, j.next_attempt_at > now() + interval '1 second' AS too_early,
a.status AS attachment_status, a.content_type, a.size_bytes, a.sha256, a.width, a.height,
a.object_key, a.staging_key, a.filename, a.pipeline_version AS current_pipeline_version"""
def load_job(conn, job_id, lock=False):
return conn.execute(
"SELECT " + JOB_COLUMNS + " FROM jobs j JOIN attachments a ON a.id = j.attachment_id WHERE j.id = %s"
+ (" FOR UPDATE OF j" if lock else ""), (job_id,)).fetchone()
def _owner_host(owner):
return (owner or "").split(":", 1)[0]
def claim(conn, msg, owner, lease_seconds):
"""Решение по сообщению. Возвращает (action, job):
'process' — аренда взята (job со свежим lease_token), можно работать;
'ack' — ничего делать не нужно (уже ready/failed, занято живой арендой, ранний дубль);
'reject' — сообщение не соответствует заданию (в DLQ, разбирает оператор).
Вызывается в транзакции; при 'process' коммит фиксирует processing ДО начала работы."""
job = load_job(conn, msg["job_id"], lock=True)
if job is None:
return "reject", "unknown_job"
if str(job["attachment_id"]) != msg["attachment_id"] or job["pipeline_version"] != msg["pipeline_version"]:
return "reject", "job_mismatch"
status = job["job_status"]
if status == "ready":
add_event(conn, job["job_id"], "duplicate_ignored", msg["attempt"], owner, {"status": "ready"})
return "ack", job
if status == "failed":
add_event(conn, job["job_id"], "duplicate_ignored", msg["attempt"], owner, {"status": "failed"})
return "ack", job
if job["current_pipeline_version"] > job["pipeline_version"]:
# Устаревшая job после новой версии pipeline: результат не публикуем.
conn.execute("""UPDATE jobs SET status = 'failed', error_code = 'superseded', lease_owner = NULL,
lease_token = NULL, lease_until = NULL, updated_at = now(), finished_at = now()
WHERE id = %s""", (job["job_id"],))
add_event(conn, job["job_id"], "superseded", msg["attempt"], owner)
return "ack", job
if status == "processing" and job["lease_alive"]:
prev = job["lease_owner"] or ""
# Тот же контейнер (hostname), но другой процесс (boot id): прежняя инкарнация этого
# worker умерла (crash/restart) — два процесса одного контейнера одновременно не живут.
if not (_owner_host(prev) == _owner_host(owner) and prev != owner):
add_event(conn, job["job_id"], "busy_ignored", msg["attempt"], owner, {"lease_owner": prev})
return "ack", job
add_event(conn, job["job_id"], "lease_taken_over", job["attempt"], owner,
{"previous_owner": prev, "reason": "previous process of this container died"})
elif status == "processing":
add_event(conn, job["job_id"], "lease_taken_over", job["attempt"], owner,
{"previous_owner": job["lease_owner"], "reason": "lease expired"})
elif job["too_early"]:
# queued, но время следующей попытки ещё не пришло: это старый дубль, а запланированное
# сообщение relay опубликует само (outbox.available_at).
add_event(conn, job["job_id"], "early_duplicate_ignored", msg["attempt"], owner)
return "ack", job
if job["attempt"] >= job["max_attempts"]:
_finish_failed(conn, job, "retry_exhausted", owner, "attempts exhausted before claim")
return "ack", job
token = uuid.uuid4()
conn.execute(
"""UPDATE jobs SET status = 'processing', attempt = attempt + 1, lease_owner = %s, lease_token = %s,
lease_until = now() + make_interval(secs => %s), updated_at = now()
WHERE id = %s""", (owner, token, lease_seconds, job["job_id"]))
conn.execute("UPDATE attachments SET status = 'processing', updated_at = now() WHERE id = %s",
(job["attachment_id"],))
job = dict(job, attempt=job["attempt"] + 1, lease_token=token, job_status="processing")
add_event(conn, job["job_id"], "claimed", job["attempt"], owner,
{"redelivered_message_attempt": msg["attempt"]})
return "process", job
def heartbeat(conn, job_id, token, lease_seconds):
"""Продлить аренду. False — аренда потеряна (reaper/другой worker), работу надо бросить."""
cur = conn.execute(
"""UPDATE jobs SET lease_until = now() + make_interval(secs => %s)
WHERE id = %s AND lease_token = %s AND status = 'processing'""", (lease_seconds, job_id, token))
return cur.rowcount == 1
def complete(conn, job, variants, owner):
"""processing -> ready атомарно с метаданными вариантов. Только владелец аренды (fencing по
lease_token): опоздавший процесс, у которого аренду забрали, ничего не перезапишет.
Возвращает 'ready' | 'already_ready' | 'lease_lost'."""
cur = conn.execute(
"""UPDATE jobs SET status = 'ready', lease_owner = NULL, lease_token = NULL, lease_until = NULL,
error_code = NULL, last_error = NULL, updated_at = now(), finished_at = now()
WHERE id = %s AND status = 'processing' AND lease_token = %s""", (job["job_id"], job["lease_token"]))
if cur.rowcount != 1:
now = load_job(conn, job["job_id"])
add_event(conn, job["job_id"], "commit_rejected_lease_lost", job["attempt"], owner,
{"current_status": now["job_status"]})
return "already_ready" if now["job_status"] == "ready" else "lease_lost"
with conn.cursor() as cur:
# Ключ эффекта — PK (attachment_id, pipeline_version, name): второго набора не будет.
cur.executemany(
"""INSERT INTO attachment_variants (attachment_id, pipeline_version, name, object_key, content_type,
size_bytes, width, height, sha256, created_at)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, now())
ON CONFLICT (attachment_id, pipeline_version, name) DO UPDATE SET
object_key = EXCLUDED.object_key, content_type = EXCLUDED.content_type,
size_bytes = EXCLUDED.size_bytes, width = EXCLUDED.width, height = EXCLUDED.height,
sha256 = EXCLUDED.sha256""",
[(job["attachment_id"], job["pipeline_version"], v["name"], v["key"], v["content_type"],
v["size_bytes"], v["width"], v["height"], v["sha256"]) for v in variants])
# Не откатываем более новую версию pipeline (на случай нескольких версий, трек 5).
conn.execute(
"""UPDATE attachments SET status = 'ready', error_code = NULL, updated_at = now()
WHERE id = %s AND pipeline_version <= %s""", (job["attachment_id"], job["pipeline_version"]))
add_event(conn, job["job_id"], "ready", job["attempt"], owner,
{"variants": {v["name"]: [v["width"], v["height"]] for v in variants}})
return "ready"
def _finish_failed(conn, job, code, actor, detail):
conn.execute(
"""UPDATE jobs SET status = 'failed', error_code = %s, last_error = %s, lease_owner = NULL,
lease_token = NULL, lease_until = NULL, updated_at = now(), finished_at = now()
WHERE id = %s""", (code, (detail or "")[:500], job["job_id"]))
conn.execute("UPDATE attachments SET status = 'failed', error_code = %s, updated_at = now() WHERE id = %s",
(code, job["attachment_id"]))
add_event(conn, job["job_id"], "failed", job["attempt"], actor, {"error_code": code, "detail": detail})
def fail_or_retry(conn, job, code, detail, owner, base, cap, rng=random):
"""Ошибка попытки. Постоянная -> failed(code); временная -> queued с backoff, пока есть
попытки, иначе failed(retry_exhausted). Только владелец аренды.
Возвращает 'failed' | 'retry' | 'lease_lost' и задержку."""
cur = load_job(conn, job["job_id"], lock=True)
if cur["job_status"] != "processing" or cur["lease_token"] != job["lease_token"]:
add_event(conn, job["job_id"], "error_ignored_lease_lost", job["attempt"], owner, {"error_code": code})
return "lease_lost", None
if code in PERMANENT_ERRORS:
_finish_failed(conn, job, code, owner, detail)
return "failed", None
if cur["attempt"] >= cur["max_attempts"]:
_finish_failed(conn, job, "retry_exhausted", owner, "last error: %s %s" % (code, detail or ""))
return "failed", None
delay = backoff_seconds(cur["attempt"], base, cap, rng)
_schedule_retry(conn, cur, delay, code, detail, owner, "retry_scheduled")
return "retry", delay
def _schedule_retry(conn, job, delay, code, detail, actor, event):
conn.execute(
"""UPDATE jobs SET status = 'queued', lease_owner = NULL, lease_token = NULL, lease_until = NULL,
error_code = NULL, last_error = %s, next_attempt_at = now() + make_interval(secs => %s),
updated_at = now()
WHERE id = %s""", (("%s: %s" % (code, detail or ""))[:500], delay, job["job_id"]))
conn.execute("UPDATE attachments SET status = 'queued', updated_at = now() WHERE id = %s",
(job["attachment_id"],))
add_outbox(conn, job["job_id"], job["attachment_id"], job["pipeline_version"], job["attempt"] + 1, delay)
add_event(conn, job["job_id"], event, job["attempt"], actor,
{"error_code": code, "delay_seconds": round(delay, 3), "next_attempt": job["attempt"] + 1})
# ---------------------------------------------------------------------------
# Reaper (в relay): зависшие processing и потерянные сообщения
# ---------------------------------------------------------------------------
def reap_expired_leases(conn, base, cap, actor="reaper", limit=100):
"""processing с истёкшей арендой (worker умер/завис и не продлевал lease) -> queued
с backoff или failed(retry_exhausted). Возвращает число обработанных."""
rows = conn.execute(
"SELECT " + JOB_COLUMNS + """ FROM jobs j JOIN attachments a ON a.id = j.attachment_id
WHERE j.status = 'processing' AND j.lease_until < now()
ORDER BY j.lease_until LIMIT %s FOR UPDATE OF j SKIP LOCKED""", (limit,)).fetchall()
for job in rows:
add_event(conn, job["job_id"], "lease_expired", job["attempt"], actor, {"lease_owner": job["lease_owner"]})
if job["attempt"] >= job["max_attempts"]:
_finish_failed(conn, job, "retry_exhausted", actor, "lease expired on last attempt")
else:
_schedule_retry(conn, job, backoff_seconds(job["attempt"], base, cap), "lease_expired",
"worker did not renew lease", actor, "requeued_after_lease")
return len(rows)
def redrive_stale_queued(conn, after_seconds, actor="reaper", limit=100):
"""queued-задание, по которому давно нет ни неопубликованного outbox, ни движения:
сообщение могло потеряться в брокере (например, после потери его volume). Публикуем
ещё раз — дубль безопасен, решение примет worker по строке jobs."""
rows = conn.execute(
"""SELECT j.id, j.attachment_id, j.pipeline_version, j.attempt FROM jobs j
WHERE j.status = 'queued' AND j.updated_at < now() - make_interval(secs => %s)
AND j.next_attempt_at < now() - make_interval(secs => %s)
AND NOT EXISTS (SELECT 1 FROM outbox o WHERE o.job_id = j.id AND o.published_at IS NULL)
ORDER BY j.updated_at LIMIT %s FOR UPDATE OF j SKIP LOCKED""",
(after_seconds, after_seconds, limit)).fetchall()
for r in rows:
conn.execute("UPDATE jobs SET updated_at = now() WHERE id = %s", (r["id"],))
add_outbox(conn, r["id"], r["attachment_id"], r["pipeline_version"], r["attempt"] + 1)
add_event(conn, r["id"], "redriven", r["attempt"] + 1, actor, {"stale_after_seconds": after_seconds})
return len(rows)
# ---------------------------------------------------------------------------
# Оператор: replay
# ---------------------------------------------------------------------------
def replay(conn, attachment_id, actor, extra_attempts, reason, dry_run=False):
"""failed -> queued. Новая попытка того же job_id (прежний ключ эффекта), max_attempts
увеличивается на extra_attempts. ready/queued/processing НЕ трогаются: «повторить» не
означает выполнить дубль успешной работы. Возвращает (result, job)."""
job = conn.execute(
"SELECT " + JOB_COLUMNS + """ FROM jobs j JOIN attachments a ON a.id = j.attachment_id
WHERE j.attachment_id = %s AND j.pipeline_version = a.pipeline_version FOR UPDATE OF j""",
(attachment_id,)).fetchone()
if job is None:
return "not_found", None
if job["job_status"] != "failed":
return "refused_status_" + job["job_status"], job
if job["staging_key"] is None:
return "refused_staging_expired", job
if dry_run:
return "would_replay", job
conn.execute(
"""UPDATE jobs SET status = 'queued', max_attempts = attempt + %s, error_code = NULL,
next_attempt_at = now(), replay_count = replay_count + 1, updated_at = now(), finished_at = NULL
WHERE id = %s""", (extra_attempts, job["job_id"]))
conn.execute("UPDATE attachments SET status = 'queued', error_code = NULL, updated_at = now() WHERE id = %s",
(job["attachment_id"],))
add_outbox(conn, job["job_id"], job["attachment_id"], job["pipeline_version"], job["attempt"] + 1)
add_event(conn, job["job_id"], "replayed", job["attempt"] + 1, actor,
{"reason": reason, "previous_error": job.get("error_code"), "replay_count": job["replay_count"] + 1})
return "replayed", job