This commit is contained in:
2026-10-25 21:43:03 +03:00
parent 276dbdad8a
commit a591243d80
103 changed files with 10857 additions and 36 deletions
+122
View File
@@ -0,0 +1,122 @@
"""lab5, уровень 4: ограниченные повторы с backoff и jitter, постоянные и временные ошибки, DLQ и replay.
make retry-replay (= python student-tests/retry_replay.py)
A. Временная ошибка, потом успех: точка worker_transient=2 — две попытки подряд «падают», как при
недоступном S3. Каждая назначает следующую с паузой backoff + jitter (случайно в [d/2, d],
d = 2, 4, 8… с). Третья попытка успешна -> ready. Паузы берутся из outbox (available_at).
B. Попытки исчерпаны: worker_transient=99 -> 5 попыток (JOB_MAX_ATTEMPTS) -> failed с
error_code=retry_exhausted; сообщение уходит в DLQ (attachments.dead), задание — в реестр failed
(python -m messenger.jobs failed); /content -> 409, прикрепить к сообщению -> 409.
C. Постоянная ошибка: JPEG с испорченными сжатыми данными -> invalid_image сразу, без повторов (попытка 1).
D. Replay оператора (python -m messenger.jobs replay): failed из B -> queued -> ready (новая попытка,
запись в журнале с автором). Replay готового вложения — no-op: дубль успешной работы не запускается.
Replay постоянной ошибки из C снова даёт invalid_image: replay не обходит проверку файла.
"""
import time
from datetime import datetime
import ops
from filegen import garbage_scan_jpeg, upload_when_ready, wait_status
from helpers import Client, check, idempotency, run
def parse(value):
return datetime.fromisoformat(value)
def delays(job):
"""Пауза перед каждой следующей попыткой: available_at - created_at строки outbox этой попытки."""
created = {e["attempt"]: e["at"] for e in job["events"] if e["event"] == "retry_scheduled"}
rows = {o["attempt"]: o for o in job["outbox"]}
out = []
for attempt in sorted(created):
row = rows.get(attempt + 1)
if row:
out.append((attempt + 1, (parse(row["available_at"]) - parse(created[attempt])).total_seconds()))
return out
def main():
api = Client(timeout=15)
worker = ops.wait_healthy("worker", 1)[0]
alice, bob, _eve, chat = api.bootstrap()
try:
# ---------- A ----------
ops.arm("worker", "worker_transient", "2", container=worker)
att_a = upload_when_ready(api, alice, chat, name="retry-a.png")["json"]
wait_status(api, bob, att_a["id"], seconds=90)
job = ops.job(att_a["id"])
check(job["job"]["attempt"] == 3, "expected success at attempt 3")
pauses = delays(job)
for attempt, pause in pauses:
limit = min(60, 2 * 2 ** (attempt - 2))
check(limit / 2 - 0.05 <= pause <= limit + 0.05, f"pause {pause:.2f} s before attempt {attempt} "
f"is outside [{limit / 2}, {limit}]")
print(f"A. transient errors twice, then success: ready at attempt {job['job']['attempt']}")
print(" pauses before attempts: " + ", ".join(f"#{a}: {p:.2f} s" for a, p in pauses) +
" (backoff 2^n with random jitter in [d/2, d])")
print(" events: " + " -> ".join(f"{e['event']}({e['attempt']})" for e in job["events"]))
# ---------- B ----------
dead_before = ops.queues().get("attachments.dead", (0, 0))[0]
ops.arm("worker", "worker_transient", "99", container=worker)
att_b = upload_when_ready(api, alice, chat, name="retry-b.png")["json"]
failed = wait_status(api, bob, att_b["id"], ("failed",), seconds=180)
ops.disarm("worker", "worker_transient")
job = ops.job(att_b["id"])
check(failed["error_code"] == "retry_exhausted" and job["job"]["attempt"] == 5, "expected 5 attempts")
api.call("GET", f"/api/v1/attachments/{att_b['id']}/content", 409, actor=bob)
api.call("POST", f"/api/v1/chats/{chat['id']}/messages", 409, actor=alice, headers=idempotency(),
body={"text": "", "attachment_ids": [att_b["id"]]})
deadline = time.monotonic() + 30
while ops.queues().get("attachments.dead", (0, 0))[0] <= dead_before:
check(time.monotonic() < deadline, "the final failure did not reach the DLQ")
time.sleep(1)
registry = ops.cli("api", "messenger.jobs", "failed")
check(isinstance(registry, list) and any(r["attachment_id"] == att_b["id"] for r in registry),
"the failed job is missing from the registry")
entry = [r for r in registry if r["attachment_id"] == att_b["id"]][0]
print(f"B. transient error every time: {job['job']['attempt']} attempts -> failed, "
f"error_code={failed['error_code']} (last error {entry['last_error_code']})")
print(" pauses: " + ", ".join(f"#{a}: {p:.2f} s" for a, p in delays(job)))
print(f" DLQ attachments.dead: {dead_before} -> {ops.queues()['attachments.dead'][0]}; "
f"registry: python -m messenger.jobs failed lists it; content -> 409, attach -> 409")
# ---------- C ----------
att_c = upload_when_ready(api, alice, chat, data=garbage_scan_jpeg(), name="broken.jpg",
ctype="image/jpeg")["json"]
failed_c = wait_status(api, bob, att_c["id"], ("failed",), seconds=60)
job_c = ops.job(att_c["id"])
check(failed_c["error_code"] == "invalid_image" and job_c["job"]["attempt"] == 1, "no retries for a bad file")
print(f"C. permanent error: broken JPEG scan -> failed at attempt 1, error_code={failed_c['error_code']} "
f"(no retries)")
finally:
ops.disarm("worker", "worker_transient")
# ---------- D ----------
result = ops.replay(att_b["id"])
check(result.get("result") == "queued", f"replay of a failed job must queue it: {result}")
ready = wait_status(api, bob, att_b["id"], seconds=90)
job = ops.job(att_b["id"])
audit = [e for e in job["events"] if e["event"] == "replay_requested"]
check(audit and audit[-1]["actor"].startswith("operator:"), "replay must be audited")
print(f"D. replay of the failed job: {result} -> ready at attempt {job['job']['attempt']}; "
f"audit: {audit[-1]['actor']}: {audit[-1]['detail']}")
outbox_rows, variants = len(job["outbox"]), job["variants"]
noop = ops.replay(att_b["id"])
after = ops.job(att_b["id"])
check(noop == {"result": "noop", "reason": "ready"}, f"replay of a ready job must be a no-op: {noop}")
check(len(after["outbox"]) == outbox_rows and after["variants"] == variants, "replay of ready changed something")
print(f" replay of the now ready job: {noop} — no new message, variants unchanged "
f"({len(variants)} rows), status {ready['status']}")
again = ops.replay(att_c["id"])
failed_again = wait_status(api, bob, att_c["id"], ("failed",), seconds=60)
check(again.get("result") == "queued" and failed_again["error_code"] == "invalid_image", "bad file must fail again")
print(f" replay of the permanent failure: {again} -> failed again with {failed_again['error_code']}")
print("PASS: bounded retries with backoff and jitter; permanent errors fail at once; final failures go to the "
"DLQ and the failed registry; replay re-runs only failed jobs and is audited")
if __name__ == "__main__":
run(main)