исправление

This commit is contained in:
2026-10-15 19:44:46 +03:00
parent 825f6fdbf5
commit f7f689c7c2
26 changed files with 482 additions and 399 deletions
+3 -1
View File
@@ -60,9 +60,11 @@ ps:
logs:
docker compose logs --tail 50 api lb
# Вернуть остановленные реплики (после make test-failover): запустить всё, что должно работать.
# Вернуть остановленные реплики (после make test-failover): запустить всё, что должно работать,
# и дождаться, пока HAProxy снова возьмёт в работу все реплики.
restore:
docker compose up -d --wait
$(PYTHON) student-tests/stand.py
# ---------- собственные проверки lab1–lab2 (теперь через балансировщик) ----------
+22 -20
View File
@@ -3,7 +3,7 @@
- Автор, группа: Гаджиев Нухбала, БВТ2303
- Целевая оценка; выбранный трек 5, если нужен: 4, трек 5 не выбран
- Commit/PR: https://gitea.privcloud.tech/mtusi2026/mtusi2026lab3/pulls/9
- Использованные источники, библиотеки и помощь ИИ: всё из lab2 (FastAPI, uvicorn, pydantic, psycopg 3 + psycopg-pool, argon2-cffi, valkey-py; версии в requirements.txt); образы haproxy:3.2.25-alpine, python:3.12.8-slim-bookworm, postgres:17.10-bookworm, valkey/valkey:8.1.9; документация HAProxy 3.2 (resolvers, server-template, http-check, retries, observe), Docker Compose (deploy.replicas и resources, depends_on с condition, healthcheck), PostgreSQL (INSERT ... ON CONFLICT, уникальные ограничения). ИИ использовался только как вспомогательный ресурс: для оценки решения, написания комментариев к коду и составления текстовых документов.
- Использованные источники, библиотеки и помощь ИИ: всё из lab2 (FastAPI, uvicorn, pydantic, psycopg 3 + psycopg-pool, argon2-cffi, valkey-py; версии в requirements.txt); образы haproxy:3.2.25-alpine, python:3.12.8-slim-bookworm, postgres:17.10-bookworm, valkey/valkey:8.1.9; документация HAProxy 3.2 (resolvers, server-template, http-check, retries, observe), Docker Compose (deploy.replicas и resources, depends_on с condition, healthcheck), PostgreSQL (INSERT ... ON CONFLICT, уникальные ограничения). ИИ использовался как вспомогательный ресурс: для оценки решения, написания комментариев к коду и составления текстовых документов.
## Запуск из чистого clone
@@ -21,7 +21,7 @@ make ps # api x2, lb, postgres, valkey: healthy;
make check PYTHON=python
make test PYTHON=python
make test-failover ACTION_SCRIPT=scripts/stop-one.cmd PYTHON=python # Linux/macOS: scripts/stop-one.sh
make restore # вернуть остановленную реплику
make restore PYTHON=python # вернуть реплику и дождаться её в HAProxy
make test-persistence ACTION_SCRIPT=scripts/restart.cmd PYTHON=python # Linux/macOS: scripts/restart.sh
```
@@ -31,7 +31,7 @@ make test-persistence ACTION_SCRIPT=scripts/restart.cmd PYTHON=python # Linux/m
Безопасная остановка: `make down` (контейнеры удаляются, volume `pgdata` остаётся). Намеренное удаление учебных данных: `docker compose down -v`, затем `rm -rf secrets` и заново `sh scripts/init-secrets.sh`.
Почему у hook два варианта: тест запускает hook напрямую, без shell, а Python на Windows не запускает `.sh` (WinError 193). Поэтому есть `scripts/stop-one.cmd` и `scripts/restart.cmd` для Windows и `.sh` для Linux/macOS. Логика stop-one одна (`scripts/stop_one.py`), оба варианта вызывают её. Остановленную реплику hook оставляет остановленной, вернуть её: `make restore` (= `docker compose up -d --wait`).
Почему у hook два варианта: тест запускает hook напрямую, без shell, а Python на Windows не запускает `.sh` (WinError 193). Поэтому есть `scripts/stop-one.cmd` и `scripts/restart.cmd` для Windows и `.sh` для Linux/macOS. Логика stop-one одна (`scripts/stop_one.py`), оба варианта вызывают её. Остановленную реплику hook оставляет остановленной, вернуть её: `make restore PYTHON=python` (`docker compose up -d --wait`, затем ожидание, пока HAProxy снова возьмёт в работу все реплики).
## Архитектура и решения
@@ -71,7 +71,7 @@ migrate (одноразовый): применяет migrations/*.sql до ст
- Плановая остановка (`docker stop`, SIGTERM): реплика сразу отвечает 503 на `/health/ready`, но ещё 3 с обслуживает запросы (`SHUTDOWN_DRAIN_SECONDS`); HAProxy за это время выводит её. Потом uvicorn закрывает приём и доделывает начатые запросы (не дольше 8 с: ожидание пула 3 с + statement_timeout 5 с). Docker ждёт 15 с (`stop_grace_period`), затем SIGKILL. Hook ждёт не дольше 8 с, поэтому укладывается в 10 с теста.
- Таймауты согласованы снизу вверх: запрос к БД ≤ 8 с < `timeout server 15s` в HAProxy < 15 с `stop_grace_period`; `timeout connect 1s`.
- HAProxy повторяет запрос только при ошибке соединения (запрос ещё не ушёл) и на другой реплике (`retries 2`, `option redispatch`). Уже отправленный POST сам не повторяет: это делает клиент с тем же `Idempotency-Key`.
- Аварийный режим: если готовых реплик нет совсем (например, недоступна PostgreSQL), запросы идут в API через резервные слоты `fallback`. Клиент получает ответ самого API (503 в формате контракта, с `X-Request-Id` и `X-Instance-Id`), а `/health/live` отвечает 200.
- Запросы получают только реплики, прошедшие проверку готовности, резервных серверов без проверки нет. Если не готова ни одна реплика (например, недоступна PostgreSQL), балансировщик сам отвечает 503 и запрос до API не передаёт, даже если реплика могла бы ответить из кэша. Ответы самого балансировщика (503, 502, 504) отдаются в формате ошибки контракта с `X-Request-Id`; `X-Instance-Id` у них нет, потому что ни одна реплика их не создавала.
Миграции. `migrate` запускается после healthy PostgreSQL, применяет новые файлы (учёт в `schema_migrations`, `pg_advisory_lock` от двух одновременных запусков) и завершается. `api` стартует только после его успешного завершения (`depends_on: condition: service_completed_successfully`). Миграция 004 только добавляет столбцы, которые могут быть NULL, поэтому совместима с уже работающей версией: старый код пишет сообщения без ключа. Порядок обновления: сначала `docker compose run --rm migrate`, потом замена реплик по одной (`make rolling-update`).
@@ -97,6 +97,7 @@ migrate (одноразовый): применяет migrations/*.sql до ст
| --- | --- | --- | --- |
| Публичный smoke | make test | PASS: lab3 public API scenario (в том числе повтор с ключом, 409, 400 без ключа) | evidence/test.txt |
| Структура skeleton и контракт не изменены | make check | PASS: offline skeleton structure | evidence/check.txt |
| Замечание к MR: резервные слоты fallback без проверки обходили readiness | убраны из infra/haproxy/haproxy.cfg; make failure-postgres; make check-stack | PostgreSQL остановлена: HAProxy за 2,5–2,8 с вывел обе реплики (изнутри контейнеров live 200, ready 503); /users/me с действующим токеном из кэша через LB — 503 от балансировщика без X-Instance-Id, до реплики не дошёл; запись не сохранилась; check-stack: в backend нет резервных серверов и серверов без проверки. На старом конфиге тот же тест падает (/users/me — 200) | evidence/failure-postgres.txt, evidence/stack.txt |
| 3: стенд в compose.yaml, одна команда; ≥2 API, одна точка входа, общая БД и общий кэш сессий | docker compose up -d --build --wait; make check-stack | 2 реплики api без портов; опубликован только lb на 127.0.0.1; одна postgres и один valkey | evidence/stack.txt |
| 3: запросы одного пользователя обслуживают разные реплики без повторного входа (X-Instance-Id) | make student-test (test_one_session_is_served_by_every_replica), make demo | 20 запросов с одним токеном — 2 разных X-Instance-Id по 10 раз; это ID запущенных контейнеров api | evidence/student-test.txt |
| 3: доступ через LB — основной маршрут | все тесты на BASE_URL=http://127.0.0.1:8080 (HAProxy) | порт наружу есть только у lb | evidence/stack.txt |
@@ -126,31 +127,31 @@ migrate (одноразовый): применяет migrations/*.sql до ст
| Реплика | Отказ | Вывод из LB, с | Ошибок (коды) | Ошибки закончились через, с | Записей/с до → после | p95 записи после, мс | Возврат в LB после `docker start`, с | Потери / дубли |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| 4e5560c6d072 | stop | 0.83 | 0 (-) | 0.0 | 231.0 → 112.4 | 78.0 | 4.01 | 0 / 0 (подтверждено 1817) |
| 4e5560c6d072 | kill | 0.2 | 4 (502: 4) | 0.11 | 184.7 → 98.0 | 93.0 | 4.01 | 0 / 0 (подтверждено 1536) |
| 7740e49a1d8c | stop | 1.27 | 0 (-) | 0.0 | 204.0 → 110.7 | 78.0 | 4.91 | 0 / 0 (подтверждено 1719) |
| 7740e49a1d8c | kill | 0.17 | 2 (502: 2) | 0.11 | 151.7 → 103.7 | 78.0 | 4.17 | 0 / 0 (подтверждено 1492) |
| 1c773748bc05 | stop | 1.16 | 0 (-) | 0.0 | 114.7 → 65.9 | 125.0 | 4.5 | 0 / 0 (подтверждено 1006) |
| 1c773748bc05 | kill | 0.11 | 1 (502: 1) | 0.11 | 151.3 → 70.3 | 109.0 | 5.64 | 0 / 0 (подтверждено 1160) |
| aa3dac85e7ed | stop | 1.59 | 0 (-) | 0.0 | 104.0 → 57.8 | 141.0 | 3.97 | 0 / 0 (подтверждено 892) |
| aa3dac85e7ed | kill | 0.25 | 1 (502: 1) | 0.14 | 155.3 → 79.7 | 94.0 | 4.25 | 0 / 0 (подтверждено 1266) |
Rolling update под той же нагрузкой (`make rolling-update`, evidence/rolling-update.json): версия dev → rolling-20261015-000949, 2 реплики заменены по одной за 22.59 с (4e5560c6d072 → b021c4a75186: новая готова через 6.75 с, шаг 11.38 с; 7740e49a1d8c → a1fe17dd4bd2: новая готова через 6.11 с, шаг 11.2 с). Записей/с до: 162.3, во время замены: 144.2; ошибок: 0 (-); p95 78.0 мс, максимум 250.0 мс; подтверждено 4260 сообщений, потерь и дублей нет.
Rolling update под той же нагрузкой (`make rolling-update`, evidence/rolling-update.json): версия dev → rolling-20261015-193851, 2 реплики заменены по одной за 22.38 с (1c773748bc05 → e8baa1b553a1: новая готова через 6.64 с, шаг 11.8 с; aa3dac85e7ed → db0d1f669f44: новая готова через 5.89 с, шаг 10.55 с). Записей/с до: 104.3, во время замены: 138.7; ошибок: 0 (-); p95 63.0 мс, максимум 312.0 мс; подтверждено 3867 сообщений, потерь и дублей нет.
Публичный генератор нагрузки (`make load-profile` = `tests/load.py`, closed loop, 4 потока, 30 с, 2 реплики): 210.145 успешных POST/с, ошибок 0 (доля 0.0), задержка успешных: p50 16.0 мс, p95 47.0 мс, p99 78.0 мс.
Публичный генератор нагрузки (`make load-profile` = `tests/load.py`, closed loop, 4 потока, 30 с, 2 реплики): 130.05 успешных POST/с, ошибок 0 (доля 0.0), задержка успешных: p50 16.0 мс, p95 78.0 мс, p99 141.0 мс.
| Сервис | CPU, % макс. (100 % = 1 ядро) | RAM макс. / лимит, МиБ |
| --- | --- | --- |
| api | 103.4 | 140 / 512 |
| api | 98.2 | 94 / 512 |
| lb | 25.5 | 16 / 128 |
| postgres | 31.5 | 49 / 512 |
| valkey | 6.7 | 8 / 128 |
| api | 97.5 | 83 / 512 |
| api | 90.2 | 122 / 512 |
| lb | 24.2 | 20 / 128 |
| postgres | 31.1 | 52 / 512 |
| valkey | 9.6 | 8 / 128 |
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
| --- | --- | --- | --- |
| `docker stop` одной реплики (по очереди каждой) | реплика сама уходит из балансировки до выхода; ошибок нет | ошибок всего 0 за 2 прогона; HAProxy вывел реплику не позже 1.27 с; остановленная реплика после остановки не отвечала | ошибок не было; потерь и дублей 0 |
| `docker kill` одной реплики (по очереди каждой) | несколько 502 у запросов, начатых на ней; клиент повторяет с тем же ключом | ошибок всего 6 за 2 прогона; HAProxy вывел реплику не позже 0.2 с; остановленная реплика после остановки не отвечала | ошибки закончились не позже 0.11 с после отказа; потерь и дублей 0 |
| Rolling update 2 реплик под нагрузкой | замена по одной без простоя | ошибок 0, записей/с 144.2 | 22.59 с на замену; потерь и дублей 0 |
| Перезапуск всего стенда (`make persistence`, hook restart) | данные и действующий токен сохраняются | PASS: те же контейнеры с новым временем старта, прежний токен работает | 18.5 с на весь тест (hook + готовность); потерь нет |
| `docker stop` одной реплики (по очереди каждой) | реплика сама уходит из балансировки до выхода; ошибок нет | ошибок всего 0 за 2 прогона; HAProxy вывел реплику не позже 1.59 с; остановленная реплика после остановки не отвечала | ошибок не было; потерь и дублей 0 |
| `docker kill` одной реплики (по очереди каждой) | несколько 502 у запросов, начатых на ней; клиент повторяет с тем же ключом | ошибок всего 2 за 2 прогона; HAProxy вывел реплику не позже 0.25 с; остановленная реплика после остановки не отвечала | ошибки закончились не позже 0.14 с после отказа; потерь и дублей 0 |
| Rolling update 2 реплик под нагрузкой | замена по одной без простоя | ошибок 0, записей/с 138.7 | 22.38 с на замену; потерь и дублей 0 |
| Перезапуск всего стенда (`make persistence`, hook restart) | данные и действующий токен сохраняются | PASS: те же контейнеры с новым временем старта, прежний токен работает | 19.6 с на весь тест (hook + готовность); потерь нет |
| `docker compose stop valkey` | API работает без кэша | ready 200; вход, сообщения и logout работают через PostgreSQL | кэш снова включается за 1–2 с после start; потерь нет |
| `docker compose stop postgres` | 503 без подробностей, аноним не доверенный | через балансировщик (слоты fallback): ready 503, бизнес-запросы 503, без токена 401 | после start прежний токен и данные на месте; запросы во время отказа не сохранены (503) |
| `docker compose stop postgres` | неготовые реплики исключены из маршрутизации, клиенту 503 | HAProxy вывел обе реплики (ready 503, live 200); запрос с действующим токеном из кэша -> 503 от балансировщика, до реплики не дошёл; запись не сохранилась | после start прежний токен и данные на месте; запросы во время отказа не сохранены (503) |
| `docker compose pause valkey`, logout, `unpause` | отозванный токен не оживает ни на одной реплике | после unpause отозванный токен всегда 401 | поколение кэша сменилось после возвращения Valkey; отзыв не потерян |
<!-- measurements:end -->
@@ -165,4 +166,5 @@ Rolling update под той же нагрузкой (`make rolling-update`, evi
- `X-Instance-Id` раскрывает ID контейнера; в lab7 его нужно заменить случайным alias.
- Ключи идемпотентности хранятся вместе с сообщениями бессрочно, индекс растёт вместе с числом сообщений.
- Общее поколение кэша закрывает сценарий «отзыв во время сбоя Valkey» для всех реплик, которые заметили сбой. Если сбой Valkey короче интервала проверки (1 с) и logout пришёлся ровно на него, реплика, не заметившая сбой, теоретически может до следующей проверки другой реплики (≤ 1 с) доверять старой записи.
- Если PostgreSQL недоступна, через балансировщик недоступно всё, включая `/health/live` (готовых реплик нет, HAProxy отвечает 503). Что сами реплики живы, видно изнутри контейнеров и по статистике HAProxy.
- API подключается к PostgreSQL владельцем базы, Basic идёт по HTTP — только для локального стенда (минимальные права и TLS — lab7).
+10 -10
View File
@@ -2,18 +2,18 @@ docker compose --profile tools run --rm db-test
Container mtusi-lab3-postgres-1 Running
Container mtusi-lab3-postgres-1 Waiting
Container mtusi-lab3-postgres-1 Healthy
Container mtusi-lab3-db-test-run-20693dcae707 Creating
Container mtusi-lab3-db-test-run-20693dcae707 Created
Container mtusi-lab3-db-test-run-4288ad929232 Creating
Container mtusi-lab3-db-test-run-4288ad929232 Created
test_concurrent_registration_has_one_winner (test_store.StoreIntegrationTest.test_concurrent_registration_has_one_winner) ...
20 параллельных create_user: 1 создан, 19 получили Conflict (409)
ok
test_concurrent_same_idempotency_key_creates_one_row (test_store.StoreIntegrationTest.test_concurrent_same_idempotency_key_creates_one_row) ...
test_concurrent_same_idempotency_key_creates_one_row (test_store.StoreIntegrationTest.test_concurrent_same_idempotency_key_creates_one_row) ... ok
test_create_chat_rolls_back_when_failing_midway (test_store.StoreIntegrationTest.test_create_chat_rolls_back_when_failing_midway) ...
20 одновременных add_message с одним ключом: 1 строка, 1 новое + 19 повторов с тем же сообщением
ok
test_create_chat_rolls_back_when_failing_midway (test_store.StoreIntegrationTest.test_create_chat_rolls_back_when_failing_midway) ... ok
test_database_rejects_message_from_non_member (test_store.StoreIntegrationTest.test_database_rejects_message_from_non_member) ...
чат с несуществующим участником: транзакция откатилась, строк chats/chat_members не осталось
чат с несуществующим участником: транзакция откатилась, строк chats/chat_members не осталось
ok
test_database_rejects_message_from_non_member (test_store.StoreIntegrationTest.test_database_rejects_message_from_non_member) ...
INSERT сообщения от не-участника напрямую в БД: ForeignKeyViolation
ok
test_migrations_rerun_is_noop (test_store.StoreIntegrationTest.test_migrations_rerun_is_noop) ...
@@ -22,11 +22,11 @@ ok
test_old_version_insert_without_key_still_works (test_store.StoreIntegrationTest.test_old_version_insert_without_key_still_works) ...
INSERT как в lab2 (без ключа) после миграции 004 работает: старая версия совместима со схемой
ok
test_same_key_other_body_is_conflict (test_store.StoreIntegrationTest.test_same_key_other_body_is_conflict) ... ok
test_same_key_other_body_is_conflict (test_store.StoreIntegrationTest.test_same_key_other_body_is_conflict) ...
тот же ключ с другим телом: Conflict (409), в базе по-прежнему одна строка
ok
----------------------------------------------------------------------
Ran 7 tests in 0.259s
Ran 7 tests in 0.493s
OK
+4 -4
View File
@@ -3,20 +3,20 @@ docker compose --profile ttl up -d --wait api-short-ttl
Container mtusi-lab3-valkey-1 Running
Container mtusi-lab3-api-short-ttl-1 Creating
Container mtusi-lab3-api-short-ttl-1 Created
Container mtusi-lab3-valkey-1 Waiting
Container mtusi-lab3-postgres-1 Waiting
Container mtusi-lab3-postgres-1 Healthy
Container mtusi-lab3-valkey-1 Waiting
Container mtusi-lab3-valkey-1 Healthy
Container mtusi-lab3-postgres-1 Healthy
Container mtusi-lab3-api-short-ttl-1 Starting
Container mtusi-lab3-api-short-ttl-1 Started
Container mtusi-lab3-postgres-1 Waiting
Container mtusi-lab3-valkey-1 Waiting
Container mtusi-lab3-api-short-ttl-1 Waiting
Container mtusi-lab3-postgres-1 Waiting
Container mtusi-lab3-valkey-1 Healthy
Container mtusi-lab3-postgres-1 Healthy
Container mtusi-lab3-api-short-ttl-1 Healthy
python student-tests/expiry.py; status=$?; docker compose --profile ttl rm -sf api-short-ttl >/dev/null 2>&1; exit $status
session issued by short-TTL API, expires in 1.99s
session issued by short-TTL API, expires in 1.98s
before expiry: GET /users/me -> 200 (short API twice, main API once)
after expiry: GET /users/me -> 401 on both instances
PASS: session expired after SESSION_TTL_SECONDS; cache did not extend it
+36 -36
View File
@@ -2,7 +2,7 @@ docker compose exec -T postgres psql -X -q -U messenger -d messenger -v ON_ERROR
=== Объём данных
messages_total | messages_in_big_chat
----------------+----------------------
21635 | 12000
39193 | 12000
=== Индекс истории (migrations/001_core.sql)
@@ -14,63 +14,63 @@ docker compose exec -T postgres psql -X -q -U messenger -d messenger -v ON_ERROR
=== 1. Первая страница (limit=50, приложение просит 51 строку, чтобы понять, есть ли следующая)
QUERY PLAN
---------------------------------------------------------------------------------------------------------
Limit (actual time=0.016..0.030 rows=51 loops=1)
Buffers: shared hit=4
Limit (actual time=0.016..0.031 rows=51 loops=1)
Buffers: shared hit=5
-> Index Scan using messages_chat_history_idx on messages (actual time=0.015..0.026 rows=51 loops=1)
Index Cond: (chat_id = 'e4e1b497-87b7-4320-9a40-27873d99fc1a'::uuid)
Buffers: shared hit=4
Index Cond: (chat_id = 'c4170f65-25c8-486b-a880-dcf11a354bca'::uuid)
Buffers: shared hit=5
Planning:
Buffers: shared hit=7
Planning Time: 0.139 ms
Execution Time: 0.050 ms
Buffers: shared hit=6
Planning Time: 0.186 ms
Execution Time: 0.054 ms
=== 2. Страница из середины истории по keyset-курсору (после 6000-го сообщения)
QUERY PLAN
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Limit (actual time=0.009..0.029 rows=51 loops=1)
Buffers: shared hit=5
-> Index Scan using messages_chat_history_idx on messages (actual time=0.009..0.025 rows=51 loops=1)
Index Cond: ((chat_id = 'e4e1b497-87b7-4320-9a40-27873d99fc1a'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 01:40:00+00'::timestamp with time zone, '509a5d7d-2d2f-4322-8b64-938949155ce0'::uuid)))
Buffers: shared hit=5
Planning Time: 0.087 ms
Execution Time: 0.059 ms
Limit (actual time=0.012..0.031 rows=51 loops=1)
Buffers: shared hit=6
-> Index Scan using messages_chat_history_idx on messages (actual time=0.011..0.026 rows=51 loops=1)
Index Cond: ((chat_id = 'c4170f65-25c8-486b-a880-dcf11a354bca'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 01:40:00+00'::timestamp with time zone, '4cf0e1fe-ddbf-4da7-b5d3-e610ab7325b9'::uuid)))
Buffers: shared hit=6
Planning Time: 0.105 ms
Execution Time: 0.115 ms
=== 3. Для сравнения: та же страница через OFFSET (так приложение НЕ делает)
QUERY PLAN
-----------------------------------------------------------------------------------------------------------
Limit (actual time=1.583..1.600 rows=51 loops=1)
Buffers: shared hit=127
-> Index Scan using messages_chat_history_idx on messages (actual time=0.021..1.393 rows=6051 loops=1)
Index Cond: (chat_id = 'e4e1b497-87b7-4320-9a40-27873d99fc1a'::uuid)
Buffers: shared hit=127
Planning Time: 0.089 ms
Execution Time: 1.621 ms
Limit (actual time=1.711..1.729 rows=51 loops=1)
Buffers: shared hit=169
-> Index Scan using messages_chat_history_idx on messages (actual time=0.025..1.504 rows=6051 loops=1)
Index Cond: (chat_id = 'c4170f65-25c8-486b-a880-dcf11a354bca'::uuid)
Buffers: shared hit=169
Planning Time: 0.112 ms
Execution Time: 1.751 ms
=== 4. Для сравнения: запрос 2 без индекса (индекс удалён только внутри этой транзакции)
QUERY PLAN
-----------------------------------------------------------------------------------------------------------------------------------------------------
Limit (actual time=2.654..2.660 rows=51 loops=1)
Buffers: shared hit=172
-> Sort (actual time=2.653..2.655 rows=51 loops=1)
Limit (actual time=4.045..4.053 rows=51 loops=1)
Buffers: shared hit=180
-> Sort (actual time=4.044..4.047 rows=51 loops=1)
Sort Key: created_at, id
Sort Method: top-N heapsort Memory: 31kB
Buffers: shared hit=172
-> Bitmap Heap Scan on messages (actual time=0.782..1.755 rows=6000 loops=1)
Recheck Cond: (chat_id = 'e4e1b497-87b7-4320-9a40-27873d99fc1a'::uuid)
Filter: (ROW(created_at, id) > ROW('2026-01-01 01:40:00+00'::timestamp with time zone, '509a5d7d-2d2f-4322-8b64-938949155ce0'::uuid))
Buffers: shared hit=180
-> Bitmap Heap Scan on messages (actual time=0.996..2.398 rows=6000 loops=1)
Recheck Cond: (chat_id = 'c4170f65-25c8-486b-a880-dcf11a354bca'::uuid)
Filter: (ROW(created_at, id) > ROW('2026-01-01 01:40:00+00'::timestamp with time zone, '4cf0e1fe-ddbf-4da7-b5d3-e610ab7325b9'::uuid))
Rows Removed by Filter: 6000
Heap Blocks: exact=161
Buffers: shared hit=172
-> Bitmap Index Scan on messages_idempotency_unique (actual time=0.201..0.202 rows=12000 loops=1)
Index Cond: (chat_id = 'e4e1b497-87b7-4320-9a40-27873d99fc1a'::uuid)
Buffers: shared hit=11
Heap Blocks: exact=168
Buffers: shared hit=180
-> Bitmap Index Scan on messages_idempotency_unique (actual time=0.253..0.253 rows=12000 loops=1)
Index Cond: (chat_id = 'c4170f65-25c8-486b-a880-dcf11a354bca'::uuid)
Buffers: shared hit=12
Planning:
Buffers: shared hit=5
Planning Time: 0.097 ms
Execution Time: 2.681 ms
Planning Time: 0.126 ms
Execution Time: 4.078 ms
=== ROLLBACK: синтетические данные удалены, индекс на месте
+115 -115
View File
@@ -10,160 +10,160 @@
},
"runs": [
{
"replica": "4e5560c6d072",
"replica": "1c773748bc05",
"mode": "stop",
"command_seconds": 4.11,
"lb_excluded_after_seconds": 0.83,
"command_seconds": 4.56,
"lb_excluded_after_seconds": 1.16,
"errors": 0,
"error_codes": {},
"errors_stopped_after_seconds": 0.0,
"before": {
"seconds": 3.0,
"write_rps": 231.0,
"reads": 42,
"errors": 0,
"error_codes": {},
"write_p50_ms": 16.0,
"write_p95_ms": 32.0,
"write_max_ms": 109.0
},
"after": {
"seconds": 10.0,
"write_rps": 112.4,
"reads": 101,
"write_rps": 114.7,
"reads": 34,
"errors": 0,
"error_codes": {},
"write_p50_ms": 31.0,
"write_p95_ms": 78.0,
"write_max_ms": 282.0
"write_p95_ms": 94.0,
"write_max_ms": 172.0
},
"after": {
"seconds": 10.0,
"write_rps": 65.9,
"reads": 87,
"errors": 0,
"error_codes": {},
"write_p50_ms": 47.0,
"write_p95_ms": 125.0,
"write_max_ms": 250.0
},
"stopped_replica_answers_after_stop": 0,
"integrity": {
"confirmed_writes": 1817,
"messages_in_history": 1817,
"confirmed_writes": 1006,
"messages_in_history": 1006,
"duplicates": 0,
"lost": 0
},
"rejoin_seconds": 4.01
"rejoin_seconds": 4.5
},
{
"replica": "4e5560c6d072",
"replica": "1c773748bc05",
"mode": "kill",
"command_seconds": 0.75,
"lb_excluded_after_seconds": 0.2,
"errors": 4,
"command_seconds": 0.84,
"lb_excluded_after_seconds": 0.11,
"errors": 1,
"error_codes": {
"502": 4
"502": 1
},
"errors_stopped_after_seconds": 0.11,
"before": {
"seconds": 3.0,
"write_rps": 184.7,
"reads": 39,
"write_rps": 151.3,
"reads": 38,
"errors": 0,
"error_codes": {},
"write_p50_ms": 16.0,
"write_p50_ms": 31.0,
"write_p95_ms": 47.0,
"write_max_ms": 94.0
},
"after": {
"seconds": 10.0,
"write_rps": 98.0,
"reads": 84,
"errors": 4,
"error_codes": {
"502": 4
},
"write_p50_ms": 32.0,
"write_p95_ms": 93.0,
"write_max_ms": 156.0
},
"stopped_replica_answers_after_stop": 0,
"integrity": {
"confirmed_writes": 1536,
"messages_in_history": 1536,
"duplicates": 0,
"lost": 0
},
"rejoin_seconds": 4.01
},
{
"replica": "7740e49a1d8c",
"mode": "stop",
"command_seconds": 4.24,
"lb_excluded_after_seconds": 1.27,
"errors": 0,
"error_codes": {},
"errors_stopped_after_seconds": 0.0,
"before": {
"seconds": 3.0,
"write_rps": 204.0,
"reads": 40,
"errors": 0,
"error_codes": {},
"write_p50_ms": 16.0,
"write_p95_ms": 32.0,
"write_max_ms": 109.0
},
"after": {
"seconds": 10.0,
"write_rps": 110.7,
"reads": 102,
"errors": 0,
"error_codes": {},
"write_p50_ms": 31.0,
"write_p95_ms": 78.0,
"write_max_ms": 125.0
},
"stopped_replica_answers_after_stop": 0,
"integrity": {
"confirmed_writes": 1719,
"messages_in_history": 1719,
"duplicates": 0,
"lost": 0
},
"rejoin_seconds": 4.91
},
{
"replica": "7740e49a1d8c",
"mode": "kill",
"command_seconds": 0.83,
"lb_excluded_after_seconds": 0.17,
"errors": 2,
"error_codes": {
"502": 2
},
"errors_stopped_after_seconds": 0.11,
"before": {
"seconds": 3.0,
"write_rps": 151.7,
"reads": 42,
"errors": 0,
"error_codes": {},
"write_p50_ms": 16.0,
"write_p95_ms": 78.0,
"write_max_ms": 109.0
},
"after": {
"seconds": 10.0,
"write_rps": 103.7,
"reads": 103,
"errors": 2,
"write_rps": 70.3,
"reads": 93,
"errors": 1,
"error_codes": {
"502": 2
"502": 1
},
"write_p50_ms": 31.0,
"write_p95_ms": 78.0,
"write_p50_ms": 47.0,
"write_p95_ms": 109.0,
"write_max_ms": 1031.0
},
"stopped_replica_answers_after_stop": 0,
"integrity": {
"confirmed_writes": 1492,
"messages_in_history": 1492,
"confirmed_writes": 1160,
"messages_in_history": 1160,
"duplicates": 0,
"lost": 0
},
"rejoin_seconds": 4.17
"rejoin_seconds": 5.64
},
{
"replica": "aa3dac85e7ed",
"mode": "stop",
"command_seconds": 4.78,
"lb_excluded_after_seconds": 1.59,
"errors": 0,
"error_codes": {},
"errors_stopped_after_seconds": 0.0,
"before": {
"seconds": 3.0,
"write_rps": 104.0,
"reads": 33,
"errors": 0,
"error_codes": {},
"write_p50_ms": 31.0,
"write_p95_ms": 78.0,
"write_max_ms": 234.0
},
"after": {
"seconds": 10.0,
"write_rps": 57.8,
"reads": 78,
"errors": 0,
"error_codes": {},
"write_p50_ms": 63.0,
"write_p95_ms": 141.0,
"write_max_ms": 265.0
},
"stopped_replica_answers_after_stop": 0,
"integrity": {
"confirmed_writes": 892,
"messages_in_history": 892,
"duplicates": 0,
"lost": 0
},
"rejoin_seconds": 3.97
},
{
"replica": "aa3dac85e7ed",
"mode": "kill",
"command_seconds": 0.94,
"lb_excluded_after_seconds": 0.25,
"errors": 1,
"error_codes": {
"502": 1
},
"errors_stopped_after_seconds": 0.14,
"before": {
"seconds": 3.0,
"write_rps": 155.3,
"reads": 38,
"errors": 0,
"error_codes": {},
"write_p50_ms": 31.0,
"write_p95_ms": 47.0,
"write_max_ms": 78.0
},
"after": {
"seconds": 10.0,
"write_rps": 79.7,
"reads": 95,
"errors": 1,
"error_codes": {
"502": 1
},
"write_p50_ms": 47.0,
"write_p95_ms": 94.0,
"write_max_ms": 1094.0
},
"stopped_replica_answers_after_stop": 0,
"integrity": {
"confirmed_writes": 1266,
"messages_in_history": 1266,
"duplicates": 0,
"lost": 0
},
"rejoin_seconds": 4.25
}
]
}
+21 -21
View File
@@ -1,25 +1,25 @@
python student-tests/failover_metrics.py
api replicas: ['4e5560c6d072', '7740e49a1d8c']; load: 4 writers without pauses + 1 reader, client timeout 2 s, retry with the same Idempotency-Key; 3 s before and 10 s after the failure
--- stop 4e5560c6d072 ...
docker stop: 4.11 s; HAProxy excluded it after 0.83 s; errors: 0 {}, last error ended 0.0 s after the failure
write RPS before 231.0 -> after 112.4; p95 after 78.0 ms, max 282.0 ms; answers from the stopped replica after stop: 0
confirmed 1817, in history 1817, lost 0, duplicates 0; back in the balancer 4.01 s after docker start
--- kill 4e5560c6d072 ...
docker kill: 0.75 s; HAProxy excluded it after 0.2 s; errors: 4 {'502': 4}, last error ended 0.11 s after the failure
write RPS before 184.7 -> after 98.0; p95 after 93.0 ms, max 156.0 ms; answers from the stopped replica after stop: 0
confirmed 1536, in history 1536, lost 0, duplicates 0; back in the balancer 4.01 s after docker start
--- stop 7740e49a1d8c ...
docker stop: 4.24 s; HAProxy excluded it after 1.27 s; errors: 0 {}, last error ended 0.0 s after the failure
write RPS before 204.0 -> after 110.7; p95 after 78.0 ms, max 125.0 ms; answers from the stopped replica after stop: 0
confirmed 1719, in history 1719, lost 0, duplicates 0; back in the balancer 4.91 s after docker start
--- kill 7740e49a1d8c ...
docker kill: 0.83 s; HAProxy excluded it after 0.17 s; errors: 2 {'502': 2}, last error ended 0.11 s after the failure
write RPS before 151.7 -> after 103.7; p95 after 78.0 ms, max 1031.0 ms; answers from the stopped replica after stop: 0
confirmed 1492, in history 1492, lost 0, duplicates 0; back in the balancer 4.17 s after docker start
api replicas: ['1c773748bc05', 'aa3dac85e7ed']; load: 4 writers without pauses + 1 reader, client timeout 2 s, retry with the same Idempotency-Key; 3 s before and 10 s after the failure
--- stop 1c773748bc05 ...
docker stop: 4.56 s; HAProxy excluded it after 1.16 s; errors: 0 {}, last error ended 0.0 s after the failure
write RPS before 114.7 -> after 65.9; p95 after 125.0 ms, max 250.0 ms; answers from the stopped replica after stop: 0
confirmed 1006, in history 1006, lost 0, duplicates 0; back in the balancer 4.5 s after docker start
--- kill 1c773748bc05 ...
docker kill: 0.84 s; HAProxy excluded it after 0.11 s; errors: 1 {'502': 1}, last error ended 0.11 s after the failure
write RPS before 151.3 -> after 70.3; p95 after 109.0 ms, max 1031.0 ms; answers from the stopped replica after stop: 0
confirmed 1160, in history 1160, lost 0, duplicates 0; back in the balancer 5.64 s after docker start
--- stop aa3dac85e7ed ...
docker stop: 4.78 s; HAProxy excluded it after 1.59 s; errors: 0 {}, last error ended 0.0 s after the failure
write RPS before 104.0 -> after 57.8; p95 after 141.0 ms, max 265.0 ms; answers from the stopped replica after stop: 0
confirmed 892, in history 892, lost 0, duplicates 0; back in the balancer 3.97 s after docker start
--- kill aa3dac85e7ed ...
docker kill: 0.94 s; HAProxy excluded it after 0.25 s; errors: 1 {'502': 1}, last error ended 0.14 s after the failure
write RPS before 155.3 -> after 79.7; p95 after 94.0 ms, max 1094.0 ms; answers from the stopped replica after stop: 0
confirmed 1266, in history 1266, lost 0, duplicates 0; back in the balancer 4.25 s after docker start
replica mode cmd,s lb_out,s errors errors_end,s rps_before rps_after p95_after,ms rejoin,s
4e5560c6d072 stop 4.11 0.83 0 0.0 231.0 112.4 78.0 4.01
4e5560c6d072 kill 0.75 0.2 4 0.11 184.7 98.0 93.0 4.01
7740e49a1d8c stop 4.24 1.27 0 0.0 204.0 110.7 78.0 4.91
7740e49a1d8c kill 0.83 0.17 2 0.11 151.7 103.7 78.0 4.17
1c773748bc05 stop 4.56 1.16 0 0.0 114.7 65.9 125.0 4.5
1c773748bc05 kill 0.84 0.11 1 0.11 151.3 70.3 109.0 5.64
aa3dac85e7ed stop 4.78 1.59 0 0.0 104.0 57.8 141.0 3.97
aa3dac85e7ed kill 0.94 0.25 1 0.14 155.3 79.7 94.0 4.25
PASS: every replica was stopped (stop, kill) and restored; no lost or duplicated messages; saved evidence/failover-metrics.json
+38 -38
View File
@@ -1,48 +1,48 @@
python student-tests/run_failover.py
hook: scripts/stop-one.cmd; api replicas: ['4e5560c6d072', '7740e49a1d8c']
hook: scripts/stop-one.cmd; api replicas: ['1c773748bc05', 'aa3dac85e7ed']
=== run 1: containers before (HAProxy: api1 UP, api2 UP)
SERVICE CONTAINER STATE STARTED AT (UTC)
api 4e5560c6d072 running (healthy) 2026-10-14T20:46:50.376
api 7740e49a1d8c running (healthy) 2026-10-14T20:46:50.691
lb 91c0051bd4c8 running (healthy) 2026-10-14T20:46:51.195
migrate 523965b912bb exited 2026-10-14T20:46:48.669
postgres 5c16b9b684f2 running (healthy) 2026-10-14T21:05:32.785
valkey c74935587700 running (healthy) 2026-10-14T21:05:11.672
api 1c773748bc05 running (healthy) 2026-10-15T16:32:38.776
api aa3dac85e7ed running (healthy) 2026-10-15T16:32:38.423
lb f9c8bda9ea4c running (healthy) 2026-10-15T16:32:39.190
migrate 7420f3f1ddda exited 2026-10-15T16:32:47.434
postgres 5c16b9b684f2 running (healthy) 2026-10-15T16:35:06.670
valkey c74935587700 running (healthy) 2026-10-15T16:34:57.760
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.␍
{"observed_instances_before": 2, "successful_writes": 124, "failed_attempts": 0, "first_recovery_seconds": 4.437}␍
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
containers after (HAProxy: api2 UP)
SERVICE CONTAINER STATE STARTED AT (UTC)
api 4e5560c6d072 running (healthy) 2026-10-14T20:46:50.376
api 7740e49a1d8c exited 2026-10-14T20:46:50.691
lb 91c0051bd4c8 running (healthy) 2026-10-14T20:46:51.195
migrate 523965b912bb exited 2026-10-14T20:46:48.669
postgres 5c16b9b684f2 running (healthy) 2026-10-14T21:05:32.785
valkey c74935587700 running (healthy) 2026-10-14T21:05:11.672
the hook stopped 7740e49a1d8c (X-Instance-Id of that replica = container ID); other api containers, postgres, valkey and lb kept running
restored: docker start 7740e49a1d8c -> healthy and back in HAProxy (api1 UP, api2 UP)
=== run 2: containers before (HAProxy: api1 UP, api2 UP)
SERVICE CONTAINER STATE STARTED AT (UTC)
api 4e5560c6d072 running (healthy) 2026-10-14T20:46:50.376
api 7740e49a1d8c running (healthy) 2026-10-14T21:07:12.761
lb 91c0051bd4c8 running (healthy) 2026-10-14T20:46:51.195
migrate 523965b912bb exited 2026-10-14T20:46:48.669
postgres 5c16b9b684f2 running (healthy) 2026-10-14T21:05:32.785
valkey c74935587700 running (healthy) 2026-10-14T21:05:11.672
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.␍
{"observed_instances_before": 2, "successful_writes": 124, "failed_attempts": 0, "first_recovery_seconds": 4.594}␍
{"observed_instances_before": 2, "successful_writes": 125, "failed_attempts": 0, "first_recovery_seconds": 5.703}␍
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
containers after (HAProxy: api1 UP)
SERVICE CONTAINER STATE STARTED AT (UTC)
api 4e5560c6d072 exited 2026-10-14T20:46:50.376
api 7740e49a1d8c running (healthy) 2026-10-14T21:07:12.761
lb 91c0051bd4c8 running (healthy) 2026-10-14T20:46:51.195
migrate 523965b912bb exited 2026-10-14T20:46:48.669
postgres 5c16b9b684f2 running (healthy) 2026-10-14T21:05:32.785
valkey c74935587700 running (healthy) 2026-10-14T21:05:11.672
the hook stopped 4e5560c6d072 (X-Instance-Id of that replica = container ID); other api containers, postgres, valkey and lb kept running
restored: docker start 4e5560c6d072 -> healthy and back in HAProxy (api1 UP, api2 UP)
api 1c773748bc05 running (healthy) 2026-10-15T16:32:38.776
api aa3dac85e7ed exited 2026-10-15T16:32:38.423
lb f9c8bda9ea4c running (healthy) 2026-10-15T16:32:39.190
migrate 7420f3f1ddda exited 2026-10-15T16:32:47.434
postgres 5c16b9b684f2 running (healthy) 2026-10-15T16:35:06.670
valkey c74935587700 running (healthy) 2026-10-15T16:34:57.760
the hook stopped aa3dac85e7ed (X-Instance-Id of that replica = container ID); other api containers, postgres, valkey and lb kept running
restored: docker start aa3dac85e7ed -> healthy and back in HAProxy (api1 UP, api2 UP)
=== run 2: containers before (HAProxy: api1 UP, api2 UP)
SERVICE CONTAINER STATE STARTED AT (UTC)
api 1c773748bc05 running (healthy) 2026-10-15T16:32:38.776
api aa3dac85e7ed running (healthy) 2026-10-15T16:36:08.417
lb f9c8bda9ea4c running (healthy) 2026-10-15T16:32:39.190
migrate 7420f3f1ddda exited 2026-10-15T16:32:47.434
postgres 5c16b9b684f2 running (healthy) 2026-10-15T16:35:06.670
valkey c74935587700 running (healthy) 2026-10-15T16:34:57.760
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.␍
{"observed_instances_before": 2, "successful_writes": 125, "failed_attempts": 0, "first_recovery_seconds": 4.843}␍
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
containers after (HAProxy: api2 UP)
SERVICE CONTAINER STATE STARTED AT (UTC)
api 1c773748bc05 exited 2026-10-15T16:32:38.776
api aa3dac85e7ed running (healthy) 2026-10-15T16:36:08.417
lb f9c8bda9ea4c running (healthy) 2026-10-15T16:32:39.190
migrate 7420f3f1ddda exited 2026-10-15T16:32:47.434
postgres 5c16b9b684f2 running (healthy) 2026-10-15T16:35:06.670
valkey c74935587700 running (healthy) 2026-10-15T16:34:57.760
the hook stopped 1c773748bc05 (X-Instance-Id of that replica = container ID); other api containers, postgres, valkey and lb kept running
restored: docker start 1c773748bc05 -> healthy and back in HAProxy (api1 UP, api2 UP)
PASS: public failover test passed 2 times; every api replica was stopped once and restored
+7 -8
View File
@@ -1,12 +1,11 @@
python student-tests/dependency_failure.py postgres
stopping postgres (docker compose stop postgres)
/health/live -> 200: процесс жив
/health/ready -> 503 (1000 ms): без PostgreSQL обслуживать нельзя
бизнес-запросы с действующим токеном -> 503 unavailable (без SQL и stack trace в ответе)
без токена -> 401: аноним не становится доверенным
неизвестный токен -> 503: не подтверждается ни кэшем, ни базой
вход -> 503: сессию без базы не выдаём
регистрация -> 503
HAProxy вывел все реплики из балансировки через 2.8 с после остановки PostgreSQL (api1 DOWN, api2 DOWN)
реплика 1c773748bc05 изнутри контейнера: /health/live -> 200, /health/ready -> 503 (жива, но не готова)
реплика aa3dac85e7ed изнутри контейнера: /health/live -> 200, /health/ready -> 503 (жива, но не готова)
GET /users/me с действующим токеном (он есть в кэше) -> 503 от балансировщика, без X-Instance-Id: до неготовой реплики запрос не дошёл
бизнес-запросы (список чатов, история, отправка сообщения) -> 503 от балансировщика
без токена, регистрация и /health/ready через балансировщик -> 503: успешного ответа нет ни у кого
starting postgres again
after recovery: прежний токен работает, подтверждённые сообщения на месте
PASS: postgres outage handled without trusting anonymous requests
PASS: postgres outage: not ready replicas were excluded by the balancer, no request reached them, nothing was stored; data and the existing token survived
+3 -3
View File
@@ -1,7 +1,7 @@
python student-tests/dependency_failure.py valkey
stopping valkey (docker compose stop valkey)
/health/ready -> 200 (0 ms): Valkey не критичен, API готов
existing token: GET /users/me -> 200 (4016 ms), сессия проверена по PostgreSQL (этот запрос и обнаружил сбой кэша)
/health/ready -> 200 (15 ms): Valkey не критичен, API готов
existing token: GET /users/me -> 200 (0 ms), сессия проверена по PostgreSQL (этот запрос и обнаружил сбой кэша)
POST message -> 201, история читается
register + login new user -> 201
logout -> 204, затем тот же токен -> 401 (отзыв записан в PostgreSQL)
@@ -9,4 +9,4 @@ logout -> 204, затем тот же токен -> 401 (отзыв записа
через 6 с, ещё 10 x GET /users/me: max 31 ms (повторные попытки — в фоне)
starting valkey again
after recovery: прежний токен работает, подтверждённые сообщения на месте
PASS: valkey outage handled without trusting anonymous requests
PASS: valkey outage handled without the cache; revoked tokens stay revoked
+10 -10
View File
@@ -3,24 +3,24 @@ python student-tests/load_profile.py
"lab": 3,␍
"workload": "closed-loop POST messages; no automatic retries",␍
"requested_duration_seconds": 30.0,␍
"elapsed_seconds": 30.203,␍
"elapsed_seconds": 30.25,␍
"concurrency": 4,␍
"successful_requests": 6347,␍
"successful_requests": 3934,␍
"failed_requests": 0,␍
"error_ratio": 0.0,␍
"successful_rps": 210.145,␍
"successful_rps": 130.05,␍
"successful_latency_ms": {␍
"p50": 16.0,␍
"p95": 47.0,␍
"p99": 78.0␍
"p95": 78.0,␍
"p99": 141.0␍
},␍
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."␍
}
service cpu % max RAM max / limit, MiB
api 103.4 139.6 / 512
api 98.2 93.8 / 512
lb 25.5 15.8 / 128
postgres 31.5 49.0 / 512
valkey 6.7 8.2 / 128
api 97.5 83.3 / 512
api 90.2 122.3 / 512
lb 24.2 19.6 / 128
postgres 31.1 51.5 / 512
valkey 9.6 8.3 / 128
PASS: load profile saved to evidence/load.json and evidence/load-stats.json
+10 -10
View File
@@ -4,32 +4,32 @@
"containers": [
{
"service": "api",
"cpu_percent_max": 103.4,
"mem_mib_max": 139.6,
"cpu_percent_max": 97.47,
"mem_mib_max": 83.3,
"mem_limit_mib": 512
},
{
"service": "api",
"cpu_percent_max": 98.18,
"mem_mib_max": 93.8,
"cpu_percent_max": 90.24,
"mem_mib_max": 122.3,
"mem_limit_mib": 512
},
{
"service": "lb",
"cpu_percent_max": 25.48,
"mem_mib_max": 15.8,
"cpu_percent_max": 24.22,
"mem_mib_max": 19.6,
"mem_limit_mib": 128
},
{
"service": "postgres",
"cpu_percent_max": 31.52,
"mem_mib_max": 49.0,
"cpu_percent_max": 31.15,
"mem_mib_max": 51.5,
"mem_limit_mib": 512
},
{
"service": "valkey",
"cpu_percent_max": 6.71,
"mem_mib_max": 8.2,
"cpu_percent_max": 9.56,
"mem_mib_max": 8.3,
"mem_limit_mib": 128
}
]
+5 -5
View File
@@ -2,16 +2,16 @@
"lab": 3,
"workload": "closed-loop POST messages; no automatic retries",
"requested_duration_seconds": 30.0,
"elapsed_seconds": 30.203,
"elapsed_seconds": 30.25,
"concurrency": 4,
"successful_requests": 6347,
"successful_requests": 3934,
"failed_requests": 0,
"error_ratio": 0.0,
"successful_rps": 210.145,
"successful_rps": 130.05,
"successful_latency_ms": {
"p50": 16.0,
"p95": 47.0,
"p99": 78.0
"p95": 78.0,
"p99": 141.0
},
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
}
+18 -18
View File
@@ -2,25 +2,25 @@ python student-tests/run_persistence.py
hook: scripts/restart.cmd
=== containers before
SERVICE CONTAINER STATE STARTED AT (UTC)
api 4e5560c6d072 running (healthy) 2026-10-14T21:07:35.489
api 7740e49a1d8c running (healthy) 2026-10-14T21:07:12.761
lb 91c0051bd4c8 running (healthy) 2026-10-14T20:46:51.195
migrate 523965b912bb exited 2026-10-14T20:46:48.669
postgres 5c16b9b684f2 running (healthy) 2026-10-14T21:05:32.785
valkey c74935587700 running (healthy) 2026-10-14T21:05:11.672
api 1c773748bc05 running (healthy) 2026-10-15T16:36:31.798
api aa3dac85e7ed running (healthy) 2026-10-15T16:36:08.417
lb f9c8bda9ea4c running (healthy) 2026-10-15T16:32:39.190
migrate 7420f3f1ddda exited 2026-10-15T16:32:47.434
postgres 5c16b9b684f2 running (healthy) 2026-10-15T16:35:06.670
valkey c74935587700 running (healthy) 2026-10-15T16:34:57.760
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.␍
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
=== containers after (test took 18.5 s: hook + waiting for readiness + data checks)
=== containers after (test took 19.6 s: hook + waiting for readiness + data checks)
SERVICE CONTAINER STATE STARTED AT (UTC)
api 4e5560c6d072 running (healthy) 2026-10-14T21:07:56.102
api 7740e49a1d8c running (healthy) 2026-10-14T21:07:56.434
lb 91c0051bd4c8 running (healthy) 2026-10-14T21:08:00.229
migrate 523965b912bb exited 2026-10-14T21:07:54.122
postgres 5c16b9b684f2 running (healthy) 2026-10-14T21:07:48.620
valkey c74935587700 running (healthy) 2026-10-14T21:07:48.474
api 7740e49a1d8c: same container, start time 21:07:12 -> 21:07:56
api 4e5560c6d072: same container, start time 21:07:35 -> 21:07:56
lb 91c0051bd4c8: same container, start time 20:46:51 -> 21:08:00
postgres 5c16b9b684f2: same container, start time 21:05:32 -> 21:07:48
valkey c74935587700: same container, start time 21:05:11 -> 21:07:48
api 1c773748bc05 running (healthy) 2026-10-15T16:36:52.431
api aa3dac85e7ed running (healthy) 2026-10-15T16:36:52.088
lb f9c8bda9ea4c running (healthy) 2026-10-15T16:36:56.814
migrate 7420f3f1ddda exited 2026-10-15T16:36:50.153
postgres 5c16b9b684f2 running (healthy) 2026-10-15T16:36:44.391
valkey c74935587700 running (healthy) 2026-10-15T16:36:44.221
api aa3dac85e7ed: same container, start time 16:36:08 -> 16:36:52
api 1c773748bc05: same container, start time 16:36:31 -> 16:36:52
lb f9c8bda9ea4c: same container, start time 16:32:39 -> 16:36:56
postgres 5c16b9b684f2: same container, start time 16:35:06 -> 16:36:44
valkey c74935587700: same container, start time 16:34:57 -> 16:36:44
PASS: api replicas, postgres, valkey and lb were restarted (same containers and volumes, new start time); data and the existing token survived
+1 -1
View File
@@ -1,5 +1,5 @@
python student-tests/race.py
messages: sent 100 from 10 parallel clients in 0.88s
messages: sent 100 from 10 parallel clients in 1.55s
messages: read 100 in 4 pages, unique ids: 100
PASS: 100 concurrent messages stored without loss or duplicates
registration: 20 parallel requests for one username -> 201 x1, 409 x19
+22 -22
View File
@@ -1,6 +1,6 @@
{
"from_version": "dev",
"to_version": "rolling-20261015-000949",
"to_version": "rolling-20261015-193851",
"replicas": 2,
"profile": {
"writers": 4,
@@ -9,42 +9,42 @@
},
"steps": [
{
"old": "4e5560c6d072",
"new": "b021c4a75186",
"new_ready_seconds": 6.75,
"step_seconds": 11.38
"old": "1c773748bc05",
"new": "e8baa1b553a1",
"new_ready_seconds": 6.64,
"step_seconds": 11.8
},
{
"old": "7740e49a1d8c",
"new": "a1fe17dd4bd2",
"new_ready_seconds": 6.11,
"step_seconds": 11.2
"old": "aa3dac85e7ed",
"new": "db0d1f669f44",
"new_ready_seconds": 5.89,
"step_seconds": 10.55
}
],
"update_seconds": 22.59,
"update_seconds": 22.38,
"before": {
"seconds": 3.0,
"write_rps": 162.3,
"reads": 34,
"write_rps": 104.3,
"reads": 33,
"errors": 0,
"error_codes": {},
"write_p50_ms": 16.0,
"write_p95_ms": 78.0,
"write_max_ms": 203.0
"write_p50_ms": 31.0,
"write_p95_ms": 94.0,
"write_max_ms": 157.0
},
"during": {
"seconds": 22.59,
"write_rps": 144.2,
"reads": 266,
"seconds": 22.38,
"write_rps": 138.7,
"reads": 277,
"errors": 0,
"error_codes": {},
"write_p50_ms": 16.0,
"write_p95_ms": 78.0,
"write_max_ms": 250.0
"write_p95_ms": 63.0,
"write_max_ms": 312.0
},
"integrity": {
"confirmed_writes": 4260,
"messages_in_history": 4260,
"confirmed_writes": 3867,
"messages_in_history": 3867,
"duplicates": 0,
"lost": 0
}
+7 -7
View File
@@ -1,10 +1,10 @@
python student-tests/rolling_update.py
old replicas ['4e5560c6d072', '7740e49a1d8c'], version dev; building version rolling-20261015-000949
image built in 3.0 s
old replicas ['1c773748bc05', 'aa3dac85e7ed'], version dev; building version rolling-20261015-193851
image built in 3.8 s
migrations (one run, before replacing replicas): Миграции: новых нет, схема актуальна
replaced 4e5560c6d072 -> b021c4a75186: new replica healthy and UP in HAProxy after 6.8 s, then the old one drained and stopped; step 11.38 s (HAProxy: api1 UP, api2 DOWN, api3 UP)
replaced 7740e49a1d8c -> a1fe17dd4bd2: new replica healthy and UP in HAProxy after 6.1 s, then the old one drained and stopped; step 11.2 s (HAProxy: api1 DOWN, api2 UP, api3 UP)
now: replicas ['a1fe17dd4bd2', 'b021c4a75186'], versions ['rolling-20261015-000949']
under load: write RPS before 162.3, during the update 144.2; errors 0 {}; p95 78.0 ms, max 250.0 ms; update took 22.6 s
confirmed 4260, in history 4260, lost 0, duplicates 0
replaced 1c773748bc05 -> e8baa1b553a1: new replica healthy and UP in HAProxy after 6.6 s, then the old one drained and stopped; step 11.8 s (HAProxy: api1 DOWN, api2 UP, api3 UP)
replaced aa3dac85e7ed -> db0d1f669f44: new replica healthy and UP in HAProxy after 5.9 s, then the old one drained and stopped; step 10.55 s (HAProxy: api1 UP, api2 DOWN, api3 UP)
now: replicas ['db0d1f669f44', 'e8baa1b553a1'], versions ['rolling-20261015-193851']
under load: write RPS before 104.3, during the update 138.7; errors 0 {}; p95 63.0 ms, max 312.0 ms; update took 22.4 s
confirmed 3867, in history 3867, lost 0, duplicates 0
PASS: all 2 replicas replaced one by one under load, 0 errors, no lost or duplicated messages; saved evidence/rolling-update.json
+18 -16
View File
@@ -2,33 +2,35 @@ python student-tests/check_stack.py
docker: 29.6.2
compose: 5.3.1
container_name: not set for any service (replicas of one service are possible)
api replicas running: 2 -> ['4e5560c6d072', '7740e49a1d8c'] (deploy.replicas = 2)
api replicas running: 2 -> ['1c773748bc05', 'aa3dac85e7ed'] (deploy.replicas = 2)
service container cpus memory published ports networks
api 4e5560c6d072 1.00 512Mi - backend, edge
api 1c773748bc05 1.00 512Mi - backend, edge
postgres 5c16b9b684f2 1.00 512Mi - backend
api 7740e49a1d8c 1.00 512Mi - backend, edge
lb 91c0051bd4c8 0.50 128Mi 127.0.0.1:8080->8080/tcp, 127.0.0.1:8081->8081/tcp, 127.0.0.1:8404->8404/tcp edge
api aa3dac85e7ed 1.00 512Mi - backend, edge
valkey c74935587700 0.50 128Mi - backend
lb f9c8bda9ea4c 0.50 128Mi 127.0.0.1:8080->8080/tcp, 127.0.0.1:8081->8081/tcp, 127.0.0.1:8404->8404/tcp edge
published: only lb, only on 127.0.0.1 (api replicas have no ports)
balancer: every api server is under the /health/ready check, no backup servers -> api1 UP (L7OK), api2 UP (L7OK)
limits: every running container has CPU and RAM limits
networks: lb -> edge; api -> edge + backend; postgres, valkey -> backend (internal: no way out)
secrets: api -> cache_url, database_url; migrate -> database_url; lb -> none; postgres -> postgres_password; valkey -> valkey_acl
images: lb haproxy:3.2.25-alpine; api mtusi-messenger:lab3; postgres postgres:17.10-bookworm; valkey valkey/valkey:8.1.9
PASS: one entry point (lb on 127.0.0.1), >= 2 api replicas without ports and container_name, CPU/RAM limits everywhere, stores only on the internal network
PASS: one entry point (lb on 127.0.0.1), >= 2 api replicas without ports and container_name, only ready replicas get traffic, CPU/RAM limits everywhere, stores only on the internal network
docker compose ps -a --format "table {{.Service}}\t{{.ID}}\t{{.Status}}"
SERVICE CONTAINER ID STATUS
api 4e5560c6d072 Up 17 minutes (healthy)
api 7740e49a1d8c Up 17 minutes (healthy)
lb 91c0051bd4c8 Up 17 minutes (healthy)
migrate 523965b912bb Exited (0) 17 minutes ago
postgres 5c16b9b684f2 Up 17 minutes (healthy)
valkey c74935587700 Up 17 minutes (healthy)
migrate-1 | 2026-10-14 20:46:49,990 INFO messenger.db: Миграции применены: 001_core, 002_sessions, 003_text_as_bytes, 004_message_idempotency
api-2 | 2026-10-14 20:46:52,427 INFO messenger.db: Схема БД актуальна (миграции применены сервисом migrate)
api-2 | 2026-10-14 20:46:52,430 INFO messenger: Реплика 7740e49a1d8c запущена: версия dev, env=lab, TTL сессии=3600 c, кэш сессий: Valkey
api-1 | 2026-10-14 20:46:52,226 INFO messenger.db: Схема БД актуальна (миграции применены сервисом migrate)
api-1 | 2026-10-14 20:46:52,229 INFO messenger: Реплика 4e5560c6d072 запущена: версия dev, env=lab, TTL сессии=3600 c, кэш сессий: Valkey
api aa3dac85e7ed Up About a minute (healthy)
api 1c773748bc05 Up About a minute (healthy)
lb f9c8bda9ea4c Up About a minute (healthy)
migrate 7420f3f1ddda Exited (0) About a minute ago
postgres 5c16b9b684f2 Up 30 seconds (healthy)
valkey c74935587700 Up 8 minutes (healthy)
api-3 | 2026-10-15 16:32:41,372 INFO messenger.db: Схема БД актуальна (миграции применены сервисом migrate)
api-3 | 2026-10-15 16:32:41,376 INFO messenger: Реплика aa3dac85e7ed запущена: версия dev, env=lab, TTL сессии=3600 c, кэш сессий: Valkey
migrate-1 | 2026-10-15 16:32:37,955 INFO messenger.db: Миграции: новых нет, схема актуальна
migrate-1 | 2026-10-15 16:32:49,046 INFO messenger.db: Миграции: новых нет, схема актуальна
api-4 | 2026-10-15 16:32:41,595 INFO messenger.db: Схема БД актуальна (миграции применены сервисом migrate)
api-4 | 2026-10-15 16:32:41,600 INFO messenger: Реплика 1c773748bc05 запущена: версия dev, env=lab, TTL сессии=3600 c, кэш сессий: Valkey
.gitignore:2:.env .env
.gitignore:5:secrets/ secrets/database_url
+7 -7
View File
@@ -37,19 +37,19 @@ test_replay_through_another_replica_returns_same_message (test_idempotency.Idemp
test_same_key_other_body_is_409 (test_idempotency.IdempotencyTest.test_same_key_other_body_is_409) ... ok
----------------------------------------------------------------------
Ran 36 tests in 6.481s
Ran 36 tests in 11.028s
OK
X-Instance-Id есть в health, 404, 401 и 400
logout через одну реплику -> 401 на ['4e5560c6d072', '7740e49a1d8c']
logout через одну реплику -> 401 на ['1c773748bc05', 'aa3dac85e7ed']
20 x GET /users/me с одним токеном -> реплики {'7740e49a1d8c': 10, '4e5560c6d072': 10}; это ID запущенных контейнеров api, повторный вход не нужен
20 x GET /users/me с одним токеном -> реплики {'aa3dac85e7ed': 10, '1c773748bc05': 10}; это ID запущенных контейнеров api, повторный вход не нужен
10 x GET /users/me через реплики {'7740e49a1d8c': 5, '4e5560c6d072': 5}: попаданий в кэш +20, промахов +0 — кэш общий
10 x GET /users/me через реплики {'aa3dac85e7ed': 5, '1c773748bc05': 5}: попаданий в кэш +20, промахов +0 — кэш общий
сообщение записала реплика 7740e49a1d8c, сразу прочитали ['4e5560c6d072', '7740e49a1d8c']
сообщение записала реплика aa3dac85e7ed, сразу прочитали ['1c773748bc05', 'aa3dac85e7ed']
с тем же ключом: сначала 400 (пустой текст), потом 201 — ошибка ключ не заняла
@@ -61,10 +61,10 @@ OK
10 одновременных разных тел с одним ключом: 201 x1, 409 x9, в истории 1 сообщение
20 одновременных POST с одним ключом через реплики {'7740e49a1d8c': 10, '4e5560c6d072': 10}: все 201 с одним id, в истории 1 сообщение
20 одновременных POST с одним ключом через реплики {'1c773748bc05': 10, 'aa3dac85e7ed': 10}: все 201 с одним id, в истории 1 сообщение
повтор: посторонний -> 404, после logout -> 401, после нового входа -> то же сообщение
1 запрос + 4 повтора через реплики ['4e5560c6d072', '7740e49a1d8c']: 201 и то же сообщение, в истории 1
1 запрос + 4 повтора через реплики ['1c773748bc05', 'aa3dac85e7ed']: 201 и то же сообщение, в истории 1
другой текст с тем же ключом -> 409 conflict, второе сообщение не создано
+2 -2
View File
@@ -1,8 +1,8 @@
docker compose exec -T valkey valkey-cli --user health --pass none --no-auth-warning dbsize
6
docker compose exec -T valkey valkey-cli --user health --pass none --no-auth-warning info stats | grep -E "keyspace_(hits|misses)"
keyspace_hits:106
keyspace_misses:4
keyspace_hits:105
keyspace_misses:1
docker compose exec -T valkey valkey-cli --user health --pass none --no-auth-warning get sess:anything
NOPERM User health has no permissions to run the 'get' command
+10 -6
View File
@@ -41,6 +41,13 @@ defaults
# POST сообщения повторяет клиент с тем же Idempotency-Key.
retries 2
option redispatch 1
# Ошибки, которые создаёт сам балансировщик (нет ни одной готовой реплики — 503, реплика оборвала
# соединение — 502, не ответила вовремя — 504), отдаются в формате ошибки из контракта
# с X-Request-Id. X-Instance-Id у них нет: ни одна реплика API этот ответ не создавала.
unique-id-format %[uuid]
http-error status 503 content-type application/json lf-string '{"error":{"code":"unavailable","message":"Нет готовой реплики API, повторите запрос позже","request_id":"%[unique-id]"}}' hdr X-Request-Id "%[unique-id]"
http-error status 502 content-type application/json lf-string '{"error":{"code":"unavailable","message":"Реплика API оборвала соединение, повторите запрос","request_id":"%[unique-id]"}}' hdr X-Request-Id "%[unique-id]"
http-error status 504 content-type application/json lf-string '{"error":{"code":"unavailable","message":"Реплика API не ответила вовремя, повторите запрос","request_id":"%[unique-id]"}}' hdr X-Request-Id "%[unique-id]"
frontend api_in
bind :8080
@@ -55,13 +62,10 @@ backend api
# До 6 реплик (обычно 2, во время rolling update 3); пустые слоты стоят в MAINT.
# Проверка раз в 1 с, при смене состояния раз в 0,5 с; 2 неудачи подряд -> DOWN, 2 удачи -> UP.
# observe layer4: первая же ошибка соединения у живого запроса сразу выводит реплику из балансировки.
# Запросы получают ТОЛЬКО реплики, прошедшие проверку готовности. Резервных слотов без проверки нет:
# если не готова ни одна реплика (например, недоступна PostgreSQL), балансировщик сам отвечает 503
# и никуда запрос не передаёт, даже если реплика могла бы ответить из кэша.
server-template api 6 api:8080 check inter 1s fastinter 500ms downinter 2s fall 2 rise 2 observe layer4 error-limit 1 on-error mark-down resolvers docker resolve-prefer ipv4 init-addr none
# Аварийный режим: если НИ ОДНА реплика не готова (например, недоступна PostgreSQL), запросы всё
# равно идут в API. Клиент получает ответ самого API (503 в формате контракта, с X-Request-Id
# и X-Instance-Id), а /health/live отвечает 200. Пока готова хоть одна реплика, слоты не используются.
# allow-dup-ip: те же адреса, что у основных слотов (по умолчанию HAProxy запрещает повтор адреса).
server-template fallback 6 api:8080 backup resolvers docker resolve-prefer ipv4 resolve-opts allow-dup-ip init-addr none
option allbackups
# Второй вход только для проверки истечения сессии (make expiry): API с SESSION_TTL_SECONDS=2
# (сервис api-short-ttl, профиль ttl). Он тоже доступен только через балансировщик.
+14 -2
View File
@@ -3,6 +3,8 @@
make check-stack (= python student-tests/check_stack.py)
- не меньше 2 работающих реплик api, у них нет опубликованных портов (обойти балансировщик нельзя);
- в балансировщике каждая реплика под проверкой готовности, резервных серверов без проверки нет
(неготовая реплика не получает запросы ни при каких условиях);
- ни у одного сервиса нет container_name (иначе нельзя запустить несколько реплик одного сервиса);
- наружу опубликован только балансировщик и только на 127.0.0.1;
- у каждого работающего контейнера есть лимиты CPU и RAM;
@@ -13,7 +15,7 @@
import json
from helpers import check, run
from stand import api_containers, compose_config, compose_output, docker, inspect
from stand import api_containers, compose_config, compose_output, docker, inspect, lb_rows
def main():
@@ -55,6 +57,16 @@ def main():
check(published.get("lb") and all(b.startswith("127.0.0.1:") for b in published["lb"]),
"the balancer must be published on 127.0.0.1 only")
print("published: only lb, only on 127.0.0.1 (api replicas have no ports)")
servers = lb_rows("api")
backups = [row["svname"] for row in servers if row.get("bck") == "1"]
unchecked = [row["svname"] for row in servers
if not row.get("status", "").startswith("MAINT") and not row.get("check_status")]
check(not backups, f"backup servers in the balancer: {backups}")
check(not unchecked, f"servers without a readiness check in the balancer: {unchecked}")
in_use = [f"{row['svname']} {row['status']} ({row['check_status']})" for row in servers
if not row.get("status", "").startswith("MAINT")]
print(f"balancer: every api server is under the /health/ready check, no backup servers -> {', '.join(in_use)}")
print("limits: every running container has CPU and RAM limits")
def nets_of(name):
@@ -76,7 +88,7 @@ def main():
print("secrets: " + "; ".join(f"{name} -> {', '.join(wanted) or 'none'}" for name, wanted in expected.items()))
print("images: " + "; ".join(f"{name} {services[name]['image']}" for name in ("lb", "api", "postgres", "valkey")))
print("PASS: one entry point (lb on 127.0.0.1), >= 2 api replicas without ports and container_name, "
"CPU/RAM limits everywhere, stores only on the internal network")
"only ready replicas get traffic, CPU/RAM limits everywhere, stores only on the internal network")
if __name__ == "__main__":
+61 -25
View File
@@ -4,15 +4,22 @@
и запускает контейнер обратно (docker compose start). Volumes не трогаются.
valkey — кэш недоступен: API обходит его и работает через PostgreSQL; logout действует сразу.
postgres — источник истины недоступен: API отвечает ограниченной ошибкой 503 (без деталей),
/health/ready = 503, аноним и неизвестный токен НЕ получают успешный ответ.
После запуска БД прежний токен и данные снова доступны.
postgres — источник истины недоступен: обе реплики не готовы (/health/ready = 503), и балансировщик
исключает их из маршрутизации. Даже запрос с действующим токеном, который реплика могла бы
подтвердить из кэша Valkey, через балансировщик получает 503 и до реплики не доходит
(замечание к MR: раньше резервные слоты без проверки пропускали его, и он получал 200).
Сами реплики при этом живы (/health/live = 200 изнутри контейнера).
Запись во время отказа не сохраняется. После запуска БД прежний токен и данные доступны.
"""
import sys
import time
import uuid
from helpers import Client, basic, check, compose, idempotency, read_history, run, wait_ready
from helpers import Client, check, compose, idempotency, read_history, run, wait_ready
from stand import api_containers, lb_summary, lb_up_count, replica_status, try_call
LB_EXCLUDE_TIMEOUT_SECONDS = 15
LOST_TEXT = "во время отказа PostgreSQL, не должно сохраниться " + uuid.uuid4().hex
def timed(fn):
@@ -46,27 +53,49 @@ def valkey_down(api, alice, bob, chat):
return carol
def refused_by_lb(method, path, token=None, body=None, headers=None):
"""Запрос через балансировщик: ждём 503 от САМОГО балансировщика в формате ошибки контракта.
Признак того, что запрос не дошёл до реплики API: в ответе нет X-Instance-Id
(его ставит каждая реплика), а X-Request-Id и request_id в теле — от балансировщика.
"""
reply = try_call(method, path, token=token, body=body, headers=headers, timeout=5)
check(reply is not None, f"{method} {path}: no response from the balancer")
check(reply.status == 503, f"{method} {path}: expected 503 from the balancer, got {reply.status}")
check(not reply.instance, f"{method} {path}: answered by a NOT READY API replica {reply.instance}")
error = (reply.json or {}).get("error") or {}
check(error.get("code") == "unavailable", f"{method} {path}: wrong error format {reply.json}")
check(error.get("request_id") and error["request_id"] == reply.headers.get("x-request-id"),
f"{method} {path}: request_id differs from X-Request-Id")
def postgres_down(api, alice, chat):
api.call("GET", "/health/live", schema="Health")
print("/health/live -> 200: процесс жив")
_, ms = timed(lambda: api.call("GET", "/health/ready", 503))
print(f"/health/ready -> 503 ({ms:.0f} ms): без PostgreSQL обслуживать нельзя")
for method, path in (("GET", "/api/v1/chats"), ("GET", f"/api/v1/chats/{chat['id']}/messages")):
error = api.call(method, path, 503, actor=alice)["json"]["error"]
check(error["code"] == "unavailable", "expected unavailable error code")
api.call("POST", f"/api/v1/chats/{chat['id']}/messages", 503, actor=alice, body={"text": "не сохранится"},
headers=idempotency())
print("бизнес-запросы с действующим токеном -> 503 unavailable (без SQL и stack trace в ответе)")
api.call("GET", "/api/v1/users/me", 401)
print("без токена -> 401: аноним не становится доверенным")
status = api.call("GET", "/api/v1/users/me", [401, 503], headers={"Authorization": "Bearer " + "x" * 43})["status"]
print(f"неизвестный токен -> {status}: не подтверждается ни кэшем, ни базой")
status = api.call("POST", "/api/v1/auth/sessions", [401, 503],
headers={"Authorization": basic("nobody", "Some-password-1")})["status"]
print(f"вход -> {status}: сессию без базы не выдаём")
api.call("POST", "/api/v1/users", 503,
body={"username": "pg_" + uuid.uuid4().hex[:10], "display_name": "x", "password": "Pg-down-password"})
print("регистрация -> 503")
started = time.monotonic()
while lb_up_count() > 0:
check(time.monotonic() - started < LB_EXCLUDE_TIMEOUT_SECONDS,
f"HAProxy still routes to a replica {LB_EXCLUDE_TIMEOUT_SECONDS} s after the failure")
time.sleep(0.2)
print(f"HAProxy вывел все реплики из балансировки через {time.monotonic() - started:.1f} с "
f"после остановки PostgreSQL ({lb_summary()})")
for container in api_containers():
live, ready = replica_status(container, "/health/live"), replica_status(container, "/health/ready")
check(live == 200 and ready == 503, f"replica {container[:12]}: live {live}, ready {ready}")
print(f"реплика {container[:12]} изнутри контейнера: /health/live -> {live}, /health/ready -> {ready} "
f"(жива, но не готова)")
# Главное (замечание к MR): токен alice лежит в кэше Valkey, и реплика могла бы ответить 200 без базы.
refused_by_lb("GET", "/api/v1/users/me", token=alice["token"])
print("GET /users/me с действующим токеном (он есть в кэше) -> 503 от балансировщика, без X-Instance-Id: "
"до неготовой реплики запрос не дошёл")
refused_by_lb("GET", "/api/v1/chats", token=alice["token"])
refused_by_lb("GET", f"/api/v1/chats/{chat['id']}/messages", token=alice["token"])
refused_by_lb("POST", f"/api/v1/chats/{chat['id']}/messages", token=alice["token"],
body={"text": LOST_TEXT}, headers=idempotency())
print("бизнес-запросы (список чатов, история, отправка сообщения) -> 503 от балансировщика")
refused_by_lb("GET", "/api/v1/users/me")
refused_by_lb("POST", "/api/v1/users", body={"username": "pg_" + uuid.uuid4().hex[:10],
"display_name": "x", "password": "Pg-down-password"})
refused_by_lb("GET", "/health/ready")
print("без токена, регистрация и /health/ready через балансировщик -> 503: успешного ответа нет ни у кого")
def main():
@@ -75,6 +104,8 @@ def main():
api = Client()
alice, bob, _eve, chat = api.bootstrap()
before = api.message(alice, chat, "до отказа " + target)["json"]
for _ in range(4): # запись о сессии alice точно лежит в общем кэше Valkey
api.call("GET", "/api/v1/users/me", actor=alice, schema="User")
print(f"stopping {target} (docker compose stop {target})")
compose("stop", target)
@@ -90,11 +121,16 @@ def main():
wait_ready(api)
history, _ = read_history(api, alice, chat["id"])
check(before in history, "message confirmed before the outage is lost or changed")
check(all(m["text"] != LOST_TEXT for m in history), "a write refused during the outage was stored")
api.call("GET", "/api/v1/users/me", actor=alice, schema="User")
if target == "valkey":
api.call("GET", "/api/v1/users/me", 401, actor=carol) # отозванный токен не «воскрес» из кэша
print("after recovery: прежний токен работает, подтверждённые сообщения на месте")
print(f"PASS: {target} outage handled without trusting anonymous requests")
if target == "postgres":
print("PASS: postgres outage: not ready replicas were excluded by the balancer, no request reached them, "
"nothing was stored; data and the existing token survived")
else:
print("PASS: valkey outage handled without the cache; revoked tokens stay revoked")
if __name__ == "__main__":
+4 -1
View File
@@ -13,12 +13,15 @@ import os
import time
import uuid
from helpers import Client, check, login, run
from helpers import Client, check, login, run, wait_ready
def main():
short = Client(os.environ.get("BASE_URL_TTL", "http://127.0.0.1:8081"))
main_api = Client()
# Контейнер уже healthy, но балансировщику нужно ещё пару секунд: найти его по DNS
# и пройти 2 проверки готовности. Ждём готовности именно через балансировщик (:8081).
wait_ready(short, seconds=60)
body = {"username": "ttl_" + uuid.uuid4().hex[:12], "display_name": "TTL", "password": "Ttl-password-123"}
short.call("POST", "/api/v1/users", 201, body=body, schema="User")
session = login(short, body["username"], body["password"])
+4 -2
View File
@@ -106,8 +106,10 @@ def impacts(failover, rolling):
("failure-valkey.txt", "`docker compose stop valkey`", "API работает без кэша",
"ready 200; вход, сообщения и logout работают через PostgreSQL",
"кэш снова включается за 1–2 с после start; потерь нет"),
("failure-postgres.txt", "`docker compose stop postgres`", "503 без подробностей, аноним не доверенный",
"через балансировщик (слоты fallback): ready 503, бизнес-запросы 503, без токена 401",
("failure-postgres.txt", "`docker compose stop postgres`",
"неготовые реплики исключены из маршрутизации, клиенту 503",
"HAProxy вывел обе реплики (ready 503, live 200); запрос с действующим токеном из кэша -> 503 "
"от балансировщика, до реплики не дошёл; запись не сохранилась",
"после start прежний токен и данные на месте; запросы во время отказа не сохранены (503)"),
("failure-valkey-pause.txt", "`docker compose pause valkey`, logout, `unpause`",
"отозванный токен не оживает ни на одной реплике", "после unpause отозванный токен всегда 401",
+30 -9
View File
@@ -121,21 +121,23 @@ def ps_table():
# ---------- балансировщик ----------
def lb_servers(backend="api"):
"""Слоты backend в HAProxy (страница статистики, CSV): {имя: статус}, например {'api1': 'UP'}."""
def lb_rows(backend="api"):
"""Строки статистики HAProxy (CSV) по серверам backend: имя, статус, backup-флаг, результат проверки."""
with urllib.request.urlopen(LB_STATS_URL, timeout=2) as reply:
rows = list(csv.reader(io.StringIO(reply.read().decode("utf-8", "replace"))))
header = [name.lstrip("# ") for name in rows[0]]
servers = {}
for row in rows[1:]:
item = dict(zip(header, row))
if item.get("pxname") == backend and item.get("svname") not in ("FRONTEND", "BACKEND"):
servers[item["svname"]] = item.get("status", "")
return servers
items = [dict(zip(header, row)) for row in rows[1:]]
return [item for item in items
if item.get("pxname") == backend and item.get("svname") not in ("FRONTEND", "BACKEND")]
def lb_servers(backend="api"):
"""Слоты backend в HAProxy: {имя: статус}, например {'api1': 'UP'}."""
return {item["svname"]: item.get("status", "") for item in lb_rows(backend)}
def lb_up_count():
"""Сколько основных слотов (api1..api6, без аварийных fallback) HAProxy держит в балансировке (UP)."""
"""Сколько реплик (слоты api1..api6) HAProxy держит в балансировке (UP)."""
return sum(1 for name, status in lb_servers().items() if name.startswith("api") and status.startswith("UP"))
@@ -164,9 +166,28 @@ def wait_balanced(replicas, seconds=90):
time.sleep(0.5)
def replica_status(container, path):
"""Код ответа реплики на GET path изнутри её контейнера, в обход балансировщика.
Так видно состояние самой реплики (жива ли, готова ли), когда балансировщик её уже исключил.
Одна строка без переводов строк: так команда одинаково передаётся и на Windows, и на Linux.
"""
code = ("import http.client as h; c = h.HTTPConnection('127.0.0.1', 8080, timeout=5); "
f"c.request('GET', '{path}'); print(c.getresponse().status)")
return int(docker("exec", container, "python", "-c", code))
def valkey_stats():
"""keyspace_hits и keyspace_misses Valkey (пользователь health без пароля: только info/ping/dbsize)."""
output = compose_output("exec", "-T", "valkey", "valkey-cli", "--user", "health", "--pass", "none",
"--no-auth-warning", "info", "stats")
stats = dict(line.strip().split(":", 1) for line in output.splitlines() if line.startswith("keyspace_"))
return int(stats["keyspace_hits"]), int(stats["keyspace_misses"])
if __name__ == "__main__":
# make restore: после `docker compose up -d --wait` дождаться, пока HAProxy вернёт в работу
# ВСЕ запущенные реплики (DNS + 2 удачные проверки готовности — ещё несколько секунд).
replicas = len(api_containers())
wait_balanced(replicas)
print(f"all {replicas} api replicas are healthy and UP in HAProxy: {lb_summary()}")