feat: add replicated messenger and reproducible lab3 stand
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
# Что доказывает (уровень 4: автоматические проверки отказов): одной
|
||||
# командой на отдельном стенде проверяются
|
||||
# - истечение сессии при SESSION_TTL_SECONDS=2 и то, что запросы её не
|
||||
# продлевают;
|
||||
# - запрос с токеном при остановленной БД — 503 без вызова
|
||||
# аутентификации, после возврата тот же токен работает;
|
||||
# - откат составной операции: сбой вставки участников — нет ни чата, ни
|
||||
# участников;
|
||||
# - ключ идемпотентности (лаба 3): сбой вставки сообщения уже после
|
||||
# вставки ключа откатывает и ключ (повтор с тем же ключом создаёт
|
||||
# сообщение); 503 при остановленной БД не фиксируется результатом —
|
||||
# тот же ключ после возврата даёт 201 один раз; срок ключа 2 с на
|
||||
# «тесном» API — в срок повтор и 409, после срока ключ занимается заново;
|
||||
# - остановленная БД: 503 быстро, без деталей; запись во время отказа не
|
||||
# появилась;
|
||||
# - замёрзшая БД и исчерпанный пул: 503 за срок операции + закрытие
|
||||
# соединения, второй запрос — за срок ожидания пула;
|
||||
# - readiness без БД — 503 за 2 с, live 200; без Valkey — ready 200;
|
||||
# - Valkey остановлен, заморожен, очищен и вернулся: те же ответы, не
|
||||
# дольше срока команды 0,2 с, кэш снова в работе без рестарта API.
|
||||
# Дата (UTC): 2026-10-13T22:16:52Z — 2026-10-13T22:17:44Z
|
||||
# Окружение: macOS 26.6.2, Apple M3 Pro; Docker 29.8.2, Compose 5.5.1;
|
||||
# python3 хоста 3.11.9 (stand.py, fault_hook.py), pytest на Python 3.13.15
|
||||
# Стенд: student-tests/stand.py failures — проект vladimirceva-lab3-failures:
|
||||
# обычный API (настройки по умолчанию) и «тесный» (SESSION_TTL_SECONDS=2,
|
||||
# IDEMPOTENCY_TTL_SECONDS=2, DB_POOL_SIZE=1, DB_POOL_OVERFLOW=0,
|
||||
# DB_POOL_TIMEOUT=1, DB_OPERATION_TIMEOUT=2) — по одному процессу без LB;
|
||||
# хранилища — только через hook student-tests/fault_hook.py; стенд удалён
|
||||
# после прогона. Код src_sha256 0349e9a270178467. Абсолютный путь заменён
|
||||
# на <репозиторий>; строки docker compose опущены («...»).
|
||||
# Как повторить: make failure-checks FAULT_ARGS=-rP
|
||||
|
||||
$ time make failure-checks FAULT_ARGS=-rP
|
||||
python3 student-tests/stand.py failures -rP
|
||||
[failures] project=vladimirceva-lab3-failures
|
||||
[failures] build image
|
||||
...
|
||||
[failures] start postgres and valkey
|
||||
...
|
||||
[failures] migrations
|
||||
...
|
||||
2026-10-13T22:16:56.998Z INFO alembic.runtime.migration [rid=-] Running upgrade -> 0001, messenger schema: users, sessions, chats, chat members, messages
|
||||
2026-10-13T22:16:57.006Z INFO alembic.runtime.migration [rid=-] Running upgrade 0001 -> 0002, idempotency keys for sending messages
|
||||
2026-10-13T22:16:57.011Z INFO src.migrations [rid=-] migrations finished db=messenger
|
||||
[failures] ready: api=http://127.0.0.1:63305 tight=http://127.0.0.1:63311
|
||||
[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 99 items / 84 deselected / 15 selected
|
||||
|
||||
student-tests/test_failures.py ............... [100%]
|
||||
|
||||
==================================== PASSES ====================================
|
||||
________________________ test_database_stopped_and_back ________________________
|
||||
----------------------------- Captured stdout call -----------------------------
|
||||
postgres stopped: POST message -> 503 in 0.007s
|
||||
___________________ test_frozen_database_and_exhausted_pool ____________________
|
||||
----------------------------- Captured stdout call -----------------------------
|
||||
postgres paused: first request -> 503 in 4.02s, second (pool of 1 busy) -> 503 in 1.02s
|
||||
_______________________ test_readiness_without_database ________________________
|
||||
----------------------------- Captured stdout call -----------------------------
|
||||
postgres stopped: /health/ready -> 503 in 0.013s
|
||||
_______________________ test_valkey_stopped_is_bypassed ________________________
|
||||
----------------------------- Captured stdout call -----------------------------
|
||||
valkey stopped: GET chat -> 200 in 0.013s, POST message -> 201 in 0.009s
|
||||
_____________________ test_valkey_paused_costs_one_timeout _____________________
|
||||
----------------------------- Captured stdout call -----------------------------
|
||||
valkey paused: baseline 0.002s, first read 0.219s, second read 0.006s
|
||||
====================== 15 passed, 84 deselected in 43.01s ======================
|
||||
[failures] cleanup
|
||||
[failures] results: {'fault': 0}
|
||||
make failure-checks FAULT_ARGS=-rP 4.34s user 2.15s system 12% cpu 51.845 total
|
||||
|
||||
# 15 passed, весь прогон со сборкой и уборкой — 52 с. Замёрзшая БД на
|
||||
# «тесном» API: 503 через 4,02 с = срок операции 2 с + закрытие 2 с; пока
|
||||
# единственное соединение пула занято, второй запрос — 503 через 1,02 с
|
||||
# (срок ожидания пула). Замёрзший Valkey добавил к одному запросу 0,22 с
|
||||
# (срок команды 0,2 с), следующий — без ожидания (окно пропуска 5 с).
|
||||
# Тексты остальных проверок — student-tests/test_failures.py.
|
||||
@@ -0,0 +1,71 @@
|
||||
# Что доказывает (уровни 3 и 4): собственный набор целиком через HAProxy
|
||||
# рабочего стенда с двумя репликами (EXPECT_REPLICAS=2: тесты реплик
|
||||
# выполняются, а не пропускаются). Отдельно — вывод тестов реплик и
|
||||
# идемпотентности через разные реплики:
|
||||
# - одна сессия, 20 запросов — ответили обе реплики, без повторного входа;
|
||||
# - сообщение, записанное через одну реплику, видно в каждом чтении,
|
||||
# в том числе через другую;
|
||||
# - X-Instance-Id стабилен на время жизни процесса;
|
||||
# - 10 одновременных отправок одного тела с одним Idempotency-Key — десять
|
||||
# 201 с одним id и одно сообщение в истории, причём пара пересекающихся
|
||||
# по времени запросов обслужена разными репликами;
|
||||
# - повтор с тем же ключом через другую реплику — тот же Message; другое
|
||||
# тело — 409 от обеих реплик.
|
||||
# Дата (UTC): 2026-10-13T22:11Z
|
||||
# Окружение: macOS 26.6.2, Apple M3 Pro; Docker 29.8.2, Compose 5.5.1;
|
||||
# pytest на Python 3.13.15 (uv)
|
||||
# Стенд: рабочий проект vladimirceva-lab3, HAProxy на 127.0.0.1:8090 (на
|
||||
# этой машине), код src_sha256 0349e9a270178467. Тесты оставляют в
|
||||
# рабочей базе синтетических пользователей и чаты; чистый прогон —
|
||||
# make test-isolated (evidence/tests/test-isolated.txt).
|
||||
# Как повторить: make student-test [BASE_URL=...] (EXPECT_REPLICAS берётся
|
||||
# из API_REPLICAS); вывод тестов реплик — pytest -rP по тем же тестам.
|
||||
|
||||
$ make student-test BASE_URL=http://localhost:8090 EXPECT_REPLICAS=2
|
||||
BASE_URL=http://localhost:8090 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 99 items / 15 deselected / 84 selected
|
||||
|
||||
student-tests/test_auth.py ...................... [ 26%]
|
||||
student-tests/test_balancing.py ... [ 29%]
|
||||
student-tests/test_cache.py .... [ 34%]
|
||||
student-tests/test_idempotency.py ................... [ 57%]
|
||||
student-tests/test_race.py .... [ 61%]
|
||||
student-tests/test_request_id.py ............. [ 77%]
|
||||
student-tests/test_rubric.py ................... [100%]
|
||||
|
||||
====================== 84 passed, 15 deselected in 13.15s ======================
|
||||
|
||||
$ BASE_URL=http://localhost:8090 EXPECT_REPLICAS=2 uv run pytest -rP -q \
|
||||
student-tests/test_balancing.py \
|
||||
student-tests/test_race.py::test_same_key_through_replicas \
|
||||
student-tests/test_idempotency.py::test_replay_through_other_replica
|
||||
..... [100%]
|
||||
==================================== PASSES ====================================
|
||||
_____________________ test_one_session_on_several_replicas _____________________
|
||||
----------------------------- Captured stdout call -----------------------------
|
||||
one session, 20 requests: {'4c13b772d928': 10, 'd69ba3cda2cf': 10}
|
||||
___________________ test_write_visible_through_other_replica ___________________
|
||||
----------------------------- Captured stdout call -----------------------------
|
||||
written via d69ba3cda2cf, read via {'4c13b772d928': 3, 'd69ba3cda2cf': 3}
|
||||
____________________ test_instance_id_is_stable_per_process ____________________
|
||||
----------------------------- Captured stdout call -----------------------------
|
||||
series: [{'4c13b772d928': 6, 'd69ba3cda2cf': 6}, {'4c13b772d928': 6, 'd69ba3cda2cf': 6}]
|
||||
________________________ test_same_key_through_replicas ________________________
|
||||
----------------------------- Captured stdout call -----------------------------
|
||||
statuses={201: 10} peak_in_flight=10 ids=1 history=1
|
||||
attempt 1: served={'d69ba3cda2cf': 5, '4c13b772d928': 5} overlapping pairs={('4c13b772d928', 'd69ba3cda2cf')}
|
||||
______________________ test_replay_through_other_replica _______________________
|
||||
----------------------------- Captured stdout call -----------------------------
|
||||
sent via d69ba3cda2cf, replayed via ['4c13b772d928', 'd69ba3cda2cf']
|
||||
409 via ['4c13b772d928', 'd69ba3cda2cf']
|
||||
5 passed in 1.32s
|
||||
|
||||
# 15 deselected — проверки отказов (маркер fault): их выполняет только
|
||||
# make failure-checks (evidence/tests/failure-checks.txt). Абсолютный путь
|
||||
# заменён на <репозиторий>.
|
||||
@@ -0,0 +1,71 @@
|
||||
# Что доказывает (уровни 3 и 4): на отдельном чистом стенде лабы 3 (свои
|
||||
# PostgreSQL, Valkey и volume, HAProxy и две реплики, свои случайные
|
||||
# пароли, без .env) одной командой проходят: публичный smoke (make test),
|
||||
# весь собственный набор через LB с тестами реплик (EXPECT_REPLICAS=2),
|
||||
# make test-failover (hook scripts/stop-one.sh в проекте стенда), возврат
|
||||
# реплик и make test-persistence (hook scripts/restart.sh). Миграции на
|
||||
# пустом volume — сервисом migrate, обе ревизии по порядку. Рабочий стенд
|
||||
# не затрагивается, отдельный удаляется вместе с volume.
|
||||
# Дата (UTC): 2026-10-13T22:16:04Z — 2026-10-13T22:16:52Z
|
||||
# Окружение: macOS 26.6.2, Apple M3 Pro; Docker 29.8.2, Compose 5.5.1;
|
||||
# python3 хоста 3.11.9 (stand.py, проверки skeleton), pytest на Python
|
||||
# 3.13.15 (uv)
|
||||
# Стенд: student-tests/stand.py isolated — проект vladimirceva-lab3-isolated,
|
||||
# HAProxy на свободном порту 127.0.0.1; код src_sha256 0349e9a270178467.
|
||||
# Абсолютный путь заменён на <репозиторий>; строки docker compose о
|
||||
# контейнерах, сети и сборке опущены («...»).
|
||||
# Как повторить: make test-isolated
|
||||
|
||||
$ time make test-isolated
|
||||
python3 student-tests/stand.py isolated
|
||||
[isolated] project=vladimirceva-lab3-isolated
|
||||
[isolated] build image
|
||||
...
|
||||
[isolated] start postgres and valkey
|
||||
...
|
||||
[isolated] migrations
|
||||
...
|
||||
2026-10-13T22:16:09.550Z INFO src.migrations [rid=-] migrations started db=postgres:5432/messenger
|
||||
2026-10-13T22:16:09.570Z INFO alembic.runtime.migration [rid=-] Context impl PostgresqlImpl.
|
||||
2026-10-13T22:16:09.570Z INFO alembic.runtime.migration [rid=-] Will assume transactional DDL.
|
||||
2026-10-13T22:16:09.576Z INFO alembic.runtime.migration [rid=-] Running upgrade -> 0001, messenger schema: users, sessions, chats, chat members, messages
|
||||
2026-10-13T22:16:09.618Z INFO alembic.runtime.migration [rid=-] Running upgrade 0001 -> 0002, idempotency keys for sending messages
|
||||
2026-10-13T22:16:09.625Z INFO src.migrations [rid=-] migrations finished db=messenger
|
||||
...
|
||||
[isolated] ready: lb=http://127.0.0.1:62916 replicas=2
|
||||
[isolated] make test
|
||||
PASS: lab3 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 99 items / 15 deselected / 84 selected
|
||||
|
||||
student-tests/test_auth.py ...................... [ 26%]
|
||||
student-tests/test_balancing.py ... [ 29%]
|
||||
student-tests/test_cache.py .... [ 34%]
|
||||
student-tests/test_idempotency.py ................... [ 57%]
|
||||
student-tests/test_race.py .... [ 61%]
|
||||
student-tests/test_request_id.py ............. [ 77%]
|
||||
student-tests/test_rubric.py ................... [100%]
|
||||
|
||||
====================== 84 passed, 15 deselected in 12.47s ======================
|
||||
[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": 116, "failed_attempts": 0, "first_recovery_seconds": 1.729}
|
||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
[isolated] restore replicas
|
||||
...
|
||||
[isolated] make test-persistence (scripts/restart.sh)
|
||||
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||
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, 'test-persistence': 0}
|
||||
make test-isolated 3.28s user 0.94s system 8% cpu 47.602 total
|
||||
|
||||
# Весь прогон со сборкой (из кэша слоёв), стендом, тестами и уборкой —
|
||||
# 48 с. 15 deselected — проверки отказов (маркер fault): их выполняет
|
||||
# make failure-checks (evidence/tests/failure-checks.txt).
|
||||
Reference in New Issue
Block a user