Исправить замечания перепроверки: непредусмотренные ошибки worker, pull_policy, тест окна D
This commit is contained in:
+2
-1
@@ -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
|
||||
|
||||
@@ -27,6 +27,7 @@ WORKER_CONCURRENCY потоков-потребителей; у каждого с
|
||||
Учебные отказы (WORKER_FAULT_INJECTION=1): filename вида fault-<point>.png задаёт точку:
|
||||
crash-after-claim, crash-after-s3-put, crash-after-commit (os._exit один раз на job),
|
||||
transient-<N> (временная ошибка в первых 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")
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user