feat: implement lab 4 attachments and storage reconciliation

This commit is contained in:
2026-10-27 22:14:19 +03:00
parent ec540a1a72
commit fea6770389
128 changed files with 27650 additions and 24 deletions
+131
View File
@@ -0,0 +1,131 @@
# Что доказывает: уровень 4 — «прерывание загрузки и отказ между записью
# S3/БД не оставляют вечных неучтённых объектов: есть компенсация,
# сверка и очистка с безопасным grace period»; «лимиты/таймауты не
# позволяют одной загрузке занять неограниченную RAM»; проверка
# недоступности S3 (README, «Что сделать», п. 5). Трек 2 — ошибки
# внедрены с обеих сторон, обнаружены dry-run, безопасно исправлены
# --apply, повтор находит только неисправимое; свежие и используемые
# вложения под загрузками не удаляются. С лаб 2–3 — отказы PostgreSQL,
# Valkey, пул, сроки сессии и ключа.
# Дата: 2026-10-23T16:52:13Z (UTC)
# Окружение: macOS 26.6.2, Apple M3 Pro; ВМ Docker 12 CPU / 7,7 ГиБ;
# Docker 29.9.2, Compose 5.6.1; python3 хоста 3.11.9, uv Python 3.13.15,
# pytest 9.1.1.
# Стенд: отдельный проект vladimirceva-lab4-failures (student-tests/stand.py):
# PostgreSQL, Valkey, S3 с bootstrap; три процесса API без LB — обычный,
# «тесный» (сроки сессии и ключа 2 с, пул 1, срок операции 2 с) и «узкий
# по загрузкам» (1 место, очередь 1, ожидание 1 с, срок тела 2 с; ему же
# передано MAX_UPLOAD_BYTES=1 и MAX_IMAGE_PIXELS=1 — лимиты контракта
# окружение не меняет); уборщик с grace 25 с и проходом раз в секунду
# (без плановой сверки: её запускают тесты). Удаляется после прогона.
# Код: src_sha256 bc10d566e2f63173541445a2f6273b967447e13e5dd7f1fb76900934e5692cbe.
# Как повторить: make failure-checks FAULT_ARGS=-rP
#
# Вывод сборки образа и строки compose о контейнерах сокращены (...).
$ make failure-checks FAULT_ARGS=-rP
python3 student-tests/stand.py failures -rP
[failures] project=vladimirceva-lab4-failures
[failures] build image
...
[failures] start postgres, valkey and s3
...
[failures] s3 bootstrap
[failures] migrations
...
2026-10-23T16:52:25.803Z INFO alembic.runtime.migration [rid=-] Running upgrade -> 0001, messenger schema: users, sessions, chats, chat members, messages
2026-10-23T16:52:25.814Z INFO alembic.runtime.migration [rid=-] Running upgrade 0001 -> 0002, idempotency keys for sending messages
2026-10-23T16:52:25.818Z INFO alembic.runtime.migration [rid=-] Running upgrade 0002 -> 0003, attachments and message attachments
2026-10-23T16:52:25.829Z INFO src.migrations [rid=-] migrations finished db=messenger
[failures] ready: api=http://127.0.0.1:59093 tight=http://127.0.0.1:59099 uploads=http://127.0.0.1:59105 cleaner=vladimirceva-lab4-failures-cleaner
[failures] pytest -m fault
============================= test session starts ==============================
platform darwin -- Python 3.13.15, pytest-9.1.1, pluggy-1.6.0
rootdir: <репозиторий>
configfile: pyproject.toml
testpaths: student-tests
plugins: anyio-4.15.1
collected 154 items / 130 deselected / 24 selected
student-tests/test_failures.py ........................ [100%]
==================================== PASSES ====================================
________________________ test_database_stopped_and_back ________________________
----------------------------- Captured stdout call -----------------------------
postgres stopped: POST message -> 503 in 0.008s
___________________ test_frozen_database_and_exhausted_pool ____________________
----------------------------- Captured stdout call -----------------------------
postgres paused: first request -> 503 in 4.01s, second (pool of 1 busy) -> 503 in 1.01s
_______________________ test_readiness_without_database ________________________
----------------------------- Captured stdout call -----------------------------
postgres stopped: /health/ready -> 503 in 0.011s
_______________________ test_valkey_stopped_is_bypassed ________________________
----------------------------- Captured stdout call -----------------------------
valkey stopped: GET chat -> 200 in 0.012s, POST message -> 201 in 0.011s
_____________________ test_valkey_paused_costs_one_timeout _____________________
----------------------------- Captured stdout call -----------------------------
valkey paused: baseline 0.002s, first read 0.205s, second read 0.003s
_________________________ test_upload_with_s3_stopped __________________________
----------------------------- Captured stdout call -----------------------------
s3 stopped: upload -> 503 in 0.040s
___________________ test_upload_and_download_with_s3_paused ____________________
----------------------------- Captured stdout call -----------------------------
s3 paused: upload -> 503 in 5.01s, download -> 503 in 5.01s
____________ test_ready_failure_compensates_and_cleaner_removes_row ____________
----------------------------- Captured stdout call -----------------------------
ready failed: object compensated at once, row removed after 25.8s
_______________________ test_kill_between_put_and_ready ________________________
----------------------------- Captured stdout call -----------------------------
killed between PUT and ready: client got ['RemoteProtocolError']
cleaner removed row and object 19.3s after the kill check
________________________ test_upload_slots_busy_is_429 _________________________
----------------------------- Captured stdout call -----------------------------
slots busy: third upload -> 429 in 0.005s (Too many uploads in progress, retry later)
_______________________ test_upload_body_timeout_is_400 ________________________
----------------------------- Captured stdout call -----------------------------
slow body: -> 400 in 3.01s (Upload body was not received in time)
__________________ test_reconcile_finds_and_fixes_both_sides ___________________
----------------------------- Captured stdout call -----------------------------
dry-run: {'7465519f-7877-413d-a045-81bfd7b10de7': 'orphan_object', 'fd249ee1-1c8b-430a-84e6-d0761ba2accb': 'size_mismatch', '13691faf-6b35-4f7b-8d9e-03b9947a11a8': 'missing_object', '115eff2d-49d9-4531-95f3-10df6fcc3481': 'stale_pending', 'attachments': 'foreign_object'}
after fixes: apply=false strategy=batch deep=false rate=2000 listed_objects=7 checked_rows=7 fresh_objects=0 fresh_rows=0 lost_known=1 found_orphan_object=0 found_stale_pending=0 found_missing_object=0 found_size_mismatch=0 found_checksum_mismatch=0 found_restored_object=0 found_foreign_object=0 fixed_cleared_lost=0 fixed_deleted_object=0 fixed_marked_lost=0 fixed_removed_pending=0 remaining=0 refused=false u
______________________ test_reconcile_apply_under_uploads ______________________
----------------------------- Captured stdout call -----------------------------
reconcile --apply passes: [0, 0, 0]; uploads: 2023; errors: []
================ 24 passed, 130 deselected in 218.83s (0:03:38) ================
[failures] cleanup
[failures] results: {'fault': 0}
$ docker ps -a --format '{{.Names}}' | grep failures; docker volume ls -q | grep failures
(пусто)
# Итог: 24 passed. Что именно проверено (утверждения тестов, а не только
# печать выше; student-tests/test_failures.py):
# - S3 остановлен — загрузка 503 за 0,04 с, в тексте ошибки нет
# внутренностей S3; строка pending остаётся уборщику, ready нет; текст и
# /health/ready работают (S3 готовность не проверяет); после возврата S3
# тот же файл — 201. Заморожен — загрузка и скачивание 503 за срок
# вызова 5,01 с, метаданные и ссылка в сообщении работают, после
# разморозки оригинал побайтно тот же.
# - Сбой перевода в ready после записанного объекта (триггер в БД) — 503,
# объект удалён компенсацией сразу, строку pending уборщик убрал через
# 25,8 с (grace 25 с); объектов без строки 0.
# - Процесс API убит между PUT и ready — клиент 201 не получил, уборщик
# после grace убрал и строку, и объект.
# - Места загрузок: при занятом месте и полной очереди — 429 за 0,005 с с
# Retry-After: 1; ожидавшая загрузка — 429 по сроку ожидания места;
# занявшая место — 201 с полным размером (MAX_UPLOAD_BYTES=1 в окружении
# лимит не изменил). Медленное тело — 400 по сроку тела (2 с + отправка),
# ни строки, ни объекта, место освобождено (следующая загрузка — 201).
# - Сверка: внесены объект без строки, чужой объект, строка без объекта
# (на неё ссылается сообщение), другой размер, зависшая загрузка — dry-run
# нашёл все пять классов и ничего не изменил (число объектов и строк то
# же); --apply удалил объект без строки, убрал зависшую, пометил
# потерянный оригинал (метаданные 200, байты 404, сообщение со ссылкой
# живо) и другой размер, чужой объект не тронул (код 3); повтор нашёл
# только чужой; вернувшийся оригинал с тем же SHA-256 снял пометку (код
# 0), повторный dry-run — 0 находок (lost_known=1 — оригинал другого
# размера остаётся помеченным).
# - --apply трижды во время 2023 загрузок и отправок четырёх клиентов —
# коды 0, ни одно подтверждённое (201) вложение не удалено и не помечено,
# каждое скачивается с тем же SHA-256: свежие и используемые вложения
# сверка не трогает.
+42
View File
@@ -0,0 +1,42 @@
# Что доказывает: уровень 4 — собственные тесты проходят через LB
# рабочего стенда с двумя репликами: вложения (слишком большой файл,
# повреждённое изображение, подмена MIME, чужое attachment_id, вложение
# другого чата, опасный filename, 10 одновременных загрузок, скачивание
# через другую реплику), обязательные сценарии лаб 1–3, гонки,
# идемпотентность через разные реплики.
# Дата: 2026-10-23T16:47:29Z (UTC)
# Окружение: macOS 26.6.2, Apple M3 Pro; Docker 29.9.2, Compose 5.6.1;
# uv Python 3.13.15, pytest 9.1.1.
# Стенд: рабочий (`make up`, проект vladimirceva-lab4), HAProxy
# 127.0.0.1:8180 (порт из .env), 2 реплики, EXPECT_REPLICAS=2.
# Код: src_sha256 bc10d566e2f63173541445a2f6273b967447e13e5dd7f1fb76900934e5692cbe.
# Как повторить: make up; make student-test [BASE_URL=http://localhost:<HOST_PORT>]
# Проверки отказов (24, маркер fault) здесь не идут — только на своём
# стенде: tests/failure-checks.txt.
$ make student-test BASE_URL=http://localhost:8180
BASE_URL=http://localhost:8180 EXPECT_REPLICAS=2 uv run pytest
============================= test session starts ==============================
platform darwin -- Python 3.13.15, pytest-9.1.1, pluggy-1.6.0
rootdir: <репозиторий>
configfile: pyproject.toml
testpaths: student-tests
plugins: anyio-4.15.1
collected 154 items / 24 deselected / 130 selected
student-tests/test_attachments.py ...................................... [ 29%]
........ [ 35%]
student-tests/test_auth.py ...................... [ 52%]
student-tests/test_balancing.py ... [ 54%]
student-tests/test_cache.py .... [ 57%]
student-tests/test_idempotency.py ................... [ 72%]
student-tests/test_race.py .... [ 75%]
student-tests/test_request_id.py ............. [ 85%]
student-tests/test_rubric.py ................... [100%]
===================== 130 passed, 24 deselected in 34.66s ======================
# Итог: 130 passed, пропусков нет (тесты реплик идут: EXPECT_REPLICAS=2),
# из них 46 — test_attachments.py. Пользовательские ошибки (413, 415, 400,
# 404) не превращаются в 500 — каждый негативный тест проверяет статус и
# форму ошибки контракта.
+94
View File
@@ -0,0 +1,94 @@
# Что доказывает: уровни 3 и 4 на отдельном чистом стенде с LB и двумя
# репликами: публичный smoke лабы 4, собственные тесты (с тестами
# реплик), make test-failover, вложение после остановки принявшей
# реплики (тот же SHA-256 через другую, 404 постороннему), make
# test-persistence (рестарт LB, реплик и всех хранилищ, в том числе S3);
# миграции 0001 → 0002 → 0003 с нуля на пустой базе.
# Дата: 2026-10-23T16:48:19Z (UTC)
# Окружение: macOS 26.6.2, Apple M3 Pro; ВМ Docker 12 CPU / 7,7 ГиБ;
# Docker 29.9.2, Compose 5.6.1; python3 хоста 3.11.9, uv Python 3.13.15.
# Стенд: отдельный проект vladimirceva-lab4-isolated (student-tests/stand.py):
# свои PostgreSQL, Valkey, S3 с bootstrap, volume, HAProxy на свободном
# порту и 2 реплики, свои пароли и ключи S3; удаляется после прогона.
# Рабочий стенд не затрагивается.
# Код: src_sha256 bc10d566e2f63173541445a2f6273b967447e13e5dd7f1fb76900934e5692cbe
# (образ :lab4-test собран из того же рабочего дерева).
# Как повторить: make test-isolated
#
# Вывод сборки образа и строки compose о контейнерах, сети и volume
# сокращены (...); остальное — как есть.
$ make test-isolated
python3 student-tests/stand.py isolated
[isolated] project=vladimirceva-lab4-isolated
[isolated] build image
Image mtusi-messenger-vladimirceva:lab4-test Building
...
Image mtusi-messenger-vladimirceva:lab4-test Built
[isolated] start postgres, valkey and s3
...
[isolated] s3 bootstrap
[isolated] migrations
2026-10-23T16:48:31.044Z INFO src.migrations [rid=-] migrations started db=postgres:5432/messenger
2026-10-23T16:48:31.062Z INFO alembic.runtime.migration [rid=-] Context impl PostgresqlImpl.
2026-10-23T16:48:31.062Z INFO alembic.runtime.migration [rid=-] Will assume transactional DDL.
2026-10-23T16:48:31.070Z INFO alembic.runtime.migration [rid=-] Running upgrade -> 0001, messenger schema: users, sessions, chats, chat members, messages
2026-10-23T16:48:31.081Z INFO alembic.runtime.migration [rid=-] Running upgrade 0001 -> 0002, idempotency keys for sending messages
2026-10-23T16:48:31.085Z INFO alembic.runtime.migration [rid=-] Running upgrade 0002 -> 0003, attachments and message attachments
2026-10-23T16:48:31.093Z INFO src.migrations [rid=-] migrations finished db=messenger
...
[isolated] ready: lb=http://127.0.0.1:58414 replicas=2
[isolated] make test
PASS: lab4 public API scenario; infrastructure and grading evidence remain separate.
[isolated] pytest
============================= test session starts ==============================
platform darwin -- Python 3.13.15, pytest-9.1.1, pluggy-1.6.0
rootdir: <репозиторий>
configfile: pyproject.toml
testpaths: student-tests
plugins: anyio-4.15.1
collected 154 items / 24 deselected / 130 selected
student-tests/test_attachments.py ...................................... [ 29%]
........ [ 35%]
student-tests/test_auth.py ...................... [ 52%]
student-tests/test_balancing.py ... [ 54%]
student-tests/test_cache.py .... [ 57%]
student-tests/test_idempotency.py ................... [ 72%]
student-tests/test_race.py .... [ 75%]
student-tests/test_request_id.py ............. [ 85%]
student-tests/test_rubric.py ................... [100%]
===================== 130 passed, 24 deselected in 33.94s ======================
[isolated] make test-failover (scripts/stop-one.sh)
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
{"observed_instances_before": 2, "successful_writes": 124, "failed_attempts": 0, "first_recovery_seconds": 1.199}
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
[isolated] restore replicas
...
[isolated] attachment failover (scripts/lab4.py, stop the uploader)
upload: 201 X-Instance-Id=8e155477e367 size=111817 sha256=99ea7533c441f79c… (fixture 99ea7533c441f79c…)
message with attachment: 201 attachment_ids=['b5f06800-4aca-48df-87bc-c67d932c448f']
...
exit 0; STOP_ONE_LOG: 2026-10-23T16:49:31Z TARGET_INSTANCE_ID=8e155477e367 container=8e155477e367cc8c061169c1856dbdaf09bba0a5c0f441499e6fda3d5560fa44 mode=stop
download by bob after stop: 200 X-Instance-Id=89d14eb71508 after 0.51s, bytes=111817, sha256 == fixture, content-type=image/png
outsider GET /attachments/{id}: 404
outsider GET /attachments/{id}/content: 404
...
vladimirceva-lab4-isolated-api-2 8e155477e367 exited Exited (0) Less than a second ago
...
PASS
[isolated] make test-persistence (scripts/restart.sh)
...
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
[isolated] cleanup
[isolated] results: {'test': 0, 'student-test': 0, 'test-failover': 0, 'attachment-failover': 0, 'test-persistence': 0}
$ docker ps -a --format '{{.Names}}' | grep isolated
(пусто)
# Итог: все пять шагов — код 0. Миграции применились с нуля на пустой
# базе (0001 → 0002 → 0003). Тесты реплик идут (EXPECT_REPLICAS=2), 130
# passed. test-failover: 124 успешные записи, ни одной неудачной, первая
# запись после hook — 1,2 с. Вложение после остановки принявшей реплики
# отдала другая (тот же SHA-256), посторонний — 404. Стенд удалён.