feat: compensate failed uploads and clean stale pending attachments

- upload: delete the stored object when ready fails before COMMIT or the
  pending row is gone (503 instead of 500); unknown COMMIT outcome keeps it
- cleaner service (python -m src.cleaner): stale pending rows older than
  grace (900 s, must exceed 17 s live-upload bound) under FOR UPDATE SKIP
  LOCKED, object before row, own S3 user with read/delete only
- shared session_scope for API and cleaner; early_stop process name
- partial index on pending attachments, CREATE INDEX CONCURRENTLY
- s3-bootstrap: cleaner user, policy and checks; make env_setup appends
  missing template variables to an existing .env
- failure checks: cleaner on the failure stand, id-list hook actions,
  five new and three updated tests; driver upload-consistency
- sync upload-consistency deltas into main specs (storage-consistency)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-21 06:10:37 +03:00
co-authored by Claude Opus 5.5
parent 450b091ae3
commit 5b42bd2891
54 changed files with 2958 additions and 411 deletions
+332 -29
View File
@@ -1,11 +1,14 @@
"""Проверки отказов: выполняет только `make failure_checks` (маркер `fault`).
Стенд и hook готовит `student-tests/run_failures.py`: свои Postgres,
Valkey и S3, обычный API (`BASE_URL`, с `MAX_UPLOAD_BYTES=1` и
`MAX_IMAGE_PIXELS=1` в окружении) и «тесный» (сроки сессии и ключа
идемпотентности 2 с, пул из одного соединения). На хранилища тесты действуют только через фикстуру
Valkey и S3, уборщик незавершённых загрузок (grace и интервал —
`FAULT_CLEANER_GRACE_S`, `FAULT_CLEANER_INTERVAL_S`), обычный API
(`BASE_URL`, с `MAX_UPLOAD_BYTES=1` и `MAX_IMAGE_PIXELS=1` в окружении) и
«тесный» (сроки сессии и ключа идемпотентности 2 с, пул из одного
соединения). На хранилища и API тесты действуют только через фикстуру
`stand` (hook `student-tests/fault_hook.py`) и всегда возвращают их в
рабочее состояние. Решение 4 design change `failure-checks`.
рабочее состояние. Решение 4 design change `failure-checks`, решение 10
design change `upload-consistency`.
"""
import os
@@ -535,22 +538,77 @@ def test_key_free_after_ttl(tight_api: Api) -> None:
# ---------------------------------------------------------------------------
# Вложения: S3 остановлен или заморожен, счётчики строк и объектов — hook
# Вложения: S3 остановлен или заморожен, сбои записи строки, уборщик. Строки
# и объекты — списками id от hook, а не счётчиками: уборщик стенда убирает
# строки прежних тестов параллельно (design change upload-consistency,
# решение 10)
# ---------------------------------------------------------------------------
def attachment_counts(stand: Stand) -> dict[str, int]:
"""Вложения стенда по статусам: `pending=N ready=M` от hook."""
return {
name: int(value)
for name, value in (
item.split("=") for item in stand("count-attachments").split()
)
}
# grace и интервал уборщика стенда отказов (run_failures.py,
# failures.compose.yml)
CLEANER_GRACE_S = float(os.environ.get("FAULT_CLEANER_GRACE_S", "20"))
CLEANER_INTERVAL_S = float(os.environ.get("FAULT_CLEANER_INTERVAL_S", "1"))
# запас поверх grace и интервала: проход, вызов hook, планировщик Docker
# Desktop
CLEANUP_SLACK_S = 5
# задержка перевода в ready триггером stall (fault_hook.py)
STALL_S = 4
# срок клиента загрузок в потоке
THREAD_CLIENT_TIMEOUT_S = 30
def object_count(stand: Stand) -> int:
return int(stand("count-objects"))
def attachment_rows(stand: Stand) -> dict[str, str]:
"""Вложения стенда: `id` → статус."""
return dict(line.split() for line in stand("attachment-ids").splitlines())
def stored_ids(stand: Stand) -> set[str]:
"""`id` вложений, у которых есть объект в bucket стенда."""
return set(stand("object-ids").splitlines())
def orphan_objects(stand: Stand) -> set[str]:
"""Объекты вложений без строки. Сначала строки, потом объекты: уборщик
удаляет объект раньше строки, и убранная между вызовами строка не
даёт ложного «объекта без строки»."""
rows = attachment_rows(stand)
return stored_ids(stand) - set(rows)
def new_ids(before: dict[str, str], after: dict[str, str]) -> set[str]:
return set(after) - set(before)
def ready_ids(rows: dict[str, str]) -> set[str]:
return {item for item, status in rows.items() if status == "ready"}
def wait_cleaned(stand: Stand, attachment_id: str, *, since: float) -> None:
"""Строка и объект вложения убраны не позже grace + интервал + запас
от `since` (момент до загрузки: `created_at` строки не раньше)."""
deadline = since + CLEANER_GRACE_S + CLEANER_INTERVAL_S + CLEANUP_SLACK_S
while True:
rows = attachment_rows(stand)
stored = stored_ids(stand)
if attachment_id not in rows and attachment_id not in stored:
return
if time.monotonic() > deadline:
raise AssertionError(
f"attachment {attachment_id} is not cleaned "
f"{time.monotonic() - since:.1f}s after upload: "
f"row {rows.get(attachment_id)}, "
f"object {attachment_id in stored}",
)
time.sleep(0.5)
def sleep_until(moment: float) -> None:
time.sleep(max(0.0, moment - time.monotonic()))
def fault_filename() -> str:
"""Уникальное имя загрузки, на которое срабатывает триггер hook."""
return f"fault-{uuid.uuid4().hex}.png"
def upload_raw(
@@ -563,7 +621,35 @@ def upload_raw(
return api.post_attachment(actor, chat["id"], data, **kwargs)
def assert_invisible(
api: Api,
actor: Actor,
chat: dict[str, Any],
attachment_id: str,
) -> None:
"""Вложение не в статусе ready: метаданные, байты и ссылка в сообщении
— 404 с тем же `message`, что у неизвестного `id`."""
def calls(item: str) -> tuple[httpx.Response, ...]:
return (
api.attachment_meta(actor, item),
api.attachment_content(actor, item),
api.post_message(
actor,
chat["id"],
json={"text": "ссылка", "attachment_ids": [item]},
),
)
unknown = [assert_error(resp, 404) for resp in calls(str(uuid.uuid4()))]
hidden = [assert_error(resp, 404) for resp in calls(attachment_id)]
assert [error["message"] for error in hidden] == [
error["message"] for error in unknown
]
@pytest.mark.spec("attachments", "Запись в S3 не удалась")
@pytest.mark.spec("attachments", "Незавершённая загрузка не видна")
def test_upload_with_object_storage_stopped(
api: Api,
stand: Stand,
@@ -571,18 +657,20 @@ def test_upload_with_object_storage_stopped(
chat: dict[str, Any],
) -> None:
data = images.sample_png()
before = attachment_counts(stand)
before = attachment_rows(stand)
with outage(stand, "stop", "s3"):
resp, elapsed = timed(lambda: upload_raw(api, alice, chat, data))
assert_error(resp, 503)
assert elapsed < S3_TIMEOUT_S + SLACK_S, f"503 after {elapsed:.2f}s"
after = attachment_counts(stand)
after = attachment_rows(stand)
# строка-намерение осталась, готовых не прибавилось; её уберёт
# уборщик change upload-consistency
assert after == {
"pending": before["pending"] + 1,
"ready": before["ready"],
}
# уборщик (test_cleaner_survives_outages)
(pending,) = new_ids(before, after)
assert after[pending] == "pending"
assert ready_ids(after) == ready_ids(before)
# замечание S6 verify attachments: id последней pending — от hook
assert stand("last-pending") == pending
assert_invisible(api, alice, chat, pending)
api.send_message(alice, chat["id"], "текст без S3")
api.upload(alice, chat["id"], data)
@@ -601,11 +689,11 @@ def test_rejected_uploads_leave_nothing(
for offset in range(0, len(big), 1024 * 1024):
yield big[offset : offset + 1024 * 1024]
# хотя бы одно готовое вложение: счётчики hook не нулевые случайно
api.upload(alice, chat["id"], images.sample_png())
before = (attachment_counts(stand), object_count(stand))
assert before[0]["ready"] >= 1, before
assert before[1] >= 1, before
# хотя бы одно готовое вложение: списки hook не пусты случайно
ready = api.upload(alice, chat["id"], images.sample_png())
before = (attachment_rows(stand), stored_ids(stand))
assert before[0].get(ready["id"]) == "ready", before[0]
assert ready["id"] in before[1], before[1]
rejected = (
(404, upload_raw(api, eve, chat, images.sample_png())),
(413, upload_raw(api, alice, chat, big)),
@@ -625,7 +713,214 @@ def test_rejected_uploads_leave_nothing(
)
for status, resp in rejected:
assert_error(resp, status)
assert (attachment_counts(stand), object_count(stand)) == before
assert not new_ids(before[0], attachment_rows(stand))
assert not stored_ids(stand) - before[1]
@pytest.mark.spec("attachments", "Сбой записи метаданных")
def test_metadata_insert_failure(
api: Api,
stand: Stand,
alice: Actor,
chat: dict[str, Any],
) -> None:
filename = fault_filename()
before = (attachment_rows(stand), stored_ids(stand))
stand("fail-attachments", "insert", filename)
try:
resp = upload_raw(
api,
alice,
chat,
images.sample_png(),
filename=filename,
)
assert_error(resp, 503)
finally:
stand("clear-fail-attachments")
# строки нет — объект не записывался
assert not new_ids(before[0], attachment_rows(stand))
assert not stored_ids(stand) - before[1]
class BodyAborted(Exception):
"""Клиент обрывает передачу тела загрузки."""
@pytest.mark.spec("attachments", "Обрыв передачи тела")
def test_interrupted_body(
api: Api,
stand: Stand,
alice: Actor,
chat: dict[str, Any],
) -> None:
before = (attachment_rows(stand), stored_ids(stand))
def aborted_body() -> Iterator[bytes]:
yield images.PNG_SIGNATURE + bytes(1024 * 1024)
raise BodyAborted
# свой клиент: его соединение обрывается вместе с телом
with (
Api(str(api.client.base_url), timeout=THREAD_CLIENT_TIMEOUT_S) as own,
pytest.raises((BodyAborted, httpx.TransportError)),
):
upload_raw(own, alice, chat, aborted_body())
# API замечает обрыв не мгновенно; строки до конца тела нет в любом
# случае
time.sleep(1)
assert not new_ids(before[0], attachment_rows(stand))
assert not stored_ids(stand) - before[1]
api.upload(alice, chat["id"], images.sample_png())
@pytest.mark.spec("attachments", "Фиксация ready не удалась")
@pytest.mark.spec("storage-consistency", "Свежая загрузка не тронута")
@pytest.mark.spec("storage-consistency", "Зависшая загрузка убрана")
def test_ready_failure_compensated(
api: Api,
stand: Stand,
alice: Actor,
chat: dict[str, Any],
) -> None:
filename = fault_filename()
before = attachment_rows(stand)
stand("fail-attachments", "ready", filename)
try:
started = time.monotonic()
resp = upload_raw(
api,
alice,
chat,
images.sample_png(),
filename=filename,
)
assert_error(resp, 503)
finally:
stand("clear-fail-attachments")
after = attachment_rows(stand)
(pending,) = new_ids(before, after)
assert after[pending] == "pending"
assert stand("last-pending") == pending
# компенсация: объект удалён до ответа 503
assert pending not in stored_ids(stand)
assert_invisible(api, alice, chat, pending)
# моложе grace строку уборщик не трогает: к половине grace он сделал
# около G / 2 / I проходов
sleep_until(started + CLEANER_GRACE_S / 2)
assert attachment_rows(stand).get(pending) == "pending"
wait_cleaned(stand, pending, since=started)
assert not orphan_objects(stand)
@pytest.mark.spec("storage-consistency", "Объект без фиксации убран")
def test_killed_between_put_and_ready(
api: Api,
stand: Stand,
alice: Actor,
chat: dict[str, Any],
) -> None:
filename = fault_filename()
before = attachment_rows(stand)
outcome: dict[str, Any] = {}
client = Api(str(api.client.base_url), timeout=THREAD_CLIENT_TIMEOUT_S)
def upload() -> None:
try:
outcome["status"] = upload_raw(
client,
alice,
chat,
images.sample_png(),
filename=filename,
).status_code
except httpx.TransportError as e:
outcome["error"] = e
stand("fail-attachments", "stall", filename)
killed = False
try:
started = time.monotonic()
thread = threading.Thread(target=upload)
thread.start()
# строка pending и объект — до конца задержки перевода в ready
deadline = started + STALL_S
pending = ""
while time.monotonic() < deadline:
pending = stand("last-pending")
if (
pending
and pending not in before
and pending in stored_ids(stand)
):
break
time.sleep(0.05)
else:
raise AssertionError("no pending row with object during stall")
stand("kill-api")
killed = True
thread.join(THREAD_CLIENT_TIMEOUT_S)
assert not thread.is_alive()
# 201 до клиента не дошёл: перевод в ready ждал в триггере
assert outcome.get("status") != 201, outcome
assert attachment_rows(stand).get(pending) == "pending"
assert pending in stored_ids(stand)
finally:
client.close()
stand("clear-fail-attachments")
if killed:
stand("start-api")
wait_cleaned(stand, pending, since=started)
assert not orphan_objects(stand)
api.upload(alice, chat["id"], images.sample_png())
@pytest.mark.spec("storage-consistency", "S3 недоступен во время уборки")
@pytest.mark.spec("storage-consistency", "БД недоступна во время уборки")
@pytest.mark.spec("storage-consistency", "Готовые вложения не тронуты")
def test_cleaner_survives_outages(
api: Api,
stand: Stand,
alice: Actor,
chat: dict[str, Any],
) -> None:
data = images.sample_png()
ready = api.upload(alice, chat["id"], data)
with outage(stand, "stop", "s3"):
before = attachment_rows(stand)
started = time.monotonic()
assert_error(upload_raw(api, alice, chat, data), 503)
(pending,) = new_ids(before, attachment_rows(stand))
# PostgreSQL недоступен, пока загрузка моложе grace
with outage(stand, "stop", "postgres"):
time.sleep(3)
# grace истёк, S3 всё ещё нет: проходы прерываются, строка на месте
sleep_until(started + CLEANER_GRACE_S + 3 * CLEANER_INTERVAL_S)
assert attachment_rows(stand).get(pending) == "pending"
# S3 вернулся: уборщик без перезапуска убирает строку за проход
returned = time.monotonic()
deadline = returned + CLEANER_INTERVAL_S + CLEANUP_SLACK_S
while pending in attachment_rows(stand):
assert time.monotonic() < deadline, (
f"pending {pending} is still there "
f"{time.monotonic() - returned:.1f}s after S3 came back"
)
time.sleep(0.5)
assert pending not in stored_ids(stand)
assert not orphan_objects(stand)
# готовое вложение старше grace на месте
meta = assert_ok(
api.attachment_meta(alice, ready["id"]),
200,
"Attachment",
)
assert meta == ready
assert meta["status"] == "ready"
assert_content(
api.attachment_content(alice, ready["id"]),
data,
"image/png",
)
@pytest.mark.spec("attachments", "S3 остановлен")
@@ -690,6 +985,7 @@ def test_environment_does_not_change_limits(
@pytest.mark.spec("attachments", "S3 завис")
@pytest.mark.spec("storage-consistency", "Зависшая загрузка убрана")
def test_object_storage_paused(
api: Api,
stand: Stand,
@@ -698,6 +994,8 @@ def test_object_storage_paused(
) -> None:
data = images.sample_png()
attachment = api.upload(alice, chat["id"], data)
before = attachment_rows(stand)
started = time.monotonic()
# срок клиента больше срока вызова S3: ждём ответ API, а не свой обрыв
slow = Api(str(api.client.base_url), timeout=3 * S3_TIMEOUT_S)
with slow, outage(stand, "pause", "s3"):
@@ -716,3 +1014,8 @@ def test_object_storage_paused(
data,
"image/png",
)
# загрузка во время заморозки оставила строку pending; объект после
# разморозки не дописался, строку уборщик убирает после grace
(pending,) = new_ids(before, attachment_rows(stand))
wait_cleaned(stand, pending, since=started)
assert not orphan_objects(stand)