Files
mtusi2026lab5/student-tests/retry_exhaustion.py
T

227 lines
7.2 KiB
Python

from __future__ import annotations
import base64
import json
import secrets
import time
from uuid import UUID, uuid4
from queued_restart import ROOT, api, dc, wait_ready
from before_ack import sql
from failed_replay import staging_write
EVIDENCE = ROOT / "evidence" / "retry_exhaustion.json"
def job_details(attachment_id):
return json.loads(sql(f"""
SELECT json_build_object(
'job_id', j.id,
'status', j.status,
'attempt', j.attempt,
'max_attempts', j.max_attempts,
'error_code', j.error_code,
'lease_cleared',
j.lease_token IS NULL AND j.lease_until IS NULL,
'outbox', (
SELECT json_agg(
json_build_object(
'attempt', o.attempt,
'published', o.published_at IS NOT NULL,
'delay_seconds',
extract(epoch FROM (o.available_at - o.created_at))
)
ORDER BY o.attempt
)
FROM attachment_outbox o
WHERE o.job_id = j.id
)
)
FROM attachment_jobs j
WHERE j.attachment_id = '{attachment_id}'::uuid
AND j.pipeline_version = 1;
"""))
def remove_staging(attachment_id):
code = """
import sys
from uuid import UUID
from app.job_db import connect_db
from app.storage import bucket_name, get_client
with connect_db() as db:
row = db.execute(
"SELECT staging_key FROM attachments WHERE id = %s",
(UUID(sys.argv[1]),),
).fetchone()
if row is None or not row["staging_key"]:
raise RuntimeError("Expected staging reference")
get_client().delete_object(
Bucket=bucket_name(),
Key=row["staging_key"],
)
"""
dc("exec", "-T", "api", "python", "-c", code, attachment_id)
def main():
evidence = {"scenario": "temporary S3 read failure exhausts bounded retries"}
restore_worker = False
restore_staging = False
attachment_id = None
original = None
try:
wait_ready()
for service in ("publisher", "worker"):
if not dc("ps", "--status", "running", "-q", service):
raise AssertionError(f"Start {service} before this test")
username = "rty_" + uuid4().hex[:16]
password = secrets.token_hex(16)
user = api(
"POST", "/api/v1/users", 201,
payload={
"username": username,
"display_name": "Retry exhaustion test",
"password": password,
},
)
basic = base64.b64encode(
f"{username}:{password}".encode()
).decode()
token = api(
"POST", "/api/v1/auth/sessions", 201,
headers={"Authorization": "Basic " + basic},
)["token"]
chat = api(
"POST", "/api/v1/chats", 201,
token=token,
payload={
"title": "Retry exhaustion",
"member_ids": [user["id"]],
},
)
restore_worker = True
dc("stop", "worker")
assert not dc("ps", "--status", "running", "-q", "worker")
original = (ROOT / "tests/fixtures/sample.png").read_bytes()
attachment = api(
"POST",
f"/api/v1/chats/{chat['id']}/attachments?filename=sample.png",
202,
token=token,
data=original,
headers={"Content-Type": "image/png"},
)
attachment_id = str(UUID(attachment["id"]))
path = f"/api/v1/attachments/{attachment_id}"
initial = job_details(attachment_id)
assert initial["attempt"] == 1
assert initial["max_attempts"] == 5
evidence["attachment_id"] = attachment_id
evidence["initial_job"] = initial
restore_staging = True
remove_staging(attachment_id)
print("Test staging object removed; configured attempt limit=5")
dc("start", "worker")
started = time.monotonic()
deadline = started + 180
observed_attempts = []
previous_attempt = None
while time.monotonic() < deadline:
current = job_details(attachment_id)
if current["attempt"] != previous_attempt:
previous_attempt = current["attempt"]
observed_attempts.append(previous_attempt)
print(
f"Observed attempt={previous_attempt}, "
f"status={current['status']}",
flush=True,
)
if current["status"] == "failed":
break
if current["status"] == "ready":
raise AssertionError("Missing staging unexpectedly reached ready")
time.sleep(0.5)
else:
raise AssertionError("Retry exhaustion timeout")
assert current["job_id"] == initial["job_id"]
assert current["attempt"] == current["max_attempts"] == 5
assert current["error_code"] == "retry_exhausted"
assert current["lease_cleared"] is True
outbox = current["outbox"]
assert [row["attempt"] for row in outbox] == [1, 2, 3, 4, 5]
assert all(row["published"] for row in outbox)
for row in outbox:
if row["attempt"] == 1:
continue
previous = row["attempt"] - 1
upper = min(30.0, 2.0 ** min(previous, 5))
assert 0.49 <= row["delay_seconds"] <= upper + 0.1
failed = api("GET", path, 200, token=token)
assert failed["status"] == "failed"
assert failed["error_code"] == "retry_exhausted"
assert failed["variants"] == []
api("GET", path + "/content", 409, token=token)
count = int(sql(f"""
SELECT count(*) FROM attachment_variants
WHERE attachment_id = '{attachment_id}'::uuid;
"""))
assert count == 0
# Короткое дополнительное наблюдение терминального состояния.
time.sleep(5)
assert job_details(attachment_id) == current
evidence["observed_attempts"] = observed_attempts
evidence["final_job"] = current
evidence["terminal_observation_seconds"] = 5
evidence["elapsed_s"] = round(time.monotonic() - started, 3)
evidence["result"] = "PASS"
except BaseException as exc:
evidence["result"] = "FAIL"
evidence["error_type"] = type(exc).__name__
raise
finally:
try:
# Возвращаем принятые bytes, но failed автоматически не повторяем.
if restore_staging and attachment_id is not None:
staging_write(attachment_id, original=original)
finally:
try:
if restore_worker:
dc("start", "worker")
finally:
EVIDENCE.parent.mkdir(exist_ok=True)
EVIDENCE.write_text(
json.dumps(evidence, ensure_ascii=False, indent=2) + "\n"
)
print(
"PASS: five published attempts exhausted retries; "
"backoff bounds verified; terminal failed/retry_exhausted, no variants"
)
if __name__ == "__main__":
main()