# Что доказывает: уровни 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. Стенд удалён.
