From 3ebd674062a188690464e09b602134b93724bddc Mon Sep 17 00:00:00 2001 From: yura Date: Fri, 13 Nov 2026 16:42:44 +0300 Subject: [PATCH] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D1=82=D1=8C=20=D0=B7=D0=B0=D0=BC=D0=B5=D1=87=D0=B0=D0=BD=D0=B8?= =?UTF-8?q?=D1=8F=20=D0=BF=D0=B5=D1=80=D0=B5=D0=BF=D1=80=D0=BE=D0=B2=D0=B5?= =?UTF-8?q?=D1=80=D0=BA=D0=B8:=20=D0=BD=D0=B5=D0=BF=D1=80=D0=B5=D0=B4?= =?UTF-8?q?=D1=83=D1=81=D0=BC=D0=BE=D1=82=D1=80=D0=B5=D0=BD=D0=BD=D1=8B?= =?UTF-8?q?=D0=B5=20=D0=BE=D1=88=D0=B8=D0=B1=D0=BA=D0=B8=20worker,=20pull?= =?UTF-8?q?=5Fpolicy,=20=D1=82=D0=B5=D1=81=D1=82=20=D0=BE=D0=BA=D0=BD?= =?UTF-8?q?=D0=B0=20D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- compose.yaml | 3 ++- src/worker.py | 13 +++++++++++++ student-tests/outbox_gap.py | 24 +++++++++++++++++------- student-tests/worker_faults.py | 14 ++++++++++++++ 4 files changed, 46 insertions(+), 8 deletions(-) diff --git a/compose.yaml b/compose.yaml index 9b518fa..62215ae 100644 --- a/compose.yaml +++ b/compose.yaml @@ -133,7 +133,8 @@ services: context: . args: APP_VERSION: ${APP_VERSION:-1} - pull_policy: build + # Собрать, если образа нет; пересборка — явно (`build` или `up --build`). + pull_policy: missing command: ["python", "/app/src/migrate.py"] environment: <<: *db-env diff --git a/src/worker.py b/src/worker.py index 633d9fd..2fc7169 100644 --- a/src/worker.py +++ b/src/worker.py @@ -27,6 +27,7 @@ WORKER_CONCURRENCY потоков-потребителей; у каждого с Учебные отказы (WORKER_FAULT_INJECTION=1): filename вида fault-.png задаёт точку: crash-after-claim, crash-after-s3-put, crash-after-commit (os._exit один раз на job), transient- (временная ошибка в первых N попытках), transient-always (до replay), +bug (непредусмотренное исключение в 1-й попытке), slow (пауза FAULT_SLOW_SECONDS после claim, аренда продлевается). """ import concurrent.futures @@ -278,6 +279,8 @@ class Consumer(threading.Thread): if point == "slow" and job["attempt"] == 1: log.warning("FAULT INJECTION slow job=%s sleeping %.0fs", job["job_id"], FAULT_SLOW_SECONDS) time.sleep(FAULT_SLOW_SECONDS) + if point == "bug" and job["attempt"] == 1: + raise RuntimeError("injected programming error") if point and point.startswith("transient-"): n = point.split("-", 1)[1] if (n == "always" and job["replay_count"] == 0) or (n.isdigit() and job["attempt"] <= int(n)): @@ -297,6 +300,16 @@ class Consumer(threading.Thread): log.warning("job %s attempt %d: %s (%s) -> %s%s", job["job_id"], job["attempt"], err.code, err.detail, result, " in %.1fs" % delay if delay else "") return "ack" + except psycopg.Error: + raise # нет БД: сообщение назад в очередь (process_message) + except Exception as exc: + # Непредусмотренная ошибка (баг, неожиданный вывод transform): временная ошибка + # с обычным retry/backoff, а не «висящее» processing до истечения аренды. + log.exception("job %s attempt %d: unexpected error", job["job_id"], job["attempt"]) + with db.transaction(): + result, delay = jobs.fail_or_retry(db, job, "processing_failed", type(exc).__name__, + common.OWNER, RETRY_BASE, RETRY_MAX) + return "ack" with db.transaction(): result = jobs.complete(db, job, variants, common.OWNER) self.crash_once(db, job, point, "crash-after-commit") diff --git a/student-tests/outbox_gap.py b/student-tests/outbox_gap.py index f785cfe..64bc12c 100644 --- a/student-tests/outbox_gap.py +++ b/student-tests/outbox_gap.py @@ -15,6 +15,7 @@ и staging-объект убирает janitor после grace. """ import argparse +import json import subprocess import time @@ -34,12 +35,22 @@ def find_by_filename(name): def raw_upload(c, actor, chat, name, fault): + """Процесс API умирает посреди запроса: ответ формирует LB (без X-Instance-Id), + поэтому здесь urllib напрямую, а не проверяющий контракт Client.call.""" + import urllib.error + import urllib.request + req = urllib.request.Request( + c.base + "/api/v1/chats/%s/attachments?filename=%s" % (chat["id"], name), data=SAMPLE_PNG, method="POST", + headers={"Content-Type": "image/png", "X-Fault-Inject": fault, "Authorization": "Bearer " + actor["token"]}) try: - r = c.call("POST", "/api/v1/chats/%s/attachments?filename=%s" % (chat["id"], name), [502, 503, 504], - actor=actor, raw=SAMPLE_PNG, headers={"Content-Type": "image/png", "X-Fault-Inject": fault}) - return "http %d" % r["status"] - except Failure as exc: - return str(exc) + with urllib.request.urlopen(req, timeout=30) as r: + return {"http": r.status, "x_instance_id": r.headers.get("X-Instance-Id")} + except urllib.error.HTTPError as e: + body = e.read(2000) + return {"http": e.code, "x_instance_id": e.headers.get("X-Instance-Id"), + "error_code": json.loads(body)["error"]["code"] if body.startswith(b"{") else None} + except OSError as exc: + return {"connection_error": type(exc).__name__} def main(): @@ -121,8 +132,7 @@ def main(): "--grace-seconds", "2").stdout real = compose("exec", "-T", "janitor", "python", "/app/src/janitor.py", "--once", "--grace-seconds", "2").stdout - import json as _j - dry, real = _j.loads(dry.strip().splitlines()[-1]), _j.loads(real.strip().splitlines()[-1]) + dry, real = json.loads(dry.strip().splitlines()[-1]), json.loads(real.strip().splitlines()[-1]) gone = find_by_filename(name) is None check(row[0] in dry["abandoned_ids"] and gone, "E: janitor did not clean") res["E"] = {"attachment_id": row[0], "janitor_dry_run": {k: dry[k] for k in ("abandoned_pending", "orphan_objects", diff --git a/student-tests/worker_faults.py b/student-tests/worker_faults.py index 200a5f3..f920e51 100644 --- a/student-tests/worker_faults.py +++ b/student-tests/worker_faults.py @@ -11,6 +11,7 @@ crash-after-s3-put все объекты записаны в S3, COMMIT ready не сделан, ack не отправлен crash-after-commit ready зафиксирован, ack не отправлен (и staging не удалён) transient-2 временная ошибка в попытках 1–2: backoff с jitter, ready с 3-й + bug непредусмотренное исключение в 1-й попытке -> processing_failed -> retry -> ready transient-always временная ошибка до replay: 5 попыток -> failed(retry_exhausted) -> content 409, прикрепление 409 -> ops replay -> ready; повторный replay отклонён staging tamper staging подменён до обработки -> failed(staging_corrupted) без повторов @@ -20,6 +21,7 @@ import argparse import json import subprocess +import time from lab5lib import (Client, Log, SAMPLE_PNG, check, compose, events, get_att, invariants, ops, png, queues, recreate, upload, wait_status, wait_until) @@ -77,6 +79,18 @@ def main(): "invariants": inv} log.step("transient-2: retried with backoff", delays=delays, bounds=bounds, invariants=inv) + # --- непредусмотренное исключение: штатный retry, а не «висящий» processing ---------- + att = upload(c, alice, chat, SAMPLE_PNG, "fault-bug.png") + t0 = time.monotonic() + ready = wait_status(c, bob, att["id"], {"ready", "failed"}, timeout=60) + took = round(time.monotonic() - t0, 2) + info = ops("inspect", att["id"]) + codes = [e["detail"]["error_code"] for e in info["events"] if e["event"] == "retry_scheduled"] + check(ready["status"] == "ready" and codes == ["processing_failed"] and took < 15, "bug: retry path") + report["bug"] = {"attachment_id": att["id"], "retry_error_codes": codes, "seconds_to_ready": took, + "events": events(info), "invariants": invariants(info)} + log.step("unexpected exception -> processing_failed -> retry -> ready", **report["bug"]) + # --- исчерпание попыток -> failed -> replay ---------------------------------------- att = upload(c, alice, chat, SAMPLE_PNG, "fault-transient-always.png") failed = wait_status(c, bob, att["id"], {"ready", "failed"}, timeout=120)